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)
7 // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
28 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
35 #include "wx/wxcrtvararg.h"
38 #include "wx/apptrait.h"
39 #include "wx/cmdline.h"
40 #include "wx/confbase.h"
41 #include "wx/evtloop.h"
42 #include "wx/filename.h"
43 #include "wx/msgout.h"
44 #include "wx/scopedptr.h"
45 #include "wx/sysopt.h"
46 #include "wx/tokenzr.h"
47 #include "wx/thread.h"
59 #if !defined(__WINDOWS__) || defined(__WXMICROWIN__)
60 #include <signal.h> // for SIGTRAP used by wxTrap()
66 #include "wx/fontmap.h"
67 #endif // wxUSE_FONTMAP
71 #include "wx/stackwalk.h"
73 #include "wx/msw/debughlp.h"
75 #endif // wxUSE_STACKWALKER
77 #include "wx/recguard.h"
78 #endif // wxDEBUG_LEVEL
80 // wxABI_VERSION can be defined when compiling applications but it should be
81 // left undefined when compiling the library itself, it is then set to its
82 // default value in version.h
83 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
84 #error "wxABI_VERSION should not be defined when compiling the library"
87 // ----------------------------------------------------------------------------
88 // private functions prototypes
89 // ----------------------------------------------------------------------------
92 // really just show the assert dialog
93 static bool DoShowAssertDialog(const wxString
& msg
);
95 // prepare for showing the assert dialog, use the given traits or
96 // DoShowAssertDialog() as last fallback to really show it
98 void ShowAssertDialog(const wxString
& file
,
100 const wxString
& func
,
101 const wxString
& cond
,
103 wxAppTraits
*traits
= NULL
);
104 #endif // wxDEBUG_LEVEL
107 // turn on the trace masks specified in the env variable WXTRACE
108 static void LINKAGEMODE
SetTraceMasks();
109 #endif // __WXDEBUG__
111 // ----------------------------------------------------------------------------
113 // ----------------------------------------------------------------------------
115 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
117 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
119 wxSocketManager
*wxAppTraitsBase::ms_manager
= NULL
;
121 WXDLLIMPEXP_DATA_BASE(wxList
) wxPendingDelete
;
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 // this defines wxEventLoopPtr
128 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
130 // ============================================================================
131 // wxAppConsoleBase implementation
132 // ============================================================================
134 // ----------------------------------------------------------------------------
136 // ----------------------------------------------------------------------------
138 wxAppConsoleBase::wxAppConsoleBase()
142 m_bDoPendingEventProcessing
= true;
144 ms_appInstance
= static_cast<wxAppConsole
*>(this);
149 // In unicode mode the SetTraceMasks call can cause an apptraits to be
150 // created, but since we are still in the constructor the wrong kind will
151 // be created for GUI apps. Destroy it so it can be created again later.
156 wxEvtHandler::AddFilter(this);
159 wxAppConsoleBase::~wxAppConsoleBase()
161 wxEvtHandler::RemoveFilter(this);
163 // we're being destroyed and using this object from now on may not work or
164 // even crash so don't leave dangling pointers to it
165 ms_appInstance
= NULL
;
170 // ----------------------------------------------------------------------------
171 // initialization/cleanup
172 // ----------------------------------------------------------------------------
174 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc
), wxChar
**WXUNUSED(argv
))
179 wxString
wxAppConsoleBase::GetAppName() const
181 wxString name
= m_appName
;
186 // the application name is, by default, the name of its executable file
187 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
193 wxString
wxAppConsoleBase::GetAppDisplayName() const
195 // use the explicitly provided display name, if any
196 if ( !m_appDisplayName
.empty() )
197 return m_appDisplayName
;
199 // if the application name was explicitly set, use it as is as capitalizing
200 // it won't always produce good results
201 if ( !m_appName
.empty() )
204 // if neither is set, use the capitalized version of the program file as
205 // it's the most reasonable default
206 return GetAppName().Capitalize();
209 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
211 return GetTraits()->CreateEventLoop();
214 void wxAppConsoleBase::CleanUp()
216 wxDELETE(m_mainLoop
);
219 // ----------------------------------------------------------------------------
221 // ----------------------------------------------------------------------------
223 bool wxAppConsoleBase::OnInit()
225 #if wxUSE_CMDLINE_PARSER
226 wxCmdLineParser
parser(argc
, argv
);
228 OnInitCmdLine(parser
);
231 switch ( parser
.Parse(false /* don't show usage */) )
234 cont
= OnCmdLineHelp(parser
);
238 cont
= OnCmdLineParsed(parser
);
242 cont
= OnCmdLineError(parser
);
248 #endif // wxUSE_CMDLINE_PARSER
253 int wxAppConsoleBase::OnRun()
258 void wxAppConsoleBase::OnLaunched()
262 int wxAppConsoleBase::OnExit()
265 // delete the config object if any (don't use Get() here, but Set()
266 // because Get() could create a new config object)
267 delete wxConfigBase::Set(NULL
);
268 #endif // wxUSE_CONFIG
273 void wxAppConsoleBase::Exit()
275 if (m_mainLoop
!= NULL
)
281 // ----------------------------------------------------------------------------
283 // ----------------------------------------------------------------------------
285 wxAppTraits
*wxAppConsoleBase::CreateTraits()
287 return new wxConsoleAppTraits
;
290 wxAppTraits
*wxAppConsoleBase::GetTraits()
292 // FIXME-MT: protect this with a CS?
295 m_traits
= CreateTraits();
297 wxASSERT_MSG( m_traits
, wxT("wxApp::CreateTraits() failed?") );
304 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
306 wxAppConsole
* const app
= GetInstance();
307 return app
? app
->GetTraits() : NULL
;
311 wxAppTraits
& wxAppConsoleBase::GetValidTraits()
313 static wxConsoleAppTraits s_traitsConsole
;
314 wxAppTraits
* const traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
316 return traits
? *traits
: s_traitsConsole
;
319 // ----------------------------------------------------------------------------
320 // wxEventLoop redirection
321 // ----------------------------------------------------------------------------
323 int wxAppConsoleBase::MainLoop()
325 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
327 #if defined(__WXOSX__) && wxOSX_USE_COCOA_OR_IPHONE
328 // OnLaunched called from native app controller
331 wxTheApp
->OnLaunched();
334 return m_mainLoop
? m_mainLoop
->Run() : -1;
337 void wxAppConsoleBase::ExitMainLoop()
339 // we should exit from the main event loop, not just any currently active
340 // (e.g. modal dialog) event loop
341 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
347 bool wxAppConsoleBase::Pending()
349 // use the currently active message loop here, not m_mainLoop, because if
350 // we're showing a modal dialog (with its own event loop) currently the
351 // main event loop is not running anyhow
352 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
354 return loop
&& loop
->Pending();
357 bool wxAppConsoleBase::Dispatch()
359 // see comment in Pending()
360 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
362 return loop
&& loop
->Dispatch();
365 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
367 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
369 return loop
->Yield(onlyIfNeeded
);
371 wxScopedPtr
<wxEventLoopBase
> tmpLoop(CreateMainLoop());
372 return tmpLoop
->Yield(onlyIfNeeded
);
375 void wxAppConsoleBase::WakeUpIdle()
377 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
383 bool wxAppConsoleBase::ProcessIdle()
385 // synthesize an idle event and check if more of them are needed
387 event
.SetEventObject(this);
391 // flush the logged messages if any (do this after processing the events
392 // which could have logged new messages)
393 wxLog::FlushActive();
396 // Garbage collect all objects previously scheduled for destruction.
397 DeletePendingObjects();
399 return event
.MoreRequested();
402 bool wxAppConsoleBase::UsesEventLoop() const
404 // in console applications we don't know whether we're going to have an
405 // event loop so assume we won't -- unless we already have one running
406 return wxEventLoopBase::GetActive() != NULL
;
409 // ----------------------------------------------------------------------------
411 // ----------------------------------------------------------------------------
414 bool wxAppConsoleBase::IsMainLoopRunning()
416 const wxAppConsole
* const app
= GetInstance();
418 return app
&& app
->m_mainLoop
!= NULL
;
421 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
423 // process the events normally by default
427 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
429 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
431 // move the handler from the list of handlers with processable pending events
432 // to the list of handlers with pending events which needs to be processed later
433 m_handlersWithPendingEvents
.Remove(toDelay
);
435 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
436 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
438 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
441 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
443 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
445 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
447 m_handlersWithPendingEvents
.Remove(toRemove
);
449 // check that the handler was present only once in the list
450 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
451 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
453 //else: it wasn't in this list at all, it's ok
455 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
457 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
459 // check that the handler was present only once in the list
460 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
461 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
463 //else: it wasn't in this list at all, it's ok
465 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
468 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
470 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
472 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
473 m_handlersWithPendingEvents
.Add(toAppend
);
475 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
478 bool wxAppConsoleBase::HasPendingEvents() const
480 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
482 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
484 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
489 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
491 m_bDoPendingEventProcessing
= false;
494 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
496 m_bDoPendingEventProcessing
= true;
499 void wxAppConsoleBase::ProcessPendingEvents()
501 if ( m_bDoPendingEventProcessing
)
503 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
505 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
506 "this helper list should be empty" );
508 // iterate until the list becomes empty: the handlers remove themselves
509 // from it when they don't have any more pending events
510 while (!m_handlersWithPendingEvents
.IsEmpty())
512 // In ProcessPendingEvents(), new handlers might be added
513 // and we can safely leave the critical section here.
514 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
516 // NOTE: we always call ProcessPendingEvents() on the first event handler
517 // with pending events because handlers auto-remove themselves
518 // from this list (see RemovePendingEventHandler) if they have no
519 // more pending events.
520 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
522 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
525 // now the wxHandlersWithPendingEvents is surely empty; however some event
526 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
527 // because of a selective wxYield call in progress.
528 // Now we need to move them back to wxHandlersWithPendingEvents so the next
529 // call to this function has the chance of processing them:
530 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
532 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
533 m_handlersWithPendingDelayedEvents
.Clear();
536 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
540 void wxAppConsoleBase::DeletePendingEvents()
542 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
544 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
545 "this helper list should be empty" );
547 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
548 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
550 m_handlersWithPendingEvents
.Clear();
552 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
555 // ----------------------------------------------------------------------------
556 // delayed objects destruction
557 // ----------------------------------------------------------------------------
559 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
561 return wxPendingDelete
.Member(object
);
564 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
566 if ( !UsesEventLoop() )
568 // we won't be able to delete it later so do it right now
572 //else: we either already have or will soon start an event loop
574 if ( !wxPendingDelete
.Member(object
) )
575 wxPendingDelete
.Append(object
);
578 void wxAppConsoleBase::DeletePendingObjects()
580 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
583 wxObject
*obj
= node
->GetData();
585 // remove it from the list first so that if we get back here somehow
586 // during the object deletion (e.g. wxYield called from its dtor) we
587 // wouldn't try to delete it the second time
588 if ( wxPendingDelete
.Member(obj
) )
589 wxPendingDelete
.Erase(node
);
593 // Deleting one object may have deleted other pending
594 // objects, so start from beginning of list again.
595 node
= wxPendingDelete
.GetFirst();
599 // ----------------------------------------------------------------------------
600 // exception handling
601 // ----------------------------------------------------------------------------
606 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
607 wxEventFunction func
,
608 wxEvent
& event
) const
610 // by default, simply call the handler
611 (handler
->*func
)(event
);
614 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
615 wxEventFunctor
& functor
,
616 wxEvent
& event
) const
618 // If the functor holds a method then, for backward compatibility, call
620 wxEventFunction eventFunction
= functor
.GetEvtMethod();
623 HandleEvent(handler
, eventFunction
, event
);
625 functor(handler
, event
);
628 void wxAppConsoleBase::OnUnhandledException()
631 // we're called from an exception handler so we can re-throw the exception
632 // to recover its type
639 catch ( std::exception
& e
)
641 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
642 typeid(e
).name(), e
.what());
647 what
= "unknown exception";
650 wxMessageOutputBest().Printf(
651 "*** Caught unhandled %s; terminating\n", what
653 #endif // __WXDEBUG__
656 // ----------------------------------------------------------------------------
657 // exceptions support
658 // ----------------------------------------------------------------------------
660 bool wxAppConsoleBase::OnExceptionInMainLoop()
664 // some compilers are too stupid to know that we never return after throw
665 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
670 #endif // wxUSE_EXCEPTIONS
672 // ----------------------------------------------------------------------------
674 // ----------------------------------------------------------------------------
676 #if wxUSE_CMDLINE_PARSER
678 #define OPTION_VERBOSE "verbose"
680 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
682 // the standard command line options
683 static const wxCmdLineEntryDesc cmdLineDesc
[] =
689 gettext_noop("show this help message"),
691 wxCMD_LINE_OPTION_HELP
699 gettext_noop("generate verbose log messages"),
709 parser
.SetDesc(cmdLineDesc
);
712 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
715 if ( parser
.Found(OPTION_VERBOSE
) )
717 wxLog::SetVerbose(true);
726 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
733 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
740 #endif // wxUSE_CMDLINE_PARSER
742 // ----------------------------------------------------------------------------
744 // ----------------------------------------------------------------------------
747 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
748 const char *componentName
)
750 #if 0 // can't use wxLogTrace, not up and running yet
751 printf("checking build options object '%s' (ptr %p) in '%s'\n",
752 optionsSignature
, optionsSignature
, componentName
);
755 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
757 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
758 wxString prog
= wxString::FromAscii(optionsSignature
);
759 wxString progName
= wxString::FromAscii(componentName
);
762 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
763 lib
.c_str(), progName
.c_str(), prog
.c_str());
765 wxLogFatalError(msg
.c_str());
767 // normally wxLogFatalError doesn't return
774 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
781 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
783 // this function is still present even in debug level 0 build for ABI
784 // compatibility reasons but is never called there and so can simply do
791 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
794 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
799 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
802 // ----------------------------------------------------------------------------
803 // Miscellaneous other methods
804 // ----------------------------------------------------------------------------
806 void wxAppConsoleBase::SetCLocale()
808 // We want to use the user locale by default in GUI applications in order
809 // to show the numbers, dates &c in the familiar format -- and also accept
810 // this format on input (especially important for decimal comma/dot).
811 wxSetlocale(LC_ALL
, "");
814 // ============================================================================
815 // other classes implementations
816 // ============================================================================
818 // ----------------------------------------------------------------------------
819 // wxConsoleAppTraitsBase
820 // ----------------------------------------------------------------------------
824 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
826 return new wxLogStderr
;
831 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
833 return new wxMessageOutputStderr
;
838 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
840 return (wxFontMapper
*)new wxFontMapperBase
;
843 #endif // wxUSE_FONTMAP
845 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
847 // console applications don't use renderers
851 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
853 return wxAppTraitsBase::ShowAssertDialog(msg
);
856 bool wxConsoleAppTraitsBase::HasStderr()
858 // console applications always have stderr, even under Mac/Windows
862 // ----------------------------------------------------------------------------
864 // ----------------------------------------------------------------------------
867 void wxMutexGuiEnterImpl();
868 void wxMutexGuiLeaveImpl();
870 void wxAppTraitsBase::MutexGuiEnter()
872 wxMutexGuiEnterImpl();
875 void wxAppTraitsBase::MutexGuiLeave()
877 wxMutexGuiLeaveImpl();
880 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
882 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
884 traits
->MutexGuiEnter();
887 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
889 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
891 traits
->MutexGuiLeave();
893 #endif // wxUSE_THREADS
895 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
900 #if wxUSE_STACKWALKER
901 const wxString stackTrace
= GetAssertStackTrace();
902 if ( !stackTrace
.empty() )
904 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
906 wxMessageOutputDebug().Output(msg
);
908 #endif // wxUSE_STACKWALKER
910 return DoShowAssertDialog(msgOriginal
+ msg
);
911 #else // !wxDEBUG_LEVEL
912 wxUnusedVar(msgOriginal
);
915 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
918 #if wxUSE_STACKWALKER
919 wxString
wxAppTraitsBase::GetAssertStackTrace()
923 #if !defined(__WINDOWS__)
924 // on Unix stack frame generation may take some time, depending on the
925 // size of the executable mainly... warn the user that we are working
926 wxFprintf(stderr
, "Collecting stack trace information, please wait...");
928 #endif // !__WINDOWS__
933 class StackDump
: public wxStackWalker
938 const wxString
& GetStackTrace() const { return m_stackTrace
; }
941 virtual void OnStackFrame(const wxStackFrame
& frame
)
943 m_stackTrace
<< wxString::Format
946 wx_truncate_cast(int, frame
.GetLevel())
949 wxString name
= frame
.GetName();
952 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
956 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
959 if ( frame
.HasSourceLocation() )
961 m_stackTrace
<< wxT('\t')
962 << frame
.GetFileName()
967 m_stackTrace
<< wxT('\n');
971 wxString m_stackTrace
;
974 // don't show more than maxLines or we could get a dialog too tall to be
975 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
976 // characters it is still only 300 pixels...
977 static const int maxLines
= 20;
980 dump
.Walk(8, maxLines
); // 8 is chosen to hide all OnAssert() calls
981 stackTrace
= dump
.GetStackTrace();
983 const int count
= stackTrace
.Freq(wxT('\n'));
984 for ( int i
= 0; i
< count
- maxLines
; i
++ )
985 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
988 #else // !wxDEBUG_LEVEL
989 // this function is still present for ABI-compatibility even in debug level
990 // 0 build but is not used there and so can simply do nothing
992 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
994 #endif // wxUSE_STACKWALKER
997 // ============================================================================
998 // global functions implementation
999 // ============================================================================
1009 // what else can we do?
1018 wxTheApp
->WakeUpIdle();
1020 //else: do nothing, what can we do?
1023 // wxASSERT() helper
1024 bool wxAssertIsEqual(int x
, int y
)
1040 // break into the debugger
1045 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1047 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1049 #elif defined(__UNIX__)
1056 #endif // wxTrap already defined as a macro
1058 // default assert handler
1060 wxDefaultAssertHandler(const wxString
& file
,
1062 const wxString
& func
,
1063 const wxString
& cond
,
1064 const wxString
& msg
)
1066 // If this option is set, we should abort immediately when assert happens.
1067 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1071 static int s_bInAssert
= 0;
1073 wxRecursionGuard
guard(s_bInAssert
);
1074 if ( guard
.IsInside() )
1076 // can't use assert here to avoid infinite loops, so just trap
1084 // by default, show the assert dialog box -- we can't customize this
1086 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1090 // let the app process it as it wants
1091 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1092 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1093 cond
.c_str(), msg
.c_str());
1097 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1099 void wxSetDefaultAssertHandler()
1101 wxTheAssertHandler
= wxDefaultAssertHandler
;
1104 void wxOnAssert(const wxString
& file
,
1106 const wxString
& func
,
1107 const wxString
& cond
,
1108 const wxString
& msg
)
1110 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1113 void wxOnAssert(const wxString
& file
,
1115 const wxString
& func
,
1116 const wxString
& cond
)
1118 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1121 void wxOnAssert(const wxChar
*file
,
1127 // this is the backwards-compatible version (unless we don't use Unicode)
1128 // so it could be called directly from the user code and this might happen
1129 // even when wxTheAssertHandler is NULL
1131 if ( wxTheAssertHandler
)
1132 #endif // wxUSE_UNICODE
1133 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1136 void wxOnAssert(const char *file
,
1140 const wxString
& msg
)
1142 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1145 void wxOnAssert(const char *file
,
1149 const wxCStrData
& msg
)
1151 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1155 void wxOnAssert(const char *file
,
1160 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1163 void wxOnAssert(const char *file
,
1169 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1172 void wxOnAssert(const char *file
,
1178 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1180 #endif // wxUSE_UNICODE
1182 #endif // wxDEBUG_LEVEL
1184 // ============================================================================
1185 // private functions implementation
1186 // ============================================================================
1190 static void LINKAGEMODE
SetTraceMasks()
1194 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1196 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1197 while ( tkn
.HasMoreTokens() )
1198 wxLog::AddTraceMask(tkn
.GetNextToken());
1203 #endif // __WXDEBUG__
1207 bool wxTrapInAssert
= false;
1210 bool DoShowAssertDialog(const wxString
& msg
)
1212 // under Windows we can show the dialog even in the console mode
1213 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1214 wxString
msgDlg(msg
);
1216 // this message is intentionally not translated -- it is for developers
1217 // only -- and the less code we use here, less is the danger of recursively
1218 // asserting and dying
1219 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1220 wxT("You can also choose [Cancel] to suppress ")
1221 wxT("further warnings.");
1223 switch ( ::MessageBox(NULL
, msgDlg
.t_str(), wxT("wxWidgets Debug Alert"),
1224 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1227 // If we called wxTrap() directly from here, the programmer would
1228 // see this function and a few more calls between his own code and
1229 // it in the stack trace which would be perfectly useless and often
1230 // confusing. So instead just set the flag here and let the macros
1231 // defined in wx/debug.h call wxTrap() themselves, this ensures
1232 // that the debugger will show the line in the user code containing
1233 // the failing assert.
1234 wxTrapInAssert
= true;
1241 //case IDNO: nothing to do
1243 #else // !__WINDOWS__
1245 #endif // __WINDOWS__/!__WINDOWS__
1247 // continue with the asserts by default
1251 // show the standard assert dialog
1253 void ShowAssertDialog(const wxString
& file
,
1255 const wxString
& func
,
1256 const wxString
& cond
,
1257 const wxString
& msgUser
,
1258 wxAppTraits
*traits
)
1260 // this variable can be set to true to suppress "assert failure" messages
1261 static bool s_bNoAsserts
= false;
1266 // make life easier for people using VC++ IDE by using this format: like
1267 // this, clicking on the message will take us immediately to the place of
1268 // the failed assert
1269 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1271 // add the function name, if any
1272 if ( !func
.empty() )
1273 msg
<< wxT(" in ") << func
<< wxT("()");
1275 // and the message itself
1276 if ( !msgUser
.empty() )
1278 msg
<< wxT(": ") << msgUser
;
1280 else // no message given
1286 // if we are not in the main thread, output the assert directly and trap
1287 // since dialogs cannot be displayed
1288 if ( !wxThread::IsMain() )
1290 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1292 #endif // wxUSE_THREADS
1294 // log the assert in any case
1295 wxMessageOutputDebug().Output(msg
);
1297 if ( !s_bNoAsserts
)
1301 // delegate showing assert dialog (if possible) to that class
1302 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1304 else // no traits object
1306 // fall back to the function of last resort
1307 s_bNoAsserts
= DoShowAssertDialog(msg
);
1312 #endif // wxDEBUG_LEVEL