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