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