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"
29 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
36 #include "wx/wxcrtvararg.h"
39 #include "wx/apptrait.h"
40 #include "wx/cmdline.h"
41 #include "wx/confbase.h"
42 #include "wx/filename.h"
43 #include "wx/msgout.h"
44 #include "wx/tokenzr.h"
46 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
47 #include <signal.h> // for SIGTRAP used by wxTrap()
53 #include "wx/fontmap.h"
54 #endif // wxUSE_FONTMAP
56 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
57 // For MacTypes.h for Debugger function
58 #include <CoreFoundation/CFBase.h>
61 #if defined(__WXMAC__)
63 #include <CoreServices/CoreServices.h>
65 #include "wx/mac/private.h" // includes mac headers
71 #include "wx/stackwalk.h"
73 #include "wx/msw/debughlp.h"
75 #endif // wxUSE_STACKWALKER
78 // wxABI_VERSION can be defined when compiling applications but it should be
79 // left undefined when compiling the library itself, it is then set to its
80 // default value in version.h
81 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
82 #error "wxABI_VERSION should not be defined when compiling the library"
85 // ----------------------------------------------------------------------------
86 // private functions prototypes
87 // ----------------------------------------------------------------------------
90 // really just show the assert dialog
91 static bool DoShowAssertDialog(const wxString
& msg
);
93 // prepare for showing the assert dialog, use the given traits or
94 // DoShowAssertDialog() as last fallback to really show it
96 void ShowAssertDialog(const wxChar
*szFile
,
101 wxAppTraits
*traits
= NULL
);
103 // turn on the trace masks specified in the env variable WXTRACE
104 static void LINKAGEMODE
SetTraceMasks();
105 #endif // __WXDEBUG__
107 // ----------------------------------------------------------------------------
109 // ----------------------------------------------------------------------------
111 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
113 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
115 // ============================================================================
116 // wxAppConsole implementation
117 // ============================================================================
119 // ----------------------------------------------------------------------------
121 // ----------------------------------------------------------------------------
123 wxAppConsole::wxAppConsole()
127 ms_appInstance
= this;
132 // In unicode mode the SetTraceMasks call can cause an apptraits to be
133 // created, but since we are still in the constructor the wrong kind will
134 // be created for GUI apps. Destroy it so it can be created again later.
141 wxAppConsole::~wxAppConsole()
146 // ----------------------------------------------------------------------------
147 // initilization/cleanup
148 // ----------------------------------------------------------------------------
150 bool wxAppConsole::Initialize(int& argcOrig
, wxChar
**argvOrig
)
153 GetTraits()->SetLocale();
156 // remember the command line arguments
161 if ( m_appName
.empty() && argv
)
163 // the application name is, by default, the name of its executable file
164 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
166 #endif // !__WXPALMOS__
171 void wxAppConsole::CleanUp()
175 // ----------------------------------------------------------------------------
177 // ----------------------------------------------------------------------------
179 bool wxAppConsole::OnInit()
181 #if wxUSE_CMDLINE_PARSER
182 wxCmdLineParser
parser(argc
, argv
);
184 OnInitCmdLine(parser
);
187 switch ( parser
.Parse(false /* don't show usage */) )
190 cont
= OnCmdLineHelp(parser
);
194 cont
= OnCmdLineParsed(parser
);
198 cont
= OnCmdLineError(parser
);
204 #endif // wxUSE_CMDLINE_PARSER
209 int wxAppConsole::OnExit()
212 // delete the config object if any (don't use Get() here, but Set()
213 // because Get() could create a new config object)
214 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
215 #endif // wxUSE_CONFIG
220 void wxAppConsole::Exit()
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
229 wxAppTraits
*wxAppConsole::CreateTraits()
231 return new wxConsoleAppTraits
;
234 wxAppTraits
*wxAppConsole::GetTraits()
236 // FIXME-MT: protect this with a CS?
239 m_traits
= CreateTraits();
241 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
247 // ----------------------------------------------------------------------------
249 // ----------------------------------------------------------------------------
251 void wxAppConsole::ProcessPendingEvents()
254 if ( !wxPendingEventsLocker
)
258 // ensure that we're the only thread to modify the pending events list
259 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
261 if ( !wxPendingEvents
)
263 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
267 // iterate until the list becomes empty
268 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
271 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
272 wxPendingEvents
->Erase(node
);
274 // In ProcessPendingEvents(), new handlers might be add
275 // and we can safely leave the critical section here.
276 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
278 handler
->ProcessPendingEvents();
280 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
282 node
= wxPendingEvents
->GetFirst();
285 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
288 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
290 // process the events normally by default
294 // ----------------------------------------------------------------------------
295 // exception handling
296 // ----------------------------------------------------------------------------
301 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
302 wxEventFunction func
,
303 wxEvent
& event
) const
305 // by default, simply call the handler
306 (handler
->*func
)(event
);
309 #endif // wxUSE_EXCEPTIONS
311 // ----------------------------------------------------------------------------
313 // ----------------------------------------------------------------------------
315 #if wxUSE_CMDLINE_PARSER
317 #define OPTION_VERBOSE _T("verbose")
319 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
321 // the standard command line options
322 static const wxCmdLineEntryDesc cmdLineDesc
[] =
328 gettext_noop("show this help message"),
330 wxCMD_LINE_OPTION_HELP
338 gettext_noop("generate verbose log messages"),
355 parser
.SetDesc(cmdLineDesc
);
358 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
361 if ( parser
.Found(OPTION_VERBOSE
) )
363 wxLog::SetVerbose(true);
372 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
379 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
386 #endif // wxUSE_CMDLINE_PARSER
388 // ----------------------------------------------------------------------------
390 // ----------------------------------------------------------------------------
393 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
394 const char *componentName
)
396 #if 0 // can't use wxLogTrace, not up and running yet
397 printf("checking build options object '%s' (ptr %p) in '%s'\n",
398 optionsSignature
, optionsSignature
, componentName
);
401 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
403 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
404 wxString prog
= wxString::FromAscii(optionsSignature
);
405 wxString progName
= wxString::FromAscii(componentName
);
408 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
409 lib
.c_str(), progName
.c_str(), prog
.c_str());
411 wxLogFatalError(msg
.c_str());
413 // normally wxLogFatalError doesn't return
423 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
429 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
432 void wxAppConsole::OnAssert(const wxChar
*file
,
437 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
440 #endif // __WXDEBUG__
442 // ============================================================================
443 // other classes implementations
444 // ============================================================================
446 // ----------------------------------------------------------------------------
447 // wxConsoleAppTraitsBase
448 // ----------------------------------------------------------------------------
452 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
454 return new wxLogStderr
;
459 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
461 return new wxMessageOutputStderr
;
466 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
468 return (wxFontMapper
*)new wxFontMapperBase
;
471 #endif // wxUSE_FONTMAP
473 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
475 // console applications don't use renderers
480 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
482 return wxAppTraitsBase::ShowAssertDialog(msg
);
486 bool wxConsoleAppTraitsBase::HasStderr()
488 // console applications always have stderr, even under Mac/Windows
492 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
497 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
503 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
509 // ----------------------------------------------------------------------------
511 // ----------------------------------------------------------------------------
514 void wxAppTraitsBase::SetLocale()
516 setlocale(LC_ALL
, "");
517 wxUpdateLocaleIsUtf8();
523 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
525 wxString msg
= msgOriginal
;
527 #if wxUSE_STACKWALKER
528 #if !defined(__WXMSW__)
529 // on Unix stack frame generation may take some time, depending on the
530 // size of the executable mainly... warn the user that we are working
531 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
535 const wxString stackTrace
= GetAssertStackTrace();
536 if ( !stackTrace
.empty() )
537 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
538 #endif // wxUSE_STACKWALKER
540 return DoShowAssertDialog(msg
);
543 #if wxUSE_STACKWALKER
544 wxString
wxAppTraitsBase::GetAssertStackTrace()
548 class StackDump
: public wxStackWalker
553 const wxString
& GetStackTrace() const { return m_stackTrace
; }
556 virtual void OnStackFrame(const wxStackFrame
& frame
)
558 m_stackTrace
<< wxString::Format
561 wx_truncate_cast(int, frame
.GetLevel())
564 wxString name
= frame
.GetName();
567 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
571 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
574 if ( frame
.HasSourceLocation() )
576 m_stackTrace
<< _T('\t')
577 << frame
.GetFileName()
582 m_stackTrace
<< _T('\n');
586 wxString m_stackTrace
;
589 // don't show more than maxLines or we could get a dialog too tall to be
590 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
591 // characters it is still only 300 pixels...
592 static const int maxLines
= 20;
595 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
596 stackTrace
= dump
.GetStackTrace();
598 const int count
= stackTrace
.Freq(wxT('\n'));
599 for ( int i
= 0; i
< count
- maxLines
; i
++ )
600 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
604 #endif // wxUSE_STACKWALKER
607 #endif // __WXDEBUG__
609 // ============================================================================
610 // global functions implementation
611 // ============================================================================
621 // what else can we do?
630 wxTheApp
->WakeUpIdle();
632 //else: do nothing, what can we do?
638 bool wxAssertIsEqual(int x
, int y
)
643 // break into the debugger
646 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
648 #elif defined(__WXMAC__) && !defined(__DARWIN__)
654 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
656 #elif defined(__UNIX__)
663 // this function is called when an assert fails
664 void wxOnAssert(const wxChar
*szFile
,
667 const wxChar
*szCond
,
671 static bool s_bInAssert
= false;
675 // He-e-e-e-elp!! we're trapped in endless loop
685 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
686 const wxString strFunc
= wxString::FromAscii(szFunc
);
690 // by default, show the assert dialog box -- we can't customize this
692 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
696 // let the app process it as it wants
697 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
703 #endif // __WXDEBUG__
705 // ============================================================================
706 // private functions implementation
707 // ============================================================================
711 static void LINKAGEMODE
SetTraceMasks()
715 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
717 wxStringTokenizer
tkn(mask
, wxT(",;:"));
718 while ( tkn
.HasMoreTokens() )
719 wxLog::AddTraceMask(tkn
.GetNextToken());
724 bool DoShowAssertDialog(const wxString
& msg
)
726 // under MSW we can show the dialog even in the console mode
727 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
728 wxString
msgDlg(msg
);
730 // this message is intentionally not translated -- it is for
732 msgDlg
+= wxT("\nDo you want to stop the program?\n")
733 wxT("You can also choose [Cancel] to suppress ")
734 wxT("further warnings.");
736 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
737 MB_YESNOCANCEL
| MB_ICONSTOP
) )
747 //case IDNO: nothing to do
750 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
753 // TODO: ask the user to enter "Y" or "N" on the console?
755 #endif // __WXMSW__/!__WXMSW__
757 // continue with the asserts
761 // show the assert modal dialog
763 void ShowAssertDialog(const wxChar
*szFile
,
765 const wxChar
*szFunc
,
766 const wxChar
*szCond
,
770 // this variable can be set to true to suppress "assert failure" messages
771 static bool s_bNoAsserts
= false;
776 // make life easier for people using VC++ IDE by using this format: like
777 // this, clicking on the message will take us immediately to the place of
779 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
781 // add the function name, if any
782 if ( szFunc
&& *szFunc
)
783 msg
<< _T(" in ") << szFunc
<< _T("()");
785 // and the message itself
788 msg
<< _T(": ") << szMsg
;
790 else // no message given
796 // if we are not in the main thread, output the assert directly and trap
797 // since dialogs cannot be displayed
798 if ( !wxThread::IsMain() )
800 msg
+= wxT(" [in child thread]");
802 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
804 OutputDebugString(msg
);
807 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
810 // He-e-e-e-elp!! we're asserting in a child thread
814 #endif // wxUSE_THREADS
818 // send it to the normal log destination
819 wxLogDebug(_T("%s"), msg
.c_str());
823 // delegate showing assert dialog (if possible) to that class
824 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
826 else // no traits object
828 // fall back to the function of last resort
829 s_bNoAsserts
= DoShowAssertDialog(msg
);
834 #endif // __WXDEBUG__