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