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