avoid nested modal log dialogs
[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 {
675 if ( ms_details.IsEmpty() )
676 {
677 // ensure that we won't loop here if wxGetTranslation()
678 // happens to pop up a Log message while translating this :-)
679 ms_details = wxTRANSLATE("&Details");
680 ms_details = wxGetTranslation(ms_details);
681 }
682
683 size_t count = messages.GetCount();
684 m_messages.Alloc(count);
685 m_severity.Alloc(count);
686 m_times.Alloc(count);
687
688 for ( size_t n = 0; n < count; n++ )
689 {
690 wxString msg = messages[n];
691 do
692 {
693 m_messages.Add(msg.BeforeFirst(_T('\n')));
694 msg = msg.AfterFirst(_T('\n'));
695
696 m_severity.Add(severity[n]);
697 m_times.Add(times[n]);
698 }
699 while ( !!msg );
700 }
701
702 m_showingDetails = FALSE; // not initially
703 m_listctrl = (wxListCtrl *)NULL;
704
705 #if wxUSE_STATLINE
706 m_statline = (wxStaticLine *)NULL;
707 #endif // wxUSE_STATLINE
708
709 #if wxUSE_FILE
710 m_btnSave = (wxButton *)NULL;
711 #endif // wxUSE_FILE
712
713 // create the controls which are always shown and layout them: we use
714 // sizers even though our window is not resizeable to calculate the size of
715 // the dialog properly
716 wxBoxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
717 wxBoxSizer *sizerButtons = new wxBoxSizer(wxVERTICAL);
718 wxBoxSizer *sizerAll = new wxBoxSizer(wxHORIZONTAL);
719
720 // this "Ok" button has wxID_CANCEL id - not very logical, but this allows
721 // to close the log dialog with <Esc> which wouldn't work otherwise (as it
722 // translates into click on cancel button)
723 wxButton *btnOk = new wxButton(this, wxID_CANCEL, _("OK"));
724 sizerButtons->Add(btnOk, 0, wxCENTRE|wxBOTTOM, MARGIN/2);
725 m_btnDetails = new wxButton(this, wxID_MORE, ms_details + _T(" >>"));
726 sizerButtons->Add(m_btnDetails, 0, wxCENTRE|wxTOP, MARGIN/2 - 1);
727
728 #ifndef __WIN16__
729 wxIcon icon = wxTheApp->GetStdIcon((int)(style & wxICON_MASK));
730 sizerAll->Add(new wxStaticBitmap(this, -1, icon), 0, wxCENTRE);
731 #endif // !Win16
732
733 const wxString& message = messages.Last();
734 sizerAll->Add(CreateTextSizer(message), 0, wxCENTRE|wxLEFT|wxRIGHT, MARGIN);
735 sizerAll->Add(sizerButtons, 0, wxALIGN_RIGHT|wxLEFT, MARGIN);
736
737 sizerTop->Add(sizerAll, 0, wxCENTRE|wxALL, MARGIN);
738
739 SetAutoLayout(TRUE);
740 SetSizer(sizerTop);
741
742 sizerTop->SetSizeHints(this);
743 sizerTop->Fit(this);
744
745 btnOk->SetFocus();
746
747 // this can't happen any more as we don't use this dialog in this case
748 #if 0
749 if ( count == 1 )
750 {
751 // no details... it's easier to disable a button than to change the
752 // dialog layout depending on whether we have details or not
753 m_btnDetails->Disable();
754 }
755 #endif // 0
756
757 Centre();
758 }
759
760 void wxLogDialog::CreateDetailsControls()
761 {
762 // create the save button and separator line if possible
763 #if wxUSE_FILE
764 m_btnSave = new wxButton(this, wxID_SAVE, _("&Save..."));
765 #endif // wxUSE_FILE
766
767 #if wxUSE_STATLINE
768 m_statline = new wxStaticLine(this, -1);
769 #endif // wxUSE_STATLINE
770
771 // create the list ctrl now
772 m_listctrl = new wxListCtrl(this, -1,
773 wxDefaultPosition, wxDefaultSize,
774 wxSUNKEN_BORDER |
775 wxLC_REPORT |
776 wxLC_NO_HEADER |
777 wxLC_SINGLE_SEL);
778
779 // no need to translate these strings as they're not shown to the
780 // user anyhow (we use wxLC_NO_HEADER style)
781 m_listctrl->InsertColumn(0, _T("Message"));
782 m_listctrl->InsertColumn(1, _T("Time"));
783
784 // prepare the imagelist
785 static const int ICON_SIZE = 16;
786 wxImageList *imageList = new wxImageList(ICON_SIZE, ICON_SIZE);
787
788 // order should be the same as in the switch below!
789 static const int icons[] =
790 {
791 wxICON_ERROR,
792 wxICON_EXCLAMATION,
793 wxICON_INFORMATION
794 };
795
796 bool loadedIcons = TRUE;
797
798 #ifndef __WIN16__
799 for ( size_t icon = 0; icon < WXSIZEOF(icons); icon++ )
800 {
801 wxBitmap bmp = wxTheApp->GetStdIcon(icons[icon]);
802
803 // This may very well fail if there are insufficient
804 // colours available. Degrade gracefully.
805
806 if (!bmp.Ok())
807 loadedIcons = FALSE;
808 else
809 imageList->Add(wxImage(bmp).
810 Rescale(ICON_SIZE, ICON_SIZE).
811 ConvertToBitmap());
812 }
813
814 m_listctrl->SetImageList(imageList, wxIMAGE_LIST_SMALL);
815 #endif // !Win16
816
817 // and fill it
818 wxString fmt = wxLog::GetTimestamp();
819 if ( !fmt )
820 {
821 // default format
822 fmt = _T("%c");
823 }
824
825 size_t count = m_messages.GetCount();
826 for ( size_t n = 0; n < count; n++ )
827 {
828 int image = -1;
829 #ifndef __WIN16__
830 switch ( m_severity[n] )
831 {
832 case wxLOG_Error:
833 image = 0;
834 break;
835
836 case wxLOG_Warning:
837 image = 1;
838 break;
839
840 default:
841 image = 2;
842 }
843 #endif // !Win16
844
845 if (!loadedIcons)
846 image = -1;
847
848 if (image > -1)
849 m_listctrl->InsertItem(n, m_messages[n], image);
850 else
851 m_listctrl->InsertItem(n, m_messages[n]);
852
853 m_listctrl->SetItem(n, 1,
854 TimeStamp(fmt, (time_t)m_times[n]));
855 }
856
857 // let the columns size themselves
858 m_listctrl->SetColumnWidth(0, wxLIST_AUTOSIZE);
859 m_listctrl->SetColumnWidth(1, wxLIST_AUTOSIZE);
860
861 // get the approx height of the listctrl
862 wxFont font = GetFont();
863 if ( !font.Ok() )
864 font = *wxSWISS_FONT;
865
866 int y;
867 GetTextExtent(_T("H"), (int*)NULL, &y, (int*)NULL, (int*)NULL, &font);
868 int height = wxMax(y*(count + 3), 100);
869 m_listctrl->SetSize(-1, height);
870 }
871
872 void wxLogDialog::OnListSelect(wxListEvent& event)
873 {
874 // we can't just disable the control because this looks ugly under Windows
875 // (wrong bg colour, no scrolling...), but we still want to disable
876 // selecting items - it makes no sense here
877 m_listctrl->SetItemState(event.GetIndex(), 0, wxLIST_STATE_SELECTED);
878 }
879
880 void wxLogDialog::OnOk(wxCommandEvent& WXUNUSED(event))
881 {
882 EndModal(wxID_OK);
883 }
884
885 #if wxUSE_FILE
886
887 void wxLogDialog::OnSave(wxCommandEvent& WXUNUSED(event))
888 {
889 #if wxUSE_FILEDLG
890 wxFile file;
891 int rc = OpenLogFile(file);
892 if ( rc == -1 )
893 {
894 // cancelled
895 return;
896 }
897
898 bool ok = rc != 0;
899
900 wxString fmt = wxLog::GetTimestamp();
901 if ( !fmt )
902 {
903 // default format
904 fmt = _T("%c");
905 }
906
907 size_t count = m_messages.GetCount();
908 for ( size_t n = 0; ok && (n < count); n++ )
909 {
910 wxString line;
911 line << TimeStamp(fmt, (time_t)m_times[n])
912 << _T(": ")
913 << m_messages[n]
914 << wxTextFile::GetEOL();
915
916 ok = file.Write(line);
917 }
918
919 if ( ok )
920 ok = file.Close();
921
922 if ( !ok )
923 wxLogError(_("Can't save log contents to file."));
924 #endif
925 }
926
927 #endif // wxUSE_FILE
928
929 void wxLogDialog::OnDetails(wxCommandEvent& WXUNUSED(event))
930 {
931 wxSizer *sizer = GetSizer();
932
933 if ( m_showingDetails )
934 {
935 m_btnDetails->SetLabel(ms_details + _T(">>"));
936
937 sizer->Remove(m_listctrl);
938
939 #if wxUSE_STATLINE
940 sizer->Remove(m_statline);
941 #endif // wxUSE_STATLINE
942
943 #if wxUSE_FILE
944 sizer->Remove(m_btnSave);
945 #endif // wxUSE_FILE
946 }
947 else // show details now
948 {
949 m_btnDetails->SetLabel(wxString(_T("<< ")) + ms_details);
950
951 if ( !m_listctrl )
952 {
953 CreateDetailsControls();
954 }
955
956 #if wxUSE_STATLINE
957 sizer->Add(m_statline, 0, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
958 #endif // wxUSE_STATLINE
959
960 sizer->Add(m_listctrl, 1, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
961
962 #if wxUSE_FILE
963 sizer->Add(m_btnSave, 0, wxALIGN_RIGHT | (wxALL & ~wxTOP), MARGIN);
964 #endif // wxUSE_FILE
965 }
966
967 m_showingDetails = !m_showingDetails;
968
969 // in any case, our size changed - update
970 sizer->SetSizeHints(this);
971 sizer->Fit(this);
972
973 #ifdef __WXGTK__
974 // VS: this is neccessary in order to force frame redraw under
975 // WindowMaker or fvwm2 (and probably other broken WMs).
976 // Otherwise, detailed list wouldn't be displayed.
977 Show(TRUE);
978 #endif // wxGTK
979 }
980
981 wxLogDialog::~wxLogDialog()
982 {
983 if ( m_listctrl )
984 {
985 delete m_listctrl->GetImageList(wxIMAGE_LIST_SMALL);
986 }
987 }
988
989 #endif // wxUSE_LOG_DIALOG
990
991 #if wxUSE_FILE && wxUSE_FILEDLG
992
993 // pass an uninitialized file object, the function will ask the user for the
994 // filename and try to open it, returns TRUE on success (file was opened),
995 // FALSE if file couldn't be opened/created and -1 if the file selection
996 // dialog was cancelled
997 static int OpenLogFile(wxFile& file, wxString *pFilename)
998 {
999 // get the file name
1000 // -----------------
1001 wxString filename = wxSaveFileSelector(wxT("log"), wxT("txt"), wxT("log.txt"));
1002 if ( !filename ) {
1003 // cancelled
1004 return -1;
1005 }
1006
1007 // open file
1008 // ---------
1009 bool bOk = FALSE;
1010 if ( wxFile::Exists(filename) ) {
1011 bool bAppend = FALSE;
1012 wxString strMsg;
1013 strMsg.Printf(_("Append log to file '%s' (choosing [No] will overwrite it)?"),
1014 filename.c_str());
1015 switch ( wxMessageBox(strMsg, _("Question"),
1016 wxICON_QUESTION | wxYES_NO | wxCANCEL) ) {
1017 case wxYES:
1018 bAppend = TRUE;
1019 break;
1020
1021 case wxNO:
1022 bAppend = FALSE;
1023 break;
1024
1025 case wxCANCEL:
1026 return -1;
1027
1028 default:
1029 wxFAIL_MSG(_("invalid message box return value"));
1030 }
1031
1032 if ( bAppend ) {
1033 bOk = file.Open(filename, wxFile::write_append);
1034 }
1035 else {
1036 bOk = file.Create(filename, TRUE /* overwrite */);
1037 }
1038 }
1039 else {
1040 bOk = file.Create(filename);
1041 }
1042
1043 if ( pFilename )
1044 *pFilename = filename;
1045
1046 return bOk;
1047 }
1048
1049 #endif // wxUSE_FILE
1050
1051 #endif // !(wxUSE_LOGGUI || wxUSE_LOGWINDOW)
1052
1053 #if wxUSE_TEXTCTRL
1054
1055 // ----------------------------------------------------------------------------
1056 // wxLogTextCtrl implementation
1057 // ----------------------------------------------------------------------------
1058
1059 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
1060 {
1061 m_pTextCtrl = pTextCtrl;
1062 }
1063
1064 void wxLogTextCtrl::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
1065 {
1066 wxString msg;
1067 TimeStamp(&msg);
1068
1069 #ifdef __WXMAC__
1070 // VZ: this is a bug in wxMac, it *must* accept '\n' as new line, the
1071 // translation must be done in wxTextCtrl, not here! (FIXME)
1072 msg << szString << wxT('\r');
1073 #else
1074 msg << szString << wxT('\n');
1075 #endif
1076
1077 m_pTextCtrl->AppendText(msg);
1078 }
1079
1080 #endif // wxUSE_TEXTCTRL
1081