1) wxFileConfig now longer tries to delete system-wide config file in DeleteAll
[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 void wxLog::DoLog(wxLogLevel level, const char *szString)
253 {
254 wxString str;
255
256 // prepend a timestamp if not disabled
257 if ( !IsEmpty(m_szTimeFormat) ) {
258 char szBuf[128];
259 time_t timeNow;
260 struct tm *ptmNow;
261
262 time(&timeNow);
263 ptmNow = localtime(&timeNow);
264
265 strftime(szBuf, WXSIZEOF(szBuf), m_szTimeFormat, ptmNow);
266 str = szBuf;
267 }
268
269 switch ( level ) {
270 case wxLOG_FatalError:
271 DoLogString(str << _("Fatal error: ") << szString);
272 DoLogString(_("Program aborted."));
273 Flush();
274 abort();
275 break;
276
277 case wxLOG_Error:
278 DoLogString(str << _("Error: ") << szString);
279 break;
280
281 case wxLOG_Warning:
282 DoLogString(str << _("Warning: ") << szString);
283 break;
284
285 case wxLOG_Info:
286 if ( GetVerbose() )
287 case wxLOG_Message:
288 DoLogString(str + szString);
289 // fall through
290
291 case wxLOG_Status:
292 // nothing to do
293 break;
294
295 case wxLOG_Trace:
296 case wxLOG_Debug:
297 #ifdef __WXDEBUG__
298 #ifdef __WIN32__
299 // in addition to normal logging, also send the string to debugger
300 // (don't prepend "Debug" here: it will go to debug window anyhow)
301 ::OutputDebugString(str + szString + "\n\r");
302 #endif //Win32
303 DoLogString(str << (level == wxLOG_Trace ? _("Trace") : _("Debug"))
304 << ": " << szString);
305 #endif
306
307 break;
308
309 default:
310 wxFAIL_MSG("unknown log level in wxLog::DoLog");
311 }
312 }
313
314 void wxLog::DoLogString(const char *WXUNUSED(szString))
315 {
316 wxFAIL_MSG("DoLogString must be overrided if it's called.");
317 }
318
319 void wxLog::Flush()
320 {
321 // do nothing
322 }
323
324 // ----------------------------------------------------------------------------
325 // wxLogStderr class implementation
326 // ----------------------------------------------------------------------------
327
328 wxLogStderr::wxLogStderr(FILE *fp)
329 {
330 if ( fp == NULL )
331 m_fp = stderr;
332 else
333 m_fp = fp;
334 }
335
336 void wxLogStderr::DoLogString(const char *szString)
337 {
338 fputs(szString, m_fp);
339 fputc('\n', m_fp);
340 fflush(m_fp);
341 }
342
343 // ----------------------------------------------------------------------------
344 // wxLogStream implementation
345 // ----------------------------------------------------------------------------
346
347 wxLogStream::wxLogStream(ostream *ostr)
348 {
349 if ( ostr == NULL )
350 m_ostr = &cerr;
351 else
352 m_ostr = ostr;
353 }
354
355 void wxLogStream::DoLogString(const char *szString)
356 {
357 (*m_ostr) << szString << endl << flush;
358 }
359
360 // ----------------------------------------------------------------------------
361 // wxLogTextCtrl implementation
362 // ----------------------------------------------------------------------------
363 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
364 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
365 : wxLogStream(new ostream(pTextCtrl))
366 {
367 }
368
369 wxLogTextCtrl::~wxLogTextCtrl()
370 {
371 delete m_ostr;
372 }
373
374 // ----------------------------------------------------------------------------
375 // wxLogGui implementation
376 // ----------------------------------------------------------------------------
377
378 #ifndef WX_TEST_MINIMAL
379
380 wxLogGui::wxLogGui()
381 {
382 m_bErrors = FALSE;
383 }
384
385 void wxLogGui::Flush()
386 {
387 if ( !m_bHasMessages )
388 return;
389
390 // @@@ ugly...
391
392 // concatenate all strings (but not too many to not overfill the msg box)
393 wxString str;
394 uint nLines = 0,
395 nMsgCount = m_aMessages.Count();
396
397 // start from the most recent message
398 for ( uint n = nMsgCount; n > 0; n-- ) {
399 // for Windows strings longer than this value are wrapped (NT 4.0)
400 const uint nMsgLineWidth = 156;
401
402 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
403
404 if ( nLines > 25 ) // don't put too many lines in message box
405 break;
406
407 str << m_aMessages[n - 1] << "\n";
408 }
409
410 if ( m_bErrors ) {
411 wxMessageBox(str, _("Error"), wxOK | wxICON_EXCLAMATION);
412 }
413 else {
414 wxMessageBox(str, _("Information"), wxOK | wxICON_INFORMATION);
415 }
416
417 // no undisplayed messages whatsoever
418 m_bHasMessages =
419 m_bErrors = FALSE;
420 m_aMessages.Empty();
421 }
422
423 // the default behaviour is to discard all informational messages if there
424 // are any errors/warnings.
425 void wxLogGui::DoLog(wxLogLevel level, const char *szString)
426 {
427 switch ( level ) {
428 case wxLOG_Info:
429 if ( GetVerbose() )
430 case wxLOG_Message:
431 if ( !m_bErrors ) {
432 m_aMessages.Add(szString);
433 m_bHasMessages = TRUE;
434 }
435 break;
436
437 case wxLOG_Status:
438 {
439 // find the top window and set it's status text if it has any
440 wxWindow *pWin = wxTheApp->GetTopWindow();
441 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
442 wxFrame *pFrame = (wxFrame *)pWin;
443 pFrame->SetStatusText(szString);
444 }
445 }
446 break;
447
448 case wxLOG_Trace:
449 case wxLOG_Debug:
450 #ifdef __WXDEBUG__
451 #ifdef __WIN32__
452 OutputDebugString(szString);
453 OutputDebugString("\n\r");
454 #else //!WIN32
455 // send them to stderr
456 fprintf(stderr, "%s: %s\n",
457 level == wxLOG_Trace ? _("Trace") : _("Debug"), szString);
458 fflush(stderr);
459 #endif // WIN32
460 #endif
461 break;
462
463 case wxLOG_FatalError:
464 // show this one immediately
465 wxMessageBox(szString, _("Fatal error"), wxICON_HAND);
466 break;
467
468 case wxLOG_Error:
469 case wxLOG_Warning:
470 // discard earlier informational messages if this is the 1st error
471 if ( !m_bErrors ) {
472 m_aMessages.Empty();
473 m_bHasMessages = TRUE;
474 m_bErrors = TRUE;
475 }
476
477 m_aMessages.Add(szString);
478 break;
479
480 default:
481 wxFAIL_MSG("unknown log level in wxLogGui::DoLog");
482 }
483 }
484
485 // ----------------------------------------------------------------------------
486 // wxLogWindow implementation
487 // ----------------------------------------------------------------------------
488
489 // log frame class
490 class wxLogFrame : public wxFrame
491 {
492 public:
493 // ctor
494 wxLogFrame(const char *szTitle);
495
496 // menu callbacks
497 void OnClose(wxCommandEvent& event);
498 void OnCloseWindow(wxCloseEvent& event);
499 void OnSave (wxCommandEvent& event);
500 void OnClear(wxCommandEvent& event);
501
502 // accessors
503 wxTextCtrl *TextCtrl() const { return m_pTextCtrl; }
504
505 private:
506 enum
507 {
508 Menu_Close = 100,
509 Menu_Save,
510 Menu_Clear
511 };
512
513 wxTextCtrl *m_pTextCtrl;
514
515 DECLARE_EVENT_TABLE()
516 };
517
518 BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
519 // wxLogWindow menu events
520 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
521 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
522 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
523
524 EVT_CLOSE(wxLogFrame::OnCloseWindow)
525 END_EVENT_TABLE()
526
527 wxLogFrame::wxLogFrame(const char *szTitle)
528 : wxFrame(NULL, -1, szTitle)
529 {
530 // we don't want to be a top-level frame because it would prevent the
531 // application termination when all other frames are closed
532 wxTopLevelWindows.DeleteObject(this);
533
534 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
535 // a rich edit control instead of a normal one we want
536 m_pTextCtrl = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition,
537 wxDefaultSize,
538 wxSIMPLE_BORDER |
539 wxTE_MULTILINE |
540 wxHSCROLL |
541 wxTE_READONLY);
542 /*
543 m_pTextCtrl->SetEditable(FALSE);
544 m_pTextCtrl->SetRichEdit(FALSE);
545 */
546
547 // create menu
548 wxMenuBar *pMenuBar = new wxMenuBar;
549 wxMenu *pMenu = new wxMenu;
550 pMenu->Append(Menu_Save, "&Save...");
551 pMenu->Append(Menu_Clear, "C&lear");
552 pMenu->AppendSeparator();
553 pMenu->Append(Menu_Close, "&Close");
554 pMenuBar->Append(pMenu, "&Log");
555 SetMenuBar(pMenuBar);
556
557 // @@ what about status bar? needed (for menu prompts)?
558 }
559
560 void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
561 {
562 // just hide the window
563 Show(FALSE);
564 }
565
566 void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
567 {
568 // just hide the window
569 Show(FALSE);
570 }
571
572 void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
573 {
574 // get the file name
575 // -----------------
576 const char *szFileName = wxSaveFileSelector("log", "txt", "log.txt");
577 if ( szFileName == NULL ) {
578 // cancelled
579 return;
580 }
581
582 // open file
583 // ---------
584 wxFile file;
585 bool bOk = FALSE;
586 if ( wxFile::Exists(szFileName) ) {
587 bool bAppend = FALSE;
588 wxString strMsg;
589 strMsg.Printf(_("Append log to file '%s' "
590 "(choosing [No] will overwrite it)?"), szFileName);
591 switch ( wxMessageBox(strMsg, "Question", wxYES_NO | wxCANCEL) ) {
592 case wxYES:
593 bAppend = TRUE;
594 break;
595
596 case wxNO:
597 bAppend = FALSE;
598 break;
599
600 case wxCANCEL:
601 return;
602
603 default:
604 wxFAIL_MSG("invalid message box return value");
605 }
606
607 if ( bAppend ) {
608 bOk = file.Open(szFileName, wxFile::write_append);
609 }
610 else {
611 bOk = file.Create(szFileName, TRUE /* overwrite */);
612 }
613 }
614 else {
615 bOk = file.Create(szFileName);
616 }
617
618 // retrieve text and save it
619 // -------------------------
620 #ifdef __WXGTK__
621 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
622 wxLogError("Sorry, this function is not implemented under GTK");
623 #else
624 int nLines = m_pTextCtrl->GetNumberOfLines();
625 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
626 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) + wxTextFile::GetEOL());
627 }
628 #endif //GTK
629
630 if ( bOk )
631 bOk = file.Close();
632
633 if ( !bOk ) {
634 wxLogError(_("Can't save log contents to file."));
635 return;
636 }
637 }
638
639 void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
640 {
641 m_pTextCtrl->Clear();
642 }
643
644 wxLogWindow::wxLogWindow(const char *szTitle, bool bShow)
645 {
646 m_pOldLog = wxLog::GetActiveTarget();
647 m_pLogFrame = new wxLogFrame(szTitle);
648
649 if ( bShow )
650 m_pLogFrame->Show(TRUE);
651 }
652
653 void wxLogWindow::Show(bool bShow)
654 {
655 m_pLogFrame->Show(bShow);
656 }
657
658 void wxLogWindow::DoLog(wxLogLevel level, const char *szString)
659 {
660 // first let the previous logger show it
661 if ( m_pOldLog != NULL ) {
662 // @@@ why can't we access protected wxLog method from here (we derive
663 // from wxLog)? gcc gives "DoLog is protected in this context", what
664 // does this mean? Anyhow, the cast is harmless and let's us do what
665 // we want.
666 ((wxLogWindow *)m_pOldLog)->DoLog(level, szString);
667 }
668
669 // and this will format it nicely and call our DoLogString()
670 wxLog::DoLog(level, szString);
671 }
672
673 void wxLogWindow::DoLogString(const char *szString)
674 {
675 // put the text into our window
676 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
677
678 // remove selection (WriteText is in fact ReplaceSelection)
679 #ifdef __WXMSW__
680 long nLen = pText->GetLastPosition();
681 pText->SetSelection(nLen, nLen);
682 #endif // Windows
683
684 pText->WriteText(szString);
685 pText->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
686
687 // ensure that the line can be seen
688 // @@@ TODO
689 }
690
691 wxLogWindow::~wxLogWindow()
692 {
693 m_pLogFrame->Close(TRUE);
694 }
695
696 #endif //WX_TEST_MINIMAL
697
698 // ============================================================================
699 // Global functions/variables
700 // ============================================================================
701
702 // ----------------------------------------------------------------------------
703 // static variables
704 // ----------------------------------------------------------------------------
705 wxLog *wxLog::ms_pLogger = NULL;
706 bool wxLog::ms_bAutoCreate = TRUE;
707 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
708
709 // ----------------------------------------------------------------------------
710 // stdout error logging helper
711 // ----------------------------------------------------------------------------
712
713 // helper function: wraps the message and justifies it under given position
714 // (looks more pretty on the terminal). Also adds newline at the end.
715 //
716 // @@ this is now disabled until I find a portable way of determining the
717 // terminal window size (ok, I found it but does anybody really cares?)
718 #ifdef LOG_PRETTY_WRAP
719 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
720 {
721 size_t nMax = 80; // @@@@
722 size_t nStart = strlen(pszPrefix);
723 fputs(pszPrefix, f);
724
725 size_t n;
726 while ( *psz != '\0' ) {
727 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
728 putc(*psz++, f);
729
730 // wrapped?
731 if ( *psz != '\0' ) {
732 /*putc('\n', f);*/
733 for ( n = 0; n < nStart; n++ )
734 putc(' ', f);
735
736 // as we wrapped, squeeze all white space
737 while ( isspace(*psz) )
738 psz++;
739 }
740 }
741
742 putc('\n', f);
743 }
744 #endif //LOG_PRETTY_WRAP
745
746 // ----------------------------------------------------------------------------
747 // error code/error message retrieval functions
748 // ----------------------------------------------------------------------------
749
750 // get error code from syste
751 unsigned long wxSysErrorCode()
752 {
753 #ifdef __WXMSW__
754 #ifdef __WIN32__
755 return ::GetLastError();
756 #else //WIN16
757 // @@@@ what to do on Windows 3.1?
758 return 0;
759 #endif //WIN16/32
760 #else //Unix
761 return errno;
762 #endif //Win/Unix
763 }
764
765 // get error message from system
766 const char *wxSysErrorMsg(unsigned long nErrCode)
767 {
768 if ( nErrCode == 0 )
769 nErrCode = wxSysErrorCode();
770
771 #ifdef __WXMSW__
772 #ifdef __WIN32__
773 static char s_szBuf[LOG_BUFFER_SIZE / 2];
774
775 // get error message from system
776 LPVOID lpMsgBuf;
777 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
778 NULL, nErrCode,
779 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
780 (LPTSTR)&lpMsgBuf,
781 0, NULL);
782
783 // copy it to our buffer and free memory
784 strncpy(s_szBuf, (const char *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
785 s_szBuf[WXSIZEOF(s_szBuf) - 1] = '\0';
786 LocalFree(lpMsgBuf);
787
788 // returned string is capitalized and ended with '\r\n' - bad
789 s_szBuf[0] = (char)wxToLower(s_szBuf[0]);
790 size_t len = strlen(s_szBuf);
791 if ( len > 0 ) {
792 // truncate string
793 if ( s_szBuf[len - 2] == '\r' )
794 s_szBuf[len - 2] = '\0';
795 }
796
797 return s_szBuf;
798 #else //Win16
799 // TODO @@@@
800 return NULL;
801 #endif // Win16/32
802 #else // Unix
803 return strerror(nErrCode);
804 #endif // Win/Unix
805 }
806
807 // ----------------------------------------------------------------------------
808 // debug helper
809 // ----------------------------------------------------------------------------
810
811 #ifdef __WXDEBUG__
812
813 void Trap()
814 {
815 #ifdef __WXMSW__
816 DebugBreak();
817 #else // Unix
818 raise(SIGTRAP);
819 #endif // Win/Unix
820 }
821
822 // this function is called when an assert fails
823 void wxOnAssert(const char *szFile, int nLine, const char *szMsg)
824 {
825 // this variable can be set to true to suppress "assert failure" messages
826 static bool s_bNoAsserts = FALSE;
827 static bool s_bInAssert = FALSE;
828
829 if ( s_bInAssert ) {
830 // He-e-e-e-elp!! we're trapped in endless loop
831 Trap();
832 }
833
834 s_bInAssert = TRUE;
835
836 char szBuf[LOG_BUFFER_SIZE];
837 sprintf(szBuf, _("Assert failed in file %s at line %d"), szFile, nLine);
838 if ( szMsg != NULL ) {
839 strcat(szBuf, ": ");
840 strcat(szBuf, szMsg);
841 }
842 else {
843 strcat(szBuf, ".");
844 }
845
846 if ( !s_bNoAsserts ) {
847 // send it to the normal log destination
848 wxLogDebug(szBuf);
849
850 strcat(szBuf, _("\nDo you want to stop the program?"
851 "\nYou can also choose [Cancel] to suppress "
852 "further warnings."));
853
854 switch ( wxMessageBox(szBuf, _("Debug"),
855 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
856 case wxYES:
857 Trap();
858 break;
859
860 case wxCANCEL:
861 s_bNoAsserts = TRUE;
862 break;
863
864 //case wxNO: nothing to do
865 }
866 }
867
868 s_bInAssert = FALSE;
869 }
870
871 #endif //WXDEBUG
872