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