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