Added wxAppTraits::CreateGSocket() as well as implementations for wxBase and
[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 wxUSE_SOCKETS
57 #include "wx/gsocket.h"
58 #endif // wxUSE_SOCKETS
59
60 #if defined(__WXMAC__)
61 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
62 // I don't know which headers are needed under earlier systems so
63 // include everything when in doubt
64 #ifdef __DARWIN__
65 #include "MacTypes.h"
66 #else
67 #include "wx/mac/private.h" // includes mac headers
68 #endif
69 #endif // __WXMAC__
70
71 // ----------------------------------------------------------------------------
72 // private functions prototypes
73 // ----------------------------------------------------------------------------
74
75 #ifdef __WXDEBUG__
76 // really just show the assert dialog
77 static bool DoShowAssertDialog(const wxString& msg);
78
79 // prepare for showing the assert dialog, use the given traits or
80 // DoShowAssertDialog() as last fallback to really show it
81 static
82 void ShowAssertDialog(const wxChar *szFile,
83 int nLine,
84 const wxChar *szCond,
85 const wxChar *szMsg,
86 wxAppTraits *traits = NULL);
87
88 // turn on the trace masks specified in the env variable WXTRACE
89 static void LINKAGEMODE SetTraceMasks();
90 #endif // __WXDEBUG__
91
92 // ----------------------------------------------------------------------------
93 // global vars
94 // ----------------------------------------------------------------------------
95
96 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
97
98 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
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 #if wxUSE_EXCEPTIONS
285
286 void
287 wxAppConsole::HandleEvent(wxEvtHandler *handler,
288 wxEventFunction func,
289 wxEvent& event) const
290 {
291 // by default, simply call the handler
292 (handler->*func)(event);
293 }
294
295 #endif // wxUSE_EXCEPTIONS
296
297 // ----------------------------------------------------------------------------
298 // cmd line parsing
299 // ----------------------------------------------------------------------------
300
301 #if wxUSE_CMDLINE_PARSER
302
303 #define OPTION_VERBOSE _T("verbose")
304
305 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
306 {
307 // the standard command line options
308 static const wxCmdLineEntryDesc cmdLineDesc[] =
309 {
310 {
311 wxCMD_LINE_SWITCH,
312 _T("h"),
313 _T("help"),
314 gettext_noop("show this help message"),
315 wxCMD_LINE_VAL_NONE,
316 wxCMD_LINE_OPTION_HELP
317 },
318
319 #if wxUSE_LOG
320 {
321 wxCMD_LINE_SWITCH,
322 _T(""),
323 OPTION_VERBOSE,
324 gettext_noop("generate verbose log messages"),
325 wxCMD_LINE_VAL_NONE,
326 0x0
327 },
328 #endif // wxUSE_LOG
329
330 // terminator
331 {
332 wxCMD_LINE_NONE,
333 _T(""),
334 _T(""),
335 _T(""),
336 wxCMD_LINE_VAL_NONE,
337 0x0
338 }
339 };
340
341 parser.SetDesc(cmdLineDesc);
342 }
343
344 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
345 {
346 #if wxUSE_LOG
347 if ( parser.Found(OPTION_VERBOSE) )
348 {
349 wxLog::SetVerbose(TRUE);
350 }
351 #endif // wxUSE_LOG
352
353 return TRUE;
354 }
355
356 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
357 {
358 parser.Usage();
359
360 return FALSE;
361 }
362
363 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
364 {
365 parser.Usage();
366
367 return FALSE;
368 }
369
370 #endif // wxUSE_CMDLINE_PARSER
371
372 // ----------------------------------------------------------------------------
373 // debugging support
374 // ----------------------------------------------------------------------------
375
376 /* static */
377 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
378 const char *componentName)
379 {
380 #if 0 // can't use wxLogTrace, not up and running yet
381 printf("checking build options object '%s' (ptr %p) in '%s'\n",
382 optionsSignature, optionsSignature, componentName);
383 #endif
384
385 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
386 {
387 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
388 wxString prog = wxString::FromAscii(optionsSignature);
389 wxString progName = wxString::FromAscii(componentName);
390 wxString msg;
391
392 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
393 lib.c_str(), progName.c_str(), prog.c_str());
394
395 wxLogFatalError(msg);
396
397 // normally wxLogFatalError doesn't return
398 return FALSE;
399 }
400 #undef wxCMP
401
402 return TRUE;
403 }
404
405 #ifdef __WXDEBUG__
406
407 void wxAppConsole::OnAssert(const wxChar *file,
408 int line,
409 const wxChar *cond,
410 const wxChar *msg)
411 {
412 ShowAssertDialog(file, line, cond, msg, GetTraits());
413 }
414
415 #endif // __WXDEBUG__
416
417 // ============================================================================
418 // other classes implementations
419 // ============================================================================
420
421 // ----------------------------------------------------------------------------
422 // wxConsoleAppTraitsBase
423 // ----------------------------------------------------------------------------
424
425 #if wxUSE_LOG
426
427 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
428 {
429 return new wxLogStderr;
430 }
431
432 #endif // wxUSE_LOG
433
434 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
435 {
436 return new wxMessageOutputStderr;
437 }
438
439 #if wxUSE_FONTMAP
440
441 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
442 {
443 return (wxFontMapper *)new wxFontMapperBase;
444 }
445
446 #endif // wxUSE_FONTMAP
447
448 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
449 {
450 // console applications don't use renderers
451 return NULL;
452 }
453
454 #ifdef __WXDEBUG__
455 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
456 {
457 return wxAppTraitsBase::ShowAssertDialog(msg);
458 }
459 #endif
460
461 bool wxConsoleAppTraitsBase::HasStderr()
462 {
463 // console applications always have stderr, even under Mac/Windows
464 return true;
465 }
466
467 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
468 {
469 delete object;
470 }
471
472 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
473 {
474 // nothing to do
475 }
476
477 #if wxUSE_SOCKETS
478 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
479 {
480 return NULL;
481 }
482
483 // TODO: Use a different class that only stubs out the event loop functions
484 GSocketBSD* wxConsoleAppTraitsBase::CreateGSocket()
485 {
486 #ifdef wxUSE_GSOCKET_CPLUSPLUS
487 return new GSocketBSDGUIShim();
488 #else
489 return NULL;
490 #endif
491 }
492 #endif
493
494 // ----------------------------------------------------------------------------
495 // wxAppTraits
496 // ----------------------------------------------------------------------------
497
498 #ifdef __WXDEBUG__
499
500 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
501 {
502 return DoShowAssertDialog(msg);
503 }
504
505 #endif // __WXDEBUG__
506
507 // ============================================================================
508 // global functions implementation
509 // ============================================================================
510
511 void wxExit()
512 {
513 if ( wxTheApp )
514 {
515 wxTheApp->Exit();
516 }
517 else
518 {
519 // what else can we do?
520 exit(-1);
521 }
522 }
523
524 void wxWakeUpIdle()
525 {
526 if ( wxTheApp )
527 {
528 wxTheApp->WakeUpIdle();
529 }
530 //else: do nothing, what can we do?
531 }
532
533 #ifdef __WXDEBUG__
534
535 // wxASSERT() helper
536 bool wxAssertIsEqual(int x, int y)
537 {
538 return x == y;
539 }
540
541 // break into the debugger
542 void wxTrap()
543 {
544 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
545 DebugBreak();
546 #elif defined(__WXMAC__) && !defined(__DARWIN__)
547 #if __powerc
548 Debugger();
549 #else
550 SysBreak();
551 #endif
552 #elif defined(__UNIX__)
553 raise(SIGTRAP);
554 #else
555 // TODO
556 #endif // Win/Unix
557 }
558
559 void wxAssert(int cond,
560 const wxChar *szFile,
561 int nLine,
562 const wxChar *szCond,
563 const wxChar *szMsg)
564 {
565 if ( !cond )
566 wxOnAssert(szFile, nLine, szCond, szMsg);
567 }
568
569 // this function is called when an assert fails
570 void wxOnAssert(const wxChar *szFile,
571 int nLine,
572 const wxChar *szCond,
573 const wxChar *szMsg)
574 {
575 // FIXME MT-unsafe
576 static bool s_bInAssert = FALSE;
577
578 if ( s_bInAssert )
579 {
580 // He-e-e-e-elp!! we're trapped in endless loop
581 wxTrap();
582
583 s_bInAssert = FALSE;
584
585 return;
586 }
587
588 s_bInAssert = TRUE;
589
590 if ( !wxTheApp )
591 {
592 // by default, show the assert dialog box -- we can't customize this
593 // behaviour
594 ShowAssertDialog(szFile, nLine, szCond, szMsg);
595 }
596 else
597 {
598 // let the app process it as it wants
599 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
600 }
601
602 s_bInAssert = FALSE;
603 }
604
605 #endif // __WXDEBUG__
606
607 // ============================================================================
608 // private functions implementation
609 // ============================================================================
610
611 #ifdef __WXDEBUG__
612
613 static void LINKAGEMODE SetTraceMasks()
614 {
615 #if wxUSE_LOG
616 wxString mask;
617 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
618 {
619 wxStringTokenizer tkn(mask, wxT(",;:"));
620 while ( tkn.HasMoreTokens() )
621 wxLog::AddTraceMask(tkn.GetNextToken());
622 }
623 #endif // wxUSE_LOG
624 }
625
626 bool DoShowAssertDialog(const wxString& msg)
627 {
628 // under MSW we can show the dialog even in the console mode
629 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
630 wxString msgDlg(msg);
631
632 // this message is intentionally not translated -- it is for
633 // developpers only
634 msgDlg += wxT("\nDo you want to stop the program?\n")
635 wxT("You can also choose [Cancel] to suppress ")
636 wxT("further warnings.");
637
638 switch ( ::MessageBox(NULL, msgDlg, _T("wxWindows Debug Alert"),
639 MB_YESNOCANCEL | MB_ICONSTOP ) )
640 {
641 case IDYES:
642 wxTrap();
643 break;
644
645 case IDCANCEL:
646 // stop the asserts
647 return true;
648
649 //case IDNO: nothing to do
650 }
651 #else // !__WXMSW__
652 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
653 fflush(stderr);
654
655 // TODO: ask the user to enter "Y" or "N" on the console?
656 wxTrap();
657 #endif // __WXMSW__/!__WXMSW__
658
659 // continue with the asserts
660 return false;
661 }
662
663 // show the assert modal dialog
664 static
665 void ShowAssertDialog(const wxChar *szFile,
666 int nLine,
667 const wxChar *szCond,
668 const wxChar *szMsg,
669 wxAppTraits *traits)
670 {
671 // this variable can be set to true to suppress "assert failure" messages
672 static bool s_bNoAsserts = FALSE;
673
674 wxString msg;
675 msg.reserve(2048);
676
677 // make life easier for people using VC++ IDE by using this format: like
678 // this, clicking on the message will take us immediately to the place of
679 // the failed assert
680 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
681
682 if ( szMsg )
683 {
684 msg << _T(": ") << szMsg;
685 }
686 else // no message given
687 {
688 msg << _T('.');
689 }
690
691 #if wxUSE_THREADS
692 // if we are not in the main thread, output the assert directly and trap
693 // since dialogs cannot be displayed
694 if ( !wxThread::IsMain() )
695 {
696 msg += wxT(" [in child thread]");
697
698 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
699 msg << wxT("\r\n");
700 OutputDebugString(msg );
701 #else
702 // send to stderr
703 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
704 fflush(stderr);
705 #endif
706 // He-e-e-e-elp!! we're asserting in a child thread
707 wxTrap();
708 }
709 #endif // wxUSE_THREADS
710
711 if ( !s_bNoAsserts )
712 {
713 // send it to the normal log destination
714 wxLogDebug(_T("%s"), msg.c_str());
715
716 if ( traits )
717 {
718 // delegate showing assert dialog (if possible) to that class
719 s_bNoAsserts = traits->ShowAssertDialog(msg);
720 }
721 else // no traits object
722 {
723 // fall back to the function of last resort
724 s_bNoAsserts = DoShowAssertDialog(msg);
725 }
726 }
727 }
728
729 #endif // __WXDEBUG__
730