Added wxUSE_THREADS guards
[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(__DARWIN__) && defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
55 // For MacTypes.h for Debugger function
56 #include <CoreFoundation/CFBase.h>
57 #endif
58
59 #if defined(__WXMAC__)
60 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
61 // I don't know which headers are needed under earlier systems so
62 // include everything when in doubt
63 #ifdef __DARWIN__
64 #include "MacTypes.h"
65 #else
66 #include "wx/mac/private.h" // includes mac headers
67 #endif
68 #endif // __WXMAC__
69
70 #ifdef __WXDEBUG__
71 #ifdef wxUSE_STACKWALKER
72 #include "wx/stackwalk.h"
73 #endif // wxUSE_STACKWALKER
74 #endif // __WXDEBUG__
75
76 // ----------------------------------------------------------------------------
77 // private functions prototypes
78 // ----------------------------------------------------------------------------
79
80 #ifdef __WXDEBUG__
81 // really just show the assert dialog
82 static bool DoShowAssertDialog(const wxString& msg);
83
84 // prepare for showing the assert dialog, use the given traits or
85 // DoShowAssertDialog() as last fallback to really show it
86 static
87 void ShowAssertDialog(const wxChar *szFile,
88 int nLine,
89 const wxChar *szCond,
90 const wxChar *szMsg,
91 wxAppTraits *traits = NULL);
92
93 // turn on the trace masks specified in the env variable WXTRACE
94 static void LINKAGEMODE SetTraceMasks();
95 #endif // __WXDEBUG__
96
97 // ----------------------------------------------------------------------------
98 // global vars
99 // ----------------------------------------------------------------------------
100
101 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
102
103 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
104
105 // ============================================================================
106 // wxAppConsole implementation
107 // ============================================================================
108
109 // ----------------------------------------------------------------------------
110 // ctor/dtor
111 // ----------------------------------------------------------------------------
112
113 wxAppConsole::wxAppConsole()
114 {
115 m_traits = NULL;
116
117 ms_appInstance = this;
118
119 #ifdef __WXDEBUG__
120 SetTraceMasks();
121 #if wxUSE_UNICODE
122 // In unicode mode the SetTraceMasks call can cause an apptraits to be
123 // created, but since we are still in the constructor the wrong kind will
124 // be created for GUI apps. Destroy it so it can be created again later.
125 delete m_traits;
126 m_traits = NULL;
127 #endif
128 #endif
129 }
130
131 wxAppConsole::~wxAppConsole()
132 {
133 delete m_traits;
134 }
135
136 // ----------------------------------------------------------------------------
137 // initilization/cleanup
138 // ----------------------------------------------------------------------------
139
140 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
141 {
142 #if wxUSE_LOG
143 // If some code logged something before wxApp instance was created,
144 // wxLogStderr was set as the target. Undo it here by destroying the
145 // current target. It will be re-created next time logging is needed, but
146 // this time wxAppTraits will be used:
147 delete wxLog::SetActiveTarget(NULL);
148 #endif // wxUSE_LOG
149
150 // remember the command line arguments
151 this->argc = argc;
152 this->argv = argv;
153
154 #ifndef __WXPALMOS__
155 if ( m_appName.empty() && argv )
156 {
157 // the application name is, by default, the name of its executable file
158 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
159 }
160 #endif
161
162 return true;
163 }
164
165 void wxAppConsole::CleanUp()
166 {
167 }
168
169 // ----------------------------------------------------------------------------
170 // OnXXX() callbacks
171 // ----------------------------------------------------------------------------
172
173 bool wxAppConsole::OnInit()
174 {
175 #if wxUSE_CMDLINE_PARSER
176 wxCmdLineParser parser(argc, argv);
177
178 OnInitCmdLine(parser);
179
180 bool cont;
181 switch ( parser.Parse(false /* don't show usage */) )
182 {
183 case -1:
184 cont = OnCmdLineHelp(parser);
185 break;
186
187 case 0:
188 cont = OnCmdLineParsed(parser);
189 break;
190
191 default:
192 cont = OnCmdLineError(parser);
193 break;
194 }
195
196 if ( !cont )
197 return false;
198 #endif // wxUSE_CMDLINE_PARSER
199
200 return true;
201 }
202
203 int wxAppConsole::OnExit()
204 {
205 #if wxUSE_CONFIG
206 // delete the config object if any (don't use Get() here, but Set()
207 // because Get() could create a new config object)
208 delete wxConfigBase::Set((wxConfigBase *) NULL);
209 #endif // wxUSE_CONFIG
210
211 // use Set(NULL) and not Get() to avoid creating a message output object on
212 // demand when we just want to delete it
213 delete wxMessageOutput::Set(NULL);
214
215 return 0;
216 }
217
218 void wxAppConsole::Exit()
219 {
220 exit(-1);
221 }
222
223 // ----------------------------------------------------------------------------
224 // traits stuff
225 // ----------------------------------------------------------------------------
226
227 wxAppTraits *wxAppConsole::CreateTraits()
228 {
229 return new wxConsoleAppTraits;
230 }
231
232 wxAppTraits *wxAppConsole::GetTraits()
233 {
234 // FIXME-MT: protect this with a CS?
235 if ( !m_traits )
236 {
237 m_traits = CreateTraits();
238
239 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
240 }
241
242 return m_traits;
243 }
244
245 // we must implement CreateXXX() in wxApp itself for backwards compatibility
246 #if WXWIN_COMPATIBILITY_2_4
247
248 #if wxUSE_LOG
249
250 wxLog *wxAppConsole::CreateLogTarget()
251 {
252 wxAppTraits *traits = GetTraits();
253 return traits ? traits->CreateLogTarget() : NULL;
254 }
255
256 #endif // wxUSE_LOG
257
258 wxMessageOutput *wxAppConsole::CreateMessageOutput()
259 {
260 wxAppTraits *traits = GetTraits();
261 return traits ? traits->CreateMessageOutput() : NULL;
262 }
263
264 #endif // WXWIN_COMPATIBILITY_2_4
265
266 // ----------------------------------------------------------------------------
267 // event processing
268 // ----------------------------------------------------------------------------
269
270 void wxAppConsole::ProcessPendingEvents()
271 {
272 #if wxUSE_THREADS
273 if ( !wxPendingEventsLocker )
274 return;
275
276 // ensure that we're the only thread to modify the pending events list
277 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
278
279 if ( !wxPendingEvents )
280 {
281 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
282 return;
283 }
284 #endif
285
286 // iterate until the list becomes empty
287 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
288 while (node)
289 {
290 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
291 wxPendingEvents->Erase(node);
292
293 #if wxUSE_THREADS
294 // In ProcessPendingEvents(), new handlers might be add
295 // and we can safely leave the critical section here.
296 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
297 #endif
298
299 handler->ProcessPendingEvents();
300
301 #if wxUSE_THREADS
302 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
303 #endif
304
305 node = wxPendingEvents->GetFirst();
306 }
307
308 #if wxUSE_THREADS
309 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
310 #endif
311 }
312
313 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
314 {
315 // process the events normally by default
316 return -1;
317 }
318
319 // ----------------------------------------------------------------------------
320 // exception handling
321 // ----------------------------------------------------------------------------
322
323 #if wxUSE_EXCEPTIONS
324
325 void
326 wxAppConsole::HandleEvent(wxEvtHandler *handler,
327 wxEventFunction func,
328 wxEvent& event) const
329 {
330 // by default, simply call the handler
331 (handler->*func)(event);
332 }
333
334 bool
335 wxAppConsole::OnExceptionInMainLoop()
336 {
337 throw;
338
339 // some compilers are too stupid to know that we never return after throw
340 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
341 return false;
342 #endif
343 }
344
345 #endif // wxUSE_EXCEPTIONS
346
347 // ----------------------------------------------------------------------------
348 // cmd line parsing
349 // ----------------------------------------------------------------------------
350
351 #if wxUSE_CMDLINE_PARSER
352
353 #define OPTION_VERBOSE _T("verbose")
354
355 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
356 {
357 // the standard command line options
358 static const wxCmdLineEntryDesc cmdLineDesc[] =
359 {
360 {
361 wxCMD_LINE_SWITCH,
362 _T("h"),
363 _T("help"),
364 gettext_noop("show this help message"),
365 wxCMD_LINE_VAL_NONE,
366 wxCMD_LINE_OPTION_HELP
367 },
368
369 #if wxUSE_LOG
370 {
371 wxCMD_LINE_SWITCH,
372 wxEmptyString,
373 OPTION_VERBOSE,
374 gettext_noop("generate verbose log messages"),
375 wxCMD_LINE_VAL_NONE,
376 0x0
377 },
378 #endif // wxUSE_LOG
379
380 // terminator
381 {
382 wxCMD_LINE_NONE,
383 wxEmptyString,
384 wxEmptyString,
385 wxEmptyString,
386 wxCMD_LINE_VAL_NONE,
387 0x0
388 }
389 };
390
391 parser.SetDesc(cmdLineDesc);
392 }
393
394 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
395 {
396 #if wxUSE_LOG
397 if ( parser.Found(OPTION_VERBOSE) )
398 {
399 wxLog::SetVerbose(true);
400 }
401 #else
402 wxUnusedVar(parser);
403 #endif // wxUSE_LOG
404
405 return true;
406 }
407
408 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
409 {
410 parser.Usage();
411
412 return false;
413 }
414
415 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
416 {
417 parser.Usage();
418
419 return false;
420 }
421
422 #endif // wxUSE_CMDLINE_PARSER
423
424 // ----------------------------------------------------------------------------
425 // debugging support
426 // ----------------------------------------------------------------------------
427
428 /* static */
429 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
430 const char *componentName)
431 {
432 #if 0 // can't use wxLogTrace, not up and running yet
433 printf("checking build options object '%s' (ptr %p) in '%s'\n",
434 optionsSignature, optionsSignature, componentName);
435 #endif
436
437 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
438 {
439 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
440 wxString prog = wxString::FromAscii(optionsSignature);
441 wxString progName = wxString::FromAscii(componentName);
442 wxString msg;
443
444 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
445 lib.c_str(), progName.c_str(), prog.c_str());
446
447 wxLogFatalError(msg.c_str());
448
449 // normally wxLogFatalError doesn't return
450 return false;
451 }
452 #undef wxCMP
453
454 return true;
455 }
456
457 #ifdef __WXDEBUG__
458
459 void wxAppConsole::OnAssert(const wxChar *file,
460 int line,
461 const wxChar *cond,
462 const wxChar *msg)
463 {
464 ShowAssertDialog(file, line, cond, msg, GetTraits());
465 }
466
467 #endif // __WXDEBUG__
468
469 #if WXWIN_COMPATIBILITY_2_4
470
471 bool wxAppConsole::CheckBuildOptions(const wxBuildOptions& buildOptions)
472 {
473 return CheckBuildOptions(buildOptions.m_signature, "your program");
474 }
475
476 #endif
477
478 // ============================================================================
479 // other classes implementations
480 // ============================================================================
481
482 // ----------------------------------------------------------------------------
483 // wxConsoleAppTraitsBase
484 // ----------------------------------------------------------------------------
485
486 #if wxUSE_LOG
487
488 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
489 {
490 return new wxLogStderr;
491 }
492
493 #endif // wxUSE_LOG
494
495 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
496 {
497 return new wxMessageOutputStderr;
498 }
499
500 #if wxUSE_FONTMAP
501
502 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
503 {
504 return (wxFontMapper *)new wxFontMapperBase;
505 }
506
507 #endif // wxUSE_FONTMAP
508
509 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
510 {
511 // console applications don't use renderers
512 return NULL;
513 }
514
515 #ifdef __WXDEBUG__
516 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
517 {
518 return wxAppTraitsBase::ShowAssertDialog(msg);
519 }
520 #endif
521
522 bool wxConsoleAppTraitsBase::HasStderr()
523 {
524 // console applications always have stderr, even under Mac/Windows
525 return true;
526 }
527
528 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
529 {
530 delete object;
531 }
532
533 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
534 {
535 // nothing to do
536 }
537
538 #if wxUSE_SOCKETS
539 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
540 {
541 return NULL;
542 }
543 #endif
544
545 // ----------------------------------------------------------------------------
546 // wxAppTraits
547 // ----------------------------------------------------------------------------
548
549 #ifdef __WXDEBUG__
550
551 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
552 {
553 return DoShowAssertDialog(msg);
554 }
555
556 #endif // __WXDEBUG__
557
558 // ============================================================================
559 // global functions implementation
560 // ============================================================================
561
562 void wxExit()
563 {
564 if ( wxTheApp )
565 {
566 wxTheApp->Exit();
567 }
568 else
569 {
570 // what else can we do?
571 exit(-1);
572 }
573 }
574
575 void wxWakeUpIdle()
576 {
577 if ( wxTheApp )
578 {
579 wxTheApp->WakeUpIdle();
580 }
581 //else: do nothing, what can we do?
582 }
583
584 #ifdef __WXDEBUG__
585
586 // wxASSERT() helper
587 bool wxAssertIsEqual(int x, int y)
588 {
589 return x == y;
590 }
591
592 // break into the debugger
593 void wxTrap()
594 {
595 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
596 DebugBreak();
597 #elif defined(__WXMAC__) && !defined(__DARWIN__)
598 #if __powerc
599 Debugger();
600 #else
601 SysBreak();
602 #endif
603 #elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
604 Debugger();
605 #elif defined(__UNIX__)
606 raise(SIGTRAP);
607 #else
608 // TODO
609 #endif // Win/Unix
610 }
611
612 void wxAssert(int cond,
613 const wxChar *szFile,
614 int nLine,
615 const wxChar *szCond,
616 const wxChar *szMsg)
617 {
618 if ( !cond )
619 wxOnAssert(szFile, nLine, szCond, szMsg);
620 }
621
622 // this function is called when an assert fails
623 void wxOnAssert(const wxChar *szFile,
624 int nLine,
625 const wxChar *szCond,
626 const wxChar *szMsg)
627 {
628 // FIXME MT-unsafe
629 static bool s_bInAssert = false;
630
631 if ( s_bInAssert )
632 {
633 // He-e-e-e-elp!! we're trapped in endless loop
634 wxTrap();
635
636 s_bInAssert = false;
637
638 return;
639 }
640
641 s_bInAssert = true;
642
643 if ( !wxTheApp )
644 {
645 // by default, show the assert dialog box -- we can't customize this
646 // behaviour
647 ShowAssertDialog(szFile, nLine, szCond, szMsg);
648 }
649 else
650 {
651 // let the app process it as it wants
652 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
653 }
654
655 s_bInAssert = false;
656 }
657
658 #endif // __WXDEBUG__
659
660 // ============================================================================
661 // private functions implementation
662 // ============================================================================
663
664 #ifdef __WXDEBUG__
665
666 static void LINKAGEMODE SetTraceMasks()
667 {
668 #if wxUSE_LOG
669 wxString mask;
670 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
671 {
672 wxStringTokenizer tkn(mask, wxT(",;:"));
673 while ( tkn.HasMoreTokens() )
674 wxLog::AddTraceMask(tkn.GetNextToken());
675 }
676 #endif // wxUSE_LOG
677 }
678
679 bool DoShowAssertDialog(const wxString& msg)
680 {
681 // under MSW we can show the dialog even in the console mode
682 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
683 wxString msgDlg(msg);
684
685 // this message is intentionally not translated -- it is for
686 // developpers only
687 msgDlg += wxT("\nDo you want to stop the program?\n")
688 wxT("You can also choose [Cancel] to suppress ")
689 wxT("further warnings.");
690
691 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
692 MB_YESNOCANCEL | MB_ICONSTOP ) )
693 {
694 case IDYES:
695 wxTrap();
696 break;
697
698 case IDCANCEL:
699 // stop the asserts
700 return true;
701
702 //case IDNO: nothing to do
703 }
704 #else // !__WXMSW__
705 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
706 fflush(stderr);
707
708 // TODO: ask the user to enter "Y" or "N" on the console?
709 wxTrap();
710 #endif // __WXMSW__/!__WXMSW__
711
712 // continue with the asserts
713 return false;
714 }
715
716 // show the assert modal dialog
717 static
718 void ShowAssertDialog(const wxChar *szFile,
719 int nLine,
720 const wxChar *szCond,
721 const wxChar *szMsg,
722 wxAppTraits *traits)
723 {
724 // this variable can be set to true to suppress "assert failure" messages
725 static bool s_bNoAsserts = false;
726
727 wxString msg;
728 msg.reserve(2048);
729
730 // make life easier for people using VC++ IDE by using this format: like
731 // this, clicking on the message will take us immediately to the place of
732 // the failed assert
733 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
734
735 if ( szMsg )
736 {
737 msg << _T(": ") << szMsg;
738 }
739 else // no message given
740 {
741 msg << _T('.');
742 }
743
744 #if wxUSE_STACKWALKER
745 class StackDump : public wxStackWalker
746 {
747 public:
748 StackDump() { }
749
750 const wxString& GetStackTrace() const { return m_stackTrace; }
751
752 protected:
753 virtual void OnStackFrame(const wxStackFrame& frame)
754 {
755 m_stackTrace << wxString::Format(_T("[%02d] "), frame.GetLevel());
756
757 wxString name = frame.GetName();
758 if ( !name.empty() )
759 {
760 m_stackTrace << wxString::Format(_T("%-40s"), name.c_str());
761 }
762 else
763 {
764 m_stackTrace << wxString::Format
765 (
766 _T("0x%08lx"),
767 (unsigned long)frame.GetAddress()
768 );
769 }
770
771 if ( frame.HasSourceLocation() )
772 {
773 m_stackTrace << _T('\t')
774 << frame.GetFileName()
775 << _T(':')
776 << frame.GetLine();
777 }
778
779 m_stackTrace << _T('\n');
780 }
781
782 private:
783 wxString m_stackTrace;
784 };
785
786 StackDump dump;
787 dump.Walk(5); // don't show OnAssert() call itself
788 wxString stackTrace = dump.GetStackTrace();
789
790 // don't show more than maxLines or we could get a dialog too tall to be
791 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
792 // characters it is still only 300 pixels...
793 const int maxLines = 20;
794 int count = stackTrace.Freq(wxT('\n'));
795 if (count > maxLines)
796 {
797 int i;
798 for (i = 0; i < count - maxLines; i++)
799 stackTrace = stackTrace.BeforeLast(wxT('\n'));
800 }
801 if ( !stackTrace.empty() )
802 {
803 msg << _T("\n\nCall stack:\n")
804 << stackTrace;
805 }
806 #endif // wxUSE_STACKWALKER
807
808 #if wxUSE_THREADS
809 // if we are not in the main thread, output the assert directly and trap
810 // since dialogs cannot be displayed
811 if ( !wxThread::IsMain() )
812 {
813 msg += wxT(" [in child thread]");
814
815 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
816 msg << wxT("\r\n");
817 OutputDebugString(msg );
818 #else
819 // send to stderr
820 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
821 fflush(stderr);
822 #endif
823 // He-e-e-e-elp!! we're asserting in a child thread
824 wxTrap();
825 }
826 else
827 #endif // wxUSE_THREADS
828
829 if ( !s_bNoAsserts )
830 {
831 // send it to the normal log destination
832 wxLogDebug(_T("%s"), msg.c_str());
833
834 if ( traits )
835 {
836 // delegate showing assert dialog (if possible) to that class
837 s_bNoAsserts = traits->ShowAssertDialog(msg);
838 }
839 else // no traits object
840 {
841 // fall back to the function of last resort
842 s_bNoAsserts = DoShowAssertDialog(msg);
843 }
844 }
845 }
846
847 #endif // __WXDEBUG__
848