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