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
86 // wxABI_VERSION can be defined when compiling applications but it should be
87 // left undefined when compiling the library itself, it is then set to its
88 // default value in version.h
89 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
90 #error "wxABI_VERSION should not be defined when compiling the library"
93 // ----------------------------------------------------------------------------
94 // private functions prototypes
95 // ----------------------------------------------------------------------------
98 // really just show the assert dialog
99 static bool DoShowAssertDialog(const wxString
& msg
);
101 // prepare for showing the assert dialog, use the given traits or
102 // DoShowAssertDialog() as last fallback to really show it
104 void ShowAssertDialog(const wxString
& szFile
,
106 const wxString
& szFunc
,
107 const wxString
& szCond
,
108 const wxString
& szMsg
,
109 wxAppTraits
*traits
= NULL
);
111 // turn on the trace masks specified in the env variable WXTRACE
112 static void LINKAGEMODE
SetTraceMasks();
113 #endif // __WXDEBUG__
115 // ----------------------------------------------------------------------------
117 // ----------------------------------------------------------------------------
119 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
121 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 // this defines wxEventLoopPtr
128 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
130 // ============================================================================
131 // wxAppConsoleBase implementation
132 // ============================================================================
134 // ----------------------------------------------------------------------------
136 // ----------------------------------------------------------------------------
138 wxAppConsoleBase::wxAppConsoleBase()
143 ms_appInstance
= wx_static_cast(wxAppConsole
*, this);
148 // In unicode mode the SetTraceMasks call can cause an apptraits to be
149 // created, but since we are still in the constructor the wrong kind will
150 // be created for GUI apps. Destroy it so it can be created again later.
157 wxAppConsoleBase::~wxAppConsoleBase()
162 // ----------------------------------------------------------------------------
163 // initilization/cleanup
164 // ----------------------------------------------------------------------------
166 bool wxAppConsoleBase::Initialize(int& argcOrig
, wxChar
**argvOrig
)
169 GetTraits()->SetLocale();
172 // remember the command line arguments
177 wxPendingEventsLocker
= new wxCriticalSection
;
181 if ( m_appName
.empty() && argv
)
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?") );
293 // ----------------------------------------------------------------------------
295 // ----------------------------------------------------------------------------
297 int wxAppConsoleBase::MainLoop()
299 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
301 return m_mainLoop
? m_mainLoop
->Run() : -1;
304 void wxAppConsoleBase::ExitMainLoop()
306 // we should exit from the main event loop, not just any currently active
307 // (e.g. modal dialog) event loop
308 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
314 bool wxAppConsoleBase::Pending()
316 // use the currently active message loop here, not m_mainLoop, because if
317 // we're showing a modal dialog (with its own event loop) currently the
318 // main event loop is not running anyhow
319 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
321 return loop
&& loop
->Pending();
324 bool wxAppConsoleBase::Dispatch()
326 // see comment in Pending()
327 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
329 return loop
&& loop
->Dispatch();
332 bool wxAppConsoleBase::HasPendingEvents() const
334 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
336 bool has
= wxPendingEvents
&& !wxPendingEvents
->IsEmpty();
338 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
344 bool wxAppConsoleBase::IsMainLoopRunning()
346 const wxAppConsole
* const app
= GetInstance();
348 return app
&& app
->m_mainLoop
!= NULL
;
351 void wxAppConsoleBase::ProcessPendingEvents()
354 if ( !wxPendingEventsLocker
)
358 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
362 // iterate until the list becomes empty
363 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
366 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
367 wxPendingEvents
->Erase(node
);
369 // In ProcessPendingEvents(), new handlers might be add
370 // and we can safely leave the critical section here.
371 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
373 handler
->ProcessPendingEvents();
375 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
377 node
= wxPendingEvents
->GetFirst();
381 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
384 void wxAppConsoleBase::WakeUpIdle()
387 m_mainLoop
->WakeUp();
390 bool wxAppConsoleBase::ProcessIdle()
394 event
.SetEventObject(this);
396 return event
.MoreRequested();
399 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
401 // process the events normally by default
405 // ----------------------------------------------------------------------------
406 // exception handling
407 // ----------------------------------------------------------------------------
412 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
413 wxEventFunction func
,
414 wxEvent
& event
) const
416 // by default, simply call the handler
417 (handler
->*func
)(event
);
420 void wxAppConsoleBase::OnUnhandledException()
423 // we're called from an exception handler so we can re-throw the exception
424 // to recover its type
431 catch ( std::exception
& e
)
433 what
.Printf("std::exception of type \"%s\", what() = \"%s\"",
434 typeid(e
).name(), e
.what());
439 what
= "unknown exception";
442 wxMessageOutputBest().Printf(
443 "*** Caught unhandled %s; terminating\n", what
445 #endif // __WXDEBUG__
448 // ----------------------------------------------------------------------------
449 // exceptions support
450 // ----------------------------------------------------------------------------
452 bool wxAppConsoleBase::OnExceptionInMainLoop()
456 // some compilers are too stupid to know that we never return after throw
457 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
462 #endif // wxUSE_EXCEPTIONS
464 // ----------------------------------------------------------------------------
466 // ----------------------------------------------------------------------------
468 #if wxUSE_CMDLINE_PARSER
470 #define OPTION_VERBOSE "verbose"
472 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
474 // the standard command line options
475 static const wxCmdLineEntryDesc cmdLineDesc
[] =
481 gettext_noop("show this help message"),
483 wxCMD_LINE_OPTION_HELP
491 gettext_noop("generate verbose log messages"),
501 parser
.SetDesc(cmdLineDesc
);
504 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
507 if ( parser
.Found(OPTION_VERBOSE
) )
509 wxLog::SetVerbose(true);
518 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
525 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
532 #endif // wxUSE_CMDLINE_PARSER
534 // ----------------------------------------------------------------------------
536 // ----------------------------------------------------------------------------
539 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
540 const char *componentName
)
542 #if 0 // can't use wxLogTrace, not up and running yet
543 printf("checking build options object '%s' (ptr %p) in '%s'\n",
544 optionsSignature
, optionsSignature
, componentName
);
547 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
549 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
550 wxString prog
= wxString::FromAscii(optionsSignature
);
551 wxString progName
= wxString::FromAscii(componentName
);
554 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
555 lib
.c_str(), progName
.c_str(), prog
.c_str());
557 wxLogFatalError(msg
.c_str());
559 // normally wxLogFatalError doesn't return
569 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
575 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
578 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
583 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
586 #endif // __WXDEBUG__
588 // ============================================================================
589 // other classes implementations
590 // ============================================================================
592 // ----------------------------------------------------------------------------
593 // wxConsoleAppTraitsBase
594 // ----------------------------------------------------------------------------
598 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
600 return new wxLogStderr
;
605 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
607 return new wxMessageOutputStderr
;
612 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
614 return (wxFontMapper
*)new wxFontMapperBase
;
617 #endif // wxUSE_FONTMAP
619 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
621 // console applications don't use renderers
626 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
628 return wxAppTraitsBase::ShowAssertDialog(msg
);
632 bool wxConsoleAppTraitsBase::HasStderr()
634 // console applications always have stderr, even under Mac/Windows
638 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
643 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
649 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
655 // ----------------------------------------------------------------------------
657 // ----------------------------------------------------------------------------
660 void wxAppTraitsBase::SetLocale()
662 wxSetlocale(LC_ALL
, "");
663 wxUpdateLocaleIsUtf8();
669 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
671 wxString msg
= msgOriginal
;
673 #if wxUSE_STACKWALKER
674 #if !defined(__WXMSW__)
675 // on Unix stack frame generation may take some time, depending on the
676 // size of the executable mainly... warn the user that we are working
677 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
681 const wxString stackTrace
= GetAssertStackTrace();
682 if ( !stackTrace
.empty() )
683 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
684 #endif // wxUSE_STACKWALKER
686 return DoShowAssertDialog(msg
);
689 #if wxUSE_STACKWALKER
690 wxString
wxAppTraitsBase::GetAssertStackTrace()
694 class StackDump
: public wxStackWalker
699 const wxString
& GetStackTrace() const { return m_stackTrace
; }
702 virtual void OnStackFrame(const wxStackFrame
& frame
)
704 m_stackTrace
<< wxString::Format
707 wx_truncate_cast(int, frame
.GetLevel())
710 wxString name
= frame
.GetName();
713 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
717 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
720 if ( frame
.HasSourceLocation() )
722 m_stackTrace
<< _T('\t')
723 << frame
.GetFileName()
728 m_stackTrace
<< _T('\n');
732 wxString m_stackTrace
;
735 // don't show more than maxLines or we could get a dialog too tall to be
736 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
737 // characters it is still only 300 pixels...
738 static const int maxLines
= 20;
741 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
742 stackTrace
= dump
.GetStackTrace();
744 const int count
= stackTrace
.Freq(wxT('\n'));
745 for ( int i
= 0; i
< count
- maxLines
; i
++ )
746 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
750 #endif // wxUSE_STACKWALKER
753 #endif // __WXDEBUG__
755 // ============================================================================
756 // global functions implementation
757 // ============================================================================
767 // what else can we do?
776 wxTheApp
->WakeUpIdle();
778 //else: do nothing, what can we do?
784 bool wxAssertIsEqual(int x
, int y
)
789 // break into the debugger
792 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
794 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
796 #elif defined(__UNIX__)
803 // this function is called when an assert fails
804 static void wxDoOnAssert(const wxString
& szFile
,
806 const wxString
& szFunc
,
807 const wxString
& szCond
,
808 const wxString
& szMsg
= wxEmptyString
)
811 static bool s_bInAssert
= false;
815 // He-e-e-e-elp!! we're trapped in endless loop
827 // by default, show the assert dialog box -- we can't customize this
829 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
833 // let the app process it as it wants
834 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
835 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
836 szCond
.c_str(), szMsg
.c_str());
842 void wxOnAssert(const wxString
& szFile
,
844 const wxString
& szFunc
,
845 const wxString
& szCond
,
846 const wxString
& szMsg
)
848 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
851 void wxOnAssert(const wxString
& szFile
,
853 const wxString
& szFunc
,
854 const wxString
& szCond
)
856 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
859 void wxOnAssert(const wxChar
*szFile
,
862 const wxChar
*szCond
,
865 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
868 void wxOnAssert(const char *szFile
,
872 const wxString
& szMsg
)
874 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
877 void wxOnAssert(const char *szFile
,
881 const wxCStrData
& msg
)
883 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, msg
);
887 void wxOnAssert(const char *szFile
,
892 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
895 void wxOnAssert(const char *szFile
,
901 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
904 void wxOnAssert(const char *szFile
,
910 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
912 #endif // wxUSE_UNICODE
914 #endif // __WXDEBUG__
916 // ============================================================================
917 // private functions implementation
918 // ============================================================================
922 static void LINKAGEMODE
SetTraceMasks()
926 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
928 wxStringTokenizer
tkn(mask
, wxT(",;:"));
929 while ( tkn
.HasMoreTokens() )
930 wxLog::AddTraceMask(tkn
.GetNextToken());
936 bool DoShowAssertDialog(const wxString
& msg
)
938 // under MSW we can show the dialog even in the console mode
939 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
940 wxString
msgDlg(msg
);
942 // this message is intentionally not translated -- it is for
944 msgDlg
+= wxT("\nDo you want to stop the program?\n")
945 wxT("You can also choose [Cancel] to suppress ")
946 wxT("further warnings.");
948 switch ( ::MessageBox(NULL
, msgDlg
.wx_str(), _T("wxWidgets Debug Alert"),
949 MB_YESNOCANCEL
| MB_ICONSTOP
) )
959 //case IDNO: nothing to do
962 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
965 // TODO: ask the user to enter "Y" or "N" on the console?
967 #endif // __WXMSW__/!__WXMSW__
969 // continue with the asserts
973 // show the assert modal dialog
975 void ShowAssertDialog(const wxString
& szFile
,
977 const wxString
& szFunc
,
978 const wxString
& szCond
,
979 const wxString
& szMsg
,
982 // this variable can be set to true to suppress "assert failure" messages
983 static bool s_bNoAsserts
= false;
988 // make life easier for people using VC++ IDE by using this format: like
989 // this, clicking on the message will take us immediately to the place of
991 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
993 // add the function name, if any
994 if ( !szFunc
.empty() )
995 msg
<< _T(" in ") << szFunc
<< _T("()");
997 // and the message itself
998 if ( !szMsg
.empty() )
1000 msg
<< _T(": ") << szMsg
;
1002 else // no message given
1008 // if we are not in the main thread, output the assert directly and trap
1009 // since dialogs cannot be displayed
1010 if ( !wxThread::IsMain() )
1012 msg
+= wxT(" [in child thread]");
1014 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1016 OutputDebugString(msg
.wx_str());
1019 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1022 // He-e-e-e-elp!! we're asserting in a child thread
1026 #endif // wxUSE_THREADS
1028 if ( !s_bNoAsserts
)
1030 // send it to the normal log destination
1031 wxLogDebug(_T("%s"), msg
.c_str());
1035 // delegate showing assert dialog (if possible) to that class
1036 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1038 else // no traits object
1040 // fall back to the function of last resort
1041 s_bNoAsserts
= DoShowAssertDialog(msg
);
1046 #endif // __WXDEBUG__