]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/log.cpp
Changed values passed to SetClientSize() in CreateWidgets() so that buttons are not...
[wxWidgets.git] / src / common / log.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: log.cpp
3// Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 29/01/98
7// RCS-ID: $Id$
8// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9// Licence: wxWindows license
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19#ifdef __GNUG__
20 #pragma implementation "log.h"
21#endif
22
23// For compilers that support precompilation, includes "wx.h".
24#include "wx/wxprec.h"
25
26#ifdef __BORLANDC__
27 #pragma hdrstop
28#endif
29
30// wxWindows
31#ifndef WX_PRECOMP
32 #include "wx/window.h"
33#ifdef __WXMSW__
34 #include "wx/msw/private.h"
35#endif
36 #include "wx/event.h"
37 #include "wx/app.h"
38 #include "wx/string.h"
39 #include "wx/intl.h"
40 #include "wx/menu.h"
41 #include "wx/frame.h"
42 #include "wx/msgdlg.h"
43 #include "wx/filedlg.h"
44 #include "wx/textctrl.h"
45#endif //WX_PRECOMP
46
47#include "wx/file.h"
48#include "wx/textfile.h"
49#include "wx/utils.h"
50#include "wx/wxchar.h"
51#include "wx/log.h"
52
53// other standard headers
54#include <errno.h>
55#include <stdlib.h>
56#include <time.h>
57
58#ifdef __WXMSW__
59 #include <windows.h>
60 // Redefines OutputDebugString if necessary
61 #include "wx/msw/private.h"
62#else //Unix
63 #include <signal.h>
64#endif //Win/Unix
65
66// ----------------------------------------------------------------------------
67// non member functions
68// ----------------------------------------------------------------------------
69
70// define this to enable wrapping of log messages
71//#define LOG_PRETTY_WRAP
72
73#ifdef LOG_PRETTY_WRAP
74 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
75#endif
76
77// ----------------------------------------------------------------------------
78// global variables
79// ----------------------------------------------------------------------------
80
81// we use a global variable to store the frame pointer for wxLogStatus - bad,
82// but it's he easiest way
83static wxFrame *gs_pFrame; // FIXME MT-unsafe
84
85// ============================================================================
86// implementation
87// ============================================================================
88
89// ----------------------------------------------------------------------------
90// implementation of Log functions
91//
92// NB: unfortunately we need all these distinct functions, we can't make them
93// macros and not all compilers inline vararg functions.
94// ----------------------------------------------------------------------------
95
96// log functions can't allocate memory (LogError("out of memory...") should
97// work!), so we use a static buffer for all log messages
98#define LOG_BUFFER_SIZE (4096)
99
100// static buffer for error messages (FIXME MT-unsafe)
101static wxChar s_szBuf[LOG_BUFFER_SIZE];
102
103// generic log function
104void wxLogGeneric(wxLogLevel level, const wxChar *szFormat, ...)
105{
106 if ( wxLog::GetActiveTarget() != NULL ) {
107 va_list argptr;
108 va_start(argptr, szFormat);
109 wxVsprintf(s_szBuf, szFormat, argptr);
110 va_end(argptr);
111
112 wxLog::OnLog(level, s_szBuf, time(NULL));
113 }
114}
115
116#define IMPLEMENT_LOG_FUNCTION(level) \
117 void wxLog##level(const wxChar *szFormat, ...) \
118 { \
119 if ( wxLog::GetActiveTarget() != NULL ) { \
120 va_list argptr; \
121 va_start(argptr, szFormat); \
122 wxVsprintf(s_szBuf, szFormat, argptr); \
123 va_end(argptr); \
124 \
125 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
126 } \
127 }
128
129IMPLEMENT_LOG_FUNCTION(FatalError)
130IMPLEMENT_LOG_FUNCTION(Error)
131IMPLEMENT_LOG_FUNCTION(Warning)
132IMPLEMENT_LOG_FUNCTION(Message)
133IMPLEMENT_LOG_FUNCTION(Info)
134IMPLEMENT_LOG_FUNCTION(Status)
135
136// accepts an additional argument which tells to which frame the output should
137// be directed
138void wxLogStatus(wxFrame *pFrame, const wxChar *szFormat, ...)
139{
140 wxLog *pLog = wxLog::GetActiveTarget();
141 if ( pLog != NULL ) {
142 va_list argptr;
143 va_start(argptr, szFormat);
144 wxVsprintf(s_szBuf, szFormat, argptr);
145 va_end(argptr);
146
147 wxASSERT( gs_pFrame == NULL ); // should be reset!
148 gs_pFrame = pFrame;
149 wxLog::OnLog(wxLOG_Status, s_szBuf, time(NULL));
150 gs_pFrame = (wxFrame *) NULL;
151 }
152}
153
154// same as info, but only if 'verbose' mode is on
155void wxLogVerbose(const wxChar *szFormat, ...)
156{
157 wxLog *pLog = wxLog::GetActiveTarget();
158 if ( pLog != NULL && pLog->GetVerbose() ) {
159 va_list argptr;
160 va_start(argptr, szFormat);
161 wxVsprintf(s_szBuf, szFormat, argptr);
162 va_end(argptr);
163
164 wxLog::OnLog(wxLOG_Info, s_szBuf, time(NULL));
165 }
166}
167
168// debug functions
169#ifdef __WXDEBUG__
170#define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
171 void wxLog##level(const wxChar *szFormat, ...) \
172 { \
173 if ( wxLog::GetActiveTarget() != NULL ) { \
174 va_list argptr; \
175 va_start(argptr, szFormat); \
176 wxVsprintf(s_szBuf, szFormat, argptr); \
177 va_end(argptr); \
178 \
179 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
180 } \
181 }
182
183 void wxLogTrace(const wxChar *mask, const wxChar *szFormat, ...)
184 {
185 wxLog *pLog = wxLog::GetActiveTarget();
186
187 if ( pLog != NULL && wxLog::IsAllowedTraceMask(mask) ) {
188 va_list argptr;
189 va_start(argptr, szFormat);
190 wxVsprintf(s_szBuf, szFormat, argptr);
191 va_end(argptr);
192
193 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
194 }
195 }
196
197 void wxLogTrace(wxTraceMask mask, const wxChar *szFormat, ...)
198 {
199 wxLog *pLog = wxLog::GetActiveTarget();
200
201 // we check that all of mask bits are set in the current mask, so
202 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
203 // if both bits are set.
204 if ( pLog != NULL && ((pLog->GetTraceMask() & mask) == mask) ) {
205 va_list argptr;
206 va_start(argptr, szFormat);
207 wxVsprintf(s_szBuf, szFormat, argptr);
208 va_end(argptr);
209
210 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
211 }
212 }
213
214#else // release
215 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
216#endif
217
218IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
219IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
220
221// wxLogSysError: one uses the last error code, for other you must give it
222// explicitly
223
224// common part of both wxLogSysError
225void wxLogSysErrorHelper(long lErrCode)
226{
227 wxChar szErrMsg[LOG_BUFFER_SIZE / 2];
228 wxSprintf(szErrMsg, _(" (error %ld: %s)"), lErrCode, wxSysErrorMsg(lErrCode));
229 wxStrncat(s_szBuf, szErrMsg, WXSIZEOF(s_szBuf) - wxStrlen(s_szBuf));
230
231 wxLog::OnLog(wxLOG_Error, s_szBuf, time(NULL));
232}
233
234void WXDLLEXPORT wxLogSysError(const wxChar *szFormat, ...)
235{
236 va_list argptr;
237 va_start(argptr, szFormat);
238 wxVsprintf(s_szBuf, szFormat, argptr);
239 va_end(argptr);
240
241 wxLogSysErrorHelper(wxSysErrorCode());
242}
243
244void WXDLLEXPORT wxLogSysError(long lErrCode, const wxChar *szFormat, ...)
245{
246 va_list argptr;
247 va_start(argptr, szFormat);
248 wxVsprintf(s_szBuf, szFormat, argptr);
249 va_end(argptr);
250
251 wxLogSysErrorHelper(lErrCode);
252}
253
254// ----------------------------------------------------------------------------
255// wxLog class implementation
256// ----------------------------------------------------------------------------
257
258wxLog::wxLog()
259{
260 m_bHasMessages = FALSE;
261
262 // enable verbose messages by default in the debug builds
263#ifdef __WXDEBUG__
264 m_bVerbose = TRUE;
265#else // release
266 m_bVerbose = FALSE;
267#endif // debug/release
268}
269
270wxLog *wxLog::GetActiveTarget()
271{
272 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
273 // prevent infinite recursion if someone calls wxLogXXX() from
274 // wxApp::CreateLogTarget()
275 static bool s_bInGetActiveTarget = FALSE;
276 if ( !s_bInGetActiveTarget ) {
277 s_bInGetActiveTarget = TRUE;
278
279#ifdef wxUSE_NOGUI
280 ms_pLogger = new wxLogStderr;
281#else
282 // ask the application to create a log target for us
283 if ( wxTheApp != NULL )
284 ms_pLogger = wxTheApp->CreateLogTarget();
285 else
286 ms_pLogger = new wxLogStderr;
287#endif
288
289 s_bInGetActiveTarget = FALSE;
290
291 // do nothing if it fails - what can we do?
292 }
293 }
294
295 return ms_pLogger;
296}
297
298wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
299{
300 if ( ms_pLogger != NULL ) {
301 // flush the old messages before changing because otherwise they might
302 // get lost later if this target is not restored
303 ms_pLogger->Flush();
304 }
305
306 wxLog *pOldLogger = ms_pLogger;
307 ms_pLogger = pLogger;
308
309 return pOldLogger;
310}
311
312void wxLog::RemoveTraceMask(const wxString& str)
313{
314 int index = ms_aTraceMasks.Index(str);
315 if ( index != wxNOT_FOUND )
316 ms_aTraceMasks.Remove((size_t)index);
317}
318
319void wxLog::TimeStamp(wxString *str)
320{
321 if ( ms_timestamp )
322 {
323 wxChar buf[256];
324 time_t timeNow;
325 (void)time(&timeNow);
326 wxStrftime(buf, WXSIZEOF(buf), ms_timestamp, localtime(&timeNow));
327
328 str->Empty();
329 *str << buf << _T(": ");
330 }
331}
332
333void wxLog::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
334{
335 switch ( level ) {
336 case wxLOG_FatalError:
337 DoLogString(wxString(_("Fatal error: ")) + szString, t);
338 DoLogString(_("Program aborted."), t);
339 Flush();
340 abort();
341 break;
342
343 case wxLOG_Error:
344 DoLogString(wxString(_("Error: ")) + szString, t);
345 break;
346
347 case wxLOG_Warning:
348 DoLogString(wxString(_("Warning: ")) + szString, t);
349 break;
350
351 case wxLOG_Info:
352 if ( GetVerbose() )
353 case wxLOG_Message:
354 default: // log unknown log levels too
355 DoLogString(szString, t);
356 // fall through
357
358 case wxLOG_Status:
359 // nothing to do
360 break;
361
362 case wxLOG_Trace:
363 case wxLOG_Debug:
364#ifdef __WXDEBUG__
365 DoLogString(szString, t);
366#endif
367 break;
368 }
369}
370
371void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t WXUNUSED(t))
372{
373 wxFAIL_MSG(_T("DoLogString must be overriden if it's called."));
374}
375
376void wxLog::Flush()
377{
378 // do nothing
379}
380
381// ----------------------------------------------------------------------------
382// wxLogStderr class implementation
383// ----------------------------------------------------------------------------
384
385wxLogStderr::wxLogStderr(FILE *fp)
386{
387 if ( fp == NULL )
388 m_fp = stderr;
389 else
390 m_fp = fp;
391}
392
393void wxLogStderr::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
394{
395 wxString str;
396 TimeStamp(&str);
397 str << szString << _T('\n');
398
399 fputs(str.mb_str(), m_fp);
400 fflush(m_fp);
401
402 // under Windows, programs usually don't have stderr at all, so make show the
403 // messages also under debugger
404#ifdef __WXMSW__
405 OutputDebugString(str + _T('\r'));
406#endif // MSW
407}
408
409// ----------------------------------------------------------------------------
410// wxLogStream implementation
411// ----------------------------------------------------------------------------
412
413#if wxUSE_STD_IOSTREAM
414wxLogStream::wxLogStream(ostream *ostr)
415{
416 if ( ostr == NULL )
417 m_ostr = &cerr;
418 else
419 m_ostr = ostr;
420}
421
422void wxLogStream::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
423{
424 (*m_ostr) << wxConvCurrent->cWX2MB(szString) << endl << flush;
425}
426#endif // wxUSE_STD_IOSTREAM
427
428#ifndef wxUSE_NOGUI
429
430// ----------------------------------------------------------------------------
431// wxLogTextCtrl implementation
432// ----------------------------------------------------------------------------
433
434wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
435{
436 m_pTextCtrl = pTextCtrl;
437}
438
439void wxLogTextCtrl::DoLogString(const wxChar *szString, time_t t)
440{
441 wxString msg;
442 TimeStamp(&msg);
443 msg << szString << _T('\n');
444
445 m_pTextCtrl->AppendText(msg);
446}
447
448// ----------------------------------------------------------------------------
449// wxLogGui implementation (FIXME MT-unsafe)
450// ----------------------------------------------------------------------------
451
452wxLogGui::wxLogGui()
453{
454 Clear();
455}
456
457void wxLogGui::Clear()
458{
459 m_bErrors = m_bWarnings = FALSE;
460 m_aMessages.Empty();
461 m_aTimes.Empty();
462}
463
464void wxLogGui::Flush()
465{
466 if ( !m_bHasMessages )
467 return;
468
469 // do it right now to block any new calls to Flush() while we're here
470 m_bHasMessages = FALSE;
471
472 // concatenate all strings (but not too many to not overfill the msg box)
473 wxString str;
474 size_t nLines = 0,
475 nMsgCount = m_aMessages.Count();
476
477 // start from the most recent message
478 for ( size_t n = nMsgCount; n > 0; n-- ) {
479 // for Windows strings longer than this value are wrapped (NT 4.0)
480 const size_t nMsgLineWidth = 156;
481
482 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
483
484 if ( nLines > 25 ) // don't put too many lines in message box
485 break;
486
487 str << m_aMessages[n - 1] << _T("\n");
488 }
489
490 const wxChar *title;
491 long style;
492
493 if ( m_bErrors ) {
494 title = _("Error");
495 style = wxICON_STOP;
496 }
497 else if ( m_bWarnings ) {
498 title = _("Warning");
499 style = wxICON_EXCLAMATION;
500 }
501 else {
502 title = _("Information");
503 style = wxICON_INFORMATION;
504 }
505
506 wxMessageBox(str, title, wxOK | style);
507
508 // no undisplayed messages whatsoever
509 Clear();
510}
511
512// the default behaviour is to discard all informational messages if there
513// are any errors/warnings.
514void wxLogGui::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
515{
516 switch ( level ) {
517 case wxLOG_Info:
518 if ( GetVerbose() )
519 case wxLOG_Message:
520 if ( !m_bErrors ) {
521 m_aMessages.Add(szString);
522 m_aTimes.Add((long)t);
523 m_bHasMessages = TRUE;
524 }
525 break;
526
527 case wxLOG_Status:
528#if wxUSE_STATUSBAR
529 {
530 // find the top window and set it's status text if it has any
531 wxFrame *pFrame = gs_pFrame;
532 if ( pFrame == NULL ) {
533 wxWindow *pWin = wxTheApp->GetTopWindow();
534 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
535 pFrame = (wxFrame *)pWin;
536 }
537 }
538
539 if ( pFrame != NULL )
540 pFrame->SetStatusText(szString);
541 }
542#endif // wxUSE_STATUSBAR
543 break;
544
545 case wxLOG_Trace:
546 case wxLOG_Debug:
547 #ifdef __WXDEBUG__
548 {
549 #ifdef __WXMSW__
550 // don't prepend debug/trace here: it goes to the
551 // debug window anyhow, but do put a timestamp
552 wxString str;
553 TimeStamp(&str);
554 str << szString << _T("\n\r");
555 OutputDebugString(str);
556 #else
557 // send them to stderr
558 wxFprintf(stderr, _T("%s: %s\n"),
559 level == wxLOG_Trace ? _T("Trace")
560 : _T("Debug"),
561 szString);
562 fflush(stderr);
563 #endif
564 }
565 #endif // __WXDEBUG__
566
567 break;
568
569 case wxLOG_FatalError:
570 // show this one immediately
571 wxMessageBox(szString, _("Fatal error"), wxICON_HAND);
572 break;
573
574 case wxLOG_Error:
575 // discard earlier informational messages if this is the 1st
576 // error because they might not make sense any more
577 if ( !m_bErrors ) {
578 m_aMessages.Empty();
579 m_aTimes.Empty();
580 m_bErrors = TRUE;
581 }
582 // fall through
583
584 case wxLOG_Warning:
585 if ( !m_bErrors ) {
586 // for the warning we don't discard the info messages
587 m_bWarnings = TRUE;
588 }
589
590 m_aMessages.Add(szString);
591 m_aTimes.Add((long)t);
592 m_bHasMessages = TRUE;
593 break;
594 }
595}
596
597// ----------------------------------------------------------------------------
598// wxLogWindow and wxLogFrame implementation
599// ----------------------------------------------------------------------------
600
601// log frame class
602// ---------------
603class wxLogFrame : public wxFrame
604{
605public:
606 // ctor & dtor
607 wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle);
608 virtual ~wxLogFrame();
609
610 // menu callbacks
611 void OnClose(wxCommandEvent& event);
612 void OnCloseWindow(wxCloseEvent& event);
613#if wxUSE_FILE
614 void OnSave (wxCommandEvent& event);
615#endif // wxUSE_FILE
616 void OnClear(wxCommandEvent& event);
617
618 void OnIdle(wxIdleEvent&);
619
620 // accessors
621 wxTextCtrl *TextCtrl() const { return m_pTextCtrl; }
622
623private:
624 enum
625 {
626 Menu_Close = 100,
627 Menu_Save,
628 Menu_Clear
629 };
630
631 // instead of closing just hide the window to be able to Show() it later
632 void DoClose() { Show(FALSE); }
633
634 wxTextCtrl *m_pTextCtrl;
635 wxLogWindow *m_log;
636
637 DECLARE_EVENT_TABLE()
638};
639
640BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
641 // wxLogWindow menu events
642 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
643#if wxUSE_FILE
644 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
645#endif // wxUSE_FILE
646 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
647
648 EVT_CLOSE(wxLogFrame::OnCloseWindow)
649END_EVENT_TABLE()
650
651wxLogFrame::wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle)
652 : wxFrame(pParent, -1, szTitle)
653{
654 m_log = log;
655
656 m_pTextCtrl = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition,
657 wxDefaultSize,
658 wxTE_MULTILINE |
659 wxHSCROLL |
660 wxTE_READONLY);
661
662 // create menu
663 wxMenuBar *pMenuBar = new wxMenuBar;
664 wxMenu *pMenu = new wxMenu;
665#if wxUSE_FILE
666 pMenu->Append(Menu_Save, _("&Save..."), _("Save log contents to file"));
667#endif // wxUSE_FILE
668 pMenu->Append(Menu_Clear, _("C&lear"), _("Clear the log contents"));
669 pMenu->AppendSeparator();
670 pMenu->Append(Menu_Close, _("&Close"), _("Close this window"));
671 pMenuBar->Append(pMenu, _("&Log"));
672 SetMenuBar(pMenuBar);
673
674#if wxUSE_STATUSBAR
675 // status bar for menu prompts
676 CreateStatusBar();
677#endif // wxUSE_STATUSBAR
678
679 m_log->OnFrameCreate(this);
680}
681
682void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
683{
684 DoClose();
685}
686
687void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
688{
689 DoClose();
690}
691
692#if wxUSE_FILE
693void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
694{
695 // get the file name
696 // -----------------
697 const wxChar *szFileName = wxSaveFileSelector(_T("log"), _T("txt"), _T("log.txt"));
698 if ( szFileName == NULL ) {
699 // cancelled
700 return;
701 }
702
703 // open file
704 // ---------
705 wxFile file;
706 bool bOk = FALSE;
707 if ( wxFile::Exists(szFileName) ) {
708 bool bAppend = FALSE;
709 wxString strMsg;
710 strMsg.Printf(_("Append log to file '%s' "
711 "(choosing [No] will overwrite it)?"), szFileName);
712 switch ( wxMessageBox(strMsg, _("Question"), wxYES_NO | wxCANCEL) ) {
713 case wxYES:
714 bAppend = TRUE;
715 break;
716
717 case wxNO:
718 bAppend = FALSE;
719 break;
720
721 case wxCANCEL:
722 return;
723
724 default:
725 wxFAIL_MSG(_("invalid message box return value"));
726 }
727
728 if ( bAppend ) {
729 bOk = file.Open(szFileName, wxFile::write_append);
730 }
731 else {
732 bOk = file.Create(szFileName, TRUE /* overwrite */);
733 }
734 }
735 else {
736 bOk = file.Create(szFileName);
737 }
738
739 // retrieve text and save it
740 // -------------------------
741 int nLines = m_pTextCtrl->GetNumberOfLines();
742 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
743 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) +
744 // we're not going to pull in the whole wxTextFile if all we need is this...
745#if wxUSE_TEXTFILE
746 wxTextFile::GetEOL()
747#else // !wxUSE_TEXTFILE
748 '\n'
749#endif // wxUSE_TEXTFILE
750 );
751 }
752
753 if ( bOk )
754 bOk = file.Close();
755
756 if ( !bOk ) {
757 wxLogError(_("Can't save log contents to file."));
758 }
759 else {
760 wxLogStatus(this, _("Log saved to the file '%s'."), szFileName);
761 }
762}
763#endif // wxUSE_FILE
764
765void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
766{
767 m_pTextCtrl->Clear();
768}
769
770wxLogFrame::~wxLogFrame()
771{
772 m_log->OnFrameDelete(this);
773}
774
775// wxLogWindow
776// -----------
777wxLogWindow::wxLogWindow(wxFrame *pParent,
778 const wxChar *szTitle,
779 bool bShow,
780 bool bDoPass)
781{
782 m_bPassMessages = bDoPass;
783
784 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
785 m_pOldLog = wxLog::SetActiveTarget(this);
786
787 if ( bShow )
788 m_pLogFrame->Show(TRUE);
789}
790
791void wxLogWindow::Show(bool bShow)
792{
793 m_pLogFrame->Show(bShow);
794}
795
796void wxLogWindow::Flush()
797{
798 if ( m_pOldLog != NULL )
799 m_pOldLog->Flush();
800
801 m_bHasMessages = FALSE;
802}
803
804void wxLogWindow::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
805{
806 // first let the previous logger show it
807 if ( m_pOldLog != NULL && m_bPassMessages ) {
808 // FIXME why can't we access protected wxLog method from here (we derive
809 // from wxLog)? gcc gives "DoLog is protected in this context", what
810 // does this mean? Anyhow, the cast is harmless and let's us do what
811 // we want.
812 ((wxLogWindow *)m_pOldLog)->DoLog(level, szString, t);
813 }
814
815 if ( m_pLogFrame ) {
816 switch ( level ) {
817 case wxLOG_Status:
818 // by default, these messages are ignored by wxLog, so process
819 // them ourselves
820 if ( !wxIsEmpty(szString) )
821 {
822 wxString str;
823 str << _("Status: ") << szString;
824 DoLogString(str, t);
825 }
826 break;
827
828 // don't put trace messages in the text window for 2 reasons:
829 // 1) there are too many of them
830 // 2) they may provoke other trace messages thus sending a program
831 // into an infinite loop
832 case wxLOG_Trace:
833 break;
834
835 default:
836 // and this will format it nicely and call our DoLogString()
837 wxLog::DoLog(level, szString, t);
838 }
839 }
840
841 m_bHasMessages = TRUE;
842}
843
844void wxLogWindow::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
845{
846 // put the text into our window
847 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
848
849 // remove selection (WriteText is in fact ReplaceSelection)
850#ifdef __WXMSW__
851 long nLen = pText->GetLastPosition();
852 pText->SetSelection(nLen, nLen);
853#endif // Windows
854
855 wxString msg;
856 TimeStamp(&msg);
857 msg << szString << _T('\n');
858
859 pText->AppendText(msg);
860
861 // TODO ensure that the line can be seen
862}
863
864wxFrame *wxLogWindow::GetFrame() const
865{
866 return m_pLogFrame;
867}
868
869void wxLogWindow::OnFrameCreate(wxFrame * WXUNUSED(frame))
870{
871}
872
873void wxLogWindow::OnFrameDelete(wxFrame * WXUNUSED(frame))
874{
875 m_pLogFrame = (wxLogFrame *)NULL;
876}
877
878wxLogWindow::~wxLogWindow()
879{
880 delete m_pOldLog;
881
882 // may be NULL if log frame already auto destroyed itself
883 delete m_pLogFrame;
884}
885
886#endif //wxUSE_NOGUI
887
888// ============================================================================
889// Global functions/variables
890// ============================================================================
891
892// ----------------------------------------------------------------------------
893// static variables
894// ----------------------------------------------------------------------------
895
896wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
897bool wxLog::ms_doLog = TRUE;
898bool wxLog::ms_bAutoCreate = TRUE;
899
900const wxChar *wxLog::ms_timestamp = _T("%X"); // time only, no date
901
902wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
903wxArrayString wxLog::ms_aTraceMasks;
904
905// ----------------------------------------------------------------------------
906// stdout error logging helper
907// ----------------------------------------------------------------------------
908
909// helper function: wraps the message and justifies it under given position
910// (looks more pretty on the terminal). Also adds newline at the end.
911//
912// TODO this is now disabled until I find a portable way of determining the
913// terminal window size (ok, I found it but does anybody really cares?)
914#ifdef LOG_PRETTY_WRAP
915static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
916{
917 size_t nMax = 80; // FIXME
918 size_t nStart = strlen(pszPrefix);
919 fputs(pszPrefix, f);
920
921 size_t n;
922 while ( *psz != '\0' ) {
923 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
924 putc(*psz++, f);
925
926 // wrapped?
927 if ( *psz != '\0' ) {
928 /*putc('\n', f);*/
929 for ( n = 0; n < nStart; n++ )
930 putc(' ', f);
931
932 // as we wrapped, squeeze all white space
933 while ( isspace(*psz) )
934 psz++;
935 }
936 }
937
938 putc('\n', f);
939}
940#endif //LOG_PRETTY_WRAP
941
942// ----------------------------------------------------------------------------
943// error code/error message retrieval functions
944// ----------------------------------------------------------------------------
945
946// get error code from syste
947unsigned long wxSysErrorCode()
948{
949#ifdef __WXMSW__
950#ifdef __WIN32__
951 return ::GetLastError();
952#else //WIN16
953 // TODO what to do on Windows 3.1?
954 return 0;
955#endif //WIN16/32
956#else //Unix
957 return errno;
958#endif //Win/Unix
959}
960
961// get error message from system
962const wxChar *wxSysErrorMsg(unsigned long nErrCode)
963{
964 if ( nErrCode == 0 )
965 nErrCode = wxSysErrorCode();
966
967#ifdef __WXMSW__
968#ifdef __WIN32__
969 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
970
971 // get error message from system
972 LPVOID lpMsgBuf;
973 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
974 NULL, nErrCode,
975 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
976 (LPTSTR)&lpMsgBuf,
977 0, NULL);
978
979 // copy it to our buffer and free memory
980 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
981 s_szBuf[WXSIZEOF(s_szBuf) - 1] = _T('\0');
982 LocalFree(lpMsgBuf);
983
984 // returned string is capitalized and ended with '\r\n' - bad
985 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
986 size_t len = wxStrlen(s_szBuf);
987 if ( len > 0 ) {
988 // truncate string
989 if ( s_szBuf[len - 2] == _T('\r') )
990 s_szBuf[len - 2] = _T('\0');
991 }
992
993 return s_szBuf;
994#else //Win16
995 // TODO
996 return NULL;
997#endif // Win16/32
998#else // Unix
999#if wxUSE_UNICODE
1000 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
1001 wxConvCurrent->MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
1002 return s_szBuf;
1003#else
1004 return strerror(nErrCode);
1005#endif
1006#endif // Win/Unix
1007}
1008
1009// ----------------------------------------------------------------------------
1010// debug helper
1011// ----------------------------------------------------------------------------
1012
1013#ifdef __WXDEBUG__
1014
1015// break into the debugger
1016void Trap()
1017{
1018#ifdef __WXMSW__
1019 DebugBreak();
1020#elif defined(__WXMAC__)
1021#if __powerc
1022 Debugger();
1023#else
1024 SysBreak();
1025#endif
1026#elif defined(__UNIX__)
1027 raise(SIGTRAP);
1028#else
1029 // TODO
1030#endif // Win/Unix
1031}
1032
1033// this function is called when an assert fails
1034void wxOnAssert(const wxChar *szFile, int nLine, const wxChar *szMsg)
1035{
1036 // this variable can be set to true to suppress "assert failure" messages
1037 static bool s_bNoAsserts = FALSE;
1038 static bool s_bInAssert = FALSE; // FIXME MT-unsafe
1039
1040 if ( s_bInAssert ) {
1041 // He-e-e-e-elp!! we're trapped in endless loop
1042 Trap();
1043
1044 s_bInAssert = FALSE;
1045
1046 return;
1047 }
1048
1049 s_bInAssert = TRUE;
1050
1051 wxChar szBuf[LOG_BUFFER_SIZE];
1052
1053 // make life easier for people using VC++ IDE: clicking on the message
1054 // will take us immediately to the place of the failed assert
1055#ifdef __VISUALC__
1056 wxSprintf(szBuf, _T("%s(%d): assert failed"), szFile, nLine);
1057#else // !VC++
1058 // make the error message more clear for all the others
1059 wxSprintf(szBuf, _T("Assert failed in file %s at line %d"), szFile, nLine);
1060#endif // VC/!VC
1061
1062 if ( szMsg != NULL ) {
1063 wxStrcat(szBuf, _T(": "));
1064 wxStrcat(szBuf, szMsg);
1065 }
1066 else {
1067 wxStrcat(szBuf, _T("."));
1068 }
1069
1070 if ( !s_bNoAsserts ) {
1071 // send it to the normal log destination
1072 wxLogDebug(szBuf);
1073
1074#if wxUSE_NOGUI
1075 Trap();
1076#else
1077 // this message is intentionally not translated - it is for
1078 // developpers only
1079 wxStrcat(szBuf, _T("\nDo you want to stop the program?"
1080 "\nYou can also choose [Cancel] to suppress "
1081 "further warnings."));
1082
1083 switch ( wxMessageBox(szBuf, _("Debug"),
1084 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
1085 case wxYES:
1086 Trap();
1087 break;
1088
1089 case wxCANCEL:
1090 s_bNoAsserts = TRUE;
1091 break;
1092
1093 //case wxNO: nothing to do
1094 }
1095#endif // USE_NOGUI
1096 }
1097
1098 s_bInAssert = FALSE;
1099}
1100
1101#endif //WXDEBUG
1102