Fixed drawing sample compilo for wxMotif (doesn't have wxRegion::Offset)
[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 // 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 #if wxUSE_WX_RESOURCES
121 wxInitializeResourceSystem();
122 #endif
123
124 wxWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
125 wxClientWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
126
127 wxModule::RegisterModules();
128 if (!wxModule::InitializeModules()) return FALSE;
129
130 return TRUE;
131 }
132
133 void wxApp::CleanUp()
134 {
135 if (g_newArgv)
136 delete[] g_newArgv;
137 g_newArgv = NULL;
138
139 delete wxWidgetHashTable;
140 wxWidgetHashTable = NULL;
141 delete wxClientWidgetHashTable;
142 wxClientWidgetHashTable = NULL;
143
144 wxModule::CleanUpModules();
145
146 #if wxUSE_WX_RESOURCES
147 wxCleanUpResourceSystem();
148 #endif
149
150 delete wxTheColourDatabase;
151 wxTheColourDatabase = NULL;
152
153 wxDeleteStockObjects();
154
155 wxDeleteStockLists();
156
157 delete wxTheApp;
158 wxTheApp = NULL;
159
160 wxClassInfo::CleanUpClasses();
161
162 #if wxUSE_THREADS
163 delete wxPendingEvents;
164 delete wxPendingEventsLocker;
165 #endif
166
167 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
168 // At this point we want to check if there are any memory
169 // blocks that aren't part of the wxDebugContext itself,
170 // as a special case. Then when dumping we need to ignore
171 // wxDebugContext, too.
172 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
173 {
174 wxLogDebug("There were memory leaks.");
175 wxDebugContext::Dump();
176 wxDebugContext::PrintStatistics();
177 }
178 #endif
179
180 // do it as the very last thing because everything else can log messages
181 wxLog::DontCreateOnDemand();
182 // do it as the very last thing because everything else can log messages
183 delete wxLog::SetActiveTarget(NULL);
184 }
185
186 // NB: argc and argv may be changed here, pass by reference!
187 int wxEntryStart( int& argc, char *argv[] )
188 {
189 #ifdef __WXDEBUG__
190 #if !wxUSE_NANOX
191 // install the X error handler
192 gs_pfnXErrorHandler = XSetErrorHandler( wxXErrorHandler );
193 #endif
194 #endif // __WXDEBUG__
195
196 wxString displayName;
197 bool syncDisplay = FALSE;
198
199 // Parse the arguments.
200 // We can't use wxCmdLineParser or OnInitCmdLine and friends because
201 // we have to create the Display earlier. If we can find a way to
202 // use the wxAppBase API then I'll be quite happy to change it.
203 g_newArgv = new wxChar*[argc];
204 g_newArgc = 0;
205 int i;
206 for (i = 0; i < argc; i++)
207 {
208 wxString arg(argv[i]);
209 if (arg == wxT("-display"))
210 {
211 if (i < (argc - 1))
212 {
213 i ++;
214 displayName = argv[i];
215 continue;
216 }
217 }
218 else if (arg == wxT("-geometry"))
219 {
220 if (i < (argc - 1))
221 {
222 i ++;
223 wxString windowGeometry = argv[i];
224 int w, h;
225 if (wxSscanf(windowGeometry.c_str(), _T("%dx%d"), &w, &h) != 2)
226 {
227 wxLogError(_("Invalid geometry specification '%s'"), windowGeometry.c_str());
228 }
229 else
230 {
231 g_initialSize = wxSize(w, h);
232 }
233 continue;
234 }
235 }
236 else if (arg == wxT("-sync"))
237 {
238 syncDisplay = TRUE;
239 continue;
240 }
241 else if (arg == wxT("-iconic"))
242 {
243 g_showIconic = TRUE;
244
245 continue;
246 }
247
248 // Not eaten by wxWindows, so pass through
249 g_newArgv[g_newArgc] = argv[i];
250 g_newArgc ++;
251 }
252
253 Display* xdisplay = NULL;
254 if (displayName.IsEmpty())
255 xdisplay = XOpenDisplay(NULL);
256 else
257 xdisplay = XOpenDisplay((char*) displayName.c_str());
258
259 if (!xdisplay)
260 {
261 wxLogError( _("wxWindows could not open display. Exiting.") );
262 return -1;
263 }
264
265 if (syncDisplay)
266 {
267 XSynchronize(xdisplay, True);
268 }
269
270 wxApp::ms_display = (WXDisplay*) xdisplay;
271
272 XSelectInput( xdisplay, XDefaultRootWindow(xdisplay), PropertyChangeMask);
273
274 wxSetDetectableAutoRepeat( TRUE );
275
276 if (!wxApp::Initialize())
277 return -1;
278
279 return 0;
280 }
281
282 int wxEntryInitGui()
283 {
284 int retValue = 0;
285
286 if ( !wxTheApp->OnInitGui() )
287 retValue = -1;
288
289 return retValue;
290 }
291
292
293 int wxEntry( int argc, char *argv[] )
294 {
295 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
296 // This seems to be necessary since there are 'rogue'
297 // objects present at this point (perhaps global objects?)
298 // Setting a checkpoint will ignore them as far as the
299 // memory checking facility is concerned.
300 // Of course you may argue that memory allocated in globals should be
301 // checked, but this is a reasonable compromise.
302 wxDebugContext::SetCheckpoint();
303 #endif
304 int err = wxEntryStart(argc, argv);
305 if (err)
306 return err;
307
308 if (!wxTheApp)
309 {
310 if (!wxApp::GetInitializerFunction())
311 {
312 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
313 return 0;
314 };
315
316 wxTheApp = (wxApp*) (* wxApp::GetInitializerFunction()) ();
317 };
318
319 if (!wxTheApp)
320 {
321 printf( "wxWindows error: wxTheApp == NULL\n" );
322 return 0;
323 };
324
325 wxTheApp->SetClassName(wxFileNameFromPath(argv[0]));
326 wxTheApp->SetAppName(wxFileNameFromPath(argv[0]));
327
328 // The command line may have been changed
329 // by stripping out -display etc.
330 if (g_newArgc > 0)
331 {
332 wxTheApp->argc = g_newArgc;
333 wxTheApp->argv = g_newArgv;
334 }
335 else
336 {
337 wxTheApp->argc = argc;
338 wxTheApp->argv = argv;
339 }
340 wxTheApp->m_showIconic = g_showIconic;
341 wxTheApp->m_initialSize = g_initialSize;
342
343 int retValue;
344 retValue = wxEntryInitGui();
345
346 // Here frames insert themselves automatically into wxTopLevelWindows by
347 // getting created in OnInit().
348 if ( retValue == 0 )
349 {
350 if ( !wxTheApp->OnInit() )
351 retValue = -1;
352 }
353
354 if ( retValue == 0 )
355 {
356 if (wxTheApp->Initialized()) retValue = wxTheApp->OnRun();
357 }
358
359 // flush the logged messages if any
360 wxLog *pLog = wxLog::GetActiveTarget();
361 if ( pLog != NULL && pLog->HasPendingMessages() )
362 pLog->Flush();
363
364 delete wxLog::SetActiveTarget(new wxLogStderr); // So dialog boxes aren't used
365 // for further messages
366
367 if (wxTheApp->GetTopWindow())
368 {
369 delete wxTheApp->GetTopWindow();
370 wxTheApp->SetTopWindow(NULL);
371 }
372
373 wxTheApp->DeletePendingObjects();
374
375 wxTheApp->OnExit();
376
377 wxApp::CleanUp();
378
379 return retValue;
380 };
381
382 // Static member initialization
383 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
384
385 wxApp::wxApp()
386 {
387 m_topWindow = NULL;
388 wxTheApp = this;
389 m_className = "";
390 m_wantDebugOutput = TRUE ;
391 m_appName = "";
392 argc = 0;
393 argv = NULL;
394 m_exitOnFrameDelete = TRUE;
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->GetClientWindow())
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->GetClientWindow())
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 // wxLogDebug( "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 win->SetFocus();
762 }
763 }
764
765 #if !wxUSE_NANOX
766 if (event->type == LeaveNotify || event->type == EnterNotify)
767 {
768 // Throw out NotifyGrab and NotifyUngrab
769 if (event->xcrossing.mode != NotifyNormal)
770 return FALSE;
771 }
772 #endif
773 wxMouseEvent wxevent;
774 wxTranslateMouseEvent(wxevent, win, window, event);
775 return win->GetEventHandler()->ProcessEvent( wxevent );
776 }
777 case FocusIn:
778 {
779 #if !wxUSE_NANOX
780 if ((event->xfocus.detail != NotifyPointer) &&
781 (event->xfocus.mode == NotifyNormal))
782 #endif
783 {
784 // wxLogDebug( "FocusIn from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
785 #if 0
786 wxString msg;
787 msg.Printf( "FocusIn from %s of type %s\n", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
788 printf(msg.c_str());
789 #endif
790
791 wxFocusEvent focusEvent(wxEVT_SET_FOCUS, win->GetId());
792 focusEvent.SetEventObject(win);
793 focusEvent.SetWindow( g_prevFocus );
794 g_prevFocus = NULL;
795
796 return win->GetEventHandler()->ProcessEvent(focusEvent);
797 }
798 return FALSE;
799 break;
800 }
801 case FocusOut:
802 {
803 #if !wxUSE_NANOX
804 if ((event->xfocus.detail != NotifyPointer) &&
805 (event->xfocus.mode == NotifyNormal))
806 #endif
807 {
808 // wxLogDebug( "FocusOut from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
809
810 wxFocusEvent focusEvent(wxEVT_KILL_FOCUS, win->GetId());
811 focusEvent.SetEventObject(win);
812 focusEvent.SetWindow( g_nextFocus );
813 g_nextFocus = NULL;
814 return win->GetEventHandler()->ProcessEvent(focusEvent);
815 }
816 return FALSE;
817 break;
818 }
819 default:
820 {
821 #ifdef __WXDEBUG__
822 //wxString eventName = wxGetXEventName(XEvent& event);
823 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
824 #endif
825 return FALSE;
826 break;
827 }
828 }
829 return FALSE;
830 }
831
832 // Returns TRUE if more time is needed.
833 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
834 // but ProcessIdle may be needed by apps, so is kept.
835 bool wxApp::ProcessIdle()
836 {
837 wxIdleEvent event;
838 event.SetEventObject(this);
839 ProcessEvent(event);
840
841 return event.MoreRequested();
842 }
843
844 void wxApp::ExitMainLoop()
845 {
846 if (m_mainLoop)
847 m_mainLoop->Exit(0);
848 }
849
850 // Is a message/event pending?
851 bool wxApp::Pending()
852 {
853 return wxEventLoop::GetActive()->Pending();
854 }
855
856 // Dispatch a message.
857 void wxApp::Dispatch()
858 {
859 wxEventLoop::GetActive()->Dispatch();
860 }
861
862 // This should be redefined in a derived class for
863 // handling property change events for XAtom IPC.
864 bool wxApp::HandlePropertyChange(WXEvent *event)
865 {
866 // by default do nothing special
867 // TODO: what to do for X11
868 // XtDispatchEvent((XEvent*) event);
869 return FALSE;
870 }
871
872 void wxApp::OnIdle(wxIdleEvent& event)
873 {
874 static bool s_inOnIdle = FALSE;
875
876 // Avoid recursion (via ProcessEvent default case)
877 if (s_inOnIdle)
878 return;
879
880 s_inOnIdle = TRUE;
881
882 // Resend in the main thread events which have been prepared in other
883 // threads
884 ProcessPendingEvents();
885
886 // 'Garbage' collection of windows deleted with Close()
887 DeletePendingObjects();
888
889 // Send OnIdle events to all windows
890 bool needMore = SendIdleEvents();
891
892 if (needMore)
893 event.RequestMore(TRUE);
894
895 s_inOnIdle = FALSE;
896 }
897
898 void wxWakeUpIdle()
899 {
900 // **** please implement me! ****
901 // Wake up the idle handler processor, even if it is in another thread...
902 }
903
904
905 // Send idle event to all top-level windows
906 bool wxApp::SendIdleEvents()
907 {
908 bool needMore = FALSE;
909
910 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
911 while (node)
912 {
913 wxWindow* win = node->GetData();
914 if (SendIdleEvents(win))
915 needMore = TRUE;
916 node = node->GetNext();
917 }
918
919 return needMore;
920 }
921
922 // Send idle event to window and all subwindows
923 bool wxApp::SendIdleEvents(wxWindow* win)
924 {
925 bool needMore = FALSE;
926
927 wxIdleEvent event;
928 event.SetEventObject(win);
929
930 win->GetEventHandler()->ProcessEvent(event);
931
932 if (event.MoreRequested())
933 needMore = TRUE;
934
935 wxNode* node = win->GetChildren().First();
936 while (node)
937 {
938 wxWindow* win = (wxWindow*) node->Data();
939 if (SendIdleEvents(win))
940 needMore = TRUE;
941
942 node = node->Next();
943 }
944
945 win->OnInternalIdle();
946
947 return needMore;
948 }
949
950 void wxApp::DeletePendingObjects()
951 {
952 wxNode *node = wxPendingDelete.First();
953 while (node)
954 {
955 wxObject *obj = (wxObject *)node->Data();
956
957 delete obj;
958
959 if (wxPendingDelete.Member(obj))
960 delete node;
961
962 // Deleting one object may have deleted other pending
963 // objects, so start from beginning of list again.
964 node = wxPendingDelete.First();
965 }
966 }
967
968 static void wxCalcPrecAndShift( unsigned long mask, int *shift, int *prec )
969 {
970 *shift = 0;
971 *prec = 0;
972
973 while (!(mask & 0x1))
974 {
975 (*shift)++;
976 mask >>= 1;
977 }
978
979 while (mask & 0x1)
980 {
981 (*prec)++;
982 mask >>= 1;
983 }
984 }
985
986 // Create display, and other initialization
987 bool wxApp::OnInitGui()
988 {
989 // Eventually this line will be removed, but for
990 // now we don't want to try popping up a dialog
991 // for error messages.
992 delete wxLog::SetActiveTarget(new wxLogStderr);
993
994 if (!wxAppBase::OnInitGui())
995 return FALSE;
996
997 GetMainColormap( wxApp::GetDisplay() );
998
999 m_maxRequestSize = XMaxRequestSize( (Display*) wxApp::GetDisplay() );
1000
1001 #if !wxUSE_NANOX
1002 // Get info about the current visual. It is enough
1003 // to do this once here unless we support different
1004 // visuals, displays and screens. Given that wxX11
1005 // mostly for embedded things, that is no real
1006 // limitation.
1007 Display *xdisplay = (Display*) wxApp::GetDisplay();
1008 int xscreen = DefaultScreen(xdisplay);
1009 Visual* xvisual = DefaultVisual(xdisplay,xscreen);
1010 int xdepth = DefaultDepth(xdisplay, xscreen);
1011
1012 XVisualInfo vinfo_template;
1013 vinfo_template.visual = xvisual;
1014 vinfo_template.visualid = XVisualIDFromVisual( xvisual );
1015 vinfo_template.depth = xdepth;
1016
1017 int nitem = 0;
1018 XVisualInfo *vi = XGetVisualInfo( xdisplay, VisualIDMask|VisualDepthMask, &vinfo_template, &nitem );
1019 wxASSERT_MSG( vi, wxT("No visual info") );
1020
1021 m_visualType = vi->visual->c_class;
1022 m_visualScreen = vi->screen;
1023
1024 m_visualRedMask = vi->red_mask;
1025 m_visualGreenMask = vi->green_mask;
1026 m_visualBlueMask = vi->blue_mask;
1027
1028 if (m_visualType != GrayScale && m_visualType != PseudoColor)
1029 {
1030 wxCalcPrecAndShift( m_visualRedMask, &m_visualRedShift, &m_visualRedPrec );
1031 wxCalcPrecAndShift( m_visualGreenMask, &m_visualGreenShift, &m_visualGreenPrec );
1032 wxCalcPrecAndShift( m_visualBlueMask, &m_visualBlueShift, &m_visualBluePrec );
1033 }
1034
1035 m_visualDepth = xdepth;
1036 if (xdepth == 16)
1037 xdepth = m_visualRedPrec + m_visualGreenPrec + m_visualBluePrec;
1038
1039 m_visualColormapSize = vi->colormap_size;
1040
1041 XFree( vi );
1042
1043 if (m_visualDepth > 8)
1044 return TRUE;
1045
1046 m_visualColormap = new XColor[m_visualColormapSize];
1047 XColor* colors = (XColor*) m_visualColormap;
1048
1049 for (int i = 0; i < m_visualColormapSize; i++)
1050 colors[i].pixel = i;
1051
1052 XQueryColors( xdisplay, DefaultColormap(xdisplay,xscreen), colors, m_visualColormapSize );
1053
1054 m_colorCube = (unsigned char*)malloc(32 * 32 * 32);
1055
1056 for (int r = 0; r < 32; r++)
1057 {
1058 for (int g = 0; g < 32; g++)
1059 {
1060 for (int b = 0; b < 32; b++)
1061 {
1062 int rr = (r << 3) | (r >> 2);
1063 int gg = (g << 3) | (g >> 2);
1064 int bb = (b << 3) | (b >> 2);
1065
1066 int index = -1;
1067
1068 if (colors)
1069 {
1070 int max = 3 * 65536;
1071
1072 for (int i = 0; i < m_visualColormapSize; i++)
1073 {
1074 int rdiff = ((rr << 8) - colors[i].red);
1075 int gdiff = ((gg << 8) - colors[i].green);
1076 int bdiff = ((bb << 8) - colors[i].blue);
1077 int sum = ABS (rdiff) + ABS (gdiff) + ABS (bdiff);
1078 if (sum < max)
1079 {
1080 index = i; max = sum;
1081 }
1082 }
1083 }
1084 else
1085 {
1086 // assume 8-bit true or static colors. this really exists
1087 index = (r >> (5 - m_visualRedPrec)) << m_visualRedShift;
1088 index |= (g >> (5 - m_visualGreenPrec)) << m_visualGreenShift;
1089 index |= (b >> (5 - m_visualBluePrec)) << m_visualBlueShift;
1090 }
1091 m_colorCube[ (r*1024) + (g*32) + b ] = index;
1092 }
1093 }
1094 }
1095 #endif
1096
1097 return TRUE;
1098 }
1099
1100 WXColormap wxApp::GetMainColormap(WXDisplay* display)
1101 {
1102 if (!display) /* Must be called first with non-NULL display */
1103 return m_mainColormap;
1104
1105 int defaultScreen = DefaultScreen((Display*) display);
1106 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
1107
1108 Colormap c = DefaultColormapOfScreen(screen);
1109
1110 if (!m_mainColormap)
1111 m_mainColormap = (WXColormap) c;
1112
1113 return (WXColormap) c;
1114 }
1115
1116 Window wxGetWindowParent(Window window)
1117 {
1118 wxASSERT_MSG( window, "invalid window" );
1119
1120 return (Window) 0;
1121
1122 Window parent, root = 0;
1123 #if wxUSE_NANOX
1124 int noChildren = 0;
1125 #else
1126 unsigned int noChildren = 0;
1127 #endif
1128 Window* children = NULL;
1129
1130 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
1131 int res = 1;
1132 #if !wxUSE_NANOX
1133 res =
1134 #endif
1135 XQueryTree((Display*) wxGetDisplay(), window, & root, & parent,
1136 & children, & noChildren);
1137 if (children)
1138 XFree(children);
1139 if (res)
1140 return parent;
1141 else
1142 return (Window) 0;
1143 }
1144
1145 void wxExit()
1146 {
1147 int retValue = 0;
1148 if (wxTheApp)
1149 retValue = wxTheApp->OnExit();
1150
1151 wxApp::CleanUp();
1152 /*
1153 * Exit in some platform-specific way. Not recommended that the app calls this:
1154 * only for emergencies.
1155 */
1156 exit(retValue);
1157 }
1158
1159 // Yield to other processes
1160
1161 bool wxApp::Yield(bool onlyIfNeeded)
1162 {
1163 bool s_inYield = FALSE;
1164
1165 if ( s_inYield )
1166 {
1167 if ( !onlyIfNeeded )
1168 {
1169 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1170 }
1171
1172 return FALSE;
1173 }
1174
1175 s_inYield = TRUE;
1176
1177 // Make sure we have an event loop object,
1178 // or Pending/Dispatch will fail
1179 wxEventLoop* eventLoop = wxEventLoop::GetActive();
1180 wxEventLoop* newEventLoop = NULL;
1181 if (!eventLoop)
1182 {
1183 newEventLoop = new wxEventLoop;
1184 wxEventLoop::SetActive(newEventLoop);
1185 }
1186
1187 while (wxTheApp && wxTheApp->Pending())
1188 wxTheApp->Dispatch();
1189
1190 #if wxUSE_TIMER
1191 wxTimer::NotifyTimers();
1192 #endif
1193 ProcessIdle();
1194
1195 if (newEventLoop)
1196 {
1197 wxEventLoop::SetActive(NULL);
1198 delete newEventLoop;
1199 }
1200
1201 s_inYield = FALSE;
1202
1203 return TRUE;
1204 }
1205
1206 void wxApp::OnAssert(const wxChar *file, int line, const wxChar *msg)
1207 {
1208 // While the GUI isn't working that well, just print out the
1209 // message.
1210 #if 1
1211 wxAppBase::OnAssert(file, line, msg);
1212 #else
1213 wxString msg2;
1214 msg2.Printf("At file %s:%d: %s", file, line, msg);
1215 wxLogDebug(msg2);
1216 #endif
1217 }
1218