From 15151d7a4c7c9138f960a8687224a52ff3722931 Mon Sep 17 00:00:00 2001 From: Shannon Booth Date: Sun, 28 May 2023 15:01:54 +1200 Subject: [PATCH] LibGfx: Add Color::from_named_css_color_string This is factored out from Color::from_string and determines the color only from performing an ASCII case-insensitive search over the named CSS colors. --- Userland/Libraries/LibGfx/Color.cpp | 20 ++++++++++++++++---- Userland/Libraries/LibGfx/Color.h | 1 + 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Userland/Libraries/LibGfx/Color.cpp b/Userland/Libraries/LibGfx/Color.cpp index a599e59cd2..e4323e67f1 100644 --- a/Userland/Libraries/LibGfx/Color.cpp +++ b/Userland/Libraries/LibGfx/Color.cpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling + * Copyright (c) 2019-2023, Shannon Booth * * SPDX-License-Identifier: BSD-2-Clause */ @@ -78,7 +79,7 @@ static Optional parse_rgba_color(StringView string) return Color(r, g, b, a); } -Optional Color::from_string(StringView string) +Optional Color::from_named_css_color_string(StringView string) { if (string.is_empty()) return {}; @@ -243,14 +244,25 @@ Optional Color::from_string(StringView string) WebColor { 0x663399, "rebeccapurple"sv }, }; - if (string.equals_ignoring_ascii_case("transparent"sv)) - return Color::from_argb(0x00000000); - for (auto const& web_color : web_colors) { if (string.equals_ignoring_ascii_case(web_color.name)) return Color::from_rgb(web_color.color); } + return {}; +} + +Optional Color::from_string(StringView string) +{ + if (string.is_empty()) + return {}; + + if (string.equals_ignoring_ascii_case("transparent"sv)) + return Color::from_argb(0x00000000); + + if (auto const color = from_named_css_color_string(string); color.has_value()) + return color; + if (string.starts_with("rgb("sv, CaseSensitivity::CaseInsensitive) && string.ends_with(')')) return parse_rgb_color(string); diff --git a/Userland/Libraries/LibGfx/Color.h b/Userland/Libraries/LibGfx/Color.h index 6f01981cb8..3f4ea9f4e2 100644 --- a/Userland/Libraries/LibGfx/Color.h +++ b/Userland/Libraries/LibGfx/Color.h @@ -378,6 +378,7 @@ public: DeprecatedString to_deprecated_string() const; DeprecatedString to_deprecated_string_without_alpha() const; static Optional from_string(StringView); + static Optional from_named_css_color_string(StringView); constexpr HSV to_hsv() const {