1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/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__)
61 #include <CoreServices/CoreServices.h>
63 #include "wx/mac/private.h" // includes mac headers
69 #include "wx/stackwalk.h"
71 #include "wx/msw/debughlp.h"
73 #endif // wxUSE_STACKWALKER
76 // wxABI_VERSION can be defined when compiling applications but it should be
77 // left undefined when compiling the library itself, it is then set to its
78 // default value in version.h
79 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
80 #error "wxABI_VERSION should not be defined when compiling the library"
83 // ----------------------------------------------------------------------------
84 // private functions prototypes
85 // ----------------------------------------------------------------------------
88 // really just show the assert dialog
89 static bool DoShowAssertDialog(const wxString
& msg
);
91 // prepare for showing the assert dialog, use the given traits or
92 // DoShowAssertDialog() as last fallback to really show it
94 void ShowAssertDialog(const wxChar
*szFile
,
99 wxAppTraits
*traits
= NULL
);
101 // turn on the trace masks specified in the env variable WXTRACE
102 static void LINKAGEMODE
SetTraceMasks();
103 #endif // __WXDEBUG__
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
111 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
113 // ============================================================================
114 // wxAppConsole implementation
115 // ============================================================================
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 wxAppConsole::wxAppConsole()
125 ms_appInstance
= this;
130 // In unicode mode the SetTraceMasks call can cause an apptraits to be
131 // created, but since we are still in the constructor the wrong kind will
132 // be created for GUI apps. Destroy it so it can be created again later.
139 wxAppConsole::~wxAppConsole()
144 // ----------------------------------------------------------------------------
145 // initilization/cleanup
146 // ----------------------------------------------------------------------------
148 bool wxAppConsole::Initialize(int& argcOrig
, wxChar
**argvOrig
)
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
214 void wxAppConsole::Exit()
219 // ----------------------------------------------------------------------------
221 // ----------------------------------------------------------------------------
223 wxAppTraits
*wxAppConsole::CreateTraits()
225 return new wxConsoleAppTraits
;
228 wxAppTraits
*wxAppConsole::GetTraits()
230 // FIXME-MT: protect this with a CS?
233 m_traits
= CreateTraits();
235 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
241 // we must implement CreateXXX() in wxApp itself for backwards compatibility
242 #if WXWIN_COMPATIBILITY_2_4
246 wxLog
*wxAppConsole::CreateLogTarget()
248 wxAppTraits
*traits
= GetTraits();
249 return traits
? traits
->CreateLogTarget() : NULL
;
254 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
256 wxAppTraits
*traits
= GetTraits();
257 return traits
? traits
->CreateMessageOutput() : NULL
;
260 #endif // WXWIN_COMPATIBILITY_2_4
262 // ----------------------------------------------------------------------------
264 // ----------------------------------------------------------------------------
266 void wxAppConsole::ProcessPendingEvents()
269 if ( !wxPendingEventsLocker
)
273 // ensure that we're the only thread to modify the pending events list
274 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
276 if ( !wxPendingEvents
)
278 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
282 // iterate until the list becomes empty
283 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
286 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
287 wxPendingEvents
->Erase(node
);
289 // In ProcessPendingEvents(), new handlers might be add
290 // and we can safely leave the critical section here.
291 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
293 handler
->ProcessPendingEvents();
295 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
297 node
= wxPendingEvents
->GetFirst();
300 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
303 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
305 // process the events normally by default
309 // ----------------------------------------------------------------------------
310 // exception handling
311 // ----------------------------------------------------------------------------
316 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
317 wxEventFunction func
,
318 wxEvent
& event
) const
320 // by default, simply call the handler
321 (handler
->*func
)(event
);
324 #endif // wxUSE_EXCEPTIONS
326 // ----------------------------------------------------------------------------
328 // ----------------------------------------------------------------------------
330 #if wxUSE_CMDLINE_PARSER
332 #define OPTION_VERBOSE _T("verbose")
334 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
336 // the standard command line options
337 static const wxCmdLineEntryDesc cmdLineDesc
[] =
343 gettext_noop("show this help message"),
345 wxCMD_LINE_OPTION_HELP
353 gettext_noop("generate verbose log messages"),
370 parser
.SetDesc(cmdLineDesc
);
373 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
376 if ( parser
.Found(OPTION_VERBOSE
) )
378 wxLog::SetVerbose(true);
387 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
394 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
401 #endif // wxUSE_CMDLINE_PARSER
403 // ----------------------------------------------------------------------------
405 // ----------------------------------------------------------------------------
408 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
409 const char *componentName
)
411 #if 0 // can't use wxLogTrace, not up and running yet
412 printf("checking build options object '%s' (ptr %p) in '%s'\n",
413 optionsSignature
, optionsSignature
, componentName
);
416 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
418 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
419 wxString prog
= wxString::FromAscii(optionsSignature
);
420 wxString progName
= wxString::FromAscii(componentName
);
423 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
424 lib
.c_str(), progName
.c_str(), prog
.c_str());
426 wxLogFatalError(msg
.c_str());
428 // normally wxLogFatalError doesn't return
438 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
444 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
447 void wxAppConsole::OnAssert(const wxChar
*file
,
452 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
455 #endif // __WXDEBUG__
457 #if WXWIN_COMPATIBILITY_2_4
459 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
461 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
466 // ============================================================================
467 // other classes implementations
468 // ============================================================================
470 // ----------------------------------------------------------------------------
471 // wxConsoleAppTraitsBase
472 // ----------------------------------------------------------------------------
476 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
478 return new wxLogStderr
;
483 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
485 return new wxMessageOutputStderr
;
490 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
492 return (wxFontMapper
*)new wxFontMapperBase
;
495 #endif // wxUSE_FONTMAP
497 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
499 // console applications don't use renderers
504 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
506 return wxAppTraitsBase::ShowAssertDialog(msg
);
510 bool wxConsoleAppTraitsBase::HasStderr()
512 // console applications always have stderr, even under Mac/Windows
516 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
521 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
527 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
533 // ----------------------------------------------------------------------------
535 // ----------------------------------------------------------------------------
539 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
541 return DoShowAssertDialog(msg
);
544 #endif // __WXDEBUG__
546 // ============================================================================
547 // global functions implementation
548 // ============================================================================
558 // what else can we do?
567 wxTheApp
->WakeUpIdle();
569 //else: do nothing, what can we do?
575 bool wxAssertIsEqual(int x
, int y
)
580 // break into the debugger
583 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
585 #elif defined(__WXMAC__) && !defined(__DARWIN__)
591 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
593 #elif defined(__UNIX__)
600 // this function is called when an assert fails
601 void wxOnAssert(const wxChar
*szFile
,
604 const wxChar
*szCond
,
608 static bool s_bInAssert
= false;
612 // He-e-e-e-elp!! we're trapped in endless loop
622 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
623 const wxString strFunc
= wxString::FromAscii(szFunc
);
627 // by default, show the assert dialog box -- we can't customize this
629 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
633 // let the app process it as it wants
634 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
640 #endif // __WXDEBUG__
642 // ============================================================================
643 // private functions implementation
644 // ============================================================================
648 static void LINKAGEMODE
SetTraceMasks()
652 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
654 wxStringTokenizer
tkn(mask
, wxT(",;:"));
655 while ( tkn
.HasMoreTokens() )
656 wxLog::AddTraceMask(tkn
.GetNextToken());
661 bool DoShowAssertDialog(const wxString
& msg
)
663 // under MSW we can show the dialog even in the console mode
664 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
665 wxString
msgDlg(msg
);
667 // this message is intentionally not translated -- it is for
669 msgDlg
+= wxT("\nDo you want to stop the program?\n")
670 wxT("You can also choose [Cancel] to suppress ")
671 wxT("further warnings.");
673 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
674 MB_YESNOCANCEL
| MB_ICONSTOP
) )
684 //case IDNO: nothing to do
687 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
690 // TODO: ask the user to enter "Y" or "N" on the console?
692 #endif // __WXMSW__/!__WXMSW__
694 // continue with the asserts
698 #if wxUSE_STACKWALKER
699 static wxString
GetAssertStackTrace()
703 class StackDump
: public wxStackWalker
708 const wxString
& GetStackTrace() const { return m_stackTrace
; }
711 virtual void OnStackFrame(const wxStackFrame
& frame
)
713 m_stackTrace
<< wxString::Format
716 wx_truncate_cast(int, frame
.GetLevel())
719 wxString name
= frame
.GetName();
722 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
726 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
729 if ( frame
.HasSourceLocation() )
731 m_stackTrace
<< _T('\t')
732 << frame
.GetFileName()
737 m_stackTrace
<< _T('\n');
741 wxString m_stackTrace
;
745 dump
.Walk(2); // don't show OnAssert() call itself
746 stackTrace
= dump
.GetStackTrace();
748 // don't show more than maxLines or we could get a dialog too tall to be
749 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
750 // characters it is still only 300 pixels...
751 static const int maxLines
= 20;
752 const int count
= stackTrace
.Freq(wxT('\n'));
753 for ( int i
= 0; i
< count
- maxLines
; i
++ )
754 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
758 #endif // wxUSE_STACKWALKER
760 // show the assert modal dialog
762 void ShowAssertDialog(const wxChar
*szFile
,
764 const wxChar
*szFunc
,
765 const wxChar
*szCond
,
769 // this variable can be set to true to suppress "assert failure" messages
770 static bool s_bNoAsserts
= false;
775 // make life easier for people using VC++ IDE by using this format: like
776 // this, clicking on the message will take us immediately to the place of
778 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
780 // add the function name, if any
781 if ( szFunc
&& *szFunc
)
782 msg
<< _T(" in ") << szFunc
<< _T("()");
784 // and the message itself
787 msg
<< _T(": ") << szMsg
;
789 else // no message given
794 #if wxUSE_STACKWALKER
795 const wxString stackTrace
= GetAssertStackTrace();
796 if ( !stackTrace
.empty() )
798 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
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__