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