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