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