]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
added support for range types to runtime depersister
[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
7cafd224 92wxAppConsole *wxAppConsole::ms_appInstance = NULL;
e2478fde
VZ
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
7cafd224 108 ms_appInstance = this;
e2478fde
VZ
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
e2478fde
VZ
185 // use Set(NULL) and not Get() to avoid creating a message output object on
186 // demand when we just want to delete it
187 delete wxMessageOutput::Set(NULL);
188
189 return 0;
190}
191
192void wxAppConsole::Exit()
193{
194 exit(-1);
195}
196
197// ----------------------------------------------------------------------------
198// traits stuff
199// ----------------------------------------------------------------------------
200
201wxAppTraits *wxAppConsole::CreateTraits()
202{
7843d11b 203 return new wxConsoleAppTraits;
e2478fde
VZ
204}
205
206wxAppTraits *wxAppConsole::GetTraits()
207{
208 // FIXME-MT: protect this with a CS?
209 if ( !m_traits )
210 {
211 m_traits = CreateTraits();
212
213 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
214 }
215
216 return m_traits;
217}
218
219// we must implement CreateXXX() in wxApp itself for backwards compatibility
220#if WXWIN_COMPATIBILITY_2_4
221
222#if wxUSE_LOG
223
224wxLog *wxAppConsole::CreateLogTarget()
225{
226 wxAppTraits *traits = GetTraits();
227 return traits ? traits->CreateLogTarget() : NULL;
228}
229
230#endif // wxUSE_LOG
231
232wxMessageOutput *wxAppConsole::CreateMessageOutput()
233{
234 wxAppTraits *traits = GetTraits();
235 return traits ? traits->CreateMessageOutput() : NULL;
236}
237
238#endif // WXWIN_COMPATIBILITY_2_4
239
240// ----------------------------------------------------------------------------
241// event processing
242// ----------------------------------------------------------------------------
243
244void wxAppConsole::ProcessPendingEvents()
245{
246 // ensure that we're the only thread to modify the pending events list
247 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
248
249 if ( !wxPendingEvents )
250 {
251 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
252 return;
253 }
254
255 // iterate until the list becomes empty
df5168c4 256 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
e2478fde
VZ
257 while (node)
258 {
259 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
df5168c4 260 wxPendingEvents->Erase(node);
e2478fde
VZ
261
262 // In ProcessPendingEvents(), new handlers might be add
263 // and we can safely leave the critical section here.
264 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
265 handler->ProcessPendingEvents();
266 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
267
268 node = wxPendingEvents->GetFirst();
269 }
270
271 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
272}
273
274int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
275{
276 // process the events normally by default
277 return -1;
278}
279
280// ----------------------------------------------------------------------------
281// cmd line parsing
282// ----------------------------------------------------------------------------
283
284#if wxUSE_CMDLINE_PARSER
285
286#define OPTION_VERBOSE _T("verbose")
e2478fde
VZ
287
288void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
289{
290 // the standard command line options
291 static const wxCmdLineEntryDesc cmdLineDesc[] =
292 {
293 {
294 wxCMD_LINE_SWITCH,
295 _T("h"),
296 _T("help"),
297 gettext_noop("show this help message"),
298 wxCMD_LINE_VAL_NONE,
299 wxCMD_LINE_OPTION_HELP
300 },
301
302#if wxUSE_LOG
303 {
304 wxCMD_LINE_SWITCH,
305 _T(""),
306 OPTION_VERBOSE,
307 gettext_noop("generate verbose log messages"),
308 wxCMD_LINE_VAL_NONE,
309 0x0
310 },
311#endif // wxUSE_LOG
312
e2478fde
VZ
313 // terminator
314 {
315 wxCMD_LINE_NONE,
316 _T(""),
317 _T(""),
318 _T(""),
319 wxCMD_LINE_VAL_NONE,
320 0x0
321 }
322 };
323
324 parser.SetDesc(cmdLineDesc);
325}
326
327bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
328{
329#if wxUSE_LOG
330 if ( parser.Found(OPTION_VERBOSE) )
331 {
332 wxLog::SetVerbose(TRUE);
333 }
334#endif // wxUSE_LOG
335
e2478fde
VZ
336 return TRUE;
337}
338
339bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
340{
341 parser.Usage();
342
343 return FALSE;
344}
345
346bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
347{
348 parser.Usage();
349
350 return FALSE;
351}
352
353#endif // wxUSE_CMDLINE_PARSER
354
355// ----------------------------------------------------------------------------
356// debugging support
357// ----------------------------------------------------------------------------
358
359/* static */
2a7c7605
VS
360bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
361 const char *componentName)
e2478fde 362{
2a7c7605
VS
363#if 0 // can't use wxLogTrace, not up and running yet
364 printf("checking build options object '%s' (ptr %p) in '%s'\n",
365 optionsSignature, optionsSignature, componentName);
e2478fde
VZ
366#endif
367
2a7c7605 368 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
e2478fde 369 {
2a7c7605
VS
370 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
371 wxString prog = wxString::FromAscii(optionsSignature);
372 wxString progName = wxString::FromAscii(componentName);
e2478fde 373 wxString msg;
e2478fde 374
b880adec 375 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
2a7c7605 376 lib.c_str(), progName.c_str(), prog.c_str());
e2478fde
VZ
377
378 wxLogFatalError(msg);
379
380 // normally wxLogFatalError doesn't return
381 return FALSE;
382 }
383#undef wxCMP
384
385 return TRUE;
386}
387
388#ifdef __WXDEBUG__
389
390void wxAppConsole::OnAssert(const wxChar *file,
391 int line,
392 const wxChar *cond,
393 const wxChar *msg)
394{
395 ShowAssertDialog(file, line, cond, msg, m_traits);
396}
397
398#endif // __WXDEBUG__
399
400// ============================================================================
401// other classes implementations
402// ============================================================================
403
404// ----------------------------------------------------------------------------
405// wxConsoleAppTraitsBase
406// ----------------------------------------------------------------------------
407
408#if wxUSE_LOG
409
410wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
411{
412 return new wxLogStderr;
413}
414
415#endif // wxUSE_LOG
416
417wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
418{
419 return new wxMessageOutputStderr;
420}
421
422#if wxUSE_FONTMAP
423
424wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
425{
426 return (wxFontMapper *)new wxFontMapperBase;
427}
428
429#endif // wxUSE_FONTMAP
430
f0244295
VZ
431wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
432{
433 // console applications don't use renderers
434 return NULL;
435}
436
8df6de97 437#ifdef __WXDEBUG__
e2478fde
VZ
438bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
439{
440 return wxAppTraitsBase::ShowAssertDialog(msg);
441}
8df6de97 442#endif
e2478fde
VZ
443
444bool wxConsoleAppTraitsBase::HasStderr()
445{
446 // console applications always have stderr, even under Mac/Windows
447 return true;
448}
449
450void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
451{
452 delete object;
453}
454
455void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
456{
457 // nothing to do
458}
38bb138f
VS
459
460#if wxUSE_SOCKETS
461GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
462{
463 return NULL;
464}
465#endif
e2478fde
VZ
466
467// ----------------------------------------------------------------------------
468// wxAppTraits
469// ----------------------------------------------------------------------------
470
471#ifdef __WXDEBUG__
472
473bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
474{
475 return DoShowAssertDialog(msg);
476}
477
478#endif // __WXDEBUG__
479
e2478fde
VZ
480// ============================================================================
481// global functions implementation
482// ============================================================================
483
484void wxExit()
485{
486 if ( wxTheApp )
487 {
488 wxTheApp->Exit();
489 }
490 else
491 {
492 // what else can we do?
493 exit(-1);
494 }
495}
496
497void wxWakeUpIdle()
498{
499 if ( wxTheApp )
500 {
501 wxTheApp->WakeUpIdle();
502 }
503 //else: do nothing, what can we do?
504}
505
506#ifdef __WXDEBUG__
507
508// wxASSERT() helper
509bool wxAssertIsEqual(int x, int y)
510{
511 return x == y;
512}
513
514// break into the debugger
515void wxTrap()
516{
517#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
518 DebugBreak();
519#elif defined(__WXMAC__) && !defined(__DARWIN__)
520 #if __powerc
521 Debugger();
522 #else
523 SysBreak();
524 #endif
525#elif defined(__UNIX__)
526 raise(SIGTRAP);
527#else
528 // TODO
529#endif // Win/Unix
530}
531
532void wxAssert(int cond,
533 const wxChar *szFile,
534 int nLine,
535 const wxChar *szCond,
536 const wxChar *szMsg)
537{
538 if ( !cond )
539 wxOnAssert(szFile, nLine, szCond, szMsg);
540}
541
542// this function is called when an assert fails
543void wxOnAssert(const wxChar *szFile,
544 int nLine,
545 const wxChar *szCond,
546 const wxChar *szMsg)
547{
548 // FIXME MT-unsafe
549 static bool s_bInAssert = FALSE;
550
551 if ( s_bInAssert )
552 {
553 // He-e-e-e-elp!! we're trapped in endless loop
554 wxTrap();
555
556 s_bInAssert = FALSE;
557
558 return;
559 }
560
561 s_bInAssert = TRUE;
562
563 if ( !wxTheApp )
564 {
565 // by default, show the assert dialog box -- we can't customize this
566 // behaviour
567 ShowAssertDialog(szFile, nLine, szCond, szMsg);
568 }
569 else
570 {
571 // let the app process it as it wants
572 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
573 }
574
575 s_bInAssert = FALSE;
576}
577
578#endif // __WXDEBUG__
579
580// ============================================================================
581// private functions implementation
582// ============================================================================
583
584#ifdef __WXDEBUG__
585
586static void LINKAGEMODE SetTraceMasks()
587{
588#if wxUSE_LOG
589 wxString mask;
590 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
591 {
592 wxStringTokenizer tkn(mask, wxT(",;:"));
593 while ( tkn.HasMoreTokens() )
594 wxLog::AddTraceMask(tkn.GetNextToken());
595 }
596#endif // wxUSE_LOG
597}
598
599bool DoShowAssertDialog(const wxString& msg)
600{
601 // under MSW we can show the dialog even in the console mode
602#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
603 wxString msgDlg(msg);
604
605 // this message is intentionally not translated -- it is for
606 // developpers only
607 msgDlg += wxT("\nDo you want to stop the program?\n")
608 wxT("You can also choose [Cancel] to suppress ")
609 wxT("further warnings.");
610
611 switch ( ::MessageBox(NULL, msgDlg, _T("wxWindows Debug Alert"),
612 MB_YESNOCANCEL | MB_ICONSTOP ) )
613 {
614 case IDYES:
615 wxTrap();
616 break;
617
618 case IDCANCEL:
619 // stop the asserts
620 return true;
621
622 //case IDNO: nothing to do
623 }
624#else // !__WXMSW__
625 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
626 fflush(stderr);
627
628 // TODO: ask the user to enter "Y" or "N" on the console?
629 wxTrap();
630#endif // __WXMSW__/!__WXMSW__
631
632 // continue with the asserts
633 return false;
634}
635
636// show the assert modal dialog
637static
638void ShowAssertDialog(const wxChar *szFile,
639 int nLine,
640 const wxChar *szCond,
641 const wxChar *szMsg,
642 wxAppTraits *traits)
643{
644 // this variable can be set to true to suppress "assert failure" messages
645 static bool s_bNoAsserts = FALSE;
646
647 wxString msg;
648 msg.reserve(2048);
649
650 // make life easier for people using VC++ IDE by using this format: like
651 // this, clicking on the message will take us immediately to the place of
652 // the failed assert
653 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
654
655 if ( szMsg )
656 {
657 msg << _T(": ") << szMsg;
658 }
659 else // no message given
660 {
661 msg << _T('.');
662 }
663
664#if wxUSE_THREADS
665 // if we are not in the main thread, output the assert directly and trap
666 // since dialogs cannot be displayed
667 if ( !wxThread::IsMain() )
668 {
669 msg += wxT(" [in child thread]");
670
671#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
672 msg << wxT("\r\n");
673 OutputDebugString(msg );
674#else
675 // send to stderr
676 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
677 fflush(stderr);
678#endif
679 // He-e-e-e-elp!! we're asserting in a child thread
680 wxTrap();
681 }
682#endif // wxUSE_THREADS
683
684 if ( !s_bNoAsserts )
685 {
686 // send it to the normal log destination
56fae7b8 687 wxLogDebug(_T("%s"), msg.c_str());
e2478fde
VZ
688
689 if ( traits )
690 {
691 // delegate showing assert dialog (if possible) to that class
692 s_bNoAsserts = traits->ShowAssertDialog(msg);
693 }
694 else // no traits object
695 {
696 // fall back to the function of last resort
697 s_bNoAsserts = DoShowAssertDialog(msg);
698 }
699 }
700}
701
702#endif // __WXDEBUG__
703