Fix wxSocket under wxMotif.
[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 #include "wx/evtloop.h"
39 #include "wx/hash.h"
40
41 #if wxUSE_THREADS
42 #include "wx/thread.h"
43 #endif
44
45 #if wxUSE_WX_RESOURCES
46 #include "wx/resource.h"
47 #endif
48
49 #ifdef __VMS__
50 #pragma message disable nosimpint
51 #endif
52 #include <Xm/Xm.h>
53 #include <X11/Xlib.h>
54 #include <X11/Xutil.h>
55 #include <X11/Xresource.h>
56 #include <X11/Xatom.h>
57 #ifdef __VMS__
58 #pragma message enable nosimpint
59 #endif
60
61 #include "wx/motif/private.h"
62
63 #include <string.h>
64
65 extern wxList wxPendingDelete;
66 extern bool wxAddIdleCallback();
67
68 wxApp *wxTheApp = NULL;
69
70 wxHashTable *wxWidgetHashTable = NULL;
71
72 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
73
74 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
75 EVT_IDLE(wxApp::OnIdle)
76 END_EVENT_TABLE()
77
78 #ifdef __WXDEBUG__
79 typedef int (*XErrorHandlerFunc)(Display *, XErrorEvent *);
80
81 XErrorHandlerFunc gs_pfnXErrorHandler = 0;
82
83 static int wxXErrorHandler(Display *dpy, XErrorEvent *xevent)
84 {
85 // just forward to the default handler for now
86 return gs_pfnXErrorHandler(dpy, xevent);
87 }
88 #endif // __WXDEBUG__
89
90 long wxApp::sm_lastMessageTime = 0;
91
92 bool wxApp::Initialize()
93 {
94 wxClassInfo::InitializeClasses();
95
96 // GL: I'm annoyed ... I don't know where to put this and I don't want to
97 // create a module for that as it's part of the core.
98 #if wxUSE_THREADS
99 wxPendingEventsLocker = new wxCriticalSection();
100 #endif
101
102 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
103 wxTheColourDatabase->Initialize();
104
105 wxInitializeStockLists();
106 wxInitializeStockObjects();
107
108 #if wxUSE_WX_RESOURCES
109 wxInitializeResourceSystem();
110 #endif
111
112 // For PostScript printing
113 #if wxUSE_POSTSCRIPT
114 /* Done using wxModule now
115 wxInitializePrintSetupData();
116 wxThePrintPaperDatabase = new wxPrintPaperDatabase;
117 wxThePrintPaperDatabase->CreateDatabase();
118 */
119 #endif
120
121 wxBitmap::InitStandardHandlers();
122
123 wxWidgetHashTable = new wxHashTable(wxKEY_INTEGER);
124
125 wxModule::RegisterModules();
126 if (!wxModule::InitializeModules()) return FALSE;
127
128 return TRUE;
129 }
130
131 void wxApp::CleanUp()
132 {
133 delete wxWidgetHashTable;
134 wxWidgetHashTable = NULL;
135
136 wxModule::CleanUpModules();
137
138 #if wxUSE_WX_RESOURCES
139 wxCleanUpResourceSystem();
140 #endif
141
142 wxDeleteStockObjects() ;
143
144 // Destroy all GDI lists, etc.
145
146 wxDeleteStockLists();
147
148 delete wxTheColourDatabase;
149 wxTheColourDatabase = NULL;
150
151 #if wxUSE_POSTSCRIPT
152 /* Done using wxModule now
153 wxInitializePrintSetupData(FALSE);
154 delete wxThePrintPaperDatabase;
155 wxThePrintPaperDatabase = NULL;
156 */
157 #endif
158
159 wxBitmap::CleanUpHandlers();
160
161 wxClassInfo::CleanUpClasses();
162
163 delete wxTheApp;
164 wxTheApp = NULL;
165
166 // GL: I'm annoyed ... I don't know where to put this and I don't want to
167 // create a module for that as it's part of the core.
168 #if wxUSE_THREADS
169 delete wxPendingEvents;
170 delete wxPendingEventsLocker;
171 #endif
172
173 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
174 // At this point we want to check if there are any memory
175 // blocks that aren't part of the wxDebugContext itself,
176 // as a special case. Then when dumping we need to ignore
177 // wxDebugContext, too.
178 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
179 {
180 wxLogDebug("There were memory leaks.\n");
181 wxDebugContext::Dump();
182 wxDebugContext::PrintStatistics();
183 }
184 #endif
185
186 // do it as the very last thing because everything else can log messages
187 wxLog::DontCreateOnDemand();
188 // do it as the very last thing because everything else can log messages
189 delete wxLog::SetActiveTarget(NULL);
190 }
191
192 int wxEntry( int argc, char *argv[] )
193 {
194 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
195 // This seems to be necessary since there are 'rogue'
196 // objects present at this point (perhaps global objects?)
197 // Setting a checkpoint will ignore them as far as the
198 // memory checking facility is concerned.
199 // Of course you may argue that memory allocated in globals should be
200 // checked, but this is a reasonable compromise.
201 wxDebugContext::SetCheckpoint();
202 #endif
203
204 if (!wxApp::Initialize())
205 return FALSE;
206
207 if (!wxTheApp)
208 {
209 if (!wxApp::GetInitializerFunction())
210 {
211 printf( "wxWindows error: No initializer - use IMPLEMENT_APP macro.\n" );
212 return 0;
213 };
214
215 wxTheApp = (wxApp*) (* wxApp::GetInitializerFunction()) ();
216 };
217
218 if (!wxTheApp)
219 {
220 printf( "wxWindows error: wxTheApp == NULL\n" );
221 return 0;
222 };
223
224 wxTheApp->SetClassName(wxFileNameFromPath(argv[0]));
225 wxTheApp->SetAppName(wxFileNameFromPath(argv[0]));
226
227 wxTheApp->argc = argc;
228 wxTheApp->argv = argv;
229
230 // GUI-specific initialization, such as creating an app context.
231 wxTheApp->OnInitGui();
232
233 // Here frames insert themselves automatically into wxTopLevelWindows by
234 // getting created in OnInit().
235
236 int retValue = 0;
237 if (wxTheApp->OnInit())
238 {
239 if (wxTheApp->Initialized()) retValue = wxTheApp->OnRun();
240 }
241
242 // flush the logged messages if any
243 wxLog *pLog = wxLog::GetActiveTarget();
244 if ( pLog != NULL && pLog->HasPendingMessages() )
245 pLog->Flush();
246
247 delete wxLog::SetActiveTarget(new wxLogStderr); // So dialog boxes aren't used
248 // for further messages
249
250 if (wxTheApp->GetTopWindow())
251 {
252 delete wxTheApp->GetTopWindow();
253 wxTheApp->SetTopWindow(NULL);
254 }
255
256 wxTheApp->DeletePendingObjects();
257
258 wxTheApp->OnExit();
259
260 wxApp::CleanUp();
261
262 return retValue;
263 };
264
265 // Static member initialization
266 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
267
268 wxApp::wxApp()
269 {
270 argc = 0;
271 argv = NULL;
272
273 m_eventLoop = new wxEventLoop;
274 m_mainColormap = (WXColormap) NULL;
275 m_appContext = (WXAppContext) NULL;
276 m_topLevelWidget = (WXWidget) NULL;
277 m_maxRequestSize = 0;
278 m_initialDisplay = (WXDisplay*) 0;
279 }
280
281 wxApp::~wxApp()
282 {
283 delete m_eventLoop;
284 }
285
286 bool wxApp::Initialized()
287 {
288 if (GetTopWindow())
289 return TRUE;
290 else
291 return FALSE;
292 }
293
294 int wxApp::MainLoop()
295 {
296 /*
297 * Sit around forever waiting to process X-events. Property Change
298 * event are handled special, because they have to refer to
299 * the root window rather than to a widget. therefore we can't
300 * use an Xt-eventhandler.
301 */
302
303 XSelectInput(XtDisplay((Widget) wxTheApp->GetTopLevelWidget()),
304 XDefaultRootWindow(XtDisplay((Widget) wxTheApp->GetTopLevelWidget())),
305 PropertyChangeMask);
306
307 m_eventLoop->Run();
308
309 return 0;
310 }
311
312 // Processes an idle event.
313 // Returns TRUE if more time is needed.
314 bool wxApp::ProcessIdle()
315 {
316 wxIdleEvent event;
317
318 return ProcessEvent(event) && event.MoreRequested();
319 }
320
321 void wxApp::ExitMainLoop()
322 {
323 m_eventLoop->Exit();
324 }
325
326 // Is a message/event pending?
327 bool wxApp::Pending()
328 {
329 return m_eventLoop->Pending();
330 #if 0
331 XFlush(XtDisplay( (Widget) wxTheApp->GetTopLevelWidget() ));
332
333 // Fix by Doug from STI, to prevent a stall if non-X event
334 // is found.
335 return ((XtAppPending( (XtAppContext) GetAppContext() ) & XtIMXEvent) != 0) ;
336 #endif
337 }
338
339 // Dispatch a message.
340 void wxApp::Dispatch()
341 {
342 m_eventLoop->Dispatch();
343 }
344
345 // This should be redefined in a derived class for
346 // handling property change events for XAtom IPC.
347 void wxApp::HandlePropertyChange(WXEvent *event)
348 {
349 // by default do nothing special
350 XtDispatchEvent((XEvent*) event); /* let Motif do the work */
351 }
352
353 void wxApp::OnIdle(wxIdleEvent& event)
354 {
355 static bool inOnIdle = FALSE;
356
357 // Avoid recursion (via ProcessEvent default case)
358 if (inOnIdle)
359 return;
360
361 inOnIdle = TRUE;
362
363 // If there are pending events, we must process them: pending events
364 // are either events to the threads other than main or events posted
365 // with wxPostEvent() functions
366 // GRG: I have moved this here so that all pending events are processed
367 // before starting to delete any objects. This behaves better (in
368 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
369 // behaviour. Also removed the '#if wxUSE_THREADS' around it.
370 // Changed Mar/2000 before 2.1.14
371
372 // Flush pending events.
373 ProcessPendingEvents();
374
375 // 'Garbage' collection of windows deleted with Close().
376 DeletePendingObjects();
377
378 // flush the logged messages if any
379 wxLog *pLog = wxLog::GetActiveTarget();
380 if ( pLog != NULL && pLog->HasPendingMessages() )
381 pLog->Flush();
382
383 // Send OnIdle events to all windows
384 bool needMore = SendIdleEvents();
385
386 if (needMore)
387 event.RequestMore(TRUE);
388
389 inOnIdle = FALSE;
390 }
391
392 // Send idle event to all top-level windows
393 bool wxApp::SendIdleEvents()
394 {
395 bool needMore = FALSE;
396
397 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
398 while (node)
399 {
400 wxWindow* win = node->GetData();
401 if (SendIdleEvents(win))
402 needMore = TRUE;
403 node = node->GetNext();
404 }
405
406 return needMore;
407 }
408
409 // Send idle event to window and all subwindows
410 bool wxApp::SendIdleEvents(wxWindow* win)
411 {
412 bool needMore = FALSE;
413
414 wxIdleEvent event;
415 event.SetEventObject(win);
416 win->ProcessEvent(event);
417
418 if (event.MoreRequested())
419 needMore = TRUE;
420
421 wxWindowList::Node* node = win->GetChildren().GetFirst();
422 while (node)
423 {
424 wxWindow* win = node->GetData();
425 if (SendIdleEvents(win))
426 needMore = TRUE;
427
428 node = node->GetNext();
429 }
430 return needMore ;
431 }
432
433 void wxApp::DeletePendingObjects()
434 {
435 wxList::Node *node = wxPendingDelete.GetFirst();
436 while (node)
437 {
438 wxObject *obj = node->GetData();
439
440 delete obj;
441
442 if (wxPendingDelete.Member(obj))
443 delete node;
444
445 // Deleting one object may have deleted other pending
446 // objects, so start from beginning of list again.
447 node = wxPendingDelete.GetFirst();
448 }
449 }
450
451 static char *fallbackResources[] = {
452 "*menuBar.marginHeight: 0",
453 "*menuBar.shadowThickness: 1",
454 "*background: #c0c0c0",
455 "*foreground: black",
456 NULL
457 };
458
459 // Create an application context
460 bool wxApp::OnInitGui()
461 {
462 if( !wxAppBase::OnInitGui() )
463 return FALSE;
464
465 XtToolkitInitialize() ;
466 wxTheApp->m_appContext = (WXAppContext) XtCreateApplicationContext();
467 XtAppSetFallbackResources((XtAppContext) wxTheApp->m_appContext, fallbackResources);
468
469 Display *dpy = XtOpenDisplay((XtAppContext) wxTheApp->m_appContext,(String)NULL,NULL,
470 wxTheApp->GetClassName().c_str(), NULL, 0,
471 # if XtSpecificationRelease < 5
472 (Cardinal*) &argc,
473 # else
474 &argc,
475 # endif
476 argv);
477
478 if (!dpy) {
479 // if you don't log to stderr, nothing will be shown...
480 delete wxLog::SetActiveTarget(new wxLogStderr);
481 wxString className(wxTheApp->GetClassName());
482 wxLogError(_("wxWindows could not open display for '%s': exiting."),
483 className.c_str());
484 exit(-1);
485 }
486 m_initialDisplay = (WXDisplay*) dpy;
487
488 #ifdef __WXDEBUG__
489 // install the X error handler
490 gs_pfnXErrorHandler = XSetErrorHandler(wxXErrorHandler);
491 #endif // __WXDEBUG__
492
493 wxTheApp->m_topLevelWidget =
494 (WXWidget) XtAppCreateShell((String)NULL,
495 wxTheApp->GetClassName().c_str(),
496 applicationShellWidgetClass,dpy,
497 NULL,0) ;
498
499 // Add general resize proc
500 XtActionsRec rec;
501 rec.string = "resize";
502 rec.proc = (XtActionProc)wxWidgetResizeProc;
503 XtAppAddActions((XtAppContext) wxTheApp->m_appContext, &rec, 1);
504
505 GetMainColormap(dpy);
506 m_maxRequestSize = XMaxRequestSize((Display*) dpy);
507
508 wxAddIdleCallback();
509
510 return TRUE;
511 }
512
513 WXColormap wxApp::GetMainColormap(WXDisplay* display)
514 {
515 if (!display) /* Must be called first with non-NULL display */
516 return m_mainColormap;
517
518 int defaultScreen = DefaultScreen((Display*) display);
519 Screen* screen = XScreenOfDisplay((Display*) display, defaultScreen);
520
521 Colormap c = DefaultColormapOfScreen(screen);
522
523 if (!m_mainColormap)
524 m_mainColormap = (WXColormap) c;
525
526 return (WXColormap) c;
527 }
528
529 void wxExit()
530 {
531 int retValue = 0;
532 if (wxTheApp)
533 retValue = wxTheApp->OnExit();
534
535 wxApp::CleanUp();
536 /*
537 * Exit in some platform-specific way. Not recommended that the app calls this:
538 * only for emergencies.
539 */
540 exit(retValue);
541 }
542
543 // Yield to other processes
544
545 bool wxApp::Yield(bool onlyIfNeeded)
546 {
547 bool s_inYield = FALSE;
548
549 if ( s_inYield )
550 {
551 if ( !onlyIfNeeded )
552 {
553 wxFAIL_MSG( wxT("wxYield called recursively" ) );
554 }
555
556 return FALSE;
557 }
558
559 s_inYield = TRUE;
560
561 while (wxTheApp && wxTheApp->Pending())
562 wxTheApp->Dispatch();
563
564 s_inYield = FALSE;
565
566 return TRUE;
567 }
568
569 // ----------------------------------------------------------------------------
570 // accessors for C modules
571 // ----------------------------------------------------------------------------
572
573 extern "C" XtAppContext wxGetAppContext()
574 {
575 return (XtAppContext)wxTheApp->GetAppContext();
576 }