1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: common/base/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"
35 #include "wx/apptrait.h"
36 #include "wx/cmdline.h"
37 #include "wx/confbase.h"
38 #include "wx/filename.h"
39 #include "wx/msgout.h"
40 #include "wx/tokenzr.h"
42 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
43 #include <signal.h> // for SIGTRAP used by wxTrap()
46 #if defined(__WXMSW__)
47 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
51 #include "wx/fontmap.h"
52 #endif // wxUSE_FONTMAP
54 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
55 // For MacTypes.h for Debugger function
56 #include <CoreFoundation/CFBase.h>
59 #if defined(__WXMAC__)
60 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
61 // I don't know which headers are needed under earlier systems so
62 // include everything when in doubt
66 #include "wx/mac/private.h" // includes mac headers
72 #include "wx/stackwalk.h"
74 #include "wx/msw/debughlp.h"
76 #endif // wxUSE_STACKWALKER
79 // wxABI_VERSION can be defined when compiling applications but it should be
80 // left undefined when compiling the library itself, it is then set to its
81 // default value in version.h
82 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
83 #error "wxABI_VERSION should not be defined when compiling the library"
86 // ----------------------------------------------------------------------------
87 // private functions prototypes
88 // ----------------------------------------------------------------------------
91 // really just show the assert dialog
92 static bool DoShowAssertDialog(const wxString
& msg
);
94 // prepare for showing the assert dialog, use the given traits or
95 // DoShowAssertDialog() as last fallback to really show it
97 void ShowAssertDialog(const wxChar
*szFile
,
101 wxAppTraits
*traits
= NULL
);
103 // turn on the trace masks specified in the env variable WXTRACE
104 static void LINKAGEMODE
SetTraceMasks();
105 #endif // __WXDEBUG__
107 // ----------------------------------------------------------------------------
109 // ----------------------------------------------------------------------------
111 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
113 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
115 // ============================================================================
116 // wxAppConsole implementation
117 // ============================================================================
119 // ----------------------------------------------------------------------------
121 // ----------------------------------------------------------------------------
123 wxAppConsole::wxAppConsole()
127 ms_appInstance
= this;
132 // In unicode mode the SetTraceMasks call can cause an apptraits to be
133 // created, but since we are still in the constructor the wrong kind will
134 // be created for GUI apps. Destroy it so it can be created again later.
141 wxAppConsole::~wxAppConsole()
146 // ----------------------------------------------------------------------------
147 // initilization/cleanup
148 // ----------------------------------------------------------------------------
150 bool wxAppConsole::Initialize(int& argc
, wxChar
**argv
)
152 // remember the command line arguments
157 if ( m_appName
.empty() && argv
)
159 // the application name is, by default, the name of its executable file
160 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
167 void wxAppConsole::CleanUp()
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
175 bool wxAppConsole::OnInit()
177 #if wxUSE_CMDLINE_PARSER
178 wxCmdLineParser
parser(argc
, argv
);
180 OnInitCmdLine(parser
);
183 switch ( parser
.Parse(false /* don't show usage */) )
186 cont
= OnCmdLineHelp(parser
);
190 cont
= OnCmdLineParsed(parser
);
194 cont
= OnCmdLineError(parser
);
200 #endif // wxUSE_CMDLINE_PARSER
205 int wxAppConsole::OnExit()
208 // delete the config object if any (don't use Get() here, but Set()
209 // because Get() could create a new config object)
210 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
211 #endif // wxUSE_CONFIG
213 // use Set(NULL) and not Get() to avoid creating a message output object on
214 // demand when we just want to delete it
215 delete wxMessageOutput::Set(NULL
);
220 void wxAppConsole::Exit()
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
229 wxAppTraits
*wxAppConsole::CreateTraits()
231 return new wxConsoleAppTraits
;
234 wxAppTraits
*wxAppConsole::GetTraits()
236 // FIXME-MT: protect this with a CS?
239 m_traits
= CreateTraits();
241 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
247 // we must implement CreateXXX() in wxApp itself for backwards compatibility
248 #if WXWIN_COMPATIBILITY_2_4
252 wxLog
*wxAppConsole::CreateLogTarget()
254 wxAppTraits
*traits
= GetTraits();
255 return traits
? traits
->CreateLogTarget() : NULL
;
260 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
262 wxAppTraits
*traits
= GetTraits();
263 return traits
? traits
->CreateMessageOutput() : NULL
;
266 #endif // WXWIN_COMPATIBILITY_2_4
268 // ----------------------------------------------------------------------------
270 // ----------------------------------------------------------------------------
272 void wxAppConsole::ProcessPendingEvents()
275 if ( !wxPendingEventsLocker
)
279 // ensure that we're the only thread to modify the pending events list
280 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
282 if ( !wxPendingEvents
)
284 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
288 // iterate until the list becomes empty
289 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
292 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
293 wxPendingEvents
->Erase(node
);
295 // In ProcessPendingEvents(), new handlers might be add
296 // and we can safely leave the critical section here.
297 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
299 handler
->ProcessPendingEvents();
301 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
303 node
= wxPendingEvents
->GetFirst();
306 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
309 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
311 // process the events normally by default
315 // ----------------------------------------------------------------------------
316 // exception handling
317 // ----------------------------------------------------------------------------
322 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
323 wxEventFunction func
,
324 wxEvent
& event
) const
326 // by default, simply call the handler
327 (handler
->*func
)(event
);
331 wxAppConsole::OnExceptionInMainLoop()
335 // some compilers are too stupid to know that we never return after throw
336 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
341 #endif // wxUSE_EXCEPTIONS
343 // ----------------------------------------------------------------------------
345 // ----------------------------------------------------------------------------
347 #if wxUSE_CMDLINE_PARSER
349 #define OPTION_VERBOSE _T("verbose")
351 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
353 // the standard command line options
354 static const wxCmdLineEntryDesc cmdLineDesc
[] =
360 gettext_noop("show this help message"),
362 wxCMD_LINE_OPTION_HELP
370 gettext_noop("generate verbose log messages"),
387 parser
.SetDesc(cmdLineDesc
);
390 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
393 if ( parser
.Found(OPTION_VERBOSE
) )
395 wxLog::SetVerbose(true);
404 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
411 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
418 #endif // wxUSE_CMDLINE_PARSER
420 // ----------------------------------------------------------------------------
422 // ----------------------------------------------------------------------------
425 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
426 const char *componentName
)
428 #if 0 // can't use wxLogTrace, not up and running yet
429 printf("checking build options object '%s' (ptr %p) in '%s'\n",
430 optionsSignature
, optionsSignature
, componentName
);
433 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
435 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
436 wxString prog
= wxString::FromAscii(optionsSignature
);
437 wxString progName
= wxString::FromAscii(componentName
);
440 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
441 lib
.c_str(), progName
.c_str(), prog
.c_str());
443 wxLogFatalError(msg
.c_str());
445 // normally wxLogFatalError doesn't return
455 void wxAppConsole::OnAssert(const wxChar
*file
,
460 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
463 #endif // __WXDEBUG__
465 #if WXWIN_COMPATIBILITY_2_4
467 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
469 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
474 // ============================================================================
475 // other classes implementations
476 // ============================================================================
478 // ----------------------------------------------------------------------------
479 // wxConsoleAppTraitsBase
480 // ----------------------------------------------------------------------------
484 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
486 return new wxLogStderr
;
491 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
493 return new wxMessageOutputStderr
;
498 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
500 return (wxFontMapper
*)new wxFontMapperBase
;
503 #endif // wxUSE_FONTMAP
505 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
507 // console applications don't use renderers
512 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
514 return wxAppTraitsBase::ShowAssertDialog(msg
);
518 bool wxConsoleAppTraitsBase::HasStderr()
520 // console applications always have stderr, even under Mac/Windows
524 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
529 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
535 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
541 // ----------------------------------------------------------------------------
543 // ----------------------------------------------------------------------------
547 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
549 return DoShowAssertDialog(msg
);
552 #endif // __WXDEBUG__
554 // ============================================================================
555 // global functions implementation
556 // ============================================================================
566 // what else can we do?
575 wxTheApp
->WakeUpIdle();
577 //else: do nothing, what can we do?
583 bool wxAssertIsEqual(int x
, int y
)
588 // break into the debugger
591 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
593 #elif defined(__WXMAC__) && !defined(__DARWIN__)
599 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
601 #elif defined(__UNIX__)
608 void wxAssert(int cond
,
609 const wxChar
*szFile
,
611 const wxChar
*szCond
,
615 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
618 // this function is called when an assert fails
619 void wxOnAssert(const wxChar
*szFile
,
621 const wxChar
*szCond
,
625 static bool s_bInAssert
= false;
629 // He-e-e-e-elp!! we're trapped in endless loop
641 // by default, show the assert dialog box -- we can't customize this
643 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
647 // let the app process it as it wants
648 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
654 #endif // __WXDEBUG__
656 // ============================================================================
657 // private functions implementation
658 // ============================================================================
662 static void LINKAGEMODE
SetTraceMasks()
666 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
668 wxStringTokenizer
tkn(mask
, wxT(",;:"));
669 while ( tkn
.HasMoreTokens() )
670 wxLog::AddTraceMask(tkn
.GetNextToken());
675 bool DoShowAssertDialog(const wxString
& msg
)
677 // under MSW we can show the dialog even in the console mode
678 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
679 wxString
msgDlg(msg
);
681 // this message is intentionally not translated -- it is for
683 msgDlg
+= wxT("\nDo you want to stop the program?\n")
684 wxT("You can also choose [Cancel] to suppress ")
685 wxT("further warnings.");
687 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
688 MB_YESNOCANCEL
| MB_ICONSTOP
) )
698 //case IDNO: nothing to do
701 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
704 // TODO: ask the user to enter "Y" or "N" on the console?
706 #endif // __WXMSW__/!__WXMSW__
708 // continue with the asserts
712 #if wxUSE_STACKWALKER
713 static wxString
GetAssertStackTrace()
718 // check that we can get the stack trace before trying to do it
719 if ( !wxDbgHelpDLL::Init() )
723 class StackDump
: public wxStackWalker
728 const wxString
& GetStackTrace() const { return m_stackTrace
; }
731 virtual void OnStackFrame(const wxStackFrame
& frame
)
733 m_stackTrace
<< wxString::Format(_T("[%02d] "), frame
.GetLevel());
735 wxString name
= frame
.GetName();
738 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
742 m_stackTrace
<< wxString::Format
745 (unsigned long)frame
.GetAddress()
749 if ( frame
.HasSourceLocation() )
751 m_stackTrace
<< _T('\t')
752 << frame
.GetFileName()
757 m_stackTrace
<< _T('\n');
761 wxString m_stackTrace
;
765 dump
.Walk(5); // don't show OnAssert() call itself
766 stackTrace
= dump
.GetStackTrace();
768 // don't show more than maxLines or we could get a dialog too tall to be
769 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
770 // characters it is still only 300 pixels...
771 static const int maxLines
= 20;
772 const int count
= stackTrace
.Freq(wxT('\n'));
773 for ( int i
= 0; i
< count
- maxLines
; i
++ )
774 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
778 #endif // wxUSE_STACKWALKER
780 // show the assert modal dialog
782 void ShowAssertDialog(const wxChar
*szFile
,
784 const wxChar
*szCond
,
788 // this variable can be set to true to suppress "assert failure" messages
789 static bool s_bNoAsserts
= false;
794 // make life easier for people using VC++ IDE by using this format: like
795 // this, clicking on the message will take us immediately to the place of
797 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
801 msg
<< _T(": ") << szMsg
;
803 else // no message given
808 #if wxUSE_STACKWALKER
809 const wxString stackTrace
= GetAssertStackTrace();
810 if ( !stackTrace
.empty() )
812 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
814 #endif // wxUSE_STACKWALKER
817 // if we are not in the main thread, output the assert directly and trap
818 // since dialogs cannot be displayed
819 if ( !wxThread::IsMain() )
821 msg
+= wxT(" [in child thread]");
823 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
825 OutputDebugString(msg
);
828 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
831 // He-e-e-e-elp!! we're asserting in a child thread
835 #endif // wxUSE_THREADS
839 // send it to the normal log destination
840 wxLogDebug(_T("%s"), msg
.c_str());
844 // delegate showing assert dialog (if possible) to that class
845 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
847 else // no traits object
849 // fall back to the function of last resort
850 s_bNoAsserts
= DoShowAssertDialog(msg
);
855 #endif // __WXDEBUG__