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