]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
make sure it is compilable w/o menus (eg on iPhone)
[wxWidgets.git] / src / common / appbase.cpp
CommitLineData
e2478fde 1///////////////////////////////////////////////////////////////////////////////
8ecff181 2// Name: src/common/appbase.cpp
e0954e72 3// Purpose: implements wxAppConsoleBase class
e2478fde
VZ
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 19.06.2003 (extracted from common/appcmn.cpp)
7// RCS-ID: $Id$
8// Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
0a53b9b8 9// License: wxWindows license
e2478fde
VZ
10///////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20// for compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
24 #pragma hdrstop
25#endif
26
27#ifndef WX_PRECOMP
57bd4c60
WS
28 #ifdef __WXMSW__
29 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
30 #endif
8ecff181 31 #include "wx/list.h"
8df6de97
VS
32 #include "wx/app.h"
33 #include "wx/intl.h"
86f8d1a8 34 #include "wx/log.h"
de6185e2 35 #include "wx/utils.h"
0cb7e05c 36 #include "wx/wxcrtvararg.h"
e2478fde
VZ
37#endif //WX_PRECOMP
38
39#include "wx/apptrait.h"
40#include "wx/cmdline.h"
41#include "wx/confbase.h"
b46b1d59 42#include "wx/evtloop.h"
ce39c39e 43#include "wx/filename.h"
e2478fde 44#include "wx/msgout.h"
664e1314 45#include "wx/scopedptr.h"
e2478fde 46#include "wx/tokenzr.h"
204abcd4 47#include "wx/thread.h"
e2478fde 48
1663c655
VZ
49#if wxUSE_EXCEPTIONS && wxUSE_STL
50 #include <exception>
51 #include <typeinfo>
52#endif
53
9b4da627 54#ifndef __WXPALMOS5__
e2478fde
VZ
55#if !defined(__WXMSW__) || defined(__WXMICROWIN__)
56 #include <signal.h> // for SIGTRAP used by wxTrap()
57#endif //Win/Unix
58
0e5ab030 59#include <locale.h>
9b4da627 60#endif // ! __WXPALMOS5__
0e5ab030 61
1c193821
JS
62#if wxUSE_FONTMAP
63 #include "wx/fontmap.h"
64#endif // wxUSE_FONTMAP
65
657a8a35 66#if wxDEBUG_LEVEL
7b1c3469 67 #if wxUSE_STACKWALKER
6c8f8d92 68 #include "wx/stackwalk.h"
4a92d4bc
VZ
69 #ifdef __WXMSW__
70 #include "wx/msw/debughlp.h"
71 #endif
6c8f8d92 72 #endif // wxUSE_STACKWALKER
000eea7a
VZ
73
74 #include "wx/recguard.h"
657a8a35 75#endif // wxDEBUG_LEVEL
6c8f8d92 76
121aea46
MW
77// wxABI_VERSION can be defined when compiling applications but it should be
78// left undefined when compiling the library itself, it is then set to its
79// default value in version.h
80#if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
81#error "wxABI_VERSION should not be defined when compiling the library"
82#endif
83
e2478fde
VZ
84// ----------------------------------------------------------------------------
85// private functions prototypes
86// ----------------------------------------------------------------------------
87
657a8a35 88#if wxDEBUG_LEVEL
e2478fde
VZ
89 // really just show the assert dialog
90 static bool DoShowAssertDialog(const wxString& msg);
91
92 // prepare for showing the assert dialog, use the given traits or
93 // DoShowAssertDialog() as last fallback to really show it
94 static
657a8a35
VZ
95 void ShowAssertDialog(const wxString& file,
96 int line,
97 const wxString& func,
98 const wxString& cond,
99 const wxString& msg,
e2478fde 100 wxAppTraits *traits = NULL);
657a8a35 101#endif // wxDEBUG_LEVEL
e2478fde 102
657a8a35 103#ifdef __WXDEBUG__
e2478fde
VZ
104 // turn on the trace masks specified in the env variable WXTRACE
105 static void LINKAGEMODE SetTraceMasks();
106#endif // __WXDEBUG__
107
108// ----------------------------------------------------------------------------
109// global vars
110// ----------------------------------------------------------------------------
111
e0954e72 112wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
e2478fde 113
e0954e72 114wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
e2478fde 115
51fe4b60
VZ
116wxSocketManager *wxAppTraitsBase::ms_manager = NULL;
117
3185abc2
VZ
118WXDLLIMPEXP_DATA_BASE(wxList) wxPendingDelete;
119
b46b1d59
VZ
120// ----------------------------------------------------------------------------
121// wxEventLoopPtr
122// ----------------------------------------------------------------------------
123
124// this defines wxEventLoopPtr
2ddff00c 125wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
b46b1d59 126
e2478fde 127// ============================================================================
e0954e72 128// wxAppConsoleBase implementation
e2478fde
VZ
129// ============================================================================
130
131// ----------------------------------------------------------------------------
132// ctor/dtor
133// ----------------------------------------------------------------------------
134
e0954e72 135wxAppConsoleBase::wxAppConsoleBase()
e2478fde
VZ
136{
137 m_traits = NULL;
b46b1d59 138 m_mainLoop = NULL;
cae9e7b1 139 m_bDoPendingEventProcessing = true;
e2478fde 140
5c33522f 141 ms_appInstance = static_cast<wxAppConsole *>(this);
e2478fde
VZ
142
143#ifdef __WXDEBUG__
144 SetTraceMasks();
bc334f39
RD
145#if wxUSE_UNICODE
146 // In unicode mode the SetTraceMasks call can cause an apptraits to be
147 // created, but since we are still in the constructor the wrong kind will
148 // be created for GUI apps. Destroy it so it can be created again later.
149 delete m_traits;
150 m_traits = NULL;
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{
aea33a3e
VZ
216 if ( m_mainLoop )
217 {
218 delete m_mainLoop;
219 m_mainLoop = NULL;
220 }
94826170
VZ
221}
222
e2478fde
VZ
223// ----------------------------------------------------------------------------
224// OnXXX() callbacks
225// ----------------------------------------------------------------------------
226
e0954e72 227bool wxAppConsoleBase::OnInit()
e2478fde
VZ
228{
229#if wxUSE_CMDLINE_PARSER
230 wxCmdLineParser parser(argc, argv);
231
232 OnInitCmdLine(parser);
233
234 bool cont;
4629016d 235 switch ( parser.Parse(false /* don't show usage */) )
e2478fde
VZ
236 {
237 case -1:
238 cont = OnCmdLineHelp(parser);
239 break;
240
241 case 0:
242 cont = OnCmdLineParsed(parser);
243 break;
244
245 default:
246 cont = OnCmdLineError(parser);
247 break;
248 }
249
250 if ( !cont )
4629016d 251 return false;
e2478fde
VZ
252#endif // wxUSE_CMDLINE_PARSER
253
4629016d 254 return true;
e2478fde
VZ
255}
256
e0954e72 257int wxAppConsoleBase::OnRun()
b46b1d59
VZ
258{
259 return MainLoop();
8ac09e52 260}
b46b1d59 261
e0954e72 262int wxAppConsoleBase::OnExit()
e2478fde
VZ
263{
264#if wxUSE_CONFIG
265 // delete the config object if any (don't use Get() here, but Set()
266 // because Get() could create a new config object)
d3b9f782 267 delete wxConfigBase::Set(NULL);
e2478fde
VZ
268#endif // wxUSE_CONFIG
269
e2478fde
VZ
270 return 0;
271}
272
e0954e72 273void wxAppConsoleBase::Exit()
e2478fde 274{
b46b1d59
VZ
275 if (m_mainLoop != NULL)
276 ExitMainLoop();
277 else
278 exit(-1);
e2478fde
VZ
279}
280
281// ----------------------------------------------------------------------------
282// traits stuff
283// ----------------------------------------------------------------------------
284
e0954e72 285wxAppTraits *wxAppConsoleBase::CreateTraits()
e2478fde 286{
7843d11b 287 return new wxConsoleAppTraits;
e2478fde
VZ
288}
289
e0954e72 290wxAppTraits *wxAppConsoleBase::GetTraits()
e2478fde
VZ
291{
292 // FIXME-MT: protect this with a CS?
293 if ( !m_traits )
294 {
295 m_traits = CreateTraits();
296
9a83f860 297 wxASSERT_MSG( m_traits, wxT("wxApp::CreateTraits() failed?") );
e2478fde
VZ
298 }
299
300 return m_traits;
301}
302
96b2cbe8
VZ
303/* static */
304wxAppTraits *wxAppConsoleBase::GetTraitsIfExists()
305{
306 wxAppConsole * const app = GetInstance();
307 return app ? app->GetTraits() : NULL;
308}
309
e2478fde 310// ----------------------------------------------------------------------------
dde19c21 311// wxEventLoop redirection
e2478fde
VZ
312// ----------------------------------------------------------------------------
313
e0954e72 314int wxAppConsoleBase::MainLoop()
e2478fde 315{
2ddff00c 316 wxEventLoopBaseTiedPtr mainLoop(&m_mainLoop, CreateMainLoop());
b46b1d59
VZ
317
318 return m_mainLoop ? m_mainLoop->Run() : -1;
319}
320
e0954e72 321void wxAppConsoleBase::ExitMainLoop()
b46b1d59
VZ
322{
323 // we should exit from the main event loop, not just any currently active
324 // (e.g. modal dialog) event loop
325 if ( m_mainLoop && m_mainLoop->IsRunning() )
326 {
327 m_mainLoop->Exit(0);
328 }
329}
330
e0954e72 331bool wxAppConsoleBase::Pending()
b46b1d59
VZ
332{
333 // use the currently active message loop here, not m_mainLoop, because if
334 // we're showing a modal dialog (with its own event loop) currently the
335 // main event loop is not running anyhow
2ddff00c 336 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
b46b1d59
VZ
337
338 return loop && loop->Pending();
339}
340
e0954e72 341bool wxAppConsoleBase::Dispatch()
b46b1d59
VZ
342{
343 // see comment in Pending()
2ddff00c 344 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
b46b1d59
VZ
345
346 return loop && loop->Dispatch();
347}
8ecff181 348
dde19c21
FM
349bool wxAppConsoleBase::Yield(bool onlyIfNeeded)
350{
351 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
d48b06bd 352
dde19c21 353 return loop && loop->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
a758f601 377 return event.MoreRequested();
dde19c21 378}
14eb37a0 379
3185abc2
VZ
380bool wxAppConsoleBase::UsesEventLoop() const
381{
382 // in console applications we don't know whether we're going to have an
383 // event loop so assume we won't -- unless we already have one running
384 return wxEventLoopBase::GetActive() != NULL;
385}
386
dde19c21
FM
387// ----------------------------------------------------------------------------
388// events
389// ----------------------------------------------------------------------------
b46b1d59 390
dde19c21
FM
391/* static */
392bool wxAppConsoleBase::IsMainLoopRunning()
393{
394 const wxAppConsole * const app = GetInstance();
395
396 return app && app->m_mainLoop != NULL;
b46b1d59
VZ
397}
398
e0954e72 399int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
e2478fde
VZ
400{
401 // process the events normally by default
402 return -1;
403}
404
8e40ed85
FM
405void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler* toDelay)
406{
407 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
408
409 // move the handler from the list of handlers with processable pending events
410 // to the list of handlers with pending events which needs to be processed later
411 m_handlersWithPendingEvents.Remove(toDelay);
412
413 if (m_handlersWithPendingDelayedEvents.Index(toDelay) == wxNOT_FOUND)
414 m_handlersWithPendingDelayedEvents.Add(toDelay);
415
416 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
417}
418
419void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler* toRemove)
420{
421 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
422
423 if (m_handlersWithPendingEvents.Index(toRemove) != wxNOT_FOUND)
424 {
425 m_handlersWithPendingEvents.Remove(toRemove);
426
427 // check that the handler was present only once in the list
428 wxASSERT_MSG( m_handlersWithPendingEvents.Index(toRemove) == wxNOT_FOUND,
429 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
430 }
431 //else: it wasn't in this list at all, it's ok
432
433 if (m_handlersWithPendingDelayedEvents.Index(toRemove) != wxNOT_FOUND)
434 {
435 m_handlersWithPendingDelayedEvents.Remove(toRemove);
436
437 // check that the handler was present only once in the list
438 wxASSERT_MSG( m_handlersWithPendingDelayedEvents.Index(toRemove) == wxNOT_FOUND,
439 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
440 }
441 //else: it wasn't in this list at all, it's ok
442
443 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
444}
445
446void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler* toAppend)
447{
448 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
449
450 if ( m_handlersWithPendingEvents.Index(toAppend) == wxNOT_FOUND )
451 m_handlersWithPendingEvents.Add(toAppend);
452
453 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
454}
455
456bool wxAppConsoleBase::HasPendingEvents() const
457{
458 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase*>(this)->m_handlersWithPendingEventsLocker);
459
460 bool has = !m_handlersWithPendingEvents.IsEmpty();
461
462 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase*>(this)->m_handlersWithPendingEventsLocker);
463
464 return has;
465}
466
467void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
468{
cae9e7b1 469 m_bDoPendingEventProcessing = false;
8e40ed85
FM
470}
471
472void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
473{
cae9e7b1 474 m_bDoPendingEventProcessing = true;
8e40ed85
FM
475}
476
477void wxAppConsoleBase::ProcessPendingEvents()
478{
3185abc2 479 if ( m_bDoPendingEventProcessing )
8e40ed85 480 {
3185abc2 481 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
8e40ed85 482
3185abc2
VZ
483 wxCHECK_RET( m_handlersWithPendingDelayedEvents.IsEmpty(),
484 "this helper list should be empty" );
8e40ed85 485
3185abc2
VZ
486 // iterate until the list becomes empty: the handlers remove themselves
487 // from it when they don't have any more pending events
488 while (!m_handlersWithPendingEvents.IsEmpty())
489 {
490 // In ProcessPendingEvents(), new handlers might be added
491 // and we can safely leave the critical section here.
492 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
493
494 // NOTE: we always call ProcessPendingEvents() on the first event handler
495 // with pending events because handlers auto-remove themselves
496 // from this list (see RemovePendingEventHandler) if they have no
497 // more pending events.
498 m_handlersWithPendingEvents[0]->ProcessPendingEvents();
499
500 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
501 }
502
503 // now the wxHandlersWithPendingEvents is surely empty; however some event
504 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
505 // because of a selective wxYield call in progress.
506 // Now we need to move them back to wxHandlersWithPendingEvents so the next
507 // call to this function has the chance of processing them:
508 if (!m_handlersWithPendingDelayedEvents.IsEmpty())
509 {
510 WX_APPEND_ARRAY(m_handlersWithPendingEvents, m_handlersWithPendingDelayedEvents);
511 m_handlersWithPendingDelayedEvents.Clear();
512 }
8e40ed85 513
3185abc2 514 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
8e40ed85
FM
515 }
516
3185abc2
VZ
517 // Garbage collect all objects previously scheduled for destruction.
518 DeletePendingObjects();
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
e2478fde
VZ
783// ============================================================================
784// other classes implementations
785// ============================================================================
786
787// ----------------------------------------------------------------------------
788// wxConsoleAppTraitsBase
789// ----------------------------------------------------------------------------
790
791#if wxUSE_LOG
792
793wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
794{
795 return new wxLogStderr;
796}
797
798#endif // wxUSE_LOG
799
800wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
801{
802 return new wxMessageOutputStderr;
803}
804
805#if wxUSE_FONTMAP
806
807wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
808{
809 return (wxFontMapper *)new wxFontMapperBase;
810}
811
812#endif // wxUSE_FONTMAP
813
f0244295
VZ
814wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
815{
816 // console applications don't use renderers
817 return NULL;
818}
819
e2478fde
VZ
820bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
821{
822 return wxAppTraitsBase::ShowAssertDialog(msg);
823}
824
825bool wxConsoleAppTraitsBase::HasStderr()
826{
827 // console applications always have stderr, even under Mac/Windows
828 return true;
829}
830
e2478fde
VZ
831// ----------------------------------------------------------------------------
832// wxAppTraits
833// ----------------------------------------------------------------------------
834
6c4f5ea5 835#if wxUSE_INTL
d774f916
VZ
836void wxAppTraitsBase::SetLocale()
837{
d6f2a891 838 wxSetlocale(LC_ALL, "");
cb352236 839 wxUpdateLocaleIsUtf8();
d774f916 840}
6c4f5ea5 841#endif
d774f916 842
d254213e
PC
843#if wxUSE_THREADS
844void wxMutexGuiEnterImpl();
845void wxMutexGuiLeaveImpl();
846
847void wxAppTraitsBase::MutexGuiEnter()
848{
849 wxMutexGuiEnterImpl();
850}
851
852void wxAppTraitsBase::MutexGuiLeave()
853{
854 wxMutexGuiLeaveImpl();
855}
856
857void WXDLLIMPEXP_BASE wxMutexGuiEnter()
858{
96b2cbe8
VZ
859 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
860 if ( traits )
861 traits->MutexGuiEnter();
d254213e
PC
862}
863
864void WXDLLIMPEXP_BASE wxMutexGuiLeave()
865{
96b2cbe8
VZ
866 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
867 if ( traits )
868 traits->MutexGuiLeave();
d254213e
PC
869}
870#endif // wxUSE_THREADS
871
db9febdf 872bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
e2478fde 873{
657a8a35 874#if wxDEBUG_LEVEL
db9febdf
RR
875 wxString msg = msgOriginal;
876
877#if wxUSE_STACKWALKER
878#if !defined(__WXMSW__)
879 // on Unix stack frame generation may take some time, depending on the
880 // size of the executable mainly... warn the user that we are working
881 wxFprintf(stderr, wxT("[Debug] Generating a stack trace... please wait"));
882 fflush(stderr);
883#endif
884
885 const wxString stackTrace = GetAssertStackTrace();
886 if ( !stackTrace.empty() )
9a83f860 887 msg << wxT("\n\nCall stack:\n") << stackTrace;
db9febdf
RR
888#endif // wxUSE_STACKWALKER
889
e2478fde 890 return DoShowAssertDialog(msg);
657a8a35
VZ
891#else // !wxDEBUG_LEVEL
892 wxUnusedVar(msgOriginal);
893
894 return false;
895#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
e2478fde
VZ
896}
897
db9febdf
RR
898#if wxUSE_STACKWALKER
899wxString wxAppTraitsBase::GetAssertStackTrace()
900{
657a8a35 901#if wxDEBUG_LEVEL
db9febdf
RR
902 wxString stackTrace;
903
904 class StackDump : public wxStackWalker
905 {
906 public:
907 StackDump() { }
908
909 const wxString& GetStackTrace() const { return m_stackTrace; }
910
911 protected:
912 virtual void OnStackFrame(const wxStackFrame& frame)
913 {
914 m_stackTrace << wxString::Format
915 (
9a83f860 916 wxT("[%02d] "),
db9febdf
RR
917 wx_truncate_cast(int, frame.GetLevel())
918 );
919
920 wxString name = frame.GetName();
921 if ( !name.empty() )
922 {
9a83f860 923 m_stackTrace << wxString::Format(wxT("%-40s"), name.c_str());
db9febdf
RR
924 }
925 else
926 {
9a83f860 927 m_stackTrace << wxString::Format(wxT("%p"), frame.GetAddress());
db9febdf
RR
928 }
929
930 if ( frame.HasSourceLocation() )
931 {
9a83f860 932 m_stackTrace << wxT('\t')
db9febdf 933 << frame.GetFileName()
9a83f860 934 << wxT(':')
db9febdf
RR
935 << frame.GetLine();
936 }
937
9a83f860 938 m_stackTrace << wxT('\n');
db9febdf
RR
939 }
940
941 private:
942 wxString m_stackTrace;
943 };
944
945 // don't show more than maxLines or we could get a dialog too tall to be
946 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
947 // characters it is still only 300 pixels...
948 static const int maxLines = 20;
949
950 StackDump dump;
951 dump.Walk(2, maxLines); // don't show OnAssert() call itself
952 stackTrace = dump.GetStackTrace();
953
954 const int count = stackTrace.Freq(wxT('\n'));
955 for ( int i = 0; i < count - maxLines; i++ )
956 stackTrace = stackTrace.BeforeLast(wxT('\n'));
957
958 return stackTrace;
657a8a35
VZ
959#else // !wxDEBUG_LEVEL
960 // this function is still present for ABI-compatibility even in debug level
961 // 0 build but is not used there and so can simply do nothing
962 return wxString();
963#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
db9febdf
RR
964}
965#endif // wxUSE_STACKWALKER
966
967
e2478fde
VZ
968// ============================================================================
969// global functions implementation
970// ============================================================================
971
972void wxExit()
973{
974 if ( wxTheApp )
975 {
976 wxTheApp->Exit();
977 }
978 else
979 {
980 // what else can we do?
981 exit(-1);
982 }
983}
984
985void wxWakeUpIdle()
986{
987 if ( wxTheApp )
988 {
989 wxTheApp->WakeUpIdle();
990 }
991 //else: do nothing, what can we do?
992}
993
e2478fde
VZ
994// wxASSERT() helper
995bool wxAssertIsEqual(int x, int y)
996{
997 return x == y;
998}
999
657a8a35
VZ
1000#if wxDEBUG_LEVEL
1001
e2478fde
VZ
1002// break into the debugger
1003void wxTrap()
1004{
1005#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1006 DebugBreak();
f0756afe
DE
1007#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1008 Debugger();
e2478fde
VZ
1009#elif defined(__UNIX__)
1010 raise(SIGTRAP);
1011#else
1012 // TODO
1013#endif // Win/Unix
1014}
1015
657a8a35
VZ
1016// default assert handler
1017static void
1018wxDefaultAssertHandler(const wxString& file,
1019 int line,
1020 const wxString& func,
1021 const wxString& cond,
1022 const wxString& msg)
e2478fde
VZ
1023{
1024 // FIXME MT-unsafe
000eea7a 1025 static int s_bInAssert = 0;
e2478fde 1026
000eea7a
VZ
1027 wxRecursionGuard guard(s_bInAssert);
1028 if ( guard.IsInside() )
e2478fde 1029 {
000eea7a 1030 // can't use assert here to avoid infinite loops, so just trap
e2478fde
VZ
1031 wxTrap();
1032
e2478fde
VZ
1033 return;
1034 }
1035
e2478fde
VZ
1036 if ( !wxTheApp )
1037 {
1038 // by default, show the assert dialog box -- we can't customize this
1039 // behaviour
657a8a35 1040 ShowAssertDialog(file, line, func, cond, msg);
e2478fde
VZ
1041 }
1042 else
1043 {
1044 // let the app process it as it wants
0accd1cf 1045 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
657a8a35
VZ
1046 wxTheApp->OnAssertFailure(file.c_str(), line, func.c_str(),
1047 cond.c_str(), msg.c_str());
e2478fde 1048 }
e2478fde
VZ
1049}
1050
657a8a35
VZ
1051wxAssertHandler_t wxTheAssertHandler = wxDefaultAssertHandler;
1052
7d9550df
VZ
1053void wxSetDefaultAssertHandler()
1054{
1055 wxTheAssertHandler = wxDefaultAssertHandler;
1056}
1057
657a8a35
VZ
1058void wxOnAssert(const wxString& file,
1059 int line,
1060 const wxString& func,
1061 const wxString& cond,
1062 const wxString& msg)
0accd1cf 1063{
657a8a35 1064 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1065}
1066
657a8a35
VZ
1067void wxOnAssert(const wxString& file,
1068 int line,
1069 const wxString& func,
1070 const wxString& cond)
0accd1cf 1071{
657a8a35 1072 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1073}
1074
657a8a35
VZ
1075void wxOnAssert(const wxChar *file,
1076 int line,
1077 const char *func,
1078 const wxChar *cond,
1079 const wxChar *msg)
0accd1cf 1080{
657a8a35
VZ
1081 // this is the backwards-compatible version (unless we don't use Unicode)
1082 // so it could be called directly from the user code and this might happen
1083 // even when wxTheAssertHandler is NULL
1084#if wxUSE_UNICODE
1085 if ( wxTheAssertHandler )
1086#endif // wxUSE_UNICODE
1087 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1088}
1089
657a8a35
VZ
1090void wxOnAssert(const char *file,
1091 int line,
1092 const char *func,
1093 const char *cond,
1094 const wxString& msg)
fbaf7d45 1095{
657a8a35 1096 wxTheAssertHandler(file, line, func, cond, msg);
fbaf7d45
VS
1097}
1098
657a8a35
VZ
1099void wxOnAssert(const char *file,
1100 int line,
1101 const char *func,
1102 const char *cond,
2b232d20
VZ
1103 const wxCStrData& msg)
1104{
657a8a35 1105 wxTheAssertHandler(file, line, func, cond, msg);
2b232d20
VZ
1106}
1107
0accd1cf 1108#if wxUSE_UNICODE
657a8a35
VZ
1109void wxOnAssert(const char *file,
1110 int line,
1111 const char *func,
1112 const char *cond)
0accd1cf 1113{
657a8a35 1114 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1115}
1116
657a8a35
VZ
1117void wxOnAssert(const char *file,
1118 int line,
1119 const char *func,
1120 const char *cond,
1121 const char *msg)
0accd1cf 1122{
657a8a35 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 wxChar *msg)
0accd1cf 1131{
657a8a35 1132 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1133}
1134#endif // wxUSE_UNICODE
1135
657a8a35 1136#endif // wxDEBUG_LEVEL
e2478fde
VZ
1137
1138// ============================================================================
1139// private functions implementation
1140// ============================================================================
1141
1142#ifdef __WXDEBUG__
1143
1144static void LINKAGEMODE SetTraceMasks()
1145{
1146#if wxUSE_LOG
1147 wxString mask;
1148 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
1149 {
1150 wxStringTokenizer tkn(mask, wxT(",;:"));
1151 while ( tkn.HasMoreTokens() )
1152 wxLog::AddTraceMask(tkn.GetNextToken());
1153 }
1154#endif // wxUSE_LOG
1155}
1156
657a8a35
VZ
1157#endif // __WXDEBUG__
1158
1159#if wxDEBUG_LEVEL
1160
6ef1b2a1 1161static
e2478fde
VZ
1162bool DoShowAssertDialog(const wxString& msg)
1163{
1164 // under MSW we can show the dialog even in the console mode
1165#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1166 wxString msgDlg(msg);
1167
657a8a35
VZ
1168 // this message is intentionally not translated -- it is for developers
1169 // only -- and the less code we use here, less is the danger of recursively
1170 // asserting and dying
e2478fde
VZ
1171 msgDlg += wxT("\nDo you want to stop the program?\n")
1172 wxT("You can also choose [Cancel] to suppress ")
1173 wxT("further warnings.");
1174
9a83f860 1175 switch ( ::MessageBox(NULL, msgDlg.wx_str(), wxT("wxWidgets Debug Alert"),
e2478fde
VZ
1176 MB_YESNOCANCEL | MB_ICONSTOP ) )
1177 {
1178 case IDYES:
1179 wxTrap();
1180 break;
1181
1182 case IDCANCEL:
1183 // stop the asserts
1184 return true;
1185
1186 //case IDNO: nothing to do
1187 }
1188#else // !__WXMSW__
1189 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
1190 fflush(stderr);
1191
1192 // TODO: ask the user to enter "Y" or "N" on the console?
1193 wxTrap();
1194#endif // __WXMSW__/!__WXMSW__
1195
1196 // continue with the asserts
1197 return false;
1198}
1199
657a8a35 1200// show the standard assert dialog
4a92d4bc 1201static
657a8a35
VZ
1202void ShowAssertDialog(const wxString& file,
1203 int line,
1204 const wxString& func,
1205 const wxString& cond,
1206 const wxString& msgUser,
4a92d4bc
VZ
1207 wxAppTraits *traits)
1208{
1209 // this variable can be set to true to suppress "assert failure" messages
1210 static bool s_bNoAsserts = false;
1211
1212 wxString msg;
1213 msg.reserve(2048);
1214
1215 // make life easier for people using VC++ IDE by using this format: like
1216 // this, clicking on the message will take us immediately to the place of
1217 // the failed assert
657a8a35 1218 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), file, line, cond);
4a92d4bc 1219
dfa0b52f 1220 // add the function name, if any
657a8a35 1221 if ( !func.empty() )
9a83f860 1222 msg << wxT(" in ") << func << wxT("()");
dfa0b52f
VZ
1223
1224 // and the message itself
657a8a35 1225 if ( !msgUser.empty() )
2c9b3131 1226 {
9a83f860 1227 msg << wxT(": ") << msgUser;
2c9b3131 1228 }
4a92d4bc
VZ
1229 else // no message given
1230 {
9a83f860 1231 msg << wxT('.');
4a92d4bc
VZ
1232 }
1233
e2478fde
VZ
1234#if wxUSE_THREADS
1235 // if we are not in the main thread, output the assert directly and trap
1236 // since dialogs cannot be displayed
1237 if ( !wxThread::IsMain() )
1238 {
1239 msg += wxT(" [in child thread]");
1240
1241#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1242 msg << wxT("\r\n");
e0a050e3 1243 OutputDebugString(msg.wx_str());
e2478fde
VZ
1244#else
1245 // send to stderr
1246 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
1247 fflush(stderr);
1248#endif
1249 // He-e-e-e-elp!! we're asserting in a child thread
1250 wxTrap();
1251 }
6c8f8d92 1252 else
e2478fde
VZ
1253#endif // wxUSE_THREADS
1254
1255 if ( !s_bNoAsserts )
1256 {
1257 // send it to the normal log destination
9a83f860 1258 wxLogDebug(wxT("%s"), msg.c_str());
e2478fde
VZ
1259
1260 if ( traits )
1261 {
1262 // delegate showing assert dialog (if possible) to that class
1263 s_bNoAsserts = traits->ShowAssertDialog(msg);
1264 }
1265 else // no traits object
1266 {
1267 // fall back to the function of last resort
1268 s_bNoAsserts = DoShowAssertDialog(msg);
1269 }
1270 }
1271}
1272
657a8a35 1273#endif // wxDEBUG_LEVEL