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