]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
No significant change
[wxWidgets.git] / src / common / appbase.cpp
CommitLineData
e2478fde
VZ
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
8df6de97
VS
28 #include "wx/app.h"
29 #include "wx/intl.h"
910426ee 30 #include "wx/list.h"
e2478fde
VZ
31 #if wxUSE_LOG
32 #include "wx/log.h"
33 #endif // wxUSE_LOG
34#endif //WX_PRECOMP
35
56fae7b8 36#include "wx/utils.h"
e2478fde
VZ
37#include "wx/apptrait.h"
38#include "wx/cmdline.h"
39#include "wx/confbase.h"
ce39c39e 40#include "wx/filename.h"
e2478fde
VZ
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
1c193821
JS
52#if wxUSE_FONTMAP
53 #include "wx/fontmap.h"
54#endif // wxUSE_FONTMAP
55
e2478fde 56#if defined(__WXMAC__)
22f69dd4
VZ
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__
e2478fde
VZ
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
92wxApp *wxTheApp = NULL;
93
94wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
95
96// ============================================================================
97// wxAppConsole implementation
98// ============================================================================
99
100// ----------------------------------------------------------------------------
101// ctor/dtor
102// ----------------------------------------------------------------------------
103
104wxAppConsole::wxAppConsole()
105{
106 m_traits = NULL;
107
108 wxTheApp = (wxApp *)this;
109
110#ifdef __WXDEBUG__
111 SetTraceMasks();
112#endif
113}
114
115wxAppConsole::~wxAppConsole()
116{
117 delete m_traits;
118}
119
94826170
VZ
120// ----------------------------------------------------------------------------
121// initilization/cleanup
122// ----------------------------------------------------------------------------
123
05e2b077 124bool wxAppConsole::Initialize(int& argc, wxChar **argv)
94826170
VZ
125{
126 // remember the command line arguments
127 this->argc = argc;
128 this->argv = argv;
129
d546eba9 130 if ( m_appName.empty() && argv )
94826170
VZ
131 {
132 // the application name is, by default, the name of its executable file
94826170 133 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
94826170
VZ
134 }
135
136 return true;
137}
138
139void wxAppConsole::CleanUp()
140{
141}
142
e2478fde
VZ
143// ----------------------------------------------------------------------------
144// OnXXX() callbacks
145// ----------------------------------------------------------------------------
146
147bool 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
177int 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
196void wxAppConsole::Exit()
197{
198 exit(-1);
199}
200
201// ----------------------------------------------------------------------------
202// traits stuff
203// ----------------------------------------------------------------------------
204
205wxAppTraits *wxAppConsole::CreateTraits()
206{
7843d11b 207 return new wxConsoleAppTraits;
e2478fde
VZ
208}
209
210wxAppTraits *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
228wxLog *wxAppConsole::CreateLogTarget()
229{
230 wxAppTraits *traits = GetTraits();
231 return traits ? traits->CreateLogTarget() : NULL;
232}
233
234#endif // wxUSE_LOG
235
236wxMessageOutput *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
248void 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
df5168c4 260 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
e2478fde
VZ
261 while (node)
262 {
263 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
df5168c4 264 wxPendingEvents->Erase(node);
e2478fde
VZ
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
278int 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
294void 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
358bool 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
403bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
404{
405 parser.Usage();
406
407 return FALSE;
408}
409
410bool 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 */
424bool 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
468void 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
488wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
489{
490 return new wxLogStderr;
491}
492
493#endif // wxUSE_LOG
494
495wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
496{
497 return new wxMessageOutputStderr;
498}
499
500#if wxUSE_FONTMAP
501
502wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
503{
504 return (wxFontMapper *)new wxFontMapperBase;
505}
506
507#endif // wxUSE_FONTMAP
508
8df6de97 509#ifdef __WXDEBUG__
e2478fde
VZ
510bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
511{
512 return wxAppTraitsBase::ShowAssertDialog(msg);
513}
8df6de97 514#endif
e2478fde
VZ
515
516bool wxConsoleAppTraitsBase::HasStderr()
517{
518 // console applications always have stderr, even under Mac/Windows
519 return true;
520}
521
522void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
523{
524 delete object;
525}
526
527void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
528{
529 // nothing to do
530}
531
532// ----------------------------------------------------------------------------
533// wxAppTraits
534// ----------------------------------------------------------------------------
535
536#ifdef __WXDEBUG__
537
538bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
539{
540 return DoShowAssertDialog(msg);
541}
542
543#endif // __WXDEBUG__
544
e2478fde
VZ
545// ============================================================================
546// global functions implementation
547// ============================================================================
548
549void 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
562void 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
574bool wxAssertIsEqual(int x, int y)
575{
576 return x == y;
577}
578
579// break into the debugger
580void 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(__UNIX__)
591 raise(SIGTRAP);
592#else
593 // TODO
594#endif // Win/Unix
595}
596
597void wxAssert(int cond,
598 const wxChar *szFile,
599 int nLine,
600 const wxChar *szCond,
601 const wxChar *szMsg)
602{
603 if ( !cond )
604 wxOnAssert(szFile, nLine, szCond, szMsg);
605}
606
607// this function is called when an assert fails
608void wxOnAssert(const wxChar *szFile,
609 int nLine,
610 const wxChar *szCond,
611 const wxChar *szMsg)
612{
613 // FIXME MT-unsafe
614 static bool s_bInAssert = FALSE;
615
616 if ( s_bInAssert )
617 {
618 // He-e-e-e-elp!! we're trapped in endless loop
619 wxTrap();
620
621 s_bInAssert = FALSE;
622
623 return;
624 }
625
626 s_bInAssert = TRUE;
627
628 if ( !wxTheApp )
629 {
630 // by default, show the assert dialog box -- we can't customize this
631 // behaviour
632 ShowAssertDialog(szFile, nLine, szCond, szMsg);
633 }
634 else
635 {
636 // let the app process it as it wants
637 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
638 }
639
640 s_bInAssert = FALSE;
641}
642
643#endif // __WXDEBUG__
644
645// ============================================================================
646// private functions implementation
647// ============================================================================
648
649#ifdef __WXDEBUG__
650
651static void LINKAGEMODE SetTraceMasks()
652{
653#if wxUSE_LOG
654 wxString mask;
655 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
656 {
657 wxStringTokenizer tkn(mask, wxT(",;:"));
658 while ( tkn.HasMoreTokens() )
659 wxLog::AddTraceMask(tkn.GetNextToken());
660 }
661#endif // wxUSE_LOG
662}
663
664bool DoShowAssertDialog(const wxString& msg)
665{
666 // under MSW we can show the dialog even in the console mode
667#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
668 wxString msgDlg(msg);
669
670 // this message is intentionally not translated -- it is for
671 // developpers only
672 msgDlg += wxT("\nDo you want to stop the program?\n")
673 wxT("You can also choose [Cancel] to suppress ")
674 wxT("further warnings.");
675
676 switch ( ::MessageBox(NULL, msgDlg, _T("wxWindows Debug Alert"),
677 MB_YESNOCANCEL | MB_ICONSTOP ) )
678 {
679 case IDYES:
680 wxTrap();
681 break;
682
683 case IDCANCEL:
684 // stop the asserts
685 return true;
686
687 //case IDNO: nothing to do
688 }
689#else // !__WXMSW__
690 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
691 fflush(stderr);
692
693 // TODO: ask the user to enter "Y" or "N" on the console?
694 wxTrap();
695#endif // __WXMSW__/!__WXMSW__
696
697 // continue with the asserts
698 return false;
699}
700
701// show the assert modal dialog
702static
703void ShowAssertDialog(const wxChar *szFile,
704 int nLine,
705 const wxChar *szCond,
706 const wxChar *szMsg,
707 wxAppTraits *traits)
708{
709 // this variable can be set to true to suppress "assert failure" messages
710 static bool s_bNoAsserts = FALSE;
711
712 wxString msg;
713 msg.reserve(2048);
714
715 // make life easier for people using VC++ IDE by using this format: like
716 // this, clicking on the message will take us immediately to the place of
717 // the failed assert
718 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
719
720 if ( szMsg )
721 {
722 msg << _T(": ") << szMsg;
723 }
724 else // no message given
725 {
726 msg << _T('.');
727 }
728
729#if wxUSE_THREADS
730 // if we are not in the main thread, output the assert directly and trap
731 // since dialogs cannot be displayed
732 if ( !wxThread::IsMain() )
733 {
734 msg += wxT(" [in child thread]");
735
736#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
737 msg << wxT("\r\n");
738 OutputDebugString(msg );
739#else
740 // send to stderr
741 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
742 fflush(stderr);
743#endif
744 // He-e-e-e-elp!! we're asserting in a child thread
745 wxTrap();
746 }
747#endif // wxUSE_THREADS
748
749 if ( !s_bNoAsserts )
750 {
751 // send it to the normal log destination
56fae7b8 752 wxLogDebug(_T("%s"), msg.c_str());
e2478fde
VZ
753
754 if ( traits )
755 {
756 // delegate showing assert dialog (if possible) to that class
757 s_bNoAsserts = traits->ShowAssertDialog(msg);
758 }
759 else // no traits object
760 {
761 // fall back to the function of last resort
762 s_bNoAsserts = DoShowAssertDialog(msg);
763 }
764 }
765}
766
767#endif // __WXDEBUG__
768