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