Old API deprecated. Use new and remove old usage where necessary.
[wxWidgets.git] / src / common / appbase.cpp
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
28 #include "wx/app.h"
29 #include "wx/intl.h"
30 #include "wx/list.h"
31 #include "wx/log.h"
32 #endif //WX_PRECOMP
33
34 #include "wx/utils.h"
35 #include "wx/apptrait.h"
36 #include "wx/cmdline.h"
37 #include "wx/confbase.h"
38 #include "wx/filename.h"
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__)
47 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
48 #endif
49
50 #if wxUSE_FONTMAP
51 #include "wx/fontmap.h"
52 #endif // wxUSE_FONTMAP
53
54 #if defined(__WXMAC__)
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__
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
90 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
91
92 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
93
94 // ============================================================================
95 // wxAppConsole implementation
96 // ============================================================================
97
98 // ----------------------------------------------------------------------------
99 // ctor/dtor
100 // ----------------------------------------------------------------------------
101
102 wxAppConsole::wxAppConsole()
103 {
104 m_traits = NULL;
105
106 ms_appInstance = this;
107
108 #ifdef __WXDEBUG__
109 SetTraceMasks();
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
117 #endif
118 }
119
120 wxAppConsole::~wxAppConsole()
121 {
122 delete m_traits;
123 }
124
125 // ----------------------------------------------------------------------------
126 // initilization/cleanup
127 // ----------------------------------------------------------------------------
128
129 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
130 {
131 #if wxUSE_LOG
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);
137 #endif // wxUSE_LOG
138
139 // remember the command line arguments
140 this->argc = argc;
141 this->argv = argv;
142
143 #ifndef __WXPALMOS__
144 if ( m_appName.empty() && argv )
145 {
146 // the application name is, by default, the name of its executable file
147 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
148 }
149 #endif
150
151 return true;
152 }
153
154 void wxAppConsole::CleanUp()
155 {
156 }
157
158 // ----------------------------------------------------------------------------
159 // OnXXX() callbacks
160 // ----------------------------------------------------------------------------
161
162 bool wxAppConsole::OnInit()
163 {
164 #if wxUSE_CMDLINE_PARSER
165 wxCmdLineParser parser(argc, argv);
166
167 OnInitCmdLine(parser);
168
169 bool cont;
170 switch ( parser.Parse(false /* don't show usage */) )
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 )
186 return false;
187 #endif // wxUSE_CMDLINE_PARSER
188
189 return true;
190 }
191
192 int 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
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
207 void wxAppConsole::Exit()
208 {
209 exit(-1);
210 }
211
212 // ----------------------------------------------------------------------------
213 // traits stuff
214 // ----------------------------------------------------------------------------
215
216 wxAppTraits *wxAppConsole::CreateTraits()
217 {
218 return new wxConsoleAppTraits;
219 }
220
221 wxAppTraits *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
239 wxLog *wxAppConsole::CreateLogTarget()
240 {
241 wxAppTraits *traits = GetTraits();
242 return traits ? traits->CreateLogTarget() : NULL;
243 }
244
245 #endif // wxUSE_LOG
246
247 wxMessageOutput *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
259 void 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
271 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
272 while (node)
273 {
274 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
275 wxPendingEvents->Erase(node);
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
289 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
290 {
291 // process the events normally by default
292 return -1;
293 }
294
295 // ----------------------------------------------------------------------------
296 // exception handling
297 // ----------------------------------------------------------------------------
298
299 #if wxUSE_EXCEPTIONS
300
301 void
302 wxAppConsole::HandleEvent(wxEvtHandler *handler,
303 wxEventFunction func,
304 wxEvent& event) const
305 {
306 // by default, simply call the handler
307 (handler->*func)(event);
308 }
309
310 bool
311 wxAppConsole::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
321 #endif // wxUSE_EXCEPTIONS
322
323 // ----------------------------------------------------------------------------
324 // cmd line parsing
325 // ----------------------------------------------------------------------------
326
327 #if wxUSE_CMDLINE_PARSER
328
329 #define OPTION_VERBOSE _T("verbose")
330
331 void 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
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
370 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
371 {
372 #if wxUSE_LOG
373 if ( parser.Found(OPTION_VERBOSE) )
374 {
375 wxLog::SetVerbose(true);
376 }
377 #else
378 wxUnusedVar(parser);
379 #endif // wxUSE_LOG
380
381 return true;
382 }
383
384 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
385 {
386 parser.Usage();
387
388 return false;
389 }
390
391 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
392 {
393 parser.Usage();
394
395 return false;
396 }
397
398 #endif // wxUSE_CMDLINE_PARSER
399
400 // ----------------------------------------------------------------------------
401 // debugging support
402 // ----------------------------------------------------------------------------
403
404 /* static */
405 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
406 const char *componentName)
407 {
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);
411 #endif
412
413 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
414 {
415 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
416 wxString prog = wxString::FromAscii(optionsSignature);
417 wxString progName = wxString::FromAscii(componentName);
418 wxString msg;
419
420 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
421 lib.c_str(), progName.c_str(), prog.c_str());
422
423 wxLogFatalError(msg.c_str());
424
425 // normally wxLogFatalError doesn't return
426 return false;
427 }
428 #undef wxCMP
429
430 return true;
431 }
432
433 #ifdef __WXDEBUG__
434
435 void wxAppConsole::OnAssert(const wxChar *file,
436 int line,
437 const wxChar *cond,
438 const wxChar *msg)
439 {
440 ShowAssertDialog(file, line, cond, msg, GetTraits());
441 }
442
443 #endif // __WXDEBUG__
444
445 #if WXWIN_COMPATIBILITY_2_4
446
447 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& buildOptions)
448 {
449 return CheckBuildOptions(buildOptions.m_signature, "your program");
450 }
451
452 #endif
453
454 // ============================================================================
455 // other classes implementations
456 // ============================================================================
457
458 // ----------------------------------------------------------------------------
459 // wxConsoleAppTraitsBase
460 // ----------------------------------------------------------------------------
461
462 #if wxUSE_LOG
463
464 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
465 {
466 return new wxLogStderr;
467 }
468
469 #endif // wxUSE_LOG
470
471 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
472 {
473 return new wxMessageOutputStderr;
474 }
475
476 #if wxUSE_FONTMAP
477
478 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
479 {
480 return (wxFontMapper *)new wxFontMapperBase;
481 }
482
483 #endif // wxUSE_FONTMAP
484
485 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
486 {
487 // console applications don't use renderers
488 return NULL;
489 }
490
491 #ifdef __WXDEBUG__
492 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
493 {
494 return wxAppTraitsBase::ShowAssertDialog(msg);
495 }
496 #endif
497
498 bool wxConsoleAppTraitsBase::HasStderr()
499 {
500 // console applications always have stderr, even under Mac/Windows
501 return true;
502 }
503
504 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
505 {
506 delete object;
507 }
508
509 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
510 {
511 // nothing to do
512 }
513
514 #if wxUSE_SOCKETS
515 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
516 {
517 return NULL;
518 }
519 #endif
520
521 // ----------------------------------------------------------------------------
522 // wxAppTraits
523 // ----------------------------------------------------------------------------
524
525 #ifdef __WXDEBUG__
526
527 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
528 {
529 return DoShowAssertDialog(msg);
530 }
531
532 #endif // __WXDEBUG__
533
534 // ============================================================================
535 // global functions implementation
536 // ============================================================================
537
538 void 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
551 void 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
563 bool wxAssertIsEqual(int x, int y)
564 {
565 return x == y;
566 }
567
568 // break into the debugger
569 void 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
586 void wxAssert(int cond,
587 const wxChar *szFile,
588 int nLine,
589 const wxChar *szCond,
590 const wxChar *szMsg)
591 {
592 if ( !cond )
593 wxOnAssert(szFile, nLine, szCond, szMsg);
594 }
595
596 // this function is called when an assert fails
597 void wxOnAssert(const wxChar *szFile,
598 int nLine,
599 const wxChar *szCond,
600 const wxChar *szMsg)
601 {
602 // FIXME MT-unsafe
603 static bool s_bInAssert = false;
604
605 if ( s_bInAssert )
606 {
607 // He-e-e-e-elp!! we're trapped in endless loop
608 wxTrap();
609
610 s_bInAssert = false;
611
612 return;
613 }
614
615 s_bInAssert = true;
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
629 s_bInAssert = false;
630 }
631
632 #endif // __WXDEBUG__
633
634 // ============================================================================
635 // private functions implementation
636 // ============================================================================
637
638 #ifdef __WXDEBUG__
639
640 static 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
653 bool 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
665 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
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
691 static
692 void 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
699 static bool s_bNoAsserts = false;
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
741 wxLogDebug(_T("%s"), msg.c_str());
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