]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/appbase.cpp
Fix type mismatch in wxLogTrace() call in wxSocket.
[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 __WINDOWS__
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#if !defined(__WINDOWS__) || defined(__WXMICROWIN__)
56 #include <signal.h> // for SIGTRAP used by wxTrap()
57#endif //Win/Unix
58
59#include <locale.h>
60
61#if wxUSE_FONTMAP
62 #include "wx/fontmap.h"
63#endif // wxUSE_FONTMAP
64
65#if wxDEBUG_LEVEL
66 #if wxUSE_STACKWALKER
67 #include "wx/stackwalk.h"
68 #ifdef __WINDOWS__
69 #include "wx/msw/debughlp.h"
70 #endif
71 #endif // wxUSE_STACKWALKER
72
73 #include "wx/recguard.h"
74#endif // wxDEBUG_LEVEL
75
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
83// ----------------------------------------------------------------------------
84// private functions prototypes
85// ----------------------------------------------------------------------------
86
87#if wxDEBUG_LEVEL
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
94 void ShowAssertDialog(const wxString& file,
95 int line,
96 const wxString& func,
97 const wxString& cond,
98 const wxString& msg,
99 wxAppTraits *traits = NULL);
100#endif // wxDEBUG_LEVEL
101
102#ifdef __WXDEBUG__
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
111wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
112
113wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
114
115wxSocketManager *wxAppTraitsBase::ms_manager = NULL;
116
117WXDLLIMPEXP_DATA_BASE(wxList) wxPendingDelete;
118
119// ----------------------------------------------------------------------------
120// wxEventLoopPtr
121// ----------------------------------------------------------------------------
122
123// this defines wxEventLoopPtr
124wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
125
126// ============================================================================
127// wxAppConsoleBase implementation
128// ============================================================================
129
130// ----------------------------------------------------------------------------
131// ctor/dtor
132// ----------------------------------------------------------------------------
133
134wxAppConsoleBase::wxAppConsoleBase()
135{
136 m_traits = NULL;
137 m_mainLoop = NULL;
138 m_bDoPendingEventProcessing = true;
139
140 ms_appInstance = static_cast<wxAppConsole *>(this);
141
142#ifdef __WXDEBUG__
143 SetTraceMasks();
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.
148 wxDELETE(m_traits);
149#endif
150#endif
151
152 wxEvtHandler::AddFilter(this);
153}
154
155wxAppConsoleBase::~wxAppConsoleBase()
156{
157 wxEvtHandler::RemoveFilter(this);
158
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
163 delete m_traits;
164}
165
166// ----------------------------------------------------------------------------
167// initialization/cleanup
168// ----------------------------------------------------------------------------
169
170bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc), wxChar **WXUNUSED(argv))
171{
172#if wxUSE_INTL
173 GetTraits()->SetLocale();
174#endif // wxUSE_INTL
175
176 return true;
177}
178
179wxString wxAppConsoleBase::GetAppName() const
180{
181 wxString name = m_appName;
182 if ( name.empty() )
183 {
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 }
189 }
190 return name;
191}
192
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();
207}
208
209wxEventLoopBase *wxAppConsoleBase::CreateMainLoop()
210{
211 return GetTraits()->CreateEventLoop();
212}
213
214void wxAppConsoleBase::CleanUp()
215{
216 wxDELETE(m_mainLoop);
217}
218
219// ----------------------------------------------------------------------------
220// OnXXX() callbacks
221// ----------------------------------------------------------------------------
222
223bool wxAppConsoleBase::OnInit()
224{
225#if wxUSE_CMDLINE_PARSER
226 wxCmdLineParser parser(argc, argv);
227
228 OnInitCmdLine(parser);
229
230 bool cont;
231 switch ( parser.Parse(false /* don't show usage */) )
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 )
247 return false;
248#endif // wxUSE_CMDLINE_PARSER
249
250 return true;
251}
252
253int wxAppConsoleBase::OnRun()
254{
255 return MainLoop();
256}
257
258int wxAppConsoleBase::OnExit()
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)
263 delete wxConfigBase::Set(NULL);
264#endif // wxUSE_CONFIG
265
266 return 0;
267}
268
269void wxAppConsoleBase::Exit()
270{
271 if (m_mainLoop != NULL)
272 ExitMainLoop();
273 else
274 exit(-1);
275}
276
277// ----------------------------------------------------------------------------
278// traits stuff
279// ----------------------------------------------------------------------------
280
281wxAppTraits *wxAppConsoleBase::CreateTraits()
282{
283 return new wxConsoleAppTraits;
284}
285
286wxAppTraits *wxAppConsoleBase::GetTraits()
287{
288 // FIXME-MT: protect this with a CS?
289 if ( !m_traits )
290 {
291 m_traits = CreateTraits();
292
293 wxASSERT_MSG( m_traits, wxT("wxApp::CreateTraits() failed?") );
294 }
295
296 return m_traits;
297}
298
299/* static */
300wxAppTraits *wxAppConsoleBase::GetTraitsIfExists()
301{
302 wxAppConsole * const app = GetInstance();
303 return app ? app->GetTraits() : NULL;
304}
305
306// ----------------------------------------------------------------------------
307// wxEventLoop redirection
308// ----------------------------------------------------------------------------
309
310int wxAppConsoleBase::MainLoop()
311{
312 wxEventLoopBaseTiedPtr mainLoop(&m_mainLoop, CreateMainLoop());
313
314 return m_mainLoop ? m_mainLoop->Run() : -1;
315}
316
317void wxAppConsoleBase::ExitMainLoop()
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
327bool wxAppConsoleBase::Pending()
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
332 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
333
334 return loop && loop->Pending();
335}
336
337bool wxAppConsoleBase::Dispatch()
338{
339 // see comment in Pending()
340 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
341
342 return loop && loop->Dispatch();
343}
344
345bool wxAppConsoleBase::Yield(bool onlyIfNeeded)
346{
347 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
348 if ( loop )
349 return loop->Yield(onlyIfNeeded);
350
351 wxScopedPtr<wxEventLoopBase> tmpLoop(CreateMainLoop());
352 return tmpLoop->Yield(onlyIfNeeded);
353}
354
355void wxAppConsoleBase::WakeUpIdle()
356{
357 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
358
359 if ( loop )
360 loop->WakeUp();
361}
362
363bool wxAppConsoleBase::ProcessIdle()
364{
365 // synthesize an idle event and check if more of them are needed
366 wxIdleEvent event;
367 event.SetEventObject(this);
368 ProcessEvent(event);
369
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
376 // Garbage collect all objects previously scheduled for destruction.
377 DeletePendingObjects();
378
379 return event.MoreRequested();
380}
381
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
389// ----------------------------------------------------------------------------
390// events
391// ----------------------------------------------------------------------------
392
393/* static */
394bool wxAppConsoleBase::IsMainLoopRunning()
395{
396 const wxAppConsole * const app = GetInstance();
397
398 return app && app->m_mainLoop != NULL;
399}
400
401int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
402{
403 // process the events normally by default
404 return Event_Skip;
405}
406
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{
471 m_bDoPendingEventProcessing = false;
472}
473
474void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
475{
476 m_bDoPendingEventProcessing = true;
477}
478
479void wxAppConsoleBase::ProcessPendingEvents()
480{
481 if ( m_bDoPendingEventProcessing )
482 {
483 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
484
485 wxCHECK_RET( m_handlersWithPendingDelayedEvents.IsEmpty(),
486 "this helper list should be empty" );
487
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 }
515
516 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
517 }
518}
519
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
535// ----------------------------------------------------------------------------
536// delayed objects destruction
537// ----------------------------------------------------------------------------
538
539bool wxAppConsoleBase::IsScheduledForDestruction(wxObject *object) const
540{
541 return wxPendingDelete.Member(object);
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
579// ----------------------------------------------------------------------------
580// exception handling
581// ----------------------------------------------------------------------------
582
583#if wxUSE_EXCEPTIONS
584
585void
586wxAppConsoleBase::HandleEvent(wxEvtHandler *handler,
587 wxEventFunction func,
588 wxEvent& event) const
589{
590 // by default, simply call the handler
591 (handler->*func)(event);
592}
593
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():
600 wxEventFunction eventFunction = functor.GetEvtMethod();
601
602 if ( eventFunction )
603 HandleEvent(handler, eventFunction, event);
604 else
605 functor(handler, event);
606}
607
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
636// ----------------------------------------------------------------------------
637// exceptions support
638// ----------------------------------------------------------------------------
639
640bool wxAppConsoleBase::OnExceptionInMainLoop()
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
650#endif // wxUSE_EXCEPTIONS
651
652// ----------------------------------------------------------------------------
653// cmd line parsing
654// ----------------------------------------------------------------------------
655
656#if wxUSE_CMDLINE_PARSER
657
658#define OPTION_VERBOSE "verbose"
659
660void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser& parser)
661{
662 // the standard command line options
663 static const wxCmdLineEntryDesc cmdLineDesc[] =
664 {
665 {
666 wxCMD_LINE_SWITCH,
667 "h",
668 "help",
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,
677 NULL,
678 OPTION_VERBOSE,
679 gettext_noop("generate verbose log messages"),
680 wxCMD_LINE_VAL_NONE,
681 0x0
682 },
683#endif // wxUSE_LOG
684
685 // terminator
686 wxCMD_LINE_DESC_END
687 };
688
689 parser.SetDesc(cmdLineDesc);
690}
691
692bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser& parser)
693{
694#if wxUSE_LOG
695 if ( parser.Found(OPTION_VERBOSE) )
696 {
697 wxLog::SetVerbose(true);
698 }
699#else
700 wxUnusedVar(parser);
701#endif // wxUSE_LOG
702
703 return true;
704}
705
706bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser& parser)
707{
708 parser.Usage();
709
710 return false;
711}
712
713bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser& parser)
714{
715 parser.Usage();
716
717 return false;
718}
719
720#endif // wxUSE_CMDLINE_PARSER
721
722// ----------------------------------------------------------------------------
723// debugging support
724// ----------------------------------------------------------------------------
725
726/* static */
727bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature,
728 const char *componentName)
729{
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);
733#endif
734
735 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
736 {
737 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
738 wxString prog = wxString::FromAscii(optionsSignature);
739 wxString progName = wxString::FromAscii(componentName);
740 wxString msg;
741
742 msg.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
743 lib.c_str(), progName.c_str(), prog.c_str());
744
745 wxLogFatalError(msg.c_str());
746
747 // normally wxLogFatalError doesn't return
748 return false;
749 }
750
751 return true;
752}
753
754void wxAppConsoleBase::OnAssertFailure(const wxChar *file,
755 int line,
756 const wxChar *func,
757 const wxChar *cond,
758 const wxChar *msg)
759{
760#if wxDEBUG_LEVEL
761 ShowAssertDialog(file, line, func, cond, msg, GetTraits());
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
772}
773
774void wxAppConsoleBase::OnAssert(const wxChar *file,
775 int line,
776 const wxChar *cond,
777 const wxChar *msg)
778{
779 OnAssertFailure(file, line, NULL, cond, msg);
780}
781
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
813wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
814{
815 // console applications don't use renderers
816 return NULL;
817}
818
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
830// ----------------------------------------------------------------------------
831// wxAppTraits
832// ----------------------------------------------------------------------------
833
834#if wxUSE_INTL
835void wxAppTraitsBase::SetLocale()
836{
837 wxSetlocale(LC_ALL, "");
838 wxUpdateLocaleIsUtf8();
839}
840#endif
841
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{
858 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
859 if ( traits )
860 traits->MutexGuiEnter();
861}
862
863void WXDLLIMPEXP_BASE wxMutexGuiLeave()
864{
865 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
866 if ( traits )
867 traits->MutexGuiLeave();
868}
869#endif // wxUSE_THREADS
870
871bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
872{
873#if wxDEBUG_LEVEL
874 wxString msg;
875
876#if wxUSE_STACKWALKER
877 const wxString stackTrace = GetAssertStackTrace();
878 if ( !stackTrace.empty() )
879 {
880 msg << wxT("\n\nCall stack:\n") << stackTrace;
881
882 wxMessageOutputDebug().Output(msg);
883 }
884#endif // wxUSE_STACKWALKER
885
886 return DoShowAssertDialog(msgOriginal + msg);
887#else // !wxDEBUG_LEVEL
888 wxUnusedVar(msgOriginal);
889
890 return false;
891#endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
892}
893
894#if wxUSE_STACKWALKER
895wxString wxAppTraitsBase::GetAssertStackTrace()
896{
897#if wxDEBUG_LEVEL
898
899#if !defined(__WINDOWS__)
900 // on Unix stack frame generation may take some time, depending on the
901 // size of the executable mainly... warn the user that we are working
902 wxFprintf(stderr, "Collecting stack trace information, please wait...");
903 fflush(stderr);
904#endif // !__WINDOWS__
905
906
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 (
921 wxT("[%02d] "),
922 wx_truncate_cast(int, frame.GetLevel())
923 );
924
925 wxString name = frame.GetName();
926 if ( !name.empty() )
927 {
928 m_stackTrace << wxString::Format(wxT("%-40s"), name.c_str());
929 }
930 else
931 {
932 m_stackTrace << wxString::Format(wxT("%p"), frame.GetAddress());
933 }
934
935 if ( frame.HasSourceLocation() )
936 {
937 m_stackTrace << wxT('\t')
938 << frame.GetFileName()
939 << wxT(':')
940 << frame.GetLine();
941 }
942
943 m_stackTrace << wxT('\n');
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;
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
969}
970#endif // wxUSE_STACKWALKER
971
972
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
999// wxASSERT() helper
1000bool wxAssertIsEqual(int x, int y)
1001{
1002 return x == y;
1003}
1004
1005void wxAbort()
1006{
1007#ifdef __WXWINCE__
1008 ExitThread(3);
1009#else
1010 abort();
1011#endif
1012}
1013
1014#if wxDEBUG_LEVEL
1015
1016// break into the debugger
1017void wxTrap()
1018{
1019#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1020 DebugBreak();
1021#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1022 Debugger();
1023#elif defined(__UNIX__)
1024 raise(SIGTRAP);
1025#else
1026 // TODO
1027#endif // Win/Unix
1028}
1029
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)
1037{
1038 // If this option is set, we should abort immediately when assert happens.
1039 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1040 wxAbort();
1041
1042 // FIXME MT-unsafe
1043 static int s_bInAssert = 0;
1044
1045 wxRecursionGuard guard(s_bInAssert);
1046 if ( guard.IsInside() )
1047 {
1048 // can't use assert here to avoid infinite loops, so just trap
1049 wxTrap();
1050
1051 return;
1052 }
1053
1054 if ( !wxTheApp )
1055 {
1056 // by default, show the assert dialog box -- we can't customize this
1057 // behaviour
1058 ShowAssertDialog(file, line, func, cond, msg);
1059 }
1060 else
1061 {
1062 // let the app process it as it wants
1063 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1064 wxTheApp->OnAssertFailure(file.c_str(), line, func.c_str(),
1065 cond.c_str(), msg.c_str());
1066 }
1067}
1068
1069wxAssertHandler_t wxTheAssertHandler = wxDefaultAssertHandler;
1070
1071void wxSetDefaultAssertHandler()
1072{
1073 wxTheAssertHandler = wxDefaultAssertHandler;
1074}
1075
1076void wxOnAssert(const wxString& file,
1077 int line,
1078 const wxString& func,
1079 const wxString& cond,
1080 const wxString& msg)
1081{
1082 wxTheAssertHandler(file, line, func, cond, msg);
1083}
1084
1085void wxOnAssert(const wxString& file,
1086 int line,
1087 const wxString& func,
1088 const wxString& cond)
1089{
1090 wxTheAssertHandler(file, line, func, cond, wxString());
1091}
1092
1093void wxOnAssert(const wxChar *file,
1094 int line,
1095 const char *func,
1096 const wxChar *cond,
1097 const wxChar *msg)
1098{
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);
1106}
1107
1108void wxOnAssert(const char *file,
1109 int line,
1110 const char *func,
1111 const char *cond,
1112 const wxString& msg)
1113{
1114 wxTheAssertHandler(file, line, func, cond, msg);
1115}
1116
1117void wxOnAssert(const char *file,
1118 int line,
1119 const char *func,
1120 const char *cond,
1121 const wxCStrData& msg)
1122{
1123 wxTheAssertHandler(file, line, func, cond, msg);
1124}
1125
1126#if wxUSE_UNICODE
1127void wxOnAssert(const char *file,
1128 int line,
1129 const char *func,
1130 const char *cond)
1131{
1132 wxTheAssertHandler(file, line, func, cond, wxString());
1133}
1134
1135void wxOnAssert(const char *file,
1136 int line,
1137 const char *func,
1138 const char *cond,
1139 const char *msg)
1140{
1141 wxTheAssertHandler(file, line, func, cond, msg);
1142}
1143
1144void wxOnAssert(const char *file,
1145 int line,
1146 const char *func,
1147 const char *cond,
1148 const wxChar *msg)
1149{
1150 wxTheAssertHandler(file, line, func, cond, msg);
1151}
1152#endif // wxUSE_UNICODE
1153
1154#endif // wxDEBUG_LEVEL
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
1175#endif // __WXDEBUG__
1176
1177#if wxDEBUG_LEVEL
1178
1179static
1180bool DoShowAssertDialog(const wxString& msg)
1181{
1182 // under Windows we can show the dialog even in the console mode
1183#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1184 wxString msgDlg(msg);
1185
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
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
1193 switch ( ::MessageBox(NULL, msgDlg.wx_str(), wxT("wxWidgets Debug Alert"),
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 }
1206#else // !__WINDOWS__
1207 wxUnusedVar(msg);
1208#endif // __WINDOWS__/!__WINDOWS__
1209
1210 // continue with the asserts by default
1211 return false;
1212}
1213
1214// show the standard assert dialog
1215static
1216void ShowAssertDialog(const wxString& file,
1217 int line,
1218 const wxString& func,
1219 const wxString& cond,
1220 const wxString& msgUser,
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
1232 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), file, line, cond);
1233
1234 // add the function name, if any
1235 if ( !func.empty() )
1236 msg << wxT(" in ") << func << wxT("()");
1237
1238 // and the message itself
1239 if ( !msgUser.empty() )
1240 {
1241 msg << wxT(": ") << msgUser;
1242 }
1243 else // no message given
1244 {
1245 msg << wxT('.');
1246 }
1247
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 {
1253 msg += wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1254 }
1255#endif // wxUSE_THREADS
1256
1257 // log the assert in any case
1258 wxMessageOutputDebug().Output(msg);
1259
1260 if ( !s_bNoAsserts )
1261 {
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
1275#endif // wxDEBUG_LEVEL