Refactor wxLog and wxMessageOutput classes to avoid duplication

Add wxMessageOutputWithConv mix-in class to avoid duplicating the same
code in wxLogStream and wxMessageOutputStderr.

Also derive wxLogStderr from wxMessageOutputStderr to reuse its code
without having to create a temporary object of this type (which will be
more expensive now that doing it involves creating a heap-allocated
conversion object copy).
This commit is contained in:
Vadim Zeitlin
2017-10-21 22:06:08 +02:00
parent 6b73bd9136
commit a7dddd9f3b
4 changed files with 72 additions and 74 deletions

View File

@@ -133,21 +133,10 @@ void wxMessageOutputBest::Output(const wxString& str)
}
// ----------------------------------------------------------------------------
// wxMessageOutputStderr
// wxMessageOutputWithConv
// ----------------------------------------------------------------------------
wxMessageOutputStderr::wxMessageOutputStderr(FILE *fp,
const wxMBConv &conv):
m_fp(fp), m_conv(conv.Clone())
{
}
wxMessageOutputStderr::~wxMessageOutputStderr()
{
delete m_conv;
}
wxString wxMessageOutputStderr::AppendLineFeedIfNeeded(const wxString& str)
wxString wxMessageOutputWithConv::AppendLineFeedIfNeeded(const wxString& str)
{
wxString strLF(str);
if ( strLF.empty() || *strLF.rbegin() != '\n' )
@@ -156,23 +145,36 @@ wxString wxMessageOutputStderr::AppendLineFeedIfNeeded(const wxString& str)
return strLF;
}
void wxMessageOutputStderr::Output(const wxString& str)
wxCharBuffer wxMessageOutputWithConv::PrepareForOutput(const wxString& str)
{
wxString strWithLF = AppendLineFeedIfNeeded(str);
#if defined(__WINDOWS__)
// Determine whether the encoding is UTF-16. In that case, the file
// should have been opened in "wb" mode, and EOL-style must be handled
// here.
if (m_conv->GetMBNulLen() == 2)
// should have been opened in "wb" mode, and EOL conversion must be done
// here as it won't be done at stdio level.
if ( m_conv->GetMBNulLen() == 2 )
{
strWithLF.Replace("\n", "\r\n");
}
#endif
#endif // __WINDOWS__
const wxCharBuffer buf = m_conv->cWX2MB(strWithLF.c_str());
return m_conv->cWX2MB(strWithLF.c_str());
}
// ----------------------------------------------------------------------------
// wxMessageOutputStderr
// ----------------------------------------------------------------------------
wxMessageOutputStderr::wxMessageOutputStderr(FILE *fp, const wxMBConv& conv)
: wxMessageOutputWithConv(conv),
m_fp(fp)
{
}
void wxMessageOutputStderr::Output(const wxString& str)
{
const wxCharBuffer& buf = PrepareForOutput(str);
fwrite(buf, buf.length(), 1, m_fp);
fflush(m_fp);
}