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