more Sun C++ compiler warning fixes: in particular, added an ugly but
[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/frame.h"
22 #include "wx/app.h"
23 #include "wx/utils.h"
24 #include "wx/gdicmn.h"
25 #include "wx/pen.h"
26 #include "wx/brush.h"
27 #include "wx/cursor.h"
28 #include "wx/icon.h"
29 #include "wx/palette.h"
30 #include "wx/dc.h"
31 #include "wx/dialog.h"
32 #include "wx/msgdlg.h"
33 #include "wx/log.h"
34 #include "wx/module.h"
35 #include "wx/memory.h"
36 #include "wx/log.h"
37 #include "wx/intl.h"
38
39 #if wxUSE_THREADS
40 #include "wx/thread.h"
41 #endif
42
43 #if wxUSE_WX_RESOURCES
44 #include "wx/resource.h"
45 #endif
46
47 #ifdef __VMS__
48 #pragma message disable nosimpint
49 #endif
50 #include <Xm/Xm.h>
51 #include <X11/Xlib.h>
52 #include <X11/Xutil.h>
53 #include <X11/Xresource.h>
54 #include <X11/Xatom.h>
55 #ifdef __VMS__
56 #pragma message enable nosimpint
57 #endif
58
59 #include "wx/motif/private.h"
60
61 #include <string.h>
62
63 extern char *wxBuffer;
64 extern wxList wxPendingDelete;
65
66 wxApp *wxTheApp = NULL;
67
68 wxHashTable *wxWidgetHashTable = NULL;
69
70 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
71
72 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
73 EVT_IDLE(wxApp::OnIdle)
74 END_EVENT_TABLE()
75
76 #ifdef __WXDEBUG__
77 typedef int (*XErrorHandlerFunc)(Display *, XErrorEvent *);
78
79 XErrorHandlerFunc gs_pfnXErrorHandler = 0;
80
81 static int wxXErrorHandler(Display *dpy, XErrorEvent *xevent)
82 {
83 // just forward to the default handler for now
84 return gs_pfnXErrorHandler(dpy, xevent);
85 }
86 #endif // __WXDEBUG__
87
88 long wxApp::sm_lastMessageTime = 0;
89
90 bool wxApp::Initialize()
91 {
92 wxBuffer = new char[BUFSIZ + 512];
93
94 wxClassInfo::InitializeClasses();
95
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.
98 #if wxUSE_THREADS
99 wxPendingEventsLocker = new wxCriticalSection();
100 #endif
101
102 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
103 wxTheColourDatabase->Initialize();
104
105 wxInitializeStockLists();
106 wxInitializeStockObjects();
107
108 #if wxUSE_WX_RESOURCES
109 wxInitializeResourceSystem();
110 #endif
111
112 // For PostScript printing
113 #if wxUSE_POSTSCRIPT
114 /* Done using wxModule now
115 wxInitializePrintSetupData();
116 wxThePrintPaperDatabase = new wxPrintPaperDatabase;
117 wxThePrintPaperDatabase->CreateDatabase();
118 */
119 #endif
120
121 wxBitmap::InitStandardHandlers();
122
123 wxWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
124
125 wxModule::RegisterModules();
126 if (!wxModule::InitializeModules()) return FALSE;
127
128 return TRUE;
129 }
130
131 void wxApp::CleanUp()
132 {
133 delete wxWidgetHashTable;
134 wxWidgetHashTable = NULL;
135
136 wxModule::CleanUpModules();
137
138 #if wxUSE_WX_RESOURCES
139 wxCleanUpResourceSystem();
140 #endif
141
142 wxDeleteStockObjects() ;
143
144 // Destroy all GDI lists, etc.
145
146 wxDeleteStockLists();
147
148 delete wxTheColourDatabase;
149 wxTheColourDatabase = NULL;
150
151 #if wxUSE_POSTSCRIPT
152 /* Done using wxModule now
153 wxInitializePrintSetupData(FALSE);
154 delete wxThePrintPaperDatabase;
155 wxThePrintPaperDatabase = NULL;
156 */
157 #endif
158
159 wxBitmap::CleanUpHandlers();
160
161 delete[] wxBuffer;
162 wxBuffer = NULL;
163
164 wxClassInfo::CleanUpClasses();
165
166 delete wxTheApp;
167 wxTheApp = NULL;
168
169 // GL: I'm annoyed ... I don't know where to put this and I don't want to
170 // create a module for that as it's part of the core.
171 #if wxUSE_THREADS
172 delete wxPendingEvents;
173 delete wxPendingEventsLocker;
174 #endif
175
176 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
177 // At this point we want to check if there are any memory
178 // blocks that aren't part of the wxDebugContext itself,
179 // as a special case. Then when dumping we need to ignore
180 // wxDebugContext, too.
181 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
182 {
183 wxLogDebug("There were memory leaks.\n");
184 wxDebugContext::Dump();
185 wxDebugContext::PrintStatistics();
186 }
187 #endif
188
189 // do it as the very last thing because everything else can log messages
190 wxLog::DontCreateOnDemand();
191 // do it as the very last thing because everything else can log messages
192 delete wxLog::SetActiveTarget(NULL);
193 }
194
195 int wxEntry( int argc, char *argv[] )
196 {
197 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
198 // This seems to be necessary since there are 'rogue'
199 // objects present at this point (perhaps global objects?)
200 // Setting a checkpoint will ignore them as far as the
201 // memory checking facility is concerned.
202 // Of course you may argue that memory allocated in globals should be
203 // checked, but this is a reasonable compromise.
204 wxDebugContext::SetCheckpoint();
205 #endif
206
207 if (!wxApp::Initialize())
208 return FALSE;
209
210 if (!wxTheApp)
211 {
212 if (!wxApp::GetInitializerFunction())
213 {
214 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
215 return 0;
216 };
217
218 wxTheApp = (wxApp*) (* wxApp::GetInitializerFunction()) ();
219 };
220
221 if (!wxTheApp)
222 {
223 printf( "wxWindows error: wxTheApp == NULL\n" );
224 return 0;
225 };
226
227 wxTheApp->SetClassName(wxFileNameFromPath(argv[0]));
228 wxTheApp->SetAppName(wxFileNameFromPath(argv[0]));
229
230 wxTheApp->argc = argc;
231 wxTheApp->argv = argv;
232
233 // GUI-specific initialization, such as creating an app context.
234 wxTheApp->OnInitGui();
235
236 // Here frames insert themselves automatically into wxTopLevelWindows by
237 // getting created in OnInit().
238
239 int retValue = 0;
240 if (wxTheApp->OnInit())
241 {
242 if (wxTheApp->Initialized()) retValue = wxTheApp->OnRun();
243 }
244
245 // flush the logged messages if any
246 wxLog *pLog = wxLog::GetActiveTarget();
247 if ( pLog != NULL && pLog->HasPendingMessages() )
248 pLog->Flush();
249
250 delete wxLog::SetActiveTarget(new wxLogStderr); // So dialog boxes aren't used
251 // for further messages
252
253 if (wxTheApp->GetTopWindow())
254 {
255 delete wxTheApp->GetTopWindow();
256 wxTheApp->SetTopWindow(NULL);
257 }
258
259 wxTheApp->DeletePendingObjects();
260
261 wxTheApp->OnExit();
262
263 wxApp::CleanUp();
264
265 return retValue;
266 };
267
268 // Static member initialization
269 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
270
271 wxApp::wxApp()
272 {
273 m_topWindow = NULL;
274 wxTheApp = this;
275 m_className = "";
276 m_wantDebugOutput = TRUE ;
277 m_appName = "";
278 argc = 0;
279 argv = NULL;
280 m_exitOnFrameDelete = TRUE;
281
282 m_mainColormap = (WXColormap) NULL;
283 m_appContext = (WXAppContext) NULL;
284 m_topLevelWidget = (WXWidget) NULL;
285 m_maxRequestSize = 0;
286 m_initialDisplay = (WXDisplay*) 0;
287 }
288
289 bool wxApp::Initialized()
290 {
291 if (GetTopWindow())
292 return TRUE;
293 else
294 return FALSE;
295 }
296
297 int wxApp::MainLoop()
298 {
299 m_keepGoing = TRUE;
300
301 /*
302 * Sit around forever waiting to process X-events. Property Change
303 * event are handled special, because they have to refer to
304 * the root window rather than to a widget. therefore we can't
305 * use an Xt-eventhandler.
306 */
307
308 XSelectInput(XtDisplay((Widget) wxTheApp->GetTopLevelWidget()),
309 XDefaultRootWindow(XtDisplay((Widget) wxTheApp->GetTopLevelWidget())),
310 PropertyChangeMask);
311
312 XEvent event;
313
314 // Use this flag to allow breaking the loop via wxApp::ExitMainLoop()
315 while (m_keepGoing)
316 {
317 XtAppNextEvent( (XtAppContext) wxTheApp->GetAppContext(), &event);
318
319 ProcessXEvent((WXEvent*) & event);
320
321 if (XtAppPending( (XtAppContext) wxTheApp->GetAppContext() ) == 0)
322 {
323 if (!ProcessIdle())
324 {
325 #if wxUSE_THREADS
326 // leave the main loop to give other threads a chance to
327 // perform their GUI work
328 wxMutexGuiLeave();
329 wxUsleep(20);
330 wxMutexGuiEnter();
331 #endif
332 }
333 }
334
335 }
336
337 return 0;
338 }
339
340 // Processes an X event.
341 void wxApp::ProcessXEvent(WXEvent* _event)
342 {
343 XEvent* event = (XEvent*) _event;
344
345 if (event->type == KeyPress)
346 {
347 #if 0 // def __WXDEBUG__
348 Widget widget = XtWindowToWidget(event->xany.display, event->xany.window);
349 wxLogDebug("Got key press event for 0x%08x (parent = 0x%08x)",
350 widget, XtParent(widget));
351 #endif // DEBUG
352
353 if (CheckForAccelerator(_event))
354 {
355 // Do nothing! We intercepted and processed the event as an
356 // accelerator.
357 return;
358 }
359 #if 1
360 // It seemed before that this hack was redundant and
361 // key down events were being generated by wxCanvasInputEvent.
362 // But no longer - why ???
363 //
364 else if (CheckForKeyDown(_event))
365 {
366 // We intercepted and processed the key down event
367 return;
368 }
369 #endif
370 else
371 {
372 XtDispatchEvent(event);
373 return;
374 }
375 }
376 else if (event->type == KeyRelease)
377 {
378 // TODO: work out why we still need this ! -michael
379 //
380 if (CheckForKeyUp(_event))
381 {
382 // We intercepted and processed the key up event
383 return;
384 }
385 else
386 {
387 XtDispatchEvent(event);
388 return;
389 }
390 }
391 else if (event->type == PropertyNotify)
392 {
393 HandlePropertyChange(_event);
394 return;
395 }
396 else if (event->type == ResizeRequest)
397 {
398 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
399 * If resize event, don't resize until the last resize event for this
400 * window is recieved. Prevents flicker as windows are resized.
401 */
402
403 Display *disp = XtDisplay((Widget) wxTheApp->GetTopLevelWidget());
404 Window win = event->xany.window;
405 XEvent report;
406
407 // to avoid flicker
408 report = * event;
409 while( XCheckTypedWindowEvent (disp, win, ResizeRequest, &report));
410
411 // TODO: when implementing refresh optimization, we can use
412 // XtAddExposureToRegion to expand the window's paint region.
413
414 XtDispatchEvent(event);
415 }
416 else
417 {
418 XtDispatchEvent(event);
419 }
420 }
421
422 // Returns TRUE if more time is needed.
423 bool wxApp::ProcessIdle()
424 {
425 wxIdleEvent event;
426 event.SetEventObject(this);
427 ProcessEvent(event);
428
429 return event.MoreRequested();
430 }
431
432 void wxApp::ExitMainLoop()
433 {
434 m_keepGoing = FALSE;
435 }
436
437 // Is a message/event pending?
438 bool wxApp::Pending()
439 {
440 XFlush(XtDisplay( (Widget) wxTheApp->GetTopLevelWidget() ));
441
442 // Fix by Doug from STI, to prevent a stall if non-X event
443 // is found.
444 return ((XtAppPending( (XtAppContext) GetAppContext() ) & XtIMXEvent) != 0) ;
445 }
446
447 // Dispatch a message.
448 void wxApp::Dispatch()
449 {
450 // XtAppProcessEvent( (XtAppContext) wxTheApp->GetAppContext(), XtIMAll);
451
452 XEvent event;
453 XtAppNextEvent((XtAppContext) GetAppContext(), &event);
454 ProcessXEvent((WXEvent*) & event);
455 }
456
457 // This should be redefined in a derived class for
458 // handling property change events for XAtom IPC.
459 void wxApp::HandlePropertyChange(WXEvent *event)
460 {
461 // by default do nothing special
462 XtDispatchEvent((XEvent*) event); /* let Motif do the work */
463 }
464
465 void wxApp::OnIdle(wxIdleEvent& event)
466 {
467 static bool inOnIdle = FALSE;
468
469 // Avoid recursion (via ProcessEvent default case)
470 if (inOnIdle)
471 return;
472
473 inOnIdle = TRUE;
474
475 // If there are pending events, we must process them: pending events
476 // are either events to the threads other than main or events posted
477 // with wxPostEvent() functions
478 // GRG: I have moved this here so that all pending events are processed
479 // before starting to delete any objects. This behaves better (in
480 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
481 // behaviour. Also removed the '#if wxUSE_THREADS' around it.
482 // Changed Mar/2000 before 2.1.14
483
484 // Flush pending events.
485 ProcessPendingEvents();
486
487 // 'Garbage' collection of windows deleted with Close().
488 DeletePendingObjects();
489
490 // flush the logged messages if any
491 wxLog *pLog = wxLog::GetActiveTarget();
492 if ( pLog != NULL && pLog->HasPendingMessages() )
493 pLog->Flush();
494
495 // Send OnIdle events to all windows
496 bool needMore = SendIdleEvents();
497
498 if (needMore)
499 event.RequestMore(TRUE);
500
501 inOnIdle = FALSE;
502 }
503
504 void wxWakeUpIdle()
505 {
506 // **** please implement me! ****
507 // Wake up the idle handler processor, even if it is in another thread...
508 }
509
510
511 // Send idle event to all top-level windows
512 bool wxApp::SendIdleEvents()
513 {
514 bool needMore = FALSE;
515
516 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
517 while (node)
518 {
519 wxWindow* win = node->GetData();
520 if (SendIdleEvents(win))
521 needMore = TRUE;
522 node = node->GetNext();
523 }
524
525 return needMore;
526 }
527
528 // Send idle event to window and all subwindows
529 bool wxApp::SendIdleEvents(wxWindow* win)
530 {
531 bool needMore = FALSE;
532
533 wxIdleEvent event;
534 event.SetEventObject(win);
535 win->ProcessEvent(event);
536
537 if (event.MoreRequested())
538 needMore = TRUE;
539
540 wxNode* node = win->GetChildren().First();
541 while (node)
542 {
543 wxWindow* win = (wxWindow*) node->Data();
544 if (SendIdleEvents(win))
545 needMore = TRUE;
546
547 node = node->Next();
548 }
549 return needMore ;
550 }
551
552 void wxApp::DeletePendingObjects()
553 {
554 wxNode *node = wxPendingDelete.First();
555 while (node)
556 {
557 wxObject *obj = (wxObject *)node->Data();
558
559 delete obj;
560
561 if (wxPendingDelete.Member(obj))
562 delete node;
563
564 // Deleting one object may have deleted other pending
565 // objects, so start from beginning of list again.
566 node = wxPendingDelete.First();
567 }
568 }
569
570 // Create an application context
571 bool wxApp::OnInitGui()
572 {
573 XtToolkitInitialize() ;
574 wxTheApp->m_appContext = (WXAppContext) XtCreateApplicationContext() ;
575 Display *dpy = XtOpenDisplay((XtAppContext) wxTheApp->m_appContext,(String)NULL,NULL,
576 (const char*) wxTheApp->GetClassName(), NULL, 0,
577 # if XtSpecificationRelease < 5
578 (Cardinal*) &argc,
579 # else
580 &argc,
581 # endif
582 argv);
583
584 if (!dpy) {
585 wxString className(wxTheApp->GetClassName());
586 wxLogError(_("wxWindows could not open display for '%s': exiting."),
587 (const char*) className);
588 exit(-1);
589 }
590 m_initialDisplay = (WXDisplay*) dpy;
591
592 #ifdef __WXDEBUG__
593 // install the X error handler
594 gs_pfnXErrorHandler = XSetErrorHandler(wxXErrorHandler);
595 #endif // __WXDEBUG__
596
597 wxTheApp->m_topLevelWidget = (WXWidget) XtAppCreateShell((String)NULL, (const char*) wxTheApp->GetClassName(),
598 applicationShellWidgetClass,dpy,
599 NULL,0) ;
600
601 // Add general resize proc
602 XtActionsRec rec;
603 rec.string = "resize";
604 rec.proc = (XtActionProc)wxWidgetResizeProc;
605 XtAppAddActions((XtAppContext) wxTheApp->m_appContext, &rec, 1);
606
607 GetMainColormap(dpy);
608 m_maxRequestSize = XMaxRequestSize((Display*) dpy);
609
610 return TRUE;
611 }
612
613 WXColormap wxApp::GetMainColormap(WXDisplay* display)
614 {
615 if (!display) /* Must be called first with non-NULL display */
616 return m_mainColormap;
617
618 int defaultScreen = DefaultScreen((Display*) display);
619 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
620
621 Colormap c = DefaultColormapOfScreen(screen);
622
623 if (!m_mainColormap)
624 m_mainColormap = (WXColormap) c;
625
626 return (WXColormap) c;
627 }
628
629 // Returns TRUE if an accelerator has been processed
630 bool wxApp::CheckForAccelerator(WXEvent* event)
631 {
632 XEvent* xEvent = (XEvent*) event;
633 if (xEvent->xany.type == KeyPress)
634 {
635 // Find a wxWindow for this window
636 // TODO: should get display for the window, not the current display
637 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(), xEvent->xany.window);
638 wxWindow* win = NULL;
639
640 // Find the first wxWindow that corresponds to this event window
641 while (widget && !(win = wxGetWindowFromTable(widget)))
642 widget = XtParent(widget);
643
644 if (!widget || !win)
645 return FALSE;
646
647 wxKeyEvent keyEvent(wxEVT_CHAR);
648 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
649
650 // Now we have a wxKeyEvent and we have a wxWindow.
651 // Go up the hierarchy until we find a matching accelerator,
652 // or we get to the top.
653 while (win)
654 {
655 if (win->ProcessAccelerator(keyEvent))
656 return TRUE;
657 win = win->GetParent();
658 }
659 return FALSE;
660 }
661 return FALSE;
662 }
663
664 bool wxApp::CheckForKeyDown(WXEvent* event)
665 {
666 XEvent* xEvent = (XEvent*) event;
667 if (xEvent->xany.type == KeyPress)
668 {
669 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(),
670 xEvent->xany.window);
671 wxWindow* win = NULL;
672
673 // Find the first wxWindow that corresponds to this event window
674 while (widget && !(win = wxGetWindowFromTable(widget)))
675 widget = XtParent(widget);
676
677 if (!widget || !win)
678 return FALSE;
679
680 wxKeyEvent keyEvent(wxEVT_KEY_DOWN);
681 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
682
683 return win->ProcessEvent( keyEvent );
684 }
685
686 return FALSE;
687 }
688
689 bool wxApp::CheckForKeyUp(WXEvent* event)
690 {
691 XEvent* xEvent = (XEvent*) event;
692 if (xEvent->xany.type == KeyRelease)
693 {
694 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(),
695 xEvent->xany.window);
696 wxWindow* win = NULL;
697
698 // Find the first wxWindow that corresponds to this event window
699 while (widget && !(win = wxGetWindowFromTable(widget)))
700 widget = XtParent(widget);
701
702 if (!widget || !win)
703 return FALSE;
704
705 wxKeyEvent keyEvent(wxEVT_KEY_UP);
706 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
707
708 return win->ProcessEvent( keyEvent );
709 }
710
711 return FALSE;
712 }
713
714 void wxExit()
715 {
716 int retValue = 0;
717 if (wxTheApp)
718 retValue = wxTheApp->OnExit();
719
720 wxApp::CleanUp();
721 /*
722 * Exit in some platform-specific way. Not recommended that the app calls this:
723 * only for emergencies.
724 */
725 exit(retValue);
726 }
727
728 // Yield to other processes
729
730 bool wxApp::Yield(bool onlyIfNeeded)
731 {
732 bool s_inYield = FALSE;
733
734 if ( s_inYield )
735 {
736 if ( !onlyIfNeeded )
737 {
738 wxFAIL_MSG( wxT("wxYield called recursively" ) );
739 }
740
741 return FALSE;
742 }
743
744 s_inYield = TRUE;
745
746 while (wxTheApp && wxTheApp->Pending())
747 wxTheApp->Dispatch();
748
749 s_inYield = FALSE;
750
751 return TRUE;
752 }
753
754 // TODO use XmGetPixmap (?) to get the really standard icons!
755
756 // XPM hack: make the arrays const
757 #define static static const
758
759 #include "wx/generic/info.xpm"
760 #include "wx/generic/error.xpm"
761 #include "wx/generic/question.xpm"
762 #include "wx/generic/warning.xpm"
763
764 #undef static
765
766 wxIcon
767 wxApp::GetStdIcon(int which) const
768 {
769 switch(which)
770 {
771 case wxICON_INFORMATION:
772 return wxIcon(info_xpm);
773
774 case wxICON_QUESTION:
775 return wxIcon(question_xpm);
776
777 case wxICON_EXCLAMATION:
778 return wxIcon(warning_xpm);
779
780 default:
781 wxFAIL_MSG("requested non existent standard icon");
782 // still fall through
783
784 case wxICON_HAND:
785 return wxIcon(error_xpm);
786 }
787 }
788
789 // ----------------------------------------------------------------------------
790 // accessors for C modules
791 // ----------------------------------------------------------------------------
792
793 extern "C" XtAppContext wxGetAppContext()
794 {
795 return (XtAppContext)wxTheApp->GetAppContext();
796 }