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/tokenzr.h"
47 #include "wx/thread.h"
49 #if wxUSE_EXCEPTIONS && wxUSE_STL
55 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
56 #include <signal.h> // for SIGTRAP used by wxTrap()
60 #endif // ! __WXPALMOS5__
63 #include "wx/fontmap.h"
64 #endif // wxUSE_FONTMAP
68 #include "wx/stackwalk.h"
70 #include "wx/msw/debughlp.h"
72 #endif // wxUSE_STACKWALKER
74 #include "wx/recguard.h"
75 #endif // wxDEBUG_LEVEL
77 // wxABI_VERSION can be defined when compiling applications but it should be
78 // left undefined when compiling the library itself, it is then set to its
79 // default value in version.h
80 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
81 #error "wxABI_VERSION should not be defined when compiling the library"
84 // ----------------------------------------------------------------------------
85 // private functions prototypes
86 // ----------------------------------------------------------------------------
89 // really just show the assert dialog
90 static bool DoShowAssertDialog(const wxString
& msg
);
92 // prepare for showing the assert dialog, use the given traits or
93 // DoShowAssertDialog() as last fallback to really show it
95 void ShowAssertDialog(const wxString
& file
,
100 wxAppTraits
*traits
= NULL
);
101 #endif // wxDEBUG_LEVEL
104 // turn on the trace masks specified in the env variable WXTRACE
105 static void LINKAGEMODE
SetTraceMasks();
106 #endif // __WXDEBUG__
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
112 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
114 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
116 wxSocketManager
*wxAppTraitsBase::ms_manager
= NULL
;
118 WXDLLIMPEXP_DATA_BASE(wxList
) wxPendingDelete
;
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 // this defines wxEventLoopPtr
125 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
127 // ============================================================================
128 // wxAppConsoleBase implementation
129 // ============================================================================
131 // ----------------------------------------------------------------------------
133 // ----------------------------------------------------------------------------
135 wxAppConsoleBase::wxAppConsoleBase()
139 m_bDoPendingEventProcessing
= true;
141 ms_appInstance
= static_cast<wxAppConsole
*>(this);
146 // In unicode mode the SetTraceMasks call can cause an apptraits to be
147 // created, but since we are still in the constructor the wrong kind will
148 // be created for GUI apps. Destroy it so it can be created again later.
155 wxAppConsoleBase::~wxAppConsoleBase()
160 // ----------------------------------------------------------------------------
161 // initialization/cleanup
162 // ----------------------------------------------------------------------------
164 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc
), wxChar
**WXUNUSED(argv
))
167 GetTraits()->SetLocale();
173 wxString
wxAppConsoleBase::GetAppName() const
175 wxString name
= m_appName
;
181 // the application name is, by default, the name of its executable file
182 wxFileName::SplitPath(argv
[0], NULL
, &name
, NULL
);
185 #endif // !__WXPALMOS__
189 wxString
wxAppConsoleBase::GetAppDisplayName() const
191 // use the explicitly provided display name, if any
192 if ( !m_appDisplayName
.empty() )
193 return m_appDisplayName
;
195 // if the application name was explicitly set, use it as is as capitalizing
196 // it won't always produce good results
197 if ( !m_appName
.empty() )
200 // if neither is set, use the capitalized version of the program file as
201 // it's the most reasonable default
202 return GetAppName().Capitalize();
205 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
207 return GetTraits()->CreateEventLoop();
210 void wxAppConsoleBase::CleanUp()
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 int wxAppConsoleBase::OnExit()
261 // delete the config object if any (don't use Get() here, but Set()
262 // because Get() could create a new config object)
263 delete wxConfigBase::Set(NULL
);
264 #endif // wxUSE_CONFIG
269 void wxAppConsoleBase::Exit()
271 if (m_mainLoop
!= NULL
)
277 // ----------------------------------------------------------------------------
279 // ----------------------------------------------------------------------------
281 wxAppTraits
*wxAppConsoleBase::CreateTraits()
283 return new wxConsoleAppTraits
;
286 wxAppTraits
*wxAppConsoleBase::GetTraits()
288 // FIXME-MT: protect this with a CS?
291 m_traits
= CreateTraits();
293 wxASSERT_MSG( m_traits
, wxT("wxApp::CreateTraits() failed?") );
300 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
302 wxAppConsole
* const app
= GetInstance();
303 return app
? app
->GetTraits() : NULL
;
306 // ----------------------------------------------------------------------------
307 // wxEventLoop redirection
308 // ----------------------------------------------------------------------------
310 int wxAppConsoleBase::MainLoop()
312 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
314 return m_mainLoop
? m_mainLoop
->Run() : -1;
317 void wxAppConsoleBase::ExitMainLoop()
319 // we should exit from the main event loop, not just any currently active
320 // (e.g. modal dialog) event loop
321 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
327 bool wxAppConsoleBase::Pending()
329 // use the currently active message loop here, not m_mainLoop, because if
330 // we're showing a modal dialog (with its own event loop) currently the
331 // main event loop is not running anyhow
332 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
334 return loop
&& loop
->Pending();
337 bool wxAppConsoleBase::Dispatch()
339 // see comment in Pending()
340 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
342 return loop
&& loop
->Dispatch();
345 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
347 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
349 return loop
&& loop
->Yield(onlyIfNeeded
);
352 void wxAppConsoleBase::WakeUpIdle()
354 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
360 bool wxAppConsoleBase::ProcessIdle()
362 // synthesize an idle event and check if more of them are needed
364 event
.SetEventObject(this);
368 // flush the logged messages if any (do this after processing the events
369 // which could have logged new messages)
370 wxLog::FlushActive();
373 return event
.MoreRequested();
376 bool wxAppConsoleBase::UsesEventLoop() const
378 // in console applications we don't know whether we're going to have an
379 // event loop so assume we won't -- unless we already have one running
380 return wxEventLoopBase::GetActive() != NULL
;
383 // ----------------------------------------------------------------------------
385 // ----------------------------------------------------------------------------
388 bool wxAppConsoleBase::IsMainLoopRunning()
390 const wxAppConsole
* const app
= GetInstance();
392 return app
&& app
->m_mainLoop
!= NULL
;
395 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
397 // process the events normally by default
401 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler
* toDelay
)
403 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
405 // move the handler from the list of handlers with processable pending events
406 // to the list of handlers with pending events which needs to be processed later
407 m_handlersWithPendingEvents
.Remove(toDelay
);
409 if (m_handlersWithPendingDelayedEvents
.Index(toDelay
) == wxNOT_FOUND
)
410 m_handlersWithPendingDelayedEvents
.Add(toDelay
);
412 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
415 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler
* toRemove
)
417 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
419 if (m_handlersWithPendingEvents
.Index(toRemove
) != wxNOT_FOUND
)
421 m_handlersWithPendingEvents
.Remove(toRemove
);
423 // check that the handler was present only once in the list
424 wxASSERT_MSG( m_handlersWithPendingEvents
.Index(toRemove
) == wxNOT_FOUND
,
425 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
427 //else: it wasn't in this list at all, it's ok
429 if (m_handlersWithPendingDelayedEvents
.Index(toRemove
) != wxNOT_FOUND
)
431 m_handlersWithPendingDelayedEvents
.Remove(toRemove
);
433 // check that the handler was present only once in the list
434 wxASSERT_MSG( m_handlersWithPendingDelayedEvents
.Index(toRemove
) == wxNOT_FOUND
,
435 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
437 //else: it wasn't in this list at all, it's ok
439 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
442 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler
* toAppend
)
444 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
446 if ( m_handlersWithPendingEvents
.Index(toAppend
) == wxNOT_FOUND
)
447 m_handlersWithPendingEvents
.Add(toAppend
);
449 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
452 bool wxAppConsoleBase::HasPendingEvents() const
454 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
456 bool has
= !m_handlersWithPendingEvents
.IsEmpty();
458 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase
*>(this)->m_handlersWithPendingEventsLocker
);
463 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
465 m_bDoPendingEventProcessing
= false;
468 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
470 m_bDoPendingEventProcessing
= true;
473 void wxAppConsoleBase::ProcessPendingEvents()
475 if ( m_bDoPendingEventProcessing
)
477 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
479 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
480 "this helper list should be empty" );
482 // iterate until the list becomes empty: the handlers remove themselves
483 // from it when they don't have any more pending events
484 while (!m_handlersWithPendingEvents
.IsEmpty())
486 // In ProcessPendingEvents(), new handlers might be added
487 // and we can safely leave the critical section here.
488 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
490 // NOTE: we always call ProcessPendingEvents() on the first event handler
491 // with pending events because handlers auto-remove themselves
492 // from this list (see RemovePendingEventHandler) if they have no
493 // more pending events.
494 m_handlersWithPendingEvents
[0]->ProcessPendingEvents();
496 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
499 // now the wxHandlersWithPendingEvents is surely empty; however some event
500 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
501 // because of a selective wxYield call in progress.
502 // Now we need to move them back to wxHandlersWithPendingEvents so the next
503 // call to this function has the chance of processing them:
504 if (!m_handlersWithPendingDelayedEvents
.IsEmpty())
506 WX_APPEND_ARRAY(m_handlersWithPendingEvents
, m_handlersWithPendingDelayedEvents
);
507 m_handlersWithPendingDelayedEvents
.Clear();
510 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
513 // Garbage collect all objects previously scheduled for destruction.
514 DeletePendingObjects();
517 void wxAppConsoleBase::DeletePendingEvents()
519 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker
);
521 wxCHECK_RET( m_handlersWithPendingDelayedEvents
.IsEmpty(),
522 "this helper list should be empty" );
524 for (unsigned int i
=0; i
<m_handlersWithPendingEvents
.GetCount(); i
++)
525 m_handlersWithPendingEvents
[i
]->DeletePendingEvents();
527 m_handlersWithPendingEvents
.Clear();
529 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker
);
532 // ----------------------------------------------------------------------------
533 // delayed objects destruction
534 // ----------------------------------------------------------------------------
536 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject
*object
) const
538 return wxPendingDelete
.Member(object
);
541 void wxAppConsoleBase::ScheduleForDestruction(wxObject
*object
)
543 if ( !UsesEventLoop() )
545 // we won't be able to delete it later so do it right now
549 //else: we either already have or will soon start an event loop
551 if ( !wxPendingDelete
.Member(object
) )
552 wxPendingDelete
.Append(object
);
555 void wxAppConsoleBase::DeletePendingObjects()
557 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
560 wxObject
*obj
= node
->GetData();
562 // remove it from the list first so that if we get back here somehow
563 // during the object deletion (e.g. wxYield called from its dtor) we
564 // wouldn't try to delete it the second time
565 if ( wxPendingDelete
.Member(obj
) )
566 wxPendingDelete
.Erase(node
);
570 // Deleting one object may have deleted other pending
571 // objects, so start from beginning of list again.
572 node
= wxPendingDelete
.GetFirst();
576 // ----------------------------------------------------------------------------
577 // exception handling
578 // ----------------------------------------------------------------------------
583 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
584 wxEventFunction func
,
585 wxEvent
& event
) const
587 // by default, simply call the handler
588 (handler
->*func
)(event
);
591 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
592 wxEventFunctor
& functor
,
593 wxEvent
& event
) const
595 // If the functor holds a method then, for backward compatibility, call
597 wxEventFunction eventFunction
= functor
.GetEvtMethod();
600 HandleEvent(handler
, eventFunction
, event
);
602 functor(handler
, event
);
605 void wxAppConsoleBase::OnUnhandledException()
608 // we're called from an exception handler so we can re-throw the exception
609 // to recover its type
616 catch ( std::exception
& e
)
618 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
619 typeid(e
).name(), e
.what());
624 what
= "unknown exception";
627 wxMessageOutputBest().Printf(
628 "*** Caught unhandled %s; terminating\n", what
630 #endif // __WXDEBUG__
633 // ----------------------------------------------------------------------------
634 // exceptions support
635 // ----------------------------------------------------------------------------
637 bool wxAppConsoleBase::OnExceptionInMainLoop()
641 // some compilers are too stupid to know that we never return after throw
642 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
647 #endif // wxUSE_EXCEPTIONS
649 // ----------------------------------------------------------------------------
651 // ----------------------------------------------------------------------------
653 #if wxUSE_CMDLINE_PARSER
655 #define OPTION_VERBOSE "verbose"
657 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
659 // the standard command line options
660 static const wxCmdLineEntryDesc cmdLineDesc
[] =
666 gettext_noop("show this help message"),
668 wxCMD_LINE_OPTION_HELP
676 gettext_noop("generate verbose log messages"),
686 parser
.SetDesc(cmdLineDesc
);
689 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
692 if ( parser
.Found(OPTION_VERBOSE
) )
694 wxLog::SetVerbose(true);
703 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
710 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
717 #endif // wxUSE_CMDLINE_PARSER
719 // ----------------------------------------------------------------------------
721 // ----------------------------------------------------------------------------
724 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
725 const char *componentName
)
727 #if 0 // can't use wxLogTrace, not up and running yet
728 printf("checking build options object '%s' (ptr %p) in '%s'\n",
729 optionsSignature
, optionsSignature
, componentName
);
732 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
734 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
735 wxString prog
= wxString::FromAscii(optionsSignature
);
736 wxString progName
= wxString::FromAscii(componentName
);
739 msg
.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
740 lib
.c_str(), progName
.c_str(), prog
.c_str());
742 wxLogFatalError(msg
.c_str());
744 // normally wxLogFatalError doesn't return
751 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
758 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
760 // this function is still present even in debug level 0 build for ABI
761 // compatibility reasons but is never called there and so can simply do
768 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
771 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
776 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
779 // ============================================================================
780 // other classes implementations
781 // ============================================================================
783 // ----------------------------------------------------------------------------
784 // wxConsoleAppTraitsBase
785 // ----------------------------------------------------------------------------
789 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
791 return new wxLogStderr
;
796 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
798 return new wxMessageOutputStderr
;
803 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
805 return (wxFontMapper
*)new wxFontMapperBase
;
808 #endif // wxUSE_FONTMAP
810 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
812 // console applications don't use renderers
816 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
818 return wxAppTraitsBase::ShowAssertDialog(msg
);
821 bool wxConsoleAppTraitsBase::HasStderr()
823 // console applications always have stderr, even under Mac/Windows
827 // ----------------------------------------------------------------------------
829 // ----------------------------------------------------------------------------
832 void wxAppTraitsBase::SetLocale()
834 wxSetlocale(LC_ALL
, "");
835 wxUpdateLocaleIsUtf8();
840 void wxMutexGuiEnterImpl();
841 void wxMutexGuiLeaveImpl();
843 void wxAppTraitsBase::MutexGuiEnter()
845 wxMutexGuiEnterImpl();
848 void wxAppTraitsBase::MutexGuiLeave()
850 wxMutexGuiLeaveImpl();
853 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
855 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
857 traits
->MutexGuiEnter();
860 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
862 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
864 traits
->MutexGuiLeave();
866 #endif // wxUSE_THREADS
868 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
871 wxString msg
= msgOriginal
;
873 #if wxUSE_STACKWALKER
874 #if !defined(__WXMSW__)
875 // on Unix stack frame generation may take some time, depending on the
876 // size of the executable mainly... warn the user that we are working
877 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
881 const wxString stackTrace
= GetAssertStackTrace();
882 if ( !stackTrace
.empty() )
883 msg
<< wxT("\n\nCall stack:\n") << stackTrace
;
884 #endif // wxUSE_STACKWALKER
886 return DoShowAssertDialog(msg
);
887 #else // !wxDEBUG_LEVEL
888 wxUnusedVar(msgOriginal
);
891 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
894 #if wxUSE_STACKWALKER
895 wxString
wxAppTraitsBase::GetAssertStackTrace()
900 class StackDump
: public wxStackWalker
905 const wxString
& GetStackTrace() const { return m_stackTrace
; }
908 virtual void OnStackFrame(const wxStackFrame
& frame
)
910 m_stackTrace
<< wxString::Format
913 wx_truncate_cast(int, frame
.GetLevel())
916 wxString name
= frame
.GetName();
919 m_stackTrace
<< wxString::Format(wxT("%-40s"), name
.c_str());
923 m_stackTrace
<< wxString::Format(wxT("%p"), frame
.GetAddress());
926 if ( frame
.HasSourceLocation() )
928 m_stackTrace
<< wxT('\t')
929 << frame
.GetFileName()
934 m_stackTrace
<< wxT('\n');
938 wxString m_stackTrace
;
941 // don't show more than maxLines or we could get a dialog too tall to be
942 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
943 // characters it is still only 300 pixels...
944 static const int maxLines
= 20;
947 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
948 stackTrace
= dump
.GetStackTrace();
950 const int count
= stackTrace
.Freq(wxT('\n'));
951 for ( int i
= 0; i
< count
- maxLines
; i
++ )
952 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
955 #else // !wxDEBUG_LEVEL
956 // this function is still present for ABI-compatibility even in debug level
957 // 0 build but is not used there and so can simply do nothing
959 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
961 #endif // wxUSE_STACKWALKER
964 // ============================================================================
965 // global functions implementation
966 // ============================================================================
976 // what else can we do?
985 wxTheApp
->WakeUpIdle();
987 //else: do nothing, what can we do?
991 bool wxAssertIsEqual(int x
, int y
)
998 // break into the debugger
1001 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1003 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1005 #elif defined(__UNIX__)
1012 // default assert handler
1014 wxDefaultAssertHandler(const wxString
& file
,
1016 const wxString
& func
,
1017 const wxString
& cond
,
1018 const wxString
& msg
)
1021 static int s_bInAssert
= 0;
1023 wxRecursionGuard
guard(s_bInAssert
);
1024 if ( guard
.IsInside() )
1026 // can't use assert here to avoid infinite loops, so just trap
1034 // by default, show the assert dialog box -- we can't customize this
1036 ShowAssertDialog(file
, line
, func
, cond
, msg
);
1040 // let the app process it as it wants
1041 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1042 wxTheApp
->OnAssertFailure(file
.c_str(), line
, func
.c_str(),
1043 cond
.c_str(), msg
.c_str());
1047 wxAssertHandler_t wxTheAssertHandler
= wxDefaultAssertHandler
;
1049 void wxSetDefaultAssertHandler()
1051 wxTheAssertHandler
= wxDefaultAssertHandler
;
1054 void wxOnAssert(const wxString
& file
,
1056 const wxString
& func
,
1057 const wxString
& cond
,
1058 const wxString
& msg
)
1060 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1063 void wxOnAssert(const wxString
& file
,
1065 const wxString
& func
,
1066 const wxString
& cond
)
1068 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1071 void wxOnAssert(const wxChar
*file
,
1077 // this is the backwards-compatible version (unless we don't use Unicode)
1078 // so it could be called directly from the user code and this might happen
1079 // even when wxTheAssertHandler is NULL
1081 if ( wxTheAssertHandler
)
1082 #endif // wxUSE_UNICODE
1083 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1086 void wxOnAssert(const char *file
,
1090 const wxString
& msg
)
1092 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1095 void wxOnAssert(const char *file
,
1099 const wxCStrData
& msg
)
1101 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1105 void wxOnAssert(const char *file
,
1110 wxTheAssertHandler(file
, line
, func
, cond
, wxString());
1113 void wxOnAssert(const char *file
,
1119 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1122 void wxOnAssert(const char *file
,
1128 wxTheAssertHandler(file
, line
, func
, cond
, msg
);
1130 #endif // wxUSE_UNICODE
1132 #endif // wxDEBUG_LEVEL
1134 // ============================================================================
1135 // private functions implementation
1136 // ============================================================================
1140 static void LINKAGEMODE
SetTraceMasks()
1144 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
1146 wxStringTokenizer
tkn(mask
, wxT(",;:"));
1147 while ( tkn
.HasMoreTokens() )
1148 wxLog::AddTraceMask(tkn
.GetNextToken());
1153 #endif // __WXDEBUG__
1158 bool DoShowAssertDialog(const wxString
& msg
)
1160 // under MSW we can show the dialog even in the console mode
1161 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1162 wxString
msgDlg(msg
);
1164 // this message is intentionally not translated -- it is for developers
1165 // only -- and the less code we use here, less is the danger of recursively
1166 // asserting and dying
1167 msgDlg
+= wxT("\nDo you want to stop the program?\n")
1168 wxT("You can also choose [Cancel] to suppress ")
1169 wxT("further warnings.");
1171 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), wxT("wxWidgets Debug Alert"),
1172 MB_YESNOCANCEL
| MB_ICONSTOP
) )
1182 //case IDNO: nothing to do
1185 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1188 // TODO: ask the user to enter "Y" or "N" on the console?
1190 #endif // __WXMSW__/!__WXMSW__
1192 // continue with the asserts
1196 // show the standard assert dialog
1198 void ShowAssertDialog(const wxString
& file
,
1200 const wxString
& func
,
1201 const wxString
& cond
,
1202 const wxString
& msgUser
,
1203 wxAppTraits
*traits
)
1205 // this variable can be set to true to suppress "assert failure" messages
1206 static bool s_bNoAsserts
= false;
1211 // make life easier for people using VC++ IDE by using this format: like
1212 // this, clicking on the message will take us immediately to the place of
1213 // the failed assert
1214 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), file
, line
, cond
);
1216 // add the function name, if any
1217 if ( !func
.empty() )
1218 msg
<< wxT(" in ") << func
<< wxT("()");
1220 // and the message itself
1221 if ( !msgUser
.empty() )
1223 msg
<< wxT(": ") << msgUser
;
1225 else // no message given
1231 // if we are not in the main thread, output the assert directly and trap
1232 // since dialogs cannot be displayed
1233 if ( !wxThread::IsMain() )
1235 msg
+= wxT(" [in child thread]");
1237 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1239 OutputDebugString(msg
.wx_str());
1242 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1245 // He-e-e-e-elp!! we're asserting in a child thread
1249 #endif // wxUSE_THREADS
1251 if ( !s_bNoAsserts
)
1253 // send it to the normal log destination
1254 wxLogDebug(wxT("%s"), msg
.c_str());
1258 // delegate showing assert dialog (if possible) to that class
1259 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1261 else // no traits object
1263 // fall back to the function of last resort
1264 s_bNoAsserts
= DoShowAssertDialog(msg
);
1269 #endif // wxDEBUG_LEVEL