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