]> git.saurik.com Git - wxWidgets.git/blob - src/motif/app.cpp
Font work.
[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 argc = 0;
268 argv = NULL;
269
270 m_mainColormap = (WXColormap) NULL;
271 m_appContext = (WXAppContext) NULL;
272 m_topLevelWidget = (WXWidget) NULL;
273 m_maxRequestSize = 0;
274 m_initialDisplay = (WXDisplay*) 0;
275 }
276
277 bool wxApp::Initialized()
278 {
279 if (GetTopWindow())
280 return TRUE;
281 else
282 return FALSE;
283 }
284
285 int wxApp::MainLoop()
286 {
287 m_keepGoing = TRUE;
288
289 /*
290 * Sit around forever waiting to process X-events. Property Change
291 * event are handled special, because they have to refer to
292 * the root window rather than to a widget. therefore we can't
293 * use an Xt-eventhandler.
294 */
295
296 XSelectInput(XtDisplay((Widget) wxTheApp->GetTopLevelWidget()),
297 XDefaultRootWindow(XtDisplay((Widget) wxTheApp->GetTopLevelWidget())),
298 PropertyChangeMask);
299
300 XEvent event;
301
302 // Use this flag to allow breaking the loop via wxApp::ExitMainLoop()
303 while (m_keepGoing)
304 {
305 XtAppNextEvent( (XtAppContext) wxTheApp->GetAppContext(), &event);
306
307 ProcessXEvent((WXEvent*) & event);
308
309 if (XtAppPending( (XtAppContext) wxTheApp->GetAppContext() ) == 0)
310 {
311 if (!ProcessIdle())
312 {
313 #if wxUSE_THREADS
314 // leave the main loop to give other threads a chance to
315 // perform their GUI work
316 wxMutexGuiLeave();
317 wxUsleep(20);
318 wxMutexGuiEnter();
319 #endif
320 }
321 }
322
323 }
324
325 return 0;
326 }
327
328 // Processes an X event.
329 void wxApp::ProcessXEvent(WXEvent* _event)
330 {
331 XEvent* event = (XEvent*) _event;
332
333 if (event->type == KeyPress)
334 {
335 #if 0 // def __WXDEBUG__
336 Widget widget = XtWindowToWidget(event->xany.display, event->xany.window);
337 wxLogDebug("Got key press event for 0x%08x (parent = 0x%08x)",
338 widget, XtParent(widget));
339 #endif // DEBUG
340
341 if (CheckForAccelerator(_event))
342 {
343 // Do nothing! We intercepted and processed the event as an
344 // accelerator.
345 return;
346 }
347 #if 1
348 // It seemed before that this hack was redundant and
349 // key down events were being generated by wxCanvasInputEvent.
350 // But no longer - why ???
351 //
352 else if (CheckForKeyDown(_event))
353 {
354 // We intercepted and processed the key down event
355 return;
356 }
357 #endif
358 else
359 {
360 XtDispatchEvent(event);
361 return;
362 }
363 }
364 else if (event->type == KeyRelease)
365 {
366 // TODO: work out why we still need this ! -michael
367 //
368 if (CheckForKeyUp(_event))
369 {
370 // We intercepted and processed the key up event
371 return;
372 }
373 else
374 {
375 XtDispatchEvent(event);
376 return;
377 }
378 }
379 else if (event->type == PropertyNotify)
380 {
381 HandlePropertyChange(_event);
382 return;
383 }
384 else if (event->type == ResizeRequest)
385 {
386 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
387 * If resize event, don't resize until the last resize event for this
388 * window is recieved. Prevents flicker as windows are resized.
389 */
390
391 Display *disp = XtDisplay((Widget) wxTheApp->GetTopLevelWidget());
392 Window win = event->xany.window;
393 XEvent report;
394
395 // to avoid flicker
396 report = * event;
397 while( XCheckTypedWindowEvent (disp, win, ResizeRequest, &report));
398
399 // TODO: when implementing refresh optimization, we can use
400 // XtAddExposureToRegion to expand the window's paint region.
401
402 XtDispatchEvent(event);
403 }
404 else
405 {
406 XtDispatchEvent(event);
407 }
408 }
409
410 // Returns TRUE if more time is needed.
411 bool wxApp::ProcessIdle()
412 {
413 wxIdleEvent event;
414 event.SetEventObject(this);
415 ProcessEvent(event);
416
417 return event.MoreRequested();
418 }
419
420 void wxApp::ExitMainLoop()
421 {
422 m_keepGoing = FALSE;
423 }
424
425 // Is a message/event pending?
426 bool wxApp::Pending()
427 {
428 XFlush(XtDisplay( (Widget) wxTheApp->GetTopLevelWidget() ));
429
430 // Fix by Doug from STI, to prevent a stall if non-X event
431 // is found.
432 return ((XtAppPending( (XtAppContext) GetAppContext() ) & XtIMXEvent) != 0) ;
433 }
434
435 // Dispatch a message.
436 void wxApp::Dispatch()
437 {
438 // XtAppProcessEvent( (XtAppContext) wxTheApp->GetAppContext(), XtIMAll);
439
440 XEvent event;
441 XtAppNextEvent((XtAppContext) GetAppContext(), &event);
442 ProcessXEvent((WXEvent*) & event);
443 }
444
445 // This should be redefined in a derived class for
446 // handling property change events for XAtom IPC.
447 void wxApp::HandlePropertyChange(WXEvent *event)
448 {
449 // by default do nothing special
450 XtDispatchEvent((XEvent*) event); /* let Motif do the work */
451 }
452
453 void wxApp::OnIdle(wxIdleEvent& event)
454 {
455 static bool inOnIdle = FALSE;
456
457 // Avoid recursion (via ProcessEvent default case)
458 if (inOnIdle)
459 return;
460
461 inOnIdle = TRUE;
462
463 // If there are pending events, we must process them: pending events
464 // are either events to the threads other than main or events posted
465 // with wxPostEvent() functions
466 // GRG: I have moved this here so that all pending events are processed
467 // before starting to delete any objects. This behaves better (in
468 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
469 // behaviour. Also removed the '#if wxUSE_THREADS' around it.
470 // Changed Mar/2000 before 2.1.14
471
472 // Flush pending events.
473 ProcessPendingEvents();
474
475 // 'Garbage' collection of windows deleted with Close().
476 DeletePendingObjects();
477
478 // flush the logged messages if any
479 wxLog *pLog = wxLog::GetActiveTarget();
480 if ( pLog != NULL && pLog->HasPendingMessages() )
481 pLog->Flush();
482
483 // Send OnIdle events to all windows
484 bool needMore = SendIdleEvents();
485
486 if (needMore)
487 event.RequestMore(TRUE);
488
489 inOnIdle = FALSE;
490 }
491
492 void wxWakeUpIdle()
493 {
494 // **** please implement me! ****
495 // Wake up the idle handler processor, even if it is in another thread...
496 }
497
498
499 // Send idle event to all top-level windows
500 bool wxApp::SendIdleEvents()
501 {
502 bool needMore = FALSE;
503
504 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
505 while (node)
506 {
507 wxWindow* win = node->GetData();
508 if (SendIdleEvents(win))
509 needMore = TRUE;
510 node = node->GetNext();
511 }
512
513 return needMore;
514 }
515
516 // Send idle event to window and all subwindows
517 bool wxApp::SendIdleEvents(wxWindow* win)
518 {
519 bool needMore = FALSE;
520
521 wxIdleEvent event;
522 event.SetEventObject(win);
523 win->ProcessEvent(event);
524
525 if (event.MoreRequested())
526 needMore = TRUE;
527
528 wxWindowList::Node* node = win->GetChildren().GetFirst();
529 while (node)
530 {
531 wxWindow* win = node->GetData();
532 if (SendIdleEvents(win))
533 needMore = TRUE;
534
535 node = node->GetNext();
536 }
537 return needMore ;
538 }
539
540 void wxApp::DeletePendingObjects()
541 {
542 wxNode *node = wxPendingDelete.GetFirst();
543 while (node)
544 {
545 wxObject *obj = node->GetData();
546
547 delete obj;
548
549 if (wxPendingDelete.Member(obj))
550 delete node;
551
552 // Deleting one object may have deleted other pending
553 // objects, so start from beginning of list again.
554 node = wxPendingDelete.GetFirst();
555 }
556 }
557
558 static char *fallbackResources[] = {
559 "*menuBar.marginHeight: 0",
560 "*menuBar.shadowThickness: 1",
561 "*background: #c0c0c0",
562 "*foreground: black",
563 NULL
564 };
565
566 // Create an application context
567 bool wxApp::OnInitGui()
568 {
569 if( !wxAppBase::OnInitGui() )
570 return FALSE;
571
572 XtToolkitInitialize() ;
573 wxTheApp->m_appContext = (WXAppContext) XtCreateApplicationContext();
574 XtAppSetFallbackResources((XtAppContext) wxTheApp->m_appContext, fallbackResources);
575
576 Display *dpy = XtOpenDisplay((XtAppContext) wxTheApp->m_appContext,(String)NULL,NULL,
577 (const char*) wxTheApp->GetClassName(), NULL, 0,
578 # if XtSpecificationRelease < 5
579 (Cardinal*) &argc,
580 # else
581 &argc,
582 # endif
583 argv);
584
585 if (!dpy) {
586 // if you don't log to stderr, nothing will be shown...
587 delete wxLog::SetActiveTarget(new wxLogStderr);
588 wxString className(wxTheApp->GetClassName());
589 wxLogError(_("wxWindows could not open display for '%s': exiting."),
590 (const char*) className);
591 exit(-1);
592 }
593 m_initialDisplay = (WXDisplay*) dpy;
594
595 #ifdef __WXDEBUG__
596 // install the X error handler
597 gs_pfnXErrorHandler = XSetErrorHandler(wxXErrorHandler);
598 #endif // __WXDEBUG__
599
600 wxTheApp->m_topLevelWidget = (WXWidget) XtAppCreateShell((String)NULL, (const char*) wxTheApp->GetClassName(),
601 applicationShellWidgetClass,dpy,
602 NULL,0) ;
603
604 // Add general resize proc
605 XtActionsRec rec;
606 rec.string = "resize";
607 rec.proc = (XtActionProc)wxWidgetResizeProc;
608 XtAppAddActions((XtAppContext) wxTheApp->m_appContext, &rec, 1);
609
610 GetMainColormap(dpy);
611 m_maxRequestSize = XMaxRequestSize((Display*) dpy);
612
613 return TRUE;
614 }
615
616 WXColormap wxApp::GetMainColormap(WXDisplay* display)
617 {
618 if (!display) /* Must be called first with non-NULL display */
619 return m_mainColormap;
620
621 int defaultScreen = DefaultScreen((Display*) display);
622 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
623
624 Colormap c = DefaultColormapOfScreen(screen);
625
626 if (!m_mainColormap)
627 m_mainColormap = (WXColormap) c;
628
629 return (WXColormap) c;
630 }
631
632 // Returns TRUE if an accelerator has been processed
633 bool wxApp::CheckForAccelerator(WXEvent* event)
634 {
635 XEvent* xEvent = (XEvent*) event;
636 if (xEvent->xany.type == KeyPress)
637 {
638 // Find a wxWindow for this window
639 // TODO: should get display for the window, not the current display
640 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(), xEvent->xany.window);
641 wxWindow* win = NULL;
642
643 // Find the first wxWindow that corresponds to this event window
644 while (widget && !(win = wxGetWindowFromTable(widget)))
645 widget = XtParent(widget);
646
647 if (!widget || !win)
648 return FALSE;
649
650 wxKeyEvent keyEvent(wxEVT_CHAR);
651 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
652
653 // Now we have a wxKeyEvent and we have a wxWindow.
654 // Go up the hierarchy until we find a matching accelerator,
655 // or we get to the top.
656 while (win)
657 {
658 if (win->ProcessAccelerator(keyEvent))
659 return TRUE;
660 win = win->GetParent();
661 }
662 return FALSE;
663 }
664 return FALSE;
665 }
666
667 bool wxApp::CheckForKeyDown(WXEvent* event)
668 {
669 XEvent* xEvent = (XEvent*) event;
670 if (xEvent->xany.type == KeyPress)
671 {
672 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(),
673 xEvent->xany.window);
674 wxWindow* win = NULL;
675
676 // Find the first wxWindow that corresponds to this event window
677 while (widget && !(win = wxGetWindowFromTable(widget)))
678 widget = XtParent(widget);
679
680 if (!widget || !win)
681 return FALSE;
682
683 wxKeyEvent keyEvent(wxEVT_KEY_DOWN);
684 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
685
686 return win->ProcessEvent( keyEvent );
687 }
688
689 return FALSE;
690 }
691
692 bool wxApp::CheckForKeyUp(WXEvent* event)
693 {
694 XEvent* xEvent = (XEvent*) event;
695 if (xEvent->xany.type == KeyRelease)
696 {
697 Widget widget = XtWindowToWidget((Display*) wxGetDisplay(),
698 xEvent->xany.window);
699 wxWindow* win = NULL;
700
701 // Find the first wxWindow that corresponds to this event window
702 while (widget && !(win = wxGetWindowFromTable(widget)))
703 widget = XtParent(widget);
704
705 if (!widget || !win)
706 return FALSE;
707
708 wxKeyEvent keyEvent(wxEVT_KEY_UP);
709 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, xEvent);
710
711 return win->ProcessEvent( keyEvent );
712 }
713
714 return FALSE;
715 }
716
717 void wxExit()
718 {
719 int retValue = 0;
720 if (wxTheApp)
721 retValue = wxTheApp->OnExit();
722
723 wxApp::CleanUp();
724 /*
725 * Exit in some platform-specific way. Not recommended that the app calls this:
726 * only for emergencies.
727 */
728 exit(retValue);
729 }
730
731 // Yield to other processes
732
733 bool wxApp::Yield(bool onlyIfNeeded)
734 {
735 bool s_inYield = FALSE;
736
737 if ( s_inYield )
738 {
739 if ( !onlyIfNeeded )
740 {
741 wxFAIL_MSG( wxT("wxYield called recursively" ) );
742 }
743
744 return FALSE;
745 }
746
747 s_inYield = TRUE;
748
749 while (wxTheApp && wxTheApp->Pending())
750 wxTheApp->Dispatch();
751
752 s_inYield = FALSE;
753
754 return TRUE;
755 }
756
757 // ----------------------------------------------------------------------------
758 // accessors for C modules
759 // ----------------------------------------------------------------------------
760
761 extern "C" XtAppContext wxGetAppContext()
762 {
763 return (XtAppContext)wxTheApp->GetAppContext();
764 }