]> git.saurik.com Git - wxWidgets.git/blob - src/generic/logg.cpp
Added SetActive to wxEventLoop
[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 wxLogError("FAILED fro %s:", icons[icon]);
830 loadedIcons = FALSE;
831
832 break;
833 }
834
835 imageList->Add(bmp);
836 }
837
838 m_listctrl->SetImageList(imageList, wxIMAGE_LIST_SMALL);
839 #endif // !Win16
840
841 // and fill it
842 wxString fmt = wxLog::GetTimestamp();
843 if ( !fmt )
844 {
845 // default format
846 fmt = _T("%c");
847 }
848
849 size_t count = m_messages.GetCount();
850 for ( size_t n = 0; n < count; n++ )
851 {
852 int image;
853
854 #ifndef __WIN16__
855 if ( loadedIcons )
856 {
857 switch ( m_severity[n] )
858 {
859 case wxLOG_Error:
860 image = 0;
861 break;
862
863 case wxLOG_Warning:
864 image = 1;
865 break;
866
867 default:
868 image = 2;
869 }
870 }
871 else // failed to load images
872 #endif // !Win16
873 {
874 image = -1;
875 }
876
877 m_listctrl->InsertItem(n, m_messages[n], image);
878 m_listctrl->SetItem(n, 1, TimeStamp(fmt, (time_t)m_times[n]));
879 }
880
881 // let the columns size themselves
882 m_listctrl->SetColumnWidth(0, wxLIST_AUTOSIZE);
883 m_listctrl->SetColumnWidth(1, wxLIST_AUTOSIZE);
884
885 // calculate an approximately nice height for the listctrl
886 int height = GetCharHeight()*(count + 4);
887
888 // but check that the dialog won't fall fown from the screen
889 //
890 // we use GetMinHeight() to get the height of the dialog part without the
891 // details and we consider that the "Save" button below and the separator
892 // line (and the margins around it) take about as much, hence double it
893 int heightMax = wxGetDisplaySize().y - GetPosition().y - 2*GetMinHeight();
894
895 // we should leave a margin
896 heightMax *= 9;
897 heightMax /= 10;
898
899 m_listctrl->SetSize(-1, wxMin(height, heightMax));
900 }
901
902 void wxLogDialog::OnListSelect(wxListEvent& event)
903 {
904 // we can't just disable the control because this looks ugly under Windows
905 // (wrong bg colour, no scrolling...), but we still want to disable
906 // selecting items - it makes no sense here
907 m_listctrl->SetItemState(event.GetIndex(), 0, wxLIST_STATE_SELECTED);
908 }
909
910 void wxLogDialog::OnOk(wxCommandEvent& WXUNUSED(event))
911 {
912 EndModal(wxID_OK);
913 }
914
915 #if wxUSE_FILE
916
917 void wxLogDialog::OnSave(wxCommandEvent& WXUNUSED(event))
918 {
919 #if wxUSE_FILEDLG
920 wxFile file;
921 int rc = OpenLogFile(file);
922 if ( rc == -1 )
923 {
924 // cancelled
925 return;
926 }
927
928 bool ok = rc != 0;
929
930 wxString fmt = wxLog::GetTimestamp();
931 if ( !fmt )
932 {
933 // default format
934 fmt = _T("%c");
935 }
936
937 size_t count = m_messages.GetCount();
938 for ( size_t n = 0; ok && (n < count); n++ )
939 {
940 wxString line;
941 line << TimeStamp(fmt, (time_t)m_times[n])
942 << _T(": ")
943 << m_messages[n]
944 << wxTextFile::GetEOL();
945
946 ok = file.Write(line);
947 }
948
949 if ( ok )
950 ok = file.Close();
951
952 if ( !ok )
953 wxLogError(_("Can't save log contents to file."));
954 #endif // wxUSE_FILEDLG
955 }
956
957 #endif // wxUSE_FILE
958
959 void wxLogDialog::OnDetails(wxCommandEvent& WXUNUSED(event))
960 {
961 wxSizer *sizer = GetSizer();
962
963 if ( m_showingDetails )
964 {
965 m_btnDetails->SetLabel(ms_details + _T(">>"));
966
967 sizer->Remove(m_listctrl);
968
969 #if wxUSE_STATLINE
970 sizer->Remove(m_statline);
971 #endif // wxUSE_STATLINE
972
973 #if wxUSE_FILE
974 sizer->Remove(m_btnSave);
975 #endif // wxUSE_FILE
976 }
977 else // show details now
978 {
979 m_btnDetails->SetLabel(wxString(_T("<< ")) + ms_details);
980
981 if ( !m_listctrl )
982 {
983 CreateDetailsControls();
984 }
985
986 #if wxUSE_STATLINE
987 sizer->Add(m_statline, 0, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
988 #endif // wxUSE_STATLINE
989
990 sizer->Add(m_listctrl, 1, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
991
992 // VZ: this doesn't work as this becomes the initial (and not only
993 // minimal) listctrl height as well - why?
994 #if 0
995 // allow the user to make the dialog shorter than its initial height -
996 // without this it wouldn't work as the list ctrl would have been
997 // incompressible
998 sizer->SetItemMinSize(m_listctrl, 100, 3*GetCharHeight());
999 #endif // 0
1000
1001 #if wxUSE_FILE
1002 sizer->Add(m_btnSave, 0, wxALIGN_RIGHT | (wxALL & ~wxTOP), MARGIN);
1003 #endif // wxUSE_FILE
1004 }
1005
1006 m_showingDetails = !m_showingDetails;
1007
1008 // in any case, our size changed - update
1009 sizer->SetSizeHints(this);
1010 sizer->Fit(this);
1011
1012 #ifdef __WXGTK__
1013 // VS: this is neccessary in order to force frame redraw under
1014 // WindowMaker or fvwm2 (and probably other broken WMs).
1015 // Otherwise, detailed list wouldn't be displayed.
1016 Show(TRUE);
1017 #endif // wxGTK
1018 }
1019
1020 wxLogDialog::~wxLogDialog()
1021 {
1022 if ( m_listctrl )
1023 {
1024 delete m_listctrl->GetImageList(wxIMAGE_LIST_SMALL);
1025 }
1026 }
1027
1028 #endif // wxUSE_LOG_DIALOG
1029
1030 #if wxUSE_FILE && wxUSE_FILEDLG
1031
1032 // pass an uninitialized file object, the function will ask the user for the
1033 // filename and try to open it, returns TRUE on success (file was opened),
1034 // FALSE if file couldn't be opened/created and -1 if the file selection
1035 // dialog was cancelled
1036 static int OpenLogFile(wxFile& file, wxString *pFilename)
1037 {
1038 // get the file name
1039 // -----------------
1040 wxString filename = wxSaveFileSelector(wxT("log"), wxT("txt"), wxT("log.txt"));
1041 if ( !filename ) {
1042 // cancelled
1043 return -1;
1044 }
1045
1046 // open file
1047 // ---------
1048 bool bOk = FALSE;
1049 if ( wxFile::Exists(filename) ) {
1050 bool bAppend = FALSE;
1051 wxString strMsg;
1052 strMsg.Printf(_("Append log to file '%s' (choosing [No] will overwrite it)?"),
1053 filename.c_str());
1054 switch ( wxMessageBox(strMsg, _("Question"),
1055 wxICON_QUESTION | wxYES_NO | wxCANCEL) ) {
1056 case wxYES:
1057 bAppend = TRUE;
1058 break;
1059
1060 case wxNO:
1061 bAppend = FALSE;
1062 break;
1063
1064 case wxCANCEL:
1065 return -1;
1066
1067 default:
1068 wxFAIL_MSG(_("invalid message box return value"));
1069 }
1070
1071 if ( bAppend ) {
1072 bOk = file.Open(filename, wxFile::write_append);
1073 }
1074 else {
1075 bOk = file.Create(filename, TRUE /* overwrite */);
1076 }
1077 }
1078 else {
1079 bOk = file.Create(filename);
1080 }
1081
1082 if ( pFilename )
1083 *pFilename = filename;
1084
1085 return bOk;
1086 }
1087
1088 #endif // wxUSE_FILE
1089
1090 #endif // !(wxUSE_LOGGUI || wxUSE_LOGWINDOW)
1091
1092 #if wxUSE_TEXTCTRL
1093
1094 // ----------------------------------------------------------------------------
1095 // wxLogTextCtrl implementation
1096 // ----------------------------------------------------------------------------
1097
1098 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
1099 {
1100 m_pTextCtrl = pTextCtrl;
1101 }
1102
1103 void wxLogTextCtrl::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
1104 {
1105 wxString msg;
1106 TimeStamp(&msg);
1107
1108 #if defined(__WXMAC__) && !defined(__DARWIN__)
1109 // VZ: this is a bug in wxMac, it *must* accept '\n' as new line, the
1110 // translation must be done in wxTextCtrl, not here! (FIXME)
1111 msg << szString << wxT('\r');
1112 #else
1113 msg << szString << wxT('\n');
1114 #endif
1115
1116 m_pTextCtrl->AppendText(msg);
1117 }
1118
1119 #endif // wxUSE_TEXTCTRL
1120