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