]> git.saurik.com Git - wxWidgets.git/blob - src/common/log.cpp
wxDataObject changes - ok for MSW, still not for GTK/Motif/...
[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
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
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
44 #endif //WX_PRECOMP
45
46 #include "wx/file.h"
47 #include "wx/textfile.h"
48 #include "wx/utils.h"
49 #include "wx/wxchar.h"
50 #include "wx/log.h"
51
52 // other standard headers
53 #include <errno.h>
54 #include <stdlib.h>
55 #include <time.h>
56
57 #ifdef __WXMSW__
58 #include <windows.h>
59 // Redefines OutputDebugString if necessary
60 #include "wx/msw/private.h"
61 #else //Unix
62 #include <signal.h>
63 #endif //Win/Unix
64
65 // ----------------------------------------------------------------------------
66 // non member functions
67 // ----------------------------------------------------------------------------
68
69 // define this to enable wrapping of log messages
70 //#define LOG_PRETTY_WRAP
71
72 #ifdef LOG_PRETTY_WRAP
73 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
74 #endif
75
76 // ============================================================================
77 // implementation
78 // ============================================================================
79
80 // ----------------------------------------------------------------------------
81 // implementation of Log functions
82 //
83 // NB: unfortunately we need all these distinct functions, we can't make them
84 // macros and not all compilers inline vararg functions.
85 // ----------------------------------------------------------------------------
86
87 // log functions can't allocate memory (LogError("out of memory...") should
88 // work!), so we use a static buffer for all log messages
89 #define LOG_BUFFER_SIZE (4096)
90
91 // static buffer for error messages (FIXME MT-unsafe)
92 static wxChar s_szBuf[LOG_BUFFER_SIZE];
93
94 // generic log function
95 void wxLogGeneric(wxLogLevel level, const wxChar *szFormat, ...)
96 {
97 if ( wxLog::GetActiveTarget() != NULL ) {
98 va_list argptr;
99 va_start(argptr, szFormat);
100 wxVsprintf(s_szBuf, szFormat, argptr);
101 va_end(argptr);
102
103 wxLog::OnLog(level, s_szBuf, time(NULL));
104 }
105 }
106
107 #define IMPLEMENT_LOG_FUNCTION(level) \
108 void wxLog##level(const wxChar *szFormat, ...) \
109 { \
110 if ( wxLog::GetActiveTarget() != NULL ) { \
111 va_list argptr; \
112 va_start(argptr, szFormat); \
113 wxVsprintf(s_szBuf, szFormat, argptr); \
114 va_end(argptr); \
115 \
116 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
117 } \
118 }
119
120 IMPLEMENT_LOG_FUNCTION(FatalError)
121 IMPLEMENT_LOG_FUNCTION(Error)
122 IMPLEMENT_LOG_FUNCTION(Warning)
123 IMPLEMENT_LOG_FUNCTION(Message)
124 IMPLEMENT_LOG_FUNCTION(Info)
125 IMPLEMENT_LOG_FUNCTION(Status)
126
127 // same as info, but only if 'verbose' mode is on
128 void wxLogVerbose(const wxChar *szFormat, ...)
129 {
130 wxLog *pLog = wxLog::GetActiveTarget();
131 if ( pLog != NULL && pLog->GetVerbose() ) {
132 va_list argptr;
133 va_start(argptr, szFormat);
134 wxVsprintf(s_szBuf, szFormat, argptr);
135 va_end(argptr);
136
137 wxLog::OnLog(wxLOG_Info, s_szBuf, time(NULL));
138 }
139 }
140
141 // debug functions
142 #ifdef __WXDEBUG__
143 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
144 void wxLog##level(const wxChar *szFormat, ...) \
145 { \
146 if ( wxLog::GetActiveTarget() != NULL ) { \
147 va_list argptr; \
148 va_start(argptr, szFormat); \
149 wxVsprintf(s_szBuf, szFormat, argptr); \
150 va_end(argptr); \
151 \
152 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
153 } \
154 }
155
156 void wxLogTrace(const wxChar *mask, const wxChar *szFormat, ...)
157 {
158 wxLog *pLog = wxLog::GetActiveTarget();
159
160 if ( pLog != NULL && wxLog::IsAllowedTraceMask(mask) ) {
161 va_list argptr;
162 va_start(argptr, szFormat);
163 wxVsprintf(s_szBuf, szFormat, argptr);
164 va_end(argptr);
165
166 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
167 }
168 }
169
170 void wxLogTrace(wxTraceMask mask, const wxChar *szFormat, ...)
171 {
172 wxLog *pLog = wxLog::GetActiveTarget();
173
174 // we check that all of mask bits are set in the current mask, so
175 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
176 // if both bits are set.
177 if ( pLog != NULL && ((pLog->GetTraceMask() & mask) == mask) ) {
178 va_list argptr;
179 va_start(argptr, szFormat);
180 wxVsprintf(s_szBuf, szFormat, argptr);
181 va_end(argptr);
182
183 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
184 }
185 }
186
187 #else // release
188 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
189 #endif
190
191 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
192 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
193
194 // wxLogSysError: one uses the last error code, for other you must give it
195 // explicitly
196
197 // common part of both wxLogSysError
198 void wxLogSysErrorHelper(long lErrCode)
199 {
200 wxChar szErrMsg[LOG_BUFFER_SIZE / 2];
201 wxSprintf(szErrMsg, _(" (error %ld: %s)"), lErrCode, wxSysErrorMsg(lErrCode));
202 wxStrncat(s_szBuf, szErrMsg, WXSIZEOF(s_szBuf) - wxStrlen(s_szBuf));
203
204 wxLog::OnLog(wxLOG_Error, s_szBuf, time(NULL));
205 }
206
207 void WXDLLEXPORT wxLogSysError(const wxChar *szFormat, ...)
208 {
209 va_list argptr;
210 va_start(argptr, szFormat);
211 wxVsprintf(s_szBuf, szFormat, argptr);
212 va_end(argptr);
213
214 wxLogSysErrorHelper(wxSysErrorCode());
215 }
216
217 void WXDLLEXPORT wxLogSysError(long lErrCode, const wxChar *szFormat, ...)
218 {
219 va_list argptr;
220 va_start(argptr, szFormat);
221 wxVsprintf(s_szBuf, szFormat, argptr);
222 va_end(argptr);
223
224 wxLogSysErrorHelper(lErrCode);
225 }
226
227 // ----------------------------------------------------------------------------
228 // wxLog class implementation
229 // ----------------------------------------------------------------------------
230
231 wxLog::wxLog()
232 {
233 m_bHasMessages = FALSE;
234
235 // enable verbose messages by default in the debug builds
236 #ifdef __WXDEBUG__
237 m_bVerbose = TRUE;
238 #else // release
239 m_bVerbose = FALSE;
240 #endif // debug/release
241 }
242
243 wxLog *wxLog::GetActiveTarget()
244 {
245 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
246 // prevent infinite recursion if someone calls wxLogXXX() from
247 // wxApp::CreateLogTarget()
248 static bool s_bInGetActiveTarget = FALSE;
249 if ( !s_bInGetActiveTarget ) {
250 s_bInGetActiveTarget = TRUE;
251
252 // ask the application to create a log target for us
253 if ( wxTheApp != NULL )
254 ms_pLogger = wxTheApp->CreateLogTarget();
255 else
256 ms_pLogger = new wxLogStderr;
257
258 s_bInGetActiveTarget = FALSE;
259
260 // do nothing if it fails - what can we do?
261 }
262 }
263
264 return ms_pLogger;
265 }
266
267 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
268 {
269 if ( ms_pLogger != NULL ) {
270 // flush the old messages before changing because otherwise they might
271 // get lost later if this target is not restored
272 ms_pLogger->Flush();
273 }
274
275 wxLog *pOldLogger = ms_pLogger;
276 ms_pLogger = pLogger;
277
278 return pOldLogger;
279 }
280
281 void wxLog::RemoveTraceMask(const wxString& str)
282 {
283 int index = ms_aTraceMasks.Index(str);
284 if ( index != wxNOT_FOUND )
285 ms_aTraceMasks.Remove((size_t)index);
286 }
287
288 void wxLog::TimeStamp(wxString *str)
289 {
290 if ( ms_timestamp )
291 {
292 wxChar buf[256];
293 time_t timeNow;
294 (void)time(&timeNow);
295 wxStrftime(buf, WXSIZEOF(buf), ms_timestamp, localtime(&timeNow));
296
297 str->Empty();
298 *str << buf << wxT(": ");
299 }
300 }
301
302 void wxLog::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
303 {
304 switch ( level ) {
305 case wxLOG_FatalError:
306 DoLogString(wxString(_("Fatal error: ")) + szString, t);
307 DoLogString(_("Program aborted."), t);
308 Flush();
309 abort();
310 break;
311
312 case wxLOG_Error:
313 DoLogString(wxString(_("Error: ")) + szString, t);
314 break;
315
316 case wxLOG_Warning:
317 DoLogString(wxString(_("Warning: ")) + szString, t);
318 break;
319
320 case wxLOG_Info:
321 if ( GetVerbose() )
322 case wxLOG_Message:
323 default: // log unknown log levels too
324 DoLogString(szString, t);
325 // fall through
326
327 case wxLOG_Status:
328 // nothing to do
329 break;
330
331 case wxLOG_Trace:
332 case wxLOG_Debug:
333 #ifdef __WXDEBUG__
334 DoLogString(szString, t);
335 #endif
336 break;
337 }
338 }
339
340 void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t WXUNUSED(t))
341 {
342 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
343 }
344
345 void wxLog::Flush()
346 {
347 // do nothing
348 }
349
350 // ----------------------------------------------------------------------------
351 // wxLogStderr class implementation
352 // ----------------------------------------------------------------------------
353
354 wxLogStderr::wxLogStderr(FILE *fp)
355 {
356 if ( fp == NULL )
357 m_fp = stderr;
358 else
359 m_fp = fp;
360 }
361
362 void wxLogStderr::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
363 {
364 wxString str;
365 TimeStamp(&str);
366 str << szString << wxT('\n');
367
368 fputs(str.mb_str(), m_fp);
369 fflush(m_fp);
370
371 // under Windows, programs usually don't have stderr at all, so make show the
372 // messages also under debugger
373 #ifdef __WXMSW__
374 OutputDebugString(str + wxT('\r'));
375 #endif // MSW
376 }
377
378 // ----------------------------------------------------------------------------
379 // wxLogStream implementation
380 // ----------------------------------------------------------------------------
381
382 #if wxUSE_STD_IOSTREAM
383 wxLogStream::wxLogStream(ostream *ostr)
384 {
385 if ( ostr == NULL )
386 m_ostr = &cerr;
387 else
388 m_ostr = ostr;
389 }
390
391 void wxLogStream::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
392 {
393 (*m_ostr) << wxConvertWX2MB(szString) << endl;
394 }
395 #endif // wxUSE_STD_IOSTREAM
396
397 // ============================================================================
398 // Global functions/variables
399 // ============================================================================
400
401 // ----------------------------------------------------------------------------
402 // static variables
403 // ----------------------------------------------------------------------------
404
405 wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
406 bool wxLog::ms_doLog = TRUE;
407 bool wxLog::ms_bAutoCreate = TRUE;
408
409 const wxChar *wxLog::ms_timestamp = wxT("%X"); // time only, no date
410
411 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
412 wxArrayString wxLog::ms_aTraceMasks;
413
414 // ----------------------------------------------------------------------------
415 // stdout error logging helper
416 // ----------------------------------------------------------------------------
417
418 // helper function: wraps the message and justifies it under given position
419 // (looks more pretty on the terminal). Also adds newline at the end.
420 //
421 // TODO this is now disabled until I find a portable way of determining the
422 // terminal window size (ok, I found it but does anybody really cares?)
423 #ifdef LOG_PRETTY_WRAP
424 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
425 {
426 size_t nMax = 80; // FIXME
427 size_t nStart = strlen(pszPrefix);
428 fputs(pszPrefix, f);
429
430 size_t n;
431 while ( *psz != '\0' ) {
432 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
433 putc(*psz++, f);
434
435 // wrapped?
436 if ( *psz != '\0' ) {
437 /*putc('\n', f);*/
438 for ( n = 0; n < nStart; n++ )
439 putc(' ', f);
440
441 // as we wrapped, squeeze all white space
442 while ( isspace(*psz) )
443 psz++;
444 }
445 }
446
447 putc('\n', f);
448 }
449 #endif //LOG_PRETTY_WRAP
450
451 // ----------------------------------------------------------------------------
452 // error code/error message retrieval functions
453 // ----------------------------------------------------------------------------
454
455 // get error code from syste
456 unsigned long wxSysErrorCode()
457 {
458 #ifdef __WXMSW__
459 #ifdef __WIN32__
460 return ::GetLastError();
461 #else //WIN16
462 // TODO what to do on Windows 3.1?
463 return 0;
464 #endif //WIN16/32
465 #else //Unix
466 return errno;
467 #endif //Win/Unix
468 }
469
470 // get error message from system
471 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
472 {
473 if ( nErrCode == 0 )
474 nErrCode = wxSysErrorCode();
475
476 #ifdef __WXMSW__
477 #ifdef __WIN32__
478 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
479
480 // get error message from system
481 LPVOID lpMsgBuf;
482 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
483 NULL, nErrCode,
484 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
485 (LPTSTR)&lpMsgBuf,
486 0, NULL);
487
488 // copy it to our buffer and free memory
489 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
490 s_szBuf[WXSIZEOF(s_szBuf) - 1] = wxT('\0');
491 LocalFree(lpMsgBuf);
492
493 // returned string is capitalized and ended with '\r\n' - bad
494 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
495 size_t len = wxStrlen(s_szBuf);
496 if ( len > 0 ) {
497 // truncate string
498 if ( s_szBuf[len - 2] == wxT('\r') )
499 s_szBuf[len - 2] = wxT('\0');
500 }
501
502 return s_szBuf;
503 #else //Win16
504 // TODO
505 return NULL;
506 #endif // Win16/32
507 #else // Unix
508 #if wxUSE_UNICODE
509 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
510 wxConvCurrent->MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
511 return s_szBuf;
512 #else
513 return strerror(nErrCode);
514 #endif
515 #endif // Win/Unix
516 }
517
518 // ----------------------------------------------------------------------------
519 // debug helper
520 // ----------------------------------------------------------------------------
521
522 #ifdef __WXDEBUG__
523
524 // break into the debugger
525 void Trap()
526 {
527 #ifdef __WXMSW__
528 DebugBreak();
529 #elif defined(__WXMAC__)
530 #if __powerc
531 Debugger();
532 #else
533 SysBreak();
534 #endif
535 #elif defined(__UNIX__)
536 raise(SIGTRAP);
537 #else
538 // TODO
539 #endif // Win/Unix
540 }
541
542 // this function is called when an assert fails
543 void wxOnAssert(const wxChar *szFile, int nLine, const wxChar *szMsg)
544 {
545 // this variable can be set to true to suppress "assert failure" messages
546 static bool s_bNoAsserts = FALSE;
547 static bool s_bInAssert = FALSE; // FIXME MT-unsafe
548
549 if ( s_bInAssert ) {
550 // He-e-e-e-elp!! we're trapped in endless loop
551 Trap();
552
553 s_bInAssert = FALSE;
554
555 return;
556 }
557
558 s_bInAssert = TRUE;
559
560 wxChar szBuf[LOG_BUFFER_SIZE];
561
562 // make life easier for people using VC++ IDE: clicking on the message
563 // will take us immediately to the place of the failed assert
564 #ifdef __VISUALC__
565 wxSprintf(szBuf, wxT("%s(%d): assert failed"), szFile, nLine);
566 #else // !VC++
567 // make the error message more clear for all the others
568 wxSprintf(szBuf, wxT("Assert failed in file %s at line %d"), szFile, nLine);
569 #endif // VC/!VC
570
571 if ( szMsg != NULL ) {
572 wxStrcat(szBuf, wxT(": "));
573 wxStrcat(szBuf, szMsg);
574 }
575 else {
576 wxStrcat(szBuf, wxT("."));
577 }
578
579 if ( !s_bNoAsserts ) {
580 // send it to the normal log destination
581 wxLogDebug(szBuf);
582
583 #if wxUSE_GUI
584 // this message is intentionally not translated - it is for
585 // developpers only
586 wxStrcat(szBuf, wxT("\nDo you want to stop the program?"
587 "\nYou can also choose [Cancel] to suppress "
588 "further warnings."));
589
590 switch ( wxMessageBox(szBuf, _("Debug"),
591 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
592 case wxYES:
593 Trap();
594 break;
595
596 case wxCANCEL:
597 s_bNoAsserts = TRUE;
598 break;
599
600 //case wxNO: nothing to do
601 }
602 #else // !GUI
603 Trap();
604 #endif // GUI/!GUI
605 }
606
607 s_bInAssert = FALSE;
608 }
609
610 #endif //WXDEBUG
611