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