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()
48 #include "wx/msw/debughlp.h" // includes windows.h for MessageBox()
52 #include "wx/fontmap.h"
53 #endif // wxUSE_FONTMAP
55 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
56 // For MacTypes.h for Debugger function
57 #include <CoreFoundation/CFBase.h>
60 #if defined(__WXMAC__)
61 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
62 // I don't know which headers are needed under earlier systems so
63 // include everything when in doubt
67 #include "wx/mac/private.h" // includes mac headers
72 #ifdef wxUSE_STACKWALKER
73 #include "wx/stackwalk.h"
75 #include "wx/msw/debughlp.h"
77 #endif // wxUSE_STACKWALKER
80 // ----------------------------------------------------------------------------
81 // private functions prototypes
82 // ----------------------------------------------------------------------------
85 // really just show the assert dialog
86 static bool DoShowAssertDialog(const wxString
& msg
);
88 // prepare for showing the assert dialog, use the given traits or
89 // DoShowAssertDialog() as last fallback to really show it
91 void ShowAssertDialog(const wxChar
*szFile
,
95 wxAppTraits
*traits
= NULL
);
97 // turn on the trace masks specified in the env variable WXTRACE
98 static void LINKAGEMODE
SetTraceMasks();
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
105 wxAppConsole
*wxAppConsole
::ms_appInstance
= NULL
;
107 wxAppInitializerFunction wxAppConsole
::ms_appInitFn
= NULL
;
109 // ============================================================================
110 // wxAppConsole implementation
111 // ============================================================================
113 // ----------------------------------------------------------------------------
115 // ----------------------------------------------------------------------------
117 wxAppConsole
::wxAppConsole()
121 ms_appInstance
= this;
126 // In unicode mode the SetTraceMasks call can cause an apptraits to be
127 // created, but since we are still in the constructor the wrong kind will
128 // be created for GUI apps. Destroy it so it can be created again later.
135 wxAppConsole
::~wxAppConsole()
140 // ----------------------------------------------------------------------------
141 // initilization/cleanup
142 // ----------------------------------------------------------------------------
144 bool wxAppConsole
::Initialize(int& argc
, wxChar
**argv
)
147 // If some code logged something before wxApp instance was created,
148 // wxLogStderr was set as the target. Undo it here by destroying the
149 // current target. It will be re-created next time logging is needed, but
150 // this time wxAppTraits will be used:
151 delete wxLog
::SetActiveTarget(NULL
);
154 // remember the command line arguments
159 if ( m_appName
.empty() && argv
)
161 // the application name is, by default, the name of its executable file
162 wxFileName
::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
169 void wxAppConsole
::CleanUp()
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
177 bool wxAppConsole
::OnInit()
179 #if wxUSE_CMDLINE_PARSER
180 wxCmdLineParser
parser(argc
, argv
);
182 OnInitCmdLine(parser
);
185 switch ( parser
.Parse(false /* don't show usage */) )
188 cont
= OnCmdLineHelp(parser
);
192 cont
= OnCmdLineParsed(parser
);
196 cont
= OnCmdLineError(parser
);
202 #endif // wxUSE_CMDLINE_PARSER
207 int wxAppConsole
::OnExit()
210 // delete the config object if any (don't use Get() here, but Set()
211 // because Get() could create a new config object)
212 delete wxConfigBase
::Set((wxConfigBase
*) NULL
);
213 #endif // wxUSE_CONFIG
215 // use Set(NULL) and not Get() to avoid creating a message output object on
216 // demand when we just want to delete it
217 delete wxMessageOutput
::Set(NULL
);
222 void wxAppConsole
::Exit()
227 // ----------------------------------------------------------------------------
229 // ----------------------------------------------------------------------------
231 wxAppTraits
*wxAppConsole
::CreateTraits()
233 return new wxConsoleAppTraits
;
236 wxAppTraits
*wxAppConsole
::GetTraits()
238 // FIXME-MT: protect this with a CS?
241 m_traits
= CreateTraits();
243 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
249 // we must implement CreateXXX() in wxApp itself for backwards compatibility
250 #if WXWIN_COMPATIBILITY_2_4
254 wxLog
*wxAppConsole
::CreateLogTarget()
256 wxAppTraits
*traits
= GetTraits();
257 return traits ? traits
->CreateLogTarget() : NULL
;
262 wxMessageOutput
*wxAppConsole
::CreateMessageOutput()
264 wxAppTraits
*traits
= GetTraits();
265 return traits ? traits
->CreateMessageOutput() : NULL
;
268 #endif // WXWIN_COMPATIBILITY_2_4
270 // ----------------------------------------------------------------------------
272 // ----------------------------------------------------------------------------
274 void wxAppConsole
::ProcessPendingEvents()
277 if ( !wxPendingEventsLocker
)
281 // ensure that we're the only thread to modify the pending events list
282 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
284 if ( !wxPendingEvents
)
286 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
290 // iterate until the list becomes empty
291 wxList
::compatibility_iterator node
= wxPendingEvents
->GetFirst();
294 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
295 wxPendingEvents
->Erase(node
);
297 // In ProcessPendingEvents(), new handlers might be add
298 // and we can safely leave the critical section here.
299 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
301 handler
->ProcessPendingEvents();
303 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
305 node
= wxPendingEvents
->GetFirst();
308 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
311 int wxAppConsole
::FilterEvent(wxEvent
& WXUNUSED(event
))
313 // process the events normally by default
317 // ----------------------------------------------------------------------------
318 // exception handling
319 // ----------------------------------------------------------------------------
324 wxAppConsole
::HandleEvent(wxEvtHandler
*handler
,
325 wxEventFunction func
,
326 wxEvent
& event
) const
328 // by default, simply call the handler
329 (handler
->*func
)(event
);
333 wxAppConsole
::OnExceptionInMainLoop()
337 // some compilers are too stupid to know that we never return after throw
338 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
343 #endif // wxUSE_EXCEPTIONS
345 // ----------------------------------------------------------------------------
347 // ----------------------------------------------------------------------------
349 #if wxUSE_CMDLINE_PARSER
351 #define OPTION_VERBOSE _T("verbose")
353 void wxAppConsole
::OnInitCmdLine(wxCmdLineParser
& parser
)
355 // the standard command line options
356 static const wxCmdLineEntryDesc cmdLineDesc
[] =
362 gettext_noop("show this help message"),
364 wxCMD_LINE_OPTION_HELP
372 gettext_noop("generate verbose log messages"),
389 parser
.SetDesc(cmdLineDesc
);
392 bool wxAppConsole
::OnCmdLineParsed(wxCmdLineParser
& parser
)
395 if ( parser
.Found(OPTION_VERBOSE
) )
397 wxLog
::SetVerbose(true);
406 bool wxAppConsole
::OnCmdLineHelp(wxCmdLineParser
& parser
)
413 bool wxAppConsole
::OnCmdLineError(wxCmdLineParser
& parser
)
420 #endif // wxUSE_CMDLINE_PARSER
422 // ----------------------------------------------------------------------------
424 // ----------------------------------------------------------------------------
427 bool wxAppConsole
::CheckBuildOptions(const char *optionsSignature
,
428 const char *componentName
)
430 #if 0 // can't use wxLogTrace, not up and running yet
431 printf("checking build options object '%s' (ptr %p) in '%s'\n",
432 optionsSignature
, optionsSignature
, componentName
);
435 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
437 wxString lib
= wxString
::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
438 wxString prog
= wxString
::FromAscii(optionsSignature
);
439 wxString progName
= wxString
::FromAscii(componentName
);
442 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
443 lib
.c_str(), progName
.c_str(), prog
.c_str());
445 wxLogFatalError(msg
.c_str());
447 // normally wxLogFatalError doesn't return
457 void wxAppConsole
::OnAssert(const wxChar
*file
,
462 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
465 #endif // __WXDEBUG__
467 #if WXWIN_COMPATIBILITY_2_4
469 bool wxAppConsole
::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
471 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
476 // ============================================================================
477 // other classes implementations
478 // ============================================================================
480 // ----------------------------------------------------------------------------
481 // wxConsoleAppTraitsBase
482 // ----------------------------------------------------------------------------
486 wxLog
*wxConsoleAppTraitsBase
::CreateLogTarget()
488 return new wxLogStderr
;
493 wxMessageOutput
*wxConsoleAppTraitsBase
::CreateMessageOutput()
495 return new wxMessageOutputStderr
;
500 wxFontMapper
*wxConsoleAppTraitsBase
::CreateFontMapper()
502 return (wxFontMapper
*)new wxFontMapperBase
;
505 #endif // wxUSE_FONTMAP
507 wxRendererNative
*wxConsoleAppTraitsBase
::CreateRenderer()
509 // console applications don't use renderers
514 bool wxConsoleAppTraitsBase
::ShowAssertDialog(const wxString
& msg
)
516 return wxAppTraitsBase
::ShowAssertDialog(msg
);
520 bool wxConsoleAppTraitsBase
::HasStderr()
522 // console applications always have stderr, even under Mac/Windows
526 void wxConsoleAppTraitsBase
::ScheduleForDestroy(wxObject
*object
)
531 void wxConsoleAppTraitsBase
::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
537 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase
::GetSocketGUIFunctionsTable()
543 // ----------------------------------------------------------------------------
545 // ----------------------------------------------------------------------------
549 bool wxAppTraitsBase
::ShowAssertDialog(const wxString
& msg
)
551 return DoShowAssertDialog(msg
);
554 #endif // __WXDEBUG__
556 // ============================================================================
557 // global functions implementation
558 // ============================================================================
568 // what else can we do?
577 wxTheApp
->WakeUpIdle();
579 //else: do nothing, what can we do?
585 bool wxAssertIsEqual(int x
, int y
)
590 // break into the debugger
593 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
595 #elif defined(__WXMAC__) && !defined(__DARWIN__)
601 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
603 #elif defined(__UNIX__)
610 void wxAssert(int cond
,
611 const wxChar
*szFile
,
613 const wxChar
*szCond
,
617 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
620 // this function is called when an assert fails
621 void wxOnAssert(const wxChar
*szFile
,
623 const wxChar
*szCond
,
627 static bool s_bInAssert
= false;
631 // He-e-e-e-elp!! we're trapped in endless loop
643 // by default, show the assert dialog box -- we can't customize this
645 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
649 // let the app process it as it wants
650 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
656 #endif // __WXDEBUG__
658 // ============================================================================
659 // private functions implementation
660 // ============================================================================
664 static void LINKAGEMODE
SetTraceMasks()
668 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
670 wxStringTokenizer
tkn(mask
, wxT(",;:"));
671 while ( tkn
.HasMoreTokens() )
672 wxLog
::AddTraceMask(tkn
.GetNextToken());
677 bool DoShowAssertDialog(const wxString
& msg
)
679 // under MSW we can show the dialog even in the console mode
680 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
681 wxString
msgDlg(msg
);
683 // this message is intentionally not translated -- it is for
685 msgDlg
+= wxT("\nDo you want to stop the program?\n")
686 wxT("You can also choose [Cancel] to suppress ")
687 wxT("further warnings.");
689 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
690 MB_YESNOCANCEL
| MB_ICONSTOP
) )
700 //case IDNO: nothing to do
703 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
706 // TODO: ask the user to enter "Y" or "N" on the console?
708 #endif // __WXMSW__/!__WXMSW__
710 // continue with the asserts
714 #if wxUSE_STACKWALKER
715 static wxString
GetAssertStackTrace()
720 // check that we can get the stack trace before trying to do it
721 if ( !wxDbgHelpDLL
::Init() )
725 class StackDump
: public wxStackWalker
730 const wxString
& GetStackTrace() const { return m_stackTrace
; }
733 virtual void OnStackFrame(const wxStackFrame
& frame
)
735 m_stackTrace
<< wxString
::Format(_T("[%02d] "), frame
.GetLevel());
737 wxString name
= frame
.GetName();
740 m_stackTrace
<< wxString
::Format(_T("%-40s"), name
.c_str());
744 m_stackTrace
<< wxString
::Format
747 (unsigned long)frame
.GetAddress()
751 if ( frame
.HasSourceLocation() )
753 m_stackTrace
<< _T('\t')
754 << frame
.GetFileName()
759 m_stackTrace
<< _T('\n');
763 wxString m_stackTrace
;
767 dump
.Walk(5); // don't show OnAssert() call itself
768 stackTrace
= dump
.GetStackTrace();
770 // don't show more than maxLines or we could get a dialog too tall to be
771 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
772 // characters it is still only 300 pixels...
773 static const int maxLines
= 20;
774 const int count
= stackTrace
.Freq(wxT('\n'));
775 for ( int i
= 0; i
< count
- maxLines
; i
++ )
776 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
780 #endif // wxUSE_STACKWALKER
782 // show the assert modal dialog
784 void ShowAssertDialog(const wxChar
*szFile
,
786 const wxChar
*szCond
,
790 // this variable can be set to true to suppress "assert failure" messages
791 static bool s_bNoAsserts
= false;
796 // make life easier for people using VC++ IDE by using this format: like
797 // this, clicking on the message will take us immediately to the place of
799 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
803 msg
<< _T(": ") << szMsg
;
805 else // no message given
810 #if wxUSE_STACKWALKER
811 const wxString stackTrace
= GetAssertStackTrace();
812 if ( !stackTrace
.empty() )
814 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
816 #endif // wxUSE_STACKWALKER
819 // if we are not in the main thread, output the assert directly and trap
820 // since dialogs cannot be displayed
821 if ( !wxThread
::IsMain() )
823 msg
+= wxT(" [in child thread]");
825 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
827 OutputDebugString(msg
);
830 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
833 // He-e-e-e-elp!! we're asserting in a child thread
837 #endif // wxUSE_THREADS
841 // send it to the normal log destination
842 wxLogDebug(_T("%s"), msg
.c_str());
846 // delegate showing assert dialog (if possible) to that class
847 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
849 else // no traits object
851 // fall back to the function of last resort
852 s_bNoAsserts
= DoShowAssertDialog(msg
);
857 #endif // __WXDEBUG__