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