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 // License: wxWindows license
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"
50 #if wxUSE_EXCEPTIONS && wxUSE_STL
56 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
57 #include <signal.h> // for SIGTRAP used by wxTrap()
61 #endif // ! __WXPALMOS5__
64 #include "wx/fontmap.h"
65 #endif // wxUSE_FONTMAP
69 #include "wx/stackwalk.h"
71 #include "wx/msw/debughlp.h"
73 #endif // wxUSE_STACKWALKER
75 #include "wx/recguard.h"
76 #endif // wxDEBUG_LEVEL
78 // wxABI_VERSION can be defined when compiling applications but it should be
79 // left undefined when compiling the library itself, it is then set to its
80 // default value in version.h
81 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
82 #error "wxABI_VERSION should not be defined when compiling the library"
85 // ----------------------------------------------------------------------------
86 // private functions prototypes
87 // ----------------------------------------------------------------------------
90 // really just show the assert dialog
91 static bool DoShowAssertDialog(const wxString
& msg
);
93 // prepare for showing the assert dialog, use the given traits or
94 // DoShowAssertDialog() as last fallback to really show it
96 void ShowAssertDialog(const wxString
& file
,
101 wxAppTraits
*traits
= NULL
);
102 #endif // wxDEBUG_LEVEL
105 // turn on the trace masks specified in the env variable WXTRACE
106 static void LINKAGEMODE
SetTraceMasks();
107 #endif // __WXDEBUG__
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
115 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
117 wxSocketManager
*wxAppTraitsBase::ms_manager
= NULL
;
119 WXDLLIMPEXP_DATA_BASE(wxList
) wxPendingDelete
;
121 // ----------------------------------------------------------------------------
123 // ----------------------------------------------------------------------------
125 // this defines wxEventLoopPtr
126 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
128 // ============================================================================
129 // wxAppConsoleBase implementation
130 // ============================================================================
132 // ----------------------------------------------------------------------------
134 // ----------------------------------------------------------------------------
136 wxAppConsoleBase::wxAppConsoleBase()
140 m_bDoPendingEventProcessing
= true;
142 ms_appInstance
= static_cast<wxAppConsole
*>(this);
147 // In unicode mode the SetTraceMasks call can cause an apptraits to be
148 // created, but since we are still in the constructor the wrong kind will
149 // be created for GUI apps. Destroy it so it can be created again later.
156 wxAppConsoleBase::~wxAppConsoleBase()
158 // we're being destroyed and using this object from now on may not work or
159 // even crash so don't leave dangling pointers to it
160 ms_appInstance
= NULL
;
165 // ----------------------------------------------------------------------------
166 // initialization/cleanup
167 // ----------------------------------------------------------------------------
169 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc
), wxChar
**WXUNUSED(argv
))
172 GetTraits()->SetLocale();
178 wxString
wxAppConsoleBase::GetAppName() const
180 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
);
190 #endif // !__WXPALMOS__
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()
224 // ----------------------------------------------------------------------------
226 // ----------------------------------------------------------------------------
228 bool wxAppConsoleBase::OnInit()
230 #if wxUSE_CMDLINE_PARSER
231 wxCmdLineParser
parser(argc
, argv
);
233 OnInitCmdLine(parser
);
236 switch ( parser
.Parse(false /* don't show usage */) )
239 cont
= OnCmdLineHelp(parser
);
243 cont
= OnCmdLineParsed(parser
);
247 cont
= OnCmdLineError(parser
);
253 #endif // wxUSE_CMDLINE_PARSER
258 int wxAppConsoleBase::OnRun()
263 int wxAppConsoleBase::OnExit()
266 // delete the config object if any (don't use Get() here, but Set()
267 // because Get() could create a new config object)
268 delete wxConfigBase::Set(NULL
);
269 #endif // wxUSE_CONFIG
274 void wxAppConsoleBase::Exit()
276 if (m_mainLoop
!= NULL
)
282 // ----------------------------------------------------------------------------
284 // ----------------------------------------------------------------------------
286 wxAppTraits
*wxAppConsoleBase::CreateTraits()
288 return new wxConsoleAppTraits
;
291 wxAppTraits
*wxAppConsoleBase::GetTraits()
293 // FIXME-MT: protect this with a CS?
296 m_traits
= CreateTraits();
298 wxASSERT_MSG( m_traits
, wxT("wxApp::CreateTraits() failed?") );
305 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
307 wxAppConsole
* const app
= GetInstance();
308 return app
? app
->GetTraits() : NULL
;
311 // ----------------------------------------------------------------------------
312 // wxEventLoop redirection
313 // ----------------------------------------------------------------------------
315 int wxAppConsoleBase::MainLoop()
317 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
319 return m_mainLoop
? m_mainLoop
->Run() : -1;
322 void wxAppConsoleBase::ExitMainLoop()
324 // we should exit from the main event loop, not just any currently active
325 // (e.g. modal dialog) event loop
326 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
332 bool wxAppConsoleBase::Pending()
334 // use the currently active message loop here, not m_mainLoop, because if
335 // we're showing a modal dialog (with its own event loop) currently the
336 // main event loop is not running anyhow
337 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
339 return loop
&& loop
->Pending();
342 bool wxAppConsoleBase::Dispatch()
344 // see comment in Pending()
345 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
347 return loop
&& loop
->Dispatch();
350 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
352 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
354 return loop
&& loop
->Yield(onlyIfNeeded
);
357 void wxAppConsoleBase::WakeUpIdle()
359 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
365 bool wxAppConsoleBase::ProcessIdle()
367 // synthesize an idle event and check if more of them are needed
369 event
.SetEventObject(this);
373 // flush the logged messages if any (do this after processing the events
374 // which could have logged new messages)
375 wxLog::FlushActive();
378 return event
.MoreRequested();
381 bool wxAppConsoleBase::UsesEventLoop() const
383 // in console applications we don't know whether we're going to have an
384 // event loop so assume we won't -- unless we already have one running
385 return wxEventLoopBase::GetActive() != NULL
;
388 // ----------------------------------------------------------------------------
390 // ----------------------------------------------------------------------------
393 bool wxAppConsoleBase::IsMainLoopRunning()
395 const wxAppConsole
* const app
= GetInstance();
397 return app
&& app
->m_mainLoop
!= NULL
;
400 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
402 // process the events normally by default
406 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
408 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
410 // move the handler from the list of handlers with processable pending events
411 // to the list of handlers with pending events which needs to be processed later
412 m_handlersWithPendingEvents
.Remove(toDelay
);
414 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
415 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
417 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
420 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
422 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
424 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
426 m_handlersWithPendingEvents
.Remove(toRemove
);
428 // check that the handler was present only once in the list
429 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
430 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
432 //else: it wasn't in this list at all, it's ok
434 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
436 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
438 // check that the handler was present only once in the list
439 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
440 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
442 //else: it wasn't in this list at all, it's ok
444 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
447 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
449 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
451 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
452 m_handlersWithPendingEvents
.Add(toAppend
);
454 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
457 bool wxAppConsoleBase::HasPendingEvents() const
459 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
461 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
463 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
468 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
470 m_bDoPendingEventProcessing
= false;
473 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
475 m_bDoPendingEventProcessing
= true;
478 void wxAppConsoleBase::ProcessPendingEvents()
480 if ( m_bDoPendingEventProcessing
)
482 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
484 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
485 "this helper list should be empty" );
487 // iterate until the list becomes empty: the handlers remove themselves
488 // from it when they don't have any more pending events
489 while (!m_handlersWithPendingEvents
.IsEmpty())
491 // In ProcessPendingEvents(), new handlers might be added
492 // and we can safely leave the critical section here.
493 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
495 // NOTE: we always call ProcessPendingEvents() on the first event handler
496 // with pending events because handlers auto-remove themselves
497 // from this list (see RemovePendingEventHandler) if they have no
498 // more pending events.
499 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
501 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
504 // now the wxHandlersWithPendingEvents is surely empty; however some event
505 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
506 // because of a selective wxYield call in progress.
507 // Now we need to move them back to wxHandlersWithPendingEvents so the next
508 // call to this function has the chance of processing them:
509 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
511 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
512 m_handlersWithPendingDelayedEvents
.Clear();
515 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
518 // Garbage collect all objects previously scheduled for destruction.
519 DeletePendingObjects();
522 void wxAppConsoleBase::DeletePendingEvents()
524 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
526 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
527 "this helper list should be empty" );
529 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
530 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
532 m_handlersWithPendingEvents
.Clear();
534 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
537 // ----------------------------------------------------------------------------
538 // delayed objects destruction
539 // ----------------------------------------------------------------------------
541 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
543 return wxPendingDelete
.Member(object
);
546 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
548 if ( !UsesEventLoop() )
550 // we won't be able to delete it later so do it right now
554 //else: we either already have or will soon start an event loop
556 if ( !wxPendingDelete
.Member(object
) )
557 wxPendingDelete
.Append(object
);
560 void wxAppConsoleBase::DeletePendingObjects()
562 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
565 wxObject
*obj
= node
->GetData();
567 // remove it from the list first so that if we get back here somehow
568 // during the object deletion (e.g. wxYield called from its dtor) we
569 // wouldn't try to delete it the second time
570 if ( wxPendingDelete
.Member(obj
) )
571 wxPendingDelete
.Erase(node
);
575 // Deleting one object may have deleted other pending
576 // objects, so start from beginning of list again.
577 node
= wxPendingDelete
.GetFirst();
581 // ----------------------------------------------------------------------------
582 // exception handling
583 // ----------------------------------------------------------------------------
588 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
589 wxEventFunction func
,
590 wxEvent
& event
) const
592 // by default, simply call the handler
593 (handler
->*func
)(event
);
596 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
597 wxEventFunctor
& functor
,
598 wxEvent
& event
) const
600 // If the functor holds a method then, for backward compatibility, call
602 wxEventFunction eventFunction
= functor
.GetEvtMethod();
605 HandleEvent(handler
, eventFunction
, event
);
607 functor(handler
, event
);
610 void wxAppConsoleBase::OnUnhandledException()
613 // we're called from an exception handler so we can re-throw the exception
614 // to recover its type
621 catch ( std::exception
& e
)
623 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
624 typeid(e
).name(), e
.what());
629 what
= "unknown exception";
632 wxMessageOutputBest().Printf(
633 "*** Caught unhandled %s; terminating\n", what
635 #endif // __WXDEBUG__
638 // ----------------------------------------------------------------------------
639 // exceptions support
640 // ----------------------------------------------------------------------------
642 bool wxAppConsoleBase::OnExceptionInMainLoop()
646 // some compilers are too stupid to know that we never return after throw
647 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
652 #endif // wxUSE_EXCEPTIONS
654 // ----------------------------------------------------------------------------
656 // ----------------------------------------------------------------------------
658 #if wxUSE_CMDLINE_PARSER
660 #define OPTION_VERBOSE "verbose"
662 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
664 // the standard command line options
665 static const wxCmdLineEntryDesc cmdLineDesc
[] =
671 gettext_noop("show this help message"),
673 wxCMD_LINE_OPTION_HELP
681 gettext_noop("generate verbose log messages"),
691 parser
.SetDesc(cmdLineDesc
);
694 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
697 if ( parser
.Found(OPTION_VERBOSE
) )
699 wxLog::SetVerbose(true);
708 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
715 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
722 #endif // wxUSE_CMDLINE_PARSER
724 // ----------------------------------------------------------------------------
726 // ----------------------------------------------------------------------------
729 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
730 const char *componentName
)
732 #if 0 // can't use wxLogTrace, not up and running yet
733 printf("checking build options object '%s' (ptr %p) in '%s'\n",
734 optionsSignature
, optionsSignature
, componentName
);
737 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
739 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
740 wxString prog
= wxString::FromAscii(optionsSignature
);
741 wxString progName
= wxString::FromAscii(componentName
);
744 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
745 lib
.c_str(), progName
.c_str(), prog
.c_str());
747 wxLogFatalError(msg
.c_str());
749 // normally wxLogFatalError doesn't return
756 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
763 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
765 // this function is still present even in debug level 0 build for ABI
766 // compatibility reasons but is never called there and so can simply do
773 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
776 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
781 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
784 // ============================================================================
785 // other classes implementations
786 // ============================================================================
788 // ----------------------------------------------------------------------------
789 // wxConsoleAppTraitsBase
790 // ----------------------------------------------------------------------------
794 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
796 return new wxLogStderr
;
801 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
803 return new wxMessageOutputStderr
;
808 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
810 return (wxFontMapper
*)new wxFontMapperBase
;
813 #endif // wxUSE_FONTMAP
815 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
817 // console applications don't use renderers
821 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
823 return wxAppTraitsBase::ShowAssertDialog(msg
);
826 bool wxConsoleAppTraitsBase::HasStderr()
828 // console applications always have stderr, even under Mac/Windows
832 // ----------------------------------------------------------------------------
834 // ----------------------------------------------------------------------------
837 void wxAppTraitsBase::SetLocale()
839 wxSetlocale(LC_ALL
, "");
840 wxUpdateLocaleIsUtf8();
845 void wxMutexGuiEnterImpl();
846 void wxMutexGuiLeaveImpl();
848 void wxAppTraitsBase::MutexGuiEnter()
850 wxMutexGuiEnterImpl();
853 void wxAppTraitsBase::MutexGuiLeave()
855 wxMutexGuiLeaveImpl();
858 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
860 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
862 traits
->MutexGuiEnter();
865 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
867 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
869 traits
->MutexGuiLeave();
871 #endif // wxUSE_THREADS
873 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
878 #if wxUSE_STACKWALKER
879 const wxString stackTrace
= GetAssertStackTrace();
880 if ( !stackTrace
.empty() )
882 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
884 wxMessageOutputDebug().Output(msg
);
886 #endif // wxUSE_STACKWALKER
888 return DoShowAssertDialog(msgOriginal
+ msg
);
889 #else // !wxDEBUG_LEVEL
890 wxUnusedVar(msgOriginal
);
893 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
896 #if wxUSE_STACKWALKER
897 wxString
wxAppTraitsBase::GetAssertStackTrace()
901 #if !defined(__WXMSW__)
902 // on Unix stack frame generation may take some time, depending on the
903 // size of the executable mainly... warn the user that we are working
904 wxFprintf(stderr
, "Collecting stack trace information, please wait...");
911 class StackDump
: public wxStackWalker
916 const wxString
& GetStackTrace() const { return m_stackTrace
; }
919 virtual void OnStackFrame(const wxStackFrame
& frame
)
921 m_stackTrace
<< wxString::Format
924 wx_truncate_cast(int, frame
.GetLevel())
927 wxString name
= frame
.GetName();
930 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
934 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
937 if ( frame
.HasSourceLocation() )
939 m_stackTrace
<< wxT('\t')
940 << frame
.GetFileName()
945 m_stackTrace
<< wxT('\n');
949 wxString m_stackTrace
;
952 // don't show more than maxLines or we could get a dialog too tall to be
953 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
954 // characters it is still only 300 pixels...
955 static const int maxLines
= 20;
958 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
959 stackTrace
= dump
.GetStackTrace();
961 const int count
= stackTrace
.Freq(wxT('\n'));
962 for ( int i
= 0; i
< count
- maxLines
; i
++ )
963 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
966 #else // !wxDEBUG_LEVEL
967 // this function is still present for ABI-compatibility even in debug level
968 // 0 build but is not used there and so can simply do nothing
970 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
972 #endif // wxUSE_STACKWALKER
975 // ============================================================================
976 // global functions implementation
977 // ============================================================================
987 // what else can we do?
996 wxTheApp
->WakeUpIdle();
998 //else: do nothing, what can we do?
1001 // wxASSERT() helper
1002 bool wxAssertIsEqual(int x
, int y
)
1009 // break into the debugger
1012 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1014 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1016 #elif defined(__UNIX__)
1023 // default assert handler
1025 wxDefaultAssertHandler(const wxString
& file
,
1027 const wxString
& func
,
1028 const wxString
& cond
,
1029 const wxString
& msg
)
1031 // If this option is set, we should abort immediately when assert happens.
1032 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1036 static int s_bInAssert
= 0;
1038 wxRecursionGuard
guard(s_bInAssert
);
1039 if ( guard
.IsInside() )
1041 // can't use assert here to avoid infinite loops, so just trap
1049 // by default, show the assert dialog box -- we can't customize this
1051 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1055 // let the app process it as it wants
1056 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1057 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1058 cond
.c_str(), msg
.c_str());
1062 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1064 void wxSetDefaultAssertHandler()
1066 wxTheAssertHandler
= wxDefaultAssertHandler
;
1069 void wxOnAssert(const wxString
& file
,
1071 const wxString
& func
,
1072 const wxString
& cond
,
1073 const wxString
& msg
)
1075 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1078 void wxOnAssert(const wxString
& file
,
1080 const wxString
& func
,
1081 const wxString
& cond
)
1083 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1086 void wxOnAssert(const wxChar
*file
,
1092 // this is the backwards-compatible version (unless we don't use Unicode)
1093 // so it could be called directly from the user code and this might happen
1094 // even when wxTheAssertHandler is NULL
1096 if ( wxTheAssertHandler
)
1097 #endif // wxUSE_UNICODE
1098 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1101 void wxOnAssert(const char *file
,
1105 const wxString
& msg
)
1107 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1110 void wxOnAssert(const char *file
,
1114 const wxCStrData
& msg
)
1116 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1120 void wxOnAssert(const char *file
,
1125 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1128 void wxOnAssert(const char *file
,
1134 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1137 void wxOnAssert(const char *file
,
1143 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1145 #endif // wxUSE_UNICODE
1147 #endif // wxDEBUG_LEVEL
1149 // ============================================================================
1150 // private functions implementation
1151 // ============================================================================
1155 static void LINKAGEMODE
SetTraceMasks()
1159 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1161 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1162 while ( tkn
.HasMoreTokens() )
1163 wxLog::AddTraceMask(tkn
.GetNextToken());
1168 #endif // __WXDEBUG__
1173 bool DoShowAssertDialog(const wxString
& msg
)
1175 // under MSW we can show the dialog even in the console mode
1176 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1177 wxString
msgDlg(msg
);
1179 // this message is intentionally not translated -- it is for developers
1180 // only -- and the less code we use here, less is the danger of recursively
1181 // asserting and dying
1182 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1183 wxT("You can also choose [Cancel] to suppress ")
1184 wxT("further warnings.");
1186 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), wxT("wxWidgets Debug Alert"),
1187 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1197 //case IDNO: nothing to do
1201 #endif // __WXMSW__/!__WXMSW__
1203 // continue with the asserts by default
1207 // show the standard assert dialog
1209 void ShowAssertDialog(const wxString
& file
,
1211 const wxString
& func
,
1212 const wxString
& cond
,
1213 const wxString
& msgUser
,
1214 wxAppTraits
*traits
)
1216 // this variable can be set to true to suppress "assert failure" messages
1217 static bool s_bNoAsserts
= false;
1222 // make life easier for people using VC++ IDE by using this format: like
1223 // this, clicking on the message will take us immediately to the place of
1224 // the failed assert
1225 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1227 // add the function name, if any
1228 if ( !func
.empty() )
1229 msg
<< wxT(" in ") << func
<< wxT("()");
1231 // and the message itself
1232 if ( !msgUser
.empty() )
1234 msg
<< wxT(": ") << msgUser
;
1236 else // no message given
1242 // if we are not in the main thread, output the assert directly and trap
1243 // since dialogs cannot be displayed
1244 if ( !wxThread::IsMain() )
1246 msg
+= wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1248 #endif // wxUSE_THREADS
1250 // log the assert in any case
1251 wxMessageOutputDebug().Output(msg
);
1253 if ( !s_bNoAsserts
)
1257 // delegate showing assert dialog (if possible) to that class
1258 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1260 else // no traits object
1262 // fall back to the function of last resort
1263 s_bNoAsserts
= DoShowAssertDialog(msg
);
1268 #endif // wxDEBUG_LEVEL