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