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