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
*)node
->GetData())->IsEventHandlingInProgress() &&
304 ((wxEvtHandler
*)node
->GetData())->IsReentranceAllowed() == false)
307 node
= node
->GetNext();
312 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
313 wxPendingEvents
->Erase(node
);
315 // In ProcessPendingEvents(), new handlers might be add
316 // and we can safely leave the critical section here.
317 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
319 handler
->ProcessPendingEvents();
321 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
323 node
= wxPendingEvents
->GetFirst();
326 ((wxEvtHandler
*)node
->GetData())->IsEventHandlingInProgress() &&
327 ((wxEvtHandler
*)node
->GetData())->IsReentranceAllowed() == false)
330 node
= node
->GetNext();
334 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
337 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
339 // process the events normally by default
343 // ----------------------------------------------------------------------------
344 // exception handling
345 // ----------------------------------------------------------------------------
350 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
351 wxEventFunction func
,
352 wxEvent
& event
) const
354 // by default, simply call the handler
355 (handler
->*func
)(event
);
358 #endif // wxUSE_EXCEPTIONS
360 // ----------------------------------------------------------------------------
362 // ----------------------------------------------------------------------------
364 #if wxUSE_CMDLINE_PARSER
366 #define OPTION_VERBOSE _T("verbose")
368 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
370 // the standard command line options
371 static const wxCmdLineEntryDesc cmdLineDesc
[] =
377 gettext_noop("show this help message"),
379 wxCMD_LINE_OPTION_HELP
387 gettext_noop("generate verbose log messages"),
404 parser
.SetDesc(cmdLineDesc
);
407 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
410 if ( parser
.Found(OPTION_VERBOSE
) )
412 wxLog::SetVerbose(true);
421 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
428 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
435 #endif // wxUSE_CMDLINE_PARSER
437 // ----------------------------------------------------------------------------
439 // ----------------------------------------------------------------------------
442 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
443 const char *componentName
)
445 #if 0 // can't use wxLogTrace, not up and running yet
446 printf("checking build options object '%s' (ptr %p) in '%s'\n",
447 optionsSignature
, optionsSignature
, componentName
);
450 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
452 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
453 wxString prog
= wxString::FromAscii(optionsSignature
);
454 wxString progName
= wxString::FromAscii(componentName
);
457 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
458 lib
.c_str(), progName
.c_str(), prog
.c_str());
460 wxLogFatalError(msg
.c_str());
462 // normally wxLogFatalError doesn't return
472 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
478 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
481 void wxAppConsole::OnAssert(const wxChar
*file
,
486 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
489 #endif // __WXDEBUG__
491 #if WXWIN_COMPATIBILITY_2_4
493 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
495 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
500 // ============================================================================
501 // other classes implementations
502 // ============================================================================
504 // ----------------------------------------------------------------------------
505 // wxConsoleAppTraitsBase
506 // ----------------------------------------------------------------------------
510 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
512 return new wxLogStderr
;
517 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
519 return new wxMessageOutputStderr
;
524 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
526 return (wxFontMapper
*)new wxFontMapperBase
;
529 #endif // wxUSE_FONTMAP
531 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
533 // console applications don't use renderers
538 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
540 return wxAppTraitsBase::ShowAssertDialog(msg
);
544 bool wxConsoleAppTraitsBase::HasStderr()
546 // console applications always have stderr, even under Mac/Windows
550 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
555 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
561 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
567 // ----------------------------------------------------------------------------
569 // ----------------------------------------------------------------------------
573 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
575 return DoShowAssertDialog(msg
);
578 #endif // __WXDEBUG__
580 // ============================================================================
581 // global functions implementation
582 // ============================================================================
592 // what else can we do?
601 wxTheApp
->WakeUpIdle();
603 //else: do nothing, what can we do?
609 bool wxAssertIsEqual(int x
, int y
)
614 // break into the debugger
617 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
619 #elif defined(__WXMAC__) && !defined(__DARWIN__)
625 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
627 #elif defined(__UNIX__)
634 // this function is called when an assert fails
635 void wxOnAssert(const wxChar
*szFile
,
638 const wxChar
*szCond
,
642 static bool s_bInAssert
= false;
646 // He-e-e-e-elp!! we're trapped in endless loop
656 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
657 const wxString strFunc
= wxString::FromAscii(szFunc
);
661 // by default, show the assert dialog box -- we can't customize this
663 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
667 // let the app process it as it wants
668 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
674 #endif // __WXDEBUG__
676 // ============================================================================
677 // private functions implementation
678 // ============================================================================
682 static void LINKAGEMODE
SetTraceMasks()
686 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
688 wxStringTokenizer
tkn(mask
, wxT(",;:"));
689 while ( tkn
.HasMoreTokens() )
690 wxLog::AddTraceMask(tkn
.GetNextToken());
695 bool DoShowAssertDialog(const wxString
& msg
)
697 // under MSW we can show the dialog even in the console mode
698 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
699 wxString
msgDlg(msg
);
701 // this message is intentionally not translated -- it is for
703 msgDlg
+= wxT("\nDo you want to stop the program?\n")
704 wxT("You can also choose [Cancel] to suppress ")
705 wxT("further warnings.");
707 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
708 MB_YESNOCANCEL
| MB_ICONSTOP
) )
718 //case IDNO: nothing to do
721 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
724 // TODO: ask the user to enter "Y" or "N" on the console?
726 #endif // __WXMSW__/!__WXMSW__
728 // continue with the asserts
732 #if wxUSE_STACKWALKER
733 static wxString
GetAssertStackTrace()
737 class StackDump
: public wxStackWalker
742 const wxString
& GetStackTrace() const { return m_stackTrace
; }
745 virtual void OnStackFrame(const wxStackFrame
& frame
)
747 m_stackTrace
<< wxString::Format
750 wx_truncate_cast(int, frame
.GetLevel())
753 wxString name
= frame
.GetName();
756 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
760 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
763 if ( frame
.HasSourceLocation() )
765 m_stackTrace
<< _T('\t')
766 << frame
.GetFileName()
771 m_stackTrace
<< _T('\n');
775 wxString m_stackTrace
;
779 dump
.Walk(2); // don't show OnAssert() call itself
780 stackTrace
= dump
.GetStackTrace();
782 // don't show more than maxLines or we could get a dialog too tall to be
783 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
784 // characters it is still only 300 pixels...
785 static const int maxLines
= 20;
786 const int count
= stackTrace
.Freq(wxT('\n'));
787 for ( int i
= 0; i
< count
- maxLines
; i
++ )
788 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
792 #endif // wxUSE_STACKWALKER
794 // show the assert modal dialog
796 void ShowAssertDialog(const wxChar
*szFile
,
798 const wxChar
*szFunc
,
799 const wxChar
*szCond
,
803 // this variable can be set to true to suppress "assert failure" messages
804 static bool s_bNoAsserts
= false;
809 // make life easier for people using VC++ IDE by using this format: like
810 // this, clicking on the message will take us immediately to the place of
812 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
814 // add the function name, if any
815 if ( szFunc
&& *szFunc
)
816 msg
<< _T(" in ") << szFunc
<< _T("()");
818 // and the message itself
821 msg
<< _T(": ") << szMsg
;
823 else // no message given
828 #if wxUSE_STACKWALKER
829 const wxString stackTrace
= GetAssertStackTrace();
830 if ( !stackTrace
.empty() )
832 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
834 #endif // wxUSE_STACKWALKER
837 // if we are not in the main thread, output the assert directly and trap
838 // since dialogs cannot be displayed
839 if ( !wxThread::IsMain() )
841 msg
+= wxT(" [in child thread]");
843 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
845 OutputDebugString(msg
);
848 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
851 // He-e-e-e-elp!! we're asserting in a child thread
855 #endif // wxUSE_THREADS
859 // send it to the normal log destination
860 wxLogDebug(_T("%s"), msg
.c_str());
864 // delegate showing assert dialog (if possible) to that class
865 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
867 else // no traits object
869 // fall back to the function of last resort
870 s_bNoAsserts
= DoShowAssertDialog(msg
);
875 #endif // __WXDEBUG__