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