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