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