LibGfx: Parse "rgb(r,g,b)" style color strings

This parser is not very lenient, but it does the basic job. :^)
This commit is contained in:
Andreas Kling 2020-03-21 19:06:38 +01:00
parent e2a38f3aba
commit fd5a3b3c39
Notes: sideshowbarker 2024-07-19 08:11:47 +09:00

View file

@ -28,6 +28,7 @@
#include <AK/BufferStream.h>
#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/Vector.h>
#include <LibGfx/Color.h>
#include <LibGfx/SystemTheme.h>
#include <ctype.h>
@ -120,6 +121,38 @@ String Color::to_string() const
return String::format("#%b%b%b%b", red(), green(), blue(), alpha());
}
static Optional<Color> 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> Color::from_string(const StringView& string)
{
if (string.is_empty())
@ -292,6 +325,9 @@ Optional<Color> 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 {};