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
;
53 wxApp
*wxTheApp
= NULL
;
55 // This is set within wxEntryStart -- too early on
56 // to put these in wxTheApp
57 static int g_newArgc
= 0;
58 static wxChar
** g_newArgv
= NULL
;
59 static bool g_showIconic
= FALSE
;
60 static wxSize g_initialSize
= wxDefaultSize
;
62 // This is required for wxFocusEvent::SetWindow(). It will only
63 // work for focus events which we provoke ourselves (by calling
64 // SetFocus()). It will not work for those events, which X11
66 static wxWindow
*g_nextFocus
= NULL
;
67 static wxWindow
*g_prevFocus
= NULL
;
69 //------------------------------------------------------------------------
71 //------------------------------------------------------------------------
74 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
76 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
78 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
80 // just forward to the default handler for now
81 if (gs_pfnXErrorHandler
)
82 return gs_pfnXErrorHandler(dpy
, xevent
);
88 //------------------------------------------------------------------------
90 //------------------------------------------------------------------------
92 long wxApp::sm_lastMessageTime
= 0;
93 WXDisplay
*wxApp::ms_display
= NULL
;
95 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
97 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
98 EVT_IDLE(wxApp::OnIdle
)
101 bool wxApp::Initialize()
103 wxClassInfo::InitializeClasses();
105 // GL: I'm annoyed ... I don't know where to put this and I don't want to
106 // create a module for that as it's part of the core.
108 wxPendingEventsLocker
= new wxCriticalSection();
111 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
112 wxTheColourDatabase
->Initialize();
114 wxInitializeStockLists();
115 wxInitializeStockObjects();
117 #if wxUSE_WX_RESOURCES
118 wxInitializeResourceSystem();
121 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
123 wxModule::RegisterModules();
124 if (!wxModule::InitializeModules()) return FALSE
;
129 void wxApp::CleanUp()
135 delete wxWidgetHashTable
;
136 wxWidgetHashTable
= NULL
;
138 wxModule::CleanUpModules();
140 #if wxUSE_WX_RESOURCES
141 wxCleanUpResourceSystem();
144 delete wxTheColourDatabase
;
145 wxTheColourDatabase
= NULL
;
147 wxDeleteStockObjects();
149 wxDeleteStockLists();
154 wxClassInfo::CleanUpClasses();
157 delete wxPendingEvents
;
158 delete wxPendingEventsLocker
;
161 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
162 // At this point we want to check if there are any memory
163 // blocks that aren't part of the wxDebugContext itself,
164 // as a special case. Then when dumping we need to ignore
165 // wxDebugContext, too.
166 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
168 wxLogDebug("There were memory leaks.");
169 wxDebugContext::Dump();
170 wxDebugContext::PrintStatistics();
174 // do it as the very last thing because everything else can log messages
175 wxLog::DontCreateOnDemand();
176 // do it as the very last thing because everything else can log messages
177 delete wxLog::SetActiveTarget(NULL
);
180 // NB: argc and argv may be changed here, pass by reference!
181 int wxEntryStart( int& argc
, char *argv
[] )
185 // install the X error handler
186 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
188 #endif // __WXDEBUG__
190 wxString displayName
;
191 bool syncDisplay
= FALSE
;
193 // Parse the arguments.
194 // We can't use wxCmdLineParser or OnInitCmdLine and friends because
195 // we have to create the Display earlier. If we can find a way to
196 // use the wxAppBase API then I'll be quite happy to change it.
197 g_newArgv
= new wxChar
*[argc
];
200 for (i
= 0; i
< argc
; i
++)
202 wxString
arg(argv
[i
]);
203 if (arg
== wxT("-display"))
208 displayName
= argv
[i
];
212 else if (arg
== wxT("-geometry"))
217 wxString windowGeometry
= argv
[i
];
219 if (wxSscanf(windowGeometry
.c_str(), _T("%dx%d"), &w
, &h
) != 2)
221 wxLogError(_("Invalid geometry specification '%s'"), windowGeometry
.c_str());
225 g_initialSize
= wxSize(w
, h
);
230 else if (arg
== wxT("-sync"))
235 else if (arg
== wxT("-iconic"))
242 // Not eaten by wxWindows, so pass through
243 g_newArgv
[g_newArgc
] = argv
[i
];
247 Display
* xdisplay
= NULL
;
248 if (displayName
.IsEmpty())
249 xdisplay
= XOpenDisplay(NULL
);
251 xdisplay
= XOpenDisplay((char*) displayName
.c_str());
255 wxLogError( _("wxWindows could not open display. Exiting.") );
261 XSynchronize(xdisplay
, True
);
264 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
266 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
268 wxSetDetectableAutoRepeat( TRUE
);
270 if (!wxApp::Initialize())
280 if ( !wxTheApp
->OnInitGui() )
287 int wxEntry( int argc
, char *argv
[] )
289 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
290 // This seems to be necessary since there are 'rogue'
291 // objects present at this point (perhaps global objects?)
292 // Setting a checkpoint will ignore them as far as the
293 // memory checking facility is concerned.
294 // Of course you may argue that memory allocated in globals should be
295 // checked, but this is a reasonable compromise.
296 wxDebugContext::SetCheckpoint();
298 int err
= wxEntryStart(argc
, argv
);
304 if (!wxApp::GetInitializerFunction())
306 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
310 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
315 printf( "wxWindows error: wxTheApp == NULL\n" );
319 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
320 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
322 // The command line may have been changed
323 // by stripping out -display etc.
326 wxTheApp
->argc
= g_newArgc
;
327 wxTheApp
->argv
= g_newArgv
;
331 wxTheApp
->argc
= argc
;
332 wxTheApp
->argv
= argv
;
334 wxTheApp
->m_showIconic
= g_showIconic
;
335 wxTheApp
->m_initialSize
= g_initialSize
;
338 retValue
= wxEntryInitGui();
340 // Here frames insert themselves automatically into wxTopLevelWindows by
341 // getting created in OnInit().
344 if ( !wxTheApp
->OnInit() )
350 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
353 // flush the logged messages if any
354 wxLog
*pLog
= wxLog::GetActiveTarget();
355 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
358 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
359 // for further messages
361 if (wxTheApp
->GetTopWindow())
363 delete wxTheApp
->GetTopWindow();
364 wxTheApp
->SetTopWindow(NULL
);
367 wxTheApp
->DeletePendingObjects();
376 // Static member initialization
377 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
384 m_wantDebugOutput
= TRUE
;
388 m_exitOnFrameDelete
= TRUE
;
389 m_mainColormap
= (WXColormap
) NULL
;
390 m_topLevelWidget
= (WXWindow
) NULL
;
391 m_maxRequestSize
= 0;
393 m_showIconic
= FALSE
;
394 m_initialSize
= wxDefaultSize
;
397 bool wxApp::Initialized()
405 int wxApp::MainLoop()
408 m_mainLoop
= new wxEventLoop
;
410 rt
= m_mainLoop
->Run();
418 //-----------------------------------------------------------------------
419 // X11 predicate function for exposure compression
420 //-----------------------------------------------------------------------
425 Bool found_non_matching
;
428 static Bool
expose_predicate (Display
*display
, XEvent
*xevent
, XPointer arg
)
430 wxExposeInfo
*info
= (wxExposeInfo
*) arg
;
432 if (info
->found_non_matching
)
435 if (xevent
->xany
.type
!= Expose
)
437 info
->found_non_matching
= TRUE
;
441 if (xevent
->xexpose
.window
!= info
->window
)
443 info
->found_non_matching
= TRUE
;
452 //-----------------------------------------------------------------------
453 // Processes an X event, returning TRUE if the event was processed.
454 //-----------------------------------------------------------------------
456 bool wxApp::ProcessXEvent(WXEvent
* _event
)
458 XEvent
* event
= (XEvent
*) _event
;
460 wxWindow
* win
= NULL
;
461 Window window
= XEventGetWindow(event
);
462 Window actualWindow
= window
;
464 // Find the first wxWindow that corresponds to this event window
465 // Because we're receiving events after a window
466 // has been destroyed, assume a 1:1 match between
467 // Window and wxWindow, so if it's not in the table,
468 // it must have been destroyed.
470 win
= wxGetWindowFromTable(window
);
475 wxString windowClass
= win
->GetClassInfo()->GetClassName();
482 //wxLogDebug("Expose: %s", windowClass.c_str());
483 win
->GetUpdateRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
484 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
486 win
->GetClearRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
487 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
492 info
.window
= event
->xexpose
.window
;
493 info
.found_non_matching
= FALSE
;
494 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event
, expose_predicate
, (XPointer
) &info
))
496 win
->GetUpdateRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
497 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
499 win
->GetClearRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
500 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
504 // Only erase background, paint in idle time.
505 win
->SendEraseEvents();
513 // wxLogDebug( "GraphicsExpose from %s", win->GetName().c_str(),
514 // event->xgraphicsexpose.x, event->xgraphicsexpose.y,
515 // event->xgraphicsexpose.width, event->xgraphicsexpose.height);
517 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
518 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
520 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
521 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
523 if (event
->xgraphicsexpose
.count
== 0)
525 // Only erase background, paint in idle time.
526 win
->SendEraseEvents();
536 if (!win
->IsEnabled())
539 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
540 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
542 // wxLogDebug( "OnKey from %s", win->GetName().c_str() );
544 // We didn't process wxEVT_KEY_DOWN, so send wxEVT_CHAR
545 if (win
->GetEventHandler()->ProcessEvent( keyEvent
))
548 keyEvent
.SetEventType(wxEVT_CHAR
);
549 if (win
->GetEventHandler()->ProcessEvent( keyEvent
))
552 if ( (keyEvent
.m_keyCode
== WXK_TAB
) &&
553 win
->GetParent() && (win
->GetParent()->HasFlag( wxTAB_TRAVERSAL
)) )
555 wxNavigationKeyEvent new_event
;
556 new_event
.SetEventObject( win
->GetParent() );
557 /* GDK reports GDK_ISO_Left_Tab for SHIFT-TAB */
558 new_event
.SetDirection( (keyEvent
.m_keyCode
== WXK_TAB
) );
559 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
560 new_event
.SetWindowChange( keyEvent
.ControlDown() );
561 new_event
.SetCurrentFocus( win
);
562 return win
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
569 if (!win
->IsEnabled())
572 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
573 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
575 return win
->GetEventHandler()->ProcessEvent( keyEvent
);
577 case ConfigureNotify
:
580 if (event
->update
.utype
== GR_UPDATE_SIZE
)
583 //wxLogDebug("ConfigureNotify: %s", windowClass.c_str());
584 if (win
->IsTopLevel() && win
->IsShown())
586 wxTopLevelWindowX11
*tlw
= (wxTopLevelWindowX11
*) win
;
587 tlw
->SetNeedResizeInIdle();
591 wxSizeEvent
sizeEvent( wxSize(XConfigureEventGetWidth(event
), XConfigureEventGetHeight(event
)), win
->GetId() );
592 sizeEvent
.SetEventObject( win
);
594 return win
->GetEventHandler()->ProcessEvent( sizeEvent
);
603 //wxLogDebug("PropertyNotify: %s", windowClass.c_str());
604 return HandlePropertyChange(_event
);
608 if (!win
->IsEnabled())
611 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);
612 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);
614 if (event
->xclient
.message_type
== wm_protocols
)
616 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
627 printf( "destroy from %s\n", win
->GetName().c_str() );
632 printf( "create from %s\n", win
->GetName().c_str() );
637 printf( "map request from %s\n", win
->GetName().c_str() );
642 printf( "resize request from %s\n", win
->GetName().c_str() );
644 Display
*disp
= (Display
*) wxGetDisplay();
649 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
651 wxSize sz
= win
->GetSize();
652 wxSizeEvent
sizeEvent(sz
, win
->GetId());
653 sizeEvent
.SetEventObject(win
);
655 return win
->GetEventHandler()->ProcessEvent( sizeEvent
);
660 case GR_EVENT_TYPE_CLOSE_REQ
:
677 if (!win
->IsEnabled())
680 // Here we check if the top level window is
681 // disabled, which is one aspect of modality.
683 while (tlw
&& !tlw
->IsTopLevel())
684 tlw
= tlw
->GetParent();
685 if (tlw
&& !tlw
->IsEnabled())
688 if (event
->type
== ButtonPress
)
690 if ((win
!= wxWindow::FindFocus()) && win
->AcceptsFocus())
692 // This might actually be done in wxWindow::SetFocus()
693 // and not here. TODO.
694 g_prevFocus
= wxWindow::FindFocus();
702 if (event
->type
== LeaveNotify
|| event
->type
== EnterNotify
)
704 // Throw out NotifyGrab and NotifyUngrab
705 if (event
->xcrossing
.mode
!= NotifyNormal
)
709 wxMouseEvent wxevent
;
710 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
711 return win
->GetEventHandler()->ProcessEvent( wxevent
);
716 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
717 (event
->xfocus
.mode
== NotifyNormal
))
720 // wxLogDebug( "FocusIn from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
722 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
723 focusEvent
.SetEventObject(win
);
724 focusEvent
.SetWindow( g_prevFocus
);
727 return win
->GetEventHandler()->ProcessEvent(focusEvent
);
735 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
736 (event
->xfocus
.mode
== NotifyNormal
))
739 // wxLogDebug( "FocusOut from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
741 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
742 focusEvent
.SetEventObject(win
);
743 focusEvent
.SetWindow( g_nextFocus
);
745 return win
->GetEventHandler()->ProcessEvent(focusEvent
);
753 //wxString eventName = wxGetXEventName(XEvent& event);
754 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
763 // Returns TRUE if more time is needed.
764 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
765 // but ProcessIdle may be needed by apps, so is kept.
766 bool wxApp::ProcessIdle()
769 event
.SetEventObject(this);
772 return event
.MoreRequested();
775 void wxApp::ExitMainLoop()
781 // Is a message/event pending?
782 bool wxApp::Pending()
784 return wxEventLoop::GetActive()->Pending();
787 // Dispatch a message.
788 void wxApp::Dispatch()
790 wxEventLoop::GetActive()->Dispatch();
793 // This should be redefined in a derived class for
794 // handling property change events for XAtom IPC.
795 bool wxApp::HandlePropertyChange(WXEvent
*event
)
797 // by default do nothing special
798 // TODO: what to do for X11
799 // XtDispatchEvent((XEvent*) event);
803 void wxApp::OnIdle(wxIdleEvent
& event
)
805 static bool s_inOnIdle
= FALSE
;
807 // Avoid recursion (via ProcessEvent default case)
813 // Resend in the main thread events which have been prepared in other
815 ProcessPendingEvents();
817 // 'Garbage' collection of windows deleted with Close()
818 DeletePendingObjects();
820 // Send OnIdle events to all windows
821 bool needMore
= SendIdleEvents();
824 event
.RequestMore(TRUE
);
831 // **** please implement me! ****
832 // Wake up the idle handler processor, even if it is in another thread...
836 // Send idle event to all top-level windows
837 bool wxApp::SendIdleEvents()
839 bool needMore
= FALSE
;
841 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
844 wxWindow
* win
= node
->GetData();
845 if (SendIdleEvents(win
))
847 node
= node
->GetNext();
853 // Send idle event to window and all subwindows
854 bool wxApp::SendIdleEvents(wxWindow
* win
)
856 bool needMore
= FALSE
;
859 event
.SetEventObject(win
);
861 win
->GetEventHandler()->ProcessEvent(event
);
863 win
->OnInternalIdle();
865 if (event
.MoreRequested())
868 wxNode
* node
= win
->GetChildren().First();
871 wxWindow
* win
= (wxWindow
*) node
->Data();
872 if (SendIdleEvents(win
))
881 void wxApp::DeletePendingObjects()
883 wxNode
*node
= wxPendingDelete
.First();
886 wxObject
*obj
= (wxObject
*)node
->Data();
890 if (wxPendingDelete
.Member(obj
))
893 // Deleting one object may have deleted other pending
894 // objects, so start from beginning of list again.
895 node
= wxPendingDelete
.First();
899 // Create display, and other initialization
900 bool wxApp::OnInitGui()
902 // Eventually this line will be removed, but for
903 // now we don't want to try popping up a dialog
904 // for error messages.
905 delete wxLog::SetActiveTarget(new wxLogStderr
);
907 if (!wxAppBase::OnInitGui())
910 GetMainColormap( wxApp::GetDisplay() );
912 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
917 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
919 if (!display
) /* Must be called first with non-NULL display */
920 return m_mainColormap
;
922 int defaultScreen
= DefaultScreen((Display
*) display
);
923 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
925 Colormap c
= DefaultColormapOfScreen(screen
);
928 m_mainColormap
= (WXColormap
) c
;
930 return (WXColormap
) c
;
933 Window
wxGetWindowParent(Window window
)
935 wxASSERT_MSG( window
, "invalid window" );
939 Window parent
, root
= 0;
943 unsigned int noChildren
= 0;
945 Window
* children
= NULL
;
947 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
952 XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
953 & children
, & noChildren
);
966 retValue
= wxTheApp
->OnExit();
970 * Exit in some platform-specific way. Not recommended that the app calls this:
971 * only for emergencies.
976 // Yield to other processes
978 bool wxApp::Yield(bool onlyIfNeeded
)
980 bool s_inYield
= FALSE
;
986 wxFAIL_MSG( wxT("wxYield called recursively" ) );
994 // Make sure we have an event loop object,
995 // or Pending/Dispatch will fail
996 wxEventLoop
* eventLoop
= wxEventLoop::GetActive();
997 wxEventLoop
* newEventLoop
= NULL
;
1000 newEventLoop
= new wxEventLoop
;
1001 wxEventLoop::SetActive(newEventLoop
);
1004 while (wxTheApp
&& wxTheApp
->Pending())
1005 wxTheApp
->Dispatch();
1008 wxTimer::NotifyTimers();
1014 wxEventLoop::SetActive(NULL
);
1015 delete newEventLoop
;
1023 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
1025 // While the GUI isn't working that well, just print out the
1028 wxAppBase::OnAssert(file
, line
, msg
);
1031 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);