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