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"
48 #if wxUSE_EXCEPTIONS && wxUSE_STL
53 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
54 #include <signal.h> // for SIGTRAP used by wxTrap()
60 #include "wx/fontmap.h"
61 #endif // wxUSE_FONTMAP
63 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
64 // For MacTypes.h for Debugger function
65 #include <CoreFoundation/CFBase.h>
68 #if defined(__WXMAC__)
70 #include <CoreServices/CoreServices.h>
72 #include "wx/mac/private.h" // includes mac headers
78 #include "wx/stackwalk.h"
80 #include "wx/msw/debughlp.h"
82 #endif // wxUSE_STACKWALKER
85 // wxABI_VERSION can be defined when compiling applications but it should be
86 // left undefined when compiling the library itself, it is then set to its
87 // default value in version.h
88 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
89 #error "wxABI_VERSION should not be defined when compiling the library"
92 // ----------------------------------------------------------------------------
93 // private functions prototypes
94 // ----------------------------------------------------------------------------
97 // really just show the assert dialog
98 static bool DoShowAssertDialog(const wxString
& msg
);
100 // prepare for showing the assert dialog, use the given traits or
101 // DoShowAssertDialog() as last fallback to really show it
103 void ShowAssertDialog(const wxString
& szFile
,
105 const wxString
& szFunc
,
106 const wxString
& szCond
,
107 const wxString
& szMsg
,
108 wxAppTraits
*traits
= NULL
);
110 // turn on the trace masks specified in the env variable WXTRACE
111 static void LINKAGEMODE
SetTraceMasks();
112 #endif // __WXDEBUG__
114 // ----------------------------------------------------------------------------
116 // ----------------------------------------------------------------------------
118 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
120 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
126 // this defines wxEventLoopPtr
127 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
129 // ============================================================================
130 // wxAppConsoleBase implementation
131 // ============================================================================
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 wxAppConsoleBase::wxAppConsoleBase()
142 ms_appInstance
= wx_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()
161 // ----------------------------------------------------------------------------
162 // initilization/cleanup
163 // ----------------------------------------------------------------------------
165 bool wxAppConsoleBase::Initialize(int& argcOrig
, wxChar
**argvOrig
)
168 GetTraits()->SetLocale();
171 // remember the command line arguments
176 wxPendingEventsLocker
= new wxCriticalSection
;
181 if ( m_appName
.empty() && (bool) argv
)
183 if ( m_appName
.empty() && argv
)
186 // the application name is, by default, the name of its executable file
187 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
189 #endif // !__WXPALMOS__
194 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
196 return GetTraits()->CreateEventLoop();
199 void wxAppConsoleBase::CleanUp()
207 delete wxPendingEvents
;
208 wxPendingEvents
= NULL
;
211 delete wxPendingEventsLocker
;
212 wxPendingEventsLocker
= NULL
;
213 #endif // wxUSE_THREADS
216 // ----------------------------------------------------------------------------
218 // ----------------------------------------------------------------------------
220 bool wxAppConsoleBase::OnInit()
222 #if wxUSE_CMDLINE_PARSER
223 wxCmdLineParser
parser(argc
, argv
);
225 OnInitCmdLine(parser
);
228 switch ( parser
.Parse(false /* don't show usage */) )
231 cont
= OnCmdLineHelp(parser
);
235 cont
= OnCmdLineParsed(parser
);
239 cont
= OnCmdLineError(parser
);
245 #endif // wxUSE_CMDLINE_PARSER
250 int wxAppConsoleBase::OnRun()
255 int wxAppConsoleBase::OnExit()
258 // delete the config object if any (don't use Get() here, but Set()
259 // because Get() could create a new config object)
260 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
261 #endif // wxUSE_CONFIG
266 void wxAppConsoleBase::Exit()
268 if (m_mainLoop
!= NULL
)
274 // ----------------------------------------------------------------------------
276 // ----------------------------------------------------------------------------
278 wxAppTraits
*wxAppConsoleBase::CreateTraits()
280 return new wxConsoleAppTraits
;
283 wxAppTraits
*wxAppConsoleBase::GetTraits()
285 // FIXME-MT: protect this with a CS?
288 m_traits
= CreateTraits();
290 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
296 // ----------------------------------------------------------------------------
298 // ----------------------------------------------------------------------------
300 int wxAppConsoleBase::MainLoop()
302 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
304 return m_mainLoop
? m_mainLoop
->Run() : -1;
307 void wxAppConsoleBase::ExitMainLoop()
309 // we should exit from the main event loop, not just any currently active
310 // (e.g. modal dialog) event loop
311 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
317 bool wxAppConsoleBase::Pending()
319 // use the currently active message loop here, not m_mainLoop, because if
320 // we're showing a modal dialog (with its own event loop) currently the
321 // main event loop is not running anyhow
322 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
324 return loop
&& loop
->Pending();
327 bool wxAppConsoleBase::Dispatch()
329 // see comment in Pending()
330 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
332 return loop
&& loop
->Dispatch();
335 bool wxAppConsoleBase::HasPendingEvents() const
337 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
339 bool has
= wxPendingEvents
&& !wxPendingEvents
->IsEmpty();
341 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
347 bool wxAppConsoleBase::IsMainLoopRunning()
349 const wxAppConsole
* const app
= GetInstance();
351 return app
&& app
->m_mainLoop
!= NULL
;
354 void wxAppConsoleBase::ProcessPendingEvents()
357 if ( !wxPendingEventsLocker
)
361 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
365 // iterate until the list becomes empty
366 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
369 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
370 wxPendingEvents
->Erase(node
);
372 // In ProcessPendingEvents(), new handlers might be add
373 // and we can safely leave the critical section here.
374 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
376 handler
->ProcessPendingEvents();
378 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
380 node
= wxPendingEvents
->GetFirst();
384 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
387 void wxAppConsoleBase::WakeUpIdle()
390 m_mainLoop
->WakeUp();
393 bool wxAppConsoleBase::ProcessIdle()
397 event
.SetEventObject(this);
399 return event
.MoreRequested();
402 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
404 // process the events normally by default
408 // ----------------------------------------------------------------------------
409 // exception handling
410 // ----------------------------------------------------------------------------
415 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
416 wxEventFunction func
,
417 wxEvent
& event
) const
419 // by default, simply call the handler
420 (handler
->*func
)(event
);
423 void wxAppConsoleBase::OnUnhandledException()
426 // we're called from an exception handler so we can re-throw the exception
427 // to recover its type
434 catch ( std::exception
& e
)
436 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
437 typeid(e
).name(), e
.what());
442 what
= "unknown exception";
445 wxMessageOutputBest().Printf(
446 "*** Caught unhandled %s; terminating\n", what
448 #endif // __WXDEBUG__
451 // ----------------------------------------------------------------------------
452 // exceptions support
453 // ----------------------------------------------------------------------------
455 bool wxAppConsoleBase::OnExceptionInMainLoop()
459 // some compilers are too stupid to know that we never return after throw
460 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
465 #endif // wxUSE_EXCEPTIONS
467 // ----------------------------------------------------------------------------
469 // ----------------------------------------------------------------------------
471 #if wxUSE_CMDLINE_PARSER
473 #define OPTION_VERBOSE "verbose"
475 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
477 // the standard command line options
478 static const wxCmdLineEntryDesc cmdLineDesc
[] =
484 gettext_noop("show this help message"),
486 wxCMD_LINE_OPTION_HELP
494 gettext_noop("generate verbose log messages"),
504 parser
.SetDesc(cmdLineDesc
);
507 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
510 if ( parser
.Found(OPTION_VERBOSE
) )
512 wxLog::SetVerbose(true);
521 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
528 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
535 #endif // wxUSE_CMDLINE_PARSER
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
542 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
543 const char *componentName
)
545 #if 0 // can't use wxLogTrace, not up and running yet
546 printf("checking build options object '%s' (ptr %p) in '%s'\n",
547 optionsSignature
, optionsSignature
, componentName
);
550 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
552 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
553 wxString prog
= wxString::FromAscii(optionsSignature
);
554 wxString progName
= wxString::FromAscii(componentName
);
557 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
558 lib
.c_str(), progName
.c_str(), prog
.c_str());
560 wxLogFatalError(msg
.c_str());
562 // normally wxLogFatalError doesn't return
572 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
578 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
581 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
586 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
589 #endif // __WXDEBUG__
591 // ============================================================================
592 // other classes implementations
593 // ============================================================================
595 // ----------------------------------------------------------------------------
596 // wxConsoleAppTraitsBase
597 // ----------------------------------------------------------------------------
601 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
603 return new wxLogStderr
;
608 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
610 return new wxMessageOutputStderr
;
615 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
617 return (wxFontMapper
*)new wxFontMapperBase
;
620 #endif // wxUSE_FONTMAP
622 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
624 // console applications don't use renderers
629 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
631 return wxAppTraitsBase::ShowAssertDialog(msg
);
635 bool wxConsoleAppTraitsBase::HasStderr()
637 // console applications always have stderr, even under Mac/Windows
641 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
646 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
652 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
658 // ----------------------------------------------------------------------------
660 // ----------------------------------------------------------------------------
663 void wxAppTraitsBase::SetLocale()
665 wxSetlocale(LC_ALL
, "");
666 wxUpdateLocaleIsUtf8();
672 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
674 wxString msg
= msgOriginal
;
676 #if wxUSE_STACKWALKER
677 #if !defined(__WXMSW__)
678 // on Unix stack frame generation may take some time, depending on the
679 // size of the executable mainly... warn the user that we are working
680 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
684 const wxString stackTrace
= GetAssertStackTrace();
685 if ( !stackTrace
.empty() )
686 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
687 #endif // wxUSE_STACKWALKER
689 return DoShowAssertDialog(msg
);
692 #if wxUSE_STACKWALKER
693 wxString
wxAppTraitsBase::GetAssertStackTrace()
697 class StackDump
: public wxStackWalker
702 const wxString
& GetStackTrace() const { return m_stackTrace
; }
705 virtual void OnStackFrame(const wxStackFrame
& frame
)
707 m_stackTrace
<< wxString::Format
710 wx_truncate_cast(int, frame
.GetLevel())
713 wxString name
= frame
.GetName();
716 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
720 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
723 if ( frame
.HasSourceLocation() )
725 m_stackTrace
<< _T('\t')
726 << frame
.GetFileName()
731 m_stackTrace
<< _T('\n');
735 wxString m_stackTrace
;
738 // don't show more than maxLines or we could get a dialog too tall to be
739 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
740 // characters it is still only 300 pixels...
741 static const int maxLines
= 20;
744 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
745 stackTrace
= dump
.GetStackTrace();
747 const int count
= stackTrace
.Freq(wxT('\n'));
748 for ( int i
= 0; i
< count
- maxLines
; i
++ )
749 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
753 #endif // wxUSE_STACKWALKER
756 #endif // __WXDEBUG__
758 // ============================================================================
759 // global functions implementation
760 // ============================================================================
770 // what else can we do?
779 wxTheApp
->WakeUpIdle();
781 //else: do nothing, what can we do?
787 bool wxAssertIsEqual(int x
, int y
)
792 // break into the debugger
795 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
797 #elif defined(__WXMAC__) && !defined(__DARWIN__)
803 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
805 #elif defined(__UNIX__)
812 // this function is called when an assert fails
813 static void wxDoOnAssert(const wxString
& szFile
,
815 const wxString
& szFunc
,
816 const wxString
& szCond
,
817 const wxString
& szMsg
= wxEmptyString
)
820 static bool s_bInAssert
= false;
824 // He-e-e-e-elp!! we're trapped in endless loop
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());
851 void wxOnAssert(const wxString
& szFile
,
853 const wxString
& szFunc
,
854 const wxString
& szCond
,
855 const wxString
& szMsg
)
857 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
860 void wxOnAssert(const wxString
& szFile
,
862 const wxString
& szFunc
,
863 const wxString
& szCond
)
865 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
868 void wxOnAssert(const wxChar
*szFile
,
871 const wxChar
*szCond
,
874 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
877 void wxOnAssert(const char *szFile
,
881 const wxString
& szMsg
)
883 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
886 void wxOnAssert(const char *szFile
,
890 const wxCStrData
& msg
)
892 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, msg
);
896 void wxOnAssert(const char *szFile
,
901 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
904 void wxOnAssert(const char *szFile
,
910 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
913 void wxOnAssert(const char *szFile
,
919 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
921 #endif // wxUSE_UNICODE
923 #endif // __WXDEBUG__
925 // ============================================================================
926 // private functions implementation
927 // ============================================================================
931 static void LINKAGEMODE
SetTraceMasks()
935 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
937 wxStringTokenizer
tkn(mask
, wxT(",;:"));
938 while ( tkn
.HasMoreTokens() )
939 wxLog::AddTraceMask(tkn
.GetNextToken());
945 bool DoShowAssertDialog(const wxString
& msg
)
947 // under MSW we can show the dialog even in the console mode
948 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
949 wxString
msgDlg(msg
);
951 // this message is intentionally not translated -- it is for
953 msgDlg
+= wxT("\nDo you want to stop the program?\n")
954 wxT("You can also choose [Cancel] to suppress ")
955 wxT("further warnings.");
957 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), _T("wxWidgets Debug Alert"),
958 MB_YESNOCANCEL
| MB_ICONSTOP
) )
968 //case IDNO: nothing to do
971 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
974 // TODO: ask the user to enter "Y" or "N" on the console?
976 #endif // __WXMSW__/!__WXMSW__
978 // continue with the asserts
982 // show the assert modal dialog
984 void ShowAssertDialog(const wxString
& szFile
,
986 const wxString
& szFunc
,
987 const wxString
& szCond
,
988 const wxString
& szMsg
,
991 // this variable can be set to true to suppress "assert failure" messages
992 static bool s_bNoAsserts
= false;
997 // make life easier for people using VC++ IDE by using this format: like
998 // this, clicking on the message will take us immediately to the place of
1000 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
1002 // add the function name, if any
1003 if ( !szFunc
.empty() )
1004 msg
<< _T(" in ") << szFunc
<< _T("()");
1006 // and the message itself
1007 if ( !szMsg
.empty() )
1009 msg
<< _T(": ") << szMsg
;
1011 else // no message given
1017 // if we are not in the main thread, output the assert directly and trap
1018 // since dialogs cannot be displayed
1019 if ( !wxThread::IsMain() )
1021 msg
+= wxT(" [in child thread]");
1023 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1025 OutputDebugString(msg
.wx_str());
1028 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1031 // He-e-e-e-elp!! we're asserting in a child thread
1035 #endif // wxUSE_THREADS
1037 if ( !s_bNoAsserts
)
1039 // send it to the normal log destination
1040 wxLogDebug(_T("%s"), msg
.c_str());
1044 // delegate showing assert dialog (if possible) to that class
1045 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1047 else // no traits object
1049 // fall back to the function of last resort
1050 s_bNoAsserts
= DoShowAssertDialog(msg
);
1055 #endif // __WXDEBUG__