wxSize/wxPoint/wxRect versions of functions added to wxMSW, wxMotif;
[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 #include <wx/frame.h>
37
38 #include <wx/generic/msgdlgg.h>
39 #include <wx/filedlg.h>
40 #include <wx/textctrl.h>
41 #endif //WX_PRECOMP
42
43 #include <wx/file.h>
44 #include <wx/textfile.h>
45 #include <wx/utils.h>
46 #include <wx/log.h>
47
48 // other standard headers
49 #include <errno.h>
50 #include <stdlib.h>
51 #include <time.h>
52
53 #ifdef __WXMSW__
54 #include <windows.h>
55 #else //Unix
56 #include <signal.h>
57 #endif //Win/Unix
58
59 // ----------------------------------------------------------------------------
60 // non member functions
61 // ----------------------------------------------------------------------------
62
63 // define this to enable wrapping of log messages
64 //#define LOG_PRETTY_WRAP
65
66 #ifdef LOG_PRETTY_WRAP
67 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
68 #endif
69
70 // ----------------------------------------------------------------------------
71 // global variables
72 // ----------------------------------------------------------------------------
73
74 // we use a global variable to store the frame pointer for wxLogStatus - bad,
75 // but it's he easiest way
76 static wxFrame *gs_pFrame;
77
78 // ============================================================================
79 // implementation
80 // ============================================================================
81
82 // ----------------------------------------------------------------------------
83 // implementation of Log functions
84 //
85 // NB: unfortunately we need all these distinct functions, we can't make them
86 // macros and not all compilers inline vararg functions.
87 // ----------------------------------------------------------------------------
88
89 // log functions can't allocate memory (LogError("out of memory...") should
90 // work!), so we use a static buffer for all log messages
91 #define LOG_BUFFER_SIZE (4096)
92
93 // static buffer for error messages (@@@ MT-unsafe)
94 static char s_szBuf[LOG_BUFFER_SIZE];
95
96 // generic log function
97 void wxLogGeneric(wxLogLevel level, const char *szFormat, ...)
98 {
99 if ( wxLog::GetActiveTarget() != NULL ) {
100 va_list argptr;
101 va_start(argptr, szFormat);
102 vsprintf(s_szBuf, szFormat, argptr);
103 va_end(argptr);
104
105 wxLog::OnLog(level, s_szBuf);
106 }
107 }
108
109 #define IMPLEMENT_LOG_FUNCTION(level) \
110 void wxLog##level(const char *szFormat, ...) \
111 { \
112 if ( wxLog::GetActiveTarget() != NULL ) { \
113 va_list argptr; \
114 va_start(argptr, szFormat); \
115 vsprintf(s_szBuf, szFormat, argptr); \
116 va_end(argptr); \
117 \
118 wxLog::OnLog(wxLOG_##level, s_szBuf); \
119 } \
120 }
121
122 IMPLEMENT_LOG_FUNCTION(FatalError)
123 IMPLEMENT_LOG_FUNCTION(Error)
124 IMPLEMENT_LOG_FUNCTION(Warning)
125 IMPLEMENT_LOG_FUNCTION(Message)
126 IMPLEMENT_LOG_FUNCTION(Info)
127 IMPLEMENT_LOG_FUNCTION(Status)
128
129 // accepts an additional argument which tells to which frame the output should
130 // be directed
131 void wxLogStatus(wxFrame *pFrame, const char *szFormat, ...)
132 {
133 wxLog *pLog = wxLog::GetActiveTarget();
134 if ( pLog != NULL ) {
135 va_list argptr;
136 va_start(argptr, szFormat);
137 vsprintf(s_szBuf, szFormat, argptr);
138 va_end(argptr);
139
140 wxASSERT( gs_pFrame == NULL ); // should be reset!
141 gs_pFrame = pFrame;
142 wxLog::OnLog(wxLOG_Status, s_szBuf);
143 gs_pFrame = (wxFrame *) NULL;
144 }
145 }
146
147 // same as info, but only if 'verbose' mode is on
148 void wxLogVerbose(const char *szFormat, ...)
149 {
150 wxLog *pLog = wxLog::GetActiveTarget();
151 if ( pLog != NULL && pLog->GetVerbose() ) {
152 va_list argptr;
153 va_start(argptr, szFormat);
154 vsprintf(s_szBuf, szFormat, argptr);
155 va_end(argptr);
156
157 wxLog::OnLog(wxLOG_Info, s_szBuf);
158 }
159 }
160
161 // debug functions
162 #ifdef __WXDEBUG__
163 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
164 void wxLog##level(const char *szFormat, ...) \
165 { \
166 if ( wxLog::GetActiveTarget() != NULL ) { \
167 va_list argptr; \
168 va_start(argptr, szFormat); \
169 vsprintf(s_szBuf, szFormat, argptr); \
170 va_end(argptr); \
171 \
172 wxLog::OnLog(wxLOG_##level, s_szBuf); \
173 } \
174 }
175
176 void wxLogTrace(wxTraceMask mask, const char *szFormat, ...)
177 {
178 wxLog *pLog = wxLog::GetActiveTarget();
179
180 // we check that all of mask bits are set in the current mask, so
181 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
182 // if both bits are set.
183 if ( pLog != NULL && ((pLog->GetTraceMask() & mask) == mask) ) {
184 va_list argptr;
185 va_start(argptr, szFormat);
186 vsprintf(s_szBuf, szFormat, argptr);
187 va_end(argptr);
188
189 wxLog::OnLog(wxLOG_Trace, s_szBuf);
190 }
191 }
192
193 #else // release
194 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
195 #endif
196
197 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
198 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
199
200 // wxLogSysError: one uses the last error code, for other you must give it
201 // explicitly
202
203 // common part of both wxLogSysError
204 void wxLogSysErrorHelper(long lErrCode)
205 {
206 char szErrMsg[LOG_BUFFER_SIZE / 2];
207 sprintf(szErrMsg, _(" (error %ld: %s)"), lErrCode, wxSysErrorMsg(lErrCode));
208 strncat(s_szBuf, szErrMsg, WXSIZEOF(s_szBuf) - strlen(s_szBuf));
209
210 wxLog::OnLog(wxLOG_Error, s_szBuf);
211 }
212
213 void WXDLLEXPORT wxLogSysError(const char *szFormat, ...)
214 {
215 va_list argptr;
216 va_start(argptr, szFormat);
217 vsprintf(s_szBuf, szFormat, argptr);
218 va_end(argptr);
219
220 wxLogSysErrorHelper(wxSysErrorCode());
221 }
222
223 void WXDLLEXPORT wxLogSysError(long lErrCode, const char *szFormat, ...)
224 {
225 va_list argptr;
226 va_start(argptr, szFormat);
227 vsprintf(s_szBuf, szFormat, argptr);
228 va_end(argptr);
229
230 wxLogSysErrorHelper(lErrCode);
231 }
232
233 // ----------------------------------------------------------------------------
234 // wxLog class implementation
235 // ----------------------------------------------------------------------------
236
237 wxLog::wxLog()
238 {
239 m_bHasMessages = FALSE;
240 m_bVerbose = FALSE;
241 m_szTimeFormat = "[%d/%b/%y %H:%M:%S] ";
242 }
243
244 wxLog *wxLog::GetActiveTarget()
245 {
246 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
247 // prevent infinite recursion if someone calls wxLogXXX() from
248 // wxApp::CreateLogTarget()
249 static bool s_bInGetActiveTarget = FALSE;
250 if ( !s_bInGetActiveTarget ) {
251 s_bInGetActiveTarget = TRUE;
252
253 #ifdef wxUSE_NOGUI
254 ms_pLogger = new wxLogStderr;
255 #else
256 // ask the application to create a log target for us
257 if ( wxTheApp != NULL )
258 ms_pLogger = wxTheApp->CreateLogTarget();
259 else
260 ms_pLogger = new wxLogStderr;
261 #endif
262
263 s_bInGetActiveTarget = FALSE;
264
265 // do nothing if it fails - what can we do?
266 }
267 }
268
269 return ms_pLogger;
270 }
271
272 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
273 {
274 if ( ms_pLogger != NULL ) {
275 // flush the old messages before changing because otherwise they might
276 // get lost later if this target is not restored
277 ms_pLogger->Flush();
278 }
279
280 wxLog *pOldLogger = ms_pLogger;
281 ms_pLogger = pLogger;
282
283 return pOldLogger;
284 }
285
286 wxString wxLog::TimeStamp() const
287 {
288 wxString str;
289
290 /* Let's disable TimeStamp and see if anyone complains.
291 * If not, we'll remove it, since it's probably unlikely
292 * to ever be used. -- JACS 22/11/98
293 if ( !IsEmpty(m_szTimeFormat) ) {
294 char szBuf[128];
295 time_t timeNow;
296 struct tm *ptmNow;
297
298 time(&timeNow);
299 ptmNow = localtime(&timeNow);
300
301 strftime(szBuf, WXSIZEOF(szBuf), m_szTimeFormat, ptmNow);
302 str = szBuf;
303 }
304 */
305
306 return str;
307 }
308
309 void wxLog::DoLog(wxLogLevel level, const char *szString)
310 {
311 // prepend a timestamp if not disabled
312 wxString str = TimeStamp();
313
314 switch ( level ) {
315 case wxLOG_FatalError:
316 DoLogString(str << _("Fatal error: ") << szString);
317 DoLogString(_("Program aborted."));
318 Flush();
319 abort();
320 break;
321
322 case wxLOG_Error:
323 DoLogString(str << _("Error: ") << szString);
324 break;
325
326 case wxLOG_Warning:
327 DoLogString(str << _("Warning: ") << szString);
328 break;
329
330 case wxLOG_Info:
331 if ( GetVerbose() )
332 case wxLOG_Message:
333 DoLogString(str + szString);
334 // fall through
335
336 case wxLOG_Status:
337 // nothing to do
338 break;
339
340 case wxLOG_Trace:
341 case wxLOG_Debug:
342 #ifdef __WXDEBUG__
343 // DoLogString(str << (level == wxLOG_Trace ? _("Trace") : _("Debug"))
344 // << ": " << szString);
345 // JACS: we don't really want to prefix with 'Debug'. It's just extra
346 // verbiage.
347 DoLogString(szString);
348 #endif
349
350 break;
351
352 default:
353 wxFAIL_MSG(_("unknown log level in wxLog::DoLog"));
354 }
355 }
356
357 void wxLog::DoLogString(const char *WXUNUSED(szString))
358 {
359 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
360 }
361
362 void wxLog::Flush()
363 {
364 // do nothing
365 }
366
367 // ----------------------------------------------------------------------------
368 // wxLogStderr class implementation
369 // ----------------------------------------------------------------------------
370
371 wxLogStderr::wxLogStderr(FILE *fp)
372 {
373 if ( fp == NULL )
374 m_fp = stderr;
375 else
376 m_fp = fp;
377 }
378
379 void wxLogStderr::DoLogString(const char *szString)
380 {
381 fputs(szString, m_fp);
382 fputc('\n', m_fp);
383 fflush(m_fp);
384 }
385
386 // ----------------------------------------------------------------------------
387 // wxLogStream implementation
388 // ----------------------------------------------------------------------------
389
390 wxLogStream::wxLogStream(ostream *ostr)
391 {
392 if ( ostr == NULL )
393 m_ostr = &cerr;
394 else
395 m_ostr = ostr;
396 }
397
398 void wxLogStream::DoLogString(const char *szString)
399 {
400 (*m_ostr) << szString << endl << flush;
401 }
402
403 #ifndef wxUSE_NOGUI
404 // ----------------------------------------------------------------------------
405 // wxLogTextCtrl implementation
406 // ----------------------------------------------------------------------------
407 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
408 // @@@ TODO: in wxGTK wxTextCtrl doesn't derive from streambuf
409
410 // Also, in DLL mode in wxMSW, can't use it.
411 #if defined(NO_TEXT_WINDOW_STREAM)
412 #else
413 : wxLogStream(new ostream(pTextCtrl))
414 #endif
415 {
416 }
417
418 wxLogTextCtrl::~wxLogTextCtrl()
419 {
420 delete m_ostr;
421 }
422
423 // ----------------------------------------------------------------------------
424 // wxLogGui implementation
425 // ----------------------------------------------------------------------------
426
427 wxLogGui::wxLogGui()
428 {
429 m_bErrors = FALSE;
430 }
431
432 void wxLogGui::Flush()
433 {
434 if ( !m_bHasMessages )
435 return;
436
437 // do it right now to block any new calls to Flush() while we're here
438 m_bHasMessages = FALSE;
439
440 // @@@ ugly...
441
442 // concatenate all strings (but not too many to not overfill the msg box)
443 wxString str;
444 size_t nLines = 0,
445 nMsgCount = m_aMessages.Count();
446
447 // start from the most recent message
448 for ( size_t n = nMsgCount; n > 0; n-- ) {
449 // for Windows strings longer than this value are wrapped (NT 4.0)
450 const size_t nMsgLineWidth = 156;
451
452 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
453
454 if ( nLines > 25 ) // don't put too many lines in message box
455 break;
456
457 str << m_aMessages[n - 1] << "\n";
458 }
459
460 if ( m_bErrors ) {
461 wxMessageBox(str, _("Error"), wxOK | wxICON_EXCLAMATION);
462 }
463 else {
464 wxMessageBox(str, _("Information"), wxOK | wxICON_INFORMATION);
465 }
466
467 // no undisplayed messages whatsoever
468 m_bErrors = FALSE;
469 m_aMessages.Empty();
470 }
471
472 // the default behaviour is to discard all informational messages if there
473 // are any errors/warnings.
474 void wxLogGui::DoLog(wxLogLevel level, const char *szString)
475 {
476 switch ( level ) {
477 case wxLOG_Info:
478 if ( GetVerbose() )
479 case wxLOG_Message:
480 if ( !m_bErrors ) {
481 m_aMessages.Add(szString);
482 m_bHasMessages = TRUE;
483 }
484 break;
485
486 case wxLOG_Status:
487 {
488 // find the top window and set it's status text if it has any
489 wxFrame *pFrame = gs_pFrame;
490 if ( pFrame == NULL ) {
491 wxWindow *pWin = wxTheApp->GetTopWindow();
492 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
493 pFrame = (wxFrame *)pWin;
494 }
495 }
496
497 if ( pFrame != NULL )
498 pFrame->SetStatusText(szString);
499 }
500 break;
501
502 case wxLOG_Trace:
503 case wxLOG_Debug:
504 #ifdef __WXDEBUG__
505 {
506 wxString strTime = TimeStamp();
507
508 #ifdef __WXMSW__
509 // don't prepend debug/trace here: it goes to the debug window
510 // anyhow, but do put a timestamp
511 OutputDebugString(strTime + szString + "\n\r");
512 #else
513 // send them to stderr
514 /*
515 fprintf(stderr, "%s %s: %s\n",
516 strTime.c_str(),
517 level == wxLOG_Trace ? _("Trace") : _("Debug"),
518 szString);
519 */
520 fprintf(stderr, "%s\n",
521 szString);
522 fflush(stderr);
523 #endif
524 }
525 #endif
526 break;
527
528 case wxLOG_FatalError:
529 // show this one immediately
530 wxMessageBox(szString, _("Fatal error"), wxICON_HAND);
531 break;
532
533 case wxLOG_Error:
534 case wxLOG_Warning:
535 // discard earlier informational messages if this is the 1st error
536 if ( !m_bErrors ) {
537 m_aMessages.Empty();
538 m_bHasMessages = TRUE;
539 m_bErrors = TRUE;
540 }
541
542 m_aMessages.Add(szString);
543 break;
544
545 default:
546 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
547 }
548 }
549
550 // ----------------------------------------------------------------------------
551 // wxLogWindow and wxLogFrame implementation
552 // ----------------------------------------------------------------------------
553
554 // log frame class
555 // ---------------
556 class wxLogFrame : public wxFrame
557 {
558 public:
559 // ctor & dtor
560 wxLogFrame(wxFrame *pParent, wxLogWindow *log, const char *szTitle);
561 virtual ~wxLogFrame();
562
563 // menu callbacks
564 void OnClose(wxCommandEvent& event);
565 void OnCloseWindow(wxCloseEvent& event);
566 void OnSave (wxCommandEvent& event);
567 void OnClear(wxCommandEvent& event);
568
569 void OnIdle(wxIdleEvent&);
570
571 // accessors
572 wxTextCtrl *TextCtrl() const { return m_pTextCtrl; }
573
574 private:
575 enum
576 {
577 Menu_Close = 100,
578 Menu_Save,
579 Menu_Clear
580 };
581
582 // instead of closing just hide the window to be able to Show() it later
583 void DoClose() { Show(FALSE); }
584
585 wxTextCtrl *m_pTextCtrl;
586 wxLogWindow *m_log;
587
588 DECLARE_EVENT_TABLE()
589 };
590
591 BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
592 // wxLogWindow menu events
593 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
594 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
595 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
596
597 EVT_CLOSE(wxLogFrame::OnCloseWindow)
598 END_EVENT_TABLE()
599
600 wxLogFrame::wxLogFrame(wxFrame *pParent, wxLogWindow *log, const char *szTitle)
601 : wxFrame(pParent, -1, szTitle)
602 {
603 m_log = log;
604
605 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
606 // a rich edit control instead of a normal one we want in wxMSW
607 m_pTextCtrl = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition,
608 wxDefaultSize,
609 //wxSIMPLE_BORDER |
610 wxTE_MULTILINE |
611 wxHSCROLL |
612 wxTE_READONLY);
613
614 // create menu
615 wxMenuBar *pMenuBar = new wxMenuBar;
616 wxMenu *pMenu = new wxMenu;
617 pMenu->Append(Menu_Save, _("&Save..."), _("Save log contents to file"));
618 pMenu->Append(Menu_Clear, _("C&lear"), _("Clear the log contents"));
619 pMenu->AppendSeparator();
620 pMenu->Append(Menu_Close, _("&Close"), _("Close this window"));
621 pMenuBar->Append(pMenu, _("&Log"));
622 SetMenuBar(pMenuBar);
623
624 // status bar for menu prompts
625 CreateStatusBar();
626
627 m_log->OnFrameCreate(this);
628 }
629
630 void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
631 {
632 DoClose();
633 }
634
635 void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
636 {
637 DoClose();
638 }
639
640 void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
641 {
642 // get the file name
643 // -----------------
644 const char *szFileName = wxSaveFileSelector("log", "txt", "log.txt");
645 if ( szFileName == NULL ) {
646 // cancelled
647 return;
648 }
649
650 // open file
651 // ---------
652 wxFile file;
653 bool bOk = FALSE;
654 if ( wxFile::Exists(szFileName) ) {
655 bool bAppend = FALSE;
656 wxString strMsg;
657 strMsg.Printf(_("Append log to file '%s' "
658 "(choosing [No] will overwrite it)?"), szFileName);
659 switch ( wxMessageBox(strMsg, _("Question"), wxYES_NO | wxCANCEL) ) {
660 case wxYES:
661 bAppend = TRUE;
662 break;
663
664 case wxNO:
665 bAppend = FALSE;
666 break;
667
668 case wxCANCEL:
669 return;
670
671 default:
672 wxFAIL_MSG(_("invalid message box return value"));
673 }
674
675 if ( bAppend ) {
676 bOk = file.Open(szFileName, wxFile::write_append);
677 }
678 else {
679 bOk = file.Create(szFileName, TRUE /* overwrite */);
680 }
681 }
682 else {
683 bOk = file.Create(szFileName);
684 }
685
686 // retrieve text and save it
687 // -------------------------
688 #ifdef __WXGTK__
689 // @@@@ TODO: no GetNumberOfLines and GetLineText in wxGTK yet
690 wxLogError(_("Sorry, this function is not implemented under GTK"));
691 #else
692 int nLines = m_pTextCtrl->GetNumberOfLines();
693 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
694 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) + wxTextFile::GetEOL());
695 }
696 #endif //GTK
697
698 if ( bOk )
699 bOk = file.Close();
700
701 if ( !bOk ) {
702 wxLogError(_("Can't save log contents to file."));
703 return;
704 }
705 }
706
707 void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
708 {
709 m_pTextCtrl->Clear();
710 }
711
712 wxLogFrame::~wxLogFrame()
713 {
714 m_log->OnFrameDelete(this);
715 }
716
717 // wxLogWindow
718 // -----------
719 wxLogWindow::wxLogWindow(wxFrame *pParent,
720 const char *szTitle,
721 bool bShow,
722 bool bDoPass)
723 {
724 m_bPassMessages = bDoPass;
725
726 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
727 m_pOldLog = wxLog::SetActiveTarget(this);
728
729 if ( bShow )
730 m_pLogFrame->Show(TRUE);
731 }
732
733 void wxLogWindow::Show(bool bShow)
734 {
735 m_pLogFrame->Show(bShow);
736 }
737
738 void wxLogWindow::Flush()
739 {
740 if ( m_pOldLog != NULL )
741 m_pOldLog->Flush();
742
743 m_bHasMessages = FALSE;
744 }
745
746 void wxLogWindow::DoLog(wxLogLevel level, const char *szString)
747 {
748 // first let the previous logger show it
749 if ( m_pOldLog != NULL && m_bPassMessages ) {
750 // @@@ why can't we access protected wxLog method from here (we derive
751 // from wxLog)? gcc gives "DoLog is protected in this context", what
752 // does this mean? Anyhow, the cast is harmless and let's us do what
753 // we want.
754 ((wxLogWindow *)m_pOldLog)->DoLog(level, szString);
755 }
756
757 if ( m_pLogFrame ) {
758 switch ( level ) {
759 case wxLOG_Status:
760 // by default, these messages are ignored by wxLog, so process
761 // them ourselves
762 {
763 wxString str = TimeStamp();
764 str << _("Status: ") << szString;
765 DoLogString(str);
766 }
767 break;
768
769 // don't put trace messages in the text window for 2 reasons:
770 // 1) there are too many of them
771 // 2) they may provoke other trace messages thus sending a program
772 // into an infinite loop
773 case wxLOG_Trace:
774 break;
775
776 default:
777 // and this will format it nicely and call our DoLogString()
778 wxLog::DoLog(level, szString);
779 }
780 }
781
782 m_bHasMessages = TRUE;
783 }
784
785 void wxLogWindow::DoLogString(const char *szString)
786 {
787 // put the text into our window
788 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
789
790 // remove selection (WriteText is in fact ReplaceSelection)
791 #ifdef __WXMSW__
792 long nLen = pText->GetLastPosition();
793 pText->SetSelection(nLen, nLen);
794 #endif // Windows
795
796 pText->WriteText(szString);
797 pText->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
798
799 // TODO ensure that the line can be seen
800 }
801
802 wxFrame *wxLogWindow::GetFrame() const
803 {
804 return m_pLogFrame;
805 }
806
807 void wxLogWindow::OnFrameCreate(wxFrame *WXUNUSED(frame))
808 {
809 }
810
811 void wxLogWindow::OnFrameDelete(wxFrame *WXUNUSED(frame))
812 {
813 m_pLogFrame = (wxLogFrame *)NULL;
814 }
815
816 wxLogWindow::~wxLogWindow()
817 {
818 delete m_pOldLog;
819
820 // may be NULL if log frame already auto destroyed itself
821 delete m_pLogFrame;
822 }
823
824 #endif //wxUSE_NOGUI
825
826 // ============================================================================
827 // Global functions/variables
828 // ============================================================================
829
830 // ----------------------------------------------------------------------------
831 // static variables
832 // ----------------------------------------------------------------------------
833 wxLog *wxLog::ms_pLogger = (wxLog *) NULL;
834 bool wxLog::ms_doLog = TRUE;
835 bool wxLog::ms_bAutoCreate = TRUE;
836 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
837
838 // ----------------------------------------------------------------------------
839 // stdout error logging helper
840 // ----------------------------------------------------------------------------
841
842 // helper function: wraps the message and justifies it under given position
843 // (looks more pretty on the terminal). Also adds newline at the end.
844 //
845 // @@ this is now disabled until I find a portable way of determining the
846 // terminal window size (ok, I found it but does anybody really cares?)
847 #ifdef LOG_PRETTY_WRAP
848 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
849 {
850 size_t nMax = 80; // @@@@
851 size_t nStart = strlen(pszPrefix);
852 fputs(pszPrefix, f);
853
854 size_t n;
855 while ( *psz != '\0' ) {
856 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
857 putc(*psz++, f);
858
859 // wrapped?
860 if ( *psz != '\0' ) {
861 /*putc('\n', f);*/
862 for ( n = 0; n < nStart; n++ )
863 putc(' ', f);
864
865 // as we wrapped, squeeze all white space
866 while ( isspace(*psz) )
867 psz++;
868 }
869 }
870
871 putc('\n', f);
872 }
873 #endif //LOG_PRETTY_WRAP
874
875 // ----------------------------------------------------------------------------
876 // error code/error message retrieval functions
877 // ----------------------------------------------------------------------------
878
879 // get error code from syste
880 unsigned long wxSysErrorCode()
881 {
882 #ifdef __WXMSW__
883 #ifdef __WIN32__
884 return ::GetLastError();
885 #else //WIN16
886 // @@@@ what to do on Windows 3.1?
887 return 0;
888 #endif //WIN16/32
889 #else //Unix
890 return errno;
891 #endif //Win/Unix
892 }
893
894 // get error message from system
895 const char *wxSysErrorMsg(unsigned long nErrCode)
896 {
897 if ( nErrCode == 0 )
898 nErrCode = wxSysErrorCode();
899
900 #ifdef __WXMSW__
901 #ifdef __WIN32__
902 static char s_szBuf[LOG_BUFFER_SIZE / 2];
903
904 // get error message from system
905 LPVOID lpMsgBuf;
906 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
907 NULL, nErrCode,
908 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
909 (LPTSTR)&lpMsgBuf,
910 0, NULL);
911
912 // copy it to our buffer and free memory
913 strncpy(s_szBuf, (const char *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
914 s_szBuf[WXSIZEOF(s_szBuf) - 1] = '\0';
915 LocalFree(lpMsgBuf);
916
917 // returned string is capitalized and ended with '\r\n' - bad
918 s_szBuf[0] = (char)wxToLower(s_szBuf[0]);
919 size_t len = strlen(s_szBuf);
920 if ( len > 0 ) {
921 // truncate string
922 if ( s_szBuf[len - 2] == '\r' )
923 s_szBuf[len - 2] = '\0';
924 }
925
926 return s_szBuf;
927 #else //Win16
928 // TODO @@@@
929 return NULL;
930 #endif // Win16/32
931 #else // Unix
932 return strerror(nErrCode);
933 #endif // Win/Unix
934 }
935
936 // ----------------------------------------------------------------------------
937 // debug helper
938 // ----------------------------------------------------------------------------
939
940 #ifdef __WXDEBUG__
941
942 void Trap()
943 {
944 #ifdef __WXMSW__
945 DebugBreak();
946 #elif defined(__WXSTUBS__)
947 // TODO
948 #else // Unix
949 raise(SIGTRAP);
950 #endif // Win/Unix
951 }
952
953 // this function is called when an assert fails
954 void wxOnAssert(const char *szFile, int nLine, const char *szMsg)
955 {
956 // this variable can be set to true to suppress "assert failure" messages
957 static bool s_bNoAsserts = FALSE;
958 static bool s_bInAssert = FALSE;
959
960 if ( s_bInAssert ) {
961 // He-e-e-e-elp!! we're trapped in endless loop
962 Trap();
963
964 return;
965 }
966
967 s_bInAssert = TRUE;
968
969 char szBuf[LOG_BUFFER_SIZE];
970 sprintf(szBuf, _("Assert failed in file %s at line %d"), szFile, nLine);
971 if ( szMsg != NULL ) {
972 strcat(szBuf, ": ");
973 strcat(szBuf, szMsg);
974 }
975 else {
976 strcat(szBuf, ".");
977 }
978
979 if ( !s_bNoAsserts ) {
980 // send it to the normal log destination
981 wxLogDebug(szBuf);
982
983 #ifdef wxUSE_NOGUI
984 Trap();
985 #else
986 strcat(szBuf, _("\nDo you want to stop the program?"
987 "\nYou can also choose [Cancel] to suppress "
988 "further warnings."));
989
990 switch ( wxMessageBox(szBuf, _("Debug"),
991 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
992 case wxYES:
993 Trap();
994 break;
995
996 case wxCANCEL:
997 s_bNoAsserts = TRUE;
998 break;
999
1000 //case wxNO: nothing to do
1001 }
1002 #endif // USE_NOGUI
1003 }
1004
1005 s_bInAssert = FALSE;
1006 }
1007
1008 #endif //WXDEBUG
1009