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