More deprecated class mods
[wxWidgets.git] / src / x11 / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose: wxApp
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 17/09/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "app.h"
14 #endif
15
16 #include "wx/frame.h"
17 #include "wx/app.h"
18 #include "wx/utils.h"
19 #include "wx/gdicmn.h"
20 #include "wx/icon.h"
21 #include "wx/dialog.h"
22 #include "wx/log.h"
23 #include "wx/module.h"
24 #include "wx/memory.h"
25 #include "wx/log.h"
26 #include "wx/intl.h"
27 #include "wx/evtloop.h"
28 #include "wx/timer.h"
29 #include "wx/filename.h"
30 #include "wx/hash.h"
31
32 #include "wx/univ/theme.h"
33 #include "wx/univ/renderer.h"
34
35 #define ABS(a) (((a) < 0) ? -(a) : (a))
36
37 #if wxUSE_THREADS
38 #include "wx/thread.h"
39 #endif
40
41 #include "wx/x11/private.h"
42
43 #include <string.h>
44
45 //------------------------------------------------------------------------
46 // global data
47 //------------------------------------------------------------------------
48
49 extern wxList wxPendingDelete;
50
51 wxHashTable *wxWidgetHashTable = NULL;
52 wxHashTable *wxClientWidgetHashTable = NULL;
53
54 wxApp *wxTheApp = NULL;
55
56 // This is set within wxEntryStart -- too early on
57 // to put these in wxTheApp
58 static bool g_showIconic = FALSE;
59 static wxSize g_initialSize = wxDefaultSize;
60
61 // This is required for wxFocusEvent::SetWindow(). It will only
62 // work for focus events which we provoke ourselves (by calling
63 // SetFocus()). It will not work for those events, which X11
64 // generates itself.
65 static wxWindow *g_nextFocus = NULL;
66 static wxWindow *g_prevFocus = NULL;
67
68 //------------------------------------------------------------------------
69 // X11 error handling
70 //------------------------------------------------------------------------
71
72 #ifdef __WXDEBUG__
73 typedef int (*XErrorHandlerFunc)(Display *, XErrorEvent *);
74
75 XErrorHandlerFunc gs_pfnXErrorHandler = 0;
76
77 static int wxXErrorHandler(Display *dpy, XErrorEvent *xevent)
78 {
79 // just forward to the default handler for now
80 if (gs_pfnXErrorHandler)
81 return gs_pfnXErrorHandler(dpy, xevent);
82 else
83 return 0;
84 }
85 #endif // __WXDEBUG__
86
87 //------------------------------------------------------------------------
88 // wxApp
89 //------------------------------------------------------------------------
90
91 long wxApp::sm_lastMessageTime = 0;
92 WXDisplay *wxApp::ms_display = NULL;
93
94 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
95
96 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
97 EVT_IDLE(wxApp::OnIdle)
98 END_EVENT_TABLE()
99
100 bool wxApp::Initialize()
101 {
102 wxClassInfo::InitializeClasses();
103
104 #if wxUSE_INTL
105 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
106 #endif
107
108 // GL: I'm annoyed ... I don't know where to put this and I don't want to
109 // create a module for that as it's part of the core.
110 #if wxUSE_THREADS
111 wxPendingEventsLocker = new wxCriticalSection();
112 #endif
113
114 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
115 wxTheColourDatabase->Initialize();
116
117 wxInitializeStockLists();
118 wxInitializeStockObjects();
119
120 wxWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
121 wxClientWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
122
123 wxModule::RegisterModules();
124 if (!wxModule::InitializeModules()) return FALSE;
125
126 return TRUE;
127 }
128
129 void wxApp::CleanUp()
130 {
131 delete wxWidgetHashTable;
132 wxWidgetHashTable = NULL;
133 delete wxClientWidgetHashTable;
134 wxClientWidgetHashTable = NULL;
135
136 wxModule::CleanUpModules();
137
138 delete wxTheColourDatabase;
139 wxTheColourDatabase = NULL;
140
141 wxDeleteStockObjects();
142
143 wxDeleteStockLists();
144
145 delete wxTheApp;
146 wxTheApp = NULL;
147
148 wxClassInfo::CleanUpClasses();
149
150 #if wxUSE_THREADS
151 delete wxPendingEvents;
152 delete wxPendingEventsLocker;
153 #endif
154
155 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
156 // At this point we want to check if there are any memory
157 // blocks that aren't part of the wxDebugContext itself,
158 // as a special case. Then when dumping we need to ignore
159 // wxDebugContext, too.
160 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
161 {
162 wxLogDebug("There were memory leaks.");
163 wxDebugContext::Dump();
164 wxDebugContext::PrintStatistics();
165 }
166 #endif
167
168 // do it as the very last thing because everything else can log messages
169 wxLog::DontCreateOnDemand();
170 // do it as the very last thing because everything else can log messages
171 delete wxLog::SetActiveTarget(NULL);
172 }
173
174 // NB: argc and argv may be changed here, pass by reference!
175 int wxEntryStart( int& argc, char *argv[] )
176 {
177 #ifdef __WXDEBUG__
178 #if !wxUSE_NANOX
179 // install the X error handler
180 gs_pfnXErrorHandler = XSetErrorHandler( wxXErrorHandler );
181 #endif
182 #endif // __WXDEBUG__
183
184 char *displayName = NULL;
185 bool syncDisplay = FALSE;
186
187 int i;
188 for (i = 0; i < argc; i++)
189 {
190 if (strcmp( argv[i], "-display") == 0)
191 {
192 if (i < (argc - 1))
193 {
194 i ++;
195 displayName = argv[i];
196 continue;
197 }
198 }
199 else if (strcmp( argv[i], "-geometry") == 0)
200 {
201 if (i < (argc - 1))
202 {
203 i ++;
204 int w, h;
205 if (sscanf(argv[i], "%dx%d", &w, &h) != 2)
206 {
207 wxLogError( _("Invalid geometry specification '%s'"), wxString::FromAscii(argv[i]).c_str() );
208 }
209 else
210 {
211 g_initialSize = wxSize(w, h);
212 }
213 continue;
214 }
215 }
216 else if (strcmp( argv[i], "-sync") == 0)
217 {
218 syncDisplay = TRUE;
219 continue;
220 }
221 else if (strcmp( argv[i], "-iconic") == 0)
222 {
223 g_showIconic = TRUE;
224
225 continue;
226 }
227
228 }
229
230 // X11 display stuff
231 Display* xdisplay = XOpenDisplay( displayName );
232 if (!xdisplay)
233 {
234 wxLogError( _("wxWindows could not open display. Exiting.") );
235 return -1;
236 }
237
238 if (syncDisplay)
239 XSynchronize(xdisplay, True);
240
241 wxApp::ms_display = (WXDisplay*) xdisplay;
242
243 XSelectInput( xdisplay, XDefaultRootWindow(xdisplay), PropertyChangeMask);
244
245 // Misc.
246 wxSetDetectableAutoRepeat( TRUE );
247
248 #if wxUSE_UNICODE
249 // Glib's type system required by Pango
250 g_type_init();
251 #endif
252
253 if (!wxApp::Initialize())
254 return -1;
255
256 return 0;
257 }
258
259 int wxEntryInitGui()
260 {
261 int retValue = 0;
262
263 if ( !wxTheApp->OnInitGui() )
264 retValue = -1;
265
266 return retValue;
267 }
268
269
270 int wxEntry( int argc, char *argv[] )
271 {
272 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
273 // This seems to be necessary since there are 'rogue'
274 // objects present at this point (perhaps global objects?)
275 // Setting a checkpoint will ignore them as far as the
276 // memory checking facility is concerned.
277 // Of course you may argue that memory allocated in globals should be
278 // checked, but this is a reasonable compromise.
279 wxDebugContext::SetCheckpoint();
280 #endif
281 int err = wxEntryStart(argc, argv);
282 if (err)
283 return err;
284
285 if (!wxTheApp)
286 {
287 if (!wxApp::GetInitializerFunction())
288 {
289 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
290 return 0;
291 }
292
293 wxTheApp = (wxApp*) (* wxApp::GetInitializerFunction()) ();
294 }
295
296 if (!wxTheApp)
297 {
298 printf( "wxWindows error: wxTheApp == NULL\n" );
299 return 0;
300 }
301
302 // Command line argument stuff
303 wxTheApp->argc = argc;
304 #if wxUSE_UNICODE
305 wxTheApp->argv = new wxChar*[argc+1];
306 int mb_argc = 0;
307 while (mb_argc < argc)
308 {
309 wxString tmp = wxString::FromAscii( argv[mb_argc] );
310 wxTheApp->argv[mb_argc] = wxStrdup( tmp.c_str() );
311 mb_argc++;
312 }
313 wxTheApp->argv[mb_argc] = (wxChar *)NULL;
314 #else
315 wxTheApp->argv = argv;
316 #endif
317
318 if (wxTheApp->argc > 0)
319 {
320 wxFileName fname( wxTheApp->argv[0] );
321 wxTheApp->SetAppName( fname.GetName() );
322 }
323
324 wxTheApp->m_showIconic = g_showIconic;
325 wxTheApp->m_initialSize = g_initialSize;
326
327 int retValue;
328 retValue = wxEntryInitGui();
329
330 // Here frames insert themselves automatically into wxTopLevelWindows by
331 // getting created in OnInit().
332 if ( retValue == 0 )
333 {
334 if ( !wxTheApp->OnInit() )
335 retValue = -1;
336 }
337
338 if ( retValue == 0 )
339 {
340 if (wxTheApp->Initialized()) retValue = wxTheApp->OnRun();
341 }
342
343 // flush the logged messages if any
344 wxLog *pLog = wxLog::GetActiveTarget();
345 if ( pLog != NULL && pLog->HasPendingMessages() )
346 pLog->Flush();
347
348 delete wxLog::SetActiveTarget(new wxLogStderr); // So dialog boxes aren't used
349 // for further messages
350
351 if (wxTheApp->GetTopWindow())
352 {
353 delete wxTheApp->GetTopWindow();
354 wxTheApp->SetTopWindow(NULL);
355 }
356
357 wxTheApp->DeletePendingObjects();
358
359 wxTheApp->OnExit();
360
361 wxApp::CleanUp();
362
363 return retValue;
364 };
365
366 // Static member initialization
367 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
368
369 wxApp::wxApp()
370 {
371 // TODO: parse the command line
372 argc = 0;
373 argv = NULL;
374
375 m_mainColormap = (WXColormap) NULL;
376 m_topLevelWidget = (WXWindow) NULL;
377 m_maxRequestSize = 0;
378 m_mainLoop = NULL;
379 m_showIconic = FALSE;
380 m_initialSize = wxDefaultSize;
381
382 #if !wxUSE_NANOX
383 m_visualColormap = NULL;
384 m_colorCube = NULL;
385 #endif
386 }
387
388 wxApp::~wxApp()
389 {
390 #if !wxUSE_NANOX
391 if (m_colorCube)
392 free( m_colorCube );
393
394 if (m_visualColormap)
395 delete [] (XColor*)m_visualColormap;
396 #endif
397 }
398
399 bool wxApp::Initialized()
400 {
401 if (GetTopWindow())
402 return TRUE;
403 else
404 return FALSE;
405 }
406
407 int wxApp::MainLoop()
408 {
409 int rt;
410 m_mainLoop = new wxEventLoop;
411
412 rt = m_mainLoop->Run();
413
414 delete m_mainLoop;
415 m_mainLoop = NULL;
416 return rt;
417 }
418
419 #if !wxUSE_NANOX
420 //-----------------------------------------------------------------------
421 // X11 predicate function for exposure compression
422 //-----------------------------------------------------------------------
423
424 struct wxExposeInfo
425 {
426 Window window;
427 Bool found_non_matching;
428 };
429
430 static Bool expose_predicate (Display *display, XEvent *xevent, XPointer arg)
431 {
432 wxExposeInfo *info = (wxExposeInfo*) arg;
433
434 if (info->found_non_matching)
435 return FALSE;
436
437 if (xevent->xany.type != Expose)
438 {
439 info->found_non_matching = TRUE;
440 return FALSE;
441 }
442
443 if (xevent->xexpose.window != info->window)
444 {
445 info->found_non_matching = TRUE;
446 return FALSE;
447 }
448
449 return TRUE;
450 }
451 #endif
452 // wxUSE_NANOX
453
454 //-----------------------------------------------------------------------
455 // Processes an X event, returning TRUE if the event was processed.
456 //-----------------------------------------------------------------------
457
458 bool wxApp::ProcessXEvent(WXEvent* _event)
459 {
460 XEvent* event = (XEvent*) _event;
461
462 wxWindow* win = NULL;
463 Window window = XEventGetWindow(event);
464 #if 0
465 Window actualWindow = window;
466 #endif
467
468 // Find the first wxWindow that corresponds to this event window
469 // Because we're receiving events after a window
470 // has been destroyed, assume a 1:1 match between
471 // Window and wxWindow, so if it's not in the table,
472 // it must have been destroyed.
473
474 win = wxGetWindowFromTable(window);
475 if (!win)
476 {
477 #if wxUSE_TWO_WINDOWS
478 win = wxGetClientWindowFromTable(window);
479 if (!win)
480 #endif
481 return FALSE;
482 }
483
484 #ifdef __WXDEBUG__
485 wxString windowClass = win->GetClassInfo()->GetClassName();
486 #endif
487
488 switch (event->type)
489 {
490 case Expose:
491 {
492 #if wxUSE_TWO_WINDOWS && !wxUSE_NANOX
493 if (event->xexpose.window != (Window)win->GetClientAreaWindow())
494 {
495 XEvent tmp_event;
496 wxExposeInfo info;
497 info.window = event->xexpose.window;
498 info.found_non_matching = FALSE;
499 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event, expose_predicate, (XPointer) &info ))
500 {
501 // Don't worry about optimizing redrawing the border etc.
502 }
503 win->NeedUpdateNcAreaInIdle();
504 }
505 else
506 #endif
507 {
508 win->GetUpdateRegion().Union( XExposeEventGetX(event), XExposeEventGetY(event),
509 XExposeEventGetWidth(event), XExposeEventGetHeight(event));
510 win->GetClearRegion().Union( XExposeEventGetX(event), XExposeEventGetY(event),
511 XExposeEventGetWidth(event), XExposeEventGetHeight(event));
512
513 #if !wxUSE_NANOX
514 XEvent tmp_event;
515 wxExposeInfo info;
516 info.window = event->xexpose.window;
517 info.found_non_matching = FALSE;
518 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event, expose_predicate, (XPointer) &info ))
519 {
520 win->GetUpdateRegion().Union( tmp_event.xexpose.x, tmp_event.xexpose.y,
521 tmp_event.xexpose.width, tmp_event.xexpose.height );
522
523 win->GetClearRegion().Union( tmp_event.xexpose.x, tmp_event.xexpose.y,
524 tmp_event.xexpose.width, tmp_event.xexpose.height );
525 }
526 #endif
527
528 // This simplifies the expose and clear areas to simple
529 // rectangles.
530 win->GetUpdateRegion() = win->GetUpdateRegion().GetBox();
531 win->GetClearRegion() = win->GetClearRegion().GetBox();
532
533 // If we only have one X11 window, always indicate
534 // that borders might have to be redrawn.
535 if (win->GetMainWindow() == win->GetClientAreaWindow())
536 win->NeedUpdateNcAreaInIdle();
537
538 // Only erase background, paint in idle time.
539 win->SendEraseEvents();
540
541 // EXPERIMENT
542 //win->Update();
543 }
544
545 return TRUE;
546 }
547
548 #if !wxUSE_NANOX
549 case GraphicsExpose:
550 {
551 printf( "GraphicExpose event\n" );
552
553 wxLogTrace( _T("expose"), _T("GraphicsExpose from %s"), win->GetName().c_str());
554
555 win->GetUpdateRegion().Union( event->xgraphicsexpose.x, event->xgraphicsexpose.y,
556 event->xgraphicsexpose.width, event->xgraphicsexpose.height);
557
558 win->GetClearRegion().Union( event->xgraphicsexpose.x, event->xgraphicsexpose.y,
559 event->xgraphicsexpose.width, event->xgraphicsexpose.height);
560
561 if (event->xgraphicsexpose.count == 0)
562 {
563 // Only erase background, paint in idle time.
564 win->SendEraseEvents();
565 // win->Update();
566 }
567
568 return TRUE;
569 }
570 #endif
571
572 case KeyPress:
573 {
574 if (!win->IsEnabled())
575 return FALSE;
576
577 wxKeyEvent keyEvent(wxEVT_KEY_DOWN);
578 wxTranslateKeyEvent(keyEvent, win, window, event);
579
580 // wxLogDebug( "OnKey from %s", win->GetName().c_str() );
581
582 // We didn't process wxEVT_KEY_DOWN, so send wxEVT_CHAR
583 if (win->GetEventHandler()->ProcessEvent( keyEvent ))
584 return TRUE;
585
586 keyEvent.SetEventType(wxEVT_CHAR);
587 // Do the translation again, retaining the ASCII
588 // code.
589 wxTranslateKeyEvent(keyEvent, win, window, event, TRUE);
590 if (win->GetEventHandler()->ProcessEvent( keyEvent ))
591 return TRUE;
592
593 if ( (keyEvent.m_keyCode == WXK_TAB) &&
594 win->GetParent() && (win->GetParent()->HasFlag( wxTAB_TRAVERSAL)) )
595 {
596 wxNavigationKeyEvent new_event;
597 new_event.SetEventObject( win->GetParent() );
598 /* GDK reports GDK_ISO_Left_Tab for SHIFT-TAB */
599 new_event.SetDirection( (keyEvent.m_keyCode == WXK_TAB) );
600 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
601 new_event.SetWindowChange( keyEvent.ControlDown() );
602 new_event.SetCurrentFocus( win );
603 return win->GetParent()->GetEventHandler()->ProcessEvent( new_event );
604 }
605
606 return FALSE;
607 }
608 case KeyRelease:
609 {
610 if (!win->IsEnabled())
611 return FALSE;
612
613 wxKeyEvent keyEvent(wxEVT_KEY_UP);
614 wxTranslateKeyEvent(keyEvent, win, window, event);
615
616 return win->GetEventHandler()->ProcessEvent( keyEvent );
617 }
618 case ConfigureNotify:
619 {
620 #if wxUSE_NANOX
621 if (event->update.utype == GR_UPDATE_SIZE)
622 #endif
623 {
624 if (win->IsTopLevel())
625 {
626 wxTopLevelWindow *tlw = (wxTopLevelWindow*) win;
627 tlw->SetConfigureGeometry( XConfigureEventGetX(event), XConfigureEventGetY(event),
628 XConfigureEventGetWidth(event), XConfigureEventGetHeight(event) );
629 }
630
631 if (win->IsTopLevel() && win->IsShown())
632 {
633 wxTopLevelWindowX11 *tlw = (wxTopLevelWindowX11 *) win;
634 tlw->SetNeedResizeInIdle();
635 }
636 else
637 {
638 wxSizeEvent sizeEvent( wxSize(XConfigureEventGetWidth(event), XConfigureEventGetHeight(event)), win->GetId() );
639 sizeEvent.SetEventObject( win );
640
641 return win->GetEventHandler()->ProcessEvent( sizeEvent );
642 }
643 }
644 return FALSE;
645 break;
646 }
647 #if !wxUSE_NANOX
648 case PropertyNotify:
649 {
650 //wxLogDebug("PropertyNotify: %s", windowClass.c_str());
651 return HandlePropertyChange(_event);
652 }
653 case ClientMessage:
654 {
655 if (!win->IsEnabled())
656 return FALSE;
657
658 Atom wm_delete_window = XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True);
659 Atom wm_protocols = XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True);
660
661 if (event->xclient.message_type == wm_protocols)
662 {
663 if ((Atom) (event->xclient.data.l[0]) == wm_delete_window)
664 {
665 win->Close(FALSE);
666 return TRUE;
667 }
668 }
669 return FALSE;
670 }
671 #if 0
672 case DestroyNotify:
673 {
674 printf( "destroy from %s\n", win->GetName().c_str() );
675 break;
676 }
677 case CreateNotify:
678 {
679 printf( "create from %s\n", win->GetName().c_str() );
680 break;
681 }
682 case MapRequest:
683 {
684 printf( "map request from %s\n", win->GetName().c_str() );
685 break;
686 }
687 case ResizeRequest:
688 {
689 printf( "resize request from %s\n", win->GetName().c_str() );
690
691 Display *disp = (Display*) wxGetDisplay();
692 XEvent report;
693
694 // to avoid flicker
695 report = * event;
696 while( XCheckTypedWindowEvent (disp, actualWindow, ResizeRequest, &report));
697
698 wxSize sz = win->GetSize();
699 wxSizeEvent sizeEvent(sz, win->GetId());
700 sizeEvent.SetEventObject(win);
701
702 return win->GetEventHandler()->ProcessEvent( sizeEvent );
703 }
704 #endif
705 #endif
706 #if wxUSE_NANOX
707 case GR_EVENT_TYPE_CLOSE_REQ:
708 {
709 if (win)
710 {
711 win->Close(FALSE);
712 return TRUE;
713 }
714 return FALSE;
715 break;
716 }
717 #endif
718 case EnterNotify:
719 case LeaveNotify:
720 case ButtonPress:
721 case ButtonRelease:
722 case MotionNotify:
723 {
724 if (!win->IsEnabled())
725 return FALSE;
726
727 // Here we check if the top level window is
728 // disabled, which is one aspect of modality.
729 wxWindow *tlw = win;
730 while (tlw && !tlw->IsTopLevel())
731 tlw = tlw->GetParent();
732 if (tlw && !tlw->IsEnabled())
733 return FALSE;
734
735 if (event->type == ButtonPress)
736 {
737 if ((win != wxWindow::FindFocus()) && win->AcceptsFocus())
738 {
739 // This might actually be done in wxWindow::SetFocus()
740 // and not here. TODO.
741 g_prevFocus = wxWindow::FindFocus();
742 g_nextFocus = win;
743
744 wxLogTrace( _T("focus"), _T("About to call SetFocus on %s of type %s due to button press"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
745
746 // Record the fact that this window is
747 // getting the focus, because we'll need to
748 // check if its parent is getting a bogus
749 // focus and duly ignore it.
750 // TODO: may need to have this code in SetFocus, too.
751 extern wxWindow* g_GettingFocus;
752 g_GettingFocus = win;
753 win->SetFocus();
754 }
755 }
756
757 #if !wxUSE_NANOX
758 if (event->type == LeaveNotify || event->type == EnterNotify)
759 {
760 // Throw out NotifyGrab and NotifyUngrab
761 if (event->xcrossing.mode != NotifyNormal)
762 return FALSE;
763 }
764 #endif
765 wxMouseEvent wxevent;
766 wxTranslateMouseEvent(wxevent, win, window, event);
767 return win->GetEventHandler()->ProcessEvent( wxevent );
768 }
769 case FocusIn:
770 {
771 #if !wxUSE_NANOX
772 if ((event->xfocus.detail != NotifyPointer) &&
773 (event->xfocus.mode == NotifyNormal))
774 #endif
775 {
776 wxLogTrace( _T("focus"), _T("FocusIn from %s of type %s"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
777
778 extern wxWindow* g_GettingFocus;
779 if (g_GettingFocus && g_GettingFocus->GetParent() == win)
780 {
781 // Ignore this, this can be a spurious FocusIn
782 // caused by a child having its focus set.
783 g_GettingFocus = NULL;
784 wxLogTrace( _T("focus"), _T("FocusIn from %s of type %s being deliberately ignored"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
785 return TRUE;
786 }
787 else
788 {
789 wxFocusEvent focusEvent(wxEVT_SET_FOCUS, win->GetId());
790 focusEvent.SetEventObject(win);
791 focusEvent.SetWindow( g_prevFocus );
792 g_prevFocus = NULL;
793
794 return win->GetEventHandler()->ProcessEvent(focusEvent);
795 }
796 }
797 return FALSE;
798 break;
799 }
800 case FocusOut:
801 {
802 #if !wxUSE_NANOX
803 if ((event->xfocus.detail != NotifyPointer) &&
804 (event->xfocus.mode == NotifyNormal))
805 #endif
806 {
807 wxLogTrace( _T("focus"), _T("FocusOut from %s of type %s"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
808
809 wxFocusEvent focusEvent(wxEVT_KILL_FOCUS, win->GetId());
810 focusEvent.SetEventObject(win);
811 focusEvent.SetWindow( g_nextFocus );
812 g_nextFocus = NULL;
813 return win->GetEventHandler()->ProcessEvent(focusEvent);
814 }
815 return FALSE;
816 break;
817 }
818 default:
819 {
820 #ifdef __WXDEBUG__
821 //wxString eventName = wxGetXEventName(XEvent& event);
822 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
823 #endif
824 return FALSE;
825 break;
826 }
827 }
828 return FALSE;
829 }
830
831 // Returns TRUE if more time is needed.
832 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
833 // but ProcessIdle may be needed by apps, so is kept.
834 bool wxApp::ProcessIdle()
835 {
836 wxIdleEvent event;
837 event.SetEventObject(this);
838 ProcessEvent(event);
839
840 return event.MoreRequested();
841 }
842
843 void wxApp::ExitMainLoop()
844 {
845 if (m_mainLoop)
846 m_mainLoop->Exit(0);
847 }
848
849 // Is a message/event pending?
850 bool wxApp::Pending()
851 {
852 return wxEventLoop::GetActive()->Pending();
853 }
854
855 // Dispatch a message.
856 void wxApp::Dispatch()
857 {
858 wxEventLoop::GetActive()->Dispatch();
859 }
860
861 // This should be redefined in a derived class for
862 // handling property change events for XAtom IPC.
863 bool wxApp::HandlePropertyChange(WXEvent *event)
864 {
865 // by default do nothing special
866 // TODO: what to do for X11
867 // XtDispatchEvent((XEvent*) event);
868 return FALSE;
869 }
870
871 void wxApp::OnIdle(wxIdleEvent& event)
872 {
873 static bool s_inOnIdle = FALSE;
874
875 // Avoid recursion (via ProcessEvent default case)
876 if (s_inOnIdle)
877 return;
878
879 s_inOnIdle = TRUE;
880
881 // Resend in the main thread events which have been prepared in other
882 // threads
883 ProcessPendingEvents();
884
885 // 'Garbage' collection of windows deleted with Close()
886 DeletePendingObjects();
887
888 // Send OnIdle events to all windows
889 bool needMore = SendIdleEvents();
890
891 if (needMore)
892 event.RequestMore(TRUE);
893
894 s_inOnIdle = FALSE;
895 }
896
897 void wxWakeUpIdle()
898 {
899 // **** please implement me! ****
900 // Wake up the idle handler processor, even if it is in another thread...
901 }
902
903
904 // Send idle event to all top-level windows
905 bool wxApp::SendIdleEvents()
906 {
907 bool needMore = FALSE;
908
909 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
910 while (node)
911 {
912 wxWindow* win = node->GetData();
913 if (SendIdleEvents(win))
914 needMore = TRUE;
915 node = node->GetNext();
916 }
917
918 return needMore;
919 }
920
921 // Send idle event to window and all subwindows
922 bool wxApp::SendIdleEvents(wxWindow* win)
923 {
924 bool needMore = FALSE;
925
926 wxIdleEvent event;
927 event.SetEventObject(win);
928
929 win->GetEventHandler()->ProcessEvent(event);
930
931 if (event.MoreRequested())
932 needMore = TRUE;
933
934 wxWindowListNode* node = win->GetChildren().GetFirst();
935 while (node)
936 {
937 wxWindow* win = (wxWindow*) node->GetData();
938 if (SendIdleEvents(win))
939 needMore = TRUE;
940
941 node = node->GetNext();
942 }
943
944 win->OnInternalIdle();
945
946 return needMore;
947 }
948
949 void wxApp::DeletePendingObjects()
950 {
951 wxNode *node = wxPendingDelete.GetFirst();
952 while (node)
953 {
954 wxObject *obj = (wxObject *)node->GetData();
955
956 delete obj;
957
958 if (wxPendingDelete.Member(obj))
959 delete node;
960
961 // Deleting one object may have deleted other pending
962 // objects, so start from beginning of list again.
963 node = wxPendingDelete.GetFirst();
964 }
965 }
966
967 static void wxCalcPrecAndShift( unsigned long mask, int *shift, int *prec )
968 {
969 *shift = 0;
970 *prec = 0;
971
972 while (!(mask & 0x1))
973 {
974 (*shift)++;
975 mask >>= 1;
976 }
977
978 while (mask & 0x1)
979 {
980 (*prec)++;
981 mask >>= 1;
982 }
983 }
984
985 // Create display, and other initialization
986 bool wxApp::OnInitGui()
987 {
988 // Eventually this line will be removed, but for
989 // now we don't want to try popping up a dialog
990 // for error messages.
991 delete wxLog::SetActiveTarget(new wxLogStderr);
992
993 if (!wxAppBase::OnInitGui())
994 return FALSE;
995
996 GetMainColormap( wxApp::GetDisplay() );
997
998 m_maxRequestSize = XMaxRequestSize( (Display*) wxApp::GetDisplay() );
999
1000 #if !wxUSE_NANOX
1001 // Get info about the current visual. It is enough
1002 // to do this once here unless we support different
1003 // visuals, displays and screens. Given that wxX11
1004 // mostly for embedded things, that is no real
1005 // limitation.
1006 Display *xdisplay = (Display*) wxApp::GetDisplay();
1007 int xscreen = DefaultScreen(xdisplay);
1008 Visual* xvisual = DefaultVisual(xdisplay,xscreen);
1009 int xdepth = DefaultDepth(xdisplay, xscreen);
1010
1011 XVisualInfo vinfo_template;
1012 vinfo_template.visual = xvisual;
1013 vinfo_template.visualid = XVisualIDFromVisual( xvisual );
1014 vinfo_template.depth = xdepth;
1015
1016 int nitem = 0;
1017 XVisualInfo *vi = XGetVisualInfo( xdisplay, VisualIDMask|VisualDepthMask, &vinfo_template, &nitem );
1018 wxASSERT_MSG( vi, wxT("No visual info") );
1019
1020 m_visualType = vi->visual->c_class;
1021 m_visualScreen = vi->screen;
1022
1023 m_visualRedMask = vi->red_mask;
1024 m_visualGreenMask = vi->green_mask;
1025 m_visualBlueMask = vi->blue_mask;
1026
1027 if (m_visualType != GrayScale && m_visualType != PseudoColor)
1028 {
1029 wxCalcPrecAndShift( m_visualRedMask, &m_visualRedShift, &m_visualRedPrec );
1030 wxCalcPrecAndShift( m_visualGreenMask, &m_visualGreenShift, &m_visualGreenPrec );
1031 wxCalcPrecAndShift( m_visualBlueMask, &m_visualBlueShift, &m_visualBluePrec );
1032 }
1033
1034 m_visualDepth = xdepth;
1035 if (xdepth == 16)
1036 xdepth = m_visualRedPrec + m_visualGreenPrec + m_visualBluePrec;
1037
1038 m_visualColormapSize = vi->colormap_size;
1039
1040 XFree( vi );
1041
1042 if (m_visualDepth > 8)
1043 return TRUE;
1044
1045 m_visualColormap = new XColor[m_visualColormapSize];
1046 XColor* colors = (XColor*) m_visualColormap;
1047
1048 for (int i = 0; i < m_visualColormapSize; i++)
1049 colors[i].pixel = i;
1050
1051 XQueryColors( xdisplay, DefaultColormap(xdisplay,xscreen), colors, m_visualColormapSize );
1052
1053 m_colorCube = (unsigned char*)malloc(32 * 32 * 32);
1054
1055 for (int r = 0; r < 32; r++)
1056 {
1057 for (int g = 0; g < 32; g++)
1058 {
1059 for (int b = 0; b < 32; b++)
1060 {
1061 int rr = (r << 3) | (r >> 2);
1062 int gg = (g << 3) | (g >> 2);
1063 int bb = (b << 3) | (b >> 2);
1064
1065 int index = -1;
1066
1067 if (colors)
1068 {
1069 int max = 3 * 65536;
1070
1071 for (int i = 0; i < m_visualColormapSize; i++)
1072 {
1073 int rdiff = ((rr << 8) - colors[i].red);
1074 int gdiff = ((gg << 8) - colors[i].green);
1075 int bdiff = ((bb << 8) - colors[i].blue);
1076 int sum = ABS (rdiff) + ABS (gdiff) + ABS (bdiff);
1077 if (sum < max)
1078 {
1079 index = i; max = sum;
1080 }
1081 }
1082 }
1083 else
1084 {
1085 // assume 8-bit true or static colors. this really exists
1086 index = (r >> (5 - m_visualRedPrec)) << m_visualRedShift;
1087 index |= (g >> (5 - m_visualGreenPrec)) << m_visualGreenShift;
1088 index |= (b >> (5 - m_visualBluePrec)) << m_visualBlueShift;
1089 }
1090 m_colorCube[ (r*1024) + (g*32) + b ] = index;
1091 }
1092 }
1093 }
1094 #endif
1095
1096 return TRUE;
1097 }
1098
1099 #if wxUSE_UNICODE
1100
1101 #include <pango/pango.h>
1102 #include <pango/pangox.h>
1103 #include <pango/pangoxft.h>
1104
1105 PangoContext* wxApp::GetPangoContext()
1106 {
1107 static PangoContext *ret = NULL;
1108 if (ret)
1109 return ret;
1110
1111 Display *xdisplay = (Display*) wxApp::GetDisplay();
1112
1113 #if 1
1114 int xscreen = DefaultScreen(xdisplay);
1115 static int use_xft = -1;
1116 if (use_xft == -1)
1117 {
1118 wxString val = wxGetenv( L"GDK_USE_XFT" );
1119 use_xft = (val == L"1");
1120 }
1121
1122 if (use_xft)
1123 ret = pango_xft_get_context( xdisplay, xscreen );
1124 else
1125 #endif
1126 ret = pango_x_get_context( xdisplay );
1127
1128 if (!PANGO_IS_CONTEXT(ret))
1129 wxLogError( wxT("No pango context.") );
1130
1131 return ret;
1132 }
1133 #endif
1134
1135 WXColormap wxApp::GetMainColormap(WXDisplay* display)
1136 {
1137 if (!display) /* Must be called first with non-NULL display */
1138 return m_mainColormap;
1139
1140 int defaultScreen = DefaultScreen((Display*) display);
1141 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
1142
1143 Colormap c = DefaultColormapOfScreen(screen);
1144
1145 if (!m_mainColormap)
1146 m_mainColormap = (WXColormap) c;
1147
1148 return (WXColormap) c;
1149 }
1150
1151 Window wxGetWindowParent(Window window)
1152 {
1153 wxASSERT_MSG( window, "invalid window" );
1154
1155 return (Window) 0;
1156
1157 Window parent, root = 0;
1158 #if wxUSE_NANOX
1159 int noChildren = 0;
1160 #else
1161 unsigned int noChildren = 0;
1162 #endif
1163 Window* children = NULL;
1164
1165 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
1166 int res = 1;
1167 #if !wxUSE_NANOX
1168 res =
1169 #endif
1170 XQueryTree((Display*) wxGetDisplay(), window, & root, & parent,
1171 & children, & noChildren);
1172 if (children)
1173 XFree(children);
1174 if (res)
1175 return parent;
1176 else
1177 return (Window) 0;
1178 }
1179
1180 void wxExit()
1181 {
1182 int retValue = 0;
1183 if (wxTheApp)
1184 retValue = wxTheApp->OnExit();
1185
1186 wxApp::CleanUp();
1187 /*
1188 * Exit in some platform-specific way. Not recommended that the app calls this:
1189 * only for emergencies.
1190 */
1191 exit(retValue);
1192 }
1193
1194 // Yield to other processes
1195
1196 bool wxApp::Yield(bool onlyIfNeeded)
1197 {
1198 // Sometimes only 2 yields seem
1199 // to do the trick, e.g. in the
1200 // progress dialog
1201 int i;
1202 for (i = 0; i < 2; i++)
1203 {
1204 bool s_inYield = FALSE;
1205
1206 if ( s_inYield )
1207 {
1208 if ( !onlyIfNeeded )
1209 {
1210 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1211 }
1212
1213 return FALSE;
1214 }
1215
1216 s_inYield = TRUE;
1217
1218 // Make sure we have an event loop object,
1219 // or Pending/Dispatch will fail
1220 wxEventLoop* eventLoop = wxEventLoop::GetActive();
1221 wxEventLoop* newEventLoop = NULL;
1222 if (!eventLoop)
1223 {
1224 newEventLoop = new wxEventLoop;
1225 wxEventLoop::SetActive(newEventLoop);
1226 }
1227
1228 // Call dispatch at least once so that sockets
1229 // can be tested
1230 wxTheApp->Dispatch();
1231
1232 while (wxTheApp && wxTheApp->Pending())
1233 wxTheApp->Dispatch();
1234
1235 #if wxUSE_TIMER
1236 wxTimer::NotifyTimers();
1237 #endif
1238 ProcessIdle();
1239
1240 if (newEventLoop)
1241 {
1242 wxEventLoop::SetActive(NULL);
1243 delete newEventLoop;
1244 }
1245
1246 s_inYield = FALSE;
1247 }
1248
1249 return TRUE;
1250 }
1251
1252 #ifdef __WXDEBUG__
1253
1254 void wxApp::OnAssert(const wxChar *file, int line, const wxChar* cond, const wxChar *msg)
1255 {
1256 // While the GUI isn't working that well, just print out the
1257 // message.
1258 #if 1
1259 wxAppBase::OnAssert(file, line, cond, msg);
1260 #else
1261 wxString msg2;
1262 msg2.Printf("At file %s:%d: %s", file, line, msg);
1263 wxLogDebug(msg2);
1264 #endif
1265 }
1266
1267 #endif // __WXDEBUG__
1268