Color.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2019-2023, Shannon Booth <shannon@serenityos.org>
  4. * Copyright (c) 2024, Lucas Chollet <lucas.chollet@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Assertions.h>
  9. #include <AK/ByteString.h>
  10. #include <AK/FloatingPointStringConversions.h>
  11. #include <AK/Optional.h>
  12. #include <AK/Swift.h>
  13. #include <AK/Vector.h>
  14. #include <LibGfx/Color.h>
  15. #include <LibGfx/SystemTheme.h>
  16. #include <LibIPC/Decoder.h>
  17. #include <LibIPC/Encoder.h>
  18. #include <ctype.h>
  19. #ifdef LIBGFX_USE_SWIFT
  20. # include <LibGfx-Swift.h>
  21. #endif
  22. namespace Gfx {
  23. String Color::to_string(HTMLCompatibleSerialization html_compatible_serialization) const
  24. {
  25. // If the following conditions are all true:
  26. // 1. The color space is sRGB
  27. // NOTE: This is currently always true for Gfx::Color.
  28. // 2. The alpha is 1
  29. // NOTE: An alpha value of 1 will be stored as 255 currently.
  30. // 3. The RGB component values are internally represented as integers between 0 and 255 inclusive (i.e. 8-bit unsigned integer)
  31. // NOTE: This is currently always true for Gfx::Color.
  32. // 4. HTML-compatible serialization is requested
  33. if (alpha() == 255
  34. && html_compatible_serialization == HTMLCompatibleSerialization::Yes) {
  35. return MUST(String::formatted("#{:02x}{:02x}{:02x}", red(), green(), blue()));
  36. }
  37. // Otherwise, for sRGB the CSS serialization of sRGB values is used and for other color spaces, the relevant serialization of the <color> value.
  38. if (alpha() < 255)
  39. return MUST(String::formatted("rgba({}, {}, {}, {})", red(), green(), blue(), alpha() / 255.0));
  40. return MUST(String::formatted("rgb({}, {}, {})", red(), green(), blue()));
  41. }
  42. String Color::to_string_without_alpha() const
  43. {
  44. return MUST(String::formatted("#{:02x}{:02x}{:02x}", red(), green(), blue()));
  45. }
  46. ByteString Color::to_byte_string() const
  47. {
  48. return to_string().to_byte_string();
  49. }
  50. ByteString Color::to_byte_string_without_alpha() const
  51. {
  52. return to_string_without_alpha().to_byte_string();
  53. }
  54. static Optional<Color> parse_rgb_color(StringView string)
  55. {
  56. VERIFY(string.starts_with("rgb("sv, CaseSensitivity::CaseInsensitive));
  57. VERIFY(string.ends_with(')'));
  58. auto substring = string.substring_view(4, string.length() - 5);
  59. auto parts = substring.split_view(',');
  60. if (parts.size() != 3)
  61. return {};
  62. auto r = parts[0].to_number<double>().map(AK::clamp_to<u8, double>);
  63. auto g = parts[1].to_number<double>().map(AK::clamp_to<u8, double>);
  64. auto b = parts[2].to_number<double>().map(AK::clamp_to<u8, double>);
  65. if (!r.has_value() || !g.has_value() || !b.has_value())
  66. return {};
  67. return Color(*r, *g, *b);
  68. }
  69. static Optional<Color> parse_rgba_color(StringView string)
  70. {
  71. VERIFY(string.starts_with("rgba("sv, CaseSensitivity::CaseInsensitive));
  72. VERIFY(string.ends_with(')'));
  73. auto substring = string.substring_view(5, string.length() - 6);
  74. auto parts = substring.split_view(',');
  75. if (parts.size() != 4)
  76. return {};
  77. auto r = parts[0].to_number<double>().map(AK::clamp_to<u8, double>);
  78. auto g = parts[1].to_number<double>().map(AK::clamp_to<u8, double>);
  79. auto b = parts[2].to_number<double>().map(AK::clamp_to<u8, double>);
  80. double alpha = 0;
  81. auto alpha_str = parts[3].trim_whitespace();
  82. char const* start = alpha_str.characters_without_null_termination();
  83. auto alpha_result = parse_first_floating_point(start, start + alpha_str.length());
  84. if (alpha_result.parsed_value())
  85. alpha = alpha_result.value;
  86. unsigned a = alpha * 255;
  87. if (!r.has_value() || !g.has_value() || !b.has_value() || a > 255)
  88. return {};
  89. return Color(*r, *g, *b, a);
  90. }
  91. Optional<Color> Color::from_named_css_color_string(StringView string)
  92. {
  93. if (string.is_empty())
  94. return {};
  95. struct WebColor {
  96. ARGB32 color;
  97. StringView name;
  98. };
  99. constexpr Array web_colors {
  100. // CSS Level 1
  101. WebColor { 0x000000, "black"sv },
  102. WebColor { 0xc0c0c0, "silver"sv },
  103. WebColor { 0x808080, "gray"sv },
  104. WebColor { 0xffffff, "white"sv },
  105. WebColor { 0x800000, "maroon"sv },
  106. WebColor { 0xff0000, "red"sv },
  107. WebColor { 0x800080, "purple"sv },
  108. WebColor { 0xff00ff, "fuchsia"sv },
  109. WebColor { 0x008000, "green"sv },
  110. WebColor { 0x00ff00, "lime"sv },
  111. WebColor { 0x808000, "olive"sv },
  112. WebColor { 0xffff00, "yellow"sv },
  113. WebColor { 0x000080, "navy"sv },
  114. WebColor { 0x0000ff, "blue"sv },
  115. WebColor { 0x008080, "teal"sv },
  116. WebColor { 0x00ffff, "aqua"sv },
  117. // CSS Level 2 (Revision 1)
  118. WebColor { 0xffa500, "orange"sv },
  119. // CSS Color Module Level 3
  120. WebColor { 0xf0f8ff, "aliceblue"sv },
  121. WebColor { 0xfaebd7, "antiquewhite"sv },
  122. WebColor { 0x7fffd4, "aquamarine"sv },
  123. WebColor { 0xf0ffff, "azure"sv },
  124. WebColor { 0xf5f5dc, "beige"sv },
  125. WebColor { 0xffe4c4, "bisque"sv },
  126. WebColor { 0xffebcd, "blanchedalmond"sv },
  127. WebColor { 0x8a2be2, "blueviolet"sv },
  128. WebColor { 0xa52a2a, "brown"sv },
  129. WebColor { 0xdeb887, "burlywood"sv },
  130. WebColor { 0x5f9ea0, "cadetblue"sv },
  131. WebColor { 0x7fff00, "chartreuse"sv },
  132. WebColor { 0xd2691e, "chocolate"sv },
  133. WebColor { 0xff7f50, "coral"sv },
  134. WebColor { 0x6495ed, "cornflowerblue"sv },
  135. WebColor { 0xfff8dc, "cornsilk"sv },
  136. WebColor { 0xdc143c, "crimson"sv },
  137. WebColor { 0x00ffff, "cyan"sv },
  138. WebColor { 0x00008b, "darkblue"sv },
  139. WebColor { 0x008b8b, "darkcyan"sv },
  140. WebColor { 0xb8860b, "darkgoldenrod"sv },
  141. WebColor { 0xa9a9a9, "darkgray"sv },
  142. WebColor { 0x006400, "darkgreen"sv },
  143. WebColor { 0xa9a9a9, "darkgrey"sv },
  144. WebColor { 0xbdb76b, "darkkhaki"sv },
  145. WebColor { 0x8b008b, "darkmagenta"sv },
  146. WebColor { 0x556b2f, "darkolivegreen"sv },
  147. WebColor { 0xff8c00, "darkorange"sv },
  148. WebColor { 0x9932cc, "darkorchid"sv },
  149. WebColor { 0x8b0000, "darkred"sv },
  150. WebColor { 0xe9967a, "darksalmon"sv },
  151. WebColor { 0x8fbc8f, "darkseagreen"sv },
  152. WebColor { 0x483d8b, "darkslateblue"sv },
  153. WebColor { 0x2f4f4f, "darkslategray"sv },
  154. WebColor { 0x2f4f4f, "darkslategrey"sv },
  155. WebColor { 0x00ced1, "darkturquoise"sv },
  156. WebColor { 0x9400d3, "darkviolet"sv },
  157. WebColor { 0xff1493, "deeppink"sv },
  158. WebColor { 0x00bfff, "deepskyblue"sv },
  159. WebColor { 0x696969, "dimgray"sv },
  160. WebColor { 0x696969, "dimgrey"sv },
  161. WebColor { 0x1e90ff, "dodgerblue"sv },
  162. WebColor { 0xb22222, "firebrick"sv },
  163. WebColor { 0xfffaf0, "floralwhite"sv },
  164. WebColor { 0x228b22, "forestgreen"sv },
  165. WebColor { 0xdcdcdc, "gainsboro"sv },
  166. WebColor { 0xf8f8ff, "ghostwhite"sv },
  167. WebColor { 0xffd700, "gold"sv },
  168. WebColor { 0xdaa520, "goldenrod"sv },
  169. WebColor { 0xadff2f, "greenyellow"sv },
  170. WebColor { 0x808080, "grey"sv },
  171. WebColor { 0xf0fff0, "honeydew"sv },
  172. WebColor { 0xff69b4, "hotpink"sv },
  173. WebColor { 0xcd5c5c, "indianred"sv },
  174. WebColor { 0x4b0082, "indigo"sv },
  175. WebColor { 0xfffff0, "ivory"sv },
  176. WebColor { 0xf0e68c, "khaki"sv },
  177. WebColor { 0xe6e6fa, "lavender"sv },
  178. WebColor { 0xfff0f5, "lavenderblush"sv },
  179. WebColor { 0x7cfc00, "lawngreen"sv },
  180. WebColor { 0xfffacd, "lemonchiffon"sv },
  181. WebColor { 0xadd8e6, "lightblue"sv },
  182. WebColor { 0xf08080, "lightcoral"sv },
  183. WebColor { 0xe0ffff, "lightcyan"sv },
  184. WebColor { 0xfafad2, "lightgoldenrodyellow"sv },
  185. WebColor { 0xd3d3d3, "lightgray"sv },
  186. WebColor { 0x90ee90, "lightgreen"sv },
  187. WebColor { 0xd3d3d3, "lightgrey"sv },
  188. WebColor { 0xffb6c1, "lightpink"sv },
  189. WebColor { 0xffa07a, "lightsalmon"sv },
  190. WebColor { 0x20b2aa, "lightseagreen"sv },
  191. WebColor { 0x87cefa, "lightskyblue"sv },
  192. WebColor { 0x778899, "lightslategray"sv },
  193. WebColor { 0x778899, "lightslategrey"sv },
  194. WebColor { 0xb0c4de, "lightsteelblue"sv },
  195. WebColor { 0xffffe0, "lightyellow"sv },
  196. WebColor { 0x32cd32, "limegreen"sv },
  197. WebColor { 0xfaf0e6, "linen"sv },
  198. WebColor { 0xff00ff, "magenta"sv },
  199. WebColor { 0x66cdaa, "mediumaquamarine"sv },
  200. WebColor { 0x0000cd, "mediumblue"sv },
  201. WebColor { 0xba55d3, "mediumorchid"sv },
  202. WebColor { 0x9370db, "mediumpurple"sv },
  203. WebColor { 0x3cb371, "mediumseagreen"sv },
  204. WebColor { 0x7b68ee, "mediumslateblue"sv },
  205. WebColor { 0x00fa9a, "mediumspringgreen"sv },
  206. WebColor { 0x48d1cc, "mediumturquoise"sv },
  207. WebColor { 0xc71585, "mediumvioletred"sv },
  208. WebColor { 0x191970, "midnightblue"sv },
  209. WebColor { 0xf5fffa, "mintcream"sv },
  210. WebColor { 0xffe4e1, "mistyrose"sv },
  211. WebColor { 0xffe4b5, "moccasin"sv },
  212. WebColor { 0xffdead, "navajowhite"sv },
  213. WebColor { 0xfdf5e6, "oldlace"sv },
  214. WebColor { 0x6b8e23, "olivedrab"sv },
  215. WebColor { 0xff4500, "orangered"sv },
  216. WebColor { 0xda70d6, "orchid"sv },
  217. WebColor { 0xeee8aa, "palegoldenrod"sv },
  218. WebColor { 0x98fb98, "palegreen"sv },
  219. WebColor { 0xafeeee, "paleturquoise"sv },
  220. WebColor { 0xdb7093, "palevioletred"sv },
  221. WebColor { 0xffefd5, "papayawhip"sv },
  222. WebColor { 0xffdab9, "peachpuff"sv },
  223. WebColor { 0xcd853f, "peru"sv },
  224. WebColor { 0xffc0cb, "pink"sv },
  225. WebColor { 0xdda0dd, "plum"sv },
  226. WebColor { 0xb0e0e6, "powderblue"sv },
  227. WebColor { 0xbc8f8f, "rosybrown"sv },
  228. WebColor { 0x4169e1, "royalblue"sv },
  229. WebColor { 0x8b4513, "saddlebrown"sv },
  230. WebColor { 0xfa8072, "salmon"sv },
  231. WebColor { 0xf4a460, "sandybrown"sv },
  232. WebColor { 0x2e8b57, "seagreen"sv },
  233. WebColor { 0xfff5ee, "seashell"sv },
  234. WebColor { 0xa0522d, "sienna"sv },
  235. WebColor { 0x87ceeb, "skyblue"sv },
  236. WebColor { 0x6a5acd, "slateblue"sv },
  237. WebColor { 0x708090, "slategray"sv },
  238. WebColor { 0x708090, "slategrey"sv },
  239. WebColor { 0xfffafa, "snow"sv },
  240. WebColor { 0x00ff7f, "springgreen"sv },
  241. WebColor { 0x4682b4, "steelblue"sv },
  242. WebColor { 0xd2b48c, "tan"sv },
  243. WebColor { 0xd8bfd8, "thistle"sv },
  244. WebColor { 0xff6347, "tomato"sv },
  245. WebColor { 0x40e0d0, "turquoise"sv },
  246. WebColor { 0xee82ee, "violet"sv },
  247. WebColor { 0xf5deb3, "wheat"sv },
  248. WebColor { 0xf5f5f5, "whitesmoke"sv },
  249. WebColor { 0x9acd32, "yellowgreen"sv },
  250. // CSS Color Module Level 4
  251. WebColor { 0x663399, "rebeccapurple"sv },
  252. };
  253. for (auto const& web_color : web_colors) {
  254. if (string.equals_ignoring_ascii_case(web_color.name))
  255. return Color::from_rgb(web_color.color);
  256. }
  257. return {};
  258. }
  259. #if defined(LIBGFX_USE_SWIFT)
  260. static Optional<Color> hex_string_to_color(StringView string)
  261. {
  262. auto color = parseHexString(string);
  263. if (color.getCount() == 0)
  264. return {};
  265. return color[0];
  266. }
  267. #else
  268. static Optional<Color> hex_string_to_color(StringView string)
  269. {
  270. auto hex_nibble_to_u8 = [](char nibble) -> Optional<u8> {
  271. if (!isxdigit(nibble))
  272. return {};
  273. if (nibble >= '0' && nibble <= '9')
  274. return nibble - '0';
  275. return 10 + (tolower(nibble) - 'a');
  276. };
  277. if (string.length() == 4) {
  278. Optional<u8> r = hex_nibble_to_u8(string[1]);
  279. Optional<u8> g = hex_nibble_to_u8(string[2]);
  280. Optional<u8> b = hex_nibble_to_u8(string[3]);
  281. if (!r.has_value() || !g.has_value() || !b.has_value())
  282. return {};
  283. return Color(r.value() * 17, g.value() * 17, b.value() * 17);
  284. }
  285. if (string.length() == 5) {
  286. Optional<u8> r = hex_nibble_to_u8(string[1]);
  287. Optional<u8> g = hex_nibble_to_u8(string[2]);
  288. Optional<u8> b = hex_nibble_to_u8(string[3]);
  289. Optional<u8> a = hex_nibble_to_u8(string[4]);
  290. if (!r.has_value() || !g.has_value() || !b.has_value() || !a.has_value())
  291. return {};
  292. return Color(r.value() * 17, g.value() * 17, b.value() * 17, a.value() * 17);
  293. }
  294. if (string.length() != 7 && string.length() != 9)
  295. return {};
  296. auto to_hex = [&](char c1, char c2) -> Optional<u8> {
  297. auto nib1 = hex_nibble_to_u8(c1);
  298. auto nib2 = hex_nibble_to_u8(c2);
  299. if (!nib1.has_value() || !nib2.has_value())
  300. return {};
  301. return nib1.value() << 4 | nib2.value();
  302. };
  303. Optional<u8> r = to_hex(string[1], string[2]);
  304. Optional<u8> g = to_hex(string[3], string[4]);
  305. Optional<u8> b = to_hex(string[5], string[6]);
  306. Optional<u8> a = string.length() == 9 ? to_hex(string[7], string[8]) : Optional<u8>(255);
  307. if (!r.has_value() || !g.has_value() || !b.has_value() || !a.has_value())
  308. return {};
  309. return Color(r.value(), g.value(), b.value(), a.value());
  310. }
  311. #endif
  312. Optional<Color> Color::from_string(StringView string)
  313. {
  314. if (string.is_empty())
  315. return {};
  316. if (string[0] == '#')
  317. return hex_string_to_color(string);
  318. if (string.starts_with("rgb("sv, CaseSensitivity::CaseInsensitive) && string.ends_with(')'))
  319. return parse_rgb_color(string);
  320. if (string.starts_with("rgba("sv, CaseSensitivity::CaseInsensitive) && string.ends_with(')'))
  321. return parse_rgba_color(string);
  322. if (string.equals_ignoring_ascii_case("transparent"sv))
  323. return Color::from_argb(0x00000000);
  324. if (auto const color = from_named_css_color_string(string); color.has_value())
  325. return color;
  326. return {};
  327. }
  328. Vector<Color> Color::shades(u32 steps, float max) const
  329. {
  330. float shade = 1.f;
  331. float step = max / steps;
  332. Vector<Color> shades;
  333. for (u32 i = 0; i < steps; i++) {
  334. shade -= step;
  335. shades.append(this->darkened(shade));
  336. }
  337. return shades;
  338. }
  339. Vector<Color> Color::tints(u32 steps, float max) const
  340. {
  341. float shade = 1.f;
  342. float step = max / steps;
  343. Vector<Color> tints;
  344. for (u32 i = 0; i < steps; i++) {
  345. shade += step;
  346. tints.append(this->lightened(shade));
  347. }
  348. return tints;
  349. }
  350. Color Color::from_linear_srgb(float red, float green, float blue, float alpha)
  351. {
  352. auto linear_to_srgb = [](float c) {
  353. return c >= 0.0031308f ? 1.055f * pow(c, 0.4166666f) - 0.055f : 12.92f * c;
  354. };
  355. red = linear_to_srgb(red) * 255.f;
  356. green = linear_to_srgb(green) * 255.f;
  357. blue = linear_to_srgb(blue) * 255.f;
  358. return Color(
  359. clamp(lroundf(red), 0, 255),
  360. clamp(lroundf(green), 0, 255),
  361. clamp(lroundf(blue), 0, 255),
  362. clamp(lroundf(alpha * 255.f), 0, 255));
  363. }
  364. // https://www.w3.org/TR/css-color-4/#predefined-a98-rgb
  365. Color Color::from_a98rgb(float r, float g, float b, float alpha)
  366. {
  367. auto to_linear = [](float c) {
  368. return pow(c, 563. / 256);
  369. };
  370. auto linear_r = to_linear(r);
  371. auto linear_g = to_linear(g);
  372. auto linear_b = to_linear(b);
  373. float x = 0.57666904 * linear_r + 0.18555824 * linear_g + 0.18822865 * linear_b;
  374. float y = 0.29734498 * linear_r + 0.62736357 * linear_g + 0.07529146 * linear_b;
  375. float z = 0.02703136 * linear_r + 0.07068885 * linear_g + 0.99133754 * linear_b;
  376. return from_xyz65(x, y, z, alpha);
  377. }
  378. Color Color::from_xyz50(float x, float y, float z, float alpha)
  379. {
  380. // See commit description for these values
  381. float red = 3.13397926 * x - 1.61689519 * y - 0.49070587 * z;
  382. float green = -0.97840009 * x + 1.91589112 * y + 0.03339256 * z;
  383. float blue = 0.07200357 * x - 0.22897505 * y + 1.40517398 * z;
  384. return from_linear_srgb(red, green, blue, alpha);
  385. }
  386. Color Color::from_xyz65(float x, float y, float z, float alpha)
  387. {
  388. // https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB
  389. float red = 3.2406 * x - 1.5372 * y - 0.4986 * z;
  390. float green = -0.9689 * x + 1.8758 * y + 0.0415 * z;
  391. float blue = 0.0557 * x - 0.2040 * y + 1.0570 * z;
  392. return from_linear_srgb(red, green, blue, alpha);
  393. }
  394. Color Color::from_lab(float L, float a, float b, float alpha)
  395. {
  396. // Third edition of "Colorimetry" by the CIE
  397. // 8.2.1 CIE 1976 (L*a*b*) colour space; CIELAB colour space
  398. float y = (L + 16) / 116;
  399. float x = y + a / 500;
  400. float z = y - b / 200;
  401. auto f_inv = [](float t) -> float {
  402. constexpr auto delta = 24. / 116;
  403. if (t > delta)
  404. return t * t * t;
  405. return (108. / 841) * (t - 116. / 16);
  406. };
  407. // D50
  408. constexpr float x_n = 0.96422;
  409. constexpr float y_n = 1;
  410. constexpr float z_n = 0.82521;
  411. x = x_n * f_inv(x);
  412. y = y_n * f_inv(y);
  413. z = z_n * f_inv(z);
  414. return from_xyz50(x, y, z, alpha);
  415. }
  416. }
  417. template<>
  418. ErrorOr<void> IPC::encode(Encoder& encoder, Color const& color)
  419. {
  420. return encoder.encode(color.value());
  421. }
  422. template<>
  423. ErrorOr<Gfx::Color> IPC::decode(Decoder& decoder)
  424. {
  425. auto rgba = TRY(decoder.decode<u32>());
  426. return Gfx::Color::from_argb(rgba);
  427. }
  428. ErrorOr<void> AK::Formatter<Gfx::Color>::format(FormatBuilder& builder, Gfx::Color value)
  429. {
  430. return Formatter<StringView>::format(builder, value.to_byte_string());
  431. }
  432. ErrorOr<void> AK::Formatter<Gfx::YUV>::format(FormatBuilder& builder, Gfx::YUV value)
  433. {
  434. return Formatter<FormatString>::format(builder, "{} {} {}"sv, value.y, value.u, value.v);
  435. }
  436. ErrorOr<void> AK::Formatter<Gfx::HSV>::format(FormatBuilder& builder, Gfx::HSV value)
  437. {
  438. return Formatter<FormatString>::format(builder, "{} {} {}"sv, value.hue, value.saturation, value.value);
  439. }
  440. ErrorOr<void> AK::Formatter<Gfx::Oklab>::format(FormatBuilder& builder, Gfx::Oklab value)
  441. {
  442. return Formatter<FormatString>::format(builder, "{} {} {}"sv, value.L, value.a, value.b);
  443. }