]> git.saurik.com Git - wxWidgets.git/blob - src/x11/app.cpp
fdfe4c3a42476139ac662e5f4dd20ef6ed8d2c61
[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 // TODO: parse the command line
392 argc = 0;
393 argv = NULL;
394
395 m_mainColormap = (WXColormap) NULL;
396 m_topLevelWidget = (WXWindow) NULL;
397 m_maxRequestSize = 0;
398 m_mainLoop = NULL;
399 m_showIconic = FALSE;
400 m_initialSize = wxDefaultSize;
401
402 #if !wxUSE_NANOX
403 m_visualColormap = NULL;
404 m_colorCube = NULL;
405 #endif
406 }
407
408 wxApp::~wxApp()
409 {
410 #if !wxUSE_NANOX
411 if (m_colorCube)
412 free( m_colorCube );
413
414 if (m_visualColormap)
415 delete [] (XColor*)m_visualColormap;
416 #endif
417 }
418
419 bool wxApp::Initialized()
420 {
421 if (GetTopWindow())
422 return TRUE;
423 else
424 return FALSE;
425 }
426
427 int wxApp::MainLoop()
428 {
429 int rt;
430 m_mainLoop = new wxEventLoop;
431
432 rt = m_mainLoop->Run();
433
434 delete m_mainLoop;
435 m_mainLoop = NULL;
436 return rt;
437 }
438
439 #if !wxUSE_NANOX
440 //-----------------------------------------------------------------------
441 // X11 predicate function for exposure compression
442 //-----------------------------------------------------------------------
443
444 struct wxExposeInfo
445 {
446 Window window;
447 Bool found_non_matching;
448 };
449
450 static Bool expose_predicate (Display *display, XEvent *xevent, XPointer arg)
451 {
452 wxExposeInfo *info = (wxExposeInfo*) arg;
453
454 if (info->found_non_matching)
455 return FALSE;
456
457 if (xevent->xany.type != Expose)
458 {
459 info->found_non_matching = TRUE;
460 return FALSE;
461 }
462
463 if (xevent->xexpose.window != info->window)
464 {
465 info->found_non_matching = TRUE;
466 return FALSE;
467 }
468
469 return TRUE;
470 }
471 #endif
472 // wxUSE_NANOX
473
474 //-----------------------------------------------------------------------
475 // Processes an X event, returning TRUE if the event was processed.
476 //-----------------------------------------------------------------------
477
478 bool wxApp::ProcessXEvent(WXEvent* _event)
479 {
480 XEvent* event = (XEvent*) _event;
481
482 wxWindow* win = NULL;
483 Window window = XEventGetWindow(event);
484 #if 0
485 Window actualWindow = window;
486 #endif
487
488 // Find the first wxWindow that corresponds to this event window
489 // Because we're receiving events after a window
490 // has been destroyed, assume a 1:1 match between
491 // Window and wxWindow, so if it's not in the table,
492 // it must have been destroyed.
493
494 win = wxGetWindowFromTable(window);
495 if (!win)
496 {
497 #if wxUSE_TWO_WINDOWS
498 win = wxGetClientWindowFromTable(window);
499 if (!win)
500 #endif
501 return FALSE;
502 }
503
504 #ifdef __WXDEBUG__
505 wxString windowClass = win->GetClassInfo()->GetClassName();
506 #endif
507
508 switch (event->type)
509 {
510 case Expose:
511 {
512 #if wxUSE_TWO_WINDOWS && !wxUSE_NANOX
513 if (event->xexpose.window != (Window)win->GetClientAreaWindow())
514 {
515 XEvent tmp_event;
516 wxExposeInfo info;
517 info.window = event->xexpose.window;
518 info.found_non_matching = FALSE;
519 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event, expose_predicate, (XPointer) &info ))
520 {
521 // Don't worry about optimizing redrawing the border etc.
522 }
523 win->NeedUpdateNcAreaInIdle();
524 }
525 else
526 #endif
527 {
528 win->GetUpdateRegion().Union( XExposeEventGetX(event), XExposeEventGetY(event),
529 XExposeEventGetWidth(event), XExposeEventGetHeight(event));
530 win->GetClearRegion().Union( XExposeEventGetX(event), XExposeEventGetY(event),
531 XExposeEventGetWidth(event), XExposeEventGetHeight(event));
532
533 #if !wxUSE_NANOX
534 XEvent tmp_event;
535 wxExposeInfo info;
536 info.window = event->xexpose.window;
537 info.found_non_matching = FALSE;
538 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event, expose_predicate, (XPointer) &info ))
539 {
540 win->GetUpdateRegion().Union( tmp_event.xexpose.x, tmp_event.xexpose.y,
541 tmp_event.xexpose.width, tmp_event.xexpose.height );
542
543 win->GetClearRegion().Union( tmp_event.xexpose.x, tmp_event.xexpose.y,
544 tmp_event.xexpose.width, tmp_event.xexpose.height );
545 }
546 #endif
547
548 // This simplifies the expose and clear areas to simple
549 // rectangles.
550 win->GetUpdateRegion() = win->GetUpdateRegion().GetBox();
551 win->GetClearRegion() = win->GetClearRegion().GetBox();
552
553 // If we only have one X11 window, always indicate
554 // that borders might have to be redrawn.
555 if (win->GetMainWindow() == win->GetClientAreaWindow())
556 win->NeedUpdateNcAreaInIdle();
557
558 // Only erase background, paint in idle time.
559 win->SendEraseEvents();
560 // win->Update();
561 }
562
563 return TRUE;
564 }
565
566 #if !wxUSE_NANOX
567 case GraphicsExpose:
568 {
569 printf( "GraphicExpose event\n" );
570
571 wxLogTrace( _T("expose"), _T("GraphicsExpose from %s"), win->GetName().c_str(),
572 event->xgraphicsexpose.x, event->xgraphicsexpose.y,
573 event->xgraphicsexpose.width, event->xgraphicsexpose.height);
574
575 win->GetUpdateRegion().Union( event->xgraphicsexpose.x, event->xgraphicsexpose.y,
576 event->xgraphicsexpose.width, event->xgraphicsexpose.height);
577
578 win->GetClearRegion().Union( event->xgraphicsexpose.x, event->xgraphicsexpose.y,
579 event->xgraphicsexpose.width, event->xgraphicsexpose.height);
580
581 if (event->xgraphicsexpose.count == 0)
582 {
583 // Only erase background, paint in idle time.
584 win->SendEraseEvents();
585 // win->Update();
586 }
587
588 return TRUE;
589 }
590 #endif
591
592 case KeyPress:
593 {
594 if (!win->IsEnabled())
595 return FALSE;
596
597 wxKeyEvent keyEvent(wxEVT_KEY_DOWN);
598 wxTranslateKeyEvent(keyEvent, win, window, event);
599
600 // wxLogDebug( "OnKey from %s", win->GetName().c_str() );
601
602 // We didn't process wxEVT_KEY_DOWN, so send wxEVT_CHAR
603 if (win->GetEventHandler()->ProcessEvent( keyEvent ))
604 return TRUE;
605
606 keyEvent.SetEventType(wxEVT_CHAR);
607 if (win->GetEventHandler()->ProcessEvent( keyEvent ))
608 return TRUE;
609
610 if ( (keyEvent.m_keyCode == WXK_TAB) &&
611 win->GetParent() && (win->GetParent()->HasFlag( wxTAB_TRAVERSAL)) )
612 {
613 wxNavigationKeyEvent new_event;
614 new_event.SetEventObject( win->GetParent() );
615 /* GDK reports GDK_ISO_Left_Tab for SHIFT-TAB */
616 new_event.SetDirection( (keyEvent.m_keyCode == WXK_TAB) );
617 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
618 new_event.SetWindowChange( keyEvent.ControlDown() );
619 new_event.SetCurrentFocus( win );
620 return win->GetParent()->GetEventHandler()->ProcessEvent( new_event );
621 }
622
623 return FALSE;
624 }
625 case KeyRelease:
626 {
627 if (!win->IsEnabled())
628 return FALSE;
629
630 wxKeyEvent keyEvent(wxEVT_KEY_UP);
631 wxTranslateKeyEvent(keyEvent, win, window, event);
632
633 return win->GetEventHandler()->ProcessEvent( keyEvent );
634 }
635 case ConfigureNotify:
636 {
637 #if wxUSE_NANOX
638 if (event->update.utype == GR_UPDATE_SIZE)
639 #endif
640 {
641 if (win->IsTopLevel())
642 {
643 wxTopLevelWindow *tlw = (wxTopLevelWindow*) win;
644 tlw->SetConfigureGeometry( XConfigureEventGetX(event), XConfigureEventGetY(event),
645 XConfigureEventGetWidth(event), XConfigureEventGetHeight(event) );
646 }
647
648 if (win->IsTopLevel() && win->IsShown())
649 {
650 wxTopLevelWindowX11 *tlw = (wxTopLevelWindowX11 *) win;
651 tlw->SetNeedResizeInIdle();
652 }
653 else
654 {
655 wxSizeEvent sizeEvent( wxSize(XConfigureEventGetWidth(event), XConfigureEventGetHeight(event)), win->GetId() );
656 sizeEvent.SetEventObject( win );
657
658 return win->GetEventHandler()->ProcessEvent( sizeEvent );
659 }
660 }
661 return FALSE;
662 break;
663 }
664 #if !wxUSE_NANOX
665 case PropertyNotify:
666 {
667 //wxLogDebug("PropertyNotify: %s", windowClass.c_str());
668 return HandlePropertyChange(_event);
669 }
670 case ClientMessage:
671 {
672 if (!win->IsEnabled())
673 return FALSE;
674
675 Atom wm_delete_window = XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True);
676 Atom wm_protocols = XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True);
677
678 if (event->xclient.message_type == wm_protocols)
679 {
680 if ((Atom) (event->xclient.data.l[0]) == wm_delete_window)
681 {
682 win->Close(FALSE);
683 return TRUE;
684 }
685 }
686 return FALSE;
687 }
688 #if 0
689 case DestroyNotify:
690 {
691 printf( "destroy from %s\n", win->GetName().c_str() );
692 break;
693 }
694 case CreateNotify:
695 {
696 printf( "create from %s\n", win->GetName().c_str() );
697 break;
698 }
699 case MapRequest:
700 {
701 printf( "map request from %s\n", win->GetName().c_str() );
702 break;
703 }
704 case ResizeRequest:
705 {
706 printf( "resize request from %s\n", win->GetName().c_str() );
707
708 Display *disp = (Display*) wxGetDisplay();
709 XEvent report;
710
711 // to avoid flicker
712 report = * event;
713 while( XCheckTypedWindowEvent (disp, actualWindow, ResizeRequest, &report));
714
715 wxSize sz = win->GetSize();
716 wxSizeEvent sizeEvent(sz, win->GetId());
717 sizeEvent.SetEventObject(win);
718
719 return win->GetEventHandler()->ProcessEvent( sizeEvent );
720 }
721 #endif
722 #endif
723 #if wxUSE_NANOX
724 case GR_EVENT_TYPE_CLOSE_REQ:
725 {
726 if (win)
727 {
728 win->Close(FALSE);
729 return TRUE;
730 }
731 return FALSE;
732 break;
733 }
734 #endif
735 case EnterNotify:
736 case LeaveNotify:
737 case ButtonPress:
738 case ButtonRelease:
739 case MotionNotify:
740 {
741 if (!win->IsEnabled())
742 return FALSE;
743
744 // Here we check if the top level window is
745 // disabled, which is one aspect of modality.
746 wxWindow *tlw = win;
747 while (tlw && !tlw->IsTopLevel())
748 tlw = tlw->GetParent();
749 if (tlw && !tlw->IsEnabled())
750 return FALSE;
751
752 if (event->type == ButtonPress)
753 {
754 if ((win != wxWindow::FindFocus()) && win->AcceptsFocus())
755 {
756 // This might actually be done in wxWindow::SetFocus()
757 // and not here. TODO.
758 g_prevFocus = wxWindow::FindFocus();
759 g_nextFocus = win;
760
761 wxLogTrace( _T("focus"), _T("About to call SetFocus on %s of type %s due to button press"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
762
763 // Record the fact that this window is
764 // getting the focus, because we'll need to
765 // check if its parent is getting a bogus
766 // focus and duly ignore it.
767 // TODO: may need to have this code in SetFocus, too.
768 extern wxWindow* g_GettingFocus;
769 g_GettingFocus = win;
770 win->SetFocus();
771 }
772 }
773
774 #if !wxUSE_NANOX
775 if (event->type == LeaveNotify || event->type == EnterNotify)
776 {
777 // Throw out NotifyGrab and NotifyUngrab
778 if (event->xcrossing.mode != NotifyNormal)
779 return FALSE;
780 }
781 #endif
782 wxMouseEvent wxevent;
783 wxTranslateMouseEvent(wxevent, win, window, event);
784 return win->GetEventHandler()->ProcessEvent( wxevent );
785 }
786 case FocusIn:
787 {
788 #if !wxUSE_NANOX
789 if ((event->xfocus.detail != NotifyPointer) &&
790 (event->xfocus.mode == NotifyNormal))
791 #endif
792 {
793 wxLogTrace( _T("focus"), _T("FocusIn from %s of type %s"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
794
795 extern wxWindow* g_GettingFocus;
796 if (g_GettingFocus && g_GettingFocus->GetParent() == win)
797 {
798 // Ignore this, this can be a spurious FocusIn
799 // caused by a child having its focus set.
800 g_GettingFocus = NULL;
801 wxLogTrace( _T("focus"), _T("FocusIn from %s of type %s being deliberately ignored"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
802 return TRUE;
803 }
804 else
805 {
806 wxFocusEvent focusEvent(wxEVT_SET_FOCUS, win->GetId());
807 focusEvent.SetEventObject(win);
808 focusEvent.SetWindow( g_prevFocus );
809 g_prevFocus = NULL;
810
811 return win->GetEventHandler()->ProcessEvent(focusEvent);
812 }
813 }
814 return FALSE;
815 break;
816 }
817 case FocusOut:
818 {
819 #if !wxUSE_NANOX
820 if ((event->xfocus.detail != NotifyPointer) &&
821 (event->xfocus.mode == NotifyNormal))
822 #endif
823 {
824 wxLogTrace( _T("focus"), _T("FocusOut from %s of type %s"), win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
825
826 wxFocusEvent focusEvent(wxEVT_KILL_FOCUS, win->GetId());
827 focusEvent.SetEventObject(win);
828 focusEvent.SetWindow( g_nextFocus );
829 g_nextFocus = NULL;
830 return win->GetEventHandler()->ProcessEvent(focusEvent);
831 }
832 return FALSE;
833 break;
834 }
835 default:
836 {
837 #ifdef __WXDEBUG__
838 //wxString eventName = wxGetXEventName(XEvent& event);
839 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
840 #endif
841 return FALSE;
842 break;
843 }
844 }
845 return FALSE;
846 }
847
848 // Returns TRUE if more time is needed.
849 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
850 // but ProcessIdle may be needed by apps, so is kept.
851 bool wxApp::ProcessIdle()
852 {
853 wxIdleEvent event;
854 event.SetEventObject(this);
855 ProcessEvent(event);
856
857 return event.MoreRequested();
858 }
859
860 void wxApp::ExitMainLoop()
861 {
862 if (m_mainLoop)
863 m_mainLoop->Exit(0);
864 }
865
866 // Is a message/event pending?
867 bool wxApp::Pending()
868 {
869 return wxEventLoop::GetActive()->Pending();
870 }
871
872 // Dispatch a message.
873 void wxApp::Dispatch()
874 {
875 wxEventLoop::GetActive()->Dispatch();
876 }
877
878 // This should be redefined in a derived class for
879 // handling property change events for XAtom IPC.
880 bool wxApp::HandlePropertyChange(WXEvent *event)
881 {
882 // by default do nothing special
883 // TODO: what to do for X11
884 // XtDispatchEvent((XEvent*) event);
885 return FALSE;
886 }
887
888 void wxApp::OnIdle(wxIdleEvent& event)
889 {
890 static bool s_inOnIdle = FALSE;
891
892 // Avoid recursion (via ProcessEvent default case)
893 if (s_inOnIdle)
894 return;
895
896 s_inOnIdle = TRUE;
897
898 // Resend in the main thread events which have been prepared in other
899 // threads
900 ProcessPendingEvents();
901
902 // 'Garbage' collection of windows deleted with Close()
903 DeletePendingObjects();
904
905 // Send OnIdle events to all windows
906 bool needMore = SendIdleEvents();
907
908 if (needMore)
909 event.RequestMore(TRUE);
910
911 s_inOnIdle = FALSE;
912 }
913
914 void wxWakeUpIdle()
915 {
916 // **** please implement me! ****
917 // Wake up the idle handler processor, even if it is in another thread...
918 }
919
920
921 // Send idle event to all top-level windows
922 bool wxApp::SendIdleEvents()
923 {
924 bool needMore = FALSE;
925
926 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
927 while (node)
928 {
929 wxWindow* win = node->GetData();
930 if (SendIdleEvents(win))
931 needMore = TRUE;
932 node = node->GetNext();
933 }
934
935 return needMore;
936 }
937
938 // Send idle event to window and all subwindows
939 bool wxApp::SendIdleEvents(wxWindow* win)
940 {
941 bool needMore = FALSE;
942
943 wxIdleEvent event;
944 event.SetEventObject(win);
945
946 win->GetEventHandler()->ProcessEvent(event);
947
948 if (event.MoreRequested())
949 needMore = TRUE;
950
951 wxNode* node = win->GetChildren().First();
952 while (node)
953 {
954 wxWindow* win = (wxWindow*) node->Data();
955 if (SendIdleEvents(win))
956 needMore = TRUE;
957
958 node = node->Next();
959 }
960
961 win->OnInternalIdle();
962
963 return needMore;
964 }
965
966 void wxApp::DeletePendingObjects()
967 {
968 wxNode *node = wxPendingDelete.First();
969 while (node)
970 {
971 wxObject *obj = (wxObject *)node->Data();
972
973 delete obj;
974
975 if (wxPendingDelete.Member(obj))
976 delete node;
977
978 // Deleting one object may have deleted other pending
979 // objects, so start from beginning of list again.
980 node = wxPendingDelete.First();
981 }
982 }
983
984 static void wxCalcPrecAndShift( unsigned long mask, int *shift, int *prec )
985 {
986 *shift = 0;
987 *prec = 0;
988
989 while (!(mask & 0x1))
990 {
991 (*shift)++;
992 mask >>= 1;
993 }
994
995 while (mask & 0x1)
996 {
997 (*prec)++;
998 mask >>= 1;
999 }
1000 }
1001
1002 // Create display, and other initialization
1003 bool wxApp::OnInitGui()
1004 {
1005 // Eventually this line will be removed, but for
1006 // now we don't want to try popping up a dialog
1007 // for error messages.
1008 delete wxLog::SetActiveTarget(new wxLogStderr);
1009
1010 if (!wxAppBase::OnInitGui())
1011 return FALSE;
1012
1013 GetMainColormap( wxApp::GetDisplay() );
1014
1015 m_maxRequestSize = XMaxRequestSize( (Display*) wxApp::GetDisplay() );
1016
1017 #if !wxUSE_NANOX
1018 // Get info about the current visual. It is enough
1019 // to do this once here unless we support different
1020 // visuals, displays and screens. Given that wxX11
1021 // mostly for embedded things, that is no real
1022 // limitation.
1023 Display *xdisplay = (Display*) wxApp::GetDisplay();
1024 int xscreen = DefaultScreen(xdisplay);
1025 Visual* xvisual = DefaultVisual(xdisplay,xscreen);
1026 int xdepth = DefaultDepth(xdisplay, xscreen);
1027
1028 XVisualInfo vinfo_template;
1029 vinfo_template.visual = xvisual;
1030 vinfo_template.visualid = XVisualIDFromVisual( xvisual );
1031 vinfo_template.depth = xdepth;
1032
1033 int nitem = 0;
1034 XVisualInfo *vi = XGetVisualInfo( xdisplay, VisualIDMask|VisualDepthMask, &vinfo_template, &nitem );
1035 wxASSERT_MSG( vi, wxT("No visual info") );
1036
1037 m_visualType = vi->visual->c_class;
1038 m_visualScreen = vi->screen;
1039
1040 m_visualRedMask = vi->red_mask;
1041 m_visualGreenMask = vi->green_mask;
1042 m_visualBlueMask = vi->blue_mask;
1043
1044 if (m_visualType != GrayScale && m_visualType != PseudoColor)
1045 {
1046 wxCalcPrecAndShift( m_visualRedMask, &m_visualRedShift, &m_visualRedPrec );
1047 wxCalcPrecAndShift( m_visualGreenMask, &m_visualGreenShift, &m_visualGreenPrec );
1048 wxCalcPrecAndShift( m_visualBlueMask, &m_visualBlueShift, &m_visualBluePrec );
1049 }
1050
1051 m_visualDepth = xdepth;
1052 if (xdepth == 16)
1053 xdepth = m_visualRedPrec + m_visualGreenPrec + m_visualBluePrec;
1054
1055 m_visualColormapSize = vi->colormap_size;
1056
1057 XFree( vi );
1058
1059 if (m_visualDepth > 8)
1060 return TRUE;
1061
1062 m_visualColormap = new XColor[m_visualColormapSize];
1063 XColor* colors = (XColor*) m_visualColormap;
1064
1065 for (int i = 0; i < m_visualColormapSize; i++)
1066 colors[i].pixel = i;
1067
1068 XQueryColors( xdisplay, DefaultColormap(xdisplay,xscreen), colors, m_visualColormapSize );
1069
1070 m_colorCube = (unsigned char*)malloc(32 * 32 * 32);
1071
1072 for (int r = 0; r < 32; r++)
1073 {
1074 for (int g = 0; g < 32; g++)
1075 {
1076 for (int b = 0; b < 32; b++)
1077 {
1078 int rr = (r << 3) | (r >> 2);
1079 int gg = (g << 3) | (g >> 2);
1080 int bb = (b << 3) | (b >> 2);
1081
1082 int index = -1;
1083
1084 if (colors)
1085 {
1086 int max = 3 * 65536;
1087
1088 for (int i = 0; i < m_visualColormapSize; i++)
1089 {
1090 int rdiff = ((rr << 8) - colors[i].red);
1091 int gdiff = ((gg << 8) - colors[i].green);
1092 int bdiff = ((bb << 8) - colors[i].blue);
1093 int sum = ABS (rdiff) + ABS (gdiff) + ABS (bdiff);
1094 if (sum < max)
1095 {
1096 index = i; max = sum;
1097 }
1098 }
1099 }
1100 else
1101 {
1102 // assume 8-bit true or static colors. this really exists
1103 index = (r >> (5 - m_visualRedPrec)) << m_visualRedShift;
1104 index |= (g >> (5 - m_visualGreenPrec)) << m_visualGreenShift;
1105 index |= (b >> (5 - m_visualBluePrec)) << m_visualBlueShift;
1106 }
1107 m_colorCube[ (r*1024) + (g*32) + b ] = index;
1108 }
1109 }
1110 }
1111 #endif
1112
1113 return TRUE;
1114 }
1115
1116 WXColormap wxApp::GetMainColormap(WXDisplay* display)
1117 {
1118 if (!display) /* Must be called first with non-NULL display */
1119 return m_mainColormap;
1120
1121 int defaultScreen = DefaultScreen((Display*) display);
1122 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
1123
1124 Colormap c = DefaultColormapOfScreen(screen);
1125
1126 if (!m_mainColormap)
1127 m_mainColormap = (WXColormap) c;
1128
1129 return (WXColormap) c;
1130 }
1131
1132 Window wxGetWindowParent(Window window)
1133 {
1134 wxASSERT_MSG( window, "invalid window" );
1135
1136 return (Window) 0;
1137
1138 Window parent, root = 0;
1139 #if wxUSE_NANOX
1140 int noChildren = 0;
1141 #else
1142 unsigned int noChildren = 0;
1143 #endif
1144 Window* children = NULL;
1145
1146 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
1147 int res = 1;
1148 #if !wxUSE_NANOX
1149 res =
1150 #endif
1151 XQueryTree((Display*) wxGetDisplay(), window, & root, & parent,
1152 & children, & noChildren);
1153 if (children)
1154 XFree(children);
1155 if (res)
1156 return parent;
1157 else
1158 return (Window) 0;
1159 }
1160
1161 void wxExit()
1162 {
1163 int retValue = 0;
1164 if (wxTheApp)
1165 retValue = wxTheApp->OnExit();
1166
1167 wxApp::CleanUp();
1168 /*
1169 * Exit in some platform-specific way. Not recommended that the app calls this:
1170 * only for emergencies.
1171 */
1172 exit(retValue);
1173 }
1174
1175 // Yield to other processes
1176
1177 bool wxApp::Yield(bool onlyIfNeeded)
1178 {
1179 bool s_inYield = FALSE;
1180
1181 if ( s_inYield )
1182 {
1183 if ( !onlyIfNeeded )
1184 {
1185 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1186 }
1187
1188 return FALSE;
1189 }
1190
1191 s_inYield = TRUE;
1192
1193 // Make sure we have an event loop object,
1194 // or Pending/Dispatch will fail
1195 wxEventLoop* eventLoop = wxEventLoop::GetActive();
1196 wxEventLoop* newEventLoop = NULL;
1197 if (!eventLoop)
1198 {
1199 newEventLoop = new wxEventLoop;
1200 wxEventLoop::SetActive(newEventLoop);
1201 }
1202
1203 while (wxTheApp && wxTheApp->Pending())
1204 wxTheApp->Dispatch();
1205
1206 #if wxUSE_TIMER
1207 wxTimer::NotifyTimers();
1208 #endif
1209 ProcessIdle();
1210
1211 if (newEventLoop)
1212 {
1213 wxEventLoop::SetActive(NULL);
1214 delete newEventLoop;
1215 }
1216
1217 s_inYield = FALSE;
1218
1219 return TRUE;
1220 }
1221
1222 #ifdef __WXDEBUG__
1223
1224 void wxApp::OnAssert(const wxChar *file, int line, const wxChar* cond, const wxChar *msg)
1225 {
1226 // While the GUI isn't working that well, just print out the
1227 // message.
1228 #if 1
1229 wxAppBase::OnAssert(file, line, cond, msg);
1230 #else
1231 wxString msg2;
1232 msg2.Printf("At file %s:%d: %s", file, line, msg);
1233 wxLogDebug(msg2);
1234 #endif
1235 }
1236
1237 #endif // __WXDEBUG__
1238