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