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