From 9890cf6bac143b07a15d5e1009e3a0c51ab1eee9 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Sat, 11 Jul 2020 14:31:54 +0200 Subject: [PATCH] Return empty string from wxColour::GetAsString() if it's invalid This is consistent with wxToString(wxColour) and seems more useful than either returning black string representation (as wxMSW used to do) or asserting (as wxGTK did). Document this behaviour and add a test checking for it. Closes #18623. --- interface/wx/colour.h | 9 +++++---- src/common/colourcmn.cpp | 3 +++ tests/graphics/colour.cpp | 10 ++++++++++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/interface/wx/colour.h b/interface/wx/colour.h index 8f3a8535bc..4b35c82598 100644 --- a/interface/wx/colour.h +++ b/interface/wx/colour.h @@ -113,10 +113,11 @@ public: @c wxC2S_HTML_SYNTAX, to obtain the colour as "#" followed by 6 hexadecimal digits (e.g. wxColour(255,0,0) == "#FF0000"). - This function never fails and always returns a non-empty string but - asserts if the colour has alpha channel (i.e. is non opaque) but - @c wxC2S_CSS_SYNTAX (which is the only one supporting alpha) is not - specified in flags. + This function returns empty string if the colour is not initialized + (see IsOk()). Otherwise, the returned string is always non-empty, but + the function asserts if the colour has alpha channel (i.e. is non + opaque) but @c wxC2S_CSS_SYNTAX (which is the only one supporting + alpha) is not specified in @a flags. @note For non-solid (i.e. non-RGB) colour this function returns "rgb(??, ?? ??)" or "#??????". diff --git a/src/common/colourcmn.cpp b/src/common/colourcmn.cpp index 9d0b40a46c..56ed78321a 100644 --- a/src/common/colourcmn.cpp +++ b/src/common/colourcmn.cpp @@ -218,6 +218,9 @@ bool wxColourBase::FromString(const wxString& str) wxString wxColourBase::GetAsString(long flags) const { + if ( !IsOk() ) + return wxString(); + wxString colName; if ( IsSolid() ) diff --git a/tests/graphics/colour.cpp b/tests/graphics/colour.cpp index ec26cfefa2..865d92f662 100644 --- a/tests/graphics/colour.cpp +++ b/tests/graphics/colour.cpp @@ -145,6 +145,16 @@ TEST_CASE("wxColour::FromString", "[colour][string]") CHECK( !wxFromString("rgba(1, 2, 3.456, foo)", &col) ); } +TEST_CASE("wxColour::GetAsString", "[colour][string]") +{ + CHECK( wxColour().GetAsString() == "" ); + + wxColour red("red"); + CHECK( red.GetAsString() == "red" ); + CHECK( red.GetAsString(wxC2S_CSS_SYNTAX) == "rgb(255, 0, 0)" ); + CHECK( red.GetAsString(wxC2S_HTML_SYNTAX) == "#FF0000" ); +} + TEST_CASE("wxColour::GetLuminance", "[colour][luminance]") { CHECK( wxBLACK->GetLuminance() == Approx(0.0) );