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