]> git.saurik.com Git - wxWidgets.git/blob - src/common/appbase.cpp
replaced the old wxApp with wxAppConsole::ms_appInstance of type wxAppConsole; wxTheA...
[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 #include "wx/filename.h"
41 #include "wx/msgout.h"
42 #include "wx/tokenzr.h"
43
44 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
45 #include <signal.h> // for SIGTRAP used by wxTrap()
46 #endif //Win/Unix
47
48 #if defined(__WXMSW__)
49 #include "wx/msw/private.h" // includes windows.h for MessageBox()
50 #endif
51
52 #if wxUSE_FONTMAP
53 #include "wx/fontmap.h"
54 #endif // wxUSE_FONTMAP
55
56 #if defined(__WXMAC__)
57 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
58 // I don't know which headers are needed under earlier systems so
59 // include everything when in doubt
60 #ifdef __DARWIN__
61 #include "MacTypes.h"
62 #else
63 #include "wx/mac/private.h" // includes mac headers
64 #endif
65 #endif // __WXMAC__
66
67 // ----------------------------------------------------------------------------
68 // private functions prototypes
69 // ----------------------------------------------------------------------------
70
71 #ifdef __WXDEBUG__
72 // really just show the assert dialog
73 static bool DoShowAssertDialog(const wxString& msg);
74
75 // prepare for showing the assert dialog, use the given traits or
76 // DoShowAssertDialog() as last fallback to really show it
77 static
78 void ShowAssertDialog(const wxChar *szFile,
79 int nLine,
80 const wxChar *szCond,
81 const wxChar *szMsg,
82 wxAppTraits *traits = NULL);
83
84 // turn on the trace masks specified in the env variable WXTRACE
85 static void LINKAGEMODE SetTraceMasks();
86 #endif // __WXDEBUG__
87
88 // ----------------------------------------------------------------------------
89 // global vars
90 // ----------------------------------------------------------------------------
91
92 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
93
94 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
95
96 // ============================================================================
97 // wxAppConsole implementation
98 // ============================================================================
99
100 // ----------------------------------------------------------------------------
101 // ctor/dtor
102 // ----------------------------------------------------------------------------
103
104 wxAppConsole::wxAppConsole()
105 {
106 m_traits = NULL;
107
108 ms_appInstance = this;
109
110 #ifdef __WXDEBUG__
111 SetTraceMasks();
112 #endif
113 }
114
115 wxAppConsole::~wxAppConsole()
116 {
117 delete m_traits;
118 }
119
120 // ----------------------------------------------------------------------------
121 // initilization/cleanup
122 // ----------------------------------------------------------------------------
123
124 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
125 {
126 // remember the command line arguments
127 this->argc = argc;
128 this->argv = argv;
129
130 if ( m_appName.empty() && argv )
131 {
132 // the application name is, by default, the name of its executable file
133 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
134 }
135
136 return true;
137 }
138
139 void wxAppConsole::CleanUp()
140 {
141 }
142
143 // ----------------------------------------------------------------------------
144 // OnXXX() callbacks
145 // ----------------------------------------------------------------------------
146
147 bool wxAppConsole::OnInit()
148 {
149 #if wxUSE_CMDLINE_PARSER
150 wxCmdLineParser parser(argc, argv);
151
152 OnInitCmdLine(parser);
153
154 bool cont;
155 switch ( parser.Parse(FALSE /* don't show usage */) )
156 {
157 case -1:
158 cont = OnCmdLineHelp(parser);
159 break;
160
161 case 0:
162 cont = OnCmdLineParsed(parser);
163 break;
164
165 default:
166 cont = OnCmdLineError(parser);
167 break;
168 }
169
170 if ( !cont )
171 return FALSE;
172 #endif // wxUSE_CMDLINE_PARSER
173
174 return TRUE;
175 }
176
177 int wxAppConsole::OnExit()
178 {
179 #if wxUSE_CONFIG
180 // delete the config object if any (don't use Get() here, but Set()
181 // because Get() could create a new config object)
182 delete wxConfigBase::Set((wxConfigBase *) NULL);
183 #endif // wxUSE_CONFIG
184
185 #ifdef __WXUNIVERSAL__
186 delete wxTheme::Set(NULL);
187 #endif // __WXUNIVERSAL__
188
189 // use Set(NULL) and not Get() to avoid creating a message output object on
190 // demand when we just want to delete it
191 delete wxMessageOutput::Set(NULL);
192
193 return 0;
194 }
195
196 void wxAppConsole::Exit()
197 {
198 exit(-1);
199 }
200
201 // ----------------------------------------------------------------------------
202 // traits stuff
203 // ----------------------------------------------------------------------------
204
205 wxAppTraits *wxAppConsole::CreateTraits()
206 {
207 return new wxConsoleAppTraits;
208 }
209
210 wxAppTraits *wxAppConsole::GetTraits()
211 {
212 // FIXME-MT: protect this with a CS?
213 if ( !m_traits )
214 {
215 m_traits = CreateTraits();
216
217 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
218 }
219
220 return m_traits;
221 }
222
223 // we must implement CreateXXX() in wxApp itself for backwards compatibility
224 #if WXWIN_COMPATIBILITY_2_4
225
226 #if wxUSE_LOG
227
228 wxLog *wxAppConsole::CreateLogTarget()
229 {
230 wxAppTraits *traits = GetTraits();
231 return traits ? traits->CreateLogTarget() : NULL;
232 }
233
234 #endif // wxUSE_LOG
235
236 wxMessageOutput *wxAppConsole::CreateMessageOutput()
237 {
238 wxAppTraits *traits = GetTraits();
239 return traits ? traits->CreateMessageOutput() : NULL;
240 }
241
242 #endif // WXWIN_COMPATIBILITY_2_4
243
244 // ----------------------------------------------------------------------------
245 // event processing
246 // ----------------------------------------------------------------------------
247
248 void wxAppConsole::ProcessPendingEvents()
249 {
250 // ensure that we're the only thread to modify the pending events list
251 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
252
253 if ( !wxPendingEvents )
254 {
255 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
256 return;
257 }
258
259 // iterate until the list becomes empty
260 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
261 while (node)
262 {
263 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
264 wxPendingEvents->Erase(node);
265
266 // In ProcessPendingEvents(), new handlers might be add
267 // and we can safely leave the critical section here.
268 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
269 handler->ProcessPendingEvents();
270 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
271
272 node = wxPendingEvents->GetFirst();
273 }
274
275 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
276 }
277
278 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
279 {
280 // process the events normally by default
281 return -1;
282 }
283
284 // ----------------------------------------------------------------------------
285 // cmd line parsing
286 // ----------------------------------------------------------------------------
287
288 #if wxUSE_CMDLINE_PARSER
289
290 #define OPTION_VERBOSE _T("verbose")
291 #define OPTION_THEME _T("theme")
292 #define OPTION_MODE _T("mode")
293
294 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
295 {
296 // the standard command line options
297 static const wxCmdLineEntryDesc cmdLineDesc[] =
298 {
299 {
300 wxCMD_LINE_SWITCH,
301 _T("h"),
302 _T("help"),
303 gettext_noop("show this help message"),
304 wxCMD_LINE_VAL_NONE,
305 wxCMD_LINE_OPTION_HELP
306 },
307
308 #if wxUSE_LOG
309 {
310 wxCMD_LINE_SWITCH,
311 _T(""),
312 OPTION_VERBOSE,
313 gettext_noop("generate verbose log messages"),
314 wxCMD_LINE_VAL_NONE,
315 0x0
316 },
317 #endif // wxUSE_LOG
318
319 #ifdef __WXUNIVERSAL__
320 {
321 wxCMD_LINE_OPTION,
322 _T(""),
323 OPTION_THEME,
324 gettext_noop("specify the theme to use"),
325 wxCMD_LINE_VAL_STRING,
326 0x0
327 },
328 #endif // __WXUNIVERSAL__
329
330 #if defined(__WXMGL__)
331 // VS: this is not specific to wxMGL, all fullscreen (framebuffer) ports
332 // should provide this option. That's why it is in common/appcmn.cpp
333 // and not mgl/app.cpp
334 {
335 wxCMD_LINE_OPTION,
336 _T(""),
337 OPTION_MODE,
338 gettext_noop("specify display mode to use (e.g. 640x480-16)"),
339 wxCMD_LINE_VAL_STRING,
340 0x0
341 },
342 #endif // __WXMGL__
343
344 // terminator
345 {
346 wxCMD_LINE_NONE,
347 _T(""),
348 _T(""),
349 _T(""),
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 #endif // wxUSE_LOG
366
367 #ifdef __WXUNIVERSAL__
368 wxString themeName;
369 if ( parser.Found(OPTION_THEME, &themeName) )
370 {
371 wxTheme *theme = wxTheme::Create(themeName);
372 if ( !theme )
373 {
374 wxLogError(_("Unsupported theme '%s'."), themeName.c_str());
375 return FALSE;
376 }
377
378 // Delete the defaultly created theme and set the new theme.
379 delete wxTheme::Get();
380 wxTheme::Set(theme);
381 }
382 #endif // __WXUNIVERSAL__
383
384 #if defined(__WXMGL__)
385 wxString modeDesc;
386 if ( parser.Found(OPTION_MODE, &modeDesc) )
387 {
388 unsigned w, h, bpp;
389 if ( wxSscanf(modeDesc.c_str(), _T("%ux%u-%u"), &w, &h, &bpp) != 3 )
390 {
391 wxLogError(_("Invalid display mode specification '%s'."), modeDesc.c_str());
392 return FALSE;
393 }
394
395 if ( !SetDisplayMode(wxDisplayModeInfo(w, h, bpp)) )
396 return FALSE;
397 }
398 #endif // __WXMGL__
399
400 return TRUE;
401 }
402
403 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
404 {
405 parser.Usage();
406
407 return FALSE;
408 }
409
410 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
411 {
412 parser.Usage();
413
414 return FALSE;
415 }
416
417 #endif // wxUSE_CMDLINE_PARSER
418
419 // ----------------------------------------------------------------------------
420 // debugging support
421 // ----------------------------------------------------------------------------
422
423 /* static */
424 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& opts)
425 {
426 #define wxCMP(what) (what == opts.m_ ## what)
427
428 bool
429 #ifdef __WXDEBUG__
430 isDebug = TRUE;
431 #else
432 isDebug = FALSE;
433 #endif
434
435 int verMaj = wxMAJOR_VERSION,
436 verMin = wxMINOR_VERSION;
437
438 if ( !(wxCMP(isDebug) && wxCMP(verMaj) && wxCMP(verMin)) )
439 {
440 wxString msg;
441 wxString libDebug, progDebug;
442
443 if (isDebug)
444 libDebug = wxT("debug");
445 else
446 libDebug = wxT("no debug");
447
448 if (opts.m_isDebug)
449 progDebug = wxT("debug");
450 else
451 progDebug = wxT("no debug");
452
453 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)."),
454 verMaj, verMin, libDebug.c_str(), opts.m_verMaj, opts.m_verMin, progDebug.c_str());
455
456 wxLogFatalError(msg);
457
458 // normally wxLogFatalError doesn't return
459 return FALSE;
460 }
461 #undef wxCMP
462
463 return TRUE;
464 }
465
466 #ifdef __WXDEBUG__
467
468 void wxAppConsole::OnAssert(const wxChar *file,
469 int line,
470 const wxChar *cond,
471 const wxChar *msg)
472 {
473 ShowAssertDialog(file, line, cond, msg, m_traits);
474 }
475
476 #endif // __WXDEBUG__
477
478 // ============================================================================
479 // other classes implementations
480 // ============================================================================
481
482 // ----------------------------------------------------------------------------
483 // wxConsoleAppTraitsBase
484 // ----------------------------------------------------------------------------
485
486 #if wxUSE_LOG
487
488 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
489 {
490 return new wxLogStderr;
491 }
492
493 #endif // wxUSE_LOG
494
495 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
496 {
497 return new wxMessageOutputStderr;
498 }
499
500 #if wxUSE_FONTMAP
501
502 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
503 {
504 return (wxFontMapper *)new wxFontMapperBase;
505 }
506
507 #endif // wxUSE_FONTMAP
508
509 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
510 {
511 // console applications don't use renderers
512 return NULL;
513 }
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