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