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"
22 #include "wx/cursor.h"
24 #include "wx/dialog.h"
25 #include "wx/msgdlg.h"
27 #include "wx/module.h"
28 #include "wx/memory.h"
31 #include "wx/evtloop.h"
32 #include "wx/cmdline.h"
35 #include "wx/thread.h"
38 #if wxUSE_WX_RESOURCES
39 #include "wx/resource.h"
43 #pragma message disable nosimpint
46 #include <X11/Xutil.h>
47 #include <X11/Xresource.h>
48 #include <X11/Xatom.h>
50 #pragma message enable nosimpint
53 #include "wx/x11/private.h"
57 extern wxList wxPendingDelete
;
59 wxApp
*wxTheApp
= NULL
;
61 wxHashTable
*wxWidgetHashTable
= NULL
;
63 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
65 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
66 EVT_IDLE(wxApp::OnIdle
)
70 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
72 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
74 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
76 // just forward to the default handler for now
77 return gs_pfnXErrorHandler(dpy
, xevent
);
81 long wxApp::sm_lastMessageTime
= 0;
82 WXDisplay
*wxApp::ms_display
= NULL
;
84 bool wxApp::Initialize()
86 wxClassInfo::InitializeClasses();
88 // GL: I'm annoyed ... I don't know where to put this and I don't want to
89 // create a module for that as it's part of the core.
91 wxPendingEventsLocker
= new wxCriticalSection();
94 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
95 wxTheColourDatabase
->Initialize();
97 wxInitializeStockLists();
98 wxInitializeStockObjects();
100 #if wxUSE_WX_RESOURCES
101 wxInitializeResourceSystem();
104 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
106 wxModule::RegisterModules();
107 if (!wxModule::InitializeModules()) return FALSE
;
112 void wxApp::CleanUp()
114 delete wxWidgetHashTable
;
115 wxWidgetHashTable
= NULL
;
117 wxModule::CleanUpModules();
119 #if wxUSE_WX_RESOURCES
120 wxCleanUpResourceSystem();
123 delete wxTheColourDatabase
;
124 wxTheColourDatabase
= NULL
;
126 wxDeleteStockObjects();
128 wxDeleteStockLists();
133 wxClassInfo::CleanUpClasses();
136 delete wxPendingEvents
;
137 delete wxPendingEventsLocker
;
140 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
141 // At this point we want to check if there are any memory
142 // blocks that aren't part of the wxDebugContext itself,
143 // as a special case. Then when dumping we need to ignore
144 // wxDebugContext, too.
145 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
147 wxLogDebug("There were memory leaks.");
148 wxDebugContext::Dump();
149 wxDebugContext::PrintStatistics();
153 // do it as the very last thing because everything else can log messages
154 wxLog::DontCreateOnDemand();
155 // do it as the very last thing because everything else can log messages
156 delete wxLog::SetActiveTarget(NULL
);
159 // This is set within wxEntryStart -- too early on
160 // to put these in wxTheApp
161 static int g_newArgc
= 0;
162 static wxChar
** g_newArgv
= NULL
;
164 // NB: argc and argv may be changed here, pass by reference!
165 int wxEntryStart( int& argc
, char *argv
[] )
168 // install the X error handler
169 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
170 #endif // __WXDEBUG__
174 // Parse the arguments.
177 Display
* xdisplay
= XOpenDisplay(NULL
);
181 wxLogError( _("wxWindows could not open display. Exiting.") );
185 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
187 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
189 // wxSetDetectableAutoRepeat( TRUE );
191 if (!wxApp::Initialize())
202 if ( !wxTheApp
->OnInitGui() )
209 int wxEntry( int argc
, char *argv
[] )
211 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
212 // This seems to be necessary since there are 'rogue'
213 // objects present at this point (perhaps global objects?)
214 // Setting a checkpoint will ignore them as far as the
215 // memory checking facility is concerned.
216 // Of course you may argue that memory allocated in globals should be
217 // checked, but this is a reasonable compromise.
218 wxDebugContext::SetCheckpoint();
220 int err
= wxEntryStart(argc
, argv
);
226 if (!wxApp::GetInitializerFunction())
228 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
232 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
237 printf( "wxWindows error: wxTheApp == NULL\n" );
241 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
242 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
244 // The command line may have been changed
245 // by stripping out -display etc.
248 wxTheApp
->argc
= g_newArgc
;
249 wxTheApp
->argv
= g_newArgv
;
253 wxTheApp
->argc
= argc
;
254 wxTheApp
->argv
= argv
;
258 retValue
= wxEntryInitGui();
260 // Here frames insert themselves automatically into wxTopLevelWindows by
261 // getting created in OnInit().
264 if ( !wxTheApp
->OnInit() )
270 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
273 // flush the logged messages if any
274 wxLog
*pLog
= wxLog::GetActiveTarget();
275 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
278 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
279 // for further messages
281 if (wxTheApp
->GetTopWindow())
283 delete wxTheApp
->GetTopWindow();
284 wxTheApp
->SetTopWindow(NULL
);
287 wxTheApp
->DeletePendingObjects();
296 // Static member initialization
297 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
304 m_wantDebugOutput
= TRUE
;
308 m_exitOnFrameDelete
= TRUE
;
309 m_mainColormap
= (WXColormap
) NULL
;
310 m_topLevelWidget
= (WXWindow
) NULL
;
311 m_maxRequestSize
= 0;
315 bool wxApp::Initialized()
323 int wxApp::MainLoop()
326 m_mainLoop
= new wxEventLoop
;
328 rt
= m_mainLoop
->Run();
335 // Processes an X event.
336 void wxApp::ProcessXEvent(WXEvent
* _event
)
338 XEvent
* event
= (XEvent
*) _event
;
340 wxWindow
* win
= NULL
;
341 Window window
= event
->xany
.window
;
342 Window actualWindow
= window
;
344 // Find the first wxWindow that corresponds to this event window
345 // TODO: may need to translate coordinates from actualWindow
346 // to window, if the receiving window != wxWindow window
347 // while (window && !(win = wxGetWindowFromTable(window)))
348 // window = wxGetWindowParent(window);
350 // Because we're receiving events after a window
351 // has been destroyed, assume a 1:1 match between
352 // Window and wxWindow, so if it's not in the table,
353 // it must have been destroyed.
355 win
= wxGetWindowFromTable(window
);
363 if (win
&& !win
->IsEnabled())
369 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
370 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
372 wxLogDebug( "OnKey from %s", win
->GetName().c_str() );
374 // We didn't process wxEVT_KEY_DOWN, so send
376 if (!win
->GetEventHandler()->ProcessEvent( keyEvent
))
378 keyEvent
.SetEventType(wxEVT_CHAR
);
379 win
->GetEventHandler()->ProcessEvent( keyEvent
);
382 // We intercepted and processed the key down event
390 if (win
&& !win
->IsEnabled())
395 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
396 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
398 win
->GetEventHandler()->ProcessEvent( keyEvent
);
404 HandlePropertyChange(_event
);
409 if (win
&& !win
->IsEnabled())
412 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);;
413 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);;
415 if (event
->xclient
.message_type
== wm_protocols
)
417 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
427 case ConfigureNotify
:
431 wxSizeEvent
sizeEvent( wxSize(event
->xconfigure
.width
,event
->xconfigure
.height
), win
->GetId() );
432 sizeEvent
.SetEventObject( win
);
434 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
439 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
440 * If resize event, don't resize until the last resize event for this
441 * window is recieved. Prevents flicker as windows are resized.
444 Display
*disp
= (Display
*) wxGetDisplay();
449 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
451 // TODO: when implementing refresh optimization, we can use
452 // XtAddExposureToRegion to expand the window's paint region.
456 wxSize sz
= win
->GetSize();
457 wxSizeEvent
sizeEvent(sz
, win
->GetId());
458 sizeEvent
.SetEventObject(win
);
460 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
469 win
->GetUpdateRegion().Union( event
->xexpose
.x
, event
->xexpose
.y
,
470 event
->xexpose
.width
, event
->xexpose
.height
);
472 win
->GetClearRegion().Union( event
->xexpose
.x
, event
->xexpose
.y
,
473 event
->xexpose
.width
, event
->xexpose
.height
);
475 // if (event->xexpose.count == 0)
487 if (win
&& !win
->IsEnabled())
492 wxMouseEvent wxevent
;
493 wxTranslateMouseEvent(wxevent
, win
, window
, event
);
494 win
->GetEventHandler()->ProcessEvent( wxevent
);
500 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
502 wxLogDebug( "FocusIn from %s", win
->GetName().c_str() );
504 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
505 focusEvent
.SetEventObject(win
);
506 win
->GetEventHandler()->ProcessEvent(focusEvent
);
512 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
514 wxLogDebug( "FocusOut from %s\n", win
->GetName().c_str() );
516 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
517 focusEvent
.SetEventObject(win
);
518 win
->GetEventHandler()->ProcessEvent(focusEvent
);
524 // Do we want to process this (for top-level windows)?
525 // But we want to be able to veto closes, anyway
531 //wxString eventName = wxGetXEventName(XEvent& event);
532 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
539 // Returns TRUE if more time is needed.
540 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
541 // but ProcessIdle may be needed by apps, so is kept.
542 bool wxApp::ProcessIdle()
545 event
.SetEventObject(this);
548 return event
.MoreRequested();
551 void wxApp::ExitMainLoop()
557 // Is a message/event pending?
558 bool wxApp::Pending()
560 return wxEventLoop::GetActive()->Pending();
563 // Dispatch a message.
564 void wxApp::Dispatch()
566 wxEventLoop::GetActive()->Dispatch();
569 // This should be redefined in a derived class for
570 // handling property change events for XAtom IPC.
571 void wxApp::HandlePropertyChange(WXEvent
*event
)
573 // by default do nothing special
574 // TODO: what to do for X11
575 // XtDispatchEvent((XEvent*) event); /* let Motif do the work */
578 void wxApp::OnIdle(wxIdleEvent
& event
)
580 static bool s_inOnIdle
= FALSE
;
582 // Avoid recursion (via ProcessEvent default case)
588 // Resend in the main thread events which have been prepared in other
590 ProcessPendingEvents();
592 // 'Garbage' collection of windows deleted with Close()
593 DeletePendingObjects();
595 // Send OnIdle events to all windows
596 bool needMore
= SendIdleEvents();
599 event
.RequestMore(TRUE
);
606 // **** please implement me! ****
607 // Wake up the idle handler processor, even if it is in another thread...
611 // Send idle event to all top-level windows
612 bool wxApp::SendIdleEvents()
614 bool needMore
= FALSE
;
616 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
619 wxWindow
* win
= node
->GetData();
620 if (SendIdleEvents(win
))
622 node
= node
->GetNext();
628 // Send idle event to window and all subwindows
629 bool wxApp::SendIdleEvents(wxWindow
* win
)
631 bool needMore
= FALSE
;
634 event
.SetEventObject(win
);
636 win
->GetEventHandler()->ProcessEvent(event
);
638 win
->OnInternalIdle();
640 if (event
.MoreRequested())
643 wxNode
* node
= win
->GetChildren().First();
646 wxWindow
* win
= (wxWindow
*) node
->Data();
647 if (SendIdleEvents(win
))
656 void wxApp::DeletePendingObjects()
658 wxNode
*node
= wxPendingDelete
.First();
661 wxObject
*obj
= (wxObject
*)node
->Data();
665 if (wxPendingDelete
.Member(obj
))
668 // Deleting one object may have deleted other pending
669 // objects, so start from beginning of list again.
670 node
= wxPendingDelete
.First();
674 // Create an application context
675 bool wxApp::OnInitGui()
677 // Eventually this line will be removed, but for
678 // now we don't want to try popping up a dialog
679 // for error messages.
680 delete wxLog::SetActiveTarget(new wxLogStderr
);
682 if (!wxAppBase::OnInitGui())
686 GetMainColormap( wxApp::GetDisplay() );
687 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
692 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
694 if (!display
) /* Must be called first with non-NULL display */
695 return m_mainColormap
;
697 int defaultScreen
= DefaultScreen((Display
*) display
);
698 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
700 Colormap c
= DefaultColormapOfScreen(screen
);
703 m_mainColormap
= (WXColormap
) c
;
705 return (WXColormap
) c
;
708 Window
wxGetWindowParent(Window window
)
710 wxASSERT_MSG( window
, "invalid window" );
714 Window parent
, root
= 0;
715 unsigned int noChildren
= 0;
716 Window
* children
= NULL
;
717 int res
= XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
718 & children
, & noChildren
);
731 retValue
= wxTheApp
->OnExit();
735 * Exit in some platform-specific way. Not recommended that the app calls this:
736 * only for emergencies.
741 // Yield to other processes
743 bool wxApp::Yield(bool onlyIfNeeded
)
745 bool s_inYield
= FALSE
;
751 wxFAIL_MSG( wxT("wxYield called recursively" ) );
759 while (wxTheApp
&& wxTheApp
->Pending())
760 wxTheApp
->Dispatch();
767 // TODO use XmGetPixmap (?) to get the really standard icons!
769 // XPM hack: make the arrays const
770 #define static static const
772 #include "wx/generic/info.xpm"
773 #include "wx/generic/error.xpm"
774 #include "wx/generic/question.xpm"
775 #include "wx/generic/warning.xpm"
780 wxApp::GetStdIcon(int which
) const
784 case wxICON_INFORMATION
:
785 return wxIcon(info_xpm
);
787 case wxICON_QUESTION
:
788 return wxIcon(question_xpm
);
790 case wxICON_EXCLAMATION
:
791 return wxIcon(warning_xpm
);
794 wxFAIL_MSG("requested non existent standard icon");
795 // still fall through
798 return wxIcon(error_xpm
);
802 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
804 // While the GUI isn't working that well, just print out the
807 wxAppBase::OnAssert(file
, line
, msg
);
810 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);