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 int wxAppConsoleBase::OnExit()
262 // delete the config object if any (don't use Get() here, but Set()
263 // because Get() could create a new config object)
264 delete wxConfigBase::Set(NULL
);
265 #endif // wxUSE_CONFIG
270 void wxAppConsoleBase::Exit()
272 if (m_mainLoop
!= NULL
)
278 // ----------------------------------------------------------------------------
280 // ----------------------------------------------------------------------------
282 wxAppTraits
*wxAppConsoleBase::CreateTraits()
284 return new wxConsoleAppTraits
;
287 wxAppTraits
*wxAppConsoleBase::GetTraits()
289 // FIXME-MT: protect this with a CS?
292 m_traits
= CreateTraits();
294 wxASSERT_MSG( m_traits
, wxT("wxApp::CreateTraits() failed?") );
301 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
303 wxAppConsole
* const app
= GetInstance();
304 return app
? app
->GetTraits() : NULL
;
308 wxAppTraits
& wxAppConsoleBase::GetValidTraits()
310 static wxConsoleAppTraits s_traitsConsole
;
311 wxAppTraits
* const traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
313 return traits
? *traits
: s_traitsConsole
;
316 // ----------------------------------------------------------------------------
317 // wxEventLoop redirection
318 // ----------------------------------------------------------------------------
320 int wxAppConsoleBase::MainLoop()
322 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
324 return m_mainLoop
? m_mainLoop
->Run() : -1;
327 void wxAppConsoleBase::ExitMainLoop()
329 // we should exit from the main event loop, not just any currently active
330 // (e.g. modal dialog) event loop
331 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
337 bool wxAppConsoleBase::Pending()
339 // use the currently active message loop here, not m_mainLoop, because if
340 // we're showing a modal dialog (with its own event loop) currently the
341 // main event loop is not running anyhow
342 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
344 return loop
&& loop
->Pending();
347 bool wxAppConsoleBase::Dispatch()
349 // see comment in Pending()
350 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
352 return loop
&& loop
->Dispatch();
355 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
357 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
359 return loop
->Yield(onlyIfNeeded
);
361 wxScopedPtr
<wxEventLoopBase
> tmpLoop(CreateMainLoop());
362 return tmpLoop
->Yield(onlyIfNeeded
);
365 void wxAppConsoleBase::WakeUpIdle()
367 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
373 bool wxAppConsoleBase::ProcessIdle()
375 // synthesize an idle event and check if more of them are needed
377 event
.SetEventObject(this);
381 // flush the logged messages if any (do this after processing the events
382 // which could have logged new messages)
383 wxLog::FlushActive();
386 // Garbage collect all objects previously scheduled for destruction.
387 DeletePendingObjects();
389 return event
.MoreRequested();
392 bool wxAppConsoleBase::UsesEventLoop() const
394 // in console applications we don't know whether we're going to have an
395 // event loop so assume we won't -- unless we already have one running
396 return wxEventLoopBase::GetActive() != NULL
;
399 // ----------------------------------------------------------------------------
401 // ----------------------------------------------------------------------------
404 bool wxAppConsoleBase::IsMainLoopRunning()
406 const wxAppConsole
* const app
= GetInstance();
408 return app
&& app
->m_mainLoop
!= NULL
;
411 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
413 // process the events normally by default
417 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
419 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
421 // move the handler from the list of handlers with processable pending events
422 // to the list of handlers with pending events which needs to be processed later
423 m_handlersWithPendingEvents
.Remove(toDelay
);
425 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
426 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
428 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
431 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
433 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
435 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
437 m_handlersWithPendingEvents
.Remove(toRemove
);
439 // check that the handler was present only once in the list
440 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
441 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
443 //else: it wasn't in this list at all, it's ok
445 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
447 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
449 // check that the handler was present only once in the list
450 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
451 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
453 //else: it wasn't in this list at all, it's ok
455 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
458 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
460 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
462 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
463 m_handlersWithPendingEvents
.Add(toAppend
);
465 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
468 bool wxAppConsoleBase::HasPendingEvents() const
470 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
472 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
474 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
479 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
481 m_bDoPendingEventProcessing
= false;
484 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
486 m_bDoPendingEventProcessing
= true;
489 void wxAppConsoleBase::ProcessPendingEvents()
491 if ( m_bDoPendingEventProcessing
)
493 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
495 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
496 "this helper list should be empty" );
498 // iterate until the list becomes empty: the handlers remove themselves
499 // from it when they don't have any more pending events
500 while (!m_handlersWithPendingEvents
.IsEmpty())
502 // In ProcessPendingEvents(), new handlers might be added
503 // and we can safely leave the critical section here.
504 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
506 // NOTE: we always call ProcessPendingEvents() on the first event handler
507 // with pending events because handlers auto-remove themselves
508 // from this list (see RemovePendingEventHandler) if they have no
509 // more pending events.
510 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
512 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
515 // now the wxHandlersWithPendingEvents is surely empty; however some event
516 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
517 // because of a selective wxYield call in progress.
518 // Now we need to move them back to wxHandlersWithPendingEvents so the next
519 // call to this function has the chance of processing them:
520 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
522 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
523 m_handlersWithPendingDelayedEvents
.Clear();
526 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
530 void wxAppConsoleBase::DeletePendingEvents()
532 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
534 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
535 "this helper list should be empty" );
537 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
538 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
540 m_handlersWithPendingEvents
.Clear();
542 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
545 // ----------------------------------------------------------------------------
546 // delayed objects destruction
547 // ----------------------------------------------------------------------------
549 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
551 return wxPendingDelete
.Member(object
);
554 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
556 if ( !UsesEventLoop() )
558 // we won't be able to delete it later so do it right now
562 //else: we either already have or will soon start an event loop
564 if ( !wxPendingDelete
.Member(object
) )
565 wxPendingDelete
.Append(object
);
568 void wxAppConsoleBase::DeletePendingObjects()
570 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
573 wxObject
*obj
= node
->GetData();
575 // remove it from the list first so that if we get back here somehow
576 // during the object deletion (e.g. wxYield called from its dtor) we
577 // wouldn't try to delete it the second time
578 if ( wxPendingDelete
.Member(obj
) )
579 wxPendingDelete
.Erase(node
);
583 // Deleting one object may have deleted other pending
584 // objects, so start from beginning of list again.
585 node
= wxPendingDelete
.GetFirst();
589 // ----------------------------------------------------------------------------
590 // exception handling
591 // ----------------------------------------------------------------------------
596 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
597 wxEventFunction func
,
598 wxEvent
& event
) const
600 // by default, simply call the handler
601 (handler
->*func
)(event
);
604 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
605 wxEventFunctor
& functor
,
606 wxEvent
& event
) const
608 // If the functor holds a method then, for backward compatibility, call
610 wxEventFunction eventFunction
= functor
.GetEvtMethod();
613 HandleEvent(handler
, eventFunction
, event
);
615 functor(handler
, event
);
618 void wxAppConsoleBase::OnUnhandledException()
621 // we're called from an exception handler so we can re-throw the exception
622 // to recover its type
629 catch ( std::exception
& e
)
631 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
632 typeid(e
).name(), e
.what());
637 what
= "unknown exception";
640 wxMessageOutputBest().Printf(
641 "*** Caught unhandled %s; terminating\n", what
643 #endif // __WXDEBUG__
646 // ----------------------------------------------------------------------------
647 // exceptions support
648 // ----------------------------------------------------------------------------
650 bool wxAppConsoleBase::OnExceptionInMainLoop()
654 // some compilers are too stupid to know that we never return after throw
655 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
660 #endif // wxUSE_EXCEPTIONS
662 // ----------------------------------------------------------------------------
664 // ----------------------------------------------------------------------------
666 #if wxUSE_CMDLINE_PARSER
668 #define OPTION_VERBOSE "verbose"
670 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
672 // the standard command line options
673 static const wxCmdLineEntryDesc cmdLineDesc
[] =
679 gettext_noop("show this help message"),
681 wxCMD_LINE_OPTION_HELP
689 gettext_noop("generate verbose log messages"),
699 parser
.SetDesc(cmdLineDesc
);
702 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
705 if ( parser
.Found(OPTION_VERBOSE
) )
707 wxLog::SetVerbose(true);
716 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
723 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
730 #endif // wxUSE_CMDLINE_PARSER
732 // ----------------------------------------------------------------------------
734 // ----------------------------------------------------------------------------
737 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
738 const char *componentName
)
740 #if 0 // can't use wxLogTrace, not up and running yet
741 printf("checking build options object '%s' (ptr %p) in '%s'\n",
742 optionsSignature
, optionsSignature
, componentName
);
745 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
747 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
748 wxString prog
= wxString::FromAscii(optionsSignature
);
749 wxString progName
= wxString::FromAscii(componentName
);
752 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
753 lib
.c_str(), progName
.c_str(), prog
.c_str());
755 wxLogFatalError(msg
.c_str());
757 // normally wxLogFatalError doesn't return
764 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
771 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
773 // this function is still present even in debug level 0 build for ABI
774 // compatibility reasons but is never called there and so can simply do
781 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
784 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
789 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
792 // ----------------------------------------------------------------------------
793 // Miscellaneous other methods
794 // ----------------------------------------------------------------------------
796 void wxAppConsoleBase::SetCLocale()
798 // We want to use the user locale by default in GUI applications in order
799 // to show the numbers, dates &c in the familiar format -- and also accept
800 // this format on input (especially important for decimal comma/dot).
801 wxSetlocale(LC_ALL
, "");
804 // ============================================================================
805 // other classes implementations
806 // ============================================================================
808 // ----------------------------------------------------------------------------
809 // wxConsoleAppTraitsBase
810 // ----------------------------------------------------------------------------
814 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
816 return new wxLogStderr
;
821 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
823 return new wxMessageOutputStderr
;
828 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
830 return (wxFontMapper
*)new wxFontMapperBase
;
833 #endif // wxUSE_FONTMAP
835 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
837 // console applications don't use renderers
841 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
843 return wxAppTraitsBase::ShowAssertDialog(msg
);
846 bool wxConsoleAppTraitsBase::HasStderr()
848 // console applications always have stderr, even under Mac/Windows
852 // ----------------------------------------------------------------------------
854 // ----------------------------------------------------------------------------
857 void wxMutexGuiEnterImpl();
858 void wxMutexGuiLeaveImpl();
860 void wxAppTraitsBase::MutexGuiEnter()
862 wxMutexGuiEnterImpl();
865 void wxAppTraitsBase::MutexGuiLeave()
867 wxMutexGuiLeaveImpl();
870 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
872 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
874 traits
->MutexGuiEnter();
877 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
879 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
881 traits
->MutexGuiLeave();
883 #endif // wxUSE_THREADS
885 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
890 #if wxUSE_STACKWALKER
891 const wxString stackTrace
= GetAssertStackTrace();
892 if ( !stackTrace
.empty() )
894 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
896 wxMessageOutputDebug().Output(msg
);
898 #endif // wxUSE_STACKWALKER
900 return DoShowAssertDialog(msgOriginal
+ msg
);
901 #else // !wxDEBUG_LEVEL
902 wxUnusedVar(msgOriginal
);
905 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
908 #if wxUSE_STACKWALKER
909 wxString
wxAppTraitsBase::GetAssertStackTrace()
913 #if !defined(__WINDOWS__)
914 // on Unix stack frame generation may take some time, depending on the
915 // size of the executable mainly... warn the user that we are working
916 wxFprintf(stderr
, "Collecting stack trace information, please wait...");
918 #endif // !__WINDOWS__
923 class StackDump
: public wxStackWalker
928 const wxString
& GetStackTrace() const { return m_stackTrace
; }
931 virtual void OnStackFrame(const wxStackFrame
& frame
)
933 m_stackTrace
<< wxString::Format
936 wx_truncate_cast(int, frame
.GetLevel())
939 wxString name
= frame
.GetName();
942 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
946 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
949 if ( frame
.HasSourceLocation() )
951 m_stackTrace
<< wxT('\t')
952 << frame
.GetFileName()
957 m_stackTrace
<< wxT('\n');
961 wxString m_stackTrace
;
964 // don't show more than maxLines or we could get a dialog too tall to be
965 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
966 // characters it is still only 300 pixels...
967 static const int maxLines
= 20;
970 dump
.Walk(8, maxLines
); // 8 is chosen to hide all OnAssert() calls
971 stackTrace
= dump
.GetStackTrace();
973 const int count
= stackTrace
.Freq(wxT('\n'));
974 for ( int i
= 0; i
< count
- maxLines
; i
++ )
975 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
978 #else // !wxDEBUG_LEVEL
979 // this function is still present for ABI-compatibility even in debug level
980 // 0 build but is not used there and so can simply do nothing
982 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
984 #endif // wxUSE_STACKWALKER
987 // ============================================================================
988 // global functions implementation
989 // ============================================================================
999 // what else can we do?
1008 wxTheApp
->WakeUpIdle();
1010 //else: do nothing, what can we do?
1013 // wxASSERT() helper
1014 bool wxAssertIsEqual(int x
, int y
)
1030 // break into the debugger
1035 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1037 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1039 #elif defined(__UNIX__)
1046 #endif // wxTrap already defined as a macro
1048 // default assert handler
1050 wxDefaultAssertHandler(const wxString
& file
,
1052 const wxString
& func
,
1053 const wxString
& cond
,
1054 const wxString
& msg
)
1056 // If this option is set, we should abort immediately when assert happens.
1057 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1061 static int s_bInAssert
= 0;
1063 wxRecursionGuard
guard(s_bInAssert
);
1064 if ( guard
.IsInside() )
1066 // can't use assert here to avoid infinite loops, so just trap
1074 // by default, show the assert dialog box -- we can't customize this
1076 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1080 // let the app process it as it wants
1081 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1082 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1083 cond
.c_str(), msg
.c_str());
1087 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1089 void wxSetDefaultAssertHandler()
1091 wxTheAssertHandler
= wxDefaultAssertHandler
;
1094 void wxOnAssert(const wxString
& file
,
1096 const wxString
& func
,
1097 const wxString
& cond
,
1098 const wxString
& msg
)
1100 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1103 void wxOnAssert(const wxString
& file
,
1105 const wxString
& func
,
1106 const wxString
& cond
)
1108 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1111 void wxOnAssert(const wxChar
*file
,
1117 // this is the backwards-compatible version (unless we don't use Unicode)
1118 // so it could be called directly from the user code and this might happen
1119 // even when wxTheAssertHandler is NULL
1121 if ( wxTheAssertHandler
)
1122 #endif // wxUSE_UNICODE
1123 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1126 void wxOnAssert(const char *file
,
1130 const wxString
& msg
)
1132 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1135 void wxOnAssert(const char *file
,
1139 const wxCStrData
& msg
)
1141 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1145 void wxOnAssert(const char *file
,
1150 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1153 void wxOnAssert(const char *file
,
1159 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1162 void wxOnAssert(const char *file
,
1168 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1170 #endif // wxUSE_UNICODE
1172 #endif // wxDEBUG_LEVEL
1174 // ============================================================================
1175 // private functions implementation
1176 // ============================================================================
1180 static void LINKAGEMODE
SetTraceMasks()
1184 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1186 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1187 while ( tkn
.HasMoreTokens() )
1188 wxLog::AddTraceMask(tkn
.GetNextToken());
1193 #endif // __WXDEBUG__
1197 bool wxTrapInAssert
= false;
1200 bool DoShowAssertDialog(const wxString
& msg
)
1202 // under Windows we can show the dialog even in the console mode
1203 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1204 wxString
msgDlg(msg
);
1206 // this message is intentionally not translated -- it is for developers
1207 // only -- and the less code we use here, less is the danger of recursively
1208 // asserting and dying
1209 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1210 wxT("You can also choose [Cancel] to suppress ")
1211 wxT("further warnings.");
1213 switch ( ::MessageBox(NULL
, msgDlg
.t_str(), wxT("wxWidgets Debug Alert"),
1214 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1217 // If we called wxTrap() directly from here, the programmer would
1218 // see this function and a few more calls between his own code and
1219 // it in the stack trace which would be perfectly useless and often
1220 // confusing. So instead just set the flag here and let the macros
1221 // defined in wx/debug.h call wxTrap() themselves, this ensures
1222 // that the debugger will show the line in the user code containing
1223 // the failing assert.
1224 wxTrapInAssert
= true;
1231 //case IDNO: nothing to do
1233 #else // !__WINDOWS__
1235 #endif // __WINDOWS__/!__WINDOWS__
1237 // continue with the asserts by default
1241 // show the standard assert dialog
1243 void ShowAssertDialog(const wxString
& file
,
1245 const wxString
& func
,
1246 const wxString
& cond
,
1247 const wxString
& msgUser
,
1248 wxAppTraits
*traits
)
1250 // this variable can be set to true to suppress "assert failure" messages
1251 static bool s_bNoAsserts
= false;
1256 // make life easier for people using VC++ IDE by using this format: like
1257 // this, clicking on the message will take us immediately to the place of
1258 // the failed assert
1259 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1261 // add the function name, if any
1262 if ( !func
.empty() )
1263 msg
<< wxT(" in ") << func
<< wxT("()");
1265 // and the message itself
1266 if ( !msgUser
.empty() )
1268 msg
<< wxT(": ") << msgUser
;
1270 else // no message given
1276 // if we are not in the main thread, output the assert directly and trap
1277 // since dialogs cannot be displayed
1278 if ( !wxThread::IsMain() )
1280 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1282 #endif // wxUSE_THREADS
1284 // log the assert in any case
1285 wxMessageOutputDebug().Output(msg
);
1287 if ( !s_bNoAsserts
)
1291 // delegate showing assert dialog (if possible) to that class
1292 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1294 else // no traits object
1296 // fall back to the function of last resort
1297 s_bNoAsserts
= DoShowAssertDialog(msg
);
1302 #endif // wxDEBUG_LEVEL