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