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