]> git.saurik.com Git - wxWidgets.git/blob - src/common/appbase.cpp
move code ignoring VK_SPACE and VK_RETURN WM_CHAR messages to MSWDefWindowProc()...
[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 // ensure that we're the only thread to modify the pending events list
273 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
274
275 if ( !wxPendingEvents )
276 {
277 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
278 return;
279 }
280
281 // iterate until the list becomes empty
282 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
283 while (node)
284 {
285 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
286 wxPendingEvents->Erase(node);
287
288 // In ProcessPendingEvents(), new handlers might be add
289 // and we can safely leave the critical section here.
290 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
291 handler->ProcessPendingEvents();
292 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
293
294 node = wxPendingEvents->GetFirst();
295 }
296
297 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
298 }
299
300 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
301 {
302 // process the events normally by default
303 return -1;
304 }
305
306 // ----------------------------------------------------------------------------
307 // exception handling
308 // ----------------------------------------------------------------------------
309
310 #if wxUSE_EXCEPTIONS
311
312 void
313 wxAppConsole::HandleEvent(wxEvtHandler *handler,
314 wxEventFunction func,
315 wxEvent& event) const
316 {
317 // by default, simply call the handler
318 (handler->*func)(event);
319 }
320
321 bool
322 wxAppConsole::OnExceptionInMainLoop()
323 {
324 throw;
325
326 // some compilers are too stupid to know that we never return after throw
327 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
328 return false;
329 #endif
330 }
331
332 #endif // wxUSE_EXCEPTIONS
333
334 // ----------------------------------------------------------------------------
335 // cmd line parsing
336 // ----------------------------------------------------------------------------
337
338 #if wxUSE_CMDLINE_PARSER
339
340 #define OPTION_VERBOSE _T("verbose")
341
342 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
343 {
344 // the standard command line options
345 static const wxCmdLineEntryDesc cmdLineDesc[] =
346 {
347 {
348 wxCMD_LINE_SWITCH,
349 _T("h"),
350 _T("help"),
351 gettext_noop("show this help message"),
352 wxCMD_LINE_VAL_NONE,
353 wxCMD_LINE_OPTION_HELP
354 },
355
356 #if wxUSE_LOG
357 {
358 wxCMD_LINE_SWITCH,
359 wxEmptyString,
360 OPTION_VERBOSE,
361 gettext_noop("generate verbose log messages"),
362 wxCMD_LINE_VAL_NONE,
363 0x0
364 },
365 #endif // wxUSE_LOG
366
367 // terminator
368 {
369 wxCMD_LINE_NONE,
370 wxEmptyString,
371 wxEmptyString,
372 wxEmptyString,
373 wxCMD_LINE_VAL_NONE,
374 0x0
375 }
376 };
377
378 parser.SetDesc(cmdLineDesc);
379 }
380
381 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
382 {
383 #if wxUSE_LOG
384 if ( parser.Found(OPTION_VERBOSE) )
385 {
386 wxLog::SetVerbose(true);
387 }
388 #else
389 wxUnusedVar(parser);
390 #endif // wxUSE_LOG
391
392 return true;
393 }
394
395 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
396 {
397 parser.Usage();
398
399 return false;
400 }
401
402 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
403 {
404 parser.Usage();
405
406 return false;
407 }
408
409 #endif // wxUSE_CMDLINE_PARSER
410
411 // ----------------------------------------------------------------------------
412 // debugging support
413 // ----------------------------------------------------------------------------
414
415 /* static */
416 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
417 const char *componentName)
418 {
419 #if 0 // can't use wxLogTrace, not up and running yet
420 printf("checking build options object '%s' (ptr %p) in '%s'\n",
421 optionsSignature, optionsSignature, componentName);
422 #endif
423
424 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
425 {
426 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
427 wxString prog = wxString::FromAscii(optionsSignature);
428 wxString progName = wxString::FromAscii(componentName);
429 wxString msg;
430
431 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
432 lib.c_str(), progName.c_str(), prog.c_str());
433
434 wxLogFatalError(msg.c_str());
435
436 // normally wxLogFatalError doesn't return
437 return false;
438 }
439 #undef wxCMP
440
441 return true;
442 }
443
444 #ifdef __WXDEBUG__
445
446 void wxAppConsole::OnAssert(const wxChar *file,
447 int line,
448 const wxChar *cond,
449 const wxChar *msg)
450 {
451 ShowAssertDialog(file, line, cond, msg, GetTraits());
452 }
453
454 #endif // __WXDEBUG__
455
456 #if WXWIN_COMPATIBILITY_2_4
457
458 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& buildOptions)
459 {
460 return CheckBuildOptions(buildOptions.m_signature, "your program");
461 }
462
463 #endif
464
465 // ============================================================================
466 // other classes implementations
467 // ============================================================================
468
469 // ----------------------------------------------------------------------------
470 // wxConsoleAppTraitsBase
471 // ----------------------------------------------------------------------------
472
473 #if wxUSE_LOG
474
475 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
476 {
477 return new wxLogStderr;
478 }
479
480 #endif // wxUSE_LOG
481
482 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
483 {
484 return new wxMessageOutputStderr;
485 }
486
487 #if wxUSE_FONTMAP
488
489 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
490 {
491 return (wxFontMapper *)new wxFontMapperBase;
492 }
493
494 #endif // wxUSE_FONTMAP
495
496 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
497 {
498 // console applications don't use renderers
499 return NULL;
500 }
501
502 #ifdef __WXDEBUG__
503 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
504 {
505 return wxAppTraitsBase::ShowAssertDialog(msg);
506 }
507 #endif
508
509 bool wxConsoleAppTraitsBase::HasStderr()
510 {
511 // console applications always have stderr, even under Mac/Windows
512 return true;
513 }
514
515 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
516 {
517 delete object;
518 }
519
520 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
521 {
522 // nothing to do
523 }
524
525 #if wxUSE_SOCKETS
526 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
527 {
528 return NULL;
529 }
530 #endif
531
532 // ----------------------------------------------------------------------------
533 // wxAppTraits
534 // ----------------------------------------------------------------------------
535
536 #ifdef __WXDEBUG__
537
538 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
539 {
540 return DoShowAssertDialog(msg);
541 }
542
543 #endif // __WXDEBUG__
544
545 // ============================================================================
546 // global functions implementation
547 // ============================================================================
548
549 void wxExit()
550 {
551 if ( wxTheApp )
552 {
553 wxTheApp->Exit();
554 }
555 else
556 {
557 // what else can we do?
558 exit(-1);
559 }
560 }
561
562 void wxWakeUpIdle()
563 {
564 if ( wxTheApp )
565 {
566 wxTheApp->WakeUpIdle();
567 }
568 //else: do nothing, what can we do?
569 }
570
571 #ifdef __WXDEBUG__
572
573 // wxASSERT() helper
574 bool wxAssertIsEqual(int x, int y)
575 {
576 return x == y;
577 }
578
579 // break into the debugger
580 void wxTrap()
581 {
582 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
583 DebugBreak();
584 #elif defined(__WXMAC__) && !defined(__DARWIN__)
585 #if __powerc
586 Debugger();
587 #else
588 SysBreak();
589 #endif
590 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
591 Debugger();
592 #elif defined(__UNIX__)
593 raise(SIGTRAP);
594 #else
595 // TODO
596 #endif // Win/Unix
597 }
598
599 void wxAssert(int cond,
600 const wxChar *szFile,
601 int nLine,
602 const wxChar *szCond,
603 const wxChar *szMsg)
604 {
605 if ( !cond )
606 wxOnAssert(szFile, nLine, szCond, szMsg);
607 }
608
609 // this function is called when an assert fails
610 void wxOnAssert(const wxChar *szFile,
611 int nLine,
612 const wxChar *szCond,
613 const wxChar *szMsg)
614 {
615 // FIXME MT-unsafe
616 static bool s_bInAssert = false;
617
618 if ( s_bInAssert )
619 {
620 // He-e-e-e-elp!! we're trapped in endless loop
621 wxTrap();
622
623 s_bInAssert = false;
624
625 return;
626 }
627
628 s_bInAssert = true;
629
630 if ( !wxTheApp )
631 {
632 // by default, show the assert dialog box -- we can't customize this
633 // behaviour
634 ShowAssertDialog(szFile, nLine, szCond, szMsg);
635 }
636 else
637 {
638 // let the app process it as it wants
639 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
640 }
641
642 s_bInAssert = false;
643 }
644
645 #endif // __WXDEBUG__
646
647 // ============================================================================
648 // private functions implementation
649 // ============================================================================
650
651 #ifdef __WXDEBUG__
652
653 static void LINKAGEMODE SetTraceMasks()
654 {
655 #if wxUSE_LOG
656 wxString mask;
657 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
658 {
659 wxStringTokenizer tkn(mask, wxT(",;:"));
660 while ( tkn.HasMoreTokens() )
661 wxLog::AddTraceMask(tkn.GetNextToken());
662 }
663 #endif // wxUSE_LOG
664 }
665
666 bool DoShowAssertDialog(const wxString& msg)
667 {
668 // under MSW we can show the dialog even in the console mode
669 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
670 wxString msgDlg(msg);
671
672 // this message is intentionally not translated -- it is for
673 // developpers only
674 msgDlg += wxT("\nDo you want to stop the program?\n")
675 wxT("You can also choose [Cancel] to suppress ")
676 wxT("further warnings.");
677
678 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
679 MB_YESNOCANCEL | MB_ICONSTOP ) )
680 {
681 case IDYES:
682 wxTrap();
683 break;
684
685 case IDCANCEL:
686 // stop the asserts
687 return true;
688
689 //case IDNO: nothing to do
690 }
691 #else // !__WXMSW__
692 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
693 fflush(stderr);
694
695 // TODO: ask the user to enter "Y" or "N" on the console?
696 wxTrap();
697 #endif // __WXMSW__/!__WXMSW__
698
699 // continue with the asserts
700 return false;
701 }
702
703 // show the assert modal dialog
704 static
705 void ShowAssertDialog(const wxChar *szFile,
706 int nLine,
707 const wxChar *szCond,
708 const wxChar *szMsg,
709 wxAppTraits *traits)
710 {
711 // this variable can be set to true to suppress "assert failure" messages
712 static bool s_bNoAsserts = false;
713
714 wxString msg;
715 msg.reserve(2048);
716
717 // make life easier for people using VC++ IDE by using this format: like
718 // this, clicking on the message will take us immediately to the place of
719 // the failed assert
720 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
721
722 if ( szMsg )
723 {
724 msg << _T(": ") << szMsg;
725 }
726 else // no message given
727 {
728 msg << _T('.');
729 }
730
731 #if wxUSE_STACKWALKER
732 class StackDump : public wxStackWalker
733 {
734 public:
735 StackDump() { }
736
737 const wxString& GetStackTrace() const { return m_stackTrace; }
738
739 protected:
740 virtual void OnStackFrame(const wxStackFrame& frame)
741 {
742 m_stackTrace << wxString::Format(_T("[%02d] "), frame.GetLevel());
743
744 wxString name = frame.GetName();
745 if ( !name.empty() )
746 {
747 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
748 }
749 else
750 {
751 m_stackTrace << wxString::Format
752 (
753 _T("0x%08lx"),
754 (unsigned long)frame.GetAddress()
755 );
756 }
757
758 if ( frame.HasSourceLocation() )
759 {
760 m_stackTrace << _T('\t')
761 << frame.GetFileName()
762 << _T(':')
763 << frame.GetLine();
764 }
765
766 m_stackTrace << _T('\n');
767 }
768
769 private:
770 wxString m_stackTrace;
771 };
772
773 StackDump dump;
774 dump.Walk(5); // don't show OnAssert() call itself
775 wxString stackTrace = dump.GetStackTrace();
776
777 const int maxLines = 10;
778 // Don't show more than maxLines or we could get an enormous dialog
779 int count = stackTrace.Freq(wxT('\n'));
780 if (count > maxLines)
781 {
782 int i;
783 for (i = 0; i < count - maxLines; i++)
784 stackTrace = stackTrace.BeforeLast(wxT('\n'));
785 }
786 if ( !stackTrace.empty() )
787 {
788 msg << _T("\n\nCall stack:\n")
789 << stackTrace;
790 }
791 #endif // wxUSE_STACKWALKER
792
793 #if wxUSE_THREADS
794 // if we are not in the main thread, output the assert directly and trap
795 // since dialogs cannot be displayed
796 if ( !wxThread::IsMain() )
797 {
798 msg += wxT(" [in child thread]");
799
800 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
801 msg << wxT("\r\n");
802 OutputDebugString(msg );
803 #else
804 // send to stderr
805 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
806 fflush(stderr);
807 #endif
808 // He-e-e-e-elp!! we're asserting in a child thread
809 wxTrap();
810 }
811 else
812 #endif // wxUSE_THREADS
813
814 if ( !s_bNoAsserts )
815 {
816 // send it to the normal log destination
817 wxLogDebug(_T("%s"), msg.c_str());
818
819 if ( traits )
820 {
821 // delegate showing assert dialog (if possible) to that class
822 s_bNoAsserts = traits->ShowAssertDialog(msg);
823 }
824 else // no traits object
825 {
826 // fall back to the function of last resort
827 s_bNoAsserts = DoShowAssertDialog(msg);
828 }
829 }
830 }
831
832 #endif // __WXDEBUG__
833