Skip to main content

hyprforge_look/
color.rs

1//! One colour type, and one parser for it.
2//!
3//! `rgba(rrggbbaa)` is already the universal spelling across this
4//! workspace — the catalogue defaults, every stored `Value::Text`, the
5//! lock screen's theme file. What was missing was a single
6//! implementation: four grew independently, with three different ideas
7//! about what to do with input that doesn't parse.
8//!
9//! **Leniency is not a mode here.** `parse` is strict and there is no
10//! forgiving variant, because a fallback is a decision about what the
11//! user should see and it belongs at the place that decides — a lock
12//! screen writes `Color::parse(s).unwrap_or(Color::BLACK)` and the
13//! reason ("a lock screen with a bad colour must be plain, not absent")
14//! stays visible next to the code that depends on it, instead of being
15//! a property hidden inside a helper.
16//!
17//! [`Display`](std::fmt::Display) is the only way to turn one back into
18//! a string, so no caller can invent a fifth spelling.
19
20use std::fmt;
21
22/// A colour, 8 bits per channel.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Color {
25    /// Red, 0-255.
26    pub r: u8,
27    /// Green, 0-255.
28    pub g: u8,
29    /// Blue, 0-255.
30    pub b: u8,
31    /// Alpha, 0-255. `0xff` is opaque; the auth screen's defaults are
32    /// deliberately all opaque, because a transparent background or text
33    /// colour there renders nothing at all.
34    pub a: u8,
35}
36
37/// A string that isn't `rgba(rrggbbaa)` or `rgb(rrggbb)` in hex.
38///
39/// Carries the rejected input rather than just a message, because the
40/// caller decides what to do with a bad colour — a lock screen falls
41/// back to [`Color::BLACK`], a settings form shows the input back to the
42/// user — and both need the string to do it.
43#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
44#[error("expected rgba(rrggbbaa) or rgb(rrggbb) in hex, got {0:?}")]
45pub struct ColorError(pub String);
46
47impl Color {
48    /// Opaque black. The fallback a caller reaches for when a colour
49    /// fails to parse and something must still be drawn — see the module
50    /// doc's note on leniency living at the call site, not in here.
51    pub const BLACK: Color = Color { r: 0, g: 0, b: 0, a: 0xff };
52
53    /// Builds a colour directly from its channels, bypassing
54    /// [`parse`](Self::parse). `const fn` so it can build the default
55    /// palette's constants at compile time.
56    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
57        Color { r, g, b, a }
58    }
59
60    /// Parses `rgba(rrggbbaa)` or `rgb(rrggbb)`, strictly.
61    ///
62    /// The digit count is tied to the prefix: `rgba()` takes eight and
63    /// `rgb()` six. Accepting eight digits inside `rgb(` would draw a
64    /// confident swatch beside a value Hyprland is about to refuse.
65    pub fn parse(s: &str) -> Result<Color, ColorError> {
66        let bad = || ColorError(s.to_string());
67        let (body, want) = match s.strip_prefix("rgba(") {
68            Some(rest) => (rest.strip_suffix(')').ok_or_else(bad)?, 8),
69            None => (
70                s.strip_prefix("rgb(")
71                    .ok_or_else(bad)?
72                    .strip_suffix(')')
73                    .ok_or_else(bad)?,
74                6,
75            ),
76        };
77        if body.len() != want || !body.chars().all(|c| c.is_ascii_hexdigit()) {
78            return Err(bad());
79        }
80        let byte = |i: usize| u8::from_str_radix(&body[i..i + 2], 16).map_err(|_| bad());
81        Ok(Color {
82            r: byte(0)?,
83            g: byte(2)?,
84            b: byte(4)?,
85            a: if want == 8 { byte(6)? } else { 0xff },
86        })
87    }
88
89    /// Reads `hyprctl`'s gradient spelling, which is `AARRGGBB` — the
90    /// alpha leading rather than trailing. Copying that string into a
91    /// config would be a different colour.
92    pub fn from_argb_hex(s: &str) -> Option<Color> {
93        if s.len() != 8 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
94            return None;
95        }
96        let byte = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
97        Some(Color { a: byte(0)?, r: byte(2)?, g: byte(4)?, b: byte(6)? })
98    }
99
100    /// Reads `hyprctl`'s plain-colour spelling, a packed `0xAARRGGBB`
101    /// integer. `rgba(112233ff)` comes back as `4279312947`.
102    pub fn from_argb_u32(v: u32) -> Color {
103        Color {
104            a: (v >> 24) as u8,
105            r: (v >> 16) as u8,
106            g: (v >> 8) as u8,
107            b: v as u8,
108        }
109    }
110}
111
112impl fmt::Display for Color {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        write!(f, "rgba({:02x}{:02x}{:02x}{:02x})", self.r, self.g, self.b, self.a)
115    }
116}
117
118impl serde::Serialize for Color {
119    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
120        s.serialize_str(&self.to_string())
121    }
122}
123
124impl<'de> serde::Deserialize<'de> for Color {
125    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Color, D::Error> {
126        let raw = String::deserialize(d)?;
127        Color::parse(&raw).map_err(serde::de::Error::custom)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn the_two_accepted_spellings_parse() {
137        assert_eq!(Color::parse("rgba(bd93f9ff)").unwrap(), Color::rgba(0xbd, 0x93, 0xf9, 0xff));
138        assert_eq!(Color::parse("rgb(282a36)").unwrap(), Color::rgba(0x28, 0x2a, 0x36, 0xff));
139        assert_eq!(Color::parse("rgba(00000080)").unwrap(), Color::rgba(0, 0, 0, 0x80));
140    }
141
142    /// The digit count is tied to the prefix. Being more lenient would
143    /// accept values Hyprland itself refuses, which is worse than
144    /// refusing them here: the user would see a confident swatch beside
145    /// a setting that will not apply.
146    #[test]
147    fn the_digit_count_must_match_the_prefix() {
148        assert!(Color::parse("rgb(bd93f9ff)").is_err(), "eight digits in rgb(");
149        assert!(Color::parse("rgba(282a36)").is_err(), "six digits in rgba(");
150    }
151
152    /// Every shape the old parsers disagreed about. One of them treated
153    /// these as opaque black, another as `None`; now there is one answer
154    /// and the caller decides what to do with it.
155    #[test]
156    fn anything_else_is_refused_rather_than_guessed() {
157        for bad in [
158            "",
159            "nonsense",
160            "rgba(",
161            "rgba(zzzzzzzz)",
162            "0xffbd93f9",
163            "rgba(bd93f9ff",
164            "bd93f9ff",
165            "rgba(bd93f9ff) ",
166        ] {
167            assert!(Color::parse(bad).is_err(), "{bad:?} should not parse");
168        }
169    }
170
171    /// `hyprctl` puts the alpha first; the config format puts it last.
172    /// Getting this backwards is a different colour, not a near miss.
173    #[test]
174    fn hyprctl_spellings_move_the_alpha_to_the_end() {
175        assert_eq!(Color::from_argb_hex("ffbd93f9").unwrap().to_string(), "rgba(bd93f9ff)");
176        assert_eq!(Color::from_argb_u32(4279312947).to_string(), "rgba(112233ff)");
177    }
178
179    #[test]
180    fn a_colour_round_trips_through_its_string_form() {
181        for original in ["rgba(bd93f9ff)", "rgba(00000000)", "rgba(ffffffff)"] {
182            let parsed = Color::parse(original).unwrap();
183            assert_eq!(parsed.to_string(), original);
184            assert_eq!(Color::parse(&parsed.to_string()).unwrap(), parsed);
185        }
186    }
187
188    #[test]
189    fn colours_survive_serde_as_the_string_form() {
190        #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
191        struct Holder {
192            accent: Color,
193        }
194        let held = Holder { accent: Color::parse("rgba(bd93f9ff)").unwrap() };
195        let text = toml::to_string(&held).unwrap();
196        assert!(text.contains(r#"accent = "rgba(bd93f9ff)""#), "{text}");
197        assert_eq!(toml::from_str::<Holder>(&text).unwrap(), held);
198    }
199}