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