]> git.saurik.com Git - wxWidgets.git/blob - src/common/log.cpp
removing dependancy on mac headers from public wx headers (eventually adding wx/mac...
[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 #endif
43 #endif //WX_PRECOMP
44
45 #include "wx/file.h"
46 #include "wx/textfile.h"
47 #include "wx/utils.h"
48 #include "wx/wxchar.h"
49 #include "wx/log.h"
50 #include "wx/thread.h"
51
52 #if wxUSE_LOG
53
54 // other standard headers
55 #include <errno.h>
56 #include <stdlib.h>
57 #include <time.h>
58
59 #if defined(__WXMSW__)
60 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
61 #endif
62
63 #if defined(__WXMAC__)
64 #include "wx/mac/private.h" // includes mac headers
65 #endif
66
67 // ----------------------------------------------------------------------------
68 // non member functions
69 // ----------------------------------------------------------------------------
70
71 // define this to enable wrapping of log messages
72 //#define LOG_PRETTY_WRAP
73
74 #ifdef LOG_PRETTY_WRAP
75 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
76 #endif
77
78 // ============================================================================
79 // implementation
80 // ============================================================================
81
82 // ----------------------------------------------------------------------------
83 // globals
84 // ----------------------------------------------------------------------------
85
86 // log functions can't allocate memory (LogError("out of memory...") should
87 // work!), so we use a static buffer for all log messages
88 #define LOG_BUFFER_SIZE (4096)
89
90 // static buffer for error messages
91 static wxChar s_szBuf[LOG_BUFFER_SIZE];
92
93 #if wxUSE_THREADS
94
95 // the critical section protecting the static buffer
96 static wxCriticalSection gs_csLogBuf;
97
98 #endif // wxUSE_THREADS
99
100 // return true if we have a non NULL non disabled log target
101 static inline bool IsLoggingEnabled()
102 {
103 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL);
104 }
105
106 // ----------------------------------------------------------------------------
107 // implementation of Log functions
108 //
109 // NB: unfortunately we need all these distinct functions, we can't make them
110 // macros and not all compilers inline vararg functions.
111 // ----------------------------------------------------------------------------
112
113 // generic log function
114 void wxLogGeneric(wxLogLevel level, const wxChar *szFormat, ...)
115 {
116 if ( IsLoggingEnabled() ) {
117 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
118
119 va_list argptr;
120 va_start(argptr, szFormat);
121 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
122 va_end(argptr);
123
124 wxLog::OnLog(level, s_szBuf, time(NULL));
125 }
126 }
127
128 #define IMPLEMENT_LOG_FUNCTION(level) \
129 void wxLog##level(const wxChar *szFormat, ...) \
130 { \
131 if ( IsLoggingEnabled() ) { \
132 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
133 \
134 va_list argptr; \
135 va_start(argptr, szFormat); \
136 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
137 va_end(argptr); \
138 \
139 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
140 } \
141 }
142
143 IMPLEMENT_LOG_FUNCTION(FatalError)
144 IMPLEMENT_LOG_FUNCTION(Error)
145 IMPLEMENT_LOG_FUNCTION(Warning)
146 IMPLEMENT_LOG_FUNCTION(Message)
147 IMPLEMENT_LOG_FUNCTION(Info)
148 IMPLEMENT_LOG_FUNCTION(Status)
149
150 // same as info, but only if 'verbose' mode is on
151 void wxLogVerbose(const wxChar *szFormat, ...)
152 {
153 if ( IsLoggingEnabled() ) {
154 wxLog *pLog = wxLog::GetActiveTarget();
155 if ( pLog != NULL && pLog->GetVerbose() ) {
156 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
157
158 va_list argptr;
159 va_start(argptr, szFormat);
160 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
161 va_end(argptr);
162
163 wxLog::OnLog(wxLOG_Info, s_szBuf, time(NULL));
164 }
165 }
166 }
167
168 // debug functions
169 #ifdef __WXDEBUG__
170 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
171 void wxLog##level(const wxChar *szFormat, ...) \
172 { \
173 if ( IsLoggingEnabled() ) { \
174 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
175 \
176 va_list argptr; \
177 va_start(argptr, szFormat); \
178 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
179 va_end(argptr); \
180 \
181 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
182 } \
183 }
184
185 void wxLogTrace(const wxChar *mask, const wxChar *szFormat, ...)
186 {
187 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask) ) {
188 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
189
190 wxChar *p = s_szBuf;
191 size_t len = WXSIZEOF(s_szBuf);
192 wxStrncpy(s_szBuf, _T("("), len);
193 len -= 1; // strlen("(")
194 p += 1;
195 wxStrncat(p, mask, len);
196 size_t lenMask = wxStrlen(mask);
197 len -= lenMask;
198 p += lenMask;
199
200 wxStrncat(p, _T(") "), len);
201 len -= 2;
202 p += 2;
203
204 va_list argptr;
205 va_start(argptr, szFormat);
206 wxVsnprintf(p, len, szFormat, argptr);
207 va_end(argptr);
208
209 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
210 }
211 }
212
213 void wxLogTrace(wxTraceMask mask, const wxChar *szFormat, ...)
214 {
215 // we check that all of mask bits are set in the current mask, so
216 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
217 // if both bits are set.
218 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask) == mask) ) {
219 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
220
221 va_list argptr;
222 va_start(argptr, szFormat);
223 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
224 va_end(argptr);
225
226 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
227 }
228 }
229
230 #else // release
231 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
232 #endif
233
234 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
235 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
236
237 // wxLogSysError: one uses the last error code, for other you must give it
238 // explicitly
239
240 // common part of both wxLogSysError
241 void wxLogSysErrorHelper(long lErrCode)
242 {
243 wxChar szErrMsg[LOG_BUFFER_SIZE / 2];
244 wxSnprintf(szErrMsg, WXSIZEOF(szErrMsg),
245 _(" (error %ld: %s)"), lErrCode, wxSysErrorMsg(lErrCode));
246 wxStrncat(s_szBuf, szErrMsg, WXSIZEOF(s_szBuf) - wxStrlen(s_szBuf));
247
248 wxLog::OnLog(wxLOG_Error, s_szBuf, time(NULL));
249 }
250
251 void WXDLLEXPORT wxLogSysError(const wxChar *szFormat, ...)
252 {
253 if ( IsLoggingEnabled() ) {
254 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
255
256 va_list argptr;
257 va_start(argptr, szFormat);
258 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
259 va_end(argptr);
260
261 wxLogSysErrorHelper(wxSysErrorCode());
262 }
263 }
264
265 void WXDLLEXPORT wxLogSysError(long lErrCode, const wxChar *szFormat, ...)
266 {
267 if ( IsLoggingEnabled() ) {
268 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
269
270 va_list argptr;
271 va_start(argptr, szFormat);
272 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
273 va_end(argptr);
274
275 wxLogSysErrorHelper(lErrCode);
276 }
277 }
278
279 // ----------------------------------------------------------------------------
280 // wxLog class implementation
281 // ----------------------------------------------------------------------------
282
283 wxLog::wxLog()
284 {
285 m_bHasMessages = FALSE;
286 }
287
288 wxLog *wxLog::GetActiveTarget()
289 {
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
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;
302
303 s_bInGetActiveTarget = FALSE;
304
305 // do nothing if it fails - what can we do?
306 }
307 }
308
309 return ms_pLogger;
310 }
311
312 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
313 {
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 }
319
320 wxLog *pOldLogger = ms_pLogger;
321 ms_pLogger = pLogger;
322
323 return pOldLogger;
324 }
325
326 void 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
336 void wxLog::RemoveTraceMask(const wxString& str)
337 {
338 int index = ms_aTraceMasks.Index(str);
339 if ( index != wxNOT_FOUND )
340 ms_aTraceMasks.Remove((size_t)index);
341 }
342
343 void wxLog::ClearTraceMasks()
344 {
345 ms_aTraceMasks.Clear();
346 }
347
348 void wxLog::TimeStamp(wxString *str)
349 {
350 if ( ms_timestamp )
351 {
352 wxChar buf[256];
353 time_t timeNow;
354 (void)time(&timeNow);
355 wxStrftime(buf, WXSIZEOF(buf), ms_timestamp, localtime(&timeNow));
356
357 str->Empty();
358 *str << buf << wxT(": ");
359 }
360 }
361
362 void wxLog::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
363 {
364 switch ( level ) {
365 case wxLOG_FatalError:
366 DoLogString(wxString(_("Fatal error: ")) + szString, t);
367 DoLogString(_("Program aborted."), t);
368 Flush();
369 abort();
370 break;
371
372 case wxLOG_Error:
373 DoLogString(wxString(_("Error: ")) + szString, t);
374 break;
375
376 case wxLOG_Warning:
377 DoLogString(wxString(_("Warning: ")) + szString, t);
378 break;
379
380 case wxLOG_Info:
381 if ( GetVerbose() )
382 case wxLOG_Message:
383 case wxLOG_Status:
384 default: // log unknown log levels too
385 DoLogString(szString, t);
386 break;
387
388 case wxLOG_Trace:
389 case wxLOG_Debug:
390 #ifdef __WXDEBUG__
391 {
392 wxString msg = level == wxLOG_Trace ? wxT("Trace: ")
393 : wxT("Debug: ");
394 msg << szString;
395 DoLogString(msg, t);
396 }
397 #endif // Debug
398 break;
399 }
400 }
401
402 void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t WXUNUSED(t))
403 {
404 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
405 }
406
407 void wxLog::Flush()
408 {
409 // remember that we don't have any more messages to show
410 m_bHasMessages = FALSE;
411 }
412
413 // ----------------------------------------------------------------------------
414 // wxLogStderr class implementation
415 // ----------------------------------------------------------------------------
416
417 wxLogStderr::wxLogStderr(FILE *fp)
418 {
419 if ( fp == NULL )
420 m_fp = stderr;
421 else
422 m_fp = fp;
423 }
424
425 #if defined(__WXMAC__) && !defined(__DARWIN__)
426
427 #ifndef __MetroNubUtils__
428 #include "MetroNubUtils.h"
429 #endif
430
431 #ifdef __cplusplus
432 extern "C" {
433 #endif
434
435 #ifndef __GESTALT__
436 #include <Gestalt.h>
437 #endif
438
439 #ifndef true
440 #define true 1
441 #endif
442
443 #ifndef false
444 #define false 0
445 #endif
446
447 #if TARGET_API_MAC_CARBON
448
449 #include <CodeFragments.h>
450
451 EXTERN_API_C( long )
452 CallUniversalProc(UniversalProcPtr theProcPtr, ProcInfoType procInfo, ...);
453
454 ProcPtr gCallUniversalProc_Proc = NULL;
455
456 #endif
457
458 static MetroNubUserEntryBlock* gMetroNubEntry = NULL;
459
460 static long fRunOnce = false;
461
462 Boolean IsCompatibleVersion(short inVersion);
463
464 /* ---------------------------------------------------------------------------
465 IsCompatibleVersion
466 --------------------------------------------------------------------------- */
467
468 Boolean IsCompatibleVersion(short inVersion)
469 {
470 Boolean result = false;
471
472 if (fRunOnce)
473 {
474 MetroNubUserEntryBlock* block = (MetroNubUserEntryBlock *)result;
475
476 result = (inVersion <= block->apiHiVersion);
477 }
478
479 return result;
480 }
481
482 /* ---------------------------------------------------------------------------
483 IsMetroNubInstalled
484 --------------------------------------------------------------------------- */
485
486 Boolean IsMetroNubInstalled()
487 {
488 if (!fRunOnce)
489 {
490 long result, value;
491
492 fRunOnce = true;
493 gMetroNubEntry = NULL;
494
495 if (Gestalt(gestaltSystemVersion, &value) == noErr && value < 0x1000)
496 {
497 /* look for MetroNub's Gestalt selector */
498 if (Gestalt(kMetroNubUserSignature, &result) == noErr)
499 {
500
501 #if TARGET_API_MAC_CARBON
502 if (gCallUniversalProc_Proc == NULL)
503 {
504 CFragConnectionID connectionID;
505 Ptr mainAddress;
506 Str255 errorString;
507 ProcPtr symbolAddress;
508 OSErr err;
509 CFragSymbolClass symbolClass;
510
511 symbolAddress = NULL;
512 err = GetSharedLibrary("\pInterfaceLib", kPowerPCCFragArch, kFindCFrag,
513 &connectionID, &mainAddress, errorString);
514
515 if (err != noErr)
516 {
517 gCallUniversalProc_Proc = NULL;
518 goto end;
519 }
520
521 err = FindSymbol(connectionID, "\pCallUniversalProc",
522 (Ptr *) &gCallUniversalProc_Proc, &symbolClass);
523
524 if (err != noErr)
525 {
526 gCallUniversalProc_Proc = NULL;
527 goto end;
528 }
529 }
530 #endif
531
532 {
533 MetroNubUserEntryBlock* block = (MetroNubUserEntryBlock *)result;
534
535 /* make sure the version of the API is compatible */
536 if (block->apiLowVersion <= kMetroNubUserAPIVersion &&
537 kMetroNubUserAPIVersion <= block->apiHiVersion)
538 gMetroNubEntry = block; /* success! */
539 }
540
541 }
542 }
543 }
544
545 end:
546
547 #if TARGET_API_MAC_CARBON
548 return (gMetroNubEntry != NULL && gCallUniversalProc_Proc != NULL);
549 #else
550 return (gMetroNubEntry != NULL);
551 #endif
552 }
553
554 /* ---------------------------------------------------------------------------
555 IsMWDebuggerRunning [v1 API]
556 --------------------------------------------------------------------------- */
557
558 Boolean IsMWDebuggerRunning()
559 {
560 if (IsMetroNubInstalled())
561 return CallIsDebuggerRunningProc(gMetroNubEntry->isDebuggerRunning);
562 else
563 return false;
564 }
565
566 /* ---------------------------------------------------------------------------
567 AmIBeingMWDebugged [v1 API]
568 --------------------------------------------------------------------------- */
569
570 Boolean AmIBeingMWDebugged()
571 {
572 if (IsMetroNubInstalled())
573 return CallAmIBeingDebuggedProc(gMetroNubEntry->amIBeingDebugged);
574 else
575 return false;
576 }
577
578 /* ---------------------------------------------------------------------------
579 UserSetWatchPoint [v2 API]
580 --------------------------------------------------------------------------- */
581
582 OSErr UserSetWatchPoint (Ptr address, long length, WatchPointIDT* watchPointID)
583 {
584 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion))
585 return CallUserSetWatchPointProc(gMetroNubEntry->userSetWatchPoint,
586 address, length, watchPointID);
587 else
588 return errProcessIsNotClient;
589 }
590
591 /* ---------------------------------------------------------------------------
592 ClearWatchPoint [v2 API]
593 --------------------------------------------------------------------------- */
594
595 OSErr ClearWatchPoint (WatchPointIDT watchPointID)
596 {
597 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion))
598 return CallClearWatchPointProc(gMetroNubEntry->clearWatchPoint,
599 watchPointID);
600 else
601 return errProcessIsNotClient;
602 }
603
604 #ifdef __cplusplus
605 }
606 #endif
607
608 #endif
609
610 void wxLogStderr::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
611 {
612 wxString str;
613 TimeStamp(&str);
614 str << szString;
615
616 fputs(str.mb_str(), m_fp);
617 fputc(_T('\n'), m_fp);
618 fflush(m_fp);
619
620 // under Windows, programs usually don't have stderr at all, so show the
621 // messages also under debugger - unless it's a console program
622 #if defined(__WXMSW__) && wxUSE_GUI && !defined(__WXMICROWIN__)
623 str += wxT("\r\n") ;
624 OutputDebugString(str.c_str());
625 #endif // MSW
626 #if defined(__WXMAC__) && !defined(__DARWIN__) && wxUSE_GUI
627 Str255 pstr ;
628 strcpy( (char*) pstr , str.c_str() ) ;
629 strcat( (char*) pstr , ";g" ) ;
630 c2pstr( (char*) pstr ) ;
631
632 Boolean running = false ;
633
634 if ( IsMWDebuggerRunning() && AmIBeingMWDebugged() )
635 {
636 running = true ;
637 }
638
639 if (running)
640 {
641 #ifdef __powerc
642 DebugStr(pstr);
643 #else
644 SysBreakStr(pstr);
645 #endif
646 }
647 #endif // Mac
648 }
649
650 // ----------------------------------------------------------------------------
651 // wxLogStream implementation
652 // ----------------------------------------------------------------------------
653
654 #if wxUSE_STD_IOSTREAM
655 wxLogStream::wxLogStream(wxSTD ostream *ostr)
656 {
657 if ( ostr == NULL )
658 m_ostr = &wxSTD cerr;
659 else
660 m_ostr = ostr;
661 }
662
663 void wxLogStream::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
664 {
665 wxString str;
666 TimeStamp(&str);
667 (*m_ostr) << str << wxConvertWX2MB(szString) << wxSTD endl;
668 }
669 #endif // wxUSE_STD_IOSTREAM
670
671 // ----------------------------------------------------------------------------
672 // wxLogChain
673 // ----------------------------------------------------------------------------
674
675 wxLogChain::wxLogChain(wxLog *logger)
676 {
677 m_logNew = logger;
678 m_logOld = wxLog::SetActiveTarget(this);
679 }
680
681 void wxLogChain::SetLog(wxLog *logger)
682 {
683 if ( m_logNew != this )
684 delete m_logNew;
685
686 wxLog::SetActiveTarget(logger);
687
688 m_logNew = logger;
689 }
690
691 void wxLogChain::Flush()
692 {
693 if ( m_logOld )
694 m_logOld->Flush();
695
696 // be careful to avoid inifinite recursion
697 if ( m_logNew && m_logNew != this )
698 m_logNew->Flush();
699 }
700
701 void wxLogChain::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
702 {
703 // let the previous logger show it
704 if ( m_logOld && IsPassingMessages() )
705 {
706 // bogus cast just to access protected DoLog
707 ((wxLogChain *)m_logOld)->DoLog(level, szString, t);
708 }
709
710 if ( m_logNew && m_logNew != this )
711 {
712 // as above...
713 ((wxLogChain *)m_logNew)->DoLog(level, szString, t);
714 }
715 }
716
717 // ----------------------------------------------------------------------------
718 // wxLogPassThrough
719 // ----------------------------------------------------------------------------
720
721 #ifdef __VISUALC__
722 // "'this' : used in base member initializer list" - so what?
723 #pragma warning(disable:4355)
724 #endif // VC++
725
726 wxLogPassThrough::wxLogPassThrough()
727 : wxLogChain(this)
728 {
729 }
730
731 #ifdef __VISUALC__
732 #pragma warning(default:4355)
733 #endif // VC++
734
735 // ============================================================================
736 // Global functions/variables
737 // ============================================================================
738
739 // ----------------------------------------------------------------------------
740 // static variables
741 // ----------------------------------------------------------------------------
742
743 wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
744 bool wxLog::ms_doLog = TRUE;
745 bool wxLog::ms_bAutoCreate = TRUE;
746 bool wxLog::ms_bVerbose = FALSE;
747
748 size_t wxLog::ms_suspendCount = 0;
749
750 #if wxUSE_GUI
751 const wxChar *wxLog::ms_timestamp = wxT("%X"); // time only, no date
752 #else
753 const wxChar *wxLog::ms_timestamp = NULL; // save space
754 #endif
755
756 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
757 wxArrayString wxLog::ms_aTraceMasks;
758
759 // ----------------------------------------------------------------------------
760 // stdout error logging helper
761 // ----------------------------------------------------------------------------
762
763 // helper function: wraps the message and justifies it under given position
764 // (looks more pretty on the terminal). Also adds newline at the end.
765 //
766 // TODO this is now disabled until I find a portable way of determining the
767 // terminal window size (ok, I found it but does anybody really cares?)
768 #ifdef LOG_PRETTY_WRAP
769 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
770 {
771 size_t nMax = 80; // FIXME
772 size_t nStart = strlen(pszPrefix);
773 fputs(pszPrefix, f);
774
775 size_t n;
776 while ( *psz != '\0' ) {
777 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
778 putc(*psz++, f);
779
780 // wrapped?
781 if ( *psz != '\0' ) {
782 /*putc('\n', f);*/
783 for ( n = 0; n < nStart; n++ )
784 putc(' ', f);
785
786 // as we wrapped, squeeze all white space
787 while ( isspace(*psz) )
788 psz++;
789 }
790 }
791
792 putc('\n', f);
793 }
794 #endif //LOG_PRETTY_WRAP
795
796 // ----------------------------------------------------------------------------
797 // error code/error message retrieval functions
798 // ----------------------------------------------------------------------------
799
800 // get error code from syste
801 unsigned long wxSysErrorCode()
802 {
803 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
804 #ifdef __WIN32__
805 return ::GetLastError();
806 #else //WIN16
807 // TODO what to do on Windows 3.1?
808 return 0;
809 #endif //WIN16/32
810 #else //Unix
811 return errno;
812 #endif //Win/Unix
813 }
814
815 // get error message from system
816 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
817 {
818 if ( nErrCode == 0 )
819 nErrCode = wxSysErrorCode();
820
821 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
822 #ifdef __WIN32__
823 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
824
825 // get error message from system
826 LPVOID lpMsgBuf;
827 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
828 NULL, nErrCode,
829 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
830 (LPTSTR)&lpMsgBuf,
831 0, NULL);
832
833 // copy it to our buffer and free memory
834 if( lpMsgBuf != 0 ) {
835 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
836 s_szBuf[WXSIZEOF(s_szBuf) - 1] = wxT('\0');
837
838 LocalFree(lpMsgBuf);
839
840 // returned string is capitalized and ended with '\r\n' - bad
841 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
842 size_t len = wxStrlen(s_szBuf);
843 if ( len > 0 ) {
844 // truncate string
845 if ( s_szBuf[len - 2] == wxT('\r') )
846 s_szBuf[len - 2] = wxT('\0');
847 }
848 }
849 else {
850 s_szBuf[0] = wxT('\0');
851 }
852
853 return s_szBuf;
854 #else //Win16
855 // TODO
856 return NULL;
857 #endif // Win16/32
858 #else // Unix
859 #if wxUSE_UNICODE
860 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
861 wxConvCurrent->MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
862 return s_szBuf;
863 #else
864 return strerror((int)nErrCode);
865 #endif
866 #endif // Win/Unix
867 }
868
869 #endif //wxUSE_LOG