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/thread.h"
33 #if wxUSE_WX_RESOURCES
34 #include "wx/resource.h"
38 #pragma message disable nosimpint
41 #include <X11/Xutil.h>
42 #include <X11/Xatom.h>
45 #pragma message enable nosimpint
48 #include "wx/x11/private.h"
52 extern wxList wxPendingDelete
;
54 wxApp
*wxTheApp
= NULL
;
56 wxHashTable
*wxWidgetHashTable
= NULL
;
58 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
60 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
61 EVT_IDLE(wxApp::OnIdle
)
65 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
67 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
69 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
71 // just forward to the default handler for now
72 return gs_pfnXErrorHandler(dpy
, xevent
);
76 long wxApp::sm_lastMessageTime
= 0;
77 WXDisplay
*wxApp::ms_display
= NULL
;
79 // This is set within wxEntryStart -- too early on
80 // to put these in wxTheApp
81 static int g_newArgc
= 0;
82 static wxChar
** g_newArgv
= NULL
;
83 static bool g_showIconic
= FALSE
;
84 static wxSize g_initialSize
= wxDefaultSize
;
86 bool wxApp::Initialize()
88 wxClassInfo::InitializeClasses();
90 // GL: I'm annoyed ... I don't know where to put this and I don't want to
91 // create a module for that as it's part of the core.
93 wxPendingEventsLocker
= new wxCriticalSection();
96 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
97 wxTheColourDatabase
->Initialize();
99 wxInitializeStockLists();
100 wxInitializeStockObjects();
102 #if wxUSE_WX_RESOURCES
103 wxInitializeResourceSystem();
106 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
108 wxModule::RegisterModules();
109 if (!wxModule::InitializeModules()) return FALSE
;
114 void wxApp::CleanUp()
120 delete wxWidgetHashTable
;
121 wxWidgetHashTable
= NULL
;
123 wxModule::CleanUpModules();
125 #if wxUSE_WX_RESOURCES
126 wxCleanUpResourceSystem();
129 delete wxTheColourDatabase
;
130 wxTheColourDatabase
= NULL
;
132 wxDeleteStockObjects();
134 wxDeleteStockLists();
139 wxClassInfo::CleanUpClasses();
142 delete wxPendingEvents
;
143 delete wxPendingEventsLocker
;
146 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
147 // At this point we want to check if there are any memory
148 // blocks that aren't part of the wxDebugContext itself,
149 // as a special case. Then when dumping we need to ignore
150 // wxDebugContext, too.
151 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
153 wxLogDebug("There were memory leaks.");
154 wxDebugContext::Dump();
155 wxDebugContext::PrintStatistics();
159 // do it as the very last thing because everything else can log messages
160 wxLog::DontCreateOnDemand();
161 // do it as the very last thing because everything else can log messages
162 delete wxLog::SetActiveTarget(NULL
);
165 // NB: argc and argv may be changed here, pass by reference!
166 int wxEntryStart( int& argc
, char *argv
[] )
169 // install the X error handler
170 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
171 #endif // __WXDEBUG__
173 wxString displayName
;
174 bool syncDisplay
= FALSE
;
176 // Parse the arguments.
177 // We can't use wxCmdLineParser or OnInitCmdLine and friends because
178 // we have to create the Display earlier. If we can find a way to
179 // use the wxAppBase API then I'll be quite happy to change it.
180 g_newArgv
= new wxChar
*[argc
];
183 for (i
= 0; i
< argc
; i
++)
185 wxString
arg(argv
[i
]);
186 if (arg
== wxT("-display"))
191 displayName
= argv
[i
];
195 else if (arg
== wxT("-geometry"))
200 wxString windowGeometry
= argv
[i
];
202 if (wxSscanf(windowGeometry
.c_str(), _T("%dx%d"), &w
, &h
) != 2)
204 wxLogError(_("Invalid geometry specification '%s'"), windowGeometry
.c_str());
208 g_initialSize
= wxSize(w
, h
);
213 else if (arg
== wxT("-sync"))
218 else if (arg
== wxT("-iconic"))
225 // Not eaten by wxWindows, so pass through
226 g_newArgv
[g_newArgc
] = argv
[i
];
231 if (displayName
.IsEmpty())
232 xdisplay
= XOpenDisplay(NULL
);
234 xdisplay
= XOpenDisplay(displayName
);
238 wxLogError( _("wxWindows could not open display. Exiting.") );
244 XSynchronize(xdisplay
, True
);
247 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
249 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
251 // wxSetDetectableAutoRepeat( TRUE );
253 if (!wxApp::Initialize())
263 if ( !wxTheApp
->OnInitGui() )
270 int wxEntry( int argc
, char *argv
[] )
272 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
273 // This seems to be necessary since there are 'rogue'
274 // objects present at this point (perhaps global objects?)
275 // Setting a checkpoint will ignore them as far as the
276 // memory checking facility is concerned.
277 // Of course you may argue that memory allocated in globals should be
278 // checked, but this is a reasonable compromise.
279 wxDebugContext::SetCheckpoint();
281 int err
= wxEntryStart(argc
, argv
);
287 if (!wxApp::GetInitializerFunction())
289 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
293 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
298 printf( "wxWindows error: wxTheApp == NULL\n" );
302 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
303 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
305 // The command line may have been changed
306 // by stripping out -display etc.
309 wxTheApp
->argc
= g_newArgc
;
310 wxTheApp
->argv
= g_newArgv
;
314 wxTheApp
->argc
= argc
;
315 wxTheApp
->argv
= argv
;
317 wxTheApp
->m_showIconic
= g_showIconic
;
318 wxTheApp
->m_initialSize
= g_initialSize
;
321 retValue
= wxEntryInitGui();
323 // Here frames insert themselves automatically into wxTopLevelWindows by
324 // getting created in OnInit().
327 if ( !wxTheApp
->OnInit() )
333 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
336 // flush the logged messages if any
337 wxLog
*pLog
= wxLog::GetActiveTarget();
338 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
341 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
342 // for further messages
344 if (wxTheApp
->GetTopWindow())
346 delete wxTheApp
->GetTopWindow();
347 wxTheApp
->SetTopWindow(NULL
);
350 wxTheApp
->DeletePendingObjects();
359 // Static member initialization
360 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
367 m_wantDebugOutput
= TRUE
;
371 m_exitOnFrameDelete
= TRUE
;
372 m_mainColormap
= (WXColormap
) NULL
;
373 m_topLevelWidget
= (WXWindow
) NULL
;
374 m_maxRequestSize
= 0;
376 m_showIconic
= FALSE
;
377 m_initialSize
= wxDefaultSize
;
380 bool wxApp::Initialized()
388 int wxApp::MainLoop()
391 m_mainLoop
= new wxEventLoop
;
393 rt
= m_mainLoop
->Run();
400 // Processes an X event.
401 void wxApp::ProcessXEvent(WXEvent
* _event
)
403 XEvent
* event
= (XEvent
*) _event
;
405 wxWindow
* win
= NULL
;
406 Window window
= event
->xany
.window
;
407 Window actualWindow
= window
;
409 // Find the first wxWindow that corresponds to this event window
410 // Because we're receiving events after a window
411 // has been destroyed, assume a 1:1 match between
412 // Window and wxWindow, so if it's not in the table,
413 // it must have been destroyed.
415 win
= wxGetWindowFromTable(window
);
423 if (win
&& !win
->IsEnabled())
429 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
430 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
432 wxLogDebug( "OnKey from %s", win
->GetName().c_str() );
434 // We didn't process wxEVT_KEY_DOWN, so send
436 if (!win
->GetEventHandler()->ProcessEvent( keyEvent
))
438 keyEvent
.SetEventType(wxEVT_CHAR
);
439 win
->GetEventHandler()->ProcessEvent( keyEvent
);
442 // We intercepted and processed the key down event
450 if (win
&& !win
->IsEnabled())
455 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
456 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
458 win
->GetEventHandler()->ProcessEvent( keyEvent
);
462 case ConfigureNotify
:
464 // Not clear if this is the same in NanoX
467 wxSizeEvent
sizeEvent( wxSize(event
->xconfigure
.width
,event
->xconfigure
.height
), win
->GetId() );
468 sizeEvent
.SetEventObject( win
);
470 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
476 HandlePropertyChange(_event
);
481 if (win
&& !win
->IsEnabled())
484 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);;
485 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);;
487 if (event
->xclient
.message_type
== wm_protocols
)
489 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
502 * If resize event, don't resize until the last resize event for this
503 * window is recieved. Prevents flicker as windows are resized.
506 Display
*disp
= (Display
*) wxGetDisplay();
511 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
515 wxSize sz
= win
->GetSize();
516 wxSizeEvent
sizeEvent(sz
, win
->GetId());
517 sizeEvent
.SetEventObject(win
);
519 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
526 case GR_EVENT_TYPE_CLOSE_REQ
:
539 win
->GetUpdateRegion().Union( event
->xexpose
.x
, event
->xexpose
.y
,
540 event
->xexpose
.width
, event
->xexpose
.height
);
542 win
->GetClearRegion().Union( event
->xexpose
.x
, event
->xexpose
.y
,
543 event
->xexpose
.width
, event
->xexpose
.height
);
545 // if (event->xexpose.count == 0)
555 wxLogDebug( "GraphicsExpose from %s", win
->GetName().c_str(),
556 event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
557 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
559 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
560 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
562 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
563 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
565 // if (event->xgraphicsexpose.count == 0)
577 if (win
&& !win
->IsEnabled())
582 wxMouseEvent wxevent
;
583 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
584 win
->GetEventHandler()->ProcessEvent( wxevent
);
591 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
594 wxLogDebug( "FocusIn from %s", win
->GetName().c_str() );
596 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
597 focusEvent
.SetEventObject(win
);
598 win
->GetEventHandler()->ProcessEvent(focusEvent
);
605 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
608 wxLogDebug( "FocusOut from %s", win
->GetName().c_str() );
610 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
611 focusEvent
.SetEventObject(win
);
612 win
->GetEventHandler()->ProcessEvent(focusEvent
);
618 // Do we want to process this (for top-level windows)?
619 // But we want to be able to veto closes, anyway
625 //wxString eventName = wxGetXEventName(XEvent& event);
626 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
633 // Returns TRUE if more time is needed.
634 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
635 // but ProcessIdle may be needed by apps, so is kept.
636 bool wxApp::ProcessIdle()
639 event
.SetEventObject(this);
642 return event
.MoreRequested();
645 void wxApp::ExitMainLoop()
651 // Is a message/event pending?
652 bool wxApp::Pending()
654 return wxEventLoop::GetActive()->Pending();
657 // Dispatch a message.
658 void wxApp::Dispatch()
660 wxEventLoop::GetActive()->Dispatch();
663 // This should be redefined in a derived class for
664 // handling property change events for XAtom IPC.
665 void wxApp::HandlePropertyChange(WXEvent
*event
)
667 // by default do nothing special
668 // TODO: what to do for X11
669 // XtDispatchEvent((XEvent*) event);
672 void wxApp::OnIdle(wxIdleEvent
& event
)
674 static bool s_inOnIdle
= FALSE
;
676 // Avoid recursion (via ProcessEvent default case)
682 // Resend in the main thread events which have been prepared in other
684 ProcessPendingEvents();
686 // 'Garbage' collection of windows deleted with Close()
687 DeletePendingObjects();
689 // Send OnIdle events to all windows
690 bool needMore
= SendIdleEvents();
693 event
.RequestMore(TRUE
);
700 // **** please implement me! ****
701 // Wake up the idle handler processor, even if it is in another thread...
705 // Send idle event to all top-level windows
706 bool wxApp::SendIdleEvents()
708 bool needMore
= FALSE
;
710 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
713 wxWindow
* win
= node
->GetData();
714 if (SendIdleEvents(win
))
716 node
= node
->GetNext();
722 // Send idle event to window and all subwindows
723 bool wxApp::SendIdleEvents(wxWindow
* win
)
725 bool needMore
= FALSE
;
728 event
.SetEventObject(win
);
730 win
->GetEventHandler()->ProcessEvent(event
);
732 win
->OnInternalIdle();
734 if (event
.MoreRequested())
737 wxNode
* node
= win
->GetChildren().First();
740 wxWindow
* win
= (wxWindow
*) node
->Data();
741 if (SendIdleEvents(win
))
750 void wxApp::DeletePendingObjects()
752 wxNode
*node
= wxPendingDelete
.First();
755 wxObject
*obj
= (wxObject
*)node
->Data();
759 if (wxPendingDelete
.Member(obj
))
762 // Deleting one object may have deleted other pending
763 // objects, so start from beginning of list again.
764 node
= wxPendingDelete
.First();
768 // Create display, and other initialization
769 bool wxApp::OnInitGui()
771 // Eventually this line will be removed, but for
772 // now we don't want to try popping up a dialog
773 // for error messages.
774 delete wxLog::SetActiveTarget(new wxLogStderr
);
776 if (!wxAppBase::OnInitGui())
779 GetMainColormap( wxApp::GetDisplay() );
781 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
786 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
788 if (!display
) /* Must be called first with non-NULL display */
789 return m_mainColormap
;
791 int defaultScreen
= DefaultScreen((Display
*) display
);
792 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
794 Colormap c
= DefaultColormapOfScreen(screen
);
797 m_mainColormap
= (WXColormap
) c
;
799 return (WXColormap
) c
;
802 Window
wxGetWindowParent(Window window
)
804 wxASSERT_MSG( window
, "invalid window" );
808 Window parent
, root
= 0;
809 unsigned int noChildren
= 0;
810 Window
* children
= NULL
;
811 int res
= XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
812 & children
, & noChildren
);
825 retValue
= wxTheApp
->OnExit();
829 * Exit in some platform-specific way. Not recommended that the app calls this:
830 * only for emergencies.
835 // Yield to other processes
837 bool wxApp::Yield(bool onlyIfNeeded
)
839 bool s_inYield
= FALSE
;
845 wxFAIL_MSG( wxT("wxYield called recursively" ) );
853 while (wxTheApp
&& wxTheApp
->Pending())
854 wxTheApp
->Dispatch();
861 // XPM hack: make the arrays const
862 #define static static const
864 #include "wx/generic/info.xpm"
865 #include "wx/generic/error.xpm"
866 #include "wx/generic/question.xpm"
867 #include "wx/generic/warning.xpm"
872 wxApp::GetStdIcon(int which
) const
876 case wxICON_INFORMATION
:
877 return wxIcon(info_xpm
);
879 case wxICON_QUESTION
:
880 return wxIcon(question_xpm
);
882 case wxICON_EXCLAMATION
:
883 return wxIcon(warning_xpm
);
886 wxFAIL_MSG("requested non existent standard icon");
887 // still fall through
890 return wxIcon(error_xpm
);
894 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
896 // While the GUI isn't working that well, just print out the
899 wxAppBase::OnAssert(file
, line
, msg
);
902 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);