From 2ecc1d64d89834789893761ca14d2240567d72cf Mon Sep 17 00:00:00 2001 From: timmot Date: Sat, 18 Nov 2023 20:14:42 +1100 Subject: [PATCH] LibGfx: Accept decimal numbers when parsing rgb and rgba strings This will round all numbers and clamp them within the limits of a u8. This also standardises on returning u8 instead of uint/int. --- Userland/Libraries/LibGfx/Color.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Userland/Libraries/LibGfx/Color.cpp b/Userland/Libraries/LibGfx/Color.cpp index 5c538aa368..a2c70389b3 100644 --- a/Userland/Libraries/LibGfx/Color.cpp +++ b/Userland/Libraries/LibGfx/Color.cpp @@ -49,14 +49,14 @@ static Optional parse_rgb_color(StringView string) if (parts.size() != 3) return {}; - auto r = parts[0].to_uint().value_or(256); - auto g = parts[1].to_uint().value_or(256); - auto b = parts[2].to_uint().value_or(256); + auto r = parts[0].to_double().map(AK::clamp_to); + auto g = parts[1].to_double().map(AK::clamp_to); + auto b = parts[2].to_double().map(AK::clamp_to); - if (r > 255 || g > 255 || b > 255) + if (!r.has_value() || !g.has_value() || !b.has_value()) return {}; - return Color(r, g, b); + return Color(*r, *g, *b); } static Optional parse_rgba_color(StringView string) @@ -70,9 +70,9 @@ static Optional parse_rgba_color(StringView string) if (parts.size() != 4) return {}; - auto r = parts[0].to_int().value_or(256); - auto g = parts[1].to_int().value_or(256); - auto b = parts[2].to_int().value_or(256); + auto r = parts[0].to_double().map(AK::clamp_to); + auto g = parts[1].to_double().map(AK::clamp_to); + auto b = parts[2].to_double().map(AK::clamp_to); double alpha = 0; auto alpha_str = parts[3].trim_whitespace(); @@ -83,10 +83,10 @@ static Optional parse_rgba_color(StringView string) unsigned a = alpha * 255; - if (r > 255 || g > 255 || b > 255 || a > 255) + if (!r.has_value() || !g.has_value() || !b.has_value() || a > 255) return {}; - return Color(r, g, b, a); + return Color(*r, *g, *b, a); } Optional Color::from_named_css_color_string(StringView string)