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
66 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
67 // For MacTypes.h for Debugger function
68 #include <CoreFoundation/CFBase.h>
71 #if defined(__WXMAC__)
73 #include <CoreServices/CoreServices.h>
75 #include "wx/mac/private.h" // includes mac headers
81 #include "wx/stackwalk.h"
83 #include "wx/msw/debughlp.h"
85 #endif // wxUSE_STACKWALKER
87 #include "wx/recguard.h"
90 // wxABI_VERSION can be defined when compiling applications but it should be
91 // left undefined when compiling the library itself, it is then set to its
92 // default value in version.h
93 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
94 #error "wxABI_VERSION should not be defined when compiling the library"
97 // ----------------------------------------------------------------------------
98 // private functions prototypes
99 // ----------------------------------------------------------------------------
102 // really just show the assert dialog
103 static bool DoShowAssertDialog(const wxString
& msg
);
105 // prepare for showing the assert dialog, use the given traits or
106 // DoShowAssertDialog() as last fallback to really show it
108 void ShowAssertDialog(const wxString
& szFile
,
110 const wxString
& szFunc
,
111 const wxString
& szCond
,
112 const wxString
& szMsg
,
113 wxAppTraits
*traits
= NULL
);
115 // turn on the trace masks specified in the env variable WXTRACE
116 static void LINKAGEMODE
SetTraceMasks();
117 #endif // __WXDEBUG__
119 // ----------------------------------------------------------------------------
121 // ----------------------------------------------------------------------------
123 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
125 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
131 // this defines wxEventLoopPtr
132 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
134 // ============================================================================
135 // wxAppConsoleBase implementation
136 // ============================================================================
138 // ----------------------------------------------------------------------------
140 // ----------------------------------------------------------------------------
142 wxAppConsoleBase::wxAppConsoleBase()
147 ms_appInstance
= wx_static_cast(wxAppConsole
*, this);
152 // In unicode mode the SetTraceMasks call can cause an apptraits to be
153 // created, but since we are still in the constructor the wrong kind will
154 // be created for GUI apps. Destroy it so it can be created again later.
161 wxAppConsoleBase::~wxAppConsoleBase()
166 // ----------------------------------------------------------------------------
167 // initilization/cleanup
168 // ----------------------------------------------------------------------------
170 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc
), wxChar
**argv
)
173 GetTraits()->SetLocale();
177 wxPendingEventsLocker
= new wxCriticalSection
;
181 if ( m_appName
.empty() && argv
&& argv
[0] )
183 // the application name is, by default, the name of its executable file
184 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
186 #endif // !__WXPALMOS__
191 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
193 return GetTraits()->CreateEventLoop();
196 void wxAppConsoleBase::CleanUp()
204 delete wxPendingEvents
;
205 wxPendingEvents
= NULL
;
208 delete wxPendingEventsLocker
;
209 wxPendingEventsLocker
= NULL
;
210 #endif // wxUSE_THREADS
213 // ----------------------------------------------------------------------------
215 // ----------------------------------------------------------------------------
217 bool wxAppConsoleBase::OnInit()
219 #if wxUSE_CMDLINE_PARSER
220 wxCmdLineParser
parser(argc
, argv
);
222 OnInitCmdLine(parser
);
225 switch ( parser
.Parse(false /* don't show usage */) )
228 cont
= OnCmdLineHelp(parser
);
232 cont
= OnCmdLineParsed(parser
);
236 cont
= OnCmdLineError(parser
);
242 #endif // wxUSE_CMDLINE_PARSER
247 int wxAppConsoleBase::OnRun()
252 int wxAppConsoleBase::OnExit()
255 // delete the config object if any (don't use Get() here, but Set()
256 // because Get() could create a new config object)
257 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
258 #endif // wxUSE_CONFIG
263 void wxAppConsoleBase::Exit()
265 if (m_mainLoop
!= NULL
)
271 // ----------------------------------------------------------------------------
273 // ----------------------------------------------------------------------------
275 wxAppTraits
*wxAppConsoleBase::CreateTraits()
277 return new wxConsoleAppTraits
;
280 wxAppTraits
*wxAppConsoleBase::GetTraits()
282 // FIXME-MT: protect this with a CS?
285 m_traits
= CreateTraits();
287 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
294 wxAppTraits
*wxAppConsoleBase::GetTraitsIfExists()
296 wxAppConsole
* const app
= GetInstance();
297 return app
? app
->GetTraits() : NULL
;
300 // ----------------------------------------------------------------------------
302 // ----------------------------------------------------------------------------
304 int wxAppConsoleBase::MainLoop()
306 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
308 return m_mainLoop
? m_mainLoop
->Run() : -1;
311 void wxAppConsoleBase::ExitMainLoop()
313 // we should exit from the main event loop, not just any currently active
314 // (e.g. modal dialog) event loop
315 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
321 bool wxAppConsoleBase::Pending()
323 // use the currently active message loop here, not m_mainLoop, because if
324 // we're showing a modal dialog (with its own event loop) currently the
325 // main event loop is not running anyhow
326 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
328 return loop
&& loop
->Pending();
331 bool wxAppConsoleBase::Dispatch()
333 // see comment in Pending()
334 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
336 return loop
&& loop
->Dispatch();
339 bool wxAppConsoleBase::HasPendingEvents() const
341 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
343 bool has
= wxPendingEvents
&& !wxPendingEvents
->IsEmpty();
345 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
351 bool wxAppConsoleBase::IsMainLoopRunning()
353 const wxAppConsole
* const app
= GetInstance();
355 return app
&& app
->m_mainLoop
!= NULL
;
358 void wxAppConsoleBase::ProcessPendingEvents()
361 if ( !wxPendingEventsLocker
)
365 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
369 // iterate until the list becomes empty: the handlers remove themselves
370 // from it when they don't have any more pending events
371 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
374 // In ProcessPendingEvents(), new handlers might be add
375 // and we can safely leave the critical section here.
376 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
378 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
379 handler
->ProcessPendingEvents();
381 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
383 // restart as the iterators could have been invalidated
384 node
= wxPendingEvents
->GetFirst();
388 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
391 void wxAppConsoleBase::WakeUpIdle()
394 m_mainLoop
->WakeUp();
397 bool wxAppConsoleBase::ProcessIdle()
401 event
.SetEventObject(this);
403 return event
.MoreRequested();
406 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
408 // process the events normally by default
412 // ----------------------------------------------------------------------------
413 // exception handling
414 // ----------------------------------------------------------------------------
419 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
420 wxEventFunction func
,
421 wxEvent
& event
) const
423 // by default, simply call the handler
424 (handler
->*func
)(event
);
427 void wxAppConsoleBase::OnUnhandledException()
430 // we're called from an exception handler so we can re-throw the exception
431 // to recover its type
438 catch ( std::exception
& e
)
440 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
441 typeid(e
).name(), e
.what());
446 what
= "unknown exception";
449 wxMessageOutputBest().Printf(
450 "*** Caught unhandled %s; terminating\n", what
452 #endif // __WXDEBUG__
455 // ----------------------------------------------------------------------------
456 // exceptions support
457 // ----------------------------------------------------------------------------
459 bool wxAppConsoleBase::OnExceptionInMainLoop()
463 // some compilers are too stupid to know that we never return after throw
464 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
469 #endif // wxUSE_EXCEPTIONS
471 // ----------------------------------------------------------------------------
473 // ----------------------------------------------------------------------------
475 #if wxUSE_CMDLINE_PARSER
477 #define OPTION_VERBOSE "verbose"
479 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
481 // the standard command line options
482 static const wxCmdLineEntryDesc cmdLineDesc
[] =
488 gettext_noop("show this help message"),
490 wxCMD_LINE_OPTION_HELP
498 gettext_noop("generate verbose log messages"),
508 parser
.SetDesc(cmdLineDesc
);
511 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
514 if ( parser
.Found(OPTION_VERBOSE
) )
516 wxLog::SetVerbose(true);
525 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
532 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
539 #endif // wxUSE_CMDLINE_PARSER
541 // ----------------------------------------------------------------------------
543 // ----------------------------------------------------------------------------
546 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
547 const char *componentName
)
549 #if 0 // can't use wxLogTrace, not up and running yet
550 printf("checking build options object '%s' (ptr %p) in '%s'\n",
551 optionsSignature
, optionsSignature
, componentName
);
554 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
556 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
557 wxString prog
= wxString::FromAscii(optionsSignature
);
558 wxString progName
= wxString::FromAscii(componentName
);
561 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
562 lib
.c_str(), progName
.c_str(), prog
.c_str());
564 wxLogFatalError(msg
.c_str());
566 // normally wxLogFatalError doesn't return
576 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
582 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
585 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
590 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
593 #endif // __WXDEBUG__
595 // ============================================================================
596 // other classes implementations
597 // ============================================================================
599 // ----------------------------------------------------------------------------
600 // wxConsoleAppTraitsBase
601 // ----------------------------------------------------------------------------
605 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
607 return new wxLogStderr
;
612 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
614 return new wxMessageOutputStderr
;
619 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
621 return (wxFontMapper
*)new wxFontMapperBase
;
624 #endif // wxUSE_FONTMAP
626 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
628 // console applications don't use renderers
633 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
635 return wxAppTraitsBase::ShowAssertDialog(msg
);
639 bool wxConsoleAppTraitsBase::HasStderr()
641 // console applications always have stderr, even under Mac/Windows
645 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
650 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
655 // ----------------------------------------------------------------------------
657 // ----------------------------------------------------------------------------
660 void wxAppTraitsBase::SetLocale()
662 wxSetlocale(LC_ALL
, "");
663 wxUpdateLocaleIsUtf8();
668 void wxMutexGuiEnterImpl();
669 void wxMutexGuiLeaveImpl();
671 void wxAppTraitsBase::MutexGuiEnter()
673 wxMutexGuiEnterImpl();
676 void wxAppTraitsBase::MutexGuiLeave()
678 wxMutexGuiLeaveImpl();
681 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
683 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
685 traits
->MutexGuiEnter();
688 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
690 wxAppTraits
* const traits
= wxAppConsoleBase::GetTraitsIfExists();
692 traits
->MutexGuiLeave();
694 #endif // wxUSE_THREADS
698 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
700 wxString msg
= msgOriginal
;
702 #if wxUSE_STACKWALKER
703 #if !defined(__WXMSW__)
704 // on Unix stack frame generation may take some time, depending on the
705 // size of the executable mainly... warn the user that we are working
706 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
710 const wxString stackTrace
= GetAssertStackTrace();
711 if ( !stackTrace
.empty() )
712 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
713 #endif // wxUSE_STACKWALKER
715 return DoShowAssertDialog(msg
);
718 #if wxUSE_STACKWALKER
719 wxString
wxAppTraitsBase::GetAssertStackTrace()
723 class StackDump
: public wxStackWalker
728 const wxString
& GetStackTrace() const { return m_stackTrace
; }
731 virtual void OnStackFrame(const wxStackFrame
& frame
)
733 m_stackTrace
<< wxString::Format
736 wx_truncate_cast(int, frame
.GetLevel())
739 wxString name
= frame
.GetName();
742 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
746 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
749 if ( frame
.HasSourceLocation() )
751 m_stackTrace
<< _T('\t')
752 << frame
.GetFileName()
757 m_stackTrace
<< _T('\n');
761 wxString m_stackTrace
;
764 // don't show more than maxLines or we could get a dialog too tall to be
765 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
766 // characters it is still only 300 pixels...
767 static const int maxLines
= 20;
770 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
771 stackTrace
= dump
.GetStackTrace();
773 const int count
= stackTrace
.Freq(wxT('\n'));
774 for ( int i
= 0; i
< count
- maxLines
; i
++ )
775 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
779 #endif // wxUSE_STACKWALKER
782 #endif // __WXDEBUG__
784 // ============================================================================
785 // global functions implementation
786 // ============================================================================
796 // what else can we do?
805 wxTheApp
->WakeUpIdle();
807 //else: do nothing, what can we do?
813 bool wxAssertIsEqual(int x
, int y
)
818 // break into the debugger
821 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
823 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
825 #elif defined(__UNIX__)
832 // this function is called when an assert fails
833 static void wxDoOnAssert(const wxString
& szFile
,
835 const wxString
& szFunc
,
836 const wxString
& szCond
,
837 const wxString
& szMsg
= wxEmptyString
)
840 static int s_bInAssert
= 0;
842 wxRecursionGuard
guard(s_bInAssert
);
843 if ( guard
.IsInside() )
845 // can't use assert here to avoid infinite loops, so just trap
853 // by default, show the assert dialog box -- we can't customize this
855 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
859 // let the app process it as it wants
860 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
861 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
862 szCond
.c_str(), szMsg
.c_str());
866 void wxOnAssert(const wxString
& szFile
,
868 const wxString
& szFunc
,
869 const wxString
& szCond
,
870 const wxString
& szMsg
)
872 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
875 void wxOnAssert(const wxString
& szFile
,
877 const wxString
& szFunc
,
878 const wxString
& szCond
)
880 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
883 void wxOnAssert(const wxChar
*szFile
,
886 const wxChar
*szCond
,
889 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
892 void wxOnAssert(const char *szFile
,
896 const wxString
& szMsg
)
898 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
901 void wxOnAssert(const char *szFile
,
905 const wxCStrData
& msg
)
907 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, msg
);
911 void wxOnAssert(const char *szFile
,
916 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
919 void wxOnAssert(const char *szFile
,
925 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
928 void wxOnAssert(const char *szFile
,
934 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
936 #endif // wxUSE_UNICODE
938 #endif // __WXDEBUG__
940 // ============================================================================
941 // private functions implementation
942 // ============================================================================
946 static void LINKAGEMODE
SetTraceMasks()
950 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
952 wxStringTokenizer
tkn(mask
, wxT(",;:"));
953 while ( tkn
.HasMoreTokens() )
954 wxLog::AddTraceMask(tkn
.GetNextToken());
960 bool DoShowAssertDialog(const wxString
& msg
)
962 // under MSW we can show the dialog even in the console mode
963 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
964 wxString
msgDlg(msg
);
966 // this message is intentionally not translated -- it is for
968 msgDlg
+= wxT("\nDo you want to stop the program?\n")
969 wxT("You can also choose [Cancel] to suppress ")
970 wxT("further warnings.");
972 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), _T("wxWidgets Debug Alert"),
973 MB_YESNOCANCEL
| MB_ICONSTOP
) )
983 //case IDNO: nothing to do
986 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
989 // TODO: ask the user to enter "Y" or "N" on the console?
991 #endif // __WXMSW__/!__WXMSW__
993 // continue with the asserts
997 // show the assert modal dialog
999 void ShowAssertDialog(const wxString
& szFile
,
1001 const wxString
& szFunc
,
1002 const wxString
& szCond
,
1003 const wxString
& szMsg
,
1004 wxAppTraits
*traits
)
1006 // this variable can be set to true to suppress "assert failure" messages
1007 static bool s_bNoAsserts
= false;
1012 // make life easier for people using VC++ IDE by using this format: like
1013 // this, clicking on the message will take us immediately to the place of
1014 // the failed assert
1015 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
1017 // add the function name, if any
1018 if ( !szFunc
.empty() )
1019 msg
<< _T(" in ") << szFunc
<< _T("()");
1021 // and the message itself
1022 if ( !szMsg
.empty() )
1024 msg
<< _T(": ") << szMsg
;
1026 else // no message given
1032 // if we are not in the main thread, output the assert directly and trap
1033 // since dialogs cannot be displayed
1034 if ( !wxThread::IsMain() )
1036 msg
+= wxT(" [in child thread]");
1038 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1040 OutputDebugString(msg
.wx_str());
1043 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1046 // He-e-e-e-elp!! we're asserting in a child thread
1050 #endif // wxUSE_THREADS
1052 if ( !s_bNoAsserts
)
1054 // send it to the normal log destination
1055 wxLogDebug(_T("%s"), msg
.c_str());
1059 // delegate showing assert dialog (if possible) to that class
1060 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1062 else // no traits object
1064 // fall back to the function of last resort
1065 s_bNoAsserts
= DoShowAssertDialog(msg
);
1070 #endif // __WXDEBUG__