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