1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "app.h"
19 #include "wx/gdicmn.h"
21 #include "wx/dialog.h"
23 #include "wx/module.h"
24 #include "wx/memory.h"
27 #include "wx/evtloop.h"
30 #include "wx/univ/theme.h"
31 #include "wx/univ/renderer.h"
34 #include "wx/thread.h"
37 #if wxUSE_WX_RESOURCES
38 #include "wx/resource.h"
41 #include "wx/x11/private.h"
45 //------------------------------------------------------------------------
47 //------------------------------------------------------------------------
49 extern wxList wxPendingDelete
;
51 wxHashTable
*wxWidgetHashTable
= NULL
;
52 wxHashTable
*wxClientWidgetHashTable
= NULL
;
54 wxApp
*wxTheApp
= NULL
;
56 // This is set within wxEntryStart -- too early on
57 // to put these in wxTheApp
58 static int g_newArgc
= 0;
59 static wxChar
** g_newArgv
= NULL
;
60 static bool g_showIconic
= FALSE
;
61 static wxSize g_initialSize
= wxDefaultSize
;
63 // This is required for wxFocusEvent::SetWindow(). It will only
64 // work for focus events which we provoke ourselves (by calling
65 // SetFocus()). It will not work for those events, which X11
67 static wxWindow
*g_nextFocus
= NULL
;
68 static wxWindow
*g_prevFocus
= NULL
;
70 //------------------------------------------------------------------------
72 //------------------------------------------------------------------------
75 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
77 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
79 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
81 // just forward to the default handler for now
82 if (gs_pfnXErrorHandler
)
83 return gs_pfnXErrorHandler(dpy
, xevent
);
89 //------------------------------------------------------------------------
91 //------------------------------------------------------------------------
93 long wxApp::sm_lastMessageTime
= 0;
94 WXDisplay
*wxApp::ms_display
= NULL
;
96 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
98 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
99 EVT_IDLE(wxApp::OnIdle
)
102 bool wxApp::Initialize()
104 wxClassInfo::InitializeClasses();
106 // GL: I'm annoyed ... I don't know where to put this and I don't want to
107 // create a module for that as it's part of the core.
109 wxPendingEventsLocker
= new wxCriticalSection();
112 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
113 wxTheColourDatabase
->Initialize();
115 wxInitializeStockLists();
116 wxInitializeStockObjects();
118 #if wxUSE_WX_RESOURCES
119 wxInitializeResourceSystem();
122 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
123 wxClientWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
125 wxModule::RegisterModules();
126 if (!wxModule::InitializeModules()) return FALSE
;
131 void wxApp::CleanUp()
137 delete wxWidgetHashTable
;
138 wxWidgetHashTable
= NULL
;
139 delete wxClientWidgetHashTable
;
140 wxClientWidgetHashTable
= NULL
;
142 wxModule::CleanUpModules();
144 #if wxUSE_WX_RESOURCES
145 wxCleanUpResourceSystem();
148 delete wxTheColourDatabase
;
149 wxTheColourDatabase
= NULL
;
151 wxDeleteStockObjects();
153 wxDeleteStockLists();
158 wxClassInfo::CleanUpClasses();
161 delete wxPendingEvents
;
162 delete wxPendingEventsLocker
;
165 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
166 // At this point we want to check if there are any memory
167 // blocks that aren't part of the wxDebugContext itself,
168 // as a special case. Then when dumping we need to ignore
169 // wxDebugContext, too.
170 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
172 wxLogDebug("There were memory leaks.");
173 wxDebugContext::Dump();
174 wxDebugContext::PrintStatistics();
178 // do it as the very last thing because everything else can log messages
179 wxLog::DontCreateOnDemand();
180 // do it as the very last thing because everything else can log messages
181 delete wxLog::SetActiveTarget(NULL
);
184 // NB: argc and argv may be changed here, pass by reference!
185 int wxEntryStart( int& argc
, char *argv
[] )
189 // install the X error handler
190 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
192 #endif // __WXDEBUG__
194 wxString displayName
;
195 bool syncDisplay
= FALSE
;
197 // Parse the arguments.
198 // We can't use wxCmdLineParser or OnInitCmdLine and friends because
199 // we have to create the Display earlier. If we can find a way to
200 // use the wxAppBase API then I'll be quite happy to change it.
201 g_newArgv
= new wxChar
*[argc
];
204 for (i
= 0; i
< argc
; i
++)
206 wxString
arg(argv
[i
]);
207 if (arg
== wxT("-display"))
212 displayName
= argv
[i
];
216 else if (arg
== wxT("-geometry"))
221 wxString windowGeometry
= argv
[i
];
223 if (wxSscanf(windowGeometry
.c_str(), _T("%dx%d"), &w
, &h
) != 2)
225 wxLogError(_("Invalid geometry specification '%s'"), windowGeometry
.c_str());
229 g_initialSize
= wxSize(w
, h
);
234 else if (arg
== wxT("-sync"))
239 else if (arg
== wxT("-iconic"))
246 // Not eaten by wxWindows, so pass through
247 g_newArgv
[g_newArgc
] = argv
[i
];
251 Display
* xdisplay
= NULL
;
252 if (displayName
.IsEmpty())
253 xdisplay
= XOpenDisplay(NULL
);
255 xdisplay
= XOpenDisplay((char*) displayName
.c_str());
259 wxLogError( _("wxWindows could not open display. Exiting.") );
265 XSynchronize(xdisplay
, True
);
268 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
270 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
272 wxSetDetectableAutoRepeat( TRUE
);
274 if (!wxApp::Initialize())
284 if ( !wxTheApp
->OnInitGui() )
291 int wxEntry( int argc
, char *argv
[] )
293 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
294 // This seems to be necessary since there are 'rogue'
295 // objects present at this point (perhaps global objects?)
296 // Setting a checkpoint will ignore them as far as the
297 // memory checking facility is concerned.
298 // Of course you may argue that memory allocated in globals should be
299 // checked, but this is a reasonable compromise.
300 wxDebugContext::SetCheckpoint();
302 int err
= wxEntryStart(argc
, argv
);
308 if (!wxApp::GetInitializerFunction())
310 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
314 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
319 printf( "wxWindows error: wxTheApp == NULL\n" );
323 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
324 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
326 // The command line may have been changed
327 // by stripping out -display etc.
330 wxTheApp
->argc
= g_newArgc
;
331 wxTheApp
->argv
= g_newArgv
;
335 wxTheApp
->argc
= argc
;
336 wxTheApp
->argv
= argv
;
338 wxTheApp
->m_showIconic
= g_showIconic
;
339 wxTheApp
->m_initialSize
= g_initialSize
;
342 retValue
= wxEntryInitGui();
344 // Here frames insert themselves automatically into wxTopLevelWindows by
345 // getting created in OnInit().
348 if ( !wxTheApp
->OnInit() )
354 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
357 // flush the logged messages if any
358 wxLog
*pLog
= wxLog::GetActiveTarget();
359 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
362 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
363 // for further messages
365 if (wxTheApp
->GetTopWindow())
367 delete wxTheApp
->GetTopWindow();
368 wxTheApp
->SetTopWindow(NULL
);
371 wxTheApp
->DeletePendingObjects();
380 // Static member initialization
381 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
388 m_wantDebugOutput
= TRUE
;
392 m_exitOnFrameDelete
= TRUE
;
393 m_mainColormap
= (WXColormap
) NULL
;
394 m_topLevelWidget
= (WXWindow
) NULL
;
395 m_maxRequestSize
= 0;
397 m_showIconic
= FALSE
;
398 m_initialSize
= wxDefaultSize
;
401 bool wxApp::Initialized()
409 int wxApp::MainLoop()
412 m_mainLoop
= new wxEventLoop
;
414 rt
= m_mainLoop
->Run();
422 //-----------------------------------------------------------------------
423 // X11 predicate function for exposure compression
424 //-----------------------------------------------------------------------
429 Bool found_non_matching
;
432 static Bool
expose_predicate (Display
*display
, XEvent
*xevent
, XPointer arg
)
434 wxExposeInfo
*info
= (wxExposeInfo
*) arg
;
436 if (info
->found_non_matching
)
439 if (xevent
->xany
.type
!= Expose
)
441 info
->found_non_matching
= TRUE
;
445 if (xevent
->xexpose
.window
!= info
->window
)
447 info
->found_non_matching
= TRUE
;
456 //-----------------------------------------------------------------------
457 // Processes an X event, returning TRUE if the event was processed.
458 //-----------------------------------------------------------------------
460 bool wxApp::ProcessXEvent(WXEvent
* _event
)
462 XEvent
* event
= (XEvent
*) _event
;
464 wxWindow
* win
= NULL
;
465 Window window
= XEventGetWindow(event
);
466 Window actualWindow
= window
;
468 // Find the first wxWindow that corresponds to this event window
469 // Because we're receiving events after a window
470 // has been destroyed, assume a 1:1 match between
471 // Window and wxWindow, so if it's not in the table,
472 // it must have been destroyed.
474 win
= wxGetWindowFromTable(window
);
477 #if wxUSE_TWO_WINDOWS
478 win
= wxGetClientWindowFromTable(window
);
485 wxString windowClass
= win
->GetClassInfo()->GetClassName();
492 #if wxUSE_TWO_WINDOWS
493 if (event
->xexpose
.window
!= (Window
)win
->GetClientWindow())
497 info
.window
= event
->xexpose
.window
;
498 info
.found_non_matching
= FALSE
;
499 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event
, expose_predicate
, (XPointer
) &info
))
501 // Don't worry about optimizing redrawing the border etc.
503 win
->NeedUpdateNcAreaInIdle();
508 win
->GetUpdateRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
509 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
511 win
->GetClearRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
512 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
517 info
.window
= event
->xexpose
.window
;
518 info
.found_non_matching
= FALSE
;
519 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event
, expose_predicate
, (XPointer
) &info
))
521 win
->GetUpdateRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
522 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
524 win
->GetClearRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
525 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
528 if (win
->GetMainWindow() == win
->GetClientWindow())
529 win
->NeedUpdateNcAreaInIdle();
531 // Only erase background, paint in idle time.
532 win
->SendEraseEvents();
542 // wxLogDebug( "GraphicsExpose from %s", win->GetName().c_str(),
543 // event->xgraphicsexpose.x, event->xgraphicsexpose.y,
544 // event->xgraphicsexpose.width, event->xgraphicsexpose.height);
546 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
547 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
549 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
550 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
552 if (event
->xgraphicsexpose
.count
== 0)
554 // Only erase background, paint in idle time.
555 win
->SendEraseEvents();
565 if (!win
->IsEnabled())
568 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
569 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
571 // wxLogDebug( "OnKey from %s", win->GetName().c_str() );
573 // We didn't process wxEVT_KEY_DOWN, so send wxEVT_CHAR
574 if (win
->GetEventHandler()->ProcessEvent( keyEvent
))
577 keyEvent
.SetEventType(wxEVT_CHAR
);
578 if (win
->GetEventHandler()->ProcessEvent( keyEvent
))
581 if ( (keyEvent
.m_keyCode
== WXK_TAB
) &&
582 win
->GetParent() && (win
->GetParent()->HasFlag( wxTAB_TRAVERSAL
)) )
584 wxNavigationKeyEvent new_event
;
585 new_event
.SetEventObject( win
->GetParent() );
586 /* GDK reports GDK_ISO_Left_Tab for SHIFT-TAB */
587 new_event
.SetDirection( (keyEvent
.m_keyCode
== WXK_TAB
) );
588 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
589 new_event
.SetWindowChange( keyEvent
.ControlDown() );
590 new_event
.SetCurrentFocus( win
);
591 return win
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
598 if (!win
->IsEnabled())
601 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
602 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
604 return win
->GetEventHandler()->ProcessEvent( keyEvent
);
606 case ConfigureNotify
:
609 if (event
->update
.utype
== GR_UPDATE_SIZE
)
612 if (win
->IsTopLevel() && win
->IsShown())
614 wxTopLevelWindowX11
*tlw
= (wxTopLevelWindowX11
*) win
;
615 tlw
->SetNeedResizeInIdle();
619 wxSizeEvent
sizeEvent( wxSize(XConfigureEventGetWidth(event
), XConfigureEventGetHeight(event
)), win
->GetId() );
620 sizeEvent
.SetEventObject( win
);
622 return win
->GetEventHandler()->ProcessEvent( sizeEvent
);
631 //wxLogDebug("PropertyNotify: %s", windowClass.c_str());
632 return HandlePropertyChange(_event
);
636 if (!win
->IsEnabled())
639 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);
640 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);
642 if (event
->xclient
.message_type
== wm_protocols
)
644 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
655 printf( "destroy from %s\n", win
->GetName().c_str() );
660 printf( "create from %s\n", win
->GetName().c_str() );
665 printf( "map request from %s\n", win
->GetName().c_str() );
670 printf( "resize request from %s\n", win
->GetName().c_str() );
672 Display
*disp
= (Display
*) wxGetDisplay();
677 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
679 wxSize sz
= win
->GetSize();
680 wxSizeEvent
sizeEvent(sz
, win
->GetId());
681 sizeEvent
.SetEventObject(win
);
683 return win
->GetEventHandler()->ProcessEvent( sizeEvent
);
688 case GR_EVENT_TYPE_CLOSE_REQ
:
705 if (!win
->IsEnabled())
708 // Here we check if the top level window is
709 // disabled, which is one aspect of modality.
711 while (tlw
&& !tlw
->IsTopLevel())
712 tlw
= tlw
->GetParent();
713 if (tlw
&& !tlw
->IsEnabled())
716 if (event
->type
== ButtonPress
)
718 if ((win
!= wxWindow::FindFocus()) && win
->AcceptsFocus())
720 // This might actually be done in wxWindow::SetFocus()
721 // and not here. TODO.
722 g_prevFocus
= wxWindow::FindFocus();
730 if (event
->type
== LeaveNotify
|| event
->type
== EnterNotify
)
732 // Throw out NotifyGrab and NotifyUngrab
733 if (event
->xcrossing
.mode
!= NotifyNormal
)
737 wxMouseEvent wxevent
;
738 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
739 return win
->GetEventHandler()->ProcessEvent( wxevent
);
744 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
745 (event
->xfocus
.mode
== NotifyNormal
))
748 // wxLogDebug( "FocusIn from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
750 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
751 focusEvent
.SetEventObject(win
);
752 focusEvent
.SetWindow( g_prevFocus
);
755 return win
->GetEventHandler()->ProcessEvent(focusEvent
);
763 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
764 (event
->xfocus
.mode
== NotifyNormal
))
767 // wxLogDebug( "FocusOut from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
769 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
770 focusEvent
.SetEventObject(win
);
771 focusEvent
.SetWindow( g_nextFocus
);
773 return win
->GetEventHandler()->ProcessEvent(focusEvent
);
781 //wxString eventName = wxGetXEventName(XEvent& event);
782 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
791 // Returns TRUE if more time is needed.
792 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
793 // but ProcessIdle may be needed by apps, so is kept.
794 bool wxApp::ProcessIdle()
797 event
.SetEventObject(this);
800 return event
.MoreRequested();
803 void wxApp::ExitMainLoop()
809 // Is a message/event pending?
810 bool wxApp::Pending()
812 return wxEventLoop::GetActive()->Pending();
815 // Dispatch a message.
816 void wxApp::Dispatch()
818 wxEventLoop::GetActive()->Dispatch();
821 // This should be redefined in a derived class for
822 // handling property change events for XAtom IPC.
823 bool wxApp::HandlePropertyChange(WXEvent
*event
)
825 // by default do nothing special
826 // TODO: what to do for X11
827 // XtDispatchEvent((XEvent*) event);
831 void wxApp::OnIdle(wxIdleEvent
& event
)
833 static bool s_inOnIdle
= FALSE
;
835 // Avoid recursion (via ProcessEvent default case)
841 // Resend in the main thread events which have been prepared in other
843 ProcessPendingEvents();
845 // 'Garbage' collection of windows deleted with Close()
846 DeletePendingObjects();
848 // Send OnIdle events to all windows
849 bool needMore
= SendIdleEvents();
852 event
.RequestMore(TRUE
);
859 // **** please implement me! ****
860 // Wake up the idle handler processor, even if it is in another thread...
864 // Send idle event to all top-level windows
865 bool wxApp::SendIdleEvents()
867 bool needMore
= FALSE
;
869 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
872 wxWindow
* win
= node
->GetData();
873 if (SendIdleEvents(win
))
875 node
= node
->GetNext();
881 // Send idle event to window and all subwindows
882 bool wxApp::SendIdleEvents(wxWindow
* win
)
884 bool needMore
= FALSE
;
887 event
.SetEventObject(win
);
889 win
->GetEventHandler()->ProcessEvent(event
);
891 win
->OnInternalIdle();
893 if (event
.MoreRequested())
896 wxNode
* node
= win
->GetChildren().First();
899 wxWindow
* win
= (wxWindow
*) node
->Data();
900 if (SendIdleEvents(win
))
909 void wxApp::DeletePendingObjects()
911 wxNode
*node
= wxPendingDelete
.First();
914 wxObject
*obj
= (wxObject
*)node
->Data();
918 if (wxPendingDelete
.Member(obj
))
921 // Deleting one object may have deleted other pending
922 // objects, so start from beginning of list again.
923 node
= wxPendingDelete
.First();
927 // Create display, and other initialization
928 bool wxApp::OnInitGui()
930 // Eventually this line will be removed, but for
931 // now we don't want to try popping up a dialog
932 // for error messages.
933 delete wxLog::SetActiveTarget(new wxLogStderr
);
935 if (!wxAppBase::OnInitGui())
938 GetMainColormap( wxApp::GetDisplay() );
940 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
945 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
947 if (!display
) /* Must be called first with non-NULL display */
948 return m_mainColormap
;
950 int defaultScreen
= DefaultScreen((Display
*) display
);
951 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
953 Colormap c
= DefaultColormapOfScreen(screen
);
956 m_mainColormap
= (WXColormap
) c
;
958 return (WXColormap
) c
;
961 Window
wxGetWindowParent(Window window
)
963 wxASSERT_MSG( window
, "invalid window" );
967 Window parent
, root
= 0;
971 unsigned int noChildren
= 0;
973 Window
* children
= NULL
;
975 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
980 XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
981 & children
, & noChildren
);
994 retValue
= wxTheApp
->OnExit();
998 * Exit in some platform-specific way. Not recommended that the app calls this:
999 * only for emergencies.
1004 // Yield to other processes
1006 bool wxApp::Yield(bool onlyIfNeeded
)
1008 bool s_inYield
= FALSE
;
1012 if ( !onlyIfNeeded
)
1014 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1022 // Make sure we have an event loop object,
1023 // or Pending/Dispatch will fail
1024 wxEventLoop
* eventLoop
= wxEventLoop::GetActive();
1025 wxEventLoop
* newEventLoop
= NULL
;
1028 newEventLoop
= new wxEventLoop
;
1029 wxEventLoop::SetActive(newEventLoop
);
1032 while (wxTheApp
&& wxTheApp
->Pending())
1033 wxTheApp
->Dispatch();
1036 wxTimer::NotifyTimers();
1042 wxEventLoop::SetActive(NULL
);
1043 delete newEventLoop
;
1051 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
1053 // While the GUI isn't working that well, just print out the
1056 wxAppBase::OnAssert(file
, line
, msg
);
1059 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);