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