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