second part of #10320: move wxApp event handling functions to wxEventLoopBase (in...
[wxWidgets.git] / src / common / appcmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/appcmn.cpp
3 // Purpose: 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 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #if defined(__BORLANDC__)
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/app.h"
29 #include "wx/window.h"
30 #include "wx/bitmap.h"
31 #include "wx/log.h"
32 #include "wx/msgdlg.h"
33 #include "wx/confbase.h"
34 #include "wx/utils.h"
35 #include "wx/wxcrtvararg.h"
36 #endif
37
38 #include "wx/apptrait.h"
39 #include "wx/cmdline.h"
40 #include "wx/msgout.h"
41 #include "wx/thread.h"
42 #include "wx/vidmode.h"
43 #include "wx/evtloop.h"
44
45 #ifdef __WXDEBUG__
46 #if wxUSE_STACKWALKER
47 #include "wx/stackwalk.h"
48 #endif // wxUSE_STACKWALKER
49 #endif // __WXDEBUG__
50
51 #if defined(__WXMSW__)
52 #include "wx/msw/private.h" // includes windows.h for LOGFONT
53 #endif
54
55 #if wxUSE_FONTMAP
56 #include "wx/fontmap.h"
57 #endif // wxUSE_FONTMAP
58
59 // DLL options compatibility check:
60 #include "wx/build.h"
61 WX_CHECK_BUILD_OPTIONS("wxCore")
62
63 WXDLLIMPEXP_DATA_CORE(wxList) wxPendingDelete;
64
65 // ============================================================================
66 // wxAppBase implementation
67 // ============================================================================
68
69 // ----------------------------------------------------------------------------
70 // initialization
71 // ----------------------------------------------------------------------------
72
73 wxAppBase::wxAppBase()
74 {
75 m_topWindow = NULL;
76
77 m_useBestVisual = false;
78 m_forceTrueColour = false;
79
80 m_isActive = true;
81
82 // We don't want to exit the app if the user code shows a dialog from its
83 // OnInit() -- but this is what would happen if we set m_exitOnFrameDelete
84 // to Yes initially as this dialog would be the last top level window.
85 // OTOH, if we set it to No initially we'll have to overwrite it with Yes
86 // when we enter our OnRun() because we do want the default behaviour from
87 // then on. But this would be a problem if the user code calls
88 // SetExitOnFrameDelete(false) from OnInit().
89 //
90 // So we use the special "Later" value which is such that
91 // GetExitOnFrameDelete() returns false for it but which we know we can
92 // safely (i.e. without losing the effect of the users SetExitOnFrameDelete
93 // call) overwrite in OnRun()
94 m_exitOnFrameDelete = Later;
95 }
96
97 bool wxAppBase::Initialize(int& argcOrig, wxChar **argvOrig)
98 {
99 if ( !wxAppConsole::Initialize(argcOrig, argvOrig) )
100 return false;
101
102 wxInitializeStockLists();
103
104 wxBitmap::InitStandardHandlers();
105
106 return true;
107 }
108
109 // ----------------------------------------------------------------------------
110 // cleanup
111 // ----------------------------------------------------------------------------
112
113 wxAppBase::~wxAppBase()
114 {
115 // this destructor is required for Darwin
116 }
117
118 void wxAppBase::CleanUp()
119 {
120 // clean up all the pending objects
121 DeletePendingObjects();
122
123 // and any remaining TLWs (they remove themselves from wxTopLevelWindows
124 // when destroyed, so iterate until none are left)
125 while ( !wxTopLevelWindows.empty() )
126 {
127 // do not use Destroy() here as it only puts the TLW in pending list
128 // but we want to delete them now
129 delete wxTopLevelWindows.GetFirst()->GetData();
130 }
131
132 // undo everything we did in Initialize() above
133 wxBitmap::CleanUpHandlers();
134
135 wxStockGDI::DeleteAll();
136
137 wxDeleteStockLists();
138
139 delete wxTheColourDatabase;
140 wxTheColourDatabase = NULL;
141
142 wxAppConsole::CleanUp();
143 }
144
145 // ----------------------------------------------------------------------------
146 // various accessors
147 // ----------------------------------------------------------------------------
148
149 wxWindow* wxAppBase::GetTopWindow() const
150 {
151 wxWindow* window = m_topWindow;
152 if (window == NULL && wxTopLevelWindows.GetCount() > 0)
153 window = wxTopLevelWindows.GetFirst()->GetData();
154 return window;
155 }
156
157 wxVideoMode wxAppBase::GetDisplayMode() const
158 {
159 return wxVideoMode();
160 }
161
162 wxLayoutDirection wxAppBase::GetLayoutDirection() const
163 {
164 #if wxUSE_INTL
165 const wxLocale *const locale = wxGetLocale();
166 if ( locale )
167 {
168 const wxLanguageInfo *const
169 info = wxLocale::GetLanguageInfo(locale->GetLanguage());
170
171 if ( info )
172 return info->LayoutDirection;
173 }
174 #endif // wxUSE_INTL
175
176 // we don't know
177 return wxLayout_Default;
178 }
179
180 #if wxUSE_CMDLINE_PARSER
181
182 // ----------------------------------------------------------------------------
183 // GUI-specific command line options handling
184 // ----------------------------------------------------------------------------
185
186 #define OPTION_THEME "theme"
187 #define OPTION_MODE "mode"
188
189 void wxAppBase::OnInitCmdLine(wxCmdLineParser& parser)
190 {
191 // first add the standard non GUI options
192 wxAppConsole::OnInitCmdLine(parser);
193
194 // the standard command line options
195 static const wxCmdLineEntryDesc cmdLineGUIDesc[] =
196 {
197 #ifdef __WXUNIVERSAL__
198 {
199 wxCMD_LINE_OPTION,
200 NULL,
201 OPTION_THEME,
202 gettext_noop("specify the theme to use"),
203 wxCMD_LINE_VAL_STRING,
204 0x0
205 },
206 #endif // __WXUNIVERSAL__
207
208 #if defined(__WXMGL__)
209 // VS: this is not specific to wxMGL, all fullscreen (framebuffer) ports
210 // should provide this option. That's why it is in common/appcmn.cpp
211 // and not mgl/app.cpp
212 {
213 wxCMD_LINE_OPTION,
214 NULL,
215 OPTION_MODE,
216 gettext_noop("specify display mode to use (e.g. 640x480-16)"),
217 wxCMD_LINE_VAL_STRING,
218 0x0
219 },
220 #endif // __WXMGL__
221
222 // terminator
223 wxCMD_LINE_DESC_END
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(wxVideoMode(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 // OnXXX() hooks
271 // ----------------------------------------------------------------------------
272
273 bool wxAppBase::OnInitGui()
274 {
275 #ifdef __WXUNIVERSAL__
276 if ( !wxTheme::Get() && !wxTheme::CreateDefault() )
277 return false;
278 #endif // __WXUNIVERSAL__
279
280 return true;
281 }
282
283 int wxAppBase::OnRun()
284 {
285 // see the comment in ctor: if the initial value hasn't been changed, use
286 // the default Yes from now on
287 if ( m_exitOnFrameDelete == Later )
288 {
289 m_exitOnFrameDelete = Yes;
290 }
291 //else: it has been changed, assume the user knows what he is doing
292
293 return wxAppConsole::OnRun();
294 }
295
296 int wxAppBase::OnExit()
297 {
298 #ifdef __WXUNIVERSAL__
299 delete wxTheme::Set(NULL);
300 #endif // __WXUNIVERSAL__
301
302 return wxAppConsole::OnExit();
303 }
304
305 wxAppTraits *wxAppBase::CreateTraits()
306 {
307 return new wxGUIAppTraits;
308 }
309
310 // ----------------------------------------------------------------------------
311 // misc
312 // ----------------------------------------------------------------------------
313
314 void wxAppBase::SetActive(bool active, wxWindow * WXUNUSED(lastFocus))
315 {
316 if ( active == m_isActive )
317 return;
318
319 m_isActive = active;
320
321 wxActivateEvent event(wxEVT_ACTIVATE_APP, active);
322 event.SetEventObject(this);
323
324 (void)ProcessEvent(event);
325 }
326
327 bool wxAppBase::SafeYield(wxWindow *win, bool onlyIfNeeded)
328 {
329 wxWindowDisabler wd(win);
330
331 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
332
333 return loop && loop->Yield(onlyIfNeeded);
334 }
335
336 bool wxAppBase::SafeYieldFor(wxWindow *win, long eventsToProcess)
337 {
338 wxWindowDisabler wd(win);
339
340 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
341
342 return loop && loop->YieldFor(eventsToProcess);
343 }
344
345
346 // ----------------------------------------------------------------------------
347 // idle handling
348 // ----------------------------------------------------------------------------
349
350 void wxAppBase::DeletePendingObjects()
351 {
352 wxList::compatibility_iterator node = wxPendingDelete.GetFirst();
353 while (node)
354 {
355 wxObject *obj = node->GetData();
356
357 // remove it from the list first so that if we get back here somehow
358 // during the object deletion (e.g. wxYield called from its dtor) we
359 // wouldn't try to delete it the second time
360 if ( wxPendingDelete.Member(obj) )
361 wxPendingDelete.Erase(node);
362
363 delete obj;
364
365 // Deleting one object may have deleted other pending
366 // objects, so start from beginning of list again.
367 node = wxPendingDelete.GetFirst();
368 }
369 }
370
371 // Returns true if more time is needed.
372 bool wxAppBase::ProcessIdle()
373 {
374 // call the base class version first, it will process the pending events
375 // (which should be done before the idle events generation) and send the
376 // idle event to wxTheApp itself
377 bool needMore = wxAppConsoleBase::ProcessIdle();
378 wxIdleEvent event;
379 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
380 while (node)
381 {
382 wxWindow* win = node->GetData();
383 if (SendIdleEvents(win, event))
384 needMore = true;
385 node = node->GetNext();
386 }
387
388 // 'Garbage' collection of windows deleted with Close().
389 DeletePendingObjects();
390
391 #if wxUSE_LOG
392 // flush the logged messages if any
393 wxLog::FlushActive();
394 #endif
395
396 wxUpdateUIEvent::ResetUpdateTime();
397
398 return needMore;
399 }
400
401 // Send idle event to window and all subwindows
402 bool wxAppBase::SendIdleEvents(wxWindow* win, wxIdleEvent& event)
403 {
404 bool needMore = false;
405
406 win->OnInternalIdle();
407
408 // should we send idle event to this window?
409 if ( wxIdleEvent::GetMode() == wxIDLE_PROCESS_ALL ||
410 win->HasExtraStyle(wxWS_EX_PROCESS_IDLE) )
411 {
412 event.SetEventObject(win);
413 win->HandleWindowEvent(event);
414
415 if (event.MoreRequested())
416 needMore = true;
417 }
418 wxWindowList::compatibility_iterator node = win->GetChildren().GetFirst();
419 while ( node )
420 {
421 wxWindow *child = node->GetData();
422 if (SendIdleEvents(child, event))
423 needMore = true;
424
425 node = node->GetNext();
426 }
427
428 return needMore;
429 }
430
431 // ----------------------------------------------------------------------------
432 // wxGUIAppTraitsBase
433 // ----------------------------------------------------------------------------
434
435 #if wxUSE_LOG
436
437 wxLog *wxGUIAppTraitsBase::CreateLogTarget()
438 {
439 #if wxUSE_LOGGUI
440 return new wxLogGui;
441 #else
442 // we must have something!
443 return new wxLogStderr;
444 #endif
445 }
446
447 #endif // wxUSE_LOG
448
449 wxMessageOutput *wxGUIAppTraitsBase::CreateMessageOutput()
450 {
451 // The standard way of printing help on command line arguments (app --help)
452 // is (according to common practice):
453 // - console apps: to stderr (on any platform)
454 // - GUI apps: stderr on Unix platforms (!)
455 // stderr if available and message box otherwise on others
456 // (currently stderr only Windows if app running from console)
457 #ifdef __UNIX__
458 return new wxMessageOutputStderr;
459 #else // !__UNIX__
460 // wxMessageOutputMessageBox doesn't work under Motif
461 #ifdef __WXMOTIF__
462 return new wxMessageOutputLog;
463 #elif wxUSE_MSGDLG
464 return new wxMessageOutputBest(wxMSGOUT_PREFER_STDERR);
465 #else
466 return new wxMessageOutputStderr;
467 #endif
468 #endif // __UNIX__/!__UNIX__
469 }
470
471 #if wxUSE_FONTMAP
472
473 wxFontMapper *wxGUIAppTraitsBase::CreateFontMapper()
474 {
475 return new wxFontMapper;
476 }
477
478 #endif // wxUSE_FONTMAP
479
480 wxRendererNative *wxGUIAppTraitsBase::CreateRenderer()
481 {
482 // use the default native renderer by default
483 return NULL;
484 }
485
486 #ifdef __WXDEBUG__
487
488 bool wxGUIAppTraitsBase::ShowAssertDialog(const wxString& msg)
489 {
490 // under MSW we prefer to use the base class version using ::MessageBox()
491 // even if wxMessageBox() is available because it has less chances to
492 // double fault our app than our wxMessageBox()
493 //
494 // under DFB the message dialog is not always functional right now
495 //
496 // and finally we can't use wxMessageBox() if it wasn't compiled in, of
497 // course
498 #if defined(__WXMSW__) || defined(__WXDFB__) || !wxUSE_MSGDLG
499 return wxAppTraitsBase::ShowAssertDialog(msg);
500 #else // wxUSE_MSGDLG
501 wxString msgDlg = msg;
502
503 #if wxUSE_STACKWALKER
504 // on Unix stack frame generation may take some time, depending on the
505 // size of the executable mainly... warn the user that we are working
506 wxFprintf(stderr, wxT("[Debug] Generating a stack trace... please wait"));
507 fflush(stderr);
508
509 const wxString stackTrace = GetAssertStackTrace();
510 if ( !stackTrace.empty() )
511 msgDlg << _T("\n\nCall stack:\n") << stackTrace;
512 #endif // wxUSE_STACKWALKER
513
514 // this message is intentionally not translated -- it is for
515 // developpers only
516 msgDlg += wxT("\nDo you want to stop the program?\n")
517 wxT("You can also choose [Cancel] to suppress ")
518 wxT("further warnings.");
519
520 switch ( wxMessageBox(msgDlg, wxT("wxWidgets Debug Alert"),
521 wxYES_NO | wxCANCEL | wxICON_STOP ) )
522 {
523 case wxYES:
524 wxTrap();
525 break;
526
527 case wxCANCEL:
528 // no more asserts
529 return true;
530
531 //case wxNO: nothing to do
532 }
533
534 return false;
535 #endif // !wxUSE_MSGDLG/wxUSE_MSGDLG
536 }
537
538 #endif // __WXDEBUG__
539
540 bool wxGUIAppTraitsBase::HasStderr()
541 {
542 // we consider that under Unix stderr always goes somewhere, even if the
543 // user doesn't always see it under GUI desktops
544 #ifdef __UNIX__
545 return true;
546 #else
547 return false;
548 #endif
549 }
550
551 void wxGUIAppTraitsBase::ScheduleForDestroy(wxObject *object)
552 {
553 if ( !wxPendingDelete.Member(object) )
554 wxPendingDelete.Append(object);
555 }
556
557 void wxGUIAppTraitsBase::RemoveFromPendingDelete(wxObject *object)
558 {
559 wxPendingDelete.DeleteObject(object);
560 }
561