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