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