use (new) safer GetTraitsIfExists() in wxMutexGuiEnter/Leave() to avoid crashing...
[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/ptr_scpd.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 defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
67 // For MacTypes.h for Debugger function
68 #include <CoreFoundation/CFBase.h>
69 #endif
70
71 #if defined(__WXMAC__)
72 #ifdef __DARWIN__
73 #include <CoreServices/CoreServices.h>
74 #else
75 #include "wx/mac/private.h" // includes mac headers
76 #endif
77 #endif // __WXMAC__
78
79 #ifdef __WXDEBUG__
80 #if wxUSE_STACKWALKER
81 #include "wx/stackwalk.h"
82 #ifdef __WXMSW__
83 #include "wx/msw/debughlp.h"
84 #endif
85 #endif // wxUSE_STACKWALKER
86
87 #include "wx/recguard.h"
88 #endif // __WXDEBUG__
89
90 // wxABI_VERSION can be defined when compiling applications but it should be
91 // left undefined when compiling the library itself, it is then set to its
92 // default value in version.h
93 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
94 #error "wxABI_VERSION should not be defined when compiling the library"
95 #endif
96
97 // ----------------------------------------------------------------------------
98 // private functions prototypes
99 // ----------------------------------------------------------------------------
100
101 #ifdef __WXDEBUG__
102 // really just show the assert dialog
103 static bool DoShowAssertDialog(const wxString& msg);
104
105 // prepare for showing the assert dialog, use the given traits or
106 // DoShowAssertDialog() as last fallback to really show it
107 static
108 void ShowAssertDialog(const wxString& szFile,
109 int nLine,
110 const wxString& szFunc,
111 const wxString& szCond,
112 const wxString& szMsg,
113 wxAppTraits *traits = NULL);
114
115 // turn on the trace masks specified in the env variable WXTRACE
116 static void LINKAGEMODE SetTraceMasks();
117 #endif // __WXDEBUG__
118
119 // ----------------------------------------------------------------------------
120 // global vars
121 // ----------------------------------------------------------------------------
122
123 wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
124
125 wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
126
127 // ----------------------------------------------------------------------------
128 // wxEventLoopPtr
129 // ----------------------------------------------------------------------------
130
131 // this defines wxEventLoopPtr
132 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
133
134 // ============================================================================
135 // wxAppConsoleBase implementation
136 // ============================================================================
137
138 // ----------------------------------------------------------------------------
139 // ctor/dtor
140 // ----------------------------------------------------------------------------
141
142 wxAppConsoleBase::wxAppConsoleBase()
143 {
144 m_traits = NULL;
145 m_mainLoop = NULL;
146
147 ms_appInstance = wx_static_cast(wxAppConsole *, this);
148
149 #ifdef __WXDEBUG__
150 SetTraceMasks();
151 #if wxUSE_UNICODE
152 // In unicode mode the SetTraceMasks call can cause an apptraits to be
153 // created, but since we are still in the constructor the wrong kind will
154 // be created for GUI apps. Destroy it so it can be created again later.
155 delete m_traits;
156 m_traits = NULL;
157 #endif
158 #endif
159 }
160
161 wxAppConsoleBase::~wxAppConsoleBase()
162 {
163 delete m_traits;
164 }
165
166 // ----------------------------------------------------------------------------
167 // initilization/cleanup
168 // ----------------------------------------------------------------------------
169
170 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc), wxChar **argv)
171 {
172 #if wxUSE_INTL
173 GetTraits()->SetLocale();
174 #endif // wxUSE_INTL
175
176 #if wxUSE_THREADS
177 wxPendingEventsLocker = new wxCriticalSection;
178 #endif
179
180 #ifndef __WXPALMOS__
181 if ( m_appName.empty() && argv && argv[0] )
182 {
183 // the application name is, by default, the name of its executable file
184 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
185 }
186 #endif // !__WXPALMOS__
187
188 return true;
189 }
190
191 wxEventLoopBase *wxAppConsoleBase::CreateMainLoop()
192 {
193 return GetTraits()->CreateEventLoop();
194 }
195
196 void wxAppConsoleBase::CleanUp()
197 {
198 if ( m_mainLoop )
199 {
200 delete m_mainLoop;
201 m_mainLoop = NULL;
202 }
203
204 delete wxPendingEvents;
205 wxPendingEvents = NULL;
206
207 #if wxUSE_THREADS
208 delete wxPendingEventsLocker;
209 wxPendingEventsLocker = NULL;
210 #endif // wxUSE_THREADS
211 }
212
213 // ----------------------------------------------------------------------------
214 // OnXXX() callbacks
215 // ----------------------------------------------------------------------------
216
217 bool wxAppConsoleBase::OnInit()
218 {
219 #if wxUSE_CMDLINE_PARSER
220 wxCmdLineParser parser(argc, argv);
221
222 OnInitCmdLine(parser);
223
224 bool cont;
225 switch ( parser.Parse(false /* don't show usage */) )
226 {
227 case -1:
228 cont = OnCmdLineHelp(parser);
229 break;
230
231 case 0:
232 cont = OnCmdLineParsed(parser);
233 break;
234
235 default:
236 cont = OnCmdLineError(parser);
237 break;
238 }
239
240 if ( !cont )
241 return false;
242 #endif // wxUSE_CMDLINE_PARSER
243
244 return true;
245 }
246
247 int wxAppConsoleBase::OnRun()
248 {
249 return MainLoop();
250 }
251
252 int wxAppConsoleBase::OnExit()
253 {
254 #if wxUSE_CONFIG
255 // delete the config object if any (don't use Get() here, but Set()
256 // because Get() could create a new config object)
257 delete wxConfigBase::Set((wxConfigBase *) NULL);
258 #endif // wxUSE_CONFIG
259
260 return 0;
261 }
262
263 void wxAppConsoleBase::Exit()
264 {
265 if (m_mainLoop != NULL)
266 ExitMainLoop();
267 else
268 exit(-1);
269 }
270
271 // ----------------------------------------------------------------------------
272 // traits stuff
273 // ----------------------------------------------------------------------------
274
275 wxAppTraits *wxAppConsoleBase::CreateTraits()
276 {
277 return new wxConsoleAppTraits;
278 }
279
280 wxAppTraits *wxAppConsoleBase::GetTraits()
281 {
282 // FIXME-MT: protect this with a CS?
283 if ( !m_traits )
284 {
285 m_traits = CreateTraits();
286
287 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
288 }
289
290 return m_traits;
291 }
292
293 /* static */
294 wxAppTraits *wxAppConsoleBase::GetTraitsIfExists()
295 {
296 wxAppConsole * const app = GetInstance();
297 return app ? app->GetTraits() : NULL;
298 }
299
300 // ----------------------------------------------------------------------------
301 // event processing
302 // ----------------------------------------------------------------------------
303
304 int wxAppConsoleBase::MainLoop()
305 {
306 wxEventLoopBaseTiedPtr mainLoop(&m_mainLoop, CreateMainLoop());
307
308 return m_mainLoop ? m_mainLoop->Run() : -1;
309 }
310
311 void wxAppConsoleBase::ExitMainLoop()
312 {
313 // we should exit from the main event loop, not just any currently active
314 // (e.g. modal dialog) event loop
315 if ( m_mainLoop && m_mainLoop->IsRunning() )
316 {
317 m_mainLoop->Exit(0);
318 }
319 }
320
321 bool wxAppConsoleBase::Pending()
322 {
323 // use the currently active message loop here, not m_mainLoop, because if
324 // we're showing a modal dialog (with its own event loop) currently the
325 // main event loop is not running anyhow
326 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
327
328 return loop && loop->Pending();
329 }
330
331 bool wxAppConsoleBase::Dispatch()
332 {
333 // see comment in Pending()
334 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
335
336 return loop && loop->Dispatch();
337 }
338
339 bool wxAppConsoleBase::HasPendingEvents() const
340 {
341 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
342
343 bool has = wxPendingEvents && !wxPendingEvents->IsEmpty();
344
345 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
346
347 return has;
348 }
349
350 /* static */
351 bool wxAppConsoleBase::IsMainLoopRunning()
352 {
353 const wxAppConsole * const app = GetInstance();
354
355 return app && app->m_mainLoop != NULL;
356 }
357
358 void wxAppConsoleBase::ProcessPendingEvents()
359 {
360 #if wxUSE_THREADS
361 if ( !wxPendingEventsLocker )
362 return;
363 #endif
364
365 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
366
367 if (wxPendingEvents)
368 {
369 // iterate until the list becomes empty: the handlers remove themselves
370 // from it when they don't have any more pending events
371 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
372 while (node)
373 {
374 // In ProcessPendingEvents(), new handlers might be add
375 // and we can safely leave the critical section here.
376 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
377
378 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
379 handler->ProcessPendingEvents();
380
381 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
382
383 // restart as the iterators could have been invalidated
384 node = wxPendingEvents->GetFirst();
385 }
386 }
387
388 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
389 }
390
391 void wxAppConsoleBase::WakeUpIdle()
392 {
393 if ( m_mainLoop )
394 m_mainLoop->WakeUp();
395 }
396
397 bool wxAppConsoleBase::ProcessIdle()
398 {
399 wxIdleEvent event;
400
401 event.SetEventObject(this);
402 ProcessEvent(event);
403 return event.MoreRequested();
404 }
405
406 int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
407 {
408 // process the events normally by default
409 return -1;
410 }
411
412 // ----------------------------------------------------------------------------
413 // exception handling
414 // ----------------------------------------------------------------------------
415
416 #if wxUSE_EXCEPTIONS
417
418 void
419 wxAppConsoleBase::HandleEvent(wxEvtHandler *handler,
420 wxEventFunction func,
421 wxEvent& event) const
422 {
423 // by default, simply call the handler
424 (handler->*func)(event);
425 }
426
427 void wxAppConsoleBase::OnUnhandledException()
428 {
429 #ifdef __WXDEBUG__
430 // we're called from an exception handler so we can re-throw the exception
431 // to recover its type
432 wxString what;
433 try
434 {
435 throw;
436 }
437 #if wxUSE_STL
438 catch ( std::exception& e )
439 {
440 what.Printf("std::exception of type \"%s\", what() = \"%s\"",
441 typeid(e).name(), e.what());
442 }
443 #endif // wxUSE_STL
444 catch ( ... )
445 {
446 what = "unknown exception";
447 }
448
449 wxMessageOutputBest().Printf(
450 "*** Caught unhandled %s; terminating\n", what
451 );
452 #endif // __WXDEBUG__
453 }
454
455 // ----------------------------------------------------------------------------
456 // exceptions support
457 // ----------------------------------------------------------------------------
458
459 bool wxAppConsoleBase::OnExceptionInMainLoop()
460 {
461 throw;
462
463 // some compilers are too stupid to know that we never return after throw
464 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
465 return false;
466 #endif
467 }
468
469 #endif // wxUSE_EXCEPTIONS
470
471 // ----------------------------------------------------------------------------
472 // cmd line parsing
473 // ----------------------------------------------------------------------------
474
475 #if wxUSE_CMDLINE_PARSER
476
477 #define OPTION_VERBOSE "verbose"
478
479 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser& parser)
480 {
481 // the standard command line options
482 static const wxCmdLineEntryDesc cmdLineDesc[] =
483 {
484 {
485 wxCMD_LINE_SWITCH,
486 "h",
487 "help",
488 gettext_noop("show this help message"),
489 wxCMD_LINE_VAL_NONE,
490 wxCMD_LINE_OPTION_HELP
491 },
492
493 #if wxUSE_LOG
494 {
495 wxCMD_LINE_SWITCH,
496 NULL,
497 OPTION_VERBOSE,
498 gettext_noop("generate verbose log messages"),
499 wxCMD_LINE_VAL_NONE,
500 0x0
501 },
502 #endif // wxUSE_LOG
503
504 // terminator
505 wxCMD_LINE_DESC_END
506 };
507
508 parser.SetDesc(cmdLineDesc);
509 }
510
511 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser& parser)
512 {
513 #if wxUSE_LOG
514 if ( parser.Found(OPTION_VERBOSE) )
515 {
516 wxLog::SetVerbose(true);
517 }
518 #else
519 wxUnusedVar(parser);
520 #endif // wxUSE_LOG
521
522 return true;
523 }
524
525 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser& parser)
526 {
527 parser.Usage();
528
529 return false;
530 }
531
532 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser& parser)
533 {
534 parser.Usage();
535
536 return false;
537 }
538
539 #endif // wxUSE_CMDLINE_PARSER
540
541 // ----------------------------------------------------------------------------
542 // debugging support
543 // ----------------------------------------------------------------------------
544
545 /* static */
546 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature,
547 const char *componentName)
548 {
549 #if 0 // can't use wxLogTrace, not up and running yet
550 printf("checking build options object '%s' (ptr %p) in '%s'\n",
551 optionsSignature, optionsSignature, componentName);
552 #endif
553
554 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
555 {
556 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
557 wxString prog = wxString::FromAscii(optionsSignature);
558 wxString progName = wxString::FromAscii(componentName);
559 wxString msg;
560
561 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
562 lib.c_str(), progName.c_str(), prog.c_str());
563
564 wxLogFatalError(msg.c_str());
565
566 // normally wxLogFatalError doesn't return
567 return false;
568 }
569 #undef wxCMP
570
571 return true;
572 }
573
574 #ifdef __WXDEBUG__
575
576 void wxAppConsoleBase::OnAssertFailure(const wxChar *file,
577 int line,
578 const wxChar *func,
579 const wxChar *cond,
580 const wxChar *msg)
581 {
582 ShowAssertDialog(file, line, func, cond, msg, GetTraits());
583 }
584
585 void wxAppConsoleBase::OnAssert(const wxChar *file,
586 int line,
587 const wxChar *cond,
588 const wxChar *msg)
589 {
590 OnAssertFailure(file, line, NULL, cond, msg);
591 }
592
593 #endif // __WXDEBUG__
594
595 // ============================================================================
596 // other classes implementations
597 // ============================================================================
598
599 // ----------------------------------------------------------------------------
600 // wxConsoleAppTraitsBase
601 // ----------------------------------------------------------------------------
602
603 #if wxUSE_LOG
604
605 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
606 {
607 return new wxLogStderr;
608 }
609
610 #endif // wxUSE_LOG
611
612 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
613 {
614 return new wxMessageOutputStderr;
615 }
616
617 #if wxUSE_FONTMAP
618
619 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
620 {
621 return (wxFontMapper *)new wxFontMapperBase;
622 }
623
624 #endif // wxUSE_FONTMAP
625
626 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
627 {
628 // console applications don't use renderers
629 return NULL;
630 }
631
632 #ifdef __WXDEBUG__
633 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
634 {
635 return wxAppTraitsBase::ShowAssertDialog(msg);
636 }
637 #endif
638
639 bool wxConsoleAppTraitsBase::HasStderr()
640 {
641 // console applications always have stderr, even under Mac/Windows
642 return true;
643 }
644
645 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
646 {
647 delete object;
648 }
649
650 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
651 {
652 // nothing to do
653 }
654
655 // ----------------------------------------------------------------------------
656 // wxAppTraits
657 // ----------------------------------------------------------------------------
658
659 #if wxUSE_INTL
660 void wxAppTraitsBase::SetLocale()
661 {
662 wxSetlocale(LC_ALL, "");
663 wxUpdateLocaleIsUtf8();
664 }
665 #endif
666
667 #if wxUSE_THREADS
668 void wxMutexGuiEnterImpl();
669 void wxMutexGuiLeaveImpl();
670
671 void wxAppTraitsBase::MutexGuiEnter()
672 {
673 wxMutexGuiEnterImpl();
674 }
675
676 void wxAppTraitsBase::MutexGuiLeave()
677 {
678 wxMutexGuiLeaveImpl();
679 }
680
681 void WXDLLIMPEXP_BASE wxMutexGuiEnter()
682 {
683 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
684 if ( traits )
685 traits->MutexGuiEnter();
686 }
687
688 void WXDLLIMPEXP_BASE wxMutexGuiLeave()
689 {
690 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
691 if ( traits )
692 traits->MutexGuiLeave();
693 }
694 #endif // wxUSE_THREADS
695
696 #ifdef __WXDEBUG__
697
698 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
699 {
700 wxString msg = msgOriginal;
701
702 #if wxUSE_STACKWALKER
703 #if !defined(__WXMSW__)
704 // on Unix stack frame generation may take some time, depending on the
705 // size of the executable mainly... warn the user that we are working
706 wxFprintf(stderr, wxT("[Debug] Generating a stack trace... please wait"));
707 fflush(stderr);
708 #endif
709
710 const wxString stackTrace = GetAssertStackTrace();
711 if ( !stackTrace.empty() )
712 msg << _T("\n\nCall stack:\n") << stackTrace;
713 #endif // wxUSE_STACKWALKER
714
715 return DoShowAssertDialog(msg);
716 }
717
718 #if wxUSE_STACKWALKER
719 wxString wxAppTraitsBase::GetAssertStackTrace()
720 {
721 wxString stackTrace;
722
723 class StackDump : public wxStackWalker
724 {
725 public:
726 StackDump() { }
727
728 const wxString& GetStackTrace() const { return m_stackTrace; }
729
730 protected:
731 virtual void OnStackFrame(const wxStackFrame& frame)
732 {
733 m_stackTrace << wxString::Format
734 (
735 _T("[%02d] "),
736 wx_truncate_cast(int, frame.GetLevel())
737 );
738
739 wxString name = frame.GetName();
740 if ( !name.empty() )
741 {
742 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
743 }
744 else
745 {
746 m_stackTrace << wxString::Format(_T("%p"), frame.GetAddress());
747 }
748
749 if ( frame.HasSourceLocation() )
750 {
751 m_stackTrace << _T('\t')
752 << frame.GetFileName()
753 << _T(':')
754 << frame.GetLine();
755 }
756
757 m_stackTrace << _T('\n');
758 }
759
760 private:
761 wxString m_stackTrace;
762 };
763
764 // don't show more than maxLines or we could get a dialog too tall to be
765 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
766 // characters it is still only 300 pixels...
767 static const int maxLines = 20;
768
769 StackDump dump;
770 dump.Walk(2, maxLines); // don't show OnAssert() call itself
771 stackTrace = dump.GetStackTrace();
772
773 const int count = stackTrace.Freq(wxT('\n'));
774 for ( int i = 0; i < count - maxLines; i++ )
775 stackTrace = stackTrace.BeforeLast(wxT('\n'));
776
777 return stackTrace;
778 }
779 #endif // wxUSE_STACKWALKER
780
781
782 #endif // __WXDEBUG__
783
784 // ============================================================================
785 // global functions implementation
786 // ============================================================================
787
788 void wxExit()
789 {
790 if ( wxTheApp )
791 {
792 wxTheApp->Exit();
793 }
794 else
795 {
796 // what else can we do?
797 exit(-1);
798 }
799 }
800
801 void wxWakeUpIdle()
802 {
803 if ( wxTheApp )
804 {
805 wxTheApp->WakeUpIdle();
806 }
807 //else: do nothing, what can we do?
808 }
809
810 #ifdef __WXDEBUG__
811
812 // wxASSERT() helper
813 bool wxAssertIsEqual(int x, int y)
814 {
815 return x == y;
816 }
817
818 // break into the debugger
819 void wxTrap()
820 {
821 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
822 DebugBreak();
823 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
824 Debugger();
825 #elif defined(__UNIX__)
826 raise(SIGTRAP);
827 #else
828 // TODO
829 #endif // Win/Unix
830 }
831
832 // this function is called when an assert fails
833 static void wxDoOnAssert(const wxString& szFile,
834 int nLine,
835 const wxString& szFunc,
836 const wxString& szCond,
837 const wxString& szMsg = wxEmptyString)
838 {
839 // FIXME MT-unsafe
840 static int s_bInAssert = 0;
841
842 wxRecursionGuard guard(s_bInAssert);
843 if ( guard.IsInside() )
844 {
845 // can't use assert here to avoid infinite loops, so just trap
846 wxTrap();
847
848 return;
849 }
850
851 if ( !wxTheApp )
852 {
853 // by default, show the assert dialog box -- we can't customize this
854 // behaviour
855 ShowAssertDialog(szFile, nLine, szFunc, szCond, szMsg);
856 }
857 else
858 {
859 // let the app process it as it wants
860 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
861 wxTheApp->OnAssertFailure(szFile.c_str(), nLine, szFunc.c_str(),
862 szCond.c_str(), szMsg.c_str());
863 }
864 }
865
866 void wxOnAssert(const wxString& szFile,
867 int nLine,
868 const wxString& szFunc,
869 const wxString& szCond,
870 const wxString& szMsg)
871 {
872 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
873 }
874
875 void wxOnAssert(const wxString& szFile,
876 int nLine,
877 const wxString& szFunc,
878 const wxString& szCond)
879 {
880 wxDoOnAssert(szFile, nLine, szFunc, szCond);
881 }
882
883 void wxOnAssert(const wxChar *szFile,
884 int nLine,
885 const char *szFunc,
886 const wxChar *szCond,
887 const wxChar *szMsg)
888 {
889 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
890 }
891
892 void wxOnAssert(const char *szFile,
893 int nLine,
894 const char *szFunc,
895 const char *szCond,
896 const wxString& szMsg)
897 {
898 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
899 }
900
901 void wxOnAssert(const char *szFile,
902 int nLine,
903 const char *szFunc,
904 const char *szCond,
905 const wxCStrData& msg)
906 {
907 wxDoOnAssert(szFile, nLine, szFunc, szCond, msg);
908 }
909
910 #if wxUSE_UNICODE
911 void wxOnAssert(const char *szFile,
912 int nLine,
913 const char *szFunc,
914 const char *szCond)
915 {
916 wxDoOnAssert(szFile, nLine, szFunc, szCond);
917 }
918
919 void wxOnAssert(const char *szFile,
920 int nLine,
921 const char *szFunc,
922 const char *szCond,
923 const char *szMsg)
924 {
925 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
926 }
927
928 void wxOnAssert(const char *szFile,
929 int nLine,
930 const char *szFunc,
931 const char *szCond,
932 const wxChar *szMsg)
933 {
934 wxDoOnAssert(szFile, nLine, szFunc, szCond, szMsg);
935 }
936 #endif // wxUSE_UNICODE
937
938 #endif // __WXDEBUG__
939
940 // ============================================================================
941 // private functions implementation
942 // ============================================================================
943
944 #ifdef __WXDEBUG__
945
946 static void LINKAGEMODE SetTraceMasks()
947 {
948 #if wxUSE_LOG
949 wxString mask;
950 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
951 {
952 wxStringTokenizer tkn(mask, wxT(",;:"));
953 while ( tkn.HasMoreTokens() )
954 wxLog::AddTraceMask(tkn.GetNextToken());
955 }
956 #endif // wxUSE_LOG
957 }
958
959 static
960 bool DoShowAssertDialog(const wxString& msg)
961 {
962 // under MSW we can show the dialog even in the console mode
963 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
964 wxString msgDlg(msg);
965
966 // this message is intentionally not translated -- it is for
967 // developpers only
968 msgDlg += wxT("\nDo you want to stop the program?\n")
969 wxT("You can also choose [Cancel] to suppress ")
970 wxT("further warnings.");
971
972 switch ( ::MessageBox(NULL, msgDlg.wx_str(), _T("wxWidgets Debug Alert"),
973 MB_YESNOCANCEL | MB_ICONSTOP ) )
974 {
975 case IDYES:
976 wxTrap();
977 break;
978
979 case IDCANCEL:
980 // stop the asserts
981 return true;
982
983 //case IDNO: nothing to do
984 }
985 #else // !__WXMSW__
986 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
987 fflush(stderr);
988
989 // TODO: ask the user to enter "Y" or "N" on the console?
990 wxTrap();
991 #endif // __WXMSW__/!__WXMSW__
992
993 // continue with the asserts
994 return false;
995 }
996
997 // show the assert modal dialog
998 static
999 void ShowAssertDialog(const wxString& szFile,
1000 int nLine,
1001 const wxString& szFunc,
1002 const wxString& szCond,
1003 const wxString& szMsg,
1004 wxAppTraits *traits)
1005 {
1006 // this variable can be set to true to suppress "assert failure" messages
1007 static bool s_bNoAsserts = false;
1008
1009 wxString msg;
1010 msg.reserve(2048);
1011
1012 // make life easier for people using VC++ IDE by using this format: like
1013 // this, clicking on the message will take us immediately to the place of
1014 // the failed assert
1015 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
1016
1017 // add the function name, if any
1018 if ( !szFunc.empty() )
1019 msg << _T(" in ") << szFunc << _T("()");
1020
1021 // and the message itself
1022 if ( !szMsg.empty() )
1023 {
1024 msg << _T(": ") << szMsg;
1025 }
1026 else // no message given
1027 {
1028 msg << _T('.');
1029 }
1030
1031 #if wxUSE_THREADS
1032 // if we are not in the main thread, output the assert directly and trap
1033 // since dialogs cannot be displayed
1034 if ( !wxThread::IsMain() )
1035 {
1036 msg += wxT(" [in child thread]");
1037
1038 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
1039 msg << wxT("\r\n");
1040 OutputDebugString(msg.wx_str());
1041 #else
1042 // send to stderr
1043 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
1044 fflush(stderr);
1045 #endif
1046 // He-e-e-e-elp!! we're asserting in a child thread
1047 wxTrap();
1048 }
1049 else
1050 #endif // wxUSE_THREADS
1051
1052 if ( !s_bNoAsserts )
1053 {
1054 // send it to the normal log destination
1055 wxLogDebug(_T("%s"), msg.c_str());
1056
1057 if ( traits )
1058 {
1059 // delegate showing assert dialog (if possible) to that class
1060 s_bNoAsserts = traits->ShowAssertDialog(msg);
1061 }
1062 else // no traits object
1063 {
1064 // fall back to the function of last resort
1065 s_bNoAsserts = DoShowAssertDialog(msg);
1066 }
1067 }
1068 }
1069
1070 #endif // __WXDEBUG__