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 wxLayoutDirection
wxAppConsole::GetLayoutDirection() const
222 const wxLocale
*const locale
= wxGetLocale();
225 const wxLanguageInfo
*const
226 info
= wxLocale::GetLanguageInfo(locale
->GetLanguage());
229 return info
->LayoutDirection
;
234 return wxLayout_Default
;
237 // ----------------------------------------------------------------------------
239 // ----------------------------------------------------------------------------
241 wxAppTraits
*wxAppConsole::CreateTraits()
243 return new wxConsoleAppTraits
;
246 wxAppTraits
*wxAppConsole::GetTraits()
248 // FIXME-MT: protect this with a CS?
251 m_traits
= CreateTraits();
253 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
259 // we must implement CreateXXX() in wxApp itself for backwards compatibility
260 #if WXWIN_COMPATIBILITY_2_4
264 wxLog
*wxAppConsole::CreateLogTarget()
266 wxAppTraits
*traits
= GetTraits();
267 return traits
? traits
->CreateLogTarget() : NULL
;
272 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
274 wxAppTraits
*traits
= GetTraits();
275 return traits
? traits
->CreateMessageOutput() : NULL
;
278 #endif // WXWIN_COMPATIBILITY_2_4
280 // ----------------------------------------------------------------------------
282 // ----------------------------------------------------------------------------
284 void wxAppConsole::ProcessPendingEvents()
287 if ( !wxPendingEventsLocker
)
291 // ensure that we're the only thread to modify the pending events list
292 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
294 if ( !wxPendingEvents
)
296 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
300 // iterate until the list becomes empty
301 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
304 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
305 wxPendingEvents
->Erase(node
);
307 // In ProcessPendingEvents(), new handlers might be add
308 // and we can safely leave the critical section here.
309 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
311 handler
->ProcessPendingEvents();
313 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
315 node
= wxPendingEvents
->GetFirst();
318 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
321 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
323 // process the events normally by default
327 // ----------------------------------------------------------------------------
328 // exception handling
329 // ----------------------------------------------------------------------------
334 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
335 wxEventFunction func
,
336 wxEvent
& event
) const
338 // by default, simply call the handler
339 (handler
->*func
)(event
);
342 #endif // wxUSE_EXCEPTIONS
344 // ----------------------------------------------------------------------------
346 // ----------------------------------------------------------------------------
348 #if wxUSE_CMDLINE_PARSER
350 #define OPTION_VERBOSE _T("verbose")
352 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
354 // the standard command line options
355 static const wxCmdLineEntryDesc cmdLineDesc
[] =
361 gettext_noop("show this help message"),
363 wxCMD_LINE_OPTION_HELP
371 gettext_noop("generate verbose log messages"),
388 parser
.SetDesc(cmdLineDesc
);
391 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
394 if ( parser
.Found(OPTION_VERBOSE
) )
396 wxLog::SetVerbose(true);
405 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
412 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
419 #endif // wxUSE_CMDLINE_PARSER
421 // ----------------------------------------------------------------------------
423 // ----------------------------------------------------------------------------
426 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
427 const char *componentName
)
429 #if 0 // can't use wxLogTrace, not up and running yet
430 printf("checking build options object '%s' (ptr %p) in '%s'\n",
431 optionsSignature
, optionsSignature
, componentName
);
434 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
436 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
437 wxString prog
= wxString::FromAscii(optionsSignature
);
438 wxString progName
= wxString::FromAscii(componentName
);
441 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
442 lib
.c_str(), progName
.c_str(), prog
.c_str());
444 wxLogFatalError(msg
.c_str());
446 // normally wxLogFatalError doesn't return
456 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
462 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
465 void wxAppConsole::OnAssert(const wxChar
*file
,
470 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
473 #endif // __WXDEBUG__
475 #if WXWIN_COMPATIBILITY_2_4
477 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
479 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
484 // ============================================================================
485 // other classes implementations
486 // ============================================================================
488 // ----------------------------------------------------------------------------
489 // wxConsoleAppTraitsBase
490 // ----------------------------------------------------------------------------
494 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
496 return new wxLogStderr
;
501 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
503 return new wxMessageOutputStderr
;
508 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
510 return (wxFontMapper
*)new wxFontMapperBase
;
513 #endif // wxUSE_FONTMAP
515 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
517 // console applications don't use renderers
522 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
524 return wxAppTraitsBase::ShowAssertDialog(msg
);
528 bool wxConsoleAppTraitsBase::HasStderr()
530 // console applications always have stderr, even under Mac/Windows
534 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
539 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
545 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
551 // ----------------------------------------------------------------------------
553 // ----------------------------------------------------------------------------
557 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
559 return DoShowAssertDialog(msg
);
562 #endif // __WXDEBUG__
564 // ============================================================================
565 // global functions implementation
566 // ============================================================================
576 // what else can we do?
585 wxTheApp
->WakeUpIdle();
587 //else: do nothing, what can we do?
593 bool wxAssertIsEqual(int x
, int y
)
598 // break into the debugger
601 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
603 #elif defined(__WXMAC__) && !defined(__DARWIN__)
609 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
611 #elif defined(__UNIX__)
618 // this function is called when an assert fails
619 void wxOnAssert(const wxChar
*szFile
,
622 const wxChar
*szCond
,
626 static bool s_bInAssert
= false;
630 // He-e-e-e-elp!! we're trapped in endless loop
640 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
641 const wxString strFunc
= wxString::FromAscii(szFunc
);
645 // by default, show the assert dialog box -- we can't customize this
647 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
651 // let the app process it as it wants
652 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
658 #endif // __WXDEBUG__
660 // ============================================================================
661 // private functions implementation
662 // ============================================================================
666 static void LINKAGEMODE
SetTraceMasks()
670 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
672 wxStringTokenizer
tkn(mask
, wxT(",;:"));
673 while ( tkn
.HasMoreTokens() )
674 wxLog::AddTraceMask(tkn
.GetNextToken());
679 bool DoShowAssertDialog(const wxString
& msg
)
681 // under MSW we can show the dialog even in the console mode
682 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
683 wxString
msgDlg(msg
);
685 // this message is intentionally not translated -- it is for
687 msgDlg
+= wxT("\nDo you want to stop the program?\n")
688 wxT("You can also choose [Cancel] to suppress ")
689 wxT("further warnings.");
691 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
692 MB_YESNOCANCEL
| MB_ICONSTOP
) )
702 //case IDNO: nothing to do
705 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
708 // TODO: ask the user to enter "Y" or "N" on the console?
710 #endif // __WXMSW__/!__WXMSW__
712 // continue with the asserts
716 #if wxUSE_STACKWALKER
717 static wxString
GetAssertStackTrace()
721 class StackDump
: public wxStackWalker
726 const wxString
& GetStackTrace() const { return m_stackTrace
; }
729 virtual void OnStackFrame(const wxStackFrame
& frame
)
731 m_stackTrace
<< wxString::Format
734 wx_truncate_cast(int, frame
.GetLevel())
737 wxString name
= frame
.GetName();
740 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
744 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
747 if ( frame
.HasSourceLocation() )
749 m_stackTrace
<< _T('\t')
750 << frame
.GetFileName()
755 m_stackTrace
<< _T('\n');
759 wxString m_stackTrace
;
763 dump
.Walk(2); // don't show OnAssert() call itself
764 stackTrace
= dump
.GetStackTrace();
766 // don't show more than maxLines or we could get a dialog too tall to be
767 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
768 // characters it is still only 300 pixels...
769 static const int maxLines
= 20;
770 const int count
= stackTrace
.Freq(wxT('\n'));
771 for ( int i
= 0; i
< count
- maxLines
; i
++ )
772 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
776 #endif // wxUSE_STACKWALKER
778 // show the assert modal dialog
780 void ShowAssertDialog(const wxChar
*szFile
,
782 const wxChar
*szFunc
,
783 const wxChar
*szCond
,
787 // this variable can be set to true to suppress "assert failure" messages
788 static bool s_bNoAsserts
= false;
793 // make life easier for people using VC++ IDE by using this format: like
794 // this, clicking on the message will take us immediately to the place of
796 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
798 // add the function name, if any
799 if ( szFunc
&& *szFunc
)
800 msg
<< _T(" in ") << szFunc
<< _T("()");
802 // and the message itself
805 msg
<< _T(": ") << szMsg
;
807 else // no message given
812 #if wxUSE_STACKWALKER
813 const wxString stackTrace
= GetAssertStackTrace();
814 if ( !stackTrace
.empty() )
816 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
818 #endif // wxUSE_STACKWALKER
821 // if we are not in the main thread, output the assert directly and trap
822 // since dialogs cannot be displayed
823 if ( !wxThread::IsMain() )
825 msg
+= wxT(" [in child thread]");
827 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
829 OutputDebugString(msg
);
832 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
835 // He-e-e-e-elp!! we're asserting in a child thread
839 #endif // wxUSE_THREADS
843 // send it to the normal log destination
844 wxLogDebug(_T("%s"), msg
.c_str());
848 // delegate showing assert dialog (if possible) to that class
849 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
851 else // no traits object
853 // fall back to the function of last resort
854 s_bNoAsserts
= DoShowAssertDialog(msg
);
859 #endif // __WXDEBUG__