Removed another occurrence of previous log critical section (should have been
[wxWidgets.git] / src / common / log.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/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 licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_LOG
28
29 // wxWidgets
30 #ifndef WX_PRECOMP
31 #include "wx/log.h"
32 #include "wx/app.h"
33 #include "wx/arrstr.h"
34 #include "wx/intl.h"
35 #include "wx/string.h"
36 #include "wx/utils.h"
37 #endif //WX_PRECOMP
38
39 #include "wx/apptrait.h"
40 #include "wx/datetime.h"
41 #include "wx/file.h"
42 #include "wx/msgout.h"
43 #include "wx/textfile.h"
44 #include "wx/thread.h"
45 #include "wx/crt.h"
46 #include "wx/vector.h"
47
48 // other standard headers
49 #ifndef __WXWINCE__
50 #include <errno.h>
51 #endif
52
53 #include <stdlib.h>
54
55 #ifndef __WXPALMOS5__
56 #ifndef __WXWINCE__
57 #include <time.h>
58 #else
59 #include "wx/msw/wince/time.h"
60 #endif
61 #endif /* ! __WXPALMOS5__ */
62
63 #if defined(__WINDOWS__)
64 #include "wx/msw/private.h" // includes windows.h
65 #endif
66
67 #undef wxLOG_COMPONENT
68 const char *wxLOG_COMPONENT = "";
69
70 #if wxUSE_THREADS
71
72 namespace
73 {
74
75 // contains messages logged by the other threads and waiting to be shown until
76 // Flush() is called in the main one
77 typedef wxVector<wxLogRecord> wxLogRecords;
78 wxLogRecords gs_bufferedLogRecords;
79
80
81 // define static functions providing access to the critical sections we use
82 // instead of just using static critical section variables as log functions may
83 // be used during static initialization and while this is certainly not
84 // advisable it's still better to not crash (as we'd do if we used a yet
85 // uninitialized critical section) if it happens
86
87 // this critical section is used for buffering the messages from threads other
88 // than main, i.e. it protects all accesses to gs_bufferedLogRecords above
89 inline wxCriticalSection& GetBackgroundLogCS()
90 {
91 static wxCriticalSection s_csBackground;
92
93 return s_csBackground;
94 }
95
96 inline wxCriticalSection& GetTraceMaskCS()
97 {
98 static wxCriticalSection s_csTrace;
99
100 return s_csTrace;
101 }
102
103 inline wxCriticalSection& GetLevelsCS()
104 {
105 static wxCriticalSection s_csLevels;
106
107 return s_csLevels;
108 }
109
110 } // anonymous namespace
111
112 #endif // wxUSE_THREADS
113
114 // ----------------------------------------------------------------------------
115 // non member functions
116 // ----------------------------------------------------------------------------
117
118 // define this to enable wrapping of log messages
119 //#define LOG_PRETTY_WRAP
120
121 #ifdef LOG_PRETTY_WRAP
122 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
123 #endif
124
125 // ----------------------------------------------------------------------------
126 // module globals
127 // ----------------------------------------------------------------------------
128
129 namespace
130 {
131
132 // this struct is used to store information about the previous log message used
133 // by OnLog() to (optionally) avoid logging multiple copies of the same message
134 struct PreviousLogInfo
135 {
136 PreviousLogInfo()
137 {
138 numRepeated = 0;
139 }
140
141
142 // previous message itself
143 wxString msg;
144
145 // its level
146 wxLogLevel level;
147
148 // other information about it
149 wxLogRecordInfo info;
150
151 // the number of times it was already repeated
152 unsigned numRepeated;
153 };
154
155 PreviousLogInfo gs_prevLog;
156
157
158 // map containing all components for which log level was explicitly set
159 //
160 // NB: all accesses to it must be protected by GetLevelsCS() critical section
161 wxStringToNumHashMap gs_componentLevels;
162
163 } // anonymous namespace
164
165 // ============================================================================
166 // implementation
167 // ============================================================================
168
169 // ----------------------------------------------------------------------------
170 // helper global functions
171 // ----------------------------------------------------------------------------
172
173 void wxSafeShowMessage(const wxString& title, const wxString& text)
174 {
175 #ifdef __WINDOWS__
176 ::MessageBox(NULL, text.t_str(), title.t_str(), MB_OK | MB_ICONSTOP);
177 #else
178 wxFprintf(stderr, wxS("%s: %s\n"), title.c_str(), text.c_str());
179 fflush(stderr);
180 #endif
181 }
182
183 // ----------------------------------------------------------------------------
184 // wxLog class implementation
185 // ----------------------------------------------------------------------------
186
187 unsigned wxLog::LogLastRepeatIfNeeded()
188 {
189 const unsigned count = gs_prevLog.numRepeated;
190
191 if ( gs_prevLog.numRepeated )
192 {
193 wxString msg;
194 #if wxUSE_INTL
195 msg.Printf(wxPLURAL("The previous message repeated once.",
196 "The previous message repeated %lu times.",
197 gs_prevLog.numRepeated),
198 gs_prevLog.numRepeated);
199 #else
200 msg.Printf(wxS("The previous message was repeated %lu times."),
201 gs_prevLog.numRepeated);
202 #endif
203 gs_prevLog.numRepeated = 0;
204 gs_prevLog.msg.clear();
205 DoLogRecord(gs_prevLog.level, msg, gs_prevLog.info);
206 }
207
208 return count;
209 }
210
211 wxLog::~wxLog()
212 {
213 // Flush() must be called before destroying the object as otherwise some
214 // messages could be lost
215 if ( gs_prevLog.numRepeated )
216 {
217 wxMessageOutputDebug().Printf
218 (
219 wxS("Last repeated message (\"%s\", %lu times) wasn't output"),
220 gs_prevLog.msg,
221 gs_prevLog.numRepeated
222 );
223 }
224 }
225
226 // ----------------------------------------------------------------------------
227 // wxLog logging functions
228 // ----------------------------------------------------------------------------
229
230 /* static */
231 void
232 wxLog::OnLog(wxLogLevel level, const wxString& msg, time_t t)
233 {
234 wxLogRecordInfo info;
235 info.timestamp = t;
236 #if wxUSE_THREADS
237 info.threadId = wxThread::GetCurrentId();
238 #endif // wxUSE_THREADS
239
240 OnLog(level, msg, info);
241 }
242
243 /* static */
244 void
245 wxLog::OnLog(wxLogLevel level,
246 const wxString& msg,
247 const wxLogRecordInfo& info)
248 {
249 // fatal errors can't be suppressed nor handled by the custom log target
250 // and always terminate the program
251 if ( level == wxLOG_FatalError )
252 {
253 wxSafeShowMessage(wxS("Fatal Error"), msg);
254
255 #ifdef __WXWINCE__
256 ExitThread(3);
257 #else
258 abort();
259 #endif
260 }
261
262 wxLog *pLogger = GetActiveTarget();
263 if ( !pLogger )
264 return;
265
266 #if wxUSE_THREADS
267 if ( !wxThread::IsMain() )
268 {
269 wxCriticalSectionLocker lock(GetBackgroundLogCS());
270
271 gs_bufferedLogRecords.push_back(wxLogRecord(level, msg, info));
272
273 // ensure that our Flush() will be called soon
274 wxWakeUpIdle();
275
276 return;
277 }
278 #endif // wxUSE_THREADS
279
280 pLogger->OnLogInMainThread(level, msg, info);
281 }
282
283 void
284 wxLog::OnLogInMainThread(wxLogLevel level,
285 const wxString& msg,
286 const wxLogRecordInfo& info)
287 {
288 if ( GetRepetitionCounting() )
289 {
290 if ( msg == gs_prevLog.msg )
291 {
292 gs_prevLog.numRepeated++;
293
294 // nothing else to do, in particular, don't log the
295 // repeated message
296 return;
297 }
298
299 LogLastRepeatIfNeeded();
300
301 // reset repetition counter for a new message
302 gs_prevLog.msg = msg;
303 gs_prevLog.level = level;
304 gs_prevLog.info = info;
305 }
306
307 // handle extra data which may be passed to us by wxLogXXX()
308 wxString prefix, suffix;
309 wxUIntPtr num = 0;
310 if ( info.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE, &num) )
311 {
312 long err = static_cast<long>(num);
313 if ( !err )
314 err = wxSysErrorCode();
315
316 suffix.Printf(_(" (error %ld: %s)"), err, wxSysErrorMsg(err));
317 }
318
319 #if wxUSE_LOG_TRACE
320 wxString str;
321 if ( level == wxLOG_Trace && info.GetStrValue(wxLOG_KEY_TRACE_MASK, &str) )
322 {
323 prefix = "(" + str + ") ";
324 }
325 #endif // wxUSE_LOG_TRACE
326
327 DoLogRecord(level, prefix + msg + suffix, info);
328 }
329
330 void wxLog::DoLogRecord(wxLogLevel level,
331 const wxString& msg,
332 const wxLogRecordInfo& info)
333 {
334 #if WXWIN_COMPATIBILITY_2_8
335 // call the old DoLog() to ensure that existing custom log classes still
336 // work
337 //
338 // as the user code could have defined it as either taking "const char *"
339 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
340 // but to call both of them
341 DoLog(level, (const char*)msg.mb_str(), info.timestamp);
342 DoLog(level, (const wchar_t*)msg.wc_str(), info.timestamp);
343 #endif // WXWIN_COMPATIBILITY_2_8
344
345
346 // TODO: it would be better to extract message formatting in a separate
347 // wxLogFormatter class but for now we hard code formatting here
348
349 wxString prefix;
350
351 // don't time stamp debug messages under MSW as debug viewers usually
352 // already have an option to do it
353 #ifdef __WXMSW__
354 if ( level != wxLOG_Debug && level != wxLOG_Trace )
355 #endif // __WXMSW__
356 TimeStamp(&prefix);
357
358 // TODO: use the other wxLogRecordInfo fields
359
360 switch ( level )
361 {
362 case wxLOG_Error:
363 prefix += _("Error: ");
364 break;
365
366 case wxLOG_Warning:
367 prefix += _("Warning: ");
368 break;
369
370 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
371 // window anyhow and so can't be confused with something else
372 #ifndef __WXMSW__
373 case wxLOG_Debug:
374 // this prefix (as well as the one below) is intentionally not
375 // translated as nobody translates debug messages anyhow
376 prefix += "Debug: ";
377 break;
378
379 case wxLOG_Trace:
380 prefix += "Trace: ";
381 break;
382 #endif // !__WXMSW__
383 }
384
385 DoLogTextAtLevel(level, prefix + msg);
386 }
387
388 void wxLog::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
389 {
390 // we know about debug messages (because using wxMessageOutputDebug is the
391 // right thing to do in 99% of all cases and also for compatibility) but
392 // anything else needs to be handled in the derived class
393 if ( level == wxLOG_Debug || level == wxLOG_Trace )
394 {
395 wxMessageOutputDebug().Output(msg + wxS('\n'));
396 }
397 else
398 {
399 DoLogText(msg);
400 }
401 }
402
403 void wxLog::DoLogText(const wxString& WXUNUSED(msg))
404 {
405 // in 2.8-compatible build the derived class might override DoLog() or
406 // DoLogString() instead so we can't have this assert there
407 #if !WXWIN_COMPATIBILITY_2_8
408 wxFAIL_MSG( "must be overridden if it is called" );
409 #endif // WXWIN_COMPATIBILITY_2_8
410 }
411
412 #if WXWIN_COMPATIBILITY_2_8
413
414 void wxLog::DoLog(wxLogLevel WXUNUSED(level), const char *szString, time_t t)
415 {
416 DoLogString(szString, t);
417 }
418
419 void wxLog::DoLog(wxLogLevel WXUNUSED(level), const wchar_t *wzString, time_t t)
420 {
421 DoLogString(wzString, t);
422 }
423
424 #endif // WXWIN_COMPATIBILITY_2_8
425
426 // ----------------------------------------------------------------------------
427 // wxLog active target management
428 // ----------------------------------------------------------------------------
429
430 wxLog *wxLog::GetActiveTarget()
431 {
432 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
433 // prevent infinite recursion if someone calls wxLogXXX() from
434 // wxApp::CreateLogTarget()
435 static bool s_bInGetActiveTarget = false;
436 if ( !s_bInGetActiveTarget ) {
437 s_bInGetActiveTarget = true;
438
439 // ask the application to create a log target for us
440 if ( wxTheApp != NULL )
441 ms_pLogger = wxTheApp->GetTraits()->CreateLogTarget();
442 else
443 ms_pLogger = new wxLogStderr;
444
445 s_bInGetActiveTarget = false;
446
447 // do nothing if it fails - what can we do?
448 }
449 }
450
451 return ms_pLogger;
452 }
453
454 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
455 {
456 if ( ms_pLogger != NULL ) {
457 // flush the old messages before changing because otherwise they might
458 // get lost later if this target is not restored
459 ms_pLogger->Flush();
460 }
461
462 wxLog *pOldLogger = ms_pLogger;
463 ms_pLogger = pLogger;
464
465 return pOldLogger;
466 }
467
468 void wxLog::DontCreateOnDemand()
469 {
470 ms_bAutoCreate = false;
471
472 // this is usually called at the end of the program and we assume that it
473 // is *always* called at the end - so we free memory here to avoid false
474 // memory leak reports from wxWin memory tracking code
475 ClearTraceMasks();
476 }
477
478 void wxLog::DoCreateOnDemand()
479 {
480 ms_bAutoCreate = true;
481 }
482
483 // ----------------------------------------------------------------------------
484 // wxLog components levels
485 // ----------------------------------------------------------------------------
486
487 /* static */
488 void wxLog::SetComponentLevel(const wxString& component, wxLogLevel level)
489 {
490 if ( component.empty() )
491 {
492 SetLogLevel(level);
493 }
494 else
495 {
496 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
497
498 gs_componentLevels[component] = level;
499 }
500 }
501
502 /* static */
503 wxLogLevel wxLog::GetComponentLevel(wxString component)
504 {
505 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
506
507 while ( !component.empty() )
508 {
509 wxStringToNumHashMap::const_iterator
510 it = gs_componentLevels.find(component);
511 if ( it != gs_componentLevels.end() )
512 return static_cast<wxLogLevel>(it->second);
513
514 component = component.BeforeLast('/');
515 }
516
517 return GetLogLevel();
518 }
519
520 // ----------------------------------------------------------------------------
521 // wxLog trace masks
522 // ----------------------------------------------------------------------------
523
524 void wxLog::AddTraceMask(const wxString& str)
525 {
526 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
527
528 ms_aTraceMasks.push_back(str);
529 }
530
531 void wxLog::RemoveTraceMask(const wxString& str)
532 {
533 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
534
535 int index = ms_aTraceMasks.Index(str);
536 if ( index != wxNOT_FOUND )
537 ms_aTraceMasks.RemoveAt((size_t)index);
538 }
539
540 void wxLog::ClearTraceMasks()
541 {
542 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
543
544 ms_aTraceMasks.Clear();
545 }
546
547 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString& mask)
548 {
549 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
550
551 for ( wxArrayString::iterator it = ms_aTraceMasks.begin(),
552 en = ms_aTraceMasks.end();
553 it != en; ++it )
554 {
555 if ( *it == mask)
556 return true;
557 }
558
559 return false;
560 }
561
562 // ----------------------------------------------------------------------------
563 // wxLog miscellaneous other methods
564 // ----------------------------------------------------------------------------
565
566 void wxLog::TimeStamp(wxString *str)
567 {
568 #if wxUSE_DATETIME
569 if ( !ms_timestamp.empty() )
570 {
571 wxChar buf[256];
572 time_t timeNow;
573 (void)time(&timeNow);
574
575 struct tm tm;
576 wxStrftime(buf, WXSIZEOF(buf),
577 ms_timestamp, wxLocaltime_r(&timeNow, &tm));
578
579 str->Empty();
580 *str << buf << wxS(": ");
581 }
582 #endif // wxUSE_DATETIME
583 }
584
585 void wxLog::Flush()
586 {
587 #if wxUSE_THREADS
588 wxASSERT_MSG( wxThread::IsMain(),
589 "should be called from the main thread only" );
590
591 // check if we have queued messages from other threads
592 wxLogRecords bufferedLogRecords;
593
594 {
595 wxCriticalSectionLocker lock(GetBackgroundLogCS());
596 bufferedLogRecords.swap(gs_bufferedLogRecords);
597
598 // release the lock now to not keep it while we are logging the
599 // messages below, allowing background threads to run
600 }
601
602 if ( !bufferedLogRecords.empty() )
603 {
604 for ( wxLogRecords::const_iterator it = bufferedLogRecords.begin();
605 it != bufferedLogRecords.end();
606 ++it )
607 {
608 OnLogInMainThread(it->level, it->msg, it->info);
609 }
610 }
611 #endif // wxUSE_THREADS
612
613 LogLastRepeatIfNeeded();
614 }
615
616 // ----------------------------------------------------------------------------
617 // wxLogBuffer implementation
618 // ----------------------------------------------------------------------------
619
620 void wxLogBuffer::Flush()
621 {
622 wxLog::Flush();
623
624 if ( !m_str.empty() )
625 {
626 wxMessageOutputBest out;
627 out.Printf(wxS("%s"), m_str.c_str());
628 m_str.clear();
629 }
630 }
631
632 void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
633 {
634 // don't put debug messages in the buffer, we don't want to show
635 // them to the user in a msg box, log them immediately
636 switch ( level )
637 {
638 case wxLOG_Debug:
639 case wxLOG_Trace:
640 wxLog::DoLogTextAtLevel(level, msg);
641 break;
642
643 default:
644 m_str << msg << wxS("\n");
645 }
646 }
647
648 // ----------------------------------------------------------------------------
649 // wxLogStderr class implementation
650 // ----------------------------------------------------------------------------
651
652 wxLogStderr::wxLogStderr(FILE *fp)
653 {
654 if ( fp == NULL )
655 m_fp = stderr;
656 else
657 m_fp = fp;
658 }
659
660 void wxLogStderr::DoLogText(const wxString& msg)
661 {
662 wxFputs(msg + '\n', m_fp);
663 fflush(m_fp);
664
665 // under GUI systems such as Windows or Mac, programs usually don't have
666 // stderr at all, so show the messages also somewhere else, typically in
667 // the debugger window so that they go at least somewhere instead of being
668 // simply lost
669 if ( m_fp == stderr )
670 {
671 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
672 if ( traits && !traits->HasStderr() )
673 {
674 wxMessageOutputDebug().Output(msg + wxS('\n'));
675 }
676 }
677 }
678
679 // ----------------------------------------------------------------------------
680 // wxLogStream implementation
681 // ----------------------------------------------------------------------------
682
683 #if wxUSE_STD_IOSTREAM
684 #include "wx/ioswrap.h"
685 wxLogStream::wxLogStream(wxSTD ostream *ostr)
686 {
687 if ( ostr == NULL )
688 m_ostr = &wxSTD cerr;
689 else
690 m_ostr = ostr;
691 }
692
693 void wxLogStream::DoLogText(const wxString& msg)
694 {
695 (*m_ostr) << msg << wxSTD endl;
696 }
697 #endif // wxUSE_STD_IOSTREAM
698
699 // ----------------------------------------------------------------------------
700 // wxLogChain
701 // ----------------------------------------------------------------------------
702
703 wxLogChain::wxLogChain(wxLog *logger)
704 {
705 m_bPassMessages = true;
706
707 m_logNew = logger;
708 m_logOld = wxLog::SetActiveTarget(this);
709 }
710
711 wxLogChain::~wxLogChain()
712 {
713 delete m_logOld;
714
715 if ( m_logNew != this )
716 delete m_logNew;
717 }
718
719 void wxLogChain::SetLog(wxLog *logger)
720 {
721 if ( m_logNew != this )
722 delete m_logNew;
723
724 m_logNew = logger;
725 }
726
727 void wxLogChain::Flush()
728 {
729 if ( m_logOld )
730 m_logOld->Flush();
731
732 // be careful to avoid infinite recursion
733 if ( m_logNew && m_logNew != this )
734 m_logNew->Flush();
735 }
736
737 void wxLogChain::DoLogRecord(wxLogLevel level,
738 const wxString& msg,
739 const wxLogRecordInfo& info)
740 {
741 // let the previous logger show it
742 if ( m_logOld && IsPassingMessages() )
743 m_logOld->LogRecord(level, msg, info);
744
745 // and also send it to the new one
746 if ( m_logNew && m_logNew != this )
747 m_logNew->LogRecord(level, msg, info);
748 }
749
750 #ifdef __VISUALC__
751 // "'this' : used in base member initializer list" - so what?
752 #pragma warning(disable:4355)
753 #endif // VC++
754
755 // ----------------------------------------------------------------------------
756 // wxLogInterposer
757 // ----------------------------------------------------------------------------
758
759 wxLogInterposer::wxLogInterposer()
760 : wxLogChain(this)
761 {
762 }
763
764 // ----------------------------------------------------------------------------
765 // wxLogInterposerTemp
766 // ----------------------------------------------------------------------------
767
768 wxLogInterposerTemp::wxLogInterposerTemp()
769 : wxLogChain(this)
770 {
771 DetachOldLog();
772 }
773
774 #ifdef __VISUALC__
775 #pragma warning(default:4355)
776 #endif // VC++
777
778 // ============================================================================
779 // Global functions/variables
780 // ============================================================================
781
782 // ----------------------------------------------------------------------------
783 // static variables
784 // ----------------------------------------------------------------------------
785
786 bool wxLog::ms_bRepetCounting = false;
787
788 wxLog *wxLog::ms_pLogger = NULL;
789 bool wxLog::ms_doLog = true;
790 bool wxLog::ms_bAutoCreate = true;
791 bool wxLog::ms_bVerbose = false;
792
793 wxLogLevel wxLog::ms_logLevel = wxLOG_Max; // log everything by default
794
795 size_t wxLog::ms_suspendCount = 0;
796
797 wxString wxLog::ms_timestamp(wxS("%X")); // time only, no date
798
799 #if WXWIN_COMPATIBILITY_2_8
800 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
801 #endif // wxDEBUG_LEVEL
802
803 wxArrayString wxLog::ms_aTraceMasks;
804
805 // ----------------------------------------------------------------------------
806 // stdout error logging helper
807 // ----------------------------------------------------------------------------
808
809 // helper function: wraps the message and justifies it under given position
810 // (looks more pretty on the terminal). Also adds newline at the end.
811 //
812 // TODO this is now disabled until I find a portable way of determining the
813 // terminal window size (ok, I found it but does anybody really cares?)
814 #ifdef LOG_PRETTY_WRAP
815 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
816 {
817 size_t nMax = 80; // FIXME
818 size_t nStart = strlen(pszPrefix);
819 fputs(pszPrefix, f);
820
821 size_t n;
822 while ( *psz != '\0' ) {
823 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
824 putc(*psz++, f);
825
826 // wrapped?
827 if ( *psz != '\0' ) {
828 /*putc('\n', f);*/
829 for ( n = 0; n < nStart; n++ )
830 putc(' ', f);
831
832 // as we wrapped, squeeze all white space
833 while ( isspace(*psz) )
834 psz++;
835 }
836 }
837
838 putc('\n', f);
839 }
840 #endif //LOG_PRETTY_WRAP
841
842 // ----------------------------------------------------------------------------
843 // error code/error message retrieval functions
844 // ----------------------------------------------------------------------------
845
846 // get error code from syste
847 unsigned long wxSysErrorCode()
848 {
849 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
850 return ::GetLastError();
851 #else //Unix
852 return errno;
853 #endif //Win/Unix
854 }
855
856 // get error message from system
857 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
858 {
859 if ( nErrCode == 0 )
860 nErrCode = wxSysErrorCode();
861
862 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
863 static wxChar s_szBuf[1024];
864
865 // get error message from system
866 LPVOID lpMsgBuf;
867 if ( ::FormatMessage
868 (
869 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
870 NULL,
871 nErrCode,
872 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
873 (LPTSTR)&lpMsgBuf,
874 0,
875 NULL
876 ) == 0 )
877 {
878 // if this happens, something is seriously wrong, so don't use _() here
879 // for safety
880 wxSprintf(s_szBuf, wxS("unknown error %lx"), nErrCode);
881 return s_szBuf;
882 }
883
884
885 // copy it to our buffer and free memory
886 // Crashes on SmartPhone (FIXME)
887 #if !defined(__SMARTPHONE__) /* of WinCE */
888 if( lpMsgBuf != 0 )
889 {
890 wxStrlcpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf));
891
892 LocalFree(lpMsgBuf);
893
894 // returned string is capitalized and ended with '\r\n' - bad
895 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
896 size_t len = wxStrlen(s_szBuf);
897 if ( len > 0 ) {
898 // truncate string
899 if ( s_szBuf[len - 2] == wxS('\r') )
900 s_szBuf[len - 2] = wxS('\0');
901 }
902 }
903 else
904 #endif // !__SMARTPHONE__
905 {
906 s_szBuf[0] = wxS('\0');
907 }
908
909 return s_szBuf;
910 #else // !__WXMSW__
911 #if wxUSE_UNICODE
912 static wchar_t s_wzBuf[1024];
913 wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
914 WXSIZEOF(s_wzBuf) - 1);
915 return s_wzBuf;
916 #else
917 return strerror((int)nErrCode);
918 #endif
919 #endif // __WXMSW__/!__WXMSW__
920 }
921
922 #endif // wxUSE_LOG