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