Don't call base class version unnecessarily in wxLogWindow::DoLogTextAtLevel().
[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 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
23
24 #ifdef __BORLANDC__
25 #pragma hdrstop
26 #endif
27
28 #ifndef WX_PRECOMP
29 #include "wx/app.h"
30 #include "wx/button.h"
31 #include "wx/intl.h"
32 #include "wx/log.h"
33 #include "wx/menu.h"
34 #include "wx/frame.h"
35 #include "wx/filedlg.h"
36 #include "wx/msgdlg.h"
37 #include "wx/textctrl.h"
38 #include "wx/sizer.h"
39 #include "wx/statbmp.h"
40 #include "wx/settings.h"
41 #include "wx/wxcrtvararg.h"
42 #endif // WX_PRECOMP
43
44 #if wxUSE_LOGGUI || wxUSE_LOGWINDOW
45
46 #include "wx/file.h"
47 #include "wx/clipbrd.h"
48 #include "wx/dataobj.h"
49 #include "wx/textfile.h"
50 #include "wx/statline.h"
51 #include "wx/artprov.h"
52 #include "wx/collpane.h"
53 #include "wx/arrstr.h"
54 #include "wx/msgout.h"
55
56 #ifdef __WXMSW__
57 // for OutputDebugString()
58 #include "wx/msw/private.h"
59 #endif // Windows
60
61
62 #ifdef __WXPM__
63 #include <time.h>
64 #endif
65
66 #if wxUSE_LOG_DIALOG
67 #include "wx/listctrl.h"
68 #include "wx/imaglist.h"
69 #include "wx/image.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 wxT(" >>")
80
81 #define CAN_SAVE_FILES (wxUSE_FILE && wxUSE_FILEDLG)
82
83 // ----------------------------------------------------------------------------
84 // private classes
85 // ----------------------------------------------------------------------------
86
87 #if wxUSE_LOG_DIALOG
88
89 // this function is a wrapper around strftime(3)
90 // allows to exclude the usage of wxDateTime
91 static wxString TimeStamp(const wxString& format, time_t t)
92 {
93 #if wxUSE_DATETIME
94 wxChar buf[4096];
95 struct tm tm;
96 if ( !wxStrftime(buf, WXSIZEOF(buf), format, wxLocaltime_r(&t, &tm)) )
97 {
98 // buffer is too small?
99 wxFAIL_MSG(wxT("strftime() failed"));
100 }
101 return wxString(buf);
102 #else // !wxUSE_DATETIME
103 return wxEmptyString;
104 #endif // wxUSE_DATETIME/!wxUSE_DATETIME
105 }
106
107
108 class wxLogDialog : public wxDialog
109 {
110 public:
111 wxLogDialog(wxWindow *parent,
112 const wxArrayString& messages,
113 const wxArrayInt& severity,
114 const wxArrayLong& timess,
115 const wxString& caption,
116 long style);
117 virtual ~wxLogDialog();
118
119 // event handlers
120 void OnOk(wxCommandEvent& event);
121 #if wxUSE_CLIPBOARD
122 void OnCopy(wxCommandEvent& event);
123 #endif // wxUSE_CLIPBOARD
124 #if CAN_SAVE_FILES
125 void OnSave(wxCommandEvent& event);
126 #endif // CAN_SAVE_FILES
127 void OnListItemActivated(wxListEvent& event);
128
129 private:
130 // create controls needed for the details display
131 void CreateDetailsControls(wxWindow *);
132
133 // if necessary truncates the given string and adds an ellipsis
134 wxString EllipsizeString(const wxString &text)
135 {
136 if (ms_maxLength > 0 &&
137 text.length() > ms_maxLength)
138 {
139 wxString ret(text);
140 ret.Truncate(ms_maxLength);
141 ret << "...";
142 return ret;
143 }
144
145 return text;
146 }
147
148 #if CAN_SAVE_FILES || wxUSE_CLIPBOARD
149 // return the contents of the dialog as a multiline string
150 wxString GetLogMessages() const;
151 #endif // CAN_SAVE_FILES || wxUSE_CLIPBOARD
152
153
154 // the data for the listctrl
155 wxArrayString m_messages;
156 wxArrayInt m_severity;
157 wxArrayLong m_times;
158
159 // the controls which are not shown initially (but only when details
160 // button is pressed)
161 wxListCtrl *m_listctrl;
162
163 // the translated "Details" string
164 static wxString ms_details;
165
166 // the maximum length of the log message
167 static size_t ms_maxLength;
168
169 DECLARE_EVENT_TABLE()
170 wxDECLARE_NO_COPY_CLASS(wxLogDialog);
171 };
172
173 BEGIN_EVENT_TABLE(wxLogDialog, wxDialog)
174 EVT_BUTTON(wxID_OK, wxLogDialog::OnOk)
175 #if wxUSE_CLIPBOARD
176 EVT_BUTTON(wxID_COPY, wxLogDialog::OnCopy)
177 #endif // wxUSE_CLIPBOARD
178 #if CAN_SAVE_FILES
179 EVT_BUTTON(wxID_SAVE, wxLogDialog::OnSave)
180 #endif // CAN_SAVE_FILES
181 EVT_LIST_ITEM_ACTIVATED(wxID_ANY, wxLogDialog::OnListItemActivated)
182 END_EVENT_TABLE()
183
184 #endif // wxUSE_LOG_DIALOG
185
186 // ----------------------------------------------------------------------------
187 // private functions
188 // ----------------------------------------------------------------------------
189
190 #if CAN_SAVE_FILES
191
192 // pass an uninitialized file object, the function will ask the user for the
193 // filename and try to open it, returns true on success (file was opened),
194 // false if file couldn't be opened/created and -1 if the file selection
195 // dialog was cancelled
196 static int OpenLogFile(wxFile& file, wxString *filename = NULL, wxWindow *parent = NULL);
197
198 #endif // CAN_SAVE_FILES
199
200 // ============================================================================
201 // implementation
202 // ============================================================================
203
204 // ----------------------------------------------------------------------------
205 // wxLogGui implementation (FIXME MT-unsafe)
206 // ----------------------------------------------------------------------------
207
208 #if wxUSE_LOGGUI
209
210 wxLogGui::wxLogGui()
211 {
212 Clear();
213 }
214
215 void wxLogGui::Clear()
216 {
217 m_bErrors =
218 m_bWarnings =
219 m_bHasMessages = false;
220
221 m_aMessages.Empty();
222 m_aSeverity.Empty();
223 m_aTimes.Empty();
224 }
225
226 int wxLogGui::GetSeverityIcon() const
227 {
228 return m_bErrors ? wxICON_STOP
229 : m_bWarnings ? wxICON_EXCLAMATION
230 : wxICON_INFORMATION;
231 }
232
233 wxString wxLogGui::GetTitle() const
234 {
235 wxString titleFormat;
236 switch ( GetSeverityIcon() )
237 {
238 case wxICON_STOP:
239 titleFormat = _("%s Error");
240 break;
241
242 case wxICON_EXCLAMATION:
243 titleFormat = _("%s Warning");
244 break;
245
246 default:
247 wxFAIL_MSG( "unexpected icon severity" );
248 // fall through
249
250 case wxICON_INFORMATION:
251 titleFormat = _("%s Information");
252 }
253
254 return wxString::Format(titleFormat, wxTheApp->GetAppDisplayName());
255 }
256
257 void
258 wxLogGui::DoShowSingleLogMessage(const wxString& message,
259 const wxString& title,
260 int style)
261 {
262 wxMessageBox(message, title, wxOK | style);
263 }
264
265 void
266 wxLogGui::DoShowMultipleLogMessages(const wxArrayString& messages,
267 const wxArrayInt& severities,
268 const wxArrayLong& times,
269 const wxString& title,
270 int style)
271 {
272 #if wxUSE_LOG_DIALOG
273 wxLogDialog dlg(NULL,
274 messages, severities, times,
275 title, style);
276
277 // clear the message list before showing the dialog because while it's
278 // shown some new messages may appear
279 Clear();
280
281 (void)dlg.ShowModal();
282 #else // !wxUSE_LOG_DIALOG
283 // start from the most recent message
284 wxString message;
285 const size_t nMsgCount = messages.size();
286 message.reserve(nMsgCount*100);
287 for ( size_t n = nMsgCount; n > 0; n-- ) {
288 message << m_aMessages[n - 1] << wxT("\n");
289 }
290
291 DoShowSingleLogMessage(message, title, style);
292 #endif // wxUSE_LOG_DIALOG/!wxUSE_LOG_DIALOG
293 }
294
295 void wxLogGui::Flush()
296 {
297 wxLog::Flush();
298
299 if ( !m_bHasMessages )
300 return;
301
302 // do it right now to block any new calls to Flush() while we're here
303 m_bHasMessages = false;
304
305 // note that this must be done before examining m_aMessages as it may log
306 // yet another message
307 const unsigned repeatCount = LogLastRepeatIfNeeded();
308
309 const size_t nMsgCount = m_aMessages.size();
310
311 if ( repeatCount > 0 )
312 {
313 m_aMessages[nMsgCount - 1] << " (" << m_aMessages[nMsgCount - 2] << ")";
314 }
315
316 const wxString title = GetTitle();
317 const int style = GetSeverityIcon();
318
319 // avoid showing other log dialogs until we're done with the dialog we're
320 // showing right now: nested modal dialogs make for really bad UI!
321 Suspend();
322
323 if ( nMsgCount == 1 )
324 {
325 // make a copy before calling Clear()
326 const wxString message(m_aMessages[0]);
327 Clear();
328
329 DoShowSingleLogMessage(message, title, style);
330 }
331 else // more than one message
332 {
333 wxArrayString messages;
334 wxArrayInt severities;
335 wxArrayLong times;
336
337 messages.swap(m_aMessages);
338 severities.swap(m_aSeverity);
339 times.swap(m_aTimes);
340
341 Clear();
342
343 DoShowMultipleLogMessages(messages, severities, times, title, style);
344 }
345
346 // allow flushing the logs again
347 Resume();
348 }
349
350 // log all kinds of messages
351 void wxLogGui::DoLogRecord(wxLogLevel level,
352 const wxString& msg,
353 const wxLogRecordInfo& info)
354 {
355 switch ( level )
356 {
357 case wxLOG_Info:
358 if ( GetVerbose() )
359 case wxLOG_Message:
360 {
361 m_aMessages.Add(msg);
362 m_aSeverity.Add(wxLOG_Message);
363 m_aTimes.Add((long)info.timestamp);
364 m_bHasMessages = true;
365 }
366 break;
367
368 case wxLOG_Status:
369 #if wxUSE_STATUSBAR
370 {
371 wxFrame *pFrame = NULL;
372
373 // check if the frame was passed to us explicitly
374 wxUIntPtr ptr = 0;
375 if ( info.GetNumValue(wxLOG_KEY_FRAME, &ptr) )
376 {
377 pFrame = static_cast<wxFrame *>(wxUIntToPtr(ptr));
378 }
379
380 // find the top window and set it's status text if it has any
381 if ( pFrame == NULL ) {
382 wxWindow *pWin = wxTheApp->GetTopWindow();
383 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
384 pFrame = (wxFrame *)pWin;
385 }
386 }
387
388 if ( pFrame && pFrame->GetStatusBar() )
389 pFrame->SetStatusText(msg);
390 }
391 #endif // wxUSE_STATUSBAR
392 break;
393
394 case wxLOG_Error:
395 if ( !m_bErrors ) {
396 #if !wxUSE_LOG_DIALOG
397 // discard earlier informational messages if this is the 1st
398 // error because they might not make sense any more and showing
399 // them in a message box might be confusing
400 m_aMessages.Empty();
401 m_aSeverity.Empty();
402 m_aTimes.Empty();
403 #endif // wxUSE_LOG_DIALOG
404 m_bErrors = true;
405 }
406 // fall through
407
408 case wxLOG_Warning:
409 if ( !m_bErrors ) {
410 // for the warning we don't discard the info messages
411 m_bWarnings = true;
412 }
413
414 m_aMessages.Add(msg);
415 m_aSeverity.Add((int)level);
416 m_aTimes.Add((long)info.timestamp);
417 m_bHasMessages = true;
418 break;
419
420 default:
421 // let the base class deal with debug/trace messages as well as any
422 // custom levels
423 wxLog::DoLogRecord(level, msg, info);
424 }
425 }
426
427 #endif // wxUSE_LOGGUI
428
429 // ----------------------------------------------------------------------------
430 // wxLogWindow and wxLogFrame implementation
431 // ----------------------------------------------------------------------------
432
433 #if wxUSE_LOGWINDOW
434
435 // log frame class
436 // ---------------
437 class wxLogFrame : public wxFrame
438 {
439 public:
440 // ctor & dtor
441 wxLogFrame(wxWindow *pParent, wxLogWindow *log, const wxString& szTitle);
442 virtual ~wxLogFrame();
443
444 // menu callbacks
445 void OnClose(wxCommandEvent& event);
446 void OnCloseWindow(wxCloseEvent& event);
447 #if CAN_SAVE_FILES
448 void OnSave(wxCommandEvent& event);
449 #endif // CAN_SAVE_FILES
450 void OnClear(wxCommandEvent& event);
451
452 // do show the message in the text control
453 void ShowLogMessage(const wxString& message)
454 {
455 m_pTextCtrl->AppendText(message + wxS('\n'));
456 }
457
458 private:
459 // use standard ids for our commands!
460 enum
461 {
462 Menu_Close = wxID_CLOSE,
463 Menu_Save = wxID_SAVE,
464 Menu_Clear = wxID_CLEAR
465 };
466
467 // common part of OnClose() and OnCloseWindow()
468 void DoClose();
469
470 wxTextCtrl *m_pTextCtrl;
471 wxLogWindow *m_log;
472
473 DECLARE_EVENT_TABLE()
474 wxDECLARE_NO_COPY_CLASS(wxLogFrame);
475 };
476
477 BEGIN_EVENT_TABLE(wxLogFrame, wxFrame)
478 // wxLogWindow menu events
479 EVT_MENU(Menu_Close, wxLogFrame::OnClose)
480 #if CAN_SAVE_FILES
481 EVT_MENU(Menu_Save, wxLogFrame::OnSave)
482 #endif // CAN_SAVE_FILES
483 EVT_MENU(Menu_Clear, wxLogFrame::OnClear)
484
485 EVT_CLOSE(wxLogFrame::OnCloseWindow)
486 END_EVENT_TABLE()
487
488 wxLogFrame::wxLogFrame(wxWindow *pParent, wxLogWindow *log, const wxString& szTitle)
489 : wxFrame(pParent, wxID_ANY, szTitle)
490 {
491 m_log = log;
492
493 m_pTextCtrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition,
494 wxDefaultSize,
495 wxTE_MULTILINE |
496 wxHSCROLL |
497 // needed for Win32 to avoid 65Kb limit but it doesn't work well
498 // when using RichEdit 2.0 which we always do in the Unicode build
499 #if !wxUSE_UNICODE
500 wxTE_RICH |
501 #endif // !wxUSE_UNICODE
502 wxTE_READONLY);
503
504 #if wxUSE_MENUS
505 // create menu
506 wxMenuBar *pMenuBar = new wxMenuBar;
507 wxMenu *pMenu = new wxMenu;
508 #if CAN_SAVE_FILES
509 pMenu->Append(Menu_Save, _("&Save..."), _("Save log contents to file"));
510 #endif // CAN_SAVE_FILES
511 pMenu->Append(Menu_Clear, _("C&lear"), _("Clear the log contents"));
512 pMenu->AppendSeparator();
513 pMenu->Append(Menu_Close, _("&Close"), _("Close this window"));
514 pMenuBar->Append(pMenu, _("&Log"));
515 SetMenuBar(pMenuBar);
516 #endif // wxUSE_MENUS
517
518 #if wxUSE_STATUSBAR
519 // status bar for menu prompts
520 CreateStatusBar();
521 #endif // wxUSE_STATUSBAR
522
523 m_log->OnFrameCreate(this);
524 }
525
526 void wxLogFrame::DoClose()
527 {
528 if ( m_log->OnFrameClose(this) )
529 {
530 // instead of closing just hide the window to be able to Show() it
531 // later
532 Show(false);
533 }
534 }
535
536 void wxLogFrame::OnClose(wxCommandEvent& WXUNUSED(event))
537 {
538 DoClose();
539 }
540
541 void wxLogFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
542 {
543 DoClose();
544 }
545
546 #if CAN_SAVE_FILES
547 void wxLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
548 {
549 wxString filename;
550 wxFile file;
551 int rc = OpenLogFile(file, &filename, this);
552 if ( rc == -1 )
553 {
554 // cancelled
555 return;
556 }
557
558 bool bOk = rc != 0;
559
560 // retrieve text and save it
561 // -------------------------
562 int nLines = m_pTextCtrl->GetNumberOfLines();
563 for ( int nLine = 0; bOk && nLine < nLines; nLine++ ) {
564 bOk = file.Write(m_pTextCtrl->GetLineText(nLine) +
565 wxTextFile::GetEOL());
566 }
567
568 if ( bOk )
569 bOk = file.Close();
570
571 if ( !bOk ) {
572 wxLogError(_("Can't save log contents to file."));
573 }
574 else {
575 wxLogStatus((wxFrame*)this, _("Log saved to the file '%s'."), filename.c_str());
576 }
577 }
578 #endif // CAN_SAVE_FILES
579
580 void wxLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
581 {
582 m_pTextCtrl->Clear();
583 }
584
585 wxLogFrame::~wxLogFrame()
586 {
587 m_log->OnFrameDelete(this);
588 }
589
590 // wxLogWindow
591 // -----------
592
593 wxLogWindow::wxLogWindow(wxWindow *pParent,
594 const wxString& szTitle,
595 bool bShow,
596 bool bDoPass)
597 {
598 PassMessages(bDoPass);
599
600 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
601
602 if ( bShow )
603 m_pLogFrame->Show();
604 }
605
606 void wxLogWindow::Show(bool bShow)
607 {
608 m_pLogFrame->Show(bShow);
609 }
610
611 void wxLogWindow::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
612 {
613 if ( !m_pLogFrame )
614 return;
615
616 // don't put trace messages in the text window for 2 reasons:
617 // 1) there are too many of them
618 // 2) they may provoke other trace messages (e.g. wxMSW code uses
619 // wxLogTrace to log Windows messages and adding text to the control
620 // sends more of them) thus sending a program into an infinite loop
621 if ( level == wxLOG_Trace )
622 return;
623
624 m_pLogFrame->ShowLogMessage(msg);
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 = 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 #endif // wxUSE_LOGWINDOW
654
655 // ----------------------------------------------------------------------------
656 // wxLogDialog
657 // ----------------------------------------------------------------------------
658
659 #if wxUSE_LOG_DIALOG
660
661 wxString wxLogDialog::ms_details;
662 size_t wxLogDialog::ms_maxLength = 0;
663
664 wxLogDialog::wxLogDialog(wxWindow *parent,
665 const wxArrayString& messages,
666 const wxArrayInt& severity,
667 const wxArrayLong& times,
668 const wxString& caption,
669 long style)
670 : wxDialog(parent, wxID_ANY, caption,
671 wxDefaultPosition, wxDefaultSize,
672 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
673 {
674 // init the static variables:
675
676 if ( ms_details.empty() )
677 {
678 // ensure that we won't loop here if wxGetTranslation()
679 // happens to pop up a Log message while translating this :-)
680 ms_details = wxTRANSLATE("&Details");
681 ms_details = wxGetTranslation(ms_details);
682 #ifdef __SMARTPHONE__
683 ms_details = wxStripMenuCodes(ms_details);
684 #endif
685 }
686
687 if ( ms_maxLength == 0 )
688 {
689 ms_maxLength = (2 * wxGetDisplaySize().x/3) / GetCharWidth();
690 }
691
692 size_t count = messages.GetCount();
693 m_messages.Alloc(count);
694 m_severity.Alloc(count);
695 m_times.Alloc(count);
696
697 for ( size_t n = 0; n < count; n++ )
698 {
699 m_messages.Add(messages[n]);
700 m_severity.Add(severity[n]);
701 m_times.Add(times[n]);
702 }
703
704 m_listctrl = NULL;
705
706 bool isPda = (wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA);
707
708 // create the controls which are always shown and layout them: we use
709 // sizers even though our window is not resizeable to calculate the size of
710 // the dialog properly
711 wxBoxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
712 wxBoxSizer *sizerAll = new wxBoxSizer(isPda ? wxVERTICAL : wxHORIZONTAL);
713
714 if (!isPda)
715 {
716 wxStaticBitmap *icon = new wxStaticBitmap
717 (
718 this,
719 wxID_ANY,
720 wxArtProvider::GetMessageBoxIcon(style)
721 );
722 sizerAll->Add(icon, wxSizerFlags().Centre());
723 }
724
725 // create the text sizer with a minimal size so that we are sure it won't be too small
726 wxString message = EllipsizeString(messages.Last());
727 wxSizer *szText = CreateTextSizer(message);
728 szText->SetMinSize(wxMin(300, wxGetDisplaySize().x / 3), -1);
729
730 sizerAll->Add(szText, wxSizerFlags(1).Centre().Border(wxLEFT | wxRIGHT));
731
732 wxButton *btnOk = new wxButton(this, wxID_OK);
733 sizerAll->Add(btnOk, wxSizerFlags().Centre());
734
735 sizerTop->Add(sizerAll, wxSizerFlags().Expand().Border());
736
737
738 // add the details pane
739 #ifndef __SMARTPHONE__
740 wxCollapsiblePane * const
741 collpane = new wxCollapsiblePane(this, wxID_ANY, ms_details);
742 sizerTop->Add(collpane, wxSizerFlags(1).Expand().Border());
743
744 wxWindow *win = collpane->GetPane();
745 wxSizer * const paneSz = new wxBoxSizer(wxVERTICAL);
746
747 CreateDetailsControls(win);
748
749 paneSz->Add(m_listctrl, wxSizerFlags(1).Expand().Border(wxTOP));
750
751 #if wxUSE_CLIPBOARD || CAN_SAVE_FILES
752 wxBoxSizer * const btnSizer = new wxBoxSizer(wxHORIZONTAL);
753
754 wxSizerFlags flagsBtn;
755 flagsBtn.Border(wxLEFT);
756
757 #if wxUSE_CLIPBOARD
758 btnSizer->Add(new wxButton(win, wxID_COPY), flagsBtn);
759 #endif // wxUSE_CLIPBOARD
760
761 #if CAN_SAVE_FILES
762 btnSizer->Add(new wxButton(win, wxID_SAVE), flagsBtn);
763 #endif // CAN_SAVE_FILES
764
765 paneSz->Add(btnSizer, wxSizerFlags().Right().Border(wxTOP));
766 #endif // wxUSE_CLIPBOARD || CAN_SAVE_FILES
767
768 win->SetSizer(paneSz);
769 paneSz->SetSizeHints(win);
770 #else // __SMARTPHONE__
771 SetLeftMenu(wxID_OK);
772 SetRightMenu(wxID_MORE, ms_details + EXPAND_SUFFIX);
773 #endif // __SMARTPHONE__/!__SMARTPHONE__
774
775 SetSizerAndFit(sizerTop);
776
777 Centre();
778
779 if (isPda)
780 {
781 // Move up the screen so that when we expand the dialog,
782 // there's enough space.
783 Move(wxPoint(GetPosition().x, GetPosition().y / 2));
784 }
785 }
786
787 void wxLogDialog::CreateDetailsControls(wxWindow *parent)
788 {
789 wxString fmt = wxLog::GetTimestamp();
790 bool hasTimeStamp = !fmt.IsEmpty();
791
792 // create the list ctrl now
793 m_listctrl = new wxListCtrl(parent, wxID_ANY,
794 wxDefaultPosition, wxDefaultSize,
795 wxBORDER_SIMPLE |
796 wxLC_REPORT |
797 wxLC_NO_HEADER |
798 wxLC_SINGLE_SEL);
799 #ifdef __WXWINCE__
800 // This makes a big aesthetic difference on WinCE but I
801 // don't want to risk problems on other platforms
802 m_listctrl->Hide();
803 #endif
804
805 // no need to translate these strings as they're not shown to the
806 // user anyhow (we use wxLC_NO_HEADER style)
807 m_listctrl->InsertColumn(0, wxT("Message"));
808
809 if (hasTimeStamp)
810 m_listctrl->InsertColumn(1, wxT("Time"));
811
812 // prepare the imagelist
813 static const int ICON_SIZE = 16;
814 wxImageList *imageList = new wxImageList(ICON_SIZE, ICON_SIZE);
815
816 // order should be the same as in the switch below!
817 static const wxChar* const icons[] =
818 {
819 wxART_ERROR,
820 wxART_WARNING,
821 wxART_INFORMATION
822 };
823
824 bool loadedIcons = true;
825
826 for ( size_t icon = 0; icon < WXSIZEOF(icons); icon++ )
827 {
828 wxBitmap bmp = wxArtProvider::GetBitmap(icons[icon], wxART_MESSAGE_BOX,
829 wxSize(ICON_SIZE, ICON_SIZE));
830
831 // This may very well fail if there are insufficient colours available.
832 // Degrade gracefully.
833 if ( !bmp.Ok() )
834 {
835 loadedIcons = false;
836
837 break;
838 }
839
840 imageList->Add(bmp);
841 }
842
843 m_listctrl->SetImageList(imageList, wxIMAGE_LIST_SMALL);
844
845 // fill the listctrl
846 size_t count = m_messages.GetCount();
847 for ( size_t n = 0; n < count; n++ )
848 {
849 int image;
850
851 if ( loadedIcons )
852 {
853 switch ( m_severity[n] )
854 {
855 case wxLOG_Error:
856 image = 0;
857 break;
858
859 case wxLOG_Warning:
860 image = 1;
861 break;
862
863 default:
864 image = 2;
865 }
866 }
867 else // failed to load images
868 {
869 image = -1;
870 }
871
872 wxString msg = m_messages[n];
873 msg.Replace(wxT("\n"), wxT(" "));
874 msg = EllipsizeString(msg);
875
876 m_listctrl->InsertItem(n, msg, image);
877
878 if (hasTimeStamp)
879 m_listctrl->SetItem(n, 1, TimeStamp(fmt, (time_t)m_times[n]));
880 }
881
882 // let the columns size themselves
883 m_listctrl->SetColumnWidth(0, wxLIST_AUTOSIZE);
884 if (hasTimeStamp)
885 m_listctrl->SetColumnWidth(1, wxLIST_AUTOSIZE);
886
887 // calculate an approximately nice height for the listctrl
888 int height = GetCharHeight()*(count + 4);
889
890 // but check that the dialog won't fall fown from the screen
891 //
892 // we use GetMinHeight() to get the height of the dialog part without the
893 // details and we consider that the "Save" button below and the separator
894 // line (and the margins around it) take about as much, hence double it
895 int heightMax = wxGetDisplaySize().y - GetPosition().y - 2*GetMinHeight();
896
897 // we should leave a margin
898 heightMax *= 9;
899 heightMax /= 10;
900
901 m_listctrl->SetSize(wxDefaultCoord, wxMin(height, heightMax));
902 }
903
904 void wxLogDialog::OnListItemActivated(wxListEvent& event)
905 {
906 // show the activated item in a message box
907 // This allow the user to correctly display the logs which are longer
908 // than the listctrl and thus gets truncated or those which contains
909 // newlines.
910
911 // NB: don't do:
912 // wxString str = m_listctrl->GetItemText(event.GetIndex());
913 // as there's a 260 chars limit on the items inside a wxListCtrl in wxMSW.
914 wxString str = m_messages[event.GetIndex()];
915
916 // wxMessageBox will nicely handle the '\n' in the string (if any)
917 // and supports long strings
918 wxMessageBox(str, wxT("Log message"), wxOK, this);
919 }
920
921 void wxLogDialog::OnOk(wxCommandEvent& WXUNUSED(event))
922 {
923 EndModal(wxID_OK);
924 }
925
926 #if CAN_SAVE_FILES || wxUSE_CLIPBOARD
927
928 wxString wxLogDialog::GetLogMessages() const
929 {
930 wxString fmt = wxLog::GetTimestamp();
931 if ( fmt.empty() )
932 {
933 // use the default format
934 fmt = "%c";
935 }
936
937 const size_t count = m_messages.GetCount();
938
939 wxString text;
940 text.reserve(count*m_messages[0].length());
941 for ( size_t n = 0; n < count; n++ )
942 {
943 text << TimeStamp(fmt, (time_t)m_times[n])
944 << ": "
945 << m_messages[n]
946 << wxTextFile::GetEOL();
947 }
948
949 return text;
950 }
951
952 #endif // CAN_SAVE_FILES || wxUSE_CLIPBOARD
953
954 #if wxUSE_CLIPBOARD
955
956 void wxLogDialog::OnCopy(wxCommandEvent& WXUNUSED(event))
957 {
958 wxClipboardLocker clip;
959 if ( !clip ||
960 !wxTheClipboard->AddData(new wxTextDataObject(GetLogMessages())) )
961 {
962 wxLogError(_("Failed to copy dialog contents to the clipboard."));
963 }
964 }
965
966 #endif // wxUSE_CLIPBOARD
967
968 #if CAN_SAVE_FILES
969
970 void wxLogDialog::OnSave(wxCommandEvent& WXUNUSED(event))
971 {
972 wxFile file;
973 int rc = OpenLogFile(file, NULL, this);
974 if ( rc == -1 )
975 {
976 // cancelled
977 return;
978 }
979
980 if ( !rc || !file.Write(GetLogMessages()) || !file.Close() )
981 {
982 wxLogError(_("Can't save log contents to file."));
983 }
984 }
985
986 #endif // CAN_SAVE_FILES
987
988 wxLogDialog::~wxLogDialog()
989 {
990 if ( m_listctrl )
991 {
992 delete m_listctrl->GetImageList(wxIMAGE_LIST_SMALL);
993 }
994 }
995
996 #endif // wxUSE_LOG_DIALOG
997
998 #if CAN_SAVE_FILES
999
1000 // pass an uninitialized file object, the function will ask the user for the
1001 // filename and try to open it, returns true on success (file was opened),
1002 // false if file couldn't be opened/created and -1 if the file selection
1003 // dialog was cancelled
1004 static int OpenLogFile(wxFile& file, wxString *pFilename, wxWindow *parent)
1005 {
1006 // get the file name
1007 // -----------------
1008 wxString filename = wxSaveFileSelector(wxT("log"), wxT("txt"), wxT("log.txt"), parent);
1009 if ( !filename ) {
1010 // cancelled
1011 return -1;
1012 }
1013
1014 // open file
1015 // ---------
1016 bool bOk = true; // suppress warning about it being possible uninitialized
1017 if ( wxFile::Exists(filename) ) {
1018 bool bAppend = false;
1019 wxString strMsg;
1020 strMsg.Printf(_("Append log to file '%s' (choosing [No] will overwrite it)?"),
1021 filename.c_str());
1022 switch ( wxMessageBox(strMsg, _("Question"),
1023 wxICON_QUESTION | wxYES_NO | wxCANCEL) ) {
1024 case wxYES:
1025 bAppend = true;
1026 break;
1027
1028 case wxNO:
1029 bAppend = false;
1030 break;
1031
1032 case wxCANCEL:
1033 return -1;
1034
1035 default:
1036 wxFAIL_MSG(_("invalid message box return value"));
1037 }
1038
1039 if ( bAppend ) {
1040 bOk = file.Open(filename, wxFile::write_append);
1041 }
1042 else {
1043 bOk = file.Create(filename, true /* overwrite */);
1044 }
1045 }
1046 else {
1047 bOk = file.Create(filename);
1048 }
1049
1050 if ( pFilename )
1051 *pFilename = filename;
1052
1053 return bOk;
1054 }
1055
1056 #endif // CAN_SAVE_FILES
1057
1058 #endif // !(wxUSE_LOGGUI || wxUSE_LOGWINDOW)
1059
1060 #if wxUSE_LOG && wxUSE_TEXTCTRL
1061
1062 // ----------------------------------------------------------------------------
1063 // wxLogTextCtrl implementation
1064 // ----------------------------------------------------------------------------
1065
1066 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
1067 {
1068 m_pTextCtrl = pTextCtrl;
1069 }
1070
1071 void wxLogTextCtrl::DoLogText(const wxString& msg)
1072 {
1073 m_pTextCtrl->AppendText(msg + wxS('\n'));
1074 }
1075
1076 #endif // wxUSE_LOG && wxUSE_TEXTCTRL