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