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