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
71 #ifdef wxUSE_STACKWALKER
72 #include "wx/stackwalk.h"
73 #endif // wxUSE_STACKWALKER
76 // ----------------------------------------------------------------------------
77 // private functions prototypes
78 // ----------------------------------------------------------------------------
81 // really just show the assert dialog
82 static bool DoShowAssertDialog(const wxString
& msg
);
84 // prepare for showing the assert dialog, use the given traits or
85 // DoShowAssertDialog() as last fallback to really show it
87 void ShowAssertDialog(const wxChar
*szFile
,
91 wxAppTraits
*traits
= NULL
);
93 // turn on the trace masks specified in the env variable WXTRACE
94 static void LINKAGEMODE
SetTraceMasks();
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
103 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
105 // ============================================================================
106 // wxAppConsole implementation
107 // ============================================================================
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 wxAppConsole::wxAppConsole()
117 ms_appInstance
= this;
122 // In unicode mode the SetTraceMasks call can cause an apptraits to be
123 // created, but since we are still in the constructor the wrong kind will
124 // be created for GUI apps. Destroy it so it can be created again later.
131 wxAppConsole::~wxAppConsole()
136 // ----------------------------------------------------------------------------
137 // initilization/cleanup
138 // ----------------------------------------------------------------------------
140 bool wxAppConsole::Initialize(int& argc
, wxChar
**argv
)
143 // If some code logged something before wxApp instance was created,
144 // wxLogStderr was set as the target. Undo it here by destroying the
145 // current target. It will be re-created next time logging is needed, but
146 // this time wxAppTraits will be used:
147 delete wxLog::SetActiveTarget(NULL
);
150 // remember the command line arguments
155 if ( m_appName
.empty() && argv
)
157 // the application name is, by default, the name of its executable file
158 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
165 void wxAppConsole::CleanUp()
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 bool wxAppConsole::OnInit()
175 #if wxUSE_CMDLINE_PARSER
176 wxCmdLineParser
parser(argc
, argv
);
178 OnInitCmdLine(parser
);
181 switch ( parser
.Parse(false /* don't show usage */) )
184 cont
= OnCmdLineHelp(parser
);
188 cont
= OnCmdLineParsed(parser
);
192 cont
= OnCmdLineError(parser
);
198 #endif // wxUSE_CMDLINE_PARSER
203 int wxAppConsole::OnExit()
206 // delete the config object if any (don't use Get() here, but Set()
207 // because Get() could create a new config object)
208 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
209 #endif // wxUSE_CONFIG
211 // use Set(NULL) and not Get() to avoid creating a message output object on
212 // demand when we just want to delete it
213 delete wxMessageOutput::Set(NULL
);
218 void wxAppConsole::Exit()
223 // ----------------------------------------------------------------------------
225 // ----------------------------------------------------------------------------
227 wxAppTraits
*wxAppConsole::CreateTraits()
229 return new wxConsoleAppTraits
;
232 wxAppTraits
*wxAppConsole::GetTraits()
234 // FIXME-MT: protect this with a CS?
237 m_traits
= CreateTraits();
239 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
245 // we must implement CreateXXX() in wxApp itself for backwards compatibility
246 #if WXWIN_COMPATIBILITY_2_4
250 wxLog
*wxAppConsole::CreateLogTarget()
252 wxAppTraits
*traits
= GetTraits();
253 return traits
? traits
->CreateLogTarget() : NULL
;
258 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
260 wxAppTraits
*traits
= GetTraits();
261 return traits
? traits
->CreateMessageOutput() : NULL
;
264 #endif // WXWIN_COMPATIBILITY_2_4
266 // ----------------------------------------------------------------------------
268 // ----------------------------------------------------------------------------
270 void wxAppConsole::ProcessPendingEvents()
273 if ( !wxPendingEventsLocker
)
277 // ensure that we're the only thread to modify the pending events list
278 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
280 if ( !wxPendingEvents
)
282 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
286 // iterate until the list becomes empty
287 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
290 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
291 wxPendingEvents
->Erase(node
);
293 // In ProcessPendingEvents(), new handlers might be add
294 // and we can safely leave the critical section here.
295 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
297 handler
->ProcessPendingEvents();
299 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
301 node
= wxPendingEvents
->GetFirst();
304 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
307 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
309 // process the events normally by default
313 // ----------------------------------------------------------------------------
314 // exception handling
315 // ----------------------------------------------------------------------------
320 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
321 wxEventFunction func
,
322 wxEvent
& event
) const
324 // by default, simply call the handler
325 (handler
->*func
)(event
);
329 wxAppConsole::OnExceptionInMainLoop()
333 // some compilers are too stupid to know that we never return after throw
334 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
339 #endif // wxUSE_EXCEPTIONS
341 // ----------------------------------------------------------------------------
343 // ----------------------------------------------------------------------------
345 #if wxUSE_CMDLINE_PARSER
347 #define OPTION_VERBOSE _T("verbose")
349 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
351 // the standard command line options
352 static const wxCmdLineEntryDesc cmdLineDesc
[] =
358 gettext_noop("show this help message"),
360 wxCMD_LINE_OPTION_HELP
368 gettext_noop("generate verbose log messages"),
385 parser
.SetDesc(cmdLineDesc
);
388 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
391 if ( parser
.Found(OPTION_VERBOSE
) )
393 wxLog::SetVerbose(true);
402 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
409 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
416 #endif // wxUSE_CMDLINE_PARSER
418 // ----------------------------------------------------------------------------
420 // ----------------------------------------------------------------------------
423 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
424 const char *componentName
)
426 #if 0 // can't use wxLogTrace, not up and running yet
427 printf("checking build options object '%s' (ptr %p) in '%s'\n",
428 optionsSignature
, optionsSignature
, componentName
);
431 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
433 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
434 wxString prog
= wxString::FromAscii(optionsSignature
);
435 wxString progName
= wxString::FromAscii(componentName
);
438 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
439 lib
.c_str(), progName
.c_str(), prog
.c_str());
441 wxLogFatalError(msg
.c_str());
443 // normally wxLogFatalError doesn't return
453 void wxAppConsole::OnAssert(const wxChar
*file
,
458 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
461 #endif // __WXDEBUG__
463 #if WXWIN_COMPATIBILITY_2_4
465 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
467 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
472 // ============================================================================
473 // other classes implementations
474 // ============================================================================
476 // ----------------------------------------------------------------------------
477 // wxConsoleAppTraitsBase
478 // ----------------------------------------------------------------------------
482 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
484 return new wxLogStderr
;
489 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
491 return new wxMessageOutputStderr
;
496 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
498 return (wxFontMapper
*)new wxFontMapperBase
;
501 #endif // wxUSE_FONTMAP
503 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
505 // console applications don't use renderers
510 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
512 return wxAppTraitsBase::ShowAssertDialog(msg
);
516 bool wxConsoleAppTraitsBase::HasStderr()
518 // console applications always have stderr, even under Mac/Windows
522 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
527 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
533 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
539 // ----------------------------------------------------------------------------
541 // ----------------------------------------------------------------------------
545 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
547 return DoShowAssertDialog(msg
);
550 #endif // __WXDEBUG__
552 // ============================================================================
553 // global functions implementation
554 // ============================================================================
564 // what else can we do?
573 wxTheApp
->WakeUpIdle();
575 //else: do nothing, what can we do?
581 bool wxAssertIsEqual(int x
, int y
)
586 // break into the debugger
589 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
591 #elif defined(__WXMAC__) && !defined(__DARWIN__)
597 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
599 #elif defined(__UNIX__)
606 void wxAssert(int cond
,
607 const wxChar
*szFile
,
609 const wxChar
*szCond
,
613 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
616 // this function is called when an assert fails
617 void wxOnAssert(const wxChar
*szFile
,
619 const wxChar
*szCond
,
623 static bool s_bInAssert
= false;
627 // He-e-e-e-elp!! we're trapped in endless loop
639 // by default, show the assert dialog box -- we can't customize this
641 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
645 // let the app process it as it wants
646 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
652 #endif // __WXDEBUG__
654 // ============================================================================
655 // private functions implementation
656 // ============================================================================
660 static void LINKAGEMODE
SetTraceMasks()
664 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
666 wxStringTokenizer
tkn(mask
, wxT(",;:"));
667 while ( tkn
.HasMoreTokens() )
668 wxLog::AddTraceMask(tkn
.GetNextToken());
673 bool DoShowAssertDialog(const wxString
& msg
)
675 // under MSW we can show the dialog even in the console mode
676 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
677 wxString
msgDlg(msg
);
679 // this message is intentionally not translated -- it is for
681 msgDlg
+= wxT("\nDo you want to stop the program?\n")
682 wxT("You can also choose [Cancel] to suppress ")
683 wxT("further warnings.");
685 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
686 MB_YESNOCANCEL
| MB_ICONSTOP
) )
696 //case IDNO: nothing to do
699 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
702 // TODO: ask the user to enter "Y" or "N" on the console?
704 #endif // __WXMSW__/!__WXMSW__
706 // continue with the asserts
710 // show the assert modal dialog
712 void ShowAssertDialog(const wxChar
*szFile
,
714 const wxChar
*szCond
,
718 // this variable can be set to true to suppress "assert failure" messages
719 static bool s_bNoAsserts
= false;
724 // make life easier for people using VC++ IDE by using this format: like
725 // this, clicking on the message will take us immediately to the place of
727 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
731 msg
<< _T(": ") << szMsg
;
733 else // no message given
738 #if wxUSE_STACKWALKER
739 class StackDump
: public wxStackWalker
744 const wxString
& GetStackTrace() const { return m_stackTrace
; }
747 virtual void OnStackFrame(const wxStackFrame
& frame
)
749 m_stackTrace
<< wxString::Format(_T("[%02d] "), frame
.GetLevel());
751 wxString name
= frame
.GetName();
754 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
758 m_stackTrace
<< wxString::Format
761 (unsigned long)frame
.GetAddress()
765 if ( frame
.HasSourceLocation() )
767 m_stackTrace
<< _T('\t')
768 << frame
.GetFileName()
773 m_stackTrace
<< _T('\n');
777 wxString m_stackTrace
;
781 dump
.Walk(5); // don't show OnAssert() call itself
782 wxString stackTrace
= dump
.GetStackTrace();
784 // don't show more than maxLines or we could get a dialog too tall to be
785 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
786 // characters it is still only 300 pixels...
787 const int maxLines
= 20;
788 int count
= stackTrace
.Freq(wxT('\n'));
789 if (count
> maxLines
)
792 for (i
= 0; i
< count
- maxLines
; i
++)
793 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
795 if ( !stackTrace
.empty() )
797 msg
<< _T("\n\nCall stack:\n")
800 #endif // wxUSE_STACKWALKER
803 // if we are not in the main thread, output the assert directly and trap
804 // since dialogs cannot be displayed
805 if ( !wxThread::IsMain() )
807 msg
+= wxT(" [in child thread]");
809 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
811 OutputDebugString(msg
);
814 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
817 // He-e-e-e-elp!! we're asserting in a child thread
821 #endif // wxUSE_THREADS
825 // send it to the normal log destination
826 wxLogDebug(_T("%s"), msg
.c_str());
830 // delegate showing assert dialog (if possible) to that class
831 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
833 else // no traits object
835 // fall back to the function of last resort
836 s_bNoAsserts
= DoShowAssertDialog(msg
);
841 #endif // __WXDEBUG__