ladybird/Libraries/LibGfx/Color.cpp

604 lines
21 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
* Copyright (c) 2019-2023, Shannon Booth <shannon@serenityos.org>
LibGfx+LibWeb/CSS: Add support for the `lab()` color function The support in LibWeb is quite easy as the previous commits introduced helpers to support lab-like colors. Now for the methods in Color: - The formulas in `from_lab()` are derived from the CIEXYZ to CIELAB formulas the "Colorimetry" paper published by the CIE. - The conversion in `from_xyz50()` can be decomposed in multiple steps XYZ D50 -> XYZ D65 -> Linear sRGB -> sRGB. The two first conversion are done with a singular matrix operation. This matrix was generated with a Python script [1]. This commit makes us pass all the `css/css-color/lab-00*.html` WPT tests (0 to 7 at the time of writing). [1] Python script used to generate the XYZ D50 -> Linear sRGB conversion: ```python import numpy as np # http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html # First let's convert from D50 to D65 using the Bradford method. m_a = np.array([ [0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000] ]) # D50 chromaticities_source = np.array([0.96422, 1, 0.82521]) # D65 chromaticities_destination = np.array([0.9505, 1, 1.0890]) cone_response_source = m_a @ chromaticities_source cone_response_destination = m_a @ chromaticities_destination cone_response_ratio = cone_response_destination / cone_response_source m = np.linalg.inv(m_a) @ np.diagflat(cone_response_ratio) @ m_a D50_to_D65 = m # https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB # Then, the matrix to convert to linear sRGB. xyz_65_to_srgb = np.array([ [3.2406, - 1.5372, - 0.4986], [-0.9689, + 1.8758, 0.0415], [0.0557, - 0.2040, 1.0570] ]) # Finally, let's retrieve the final transformation. xyz_50_to_srgb = xyz_65_to_srgb @ D50_to_D65 print(xyz_50_to_srgb) ```
2024-10-26 18:16:13 -03:00
* Copyright (c) 2024, Lucas Chollet <lucas.chollet@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Assertions.h>
#include <AK/ByteString.h>
#include <AK/Optional.h>
#include <AK/StringConversions.h>
#include <AK/Utf16String.h>
2025-07-22 12:25:56 -03:00
#include <AK/Utf16View.h>
#include <AK/Vector.h>
2020-02-06 08:04:00 -03:00
#include <LibGfx/Color.h>
#include <LibGfx/ColorConversion.h>
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
#include <ctype.h>
2018-10-10 11:49:36 -03:00
namespace Gfx {
namespace {
char nth_digit(u32 value, u8 digit)
{
// This helper is used to format integers.
// nth_digit(745, 1) -> '5'
// nth_digit(745, 2) -> '4'
// nth_digit(745, 3) -> '7'
VERIFY(value < 1000);
VERIFY(digit <= 3);
VERIFY(digit > 0);
while (digit > 1) {
value /= 10;
digit--;
}
return '0' + value % 10;
}
Array<char, 4> format_to_8bit_compatible(u8 value)
{
// This function formats to the shortest string that roundtrips at 8 bits.
// As an example:
// 127 / 255 = 0.498 ± 0.001
// 128 / 255 = 0.502 ± 0.001
// But round(.5 * 255) == 128, so this function returns (note that it's only the fractional part):
// 127 -> "498"
// 128 -> "5"
u32 const three_digits = (value * 1000u + 127) / 255;
u32 const rounded_to_two_digits = (three_digits + 5) / 10 * 10;
if ((rounded_to_two_digits * 255 / 100 + 5) / 10 != value)
return { nth_digit(three_digits, 3), nth_digit(three_digits, 2), nth_digit(three_digits, 1), '\0' };
u32 const rounded_to_one_digit = (three_digits + 50) / 100 * 100;
if ((rounded_to_one_digit * 255 / 100 + 5) / 10 != value)
return { nth_digit(rounded_to_two_digits, 3), nth_digit(rounded_to_two_digits, 2), '\0', '\0' };
return { nth_digit(rounded_to_one_digit, 3), '\0', '\0', '\0' };
}
}
// https://w3c.github.io/wcag/guidelines/22/#dfn-relative-luminance
double Color::relative_luminance() const
{
// the relative brightness of any point in a colorspace, normalized to 0 for darkest black and 1 for lightest
// white.
// Note 1:
// For the sRGB colorspace, the relative luminance of a color is defined as L = 0.2126 * R + 0.7152 * G +
// 0.0722 * B where R, G and B are defined as:
// * if RsRGB <= 0.04045 then R = RsRGB/12.92 else R = ((RsRGB+0.055)/1.055) ^ 2.4
// * if GsRGB <= 0.04045 then G = GsRGB/12.92 else G = ((GsRGB+0.055)/1.055) ^ 2.4
// * if BsRGB <= 0.04045 then B = BsRGB/12.92 else B = ((BsRGB+0.055)/1.055) ^ 2.4
// and RsRGB, GsRGB, and BsRGB are defined as:
// * RsRGB = R8bit/255
// * GsRGB = G8bit/255
// * BsRGB = B8bit/255
// The "^" character is the exponentiation operator. (Formula taken from [SRGB].)
auto linearized_srgb_component = [](u8 component) {
auto srgb_component = component / 255.0;
if (srgb_component <= 0.04045)
return srgb_component / 12.92;
return AK::pow((srgb_component + 0.055) / 1.055, 2.4);
};
return 0.2126 * linearized_srgb_component(red())
+ 0.7152 * linearized_srgb_component(green())
+ 0.0722 * linearized_srgb_component(blue());
}
// https://w3c.github.io/wcag/guidelines/22/#dfn-contrast-ratio
double Color::contrast_ratio(Color const other) const
{
// (L1 + 0.05) / (L2 + 0.05), where
// * L1 is the relative luminance of the lighter of the colors, and
// * L2 is the relative luminance of the darker of the colors.
auto l1 = relative_luminance();
auto l2 = other.relative_luminance();
auto darkest = min(l1, l2);
auto brightest = max(l1, l2);
return (brightest + 0.05) / (darkest + 0.05);
}
Color Color::suggested_foreground_color() const
{
return contrast_ratio(Black) >= contrast_ratio(White) ? Black : White;
}
// https://www.w3.org/TR/css-color-4/#serializing-sRGB-values
void Color::serialize_a_srgb_value(StringBuilder& builder) const
{
// The serialized form is derived from the computed value and thus, uses either the rgb() or rgba() form
// (depending on whether the alpha is exactly 1, or not), with lowercase letters for the function name.
// NOTE: Since we use Gfx::Color, having an "alpha of 1" means its value is 255.
if (alpha() == 0)
builder.appendff("rgba({}, {}, {}, 0)", red(), green(), blue());
else if (alpha() == 255)
builder.appendff("rgb({}, {}, {})", red(), green(), blue());
else
builder.appendff("rgba({}, {}, {}, 0.{})", red(), green(), blue(), format_to_8bit_compatible(alpha()).data());
}
String Color::serialize_a_srgb_value() const
{
StringBuilder builder;
serialize_a_srgb_value(builder);
return builder.to_string_without_validation();
}
String Color::to_string(HTMLCompatibleSerialization html_compatible_serialization) const
{
// If the following conditions are all true:
// 1. The color space is sRGB
// NOTE: This is currently always true for Gfx::Color.
// 2. The alpha is 1
// NOTE: An alpha value of 1 will be stored as 255 currently.
// 3. The RGB component values are internally represented as integers between 0 and 255 inclusive (i.e. 8-bit unsigned integer)
// NOTE: This is currently always true for Gfx::Color.
// 4. HTML-compatible serialization is requested
if (alpha() == 255
&& html_compatible_serialization == HTMLCompatibleSerialization::Yes) {
return MUST(String::formatted("#{:02x}{:02x}{:02x}", red(), green(), blue()));
}
// Otherwise, for sRGB the CSS serialization of sRGB values is used and for other color spaces, the relevant serialization of the <color> value.
return serialize_a_srgb_value();
}
String Color::to_string_without_alpha() const
{
return MUST(String::formatted("#{:02x}{:02x}{:02x}", red(), green(), blue()));
}
Utf16String Color::to_utf16_string_without_alpha() const
{
return Utf16String::formatted("#{:02x}{:02x}{:02x}", red(), green(), blue());
}
ByteString Color::to_byte_string() const
{
return to_string().to_byte_string();
}
ByteString Color::to_byte_string_without_alpha() const
{
return to_string_without_alpha().to_byte_string();
}
static Optional<Color> parse_rgb_color(StringView string)
{
VERIFY(string.starts_with("rgb("sv, CaseSensitivity::CaseInsensitive));
VERIFY(string.ends_with(')'));
auto substring = string.substring_view(4, string.length() - 5);
auto parts = substring.split_view(',');
if (parts.size() != 3)
return {};
auto r = parts[0].to_number<double>().map(AK::clamp_to<u8, double>);
auto g = parts[1].to_number<double>().map(AK::clamp_to<u8, double>);
auto b = parts[2].to_number<double>().map(AK::clamp_to<u8, double>);
if (!r.has_value() || !g.has_value() || !b.has_value())
return {};
return Color(*r, *g, *b);
}
static Optional<Color> parse_rgba_color(StringView string)
{
VERIFY(string.starts_with("rgba("sv, CaseSensitivity::CaseInsensitive));
VERIFY(string.ends_with(')'));
auto substring = string.substring_view(5, string.length() - 6);
auto parts = substring.split_view(',');
if (parts.size() != 4)
return {};
auto r = parts[0].to_number<double>().map(AK::clamp_to<u8, double>);
auto g = parts[1].to_number<double>().map(AK::clamp_to<u8, double>);
auto b = parts[2].to_number<double>().map(AK::clamp_to<u8, double>);
auto parse_result = AK::parse_first_number<double>(parts[3]);
auto alpha = parse_result.has_value() ? parse_result->value : 0.0;
unsigned a = alpha * 255;
if (!r.has_value() || !g.has_value() || !b.has_value() || a > 255)
return {};
return Color(*r, *g, *b, a);
}
Optional<Color> Color::from_named_css_color_string(StringView string)
{
if (string.is_empty())
return {};
struct WebColor {
Everywhere: Unify naming of RGBA-like colors The `Bitmap` type was referring to to its internal pixel format by a name that represents the order of the color components as they are layed out in memory. Contrary, the `Color` type was using a naming that where the name represents the order of the components from most to least significant byte when viewed as a unsigned 32bit integer. This is confusing as you have to keep remembering which mental model to use depending on which code you work with. To unify the two, the naming of RGBA-like colors in the `Color` type has been adjusted to match the one from the Bitmap type. This seems to be generally in line with how web APIs think about these types: * `ImageData.pixelFormat` can be `rgba-8unorm` backed by a `Uint8ClamedArray`, but there is no pixel format backed by a 32bit unsigned type. * WebGL can use format `RGBA` with type `UNSIGNED_BYTE`, but there is no such format with type `UNSIGNED_INT`. Additionally, it appears that other browsers and browser-adjacent libraries also think similarly about these types: * Firefox: https://github.com/mozilla-firefox/firefox/blob/main/gfx/2d/Types.h * WebKit: https://github.com/WebKit/WebKit/blob/main/Source/WebCore/platform/graphics/PixelFormat.h * Skia: https://chromium.googlesource.com/skia/+/refs/heads/main/include/core/SkColorType.h This has the not so nice side effect that APIs that interact with these types through 32bit unsigned integers now have the component order inverted due to little-endian byte order. E.g. specifying a color as hex constant needs to be done as `0xAABBGGRR` if it is to be treated as RGBA8888. We could alleviate this by providing endian-independent APIs to callers. But I suspect long-term we might want to think differently about bitmap data anyway, e.g. to better support HDR in the future. However, such changes would be more involved than just unifying the naming as done here. So I considered that out of scope for now.
2025-11-23 09:07:38 -03:00
BGRA8888 color;
StringView name;
};
constexpr Array web_colors {
// CSS Level 1
WebColor { 0x000000, "black"sv },
WebColor { 0xc0c0c0, "silver"sv },
WebColor { 0x808080, "gray"sv },
WebColor { 0xffffff, "white"sv },
WebColor { 0x800000, "maroon"sv },
WebColor { 0xff0000, "red"sv },
WebColor { 0x800080, "purple"sv },
WebColor { 0xff00ff, "fuchsia"sv },
WebColor { 0x008000, "green"sv },
WebColor { 0x00ff00, "lime"sv },
WebColor { 0x808000, "olive"sv },
WebColor { 0xffff00, "yellow"sv },
WebColor { 0x000080, "navy"sv },
WebColor { 0x0000ff, "blue"sv },
WebColor { 0x008080, "teal"sv },
WebColor { 0x00ffff, "aqua"sv },
// CSS Level 2 (Revision 1)
WebColor { 0xffa500, "orange"sv },
// CSS Color Module Level 3
WebColor { 0xf0f8ff, "aliceblue"sv },
WebColor { 0xfaebd7, "antiquewhite"sv },
WebColor { 0x7fffd4, "aquamarine"sv },
WebColor { 0xf0ffff, "azure"sv },
WebColor { 0xf5f5dc, "beige"sv },
WebColor { 0xffe4c4, "bisque"sv },
WebColor { 0xffebcd, "blanchedalmond"sv },
WebColor { 0x8a2be2, "blueviolet"sv },
WebColor { 0xa52a2a, "brown"sv },
WebColor { 0xdeb887, "burlywood"sv },
WebColor { 0x5f9ea0, "cadetblue"sv },
WebColor { 0x7fff00, "chartreuse"sv },
WebColor { 0xd2691e, "chocolate"sv },
WebColor { 0xff7f50, "coral"sv },
WebColor { 0x6495ed, "cornflowerblue"sv },
WebColor { 0xfff8dc, "cornsilk"sv },
WebColor { 0xdc143c, "crimson"sv },
WebColor { 0x00ffff, "cyan"sv },
WebColor { 0x00008b, "darkblue"sv },
WebColor { 0x008b8b, "darkcyan"sv },
WebColor { 0xb8860b, "darkgoldenrod"sv },
WebColor { 0xa9a9a9, "darkgray"sv },
WebColor { 0x006400, "darkgreen"sv },
WebColor { 0xa9a9a9, "darkgrey"sv },
WebColor { 0xbdb76b, "darkkhaki"sv },
WebColor { 0x8b008b, "darkmagenta"sv },
WebColor { 0x556b2f, "darkolivegreen"sv },
WebColor { 0xff8c00, "darkorange"sv },
WebColor { 0x9932cc, "darkorchid"sv },
WebColor { 0x8b0000, "darkred"sv },
WebColor { 0xe9967a, "darksalmon"sv },
WebColor { 0x8fbc8f, "darkseagreen"sv },
WebColor { 0x483d8b, "darkslateblue"sv },
WebColor { 0x2f4f4f, "darkslategray"sv },
WebColor { 0x2f4f4f, "darkslategrey"sv },
WebColor { 0x00ced1, "darkturquoise"sv },
WebColor { 0x9400d3, "darkviolet"sv },
WebColor { 0xff1493, "deeppink"sv },
WebColor { 0x00bfff, "deepskyblue"sv },
WebColor { 0x696969, "dimgray"sv },
WebColor { 0x696969, "dimgrey"sv },
WebColor { 0x1e90ff, "dodgerblue"sv },
WebColor { 0xb22222, "firebrick"sv },
WebColor { 0xfffaf0, "floralwhite"sv },
WebColor { 0x228b22, "forestgreen"sv },
WebColor { 0xdcdcdc, "gainsboro"sv },
WebColor { 0xf8f8ff, "ghostwhite"sv },
WebColor { 0xffd700, "gold"sv },
WebColor { 0xdaa520, "goldenrod"sv },
WebColor { 0xadff2f, "greenyellow"sv },
WebColor { 0x808080, "grey"sv },
WebColor { 0xf0fff0, "honeydew"sv },
WebColor { 0xff69b4, "hotpink"sv },
WebColor { 0xcd5c5c, "indianred"sv },
WebColor { 0x4b0082, "indigo"sv },
WebColor { 0xfffff0, "ivory"sv },
WebColor { 0xf0e68c, "khaki"sv },
WebColor { 0xe6e6fa, "lavender"sv },
WebColor { 0xfff0f5, "lavenderblush"sv },
WebColor { 0x7cfc00, "lawngreen"sv },
WebColor { 0xfffacd, "lemonchiffon"sv },
WebColor { 0xadd8e6, "lightblue"sv },
WebColor { 0xf08080, "lightcoral"sv },
WebColor { 0xe0ffff, "lightcyan"sv },
WebColor { 0xfafad2, "lightgoldenrodyellow"sv },
WebColor { 0xd3d3d3, "lightgray"sv },
WebColor { 0x90ee90, "lightgreen"sv },
WebColor { 0xd3d3d3, "lightgrey"sv },
WebColor { 0xffb6c1, "lightpink"sv },
WebColor { 0xffa07a, "lightsalmon"sv },
WebColor { 0x20b2aa, "lightseagreen"sv },
WebColor { 0x87cefa, "lightskyblue"sv },
WebColor { 0x778899, "lightslategray"sv },
WebColor { 0x778899, "lightslategrey"sv },
WebColor { 0xb0c4de, "lightsteelblue"sv },
WebColor { 0xffffe0, "lightyellow"sv },
WebColor { 0x32cd32, "limegreen"sv },
WebColor { 0xfaf0e6, "linen"sv },
WebColor { 0xff00ff, "magenta"sv },
WebColor { 0x66cdaa, "mediumaquamarine"sv },
WebColor { 0x0000cd, "mediumblue"sv },
WebColor { 0xba55d3, "mediumorchid"sv },
WebColor { 0x9370db, "mediumpurple"sv },
WebColor { 0x3cb371, "mediumseagreen"sv },
WebColor { 0x7b68ee, "mediumslateblue"sv },
WebColor { 0x00fa9a, "mediumspringgreen"sv },
WebColor { 0x48d1cc, "mediumturquoise"sv },
WebColor { 0xc71585, "mediumvioletred"sv },
WebColor { 0x191970, "midnightblue"sv },
WebColor { 0xf5fffa, "mintcream"sv },
WebColor { 0xffe4e1, "mistyrose"sv },
WebColor { 0xffe4b5, "moccasin"sv },
WebColor { 0xffdead, "navajowhite"sv },
WebColor { 0xfdf5e6, "oldlace"sv },
WebColor { 0x6b8e23, "olivedrab"sv },
WebColor { 0xff4500, "orangered"sv },
WebColor { 0xda70d6, "orchid"sv },
WebColor { 0xeee8aa, "palegoldenrod"sv },
WebColor { 0x98fb98, "palegreen"sv },
WebColor { 0xafeeee, "paleturquoise"sv },
WebColor { 0xdb7093, "palevioletred"sv },
WebColor { 0xffefd5, "papayawhip"sv },
WebColor { 0xffdab9, "peachpuff"sv },
WebColor { 0xcd853f, "peru"sv },
WebColor { 0xffc0cb, "pink"sv },
WebColor { 0xdda0dd, "plum"sv },
WebColor { 0xb0e0e6, "powderblue"sv },
WebColor { 0xbc8f8f, "rosybrown"sv },
WebColor { 0x4169e1, "royalblue"sv },
WebColor { 0x8b4513, "saddlebrown"sv },
WebColor { 0xfa8072, "salmon"sv },
WebColor { 0xf4a460, "sandybrown"sv },
WebColor { 0x2e8b57, "seagreen"sv },
WebColor { 0xfff5ee, "seashell"sv },
WebColor { 0xa0522d, "sienna"sv },
WebColor { 0x87ceeb, "skyblue"sv },
WebColor { 0x6a5acd, "slateblue"sv },
WebColor { 0x708090, "slategray"sv },
WebColor { 0x708090, "slategrey"sv },
WebColor { 0xfffafa, "snow"sv },
WebColor { 0x00ff7f, "springgreen"sv },
WebColor { 0x4682b4, "steelblue"sv },
WebColor { 0xd2b48c, "tan"sv },
WebColor { 0xd8bfd8, "thistle"sv },
WebColor { 0xff6347, "tomato"sv },
WebColor { 0x40e0d0, "turquoise"sv },
WebColor { 0xee82ee, "violet"sv },
WebColor { 0xf5deb3, "wheat"sv },
WebColor { 0xf5f5f5, "whitesmoke"sv },
WebColor { 0x9acd32, "yellowgreen"sv },
// CSS Color Module Level 4
WebColor { 0x663399, "rebeccapurple"sv },
};
for (auto const& web_color : web_colors) {
if (string.equals_ignoring_ascii_case(web_color.name))
Everywhere: Unify naming of RGBA-like colors The `Bitmap` type was referring to to its internal pixel format by a name that represents the order of the color components as they are layed out in memory. Contrary, the `Color` type was using a naming that where the name represents the order of the components from most to least significant byte when viewed as a unsigned 32bit integer. This is confusing as you have to keep remembering which mental model to use depending on which code you work with. To unify the two, the naming of RGBA-like colors in the `Color` type has been adjusted to match the one from the Bitmap type. This seems to be generally in line with how web APIs think about these types: * `ImageData.pixelFormat` can be `rgba-8unorm` backed by a `Uint8ClamedArray`, but there is no pixel format backed by a 32bit unsigned type. * WebGL can use format `RGBA` with type `UNSIGNED_BYTE`, but there is no such format with type `UNSIGNED_INT`. Additionally, it appears that other browsers and browser-adjacent libraries also think similarly about these types: * Firefox: https://github.com/mozilla-firefox/firefox/blob/main/gfx/2d/Types.h * WebKit: https://github.com/WebKit/WebKit/blob/main/Source/WebCore/platform/graphics/PixelFormat.h * Skia: https://chromium.googlesource.com/skia/+/refs/heads/main/include/core/SkColorType.h This has the not so nice side effect that APIs that interact with these types through 32bit unsigned integers now have the component order inverted due to little-endian byte order. E.g. specifying a color as hex constant needs to be done as `0xAABBGGRR` if it is to be treated as RGBA8888. We could alleviate this by providing endian-independent APIs to callers. But I suspect long-term we might want to think differently about bitmap data anyway, e.g. to better support HDR in the future. However, such changes would be more involved than just unifying the naming as done here. So I considered that out of scope for now.
2025-11-23 09:07:38 -03:00
return Color::from_bgrx(web_color.color);
}
return {};
}
static Optional<Color> hex_string_to_color(StringView string)
{
auto hex_nibble_to_u8 = [](char nibble) -> Optional<u8> {
if (!isxdigit(nibble))
return {};
if (nibble >= '0' && nibble <= '9')
return nibble - '0';
return 10 + (tolower(nibble) - 'a');
};
if (string.length() == 4) {
Optional<u8> r = hex_nibble_to_u8(string[1]);
Optional<u8> g = hex_nibble_to_u8(string[2]);
Optional<u8> b = hex_nibble_to_u8(string[3]);
if (!r.has_value() || !g.has_value() || !b.has_value())
return {};
return Color(r.value() * 17, g.value() * 17, b.value() * 17);
}
if (string.length() == 5) {
Optional<u8> r = hex_nibble_to_u8(string[1]);
Optional<u8> g = hex_nibble_to_u8(string[2]);
Optional<u8> b = hex_nibble_to_u8(string[3]);
Optional<u8> a = hex_nibble_to_u8(string[4]);
if (!r.has_value() || !g.has_value() || !b.has_value() || !a.has_value())
return {};
return Color(r.value() * 17, g.value() * 17, b.value() * 17, a.value() * 17);
}
if (string.length() != 7 && string.length() != 9)
return {};
auto to_hex = [&](char c1, char c2) -> Optional<u8> {
auto nib1 = hex_nibble_to_u8(c1);
auto nib2 = hex_nibble_to_u8(c2);
if (!nib1.has_value() || !nib2.has_value())
return {};
return nib1.value() << 4 | nib2.value();
};
Optional<u8> r = to_hex(string[1], string[2]);
Optional<u8> g = to_hex(string[3], string[4]);
Optional<u8> b = to_hex(string[5], string[6]);
Optional<u8> a = string.length() == 9 ? to_hex(string[7], string[8]) : Optional<u8>(255);
if (!r.has_value() || !g.has_value() || !b.has_value() || !a.has_value())
return {};
return Color(r.value(), g.value(), b.value(), a.value());
}
Optional<Color> Color::from_string(StringView string)
{
if (string.is_empty())
return {};
if (string[0] == '#')
return hex_string_to_color(string);
if (string.starts_with("rgb("sv, CaseSensitivity::CaseInsensitive) && string.ends_with(')'))
return parse_rgb_color(string);
if (string.starts_with("rgba("sv, CaseSensitivity::CaseInsensitive) && string.ends_with(')'))
return parse_rgba_color(string);
if (string.equals_ignoring_ascii_case("transparent"sv))
Everywhere: Unify naming of RGBA-like colors The `Bitmap` type was referring to to its internal pixel format by a name that represents the order of the color components as they are layed out in memory. Contrary, the `Color` type was using a naming that where the name represents the order of the components from most to least significant byte when viewed as a unsigned 32bit integer. This is confusing as you have to keep remembering which mental model to use depending on which code you work with. To unify the two, the naming of RGBA-like colors in the `Color` type has been adjusted to match the one from the Bitmap type. This seems to be generally in line with how web APIs think about these types: * `ImageData.pixelFormat` can be `rgba-8unorm` backed by a `Uint8ClamedArray`, but there is no pixel format backed by a 32bit unsigned type. * WebGL can use format `RGBA` with type `UNSIGNED_BYTE`, but there is no such format with type `UNSIGNED_INT`. Additionally, it appears that other browsers and browser-adjacent libraries also think similarly about these types: * Firefox: https://github.com/mozilla-firefox/firefox/blob/main/gfx/2d/Types.h * WebKit: https://github.com/WebKit/WebKit/blob/main/Source/WebCore/platform/graphics/PixelFormat.h * Skia: https://chromium.googlesource.com/skia/+/refs/heads/main/include/core/SkColorType.h This has the not so nice side effect that APIs that interact with these types through 32bit unsigned integers now have the component order inverted due to little-endian byte order. E.g. specifying a color as hex constant needs to be done as `0xAABBGGRR` if it is to be treated as RGBA8888. We could alleviate this by providing endian-independent APIs to callers. But I suspect long-term we might want to think differently about bitmap data anyway, e.g. to better support HDR in the future. However, such changes would be more involved than just unifying the naming as done here. So I considered that out of scope for now.
2025-11-23 09:07:38 -03:00
return Color::from_bgra(0x00000000);
if (auto const color = from_named_css_color_string(string); color.has_value())
return color;
return {};
}
2025-07-22 12:25:56 -03:00
Optional<Color> Color::from_utf16_string(Utf16View const& string)
{
return from_string(string.to_utf8_but_should_be_ported_to_utf16());
}
Vector<Color> Color::shades(u32 steps, float max) const
{
float shade = 1.f;
float step = max / steps;
Vector<Color> shades;
for (u32 i = 0; i < steps; i++) {
shade -= step;
shades.append(this->darkened(shade));
}
return shades;
}
Vector<Color> Color::tints(u32 steps, float max) const
{
float shade = 1.f;
float step = max / steps;
Vector<Color> tints;
for (u32 i = 0; i < steps; i++) {
shade += step;
tints.append(this->lightened(shade));
}
return tints;
}
static Color color_from_linear_srgb(ColorComponents const& linear)
LibGfx+LibWeb/CSS: Add support for the `lab()` color function The support in LibWeb is quite easy as the previous commits introduced helpers to support lab-like colors. Now for the methods in Color: - The formulas in `from_lab()` are derived from the CIEXYZ to CIELAB formulas the "Colorimetry" paper published by the CIE. - The conversion in `from_xyz50()` can be decomposed in multiple steps XYZ D50 -> XYZ D65 -> Linear sRGB -> sRGB. The two first conversion are done with a singular matrix operation. This matrix was generated with a Python script [1]. This commit makes us pass all the `css/css-color/lab-00*.html` WPT tests (0 to 7 at the time of writing). [1] Python script used to generate the XYZ D50 -> Linear sRGB conversion: ```python import numpy as np # http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html # First let's convert from D50 to D65 using the Bradford method. m_a = np.array([ [0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000] ]) # D50 chromaticities_source = np.array([0.96422, 1, 0.82521]) # D65 chromaticities_destination = np.array([0.9505, 1, 1.0890]) cone_response_source = m_a @ chromaticities_source cone_response_destination = m_a @ chromaticities_destination cone_response_ratio = cone_response_destination / cone_response_source m = np.linalg.inv(m_a) @ np.diagflat(cone_response_ratio) @ m_a D50_to_D65 = m # https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB # Then, the matrix to convert to linear sRGB. xyz_65_to_srgb = np.array([ [3.2406, - 1.5372, - 0.4986], [-0.9689, + 1.8758, 0.0415], [0.0557, - 0.2040, 1.0570] ]) # Finally, let's retrieve the final transformation. xyz_50_to_srgb = xyz_65_to_srgb @ D50_to_D65 print(xyz_50_to_srgb) ```
2024-10-26 18:16:13 -03:00
{
auto srgb = linear_srgb_to_srgb(linear);
LibGfx+LibWeb/CSS: Add support for the `lab()` color function The support in LibWeb is quite easy as the previous commits introduced helpers to support lab-like colors. Now for the methods in Color: - The formulas in `from_lab()` are derived from the CIEXYZ to CIELAB formulas the "Colorimetry" paper published by the CIE. - The conversion in `from_xyz50()` can be decomposed in multiple steps XYZ D50 -> XYZ D65 -> Linear sRGB -> sRGB. The two first conversion are done with a singular matrix operation. This matrix was generated with a Python script [1]. This commit makes us pass all the `css/css-color/lab-00*.html` WPT tests (0 to 7 at the time of writing). [1] Python script used to generate the XYZ D50 -> Linear sRGB conversion: ```python import numpy as np # http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html # First let's convert from D50 to D65 using the Bradford method. m_a = np.array([ [0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000] ]) # D50 chromaticities_source = np.array([0.96422, 1, 0.82521]) # D65 chromaticities_destination = np.array([0.9505, 1, 1.0890]) cone_response_source = m_a @ chromaticities_source cone_response_destination = m_a @ chromaticities_destination cone_response_ratio = cone_response_destination / cone_response_source m = np.linalg.inv(m_a) @ np.diagflat(cone_response_ratio) @ m_a D50_to_D65 = m # https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB # Then, the matrix to convert to linear sRGB. xyz_65_to_srgb = np.array([ [3.2406, - 1.5372, - 0.4986], [-0.9689, + 1.8758, 0.0415], [0.0557, - 0.2040, 1.0570] ]) # Finally, let's retrieve the final transformation. xyz_50_to_srgb = xyz_65_to_srgb @ D50_to_D65 print(xyz_50_to_srgb) ```
2024-10-26 18:16:13 -03:00
return Color(
clamp(lroundf(srgb[0] * 255.0f), 0, 255),
clamp(lroundf(srgb[1] * 255.0f), 0, 255),
clamp(lroundf(srgb[2] * 255.0f), 0, 255),
clamp(lroundf(srgb.alpha() * 255.0f), 0, 255));
LibGfx+LibWeb/CSS: Add support for the `lab()` color function The support in LibWeb is quite easy as the previous commits introduced helpers to support lab-like colors. Now for the methods in Color: - The formulas in `from_lab()` are derived from the CIEXYZ to CIELAB formulas the "Colorimetry" paper published by the CIE. - The conversion in `from_xyz50()` can be decomposed in multiple steps XYZ D50 -> XYZ D65 -> Linear sRGB -> sRGB. The two first conversion are done with a singular matrix operation. This matrix was generated with a Python script [1]. This commit makes us pass all the `css/css-color/lab-00*.html` WPT tests (0 to 7 at the time of writing). [1] Python script used to generate the XYZ D50 -> Linear sRGB conversion: ```python import numpy as np # http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html # First let's convert from D50 to D65 using the Bradford method. m_a = np.array([ [0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000] ]) # D50 chromaticities_source = np.array([0.96422, 1, 0.82521]) # D65 chromaticities_destination = np.array([0.9505, 1, 1.0890]) cone_response_source = m_a @ chromaticities_source cone_response_destination = m_a @ chromaticities_destination cone_response_ratio = cone_response_destination / cone_response_source m = np.linalg.inv(m_a) @ np.diagflat(cone_response_ratio) @ m_a D50_to_D65 = m # https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB # Then, the matrix to convert to linear sRGB. xyz_65_to_srgb = np.array([ [3.2406, - 1.5372, - 0.4986], [-0.9689, + 1.8758, 0.0415], [0.0557, - 0.2040, 1.0570] ]) # Finally, let's retrieve the final transformation. xyz_50_to_srgb = xyz_65_to_srgb @ D50_to_D65 print(xyz_50_to_srgb) ```
2024-10-26 18:16:13 -03:00
}
Color Color::from_linear_srgb(float red, float green, float blue, float alpha)
{
return color_from_linear_srgb({ red, green, blue, alpha });
}
Color Color::from_linear_display_p3(float r, float g, float b, float alpha)
{
auto xyz = linear_display_p3_to_xyz65({ r, g, b, alpha });
return from_xyz65(xyz[0], xyz[1], xyz[2], xyz.alpha());
}
// https://www.w3.org/TR/css-color-4/#predefined-a98-rgb
Color Color::from_a98rgb(float r, float g, float b, float alpha)
{
auto xyz = a98rgb_to_xyz65({ r, g, b, alpha });
return from_xyz65(xyz[0], xyz[1], xyz[2], xyz.alpha());
}
// https://www.w3.org/TR/css-color-4/#predefined-a98-rgb
Color Color::from_display_p3(float r, float g, float b, float alpha)
{
auto linear = display_p3_to_linear_display_p3({ r, g, b, alpha });
return from_linear_display_p3(linear[0], linear[1], linear[2], linear.alpha());
}
// https://www.w3.org/TR/css-color-4/#predefined-prophoto-rgb
Color Color::from_pro_photo_rgb(float r, float g, float b, float alpha)
{
auto xyz = pro_photo_rgb_to_xyz50({ r, g, b, alpha });
return from_xyz50(xyz[0], xyz[1], xyz[2], xyz.alpha());
}
// https://www.w3.org/TR/css-color-4/#predefined-rec2020
Color Color::from_rec2020(float r, float g, float b, float alpha)
{
auto xyz = rec2020_to_xyz65({ r, g, b, alpha });
return from_xyz65(xyz[0], xyz[1], xyz[2], xyz.alpha());
}
Color Color::from_xyz50(float x, float y, float z, float alpha)
{
auto linear = xyz50_to_linear_srgb({ x, y, z, alpha });
return color_from_linear_srgb(linear);
}
Color Color::from_xyz65(float x, float y, float z, float alpha)
{
auto linear = xyz65_to_linear_srgb({ x, y, z, alpha });
return color_from_linear_srgb(linear);
}
LibGfx+LibWeb/CSS: Add support for the `lab()` color function The support in LibWeb is quite easy as the previous commits introduced helpers to support lab-like colors. Now for the methods in Color: - The formulas in `from_lab()` are derived from the CIEXYZ to CIELAB formulas the "Colorimetry" paper published by the CIE. - The conversion in `from_xyz50()` can be decomposed in multiple steps XYZ D50 -> XYZ D65 -> Linear sRGB -> sRGB. The two first conversion are done with a singular matrix operation. This matrix was generated with a Python script [1]. This commit makes us pass all the `css/css-color/lab-00*.html` WPT tests (0 to 7 at the time of writing). [1] Python script used to generate the XYZ D50 -> Linear sRGB conversion: ```python import numpy as np # http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html # First let's convert from D50 to D65 using the Bradford method. m_a = np.array([ [0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000] ]) # D50 chromaticities_source = np.array([0.96422, 1, 0.82521]) # D65 chromaticities_destination = np.array([0.9505, 1, 1.0890]) cone_response_source = m_a @ chromaticities_source cone_response_destination = m_a @ chromaticities_destination cone_response_ratio = cone_response_destination / cone_response_source m = np.linalg.inv(m_a) @ np.diagflat(cone_response_ratio) @ m_a D50_to_D65 = m # https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB # Then, the matrix to convert to linear sRGB. xyz_65_to_srgb = np.array([ [3.2406, - 1.5372, - 0.4986], [-0.9689, + 1.8758, 0.0415], [0.0557, - 0.2040, 1.0570] ]) # Finally, let's retrieve the final transformation. xyz_50_to_srgb = xyz_65_to_srgb @ D50_to_D65 print(xyz_50_to_srgb) ```
2024-10-26 18:16:13 -03:00
Color Color::from_lab(float L, float a, float b, float alpha)
{
auto xyz = lab_to_xyz50({ L, a, b, alpha });
return from_xyz50(xyz[0], xyz[1], xyz[2], xyz.alpha());
LibGfx+LibWeb/CSS: Add support for the `lab()` color function The support in LibWeb is quite easy as the previous commits introduced helpers to support lab-like colors. Now for the methods in Color: - The formulas in `from_lab()` are derived from the CIEXYZ to CIELAB formulas the "Colorimetry" paper published by the CIE. - The conversion in `from_xyz50()` can be decomposed in multiple steps XYZ D50 -> XYZ D65 -> Linear sRGB -> sRGB. The two first conversion are done with a singular matrix operation. This matrix was generated with a Python script [1]. This commit makes us pass all the `css/css-color/lab-00*.html` WPT tests (0 to 7 at the time of writing). [1] Python script used to generate the XYZ D50 -> Linear sRGB conversion: ```python import numpy as np # http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html # First let's convert from D50 to D65 using the Bradford method. m_a = np.array([ [0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000] ]) # D50 chromaticities_source = np.array([0.96422, 1, 0.82521]) # D65 chromaticities_destination = np.array([0.9505, 1, 1.0890]) cone_response_source = m_a @ chromaticities_source cone_response_destination = m_a @ chromaticities_destination cone_response_ratio = cone_response_destination / cone_response_source m = np.linalg.inv(m_a) @ np.diagflat(cone_response_ratio) @ m_a D50_to_D65 = m # https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB # Then, the matrix to convert to linear sRGB. xyz_65_to_srgb = np.array([ [3.2406, - 1.5372, - 0.4986], [-0.9689, + 1.8758, 0.0415], [0.0557, - 0.2040, 1.0570] ]) # Finally, let's retrieve the final transformation. xyz_50_to_srgb = xyz_65_to_srgb @ D50_to_D65 print(xyz_50_to_srgb) ```
2024-10-26 18:16:13 -03:00
}
}
template<>
ErrorOr<void> IPC::encode(Encoder& encoder, Color const& color)
{
return encoder.encode(color.value());
}
template<>
ErrorOr<Gfx::Color> IPC::decode(Decoder& decoder)
{
auto rgba = TRY(decoder.decode<u32>());
Everywhere: Unify naming of RGBA-like colors The `Bitmap` type was referring to to its internal pixel format by a name that represents the order of the color components as they are layed out in memory. Contrary, the `Color` type was using a naming that where the name represents the order of the components from most to least significant byte when viewed as a unsigned 32bit integer. This is confusing as you have to keep remembering which mental model to use depending on which code you work with. To unify the two, the naming of RGBA-like colors in the `Color` type has been adjusted to match the one from the Bitmap type. This seems to be generally in line with how web APIs think about these types: * `ImageData.pixelFormat` can be `rgba-8unorm` backed by a `Uint8ClamedArray`, but there is no pixel format backed by a 32bit unsigned type. * WebGL can use format `RGBA` with type `UNSIGNED_BYTE`, but there is no such format with type `UNSIGNED_INT`. Additionally, it appears that other browsers and browser-adjacent libraries also think similarly about these types: * Firefox: https://github.com/mozilla-firefox/firefox/blob/main/gfx/2d/Types.h * WebKit: https://github.com/WebKit/WebKit/blob/main/Source/WebCore/platform/graphics/PixelFormat.h * Skia: https://chromium.googlesource.com/skia/+/refs/heads/main/include/core/SkColorType.h This has the not so nice side effect that APIs that interact with these types through 32bit unsigned integers now have the component order inverted due to little-endian byte order. E.g. specifying a color as hex constant needs to be done as `0xAABBGGRR` if it is to be treated as RGBA8888. We could alleviate this by providing endian-independent APIs to callers. But I suspect long-term we might want to think differently about bitmap data anyway, e.g. to better support HDR in the future. However, such changes would be more involved than just unifying the naming as done here. So I considered that out of scope for now.
2025-11-23 09:07:38 -03:00
return Gfx::Color::from_bgra(rgba);
}
2020-10-26 12:47:38 -03:00
ErrorOr<void> AK::Formatter<Gfx::Color>::format(FormatBuilder& builder, Gfx::Color value)
2020-10-26 12:47:38 -03:00
{
return Formatter<StringView>::format(builder, value.to_byte_string());
2020-10-26 12:47:38 -03:00
}
ErrorOr<void> AK::Formatter<Gfx::YUV>::format(FormatBuilder& builder, Gfx::YUV value)
{
return Formatter<FormatString>::format(builder, "{} {} {}"sv, value.y, value.u, value.v);
}
ErrorOr<void> AK::Formatter<Gfx::HSV>::format(FormatBuilder& builder, Gfx::HSV value)
{
return Formatter<FormatString>::format(builder, "{} {} {}"sv, value.hue, value.saturation, value.value);
}
ErrorOr<void> AK::Formatter<Gfx::Oklab>::format(FormatBuilder& builder, Gfx::Oklab value)
{
return Formatter<FormatString>::format(builder, "{} {} {}"sv, value.L, value.a, value.b);
}