1use std::collections::BTreeMap;
8use std::fmt;
9use std::sync::OnceLock;
10
11use crate::dim::Dim;
12use crate::error::Error;
13
14const DVIPS: &str = include_str!("../data/dvipsnames.tsv");
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct Color {
35 pub r: u8,
37 pub g: u8,
39 pub b: u8,
41}
42
43impl Color {
44 #[must_use]
53 pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
54 Self { r, g, b }
55 }
56
57 #[must_use]
59 pub fn css_hex(self) -> String {
60 format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
61 }
62
63 #[must_use]
65 pub const fn to_rgba8(self) -> [u8; 4] {
66 [self.r, self.g, self.b, 255]
67 }
68}
69
70impl fmt::Display for Color {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(&self.css_hex())
73 }
74}
75
76const BASE: &[(&str, Color)] = &[
77 ("black", Color::rgb(0, 0, 0)),
78 ("white", Color::rgb(255, 255, 255)),
79 ("red", Color::rgb(255, 0, 0)),
80 ("green", Color::rgb(0, 255, 0)),
81 ("blue", Color::rgb(0, 0, 255)),
82 ("cyan", Color::rgb(0, 255, 255)),
83 ("magenta", Color::rgb(255, 0, 255)),
84 ("yellow", Color::rgb(255, 255, 0)),
85];
86
87#[derive(Clone, Debug)]
100pub struct ColorTable {
101 named: BTreeMap<String, Color>,
102}
103
104impl Default for ColorTable {
105 fn default() -> Self {
106 Self::new()
107 }
108}
109
110impl ColorTable {
111 #[must_use]
113 pub fn new() -> Self {
114 builtin().clone()
115 }
116
117 pub(crate) fn empty() -> Self {
120 Self {
121 named: BTreeMap::new(),
122 }
123 }
124
125 #[must_use]
127 pub fn len(&self) -> usize {
128 self.named.len()
129 }
130
131 #[must_use]
133 pub fn is_empty(&self) -> bool {
134 self.named.is_empty()
135 }
136
137 pub fn get(&self, name: &str) -> Result<Color, Error> {
139 self.named
140 .get(name)
141 .copied()
142 .ok_or_else(|| Error::Unsupported {
143 what: format!("named color {name}"),
144 })
145 }
146
147 pub fn define(&mut self, name: &str, model: &str, spec: &str) -> Result<Color, Error> {
149 let c = parse_color_spec(model, spec, Some(self))?;
150 self.named.insert(name.to_string(), c);
151 Ok(c)
152 }
153}
154
155fn dvipsnames() -> &'static [(String, Color)] {
156 static T: OnceLock<Vec<(String, Color)>> = OnceLock::new();
157 T.get_or_init(load_dvips).as_slice()
158}
159
160fn load_dvips() -> Vec<(String, Color)> {
161 let mut out = Vec::new();
162 let mut lines = DVIPS.lines().filter(|line| {
163 let trimmed = line.trim();
164 !trimmed.is_empty() && !trimmed.starts_with('#')
165 });
166 let header = lines.next().expect("dvipsnames header");
167 assert_eq!(header, "name\tc\tm\ty\tk", "dvipsnames.tsv schema");
168 for line in lines {
169 if line.is_empty() {
170 continue;
171 }
172 let mut cols = line.split('\t');
173 let name = cols.next().expect("name").to_string();
174 let c = cols.next().expect("c");
175 let m = cols.next().expect("m");
176 let y = cols.next().expect("y");
177 let k = cols.next().expect("k");
178 let color = cmyk_to_rgb(
179 &Dim::parse(c),
180 &Dim::parse(m),
181 &Dim::parse(y),
182 &Dim::parse(k),
183 )
184 .expect("dvipsnames cmyk");
185 out.push((name, color));
186 }
187 assert_eq!(out.len(), 68, "dvipsnames must be the full 68-color set");
188 out
189}
190
191pub fn parse_color_spec(
219 model: &str,
220 spec: &str,
221 table: Option<&ColorTable>,
222) -> Result<Color, Error> {
223 let model = model.trim();
224 let spec = spec.trim();
225 match model {
226 "named" => match table {
227 Some(t) => t.get(spec),
228 None => builtin().get(spec),
229 },
230 "rgb" => {
231 let v = unit_components(spec, 3)?;
232 Ok(Color::rgb(
233 unit_to_u8(&v[0])?,
234 unit_to_u8(&v[1])?,
235 unit_to_u8(&v[2])?,
236 ))
237 }
238 "RGB" => {
239 let v = unit_components(spec, 3)?;
240 Ok(Color::rgb(
241 byte_channel(&v[0])?,
242 byte_channel(&v[1])?,
243 byte_channel(&v[2])?,
244 ))
245 }
246 "HTML" => parse_html(spec),
247 "cmyk" => {
248 let v = unit_components(spec, 4)?;
249 cmyk_to_rgb(&v[0], &v[1], &v[2], &v[3])
250 }
251 "gray" => {
252 let v = unit_components(spec, 1)?;
253 let g = unit_to_u8(&v[0])?;
254 Ok(Color::rgb(g, g, g))
255 }
256 other => Err(Error::Unsupported {
257 what: format!("color model {other}"),
258 }),
259 }
260}
261
262fn builtin() -> &'static ColorTable {
263 static T: OnceLock<ColorTable> = OnceLock::new();
264 T.get_or_init(|| {
265 let mut named = BTreeMap::new();
266 for (n, c) in BASE {
267 named.insert((*n).to_string(), *c);
268 }
269 for (n, c) in dvipsnames() {
270 named.insert(n.clone(), *c);
271 }
272 ColorTable { named }
273 })
274}
275
276pub fn named_color(name: &str) -> Result<Color, Error> {
299 builtin().get(name)
300}
301
302fn parse_html(spec: &str) -> Result<Color, Error> {
303 let s = spec.trim().trim_start_matches('#');
304 if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
305 return Err(malformed(format!("HTML color {spec}")));
306 }
307 let n = u32::from_str_radix(s, 16).map_err(|_| malformed(format!("HTML color {spec}")))?;
308 Ok(Color::rgb(
309 ((n >> 16) & 0xff) as u8,
310 ((n >> 8) & 0xff) as u8,
311 (n & 0xff) as u8,
312 ))
313}
314
315fn unit_components(spec: &str, n: usize) -> Result<Vec<Dim>, Error> {
316 let parts: Vec<&str> = spec
317 .split(',')
318 .map(str::trim)
319 .filter(|p| !p.is_empty())
320 .collect();
321 if parts.len() != n {
322 return Err(malformed(format!(
323 "color spec `{spec}` (need {n} components)"
324 )));
325 }
326 Ok(parts.iter().map(|p| Dim::parse(p)).collect())
327}
328
329fn cmyk_to_rgb(c: &Dim, m: &Dim, y: &Dim, k: &Dim) -> Result<Color, Error> {
330 let one = Dim::one();
331 let r = &(&one - c) * &(&one - k);
332 let g = &(&one - m) * &(&one - k);
333 let b = &(&one - y) * &(&one - k);
334 Ok(Color::rgb(
335 unit_to_u8(&r)?,
336 unit_to_u8(&g)?,
337 unit_to_u8(&b)?,
338 ))
339}
340
341fn unit_to_u8(d: &Dim) -> Result<u8, Error> {
342 if d.is_nan() {
343 return Err(malformed("color component NaN"));
344 }
345 let zero = Dim::zero();
346 let one = Dim::one();
347 let clamped = if matches!(d.cmp(&zero), Some(core::cmp::Ordering::Less)) {
348 zero
349 } else if matches!(d.cmp(&one), Some(core::cmp::Ordering::Greater)) {
350 one
351 } else {
352 d.clone()
353 };
354 let scaled = clamped * Dim::from_i64(255);
355 let rounded = &scaled + &Dim::ratio(1, 2);
356 Ok(floor_u8(&rounded))
357}
358
359fn byte_channel(d: &Dim) -> Result<u8, Error> {
360 if d.is_nan() {
361 return Err(malformed("RGB component NaN"));
362 }
363 let zero = Dim::zero();
364 let max = Dim::from_i64(255);
365 if matches!(d.cmp(&zero), Some(core::cmp::Ordering::Less))
366 || matches!(d.cmp(&max), Some(core::cmp::Ordering::Greater))
367 {
368 return Err(malformed("RGB component out of 0..255"));
369 }
370 let rounded = d + &Dim::ratio(1, 2);
371 Ok(floor_u8(&rounded))
372}
373
374fn malformed(what: impl Into<String>) -> Error {
375 Error::Malformed { what: what.into() }
376}
377
378fn floor_u8(d: &Dim) -> u8 {
379 let mut ans = 0u8;
380 let mut bit = 128u8;
381 while bit > 0 {
382 let cand = ans.saturating_add(bit);
383 if Dim::from_i64(i64::from(cand))
384 .cmp(d)
385 .is_some_and(|o| o != core::cmp::Ordering::Greater)
386 {
387 ans = cand;
388 }
389 bit /= 2;
390 }
391 ans
392}