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
[] )
183 // install the X error handler
184 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
185 #endif // __WXDEBUG__
187 wxString displayName
;
188 bool syncDisplay
= FALSE
;
190 // Parse the arguments.
191 // We can't use wxCmdLineParser or OnInitCmdLine and friends because
192 // we have to create the Display earlier. If we can find a way to
193 // use the wxAppBase API then I'll be quite happy to change it.
194 g_newArgv
= new wxChar
*[argc
];
197 for (i
= 0; i
< argc
; i
++)
199 wxString
arg(argv
[i
]);
200 if (arg
== wxT("-display"))
205 displayName
= argv
[i
];
209 else if (arg
== wxT("-geometry"))
214 wxString windowGeometry
= argv
[i
];
216 if (wxSscanf(windowGeometry
.c_str(), _T("%dx%d"), &w
, &h
) != 2)
218 wxLogError(_("Invalid geometry specification '%s'"), windowGeometry
.c_str());
222 g_initialSize
= wxSize(w
, h
);
227 else if (arg
== wxT("-sync"))
232 else if (arg
== wxT("-iconic"))
239 // Not eaten by wxWindows, so pass through
240 g_newArgv
[g_newArgc
] = argv
[i
];
244 Display
* xdisplay
= NULL
;
245 if (displayName
.IsEmpty())
246 xdisplay
= XOpenDisplay(NULL
);
248 xdisplay
= XOpenDisplay((char*) displayName
.c_str());
252 wxLogError( _("wxWindows could not open display. Exiting.") );
258 XSynchronize(xdisplay
, True
);
261 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
263 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
265 wxSetDetectableAutoRepeat( TRUE
);
267 if (!wxApp::Initialize())
277 if ( !wxTheApp
->OnInitGui() )
284 int wxEntry( int argc
, char *argv
[] )
286 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
287 // This seems to be necessary since there are 'rogue'
288 // objects present at this point (perhaps global objects?)
289 // Setting a checkpoint will ignore them as far as the
290 // memory checking facility is concerned.
291 // Of course you may argue that memory allocated in globals should be
292 // checked, but this is a reasonable compromise.
293 wxDebugContext::SetCheckpoint();
295 int err
= wxEntryStart(argc
, argv
);
301 if (!wxApp::GetInitializerFunction())
303 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
307 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
312 printf( "wxWindows error: wxTheApp == NULL\n" );
316 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
317 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
319 // The command line may have been changed
320 // by stripping out -display etc.
323 wxTheApp
->argc
= g_newArgc
;
324 wxTheApp
->argv
= g_newArgv
;
328 wxTheApp
->argc
= argc
;
329 wxTheApp
->argv
= argv
;
331 wxTheApp
->m_showIconic
= g_showIconic
;
332 wxTheApp
->m_initialSize
= g_initialSize
;
335 retValue
= wxEntryInitGui();
337 // Here frames insert themselves automatically into wxTopLevelWindows by
338 // getting created in OnInit().
341 if ( !wxTheApp
->OnInit() )
347 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
350 // flush the logged messages if any
351 wxLog
*pLog
= wxLog::GetActiveTarget();
352 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
355 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
356 // for further messages
358 if (wxTheApp
->GetTopWindow())
360 delete wxTheApp
->GetTopWindow();
361 wxTheApp
->SetTopWindow(NULL
);
364 wxTheApp
->DeletePendingObjects();
373 // Static member initialization
374 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
381 m_wantDebugOutput
= TRUE
;
385 m_exitOnFrameDelete
= TRUE
;
386 m_mainColormap
= (WXColormap
) NULL
;
387 m_topLevelWidget
= (WXWindow
) NULL
;
388 m_maxRequestSize
= 0;
390 m_showIconic
= FALSE
;
391 m_initialSize
= wxDefaultSize
;
394 bool wxApp::Initialized()
402 int wxApp::MainLoop()
405 m_mainLoop
= new wxEventLoop
;
407 rt
= m_mainLoop
->Run();
414 //-----------------------------------------------------------------------
415 // X11 predicate function for exposure compression
416 //-----------------------------------------------------------------------
421 Bool found_non_matching
;
424 static Bool
expose_predicate (Display
*display
, XEvent
*xevent
, XPointer arg
)
426 wxExposeInfo
*info
= (wxExposeInfo
*) arg
;
428 if (info
->found_non_matching
)
431 if (xevent
->xany
.type
!= Expose
)
433 info
->found_non_matching
= TRUE
;
437 if (xevent
->xexpose
.window
!= info
->window
)
439 info
->found_non_matching
= TRUE
;
446 //-----------------------------------------------------------------------
447 // Processes an X event.
448 //-----------------------------------------------------------------------
450 void wxApp::ProcessXEvent(WXEvent
* _event
)
452 XEvent
* event
= (XEvent
*) _event
;
454 wxWindow
* win
= NULL
;
455 Window window
= XEventGetWindow(event
);
456 Window actualWindow
= window
;
458 // Find the first wxWindow that corresponds to this event window
459 // Because we're receiving events after a window
460 // has been destroyed, assume a 1:1 match between
461 // Window and wxWindow, so if it's not in the table,
462 // it must have been destroyed.
464 win
= wxGetWindowFromTable(window
);
472 if (!win
->IsEnabled())
475 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
476 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
478 // wxLogDebug( "OnKey from %s", win->GetName().c_str() );
480 // We didn't process wxEVT_KEY_DOWN, so send
482 if (!win
->GetEventHandler()->ProcessEvent( keyEvent
))
484 keyEvent
.SetEventType(wxEVT_CHAR
);
485 win
->GetEventHandler()->ProcessEvent( keyEvent
);
491 if (!win
->IsEnabled())
494 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
495 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
497 win
->GetEventHandler()->ProcessEvent( keyEvent
);
500 case ConfigureNotify
:
503 if (event
->update
.utype
== GR_UPDATE_SIZE
)
506 wxSizeEvent
sizeEvent( wxSize(XConfigureEventGetWidth(event
), XConfigureEventGetHeight(event
)), win
->GetId() );
507 sizeEvent
.SetEventObject( win
);
509 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
515 HandlePropertyChange(_event
);
520 if (!win
->IsEnabled())
523 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);
524 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);
526 if (event
->xclient
.message_type
== wm_protocols
)
528 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
538 * If resize event, don't resize until the last resize event for this
539 * window is recieved. Prevents flicker as windows are resized.
542 Display
*disp
= (Display
*) wxGetDisplay();
547 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
551 wxSize sz
= win
->GetSize();
552 wxSizeEvent
sizeEvent(sz
, win
->GetId());
553 sizeEvent
.SetEventObject(win
);
555 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
562 case GR_EVENT_TYPE_CLOSE_REQ
:
573 win
->GetUpdateRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
574 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
576 win
->GetClearRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
577 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
583 info
.window
= event
->xexpose
.window
;
584 info
.found_non_matching
= FALSE
;
585 while (XCheckIfEvent( wxGlobalDisplay(), &tmp_event
, expose_predicate
, (XPointer
) &info
))
587 win
->GetUpdateRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
588 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
590 win
->GetClearRegion().Union( tmp_event
.xexpose
.x
, tmp_event
.xexpose
.y
,
591 tmp_event
.xexpose
.width
, tmp_event
.xexpose
.height
);
595 win
->SendEraseEvents();
602 // wxLogDebug( "GraphicsExpose from %s", win->GetName().c_str(),
603 // event->xgraphicsexpose.x, event->xgraphicsexpose.y,
604 // event->xgraphicsexpose.width, event->xgraphicsexpose.height);
606 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
607 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
609 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
610 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
612 if (event
->xgraphicsexpose
.count
== 0)
614 // Only erase background, paint in idle time.
615 win
->SendEraseEvents();
627 if (!win
->IsEnabled())
630 // Here we check if the top level window is
631 // disabled, which is one aspect of modality.
633 while (tlw
&& !tlw
->IsTopLevel())
634 tlw
= tlw
->GetParent();
635 if (tlw
&& !tlw
->IsEnabled())
638 if (event
->type
== ButtonPress
)
640 if ((win
!= wxWindow::FindFocus()) && win
->AcceptsFocus())
642 // This might actually be done in wxWindow::SetFocus()
644 g_prevFocus
= wxWindow::FindFocus();
651 wxMouseEvent wxevent
;
652 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
653 win
->GetEventHandler()->ProcessEvent( wxevent
);
659 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
660 (event
->xfocus
.mode
== NotifyNormal
))
663 // wxLogDebug( "FocusIn from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
665 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
666 focusEvent
.SetEventObject(win
);
667 focusEvent
.SetWindow( g_prevFocus
);
670 win
->GetEventHandler()->ProcessEvent(focusEvent
);
677 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
678 (event
->xfocus
.mode
== NotifyNormal
))
681 // wxLogDebug( "FocusOut from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
683 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
684 focusEvent
.SetEventObject(win
);
685 focusEvent
.SetWindow( g_nextFocus
);
687 win
->GetEventHandler()->ProcessEvent(focusEvent
);
694 // Do we want to process this (for top-level windows)?
695 // But we want to be able to veto closes, anyway
702 //wxString eventName = wxGetXEventName(XEvent& event);
703 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
710 // Returns TRUE if more time is needed.
711 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
712 // but ProcessIdle may be needed by apps, so is kept.
713 bool wxApp::ProcessIdle()
716 event
.SetEventObject(this);
719 return event
.MoreRequested();
722 void wxApp::ExitMainLoop()
728 // Is a message/event pending?
729 bool wxApp::Pending()
731 return wxEventLoop::GetActive()->Pending();
734 // Dispatch a message.
735 void wxApp::Dispatch()
737 wxEventLoop::GetActive()->Dispatch();
740 // This should be redefined in a derived class for
741 // handling property change events for XAtom IPC.
742 void wxApp::HandlePropertyChange(WXEvent
*event
)
744 // by default do nothing special
745 // TODO: what to do for X11
746 // XtDispatchEvent((XEvent*) event);
749 void wxApp::OnIdle(wxIdleEvent
& event
)
751 static bool s_inOnIdle
= FALSE
;
753 // Avoid recursion (via ProcessEvent default case)
759 // Resend in the main thread events which have been prepared in other
761 ProcessPendingEvents();
763 // 'Garbage' collection of windows deleted with Close()
764 DeletePendingObjects();
766 // Send OnIdle events to all windows
767 bool needMore
= SendIdleEvents();
770 event
.RequestMore(TRUE
);
777 // **** please implement me! ****
778 // Wake up the idle handler processor, even if it is in another thread...
782 // Send idle event to all top-level windows
783 bool wxApp::SendIdleEvents()
785 bool needMore
= FALSE
;
787 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
790 wxWindow
* win
= node
->GetData();
791 if (SendIdleEvents(win
))
793 node
= node
->GetNext();
799 // Send idle event to window and all subwindows
800 bool wxApp::SendIdleEvents(wxWindow
* win
)
802 bool needMore
= FALSE
;
805 event
.SetEventObject(win
);
807 win
->GetEventHandler()->ProcessEvent(event
);
809 win
->OnInternalIdle();
811 if (event
.MoreRequested())
814 wxNode
* node
= win
->GetChildren().First();
817 wxWindow
* win
= (wxWindow
*) node
->Data();
818 if (SendIdleEvents(win
))
827 void wxApp::DeletePendingObjects()
829 wxNode
*node
= wxPendingDelete
.First();
832 wxObject
*obj
= (wxObject
*)node
->Data();
836 if (wxPendingDelete
.Member(obj
))
839 // Deleting one object may have deleted other pending
840 // objects, so start from beginning of list again.
841 node
= wxPendingDelete
.First();
845 // Create display, and other initialization
846 bool wxApp::OnInitGui()
848 // Eventually this line will be removed, but for
849 // now we don't want to try popping up a dialog
850 // for error messages.
851 delete wxLog::SetActiveTarget(new wxLogStderr
);
853 if (!wxAppBase::OnInitGui())
856 GetMainColormap( wxApp::GetDisplay() );
858 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
863 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
865 if (!display
) /* Must be called first with non-NULL display */
866 return m_mainColormap
;
868 int defaultScreen
= DefaultScreen((Display
*) display
);
869 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
871 Colormap c
= DefaultColormapOfScreen(screen
);
874 m_mainColormap
= (WXColormap
) c
;
876 return (WXColormap
) c
;
879 Window
wxGetWindowParent(Window window
)
881 wxASSERT_MSG( window
, "invalid window" );
885 Window parent
, root
= 0;
889 unsigned int noChildren
= 0;
891 Window
* children
= NULL
;
893 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
898 XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
899 & children
, & noChildren
);
912 retValue
= wxTheApp
->OnExit();
916 * Exit in some platform-specific way. Not recommended that the app calls this:
917 * only for emergencies.
922 // Yield to other processes
924 bool wxApp::Yield(bool onlyIfNeeded
)
926 bool s_inYield
= FALSE
;
932 wxFAIL_MSG( wxT("wxYield called recursively" ) );
940 while (wxTheApp
&& wxTheApp
->Pending())
941 wxTheApp
->Dispatch();
948 wxIcon
wxApp::GetStdIcon(int which
) const
950 return wxTheme::Get()->GetRenderer()->GetStdIcon(which
);
953 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
955 // While the GUI isn't working that well, just print out the
958 wxAppBase::OnAssert(file
, line
, msg
);
961 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);