]> git.saurik.com Git - wxWidgets.git/blame - src/common/appbase.cpp
Add wxTempFileOutputStream
[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
82ef81ed 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{
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
4055ed82 143#ifndef __WXPALMOS__
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,
b494c48b 348 wxEmptyString,
e2478fde
VZ
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,
b494c48b
WS
359 wxEmptyString,
360 wxEmptyString,
361 wxEmptyString,
e2478fde
VZ
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
eecb33b0
WS
445#if WXWIN_COMPATIBILITY_2_4
446
447bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& buildOptions)
448{
449 return CheckBuildOptions(buildOptions.m_signature, "your program");
450}
451
452#endif
453
e2478fde
VZ
454// ============================================================================
455// other classes implementations
456// ============================================================================
457
458// ----------------------------------------------------------------------------
459// wxConsoleAppTraitsBase
460// ----------------------------------------------------------------------------
461
462#if wxUSE_LOG
463
464wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
465{
466 return new wxLogStderr;
467}
468
469#endif // wxUSE_LOG
470
471wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
472{
473 return new wxMessageOutputStderr;
474}
475
476#if wxUSE_FONTMAP
477
478wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
479{
480 return (wxFontMapper *)new wxFontMapperBase;
481}
482
483#endif // wxUSE_FONTMAP
484
f0244295
VZ
485wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
486{
487 // console applications don't use renderers
488 return NULL;
489}
490
8df6de97 491#ifdef __WXDEBUG__
e2478fde
VZ
492bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
493{
494 return wxAppTraitsBase::ShowAssertDialog(msg);
495}
8df6de97 496#endif
e2478fde
VZ
497
498bool wxConsoleAppTraitsBase::HasStderr()
499{
500 // console applications always have stderr, even under Mac/Windows
501 return true;
502}
503
504void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
505{
506 delete object;
507}
508
509void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
510{
511 // nothing to do
512}
2dbc444a 513
38bb138f
VS
514#if wxUSE_SOCKETS
515GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
516{
517 return NULL;
518}
519#endif
e2478fde
VZ
520
521// ----------------------------------------------------------------------------
522// wxAppTraits
523// ----------------------------------------------------------------------------
524
525#ifdef __WXDEBUG__
526
527bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
528{
529 return DoShowAssertDialog(msg);
530}
531
532#endif // __WXDEBUG__
533
e2478fde
VZ
534// ============================================================================
535// global functions implementation
536// ============================================================================
537
538void wxExit()
539{
540 if ( wxTheApp )
541 {
542 wxTheApp->Exit();
543 }
544 else
545 {
546 // what else can we do?
547 exit(-1);
548 }
549}
550
551void wxWakeUpIdle()
552{
553 if ( wxTheApp )
554 {
555 wxTheApp->WakeUpIdle();
556 }
557 //else: do nothing, what can we do?
558}
559
560#ifdef __WXDEBUG__
561
562// wxASSERT() helper
563bool wxAssertIsEqual(int x, int y)
564{
565 return x == y;
566}
567
568// break into the debugger
569void wxTrap()
570{
571#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
572 DebugBreak();
573#elif defined(__WXMAC__) && !defined(__DARWIN__)
574 #if __powerc
575 Debugger();
576 #else
577 SysBreak();
578 #endif
579#elif defined(__UNIX__)
580 raise(SIGTRAP);
581#else
582 // TODO
583#endif // Win/Unix
584}
585
586void wxAssert(int cond,
587 const wxChar *szFile,
588 int nLine,
589 const wxChar *szCond,
2dbc444a 590 const wxChar *szMsg)
e2478fde
VZ
591{
592 if ( !cond )
593 wxOnAssert(szFile, nLine, szCond, szMsg);
594}
595
596// this function is called when an assert fails
597void wxOnAssert(const wxChar *szFile,
598 int nLine,
599 const wxChar *szCond,
600 const wxChar *szMsg)
601{
602 // FIXME MT-unsafe
4629016d 603 static bool s_bInAssert = false;
e2478fde
VZ
604
605 if ( s_bInAssert )
606 {
607 // He-e-e-e-elp!! we're trapped in endless loop
608 wxTrap();
609
4629016d 610 s_bInAssert = false;
e2478fde
VZ
611
612 return;
613 }
614
4629016d 615 s_bInAssert = true;
e2478fde
VZ
616
617 if ( !wxTheApp )
618 {
619 // by default, show the assert dialog box -- we can't customize this
620 // behaviour
621 ShowAssertDialog(szFile, nLine, szCond, szMsg);
622 }
623 else
624 {
625 // let the app process it as it wants
626 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
627 }
628
4629016d 629 s_bInAssert = false;
e2478fde
VZ
630}
631
632#endif // __WXDEBUG__
633
634// ============================================================================
635// private functions implementation
636// ============================================================================
637
638#ifdef __WXDEBUG__
639
640static void LINKAGEMODE SetTraceMasks()
641{
642#if wxUSE_LOG
643 wxString mask;
644 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
645 {
646 wxStringTokenizer tkn(mask, wxT(",;:"));
647 while ( tkn.HasMoreTokens() )
648 wxLog::AddTraceMask(tkn.GetNextToken());
649 }
650#endif // wxUSE_LOG
651}
652
653bool DoShowAssertDialog(const wxString& msg)
654{
655 // under MSW we can show the dialog even in the console mode
656#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
657 wxString msgDlg(msg);
658
659 // this message is intentionally not translated -- it is for
660 // developpers only
661 msgDlg += wxT("\nDo you want to stop the program?\n")
662 wxT("You can also choose [Cancel] to suppress ")
663 wxT("further warnings.");
664
77ffb593 665 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
e2478fde
VZ
666 MB_YESNOCANCEL | MB_ICONSTOP ) )
667 {
668 case IDYES:
669 wxTrap();
670 break;
671
672 case IDCANCEL:
673 // stop the asserts
674 return true;
675
676 //case IDNO: nothing to do
677 }
678#else // !__WXMSW__
679 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
680 fflush(stderr);
681
682 // TODO: ask the user to enter "Y" or "N" on the console?
683 wxTrap();
684#endif // __WXMSW__/!__WXMSW__
685
686 // continue with the asserts
687 return false;
688}
689
690// show the assert modal dialog
691static
692void ShowAssertDialog(const wxChar *szFile,
693 int nLine,
694 const wxChar *szCond,
695 const wxChar *szMsg,
696 wxAppTraits *traits)
697{
698 // this variable can be set to true to suppress "assert failure" messages
4629016d 699 static bool s_bNoAsserts = false;
e2478fde
VZ
700
701 wxString msg;
702 msg.reserve(2048);
703
704 // make life easier for people using VC++ IDE by using this format: like
705 // this, clicking on the message will take us immediately to the place of
706 // the failed assert
707 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
708
709 if ( szMsg )
710 {
711 msg << _T(": ") << szMsg;
712 }
713 else // no message given
714 {
715 msg << _T('.');
716 }
717
718#if wxUSE_THREADS
719 // if we are not in the main thread, output the assert directly and trap
720 // since dialogs cannot be displayed
721 if ( !wxThread::IsMain() )
722 {
723 msg += wxT(" [in child thread]");
724
725#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
726 msg << wxT("\r\n");
727 OutputDebugString(msg );
728#else
729 // send to stderr
730 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
731 fflush(stderr);
732#endif
733 // He-e-e-e-elp!! we're asserting in a child thread
734 wxTrap();
735 }
736#endif // wxUSE_THREADS
737
738 if ( !s_bNoAsserts )
739 {
740 // send it to the normal log destination
56fae7b8 741 wxLogDebug(_T("%s"), msg.c_str());
e2478fde
VZ
742
743 if ( traits )
744 {
745 // delegate showing assert dialog (if possible) to that class
746 s_bNoAsserts = traits->ShowAssertDialog(msg);
747 }
748 else // no traits object
749 {
750 // fall back to the function of last resort
751 s_bNoAsserts = DoShowAssertDialog(msg);
752 }
753 }
754}
755
756#endif // __WXDEBUG__
757