wxTopLevelWindows is now a wxWindowList, better compatibility with the old
[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 #include "wx/frame.h"
17 #include "wx/app.h"
18 #include "wx/utils.h"
19 #include "wx/gdicmn.h"
20 #include "wx/pen.h"
21 #include "wx/brush.h"
22 #include "wx/cursor.h"
23 #include "wx/icon.h"
24 #include "wx/palette.h"
25 #include "wx/dc.h"
26 #include "wx/dialog.h"
27 #include "wx/msgdlg.h"
28 #include "wx/log.h"
29 #include "wx/module.h"
30 #include "wx/memory.h"
31
32 #if wxUSE_THREADS
33 #include "wx/thread.h"
34 #endif
35
36 #if wxUSE_WX_RESOURCES
37 #include "wx/resource.h"
38 #endif
39
40 #include <Xm/Xm.h>
41 #include <X11/Xlib.h>
42 #include <X11/Xutil.h>
43 #include <X11/Xresource.h>
44 #include <X11/Xatom.h>
45
46 #include "wx/motif/private.h"
47
48 #include <string.h>
49
50 extern char *wxBuffer;
51 extern wxList wxPendingDelete;
52 #if wxUSE_THREADS
53 extern wxList wxPendingEvents;
54 extern wxList wxPendingEventsLocker;
55 #endif
56
57 wxApp *wxTheApp = NULL;
58
59 wxHashTable *wxWidgetHashTable = NULL;
60
61 #if !USE_SHARED_LIBRARY
62 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
63
64 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
65 EVT_IDLE(wxApp::OnIdle)
66 END_EVENT_TABLE()
67 #endif
68
69 long wxApp::sm_lastMessageTime = 0;
70
71 bool wxApp::Initialize()
72 {
73 wxBuffer = new char[BUFSIZ + 512];
74
75 wxClassInfo::InitializeClasses();
76
77 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
78 wxTheColourDatabase->Initialize();
79
80 wxInitializeStockLists();
81 wxInitializeStockObjects();
82
83 #if wxUSE_WX_RESOURCES
84 wxInitializeResourceSystem();
85 #endif
86
87 // For PostScript printing
88 #if wxUSE_POSTSCRIPT
89 /* Done using wxModule now
90 wxInitializePrintSetupData();
91 wxThePrintPaperDatabase = new wxPrintPaperDatabase;
92 wxThePrintPaperDatabase->CreateDatabase();
93 */
94 #endif
95
96 wxBitmap::InitStandardHandlers();
97
98 wxWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
99
100 wxModule::RegisterModules();
101 if (!wxModule::InitializeModules()) return FALSE;
102
103 return TRUE;
104 }
105
106 void wxApp::CleanUp()
107 {
108 delete wxWidgetHashTable;
109 wxWidgetHashTable = NULL;
110
111 wxModule::CleanUpModules();
112
113 #if wxUSE_WX_RESOURCES
114 wxCleanUpResourceSystem();
115 #endif
116
117 wxDeleteStockObjects() ;
118
119 // Destroy all GDI lists, etc.
120
121 delete wxTheBrushList;
122 wxTheBrushList = NULL;
123
124 delete wxThePenList;
125 wxThePenList = NULL;
126
127 delete wxTheFontList;
128 wxTheFontList = NULL;
129
130 delete wxTheBitmapList;
131 wxTheBitmapList = NULL;
132
133 delete wxTheColourDatabase;
134 wxTheColourDatabase = NULL;
135
136 #if wxUSE_POSTSCRIPT
137 /* Done using wxModule now
138 wxInitializePrintSetupData(FALSE);
139 delete wxThePrintPaperDatabase;
140 wxThePrintPaperDatabase = NULL;
141 */
142 #endif
143
144 wxBitmap::CleanUpHandlers();
145
146 delete[] wxBuffer;
147 wxBuffer = NULL;
148
149 wxClassInfo::CleanUpClasses();
150
151 delete wxTheApp;
152 wxTheApp = NULL;
153
154 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
155 // At this point we want to check if there are any memory
156 // blocks that aren't part of the wxDebugContext itself,
157 // as a special case. Then when dumping we need to ignore
158 // wxDebugContext, too.
159 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
160 {
161 wxLogDebug("There were memory leaks.\n");
162 wxDebugContext::Dump();
163 wxDebugContext::PrintStatistics();
164 }
165 #endif
166
167 // do it as the very last thing because everything else can log messages
168 wxLog::DontCreateOnDemand();
169 // do it as the very last thing because everything else can log messages
170 delete wxLog::SetActiveTarget(NULL);
171 }
172
173 int wxEntry( int argc, char *argv[] )
174 {
175 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
176 // This seems to be necessary since there are 'rogue'
177 // objects present at this point (perhaps global objects?)
178 // Setting a checkpoint will ignore them as far as the
179 // memory checking facility is concerned.
180 // Of course you may argue that memory allocated in globals should be
181 // checked, but this is a reasonable compromise.
182 wxDebugContext::SetCheckpoint();
183 #endif
184
185 if (!wxApp::Initialize())
186 return FALSE;
187
188 if (!wxTheApp)
189 {
190 if (!wxApp::GetInitializerFunction())
191 {
192 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
193 return 0;
194 };
195
196 wxTheApp = (wxApp*) (* wxApp::GetInitializerFunction()) ();
197 };
198
199 if (!wxTheApp)
200 {
201 printf( "wxWindows error: wxTheApp == NULL\n" );
202 return 0;
203 };
204
205 wxTheApp->SetClassName(wxFileNameFromPath(argv[0]));
206 wxTheApp->SetAppName(wxFileNameFromPath(argv[0]));
207
208 wxTheApp->argc = argc;
209 wxTheApp->argv = argv;
210
211 // GUI-specific initialization, such as creating an app context.
212 wxTheApp->OnInitGui();
213
214 // Here frames insert themselves automatically into wxTopLevelWindows by
215 // getting created in OnInit().
216
217 int retValue = 0;
218 if (wxTheApp->OnInit())
219 {
220 if (wxTheApp->Initialized()) retValue = wxTheApp->OnRun();
221 }
222
223 // flush the logged messages if any
224 wxLog *pLog = wxLog::GetActiveTarget();
225 if ( pLog != NULL && pLog->HasPendingMessages() )
226 pLog->Flush();
227
228 delete wxLog::SetActiveTarget(new wxLogStderr); // So dialog boxes aren't used
229 // for further messages
230
231 if (wxTheApp->GetTopWindow())
232 {
233 delete wxTheApp->GetTopWindow();
234 wxTheApp->SetTopWindow(NULL);
235 }
236
237 wxTheApp->DeletePendingObjects();
238
239 wxTheApp->OnExit();
240
241 wxApp::CleanUp();
242
243 return retValue;
244 };
245
246 // Static member initialization
247 wxAppInitializerFunction wxApp::m_appInitFn = (wxAppInitializerFunction) NULL;
248
249 wxApp::wxApp()
250 {
251 m_topWindow = NULL;
252 wxTheApp = this;
253 m_className = "";
254 m_wantDebugOutput = TRUE ;
255 m_appName = "";
256 argc = 0;
257 argv = NULL;
258 m_printMode = wxPRINT_POSTSCRIPT;
259 m_exitOnFrameDelete = TRUE;
260 m_auto3D = TRUE;
261
262 m_mainColormap = (WXColormap) NULL;
263 m_appContext = (WXAppContext) NULL;
264 m_topLevelWidget = (WXWidget) NULL;
265 m_maxRequestSize = 0;
266 m_initialDisplay = (WXDisplay*) 0;
267 }
268
269 bool wxApp::Initialized()
270 {
271 if (GetTopWindow())
272 return TRUE;
273 else
274 return FALSE;
275 }
276
277 int wxApp::MainLoop()
278 {
279 m_keepGoing = TRUE;
280
281 /*
282 * Sit around forever waiting to process X-events. Property Change
283 * event are handled special, because they have to refer to
284 * the root window rather than to a widget. therefore we can't
285 * use an Xt-eventhandler.
286 */
287
288 XSelectInput(XtDisplay((Widget) wxTheApp->GetTopLevelWidget()),
289 XDefaultRootWindow(XtDisplay((Widget) wxTheApp->GetTopLevelWidget())),
290 PropertyChangeMask);
291
292 XEvent event;
293
294 // Use this flag to allow breaking the loop via wxApp::ExitMainLoop()
295 while (m_keepGoing)
296 {
297 XtAppNextEvent( (XtAppContext) wxTheApp->GetAppContext(), &event);
298
299 ProcessXEvent((WXEvent*) & event);
300
301 if (XtAppPending( (XtAppContext) wxTheApp->GetAppContext() ) == 0)
302 {
303 if (!ProcessIdle())
304 {
305 #if wxUSE_THREADS
306 // leave the main loop to give other threads a chance to
307 // perform their GUI work
308 wxMutexGuiLeave();
309 wxUsleep(20);
310 wxMutexGuiEnter();
311 #endif
312 }
313 }
314
315 }
316
317 return 0;
318 }
319
320 // Processes an X event.
321 void wxApp::ProcessXEvent(WXEvent* _event)
322 {
323 XEvent* event = (XEvent*) _event;
324
325 if ((event->type == KeyPress) && CheckForAccelerator(_event))
326 {
327 // Do nothing! We intercepted and processed the event as an accelerator.
328 return;
329 }
330 else if (event->type == PropertyNotify)
331 {
332 HandlePropertyChange(_event);
333 return;
334 }
335 else if (event->type == ResizeRequest)
336 {
337 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
338 * If resize event, don't resize until the last resize event for this
339 * window is recieved. Prevents flicker as windows are resized.
340 */
341
342 Display *disp = XtDisplay((Widget) wxTheApp->GetTopLevelWidget());
343 Window win = event->xany.window;
344 XEvent report;
345
346 // to avoid flicker
347 report = * event;
348 while( XCheckTypedWindowEvent (disp, win, ResizeRequest, &report));
349
350 // TODO: when implementing refresh optimization, we can use
351 // XtAddExposureToRegion to expand the window's paint region.
352
353 XtDispatchEvent(event);
354 }
355 else
356 {
357 XtDispatchEvent(event);
358 }
359 }
360
361 // Returns TRUE if more time is needed.
362 bool wxApp::ProcessIdle()
363 {
364 wxIdleEvent event;
365 event.SetEventObject(this);
366 ProcessEvent(event);
367
368 return event.MoreRequested();
369 }
370
371 void wxApp::ExitMainLoop()
372 {
373 m_keepGoing = FALSE;
374 }
375
376 // Is a message/event pending?
377 bool wxApp::Pending()
378 {
379 XFlush(XtDisplay( (Widget) wxTheApp->GetTopLevelWidget() ));
380
381 // Fix by Doug from STI, to prevent a stall if non-X event
382 // is found.
383 return ((XtAppPending( (XtAppContext) GetAppContext() ) & XtIMXEvent) != 0) ;
384 }
385
386 // Dispatch a message.
387 void wxApp::Dispatch()
388 {
389 // XtAppProcessEvent( (XtAppContext) wxTheApp->GetAppContext(), XtIMAll);
390
391 XEvent event;
392 XtAppNextEvent((XtAppContext) GetAppContext(), &event);
393 ProcessXEvent((WXEvent*) & event);
394 }
395
396 // This should be redefined in a derived class for
397 // handling property change events for XAtom IPC.
398 void wxApp::HandlePropertyChange(WXEvent *event)
399 {
400 // by default do nothing special
401 XtDispatchEvent((XEvent*) event); /* let Motif do the work */
402 }
403
404 void wxApp::OnIdle(wxIdleEvent& event)
405 {
406 static bool inOnIdle = FALSE;
407
408 // Avoid recursion (via ProcessEvent default case)
409 if (inOnIdle)
410 return;
411
412 inOnIdle = TRUE;
413
414 // 'Garbage' collection of windows deleted with Close().
415 DeletePendingObjects();
416
417 #if wxUSE_THREADS
418 // Flush pending events.
419 ProcessPendingEvents();
420 #endif
421
422 // flush the logged messages if any
423 wxLog *pLog = wxLog::GetActiveTarget();
424 if ( pLog != NULL && pLog->HasPendingMessages() )
425 pLog->Flush();
426
427 // Send OnIdle events to all windows
428 bool needMore = SendIdleEvents();
429
430 if (needMore)
431 event.RequestMore(TRUE);
432
433 inOnIdle = FALSE;
434 }
435
436 // Send idle event to all top-level windows
437 bool wxApp::SendIdleEvents()
438 {
439 bool needMore = FALSE;
440
441 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
442 while (node)
443 {
444 wxWindow* win = node->GetData();
445 if (SendIdleEvents(win))
446 needMore = TRUE;
447 node = node->GetNext();
448 }
449
450 return needMore;
451 }
452
453 // Send idle event to window and all subwindows
454 bool wxApp::SendIdleEvents(wxWindow* win)
455 {
456 bool needMore = FALSE;
457
458 wxIdleEvent event;
459 event.SetEventObject(win);
460 win->ProcessEvent(event);
461
462 if (event.MoreRequested())
463 needMore = TRUE;
464
465 wxNode* node = win->GetChildren().First();
466 while (node)
467 {
468 wxWindow* win = (wxWindow*) node->Data();
469 if (SendIdleEvents(win))
470 needMore = TRUE;
471
472 node = node->Next();
473 }
474 return needMore ;
475 }
476
477 void wxApp::DeletePendingObjects()
478 {
479 wxNode *node = wxPendingDelete.First();
480 while (node)
481 {
482 wxObject *obj = (wxObject *)node->Data();
483
484 delete obj;
485
486 if (wxPendingDelete.Member(obj))
487 delete node;
488
489 // Deleting one object may have deleted other pending
490 // objects, so start from beginning of list again.
491 node = wxPendingDelete.First();
492 }
493 }
494
495 #if wxUSE_THREADS
496 void wxApp::ProcessPendingEvents()
497
498 wxNode *node = wxPendingEvents.First();
499 wxCriticalSectionLocker locker(wxPendingEventsLocker);
500
501 while (node)
502 {
503 wxEvtHandler *handler = (wxEvtHandler *)node->Data();
504
505 handler->ProcessPendingEvents();
506
507 delete node;
508 node = wxPendingEvents.First();
509 }
510
511 #endif
512
513 wxLog* wxApp::CreateLogTarget()
514 {
515 return new wxLogGui;
516 }
517
518 wxWindow* wxApp::GetTopWindow() const
519 {
520 if (m_topWindow)
521 return m_topWindow;
522 else if (wxTopLevelWindows.GetCount() > 0)
523 return wxTopLevelWindows.GetFirst()->GetData();
524 else
525 return NULL;
526 }
527
528 // Create an application context
529 bool wxApp::OnInitGui()
530 {
531 XtToolkitInitialize() ;
532 wxTheApp->m_appContext = (WXAppContext) XtCreateApplicationContext() ;
533 Display *dpy = XtOpenDisplay((XtAppContext) wxTheApp->m_appContext,(String)NULL,NULL,
534 (const char*) wxTheApp->GetClassName(), NULL, 0,
535 # if XtSpecificationRelease < 5
536 (Cardinal*) &argc,
537 # else
538 &argc,
539 # endif
540 argv);
541
542 if (!dpy) {
543 wxString className(wxTheApp->GetClassName());
544 wxLogError(_("wxWindows could not open display for '%s': exiting."),
545 (const char*) className);
546 exit(-1);
547 }
548 m_initialDisplay = (WXDisplay*) dpy;
549
550 wxTheApp->m_topLevelWidget = (WXWidget) XtAppCreateShell((String)NULL, (const char*) wxTheApp->GetClassName(),
551 applicationShellWidgetClass,dpy,
552 NULL,0) ;
553
554 // Add general resize proc
555 XtActionsRec rec;
556 rec.string = "resize";
557 rec.proc = (XtActionProc)wxWidgetResizeProc;
558 XtAppAddActions((XtAppContext) wxTheApp->m_appContext, &rec, 1);
559
560 GetMainColormap(dpy);
561 m_maxRequestSize = XMaxRequestSize((Display*) dpy);
562
563 return TRUE;
564 }
565
566 WXColormap wxApp::GetMainColormap(WXDisplay* display)
567 {
568 if (!display) /* Must be called first with non-NULL display */
569 return m_mainColormap;
570
571 int defaultScreen = DefaultScreen((Display*) display);
572 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
573
574 Colormap c = DefaultColormapOfScreen(screen);
575
576 if (!m_mainColormap)
577 m_mainColormap = (WXColormap) c;
578
579 return (WXColormap) c;
580 }
581
582 // Returns TRUE if an accelerator has been processed
583 bool wxApp::CheckForAccelerator(WXEvent* event)
584 {
585 XEvent* xEvent = (XEvent*) event;
586 if (xEvent->xany.type == KeyPress)
587 {
588 // Find a wxWindow for this window
589 // TODO: should get display for the window, not the current display
590 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(), xEvent->xany.window);
591 wxWindow* win = NULL;
592
593 // Find the first wxWindow that corresponds to this event window
594 while (widget && !(win = wxGetWindowFromTable(widget)))
595 widget = XtParent(widget);
596
597 if (!widget || !win)
598 return FALSE;
599
600 wxKeyEvent keyEvent(wxEVT_CHAR);
601 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
602
603 // Now we have a wxKeyEvent and we have a wxWindow.
604 // Go up the hierarchy until we find a matching accelerator,
605 // or we get to the top.
606 while (win)
607 {
608 if (win->ProcessAccelerator(keyEvent))
609 return TRUE;
610 win = win->GetParent();
611 }
612 return FALSE;
613 }
614 return FALSE;
615 }
616
617 void wxExit()
618 {
619 int retValue = 0;
620 if (wxTheApp)
621 retValue = wxTheApp->OnExit();
622
623 wxApp::CleanUp();
624 /*
625 * Exit in some platform-specific way. Not recommended that the app calls this:
626 * only for emergencies.
627 */
628 exit(retValue);
629 }
630
631 // Yield to other processes
632 bool wxYield()
633 {
634 while (wxTheApp && wxTheApp->Pending())
635 wxTheApp->Dispatch();
636
637 // VZ: is it the same as this (taken from old wxExecute)?
638 #if 0
639 XtAppProcessEvent((XtAppContext) wxTheApp->GetAppContext(), XtIMAll);
640 #endif
641
642 return TRUE;
643 }
644