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