]> git.saurik.com Git - wxWidgets.git/blob - src/common/appbase.cpp
c2528ec5c9e227db222927d9abc362520c9c15ef
[wxWidgets.git] / src / common / appbase.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: common/base/appbase.cpp
3 // Purpose: implements wxAppConsole class
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 19.06.2003 (extracted from common/appcmn.cpp)
7 // RCS-ID: $Id$
8 // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
9 // License: wxWindows license
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 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/app.h"
29 #include "wx/intl.h"
30 #include "wx/list.h"
31 #if wxUSE_LOG
32 #include "wx/log.h"
33 #endif // wxUSE_LOG
34 #endif //WX_PRECOMP
35
36 #include "wx/apptrait.h"
37 #include "wx/cmdline.h"
38 #include "wx/confbase.h"
39 #if wxUSE_FILENAME
40 #include "wx/filename.h"
41 #endif // wxUSE_FILENAME
42 #if wxUSE_FONTMAP
43 #include "wx/fontmap.h"
44 #endif // wxUSE_FONTMAP
45 #include "wx/msgout.h"
46 #include "wx/tokenzr.h"
47
48 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
49 #include <signal.h> // for SIGTRAP used by wxTrap()
50 #endif //Win/Unix
51
52 #if defined(__WXMSW__)
53 #include "wx/msw/private.h" // includes windows.h for MessageBox()
54 #endif
55
56 #if defined(__WXMAC__)
57 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
58 // I don't know which headers are needed under earlier systems so
59 // include everything when in doubt
60 #ifdef __DARWIN__
61 #include "MacTypes.h"
62 #else
63 #include "wx/mac/private.h" // includes mac headers
64 #endif
65 #endif // __WXMAC__
66
67 // ----------------------------------------------------------------------------
68 // private functions prototypes
69 // ----------------------------------------------------------------------------
70
71 #ifdef __WXDEBUG__
72 // really just show the assert dialog
73 static bool DoShowAssertDialog(const wxString& msg);
74
75 // prepare for showing the assert dialog, use the given traits or
76 // DoShowAssertDialog() as last fallback to really show it
77 static
78 void ShowAssertDialog(const wxChar *szFile,
79 int nLine,
80 const wxChar *szCond,
81 const wxChar *szMsg,
82 wxAppTraits *traits = NULL);
83
84 // turn on the trace masks specified in the env variable WXTRACE
85 static void LINKAGEMODE SetTraceMasks();
86 #endif // __WXDEBUG__
87
88 // ----------------------------------------------------------------------------
89 // global vars
90 // ----------------------------------------------------------------------------
91
92 wxApp *wxTheApp = NULL;
93
94 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
95
96 // ============================================================================
97 // wxAppConsole implementation
98 // ============================================================================
99
100 // ----------------------------------------------------------------------------
101 // ctor/dtor
102 // ----------------------------------------------------------------------------
103
104 wxAppConsole::wxAppConsole()
105 {
106 m_traits = NULL;
107
108 wxTheApp = (wxApp *)this;
109
110 #ifdef __WXDEBUG__
111 SetTraceMasks();
112 #endif
113 }
114
115 wxAppConsole::~wxAppConsole()
116 {
117 delete m_traits;
118 }
119
120 // ----------------------------------------------------------------------------
121 // initilization/cleanup
122 // ----------------------------------------------------------------------------
123
124 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
125 {
126 // remember the command line arguments
127 this->argc = argc;
128 this->argv = argv;
129
130 if ( m_appName.empty() && argv )
131 {
132 // the application name is, by default, the name of its executable file
133 #if wxUSE_FILENAME
134 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
135 #else // !wxUSE_FILENAME
136 m_appName = argv[0];
137 #endif // wxUSE_FILENAME/!wxUSE_FILENAME
138 }
139
140 return true;
141 }
142
143 void wxAppConsole::CleanUp()
144 {
145 }
146
147 // ----------------------------------------------------------------------------
148 // OnXXX() callbacks
149 // ----------------------------------------------------------------------------
150
151 bool wxAppConsole::OnInit()
152 {
153 #if wxUSE_CMDLINE_PARSER
154 wxCmdLineParser parser(argc, argv);
155
156 OnInitCmdLine(parser);
157
158 bool cont;
159 switch ( parser.Parse(FALSE /* don't show usage */) )
160 {
161 case -1:
162 cont = OnCmdLineHelp(parser);
163 break;
164
165 case 0:
166 cont = OnCmdLineParsed(parser);
167 break;
168
169 default:
170 cont = OnCmdLineError(parser);
171 break;
172 }
173
174 if ( !cont )
175 return FALSE;
176 #endif // wxUSE_CMDLINE_PARSER
177
178 return TRUE;
179 }
180
181 int wxAppConsole::OnExit()
182 {
183 #if wxUSE_CONFIG
184 // delete the config object if any (don't use Get() here, but Set()
185 // because Get() could create a new config object)
186 delete wxConfigBase::Set((wxConfigBase *) NULL);
187 #endif // wxUSE_CONFIG
188
189 #ifdef __WXUNIVERSAL__
190 delete wxTheme::Set(NULL);
191 #endif // __WXUNIVERSAL__
192
193 // use Set(NULL) and not Get() to avoid creating a message output object on
194 // demand when we just want to delete it
195 delete wxMessageOutput::Set(NULL);
196
197 return 0;
198 }
199
200 void wxAppConsole::Exit()
201 {
202 exit(-1);
203 }
204
205 // ----------------------------------------------------------------------------
206 // traits stuff
207 // ----------------------------------------------------------------------------
208
209 wxAppTraits *wxAppConsole::CreateTraits()
210 {
211 return new wxConsoleAppTraits;
212 }
213
214 wxAppTraits *wxAppConsole::GetTraits()
215 {
216 // FIXME-MT: protect this with a CS?
217 if ( !m_traits )
218 {
219 m_traits = CreateTraits();
220
221 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
222 }
223
224 return m_traits;
225 }
226
227 // we must implement CreateXXX() in wxApp itself for backwards compatibility
228 #if WXWIN_COMPATIBILITY_2_4
229
230 #if wxUSE_LOG
231
232 wxLog *wxAppConsole::CreateLogTarget()
233 {
234 wxAppTraits *traits = GetTraits();
235 return traits ? traits->CreateLogTarget() : NULL;
236 }
237
238 #endif // wxUSE_LOG
239
240 wxMessageOutput *wxAppConsole::CreateMessageOutput()
241 {
242 wxAppTraits *traits = GetTraits();
243 return traits ? traits->CreateMessageOutput() : NULL;
244 }
245
246 #endif // WXWIN_COMPATIBILITY_2_4
247
248 // ----------------------------------------------------------------------------
249 // event processing
250 // ----------------------------------------------------------------------------
251
252 void wxAppConsole::ProcessPendingEvents()
253 {
254 // ensure that we're the only thread to modify the pending events list
255 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
256
257 if ( !wxPendingEvents )
258 {
259 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
260 return;
261 }
262
263 // iterate until the list becomes empty
264 wxNode *node = wxPendingEvents->GetFirst();
265 while (node)
266 {
267 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
268 delete node;
269
270 // In ProcessPendingEvents(), new handlers might be add
271 // and we can safely leave the critical section here.
272 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
273 handler->ProcessPendingEvents();
274 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
275
276 node = wxPendingEvents->GetFirst();
277 }
278
279 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
280 }
281
282 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
283 {
284 // process the events normally by default
285 return -1;
286 }
287
288 // ----------------------------------------------------------------------------
289 // cmd line parsing
290 // ----------------------------------------------------------------------------
291
292 #if wxUSE_CMDLINE_PARSER
293
294 #define OPTION_VERBOSE _T("verbose")
295 #define OPTION_THEME _T("theme")
296 #define OPTION_MODE _T("mode")
297
298 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
299 {
300 // the standard command line options
301 static const wxCmdLineEntryDesc cmdLineDesc[] =
302 {
303 {
304 wxCMD_LINE_SWITCH,
305 _T("h"),
306 _T("help"),
307 gettext_noop("show this help message"),
308 wxCMD_LINE_VAL_NONE,
309 wxCMD_LINE_OPTION_HELP
310 },
311
312 #if wxUSE_LOG
313 {
314 wxCMD_LINE_SWITCH,
315 _T(""),
316 OPTION_VERBOSE,
317 gettext_noop("generate verbose log messages"),
318 wxCMD_LINE_VAL_NONE,
319 0x0
320 },
321 #endif // wxUSE_LOG
322
323 #ifdef __WXUNIVERSAL__
324 {
325 wxCMD_LINE_OPTION,
326 _T(""),
327 OPTION_THEME,
328 gettext_noop("specify the theme to use"),
329 wxCMD_LINE_VAL_STRING,
330 0x0
331 },
332 #endif // __WXUNIVERSAL__
333
334 #if defined(__WXMGL__)
335 // VS: this is not specific to wxMGL, all fullscreen (framebuffer) ports
336 // should provide this option. That's why it is in common/appcmn.cpp
337 // and not mgl/app.cpp
338 {
339 wxCMD_LINE_OPTION,
340 _T(""),
341 OPTION_MODE,
342 gettext_noop("specify display mode to use (e.g. 640x480-16)"),
343 wxCMD_LINE_VAL_STRING,
344 0x0
345 },
346 #endif // __WXMGL__
347
348 // terminator
349 {
350 wxCMD_LINE_NONE,
351 _T(""),
352 _T(""),
353 _T(""),
354 wxCMD_LINE_VAL_NONE,
355 0x0
356 }
357 };
358
359 parser.SetDesc(cmdLineDesc);
360 }
361
362 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
363 {
364 #if wxUSE_LOG
365 if ( parser.Found(OPTION_VERBOSE) )
366 {
367 wxLog::SetVerbose(TRUE);
368 }
369 #endif // wxUSE_LOG
370
371 #ifdef __WXUNIVERSAL__
372 wxString themeName;
373 if ( parser.Found(OPTION_THEME, &themeName) )
374 {
375 wxTheme *theme = wxTheme::Create(themeName);
376 if ( !theme )
377 {
378 wxLogError(_("Unsupported theme '%s'."), themeName.c_str());
379 return FALSE;
380 }
381
382 // Delete the defaultly created theme and set the new theme.
383 delete wxTheme::Get();
384 wxTheme::Set(theme);
385 }
386 #endif // __WXUNIVERSAL__
387
388 #if defined(__WXMGL__)
389 wxString modeDesc;
390 if ( parser.Found(OPTION_MODE, &modeDesc) )
391 {
392 unsigned w, h, bpp;
393 if ( wxSscanf(modeDesc.c_str(), _T("%ux%u-%u"), &w, &h, &bpp) != 3 )
394 {
395 wxLogError(_("Invalid display mode specification '%s'."), modeDesc.c_str());
396 return FALSE;
397 }
398
399 if ( !SetDisplayMode(wxDisplayModeInfo(w, h, bpp)) )
400 return FALSE;
401 }
402 #endif // __WXMGL__
403
404 return TRUE;
405 }
406
407 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
408 {
409 parser.Usage();
410
411 return FALSE;
412 }
413
414 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
415 {
416 parser.Usage();
417
418 return FALSE;
419 }
420
421 #endif // wxUSE_CMDLINE_PARSER
422
423 // ----------------------------------------------------------------------------
424 // debugging support
425 // ----------------------------------------------------------------------------
426
427 /* static */
428 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& opts)
429 {
430 #define wxCMP(what) (what == opts.m_ ## what)
431
432 bool
433 #ifdef __WXDEBUG__
434 isDebug = TRUE;
435 #else
436 isDebug = FALSE;
437 #endif
438
439 int verMaj = wxMAJOR_VERSION,
440 verMin = wxMINOR_VERSION;
441
442 if ( !(wxCMP(isDebug) && wxCMP(verMaj) && wxCMP(verMin)) )
443 {
444 wxString msg;
445 wxString libDebug, progDebug;
446
447 if (isDebug)
448 libDebug = wxT("debug");
449 else
450 libDebug = wxT("no debug");
451
452 if (opts.m_isDebug)
453 progDebug = wxT("debug");
454 else
455 progDebug = wxT("no debug");
456
457 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %d.%d (%s), and your program used %d.%d (%s)."),
458 verMaj, verMin, libDebug.c_str(), opts.m_verMaj, opts.m_verMin, progDebug.c_str());
459
460 wxLogFatalError(msg);
461
462 // normally wxLogFatalError doesn't return
463 return FALSE;
464 }
465 #undef wxCMP
466
467 return TRUE;
468 }
469
470 #ifdef __WXDEBUG__
471
472 void wxAppConsole::OnAssert(const wxChar *file,
473 int line,
474 const wxChar *cond,
475 const wxChar *msg)
476 {
477 ShowAssertDialog(file, line, cond, msg, m_traits);
478 }
479
480 #endif // __WXDEBUG__
481
482 // ============================================================================
483 // other classes implementations
484 // ============================================================================
485
486 // ----------------------------------------------------------------------------
487 // wxConsoleAppTraitsBase
488 // ----------------------------------------------------------------------------
489
490 #if wxUSE_LOG
491
492 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
493 {
494 return new wxLogStderr;
495 }
496
497 #endif // wxUSE_LOG
498
499 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
500 {
501 return new wxMessageOutputStderr;
502 }
503
504 #if wxUSE_FONTMAP
505
506 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
507 {
508 return (wxFontMapper *)new wxFontMapperBase;
509 }
510
511 #endif // wxUSE_FONTMAP
512
513 #ifdef __WXDEBUG__
514 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
515 {
516 return wxAppTraitsBase::ShowAssertDialog(msg);
517 }
518 #endif
519
520 bool wxConsoleAppTraitsBase::HasStderr()
521 {
522 // console applications always have stderr, even under Mac/Windows
523 return true;
524 }
525
526 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
527 {
528 delete object;
529 }
530
531 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
532 {
533 // nothing to do
534 }
535
536 // ----------------------------------------------------------------------------
537 // wxAppTraits
538 // ----------------------------------------------------------------------------
539
540 #ifdef __WXDEBUG__
541
542 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
543 {
544 return DoShowAssertDialog(msg);
545 }
546
547 #endif // __WXDEBUG__
548
549 // ============================================================================
550 // global functions implementation
551 // ============================================================================
552
553 void wxExit()
554 {
555 if ( wxTheApp )
556 {
557 wxTheApp->Exit();
558 }
559 else
560 {
561 // what else can we do?
562 exit(-1);
563 }
564 }
565
566 void wxWakeUpIdle()
567 {
568 if ( wxTheApp )
569 {
570 wxTheApp->WakeUpIdle();
571 }
572 //else: do nothing, what can we do?
573 }
574
575 #ifdef __WXDEBUG__
576
577 // wxASSERT() helper
578 bool wxAssertIsEqual(int x, int y)
579 {
580 return x == y;
581 }
582
583 // break into the debugger
584 void wxTrap()
585 {
586 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
587 DebugBreak();
588 #elif defined(__WXMAC__) && !defined(__DARWIN__)
589 #if __powerc
590 Debugger();
591 #else
592 SysBreak();
593 #endif
594 #elif defined(__UNIX__)
595 raise(SIGTRAP);
596 #else
597 // TODO
598 #endif // Win/Unix
599 }
600
601 void wxAssert(int cond,
602 const wxChar *szFile,
603 int nLine,
604 const wxChar *szCond,
605 const wxChar *szMsg)
606 {
607 if ( !cond )
608 wxOnAssert(szFile, nLine, szCond, szMsg);
609 }
610
611 // this function is called when an assert fails
612 void wxOnAssert(const wxChar *szFile,
613 int nLine,
614 const wxChar *szCond,
615 const wxChar *szMsg)
616 {
617 // FIXME MT-unsafe
618 static bool s_bInAssert = FALSE;
619
620 if ( s_bInAssert )
621 {
622 // He-e-e-e-elp!! we're trapped in endless loop
623 wxTrap();
624
625 s_bInAssert = FALSE;
626
627 return;
628 }
629
630 s_bInAssert = TRUE;
631
632 if ( !wxTheApp )
633 {
634 // by default, show the assert dialog box -- we can't customize this
635 // behaviour
636 ShowAssertDialog(szFile, nLine, szCond, szMsg);
637 }
638 else
639 {
640 // let the app process it as it wants
641 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
642 }
643
644 s_bInAssert = FALSE;
645 }
646
647 #endif // __WXDEBUG__
648
649 // ============================================================================
650 // private functions implementation
651 // ============================================================================
652
653 #ifdef __WXDEBUG__
654
655 static void LINKAGEMODE SetTraceMasks()
656 {
657 #if wxUSE_LOG
658 wxString mask;
659 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
660 {
661 wxStringTokenizer tkn(mask, wxT(",;:"));
662 while ( tkn.HasMoreTokens() )
663 wxLog::AddTraceMask(tkn.GetNextToken());
664 }
665 #endif // wxUSE_LOG
666 }
667
668 bool DoShowAssertDialog(const wxString& msg)
669 {
670 // under MSW we can show the dialog even in the console mode
671 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
672 wxString msgDlg(msg);
673
674 // this message is intentionally not translated -- it is for
675 // developpers only
676 msgDlg += wxT("\nDo you want to stop the program?\n")
677 wxT("You can also choose [Cancel] to suppress ")
678 wxT("further warnings.");
679
680 switch ( ::MessageBox(NULL, msgDlg, _T("wxWindows Debug Alert"),
681 MB_YESNOCANCEL | MB_ICONSTOP ) )
682 {
683 case IDYES:
684 wxTrap();
685 break;
686
687 case IDCANCEL:
688 // stop the asserts
689 return true;
690
691 //case IDNO: nothing to do
692 }
693 #else // !__WXMSW__
694 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
695 fflush(stderr);
696
697 // TODO: ask the user to enter "Y" or "N" on the console?
698 wxTrap();
699 #endif // __WXMSW__/!__WXMSW__
700
701 // continue with the asserts
702 return false;
703 }
704
705 // show the assert modal dialog
706 static
707 void ShowAssertDialog(const wxChar *szFile,
708 int nLine,
709 const wxChar *szCond,
710 const wxChar *szMsg,
711 wxAppTraits *traits)
712 {
713 // this variable can be set to true to suppress "assert failure" messages
714 static bool s_bNoAsserts = FALSE;
715
716 wxString msg;
717 msg.reserve(2048);
718
719 // make life easier for people using VC++ IDE by using this format: like
720 // this, clicking on the message will take us immediately to the place of
721 // the failed assert
722 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
723
724 if ( szMsg )
725 {
726 msg << _T(": ") << szMsg;
727 }
728 else // no message given
729 {
730 msg << _T('.');
731 }
732
733 #if wxUSE_THREADS
734 // if we are not in the main thread, output the assert directly and trap
735 // since dialogs cannot be displayed
736 if ( !wxThread::IsMain() )
737 {
738 msg += wxT(" [in child thread]");
739
740 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
741 msg << wxT("\r\n");
742 OutputDebugString(msg );
743 #else
744 // send to stderr
745 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
746 fflush(stderr);
747 #endif
748 // He-e-e-e-elp!! we're asserting in a child thread
749 wxTrap();
750 }
751 #endif // wxUSE_THREADS
752
753 if ( !s_bNoAsserts )
754 {
755 // send it to the normal log destination
756 wxLogDebug(_T("%s"), msg);
757
758 if ( traits )
759 {
760 // delegate showing assert dialog (if possible) to that class
761 s_bNoAsserts = traits->ShowAssertDialog(msg);
762 }
763 else // no traits object
764 {
765 // fall back to the function of last resort
766 s_bNoAsserts = DoShowAssertDialog(msg);
767 }
768 }
769 }
770
771 #endif // __WXDEBUG__
772