1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: common/base/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__)
60 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
61 // I don't know which headers are needed under earlier systems so
62 // include everything when in doubt
66 #include "wx/mac/private.h" // includes mac headers
72 #include "wx/stackwalk.h"
74 #include "wx/msw/debughlp.h"
76 #endif // wxUSE_STACKWALKER
79 // ----------------------------------------------------------------------------
80 // private functions prototypes
81 // ----------------------------------------------------------------------------
84 // really just show the assert dialog
85 static bool DoShowAssertDialog(const wxString
& msg
);
87 // prepare for showing the assert dialog, use the given traits or
88 // DoShowAssertDialog() as last fallback to really show it
90 void ShowAssertDialog(const wxChar
*szFile
,
94 wxAppTraits
*traits
= NULL
);
96 // turn on the trace masks specified in the env variable WXTRACE
97 static void LINKAGEMODE
SetTraceMasks();
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
104 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
106 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
108 // ============================================================================
109 // wxAppConsole implementation
110 // ============================================================================
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 wxAppConsole::wxAppConsole()
120 ms_appInstance
= this;
125 // In unicode mode the SetTraceMasks call can cause an apptraits to be
126 // created, but since we are still in the constructor the wrong kind will
127 // be created for GUI apps. Destroy it so it can be created again later.
134 wxAppConsole::~wxAppConsole()
139 // ----------------------------------------------------------------------------
140 // initilization/cleanup
141 // ----------------------------------------------------------------------------
143 bool wxAppConsole::Initialize(int& argc
, wxChar
**argv
)
146 // If some code logged something before wxApp instance was created,
147 // wxLogStderr was set as the target. Undo it here by destroying the
148 // current target. It will be re-created next time logging is needed, but
149 // this time wxAppTraits will be used:
150 delete wxLog::SetActiveTarget(NULL
);
153 // remember the command line arguments
158 if ( m_appName
.empty() && argv
)
160 // the application name is, by default, the name of its executable file
161 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
168 void wxAppConsole::CleanUp()
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 bool wxAppConsole::OnInit()
178 #if wxUSE_CMDLINE_PARSER
179 wxCmdLineParser
parser(argc
, argv
);
181 OnInitCmdLine(parser
);
184 switch ( parser
.Parse(false /* don't show usage */) )
187 cont
= OnCmdLineHelp(parser
);
191 cont
= OnCmdLineParsed(parser
);
195 cont
= OnCmdLineError(parser
);
201 #endif // wxUSE_CMDLINE_PARSER
206 int wxAppConsole::OnExit()
209 // delete the config object if any (don't use Get() here, but Set()
210 // because Get() could create a new config object)
211 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
212 #endif // wxUSE_CONFIG
214 // use Set(NULL) and not Get() to avoid creating a message output object on
215 // demand when we just want to delete it
216 delete wxMessageOutput::Set(NULL
);
221 void wxAppConsole::Exit()
226 // ----------------------------------------------------------------------------
228 // ----------------------------------------------------------------------------
230 wxAppTraits
*wxAppConsole::CreateTraits()
232 return new wxConsoleAppTraits
;
235 wxAppTraits
*wxAppConsole::GetTraits()
237 // FIXME-MT: protect this with a CS?
240 m_traits
= CreateTraits();
242 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
248 // we must implement CreateXXX() in wxApp itself for backwards compatibility
249 #if WXWIN_COMPATIBILITY_2_4
253 wxLog
*wxAppConsole::CreateLogTarget()
255 wxAppTraits
*traits
= GetTraits();
256 return traits
? traits
->CreateLogTarget() : NULL
;
261 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
263 wxAppTraits
*traits
= GetTraits();
264 return traits
? traits
->CreateMessageOutput() : NULL
;
267 #endif // WXWIN_COMPATIBILITY_2_4
269 // ----------------------------------------------------------------------------
271 // ----------------------------------------------------------------------------
273 void wxAppConsole::ProcessPendingEvents()
276 if ( !wxPendingEventsLocker
)
280 // ensure that we're the only thread to modify the pending events list
281 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
283 if ( !wxPendingEvents
)
285 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
289 // iterate until the list becomes empty
290 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
293 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
294 wxPendingEvents
->Erase(node
);
296 // In ProcessPendingEvents(), new handlers might be add
297 // and we can safely leave the critical section here.
298 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
300 handler
->ProcessPendingEvents();
302 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
304 node
= wxPendingEvents
->GetFirst();
307 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
310 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
312 // process the events normally by default
316 // ----------------------------------------------------------------------------
317 // exception handling
318 // ----------------------------------------------------------------------------
323 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
324 wxEventFunction func
,
325 wxEvent
& event
) const
327 // by default, simply call the handler
328 (handler
->*func
)(event
);
332 wxAppConsole::OnExceptionInMainLoop()
336 // some compilers are too stupid to know that we never return after throw
337 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
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::OnAssert(const wxChar
*file
,
461 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
464 #endif // __WXDEBUG__
466 #if WXWIN_COMPATIBILITY_2_4
468 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions
& buildOptions
)
470 return CheckBuildOptions(buildOptions
.m_signature
, "your program");
475 // ============================================================================
476 // other classes implementations
477 // ============================================================================
479 // ----------------------------------------------------------------------------
480 // wxConsoleAppTraitsBase
481 // ----------------------------------------------------------------------------
485 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
487 return new wxLogStderr
;
492 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
494 return new wxMessageOutputStderr
;
499 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
501 return (wxFontMapper
*)new wxFontMapperBase
;
504 #endif // wxUSE_FONTMAP
506 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
508 // console applications don't use renderers
513 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
515 return wxAppTraitsBase::ShowAssertDialog(msg
);
519 bool wxConsoleAppTraitsBase::HasStderr()
521 // console applications always have stderr, even under Mac/Windows
525 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
530 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
536 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
542 // ----------------------------------------------------------------------------
544 // ----------------------------------------------------------------------------
548 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
550 return DoShowAssertDialog(msg
);
553 #endif // __WXDEBUG__
555 // ============================================================================
556 // global functions implementation
557 // ============================================================================
567 // what else can we do?
576 wxTheApp
->WakeUpIdle();
578 //else: do nothing, what can we do?
584 bool wxAssertIsEqual(int x
, int y
)
589 // break into the debugger
592 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
594 #elif defined(__WXMAC__) && !defined(__DARWIN__)
600 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
602 #elif defined(__UNIX__)
609 void wxAssert(int cond
,
610 const wxChar
*szFile
,
612 const wxChar
*szCond
,
616 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
619 // this function is called when an assert fails
620 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
642 // by default, show the assert dialog box -- we can't customize this
644 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
648 // let the app process it as it wants
649 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
655 #endif // __WXDEBUG__
657 // ============================================================================
658 // private functions implementation
659 // ============================================================================
663 static void LINKAGEMODE
SetTraceMasks()
667 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
669 wxStringTokenizer
tkn(mask
, wxT(",;:"));
670 while ( tkn
.HasMoreTokens() )
671 wxLog::AddTraceMask(tkn
.GetNextToken());
676 bool DoShowAssertDialog(const wxString
& msg
)
678 // under MSW we can show the dialog even in the console mode
679 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
680 wxString
msgDlg(msg
);
682 // this message is intentionally not translated -- it is for
684 msgDlg
+= wxT("\nDo you want to stop the program?\n")
685 wxT("You can also choose [Cancel] to suppress ")
686 wxT("further warnings.");
688 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
689 MB_YESNOCANCEL
| MB_ICONSTOP
) )
699 //case IDNO: nothing to do
702 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
705 // TODO: ask the user to enter "Y" or "N" on the console?
707 #endif // __WXMSW__/!__WXMSW__
709 // continue with the asserts
713 #if wxUSE_STACKWALKER
714 static wxString
GetAssertStackTrace()
719 // check that we can get the stack trace before trying to do it
720 if ( !wxDbgHelpDLL::Init() )
724 class StackDump
: public wxStackWalker
729 const wxString
& GetStackTrace() const { return m_stackTrace
; }
732 virtual void OnStackFrame(const wxStackFrame
& frame
)
734 m_stackTrace
<< wxString::Format(_T("[%02d] "), frame
.GetLevel());
736 wxString name
= frame
.GetName();
739 m_stackTrace
<< wxString::Format(_T("%-40s"), name
.c_str());
743 m_stackTrace
<< wxString::Format
746 (unsigned long)frame
.GetAddress()
750 if ( frame
.HasSourceLocation() )
752 m_stackTrace
<< _T('\t')
753 << frame
.GetFileName()
758 m_stackTrace
<< _T('\n');
762 wxString m_stackTrace
;
766 dump
.Walk(5); // don't show OnAssert() call itself
767 stackTrace
= dump
.GetStackTrace();
769 // don't show more than maxLines or we could get a dialog too tall to be
770 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
771 // characters it is still only 300 pixels...
772 static const int maxLines
= 20;
773 const int count
= stackTrace
.Freq(wxT('\n'));
774 for ( int i
= 0; i
< count
- maxLines
; i
++ )
775 stackTrace
= stackTrace
.BeforeLast(wxT('\n'));
779 #endif // wxUSE_STACKWALKER
781 // show the assert modal dialog
783 void ShowAssertDialog(const wxChar
*szFile
,
785 const wxChar
*szCond
,
789 // this variable can be set to true to suppress "assert failure" messages
790 static bool s_bNoAsserts
= false;
795 // make life easier for people using VC++ IDE by using this format: like
796 // this, clicking on the message will take us immediately to the place of
798 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
802 msg
<< _T(": ") << szMsg
;
804 else // no message given
809 #if wxUSE_STACKWALKER
810 const wxString stackTrace
= GetAssertStackTrace();
811 if ( !stackTrace
.empty() )
813 msg
<< _T("\n\nCall stack:\n") << stackTrace
;
815 #endif // wxUSE_STACKWALKER
818 // if we are not in the main thread, output the assert directly and trap
819 // since dialogs cannot be displayed
820 if ( !wxThread::IsMain() )
822 msg
+= wxT(" [in child thread]");
824 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
826 OutputDebugString(msg
);
829 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
832 // He-e-e-e-elp!! we're asserting in a child thread
836 #endif // wxUSE_THREADS
840 // send it to the normal log destination
841 wxLogDebug(_T("%s"), msg
.c_str());
845 // delegate showing assert dialog (if possible) to that class
846 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
848 else // no traits object
850 // fall back to the function of last resort
851 s_bNoAsserts
= DoShowAssertDialog(msg
);
856 #endif // __WXDEBUG__