1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/appbase.cpp
3 // Purpose: implements wxAppConsole 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 wxChar
*szFile
,
100 const wxChar
*szFunc
,
101 const wxChar
*szCond
,
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
*wxAppConsole::ms_appInstance
= NULL
;
115 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 // this defines wxEventLoopPtr
122 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoop
)
124 // ============================================================================
125 // wxAppConsole implementation
126 // ============================================================================
128 // ----------------------------------------------------------------------------
130 // ----------------------------------------------------------------------------
132 wxAppConsole::wxAppConsole()
137 ms_appInstance
= 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 wxAppConsole::~wxAppConsole()
156 // ----------------------------------------------------------------------------
157 // initilization/cleanup
158 // ----------------------------------------------------------------------------
160 bool wxAppConsole::Initialize(int& argcOrig
, wxChar
**argvOrig
)
163 GetTraits()->SetLocale();
166 // remember the command line arguments
171 wxPendingEventsLocker
= new wxCriticalSection
;
174 // create port-specific main loop
175 m_mainLoop
= CreateMainLoop();
178 if ( m_appName
.empty() && argv
)
180 // the application name is, by default, the name of its executable file
181 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
183 #endif // !__WXPALMOS__
188 wxEventLoop
*wxAppConsole::CreateMainLoop()
190 return GetTraits()->CreateEventLoop();
193 void wxAppConsole::CleanUp()
198 delete wxPendingEvents
;
199 wxPendingEvents
= NULL
;
202 delete wxPendingEventsLocker
;
203 wxPendingEventsLocker
= NULL
;
204 #endif // wxUSE_THREADS
207 // ----------------------------------------------------------------------------
209 // ----------------------------------------------------------------------------
211 bool wxAppConsole::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 wxAppConsole::OnRun()
246 int wxAppConsole::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 wxAppConsole::Exit()
259 if (m_mainLoop
!= NULL
)
265 // ----------------------------------------------------------------------------
267 // ----------------------------------------------------------------------------
269 wxAppTraits
*wxAppConsole::CreateTraits()
271 return new wxConsoleAppTraits
;
274 wxAppTraits
*wxAppConsole::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 wxAppConsole::MainLoop()
293 wxEventLoopTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
295 return m_mainLoop
? m_mainLoop
->Run() : -1;
298 void wxAppConsole::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 wxAppConsole::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 wxEventLoop
* const loop
= wxEventLoopBase::GetActive();
315 return loop
&& loop
->Pending();
318 bool wxAppConsole::Dispatch()
320 // see comment in Pending()
321 wxEventLoop
* const loop
= wxEventLoopBase::GetActive();
323 return loop
&& loop
->Dispatch();
326 bool wxAppConsole::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
);
340 void wxAppConsole::ProcessPendingEvents()
343 if ( !wxPendingEventsLocker
)
347 if ( !HasPendingEvents() )
350 // iterate until the list becomes empty
351 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
354 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
355 wxPendingEvents
->Erase(node
);
357 // In ProcessPendingEvents(), new handlers might be add
358 // and we can safely leave the critical section here.
359 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
361 handler
->ProcessPendingEvents();
363 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
365 node
= wxPendingEvents
->GetFirst();
368 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
371 void wxAppConsole::WakeUpIdle()
374 m_mainLoop
->WakeUp();
377 bool wxAppConsole::ProcessIdle()
381 event
.SetEventObject(this);
383 return event
.MoreRequested();
386 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
388 // process the events normally by default
392 // ----------------------------------------------------------------------------
393 // exception handling
394 // ----------------------------------------------------------------------------
399 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
400 wxEventFunction func
,
401 wxEvent
& event
) const
403 // by default, simply call the handler
404 (handler
->*func
)(event
);
407 // ----------------------------------------------------------------------------
408 // exceptions support
409 // ----------------------------------------------------------------------------
413 bool wxAppConsole::OnExceptionInMainLoop()
417 // some compilers are too stupid to know that we never return after throw
418 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
423 #endif // wxUSE_EXCEPTIONS
426 #endif // wxUSE_EXCEPTIONS
428 // ----------------------------------------------------------------------------
430 // ----------------------------------------------------------------------------
432 #if wxUSE_CMDLINE_PARSER
434 #define OPTION_VERBOSE _T("verbose")
436 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
438 // the standard command line options
439 static const wxCmdLineEntryDesc cmdLineDesc
[] =
445 gettext_noop("show this help message"),
447 wxCMD_LINE_OPTION_HELP
455 gettext_noop("generate verbose log messages"),
472 parser
.SetDesc(cmdLineDesc
);
475 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
478 if ( parser
.Found(OPTION_VERBOSE
) )
480 wxLog::SetVerbose(true);
489 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
496 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
503 #endif // wxUSE_CMDLINE_PARSER
505 // ----------------------------------------------------------------------------
507 // ----------------------------------------------------------------------------
510 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
511 const char *componentName
)
513 #if 0 // can't use wxLogTrace, not up and running yet
514 printf("checking build options object '%s' (ptr %p) in '%s'\n",
515 optionsSignature
, optionsSignature
, componentName
);
518 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
520 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
521 wxString prog
= wxString::FromAscii(optionsSignature
);
522 wxString progName
= wxString::FromAscii(componentName
);
525 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
526 lib
.c_str(), progName
.c_str(), prog
.c_str());
528 wxLogFatalError(msg
.c_str());
530 // normally wxLogFatalError doesn't return
540 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
546 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
549 void wxAppConsole::OnAssert(const wxChar
*file
,
554 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
557 #endif // __WXDEBUG__
559 // ============================================================================
560 // other classes implementations
561 // ============================================================================
563 // ----------------------------------------------------------------------------
564 // wxConsoleAppTraitsBase
565 // ----------------------------------------------------------------------------
569 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
571 return new wxLogStderr
;
576 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
578 return new wxMessageOutputStderr
;
583 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
585 return (wxFontMapper
*)new wxFontMapperBase
;
588 #endif // wxUSE_FONTMAP
590 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
592 // console applications don't use renderers
597 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
599 return wxAppTraitsBase::ShowAssertDialog(msg
);
603 bool wxConsoleAppTraitsBase::HasStderr()
605 // console applications always have stderr, even under Mac/Windows
609 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
614 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
620 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
626 // ----------------------------------------------------------------------------
628 // ----------------------------------------------------------------------------
631 void wxAppTraitsBase::SetLocale()
633 setlocale(LC_ALL
, "");
634 wxUpdateLocaleIsUtf8();
640 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
642 wxString msg
= msgOriginal
;
644 #if wxUSE_STACKWALKER
645 #if !defined(__WXMSW__)
646 // on Unix stack frame generation may take some time, depending on the
647 // size of the executable mainly... warn the user that we are working
648 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
652 const wxString stackTrace
= GetAssertStackTrace();
653 if ( !stackTrace
.empty() )
654 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
655 #endif // wxUSE_STACKWALKER
657 return DoShowAssertDialog(msg
);
660 #if wxUSE_STACKWALKER
661 wxString
wxAppTraitsBase::GetAssertStackTrace()
665 class StackDump
: public wxStackWalker
670 const wxString
& GetStackTrace() const { return m_stackTrace
; }
673 virtual void OnStackFrame(const wxStackFrame
& frame
)
675 m_stackTrace
<< wxString::Format
678 wx_truncate_cast(int, frame
.GetLevel())
681 wxString name
= frame
.GetName();
684 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
688 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
691 if ( frame
.HasSourceLocation() )
693 m_stackTrace
<< _T('\t')
694 << frame
.GetFileName()
699 m_stackTrace
<< _T('\n');
703 wxString m_stackTrace
;
706 // don't show more than maxLines or we could get a dialog too tall to be
707 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
708 // characters it is still only 300 pixels...
709 static const int maxLines
= 20;
712 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
713 stackTrace
= dump
.GetStackTrace();
715 const int count
= stackTrace
.Freq(wxT('\n'));
716 for ( int i
= 0; i
< count
- maxLines
; i
++ )
717 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
721 #endif // wxUSE_STACKWALKER
724 #endif // __WXDEBUG__
726 // ============================================================================
727 // global functions implementation
728 // ============================================================================
738 // what else can we do?
747 wxTheApp
->WakeUpIdle();
749 //else: do nothing, what can we do?
755 bool wxAssertIsEqual(int x
, int y
)
760 // break into the debugger
763 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
765 #elif defined(__WXMAC__) && !defined(__DARWIN__)
771 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
773 #elif defined(__UNIX__)
780 // this function is called when an assert fails
781 void wxOnAssert(const wxChar
*szFile
,
784 const wxChar
*szCond
,
788 static bool s_bInAssert
= false;
792 // He-e-e-e-elp!! we're trapped in endless loop
802 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
803 const wxString strFunc
= wxString::FromAscii(szFunc
);
807 // by default, show the assert dialog box -- we can't customize this
809 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
813 // let the app process it as it wants
814 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
820 #endif // __WXDEBUG__
822 // ============================================================================
823 // private functions implementation
824 // ============================================================================
828 static void LINKAGEMODE
SetTraceMasks()
832 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
834 wxStringTokenizer
tkn(mask
, wxT(",;:"));
835 while ( tkn
.HasMoreTokens() )
836 wxLog::AddTraceMask(tkn
.GetNextToken());
841 bool DoShowAssertDialog(const wxString
& msg
)
843 // under MSW we can show the dialog even in the console mode
844 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
845 wxString
msgDlg(msg
);
847 // this message is intentionally not translated -- it is for
849 msgDlg
+= wxT("\nDo you want to stop the program?\n")
850 wxT("You can also choose [Cancel] to suppress ")
851 wxT("further warnings.");
853 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
854 MB_YESNOCANCEL
| MB_ICONSTOP
) )
864 //case IDNO: nothing to do
867 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
870 // TODO: ask the user to enter "Y" or "N" on the console?
872 #endif // __WXMSW__/!__WXMSW__
874 // continue with the asserts
878 // show the assert modal dialog
880 void ShowAssertDialog(const wxChar
*szFile
,
882 const wxChar
*szFunc
,
883 const wxChar
*szCond
,
887 // this variable can be set to true to suppress "assert failure" messages
888 static bool s_bNoAsserts
= false;
893 // make life easier for people using VC++ IDE by using this format: like
894 // this, clicking on the message will take us immediately to the place of
896 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
898 // add the function name, if any
899 if ( szFunc
&& *szFunc
)
900 msg
<< _T(" in ") << szFunc
<< _T("()");
902 // and the message itself
905 msg
<< _T(": ") << szMsg
;
907 else // no message given
913 // if we are not in the main thread, output the assert directly and trap
914 // since dialogs cannot be displayed
915 if ( !wxThread::IsMain() )
917 msg
+= wxT(" [in child thread]");
919 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
921 OutputDebugString(msg
);
924 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
927 // He-e-e-e-elp!! we're asserting in a child thread
931 #endif // wxUSE_THREADS
935 // send it to the normal log destination
936 wxLogDebug(_T("%s"), msg
.c_str());
940 // delegate showing assert dialog (if possible) to that class
941 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
943 else // no traits object
945 // fall back to the function of last resort
946 s_bNoAsserts
= DoShowAssertDialog(msg
);
951 #endif // __WXDEBUG__