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
54 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
55 #include <signal.h> // for SIGTRAP used by wxTrap()
61 #include "wx/fontmap.h"
62 #endif // wxUSE_FONTMAP
64 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
65 // For MacTypes.h for Debugger function
66 #include <CoreFoundation/CFBase.h>
69 #if defined(__WXMAC__)
71 #include <CoreServices/CoreServices.h>
73 #include "wx/mac/private.h" // includes mac headers
79 #include "wx/stackwalk.h"
81 #include "wx/msw/debughlp.h"
83 #endif // wxUSE_STACKWALKER
85 #include "wx/recguard.h"
88 // wxABI_VERSION can be defined when compiling applications but it should be
89 // left undefined when compiling the library itself, it is then set to its
90 // default value in version.h
91 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
92 #error "wxABI_VERSION should not be defined when compiling the library"
95 // ----------------------------------------------------------------------------
96 // private functions prototypes
97 // ----------------------------------------------------------------------------
100 // really just show the assert dialog
101 static bool DoShowAssertDialog(const wxString
& msg
);
103 // prepare for showing the assert dialog, use the given traits or
104 // DoShowAssertDialog() as last fallback to really show it
106 void ShowAssertDialog(const wxString
& szFile
,
108 const wxString
& szFunc
,
109 const wxString
& szCond
,
110 const wxString
& szMsg
,
111 wxAppTraits
*traits
= NULL
);
113 // turn on the trace masks specified in the env variable WXTRACE
114 static void LINKAGEMODE
SetTraceMasks();
115 #endif // __WXDEBUG__
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
123 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
129 // this defines wxEventLoopPtr
130 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
132 // ============================================================================
133 // wxAppConsoleBase implementation
134 // ============================================================================
136 // ----------------------------------------------------------------------------
138 // ----------------------------------------------------------------------------
140 wxAppConsoleBase::wxAppConsoleBase()
145 ms_appInstance
= wx_static_cast(wxAppConsole
*, this);
150 // In unicode mode the SetTraceMasks call can cause an apptraits to be
151 // created, but since we are still in the constructor the wrong kind will
152 // be created for GUI apps. Destroy it so it can be created again later.
159 wxAppConsoleBase::~wxAppConsoleBase()
164 // ----------------------------------------------------------------------------
165 // initilization/cleanup
166 // ----------------------------------------------------------------------------
168 bool wxAppConsoleBase::Initialize(int& argcOrig
, wxChar
**argvOrig
)
171 GetTraits()->SetLocale();
174 // remember the command line arguments
179 wxPendingEventsLocker
= new wxCriticalSection
;
183 if ( m_appName
.empty() && argv
)
185 // the application name is, by default, the name of its executable file
186 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
188 #endif // !__WXPALMOS__
193 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
195 return GetTraits()->CreateEventLoop();
198 void wxAppConsoleBase::CleanUp()
206 delete wxPendingEvents
;
207 wxPendingEvents
= NULL
;
210 delete wxPendingEventsLocker
;
211 wxPendingEventsLocker
= NULL
;
212 #endif // wxUSE_THREADS
215 // ----------------------------------------------------------------------------
217 // ----------------------------------------------------------------------------
219 bool wxAppConsoleBase::OnInit()
221 #if wxUSE_CMDLINE_PARSER
222 wxCmdLineParser
parser(argc
, argv
);
224 OnInitCmdLine(parser
);
227 switch ( parser
.Parse(false /* don't show usage */) )
230 cont
= OnCmdLineHelp(parser
);
234 cont
= OnCmdLineParsed(parser
);
238 cont
= OnCmdLineError(parser
);
244 #endif // wxUSE_CMDLINE_PARSER
249 int wxAppConsoleBase::OnRun()
254 int wxAppConsoleBase::OnExit()
257 // delete the config object if any (don't use Get() here, but Set()
258 // because Get() could create a new config object)
259 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
260 #endif // wxUSE_CONFIG
265 void wxAppConsoleBase::Exit()
267 if (m_mainLoop
!= NULL
)
273 // ----------------------------------------------------------------------------
275 // ----------------------------------------------------------------------------
277 wxAppTraits
*wxAppConsoleBase::CreateTraits()
279 return new wxConsoleAppTraits
;
282 wxAppTraits
*wxAppConsoleBase::GetTraits()
284 // FIXME-MT: protect this with a CS?
287 m_traits
= CreateTraits();
289 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
295 // ----------------------------------------------------------------------------
297 // ----------------------------------------------------------------------------
299 int wxAppConsoleBase::MainLoop()
301 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
303 return m_mainLoop
? m_mainLoop
->Run() : -1;
306 void wxAppConsoleBase::ExitMainLoop()
308 // we should exit from the main event loop, not just any currently active
309 // (e.g. modal dialog) event loop
310 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
316 bool wxAppConsoleBase::Pending()
318 // use the currently active message loop here, not m_mainLoop, because if
319 // we're showing a modal dialog (with its own event loop) currently the
320 // main event loop is not running anyhow
321 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
323 return loop
&& loop
->Pending();
326 bool wxAppConsoleBase::Dispatch()
328 // see comment in Pending()
329 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
331 return loop
&& loop
->Dispatch();
334 bool wxAppConsoleBase::HasPendingEvents() const
336 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
338 bool has
= wxPendingEvents
&& !wxPendingEvents
->IsEmpty();
340 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 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
364 // iterate until the list becomes empty: the handlers remove themselves
365 // from it when they don't have any more pending events
366 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
369 // In ProcessPendingEvents(), new handlers might be add
370 // and we can safely leave the critical section here.
371 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
373 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
374 handler
->ProcessPendingEvents();
376 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
378 // restart as the iterators could have been invalidated
379 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 "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"),
503 parser
.SetDesc(cmdLineDesc
);
506 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
509 if ( parser
.Found(OPTION_VERBOSE
) )
511 wxLog::SetVerbose(true);
520 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
527 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
534 #endif // wxUSE_CMDLINE_PARSER
536 // ----------------------------------------------------------------------------
538 // ----------------------------------------------------------------------------
541 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
542 const char *componentName
)
544 #if 0 // can't use wxLogTrace, not up and running yet
545 printf("checking build options object '%s' (ptr %p) in '%s'\n",
546 optionsSignature
, optionsSignature
, componentName
);
549 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
551 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
552 wxString prog
= wxString::FromAscii(optionsSignature
);
553 wxString progName
= wxString::FromAscii(componentName
);
556 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
557 lib
.c_str(), progName
.c_str(), prog
.c_str());
559 wxLogFatalError(msg
.c_str());
561 // normally wxLogFatalError doesn't return
571 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
577 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
580 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
585 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
588 #endif // __WXDEBUG__
590 // ============================================================================
591 // other classes implementations
592 // ============================================================================
594 // ----------------------------------------------------------------------------
595 // wxConsoleAppTraitsBase
596 // ----------------------------------------------------------------------------
600 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
602 return new wxLogStderr
;
607 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
609 return new wxMessageOutputStderr
;
614 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
616 return (wxFontMapper
*)new wxFontMapperBase
;
619 #endif // wxUSE_FONTMAP
621 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
623 // console applications don't use renderers
628 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
630 return wxAppTraitsBase::ShowAssertDialog(msg
);
634 bool wxConsoleAppTraitsBase::HasStderr()
636 // console applications always have stderr, even under Mac/Windows
640 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
645 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
650 // ----------------------------------------------------------------------------
652 // ----------------------------------------------------------------------------
655 void wxAppTraitsBase::SetLocale()
657 wxSetlocale(LC_ALL
, "");
658 wxUpdateLocaleIsUtf8();
663 void wxMutexGuiEnterImpl();
664 void wxMutexGuiLeaveImpl();
666 void wxAppTraitsBase::MutexGuiEnter()
668 wxMutexGuiEnterImpl();
671 void wxAppTraitsBase::MutexGuiLeave()
673 wxMutexGuiLeaveImpl();
676 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
678 wxAppConsoleBase::GetInstance()->GetTraits()->MutexGuiEnter();
681 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
683 wxAppConsoleBase::GetInstance()->GetTraits()->MutexGuiLeave();
685 #endif // wxUSE_THREADS
689 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
691 wxString msg
= msgOriginal
;
693 #if wxUSE_STACKWALKER
694 #if !defined(__WXMSW__)
695 // on Unix stack frame generation may take some time, depending on the
696 // size of the executable mainly... warn the user that we are working
697 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
701 const wxString stackTrace
= GetAssertStackTrace();
702 if ( !stackTrace
.empty() )
703 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
704 #endif // wxUSE_STACKWALKER
706 return DoShowAssertDialog(msg
);
709 #if wxUSE_STACKWALKER
710 wxString
wxAppTraitsBase::GetAssertStackTrace()
714 class StackDump
: public wxStackWalker
719 const wxString
& GetStackTrace() const { return m_stackTrace
; }
722 virtual void OnStackFrame(const wxStackFrame
& frame
)
724 m_stackTrace
<< wxString::Format
727 wx_truncate_cast(int, frame
.GetLevel())
730 wxString name
= frame
.GetName();
733 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
737 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
740 if ( frame
.HasSourceLocation() )
742 m_stackTrace
<< _T('\t')
743 << frame
.GetFileName()
748 m_stackTrace
<< _T('\n');
752 wxString m_stackTrace
;
755 // don't show more than maxLines or we could get a dialog too tall to be
756 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
757 // characters it is still only 300 pixels...
758 static const int maxLines
= 20;
761 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
762 stackTrace
= dump
.GetStackTrace();
764 const int count
= stackTrace
.Freq(wxT('\n'));
765 for ( int i
= 0; i
< count
- maxLines
; i
++ )
766 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
770 #endif // wxUSE_STACKWALKER
773 #endif // __WXDEBUG__
775 // ============================================================================
776 // global functions implementation
777 // ============================================================================
787 // what else can we do?
796 wxTheApp
->WakeUpIdle();
798 //else: do nothing, what can we do?
804 bool wxAssertIsEqual(int x
, int y
)
809 // break into the debugger
812 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
814 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
816 #elif defined(__UNIX__)
823 // this function is called when an assert fails
824 static void wxDoOnAssert(const wxString
& szFile
,
826 const wxString
& szFunc
,
827 const wxString
& szCond
,
828 const wxString
& szMsg
= wxEmptyString
)
831 static int s_bInAssert
= 0;
833 wxRecursionGuard
guard(s_bInAssert
);
834 if ( guard
.IsInside() )
836 // can't use assert here to avoid infinite loops, so just trap
844 // by default, show the assert dialog box -- we can't customize this
846 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
850 // let the app process it as it wants
851 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
852 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
853 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());
951 bool DoShowAssertDialog(const wxString
& msg
)
953 // under MSW we can show the dialog even in the console mode
954 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
955 wxString
msgDlg(msg
);
957 // this message is intentionally not translated -- it is for
959 msgDlg
+= wxT("\nDo you want to stop the program?\n")
960 wxT("You can also choose [Cancel] to suppress ")
961 wxT("further warnings.");
963 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), _T("wxWidgets Debug Alert"),
964 MB_YESNOCANCEL
| MB_ICONSTOP
) )
974 //case IDNO: nothing to do
977 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
980 // TODO: ask the user to enter "Y" or "N" on the console?
982 #endif // __WXMSW__/!__WXMSW__
984 // continue with the asserts
988 // show the assert modal dialog
990 void ShowAssertDialog(const wxString
& szFile
,
992 const wxString
& szFunc
,
993 const wxString
& szCond
,
994 const wxString
& szMsg
,
997 // this variable can be set to true to suppress "assert failure" messages
998 static bool s_bNoAsserts
= false;
1003 // make life easier for people using VC++ IDE by using this format: like
1004 // this, clicking on the message will take us immediately to the place of
1005 // the failed assert
1006 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
1008 // add the function name, if any
1009 if ( !szFunc
.empty() )
1010 msg
<< _T(" in ") << szFunc
<< _T("()");
1012 // and the message itself
1013 if ( !szMsg
.empty() )
1015 msg
<< _T(": ") << szMsg
;
1017 else // no message given
1023 // if we are not in the main thread, output the assert directly and trap
1024 // since dialogs cannot be displayed
1025 if ( !wxThread::IsMain() )
1027 msg
+= wxT(" [in child thread]");
1029 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1031 OutputDebugString(msg
.wx_str());
1034 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1037 // He-e-e-e-elp!! we're asserting in a child thread
1041 #endif // wxUSE_THREADS
1043 if ( !s_bNoAsserts
)
1045 // send it to the normal log destination
1046 wxLogDebug(_T("%s"), msg
.c_str());
1050 // delegate showing assert dialog (if possible) to that class
1051 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1053 else // no traits object
1055 // fall back to the function of last resort
1056 s_bNoAsserts
= DoShowAssertDialog(msg
);
1061 #endif // __WXDEBUG__