]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
Sun CC doesn't allow calling static function from template instantiations so rename...
[wxWidgets.git] / src / common / appbase.cpp
CommitLineData
e2478fde 1///////////////////////////////////////////////////////////////////////////////
8ecff181 2// Name: src/common/appbase.cpp
e0954e72 3// Purpose: implements wxAppConsoleBase class
e2478fde
VZ
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 19.06.2003 (extracted from common/appcmn.cpp)
7// RCS-ID: $Id$
8// Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
0a53b9b8 9// License: wxWindows license
e2478fde
VZ
10///////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20// for compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
24 #pragma hdrstop
25#endif
26
27#ifndef WX_PRECOMP
57bd4c60
WS
28 #ifdef __WXMSW__
29 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
30 #endif
8ecff181 31 #include "wx/list.h"
8df6de97
VS
32 #include "wx/app.h"
33 #include "wx/intl.h"
86f8d1a8 34 #include "wx/log.h"
de6185e2 35 #include "wx/utils.h"
0cb7e05c 36 #include "wx/wxcrtvararg.h"
e2478fde
VZ
37#endif //WX_PRECOMP
38
39#include "wx/apptrait.h"
40#include "wx/cmdline.h"
41#include "wx/confbase.h"
b46b1d59 42#include "wx/evtloop.h"
ce39c39e 43#include "wx/filename.h"
e2478fde 44#include "wx/msgout.h"
b46b1d59 45#include "wx/ptr_scpd.h"
e2478fde
VZ
46#include "wx/tokenzr.h"
47
1663c655
VZ
48#if wxUSE_EXCEPTIONS && wxUSE_STL
49 #include <exception>
50 #include <typeinfo>
51#endif
52
e2478fde
VZ
53#if !defined(__WXMSW__) || defined(__WXMICROWIN__)
54 #include <signal.h> // for SIGTRAP used by wxTrap()
55#endif //Win/Unix
56
0e5ab030
VZ
57#include <locale.h>
58
1c193821
JS
59#if wxUSE_FONTMAP
60 #include "wx/fontmap.h"
61#endif // wxUSE_FONTMAP
62
f0756afe
DE
63#if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
64 // For MacTypes.h for Debugger function
65 #include <CoreFoundation/CFBase.h>
66#endif
67
e2478fde 68#if defined(__WXMAC__)
22f69dd4 69 #ifdef __DARWIN__
40ba2f3b 70 #include <CoreServices/CoreServices.h>
22f69dd4
VZ
71 #else
72 #include "wx/mac/private.h" // includes mac headers
73 #endif
74#endif // __WXMAC__
e2478fde 75
6c8f8d92 76#ifdef __WXDEBUG__
7b1c3469 77 #if wxUSE_STACKWALKER
6c8f8d92 78 #include "wx/stackwalk.h"
4a92d4bc
VZ
79 #ifdef __WXMSW__
80 #include "wx/msw/debughlp.h"
81 #endif
6c8f8d92
VZ
82 #endif // wxUSE_STACKWALKER
83#endif // __WXDEBUG__
84
121aea46
MW
85// wxABI_VERSION can be defined when compiling applications but it should be
86// left undefined when compiling the library itself, it is then set to its
87// default value in version.h
88#if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
89#error "wxABI_VERSION should not be defined when compiling the library"
90#endif
91
e2478fde
VZ
92// ----------------------------------------------------------------------------
93// private functions prototypes
94// ----------------------------------------------------------------------------
95
96#ifdef __WXDEBUG__
97 // really just show the assert dialog
98 static bool DoShowAssertDialog(const wxString& msg);
99
100 // prepare for showing the assert dialog, use the given traits or
101 // DoShowAssertDialog() as last fallback to really show it
102 static
0accd1cf 103 void ShowAssertDialog(const wxString& szFile,
e2478fde 104 int nLine,
0accd1cf
VS
105 const wxString& szFunc,
106 const wxString& szCond,
107 const wxString& szMsg,
e2478fde
VZ
108 wxAppTraits *traits = NULL);
109
110 // turn on the trace masks specified in the env variable WXTRACE
111 static void LINKAGEMODE SetTraceMasks();
112#endif // __WXDEBUG__
113
114// ----------------------------------------------------------------------------
115// global vars
116// ----------------------------------------------------------------------------
117
e0954e72 118wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
e2478fde 119
e0954e72 120wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
e2478fde 121
b46b1d59
VZ
122// ----------------------------------------------------------------------------
123// wxEventLoopPtr
124// ----------------------------------------------------------------------------
125
126// this defines wxEventLoopPtr
2ddff00c 127wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
b46b1d59 128
e2478fde 129// ============================================================================
e0954e72 130// wxAppConsoleBase implementation
e2478fde
VZ
131// ============================================================================
132
133// ----------------------------------------------------------------------------
134// ctor/dtor
135// ----------------------------------------------------------------------------
136
e0954e72 137wxAppConsoleBase::wxAppConsoleBase()
e2478fde
VZ
138{
139 m_traits = NULL;
b46b1d59 140 m_mainLoop = NULL;
e2478fde 141
e0954e72 142 ms_appInstance = wx_static_cast(wxAppConsole *, this);
e2478fde
VZ
143
144#ifdef __WXDEBUG__
145 SetTraceMasks();
bc334f39
RD
146#if wxUSE_UNICODE
147 // In unicode mode the SetTraceMasks call can cause an apptraits to be
148 // created, but since we are still in the constructor the wrong kind will
149 // be created for GUI apps. Destroy it so it can be created again later.
150 delete m_traits;
151 m_traits = NULL;
152#endif
e2478fde
VZ
153#endif
154}
155
e0954e72 156wxAppConsoleBase::~wxAppConsoleBase()
e2478fde
VZ
157{
158 delete m_traits;
159}
160
94826170
VZ
161// ----------------------------------------------------------------------------
162// initilization/cleanup
163// ----------------------------------------------------------------------------
164
e0954e72 165bool wxAppConsoleBase::Initialize(int& argcOrig, wxChar **argvOrig)
94826170 166{
d774f916
VZ
167#if wxUSE_INTL
168 GetTraits()->SetLocale();
169#endif // wxUSE_INTL
170
94826170 171 // remember the command line arguments
8d79ccef
VZ
172 argc = argcOrig;
173 argv = argvOrig;
94826170 174
b46b1d59
VZ
175#if wxUSE_THREADS
176 wxPendingEventsLocker = new wxCriticalSection;
177#endif
178
4055ed82 179#ifndef __WXPALMOS__
d546eba9 180 if ( m_appName.empty() && argv )
94826170
VZ
181 {
182 // the application name is, by default, the name of its executable file
94826170 183 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
94826170 184 }
d774f916 185#endif // !__WXPALMOS__
94826170
VZ
186
187 return true;
188}
189
e0954e72 190wxEventLoopBase *wxAppConsoleBase::CreateMainLoop()
b46b1d59
VZ
191{
192 return GetTraits()->CreateEventLoop();
193}
194
e0954e72 195void wxAppConsoleBase::CleanUp()
94826170 196{
aea33a3e
VZ
197 if ( m_mainLoop )
198 {
199 delete m_mainLoop;
200 m_mainLoop = NULL;
201 }
82a4f054 202
b46b1d59
VZ
203 delete wxPendingEvents;
204 wxPendingEvents = NULL;
205
206#if wxUSE_THREADS
207 delete wxPendingEventsLocker;
208 wxPendingEventsLocker = NULL;
209#endif // wxUSE_THREADS
94826170
VZ
210}
211
e2478fde
VZ
212// ----------------------------------------------------------------------------
213// OnXXX() callbacks
214// ----------------------------------------------------------------------------
215
e0954e72 216bool wxAppConsoleBase::OnInit()
e2478fde
VZ
217{
218#if wxUSE_CMDLINE_PARSER
219 wxCmdLineParser parser(argc, argv);
220
221 OnInitCmdLine(parser);
222
223 bool cont;
4629016d 224 switch ( parser.Parse(false /* don't show usage */) )
e2478fde
VZ
225 {
226 case -1:
227 cont = OnCmdLineHelp(parser);
228 break;
229
230 case 0:
231 cont = OnCmdLineParsed(parser);
232 break;
233
234 default:
235 cont = OnCmdLineError(parser);
236 break;
237 }
238
239 if ( !cont )
4629016d 240 return false;
e2478fde
VZ
241#endif // wxUSE_CMDLINE_PARSER
242
4629016d 243 return true;
e2478fde
VZ
244}
245
e0954e72 246int wxAppConsoleBase::OnRun()
b46b1d59
VZ
247{
248 return MainLoop();
8ac09e52 249}
b46b1d59 250
e0954e72 251int wxAppConsoleBase::OnExit()
e2478fde
VZ
252{
253#if wxUSE_CONFIG
254 // delete the config object if any (don't use Get() here, but Set()
255 // because Get() could create a new config object)
256 delete wxConfigBase::Set((wxConfigBase *) NULL);
257#endif // wxUSE_CONFIG
258
e2478fde
VZ
259 return 0;
260}
261
e0954e72 262void wxAppConsoleBase::Exit()
e2478fde 263{
b46b1d59
VZ
264 if (m_mainLoop != NULL)
265 ExitMainLoop();
266 else
267 exit(-1);
e2478fde
VZ
268}
269
270// ----------------------------------------------------------------------------
271// traits stuff
272// ----------------------------------------------------------------------------
273
e0954e72 274wxAppTraits *wxAppConsoleBase::CreateTraits()
e2478fde 275{
7843d11b 276 return new wxConsoleAppTraits;
e2478fde
VZ
277}
278
e0954e72 279wxAppTraits *wxAppConsoleBase::GetTraits()
e2478fde
VZ
280{
281 // FIXME-MT: protect this with a CS?
282 if ( !m_traits )
283 {
284 m_traits = CreateTraits();
285
286 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
287 }
288
289 return m_traits;
290}
291
e2478fde
VZ
292// ----------------------------------------------------------------------------
293// event processing
294// ----------------------------------------------------------------------------
295
e0954e72 296int wxAppConsoleBase::MainLoop()
e2478fde 297{
2ddff00c 298 wxEventLoopBaseTiedPtr mainLoop(&m_mainLoop, CreateMainLoop());
b46b1d59
VZ
299
300 return m_mainLoop ? m_mainLoop->Run() : -1;
301}
302
e0954e72 303void wxAppConsoleBase::ExitMainLoop()
b46b1d59
VZ
304{
305 // we should exit from the main event loop, not just any currently active
306 // (e.g. modal dialog) event loop
307 if ( m_mainLoop && m_mainLoop->IsRunning() )
308 {
309 m_mainLoop->Exit(0);
310 }
311}
312
e0954e72 313bool wxAppConsoleBase::Pending()
b46b1d59
VZ
314{
315 // use the currently active message loop here, not m_mainLoop, because if
316 // we're showing a modal dialog (with its own event loop) currently the
317 // main event loop is not running anyhow
2ddff00c 318 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
b46b1d59
VZ
319
320 return loop && loop->Pending();
321}
322
e0954e72 323bool wxAppConsoleBase::Dispatch()
b46b1d59
VZ
324{
325 // see comment in Pending()
2ddff00c 326 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
b46b1d59
VZ
327
328 return loop && loop->Dispatch();
329}
8ecff181 330
e0954e72 331bool wxAppConsoleBase::HasPendingEvents() const
b46b1d59 332{
e2478fde
VZ
333 // ensure that we're the only thread to modify the pending events list
334 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
335
336 if ( !wxPendingEvents )
337 {
338 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
b46b1d59 339 return false;
e2478fde 340 }
b46b1d59
VZ
341 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
342 return true;
8ac09e52 343}
b46b1d59 344
e0954e72
VZ
345/* static */
346bool wxAppConsoleBase::IsMainLoopRunning()
347{
348 const wxAppConsole * const app = GetInstance();
349
350 return app && app->m_mainLoop != NULL;
351}
352
353void wxAppConsoleBase::ProcessPendingEvents()
b46b1d59
VZ
354{
355#if wxUSE_THREADS
356 if ( !wxPendingEventsLocker )
357 return;
358#endif
359
360 if ( !HasPendingEvents() )
361 return;
e2478fde 362
c0bfefb6
VZ
363 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
364
e2478fde 365 // iterate until the list becomes empty
df5168c4 366 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
e2478fde
VZ
367 while (node)
368 {
369 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
df5168c4 370 wxPendingEvents->Erase(node);
e2478fde
VZ
371
372 // In ProcessPendingEvents(), new handlers might be add
373 // and we can safely leave the critical section here.
374 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
8ecff181 375
e2478fde 376 handler->ProcessPendingEvents();
de4de64f 377
e2478fde
VZ
378 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
379
380 node = wxPendingEvents->GetFirst();
381 }
382
383 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
384}
385
e0954e72 386void wxAppConsoleBase::WakeUpIdle()
b46b1d59
VZ
387{
388 if ( m_mainLoop )
389 m_mainLoop->WakeUp();
390}
391
e0954e72 392bool wxAppConsoleBase::ProcessIdle()
b46b1d59
VZ
393{
394 wxIdleEvent event;
395
396 event.SetEventObject(this);
397 ProcessEvent(event);
398 return event.MoreRequested();
399}
400
e0954e72 401int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
e2478fde
VZ
402{
403 // process the events normally by default
404 return -1;
405}
406
78361a0e
VZ
407// ----------------------------------------------------------------------------
408// exception handling
409// ----------------------------------------------------------------------------
410
6f054ac5
VZ
411#if wxUSE_EXCEPTIONS
412
413void
e0954e72
VZ
414wxAppConsoleBase::HandleEvent(wxEvtHandler *handler,
415 wxEventFunction func,
416 wxEvent& event) const
6f054ac5 417{
96d38c7e
VS
418 // by default, simply call the handler
419 (handler->*func)(event);
6f054ac5
VZ
420}
421
1663c655
VZ
422void wxAppConsoleBase::OnUnhandledException()
423{
424#ifdef __WXDEBUG__
425 // we're called from an exception handler so we can re-throw the exception
426 // to recover its type
427 wxString what;
428 try
429 {
430 throw;
431 }
432#if wxUSE_STL
433 catch ( std::exception& e )
434 {
435 what.Printf("std::exception of type \"%s\", what() = \"%s\"",
436 typeid(e).name(), e.what());
437 }
438#endif // wxUSE_STL
439 catch ( ... )
440 {
441 what = "unknown exception";
442 }
443
444 wxMessageOutputBest().Printf(
445 "*** Caught unhandled %s; terminating\n", what
446 );
447#endif // __WXDEBUG__
448}
449
b46b1d59
VZ
450// ----------------------------------------------------------------------------
451// exceptions support
452// ----------------------------------------------------------------------------
453
e0954e72 454bool wxAppConsoleBase::OnExceptionInMainLoop()
b46b1d59
VZ
455{
456 throw;
457
458 // some compilers are too stupid to know that we never return after throw
459#if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
460 return false;
461#endif
462}
463
6f054ac5
VZ
464#endif // wxUSE_EXCEPTIONS
465
e2478fde
VZ
466// ----------------------------------------------------------------------------
467// cmd line parsing
468// ----------------------------------------------------------------------------
469
470#if wxUSE_CMDLINE_PARSER
471
472#define OPTION_VERBOSE _T("verbose")
e2478fde 473
e0954e72 474void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser& parser)
e2478fde
VZ
475{
476 // the standard command line options
477 static const wxCmdLineEntryDesc cmdLineDesc[] =
478 {
479 {
480 wxCMD_LINE_SWITCH,
481 _T("h"),
482 _T("help"),
483 gettext_noop("show this help message"),
484 wxCMD_LINE_VAL_NONE,
485 wxCMD_LINE_OPTION_HELP
486 },
487
488#if wxUSE_LOG
489 {
490 wxCMD_LINE_SWITCH,
b494c48b 491 wxEmptyString,
e2478fde
VZ
492 OPTION_VERBOSE,
493 gettext_noop("generate verbose log messages"),
494 wxCMD_LINE_VAL_NONE,
495 0x0
496 },
497#endif // wxUSE_LOG
498
e2478fde
VZ
499 // terminator
500 {
501 wxCMD_LINE_NONE,
b494c48b
WS
502 wxEmptyString,
503 wxEmptyString,
504 wxEmptyString,
e2478fde
VZ
505 wxCMD_LINE_VAL_NONE,
506 0x0
507 }
508 };
509
510 parser.SetDesc(cmdLineDesc);
511}
512
e0954e72 513bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser& parser)
e2478fde
VZ
514{
515#if wxUSE_LOG
516 if ( parser.Found(OPTION_VERBOSE) )
517 {
fa0d3447 518 wxLog::SetVerbose(true);
e2478fde 519 }
fa0d3447
WS
520#else
521 wxUnusedVar(parser);
e2478fde
VZ
522#endif // wxUSE_LOG
523
fa0d3447 524 return true;
e2478fde
VZ
525}
526
e0954e72 527bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser& parser)
e2478fde
VZ
528{
529 parser.Usage();
530
4629016d 531 return false;
e2478fde
VZ
532}
533
e0954e72 534bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser& parser)
e2478fde
VZ
535{
536 parser.Usage();
537
4629016d 538 return false;
e2478fde
VZ
539}
540
541#endif // wxUSE_CMDLINE_PARSER
542
543// ----------------------------------------------------------------------------
544// debugging support
545// ----------------------------------------------------------------------------
546
547/* static */
e0954e72
VZ
548bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature,
549 const char *componentName)
e2478fde 550{
2a7c7605
VS
551#if 0 // can't use wxLogTrace, not up and running yet
552 printf("checking build options object '%s' (ptr %p) in '%s'\n",
553 optionsSignature, optionsSignature, componentName);
e2478fde
VZ
554#endif
555
2a7c7605 556 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
e2478fde 557 {
2a7c7605
VS
558 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
559 wxString prog = wxString::FromAscii(optionsSignature);
560 wxString progName = wxString::FromAscii(componentName);
e2478fde 561 wxString msg;
2dbc444a 562
b880adec 563 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
2a7c7605 564 lib.c_str(), progName.c_str(), prog.c_str());
2dbc444a 565
095d49f2 566 wxLogFatalError(msg.c_str());
e2478fde
VZ
567
568 // normally wxLogFatalError doesn't return
4629016d 569 return false;
e2478fde
VZ
570 }
571#undef wxCMP
572
4629016d 573 return true;
e2478fde
VZ
574}
575
576#ifdef __WXDEBUG__
577
e0954e72
VZ
578void wxAppConsoleBase::OnAssertFailure(const wxChar *file,
579 int line,
580 const wxChar *func,
581 const wxChar *cond,
582 const wxChar *msg)
dfa0b52f
VZ
583{
584 ShowAssertDialog(file, line, func, cond, msg, GetTraits());
585}
586
e0954e72
VZ
587void wxAppConsoleBase::OnAssert(const wxChar *file,
588 int line,
589 const wxChar *cond,
590 const wxChar *msg)
e2478fde 591{
acc476c5 592 OnAssertFailure(file, line, NULL, cond, msg);
e2478fde
VZ
593}
594
595#endif // __WXDEBUG__
596
597// ============================================================================
598// other classes implementations
599// ============================================================================
600
601// ----------------------------------------------------------------------------
602// wxConsoleAppTraitsBase
603// ----------------------------------------------------------------------------
604
605#if wxUSE_LOG
606
607wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
608{
609 return new wxLogStderr;
610}
611
612#endif // wxUSE_LOG
613
614wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
615{
616 return new wxMessageOutputStderr;
617}
618
619#if wxUSE_FONTMAP
620
621wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
622{
623 return (wxFontMapper *)new wxFontMapperBase;
624}
625
626#endif // wxUSE_FONTMAP
627
f0244295
VZ
628wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
629{
630 // console applications don't use renderers
631 return NULL;
632}
633
8df6de97 634#ifdef __WXDEBUG__
e2478fde
VZ
635bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
636{
637 return wxAppTraitsBase::ShowAssertDialog(msg);
638}
8df6de97 639#endif
e2478fde
VZ
640
641bool wxConsoleAppTraitsBase::HasStderr()
642{
643 // console applications always have stderr, even under Mac/Windows
644 return true;
645}
646
647void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
648{
649 delete object;
650}
651
652void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
653{
654 // nothing to do
655}
2dbc444a 656
38bb138f
VS
657#if wxUSE_SOCKETS
658GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
659{
660 return NULL;
661}
662#endif
e2478fde
VZ
663
664// ----------------------------------------------------------------------------
665// wxAppTraits
666// ----------------------------------------------------------------------------
667
6c4f5ea5 668#if wxUSE_INTL
d774f916
VZ
669void wxAppTraitsBase::SetLocale()
670{
671 setlocale(LC_ALL, "");
cb352236 672 wxUpdateLocaleIsUtf8();
d774f916 673}
6c4f5ea5 674#endif
d774f916 675
e2478fde
VZ
676#ifdef __WXDEBUG__
677
db9febdf 678bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
e2478fde 679{
db9febdf
RR
680 wxString msg = msgOriginal;
681
682#if wxUSE_STACKWALKER
683#if !defined(__WXMSW__)
684 // on Unix stack frame generation may take some time, depending on the
685 // size of the executable mainly... warn the user that we are working
686 wxFprintf(stderr, wxT("[Debug] Generating a stack trace... please wait"));
687 fflush(stderr);
688#endif
689
690 const wxString stackTrace = GetAssertStackTrace();
691 if ( !stackTrace.empty() )
692 msg << _T("\n\nCall stack:\n") << stackTrace;
693#endif // wxUSE_STACKWALKER
694
e2478fde
VZ
695 return DoShowAssertDialog(msg);
696}
697
db9febdf
RR
698#if wxUSE_STACKWALKER
699wxString wxAppTraitsBase::GetAssertStackTrace()
700{
701 wxString stackTrace;
702
703 class StackDump : public wxStackWalker
704 {
705 public:
706 StackDump() { }
707
708 const wxString& GetStackTrace() const { return m_stackTrace; }
709
710 protected:
711 virtual void OnStackFrame(const wxStackFrame& frame)
712 {
713 m_stackTrace << wxString::Format
714 (
715 _T("[%02d] "),
716 wx_truncate_cast(int, frame.GetLevel())
717 );
718
719 wxString name = frame.GetName();
720 if ( !name.empty() )
721 {
722 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
723 }
724 else
725 {
726 m_stackTrace << wxString::Format(_T("%p"), frame.GetAddress());
727 }
728
729 if ( frame.HasSourceLocation() )
730 {
731 m_stackTrace << _T('\t')
732 << frame.GetFileName()
733 << _T(':')
734 << frame.GetLine();
735 }
736
737 m_stackTrace << _T('\n');
738 }
739
740 private:
741 wxString m_stackTrace;
742 };
743
744 // don't show more than maxLines or we could get a dialog too tall to be
745 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
746 // characters it is still only 300 pixels...
747 static const int maxLines = 20;
748
749 StackDump dump;
750 dump.Walk(2, maxLines); // don't show OnAssert() call itself
751 stackTrace = dump.GetStackTrace();
752
753 const int count = stackTrace.Freq(wxT('\n'));
754 for ( int i = 0; i < count - maxLines; i++ )
755 stackTrace = stackTrace.BeforeLast(wxT('\n'));
756
757 return stackTrace;
758}
759#endif // wxUSE_STACKWALKER
760
761
e2478fde
VZ
762#endif // __WXDEBUG__
763
e2478fde
VZ
764// ============================================================================
765// global functions implementation
766// ============================================================================
767
768void wxExit()
769{
770 if ( wxTheApp )
771 {
772 wxTheApp->Exit();
773 }
774 else
775 {
776 // what else can we do?
777 exit(-1);
778 }
779}
780
781void wxWakeUpIdle()
782{
783 if ( wxTheApp )
784 {
785 wxTheApp->WakeUpIdle();
786 }
787 //else: do nothing, what can we do?
788}
789
790#ifdef __WXDEBUG__
791
792// wxASSERT() helper
793bool wxAssertIsEqual(int x, int y)
794{
795 return x == y;
796}
797
798// break into the debugger
799void wxTrap()
800{
801#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
802 DebugBreak();
803#elif defined(__WXMAC__) && !defined(__DARWIN__)
804 #if __powerc
805 Debugger();
806 #else
807 SysBreak();
808 #endif
f0756afe
DE
809#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
810 Debugger();
e2478fde
VZ
811#elif defined(__UNIX__)
812 raise(SIGTRAP);
813#else
814 // TODO
815#endif // Win/Unix
816}
817
e2478fde 818// this function is called when an assert fails
0accd1cf
VS
819static void wxDoOnAssert(const wxString& szFile,
820 int nLine,
821 const wxString& szFunc,
822 const wxString& szCond,
823 const wxString& szMsg = wxEmptyString)
e2478fde
VZ
824{
825 // FIXME MT-unsafe
4629016d 826 static bool s_bInAssert = false;
e2478fde
VZ
827
828 if ( s_bInAssert )
829 {
830 // He-e-e-e-elp!! we're trapped in endless loop
831 wxTrap();
832
4629016d 833 s_bInAssert = false;
e2478fde
VZ
834
835 return;
836 }
837
4629016d 838 s_bInAssert = true;
e2478fde
VZ
839
840 if ( !wxTheApp )
841 {
842 // by default, show the assert dialog box -- we can't customize this
843 // behaviour
0accd1cf 844 ShowAssertDialog(szFile, nLine, szFunc, szCond, szMsg);
e2478fde
VZ
845 }
846 else
847 {
848 // let the app process it as it wants
0accd1cf
VS
849 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
850 wxTheApp->OnAssertFailure(szFile.c_str(), nLine, szFunc.c_str(),
851 szCond.c_str(), szMsg.c_str());
e2478fde
VZ
852 }
853
4629016d 854 s_bInAssert = false;
e2478fde
VZ
855}
856
0accd1cf
VS
857void wxOnAssert(const wxString& szFile,
858 int nLine,
859 const wxString& szFunc,
860 const wxString& szCond,
861 const wxString& szMsg)
862{
863 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
864}
865
866void wxOnAssert(const wxString& szFile,
867 int nLine,
868 const wxString& szFunc,
869 const wxString& szCond)
870{
871 wxDoOnAssert(szFile, nLine, szFunc, szCond);
872}
873
874void wxOnAssert(const wxChar *szFile,
875 int nLine,
876 const char *szFunc,
877 const wxChar *szCond,
878 const wxChar *szMsg)
879{
880 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
881}
882
fbaf7d45
VS
883void wxOnAssert(const char *szFile,
884 int nLine,
885 const char *szFunc,
886 const char *szCond,
887 const wxString& szMsg)
888{
889 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
890}
891
2b232d20
VZ
892void wxOnAssert(const char *szFile,
893 int nLine,
894 const char *szFunc,
895 const char *szCond,
896 const wxCStrData& msg)
897{
898 wxDoOnAssert(szFile, nLine, szFunc, szCond, msg);
899}
900
0accd1cf
VS
901#if wxUSE_UNICODE
902void wxOnAssert(const char *szFile,
903 int nLine,
904 const char *szFunc,
905 const char *szCond)
906{
907 wxDoOnAssert(szFile, nLine, szFunc, szCond);
908}
909
910void wxOnAssert(const char *szFile,
911 int nLine,
912 const char *szFunc,
913 const char *szCond,
914 const char *szMsg)
915{
916 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
917}
918
919void wxOnAssert(const char *szFile,
920 int nLine,
921 const char *szFunc,
922 const char *szCond,
923 const wxChar *szMsg)
924{
925 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
926}
927#endif // wxUSE_UNICODE
928
e2478fde
VZ
929#endif // __WXDEBUG__
930
931// ============================================================================
932// private functions implementation
933// ============================================================================
934
935#ifdef __WXDEBUG__
936
937static void LINKAGEMODE SetTraceMasks()
938{
939#if wxUSE_LOG
940 wxString mask;
941 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
942 {
943 wxStringTokenizer tkn(mask, wxT(",;:"));
944 while ( tkn.HasMoreTokens() )
945 wxLog::AddTraceMask(tkn.GetNextToken());
946 }
947#endif // wxUSE_LOG
948}
949
950bool DoShowAssertDialog(const wxString& msg)
951{
952 // under MSW we can show the dialog even in the console mode
953#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
954 wxString msgDlg(msg);
955
956 // this message is intentionally not translated -- it is for
957 // developpers only
958 msgDlg += wxT("\nDo you want to stop the program?\n")
959 wxT("You can also choose [Cancel] to suppress ")
960 wxT("further warnings.");
961
e0a050e3 962 switch ( ::MessageBox(NULL, msgDlg.wx_str(), _T("wxWidgets Debug Alert"),
e2478fde
VZ
963 MB_YESNOCANCEL | MB_ICONSTOP ) )
964 {
965 case IDYES:
966 wxTrap();
967 break;
968
969 case IDCANCEL:
970 // stop the asserts
971 return true;
972
973 //case IDNO: nothing to do
974 }
975#else // !__WXMSW__
976 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
977 fflush(stderr);
978
979 // TODO: ask the user to enter "Y" or "N" on the console?
980 wxTrap();
981#endif // __WXMSW__/!__WXMSW__
982
983 // continue with the asserts
984 return false;
985}
986
4a92d4bc
VZ
987// show the assert modal dialog
988static
0accd1cf 989void ShowAssertDialog(const wxString& szFile,
4a92d4bc 990 int nLine,
0accd1cf
VS
991 const wxString& szFunc,
992 const wxString& szCond,
993 const wxString& szMsg,
4a92d4bc
VZ
994 wxAppTraits *traits)
995{
996 // this variable can be set to true to suppress "assert failure" messages
997 static bool s_bNoAsserts = false;
998
999 wxString msg;
1000 msg.reserve(2048);
1001
1002 // make life easier for people using VC++ IDE by using this format: like
1003 // this, clicking on the message will take us immediately to the place of
1004 // the failed assert
1005 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
1006
dfa0b52f 1007 // add the function name, if any
0accd1cf 1008 if ( !szFunc.empty() )
dfa0b52f
VZ
1009 msg << _T(" in ") << szFunc << _T("()");
1010
1011 // and the message itself
0accd1cf 1012 if ( !szMsg.empty() )
2c9b3131 1013 {
4a92d4bc 1014 msg << _T(": ") << szMsg;
2c9b3131 1015 }
4a92d4bc
VZ
1016 else // no message given
1017 {
1018 msg << _T('.');
1019 }
1020
e2478fde
VZ
1021#if wxUSE_THREADS
1022 // if we are not in the main thread, output the assert directly and trap
1023 // since dialogs cannot be displayed
1024 if ( !wxThread::IsMain() )
1025 {
1026 msg += wxT(" [in child thread]");
1027
1028#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1029 msg << wxT("\r\n");
e0a050e3 1030 OutputDebugString(msg.wx_str());
e2478fde
VZ
1031#else
1032 // send to stderr
1033 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
1034 fflush(stderr);
1035#endif
1036 // He-e-e-e-elp!! we're asserting in a child thread
1037 wxTrap();
1038 }
6c8f8d92 1039 else
e2478fde
VZ
1040#endif // wxUSE_THREADS
1041
1042 if ( !s_bNoAsserts )
1043 {
1044 // send it to the normal log destination
56fae7b8 1045 wxLogDebug(_T("%s"), msg.c_str());
e2478fde
VZ
1046
1047 if ( traits )
1048 {
1049 // delegate showing assert dialog (if possible) to that class
1050 s_bNoAsserts = traits->ShowAssertDialog(msg);
1051 }
1052 else // no traits object
1053 {
1054 // fall back to the function of last resort
1055 s_bNoAsserts = DoShowAssertDialog(msg);
1056 }
1057 }
1058}
1059
1060#endif // __WXDEBUG__