use wxLogBuffer to ensure that we don't lose error messages during initialization...
[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 #include "wx/log.h"
32 #endif //WX_PRECOMP
33
34 #include "wx/utils.h"
35 #include "wx/apptrait.h"
36 #include "wx/cmdline.h"
37 #include "wx/confbase.h"
38 #include "wx/filename.h"
39 #include "wx/msgout.h"
40 #include "wx/tokenzr.h"
41
42 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
43 #include <signal.h> // for SIGTRAP used by wxTrap()
44 #endif //Win/Unix
45
46 #if defined(__WXMSW__)
47 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
48 #endif
49
50 #if wxUSE_FONTMAP
51 #include "wx/fontmap.h"
52 #endif // wxUSE_FONTMAP
53
54 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
55 // For MacTypes.h for Debugger function
56 #include <CoreFoundation/CFBase.h>
57 #endif
58
59 #if defined(__WXMAC__)
60 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
61 // I don't know which headers are needed under earlier systems so
62 // include everything when in doubt
63 #ifdef __DARWIN__
64 #include "MacTypes.h"
65 #else
66 #include "wx/mac/private.h" // includes mac headers
67 #endif
68 #endif // __WXMAC__
69
70 #ifdef __WXDEBUG__
71 #if wxUSE_STACKWALKER
72 #include "wx/stackwalk.h"
73 #ifdef __WXMSW__
74 #include "wx/msw/debughlp.h"
75 #endif
76 #endif // wxUSE_STACKWALKER
77 #endif // __WXDEBUG__
78
79 // ----------------------------------------------------------------------------
80 // private functions prototypes
81 // ----------------------------------------------------------------------------
82
83 #ifdef __WXDEBUG__
84 // really just show the assert dialog
85 static bool DoShowAssertDialog(const wxString& msg);
86
87 // prepare for showing the assert dialog, use the given traits or
88 // DoShowAssertDialog() as last fallback to really show it
89 static
90 void ShowAssertDialog(const wxChar *szFile,
91 int nLine,
92 const wxChar *szCond,
93 const wxChar *szMsg,
94 wxAppTraits *traits = NULL);
95
96 // turn on the trace masks specified in the env variable WXTRACE
97 static void LINKAGEMODE SetTraceMasks();
98 #endif // __WXDEBUG__
99
100 // ----------------------------------------------------------------------------
101 // global vars
102 // ----------------------------------------------------------------------------
103
104 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
105
106 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
107
108 // ============================================================================
109 // wxAppConsole implementation
110 // ============================================================================
111
112 // ----------------------------------------------------------------------------
113 // ctor/dtor
114 // ----------------------------------------------------------------------------
115
116 wxAppConsole::wxAppConsole()
117 {
118 m_traits = NULL;
119
120 ms_appInstance = this;
121
122 #ifdef __WXDEBUG__
123 SetTraceMasks();
124 #if wxUSE_UNICODE
125 // In unicode mode the SetTraceMasks call can cause an apptraits to be
126 // created, but since we are still in the constructor the wrong kind will
127 // be created for GUI apps. Destroy it so it can be created again later.
128 delete m_traits;
129 m_traits = NULL;
130 #endif
131 #endif
132 }
133
134 wxAppConsole::~wxAppConsole()
135 {
136 delete m_traits;
137 }
138
139 // ----------------------------------------------------------------------------
140 // initilization/cleanup
141 // ----------------------------------------------------------------------------
142
143 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
144 {
145 // remember the command line arguments
146 this->argc = argc;
147 this->argv = argv;
148
149 #ifndef __WXPALMOS__
150 if ( m_appName.empty() && argv )
151 {
152 // the application name is, by default, the name of its executable file
153 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
154 }
155 #endif
156
157 return true;
158 }
159
160 void wxAppConsole::CleanUp()
161 {
162 }
163
164 // ----------------------------------------------------------------------------
165 // OnXXX() callbacks
166 // ----------------------------------------------------------------------------
167
168 bool wxAppConsole::OnInit()
169 {
170 #if wxUSE_CMDLINE_PARSER
171 wxCmdLineParser parser(argc, argv);
172
173 OnInitCmdLine(parser);
174
175 bool cont;
176 switch ( parser.Parse(false /* don't show usage */) )
177 {
178 case -1:
179 cont = OnCmdLineHelp(parser);
180 break;
181
182 case 0:
183 cont = OnCmdLineParsed(parser);
184 break;
185
186 default:
187 cont = OnCmdLineError(parser);
188 break;
189 }
190
191 if ( !cont )
192 return false;
193 #endif // wxUSE_CMDLINE_PARSER
194
195 return true;
196 }
197
198 int wxAppConsole::OnExit()
199 {
200 #if wxUSE_CONFIG
201 // delete the config object if any (don't use Get() here, but Set()
202 // because Get() could create a new config object)
203 delete wxConfigBase::Set((wxConfigBase *) NULL);
204 #endif // wxUSE_CONFIG
205
206 // use Set(NULL) and not Get() to avoid creating a message output object on
207 // demand when we just want to delete it
208 delete wxMessageOutput::Set(NULL);
209
210 return 0;
211 }
212
213 void wxAppConsole::Exit()
214 {
215 exit(-1);
216 }
217
218 // ----------------------------------------------------------------------------
219 // traits stuff
220 // ----------------------------------------------------------------------------
221
222 wxAppTraits *wxAppConsole::CreateTraits()
223 {
224 return new wxConsoleAppTraits;
225 }
226
227 wxAppTraits *wxAppConsole::GetTraits()
228 {
229 // FIXME-MT: protect this with a CS?
230 if ( !m_traits )
231 {
232 m_traits = CreateTraits();
233
234 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
235 }
236
237 return m_traits;
238 }
239
240 // we must implement CreateXXX() in wxApp itself for backwards compatibility
241 #if WXWIN_COMPATIBILITY_2_4
242
243 #if wxUSE_LOG
244
245 wxLog *wxAppConsole::CreateLogTarget()
246 {
247 wxAppTraits *traits = GetTraits();
248 return traits ? traits->CreateLogTarget() : NULL;
249 }
250
251 #endif // wxUSE_LOG
252
253 wxMessageOutput *wxAppConsole::CreateMessageOutput()
254 {
255 wxAppTraits *traits = GetTraits();
256 return traits ? traits->CreateMessageOutput() : NULL;
257 }
258
259 #endif // WXWIN_COMPATIBILITY_2_4
260
261 // ----------------------------------------------------------------------------
262 // event processing
263 // ----------------------------------------------------------------------------
264
265 void wxAppConsole::ProcessPendingEvents()
266 {
267 #if wxUSE_THREADS
268 if ( !wxPendingEventsLocker )
269 return;
270 #endif
271
272 // ensure that we're the only thread to modify the pending events list
273 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
274
275 if ( !wxPendingEvents )
276 {
277 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
278 return;
279 }
280
281 // iterate until the list becomes empty
282 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
283 while (node)
284 {
285 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
286 wxPendingEvents->Erase(node);
287
288 // In ProcessPendingEvents(), new handlers might be add
289 // and we can safely leave the critical section here.
290 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
291
292 handler->ProcessPendingEvents();
293
294 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
295
296 node = wxPendingEvents->GetFirst();
297 }
298
299 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
300 }
301
302 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
303 {
304 // process the events normally by default
305 return -1;
306 }
307
308 // ----------------------------------------------------------------------------
309 // exception handling
310 // ----------------------------------------------------------------------------
311
312 #if wxUSE_EXCEPTIONS
313
314 void
315 wxAppConsole::HandleEvent(wxEvtHandler *handler,
316 wxEventFunction func,
317 wxEvent& event) const
318 {
319 // by default, simply call the handler
320 (handler->*func)(event);
321 }
322
323 bool
324 wxAppConsole::OnExceptionInMainLoop()
325 {
326 throw;
327
328 // some compilers are too stupid to know that we never return after throw
329 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
330 return false;
331 #endif
332 }
333
334 #endif // wxUSE_EXCEPTIONS
335
336 // ----------------------------------------------------------------------------
337 // cmd line parsing
338 // ----------------------------------------------------------------------------
339
340 #if wxUSE_CMDLINE_PARSER
341
342 #define OPTION_VERBOSE _T("verbose")
343
344 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
345 {
346 // the standard command line options
347 static const wxCmdLineEntryDesc cmdLineDesc[] =
348 {
349 {
350 wxCMD_LINE_SWITCH,
351 _T("h"),
352 _T("help"),
353 gettext_noop("show this help message"),
354 wxCMD_LINE_VAL_NONE,
355 wxCMD_LINE_OPTION_HELP
356 },
357
358 #if wxUSE_LOG
359 {
360 wxCMD_LINE_SWITCH,
361 wxEmptyString,
362 OPTION_VERBOSE,
363 gettext_noop("generate verbose log messages"),
364 wxCMD_LINE_VAL_NONE,
365 0x0
366 },
367 #endif // wxUSE_LOG
368
369 // terminator
370 {
371 wxCMD_LINE_NONE,
372 wxEmptyString,
373 wxEmptyString,
374 wxEmptyString,
375 wxCMD_LINE_VAL_NONE,
376 0x0
377 }
378 };
379
380 parser.SetDesc(cmdLineDesc);
381 }
382
383 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
384 {
385 #if wxUSE_LOG
386 if ( parser.Found(OPTION_VERBOSE) )
387 {
388 wxLog::SetVerbose(true);
389 }
390 #else
391 wxUnusedVar(parser);
392 #endif // wxUSE_LOG
393
394 return true;
395 }
396
397 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
398 {
399 parser.Usage();
400
401 return false;
402 }
403
404 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
405 {
406 parser.Usage();
407
408 return false;
409 }
410
411 #endif // wxUSE_CMDLINE_PARSER
412
413 // ----------------------------------------------------------------------------
414 // debugging support
415 // ----------------------------------------------------------------------------
416
417 /* static */
418 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
419 const char *componentName)
420 {
421 #if 0 // can't use wxLogTrace, not up and running yet
422 printf("checking build options object '%s' (ptr %p) in '%s'\n",
423 optionsSignature, optionsSignature, componentName);
424 #endif
425
426 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
427 {
428 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
429 wxString prog = wxString::FromAscii(optionsSignature);
430 wxString progName = wxString::FromAscii(componentName);
431 wxString msg;
432
433 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
434 lib.c_str(), progName.c_str(), prog.c_str());
435
436 wxLogFatalError(msg.c_str());
437
438 // normally wxLogFatalError doesn't return
439 return false;
440 }
441 #undef wxCMP
442
443 return true;
444 }
445
446 #ifdef __WXDEBUG__
447
448 void wxAppConsole::OnAssert(const wxChar *file,
449 int line,
450 const wxChar *cond,
451 const wxChar *msg)
452 {
453 ShowAssertDialog(file, line, cond, msg, GetTraits());
454 }
455
456 #endif // __WXDEBUG__
457
458 #if WXWIN_COMPATIBILITY_2_4
459
460 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& buildOptions)
461 {
462 return CheckBuildOptions(buildOptions.m_signature, "your program");
463 }
464
465 #endif
466
467 // ============================================================================
468 // other classes implementations
469 // ============================================================================
470
471 // ----------------------------------------------------------------------------
472 // wxConsoleAppTraitsBase
473 // ----------------------------------------------------------------------------
474
475 #if wxUSE_LOG
476
477 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
478 {
479 return new wxLogStderr;
480 }
481
482 #endif // wxUSE_LOG
483
484 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
485 {
486 return new wxMessageOutputStderr;
487 }
488
489 #if wxUSE_FONTMAP
490
491 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
492 {
493 return (wxFontMapper *)new wxFontMapperBase;
494 }
495
496 #endif // wxUSE_FONTMAP
497
498 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
499 {
500 // console applications don't use renderers
501 return NULL;
502 }
503
504 #ifdef __WXDEBUG__
505 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
506 {
507 return wxAppTraitsBase::ShowAssertDialog(msg);
508 }
509 #endif
510
511 bool wxConsoleAppTraitsBase::HasStderr()
512 {
513 // console applications always have stderr, even under Mac/Windows
514 return true;
515 }
516
517 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
518 {
519 delete object;
520 }
521
522 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
523 {
524 // nothing to do
525 }
526
527 #if wxUSE_SOCKETS
528 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
529 {
530 return NULL;
531 }
532 #endif
533
534 // ----------------------------------------------------------------------------
535 // wxAppTraits
536 // ----------------------------------------------------------------------------
537
538 #ifdef __WXDEBUG__
539
540 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
541 {
542 return DoShowAssertDialog(msg);
543 }
544
545 #endif // __WXDEBUG__
546
547 // ============================================================================
548 // global functions implementation
549 // ============================================================================
550
551 void wxExit()
552 {
553 if ( wxTheApp )
554 {
555 wxTheApp->Exit();
556 }
557 else
558 {
559 // what else can we do?
560 exit(-1);
561 }
562 }
563
564 void wxWakeUpIdle()
565 {
566 if ( wxTheApp )
567 {
568 wxTheApp->WakeUpIdle();
569 }
570 //else: do nothing, what can we do?
571 }
572
573 #ifdef __WXDEBUG__
574
575 // wxASSERT() helper
576 bool wxAssertIsEqual(int x, int y)
577 {
578 return x == y;
579 }
580
581 // break into the debugger
582 void wxTrap()
583 {
584 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
585 DebugBreak();
586 #elif defined(__WXMAC__) && !defined(__DARWIN__)
587 #if __powerc
588 Debugger();
589 #else
590 SysBreak();
591 #endif
592 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
593 Debugger();
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("wxWidgets 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 #if wxUSE_STACKWALKER
706 static wxString GetAssertStackTrace()
707 {
708 wxString stackTrace;
709
710 #if wxUSE_DBGHELP
711 // check that we can get the stack trace before trying to do it
712 if ( !wxDbgHelpDLL::Init() )
713 return stackTrace;
714 #endif
715
716 class StackDump : public wxStackWalker
717 {
718 public:
719 StackDump() { }
720
721 const wxString& GetStackTrace() const { return m_stackTrace; }
722
723 protected:
724 virtual void OnStackFrame(const wxStackFrame& frame)
725 {
726 m_stackTrace << wxString::Format(_T("[%02d] "), frame.GetLevel());
727
728 wxString name = frame.GetName();
729 if ( !name.empty() )
730 {
731 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
732 }
733 else
734 {
735 m_stackTrace << wxString::Format
736 (
737 _T("0x%08lx"),
738 (unsigned long)frame.GetAddress()
739 );
740 }
741
742 if ( frame.HasSourceLocation() )
743 {
744 m_stackTrace << _T('\t')
745 << frame.GetFileName()
746 << _T(':')
747 << frame.GetLine();
748 }
749
750 m_stackTrace << _T('\n');
751 }
752
753 private:
754 wxString m_stackTrace;
755 };
756
757 StackDump dump;
758 dump.Walk(5); // don't show OnAssert() call itself
759 stackTrace = dump.GetStackTrace();
760
761 // don't show more than maxLines or we could get a dialog too tall to be
762 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
763 // characters it is still only 300 pixels...
764 static const int maxLines = 20;
765 const int count = stackTrace.Freq(wxT('\n'));
766 for ( int i = 0; i < count - maxLines; i++ )
767 stackTrace = stackTrace.BeforeLast(wxT('\n'));
768
769 return stackTrace;
770 }
771 #endif // wxUSE_STACKWALKER
772
773 // show the assert modal dialog
774 static
775 void ShowAssertDialog(const wxChar *szFile,
776 int nLine,
777 const wxChar *szCond,
778 const wxChar *szMsg,
779 wxAppTraits *traits)
780 {
781 // this variable can be set to true to suppress "assert failure" messages
782 static bool s_bNoAsserts = false;
783
784 wxString msg;
785 msg.reserve(2048);
786
787 // make life easier for people using VC++ IDE by using this format: like
788 // this, clicking on the message will take us immediately to the place of
789 // the failed assert
790 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
791
792 if ( szMsg )
793 {
794 msg << _T(": ") << szMsg;
795 }
796 else // no message given
797 {
798 msg << _T('.');
799 }
800
801 #if wxUSE_STACKWALKER
802 const wxString stackTrace = GetAssertStackTrace();
803 if ( !stackTrace.empty() )
804 {
805 msg << _T("\n\nCall stack:\n") << stackTrace;
806 }
807 #endif // wxUSE_STACKWALKER
808
809 #if wxUSE_THREADS
810 // if we are not in the main thread, output the assert directly and trap
811 // since dialogs cannot be displayed
812 if ( !wxThread::IsMain() )
813 {
814 msg += wxT(" [in child thread]");
815
816 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
817 msg << wxT("\r\n");
818 OutputDebugString(msg );
819 #else
820 // send to stderr
821 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
822 fflush(stderr);
823 #endif
824 // He-e-e-e-elp!! we're asserting in a child thread
825 wxTrap();
826 }
827 else
828 #endif // wxUSE_THREADS
829
830 if ( !s_bNoAsserts )
831 {
832 // send it to the normal log destination
833 wxLogDebug(_T("%s"), msg.c_str());
834
835 if ( traits )
836 {
837 // delegate showing assert dialog (if possible) to that class
838 s_bNoAsserts = traits->ShowAssertDialog(msg);
839 }
840 else // no traits object
841 {
842 // fall back to the function of last resort
843 s_bNoAsserts = DoShowAssertDialog(msg);
844 }
845 }
846 }
847
848 #endif // __WXDEBUG__
849