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