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