1use lightningcss::traits::Parse as _;
5use lightningcss::values::color::{ColorSpace as _, CssColor, PredefinedColor};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum RgbSpace {
10 Srgb,
11 SrgbLinear,
12 DisplayP3,
13 DisplayP3Linear,
14}
15
16impl RgbSpace {
17 pub fn is_linear(self) -> bool {
18 matches!(self, RgbSpace::SrgbLinear | RgbSpace::DisplayP3Linear)
19 }
20
21 fn is_p3(self) -> bool {
22 matches!(self, RgbSpace::DisplayP3 | RgbSpace::DisplayP3Linear)
23 }
24}
25
26const SRGB_TO_XYZ: [[f64; 3]; 3] = [
27 [
28 0.412_390_799_265_959_34,
29 0.357_584_339_383_878,
30 0.180_480_788_401_834_3,
31 ],
32 [
33 0.212_639_005_871_510_27,
34 0.715_168_678_767_756,
35 0.072_192_315_360_733_71,
36 ],
37 [
38 0.019_330_818_715_591_82,
39 0.119_194_779_794_625_98,
40 0.950_532_152_249_660_7,
41 ],
42];
43const XYZ_TO_SRGB: [[f64; 3]; 3] = [
44 [
45 3.240_969_941_904_522_6,
46 -1.537_383_177_570_094,
47 -0.498_610_760_293_003_4,
48 ],
49 [
50 -0.969_243_636_280_879_6,
51 1.875_967_501_507_720_2,
52 0.041_555_057_407_175_59,
53 ],
54 [
55 0.055_630_079_696_993_66,
56 -0.203_976_958_888_976_52,
57 1.056_971_514_242_878_6,
58 ],
59];
60const P3_TO_XYZ: [[f64; 3]; 3] = [
61 [
62 0.486_570_948_648_216_2,
63 0.265_667_693_169_093_06,
64 0.198_217_285_234_362_5,
65 ],
66 [
67 0.228_974_564_069_748_8,
68 0.691_738_521_836_506_4,
69 0.079_286_914_093_745,
70 ],
71 [0.0, 0.045_113_381_858_902_64, 1.043_944_368_900_976],
72];
73const XYZ_TO_P3: [[f64; 3]; 3] = [
74 [
75 2.493_496_911_941_425,
76 -0.931_383_617_919_123_9,
77 -0.402_710_784_450_716_84,
78 ],
79 [
80 -0.829_488_969_561_574_7,
81 1.762_664_060_318_346_3,
82 0.023_624_685_841_943_577,
83 ],
84 [
85 0.035_845_830_243_784_47,
86 -0.076_172_389_268_041_82,
87 0.956_884_524_007_687_2,
88 ],
89];
90
91fn mul(m: &[[f64; 3]; 3], [r, g, b]: [f64; 3]) -> [f64; 3] {
92 m.map(|row| row[0] * r + row[1] * g + row[2] * b)
93}
94
95pub fn to_linear(c: f32) -> f32 {
97 let a = c.abs();
98 if a <= 0.040_45 {
99 c / 12.92
100 } else {
101 c.signum() * ((a + 0.055) / 1.055).powf(2.4)
102 }
103}
104
105pub fn from_linear(c: f32) -> f32 {
106 let a = c.abs();
107 if a <= 0.003_130_8 {
108 c * 12.92
109 } else {
110 c.signum() * (1.055 * a.powf(1.0 / 2.4) - 0.055)
111 }
112}
113
114pub fn convert_rgb(rgb: [f32; 3], from: RgbSpace, to: RgbSpace) -> [f32; 3] {
116 if from == to {
117 return rgb;
118 }
119 let lin = if from.is_linear() {
120 rgb
121 } else {
122 rgb.map(to_linear)
123 };
124 let lin = if from.is_p3() == to.is_p3() {
125 lin
126 } else {
127 let (into_xyz, out_of_xyz) = if from.is_p3() {
128 (&P3_TO_XYZ, &XYZ_TO_SRGB)
129 } else {
130 (&SRGB_TO_XYZ, &XYZ_TO_P3)
131 };
132 mul(out_of_xyz, mul(into_xyz, lin.map(f64::from))).map(|v| v as f32)
133 };
134 if to.is_linear() {
135 lin
136 } else {
137 lin.map(from_linear)
138 }
139}
140
141pub(crate) fn display_p3_linear(text: &str) -> Option<[f32; 4]> {
143 let rest = strip_ci(text.trim(), "color(")?.trim_start();
144 let after = strip_ci(rest, "display-p3-linear")?;
145 if !after.starts_with(|c: char| c.is_ascii_whitespace() || c == ')' || c == '/') {
146 return None;
147 }
148 match CssColor::parse_string(&format!("color(srgb-linear{after}")).ok()? {
149 CssColor::Predefined(p) => match *p {
150 PredefinedColor::SRGBLinear(c) => {
151 let c = c.resolve_missing();
152 Some([c.r, c.g, c.b, c.alpha])
153 }
154 _ => None,
155 },
156 _ => None,
157 }
158}
159
160fn strip_ci<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
161 let head = text.get(..prefix.len())?;
162 head.eq_ignore_ascii_case(prefix)
163 .then(|| &text[prefix.len()..])
164}
165
166pub(crate) fn rewrite(text: &str) -> Option<String> {
169 let lower = text.to_ascii_lowercase();
170 if !lower.contains("display-p3-linear") {
171 return None;
172 }
173 let bytes = lower.as_bytes();
174 let mut out = String::with_capacity(text.len());
175 let (mut copied, mut from) = (0, 0);
176 while let Some(at) = lower[from..].find("color(").map(|i| from + i) {
177 from = at + "color(".len();
178 let joined = at > 0
179 && (bytes[at - 1].is_ascii_alphanumeric() || matches!(bytes[at - 1], b'-' | b'_'));
180 if joined {
181 continue;
182 }
183 let Some(end) = closing(bytes, from) else {
184 break;
185 };
186 if let Some([r, g, b, a]) = display_p3_linear(&text[at..=end]) {
187 let [x, y, z] = mul(&P3_TO_XYZ, [r, g, b].map(f64::from));
188 out.push_str(&text[copied..at]);
189 out.push_str(&format!("color(xyz-d65 {x} {y} {z} / {a})"));
190 copied = end + 1;
191 }
192 from = end + 1;
193 }
194 if copied == 0 {
195 return None;
196 }
197 out.push_str(&text[copied..]);
198 Some(out)
199}
200
201fn closing(bytes: &[u8], from: usize) -> Option<usize> {
203 let mut depth = 1;
204 for (i, &b) in bytes.iter().enumerate().skip(from) {
205 match b {
206 b'(' => depth += 1,
207 b')' => {
208 depth -= 1;
209 if depth == 0 {
210 return Some(i);
211 }
212 }
213 _ => {}
214 }
215 }
216 None
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use crate::{parse_color, parse_color_in};
223
224 fn close(a: &[f32], b: &[f32]) -> bool {
225 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4)
226 }
227
228 #[test]
229 fn display_p3_linear_parses_exactly_with_alpha_percentages_and_none() {
230 assert_eq!(
231 display_p3_linear("color(display-p3-linear 2 0.5 0 / 0.25)"),
232 Some([2.0, 0.5, 0.0, 0.25])
233 );
234 assert_eq!(
235 display_p3_linear(" COLOR( Display-P3-Linear 50% none 1) "),
236 Some([0.5, 0.0, 1.0, 1.0])
237 );
238 assert_eq!(display_p3_linear("color(display-p3 1 0 0)"), None);
239 assert_eq!(display_p3_linear("color(display-p3-linearx 1 0 0)"), None);
240 assert_eq!(display_p3_linear("color(display-p3-linear 1 0)"), None);
241 }
242
243 #[test]
244 fn colors_read_into_each_space_unclipped() {
245 let red = parse_color_in("color(display-p3 1 0 0)", RgbSpace::Srgb).unwrap();
246 assert!(
247 red[0] > 1.0 && red[1] < 0.0,
248 "P3 red is outside sRGB: {red:?}"
249 );
250 let back = parse_color_in("red", RgbSpace::DisplayP3).unwrap();
251 assert!(
252 close(&back, &[0.917_488, 0.200_287, 0.138_561, 1.0]),
253 "{back:?}"
254 );
255 assert_eq!(
256 parse_color_in("color(srgb-linear 4 2 0.5 / 0.5)", RgbSpace::SrgbLinear),
257 Some([4.0, 2.0, 0.5, 0.5])
258 );
259 let lin = parse_color_in("#808080", RgbSpace::SrgbLinear).unwrap();
260 assert!(
261 close(&lin, &[0.215_861, 0.215_861, 0.215_861, 1.0]),
262 "{lin:?}"
263 );
264 assert_eq!(
265 parse_color_in("color(display-p3-linear 2 0 0)", RgbSpace::DisplayP3Linear),
266 Some([2.0, 0.0, 0.0, 1.0])
267 );
268 let p3 = parse_color_in("color(display-p3-linear 1 1 1)", RgbSpace::Srgb).unwrap();
269 assert!(close(&p3, &[1.0, 1.0, 1.0, 1.0]), "{p3:?}");
270 assert_eq!(parse_color_in("currentcolor", RgbSpace::DisplayP3), None);
271 assert_eq!(
272 parse_color("color(srgb-linear 4 0 0)"),
273 Some([1.0, 0.0, 0.0, 1.0]),
274 "painting clips"
275 );
276 }
277
278 #[test]
279 fn conversions_round_trip_through_every_space() {
280 let rgb = [0.9, 0.3, 0.05];
281 for (a, b) in [
282 (RgbSpace::Srgb, RgbSpace::DisplayP3),
283 (RgbSpace::Srgb, RgbSpace::DisplayP3Linear),
284 (RgbSpace::DisplayP3, RgbSpace::SrgbLinear),
285 (RgbSpace::SrgbLinear, RgbSpace::Srgb),
286 ] {
287 let there = convert_rgb(rgb, a, b);
288 assert!(close(&convert_rgb(there, b, a), &rgb), "{a:?} -> {b:?}");
289 }
290 assert!(close(
291 &convert_rgb([2.0, 0.0, 0.0], RgbSpace::SrgbLinear, RgbSpace::Srgb),
292 &[from_linear(2.0), 0.0, 0.0]
293 ));
294 }
295
296 #[test]
297 fn declarations_get_display_p3_linear_as_xyz() {
298 let out =
299 rewrite("background: color(display-p3-linear 1 0 0 / 0.5); color: color(srgb 1 0 0)")
300 .unwrap();
301 assert!(
302 out.starts_with("background: color(xyz-d65 0.48657"),
303 "{out}"
304 );
305 assert!(out.ends_with(" / 0.5); color: color(srgb 1 0 0)"), "{out}");
306 let back = parse_color_in(
307 &out["background: ".len()..out.find(';').unwrap()],
308 RgbSpace::DisplayP3Linear,
309 )
310 .unwrap();
311 assert!(close(&back, &[1.0, 0.0, 0.0, 0.5]), "{back:?}");
312 assert_eq!(rewrite("color: color(display-p3 1 0 0)"), None);
313 assert_eq!(rewrite("--x: color(display-p3-linear 1 0"), None);
314 }
315}