1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #pragma implementation "log.h"
23 // For compilers that support precompilation, includes "wx.h".
24 #include "wx/wxprec.h"
33 #include <wx/string.h>
36 #include <wx/generic/msgdlgg.h>
37 #include <wx/filedlg.h>
38 #include <wx/textctrl.h>
42 #include <wx/textfile.h>
46 // other standard headers
57 // ----------------------------------------------------------------------------
58 // non member functions
59 // ----------------------------------------------------------------------------
61 // define this to enable wrapping of log messages
62 //#define LOG_PRETTY_WRAP
64 #ifdef LOG_PRETTY_WRAP
65 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
68 // ============================================================================
70 // ============================================================================
72 // ----------------------------------------------------------------------------
73 // implementation of Log functions
75 // NB: unfortunately we need all these distinct functions, we can't make them
76 // macros and not all compilers inline vararg functions.
77 // ----------------------------------------------------------------------------
79 // log functions can't allocate memory (LogError("out of memory...") should
80 // work!), so we use a static buffer for all log messages
81 #define LOG_BUFFER_SIZE (4096)
83 // static buffer for error messages (@@@ MT-unsafe)
84 static char s_szBuf
[LOG_BUFFER_SIZE
];
86 // generic log function
87 void wxLogGeneric(wxLogLevel level
, const char *szFormat
, ...)
89 if ( wxLog::GetActiveTarget() != NULL
) {
91 va_start(argptr
, szFormat
);
92 vsprintf(s_szBuf
, szFormat
, argptr
);
95 wxLog::OnLog(level
, s_szBuf
);
99 #define IMPLEMENT_LOG_FUNCTION(level) \
100 void wxLog##level(const char *szFormat, ...) \
102 if ( wxLog::GetActiveTarget() != NULL ) { \
104 va_start(argptr, szFormat); \
105 vsprintf(s_szBuf, szFormat, argptr); \
108 wxLog::OnLog(wxLOG_##level, s_szBuf); \
112 IMPLEMENT_LOG_FUNCTION(FatalError
)
113 IMPLEMENT_LOG_FUNCTION(Error
)
114 IMPLEMENT_LOG_FUNCTION(Warning
)
115 IMPLEMENT_LOG_FUNCTION(Message
)
116 IMPLEMENT_LOG_FUNCTION(Info
)
117 IMPLEMENT_LOG_FUNCTION(Status
)
119 // same as info, but only if 'verbose' mode is on
120 void wxLogVerbose(const char *szFormat
, ...)
122 wxLog
*pLog
= wxLog::GetActiveTarget();
123 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
125 va_start(argptr
, szFormat
);
126 vsprintf(s_szBuf
, szFormat
, argptr
);
129 wxLog::OnLog(wxLOG_Info
, s_szBuf
);
135 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
136 void wxLog##level(const char *szFormat, ...) \
138 if ( wxLog::GetActiveTarget() != NULL ) { \
140 va_start(argptr, szFormat); \
141 vsprintf(s_szBuf, szFormat, argptr); \
144 wxLog::OnLog(wxLOG_##level, s_szBuf); \
148 void wxLogTrace(wxTraceMask mask
, const char *szFormat
, ...)
150 wxLog
*pLog
= wxLog::GetActiveTarget();
152 // we check that all of mask bits are set in the current mask, so
153 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
154 // if both bits are set.
155 if ( pLog
!= NULL
&& (pLog
->GetTraceMask() & mask
== mask
) ) {
157 va_start(argptr
, szFormat
);
158 vsprintf(s_szBuf
, szFormat
, argptr
);
161 wxLog::OnLog(wxLOG_Trace
, s_szBuf
);
166 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
169 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
170 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
172 // wxLogSysError: one uses the last error code, for other you must give it
175 // common part of both wxLogSysError
176 void wxLogSysErrorHelper(long lErrCode
)
178 char szErrMsg
[LOG_BUFFER_SIZE
/ 2];
179 sprintf(szErrMsg
, _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
180 strncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - strlen(s_szBuf
));
182 wxLog::OnLog(wxLOG_Error
, s_szBuf
);
185 void WXDLLEXPORT
wxLogSysError(const char *szFormat
, ...)
188 va_start(argptr
, szFormat
);
189 vsprintf(s_szBuf
, szFormat
, argptr
);
192 wxLogSysErrorHelper(wxSysErrorCode());
195 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const char *szFormat
, ...)
198 va_start(argptr
, szFormat
);
199 vsprintf(s_szBuf
, szFormat
, argptr
);
202 wxLogSysErrorHelper(lErrCode
);
205 // ----------------------------------------------------------------------------
206 // wxLog class implementation
207 // ----------------------------------------------------------------------------
211 m_bHasMessages
= FALSE
;
213 m_szTimeFormat
= "[%d/%b/%y %H:%M:%S] ";
214 m_ulTraceMask
= (wxTraceMask
)0; // -1 to set all bits
217 wxLog
*wxLog::GetActiveTarget()
219 if ( !ms_bInitialized
) {
220 // prevent infinite recursion if someone calls wxLogXXX() from
221 // wxApp::CreateLogTarget()
222 ms_bInitialized
= TRUE
;
224 #ifdef WX_TEST_MINIMAL
225 ms_pLogger
= new wxLogStderr
;
227 // ask the application to create a log target for us
228 ms_pLogger
= wxTheApp
->CreateLogTarget();
231 // do nothing if it fails - what can we do?
237 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
239 // flush the old messages before changing
240 if ( ms_pLogger
!= NULL
)
243 ms_bInitialized
= TRUE
;
245 wxLog
*pOldLogger
= ms_pLogger
;
246 ms_pLogger
= pLogger
;
250 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
254 // prepend a timestamp if not disabled
255 if ( !IsEmpty(m_szTimeFormat
) ) {
261 ptmNow
= localtime(&timeNow
);
263 strftime(szBuf
, WXSIZEOF(szBuf
), m_szTimeFormat
, ptmNow
);
268 case wxLOG_FatalError
:
269 DoLogString(str
<< _("Fatal error: ") << szString
);
270 DoLogString(_("Program aborted."));
276 DoLogString(str
<< _("Error: ") << szString
);
280 DoLogString(str
<< _("Warning: ") << szString
);
286 DoLogString(str
+ szString
);
297 // in addition to normal logging, also send the string to debugger
298 // (don't prepend "Debug" here: it will go to debug window anyhow)
299 ::OutputDebugString(str
+ szString
+ "\n\r");
301 DoLogString(str
<< (level
== wxLOG_Trace
? _("Trace") : _("Debug"))
302 << ": " << szString
);
308 wxFAIL_MSG("unknown log level in wxLog::DoLog");
312 void wxLog::DoLogString(const char *WXUNUSED(szString
))
314 wxFAIL_MSG("DoLogString must be overrided if it's called.");
322 // ----------------------------------------------------------------------------
323 // wxLogStderr class implementation
324 // ----------------------------------------------------------------------------
326 wxLogStderr::wxLogStderr(FILE *fp
)
334 void wxLogStderr::DoLogString(const char *szString
)
336 fputs(szString
, m_fp
);
341 // ----------------------------------------------------------------------------
342 // wxLogStream implementation
343 // ----------------------------------------------------------------------------
345 wxLogStream::wxLogStream(ostream
*ostr
)
353 void wxLogStream::DoLogString(const char *szString
)
355 (*m_ostr
) << szString
<< endl
<< flush
;
358 // ----------------------------------------------------------------------------
359 // wxLogTextCtrl implementation
360 // ----------------------------------------------------------------------------
361 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
362 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
364 : wxLogStream(new ostream(pTextCtrl
))
369 wxLogTextCtrl::~wxLogTextCtrl()
376 // ----------------------------------------------------------------------------
377 // wxLogGui implementation
378 // ----------------------------------------------------------------------------
380 #ifndef WX_TEST_MINIMAL
387 void wxLogGui::Flush()
389 if ( !m_bHasMessages
)
394 // concatenate all strings (but not too many to not overfill the msg box)
397 nMsgCount
= m_aMessages
.Count();
399 // start from the most recent message
400 for ( uint n
= nMsgCount
; n
> 0; n
-- ) {
401 // for Windows strings longer than this value are wrapped (NT 4.0)
402 const uint nMsgLineWidth
= 156;
404 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
406 if ( nLines
> 25 ) // don't put too many lines in message box
409 str
<< m_aMessages
[n
- 1] << "\n";
413 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
416 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
419 // no undisplayed messages whatsoever
425 // the default behaviour is to discard all informational messages if there
426 // are any errors/warnings.
427 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
434 m_aMessages
.Add(szString
);
435 m_bHasMessages
= TRUE
;
441 // find the top window and set it's status text if it has any
442 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
443 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
444 wxFrame
*pFrame
= (wxFrame
*)pWin
;
445 pFrame
->SetStatusText(szString
);
454 OutputDebugString(szString
);
455 OutputDebugString("\n\r");
457 // send them to stderr
458 fprintf(stderr
, "%s: %s\n",
459 level
== wxLOG_Trace
? _("Trace") : _("Debug"), szString
);
465 case wxLOG_FatalError
:
466 // show this one immediately
467 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
472 // discard earlier informational messages if this is the 1st error
475 m_bHasMessages
= TRUE
;
479 m_aMessages
.Add(szString
);
483 wxFAIL_MSG("unknown log level in wxLogGui::DoLog");
487 // ----------------------------------------------------------------------------
488 // wxLogWindow implementation
489 // ----------------------------------------------------------------------------
492 class wxLogFrame
: public wxFrame
496 wxLogFrame(const char *szTitle
);
499 void OnClose(wxCommandEvent
& event
);
500 void OnCloseWindow(wxCloseEvent
& event
);
501 void OnSave (wxCommandEvent
& event
);
502 void OnClear(wxCommandEvent
& event
);
505 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
515 wxTextCtrl
*m_pTextCtrl
;
517 DECLARE_EVENT_TABLE()
520 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
521 // wxLogWindow menu events
522 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
523 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
524 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
526 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
529 wxLogFrame::wxLogFrame(const char *szTitle
)
530 : wxFrame(NULL
, -1, szTitle
)
532 // we don't want to be a top-level frame because it would prevent the
533 // application termination when all other frames are closed
534 wxTopLevelWindows
.DeleteObject(this);
536 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
537 // a rich edit control instead of a normal one we want
538 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
545 m_pTextCtrl->SetEditable(FALSE);
546 m_pTextCtrl->SetRichEdit(FALSE);
550 wxMenuBar
*pMenuBar
= new wxMenuBar
;
551 wxMenu
*pMenu
= new wxMenu
;
552 pMenu
->Append(Menu_Save
, "&Save...");
553 pMenu
->Append(Menu_Clear
, "C&lear");
554 pMenu
->AppendSeparator();
555 pMenu
->Append(Menu_Close
, "&Close");
556 pMenuBar
->Append(pMenu
, "&Log");
557 SetMenuBar(pMenuBar
);
559 // @@ what about status bar? needed (for menu prompts)?
562 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
564 // just hide the window
568 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
570 // just hide the window
574 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
578 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
579 if ( szFileName
== NULL
) {
588 if ( wxFile::Exists(szFileName
) ) {
589 bool bAppend
= FALSE
;
591 strMsg
.Printf(_("Append log to file '%s' "
592 "(choosing [No] will overwrite it)?"), szFileName
);
593 switch ( wxMessageBox(strMsg
, "Question", wxYES_NO
| wxCANCEL
) ) {
606 wxFAIL_MSG("invalid message box return value");
610 bOk
= file
.Open(szFileName
, wxFile::write_append
);
613 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
617 bOk
= file
.Create(szFileName
);
620 // retrieve text and save it
621 // -------------------------
623 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
624 wxLogError("Sorry, this function is not implemented under GTK");
626 int nLines
= m_pTextCtrl
->GetNumberOfLines();
627 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
628 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) + wxTextFile::GetEOL());
636 wxLogError(_("Can't save log contents to file."));
641 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
643 m_pTextCtrl
->Clear();
646 wxLogWindow::wxLogWindow(const char *szTitle
, bool bShow
)
648 m_pOldLog
= wxLog::GetActiveTarget();
649 m_pLogFrame
= new wxLogFrame(szTitle
);
652 m_pLogFrame
->Show(TRUE
);
655 void wxLogWindow::Show(bool bShow
)
657 m_pLogFrame
->Show(bShow
);
660 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
662 // first let the previous logger show it
663 if ( m_pOldLog
!= NULL
) {
664 // @@@ why can't we access protected wxLog method from here (we derive
665 // from wxLog)? gcc gives "DoLog is protected in this context", what
666 // does this mean? Anyhow, the cast is harmless and let's us do what
668 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
671 // and this will format it nicely and call our DoLogString()
672 wxLog::DoLog(level
, szString
);
675 void wxLogWindow::DoLogString(const char *szString
)
677 // put the text into our window
678 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
680 // remove selection (WriteText is in fact ReplaceSelection)
682 long nLen
= pText
->GetLastPosition();
683 pText
->SetSelection(nLen
, nLen
);
686 pText
->WriteText(szString
);
687 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
689 // ensure that the line can be seen
693 wxLogWindow::~wxLogWindow()
695 m_pLogFrame
->Close(TRUE
);
698 #endif //WX_TEST_MINIMAL
700 // ============================================================================
701 // Global functions/variables
702 // ============================================================================
704 // ----------------------------------------------------------------------------
706 // ----------------------------------------------------------------------------
707 wxLog
*wxLog::ms_pLogger
= NULL
;
708 bool wxLog::ms_bInitialized
= FALSE
;
710 // ----------------------------------------------------------------------------
711 // stdout error logging helper
712 // ----------------------------------------------------------------------------
714 // helper function: wraps the message and justifies it under given position
715 // (looks more pretty on the terminal). Also adds newline at the end.
717 // @@ this is now disabled until I find a portable way of determining the
718 // terminal window size (ok, I found it but does anybody really cares?)
719 #ifdef LOG_PRETTY_WRAP
720 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
722 size_t nMax
= 80; // @@@@
723 size_t nStart
= strlen(pszPrefix
);
727 while ( *psz
!= '\0' ) {
728 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
732 if ( *psz
!= '\0' ) {
734 for ( n
= 0; n
< nStart
; n
++ )
737 // as we wrapped, squeeze all white space
738 while ( isspace(*psz
) )
745 #endif //LOG_PRETTY_WRAP
747 // ----------------------------------------------------------------------------
748 // error code/error message retrieval functions
749 // ----------------------------------------------------------------------------
751 // get error code from syste
752 unsigned long wxSysErrorCode()
756 return ::GetLastError();
758 // @@@@ what to do on Windows 3.1?
766 // get error message from system
767 const char *wxSysErrorMsg(unsigned long nErrCode
)
770 nErrCode
= wxSysErrorCode();
774 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
776 // get error message from system
778 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
780 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
784 // copy it to our buffer and free memory
785 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
786 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
789 // returned string is capitalized and ended with '\r\n' - bad
790 s_szBuf
[0] = (char)wxToLower(s_szBuf
[0]);
791 size_t len
= strlen(s_szBuf
);
794 if ( s_szBuf
[len
- 2] == '\r' )
795 s_szBuf
[len
- 2] = '\0';
804 return strerror(nErrCode
);
808 // ----------------------------------------------------------------------------
810 // ----------------------------------------------------------------------------
823 // this function is called when an assert fails
824 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
826 // this variable can be set to true to suppress "assert failure" messages
827 static bool s_bNoAsserts
= FALSE
;
828 static bool s_bInAssert
= FALSE
;
831 // He-e-e-e-elp!! we're trapped in endless loop
837 char szBuf
[LOG_BUFFER_SIZE
];
838 sprintf(szBuf
, _("Assert failed in file %s at line %d"), szFile
, nLine
);
839 if ( szMsg
!= NULL
) {
841 strcat(szBuf
, szMsg
);
847 if ( !s_bNoAsserts
) {
848 // send it to the normal log destination
851 strcat(szBuf
, _("\nDo you want to stop the program?"
852 "\nYou can also choose [Cancel] to suppress "
853 "further warnings."));
855 switch ( wxMessageBox(szBuf
, _("Debug"),
856 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
865 //case wxNO: nothing to do