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()
195 delete wxPendingEvents
;
196 wxPendingEvents
= NULL
;
199 delete wxPendingEventsLocker
;
200 wxPendingEventsLocker
= NULL
;
201 #endif // wxUSE_THREADS
204 // ----------------------------------------------------------------------------
206 // ----------------------------------------------------------------------------
208 bool wxAppConsole::OnInit()
210 #if wxUSE_CMDLINE_PARSER
211 wxCmdLineParser
parser(argc
, argv
);
213 OnInitCmdLine(parser
);
216 switch ( parser
.Parse(false /* don't show usage */) )
219 cont
= OnCmdLineHelp(parser
);
223 cont
= OnCmdLineParsed(parser
);
227 cont
= OnCmdLineError(parser
);
233 #endif // wxUSE_CMDLINE_PARSER
238 int wxAppConsole::OnRun()
243 int wxAppConsole::OnExit()
246 // delete the config object if any (don't use Get() here, but Set()
247 // because Get() could create a new config object)
248 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
249 #endif // wxUSE_CONFIG
254 void wxAppConsole::Exit()
256 if (m_mainLoop
!= NULL
)
262 // ----------------------------------------------------------------------------
264 // ----------------------------------------------------------------------------
266 wxAppTraits
*wxAppConsole::CreateTraits()
268 return new wxConsoleAppTraits
;
271 wxAppTraits
*wxAppConsole::GetTraits()
273 // FIXME-MT: protect this with a CS?
276 m_traits
= CreateTraits();
278 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
284 // ----------------------------------------------------------------------------
286 // ----------------------------------------------------------------------------
288 int wxAppConsole::MainLoop()
290 wxEventLoopTiedPtr
mainLoop(&m_mainLoop
, CreateMainLoop());
292 return m_mainLoop
? m_mainLoop
->Run() : -1;
295 void wxAppConsole::ExitMainLoop()
297 // we should exit from the main event loop, not just any currently active
298 // (e.g. modal dialog) event loop
299 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
305 bool wxAppConsole::Pending()
307 // use the currently active message loop here, not m_mainLoop, because if
308 // we're showing a modal dialog (with its own event loop) currently the
309 // main event loop is not running anyhow
310 wxEventLoop
* const loop
= wxEventLoopBase::GetActive();
312 return loop
&& loop
->Pending();
315 bool wxAppConsole::Dispatch()
317 // see comment in Pending()
318 wxEventLoop
* const loop
= wxEventLoopBase::GetActive();
320 return loop
&& loop
->Dispatch();
323 bool wxAppConsole::HasPendingEvents() const
325 // ensure that we're the only thread to modify the pending events list
326 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
328 if ( !wxPendingEvents
)
330 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
333 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
337 void wxAppConsole::ProcessPendingEvents()
340 if ( !wxPendingEventsLocker
)
344 if ( !HasPendingEvents() )
347 // iterate until the list becomes empty
348 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
351 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
352 wxPendingEvents
->Erase(node
);
354 // In ProcessPendingEvents(), new handlers might be add
355 // and we can safely leave the critical section here.
356 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
358 handler
->ProcessPendingEvents();
360 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
362 node
= wxPendingEvents
->GetFirst();
365 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
368 void wxAppConsole::WakeUpIdle()
371 m_mainLoop
->WakeUp();
374 bool wxAppConsole::ProcessIdle()
378 event
.SetEventObject(this);
380 return event
.MoreRequested();
383 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
385 // process the events normally by default
389 // ----------------------------------------------------------------------------
390 // exception handling
391 // ----------------------------------------------------------------------------
396 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
397 wxEventFunction func
,
398 wxEvent
& event
) const
400 // by default, simply call the handler
401 (handler
->*func
)(event
);
404 // ----------------------------------------------------------------------------
405 // exceptions support
406 // ----------------------------------------------------------------------------
410 bool wxAppConsole::OnExceptionInMainLoop()
414 // some compilers are too stupid to know that we never return after throw
415 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
420 #endif // wxUSE_EXCEPTIONS
423 #endif // wxUSE_EXCEPTIONS
425 // ----------------------------------------------------------------------------
427 // ----------------------------------------------------------------------------
429 #if wxUSE_CMDLINE_PARSER
431 #define OPTION_VERBOSE _T("verbose")
433 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
435 // the standard command line options
436 static const wxCmdLineEntryDesc cmdLineDesc
[] =
442 gettext_noop("show this help message"),
444 wxCMD_LINE_OPTION_HELP
452 gettext_noop("generate verbose log messages"),
469 parser
.SetDesc(cmdLineDesc
);
472 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
475 if ( parser
.Found(OPTION_VERBOSE
) )
477 wxLog::SetVerbose(true);
486 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
493 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
500 #endif // wxUSE_CMDLINE_PARSER
502 // ----------------------------------------------------------------------------
504 // ----------------------------------------------------------------------------
507 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
508 const char *componentName
)
510 #if 0 // can't use wxLogTrace, not up and running yet
511 printf("checking build options object '%s' (ptr %p) in '%s'\n",
512 optionsSignature
, optionsSignature
, componentName
);
515 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
517 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
518 wxString prog
= wxString::FromAscii(optionsSignature
);
519 wxString progName
= wxString::FromAscii(componentName
);
522 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
523 lib
.c_str(), progName
.c_str(), prog
.c_str());
525 wxLogFatalError(msg
.c_str());
527 // normally wxLogFatalError doesn't return
537 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
543 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
546 void wxAppConsole::OnAssert(const wxChar
*file
,
551 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
554 #endif // __WXDEBUG__
556 // ============================================================================
557 // other classes implementations
558 // ============================================================================
560 // ----------------------------------------------------------------------------
561 // wxConsoleAppTraitsBase
562 // ----------------------------------------------------------------------------
566 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
568 return new wxLogStderr
;
573 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
575 return new wxMessageOutputStderr
;
580 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
582 return (wxFontMapper
*)new wxFontMapperBase
;
585 #endif // wxUSE_FONTMAP
587 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
589 // console applications don't use renderers
594 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
596 return wxAppTraitsBase::ShowAssertDialog(msg
);
600 bool wxConsoleAppTraitsBase::HasStderr()
602 // console applications always have stderr, even under Mac/Windows
606 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
611 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
617 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
623 // ----------------------------------------------------------------------------
625 // ----------------------------------------------------------------------------
628 void wxAppTraitsBase::SetLocale()
630 setlocale(LC_ALL
, "");
631 wxUpdateLocaleIsUtf8();
637 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
639 wxString msg
= msgOriginal
;
641 #if wxUSE_STACKWALKER
642 #if !defined(__WXMSW__)
643 // on Unix stack frame generation may take some time, depending on the
644 // size of the executable mainly... warn the user that we are working
645 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
649 const wxString stackTrace
= GetAssertStackTrace();
650 if ( !stackTrace
.empty() )
651 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
652 #endif // wxUSE_STACKWALKER
654 return DoShowAssertDialog(msg
);
657 #if wxUSE_STACKWALKER
658 wxString
wxAppTraitsBase::GetAssertStackTrace()
662 class StackDump
: public wxStackWalker
667 const wxString
& GetStackTrace() const { return m_stackTrace
; }
670 virtual void OnStackFrame(const wxStackFrame
& frame
)
672 m_stackTrace
<< wxString::Format
675 wx_truncate_cast(int, frame
.GetLevel())
678 wxString name
= frame
.GetName();
681 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
685 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
688 if ( frame
.HasSourceLocation() )
690 m_stackTrace
<< _T('\t')
691 << frame
.GetFileName()
696 m_stackTrace
<< _T('\n');
700 wxString m_stackTrace
;
703 // don't show more than maxLines or we could get a dialog too tall to be
704 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
705 // characters it is still only 300 pixels...
706 static const int maxLines
= 20;
709 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
710 stackTrace
= dump
.GetStackTrace();
712 const int count
= stackTrace
.Freq(wxT('\n'));
713 for ( int i
= 0; i
< count
- maxLines
; i
++ )
714 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
718 #endif // wxUSE_STACKWALKER
721 #endif // __WXDEBUG__
723 // ============================================================================
724 // global functions implementation
725 // ============================================================================
735 // what else can we do?
744 wxTheApp
->WakeUpIdle();
746 //else: do nothing, what can we do?
752 bool wxAssertIsEqual(int x
, int y
)
757 // break into the debugger
760 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
762 #elif defined(__WXMAC__) && !defined(__DARWIN__)
768 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
770 #elif defined(__UNIX__)
777 // this function is called when an assert fails
778 void wxOnAssert(const wxChar
*szFile
,
781 const wxChar
*szCond
,
785 static bool s_bInAssert
= false;
789 // He-e-e-e-elp!! we're trapped in endless loop
799 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
800 const wxString strFunc
= wxString::FromAscii(szFunc
);
804 // by default, show the assert dialog box -- we can't customize this
806 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
810 // let the app process it as it wants
811 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
817 #endif // __WXDEBUG__
819 // ============================================================================
820 // private functions implementation
821 // ============================================================================
825 static void LINKAGEMODE
SetTraceMasks()
829 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
831 wxStringTokenizer
tkn(mask
, wxT(",;:"));
832 while ( tkn
.HasMoreTokens() )
833 wxLog::AddTraceMask(tkn
.GetNextToken());
838 bool DoShowAssertDialog(const wxString
& msg
)
840 // under MSW we can show the dialog even in the console mode
841 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
842 wxString
msgDlg(msg
);
844 // this message is intentionally not translated -- it is for
846 msgDlg
+= wxT("\nDo you want to stop the program?\n")
847 wxT("You can also choose [Cancel] to suppress ")
848 wxT("further warnings.");
850 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
851 MB_YESNOCANCEL
| MB_ICONSTOP
) )
861 //case IDNO: nothing to do
864 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
867 // TODO: ask the user to enter "Y" or "N" on the console?
869 #endif // __WXMSW__/!__WXMSW__
871 // continue with the asserts
875 // show the assert modal dialog
877 void ShowAssertDialog(const wxChar
*szFile
,
879 const wxChar
*szFunc
,
880 const wxChar
*szCond
,
884 // this variable can be set to true to suppress "assert failure" messages
885 static bool s_bNoAsserts
= false;
890 // make life easier for people using VC++ IDE by using this format: like
891 // this, clicking on the message will take us immediately to the place of
893 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
895 // add the function name, if any
896 if ( szFunc
&& *szFunc
)
897 msg
<< _T(" in ") << szFunc
<< _T("()");
899 // and the message itself
902 msg
<< _T(": ") << szMsg
;
904 else // no message given
910 // if we are not in the main thread, output the assert directly and trap
911 // since dialogs cannot be displayed
912 if ( !wxThread::IsMain() )
914 msg
+= wxT(" [in child thread]");
916 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
918 OutputDebugString(msg
);
921 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
924 // He-e-e-e-elp!! we're asserting in a child thread
928 #endif // wxUSE_THREADS
932 // send it to the normal log destination
933 wxLogDebug(_T("%s"), msg
.c_str());
937 // delegate showing assert dialog (if possible) to that class
938 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
940 else // no traits object
942 // fall back to the function of last resort
943 s_bNoAsserts
= DoShowAssertDialog(msg
);
948 #endif // __WXDEBUG__