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