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