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