1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/appbase.cpp
3 // Purpose: implements wxAppConsoleBase class
4 // Author: Vadim Zeitlin
6 // Created: 19.06.2003 (extracted from common/appcmn.cpp)
8 // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
9 // License: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
29 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
36 #include "wx/wxcrtvararg.h"
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"
49 #if wxUSE_EXCEPTIONS && wxUSE_STL
55 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
56 #include <signal.h> // for SIGTRAP used by wxTrap()
60 #endif // ! __WXPALMOS5__
63 #include "wx/fontmap.h"
64 #endif // wxUSE_FONTMAP
68 #include "wx/stackwalk.h"
70 #include "wx/msw/debughlp.h"
72 #endif // wxUSE_STACKWALKER
74 #include "wx/recguard.h"
75 #endif // wxDEBUG_LEVEL
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"
84 // ----------------------------------------------------------------------------
85 // private functions prototypes
86 // ----------------------------------------------------------------------------
89 // really just show the assert dialog
90 static bool DoShowAssertDialog(const wxString
& msg
);
92 // prepare for showing the assert dialog, use the given traits or
93 // DoShowAssertDialog() as last fallback to really show it
95 void ShowAssertDialog(const wxString
& file
,
100 wxAppTraits
*traits
= NULL
);
101 #endif // wxDEBUG_LEVEL
104 // turn on the trace masks specified in the env variable WXTRACE
105 static void LINKAGEMODE
SetTraceMasks();
106 #endif // __WXDEBUG__
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
112 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
114 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
116 wxSocketManager
*wxAppTraitsBase::ms_manager
= NULL
;
118 WXDLLIMPEXP_DATA_BASE(wxList
) wxPendingDelete
;
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 // this defines wxEventLoopPtr
125 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
127 // ============================================================================
128 // wxAppConsoleBase implementation
129 // ============================================================================
131 // ----------------------------------------------------------------------------
133 // ----------------------------------------------------------------------------
135 wxAppConsoleBase::wxAppConsoleBase()
139 m_bDoPendingEventProcessing
= true;
141 ms_appInstance
= static_cast<wxAppConsole
*>(this);
146 // In unicode mode the SetTraceMasks call can cause an apptraits to be
147 // created, but since we are still in the constructor the wrong kind will
148 // be created for GUI apps. Destroy it so it can be created again later.
155 wxAppConsoleBase::~wxAppConsoleBase()
160 // ----------------------------------------------------------------------------
161 // initialization/cleanup
162 // ----------------------------------------------------------------------------
164 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc
), wxChar
**argv
)
167 GetTraits()->SetLocale();
171 if ( m_appName
.empty() && argv
&& argv
[0] )
173 // the application name is, by default, the name of its executable file
174 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
176 #endif // !__WXPALMOS__
181 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
183 return GetTraits()->CreateEventLoop();
186 void wxAppConsoleBase::CleanUp()
195 // ----------------------------------------------------------------------------
197 // ----------------------------------------------------------------------------
199 bool wxAppConsoleBase::OnInit()
201 #if wxUSE_CMDLINE_PARSER
202 wxCmdLineParser
parser(argc
, argv
);
204 OnInitCmdLine(parser
);
207 switch ( parser
.Parse(false /* don't show usage */) )
210 cont
= OnCmdLineHelp(parser
);
214 cont
= OnCmdLineParsed(parser
);
218 cont
= OnCmdLineError(parser
);
224 #endif // wxUSE_CMDLINE_PARSER
229 int wxAppConsoleBase::OnRun()
234 int wxAppConsoleBase::OnExit()
237 // delete the config object if any (don't use Get() here, but Set()
238 // because Get() could create a new config object)
239 delete wxConfigBase::Set(NULL
);
240 #endif // wxUSE_CONFIG
245 void wxAppConsoleBase::Exit()
247 if (m_mainLoop
!= NULL
)
253 // ----------------------------------------------------------------------------
255 // ----------------------------------------------------------------------------
257 wxAppTraits
*wxAppConsoleBase::CreateTraits()
259 return new wxConsoleAppTraits
;
262 wxAppTraits
*wxAppConsoleBase::GetTraits()
264 // FIXME-MT: protect this with a CS?
267 m_traits
= CreateTraits();
269 wxASSERT_MSG( m_traits
, wxT("wxApp::CreateTraits() failed?") );
276 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
278 wxAppConsole
* const app
= GetInstance();
279 return app
? app
->GetTraits() : NULL
;
282 // ----------------------------------------------------------------------------
283 // wxEventLoop redirection
284 // ----------------------------------------------------------------------------
286 int wxAppConsoleBase::MainLoop()
288 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
290 return m_mainLoop
? m_mainLoop
->Run() : -1;
293 void wxAppConsoleBase::ExitMainLoop()
295 // we should exit from the main event loop, not just any currently active
296 // (e.g. modal dialog) event loop
297 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
303 bool wxAppConsoleBase::Pending()
305 // use the currently active message loop here, not m_mainLoop, because if
306 // we're showing a modal dialog (with its own event loop) currently the
307 // main event loop is not running anyhow
308 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
310 return loop
&& loop
->Pending();
313 bool wxAppConsoleBase::Dispatch()
315 // see comment in Pending()
316 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
318 return loop
&& loop
->Dispatch();
321 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
323 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
325 return loop
&& loop
->Yield(onlyIfNeeded
);
328 void wxAppConsoleBase::WakeUpIdle()
330 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
336 bool wxAppConsoleBase::ProcessIdle()
338 // synthesize an idle event and check if more of them are needed
340 event
.SetEventObject(this);
343 return event
.MoreRequested();
346 bool wxAppConsoleBase::UsesEventLoop() const
348 // in console applications we don't know whether we're going to have an
349 // event loop so assume we won't -- unless we already have one running
350 return wxEventLoopBase::GetActive() != NULL
;
353 // ----------------------------------------------------------------------------
355 // ----------------------------------------------------------------------------
358 bool wxAppConsoleBase::IsMainLoopRunning()
360 const wxAppConsole
* const app
= GetInstance();
362 return app
&& app
->m_mainLoop
!= NULL
;
365 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
367 // process the events normally by default
371 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
373 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
375 // move the handler from the list of handlers with processable pending events
376 // to the list of handlers with pending events which needs to be processed later
377 m_handlersWithPendingEvents
.Remove(toDelay
);
379 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
380 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
382 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
385 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
387 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
389 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
391 m_handlersWithPendingEvents
.Remove(toRemove
);
393 // check that the handler was present only once in the list
394 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
395 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
397 //else: it wasn't in this list at all, it's ok
399 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
401 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
403 // check that the handler was present only once in the list
404 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
405 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
407 //else: it wasn't in this list at all, it's ok
409 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
412 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
414 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
416 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
417 m_handlersWithPendingEvents
.Add(toAppend
);
419 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
422 bool wxAppConsoleBase::HasPendingEvents() const
424 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
426 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
428 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
433 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
435 m_bDoPendingEventProcessing
= false;
438 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
440 m_bDoPendingEventProcessing
= true;
443 void wxAppConsoleBase::ProcessPendingEvents()
445 if ( m_bDoPendingEventProcessing
)
447 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
449 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
450 "this helper list should be empty" );
452 // iterate until the list becomes empty: the handlers remove themselves
453 // from it when they don't have any more pending events
454 while (!m_handlersWithPendingEvents
.IsEmpty())
456 // In ProcessPendingEvents(), new handlers might be added
457 // and we can safely leave the critical section here.
458 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
460 // NOTE: we always call ProcessPendingEvents() on the first event handler
461 // with pending events because handlers auto-remove themselves
462 // from this list (see RemovePendingEventHandler) if they have no
463 // more pending events.
464 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
466 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
469 // now the wxHandlersWithPendingEvents is surely empty; however some event
470 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
471 // because of a selective wxYield call in progress.
472 // Now we need to move them back to wxHandlersWithPendingEvents so the next
473 // call to this function has the chance of processing them:
474 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
476 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
477 m_handlersWithPendingDelayedEvents
.Clear();
480 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
483 // Garbage collect all objects previously scheduled for destruction.
484 DeletePendingObjects();
487 void wxAppConsoleBase::DeletePendingEvents()
489 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
491 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
492 "this helper list should be empty" );
494 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
495 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
497 m_handlersWithPendingEvents
.Clear();
499 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
502 // ----------------------------------------------------------------------------
503 // delayed objects destruction
504 // ----------------------------------------------------------------------------
506 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
508 return wxPendingDelete
.Member(object
) != NULL
;
511 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
513 if ( !UsesEventLoop() )
515 // we won't be able to delete it later so do it right now
519 //else: we either already have or will soon start an event loop
521 if ( !wxPendingDelete
.Member(object
) )
522 wxPendingDelete
.Append(object
);
525 void wxAppConsoleBase::DeletePendingObjects()
527 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
530 wxObject
*obj
= node
->GetData();
532 // remove it from the list first so that if we get back here somehow
533 // during the object deletion (e.g. wxYield called from its dtor) we
534 // wouldn't try to delete it the second time
535 if ( wxPendingDelete
.Member(obj
) )
536 wxPendingDelete
.Erase(node
);
540 // Deleting one object may have deleted other pending
541 // objects, so start from beginning of list again.
542 node
= wxPendingDelete
.GetFirst();
546 // ----------------------------------------------------------------------------
547 // exception handling
548 // ----------------------------------------------------------------------------
553 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
554 wxEventFunction func
,
555 wxEvent
& event
) const
557 // by default, simply call the handler
558 (handler
->*func
)(event
);
561 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
562 wxEventFunctor
& functor
,
563 wxEvent
& event
) const
565 // If the functor holds a method then, for backward compatibility, call
567 wxEventFunction eventFunction
= functor
.GetEvtMethod();
570 HandleEvent(handler
, eventFunction
, event
);
572 functor(handler
, event
);
575 void wxAppConsoleBase::OnUnhandledException()
578 // we're called from an exception handler so we can re-throw the exception
579 // to recover its type
586 catch ( std::exception
& e
)
588 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
589 typeid(e
).name(), e
.what());
594 what
= "unknown exception";
597 wxMessageOutputBest().Printf(
598 "*** Caught unhandled %s; terminating\n", what
600 #endif // __WXDEBUG__
603 // ----------------------------------------------------------------------------
604 // exceptions support
605 // ----------------------------------------------------------------------------
607 bool wxAppConsoleBase::OnExceptionInMainLoop()
611 // some compilers are too stupid to know that we never return after throw
612 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
617 #endif // wxUSE_EXCEPTIONS
619 // ----------------------------------------------------------------------------
621 // ----------------------------------------------------------------------------
623 #if wxUSE_CMDLINE_PARSER
625 #define OPTION_VERBOSE "verbose"
627 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
629 // the standard command line options
630 static const wxCmdLineEntryDesc cmdLineDesc
[] =
636 gettext_noop("show this help message"),
638 wxCMD_LINE_OPTION_HELP
646 gettext_noop("generate verbose log messages"),
656 parser
.SetDesc(cmdLineDesc
);
659 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
662 if ( parser
.Found(OPTION_VERBOSE
) )
664 wxLog::SetVerbose(true);
673 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
680 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
687 #endif // wxUSE_CMDLINE_PARSER
689 // ----------------------------------------------------------------------------
691 // ----------------------------------------------------------------------------
694 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
695 const char *componentName
)
697 #if 0 // can't use wxLogTrace, not up and running yet
698 printf("checking build options object '%s' (ptr %p) in '%s'\n",
699 optionsSignature
, optionsSignature
, componentName
);
702 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
704 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
705 wxString prog
= wxString::FromAscii(optionsSignature
);
706 wxString progName
= wxString::FromAscii(componentName
);
709 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
710 lib
.c_str(), progName
.c_str(), prog
.c_str());
712 wxLogFatalError(msg
.c_str());
714 // normally wxLogFatalError doesn't return
721 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
728 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
730 // this function is still present even in debug level 0 build for ABI
731 // compatibility reasons but is never called there and so can simply do
738 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
741 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
746 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
749 // ============================================================================
750 // other classes implementations
751 // ============================================================================
753 // ----------------------------------------------------------------------------
754 // wxConsoleAppTraitsBase
755 // ----------------------------------------------------------------------------
759 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
761 return new wxLogStderr
;
766 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
768 return new wxMessageOutputStderr
;
773 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
775 return (wxFontMapper
*)new wxFontMapperBase
;
778 #endif // wxUSE_FONTMAP
780 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
782 // console applications don't use renderers
786 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
788 return wxAppTraitsBase::ShowAssertDialog(msg
);
791 bool wxConsoleAppTraitsBase::HasStderr()
793 // console applications always have stderr, even under Mac/Windows
797 // ----------------------------------------------------------------------------
799 // ----------------------------------------------------------------------------
802 void wxAppTraitsBase::SetLocale()
804 wxSetlocale(LC_ALL
, "");
805 wxUpdateLocaleIsUtf8();
810 void wxMutexGuiEnterImpl();
811 void wxMutexGuiLeaveImpl();
813 void wxAppTraitsBase::MutexGuiEnter()
815 wxMutexGuiEnterImpl();
818 void wxAppTraitsBase::MutexGuiLeave()
820 wxMutexGuiLeaveImpl();
823 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
825 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
827 traits
->MutexGuiEnter();
830 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
832 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
834 traits
->MutexGuiLeave();
836 #endif // wxUSE_THREADS
838 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
841 wxString msg
= msgOriginal
;
843 #if wxUSE_STACKWALKER
844 #if !defined(__WXMSW__)
845 // on Unix stack frame generation may take some time, depending on the
846 // size of the executable mainly... warn the user that we are working
847 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
851 const wxString stackTrace
= GetAssertStackTrace();
852 if ( !stackTrace
.empty() )
853 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
854 #endif // wxUSE_STACKWALKER
856 return DoShowAssertDialog(msg
);
857 #else // !wxDEBUG_LEVEL
858 wxUnusedVar(msgOriginal
);
861 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
864 #if wxUSE_STACKWALKER
865 wxString
wxAppTraitsBase::GetAssertStackTrace()
870 class StackDump
: public wxStackWalker
875 const wxString
& GetStackTrace() const { return m_stackTrace
; }
878 virtual void OnStackFrame(const wxStackFrame
& frame
)
880 m_stackTrace
<< wxString::Format
883 wx_truncate_cast(int, frame
.GetLevel())
886 wxString name
= frame
.GetName();
889 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
893 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
896 if ( frame
.HasSourceLocation() )
898 m_stackTrace
<< wxT('\t')
899 << frame
.GetFileName()
904 m_stackTrace
<< wxT('\n');
908 wxString m_stackTrace
;
911 // don't show more than maxLines or we could get a dialog too tall to be
912 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
913 // characters it is still only 300 pixels...
914 static const int maxLines
= 20;
917 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
918 stackTrace
= dump
.GetStackTrace();
920 const int count
= stackTrace
.Freq(wxT('\n'));
921 for ( int i
= 0; i
< count
- maxLines
; i
++ )
922 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
925 #else // !wxDEBUG_LEVEL
926 // this function is still present for ABI-compatibility even in debug level
927 // 0 build but is not used there and so can simply do nothing
929 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
931 #endif // wxUSE_STACKWALKER
934 // ============================================================================
935 // global functions implementation
936 // ============================================================================
946 // what else can we do?
955 wxTheApp
->WakeUpIdle();
957 //else: do nothing, what can we do?
961 bool wxAssertIsEqual(int x
, int y
)
968 // break into the debugger
971 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
973 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
975 #elif defined(__UNIX__)
982 // default assert handler
984 wxDefaultAssertHandler(const wxString
& file
,
986 const wxString
& func
,
987 const wxString
& cond
,
991 static int s_bInAssert
= 0;
993 wxRecursionGuard
guard(s_bInAssert
);
994 if ( guard
.IsInside() )
996 // can't use assert here to avoid infinite loops, so just trap
1004 // by default, show the assert dialog box -- we can't customize this
1006 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1010 // let the app process it as it wants
1011 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1012 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1013 cond
.c_str(), msg
.c_str());
1017 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1019 void wxOnAssert(const wxString
& file
,
1021 const wxString
& func
,
1022 const wxString
& cond
,
1023 const wxString
& msg
)
1025 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1028 void wxOnAssert(const wxString
& file
,
1030 const wxString
& func
,
1031 const wxString
& cond
)
1033 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1036 void wxOnAssert(const wxChar
*file
,
1042 // this is the backwards-compatible version (unless we don't use Unicode)
1043 // so it could be called directly from the user code and this might happen
1044 // even when wxTheAssertHandler is NULL
1046 if ( wxTheAssertHandler
)
1047 #endif // wxUSE_UNICODE
1048 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1051 void wxOnAssert(const char *file
,
1055 const wxString
& msg
)
1057 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1060 void wxOnAssert(const char *file
,
1064 const wxCStrData
& msg
)
1066 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1070 void wxOnAssert(const char *file
,
1075 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1078 void wxOnAssert(const char *file
,
1084 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1087 void wxOnAssert(const char *file
,
1093 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1095 #endif // wxUSE_UNICODE
1097 #endif // wxDEBUG_LEVEL
1099 // ============================================================================
1100 // private functions implementation
1101 // ============================================================================
1105 static void LINKAGEMODE
SetTraceMasks()
1109 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1111 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1112 while ( tkn
.HasMoreTokens() )
1113 wxLog::AddTraceMask(tkn
.GetNextToken());
1118 #endif // __WXDEBUG__
1123 bool DoShowAssertDialog(const wxString
& msg
)
1125 // under MSW we can show the dialog even in the console mode
1126 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1127 wxString
msgDlg(msg
);
1129 // this message is intentionally not translated -- it is for developers
1130 // only -- and the less code we use here, less is the danger of recursively
1131 // asserting and dying
1132 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1133 wxT("You can also choose [Cancel] to suppress ")
1134 wxT("further warnings.");
1136 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), wxT("wxWidgets Debug Alert"),
1137 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1147 //case IDNO: nothing to do
1150 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1153 // TODO: ask the user to enter "Y" or "N" on the console?
1155 #endif // __WXMSW__/!__WXMSW__
1157 // continue with the asserts
1161 // show the standard assert dialog
1163 void ShowAssertDialog(const wxString
& file
,
1165 const wxString
& func
,
1166 const wxString
& cond
,
1167 const wxString
& msgUser
,
1168 wxAppTraits
*traits
)
1170 // this variable can be set to true to suppress "assert failure" messages
1171 static bool s_bNoAsserts
= false;
1176 // make life easier for people using VC++ IDE by using this format: like
1177 // this, clicking on the message will take us immediately to the place of
1178 // the failed assert
1179 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1181 // add the function name, if any
1182 if ( !func
.empty() )
1183 msg
<< wxT(" in ") << func
<< wxT("()");
1185 // and the message itself
1186 if ( !msgUser
.empty() )
1188 msg
<< wxT(": ") << msgUser
;
1190 else // no message given
1196 // if we are not in the main thread, output the assert directly and trap
1197 // since dialogs cannot be displayed
1198 if ( !wxThread::IsMain() )
1200 msg
+= wxT(" [in child thread]");
1202 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1204 OutputDebugString(msg
.wx_str());
1207 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1210 // He-e-e-e-elp!! we're asserting in a child thread
1214 #endif // wxUSE_THREADS
1216 if ( !s_bNoAsserts
)
1218 // send it to the normal log destination
1219 wxLogDebug(wxT("%s"), msg
.c_str());
1223 // delegate showing assert dialog (if possible) to that class
1224 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1226 else // no traits object
1228 // fall back to the function of last resort
1229 s_bNoAsserts
= DoShowAssertDialog(msg
);
1234 #endif // wxDEBUG_LEVEL