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