]> git.saurik.com Git - wxWidgets.git/blob - src/common/log.cpp
Ignore erase failures
[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::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
319 {
320 switch ( level ) {
321 case wxLOG_FatalError:
322 DoLogString(wxString(_("Fatal error: ")) + szString, t);
323 DoLogString(_("Program aborted."), t);
324 Flush();
325 abort();
326 break;
327
328 case wxLOG_Error:
329 DoLogString(wxString(_("Error: ")) + szString, t);
330 break;
331
332 case wxLOG_Warning:
333 DoLogString(wxString(_("Warning: ")) + szString, t);
334 break;
335
336 case wxLOG_Info:
337 if ( GetVerbose() )
338 case wxLOG_Message:
339 default: // log unknown log levels too
340 DoLogString(szString, t);
341 // fall through
342
343 case wxLOG_Status:
344 // nothing to do
345 break;
346
347 case wxLOG_Trace:
348 case wxLOG_Debug:
349 #ifdef __WXDEBUG__
350 DoLogString(szString, t);
351 #endif
352 break;
353 }
354 }
355
356 void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t WXUNUSED(t))
357 {
358 wxFAIL_MSG(_T("DoLogString must be overriden if it's called."));
359 }
360
361 void wxLog::Flush()
362 {
363 // do nothing
364 }
365
366 // ----------------------------------------------------------------------------
367 // wxLogStderr class implementation
368 // ----------------------------------------------------------------------------
369
370 wxLogStderr::wxLogStderr(FILE *fp)
371 {
372 if ( fp == NULL )
373 m_fp = stderr;
374 else
375 m_fp = fp;
376 }
377
378 void wxLogStderr::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
379 {
380 wxString str(szString);
381 str << _T('\n');
382
383 fputs(str.mb_str(), m_fp);
384 fflush(m_fp);
385
386 // under Windows, programs usually don't have stderr at all, so make show the
387 // messages also under debugger
388 #ifdef __WXMSW__
389 OutputDebugString(str + _T('\r'));
390 #endif // MSW
391 }
392
393 // ----------------------------------------------------------------------------
394 // wxLogStream implementation
395 // ----------------------------------------------------------------------------
396
397 #if wxUSE_STD_IOSTREAM
398 wxLogStream::wxLogStream(ostream *ostr)
399 {
400 if ( ostr == NULL )
401 m_ostr = &cerr;
402 else
403 m_ostr = ostr;
404 }
405
406 void wxLogStream::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
407 {
408 (*m_ostr) << wxConvCurrent->cWX2MB(szString) << endl << flush;
409 }
410 #endif // wxUSE_STD_IOSTREAM
411
412 #ifndef wxUSE_NOGUI
413
414 // ----------------------------------------------------------------------------
415 // wxLogTextCtrl implementation
416 // ----------------------------------------------------------------------------
417
418 #if wxUSE_STD_IOSTREAM
419 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
420 #if !defined(NO_TEXT_WINDOW_STREAM)
421 : wxLogStream(new ostream(pTextCtrl))
422 #endif
423 {
424 }
425
426 wxLogTextCtrl::~wxLogTextCtrl()
427 {
428 delete m_ostr;
429 }
430 #endif // wxUSE_STD_IOSTREAM
431
432 // ----------------------------------------------------------------------------
433 // wxLogGui implementation (FIXME MT-unsafe)
434 // ----------------------------------------------------------------------------
435
436 wxLogGui::wxLogGui()
437 {
438 Clear();
439 }
440
441 void wxLogGui::Clear()
442 {
443 m_bErrors = m_bWarnings = FALSE;
444 m_aMessages.Empty();
445 m_aTimes.Empty();
446 }
447
448 void wxLogGui::Flush()
449 {
450 if ( !m_bHasMessages )
451 return;
452
453 // do it right now to block any new calls to Flush() while we're here
454 m_bHasMessages = FALSE;
455
456 // concatenate all strings (but not too many to not overfill the msg box)
457 wxString str;
458 size_t nLines = 0,
459 nMsgCount = m_aMessages.Count();
460
461 // start from the most recent message
462 for ( size_t n = nMsgCount; n > 0; n-- ) {
463 // for Windows strings longer than this value are wrapped (NT 4.0)
464 const size_t nMsgLineWidth = 156;
465
466 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
467
468 if ( nLines > 25 ) // don't put too many lines in message box
469 break;
470
471 str << m_aMessages[n - 1] << _T("\n");
472 }
473
474 const wxChar *title;
475 long style;
476
477 if ( m_bErrors ) {
478 title = _("Error");
479 style = wxICON_STOP;
480 }
481 else if ( m_bWarnings ) {
482 title = _("Warning");
483 style = wxICON_EXCLAMATION;
484 }
485 else {
486 title = _("Information");
487 style = wxICON_INFORMATION;
488 }
489
490 wxMessageBox(str, title, wxOK | style);
491
492 // no undisplayed messages whatsoever
493 Clear();
494 }
495
496 // the default behaviour is to discard all informational messages if there
497 // are any errors/warnings.
498 void wxLogGui::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
499 {
500 switch ( level ) {
501 case wxLOG_Info:
502 if ( GetVerbose() )
503 case wxLOG_Message:
504 if ( !m_bErrors ) {
505 m_aMessages.Add(szString);
506 m_aTimes.Add((long)t);
507 m_bHasMessages = TRUE;
508 }
509 break;
510
511 case wxLOG_Status:
512 #if wxUSE_STATUSBAR
513 {
514 // find the top window and set it's status text if it has any
515 wxFrame *pFrame = gs_pFrame;
516 if ( pFrame == NULL ) {
517 wxWindow *pWin = wxTheApp->GetTopWindow();
518 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
519 pFrame = (wxFrame *)pWin;
520 }
521 }
522
523 if ( pFrame != NULL )
524 pFrame->SetStatusText(szString);
525 }
526 #endif // wxUSE_STATUSBAR
527 break;
528
529 case wxLOG_Trace:
530 case wxLOG_Debug:
531 #ifdef __WXDEBUG__
532 {
533 #ifdef __WXMSW__
534 // don't prepend debug/trace here: it goes to the
535 // debug window anyhow, but do put a timestamp
536 OutputDebugString(wxString(szString) + _T("\n\r"));
537 #else
538 // send them to stderr
539 wxFprintf(stderr, _T("%s: %s\n"),
540 level == wxLOG_Trace ? _T("Trace") : _T("Debug"),
541 szString);
542 fflush(stderr);
543 #endif
544 }
545 #endif // __WXDEBUG__
546
547 break;
548
549 case wxLOG_FatalError:
550 // show this one immediately
551 wxMessageBox(szString, _("Fatal error"), wxICON_HAND);
552 break;
553
554 case wxLOG_Error:
555 // discard earlier informational messages if this is the 1st
556 // error because they might not make sense any more
557 if ( !m_bErrors ) {
558 m_aMessages.Empty();
559 m_aTimes.Empty();
560 m_bHasMessages = TRUE;
561 m_bErrors = TRUE;
562 }
563 // fall through
564
565 case wxLOG_Warning:
566 if ( !m_bErrors ) {
567 // for the warning we don't discard the info messages
568 m_bWarnings = TRUE;
569 }
570
571 m_aMessages.Add(szString);
572 m_aTimes.Add((long)t);
573 break;
574 }
575 }
576
577 // ----------------------------------------------------------------------------
578 // wxLogWindow and wxLogFrame implementation
579 // ----------------------------------------------------------------------------
580
581 // log frame class
582 // ---------------
583 class wxLogFrame : public wxFrame
584 {
585 public:
586 // ctor & dtor
587 wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle);
588 virtual ~wxLogFrame();
589
590 // menu callbacks
591 void OnClose(wxCommandEvent& event);
592 void OnCloseWindow(wxCloseEvent& event);
593 #if wxUSE_FILE
594 void OnSave (wxCommandEvent& event);
595 #endif // wxUSE_FILE
596 void OnClear(wxCommandEvent& event);
597
598 void OnIdle(wxIdleEvent&);
599
600 // accessors
601 wxTextCtrl *TextCtrl() const { return m_pTextCtrl; }
602
603 private:
604 enum
605 {
606 Menu_Close = 100,
607 Menu_Save,
608 Menu_Clear
609 };
610
611 // instead of closing just hide the window to be able to Show() it later
612 void DoClose() { Show(FALSE); }
613
614 wxTextCtrl *m_pTextCtrl;
615 wxLogWindow *m_log;
616
617 DECLARE_EVENT_TABLE()
618 };
619
620 BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
621 // wxLogWindow menu events
622 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
623 #if wxUSE_FILE
624 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
625 #endif // wxUSE_FILE
626 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
627
628 EVT_CLOSE(wxLogFrame::OnCloseWindow)
629 END_EVENT_TABLE()
630
631 wxLogFrame::wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle)
632 : wxFrame(pParent, -1, szTitle)
633 {
634 m_log = log;
635
636 m_pTextCtrl = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition,
637 wxDefaultSize,
638 wxTE_MULTILINE |
639 wxHSCROLL |
640 wxTE_READONLY);
641
642 // create menu
643 wxMenuBar *pMenuBar = new wxMenuBar;
644 wxMenu *pMenu = new wxMenu;
645 #if wxUSE_FILE
646 pMenu->Append(Menu_Save, _("&Save..."), _("Save log contents to file"));
647 #endif // wxUSE_FILE
648 pMenu->Append(Menu_Clear, _("C&lear"), _("Clear the log contents"));
649 pMenu->AppendSeparator();
650 pMenu->Append(Menu_Close, _("&Close"), _("Close this window"));
651 pMenuBar->Append(pMenu, _("&Log"));
652 SetMenuBar(pMenuBar);
653
654 #if wxUSE_STATUSBAR
655 // status bar for menu prompts
656 CreateStatusBar();
657 #endif // wxUSE_STATUSBAR
658
659 m_log->OnFrameCreate(this);
660 }
661
662 void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
663 {
664 DoClose();
665 }
666
667 void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
668 {
669 DoClose();
670 }
671
672 #if wxUSE_FILE
673 void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
674 {
675 // get the file name
676 // -----------------
677 const wxChar *szFileName = wxSaveFileSelector(_T("log"), _T("txt"), _T("log.txt"));
678 if ( szFileName == NULL ) {
679 // cancelled
680 return;
681 }
682
683 // open file
684 // ---------
685 wxFile file;
686 bool bOk = FALSE;
687 if ( wxFile::Exists(szFileName) ) {
688 bool bAppend = FALSE;
689 wxString strMsg;
690 strMsg.Printf(_("Append log to file '%s' "
691 "(choosing [No] will overwrite it)?"), szFileName);
692 switch ( wxMessageBox(strMsg, _("Question"), wxYES_NO | wxCANCEL) ) {
693 case wxYES:
694 bAppend = TRUE;
695 break;
696
697 case wxNO:
698 bAppend = FALSE;
699 break;
700
701 case wxCANCEL:
702 return;
703
704 default:
705 wxFAIL_MSG(_("invalid message box return value"));
706 }
707
708 if ( bAppend ) {
709 bOk = file.Open(szFileName, wxFile::write_append);
710 }
711 else {
712 bOk = file.Create(szFileName, TRUE /* overwrite */);
713 }
714 }
715 else {
716 bOk = file.Create(szFileName);
717 }
718
719 // retrieve text and save it
720 // -------------------------
721 int nLines = m_pTextCtrl->GetNumberOfLines();
722 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
723 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) +
724 // we're not going to pull in the whole wxTextFile if all we need is this...
725 #if wxUSE_TEXTFILE
726 wxTextFile::GetEOL()
727 #else // !wxUSE_TEXTFILE
728 '\n'
729 #endif // wxUSE_TEXTFILE
730 );
731 }
732
733 if ( bOk )
734 bOk = file.Close();
735
736 if ( !bOk ) {
737 wxLogError(_("Can't save log contents to file."));
738 }
739 else {
740 wxLogStatus(this, _("Log saved to the file '%s'."), szFileName);
741 }
742 }
743 #endif // wxUSE_FILE
744
745 void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
746 {
747 m_pTextCtrl->Clear();
748 }
749
750 wxLogFrame::~wxLogFrame()
751 {
752 m_log->OnFrameDelete(this);
753 }
754
755 // wxLogWindow
756 // -----------
757 wxLogWindow::wxLogWindow(wxFrame *pParent,
758 const wxChar *szTitle,
759 bool bShow,
760 bool bDoPass)
761 {
762 m_bPassMessages = bDoPass;
763
764 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
765 m_pOldLog = wxLog::SetActiveTarget(this);
766
767 if ( bShow )
768 m_pLogFrame->Show(TRUE);
769 }
770
771 void wxLogWindow::Show(bool bShow)
772 {
773 m_pLogFrame->Show(bShow);
774 }
775
776 void wxLogWindow::Flush()
777 {
778 if ( m_pOldLog != NULL )
779 m_pOldLog->Flush();
780
781 m_bHasMessages = FALSE;
782 }
783
784 void wxLogWindow::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
785 {
786 // first let the previous logger show it
787 if ( m_pOldLog != NULL && m_bPassMessages ) {
788 // FIXME why can't we access protected wxLog method from here (we derive
789 // from wxLog)? gcc gives "DoLog is protected in this context", what
790 // does this mean? Anyhow, the cast is harmless and let's us do what
791 // we want.
792 ((wxLogWindow *)m_pOldLog)->DoLog(level, szString, t);
793 }
794
795 if ( m_pLogFrame ) {
796 switch ( level ) {
797 case wxLOG_Status:
798 // by default, these messages are ignored by wxLog, so process
799 // them ourselves
800 if ( !wxIsEmpty(szString) )
801 {
802 wxString str;
803 str << _("Status: ") << szString;
804 DoLogString(str, t);
805 }
806 break;
807
808 // don't put trace messages in the text window for 2 reasons:
809 // 1) there are too many of them
810 // 2) they may provoke other trace messages thus sending a program
811 // into an infinite loop
812 case wxLOG_Trace:
813 break;
814
815 default:
816 // and this will format it nicely and call our DoLogString()
817 wxLog::DoLog(level, szString, t);
818 }
819 }
820
821 m_bHasMessages = TRUE;
822 }
823
824 void wxLogWindow::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
825 {
826 // put the text into our window
827 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
828
829 // remove selection (WriteText is in fact ReplaceSelection)
830 #ifdef __WXMSW__
831 long nLen = pText->GetLastPosition();
832 pText->SetSelection(nLen, nLen);
833 #endif // Windows
834
835 pText->WriteText(szString);
836 pText->WriteText(_T("\n")); // "\n" ok here (_not_ "\r\n")
837
838 // TODO ensure that the line can be seen
839 }
840
841 wxFrame *wxLogWindow::GetFrame() const
842 {
843 return m_pLogFrame;
844 }
845
846 void wxLogWindow::OnFrameCreate(wxFrame * WXUNUSED(frame))
847 {
848 }
849
850 void wxLogWindow::OnFrameDelete(wxFrame * WXUNUSED(frame))
851 {
852 m_pLogFrame = (wxLogFrame *)NULL;
853 }
854
855 wxLogWindow::~wxLogWindow()
856 {
857 delete m_pOldLog;
858
859 // may be NULL if log frame already auto destroyed itself
860 delete m_pLogFrame;
861 }
862
863 #endif //wxUSE_NOGUI
864
865 // ============================================================================
866 // Global functions/variables
867 // ============================================================================
868
869 // ----------------------------------------------------------------------------
870 // static variables
871 // ----------------------------------------------------------------------------
872
873 wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
874 bool wxLog::ms_doLog = TRUE;
875 bool wxLog::ms_bAutoCreate = TRUE;
876 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
877 wxArrayString wxLog::ms_aTraceMasks;
878
879 // ----------------------------------------------------------------------------
880 // stdout error logging helper
881 // ----------------------------------------------------------------------------
882
883 // helper function: wraps the message and justifies it under given position
884 // (looks more pretty on the terminal). Also adds newline at the end.
885 //
886 // TODO this is now disabled until I find a portable way of determining the
887 // terminal window size (ok, I found it but does anybody really cares?)
888 #ifdef LOG_PRETTY_WRAP
889 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
890 {
891 size_t nMax = 80; // FIXME
892 size_t nStart = strlen(pszPrefix);
893 fputs(pszPrefix, f);
894
895 size_t n;
896 while ( *psz != '\0' ) {
897 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
898 putc(*psz++, f);
899
900 // wrapped?
901 if ( *psz != '\0' ) {
902 /*putc('\n', f);*/
903 for ( n = 0; n < nStart; n++ )
904 putc(' ', f);
905
906 // as we wrapped, squeeze all white space
907 while ( isspace(*psz) )
908 psz++;
909 }
910 }
911
912 putc('\n', f);
913 }
914 #endif //LOG_PRETTY_WRAP
915
916 // ----------------------------------------------------------------------------
917 // error code/error message retrieval functions
918 // ----------------------------------------------------------------------------
919
920 // get error code from syste
921 unsigned long wxSysErrorCode()
922 {
923 #ifdef __WXMSW__
924 #ifdef __WIN32__
925 return ::GetLastError();
926 #else //WIN16
927 // TODO what to do on Windows 3.1?
928 return 0;
929 #endif //WIN16/32
930 #else //Unix
931 return errno;
932 #endif //Win/Unix
933 }
934
935 // get error message from system
936 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
937 {
938 if ( nErrCode == 0 )
939 nErrCode = wxSysErrorCode();
940
941 #ifdef __WXMSW__
942 #ifdef __WIN32__
943 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
944
945 // get error message from system
946 LPVOID lpMsgBuf;
947 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
948 NULL, nErrCode,
949 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
950 (LPTSTR)&lpMsgBuf,
951 0, NULL);
952
953 // copy it to our buffer and free memory
954 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
955 s_szBuf[WXSIZEOF(s_szBuf) - 1] = _T('\0');
956 LocalFree(lpMsgBuf);
957
958 // returned string is capitalized and ended with '\r\n' - bad
959 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
960 size_t len = wxStrlen(s_szBuf);
961 if ( len > 0 ) {
962 // truncate string
963 if ( s_szBuf[len - 2] == _T('\r') )
964 s_szBuf[len - 2] = _T('\0');
965 }
966
967 return s_szBuf;
968 #else //Win16
969 // TODO
970 return NULL;
971 #endif // Win16/32
972 #else // Unix
973 #if wxUSE_UNICODE
974 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
975 wxConvCurrent->MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
976 return s_szBuf;
977 #else
978 return strerror(nErrCode);
979 #endif
980 #endif // Win/Unix
981 }
982
983 // ----------------------------------------------------------------------------
984 // debug helper
985 // ----------------------------------------------------------------------------
986
987 #ifdef __WXDEBUG__
988
989 // break into the debugger
990 void Trap()
991 {
992 #ifdef __WXMSW__
993 DebugBreak();
994 #elif defined(__WXMAC__)
995 #if __powerc
996 Debugger();
997 #else
998 SysBreak();
999 #endif
1000 #elif defined(__UNIX__)
1001 raise(SIGTRAP);
1002 #else
1003 // TODO
1004 #endif // Win/Unix
1005 }
1006
1007 // this function is called when an assert fails
1008 void wxOnAssert(const wxChar *szFile, int nLine, const wxChar *szMsg)
1009 {
1010 // this variable can be set to true to suppress "assert failure" messages
1011 static bool s_bNoAsserts = FALSE;
1012 static bool s_bInAssert = FALSE; // FIXME MT-unsafe
1013
1014 if ( s_bInAssert ) {
1015 // He-e-e-e-elp!! we're trapped in endless loop
1016 Trap();
1017
1018 s_bInAssert = FALSE;
1019
1020 return;
1021 }
1022
1023 s_bInAssert = TRUE;
1024
1025 wxChar szBuf[LOG_BUFFER_SIZE];
1026
1027 // make life easier for people using VC++ IDE: clicking on the message
1028 // will take us immediately to the place of the failed assert
1029 #ifdef __VISUALC__
1030 wxSprintf(szBuf, _T("%s(%d): assert failed"), szFile, nLine);
1031 #else // !VC++
1032 // make the error message more clear for all the others
1033 wxSprintf(szBuf, _T("Assert failed in file %s at line %d"), szFile, nLine);
1034 #endif // VC/!VC
1035
1036 if ( szMsg != NULL ) {
1037 wxStrcat(szBuf, _T(": "));
1038 wxStrcat(szBuf, szMsg);
1039 }
1040 else {
1041 wxStrcat(szBuf, _T("."));
1042 }
1043
1044 if ( !s_bNoAsserts ) {
1045 // send it to the normal log destination
1046 wxLogDebug(szBuf);
1047
1048 #if wxUSE_NOGUI
1049 Trap();
1050 #else
1051 // this message is intentionally not translated - it is for
1052 // developpers only
1053 wxStrcat(szBuf, _T("\nDo you want to stop the program?"
1054 "\nYou can also choose [Cancel] to suppress "
1055 "further warnings."));
1056
1057 switch ( wxMessageBox(szBuf, _("Debug"),
1058 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
1059 case wxYES:
1060 Trap();
1061 break;
1062
1063 case wxCANCEL:
1064 s_bNoAsserts = TRUE;
1065 break;
1066
1067 //case wxNO: nothing to do
1068 }
1069 #endif // USE_NOGUI
1070 }
1071
1072 s_bInAssert = FALSE;
1073 }
1074
1075 #endif //WXDEBUG
1076