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()
52 #include "wx/fontmap.h"
53 #endif // wxUSE_FONTMAP
55 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
56 // For MacTypes.h for Debugger function
57 #include <CoreFoundation/CFBase.h>
60 #if defined(__WXMAC__)
62 #include <CoreServices/CoreServices.h>
64 #include "wx/mac/private.h" // includes mac headers
70 #include "wx/stackwalk.h"
72 #include "wx/msw/debughlp.h"
74 #endif // wxUSE_STACKWALKER
77 // wxABI_VERSION can be defined when compiling applications but it should be
78 // left undefined when compiling the library itself, it is then set to its
79 // default value in version.h
80 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
81 #error "wxABI_VERSION should not be defined when compiling the library"
84 // ----------------------------------------------------------------------------
85 // private functions prototypes
86 // ----------------------------------------------------------------------------
89 // really just show the assert dialog
90 static bool DoShowAssertDialog(const wxString
& msg
);
92 // prepare for showing the assert dialog, use the given traits or
93 // DoShowAssertDialog() as last fallback to really show it
95 void ShowAssertDialog(const wxChar
*szFile
,
100 wxAppTraits
*traits
= NULL
);
102 // turn on the trace masks specified in the env variable WXTRACE
103 static void LINKAGEMODE
SetTraceMasks();
104 #endif // __WXDEBUG__
106 // ----------------------------------------------------------------------------
108 // ----------------------------------------------------------------------------
110 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
112 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
114 // ============================================================================
115 // wxAppConsole implementation
116 // ============================================================================
118 // ----------------------------------------------------------------------------
120 // ----------------------------------------------------------------------------
122 wxAppConsole::wxAppConsole()
126 ms_appInstance
= this;
131 // In unicode mode the SetTraceMasks call can cause an apptraits to be
132 // created, but since we are still in the constructor the wrong kind will
133 // be created for GUI apps. Destroy it so it can be created again later.
140 wxAppConsole::~wxAppConsole()
145 // ----------------------------------------------------------------------------
146 // initilization/cleanup
147 // ----------------------------------------------------------------------------
149 bool wxAppConsole::Initialize(int& argcOrig
, wxChar
**argvOrig
)
152 GetTraits()->SetLocale();
155 // remember the command line arguments
160 if ( m_appName
.empty() && argv
)
162 // the application name is, by default, the name of its executable file
163 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
165 #endif // !__WXPALMOS__
170 void wxAppConsole::CleanUp()
174 // ----------------------------------------------------------------------------
176 // ----------------------------------------------------------------------------
178 bool wxAppConsole::OnInit()
180 #if wxUSE_CMDLINE_PARSER
181 wxCmdLineParser
parser(argc
, argv
);
183 OnInitCmdLine(parser
);
186 switch ( parser
.Parse(false /* don't show usage */) )
189 cont
= OnCmdLineHelp(parser
);
193 cont
= OnCmdLineParsed(parser
);
197 cont
= OnCmdLineError(parser
);
203 #endif // wxUSE_CMDLINE_PARSER
208 int wxAppConsole::OnExit()
211 // delete the config object if any (don't use Get() here, but Set()
212 // because Get() could create a new config object)
213 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
214 #endif // wxUSE_CONFIG
219 void wxAppConsole::Exit()
224 // ----------------------------------------------------------------------------
226 // ----------------------------------------------------------------------------
228 wxAppTraits
*wxAppConsole::CreateTraits()
230 return new wxConsoleAppTraits
;
233 wxAppTraits
*wxAppConsole::GetTraits()
235 // FIXME-MT: protect this with a CS?
238 m_traits
= CreateTraits();
240 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
246 // ----------------------------------------------------------------------------
248 // ----------------------------------------------------------------------------
250 void wxAppConsole::ProcessPendingEvents()
253 if ( !wxPendingEventsLocker
)
257 // ensure that we're the only thread to modify the pending events list
258 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
260 if ( !wxPendingEvents
)
262 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
266 // iterate until the list becomes empty
267 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
270 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
271 wxPendingEvents
->Erase(node
);
273 // In ProcessPendingEvents(), new handlers might be add
274 // and we can safely leave the critical section here.
275 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
277 handler
->ProcessPendingEvents();
279 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
281 node
= wxPendingEvents
->GetFirst();
284 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
287 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
289 // process the events normally by default
293 // ----------------------------------------------------------------------------
294 // exception handling
295 // ----------------------------------------------------------------------------
300 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
301 wxEventFunction func
,
302 wxEvent
& event
) const
304 // by default, simply call the handler
305 (handler
->*func
)(event
);
308 #endif // wxUSE_EXCEPTIONS
310 // ----------------------------------------------------------------------------
312 // ----------------------------------------------------------------------------
314 #if wxUSE_CMDLINE_PARSER
316 #define OPTION_VERBOSE _T("verbose")
318 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
320 // the standard command line options
321 static const wxCmdLineEntryDesc cmdLineDesc
[] =
327 gettext_noop("show this help message"),
329 wxCMD_LINE_OPTION_HELP
337 gettext_noop("generate verbose log messages"),
354 parser
.SetDesc(cmdLineDesc
);
357 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
360 if ( parser
.Found(OPTION_VERBOSE
) )
362 wxLog::SetVerbose(true);
371 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
378 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
385 #endif // wxUSE_CMDLINE_PARSER
387 // ----------------------------------------------------------------------------
389 // ----------------------------------------------------------------------------
392 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
393 const char *componentName
)
395 #if 0 // can't use wxLogTrace, not up and running yet
396 printf("checking build options object '%s' (ptr %p) in '%s'\n",
397 optionsSignature
, optionsSignature
, componentName
);
400 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
402 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
403 wxString prog
= wxString::FromAscii(optionsSignature
);
404 wxString progName
= wxString::FromAscii(componentName
);
407 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
408 lib
.c_str(), progName
.c_str(), prog
.c_str());
410 wxLogFatalError(msg
.c_str());
412 // normally wxLogFatalError doesn't return
422 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
428 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
431 void wxAppConsole::OnAssert(const wxChar
*file
,
436 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
439 #endif // __WXDEBUG__
441 // ============================================================================
442 // other classes implementations
443 // ============================================================================
445 // ----------------------------------------------------------------------------
446 // wxConsoleAppTraitsBase
447 // ----------------------------------------------------------------------------
451 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
453 return new wxLogStderr
;
458 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
460 return new wxMessageOutputStderr
;
465 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
467 return (wxFontMapper
*)new wxFontMapperBase
;
470 #endif // wxUSE_FONTMAP
472 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
474 // console applications don't use renderers
479 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
481 return wxAppTraitsBase::ShowAssertDialog(msg
);
485 bool wxConsoleAppTraitsBase::HasStderr()
487 // console applications always have stderr, even under Mac/Windows
491 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
496 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
502 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
508 // ----------------------------------------------------------------------------
510 // ----------------------------------------------------------------------------
513 void wxAppTraitsBase::SetLocale()
515 setlocale(LC_ALL
, "");
521 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msgOriginal
)
523 wxString msg
= msgOriginal
;
525 #if wxUSE_STACKWALKER
526 #if !defined(__WXMSW__)
527 // on Unix stack frame generation may take some time, depending on the
528 // size of the executable mainly... warn the user that we are working
529 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
533 const wxString stackTrace
= GetAssertStackTrace();
534 if ( !stackTrace
.empty() )
535 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
536 #endif // wxUSE_STACKWALKER
538 return DoShowAssertDialog(msg
);
541 #if wxUSE_STACKWALKER
542 wxString
wxAppTraitsBase::GetAssertStackTrace()
546 class StackDump
: public wxStackWalker
551 const wxString
& GetStackTrace() const { return m_stackTrace
; }
554 virtual void OnStackFrame(const wxStackFrame
& frame
)
556 m_stackTrace
<< wxString::Format
559 wx_truncate_cast(int, frame
.GetLevel())
562 wxString name
= frame
.GetName();
565 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
569 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
572 if ( frame
.HasSourceLocation() )
574 m_stackTrace
<< _T('\t')
575 << frame
.GetFileName()
580 m_stackTrace
<< _T('\n');
584 wxString m_stackTrace
;
587 // don't show more than maxLines or we could get a dialog too tall to be
588 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
589 // characters it is still only 300 pixels...
590 static const int maxLines
= 20;
593 dump
.Walk(2, maxLines
); // don't show OnAssert() call itself
594 stackTrace
= dump
.GetStackTrace();
596 const int count
= stackTrace
.Freq(wxT('\n'));
597 for ( int i
= 0; i
< count
- maxLines
; i
++ )
598 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
602 #endif // wxUSE_STACKWALKER
605 #endif // __WXDEBUG__
607 // ============================================================================
608 // global functions implementation
609 // ============================================================================
619 // what else can we do?
628 wxTheApp
->WakeUpIdle();
630 //else: do nothing, what can we do?
636 bool wxAssertIsEqual(int x
, int y
)
641 // break into the debugger
644 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
646 #elif defined(__WXMAC__) && !defined(__DARWIN__)
652 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
654 #elif defined(__UNIX__)
661 // this function is called when an assert fails
662 void wxOnAssert(const wxChar
*szFile
,
665 const wxChar
*szCond
,
669 static bool s_bInAssert
= false;
673 // He-e-e-e-elp!! we're trapped in endless loop
683 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
684 const wxString strFunc
= wxString::FromAscii(szFunc
);
688 // by default, show the assert dialog box -- we can't customize this
690 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
694 // let the app process it as it wants
695 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
701 #endif // __WXDEBUG__
703 // ============================================================================
704 // private functions implementation
705 // ============================================================================
709 static void LINKAGEMODE
SetTraceMasks()
713 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
715 wxStringTokenizer
tkn(mask
, wxT(",;:"));
716 while ( tkn
.HasMoreTokens() )
717 wxLog::AddTraceMask(tkn
.GetNextToken());
722 bool DoShowAssertDialog(const wxString
& msg
)
724 // under MSW we can show the dialog even in the console mode
725 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
726 wxString
msgDlg(msg
);
728 // this message is intentionally not translated -- it is for
730 msgDlg
+= wxT("\nDo you want to stop the program?\n")
731 wxT("You can also choose [Cancel] to suppress ")
732 wxT("further warnings.");
734 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
735 MB_YESNOCANCEL
| MB_ICONSTOP
) )
745 //case IDNO: nothing to do
748 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
751 // TODO: ask the user to enter "Y" or "N" on the console?
753 #endif // __WXMSW__/!__WXMSW__
755 // continue with the asserts
759 // show the assert modal dialog
761 void ShowAssertDialog(const wxChar
*szFile
,
763 const wxChar
*szFunc
,
764 const wxChar
*szCond
,
768 // this variable can be set to true to suppress "assert failure" messages
769 static bool s_bNoAsserts
= false;
774 // make life easier for people using VC++ IDE by using this format: like
775 // this, clicking on the message will take us immediately to the place of
777 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
779 // add the function name, if any
780 if ( szFunc
&& *szFunc
)
781 msg
<< _T(" in ") << szFunc
<< _T("()");
783 // and the message itself
786 msg
<< _T(": ") << szMsg
;
788 else // no message given
794 // if we are not in the main thread, output the assert directly and trap
795 // since dialogs cannot be displayed
796 if ( !wxThread::IsMain() )
798 msg
+= wxT(" [in child thread]");
800 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
802 OutputDebugString(msg
);
805 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
808 // He-e-e-e-elp!! we're asserting in a child thread
812 #endif // wxUSE_THREADS
816 // send it to the normal log destination
817 wxLogDebug(_T("%s"), msg
.c_str());
821 // delegate showing assert dialog (if possible) to that class
822 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
824 else // no traits object
826 // fall back to the function of last resort
827 s_bNoAsserts
= DoShowAssertDialog(msg
);
832 #endif // __WXDEBUG__