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