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