diff --git a/include/wx/msgout.h b/include/wx/msgout.h index e04e082f00..b03fc29c8b 100644 --- a/include/wx/msgout.h +++ b/include/wx/msgout.h @@ -49,6 +49,14 @@ private: static wxMessageOutput* ms_msgOut; }; +// This is equivalent to wxMessageOutput::Get()->Output() but doesn't crash if +// there is no message output object (which shouldn't normally happen). +inline void wxSafeMessageOutput(const wxString& str) +{ + if ( wxMessageOutput* msgOut = wxMessageOutput::Get() ) + msgOut->Output(str); +} + // ---------------------------------------------------------------------------- // helper mix-in for output targets that can use difference encodings // ---------------------------------------------------------------------------- diff --git a/interface/wx/msgout.h b/interface/wx/msgout.h index e7b6631403..b81ea6da46 100644 --- a/interface/wx/msgout.h +++ b/interface/wx/msgout.h @@ -183,3 +183,24 @@ public: /// Default constructor. wxMessageOutputMessageBox(); }; + +/** + Check that the message output exists before using it. + + This function is equivalent to + + @code + wxMessageOutput::Get()->Output(str); + @endcode + + but doesn't do anything if wxMessageOutput::Get() returns @NULL, instead of + crashing. + + Note that typically wxMessageOutput::Get() can only ever return @NULL if + wxAppTraits::CreateMessageOutput() is overridden to return @NULL, so unless + your application does this, using this function is not necessary as the + snippet above can be used directly. + + @since 3.3.0 + */ +void wxSafeMessageOutput(const wxString& str); diff --git a/src/common/cmdline.cpp b/src/common/cmdline.cpp index de2afcb51e..a9a7b60a7c 100644 --- a/src/common/cmdline.cpp +++ b/src/common/cmdline.cpp @@ -1236,19 +1236,10 @@ int wxCmdLineParser::Parse(bool showUsage) // and also the usage message if it had been requested if ( !ok && (!errorMsg.empty() || (helpRequested && showUsage)) ) { - wxMessageOutput* msgOut = wxMessageOutput::Get(); - if ( msgOut ) - { - wxString usage; - if ( showUsage ) - usage = GetUsageString(); + if ( showUsage ) + Usage(); - msgOut->Printf( wxT("%s%s"), usage.c_str(), errorMsg.c_str() ); - } - else - { - wxFAIL_MSG( wxT("no wxMessageOutput object?") ); - } + wxSafeMessageOutput(errorMsg); } return ok ? 0 : helpRequested ? -1 : 1; @@ -1260,10 +1251,7 @@ int wxCmdLineParser::Parse(bool showUsage) void wxCmdLineParser::Usage() const { - wxMessageOutput* msgOut = wxMessageOutput::Get(); - wxCHECK_RET( msgOut, wxT("no wxMessageOutput?") ); - - msgOut->Output(GetUsageString()); + wxSafeMessageOutput(GetUsageString(wrapColumn)); } wxString wxCmdLineParser::GetUsageString() const