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