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());
328 wxTheApp
->OnLaunched();
330 return m_mainLoop
? m_mainLoop
->Run() : -1;
333 void wxAppConsoleBase::ExitMainLoop()
335 // we should exit from the main event loop, not just any currently active
336 // (e.g. modal dialog) event loop
337 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
343 bool wxAppConsoleBase::Pending()
345 // use the currently active message loop here, not m_mainLoop, because if
346 // we're showing a modal dialog (with its own event loop) currently the
347 // main event loop is not running anyhow
348 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
350 return loop
&& loop
->Pending();
353 bool wxAppConsoleBase::Dispatch()
355 // see comment in Pending()
356 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
358 return loop
&& loop
->Dispatch();
361 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
363 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
365 return loop
->Yield(onlyIfNeeded
);
367 wxScopedPtr
<wxEventLoopBase
> tmpLoop(CreateMainLoop());
368 return tmpLoop
->Yield(onlyIfNeeded
);
371 void wxAppConsoleBase::WakeUpIdle()
373 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
379 bool wxAppConsoleBase::ProcessIdle()
381 // synthesize an idle event and check if more of them are needed
383 event
.SetEventObject(this);
387 // flush the logged messages if any (do this after processing the events
388 // which could have logged new messages)
389 wxLog::FlushActive();
392 // Garbage collect all objects previously scheduled for destruction.
393 DeletePendingObjects();
395 return event
.MoreRequested();
398 bool wxAppConsoleBase::UsesEventLoop() const
400 // in console applications we don't know whether we're going to have an
401 // event loop so assume we won't -- unless we already have one running
402 return wxEventLoopBase::GetActive() != NULL
;
405 // ----------------------------------------------------------------------------
407 // ----------------------------------------------------------------------------
410 bool wxAppConsoleBase::IsMainLoopRunning()
412 const wxAppConsole
* const app
= GetInstance();
414 return app
&& app
->m_mainLoop
!= NULL
;
417 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
419 // process the events normally by default
423 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
425 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
427 // move the handler from the list of handlers with processable pending events
428 // to the list of handlers with pending events which needs to be processed later
429 m_handlersWithPendingEvents
.Remove(toDelay
);
431 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
432 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
434 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
437 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
439 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
441 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
443 m_handlersWithPendingEvents
.Remove(toRemove
);
445 // check that the handler was present only once in the list
446 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
447 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
449 //else: it wasn't in this list at all, it's ok
451 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
453 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
455 // check that the handler was present only once in the list
456 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
457 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
459 //else: it wasn't in this list at all, it's ok
461 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
464 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
466 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
468 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
469 m_handlersWithPendingEvents
.Add(toAppend
);
471 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
474 bool wxAppConsoleBase::HasPendingEvents() const
476 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
478 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
480 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
485 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
487 m_bDoPendingEventProcessing
= false;
490 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
492 m_bDoPendingEventProcessing
= true;
495 void wxAppConsoleBase::ProcessPendingEvents()
497 if ( m_bDoPendingEventProcessing
)
499 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
501 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
502 "this helper list should be empty" );
504 // iterate until the list becomes empty: the handlers remove themselves
505 // from it when they don't have any more pending events
506 while (!m_handlersWithPendingEvents
.IsEmpty())
508 // In ProcessPendingEvents(), new handlers might be added
509 // and we can safely leave the critical section here.
510 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
512 // NOTE: we always call ProcessPendingEvents() on the first event handler
513 // with pending events because handlers auto-remove themselves
514 // from this list (see RemovePendingEventHandler) if they have no
515 // more pending events.
516 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
518 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
521 // now the wxHandlersWithPendingEvents is surely empty; however some event
522 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
523 // because of a selective wxYield call in progress.
524 // Now we need to move them back to wxHandlersWithPendingEvents so the next
525 // call to this function has the chance of processing them:
526 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
528 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
529 m_handlersWithPendingDelayedEvents
.Clear();
532 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
536 void wxAppConsoleBase::DeletePendingEvents()
538 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
540 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
541 "this helper list should be empty" );
543 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
544 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
546 m_handlersWithPendingEvents
.Clear();
548 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
551 // ----------------------------------------------------------------------------
552 // delayed objects destruction
553 // ----------------------------------------------------------------------------
555 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
557 return wxPendingDelete
.Member(object
);
560 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
562 if ( !UsesEventLoop() )
564 // we won't be able to delete it later so do it right now
568 //else: we either already have or will soon start an event loop
570 if ( !wxPendingDelete
.Member(object
) )
571 wxPendingDelete
.Append(object
);
574 void wxAppConsoleBase::DeletePendingObjects()
576 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
579 wxObject
*obj
= node
->GetData();
581 // remove it from the list first so that if we get back here somehow
582 // during the object deletion (e.g. wxYield called from its dtor) we
583 // wouldn't try to delete it the second time
584 if ( wxPendingDelete
.Member(obj
) )
585 wxPendingDelete
.Erase(node
);
589 // Deleting one object may have deleted other pending
590 // objects, so start from beginning of list again.
591 node
= wxPendingDelete
.GetFirst();
595 // ----------------------------------------------------------------------------
596 // exception handling
597 // ----------------------------------------------------------------------------
602 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
603 wxEventFunction func
,
604 wxEvent
& event
) const
606 // by default, simply call the handler
607 (handler
->*func
)(event
);
610 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
611 wxEventFunctor
& functor
,
612 wxEvent
& event
) const
614 // If the functor holds a method then, for backward compatibility, call
616 wxEventFunction eventFunction
= functor
.GetEvtMethod();
619 HandleEvent(handler
, eventFunction
, event
);
621 functor(handler
, event
);
624 void wxAppConsoleBase::OnUnhandledException()
627 // we're called from an exception handler so we can re-throw the exception
628 // to recover its type
635 catch ( std::exception
& e
)
637 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
638 typeid(e
).name(), e
.what());
643 what
= "unknown exception";
646 wxMessageOutputBest().Printf(
647 "*** Caught unhandled %s; terminating\n", what
649 #endif // __WXDEBUG__
652 // ----------------------------------------------------------------------------
653 // exceptions support
654 // ----------------------------------------------------------------------------
656 bool wxAppConsoleBase::OnExceptionInMainLoop()
660 // some compilers are too stupid to know that we never return after throw
661 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
666 #endif // wxUSE_EXCEPTIONS
668 // ----------------------------------------------------------------------------
670 // ----------------------------------------------------------------------------
672 #if wxUSE_CMDLINE_PARSER
674 #define OPTION_VERBOSE "verbose"
676 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
678 // the standard command line options
679 static const wxCmdLineEntryDesc cmdLineDesc
[] =
685 gettext_noop("show this help message"),
687 wxCMD_LINE_OPTION_HELP
695 gettext_noop("generate verbose log messages"),
705 parser
.SetDesc(cmdLineDesc
);
708 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
711 if ( parser
.Found(OPTION_VERBOSE
) )
713 wxLog::SetVerbose(true);
722 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
729 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
736 #endif // wxUSE_CMDLINE_PARSER
738 // ----------------------------------------------------------------------------
740 // ----------------------------------------------------------------------------
743 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
744 const char *componentName
)
746 #if 0 // can't use wxLogTrace, not up and running yet
747 printf("checking build options object '%s' (ptr %p) in '%s'\n",
748 optionsSignature
, optionsSignature
, componentName
);
751 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
753 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
754 wxString prog
= wxString::FromAscii(optionsSignature
);
755 wxString progName
= wxString::FromAscii(componentName
);
758 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
759 lib
.c_str(), progName
.c_str(), prog
.c_str());
761 wxLogFatalError(msg
.c_str());
763 // normally wxLogFatalError doesn't return
770 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
777 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
779 // this function is still present even in debug level 0 build for ABI
780 // compatibility reasons but is never called there and so can simply do
787 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
790 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
795 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
798 // ----------------------------------------------------------------------------
799 // Miscellaneous other methods
800 // ----------------------------------------------------------------------------
802 void wxAppConsoleBase::SetCLocale()
804 // We want to use the user locale by default in GUI applications in order
805 // to show the numbers, dates &c in the familiar format -- and also accept
806 // this format on input (especially important for decimal comma/dot).
807 wxSetlocale(LC_ALL
, "");
810 // ============================================================================
811 // other classes implementations
812 // ============================================================================
814 // ----------------------------------------------------------------------------
815 // wxConsoleAppTraitsBase
816 // ----------------------------------------------------------------------------
820 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
822 return new wxLogStderr
;
827 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
829 return new wxMessageOutputStderr
;
834 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
836 return (wxFontMapper
*)new wxFontMapperBase
;
839 #endif // wxUSE_FONTMAP
841 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
843 // console applications don't use renderers
847 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
849 return wxAppTraitsBase::ShowAssertDialog(msg
);
852 bool wxConsoleAppTraitsBase::HasStderr()
854 // console applications always have stderr, even under Mac/Windows
858 // ----------------------------------------------------------------------------
860 // ----------------------------------------------------------------------------
863 void wxMutexGuiEnterImpl();
864 void wxMutexGuiLeaveImpl();
866 void wxAppTraitsBase::MutexGuiEnter()
868 wxMutexGuiEnterImpl();
871 void wxAppTraitsBase::MutexGuiLeave()
873 wxMutexGuiLeaveImpl();
876 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
878 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
880 traits
->MutexGuiEnter();
883 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
885 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
887 traits
->MutexGuiLeave();
889 #endif // wxUSE_THREADS
891 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
896 #if wxUSE_STACKWALKER
897 const wxString stackTrace
= GetAssertStackTrace();
898 if ( !stackTrace
.empty() )
900 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
902 wxMessageOutputDebug().Output(msg
);
904 #endif // wxUSE_STACKWALKER
906 return DoShowAssertDialog(msgOriginal
+ msg
);
907 #else // !wxDEBUG_LEVEL
908 wxUnusedVar(msgOriginal
);
911 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
914 #if wxUSE_STACKWALKER
915 wxString
wxAppTraitsBase::GetAssertStackTrace()
919 #if !defined(__WINDOWS__)
920 // on Unix stack frame generation may take some time, depending on the
921 // size of the executable mainly... warn the user that we are working
922 wxFprintf(stderr
, "Collecting stack trace information, please wait...");
924 #endif // !__WINDOWS__
929 class StackDump
: public wxStackWalker
934 const wxString
& GetStackTrace() const { return m_stackTrace
; }
937 virtual void OnStackFrame(const wxStackFrame
& frame
)
939 m_stackTrace
<< wxString::Format
942 wx_truncate_cast(int, frame
.GetLevel())
945 wxString name
= frame
.GetName();
948 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
952 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
955 if ( frame
.HasSourceLocation() )
957 m_stackTrace
<< wxT('\t')
958 << frame
.GetFileName()
963 m_stackTrace
<< wxT('\n');
967 wxString m_stackTrace
;
970 // don't show more than maxLines or we could get a dialog too tall to be
971 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
972 // characters it is still only 300 pixels...
973 static const int maxLines
= 20;
976 dump
.Walk(8, maxLines
); // 8 is chosen to hide all OnAssert() calls
977 stackTrace
= dump
.GetStackTrace();
979 const int count
= stackTrace
.Freq(wxT('\n'));
980 for ( int i
= 0; i
< count
- maxLines
; i
++ )
981 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
984 #else // !wxDEBUG_LEVEL
985 // this function is still present for ABI-compatibility even in debug level
986 // 0 build but is not used there and so can simply do nothing
988 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
990 #endif // wxUSE_STACKWALKER
993 // ============================================================================
994 // global functions implementation
995 // ============================================================================
1005 // what else can we do?
1014 wxTheApp
->WakeUpIdle();
1016 //else: do nothing, what can we do?
1019 // wxASSERT() helper
1020 bool wxAssertIsEqual(int x
, int y
)
1036 // break into the debugger
1041 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1043 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1045 #elif defined(__UNIX__)
1052 #endif // wxTrap already defined as a macro
1054 // default assert handler
1056 wxDefaultAssertHandler(const wxString
& file
,
1058 const wxString
& func
,
1059 const wxString
& cond
,
1060 const wxString
& msg
)
1062 // If this option is set, we should abort immediately when assert happens.
1063 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1067 static int s_bInAssert
= 0;
1069 wxRecursionGuard
guard(s_bInAssert
);
1070 if ( guard
.IsInside() )
1072 // can't use assert here to avoid infinite loops, so just trap
1080 // by default, show the assert dialog box -- we can't customize this
1082 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1086 // let the app process it as it wants
1087 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1088 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1089 cond
.c_str(), msg
.c_str());
1093 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1095 void wxSetDefaultAssertHandler()
1097 wxTheAssertHandler
= wxDefaultAssertHandler
;
1100 void wxOnAssert(const wxString
& file
,
1102 const wxString
& func
,
1103 const wxString
& cond
,
1104 const wxString
& msg
)
1106 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1109 void wxOnAssert(const wxString
& file
,
1111 const wxString
& func
,
1112 const wxString
& cond
)
1114 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1117 void wxOnAssert(const wxChar
*file
,
1123 // this is the backwards-compatible version (unless we don't use Unicode)
1124 // so it could be called directly from the user code and this might happen
1125 // even when wxTheAssertHandler is NULL
1127 if ( wxTheAssertHandler
)
1128 #endif // wxUSE_UNICODE
1129 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1132 void wxOnAssert(const char *file
,
1136 const wxString
& msg
)
1138 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1141 void wxOnAssert(const char *file
,
1145 const wxCStrData
& msg
)
1147 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1151 void wxOnAssert(const char *file
,
1156 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1159 void wxOnAssert(const char *file
,
1165 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1168 void wxOnAssert(const char *file
,
1174 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1176 #endif // wxUSE_UNICODE
1178 #endif // wxDEBUG_LEVEL
1180 // ============================================================================
1181 // private functions implementation
1182 // ============================================================================
1186 static void LINKAGEMODE
SetTraceMasks()
1190 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1192 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1193 while ( tkn
.HasMoreTokens() )
1194 wxLog::AddTraceMask(tkn
.GetNextToken());
1199 #endif // __WXDEBUG__
1203 bool wxTrapInAssert
= false;
1206 bool DoShowAssertDialog(const wxString
& msg
)
1208 // under Windows we can show the dialog even in the console mode
1209 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1210 wxString
msgDlg(msg
);
1212 // this message is intentionally not translated -- it is for developers
1213 // only -- and the less code we use here, less is the danger of recursively
1214 // asserting and dying
1215 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1216 wxT("You can also choose [Cancel] to suppress ")
1217 wxT("further warnings.");
1219 switch ( ::MessageBox(NULL
, msgDlg
.t_str(), wxT("wxWidgets Debug Alert"),
1220 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1223 // If we called wxTrap() directly from here, the programmer would
1224 // see this function and a few more calls between his own code and
1225 // it in the stack trace which would be perfectly useless and often
1226 // confusing. So instead just set the flag here and let the macros
1227 // defined in wx/debug.h call wxTrap() themselves, this ensures
1228 // that the debugger will show the line in the user code containing
1229 // the failing assert.
1230 wxTrapInAssert
= true;
1237 //case IDNO: nothing to do
1239 #else // !__WINDOWS__
1241 #endif // __WINDOWS__/!__WINDOWS__
1243 // continue with the asserts by default
1247 // show the standard assert dialog
1249 void ShowAssertDialog(const wxString
& file
,
1251 const wxString
& func
,
1252 const wxString
& cond
,
1253 const wxString
& msgUser
,
1254 wxAppTraits
*traits
)
1256 // this variable can be set to true to suppress "assert failure" messages
1257 static bool s_bNoAsserts
= false;
1262 // make life easier for people using VC++ IDE by using this format: like
1263 // this, clicking on the message will take us immediately to the place of
1264 // the failed assert
1265 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1267 // add the function name, if any
1268 if ( !func
.empty() )
1269 msg
<< wxT(" in ") << func
<< wxT("()");
1271 // and the message itself
1272 if ( !msgUser
.empty() )
1274 msg
<< wxT(": ") << msgUser
;
1276 else // no message given
1282 // if we are not in the main thread, output the assert directly and trap
1283 // since dialogs cannot be displayed
1284 if ( !wxThread::IsMain() )
1286 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1288 #endif // wxUSE_THREADS
1290 // log the assert in any case
1291 wxMessageOutputDebug().Output(msg
);
1293 if ( !s_bNoAsserts
)
1297 // delegate showing assert dialog (if possible) to that class
1298 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1300 else // no traits object
1302 // fall back to the function of last resort
1303 s_bNoAsserts
= DoShowAssertDialog(msg
);
1308 #endif // wxDEBUG_LEVEL