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 // we use a global variable to store the frame pointer for wxLogStatus - bad,
74 // but it's he easiest way
75 static wxFrame
*gs_pFrame
;
77 // ============================================================================
79 // ============================================================================
81 // ----------------------------------------------------------------------------
82 // implementation of Log functions
84 // NB: unfortunately we need all these distinct functions, we can't make them
85 // macros and not all compilers inline vararg functions.
86 // ----------------------------------------------------------------------------
88 // log functions can't allocate memory (LogError("out of memory...") should
89 // work!), so we use a static buffer for all log messages
90 #define LOG_BUFFER_SIZE (4096)
92 // static buffer for error messages (@@@ MT-unsafe)
93 static char s_szBuf
[LOG_BUFFER_SIZE
];
95 // generic log function
96 void wxLogGeneric(wxLogLevel level
, const char *szFormat
, ...)
98 if ( wxLog::GetActiveTarget() != NULL
) {
100 va_start(argptr
, szFormat
);
101 vsprintf(s_szBuf
, szFormat
, argptr
);
104 wxLog::OnLog(level
, s_szBuf
);
108 #define IMPLEMENT_LOG_FUNCTION(level) \
109 void wxLog##level(const char *szFormat, ...) \
111 if ( wxLog::GetActiveTarget() != NULL ) { \
113 va_start(argptr, szFormat); \
114 vsprintf(s_szBuf, szFormat, argptr); \
117 wxLog::OnLog(wxLOG_##level, s_szBuf); \
121 IMPLEMENT_LOG_FUNCTION(FatalError
)
122 IMPLEMENT_LOG_FUNCTION(Error
)
123 IMPLEMENT_LOG_FUNCTION(Warning
)
124 IMPLEMENT_LOG_FUNCTION(Message
)
125 IMPLEMENT_LOG_FUNCTION(Info
)
126 IMPLEMENT_LOG_FUNCTION(Status
)
128 // accepts an additional argument which tells to which frame the output should
130 void wxLogStatus(wxFrame
*pFrame
, const char *szFormat
, ...)
132 wxLog
*pLog
= wxLog::GetActiveTarget();
133 if ( pLog
!= NULL
) {
135 va_start(argptr
, szFormat
);
136 vsprintf(s_szBuf
, szFormat
, argptr
);
139 wxASSERT( gs_pFrame
== NULL
); // should be reset!
141 wxLog::OnLog(wxLOG_Status
, s_szBuf
);
146 // same as info, but only if 'verbose' mode is on
147 void wxLogVerbose(const char *szFormat
, ...)
149 wxLog
*pLog
= wxLog::GetActiveTarget();
150 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
152 va_start(argptr
, szFormat
);
153 vsprintf(s_szBuf
, szFormat
, argptr
);
156 wxLog::OnLog(wxLOG_Info
, s_szBuf
);
162 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
163 void wxLog##level(const char *szFormat, ...) \
165 if ( wxLog::GetActiveTarget() != NULL ) { \
167 va_start(argptr, szFormat); \
168 vsprintf(s_szBuf, szFormat, argptr); \
171 wxLog::OnLog(wxLOG_##level, s_szBuf); \
175 void wxLogTrace(wxTraceMask mask
, const char *szFormat
, ...)
177 wxLog
*pLog
= wxLog::GetActiveTarget();
179 // we check that all of mask bits are set in the current mask, so
180 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
181 // if both bits are set.
182 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
184 va_start(argptr
, szFormat
);
185 vsprintf(s_szBuf
, szFormat
, argptr
);
188 wxLog::OnLog(wxLOG_Trace
, s_szBuf
);
193 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
196 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
197 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
199 // wxLogSysError: one uses the last error code, for other you must give it
202 // common part of both wxLogSysError
203 void wxLogSysErrorHelper(long lErrCode
)
205 char szErrMsg
[LOG_BUFFER_SIZE
/ 2];
206 sprintf(szErrMsg
, _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
207 strncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - strlen(s_szBuf
));
209 wxLog::OnLog(wxLOG_Error
, s_szBuf
);
212 void WXDLLEXPORT
wxLogSysError(const char *szFormat
, ...)
215 va_start(argptr
, szFormat
);
216 vsprintf(s_szBuf
, szFormat
, argptr
);
219 wxLogSysErrorHelper(wxSysErrorCode());
222 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const char *szFormat
, ...)
225 va_start(argptr
, szFormat
);
226 vsprintf(s_szBuf
, szFormat
, argptr
);
229 wxLogSysErrorHelper(lErrCode
);
232 // ----------------------------------------------------------------------------
233 // wxLog class implementation
234 // ----------------------------------------------------------------------------
238 m_bHasMessages
= FALSE
;
240 m_szTimeFormat
= "[%d/%b/%y %H:%M:%S] ";
243 wxLog
*wxLog::GetActiveTarget()
245 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
246 // prevent infinite recursion if someone calls wxLogXXX() from
247 // wxApp::CreateLogTarget()
248 static bool s_bInGetActiveTarget
= FALSE
;
249 if ( !s_bInGetActiveTarget
) {
250 s_bInGetActiveTarget
= TRUE
;
252 #ifdef WX_TEST_MINIMAL
253 ms_pLogger
= new wxLogStderr
;
255 // ask the application to create a log target for us
256 if ( wxTheApp
!= NULL
)
257 ms_pLogger
= wxTheApp
->CreateLogTarget();
260 // do nothing if it fails - what can we do?
267 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
269 // flush the old messages before changing
270 if ( ms_pLogger
!= NULL
)
273 wxLog
*pOldLogger
= ms_pLogger
;
274 ms_pLogger
= pLogger
;
278 wxString
wxLog::TimeStamp() const
282 if ( !IsEmpty(m_szTimeFormat
) ) {
288 ptmNow
= localtime(&timeNow
);
290 strftime(szBuf
, WXSIZEOF(szBuf
), m_szTimeFormat
, ptmNow
);
297 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
299 // prepend a timestamp if not disabled
300 wxString str
= TimeStamp();
303 case wxLOG_FatalError
:
304 DoLogString(str
<< _("Fatal error: ") << szString
);
305 DoLogString(_("Program aborted."));
311 DoLogString(str
<< _("Error: ") << szString
);
315 DoLogString(str
<< _("Warning: ") << szString
);
321 DoLogString(str
+ szString
);
331 DoLogString(str
<< (level
== wxLOG_Trace
? _("Trace") : _("Debug"))
332 << ": " << szString
);
338 wxFAIL_MSG(_("unknown log level in wxLog::DoLog"));
342 void wxLog::DoLogString(const char *WXUNUSED(szString
))
344 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
352 // ----------------------------------------------------------------------------
353 // wxLogStderr class implementation
354 // ----------------------------------------------------------------------------
356 wxLogStderr::wxLogStderr(FILE *fp
)
364 void wxLogStderr::DoLogString(const char *szString
)
366 fputs(szString
, m_fp
);
371 // ----------------------------------------------------------------------------
372 // wxLogStream implementation
373 // ----------------------------------------------------------------------------
375 wxLogStream::wxLogStream(ostream
*ostr
)
383 void wxLogStream::DoLogString(const char *szString
)
385 (*m_ostr
) << szString
<< endl
<< flush
;
388 // ----------------------------------------------------------------------------
389 // wxLogTextCtrl implementation
390 // ----------------------------------------------------------------------------
391 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
392 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
394 // Also, in DLL mode in wxMSW, can't use it.
395 #if defined(NO_TEXT_WINDOW_STREAM)
397 : wxLogStream(new ostream(pTextCtrl
))
402 wxLogTextCtrl::~wxLogTextCtrl()
407 // ----------------------------------------------------------------------------
408 // wxLogGui implementation
409 // ----------------------------------------------------------------------------
411 #ifndef WX_TEST_MINIMAL
418 void wxLogGui::Flush()
420 if ( !m_bHasMessages
)
425 // concatenate all strings (but not too many to not overfill the msg box)
428 nMsgCount
= m_aMessages
.Count();
430 // start from the most recent message
431 for ( uint n
= nMsgCount
; n
> 0; n
-- ) {
432 // for Windows strings longer than this value are wrapped (NT 4.0)
433 const uint nMsgLineWidth
= 156;
435 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
437 if ( nLines
> 25 ) // don't put too many lines in message box
440 str
<< m_aMessages
[n
- 1] << "\n";
444 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
447 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
450 // no undisplayed messages whatsoever
456 // the default behaviour is to discard all informational messages if there
457 // are any errors/warnings.
458 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
465 m_aMessages
.Add(szString
);
466 m_bHasMessages
= TRUE
;
472 // find the top window and set it's status text if it has any
473 wxFrame
*pFrame
= gs_pFrame
;
474 if ( pFrame
== NULL
) {
475 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
476 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
477 pFrame
= (wxFrame
*)pWin
;
481 if ( pFrame
!= NULL
)
482 pFrame
->SetStatusText(szString
);
490 wxString strTime
= TimeStamp();
493 // don't prepend debug/trace here: it goes to the debug window
494 // anyhow, but do put a timestamp
495 OutputDebugString(strTime
+ szString
+ "\n\r");
497 // send them to stderr
498 fprintf(stderr
, "%s %s: %s\n",
500 level
== wxLOG_Trace
? _("Trace") : _("Debug"),
508 case wxLOG_FatalError
:
509 // show this one immediately
510 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
515 // discard earlier informational messages if this is the 1st error
518 m_bHasMessages
= TRUE
;
522 m_aMessages
.Add(szString
);
526 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
530 // ----------------------------------------------------------------------------
531 // wxLogWindow and wxLogFrame implementation
532 // ----------------------------------------------------------------------------
536 class wxLogFrame
: public wxFrame
540 wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
);
541 virtual ~wxLogFrame();
544 void OnClose(wxCommandEvent
& event
);
545 void OnCloseWindow(wxCloseEvent
& event
);
546 void OnSave (wxCommandEvent
& event
);
547 void OnClear(wxCommandEvent
& event
);
549 void OnIdle(wxIdleEvent
&);
552 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
562 // instead of closing just hide the window to be able to Show() it later
563 void DoClose() { Show(FALSE
); }
565 wxTextCtrl
*m_pTextCtrl
;
568 DECLARE_EVENT_TABLE()
571 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
572 // wxLogWindow menu events
573 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
574 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
575 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
577 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
580 wxLogFrame::wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
)
581 : wxFrame(pParent
, -1, szTitle
)
585 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
586 // a rich edit control instead of a normal one we want in wxMSW
587 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
595 wxMenuBar
*pMenuBar
= new wxMenuBar
;
596 wxMenu
*pMenu
= new wxMenu
;
597 pMenu
->Append(Menu_Save
, _("&Save..."), _("Save log contents to file"));
598 pMenu
->Append(Menu_Clear
, _("C&lear"), _("Clear the log contents"));
599 pMenu
->AppendSeparator();
600 pMenu
->Append(Menu_Close
, _("&Close"), _("Close this window"));
601 pMenuBar
->Append(pMenu
, _("&Log"));
602 SetMenuBar(pMenuBar
);
604 // status bar for menu prompts
607 m_log
->OnFrameCreate(this);
610 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
615 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
620 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
624 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
625 if ( szFileName
== NULL
) {
634 if ( wxFile::Exists(szFileName
) ) {
635 bool bAppend
= FALSE
;
637 strMsg
.Printf(_("Append log to file '%s' "
638 "(choosing [No] will overwrite it)?"), szFileName
);
639 switch ( wxMessageBox(strMsg
, _("Question"), wxYES_NO
| wxCANCEL
) ) {
652 wxFAIL_MSG(_("invalid message box return value"));
656 bOk
= file
.Open(szFileName
, wxFile::write_append
);
659 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
663 bOk
= file
.Create(szFileName
);
666 // retrieve text and save it
667 // -------------------------
669 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
670 wxLogError(_("Sorry, this function is not implemented under GTK"));
672 int nLines
= m_pTextCtrl
->GetNumberOfLines();
673 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
674 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) + wxTextFile::GetEOL());
682 wxLogError(_("Can't save log contents to file."));
687 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
689 m_pTextCtrl
->Clear();
692 wxLogFrame::~wxLogFrame()
694 m_log
->OnFrameDelete(this);
699 wxLogWindow::wxLogWindow(wxFrame
*pParent
,
704 m_bPassMessages
= bDoPass
;
706 m_pLogFrame
= new wxLogFrame(pParent
, this, szTitle
);
707 m_pOldLog
= wxLog::SetActiveTarget(this);
710 m_pLogFrame
->Show(TRUE
);
713 void wxLogWindow::Show(bool bShow
)
715 m_pLogFrame
->Show(bShow
);
718 void wxLogWindow::Flush()
720 if ( m_pOldLog
!= NULL
)
723 m_bHasMessages
= FALSE
;
726 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
728 // first let the previous logger show it
729 if ( m_pOldLog
!= NULL
&& m_bPassMessages
) {
730 // @@@ why can't we access protected wxLog method from here (we derive
731 // from wxLog)? gcc gives "DoLog is protected in this context", what
732 // does this mean? Anyhow, the cast is harmless and let's us do what
734 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
737 // don't put trace messages in the text window for 2 reasons:
738 // 1) there are too many of them
739 // 2) they may provoke other trace messages thus sending a program into an
741 if ( m_pLogFrame
&& level
!= wxLOG_Trace
) {
742 // and this will format it nicely and call our DoLogString()
743 wxLog::DoLog(level
, szString
);
746 m_bHasMessages
= TRUE
;
749 void wxLogWindow::DoLogString(const char *szString
)
751 // put the text into our window
752 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
754 // remove selection (WriteText is in fact ReplaceSelection)
756 long nLen
= pText
->GetLastPosition();
757 pText
->SetSelection(nLen
, nLen
);
760 pText
->WriteText(szString
);
761 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
763 // ensure that the line can be seen
767 wxFrame
*wxLogWindow::GetFrame() const
772 void wxLogWindow::OnFrameCreate(wxFrame
*frame
)
776 void wxLogWindow::OnFrameDelete(wxFrame
*frame
)
781 wxLogWindow::~wxLogWindow()
783 // may be NULL if log frame already auto destroyed itself
787 #endif //WX_TEST_MINIMAL
789 // ============================================================================
790 // Global functions/variables
791 // ============================================================================
793 // ----------------------------------------------------------------------------
795 // ----------------------------------------------------------------------------
796 wxLog
*wxLog::ms_pLogger
= NULL
;
797 bool wxLog::ms_bAutoCreate
= TRUE
;
798 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
800 // ----------------------------------------------------------------------------
801 // stdout error logging helper
802 // ----------------------------------------------------------------------------
804 // helper function: wraps the message and justifies it under given position
805 // (looks more pretty on the terminal). Also adds newline at the end.
807 // @@ this is now disabled until I find a portable way of determining the
808 // terminal window size (ok, I found it but does anybody really cares?)
809 #ifdef LOG_PRETTY_WRAP
810 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
812 size_t nMax
= 80; // @@@@
813 size_t nStart
= strlen(pszPrefix
);
817 while ( *psz
!= '\0' ) {
818 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
822 if ( *psz
!= '\0' ) {
824 for ( n
= 0; n
< nStart
; n
++ )
827 // as we wrapped, squeeze all white space
828 while ( isspace(*psz
) )
835 #endif //LOG_PRETTY_WRAP
837 // ----------------------------------------------------------------------------
838 // error code/error message retrieval functions
839 // ----------------------------------------------------------------------------
841 // get error code from syste
842 unsigned long wxSysErrorCode()
846 return ::GetLastError();
848 // @@@@ what to do on Windows 3.1?
856 // get error message from system
857 const char *wxSysErrorMsg(unsigned long nErrCode
)
860 nErrCode
= wxSysErrorCode();
864 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
866 // get error message from system
868 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
870 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
874 // copy it to our buffer and free memory
875 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
876 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
879 // returned string is capitalized and ended with '\r\n' - bad
880 s_szBuf
[0] = (char)wxToLower(s_szBuf
[0]);
881 size_t len
= strlen(s_szBuf
);
884 if ( s_szBuf
[len
- 2] == '\r' )
885 s_szBuf
[len
- 2] = '\0';
894 return strerror(nErrCode
);
898 // ----------------------------------------------------------------------------
900 // ----------------------------------------------------------------------------
913 // this function is called when an assert fails
914 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
916 // this variable can be set to true to suppress "assert failure" messages
917 static bool s_bNoAsserts
= FALSE
;
918 static bool s_bInAssert
= FALSE
;
921 // He-e-e-e-elp!! we're trapped in endless loop
927 char szBuf
[LOG_BUFFER_SIZE
];
928 sprintf(szBuf
, _("Assert failed in file %s at line %d"), szFile
, nLine
);
929 if ( szMsg
!= NULL
) {
931 strcat(szBuf
, szMsg
);
937 if ( !s_bNoAsserts
) {
938 // send it to the normal log destination
941 strcat(szBuf
, _("\nDo you want to stop the program?"
942 "\nYou can also choose [Cancel] to suppress "
943 "further warnings."));
945 switch ( wxMessageBox(szBuf
, _("Debug"),
946 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
955 //case wxNO: nothing to do