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