1. Assorted Motif fixes
[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 if (CheckForAccelerator(_event))
344 {
345 // Do nothing! We intercepted and processed the event as an
346 // accelerator.
347 return;
348 }
349 else if (CheckForKeyDown(_event))
350 {
351 // We intercepted and processed the key down event
352 return;
353 }
354 else
355 {
356 XtDispatchEvent(event);
357 return;
358 }
359 }
360 else if (event->type == PropertyNotify)
361 {
362 HandlePropertyChange(_event);
363 return;
364 }
365 else if (event->type == ResizeRequest)
366 {
367 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
368 * If resize event, don't resize until the last resize event for this
369 * window is recieved. Prevents flicker as windows are resized.
370 */
371
372 Display *disp = XtDisplay((Widget) wxTheApp->GetTopLevelWidget());
373 Window win = event->xany.window;
374 XEvent report;
375
376 // to avoid flicker
377 report = * event;
378 while( XCheckTypedWindowEvent (disp, win, ResizeRequest, &report));
379
380 // TODO: when implementing refresh optimization, we can use
381 // XtAddExposureToRegion to expand the window's paint region.
382
383 XtDispatchEvent(event);
384 }
385 else
386 {
387 XtDispatchEvent(event);
388 }
389 }
390
391 // Returns TRUE if more time is needed.
392 bool wxApp::ProcessIdle()
393 {
394 wxIdleEvent event;
395 event.SetEventObject(this);
396 ProcessEvent(event);
397
398 return event.MoreRequested();
399 }
400
401 void wxApp::ExitMainLoop()
402 {
403 m_keepGoing = FALSE;
404 }
405
406 // Is a message/event pending?
407 bool wxApp::Pending()
408 {
409 XFlush(XtDisplay( (Widget) wxTheApp->GetTopLevelWidget() ));
410
411 // Fix by Doug from STI, to prevent a stall if non-X event
412 // is found.
413 return ((XtAppPending( (XtAppContext) GetAppContext() ) & XtIMXEvent) != 0) ;
414 }
415
416 // Dispatch a message.
417 void wxApp::Dispatch()
418 {
419 // XtAppProcessEvent( (XtAppContext) wxTheApp->GetAppContext(), XtIMAll);
420
421 XEvent event;
422 XtAppNextEvent((XtAppContext) GetAppContext(), &event);
423 ProcessXEvent((WXEvent*) & event);
424 }
425
426 // This should be redefined in a derived class for
427 // handling property change events for XAtom IPC.
428 void wxApp::HandlePropertyChange(WXEvent *event)
429 {
430 // by default do nothing special
431 XtDispatchEvent((XEvent*) event); /* let Motif do the work */
432 }
433
434 void wxApp::OnIdle(wxIdleEvent& event)
435 {
436 static bool inOnIdle = FALSE;
437
438 // Avoid recursion (via ProcessEvent default case)
439 if (inOnIdle)
440 return;
441
442 inOnIdle = TRUE;
443
444 // 'Garbage' collection of windows deleted with Close().
445 DeletePendingObjects();
446
447 #if wxUSE_THREADS
448 // Flush pending events.
449 ProcessPendingEvents();
450 #endif
451
452 // flush the logged messages if any
453 wxLog *pLog = wxLog::GetActiveTarget();
454 if ( pLog != NULL && pLog->HasPendingMessages() )
455 pLog->Flush();
456
457 // Send OnIdle events to all windows
458 bool needMore = SendIdleEvents();
459
460 if (needMore)
461 event.RequestMore(TRUE);
462
463 inOnIdle = FALSE;
464 }
465
466 // Send idle event to all top-level windows
467 bool wxApp::SendIdleEvents()
468 {
469 bool needMore = FALSE;
470
471 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
472 while (node)
473 {
474 wxWindow* win = node->GetData();
475 if (SendIdleEvents(win))
476 needMore = TRUE;
477 node = node->GetNext();
478 }
479
480 return needMore;
481 }
482
483 // Send idle event to window and all subwindows
484 bool wxApp::SendIdleEvents(wxWindow* win)
485 {
486 bool needMore = FALSE;
487
488 wxIdleEvent event;
489 event.SetEventObject(win);
490 win->ProcessEvent(event);
491
492 if (event.MoreRequested())
493 needMore = TRUE;
494
495 wxNode* node = win->GetChildren().First();
496 while (node)
497 {
498 wxWindow* win = (wxWindow*) node->Data();
499 if (SendIdleEvents(win))
500 needMore = TRUE;
501
502 node = node->Next();
503 }
504 return needMore ;
505 }
506
507 void wxApp::DeletePendingObjects()
508 {
509 wxNode *node = wxPendingDelete.First();
510 while (node)
511 {
512 wxObject *obj = (wxObject *)node->Data();
513
514 delete obj;
515
516 if (wxPendingDelete.Member(obj))
517 delete node;
518
519 // Deleting one object may have deleted other pending
520 // objects, so start from beginning of list again.
521 node = wxPendingDelete.First();
522 }
523 }
524
525 #if wxUSE_THREADS
526 void wxApp::ProcessPendingEvents()
527 {
528 wxNode *node = wxPendingEvents->First();
529 wxCriticalSectionLocker locker(*wxPendingEventsLocker);
530
531 while (node)
532 {
533 wxEvtHandler *handler = (wxEvtHandler *)node->Data();
534
535 handler->ProcessPendingEvents();
536
537 delete node;
538 node = wxPendingEvents->First();
539 }
540 }
541 #endif // wxUSE_THREADS
542
543 // Create an application context
544 bool wxApp::OnInitGui()
545 {
546 XtToolkitInitialize() ;
547 wxTheApp->m_appContext = (WXAppContext) XtCreateApplicationContext() ;
548 Display *dpy = XtOpenDisplay((XtAppContext) wxTheApp->m_appContext,(String)NULL,NULL,
549 (const char*) wxTheApp->GetClassName(), NULL, 0,
550 # if XtSpecificationRelease < 5
551 (Cardinal*) &argc,
552 # else
553 &argc,
554 # endif
555 argv);
556
557 if (!dpy) {
558 wxString className(wxTheApp->GetClassName());
559 wxLogError(_("wxWindows could not open display for '%s': exiting."),
560 (const char*) className);
561 exit(-1);
562 }
563 m_initialDisplay = (WXDisplay*) dpy;
564
565 wxTheApp->m_topLevelWidget = (WXWidget) XtAppCreateShell((String)NULL, (const char*) wxTheApp->GetClassName(),
566 applicationShellWidgetClass,dpy,
567 NULL,0) ;
568
569 // Add general resize proc
570 XtActionsRec rec;
571 rec.string = "resize";
572 rec.proc = (XtActionProc)wxWidgetResizeProc;
573 XtAppAddActions((XtAppContext) wxTheApp->m_appContext, &rec, 1);
574
575 GetMainColormap(dpy);
576 m_maxRequestSize = XMaxRequestSize((Display*) dpy);
577
578 return TRUE;
579 }
580
581 WXColormap wxApp::GetMainColormap(WXDisplay* display)
582 {
583 if (!display) /* Must be called first with non-NULL display */
584 return m_mainColormap;
585
586 int defaultScreen = DefaultScreen((Display*) display);
587 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
588
589 Colormap c = DefaultColormapOfScreen(screen);
590
591 if (!m_mainColormap)
592 m_mainColormap = (WXColormap) c;
593
594 return (WXColormap) c;
595 }
596
597 // Returns TRUE if an accelerator has been processed
598 bool wxApp::CheckForAccelerator(WXEvent* event)
599 {
600 XEvent* xEvent = (XEvent*) event;
601 if (xEvent->xany.type == KeyPress)
602 {
603 // Find a wxWindow for this window
604 // TODO: should get display for the window, not the current display
605 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(), xEvent->xany.window);
606 wxWindow* win = NULL;
607
608 // Find the first wxWindow that corresponds to this event window
609 while (widget && !(win = wxGetWindowFromTable(widget)))
610 widget = XtParent(widget);
611
612 if (!widget || !win)
613 return FALSE;
614
615 wxKeyEvent keyEvent(wxEVT_CHAR);
616 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
617
618 // Now we have a wxKeyEvent and we have a wxWindow.
619 // Go up the hierarchy until we find a matching accelerator,
620 // or we get to the top.
621 while (win)
622 {
623 if (win->ProcessAccelerator(keyEvent))
624 return TRUE;
625 win = win->GetParent();
626 }
627 return FALSE;
628 }
629 return FALSE;
630 }
631
632 bool wxApp::CheckForKeyDown(WXEvent* event)
633 {
634 XEvent* xEvent = (XEvent*) event;
635 // VZ: this code doesn't work for me because it never finds the correct
636 // window. Also, if we go this way, we should generate KEY_UP and
637 // CHAR events as well, not only KEY_DOWN.
638 #if 0
639 if (xEvent->xany.type == KeyPress)
640 {
641 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(),
642 xEvent->xany.window);
643 wxWindow* win = NULL;
644
645 // Find the first wxWindow that corresponds to this event window
646 while (widget && !(win = wxGetWindowFromTable(widget)))
647 widget = XtParent(widget);
648
649 if (!widget || !win)
650 return FALSE;
651
652 wxKeyEvent keyEvent(wxEVT_KEY_DOWN);
653 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
654
655 win->ProcessEvent( keyEvent );
656 return (keyEvent.GetSkipped() != TRUE);
657 }
658 #endif // 0
659
660 return FALSE;
661 }
662
663 void wxExit()
664 {
665 int retValue = 0;
666 if (wxTheApp)
667 retValue = wxTheApp->OnExit();
668
669 wxApp::CleanUp();
670 /*
671 * Exit in some platform-specific way. Not recommended that the app calls this:
672 * only for emergencies.
673 */
674 exit(retValue);
675 }
676
677 // Yield to other processes
678 bool wxYield()
679 {
680 while (wxTheApp && wxTheApp->Pending())
681 wxTheApp->Dispatch();
682
683 // VZ: is it the same as this (taken from old wxExecute)?
684 #if 0
685 XtAppProcessEvent((XtAppContext) wxTheApp->GetAppContext(), XtIMAll);
686 #endif
687
688 return TRUE;
689 }
690
691 // TODO use XmGetPixmap (?) to get the really standard icons!
692
693 #include "wx/generic/info.xpm"
694 #include "wx/generic/error.xpm"
695 #include "wx/generic/question.xpm"
696 #include "wx/generic/warning.xpm"
697
698 wxIcon
699 wxApp::GetStdIcon(int which) const
700 {
701 switch(which)
702 {
703 case wxICON_INFORMATION:
704 return wxIcon(info_xpm);
705
706 case wxICON_QUESTION:
707 return wxIcon(question_xpm);
708
709 case wxICON_EXCLAMATION:
710 return wxIcon(warning_xpm);
711
712 default:
713 wxFAIL_MSG("requested non existent standard icon");
714 // still fall through
715
716 case wxICON_HAND:
717 return wxIcon(error_xpm);
718 }
719 }