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()
38 #include "wx/apptrait.h"
39 #include "wx/cmdline.h"
40 #include "wx/confbase.h"
41 #include "wx/filename.h"
42 #include "wx/msgout.h"
43 #include "wx/tokenzr.h"
45 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
46 #include <signal.h> // for SIGTRAP used by wxTrap()
50 #include "wx/fontmap.h"
51 #endif // wxUSE_FONTMAP
53 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
54 // For MacTypes.h for Debugger function
55 #include <CoreFoundation/CFBase.h>
58 #if defined(__WXMAC__)
60 #include <CoreServices/CoreServices.h>
62 #include "wx/mac/private.h" // includes mac headers
68 #include "wx/stackwalk.h"
70 #include "wx/msw/debughlp.h"
72 #endif // wxUSE_STACKWALKER
75 // wxABI_VERSION can be defined when compiling applications but it should be
76 // left undefined when compiling the library itself, it is then set to its
77 // default value in version.h
78 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
79 #error "wxABI_VERSION should not be defined when compiling the library"
82 // ----------------------------------------------------------------------------
83 // private functions prototypes
84 // ----------------------------------------------------------------------------
87 // really just show the assert dialog
88 static bool DoShowAssertDialog(const wxString
& msg
);
90 // prepare for showing the assert dialog, use the given traits or
91 // DoShowAssertDialog() as last fallback to really show it
93 void ShowAssertDialog(const wxChar
*szFile
,
98 wxAppTraits
*traits
= NULL
);
100 // turn on the trace masks specified in the env variable WXTRACE
101 static void LINKAGEMODE
SetTraceMasks();
102 #endif // __WXDEBUG__
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
110 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
112 // ============================================================================
113 // wxAppConsole implementation
114 // ============================================================================
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
120 wxAppConsole::wxAppConsole()
124 ms_appInstance
= this;
129 // In unicode mode the SetTraceMasks call can cause an apptraits to be
130 // created, but since we are still in the constructor the wrong kind will
131 // be created for GUI apps. Destroy it so it can be created again later.
138 wxAppConsole::~wxAppConsole()
143 // ----------------------------------------------------------------------------
144 // initilization/cleanup
145 // ----------------------------------------------------------------------------
147 bool wxAppConsole::Initialize(int& argcOrig
, wxChar
**argvOrig
)
149 // remember the command line arguments
154 if ( m_appName
.empty() && argv
)
156 // the application name is, by default, the name of its executable file
157 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
164 void wxAppConsole::CleanUp()
168 // ----------------------------------------------------------------------------
170 // ----------------------------------------------------------------------------
172 bool wxAppConsole::OnInit()
174 #if wxUSE_CMDLINE_PARSER
175 wxCmdLineParser
parser(argc
, argv
);
177 OnInitCmdLine(parser
);
180 switch ( parser
.Parse(false /* don't show usage */) )
183 cont
= OnCmdLineHelp(parser
);
187 cont
= OnCmdLineParsed(parser
);
191 cont
= OnCmdLineError(parser
);
197 #endif // wxUSE_CMDLINE_PARSER
202 int wxAppConsole::OnExit()
205 // delete the config object if any (don't use Get() here, but Set()
206 // because Get() could create a new config object)
207 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
208 #endif // wxUSE_CONFIG
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 // ----------------------------------------------------------------------------
242 // ----------------------------------------------------------------------------
244 void wxAppConsole::ProcessPendingEvents()
247 if ( !wxPendingEventsLocker
)
251 // ensure that we're the only thread to modify the pending events list
252 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
254 if ( !wxPendingEvents
)
256 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
260 // iterate until the list becomes empty
261 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
264 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
265 wxPendingEvents
->Erase(node
);
267 // In ProcessPendingEvents(), new handlers might be add
268 // and we can safely leave the critical section here.
269 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
271 handler
->ProcessPendingEvents();
273 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
275 node
= wxPendingEvents
->GetFirst();
278 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
281 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
283 // process the events normally by default
287 // ----------------------------------------------------------------------------
288 // exception handling
289 // ----------------------------------------------------------------------------
294 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
295 wxEventFunction func
,
296 wxEvent
& event
) const
298 // by default, simply call the handler
299 (handler
->*func
)(event
);
302 #endif // wxUSE_EXCEPTIONS
304 // ----------------------------------------------------------------------------
306 // ----------------------------------------------------------------------------
308 #if wxUSE_CMDLINE_PARSER
310 #define OPTION_VERBOSE _T("verbose")
312 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
314 // the standard command line options
315 static const wxCmdLineEntryDesc cmdLineDesc
[] =
321 gettext_noop("show this help message"),
323 wxCMD_LINE_OPTION_HELP
331 gettext_noop("generate verbose log messages"),
348 parser
.SetDesc(cmdLineDesc
);
351 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
354 if ( parser
.Found(OPTION_VERBOSE
) )
356 wxLog::SetVerbose(true);
365 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
372 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
379 #endif // wxUSE_CMDLINE_PARSER
381 // ----------------------------------------------------------------------------
383 // ----------------------------------------------------------------------------
386 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
387 const char *componentName
)
389 #if 0 // can't use wxLogTrace, not up and running yet
390 printf("checking build options object '%s' (ptr %p) in '%s'\n",
391 optionsSignature
, optionsSignature
, componentName
);
394 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
396 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
397 wxString prog
= wxString::FromAscii(optionsSignature
);
398 wxString progName
= wxString::FromAscii(componentName
);
401 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
402 lib
.c_str(), progName
.c_str(), prog
.c_str());
404 wxLogFatalError(msg
.c_str());
406 // normally wxLogFatalError doesn't return
416 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
422 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
425 void wxAppConsole::OnAssert(const wxChar
*file
,
430 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
433 #endif // __WXDEBUG__
435 // ============================================================================
436 // other classes implementations
437 // ============================================================================
439 // ----------------------------------------------------------------------------
440 // wxConsoleAppTraitsBase
441 // ----------------------------------------------------------------------------
445 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
447 return new wxLogStderr
;
452 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
454 return new wxMessageOutputStderr
;
459 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
461 return (wxFontMapper
*)new wxFontMapperBase
;
464 #endif // wxUSE_FONTMAP
466 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
468 // console applications don't use renderers
473 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
475 return wxAppTraitsBase::ShowAssertDialog(msg
);
479 bool wxConsoleAppTraitsBase::HasStderr()
481 // console applications always have stderr, even under Mac/Windows
485 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
490 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
496 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
502 // ----------------------------------------------------------------------------
504 // ----------------------------------------------------------------------------
508 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
510 wxString msg
= msgOriginal
;
512 #if wxUSE_STACKWALKER
513 #if !defined(__WXMSW__)
514 // on Unix stack frame generation may take some time, depending on the
515 // size of the executable mainly... warn the user that we are working
516 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
520 const wxString stackTrace
= GetAssertStackTrace();
521 if ( !stackTrace
.empty() )
522 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
523 #endif // wxUSE_STACKWALKER
525 return DoShowAssertDialog(msg
);
528 #if wxUSE_STACKWALKER
529 wxString
wxAppTraitsBase::GetAssertStackTrace()
533 class StackDump
: public wxStackWalker
538 const wxString
& GetStackTrace() const { return m_stackTrace
; }
541 virtual void OnStackFrame(const wxStackFrame
& frame
)
543 m_stackTrace
<< wxString::Format
546 wx_truncate_cast(int, frame
.GetLevel())
549 wxString name
= frame
.GetName();
552 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
556 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
559 if ( frame
.HasSourceLocation() )
561 m_stackTrace
<< _T('\t')
562 << frame
.GetFileName()
567 m_stackTrace
<< _T('\n');
571 wxString m_stackTrace
;
574 // don't show more than maxLines or we could get a dialog too tall to be
575 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
576 // characters it is still only 300 pixels...
577 static const int maxLines
= 20;
580 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
581 stackTrace
= dump
.GetStackTrace();
583 const int count
= stackTrace
.Freq(wxT('\n'));
584 for ( int i
= 0; i
< count
- maxLines
; i
++ )
585 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
589 #endif // wxUSE_STACKWALKER
592 #endif // __WXDEBUG__
594 // ============================================================================
595 // global functions implementation
596 // ============================================================================
606 // what else can we do?
615 wxTheApp
->WakeUpIdle();
617 //else: do nothing, what can we do?
623 bool wxAssertIsEqual(int x
, int y
)
628 // break into the debugger
631 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
633 #elif defined(__WXMAC__) && !defined(__DARWIN__)
639 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
641 #elif defined(__UNIX__)
648 // this function is called when an assert fails
649 void wxOnAssert(const wxChar
*szFile
,
652 const wxChar
*szCond
,
656 static bool s_bInAssert
= false;
660 // He-e-e-e-elp!! we're trapped in endless loop
670 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
671 const wxString strFunc
= wxString::FromAscii(szFunc
);
675 // by default, show the assert dialog box -- we can't customize this
677 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
681 // let the app process it as it wants
682 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
688 #endif // __WXDEBUG__
690 // ============================================================================
691 // private functions implementation
692 // ============================================================================
696 static void LINKAGEMODE
SetTraceMasks()
700 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
702 wxStringTokenizer
tkn(mask
, wxT(",;:"));
703 while ( tkn
.HasMoreTokens() )
704 wxLog::AddTraceMask(tkn
.GetNextToken());
709 bool DoShowAssertDialog(const wxString
& msg
)
711 // under MSW we can show the dialog even in the console mode
712 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
713 wxString
msgDlg(msg
);
715 // this message is intentionally not translated -- it is for
717 msgDlg
+= wxT("\nDo you want to stop the program?\n")
718 wxT("You can also choose [Cancel] to suppress ")
719 wxT("further warnings.");
721 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
722 MB_YESNOCANCEL
| MB_ICONSTOP
) )
732 //case IDNO: nothing to do
735 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
738 // TODO: ask the user to enter "Y" or "N" on the console?
740 #endif // __WXMSW__/!__WXMSW__
742 // continue with the asserts
746 // show the assert modal dialog
748 void ShowAssertDialog(const wxChar
*szFile
,
750 const wxChar
*szFunc
,
751 const wxChar
*szCond
,
755 // this variable can be set to true to suppress "assert failure" messages
756 static bool s_bNoAsserts
= false;
761 // make life easier for people using VC++ IDE by using this format: like
762 // this, clicking on the message will take us immediately to the place of
764 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
766 // add the function name, if any
767 if ( szFunc
&& *szFunc
)
768 msg
<< _T(" in ") << szFunc
<< _T("()");
770 // and the message itself
773 msg
<< _T(": ") << szMsg
;
775 else // no message given
781 // if we are not in the main thread, output the assert directly and trap
782 // since dialogs cannot be displayed
783 if ( !wxThread::IsMain() )
785 msg
+= wxT(" [in child thread]");
787 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
789 OutputDebugString(msg
);
792 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
795 // He-e-e-e-elp!! we're asserting in a child thread
799 #endif // wxUSE_THREADS
803 // send it to the normal log destination
804 wxLogDebug(_T("%s"), msg
.c_str());
808 // delegate showing assert dialog (if possible) to that class
809 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
811 else // no traits object
813 // fall back to the function of last resort
814 s_bNoAsserts
= DoShowAssertDialog(msg
);
819 #endif // __WXDEBUG__