fix 10.2 shared builds from crashing
[wxWidgets.git] / src / common / appbase.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: common/base/appbase.cpp
3 // Purpose: implements wxAppConsole 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 // License: wxWindows license
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 #include "wx/app.h"
29 #include "wx/intl.h"
30 #include "wx/list.h"
31 #include "wx/log.h"
32 #endif //WX_PRECOMP
33
34 #include "wx/utils.h"
35 #include "wx/apptrait.h"
36 #include "wx/cmdline.h"
37 #include "wx/confbase.h"
38 #include "wx/filename.h"
39 #include "wx/msgout.h"
40 #include "wx/tokenzr.h"
41
42 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
43 #include <signal.h> // for SIGTRAP used by wxTrap()
44 #endif //Win/Unix
45
46 #if defined(__WXMSW__)
47 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
48 #endif
49
50 #if wxUSE_FONTMAP
51 #include "wx/fontmap.h"
52 #endif // wxUSE_FONTMAP
53
54 #if defined(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
55 // For MacTypes.h for Debugger function
56 #include <CoreFoundation/CFBase.h>
57 #endif
58
59 #if defined(__WXMAC__)
60 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
61 // I don't know which headers are needed under earlier systems so
62 // include everything when in doubt
63 #ifdef __DARWIN__
64 #include "MacTypes.h"
65 #else
66 #include "wx/mac/private.h" // includes mac headers
67 #endif
68 #endif // __WXMAC__
69
70 #ifdef __WXDEBUG__
71 #ifdef wxUSE_STACKWALKER
72 #include "wx/stackwalk.h"
73 #endif // wxUSE_STACKWALKER
74 #endif // __WXDEBUG__
75
76 // ----------------------------------------------------------------------------
77 // private functions prototypes
78 // ----------------------------------------------------------------------------
79
80 #ifdef __WXDEBUG__
81 // really just show the assert dialog
82 static bool DoShowAssertDialog(const wxString& msg);
83
84 // prepare for showing the assert dialog, use the given traits or
85 // DoShowAssertDialog() as last fallback to really show it
86 static
87 void ShowAssertDialog(const wxChar *szFile,
88 int nLine,
89 const wxChar *szCond,
90 const wxChar *szMsg,
91 wxAppTraits *traits = NULL);
92
93 // turn on the trace masks specified in the env variable WXTRACE
94 static void LINKAGEMODE SetTraceMasks();
95 #endif // __WXDEBUG__
96
97 // ----------------------------------------------------------------------------
98 // global vars
99 // ----------------------------------------------------------------------------
100
101 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
102
103 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
104
105 // ============================================================================
106 // wxAppConsole implementation
107 // ============================================================================
108
109 // ----------------------------------------------------------------------------
110 // ctor/dtor
111 // ----------------------------------------------------------------------------
112
113 wxAppConsole::wxAppConsole()
114 {
115 m_traits = NULL;
116
117 ms_appInstance = this;
118
119 #ifdef __WXDEBUG__
120 SetTraceMasks();
121 #if wxUSE_UNICODE
122 // In unicode mode the SetTraceMasks call can cause an apptraits to be
123 // created, but since we are still in the constructor the wrong kind will
124 // be created for GUI apps. Destroy it so it can be created again later.
125 delete m_traits;
126 m_traits = NULL;
127 #endif
128 #endif
129 }
130
131 wxAppConsole::~wxAppConsole()
132 {
133 delete m_traits;
134 }
135
136 // ----------------------------------------------------------------------------
137 // initilization/cleanup
138 // ----------------------------------------------------------------------------
139
140 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
141 {
142 #if wxUSE_LOG
143 // If some code logged something before wxApp instance was created,
144 // wxLogStderr was set as the target. Undo it here by destroying the
145 // current target. It will be re-created next time logging is needed, but
146 // this time wxAppTraits will be used:
147 delete wxLog::SetActiveTarget(NULL);
148 #endif // wxUSE_LOG
149
150 // remember the command line arguments
151 this->argc = argc;
152 this->argv = argv;
153
154 #ifndef __WXPALMOS__
155 if ( m_appName.empty() && argv )
156 {
157 // the application name is, by default, the name of its executable file
158 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
159 }
160 #endif
161
162 return true;
163 }
164
165 void wxAppConsole::CleanUp()
166 {
167 }
168
169 // ----------------------------------------------------------------------------
170 // OnXXX() callbacks
171 // ----------------------------------------------------------------------------
172
173 bool wxAppConsole::OnInit()
174 {
175 #if wxUSE_CMDLINE_PARSER
176 wxCmdLineParser parser(argc, argv);
177
178 OnInitCmdLine(parser);
179
180 bool cont;
181 switch ( parser.Parse(false /* don't show usage */) )
182 {
183 case -1:
184 cont = OnCmdLineHelp(parser);
185 break;
186
187 case 0:
188 cont = OnCmdLineParsed(parser);
189 break;
190
191 default:
192 cont = OnCmdLineError(parser);
193 break;
194 }
195
196 if ( !cont )
197 return false;
198 #endif // wxUSE_CMDLINE_PARSER
199
200 return true;
201 }
202
203 int wxAppConsole::OnExit()
204 {
205 #if wxUSE_CONFIG
206 // delete the config object if any (don't use Get() here, but Set()
207 // because Get() could create a new config object)
208 delete wxConfigBase::Set((wxConfigBase *) NULL);
209 #endif // wxUSE_CONFIG
210
211 // use Set(NULL) and not Get() to avoid creating a message output object on
212 // demand when we just want to delete it
213 delete wxMessageOutput::Set(NULL);
214
215 return 0;
216 }
217
218 void wxAppConsole::Exit()
219 {
220 exit(-1);
221 }
222
223 // ----------------------------------------------------------------------------
224 // traits stuff
225 // ----------------------------------------------------------------------------
226
227 wxAppTraits *wxAppConsole::CreateTraits()
228 {
229 return new wxConsoleAppTraits;
230 }
231
232 wxAppTraits *wxAppConsole::GetTraits()
233 {
234 // FIXME-MT: protect this with a CS?
235 if ( !m_traits )
236 {
237 m_traits = CreateTraits();
238
239 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
240 }
241
242 return m_traits;
243 }
244
245 // we must implement CreateXXX() in wxApp itself for backwards compatibility
246 #if WXWIN_COMPATIBILITY_2_4
247
248 #if wxUSE_LOG
249
250 wxLog *wxAppConsole::CreateLogTarget()
251 {
252 wxAppTraits *traits = GetTraits();
253 return traits ? traits->CreateLogTarget() : NULL;
254 }
255
256 #endif // wxUSE_LOG
257
258 wxMessageOutput *wxAppConsole::CreateMessageOutput()
259 {
260 wxAppTraits *traits = GetTraits();
261 return traits ? traits->CreateMessageOutput() : NULL;
262 }
263
264 #endif // WXWIN_COMPATIBILITY_2_4
265
266 // ----------------------------------------------------------------------------
267 // event processing
268 // ----------------------------------------------------------------------------
269
270 void wxAppConsole::ProcessPendingEvents()
271 {
272 if ( !wxPendingEventsLocker )
273 return;
274
275 // ensure that we're the only thread to modify the pending events list
276 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
277
278 if ( !wxPendingEvents )
279 {
280 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
281 return;
282 }
283
284 // iterate until the list becomes empty
285 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
286 while (node)
287 {
288 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
289 wxPendingEvents->Erase(node);
290
291 // In ProcessPendingEvents(), new handlers might be add
292 // and we can safely leave the critical section here.
293 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
294 handler->ProcessPendingEvents();
295 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
296
297 node = wxPendingEvents->GetFirst();
298 }
299
300 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
301 }
302
303 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
304 {
305 // process the events normally by default
306 return -1;
307 }
308
309 // ----------------------------------------------------------------------------
310 // exception handling
311 // ----------------------------------------------------------------------------
312
313 #if wxUSE_EXCEPTIONS
314
315 void
316 wxAppConsole::HandleEvent(wxEvtHandler *handler,
317 wxEventFunction func,
318 wxEvent& event) const
319 {
320 // by default, simply call the handler
321 (handler->*func)(event);
322 }
323
324 bool
325 wxAppConsole::OnExceptionInMainLoop()
326 {
327 throw;
328
329 // some compilers are too stupid to know that we never return after throw
330 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
331 return false;
332 #endif
333 }
334
335 #endif // wxUSE_EXCEPTIONS
336
337 // ----------------------------------------------------------------------------
338 // cmd line parsing
339 // ----------------------------------------------------------------------------
340
341 #if wxUSE_CMDLINE_PARSER
342
343 #define OPTION_VERBOSE _T("verbose")
344
345 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
346 {
347 // the standard command line options
348 static const wxCmdLineEntryDesc cmdLineDesc[] =
349 {
350 {
351 wxCMD_LINE_SWITCH,
352 _T("h"),
353 _T("help"),
354 gettext_noop("show this help message"),
355 wxCMD_LINE_VAL_NONE,
356 wxCMD_LINE_OPTION_HELP
357 },
358
359 #if wxUSE_LOG
360 {
361 wxCMD_LINE_SWITCH,
362 wxEmptyString,
363 OPTION_VERBOSE,
364 gettext_noop("generate verbose log messages"),
365 wxCMD_LINE_VAL_NONE,
366 0x0
367 },
368 #endif // wxUSE_LOG
369
370 // terminator
371 {
372 wxCMD_LINE_NONE,
373 wxEmptyString,
374 wxEmptyString,
375 wxEmptyString,
376 wxCMD_LINE_VAL_NONE,
377 0x0
378 }
379 };
380
381 parser.SetDesc(cmdLineDesc);
382 }
383
384 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
385 {
386 #if wxUSE_LOG
387 if ( parser.Found(OPTION_VERBOSE) )
388 {
389 wxLog::SetVerbose(true);
390 }
391 #else
392 wxUnusedVar(parser);
393 #endif // wxUSE_LOG
394
395 return true;
396 }
397
398 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
399 {
400 parser.Usage();
401
402 return false;
403 }
404
405 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
406 {
407 parser.Usage();
408
409 return false;
410 }
411
412 #endif // wxUSE_CMDLINE_PARSER
413
414 // ----------------------------------------------------------------------------
415 // debugging support
416 // ----------------------------------------------------------------------------
417
418 /* static */
419 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
420 const char *componentName)
421 {
422 #if 0 // can't use wxLogTrace, not up and running yet
423 printf("checking build options object '%s' (ptr %p) in '%s'\n",
424 optionsSignature, optionsSignature, componentName);
425 #endif
426
427 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
428 {
429 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
430 wxString prog = wxString::FromAscii(optionsSignature);
431 wxString progName = wxString::FromAscii(componentName);
432 wxString msg;
433
434 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
435 lib.c_str(), progName.c_str(), prog.c_str());
436
437 wxLogFatalError(msg.c_str());
438
439 // normally wxLogFatalError doesn't return
440 return false;
441 }
442 #undef wxCMP
443
444 return true;
445 }
446
447 #ifdef __WXDEBUG__
448
449 void wxAppConsole::OnAssert(const wxChar *file,
450 int line,
451 const wxChar *cond,
452 const wxChar *msg)
453 {
454 ShowAssertDialog(file, line, cond, msg, GetTraits());
455 }
456
457 #endif // __WXDEBUG__
458
459 #if WXWIN_COMPATIBILITY_2_4
460
461 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& buildOptions)
462 {
463 return CheckBuildOptions(buildOptions.m_signature, "your program");
464 }
465
466 #endif
467
468 // ============================================================================
469 // other classes implementations
470 // ============================================================================
471
472 // ----------------------------------------------------------------------------
473 // wxConsoleAppTraitsBase
474 // ----------------------------------------------------------------------------
475
476 #if wxUSE_LOG
477
478 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
479 {
480 return new wxLogStderr;
481 }
482
483 #endif // wxUSE_LOG
484
485 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
486 {
487 return new wxMessageOutputStderr;
488 }
489
490 #if wxUSE_FONTMAP
491
492 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
493 {
494 return (wxFontMapper *)new wxFontMapperBase;
495 }
496
497 #endif // wxUSE_FONTMAP
498
499 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
500 {
501 // console applications don't use renderers
502 return NULL;
503 }
504
505 #ifdef __WXDEBUG__
506 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
507 {
508 return wxAppTraitsBase::ShowAssertDialog(msg);
509 }
510 #endif
511
512 bool wxConsoleAppTraitsBase::HasStderr()
513 {
514 // console applications always have stderr, even under Mac/Windows
515 return true;
516 }
517
518 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
519 {
520 delete object;
521 }
522
523 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
524 {
525 // nothing to do
526 }
527
528 #if wxUSE_SOCKETS
529 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
530 {
531 return NULL;
532 }
533 #endif
534
535 // ----------------------------------------------------------------------------
536 // wxAppTraits
537 // ----------------------------------------------------------------------------
538
539 #ifdef __WXDEBUG__
540
541 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
542 {
543 return DoShowAssertDialog(msg);
544 }
545
546 #endif // __WXDEBUG__
547
548 // ============================================================================
549 // global functions implementation
550 // ============================================================================
551
552 void wxExit()
553 {
554 if ( wxTheApp )
555 {
556 wxTheApp->Exit();
557 }
558 else
559 {
560 // what else can we do?
561 exit(-1);
562 }
563 }
564
565 void wxWakeUpIdle()
566 {
567 if ( wxTheApp )
568 {
569 wxTheApp->WakeUpIdle();
570 }
571 //else: do nothing, what can we do?
572 }
573
574 #ifdef __WXDEBUG__
575
576 // wxASSERT() helper
577 bool wxAssertIsEqual(int x, int y)
578 {
579 return x == y;
580 }
581
582 // break into the debugger
583 void wxTrap()
584 {
585 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
586 DebugBreak();
587 #elif defined(__WXMAC__) && !defined(__DARWIN__)
588 #if __powerc
589 Debugger();
590 #else
591 SysBreak();
592 #endif
593 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
594 Debugger();
595 #elif defined(__UNIX__)
596 raise(SIGTRAP);
597 #else
598 // TODO
599 #endif // Win/Unix
600 }
601
602 void wxAssert(int cond,
603 const wxChar *szFile,
604 int nLine,
605 const wxChar *szCond,
606 const wxChar *szMsg)
607 {
608 if ( !cond )
609 wxOnAssert(szFile, nLine, szCond, szMsg);
610 }
611
612 // this function is called when an assert fails
613 void wxOnAssert(const wxChar *szFile,
614 int nLine,
615 const wxChar *szCond,
616 const wxChar *szMsg)
617 {
618 // FIXME MT-unsafe
619 static bool s_bInAssert = false;
620
621 if ( s_bInAssert )
622 {
623 // He-e-e-e-elp!! we're trapped in endless loop
624 wxTrap();
625
626 s_bInAssert = false;
627
628 return;
629 }
630
631 s_bInAssert = true;
632
633 if ( !wxTheApp )
634 {
635 // by default, show the assert dialog box -- we can't customize this
636 // behaviour
637 ShowAssertDialog(szFile, nLine, szCond, szMsg);
638 }
639 else
640 {
641 // let the app process it as it wants
642 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
643 }
644
645 s_bInAssert = false;
646 }
647
648 #endif // __WXDEBUG__
649
650 // ============================================================================
651 // private functions implementation
652 // ============================================================================
653
654 #ifdef __WXDEBUG__
655
656 static void LINKAGEMODE SetTraceMasks()
657 {
658 #if wxUSE_LOG
659 wxString mask;
660 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
661 {
662 wxStringTokenizer tkn(mask, wxT(",;:"));
663 while ( tkn.HasMoreTokens() )
664 wxLog::AddTraceMask(tkn.GetNextToken());
665 }
666 #endif // wxUSE_LOG
667 }
668
669 bool DoShowAssertDialog(const wxString& msg)
670 {
671 // under MSW we can show the dialog even in the console mode
672 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
673 wxString msgDlg(msg);
674
675 // this message is intentionally not translated -- it is for
676 // developpers only
677 msgDlg += wxT("\nDo you want to stop the program?\n")
678 wxT("You can also choose [Cancel] to suppress ")
679 wxT("further warnings.");
680
681 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
682 MB_YESNOCANCEL | MB_ICONSTOP ) )
683 {
684 case IDYES:
685 wxTrap();
686 break;
687
688 case IDCANCEL:
689 // stop the asserts
690 return true;
691
692 //case IDNO: nothing to do
693 }
694 #else // !__WXMSW__
695 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
696 fflush(stderr);
697
698 // TODO: ask the user to enter "Y" or "N" on the console?
699 wxTrap();
700 #endif // __WXMSW__/!__WXMSW__
701
702 // continue with the asserts
703 return false;
704 }
705
706 // show the assert modal dialog
707 static
708 void ShowAssertDialog(const wxChar *szFile,
709 int nLine,
710 const wxChar *szCond,
711 const wxChar *szMsg,
712 wxAppTraits *traits)
713 {
714 // this variable can be set to true to suppress "assert failure" messages
715 static bool s_bNoAsserts = false;
716
717 wxString msg;
718 msg.reserve(2048);
719
720 // make life easier for people using VC++ IDE by using this format: like
721 // this, clicking on the message will take us immediately to the place of
722 // the failed assert
723 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
724
725 if ( szMsg )
726 {
727 msg << _T(": ") << szMsg;
728 }
729 else // no message given
730 {
731 msg << _T('.');
732 }
733
734 #if wxUSE_STACKWALKER
735 class StackDump : public wxStackWalker
736 {
737 public:
738 StackDump() { }
739
740 const wxString& GetStackTrace() const { return m_stackTrace; }
741
742 protected:
743 virtual void OnStackFrame(const wxStackFrame& frame)
744 {
745 m_stackTrace << wxString::Format(_T("[%02d] "), frame.GetLevel());
746
747 wxString name = frame.GetName();
748 if ( !name.empty() )
749 {
750 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
751 }
752 else
753 {
754 m_stackTrace << wxString::Format
755 (
756 _T("0x%08lx"),
757 (unsigned long)frame.GetAddress()
758 );
759 }
760
761 if ( frame.HasSourceLocation() )
762 {
763 m_stackTrace << _T('\t')
764 << frame.GetFileName()
765 << _T(':')
766 << frame.GetLine();
767 }
768
769 m_stackTrace << _T('\n');
770 }
771
772 private:
773 wxString m_stackTrace;
774 };
775
776 StackDump dump;
777 dump.Walk(5); // don't show OnAssert() call itself
778 wxString stackTrace = dump.GetStackTrace();
779
780 // don't show more than maxLines or we could get a dialog too tall to be
781 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
782 // characters it is still only 300 pixels...
783 const int maxLines = 20;
784 int count = stackTrace.Freq(wxT('\n'));
785 if (count > maxLines)
786 {
787 int i;
788 for (i = 0; i < count - maxLines; i++)
789 stackTrace = stackTrace.BeforeLast(wxT('\n'));
790 }
791 if ( !stackTrace.empty() )
792 {
793 msg << _T("\n\nCall stack:\n")
794 << stackTrace;
795 }
796 #endif // wxUSE_STACKWALKER
797
798 #if wxUSE_THREADS
799 // if we are not in the main thread, output the assert directly and trap
800 // since dialogs cannot be displayed
801 if ( !wxThread::IsMain() )
802 {
803 msg += wxT(" [in child thread]");
804
805 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
806 msg << wxT("\r\n");
807 OutputDebugString(msg );
808 #else
809 // send to stderr
810 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
811 fflush(stderr);
812 #endif
813 // He-e-e-e-elp!! we're asserting in a child thread
814 wxTrap();
815 }
816 else
817 #endif // wxUSE_THREADS
818
819 if ( !s_bNoAsserts )
820 {
821 // send it to the normal log destination
822 wxLogDebug(_T("%s"), msg.c_str());
823
824 if ( traits )
825 {
826 // delegate showing assert dialog (if possible) to that class
827 s_bNoAsserts = traits->ShowAssertDialog(msg);
828 }
829 else // no traits object
830 {
831 // fall back to the function of last resort
832 s_bNoAsserts = DoShowAssertDialog(msg);
833 }
834 }
835 }
836
837 #endif // __WXDEBUG__
838