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>
37 #include <wx/generic/msgdlgg.h>
38 #include <wx/filedlg.h>
39 #include <wx/textctrl.h>
43 #include <wx/textfile.h>
47 // other standard headers
58 // ----------------------------------------------------------------------------
59 // non member functions
60 // ----------------------------------------------------------------------------
62 // define this to enable wrapping of log messages
63 //#define LOG_PRETTY_WRAP
65 #ifdef LOG_PRETTY_WRAP
66 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
69 // ============================================================================
71 // ============================================================================
73 // ----------------------------------------------------------------------------
74 // implementation of Log functions
76 // NB: unfortunately we need all these distinct functions, we can't make them
77 // macros and not all compilers inline vararg functions.
78 // ----------------------------------------------------------------------------
80 // log functions can't allocate memory (LogError("out of memory...") should
81 // work!), so we use a static buffer for all log messages
82 #define LOG_BUFFER_SIZE (4096)
84 // static buffer for error messages (@@@ MT-unsafe)
85 static char s_szBuf
[LOG_BUFFER_SIZE
];
87 // generic log function
88 void wxLogGeneric(wxLogLevel level
, const char *szFormat
, ...)
90 if ( wxLog::GetActiveTarget() != NULL
) {
92 va_start(argptr
, szFormat
);
93 vsprintf(s_szBuf
, szFormat
, argptr
);
96 wxLog::OnLog(level
, s_szBuf
);
100 #define IMPLEMENT_LOG_FUNCTION(level) \
101 void wxLog##level(const char *szFormat, ...) \
103 if ( wxLog::GetActiveTarget() != NULL ) { \
105 va_start(argptr, szFormat); \
106 vsprintf(s_szBuf, szFormat, argptr); \
109 wxLog::OnLog(wxLOG_##level, s_szBuf); \
113 IMPLEMENT_LOG_FUNCTION(FatalError
)
114 IMPLEMENT_LOG_FUNCTION(Error
)
115 IMPLEMENT_LOG_FUNCTION(Warning
)
116 IMPLEMENT_LOG_FUNCTION(Message
)
117 IMPLEMENT_LOG_FUNCTION(Info
)
118 IMPLEMENT_LOG_FUNCTION(Status
)
120 // same as info, but only if 'verbose' mode is on
121 void wxLogVerbose(const char *szFormat
, ...)
123 wxLog
*pLog
= wxLog::GetActiveTarget();
124 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
126 va_start(argptr
, szFormat
);
127 vsprintf(s_szBuf
, szFormat
, argptr
);
130 wxLog::OnLog(wxLOG_Info
, s_szBuf
);
136 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
137 void wxLog##level(const char *szFormat, ...) \
139 if ( wxLog::GetActiveTarget() != NULL ) { \
141 va_start(argptr, szFormat); \
142 vsprintf(s_szBuf, szFormat, argptr); \
145 wxLog::OnLog(wxLOG_##level, s_szBuf); \
149 void wxLogTrace(wxTraceMask mask
, const char *szFormat
, ...)
151 wxLog
*pLog
= wxLog::GetActiveTarget();
153 // we check that all of mask bits are set in the current mask, so
154 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
155 // if both bits are set.
156 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
158 va_start(argptr
, szFormat
);
159 vsprintf(s_szBuf
, szFormat
, argptr
);
162 wxLog::OnLog(wxLOG_Trace
, s_szBuf
);
167 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
170 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
171 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
173 // wxLogSysError: one uses the last error code, for other you must give it
176 // common part of both wxLogSysError
177 void wxLogSysErrorHelper(long lErrCode
)
179 char szErrMsg
[LOG_BUFFER_SIZE
/ 2];
180 sprintf(szErrMsg
, _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
181 strncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - strlen(s_szBuf
));
183 wxLog::OnLog(wxLOG_Error
, s_szBuf
);
186 void WXDLLEXPORT
wxLogSysError(const char *szFormat
, ...)
189 va_start(argptr
, szFormat
);
190 vsprintf(s_szBuf
, szFormat
, argptr
);
193 wxLogSysErrorHelper(wxSysErrorCode());
196 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const char *szFormat
, ...)
199 va_start(argptr
, szFormat
);
200 vsprintf(s_szBuf
, szFormat
, argptr
);
203 wxLogSysErrorHelper(lErrCode
);
206 // ----------------------------------------------------------------------------
207 // wxLog class implementation
208 // ----------------------------------------------------------------------------
212 m_bHasMessages
= FALSE
;
214 m_szTimeFormat
= "[%d/%b/%y %H:%M:%S] ";
217 wxLog
*wxLog::GetActiveTarget()
219 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
220 // prevent infinite recursion if someone calls wxLogXXX() from
221 // wxApp::CreateLogTarget()
222 static bool s_bInGetActiveTarget
= FALSE
;
223 if ( !s_bInGetActiveTarget
) {
224 s_bInGetActiveTarget
= TRUE
;
226 #ifdef WX_TEST_MINIMAL
227 ms_pLogger
= new wxLogStderr
;
229 // ask the application to create a log target for us
230 if ( wxTheApp
!= NULL
)
231 ms_pLogger
= wxTheApp
->CreateLogTarget();
234 // do nothing if it fails - what can we do?
241 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
243 // flush the old messages before changing
244 if ( ms_pLogger
!= NULL
)
247 wxLog
*pOldLogger
= ms_pLogger
;
248 ms_pLogger
= pLogger
;
252 wxString
wxLog::TimeStamp() const
256 if ( !IsEmpty(m_szTimeFormat
) ) {
262 ptmNow
= localtime(&timeNow
);
264 strftime(szBuf
, WXSIZEOF(szBuf
), m_szTimeFormat
, ptmNow
);
271 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
273 // prepend a timestamp if not disabled
274 wxString str
= TimeStamp();
277 case wxLOG_FatalError
:
278 DoLogString(str
<< _("Fatal error: ") << szString
);
279 DoLogString(_("Program aborted."));
285 DoLogString(str
<< _("Error: ") << szString
);
289 DoLogString(str
<< _("Warning: ") << szString
);
295 DoLogString(str
+ szString
);
305 DoLogString(str
<< (level
== wxLOG_Trace
? _("Trace") : _("Debug"))
306 << ": " << szString
);
312 wxFAIL_MSG(_("unknown log level in wxLog::DoLog"));
316 void wxLog::DoLogString(const char *WXUNUSED(szString
))
318 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
326 // ----------------------------------------------------------------------------
327 // wxLogStderr class implementation
328 // ----------------------------------------------------------------------------
330 wxLogStderr::wxLogStderr(FILE *fp
)
338 void wxLogStderr::DoLogString(const char *szString
)
340 fputs(szString
, m_fp
);
345 // ----------------------------------------------------------------------------
346 // wxLogStream implementation
347 // ----------------------------------------------------------------------------
349 wxLogStream::wxLogStream(ostream
*ostr
)
357 void wxLogStream::DoLogString(const char *szString
)
359 (*m_ostr
) << szString
<< endl
<< flush
;
362 // ----------------------------------------------------------------------------
363 // wxLogTextCtrl implementation
364 // ----------------------------------------------------------------------------
365 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
366 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
368 // Also, in DLL mode in wxMSW, can't use it.
369 #if defined(NO_TEXT_WINDOW_STREAM)
371 : wxLogStream(new ostream(pTextCtrl
))
376 wxLogTextCtrl::~wxLogTextCtrl()
381 // ----------------------------------------------------------------------------
382 // wxLogGui implementation
383 // ----------------------------------------------------------------------------
385 #ifndef WX_TEST_MINIMAL
392 void wxLogGui::Flush()
394 if ( !m_bHasMessages
)
399 // concatenate all strings (but not too many to not overfill the msg box)
402 nMsgCount
= m_aMessages
.Count();
404 // start from the most recent message
405 for ( uint n
= nMsgCount
; n
> 0; n
-- ) {
406 // for Windows strings longer than this value are wrapped (NT 4.0)
407 const uint nMsgLineWidth
= 156;
409 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
411 if ( nLines
> 25 ) // don't put too many lines in message box
414 str
<< m_aMessages
[n
- 1] << "\n";
418 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
421 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
424 // no undisplayed messages whatsoever
430 // the default behaviour is to discard all informational messages if there
431 // are any errors/warnings.
432 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
439 m_aMessages
.Add(szString
);
440 m_bHasMessages
= TRUE
;
446 // find the top window and set it's status text if it has any
447 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
448 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
449 wxFrame
*pFrame
= (wxFrame
*)pWin
;
450 pFrame
->SetStatusText(szString
);
459 wxString strTime
= TimeStamp();
462 // don't prepend debug/trace here: it goes to the debug window
463 // anyhow, but do put a timestamp
464 OutputDebugString(strTime
+ szString
+ "\n\r");
466 // send them to stderr
467 fprintf(stderr
, "%s %s: %s\n",
469 level
== wxLOG_Trace
? _("Trace") : _("Debug"),
477 case wxLOG_FatalError
:
478 // show this one immediately
479 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
484 // discard earlier informational messages if this is the 1st error
487 m_bHasMessages
= TRUE
;
491 m_aMessages
.Add(szString
);
495 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
499 // ----------------------------------------------------------------------------
500 // wxLogWindow and wxLogFrame implementation
501 // ----------------------------------------------------------------------------
505 class wxLogFrame
: public wxFrame
509 wxLogFrame(wxLogWindow
*log
, const char *szTitle
);
510 virtual ~wxLogFrame();
513 void OnClose(wxCommandEvent
& event
);
514 void OnCloseWindow(wxCloseEvent
& event
);
515 void OnSave (wxCommandEvent
& event
);
516 void OnClear(wxCommandEvent
& event
);
518 void OnIdle(wxIdleEvent
&);
521 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
531 // instead of closing just hide the window to be able to Show() it later
532 void DoClose() { Show(FALSE
); }
534 wxTextCtrl
*m_pTextCtrl
;
537 DECLARE_EVENT_TABLE()
540 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
541 // wxLogWindow menu events
542 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
543 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
544 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
546 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
548 EVT_IDLE(wxLogFrame::OnIdle
)
551 wxLogFrame::wxLogFrame(wxLogWindow
*log
, const char *szTitle
)
552 : wxFrame(NULL
, -1, szTitle
)
556 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
557 // a rich edit control instead of a normal one we want in wxMSW
558 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
565 m_pTextCtrl->SetEditable(FALSE);
566 m_pTextCtrl->SetRichEdit(FALSE);
570 wxMenuBar
*pMenuBar
= new wxMenuBar
;
571 wxMenu
*pMenu
= new wxMenu
;
572 pMenu
->Append(Menu_Save
, _("&Save..."), _("Save log contents to file"));
573 pMenu
->Append(Menu_Clear
, _("C&lear"), _("Clear the log contents"));
574 pMenu
->AppendSeparator();
575 pMenu
->Append(Menu_Close
, _("&Close"), _("Close this window"));
576 pMenuBar
->Append(pMenu
, _("&Log"));
577 SetMenuBar(pMenuBar
);
579 // status bar for menu prompts
582 m_log
->OnFrameCreate(this);
585 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
590 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
595 void wxLogFrame::OnIdle(wxIdleEvent
& WXUNUSED(event
))
597 // if we're the last frame to stay, delete log frame letting the
598 // application to close
599 if ( wxTopLevelWindows
.Number() == 1 )
603 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
607 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
608 if ( szFileName
== NULL
) {
617 if ( wxFile::Exists(szFileName
) ) {
618 bool bAppend
= FALSE
;
620 strMsg
.Printf(_("Append log to file '%s' "
621 "(choosing [No] will overwrite it)?"), szFileName
);
622 switch ( wxMessageBox(strMsg
, _("Question"), wxYES_NO
| wxCANCEL
) ) {
635 wxFAIL_MSG(_("invalid message box return value"));
639 bOk
= file
.Open(szFileName
, wxFile::write_append
);
642 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
646 bOk
= file
.Create(szFileName
);
649 // retrieve text and save it
650 // -------------------------
652 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
653 wxLogError(_("Sorry, this function is not implemented under GTK"));
655 int nLines
= m_pTextCtrl
->GetNumberOfLines();
656 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
657 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) + wxTextFile::GetEOL());
665 wxLogError(_("Can't save log contents to file."));
670 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
672 m_pTextCtrl
->Clear();
675 wxLogFrame::~wxLogFrame()
677 m_log
->OnFrameDelete(this);
682 wxLogWindow::wxLogWindow(const char *szTitle
, bool bShow
, bool bDoPass
)
684 m_bPassMessages
= bDoPass
;
686 m_pLogFrame
= new wxLogFrame(this, szTitle
);
687 m_pOldLog
= wxLog::SetActiveTarget(this);
690 m_pLogFrame
->Show(TRUE
);
693 void wxLogWindow::Show(bool bShow
)
695 m_pLogFrame
->Show(bShow
);
698 void wxLogWindow::Flush()
700 if ( m_pOldLog
!= NULL
)
703 m_bHasMessages
= FALSE
;
706 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
708 // first let the previous logger show it
709 if ( m_pOldLog
!= NULL
&& m_bPassMessages
) {
710 // @@@ why can't we access protected wxLog method from here (we derive
711 // from wxLog)? gcc gives "DoLog is protected in this context", what
712 // does this mean? Anyhow, the cast is harmless and let's us do what
714 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
717 // and this will format it nicely and call our DoLogString()
718 wxLog::DoLog(level
, szString
);
720 m_bHasMessages
= TRUE
;
723 void wxLogWindow::DoLogString(const char *szString
)
725 // put the text into our window
726 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
728 // remove selection (WriteText is in fact ReplaceSelection)
730 long nLen
= pText
->GetLastPosition();
731 pText
->SetSelection(nLen
, nLen
);
734 pText
->WriteText(szString
);
735 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
737 // ensure that the line can be seen
741 wxFrame
*wxLogWindow::GetFrame() const
746 void wxLogWindow::OnFrameCreate(wxFrame
*frame
)
750 void wxLogWindow::OnFrameDelete(wxFrame
*frame
)
755 wxLogWindow::~wxLogWindow()
757 // may be NULL if log frame already auto destroyed itself
760 // delete the old log
764 #endif //WX_TEST_MINIMAL
766 // ============================================================================
767 // Global functions/variables
768 // ============================================================================
770 // ----------------------------------------------------------------------------
772 // ----------------------------------------------------------------------------
773 wxLog
*wxLog::ms_pLogger
= NULL
;
774 bool wxLog::ms_bAutoCreate
= TRUE
;
775 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
777 // ----------------------------------------------------------------------------
778 // stdout error logging helper
779 // ----------------------------------------------------------------------------
781 // helper function: wraps the message and justifies it under given position
782 // (looks more pretty on the terminal). Also adds newline at the end.
784 // @@ this is now disabled until I find a portable way of determining the
785 // terminal window size (ok, I found it but does anybody really cares?)
786 #ifdef LOG_PRETTY_WRAP
787 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
789 size_t nMax
= 80; // @@@@
790 size_t nStart
= strlen(pszPrefix
);
794 while ( *psz
!= '\0' ) {
795 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
799 if ( *psz
!= '\0' ) {
801 for ( n
= 0; n
< nStart
; n
++ )
804 // as we wrapped, squeeze all white space
805 while ( isspace(*psz
) )
812 #endif //LOG_PRETTY_WRAP
814 // ----------------------------------------------------------------------------
815 // error code/error message retrieval functions
816 // ----------------------------------------------------------------------------
818 // get error code from syste
819 unsigned long wxSysErrorCode()
823 return ::GetLastError();
825 // @@@@ what to do on Windows 3.1?
833 // get error message from system
834 const char *wxSysErrorMsg(unsigned long nErrCode
)
837 nErrCode
= wxSysErrorCode();
841 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
843 // get error message from system
845 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
847 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
851 // copy it to our buffer and free memory
852 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
853 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
856 // returned string is capitalized and ended with '\r\n' - bad
857 s_szBuf
[0] = (char)wxToLower(s_szBuf
[0]);
858 size_t len
= strlen(s_szBuf
);
861 if ( s_szBuf
[len
- 2] == '\r' )
862 s_szBuf
[len
- 2] = '\0';
871 return strerror(nErrCode
);
875 // ----------------------------------------------------------------------------
877 // ----------------------------------------------------------------------------
890 // this function is called when an assert fails
891 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
893 // this variable can be set to true to suppress "assert failure" messages
894 static bool s_bNoAsserts
= FALSE
;
895 static bool s_bInAssert
= FALSE
;
898 // He-e-e-e-elp!! we're trapped in endless loop
904 char szBuf
[LOG_BUFFER_SIZE
];
905 sprintf(szBuf
, _("Assert failed in file %s at line %d"), szFile
, nLine
);
906 if ( szMsg
!= NULL
) {
908 strcat(szBuf
, szMsg
);
914 if ( !s_bNoAsserts
) {
915 // send it to the normal log destination
918 strcat(szBuf
, _("\nDo you want to stop the program?"
919 "\nYou can also choose [Cancel] to suppress "
920 "further warnings."));
922 switch ( wxMessageBox(szBuf
, _("Debug"),
923 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
932 //case wxNO: nothing to do