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 wxLayoutDirection
wxAppConsole::GetLayoutDirection() const
221 const wxLocale
*const locale
= wxGetLocale();
224 const wxLanguageInfo
*const
225 info
= wxLocale::GetLanguageInfo(locale
->GetLanguage());
228 return info
->LayoutDirection
;
233 return wxLayout_Default
;
236 // ----------------------------------------------------------------------------
238 // ----------------------------------------------------------------------------
240 wxAppTraits
*wxAppConsole::CreateTraits()
242 return new wxConsoleAppTraits
;
245 wxAppTraits
*wxAppConsole::GetTraits()
247 // FIXME-MT: protect this with a CS?
250 m_traits
= CreateTraits();
252 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
258 // we must implement CreateXXX() in wxApp itself for backwards compatibility
259 #if WXWIN_COMPATIBILITY_2_4
263 wxLog
*wxAppConsole::CreateLogTarget()
265 wxAppTraits
*traits
= GetTraits();
266 return traits
? traits
->CreateLogTarget() : NULL
;
271 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
273 wxAppTraits
*traits
= GetTraits();
274 return traits
? traits
->CreateMessageOutput() : NULL
;
277 #endif // WXWIN_COMPATIBILITY_2_4
279 // ----------------------------------------------------------------------------
281 // ----------------------------------------------------------------------------
283 void wxAppConsole::ProcessPendingEvents()
286 if ( !wxPendingEventsLocker
)
290 // ensure that we're the only thread to modify the pending events list
291 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
293 if ( !wxPendingEvents
)
295 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
299 // iterate until the list becomes empty
300 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
303 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
304 wxPendingEvents
->Erase(node
);
306 // In ProcessPendingEvents(), new handlers might be add
307 // and we can safely leave the critical section here.
308 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
310 handler
->ProcessPendingEvents();
312 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
314 node
= wxPendingEvents
->GetFirst();
317 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
320 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
322 // process the events normally by default
326 // ----------------------------------------------------------------------------
327 // exception handling
328 // ----------------------------------------------------------------------------
333 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
334 wxEventFunction func
,
335 wxEvent
& event
) const
337 // by default, simply call the handler
338 (handler
->*func
)(event
);
341 #endif // wxUSE_EXCEPTIONS
343 // ----------------------------------------------------------------------------
345 // ----------------------------------------------------------------------------
347 #if wxUSE_CMDLINE_PARSER
349 #define OPTION_VERBOSE _T("verbose")
351 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
353 // the standard command line options
354 static const wxCmdLineEntryDesc cmdLineDesc
[] =
360 gettext_noop("show this help message"),
362 wxCMD_LINE_OPTION_HELP
370 gettext_noop("generate verbose log messages"),
387 parser
.SetDesc(cmdLineDesc
);
390 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
393 if ( parser
.Found(OPTION_VERBOSE
) )
395 wxLog::SetVerbose(true);
404 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
411 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
418 #endif // wxUSE_CMDLINE_PARSER
420 // ----------------------------------------------------------------------------
422 // ----------------------------------------------------------------------------
425 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
426 const char *componentName
)
428 #if 0 // can't use wxLogTrace, not up and running yet
429 printf("checking build options object '%s' (ptr %p) in '%s'\n",
430 optionsSignature
, optionsSignature
, componentName
);
433 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
435 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
436 wxString prog
= wxString::FromAscii(optionsSignature
);
437 wxString progName
= wxString::FromAscii(componentName
);
440 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
441 lib
.c_str(), progName
.c_str(), prog
.c_str());
443 wxLogFatalError(msg
.c_str());
445 // normally wxLogFatalError doesn't return
455 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
461 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
464 void wxAppConsole::OnAssert(const wxChar
*file
,
469 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
472 #endif // __WXDEBUG__
474 #if WXWIN_COMPATIBILITY_2_4
476 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
478 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
483 // ============================================================================
484 // other classes implementations
485 // ============================================================================
487 // ----------------------------------------------------------------------------
488 // wxConsoleAppTraitsBase
489 // ----------------------------------------------------------------------------
493 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
495 return new wxLogStderr
;
500 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
502 return new wxMessageOutputStderr
;
507 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
509 return (wxFontMapper
*)new wxFontMapperBase
;
512 #endif // wxUSE_FONTMAP
514 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
516 // console applications don't use renderers
521 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
523 return wxAppTraitsBase::ShowAssertDialog(msg
);
527 bool wxConsoleAppTraitsBase::HasStderr()
529 // console applications always have stderr, even under Mac/Windows
533 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
538 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
544 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
550 // ----------------------------------------------------------------------------
552 // ----------------------------------------------------------------------------
556 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
558 return DoShowAssertDialog(msg
);
561 #endif // __WXDEBUG__
563 // ============================================================================
564 // global functions implementation
565 // ============================================================================
575 // what else can we do?
584 wxTheApp
->WakeUpIdle();
586 //else: do nothing, what can we do?
592 bool wxAssertIsEqual(int x
, int y
)
597 // break into the debugger
600 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
602 #elif defined(__WXMAC__) && !defined(__DARWIN__)
608 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
610 #elif defined(__UNIX__)
617 // this function is called when an assert fails
618 void wxOnAssert(const wxChar
*szFile
,
621 const wxChar
*szCond
,
625 static bool s_bInAssert
= false;
629 // He-e-e-e-elp!! we're trapped in endless loop
639 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
640 const wxString strFunc
= wxString::FromAscii(szFunc
);
644 // by default, show the assert dialog box -- we can't customize this
646 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
650 // let the app process it as it wants
651 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
657 #endif // __WXDEBUG__
659 // ============================================================================
660 // private functions implementation
661 // ============================================================================
665 static void LINKAGEMODE
SetTraceMasks()
669 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
671 wxStringTokenizer
tkn(mask
, wxT(",;:"));
672 while ( tkn
.HasMoreTokens() )
673 wxLog::AddTraceMask(tkn
.GetNextToken());
678 bool DoShowAssertDialog(const wxString
& msg
)
680 // under MSW we can show the dialog even in the console mode
681 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
682 wxString
msgDlg(msg
);
684 // this message is intentionally not translated -- it is for
686 msgDlg
+= wxT("\nDo you want to stop the program?\n")
687 wxT("You can also choose [Cancel] to suppress ")
688 wxT("further warnings.");
690 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
691 MB_YESNOCANCEL
| MB_ICONSTOP
) )
701 //case IDNO: nothing to do
704 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
707 // TODO: ask the user to enter "Y" or "N" on the console?
709 #endif // __WXMSW__/!__WXMSW__
711 // continue with the asserts
715 #if wxUSE_STACKWALKER
716 static wxString
GetAssertStackTrace()
720 class StackDump
: public wxStackWalker
725 const wxString
& GetStackTrace() const { return m_stackTrace
; }
728 virtual void OnStackFrame(const wxStackFrame
& frame
)
730 m_stackTrace
<< wxString::Format
733 wx_truncate_cast(int, frame
.GetLevel())
736 wxString name
= frame
.GetName();
739 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
743 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
746 if ( frame
.HasSourceLocation() )
748 m_stackTrace
<< _T('\t')
749 << frame
.GetFileName()
754 m_stackTrace
<< _T('\n');
758 wxString m_stackTrace
;
762 dump
.Walk(2); // don't show OnAssert() call itself
763 stackTrace
= dump
.GetStackTrace();
765 // don't show more than maxLines or we could get a dialog too tall to be
766 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
767 // characters it is still only 300 pixels...
768 static const int maxLines
= 20;
769 const int count
= stackTrace
.Freq(wxT('\n'));
770 for ( int i
= 0; i
< count
- maxLines
; i
++ )
771 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
775 #endif // wxUSE_STACKWALKER
777 // show the assert modal dialog
779 void ShowAssertDialog(const wxChar
*szFile
,
781 const wxChar
*szFunc
,
782 const wxChar
*szCond
,
786 // this variable can be set to true to suppress "assert failure" messages
787 static bool s_bNoAsserts
= false;
792 // make life easier for people using VC++ IDE by using this format: like
793 // this, clicking on the message will take us immediately to the place of
795 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
797 // add the function name, if any
798 if ( szFunc
&& *szFunc
)
799 msg
<< _T(" in ") << szFunc
<< _T("()");
801 // and the message itself
804 msg
<< _T(": ") << szMsg
;
806 else // no message given
811 #if wxUSE_STACKWALKER
812 const wxString stackTrace
= GetAssertStackTrace();
813 if ( !stackTrace
.empty() )
815 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
817 #endif // wxUSE_STACKWALKER
820 // if we are not in the main thread, output the assert directly and trap
821 // since dialogs cannot be displayed
822 if ( !wxThread::IsMain() )
824 msg
+= wxT(" [in child thread]");
826 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
828 OutputDebugString(msg
);
831 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
834 // He-e-e-e-elp!! we're asserting in a child thread
838 #endif // wxUSE_THREADS
842 // send it to the normal log destination
843 wxLogDebug(_T("%s"), msg
.c_str());
847 // delegate showing assert dialog (if possible) to that class
848 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
850 else // no traits object
852 // fall back to the function of last resort
853 s_bNoAsserts
= DoShowAssertDialog(msg
);
858 #endif // __WXDEBUG__