reworked wxBuildOptions code to work even w/o function inlining
[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 #if wxUSE_LOG
32 #include "wx/log.h"
33 #endif // wxUSE_LOG
34 #endif //WX_PRECOMP
35
36 #include "wx/utils.h"
37 #include "wx/apptrait.h"
38 #include "wx/cmdline.h"
39 #include "wx/confbase.h"
40 #include "wx/filename.h"
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
52 #if wxUSE_FONTMAP
53 #include "wx/fontmap.h"
54 #endif // wxUSE_FONTMAP
55
56 #if defined(__WXMAC__)
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__
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
92 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
93
94 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
95
96 // ============================================================================
97 // wxAppConsole implementation
98 // ============================================================================
99
100 // ----------------------------------------------------------------------------
101 // ctor/dtor
102 // ----------------------------------------------------------------------------
103
104 wxAppConsole::wxAppConsole()
105 {
106 m_traits = NULL;
107
108 ms_appInstance = this;
109
110 #ifdef __WXDEBUG__
111 SetTraceMasks();
112 #endif
113 }
114
115 wxAppConsole::~wxAppConsole()
116 {
117 delete m_traits;
118 }
119
120 // ----------------------------------------------------------------------------
121 // initilization/cleanup
122 // ----------------------------------------------------------------------------
123
124 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
125 {
126 // remember the command line arguments
127 this->argc = argc;
128 this->argv = argv;
129
130 if ( m_appName.empty() && argv )
131 {
132 // the application name is, by default, the name of its executable file
133 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
134 }
135
136 return true;
137 }
138
139 void wxAppConsole::CleanUp()
140 {
141 }
142
143 // ----------------------------------------------------------------------------
144 // OnXXX() callbacks
145 // ----------------------------------------------------------------------------
146
147 bool 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
177 int 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
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
192 void wxAppConsole::Exit()
193 {
194 exit(-1);
195 }
196
197 // ----------------------------------------------------------------------------
198 // traits stuff
199 // ----------------------------------------------------------------------------
200
201 wxAppTraits *wxAppConsole::CreateTraits()
202 {
203 return new wxConsoleAppTraits;
204 }
205
206 wxAppTraits *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
224 wxLog *wxAppConsole::CreateLogTarget()
225 {
226 wxAppTraits *traits = GetTraits();
227 return traits ? traits->CreateLogTarget() : NULL;
228 }
229
230 #endif // wxUSE_LOG
231
232 wxMessageOutput *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
244 void 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
256 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
257 while (node)
258 {
259 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
260 wxPendingEvents->Erase(node);
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
274 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
275 {
276 // process the events normally by default
277 return -1;
278 }
279
280 // ----------------------------------------------------------------------------
281 // cmd line parsing
282 // ----------------------------------------------------------------------------
283
284 #if wxUSE_CMDLINE_PARSER
285
286 #define OPTION_VERBOSE _T("verbose")
287
288 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
289 {
290 // the standard command line options
291 static const wxCmdLineEntryDesc cmdLineDesc[] =
292 {
293 {
294 wxCMD_LINE_SWITCH,
295 _T("h"),
296 _T("help"),
297 gettext_noop("show this help message"),
298 wxCMD_LINE_VAL_NONE,
299 wxCMD_LINE_OPTION_HELP
300 },
301
302 #if wxUSE_LOG
303 {
304 wxCMD_LINE_SWITCH,
305 _T(""),
306 OPTION_VERBOSE,
307 gettext_noop("generate verbose log messages"),
308 wxCMD_LINE_VAL_NONE,
309 0x0
310 },
311 #endif // wxUSE_LOG
312
313 // terminator
314 {
315 wxCMD_LINE_NONE,
316 _T(""),
317 _T(""),
318 _T(""),
319 wxCMD_LINE_VAL_NONE,
320 0x0
321 }
322 };
323
324 parser.SetDesc(cmdLineDesc);
325 }
326
327 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
328 {
329 #if wxUSE_LOG
330 if ( parser.Found(OPTION_VERBOSE) )
331 {
332 wxLog::SetVerbose(TRUE);
333 }
334 #endif // wxUSE_LOG
335
336 return TRUE;
337 }
338
339 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
340 {
341 parser.Usage();
342
343 return FALSE;
344 }
345
346 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
347 {
348 parser.Usage();
349
350 return FALSE;
351 }
352
353 #endif // wxUSE_CMDLINE_PARSER
354
355 // ----------------------------------------------------------------------------
356 // debugging support
357 // ----------------------------------------------------------------------------
358
359 /* static */
360 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
361 const char *componentName)
362 {
363 #if 0 // can't use wxLogTrace, not up and running yet
364 printf("checking build options object '%s' (ptr %p) in '%s'\n",
365 optionsSignature, optionsSignature, componentName);
366 #endif
367
368 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
369 {
370 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
371 wxString prog = wxString::FromAscii(optionsSignature);
372 wxString progName = wxString::FromAscii(componentName);
373 wxString msg;
374
375 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s, and %s used %s."),
376 lib.c_str(), progName.c_str(), prog.c_str());
377
378 wxLogFatalError(msg);
379
380 // normally wxLogFatalError doesn't return
381 return FALSE;
382 }
383 #undef wxCMP
384
385 return TRUE;
386 }
387
388 #ifdef __WXDEBUG__
389
390 void wxAppConsole::OnAssert(const wxChar *file,
391 int line,
392 const wxChar *cond,
393 const wxChar *msg)
394 {
395 ShowAssertDialog(file, line, cond, msg, m_traits);
396 }
397
398 #endif // __WXDEBUG__
399
400 // ============================================================================
401 // other classes implementations
402 // ============================================================================
403
404 // ----------------------------------------------------------------------------
405 // wxConsoleAppTraitsBase
406 // ----------------------------------------------------------------------------
407
408 #if wxUSE_LOG
409
410 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
411 {
412 return new wxLogStderr;
413 }
414
415 #endif // wxUSE_LOG
416
417 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
418 {
419 return new wxMessageOutputStderr;
420 }
421
422 #if wxUSE_FONTMAP
423
424 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
425 {
426 return (wxFontMapper *)new wxFontMapperBase;
427 }
428
429 #endif // wxUSE_FONTMAP
430
431 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
432 {
433 // console applications don't use renderers
434 return NULL;
435 }
436
437 #ifdef __WXDEBUG__
438 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
439 {
440 return wxAppTraitsBase::ShowAssertDialog(msg);
441 }
442 #endif
443
444 bool wxConsoleAppTraitsBase::HasStderr()
445 {
446 // console applications always have stderr, even under Mac/Windows
447 return true;
448 }
449
450 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
451 {
452 delete object;
453 }
454
455 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
456 {
457 // nothing to do
458 }
459
460 // ----------------------------------------------------------------------------
461 // wxAppTraits
462 // ----------------------------------------------------------------------------
463
464 #ifdef __WXDEBUG__
465
466 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
467 {
468 return DoShowAssertDialog(msg);
469 }
470
471 #endif // __WXDEBUG__
472
473 // ============================================================================
474 // global functions implementation
475 // ============================================================================
476
477 void wxExit()
478 {
479 if ( wxTheApp )
480 {
481 wxTheApp->Exit();
482 }
483 else
484 {
485 // what else can we do?
486 exit(-1);
487 }
488 }
489
490 void wxWakeUpIdle()
491 {
492 if ( wxTheApp )
493 {
494 wxTheApp->WakeUpIdle();
495 }
496 //else: do nothing, what can we do?
497 }
498
499 #ifdef __WXDEBUG__
500
501 // wxASSERT() helper
502 bool wxAssertIsEqual(int x, int y)
503 {
504 return x == y;
505 }
506
507 // break into the debugger
508 void wxTrap()
509 {
510 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
511 DebugBreak();
512 #elif defined(__WXMAC__) && !defined(__DARWIN__)
513 #if __powerc
514 Debugger();
515 #else
516 SysBreak();
517 #endif
518 #elif defined(__UNIX__)
519 raise(SIGTRAP);
520 #else
521 // TODO
522 #endif // Win/Unix
523 }
524
525 void wxAssert(int cond,
526 const wxChar *szFile,
527 int nLine,
528 const wxChar *szCond,
529 const wxChar *szMsg)
530 {
531 if ( !cond )
532 wxOnAssert(szFile, nLine, szCond, szMsg);
533 }
534
535 // this function is called when an assert fails
536 void wxOnAssert(const wxChar *szFile,
537 int nLine,
538 const wxChar *szCond,
539 const wxChar *szMsg)
540 {
541 // FIXME MT-unsafe
542 static bool s_bInAssert = FALSE;
543
544 if ( s_bInAssert )
545 {
546 // He-e-e-e-elp!! we're trapped in endless loop
547 wxTrap();
548
549 s_bInAssert = FALSE;
550
551 return;
552 }
553
554 s_bInAssert = TRUE;
555
556 if ( !wxTheApp )
557 {
558 // by default, show the assert dialog box -- we can't customize this
559 // behaviour
560 ShowAssertDialog(szFile, nLine, szCond, szMsg);
561 }
562 else
563 {
564 // let the app process it as it wants
565 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
566 }
567
568 s_bInAssert = FALSE;
569 }
570
571 #endif // __WXDEBUG__
572
573 // ============================================================================
574 // private functions implementation
575 // ============================================================================
576
577 #ifdef __WXDEBUG__
578
579 static void LINKAGEMODE SetTraceMasks()
580 {
581 #if wxUSE_LOG
582 wxString mask;
583 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
584 {
585 wxStringTokenizer tkn(mask, wxT(",;:"));
586 while ( tkn.HasMoreTokens() )
587 wxLog::AddTraceMask(tkn.GetNextToken());
588 }
589 #endif // wxUSE_LOG
590 }
591
592 bool DoShowAssertDialog(const wxString& msg)
593 {
594 // under MSW we can show the dialog even in the console mode
595 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
596 wxString msgDlg(msg);
597
598 // this message is intentionally not translated -- it is for
599 // developpers only
600 msgDlg += wxT("\nDo you want to stop the program?\n")
601 wxT("You can also choose [Cancel] to suppress ")
602 wxT("further warnings.");
603
604 switch ( ::MessageBox(NULL, msgDlg, _T("wxWindows Debug Alert"),
605 MB_YESNOCANCEL | MB_ICONSTOP ) )
606 {
607 case IDYES:
608 wxTrap();
609 break;
610
611 case IDCANCEL:
612 // stop the asserts
613 return true;
614
615 //case IDNO: nothing to do
616 }
617 #else // !__WXMSW__
618 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
619 fflush(stderr);
620
621 // TODO: ask the user to enter "Y" or "N" on the console?
622 wxTrap();
623 #endif // __WXMSW__/!__WXMSW__
624
625 // continue with the asserts
626 return false;
627 }
628
629 // show the assert modal dialog
630 static
631 void ShowAssertDialog(const wxChar *szFile,
632 int nLine,
633 const wxChar *szCond,
634 const wxChar *szMsg,
635 wxAppTraits *traits)
636 {
637 // this variable can be set to true to suppress "assert failure" messages
638 static bool s_bNoAsserts = FALSE;
639
640 wxString msg;
641 msg.reserve(2048);
642
643 // make life easier for people using VC++ IDE by using this format: like
644 // this, clicking on the message will take us immediately to the place of
645 // the failed assert
646 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
647
648 if ( szMsg )
649 {
650 msg << _T(": ") << szMsg;
651 }
652 else // no message given
653 {
654 msg << _T('.');
655 }
656
657 #if wxUSE_THREADS
658 // if we are not in the main thread, output the assert directly and trap
659 // since dialogs cannot be displayed
660 if ( !wxThread::IsMain() )
661 {
662 msg += wxT(" [in child thread]");
663
664 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
665 msg << wxT("\r\n");
666 OutputDebugString(msg );
667 #else
668 // send to stderr
669 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
670 fflush(stderr);
671 #endif
672 // He-e-e-e-elp!! we're asserting in a child thread
673 wxTrap();
674 }
675 #endif // wxUSE_THREADS
676
677 if ( !s_bNoAsserts )
678 {
679 // send it to the normal log destination
680 wxLogDebug(_T("%s"), msg.c_str());
681
682 if ( traits )
683 {
684 // delegate showing assert dialog (if possible) to that class
685 s_bNoAsserts = traits->ShowAssertDialog(msg);
686 }
687 else // no traits object
688 {
689 // fall back to the function of last resort
690 s_bNoAsserts = DoShowAssertDialog(msg);
691 }
692 }
693 }
694
695 #endif // __WXDEBUG__
696