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