]> git.saurik.com Git - wxWidgets.git/blob - src/common/log.cpp
Completed Vadims HAVE_BOOL changes
[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 overriden 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 wxString str(szString);
391 str << '\n';
392
393 fputs(str, m_fp);
394 fflush(m_fp);
395
396 // under Windows, programs usually don't have stderr at all, so make show the
397 // messages also under debugger
398 #ifdef __WXMSW__
399 OutputDebugString(str + '\r');
400 #endif // MSW
401 }
402
403 // ----------------------------------------------------------------------------
404 // wxLogStream implementation
405 // ----------------------------------------------------------------------------
406
407 #if wxUSE_STD_IOSTREAM
408 wxLogStream::wxLogStream(ostream *ostr)
409 {
410 if ( ostr == NULL )
411 m_ostr = &cerr;
412 else
413 m_ostr = ostr;
414 }
415
416 void wxLogStream::DoLogString(const char *szString)
417 {
418 (*m_ostr) << szString << endl << flush;
419 }
420 #endif
421
422 #ifndef wxUSE_NOGUI
423
424 // ----------------------------------------------------------------------------
425 // wxLogTextCtrl implementation
426 // ----------------------------------------------------------------------------
427
428 #if wxUSE_STD_IOSTREAM
429 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
430 // DLL mode in wxMSW, can't use it.
431 #if defined(NO_TEXT_WINDOW_STREAM)
432 #else
433 : wxLogStream(new ostream(pTextCtrl))
434 #endif
435 {
436 }
437
438 wxLogTextCtrl::~wxLogTextCtrl()
439 {
440 delete m_ostr;
441 }
442 #endif
443
444 // ----------------------------------------------------------------------------
445 // wxLogGui implementation
446 // ----------------------------------------------------------------------------
447
448 wxLogGui::wxLogGui()
449 {
450 m_bErrors = FALSE;
451 }
452
453 void wxLogGui::Flush()
454 {
455 if ( !m_bHasMessages )
456 return;
457
458 // do it right now to block any new calls to Flush() while we're here
459 m_bHasMessages = FALSE;
460
461 // @@@ ugly...
462
463 // concatenate all strings (but not too many to not overfill the msg box)
464 wxString str;
465 size_t nLines = 0,
466 nMsgCount = m_aMessages.Count();
467
468 // start from the most recent message
469 for ( size_t n = nMsgCount; n > 0; n-- ) {
470 // for Windows strings longer than this value are wrapped (NT 4.0)
471 const size_t nMsgLineWidth = 156;
472
473 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
474
475 if ( nLines > 25 ) // don't put too many lines in message box
476 break;
477
478 str << m_aMessages[n - 1] << "\n";
479 }
480
481 if ( m_bErrors ) {
482 wxMessageBox(str, _("Error"), wxOK | wxICON_EXCLAMATION);
483 }
484 else {
485 wxMessageBox(str, _("Information"), wxOK | wxICON_INFORMATION);
486 }
487
488 // no undisplayed messages whatsoever
489 m_bErrors = FALSE;
490 m_aMessages.Empty();
491 }
492
493 // the default behaviour is to discard all informational messages if there
494 // are any errors/warnings.
495 void wxLogGui::DoLog(wxLogLevel level, const char *szString)
496 {
497 switch ( level ) {
498 case wxLOG_Info:
499 if ( GetVerbose() )
500 case wxLOG_Message:
501 if ( !m_bErrors ) {
502 m_aMessages.Add(szString);
503 m_bHasMessages = TRUE;
504 }
505 break;
506
507 case wxLOG_Status:
508 {
509 // find the top window and set it's status text if it has any
510 wxFrame *pFrame = gs_pFrame;
511 if ( pFrame == NULL ) {
512 wxWindow *pWin = wxTheApp->GetTopWindow();
513 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
514 pFrame = (wxFrame *)pWin;
515 }
516 }
517
518 if ( pFrame != NULL )
519 pFrame->SetStatusText(szString);
520 }
521 break;
522
523 case wxLOG_Trace:
524 case wxLOG_Debug:
525 #ifdef __WXDEBUG__
526 {
527 wxString strTime = TimeStamp();
528
529 #ifdef __WXMSW__
530 // don't prepend debug/trace here: it goes to the debug window
531 // anyhow, but do put a timestamp
532 OutputDebugString(strTime + szString + "\n\r");
533 #else
534 // send them to stderr
535 fprintf(stderr, "%s %s: %s\n",
536 strTime.c_str(),
537 level == wxLOG_Trace ? "Trace" : "Debug",
538 szString);
539 fflush(stderr);
540 #endif
541 }
542 #endif // __WXDEBUG__
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 case wxLOG_Warning:
552 // discard earlier informational messages if this is the 1st error
553 if ( !m_bErrors ) {
554 m_aMessages.Empty();
555 m_bHasMessages = TRUE;
556 m_bErrors = TRUE;
557 }
558
559 m_aMessages.Add(szString);
560 break;
561
562 default:
563 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
564 }
565 }
566
567 // ----------------------------------------------------------------------------
568 // wxLogWindow and wxLogFrame implementation
569 // ----------------------------------------------------------------------------
570
571 // log frame class
572 // ---------------
573 class wxLogFrame : public wxFrame
574 {
575 public:
576 // ctor & dtor
577 wxLogFrame(wxFrame *pParent, wxLogWindow *log, const char *szTitle);
578 virtual ~wxLogFrame();
579
580 // menu callbacks
581 void OnClose(wxCommandEvent& event);
582 void OnCloseWindow(wxCloseEvent& event);
583 void OnSave (wxCommandEvent& event);
584 void OnClear(wxCommandEvent& event);
585
586 void OnIdle(wxIdleEvent&);
587
588 // accessors
589 wxTextCtrl *TextCtrl() const { return m_pTextCtrl; }
590
591 private:
592 enum
593 {
594 Menu_Close = 100,
595 Menu_Save,
596 Menu_Clear
597 };
598
599 // instead of closing just hide the window to be able to Show() it later
600 void DoClose() { Show(FALSE); }
601
602 wxTextCtrl *m_pTextCtrl;
603 wxLogWindow *m_log;
604
605 DECLARE_EVENT_TABLE()
606 };
607
608 BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
609 // wxLogWindow menu events
610 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
611 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
612 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
613
614 EVT_CLOSE(wxLogFrame::OnCloseWindow)
615 END_EVENT_TABLE()
616
617 wxLogFrame::wxLogFrame(wxFrame *pParent, wxLogWindow *log, const char *szTitle)
618 : wxFrame(pParent, -1, szTitle)
619 {
620 m_log = log;
621
622 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
623 // a rich edit control instead of a normal one we want in wxMSW
624 m_pTextCtrl = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition,
625 wxDefaultSize,
626 //wxSIMPLE_BORDER |
627 wxTE_MULTILINE |
628 wxHSCROLL |
629 wxTE_READONLY);
630
631 // create menu
632 wxMenuBar *pMenuBar = new wxMenuBar;
633 wxMenu *pMenu = new wxMenu;
634 pMenu->Append(Menu_Save, _("&Save..."), _("Save log contents to file"));
635 pMenu->Append(Menu_Clear, _("C&lear"), _("Clear the log contents"));
636 pMenu->AppendSeparator();
637 pMenu->Append(Menu_Close, _("&Close"), _("Close this window"));
638 pMenuBar->Append(pMenu, _("&Log"));
639 SetMenuBar(pMenuBar);
640
641 // status bar for menu prompts
642 CreateStatusBar();
643
644 m_log->OnFrameCreate(this);
645 }
646
647 void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
648 {
649 DoClose();
650 }
651
652 void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
653 {
654 DoClose();
655 }
656
657 void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
658 {
659 // get the file name
660 // -----------------
661 const char *szFileName = wxSaveFileSelector("log", "txt", "log.txt");
662 if ( szFileName == NULL ) {
663 // cancelled
664 return;
665 }
666
667 // open file
668 // ---------
669 wxFile file;
670 bool bOk = FALSE;
671 if ( wxFile::Exists(szFileName) ) {
672 bool bAppend = FALSE;
673 wxString strMsg;
674 strMsg.Printf(_("Append log to file '%s' "
675 "(choosing [No] will overwrite it)?"), szFileName);
676 switch ( wxMessageBox(strMsg, _("Question"), wxYES_NO | wxCANCEL) ) {
677 case wxYES:
678 bAppend = TRUE;
679 break;
680
681 case wxNO:
682 bAppend = FALSE;
683 break;
684
685 case wxCANCEL:
686 return;
687
688 default:
689 wxFAIL_MSG(_("invalid message box return value"));
690 }
691
692 if ( bAppend ) {
693 bOk = file.Open(szFileName, wxFile::write_append);
694 }
695 else {
696 bOk = file.Create(szFileName, TRUE /* overwrite */);
697 }
698 }
699 else {
700 bOk = file.Create(szFileName);
701 }
702
703 // retrieve text and save it
704 // -------------------------
705 int nLines = m_pTextCtrl->GetNumberOfLines();
706 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
707 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) +
708 // we're not going to pull in the whole wxTextFile if all we need is this...
709 #if wxUSE_TEXTFILE
710 wxTextFile::GetEOL()
711 #else // !wxUSE_TEXTFILE
712 '\n'
713 #endif // wxUSE_TEXTFILE
714 );
715 }
716
717 if ( bOk )
718 bOk = file.Close();
719
720 if ( !bOk ) {
721 wxLogError(_("Can't save log contents to file."));
722 }
723 else {
724 wxLogStatus(this, _("Log saved to the file '%s'."), szFileName);
725 }
726 }
727
728 void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
729 {
730 m_pTextCtrl->Clear();
731 }
732
733 wxLogFrame::~wxLogFrame()
734 {
735 m_log->OnFrameDelete(this);
736 }
737
738 // wxLogWindow
739 // -----------
740 wxLogWindow::wxLogWindow(wxFrame *pParent,
741 const char *szTitle,
742 bool bShow,
743 bool bDoPass)
744 {
745 m_bPassMessages = bDoPass;
746
747 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
748 m_pOldLog = wxLog::SetActiveTarget(this);
749
750 if ( bShow )
751 m_pLogFrame->Show(TRUE);
752 }
753
754 void wxLogWindow::Show(bool bShow)
755 {
756 m_pLogFrame->Show(bShow);
757 }
758
759 void wxLogWindow::Flush()
760 {
761 if ( m_pOldLog != NULL )
762 m_pOldLog->Flush();
763
764 m_bHasMessages = FALSE;
765 }
766
767 void wxLogWindow::DoLog(wxLogLevel level, const char *szString)
768 {
769 // first let the previous logger show it
770 if ( m_pOldLog != NULL && m_bPassMessages ) {
771 // @@@ why can't we access protected wxLog method from here (we derive
772 // from wxLog)? gcc gives "DoLog is protected in this context", what
773 // does this mean? Anyhow, the cast is harmless and let's us do what
774 // we want.
775 ((wxLogWindow *)m_pOldLog)->DoLog(level, szString);
776 }
777
778 if ( m_pLogFrame ) {
779 switch ( level ) {
780 case wxLOG_Status:
781 // by default, these messages are ignored by wxLog, so process
782 // them ourselves
783 {
784 wxString str = TimeStamp();
785 str << _("Status: ") << szString;
786 DoLogString(str);
787 }
788 break;
789
790 // don't put trace messages in the text window for 2 reasons:
791 // 1) there are too many of them
792 // 2) they may provoke other trace messages thus sending a program
793 // into an infinite loop
794 case wxLOG_Trace:
795 break;
796
797 default:
798 // and this will format it nicely and call our DoLogString()
799 wxLog::DoLog(level, szString);
800 }
801 }
802
803 m_bHasMessages = TRUE;
804 }
805
806 void wxLogWindow::DoLogString(const char *szString)
807 {
808 // put the text into our window
809 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
810
811 // remove selection (WriteText is in fact ReplaceSelection)
812 #ifdef __WXMSW__
813 long nLen = pText->GetLastPosition();
814 pText->SetSelection(nLen, nLen);
815 #endif // Windows
816
817 pText->WriteText(szString);
818 pText->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
819
820 // TODO ensure that the line can be seen
821 }
822
823 wxFrame *wxLogWindow::GetFrame() const
824 {
825 return m_pLogFrame;
826 }
827
828 void wxLogWindow::OnFrameCreate(wxFrame * WXUNUSED(frame))
829 {
830 }
831
832 void wxLogWindow::OnFrameDelete(wxFrame * WXUNUSED(frame))
833 {
834 m_pLogFrame = (wxLogFrame *)NULL;
835 }
836
837 wxLogWindow::~wxLogWindow()
838 {
839 delete m_pOldLog;
840
841 // may be NULL if log frame already auto destroyed itself
842 delete m_pLogFrame;
843 }
844
845 #endif //wxUSE_NOGUI
846
847 // ============================================================================
848 // Global functions/variables
849 // ============================================================================
850
851 // ----------------------------------------------------------------------------
852 // static variables
853 // ----------------------------------------------------------------------------
854 wxLog *wxLog::ms_pLogger = (wxLog *) NULL;
855 bool wxLog::ms_doLog = TRUE;
856 bool wxLog::ms_bAutoCreate = TRUE;
857 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
858
859 // ----------------------------------------------------------------------------
860 // stdout error logging helper
861 // ----------------------------------------------------------------------------
862
863 // helper function: wraps the message and justifies it under given position
864 // (looks more pretty on the terminal). Also adds newline at the end.
865 //
866 // @@ this is now disabled until I find a portable way of determining the
867 // terminal window size (ok, I found it but does anybody really cares?)
868 #ifdef LOG_PRETTY_WRAP
869 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
870 {
871 size_t nMax = 80; // @@@@
872 size_t nStart = strlen(pszPrefix);
873 fputs(pszPrefix, f);
874
875 size_t n;
876 while ( *psz != '\0' ) {
877 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
878 putc(*psz++, f);
879
880 // wrapped?
881 if ( *psz != '\0' ) {
882 /*putc('\n', f);*/
883 for ( n = 0; n < nStart; n++ )
884 putc(' ', f);
885
886 // as we wrapped, squeeze all white space
887 while ( isspace(*psz) )
888 psz++;
889 }
890 }
891
892 putc('\n', f);
893 }
894 #endif //LOG_PRETTY_WRAP
895
896 // ----------------------------------------------------------------------------
897 // error code/error message retrieval functions
898 // ----------------------------------------------------------------------------
899
900 // get error code from syste
901 unsigned long wxSysErrorCode()
902 {
903 #ifdef __WXMSW__
904 #ifdef __WIN32__
905 return ::GetLastError();
906 #else //WIN16
907 // @@@@ what to do on Windows 3.1?
908 return 0;
909 #endif //WIN16/32
910 #else //Unix
911 return errno;
912 #endif //Win/Unix
913 }
914
915 // get error message from system
916 const char *wxSysErrorMsg(unsigned long nErrCode)
917 {
918 if ( nErrCode == 0 )
919 nErrCode = wxSysErrorCode();
920
921 #ifdef __WXMSW__
922 #ifdef __WIN32__
923 static char s_szBuf[LOG_BUFFER_SIZE / 2];
924
925 // get error message from system
926 LPVOID lpMsgBuf;
927 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
928 NULL, nErrCode,
929 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
930 (LPTSTR)&lpMsgBuf,
931 0, NULL);
932
933 // copy it to our buffer and free memory
934 strncpy(s_szBuf, (const char *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
935 s_szBuf[WXSIZEOF(s_szBuf) - 1] = '\0';
936 LocalFree(lpMsgBuf);
937
938 // returned string is capitalized and ended with '\r\n' - bad
939 s_szBuf[0] = (char)wxToLower(s_szBuf[0]);
940 size_t len = strlen(s_szBuf);
941 if ( len > 0 ) {
942 // truncate string
943 if ( s_szBuf[len - 2] == '\r' )
944 s_szBuf[len - 2] = '\0';
945 }
946
947 return s_szBuf;
948 #else //Win16
949 // TODO @@@@
950 return NULL;
951 #endif // Win16/32
952 #else // Unix
953 return strerror(nErrCode);
954 #endif // Win/Unix
955 }
956
957 // ----------------------------------------------------------------------------
958 // debug helper
959 // ----------------------------------------------------------------------------
960
961 #ifdef __WXDEBUG__
962
963 void Trap()
964 {
965 #ifdef __WXMSW__
966 DebugBreak();
967 #elif defined(__WXSTUBS__)
968 // TODO
969 #elif defined(__WXMAC__)
970 #if __powerc
971 Debugger();
972 #else
973 SysBreak();
974 #endif
975 #else // Unix
976 raise(SIGTRAP);
977 #endif // Win/Unix
978 }
979
980 // this function is called when an assert fails
981 void wxOnAssert(const char *szFile, int nLine, const char *szMsg)
982 {
983 // this variable can be set to true to suppress "assert failure" messages
984 static bool s_bNoAsserts = FALSE;
985 static bool s_bInAssert = FALSE;
986
987 if ( s_bInAssert ) {
988 // He-e-e-e-elp!! we're trapped in endless loop
989 Trap();
990
991 s_bInAssert = FALSE;
992
993 return;
994 }
995
996 s_bInAssert = TRUE;
997
998 char szBuf[LOG_BUFFER_SIZE];
999
1000 // make life easier for people using VC++ IDE: clicking on the message will
1001 // take us immediately to the place of the failed assert
1002 #ifdef __VISUALC__
1003 sprintf(szBuf, "%s(%d): assert failed", szFile, nLine);
1004 #else // !VC++
1005 // make the error message more clear for all the others
1006 sprintf(szBuf, "Assert failed in file %s at line %d", szFile, nLine);
1007 #endif // VC/!VC
1008
1009 if ( szMsg != NULL ) {
1010 strcat(szBuf, ": ");
1011 strcat(szBuf, szMsg);
1012 }
1013 else {
1014 strcat(szBuf, ".");
1015 }
1016
1017 if ( !s_bNoAsserts ) {
1018 // send it to the normal log destination
1019 wxLogDebug(szBuf);
1020
1021 #if wxUSE_NOGUI
1022 Trap();
1023 #else
1024 strcat(szBuf, "\nDo you want to stop the program?"
1025 "\nYou can also choose [Cancel] to suppress "
1026 "further warnings.");
1027
1028 switch ( wxMessageBox(szBuf, _("Debug"),
1029 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
1030 case wxYES:
1031 Trap();
1032 break;
1033
1034 case wxCANCEL:
1035 s_bNoAsserts = TRUE;
1036 break;
1037
1038 //case wxNO: nothing to do
1039 }
1040 #endif // USE_NOGUI
1041 }
1042
1043 s_bInAssert = FALSE;
1044 }
1045
1046 #endif //WXDEBUG
1047