]> git.saurik.com Git - wxWidgets.git/blob - src/generic/logg.cpp
Made Aqua style internal in wxSplitterWindow.
[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
56 #ifdef __WXMSW__
57 // for OutputDebugString()
58 #include "wx/msw/private.h"
59 #endif // Windows
60
61 #if wxUSE_LOG_DIALOG
62 #include "wx/listctrl.h"
63 #include "wx/imaglist.h"
64 #include "wx/image.h"
65 #else // !wxUSE_LOG_DIALOG
66 #include "wx/msgdlg.h"
67 #endif // wxUSE_LOG_DIALOG/!wxUSE_LOG_DIALOG
68
69 // ----------------------------------------------------------------------------
70 // private classes
71 // ----------------------------------------------------------------------------
72
73 #if wxUSE_LOG_DIALOG
74
75 // this function is a wrapper around strftime(3)
76 // allows to exclude the usage of wxDateTime
77 static wxString TimeStamp(const wxChar *format, time_t t)
78 {
79 wxChar buf[4096];
80 if ( !wxStrftime(buf, WXSIZEOF(buf), format, localtime(&t)) )
81 {
82 // buffer is too small?
83 wxFAIL_MSG(_T("strftime() failed"));
84 }
85 return wxString(buf);
86 }
87
88
89 class wxLogDialog : public wxDialog
90 {
91 public:
92 wxLogDialog(wxWindow *parent,
93 const wxArrayString& messages,
94 const wxArrayInt& severity,
95 const wxArrayLong& timess,
96 const wxString& caption,
97 long style);
98 virtual ~wxLogDialog();
99
100 // event handlers
101 void OnOk(wxCommandEvent& event);
102 void OnDetails(wxCommandEvent& event);
103 #if wxUSE_FILE
104 void OnSave(wxCommandEvent& event);
105 #endif // wxUSE_FILE
106 void OnListSelect(wxListEvent& event);
107
108 private:
109 // create controls needed for the details display
110 void CreateDetailsControls();
111
112 // the data for the listctrl
113 wxArrayString m_messages;
114 wxArrayInt m_severity;
115 wxArrayLong m_times;
116
117 // the "toggle" button and its state
118 wxButton *m_btnDetails;
119 bool m_showingDetails;
120
121 // the controls which are not shown initially (but only when details
122 // button is pressed)
123 wxListCtrl *m_listctrl;
124 #if wxUSE_STATLINE
125 wxStaticLine *m_statline;
126 #endif // wxUSE_STATLINE
127 #if wxUSE_FILE
128 wxButton *m_btnSave;
129 #endif // wxUSE_FILE
130
131 // the translated "Details" string
132 static wxString ms_details;
133
134 DECLARE_EVENT_TABLE()
135 };
136
137 BEGIN_EVENT_TABLE(wxLogDialog, wxDialog)
138 EVT_BUTTON(wxID_CANCEL, wxLogDialog::OnOk)
139 EVT_BUTTON(wxID_MORE, wxLogDialog::OnDetails)
140 #if wxUSE_FILE
141 EVT_BUTTON(wxID_SAVE, wxLogDialog::OnSave)
142 #endif // wxUSE_FILE
143 EVT_LIST_ITEM_SELECTED(-1, wxLogDialog::OnListSelect)
144 END_EVENT_TABLE()
145
146 #endif // wxUSE_LOG_DIALOG
147
148 // ----------------------------------------------------------------------------
149 // private functions
150 // ----------------------------------------------------------------------------
151
152 #if wxUSE_FILE && wxUSE_FILEDLG
153
154 // pass an uninitialized file object, the function will ask the user for the
155 // filename and try to open it, returns TRUE on success (file was opened),
156 // FALSE if file couldn't be opened/created and -1 if the file selection
157 // dialog was cancelled
158 static int OpenLogFile(wxFile& file, wxString *filename = NULL);
159
160 #endif // wxUSE_FILE
161
162 // ----------------------------------------------------------------------------
163 // global variables
164 // ----------------------------------------------------------------------------
165
166 // we use a global variable to store the frame pointer for wxLogStatus - bad,
167 // but it's the easiest way
168 static wxFrame *gs_pFrame = NULL; // FIXME MT-unsafe
169
170 // ============================================================================
171 // implementation
172 // ============================================================================
173
174 // ----------------------------------------------------------------------------
175 // global functions
176 // ----------------------------------------------------------------------------
177
178 // accepts an additional argument which tells to which frame the output should
179 // be directed
180 void wxLogStatus(wxFrame *pFrame, const wxChar *szFormat, ...)
181 {
182 wxString msg;
183
184 wxLog *pLog = wxLog::GetActiveTarget();
185 if ( pLog != NULL ) {
186 va_list argptr;
187 va_start(argptr, szFormat);
188 msg.PrintfV(szFormat, argptr);
189 va_end(argptr);
190
191 wxASSERT( gs_pFrame == NULL ); // should be reset!
192 gs_pFrame = pFrame;
193 wxLog::OnLog(wxLOG_Status, msg, time(NULL));
194 gs_pFrame = (wxFrame *) NULL;
195 }
196 }
197
198 // ----------------------------------------------------------------------------
199 // wxLogGui implementation (FIXME MT-unsafe)
200 // ----------------------------------------------------------------------------
201
202 wxLogGui::wxLogGui()
203 {
204 Clear();
205 }
206
207 void wxLogGui::Clear()
208 {
209 m_bErrors =
210 m_bWarnings =
211 m_bHasMessages = FALSE;
212
213 m_aMessages.Empty();
214 m_aSeverity.Empty();
215 m_aTimes.Empty();
216 }
217
218 void wxLogGui::Flush()
219 {
220 if ( !m_bHasMessages )
221 return;
222
223 // do it right now to block any new calls to Flush() while we're here
224 m_bHasMessages = FALSE;
225
226 wxString appName = wxTheApp->GetAppName();
227 if ( !!appName )
228 appName[0u] = wxToupper(appName[0u]);
229
230 long style;
231 wxString titleFormat;
232 if ( m_bErrors ) {
233 titleFormat = _("%s Error");
234 style = wxICON_STOP;
235 }
236 else if ( m_bWarnings ) {
237 titleFormat = _("%s Warning");
238 style = wxICON_EXCLAMATION;
239 }
240 else {
241 titleFormat = _("%s Information");
242 style = wxICON_INFORMATION;
243 }
244
245 wxString title;
246 title.Printf(titleFormat, appName.c_str());
247
248 size_t nMsgCount = m_aMessages.Count();
249
250 // avoid showing other log dialogs until we're done with the dialog we're
251 // showing right now: nested modal dialogs make for really bad UI!
252 Suspend();
253
254 wxString str;
255 if ( nMsgCount == 1 )
256 {
257 str = m_aMessages[0];
258 }
259 else // more than one message
260 {
261 #if wxUSE_LOG_DIALOG
262
263 wxLogDialog dlg(NULL,
264 m_aMessages, m_aSeverity, m_aTimes,
265 title, style);
266
267 // clear the message list before showing the dialog because while it's
268 // shown some new messages may appear
269 Clear();
270
271 (void)dlg.ShowModal();
272 #else // !wxUSE_LOG_DIALOG
273 // concatenate all strings (but not too many to not overfill the msg box)
274 size_t nLines = 0;
275
276 // start from the most recent message
277 for ( size_t n = nMsgCount; n > 0; n-- ) {
278 // for Windows strings longer than this value are wrapped (NT 4.0)
279 const size_t nMsgLineWidth = 156;
280
281 nLines += (m_aMessages[n - 1].Len() + nMsgLineWidth - 1) / nMsgLineWidth;
282
283 if ( nLines > 25 ) // don't put too many lines in message box
284 break;
285
286 str << m_aMessages[n - 1] << wxT("\n");
287 }
288 #endif // wxUSE_LOG_DIALOG/!wxUSE_LOG_DIALOG
289 }
290
291 // this catches both cases of 1 message with wxUSE_LOG_DIALOG and any
292 // situation without it
293 if ( !!str )
294 {
295 wxMessageBox(str, title, wxOK | style);
296
297 // no undisplayed messages whatsoever
298 Clear();
299 }
300
301 // allow flushing the logs again
302 Resume();
303 }
304
305 // log all kinds of messages
306 void wxLogGui::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
307 {
308 switch ( level ) {
309 case wxLOG_Info:
310 if ( GetVerbose() )
311 case wxLOG_Message:
312 {
313 if ( !m_bErrors ) {
314 m_aMessages.Add(szString);
315 m_aSeverity.Add(wxLOG_Message);
316 m_aTimes.Add((long)t);
317 m_bHasMessages = TRUE;
318 }
319 }
320 break;
321
322 case wxLOG_Status:
323 #if wxUSE_STATUSBAR
324 {
325 // find the top window and set it's status text if it has any
326 wxFrame *pFrame = gs_pFrame;
327 if ( pFrame == NULL ) {
328 wxWindow *pWin = wxTheApp->GetTopWindow();
329 if ( pWin != NULL && pWin->IsKindOf(CLASSINFO(wxFrame)) ) {
330 pFrame = (wxFrame *)pWin;
331 }
332 }
333
334 if ( pFrame && pFrame->GetStatusBar() )
335 pFrame->SetStatusText(szString);
336 }
337 #endif // wxUSE_STATUSBAR
338 break;
339
340 case wxLOG_Trace:
341 case wxLOG_Debug:
342 #ifdef __WXDEBUG__
343 {
344 wxString str;
345 TimeStamp(&str);
346 str += szString;
347
348 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
349 // don't prepend debug/trace here: it goes to the
350 // debug window anyhow
351 str += 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 str.c_str());
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
557 wxLogWindow::wxLogWindow(wxFrame *pParent,
558 const wxChar *szTitle,
559 bool bShow,
560 bool bDoPass)
561 {
562 PassMessages(bDoPass);
563
564 m_pLogFrame = new wxLogFrame(pParent, this, szTitle);
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::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
576 {
577 // first let the previous logger show it
578 wxLogPassThrough::DoLog(level, szString, t);
579
580 if ( m_pLogFrame ) {
581 switch ( level ) {
582 case wxLOG_Status:
583 // by default, these messages are ignored by wxLog, so process
584 // them ourselves
585 if ( !wxIsEmpty(szString) )
586 {
587 wxString str;
588 str << _("Status: ") << szString;
589 DoLogString(str, t);
590 }
591 break;
592
593 // don't put trace messages in the text window for 2 reasons:
594 // 1) there are too many of them
595 // 2) they may provoke other trace messages thus sending a program
596 // into an infinite loop
597 case wxLOG_Trace:
598 break;
599
600 default:
601 // and this will format it nicely and call our DoLogString()
602 wxLog::DoLog(level, szString, t);
603 }
604 }
605
606 m_bHasMessages = TRUE;
607 }
608
609 void wxLogWindow::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
610 {
611 // put the text into our window
612 wxTextCtrl *pText = m_pLogFrame->TextCtrl();
613
614 // remove selection (WriteText is in fact ReplaceSelection)
615 #ifdef __WXMSW__
616 long nLen = pText->GetLastPosition();
617 pText->SetSelection(nLen, nLen);
618 #endif // Windows
619
620 wxString msg;
621 TimeStamp(&msg);
622 msg << szString << wxT('\n');
623
624 pText->AppendText(msg);
625
626 // TODO ensure that the line can be seen
627 }
628
629 wxFrame *wxLogWindow::GetFrame() const
630 {
631 return m_pLogFrame;
632 }
633
634 void wxLogWindow::OnFrameCreate(wxFrame * WXUNUSED(frame))
635 {
636 }
637
638 bool wxLogWindow::OnFrameClose(wxFrame * WXUNUSED(frame))
639 {
640 // allow to close
641 return TRUE;
642 }
643
644 void wxLogWindow::OnFrameDelete(wxFrame * WXUNUSED(frame))
645 {
646 m_pLogFrame = (wxLogFrame *)NULL;
647 }
648
649 wxLogWindow::~wxLogWindow()
650 {
651 // may be NULL if log frame already auto destroyed itself
652 delete m_pLogFrame;
653 }
654
655 // ----------------------------------------------------------------------------
656 // wxLogDialog
657 // ----------------------------------------------------------------------------
658
659 #if wxUSE_LOG_DIALOG
660
661 static const size_t MARGIN = 10;
662
663 wxString wxLogDialog::ms_details;
664
665 wxLogDialog::wxLogDialog(wxWindow *parent,
666 const wxArrayString& messages,
667 const wxArrayInt& severity,
668 const wxArrayLong& times,
669 const wxString& caption,
670 long style)
671 : wxDialog(parent, -1, caption,
672 wxDefaultPosition, wxDefaultSize,
673 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
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);
731 #endif // !Win16
732
733 const wxString& message = messages.Last();
734 sizerAll->Add(CreateTextSizer(message), 1,
735 wxALIGN_CENTRE_VERTICAL | wxLEFT | wxRIGHT, MARGIN);
736 sizerAll->Add(sizerButtons, 0, wxALIGN_RIGHT | wxLEFT, MARGIN);
737
738 sizerTop->Add(sizerAll, 0, wxALL | wxEXPAND, MARGIN);
739
740 SetAutoLayout(TRUE);
741 SetSizer(sizerTop);
742
743 sizerTop->SetSizeHints(this);
744 sizerTop->Fit(this);
745
746 btnOk->SetFocus();
747
748 // this can't happen any more as we don't use this dialog in this case
749 #if 0
750 if ( count == 1 )
751 {
752 // no details... it's easier to disable a button than to change the
753 // dialog layout depending on whether we have details or not
754 m_btnDetails->Disable();
755 }
756 #endif // 0
757
758 Centre();
759 }
760
761 void wxLogDialog::CreateDetailsControls()
762 {
763 // create the save button and separator line if possible
764 #if wxUSE_FILE
765 m_btnSave = new wxButton(this, wxID_SAVE, _("&Save..."));
766 #endif // wxUSE_FILE
767
768 #if wxUSE_STATLINE
769 m_statline = new wxStaticLine(this, -1);
770 #endif // wxUSE_STATLINE
771
772 // create the list ctrl now
773 m_listctrl = new wxListCtrl(this, -1,
774 wxDefaultPosition, wxDefaultSize,
775 wxSUNKEN_BORDER |
776 wxLC_REPORT |
777 wxLC_NO_HEADER |
778 wxLC_SINGLE_SEL);
779
780 // no need to translate these strings as they're not shown to the
781 // user anyhow (we use wxLC_NO_HEADER style)
782 m_listctrl->InsertColumn(0, _T("Message"));
783 m_listctrl->InsertColumn(1, _T("Time"));
784
785 // prepare the imagelist
786 static const int ICON_SIZE = 16;
787 wxImageList *imageList = new wxImageList(ICON_SIZE, ICON_SIZE);
788
789 // order should be the same as in the switch below!
790 static const int icons[] =
791 {
792 wxICON_ERROR,
793 wxICON_EXCLAMATION,
794 wxICON_INFORMATION
795 };
796
797 bool loadedIcons = TRUE;
798
799 #ifndef __WIN16__
800 for ( size_t icon = 0; icon < WXSIZEOF(icons); icon++ )
801 {
802 wxBitmap bmp = wxTheApp->GetStdIcon(icons[icon]);
803
804 // This may very well fail if there are insufficient
805 // colours available. Degrade gracefully.
806
807 if (!bmp.Ok())
808 loadedIcons = FALSE;
809 else
810 imageList->Add(wxImage(bmp).
811 Rescale(ICON_SIZE, ICON_SIZE).
812 ConvertToBitmap());
813 }
814
815 m_listctrl->SetImageList(imageList, wxIMAGE_LIST_SMALL);
816 #endif // !Win16
817
818 // and fill it
819 wxString fmt = wxLog::GetTimestamp();
820 if ( !fmt )
821 {
822 // default format
823 fmt = _T("%c");
824 }
825
826 size_t count = m_messages.GetCount();
827 for ( size_t n = 0; n < count; n++ )
828 {
829 int image = -1;
830 #ifndef __WIN16__
831 switch ( m_severity[n] )
832 {
833 case wxLOG_Error:
834 image = 0;
835 break;
836
837 case wxLOG_Warning:
838 image = 1;
839 break;
840
841 default:
842 image = 2;
843 }
844 #endif // !Win16
845
846 if (!loadedIcons)
847 image = -1;
848
849 if (image > -1)
850 m_listctrl->InsertItem(n, m_messages[n], image);
851 else
852 m_listctrl->InsertItem(n, m_messages[n]);
853
854 m_listctrl->SetItem(n, 1,
855 TimeStamp(fmt, (time_t)m_times[n]));
856 }
857
858 // let the columns size themselves
859 m_listctrl->SetColumnWidth(0, wxLIST_AUTOSIZE);
860 m_listctrl->SetColumnWidth(1, wxLIST_AUTOSIZE);
861
862 // get the approx height of the listctrl
863 wxFont font = GetFont();
864 if ( !font.Ok() )
865 font = *wxSWISS_FONT;
866
867 int y;
868 GetTextExtent(_T("H"), (int*)NULL, &y, (int*)NULL, (int*)NULL, &font);
869 int height = wxMax(y*(count + 3), 100);
870
871 // if the height as computed from list items exceeds, together with the
872 // actual message & controls, the screen, make it smaller
873 int heightMax =
874 (3*wxSystemSettings::GetSystemMetric(wxSYS_SCREEN_Y))/5 - GetSize().y;
875
876 m_listctrl->SetSize(-1, wxMin(height, heightMax));
877 }
878
879 void wxLogDialog::OnListSelect(wxListEvent& event)
880 {
881 // we can't just disable the control because this looks ugly under Windows
882 // (wrong bg colour, no scrolling...), but we still want to disable
883 // selecting items - it makes no sense here
884 m_listctrl->SetItemState(event.GetIndex(), 0, wxLIST_STATE_SELECTED);
885 }
886
887 void wxLogDialog::OnOk(wxCommandEvent& WXUNUSED(event))
888 {
889 EndModal(wxID_OK);
890 }
891
892 #if wxUSE_FILE
893
894 void wxLogDialog::OnSave(wxCommandEvent& WXUNUSED(event))
895 {
896 #if wxUSE_FILEDLG
897 wxFile file;
898 int rc = OpenLogFile(file);
899 if ( rc == -1 )
900 {
901 // cancelled
902 return;
903 }
904
905 bool ok = rc != 0;
906
907 wxString fmt = wxLog::GetTimestamp();
908 if ( !fmt )
909 {
910 // default format
911 fmt = _T("%c");
912 }
913
914 size_t count = m_messages.GetCount();
915 for ( size_t n = 0; ok && (n < count); n++ )
916 {
917 wxString line;
918 line << TimeStamp(fmt, (time_t)m_times[n])
919 << _T(": ")
920 << m_messages[n]
921 << wxTextFile::GetEOL();
922
923 ok = file.Write(line);
924 }
925
926 if ( ok )
927 ok = file.Close();
928
929 if ( !ok )
930 wxLogError(_("Can't save log contents to file."));
931 #endif
932 }
933
934 #endif // wxUSE_FILE
935
936 void wxLogDialog::OnDetails(wxCommandEvent& WXUNUSED(event))
937 {
938 wxSizer *sizer = GetSizer();
939
940 if ( m_showingDetails )
941 {
942 m_btnDetails->SetLabel(ms_details + _T(">>"));
943
944 sizer->Remove(m_listctrl);
945
946 #if wxUSE_STATLINE
947 sizer->Remove(m_statline);
948 #endif // wxUSE_STATLINE
949
950 #if wxUSE_FILE
951 sizer->Remove(m_btnSave);
952 #endif // wxUSE_FILE
953 }
954 else // show details now
955 {
956 m_btnDetails->SetLabel(wxString(_T("<< ")) + ms_details);
957
958 if ( !m_listctrl )
959 {
960 CreateDetailsControls();
961 }
962
963 #if wxUSE_STATLINE
964 sizer->Add(m_statline, 0, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
965 #endif // wxUSE_STATLINE
966
967 sizer->Add(m_listctrl, 1, wxEXPAND | (wxALL & ~wxTOP), MARGIN);
968
969 #if wxUSE_FILE
970 sizer->Add(m_btnSave, 0, wxALIGN_RIGHT | (wxALL & ~wxTOP), MARGIN);
971 #endif // wxUSE_FILE
972 }
973
974 m_showingDetails = !m_showingDetails;
975
976 // in any case, our size changed - update
977 sizer->SetSizeHints(this);
978 sizer->Fit(this);
979
980 #ifdef __WXGTK__
981 // VS: this is neccessary in order to force frame redraw under
982 // WindowMaker or fvwm2 (and probably other broken WMs).
983 // Otherwise, detailed list wouldn't be displayed.
984 Show(TRUE);
985 #endif // wxGTK
986 }
987
988 wxLogDialog::~wxLogDialog()
989 {
990 if ( m_listctrl )
991 {
992 delete m_listctrl->GetImageList(wxIMAGE_LIST_SMALL);
993 }
994 }
995
996 #endif // wxUSE_LOG_DIALOG
997
998 #if wxUSE_FILE && wxUSE_FILEDLG
999
1000 // pass an uninitialized file object, the function will ask the user for the
1001 // filename and try to open it, returns TRUE on success (file was opened),
1002 // FALSE if file couldn't be opened/created and -1 if the file selection
1003 // dialog was cancelled
1004 static int OpenLogFile(wxFile& file, wxString *pFilename)
1005 {
1006 // get the file name
1007 // -----------------
1008 wxString filename = wxSaveFileSelector(wxT("log"), wxT("txt"), wxT("log.txt"));
1009 if ( !filename ) {
1010 // cancelled
1011 return -1;
1012 }
1013
1014 // open file
1015 // ---------
1016 bool bOk = FALSE;
1017 if ( wxFile::Exists(filename) ) {
1018 bool bAppend = FALSE;
1019 wxString strMsg;
1020 strMsg.Printf(_("Append log to file '%s' (choosing [No] will overwrite it)?"),
1021 filename.c_str());
1022 switch ( wxMessageBox(strMsg, _("Question"),
1023 wxICON_QUESTION | wxYES_NO | wxCANCEL) ) {
1024 case wxYES:
1025 bAppend = TRUE;
1026 break;
1027
1028 case wxNO:
1029 bAppend = FALSE;
1030 break;
1031
1032 case wxCANCEL:
1033 return -1;
1034
1035 default:
1036 wxFAIL_MSG(_("invalid message box return value"));
1037 }
1038
1039 if ( bAppend ) {
1040 bOk = file.Open(filename, wxFile::write_append);
1041 }
1042 else {
1043 bOk = file.Create(filename, TRUE /* overwrite */);
1044 }
1045 }
1046 else {
1047 bOk = file.Create(filename);
1048 }
1049
1050 if ( pFilename )
1051 *pFilename = filename;
1052
1053 return bOk;
1054 }
1055
1056 #endif // wxUSE_FILE
1057
1058 #endif // !(wxUSE_LOGGUI || wxUSE_LOGWINDOW)
1059
1060 #if wxUSE_TEXTCTRL
1061
1062 // ----------------------------------------------------------------------------
1063 // wxLogTextCtrl implementation
1064 // ----------------------------------------------------------------------------
1065
1066 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl *pTextCtrl)
1067 {
1068 m_pTextCtrl = pTextCtrl;
1069 }
1070
1071 void wxLogTextCtrl::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
1072 {
1073 wxString msg;
1074 TimeStamp(&msg);
1075
1076 #if defined(__WXMAC__) && !defined(__DARWIN__)
1077 // VZ: this is a bug in wxMac, it *must* accept '\n' as new line, the
1078 // translation must be done in wxTextCtrl, not here! (FIXME)
1079 msg << szString << wxT('\r');
1080 #else
1081 msg << szString << wxT('\n');
1082 #endif
1083
1084 m_pTextCtrl->AppendText(msg);
1085 }
1086
1087 #endif // wxUSE_TEXTCTRL
1088