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
)
69 static const wxCmdLineEntryDesc g_cmdLineDesc
[] =
71 { wxCMD_LINE_SWITCH
, "sync", "sync", "synchronize the display" },
72 { wxCMD_LINE_OPTION
, "display", "display", "use the given display", wxCMD_LINE_VAL_STRING
},
78 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
80 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
82 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
84 // just forward to the default handler for now
85 return gs_pfnXErrorHandler(dpy
, xevent
);
89 long wxApp::sm_lastMessageTime
= 0;
90 WXDisplay
*wxApp::ms_display
= NULL
;
92 bool wxApp::Initialize()
94 wxClassInfo::InitializeClasses();
96 // GL: I'm annoyed ... I don't know where to put this and I don't want to
97 // create a module for that as it's part of the core.
99 wxPendingEventsLocker
= new wxCriticalSection();
102 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
103 wxTheColourDatabase
->Initialize();
105 wxInitializeStockLists();
106 wxInitializeStockObjects();
108 #if wxUSE_WX_RESOURCES
109 wxInitializeResourceSystem();
112 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
114 wxModule::RegisterModules();
115 if (!wxModule::InitializeModules()) return FALSE
;
120 void wxApp::CleanUp()
122 delete wxWidgetHashTable
;
123 wxWidgetHashTable
= NULL
;
125 wxModule::CleanUpModules();
127 #if wxUSE_WX_RESOURCES
128 wxCleanUpResourceSystem();
131 delete wxTheColourDatabase
;
132 wxTheColourDatabase
= NULL
;
134 wxDeleteStockObjects();
136 wxDeleteStockLists();
141 wxClassInfo::CleanUpClasses();
144 delete wxPendingEvents
;
145 delete wxPendingEventsLocker
;
148 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
149 // At this point we want to check if there are any memory
150 // blocks that aren't part of the wxDebugContext itself,
151 // as a special case. Then when dumping we need to ignore
152 // wxDebugContext, too.
153 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
155 wxLogDebug("There were memory leaks.\n");
156 wxDebugContext::Dump();
157 wxDebugContext::PrintStatistics();
161 // do it as the very last thing because everything else can log messages
162 wxLog::DontCreateOnDemand();
163 // do it as the very last thing because everything else can log messages
164 delete wxLog::SetActiveTarget(NULL
);
167 // This is set within wxEntryStart -- too early on
168 // to put these in wxTheApp
169 static int g_newArgc
= 0;
170 static wxChar
** g_newArgv
= NULL
;
172 // NB: argc and argv may be changed here, pass by reference!
173 int wxEntryStart( int& argc
, char *argv
[] )
176 // install the X error handler
177 gs_pfnXErrorHandler
= XSetErrorHandler( wxXErrorHandler
);
178 #endif // __WXDEBUG__
182 // Parse the arguments. Is it OK to use the command line
183 // parser before calling Initialize?
184 wxCmdLineParser
cmdLine(argv
, argv
);
187 Display
* xdisplay
= XOpenDisplay(NULL
);
191 wxLogError( _("wxWindows could not open display. Exiting.") );
195 wxApp::ms_display
= (WXDisplay
*) xdisplay
;
197 XSelectInput( xdisplay
, XDefaultRootWindow(xdisplay
), PropertyChangeMask
);
199 // wxSetDetectableAutoRepeat( TRUE );
201 if (!wxApp::Initialize())
212 if ( !wxTheApp
->OnInitGui() )
219 int wxEntry( int argc
, char *argv
[] )
221 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
222 // This seems to be necessary since there are 'rogue'
223 // objects present at this point (perhaps global objects?)
224 // Setting a checkpoint will ignore them as far as the
225 // memory checking facility is concerned.
226 // Of course you may argue that memory allocated in globals should be
227 // checked, but this is a reasonable compromise.
228 wxDebugContext::SetCheckpoint();
230 int err
= wxEntryStart(argc
, argv
);
236 if (!wxApp::GetInitializerFunction())
238 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
242 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
247 printf( "wxWindows error: wxTheApp == NULL\n" );
251 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
252 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
254 // The command line may have been changed
255 // by stripping out -display etc.
258 wxTheApp
->argc
= g_newArgc
;
259 wxTheApp
->argv
= g_newArgv
;
263 wxTheApp
->argc
= argc
;
264 wxTheApp
->argv
= argv
;
268 retValue
= wxEntryInitGui();
270 // Here frames insert themselves automatically into wxTopLevelWindows by
271 // getting created in OnInit().
274 if ( !wxTheApp
->OnInit() )
280 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
283 // flush the logged messages if any
284 wxLog
*pLog
= wxLog::GetActiveTarget();
285 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
288 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
289 // for further messages
291 if (wxTheApp
->GetTopWindow())
293 delete wxTheApp
->GetTopWindow();
294 wxTheApp
->SetTopWindow(NULL
);
297 wxTheApp
->DeletePendingObjects();
306 // Static member initialization
307 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
314 m_wantDebugOutput
= TRUE
;
318 m_exitOnFrameDelete
= TRUE
;
319 m_mainColormap
= (WXColormap
) NULL
;
320 m_topLevelWidget
= (WXWindow
) NULL
;
321 m_maxRequestSize
= 0;
325 bool wxApp::Initialized()
333 int wxApp::MainLoop()
336 m_mainLoop
= new wxEventLoop
;
338 rt
= m_mainLoop
->Run();
345 // Processes an X event.
346 void wxApp::ProcessXEvent(WXEvent
* _event
)
348 XEvent
* event
= (XEvent
*) _event
;
350 wxWindow
* win
= NULL
;
351 Window window
= event
->xany
.window
;
352 Window actualWindow
= window
;
354 // Find the first wxWindow that corresponds to this event window
355 // TODO: may need to translate coordinates from actualWindow
356 // to window, if the receiving window != wxWindow window
357 // while (window && !(win = wxGetWindowFromTable(window)))
358 // window = wxGetWindowParent(window);
360 // Because we're receiving events after a window
361 // has been destroyed, assume a 1:1 match between
362 // Window and wxWindow, so if it's not in the table,
363 // it must have been destroyed.
365 win
= wxGetWindowFromTable(window
);
373 if (win
&& !win
->IsEnabled())
379 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
380 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
382 // We didn't process wxEVT_KEY_DOWN, so send
384 if (!win
->GetEventHandler()->ProcessEvent( keyEvent
))
386 keyEvent
.SetEventType(wxEVT_CHAR
);
387 win
->GetEventHandler()->ProcessEvent( keyEvent
);
390 // We intercepted and processed the key down event
398 if (win
&& !win
->IsEnabled())
403 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
404 wxTranslateKeyEvent(keyEvent
, win
, window
, event
);
406 win
->GetEventHandler()->ProcessEvent( keyEvent
);
412 HandlePropertyChange(_event
);
417 Atom wm_delete_window
= XInternAtom(wxGlobalDisplay(), "WM_DELETE_WINDOW", True
);;
418 Atom wm_protocols
= XInternAtom(wxGlobalDisplay(), "WM_PROTOCOLS", True
);;
420 if (event
->xclient
.message_type
== wm_protocols
)
422 if ((Atom
) (event
->xclient
.data
.l
[0]) == wm_delete_window
)
432 case ConfigureNotify
:
436 wxSizeEvent
sizeEvent( wxSize(event
->xconfigure
.width
,event
->xconfigure
.height
), win
->GetId() );
437 sizeEvent
.SetEventObject( win
);
439 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
444 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
445 * If resize event, don't resize until the last resize event for this
446 * window is recieved. Prevents flicker as windows are resized.
449 Display
*disp
= (Display
*) wxGetDisplay();
454 while( XCheckTypedWindowEvent (disp
, actualWindow
, ResizeRequest
, &report
));
456 // TODO: when implementing refresh optimization, we can use
457 // XtAddExposureToRegion to expand the window's paint region.
461 wxSize sz
= win
->GetSize();
462 wxSizeEvent
sizeEvent(sz
, win
->GetId());
463 sizeEvent
.SetEventObject(win
);
465 win
->GetEventHandler()->ProcessEvent( sizeEvent
);
474 // Schedule update for later
475 win
->GetUpdateRegion().Union( event
->xexpose
.x
, event
->xexpose
.y
,
476 event
->xexpose
.width
, event
->xexpose
.height
);
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 wxFocusEvent
focusEvent(wxEVT_SET_FOCUS
, win
->GetId());
503 focusEvent
.SetEventObject(win
);
504 win
->GetEventHandler()->ProcessEvent(focusEvent
);
510 if (win
&& event
->xfocus
.detail
!= NotifyPointer
)
512 wxFocusEvent
focusEvent(wxEVT_KILL_FOCUS
, win
->GetId());
513 focusEvent
.SetEventObject(win
);
514 win
->GetEventHandler()->ProcessEvent(focusEvent
);
520 // Do we want to process this (for top-level windows)?
521 // But we want to be able to veto closes, anyway
527 //wxString eventName = wxGetXEventName(XEvent& event);
528 //wxLogDebug(wxT("Event %s not handled"), eventName.c_str());
535 // Returns TRUE if more time is needed.
536 // Note that this duplicates wxEventLoopImpl::SendIdleEvent
537 // but ProcessIdle may be needed by apps, so is kept.
538 bool wxApp::ProcessIdle()
541 event
.SetEventObject(this);
544 return event
.MoreRequested();
547 void wxApp::ExitMainLoop()
553 // Is a message/event pending?
554 bool wxApp::Pending()
556 return wxEventLoop::GetActive()->Pending();
559 // Dispatch a message.
560 void wxApp::Dispatch()
562 wxEventLoop::GetActive()->Dispatch();
565 // This should be redefined in a derived class for
566 // handling property change events for XAtom IPC.
567 void wxApp::HandlePropertyChange(WXEvent
*event
)
569 // by default do nothing special
570 // TODO: what to do for X11
571 // XtDispatchEvent((XEvent*) event); /* let Motif do the work */
574 void wxApp::OnIdle(wxIdleEvent
& event
)
576 static bool s_inOnIdle
= FALSE
;
578 // Avoid recursion (via ProcessEvent default case)
584 // Resend in the main thread events which have been prepared in other
586 ProcessPendingEvents();
588 // 'Garbage' collection of windows deleted with Close()
589 DeletePendingObjects();
591 // Send OnIdle events to all windows
592 bool needMore
= SendIdleEvents();
595 event
.RequestMore(TRUE
);
602 // **** please implement me! ****
603 // Wake up the idle handler processor, even if it is in another thread...
607 // Send idle event to all top-level windows
608 bool wxApp::SendIdleEvents()
610 bool needMore
= FALSE
;
612 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
615 wxWindow
* win
= node
->GetData();
616 if (SendIdleEvents(win
))
618 node
= node
->GetNext();
624 // Send idle event to window and all subwindows
625 bool wxApp::SendIdleEvents(wxWindow
* win
)
627 bool needMore
= FALSE
;
630 event
.SetEventObject(win
);
632 win
->GetEventHandler()->ProcessEvent(event
);
634 win
->OnInternalIdle();
636 if (event
.MoreRequested())
639 wxNode
* node
= win
->GetChildren().First();
642 wxWindow
* win
= (wxWindow
*) node
->Data();
643 if (SendIdleEvents(win
))
652 void wxApp::DeletePendingObjects()
654 wxNode
*node
= wxPendingDelete
.First();
657 wxObject
*obj
= (wxObject
*)node
->Data();
661 if (wxPendingDelete
.Member(obj
))
664 // Deleting one object may have deleted other pending
665 // objects, so start from beginning of list again.
666 node
= wxPendingDelete
.First();
670 // Create an application context
671 bool wxApp::OnInitGui()
673 // Eventually this line will be removed, but for
674 // now we don't want to try popping up a dialog
675 // for error messages.
676 delete wxLog::SetActiveTarget(new wxLogStderr
);
678 if (!wxAppBase::OnInitGui())
682 GetMainColormap( wxApp::GetDisplay() );
683 m_maxRequestSize
= XMaxRequestSize( (Display
*) wxApp::GetDisplay() );
688 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
690 if (!display
) /* Must be called first with non-NULL display */
691 return m_mainColormap
;
693 int defaultScreen
= DefaultScreen((Display
*) display
);
694 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
696 Colormap c
= DefaultColormapOfScreen(screen
);
699 m_mainColormap
= (WXColormap
) c
;
701 return (WXColormap
) c
;
704 Window
wxGetWindowParent(Window window
)
706 Window parent
, root
= 0;
707 unsigned int noChildren
= 0;
708 Window
* children
= NULL
;
709 int res
= XQueryTree((Display
*) wxGetDisplay(), window
, & root
, & parent
,
710 & children
, & noChildren
);
723 retValue
= wxTheApp
->OnExit();
727 * Exit in some platform-specific way. Not recommended that the app calls this:
728 * only for emergencies.
733 // Yield to other processes
735 bool wxApp::Yield(bool onlyIfNeeded
)
737 bool s_inYield
= FALSE
;
743 wxFAIL_MSG( wxT("wxYield called recursively" ) );
751 while (wxTheApp
&& wxTheApp
->Pending())
752 wxTheApp
->Dispatch();
759 // TODO use XmGetPixmap (?) to get the really standard icons!
761 // XPM hack: make the arrays const
762 #define static static const
764 #include "wx/generic/info.xpm"
765 #include "wx/generic/error.xpm"
766 #include "wx/generic/question.xpm"
767 #include "wx/generic/warning.xpm"
772 wxApp::GetStdIcon(int which
) const
776 case wxICON_INFORMATION
:
777 return wxIcon(info_xpm
);
779 case wxICON_QUESTION
:
780 return wxIcon(question_xpm
);
782 case wxICON_EXCLAMATION
:
783 return wxIcon(warning_xpm
);
786 wxFAIL_MSG("requested non existent standard icon");
787 // still fall through
790 return wxIcon(error_xpm
);
794 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
796 // While the GUI isn't working that well, just print out the
799 wxAppBase::OnAssert(file
, line
, msg
);
802 msg2
.Printf("At file %s:%d: %s", file
, line
, msg
);