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
);
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
;
253 #ifdef WX_TEST_MINIMAL
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();
261 // do nothing if it fails - what can we do?
268 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
270 // flush the old messages before changing
271 if ( ms_pLogger
!= NULL
)
274 wxLog
*pOldLogger
= ms_pLogger
;
275 ms_pLogger
= pLogger
;
279 wxString
wxLog::TimeStamp() const
283 if ( !IsEmpty(m_szTimeFormat
) ) {
289 ptmNow
= localtime(&timeNow
);
291 strftime(szBuf
, WXSIZEOF(szBuf
), m_szTimeFormat
, ptmNow
);
298 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
300 // prepend a timestamp if not disabled
301 wxString str
= TimeStamp();
304 case wxLOG_FatalError
:
305 DoLogString(str
<< _("Fatal error: ") << szString
);
306 DoLogString(_("Program aborted."));
312 DoLogString(str
<< _("Error: ") << szString
);
316 DoLogString(str
<< _("Warning: ") << szString
);
322 DoLogString(str
+ szString
);
332 DoLogString(str
<< (level
== wxLOG_Trace
? _("Trace") : _("Debug"))
333 << ": " << szString
);
339 wxFAIL_MSG(_("unknown log level in wxLog::DoLog"));
343 void wxLog::DoLogString(const char *WXUNUSED(szString
))
345 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
353 // ----------------------------------------------------------------------------
354 // wxLogStderr class implementation
355 // ----------------------------------------------------------------------------
357 wxLogStderr::wxLogStderr(FILE *fp
)
365 void wxLogStderr::DoLogString(const char *szString
)
367 fputs(szString
, m_fp
);
372 // ----------------------------------------------------------------------------
373 // wxLogStream implementation
374 // ----------------------------------------------------------------------------
376 wxLogStream::wxLogStream(ostream
*ostr
)
384 void wxLogStream::DoLogString(const char *szString
)
386 (*m_ostr
) << szString
<< endl
<< flush
;
389 // ----------------------------------------------------------------------------
390 // wxLogTextCtrl implementation
391 // ----------------------------------------------------------------------------
392 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
393 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
395 // Also, in DLL mode in wxMSW, can't use it.
396 #if defined(NO_TEXT_WINDOW_STREAM)
398 : wxLogStream(new ostream(pTextCtrl
))
403 wxLogTextCtrl::~wxLogTextCtrl()
408 // ----------------------------------------------------------------------------
409 // wxLogGui implementation
410 // ----------------------------------------------------------------------------
412 #ifndef WX_TEST_MINIMAL
419 void wxLogGui::Flush()
421 if ( !m_bHasMessages
)
426 // concatenate all strings (but not too many to not overfill the msg box)
429 nMsgCount
= m_aMessages
.Count();
431 // start from the most recent message
432 for ( uint n
= nMsgCount
; n
> 0; n
-- ) {
433 // for Windows strings longer than this value are wrapped (NT 4.0)
434 const uint nMsgLineWidth
= 156;
436 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
438 if ( nLines
> 25 ) // don't put too many lines in message box
441 str
<< m_aMessages
[n
- 1] << "\n";
445 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
448 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
451 // no undisplayed messages whatsoever
457 // the default behaviour is to discard all informational messages if there
458 // are any errors/warnings.
459 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
466 m_aMessages
.Add(szString
);
467 m_bHasMessages
= TRUE
;
473 // find the top window and set it's status text if it has any
474 wxFrame
*pFrame
= gs_pFrame
;
475 if ( pFrame
== NULL
) {
476 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
477 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
478 pFrame
= (wxFrame
*)pWin
;
482 if ( pFrame
!= NULL
)
483 pFrame
->SetStatusText(szString
);
491 wxString strTime
= TimeStamp();
493 #if defined(__WIN32__) && !defined(__WXSTUBS__)
494 // don't prepend debug/trace here: it goes to the debug window
495 // anyhow, but do put a timestamp
496 OutputDebugString(strTime
+ szString
+ "\n\r");
498 // send them to stderr
499 fprintf(stderr
, "%s %s: %s\n",
501 level
== wxLOG_Trace
? _("Trace") : _("Debug"),
509 case wxLOG_FatalError
:
510 // show this one immediately
511 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
516 // discard earlier informational messages if this is the 1st error
519 m_bHasMessages
= TRUE
;
523 m_aMessages
.Add(szString
);
527 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
531 // ----------------------------------------------------------------------------
532 // wxLogWindow and wxLogFrame implementation
533 // ----------------------------------------------------------------------------
537 class wxLogFrame
: public wxFrame
541 wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
);
542 virtual ~wxLogFrame();
545 void OnClose(wxCommandEvent
& event
);
546 void OnCloseWindow(wxCloseEvent
& event
);
547 void OnSave (wxCommandEvent
& event
);
548 void OnClear(wxCommandEvent
& event
);
550 void OnIdle(wxIdleEvent
&);
553 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
563 // instead of closing just hide the window to be able to Show() it later
564 void DoClose() { Show(FALSE
); }
566 wxTextCtrl
*m_pTextCtrl
;
569 DECLARE_EVENT_TABLE()
572 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
573 // wxLogWindow menu events
574 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
575 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
576 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
578 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
581 wxLogFrame::wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
)
582 : wxFrame(pParent
, -1, szTitle
)
586 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
587 // a rich edit control instead of a normal one we want in wxMSW
588 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
596 wxMenuBar
*pMenuBar
= new wxMenuBar
;
597 wxMenu
*pMenu
= new wxMenu
;
598 pMenu
->Append(Menu_Save
, _("&Save..."), _("Save log contents to file"));
599 pMenu
->Append(Menu_Clear
, _("C&lear"), _("Clear the log contents"));
600 pMenu
->AppendSeparator();
601 pMenu
->Append(Menu_Close
, _("&Close"), _("Close this window"));
602 pMenuBar
->Append(pMenu
, _("&Log"));
603 SetMenuBar(pMenuBar
);
605 // status bar for menu prompts
608 m_log
->OnFrameCreate(this);
611 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
616 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
621 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
625 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
626 if ( szFileName
== NULL
) {
635 if ( wxFile::Exists(szFileName
) ) {
636 bool bAppend
= FALSE
;
638 strMsg
.Printf(_("Append log to file '%s' "
639 "(choosing [No] will overwrite it)?"), szFileName
);
640 switch ( wxMessageBox(strMsg
, _("Question"), wxYES_NO
| wxCANCEL
) ) {
653 wxFAIL_MSG(_("invalid message box return value"));
657 bOk
= file
.Open(szFileName
, wxFile::write_append
);
660 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
664 bOk
= file
.Create(szFileName
);
667 // retrieve text and save it
668 // -------------------------
670 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
671 wxLogError(_("Sorry, this function is not implemented under GTK"));
673 int nLines
= m_pTextCtrl
->GetNumberOfLines();
674 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
675 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) + wxTextFile::GetEOL());
683 wxLogError(_("Can't save log contents to file."));
688 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
690 m_pTextCtrl
->Clear();
693 wxLogFrame::~wxLogFrame()
695 m_log
->OnFrameDelete(this);
700 wxLogWindow::wxLogWindow(wxFrame
*pParent
,
705 m_bPassMessages
= bDoPass
;
707 m_pLogFrame
= new wxLogFrame(pParent
, this, szTitle
);
708 m_pOldLog
= wxLog::SetActiveTarget(this);
711 m_pLogFrame
->Show(TRUE
);
714 void wxLogWindow::Show(bool bShow
)
716 m_pLogFrame
->Show(bShow
);
719 void wxLogWindow::Flush()
721 if ( m_pOldLog
!= NULL
)
724 m_bHasMessages
= FALSE
;
727 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
729 // first let the previous logger show it
730 if ( m_pOldLog
!= NULL
&& m_bPassMessages
) {
731 // @@@ why can't we access protected wxLog method from here (we derive
732 // from wxLog)? gcc gives "DoLog is protected in this context", what
733 // does this mean? Anyhow, the cast is harmless and let's us do what
735 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
738 // don't put trace messages in the text window for 2 reasons:
739 // 1) there are too many of them
740 // 2) they may provoke other trace messages thus sending a program into an
742 if ( m_pLogFrame
&& level
!= wxLOG_Trace
) {
743 // and this will format it nicely and call our DoLogString()
744 wxLog::DoLog(level
, szString
);
747 m_bHasMessages
= TRUE
;
750 void wxLogWindow::DoLogString(const char *szString
)
752 // put the text into our window
753 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
755 // remove selection (WriteText is in fact ReplaceSelection)
757 long nLen
= pText
->GetLastPosition();
758 pText
->SetSelection(nLen
, nLen
);
761 pText
->WriteText(szString
);
762 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
764 // ensure that the line can be seen
768 wxFrame
*wxLogWindow::GetFrame() const
773 void wxLogWindow::OnFrameCreate(wxFrame
*frame
)
777 void wxLogWindow::OnFrameDelete(wxFrame
*frame
)
782 wxLogWindow::~wxLogWindow()
784 // may be NULL if log frame already auto destroyed itself
788 #endif //WX_TEST_MINIMAL
790 // ============================================================================
791 // Global functions/variables
792 // ============================================================================
794 // ----------------------------------------------------------------------------
796 // ----------------------------------------------------------------------------
797 wxLog
*wxLog::ms_pLogger
= NULL
;
798 bool wxLog::ms_bAutoCreate
= TRUE
;
799 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
801 // ----------------------------------------------------------------------------
802 // stdout error logging helper
803 // ----------------------------------------------------------------------------
805 // helper function: wraps the message and justifies it under given position
806 // (looks more pretty on the terminal). Also adds newline at the end.
808 // @@ this is now disabled until I find a portable way of determining the
809 // terminal window size (ok, I found it but does anybody really cares?)
810 #ifdef LOG_PRETTY_WRAP
811 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
813 size_t nMax
= 80; // @@@@
814 size_t nStart
= strlen(pszPrefix
);
818 while ( *psz
!= '\0' ) {
819 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
823 if ( *psz
!= '\0' ) {
825 for ( n
= 0; n
< nStart
; n
++ )
828 // as we wrapped, squeeze all white space
829 while ( isspace(*psz
) )
836 #endif //LOG_PRETTY_WRAP
838 // ----------------------------------------------------------------------------
839 // error code/error message retrieval functions
840 // ----------------------------------------------------------------------------
842 // get error code from syste
843 unsigned long wxSysErrorCode()
847 return ::GetLastError();
849 // @@@@ what to do on Windows 3.1?
857 // get error message from system
858 const char *wxSysErrorMsg(unsigned long nErrCode
)
861 nErrCode
= wxSysErrorCode();
865 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
867 // get error message from system
869 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
871 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
875 // copy it to our buffer and free memory
876 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
877 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
880 // returned string is capitalized and ended with '\r\n' - bad
881 s_szBuf
[0] = (char)wxToLower(s_szBuf
[0]);
882 size_t len
= strlen(s_szBuf
);
885 if ( s_szBuf
[len
- 2] == '\r' )
886 s_szBuf
[len
- 2] = '\0';
895 return strerror(nErrCode
);
899 // ----------------------------------------------------------------------------
901 // ----------------------------------------------------------------------------
909 #elif defined(__WXSTUBS__)
916 // this function is called when an assert fails
917 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
919 // this variable can be set to true to suppress "assert failure" messages
920 static bool s_bNoAsserts
= FALSE
;
921 static bool s_bInAssert
= FALSE
;
924 // He-e-e-e-elp!! we're trapped in endless loop
930 char szBuf
[LOG_BUFFER_SIZE
];
931 sprintf(szBuf
, _("Assert failed in file %s at line %d"), szFile
, nLine
);
932 if ( szMsg
!= NULL
) {
934 strcat(szBuf
, szMsg
);
940 if ( !s_bNoAsserts
) {
941 // send it to the normal log destination
944 strcat(szBuf
, _("\nDo you want to stop the program?"
945 "\nYou can also choose [Cancel] to suppress "
946 "further warnings."));
948 switch ( wxMessageBox(szBuf
, _("Debug"),
949 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
958 //case wxNO: nothing to do