From fd5a3b3c391dd4ae872914c7c2dcb77298dc2fb1 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sat, 21 Mar 2020 19:06:38 +0100 Subject: [PATCH] LibGfx: Parse "rgb(r,g,b)" style color strings This parser is not very lenient, but it does the basic job. :^) --- Libraries/LibGfx/Color.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Libraries/LibGfx/Color.cpp b/Libraries/LibGfx/Color.cpp index de5e8eb69e..851bc1d24b 100644 --- a/Libraries/LibGfx/Color.cpp +++ b/Libraries/LibGfx/Color.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -120,6 +121,38 @@ String Color::to_string() const return String::format("#%b%b%b%b", red(), green(), blue(), alpha()); } +static Optional parse_rgb_color(const StringView& string) +{ + ASSERT(string.starts_with("rgb(")); + ASSERT(string.ends_with(")")); + + auto substring = string.substring_view(4, string.length() - 5); + auto parts = substring.split_view(','); + + if (parts.size() != 3) + return {}; + + bool ok; + auto r = parts[0].to_int(ok); + if (!ok) + return {}; + auto g = parts[1].to_int(ok); + if (!ok) + return {}; + auto b = parts[2].to_int(ok); + if (!ok) + return {}; + + if (r < 0 || r > 255) + return {}; + if (g < 0 || g > 255) + return {}; + if (b < 0 || b > 255) + return {}; + + return Color(r, g, b); +} + Optional Color::from_string(const StringView& string) { if (string.is_empty()) @@ -292,6 +325,9 @@ Optional Color::from_string(const StringView& string) return Color::from_rgb(web_colors[i].color); } + if (string.starts_with("rgb(") && string.ends_with(")")) + return parse_rgb_color(string); + if (string[0] != '#') return {};