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