]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
don't use _T() inside wxGetTranslation() and related macros (wxTRANSLATE, _, ......
[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 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
334
a1312bc8
PC
335 bool has = wxPendingEvents && !wxPendingEvents->IsEmpty();
336
b46b1d59 337 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
a1312bc8
PC
338
339 return has;
8ac09e52 340}
b46b1d59 341
e0954e72
VZ
342/* static */
343bool wxAppConsoleBase::IsMainLoopRunning()
344{
345 const wxAppConsole * const app = GetInstance();
346
347 return app && app->m_mainLoop != NULL;
348}
349
350void wxAppConsoleBase::ProcessPendingEvents()
b46b1d59
VZ
351{
352#if wxUSE_THREADS
353 if ( !wxPendingEventsLocker )
354 return;
355#endif
356
c0bfefb6
VZ
357 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
358
a1312bc8 359 if (wxPendingEvents)
e2478fde 360 {
a1312bc8
PC
361 // iterate until the list becomes empty
362 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
363 while (node)
364 {
365 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
366 wxPendingEvents->Erase(node);
e2478fde 367
a1312bc8
PC
368 // In ProcessPendingEvents(), new handlers might be add
369 // and we can safely leave the critical section here.
370 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
8ecff181 371
a1312bc8 372 handler->ProcessPendingEvents();
de4de64f 373
a1312bc8 374 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
e2478fde 375
a1312bc8
PC
376 node = wxPendingEvents->GetFirst();
377 }
e2478fde
VZ
378 }
379
380 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
381}
382
e0954e72 383void wxAppConsoleBase::WakeUpIdle()
b46b1d59
VZ
384{
385 if ( m_mainLoop )
386 m_mainLoop->WakeUp();
387}
388
e0954e72 389bool wxAppConsoleBase::ProcessIdle()
b46b1d59
VZ
390{
391 wxIdleEvent event;
392
393 event.SetEventObject(this);
394 ProcessEvent(event);
395 return event.MoreRequested();
396}
397
e0954e72 398int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
e2478fde
VZ
399{
400 // process the events normally by default
401 return -1;
402}
403
78361a0e
VZ
404// ----------------------------------------------------------------------------
405// exception handling
406// ----------------------------------------------------------------------------
407
6f054ac5
VZ
408#if wxUSE_EXCEPTIONS
409
410void
e0954e72
VZ
411wxAppConsoleBase::HandleEvent(wxEvtHandler *handler,
412 wxEventFunction func,
413 wxEvent& event) const
6f054ac5 414{
96d38c7e
VS
415 // by default, simply call the handler
416 (handler->*func)(event);
6f054ac5
VZ
417}
418
1663c655
VZ
419void wxAppConsoleBase::OnUnhandledException()
420{
421#ifdef __WXDEBUG__
422 // we're called from an exception handler so we can re-throw the exception
423 // to recover its type
424 wxString what;
425 try
426 {
427 throw;
428 }
429#if wxUSE_STL
430 catch ( std::exception& e )
431 {
432 what.Printf("std::exception of type \"%s\", what() = \"%s\"",
433 typeid(e).name(), e.what());
434 }
435#endif // wxUSE_STL
436 catch ( ... )
437 {
438 what = "unknown exception";
439 }
440
441 wxMessageOutputBest().Printf(
442 "*** Caught unhandled %s; terminating\n", what
443 );
444#endif // __WXDEBUG__
445}
446
b46b1d59
VZ
447// ----------------------------------------------------------------------------
448// exceptions support
449// ----------------------------------------------------------------------------
450
e0954e72 451bool wxAppConsoleBase::OnExceptionInMainLoop()
b46b1d59
VZ
452{
453 throw;
454
455 // some compilers are too stupid to know that we never return after throw
456#if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
457 return false;
458#endif
459}
460
6f054ac5
VZ
461#endif // wxUSE_EXCEPTIONS
462
e2478fde
VZ
463// ----------------------------------------------------------------------------
464// cmd line parsing
465// ----------------------------------------------------------------------------
466
467#if wxUSE_CMDLINE_PARSER
468
469#define OPTION_VERBOSE _T("verbose")
e2478fde 470
e0954e72 471void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser& parser)
e2478fde
VZ
472{
473 // the standard command line options
474 static const wxCmdLineEntryDesc cmdLineDesc[] =
475 {
476 {
477 wxCMD_LINE_SWITCH,
478 _T("h"),
479 _T("help"),
480 gettext_noop("show this help message"),
481 wxCMD_LINE_VAL_NONE,
482 wxCMD_LINE_OPTION_HELP
483 },
484
485#if wxUSE_LOG
486 {
487 wxCMD_LINE_SWITCH,
b494c48b 488 wxEmptyString,
e2478fde
VZ
489 OPTION_VERBOSE,
490 gettext_noop("generate verbose log messages"),
491 wxCMD_LINE_VAL_NONE,
492 0x0
493 },
494#endif // wxUSE_LOG
495
e2478fde
VZ
496 // terminator
497 {
498 wxCMD_LINE_NONE,
b494c48b
WS
499 wxEmptyString,
500 wxEmptyString,
501 wxEmptyString,
e2478fde
VZ
502 wxCMD_LINE_VAL_NONE,
503 0x0
504 }
505 };
506
507 parser.SetDesc(cmdLineDesc);
508}
509
e0954e72 510bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser& parser)
e2478fde
VZ
511{
512#if wxUSE_LOG
513 if ( parser.Found(OPTION_VERBOSE) )
514 {
fa0d3447 515 wxLog::SetVerbose(true);
e2478fde 516 }
fa0d3447
WS
517#else
518 wxUnusedVar(parser);
e2478fde
VZ
519#endif // wxUSE_LOG
520
fa0d3447 521 return true;
e2478fde
VZ
522}
523
e0954e72 524bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser& parser)
e2478fde
VZ
525{
526 parser.Usage();
527
4629016d 528 return false;
e2478fde
VZ
529}
530
e0954e72 531bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser& parser)
e2478fde
VZ
532{
533 parser.Usage();
534
4629016d 535 return false;
e2478fde
VZ
536}
537
538#endif // wxUSE_CMDLINE_PARSER
539
540// ----------------------------------------------------------------------------
541// debugging support
542// ----------------------------------------------------------------------------
543
544/* static */
e0954e72
VZ
545bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature,
546 const char *componentName)
e2478fde 547{
2a7c7605
VS
548#if 0 // can't use wxLogTrace, not up and running yet
549 printf("checking build options object '%s' (ptr %p) in '%s'\n",
550 optionsSignature, optionsSignature, componentName);
e2478fde
VZ
551#endif
552
2a7c7605 553 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
e2478fde 554 {
2a7c7605
VS
555 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
556 wxString prog = wxString::FromAscii(optionsSignature);
557 wxString progName = wxString::FromAscii(componentName);
e2478fde 558 wxString msg;
2dbc444a 559
b880adec 560 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
2a7c7605 561 lib.c_str(), progName.c_str(), prog.c_str());
2dbc444a 562
095d49f2 563 wxLogFatalError(msg.c_str());
e2478fde
VZ
564
565 // normally wxLogFatalError doesn't return
4629016d 566 return false;
e2478fde
VZ
567 }
568#undef wxCMP
569
4629016d 570 return true;
e2478fde
VZ
571}
572
573#ifdef __WXDEBUG__
574
e0954e72
VZ
575void wxAppConsoleBase::OnAssertFailure(const wxChar *file,
576 int line,
577 const wxChar *func,
578 const wxChar *cond,
579 const wxChar *msg)
dfa0b52f
VZ
580{
581 ShowAssertDialog(file, line, func, cond, msg, GetTraits());
582}
583
e0954e72
VZ
584void wxAppConsoleBase::OnAssert(const wxChar *file,
585 int line,
586 const wxChar *cond,
587 const wxChar *msg)
e2478fde 588{
acc476c5 589 OnAssertFailure(file, line, NULL, cond, msg);
e2478fde
VZ
590}
591
592#endif // __WXDEBUG__
593
594// ============================================================================
595// other classes implementations
596// ============================================================================
597
598// ----------------------------------------------------------------------------
599// wxConsoleAppTraitsBase
600// ----------------------------------------------------------------------------
601
602#if wxUSE_LOG
603
604wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
605{
606 return new wxLogStderr;
607}
608
609#endif // wxUSE_LOG
610
611wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
612{
613 return new wxMessageOutputStderr;
614}
615
616#if wxUSE_FONTMAP
617
618wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
619{
620 return (wxFontMapper *)new wxFontMapperBase;
621}
622
623#endif // wxUSE_FONTMAP
624
f0244295
VZ
625wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
626{
627 // console applications don't use renderers
628 return NULL;
629}
630
8df6de97 631#ifdef __WXDEBUG__
e2478fde
VZ
632bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
633{
634 return wxAppTraitsBase::ShowAssertDialog(msg);
635}
8df6de97 636#endif
e2478fde
VZ
637
638bool wxConsoleAppTraitsBase::HasStderr()
639{
640 // console applications always have stderr, even under Mac/Windows
641 return true;
642}
643
644void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
645{
646 delete object;
647}
648
649void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
650{
651 // nothing to do
652}
2dbc444a 653
38bb138f
VS
654#if wxUSE_SOCKETS
655GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
656{
657 return NULL;
658}
659#endif
e2478fde
VZ
660
661// ----------------------------------------------------------------------------
662// wxAppTraits
663// ----------------------------------------------------------------------------
664
6c4f5ea5 665#if wxUSE_INTL
d774f916
VZ
666void wxAppTraitsBase::SetLocale()
667{
d6f2a891 668 wxSetlocale(LC_ALL, "");
cb352236 669 wxUpdateLocaleIsUtf8();
d774f916 670}
6c4f5ea5 671#endif
d774f916 672
e2478fde
VZ
673#ifdef __WXDEBUG__
674
db9febdf 675bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
e2478fde 676{
db9febdf
RR
677 wxString msg = msgOriginal;
678
679#if wxUSE_STACKWALKER
680#if !defined(__WXMSW__)
681 // on Unix stack frame generation may take some time, depending on the
682 // size of the executable mainly... warn the user that we are working
683 wxFprintf(stderr, wxT("[Debug] Generating a stack trace... please wait"));
684 fflush(stderr);
685#endif
686
687 const wxString stackTrace = GetAssertStackTrace();
688 if ( !stackTrace.empty() )
689 msg << _T("\n\nCall stack:\n") << stackTrace;
690#endif // wxUSE_STACKWALKER
691
e2478fde
VZ
692 return DoShowAssertDialog(msg);
693}
694
db9febdf
RR
695#if wxUSE_STACKWALKER
696wxString wxAppTraitsBase::GetAssertStackTrace()
697{
698 wxString stackTrace;
699
700 class StackDump : public wxStackWalker
701 {
702 public:
703 StackDump() { }
704
705 const wxString& GetStackTrace() const { return m_stackTrace; }
706
707 protected:
708 virtual void OnStackFrame(const wxStackFrame& frame)
709 {
710 m_stackTrace << wxString::Format
711 (
712 _T("[%02d] "),
713 wx_truncate_cast(int, frame.GetLevel())
714 );
715
716 wxString name = frame.GetName();
717 if ( !name.empty() )
718 {
719 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
720 }
721 else
722 {
723 m_stackTrace << wxString::Format(_T("%p"), frame.GetAddress());
724 }
725
726 if ( frame.HasSourceLocation() )
727 {
728 m_stackTrace << _T('\t')
729 << frame.GetFileName()
730 << _T(':')
731 << frame.GetLine();
732 }
733
734 m_stackTrace << _T('\n');
735 }
736
737 private:
738 wxString m_stackTrace;
739 };
740
741 // don't show more than maxLines or we could get a dialog too tall to be
742 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
743 // characters it is still only 300 pixels...
744 static const int maxLines = 20;
745
746 StackDump dump;
747 dump.Walk(2, maxLines); // don't show OnAssert() call itself
748 stackTrace = dump.GetStackTrace();
749
750 const int count = stackTrace.Freq(wxT('\n'));
751 for ( int i = 0; i < count - maxLines; i++ )
752 stackTrace = stackTrace.BeforeLast(wxT('\n'));
753
754 return stackTrace;
755}
756#endif // wxUSE_STACKWALKER
757
758
e2478fde
VZ
759#endif // __WXDEBUG__
760
e2478fde
VZ
761// ============================================================================
762// global functions implementation
763// ============================================================================
764
765void wxExit()
766{
767 if ( wxTheApp )
768 {
769 wxTheApp->Exit();
770 }
771 else
772 {
773 // what else can we do?
774 exit(-1);
775 }
776}
777
778void wxWakeUpIdle()
779{
780 if ( wxTheApp )
781 {
782 wxTheApp->WakeUpIdle();
783 }
784 //else: do nothing, what can we do?
785}
786
787#ifdef __WXDEBUG__
788
789// wxASSERT() helper
790bool wxAssertIsEqual(int x, int y)
791{
792 return x == y;
793}
794
795// break into the debugger
796void wxTrap()
797{
798#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
799 DebugBreak();
800#elif defined(__WXMAC__) && !defined(__DARWIN__)
801 #if __powerc
802 Debugger();
803 #else
804 SysBreak();
805 #endif
f0756afe
DE
806#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
807 Debugger();
e2478fde
VZ
808#elif defined(__UNIX__)
809 raise(SIGTRAP);
810#else
811 // TODO
812#endif // Win/Unix
813}
814
e2478fde 815// this function is called when an assert fails
0accd1cf
VS
816static void wxDoOnAssert(const wxString& szFile,
817 int nLine,
818 const wxString& szFunc,
819 const wxString& szCond,
820 const wxString& szMsg = wxEmptyString)
e2478fde
VZ
821{
822 // FIXME MT-unsafe
4629016d 823 static bool s_bInAssert = false;
e2478fde
VZ
824
825 if ( s_bInAssert )
826 {
827 // He-e-e-e-elp!! we're trapped in endless loop
828 wxTrap();
829
4629016d 830 s_bInAssert = false;
e2478fde
VZ
831
832 return;
833 }
834
4629016d 835 s_bInAssert = true;
e2478fde
VZ
836
837 if ( !wxTheApp )
838 {
839 // by default, show the assert dialog box -- we can't customize this
840 // behaviour
0accd1cf 841 ShowAssertDialog(szFile, nLine, szFunc, szCond, szMsg);
e2478fde
VZ
842 }
843 else
844 {
845 // let the app process it as it wants
0accd1cf
VS
846 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
847 wxTheApp->OnAssertFailure(szFile.c_str(), nLine, szFunc.c_str(),
848 szCond.c_str(), szMsg.c_str());
e2478fde
VZ
849 }
850
4629016d 851 s_bInAssert = false;
e2478fde
VZ
852}
853
0accd1cf
VS
854void wxOnAssert(const wxString& szFile,
855 int nLine,
856 const wxString& szFunc,
857 const wxString& szCond,
858 const wxString& szMsg)
859{
860 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
861}
862
863void wxOnAssert(const wxString& szFile,
864 int nLine,
865 const wxString& szFunc,
866 const wxString& szCond)
867{
868 wxDoOnAssert(szFile, nLine, szFunc, szCond);
869}
870
871void wxOnAssert(const wxChar *szFile,
872 int nLine,
873 const char *szFunc,
874 const wxChar *szCond,
875 const wxChar *szMsg)
876{
877 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
878}
879
fbaf7d45
VS
880void wxOnAssert(const char *szFile,
881 int nLine,
882 const char *szFunc,
883 const char *szCond,
884 const wxString& szMsg)
885{
886 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
887}
888
2b232d20
VZ
889void wxOnAssert(const char *szFile,
890 int nLine,
891 const char *szFunc,
892 const char *szCond,
893 const wxCStrData& msg)
894{
895 wxDoOnAssert(szFile, nLine, szFunc, szCond, msg);
896}
897
0accd1cf
VS
898#if wxUSE_UNICODE
899void wxOnAssert(const char *szFile,
900 int nLine,
901 const char *szFunc,
902 const char *szCond)
903{
904 wxDoOnAssert(szFile, nLine, szFunc, szCond);
905}
906
907void wxOnAssert(const char *szFile,
908 int nLine,
909 const char *szFunc,
910 const char *szCond,
911 const char *szMsg)
912{
913 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
914}
915
916void wxOnAssert(const char *szFile,
917 int nLine,
918 const char *szFunc,
919 const char *szCond,
920 const wxChar *szMsg)
921{
922 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
923}
924#endif // wxUSE_UNICODE
925
e2478fde
VZ
926#endif // __WXDEBUG__
927
928// ============================================================================
929// private functions implementation
930// ============================================================================
931
932#ifdef __WXDEBUG__
933
934static void LINKAGEMODE SetTraceMasks()
935{
936#if wxUSE_LOG
937 wxString mask;
938 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
939 {
940 wxStringTokenizer tkn(mask, wxT(",;:"));
941 while ( tkn.HasMoreTokens() )
942 wxLog::AddTraceMask(tkn.GetNextToken());
943 }
944#endif // wxUSE_LOG
945}
946
6ef1b2a1 947static
e2478fde
VZ
948bool DoShowAssertDialog(const wxString& msg)
949{
950 // under MSW we can show the dialog even in the console mode
951#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
952 wxString msgDlg(msg);
953
954 // this message is intentionally not translated -- it is for
955 // developpers only
956 msgDlg += wxT("\nDo you want to stop the program?\n")
957 wxT("You can also choose [Cancel] to suppress ")
958 wxT("further warnings.");
959
e0a050e3 960 switch ( ::MessageBox(NULL, msgDlg.wx_str(), _T("wxWidgets Debug Alert"),
e2478fde
VZ
961 MB_YESNOCANCEL | MB_ICONSTOP ) )
962 {
963 case IDYES:
964 wxTrap();
965 break;
966
967 case IDCANCEL:
968 // stop the asserts
969 return true;
970
971 //case IDNO: nothing to do
972 }
973#else // !__WXMSW__
974 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
975 fflush(stderr);
976
977 // TODO: ask the user to enter "Y" or "N" on the console?
978 wxTrap();
979#endif // __WXMSW__/!__WXMSW__
980
981 // continue with the asserts
982 return false;
983}
984
4a92d4bc
VZ
985// show the assert modal dialog
986static
0accd1cf 987void ShowAssertDialog(const wxString& szFile,
4a92d4bc 988 int nLine,
0accd1cf
VS
989 const wxString& szFunc,
990 const wxString& szCond,
991 const wxString& szMsg,
4a92d4bc
VZ
992 wxAppTraits *traits)
993{
994 // this variable can be set to true to suppress "assert failure" messages
995 static bool s_bNoAsserts = false;
996
997 wxString msg;
998 msg.reserve(2048);
999
1000 // make life easier for people using VC++ IDE by using this format: like
1001 // this, clicking on the message will take us immediately to the place of
1002 // the failed assert
1003 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
1004
dfa0b52f 1005 // add the function name, if any
0accd1cf 1006 if ( !szFunc.empty() )
dfa0b52f
VZ
1007 msg << _T(" in ") << szFunc << _T("()");
1008
1009 // and the message itself
0accd1cf 1010 if ( !szMsg.empty() )
2c9b3131 1011 {
4a92d4bc 1012 msg << _T(": ") << szMsg;
2c9b3131 1013 }
4a92d4bc
VZ
1014 else // no message given
1015 {
1016 msg << _T('.');
1017 }
1018
e2478fde
VZ
1019#if wxUSE_THREADS
1020 // if we are not in the main thread, output the assert directly and trap
1021 // since dialogs cannot be displayed
1022 if ( !wxThread::IsMain() )
1023 {
1024 msg += wxT(" [in child thread]");
1025
1026#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1027 msg << wxT("\r\n");
e0a050e3 1028 OutputDebugString(msg.wx_str());
e2478fde
VZ
1029#else
1030 // send to stderr
1031 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
1032 fflush(stderr);
1033#endif
1034 // He-e-e-e-elp!! we're asserting in a child thread
1035 wxTrap();
1036 }
6c8f8d92 1037 else
e2478fde
VZ
1038#endif // wxUSE_THREADS
1039
1040 if ( !s_bNoAsserts )
1041 {
1042 // send it to the normal log destination
56fae7b8 1043 wxLogDebug(_T("%s"), msg.c_str());
e2478fde
VZ
1044
1045 if ( traits )
1046 {
1047 // delegate showing assert dialog (if possible) to that class
1048 s_bNoAsserts = traits->ShowAssertDialog(msg);
1049 }
1050 else // no traits object
1051 {
1052 // fall back to the function of last resort
1053 s_bNoAsserts = DoShowAssertDialog(msg);
1054 }
1055 }
1056}
1057
1058#endif // __WXDEBUG__