1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "app.h"
17 #define XtParent XTPARENT
18 #define XtDisplay XTDISPLAY
24 #include "wx/gdicmn.h"
27 #include "wx/cursor.h"
29 #include "wx/palette.h"
31 #include "wx/dialog.h"
32 #include "wx/msgdlg.h"
34 #include "wx/module.h"
35 #include "wx/memory.h"
40 #include "wx/thread.h"
43 #if wxUSE_WX_RESOURCES
44 #include "wx/resource.h"
48 #pragma message disable nosimpint
52 #include <X11/Xutil.h>
53 #include <X11/Xresource.h>
54 #include <X11/Xatom.h>
56 #pragma message enable nosimpint
59 #include "wx/motif/private.h"
63 extern wxList wxPendingDelete
;
65 wxApp
*wxTheApp
= NULL
;
67 wxHashTable
*wxWidgetHashTable
= NULL
;
69 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
71 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
72 EVT_IDLE(wxApp::OnIdle
)
76 typedef int (*XErrorHandlerFunc
)(Display
*, XErrorEvent
*);
78 XErrorHandlerFunc gs_pfnXErrorHandler
= 0;
80 static int wxXErrorHandler(Display
*dpy
, XErrorEvent
*xevent
)
82 // just forward to the default handler for now
83 return gs_pfnXErrorHandler(dpy
, xevent
);
87 long wxApp::sm_lastMessageTime
= 0;
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 // For PostScript printing
111 /* Done using wxModule now
112 wxInitializePrintSetupData();
113 wxThePrintPaperDatabase = new wxPrintPaperDatabase;
114 wxThePrintPaperDatabase->CreateDatabase();
118 wxBitmap::InitStandardHandlers();
120 wxWidgetHashTable
= new wxHashTable(wxKEY_INTEGER
);
122 wxModule::RegisterModules();
123 if (!wxModule::InitializeModules()) return FALSE
;
128 void wxApp::CleanUp()
130 delete wxWidgetHashTable
;
131 wxWidgetHashTable
= NULL
;
133 wxModule::CleanUpModules();
135 #if wxUSE_WX_RESOURCES
136 wxCleanUpResourceSystem();
139 wxDeleteStockObjects() ;
141 // Destroy all GDI lists, etc.
143 wxDeleteStockLists();
145 delete wxTheColourDatabase
;
146 wxTheColourDatabase
= NULL
;
149 /* Done using wxModule now
150 wxInitializePrintSetupData(FALSE);
151 delete wxThePrintPaperDatabase;
152 wxThePrintPaperDatabase = NULL;
156 wxBitmap::CleanUpHandlers();
158 wxClassInfo::CleanUpClasses();
163 // GL: I'm annoyed ... I don't know where to put this and I don't want to
164 // create a module for that as it's part of the core.
166 delete wxPendingEvents
;
167 delete wxPendingEventsLocker
;
170 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
171 // At this point we want to check if there are any memory
172 // blocks that aren't part of the wxDebugContext itself,
173 // as a special case. Then when dumping we need to ignore
174 // wxDebugContext, too.
175 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
177 wxLogDebug("There were memory leaks.\n");
178 wxDebugContext::Dump();
179 wxDebugContext::PrintStatistics();
183 // do it as the very last thing because everything else can log messages
184 wxLog::DontCreateOnDemand();
185 // do it as the very last thing because everything else can log messages
186 delete wxLog::SetActiveTarget(NULL
);
189 int wxEntry( int argc
, char *argv
[] )
191 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
192 // This seems to be necessary since there are 'rogue'
193 // objects present at this point (perhaps global objects?)
194 // Setting a checkpoint will ignore them as far as the
195 // memory checking facility is concerned.
196 // Of course you may argue that memory allocated in globals should be
197 // checked, but this is a reasonable compromise.
198 wxDebugContext::SetCheckpoint();
201 if (!wxApp::Initialize())
206 if (!wxApp::GetInitializerFunction())
208 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
212 wxTheApp
= (wxApp
*) (* wxApp::GetInitializerFunction()) ();
217 printf( "wxWindows error: wxTheApp == NULL\n" );
221 wxTheApp
->SetClassName(wxFileNameFromPath(argv
[0]));
222 wxTheApp
->SetAppName(wxFileNameFromPath(argv
[0]));
224 wxTheApp
->argc
= argc
;
225 wxTheApp
->argv
= argv
;
227 // GUI-specific initialization, such as creating an app context.
228 wxTheApp
->OnInitGui();
230 // Here frames insert themselves automatically into wxTopLevelWindows by
231 // getting created in OnInit().
234 if (wxTheApp
->OnInit())
236 if (wxTheApp
->Initialized()) retValue
= wxTheApp
->OnRun();
239 // flush the logged messages if any
240 wxLog
*pLog
= wxLog::GetActiveTarget();
241 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
244 delete wxLog::SetActiveTarget(new wxLogStderr
); // So dialog boxes aren't used
245 // for further messages
247 if (wxTheApp
->GetTopWindow())
249 delete wxTheApp
->GetTopWindow();
250 wxTheApp
->SetTopWindow(NULL
);
253 wxTheApp
->DeletePendingObjects();
262 // Static member initialization
263 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
270 m_mainColormap
= (WXColormap
) NULL
;
271 m_appContext
= (WXAppContext
) NULL
;
272 m_topLevelWidget
= (WXWidget
) NULL
;
273 m_maxRequestSize
= 0;
274 m_initialDisplay
= (WXDisplay
*) 0;
277 bool wxApp::Initialized()
285 int wxApp::MainLoop()
290 * Sit around forever waiting to process X-events. Property Change
291 * event are handled special, because they have to refer to
292 * the root window rather than to a widget. therefore we can't
293 * use an Xt-eventhandler.
296 XSelectInput(XtDisplay((Widget
) wxTheApp
->GetTopLevelWidget()),
297 XDefaultRootWindow(XtDisplay((Widget
) wxTheApp
->GetTopLevelWidget())),
302 // Use this flag to allow breaking the loop via wxApp::ExitMainLoop()
305 XtAppNextEvent( (XtAppContext
) wxTheApp
->GetAppContext(), &event
);
307 ProcessXEvent((WXEvent
*) & event
);
309 if (XtAppPending( (XtAppContext
) wxTheApp
->GetAppContext() ) == 0)
314 // leave the main loop to give other threads a chance to
315 // perform their GUI work
328 // Processes an X event.
329 void wxApp::ProcessXEvent(WXEvent
* _event
)
331 XEvent
* event
= (XEvent
*) _event
;
333 if (event
->type
== KeyPress
)
335 #if 0 // def __WXDEBUG__
336 Widget widget
= XtWindowToWidget(event
->xany
.display
, event
->xany
.window
);
337 wxLogDebug("Got key press event for 0x%08x (parent = 0x%08x)",
338 widget
, XtParent(widget
));
341 if (CheckForAccelerator(_event
))
343 // Do nothing! We intercepted and processed the event as an
348 // It seemed before that this hack was redundant and
349 // key down events were being generated by wxCanvasInputEvent.
350 // But no longer - why ???
352 else if (CheckForKeyDown(_event
))
354 // We intercepted and processed the key down event
360 XtDispatchEvent(event
);
364 else if (event
->type
== KeyRelease
)
366 // TODO: work out why we still need this ! -michael
368 if (CheckForKeyUp(_event
))
370 // We intercepted and processed the key up event
375 XtDispatchEvent(event
);
379 else if (event
->type
== PropertyNotify
)
381 HandlePropertyChange(_event
);
384 else if (event
->type
== ResizeRequest
)
386 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
387 * If resize event, don't resize until the last resize event for this
388 * window is recieved. Prevents flicker as windows are resized.
391 Display
*disp
= XtDisplay((Widget
) wxTheApp
->GetTopLevelWidget());
392 Window win
= event
->xany
.window
;
397 while( XCheckTypedWindowEvent (disp
, win
, ResizeRequest
, &report
));
399 // TODO: when implementing refresh optimization, we can use
400 // XtAddExposureToRegion to expand the window's paint region.
402 XtDispatchEvent(event
);
406 XtDispatchEvent(event
);
410 // Returns TRUE if more time is needed.
411 bool wxApp::ProcessIdle()
414 event
.SetEventObject(this);
417 return event
.MoreRequested();
420 void wxApp::ExitMainLoop()
425 // Is a message/event pending?
426 bool wxApp::Pending()
428 XFlush(XtDisplay( (Widget
) wxTheApp
->GetTopLevelWidget() ));
430 // Fix by Doug from STI, to prevent a stall if non-X event
432 return ((XtAppPending( (XtAppContext
) GetAppContext() ) & XtIMXEvent
) != 0) ;
435 // Dispatch a message.
436 void wxApp::Dispatch()
438 // XtAppProcessEvent( (XtAppContext) wxTheApp->GetAppContext(), XtIMAll);
441 XtAppNextEvent((XtAppContext
) GetAppContext(), &event
);
442 ProcessXEvent((WXEvent
*) & event
);
445 // This should be redefined in a derived class for
446 // handling property change events for XAtom IPC.
447 void wxApp::HandlePropertyChange(WXEvent
*event
)
449 // by default do nothing special
450 XtDispatchEvent((XEvent
*) event
); /* let Motif do the work */
453 void wxApp::OnIdle(wxIdleEvent
& event
)
455 static bool inOnIdle
= FALSE
;
457 // Avoid recursion (via ProcessEvent default case)
463 // If there are pending events, we must process them: pending events
464 // are either events to the threads other than main or events posted
465 // with wxPostEvent() functions
466 // GRG: I have moved this here so that all pending events are processed
467 // before starting to delete any objects. This behaves better (in
468 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
469 // behaviour. Also removed the '#if wxUSE_THREADS' around it.
470 // Changed Mar/2000 before 2.1.14
472 // Flush pending events.
473 ProcessPendingEvents();
475 // 'Garbage' collection of windows deleted with Close().
476 DeletePendingObjects();
478 // flush the logged messages if any
479 wxLog
*pLog
= wxLog::GetActiveTarget();
480 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
483 // Send OnIdle events to all windows
484 bool needMore
= SendIdleEvents();
487 event
.RequestMore(TRUE
);
494 // **** please implement me! ****
495 // Wake up the idle handler processor, even if it is in another thread...
499 // Send idle event to all top-level windows
500 bool wxApp::SendIdleEvents()
502 bool needMore
= FALSE
;
504 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
507 wxWindow
* win
= node
->GetData();
508 if (SendIdleEvents(win
))
510 node
= node
->GetNext();
516 // Send idle event to window and all subwindows
517 bool wxApp::SendIdleEvents(wxWindow
* win
)
519 bool needMore
= FALSE
;
522 event
.SetEventObject(win
);
523 win
->ProcessEvent(event
);
525 if (event
.MoreRequested())
528 wxWindowList::Node
* node
= win
->GetChildren().GetFirst();
531 wxWindow
* win
= node
->GetData();
532 if (SendIdleEvents(win
))
535 node
= node
->GetNext();
540 void wxApp::DeletePendingObjects()
542 wxNode
*node
= wxPendingDelete
.GetFirst();
545 wxObject
*obj
= node
->GetData();
549 if (wxPendingDelete
.Member(obj
))
552 // Deleting one object may have deleted other pending
553 // objects, so start from beginning of list again.
554 node
= wxPendingDelete
.GetFirst();
558 static char *fallbackResources
[] = {
559 "*menuBar.marginHeight: 0",
560 "*menuBar.shadowThickness: 1",
561 "*background: #c0c0c0",
562 "*foreground: black",
566 // Create an application context
567 bool wxApp::OnInitGui()
569 if( !wxAppBase::OnInitGui() )
572 XtToolkitInitialize() ;
573 wxTheApp
->m_appContext
= (WXAppContext
) XtCreateApplicationContext();
574 XtAppSetFallbackResources((XtAppContext
) wxTheApp
->m_appContext
, fallbackResources
);
576 Display
*dpy
= XtOpenDisplay((XtAppContext
) wxTheApp
->m_appContext
,(String
)NULL
,NULL
,
577 (const char*) wxTheApp
->GetClassName(), NULL
, 0,
578 # if XtSpecificationRelease < 5
586 // if you don't log to stderr, nothing will be shown...
587 delete wxLog::SetActiveTarget(new wxLogStderr
);
588 wxString
className(wxTheApp
->GetClassName());
589 wxLogError(_("wxWindows could not open display for '%s': exiting."),
590 (const char*) className
);
593 m_initialDisplay
= (WXDisplay
*) dpy
;
596 // install the X error handler
597 gs_pfnXErrorHandler
= XSetErrorHandler(wxXErrorHandler
);
598 #endif // __WXDEBUG__
600 wxTheApp
->m_topLevelWidget
= (WXWidget
) XtAppCreateShell((String
)NULL
, (const char*) wxTheApp
->GetClassName(),
601 applicationShellWidgetClass
,dpy
,
604 // Add general resize proc
606 rec
.string
= "resize";
607 rec
.proc
= (XtActionProc
)wxWidgetResizeProc
;
608 XtAppAddActions((XtAppContext
) wxTheApp
->m_appContext
, &rec
, 1);
610 GetMainColormap(dpy
);
611 m_maxRequestSize
= XMaxRequestSize((Display
*) dpy
);
616 WXColormap
wxApp::GetMainColormap(WXDisplay
* display
)
618 if (!display
) /* Must be called first with non-NULL display */
619 return m_mainColormap
;
621 int defaultScreen
= DefaultScreen((Display
*) display
);
622 Screen
* screen
= XScreenOfDisplay((Display
*) display
, defaultScreen
);
624 Colormap c
= DefaultColormapOfScreen(screen
);
627 m_mainColormap
= (WXColormap
) c
;
629 return (WXColormap
) c
;
632 // Returns TRUE if an accelerator has been processed
633 bool wxApp::CheckForAccelerator(WXEvent
* event
)
635 XEvent
* xEvent
= (XEvent
*) event
;
636 if (xEvent
->xany
.type
== KeyPress
)
638 // Find a wxWindow for this window
639 // TODO: should get display for the window, not the current display
640 Widget widget
= XtWindowToWidget((Display
*) wxGetDisplay(), xEvent
->xany
.window
);
641 wxWindow
* win
= NULL
;
643 // Find the first wxWindow that corresponds to this event window
644 while (widget
&& !(win
= wxGetWindowFromTable(widget
)))
645 widget
= XtParent(widget
);
650 wxKeyEvent
keyEvent(wxEVT_CHAR
);
651 wxTranslateKeyEvent(keyEvent
, win
, (Widget
) 0, xEvent
);
653 // Now we have a wxKeyEvent and we have a wxWindow.
654 // Go up the hierarchy until we find a matching accelerator,
655 // or we get to the top.
658 if (win
->ProcessAccelerator(keyEvent
))
660 win
= win
->GetParent();
667 bool wxApp::CheckForKeyDown(WXEvent
* event
)
669 XEvent
* xEvent
= (XEvent
*) event
;
670 if (xEvent
->xany
.type
== KeyPress
)
672 Widget widget
= XtWindowToWidget((Display
*) wxGetDisplay(),
673 xEvent
->xany
.window
);
674 wxWindow
* win
= NULL
;
676 // Find the first wxWindow that corresponds to this event window
677 while (widget
&& !(win
= wxGetWindowFromTable(widget
)))
678 widget
= XtParent(widget
);
683 wxKeyEvent
keyEvent(wxEVT_KEY_DOWN
);
684 wxTranslateKeyEvent(keyEvent
, win
, (Widget
) 0, xEvent
);
686 return win
->ProcessEvent( keyEvent
);
692 bool wxApp::CheckForKeyUp(WXEvent
* event
)
694 XEvent
* xEvent
= (XEvent
*) event
;
695 if (xEvent
->xany
.type
== KeyRelease
)
697 Widget widget
= XtWindowToWidget((Display
*) wxGetDisplay(),
698 xEvent
->xany
.window
);
699 wxWindow
* win
= NULL
;
701 // Find the first wxWindow that corresponds to this event window
702 while (widget
&& !(win
= wxGetWindowFromTable(widget
)))
703 widget
= XtParent(widget
);
708 wxKeyEvent
keyEvent(wxEVT_KEY_UP
);
709 wxTranslateKeyEvent(keyEvent
, win
, (Widget
) 0, xEvent
);
711 return win
->ProcessEvent( keyEvent
);
721 retValue
= wxTheApp
->OnExit();
725 * Exit in some platform-specific way. Not recommended that the app calls this:
726 * only for emergencies.
731 // Yield to other processes
733 bool wxApp::Yield(bool onlyIfNeeded
)
735 bool s_inYield
= FALSE
;
741 wxFAIL_MSG( wxT("wxYield called recursively" ) );
749 while (wxTheApp
&& wxTheApp
->Pending())
750 wxTheApp
->Dispatch();
757 // ----------------------------------------------------------------------------
758 // accessors for C modules
759 // ----------------------------------------------------------------------------
761 extern "C" XtAppContext
wxGetAppContext()
763 return (XtAppContext
)wxTheApp
->GetAppContext();