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