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