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
1026 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1028 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1030 #elif defined(__UNIX__)
1037 #endif // wxTrap already defined as a macro
1039 // default assert handler
1041 wxDefaultAssertHandler(const wxString
& file
,
1043 const wxString
& func
,
1044 const wxString
& cond
,
1045 const wxString
& msg
)
1047 // If this option is set, we should abort immediately when assert happens.
1048 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1052 static int s_bInAssert
= 0;
1054 wxRecursionGuard
guard(s_bInAssert
);
1055 if ( guard
.IsInside() )
1057 // can't use assert here to avoid infinite loops, so just trap
1065 // by default, show the assert dialog box -- we can't customize this
1067 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1071 // let the app process it as it wants
1072 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1073 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1074 cond
.c_str(), msg
.c_str());
1078 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1080 void wxSetDefaultAssertHandler()
1082 wxTheAssertHandler
= wxDefaultAssertHandler
;
1085 void wxOnAssert(const wxString
& file
,
1087 const wxString
& func
,
1088 const wxString
& cond
,
1089 const wxString
& msg
)
1091 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1094 void wxOnAssert(const wxString
& file
,
1096 const wxString
& func
,
1097 const wxString
& cond
)
1099 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1102 void wxOnAssert(const wxChar
*file
,
1108 // this is the backwards-compatible version (unless we don't use Unicode)
1109 // so it could be called directly from the user code and this might happen
1110 // even when wxTheAssertHandler is NULL
1112 if ( wxTheAssertHandler
)
1113 #endif // wxUSE_UNICODE
1114 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1117 void wxOnAssert(const char *file
,
1121 const wxString
& msg
)
1123 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1126 void wxOnAssert(const char *file
,
1130 const wxCStrData
& msg
)
1132 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1136 void wxOnAssert(const char *file
,
1141 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1144 void wxOnAssert(const char *file
,
1150 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1153 void wxOnAssert(const char *file
,
1159 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1161 #endif // wxUSE_UNICODE
1163 #endif // wxDEBUG_LEVEL
1165 // ============================================================================
1166 // private functions implementation
1167 // ============================================================================
1171 static void LINKAGEMODE
SetTraceMasks()
1175 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1177 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1178 while ( tkn
.HasMoreTokens() )
1179 wxLog::AddTraceMask(tkn
.GetNextToken());
1184 #endif // __WXDEBUG__
1188 bool wxTrapInAssert
= false;
1191 bool DoShowAssertDialog(const wxString
& msg
)
1193 // under Windows we can show the dialog even in the console mode
1194 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1195 wxString
msgDlg(msg
);
1197 // this message is intentionally not translated -- it is for developers
1198 // only -- and the less code we use here, less is the danger of recursively
1199 // asserting and dying
1200 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1201 wxT("You can also choose [Cancel] to suppress ")
1202 wxT("further warnings.");
1204 switch ( ::MessageBox(NULL
, msgDlg
.t_str(), wxT("wxWidgets Debug Alert"),
1205 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1208 // If we called wxTrap() directly from here, the programmer would
1209 // see this function and a few more calls between his own code and
1210 // it in the stack trace which would be perfectly useless and often
1211 // confusing. So instead just set the flag here and let the macros
1212 // defined in wx/debug.h call wxTrap() themselves, this ensures
1213 // that the debugger will show the line in the user code containing
1214 // the failing assert.
1215 wxTrapInAssert
= true;
1222 //case IDNO: nothing to do
1224 #else // !__WINDOWS__
1226 #endif // __WINDOWS__/!__WINDOWS__
1228 // continue with the asserts by default
1232 // show the standard assert dialog
1234 void ShowAssertDialog(const wxString
& file
,
1236 const wxString
& func
,
1237 const wxString
& cond
,
1238 const wxString
& msgUser
,
1239 wxAppTraits
*traits
)
1241 // this variable can be set to true to suppress "assert failure" messages
1242 static bool s_bNoAsserts
= false;
1247 // make life easier for people using VC++ IDE by using this format: like
1248 // this, clicking on the message will take us immediately to the place of
1249 // the failed assert
1250 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1252 // add the function name, if any
1253 if ( !func
.empty() )
1254 msg
<< wxT(" in ") << func
<< wxT("()");
1256 // and the message itself
1257 if ( !msgUser
.empty() )
1259 msg
<< wxT(": ") << msgUser
;
1261 else // no message given
1267 // if we are not in the main thread, output the assert directly and trap
1268 // since dialogs cannot be displayed
1269 if ( !wxThread::IsMain() )
1271 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1273 #endif // wxUSE_THREADS
1275 // log the assert in any case
1276 wxMessageOutputDebug().Output(msg
);
1278 if ( !s_bNoAsserts
)
1282 // delegate showing assert dialog (if possible) to that class
1283 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1285 else // no traits object
1287 // fall back to the function of last resort
1288 s_bNoAsserts
= DoShowAssertDialog(msg
);
1293 #endif // wxDEBUG_LEVEL