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