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)
550 // Only erase background, paint in idle time.
551 win
->SendEraseEvents();
561 // wxLogDebug( "GraphicsExpose from %s", win->GetName().c_str(),
562 // event->xgraphicsexpose.x, event->xgraphicsexpose.y,
563 // event->xgraphicsexpose.width, event->xgraphicsexpose.height);
565 win
->GetUpdateRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
566 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
568 win
->GetClearRegion().Union( event
->xgraphicsexpose
.x
, event
->xgraphicsexpose
.y
,
569 event
->xgraphicsexpose
.width
, event
->xgraphicsexpose
.height
);
571 if (event
->xgraphicsexpose
.count
== 0)
573 // Only erase background, paint in idle time.
574 win
->SendEraseEvents();
589 if (!win
->IsEnabled())
593 if (event
->type
== ButtonPress
)
595 if ((win
!= wxWindow::FindFocus()) && win
->AcceptsFocus())
600 wxMouseEvent wxevent
;
601 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
602 win
->GetEventHandler()->ProcessEvent( wxevent
);
608 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
611 wxLogDebug( "FocusIn from %s", win
->GetName().c_str() );
613 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
614 focusEvent
.SetEventObject(win
);
615 win
->GetEventHandler()->ProcessEvent(focusEvent
);
622 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
625 wxLogDebug( "FocusOut from %s", win
->GetName().c_str() );
627 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
628 focusEvent
.SetEventObject(win
);
629 win
->GetEventHandler()->ProcessEvent(focusEvent
);
635 // Do we want to process this (for top-level windows)?
636 // But we want to be able to veto closes, anyway
642 //wxString eventName = wxGetXEventName(XEvent& event);
643 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
650 // Returns TRUE if more time is needed.
651 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
652 // but ProcessIdle may be needed by apps, so is kept.
653 bool wxApp::ProcessIdle()
656 event
.SetEventObject(this);
659 return event
.MoreRequested();
662 void wxApp::ExitMainLoop()
668 // Is a message/event pending?
669 bool wxApp::Pending()
671 return wxEventLoop::GetActive()->Pending();
674 // Dispatch a message.
675 void wxApp::Dispatch()
677 wxEventLoop::GetActive()->Dispatch();
680 // This should be redefined in a derived class for
681 // handling property change events for XAtom IPC.
682 void wxApp::HandlePropertyChange(WXEvent
*event
)
684 // by default do nothing special
685 // TODO: what to do for X11
686 // XtDispatchEvent((XEvent*) event);
689 void wxApp::OnIdle(wxIdleEvent
& event
)
691 static bool s_inOnIdle
= FALSE
;
693 // Avoid recursion (via ProcessEvent default case)
699 // Resend in the main thread events which have been prepared in other
701 ProcessPendingEvents();
703 // 'Garbage' collection of windows deleted with Close()
704 DeletePendingObjects();
706 // Send OnIdle events to all windows
707 bool needMore
= SendIdleEvents();
710 event
.RequestMore(TRUE
);
717 // **** please implement me! ****
718 // Wake up the idle handler processor, even if it is in another thread...
722 // Send idle event to all top-level windows
723 bool wxApp::SendIdleEvents()
725 bool needMore
= FALSE
;
727 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
730 wxWindow
* win
= node
->GetData();
731 if (SendIdleEvents(win
))
733 node
= node
->GetNext();
739 // Send idle event to window and all subwindows
740 bool wxApp::SendIdleEvents(wxWindow
* win
)
742 bool needMore
= FALSE
;
745 event
.SetEventObject(win
);
747 win
->GetEventHandler()->ProcessEvent(event
);
749 win
->OnInternalIdle();
751 if (event
.MoreRequested())
754 wxNode
* node
= win
->GetChildren().First();
757 wxWindow
* win
= (wxWindow
*) node
->Data();
758 if (SendIdleEvents(win
))
767 void wxApp::DeletePendingObjects()
769 wxNode
*node
= wxPendingDelete
.First();
772 wxObject
*obj
= (wxObject
*)node
->Data();
776 if (wxPendingDelete
.Member(obj
))
779 // Deleting one object may have deleted other pending
780 // objects, so start from beginning of list again.
781 node
= wxPendingDelete
.First();
785 // Create display, and other initialization
786 bool wxApp::OnInitGui()
788 // Eventually this line will be removed, but for
789 // now we don't want to try popping up a dialog
790 // for error messages.
791 delete wxLog::SetActiveTarget(new wxLogStderr
);
793 if (!wxAppBase::OnInitGui())
796 GetMainColormap( wxApp::GetDisplay() );
798 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
803 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
805 if (!display
) /* Must be called first with non-NULL display */
806 return m_mainColormap
;
808 int defaultScreen
= DefaultScreen((Display
*) display
);
809 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
811 Colormap c
= DefaultColormapOfScreen(screen
);
814 m_mainColormap
= (WXColormap
) c
;
816 return (WXColormap
) c
;
819 Window
wxGetWindowParent(Window window
)
821 wxASSERT_MSG( window
, "invalid window" );
825 Window parent
, root
= 0;
826 unsigned int noChildren
= 0;
827 Window
* children
= NULL
;
828 int res
= XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
829 & children
, & noChildren
);
842 retValue
= wxTheApp
->OnExit();
846 * Exit in some platform-specific way. Not recommended that the app calls this:
847 * only for emergencies.
852 // Yield to other processes
854 bool wxApp::Yield(bool onlyIfNeeded
)
856 bool s_inYield
= FALSE
;
862 wxFAIL_MSG( wxT("wxYield called recursively" ) );
870 while (wxTheApp
&& wxTheApp
->Pending())
871 wxTheApp
->Dispatch();
878 wxIcon
wxApp::GetStdIcon(int which
) const
880 return wxTheme::Get()->GetRenderer()->GetStdIcon(which
);
883 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
885 // While the GUI isn't working that well, just print out the
888 wxAppBase::OnAssert(file
, line
, msg
);
891 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);