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