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 !defined(__WXMSW__) || defined(__WXMICROWIN__)
49 #include <signal.h> // for SIGTRAP used by wxTrap()
55 #include "wx/fontmap.h"
56 #endif // wxUSE_FONTMAP
58 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
59 // For MacTypes.h for Debugger function
60 #include <CoreFoundation/CFBase.h>
63 #if defined(__WXMAC__)
65 #include <CoreServices/CoreServices.h>
67 #include "wx/mac/private.h" // includes mac headers
73 #include "wx/stackwalk.h"
75 #include "wx/msw/debughlp.h"
77 #endif // wxUSE_STACKWALKER
80 // wxABI_VERSION can be defined when compiling applications but it should be
81 // left undefined when compiling the library itself, it is then set to its
82 // default value in version.h
83 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
84 #error "wxABI_VERSION should not be defined when compiling the library"
87 // ----------------------------------------------------------------------------
88 // private functions prototypes
89 // ----------------------------------------------------------------------------
92 // really just show the assert dialog
93 static bool DoShowAssertDialog(const wxString
& msg
);
95 // prepare for showing the assert dialog, use the given traits or
96 // DoShowAssertDialog() as last fallback to really show it
98 void ShowAssertDialog(const wxString
& szFile
,
100 const wxString
& szFunc
,
101 const wxString
& szCond
,
102 const wxString
& szMsg
,
103 wxAppTraits
*traits
= NULL
);
105 // turn on the trace masks specified in the env variable WXTRACE
106 static void LINKAGEMODE
SetTraceMasks();
107 #endif // __WXDEBUG__
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 wxAppConsole
*wxAppConsoleBase::ms_appInstance
= NULL
;
115 wxAppInitializerFunction
wxAppConsoleBase::ms_appInitFn
= NULL
;
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 // this defines wxEventLoopPtr
122 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase
)
124 // ============================================================================
125 // wxAppConsoleBase implementation
126 // ============================================================================
128 // ----------------------------------------------------------------------------
130 // ----------------------------------------------------------------------------
132 wxAppConsoleBase::wxAppConsoleBase()
137 ms_appInstance
= wx_static_cast(wxAppConsole
*, this);
142 // In unicode mode the SetTraceMasks call can cause an apptraits to be
143 // created, but since we are still in the constructor the wrong kind will
144 // be created for GUI apps. Destroy it so it can be created again later.
151 wxAppConsoleBase::~wxAppConsoleBase()
156 // ----------------------------------------------------------------------------
157 // initilization/cleanup
158 // ----------------------------------------------------------------------------
160 bool wxAppConsoleBase::Initialize(int& argcOrig
, wxChar
**argvOrig
)
163 GetTraits()->SetLocale();
166 // remember the command line arguments
171 wxPendingEventsLocker
= new wxCriticalSection
;
175 if ( m_appName
.empty() && argv
)
177 // the application name is, by default, the name of its executable file
178 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
180 #endif // !__WXPALMOS__
185 wxEventLoopBase
*wxAppConsoleBase::CreateMainLoop()
187 return GetTraits()->CreateEventLoop();
190 void wxAppConsoleBase::CleanUp()
198 delete wxPendingEvents
;
199 wxPendingEvents
= NULL
;
202 delete wxPendingEventsLocker
;
203 wxPendingEventsLocker
= NULL
;
204 #endif // wxUSE_THREADS
207 // ----------------------------------------------------------------------------
209 // ----------------------------------------------------------------------------
211 bool wxAppConsoleBase::OnInit()
213 #if wxUSE_CMDLINE_PARSER
214 wxCmdLineParser
parser(argc
, argv
);
216 OnInitCmdLine(parser
);
219 switch ( parser
.Parse(false /* don't show usage */) )
222 cont
= OnCmdLineHelp(parser
);
226 cont
= OnCmdLineParsed(parser
);
230 cont
= OnCmdLineError(parser
);
236 #endif // wxUSE_CMDLINE_PARSER
241 int wxAppConsoleBase::OnRun()
246 int wxAppConsoleBase::OnExit()
249 // delete the config object if any (don't use Get() here, but Set()
250 // because Get() could create a new config object)
251 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
252 #endif // wxUSE_CONFIG
257 void wxAppConsoleBase::Exit()
259 if (m_mainLoop
!= NULL
)
265 // ----------------------------------------------------------------------------
267 // ----------------------------------------------------------------------------
269 wxAppTraits
*wxAppConsoleBase::CreateTraits()
271 return new wxConsoleAppTraits
;
274 wxAppTraits
*wxAppConsoleBase::GetTraits()
276 // FIXME-MT: protect this with a CS?
279 m_traits
= CreateTraits();
281 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
287 // ----------------------------------------------------------------------------
289 // ----------------------------------------------------------------------------
291 int wxAppConsoleBase::MainLoop()
293 wxEventLoopBaseTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
295 return m_mainLoop
? m_mainLoop
->Run() : -1;
298 void wxAppConsoleBase::ExitMainLoop()
300 // we should exit from the main event loop, not just any currently active
301 // (e.g. modal dialog) event loop
302 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
308 bool wxAppConsoleBase::Pending()
310 // use the currently active message loop here, not m_mainLoop, because if
311 // we're showing a modal dialog (with its own event loop) currently the
312 // main event loop is not running anyhow
313 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
315 return loop
&& loop
->Pending();
318 bool wxAppConsoleBase::Dispatch()
320 // see comment in Pending()
321 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
323 return loop
&& loop
->Dispatch();
326 bool wxAppConsoleBase::HasPendingEvents() const
328 // ensure that we're the only thread to modify the pending events list
329 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
331 if ( !wxPendingEvents
)
333 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
336 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
341 bool wxAppConsoleBase::IsMainLoopRunning()
343 const wxAppConsole
* const app
= GetInstance();
345 return app
&& app
->m_mainLoop
!= NULL
;
348 void wxAppConsoleBase::ProcessPendingEvents()
351 if ( !wxPendingEventsLocker
)
355 if ( !HasPendingEvents() )
358 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
360 // iterate until the list becomes empty
361 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
364 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
365 wxPendingEvents
->Erase(node
);
367 // In ProcessPendingEvents(), new handlers might be add
368 // and we can safely leave the critical section here.
369 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
371 handler
->ProcessPendingEvents();
373 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
375 node
= wxPendingEvents
->GetFirst();
378 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
381 void wxAppConsoleBase::WakeUpIdle()
384 m_mainLoop
->WakeUp();
387 bool wxAppConsoleBase::ProcessIdle()
391 event
.SetEventObject(this);
393 return event
.MoreRequested();
396 int wxAppConsoleBase::FilterEvent(wxEvent
& WXUNUSED(event
))
398 // process the events normally by default
402 // ----------------------------------------------------------------------------
403 // exception handling
404 // ----------------------------------------------------------------------------
409 wxAppConsoleBase::HandleEvent(wxEvtHandler
*handler
,
410 wxEventFunction func
,
411 wxEvent
& event
) const
413 // by default, simply call the handler
414 (handler
->*func
)(event
);
417 // ----------------------------------------------------------------------------
418 // exceptions support
419 // ----------------------------------------------------------------------------
423 bool wxAppConsoleBase::OnExceptionInMainLoop()
427 // some compilers are too stupid to know that we never return after throw
428 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
433 #endif // wxUSE_EXCEPTIONS
436 #endif // wxUSE_EXCEPTIONS
438 // ----------------------------------------------------------------------------
440 // ----------------------------------------------------------------------------
442 #if wxUSE_CMDLINE_PARSER
444 #define OPTION_VERBOSE _T("verbose")
446 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser
& parser
)
448 // the standard command line options
449 static const wxCmdLineEntryDesc cmdLineDesc
[] =
455 gettext_noop("show this help message"),
457 wxCMD_LINE_OPTION_HELP
465 gettext_noop("generate verbose log messages"),
482 parser
.SetDesc(cmdLineDesc
);
485 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
488 if ( parser
.Found(OPTION_VERBOSE
) )
490 wxLog::SetVerbose(true);
499 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser
& parser
)
506 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser
& parser
)
513 #endif // wxUSE_CMDLINE_PARSER
515 // ----------------------------------------------------------------------------
517 // ----------------------------------------------------------------------------
520 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature
,
521 const char *componentName
)
523 #if 0 // can't use wxLogTrace, not up and running yet
524 printf("checking build options object '%s' (ptr %p) in '%s'\n",
525 optionsSignature
, optionsSignature
, componentName
);
528 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
530 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
531 wxString prog
= wxString::FromAscii(optionsSignature
);
532 wxString progName
= wxString::FromAscii(componentName
);
535 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
536 lib
.c_str(), progName
.c_str(), prog
.c_str());
538 wxLogFatalError(msg
.c_str());
540 // normally wxLogFatalError doesn't return
550 void wxAppConsoleBase::OnAssertFailure(const wxChar
*file
,
556 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
559 void wxAppConsoleBase::OnAssert(const wxChar
*file
,
564 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
567 #endif // __WXDEBUG__
569 // ============================================================================
570 // other classes implementations
571 // ============================================================================
573 // ----------------------------------------------------------------------------
574 // wxConsoleAppTraitsBase
575 // ----------------------------------------------------------------------------
579 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
581 return new wxLogStderr
;
586 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
588 return new wxMessageOutputStderr
;
593 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
595 return (wxFontMapper
*)new wxFontMapperBase
;
598 #endif // wxUSE_FONTMAP
600 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
602 // console applications don't use renderers
607 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
609 return wxAppTraitsBase::ShowAssertDialog(msg
);
613 bool wxConsoleAppTraitsBase::HasStderr()
615 // console applications always have stderr, even under Mac/Windows
619 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
624 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
630 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
636 // ----------------------------------------------------------------------------
638 // ----------------------------------------------------------------------------
641 void wxAppTraitsBase::SetLocale()
643 setlocale(LC_ALL
, "");
644 wxUpdateLocaleIsUtf8();
650 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
652 wxString msg
= msgOriginal
;
654 #if wxUSE_STACKWALKER
655 #if !defined(__WXMSW__)
656 // on Unix stack frame generation may take some time, depending on the
657 // size of the executable mainly... warn the user that we are working
658 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
662 const wxString stackTrace
= GetAssertStackTrace();
663 if ( !stackTrace
.empty() )
664 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
665 #endif // wxUSE_STACKWALKER
667 return DoShowAssertDialog(msg
);
670 #if wxUSE_STACKWALKER
671 wxString
wxAppTraitsBase::GetAssertStackTrace()
675 class StackDump
: public wxStackWalker
680 const wxString
& GetStackTrace() const { return m_stackTrace
; }
683 virtual void OnStackFrame(const wxStackFrame
& frame
)
685 m_stackTrace
<< wxString::Format
688 wx_truncate_cast(int, frame
.GetLevel())
691 wxString name
= frame
.GetName();
694 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
698 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
701 if ( frame
.HasSourceLocation() )
703 m_stackTrace
<< _T('\t')
704 << frame
.GetFileName()
709 m_stackTrace
<< _T('\n');
713 wxString m_stackTrace
;
716 // don't show more than maxLines or we could get a dialog too tall to be
717 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
718 // characters it is still only 300 pixels...
719 static const int maxLines
= 20;
722 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
723 stackTrace
= dump
.GetStackTrace();
725 const int count
= stackTrace
.Freq(wxT('\n'));
726 for ( int i
= 0; i
< count
- maxLines
; i
++ )
727 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
731 #endif // wxUSE_STACKWALKER
734 #endif // __WXDEBUG__
736 // ============================================================================
737 // global functions implementation
738 // ============================================================================
748 // what else can we do?
757 wxTheApp
->WakeUpIdle();
759 //else: do nothing, what can we do?
765 bool wxAssertIsEqual(int x
, int y
)
770 // break into the debugger
773 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
775 #elif defined(__WXMAC__) && !defined(__DARWIN__)
781 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
783 #elif defined(__UNIX__)
790 // this function is called when an assert fails
791 static void wxDoOnAssert(const wxString
& szFile
,
793 const wxString
& szFunc
,
794 const wxString
& szCond
,
795 const wxString
& szMsg
= wxEmptyString
)
798 static bool s_bInAssert
= false;
802 // He-e-e-e-elp!! we're trapped in endless loop
814 // by default, show the assert dialog box -- we can't customize this
816 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
820 // let the app process it as it wants
821 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
822 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
823 szCond
.c_str(), szMsg
.c_str());
829 void wxOnAssert(const wxString
& szFile
,
831 const wxString
& szFunc
,
832 const wxString
& szCond
,
833 const wxString
& szMsg
)
835 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
838 void wxOnAssert(const wxString
& szFile
,
840 const wxString
& szFunc
,
841 const wxString
& szCond
)
843 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
846 void wxOnAssert(const wxChar
*szFile
,
849 const wxChar
*szCond
,
852 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
855 void wxOnAssert(const char *szFile
,
859 const wxString
& szMsg
)
861 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
864 void wxOnAssert(const char *szFile
,
868 const wxCStrData
& msg
)
870 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, msg
);
874 void wxOnAssert(const char *szFile
,
879 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
882 void wxOnAssert(const char *szFile
,
888 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
891 void wxOnAssert(const char *szFile
,
897 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
899 #endif // wxUSE_UNICODE
901 #endif // __WXDEBUG__
903 // ============================================================================
904 // private functions implementation
905 // ============================================================================
909 static void LINKAGEMODE
SetTraceMasks()
913 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
915 wxStringTokenizer
tkn(mask
, wxT(",;:"));
916 while ( tkn
.HasMoreTokens() )
917 wxLog::AddTraceMask(tkn
.GetNextToken());
922 bool DoShowAssertDialog(const wxString
& msg
)
924 // under MSW we can show the dialog even in the console mode
925 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
926 wxString
msgDlg(msg
);
928 // this message is intentionally not translated -- it is for
930 msgDlg
+= wxT("\nDo you want to stop the program?\n")
931 wxT("You can also choose [Cancel] to suppress ")
932 wxT("further warnings.");
934 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
935 MB_YESNOCANCEL
| MB_ICONSTOP
) )
945 //case IDNO: nothing to do
948 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
951 // TODO: ask the user to enter "Y" or "N" on the console?
953 #endif // __WXMSW__/!__WXMSW__
955 // continue with the asserts
959 // show the assert modal dialog
961 void ShowAssertDialog(const wxString
& szFile
,
963 const wxString
& szFunc
,
964 const wxString
& szCond
,
965 const wxString
& szMsg
,
968 // this variable can be set to true to suppress "assert failure" messages
969 static bool s_bNoAsserts
= false;
974 // make life easier for people using VC++ IDE by using this format: like
975 // this, clicking on the message will take us immediately to the place of
977 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
979 // add the function name, if any
980 if ( !szFunc
.empty() )
981 msg
<< _T(" in ") << szFunc
<< _T("()");
983 // and the message itself
984 if ( !szMsg
.empty() )
986 msg
<< _T(": ") << szMsg
;
988 else // no message given
994 // if we are not in the main thread, output the assert directly and trap
995 // since dialogs cannot be displayed
996 if ( !wxThread::IsMain() )
998 msg
+= wxT(" [in child thread]");
1000 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1002 OutputDebugString(msg
);
1005 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
1008 // He-e-e-e-elp!! we're asserting in a child thread
1012 #endif // wxUSE_THREADS
1014 if ( !s_bNoAsserts
)
1016 // send it to the normal log destination
1017 wxLogDebug(_T("%s"), msg
.c_str());
1021 // delegate showing assert dialog (if possible) to that class
1022 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1024 else // no traits object
1026 // fall back to the function of last resort
1027 s_bNoAsserts
= DoShowAssertDialog(msg
);
1032 #endif // __WXDEBUG__