reset s_bInAssert in wxDoOnAssert() in an exception-safe way (replaces patch 1900613)
[wxWidgets.git] / src / common / appbase.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/appbase.cpp
3 // Purpose: implements wxAppConsoleBase 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 #ifdef __WXMSW__
29 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
30 #endif
31 #include "wx/list.h"
32 #include "wx/app.h"
33 #include "wx/intl.h"
34 #include "wx/log.h"
35 #include "wx/utils.h"
36 #include "wx/wxcrtvararg.h"
37 #endif //WX_PRECOMP
38
39 #include "wx/apptrait.h"
40 #include "wx/cmdline.h"
41 #include "wx/confbase.h"
42 #include "wx/evtloop.h"
43 #include "wx/filename.h"
44 #include "wx/msgout.h"
45 #include "wx/ptr_scpd.h"
46 #include "wx/tokenzr.h"
47 #include "wx/thread.h"
48
49 #if wxUSE_EXCEPTIONS && wxUSE_STL
50 #include <exception>
51 #include <typeinfo>
52 #endif
53
54 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
55 #include <signal.h> // for SIGTRAP used by wxTrap()
56 #endif //Win/Unix
57
58 #include <locale.h>
59
60 #if wxUSE_FONTMAP
61 #include "wx/fontmap.h"
62 #endif // wxUSE_FONTMAP
63
64 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
65 // For MacTypes.h for Debugger function
66 #include <CoreFoundation/CFBase.h>
67 #endif
68
69 #if defined(__WXMAC__)
70 #ifdef __DARWIN__
71 #include <CoreServices/CoreServices.h>
72 #else
73 #include "wx/mac/private.h" // includes mac headers
74 #endif
75 #endif // __WXMAC__
76
77 #ifdef __WXDEBUG__
78 #if wxUSE_STACKWALKER
79 #include "wx/stackwalk.h"
80 #ifdef __WXMSW__
81 #include "wx/msw/debughlp.h"
82 #endif
83 #endif // wxUSE_STACKWALKER
84
85 #include "wx/recguard.h"
86 #endif // __WXDEBUG__
87
88 // wxABI_VERSION can be defined when compiling applications but it should be
89 // left undefined when compiling the library itself, it is then set to its
90 // default value in version.h
91 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
92 #error "wxABI_VERSION should not be defined when compiling the library"
93 #endif
94
95 // ----------------------------------------------------------------------------
96 // private functions prototypes
97 // ----------------------------------------------------------------------------
98
99 #ifdef __WXDEBUG__
100 // really just show the assert dialog
101 static bool DoShowAssertDialog(const wxString& msg);
102
103 // prepare for showing the assert dialog, use the given traits or
104 // DoShowAssertDialog() as last fallback to really show it
105 static
106 void ShowAssertDialog(const wxString& szFile,
107 int nLine,
108 const wxString& szFunc,
109 const wxString& szCond,
110 const wxString& szMsg,
111 wxAppTraits *traits = NULL);
112
113 // turn on the trace masks specified in the env variable WXTRACE
114 static void LINKAGEMODE SetTraceMasks();
115 #endif // __WXDEBUG__
116
117 // ----------------------------------------------------------------------------
118 // global vars
119 // ----------------------------------------------------------------------------
120
121 wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
122
123 wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
124
125 // ----------------------------------------------------------------------------
126 // wxEventLoopPtr
127 // ----------------------------------------------------------------------------
128
129 // this defines wxEventLoopPtr
130 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
131
132 // ============================================================================
133 // wxAppConsoleBase implementation
134 // ============================================================================
135
136 // ----------------------------------------------------------------------------
137 // ctor/dtor
138 // ----------------------------------------------------------------------------
139
140 wxAppConsoleBase::wxAppConsoleBase()
141 {
142 m_traits = NULL;
143 m_mainLoop = NULL;
144
145 ms_appInstance = wx_static_cast(wxAppConsole *, this);
146
147 #ifdef __WXDEBUG__
148 SetTraceMasks();
149 #if wxUSE_UNICODE
150 // In unicode mode the SetTraceMasks call can cause an apptraits to be
151 // created, but since we are still in the constructor the wrong kind will
152 // be created for GUI apps. Destroy it so it can be created again later.
153 delete m_traits;
154 m_traits = NULL;
155 #endif
156 #endif
157 }
158
159 wxAppConsoleBase::~wxAppConsoleBase()
160 {
161 delete m_traits;
162 }
163
164 // ----------------------------------------------------------------------------
165 // initilization/cleanup
166 // ----------------------------------------------------------------------------
167
168 bool wxAppConsoleBase::Initialize(int& argcOrig, wxChar **argvOrig)
169 {
170 #if wxUSE_INTL
171 GetTraits()->SetLocale();
172 #endif // wxUSE_INTL
173
174 // remember the command line arguments
175 argc = argcOrig;
176 argv = argvOrig;
177
178 #if wxUSE_THREADS
179 wxPendingEventsLocker = new wxCriticalSection;
180 #endif
181
182 #ifndef __WXPALMOS__
183 if ( m_appName.empty() && argv )
184 {
185 // the application name is, by default, the name of its executable file
186 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
187 }
188 #endif // !__WXPALMOS__
189
190 return true;
191 }
192
193 wxEventLoopBase *wxAppConsoleBase::CreateMainLoop()
194 {
195 return GetTraits()->CreateEventLoop();
196 }
197
198 void wxAppConsoleBase::CleanUp()
199 {
200 if ( m_mainLoop )
201 {
202 delete m_mainLoop;
203 m_mainLoop = NULL;
204 }
205
206 delete wxPendingEvents;
207 wxPendingEvents = NULL;
208
209 #if wxUSE_THREADS
210 delete wxPendingEventsLocker;
211 wxPendingEventsLocker = NULL;
212 #endif // wxUSE_THREADS
213 }
214
215 // ----------------------------------------------------------------------------
216 // OnXXX() callbacks
217 // ----------------------------------------------------------------------------
218
219 bool wxAppConsoleBase::OnInit()
220 {
221 #if wxUSE_CMDLINE_PARSER
222 wxCmdLineParser parser(argc, argv);
223
224 OnInitCmdLine(parser);
225
226 bool cont;
227 switch ( parser.Parse(false /* don't show usage */) )
228 {
229 case -1:
230 cont = OnCmdLineHelp(parser);
231 break;
232
233 case 0:
234 cont = OnCmdLineParsed(parser);
235 break;
236
237 default:
238 cont = OnCmdLineError(parser);
239 break;
240 }
241
242 if ( !cont )
243 return false;
244 #endif // wxUSE_CMDLINE_PARSER
245
246 return true;
247 }
248
249 int wxAppConsoleBase::OnRun()
250 {
251 return MainLoop();
252 }
253
254 int wxAppConsoleBase::OnExit()
255 {
256 #if wxUSE_CONFIG
257 // delete the config object if any (don't use Get() here, but Set()
258 // because Get() could create a new config object)
259 delete wxConfigBase::Set((wxConfigBase *) NULL);
260 #endif // wxUSE_CONFIG
261
262 return 0;
263 }
264
265 void wxAppConsoleBase::Exit()
266 {
267 if (m_mainLoop != NULL)
268 ExitMainLoop();
269 else
270 exit(-1);
271 }
272
273 // ----------------------------------------------------------------------------
274 // traits stuff
275 // ----------------------------------------------------------------------------
276
277 wxAppTraits *wxAppConsoleBase::CreateTraits()
278 {
279 return new wxConsoleAppTraits;
280 }
281
282 wxAppTraits *wxAppConsoleBase::GetTraits()
283 {
284 // FIXME-MT: protect this with a CS?
285 if ( !m_traits )
286 {
287 m_traits = CreateTraits();
288
289 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
290 }
291
292 return m_traits;
293 }
294
295 // ----------------------------------------------------------------------------
296 // event processing
297 // ----------------------------------------------------------------------------
298
299 int wxAppConsoleBase::MainLoop()
300 {
301 wxEventLoopBaseTiedPtr mainLoop(&m_mainLoop, CreateMainLoop());
302
303 return m_mainLoop ? m_mainLoop->Run() : -1;
304 }
305
306 void wxAppConsoleBase::ExitMainLoop()
307 {
308 // we should exit from the main event loop, not just any currently active
309 // (e.g. modal dialog) event loop
310 if ( m_mainLoop && m_mainLoop->IsRunning() )
311 {
312 m_mainLoop->Exit(0);
313 }
314 }
315
316 bool wxAppConsoleBase::Pending()
317 {
318 // use the currently active message loop here, not m_mainLoop, because if
319 // we're showing a modal dialog (with its own event loop) currently the
320 // main event loop is not running anyhow
321 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
322
323 return loop && loop->Pending();
324 }
325
326 bool wxAppConsoleBase::Dispatch()
327 {
328 // see comment in Pending()
329 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
330
331 return loop && loop->Dispatch();
332 }
333
334 bool wxAppConsoleBase::HasPendingEvents() const
335 {
336 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
337
338 bool has = wxPendingEvents && !wxPendingEvents->IsEmpty();
339
340 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
341
342 return has;
343 }
344
345 /* static */
346 bool wxAppConsoleBase::IsMainLoopRunning()
347 {
348 const wxAppConsole * const app = GetInstance();
349
350 return app && app->m_mainLoop != NULL;
351 }
352
353 void wxAppConsoleBase::ProcessPendingEvents()
354 {
355 #if wxUSE_THREADS
356 if ( !wxPendingEventsLocker )
357 return;
358 #endif
359
360 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
361
362 if (wxPendingEvents)
363 {
364 // iterate until the list becomes empty: the handlers remove themselves
365 // from it when they don't have any more pending events
366 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
367 while (node)
368 {
369 // In ProcessPendingEvents(), new handlers might be add
370 // and we can safely leave the critical section here.
371 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
372
373 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
374 handler->ProcessPendingEvents();
375
376 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
377
378 // restart as the iterators could have been invalidated
379 node = wxPendingEvents->GetFirst();
380 }
381 }
382
383 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
384 }
385
386 void wxAppConsoleBase::WakeUpIdle()
387 {
388 if ( m_mainLoop )
389 m_mainLoop->WakeUp();
390 }
391
392 bool wxAppConsoleBase::ProcessIdle()
393 {
394 wxIdleEvent event;
395
396 event.SetEventObject(this);
397 ProcessEvent(event);
398 return event.MoreRequested();
399 }
400
401 int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
402 {
403 // process the events normally by default
404 return -1;
405 }
406
407 // ----------------------------------------------------------------------------
408 // exception handling
409 // ----------------------------------------------------------------------------
410
411 #if wxUSE_EXCEPTIONS
412
413 void
414 wxAppConsoleBase::HandleEvent(wxEvtHandler *handler,
415 wxEventFunction func,
416 wxEvent& event) const
417 {
418 // by default, simply call the handler
419 (handler->*func)(event);
420 }
421
422 void wxAppConsoleBase::OnUnhandledException()
423 {
424 #ifdef __WXDEBUG__
425 // we're called from an exception handler so we can re-throw the exception
426 // to recover its type
427 wxString what;
428 try
429 {
430 throw;
431 }
432 #if wxUSE_STL
433 catch ( std::exception& e )
434 {
435 what.Printf("std::exception of type \"%s\", what() = \"%s\"",
436 typeid(e).name(), e.what());
437 }
438 #endif // wxUSE_STL
439 catch ( ... )
440 {
441 what = "unknown exception";
442 }
443
444 wxMessageOutputBest().Printf(
445 "*** Caught unhandled %s; terminating\n", what
446 );
447 #endif // __WXDEBUG__
448 }
449
450 // ----------------------------------------------------------------------------
451 // exceptions support
452 // ----------------------------------------------------------------------------
453
454 bool wxAppConsoleBase::OnExceptionInMainLoop()
455 {
456 throw;
457
458 // some compilers are too stupid to know that we never return after throw
459 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
460 return false;
461 #endif
462 }
463
464 #endif // wxUSE_EXCEPTIONS
465
466 // ----------------------------------------------------------------------------
467 // cmd line parsing
468 // ----------------------------------------------------------------------------
469
470 #if wxUSE_CMDLINE_PARSER
471
472 #define OPTION_VERBOSE "verbose"
473
474 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser& parser)
475 {
476 // the standard command line options
477 static const wxCmdLineEntryDesc cmdLineDesc[] =
478 {
479 {
480 wxCMD_LINE_SWITCH,
481 "h",
482 "help",
483 gettext_noop("show this help message"),
484 wxCMD_LINE_VAL_NONE,
485 wxCMD_LINE_OPTION_HELP
486 },
487
488 #if wxUSE_LOG
489 {
490 wxCMD_LINE_SWITCH,
491 NULL,
492 OPTION_VERBOSE,
493 gettext_noop("generate verbose log messages"),
494 wxCMD_LINE_VAL_NONE,
495 0x0
496 },
497 #endif // wxUSE_LOG
498
499 // terminator
500 wxCMD_LINE_DESC_END
501 };
502
503 parser.SetDesc(cmdLineDesc);
504 }
505
506 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser& parser)
507 {
508 #if wxUSE_LOG
509 if ( parser.Found(OPTION_VERBOSE) )
510 {
511 wxLog::SetVerbose(true);
512 }
513 #else
514 wxUnusedVar(parser);
515 #endif // wxUSE_LOG
516
517 return true;
518 }
519
520 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser& parser)
521 {
522 parser.Usage();
523
524 return false;
525 }
526
527 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser& parser)
528 {
529 parser.Usage();
530
531 return false;
532 }
533
534 #endif // wxUSE_CMDLINE_PARSER
535
536 // ----------------------------------------------------------------------------
537 // debugging support
538 // ----------------------------------------------------------------------------
539
540 /* static */
541 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature,
542 const char *componentName)
543 {
544 #if 0 // can't use wxLogTrace, not up and running yet
545 printf("checking build options object '%s' (ptr %p) in '%s'\n",
546 optionsSignature, optionsSignature, componentName);
547 #endif
548
549 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
550 {
551 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
552 wxString prog = wxString::FromAscii(optionsSignature);
553 wxString progName = wxString::FromAscii(componentName);
554 wxString msg;
555
556 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
557 lib.c_str(), progName.c_str(), prog.c_str());
558
559 wxLogFatalError(msg.c_str());
560
561 // normally wxLogFatalError doesn't return
562 return false;
563 }
564 #undef wxCMP
565
566 return true;
567 }
568
569 #ifdef __WXDEBUG__
570
571 void wxAppConsoleBase::OnAssertFailure(const wxChar *file,
572 int line,
573 const wxChar *func,
574 const wxChar *cond,
575 const wxChar *msg)
576 {
577 ShowAssertDialog(file, line, func, cond, msg, GetTraits());
578 }
579
580 void wxAppConsoleBase::OnAssert(const wxChar *file,
581 int line,
582 const wxChar *cond,
583 const wxChar *msg)
584 {
585 OnAssertFailure(file, line, NULL, cond, msg);
586 }
587
588 #endif // __WXDEBUG__
589
590 // ============================================================================
591 // other classes implementations
592 // ============================================================================
593
594 // ----------------------------------------------------------------------------
595 // wxConsoleAppTraitsBase
596 // ----------------------------------------------------------------------------
597
598 #if wxUSE_LOG
599
600 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
601 {
602 return new wxLogStderr;
603 }
604
605 #endif // wxUSE_LOG
606
607 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
608 {
609 return new wxMessageOutputStderr;
610 }
611
612 #if wxUSE_FONTMAP
613
614 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
615 {
616 return (wxFontMapper *)new wxFontMapperBase;
617 }
618
619 #endif // wxUSE_FONTMAP
620
621 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
622 {
623 // console applications don't use renderers
624 return NULL;
625 }
626
627 #ifdef __WXDEBUG__
628 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
629 {
630 return wxAppTraitsBase::ShowAssertDialog(msg);
631 }
632 #endif
633
634 bool wxConsoleAppTraitsBase::HasStderr()
635 {
636 // console applications always have stderr, even under Mac/Windows
637 return true;
638 }
639
640 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
641 {
642 delete object;
643 }
644
645 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
646 {
647 // nothing to do
648 }
649
650 // ----------------------------------------------------------------------------
651 // wxAppTraits
652 // ----------------------------------------------------------------------------
653
654 #if wxUSE_INTL
655 void wxAppTraitsBase::SetLocale()
656 {
657 wxSetlocale(LC_ALL, "");
658 wxUpdateLocaleIsUtf8();
659 }
660 #endif
661
662 #if wxUSE_THREADS
663 void wxMutexGuiEnterImpl();
664 void wxMutexGuiLeaveImpl();
665
666 void wxAppTraitsBase::MutexGuiEnter()
667 {
668 wxMutexGuiEnterImpl();
669 }
670
671 void wxAppTraitsBase::MutexGuiLeave()
672 {
673 wxMutexGuiLeaveImpl();
674 }
675
676 void WXDLLIMPEXP_BASE wxMutexGuiEnter()
677 {
678 wxAppConsoleBase::GetInstance()->GetTraits()->MutexGuiEnter();
679 }
680
681 void WXDLLIMPEXP_BASE wxMutexGuiLeave()
682 {
683 wxAppConsoleBase::GetInstance()->GetTraits()->MutexGuiLeave();
684 }
685 #endif // wxUSE_THREADS
686
687 #ifdef __WXDEBUG__
688
689 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
690 {
691 wxString msg = msgOriginal;
692
693 #if wxUSE_STACKWALKER
694 #if !defined(__WXMSW__)
695 // on Unix stack frame generation may take some time, depending on the
696 // size of the executable mainly... warn the user that we are working
697 wxFprintf(stderr, wxT("[Debug] Generating a stack trace... please wait"));
698 fflush(stderr);
699 #endif
700
701 const wxString stackTrace = GetAssertStackTrace();
702 if ( !stackTrace.empty() )
703 msg << _T("\n\nCall stack:\n") << stackTrace;
704 #endif // wxUSE_STACKWALKER
705
706 return DoShowAssertDialog(msg);
707 }
708
709 #if wxUSE_STACKWALKER
710 wxString wxAppTraitsBase::GetAssertStackTrace()
711 {
712 wxString stackTrace;
713
714 class StackDump : public wxStackWalker
715 {
716 public:
717 StackDump() { }
718
719 const wxString& GetStackTrace() const { return m_stackTrace; }
720
721 protected:
722 virtual void OnStackFrame(const wxStackFrame& frame)
723 {
724 m_stackTrace << wxString::Format
725 (
726 _T("[%02d] "),
727 wx_truncate_cast(int, frame.GetLevel())
728 );
729
730 wxString name = frame.GetName();
731 if ( !name.empty() )
732 {
733 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
734 }
735 else
736 {
737 m_stackTrace << wxString::Format(_T("%p"), frame.GetAddress());
738 }
739
740 if ( frame.HasSourceLocation() )
741 {
742 m_stackTrace << _T('\t')
743 << frame.GetFileName()
744 << _T(':')
745 << frame.GetLine();
746 }
747
748 m_stackTrace << _T('\n');
749 }
750
751 private:
752 wxString m_stackTrace;
753 };
754
755 // don't show more than maxLines or we could get a dialog too tall to be
756 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
757 // characters it is still only 300 pixels...
758 static const int maxLines = 20;
759
760 StackDump dump;
761 dump.Walk(2, maxLines); // don't show OnAssert() call itself
762 stackTrace = dump.GetStackTrace();
763
764 const int count = stackTrace.Freq(wxT('\n'));
765 for ( int i = 0; i < count - maxLines; i++ )
766 stackTrace = stackTrace.BeforeLast(wxT('\n'));
767
768 return stackTrace;
769 }
770 #endif // wxUSE_STACKWALKER
771
772
773 #endif // __WXDEBUG__
774
775 // ============================================================================
776 // global functions implementation
777 // ============================================================================
778
779 void wxExit()
780 {
781 if ( wxTheApp )
782 {
783 wxTheApp->Exit();
784 }
785 else
786 {
787 // what else can we do?
788 exit(-1);
789 }
790 }
791
792 void wxWakeUpIdle()
793 {
794 if ( wxTheApp )
795 {
796 wxTheApp->WakeUpIdle();
797 }
798 //else: do nothing, what can we do?
799 }
800
801 #ifdef __WXDEBUG__
802
803 // wxASSERT() helper
804 bool wxAssertIsEqual(int x, int y)
805 {
806 return x == y;
807 }
808
809 // break into the debugger
810 void wxTrap()
811 {
812 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
813 DebugBreak();
814 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
815 Debugger();
816 #elif defined(__UNIX__)
817 raise(SIGTRAP);
818 #else
819 // TODO
820 #endif // Win/Unix
821 }
822
823 // this function is called when an assert fails
824 static void wxDoOnAssert(const wxString& szFile,
825 int nLine,
826 const wxString& szFunc,
827 const wxString& szCond,
828 const wxString& szMsg = wxEmptyString)
829 {
830 // FIXME MT-unsafe
831 static int s_bInAssert = 0;
832
833 wxRecursionGuard guard(s_bInAssert);
834 if ( guard.IsInside() )
835 {
836 // can't use assert here to avoid infinite loops, so just trap
837 wxTrap();
838
839 return;
840 }
841
842 if ( !wxTheApp )
843 {
844 // by default, show the assert dialog box -- we can't customize this
845 // behaviour
846 ShowAssertDialog(szFile, nLine, szFunc, szCond, szMsg);
847 }
848 else
849 {
850 // let the app process it as it wants
851 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
852 wxTheApp->OnAssertFailure(szFile.c_str(), nLine, szFunc.c_str(),
853 szCond.c_str(), szMsg.c_str());
854 }
855 }
856
857 void wxOnAssert(const wxString& szFile,
858 int nLine,
859 const wxString& szFunc,
860 const wxString& szCond,
861 const wxString& szMsg)
862 {
863 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
864 }
865
866 void wxOnAssert(const wxString& szFile,
867 int nLine,
868 const wxString& szFunc,
869 const wxString& szCond)
870 {
871 wxDoOnAssert(szFile, nLine, szFunc, szCond);
872 }
873
874 void wxOnAssert(const wxChar *szFile,
875 int nLine,
876 const char *szFunc,
877 const wxChar *szCond,
878 const wxChar *szMsg)
879 {
880 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
881 }
882
883 void wxOnAssert(const char *szFile,
884 int nLine,
885 const char *szFunc,
886 const char *szCond,
887 const wxString& szMsg)
888 {
889 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
890 }
891
892 void wxOnAssert(const char *szFile,
893 int nLine,
894 const char *szFunc,
895 const char *szCond,
896 const wxCStrData& msg)
897 {
898 wxDoOnAssert(szFile, nLine, szFunc, szCond, msg);
899 }
900
901 #if wxUSE_UNICODE
902 void wxOnAssert(const char *szFile,
903 int nLine,
904 const char *szFunc,
905 const char *szCond)
906 {
907 wxDoOnAssert(szFile, nLine, szFunc, szCond);
908 }
909
910 void wxOnAssert(const char *szFile,
911 int nLine,
912 const char *szFunc,
913 const char *szCond,
914 const char *szMsg)
915 {
916 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
917 }
918
919 void wxOnAssert(const char *szFile,
920 int nLine,
921 const char *szFunc,
922 const char *szCond,
923 const wxChar *szMsg)
924 {
925 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
926 }
927 #endif // wxUSE_UNICODE
928
929 #endif // __WXDEBUG__
930
931 // ============================================================================
932 // private functions implementation
933 // ============================================================================
934
935 #ifdef __WXDEBUG__
936
937 static void LINKAGEMODE SetTraceMasks()
938 {
939 #if wxUSE_LOG
940 wxString mask;
941 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
942 {
943 wxStringTokenizer tkn(mask, wxT(",;:"));
944 while ( tkn.HasMoreTokens() )
945 wxLog::AddTraceMask(tkn.GetNextToken());
946 }
947 #endif // wxUSE_LOG
948 }
949
950 static
951 bool DoShowAssertDialog(const wxString& msg)
952 {
953 // under MSW we can show the dialog even in the console mode
954 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
955 wxString msgDlg(msg);
956
957 // this message is intentionally not translated -- it is for
958 // developpers only
959 msgDlg += wxT("\nDo you want to stop the program?\n")
960 wxT("You can also choose [Cancel] to suppress ")
961 wxT("further warnings.");
962
963 switch ( ::MessageBox(NULL, msgDlg.wx_str(), _T("wxWidgets Debug Alert"),
964 MB_YESNOCANCEL | MB_ICONSTOP ) )
965 {
966 case IDYES:
967 wxTrap();
968 break;
969
970 case IDCANCEL:
971 // stop the asserts
972 return true;
973
974 //case IDNO: nothing to do
975 }
976 #else // !__WXMSW__
977 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
978 fflush(stderr);
979
980 // TODO: ask the user to enter "Y" or "N" on the console?
981 wxTrap();
982 #endif // __WXMSW__/!__WXMSW__
983
984 // continue with the asserts
985 return false;
986 }
987
988 // show the assert modal dialog
989 static
990 void ShowAssertDialog(const wxString& szFile,
991 int nLine,
992 const wxString& szFunc,
993 const wxString& szCond,
994 const wxString& szMsg,
995 wxAppTraits *traits)
996 {
997 // this variable can be set to true to suppress "assert failure" messages
998 static bool s_bNoAsserts = false;
999
1000 wxString msg;
1001 msg.reserve(2048);
1002
1003 // make life easier for people using VC++ IDE by using this format: like
1004 // this, clicking on the message will take us immediately to the place of
1005 // the failed assert
1006 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
1007
1008 // add the function name, if any
1009 if ( !szFunc.empty() )
1010 msg << _T(" in ") << szFunc << _T("()");
1011
1012 // and the message itself
1013 if ( !szMsg.empty() )
1014 {
1015 msg << _T(": ") << szMsg;
1016 }
1017 else // no message given
1018 {
1019 msg << _T('.');
1020 }
1021
1022 #if wxUSE_THREADS
1023 // if we are not in the main thread, output the assert directly and trap
1024 // since dialogs cannot be displayed
1025 if ( !wxThread::IsMain() )
1026 {
1027 msg += wxT(" [in child thread]");
1028
1029 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1030 msg << wxT("\r\n");
1031 OutputDebugString(msg.wx_str());
1032 #else
1033 // send to stderr
1034 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
1035 fflush(stderr);
1036 #endif
1037 // He-e-e-e-elp!! we're asserting in a child thread
1038 wxTrap();
1039 }
1040 else
1041 #endif // wxUSE_THREADS
1042
1043 if ( !s_bNoAsserts )
1044 {
1045 // send it to the normal log destination
1046 wxLogDebug(_T("%s"), msg.c_str());
1047
1048 if ( traits )
1049 {
1050 // delegate showing assert dialog (if possible) to that class
1051 s_bNoAsserts = traits->ShowAssertDialog(msg);
1052 }
1053 else // no traits object
1054 {
1055 // fall back to the function of last resort
1056 s_bNoAsserts = DoShowAssertDialog(msg);
1057 }
1058 }
1059 }
1060
1061 #endif // __WXDEBUG__