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