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"
41 #pragma message disable nosimpint
44 #include <X11/Xutil.h>
45 #include <X11/Xatom.h>
48 #pragma message enable nosimpint
51 #include "wx/x11/private.h"
55 extern wxList wxPendingDelete
;
57 wxApp
*wxTheApp
= NULL
;
59 wxHashTable
*wxWidgetHashTable
= NULL
;
61 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
63 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
64 EVT_IDLE(wxApp::OnIdle
)
68 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
70 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
72 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
74 // just forward to the default handler for now
75 return gs_pfnXErrorHandler(dpy
, xevent
);
79 long wxApp::sm_lastMessageTime
= 0;
80 WXDisplay
*wxApp::ms_display
= NULL
;
82 // This is set within wxEntryStart -- too early on
83 // to put these in wxTheApp
84 static int g_newArgc
= 0;
85 static wxChar
** g_newArgv
= NULL
;
86 static bool g_showIconic
= FALSE
;
87 static wxSize g_initialSize
= wxDefaultSize
;
89 bool wxApp::Initialize()
91 wxClassInfo::InitializeClasses();
93 // GL: I'm annoyed ... I don't know where to put this and I don't want to
94 // create a module for that as it's part of the core.
96 wxPendingEventsLocker
= new wxCriticalSection();
99 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
100 wxTheColourDatabase
->Initialize();
102 wxInitializeStockLists();
103 wxInitializeStockObjects();
105 #if wxUSE_WX_RESOURCES
106 wxInitializeResourceSystem();
109 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
111 wxModule::RegisterModules();
112 if (!wxModule::InitializeModules()) return FALSE
;
117 void wxApp::CleanUp()
123 delete wxWidgetHashTable
;
124 wxWidgetHashTable
= NULL
;
126 wxModule::CleanUpModules();
128 #if wxUSE_WX_RESOURCES
129 wxCleanUpResourceSystem();
132 delete wxTheColourDatabase
;
133 wxTheColourDatabase
= NULL
;
135 wxDeleteStockObjects();
137 wxDeleteStockLists();
142 wxClassInfo::CleanUpClasses();
145 delete wxPendingEvents
;
146 delete wxPendingEventsLocker
;
149 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
150 // At this point we want to check if there are any memory
151 // blocks that aren't part of the wxDebugContext itself,
152 // as a special case. Then when dumping we need to ignore
153 // wxDebugContext, too.
154 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
156 wxLogDebug("There were memory leaks.");
157 wxDebugContext::Dump();
158 wxDebugContext::PrintStatistics();
162 // do it as the very last thing because everything else can log messages
163 wxLog::DontCreateOnDemand();
164 // do it as the very last thing because everything else can log messages
165 delete wxLog::SetActiveTarget(NULL
);
168 // NB: argc and argv may be changed here, pass by reference!
169 int wxEntryStart( int& argc
, char *argv
[] )
172 // install the X error handler
173 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
174 #endif // __WXDEBUG__
176 wxString displayName
;
177 bool syncDisplay
= FALSE
;
179 // Parse the arguments.
180 // We can't use wxCmdLineParser or OnInitCmdLine and friends because
181 // we have to create the Display earlier. If we can find a way to
182 // use the wxAppBase API then I'll be quite happy to change it.
183 g_newArgv
= new wxChar
*[argc
];
186 for (i
= 0; i
< argc
; i
++)
188 wxString
arg(argv
[i
]);
189 if (arg
== wxT("-display"))
194 displayName
= argv
[i
];
198 else if (arg
== wxT("-geometry"))
203 wxString windowGeometry
= argv
[i
];
205 if (wxSscanf(windowGeometry
.c_str(), _T("%dx%d"), &w
, &h
) != 2)
207 wxLogError(_("Invalid geometry specification '%s'"), windowGeometry
.c_str());
211 g_initialSize
= wxSize(w
, h
);
216 else if (arg
== wxT("-sync"))
221 else if (arg
== wxT("-iconic"))
228 // Not eaten by wxWindows, so pass through
229 g_newArgv
[g_newArgc
] = argv
[i
];
234 if (displayName
.IsEmpty())
235 xdisplay
= XOpenDisplay(NULL
);
237 xdisplay
= XOpenDisplay(displayName
);
241 wxLogError( _("wxWindows could not open display. Exiting.") );
247 XSynchronize(xdisplay
, True
);
250 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
252 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
254 wxSetDetectableAutoRepeat( TRUE
);
256 if (!wxApp::Initialize())
266 if ( !wxTheApp
->OnInitGui() )
273 int wxEntry( int argc
, char *argv
[] )
275 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
276 // This seems to be necessary since there are 'rogue'
277 // objects present at this point (perhaps global objects?)
278 // Setting a checkpoint will ignore them as far as the
279 // memory checking facility is concerned.
280 // Of course you may argue that memory allocated in globals should be
281 // checked, but this is a reasonable compromise.
282 wxDebugContext::SetCheckpoint();
284 int err
= wxEntryStart(argc
, argv
);
290 if (!wxApp::GetInitializerFunction())
292 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
296 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
301 printf( "wxWindows error: wxTheApp == NULL\n" );
305 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
306 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
308 // The command line may have been changed
309 // by stripping out -display etc.
312 wxTheApp
->argc
= g_newArgc
;
313 wxTheApp
->argv
= g_newArgv
;
317 wxTheApp
->argc
= argc
;
318 wxTheApp
->argv
= argv
;
320 wxTheApp
->m_showIconic
= g_showIconic
;
321 wxTheApp
->m_initialSize
= g_initialSize
;
324 retValue
= wxEntryInitGui();
326 // Here frames insert themselves automatically into wxTopLevelWindows by
327 // getting created in OnInit().
330 if ( !wxTheApp
->OnInit() )
336 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
339 // flush the logged messages if any
340 wxLog
*pLog
= wxLog::GetActiveTarget();
341 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
344 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
345 // for further messages
347 if (wxTheApp
->GetTopWindow())
349 delete wxTheApp
->GetTopWindow();
350 wxTheApp
->SetTopWindow(NULL
);
353 wxTheApp
->DeletePendingObjects();
362 // Static member initialization
363 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
370 m_wantDebugOutput
= TRUE
;
374 m_exitOnFrameDelete
= TRUE
;
375 m_mainColormap
= (WXColormap
) NULL
;
376 m_topLevelWidget
= (WXWindow
) NULL
;
377 m_maxRequestSize
= 0;
379 m_showIconic
= FALSE
;
380 m_initialSize
= wxDefaultSize
;
383 bool wxApp::Initialized()
391 int wxApp::MainLoop()
394 m_mainLoop
= new wxEventLoop
;
396 rt
= m_mainLoop
->Run();
403 // Processes an X event.
404 void wxApp::ProcessXEvent(WXEvent
* _event
)
406 XEvent
* event
= (XEvent
*) _event
;
408 wxWindow
* win
= NULL
;
409 Window window
= event
->xany
.window
;
410 Window actualWindow
= window
;
412 // Find the first wxWindow that corresponds to this event window
413 // Because we're receiving events after a window
414 // has been destroyed, assume a 1:1 match between
415 // Window and wxWindow, so if it's not in the table,
416 // it must have been destroyed.
418 win
= wxGetWindowFromTable(window
);
426 if (win
&& !win
->IsEnabled())
432 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
433 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
435 wxLogDebug( "OnKey from %s", win
->GetName().c_str() );
437 // We didn't process wxEVT_KEY_DOWN, so send
439 if (!win
->GetEventHandler()->ProcessEvent( keyEvent
))
441 keyEvent
.SetEventType(wxEVT_CHAR
);
442 win
->GetEventHandler()->ProcessEvent( keyEvent
);
445 // We intercepted and processed the key down event
453 if (win
&& !win
->IsEnabled())
458 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
459 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
461 win
->GetEventHandler()->ProcessEvent( keyEvent
);
465 case ConfigureNotify
:
467 // Not clear if this is the same in NanoX
470 wxSizeEvent
sizeEvent( wxSize(event
->xconfigure
.width
,event
->xconfigure
.height
), win
->GetId() );
471 sizeEvent
.SetEventObject( win
);
473 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
479 HandlePropertyChange(_event
);
484 if (win
&& !win
->IsEnabled())
487 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);
488 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);
490 if (event
->xclient
.message_type
== wm_protocols
)
492 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
505 * If resize event, don't resize until the last resize event for this
506 * window is recieved. Prevents flicker as windows are resized.
509 Display
*disp
= (Display
*) wxGetDisplay();
514 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
518 wxSize sz
= win
->GetSize();
519 wxSizeEvent
sizeEvent(sz
, win
->GetId());
520 sizeEvent
.SetEventObject(win
);
522 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
529 case GR_EVENT_TYPE_CLOSE_REQ
:
542 win
->GetUpdateRegion().Union( event
->xexpose
.x
, event
->xexpose
.y
,
543 event
->xexpose
.width
, event
->xexpose
.height
);
545 win
->GetClearRegion().Union( event
->xexpose
.x
, event
->xexpose
.y
,
546 event
->xexpose
.width
, event
->xexpose
.height
);
548 // if (event->xexpose.count == 0)
558 // wxLogDebug( "GraphicsExpose from %s", win->GetName().c_str(),
559 // event->xgraphicsexpose.x, event->xgraphicsexpose.y,
560 // event->xgraphicsexpose.width, event->xgraphicsexpose.height);
562 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
563 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
565 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
566 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
568 // if (event->xgraphicsexpose.count == 0)
583 if (!win
->IsEnabled())
587 if (event
->type
== ButtonPress
)
589 if ((win
!= wxWindow::FindFocus()) && win
->AcceptsFocus())
594 wxMouseEvent wxevent
;
595 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
596 win
->GetEventHandler()->ProcessEvent( wxevent
);
602 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
605 wxLogDebug( "FocusIn from %s", win
->GetName().c_str() );
607 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
608 focusEvent
.SetEventObject(win
);
609 win
->GetEventHandler()->ProcessEvent(focusEvent
);
616 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
619 wxLogDebug( "FocusOut from %s", win
->GetName().c_str() );
621 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
622 focusEvent
.SetEventObject(win
);
623 win
->GetEventHandler()->ProcessEvent(focusEvent
);
629 // Do we want to process this (for top-level windows)?
630 // But we want to be able to veto closes, anyway
636 //wxString eventName = wxGetXEventName(XEvent& event);
637 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
644 // Returns TRUE if more time is needed.
645 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
646 // but ProcessIdle may be needed by apps, so is kept.
647 bool wxApp::ProcessIdle()
650 event
.SetEventObject(this);
653 return event
.MoreRequested();
656 void wxApp::ExitMainLoop()
662 // Is a message/event pending?
663 bool wxApp::Pending()
665 return wxEventLoop::GetActive()->Pending();
668 // Dispatch a message.
669 void wxApp::Dispatch()
671 wxEventLoop::GetActive()->Dispatch();
674 // This should be redefined in a derived class for
675 // handling property change events for XAtom IPC.
676 void wxApp::HandlePropertyChange(WXEvent
*event
)
678 // by default do nothing special
679 // TODO: what to do for X11
680 // XtDispatchEvent((XEvent*) event);
683 void wxApp::OnIdle(wxIdleEvent
& event
)
685 static bool s_inOnIdle
= FALSE
;
687 // Avoid recursion (via ProcessEvent default case)
693 // Resend in the main thread events which have been prepared in other
695 ProcessPendingEvents();
697 // 'Garbage' collection of windows deleted with Close()
698 DeletePendingObjects();
700 // Send OnIdle events to all windows
701 bool needMore
= SendIdleEvents();
704 event
.RequestMore(TRUE
);
711 // **** please implement me! ****
712 // Wake up the idle handler processor, even if it is in another thread...
716 // Send idle event to all top-level windows
717 bool wxApp::SendIdleEvents()
719 bool needMore
= FALSE
;
721 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
724 wxWindow
* win
= node
->GetData();
725 if (SendIdleEvents(win
))
727 node
= node
->GetNext();
733 // Send idle event to window and all subwindows
734 bool wxApp::SendIdleEvents(wxWindow
* win
)
736 bool needMore
= FALSE
;
739 event
.SetEventObject(win
);
741 win
->GetEventHandler()->ProcessEvent(event
);
743 win
->OnInternalIdle();
745 if (event
.MoreRequested())
748 wxNode
* node
= win
->GetChildren().First();
751 wxWindow
* win
= (wxWindow
*) node
->Data();
752 if (SendIdleEvents(win
))
761 void wxApp::DeletePendingObjects()
763 wxNode
*node
= wxPendingDelete
.First();
766 wxObject
*obj
= (wxObject
*)node
->Data();
770 if (wxPendingDelete
.Member(obj
))
773 // Deleting one object may have deleted other pending
774 // objects, so start from beginning of list again.
775 node
= wxPendingDelete
.First();
779 // Create display, and other initialization
780 bool wxApp::OnInitGui()
782 // Eventually this line will be removed, but for
783 // now we don't want to try popping up a dialog
784 // for error messages.
785 delete wxLog::SetActiveTarget(new wxLogStderr
);
787 if (!wxAppBase::OnInitGui())
790 GetMainColormap( wxApp::GetDisplay() );
792 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
797 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
799 if (!display
) /* Must be called first with non-NULL display */
800 return m_mainColormap
;
802 int defaultScreen
= DefaultScreen((Display
*) display
);
803 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
805 Colormap c
= DefaultColormapOfScreen(screen
);
808 m_mainColormap
= (WXColormap
) c
;
810 return (WXColormap
) c
;
813 Window
wxGetWindowParent(Window window
)
815 wxASSERT_MSG( window
, "invalid window" );
819 Window parent
, root
= 0;
820 unsigned int noChildren
= 0;
821 Window
* children
= NULL
;
822 int res
= XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
823 & children
, & noChildren
);
836 retValue
= wxTheApp
->OnExit();
840 * Exit in some platform-specific way. Not recommended that the app calls this:
841 * only for emergencies.
846 // Yield to other processes
848 bool wxApp::Yield(bool onlyIfNeeded
)
850 bool s_inYield
= FALSE
;
856 wxFAIL_MSG( wxT("wxYield called recursively" ) );
864 while (wxTheApp
&& wxTheApp
->Pending())
865 wxTheApp
->Dispatch();
872 wxIcon
wxApp::GetStdIcon(int which
) const
874 return wxTheme::Get()->GetRenderer()->GetStdIcon(which
);
877 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
879 // While the GUI isn't working that well, just print out the
882 wxAppBase::OnAssert(file
, line
, msg
);
885 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);