]> git.saurik.com Git - wxWidgets.git/blob - src/common/appbase.cpp
Misc validity fixes to samples/xrc/rc/*.xrc.
[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 // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
10
11 // ============================================================================
12 // declarations
13 // ============================================================================
14
15 // ----------------------------------------------------------------------------
16 // headers
17 // ----------------------------------------------------------------------------
18
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 #ifndef WX_PRECOMP
27 #ifdef __WINDOWS__
28 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
29 #endif
30 #include "wx/list.h"
31 #include "wx/app.h"
32 #include "wx/intl.h"
33 #include "wx/log.h"
34 #include "wx/utils.h"
35 #include "wx/wxcrtvararg.h"
36 #endif //WX_PRECOMP
37
38 #include "wx/apptrait.h"
39 #include "wx/cmdline.h"
40 #include "wx/confbase.h"
41 #include "wx/evtloop.h"
42 #include "wx/filename.h"
43 #include "wx/msgout.h"
44 #include "wx/scopedptr.h"
45 #include "wx/sysopt.h"
46 #include "wx/tokenzr.h"
47 #include "wx/thread.h"
48
49 #if wxUSE_STL
50 #if wxUSE_EXCEPTIONS
51 #include <exception>
52 #include <typeinfo>
53 #endif
54 #if wxUSE_INTL
55 #include <locale>
56 #endif
57 #endif // wxUSE_STL
58
59 #if !defined(__WINDOWS__) || defined(__WXMICROWIN__)
60 #include <signal.h> // for SIGTRAP used by wxTrap()
61 #endif //Win/Unix
62
63 #include <locale.h>
64
65 #if wxUSE_FONTMAP
66 #include "wx/fontmap.h"
67 #endif // wxUSE_FONTMAP
68
69 #if wxDEBUG_LEVEL
70 #if wxUSE_STACKWALKER
71 #include "wx/stackwalk.h"
72 #ifdef __WINDOWS__
73 #include "wx/msw/debughlp.h"
74 #endif
75 #endif // wxUSE_STACKWALKER
76
77 #include "wx/recguard.h"
78 #endif // wxDEBUG_LEVEL
79
80 // wxABI_VERSION can be defined when compiling applications but it should be
81 // left undefined when compiling the library itself, it is then set to its
82 // default value in version.h
83 #if wxABI_VERSION != wxMAJOR_VERSION * 10000 + wxMINOR_VERSION * 100 + 99
84 #error "wxABI_VERSION should not be defined when compiling the library"
85 #endif
86
87 // ----------------------------------------------------------------------------
88 // private functions prototypes
89 // ----------------------------------------------------------------------------
90
91 #if wxDEBUG_LEVEL
92 // really just show the assert dialog
93 static bool DoShowAssertDialog(const wxString& msg);
94
95 // prepare for showing the assert dialog, use the given traits or
96 // DoShowAssertDialog() as last fallback to really show it
97 static
98 void ShowAssertDialog(const wxString& file,
99 int line,
100 const wxString& func,
101 const wxString& cond,
102 const wxString& msg,
103 wxAppTraits *traits = NULL);
104 #endif // wxDEBUG_LEVEL
105
106 #ifdef __WXDEBUG__
107 // turn on the trace masks specified in the env variable WXTRACE
108 static void LINKAGEMODE SetTraceMasks();
109 #endif // __WXDEBUG__
110
111 // ----------------------------------------------------------------------------
112 // global vars
113 // ----------------------------------------------------------------------------
114
115 wxAppConsole *wxAppConsoleBase::ms_appInstance = NULL;
116
117 wxAppInitializerFunction wxAppConsoleBase::ms_appInitFn = NULL;
118
119 wxSocketManager *wxAppTraitsBase::ms_manager = NULL;
120
121 WXDLLIMPEXP_DATA_BASE(wxList) wxPendingDelete;
122
123 // ----------------------------------------------------------------------------
124 // wxEventLoopPtr
125 // ----------------------------------------------------------------------------
126
127 // this defines wxEventLoopPtr
128 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopBase)
129
130 // ============================================================================
131 // wxAppConsoleBase implementation
132 // ============================================================================
133
134 // ----------------------------------------------------------------------------
135 // ctor/dtor
136 // ----------------------------------------------------------------------------
137
138 wxAppConsoleBase::wxAppConsoleBase()
139 {
140 m_traits = NULL;
141 m_mainLoop = NULL;
142 m_bDoPendingEventProcessing = true;
143
144 ms_appInstance = static_cast<wxAppConsole *>(this);
145
146 #ifdef __WXDEBUG__
147 SetTraceMasks();
148 #if wxUSE_UNICODE
149 // In unicode mode the SetTraceMasks call can cause an apptraits to be
150 // created, but since we are still in the constructor the wrong kind will
151 // be created for GUI apps. Destroy it so it can be created again later.
152 wxDELETE(m_traits);
153 #endif
154 #endif
155
156 wxEvtHandler::AddFilter(this);
157 }
158
159 wxAppConsoleBase::~wxAppConsoleBase()
160 {
161 wxEvtHandler::RemoveFilter(this);
162
163 // we're being destroyed and using this object from now on may not work or
164 // even crash so don't leave dangling pointers to it
165 ms_appInstance = NULL;
166
167 delete m_traits;
168 }
169
170 // ----------------------------------------------------------------------------
171 // initialization/cleanup
172 // ----------------------------------------------------------------------------
173
174 bool wxAppConsoleBase::Initialize(int& WXUNUSED(argc), wxChar **WXUNUSED(argv))
175 {
176 return true;
177 }
178
179 wxString wxAppConsoleBase::GetAppName() const
180 {
181 wxString name = m_appName;
182 if ( name.empty() )
183 {
184 if ( argv )
185 {
186 // the application name is, by default, the name of its executable file
187 wxFileName::SplitPath(argv[0], NULL, &name, NULL);
188 }
189 }
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 wxDELETE(m_mainLoop);
217 }
218
219 // ----------------------------------------------------------------------------
220 // OnXXX() callbacks
221 // ----------------------------------------------------------------------------
222
223 bool wxAppConsoleBase::OnInit()
224 {
225 #if wxUSE_CMDLINE_PARSER
226 wxCmdLineParser parser(argc, argv);
227
228 OnInitCmdLine(parser);
229
230 bool cont;
231 switch ( parser.Parse(false /* don't show usage */) )
232 {
233 case -1:
234 cont = OnCmdLineHelp(parser);
235 break;
236
237 case 0:
238 cont = OnCmdLineParsed(parser);
239 break;
240
241 default:
242 cont = OnCmdLineError(parser);
243 break;
244 }
245
246 if ( !cont )
247 return false;
248 #endif // wxUSE_CMDLINE_PARSER
249
250 return true;
251 }
252
253 int wxAppConsoleBase::OnRun()
254 {
255 return MainLoop();
256 }
257
258 void wxAppConsoleBase::OnLaunched()
259 {
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 /* static */
311 wxAppTraits& wxAppConsoleBase::GetValidTraits()
312 {
313 static wxConsoleAppTraits s_traitsConsole;
314 wxAppTraits* const traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
315
316 return traits ? *traits : s_traitsConsole;
317 }
318
319 // ----------------------------------------------------------------------------
320 // wxEventLoop redirection
321 // ----------------------------------------------------------------------------
322
323 int wxAppConsoleBase::MainLoop()
324 {
325 wxEventLoopBaseTiedPtr mainLoop(&m_mainLoop, CreateMainLoop());
326
327 if (wxTheApp)
328 wxTheApp->OnLaunched();
329
330 return m_mainLoop ? m_mainLoop->Run() : -1;
331 }
332
333 void wxAppConsoleBase::ExitMainLoop()
334 {
335 // we should exit from the main event loop, not just any currently active
336 // (e.g. modal dialog) event loop
337 if ( m_mainLoop && m_mainLoop->IsRunning() )
338 {
339 m_mainLoop->Exit(0);
340 }
341 }
342
343 bool wxAppConsoleBase::Pending()
344 {
345 // use the currently active message loop here, not m_mainLoop, because if
346 // we're showing a modal dialog (with its own event loop) currently the
347 // main event loop is not running anyhow
348 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
349
350 return loop && loop->Pending();
351 }
352
353 bool wxAppConsoleBase::Dispatch()
354 {
355 // see comment in Pending()
356 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
357
358 return loop && loop->Dispatch();
359 }
360
361 bool wxAppConsoleBase::Yield(bool onlyIfNeeded)
362 {
363 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
364 if ( loop )
365 return loop->Yield(onlyIfNeeded);
366
367 wxScopedPtr<wxEventLoopBase> tmpLoop(CreateMainLoop());
368 return tmpLoop->Yield(onlyIfNeeded);
369 }
370
371 void wxAppConsoleBase::WakeUpIdle()
372 {
373 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
374
375 if ( loop )
376 loop->WakeUp();
377 }
378
379 bool wxAppConsoleBase::ProcessIdle()
380 {
381 // synthesize an idle event and check if more of them are needed
382 wxIdleEvent event;
383 event.SetEventObject(this);
384 ProcessEvent(event);
385
386 #if wxUSE_LOG
387 // flush the logged messages if any (do this after processing the events
388 // which could have logged new messages)
389 wxLog::FlushActive();
390 #endif
391
392 // Garbage collect all objects previously scheduled for destruction.
393 DeletePendingObjects();
394
395 return event.MoreRequested();
396 }
397
398 bool wxAppConsoleBase::UsesEventLoop() const
399 {
400 // in console applications we don't know whether we're going to have an
401 // event loop so assume we won't -- unless we already have one running
402 return wxEventLoopBase::GetActive() != NULL;
403 }
404
405 // ----------------------------------------------------------------------------
406 // events
407 // ----------------------------------------------------------------------------
408
409 /* static */
410 bool wxAppConsoleBase::IsMainLoopRunning()
411 {
412 const wxAppConsole * const app = GetInstance();
413
414 return app && app->m_mainLoop != NULL;
415 }
416
417 int wxAppConsoleBase::FilterEvent(wxEvent& WXUNUSED(event))
418 {
419 // process the events normally by default
420 return Event_Skip;
421 }
422
423 void wxAppConsoleBase::DelayPendingEventHandler(wxEvtHandler* toDelay)
424 {
425 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
426
427 // move the handler from the list of handlers with processable pending events
428 // to the list of handlers with pending events which needs to be processed later
429 m_handlersWithPendingEvents.Remove(toDelay);
430
431 if (m_handlersWithPendingDelayedEvents.Index(toDelay) == wxNOT_FOUND)
432 m_handlersWithPendingDelayedEvents.Add(toDelay);
433
434 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
435 }
436
437 void wxAppConsoleBase::RemovePendingEventHandler(wxEvtHandler* toRemove)
438 {
439 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
440
441 if (m_handlersWithPendingEvents.Index(toRemove) != wxNOT_FOUND)
442 {
443 m_handlersWithPendingEvents.Remove(toRemove);
444
445 // check that the handler was present only once in the list
446 wxASSERT_MSG( m_handlersWithPendingEvents.Index(toRemove) == wxNOT_FOUND,
447 "Handler occurs twice in the m_handlersWithPendingEvents list!" );
448 }
449 //else: it wasn't in this list at all, it's ok
450
451 if (m_handlersWithPendingDelayedEvents.Index(toRemove) != wxNOT_FOUND)
452 {
453 m_handlersWithPendingDelayedEvents.Remove(toRemove);
454
455 // check that the handler was present only once in the list
456 wxASSERT_MSG( m_handlersWithPendingDelayedEvents.Index(toRemove) == wxNOT_FOUND,
457 "Handler occurs twice in m_handlersWithPendingDelayedEvents list!" );
458 }
459 //else: it wasn't in this list at all, it's ok
460
461 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
462 }
463
464 void wxAppConsoleBase::AppendPendingEventHandler(wxEvtHandler* toAppend)
465 {
466 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
467
468 if ( m_handlersWithPendingEvents.Index(toAppend) == wxNOT_FOUND )
469 m_handlersWithPendingEvents.Add(toAppend);
470
471 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
472 }
473
474 bool wxAppConsoleBase::HasPendingEvents() const
475 {
476 wxENTER_CRIT_SECT(const_cast<wxAppConsoleBase*>(this)->m_handlersWithPendingEventsLocker);
477
478 bool has = !m_handlersWithPendingEvents.IsEmpty();
479
480 wxLEAVE_CRIT_SECT(const_cast<wxAppConsoleBase*>(this)->m_handlersWithPendingEventsLocker);
481
482 return has;
483 }
484
485 void wxAppConsoleBase::SuspendProcessingOfPendingEvents()
486 {
487 m_bDoPendingEventProcessing = false;
488 }
489
490 void wxAppConsoleBase::ResumeProcessingOfPendingEvents()
491 {
492 m_bDoPendingEventProcessing = true;
493 }
494
495 void wxAppConsoleBase::ProcessPendingEvents()
496 {
497 if ( m_bDoPendingEventProcessing )
498 {
499 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
500
501 wxCHECK_RET( m_handlersWithPendingDelayedEvents.IsEmpty(),
502 "this helper list should be empty" );
503
504 // iterate until the list becomes empty: the handlers remove themselves
505 // from it when they don't have any more pending events
506 while (!m_handlersWithPendingEvents.IsEmpty())
507 {
508 // In ProcessPendingEvents(), new handlers might be added
509 // and we can safely leave the critical section here.
510 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
511
512 // NOTE: we always call ProcessPendingEvents() on the first event handler
513 // with pending events because handlers auto-remove themselves
514 // from this list (see RemovePendingEventHandler) if they have no
515 // more pending events.
516 m_handlersWithPendingEvents[0]->ProcessPendingEvents();
517
518 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
519 }
520
521 // now the wxHandlersWithPendingEvents is surely empty; however some event
522 // handlers may have moved themselves into wxHandlersWithPendingDelayedEvents
523 // because of a selective wxYield call in progress.
524 // Now we need to move them back to wxHandlersWithPendingEvents so the next
525 // call to this function has the chance of processing them:
526 if (!m_handlersWithPendingDelayedEvents.IsEmpty())
527 {
528 WX_APPEND_ARRAY(m_handlersWithPendingEvents, m_handlersWithPendingDelayedEvents);
529 m_handlersWithPendingDelayedEvents.Clear();
530 }
531
532 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
533 }
534 }
535
536 void wxAppConsoleBase::DeletePendingEvents()
537 {
538 wxENTER_CRIT_SECT(m_handlersWithPendingEventsLocker);
539
540 wxCHECK_RET( m_handlersWithPendingDelayedEvents.IsEmpty(),
541 "this helper list should be empty" );
542
543 for (unsigned int i=0; i<m_handlersWithPendingEvents.GetCount(); i++)
544 m_handlersWithPendingEvents[i]->DeletePendingEvents();
545
546 m_handlersWithPendingEvents.Clear();
547
548 wxLEAVE_CRIT_SECT(m_handlersWithPendingEventsLocker);
549 }
550
551 // ----------------------------------------------------------------------------
552 // delayed objects destruction
553 // ----------------------------------------------------------------------------
554
555 bool wxAppConsoleBase::IsScheduledForDestruction(wxObject *object) const
556 {
557 return wxPendingDelete.Member(object);
558 }
559
560 void wxAppConsoleBase::ScheduleForDestruction(wxObject *object)
561 {
562 if ( !UsesEventLoop() )
563 {
564 // we won't be able to delete it later so do it right now
565 delete object;
566 return;
567 }
568 //else: we either already have or will soon start an event loop
569
570 if ( !wxPendingDelete.Member(object) )
571 wxPendingDelete.Append(object);
572 }
573
574 void wxAppConsoleBase::DeletePendingObjects()
575 {
576 wxList::compatibility_iterator node = wxPendingDelete.GetFirst();
577 while (node)
578 {
579 wxObject *obj = node->GetData();
580
581 // remove it from the list first so that if we get back here somehow
582 // during the object deletion (e.g. wxYield called from its dtor) we
583 // wouldn't try to delete it the second time
584 if ( wxPendingDelete.Member(obj) )
585 wxPendingDelete.Erase(node);
586
587 delete obj;
588
589 // Deleting one object may have deleted other pending
590 // objects, so start from beginning of list again.
591 node = wxPendingDelete.GetFirst();
592 }
593 }
594
595 // ----------------------------------------------------------------------------
596 // exception handling
597 // ----------------------------------------------------------------------------
598
599 #if wxUSE_EXCEPTIONS
600
601 void
602 wxAppConsoleBase::HandleEvent(wxEvtHandler *handler,
603 wxEventFunction func,
604 wxEvent& event) const
605 {
606 // by default, simply call the handler
607 (handler->*func)(event);
608 }
609
610 void wxAppConsoleBase::CallEventHandler(wxEvtHandler *handler,
611 wxEventFunctor& functor,
612 wxEvent& event) const
613 {
614 // If the functor holds a method then, for backward compatibility, call
615 // HandleEvent():
616 wxEventFunction eventFunction = functor.GetEvtMethod();
617
618 if ( eventFunction )
619 HandleEvent(handler, eventFunction, event);
620 else
621 functor(handler, event);
622 }
623
624 void wxAppConsoleBase::OnUnhandledException()
625 {
626 #ifdef __WXDEBUG__
627 // we're called from an exception handler so we can re-throw the exception
628 // to recover its type
629 wxString what;
630 try
631 {
632 throw;
633 }
634 #if wxUSE_STL
635 catch ( std::exception& e )
636 {
637 what.Printf("std::exception of type \"%s\", what() = \"%s\"",
638 typeid(e).name(), e.what());
639 }
640 #endif // wxUSE_STL
641 catch ( ... )
642 {
643 what = "unknown exception";
644 }
645
646 wxMessageOutputBest().Printf(
647 "*** Caught unhandled %s; terminating\n", what
648 );
649 #endif // __WXDEBUG__
650 }
651
652 // ----------------------------------------------------------------------------
653 // exceptions support
654 // ----------------------------------------------------------------------------
655
656 bool wxAppConsoleBase::OnExceptionInMainLoop()
657 {
658 throw;
659
660 // some compilers are too stupid to know that we never return after throw
661 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
662 return false;
663 #endif
664 }
665
666 #endif // wxUSE_EXCEPTIONS
667
668 // ----------------------------------------------------------------------------
669 // cmd line parsing
670 // ----------------------------------------------------------------------------
671
672 #if wxUSE_CMDLINE_PARSER
673
674 #define OPTION_VERBOSE "verbose"
675
676 void wxAppConsoleBase::OnInitCmdLine(wxCmdLineParser& parser)
677 {
678 // the standard command line options
679 static const wxCmdLineEntryDesc cmdLineDesc[] =
680 {
681 {
682 wxCMD_LINE_SWITCH,
683 "h",
684 "help",
685 gettext_noop("show this help message"),
686 wxCMD_LINE_VAL_NONE,
687 wxCMD_LINE_OPTION_HELP
688 },
689
690 #if wxUSE_LOG
691 {
692 wxCMD_LINE_SWITCH,
693 NULL,
694 OPTION_VERBOSE,
695 gettext_noop("generate verbose log messages"),
696 wxCMD_LINE_VAL_NONE,
697 0x0
698 },
699 #endif // wxUSE_LOG
700
701 // terminator
702 wxCMD_LINE_DESC_END
703 };
704
705 parser.SetDesc(cmdLineDesc);
706 }
707
708 bool wxAppConsoleBase::OnCmdLineParsed(wxCmdLineParser& parser)
709 {
710 #if wxUSE_LOG
711 if ( parser.Found(OPTION_VERBOSE) )
712 {
713 wxLog::SetVerbose(true);
714 }
715 #else
716 wxUnusedVar(parser);
717 #endif // wxUSE_LOG
718
719 return true;
720 }
721
722 bool wxAppConsoleBase::OnCmdLineHelp(wxCmdLineParser& parser)
723 {
724 parser.Usage();
725
726 return false;
727 }
728
729 bool wxAppConsoleBase::OnCmdLineError(wxCmdLineParser& parser)
730 {
731 parser.Usage();
732
733 return false;
734 }
735
736 #endif // wxUSE_CMDLINE_PARSER
737
738 // ----------------------------------------------------------------------------
739 // debugging support
740 // ----------------------------------------------------------------------------
741
742 /* static */
743 bool wxAppConsoleBase::CheckBuildOptions(const char *optionsSignature,
744 const char *componentName)
745 {
746 #if 0 // can't use wxLogTrace, not up and running yet
747 printf("checking build options object '%s' (ptr %p) in '%s'\n",
748 optionsSignature, optionsSignature, componentName);
749 #endif
750
751 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
752 {
753 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
754 wxString prog = wxString::FromAscii(optionsSignature);
755 wxString progName = wxString::FromAscii(componentName);
756 wxString msg;
757
758 msg.Printf(wxT("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
759 lib.c_str(), progName.c_str(), prog.c_str());
760
761 wxLogFatalError(msg.c_str());
762
763 // normally wxLogFatalError doesn't return
764 return false;
765 }
766
767 return true;
768 }
769
770 void wxAppConsoleBase::OnAssertFailure(const wxChar *file,
771 int line,
772 const wxChar *func,
773 const wxChar *cond,
774 const wxChar *msg)
775 {
776 #if wxDEBUG_LEVEL
777 ShowAssertDialog(file, line, func, cond, msg, GetTraits());
778 #else
779 // this function is still present even in debug level 0 build for ABI
780 // compatibility reasons but is never called there and so can simply do
781 // nothing in it
782 wxUnusedVar(file);
783 wxUnusedVar(line);
784 wxUnusedVar(func);
785 wxUnusedVar(cond);
786 wxUnusedVar(msg);
787 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
788 }
789
790 void wxAppConsoleBase::OnAssert(const wxChar *file,
791 int line,
792 const wxChar *cond,
793 const wxChar *msg)
794 {
795 OnAssertFailure(file, line, NULL, cond, msg);
796 }
797
798 // ----------------------------------------------------------------------------
799 // Miscellaneous other methods
800 // ----------------------------------------------------------------------------
801
802 void wxAppConsoleBase::SetCLocale()
803 {
804 // We want to use the user locale by default in GUI applications in order
805 // to show the numbers, dates &c in the familiar format -- and also accept
806 // this format on input (especially important for decimal comma/dot).
807 wxSetlocale(LC_ALL, "");
808 }
809
810 // ============================================================================
811 // other classes implementations
812 // ============================================================================
813
814 // ----------------------------------------------------------------------------
815 // wxConsoleAppTraitsBase
816 // ----------------------------------------------------------------------------
817
818 #if wxUSE_LOG
819
820 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
821 {
822 return new wxLogStderr;
823 }
824
825 #endif // wxUSE_LOG
826
827 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
828 {
829 return new wxMessageOutputStderr;
830 }
831
832 #if wxUSE_FONTMAP
833
834 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
835 {
836 return (wxFontMapper *)new wxFontMapperBase;
837 }
838
839 #endif // wxUSE_FONTMAP
840
841 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
842 {
843 // console applications don't use renderers
844 return NULL;
845 }
846
847 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
848 {
849 return wxAppTraitsBase::ShowAssertDialog(msg);
850 }
851
852 bool wxConsoleAppTraitsBase::HasStderr()
853 {
854 // console applications always have stderr, even under Mac/Windows
855 return true;
856 }
857
858 // ----------------------------------------------------------------------------
859 // wxAppTraits
860 // ----------------------------------------------------------------------------
861
862 #if wxUSE_THREADS
863 void wxMutexGuiEnterImpl();
864 void wxMutexGuiLeaveImpl();
865
866 void wxAppTraitsBase::MutexGuiEnter()
867 {
868 wxMutexGuiEnterImpl();
869 }
870
871 void wxAppTraitsBase::MutexGuiLeave()
872 {
873 wxMutexGuiLeaveImpl();
874 }
875
876 void WXDLLIMPEXP_BASE wxMutexGuiEnter()
877 {
878 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
879 if ( traits )
880 traits->MutexGuiEnter();
881 }
882
883 void WXDLLIMPEXP_BASE wxMutexGuiLeave()
884 {
885 wxAppTraits * const traits = wxAppConsoleBase::GetTraitsIfExists();
886 if ( traits )
887 traits->MutexGuiLeave();
888 }
889 #endif // wxUSE_THREADS
890
891 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msgOriginal)
892 {
893 #if wxDEBUG_LEVEL
894 wxString msg;
895
896 #if wxUSE_STACKWALKER
897 const wxString stackTrace = GetAssertStackTrace();
898 if ( !stackTrace.empty() )
899 {
900 msg << wxT("\n\nCall stack:\n") << stackTrace;
901
902 wxMessageOutputDebug().Output(msg);
903 }
904 #endif // wxUSE_STACKWALKER
905
906 return DoShowAssertDialog(msgOriginal + msg);
907 #else // !wxDEBUG_LEVEL
908 wxUnusedVar(msgOriginal);
909
910 return false;
911 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
912 }
913
914 #if wxUSE_STACKWALKER
915 wxString wxAppTraitsBase::GetAssertStackTrace()
916 {
917 #if wxDEBUG_LEVEL
918
919 #if !defined(__WINDOWS__)
920 // on Unix stack frame generation may take some time, depending on the
921 // size of the executable mainly... warn the user that we are working
922 wxFprintf(stderr, "Collecting stack trace information, please wait...");
923 fflush(stderr);
924 #endif // !__WINDOWS__
925
926
927 wxString stackTrace;
928
929 class StackDump : public wxStackWalker
930 {
931 public:
932 StackDump() { }
933
934 const wxString& GetStackTrace() const { return m_stackTrace; }
935
936 protected:
937 virtual void OnStackFrame(const wxStackFrame& frame)
938 {
939 m_stackTrace << wxString::Format
940 (
941 wxT("[%02d] "),
942 wx_truncate_cast(int, frame.GetLevel())
943 );
944
945 wxString name = frame.GetName();
946 if ( !name.empty() )
947 {
948 m_stackTrace << wxString::Format(wxT("%-40s"), name.c_str());
949 }
950 else
951 {
952 m_stackTrace << wxString::Format(wxT("%p"), frame.GetAddress());
953 }
954
955 if ( frame.HasSourceLocation() )
956 {
957 m_stackTrace << wxT('\t')
958 << frame.GetFileName()
959 << wxT(':')
960 << frame.GetLine();
961 }
962
963 m_stackTrace << wxT('\n');
964 }
965
966 private:
967 wxString m_stackTrace;
968 };
969
970 // don't show more than maxLines or we could get a dialog too tall to be
971 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
972 // characters it is still only 300 pixels...
973 static const int maxLines = 20;
974
975 StackDump dump;
976 dump.Walk(8, maxLines); // 8 is chosen to hide all OnAssert() calls
977 stackTrace = dump.GetStackTrace();
978
979 const int count = stackTrace.Freq(wxT('\n'));
980 for ( int i = 0; i < count - maxLines; i++ )
981 stackTrace = stackTrace.BeforeLast(wxT('\n'));
982
983 return stackTrace;
984 #else // !wxDEBUG_LEVEL
985 // this function is still present for ABI-compatibility even in debug level
986 // 0 build but is not used there and so can simply do nothing
987 return wxString();
988 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
989 }
990 #endif // wxUSE_STACKWALKER
991
992
993 // ============================================================================
994 // global functions implementation
995 // ============================================================================
996
997 void wxExit()
998 {
999 if ( wxTheApp )
1000 {
1001 wxTheApp->Exit();
1002 }
1003 else
1004 {
1005 // what else can we do?
1006 exit(-1);
1007 }
1008 }
1009
1010 void wxWakeUpIdle()
1011 {
1012 if ( wxTheApp )
1013 {
1014 wxTheApp->WakeUpIdle();
1015 }
1016 //else: do nothing, what can we do?
1017 }
1018
1019 // wxASSERT() helper
1020 bool wxAssertIsEqual(int x, int y)
1021 {
1022 return x == y;
1023 }
1024
1025 void wxAbort()
1026 {
1027 #ifdef __WXWINCE__
1028 ExitThread(3);
1029 #else
1030 abort();
1031 #endif
1032 }
1033
1034 #if wxDEBUG_LEVEL
1035
1036 // break into the debugger
1037 #ifndef wxTrap
1038
1039 void wxTrap()
1040 {
1041 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1042 DebugBreak();
1043 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
1044 Debugger();
1045 #elif defined(__UNIX__)
1046 raise(SIGTRAP);
1047 #else
1048 // TODO
1049 #endif // Win/Unix
1050 }
1051
1052 #endif // wxTrap already defined as a macro
1053
1054 // default assert handler
1055 static void
1056 wxDefaultAssertHandler(const wxString& file,
1057 int line,
1058 const wxString& func,
1059 const wxString& cond,
1060 const wxString& msg)
1061 {
1062 // If this option is set, we should abort immediately when assert happens.
1063 if ( wxSystemOptions::GetOptionInt("exit-on-assert") )
1064 wxAbort();
1065
1066 // FIXME MT-unsafe
1067 static int s_bInAssert = 0;
1068
1069 wxRecursionGuard guard(s_bInAssert);
1070 if ( guard.IsInside() )
1071 {
1072 // can't use assert here to avoid infinite loops, so just trap
1073 wxTrap();
1074
1075 return;
1076 }
1077
1078 if ( !wxTheApp )
1079 {
1080 // by default, show the assert dialog box -- we can't customize this
1081 // behaviour
1082 ShowAssertDialog(file, line, func, cond, msg);
1083 }
1084 else
1085 {
1086 // let the app process it as it wants
1087 // FIXME-UTF8: use wc_str(), not c_str(), when ANSI build is removed
1088 wxTheApp->OnAssertFailure(file.c_str(), line, func.c_str(),
1089 cond.c_str(), msg.c_str());
1090 }
1091 }
1092
1093 wxAssertHandler_t wxTheAssertHandler = wxDefaultAssertHandler;
1094
1095 void wxSetDefaultAssertHandler()
1096 {
1097 wxTheAssertHandler = wxDefaultAssertHandler;
1098 }
1099
1100 void wxOnAssert(const wxString& file,
1101 int line,
1102 const wxString& func,
1103 const wxString& cond,
1104 const wxString& msg)
1105 {
1106 wxTheAssertHandler(file, line, func, cond, msg);
1107 }
1108
1109 void wxOnAssert(const wxString& file,
1110 int line,
1111 const wxString& func,
1112 const wxString& cond)
1113 {
1114 wxTheAssertHandler(file, line, func, cond, wxString());
1115 }
1116
1117 void wxOnAssert(const wxChar *file,
1118 int line,
1119 const char *func,
1120 const wxChar *cond,
1121 const wxChar *msg)
1122 {
1123 // this is the backwards-compatible version (unless we don't use Unicode)
1124 // so it could be called directly from the user code and this might happen
1125 // even when wxTheAssertHandler is NULL
1126 #if wxUSE_UNICODE
1127 if ( wxTheAssertHandler )
1128 #endif // wxUSE_UNICODE
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 wxString& msg)
1137 {
1138 wxTheAssertHandler(file, line, func, cond, msg);
1139 }
1140
1141 void wxOnAssert(const char *file,
1142 int line,
1143 const char *func,
1144 const char *cond,
1145 const wxCStrData& msg)
1146 {
1147 wxTheAssertHandler(file, line, func, cond, msg);
1148 }
1149
1150 #if wxUSE_UNICODE
1151 void wxOnAssert(const char *file,
1152 int line,
1153 const char *func,
1154 const char *cond)
1155 {
1156 wxTheAssertHandler(file, line, func, cond, wxString());
1157 }
1158
1159 void wxOnAssert(const char *file,
1160 int line,
1161 const char *func,
1162 const char *cond,
1163 const char *msg)
1164 {
1165 wxTheAssertHandler(file, line, func, cond, msg);
1166 }
1167
1168 void wxOnAssert(const char *file,
1169 int line,
1170 const char *func,
1171 const char *cond,
1172 const wxChar *msg)
1173 {
1174 wxTheAssertHandler(file, line, func, cond, msg);
1175 }
1176 #endif // wxUSE_UNICODE
1177
1178 #endif // wxDEBUG_LEVEL
1179
1180 // ============================================================================
1181 // private functions implementation
1182 // ============================================================================
1183
1184 #ifdef __WXDEBUG__
1185
1186 static void LINKAGEMODE SetTraceMasks()
1187 {
1188 #if wxUSE_LOG
1189 wxString mask;
1190 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
1191 {
1192 wxStringTokenizer tkn(mask, wxT(",;:"));
1193 while ( tkn.HasMoreTokens() )
1194 wxLog::AddTraceMask(tkn.GetNextToken());
1195 }
1196 #endif // wxUSE_LOG
1197 }
1198
1199 #endif // __WXDEBUG__
1200
1201 #if wxDEBUG_LEVEL
1202
1203 bool wxTrapInAssert = false;
1204
1205 static
1206 bool DoShowAssertDialog(const wxString& msg)
1207 {
1208 // under Windows we can show the dialog even in the console mode
1209 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1210 wxString msgDlg(msg);
1211
1212 // this message is intentionally not translated -- it is for developers
1213 // only -- and the less code we use here, less is the danger of recursively
1214 // asserting and dying
1215 msgDlg += wxT("\nDo you want to stop the program?\n")
1216 wxT("You can also choose [Cancel] to suppress ")
1217 wxT("further warnings.");
1218
1219 switch ( ::MessageBox(NULL, msgDlg.t_str(), wxT("wxWidgets Debug Alert"),
1220 MB_YESNOCANCEL | MB_ICONSTOP ) )
1221 {
1222 case IDYES:
1223 // If we called wxTrap() directly from here, the programmer would
1224 // see this function and a few more calls between his own code and
1225 // it in the stack trace which would be perfectly useless and often
1226 // confusing. So instead just set the flag here and let the macros
1227 // defined in wx/debug.h call wxTrap() themselves, this ensures
1228 // that the debugger will show the line in the user code containing
1229 // the failing assert.
1230 wxTrapInAssert = true;
1231 break;
1232
1233 case IDCANCEL:
1234 // stop the asserts
1235 return true;
1236
1237 //case IDNO: nothing to do
1238 }
1239 #else // !__WINDOWS__
1240 wxUnusedVar(msg);
1241 #endif // __WINDOWS__/!__WINDOWS__
1242
1243 // continue with the asserts by default
1244 return false;
1245 }
1246
1247 // show the standard assert dialog
1248 static
1249 void ShowAssertDialog(const wxString& file,
1250 int line,
1251 const wxString& func,
1252 const wxString& cond,
1253 const wxString& msgUser,
1254 wxAppTraits *traits)
1255 {
1256 // this variable can be set to true to suppress "assert failure" messages
1257 static bool s_bNoAsserts = false;
1258
1259 wxString msg;
1260 msg.reserve(2048);
1261
1262 // make life easier for people using VC++ IDE by using this format: like
1263 // this, clicking on the message will take us immediately to the place of
1264 // the failed assert
1265 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), file, line, cond);
1266
1267 // add the function name, if any
1268 if ( !func.empty() )
1269 msg << wxT(" in ") << func << wxT("()");
1270
1271 // and the message itself
1272 if ( !msgUser.empty() )
1273 {
1274 msg << wxT(": ") << msgUser;
1275 }
1276 else // no message given
1277 {
1278 msg << wxT('.');
1279 }
1280
1281 #if wxUSE_THREADS
1282 // if we are not in the main thread, output the assert directly and trap
1283 // since dialogs cannot be displayed
1284 if ( !wxThread::IsMain() )
1285 {
1286 msg += wxString::Format(" [in thread %lx]", wxThread::GetCurrentId());
1287 }
1288 #endif // wxUSE_THREADS
1289
1290 // log the assert in any case
1291 wxMessageOutputDebug().Output(msg);
1292
1293 if ( !s_bNoAsserts )
1294 {
1295 if ( traits )
1296 {
1297 // delegate showing assert dialog (if possible) to that class
1298 s_bNoAsserts = traits->ShowAssertDialog(msg);
1299 }
1300 else // no traits object
1301 {
1302 // fall back to the function of last resort
1303 s_bNoAsserts = DoShowAssertDialog(msg);
1304 }
1305 }
1306 }
1307
1308 #endif // wxDEBUG_LEVEL