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/ptr_scpd.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"
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
& szFile
,
97 const wxString
& szFunc
,
98 const wxString
& szCond
,
99 const wxString
& szMsg
,
100 wxAppTraits
*traits
= NULL
);
102 // turn on the trace masks specified in the env variable WXTRACE
103 static void LINKAGEMODE
SetTraceMasks();
104 #endif // __WXDEBUG__
106 // ----------------------------------------------------------------------------
108 // ----------------------------------------------------------------------------
110 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
112 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
114 wxSocketManager
*wxAppTraitsBase::ms_manager
= NULL
;
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
120 // this defines wxEventLoopPtr
121 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
123 // ============================================================================
124 // wxAppConsoleBase implementation
125 // ============================================================================
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
131 wxAppConsoleBase::wxAppConsoleBase()
136 ms_appInstance
= static_cast<wxAppConsole
*>(this);
141 // In unicode mode the SetTraceMasks call can cause an apptraits to be
142 // created, but since we are still in the constructor the wrong kind will
143 // be created for GUI apps. Destroy it so it can be created again later.
150 wxAppConsoleBase::~wxAppConsoleBase()
155 // ----------------------------------------------------------------------------
156 // initilization/cleanup
157 // ----------------------------------------------------------------------------
159 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc
), wxChar
**argv
)
162 GetTraits()->SetLocale();
166 wxHandlersWithPendingEventsLocker
= new wxCriticalSection
;
170 if ( m_appName
.empty() && argv
&& argv
[0] )
172 // the application name is, by default, the name of its executable file
173 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
175 #endif // !__WXPALMOS__
180 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
182 return GetTraits()->CreateEventLoop();
185 void wxAppConsoleBase::CleanUp()
193 delete wxHandlersWithPendingEvents
;
194 wxHandlersWithPendingEvents
= NULL
;
197 delete wxHandlersWithPendingEventsLocker
;
198 wxHandlersWithPendingEventsLocker
= NULL
;
199 #endif // wxUSE_THREADS
202 // ----------------------------------------------------------------------------
204 // ----------------------------------------------------------------------------
206 bool wxAppConsoleBase::OnInit()
208 #if wxUSE_CMDLINE_PARSER
209 wxCmdLineParser
parser(argc
, argv
);
211 OnInitCmdLine(parser
);
214 switch ( parser
.Parse(false /* don't show usage */) )
217 cont
= OnCmdLineHelp(parser
);
221 cont
= OnCmdLineParsed(parser
);
225 cont
= OnCmdLineError(parser
);
231 #endif // wxUSE_CMDLINE_PARSER
236 int wxAppConsoleBase::OnRun()
241 int wxAppConsoleBase::OnExit()
244 // delete the config object if any (don't use Get() here, but Set()
245 // because Get() could create a new config object)
246 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
247 #endif // wxUSE_CONFIG
252 void wxAppConsoleBase::Exit()
254 if (m_mainLoop
!= NULL
)
260 // ----------------------------------------------------------------------------
262 // ----------------------------------------------------------------------------
264 wxAppTraits
*wxAppConsoleBase::CreateTraits()
266 return new wxConsoleAppTraits
;
269 wxAppTraits
*wxAppConsoleBase::GetTraits()
271 // FIXME-MT: protect this with a CS?
274 m_traits
= CreateTraits();
276 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
283 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
285 wxAppConsole
* const app
= GetInstance();
286 return app
? app
->GetTraits() : NULL
;
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
293 int wxAppConsoleBase::MainLoop()
295 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
297 return m_mainLoop
? m_mainLoop
->Run() : -1;
300 void wxAppConsoleBase::ExitMainLoop()
302 // we should exit from the main event loop, not just any currently active
303 // (e.g. modal dialog) event loop
304 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
310 bool wxAppConsoleBase::Pending()
312 // use the currently active message loop here, not m_mainLoop, because if
313 // we're showing a modal dialog (with its own event loop) currently the
314 // main event loop is not running anyhow
315 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
317 return loop
&& loop
->Pending();
320 bool wxAppConsoleBase::Dispatch()
322 // see comment in Pending()
323 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
325 return loop
&& loop
->Dispatch();
328 bool wxAppConsoleBase::HasPendingEvents() const
330 wxENTER_CRIT_SECT( *wxHandlersWithPendingEventsLocker
);
332 bool has
= wxHandlersWithPendingEvents
&& !wxHandlersWithPendingEvents
->IsEmpty();
334 wxLEAVE_CRIT_SECT( *wxHandlersWithPendingEventsLocker
);
340 bool wxAppConsoleBase::IsMainLoopRunning()
342 const wxAppConsole
* const app
= GetInstance();
344 return app
&& app
->m_mainLoop
!= NULL
;
347 void wxAppConsoleBase::ProcessPendingEvents()
350 if ( !wxHandlersWithPendingEventsLocker
)
354 wxENTER_CRIT_SECT( *wxHandlersWithPendingEventsLocker
);
356 if (wxHandlersWithPendingEvents
)
358 // iterate until the list becomes empty: the handlers remove themselves
359 // from it when they don't have any more pending events
360 wxList::compatibility_iterator node
= wxHandlersWithPendingEvents
->GetFirst();
363 // In ProcessPendingEvents(), new handlers might be add
364 // and we can safely leave the critical section here.
365 wxLEAVE_CRIT_SECT( *wxHandlersWithPendingEventsLocker
);
367 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
368 handler
->ProcessPendingEvents();
370 wxENTER_CRIT_SECT( *wxHandlersWithPendingEventsLocker
);
372 // restart as the iterators could have been invalidated
373 node
= wxHandlersWithPendingEvents
->GetFirst();
377 wxLEAVE_CRIT_SECT( *wxHandlersWithPendingEventsLocker
);
380 void wxAppConsoleBase::WakeUpIdle()
383 m_mainLoop
->WakeUp();
386 bool wxAppConsoleBase::ProcessIdle()
388 // process pending wx events before sending idle events
389 ProcessPendingEvents();
393 event
.SetEventObject(this);
395 return event
.MoreRequested();
398 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
400 // process the events normally by default
404 // ----------------------------------------------------------------------------
405 // exception handling
406 // ----------------------------------------------------------------------------
411 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
412 wxEventFunction func
,
413 wxEvent
& event
) const
415 // by default, simply call the handler
416 (handler
->*func
)(event
);
419 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
420 wxEventFunctor
& functor
,
421 wxEvent
& event
) const
423 // If the functor holds a method then, for backward compatibility, call
425 wxEventFunction eventFunction
= functor
.GetMethod();
428 HandleEvent(handler
, eventFunction
, event
);
430 functor(handler
, event
);
433 void wxAppConsoleBase::OnUnhandledException()
436 // we're called from an exception handler so we can re-throw the exception
437 // to recover its type
444 catch ( std::exception
& e
)
446 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
447 typeid(e
).name(), e
.what());
452 what
= "unknown exception";
455 wxMessageOutputBest().Printf(
456 "*** Caught unhandled %s; terminating\n", what
458 #endif // __WXDEBUG__
461 // ----------------------------------------------------------------------------
462 // exceptions support
463 // ----------------------------------------------------------------------------
465 bool wxAppConsoleBase::OnExceptionInMainLoop()
469 // some compilers are too stupid to know that we never return after throw
470 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
475 #endif // wxUSE_EXCEPTIONS
477 // ----------------------------------------------------------------------------
479 // ----------------------------------------------------------------------------
481 #if wxUSE_CMDLINE_PARSER
483 #define OPTION_VERBOSE "verbose"
485 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
487 // the standard command line options
488 static const wxCmdLineEntryDesc cmdLineDesc
[] =
494 gettext_noop("show this help message"),
496 wxCMD_LINE_OPTION_HELP
504 gettext_noop("generate verbose log messages"),
514 parser
.SetDesc(cmdLineDesc
);
517 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
520 if ( parser
.Found(OPTION_VERBOSE
) )
522 wxLog::SetVerbose(true);
531 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
538 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
545 #endif // wxUSE_CMDLINE_PARSER
547 // ----------------------------------------------------------------------------
549 // ----------------------------------------------------------------------------
552 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
553 const char *componentName
)
555 #if 0 // can't use wxLogTrace, not up and running yet
556 printf("checking build options object '%s' (ptr %p) in '%s'\n",
557 optionsSignature
, optionsSignature
, componentName
);
560 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
562 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
563 wxString prog
= wxString::FromAscii(optionsSignature
);
564 wxString progName
= wxString::FromAscii(componentName
);
567 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
568 lib
.c_str(), progName
.c_str(), prog
.c_str());
570 wxLogFatalError(msg
.c_str());
572 // normally wxLogFatalError doesn't return
582 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
588 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
591 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
596 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
599 #endif // __WXDEBUG__
601 // ============================================================================
602 // other classes implementations
603 // ============================================================================
605 // ----------------------------------------------------------------------------
606 // wxConsoleAppTraitsBase
607 // ----------------------------------------------------------------------------
611 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
613 return new wxLogStderr
;
618 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
620 return new wxMessageOutputStderr
;
625 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
627 return (wxFontMapper
*)new wxFontMapperBase
;
630 #endif // wxUSE_FONTMAP
632 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
634 // console applications don't use renderers
639 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
641 return wxAppTraitsBase::ShowAssertDialog(msg
);
645 bool wxConsoleAppTraitsBase::HasStderr()
647 // console applications always have stderr, even under Mac/Windows
651 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
656 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
661 // ----------------------------------------------------------------------------
663 // ----------------------------------------------------------------------------
666 void wxAppTraitsBase::SetLocale()
668 wxSetlocale(LC_ALL
, "");
669 wxUpdateLocaleIsUtf8();
674 void wxMutexGuiEnterImpl();
675 void wxMutexGuiLeaveImpl();
677 void wxAppTraitsBase::MutexGuiEnter()
679 wxMutexGuiEnterImpl();
682 void wxAppTraitsBase::MutexGuiLeave()
684 wxMutexGuiLeaveImpl();
687 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
689 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
691 traits
->MutexGuiEnter();
694 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
696 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
698 traits
->MutexGuiLeave();
700 #endif // wxUSE_THREADS
704 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
706 wxString msg
= msgOriginal
;
708 #if wxUSE_STACKWALKER
709 #if !defined(__WXMSW__)
710 // on Unix stack frame generation may take some time, depending on the
711 // size of the executable mainly... warn the user that we are working
712 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
716 const wxString stackTrace
= GetAssertStackTrace();
717 if ( !stackTrace
.empty() )
718 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
719 #endif // wxUSE_STACKWALKER
721 return DoShowAssertDialog(msg
);
724 #if wxUSE_STACKWALKER
725 wxString
wxAppTraitsBase::GetAssertStackTrace()
729 class StackDump
: public wxStackWalker
734 const wxString
& GetStackTrace() const { return m_stackTrace
; }
737 virtual void OnStackFrame(const wxStackFrame
& frame
)
739 m_stackTrace
<< wxString::Format
742 wx_truncate_cast(int, frame
.GetLevel())
745 wxString name
= frame
.GetName();
748 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
752 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
755 if ( frame
.HasSourceLocation() )
757 m_stackTrace
<< _T('\t')
758 << frame
.GetFileName()
763 m_stackTrace
<< _T('\n');
767 wxString m_stackTrace
;
770 // don't show more than maxLines or we could get a dialog too tall to be
771 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
772 // characters it is still only 300 pixels...
773 static const int maxLines
= 20;
776 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
777 stackTrace
= dump
.GetStackTrace();
779 const int count
= stackTrace
.Freq(wxT('\n'));
780 for ( int i
= 0; i
< count
- maxLines
; i
++ )
781 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
785 #endif // wxUSE_STACKWALKER
788 #endif // __WXDEBUG__
790 // ============================================================================
791 // global functions implementation
792 // ============================================================================
802 // what else can we do?
811 wxTheApp
->WakeUpIdle();
813 //else: do nothing, what can we do?
819 bool wxAssertIsEqual(int x
, int y
)
824 // break into the debugger
827 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
829 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
831 #elif defined(__UNIX__)
838 // this function is called when an assert fails
839 static void wxDoOnAssert(const wxString
& szFile
,
841 const wxString
& szFunc
,
842 const wxString
& szCond
,
843 const wxString
& szMsg
= wxEmptyString
)
846 static int s_bInAssert
= 0;
848 wxRecursionGuard
guard(s_bInAssert
);
849 if ( guard
.IsInside() )
851 // can't use assert here to avoid infinite loops, so just trap
859 // by default, show the assert dialog box -- we can't customize this
861 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
865 // let the app process it as it wants
866 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
867 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
868 szCond
.c_str(), szMsg
.c_str());
872 void wxOnAssert(const wxString
& szFile
,
874 const wxString
& szFunc
,
875 const wxString
& szCond
,
876 const wxString
& szMsg
)
878 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
881 void wxOnAssert(const wxString
& szFile
,
883 const wxString
& szFunc
,
884 const wxString
& szCond
)
886 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
889 void wxOnAssert(const wxChar
*szFile
,
892 const wxChar
*szCond
,
895 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
898 void wxOnAssert(const char *szFile
,
902 const wxString
& szMsg
)
904 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
907 void wxOnAssert(const char *szFile
,
911 const wxCStrData
& msg
)
913 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, msg
);
917 void wxOnAssert(const char *szFile
,
922 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
925 void wxOnAssert(const char *szFile
,
931 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
934 void wxOnAssert(const char *szFile
,
940 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
942 #endif // wxUSE_UNICODE
944 #endif // __WXDEBUG__
946 // ============================================================================
947 // private functions implementation
948 // ============================================================================
952 static void LINKAGEMODE
SetTraceMasks()
956 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
958 wxStringTokenizer
tkn(mask
, wxT(",;:"));
959 while ( tkn
.HasMoreTokens() )
960 wxLog::AddTraceMask(tkn
.GetNextToken());
966 bool DoShowAssertDialog(const wxString
& msg
)
968 // under MSW we can show the dialog even in the console mode
969 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
970 wxString
msgDlg(msg
);
972 // this message is intentionally not translated -- it is for
974 msgDlg
+= wxT("\nDo you want to stop the program?\n")
975 wxT("You can also choose [Cancel] to suppress ")
976 wxT("further warnings.");
978 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), _T("wxWidgets Debug Alert"),
979 MB_YESNOCANCEL
| MB_ICONSTOP
) )
989 //case IDNO: nothing to do
992 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
995 // TODO: ask the user to enter "Y" or "N" on the console?
997 #endif // __WXMSW__/!__WXMSW__
999 // continue with the asserts
1003 // show the assert modal dialog
1005 void ShowAssertDialog(const wxString
& szFile
,
1007 const wxString
& szFunc
,
1008 const wxString
& szCond
,
1009 const wxString
& szMsg
,
1010 wxAppTraits
*traits
)
1012 // this variable can be set to true to suppress "assert failure" messages
1013 static bool s_bNoAsserts
= false;
1018 // make life easier for people using VC++ IDE by using this format: like
1019 // this, clicking on the message will take us immediately to the place of
1020 // the failed assert
1021 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
1023 // add the function name, if any
1024 if ( !szFunc
.empty() )
1025 msg
<< _T(" in ") << szFunc
<< _T("()");
1027 // and the message itself
1028 if ( !szMsg
.empty() )
1030 msg
<< _T(": ") << szMsg
;
1032 else // no message given
1038 // if we are not in the main thread, output the assert directly and trap
1039 // since dialogs cannot be displayed
1040 if ( !wxThread::IsMain() )
1042 msg
+= wxT(" [in child thread]");
1044 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1046 OutputDebugString(msg
.wx_str());
1049 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1052 // He-e-e-e-elp!! we're asserting in a child thread
1056 #endif // wxUSE_THREADS
1058 if ( !s_bNoAsserts
)
1060 // send it to the normal log destination
1061 wxLogDebug(_T("%s"), msg
.c_str());
1065 // delegate showing assert dialog (if possible) to that class
1066 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1068 else // no traits object
1070 // fall back to the function of last resort
1071 s_bNoAsserts
= DoShowAssertDialog(msg
);
1076 #endif // __WXDEBUG__