Avoid crash during global destruction.
[wxWidgets.git] / src / motif / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose: wxApp
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 17/09/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "app.h"
14 #endif
15
16 #ifdef __VMS
17 #define XtParent XTPARENT
18 #define XtDisplay XTDISPLAY
19 #endif
20
21 #include "wx/app.h"
22 #include "wx/utils.h"
23 #include "wx/module.h"
24 #include "wx/memory.h"
25 #include "wx/log.h"
26 #include "wx/intl.h"
27 #include "wx/evtloop.h"
28 #include "wx/hash.h"
29 #include "wx/hashmap.h"
30
31 #if wxUSE_THREADS
32 #include "wx/thread.h"
33 #endif
34
35 #ifdef __VMS__
36 #pragma message disable nosimpint
37 #endif
38 #include <Xm/Xm.h>
39 #include <X11/Xlib.h>
40 #include <X11/Xutil.h>
41 #include <X11/Xresource.h>
42 #include <X11/Xatom.h>
43 #ifdef __VMS__
44 #pragma message enable nosimpint
45 #endif
46
47 #include "wx/motif/private.h"
48
49 #include <string.h>
50
51 WX_DECLARE_VOIDPTR_HASH_MAP( wxXVisualInfo*, wxXVisualInfoMap );
52
53 extern wxList wxPendingDelete;
54 extern bool wxAddIdleCallback();
55
56 wxApp *wxTheApp = NULL;
57
58 wxHashTable *wxWidgetHashTable = NULL;
59
60 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
61
62 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
63 EVT_IDLE(wxApp::OnIdle)
64 END_EVENT_TABLE()
65
66 #ifdef __WXDEBUG__
67 typedef int (*XErrorHandlerFunc)(Display *, XErrorEvent *);
68
69 XErrorHandlerFunc gs_pfnXErrorHandler = 0;
70
71 static int wxXErrorHandler(Display *dpy, XErrorEvent *xevent)
72 {
73 // just forward to the default handler for now
74 return gs_pfnXErrorHandler(dpy, xevent);
75 }
76 #endif // __WXDEBUG__
77
78 long wxApp::sm_lastMessageTime = 0;
79
80 bool wxApp::Initialize()
81 {
82 wxClassInfo::InitializeClasses();
83
84 // GL: I'm annoyed ... I don't know where to put this and I don't want to
85 // create a module for that as it's part of the core.
86 #if wxUSE_THREADS
87 wxPendingEventsLocker = new wxCriticalSection();
88 #endif
89
90 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
91 wxTheColourDatabase->Initialize();
92
93 wxInitializeStockLists();
94 wxInitializeStockObjects();
95
96 wxWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
97
98 wxModule::RegisterModules();
99 if (!wxModule::InitializeModules()) return FALSE;
100
101 return TRUE;
102 }
103
104 void wxApp::CleanUp()
105 {
106 wxModule::CleanUpModules();
107
108 wxDeleteStockObjects() ;
109
110 // Destroy all GDI lists, etc.
111
112 wxDeleteStockLists();
113
114 delete wxTheColourDatabase;
115 wxTheColourDatabase = NULL;
116
117 wxClassInfo::CleanUpClasses();
118
119 delete wxTheApp;
120 wxTheApp = NULL;
121
122 delete wxWidgetHashTable;
123 wxWidgetHashTable = NULL;
124
125 // GL: I'm annoyed ... I don't know where to put this and I don't want to
126 // create a module for that as it's part of the core.
127 #if wxUSE_THREADS
128 delete wxPendingEvents;
129 wxPendingEvents = NULL;
130 delete wxPendingEventsLocker;
131 wxPendingEventsLocker = NULL;
132 #endif
133
134 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
135 // At this point we want to check if there are any memory
136 // blocks that aren't part of the wxDebugContext itself,
137 // as a special case. Then when dumping we need to ignore
138 // wxDebugContext, too.
139 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
140 {
141 wxLogDebug("There were memory leaks.\n");
142 wxDebugContext::Dump();
143 wxDebugContext::PrintStatistics();
144 }
145 #endif
146
147 // do it as the very last thing because everything else can log messages
148 wxLog::DontCreateOnDemand();
149 // do it as the very last thing because everything else can log messages
150 delete wxLog::SetActiveTarget(NULL);
151 }
152
153 // ============================================================================
154 // wxEntry*
155 // ============================================================================
156
157 int wxEntryStart( int argc, char* argv[] )
158 {
159 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
160 // This seems to be necessary since there are 'rogue'
161 // objects present at this point (perhaps global objects?)
162 // Setting a checkpoint will ignore them as far as the
163 // memory checking facility is concerned.
164 // Of course you may argue that memory allocated in globals should be
165 // checked, but this is a reasonable compromise.
166 wxDebugContext::SetCheckpoint();
167 #endif
168
169 if (!wxApp::Initialize())
170 return -1;
171
172 return 0;
173 }
174
175 int wxEntryInitGui()
176 {
177 int retValue = 0;
178
179 // GUI-specific initialization, such as creating an app context.
180 if (!wxTheApp->OnInitGui())
181 retValue = -1;
182
183 return retValue;
184 }
185
186 void wxEntryCleanup()
187 {
188 // So dialog boxes aren't used for further messages
189 delete wxLog::SetActiveTarget(new wxLogStderr);
190
191 // flush the logged messages if any
192 wxLog *pLog = wxLog::GetActiveTarget();
193 if ( pLog != NULL && pLog->HasPendingMessages() )
194 pLog->Flush();
195
196 wxApp::CleanUp();
197 }
198
199 int wxEntry( int argc, char *argv[] )
200 {
201 int retValue = 0;
202
203 retValue = wxEntryStart( argc, argv );
204 if (retValue) return retValue;
205
206 if (!wxTheApp)
207 {
208 if (!wxApp::GetInitializerFunction())
209 {
210 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
211 return 0;
212 };
213
214 wxTheApp = (wxApp*) (* wxApp::GetInitializerFunction()) ();
215 };
216
217 if (!wxTheApp)
218 {
219 printf( "wxWindows error: wxTheApp == NULL\n" );
220 return 0;
221 };
222
223 wxTheApp->SetClassName(wxFileNameFromPath(argv[0]));
224 wxTheApp->SetAppName(wxFileNameFromPath(argv[0]));
225
226 wxTheApp->argc = argc;
227 wxTheApp->argv = argv;
228
229 // GUI-specific initialization, such as creating an app context.
230 retValue = wxEntryInitGui();
231 if (retValue) return retValue;
232
233 // Here frames insert themselves automatically into wxTopLevelWindows by
234 // getting created in OnInit().
235
236 if (wxTheApp->OnInit())
237 {
238 if (wxTheApp->Initialized())
239 wxTheApp->OnRun();
240 }
241
242 if (wxTheApp->GetTopWindow())
243 {
244 delete wxTheApp->GetTopWindow();
245 wxTheApp->SetTopWindow(NULL);
246 }
247
248 wxTheApp->DeletePendingObjects();
249
250 retValue = wxTheApp->OnExit();
251
252 wxEntryCleanup();
253
254 return retValue;
255 }
256
257 // Static member initialization
258 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
259
260 wxApp::wxApp()
261 {
262 argc = 0;
263 argv = NULL;
264
265 m_eventLoop = new wxEventLoop;
266 m_mainColormap = (WXColormap) NULL;
267 m_appContext = (WXAppContext) NULL;
268 m_topLevelWidget = (WXWidget) NULL;
269 m_maxRequestSize = 0;
270 m_initialDisplay = (WXDisplay*) 0;
271 m_visualInfoMap = new wxXVisualInfoMap;
272 }
273
274 wxApp::~wxApp()
275 {
276 delete m_eventLoop;
277
278 for( wxXVisualInfoMap::iterator it = m_visualInfoMap->begin(),
279 end = m_visualInfoMap->end();
280 it != end; ++it )
281 {
282 delete it->second;
283 }
284
285 delete m_visualInfoMap;
286 }
287
288 bool wxApp::Initialized()
289 {
290 if (GetTopWindow())
291 return TRUE;
292 else
293 return FALSE;
294 }
295
296 int wxApp::MainLoop()
297 {
298 /*
299 * Sit around forever waiting to process X-events. Property Change
300 * event are handled special, because they have to refer to
301 * the root window rather than to a widget. therefore we can't
302 * use an Xt-eventhandler.
303 */
304
305 XSelectInput(XtDisplay((Widget) wxTheApp->GetTopLevelWidget()),
306 XDefaultRootWindow(XtDisplay((Widget) wxTheApp->GetTopLevelWidget())),
307 PropertyChangeMask);
308
309 m_eventLoop->Run();
310
311 return 0;
312 }
313
314 // Processes an idle event.
315 // Returns TRUE if more time is needed.
316 bool wxApp::ProcessIdle()
317 {
318 wxIdleEvent event;
319
320 return ProcessEvent(event) && event.MoreRequested();
321 }
322
323 void wxApp::ExitMainLoop()
324 {
325 if( m_eventLoop->IsRunning() )
326 m_eventLoop->Exit();
327 }
328
329 // Is a message/event pending?
330 bool wxApp::Pending()
331 {
332 return m_eventLoop->Pending();
333 #if 0
334 XFlush(XtDisplay( (Widget) wxTheApp->GetTopLevelWidget() ));
335
336 // Fix by Doug from STI, to prevent a stall if non-X event
337 // is found.
338 return ((XtAppPending( (XtAppContext) GetAppContext() ) & XtIMXEvent) != 0) ;
339 #endif
340 }
341
342 // Dispatch a message.
343 void wxApp::Dispatch()
344 {
345 m_eventLoop->Dispatch();
346 }
347
348 // This should be redefined in a derived class for
349 // handling property change events for XAtom IPC.
350 void wxApp::HandlePropertyChange(WXEvent *event)
351 {
352 // by default do nothing special
353 XtDispatchEvent((XEvent*) event); /* let Motif do the work */
354 }
355
356 void wxApp::OnIdle(wxIdleEvent& event)
357 {
358 static bool inOnIdle = FALSE;
359
360 // Avoid recursion (via ProcessEvent default case)
361 if (inOnIdle)
362 return;
363
364 inOnIdle = TRUE;
365
366 // If there are pending events, we must process them: pending events
367 // are either events to the threads other than main or events posted
368 // with wxPostEvent() functions
369 // GRG: I have moved this here so that all pending events are processed
370 // before starting to delete any objects. This behaves better (in
371 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
372 // behaviour. Also removed the '#if wxUSE_THREADS' around it.
373 // Changed Mar/2000 before 2.1.14
374
375 // Flush pending events.
376 ProcessPendingEvents();
377
378 // 'Garbage' collection of windows deleted with Close().
379 DeletePendingObjects();
380
381 // flush the logged messages if any
382 wxLog *pLog = wxLog::GetActiveTarget();
383 if ( pLog != NULL && pLog->HasPendingMessages() )
384 pLog->Flush();
385
386 // Send OnIdle events to all windows
387 bool needMore = SendIdleEvents();
388
389 if (needMore)
390 event.RequestMore(TRUE);
391
392 inOnIdle = FALSE;
393 }
394
395 // Send idle event to all top-level windows
396 bool wxApp::SendIdleEvents()
397 {
398 bool needMore = FALSE;
399
400 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
401 while (node)
402 {
403 wxWindow* win = node->GetData();
404 if (SendIdleEvents(win))
405 needMore = TRUE;
406 node = node->GetNext();
407 }
408
409 return needMore;
410 }
411
412 // Send idle event to window and all subwindows
413 bool wxApp::SendIdleEvents(wxWindow* win)
414 {
415 bool needMore = FALSE;
416
417 wxIdleEvent event;
418 event.SetEventObject(win);
419 win->GetEventHandler()->ProcessEvent(event);
420
421 if (event.MoreRequested())
422 needMore = TRUE;
423
424 wxWindowList::Node* node = win->GetChildren().GetFirst();
425 while (node)
426 {
427 wxWindow* win = node->GetData();
428 if (SendIdleEvents(win))
429 needMore = TRUE;
430
431 node = node->GetNext();
432 }
433 return needMore ;
434 }
435
436 void wxApp::DeletePendingObjects()
437 {
438 wxList::Node *node = wxPendingDelete.GetFirst();
439 while (node)
440 {
441 wxObject *obj = node->GetData();
442
443 delete obj;
444
445 if (wxPendingDelete.Member(obj))
446 delete node;
447
448 // Deleting one object may have deleted other pending
449 // objects, so start from beginning of list again.
450 node = wxPendingDelete.GetFirst();
451 }
452 }
453
454 static char *fallbackResources[] = {
455 "*menuBar.marginHeight: 0",
456 "*menuBar.shadowThickness: 1",
457 "*background: #c0c0c0",
458 "*foreground: black",
459 NULL
460 };
461
462 // Create an application context
463 bool wxApp::OnInitGui()
464 {
465 if( !wxAppBase::OnInitGui() )
466 return FALSE;
467
468 XtToolkitInitialize() ;
469 wxTheApp->m_appContext = (WXAppContext) XtCreateApplicationContext();
470 XtAppSetFallbackResources((XtAppContext) wxTheApp->m_appContext, fallbackResources);
471
472 Display *dpy = XtOpenDisplay((XtAppContext) wxTheApp->m_appContext,(String)NULL,NULL,
473 wxTheApp->GetClassName().c_str(), NULL, 0,
474 # if XtSpecificationRelease < 5
475 (Cardinal*) &argc,
476 # else
477 &argc,
478 # endif
479 argv);
480
481 if (!dpy) {
482 // if you don't log to stderr, nothing will be shown...
483 delete wxLog::SetActiveTarget(new wxLogStderr);
484 wxString className(wxTheApp->GetClassName());
485 wxLogError(_("wxWindows could not open display for '%s': exiting."),
486 className.c_str());
487 exit(-1);
488 }
489 m_initialDisplay = (WXDisplay*) dpy;
490
491 #ifdef __WXDEBUG__
492 // install the X error handler
493 gs_pfnXErrorHandler = XSetErrorHandler(wxXErrorHandler);
494 #endif // __WXDEBUG__
495
496 wxTheApp->m_topLevelWidget =
497 (WXWidget) XtAppCreateShell((String)NULL,
498 wxTheApp->GetClassName().c_str(),
499 applicationShellWidgetClass,dpy,
500 NULL,0) ;
501
502 // Add general resize proc
503 XtActionsRec rec;
504 rec.string = "resize";
505 rec.proc = (XtActionProc)wxWidgetResizeProc;
506 XtAppAddActions((XtAppContext) wxTheApp->m_appContext, &rec, 1);
507
508 GetMainColormap(dpy);
509 m_maxRequestSize = XMaxRequestSize((Display*) dpy);
510
511 wxAddIdleCallback();
512
513 return TRUE;
514 }
515
516 WXColormap wxApp::GetMainColormap(WXDisplay* display)
517 {
518 if (!display) /* Must be called first with non-NULL display */
519 return m_mainColormap;
520
521 int defaultScreen = DefaultScreen((Display*) display);
522 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
523
524 Colormap c = DefaultColormapOfScreen(screen);
525
526 if (!m_mainColormap)
527 m_mainColormap = (WXColormap) c;
528
529 return (WXColormap) c;
530 }
531
532 wxXVisualInfo* wxApp::GetVisualInfo( WXDisplay* display )
533 {
534 wxXVisualInfoMap::iterator it = m_visualInfoMap->find( display );
535
536 if( it != m_visualInfoMap->end() ) return it->second;
537
538 wxXVisualInfo* vi = new wxXVisualInfo;
539 wxFillXVisualInfo( vi, (Display*)display );
540
541 (*m_visualInfoMap)[display] = vi;
542
543 return vi;
544 }
545
546 void wxExit()
547 {
548 int retValue = 0;
549 if (wxTheApp)
550 retValue = wxTheApp->OnExit();
551
552 wxApp::CleanUp();
553 /*
554 * Exit in some platform-specific way.
555 * Not recommended that the app calls this:
556 * only for emergencies.
557 */
558 exit(retValue);
559 }
560
561 // Yield to other processes
562
563 bool wxApp::Yield(bool onlyIfNeeded)
564 {
565 bool s_inYield = FALSE;
566
567 if ( s_inYield )
568 {
569 if ( !onlyIfNeeded )
570 {
571 wxFAIL_MSG( wxT("wxYield called recursively" ) );
572 }
573
574 return FALSE;
575 }
576
577 s_inYield = TRUE;
578
579 while (wxTheApp && wxTheApp->Pending())
580 wxTheApp->Dispatch();
581
582 s_inYield = FALSE;
583
584 return TRUE;
585 }
586
587 // ----------------------------------------------------------------------------
588 // accessors for C modules
589 // ----------------------------------------------------------------------------
590
591 extern "C" XtAppContext wxGetAppContext()
592 {
593 return (XtAppContext)wxTheApp->GetAppContext();
594 }