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