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