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