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>
38 #include <wx/generic/msgdlgg.h>
39 #include <wx/filedlg.h>
40 #include <wx/textctrl.h>
44 #include <wx/textfile.h>
48 // other standard headers
59 // ----------------------------------------------------------------------------
60 // non member functions
61 // ----------------------------------------------------------------------------
63 // define this to enable wrapping of log messages
64 //#define LOG_PRETTY_WRAP
66 #ifdef LOG_PRETTY_WRAP
67 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
70 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
74 // we use a global variable to store the frame pointer for wxLogStatus - bad,
75 // but it's he easiest way
76 static wxFrame
*gs_pFrame
;
78 // ============================================================================
80 // ============================================================================
82 // ----------------------------------------------------------------------------
83 // implementation of Log functions
85 // NB: unfortunately we need all these distinct functions, we can't make them
86 // macros and not all compilers inline vararg functions.
87 // ----------------------------------------------------------------------------
89 // log functions can't allocate memory (LogError("out of memory...") should
90 // work!), so we use a static buffer for all log messages
91 #define LOG_BUFFER_SIZE (4096)
93 // static buffer for error messages (@@@ MT-unsafe)
94 static char s_szBuf
[LOG_BUFFER_SIZE
];
96 // generic log function
97 void wxLogGeneric(wxLogLevel level
, const char *szFormat
, ...)
99 if ( wxLog::GetActiveTarget() != NULL
) {
101 va_start(argptr
, szFormat
);
102 vsprintf(s_szBuf
, szFormat
, argptr
);
105 wxLog::OnLog(level
, s_szBuf
);
109 #define IMPLEMENT_LOG_FUNCTION(level) \
110 void wxLog##level(const char *szFormat, ...) \
112 if ( wxLog::GetActiveTarget() != NULL ) { \
114 va_start(argptr, szFormat); \
115 vsprintf(s_szBuf, szFormat, argptr); \
118 wxLog::OnLog(wxLOG_##level, s_szBuf); \
122 IMPLEMENT_LOG_FUNCTION(FatalError
)
123 IMPLEMENT_LOG_FUNCTION(Error
)
124 IMPLEMENT_LOG_FUNCTION(Warning
)
125 IMPLEMENT_LOG_FUNCTION(Message
)
126 IMPLEMENT_LOG_FUNCTION(Info
)
127 IMPLEMENT_LOG_FUNCTION(Status
)
129 // accepts an additional argument which tells to which frame the output should
131 void wxLogStatus(wxFrame
*pFrame
, const char *szFormat
, ...)
133 wxLog
*pLog
= wxLog::GetActiveTarget();
134 if ( pLog
!= NULL
) {
136 va_start(argptr
, szFormat
);
137 vsprintf(s_szBuf
, szFormat
, argptr
);
140 wxASSERT( gs_pFrame
== NULL
); // should be reset!
142 wxLog::OnLog(wxLOG_Status
, s_szBuf
);
143 gs_pFrame
= (wxFrame
*) NULL
;
147 // same as info, but only if 'verbose' mode is on
148 void wxLogVerbose(const char *szFormat
, ...)
150 wxLog
*pLog
= wxLog::GetActiveTarget();
151 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
153 va_start(argptr
, szFormat
);
154 vsprintf(s_szBuf
, szFormat
, argptr
);
157 wxLog::OnLog(wxLOG_Info
, s_szBuf
);
163 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
164 void wxLog##level(const char *szFormat, ...) \
166 if ( wxLog::GetActiveTarget() != NULL ) { \
168 va_start(argptr, szFormat); \
169 vsprintf(s_szBuf, szFormat, argptr); \
172 wxLog::OnLog(wxLOG_##level, s_szBuf); \
176 void wxLogTrace(wxTraceMask mask
, const char *szFormat
, ...)
178 wxLog
*pLog
= wxLog::GetActiveTarget();
180 // we check that all of mask bits are set in the current mask, so
181 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
182 // if both bits are set.
183 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
185 va_start(argptr
, szFormat
);
186 vsprintf(s_szBuf
, szFormat
, argptr
);
189 wxLog::OnLog(wxLOG_Trace
, s_szBuf
);
194 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
197 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
198 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
200 // wxLogSysError: one uses the last error code, for other you must give it
203 // common part of both wxLogSysError
204 void wxLogSysErrorHelper(long lErrCode
)
206 char szErrMsg
[LOG_BUFFER_SIZE
/ 2];
207 sprintf(szErrMsg
, _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
208 strncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - strlen(s_szBuf
));
210 wxLog::OnLog(wxLOG_Error
, s_szBuf
);
213 void WXDLLEXPORT
wxLogSysError(const char *szFormat
, ...)
216 va_start(argptr
, szFormat
);
217 vsprintf(s_szBuf
, szFormat
, argptr
);
220 wxLogSysErrorHelper(wxSysErrorCode());
223 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const char *szFormat
, ...)
226 va_start(argptr
, szFormat
);
227 vsprintf(s_szBuf
, szFormat
, argptr
);
230 wxLogSysErrorHelper(lErrCode
);
233 // ----------------------------------------------------------------------------
234 // wxLog class implementation
235 // ----------------------------------------------------------------------------
239 m_bHasMessages
= FALSE
;
241 m_szTimeFormat
= "[%d/%b/%y %H:%M:%S] ";
244 wxLog
*wxLog::GetActiveTarget()
246 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
247 // prevent infinite recursion if someone calls wxLogXXX() from
248 // wxApp::CreateLogTarget()
249 static bool s_bInGetActiveTarget
= FALSE
;
250 if ( !s_bInGetActiveTarget
) {
251 s_bInGetActiveTarget
= TRUE
;
254 ms_pLogger
= new wxLogStderr
;
256 // ask the application to create a log target for us
257 if ( wxTheApp
!= NULL
)
258 ms_pLogger
= wxTheApp
->CreateLogTarget();
260 ms_pLogger
= new wxLogStderr
;
263 s_bInGetActiveTarget
= FALSE
;
265 // do nothing if it fails - what can we do?
272 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
274 if ( ms_pLogger
!= NULL
) {
275 // flush the old messages before changing because otherwise they might
276 // get lost later if this target is not restored
280 wxLog
*pOldLogger
= ms_pLogger
;
281 ms_pLogger
= pLogger
;
286 wxString
wxLog::TimeStamp() const
290 /* Let's disable TimeStamp and see if anyone complains.
291 * If not, we'll remove it, since it's probably unlikely
292 * to ever be used. -- JACS 22/11/98
293 if ( !IsEmpty(m_szTimeFormat) ) {
299 ptmNow = localtime(&timeNow);
301 strftime(szBuf, WXSIZEOF(szBuf), m_szTimeFormat, ptmNow);
309 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
311 // prepend a timestamp if not disabled
312 wxString str
= TimeStamp();
315 case wxLOG_FatalError
:
316 DoLogString(str
<< _("Fatal error: ") << szString
);
317 DoLogString(_("Program aborted."));
323 DoLogString(str
<< _("Error: ") << szString
);
327 DoLogString(str
<< _("Warning: ") << szString
);
333 DoLogString(str
+ szString
);
343 // DoLogString(str << (level == wxLOG_Trace ? _("Trace") : _("Debug"))
344 // << ": " << szString);
345 // JACS: we don't really want to prefix with 'Debug'. It's just extra
347 DoLogString(szString
);
353 wxFAIL_MSG(_("unknown log level in wxLog::DoLog"));
357 void wxLog::DoLogString(const char *WXUNUSED(szString
))
359 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
367 // ----------------------------------------------------------------------------
368 // wxLogStderr class implementation
369 // ----------------------------------------------------------------------------
371 wxLogStderr::wxLogStderr(FILE *fp
)
379 void wxLogStderr::DoLogString(const char *szString
)
381 fputs(szString
, m_fp
);
386 // ----------------------------------------------------------------------------
387 // wxLogStream implementation
388 // ----------------------------------------------------------------------------
390 wxLogStream::wxLogStream(ostream
*ostr
)
398 void wxLogStream::DoLogString(const char *szString
)
400 (*m_ostr
) << szString
<< endl
<< flush
;
404 // ----------------------------------------------------------------------------
405 // wxLogTextCtrl implementation
406 // ----------------------------------------------------------------------------
407 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
408 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
410 // Also, in DLL mode in wxMSW, can't use it.
411 #if defined(NO_TEXT_WINDOW_STREAM)
413 : wxLogStream(new ostream(pTextCtrl
))
418 wxLogTextCtrl::~wxLogTextCtrl()
423 // ----------------------------------------------------------------------------
424 // wxLogGui implementation
425 // ----------------------------------------------------------------------------
432 void wxLogGui::Flush()
434 if ( !m_bHasMessages
)
437 // do it right now to block any new calls to Flush() while we're here
438 m_bHasMessages
= FALSE
;
442 // concatenate all strings (but not too many to not overfill the msg box)
445 nMsgCount
= m_aMessages
.Count();
447 // start from the most recent message
448 for ( size_t n
= nMsgCount
; n
> 0; n
-- ) {
449 // for Windows strings longer than this value are wrapped (NT 4.0)
450 const size_t nMsgLineWidth
= 156;
452 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
454 if ( nLines
> 25 ) // don't put too many lines in message box
457 str
<< m_aMessages
[n
- 1] << "\n";
461 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
464 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
467 // no undisplayed messages whatsoever
472 // the default behaviour is to discard all informational messages if there
473 // are any errors/warnings.
474 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
481 m_aMessages
.Add(szString
);
482 m_bHasMessages
= TRUE
;
488 // find the top window and set it's status text if it has any
489 wxFrame
*pFrame
= gs_pFrame
;
490 if ( pFrame
== NULL
) {
491 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
492 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
493 pFrame
= (wxFrame
*)pWin
;
497 if ( pFrame
!= NULL
)
498 pFrame
->SetStatusText(szString
);
506 wxString strTime
= TimeStamp();
509 // don't prepend debug/trace here: it goes to the debug window
510 // anyhow, but do put a timestamp
511 OutputDebugString(strTime
+ szString
+ "\n\r");
513 // send them to stderr
515 fprintf(stderr, "%s %s: %s\n",
517 level == wxLOG_Trace ? _("Trace") : _("Debug"),
520 fprintf(stderr
, "%s\n",
528 case wxLOG_FatalError
:
529 // show this one immediately
530 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
535 // discard earlier informational messages if this is the 1st error
538 m_bHasMessages
= TRUE
;
542 m_aMessages
.Add(szString
);
546 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
550 // ----------------------------------------------------------------------------
551 // wxLogWindow and wxLogFrame implementation
552 // ----------------------------------------------------------------------------
556 class wxLogFrame
: public wxFrame
560 wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
);
561 virtual ~wxLogFrame();
564 void OnClose(wxCommandEvent
& event
);
565 void OnCloseWindow(wxCloseEvent
& event
);
566 void OnSave (wxCommandEvent
& event
);
567 void OnClear(wxCommandEvent
& event
);
569 void OnIdle(wxIdleEvent
&);
572 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
582 // instead of closing just hide the window to be able to Show() it later
583 void DoClose() { Show(FALSE
); }
585 wxTextCtrl
*m_pTextCtrl
;
588 DECLARE_EVENT_TABLE()
591 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
592 // wxLogWindow menu events
593 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
594 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
595 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
597 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
600 wxLogFrame::wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
)
601 : wxFrame(pParent
, -1, szTitle
)
605 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
606 // a rich edit control instead of a normal one we want in wxMSW
607 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
615 wxMenuBar
*pMenuBar
= new wxMenuBar
;
616 wxMenu
*pMenu
= new wxMenu
;
617 pMenu
->Append(Menu_Save
, _("&Save..."), _("Save log contents to file"));
618 pMenu
->Append(Menu_Clear
, _("C&lear"), _("Clear the log contents"));
619 pMenu
->AppendSeparator();
620 pMenu
->Append(Menu_Close
, _("&Close"), _("Close this window"));
621 pMenuBar
->Append(pMenu
, _("&Log"));
622 SetMenuBar(pMenuBar
);
624 // status bar for menu prompts
627 m_log
->OnFrameCreate(this);
630 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
635 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
640 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
644 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
645 if ( szFileName
== NULL
) {
654 if ( wxFile::Exists(szFileName
) ) {
655 bool bAppend
= FALSE
;
657 strMsg
.Printf(_("Append log to file '%s' "
658 "(choosing [No] will overwrite it)?"), szFileName
);
659 switch ( wxMessageBox(strMsg
, _("Question"), wxYES_NO
| wxCANCEL
) ) {
672 wxFAIL_MSG(_("invalid message box return value"));
676 bOk
= file
.Open(szFileName
, wxFile::write_append
);
679 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
683 bOk
= file
.Create(szFileName
);
686 // retrieve text and save it
687 // -------------------------
689 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
690 wxLogError(_("Sorry, this function is not implemented under GTK"));
692 int nLines
= m_pTextCtrl
->GetNumberOfLines();
693 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
694 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) + wxTextFile::GetEOL());
702 wxLogError(_("Can't save log contents to file."));
707 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
709 m_pTextCtrl
->Clear();
712 wxLogFrame::~wxLogFrame()
714 m_log
->OnFrameDelete(this);
719 wxLogWindow::wxLogWindow(wxFrame
*pParent
,
724 m_bPassMessages
= bDoPass
;
726 m_pLogFrame
= new wxLogFrame(pParent
, this, szTitle
);
727 m_pOldLog
= wxLog::SetActiveTarget(this);
730 m_pLogFrame
->Show(TRUE
);
733 void wxLogWindow::Show(bool bShow
)
735 m_pLogFrame
->Show(bShow
);
738 void wxLogWindow::Flush()
740 if ( m_pOldLog
!= NULL
)
743 m_bHasMessages
= FALSE
;
746 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
748 // first let the previous logger show it
749 if ( m_pOldLog
!= NULL
&& m_bPassMessages
) {
750 // @@@ why can't we access protected wxLog method from here (we derive
751 // from wxLog)? gcc gives "DoLog is protected in this context", what
752 // does this mean? Anyhow, the cast is harmless and let's us do what
754 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
760 // by default, these messages are ignored by wxLog, so process
763 wxString str
= TimeStamp();
764 str
<< _("Status: ") << szString
;
769 // don't put trace messages in the text window for 2 reasons:
770 // 1) there are too many of them
771 // 2) they may provoke other trace messages thus sending a program
772 // into an infinite loop
777 // and this will format it nicely and call our DoLogString()
778 wxLog::DoLog(level
, szString
);
782 m_bHasMessages
= TRUE
;
785 void wxLogWindow::DoLogString(const char *szString
)
787 // put the text into our window
788 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
790 // remove selection (WriteText is in fact ReplaceSelection)
792 long nLen
= pText
->GetLastPosition();
793 pText
->SetSelection(nLen
, nLen
);
796 pText
->WriteText(szString
);
797 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
799 // TODO ensure that the line can be seen
802 wxFrame
*wxLogWindow::GetFrame() const
807 void wxLogWindow::OnFrameCreate(wxFrame
*WXUNUSED(frame
))
811 void wxLogWindow::OnFrameDelete(wxFrame
*WXUNUSED(frame
))
813 m_pLogFrame
= (wxLogFrame
*)NULL
;
816 wxLogWindow::~wxLogWindow()
820 // may be NULL if log frame already auto destroyed itself
826 // ============================================================================
827 // Global functions/variables
828 // ============================================================================
830 // ----------------------------------------------------------------------------
832 // ----------------------------------------------------------------------------
833 wxLog
*wxLog::ms_pLogger
= (wxLog
*) NULL
;
834 bool wxLog::ms_doLog
= TRUE
;
835 bool wxLog::ms_bAutoCreate
= TRUE
;
836 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
838 // ----------------------------------------------------------------------------
839 // stdout error logging helper
840 // ----------------------------------------------------------------------------
842 // helper function: wraps the message and justifies it under given position
843 // (looks more pretty on the terminal). Also adds newline at the end.
845 // @@ this is now disabled until I find a portable way of determining the
846 // terminal window size (ok, I found it but does anybody really cares?)
847 #ifdef LOG_PRETTY_WRAP
848 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
850 size_t nMax
= 80; // @@@@
851 size_t nStart
= strlen(pszPrefix
);
855 while ( *psz
!= '\0' ) {
856 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
860 if ( *psz
!= '\0' ) {
862 for ( n
= 0; n
< nStart
; n
++ )
865 // as we wrapped, squeeze all white space
866 while ( isspace(*psz
) )
873 #endif //LOG_PRETTY_WRAP
875 // ----------------------------------------------------------------------------
876 // error code/error message retrieval functions
877 // ----------------------------------------------------------------------------
879 // get error code from syste
880 unsigned long wxSysErrorCode()
884 return ::GetLastError();
886 // @@@@ what to do on Windows 3.1?
894 // get error message from system
895 const char *wxSysErrorMsg(unsigned long nErrCode
)
898 nErrCode
= wxSysErrorCode();
902 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
904 // get error message from system
906 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
908 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
912 // copy it to our buffer and free memory
913 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
914 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
917 // returned string is capitalized and ended with '\r\n' - bad
918 s_szBuf
[0] = (char)wxToLower(s_szBuf
[0]);
919 size_t len
= strlen(s_szBuf
);
922 if ( s_szBuf
[len
- 2] == '\r' )
923 s_szBuf
[len
- 2] = '\0';
932 return strerror(nErrCode
);
936 // ----------------------------------------------------------------------------
938 // ----------------------------------------------------------------------------
946 #elif defined(__WXSTUBS__)
953 // this function is called when an assert fails
954 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
956 // this variable can be set to true to suppress "assert failure" messages
957 static bool s_bNoAsserts
= FALSE
;
958 static bool s_bInAssert
= FALSE
;
961 // He-e-e-e-elp!! we're trapped in endless loop
969 char szBuf
[LOG_BUFFER_SIZE
];
970 sprintf(szBuf
, _("Assert failed in file %s at line %d"), szFile
, nLine
);
971 if ( szMsg
!= NULL
) {
973 strcat(szBuf
, szMsg
);
979 if ( !s_bNoAsserts
) {
980 // send it to the normal log destination
986 strcat(szBuf
, _("\nDo you want to stop the program?"
987 "\nYou can also choose [Cancel] to suppress "
988 "further warnings."));
990 switch ( wxMessageBox(szBuf
, _("Debug"),
991 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
1000 //case wxNO: nothing to do
1005 s_bInAssert
= FALSE
;