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
;
307 // ----------------------------------------------------------------------------
308 // wxEventLoop redirection
309 // ----------------------------------------------------------------------------
311 int wxAppConsoleBase::MainLoop()
313 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
315 return m_mainLoop
? m_mainLoop
->Run() : -1;
318 void wxAppConsoleBase::ExitMainLoop()
320 // we should exit from the main event loop, not just any currently active
321 // (e.g. modal dialog) event loop
322 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
328 bool wxAppConsoleBase::Pending()
330 // use the currently active message loop here, not m_mainLoop, because if
331 // we're showing a modal dialog (with its own event loop) currently the
332 // main event loop is not running anyhow
333 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
335 return loop
&& loop
->Pending();
338 bool wxAppConsoleBase::Dispatch()
340 // see comment in Pending()
341 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
343 return loop
&& loop
->Dispatch();
346 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
348 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
350 return loop
->Yield(onlyIfNeeded
);
352 wxScopedPtr
<wxEventLoopBase
> tmpLoop(CreateMainLoop());
353 return tmpLoop
->Yield(onlyIfNeeded
);
356 void wxAppConsoleBase::WakeUpIdle()
358 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
364 bool wxAppConsoleBase::ProcessIdle()
366 // synthesize an idle event and check if more of them are needed
368 event
.SetEventObject(this);
372 // flush the logged messages if any (do this after processing the events
373 // which could have logged new messages)
374 wxLog::FlushActive();
377 // Garbage collect all objects previously scheduled for destruction.
378 DeletePendingObjects();
380 return event
.MoreRequested();
383 bool wxAppConsoleBase::UsesEventLoop() const
385 // in console applications we don't know whether we're going to have an
386 // event loop so assume we won't -- unless we already have one running
387 return wxEventLoopBase::GetActive() != NULL
;
390 // ----------------------------------------------------------------------------
392 // ----------------------------------------------------------------------------
395 bool wxAppConsoleBase::IsMainLoopRunning()
397 const wxAppConsole
* const app
= GetInstance();
399 return app
&& app
->m_mainLoop
!= NULL
;
402 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
404 // process the events normally by default
408 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
410 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
412 // move the handler from the list of handlers with processable pending events
413 // to the list of handlers with pending events which needs to be processed later
414 m_handlersWithPendingEvents
.Remove(toDelay
);
416 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
417 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
419 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
422 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
424 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
426 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
428 m_handlersWithPendingEvents
.Remove(toRemove
);
430 // check that the handler was present only once in the list
431 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
432 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
434 //else: it wasn't in this list at all, it's ok
436 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
438 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
440 // check that the handler was present only once in the list
441 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
442 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
444 //else: it wasn't in this list at all, it's ok
446 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
449 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
451 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
453 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
454 m_handlersWithPendingEvents
.Add(toAppend
);
456 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
459 bool wxAppConsoleBase::HasPendingEvents() const
461 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
463 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
465 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
470 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
472 m_bDoPendingEventProcessing
= false;
475 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
477 m_bDoPendingEventProcessing
= true;
480 void wxAppConsoleBase::ProcessPendingEvents()
482 if ( m_bDoPendingEventProcessing
)
484 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
486 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
487 "this helper list should be empty" );
489 // iterate until the list becomes empty: the handlers remove themselves
490 // from it when they don't have any more pending events
491 while (!m_handlersWithPendingEvents
.IsEmpty())
493 // In ProcessPendingEvents(), new handlers might be added
494 // and we can safely leave the critical section here.
495 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
497 // NOTE: we always call ProcessPendingEvents() on the first event handler
498 // with pending events because handlers auto-remove themselves
499 // from this list (see RemovePendingEventHandler) if they have no
500 // more pending events.
501 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
503 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
506 // now the wxHandlersWithPendingEvents is surely empty; however some event
507 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
508 // because of a selective wxYield call in progress.
509 // Now we need to move them back to wxHandlersWithPendingEvents so the next
510 // call to this function has the chance of processing them:
511 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
513 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
514 m_handlersWithPendingDelayedEvents
.Clear();
517 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
521 void wxAppConsoleBase::DeletePendingEvents()
523 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
525 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
526 "this helper list should be empty" );
528 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
529 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
531 m_handlersWithPendingEvents
.Clear();
533 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
536 // ----------------------------------------------------------------------------
537 // delayed objects destruction
538 // ----------------------------------------------------------------------------
540 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
542 return wxPendingDelete
.Member(object
);
545 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
547 if ( !UsesEventLoop() )
549 // we won't be able to delete it later so do it right now
553 //else: we either already have or will soon start an event loop
555 if ( !wxPendingDelete
.Member(object
) )
556 wxPendingDelete
.Append(object
);
559 void wxAppConsoleBase::DeletePendingObjects()
561 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
564 wxObject
*obj
= node
->GetData();
566 // remove it from the list first so that if we get back here somehow
567 // during the object deletion (e.g. wxYield called from its dtor) we
568 // wouldn't try to delete it the second time
569 if ( wxPendingDelete
.Member(obj
) )
570 wxPendingDelete
.Erase(node
);
574 // Deleting one object may have deleted other pending
575 // objects, so start from beginning of list again.
576 node
= wxPendingDelete
.GetFirst();
580 // ----------------------------------------------------------------------------
581 // exception handling
582 // ----------------------------------------------------------------------------
587 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
588 wxEventFunction func
,
589 wxEvent
& event
) const
591 // by default, simply call the handler
592 (handler
->*func
)(event
);
595 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
596 wxEventFunctor
& functor
,
597 wxEvent
& event
) const
599 // If the functor holds a method then, for backward compatibility, call
601 wxEventFunction eventFunction
= functor
.GetEvtMethod();
604 HandleEvent(handler
, eventFunction
, event
);
606 functor(handler
, event
);
609 void wxAppConsoleBase::OnUnhandledException()
612 // we're called from an exception handler so we can re-throw the exception
613 // to recover its type
620 catch ( std::exception
& e
)
622 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
623 typeid(e
).name(), e
.what());
628 what
= "unknown exception";
631 wxMessageOutputBest().Printf(
632 "*** Caught unhandled %s; terminating\n", what
634 #endif // __WXDEBUG__
637 // ----------------------------------------------------------------------------
638 // exceptions support
639 // ----------------------------------------------------------------------------
641 bool wxAppConsoleBase::OnExceptionInMainLoop()
645 // some compilers are too stupid to know that we never return after throw
646 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
651 #endif // wxUSE_EXCEPTIONS
653 // ----------------------------------------------------------------------------
655 // ----------------------------------------------------------------------------
657 #if wxUSE_CMDLINE_PARSER
659 #define OPTION_VERBOSE "verbose"
661 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
663 // the standard command line options
664 static const wxCmdLineEntryDesc cmdLineDesc
[] =
670 gettext_noop("show this help message"),
672 wxCMD_LINE_OPTION_HELP
680 gettext_noop("generate verbose log messages"),
690 parser
.SetDesc(cmdLineDesc
);
693 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
696 if ( parser
.Found(OPTION_VERBOSE
) )
698 wxLog::SetVerbose(true);
707 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
714 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
721 #endif // wxUSE_CMDLINE_PARSER
723 // ----------------------------------------------------------------------------
725 // ----------------------------------------------------------------------------
728 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
729 const char *componentName
)
731 #if 0 // can't use wxLogTrace, not up and running yet
732 printf("checking build options object '%s' (ptr %p) in '%s'\n",
733 optionsSignature
, optionsSignature
, componentName
);
736 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
738 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
739 wxString prog
= wxString::FromAscii(optionsSignature
);
740 wxString progName
= wxString::FromAscii(componentName
);
743 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
744 lib
.c_str(), progName
.c_str(), prog
.c_str());
746 wxLogFatalError(msg
.c_str());
748 // normally wxLogFatalError doesn't return
755 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
762 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
764 // this function is still present even in debug level 0 build for ABI
765 // compatibility reasons but is never called there and so can simply do
772 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
775 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
780 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
783 // ----------------------------------------------------------------------------
784 // Miscellaneous other methods
785 // ----------------------------------------------------------------------------
787 void wxAppConsoleBase::SetCLocale()
789 // We want to use the user locale by default in GUI applications in order
790 // to show the numbers, dates &c in the familiar format -- and also accept
791 // this format on input (especially important for decimal comma/dot).
792 wxSetlocale(LC_ALL
, "");
795 // ============================================================================
796 // other classes implementations
797 // ============================================================================
799 // ----------------------------------------------------------------------------
800 // wxConsoleAppTraitsBase
801 // ----------------------------------------------------------------------------
805 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
807 return new wxLogStderr
;
812 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
814 return new wxMessageOutputStderr
;
819 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
821 return (wxFontMapper
*)new wxFontMapperBase
;
824 #endif // wxUSE_FONTMAP
826 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
828 // console applications don't use renderers
832 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
834 return wxAppTraitsBase::ShowAssertDialog(msg
);
837 bool wxConsoleAppTraitsBase::HasStderr()
839 // console applications always have stderr, even under Mac/Windows
843 // ----------------------------------------------------------------------------
845 // ----------------------------------------------------------------------------
848 void wxMutexGuiEnterImpl();
849 void wxMutexGuiLeaveImpl();
851 void wxAppTraitsBase::MutexGuiEnter()
853 wxMutexGuiEnterImpl();
856 void wxAppTraitsBase::MutexGuiLeave()
858 wxMutexGuiLeaveImpl();
861 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
863 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
865 traits
->MutexGuiEnter();
868 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
870 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
872 traits
->MutexGuiLeave();
874 #endif // wxUSE_THREADS
876 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
881 #if wxUSE_STACKWALKER
882 const wxString stackTrace
= GetAssertStackTrace();
883 if ( !stackTrace
.empty() )
885 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
887 wxMessageOutputDebug().Output(msg
);
889 #endif // wxUSE_STACKWALKER
891 return DoShowAssertDialog(msgOriginal
+ msg
);
892 #else // !wxDEBUG_LEVEL
893 wxUnusedVar(msgOriginal
);
896 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
899 #if wxUSE_STACKWALKER
900 wxString
wxAppTraitsBase::GetAssertStackTrace()
904 #if !defined(__WINDOWS__)
905 // on Unix stack frame generation may take some time, depending on the
906 // size of the executable mainly... warn the user that we are working
907 wxFprintf(stderr
, "Collecting stack trace information, please wait...");
909 #endif // !__WINDOWS__
914 class StackDump
: public wxStackWalker
919 const wxString
& GetStackTrace() const { return m_stackTrace
; }
922 virtual void OnStackFrame(const wxStackFrame
& frame
)
924 m_stackTrace
<< wxString::Format
927 wx_truncate_cast(int, frame
.GetLevel())
930 wxString name
= frame
.GetName();
933 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
937 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
940 if ( frame
.HasSourceLocation() )
942 m_stackTrace
<< wxT('\t')
943 << frame
.GetFileName()
948 m_stackTrace
<< wxT('\n');
952 wxString m_stackTrace
;
955 // don't show more than maxLines or we could get a dialog too tall to be
956 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
957 // characters it is still only 300 pixels...
958 static const int maxLines
= 20;
961 dump
.Walk(8, maxLines
); // 8 is chosen to hide all OnAssert() calls
962 stackTrace
= dump
.GetStackTrace();
964 const int count
= stackTrace
.Freq(wxT('\n'));
965 for ( int i
= 0; i
< count
- maxLines
; i
++ )
966 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
969 #else // !wxDEBUG_LEVEL
970 // this function is still present for ABI-compatibility even in debug level
971 // 0 build but is not used there and so can simply do nothing
973 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
975 #endif // wxUSE_STACKWALKER
978 // ============================================================================
979 // global functions implementation
980 // ============================================================================
990 // what else can we do?
999 wxTheApp
->WakeUpIdle();
1001 //else: do nothing, what can we do?
1004 // wxASSERT() helper
1005 bool wxAssertIsEqual(int x
, int y
)
1021 // break into the debugger
1024 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1026 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1028 #elif defined(__UNIX__)
1035 // default assert handler
1037 wxDefaultAssertHandler(const wxString
& file
,
1039 const wxString
& func
,
1040 const wxString
& cond
,
1041 const wxString
& msg
)
1043 // If this option is set, we should abort immediately when assert happens.
1044 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1048 static int s_bInAssert
= 0;
1050 wxRecursionGuard
guard(s_bInAssert
);
1051 if ( guard
.IsInside() )
1053 // can't use assert here to avoid infinite loops, so just trap
1061 // by default, show the assert dialog box -- we can't customize this
1063 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1067 // let the app process it as it wants
1068 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1069 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1070 cond
.c_str(), msg
.c_str());
1074 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1076 void wxSetDefaultAssertHandler()
1078 wxTheAssertHandler
= wxDefaultAssertHandler
;
1081 void wxOnAssert(const wxString
& file
,
1083 const wxString
& func
,
1084 const wxString
& cond
,
1085 const wxString
& msg
)
1087 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1090 void wxOnAssert(const wxString
& file
,
1092 const wxString
& func
,
1093 const wxString
& cond
)
1095 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1098 void wxOnAssert(const wxChar
*file
,
1104 // this is the backwards-compatible version (unless we don't use Unicode)
1105 // so it could be called directly from the user code and this might happen
1106 // even when wxTheAssertHandler is NULL
1108 if ( wxTheAssertHandler
)
1109 #endif // wxUSE_UNICODE
1110 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1113 void wxOnAssert(const char *file
,
1117 const wxString
& msg
)
1119 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1122 void wxOnAssert(const char *file
,
1126 const wxCStrData
& msg
)
1128 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1132 void wxOnAssert(const char *file
,
1137 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1140 void wxOnAssert(const char *file
,
1146 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1149 void wxOnAssert(const char *file
,
1155 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1157 #endif // wxUSE_UNICODE
1159 #endif // wxDEBUG_LEVEL
1161 // ============================================================================
1162 // private functions implementation
1163 // ============================================================================
1167 static void LINKAGEMODE
SetTraceMasks()
1171 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1173 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1174 while ( tkn
.HasMoreTokens() )
1175 wxLog::AddTraceMask(tkn
.GetNextToken());
1180 #endif // __WXDEBUG__
1185 bool DoShowAssertDialog(const wxString
& msg
)
1187 // under Windows we can show the dialog even in the console mode
1188 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1189 wxString
msgDlg(msg
);
1191 // this message is intentionally not translated -- it is for developers
1192 // only -- and the less code we use here, less is the danger of recursively
1193 // asserting and dying
1194 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1195 wxT("You can also choose [Cancel] to suppress ")
1196 wxT("further warnings.");
1198 switch ( ::MessageBox(NULL
, msgDlg
.t_str(), wxT("wxWidgets Debug Alert"),
1199 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1209 //case IDNO: nothing to do
1211 #else // !__WINDOWS__
1213 #endif // __WINDOWS__/!__WINDOWS__
1215 // continue with the asserts by default
1219 // show the standard assert dialog
1221 void ShowAssertDialog(const wxString
& file
,
1223 const wxString
& func
,
1224 const wxString
& cond
,
1225 const wxString
& msgUser
,
1226 wxAppTraits
*traits
)
1228 // this variable can be set to true to suppress "assert failure" messages
1229 static bool s_bNoAsserts
= false;
1234 // make life easier for people using VC++ IDE by using this format: like
1235 // this, clicking on the message will take us immediately to the place of
1236 // the failed assert
1237 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1239 // add the function name, if any
1240 if ( !func
.empty() )
1241 msg
<< wxT(" in ") << func
<< wxT("()");
1243 // and the message itself
1244 if ( !msgUser
.empty() )
1246 msg
<< wxT(": ") << msgUser
;
1248 else // no message given
1254 // if we are not in the main thread, output the assert directly and trap
1255 // since dialogs cannot be displayed
1256 if ( !wxThread::IsMain() )
1258 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1260 #endif // wxUSE_THREADS
1262 // log the assert in any case
1263 wxMessageOutputDebug().Output(msg
);
1265 if ( !s_bNoAsserts
)
1269 // delegate showing assert dialog (if possible) to that class
1270 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1272 else // no traits object
1274 // fall back to the function of last resort
1275 s_bNoAsserts
= DoShowAssertDialog(msg
);
1280 #endif // wxDEBUG_LEVEL