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>
45 // other standard headers
56 // ----------------------------------------------------------------------------
57 // non member functions
58 // ----------------------------------------------------------------------------
60 // define this to enable wrapping of log messages
61 //#define LOG_PRETTY_WRAP
63 #ifdef LOG_PRETTY_WRAP
64 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
67 // ============================================================================
69 // ============================================================================
71 // ----------------------------------------------------------------------------
72 // implementation of Log functions
74 // NB: unfortunately we need all these distinct functions, we can't make them
75 // macros and not all compilers inline vararg functions.
76 // ----------------------------------------------------------------------------
78 // log functions can't allocate memory (LogError("out of memory...") should
79 // work!), so we use a static buffer for all log messages
80 #define LOG_BUFFER_SIZE (4096)
82 // static buffer for error messages (@@@ MT-unsafe)
83 static char s_szBuf
[LOG_BUFFER_SIZE
];
85 // generic log function
86 void wxLogGeneric(wxLogLevel level
, const char *szFormat
, ...)
88 if ( wxLog::GetActiveTarget() != NULL
) {
90 va_start(argptr
, szFormat
);
91 vsprintf(s_szBuf
, szFormat
, argptr
);
94 wxLog::OnLog(level
, s_szBuf
);
98 #define IMPLEMENT_LOG_FUNCTION(level) \
99 void wxLog##level(const char *szFormat, ...) \
101 if ( wxLog::GetActiveTarget() != NULL ) { \
103 va_start(argptr, szFormat); \
104 vsprintf(s_szBuf, szFormat, argptr); \
107 wxLog::OnLog(wxLOG_##level, s_szBuf); \
111 IMPLEMENT_LOG_FUNCTION(FatalError
)
112 IMPLEMENT_LOG_FUNCTION(Error
)
113 IMPLEMENT_LOG_FUNCTION(Warning
)
114 IMPLEMENT_LOG_FUNCTION(Message
)
115 IMPLEMENT_LOG_FUNCTION(Info
)
116 IMPLEMENT_LOG_FUNCTION(Status
)
118 // same as info, but only if 'verbose' mode is on
119 void wxLogVerbose(const char *szFormat
, ...)
121 wxLog
*pLog
= wxLog::GetActiveTarget();
122 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
124 va_start(argptr
, szFormat
);
125 vsprintf(s_szBuf
, szFormat
, argptr
);
128 wxLog::OnLog(wxLOG_Info
, s_szBuf
);
134 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
135 void wxLog##level(const char *szFormat, ...) \
137 if ( wxLog::GetActiveTarget() != NULL ) { \
139 va_start(argptr, szFormat); \
140 vsprintf(s_szBuf, szFormat, argptr); \
143 wxLog::OnLog(wxLOG_##level, s_szBuf); \
147 void wxLogTrace(wxTraceMask mask
, const char *szFormat
, ...)
149 wxLog
*pLog
= wxLog::GetActiveTarget();
151 // we check that all of mask bits are set in the current mask, so
152 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
153 // if both bits are set.
154 if ( pLog
!= NULL
&& (pLog
->GetTraceMask() & mask
== mask
) ) {
156 va_start(argptr
, szFormat
);
157 vsprintf(s_szBuf
, szFormat
, argptr
);
160 wxLog::OnLog(wxLOG_Trace
, s_szBuf
);
165 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
168 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
169 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
171 // wxLogSysError: one uses the last error code, for other you must give it
174 // common part of both wxLogSysError
175 void wxLogSysErrorHelper(long lErrCode
)
177 char szErrMsg
[LOG_BUFFER_SIZE
/ 2];
178 sprintf(szErrMsg
, _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
179 strncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - strlen(s_szBuf
));
181 wxLog::OnLog(wxLOG_Error
, s_szBuf
);
184 void WXDLLEXPORT
wxLogSysError(const char *szFormat
, ...)
187 va_start(argptr
, szFormat
);
188 vsprintf(s_szBuf
, szFormat
, argptr
);
191 wxLogSysErrorHelper(wxSysErrorCode());
194 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const char *szFormat
, ...)
197 va_start(argptr
, szFormat
);
198 vsprintf(s_szBuf
, szFormat
, argptr
);
201 wxLogSysErrorHelper(lErrCode
);
204 // ----------------------------------------------------------------------------
205 // wxLog class implementation
206 // ----------------------------------------------------------------------------
210 m_bHasMessages
= FALSE
;
212 m_szTimeFormat
= "[%d/%b/%y %H:%M:%S] ";
213 m_ulTraceMask
= (wxTraceMask
)0; // -1 to set all bits
216 wxLog
*wxLog::GetActiveTarget()
218 if ( !ms_bInitialized
) {
219 // prevent infinite recursion if someone calls wxLogXXX() from
220 // wxApp::CreateLogTarget()
221 ms_bInitialized
= TRUE
;
223 #ifdef WX_TEST_MINIMAL
224 ms_pLogger
= new wxLogStderr
;
226 // ask the application to create a log target for us
227 ms_pLogger
= wxTheApp
->CreateLogTarget();
230 // do nothing if it fails - what can we do?
236 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
238 // flush the old messages before changing
239 if ( ms_pLogger
!= NULL
)
242 ms_bInitialized
= TRUE
;
244 wxLog
*pOldLogger
= ms_pLogger
;
245 ms_pLogger
= pLogger
;
249 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
253 // prepend a timestamp if not disabled
254 if ( !IsEmpty(m_szTimeFormat
) ) {
260 ptmNow
= localtime(&timeNow
);
262 strftime(szBuf
, WXSIZEOF(szBuf
), m_szTimeFormat
, ptmNow
);
267 case wxLOG_FatalError
:
268 DoLogString(str
<< _("Fatal error: ") << szString
);
269 DoLogString(_("Program aborted."));
275 DoLogString(str
<< _("Error: ") << szString
);
279 DoLogString(str
<< _("Warning: ") << szString
);
285 DoLogString(str
+ szString
);
296 // in addition to normal logging, also send the string to debugger
297 // (don't prepend "Debug" here: it will go to debug window anyhow)
298 ::OutputDebugString(str
+ szString
+ "\n\r");
300 DoLogString(str
<< (level
== wxLOG_Trace
? _("Trace") : _("Debug"))
301 << ": " << szString
);
307 wxFAIL_MSG("unknown log level in wxLog::DoLog");
311 void wxLog::DoLogString(const char *WXUNUSED(szString
))
313 wxFAIL_MSG("DoLogString must be overrided if it's called.");
321 // ----------------------------------------------------------------------------
322 // wxLogStderr class implementation
323 // ----------------------------------------------------------------------------
325 wxLogStderr::wxLogStderr(FILE *fp
)
333 void wxLogStderr::DoLogString(const char *szString
)
335 fputs(szString
, m_fp
);
340 // ----------------------------------------------------------------------------
341 // wxLogStream implementation
342 // ----------------------------------------------------------------------------
344 wxLogStream::wxLogStream(ostream
*ostr
)
352 void wxLogStream::DoLogString(const char *szString
)
354 (*m_ostr
) << szString
<< endl
<< flush
;
357 // ----------------------------------------------------------------------------
358 // wxLogTextCtrl implementation
359 // ----------------------------------------------------------------------------
360 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
361 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
363 : wxLogStream(new ostream(pTextCtrl
))
368 wxLogTextCtrl::~wxLogTextCtrl()
375 // ----------------------------------------------------------------------------
376 // wxLogGui implementation
377 // ----------------------------------------------------------------------------
379 #ifndef WX_TEST_MINIMAL
386 void wxLogGui::Flush()
388 if ( !m_bHasMessages
)
393 // concatenate all strings (but not too many to not overfill the msg box)
396 nMsgCount
= m_aMessages
.Count();
398 // start from the most recent message
399 for ( uint n
= nMsgCount
; n
> 0; n
-- ) {
400 // for Windows strings longer than this value are wrapped (NT 4.0)
401 const uint nMsgLineWidth
= 156;
403 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
405 if ( nLines
> 25 ) // don't put too many lines in message box
408 str
<< m_aMessages
[n
- 1] << "\n";
412 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
415 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
418 // no undisplayed messages whatsoever
424 // the default behaviour is to discard all informational messages if there
425 // are any errors/warnings.
426 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
433 m_aMessages
.Add(szString
);
434 m_bHasMessages
= TRUE
;
440 // find the top window and set it's status text if it has any
441 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
442 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
443 wxFrame
*pFrame
= (wxFrame
*)pWin
;
444 pFrame
->SetStatusText(szString
);
453 OutputDebugString(szString
);
454 OutputDebugString("\n\r");
456 // send them to stderr
457 fprintf(stderr
, "%s: %s\n",
458 level
== wxLOG_Trace
? _("Trace") : _("Debug"), szString
);
464 case wxLOG_FatalError
:
465 // show this one immediately
466 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
471 // discard earlier informational messages if this is the 1st error
474 m_bHasMessages
= TRUE
;
478 m_aMessages
.Add(szString
);
482 wxFAIL_MSG("unknown log level in wxLogGui::DoLog");
486 // ----------------------------------------------------------------------------
487 // wxLogWindow implementation
488 // ----------------------------------------------------------------------------
491 class wxLogFrame
: public wxFrame
495 wxLogFrame(const char *szTitle
);
498 void OnClose(wxCommandEvent
& event
);
499 void OnCloseWindow(wxCloseEvent
& event
);
500 void OnSave (wxCommandEvent
& event
);
501 void OnClear(wxCommandEvent
& event
);
504 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
514 wxTextCtrl
*m_pTextCtrl
;
516 DECLARE_EVENT_TABLE()
519 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
520 // wxLogWindow menu events
521 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
522 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
523 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
525 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
528 wxLogFrame::wxLogFrame(const char *szTitle
)
529 : wxFrame(NULL
, -1, szTitle
)
531 // we don't want to be a top-level frame because it would prevent the
532 // application termination when all other frames are closed
533 wxTopLevelWindows
.DeleteObject(this);
535 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
536 // a rich edit control instead of a normal one we want
537 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
544 m_pTextCtrl->SetEditable(FALSE);
545 m_pTextCtrl->SetRichEdit(FALSE);
549 wxMenuBar
*pMenuBar
= new wxMenuBar
;
550 wxMenu
*pMenu
= new wxMenu
;
551 pMenu
->Append(Menu_Save
, "&Save...");
552 pMenu
->Append(Menu_Clear
, "C&lear");
553 pMenu
->AppendSeparator();
554 pMenu
->Append(Menu_Close
, "&Close");
555 pMenuBar
->Append(pMenu
, "&Log");
556 SetMenuBar(pMenuBar
);
558 // @@ what about status bar? needed (for menu prompts)?
561 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
563 // just hide the window
567 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
569 // just hide the window
573 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
577 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
578 if ( szFileName
== NULL
) {
587 if ( wxFile::Exists(szFileName
) ) {
588 bool bAppend
= FALSE
;
590 strMsg
.Printf(_("Append log to file '%s' "
591 "(choosing [No] will overwrite it)?"), szFileName
);
592 switch ( wxMessageBox(strMsg
, "Question", wxYES_NO
| wxCANCEL
) ) {
605 wxFAIL_MSG("invalid message box return value");
609 bOk
= file
.Open(szFileName
, wxFile::write_append
);
612 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
616 bOk
= file
.Create(szFileName
);
619 // retrieve text and save it
620 // -------------------------
622 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
623 wxLogError("Sorry, this function is not implemented under GTK");
625 int nLines
= m_pTextCtrl
->GetNumberOfLines();
626 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
627 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) + wxTextFile::GetEOL());
635 wxLogError(_("Can't save log contents to file."));
640 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
642 m_pTextCtrl
->Clear();
645 wxLogWindow::wxLogWindow(const char *szTitle
, bool bShow
)
647 m_pOldLog
= wxLog::GetActiveTarget();
648 m_pLogFrame
= new wxLogFrame(szTitle
);
651 m_pLogFrame
->Show(TRUE
);
654 void wxLogWindow::Show(bool bShow
)
656 m_pLogFrame
->Show(bShow
);
659 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
661 // first let the previous logger show it
662 if ( m_pOldLog
!= NULL
) {
663 // @@@ why can't we access protected wxLog method from here (we derive
664 // from wxLog)? gcc gives "DoLog is protected in this context", what
665 // does this mean? Anyhow, the cast is harmless and let's us do what
667 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
670 // and this will format it nicely and call our DoLogString()
671 wxLog::DoLog(level
, szString
);
674 void wxLogWindow::DoLogString(const char *szString
)
676 // put the text into our window
677 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
679 // remove selection (WriteText is in fact ReplaceSelection)
681 long nLen
= pText
->GetLastPosition();
682 pText
->SetSelection(nLen
, nLen
);
685 pText
->WriteText(szString
);
686 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
688 // ensure that the line can be seen
692 wxLogWindow::~wxLogWindow()
694 m_pLogFrame
->Close(TRUE
);
697 #endif //WX_TEST_MINIMAL
699 // ============================================================================
700 // Global functions/variables
701 // ============================================================================
703 // ----------------------------------------------------------------------------
705 // ----------------------------------------------------------------------------
706 wxLog
*wxLog::ms_pLogger
= NULL
;
707 bool wxLog::ms_bInitialized
= FALSE
;
709 // ----------------------------------------------------------------------------
710 // stdout error logging helper
711 // ----------------------------------------------------------------------------
713 // helper function: wraps the message and justifies it under given position
714 // (looks more pretty on the terminal). Also adds newline at the end.
716 // @@ this is now disabled until I find a portable way of determining the
717 // terminal window size (ok, I found it but does anybody really cares?)
718 #ifdef LOG_PRETTY_WRAP
719 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
721 size_t nMax
= 80; // @@@@
722 size_t nStart
= strlen(pszPrefix
);
726 while ( *psz
!= '\0' ) {
727 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
731 if ( *psz
!= '\0' ) {
733 for ( n
= 0; n
< nStart
; n
++ )
736 // as we wrapped, squeeze all white space
737 while ( isspace(*psz
) )
744 #endif //LOG_PRETTY_WRAP
746 // ----------------------------------------------------------------------------
747 // error code/error message retrieval functions
748 // ----------------------------------------------------------------------------
750 // get error code from syste
751 unsigned long wxSysErrorCode()
755 return ::GetLastError();
757 // @@@@ what to do on Windows 3.1?
765 // get error message from system
766 const char *wxSysErrorMsg(unsigned long nErrCode
)
769 nErrCode
= wxSysErrorCode();
773 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
775 // get error message from system
777 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
779 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
783 // copy it to our buffer and free memory
784 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
785 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
788 // returned string is capitalized and ended with '\r\n' - bad
789 s_szBuf
[0] = (char)tolower(s_szBuf
[0]);
790 size_t len
= strlen(s_szBuf
);
793 if ( s_szBuf
[len
- 2] == '\r' )
794 s_szBuf
[len
- 2] = '\0';
803 return strerror(nErrCode
);
807 // ----------------------------------------------------------------------------
809 // ----------------------------------------------------------------------------
822 // this function is called when an assert fails
823 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
825 // this variable can be set to true to suppress "assert failure" messages
826 static bool s_bNoAsserts
= FALSE
;
827 static bool s_bInAssert
= FALSE
;
830 // He-e-e-e-elp!! we're trapped in endless loop
836 char szBuf
[LOG_BUFFER_SIZE
];
837 sprintf(szBuf
, _("Assert failed in file %s at line %d"), szFile
, nLine
);
838 if ( szMsg
!= NULL
) {
840 strcat(szBuf
, szMsg
);
846 if ( !s_bNoAsserts
) {
847 // send it to the normal log destination
850 strcat(szBuf
, _("\nDo you want to stop the program?"
851 "\nYou can also choose [Cancel] to suppress "
852 "further warnings."));
854 switch ( wxMessageBox(szBuf
, _("Debug"),
855 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
864 //case wxNO: nothing to do