]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
10.2 fixes
[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 {
373 wxLog::SetVerbose(TRUE);
374 }
375#endif // wxUSE_LOG
376
e2478fde
VZ
377 return TRUE;
378}
379
380bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
381{
382 parser.Usage();
383
384 return FALSE;
385}
386
387bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
388{
389 parser.Usage();
390
391 return FALSE;
392}
393
394#endif // wxUSE_CMDLINE_PARSER
395
396// ----------------------------------------------------------------------------
397// debugging support
398// ----------------------------------------------------------------------------
399
400/* static */
2a7c7605
VS
401bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
402 const char *componentName)
e2478fde 403{
2a7c7605
VS
404#if 0 // can't use wxLogTrace, not up and running yet
405 printf("checking build options object '%s' (ptr %p) in '%s'\n",
406 optionsSignature, optionsSignature, componentName);
e2478fde
VZ
407#endif
408
2a7c7605 409 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
e2478fde 410 {
2a7c7605
VS
411 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
412 wxString prog = wxString::FromAscii(optionsSignature);
413 wxString progName = wxString::FromAscii(componentName);
e2478fde 414 wxString msg;
2dbc444a 415
b880adec 416 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
2a7c7605 417 lib.c_str(), progName.c_str(), prog.c_str());
2dbc444a 418
095d49f2 419 wxLogFatalError(msg.c_str());
e2478fde
VZ
420
421 // normally wxLogFatalError doesn't return
422 return FALSE;
423 }
424#undef wxCMP
425
426 return TRUE;
427}
428
429#ifdef __WXDEBUG__
430
431void wxAppConsole::OnAssert(const wxChar *file,
432 int line,
433 const wxChar *cond,
434 const wxChar *msg)
435{
49d3b775 436 ShowAssertDialog(file, line, cond, msg, GetTraits());
e2478fde
VZ
437}
438
439#endif // __WXDEBUG__
440
441// ============================================================================
442// other classes implementations
443// ============================================================================
444
445// ----------------------------------------------------------------------------
446// wxConsoleAppTraitsBase
447// ----------------------------------------------------------------------------
448
449#if wxUSE_LOG
450
451wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
452{
453 return new wxLogStderr;
454}
455
456#endif // wxUSE_LOG
457
458wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
459{
460 return new wxMessageOutputStderr;
461}
462
463#if wxUSE_FONTMAP
464
465wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
466{
467 return (wxFontMapper *)new wxFontMapperBase;
468}
469
470#endif // wxUSE_FONTMAP
471
f0244295
VZ
472wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
473{
474 // console applications don't use renderers
475 return NULL;
476}
477
8df6de97 478#ifdef __WXDEBUG__
e2478fde
VZ
479bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
480{
481 return wxAppTraitsBase::ShowAssertDialog(msg);
482}
8df6de97 483#endif
e2478fde
VZ
484
485bool wxConsoleAppTraitsBase::HasStderr()
486{
487 // console applications always have stderr, even under Mac/Windows
488 return true;
489}
490
491void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
492{
493 delete object;
494}
495
496void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
497{
498 // nothing to do
499}
2dbc444a 500
38bb138f
VS
501#if wxUSE_SOCKETS
502GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
503{
504 return NULL;
505}
506#endif
e2478fde
VZ
507
508// ----------------------------------------------------------------------------
509// wxAppTraits
510// ----------------------------------------------------------------------------
511
512#ifdef __WXDEBUG__
513
514bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
515{
516 return DoShowAssertDialog(msg);
517}
518
519#endif // __WXDEBUG__
520
e2478fde
VZ
521// ============================================================================
522// global functions implementation
523// ============================================================================
524
525void wxExit()
526{
527 if ( wxTheApp )
528 {
529 wxTheApp->Exit();
530 }
531 else
532 {
533 // what else can we do?
534 exit(-1);
535 }
536}
537
538void wxWakeUpIdle()
539{
540 if ( wxTheApp )
541 {
542 wxTheApp->WakeUpIdle();
543 }
544 //else: do nothing, what can we do?
545}
546
547#ifdef __WXDEBUG__
548
549// wxASSERT() helper
550bool wxAssertIsEqual(int x, int y)
551{
552 return x == y;
553}
554
555// break into the debugger
556void wxTrap()
557{
558#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
559 DebugBreak();
560#elif defined(__WXMAC__) && !defined(__DARWIN__)
561 #if __powerc
562 Debugger();
563 #else
564 SysBreak();
565 #endif
566#elif defined(__UNIX__)
567 raise(SIGTRAP);
568#else
569 // TODO
570#endif // Win/Unix
571}
572
573void wxAssert(int cond,
574 const wxChar *szFile,
575 int nLine,
576 const wxChar *szCond,
2dbc444a 577 const wxChar *szMsg)
e2478fde
VZ
578{
579 if ( !cond )
580 wxOnAssert(szFile, nLine, szCond, szMsg);
581}
582
583// this function is called when an assert fails
584void wxOnAssert(const wxChar *szFile,
585 int nLine,
586 const wxChar *szCond,
587 const wxChar *szMsg)
588{
589 // FIXME MT-unsafe
590 static bool s_bInAssert = FALSE;
591
592 if ( s_bInAssert )
593 {
594 // He-e-e-e-elp!! we're trapped in endless loop
595 wxTrap();
596
597 s_bInAssert = FALSE;
598
599 return;
600 }
601
602 s_bInAssert = TRUE;
603
604 if ( !wxTheApp )
605 {
606 // by default, show the assert dialog box -- we can't customize this
607 // behaviour
608 ShowAssertDialog(szFile, nLine, szCond, szMsg);
609 }
610 else
611 {
612 // let the app process it as it wants
613 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
614 }
615
616 s_bInAssert = FALSE;
617}
618
619#endif // __WXDEBUG__
620
621// ============================================================================
622// private functions implementation
623// ============================================================================
624
625#ifdef __WXDEBUG__
626
627static void LINKAGEMODE SetTraceMasks()
628{
629#if wxUSE_LOG
630 wxString mask;
631 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
632 {
633 wxStringTokenizer tkn(mask, wxT(",;:"));
634 while ( tkn.HasMoreTokens() )
635 wxLog::AddTraceMask(tkn.GetNextToken());
636 }
637#endif // wxUSE_LOG
638}
639
640bool DoShowAssertDialog(const wxString& msg)
641{
642 // under MSW we can show the dialog even in the console mode
643#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
644 wxString msgDlg(msg);
645
646 // this message is intentionally not translated -- it is for
647 // developpers only
648 msgDlg += wxT("\nDo you want to stop the program?\n")
649 wxT("You can also choose [Cancel] to suppress ")
650 wxT("further warnings.");
651
77ffb593 652 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
e2478fde
VZ
653 MB_YESNOCANCEL | MB_ICONSTOP ) )
654 {
655 case IDYES:
656 wxTrap();
657 break;
658
659 case IDCANCEL:
660 // stop the asserts
661 return true;
662
663 //case IDNO: nothing to do
664 }
665#else // !__WXMSW__
666 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
667 fflush(stderr);
668
669 // TODO: ask the user to enter "Y" or "N" on the console?
670 wxTrap();
671#endif // __WXMSW__/!__WXMSW__
672
673 // continue with the asserts
674 return false;
675}
676
677// show the assert modal dialog
678static
679void ShowAssertDialog(const wxChar *szFile,
680 int nLine,
681 const wxChar *szCond,
682 const wxChar *szMsg,
683 wxAppTraits *traits)
684{
685 // this variable can be set to true to suppress "assert failure" messages
686 static bool s_bNoAsserts = FALSE;
687
688 wxString msg;
689 msg.reserve(2048);
690
691 // make life easier for people using VC++ IDE by using this format: like
692 // this, clicking on the message will take us immediately to the place of
693 // the failed assert
694 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
695
696 if ( szMsg )
697 {
698 msg << _T(": ") << szMsg;
699 }
700 else // no message given
701 {
702 msg << _T('.');
703 }
704
705#if wxUSE_THREADS
706 // if we are not in the main thread, output the assert directly and trap
707 // since dialogs cannot be displayed
708 if ( !wxThread::IsMain() )
709 {
710 msg += wxT(" [in child thread]");
711
712#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
713 msg << wxT("\r\n");
714 OutputDebugString(msg );
715#else
716 // send to stderr
717 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
718 fflush(stderr);
719#endif
720 // He-e-e-e-elp!! we're asserting in a child thread
721 wxTrap();
722 }
723#endif // wxUSE_THREADS
724
725 if ( !s_bNoAsserts )
726 {
727 // send it to the normal log destination
56fae7b8 728 wxLogDebug(_T("%s"), msg.c_str());
e2478fde
VZ
729
730 if ( traits )
731 {
732 // delegate showing assert dialog (if possible) to that class
733 s_bNoAsserts = traits->ShowAssertDialog(msg);
734 }
735 else // no traits object
736 {
737 // fall back to the function of last resort
738 s_bNoAsserts = DoShowAssertDialog(msg);
739 }
740 }
741}
742
743#endif // __WXDEBUG__
744