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()
272 // ensure that we're the only thread to modify the pending events list
273 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
275 if ( !wxPendingEvents
)
277 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
281 // iterate until the list becomes empty
282 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
285 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
286 wxPendingEvents
->Erase(node
);
288 // In ProcessPendingEvents(), new handlers might be add
289 // and we can safely leave the critical section here.
290 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
291 handler
->ProcessPendingEvents();
292 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
294 node
= wxPendingEvents
->GetFirst();
297 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
300 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
302 // process the events normally by default
306 // ----------------------------------------------------------------------------
307 // exception handling
308 // ----------------------------------------------------------------------------
313 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
314 wxEventFunction func
,
315 wxEvent
& event
) const
317 // by default, simply call the handler
318 (handler
->*func
)(event
);
322 wxAppConsole::OnExceptionInMainLoop()
326 // some compilers are too stupid to know that we never return after throw
327 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
332 #endif // wxUSE_EXCEPTIONS
334 // ----------------------------------------------------------------------------
336 // ----------------------------------------------------------------------------
338 #if wxUSE_CMDLINE_PARSER
340 #define OPTION_VERBOSE _T("verbose")
342 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
344 // the standard command line options
345 static const wxCmdLineEntryDesc cmdLineDesc
[] =
351 gettext_noop("show this help message"),
353 wxCMD_LINE_OPTION_HELP
361 gettext_noop("generate verbose log messages"),
378 parser
.SetDesc(cmdLineDesc
);
381 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
384 if ( parser
.Found(OPTION_VERBOSE
) )
386 wxLog::SetVerbose(true);
395 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
402 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
409 #endif // wxUSE_CMDLINE_PARSER
411 // ----------------------------------------------------------------------------
413 // ----------------------------------------------------------------------------
416 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
417 const char *componentName
)
419 #if 0 // can't use wxLogTrace, not up and running yet
420 printf("checking build options object '%s' (ptr %p) in '%s'\n",
421 optionsSignature
, optionsSignature
, componentName
);
424 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
426 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
427 wxString prog
= wxString::FromAscii(optionsSignature
);
428 wxString progName
= wxString::FromAscii(componentName
);
431 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
432 lib
.c_str(), progName
.c_str(), prog
.c_str());
434 wxLogFatalError(msg
.c_str());
436 // normally wxLogFatalError doesn't return
446 void wxAppConsole::OnAssert(const wxChar
*file
,
451 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
454 #endif // __WXDEBUG__
456 #if WXWIN_COMPATIBILITY_2_4
458 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
460 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
465 // ============================================================================
466 // other classes implementations
467 // ============================================================================
469 // ----------------------------------------------------------------------------
470 // wxConsoleAppTraitsBase
471 // ----------------------------------------------------------------------------
475 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
477 return new wxLogStderr
;
482 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
484 return new wxMessageOutputStderr
;
489 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
491 return (wxFontMapper
*)new wxFontMapperBase
;
494 #endif // wxUSE_FONTMAP
496 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
498 // console applications don't use renderers
503 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
505 return wxAppTraitsBase::ShowAssertDialog(msg
);
509 bool wxConsoleAppTraitsBase::HasStderr()
511 // console applications always have stderr, even under Mac/Windows
515 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
520 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
526 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
532 // ----------------------------------------------------------------------------
534 // ----------------------------------------------------------------------------
538 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
540 return DoShowAssertDialog(msg
);
543 #endif // __WXDEBUG__
545 // ============================================================================
546 // global functions implementation
547 // ============================================================================
557 // what else can we do?
566 wxTheApp
->WakeUpIdle();
568 //else: do nothing, what can we do?
574 bool wxAssertIsEqual(int x
, int y
)
579 // break into the debugger
582 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
584 #elif defined(__WXMAC__) && !defined(__DARWIN__)
590 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
592 #elif defined(__UNIX__)
599 void wxAssert(int cond
,
600 const wxChar
*szFile
,
602 const wxChar
*szCond
,
606 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
609 // this function is called when an assert fails
610 void wxOnAssert(const wxChar
*szFile
,
612 const wxChar
*szCond
,
616 static bool s_bInAssert
= false;
620 // He-e-e-e-elp!! we're trapped in endless loop
632 // by default, show the assert dialog box -- we can't customize this
634 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
638 // let the app process it as it wants
639 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
645 #endif // __WXDEBUG__
647 // ============================================================================
648 // private functions implementation
649 // ============================================================================
653 static void LINKAGEMODE
SetTraceMasks()
657 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
659 wxStringTokenizer
tkn(mask
, wxT(",;:"));
660 while ( tkn
.HasMoreTokens() )
661 wxLog::AddTraceMask(tkn
.GetNextToken());
666 bool DoShowAssertDialog(const wxString
& msg
)
668 // under MSW we can show the dialog even in the console mode
669 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
670 wxString
msgDlg(msg
);
672 // this message is intentionally not translated -- it is for
674 msgDlg
+= wxT("\nDo you want to stop the program?\n")
675 wxT("You can also choose [Cancel] to suppress ")
676 wxT("further warnings.");
678 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
679 MB_YESNOCANCEL
| MB_ICONSTOP
) )
689 //case IDNO: nothing to do
692 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
695 // TODO: ask the user to enter "Y" or "N" on the console?
697 #endif // __WXMSW__/!__WXMSW__
699 // continue with the asserts
703 // show the assert modal dialog
705 void ShowAssertDialog(const wxChar
*szFile
,
707 const wxChar
*szCond
,
711 // this variable can be set to true to suppress "assert failure" messages
712 static bool s_bNoAsserts
= false;
717 // make life easier for people using VC++ IDE by using this format: like
718 // this, clicking on the message will take us immediately to the place of
720 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
724 msg
<< _T(": ") << szMsg
;
726 else // no message given
731 #if wxUSE_STACKWALKER
732 class StackDump
: public wxStackWalker
737 const wxString
& GetStackTrace() const { return m_stackTrace
; }
740 virtual void OnStackFrame(const wxStackFrame
& frame
)
742 m_stackTrace
<< wxString::Format(_T("[%02d] "), frame
.GetLevel());
744 wxString name
= frame
.GetName();
747 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
751 m_stackTrace
<< wxString::Format
754 (unsigned long)frame
.GetAddress()
758 if ( frame
.HasSourceLocation() )
760 m_stackTrace
<< _T('\t')
761 << frame
.GetFileName()
766 m_stackTrace
<< _T('\n');
770 wxString m_stackTrace
;
774 dump
.Walk(5); // don't show OnAssert() call itself
775 const wxString
& stackTrace
= dump
.GetStackTrace();
776 if ( !stackTrace
.empty() )
778 msg
<< _T("\n\nCall stack:\n")
781 #endif // wxUSE_STACKWALKER
784 // if we are not in the main thread, output the assert directly and trap
785 // since dialogs cannot be displayed
786 if ( !wxThread::IsMain() )
788 msg
+= wxT(" [in child thread]");
790 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
792 OutputDebugString(msg
);
795 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
798 // He-e-e-e-elp!! we're asserting in a child thread
802 #endif // wxUSE_THREADS
806 // send it to the normal log destination
807 wxLogDebug(_T("%s"), msg
.c_str());
811 // delegate showing assert dialog (if possible) to that class
812 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
814 else // no traits object
816 // fall back to the function of last resort
817 s_bNoAsserts
= DoShowAssertDialog(msg
);
822 #endif // __WXDEBUG__