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