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 // If some code logged something before wxApp instance was created,
132 // wxLogStderr was set as the target. Undo it here by destroying the
133 // current target. It will be re-created next time logging is needed, but
134 // this time wxAppTraits will be used:
135 delete wxLog::SetActiveTarget(NULL
);
137 // remember the command line arguments
141 if ( m_appName
.empty() && argv
)
143 // the application name is, by default, the name of its executable file
144 wxFileName::SplitPath(argv
[0], NULL
, &m_appName
, NULL
);
150 void wxAppConsole::CleanUp()
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 bool wxAppConsole::OnInit()
160 #if wxUSE_CMDLINE_PARSER
161 wxCmdLineParser
parser(argc
, argv
);
163 OnInitCmdLine(parser
);
166 switch ( parser
.Parse(FALSE
/* don't show usage */) )
169 cont
= OnCmdLineHelp(parser
);
173 cont
= OnCmdLineParsed(parser
);
177 cont
= OnCmdLineError(parser
);
183 #endif // wxUSE_CMDLINE_PARSER
188 int wxAppConsole::OnExit()
191 // delete the config object if any (don't use Get() here, but Set()
192 // because Get() could create a new config object)
193 delete wxConfigBase::Set((wxConfigBase
*) NULL
);
194 #endif // wxUSE_CONFIG
196 // use Set(NULL) and not Get() to avoid creating a message output object on
197 // demand when we just want to delete it
198 delete wxMessageOutput::Set(NULL
);
203 void wxAppConsole::Exit()
208 // ----------------------------------------------------------------------------
210 // ----------------------------------------------------------------------------
212 wxAppTraits
*wxAppConsole::CreateTraits()
214 return new wxConsoleAppTraits
;
217 wxAppTraits
*wxAppConsole::GetTraits()
219 // FIXME-MT: protect this with a CS?
222 m_traits
= CreateTraits();
224 wxASSERT_MSG( m_traits
, _T("wxApp::CreateTraits() failed?") );
230 // we must implement CreateXXX() in wxApp itself for backwards compatibility
231 #if WXWIN_COMPATIBILITY_2_4
235 wxLog
*wxAppConsole::CreateLogTarget()
237 wxAppTraits
*traits
= GetTraits();
238 return traits
? traits
->CreateLogTarget() : NULL
;
243 wxMessageOutput
*wxAppConsole::CreateMessageOutput()
245 wxAppTraits
*traits
= GetTraits();
246 return traits
? traits
->CreateMessageOutput() : NULL
;
249 #endif // WXWIN_COMPATIBILITY_2_4
251 // ----------------------------------------------------------------------------
253 // ----------------------------------------------------------------------------
255 void wxAppConsole::ProcessPendingEvents()
257 // ensure that we're the only thread to modify the pending events list
258 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
260 if ( !wxPendingEvents
)
262 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
266 // iterate until the list becomes empty
267 wxList::compatibility_iterator node
= wxPendingEvents
->GetFirst();
270 wxEvtHandler
*handler
= (wxEvtHandler
*)node
->GetData();
271 wxPendingEvents
->Erase(node
);
273 // In ProcessPendingEvents(), new handlers might be add
274 // and we can safely leave the critical section here.
275 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
276 handler
->ProcessPendingEvents();
277 wxENTER_CRIT_SECT( *wxPendingEventsLocker
);
279 node
= wxPendingEvents
->GetFirst();
282 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker
);
285 int wxAppConsole::FilterEvent(wxEvent
& WXUNUSED(event
))
287 // process the events normally by default
291 // ----------------------------------------------------------------------------
292 // exception handling
293 // ----------------------------------------------------------------------------
298 wxAppConsole::HandleEvent(wxEvtHandler
*handler
,
299 wxEventFunction func
,
300 wxEvent
& event
) const
302 // by default, simply call the handler
303 (handler
->*func
)(event
);
307 wxAppConsole::OnExceptionInMainLoop()
311 // some compilers are too stupid to know that we never return after throw
312 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
317 #endif // wxUSE_EXCEPTIONS
319 // ----------------------------------------------------------------------------
321 // ----------------------------------------------------------------------------
323 #if wxUSE_CMDLINE_PARSER
325 #define OPTION_VERBOSE _T("verbose")
327 void wxAppConsole::OnInitCmdLine(wxCmdLineParser
& parser
)
329 // the standard command line options
330 static const wxCmdLineEntryDesc cmdLineDesc
[] =
336 gettext_noop("show this help message"),
338 wxCMD_LINE_OPTION_HELP
346 gettext_noop("generate verbose log messages"),
363 parser
.SetDesc(cmdLineDesc
);
366 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser
& parser
)
369 if ( parser
.Found(OPTION_VERBOSE
) )
371 wxLog::SetVerbose(TRUE
);
378 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser
& parser
)
385 bool wxAppConsole::OnCmdLineError(wxCmdLineParser
& parser
)
392 #endif // wxUSE_CMDLINE_PARSER
394 // ----------------------------------------------------------------------------
396 // ----------------------------------------------------------------------------
399 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature
,
400 const char *componentName
)
402 #if 0 // can't use wxLogTrace, not up and running yet
403 printf("checking build options object '%s' (ptr %p) in '%s'\n",
404 optionsSignature
, optionsSignature
, componentName
);
407 if ( strcmp(optionsSignature
, WX_BUILD_OPTIONS_SIGNATURE
) != 0 )
409 wxString lib
= wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE
);
410 wxString prog
= wxString::FromAscii(optionsSignature
);
411 wxString progName
= wxString::FromAscii(componentName
);
414 msg
.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
415 lib
.c_str(), progName
.c_str(), prog
.c_str());
417 wxLogFatalError(msg
.c_str());
419 // normally wxLogFatalError doesn't return
429 void wxAppConsole::OnAssert(const wxChar
*file
,
434 ShowAssertDialog(file
, line
, cond
, msg
, GetTraits());
437 #endif // __WXDEBUG__
439 // ============================================================================
440 // other classes implementations
441 // ============================================================================
443 // ----------------------------------------------------------------------------
444 // wxConsoleAppTraitsBase
445 // ----------------------------------------------------------------------------
449 wxLog
*wxConsoleAppTraitsBase::CreateLogTarget()
451 return new wxLogStderr
;
456 wxMessageOutput
*wxConsoleAppTraitsBase::CreateMessageOutput()
458 return new wxMessageOutputStderr
;
463 wxFontMapper
*wxConsoleAppTraitsBase::CreateFontMapper()
465 return (wxFontMapper
*)new wxFontMapperBase
;
468 #endif // wxUSE_FONTMAP
470 wxRendererNative
*wxConsoleAppTraitsBase::CreateRenderer()
472 // console applications don't use renderers
477 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
479 return wxAppTraitsBase::ShowAssertDialog(msg
);
483 bool wxConsoleAppTraitsBase::HasStderr()
485 // console applications always have stderr, even under Mac/Windows
489 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
494 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject
* WXUNUSED(object
))
500 GSocketGUIFunctionsTable
* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
506 // ----------------------------------------------------------------------------
508 // ----------------------------------------------------------------------------
512 bool wxAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
514 return DoShowAssertDialog(msg
);
517 #endif // __WXDEBUG__
519 // ============================================================================
520 // global functions implementation
521 // ============================================================================
531 // what else can we do?
540 wxTheApp
->WakeUpIdle();
542 //else: do nothing, what can we do?
548 bool wxAssertIsEqual(int x
, int y
)
553 // break into the debugger
556 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
558 #elif defined(__WXMAC__) && !defined(__DARWIN__)
564 #elif defined(__UNIX__)
571 void wxAssert(int cond
,
572 const wxChar
*szFile
,
574 const wxChar
*szCond
,
578 wxOnAssert(szFile
, nLine
, szCond
, szMsg
);
581 // this function is called when an assert fails
582 void wxOnAssert(const wxChar
*szFile
,
584 const wxChar
*szCond
,
588 static bool s_bInAssert
= FALSE
;
592 // He-e-e-e-elp!! we're trapped in endless loop
604 // by default, show the assert dialog box -- we can't customize this
606 ShowAssertDialog(szFile
, nLine
, szCond
, szMsg
);
610 // let the app process it as it wants
611 wxTheApp
->OnAssert(szFile
, nLine
, szCond
, szMsg
);
617 #endif // __WXDEBUG__
619 // ============================================================================
620 // private functions implementation
621 // ============================================================================
625 static void LINKAGEMODE
SetTraceMasks()
629 if ( wxGetEnv(wxT("WXTRACE"), &mask
) )
631 wxStringTokenizer
tkn(mask
, wxT(",;:"));
632 while ( tkn
.HasMoreTokens() )
633 wxLog::AddTraceMask(tkn
.GetNextToken());
638 bool DoShowAssertDialog(const wxString
& msg
)
640 // under MSW we can show the dialog even in the console mode
641 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
642 wxString
msgDlg(msg
);
644 // this message is intentionally not translated -- it is for
646 msgDlg
+= wxT("\nDo you want to stop the program?\n")
647 wxT("You can also choose [Cancel] to suppress ")
648 wxT("further warnings.");
650 switch ( ::MessageBox(NULL
, msgDlg
, _T("wxWidgets Debug Alert"),
651 MB_YESNOCANCEL
| MB_ICONSTOP
) )
661 //case IDNO: nothing to do
664 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
667 // TODO: ask the user to enter "Y" or "N" on the console?
669 #endif // __WXMSW__/!__WXMSW__
671 // continue with the asserts
675 // show the assert modal dialog
677 void ShowAssertDialog(const wxChar
*szFile
,
679 const wxChar
*szCond
,
683 // this variable can be set to true to suppress "assert failure" messages
684 static bool s_bNoAsserts
= FALSE
;
689 // make life easier for people using VC++ IDE by using this format: like
690 // this, clicking on the message will take us immediately to the place of
692 msg
.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile
, nLine
, szCond
);
696 msg
<< _T(": ") << szMsg
;
698 else // no message given
704 // if we are not in the main thread, output the assert directly and trap
705 // since dialogs cannot be displayed
706 if ( !wxThread::IsMain() )
708 msg
+= wxT(" [in child thread]");
710 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
712 OutputDebugString(msg
);
715 wxFprintf(stderr
, wxT("%s\n"), msg
.c_str());
718 // He-e-e-e-elp!! we're asserting in a child thread
721 #endif // wxUSE_THREADS
725 // send it to the normal log destination
726 wxLogDebug(_T("%s"), msg
.c_str());
730 // delegate showing assert dialog (if possible) to that class
731 s_bNoAsserts
= traits
->ShowAssertDialog(msg
);
733 else // no traits object
735 // fall back to the function of last resort
736 s_bNoAsserts
= DoShowAssertDialog(msg
);
741 #endif // __WXDEBUG__