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(__WXMAC__)
55 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
56 // I don't know which headers are needed under earlier systems so
57 // include everything when in doubt
61 #include "wx/mac/private.h" // includes mac headers
66 #ifdef wxUSE_STACKWALKER
67 #include "wx/stackwalk.h"
68 #endif // wxUSE_STACKWALKER
71 // ----------------------------------------------------------------------------
72 // private functions prototypes
73 // ----------------------------------------------------------------------------
76 // really just show the assert dialog
77 static bool DoShowAssertDialog(const wxString
& msg
);
79 // prepare for showing the assert dialog, use the given traits or
80 // DoShowAssertDialog() as last fallback to really show it
82 void ShowAssertDialog(const wxChar
*szFile
,
86 wxAppTraits
*traits
= NULL
);
88 // turn on the trace masks specified in the env variable WXTRACE
89 static void LINKAGEMODE
SetTraceMasks();
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
96 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
98 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
100 // ============================================================================
101 // wxAppConsole implementation
102 // ============================================================================
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 wxAppConsole::wxAppConsole()
112 ms_appInstance
= this;
117 // In unicode mode the SetTraceMasks call can cause an apptraits to be
118 // created, but since we are still in the constructor the wrong kind will
119 // be created for GUI apps. Destroy it so it can be created again later.
126 wxAppConsole::~wxAppConsole()
131 // ----------------------------------------------------------------------------
132 // initilization/cleanup
133 // ----------------------------------------------------------------------------
135 bool wxAppConsole::Initialize(int& argc
, wxChar
**argv
)
138 // If some code logged something before wxApp instance was created,
139 // wxLogStderr was set as the target. Undo it here by destroying the
140 // current target. It will be re-created next time logging is needed, but
141 // this time wxAppTraits will be used:
142 delete wxLog::SetActiveTarget(NULL
);
145 // remember the command line arguments
150 if ( m_appName
.empty() && argv
)
152 // the application name is, by default, the name of its executable file
153 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
160 void wxAppConsole::CleanUp()
164 // ----------------------------------------------------------------------------
166 // ----------------------------------------------------------------------------
168 bool wxAppConsole::OnInit()
170 #if wxUSE_CMDLINE_PARSER
171 wxCmdLineParser
parser(argc
, argv
);
173 OnInitCmdLine(parser
);
176 switch ( parser
.Parse(false /* don't show usage */) )
179 cont
= OnCmdLineHelp(parser
);
183 cont
= OnCmdLineParsed(parser
);
187 cont
= OnCmdLineError(parser
);
193 #endif // wxUSE_CMDLINE_PARSER
198 int wxAppConsole::OnExit()
201 // delete the config object if any (don't use Get() here, but Set()
202 // because Get() could create a new config object)
203 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
204 #endif // wxUSE_CONFIG
206 // use Set(NULL) and not Get() to avoid creating a message output object on
207 // demand when we just want to delete it
208 delete wxMessageOutput::Set(NULL
);
213 void wxAppConsole::Exit()
218 // ----------------------------------------------------------------------------
220 // ----------------------------------------------------------------------------
222 wxAppTraits
*wxAppConsole::CreateTraits()
224 return new wxConsoleAppTraits
;
227 wxAppTraits
*wxAppConsole::GetTraits()
229 // FIXME-MT: protect this with a CS?
232 m_traits
= CreateTraits();
234 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
240 // we must implement CreateXXX() in wxApp itself for backwards compatibility
241 #if WXWIN_COMPATIBILITY_2_4
245 wxLog
*wxAppConsole::CreateLogTarget()
247 wxAppTraits
*traits
= GetTraits();
248 return traits
? traits
->CreateLogTarget() : NULL
;
253 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
255 wxAppTraits
*traits
= GetTraits();
256 return traits
? traits
->CreateMessageOutput() : NULL
;
259 #endif // WXWIN_COMPATIBILITY_2_4
261 // ----------------------------------------------------------------------------
263 // ----------------------------------------------------------------------------
265 void wxAppConsole::ProcessPendingEvents()
267 // ensure that we're the only thread to modify the pending events list
268 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
270 if ( !wxPendingEvents
)
272 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
276 // iterate until the list becomes empty
277 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
280 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
281 wxPendingEvents
->Erase(node
);
283 // In ProcessPendingEvents(), new handlers might be add
284 // and we can safely leave the critical section here.
285 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
286 handler
->ProcessPendingEvents();
287 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
289 node
= wxPendingEvents
->GetFirst();
292 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
295 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
297 // process the events normally by default
301 // ----------------------------------------------------------------------------
302 // exception handling
303 // ----------------------------------------------------------------------------
308 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
309 wxEventFunction func
,
310 wxEvent
& event
) const
312 // by default, simply call the handler
313 (handler
->*func
)(event
);
317 wxAppConsole::OnExceptionInMainLoop()
321 // some compilers are too stupid to know that we never return after throw
322 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
327 #endif // wxUSE_EXCEPTIONS
329 // ----------------------------------------------------------------------------
331 // ----------------------------------------------------------------------------
333 #if wxUSE_CMDLINE_PARSER
335 #define OPTION_VERBOSE _T("verbose")
337 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
339 // the standard command line options
340 static const wxCmdLineEntryDesc cmdLineDesc
[] =
346 gettext_noop("show this help message"),
348 wxCMD_LINE_OPTION_HELP
356 gettext_noop("generate verbose log messages"),
373 parser
.SetDesc(cmdLineDesc
);
376 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
379 if ( parser
.Found(OPTION_VERBOSE
) )
381 wxLog::SetVerbose(true);
390 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
397 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
404 #endif // wxUSE_CMDLINE_PARSER
406 // ----------------------------------------------------------------------------
408 // ----------------------------------------------------------------------------
411 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
412 const char *componentName
)
414 #if 0 // can't use wxLogTrace, not up and running yet
415 printf("checking build options object '%s' (ptr %p) in '%s'\n",
416 optionsSignature
, optionsSignature
, componentName
);
419 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
421 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
422 wxString prog
= wxString::FromAscii(optionsSignature
);
423 wxString progName
= wxString::FromAscii(componentName
);
426 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
427 lib
.c_str(), progName
.c_str(), prog
.c_str());
429 wxLogFatalError(msg
.c_str());
431 // normally wxLogFatalError doesn't return
441 void wxAppConsole::OnAssert(const wxChar
*file
,
446 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
449 #endif // __WXDEBUG__
451 #if WXWIN_COMPATIBILITY_2_4
453 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
455 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
460 // ============================================================================
461 // other classes implementations
462 // ============================================================================
464 // ----------------------------------------------------------------------------
465 // wxConsoleAppTraitsBase
466 // ----------------------------------------------------------------------------
470 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
472 return new wxLogStderr
;
477 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
479 return new wxMessageOutputStderr
;
484 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
486 return (wxFontMapper
*)new wxFontMapperBase
;
489 #endif // wxUSE_FONTMAP
491 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
493 // console applications don't use renderers
498 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
500 return wxAppTraitsBase::ShowAssertDialog(msg
);
504 bool wxConsoleAppTraitsBase::HasStderr()
506 // console applications always have stderr, even under Mac/Windows
510 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
515 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
521 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
527 // ----------------------------------------------------------------------------
529 // ----------------------------------------------------------------------------
533 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
535 return DoShowAssertDialog(msg
);
538 #endif // __WXDEBUG__
540 // ============================================================================
541 // global functions implementation
542 // ============================================================================
552 // what else can we do?
561 wxTheApp
->WakeUpIdle();
563 //else: do nothing, what can we do?
569 bool wxAssertIsEqual(int x
, int y
)
574 // break into the debugger
577 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
579 #elif defined(__WXMAC__) && !defined(__DARWIN__)
585 #elif defined(__UNIX__)
592 void wxAssert(int cond
,
593 const wxChar
*szFile
,
595 const wxChar
*szCond
,
599 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
602 // this function is called when an assert fails
603 void wxOnAssert(const wxChar
*szFile
,
605 const wxChar
*szCond
,
609 static bool s_bInAssert
= false;
613 // He-e-e-e-elp!! we're trapped in endless loop
625 // by default, show the assert dialog box -- we can't customize this
627 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
631 // let the app process it as it wants
632 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
638 #endif // __WXDEBUG__
640 // ============================================================================
641 // private functions implementation
642 // ============================================================================
646 static void LINKAGEMODE
SetTraceMasks()
650 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
652 wxStringTokenizer
tkn(mask
, wxT(",;:"));
653 while ( tkn
.HasMoreTokens() )
654 wxLog::AddTraceMask(tkn
.GetNextToken());
659 bool DoShowAssertDialog(const wxString
& msg
)
661 // under MSW we can show the dialog even in the console mode
662 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
663 wxString
msgDlg(msg
);
665 // this message is intentionally not translated -- it is for
667 msgDlg
+= wxT("\nDo you want to stop the program?\n")
668 wxT("You can also choose [Cancel] to suppress ")
669 wxT("further warnings.");
671 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
672 MB_YESNOCANCEL
| MB_ICONSTOP
) )
682 //case IDNO: nothing to do
685 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
688 // TODO: ask the user to enter "Y" or "N" on the console?
690 #endif // __WXMSW__/!__WXMSW__
692 // continue with the asserts
696 // show the assert modal dialog
698 void ShowAssertDialog(const wxChar
*szFile
,
700 const wxChar
*szCond
,
704 // this variable can be set to true to suppress "assert failure" messages
705 static bool s_bNoAsserts
= false;
710 // make life easier for people using VC++ IDE by using this format: like
711 // this, clicking on the message will take us immediately to the place of
713 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
717 msg
<< _T(": ") << szMsg
;
719 else // no message given
724 #if wxUSE_STACKWALKER
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 const wxString
& stackTrace
= dump
.GetStackTrace();
769 if ( !stackTrace
.empty() )
771 msg
<< _T("\n\nCall stack:\n")
774 #endif // wxUSE_STACKWALKER
777 // if we are not in the main thread, output the assert directly and trap
778 // since dialogs cannot be displayed
779 if ( !wxThread::IsMain() )
781 msg
+= wxT(" [in child thread]");
783 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
785 OutputDebugString(msg
);
788 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
791 // He-e-e-e-elp!! we're asserting in a child thread
795 #endif // wxUSE_THREADS
799 // send it to the normal log destination
800 wxLogDebug(_T("%s"), msg
.c_str());
804 // delegate showing assert dialog (if possible) to that class
805 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
807 else // no traits object
809 // fall back to the function of last resort
810 s_bNoAsserts
= DoShowAssertDialog(msg
);
815 #endif // __WXDEBUG__