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