]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/log.cpp
-Debian glibc2 system is 'linux-gnu', not 'Linux';updated .cvsignore's -Markus
[wxWidgets.git] / src / common / log.cpp
... / ...
CommitLineData
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)
85static char s_szBuf[LOG_BUFFER_SIZE];
86
87// generic log function
88void 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
113IMPLEMENT_LOG_FUNCTION(FatalError)
114IMPLEMENT_LOG_FUNCTION(Error)
115IMPLEMENT_LOG_FUNCTION(Warning)
116IMPLEMENT_LOG_FUNCTION(Message)
117IMPLEMENT_LOG_FUNCTION(Info)
118IMPLEMENT_LOG_FUNCTION(Status)
119
120// same as info, but only if 'verbose' mode is on
121void 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
170IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
171IMPLEMENT_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
177void 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
186void 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
196void 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
210wxLog::wxLog()
211{
212 m_bHasMessages = FALSE;
213 m_bVerbose = FALSE;
214 m_szTimeFormat = "[%d/%b/%y %H:%M:%S] ";
215}
216
217wxLog *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
241wxLog *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
252wxString 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
271void 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
316void wxLog::DoLogString(const char *WXUNUSED(szString))
317{
318 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
319}
320
321void wxLog::Flush()
322{
323 // do nothing
324}
325
326// ----------------------------------------------------------------------------
327// wxLogStderr class implementation
328// ----------------------------------------------------------------------------
329
330wxLogStderr::wxLogStderr(FILE *fp)
331{
332 if ( fp == NULL )
333 m_fp = stderr;
334 else
335 m_fp = fp;
336}
337
338void 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
349wxLogStream::wxLogStream(ostream *ostr)
350{
351 if ( ostr == NULL )
352 m_ostr = &cerr;
353 else
354 m_ostr = ostr;
355}
356
357void wxLogStream::DoLogString(const char *szString)
358{
359 (*m_ostr) << szString << endl << flush;
360}
361
362// ----------------------------------------------------------------------------
363// wxLogTextCtrl implementation
364// ----------------------------------------------------------------------------
365wxLogTextCtrl::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
376wxLogTextCtrl::~wxLogTextCtrl()
377{
378 delete m_ostr;
379}
380
381// ----------------------------------------------------------------------------
382// wxLogGui implementation
383// ----------------------------------------------------------------------------
384
385#ifndef WX_TEST_MINIMAL
386
387wxLogGui::wxLogGui()
388{
389 m_bErrors = FALSE;
390}
391
392void 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.
432void 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// ---------------
505class wxLogFrame : public wxFrame
506{
507public:
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
523private:
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
540BEGIN_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)
549END_EVENT_TABLE()
550
551wxLogFrame::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
585void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
586{
587 DoClose();
588}
589
590void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
591{
592 DoClose();
593}
594
595void 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
603void 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
670void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
671{
672 m_pTextCtrl->Clear();
673}
674
675wxLogFrame::~wxLogFrame()
676{
677 m_log->OnFrameDelete(this);
678}
679
680// wxLogWindow
681// -----------
682wxLogWindow::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
693void wxLogWindow::Show(bool bShow)
694{
695 m_pLogFrame->Show(bShow);
696}
697
698void wxLogWindow::Flush()
699{
700 if ( m_pOldLog != NULL )
701 m_pOldLog->Flush();
702
703 m_bHasMessages = FALSE;
704}
705
706void 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 // don't put trace messages in the text window for 2 reasons:
718 // 1) there are too many of them
719 // 2) they may provoke other trace messages thus sending a program into an
720 // infinite loop
721 if ( m_pLogFrame && level != wxLOG_Trace ) {
722 // and this will format it nicely and call our DoLogString()
723 wxLog::DoLog(level, szString);
724 }
725
726 m_bHasMessages = TRUE;
727}
728
729void wxLogWindow::DoLogString(const char *szString)
730{
731 // put the text into our window
732 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
733
734 // remove selection (WriteText is in fact ReplaceSelection)
735 #ifdef __WXMSW__
736 long nLen = pText->GetLastPosition();
737 pText->SetSelection(nLen, nLen);
738 #endif // Windows
739
740 pText->WriteText(szString);
741 pText->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
742
743 // ensure that the line can be seen
744 // @@@ TODO
745}
746
747wxFrame *wxLogWindow::GetFrame() const
748{
749 return m_pLogFrame;
750}
751
752void wxLogWindow::OnFrameCreate(wxFrame *frame)
753{
754}
755
756void wxLogWindow::OnFrameDelete(wxFrame *frame)
757{
758 m_pLogFrame = NULL;
759}
760
761wxLogWindow::~wxLogWindow()
762{
763 // may be NULL if log frame already auto destroyed itself
764 delete m_pLogFrame;
765}
766
767#endif //WX_TEST_MINIMAL
768
769// ============================================================================
770// Global functions/variables
771// ============================================================================
772
773// ----------------------------------------------------------------------------
774// static variables
775// ----------------------------------------------------------------------------
776wxLog *wxLog::ms_pLogger = NULL;
777bool wxLog::ms_bAutoCreate = TRUE;
778wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
779
780// ----------------------------------------------------------------------------
781// stdout error logging helper
782// ----------------------------------------------------------------------------
783
784// helper function: wraps the message and justifies it under given position
785// (looks more pretty on the terminal). Also adds newline at the end.
786//
787// @@ this is now disabled until I find a portable way of determining the
788// terminal window size (ok, I found it but does anybody really cares?)
789#ifdef LOG_PRETTY_WRAP
790static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
791{
792 size_t nMax = 80; // @@@@
793 size_t nStart = strlen(pszPrefix);
794 fputs(pszPrefix, f);
795
796 size_t n;
797 while ( *psz != '\0' ) {
798 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
799 putc(*psz++, f);
800
801 // wrapped?
802 if ( *psz != '\0' ) {
803 /*putc('\n', f);*/
804 for ( n = 0; n < nStart; n++ )
805 putc(' ', f);
806
807 // as we wrapped, squeeze all white space
808 while ( isspace(*psz) )
809 psz++;
810 }
811 }
812
813 putc('\n', f);
814}
815#endif //LOG_PRETTY_WRAP
816
817// ----------------------------------------------------------------------------
818// error code/error message retrieval functions
819// ----------------------------------------------------------------------------
820
821// get error code from syste
822unsigned long wxSysErrorCode()
823{
824 #ifdef __WXMSW__
825 #ifdef __WIN32__
826 return ::GetLastError();
827 #else //WIN16
828 // @@@@ what to do on Windows 3.1?
829 return 0;
830 #endif //WIN16/32
831 #else //Unix
832 return errno;
833 #endif //Win/Unix
834}
835
836// get error message from system
837const char *wxSysErrorMsg(unsigned long nErrCode)
838{
839 if ( nErrCode == 0 )
840 nErrCode = wxSysErrorCode();
841
842 #ifdef __WXMSW__
843 #ifdef __WIN32__
844 static char s_szBuf[LOG_BUFFER_SIZE / 2];
845
846 // get error message from system
847 LPVOID lpMsgBuf;
848 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
849 NULL, nErrCode,
850 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
851 (LPTSTR)&lpMsgBuf,
852 0, NULL);
853
854 // copy it to our buffer and free memory
855 strncpy(s_szBuf, (const char *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
856 s_szBuf[WXSIZEOF(s_szBuf) - 1] = '\0';
857 LocalFree(lpMsgBuf);
858
859 // returned string is capitalized and ended with '\r\n' - bad
860 s_szBuf[0] = (char)wxToLower(s_szBuf[0]);
861 size_t len = strlen(s_szBuf);
862 if ( len > 0 ) {
863 // truncate string
864 if ( s_szBuf[len - 2] == '\r' )
865 s_szBuf[len - 2] = '\0';
866 }
867
868 return s_szBuf;
869 #else //Win16
870 // TODO @@@@
871 return NULL;
872 #endif // Win16/32
873 #else // Unix
874 return strerror(nErrCode);
875 #endif // Win/Unix
876}
877
878// ----------------------------------------------------------------------------
879// debug helper
880// ----------------------------------------------------------------------------
881
882#ifdef __WXDEBUG__
883
884void Trap()
885{
886 #ifdef __WXMSW__
887 DebugBreak();
888 #else // Unix
889 raise(SIGTRAP);
890 #endif // Win/Unix
891}
892
893// this function is called when an assert fails
894void wxOnAssert(const char *szFile, int nLine, const char *szMsg)
895{
896 // this variable can be set to true to suppress "assert failure" messages
897 static bool s_bNoAsserts = FALSE;
898 static bool s_bInAssert = FALSE;
899
900 if ( s_bInAssert ) {
901 // He-e-e-e-elp!! we're trapped in endless loop
902 Trap();
903 }
904
905 s_bInAssert = TRUE;
906
907 char szBuf[LOG_BUFFER_SIZE];
908 sprintf(szBuf, _("Assert failed in file %s at line %d"), szFile, nLine);
909 if ( szMsg != NULL ) {
910 strcat(szBuf, ": ");
911 strcat(szBuf, szMsg);
912 }
913 else {
914 strcat(szBuf, ".");
915 }
916
917 if ( !s_bNoAsserts ) {
918 // send it to the normal log destination
919 wxLogDebug(szBuf);
920
921 strcat(szBuf, _("\nDo you want to stop the program?"
922 "\nYou can also choose [Cancel] to suppress "
923 "further warnings."));
924
925 switch ( wxMessageBox(szBuf, _("Debug"),
926 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
927 case wxYES:
928 Trap();
929 break;
930
931 case wxCANCEL:
932 s_bNoAsserts = TRUE;
933 break;
934
935 //case wxNO: nothing to do
936 }
937 }
938
939 s_bInAssert = FALSE;
940}
941
942#endif //WXDEBUG
943