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