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(__WXMAC__)
55 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
56 // I don't know which headers are needed under earlier systems so
57 // include everything when in doubt
61 #include "wx/mac/private.h" // includes mac headers
65 // ----------------------------------------------------------------------------
66 // private functions prototypes
67 // ----------------------------------------------------------------------------
70 // really just show the assert dialog
71 static bool DoShowAssertDialog(const wxString
& msg
);
73 // prepare for showing the assert dialog, use the given traits or
74 // DoShowAssertDialog() as last fallback to really show it
76 void ShowAssertDialog(const wxChar
*szFile
,
80 wxAppTraits
*traits
= NULL
);
82 // turn on the trace masks specified in the env variable WXTRACE
83 static void LINKAGEMODE
SetTraceMasks();
86 // ----------------------------------------------------------------------------
88 // ----------------------------------------------------------------------------
90 wxAppConsole
*wxAppConsole::ms_appInstance
= NULL
;
92 wxAppInitializerFunction
wxAppConsole::ms_appInitFn
= NULL
;
94 // ============================================================================
95 // wxAppConsole implementation
96 // ============================================================================
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
102 wxAppConsole::wxAppConsole()
106 ms_appInstance
= this;
111 // In unicode mode the SetTraceMasks call can cause an apptraits to be
112 // created, but since we are still in the constructor the wrong kind will
113 // be created for GUI apps. Destroy it so it can be created again later.
120 wxAppConsole::~wxAppConsole()
125 // ----------------------------------------------------------------------------
126 // initilization/cleanup
127 // ----------------------------------------------------------------------------
129 bool wxAppConsole::Initialize(int& argc
, wxChar
**argv
)
132 // If some code logged something before wxApp instance was created,
133 // wxLogStderr was set as the target. Undo it here by destroying the
134 // current target. It will be re-created next time logging is needed, but
135 // this time wxAppTraits will be used:
136 delete wxLog::SetActiveTarget(NULL
);
139 // remember the command line arguments
144 if ( m_appName
.empty() && argv
)
146 // the application name is, by default, the name of its executable file
147 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
154 void wxAppConsole::CleanUp()
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
162 bool wxAppConsole::OnInit()
164 #if wxUSE_CMDLINE_PARSER
165 wxCmdLineParser
parser(argc
, argv
);
167 OnInitCmdLine(parser
);
170 switch ( parser
.Parse(false /* don't show usage */) )
173 cont
= OnCmdLineHelp(parser
);
177 cont
= OnCmdLineParsed(parser
);
181 cont
= OnCmdLineError(parser
);
187 #endif // wxUSE_CMDLINE_PARSER
192 int wxAppConsole::OnExit()
195 // delete the config object if any (don't use Get() here, but Set()
196 // because Get() could create a new config object)
197 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
198 #endif // wxUSE_CONFIG
200 // use Set(NULL) and not Get() to avoid creating a message output object on
201 // demand when we just want to delete it
202 delete wxMessageOutput::Set(NULL
);
207 void wxAppConsole::Exit()
212 // ----------------------------------------------------------------------------
214 // ----------------------------------------------------------------------------
216 wxAppTraits
*wxAppConsole::CreateTraits()
218 return new wxConsoleAppTraits
;
221 wxAppTraits
*wxAppConsole::GetTraits()
223 // FIXME-MT: protect this with a CS?
226 m_traits
= CreateTraits();
228 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
234 // we must implement CreateXXX() in wxApp itself for backwards compatibility
235 #if WXWIN_COMPATIBILITY_2_4
239 wxLog
*wxAppConsole::CreateLogTarget()
241 wxAppTraits
*traits
= GetTraits();
242 return traits
? traits
->CreateLogTarget() : NULL
;
247 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
249 wxAppTraits
*traits
= GetTraits();
250 return traits
? traits
->CreateMessageOutput() : NULL
;
253 #endif // WXWIN_COMPATIBILITY_2_4
255 // ----------------------------------------------------------------------------
257 // ----------------------------------------------------------------------------
259 void wxAppConsole::ProcessPendingEvents()
261 // ensure that we're the only thread to modify the pending events list
262 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
264 if ( !wxPendingEvents
)
266 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
270 // iterate until the list becomes empty
271 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
274 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
275 wxPendingEvents
->Erase(node
);
277 // In ProcessPendingEvents(), new handlers might be add
278 // and we can safely leave the critical section here.
279 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
280 handler
->ProcessPendingEvents();
281 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
283 node
= wxPendingEvents
->GetFirst();
286 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
289 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
291 // process the events normally by default
295 // ----------------------------------------------------------------------------
296 // exception handling
297 // ----------------------------------------------------------------------------
302 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
303 wxEventFunction func
,
304 wxEvent
& event
) const
306 // by default, simply call the handler
307 (handler
->*func
)(event
);
311 wxAppConsole::OnExceptionInMainLoop()
315 // some compilers are too stupid to know that we never return after throw
316 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
321 #endif // wxUSE_EXCEPTIONS
323 // ----------------------------------------------------------------------------
325 // ----------------------------------------------------------------------------
327 #if wxUSE_CMDLINE_PARSER
329 #define OPTION_VERBOSE _T("verbose")
331 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
333 // the standard command line options
334 static const wxCmdLineEntryDesc cmdLineDesc
[] =
340 gettext_noop("show this help message"),
342 wxCMD_LINE_OPTION_HELP
350 gettext_noop("generate verbose log messages"),
367 parser
.SetDesc(cmdLineDesc
);
370 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
373 if ( parser
.Found(OPTION_VERBOSE
) )
375 wxLog::SetVerbose(true);
384 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
391 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
398 #endif // wxUSE_CMDLINE_PARSER
400 // ----------------------------------------------------------------------------
402 // ----------------------------------------------------------------------------
405 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
406 const char *componentName
)
408 #if 0 // can't use wxLogTrace, not up and running yet
409 printf("checking build options object '%s' (ptr %p) in '%s'\n",
410 optionsSignature
, optionsSignature
, componentName
);
413 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
415 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
416 wxString prog
= wxString::FromAscii(optionsSignature
);
417 wxString progName
= wxString::FromAscii(componentName
);
420 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
421 lib
.c_str(), progName
.c_str(), prog
.c_str());
423 wxLogFatalError(msg
.c_str());
425 // normally wxLogFatalError doesn't return
435 void wxAppConsole::OnAssert(const wxChar
*file
,
440 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
443 #endif // __WXDEBUG__
445 // ============================================================================
446 // other classes implementations
447 // ============================================================================
449 // ----------------------------------------------------------------------------
450 // wxConsoleAppTraitsBase
451 // ----------------------------------------------------------------------------
455 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
457 return new wxLogStderr
;
462 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
464 return new wxMessageOutputStderr
;
469 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
471 return (wxFontMapper
*)new wxFontMapperBase
;
474 #endif // wxUSE_FONTMAP
476 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
478 // console applications don't use renderers
483 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
485 return wxAppTraitsBase::ShowAssertDialog(msg
);
489 bool wxConsoleAppTraitsBase::HasStderr()
491 // console applications always have stderr, even under Mac/Windows
495 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
500 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
506 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
512 // ----------------------------------------------------------------------------
514 // ----------------------------------------------------------------------------
518 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
520 return DoShowAssertDialog(msg
);
523 #endif // __WXDEBUG__
525 // ============================================================================
526 // global functions implementation
527 // ============================================================================
537 // what else can we do?
546 wxTheApp
->WakeUpIdle();
548 //else: do nothing, what can we do?
554 bool wxAssertIsEqual(int x
, int y
)
559 // break into the debugger
562 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
564 #elif defined(__WXMAC__) && !defined(__DARWIN__)
570 #elif defined(__UNIX__)
577 void wxAssert(int cond
,
578 const wxChar
*szFile
,
580 const wxChar
*szCond
,
584 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
587 // this function is called when an assert fails
588 void wxOnAssert(const wxChar
*szFile
,
590 const wxChar
*szCond
,
594 static bool s_bInAssert
= false;
598 // He-e-e-e-elp!! we're trapped in endless loop
610 // by default, show the assert dialog box -- we can't customize this
612 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
616 // let the app process it as it wants
617 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
623 #endif // __WXDEBUG__
625 // ============================================================================
626 // private functions implementation
627 // ============================================================================
631 static void LINKAGEMODE
SetTraceMasks()
635 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
637 wxStringTokenizer
tkn(mask
, wxT(",;:"));
638 while ( tkn
.HasMoreTokens() )
639 wxLog::AddTraceMask(tkn
.GetNextToken());
644 bool DoShowAssertDialog(const wxString
& msg
)
646 // under MSW we can show the dialog even in the console mode
647 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
648 wxString
msgDlg(msg
);
650 // this message is intentionally not translated -- it is for
652 msgDlg
+= wxT("\nDo you want to stop the program?\n")
653 wxT("You can also choose [Cancel] to suppress ")
654 wxT("further warnings.");
656 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
657 MB_YESNOCANCEL
| MB_ICONSTOP
) )
667 //case IDNO: nothing to do
670 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
673 // TODO: ask the user to enter "Y" or "N" on the console?
675 #endif // __WXMSW__/!__WXMSW__
677 // continue with the asserts
681 // show the assert modal dialog
683 void ShowAssertDialog(const wxChar
*szFile
,
685 const wxChar
*szCond
,
689 // this variable can be set to true to suppress "assert failure" messages
690 static bool s_bNoAsserts
= false;
695 // make life easier for people using VC++ IDE by using this format: like
696 // this, clicking on the message will take us immediately to the place of
698 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
702 msg
<< _T(": ") << szMsg
;
704 else // no message given
710 // if we are not in the main thread, output the assert directly and trap
711 // since dialogs cannot be displayed
712 if ( !wxThread::IsMain() )
714 msg
+= wxT(" [in child thread]");
716 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
718 OutputDebugString(msg
);
721 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
724 // He-e-e-e-elp!! we're asserting in a child thread
727 #endif // wxUSE_THREADS
731 // send it to the normal log destination
732 wxLogDebug(_T("%s"), msg
.c_str());
736 // delegate showing assert dialog (if possible) to that class
737 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
739 else // no traits object
741 // fall back to the function of last resort
742 s_bNoAsserts
= DoShowAssertDialog(msg
);
747 #endif // __WXDEBUG__