summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2020-03-21 19:06:38 +0100
committerAndreas Kling <kling@serenityos.org>2020-03-21 19:06:38 +0100
commitfd5a3b3c391dd4ae872914c7c2dcb77298dc2fb1 (patch)
treea45f089a9db082b49e511d6230a6279e3c5f2f66
parente2a38f3abaf0f50ec28b94f221486fa65db7a721 (diff)
downloadserenity-fd5a3b3c391dd4ae872914c7c2dcb77298dc2fb1.zip
LibGfx: Parse "rgb(r,g,b)" style color strings
This parser is not very lenient, but it does the basic job. :^)
-rw-r--r--Libraries/LibGfx/Color.cpp36
1 files changed, 36 insertions, 0 deletions
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 <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 {};