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