]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
Split intl.h into intl.h, language.h and translation.h.
[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
021efd65 875 wxString msg;
db9febdf
RR
876
877#if wxUSE_STACKWALKER
db9febdf
RR
878 const wxString stackTrace = GetAssertStackTrace();
879 if ( !stackTrace.empty() )
021efd65 880 {
9a83f860 881 msg << wxT("\n\nCall stack:\n") << stackTrace;
021efd65
VZ
882
883 wxMessageOutputDebug().Output(msg);
884 }
db9febdf
RR
885#endif // wxUSE_STACKWALKER
886
021efd65 887 return DoShowAssertDialog(msgOriginal + msg);
657a8a35
VZ
888#else // !wxDEBUG_LEVEL
889 wxUnusedVar(msgOriginal);
890
891 return false;
892#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
e2478fde
VZ
893}
894
db9febdf
RR
895#if wxUSE_STACKWALKER
896wxString wxAppTraitsBase::GetAssertStackTrace()
897{
657a8a35 898#if wxDEBUG_LEVEL
021efd65
VZ
899
900#if !defined(__WXMSW__)
901 // on Unix stack frame generation may take some time, depending on the
902 // size of the executable mainly... warn the user that we are working
903 wxFprintf(stderr, "Collecting stack trace information, please wait...");
904 fflush(stderr);
905#endif // !__WXMSW__
906
907
db9febdf
RR
908 wxString stackTrace;
909
910 class StackDump : public wxStackWalker
911 {
912 public:
913 StackDump() { }
914
915 const wxString& GetStackTrace() const { return m_stackTrace; }
916
917 protected:
918 virtual void OnStackFrame(const wxStackFrame& frame)
919 {
920 m_stackTrace << wxString::Format
921 (
9a83f860 922 wxT("[%02d] "),
db9febdf
RR
923 wx_truncate_cast(int, frame.GetLevel())
924 );
925
926 wxString name = frame.GetName();
927 if ( !name.empty() )
928 {
9a83f860 929 m_stackTrace << wxString::Format(wxT("%-40s"), name.c_str());
db9febdf
RR
930 }
931 else
932 {
9a83f860 933 m_stackTrace << wxString::Format(wxT("%p"), frame.GetAddress());
db9febdf
RR
934 }
935
936 if ( frame.HasSourceLocation() )
937 {
9a83f860 938 m_stackTrace << wxT('\t')
db9febdf 939 << frame.GetFileName()
9a83f860 940 << wxT(':')
db9febdf
RR
941 << frame.GetLine();
942 }
943
9a83f860 944 m_stackTrace << wxT('\n');
db9febdf
RR
945 }
946
947 private:
948 wxString m_stackTrace;
949 };
950
951 // don't show more than maxLines or we could get a dialog too tall to be
952 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
953 // characters it is still only 300 pixels...
954 static const int maxLines = 20;
955
956 StackDump dump;
957 dump.Walk(2, maxLines); // don't show OnAssert() call itself
958 stackTrace = dump.GetStackTrace();
959
960 const int count = stackTrace.Freq(wxT('\n'));
961 for ( int i = 0; i < count - maxLines; i++ )
962 stackTrace = stackTrace.BeforeLast(wxT('\n'));
963
964 return stackTrace;
657a8a35
VZ
965#else // !wxDEBUG_LEVEL
966 // this function is still present for ABI-compatibility even in debug level
967 // 0 build but is not used there and so can simply do nothing
968 return wxString();
969#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
db9febdf
RR
970}
971#endif // wxUSE_STACKWALKER
972
973
e2478fde
VZ
974// ============================================================================
975// global functions implementation
976// ============================================================================
977
978void wxExit()
979{
980 if ( wxTheApp )
981 {
982 wxTheApp->Exit();
983 }
984 else
985 {
986 // what else can we do?
987 exit(-1);
988 }
989}
990
991void wxWakeUpIdle()
992{
993 if ( wxTheApp )
994 {
995 wxTheApp->WakeUpIdle();
996 }
997 //else: do nothing, what can we do?
998}
999
e2478fde
VZ
1000// wxASSERT() helper
1001bool wxAssertIsEqual(int x, int y)
1002{
1003 return x == y;
1004}
1005
657a8a35
VZ
1006#if wxDEBUG_LEVEL
1007
e2478fde
VZ
1008// break into the debugger
1009void wxTrap()
1010{
1011#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1012 DebugBreak();
f0756afe
DE
1013#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1014 Debugger();
e2478fde
VZ
1015#elif defined(__UNIX__)
1016 raise(SIGTRAP);
1017#else
1018 // TODO
1019#endif // Win/Unix
1020}
1021
657a8a35
VZ
1022// default assert handler
1023static void
1024wxDefaultAssertHandler(const wxString& file,
1025 int line,
1026 const wxString& func,
1027 const wxString& cond,
1028 const wxString& msg)
e2478fde
VZ
1029{
1030 // FIXME MT-unsafe
000eea7a 1031 static int s_bInAssert = 0;
e2478fde 1032
000eea7a
VZ
1033 wxRecursionGuard guard(s_bInAssert);
1034 if ( guard.IsInside() )
e2478fde 1035 {
000eea7a 1036 // can't use assert here to avoid infinite loops, so just trap
e2478fde
VZ
1037 wxTrap();
1038
e2478fde
VZ
1039 return;
1040 }
1041
e2478fde
VZ
1042 if ( !wxTheApp )
1043 {
1044 // by default, show the assert dialog box -- we can't customize this
1045 // behaviour
657a8a35 1046 ShowAssertDialog(file, line, func, cond, msg);
e2478fde
VZ
1047 }
1048 else
1049 {
1050 // let the app process it as it wants
0accd1cf 1051 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
657a8a35
VZ
1052 wxTheApp->OnAssertFailure(file.c_str(), line, func.c_str(),
1053 cond.c_str(), msg.c_str());
e2478fde 1054 }
e2478fde
VZ
1055}
1056
657a8a35
VZ
1057wxAssertHandler_t wxTheAssertHandler = wxDefaultAssertHandler;
1058
7d9550df
VZ
1059void wxSetDefaultAssertHandler()
1060{
1061 wxTheAssertHandler = wxDefaultAssertHandler;
1062}
1063
657a8a35
VZ
1064void wxOnAssert(const wxString& file,
1065 int line,
1066 const wxString& func,
1067 const wxString& cond,
1068 const wxString& msg)
0accd1cf 1069{
657a8a35 1070 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1071}
1072
657a8a35
VZ
1073void wxOnAssert(const wxString& file,
1074 int line,
1075 const wxString& func,
1076 const wxString& cond)
0accd1cf 1077{
657a8a35 1078 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1079}
1080
657a8a35
VZ
1081void wxOnAssert(const wxChar *file,
1082 int line,
1083 const char *func,
1084 const wxChar *cond,
1085 const wxChar *msg)
0accd1cf 1086{
657a8a35
VZ
1087 // this is the backwards-compatible version (unless we don't use Unicode)
1088 // so it could be called directly from the user code and this might happen
1089 // even when wxTheAssertHandler is NULL
1090#if wxUSE_UNICODE
1091 if ( wxTheAssertHandler )
1092#endif // wxUSE_UNICODE
1093 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1094}
1095
657a8a35
VZ
1096void wxOnAssert(const char *file,
1097 int line,
1098 const char *func,
1099 const char *cond,
1100 const wxString& msg)
fbaf7d45 1101{
657a8a35 1102 wxTheAssertHandler(file, line, func, cond, msg);
fbaf7d45
VS
1103}
1104
657a8a35
VZ
1105void wxOnAssert(const char *file,
1106 int line,
1107 const char *func,
1108 const char *cond,
2b232d20
VZ
1109 const wxCStrData& msg)
1110{
657a8a35 1111 wxTheAssertHandler(file, line, func, cond, msg);
2b232d20
VZ
1112}
1113
0accd1cf 1114#if wxUSE_UNICODE
657a8a35
VZ
1115void wxOnAssert(const char *file,
1116 int line,
1117 const char *func,
1118 const char *cond)
0accd1cf 1119{
657a8a35 1120 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1121}
1122
657a8a35
VZ
1123void wxOnAssert(const char *file,
1124 int line,
1125 const char *func,
1126 const char *cond,
1127 const char *msg)
0accd1cf 1128{
657a8a35 1129 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1130}
1131
657a8a35
VZ
1132void wxOnAssert(const char *file,
1133 int line,
1134 const char *func,
1135 const char *cond,
1136 const wxChar *msg)
0accd1cf 1137{
657a8a35 1138 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1139}
1140#endif // wxUSE_UNICODE
1141
657a8a35 1142#endif // wxDEBUG_LEVEL
e2478fde
VZ
1143
1144// ============================================================================
1145// private functions implementation
1146// ============================================================================
1147
1148#ifdef __WXDEBUG__
1149
1150static void LINKAGEMODE SetTraceMasks()
1151{
1152#if wxUSE_LOG
1153 wxString mask;
1154 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
1155 {
1156 wxStringTokenizer tkn(mask, wxT(",;:"));
1157 while ( tkn.HasMoreTokens() )
1158 wxLog::AddTraceMask(tkn.GetNextToken());
1159 }
1160#endif // wxUSE_LOG
1161}
1162
657a8a35
VZ
1163#endif // __WXDEBUG__
1164
1165#if wxDEBUG_LEVEL
1166
6ef1b2a1 1167static
e2478fde
VZ
1168bool DoShowAssertDialog(const wxString& msg)
1169{
1170 // under MSW we can show the dialog even in the console mode
1171#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1172 wxString msgDlg(msg);
1173
657a8a35
VZ
1174 // this message is intentionally not translated -- it is for developers
1175 // only -- and the less code we use here, less is the danger of recursively
1176 // asserting and dying
e2478fde
VZ
1177 msgDlg += wxT("\nDo you want to stop the program?\n")
1178 wxT("You can also choose [Cancel] to suppress ")
1179 wxT("further warnings.");
1180
9a83f860 1181 switch ( ::MessageBox(NULL, msgDlg.wx_str(), wxT("wxWidgets Debug Alert"),
e2478fde
VZ
1182 MB_YESNOCANCEL | MB_ICONSTOP ) )
1183 {
1184 case IDYES:
1185 wxTrap();
1186 break;
1187
1188 case IDCANCEL:
1189 // stop the asserts
1190 return true;
1191
1192 //case IDNO: nothing to do
1193 }
1194#else // !__WXMSW__
021efd65 1195 wxUnusedVar(msg);
e2478fde
VZ
1196#endif // __WXMSW__/!__WXMSW__
1197
021efd65 1198 // continue with the asserts by default
e2478fde
VZ
1199 return false;
1200}
1201
657a8a35 1202// show the standard assert dialog
4a92d4bc 1203static
657a8a35
VZ
1204void ShowAssertDialog(const wxString& file,
1205 int line,
1206 const wxString& func,
1207 const wxString& cond,
1208 const wxString& msgUser,
4a92d4bc
VZ
1209 wxAppTraits *traits)
1210{
1211 // this variable can be set to true to suppress "assert failure" messages
1212 static bool s_bNoAsserts = false;
1213
1214 wxString msg;
1215 msg.reserve(2048);
1216
1217 // make life easier for people using VC++ IDE by using this format: like
1218 // this, clicking on the message will take us immediately to the place of
1219 // the failed assert
657a8a35 1220 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), file, line, cond);
4a92d4bc 1221
dfa0b52f 1222 // add the function name, if any
657a8a35 1223 if ( !func.empty() )
9a83f860 1224 msg << wxT(" in ") << func << wxT("()");
dfa0b52f
VZ
1225
1226 // and the message itself
657a8a35 1227 if ( !msgUser.empty() )
2c9b3131 1228 {
9a83f860 1229 msg << wxT(": ") << msgUser;
2c9b3131 1230 }
4a92d4bc
VZ
1231 else // no message given
1232 {
9a83f860 1233 msg << wxT('.');
4a92d4bc
VZ
1234 }
1235
e2478fde
VZ
1236#if wxUSE_THREADS
1237 // if we are not in the main thread, output the assert directly and trap
1238 // since dialogs cannot be displayed
1239 if ( !wxThread::IsMain() )
1240 {
2d8e0096 1241 msg += wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
e2478fde
VZ
1242 }
1243#endif // wxUSE_THREADS
1244
2d8e0096
VZ
1245 // log the assert in any case
1246 wxMessageOutputDebug().Output(msg);
1247
e2478fde
VZ
1248 if ( !s_bNoAsserts )
1249 {
e2478fde
VZ
1250 if ( traits )
1251 {
1252 // delegate showing assert dialog (if possible) to that class
1253 s_bNoAsserts = traits->ShowAssertDialog(msg);
1254 }
1255 else // no traits object
1256 {
1257 // fall back to the function of last resort
1258 s_bNoAsserts = DoShowAssertDialog(msg);
1259 }
1260 }
1261}
1262
657a8a35 1263#endif // wxDEBUG_LEVEL