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