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 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
*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 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
352 // iterate until the list becomes empty
353 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
356 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
357 wxPendingEvents
->Erase(node
);
359 // In ProcessPendingEvents(), new handlers might be add
360 // and we can safely leave the critical section here.
361 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
363 handler
->ProcessPendingEvents();
365 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
367 node
= wxPendingEvents
->GetFirst();
370 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
373 void wxAppConsole::WakeUpIdle()
376 m_mainLoop
->WakeUp();
379 bool wxAppConsole::ProcessIdle()
383 event
.SetEventObject(this);
385 return event
.MoreRequested();
388 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
390 // process the events normally by default
394 // ----------------------------------------------------------------------------
395 // exception handling
396 // ----------------------------------------------------------------------------
401 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
402 wxEventFunction func
,
403 wxEvent
& event
) const
405 // by default, simply call the handler
406 (handler
->*func
)(event
);
409 // ----------------------------------------------------------------------------
410 // exceptions support
411 // ----------------------------------------------------------------------------
415 bool wxAppConsole::OnExceptionInMainLoop()
419 // some compilers are too stupid to know that we never return after throw
420 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
425 #endif // wxUSE_EXCEPTIONS
428 #endif // wxUSE_EXCEPTIONS
430 // ----------------------------------------------------------------------------
432 // ----------------------------------------------------------------------------
434 #if wxUSE_CMDLINE_PARSER
436 #define OPTION_VERBOSE _T("verbose")
438 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
440 // the standard command line options
441 static const wxCmdLineEntryDesc cmdLineDesc
[] =
447 gettext_noop("show this help message"),
449 wxCMD_LINE_OPTION_HELP
457 gettext_noop("generate verbose log messages"),
474 parser
.SetDesc(cmdLineDesc
);
477 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
480 if ( parser
.Found(OPTION_VERBOSE
) )
482 wxLog::SetVerbose(true);
491 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
498 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
505 #endif // wxUSE_CMDLINE_PARSER
507 // ----------------------------------------------------------------------------
509 // ----------------------------------------------------------------------------
512 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
513 const char *componentName
)
515 #if 0 // can't use wxLogTrace, not up and running yet
516 printf("checking build options object '%s' (ptr %p) in '%s'\n",
517 optionsSignature
, optionsSignature
, componentName
);
520 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
522 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
523 wxString prog
= wxString::FromAscii(optionsSignature
);
524 wxString progName
= wxString::FromAscii(componentName
);
527 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
528 lib
.c_str(), progName
.c_str(), prog
.c_str());
530 wxLogFatalError(msg
.c_str());
532 // normally wxLogFatalError doesn't return
542 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
548 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
551 void wxAppConsole::OnAssert(const wxChar
*file
,
556 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
559 #endif // __WXDEBUG__
561 // ============================================================================
562 // other classes implementations
563 // ============================================================================
565 // ----------------------------------------------------------------------------
566 // wxConsoleAppTraitsBase
567 // ----------------------------------------------------------------------------
571 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
573 return new wxLogStderr
;
578 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
580 return new wxMessageOutputStderr
;
585 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
587 return (wxFontMapper
*)new wxFontMapperBase
;
590 #endif // wxUSE_FONTMAP
592 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
594 // console applications don't use renderers
599 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
601 return wxAppTraitsBase::ShowAssertDialog(msg
);
605 bool wxConsoleAppTraitsBase::HasStderr()
607 // console applications always have stderr, even under Mac/Windows
611 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
616 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
622 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
628 // ----------------------------------------------------------------------------
630 // ----------------------------------------------------------------------------
633 void wxAppTraitsBase::SetLocale()
635 setlocale(LC_ALL
, "");
636 wxUpdateLocaleIsUtf8();
642 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
644 wxString msg
= msgOriginal
;
646 #if wxUSE_STACKWALKER
647 #if !defined(__WXMSW__)
648 // on Unix stack frame generation may take some time, depending on the
649 // size of the executable mainly... warn the user that we are working
650 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
654 const wxString stackTrace
= GetAssertStackTrace();
655 if ( !stackTrace
.empty() )
656 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
657 #endif // wxUSE_STACKWALKER
659 return DoShowAssertDialog(msg
);
662 #if wxUSE_STACKWALKER
663 wxString
wxAppTraitsBase::GetAssertStackTrace()
667 class StackDump
: public wxStackWalker
672 const wxString
& GetStackTrace() const { return m_stackTrace
; }
675 virtual void OnStackFrame(const wxStackFrame
& frame
)
677 m_stackTrace
<< wxString::Format
680 wx_truncate_cast(int, frame
.GetLevel())
683 wxString name
= frame
.GetName();
686 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
690 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
693 if ( frame
.HasSourceLocation() )
695 m_stackTrace
<< _T('\t')
696 << frame
.GetFileName()
701 m_stackTrace
<< _T('\n');
705 wxString m_stackTrace
;
708 // don't show more than maxLines or we could get a dialog too tall to be
709 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
710 // characters it is still only 300 pixels...
711 static const int maxLines
= 20;
714 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
715 stackTrace
= dump
.GetStackTrace();
717 const int count
= stackTrace
.Freq(wxT('\n'));
718 for ( int i
= 0; i
< count
- maxLines
; i
++ )
719 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
723 #endif // wxUSE_STACKWALKER
726 #endif // __WXDEBUG__
728 // ============================================================================
729 // global functions implementation
730 // ============================================================================
740 // what else can we do?
749 wxTheApp
->WakeUpIdle();
751 //else: do nothing, what can we do?
757 bool wxAssertIsEqual(int x
, int y
)
762 // break into the debugger
765 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
767 #elif defined(__WXMAC__) && !defined(__DARWIN__)
773 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
775 #elif defined(__UNIX__)
782 // this function is called when an assert fails
783 static void wxDoOnAssert(const wxString
& szFile
,
785 const wxString
& szFunc
,
786 const wxString
& szCond
,
787 const wxString
& szMsg
= wxEmptyString
)
790 static bool s_bInAssert
= false;
794 // He-e-e-e-elp!! we're trapped in endless loop
806 // by default, show the assert dialog box -- we can't customize this
808 ShowAssertDialog(szFile
, nLine
, szFunc
, szCond
, szMsg
);
812 // let the app process it as it wants
813 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
814 wxTheApp
->OnAssertFailure(szFile
.c_str(), nLine
, szFunc
.c_str(),
815 szCond
.c_str(), szMsg
.c_str());
821 void wxOnAssert(const wxString
& szFile
,
823 const wxString
& szFunc
,
824 const wxString
& szCond
,
825 const wxString
& szMsg
)
827 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
830 void wxOnAssert(const wxString
& szFile
,
832 const wxString
& szFunc
,
833 const wxString
& szCond
)
835 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
838 void wxOnAssert(const wxChar
*szFile
,
841 const wxChar
*szCond
,
844 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
847 void wxOnAssert(const char *szFile
,
851 const wxString
& szMsg
)
853 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
857 void wxOnAssert(const char *szFile
,
862 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
);
865 void wxOnAssert(const char *szFile
,
871 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
874 void wxOnAssert(const char *szFile
,
880 wxDoOnAssert(szFile
, nLine
, szFunc
, szCond
, szMsg
);
882 #endif // wxUSE_UNICODE
884 #endif // __WXDEBUG__
886 // ============================================================================
887 // private functions implementation
888 // ============================================================================
892 static void LINKAGEMODE
SetTraceMasks()
896 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
898 wxStringTokenizer
tkn(mask
, wxT(",;:"));
899 while ( tkn
.HasMoreTokens() )
900 wxLog::AddTraceMask(tkn
.GetNextToken());
905 bool DoShowAssertDialog(const wxString
& msg
)
907 // under MSW we can show the dialog even in the console mode
908 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
909 wxString
msgDlg(msg
);
911 // this message is intentionally not translated -- it is for
913 msgDlg
+= wxT("\nDo you want to stop the program?\n")
914 wxT("You can also choose [Cancel] to suppress ")
915 wxT("further warnings.");
917 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
918 MB_YESNOCANCEL
| MB_ICONSTOP
) )
928 //case IDNO: nothing to do
931 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
934 // TODO: ask the user to enter "Y" or "N" on the console?
936 #endif // __WXMSW__/!__WXMSW__
938 // continue with the asserts
942 // show the assert modal dialog
944 void ShowAssertDialog(const wxString
& szFile
,
946 const wxString
& szFunc
,
947 const wxString
& szCond
,
948 const wxString
& szMsg
,
951 // this variable can be set to true to suppress "assert failure" messages
952 static bool s_bNoAsserts
= false;
957 // make life easier for people using VC++ IDE by using this format: like
958 // this, clicking on the message will take us immediately to the place of
960 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
962 // add the function name, if any
963 if ( !szFunc
.empty() )
964 msg
<< _T(" in ") << szFunc
<< _T("()");
966 // and the message itself
967 if ( !szMsg
.empty() )
969 msg
<< _T(": ") << szMsg
;
971 else // no message given
977 // if we are not in the main thread, output the assert directly and trap
978 // since dialogs cannot be displayed
979 if ( !wxThread::IsMain() )
981 msg
+= wxT(" [in child thread]");
983 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
985 OutputDebugString(msg
);
988 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
991 // He-e-e-e-elp!! we're asserting in a child thread
995 #endif // wxUSE_THREADS
999 // send it to the normal log destination
1000 wxLogDebug(_T("%s"), msg
.c_str());
1004 // delegate showing assert dialog (if possible) to that class
1005 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
1007 else // no traits object
1009 // fall back to the function of last resort
1010 s_bNoAsserts
= DoShowAssertDialog(msg
);
1015 #endif // __WXDEBUG__