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