1use crate::{Color, Theme};
12use std::collections::HashMap;
13use std::f64::consts::PI;
14use std::sync::OnceLock;
15
16pub const GOOGLE_BLUE: Color = Color(0x1b, 0x6e, 0xf3, 255);
18const MIN_CHROMA: f64 = 5.0;
19const ACCENT1_CHROMA: f64 = 48.0;
20const MIDDLE_LSTAR: f64 = 49.6;
21const MAX_EXTRACTION_AREA: f64 = 112.0 * 112.0;
22
23pub const BASIC_COLOR_SEEDS: [(&str, Color); 16] = [
25 ("Google Blue", Color(0x1b, 0x6e, 0xf3, 255)),
26 ("Sky Blue", Color(0x00, 0x67, 0x83, 255)),
27 ("Ocean Teal", Color(0x00, 0x6a, 0x6a, 255)),
28 ("Mint Green", Color(0x14, 0x6c, 0x2e, 255)),
29 ("Sage Green", Color(0x38, 0x6a, 0x20, 255)),
30 ("Lime Olive", Color(0x5b, 0x63, 0x00, 255)),
31 ("Amber Gold", Color(0x78, 0x59, 0x00, 255)),
32 ("Warm Terracotta", Color(0x98, 0x47, 0x16, 255)),
33 ("Coral Red", Color(0xb3, 0x26, 0x1e, 255)),
34 ("Rose Pink", Color(0x98, 0x40, 0x61, 255)),
35 ("Orchid Magenta", Color(0x8e, 0x43, 0x7f, 255)),
36 ("Berry Plum", Color(0x7b, 0x49, 0x97, 255)),
37 ("Lavender Purple", Color(0x67, 0x50, 0xa4, 255)),
38 ("Deep Indigo", Color(0x43, 0x55, 0xb9, 255)),
39 ("Periwinkle", Color(0x3a, 0x60, 0x8f, 255)),
40 ("Cool Slate", Color(0x4d, 0x61, 0x6c, 255)),
41];
42
43const WHITE_POINT_D65: [f64; 3] = [95.047, 100.0, 108.883];
48
49const XYZ_TO_CAM16RGB: [[f64; 3]; 3] = [
50 [0.401288, 0.650173, -0.051461],
51 [-0.250268, 1.204414, 0.045854],
52 [-0.002079, 0.048952, 0.953127],
53];
54
55const SCALED_DISCOUNT_FROM_LINRGB: [[f64; 3]; 3] = [
56 [0.001200833568784504, 0.002389694492170889, 0.0002795742885861124],
57 [0.0005891086651375999, 0.0029785502573438758, 0.0003270666104008398],
58 [0.00010146692491640572, 0.0005364214359186694, 0.0032979401770712076],
59];
60
61const LINRGB_FROM_SCALED_DISCOUNT: [[f64; 3]; 3] = [
62 [1373.2198709594231, -1100.4251190754821, -7.278681089101213],
63 [-271.815969077903, 559.6580465940733, -32.46047482791194],
64 [1.9622899599665666, -57.173814538844006, 308.7233197812385],
65];
66
67const Y_FROM_LINRGB: [f64; 3] = [0.2126, 0.7152, 0.0722];
68
69#[derive(Clone, Copy, Debug)]
70struct ViewingConditions {
71 aw: f64,
72 nbb: f64,
73 ncb: f64,
74 c: f64,
75 nc: f64,
76 n: f64,
77 rgb_d: [f64; 3],
78 fl: f64,
79 z: f64,
80}
81
82fn default_viewing_conditions() -> &'static ViewingConditions {
83 static DEFAULT: OnceLock<ViewingConditions> = OnceLock::new();
84 DEFAULT.get_or_init(|| {
85 let wp = WHITE_POINT_D65;
86 let adapting_luminance = (200.0 / PI) * y_from_lstar(50.0) / 100.0;
87 let background_lstar = 50.0;
88 let surround = 2.0;
89
90 let rw = wp[0] * XYZ_TO_CAM16RGB[0][0] + wp[1] * XYZ_TO_CAM16RGB[0][1] + wp[2] * XYZ_TO_CAM16RGB[0][2];
91 let gw = wp[0] * XYZ_TO_CAM16RGB[1][0] + wp[1] * XYZ_TO_CAM16RGB[1][1] + wp[2] * XYZ_TO_CAM16RGB[1][2];
92 let bw = wp[0] * XYZ_TO_CAM16RGB[2][0] + wp[1] * XYZ_TO_CAM16RGB[2][1] + wp[2] * XYZ_TO_CAM16RGB[2][2];
93
94 let f = 0.8 + surround / 10.0;
95 let c = 0.59 + (0.69 - 0.59) * ((f - 0.9) * 10.0);
96 let d = (f * (1.0 - (1.0 / 3.6) * ((-adapting_luminance - 42.0) / 92.0).exp())).clamp(0.0, 1.0);
97 let nc = f;
98 let rgb_d = [
99 d * (100.0 / rw) + 1.0 - d,
100 d * (100.0 / gw) + 1.0 - d,
101 d * (100.0 / bw) + 1.0 - d,
102 ];
103 let k = 1.0 / (5.0 * adapting_luminance + 1.0);
104 let k4 = k * k * k * k;
105 let k4f = 1.0 - k4;
106 let fl = k4 * adapting_luminance + 0.1 * k4f * k4f * (5.0 * adapting_luminance).cbrt();
107 let n = y_from_lstar(background_lstar) / wp[1];
108 let z = 1.48 + n.sqrt();
109 let nbb = 0.725 / n.powf(0.2);
110 let ncb = nbb;
111 let raf = [
112 (fl * rgb_d[0] * rw / 100.0).powf(0.42),
113 (fl * rgb_d[1] * gw / 100.0).powf(0.42),
114 (fl * rgb_d[2] * bw / 100.0).powf(0.42),
115 ];
116 let ra = [
117 400.0 * raf[0] / (raf[0] + 27.13),
118 400.0 * raf[1] / (raf[1] + 27.13),
119 400.0 * raf[2] / (raf[2] + 27.13),
120 ];
121 let aw = (2.0 * ra[0] + ra[1] + 0.05 * ra[2]) * nbb;
122 ViewingConditions {
123 aw,
124 nbb,
125 ncb,
126 c,
127 nc,
128 n,
129 rgb_d,
130 fl,
131 z,
132 }
133 })
134}
135
136#[inline]
137fn linearized_f64(channel: f64) -> f64 {
138 let normalized = channel / 255.0;
139 if normalized <= 0.040449936 {
140 normalized / 12.92 * 100.0
141 } else {
142 ((normalized + 0.055) / 1.055).powf(2.4) * 100.0
143 }
144}
145
146#[inline]
147fn linearized(channel: u8) -> f64 {
148 linearized_f64(channel as f64)
149}
150
151#[inline]
152fn true_delinearized(rgb_component: f64) -> f64 {
153 let normalized = rgb_component / 100.0;
154 let d = if normalized <= 0.0031308 {
155 normalized * 12.92
156 } else {
157 1.055 * normalized.powf(1.0 / 2.4) - 0.055
158 };
159 d * 255.0
160}
161
162#[inline]
163fn delinearized(rgb_component: f64) -> u8 {
164 true_delinearized(rgb_component).round().clamp(0.0, 255.0) as u8
165}
166
167#[inline]
168fn lab_f(t: f64) -> f64 {
169 const E: f64 = 216.0 / 24389.0;
170 const KAPPA: f64 = 24389.0 / 27.0;
171 if t > E {
172 t.cbrt()
173 } else {
174 (KAPPA * t + 16.0) / 116.0
175 }
176}
177
178#[inline]
179fn lab_invf(ft: f64) -> f64 {
180 const E: f64 = 216.0 / 24389.0;
181 const KAPPA: f64 = 24389.0 / 27.0;
182 let ft3 = ft * ft * ft;
183 if ft3 > E {
184 ft3
185 } else {
186 (116.0 * ft - 16.0) / KAPPA
187 }
188}
189
190pub fn y_from_lstar(lstar: f64) -> f64 {
192 100.0 * lab_invf((lstar + 16.0) / 116.0)
193}
194
195pub fn lstar_from_rgb(color: Color) -> f64 {
197 let rl = linearized(color.0);
198 let gl = linearized(color.1);
199 let bl = linearized(color.2);
200 let y = 0.2126 * rl + 0.7152 * gl + 0.0722 * bl;
201 116.0 * lab_f(y / 100.0) - 16.0
202}
203
204#[inline]
205fn color_from_lstar(lstar: f64) -> Color {
206 let y = y_from_lstar(lstar.clamp(0.0, 100.0));
207 let c = delinearized(y);
208 Color(c, c, c, 255)
209}
210
211#[inline]
212fn color_from_linrgb(linrgb: [f64; 3]) -> Color {
213 Color(
214 delinearized(linrgb[0]),
215 delinearized(linrgb[1]),
216 delinearized(linrgb[2]),
217 255,
218 )
219}
220
221pub fn hct_from_rgb(color: Color) -> (f64, f64, f64) {
223 let vc = default_viewing_conditions();
224 let rl = linearized(color.0);
225 let gl = linearized(color.1);
226 let bl = linearized(color.2);
227
228 let x = 0.41233895 * rl + 0.35762064 * gl + 0.18051042 * bl;
229 let y = 0.2126 * rl + 0.7152 * gl + 0.0722 * bl;
230 let z = 0.01932141 * rl + 0.11916382 * gl + 0.95034478 * bl;
231
232 let rt = x * XYZ_TO_CAM16RGB[0][0] + y * XYZ_TO_CAM16RGB[0][1] + z * XYZ_TO_CAM16RGB[0][2];
233 let gt = x * XYZ_TO_CAM16RGB[1][0] + y * XYZ_TO_CAM16RGB[1][1] + z * XYZ_TO_CAM16RGB[1][2];
234 let bt = x * XYZ_TO_CAM16RGB[2][0] + y * XYZ_TO_CAM16RGB[2][1] + z * XYZ_TO_CAM16RGB[2][2];
235
236 let rd = vc.rgb_d[0] * rt;
237 let gd = vc.rgb_d[1] * gt;
238 let bd = vc.rgb_d[2] * bt;
239
240 let raf = (vc.fl * rd.abs() / 100.0).powf(0.42);
241 let gaf = (vc.fl * gd.abs() / 100.0).powf(0.42);
242 let baf = (vc.fl * bd.abs() / 100.0).powf(0.42);
243 let ra = signum_zero(rd) * 400.0 * raf / (raf + 27.13);
244 let ga = signum_zero(gd) * 400.0 * gaf / (gaf + 27.13);
245 let ba = signum_zero(bd) * 400.0 * baf / (baf + 27.13);
246
247 let a = (11.0 * ra - 12.0 * ga + ba) / 11.0;
248 let b = (ra + ga - 2.0 * ba) / 9.0;
249 let u = (20.0 * ra + 20.0 * ga + 21.0 * ba) / 20.0;
250 let p2 = (40.0 * ra + 20.0 * ga + ba) / 20.0;
251
252 let atan_deg = b.atan2(a).to_degrees();
253 let hue = wrap_degrees(atan_deg);
254
255 let ac = p2 * vc.nbb;
256 let j = if ac <= 0.0 {
257 0.0
258 } else {
259 100.0 * (ac / vc.aw).powf(vc.c * vc.z)
260 };
261 let hue_prime = if hue < 20.14 { hue + 360.0 } else { hue };
262 let e_hue = 0.25 * ((hue_prime.to_radians() + 2.0).cos() + 3.8);
263 let p1 = (50000.0 / 13.0) * e_hue * vc.nc * vc.ncb;
264 let t = p1 * a.hypot(b) / (u + 0.305);
265 let alpha = (1.64 - 0.29_f64.powf(vc.n)).powf(0.73) * t.powf(0.9);
266 let chroma = alpha * (j / 100.0).sqrt();
267 let tone = 116.0 * lab_f(y / 100.0) - 16.0;
268 (hue, chroma, tone)
269}
270
271#[inline]
272fn signum_zero(x: f64) -> f64 {
273 if x < 0.0 {
274 -1.0
275 } else if x > 0.0 {
276 1.0
277 } else {
278 0.0
279 }
280}
281
282#[inline]
283fn mat_mul(v: [f64; 3], m: [[f64; 3]; 3]) -> [f64; 3] {
284 [
285 v[0] * m[0][0] + v[1] * m[0][1] + v[2] * m[0][2],
286 v[0] * m[1][0] + v[1] * m[1][1] + v[2] * m[1][2],
287 v[0] * m[2][0] + v[1] * m[2][1] + v[2] * m[2][2],
288 ]
289}
290
291#[inline]
292fn sanitize_radians(angle: f64) -> f64 {
293 (angle + PI * 8.0).rem_euclid(PI * 2.0)
294}
295
296#[inline]
297fn are_in_cyclic_order(a: f64, b: f64, c: f64) -> bool {
298 sanitize_radians(b - a) < sanitize_radians(c - a)
299}
300
301#[inline]
302fn chromatic_adaptation(component: f64) -> f64 {
303 let af = component.abs().powf(0.42);
304 signum_zero(component) * 400.0 * af / (af + 27.13)
305}
306
307#[inline]
308fn inverse_chromatic_adaptation(adapted: f64) -> f64 {
309 let abs = adapted.abs();
310 let base = (27.13 * abs / (400.0 - abs).max(1e-12)).max(0.0);
311 signum_zero(adapted) * base.powf(1.0 / 0.42)
312}
313
314fn hue_of_linrgb(linrgb: [f64; 3]) -> f64 {
315 let scaled = mat_mul(linrgb, SCALED_DISCOUNT_FROM_LINRGB);
316 let ra = chromatic_adaptation(scaled[0]);
317 let ga = chromatic_adaptation(scaled[1]);
318 let ba = chromatic_adaptation(scaled[2]);
319 let a = (11.0 * ra - 12.0 * ga + ba) / 11.0;
320 let b = (ra + ga - 2.0 * ba) / 9.0;
321 b.atan2(a)
322}
323
324fn nth_vertex(y: f64, n: usize) -> Option<[f64; 3]> {
325 let [kr, kg, kb] = Y_FROM_LINRGB;
326 let coord_a = if n % 4 <= 1 { 0.0 } else { 100.0 };
327 let coord_b = if n.is_multiple_of(2) { 0.0 } else { 100.0 };
328 let (r, g, b) = if n < 4 {
329 let (g, b) = (coord_a, coord_b);
330 ((y - g * kg - b * kb) / kr, g, b)
331 } else if n < 8 {
332 let (b, r) = (coord_a, coord_b);
333 (r, (y - r * kr - b * kb) / kg, b)
334 } else {
335 let (r, g) = (coord_a, coord_b);
336 (r, g, (y - r * kr - g * kg) / kb)
337 };
338 if (0.0..=100.0).contains(&r) && (0.0..=100.0).contains(&g) && (0.0..=100.0).contains(&b) {
339 Some([r, g, b])
340 } else {
341 None
342 }
343}
344
345fn bisect_to_segment(y: f64, target_hue: f64) -> ([f64; 3], [f64; 3]) {
346 let mut left = [-1.0; 3];
347 let mut right = [-1.0; 3];
348 let mut left_hue = 0.0;
349 let mut right_hue = 0.0;
350 let mut initialized = false;
351 let mut uncut = true;
352 for n in 0..12 {
353 let Some(mid) = nth_vertex(y, n) else {
354 continue;
355 };
356 let mid_hue = hue_of_linrgb(mid);
357 if !initialized {
358 left = mid;
359 right = mid;
360 left_hue = mid_hue;
361 right_hue = mid_hue;
362 initialized = true;
363 continue;
364 }
365 if uncut || are_in_cyclic_order(left_hue, mid_hue, right_hue) {
366 uncut = false;
367 if are_in_cyclic_order(left_hue, target_hue, mid_hue) {
368 right = mid;
369 right_hue = mid_hue;
370 } else {
371 left = mid;
372 left_hue = mid_hue;
373 }
374 }
375 }
376 (left, right)
377}
378
379fn set_coordinate(source: [f64; 3], coordinate: f64, target: [f64; 3], axis: usize) -> [f64; 3] {
380 let t = (coordinate - source[axis]) / (target[axis] - source[axis]);
381 [
382 source[0] + (target[0] - source[0]) * t,
383 source[1] + (target[1] - source[1]) * t,
384 source[2] + (target[2] - source[2]) * t,
385 ]
386}
387
388fn bisect_to_limit(y: f64, target_hue: f64) -> [f64; 3] {
389 let (mut left, mut right) = bisect_to_segment(y, target_hue);
390 let mut left_hue = hue_of_linrgb(left);
391 for axis in 0..3 {
392 if left[axis] != right[axis] {
393 let (mut l_plane, mut r_plane) = if left[axis] < right[axis] {
394 (
395 (true_delinearized(left[axis]) - 0.5).floor() as i32,
396 (true_delinearized(right[axis]) - 0.5).ceil() as i32,
397 )
398 } else {
399 (
400 (true_delinearized(left[axis]) - 0.5).ceil() as i32,
401 (true_delinearized(right[axis]) - 0.5).floor() as i32,
402 )
403 };
404 for _ in 0..8 {
405 if (r_plane - l_plane).abs() <= 1 {
406 break;
407 }
408 let m_plane = ((l_plane + r_plane) as f64 / 2.0).floor() as i32;
409 let mid_coord = linearized_f64(m_plane as f64 + 0.5);
410 let mid = set_coordinate(left, mid_coord, right, axis);
411 let mid_hue = hue_of_linrgb(mid);
412 if are_in_cyclic_order(left_hue, target_hue, mid_hue) {
413 right = mid;
414 r_plane = m_plane;
415 } else {
416 left = mid;
417 left_hue = mid_hue;
418 l_plane = m_plane;
419 }
420 }
421 }
422 }
423 [
424 (left[0] + right[0]) * 0.5,
425 (left[1] + right[1]) * 0.5,
426 (left[2] + right[2]) * 0.5,
427 ]
428}
429
430fn find_result_by_j(hue_rad: f64, chroma: f64, y: f64) -> Option<Color> {
431 let vc = default_viewing_conditions();
432 let mut j = y.sqrt() * 11.0;
433 let t_inner_coeff = 1.0 / (1.64 - 0.29_f64.powf(vc.n)).powf(0.73);
434 let e_hue = 0.25 * ((hue_rad + 2.0).cos() + 3.8);
435 let p1 = e_hue * (50000.0 / 13.0) * vc.nc * vc.ncb;
436 let h_sin = hue_rad.sin();
437 let h_cos = hue_rad.cos();
438
439 for round in 0..5 {
440 let j_norm = j / 100.0;
441 let alpha = if chroma == 0.0 || j <= 0.0 {
442 0.0
443 } else {
444 chroma / j_norm.sqrt()
445 };
446 let t = (alpha * t_inner_coeff).powf(1.0 / 0.9);
447 let ac = vc.aw * j_norm.powf(1.0 / vc.c / vc.z);
448 let p2 = ac / vc.nbb;
449 let gamma = 23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11.0 * t * h_cos + 108.0 * t * h_sin);
450 let a = gamma * h_cos;
451 let b = gamma * h_sin;
452 let ra = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0;
453 let ga = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0;
454 let ba = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0;
455 let linrgb = mat_mul(
456 [
457 inverse_chromatic_adaptation(ra),
458 inverse_chromatic_adaptation(ga),
459 inverse_chromatic_adaptation(ba),
460 ],
461 LINRGB_FROM_SCALED_DISCOUNT,
462 );
463 if linrgb[0] < 0.0 || linrgb[1] < 0.0 || linrgb[2] < 0.0 {
464 return None;
465 }
466 let fnj = Y_FROM_LINRGB[0] * linrgb[0]
467 + Y_FROM_LINRGB[1] * linrgb[1]
468 + Y_FROM_LINRGB[2] * linrgb[2];
469 if fnj <= 0.0 {
470 return None;
471 }
472 if round == 4 || (fnj - y).abs() < 0.002 {
473 if linrgb[0] > 100.01 || linrgb[1] > 100.01 || linrgb[2] > 100.01 {
474 return None;
475 }
476 return Some(color_from_linrgb(linrgb));
477 }
478 j -= (fnj - y) * j / (2.0 * fnj);
479 }
480 None
481}
482
483pub fn rgb_from_hct(hue: f64, chroma: f64, tone: f64) -> Color {
486 let tone = if tone.is_finite() {
487 tone.clamp(0.0, 100.0)
488 } else {
489 50.0
490 };
491 let chroma = if chroma.is_finite() {
492 chroma.max(0.0)
493 } else {
494 0.0
495 };
496 if chroma < 0.0001 || tone < 0.0001 || tone > 99.9999 {
497 return color_from_lstar(tone);
498 }
499 let hue_deg = wrap_degrees(if hue.is_finite() { hue } else { 0.0 });
500 let hue_rad = hue_deg.to_radians();
501 let y = y_from_lstar(tone);
502 if let Some(exact) = find_result_by_j(hue_rad, chroma, y) {
503 return exact;
504 }
505 let linrgb = bisect_to_limit(y, hue_rad);
506 if linrgb[0] < 0.0 {
507 color_from_lstar(tone)
508 } else {
509 color_from_linrgb(linrgb)
510 }
511}
512
513#[inline]
514fn wrap_degrees(deg: f64) -> f64 {
515 let r = deg.rem_euclid(360.0);
516 if r >= 360.0 { 0.0 } else { r }
517}
518
519#[inline]
520fn wrap_degrees_i32(deg: i32) -> usize {
521 deg.rem_euclid(360) as usize
522}
523
524#[inline]
525fn hue_diff(a: f64, b: f64) -> f64 {
526 180.0 - ((a - b).abs() - 180.0).abs()
527}
528
529#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
535pub enum MonetStyle {
536 #[default]
537 TonalSpot,
538 Spritz,
539 Vibrant,
540 Expressive,
541 Rainbow,
542 FruitSalad,
543 Content,
544}
545
546#[derive(Clone, Copy)]
547enum HueSpec {
548 Source,
549 Add(f64),
550 Subtract(f64),
551 Table(&'static [(i32, i32)]),
552}
553
554#[derive(Clone, Copy)]
555enum ChromaSpec {
556 Constant(f64),
557 MaxOut,
558 Source,
559 Multiple(f64),
560}
561
562const VIBRANT_SECONDARY_ROTATIONS: &[(i32, i32)] = &[
563 (0, 18), (41, 15), (61, 10), (101, 12), (131, 15), (181, 18), (251, 15), (301, 12), (360, 12),
564];
565const VIBRANT_TERTIARY_ROTATIONS: &[(i32, i32)] = &[
566 (0, 35), (41, 30), (61, 20), (101, 25), (131, 30), (181, 35), (251, 30), (301, 25), (360, 25),
567];
568const EXPRESSIVE_SECONDARY_ROTATIONS: &[(i32, i32)] = &[
569 (0, 45), (21, 95), (51, 45), (121, 20), (151, 45), (191, 90), (271, 45), (321, 45), (360, 45),
570];
571const EXPRESSIVE_TERTIARY_ROTATIONS: &[(i32, i32)] = &[
572 (0, 120), (21, 120), (51, 20), (121, 45), (151, 20), (191, 15), (271, 20), (321, 120), (360, 120),
573];
574
575impl HueSpec {
576 fn resolve(self, source_hue: f64) -> f64 {
577 match self {
578 Self::Source => wrap_degrees(source_hue),
579 Self::Add(delta) => wrap_degrees(source_hue + delta),
580 Self::Subtract(delta) => wrap_degrees(source_hue - delta),
581 Self::Table(table) => {
582 let sanitized = if !(0.0..360.0).contains(&source_hue) {
583 0.0
584 } else {
585 source_hue
586 };
587 for w in table.windows(2) {
588 let lo = w[0].0 as f64;
589 let hi = w[1].0 as f64;
590 if lo <= sanitized && sanitized < hi {
591 return wrap_degrees(sanitized + w[0].1 as f64);
592 }
593 }
594 wrap_degrees(source_hue)
595 }
596 }
597 }
598}
599
600impl ChromaSpec {
601 fn resolve(self, source_chroma: f64) -> f64 {
602 match self {
603 Self::Constant(c) => c,
604 Self::MaxOut => 130.0,
605 Self::Source => source_chroma,
606 Self::Multiple(m) => source_chroma * m,
607 }
608 }
609}
610
611impl MonetStyle {
612 fn core_specs(self) -> [(HueSpec, ChromaSpec); 5] {
613 use ChromaSpec as C;
614 use HueSpec as H;
615 match self {
616 Self::Spritz => [
617 (H::Source, C::Constant(12.0)),
618 (H::Source, C::Constant(8.0)),
619 (H::Source, C::Constant(16.0)),
620 (H::Source, C::Constant(2.0)),
621 (H::Source, C::Constant(2.0)),
622 ],
623 Self::TonalSpot => [
624 (H::Source, C::Constant(36.0)),
625 (H::Source, C::Constant(16.0)),
626 (H::Add(60.0), C::Constant(24.0)),
627 (H::Source, C::Constant(4.0)),
628 (H::Source, C::Constant(8.0)),
629 ],
630 Self::Vibrant => [
631 (H::Source, C::MaxOut),
632 (H::Table(VIBRANT_SECONDARY_ROTATIONS), C::Constant(24.0)),
633 (H::Table(VIBRANT_TERTIARY_ROTATIONS), C::Constant(32.0)),
634 (H::Source, C::Constant(10.0)),
635 (H::Source, C::Constant(12.0)),
636 ],
637 Self::Expressive => [
638 (H::Add(240.0), C::Constant(40.0)),
639 (H::Table(EXPRESSIVE_SECONDARY_ROTATIONS), C::Constant(24.0)),
640 (H::Table(EXPRESSIVE_TERTIARY_ROTATIONS), C::Constant(32.0)),
641 (H::Add(15.0), C::Constant(8.0)),
642 (H::Add(15.0), C::Constant(12.0)),
643 ],
644 Self::Rainbow => [
645 (H::Source, C::Constant(48.0)),
646 (H::Source, C::Constant(16.0)),
647 (H::Add(60.0), C::Constant(24.0)),
648 (H::Source, C::Constant(0.0)),
649 (H::Source, C::Constant(0.0)),
650 ],
651 Self::FruitSalad => [
652 (H::Subtract(50.0), C::Constant(48.0)),
653 (H::Subtract(50.0), C::Constant(36.0)),
654 (H::Source, C::Constant(36.0)),
655 (H::Source, C::Constant(10.0)),
656 (H::Source, C::Constant(16.0)),
657 ],
658 Self::Content => [
659 (H::Source, C::Source),
660 (H::Source, C::Multiple(0.33)),
661 (H::Source, C::Multiple(0.66)),
662 (H::Source, C::Multiple(0.0833)),
663 (H::Source, C::Multiple(0.1666)),
664 ],
665 }
666 }
667}
668
669#[derive(Clone, Copy, Debug, PartialEq)]
672pub struct TonalPalette {
673 hue: f64,
674 chroma: f64,
675 shades: [Color; 13],
676}
677
678impl TonalPalette {
679 pub const TONES: [u8; 13] = [100, 99, 95, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0];
681
682 pub fn new(hue: f64, chroma: f64) -> Self {
683 let hue = wrap_degrees(hue);
684 let chroma = chroma.max(0.0);
685 let shades = std::array::from_fn(|idx| {
686 let t = Self::TONES[idx];
687 Self::compute_tone(hue, chroma, t)
688 });
689 Self {
690 hue,
691 chroma,
692 shades,
693 }
694 }
695
696 fn compute_tone(hue: f64, chroma: f64, t: u8) -> Color {
697 match t {
698 100 => Color(255, 255, 255, 255),
699 0 => Color(0, 0, 0, 255),
700 99 | 95 => rgb_from_hct(hue, chroma.min(40.0), t as f64),
701 50 => rgb_from_hct(hue, chroma, MIDDLE_LSTAR),
702 other => {
703 let capped = if other >= 95 { chroma.min(40.0) } else { chroma };
704 rgb_from_hct(hue, capped, other.min(100) as f64)
705 }
706 }
707 }
708
709 pub fn tone(&self, t: u8) -> Color {
712 match t {
713 100 => self.shades[0],
714 99 => self.shades[1],
715 95 => self.shades[2],
716 90 => self.shades[3],
717 80 => self.shades[4],
718 70 => self.shades[5],
719 60 => self.shades[6],
720 50 => self.shades[7],
721 40 => self.shades[8],
722 30 => self.shades[9],
723 20 => self.shades[10],
724 10 => self.shades[11],
725 0 => self.shades[12],
726 other => Self::compute_tone(self.hue, self.chroma, other),
727 }
728 }
729
730 pub fn shades(&self) -> &[Color; 13] {
732 &self.shades
733 }
734
735 pub fn hue(&self) -> f64 {
736 self.hue
737 }
738
739 pub fn chroma(&self) -> f64 {
740 self.chroma
741 }
742}
743
744#[derive(Clone, Debug, PartialEq, Eq)]
746pub struct WallpaperColors {
747 pub primary: Color,
748 pub secondary: Option<Color>,
749 pub tertiary: Option<Color>,
750 pub seeds: Vec<Color>,
751 pub supports_dark_text: bool,
752 pub supports_dark_theme: bool,
753}
754
755impl WallpaperColors {
756 pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Self {
760 let Some(expected_len) = (width as usize)
761 .checked_mul(height as usize)
762 .and_then(|px| px.checked_mul(4))
763 else {
764 return Self::fallback();
765 };
766 if width == 0 || height == 0 || rgba.len() < expected_len {
767 return Self::fallback();
768 }
769
770 let w = width as usize;
771 let h = height as usize;
772 let area = (w as f64) * (h as f64);
773 let scale = if area > MAX_EXTRACTION_AREA {
774 (MAX_EXTRACTION_AREA / area).sqrt()
775 } else {
776 1.0
777 };
778 let sw = ((w as f64 * scale).round() as usize).clamp(1, w);
779 let sh = ((h as f64 * scale).round() as usize).clamp(1, h);
780
781 let mut buckets: HashMap<u16, (u32, u64, u64, u64)> = HashMap::with_capacity(256);
783 let mut total_luminance = 0.0_f64;
784 let mut dark_pixels = 0usize;
785 let total_samples = sw * sh;
786 let mut opaque_samples = 0u32;
787
788 for sy in 0..sh {
789 let y = (sy * h) / sh;
790 let row_base = y * w;
791 for sx in 0..sw {
792 let x = (sx * w) / sw;
793 let idx = (row_base + x) * 4;
794 let r = rgba[idx];
795 let g = rgba[idx + 1];
796 let b = rgba[idx + 2];
797 let a = rgba[idx + 3];
798
799 let lum = (0.2126 * linearized(r) + 0.7152 * linearized(g) + 0.0722 * linearized(b))
800 / 100.0;
801 total_luminance += lum;
802 let contrast_black = (lum + 0.05) / 0.05;
803 if contrast_black <= 5.5 && a != 0 {
804 dark_pixels += 1;
805 }
806
807 if a > 0 {
808 opaque_samples += 1;
809 let key = (((r as u16) >> 3) << 10)
810 | (((g as u16) >> 3) << 5)
811 | ((b as u16) >> 3);
812 let entry = buckets.entry(key).or_insert((0, 0, 0, 0));
813 entry.0 += 1;
814 entry.1 += r as u64;
815 entry.2 += g as u64;
816 entry.3 += b as u64;
817 }
818 }
819 }
820
821 let mean_luminance = total_luminance / total_samples.max(1) as f64;
822 let max_dark_pixels = (total_samples as f64 * 0.05) as usize;
823 let supports_dark_text = mean_luminance > 0.7 && dark_pixels < max_dark_pixels;
824 let supports_dark_theme = mean_luminance < 0.3;
825
826 if opaque_samples == 0 || buckets.is_empty() {
827 return Self {
828 primary: GOOGLE_BLUE,
829 secondary: None,
830 tertiary: None,
831 seeds: vec![GOOGLE_BLUE],
832 supports_dark_text,
833 supports_dark_theme,
834 };
835 }
836
837 let mut clusters: Vec<(Color, u32)> = buckets
839 .into_values()
840 .map(|(count, sr, sg, sb)| {
841 let c = count as u64;
842 (
843 Color(
844 ((sr + c / 2) / c) as u8,
845 ((sg + c / 2) / c) as u8,
846 ((sb + c / 2) / c) as u8,
847 255,
848 ),
849 count,
850 )
851 })
852 .collect();
853 clusters.sort_by(|a, b| {
854 b.1.cmp(&a.1)
855 .then_with(|| (a.0.0, a.0.1, a.0.2).cmp(&(b.0.0, b.0.1, b.0.2)))
856 });
857 clusters.truncate(256);
858
859 let total_pop: f64 = clusters.iter().map(|(_, p)| *p as f64).sum();
860 struct Entry {
861 color: Color,
862 proportion: f64,
863 hue: f64,
864 chroma: f64,
865 }
866 let entries: Vec<Entry> = clusters
867 .into_iter()
868 .map(|(color, pop)| {
869 let (hue, chroma, _) = hct_from_rgb(color);
870 Entry {
871 color,
872 proportion: pop as f64 / total_pop,
873 hue,
874 chroma,
875 }
876 })
877 .collect();
878
879 let mut filtered_hue_pop = [0.0_f64; 360];
881 let mut all_hue_pop = [0.0_f64; 360];
882 for e in &entries {
883 let h_bin = wrap_degrees_i32(e.hue.round() as i32);
884 all_hue_pop[h_bin] += e.proportion;
885 if e.chroma > MIN_CHROMA {
886 filtered_hue_pop[h_bin] += e.proportion;
887 }
888 }
889
890 let window_sum = |table: &[f64; 360], hue: f64| -> f64 {
891 let center = hue.round() as i32;
892 let mut sum = 0.0;
893 for deg in (center - 15)..=(center + 15) {
894 sum += table[wrap_degrees_i32(deg)];
895 }
896 sum
897 };
898
899 let mut scored_seeds: Vec<(usize, f64)> = Vec::new();
901 for (idx, e) in entries.iter().enumerate() {
902 let hue_prop = window_sum(&filtered_hue_pop, e.hue);
903 if e.chroma >= MIN_CHROMA && hue_prop > 0.01 {
904 let proportion_score = 0.7 * 100.0 * hue_prop;
905 let chroma_score = if e.chroma < ACCENT1_CHROMA {
906 0.1 * (e.chroma - ACCENT1_CHROMA)
907 } else {
908 0.3 * (e.chroma - ACCENT1_CHROMA)
909 };
910 scored_seeds.push((idx, proportion_score + chroma_score));
911 }
912 }
913 scored_seeds.sort_by(|a, b| {
914 b.1.total_cmp(&a.1).then_with(|| {
915 let ca = entries[a.0].color;
916 let cb = entries[b.0].color;
917 (ca.0, ca.1, ca.2).cmp(&(cb.0, cb.1, cb.2))
918 })
919 });
920
921 let mut seeds: Vec<Color> = Vec::with_capacity(4);
922 let mut seed_hues: Vec<f64> = Vec::with_capacity(4);
923 'outer: for min_dist in (15..=90).rev() {
924 seeds.clear();
925 seed_hues.clear();
926 let threshold = min_dist as f64;
927 for &(idx, _) in &scored_seeds {
928 let e = &entries[idx];
929 if seed_hues.iter().any(|&h| hue_diff(e.hue, h) < threshold) {
930 continue;
931 }
932 seeds.push(e.color);
933 seed_hues.push(e.hue);
934 if seeds.len() >= 4 {
935 break 'outer;
936 }
937 }
938 }
939 if seeds.is_empty() {
940 seeds.push(GOOGLE_BLUE);
941 }
942
943 let mut scored_main: Vec<(usize, f64)> = entries
945 .iter()
946 .enumerate()
947 .map(|(idx, e)| {
948 let hp = window_sum(&all_hue_pop, e.hue);
949 (idx, e.chroma + hp * 100.0)
950 })
951 .collect();
952 scored_main.sort_by(|a, b| b.1.total_cmp(&a.1));
953
954 let mut main_colors: Vec<Color> = Vec::with_capacity(3);
955 let mut main_hues: Vec<f64> = Vec::with_capacity(3);
956 for &(idx, _) in &scored_main {
957 let e = &entries[idx];
958 if main_hues.iter().any(|&h| hue_diff(e.hue, h) < 15.0) {
959 continue;
960 }
961 main_colors.push(e.color);
962 main_hues.push(e.hue);
963 if main_colors.len() >= 3 {
964 break;
965 }
966 }
967
968 let primary = main_colors.first().copied().unwrap_or(seeds[0]);
969 let secondary = main_colors.get(1).copied();
970 let tertiary = main_colors.get(2).copied();
971
972 Self {
973 primary,
974 secondary,
975 tertiary,
976 seeds,
977 supports_dark_text,
978 supports_dark_theme,
979 }
980 }
981
982 fn fallback() -> Self {
983 Self {
984 primary: GOOGLE_BLUE,
985 secondary: None,
986 tertiary: None,
987 seeds: vec![GOOGLE_BLUE],
988 supports_dark_text: false,
989 supports_dark_theme: false,
990 }
991 }
992}
993
994#[derive(Clone, Copy, Debug, PartialEq)]
996pub struct MonetScheme {
997 pub seed: Color,
998 pub dark: bool,
999 pub style: MonetStyle,
1000 pub accent1: TonalPalette,
1001 pub accent2: TonalPalette,
1002 pub accent3: TonalPalette,
1003 pub neutral1: TonalPalette,
1004 pub neutral2: TonalPalette,
1005}
1006
1007impl MonetScheme {
1008 pub fn new(seed: Color, dark: bool, style: MonetStyle) -> Self {
1010 let (_, proposed_chroma, _) = hct_from_rgb(seed);
1011 let effective_seed = if seed.3 == 0 || (style != MonetStyle::Content && proposed_chroma < MIN_CHROMA) {
1012 GOOGLE_BLUE
1013 } else {
1014 seed
1015 };
1016 let (src_hue, src_chroma, _) = hct_from_rgb(effective_seed);
1017 let specs = style.core_specs();
1018 let make = |(h, c): (HueSpec, ChromaSpec)| {
1019 TonalPalette::new(h.resolve(src_hue), c.resolve(src_chroma))
1020 };
1021 Self {
1022 seed: effective_seed,
1023 dark,
1024 style,
1025 accent1: make(specs[0]),
1026 accent2: make(specs[1]),
1027 accent3: make(specs[2]),
1028 neutral1: make(specs[3]),
1029 neutral2: make(specs[4]),
1030 }
1031 }
1032
1033 pub fn from_wallpaper_colors(colors: &WallpaperColors, dark: bool, style: MonetStyle) -> Self {
1035 let seed = colors.seeds.first().copied().unwrap_or(GOOGLE_BLUE);
1036 Self::new(seed, dark, style)
1037 }
1038
1039 pub fn to_theme(&self) -> Theme {
1041 let error = TonalPalette::new(25.0, 84.0);
1042 if self.dark {
1043 Theme {
1044 background: self.neutral1.tone(6),
1045 text: self.neutral1.tone(90),
1046 control: self.neutral1.tone(12),
1047 hovered: self.neutral1.tone(22),
1048 pressed: self.accent1.tone(30),
1049 radius: 8.0,
1050 primary: self.accent1.tone(80),
1051 on_primary: self.accent1.tone(20),
1052 secondary: self.accent2.tone(30),
1053 outline: self.neutral2.tone(60),
1054 error: error.tone(80),
1055 on_error: error.tone(20),
1056 on_secondary: self.accent2.tone(90),
1057 secondary_container: self.accent2.tone(30),
1058 on_secondary_container: self.accent2.tone(90),
1059 surface_low: self.neutral1.tone(10),
1060 surface_high: self.neutral1.tone(17),
1061 surface_highest: self.neutral1.tone(22),
1062 outline_variant: self.neutral2.tone(30),
1063 primary_container: self.accent1.tone(30),
1064 on_primary_container: self.accent1.tone(90),
1065 tertiary_container: self.accent3.tone(30),
1066 on_tertiary_container: self.accent3.tone(90),
1067 inverse_surface: self.neutral1.tone(90),
1068 inverse_on_surface: self.neutral1.tone(20),
1069 inverse_primary: self.accent1.tone(40),
1070 on_surface_variant: self.neutral2.tone(80),
1071 surface_variant: self.neutral2.tone(30),
1072 }
1073 } else {
1074 Theme {
1075 background: self.neutral1.tone(98),
1076 text: self.neutral1.tone(10),
1077 control: self.neutral1.tone(94),
1078 hovered: self.neutral1.tone(90),
1079 pressed: self.accent1.tone(80),
1080 radius: 8.0,
1081 primary: self.accent1.tone(40),
1082 on_primary: self.accent1.tone(100),
1083 secondary: self.accent2.tone(90),
1084 outline: self.neutral2.tone(50),
1085 error: error.tone(40),
1086 on_error: error.tone(100),
1087 on_secondary: self.accent2.tone(10),
1088 secondary_container: self.accent2.tone(90),
1089 on_secondary_container: self.accent2.tone(10),
1090 surface_low: self.neutral1.tone(96),
1091 surface_high: self.neutral1.tone(92),
1092 surface_highest: self.neutral1.tone(90),
1093 outline_variant: self.neutral2.tone(80),
1094 primary_container: self.accent1.tone(90),
1095 on_primary_container: self.accent1.tone(10),
1096 tertiary_container: self.accent3.tone(90),
1097 on_tertiary_container: self.accent3.tone(10),
1098 inverse_surface: self.neutral1.tone(20),
1099 inverse_on_surface: self.neutral1.tone(95),
1100 inverse_primary: self.accent1.tone(80),
1101 on_surface_variant: self.neutral2.tone(30),
1102 surface_variant: self.neutral2.tone(90),
1103 }
1104 }
1105 }
1106
1107 pub fn preview_quadrants(&self) -> [Color; 4] {
1110 if self.dark {
1111 [
1112 self.accent1.tone(80),
1113 self.accent1.tone(30),
1114 self.accent3.tone(80),
1115 self.accent2.tone(60),
1116 ]
1117 } else {
1118 [
1119 self.accent1.tone(40),
1120 self.accent1.tone(80),
1121 self.accent3.tone(80),
1122 self.accent2.tone(90),
1123 ]
1124 }
1125 }
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130 use super::*;
1131
1132 fn contrast_ratio(a: Color, b: Color) -> f64 {
1133 let la = y_from_lstar(lstar_from_rgb(a)) / 100.0;
1134 let lb = y_from_lstar(lstar_from_rgb(b)) / 100.0;
1135 let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
1136 (hi + 0.05) / (lo + 0.05)
1137 }
1138
1139 #[test]
1140 fn hct_round_trip_and_lstar_accuracy() {
1141 let samples = [
1142 GOOGLE_BLUE,
1143 Color(0x67, 0x50, 0xa4, 255),
1144 Color(0xb3, 0x26, 0x1e, 255),
1145 Color(0x14, 0x6c, 0x2e, 255),
1146 Color(0xe6, 0x9f, 0x00, 255),
1147 Color(0x00, 0x80, 0x80, 255),
1148 Color(128, 128, 128, 255),
1149 Color(255, 255, 255, 255),
1150 Color(0, 0, 0, 255),
1151 ];
1152 for c in samples {
1153 let (h, ch, t) = hct_from_rgb(c);
1154 let round = rgb_from_hct(h, ch, t);
1155 assert!(
1156 (round.0 as i32 - c.0 as i32).abs() <= 2
1157 && (round.1 as i32 - c.1 as i32).abs() <= 2
1158 && (round.2 as i32 - c.2 as i32).abs() <= 2,
1159 "HCT round-trip drift for {:?}: h={:.2} c={:.2} t={:.2} -> {:?}",
1160 c,
1161 h,
1162 ch,
1163 t,
1164 round
1165 );
1166 assert!((lstar_from_rgb(round) - t).abs() < 1.0);
1167 }
1168 assert!((y_from_lstar(0.0) - 0.0).abs() < 1e-6);
1169 assert!((y_from_lstar(100.0) - 100.0).abs() < 1e-6);
1170 assert!((y_from_lstar(50.0) - 18.418651851244416).abs() < 1e-6);
1171 }
1172
1173 #[test]
1174 fn monet_scheme_google_blue_and_all_seven_styles() {
1175 let styles = [
1176 MonetStyle::TonalSpot,
1177 MonetStyle::Spritz,
1178 MonetStyle::Vibrant,
1179 MonetStyle::Expressive,
1180 MonetStyle::Rainbow,
1181 MonetStyle::FruitSalad,
1182 MonetStyle::Content,
1183 ];
1184 let base = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::TonalSpot);
1185 assert_eq!(base.accent1.tone(100), Color(255, 255, 255, 255));
1187 assert_eq!(base.accent1.tone(0), Color(0, 0, 0, 255));
1188 let mut prev_l = 101.0;
1189 for &t in &TonalPalette::TONES {
1190 let l = lstar_from_rgb(base.accent1.tone(t));
1191 assert!(l <= prev_l + 0.5, "non-monotonic tone {}: {} > {}", t, l, prev_l);
1192 prev_l = l;
1193 }
1194 assert!(contrast_ratio(base.accent1.tone(50), Color(255, 255, 255, 255)) >= 4.4);
1196 assert!(contrast_ratio(base.accent1.tone(50), Color(0, 0, 0, 255)) >= 4.4);
1197
1198 let mut primary40s = Vec::new();
1200 for style in styles {
1201 let light = MonetScheme::new(GOOGLE_BLUE, false, style);
1202 let dark = MonetScheme::new(GOOGLE_BLUE, true, style);
1203 primary40s.push((style, light.accent1.tone(40)));
1204 let ql = light.preview_quadrants();
1205 let qd = dark.preview_quadrants();
1206 assert_ne!(ql[0], ql[1]);
1207 assert_ne!(qd[0], qd[1]);
1208 assert_ne!(ql, qd);
1209 }
1210 let tonal_h = base.accent1.hue();
1212 let expr = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::Expressive);
1213 let fruit = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::FruitSalad);
1214 let rainbow = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::Rainbow);
1215 assert!(hue_diff(expr.accent1.hue(), wrap_degrees(tonal_h + 240.0)) < 1e-6);
1216 assert!(hue_diff(fruit.accent1.hue(), wrap_degrees(tonal_h - 50.0)) < 1e-6);
1217 assert_eq!(rainbow.neutral1.chroma(), 0.0);
1218
1219 let gray = Color(120, 120, 120, 255);
1221 assert_eq!(MonetScheme::new(gray, false, MonetStyle::TonalSpot).seed, GOOGLE_BLUE);
1222 assert_eq!(MonetScheme::new(gray, false, MonetStyle::Content).seed, gray);
1223 }
1224
1225 #[test]
1226 fn wallpaper_colors_extracts_hints_and_four_hue_separated_seeds() {
1227 let dark_img = vec![16, 16, 16, 255].repeat(64 * 64);
1230 let wc_dark = WallpaperColors::from_rgba(64, 64, &dark_img);
1231 assert!(wc_dark.supports_dark_theme);
1232 assert!(!wc_dark.supports_dark_text);
1233 assert_eq!(wc_dark.seeds, vec![GOOGLE_BLUE]);
1234
1235 let bright_img = vec![245, 248, 250, 255].repeat(64 * 64);
1237 let wc_bright = WallpaperColors::from_rgba(64, 64, &bright_img);
1238 assert!(wc_bright.supports_dark_text);
1239 assert!(!wc_bright.supports_dark_theme);
1240
1241 let w = 128u32;
1243 let h = 128u32;
1244 let mut quad = vec![0u8; (w * h * 4) as usize];
1245 for y in 0..h {
1246 for x in 0..w {
1247 let c = match (x < w / 2, y < h / 2) {
1248 (true, true) => [220, 40, 40, 255], (false, true) => [30, 180, 70, 255], (true, false) => [35, 100, 235, 255], (false, false) => [235, 190, 20, 255], };
1253 let i = ((y * w + x) * 4) as usize;
1254 quad[i..i + 4].copy_from_slice(&c);
1255 }
1256 }
1257 let wc_quad = WallpaperColors::from_rgba(w, h, &quad);
1258 assert_eq!(wc_quad.seeds.len(), 4);
1259 assert!(wc_quad.secondary.is_some());
1260 assert!(wc_quad.tertiary.is_some());
1261 for i in 0..wc_quad.seeds.len() {
1262 let (hi, _, _) = hct_from_rgb(wc_quad.seeds[i]);
1263 for j in (i + 1)..wc_quad.seeds.len() {
1264 let (hj, _, _) = hct_from_rgb(wc_quad.seeds[j]);
1265 assert!(
1266 hue_diff(hi, hj) >= 45.0,
1267 "quadrant seeds {} and {} too close in hue: {:.1} vs {:.1}",
1268 i,
1269 j,
1270 hi,
1271 hj
1272 );
1273 }
1274 }
1275 }
1276
1277 #[test]
1278 fn to_theme_meets_m3_contrast_in_light_and_dark_modes_for_all_basic_seeds() {
1279 assert_eq!(BASIC_COLOR_SEEDS.len(), 16);
1280 for &(name, seed) in &BASIC_COLOR_SEEDS {
1281 for dark in [false, true] {
1282 let theme = MonetScheme::new(seed, dark, MonetStyle::TonalSpot).to_theme();
1283 let pairs = [
1284 ("text/background", theme.text, theme.background),
1285 ("on_primary/primary", theme.on_primary, theme.primary),
1286 (
1287 "on_primary_container/primary_container",
1288 theme.on_primary_container,
1289 theme.primary_container,
1290 ),
1291 ("on_secondary/secondary", theme.on_secondary, theme.secondary),
1292 (
1293 "on_secondary_container/secondary_container",
1294 theme.on_secondary_container,
1295 theme.secondary_container,
1296 ),
1297 (
1298 "on_tertiary_container/tertiary_container",
1299 theme.on_tertiary_container,
1300 theme.tertiary_container,
1301 ),
1302 ("on_error/error", theme.on_error, theme.error),
1303 (
1304 "inverse_on_surface/inverse_surface",
1305 theme.inverse_on_surface,
1306 theme.inverse_surface,
1307 ),
1308 (
1309 "on_surface_variant/background",
1310 theme.on_surface_variant,
1311 theme.background,
1312 ),
1313 ];
1314 for (pair_name, fg, bg) in pairs {
1315 let cr = contrast_ratio(fg, bg);
1316 assert!(
1317 cr >= 4.5,
1318 "Low contrast ({:.2}) for {} ({}) in dark={}",
1319 cr,
1320 pair_name,
1321 name,
1322 dark
1323 );
1324 }
1325 }
1326 }
1327 }
1328}