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