]> git.saurik.com Git - wxWidgets.git/blame - src/common/log.cpp
fix for last commit
[wxWidgets.git] / src / common / log.cpp
CommitLineData
c801d85f
KB
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// ----------------------------------------------------------------------------
dd85fc6b 19
c801d85f
KB
20#ifdef __GNUG__
21 #pragma implementation "log.h"
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
28 #pragma hdrstop
29#endif
30
31// wxWindows
32#ifndef WX_PRECOMP
e90c1d2a
VZ
33 #include "wx/string.h"
34 #include "wx/intl.h"
35 #include "wx/app.h"
36
37 #if wxUSE_GUI
38 #include "wx/window.h"
39 #ifdef __WXMSW__
40 #include "wx/msw/private.h"
41 #endif
42 #include "wx/msgdlg.h"
43 #endif
9ef3052c 44#endif //WX_PRECOMP
c801d85f 45
dbf3cd7a
RR
46#include "wx/file.h"
47#include "wx/textfile.h"
48#include "wx/utils.h"
a324a7bc 49#include "wx/wxchar.h"
dbf3cd7a 50#include "wx/log.h"
b568d04f 51#include "wx/thread.h"
c801d85f 52
f94dfb38
VS
53#if wxUSE_LOG
54
c801d85f
KB
55// other standard headers
56#include <errno.h>
57#include <stdlib.h>
58#include <time.h>
59
2049ba38 60#ifdef __WXMSW__
b568d04f 61 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
3078c3a6
VZ
62#else //Unix
63 #include <signal.h>
64#endif //Win/Unix
c801d85f
KB
65
66// ----------------------------------------------------------------------------
67// non member functions
68// ----------------------------------------------------------------------------
69
70// define this to enable wrapping of log messages
71//#define LOG_PRETTY_WRAP
72
9ef3052c 73#ifdef LOG_PRETTY_WRAP
c801d85f
KB
74 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
75#endif
76
77// ============================================================================
78// implementation
79// ============================================================================
80
81// ----------------------------------------------------------------------------
b568d04f 82// globals
c801d85f
KB
83// ----------------------------------------------------------------------------
84
85// log functions can't allocate memory (LogError("out of memory...") should
86// work!), so we use a static buffer for all log messages
87#define LOG_BUFFER_SIZE (4096)
88
b568d04f 89// static buffer for error messages
50920146 90static wxChar s_szBuf[LOG_BUFFER_SIZE];
c801d85f 91
b568d04f
VZ
92#if wxUSE_THREADS
93
94// the critical section protecting the static buffer
95static wxCriticalSection gs_csLogBuf;
96
97#endif // wxUSE_THREADS
98
807a903e
VZ
99// return true if we have a non NULL non disabled log target
100static inline bool IsLoggingEnabled()
101{
102 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL);
103}
104
b568d04f
VZ
105// ----------------------------------------------------------------------------
106// implementation of Log functions
107//
108// NB: unfortunately we need all these distinct functions, we can't make them
109// macros and not all compilers inline vararg functions.
110// ----------------------------------------------------------------------------
111
c801d85f 112// generic log function
50920146 113void wxLogGeneric(wxLogLevel level, const wxChar *szFormat, ...)
c801d85f 114{
807a903e
VZ
115 if ( IsLoggingEnabled() ) {
116 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
9ef3052c 117
807a903e
VZ
118 va_list argptr;
119 va_start(argptr, szFormat);
120 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
121 va_end(argptr);
122
123 wxLog::OnLog(level, s_szBuf, time(NULL));
124 }
c801d85f
KB
125}
126
807a903e
VZ
127#define IMPLEMENT_LOG_FUNCTION(level) \
128 void wxLog##level(const wxChar *szFormat, ...) \
129 { \
130 if ( IsLoggingEnabled() ) { \
131 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
132 \
133 va_list argptr; \
134 va_start(argptr, szFormat); \
135 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
136 va_end(argptr); \
137 \
138 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
139 } \
c801d85f
KB
140 }
141
142IMPLEMENT_LOG_FUNCTION(FatalError)
143IMPLEMENT_LOG_FUNCTION(Error)
144IMPLEMENT_LOG_FUNCTION(Warning)
145IMPLEMENT_LOG_FUNCTION(Message)
146IMPLEMENT_LOG_FUNCTION(Info)
147IMPLEMENT_LOG_FUNCTION(Status)
148
9ef3052c 149// same as info, but only if 'verbose' mode is on
50920146 150void wxLogVerbose(const wxChar *szFormat, ...)
9ef3052c 151{
807a903e
VZ
152 if ( IsLoggingEnabled() ) {
153 wxLog *pLog = wxLog::GetActiveTarget();
154 if ( pLog != NULL && pLog->GetVerbose() ) {
155 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
156
157 va_list argptr;
158 va_start(argptr, szFormat);
159 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
160 va_end(argptr);
161
162 wxLog::OnLog(wxLOG_Info, s_szBuf, time(NULL));
163 }
164 }
9ef3052c
VZ
165}
166
167// debug functions
b2aef89b 168#ifdef __WXDEBUG__
807a903e
VZ
169#define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
170 void wxLog##level(const wxChar *szFormat, ...) \
171 { \
172 if ( IsLoggingEnabled() ) { \
173 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
174 \
175 va_list argptr; \
176 va_start(argptr, szFormat); \
177 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
178 va_end(argptr); \
179 \
180 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
181 } \
c801d85f
KB
182 }
183
50920146 184 void wxLogTrace(const wxChar *mask, const wxChar *szFormat, ...)
0fb67cd1 185 {
807a903e 186 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask) ) {
b568d04f
VZ
187 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
188
00c4e897
VZ
189 wxChar *p = s_szBuf;
190 size_t len = WXSIZEOF(s_szBuf);
f6bcfd97 191 wxStrncpy(s_szBuf, _T("("), len);
829f0541
VZ
192 len -= 1; // strlen("(")
193 p += 1;
f6bcfd97 194 wxStrncat(p, mask, len);
00c4e897
VZ
195 size_t lenMask = wxStrlen(mask);
196 len -= lenMask;
197 p += lenMask;
198
f6bcfd97 199 wxStrncat(p, _T(") "), len);
829f0541
VZ
200 len -= 2;
201 p += 2;
00c4e897 202
0fb67cd1
VZ
203 va_list argptr;
204 va_start(argptr, szFormat);
00c4e897 205 wxVsnprintf(p, len, szFormat, argptr);
0fb67cd1
VZ
206 va_end(argptr);
207
208 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
209 }
210 }
211
50920146 212 void wxLogTrace(wxTraceMask mask, const wxChar *szFormat, ...)
9ef3052c 213 {
9ef3052c
VZ
214 // we check that all of mask bits are set in the current mask, so
215 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
216 // if both bits are set.
807a903e 217 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask) == mask) ) {
b568d04f
VZ
218 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
219
9ef3052c
VZ
220 va_list argptr;
221 va_start(argptr, szFormat);
378b05f7 222 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
9ef3052c
VZ
223 va_end(argptr);
224
0fb67cd1 225 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
9ef3052c
VZ
226 }
227 }
228
229#else // release
230 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
231#endif
232
233IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
234IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
235
236// wxLogSysError: one uses the last error code, for other you must give it
237// explicitly
238
239// common part of both wxLogSysError
240void wxLogSysErrorHelper(long lErrCode)
c801d85f 241{
50920146 242 wxChar szErrMsg[LOG_BUFFER_SIZE / 2];
378b05f7
VZ
243 wxSnprintf(szErrMsg, WXSIZEOF(szErrMsg),
244 _(" (error %ld: %s)"), lErrCode, wxSysErrorMsg(lErrCode));
50920146 245 wxStrncat(s_szBuf, szErrMsg, WXSIZEOF(s_szBuf) - wxStrlen(s_szBuf));
c801d85f 246
0fb67cd1 247 wxLog::OnLog(wxLOG_Error, s_szBuf, time(NULL));
9ef3052c 248}
c801d85f 249
50920146 250void WXDLLEXPORT wxLogSysError(const wxChar *szFormat, ...)
9ef3052c 251{
807a903e
VZ
252 if ( IsLoggingEnabled() ) {
253 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
b568d04f 254
807a903e
VZ
255 va_list argptr;
256 va_start(argptr, szFormat);
257 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
258 va_end(argptr);
9ef3052c 259
807a903e
VZ
260 wxLogSysErrorHelper(wxSysErrorCode());
261 }
c801d85f
KB
262}
263
50920146 264void WXDLLEXPORT wxLogSysError(long lErrCode, const wxChar *szFormat, ...)
c801d85f 265{
807a903e
VZ
266 if ( IsLoggingEnabled() ) {
267 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
b568d04f 268
807a903e
VZ
269 va_list argptr;
270 va_start(argptr, szFormat);
271 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
272 va_end(argptr);
c801d85f 273
807a903e
VZ
274 wxLogSysErrorHelper(lErrCode);
275 }
c801d85f
KB
276}
277
278// ----------------------------------------------------------------------------
279// wxLog class implementation
280// ----------------------------------------------------------------------------
281
282wxLog::wxLog()
283{
0fb67cd1 284 m_bHasMessages = FALSE;
0fb67cd1 285 m_bVerbose = FALSE;
c801d85f
KB
286}
287
9ec05cc9
VZ
288wxLog *wxLog::GetActiveTarget()
289{
0fb67cd1
VZ
290 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
291 // prevent infinite recursion if someone calls wxLogXXX() from
292 // wxApp::CreateLogTarget()
293 static bool s_bInGetActiveTarget = FALSE;
294 if ( !s_bInGetActiveTarget ) {
295 s_bInGetActiveTarget = TRUE;
296
0fb67cd1
VZ
297 // ask the application to create a log target for us
298 if ( wxTheApp != NULL )
299 ms_pLogger = wxTheApp->CreateLogTarget();
300 else
301 ms_pLogger = new wxLogStderr;
0fb67cd1
VZ
302
303 s_bInGetActiveTarget = FALSE;
304
305 // do nothing if it fails - what can we do?
306 }
275bf4c1 307 }
c801d85f 308
0fb67cd1 309 return ms_pLogger;
c801d85f
KB
310}
311
c085e333 312wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
9ec05cc9 313{
0fb67cd1
VZ
314 if ( ms_pLogger != NULL ) {
315 // flush the old messages before changing because otherwise they might
316 // get lost later if this target is not restored
317 ms_pLogger->Flush();
318 }
c801d85f 319
0fb67cd1
VZ
320 wxLog *pOldLogger = ms_pLogger;
321 ms_pLogger = pLogger;
c085e333 322
0fb67cd1 323 return pOldLogger;
c801d85f
KB
324}
325
36bd6902
VZ
326void wxLog::DontCreateOnDemand()
327{
328 ms_bAutoCreate = FALSE;
329
330 // this is usually called at the end of the program and we assume that it
331 // is *always* called at the end - so we free memory here to avoid false
332 // memory leak reports from wxWin memory tracking code
333 ClearTraceMasks();
334}
335
0fb67cd1 336void wxLog::RemoveTraceMask(const wxString& str)
c801d85f 337{
0fb67cd1
VZ
338 int index = ms_aTraceMasks.Index(str);
339 if ( index != wxNOT_FOUND )
340 ms_aTraceMasks.Remove((size_t)index);
341}
c801d85f 342
36bd6902
VZ
343void wxLog::ClearTraceMasks()
344{
345 ms_aTraceMasks.Clear();
346}
347
d2e1ef19
VZ
348void wxLog::TimeStamp(wxString *str)
349{
350 if ( ms_timestamp )
351 {
352 wxChar buf[256];
353 time_t timeNow;
354 (void)time(&timeNow);
c49245f8 355 wxStrftime(buf, WXSIZEOF(buf), ms_timestamp, localtime(&timeNow));
d2e1ef19
VZ
356
357 str->Empty();
223d09f6 358 *str << buf << wxT(": ");
d2e1ef19
VZ
359 }
360}
361
50920146 362void wxLog::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
0fb67cd1 363{
0fb67cd1
VZ
364 switch ( level ) {
365 case wxLOG_FatalError:
786855a1 366 DoLogString(wxString(_("Fatal error: ")) + szString, t);
0fb67cd1
VZ
367 DoLogString(_("Program aborted."), t);
368 Flush();
369 abort();
370 break;
371
372 case wxLOG_Error:
786855a1 373 DoLogString(wxString(_("Error: ")) + szString, t);
0fb67cd1
VZ
374 break;
375
376 case wxLOG_Warning:
786855a1 377 DoLogString(wxString(_("Warning: ")) + szString, t);
0fb67cd1
VZ
378 break;
379
380 case wxLOG_Info:
0fb67cd1 381 if ( GetVerbose() )
37278984 382 case wxLOG_Message:
87a1e308 383 case wxLOG_Status:
786855a1
VZ
384 default: // log unknown log levels too
385 DoLogString(szString, t);
0fb67cd1
VZ
386 break;
387
388 case wxLOG_Trace:
389 case wxLOG_Debug:
390#ifdef __WXDEBUG__
0131687b
VZ
391 {
392 wxString msg = level == wxLOG_Trace ? wxT("Trace: ")
54a8f42b 393 : wxT("Debug: ");
0131687b
VZ
394 msg << szString;
395 DoLogString(msg, t);
396 }
397#endif // Debug
0fb67cd1 398 break;
0fb67cd1 399 }
c801d85f
KB
400}
401
74e3313b 402void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t WXUNUSED(t))
c801d85f 403{
223d09f6 404 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
c801d85f
KB
405}
406
407void wxLog::Flush()
408{
0fb67cd1 409 // do nothing
c801d85f
KB
410}
411
412// ----------------------------------------------------------------------------
413// wxLogStderr class implementation
414// ----------------------------------------------------------------------------
415
416wxLogStderr::wxLogStderr(FILE *fp)
417{
0fb67cd1
VZ
418 if ( fp == NULL )
419 m_fp = stderr;
420 else
421 m_fp = fp;
c801d85f
KB
422}
423
03e11df5 424#if defined(__WXMAC__) && !defined(__UNIX__)
7d610b90
SC
425#define kDebuggerSignature 'MWDB'
426
427static Boolean FindProcessBySignature(OSType signature, ProcessInfoRec* info)
428{
429 OSErr err;
430 ProcessSerialNumber psn;
431 Boolean found = false;
432 psn.highLongOfPSN = 0;
433 psn.lowLongOfPSN = kNoProcess;
434
435 if (!info) return false;
436
437 info->processInfoLength = sizeof(ProcessInfoRec);
438 info->processName = NULL;
439 info->processAppSpec = NULL;
440
441 err = noErr;
442 while (!found && err == noErr)
443 {
444 err = GetNextProcess(&psn);
445 if (err == noErr)
446 {
447 err = GetProcessInformation(&psn, info);
448 found = err == noErr && info->processSignature == signature;
449 }
450 }
451 return found;
452}
453
454pascal Boolean MWDebuggerIsRunning(void)
455{
456 ProcessInfoRec info;
457 return FindProcessBySignature(kDebuggerSignature, &info);
458}
459
460pascal OSErr AmIBeingMWDebugged(Boolean* result)
461{
462 OSErr err;
463 ProcessSerialNumber psn;
464 OSType sig = kDebuggerSignature;
465 AppleEvent theAE = {typeNull, NULL};
466 AppleEvent theReply = {typeNull, NULL};
467 AEAddressDesc addr = {typeNull, NULL};
468 DescType actualType;
469 Size actualSize;
470
471 if (!result) return paramErr;
472
473 err = AECreateDesc(typeApplSignature, &sig, sizeof(sig), &addr);
474 if (err != noErr) goto exit;
475
476 err = AECreateAppleEvent('MWDB', 'Dbg?', &addr,
477 kAutoGenerateReturnID, kAnyTransactionID, &theAE);
478 if (err != noErr) goto exit;
479
480 GetCurrentProcess(&psn);
481 err = AEPutParamPtr(&theAE, keyDirectObject, typeProcessSerialNumber,
482 &psn, sizeof(psn));
483 if (err != noErr) goto exit;
484
485 err = AESend(&theAE, &theReply, kAEWaitReply, kAENormalPriority,
486 kAEDefaultTimeout, NULL, NULL);
487 if (err != noErr) goto exit;
488
489 err = AEGetParamPtr(&theReply, keyAEResult, typeBoolean, &actualType, result,
490 sizeof(Boolean), &actualSize);
491
492exit:
493 if (addr.dataHandle)
494 AEDisposeDesc(&addr);
495 if (theAE.dataHandle)
496 AEDisposeDesc(&theAE);
497 if (theReply.dataHandle)
498 AEDisposeDesc(&theReply);
499
500 return err;
501}
502#endif
503
74e3313b 504void wxLogStderr::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
c801d85f 505{
d2e1ef19
VZ
506 wxString str;
507 TimeStamp(&str);
b568d04f 508 str << szString;
1e8a4bc2 509
50920146 510 fputs(str.mb_str(), m_fp);
b568d04f 511 fputc(_T('\n'), m_fp);
0fb67cd1 512 fflush(m_fp);
1e8a4bc2 513
378b05f7 514 // under Windows, programs usually don't have stderr at all, so show the
b568d04f
VZ
515 // messages also under debugger - unless it's a console program
516#if defined(__WXMSW__) && wxUSE_GUI
f6bcfd97
BP
517 str += wxT("\r\n") ;
518 OutputDebugString(str.c_str());
1e8a4bc2 519#endif // MSW
03e11df5 520#if defined(__WXMAC__) && !defined(__WXMAC_X__) && wxUSE_GUI
7d610b90
SC
521 Str255 pstr ;
522 strcpy( (char*) pstr , str.c_str() ) ;
523 strcat( (char*) pstr , ";g" ) ;
524 c2pstr( (char*) pstr ) ;
525#if __WXDEBUG__
526 Boolean running = false ;
527
528/*
529 if ( MWDebuggerIsRunning() )
530 {
531 AmIBeingMWDebugged( &running ) ;
532 }
533*/
534 if (running)
535 {
536 #ifdef __powerc
537 DebugStr(pstr);
538 #else
539 SysBreakStr(pstr);
540 #endif
541 }
542 else
543#endif
544 {
545 #ifdef __powerc
546 DebugStr(pstr);
547 #else
548 DebugStr(pstr);
549 #endif
550 }
03e11df5 551#endif // Mac
c801d85f
KB
552}
553
554// ----------------------------------------------------------------------------
555// wxLogStream implementation
556// ----------------------------------------------------------------------------
557
4bf78aae 558#if wxUSE_STD_IOSTREAM
c801d85f
KB
559wxLogStream::wxLogStream(ostream *ostr)
560{
0fb67cd1
VZ
561 if ( ostr == NULL )
562 m_ostr = &cerr;
563 else
564 m_ostr = ostr;
c801d85f
KB
565}
566
74e3313b 567void wxLogStream::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
c801d85f 568{
29fd317b
VZ
569 wxString str;
570 TimeStamp(&str);
571 (*m_ostr) << str << wxConvertWX2MB(szString) << endl;
c801d85f 572}
0fb67cd1 573#endif // wxUSE_STD_IOSTREAM
c801d85f 574
c801d85f
KB
575// ============================================================================
576// Global functions/variables
577// ============================================================================
578
579// ----------------------------------------------------------------------------
580// static variables
581// ----------------------------------------------------------------------------
0fb67cd1
VZ
582
583wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
584bool wxLog::ms_doLog = TRUE;
585bool wxLog::ms_bAutoCreate = TRUE;
d2e1ef19 586
2ed3265e
VZ
587size_t wxLog::ms_suspendCount = 0;
588
9f83044f
VZ
589#if wxUSE_GUI
590 const wxChar *wxLog::ms_timestamp = wxT("%X"); // time only, no date
591#else
592 const wxChar *wxLog::ms_timestamp = NULL; // save space
593#endif
d2e1ef19 594
0fb67cd1
VZ
595wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
596wxArrayString wxLog::ms_aTraceMasks;
c801d85f
KB
597
598// ----------------------------------------------------------------------------
599// stdout error logging helper
600// ----------------------------------------------------------------------------
601
602// helper function: wraps the message and justifies it under given position
603// (looks more pretty on the terminal). Also adds newline at the end.
604//
0fb67cd1
VZ
605// TODO this is now disabled until I find a portable way of determining the
606// terminal window size (ok, I found it but does anybody really cares?)
607#ifdef LOG_PRETTY_WRAP
c801d85f
KB
608static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
609{
0fb67cd1
VZ
610 size_t nMax = 80; // FIXME
611 size_t nStart = strlen(pszPrefix);
612 fputs(pszPrefix, f);
613
614 size_t n;
615 while ( *psz != '\0' ) {
616 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
617 putc(*psz++, f);
618
619 // wrapped?
620 if ( *psz != '\0' ) {
621 /*putc('\n', f);*/
622 for ( n = 0; n < nStart; n++ )
623 putc(' ', f);
624
625 // as we wrapped, squeeze all white space
626 while ( isspace(*psz) )
627 psz++;
628 }
c801d85f 629 }
c801d85f 630
0fb67cd1 631 putc('\n', f);
c801d85f
KB
632}
633#endif //LOG_PRETTY_WRAP
634
635// ----------------------------------------------------------------------------
636// error code/error message retrieval functions
637// ----------------------------------------------------------------------------
638
639// get error code from syste
640unsigned long wxSysErrorCode()
641{
0fb67cd1
VZ
642#ifdef __WXMSW__
643#ifdef __WIN32__
644 return ::GetLastError();
645#else //WIN16
646 // TODO what to do on Windows 3.1?
647 return 0;
648#endif //WIN16/32
649#else //Unix
c801d85f 650 return errno;
0fb67cd1 651#endif //Win/Unix
c801d85f
KB
652}
653
654// get error message from system
50920146 655const wxChar *wxSysErrorMsg(unsigned long nErrCode)
c801d85f 656{
0fb67cd1
VZ
657 if ( nErrCode == 0 )
658 nErrCode = wxSysErrorCode();
659
660#ifdef __WXMSW__
661#ifdef __WIN32__
50920146 662 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
0fb67cd1
VZ
663
664 // get error message from system
665 LPVOID lpMsgBuf;
666 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
667 NULL, nErrCode,
668 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
669 (LPTSTR)&lpMsgBuf,
670 0, NULL);
671
672 // copy it to our buffer and free memory
50920146 673 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
223d09f6 674 s_szBuf[WXSIZEOF(s_szBuf) - 1] = wxT('\0');
0fb67cd1
VZ
675 LocalFree(lpMsgBuf);
676
677 // returned string is capitalized and ended with '\r\n' - bad
50920146
OK
678 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
679 size_t len = wxStrlen(s_szBuf);
0fb67cd1 680 if ( len > 0 ) {
9ef3052c 681 // truncate string
223d09f6
KB
682 if ( s_szBuf[len - 2] == wxT('\r') )
683 s_szBuf[len - 2] = wxT('\0');
0fb67cd1
VZ
684 }
685
686 return s_szBuf;
687#else //Win16
688 // TODO
689 return NULL;
690#endif // Win16/32
691#else // Unix
50920146
OK
692#if wxUSE_UNICODE
693 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
dcf924a3 694 wxConvCurrent->MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
50920146
OK
695 return s_szBuf;
696#else
13111b2a 697 return strerror((int)nErrCode);
50920146 698#endif
0fb67cd1 699#endif // Win/Unix
c801d85f
KB
700}
701
702// ----------------------------------------------------------------------------
703// debug helper
704// ----------------------------------------------------------------------------
705
b2aef89b 706#ifdef __WXDEBUG__
c801d85f 707
0fb67cd1 708// break into the debugger
7502ba29
VZ
709void Trap()
710{
0fb67cd1 711#ifdef __WXMSW__
7502ba29 712 DebugBreak();
0fb67cd1
VZ
713#elif defined(__WXMAC__)
714#if __powerc
17dff81c 715 Debugger();
0fb67cd1 716#else
17dff81c 717 SysBreak();
0fb67cd1
VZ
718#endif
719#elif defined(__UNIX__)
7502ba29 720 raise(SIGTRAP);
0fb67cd1
VZ
721#else
722 // TODO
723#endif // Win/Unix
7502ba29
VZ
724}
725
c801d85f 726// this function is called when an assert fails
6f9eb452 727void wxOnAssert(const wxChar *szFile, int nLine, const wxChar *szMsg)
c801d85f 728{
0fb67cd1
VZ
729 // this variable can be set to true to suppress "assert failure" messages
730 static bool s_bNoAsserts = FALSE;
731 static bool s_bInAssert = FALSE; // FIXME MT-unsafe
7502ba29 732
0fb67cd1
VZ
733 if ( s_bInAssert ) {
734 // He-e-e-e-elp!! we're trapped in endless loop
735 Trap();
c085e333 736
0fb67cd1 737 s_bInAssert = FALSE;
1e8a4bc2 738
0fb67cd1
VZ
739 return;
740 }
7502ba29 741
0fb67cd1 742 s_bInAssert = TRUE;
c801d85f 743
50920146 744 wxChar szBuf[LOG_BUFFER_SIZE];
c263077e 745
0fb67cd1
VZ
746 // make life easier for people using VC++ IDE: clicking on the message
747 // will take us immediately to the place of the failed assert
378b05f7 748 wxSnprintf(szBuf, WXSIZEOF(szBuf),
3f4a0c5b 749#ifdef __VISUALC__
378b05f7 750 wxT("%s(%d): assert failed"),
c263077e 751#else // !VC++
0fb67cd1 752 // make the error message more clear for all the others
378b05f7 753 wxT("Assert failed in file %s at line %d"),
c263077e 754#endif // VC/!VC
378b05f7 755 szFile, nLine);
c263077e 756
0fb67cd1 757 if ( szMsg != NULL ) {
223d09f6 758 wxStrcat(szBuf, wxT(": "));
50920146 759 wxStrcat(szBuf, szMsg);
0fb67cd1
VZ
760 }
761 else {
223d09f6 762 wxStrcat(szBuf, wxT("."));
0fb67cd1 763 }
c801d85f 764
0fb67cd1
VZ
765 if ( !s_bNoAsserts ) {
766 // send it to the normal log destination
767 wxLogDebug(szBuf);
7502ba29 768
b76b015e 769#if wxUSE_GUI || defined(__WXMSW__)
0fb67cd1
VZ
770 // this message is intentionally not translated - it is for
771 // developpers only
f6bcfd97 772 wxStrcat(szBuf, wxT("\nDo you want to stop the program?\nYou can also choose [Cancel] to suppress further warnings."));
0fb67cd1 773
6b6267d3
VZ
774 // use the native message box if available: this is more robust than
775 // using our own
776#ifdef __WXMSW__
777 switch ( ::MessageBox(NULL, szBuf, _T("Debug"),
778 MB_YESNOCANCEL | MB_ICONSTOP ) ) {
779 case IDYES:
0fb67cd1
VZ
780 Trap();
781 break;
782
6b6267d3 783 case IDCANCEL:
0fb67cd1
VZ
784 s_bNoAsserts = TRUE;
785 break;
786
6b6267d3 787 //case IDNO: nothing to do
b76b015e 788 }
6b6267d3
VZ
789#else // !MSW
790 switch ( wxMessageBox(szBuf, wxT("Debug"),
791 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
792 case wxYES:
b76b015e
VZ
793 Trap();
794 break;
795
6b6267d3 796 case wxCANCEL:
b76b015e
VZ
797 s_bNoAsserts = TRUE;
798 break;
799
6b6267d3 800 //case wxNO: nothing to do
0fb67cd1 801 }
b76b015e
VZ
802#endif // GUI or MSW
803
e90c1d2a
VZ
804#else // !GUI
805 Trap();
806#endif // GUI/!GUI
0fb67cd1
VZ
807 }
808
809 s_bInAssert = FALSE;
c801d85f
KB
810}
811
b2aef89b 812#endif //WXDEBUG
c801d85f 813
f94dfb38 814#endif //wxUSE_LOG