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