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