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