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"
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 if ( m_appName
.empty() && argv
&& argv
[0] )
168 // the application name is, by default, the name of its executable file
169 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
171 #endif // !__WXPALMOS__
176 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
178 return GetTraits()->CreateEventLoop();
181 void wxAppConsoleBase::CleanUp()
190 // ----------------------------------------------------------------------------
192 // ----------------------------------------------------------------------------
194 bool wxAppConsoleBase::OnInit()
196 #if wxUSE_CMDLINE_PARSER
197 wxCmdLineParser
parser(argc
, argv
);
199 OnInitCmdLine(parser
);
202 switch ( parser
.Parse(false /* don't show usage */) )
205 cont
= OnCmdLineHelp(parser
);
209 cont
= OnCmdLineParsed(parser
);
213 cont
= OnCmdLineError(parser
);
219 #endif // wxUSE_CMDLINE_PARSER
224 int wxAppConsoleBase::OnRun()
229 int wxAppConsoleBase::OnExit()
232 // delete the config object if any (don't use Get() here, but Set()
233 // because Get() could create a new config object)
234 delete wxConfigBase::Set(NULL
);
235 #endif // wxUSE_CONFIG
240 void wxAppConsoleBase::Exit()
242 if (m_mainLoop
!= NULL
)
248 // ----------------------------------------------------------------------------
250 // ----------------------------------------------------------------------------
252 wxAppTraits
*wxAppConsoleBase::CreateTraits()
254 return new wxConsoleAppTraits
;
257 wxAppTraits
*wxAppConsoleBase::GetTraits()
259 // FIXME-MT: protect this with a CS?
262 m_traits
= CreateTraits();
264 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
271 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
273 wxAppConsole
* const app
= GetInstance();
274 return app
? app
->GetTraits() : NULL
;
277 // ----------------------------------------------------------------------------
278 // wxEventLoop redirection
279 // ----------------------------------------------------------------------------
281 int wxAppConsoleBase::MainLoop()
283 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
285 return m_mainLoop
? m_mainLoop
->Run() : -1;
288 void wxAppConsoleBase::ExitMainLoop()
290 // we should exit from the main event loop, not just any currently active
291 // (e.g. modal dialog) event loop
292 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
298 bool wxAppConsoleBase::Pending()
300 // use the currently active message loop here, not m_mainLoop, because if
301 // we're showing a modal dialog (with its own event loop) currently the
302 // main event loop is not running anyhow
303 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
305 return loop
&& loop
->Pending();
308 bool wxAppConsoleBase::Dispatch()
310 // see comment in Pending()
311 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
313 return loop
&& loop
->Dispatch();
316 bool wxAppConsoleBase::HasPendingEvents() const
318 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
320 return loop
&& loop
->HasPendingEvents();
323 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
325 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
327 if (loop
) loop
->SuspendProcessingOfPendingEvents();
330 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
332 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
334 if (loop
) loop
->ResumeProcessingOfPendingEvents();
337 void wxAppConsoleBase::ProcessPendingEvents()
339 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
341 if (loop
) loop
->ProcessPendingEvents();
344 bool wxAppConsoleBase::Yield(bool onlyIfNeeded
)
346 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
348 return loop
&& loop
->Yield(onlyIfNeeded
);
351 void wxAppConsoleBase::WakeUpIdle()
354 m_mainLoop
->WakeUp();
357 bool wxAppConsoleBase::ProcessIdle()
359 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
361 return loop
&& loop
->ProcessIdle();
364 // ----------------------------------------------------------------------------
366 // ----------------------------------------------------------------------------
369 bool wxAppConsoleBase::IsMainLoopRunning()
371 const wxAppConsole
* const app
= GetInstance();
373 return app
&& app
->m_mainLoop
!= NULL
;
376 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
378 // process the events normally by default
382 // ----------------------------------------------------------------------------
383 // exception handling
384 // ----------------------------------------------------------------------------
389 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
390 wxEventFunction func
,
391 wxEvent
& event
) const
393 // by default, simply call the handler
394 (handler
->*func
)(event
);
397 void wxAppConsoleBase::CallEventHandler(wxEvtHandler
*handler
,
398 wxEventFunctor
& functor
,
399 wxEvent
& event
) const
401 // If the functor holds a method then, for backward compatibility, call
403 wxEventFunction eventFunction
= functor
.GetMethod();
406 HandleEvent(handler
, eventFunction
, event
);
408 functor(handler
, event
);
411 void wxAppConsoleBase::OnUnhandledException()
414 // we're called from an exception handler so we can re-throw the exception
415 // to recover its type
422 catch ( std::exception
& e
)
424 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
425 typeid(e
).name(), e
.what());
430 what
= "unknown exception";
433 wxMessageOutputBest().Printf(
434 "*** Caught unhandled %s; terminating\n", what
436 #endif // __WXDEBUG__
439 // ----------------------------------------------------------------------------
440 // exceptions support
441 // ----------------------------------------------------------------------------
443 bool wxAppConsoleBase::OnExceptionInMainLoop()
447 // some compilers are too stupid to know that we never return after throw
448 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
453 #endif // wxUSE_EXCEPTIONS
455 // ----------------------------------------------------------------------------
457 // ----------------------------------------------------------------------------
459 #if wxUSE_CMDLINE_PARSER
461 #define OPTION_VERBOSE "verbose"
463 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
465 // the standard command line options
466 static const wxCmdLineEntryDesc cmdLineDesc
[] =
472 gettext_noop("show this help message"),
474 wxCMD_LINE_OPTION_HELP
482 gettext_noop("generate verbose log messages"),
492 parser
.SetDesc(cmdLineDesc
);
495 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
498 if ( parser
.Found(OPTION_VERBOSE
) )
500 wxLog::SetVerbose(true);
509 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
516 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
523 #endif // wxUSE_CMDLINE_PARSER
525 // ----------------------------------------------------------------------------
527 // ----------------------------------------------------------------------------
530 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
531 const char *componentName
)
533 #if 0 // can't use wxLogTrace, not up and running yet
534 printf("checking build options object '%s' (ptr %p) in '%s'\n",
535 optionsSignature
, optionsSignature
, componentName
);
538 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
540 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
541 wxString prog
= wxString::FromAscii(optionsSignature
);
542 wxString progName
= wxString::FromAscii(componentName
);
545 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
546 lib
.c_str(), progName
.c_str(), prog
.c_str());
548 wxLogFatalError(msg
.c_str());
550 // normally wxLogFatalError doesn't return
559 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
565 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
568 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
573 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
576 #endif // __WXDEBUG__
578 // ============================================================================
579 // other classes implementations
580 // ============================================================================
582 // ----------------------------------------------------------------------------
583 // wxConsoleAppTraitsBase
584 // ----------------------------------------------------------------------------
588 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
590 return new wxLogStderr
;
595 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
597 return new wxMessageOutputStderr
;
602 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
604 return (wxFontMapper
*)new wxFontMapperBase
;
607 #endif // wxUSE_FONTMAP
609 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
611 // console applications don't use renderers
616 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
618 return wxAppTraitsBase::ShowAssertDialog(msg
);
622 bool wxConsoleAppTraitsBase::HasStderr()
624 // console applications always have stderr, even under Mac/Windows
628 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
633 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
638 // ----------------------------------------------------------------------------
640 // ----------------------------------------------------------------------------
643 void wxAppTraitsBase::SetLocale()
645 wxSetlocale(LC_ALL
, "");
646 wxUpdateLocaleIsUtf8();
651 void wxMutexGuiEnterImpl();
652 void wxMutexGuiLeaveImpl();
654 void wxAppTraitsBase::MutexGuiEnter()
656 wxMutexGuiEnterImpl();
659 void wxAppTraitsBase::MutexGuiLeave()
661 wxMutexGuiLeaveImpl();
664 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
666 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
668 traits
->MutexGuiEnter();
671 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
673 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
675 traits
->MutexGuiLeave();
677 #endif // wxUSE_THREADS
681 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
683 wxString msg
= msgOriginal
;
685 #if wxUSE_STACKWALKER
686 #if !defined(__WXMSW__)
687 // on Unix stack frame generation may take some time, depending on the
688 // size of the executable mainly... warn the user that we are working
689 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
693 const wxString stackTrace
= GetAssertStackTrace();
694 if ( !stackTrace
.empty() )
695 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
696 #endif // wxUSE_STACKWALKER
698 return DoShowAssertDialog(msg
);
701 #if wxUSE_STACKWALKER
702 wxString
wxAppTraitsBase::GetAssertStackTrace()
706 class StackDump
: public wxStackWalker
711 const wxString
& GetStackTrace() const { return m_stackTrace
; }
714 virtual void OnStackFrame(const wxStackFrame
& frame
)
716 m_stackTrace
<< wxString::Format
719 wx_truncate_cast(int, frame
.GetLevel())
722 wxString name
= frame
.GetName();
725 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
729 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
732 if ( frame
.HasSourceLocation() )
734 m_stackTrace
<< _T('\t')
735 << frame
.GetFileName()
740 m_stackTrace
<< _T('\n');
744 wxString m_stackTrace
;
747 // don't show more than maxLines or we could get a dialog too tall to be
748 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
749 // characters it is still only 300 pixels...
750 static const int maxLines
= 20;
753 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
754 stackTrace
= dump
.GetStackTrace();
756 const int count
= stackTrace
.Freq(wxT('\n'));
757 for ( int i
= 0; i
< count
- maxLines
; i
++ )
758 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
762 #endif // wxUSE_STACKWALKER
765 #endif // __WXDEBUG__
767 // ============================================================================
768 // global functions implementation
769 // ============================================================================
779 // what else can we do?
788 wxTheApp
->WakeUpIdle();
790 //else: do nothing, what can we do?
796 bool wxAssertIsEqual(int x
, int y
)
801 // break into the debugger
804 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
806 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
808 #elif defined(__UNIX__)
815 // this function is called when an assert fails
816 static void wxDoOnAssert(const wxString
& szFile
,
818 const wxString
& szFunc
,
819 const wxString
& szCond
,
820 const wxString
& szMsg
= wxEmptyString
)
823 static int s_bInAssert
= 0;
825 wxRecursionGuard
guard(s_bInAssert
);
826 if ( guard
.IsInside() )
828 // can't use assert here to avoid infinite loops, so just trap
836 // by default, show the assert dialog box -- we can't customize this
838 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
842 // let the app process it as it wants
843 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
844 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
845 szCond
.c_str(), szMsg
.c_str());
849 void wxOnAssert(const wxString
& szFile
,
851 const wxString
& szFunc
,
852 const wxString
& szCond
,
853 const wxString
& szMsg
)
855 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
858 void wxOnAssert(const wxString
& szFile
,
860 const wxString
& szFunc
,
861 const wxString
& szCond
)
863 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
866 void wxOnAssert(const wxChar
*szFile
,
869 const wxChar
*szCond
,
872 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
875 void wxOnAssert(const char *szFile
,
879 const wxString
& szMsg
)
881 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
884 void wxOnAssert(const char *szFile
,
888 const wxCStrData
& msg
)
890 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, msg
);
894 void wxOnAssert(const char *szFile
,
899 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
902 void wxOnAssert(const char *szFile
,
908 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
911 void wxOnAssert(const char *szFile
,
917 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
919 #endif // wxUSE_UNICODE
921 #endif // __WXDEBUG__
923 // ============================================================================
924 // private functions implementation
925 // ============================================================================
929 static void LINKAGEMODE
SetTraceMasks()
933 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
935 wxStringTokenizer
tkn(mask
, wxT(",;:"));
936 while ( tkn
.HasMoreTokens() )
937 wxLog::AddTraceMask(tkn
.GetNextToken());
943 bool DoShowAssertDialog(const wxString
& msg
)
945 // under MSW we can show the dialog even in the console mode
946 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
947 wxString
msgDlg(msg
);
949 // this message is intentionally not translated -- it is for
951 msgDlg
+= wxT("\nDo you want to stop the program?\n")
952 wxT("You can also choose [Cancel] to suppress ")
953 wxT("further warnings.");
955 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), _T("wxWidgets Debug Alert"),
956 MB_YESNOCANCEL
| MB_ICONSTOP
) )
966 //case IDNO: nothing to do
969 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
972 // TODO: ask the user to enter "Y" or "N" on the console?
974 #endif // __WXMSW__/!__WXMSW__
976 // continue with the asserts
980 // show the assert modal dialog
982 void ShowAssertDialog(const wxString
& szFile
,
984 const wxString
& szFunc
,
985 const wxString
& szCond
,
986 const wxString
& szMsg
,
989 // this variable can be set to true to suppress "assert failure" messages
990 static bool s_bNoAsserts
= false;
995 // make life easier for people using VC++ IDE by using this format: like
996 // this, clicking on the message will take us immediately to the place of
998 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
1000 // add the function name, if any
1001 if ( !szFunc
.empty() )
1002 msg
<< _T(" in ") << szFunc
<< _T("()");
1004 // and the message itself
1005 if ( !szMsg
.empty() )
1007 msg
<< _T(": ") << szMsg
;
1009 else // no message given
1015 // if we are not in the main thread, output the assert directly and trap
1016 // since dialogs cannot be displayed
1017 if ( !wxThread::IsMain() )
1019 msg
+= wxT(" [in child thread]");
1021 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1023 OutputDebugString(msg
.wx_str());
1026 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1029 // He-e-e-e-elp!! we're asserting in a child thread
1033 #endif // wxUSE_THREADS
1035 if ( !s_bNoAsserts
)
1037 // send it to the normal log destination
1038 wxLogDebug(_T("%s"), msg
.c_str());
1042 // delegate showing assert dialog (if possible) to that class
1043 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1045 else // no traits object
1047 // fall back to the function of last resort
1048 s_bNoAsserts
= DoShowAssertDialog(msg
);
1053 #endif // __WXDEBUG__