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 // Licence: wxWindows licence
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/sysopt.h"
47 #include "wx/tokenzr.h"
48 #include "wx/thread.h"
60 #if !defined(__WINDOWS__) || defined(__WXMICROWIN__)
61 #include <signal.h> // for SIGTRAP used by wxTrap()
67 #include "wx/fontmap.h"
68 #endif // wxUSE_FONTMAP
72 #include "wx/stackwalk.h"
74 #include "wx/msw/debughlp.h"
76 #endif // wxUSE_STACKWALKER
78 #include "wx/recguard.h"
79 #endif // wxDEBUG_LEVEL
81 // wxABI_VERSION can be defined when compiling applications but it should be
82 // left undefined when compiling the library itself, it is then set to its
83 // default value in version.h
84 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
85 #error "wxABI_VERSION should not be defined when compiling the library"
88 // ----------------------------------------------------------------------------
89 // private functions prototypes
90 // ----------------------------------------------------------------------------
93 // really just show the assert dialog
94 static bool DoShowAssertDialog(const wxString
& msg
);
96 // prepare for showing the assert dialog, use the given traits or
97 // DoShowAssertDialog() as last fallback to really show it
99 void ShowAssertDialog(const wxString
& file
,
101 const wxString
& func
,
102 const wxString
& cond
,
104 wxAppTraits
*traits
= NULL
);
105 #endif // wxDEBUG_LEVEL
108 // turn on the trace masks specified in the env variable WXTRACE
109 static void LINKAGEMODE
SetTraceMasks();
110 #endif // __WXDEBUG__
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
118 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
120 wxSocketManager
*wxAppTraitsBase::ms_manager
= NULL
;
122 WXDLLIMPEXP_DATA_BASE(wxList
) wxPendingDelete
;
124 // ----------------------------------------------------------------------------
126 // ----------------------------------------------------------------------------
128 // this defines wxEventLoopPtr
129 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
131 // ============================================================================
132 // wxAppConsoleBase implementation
133 // ============================================================================
135 // ----------------------------------------------------------------------------
137 // ----------------------------------------------------------------------------
139 wxAppConsoleBase::wxAppConsoleBase()
143 m_bDoPendingEventProcessing
= true;
145 ms_appInstance
= static_cast<wxAppConsole
*>(this);
150 // In unicode mode the SetTraceMasks call can cause an apptraits to be
151 // created, but since we are still in the constructor the wrong kind will
152 // be created for GUI apps. Destroy it so it can be created again later.
157 wxEvtHandler::AddFilter(this);
160 wxAppConsoleBase::~wxAppConsoleBase()
162 wxEvtHandler::RemoveFilter(this);
164 // we're being destroyed and using this object from now on may not work or
165 // even crash so don't leave dangling pointers to it
166 ms_appInstance
= NULL
;
171 // ----------------------------------------------------------------------------
172 // initialization/cleanup
173 // ----------------------------------------------------------------------------
175 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc
), wxChar
**WXUNUSED(argv
))
178 GetTraits()->SetLocale();
184 wxString
wxAppConsoleBase::GetAppName() const
186 wxString name
= m_appName
;
191 // the application name is, by default, the name of its executable file
192 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
198 wxString
wxAppConsoleBase::GetAppDisplayName() const
200 // use the explicitly provided display name, if any
201 if ( !m_appDisplayName
.empty() )
202 return m_appDisplayName
;
204 // if the application name was explicitly set, use it as is as capitalizing
205 // it won't always produce good results
206 if ( !m_appName
.empty() )
209 // if neither is set, use the capitalized version of the program file as
210 // it's the most reasonable default
211 return GetAppName().Capitalize();
214 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
216 return GetTraits()->CreateEventLoop();
219 void wxAppConsoleBase::CleanUp()
221 wxDELETE(m_mainLoop
);
224 // ----------------------------------------------------------------------------
226 // ----------------------------------------------------------------------------
228 bool wxAppConsoleBase::OnInit()
230 #if wxUSE_CMDLINE_PARSER
231 wxCmdLineParser
parser(argc
, argv
);
233 OnInitCmdLine(parser
);
236 switch ( parser
.Parse(false /* don't show usage */) )
239 cont
= OnCmdLineHelp(parser
);
243 cont
= OnCmdLineParsed(parser
);
247 cont
= OnCmdLineError(parser
);
253 #endif // wxUSE_CMDLINE_PARSER
258 int wxAppConsoleBase::OnRun()
263 int wxAppConsoleBase::OnExit()
266 // delete the config object if any (don't use Get() here, but Set()
267 // because Get() could create a new config object)
268 delete wxConfigBase::Set(NULL
);
269 #endif // wxUSE_CONFIG
274 void wxAppConsoleBase::Exit()
276 if (m_mainLoop
!= NULL
)
282 // ----------------------------------------------------------------------------
284 // ----------------------------------------------------------------------------
286 wxAppTraits
*wxAppConsoleBase::CreateTraits()
288 return new wxConsoleAppTraits
;
291 wxAppTraits
*wxAppConsoleBase::GetTraits()
293 // FIXME-MT: protect this with a CS?
296 m_traits
= CreateTraits();
298 wxASSERT_MSG( m_traits
, wxT("wxApp::CreateTraits() failed?") );
305 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
307 wxAppConsole
* const app
= GetInstance();
308 return app
? app
->GetTraits() : NULL
;
311 // ----------------------------------------------------------------------------
312 // wxEventLoop redirection
313 // ----------------------------------------------------------------------------
315 int wxAppConsoleBase::MainLoop()
317 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
319 return m_mainLoop
? m_mainLoop
->Run() : -1;
322 void wxAppConsoleBase::ExitMainLoop()
324 // we should exit from the main event loop, not just any currently active
325 // (e.g. modal dialog) event loop
326 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
332 bool wxAppConsoleBase::Pending()
334 // use the currently active message loop here, not m_mainLoop, because if
335 // we're showing a modal dialog (with its own event loop) currently the
336 // main event loop is not running anyhow
337 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
339 return loop
&& loop
->Pending();
342 bool wxAppConsoleBase::Dispatch()
344 // see comment in Pending()
345 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
347 return loop
&& loop
->Dispatch();
350 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
352 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
354 return loop
->Yield(onlyIfNeeded
);
356 wxScopedPtr
<wxEventLoopBase
> tmpLoop(CreateMainLoop());
357 return tmpLoop
->Yield(onlyIfNeeded
);
360 void wxAppConsoleBase::WakeUpIdle()
362 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
368 bool wxAppConsoleBase::ProcessIdle()
370 // synthesize an idle event and check if more of them are needed
372 event
.SetEventObject(this);
376 // flush the logged messages if any (do this after processing the events
377 // which could have logged new messages)
378 wxLog::FlushActive();
381 // Garbage collect all objects previously scheduled for destruction.
382 DeletePendingObjects();
384 return event
.MoreRequested();
387 bool wxAppConsoleBase::UsesEventLoop() const
389 // in console applications we don't know whether we're going to have an
390 // event loop so assume we won't -- unless we already have one running
391 return wxEventLoopBase::GetActive() != NULL
;
394 // ----------------------------------------------------------------------------
396 // ----------------------------------------------------------------------------
399 bool wxAppConsoleBase::IsMainLoopRunning()
401 const wxAppConsole
* const app
= GetInstance();
403 return app
&& app
->m_mainLoop
!= NULL
;
406 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
408 // process the events normally by default
412 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
414 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
416 // move the handler from the list of handlers with processable pending events
417 // to the list of handlers with pending events which needs to be processed later
418 m_handlersWithPendingEvents
.Remove(toDelay
);
420 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
421 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
423 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
426 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
428 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
430 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
432 m_handlersWithPendingEvents
.Remove(toRemove
);
434 // check that the handler was present only once in the list
435 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
436 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
438 //else: it wasn't in this list at all, it's ok
440 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
442 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
444 // check that the handler was present only once in the list
445 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
446 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
448 //else: it wasn't in this list at all, it's ok
450 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
453 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
455 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
457 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
458 m_handlersWithPendingEvents
.Add(toAppend
);
460 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
463 bool wxAppConsoleBase::HasPendingEvents() const
465 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
467 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
469 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
474 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
476 m_bDoPendingEventProcessing
= false;
479 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
481 m_bDoPendingEventProcessing
= true;
484 void wxAppConsoleBase::ProcessPendingEvents()
486 if ( m_bDoPendingEventProcessing
)
488 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
490 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
491 "this helper list should be empty" );
493 // iterate until the list becomes empty: the handlers remove themselves
494 // from it when they don't have any more pending events
495 while (!m_handlersWithPendingEvents
.IsEmpty())
497 // In ProcessPendingEvents(), new handlers might be added
498 // and we can safely leave the critical section here.
499 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
501 // NOTE: we always call ProcessPendingEvents() on the first event handler
502 // with pending events because handlers auto-remove themselves
503 // from this list (see RemovePendingEventHandler) if they have no
504 // more pending events.
505 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
507 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
510 // now the wxHandlersWithPendingEvents is surely empty; however some event
511 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
512 // because of a selective wxYield call in progress.
513 // Now we need to move them back to wxHandlersWithPendingEvents so the next
514 // call to this function has the chance of processing them:
515 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
517 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
518 m_handlersWithPendingDelayedEvents
.Clear();
521 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
525 void wxAppConsoleBase::DeletePendingEvents()
527 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
529 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
530 "this helper list should be empty" );
532 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
533 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
535 m_handlersWithPendingEvents
.Clear();
537 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
540 // ----------------------------------------------------------------------------
541 // delayed objects destruction
542 // ----------------------------------------------------------------------------
544 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
546 return wxPendingDelete
.Member(object
);
549 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
551 if ( !UsesEventLoop() )
553 // we won't be able to delete it later so do it right now
557 //else: we either already have or will soon start an event loop
559 if ( !wxPendingDelete
.Member(object
) )
560 wxPendingDelete
.Append(object
);
563 void wxAppConsoleBase::DeletePendingObjects()
565 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
568 wxObject
*obj
= node
->GetData();
570 // remove it from the list first so that if we get back here somehow
571 // during the object deletion (e.g. wxYield called from its dtor) we
572 // wouldn't try to delete it the second time
573 if ( wxPendingDelete
.Member(obj
) )
574 wxPendingDelete
.Erase(node
);
578 // Deleting one object may have deleted other pending
579 // objects, so start from beginning of list again.
580 node
= wxPendingDelete
.GetFirst();
584 // ----------------------------------------------------------------------------
585 // exception handling
586 // ----------------------------------------------------------------------------
591 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
592 wxEventFunction func
,
593 wxEvent
& event
) const
595 // by default, simply call the handler
596 (handler
->*func
)(event
);
599 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
600 wxEventFunctor
& functor
,
601 wxEvent
& event
) const
603 // If the functor holds a method then, for backward compatibility, call
605 wxEventFunction eventFunction
= functor
.GetEvtMethod();
608 HandleEvent(handler
, eventFunction
, event
);
610 functor(handler
, event
);
613 void wxAppConsoleBase::OnUnhandledException()
616 // we're called from an exception handler so we can re-throw the exception
617 // to recover its type
624 catch ( std::exception
& e
)
626 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
627 typeid(e
).name(), e
.what());
632 what
= "unknown exception";
635 wxMessageOutputBest().Printf(
636 "*** Caught unhandled %s; terminating\n", what
638 #endif // __WXDEBUG__
641 // ----------------------------------------------------------------------------
642 // exceptions support
643 // ----------------------------------------------------------------------------
645 bool wxAppConsoleBase::OnExceptionInMainLoop()
649 // some compilers are too stupid to know that we never return after throw
650 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
655 #endif // wxUSE_EXCEPTIONS
657 // ----------------------------------------------------------------------------
659 // ----------------------------------------------------------------------------
661 #if wxUSE_CMDLINE_PARSER
663 #define OPTION_VERBOSE "verbose"
665 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
667 // the standard command line options
668 static const wxCmdLineEntryDesc cmdLineDesc
[] =
674 gettext_noop("show this help message"),
676 wxCMD_LINE_OPTION_HELP
684 gettext_noop("generate verbose log messages"),
694 parser
.SetDesc(cmdLineDesc
);
697 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
700 if ( parser
.Found(OPTION_VERBOSE
) )
702 wxLog::SetVerbose(true);
711 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
718 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
725 #endif // wxUSE_CMDLINE_PARSER
727 // ----------------------------------------------------------------------------
729 // ----------------------------------------------------------------------------
732 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
733 const char *componentName
)
735 #if 0 // can't use wxLogTrace, not up and running yet
736 printf("checking build options object '%s' (ptr %p) in '%s'\n",
737 optionsSignature
, optionsSignature
, componentName
);
740 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
742 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
743 wxString prog
= wxString::FromAscii(optionsSignature
);
744 wxString progName
= wxString::FromAscii(componentName
);
747 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
748 lib
.c_str(), progName
.c_str(), prog
.c_str());
750 wxLogFatalError(msg
.c_str());
752 // normally wxLogFatalError doesn't return
759 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
766 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
768 // this function is still present even in debug level 0 build for ABI
769 // compatibility reasons but is never called there and so can simply do
776 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
779 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
784 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
787 // ============================================================================
788 // other classes implementations
789 // ============================================================================
791 // ----------------------------------------------------------------------------
792 // wxConsoleAppTraitsBase
793 // ----------------------------------------------------------------------------
797 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
799 return new wxLogStderr
;
804 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
806 return new wxMessageOutputStderr
;
811 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
813 return (wxFontMapper
*)new wxFontMapperBase
;
816 #endif // wxUSE_FONTMAP
818 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
820 // console applications don't use renderers
824 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
826 return wxAppTraitsBase::ShowAssertDialog(msg
);
829 bool wxConsoleAppTraitsBase::HasStderr()
831 // console applications always have stderr, even under Mac/Windows
835 // ----------------------------------------------------------------------------
837 // ----------------------------------------------------------------------------
840 void wxAppTraitsBase::SetLocale()
842 // We want to use the user locale by default in GUI applications in order
843 // to show the numbers, dates &c in the familiar format -- and also accept
844 // this format on input (especially important for decimal comma/dot).
845 wxSetlocale(LC_ALL
, "");
848 // At least in some environments, e.g. MinGW-64, if the global C++ locale
849 // is different from the global C locale, all stream operations temporarily
850 // change the locale resulting in a huge slowdown (3 times slower in some
851 // real-life applications), so change the C++ locale to match.
852 std::locale::global(std::locale(""));
855 wxUpdateLocaleIsUtf8();
860 void wxMutexGuiEnterImpl();
861 void wxMutexGuiLeaveImpl();
863 void wxAppTraitsBase::MutexGuiEnter()
865 wxMutexGuiEnterImpl();
868 void wxAppTraitsBase::MutexGuiLeave()
870 wxMutexGuiLeaveImpl();
873 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
875 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
877 traits
->MutexGuiEnter();
880 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
882 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
884 traits
->MutexGuiLeave();
886 #endif // wxUSE_THREADS
888 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
893 #if wxUSE_STACKWALKER
894 const wxString stackTrace
= GetAssertStackTrace();
895 if ( !stackTrace
.empty() )
897 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
899 wxMessageOutputDebug().Output(msg
);
901 #endif // wxUSE_STACKWALKER
903 return DoShowAssertDialog(msgOriginal
+ msg
);
904 #else // !wxDEBUG_LEVEL
905 wxUnusedVar(msgOriginal
);
908 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
911 #if wxUSE_STACKWALKER
912 wxString
wxAppTraitsBase::GetAssertStackTrace()
916 #if !defined(__WINDOWS__)
917 // on Unix stack frame generation may take some time, depending on the
918 // size of the executable mainly... warn the user that we are working
919 wxFprintf(stderr
, "Collecting stack trace information, please wait...");
921 #endif // !__WINDOWS__
926 class StackDump
: public wxStackWalker
931 const wxString
& GetStackTrace() const { return m_stackTrace
; }
934 virtual void OnStackFrame(const wxStackFrame
& frame
)
936 m_stackTrace
<< wxString::Format
939 wx_truncate_cast(int, frame
.GetLevel())
942 wxString name
= frame
.GetName();
945 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
949 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
952 if ( frame
.HasSourceLocation() )
954 m_stackTrace
<< wxT('\t')
955 << frame
.GetFileName()
960 m_stackTrace
<< wxT('\n');
964 wxString m_stackTrace
;
967 // don't show more than maxLines or we could get a dialog too tall to be
968 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
969 // characters it is still only 300 pixels...
970 static const int maxLines
= 20;
973 dump
.Walk(8, maxLines
); // 8 is chosen to hide all OnAssert() calls
974 stackTrace
= dump
.GetStackTrace();
976 const int count
= stackTrace
.Freq(wxT('\n'));
977 for ( int i
= 0; i
< count
- maxLines
; i
++ )
978 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
981 #else // !wxDEBUG_LEVEL
982 // this function is still present for ABI-compatibility even in debug level
983 // 0 build but is not used there and so can simply do nothing
985 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
987 #endif // wxUSE_STACKWALKER
990 // ============================================================================
991 // global functions implementation
992 // ============================================================================
1002 // what else can we do?
1011 wxTheApp
->WakeUpIdle();
1013 //else: do nothing, what can we do?
1016 // wxASSERT() helper
1017 bool wxAssertIsEqual(int x
, int y
)
1033 // break into the debugger
1036 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1038 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1040 #elif defined(__UNIX__)
1047 // default assert handler
1049 wxDefaultAssertHandler(const wxString
& file
,
1051 const wxString
& func
,
1052 const wxString
& cond
,
1053 const wxString
& msg
)
1055 // If this option is set, we should abort immediately when assert happens.
1056 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1060 static int s_bInAssert
= 0;
1062 wxRecursionGuard
guard(s_bInAssert
);
1063 if ( guard
.IsInside() )
1065 // can't use assert here to avoid infinite loops, so just trap
1073 // by default, show the assert dialog box -- we can't customize this
1075 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1079 // let the app process it as it wants
1080 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1081 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1082 cond
.c_str(), msg
.c_str());
1086 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1088 void wxSetDefaultAssertHandler()
1090 wxTheAssertHandler
= wxDefaultAssertHandler
;
1093 void wxOnAssert(const wxString
& file
,
1095 const wxString
& func
,
1096 const wxString
& cond
,
1097 const wxString
& msg
)
1099 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1102 void wxOnAssert(const wxString
& file
,
1104 const wxString
& func
,
1105 const wxString
& cond
)
1107 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1110 void wxOnAssert(const wxChar
*file
,
1116 // this is the backwards-compatible version (unless we don't use Unicode)
1117 // so it could be called directly from the user code and this might happen
1118 // even when wxTheAssertHandler is NULL
1120 if ( wxTheAssertHandler
)
1121 #endif // wxUSE_UNICODE
1122 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1125 void wxOnAssert(const char *file
,
1129 const wxString
& msg
)
1131 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1134 void wxOnAssert(const char *file
,
1138 const wxCStrData
& msg
)
1140 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1144 void wxOnAssert(const char *file
,
1149 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1152 void wxOnAssert(const char *file
,
1158 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1161 void wxOnAssert(const char *file
,
1167 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1169 #endif // wxUSE_UNICODE
1171 #endif // wxDEBUG_LEVEL
1173 // ============================================================================
1174 // private functions implementation
1175 // ============================================================================
1179 static void LINKAGEMODE
SetTraceMasks()
1183 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1185 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1186 while ( tkn
.HasMoreTokens() )
1187 wxLog::AddTraceMask(tkn
.GetNextToken());
1192 #endif // __WXDEBUG__
1197 bool DoShowAssertDialog(const wxString
& msg
)
1199 // under Windows we can show the dialog even in the console mode
1200 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1201 wxString
msgDlg(msg
);
1203 // this message is intentionally not translated -- it is for developers
1204 // only -- and the less code we use here, less is the danger of recursively
1205 // asserting and dying
1206 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1207 wxT("You can also choose [Cancel] to suppress ")
1208 wxT("further warnings.");
1210 switch ( ::MessageBox(NULL
, msgDlg
.t_str(), wxT("wxWidgets Debug Alert"),
1211 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1221 //case IDNO: nothing to do
1223 #else // !__WINDOWS__
1225 #endif // __WINDOWS__/!__WINDOWS__
1227 // continue with the asserts by default
1231 // show the standard assert dialog
1233 void ShowAssertDialog(const wxString
& file
,
1235 const wxString
& func
,
1236 const wxString
& cond
,
1237 const wxString
& msgUser
,
1238 wxAppTraits
*traits
)
1240 // this variable can be set to true to suppress "assert failure" messages
1241 static bool s_bNoAsserts
= false;
1246 // make life easier for people using VC++ IDE by using this format: like
1247 // this, clicking on the message will take us immediately to the place of
1248 // the failed assert
1249 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1251 // add the function name, if any
1252 if ( !func
.empty() )
1253 msg
<< wxT(" in ") << func
<< wxT("()");
1255 // and the message itself
1256 if ( !msgUser
.empty() )
1258 msg
<< wxT(": ") << msgUser
;
1260 else // no message given
1266 // if we are not in the main thread, output the assert directly and trap
1267 // since dialogs cannot be displayed
1268 if ( !wxThread::IsMain() )
1270 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1272 #endif // wxUSE_THREADS
1274 // log the assert in any case
1275 wxMessageOutputDebug().Output(msg
);
1277 if ( !s_bNoAsserts
)
1281 // delegate showing assert dialog (if possible) to that class
1282 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1284 else // no traits object
1286 // fall back to the function of last resort
1287 s_bNoAsserts
= DoShowAssertDialog(msg
);
1292 #endif // wxDEBUG_LEVEL