]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
Disable wxUSE_ENH_METAFILE for wxGTK builds.
[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>
526954c5 9// Licence: wxWindows licence
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
d98a58c5 28 #ifdef __WINDOWS__
57bd4c60
WS
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"
4d1ea475 46#include "wx/sysopt.h"
e2478fde 47#include "wx/tokenzr.h"
204abcd4 48#include "wx/thread.h"
e2478fde 49
fe24e4e9
VZ
50#if wxUSE_STL
51 #if wxUSE_EXCEPTIONS
52 #include <exception>
53 #include <typeinfo>
54 #endif
55 #if wxUSE_INTL
56 #include <locale>
57 #endif
58#endif // wxUSE_STL
1663c655 59
d98a58c5 60#if !defined(__WINDOWS__) || defined(__WXMICROWIN__)
e2478fde
VZ
61 #include <signal.h> // for SIGTRAP used by wxTrap()
62#endif //Win/Unix
63
0e5ab030
VZ
64#include <locale.h>
65
1c193821
JS
66#if wxUSE_FONTMAP
67 #include "wx/fontmap.h"
68#endif // wxUSE_FONTMAP
69
657a8a35 70#if wxDEBUG_LEVEL
7b1c3469 71 #if wxUSE_STACKWALKER
6c8f8d92 72 #include "wx/stackwalk.h"
d98a58c5 73 #ifdef __WINDOWS__
4a92d4bc
VZ
74 #include "wx/msw/debughlp.h"
75 #endif
6c8f8d92 76 #endif // wxUSE_STACKWALKER
000eea7a
VZ
77
78 #include "wx/recguard.h"
657a8a35 79#endif // wxDEBUG_LEVEL
6c8f8d92 80
121aea46
MW
81// wxABI_VERSION can be defined when compiling applications but it should be
82// left undefined when compiling the library itself, it is then set to its
83// default value in version.h
84#if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
85#error "wxABI_VERSION should not be defined when compiling the library"
86#endif
87
e2478fde
VZ
88// ----------------------------------------------------------------------------
89// private functions prototypes
90// ----------------------------------------------------------------------------
91
657a8a35 92#if wxDEBUG_LEVEL
e2478fde
VZ
93 // really just show the assert dialog
94 static bool DoShowAssertDialog(const wxString& msg);
95
96 // prepare for showing the assert dialog, use the given traits or
97 // DoShowAssertDialog() as last fallback to really show it
98 static
657a8a35
VZ
99 void ShowAssertDialog(const wxString& file,
100 int line,
101 const wxString& func,
102 const wxString& cond,
103 const wxString& msg,
e2478fde 104 wxAppTraits *traits = NULL);
657a8a35 105#endif // wxDEBUG_LEVEL
e2478fde 106
657a8a35 107#ifdef __WXDEBUG__
e2478fde
VZ
108 // turn on the trace masks specified in the env variable WXTRACE
109 static void LINKAGEMODE SetTraceMasks();
110#endif // __WXDEBUG__
111
112// ----------------------------------------------------------------------------
113// global vars
114// ----------------------------------------------------------------------------
115
e0954e72 116wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
e2478fde 117
e0954e72 118wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
e2478fde 119
51fe4b60
VZ
120wxSocketManager *wxAppTraitsBase::ms_manager = NULL;
121
3185abc2
VZ
122WXDLLIMPEXP_DATA_BASE(wxList) wxPendingDelete;
123
b46b1d59
VZ
124// ----------------------------------------------------------------------------
125// wxEventLoopPtr
126// ----------------------------------------------------------------------------
127
128// this defines wxEventLoopPtr
2ddff00c 129wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
b46b1d59 130
e2478fde 131// ============================================================================
e0954e72 132// wxAppConsoleBase implementation
e2478fde
VZ
133// ============================================================================
134
135// ----------------------------------------------------------------------------
136// ctor/dtor
137// ----------------------------------------------------------------------------
138
e0954e72 139wxAppConsoleBase::wxAppConsoleBase()
e2478fde
VZ
140{
141 m_traits = NULL;
b46b1d59 142 m_mainLoop = NULL;
cae9e7b1 143 m_bDoPendingEventProcessing = true;
e2478fde 144
5c33522f 145 ms_appInstance = static_cast<wxAppConsole *>(this);
e2478fde
VZ
146
147#ifdef __WXDEBUG__
148 SetTraceMasks();
bc334f39
RD
149#if wxUSE_UNICODE
150 // In unicode mode the SetTraceMasks call can cause an apptraits to be
151 // created, but since we are still in the constructor the wrong kind will
152 // be created for GUI apps. Destroy it so it can be created again later.
5276b0a5 153 wxDELETE(m_traits);
bc334f39 154#endif
e2478fde 155#endif
58cc1587
VZ
156
157 wxEvtHandler::AddFilter(this);
e2478fde
VZ
158}
159
e0954e72 160wxAppConsoleBase::~wxAppConsoleBase()
e2478fde 161{
58cc1587
VZ
162 wxEvtHandler::RemoveFilter(this);
163
89fb9e52
VZ
164 // we're being destroyed and using this object from now on may not work or
165 // even crash so don't leave dangling pointers to it
166 ms_appInstance = NULL;
167
e2478fde
VZ
168 delete m_traits;
169}
170
94826170 171// ----------------------------------------------------------------------------
8b93348e 172// initialization/cleanup
94826170
VZ
173// ----------------------------------------------------------------------------
174
f432e677 175bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc), wxChar **WXUNUSED(argv))
94826170 176{
f432e677
VZ
177 return true;
178}
179
180wxString wxAppConsoleBase::GetAppName() const
181{
182 wxString name = m_appName;
f432e677 183 if ( name.empty() )
94826170 184 {
f432e677
VZ
185 if ( argv )
186 {
187 // the application name is, by default, the name of its executable file
188 wxFileName::SplitPath(argv[0], NULL, &name, NULL);
189 }
94826170 190 }
f432e677
VZ
191 return name;
192}
94826170 193
f432e677
VZ
194wxString wxAppConsoleBase::GetAppDisplayName() const
195{
196 // use the explicitly provided display name, if any
197 if ( !m_appDisplayName.empty() )
198 return m_appDisplayName;
199
200 // if the application name was explicitly set, use it as is as capitalizing
201 // it won't always produce good results
202 if ( !m_appName.empty() )
203 return m_appName;
204
205 // if neither is set, use the capitalized version of the program file as
206 // it's the most reasonable default
207 return GetAppName().Capitalize();
94826170
VZ
208}
209
e0954e72 210wxEventLoopBase *wxAppConsoleBase::CreateMainLoop()
b46b1d59
VZ
211{
212 return GetTraits()->CreateEventLoop();
213}
214
e0954e72 215void wxAppConsoleBase::CleanUp()
94826170 216{
5276b0a5 217 wxDELETE(m_mainLoop);
94826170
VZ
218}
219
e2478fde
VZ
220// ----------------------------------------------------------------------------
221// OnXXX() callbacks
222// ----------------------------------------------------------------------------
223
e0954e72 224bool wxAppConsoleBase::OnInit()
e2478fde
VZ
225{
226#if wxUSE_CMDLINE_PARSER
227 wxCmdLineParser parser(argc, argv);
228
229 OnInitCmdLine(parser);
230
231 bool cont;
4629016d 232 switch ( parser.Parse(false /* don't show usage */) )
e2478fde
VZ
233 {
234 case -1:
235 cont = OnCmdLineHelp(parser);
236 break;
237
238 case 0:
239 cont = OnCmdLineParsed(parser);
240 break;
241
242 default:
243 cont = OnCmdLineError(parser);
244 break;
245 }
246
247 if ( !cont )
4629016d 248 return false;
e2478fde
VZ
249#endif // wxUSE_CMDLINE_PARSER
250
4629016d 251 return true;
e2478fde
VZ
252}
253
e0954e72 254int wxAppConsoleBase::OnRun()
b46b1d59
VZ
255{
256 return MainLoop();
8ac09e52 257}
b46b1d59 258
e0954e72 259int wxAppConsoleBase::OnExit()
e2478fde
VZ
260{
261#if wxUSE_CONFIG
262 // delete the config object if any (don't use Get() here, but Set()
263 // because Get() could create a new config object)
d3b9f782 264 delete wxConfigBase::Set(NULL);
e2478fde
VZ
265#endif // wxUSE_CONFIG
266
e2478fde
VZ
267 return 0;
268}
269
e0954e72 270void wxAppConsoleBase::Exit()
e2478fde 271{
b46b1d59
VZ
272 if (m_mainLoop != NULL)
273 ExitMainLoop();
274 else
275 exit(-1);
e2478fde
VZ
276}
277
278// ----------------------------------------------------------------------------
279// traits stuff
280// ----------------------------------------------------------------------------
281
e0954e72 282wxAppTraits *wxAppConsoleBase::CreateTraits()
e2478fde 283{
7843d11b 284 return new wxConsoleAppTraits;
e2478fde
VZ
285}
286
e0954e72 287wxAppTraits *wxAppConsoleBase::GetTraits()
e2478fde
VZ
288{
289 // FIXME-MT: protect this with a CS?
290 if ( !m_traits )
291 {
292 m_traits = CreateTraits();
293
9a83f860 294 wxASSERT_MSG( m_traits, wxT("wxApp::CreateTraits() failed?") );
e2478fde
VZ
295 }
296
297 return m_traits;
298}
299
96b2cbe8
VZ
300/* static */
301wxAppTraits *wxAppConsoleBase::GetTraitsIfExists()
302{
303 wxAppConsole * const app = GetInstance();
304 return app ? app->GetTraits() : NULL;
305}
306
76015a6b
VZ
307/* static */
308wxAppTraits& wxAppConsoleBase::GetValidTraits()
309{
310 static wxConsoleAppTraits s_traitsConsole;
311 wxAppTraits* const traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
312
313 return traits ? *traits : s_traitsConsole;
314}
315
e2478fde 316// ----------------------------------------------------------------------------
dde19c21 317// wxEventLoop redirection
e2478fde
VZ
318// ----------------------------------------------------------------------------
319
e0954e72 320int wxAppConsoleBase::MainLoop()
e2478fde 321{
2ddff00c 322 wxEventLoopBaseTiedPtr mainLoop(&m_mainLoop, CreateMainLoop());
b46b1d59
VZ
323
324 return m_mainLoop ? m_mainLoop->Run() : -1;
325}
326
e0954e72 327void wxAppConsoleBase::ExitMainLoop()
b46b1d59
VZ
328{
329 // we should exit from the main event loop, not just any currently active
330 // (e.g. modal dialog) event loop
331 if ( m_mainLoop && m_mainLoop->IsRunning() )
332 {
333 m_mainLoop->Exit(0);
334 }
335}
336
e0954e72 337bool wxAppConsoleBase::Pending()
b46b1d59
VZ
338{
339 // use the currently active message loop here, not m_mainLoop, because if
340 // we're showing a modal dialog (with its own event loop) currently the
341 // main event loop is not running anyhow
2ddff00c 342 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
b46b1d59
VZ
343
344 return loop && loop->Pending();
345}
346
e0954e72 347bool wxAppConsoleBase::Dispatch()
b46b1d59
VZ
348{
349 // see comment in Pending()
2ddff00c 350 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
b46b1d59
VZ
351
352 return loop && loop->Dispatch();
353}
8ecff181 354
dde19c21
FM
355bool wxAppConsoleBase::Yield(bool onlyIfNeeded)
356{
357 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
6aacfc73
VZ
358 if ( loop )
359 return loop->Yield(onlyIfNeeded);
d48b06bd 360
6aacfc73
VZ
361 wxScopedPtr<wxEventLoopBase> tmpLoop(CreateMainLoop());
362 return tmpLoop->Yield(onlyIfNeeded);
e2478fde
VZ
363}
364
e0954e72 365void wxAppConsoleBase::WakeUpIdle()
b46b1d59 366{
53cda845
VZ
367 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
368
369 if ( loop )
370 loop->WakeUp();
b46b1d59
VZ
371}
372
e0954e72 373bool wxAppConsoleBase::ProcessIdle()
b46b1d59 374{
a758f601
VZ
375 // synthesize an idle event and check if more of them are needed
376 wxIdleEvent event;
377 event.SetEventObject(this);
378 ProcessEvent(event);
dde19c21 379
0055cc0e
VZ
380#if wxUSE_LOG
381 // flush the logged messages if any (do this after processing the events
382 // which could have logged new messages)
383 wxLog::FlushActive();
384#endif
385
e819ca3a
VZ
386 // Garbage collect all objects previously scheduled for destruction.
387 DeletePendingObjects();
388
a758f601 389 return event.MoreRequested();
dde19c21 390}
14eb37a0 391
3185abc2
VZ
392bool wxAppConsoleBase::UsesEventLoop() const
393{
394 // in console applications we don't know whether we're going to have an
395 // event loop so assume we won't -- unless we already have one running
396 return wxEventLoopBase::GetActive() != NULL;
397}
398
dde19c21
FM
399// ----------------------------------------------------------------------------
400// events
401// ----------------------------------------------------------------------------
b46b1d59 402
dde19c21
FM
403/* static */
404bool wxAppConsoleBase::IsMainLoopRunning()
405{
406 const wxAppConsole * const app = GetInstance();
407
408 return app && app->m_mainLoop != NULL;
b46b1d59
VZ
409}
410
e0954e72 411int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
e2478fde
VZ
412{
413 // process the events normally by default
58cc1587 414 return Event_Skip;
e2478fde
VZ
415}
416
8e40ed85
FM
417void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler* toDelay)
418{
419 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
420
421 // move the handler from the list of handlers with processable pending events
422 // to the list of handlers with pending events which needs to be processed later
423 m_handlersWithPendingEvents.Remove(toDelay);
424
425 if (m_handlersWithPendingDelayedEvents.Index(toDelay) == wxNOT_FOUND)
426 m_handlersWithPendingDelayedEvents.Add(toDelay);
427
428 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
429}
430
431void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler* toRemove)
432{
433 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
434
435 if (m_handlersWithPendingEvents.Index(toRemove) != wxNOT_FOUND)
436 {
437 m_handlersWithPendingEvents.Remove(toRemove);
438
439 // check that the handler was present only once in the list
440 wxASSERT_MSG( m_handlersWithPendingEvents.Index(toRemove) == wxNOT_FOUND,
441 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
442 }
443 //else: it wasn't in this list at all, it's ok
444
445 if (m_handlersWithPendingDelayedEvents.Index(toRemove) != wxNOT_FOUND)
446 {
447 m_handlersWithPendingDelayedEvents.Remove(toRemove);
448
449 // check that the handler was present only once in the list
450 wxASSERT_MSG( m_handlersWithPendingDelayedEvents.Index(toRemove) == wxNOT_FOUND,
451 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
452 }
453 //else: it wasn't in this list at all, it's ok
454
455 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
456}
457
458void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler* toAppend)
459{
460 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
461
462 if ( m_handlersWithPendingEvents.Index(toAppend) == wxNOT_FOUND )
463 m_handlersWithPendingEvents.Add(toAppend);
464
465 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
466}
467
468bool wxAppConsoleBase::HasPendingEvents() const
469{
470 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase*>(this)->m_handlersWithPendingEventsLocker);
471
472 bool has = !m_handlersWithPendingEvents.IsEmpty();
473
474 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase*>(this)->m_handlersWithPendingEventsLocker);
475
476 return has;
477}
478
479void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
480{
cae9e7b1 481 m_bDoPendingEventProcessing = false;
8e40ed85
FM
482}
483
484void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
485{
cae9e7b1 486 m_bDoPendingEventProcessing = true;
8e40ed85
FM
487}
488
489void wxAppConsoleBase::ProcessPendingEvents()
490{
3185abc2 491 if ( m_bDoPendingEventProcessing )
8e40ed85 492 {
3185abc2 493 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
8e40ed85 494
3185abc2
VZ
495 wxCHECK_RET( m_handlersWithPendingDelayedEvents.IsEmpty(),
496 "this helper list should be empty" );
8e40ed85 497
3185abc2
VZ
498 // iterate until the list becomes empty: the handlers remove themselves
499 // from it when they don't have any more pending events
500 while (!m_handlersWithPendingEvents.IsEmpty())
501 {
502 // In ProcessPendingEvents(), new handlers might be added
503 // and we can safely leave the critical section here.
504 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
505
506 // NOTE: we always call ProcessPendingEvents() on the first event handler
507 // with pending events because handlers auto-remove themselves
508 // from this list (see RemovePendingEventHandler) if they have no
509 // more pending events.
510 m_handlersWithPendingEvents[0]->ProcessPendingEvents();
511
512 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
513 }
514
515 // now the wxHandlersWithPendingEvents is surely empty; however some event
516 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
517 // because of a selective wxYield call in progress.
518 // Now we need to move them back to wxHandlersWithPendingEvents so the next
519 // call to this function has the chance of processing them:
520 if (!m_handlersWithPendingDelayedEvents.IsEmpty())
521 {
522 WX_APPEND_ARRAY(m_handlersWithPendingEvents, m_handlersWithPendingDelayedEvents);
523 m_handlersWithPendingDelayedEvents.Clear();
524 }
8e40ed85 525
3185abc2 526 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
8e40ed85 527 }
8e40ed85
FM
528}
529
cae9e7b1
FM
530void wxAppConsoleBase::DeletePendingEvents()
531{
532 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
533
534 wxCHECK_RET( m_handlersWithPendingDelayedEvents.IsEmpty(),
535 "this helper list should be empty" );
536
537 for (unsigned int i=0; i<m_handlersWithPendingEvents.GetCount(); i++)
538 m_handlersWithPendingEvents[i]->DeletePendingEvents();
539
540 m_handlersWithPendingEvents.Clear();
541
542 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
543}
544
3185abc2
VZ
545// ----------------------------------------------------------------------------
546// delayed objects destruction
547// ----------------------------------------------------------------------------
548
549bool wxAppConsoleBase::IsScheduledForDestruction(wxObject *object) const
550{
0f08aa44 551 return wxPendingDelete.Member(object);
3185abc2
VZ
552}
553
554void wxAppConsoleBase::ScheduleForDestruction(wxObject *object)
555{
556 if ( !UsesEventLoop() )
557 {
558 // we won't be able to delete it later so do it right now
559 delete object;
560 return;
561 }
562 //else: we either already have or will soon start an event loop
563
564 if ( !wxPendingDelete.Member(object) )
565 wxPendingDelete.Append(object);
566}
567
568void wxAppConsoleBase::DeletePendingObjects()
569{
570 wxList::compatibility_iterator node = wxPendingDelete.GetFirst();
571 while (node)
572 {
573 wxObject *obj = node->GetData();
574
575 // remove it from the list first so that if we get back here somehow
576 // during the object deletion (e.g. wxYield called from its dtor) we
577 // wouldn't try to delete it the second time
578 if ( wxPendingDelete.Member(obj) )
579 wxPendingDelete.Erase(node);
580
581 delete obj;
582
583 // Deleting one object may have deleted other pending
584 // objects, so start from beginning of list again.
585 node = wxPendingDelete.GetFirst();
586 }
587}
588
78361a0e
VZ
589// ----------------------------------------------------------------------------
590// exception handling
591// ----------------------------------------------------------------------------
592
6f054ac5
VZ
593#if wxUSE_EXCEPTIONS
594
595void
e0954e72
VZ
596wxAppConsoleBase::HandleEvent(wxEvtHandler *handler,
597 wxEventFunction func,
598 wxEvent& event) const
6f054ac5 599{
96d38c7e
VS
600 // by default, simply call the handler
601 (handler->*func)(event);
6f054ac5
VZ
602}
603
3c778901
VZ
604void wxAppConsoleBase::CallEventHandler(wxEvtHandler *handler,
605 wxEventFunctor& functor,
606 wxEvent& event) const
607{
608 // If the functor holds a method then, for backward compatibility, call
609 // HandleEvent():
890d70eb 610 wxEventFunction eventFunction = functor.GetEvtMethod();
3c778901
VZ
611
612 if ( eventFunction )
613 HandleEvent(handler, eventFunction, event);
614 else
615 functor(handler, event);
616}
617
1663c655
VZ
618void wxAppConsoleBase::OnUnhandledException()
619{
620#ifdef __WXDEBUG__
621 // we're called from an exception handler so we can re-throw the exception
622 // to recover its type
623 wxString what;
624 try
625 {
626 throw;
627 }
628#if wxUSE_STL
629 catch ( std::exception& e )
630 {
631 what.Printf("std::exception of type \"%s\", what() = \"%s\"",
632 typeid(e).name(), e.what());
633 }
634#endif // wxUSE_STL
635 catch ( ... )
636 {
637 what = "unknown exception";
638 }
639
640 wxMessageOutputBest().Printf(
641 "*** Caught unhandled %s; terminating\n", what
642 );
643#endif // __WXDEBUG__
644}
645
b46b1d59
VZ
646// ----------------------------------------------------------------------------
647// exceptions support
648// ----------------------------------------------------------------------------
649
e0954e72 650bool wxAppConsoleBase::OnExceptionInMainLoop()
b46b1d59
VZ
651{
652 throw;
653
654 // some compilers are too stupid to know that we never return after throw
655#if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
656 return false;
657#endif
658}
659
6f054ac5
VZ
660#endif // wxUSE_EXCEPTIONS
661
e2478fde
VZ
662// ----------------------------------------------------------------------------
663// cmd line parsing
664// ----------------------------------------------------------------------------
665
666#if wxUSE_CMDLINE_PARSER
667
e6d4038a 668#define OPTION_VERBOSE "verbose"
e2478fde 669
e0954e72 670void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser& parser)
e2478fde
VZ
671{
672 // the standard command line options
673 static const wxCmdLineEntryDesc cmdLineDesc[] =
674 {
675 {
676 wxCMD_LINE_SWITCH,
e6d4038a
VZ
677 "h",
678 "help",
e2478fde
VZ
679 gettext_noop("show this help message"),
680 wxCMD_LINE_VAL_NONE,
681 wxCMD_LINE_OPTION_HELP
682 },
683
684#if wxUSE_LOG
685 {
686 wxCMD_LINE_SWITCH,
0d5ab92f 687 NULL,
e2478fde
VZ
688 OPTION_VERBOSE,
689 gettext_noop("generate verbose log messages"),
690 wxCMD_LINE_VAL_NONE,
691 0x0
692 },
693#endif // wxUSE_LOG
694
e2478fde 695 // terminator
0d5ab92f 696 wxCMD_LINE_DESC_END
e2478fde
VZ
697 };
698
699 parser.SetDesc(cmdLineDesc);
700}
701
e0954e72 702bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser& parser)
e2478fde
VZ
703{
704#if wxUSE_LOG
705 if ( parser.Found(OPTION_VERBOSE) )
706 {
fa0d3447 707 wxLog::SetVerbose(true);
e2478fde 708 }
fa0d3447
WS
709#else
710 wxUnusedVar(parser);
e2478fde
VZ
711#endif // wxUSE_LOG
712
fa0d3447 713 return true;
e2478fde
VZ
714}
715
e0954e72 716bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser& parser)
e2478fde
VZ
717{
718 parser.Usage();
719
4629016d 720 return false;
e2478fde
VZ
721}
722
e0954e72 723bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser& parser)
e2478fde
VZ
724{
725 parser.Usage();
726
4629016d 727 return false;
e2478fde
VZ
728}
729
730#endif // wxUSE_CMDLINE_PARSER
731
732// ----------------------------------------------------------------------------
733// debugging support
734// ----------------------------------------------------------------------------
735
736/* static */
e0954e72
VZ
737bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature,
738 const char *componentName)
e2478fde 739{
2a7c7605
VS
740#if 0 // can't use wxLogTrace, not up and running yet
741 printf("checking build options object '%s' (ptr %p) in '%s'\n",
742 optionsSignature, optionsSignature, componentName);
e2478fde
VZ
743#endif
744
2a7c7605 745 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
e2478fde 746 {
2a7c7605
VS
747 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
748 wxString prog = wxString::FromAscii(optionsSignature);
749 wxString progName = wxString::FromAscii(componentName);
e2478fde 750 wxString msg;
2dbc444a 751
9a83f860 752 msg.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
2a7c7605 753 lib.c_str(), progName.c_str(), prog.c_str());
2dbc444a 754
095d49f2 755 wxLogFatalError(msg.c_str());
e2478fde
VZ
756
757 // normally wxLogFatalError doesn't return
4629016d 758 return false;
e2478fde 759 }
e2478fde 760
4629016d 761 return true;
e2478fde
VZ
762}
763
e0954e72
VZ
764void wxAppConsoleBase::OnAssertFailure(const wxChar *file,
765 int line,
766 const wxChar *func,
767 const wxChar *cond,
768 const wxChar *msg)
dfa0b52f 769{
657a8a35 770#if wxDEBUG_LEVEL
dfa0b52f 771 ShowAssertDialog(file, line, func, cond, msg, GetTraits());
657a8a35
VZ
772#else
773 // this function is still present even in debug level 0 build for ABI
774 // compatibility reasons but is never called there and so can simply do
775 // nothing in it
776 wxUnusedVar(file);
777 wxUnusedVar(line);
778 wxUnusedVar(func);
779 wxUnusedVar(cond);
780 wxUnusedVar(msg);
781#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
dfa0b52f
VZ
782}
783
e0954e72
VZ
784void wxAppConsoleBase::OnAssert(const wxChar *file,
785 int line,
786 const wxChar *cond,
787 const wxChar *msg)
e2478fde 788{
acc476c5 789 OnAssertFailure(file, line, NULL, cond, msg);
e2478fde
VZ
790}
791
b5101417
VZ
792// ----------------------------------------------------------------------------
793// Miscellaneous other methods
794// ----------------------------------------------------------------------------
795
796void wxAppConsoleBase::SetCLocale()
797{
798 // We want to use the user locale by default in GUI applications in order
799 // to show the numbers, dates &c in the familiar format -- and also accept
800 // this format on input (especially important for decimal comma/dot).
801 wxSetlocale(LC_ALL, "");
802}
803
e2478fde
VZ
804// ============================================================================
805// other classes implementations
806// ============================================================================
807
808// ----------------------------------------------------------------------------
809// wxConsoleAppTraitsBase
810// ----------------------------------------------------------------------------
811
812#if wxUSE_LOG
813
814wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
815{
816 return new wxLogStderr;
817}
818
819#endif // wxUSE_LOG
820
821wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
822{
823 return new wxMessageOutputStderr;
824}
825
826#if wxUSE_FONTMAP
827
828wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
829{
830 return (wxFontMapper *)new wxFontMapperBase;
831}
832
833#endif // wxUSE_FONTMAP
834
f0244295
VZ
835wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
836{
837 // console applications don't use renderers
838 return NULL;
839}
840
e2478fde
VZ
841bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
842{
843 return wxAppTraitsBase::ShowAssertDialog(msg);
844}
845
846bool wxConsoleAppTraitsBase::HasStderr()
847{
848 // console applications always have stderr, even under Mac/Windows
849 return true;
850}
851
e2478fde
VZ
852// ----------------------------------------------------------------------------
853// wxAppTraits
854// ----------------------------------------------------------------------------
855
d254213e
PC
856#if wxUSE_THREADS
857void wxMutexGuiEnterImpl();
858void wxMutexGuiLeaveImpl();
859
860void wxAppTraitsBase::MutexGuiEnter()
861{
862 wxMutexGuiEnterImpl();
863}
864
865void wxAppTraitsBase::MutexGuiLeave()
866{
867 wxMutexGuiLeaveImpl();
868}
869
870void WXDLLIMPEXP_BASE wxMutexGuiEnter()
871{
96b2cbe8
VZ
872 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
873 if ( traits )
874 traits->MutexGuiEnter();
d254213e
PC
875}
876
877void WXDLLIMPEXP_BASE wxMutexGuiLeave()
878{
96b2cbe8
VZ
879 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
880 if ( traits )
881 traits->MutexGuiLeave();
d254213e
PC
882}
883#endif // wxUSE_THREADS
884
db9febdf 885bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
e2478fde 886{
657a8a35 887#if wxDEBUG_LEVEL
021efd65 888 wxString msg;
db9febdf
RR
889
890#if wxUSE_STACKWALKER
db9febdf
RR
891 const wxString stackTrace = GetAssertStackTrace();
892 if ( !stackTrace.empty() )
021efd65 893 {
9a83f860 894 msg << wxT("\n\nCall stack:\n") << stackTrace;
021efd65
VZ
895
896 wxMessageOutputDebug().Output(msg);
897 }
db9febdf
RR
898#endif // wxUSE_STACKWALKER
899
021efd65 900 return DoShowAssertDialog(msgOriginal + msg);
657a8a35
VZ
901#else // !wxDEBUG_LEVEL
902 wxUnusedVar(msgOriginal);
903
904 return false;
905#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
e2478fde
VZ
906}
907
db9febdf
RR
908#if wxUSE_STACKWALKER
909wxString wxAppTraitsBase::GetAssertStackTrace()
910{
657a8a35 911#if wxDEBUG_LEVEL
021efd65 912
d98a58c5 913#if !defined(__WINDOWS__)
021efd65
VZ
914 // on Unix stack frame generation may take some time, depending on the
915 // size of the executable mainly... warn the user that we are working
916 wxFprintf(stderr, "Collecting stack trace information, please wait...");
917 fflush(stderr);
d98a58c5 918#endif // !__WINDOWS__
021efd65
VZ
919
920
db9febdf
RR
921 wxString stackTrace;
922
923 class StackDump : public wxStackWalker
924 {
925 public:
926 StackDump() { }
927
928 const wxString& GetStackTrace() const { return m_stackTrace; }
929
930 protected:
931 virtual void OnStackFrame(const wxStackFrame& frame)
932 {
933 m_stackTrace << wxString::Format
934 (
9a83f860 935 wxT("[%02d] "),
db9febdf
RR
936 wx_truncate_cast(int, frame.GetLevel())
937 );
938
939 wxString name = frame.GetName();
940 if ( !name.empty() )
941 {
9a83f860 942 m_stackTrace << wxString::Format(wxT("%-40s"), name.c_str());
db9febdf
RR
943 }
944 else
945 {
9a83f860 946 m_stackTrace << wxString::Format(wxT("%p"), frame.GetAddress());
db9febdf
RR
947 }
948
949 if ( frame.HasSourceLocation() )
950 {
9a83f860 951 m_stackTrace << wxT('\t')
db9febdf 952 << frame.GetFileName()
9a83f860 953 << wxT(':')
db9febdf
RR
954 << frame.GetLine();
955 }
956
9a83f860 957 m_stackTrace << wxT('\n');
db9febdf
RR
958 }
959
960 private:
961 wxString m_stackTrace;
962 };
963
964 // don't show more than maxLines or we could get a dialog too tall to be
965 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
966 // characters it is still only 300 pixels...
967 static const int maxLines = 20;
968
969 StackDump dump;
1114902a 970 dump.Walk(8, maxLines); // 8 is chosen to hide all OnAssert() calls
db9febdf
RR
971 stackTrace = dump.GetStackTrace();
972
973 const int count = stackTrace.Freq(wxT('\n'));
974 for ( int i = 0; i < count - maxLines; i++ )
975 stackTrace = stackTrace.BeforeLast(wxT('\n'));
976
977 return stackTrace;
657a8a35
VZ
978#else // !wxDEBUG_LEVEL
979 // this function is still present for ABI-compatibility even in debug level
980 // 0 build but is not used there and so can simply do nothing
981 return wxString();
982#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
db9febdf
RR
983}
984#endif // wxUSE_STACKWALKER
985
986
e2478fde
VZ
987// ============================================================================
988// global functions implementation
989// ============================================================================
990
991void wxExit()
992{
993 if ( wxTheApp )
994 {
995 wxTheApp->Exit();
996 }
997 else
998 {
999 // what else can we do?
1000 exit(-1);
1001 }
1002}
1003
1004void wxWakeUpIdle()
1005{
1006 if ( wxTheApp )
1007 {
1008 wxTheApp->WakeUpIdle();
1009 }
1010 //else: do nothing, what can we do?
1011}
1012
e2478fde
VZ
1013// wxASSERT() helper
1014bool wxAssertIsEqual(int x, int y)
1015{
1016 return x == y;
1017}
1018
975dc691
VZ
1019void wxAbort()
1020{
1021#ifdef __WXWINCE__
1022 ExitThread(3);
1023#else
1024 abort();
1025#endif
1026}
1027
657a8a35
VZ
1028#if wxDEBUG_LEVEL
1029
e2478fde 1030// break into the debugger
55fd62c1
VZ
1031#ifndef wxTrap
1032
e2478fde
VZ
1033void wxTrap()
1034{
d98a58c5 1035#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
e2478fde 1036 DebugBreak();
f0756afe
DE
1037#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1038 Debugger();
e2478fde
VZ
1039#elif defined(__UNIX__)
1040 raise(SIGTRAP);
1041#else
1042 // TODO
1043#endif // Win/Unix
1044}
1045
55fd62c1
VZ
1046#endif // wxTrap already defined as a macro
1047
657a8a35
VZ
1048// default assert handler
1049static void
1050wxDefaultAssertHandler(const wxString& file,
1051 int line,
1052 const wxString& func,
1053 const wxString& cond,
1054 const wxString& msg)
e2478fde 1055{
4d1ea475
VZ
1056 // If this option is set, we should abort immediately when assert happens.
1057 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
d58c7af8 1058 wxAbort();
4d1ea475 1059
e2478fde 1060 // FIXME MT-unsafe
000eea7a 1061 static int s_bInAssert = 0;
e2478fde 1062
000eea7a
VZ
1063 wxRecursionGuard guard(s_bInAssert);
1064 if ( guard.IsInside() )
e2478fde 1065 {
000eea7a 1066 // can't use assert here to avoid infinite loops, so just trap
e2478fde
VZ
1067 wxTrap();
1068
e2478fde
VZ
1069 return;
1070 }
1071
e2478fde
VZ
1072 if ( !wxTheApp )
1073 {
1074 // by default, show the assert dialog box -- we can't customize this
1075 // behaviour
657a8a35 1076 ShowAssertDialog(file, line, func, cond, msg);
e2478fde
VZ
1077 }
1078 else
1079 {
1080 // let the app process it as it wants
0accd1cf 1081 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
657a8a35
VZ
1082 wxTheApp->OnAssertFailure(file.c_str(), line, func.c_str(),
1083 cond.c_str(), msg.c_str());
e2478fde 1084 }
e2478fde
VZ
1085}
1086
657a8a35
VZ
1087wxAssertHandler_t wxTheAssertHandler = wxDefaultAssertHandler;
1088
7d9550df
VZ
1089void wxSetDefaultAssertHandler()
1090{
1091 wxTheAssertHandler = wxDefaultAssertHandler;
1092}
1093
657a8a35
VZ
1094void wxOnAssert(const wxString& file,
1095 int line,
1096 const wxString& func,
1097 const wxString& cond,
1098 const wxString& msg)
0accd1cf 1099{
657a8a35 1100 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1101}
1102
657a8a35
VZ
1103void wxOnAssert(const wxString& file,
1104 int line,
1105 const wxString& func,
1106 const wxString& cond)
0accd1cf 1107{
657a8a35 1108 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1109}
1110
657a8a35
VZ
1111void wxOnAssert(const wxChar *file,
1112 int line,
1113 const char *func,
1114 const wxChar *cond,
1115 const wxChar *msg)
0accd1cf 1116{
657a8a35
VZ
1117 // this is the backwards-compatible version (unless we don't use Unicode)
1118 // so it could be called directly from the user code and this might happen
1119 // even when wxTheAssertHandler is NULL
1120#if wxUSE_UNICODE
1121 if ( wxTheAssertHandler )
1122#endif // wxUSE_UNICODE
1123 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1124}
1125
657a8a35
VZ
1126void wxOnAssert(const char *file,
1127 int line,
1128 const char *func,
1129 const char *cond,
1130 const wxString& msg)
fbaf7d45 1131{
657a8a35 1132 wxTheAssertHandler(file, line, func, cond, msg);
fbaf7d45
VS
1133}
1134
657a8a35
VZ
1135void wxOnAssert(const char *file,
1136 int line,
1137 const char *func,
1138 const char *cond,
2b232d20
VZ
1139 const wxCStrData& msg)
1140{
657a8a35 1141 wxTheAssertHandler(file, line, func, cond, msg);
2b232d20
VZ
1142}
1143
0accd1cf 1144#if wxUSE_UNICODE
657a8a35
VZ
1145void wxOnAssert(const char *file,
1146 int line,
1147 const char *func,
1148 const char *cond)
0accd1cf 1149{
657a8a35 1150 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1151}
1152
657a8a35
VZ
1153void wxOnAssert(const char *file,
1154 int line,
1155 const char *func,
1156 const char *cond,
1157 const char *msg)
0accd1cf 1158{
657a8a35 1159 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1160}
1161
657a8a35
VZ
1162void wxOnAssert(const char *file,
1163 int line,
1164 const char *func,
1165 const char *cond,
1166 const wxChar *msg)
0accd1cf 1167{
657a8a35 1168 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1169}
1170#endif // wxUSE_UNICODE
1171
657a8a35 1172#endif // wxDEBUG_LEVEL
e2478fde
VZ
1173
1174// ============================================================================
1175// private functions implementation
1176// ============================================================================
1177
1178#ifdef __WXDEBUG__
1179
1180static void LINKAGEMODE SetTraceMasks()
1181{
1182#if wxUSE_LOG
1183 wxString mask;
1184 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
1185 {
1186 wxStringTokenizer tkn(mask, wxT(",;:"));
1187 while ( tkn.HasMoreTokens() )
1188 wxLog::AddTraceMask(tkn.GetNextToken());
1189 }
1190#endif // wxUSE_LOG
1191}
1192
657a8a35
VZ
1193#endif // __WXDEBUG__
1194
1195#if wxDEBUG_LEVEL
1196
55fd62c1
VZ
1197bool wxTrapInAssert = false;
1198
6ef1b2a1 1199static
e2478fde
VZ
1200bool DoShowAssertDialog(const wxString& msg)
1201{
d98a58c5
VZ
1202 // under Windows we can show the dialog even in the console mode
1203#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
e2478fde
VZ
1204 wxString msgDlg(msg);
1205
657a8a35
VZ
1206 // this message is intentionally not translated -- it is for developers
1207 // only -- and the less code we use here, less is the danger of recursively
1208 // asserting and dying
e2478fde
VZ
1209 msgDlg += wxT("\nDo you want to stop the program?\n")
1210 wxT("You can also choose [Cancel] to suppress ")
1211 wxT("further warnings.");
1212
b2b6da49 1213 switch ( ::MessageBox(NULL, msgDlg.t_str(), wxT("wxWidgets Debug Alert"),
e2478fde
VZ
1214 MB_YESNOCANCEL | MB_ICONSTOP ) )
1215 {
1216 case IDYES:
55fd62c1
VZ
1217 // If we called wxTrap() directly from here, the programmer would
1218 // see this function and a few more calls between his own code and
1219 // it in the stack trace which would be perfectly useless and often
1220 // confusing. So instead just set the flag here and let the macros
1221 // defined in wx/debug.h call wxTrap() themselves, this ensures
1222 // that the debugger will show the line in the user code containing
1223 // the failing assert.
1224 wxTrapInAssert = true;
e2478fde
VZ
1225 break;
1226
1227 case IDCANCEL:
1228 // stop the asserts
1229 return true;
1230
1231 //case IDNO: nothing to do
1232 }
d98a58c5 1233#else // !__WINDOWS__
021efd65 1234 wxUnusedVar(msg);
d98a58c5 1235#endif // __WINDOWS__/!__WINDOWS__
e2478fde 1236
021efd65 1237 // continue with the asserts by default
e2478fde
VZ
1238 return false;
1239}
1240
657a8a35 1241// show the standard assert dialog
4a92d4bc 1242static
657a8a35
VZ
1243void ShowAssertDialog(const wxString& file,
1244 int line,
1245 const wxString& func,
1246 const wxString& cond,
1247 const wxString& msgUser,
4a92d4bc
VZ
1248 wxAppTraits *traits)
1249{
1250 // this variable can be set to true to suppress "assert failure" messages
1251 static bool s_bNoAsserts = false;
1252
1253 wxString msg;
1254 msg.reserve(2048);
1255
1256 // make life easier for people using VC++ IDE by using this format: like
1257 // this, clicking on the message will take us immediately to the place of
1258 // the failed assert
657a8a35 1259 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), file, line, cond);
4a92d4bc 1260
dfa0b52f 1261 // add the function name, if any
657a8a35 1262 if ( !func.empty() )
9a83f860 1263 msg << wxT(" in ") << func << wxT("()");
dfa0b52f
VZ
1264
1265 // and the message itself
657a8a35 1266 if ( !msgUser.empty() )
2c9b3131 1267 {
9a83f860 1268 msg << wxT(": ") << msgUser;
2c9b3131 1269 }
4a92d4bc
VZ
1270 else // no message given
1271 {
9a83f860 1272 msg << wxT('.');
4a92d4bc
VZ
1273 }
1274
e2478fde
VZ
1275#if wxUSE_THREADS
1276 // if we are not in the main thread, output the assert directly and trap
1277 // since dialogs cannot be displayed
1278 if ( !wxThread::IsMain() )
1279 {
2d8e0096 1280 msg += wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
e2478fde
VZ
1281 }
1282#endif // wxUSE_THREADS
1283
2d8e0096
VZ
1284 // log the assert in any case
1285 wxMessageOutputDebug().Output(msg);
1286
e2478fde
VZ
1287 if ( !s_bNoAsserts )
1288 {
e2478fde
VZ
1289 if ( traits )
1290 {
1291 // delegate showing assert dialog (if possible) to that class
1292 s_bNoAsserts = traits->ShowAssertDialog(msg);
1293 }
1294 else // no traits object
1295 {
1296 // fall back to the function of last resort
1297 s_bNoAsserts = DoShowAssertDialog(msg);
1298 }
1299 }
1300}
1301
657a8a35 1302#endif // wxDEBUG_LEVEL