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"
29 #include "wx/univ/theme.h"
30 #include "wx/univ/renderer.h"
33 #include "wx/thread.h"
36 #if wxUSE_WX_RESOURCES
37 #include "wx/resource.h"
40 #include "wx/x11/private.h"
44 //------------------------------------------------------------------------
46 //------------------------------------------------------------------------
48 extern wxList wxPendingDelete
;
50 wxHashTable
*wxWidgetHashTable
= NULL
;
52 wxApp
*wxTheApp
= NULL
;
54 // This is set within wxEntryStart -- too early on
55 // to put these in wxTheApp
56 static int g_newArgc
= 0;
57 static wxChar
** g_newArgv
= NULL
;
58 static bool g_showIconic
= FALSE
;
59 static wxSize g_initialSize
= wxDefaultSize
;
61 // This is required for wxFocusEvent::SetWindow(). It will only
62 // work for focus events which we provoke ourselves (by calling
63 // SetFocus()). It will not work for those events, which X11
65 static wxWindow
*g_nextFocus
= NULL
;
66 static wxWindow
*g_prevFocus
= NULL
;
68 //------------------------------------------------------------------------
70 //------------------------------------------------------------------------
73 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
75 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
77 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
79 // just forward to the default handler for now
80 if (gs_pfnXErrorHandler
)
81 return gs_pfnXErrorHandler(dpy
, xevent
);
87 //------------------------------------------------------------------------
89 //------------------------------------------------------------------------
91 long wxApp::sm_lastMessageTime
= 0;
92 WXDisplay
*wxApp::ms_display
= NULL
;
94 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
96 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
97 EVT_IDLE(wxApp::OnIdle
)
100 bool wxApp::Initialize()
102 wxClassInfo::InitializeClasses();
104 // GL: I'm annoyed ... I don't know where to put this and I don't want to
105 // create a module for that as it's part of the core.
107 wxPendingEventsLocker
= new wxCriticalSection();
110 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
111 wxTheColourDatabase
->Initialize();
113 wxInitializeStockLists();
114 wxInitializeStockObjects();
116 #if wxUSE_WX_RESOURCES
117 wxInitializeResourceSystem();
120 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
122 wxModule::RegisterModules();
123 if (!wxModule::InitializeModules()) return FALSE
;
128 void wxApp::CleanUp()
134 delete wxWidgetHashTable
;
135 wxWidgetHashTable
= NULL
;
137 wxModule::CleanUpModules();
139 #if wxUSE_WX_RESOURCES
140 wxCleanUpResourceSystem();
143 delete wxTheColourDatabase
;
144 wxTheColourDatabase
= NULL
;
146 wxDeleteStockObjects();
148 wxDeleteStockLists();
153 wxClassInfo::CleanUpClasses();
156 delete wxPendingEvents
;
157 delete wxPendingEventsLocker
;
160 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
161 // At this point we want to check if there are any memory
162 // blocks that aren't part of the wxDebugContext itself,
163 // as a special case. Then when dumping we need to ignore
164 // wxDebugContext, too.
165 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
167 wxLogDebug("There were memory leaks.");
168 wxDebugContext::Dump();
169 wxDebugContext::PrintStatistics();
173 // do it as the very last thing because everything else can log messages
174 wxLog::DontCreateOnDemand();
175 // do it as the very last thing because everything else can log messages
176 delete wxLog::SetActiveTarget(NULL
);
179 // NB: argc and argv may be changed here, pass by reference!
180 int wxEntryStart( int& argc
, char *argv
[] )
184 // install the X error handler
185 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
187 #endif // __WXDEBUG__
189 wxString displayName
;
190 bool syncDisplay
= FALSE
;
192 // Parse the arguments.
193 // We can't use wxCmdLineParser or OnInitCmdLine and friends because
194 // we have to create the Display earlier. If we can find a way to
195 // use the wxAppBase API then I'll be quite happy to change it.
196 g_newArgv
= new wxChar
*[argc
];
199 for (i
= 0; i
< argc
; i
++)
201 wxString
arg(argv
[i
]);
202 if (arg
== wxT("-display"))
207 displayName
= argv
[i
];
211 else if (arg
== wxT("-geometry"))
216 wxString windowGeometry
= argv
[i
];
218 if (wxSscanf(windowGeometry
.c_str(), _T("%dx%d"), &w
, &h
) != 2)
220 wxLogError(_("Invalid geometry specification '%s'"), windowGeometry
.c_str());
224 g_initialSize
= wxSize(w
, h
);
229 else if (arg
== wxT("-sync"))
234 else if (arg
== wxT("-iconic"))
241 // Not eaten by wxWindows, so pass through
242 g_newArgv
[g_newArgc
] = argv
[i
];
246 Display
* xdisplay
= NULL
;
247 if (displayName
.IsEmpty())
248 xdisplay
= XOpenDisplay(NULL
);
250 xdisplay
= XOpenDisplay((char*) displayName
.c_str());
254 wxLogError( _("wxWindows could not open display. Exiting.") );
260 XSynchronize(xdisplay
, True
);
263 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
265 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
267 wxSetDetectableAutoRepeat( TRUE
);
269 if (!wxApp::Initialize())
279 if ( !wxTheApp
->OnInitGui() )
286 int wxEntry( int argc
, char *argv
[] )
288 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
289 // This seems to be necessary since there are 'rogue'
290 // objects present at this point (perhaps global objects?)
291 // Setting a checkpoint will ignore them as far as the
292 // memory checking facility is concerned.
293 // Of course you may argue that memory allocated in globals should be
294 // checked, but this is a reasonable compromise.
295 wxDebugContext::SetCheckpoint();
297 int err
= wxEntryStart(argc
, argv
);
303 if (!wxApp::GetInitializerFunction())
305 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
309 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
314 printf( "wxWindows error: wxTheApp == NULL\n" );
318 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
319 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
321 // The command line may have been changed
322 // by stripping out -display etc.
325 wxTheApp
->argc
= g_newArgc
;
326 wxTheApp
->argv
= g_newArgv
;
330 wxTheApp
->argc
= argc
;
331 wxTheApp
->argv
= argv
;
333 wxTheApp
->m_showIconic
= g_showIconic
;
334 wxTheApp
->m_initialSize
= g_initialSize
;
337 retValue
= wxEntryInitGui();
339 // Here frames insert themselves automatically into wxTopLevelWindows by
340 // getting created in OnInit().
343 if ( !wxTheApp
->OnInit() )
349 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
352 // flush the logged messages if any
353 wxLog
*pLog
= wxLog::GetActiveTarget();
354 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
357 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
358 // for further messages
360 if (wxTheApp
->GetTopWindow())
362 delete wxTheApp
->GetTopWindow();
363 wxTheApp
->SetTopWindow(NULL
);
366 wxTheApp
->DeletePendingObjects();
375 // Static member initialization
376 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
383 m_wantDebugOutput
= TRUE
;
387 m_exitOnFrameDelete
= TRUE
;
388 m_mainColormap
= (WXColormap
) NULL
;
389 m_topLevelWidget
= (WXWindow
) NULL
;
390 m_maxRequestSize
= 0;
392 m_showIconic
= FALSE
;
393 m_initialSize
= wxDefaultSize
;
396 bool wxApp::Initialized()
404 int wxApp::MainLoop()
407 m_mainLoop
= new wxEventLoop
;
409 rt
= m_mainLoop
->Run();
417 //-----------------------------------------------------------------------
418 // X11 predicate function for exposure compression
419 //-----------------------------------------------------------------------
424 Bool found_non_matching
;
427 static Bool
expose_predicate (Display
*display
, XEvent
*xevent
, XPointer arg
)
429 wxExposeInfo
*info
= (wxExposeInfo
*) arg
;
431 if (info
->found_non_matching
)
434 if (xevent
->xany
.type
!= Expose
)
436 info
->found_non_matching
= TRUE
;
440 if (xevent
->xexpose
.window
!= info
->window
)
442 info
->found_non_matching
= TRUE
;
451 //-----------------------------------------------------------------------
452 // Processes an X event, returning TRUE if the event was processed.
453 //-----------------------------------------------------------------------
455 bool wxApp::ProcessXEvent(WXEvent
* _event
)
457 XEvent
* event
= (XEvent
*) _event
;
459 wxWindow
* win
= NULL
;
460 Window window
= XEventGetWindow(event
);
461 Window actualWindow
= window
;
463 // Find the first wxWindow that corresponds to this event window
464 // Because we're receiving events after a window
465 // has been destroyed, assume a 1:1 match between
466 // Window and wxWindow, so if it's not in the table,
467 // it must have been destroyed.
469 win
= wxGetWindowFromTable(window
);
474 wxString windowClass
= win
->GetClassInfo()->GetClassName();
481 //wxLogDebug("Expose: %s", windowClass.c_str());
482 win
->GetUpdateRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
483 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
485 win
->GetClearRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
486 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
491 info
.window
= event
->xexpose
.window
;
492 info
.found_non_matching
= FALSE
;
493 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event
, expose_predicate
, (XPointer
) &info
))
495 win
->GetUpdateRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
496 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
498 win
->GetClearRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
499 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
503 // Only erase background, paint in idle time.
504 win
->SendEraseEvents();
512 // wxLogDebug( "GraphicsExpose from %s", win->GetName().c_str(),
513 // event->xgraphicsexpose.x, event->xgraphicsexpose.y,
514 // event->xgraphicsexpose.width, event->xgraphicsexpose.height);
516 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
517 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
519 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
520 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
522 if (event
->xgraphicsexpose
.count
== 0)
524 // Only erase background, paint in idle time.
525 win
->SendEraseEvents();
535 if (!win
->IsEnabled())
538 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
539 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
541 // wxLogDebug( "OnKey from %s", win->GetName().c_str() );
543 // We didn't process wxEVT_KEY_DOWN, so send wxEVT_CHAR
544 if (win
->GetEventHandler()->ProcessEvent( keyEvent
))
547 keyEvent
.SetEventType(wxEVT_CHAR
);
548 if (win
->GetEventHandler()->ProcessEvent( keyEvent
))
551 if ( (keyEvent
.m_keyCode
== WXK_TAB
) &&
552 win
->GetParent() && (win
->GetParent()->HasFlag( wxTAB_TRAVERSAL
)) )
554 wxNavigationKeyEvent new_event
;
555 new_event
.SetEventObject( win
->GetParent() );
556 /* GDK reports GDK_ISO_Left_Tab for SHIFT-TAB */
557 new_event
.SetDirection( (keyEvent
.m_keyCode
== WXK_TAB
) );
558 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
559 new_event
.SetWindowChange( keyEvent
.ControlDown() );
560 new_event
.SetCurrentFocus( win
);
561 return win
->GetParent()->GetEventHandler()->ProcessEvent( new_event
);
568 if (!win
->IsEnabled())
571 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
572 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
574 return win
->GetEventHandler()->ProcessEvent( keyEvent
);
576 case ConfigureNotify
:
579 if (event
->update
.utype
== GR_UPDATE_SIZE
)
582 //wxLogDebug("ConfigureNotify: %s", windowClass.c_str());
583 if (win
->IsTopLevel() && win
->IsShown())
585 wxTopLevelWindowX11
*tlw
= (wxTopLevelWindowX11
*) win
;
586 tlw
->SetNeedResizeInIdle();
590 wxSizeEvent
sizeEvent( wxSize(XConfigureEventGetWidth(event
), XConfigureEventGetHeight(event
)), win
->GetId() );
591 sizeEvent
.SetEventObject( win
);
593 return win
->GetEventHandler()->ProcessEvent( sizeEvent
);
602 //wxLogDebug("PropertyNotify: %s", windowClass.c_str());
603 return HandlePropertyChange(_event
);
607 if (!win
->IsEnabled())
610 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);
611 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);
613 if (event
->xclient
.message_type
== wm_protocols
)
615 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
626 printf( "destroy from %s\n", win
->GetName().c_str() );
631 printf( "create from %s\n", win
->GetName().c_str() );
636 printf( "map request from %s\n", win
->GetName().c_str() );
641 printf( "resize request from %s\n", win
->GetName().c_str() );
643 Display
*disp
= (Display
*) wxGetDisplay();
648 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
650 wxSize sz
= win
->GetSize();
651 wxSizeEvent
sizeEvent(sz
, win
->GetId());
652 sizeEvent
.SetEventObject(win
);
654 return win
->GetEventHandler()->ProcessEvent( sizeEvent
);
659 case GR_EVENT_TYPE_CLOSE_REQ
:
676 if (!win
->IsEnabled())
679 // Here we check if the top level window is
680 // disabled, which is one aspect of modality.
682 while (tlw
&& !tlw
->IsTopLevel())
683 tlw
= tlw
->GetParent();
684 if (tlw
&& !tlw
->IsEnabled())
687 if (event
->type
== ButtonPress
)
689 if ((win
!= wxWindow::FindFocus()) && win
->AcceptsFocus())
691 // This might actually be done in wxWindow::SetFocus()
692 // and not here. TODO.
693 g_prevFocus
= wxWindow::FindFocus();
701 if (event
->type
== LeaveNotify
|| event
->type
== EnterNotify
)
703 // Throw out NotifyGrab and NotifyUngrab
704 if (event
->xcrossing
.mode
!= NotifyNormal
)
708 wxMouseEvent wxevent
;
709 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
710 return win
->GetEventHandler()->ProcessEvent( wxevent
);
715 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
716 (event
->xfocus
.mode
== NotifyNormal
))
719 // wxLogDebug( "FocusIn from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
721 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
722 focusEvent
.SetEventObject(win
);
723 focusEvent
.SetWindow( g_prevFocus
);
726 return win
->GetEventHandler()->ProcessEvent(focusEvent
);
734 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
735 (event
->xfocus
.mode
== NotifyNormal
))
738 // wxLogDebug( "FocusOut from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
740 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
741 focusEvent
.SetEventObject(win
);
742 focusEvent
.SetWindow( g_nextFocus
);
744 return win
->GetEventHandler()->ProcessEvent(focusEvent
);
752 //wxString eventName = wxGetXEventName(XEvent& event);
753 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
762 // Returns TRUE if more time is needed.
763 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
764 // but ProcessIdle may be needed by apps, so is kept.
765 bool wxApp::ProcessIdle()
768 event
.SetEventObject(this);
771 return event
.MoreRequested();
774 void wxApp::ExitMainLoop()
780 // Is a message/event pending?
781 bool wxApp::Pending()
783 return wxEventLoop::GetActive()->Pending();
786 // Dispatch a message.
787 void wxApp::Dispatch()
789 wxEventLoop::GetActive()->Dispatch();
792 // This should be redefined in a derived class for
793 // handling property change events for XAtom IPC.
794 bool wxApp::HandlePropertyChange(WXEvent
*event
)
796 // by default do nothing special
797 // TODO: what to do for X11
798 // XtDispatchEvent((XEvent*) event);
802 void wxApp::OnIdle(wxIdleEvent
& event
)
804 static bool s_inOnIdle
= FALSE
;
806 // Avoid recursion (via ProcessEvent default case)
812 // Resend in the main thread events which have been prepared in other
814 ProcessPendingEvents();
816 // 'Garbage' collection of windows deleted with Close()
817 DeletePendingObjects();
819 // Send OnIdle events to all windows
820 bool needMore
= SendIdleEvents();
823 event
.RequestMore(TRUE
);
830 // **** please implement me! ****
831 // Wake up the idle handler processor, even if it is in another thread...
835 // Send idle event to all top-level windows
836 bool wxApp::SendIdleEvents()
838 bool needMore
= FALSE
;
840 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
843 wxWindow
* win
= node
->GetData();
844 if (SendIdleEvents(win
))
846 node
= node
->GetNext();
852 // Send idle event to window and all subwindows
853 bool wxApp::SendIdleEvents(wxWindow
* win
)
855 bool needMore
= FALSE
;
858 event
.SetEventObject(win
);
860 win
->GetEventHandler()->ProcessEvent(event
);
862 win
->OnInternalIdle();
864 if (event
.MoreRequested())
867 wxNode
* node
= win
->GetChildren().First();
870 wxWindow
* win
= (wxWindow
*) node
->Data();
871 if (SendIdleEvents(win
))
880 void wxApp::DeletePendingObjects()
882 wxNode
*node
= wxPendingDelete
.First();
885 wxObject
*obj
= (wxObject
*)node
->Data();
889 if (wxPendingDelete
.Member(obj
))
892 // Deleting one object may have deleted other pending
893 // objects, so start from beginning of list again.
894 node
= wxPendingDelete
.First();
898 // Create display, and other initialization
899 bool wxApp::OnInitGui()
901 // Eventually this line will be removed, but for
902 // now we don't want to try popping up a dialog
903 // for error messages.
904 delete wxLog::SetActiveTarget(new wxLogStderr
);
906 if (!wxAppBase::OnInitGui())
909 GetMainColormap( wxApp::GetDisplay() );
911 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
916 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
918 if (!display
) /* Must be called first with non-NULL display */
919 return m_mainColormap
;
921 int defaultScreen
= DefaultScreen((Display
*) display
);
922 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
924 Colormap c
= DefaultColormapOfScreen(screen
);
927 m_mainColormap
= (WXColormap
) c
;
929 return (WXColormap
) c
;
932 Window
wxGetWindowParent(Window window
)
934 wxASSERT_MSG( window
, "invalid window" );
938 Window parent
, root
= 0;
942 unsigned int noChildren
= 0;
944 Window
* children
= NULL
;
946 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
951 XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
952 & children
, & noChildren
);
965 retValue
= wxTheApp
->OnExit();
969 * Exit in some platform-specific way. Not recommended that the app calls this:
970 * only for emergencies.
975 // Yield to other processes
977 bool wxApp::Yield(bool onlyIfNeeded
)
979 bool s_inYield
= FALSE
;
985 wxFAIL_MSG( wxT("wxYield called recursively" ) );
993 while (wxTheApp
&& wxTheApp
->Pending())
994 wxTheApp
->Dispatch();
1001 wxIcon
wxApp::GetStdIcon(int which
) const
1003 return wxTheme::Get()->GetRenderer()->GetStdIcon(which
);
1006 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
1008 // While the GUI isn't working that well, just print out the
1011 wxAppBase::OnAssert(file
, line
, msg
);
1014 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);