don't hang forever in Dispatch() if there is no event loop
[wxWidgets.git] / src / common / appcmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: common/appcmn.cpp
3 // Purpose: wxAppConsole and wxAppBase methods common to all platforms
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 18.10.99
7 // RCS-ID: $Id$
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ---------------------------------------------------------------------------
17 // headers
18 // ---------------------------------------------------------------------------
19
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "appbase.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #if defined(__BORLANDC__)
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/app.h"
33 #include "wx/bitmap.h"
34 #include "wx/intl.h"
35 #include "wx/list.h"
36 #include "wx/log.h"
37 #include "wx/msgdlg.h"
38 #include "wx/bitmap.h"
39 #include "wx/confbase.h"
40 #endif
41
42 #include "wx/apptrait.h"
43 #include "wx/cmdline.h"
44 #include "wx/evtloop.h"
45 #include "wx/msgout.h"
46 #include "wx/thread.h"
47 #include "wx/utils.h"
48 #include "wx/ptr_scpd.h"
49
50 #if defined(__WXMSW__)
51 #include "wx/msw/private.h" // includes windows.h for LOGFONT
52 #endif
53
54 #if wxUSE_FONTMAP
55 #include "wx/fontmap.h"
56 #endif // wxUSE_FONTMAP
57
58 // DLL options compatibility check:
59 #include "wx/build.h"
60 WX_CHECK_BUILD_OPTIONS("wxCore")
61
62
63 // ----------------------------------------------------------------------------
64 // wxEventLoopPtr
65 // ----------------------------------------------------------------------------
66
67 // this defines wxEventLoopPtr
68 wxDEFINE_SCOPED_PTR_TYPE(wxEventLoop);
69
70 // but we need a smart pointer tied to wxAppBase::m_mainLoop, so we define
71 // another helper class
72 class wxTiedEventLoopPtr : public wxEventLoopPtr
73 {
74 public:
75 wxTiedEventLoopPtr(wxEventLoop **ppEvtLoop, wxEventLoop *pLoop)
76 : wxEventLoopPtr(*ppEvtLoop = pLoop), m_ppEvtLoop(ppEvtLoop)
77 {
78 }
79
80 ~wxTiedEventLoopPtr() { *m_ppEvtLoop = NULL; }
81
82 private:
83 wxEventLoop **m_ppEvtLoop;
84 };
85
86 // ============================================================================
87 // wxAppBase implementation
88 // ============================================================================
89
90 // ----------------------------------------------------------------------------
91 // initialization
92 // ----------------------------------------------------------------------------
93
94 wxAppBase::wxAppBase()
95 {
96 m_topWindow = (wxWindow *)NULL;
97 m_useBestVisual = FALSE;
98 m_isActive = TRUE;
99
100 #if wxUSE_EVTLOOP_IN_APP
101 m_mainLoop = NULL;
102 #endif // wxUSE_EVTLOOP_IN_APP
103
104 // We don't want to exit the app if the user code shows a dialog from its
105 // OnInit() -- but this is what would happen if we set m_exitOnFrameDelete
106 // to Yes initially as this dialog would be the last top level window.
107 // OTOH, if we set it to No initially we'll have to overwrite it with Yes
108 // when we enter our OnRun() because we do want the default behaviour from
109 // then on. But this would be a problem if the user code calls
110 // SetExitOnFrameDelete(FALSE) from OnInit().
111 //
112 // So we use the special "Later" value which is such that
113 // GetExitOnFrameDelete() returns FALSE for it but which we know we can
114 // safely (i.e. without losing the effect of the users SetExitOnFrameDelete
115 // call) overwrite in OnRun()
116 m_exitOnFrameDelete = Later;
117 }
118
119 bool wxAppBase::Initialize(int& argc, wxChar **argv)
120 {
121 if ( !wxAppConsole::Initialize(argc, argv) )
122 return false;
123
124 #if wxUSE_THREADS
125 wxPendingEventsLocker = new wxCriticalSection;
126 #endif
127
128 wxInitializeStockLists();
129 wxInitializeStockObjects();
130
131 wxBitmap::InitStandardHandlers();
132
133 return true;
134 }
135
136 // ----------------------------------------------------------------------------
137 // cleanup
138 // ----------------------------------------------------------------------------
139
140 wxAppBase::~wxAppBase()
141 {
142 // this destructor is required for Darwin
143 }
144
145 void wxAppBase::CleanUp()
146 {
147 // one last chance for pending objects to be cleaned up
148 DeletePendingObjects();
149
150 wxBitmap::CleanUpHandlers();
151
152 wxDeleteStockObjects();
153
154 wxDeleteStockLists();
155
156 delete wxTheColourDatabase;
157 wxTheColourDatabase = NULL;
158
159 #if wxUSE_THREADS
160 delete wxPendingEvents;
161 wxPendingEvents = NULL;
162
163 delete wxPendingEventsLocker;
164 wxPendingEventsLocker = NULL;
165
166 #if wxUSE_VALIDATORS
167 // If we don't do the following, we get an apparent memory leak.
168 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
169 #endif // wxUSE_VALIDATORS
170 #endif // wxUSE_THREADS
171 }
172
173 #if wxUSE_CMDLINE_PARSER
174
175 // ----------------------------------------------------------------------------
176 // GUI-specific command line options handling
177 // ----------------------------------------------------------------------------
178
179 #define OPTION_THEME _T("theme")
180 #define OPTION_MODE _T("mode")
181
182 void wxAppBase::OnInitCmdLine(wxCmdLineParser& parser)
183 {
184 // first add the standard non GUI options
185 wxAppConsole::OnInitCmdLine(parser);
186
187 // the standard command line options
188 static const wxCmdLineEntryDesc cmdLineGUIDesc[] =
189 {
190 #ifdef __WXUNIVERSAL__
191 {
192 wxCMD_LINE_OPTION,
193 _T(""),
194 OPTION_THEME,
195 gettext_noop("specify the theme to use"),
196 wxCMD_LINE_VAL_STRING,
197 0x0
198 },
199 #endif // __WXUNIVERSAL__
200
201 #if defined(__WXMGL__)
202 // VS: this is not specific to wxMGL, all fullscreen (framebuffer) ports
203 // should provide this option. That's why it is in common/appcmn.cpp
204 // and not mgl/app.cpp
205 {
206 wxCMD_LINE_OPTION,
207 _T(""),
208 OPTION_MODE,
209 gettext_noop("specify display mode to use (e.g. 640x480-16)"),
210 wxCMD_LINE_VAL_STRING,
211 0x0
212 },
213 #endif // __WXMGL__
214
215 // terminator
216 {
217 wxCMD_LINE_NONE,
218 _T(""),
219 _T(""),
220 _T(""),
221 wxCMD_LINE_VAL_NONE,
222 0x0
223 }
224 };
225
226 parser.SetDesc(cmdLineGUIDesc);
227 }
228
229 bool wxAppBase::OnCmdLineParsed(wxCmdLineParser& parser)
230 {
231 #ifdef __WXUNIVERSAL__
232 wxString themeName;
233 if ( parser.Found(OPTION_THEME, &themeName) )
234 {
235 wxTheme *theme = wxTheme::Create(themeName);
236 if ( !theme )
237 {
238 wxLogError(_("Unsupported theme '%s'."), themeName.c_str());
239 return FALSE;
240 }
241
242 // Delete the defaultly created theme and set the new theme.
243 delete wxTheme::Get();
244 wxTheme::Set(theme);
245 }
246 #endif // __WXUNIVERSAL__
247
248 #if defined(__WXMGL__)
249 wxString modeDesc;
250 if ( parser.Found(OPTION_MODE, &modeDesc) )
251 {
252 unsigned w, h, bpp;
253 if ( wxSscanf(modeDesc.c_str(), _T("%ux%u-%u"), &w, &h, &bpp) != 3 )
254 {
255 wxLogError(_("Invalid display mode specification '%s'."), modeDesc.c_str());
256 return FALSE;
257 }
258
259 if ( !SetDisplayMode(wxDisplayModeInfo(w, h, bpp)) )
260 return FALSE;
261 }
262 #endif // __WXMGL__
263
264 return wxAppConsole::OnCmdLineParsed(parser);
265 }
266
267 #endif // wxUSE_CMDLINE_PARSER
268
269 // ----------------------------------------------------------------------------
270 // main event loop implementation
271 // ----------------------------------------------------------------------------
272
273 int wxAppBase::MainLoop()
274 {
275 #if wxUSE_EVTLOOP_IN_APP
276 wxTiedEventLoopPtr mainLoop(&m_mainLoop, new wxEventLoop);
277
278 return m_mainLoop->Run();
279 #else // !wxUSE_EVTLOOP_IN_APP
280 return 0;
281 #endif // wxUSE_EVTLOOP_IN_APP/!wxUSE_EVTLOOP_IN_APP
282 }
283
284 void wxAppBase::ExitMainLoop()
285 {
286 #if wxUSE_EVTLOOP_IN_APP
287 // we should exit from the main event loop, not just any currently active
288 // (e.g. modal dialog) event loop
289 if ( m_mainLoop )
290 {
291 m_mainLoop->Exit(0);
292 }
293 #endif // wxUSE_EVTLOOP_IN_APP
294 }
295
296 bool wxAppBase::Pending()
297 {
298 #if wxUSE_EVTLOOP_IN_APP
299 // use the currently active message loop here, not m_mainLoop, because if
300 // we're showing a modal dialog (with its own event loop) currently the
301 // main event loop is not running anyhow
302 wxEventLoop * const loop = wxEventLoop::GetActive();
303
304 return loop && loop->Pending();
305 #else // wxUSE_EVTLOOP_IN_APP
306 return false;
307 #endif // wxUSE_EVTLOOP_IN_APP/!wxUSE_EVTLOOP_IN_APP
308 }
309
310 bool wxAppBase::Dispatch()
311 {
312 #if wxUSE_EVTLOOP_IN_APP
313 // see comment in Pending()
314 wxEventLoop * const loop = wxEventLoop::GetActive();
315
316 return loop && loop->Dispatch();
317 #else // wxUSE_EVTLOOP_IN_APP
318 return true;
319 #endif // wxUSE_EVTLOOP_IN_APP/!wxUSE_EVTLOOP_IN_APP
320 }
321
322 // ----------------------------------------------------------------------------
323 // OnXXX() hooks
324 // ----------------------------------------------------------------------------
325
326 bool wxAppBase::OnInitGui()
327 {
328 #ifdef __WXUNIVERSAL__
329 if ( !wxTheme::Get() && !wxTheme::CreateDefault() )
330 return FALSE;
331 #endif // __WXUNIVERSAL__
332
333 return TRUE;
334 }
335
336 int wxAppBase::OnRun()
337 {
338 // see the comment in ctor: if the initial value hasn't been changed, use
339 // the default Yes from now on
340 if ( m_exitOnFrameDelete == Later )
341 {
342 m_exitOnFrameDelete = Yes;
343 }
344 //else: it has been changed, assume the user knows what he is doing
345
346 return MainLoop();
347 }
348
349 int wxAppBase::OnExit()
350 {
351 #ifdef __WXUNIVERSAL__
352 delete wxTheme::Set(NULL);
353 #endif // __WXUNIVERSAL__
354
355 return wxAppConsole::OnExit();
356 }
357
358 void wxAppBase::Exit()
359 {
360 ExitMainLoop();
361 }
362
363 wxAppTraits *wxAppBase::CreateTraits()
364 {
365 return new wxGUIAppTraits;
366 }
367
368 // ----------------------------------------------------------------------------
369 // misc
370 // ----------------------------------------------------------------------------
371
372 void wxAppBase::SetActive(bool active, wxWindow * WXUNUSED(lastFocus))
373 {
374 if ( active == m_isActive )
375 return;
376
377 m_isActive = active;
378
379 wxActivateEvent event(wxEVT_ACTIVATE_APP, active);
380 event.SetEventObject(this);
381
382 (void)ProcessEvent(event);
383 }
384
385 void wxAppBase::DeletePendingObjects()
386 {
387 wxList::compatibility_iterator node = wxPendingDelete.GetFirst();
388 while (node)
389 {
390 wxObject *obj = node->GetData();
391
392 delete obj;
393
394 if (wxPendingDelete.Member(obj))
395 wxPendingDelete.Erase(node);
396
397 // Deleting one object may have deleted other pending
398 // objects, so start from beginning of list again.
399 node = wxPendingDelete.GetFirst();
400 }
401 }
402
403 // Returns TRUE if more time is needed.
404 bool wxAppBase::ProcessIdle()
405 {
406 wxIdleEvent event;
407 bool needMore = FALSE;
408 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
409 while (node)
410 {
411 wxWindow* win = node->GetData();
412 if (SendIdleEvents(win, event))
413 needMore = TRUE;
414 node = node->GetNext();
415 }
416
417 event.SetEventObject(this);
418 (void) ProcessEvent(event);
419 if (event.MoreRequested())
420 needMore = TRUE;
421
422 wxUpdateUIEvent::ResetUpdateTime();
423
424 return needMore;
425 }
426
427 // Send idle event to window and all subwindows
428 bool wxAppBase::SendIdleEvents(wxWindow* win, wxIdleEvent& event)
429 {
430 bool needMore = FALSE;
431
432 win->OnInternalIdle();
433
434 if (wxIdleEvent::CanSend(win))
435 {
436 event.SetEventObject(win);
437 win->GetEventHandler()->ProcessEvent(event);
438
439 if (event.MoreRequested())
440 needMore = TRUE;
441 }
442 wxWindowList::compatibility_iterator node = win->GetChildren().GetFirst();
443 while ( node )
444 {
445 wxWindow *child = node->GetData();
446 if (SendIdleEvents(child, event))
447 needMore = TRUE;
448
449 node = node->GetNext();
450 }
451
452 return needMore;
453 }
454
455 void wxAppBase::OnIdle(wxIdleEvent& WXUNUSED(event))
456 {
457 // If there are pending events, we must process them: pending events
458 // are either events to the threads other than main or events posted
459 // with wxPostEvent() functions
460 // GRG: I have moved this here so that all pending events are processed
461 // before starting to delete any objects. This behaves better (in
462 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
463 // behaviour. Changed Feb/2000 before 2.1.14
464 ProcessPendingEvents();
465
466 // 'Garbage' collection of windows deleted with Close().
467 DeletePendingObjects();
468
469 #if wxUSE_LOG
470 // flush the logged messages if any
471 wxLog::FlushActive();
472 #endif // wxUSE_LOG
473
474 }
475
476 // ----------------------------------------------------------------------------
477 // wxGUIAppTraitsBase
478 // ----------------------------------------------------------------------------
479
480 #if wxUSE_LOG
481
482 wxLog *wxGUIAppTraitsBase::CreateLogTarget()
483 {
484 return new wxLogGui;
485 }
486
487 #endif // wxUSE_LOG
488
489 wxMessageOutput *wxGUIAppTraitsBase::CreateMessageOutput()
490 {
491 // The standard way of printing help on command line arguments (app --help)
492 // is (according to common practice):
493 // - console apps: to stderr (on any platform)
494 // - GUI apps: stderr on Unix platforms (!)
495 // message box under Windows and others
496 #ifdef __UNIX__
497 return new wxMessageOutputStderr;
498 #else // !__UNIX__
499 // wxMessageOutputMessageBox doesn't work under Motif
500 #ifdef __WXMOTIF__
501 return new wxMessageOutputLog;
502 #else
503 return new wxMessageOutputMessageBox;
504 #endif
505 #endif // __UNIX__/!__UNIX__
506 }
507
508 #if wxUSE_FONTMAP
509
510 wxFontMapper *wxGUIAppTraitsBase::CreateFontMapper()
511 {
512 return new wxFontMapper;
513 }
514
515 #endif // wxUSE_FONTMAP
516
517 wxRendererNative *wxGUIAppTraitsBase::CreateRenderer()
518 {
519 // use the default native renderer by default
520 return NULL;
521 }
522
523 #ifdef __WXDEBUG__
524
525 bool wxGUIAppTraitsBase::ShowAssertDialog(const wxString& msg)
526 {
527 // under MSW we prefer to use the base class version using ::MessageBox()
528 // even if wxMessageBox() is available because it has less chances to
529 // double fault our app than our wxMessageBox()
530 #if defined(__WXMSW__) || !wxUSE_MSGDLG
531 return wxAppTraitsBase::ShowAssertDialog(msg);
532 #else // wxUSE_MSGDLG
533 // this message is intentionally not translated -- it is for
534 // developpers only
535 wxString msgDlg(msg);
536 msgDlg += wxT("\nDo you want to stop the program?\n")
537 wxT("You can also choose [Cancel] to suppress ")
538 wxT("further warnings.");
539
540 switch ( wxMessageBox(msgDlg, wxT("wxWindows Debug Alert"),
541 wxYES_NO | wxCANCEL | wxICON_STOP ) )
542 {
543 case wxYES:
544 wxTrap();
545 break;
546
547 case wxCANCEL:
548 // no more asserts
549 return true;
550
551 //case wxNO: nothing to do
552 }
553
554 return false;
555 #endif // !wxUSE_MSGDLG/wxUSE_MSGDLG
556 }
557
558 #endif // __WXDEBUG__
559
560 bool wxGUIAppTraitsBase::HasStderr()
561 {
562 // we consider that under Unix stderr always goes somewhere, even if the
563 // user doesn't always see it under GUI desktops
564 #ifdef __UNIX__
565 return true;
566 #else
567 return false;
568 #endif
569 }
570
571 void wxGUIAppTraitsBase::ScheduleForDestroy(wxObject *object)
572 {
573 if ( !wxPendingDelete.Member(object) )
574 wxPendingDelete.Append(object);
575 }
576
577 void wxGUIAppTraitsBase::RemoveFromPendingDelete(wxObject *object)
578 {
579 wxPendingDelete.DeleteObject(object);
580 }
581
582 #if wxUSE_SOCKETS
583
584 #if defined(__UNIX__) || defined(__DARWIN__) || defined(__OS2__)
585 #include "wx/unix/gsockunx.h"
586 #elif defined(__WINDOWS__)
587 #include "wx/msw/gsockmsw.h"
588 #elif defined(__WXMAC__)
589 #include <MacHeaders.c>
590 #define OTUNIXERRORS 1
591 #include <OpenTransport.h>
592 #include <OpenTransportProviders.h>
593 #include <OpenTptInternet.h>
594
595 #include "wx/mac/gsockmac.h"
596 #else
597 #error "Must include correct GSocket header here"
598 #endif
599
600 GSocketGUIFunctionsTable* wxGUIAppTraitsBase::GetSocketGUIFunctionsTable()
601 {
602 #ifdef __WXMAC__
603 // NB: wxMac does not have any GUI-specific functions in gsocket.c and
604 // so it doesn't need this table at all
605 return NULL;
606 #else // !__WXMAC__
607 static GSocketGUIFunctionsTable table =
608 {
609 _GSocket_GUI_Init,
610 _GSocket_GUI_Cleanup,
611 _GSocket_GUI_Init_Socket,
612 _GSocket_GUI_Destroy_Socket,
613 #ifndef __WINDOWS__
614 _GSocket_Install_Callback,
615 _GSocket_Uninstall_Callback,
616 #endif
617 _GSocket_Enable_Events,
618 _GSocket_Disable_Events
619 };
620 return &table;
621 #endif // __WXMAC__/!__WXMAC__
622 }
623
624 #endif
625