1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 06:17:35 +00:00

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.
This commit is contained in:
Shannon Booth 2023-05-28 15:01:54 +12:00 committed by Andreas Kling
parent f5bf53bc99
commit 15151d7a4c
2 changed files with 17 additions and 4 deletions

View file

@ -1,5 +1,6 @@
/* /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2019-2023, Shannon Booth <shannon.ml.booth@gmail.com>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
@ -78,7 +79,7 @@ static Optional<Color> parse_rgba_color(StringView string)
return Color(r, g, b, a); return Color(r, g, b, a);
} }
Optional<Color> Color::from_string(StringView string) Optional<Color> Color::from_named_css_color_string(StringView string)
{ {
if (string.is_empty()) if (string.is_empty())
return {}; return {};
@ -243,14 +244,25 @@ Optional<Color> Color::from_string(StringView string)
WebColor { 0x663399, "rebeccapurple"sv }, WebColor { 0x663399, "rebeccapurple"sv },
}; };
if (string.equals_ignoring_ascii_case("transparent"sv))
return Color::from_argb(0x00000000);
for (auto const& web_color : web_colors) { for (auto const& web_color : web_colors) {
if (string.equals_ignoring_ascii_case(web_color.name)) if (string.equals_ignoring_ascii_case(web_color.name))
return Color::from_rgb(web_color.color); return Color::from_rgb(web_color.color);
} }
return {};
}
Optional<Color> 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(')')) if (string.starts_with("rgb("sv, CaseSensitivity::CaseInsensitive) && string.ends_with(')'))
return parse_rgb_color(string); return parse_rgb_color(string);

View file

@ -378,6 +378,7 @@ public:
DeprecatedString to_deprecated_string() const; DeprecatedString to_deprecated_string() const;
DeprecatedString to_deprecated_string_without_alpha() const; DeprecatedString to_deprecated_string_without_alpha() const;
static Optional<Color> from_string(StringView); static Optional<Color> from_string(StringView);
static Optional<Color> from_named_css_color_string(StringView);
constexpr HSV to_hsv() const constexpr HSV to_hsv() const
{ {