Skip to main content

latex_rust/
color.rs

1//! Color models for math mode. Channel arithmetic is [`Dim`](crate::Dim) only.
2//!
3//! SVG `fill` / `stroke`, PNG (`tiny-skia`), and egui (`Color32`) all convert
4//! through [`Color::to_rgba8`]. This module resolves a color to 8-bit sRGB so
5//! every backend shares one contract.
6
7use std::collections::BTreeMap;
8use std::fmt;
9use std::sync::OnceLock;
10
11use crate::dim::Dim;
12use crate::error::Error;
13
14// dvips names from drivers.dtx (`%<*dvipsnames>` / dvipsnam.def), LPPL-1.3c
15// or later. Lines in the table that start with `#` are the modification
16// notice. See NOTICE.
17const DVIPS: &str = include_str!("../data/dvipsnames.tsv");
18
19/// 8-bit sRGB color. Values are integers; conversion from unit intervals uses `Dim`.
20///
21/// SVG `fill` / `stroke`, PNG (`tiny-skia`), and egui (`Color32`) all convert
22/// through [`Color::to_rgba8`].
23///
24/// # Examples
25///
26/// ```
27/// use latex_rust::Color;
28///
29/// let c = Color::rgb(255, 0, 0);
30/// assert_eq!(c.css_hex(), "#ff0000");
31/// assert_eq!(c.to_rgba8(), [255, 0, 0, 255]);
32/// ```
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct Color {
35    /// Red 0–255.
36    pub r: u8,
37    /// Green 0–255.
38    pub g: u8,
39    /// Blue 0–255.
40    pub b: u8,
41}
42
43impl Color {
44    /// Opaque sRGB triple.
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use latex_rust::Color;
50    /// assert_eq!(Color::rgb(0, 0, 0).css_hex(), "#000000");
51    /// ```
52    #[must_use]
53    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
54        Self { r, g, b }
55    }
56
57    /// CSS hex `#rrggbb`.
58    #[must_use]
59    pub fn css_hex(self) -> String {
60        format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
61    }
62
63    /// Opaque sRGB bytes for PNG (`tiny-skia`) and egui (`Color32`) backends.
64    #[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/// Named-color registry, including `\definecolor` overrides.
88///
89/// # Examples
90///
91/// ```
92/// use latex_rust::ColorTable;
93///
94/// let mut t = ColorTable::new();
95/// assert!(!t.is_empty());
96/// t.define("ok", "named", "red").unwrap();
97/// assert_eq!(t.get("ok").unwrap().css_hex(), "#ff0000");
98/// ```
99#[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    /// Standard LaTeX names plus the 68 dvipsnames (CMYK → sRGB via `Dim`).
112    #[must_use]
113    pub fn new() -> Self {
114        builtin().clone()
115    }
116
117    /// A table with no names, as a cheap placeholder while the real table is
118    /// moved elsewhere.
119    pub(crate) fn empty() -> Self {
120        Self {
121            named: BTreeMap::new(),
122        }
123    }
124
125    /// Number of registered names.
126    #[must_use]
127    pub fn len(&self) -> usize {
128        self.named.len()
129    }
130
131    /// True when no names are registered.
132    #[must_use]
133    pub fn is_empty(&self) -> bool {
134        self.named.is_empty()
135    }
136
137    /// Look up a named color. Unknown names are [`Error::Unsupported`].
138    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    /// `\definecolor{name}{model}{spec}`.
148    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
191/// Parse `{model}{spec}` as in `\definecolor` / `\color[model]{spec}`.
192///
193/// `named` uses `table` when provided, otherwise a fresh standard table.
194///
195/// # Arguments
196///
197/// * `model` — `named`, `rgb`, `RGB`, `HTML`, `cmyk`, or `gray`.
198/// * `spec` — model-specific components (comma-separated, or a name / hex).
199/// * `table` — optional named-color registry for the `named` model.
200///
201/// # Returns
202///
203/// An opaque sRGB [`Color`].
204///
205/// # Errors
206///
207/// * [`Error::Unsupported`] — unknown model or unknown named color.
208/// * [`Error::Malformed`] — wrong component count or out-of-range value.
209///
210/// # Examples
211///
212/// ```
213/// use latex_rust::parse_color_spec;
214///
215/// let c = parse_color_spec("RGB", "255,0,0", None).unwrap();
216/// assert_eq!(c.css_hex(), "#ff0000");
217/// ```
218pub 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
276/// Named color from the standard table (`red`, `RoyalBlue`, …).
277///
278/// # Arguments
279///
280/// * `name` — LaTeX or dvipsnames identifier (case-sensitive as stored).
281///
282/// # Returns
283///
284/// The registered sRGB color.
285///
286/// # Errors
287///
288/// [`Error::Unsupported`] when the name is not in the table.
289///
290/// # Examples
291///
292/// ```
293/// use latex_rust::named_color;
294///
295/// assert_eq!(named_color("red").unwrap().css_hex(), "#ff0000");
296/// assert!(named_color("not-a-color").is_err());
297/// ```
298pub 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}