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