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 // we must implement CreateXXX() in wxApp itself for backwards compatibility
241 #if WXWIN_COMPATIBILITY_2_4
245 wxLog
*wxAppConsole::CreateLogTarget()
247 wxAppTraits
*traits
= GetTraits();
248 return traits
? traits
->CreateLogTarget() : NULL
;
253 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
255 wxAppTraits
*traits
= GetTraits();
256 return traits
? traits
->CreateMessageOutput() : NULL
;
259 #endif // WXWIN_COMPATIBILITY_2_4
261 // ----------------------------------------------------------------------------
263 // ----------------------------------------------------------------------------
265 void wxAppConsole::ProcessPendingEvents()
268 if ( !wxPendingEventsLocker
)
272 // ensure that we're the only thread to modify the pending events list
273 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
275 if ( !wxPendingEvents
)
277 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
281 // iterate until the list becomes empty
282 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
285 ((wxEvtHandler
*)node
->GetData())->IsEventHandlingInProgress() &&
286 ((wxEvtHandler
*)node
->GetData())->IsReentranceAllowed() == false)
289 node
= node
->GetNext();
294 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
295 wxPendingEvents
->Erase(node
);
297 // In ProcessPendingEvents(), new handlers might be add
298 // and we can safely leave the critical section here.
299 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
301 handler
->ProcessPendingEvents();
303 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
305 node
= wxPendingEvents
->GetFirst();
308 ((wxEvtHandler
*)node
->GetData())->IsEventHandlingInProgress() &&
309 ((wxEvtHandler
*)node
->GetData())->IsReentranceAllowed() == false)
312 node
= node
->GetNext();
316 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
319 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
321 // process the events normally by default
325 // ----------------------------------------------------------------------------
326 // exception handling
327 // ----------------------------------------------------------------------------
332 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
333 wxEventFunction func
,
334 wxEvent
& event
) const
336 // by default, simply call the handler
337 (handler
->*func
)(event
);
340 #endif // wxUSE_EXCEPTIONS
342 // ----------------------------------------------------------------------------
344 // ----------------------------------------------------------------------------
346 #if wxUSE_CMDLINE_PARSER
348 #define OPTION_VERBOSE _T("verbose")
350 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
352 // the standard command line options
353 static const wxCmdLineEntryDesc cmdLineDesc
[] =
359 gettext_noop("show this help message"),
361 wxCMD_LINE_OPTION_HELP
369 gettext_noop("generate verbose log messages"),
386 parser
.SetDesc(cmdLineDesc
);
389 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
392 if ( parser
.Found(OPTION_VERBOSE
) )
394 wxLog::SetVerbose(true);
403 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
410 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
417 #endif // wxUSE_CMDLINE_PARSER
419 // ----------------------------------------------------------------------------
421 // ----------------------------------------------------------------------------
424 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
425 const char *componentName
)
427 #if 0 // can't use wxLogTrace, not up and running yet
428 printf("checking build options object '%s' (ptr %p) in '%s'\n",
429 optionsSignature
, optionsSignature
, componentName
);
432 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
434 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
435 wxString prog
= wxString::FromAscii(optionsSignature
);
436 wxString progName
= wxString::FromAscii(componentName
);
439 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
440 lib
.c_str(), progName
.c_str(), prog
.c_str());
442 wxLogFatalError(msg
.c_str());
444 // normally wxLogFatalError doesn't return
454 void wxAppConsole::OnAssertFailure(const wxChar
*file
,
460 ShowAssertDialog(file
, line
, func
, cond
, msg
, GetTraits());
463 void wxAppConsole::OnAssert(const wxChar
*file
,
468 OnAssertFailure(file
, line
, NULL
, cond
, msg
);
471 #endif // __WXDEBUG__
473 #if WXWIN_COMPATIBILITY_2_4
475 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
477 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
482 // ============================================================================
483 // other classes implementations
484 // ============================================================================
486 // ----------------------------------------------------------------------------
487 // wxConsoleAppTraitsBase
488 // ----------------------------------------------------------------------------
492 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
494 return new wxLogStderr
;
499 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
501 return new wxMessageOutputStderr
;
506 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
508 return (wxFontMapper
*)new wxFontMapperBase
;
511 #endif // wxUSE_FONTMAP
513 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
515 // console applications don't use renderers
520 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
522 return wxAppTraitsBase::ShowAssertDialog(msg
);
526 bool wxConsoleAppTraitsBase::HasStderr()
528 // console applications always have stderr, even under Mac/Windows
532 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
537 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
543 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
549 // ----------------------------------------------------------------------------
551 // ----------------------------------------------------------------------------
555 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
557 return DoShowAssertDialog(msg
);
560 #endif // __WXDEBUG__
562 // ============================================================================
563 // global functions implementation
564 // ============================================================================
574 // what else can we do?
583 wxTheApp
->WakeUpIdle();
585 //else: do nothing, what can we do?
591 bool wxAssertIsEqual(int x
, int y
)
596 // break into the debugger
599 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
601 #elif defined(__WXMAC__) && !defined(__DARWIN__)
607 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
609 #elif defined(__UNIX__)
616 // this function is called when an assert fails
617 void wxOnAssert(const wxChar
*szFile
,
620 const wxChar
*szCond
,
624 static bool s_bInAssert
= false;
628 // He-e-e-e-elp!! we're trapped in endless loop
638 // __FUNCTION__ is always in ASCII, convert it to wide char if needed
639 const wxString strFunc
= wxString::FromAscii(szFunc
);
643 // by default, show the assert dialog box -- we can't customize this
645 ShowAssertDialog(szFile
, nLine
, strFunc
, szCond
, szMsg
);
649 // let the app process it as it wants
650 wxTheApp
->OnAssertFailure(szFile
, nLine
, strFunc
, szCond
, szMsg
);
656 #endif // __WXDEBUG__
658 // ============================================================================
659 // private functions implementation
660 // ============================================================================
664 static void LINKAGEMODE
SetTraceMasks()
668 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
670 wxStringTokenizer
tkn(mask
, wxT(",;:"));
671 while ( tkn
.HasMoreTokens() )
672 wxLog::AddTraceMask(tkn
.GetNextToken());
677 bool DoShowAssertDialog(const wxString
& msg
)
679 // under MSW we can show the dialog even in the console mode
680 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
681 wxString
msgDlg(msg
);
683 // this message is intentionally not translated -- it is for
685 msgDlg
+= wxT("\nDo you want to stop the program?\n")
686 wxT("You can also choose [Cancel] to suppress ")
687 wxT("further warnings.");
689 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
690 MB_YESNOCANCEL
| MB_ICONSTOP
) )
700 //case IDNO: nothing to do
703 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
706 // TODO: ask the user to enter "Y" or "N" on the console?
708 #endif // __WXMSW__/!__WXMSW__
710 // continue with the asserts
714 #if wxUSE_STACKWALKER
715 static wxString
GetAssertStackTrace()
719 class StackDump
: public wxStackWalker
724 const wxString
& GetStackTrace() const { return m_stackTrace
; }
727 virtual void OnStackFrame(const wxStackFrame
& frame
)
729 m_stackTrace
<< wxString::Format
732 wx_truncate_cast(int, frame
.GetLevel())
735 wxString name
= frame
.GetName();
738 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
742 m_stackTrace
<< wxString::Format(_T("%p"), frame
.GetAddress());
745 if ( frame
.HasSourceLocation() )
747 m_stackTrace
<< _T('\t')
748 << frame
.GetFileName()
753 m_stackTrace
<< _T('\n');
757 wxString m_stackTrace
;
761 dump
.Walk(2); // don't show OnAssert() call itself
762 stackTrace
= dump
.GetStackTrace();
764 // don't show more than maxLines or we could get a dialog too tall to be
765 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
766 // characters it is still only 300 pixels...
767 static const int maxLines
= 20;
768 const int count
= stackTrace
.Freq(wxT('\n'));
769 for ( int i
= 0; i
< count
- maxLines
; i
++ )
770 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
774 #endif // wxUSE_STACKWALKER
776 // show the assert modal dialog
778 void ShowAssertDialog(const wxChar
*szFile
,
780 const wxChar
*szFunc
,
781 const wxChar
*szCond
,
785 // this variable can be set to true to suppress "assert failure" messages
786 static bool s_bNoAsserts
= false;
791 // make life easier for people using VC++ IDE by using this format: like
792 // this, clicking on the message will take us immediately to the place of
794 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
796 // add the function name, if any
797 if ( szFunc
&& *szFunc
)
798 msg
<< _T(" in ") << szFunc
<< _T("()");
800 // and the message itself
803 msg
<< _T(": ") << szMsg
;
805 else // no message given
810 #if wxUSE_STACKWALKER
811 const wxString stackTrace
= GetAssertStackTrace();
812 if ( !stackTrace
.empty() )
814 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
816 #endif // wxUSE_STACKWALKER
819 // if we are not in the main thread, output the assert directly and trap
820 // since dialogs cannot be displayed
821 if ( !wxThread::IsMain() )
823 msg
+= wxT(" [in child thread]");
825 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
827 OutputDebugString(msg
);
830 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
833 // He-e-e-e-elp!! we're asserting in a child thread
837 #endif // wxUSE_THREADS
841 // send it to the normal log destination
842 wxLogDebug(_T("%s"), msg
.c_str());
846 // delegate showing assert dialog (if possible) to that class
847 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
849 else // no traits object
851 // fall back to the function of last resort
852 s_bNoAsserts
= DoShowAssertDialog(msg
);
857 #endif // __WXDEBUG__