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"
34 #include <wx/string.h>
38 #include <wx/msgdlg.h>
39 #include <wx/filedlg.h>
40 #include <wx/textctrl.h>
44 #include <wx/textfile.h>
48 // other standard headers
55 // Redefines OutputDebugString if necessary
56 #include "wx/msw/private.h"
61 // ----------------------------------------------------------------------------
62 // non member functions
63 // ----------------------------------------------------------------------------
65 // define this to enable wrapping of log messages
66 //#define LOG_PRETTY_WRAP
68 #ifdef LOG_PRETTY_WRAP
69 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
72 // ----------------------------------------------------------------------------
74 // ----------------------------------------------------------------------------
76 // we use a global variable to store the frame pointer for wxLogStatus - bad,
77 // but it's he easiest way
78 static wxFrame
*gs_pFrame
;
80 // ============================================================================
82 // ============================================================================
84 // ----------------------------------------------------------------------------
85 // implementation of Log functions
87 // NB: unfortunately we need all these distinct functions, we can't make them
88 // macros and not all compilers inline vararg functions.
89 // ----------------------------------------------------------------------------
91 // log functions can't allocate memory (LogError("out of memory...") should
92 // work!), so we use a static buffer for all log messages
93 #define LOG_BUFFER_SIZE (4096)
95 // static buffer for error messages (@@@ MT-unsafe)
96 static char s_szBuf
[LOG_BUFFER_SIZE
];
98 // generic log function
99 void wxLogGeneric(wxLogLevel level
, const char *szFormat
, ...)
101 if ( wxLog::GetActiveTarget() != NULL
) {
103 va_start(argptr
, szFormat
);
104 vsprintf(s_szBuf
, szFormat
, argptr
);
107 wxLog::OnLog(level
, s_szBuf
);
111 #define IMPLEMENT_LOG_FUNCTION(level) \
112 void wxLog##level(const char *szFormat, ...) \
114 if ( wxLog::GetActiveTarget() != NULL ) { \
116 va_start(argptr, szFormat); \
117 vsprintf(s_szBuf, szFormat, argptr); \
120 wxLog::OnLog(wxLOG_##level, s_szBuf); \
124 IMPLEMENT_LOG_FUNCTION(FatalError
)
125 IMPLEMENT_LOG_FUNCTION(Error
)
126 IMPLEMENT_LOG_FUNCTION(Warning
)
127 IMPLEMENT_LOG_FUNCTION(Message
)
128 IMPLEMENT_LOG_FUNCTION(Info
)
129 IMPLEMENT_LOG_FUNCTION(Status
)
131 // accepts an additional argument which tells to which frame the output should
133 void wxLogStatus(wxFrame
*pFrame
, const char *szFormat
, ...)
135 wxLog
*pLog
= wxLog::GetActiveTarget();
136 if ( pLog
!= NULL
) {
138 va_start(argptr
, szFormat
);
139 vsprintf(s_szBuf
, szFormat
, argptr
);
142 wxASSERT( gs_pFrame
== NULL
); // should be reset!
144 wxLog::OnLog(wxLOG_Status
, s_szBuf
);
145 gs_pFrame
= (wxFrame
*) NULL
;
149 // same as info, but only if 'verbose' mode is on
150 void wxLogVerbose(const char *szFormat
, ...)
152 wxLog
*pLog
= wxLog::GetActiveTarget();
153 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
155 va_start(argptr
, szFormat
);
156 vsprintf(s_szBuf
, szFormat
, argptr
);
159 wxLog::OnLog(wxLOG_Info
, s_szBuf
);
165 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
166 void wxLog##level(const char *szFormat, ...) \
168 if ( wxLog::GetActiveTarget() != NULL ) { \
170 va_start(argptr, szFormat); \
171 vsprintf(s_szBuf, szFormat, argptr); \
174 wxLog::OnLog(wxLOG_##level, s_szBuf); \
178 void wxLogTrace(wxTraceMask mask
, const char *szFormat
, ...)
180 wxLog
*pLog
= wxLog::GetActiveTarget();
182 // we check that all of mask bits are set in the current mask, so
183 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
184 // if both bits are set.
185 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
187 va_start(argptr
, szFormat
);
188 vsprintf(s_szBuf
, szFormat
, argptr
);
191 wxLog::OnLog(wxLOG_Trace
, s_szBuf
);
196 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
199 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
200 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
202 // wxLogSysError: one uses the last error code, for other you must give it
205 // common part of both wxLogSysError
206 void wxLogSysErrorHelper(long lErrCode
)
208 char szErrMsg
[LOG_BUFFER_SIZE
/ 2];
209 sprintf(szErrMsg
, _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
210 strncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - strlen(s_szBuf
));
212 wxLog::OnLog(wxLOG_Error
, s_szBuf
);
215 void WXDLLEXPORT
wxLogSysError(const char *szFormat
, ...)
218 va_start(argptr
, szFormat
);
219 vsprintf(s_szBuf
, szFormat
, argptr
);
222 wxLogSysErrorHelper(wxSysErrorCode());
225 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const char *szFormat
, ...)
228 va_start(argptr
, szFormat
);
229 vsprintf(s_szBuf
, szFormat
, argptr
);
232 wxLogSysErrorHelper(lErrCode
);
235 // ----------------------------------------------------------------------------
236 // wxLog class implementation
237 // ----------------------------------------------------------------------------
241 m_bHasMessages
= FALSE
;
243 // enable verbose messages by default in the debug builds
248 #endif // debug/release
250 m_szTimeFormat
= "[%d/%b/%y %H:%M:%S] ";
253 wxLog
*wxLog::GetActiveTarget()
255 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
256 // prevent infinite recursion if someone calls wxLogXXX() from
257 // wxApp::CreateLogTarget()
258 static bool s_bInGetActiveTarget
= FALSE
;
259 if ( !s_bInGetActiveTarget
) {
260 s_bInGetActiveTarget
= TRUE
;
263 ms_pLogger
= new wxLogStderr
;
265 // ask the application to create a log target for us
266 if ( wxTheApp
!= NULL
)
267 ms_pLogger
= wxTheApp
->CreateLogTarget();
269 ms_pLogger
= new wxLogStderr
;
272 s_bInGetActiveTarget
= FALSE
;
274 // do nothing if it fails - what can we do?
281 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
283 if ( ms_pLogger
!= NULL
) {
284 // flush the old messages before changing because otherwise they might
285 // get lost later if this target is not restored
289 wxLog
*pOldLogger
= ms_pLogger
;
290 ms_pLogger
= pLogger
;
295 wxString
wxLog::TimeStamp() const
299 /* Let's disable TimeStamp and see if anyone complains.
300 * If not, we'll remove it, since it's probably unlikely
301 * to ever be used. -- JACS 22/11/98
302 if ( !IsEmpty(m_szTimeFormat) ) {
308 ptmNow = localtime(&timeNow);
310 strftime(szBuf, WXSIZEOF(szBuf), m_szTimeFormat, ptmNow);
318 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
320 // prepend a timestamp if not disabled
321 wxString str
= TimeStamp();
324 case wxLOG_FatalError
:
325 DoLogString(str
<< _("Fatal error: ") << szString
);
326 DoLogString(_("Program aborted."));
332 DoLogString(str
<< _("Error: ") << szString
);
336 DoLogString(str
<< _("Warning: ") << szString
);
342 DoLogString(str
+ szString
);
352 // DoLogString(str << (level == wxLOG_Trace ? _("Trace") : _("Debug"))
353 // << ": " << szString);
354 // JACS: we don't really want to prefix with 'Debug'. It's just extra
356 DoLogString(szString
);
362 wxFAIL_MSG(_("unknown log level in wxLog::DoLog"));
366 void wxLog::DoLogString(const char *WXUNUSED(szString
))
368 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
376 // ----------------------------------------------------------------------------
377 // wxLogStderr class implementation
378 // ----------------------------------------------------------------------------
380 wxLogStderr::wxLogStderr(FILE *fp
)
388 void wxLogStderr::DoLogString(const char *szString
)
390 wxString
str(szString
);
396 // under Windows, programs usually don't have stderr at all, so make show the
397 // messages also under debugger
399 OutputDebugString(str
+ '\r');
403 // ----------------------------------------------------------------------------
404 // wxLogStream implementation
405 // ----------------------------------------------------------------------------
407 #if wxUSE_STD_IOSTREAM
408 wxLogStream::wxLogStream(ostream
*ostr
)
416 void wxLogStream::DoLogString(const char *szString
)
418 (*m_ostr
) << szString
<< endl
<< flush
;
424 // ----------------------------------------------------------------------------
425 // wxLogTextCtrl implementation
426 // ----------------------------------------------------------------------------
428 #if wxUSE_STD_IOSTREAM
429 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
430 // DLL mode in wxMSW, can't use it.
431 #if defined(NO_TEXT_WINDOW_STREAM)
433 : wxLogStream(new ostream(pTextCtrl
))
438 wxLogTextCtrl::~wxLogTextCtrl()
444 // ----------------------------------------------------------------------------
445 // wxLogGui implementation
446 // ----------------------------------------------------------------------------
453 void wxLogGui::Flush()
455 if ( !m_bHasMessages
)
458 // do it right now to block any new calls to Flush() while we're here
459 m_bHasMessages
= FALSE
;
463 // concatenate all strings (but not too many to not overfill the msg box)
466 nMsgCount
= m_aMessages
.Count();
468 // start from the most recent message
469 for ( size_t n
= nMsgCount
; n
> 0; n
-- ) {
470 // for Windows strings longer than this value are wrapped (NT 4.0)
471 const size_t nMsgLineWidth
= 156;
473 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
475 if ( nLines
> 25 ) // don't put too many lines in message box
478 str
<< m_aMessages
[n
- 1] << "\n";
482 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
485 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
488 // no undisplayed messages whatsoever
493 // the default behaviour is to discard all informational messages if there
494 // are any errors/warnings.
495 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
502 m_aMessages
.Add(szString
);
503 m_bHasMessages
= TRUE
;
509 // find the top window and set it's status text if it has any
510 wxFrame
*pFrame
= gs_pFrame
;
511 if ( pFrame
== NULL
) {
512 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
513 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
514 pFrame
= (wxFrame
*)pWin
;
518 if ( pFrame
!= NULL
)
519 pFrame
->SetStatusText(szString
);
527 wxString strTime
= TimeStamp();
530 // don't prepend debug/trace here: it goes to the debug window
531 // anyhow, but do put a timestamp
532 OutputDebugString(strTime
+ szString
+ "\n\r");
534 // send them to stderr
535 fprintf(stderr
, "%s %s: %s\n",
537 level
== wxLOG_Trace
? "Trace" : "Debug",
542 #endif // __WXDEBUG__
545 case wxLOG_FatalError
:
546 // show this one immediately
547 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
552 // discard earlier informational messages if this is the 1st error
555 m_bHasMessages
= TRUE
;
559 m_aMessages
.Add(szString
);
563 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
567 // ----------------------------------------------------------------------------
568 // wxLogWindow and wxLogFrame implementation
569 // ----------------------------------------------------------------------------
573 class wxLogFrame
: public wxFrame
577 wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
);
578 virtual ~wxLogFrame();
581 void OnClose(wxCommandEvent
& event
);
582 void OnCloseWindow(wxCloseEvent
& event
);
583 void OnSave (wxCommandEvent
& event
);
584 void OnClear(wxCommandEvent
& event
);
586 void OnIdle(wxIdleEvent
&);
589 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
599 // instead of closing just hide the window to be able to Show() it later
600 void DoClose() { Show(FALSE
); }
602 wxTextCtrl
*m_pTextCtrl
;
605 DECLARE_EVENT_TABLE()
608 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
609 // wxLogWindow menu events
610 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
611 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
612 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
614 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
617 wxLogFrame::wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
)
618 : wxFrame(pParent
, -1, szTitle
)
622 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
623 // a rich edit control instead of a normal one we want in wxMSW
624 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
632 wxMenuBar
*pMenuBar
= new wxMenuBar
;
633 wxMenu
*pMenu
= new wxMenu
;
634 pMenu
->Append(Menu_Save
, _("&Save..."), _("Save log contents to file"));
635 pMenu
->Append(Menu_Clear
, _("C&lear"), _("Clear the log contents"));
636 pMenu
->AppendSeparator();
637 pMenu
->Append(Menu_Close
, _("&Close"), _("Close this window"));
638 pMenuBar
->Append(pMenu
, _("&Log"));
639 SetMenuBar(pMenuBar
);
641 // status bar for menu prompts
644 m_log
->OnFrameCreate(this);
647 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
652 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
657 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
661 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
662 if ( szFileName
== NULL
) {
671 if ( wxFile::Exists(szFileName
) ) {
672 bool bAppend
= FALSE
;
674 strMsg
.Printf(_("Append log to file '%s' "
675 "(choosing [No] will overwrite it)?"), szFileName
);
676 switch ( wxMessageBox(strMsg
, _("Question"), wxYES_NO
| wxCANCEL
) ) {
689 wxFAIL_MSG(_("invalid message box return value"));
693 bOk
= file
.Open(szFileName
, wxFile::write_append
);
696 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
700 bOk
= file
.Create(szFileName
);
703 // retrieve text and save it
704 // -------------------------
705 int nLines
= m_pTextCtrl
->GetNumberOfLines();
706 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
707 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) +
708 // we're not going to pull in the whole wxTextFile if all we need is this...
711 #else // !wxUSE_TEXTFILE
713 #endif // wxUSE_TEXTFILE
721 wxLogError(_("Can't save log contents to file."));
724 wxLogStatus(this, _("Log saved to the file '%s'."), szFileName
);
728 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
730 m_pTextCtrl
->Clear();
733 wxLogFrame::~wxLogFrame()
735 m_log
->OnFrameDelete(this);
740 wxLogWindow::wxLogWindow(wxFrame
*pParent
,
745 m_bPassMessages
= bDoPass
;
747 m_pLogFrame
= new wxLogFrame(pParent
, this, szTitle
);
748 m_pOldLog
= wxLog::SetActiveTarget(this);
751 m_pLogFrame
->Show(TRUE
);
754 void wxLogWindow::Show(bool bShow
)
756 m_pLogFrame
->Show(bShow
);
759 void wxLogWindow::Flush()
761 if ( m_pOldLog
!= NULL
)
764 m_bHasMessages
= FALSE
;
767 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
769 // first let the previous logger show it
770 if ( m_pOldLog
!= NULL
&& m_bPassMessages
) {
771 // @@@ why can't we access protected wxLog method from here (we derive
772 // from wxLog)? gcc gives "DoLog is protected in this context", what
773 // does this mean? Anyhow, the cast is harmless and let's us do what
775 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
781 // by default, these messages are ignored by wxLog, so process
784 wxString str
= TimeStamp();
785 str
<< _("Status: ") << szString
;
790 // don't put trace messages in the text window for 2 reasons:
791 // 1) there are too many of them
792 // 2) they may provoke other trace messages thus sending a program
793 // into an infinite loop
798 // and this will format it nicely and call our DoLogString()
799 wxLog::DoLog(level
, szString
);
803 m_bHasMessages
= TRUE
;
806 void wxLogWindow::DoLogString(const char *szString
)
808 // put the text into our window
809 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
811 // remove selection (WriteText is in fact ReplaceSelection)
813 long nLen
= pText
->GetLastPosition();
814 pText
->SetSelection(nLen
, nLen
);
817 pText
->WriteText(szString
);
818 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
820 // TODO ensure that the line can be seen
823 wxFrame
*wxLogWindow::GetFrame() const
828 void wxLogWindow::OnFrameCreate(wxFrame
* WXUNUSED(frame
))
832 void wxLogWindow::OnFrameDelete(wxFrame
* WXUNUSED(frame
))
834 m_pLogFrame
= (wxLogFrame
*)NULL
;
837 wxLogWindow::~wxLogWindow()
841 // may be NULL if log frame already auto destroyed itself
847 // ============================================================================
848 // Global functions/variables
849 // ============================================================================
851 // ----------------------------------------------------------------------------
853 // ----------------------------------------------------------------------------
854 wxLog
*wxLog::ms_pLogger
= (wxLog
*) NULL
;
855 bool wxLog::ms_doLog
= TRUE
;
856 bool wxLog::ms_bAutoCreate
= TRUE
;
857 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
859 // ----------------------------------------------------------------------------
860 // stdout error logging helper
861 // ----------------------------------------------------------------------------
863 // helper function: wraps the message and justifies it under given position
864 // (looks more pretty on the terminal). Also adds newline at the end.
866 // @@ this is now disabled until I find a portable way of determining the
867 // terminal window size (ok, I found it but does anybody really cares?)
868 #ifdef LOG_PRETTY_WRAP
869 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
871 size_t nMax
= 80; // @@@@
872 size_t nStart
= strlen(pszPrefix
);
876 while ( *psz
!= '\0' ) {
877 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
881 if ( *psz
!= '\0' ) {
883 for ( n
= 0; n
< nStart
; n
++ )
886 // as we wrapped, squeeze all white space
887 while ( isspace(*psz
) )
894 #endif //LOG_PRETTY_WRAP
896 // ----------------------------------------------------------------------------
897 // error code/error message retrieval functions
898 // ----------------------------------------------------------------------------
900 // get error code from syste
901 unsigned long wxSysErrorCode()
905 return ::GetLastError();
907 // @@@@ what to do on Windows 3.1?
915 // get error message from system
916 const char *wxSysErrorMsg(unsigned long nErrCode
)
919 nErrCode
= wxSysErrorCode();
923 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
925 // get error message from system
927 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
929 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
933 // copy it to our buffer and free memory
934 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
935 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
938 // returned string is capitalized and ended with '\r\n' - bad
939 s_szBuf
[0] = (char)wxToLower(s_szBuf
[0]);
940 size_t len
= strlen(s_szBuf
);
943 if ( s_szBuf
[len
- 2] == '\r' )
944 s_szBuf
[len
- 2] = '\0';
953 return strerror(nErrCode
);
957 // ----------------------------------------------------------------------------
959 // ----------------------------------------------------------------------------
967 #elif defined(__WXSTUBS__)
969 #elif defined(__WXMAC__)
980 // this function is called when an assert fails
981 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
983 // this variable can be set to true to suppress "assert failure" messages
984 static bool s_bNoAsserts
= FALSE
;
985 static bool s_bInAssert
= FALSE
;
988 // He-e-e-e-elp!! we're trapped in endless loop
998 char szBuf
[LOG_BUFFER_SIZE
];
1000 // make life easier for people using VC++ IDE: clicking on the message will
1001 // take us immediately to the place of the failed assert
1003 sprintf(szBuf
, "%s(%d): assert failed", szFile
, nLine
);
1005 // make the error message more clear for all the others
1006 sprintf(szBuf
, "Assert failed in file %s at line %d", szFile
, nLine
);
1009 if ( szMsg
!= NULL
) {
1010 strcat(szBuf
, ": ");
1011 strcat(szBuf
, szMsg
);
1017 if ( !s_bNoAsserts
) {
1018 // send it to the normal log destination
1024 strcat(szBuf
, "\nDo you want to stop the program?"
1025 "\nYou can also choose [Cancel] to suppress "
1026 "further warnings.");
1028 switch ( wxMessageBox(szBuf
, _("Debug"),
1029 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
1035 s_bNoAsserts
= TRUE
;
1038 //case wxNO: nothing to do
1043 s_bInAssert
= FALSE
;