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
;
180 if ( m_appName
.empty() && argv
)
182 // the application name is, by default, the name of its executable file
183 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
185 #endif // !__WXPALMOS__
190 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
192 return GetTraits()->CreateEventLoop();
195 void wxAppConsoleBase::CleanUp()
203 delete wxPendingEvents
;
204 wxPendingEvents
= NULL
;
207 delete wxPendingEventsLocker
;
208 wxPendingEventsLocker
= NULL
;
209 #endif // wxUSE_THREADS
212 // ----------------------------------------------------------------------------
214 // ----------------------------------------------------------------------------
216 bool wxAppConsoleBase::OnInit()
218 #if wxUSE_CMDLINE_PARSER
219 wxCmdLineParser
parser(argc
, argv
);
221 OnInitCmdLine(parser
);
224 switch ( parser
.Parse(false /* don't show usage */) )
227 cont
= OnCmdLineHelp(parser
);
231 cont
= OnCmdLineParsed(parser
);
235 cont
= OnCmdLineError(parser
);
241 #endif // wxUSE_CMDLINE_PARSER
246 int wxAppConsoleBase::OnRun()
251 int wxAppConsoleBase::OnExit()
254 // delete the config object if any (don't use Get() here, but Set()
255 // because Get() could create a new config object)
256 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
257 #endif // wxUSE_CONFIG
262 void wxAppConsoleBase::Exit()
264 if (m_mainLoop
!= NULL
)
270 // ----------------------------------------------------------------------------
272 // ----------------------------------------------------------------------------
274 wxAppTraits
*wxAppConsoleBase::CreateTraits()
276 return new wxConsoleAppTraits
;
279 wxAppTraits
*wxAppConsoleBase::GetTraits()
281 // FIXME-MT: protect this with a CS?
284 m_traits
= CreateTraits();
286 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
292 // ----------------------------------------------------------------------------
294 // ----------------------------------------------------------------------------
296 int wxAppConsoleBase::MainLoop()
298 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
300 return m_mainLoop
? m_mainLoop
->Run() : -1;
303 void wxAppConsoleBase::ExitMainLoop()
305 // we should exit from the main event loop, not just any currently active
306 // (e.g. modal dialog) event loop
307 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
313 bool wxAppConsoleBase::Pending()
315 // use the currently active message loop here, not m_mainLoop, because if
316 // we're showing a modal dialog (with its own event loop) currently the
317 // main event loop is not running anyhow
318 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
320 return loop
&& loop
->Pending();
323 bool wxAppConsoleBase::Dispatch()
325 // see comment in Pending()
326 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
328 return loop
&& loop
->Dispatch();
331 bool wxAppConsoleBase::HasPendingEvents() const
333 // ensure that we're the only thread to modify the pending events list
334 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
336 if ( !wxPendingEvents
)
338 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
341 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
346 bool wxAppConsoleBase::IsMainLoopRunning()
348 const wxAppConsole
* const app
= GetInstance();
350 return app
&& app
->m_mainLoop
!= NULL
;
353 void wxAppConsoleBase::ProcessPendingEvents()
356 if ( !wxPendingEventsLocker
)
360 if ( !HasPendingEvents() )
363 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();
383 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
386 void wxAppConsoleBase::WakeUpIdle()
389 m_mainLoop
->WakeUp();
392 bool wxAppConsoleBase::ProcessIdle()
396 event
.SetEventObject(this);
398 return event
.MoreRequested();
401 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
403 // process the events normally by default
407 // ----------------------------------------------------------------------------
408 // exception handling
409 // ----------------------------------------------------------------------------
414 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
415 wxEventFunction func
,
416 wxEvent
& event
) const
418 // by default, simply call the handler
419 (handler
->*func
)(event
);
422 void wxAppConsoleBase::OnUnhandledException()
425 // we're called from an exception handler so we can re-throw the exception
426 // to recover its type
433 catch ( std::exception
& e
)
435 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
436 typeid(e
).name(), e
.what());
441 what
= "unknown exception";
444 wxMessageOutputBest().Printf(
445 "*** Caught unhandled %s; terminating\n", what
447 #endif // __WXDEBUG__
450 // ----------------------------------------------------------------------------
451 // exceptions support
452 // ----------------------------------------------------------------------------
454 bool wxAppConsoleBase::OnExceptionInMainLoop()
458 // some compilers are too stupid to know that we never return after throw
459 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
464 #endif // wxUSE_EXCEPTIONS
466 // ----------------------------------------------------------------------------
468 // ----------------------------------------------------------------------------
470 #if wxUSE_CMDLINE_PARSER
472 #define OPTION_VERBOSE _T("verbose")
474 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
476 // the standard command line options
477 static const wxCmdLineEntryDesc cmdLineDesc
[] =
483 gettext_noop("show this help message"),
485 wxCMD_LINE_OPTION_HELP
493 gettext_noop("generate verbose log messages"),
510 parser
.SetDesc(cmdLineDesc
);
513 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
516 if ( parser
.Found(OPTION_VERBOSE
) )
518 wxLog::SetVerbose(true);
527 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
534 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
541 #endif // wxUSE_CMDLINE_PARSER
543 // ----------------------------------------------------------------------------
545 // ----------------------------------------------------------------------------
548 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
549 const char *componentName
)
551 #if 0 // can't use wxLogTrace, not up and running yet
552 printf("checking build options object '%s' (ptr %p) in '%s'\n",
553 optionsSignature
, optionsSignature
, componentName
);
556 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
558 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
559 wxString prog
= wxString::FromAscii(optionsSignature
);
560 wxString progName
= wxString::FromAscii(componentName
);
563 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
564 lib
.c_str(), progName
.c_str(), prog
.c_str());
566 wxLogFatalError(msg
.c_str());
568 // normally wxLogFatalError doesn't return
578 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
584 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
587 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
592 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
595 #endif // __WXDEBUG__
597 // ============================================================================
598 // other classes implementations
599 // ============================================================================
601 // ----------------------------------------------------------------------------
602 // wxConsoleAppTraitsBase
603 // ----------------------------------------------------------------------------
607 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
609 return new wxLogStderr
;
614 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
616 return new wxMessageOutputStderr
;
621 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
623 return (wxFontMapper
*)new wxFontMapperBase
;
626 #endif // wxUSE_FONTMAP
628 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
630 // console applications don't use renderers
635 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
637 return wxAppTraitsBase::ShowAssertDialog(msg
);
641 bool wxConsoleAppTraitsBase::HasStderr()
643 // console applications always have stderr, even under Mac/Windows
647 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
652 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
658 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
664 // ----------------------------------------------------------------------------
666 // ----------------------------------------------------------------------------
669 void wxAppTraitsBase::SetLocale()
671 setlocale(LC_ALL
, "");
672 wxUpdateLocaleIsUtf8();
678 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
680 wxString msg
= msgOriginal
;
682 #if wxUSE_STACKWALKER
683 #if !defined(__WXMSW__)
684 // on Unix stack frame generation may take some time, depending on the
685 // size of the executable mainly... warn the user that we are working
686 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
690 const wxString stackTrace
= GetAssertStackTrace();
691 if ( !stackTrace
.empty() )
692 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
693 #endif // wxUSE_STACKWALKER
695 return DoShowAssertDialog(msg
);
698 #if wxUSE_STACKWALKER
699 wxString
wxAppTraitsBase::GetAssertStackTrace()
703 class StackDump
: public wxStackWalker
708 const wxString
& GetStackTrace() const { return m_stackTrace
; }
711 virtual void OnStackFrame(const wxStackFrame
& frame
)
713 m_stackTrace
<< wxString::Format
716 wx_truncate_cast(int, frame
.GetLevel())
719 wxString name
= frame
.GetName();
722 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
726 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
729 if ( frame
.HasSourceLocation() )
731 m_stackTrace
<< _T('\t')
732 << frame
.GetFileName()
737 m_stackTrace
<< _T('\n');
741 wxString m_stackTrace
;
744 // don't show more than maxLines or we could get a dialog too tall to be
745 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
746 // characters it is still only 300 pixels...
747 static const int maxLines
= 20;
750 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
751 stackTrace
= dump
.GetStackTrace();
753 const int count
= stackTrace
.Freq(wxT('\n'));
754 for ( int i
= 0; i
< count
- maxLines
; i
++ )
755 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
759 #endif // wxUSE_STACKWALKER
762 #endif // __WXDEBUG__
764 // ============================================================================
765 // global functions implementation
766 // ============================================================================
776 // what else can we do?
785 wxTheApp
->WakeUpIdle();
787 //else: do nothing, what can we do?
793 bool wxAssertIsEqual(int x
, int y
)
798 // break into the debugger
801 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
803 #elif defined(__WXMAC__) && !defined(__DARWIN__)
809 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
811 #elif defined(__UNIX__)
818 // this function is called when an assert fails
819 static void wxDoOnAssert(const wxString
& szFile
,
821 const wxString
& szFunc
,
822 const wxString
& szCond
,
823 const wxString
& szMsg
= wxEmptyString
)
826 static bool s_bInAssert
= false;
830 // He-e-e-e-elp!! we're trapped in endless loop
842 // by default, show the assert dialog box -- we can't customize this
844 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
848 // let the app process it as it wants
849 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
850 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
851 szCond
.c_str(), szMsg
.c_str());
857 void wxOnAssert(const wxString
& szFile
,
859 const wxString
& szFunc
,
860 const wxString
& szCond
,
861 const wxString
& szMsg
)
863 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
866 void wxOnAssert(const wxString
& szFile
,
868 const wxString
& szFunc
,
869 const wxString
& szCond
)
871 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
874 void wxOnAssert(const wxChar
*szFile
,
877 const wxChar
*szCond
,
880 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
883 void wxOnAssert(const char *szFile
,
887 const wxString
& szMsg
)
889 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
892 void wxOnAssert(const char *szFile
,
896 const wxCStrData
& msg
)
898 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, msg
);
902 void wxOnAssert(const char *szFile
,
907 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
910 void wxOnAssert(const char *szFile
,
916 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
919 void wxOnAssert(const char *szFile
,
925 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
927 #endif // wxUSE_UNICODE
929 #endif // __WXDEBUG__
931 // ============================================================================
932 // private functions implementation
933 // ============================================================================
937 static void LINKAGEMODE
SetTraceMasks()
941 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
943 wxStringTokenizer
tkn(mask
, wxT(",;:"));
944 while ( tkn
.HasMoreTokens() )
945 wxLog::AddTraceMask(tkn
.GetNextToken());
950 bool DoShowAssertDialog(const wxString
& msg
)
952 // under MSW we can show the dialog even in the console mode
953 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
954 wxString
msgDlg(msg
);
956 // this message is intentionally not translated -- it is for
958 msgDlg
+= wxT("\nDo you want to stop the program?\n")
959 wxT("You can also choose [Cancel] to suppress ")
960 wxT("further warnings.");
962 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), _T("wxWidgets Debug Alert"),
963 MB_YESNOCANCEL
| MB_ICONSTOP
) )
973 //case IDNO: nothing to do
976 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
979 // TODO: ask the user to enter "Y" or "N" on the console?
981 #endif // __WXMSW__/!__WXMSW__
983 // continue with the asserts
987 // show the assert modal dialog
989 void ShowAssertDialog(const wxString
& szFile
,
991 const wxString
& szFunc
,
992 const wxString
& szCond
,
993 const wxString
& szMsg
,
996 // this variable can be set to true to suppress "assert failure" messages
997 static bool s_bNoAsserts
= false;
1002 // make life easier for people using VC++ IDE by using this format: like
1003 // this, clicking on the message will take us immediately to the place of
1004 // the failed assert
1005 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
1007 // add the function name, if any
1008 if ( !szFunc
.empty() )
1009 msg
<< _T(" in ") << szFunc
<< _T("()");
1011 // and the message itself
1012 if ( !szMsg
.empty() )
1014 msg
<< _T(": ") << szMsg
;
1016 else // no message given
1022 // if we are not in the main thread, output the assert directly and trap
1023 // since dialogs cannot be displayed
1024 if ( !wxThread::IsMain() )
1026 msg
+= wxT(" [in child thread]");
1028 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1030 OutputDebugString(msg
.wx_str());
1033 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1036 // He-e-e-e-elp!! we're asserting in a child thread
1040 #endif // wxUSE_THREADS
1042 if ( !s_bNoAsserts
)
1044 // send it to the normal log destination
1045 wxLogDebug(_T("%s"), msg
.c_str());
1049 // delegate showing assert dialog (if possible) to that class
1050 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1052 else // no traits object
1054 // fall back to the function of last resort
1055 s_bNoAsserts
= DoShowAssertDialog(msg
);
1060 #endif // __WXDEBUG__