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 // Processes an X event.
415 void wxApp::ProcessXEvent(WXEvent
* _event
)
417 XEvent
* event
= (XEvent
*) _event
;
419 wxWindow
* win
= NULL
;
420 Window window
= XEventGetWindow(event
);
421 Window actualWindow
= window
;
423 // Find the first wxWindow that corresponds to this event window
424 // Because we're receiving events after a window
425 // has been destroyed, assume a 1:1 match between
426 // Window and wxWindow, so if it's not in the table,
427 // it must have been destroyed.
429 win
= wxGetWindowFromTable(window
);
437 if (!win
->IsEnabled())
440 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
441 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
443 // wxLogDebug( "OnKey from %s", win->GetName().c_str() );
445 // We didn't process wxEVT_KEY_DOWN, so send
447 if (!win
->GetEventHandler()->ProcessEvent( keyEvent
))
449 keyEvent
.SetEventType(wxEVT_CHAR
);
450 win
->GetEventHandler()->ProcessEvent( keyEvent
);
456 if (!win
->IsEnabled())
459 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
460 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
462 win
->GetEventHandler()->ProcessEvent( keyEvent
);
465 case ConfigureNotify
:
468 if (event
->update
.utype
== GR_UPDATE_SIZE
)
471 wxSizeEvent
sizeEvent( wxSize(XConfigureEventGetWidth(event
), XConfigureEventGetHeight(event
)), win
->GetId() );
472 sizeEvent
.SetEventObject( win
);
474 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
480 HandlePropertyChange(_event
);
485 if (!win
->IsEnabled())
488 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);
489 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);
491 if (event
->xclient
.message_type
== wm_protocols
)
493 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
503 * If resize event, don't resize until the last resize event for this
504 * window is recieved. Prevents flicker as windows are resized.
507 Display
*disp
= (Display
*) wxGetDisplay();
512 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
516 wxSize sz
= win
->GetSize();
517 wxSizeEvent
sizeEvent(sz
, win
->GetId());
518 sizeEvent
.SetEventObject(win
);
520 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
527 case GR_EVENT_TYPE_CLOSE_REQ
:
538 win
->GetUpdateRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
539 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
541 win
->GetClearRegion().Union( XExposeEventGetX(event
), XExposeEventGetY(event
),
542 XExposeEventGetWidth(event
), XExposeEventGetHeight(event
));
545 if (event
->xexpose
.count
== 0)
548 // Only erase background, paint in idle time.
549 win
->SendEraseEvents();
557 // wxLogDebug( "GraphicsExpose from %s", win->GetName().c_str(),
558 // event->xgraphicsexpose.x, event->xgraphicsexpose.y,
559 // event->xgraphicsexpose.width, event->xgraphicsexpose.height);
561 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
562 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
564 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
565 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
567 if (event
->xgraphicsexpose
.count
== 0)
569 // Only erase background, paint in idle time.
570 win
->SendEraseEvents();
582 if (!win
->IsEnabled())
585 // Here we check if the top level window is
586 // disabled, which is one aspect of modality.
588 while (tlw
&& !tlw
->IsTopLevel())
589 tlw
= tlw
->GetParent();
590 if (tlw
&& !tlw
->IsEnabled())
593 if (event
->type
== ButtonPress
)
595 if ((win
!= wxWindow::FindFocus()) && win
->AcceptsFocus())
597 // This might actually be done in wxWindow::SetFocus()
599 g_prevFocus
= wxWindow::FindFocus();
606 wxMouseEvent wxevent
;
607 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
608 win
->GetEventHandler()->ProcessEvent( wxevent
);
614 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
615 (event
->xfocus
.mode
== NotifyNormal
))
618 // wxLogDebug( "FocusIn from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
620 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
621 focusEvent
.SetEventObject(win
);
622 focusEvent
.SetWindow( g_prevFocus
);
624 win
->GetEventHandler()->ProcessEvent(focusEvent
);
631 if ((event
->xfocus
.detail
!= NotifyPointer
) &&
632 (event
->xfocus
.mode
== NotifyNormal
))
635 // wxLogDebug( "FocusOut from %s of type %s", win->GetName().c_str(), win->GetClassInfo()->GetClassName() );
637 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
638 focusEvent
.SetEventObject(win
);
639 focusEvent
.SetWindow( g_nextFocus
);
641 win
->GetEventHandler()->ProcessEvent(focusEvent
);
648 // Do we want to process this (for top-level windows)?
649 // But we want to be able to veto closes, anyway
656 //wxString eventName = wxGetXEventName(XEvent& event);
657 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
664 // Returns TRUE if more time is needed.
665 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
666 // but ProcessIdle may be needed by apps, so is kept.
667 bool wxApp::ProcessIdle()
670 event
.SetEventObject(this);
673 return event
.MoreRequested();
676 void wxApp::ExitMainLoop()
682 // Is a message/event pending?
683 bool wxApp::Pending()
685 return wxEventLoop::GetActive()->Pending();
688 // Dispatch a message.
689 void wxApp::Dispatch()
691 wxEventLoop::GetActive()->Dispatch();
694 // This should be redefined in a derived class for
695 // handling property change events for XAtom IPC.
696 void wxApp::HandlePropertyChange(WXEvent
*event
)
698 // by default do nothing special
699 // TODO: what to do for X11
700 // XtDispatchEvent((XEvent*) event);
703 void wxApp::OnIdle(wxIdleEvent
& event
)
705 static bool s_inOnIdle
= FALSE
;
707 // Avoid recursion (via ProcessEvent default case)
713 // Resend in the main thread events which have been prepared in other
715 ProcessPendingEvents();
717 // 'Garbage' collection of windows deleted with Close()
718 DeletePendingObjects();
720 // Send OnIdle events to all windows
721 bool needMore
= SendIdleEvents();
724 event
.RequestMore(TRUE
);
731 // **** please implement me! ****
732 // Wake up the idle handler processor, even if it is in another thread...
736 // Send idle event to all top-level windows
737 bool wxApp::SendIdleEvents()
739 bool needMore
= FALSE
;
741 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
744 wxWindow
* win
= node
->GetData();
745 if (SendIdleEvents(win
))
747 node
= node
->GetNext();
753 // Send idle event to window and all subwindows
754 bool wxApp::SendIdleEvents(wxWindow
* win
)
756 bool needMore
= FALSE
;
759 event
.SetEventObject(win
);
761 win
->GetEventHandler()->ProcessEvent(event
);
763 win
->OnInternalIdle();
765 if (event
.MoreRequested())
768 wxNode
* node
= win
->GetChildren().First();
771 wxWindow
* win
= (wxWindow
*) node
->Data();
772 if (SendIdleEvents(win
))
781 void wxApp::DeletePendingObjects()
783 wxNode
*node
= wxPendingDelete
.First();
786 wxObject
*obj
= (wxObject
*)node
->Data();
790 if (wxPendingDelete
.Member(obj
))
793 // Deleting one object may have deleted other pending
794 // objects, so start from beginning of list again.
795 node
= wxPendingDelete
.First();
799 // Create display, and other initialization
800 bool wxApp::OnInitGui()
802 // Eventually this line will be removed, but for
803 // now we don't want to try popping up a dialog
804 // for error messages.
805 delete wxLog::SetActiveTarget(new wxLogStderr
);
807 if (!wxAppBase::OnInitGui())
810 GetMainColormap( wxApp::GetDisplay() );
812 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
817 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
819 if (!display
) /* Must be called first with non-NULL display */
820 return m_mainColormap
;
822 int defaultScreen
= DefaultScreen((Display
*) display
);
823 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
825 Colormap c
= DefaultColormapOfScreen(screen
);
828 m_mainColormap
= (WXColormap
) c
;
830 return (WXColormap
) c
;
833 Window
wxGetWindowParent(Window window
)
835 wxASSERT_MSG( window
, "invalid window" );
839 Window parent
, root
= 0;
843 unsigned int noChildren
= 0;
845 Window
* children
= NULL
;
847 // #define XQueryTree(d,w,r,p,c,nc) GrQueryTree(w,p,c,nc)
852 XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
853 & children
, & noChildren
);
866 retValue
= wxTheApp
->OnExit();
870 * Exit in some platform-specific way. Not recommended that the app calls this:
871 * only for emergencies.
876 // Yield to other processes
878 bool wxApp::Yield(bool onlyIfNeeded
)
880 bool s_inYield
= FALSE
;
886 wxFAIL_MSG( wxT("wxYield called recursively" ) );
894 while (wxTheApp
&& wxTheApp
->Pending())
895 wxTheApp
->Dispatch();
902 wxIcon
wxApp::GetStdIcon(int which
) const
904 return wxTheme::Get()->GetRenderer()->GetStdIcon(which
);
907 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
909 // While the GUI isn't working that well, just print out the
912 wxAppBase::OnAssert(file
, line
, msg
);
915 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);