]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
Fix type mismatch in wxLogTrace() call in wxSocket.
[wxWidgets.git] / src / common / appbase.cpp
CommitLineData
e2478fde 1///////////////////////////////////////////////////////////////////////////////
8ecff181 2// Name: src/common/appbase.cpp
e0954e72 3// Purpose: implements wxAppConsoleBase class
e2478fde
VZ
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 19.06.2003 (extracted from common/appcmn.cpp)
7// RCS-ID: $Id$
8// Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
526954c5 9// Licence: wxWindows licence
e2478fde
VZ
10///////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20// for compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
24 #pragma hdrstop
25#endif
26
27#ifndef WX_PRECOMP
d98a58c5 28 #ifdef __WINDOWS__
57bd4c60
WS
29 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
30 #endif
8ecff181 31 #include "wx/list.h"
8df6de97
VS
32 #include "wx/app.h"
33 #include "wx/intl.h"
86f8d1a8 34 #include "wx/log.h"
de6185e2 35 #include "wx/utils.h"
0cb7e05c 36 #include "wx/wxcrtvararg.h"
e2478fde
VZ
37#endif //WX_PRECOMP
38
39#include "wx/apptrait.h"
40#include "wx/cmdline.h"
41#include "wx/confbase.h"
b46b1d59 42#include "wx/evtloop.h"
ce39c39e 43#include "wx/filename.h"
e2478fde 44#include "wx/msgout.h"
664e1314 45#include "wx/scopedptr.h"
4d1ea475 46#include "wx/sysopt.h"
e2478fde 47#include "wx/tokenzr.h"
204abcd4 48#include "wx/thread.h"
e2478fde 49
1663c655
VZ
50#if wxUSE_EXCEPTIONS && wxUSE_STL
51 #include <exception>
52 #include <typeinfo>
53#endif
54
d98a58c5 55#if !defined(__WINDOWS__) || defined(__WXMICROWIN__)
e2478fde
VZ
56 #include <signal.h> // for SIGTRAP used by wxTrap()
57#endif //Win/Unix
58
0e5ab030
VZ
59#include <locale.h>
60
1c193821
JS
61#if wxUSE_FONTMAP
62 #include "wx/fontmap.h"
63#endif // wxUSE_FONTMAP
64
657a8a35 65#if wxDEBUG_LEVEL
7b1c3469 66 #if wxUSE_STACKWALKER
6c8f8d92 67 #include "wx/stackwalk.h"
d98a58c5 68 #ifdef __WINDOWS__
4a92d4bc
VZ
69 #include "wx/msw/debughlp.h"
70 #endif
6c8f8d92 71 #endif // wxUSE_STACKWALKER
000eea7a
VZ
72
73 #include "wx/recguard.h"
657a8a35 74#endif // wxDEBUG_LEVEL
6c8f8d92 75
121aea46
MW
76// wxABI_VERSION can be defined when compiling applications but it should be
77// left undefined when compiling the library itself, it is then set to its
78// default value in version.h
79#if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
80#error "wxABI_VERSION should not be defined when compiling the library"
81#endif
82
e2478fde
VZ
83// ----------------------------------------------------------------------------
84// private functions prototypes
85// ----------------------------------------------------------------------------
86
657a8a35 87#if wxDEBUG_LEVEL
e2478fde
VZ
88 // really just show the assert dialog
89 static bool DoShowAssertDialog(const wxString& msg);
90
91 // prepare for showing the assert dialog, use the given traits or
92 // DoShowAssertDialog() as last fallback to really show it
93 static
657a8a35
VZ
94 void ShowAssertDialog(const wxString& file,
95 int line,
96 const wxString& func,
97 const wxString& cond,
98 const wxString& msg,
e2478fde 99 wxAppTraits *traits = NULL);
657a8a35 100#endif // wxDEBUG_LEVEL
e2478fde 101
657a8a35 102#ifdef __WXDEBUG__
e2478fde
VZ
103 // turn on the trace masks specified in the env variable WXTRACE
104 static void LINKAGEMODE SetTraceMasks();
105#endif // __WXDEBUG__
106
107// ----------------------------------------------------------------------------
108// global vars
109// ----------------------------------------------------------------------------
110
e0954e72 111wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
e2478fde 112
e0954e72 113wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
e2478fde 114
51fe4b60
VZ
115wxSocketManager *wxAppTraitsBase::ms_manager = NULL;
116
3185abc2
VZ
117WXDLLIMPEXP_DATA_BASE(wxList) wxPendingDelete;
118
b46b1d59
VZ
119// ----------------------------------------------------------------------------
120// wxEventLoopPtr
121// ----------------------------------------------------------------------------
122
123// this defines wxEventLoopPtr
2ddff00c 124wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
b46b1d59 125
e2478fde 126// ============================================================================
e0954e72 127// wxAppConsoleBase implementation
e2478fde
VZ
128// ============================================================================
129
130// ----------------------------------------------------------------------------
131// ctor/dtor
132// ----------------------------------------------------------------------------
133
e0954e72 134wxAppConsoleBase::wxAppConsoleBase()
e2478fde
VZ
135{
136 m_traits = NULL;
b46b1d59 137 m_mainLoop = NULL;
cae9e7b1 138 m_bDoPendingEventProcessing = true;
e2478fde 139
5c33522f 140 ms_appInstance = static_cast<wxAppConsole *>(this);
e2478fde
VZ
141
142#ifdef __WXDEBUG__
143 SetTraceMasks();
bc334f39
RD
144#if wxUSE_UNICODE
145 // In unicode mode the SetTraceMasks call can cause an apptraits to be
146 // created, but since we are still in the constructor the wrong kind will
147 // be created for GUI apps. Destroy it so it can be created again later.
5276b0a5 148 wxDELETE(m_traits);
bc334f39 149#endif
e2478fde 150#endif
58cc1587
VZ
151
152 wxEvtHandler::AddFilter(this);
e2478fde
VZ
153}
154
e0954e72 155wxAppConsoleBase::~wxAppConsoleBase()
e2478fde 156{
58cc1587
VZ
157 wxEvtHandler::RemoveFilter(this);
158
89fb9e52
VZ
159 // we're being destroyed and using this object from now on may not work or
160 // even crash so don't leave dangling pointers to it
161 ms_appInstance = NULL;
162
e2478fde
VZ
163 delete m_traits;
164}
165
94826170 166// ----------------------------------------------------------------------------
8b93348e 167// initialization/cleanup
94826170
VZ
168// ----------------------------------------------------------------------------
169
f432e677 170bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc), wxChar **WXUNUSED(argv))
94826170 171{
d774f916
VZ
172#if wxUSE_INTL
173 GetTraits()->SetLocale();
174#endif // wxUSE_INTL
175
f432e677
VZ
176 return true;
177}
178
179wxString wxAppConsoleBase::GetAppName() const
180{
181 wxString name = m_appName;
f432e677 182 if ( name.empty() )
94826170 183 {
f432e677
VZ
184 if ( argv )
185 {
186 // the application name is, by default, the name of its executable file
187 wxFileName::SplitPath(argv[0], NULL, &name, NULL);
188 }
94826170 189 }
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
58cc1587 404 return Event_Skip;
e2478fde
VZ
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 898
d98a58c5 899#if !defined(__WINDOWS__)
021efd65
VZ
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);
d98a58c5 904#endif // !__WINDOWS__
021efd65
VZ
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
975dc691
VZ
1005void wxAbort()
1006{
1007#ifdef __WXWINCE__
1008 ExitThread(3);
1009#else
1010 abort();
1011#endif
1012}
1013
657a8a35
VZ
1014#if wxDEBUG_LEVEL
1015
e2478fde
VZ
1016// break into the debugger
1017void wxTrap()
1018{
d98a58c5 1019#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
e2478fde 1020 DebugBreak();
f0756afe
DE
1021#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1022 Debugger();
e2478fde
VZ
1023#elif defined(__UNIX__)
1024 raise(SIGTRAP);
1025#else
1026 // TODO
1027#endif // Win/Unix
1028}
1029
657a8a35
VZ
1030// default assert handler
1031static void
1032wxDefaultAssertHandler(const wxString& file,
1033 int line,
1034 const wxString& func,
1035 const wxString& cond,
1036 const wxString& msg)
e2478fde 1037{
4d1ea475
VZ
1038 // If this option is set, we should abort immediately when assert happens.
1039 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
d58c7af8 1040 wxAbort();
4d1ea475 1041
e2478fde 1042 // FIXME MT-unsafe
000eea7a 1043 static int s_bInAssert = 0;
e2478fde 1044
000eea7a
VZ
1045 wxRecursionGuard guard(s_bInAssert);
1046 if ( guard.IsInside() )
e2478fde 1047 {
000eea7a 1048 // can't use assert here to avoid infinite loops, so just trap
e2478fde
VZ
1049 wxTrap();
1050
e2478fde
VZ
1051 return;
1052 }
1053
e2478fde
VZ
1054 if ( !wxTheApp )
1055 {
1056 // by default, show the assert dialog box -- we can't customize this
1057 // behaviour
657a8a35 1058 ShowAssertDialog(file, line, func, cond, msg);
e2478fde
VZ
1059 }
1060 else
1061 {
1062 // let the app process it as it wants
0accd1cf 1063 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
657a8a35
VZ
1064 wxTheApp->OnAssertFailure(file.c_str(), line, func.c_str(),
1065 cond.c_str(), msg.c_str());
e2478fde 1066 }
e2478fde
VZ
1067}
1068
657a8a35
VZ
1069wxAssertHandler_t wxTheAssertHandler = wxDefaultAssertHandler;
1070
7d9550df
VZ
1071void wxSetDefaultAssertHandler()
1072{
1073 wxTheAssertHandler = wxDefaultAssertHandler;
1074}
1075
657a8a35
VZ
1076void wxOnAssert(const wxString& file,
1077 int line,
1078 const wxString& func,
1079 const wxString& cond,
1080 const wxString& msg)
0accd1cf 1081{
657a8a35 1082 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1083}
1084
657a8a35
VZ
1085void wxOnAssert(const wxString& file,
1086 int line,
1087 const wxString& func,
1088 const wxString& cond)
0accd1cf 1089{
657a8a35 1090 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1091}
1092
657a8a35
VZ
1093void wxOnAssert(const wxChar *file,
1094 int line,
1095 const char *func,
1096 const wxChar *cond,
1097 const wxChar *msg)
0accd1cf 1098{
657a8a35
VZ
1099 // this is the backwards-compatible version (unless we don't use Unicode)
1100 // so it could be called directly from the user code and this might happen
1101 // even when wxTheAssertHandler is NULL
1102#if wxUSE_UNICODE
1103 if ( wxTheAssertHandler )
1104#endif // wxUSE_UNICODE
1105 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1106}
1107
657a8a35
VZ
1108void wxOnAssert(const char *file,
1109 int line,
1110 const char *func,
1111 const char *cond,
1112 const wxString& msg)
fbaf7d45 1113{
657a8a35 1114 wxTheAssertHandler(file, line, func, cond, msg);
fbaf7d45
VS
1115}
1116
657a8a35
VZ
1117void wxOnAssert(const char *file,
1118 int line,
1119 const char *func,
1120 const char *cond,
2b232d20
VZ
1121 const wxCStrData& msg)
1122{
657a8a35 1123 wxTheAssertHandler(file, line, func, cond, msg);
2b232d20
VZ
1124}
1125
0accd1cf 1126#if wxUSE_UNICODE
657a8a35
VZ
1127void wxOnAssert(const char *file,
1128 int line,
1129 const char *func,
1130 const char *cond)
0accd1cf 1131{
657a8a35 1132 wxTheAssertHandler(file, line, func, cond, wxString());
0accd1cf
VS
1133}
1134
657a8a35
VZ
1135void wxOnAssert(const char *file,
1136 int line,
1137 const char *func,
1138 const char *cond,
1139 const char *msg)
0accd1cf 1140{
657a8a35 1141 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1142}
1143
657a8a35
VZ
1144void wxOnAssert(const char *file,
1145 int line,
1146 const char *func,
1147 const char *cond,
1148 const wxChar *msg)
0accd1cf 1149{
657a8a35 1150 wxTheAssertHandler(file, line, func, cond, msg);
0accd1cf
VS
1151}
1152#endif // wxUSE_UNICODE
1153
657a8a35 1154#endif // wxDEBUG_LEVEL
e2478fde
VZ
1155
1156// ============================================================================
1157// private functions implementation
1158// ============================================================================
1159
1160#ifdef __WXDEBUG__
1161
1162static void LINKAGEMODE SetTraceMasks()
1163{
1164#if wxUSE_LOG
1165 wxString mask;
1166 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
1167 {
1168 wxStringTokenizer tkn(mask, wxT(",;:"));
1169 while ( tkn.HasMoreTokens() )
1170 wxLog::AddTraceMask(tkn.GetNextToken());
1171 }
1172#endif // wxUSE_LOG
1173}
1174
657a8a35
VZ
1175#endif // __WXDEBUG__
1176
1177#if wxDEBUG_LEVEL
1178
6ef1b2a1 1179static
e2478fde
VZ
1180bool DoShowAssertDialog(const wxString& msg)
1181{
d98a58c5
VZ
1182 // under Windows we can show the dialog even in the console mode
1183#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
e2478fde
VZ
1184 wxString msgDlg(msg);
1185
657a8a35
VZ
1186 // this message is intentionally not translated -- it is for developers
1187 // only -- and the less code we use here, less is the danger of recursively
1188 // asserting and dying
e2478fde
VZ
1189 msgDlg += wxT("\nDo you want to stop the program?\n")
1190 wxT("You can also choose [Cancel] to suppress ")
1191 wxT("further warnings.");
1192
9a83f860 1193 switch ( ::MessageBox(NULL, msgDlg.wx_str(), wxT("wxWidgets Debug Alert"),
e2478fde
VZ
1194 MB_YESNOCANCEL | MB_ICONSTOP ) )
1195 {
1196 case IDYES:
1197 wxTrap();
1198 break;
1199
1200 case IDCANCEL:
1201 // stop the asserts
1202 return true;
1203
1204 //case IDNO: nothing to do
1205 }
d98a58c5 1206#else // !__WINDOWS__
021efd65 1207 wxUnusedVar(msg);
d98a58c5 1208#endif // __WINDOWS__/!__WINDOWS__
e2478fde 1209
021efd65 1210 // continue with the asserts by default
e2478fde
VZ
1211 return false;
1212}
1213
657a8a35 1214// show the standard assert dialog
4a92d4bc 1215static
657a8a35
VZ
1216void ShowAssertDialog(const wxString& file,
1217 int line,
1218 const wxString& func,
1219 const wxString& cond,
1220 const wxString& msgUser,
4a92d4bc
VZ
1221 wxAppTraits *traits)
1222{
1223 // this variable can be set to true to suppress "assert failure" messages
1224 static bool s_bNoAsserts = false;
1225
1226 wxString msg;
1227 msg.reserve(2048);
1228
1229 // make life easier for people using VC++ IDE by using this format: like
1230 // this, clicking on the message will take us immediately to the place of
1231 // the failed assert
657a8a35 1232 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), file, line, cond);
4a92d4bc 1233
dfa0b52f 1234 // add the function name, if any
657a8a35 1235 if ( !func.empty() )
9a83f860 1236 msg << wxT(" in ") << func << wxT("()");
dfa0b52f
VZ
1237
1238 // and the message itself
657a8a35 1239 if ( !msgUser.empty() )
2c9b3131 1240 {
9a83f860 1241 msg << wxT(": ") << msgUser;
2c9b3131 1242 }
4a92d4bc
VZ
1243 else // no message given
1244 {
9a83f860 1245 msg << wxT('.');
4a92d4bc
VZ
1246 }
1247
e2478fde
VZ
1248#if wxUSE_THREADS
1249 // if we are not in the main thread, output the assert directly and trap
1250 // since dialogs cannot be displayed
1251 if ( !wxThread::IsMain() )
1252 {
2d8e0096 1253 msg += wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
e2478fde
VZ
1254 }
1255#endif // wxUSE_THREADS
1256
2d8e0096
VZ
1257 // log the assert in any case
1258 wxMessageOutputDebug().Output(msg);
1259
e2478fde
VZ
1260 if ( !s_bNoAsserts )
1261 {
e2478fde
VZ
1262 if ( traits )
1263 {
1264 // delegate showing assert dialog (if possible) to that class
1265 s_bNoAsserts = traits->ShowAssertDialog(msg);
1266 }
1267 else // no traits object
1268 {
1269 // fall back to the function of last resort
1270 s_bNoAsserts = DoShowAssertDialog(msg);
1271 }
1272 }
1273}
1274
657a8a35 1275#endif // wxDEBUG_LEVEL