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