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