timestampt trace/debug messages under Unix too, this is useful for debugging
[wxWidgets.git] / src / generic / logg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: logg.cpp
3 // Purpose: wxLog-derived classes which need GUI support (the rest is in
4 // src/common/log.cpp)
5 // Author: Vadim Zeitlin
6 // Modified by:
7 // Created: 20.09.99 (extracted from src/common/log.cpp)
8 // RCS-ID: $Id$
9 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
12
13 // ============================================================================
14 // declarations
15 // ============================================================================
16
17 // ----------------------------------------------------------------------------
18 // headers
19 // ----------------------------------------------------------------------------
20
21 // no #pragma implementation "log.h" because it's already in src/common/log.cpp
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 #if !wxUSE_GUI
31 #error "This file can't be compiled without GUI!"
32 #endif
33
34 #ifndef WX_PRECOMP
35 #include "wx/app.h"
36 #include "wx/button.h"
37 #include "wx/intl.h"
38 #include "wx/log.h"
39 #include "wx/menu.h"
40 #include "wx/frame.h"
41 #include "wx/filedlg.h"
42 #include "wx/msgdlg.h"
43 #include "wx/textctrl.h"
44 #include "wx/sizer.h"
45 #include "wx/statbmp.h"
46 #include "wx/button.h"
47 #endif // WX_PRECOMP
48
49 #if wxUSE_LOGGUI || wxUSE_LOGWINDOW
50
51 #include "wx/file.h"
52 #include "wx/textfile.h"
53 #include "wx/statline.h"
54
55 #ifdef __WXMSW__
56 // for OutputDebugString()
57 #include "wx/msw/private.h"
58 #endif // Windows
59
60 #if wxUSE_LOG_DIALOG
61 #include "wx/listctrl.h"
62 #include "wx/imaglist.h"
63 #include "wx/image.h"
64 #else // !wxUSE_LOG_DIALOG
65 #include "wx/msgdlg.h"
66 #endif // wxUSE_LOG_DIALOG/!wxUSE_LOG_DIALOG
67
68 // ----------------------------------------------------------------------------
69 // private classes
70 // ----------------------------------------------------------------------------
71
72 #if wxUSE_LOG_DIALOG
73
74 // this function is a wrapper around strftime(3)
75 // allows to exclude the usage of wxDateTime
76 static wxString TimeStamp(const wxChar *format, time_t t)
77 {
78 wxChar buf[4096];
79 if ( !wxStrftime(buf, WXSIZEOF(buf), format, localtime(&t)) )
80 {
81 // buffer is too small?
82 wxFAIL_MSG(_T("strftime() failed"));
83 }
84 return wxString(buf);
85 }
86
87
88 class wxLogDialog : public wxDialog
89 {
90 public:
91 wxLogDialog(wxWindow *parent,
92 const wxArrayString& messages,
93 const wxArrayInt& severity,
94 const wxArrayLong& timess,
95 const wxString& caption,
96 long style);
97 virtual ~wxLogDialog();
98
99 // event handlers
100 void OnOk(wxCommandEvent& event);
101 void OnDetails(wxCommandEvent& event);
102 #if wxUSE_FILE
103 void OnSave(wxCommandEvent& event);
104 #endif // wxUSE_FILE
105 void OnListSelect(wxListEvent& event);
106
107 private:
108 // create controls needed for the details display
109 void CreateDetailsControls();
110
111 // the data for the listctrl
112 wxArrayString m_messages;
113 wxArrayInt m_severity;
114 wxArrayLong m_times;
115
116 // the "toggle" button and its state
117 wxButton *m_btnDetails;
118 bool m_showingDetails;
119
120 // the controls which are not shown initially (but only when details
121 // button is pressed)
122 wxListCtrl *m_listctrl;
123 #if wxUSE_STATLINE
124 wxStaticLine *m_statline;
125 #endif // wxUSE_STATLINE
126 #if wxUSE_FILE
127 wxButton *m_btnSave;
128 #endif // wxUSE_FILE
129
130 // the translated "Details" string
131 static wxString ms_details;
132
133 DECLARE_EVENT_TABLE()
134 };
135
136 BEGIN_EVENT_TABLE(wxLogDialog, wxDialog)
137 EVT_BUTTON(wxID_CANCEL, wxLogDialog::OnOk)
138 EVT_BUTTON(wxID_MORE, wxLogDialog::OnDetails)
139 #if wxUSE_FILE
140 EVT_BUTTON(wxID_SAVE, wxLogDialog::OnSave)
141 #endif // wxUSE_FILE
142 EVT_LIST_ITEM_SELECTED(-1, wxLogDialog::OnListSelect)
143 END_EVENT_TABLE()
144
145 #endif // wxUSE_LOG_DIALOG
146
147 // ----------------------------------------------------------------------------
148 // private functions
149 // ----------------------------------------------------------------------------
150
151 #if wxUSE_FILE && wxUSE_FILEDLG
152
153 // pass an uninitialized file object, the function will ask the user for the
154 // filename and try to open it, returns TRUE on success (file was opened),
155 // FALSE if file couldn't be opened/created and -1 if the file selection
156 // dialog was cancelled
157 static int OpenLogFile(wxFile& file, wxString *filename = NULL);
158
159 #endif // wxUSE_FILE
160
161 // ----------------------------------------------------------------------------
162 // global variables
163 // ----------------------------------------------------------------------------
164
165 // we use a global variable to store the frame pointer for wxLogStatus - bad,
166 // but it's the easiest way
167 static wxFrame *gs_pFrame = NULL; // FIXME MT-unsafe
168
169 // ============================================================================
170 // implementation
171 // ============================================================================
172
173 // ----------------------------------------------------------------------------
174 // global functions
175 // ----------------------------------------------------------------------------
176
177 // accepts an additional argument which tells to which frame the output should
178 // be directed
179 void wxLogStatus(wxFrame *pFrame, const wxChar *szFormat, ...)
180 {
181 wxString msg;
182
183 wxLog *pLog = wxLog::GetActiveTarget();
184 if ( pLog != NULL ) {
185 va_list argptr;
186 va_start(argptr, szFormat);
187 msg.PrintfV(szFormat, argptr);
188 va_end(argptr);
189
190 wxASSERT( gs_pFrame == NULL ); // should be reset!
191 gs_pFrame = pFrame;
192 wxLog::OnLog(wxLOG_Status, msg, time(NULL));
193 gs_pFrame = (wxFrame *) NULL;
194 }
195 }
196
197 // ----------------------------------------------------------------------------
198 // wxLogGui implementation (FIXME MT-unsafe)
199 // ----------------------------------------------------------------------------
200
201 wxLogGui::wxLogGui()
202 {
203 Clear();
204 }
205
206 void wxLogGui::Clear()
207 {
208 m_bErrors =
209 m_bWarnings =
210 m_bHasMessages = FALSE;
211
212 m_aMessages.Empty();
213 m_aSeverity.Empty();
214 m_aTimes.Empty();
215 }
216
217 void wxLogGui::Flush()
218 {
219 if ( !m_bHasMessages )
220 return;
221
222 // do it right now to block any new calls to Flush() while we're here
223 m_bHasMessages = FALSE;
224
225 wxString appName = wxTheApp->GetAppName();
226 if ( !!appName )
227 appName[0u] = wxToupper(appName[0u]);
228
229 long style;
230 wxString titleFormat;
231 if ( m_bErrors ) {
232 titleFormat = _("%s Error");
233 style = wxICON_STOP;
234 }
235 else if ( m_bWarnings ) {
236 titleFormat = _("%s Warning");
237 style = wxICON_EXCLAMATION;
238 }
239 else {
240 titleFormat = _("%s Information");
241 style = wxICON_INFORMATION;
242 }
243
244 wxString title;
245 title.Printf(titleFormat, appName.c_str());
246
247 // this is the best we can do here
248 wxWindow *parent = wxTheApp->GetTopWindow();
249
250 size_t nMsgCount = m_aMessages.Count();
251
252 wxString str;
253 if ( nMsgCount == 1 )
254 {
255 str = m_aMessages[0];
256 }
257 else // more than one message
258 {
259 #if wxUSE_LOG_DIALOG
260
261 wxLogDialog dlg(parent,
262 m_aMessages, m_aSeverity, m_aTimes,
263 title, style);
264
265 // clear the message list before showing the dialog because while it's
266 // shown some new messages may appear
267 Clear();
268
269 (void)dlg.ShowModal();
270 #else // !wxUSE_LOG_DIALOG
271 // concatenate all strings (but not too many to not overfill the msg box)
272 size_t nLines = 0;
273
274 // start from the most recent message
275 for ( size_t n = nMsgCount; n > 0; n-- ) {
276 // for Windows strings longer than this value are wrapped (NT 4.0)
277 const size_t nMsgLineWidth = 156;
278
279 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
280
281 if ( nLines > 25 ) // don't put too many lines in message box
282 break;
283
284 str << m_aMessages[n - 1] << wxT("\n");
285 }
286 #endif // wxUSE_LOG_DIALOG/!wxUSE_LOG_DIALOG
287 }
288
289 // this catches both cases of 1 message with wxUSE_LOG_DIALOG and any
290 // situation without it
291 if ( !!str )
292 {
293 wxMessageBox(str, title, wxOK | style, parent);
294
295 // no undisplayed messages whatsoever
296 Clear();
297 }
298 }
299
300 // log all kinds of messages
301 void wxLogGui::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
302 {
303 switch ( level ) {
304 case wxLOG_Info:
305 if ( GetVerbose() )
306 case wxLOG_Message:
307 {
308 if ( !m_bErrors ) {
309 m_aMessages.Add(szString);
310 m_aSeverity.Add(wxLOG_Message);
311 m_aTimes.Add((long)t);
312 m_bHasMessages = TRUE;
313 }
314 }
315 break;
316
317 case wxLOG_Status:
318 #if wxUSE_STATUSBAR
319 {
320 // find the top window and set it's status text if it has any
321 wxFrame *pFrame = gs_pFrame;
322 if ( pFrame == NULL ) {
323 wxWindow *pWin = wxTheApp->GetTopWindow();
324 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
325 pFrame = (wxFrame *)pWin;
326 }
327 }
328
329 if ( pFrame && pFrame->GetStatusBar() )
330 pFrame->SetStatusText(szString);
331 }
332 #endif // wxUSE_STATUSBAR
333 break;
334
335 case wxLOG_Trace:
336 case wxLOG_Debug:
337 #ifdef __WXDEBUG__
338 {
339 wxString str;
340 TimeStamp(&str);
341 str += szString;
342
343 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
344 // don't prepend debug/trace here: it goes to the
345 // debug window anyhow
346 str += wxT("\r\n");
347 OutputDebugString(str);
348 #else
349 // send them to stderr
350 wxFprintf(stderr, wxT("[%s] %s\n"),
351 level == wxLOG_Trace ? wxT("Trace")
352 : wxT("Debug"),
353 str.c_str());
354 fflush(stderr);
355 #endif
356 }
357 #endif // __WXDEBUG__
358
359 break;
360
361 case wxLOG_FatalError:
362 // show this one immediately
363 wxMessageBox(szString, _("Fatal error"), wxICON_HAND);
364 wxExit();
365 break;
366
367 case wxLOG_Error:
368 if ( !m_bErrors ) {
369 #if !wxUSE_LOG_DIALOG
370 // discard earlier informational messages if this is the 1st
371 // error because they might not make sense any more and showing
372 // them in a message box might be confusing
373 m_aMessages.Empty();
374 m_aSeverity.Empty();
375 m_aTimes.Empty();
376 #endif // wxUSE_LOG_DIALOG
377 m_bErrors = TRUE;
378 }
379 // fall through
380
381 case wxLOG_Warning:
382 if ( !m_bErrors ) {
383 // for the warning we don't discard the info messages
384 m_bWarnings = TRUE;
385 }
386
387 m_aMessages.Add(szString);
388 m_aSeverity.Add((int)level);
389 m_aTimes.Add((long)t);
390 m_bHasMessages = TRUE;
391 break;
392 }
393 }
394
395 // ----------------------------------------------------------------------------
396 // wxLogWindow and wxLogFrame implementation
397 // ----------------------------------------------------------------------------
398
399 // log frame class
400 // ---------------
401 class wxLogFrame : public wxFrame
402 {
403 public:
404 // ctor & dtor
405 wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle);
406 virtual ~wxLogFrame();
407
408 // menu callbacks
409 void OnClose(wxCommandEvent& event);
410 void OnCloseWindow(wxCloseEvent& event);
411 #if wxUSE_FILE
412 void OnSave (wxCommandEvent& event);
413 #endif // wxUSE_FILE
414 void OnClear(wxCommandEvent& event);
415
416 void OnIdle(wxIdleEvent&);
417
418 // accessors
419 wxTextCtrl *TextCtrl() const { return m_pTextCtrl; }
420
421 private:
422 // use standard ids for our commands!
423 enum
424 {
425 Menu_Close = wxID_CLOSE,
426 Menu_Save = wxID_SAVE,
427 Menu_Clear = wxID_CLEAR
428 };
429
430 // common part of OnClose() and OnCloseWindow()
431 void DoClose();
432
433 wxTextCtrl *m_pTextCtrl;
434 wxLogWindow *m_log;
435
436 DECLARE_EVENT_TABLE()
437 };
438
439 BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
440 // wxLogWindow menu events
441 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
442 #if wxUSE_FILE
443 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
444 #endif // wxUSE_FILE
445 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
446
447 EVT_CLOSE(wxLogFrame::OnCloseWindow)
448 END_EVENT_TABLE()
449
450 wxLogFrame::wxLogFrame(wxFrame *pParent, wxLogWindow *log, const wxChar *szTitle)
451 : wxFrame(pParent, -1, szTitle)
452 {
453 m_log = log;
454
455 m_pTextCtrl = new wxTextCtrl(this, -1, wxEmptyString, wxDefaultPosition,
456 wxDefaultSize,
457 wxTE_MULTILINE |
458 wxHSCROLL |
459 wxTE_READONLY);
460
461 #if wxUSE_MENUS
462 // create menu
463 wxMenuBar *pMenuBar = new wxMenuBar;
464 wxMenu *pMenu = new wxMenu;
465 #if wxUSE_FILE
466 pMenu->Append(Menu_Save, _("&Save..."), _("Save log contents to file"));
467 #endif // wxUSE_FILE
468 pMenu->Append(Menu_Clear, _("C&lear"), _("Clear the log contents"));
469 pMenu->AppendSeparator();
470 pMenu->Append(Menu_Close, _("&Close"), _("Close this window"));
471 pMenuBar->Append(pMenu, _("&Log"));
472 SetMenuBar(pMenuBar);
473 #endif // wxUSE_MENUS
474
475 #if wxUSE_STATUSBAR
476 // status bar for menu prompts
477 CreateStatusBar();
478 #endif // wxUSE_STATUSBAR
479
480 m_log->OnFrameCreate(this);
481 }
482
483 void wxLogFrame::DoClose()
484 {
485 if ( m_log->OnFrameClose(this) )
486 {
487 // instead of closing just hide the window to be able to Show() it
488 // later
489 Show(FALSE);
490 }
491 }
492
493 void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
494 {
495 DoClose();
496 }
497
498 void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
499 {
500 DoClose();
501 }
502
503 #if wxUSE_FILE
504 void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
505 {
506 #if wxUSE_FILEDLG
507 wxString filename;
508 wxFile file;
509 int rc = OpenLogFile(file, &filename);
510 if ( rc == -1 )
511 {
512 // cancelled
513 return;
514 }
515
516 bool bOk = rc != 0;
517
518 // retrieve text and save it
519 // -------------------------
520 int nLines = m_pTextCtrl->GetNumberOfLines();
521 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
522 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) +
523 wxTextFile::GetEOL());
524 }
525
526 if ( bOk )
527 bOk = file.Close();
528
529 if ( !bOk ) {
530 wxLogError(_("Can't save log contents to file."));
531 }
532 else {
533 wxLogStatus(this, _("Log saved to the file '%s'."), filename.c_str());
534 }
535 #endif
536 }
537 #endif // wxUSE_FILE
538
539 void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
540 {
541 m_pTextCtrl->Clear();
542 }
543
544 wxLogFrame::~wxLogFrame()
545 {
546 m_log->OnFrameDelete(this);
547 }
548
549 // wxLogWindow
550 // -----------
551
552 wxLogWindow::wxLogWindow(wxFrame *pParent,
553 const wxChar *szTitle,
554 bool bShow,
555 bool bDoPass)
556 {
557 PassMessages(bDoPass);
558
559 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
560
561 if ( bShow )
562 m_pLogFrame->Show(TRUE);
563 }
564
565 void wxLogWindow::Show(bool bShow)
566 {
567 m_pLogFrame->Show(bShow);
568 }
569
570 void wxLogWindow::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
571 {
572 // first let the previous logger show it
573 wxLogPassThrough::DoLog(level, szString, t);
574
575 if ( m_pLogFrame ) {
576 switch ( level ) {
577 case wxLOG_Status:
578 // by default, these messages are ignored by wxLog, so process
579 // them ourselves
580 if ( !wxIsEmpty(szString) )
581 {
582 wxString str;
583 str << _("Status: ") << szString;
584 DoLogString(str, t);
585 }
586 break;
587
588 // don't put trace messages in the text window for 2 reasons:
589 // 1) there are too many of them
590 // 2) they may provoke other trace messages thus sending a program
591 // into an infinite loop
592 case wxLOG_Trace:
593 break;
594
595 default:
596 // and this will format it nicely and call our DoLogString()
597 wxLog::DoLog(level, szString, t);
598 }
599 }
600
601 m_bHasMessages = TRUE;
602 }
603
604 void wxLogWindow::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
605 {
606 // put the text into our window
607 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
608
609 // remove selection (WriteText is in fact ReplaceSelection)
610 #ifdef __WXMSW__
611 long nLen = pText->GetLastPosition();
612 pText->SetSelection(nLen, nLen);
613 #endif // Windows
614
615 wxString msg;
616 TimeStamp(&msg);
617 msg << szString << wxT('\n');
618
619 pText->AppendText(msg);
620
621 // TODO ensure that the line can be seen
622 }
623
624 wxFrame *wxLogWindow::GetFrame() const
625 {
626 return m_pLogFrame;
627 }
628
629 void wxLogWindow::OnFrameCreate(wxFrame * WXUNUSED(frame))
630 {
631 }
632
633 bool wxLogWindow::OnFrameClose(wxFrame * WXUNUSED(frame))
634 {
635 // allow to close
636 return TRUE;
637 }
638
639 void wxLogWindow::OnFrameDelete(wxFrame * WXUNUSED(frame))
640 {
641 m_pLogFrame = (wxLogFrame *)NULL;
642 }
643
644 wxLogWindow::~wxLogWindow()
645 {
646 // may be NULL if log frame already auto destroyed itself
647 delete m_pLogFrame;
648 }
649
650 // ----------------------------------------------------------------------------
651 // wxLogDialog
652 // ----------------------------------------------------------------------------
653
654 #if wxUSE_LOG_DIALOG
655
656 static const size_t MARGIN = 10;
657
658 wxString wxLogDialog::ms_details;
659
660 wxLogDialog::wxLogDialog(wxWindow *parent,
661 const wxArrayString& messages,
662 const wxArrayInt& severity,
663 const wxArrayLong& times,
664 const wxString& caption,
665 long style)
666 : wxDialog(parent, -1, caption)
667 {
668 if ( ms_details.IsEmpty() )
669 {
670 // ensure that we won't loop here if wxGetTranslation()
671 // happens to pop up a Log message while translating this :-)
672 ms_details = wxTRANSLATE("&Details");
673 ms_details = wxGetTranslation(ms_details);
674 }
675
676 size_t count = messages.GetCount();
677 m_messages.Alloc(count);
678 m_severity.Alloc(count);
679 m_times.Alloc(count);
680
681 for ( size_t n = 0; n < count; n++ )
682 {
683 wxString msg = messages[n];
684 do
685 {
686 m_messages.Add(msg.BeforeFirst(_T('\n')));
687 msg = msg.AfterFirst(_T('\n'));
688
689 m_severity.Add(severity[n]);
690 m_times.Add(times[n]);
691 }
692 while ( !!msg );
693 }
694
695 m_showingDetails = FALSE; // not initially
696 m_listctrl = (wxListCtrl *)NULL;
697
698 #if wxUSE_STATLINE
699 m_statline = (wxStaticLine *)NULL;
700 #endif // wxUSE_STATLINE
701
702 #if wxUSE_FILE
703 m_btnSave = (wxButton *)NULL;
704 #endif // wxUSE_FILE
705
706 // create the controls which are always shown and layout them: we use
707 // sizers even though our window is not resizeable to calculate the size of
708 // the dialog properly
709 wxBoxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
710 wxBoxSizer *sizerButtons = new wxBoxSizer(wxVERTICAL);
711 wxBoxSizer *sizerAll = new wxBoxSizer(wxHORIZONTAL);
712
713 // this "Ok" button has wxID_CANCEL id - not very logical, but this allows
714 // to close the log dialog with <Esc> which wouldn't work otherwise (as it
715 // translates into click on cancel button)
716 wxButton *btnOk = new wxButton(this, wxID_CANCEL, _("OK"));
717 sizerButtons->Add(btnOk, 0, wxCENTRE|wxBOTTOM, MARGIN/2);
718 m_btnDetails = new wxButton(this, wxID_MORE, ms_details + _T(" >>"));
719 sizerButtons->Add(m_btnDetails, 0, wxCENTRE|wxTOP, MARGIN/2 - 1);
720
721 #ifndef __WIN16__
722 wxIcon icon = wxTheApp->GetStdIcon((int)(style & wxICON_MASK));
723 sizerAll->Add(new wxStaticBitmap(this, -1, icon), 0, wxCENTRE);
724 #endif // !Win16
725
726 const wxString& message = messages.Last();
727 sizerAll->Add(CreateTextSizer(message), 0, wxCENTRE|wxLEFT|wxRIGHT, MARGIN);
728 sizerAll->Add(sizerButtons, 0, wxALIGN_RIGHT|wxLEFT, MARGIN);
729
730 sizerTop->Add(sizerAll, 0, wxCENTRE|wxALL, MARGIN);
731
732 SetAutoLayout(TRUE);
733 SetSizer(sizerTop);
734
735 sizerTop->SetSizeHints(this);
736 sizerTop->Fit(this);
737
738 btnOk->SetFocus();
739
740 // this can't happen any more as we don't use this dialog in this case
741 #if 0
742 if ( count == 1 )
743 {
744 // no details... it's easier to disable a button than to change the
745 // dialog layout depending on whether we have details or not
746 m_btnDetails->Disable();
747 }
748 #endif // 0
749
750 Centre();
751 }
752
753 void wxLogDialog::CreateDetailsControls()
754 {
755 // create the save button and separator line if possible
756 #if wxUSE_FILE
757 m_btnSave = new wxButton(this, wxID_SAVE, _("&Save..."));
758 #endif // wxUSE_FILE
759
760 #if wxUSE_STATLINE
761 m_statline = new wxStaticLine(this, -1);
762 #endif // wxUSE_STATLINE
763
764 // create the list ctrl now
765 m_listctrl = new wxListCtrl(this, -1,
766 wxDefaultPosition, wxDefaultSize,
767 wxSUNKEN_BORDER |
768 wxLC_REPORT |
769 wxLC_NO_HEADER |
770 wxLC_SINGLE_SEL);
771
772 // no need to translate these strings as they're not shown to the
773 // user anyhow (we use wxLC_NO_HEADER style)
774 m_listctrl->InsertColumn(0, _T("Message"));
775 m_listctrl->InsertColumn(1, _T("Time"));
776
777 // prepare the imagelist
778 static const int ICON_SIZE = 16;
779 wxImageList *imageList = new wxImageList(ICON_SIZE, ICON_SIZE);
780
781 // order should be the same as in the switch below!
782 static const int icons[] =
783 {
784 wxICON_ERROR,
785 wxICON_EXCLAMATION,
786 wxICON_INFORMATION
787 };
788
789 bool loadedIcons = TRUE;
790
791 #ifndef __WIN16__
792 for ( size_t icon = 0; icon < WXSIZEOF(icons); icon++ )
793 {
794 wxBitmap bmp = wxTheApp->GetStdIcon(icons[icon]);
795
796 // This may very well fail if there are insufficient
797 // colours available. Degrade gracefully.
798
799 if (!bmp.Ok())
800 loadedIcons = FALSE;
801 else
802 imageList->Add(wxImage(bmp).
803 Rescale(ICON_SIZE, ICON_SIZE).
804 ConvertToBitmap());
805 }
806
807 m_listctrl->SetImageList(imageList, wxIMAGE_LIST_SMALL);
808 #endif // !Win16
809
810 // and fill it
811 wxString fmt = wxLog::GetTimestamp();
812 if ( !fmt )
813 {
814 // default format
815 fmt = _T("%c");
816 }
817
818 size_t count = m_messages.GetCount();
819 for ( size_t n = 0; n < count; n++ )
820 {
821 int image = -1;
822 #ifndef __WIN16__
823 switch ( m_severity[n] )
824 {
825 case wxLOG_Error:
826 image = 0;
827 break;
828
829 case wxLOG_Warning:
830 image = 1;
831 break;
832
833 default:
834 image = 2;
835 }
836 #endif // !Win16
837
838 if (!loadedIcons)
839 image = -1;
840
841 if (image > -1)
842 m_listctrl->InsertItem(n, m_messages[n], image);
843 else
844 m_listctrl->InsertItem(n, m_messages[n]);
845
846 m_listctrl->SetItem(n, 1,
847 TimeStamp(fmt, (time_t)m_times[n]));
848 }
849
850 // let the columns size themselves
851 m_listctrl->SetColumnWidth(0, wxLIST_AUTOSIZE);
852 m_listctrl->SetColumnWidth(1, wxLIST_AUTOSIZE);
853
854 // get the approx height of the listctrl
855 wxFont font = GetFont();
856 if ( !font.Ok() )
857 font = *wxSWISS_FONT;
858
859 int y;
860 GetTextExtent(_T("H"), (int*)NULL, &y, (int*)NULL, (int*)NULL, &font);
861 int height = wxMax(y*(count + 3), 100);
862 m_listctrl->SetSize(-1, height);
863 }
864
865 void wxLogDialog::OnListSelect(wxListEvent& event)
866 {
867 // we can't just disable the control because this looks ugly under Windows
868 // (wrong bg colour, no scrolling...), but we still want to disable
869 // selecting items - it makes no sense here
870 m_listctrl->SetItemState(event.GetIndex(), 0, wxLIST_STATE_SELECTED);
871 }
872
873 void wxLogDialog::OnOk(wxCommandEvent& WXUNUSED(event))
874 {
875 EndModal(wxID_OK);
876 }
877
878 #if wxUSE_FILE
879
880 void wxLogDialog::OnSave(wxCommandEvent& WXUNUSED(event))
881 {
882 #if wxUSE_FILEDLG
883 wxFile file;
884 int rc = OpenLogFile(file);
885 if ( rc == -1 )
886 {
887 // cancelled
888 return;
889 }
890
891 bool ok = rc != 0;
892
893 wxString fmt = wxLog::GetTimestamp();
894 if ( !fmt )
895 {
896 // default format
897 fmt = _T("%c");
898 }
899
900 size_t count = m_messages.GetCount();
901 for ( size_t n = 0; ok && (n < count); n++ )
902 {
903 wxString line;
904 line << TimeStamp(fmt, (time_t)m_times[n])
905 << _T(": ")
906 << m_messages[n]
907 << wxTextFile::GetEOL();
908
909 ok = file.Write(line);
910 }
911
912 if ( ok )
913 ok = file.Close();
914
915 if ( !ok )
916 wxLogError(_("Can't save log contents to file."));
917 #endif
918 }
919
920 #endif // wxUSE_FILE
921
922 void wxLogDialog::OnDetails(wxCommandEvent& WXUNUSED(event))
923 {
924 wxSizer *sizer = GetSizer();
925
926 if ( m_showingDetails )
927 {
928 m_btnDetails->SetLabel(ms_details + _T(">>"));
929
930 sizer->Remove(m_listctrl);
931
932 #if wxUSE_STATLINE
933 sizer->Remove(m_statline);
934 #endif // wxUSE_STATLINE
935
936 #if wxUSE_FILE
937 sizer->Remove(m_btnSave);
938 #endif // wxUSE_FILE
939 }
940 else // show details now
941 {
942 m_btnDetails->SetLabel(wxString(_T("<< ")) + ms_details);
943
944 if ( !m_listctrl )
945 {
946 CreateDetailsControls();
947 }
948
949 #if wxUSE_STATLINE
950 sizer->Add(m_statline, 0, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
951 #endif // wxUSE_STATLINE
952
953 sizer->Add(m_listctrl, 1, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
954
955 #if wxUSE_FILE
956 sizer->Add(m_btnSave, 0, wxALIGN_RIGHT | (wxALL & ~wxTOP), MARGIN);
957 #endif // wxUSE_FILE
958 }
959
960 m_showingDetails = !m_showingDetails;
961
962 // in any case, our size changed - update
963 sizer->SetSizeHints(this);
964 sizer->Fit(this);
965
966 #ifdef __WXGTK__
967 // VS: this is neccessary in order to force frame redraw under
968 // WindowMaker or fvwm2 (and probably other broken WMs).
969 // Otherwise, detailed list wouldn't be displayed.
970 Show(TRUE);
971 #endif // wxGTK
972 }
973
974 wxLogDialog::~wxLogDialog()
975 {
976 if ( m_listctrl )
977 {
978 delete m_listctrl->GetImageList(wxIMAGE_LIST_SMALL);
979 }
980 }
981
982 #endif // wxUSE_LOG_DIALOG
983
984 #if wxUSE_FILE && wxUSE_FILEDLG
985
986 // pass an uninitialized file object, the function will ask the user for the
987 // filename and try to open it, returns TRUE on success (file was opened),
988 // FALSE if file couldn't be opened/created and -1 if the file selection
989 // dialog was cancelled
990 static int OpenLogFile(wxFile& file, wxString *pFilename)
991 {
992 // get the file name
993 // -----------------
994 wxString filename = wxSaveFileSelector(wxT("log"), wxT("txt"), wxT("log.txt"));
995 if ( !filename ) {
996 // cancelled
997 return -1;
998 }
999
1000 // open file
1001 // ---------
1002 bool bOk = FALSE;
1003 if ( wxFile::Exists(filename) ) {
1004 bool bAppend = FALSE;
1005 wxString strMsg;
1006 strMsg.Printf(_("Append log to file '%s' (choosing [No] will overwrite it)?"),
1007 filename.c_str());
1008 switch ( wxMessageBox(strMsg, _("Question"),
1009 wxICON_QUESTION | wxYES_NO | wxCANCEL) ) {
1010 case wxYES:
1011 bAppend = TRUE;
1012 break;
1013
1014 case wxNO:
1015 bAppend = FALSE;
1016 break;
1017
1018 case wxCANCEL:
1019 return -1;
1020
1021 default:
1022 wxFAIL_MSG(_("invalid message box return value"));
1023 }
1024
1025 if ( bAppend ) {
1026 bOk = file.Open(filename, wxFile::write_append);
1027 }
1028 else {
1029 bOk = file.Create(filename, TRUE /* overwrite */);
1030 }
1031 }
1032 else {
1033 bOk = file.Create(filename);
1034 }
1035
1036 if ( pFilename )
1037 *pFilename = filename;
1038
1039 return bOk;
1040 }
1041
1042 #endif // wxUSE_FILE
1043
1044 #endif // !(wxUSE_LOGGUI || wxUSE_LOGWINDOW)
1045
1046 #if wxUSE_TEXTCTRL
1047
1048 // ----------------------------------------------------------------------------
1049 // wxLogTextCtrl implementation
1050 // ----------------------------------------------------------------------------
1051
1052 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
1053 {
1054 m_pTextCtrl = pTextCtrl;
1055 }
1056
1057 void wxLogTextCtrl::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
1058 {
1059 wxString msg;
1060 TimeStamp(&msg);
1061
1062 #ifdef __WXMAC__
1063 // VZ: this is a bug in wxMac, it *must* accept '\n' as new line, the
1064 // translation must be done in wxTextCtrl, not here! (FIXME)
1065 msg << szString << wxT('\r');
1066 #else
1067 msg << szString << wxT('\n');
1068 #endif
1069
1070 m_pTextCtrl->AppendText(msg);
1071 }
1072
1073 #endif // wxUSE_TEXTCTRL
1074