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
))
180 wxString
wxAppConsoleBase::GetAppName() const
182 wxString name
= m_appName
;
187 // the application name is, by default, the name of its executable file
188 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
194 wxString
wxAppConsoleBase::GetAppDisplayName() const
196 // use the explicitly provided display name, if any
197 if ( !m_appDisplayName
.empty() )
198 return m_appDisplayName
;
200 // if the application name was explicitly set, use it as is as capitalizing
201 // it won't always produce good results
202 if ( !m_appName
.empty() )
205 // if neither is set, use the capitalized version of the program file as
206 // it's the most reasonable default
207 return GetAppName().Capitalize();
210 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
212 return GetTraits()->CreateEventLoop();
215 void wxAppConsoleBase::CleanUp()
217 wxDELETE(m_mainLoop
);
220 // ----------------------------------------------------------------------------
222 // ----------------------------------------------------------------------------
224 bool wxAppConsoleBase::OnInit()
226 #if wxUSE_CMDLINE_PARSER
227 wxCmdLineParser
parser(argc
, argv
);
229 OnInitCmdLine(parser
);
232 switch ( parser
.Parse(false /* don't show usage */) )
235 cont
= OnCmdLineHelp(parser
);
239 cont
= OnCmdLineParsed(parser
);
243 cont
= OnCmdLineError(parser
);
249 #endif // wxUSE_CMDLINE_PARSER
254 int wxAppConsoleBase::OnRun()
259 void wxAppConsoleBase::OnLaunched()
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
;
312 wxAppTraits
& wxAppConsoleBase::GetValidTraits()
314 static wxConsoleAppTraits s_traitsConsole
;
315 wxAppTraits
* const traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
317 return traits
? *traits
: s_traitsConsole
;
320 // ----------------------------------------------------------------------------
321 // wxEventLoop redirection
322 // ----------------------------------------------------------------------------
324 int wxAppConsoleBase::MainLoop()
326 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
328 #if defined(__WXOSX__) && wxOSX_USE_COCOA_OR_IPHONE
329 // OnLaunched called from native app controller
332 wxTheApp
->OnLaunched();
335 return m_mainLoop
? m_mainLoop
->Run() : -1;
338 void wxAppConsoleBase::ExitMainLoop()
340 // we should exit from the main event loop, not just any currently active
341 // (e.g. modal dialog) event loop
342 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
348 bool wxAppConsoleBase::Pending()
350 // use the currently active message loop here, not m_mainLoop, because if
351 // we're showing a modal dialog (with its own event loop) currently the
352 // main event loop is not running anyhow
353 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
355 return loop
&& loop
->Pending();
358 bool wxAppConsoleBase::Dispatch()
360 // see comment in Pending()
361 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
363 return loop
&& loop
->Dispatch();
366 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
368 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
370 return loop
->Yield(onlyIfNeeded
);
372 wxScopedPtr
<wxEventLoopBase
> tmpLoop(CreateMainLoop());
373 return tmpLoop
->Yield(onlyIfNeeded
);
376 void wxAppConsoleBase::WakeUpIdle()
378 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
384 bool wxAppConsoleBase::ProcessIdle()
386 // synthesize an idle event and check if more of them are needed
388 event
.SetEventObject(this);
392 // flush the logged messages if any (do this after processing the events
393 // which could have logged new messages)
394 wxLog::FlushActive();
397 // Garbage collect all objects previously scheduled for destruction.
398 DeletePendingObjects();
400 return event
.MoreRequested();
403 bool wxAppConsoleBase::UsesEventLoop() const
405 // in console applications we don't know whether we're going to have an
406 // event loop so assume we won't -- unless we already have one running
407 return wxEventLoopBase::GetActive() != NULL
;
410 // ----------------------------------------------------------------------------
412 // ----------------------------------------------------------------------------
415 bool wxAppConsoleBase::IsMainLoopRunning()
417 const wxAppConsole
* const app
= GetInstance();
419 return app
&& app
->m_mainLoop
!= NULL
;
422 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
424 // process the events normally by default
428 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
430 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
432 // move the handler from the list of handlers with processable pending events
433 // to the list of handlers with pending events which needs to be processed later
434 m_handlersWithPendingEvents
.Remove(toDelay
);
436 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
437 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
439 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
442 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
444 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
446 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
448 m_handlersWithPendingEvents
.Remove(toRemove
);
450 // check that the handler was present only once in the list
451 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
452 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
454 //else: it wasn't in this list at all, it's ok
456 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
458 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
460 // check that the handler was present only once in the list
461 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
462 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
464 //else: it wasn't in this list at all, it's ok
466 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
469 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
471 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
473 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
474 m_handlersWithPendingEvents
.Add(toAppend
);
476 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
479 bool wxAppConsoleBase::HasPendingEvents() const
481 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
483 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
485 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
490 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
492 m_bDoPendingEventProcessing
= false;
495 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
497 m_bDoPendingEventProcessing
= true;
500 void wxAppConsoleBase::ProcessPendingEvents()
502 if ( m_bDoPendingEventProcessing
)
504 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
506 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
507 "this helper list should be empty" );
509 // iterate until the list becomes empty: the handlers remove themselves
510 // from it when they don't have any more pending events
511 while (!m_handlersWithPendingEvents
.IsEmpty())
513 // In ProcessPendingEvents(), new handlers might be added
514 // and we can safely leave the critical section here.
515 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
517 // NOTE: we always call ProcessPendingEvents() on the first event handler
518 // with pending events because handlers auto-remove themselves
519 // from this list (see RemovePendingEventHandler) if they have no
520 // more pending events.
521 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
523 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
526 // now the wxHandlersWithPendingEvents is surely empty; however some event
527 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
528 // because of a selective wxYield call in progress.
529 // Now we need to move them back to wxHandlersWithPendingEvents so the next
530 // call to this function has the chance of processing them:
531 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
533 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
534 m_handlersWithPendingDelayedEvents
.Clear();
537 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
541 void wxAppConsoleBase::DeletePendingEvents()
543 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
545 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
546 "this helper list should be empty" );
548 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
549 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
551 m_handlersWithPendingEvents
.Clear();
553 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
556 // ----------------------------------------------------------------------------
557 // delayed objects destruction
558 // ----------------------------------------------------------------------------
560 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
562 return wxPendingDelete
.Member(object
);
565 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
567 if ( !UsesEventLoop() )
569 // we won't be able to delete it later so do it right now
573 //else: we either already have or will soon start an event loop
575 if ( !wxPendingDelete
.Member(object
) )
576 wxPendingDelete
.Append(object
);
579 void wxAppConsoleBase::DeletePendingObjects()
581 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
584 wxObject
*obj
= node
->GetData();
586 // remove it from the list first so that if we get back here somehow
587 // during the object deletion (e.g. wxYield called from its dtor) we
588 // wouldn't try to delete it the second time
589 if ( wxPendingDelete
.Member(obj
) )
590 wxPendingDelete
.Erase(node
);
594 // Deleting one object may have deleted other pending
595 // objects, so start from beginning of list again.
596 node
= wxPendingDelete
.GetFirst();
600 // ----------------------------------------------------------------------------
601 // exception handling
602 // ----------------------------------------------------------------------------
607 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
608 wxEventFunction func
,
609 wxEvent
& event
) const
611 // by default, simply call the handler
612 (handler
->*func
)(event
);
615 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
616 wxEventFunctor
& functor
,
617 wxEvent
& event
) const
619 // If the functor holds a method then, for backward compatibility, call
621 wxEventFunction eventFunction
= functor
.GetEvtMethod();
624 HandleEvent(handler
, eventFunction
, event
);
626 functor(handler
, event
);
629 void wxAppConsoleBase::OnUnhandledException()
632 // we're called from an exception handler so we can re-throw the exception
633 // to recover its type
640 catch ( std::exception
& e
)
642 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
643 typeid(e
).name(), e
.what());
648 what
= "unknown exception";
651 wxMessageOutputBest().Printf(
652 "*** Caught unhandled %s; terminating\n", what
654 #endif // __WXDEBUG__
657 // ----------------------------------------------------------------------------
658 // exceptions support
659 // ----------------------------------------------------------------------------
661 bool wxAppConsoleBase::OnExceptionInMainLoop()
665 // some compilers are too stupid to know that we never return after throw
666 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
671 #endif // wxUSE_EXCEPTIONS
673 // ----------------------------------------------------------------------------
675 // ----------------------------------------------------------------------------
677 #if wxUSE_CMDLINE_PARSER
679 #define OPTION_VERBOSE "verbose"
681 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
683 // the standard command line options
684 static const wxCmdLineEntryDesc cmdLineDesc
[] =
690 gettext_noop("show this help message"),
692 wxCMD_LINE_OPTION_HELP
700 gettext_noop("generate verbose log messages"),
710 parser
.SetDesc(cmdLineDesc
);
713 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
716 if ( parser
.Found(OPTION_VERBOSE
) )
718 wxLog::SetVerbose(true);
727 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
734 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
741 #endif // wxUSE_CMDLINE_PARSER
743 // ----------------------------------------------------------------------------
745 // ----------------------------------------------------------------------------
748 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
749 const char *componentName
)
751 #if 0 // can't use wxLogTrace, not up and running yet
752 printf("checking build options object '%s' (ptr %p) in '%s'\n",
753 optionsSignature
, optionsSignature
, componentName
);
756 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
758 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
759 wxString prog
= wxString::FromAscii(optionsSignature
);
760 wxString progName
= wxString::FromAscii(componentName
);
763 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
764 lib
.c_str(), progName
.c_str(), prog
.c_str());
766 wxLogFatalError(msg
.c_str());
768 // normally wxLogFatalError doesn't return
775 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
782 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
784 // this function is still present even in debug level 0 build for ABI
785 // compatibility reasons but is never called there and so can simply do
792 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
795 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
800 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
803 // ----------------------------------------------------------------------------
804 // Miscellaneous other methods
805 // ----------------------------------------------------------------------------
807 void wxAppConsoleBase::SetCLocale()
809 // We want to use the user locale by default in GUI applications in order
810 // to show the numbers, dates &c in the familiar format -- and also accept
811 // this format on input (especially important for decimal comma/dot).
812 wxSetlocale(LC_ALL
, "");
815 // ============================================================================
816 // other classes implementations
817 // ============================================================================
819 // ----------------------------------------------------------------------------
820 // wxConsoleAppTraitsBase
821 // ----------------------------------------------------------------------------
825 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
827 return new wxLogStderr
;
832 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
834 return new wxMessageOutputStderr
;
839 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
841 return (wxFontMapper
*)new wxFontMapperBase
;
844 #endif // wxUSE_FONTMAP
846 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
848 // console applications don't use renderers
852 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
854 return wxAppTraitsBase::ShowAssertDialog(msg
);
857 bool wxConsoleAppTraitsBase::HasStderr()
859 // console applications always have stderr, even under Mac/Windows
863 // ----------------------------------------------------------------------------
865 // ----------------------------------------------------------------------------
868 void wxMutexGuiEnterImpl();
869 void wxMutexGuiLeaveImpl();
871 void wxAppTraitsBase::MutexGuiEnter()
873 wxMutexGuiEnterImpl();
876 void wxAppTraitsBase::MutexGuiLeave()
878 wxMutexGuiLeaveImpl();
881 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
883 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
885 traits
->MutexGuiEnter();
888 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
890 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
892 traits
->MutexGuiLeave();
894 #endif // wxUSE_THREADS
896 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
901 #if wxUSE_STACKWALKER
902 const wxString stackTrace
= GetAssertStackTrace();
903 if ( !stackTrace
.empty() )
905 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
907 wxMessageOutputDebug().Output(msg
);
909 #endif // wxUSE_STACKWALKER
911 return DoShowAssertDialog(msgOriginal
+ msg
);
912 #else // !wxDEBUG_LEVEL
913 wxUnusedVar(msgOriginal
);
916 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
919 #if wxUSE_STACKWALKER
920 wxString
wxAppTraitsBase::GetAssertStackTrace()
924 #if !defined(__WINDOWS__)
925 // on Unix stack frame generation may take some time, depending on the
926 // size of the executable mainly... warn the user that we are working
927 wxFprintf(stderr
, "Collecting stack trace information, please wait...");
929 #endif // !__WINDOWS__
934 class StackDump
: public wxStackWalker
939 const wxString
& GetStackTrace() const { return m_stackTrace
; }
942 virtual void OnStackFrame(const wxStackFrame
& frame
)
944 m_stackTrace
<< wxString::Format
947 wx_truncate_cast(int, frame
.GetLevel())
950 wxString name
= frame
.GetName();
953 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
957 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
960 if ( frame
.HasSourceLocation() )
962 m_stackTrace
<< wxT('\t')
963 << frame
.GetFileName()
968 m_stackTrace
<< wxT('\n');
972 wxString m_stackTrace
;
975 // don't show more than maxLines or we could get a dialog too tall to be
976 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
977 // characters it is still only 300 pixels...
978 static const int maxLines
= 20;
981 dump
.Walk(8, maxLines
); // 8 is chosen to hide all OnAssert() calls
982 stackTrace
= dump
.GetStackTrace();
984 const int count
= stackTrace
.Freq(wxT('\n'));
985 for ( int i
= 0; i
< count
- maxLines
; i
++ )
986 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
989 #else // !wxDEBUG_LEVEL
990 // this function is still present for ABI-compatibility even in debug level
991 // 0 build but is not used there and so can simply do nothing
993 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
995 #endif // wxUSE_STACKWALKER
998 // ============================================================================
999 // global functions implementation
1000 // ============================================================================
1010 // what else can we do?
1019 wxTheApp
->WakeUpIdle();
1021 //else: do nothing, what can we do?
1024 // wxASSERT() helper
1025 bool wxAssertIsEqual(int x
, int y
)
1041 // break into the debugger
1046 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1048 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1050 #elif defined(__UNIX__)
1057 #endif // wxTrap already defined as a macro
1059 // default assert handler
1061 wxDefaultAssertHandler(const wxString
& file
,
1063 const wxString
& func
,
1064 const wxString
& cond
,
1065 const wxString
& msg
)
1067 // If this option is set, we should abort immediately when assert happens.
1068 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1072 static int s_bInAssert
= 0;
1074 wxRecursionGuard
guard(s_bInAssert
);
1075 if ( guard
.IsInside() )
1077 // can't use assert here to avoid infinite loops, so just trap
1085 // by default, show the assert dialog box -- we can't customize this
1087 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1091 // let the app process it as it wants
1092 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1093 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1094 cond
.c_str(), msg
.c_str());
1098 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1100 void wxSetDefaultAssertHandler()
1102 wxTheAssertHandler
= wxDefaultAssertHandler
;
1105 void wxOnAssert(const wxString
& file
,
1107 const wxString
& func
,
1108 const wxString
& cond
,
1109 const wxString
& msg
)
1111 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1114 void wxOnAssert(const wxString
& file
,
1116 const wxString
& func
,
1117 const wxString
& cond
)
1119 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1122 void wxOnAssert(const wxChar
*file
,
1128 // this is the backwards-compatible version (unless we don't use Unicode)
1129 // so it could be called directly from the user code and this might happen
1130 // even when wxTheAssertHandler is NULL
1132 if ( wxTheAssertHandler
)
1133 #endif // wxUSE_UNICODE
1134 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1137 void wxOnAssert(const char *file
,
1141 const wxString
& msg
)
1143 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1146 void wxOnAssert(const char *file
,
1150 const wxCStrData
& msg
)
1152 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1156 void wxOnAssert(const char *file
,
1161 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1164 void wxOnAssert(const char *file
,
1170 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1173 void wxOnAssert(const char *file
,
1179 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1181 #endif // wxUSE_UNICODE
1183 #endif // wxDEBUG_LEVEL
1185 // ============================================================================
1186 // private functions implementation
1187 // ============================================================================
1191 static void LINKAGEMODE
SetTraceMasks()
1195 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1197 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1198 while ( tkn
.HasMoreTokens() )
1199 wxLog::AddTraceMask(tkn
.GetNextToken());
1204 #endif // __WXDEBUG__
1208 bool wxTrapInAssert
= false;
1211 bool DoShowAssertDialog(const wxString
& msg
)
1213 // under Windows we can show the dialog even in the console mode
1214 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1215 wxString
msgDlg(msg
);
1217 // this message is intentionally not translated -- it is for developers
1218 // only -- and the less code we use here, less is the danger of recursively
1219 // asserting and dying
1220 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1221 wxT("You can also choose [Cancel] to suppress ")
1222 wxT("further warnings.");
1224 switch ( ::MessageBox(NULL
, msgDlg
.t_str(), wxT("wxWidgets Debug Alert"),
1225 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1228 // If we called wxTrap() directly from here, the programmer would
1229 // see this function and a few more calls between his own code and
1230 // it in the stack trace which would be perfectly useless and often
1231 // confusing. So instead just set the flag here and let the macros
1232 // defined in wx/debug.h call wxTrap() themselves, this ensures
1233 // that the debugger will show the line in the user code containing
1234 // the failing assert.
1235 wxTrapInAssert
= true;
1242 //case IDNO: nothing to do
1244 #else // !__WINDOWS__
1246 #endif // __WINDOWS__/!__WINDOWS__
1248 // continue with the asserts by default
1252 // show the standard assert dialog
1254 void ShowAssertDialog(const wxString
& file
,
1256 const wxString
& func
,
1257 const wxString
& cond
,
1258 const wxString
& msgUser
,
1259 wxAppTraits
*traits
)
1261 // this variable can be set to true to suppress "assert failure" messages
1262 static bool s_bNoAsserts
= false;
1267 // make life easier for people using VC++ IDE by using this format: like
1268 // this, clicking on the message will take us immediately to the place of
1269 // the failed assert
1270 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1272 // add the function name, if any
1273 if ( !func
.empty() )
1274 msg
<< wxT(" in ") << func
<< wxT("()");
1276 // and the message itself
1277 if ( !msgUser
.empty() )
1279 msg
<< wxT(": ") << msgUser
;
1281 else // no message given
1287 // if we are not in the main thread, output the assert directly and trap
1288 // since dialogs cannot be displayed
1289 if ( !wxThread::IsMain() )
1291 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1293 #endif // wxUSE_THREADS
1295 // log the assert in any case
1296 wxMessageOutputDebug().Output(msg
);
1298 if ( !s_bNoAsserts
)
1302 // delegate showing assert dialog (if possible) to that class
1303 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1305 else // no traits object
1307 // fall back to the function of last resort
1308 s_bNoAsserts
= DoShowAssertDialog(msg
);
1313 #endif // wxDEBUG_LEVEL