wxLog shouldn't complain about log levels it doesn't know about
[wxWidgets.git] / src / common / log.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: log.cpp
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19 #ifdef __GNUG__
20 #pragma implementation "log.h"
21 #endif
22
23 // For compilers that support precompilation, includes "wx.h".
24 #include "wx/wxprec.h"
25
26 #ifdef __BORLANDC__
27 #pragma hdrstop
28 #endif
29
30 // wxWindows
31 #ifndef WX_PRECOMP
32 #include <wx/event.h>
33 #include <wx/app.h>
34 #include <wx/string.h>
35 #include <wx/intl.h>
36 #include <wx/menu.h>
37 #include <wx/frame.h>
38 #include <wx/msgdlg.h>
39 #include <wx/filedlg.h>
40 #include <wx/textctrl.h>
41 #endif //WX_PRECOMP
42
43 #include <wx/file.h>
44 #include <wx/textfile.h>
45 #include <wx/utils.h>
46 #include <wx/log.h>
47
48 // other standard headers
49 #include <errno.h>
50 #include <stdlib.h>
51 #include <time.h>
52
53 #ifdef __WXMSW__
54 #include <windows.h>
55 // Redefines OutputDebugString if necessary
56 #include "wx/msw/private.h"
57 #else //Unix
58 #include <signal.h>
59 #endif //Win/Unix
60
61 // ----------------------------------------------------------------------------
62 // non member functions
63 // ----------------------------------------------------------------------------
64
65 // define this to enable wrapping of log messages
66 //#define LOG_PRETTY_WRAP
67
68 #ifdef LOG_PRETTY_WRAP
69 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
70 #endif
71
72 // ----------------------------------------------------------------------------
73 // global variables
74 // ----------------------------------------------------------------------------
75
76 // we use a global variable to store the frame pointer for wxLogStatus - bad,
77 // but it's he easiest way
78 static wxFrame *gs_pFrame; // FIXME MT-unsafe
79
80 // ============================================================================
81 // implementation
82 // ============================================================================
83
84 // ----------------------------------------------------------------------------
85 // implementation of Log functions
86 //
87 // NB: unfortunately we need all these distinct functions, we can't make them
88 // macros and not all compilers inline vararg functions.
89 // ----------------------------------------------------------------------------
90
91 // log functions can't allocate memory (LogError("out of memory...") should
92 // work!), so we use a static buffer for all log messages
93 #define LOG_BUFFER_SIZE (4096)
94
95 // static buffer for error messages (FIXME MT-unsafe)
96 static wxChar s_szBuf[LOG_BUFFER_SIZE];
97
98 // generic log function
99 void wxLogGeneric(wxLogLevel level, const wxChar *szFormat, ...)
100 {
101 if ( wxLog::GetActiveTarget() != NULL ) {
102 va_list argptr;
103 va_start(argptr, szFormat);
104 wxVsprintf(s_szBuf, szFormat, argptr);
105 va_end(argptr);
106
107 wxLog::OnLog(level, s_szBuf, time(NULL));
108 }
109 }
110
111 #define IMPLEMENT_LOG_FUNCTION(level) \
112 void wxLog##level(const wxChar *szFormat, ...) \
113 { \
114 if ( wxLog::GetActiveTarget() != NULL ) { \
115 va_list argptr; \
116 va_start(argptr, szFormat); \
117 wxVsprintf(s_szBuf, szFormat, argptr); \
118 va_end(argptr); \
119 \
120 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
121 } \
122 }
123
124 IMPLEMENT_LOG_FUNCTION(FatalError)
125 IMPLEMENT_LOG_FUNCTION(Error)
126 IMPLEMENT_LOG_FUNCTION(Warning)
127 IMPLEMENT_LOG_FUNCTION(Message)
128 IMPLEMENT_LOG_FUNCTION(Info)
129 IMPLEMENT_LOG_FUNCTION(Status)
130
131 // accepts an additional argument which tells to which frame the output should
132 // be directed
133 void wxLogStatus(wxFrame *pFrame, const wxChar *szFormat, ...)
134 {
135 wxLog *pLog = wxLog::GetActiveTarget();
136 if ( pLog != NULL ) {
137 va_list argptr;
138 va_start(argptr, szFormat);
139 wxVsprintf(s_szBuf, szFormat, argptr);
140 va_end(argptr);
141
142 wxASSERT( gs_pFrame == NULL ); // should be reset!
143 gs_pFrame = pFrame;
144 wxLog::OnLog(wxLOG_Status, s_szBuf, time(NULL));
145 gs_pFrame = (wxFrame *) NULL;
146 }
147 }
148
149 // same as info, but only if 'verbose' mode is on
150 void wxLogVerbose(const wxChar *szFormat, ...)
151 {
152 wxLog *pLog = wxLog::GetActiveTarget();
153 if ( pLog != NULL && pLog->GetVerbose() ) {
154 va_list argptr;
155 va_start(argptr, szFormat);
156 wxVsprintf(s_szBuf, szFormat, argptr);
157 va_end(argptr);
158
159 wxLog::OnLog(wxLOG_Info, s_szBuf, time(NULL));
160 }
161 }
162
163 // debug functions
164 #ifdef __WXDEBUG__
165 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
166 void wxLog##level(const wxChar *szFormat, ...) \
167 { \
168 if ( wxLog::GetActiveTarget() != NULL ) { \
169 va_list argptr; \
170 va_start(argptr, szFormat); \
171 wxVsprintf(s_szBuf, szFormat, argptr); \
172 va_end(argptr); \
173 \
174 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
175 } \
176 }
177
178 void wxLogTrace(const wxChar *mask, const wxChar *szFormat, ...)
179 {
180 wxLog *pLog = wxLog::GetActiveTarget();
181
182 if ( pLog != NULL && wxLog::IsAllowedTraceMask(mask) ) {
183 va_list argptr;
184 va_start(argptr, szFormat);
185 wxVsprintf(s_szBuf, szFormat, argptr);
186 va_end(argptr);
187
188 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
189 }
190 }
191
192 void wxLogTrace(wxTraceMask mask, const wxChar *szFormat, ...)
193 {
194 wxLog *pLog = wxLog::GetActiveTarget();
195
196 // we check that all of mask bits are set in the current mask, so
197 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
198 // if both bits are set.
199 if ( pLog != NULL && ((pLog->GetTraceMask() & mask) == mask) ) {
200 va_list argptr;
201 va_start(argptr, szFormat);
202 wxVsprintf(s_szBuf, szFormat, argptr);
203 va_end(argptr);
204
205 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
206 }
207 }
208
209 #else // release
210 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
211 #endif
212
213 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
214 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
215
216 // wxLogSysError: one uses the last error code, for other you must give it
217 // explicitly
218
219 // common part of both wxLogSysError
220 void wxLogSysErrorHelper(long lErrCode)
221 {
222 wxChar szErrMsg[LOG_BUFFER_SIZE / 2];
223 wxSprintf(szErrMsg, _(" (error %ld: %s)"), lErrCode, wxSysErrorMsg(lErrCode));
224 wxStrncat(s_szBuf, szErrMsg, WXSIZEOF(s_szBuf) - wxStrlen(s_szBuf));
225
226 wxLog::OnLog(wxLOG_Error, s_szBuf, time(NULL));
227 }
228
229 void WXDLLEXPORT wxLogSysError(const wxChar *szFormat, ...)
230 {
231 va_list argptr;
232 va_start(argptr, szFormat);
233 wxVsprintf(s_szBuf, szFormat, argptr);
234 va_end(argptr);
235
236 wxLogSysErrorHelper(wxSysErrorCode());
237 }
238
239 void WXDLLEXPORT wxLogSysError(long lErrCode, const wxChar *szFormat, ...)
240 {
241 va_list argptr;
242 va_start(argptr, szFormat);
243 wxVsprintf(s_szBuf, szFormat, argptr);
244 va_end(argptr);
245
246 wxLogSysErrorHelper(lErrCode);
247 }
248
249 // ----------------------------------------------------------------------------
250 // wxLog class implementation
251 // ----------------------------------------------------------------------------
252
253 wxLog::wxLog()
254 {
255 m_bHasMessages = FALSE;
256
257 // enable verbose messages by default in the debug builds
258 #ifdef __WXDEBUG__
259 m_bVerbose = TRUE;
260 #else // release
261 m_bVerbose = FALSE;
262 #endif // debug/release
263 }
264
265 wxLog *wxLog::GetActiveTarget()
266 {
267 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
268 // prevent infinite recursion if someone calls wxLogXXX() from
269 // wxApp::CreateLogTarget()
270 static bool s_bInGetActiveTarget = FALSE;
271 if ( !s_bInGetActiveTarget ) {
272 s_bInGetActiveTarget = TRUE;
273
274 #ifdef wxUSE_NOGUI
275 ms_pLogger = new wxLogStderr;
276 #else
277 // ask the application to create a log target for us
278 if ( wxTheApp != NULL )
279 ms_pLogger = wxTheApp->CreateLogTarget();
280 else
281 ms_pLogger = new wxLogStderr;
282 #endif
283
284 s_bInGetActiveTarget = FALSE;
285
286 // do nothing if it fails - what can we do?
287 }
288 }
289
290 return ms_pLogger;
291 }
292
293 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
294 {
295 if ( ms_pLogger != NULL ) {
296 // flush the old messages before changing because otherwise they might
297 // get lost later if this target is not restored
298 ms_pLogger->Flush();
299 }
300
301 wxLog *pOldLogger = ms_pLogger;
302 ms_pLogger = pLogger;
303
304 return pOldLogger;
305 }
306
307 void wxLog::RemoveTraceMask(const wxString& str)
308 {
309 int index = ms_aTraceMasks.Index(str);
310 if ( index != wxNOT_FOUND )
311 ms_aTraceMasks.Remove((size_t)index);
312 }
313
314 void wxLog::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
315 {
316 wxString str;
317
318 switch ( level ) {
319 case wxLOG_FatalError:
320 DoLogString(str << _("Fatal error: ") << szString, t);
321 DoLogString(_("Program aborted."), t);
322 Flush();
323 abort();
324 break;
325
326 case wxLOG_Error:
327 DoLogString(str << _("Error: ") << szString, t);
328 break;
329
330 case wxLOG_Warning:
331 DoLogString(str << _("Warning: ") << szString, t);
332 break;
333
334 case wxLOG_Info:
335 if ( GetVerbose() )
336 case wxLOG_Message:
337 DoLogString(str + szString, t);
338 // fall through
339
340 case wxLOG_Status:
341 // nothing to do
342 break;
343
344 case wxLOG_Trace:
345 case wxLOG_Debug:
346 #ifdef __WXDEBUG__
347 DoLogString(szString, t);
348 #endif
349 break;
350 }
351 }
352
353 void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t t)
354 {
355 wxFAIL_MSG(_T("DoLogString must be overriden if it's called."));
356 }
357
358 void wxLog::Flush()
359 {
360 // do nothing
361 }
362
363 // ----------------------------------------------------------------------------
364 // wxLogStderr class implementation
365 // ----------------------------------------------------------------------------
366
367 wxLogStderr::wxLogStderr(FILE *fp)
368 {
369 if ( fp == NULL )
370 m_fp = stderr;
371 else
372 m_fp = fp;
373 }
374
375 void wxLogStderr::DoLogString(const wxChar *szString, time_t t)
376 {
377 wxString str(szString);
378 str << _T('\n');
379
380 fputs(str.mb_str(), m_fp);
381 fflush(m_fp);
382
383 // under Windows, programs usually don't have stderr at all, so make show the
384 // messages also under debugger
385 #ifdef __WXMSW__
386 OutputDebugString(str + _T('\r'));
387 #endif // MSW
388 }
389
390 // ----------------------------------------------------------------------------
391 // wxLogStream implementation
392 // ----------------------------------------------------------------------------
393
394 #if wxUSE_STD_IOSTREAM
395 wxLogStream::wxLogStream(ostream *ostr)
396 {
397 if ( ostr == NULL )
398 m_ostr = &cerr;
399 else
400 m_ostr = ostr;
401 }
402
403 void wxLogStream::DoLogString(const wxChar *szString, time_t t)
404 {
405 (*m_ostr) << szString << endl << flush;
406 }
407 #endif // wxUSE_STD_IOSTREAM
408
409 #ifndef wxUSE_NOGUI
410
411 // ----------------------------------------------------------------------------
412 // wxLogTextCtrl implementation
413 // ----------------------------------------------------------------------------
414
415 #if wxUSE_STD_IOSTREAM
416 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
417 #if !defined(NO_TEXT_WINDOW_STREAM)
418 : wxLogStream(new ostream(pTextCtrl))
419 #endif
420 {
421 }
422
423 wxLogTextCtrl::~wxLogTextCtrl()
424 {
425 delete m_ostr;
426 }
427 #endif // wxUSE_STD_IOSTREAM
428
429 // ----------------------------------------------------------------------------
430 // wxLogGui implementation (FIXME MT-unsafe)
431 // ----------------------------------------------------------------------------
432
433 wxLogGui::wxLogGui()
434 {
435 Clear();
436 }
437
438 void wxLogGui::Clear()
439 {
440 m_bErrors = m_bWarnings = FALSE;
441 m_aMessages.Empty();
442 m_aTimes.Empty();
443 }
444
445 void wxLogGui::Flush()
446 {
447 if ( !m_bHasMessages )
448 return;
449
450 // do it right now to block any new calls to Flush() while we're here
451 m_bHasMessages = FALSE;
452
453 // concatenate all strings (but not too many to not overfill the msg box)
454 wxString str;
455 size_t nLines = 0,
456 nMsgCount = m_aMessages.Count();
457
458 // start from the most recent message
459 for ( size_t n = nMsgCount; n > 0; n-- ) {
460 // for Windows strings longer than this value are wrapped (NT 4.0)
461 const size_t nMsgLineWidth = 156;
462
463 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
464
465 if ( nLines > 25 ) // don't put too many lines in message box
466 break;
467
468 str << m_aMessages[n - 1] << _T("\n");
469 }
470
471 const wxChar *title;
472 long style;
473
474 if ( m_bErrors ) {
475 title = _("Error");
476 style = wxICON_STOP;
477 }
478 else if ( m_bWarnings ) {
479 title = _("Warning");
480 style = wxICON_EXCLAMATION;
481 }
482 else {
483 title = _("Information");
484 style = wxICON_INFORMATION;
485 }
486
487 wxMessageBox(str, title, wxOK | style);
488
489 // no undisplayed messages whatsoever
490 Clear();
491 }
492
493 // the default behaviour is to discard all informational messages if there
494 // are any errors/warnings.
495 void wxLogGui::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
496 {
497 switch ( level ) {
498 case wxLOG_Info:
499 if ( GetVerbose() )
500 case wxLOG_Message:
501 if ( !m_bErrors ) {
502 m_aMessages.Add(szString);
503 m_aTimes.Add((long)t);
504 m_bHasMessages = TRUE;
505 }
506 break;
507
508 case wxLOG_Status:
509 {
510 // find the top window and set it's status text if it has any
511 wxFrame *pFrame = gs_pFrame;
512 if ( pFrame == NULL ) {
513 wxWindow *pWin = wxTheApp->GetTopWindow();
514 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
515 pFrame = (wxFrame *)pWin;
516 }
517 }
518
519 if ( pFrame != NULL )
520 pFrame->SetStatusText(szString);
521 }
522 break;
523
524 case wxLOG_Trace:
525 case wxLOG_Debug:
526 #ifdef __WXDEBUG__
527 {
528 #ifdef __WXMSW__
529 // don't prepend debug/trace here: it goes to the
530 // debug window anyhow, but do put a timestamp
531 OutputDebugString(wxString(szString) + _T("\n\r"));
532 #else
533 // send them to stderr
534 wxFprintf(stderr, _T("%s: %s\n"),
535 level == wxLOG_Trace ? _T("Trace") : _T("Debug"),
536 szString);
537 fflush(stderr);
538 #endif
539 }
540 #endif // __WXDEBUG__
541
542 break;
543
544 case wxLOG_FatalError:
545 // show this one immediately
546 wxMessageBox(szString, _("Fatal error"), wxICON_HAND);
547 break;
548
549 case wxLOG_Error:
550 // discard earlier informational messages if this is the 1st
551 // error because they might not make sense any more
552 if ( !m_bErrors ) {
553 m_aMessages.Empty();
554 m_aTimes.Empty();
555 m_bHasMessages = TRUE;
556 m_bErrors = TRUE;
557 }
558 // fall through
559
560 case wxLOG_Warning:
561 if ( !m_bErrors ) {
562 // for the warning we don't discard the info messages
563 m_bWarnings = TRUE;
564 }
565
566 m_aMessages.Add(szString);
567 m_aTimes.Add((long)t);
568 break;
569 }
570 }
571
572 // ----------------------------------------------------------------------------
573 // wxLogWindow and wxLogFrame implementation
574 // ----------------------------------------------------------------------------
575
576 // log frame class
577 // ---------------
578 class wxLogFrame : public wxFrame
579 {
580 public:
581 // ctor & dtor
582 wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle);
583 virtual ~wxLogFrame();
584
585 // menu callbacks
586 void OnClose(wxCommandEvent& event);
587 void OnCloseWindow(wxCloseEvent& event);
588 void OnSave (wxCommandEvent& event);
589 void OnClear(wxCommandEvent& event);
590
591 void OnIdle(wxIdleEvent&);
592
593 // accessors
594 wxTextCtrl *TextCtrl() const { return m_pTextCtrl; }
595
596 private:
597 enum
598 {
599 Menu_Close = 100,
600 Menu_Save,
601 Menu_Clear
602 };
603
604 // instead of closing just hide the window to be able to Show() it later
605 void DoClose() { Show(FALSE); }
606
607 wxTextCtrl *m_pTextCtrl;
608 wxLogWindow *m_log;
609
610 DECLARE_EVENT_TABLE()
611 };
612
613 BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
614 // wxLogWindow menu events
615 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
616 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
617 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
618
619 EVT_CLOSE(wxLogFrame::OnCloseWindow)
620 END_EVENT_TABLE()
621
622 wxLogFrame::wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle)
623 : wxFrame(pParent, -1, szTitle)
624 {
625 m_log = log;
626
627 m_pTextCtrl = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition,
628 wxDefaultSize,
629 wxTE_MULTILINE |
630 wxHSCROLL |
631 wxTE_READONLY);
632
633 // create menu
634 wxMenuBar *pMenuBar = new wxMenuBar;
635 wxMenu *pMenu = new wxMenu;
636 pMenu->Append(Menu_Save, _("&Save..."), _("Save log contents to file"));
637 pMenu->Append(Menu_Clear, _("C&lear"), _("Clear the log contents"));
638 pMenu->AppendSeparator();
639 pMenu->Append(Menu_Close, _("&Close"), _("Close this window"));
640 pMenuBar->Append(pMenu, _("&Log"));
641 SetMenuBar(pMenuBar);
642
643 // status bar for menu prompts
644 CreateStatusBar();
645
646 m_log->OnFrameCreate(this);
647 }
648
649 void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
650 {
651 DoClose();
652 }
653
654 void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
655 {
656 DoClose();
657 }
658
659 void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
660 {
661 // get the file name
662 // -----------------
663 const wxChar *szFileName = wxSaveFileSelector(_T("log"), _T("txt"), _T("log.txt"));
664 if ( szFileName == NULL ) {
665 // cancelled
666 return;
667 }
668
669 // open file
670 // ---------
671 wxFile file;
672 bool bOk = FALSE;
673 if ( wxFile::Exists(szFileName) ) {
674 bool bAppend = FALSE;
675 wxString strMsg;
676 strMsg.Printf(_("Append log to file '%s' "
677 "(choosing [No] will overwrite it)?"), szFileName);
678 switch ( wxMessageBox(strMsg, _("Question"), wxYES_NO | wxCANCEL) ) {
679 case wxYES:
680 bAppend = TRUE;
681 break;
682
683 case wxNO:
684 bAppend = FALSE;
685 break;
686
687 case wxCANCEL:
688 return;
689
690 default:
691 wxFAIL_MSG(_("invalid message box return value"));
692 }
693
694 if ( bAppend ) {
695 bOk = file.Open(szFileName, wxFile::write_append);
696 }
697 else {
698 bOk = file.Create(szFileName, TRUE /* overwrite */);
699 }
700 }
701 else {
702 bOk = file.Create(szFileName);
703 }
704
705 // retrieve text and save it
706 // -------------------------
707 int nLines = m_pTextCtrl->GetNumberOfLines();
708 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
709 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) +
710 // we're not going to pull in the whole wxTextFile if all we need is this...
711 #if wxUSE_TEXTFILE
712 wxTextFile::GetEOL()
713 #else // !wxUSE_TEXTFILE
714 '\n'
715 #endif // wxUSE_TEXTFILE
716 );
717 }
718
719 if ( bOk )
720 bOk = file.Close();
721
722 if ( !bOk ) {
723 wxLogError(_("Can't save log contents to file."));
724 }
725 else {
726 wxLogStatus(this, _("Log saved to the file '%s'."), szFileName);
727 }
728 }
729
730 void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
731 {
732 m_pTextCtrl->Clear();
733 }
734
735 wxLogFrame::~wxLogFrame()
736 {
737 m_log->OnFrameDelete(this);
738 }
739
740 // wxLogWindow
741 // -----------
742 wxLogWindow::wxLogWindow(wxFrame *pParent,
743 const wxChar *szTitle,
744 bool bShow,
745 bool bDoPass)
746 {
747 m_bPassMessages = bDoPass;
748
749 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
750 m_pOldLog = wxLog::SetActiveTarget(this);
751
752 if ( bShow )
753 m_pLogFrame->Show(TRUE);
754 }
755
756 void wxLogWindow::Show(bool bShow)
757 {
758 m_pLogFrame->Show(bShow);
759 }
760
761 void wxLogWindow::Flush()
762 {
763 if ( m_pOldLog != NULL )
764 m_pOldLog->Flush();
765
766 m_bHasMessages = FALSE;
767 }
768
769 void wxLogWindow::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
770 {
771 // first let the previous logger show it
772 if ( m_pOldLog != NULL && m_bPassMessages ) {
773 // FIXME why can't we access protected wxLog method from here (we derive
774 // from wxLog)? gcc gives "DoLog is protected in this context", what
775 // does this mean? Anyhow, the cast is harmless and let's us do what
776 // we want.
777 ((wxLogWindow *)m_pOldLog)->DoLog(level, szString, t);
778 }
779
780 if ( m_pLogFrame ) {
781 switch ( level ) {
782 case wxLOG_Status:
783 // by default, these messages are ignored by wxLog, so process
784 // them ourselves
785 if ( !wxIsEmpty(szString) )
786 {
787 wxString str;
788 str << _("Status: ") << szString;
789 DoLogString(str, t);
790 }
791 break;
792
793 // don't put trace messages in the text window for 2 reasons:
794 // 1) there are too many of them
795 // 2) they may provoke other trace messages thus sending a program
796 // into an infinite loop
797 case wxLOG_Trace:
798 break;
799
800 default:
801 // and this will format it nicely and call our DoLogString()
802 wxLog::DoLog(level, szString, t);
803 }
804 }
805
806 m_bHasMessages = TRUE;
807 }
808
809 void wxLogWindow::DoLogString(const wxChar *szString, time_t t)
810 {
811 // put the text into our window
812 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
813
814 // remove selection (WriteText is in fact ReplaceSelection)
815 #ifdef __WXMSW__
816 long nLen = pText->GetLastPosition();
817 pText->SetSelection(nLen, nLen);
818 #endif // Windows
819
820 pText->WriteText(szString);
821 pText->WriteText(_T("\n")); // "\n" ok here (_not_ "\r\n")
822
823 // TODO ensure that the line can be seen
824 }
825
826 wxFrame *wxLogWindow::GetFrame() const
827 {
828 return m_pLogFrame;
829 }
830
831 void wxLogWindow::OnFrameCreate(wxFrame * WXUNUSED(frame))
832 {
833 }
834
835 void wxLogWindow::OnFrameDelete(wxFrame * WXUNUSED(frame))
836 {
837 m_pLogFrame = (wxLogFrame *)NULL;
838 }
839
840 wxLogWindow::~wxLogWindow()
841 {
842 delete m_pOldLog;
843
844 // may be NULL if log frame already auto destroyed itself
845 delete m_pLogFrame;
846 }
847
848 #endif //wxUSE_NOGUI
849
850 // ============================================================================
851 // Global functions/variables
852 // ============================================================================
853
854 // ----------------------------------------------------------------------------
855 // static variables
856 // ----------------------------------------------------------------------------
857
858 wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
859 bool wxLog::ms_doLog = TRUE;
860 bool wxLog::ms_bAutoCreate = TRUE;
861 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
862 wxArrayString wxLog::ms_aTraceMasks;
863
864 // ----------------------------------------------------------------------------
865 // stdout error logging helper
866 // ----------------------------------------------------------------------------
867
868 // helper function: wraps the message and justifies it under given position
869 // (looks more pretty on the terminal). Also adds newline at the end.
870 //
871 // TODO this is now disabled until I find a portable way of determining the
872 // terminal window size (ok, I found it but does anybody really cares?)
873 #ifdef LOG_PRETTY_WRAP
874 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
875 {
876 size_t nMax = 80; // FIXME
877 size_t nStart = strlen(pszPrefix);
878 fputs(pszPrefix, f);
879
880 size_t n;
881 while ( *psz != '\0' ) {
882 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
883 putc(*psz++, f);
884
885 // wrapped?
886 if ( *psz != '\0' ) {
887 /*putc('\n', f);*/
888 for ( n = 0; n < nStart; n++ )
889 putc(' ', f);
890
891 // as we wrapped, squeeze all white space
892 while ( isspace(*psz) )
893 psz++;
894 }
895 }
896
897 putc('\n', f);
898 }
899 #endif //LOG_PRETTY_WRAP
900
901 // ----------------------------------------------------------------------------
902 // error code/error message retrieval functions
903 // ----------------------------------------------------------------------------
904
905 // get error code from syste
906 unsigned long wxSysErrorCode()
907 {
908 #ifdef __WXMSW__
909 #ifdef __WIN32__
910 return ::GetLastError();
911 #else //WIN16
912 // TODO what to do on Windows 3.1?
913 return 0;
914 #endif //WIN16/32
915 #else //Unix
916 return errno;
917 #endif //Win/Unix
918 }
919
920 // get error message from system
921 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
922 {
923 if ( nErrCode == 0 )
924 nErrCode = wxSysErrorCode();
925
926 #ifdef __WXMSW__
927 #ifdef __WIN32__
928 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
929
930 // get error message from system
931 LPVOID lpMsgBuf;
932 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
933 NULL, nErrCode,
934 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
935 (LPTSTR)&lpMsgBuf,
936 0, NULL);
937
938 // copy it to our buffer and free memory
939 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
940 s_szBuf[WXSIZEOF(s_szBuf) - 1] = _T('\0');
941 LocalFree(lpMsgBuf);
942
943 // returned string is capitalized and ended with '\r\n' - bad
944 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
945 size_t len = wxStrlen(s_szBuf);
946 if ( len > 0 ) {
947 // truncate string
948 if ( s_szBuf[len - 2] == _T('\r') )
949 s_szBuf[len - 2] = _T('\0');
950 }
951
952 return s_szBuf;
953 #else //Win16
954 // TODO
955 return NULL;
956 #endif // Win16/32
957 #else // Unix
958 #if wxUSE_UNICODE
959 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
960 wxConv_libc.MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
961 return s_szBuf;
962 #else
963 return strerror(nErrCode);
964 #endif
965 #endif // Win/Unix
966 }
967
968 // ----------------------------------------------------------------------------
969 // debug helper
970 // ----------------------------------------------------------------------------
971
972 #ifdef __WXDEBUG__
973
974 // break into the debugger
975 void Trap()
976 {
977 #ifdef __WXMSW__
978 DebugBreak();
979 #elif defined(__WXMAC__)
980 #if __powerc
981 Debugger();
982 #else
983 SysBreak();
984 #endif
985 #elif defined(__UNIX__)
986 raise(SIGTRAP);
987 #else
988 // TODO
989 #endif // Win/Unix
990 }
991
992 // this function is called when an assert fails
993 void wxOnAssert(const char *szFile, int nLine, const wxChar *szMsg)
994 {
995 // this variable can be set to true to suppress "assert failure" messages
996 static bool s_bNoAsserts = FALSE;
997 static bool s_bInAssert = FALSE; // FIXME MT-unsafe
998
999 if ( s_bInAssert ) {
1000 // He-e-e-e-elp!! we're trapped in endless loop
1001 Trap();
1002
1003 s_bInAssert = FALSE;
1004
1005 return;
1006 }
1007
1008 s_bInAssert = TRUE;
1009
1010 wxChar szBuf[LOG_BUFFER_SIZE];
1011
1012 // make life easier for people using VC++ IDE: clicking on the message
1013 // will take us immediately to the place of the failed assert
1014 #ifdef __VISUALC__
1015 wxSprintf(szBuf, _T("%s(%d): assert failed"), szFile, nLine);
1016 #else // !VC++
1017 // make the error message more clear for all the others
1018 #ifdef wxSprintf
1019 wxSprintf(szBuf, _T("Assert failed in file %s at line %d"), szFile, nLine);
1020 #else
1021 wxSprintf(szBuf, _T("Assert failed in file %hs at line %d"), szFile, nLine);
1022 #endif
1023 #endif // VC/!VC
1024
1025 if ( szMsg != NULL ) {
1026 wxStrcat(szBuf, _T(": "));
1027 wxStrcat(szBuf, szMsg);
1028 }
1029 else {
1030 wxStrcat(szBuf, _T("."));
1031 }
1032
1033 if ( !s_bNoAsserts ) {
1034 // send it to the normal log destination
1035 wxLogDebug(szBuf);
1036
1037 #if wxUSE_NOGUI
1038 Trap();
1039 #else
1040 // this message is intentionally not translated - it is for
1041 // developpers only
1042 wxStrcat(szBuf, _T("\nDo you want to stop the program?"
1043 "\nYou can also choose [Cancel] to suppress "
1044 "further warnings."));
1045
1046 switch ( wxMessageBox(szBuf, _("Debug"),
1047 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
1048 case wxYES:
1049 Trap();
1050 break;
1051
1052 case wxCANCEL:
1053 s_bNoAsserts = TRUE;
1054 break;
1055
1056 //case wxNO: nothing to do
1057 }
1058 #endif // USE_NOGUI
1059 }
1060
1061 s_bInAssert = FALSE;
1062 }
1063
1064 #endif //WXDEBUG
1065