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