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
)
131 // remember the command line arguments
135 if ( m_appName
.empty() && argv
)
137 // the application name is, by default, the name of its executable file
138 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
144 void wxAppConsole::CleanUp()
148 // ----------------------------------------------------------------------------
150 // ----------------------------------------------------------------------------
152 bool wxAppConsole::OnInit()
154 #if wxUSE_CMDLINE_PARSER
155 wxCmdLineParser
parser(argc
, argv
);
157 OnInitCmdLine(parser
);
160 switch ( parser
.Parse(FALSE
/* don't show usage */) )
163 cont
= OnCmdLineHelp(parser
);
167 cont
= OnCmdLineParsed(parser
);
171 cont
= OnCmdLineError(parser
);
177 #endif // wxUSE_CMDLINE_PARSER
182 int wxAppConsole::OnExit()
185 // delete the config object if any (don't use Get() here, but Set()
186 // because Get() could create a new config object)
187 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
188 #endif // wxUSE_CONFIG
190 // use Set(NULL) and not Get() to avoid creating a message output object on
191 // demand when we just want to delete it
192 delete wxMessageOutput::Set(NULL
);
197 void wxAppConsole::Exit()
202 // ----------------------------------------------------------------------------
204 // ----------------------------------------------------------------------------
206 wxAppTraits
*wxAppConsole::CreateTraits()
208 return new wxConsoleAppTraits
;
211 wxAppTraits
*wxAppConsole::GetTraits()
213 // FIXME-MT: protect this with a CS?
216 m_traits
= CreateTraits();
218 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
224 // we must implement CreateXXX() in wxApp itself for backwards compatibility
225 #if WXWIN_COMPATIBILITY_2_4
229 wxLog
*wxAppConsole::CreateLogTarget()
231 wxAppTraits
*traits
= GetTraits();
232 return traits
? traits
->CreateLogTarget() : NULL
;
237 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
239 wxAppTraits
*traits
= GetTraits();
240 return traits
? traits
->CreateMessageOutput() : NULL
;
243 #endif // WXWIN_COMPATIBILITY_2_4
245 // ----------------------------------------------------------------------------
247 // ----------------------------------------------------------------------------
249 void wxAppConsole::ProcessPendingEvents()
251 // ensure that we're the only thread to modify the pending events list
252 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
254 if ( !wxPendingEvents
)
256 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
260 // iterate until the list becomes empty
261 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
264 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
265 wxPendingEvents
->Erase(node
);
267 // In ProcessPendingEvents(), new handlers might be add
268 // and we can safely leave the critical section here.
269 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
270 handler
->ProcessPendingEvents();
271 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
273 node
= wxPendingEvents
->GetFirst();
276 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
279 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
281 // process the events normally by default
285 // ----------------------------------------------------------------------------
286 // exception handling
287 // ----------------------------------------------------------------------------
292 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
293 wxEventFunction func
,
294 wxEvent
& event
) const
296 // by default, simply call the handler
297 (handler
->*func
)(event
);
301 wxAppConsole::OnExceptionInMainLoop()
305 // some compilers are too stupid to know that we never return after throw
306 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
311 #endif // wxUSE_EXCEPTIONS
313 // ----------------------------------------------------------------------------
315 // ----------------------------------------------------------------------------
317 #if wxUSE_CMDLINE_PARSER
319 #define OPTION_VERBOSE _T("verbose")
321 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
323 // the standard command line options
324 static const wxCmdLineEntryDesc cmdLineDesc
[] =
330 gettext_noop("show this help message"),
332 wxCMD_LINE_OPTION_HELP
340 gettext_noop("generate verbose log messages"),
357 parser
.SetDesc(cmdLineDesc
);
360 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
363 if ( parser
.Found(OPTION_VERBOSE
) )
365 wxLog::SetVerbose(TRUE
);
372 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
379 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
386 #endif // wxUSE_CMDLINE_PARSER
388 // ----------------------------------------------------------------------------
390 // ----------------------------------------------------------------------------
393 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
394 const char *componentName
)
396 #if 0 // can't use wxLogTrace, not up and running yet
397 printf("checking build options object '%s' (ptr %p) in '%s'\n",
398 optionsSignature
, optionsSignature
, componentName
);
401 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
403 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
404 wxString prog
= wxString::FromAscii(optionsSignature
);
405 wxString progName
= wxString::FromAscii(componentName
);
408 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
409 lib
.c_str(), progName
.c_str(), prog
.c_str());
411 wxLogFatalError(msg
.c_str());
413 // normally wxLogFatalError doesn't return
423 void wxAppConsole::OnAssert(const wxChar
*file
,
428 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
431 #endif // __WXDEBUG__
433 // ============================================================================
434 // other classes implementations
435 // ============================================================================
437 // ----------------------------------------------------------------------------
438 // wxConsoleAppTraitsBase
439 // ----------------------------------------------------------------------------
443 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
445 return new wxLogStderr
;
450 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
452 return new wxMessageOutputStderr
;
457 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
459 return (wxFontMapper
*)new wxFontMapperBase
;
462 #endif // wxUSE_FONTMAP
464 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
466 // console applications don't use renderers
471 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
473 return wxAppTraitsBase::ShowAssertDialog(msg
);
477 bool wxConsoleAppTraitsBase::HasStderr()
479 // console applications always have stderr, even under Mac/Windows
483 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
488 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
494 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
500 // ----------------------------------------------------------------------------
502 // ----------------------------------------------------------------------------
506 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
508 return DoShowAssertDialog(msg
);
511 #endif // __WXDEBUG__
513 // ============================================================================
514 // global functions implementation
515 // ============================================================================
525 // what else can we do?
534 wxTheApp
->WakeUpIdle();
536 //else: do nothing, what can we do?
542 bool wxAssertIsEqual(int x
, int y
)
547 // break into the debugger
550 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
552 #elif defined(__WXMAC__) && !defined(__DARWIN__)
558 #elif defined(__UNIX__)
565 void wxAssert(int cond
,
566 const wxChar
*szFile
,
568 const wxChar
*szCond
,
572 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
575 // this function is called when an assert fails
576 void wxOnAssert(const wxChar
*szFile
,
578 const wxChar
*szCond
,
582 static bool s_bInAssert
= FALSE
;
586 // He-e-e-e-elp!! we're trapped in endless loop
598 // by default, show the assert dialog box -- we can't customize this
600 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
604 // let the app process it as it wants
605 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
611 #endif // __WXDEBUG__
613 // ============================================================================
614 // private functions implementation
615 // ============================================================================
619 static void LINKAGEMODE
SetTraceMasks()
623 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
625 wxStringTokenizer
tkn(mask
, wxT(",;:"));
626 while ( tkn
.HasMoreTokens() )
627 wxLog::AddTraceMask(tkn
.GetNextToken());
632 bool DoShowAssertDialog(const wxString
& msg
)
634 // under MSW we can show the dialog even in the console mode
635 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
636 wxString
msgDlg(msg
);
638 // this message is intentionally not translated -- it is for
640 msgDlg
+= wxT("\nDo you want to stop the program?\n")
641 wxT("You can also choose [Cancel] to suppress ")
642 wxT("further warnings.");
644 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
645 MB_YESNOCANCEL
| MB_ICONSTOP
) )
655 //case IDNO: nothing to do
658 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
661 // TODO: ask the user to enter "Y" or "N" on the console?
663 #endif // __WXMSW__/!__WXMSW__
665 // continue with the asserts
669 // show the assert modal dialog
671 void ShowAssertDialog(const wxChar
*szFile
,
673 const wxChar
*szCond
,
677 // this variable can be set to true to suppress "assert failure" messages
678 static bool s_bNoAsserts
= FALSE
;
683 // make life easier for people using VC++ IDE by using this format: like
684 // this, clicking on the message will take us immediately to the place of
686 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
690 msg
<< _T(": ") << szMsg
;
692 else // no message given
698 // if we are not in the main thread, output the assert directly and trap
699 // since dialogs cannot be displayed
700 if ( !wxThread::IsMain() )
702 msg
+= wxT(" [in child thread]");
704 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
706 OutputDebugString(msg
);
709 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
712 // He-e-e-e-elp!! we're asserting in a child thread
715 #endif // wxUSE_THREADS
719 // send it to the normal log destination
720 wxLogDebug(_T("%s"), msg
.c_str());
724 // delegate showing assert dialog (if possible) to that class
725 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
727 else // no traits object
729 // fall back to the function of last resort
730 s_bNoAsserts
= DoShowAssertDialog(msg
);
735 #endif // __WXDEBUG__