Skip to main content

hyprforge_look/
theme.rs

1//! One look, readable from both sides of the login boundary.
2//!
3//! This is the part that makes a greeter and a lock screen feel like one
4//! system, and it is not a styling problem. A greeter runs as its own
5//! user — greetd's default is `greeter` — and a home directory is
6//! `drwx------`. The greeter therefore cannot read your wallpaper, your
7//! colours or your fonts *at all*: not because the files are private, but
8//! because it cannot traverse the directory above them. On this machine
9//! `~/Pictures/Wallpapers/Dracula.png` is world-readable and still
10//! unreachable.
11//!
12//! So continuity is an **export**. Hyprforge already owns every visual
13//! input — the wallpaper (hyprpaper), the colours (appearance settings),
14//! the fonts (gsettings) — and resolves them into one [`Theme`] that both
15//! hosts read. The lock screen reads it from your config because it runs
16//! as you; the greeter reads the exported copy. Same struct, same
17//! renderer, same result.
18//!
19//! **The wallpaper is copied, not linked.** A path into `$HOME` is
20//! unreadable from the greeter no matter how the file itself is
21//! permissioned, and a symlink doesn't change that — the traversal is
22//! what fails.
23
24use crate::Color;
25use serde::{Deserialize, Serialize};
26use std::path::{Path, PathBuf};
27
28/// Where an exported theme lives.
29///
30/// Outside `$HOME` by necessity. `/var/lib` rather than `/etc` because
31/// this is generated state, not configuration a sysadmin edits.
32pub const EXPORT_DIR: &str = "/var/lib/hyprforge/greet";
33
34/// The environment variable that redirects [`export_dir`].
35///
36/// Exists so the export can be isolated the same way the config home
37/// can. Without it the two writes in `appearance::look::publish` obey
38/// different rules: `lock.toml` follows `XDG_CONFIG_HOME` and the export
39/// does not, so anything that sandboxes one still writes the real
40/// login screen's theme.
41///
42/// That is not hypothetical — the Settings module tests drive a save
43/// through `publish`, and on a machine where the greeter is installed
44/// they overwrote the user's exported theme with one derived from an
45/// empty temp config. Harmless before installing, destructive after,
46/// which is the worst time to find out.
47pub const EXPORT_DIR_ENV: &str = "HYPRFORGE_GREET_DIR";
48
49/// Where an exported theme is written and read.
50///
51/// [`EXPORT_DIR`] unless [`EXPORT_DIR_ENV`] overrides it. Read every
52/// time rather than cached, because a test sets it after this library is
53/// already loaded.
54pub fn export_dir() -> PathBuf {
55    std::env::var_os(EXPORT_DIR_ENV)
56        .filter(|v| !v.is_empty())
57        .map(PathBuf::from)
58        .unwrap_or_else(|| PathBuf::from(EXPORT_DIR))
59}
60
61/// What went wrong reading, writing or (de)serialising a [`Theme`].
62///
63/// `#[non_exhaustive]` here and nowhere else in this file: on an enum it
64/// only forces external `match`es to carry a `_` arm, so a fifth failure
65/// mode can be added later without an API break. On a *struct* the same
66/// attribute blocks external construction outright — even
67/// `Theme { accent, ..Default::default() }` fails to compile outside
68/// this crate — which is why `Theme`, `Surfaces` and `Color` do not get
69/// it: callers build those with struct-update syntax today, and freezing
70/// that would break every one of them.
71#[derive(Debug, thiserror::Error)]
72#[non_exhaustive]
73pub enum ThemeError {
74    /// The file exists but couldn't be opened or read — permissions, a
75    /// vanished mount, that kind of thing. Not raised for a missing file,
76    /// which [`Theme::load`] treats as the default instead.
77    #[error("couldn't read {path}: {source}")]
78    Read {
79        /// The path that couldn't be read.
80        path: String,
81        /// The underlying I/O failure.
82        #[source]
83        source: std::io::Error,
84    },
85    /// The write itself failed — [`Theme::save`] or [`Theme::export`]
86    /// couldn't create the file, copy the wallpaper, or rename the temp
87    /// file into place.
88    #[error("couldn't write {path}: {source}")]
89    Write {
90        /// The path that couldn't be written.
91        path: String,
92        /// The underlying I/O failure.
93        #[source]
94        source: std::io::Error,
95    },
96    /// The file was read but isn't valid TOML, or its shape doesn't match
97    /// [`Theme`] — a half-written file, most likely, since every field
98    /// defaults and a merely incomplete one parses fine.
99    #[error("couldn't parse {path}: {source}")]
100    Parse {
101        /// The path whose contents didn't parse.
102        path: String,
103        /// The underlying TOML error.
104        #[source]
105        source: toml::de::Error,
106    },
107    /// Turning a [`Theme`] into TOML failed before any write was
108    /// attempted. In practice this shouldn't happen — every field is a
109    /// plain serialisable type — but `toml::to_string_pretty` returns a
110    /// `Result`, so this variant exists to carry that error rather than
111    /// unwrap it.
112    #[error("couldn't serialize the theme: {0}")]
113    Serialize(#[from] toml::ser::Error),
114}
115
116/// How the authentication screen looks.
117///
118/// Every field has a usable default, because a greeter that fails to
119/// render is a machine nobody can log into. A missing export, an
120/// unreadable wallpaper and a half-written file all have to degrade to
121/// "plain but working" rather than to nothing.
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
123#[serde(default)]
124pub struct Theme {
125    /// Full path to the background image. `None` renders [`Self::background`]
126    /// flat, which is also the fallback when the file can't be read.
127    pub wallpaper: Option<PathBuf>,
128    /// Behind everything, and behind the wallpaper while it loads.
129    pub background: Color,
130    /// The panel the prompt sits on.
131    pub surface: Color,
132    /// Text on `surface`.
133    pub foreground: Color,
134    /// The focused/active colour — the same one window borders use.
135    pub accent: Color,
136    /// Failure text.
137    pub error: Color,
138    /// Font family name, as gsettings reports it. Not a path — the
139    /// renderer resolves it through the system's own font lookup, the
140    /// same as every other app on the desktop.
141    pub font: String,
142    /// Monospace family, as gsettings' `monospace-font-name` reports it —
143    /// for config lines, keys and values shown as they are written.
144    ///
145    /// Empty means "the toolkit's own monospace", and is the default on
146    /// purpose rather than `"Monospace"`: that name is a fontconfig
147    /// *alias*, and a renderer that looks families up by name rather than
148    /// through fontconfig finds no family called that and falls back to
149    /// the proportional default — which is the one font this field exists
150    /// to avoid. For the same reason a family that isn't installed
151    /// resolves to empty too — gsettings will name one that isn't.
152    pub mono_font: String,
153    /// Base point size before [`Self::font_scale`] is applied.
154    pub font_size: f32,
155    /// `strftime` format for the clock. Empty hides it.
156    pub clock_format: String,
157    /// `strftime` format for the date, shown alongside the clock. Empty
158    /// hides it, same as [`Self::clock_format`].
159    pub date_format: String,
160    /// Corner radius, so the prompt matches window rounding.
161    pub rounding: u32,
162    /// How much the wallpaper is dimmed behind the prompt, 0.0 to 1.0.
163    pub dim: f32,
164    /// Blur radius behind the prompt. 0 disables it.
165    pub blur: u32,
166
167    /// Scale applied to every text size, following the desktop's own
168    /// accessibility setting rather than a control of ours.
169    pub font_scale: f32,
170    /// Warnings — a setting that won't take effect, a conflicting bind.
171    pub warning: Color,
172    /// Confirmation that something applied.
173    pub success: Color,
174    /// "This is somewhere else" — a remote host, a mounted share, a
175    /// network location.
176    ///
177    /// Not a fifth shade of warning. It sits alongside
178    /// [`Self::warning`], [`Self::success`] and [`Self::error`] as a
179    /// *state* colour, and it exists because the file manager's design
180    /// reserves colour so that colour always means something: green for
181    /// good, orange for attention, red for danger, and this for
182    /// not-local. Without it a mounted share would have to borrow one
183    /// of the other three and quietly stop meaning what it says.
184    ///
185    /// Dracula's own cyan, unadjusted — the same choice
186    /// [`Self::accent`] and [`Self::error`] already make, and it holds
187    /// contrast against all four surfaces in the ramp.
188    pub info: Color,
189    /// The elevation ramp the window apps are built from. The auth
190    /// screen only needs `background` and `surface`; a settings window
191    /// needs the steps in between.
192    pub surfaces: Surfaces,
193}
194
195/// The shades a windowed app layers on top of each other.
196///
197/// Separate from the auth screen's flat `background`/`surface` pair
198/// because the two are drawing different things: a lock screen is one
199/// panel on a wallpaper, a settings window is a sidebar beside cards
200/// beside rows. Both are the same look; only one needs the ramp.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
202#[serde(default)]
203pub struct Surfaces {
204    /// The window's own background, behind everything else.
205    pub root: Color,
206    /// The navigation panel down the side.
207    pub sidebar: Color,
208    /// A raised panel grouping related settings.
209    pub card: Color,
210    /// The line around a [`Self::card`], one step lighter so the edge
211    /// reads without needing a shadow.
212    pub card_border: Color,
213    /// An individual row inside a card, one step lighter again — the
214    /// step that lets a list read as rows rather than one solid block.
215    pub row: Color,
216    /// Primary text on any of the surfaces above.
217    pub text: Color,
218    /// De-emphasised text — hints, secondary labels — on the same
219    /// surfaces as [`Self::text`].
220    pub text_dim: Color,
221}
222
223impl Default for Surfaces {
224    fn default() -> Self {
225        // Byte-for-byte the values the Settings app shipped as compile
226        // time constants. Unifying the look must not quietly restyle
227        // anything: the only colour that changes is the accent, and it
228        // changes because it is now read rather than guessed at.
229        Surfaces {
230            root: Color::rgba(0x19, 0x1a, 0x21, 0xff),
231            sidebar: Color::rgba(0x12, 0x13, 0x19, 0xff),
232            card: Color::rgba(0x25, 0x27, 0x31, 0xff),
233            card_border: Color::rgba(0x37, 0x3a, 0x47, 0xff),
234            row: Color::rgba(0x1f, 0x21, 0x29, 0xff),
235            text: Color::rgba(0xe9, 0xea, 0xef, 0xff),
236            text_dim: Color::rgba(0x92, 0x96, 0xa4, 0xff),
237        }
238    }
239}
240
241impl Default for Theme {
242    fn default() -> Self {
243        Theme {
244            wallpaper: None,
245            // Deliberately dark and neutral rather than pretty: this is
246            // what shows when everything else has failed, and it must be
247            // legible rather than fashionable.
248            background: Color::rgba(0x16, 0x16, 0x1e, 0xff),
249            surface: Color::rgba(0x26, 0x26, 0x3a, 0xff),
250            foreground: Color::rgba(0xf8, 0xf8, 0xf2, 0xff),
251            accent: Color::rgba(0xbd, 0x93, 0xf9, 0xff),
252            error: Color::rgba(0xff, 0x55, 0x55, 0xff),
253            font: "Sans".into(),
254            mono_font: String::new(),
255            font_size: 15.0,
256            clock_format: "%H:%M".into(),
257            date_format: "%A, %e %B".into(),
258            rounding: 12,
259            dim: 0.35,
260            blur: 0,
261            font_scale: 1.0,
262            warning: Color::rgba(0xf5, 0xb9, 0x42, 0xff),
263            success: Color::rgba(0x3e, 0xcf, 0x8e, 0xff),
264            info: Color::rgba(0x8b, 0xe9, 0xfd, 0xff),
265            surfaces: Surfaces::default(),
266        }
267    }
268}
269
270impl Theme {
271    /// This theme's font size, clamped to something that can actually
272    /// be drawn.
273    ///
274    /// `iced_tiny_skia`/`cosmic-text` assert a non-zero line height, so
275    /// a font size of `0.0` panics on the first frame — and the theme is
276    /// read from a file a person can edit, so `0` is reachable.
277    ///
278    /// It lives here rather than in each host because it was copied into
279    /// three of them (the clipboard popup, the emoji popup and the tray
280    /// menu). The clipboard's own copy said so: "if a third host ever
281    /// needs these bounds, they belong beside `Theme` in
282    /// `hyprforge-look` rather than being copied a third time". The
283    /// third host arrived.
284    pub fn drawable_font_size(&self) -> f32 {
285        match self.font_size.is_finite() {
286            true => self.font_size.clamp(6.0, 48.0),
287            // Not the file's number at all, so the shipped default
288            // rather than a clamp of nonsense.
289            false => Theme::default().font_size,
290        }
291    }
292
293    /// This theme's corner rounding, bounded.
294    ///
295    /// Hyprland's own `decoration:rounding` has no upper limit, and a
296    /// huge one turns a popup into a lozenge or a circle. Same reason
297    /// and same three copies as [`Theme::drawable_font_size`].
298    pub fn corner_radius(&self) -> f32 {
299        const MAX_ROUNDING: u32 = 64;
300        self.rounding.min(MAX_ROUNDING) as f32
301    }
302
303    /// Reads a theme from `path`.
304    ///
305    /// A missing file is the default theme, not an error: the greeter
306    /// runs before anything has necessarily been exported, and refusing
307    /// to draw would mean refusing to let anyone log in.
308    pub fn load(path: &Path) -> Result<Theme, ThemeError> {
309        if !path.exists() {
310            return Ok(Theme::default());
311        }
312        let contents = std::fs::read_to_string(path).map_err(|source| ThemeError::Read {
313            path: path.display().to_string(),
314            source,
315        })?;
316        toml::from_str(&contents).map_err(|source| ThemeError::Parse {
317            path: path.display().to_string(),
318            source,
319        })
320    }
321
322    /// Reads the theme exported to [`export_dir`], falling back to the
323    /// default.
324    ///
325    /// Never returns an error. A greeter has nobody to report one to and
326    /// nothing better to do than draw something usable — so a corrupt or
327    /// unreadable export degrades to plain rather than to a blank screen.
328    ///
329    /// No current caller: `hyprforge-greet` needs the `--theme-dir`
330    /// override that [`load_exported_from`](Self::load_exported_from)
331    /// takes and this fixed path doesn't, so it calls that instead. Kept
332    /// for any *other* host that only ever reads the one export
333    /// (`hyprforge-authui` consumers besides the greeter, should one
334    /// exist).
335    pub fn load_exported() -> Theme {
336        Theme::load_exported_from(&export_dir())
337    }
338
339    /// [`load_exported`](Self::load_exported) against a named directory.
340    ///
341    /// Split out so the degrade-to-default behaviour can be tested
342    /// without reading a real system path — and so a caller with its own
343    /// notion of where the export lives, like `hyprforge-greet`'s
344    /// `--theme-dir`, can use it too. The test that read a real path
345    /// instead asserted the export "won't exist in a test environment",
346    /// which stopped being true the moment the greeter was installed on
347    /// the machine running the tests — it then failed because the
348    /// product was working.
349    pub fn load_exported_from(dir: &Path) -> Theme {
350        Theme::load(&dir.join("theme.toml")).unwrap_or_default()
351    }
352
353    /// Writes the theme to `path`, as the lock screen reads it.
354    ///
355    /// The wallpaper path is stored as-is, because the reader runs as
356    /// the same user and can follow it. [`export`](Self::export) is the
357    /// version for a reader that cannot.
358    pub fn save(&self, path: &Path) -> Result<(), ThemeError> {
359        let contents = toml::to_string_pretty(self)?;
360        hyprforge_paths::write_atomic(path, &contents).map_err(|source| ThemeError::Write {
361            path: path.display().to_string(),
362            source,
363        })
364    }
365
366    /// Writes the theme and a copy of its wallpaper into `dir`.
367    ///
368    /// The wallpaper is **copied**, and the stored path rewritten to the
369    /// copy. Referring to the original would leave the greeter with a
370    /// path it cannot traverse — the failure this whole module exists to
371    /// avoid — and it would break again the moment the image moved.
372    ///
373    /// Returns the theme as written, which is not the theme passed in:
374    /// its wallpaper path points at the copy.
375    pub fn export(&self, dir: &Path) -> Result<Theme, ThemeError> {
376        std::fs::create_dir_all(dir).map_err(|source| ThemeError::Write {
377            path: dir.display().to_string(),
378            source,
379        })?;
380
381        let mut exported = self.clone();
382        exported.wallpaper = match &self.wallpaper {
383            Some(source) if source.is_file() => {
384                // One fixed name, so an old wallpaper doesn't accumulate
385                // beside the new one in a directory nobody looks at.
386                let extension = source
387                    .extension()
388                    .and_then(|e| e.to_str())
389                    .unwrap_or("img");
390                let destination = dir.join(format!("wallpaper.{extension}"));
391                std::fs::copy(source, &destination).map_err(|source| ThemeError::Write {
392                    path: destination.display().to_string(),
393                    source,
394                })?;
395                Some(destination)
396            }
397            // A wallpaper that isn't there is dropped rather than
398            // exported as a dangling path: the greeter would fall back
399            // anyway, and a path that can't resolve invites someone to
400            // debug a permissions problem that doesn't exist.
401            _ => None,
402        };
403
404        let contents = toml::to_string_pretty(&exported)?;
405        let theme_path = dir.join("theme.toml");
406        hyprforge_paths::write_atomic(&theme_path, &contents).map_err(|source| {
407            ThemeError::Write {
408                path: theme_path.display().to_string(),
409                source,
410            }
411        })?;
412        Ok(exported)
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    /// The theme is a file a person can edit, so every number in it can
419    /// be nonsense — and a zero font size panics on the first frame
420    /// rather than looking wrong.
421    #[test]
422    fn a_font_size_that_cannot_be_drawn_is_brought_into_range() {
423        let sized = |size: f32| Theme { font_size: size, ..Theme::default() }.drawable_font_size();
424        assert_eq!(sized(15.0), 15.0, "an ordinary size is left alone");
425        assert_eq!(sized(0.0), 6.0);
426        assert_eq!(sized(4000.0), 48.0);
427        assert_eq!(sized(-3.0), 6.0);
428        assert_eq!(sized(f32::NAN), Theme::default().font_size, "not a number at all");
429        assert_eq!(sized(f32::INFINITY), Theme::default().font_size);
430    }
431
432    /// Hyprland's `decoration:rounding` has no upper bound, and a large
433    /// one turns a popup into a lozenge.
434    #[test]
435    fn rounding_is_bounded_to_something_still_shaped_like_a_popup() {
436        let rounded = |r: u32| Theme { rounding: r, ..Theme::default() }.corner_radius();
437        assert_eq!(rounded(12), 12.0);
438        assert_eq!(rounded(0), 0.0, "square corners are a choice");
439        assert_eq!(rounded(9999), 64.0);
440    }
441
442    use super::*;
443
444    fn theme_with_wallpaper(path: &Path) -> Theme {
445        Theme {
446            wallpaper: Some(path.to_path_buf()),
447            accent: Color::rgba(0xbd, 0x93, 0xf9, 0xff),
448            ..Theme::default()
449        }
450    }
451
452    #[test]
453    fn a_theme_round_trips_through_toml() {
454        let dir = tempfile::tempdir().unwrap();
455        let path = dir.path().join("theme.toml");
456        let theme = Theme { rounding: 20, dim: 0.5, ..Theme::default() };
457        std::fs::write(&path, toml::to_string_pretty(&theme).unwrap()).unwrap();
458        assert_eq!(Theme::load(&path).unwrap(), theme);
459    }
460
461    /// A greeter that won't draw is a machine nobody can log into, so a
462    /// missing theme is the default rather than an error.
463    #[test]
464    fn a_missing_theme_file_is_the_default_not_an_error() {
465        let dir = tempfile::tempdir().unwrap();
466        assert_eq!(Theme::load(&dir.path().join("nope.toml")).unwrap(), Theme::default());
467    }
468
469    /// Same reasoning, one step further: the greeter has nobody to report
470    /// an error to.
471    #[test]
472    fn an_unreadable_export_degrades_to_plain_rather_than_failing() {
473        let dir = tempfile::tempdir().unwrap();
474
475        // Nothing there at all: a machine where nothing has been exported.
476        assert_eq!(Theme::load_exported_from(dir.path()), Theme::default());
477
478        // There, and not parseable: a half-finished hand edit, or a write
479        // interrupted before this file was whole. A greeter has nobody to
480        // report the error to and nothing better to do than draw
481        // something usable.
482        std::fs::write(dir.path().join("theme.toml"), "accent = [not toml").unwrap();
483        assert_eq!(Theme::load_exported_from(dir.path()), Theme::default());
484    }
485
486    /// A partial file — a half-finished hand edit — must not take the
487    /// login screen down.
488    #[test]
489    fn a_partial_theme_file_fills_in_the_rest() {
490        let dir = tempfile::tempdir().unwrap();
491        let path = dir.path().join("theme.toml");
492        std::fs::write(&path, "rounding = 4\n").unwrap();
493        let theme = Theme::load(&path).unwrap();
494        assert_eq!(theme.rounding, 4);
495        assert_eq!(theme.accent, Theme::default().accent, "the rest defaults");
496    }
497
498    /// The whole point: a path into `$HOME` is unreachable from the
499    /// greeter, so the image is copied and the path rewritten.
500    #[test]
501    fn exporting_copies_the_wallpaper_and_repoints_at_the_copy() {
502        let dir = tempfile::tempdir().unwrap();
503        let home = dir.path().join("home/Pictures");
504        std::fs::create_dir_all(&home).unwrap();
505        let original = home.join("Dracula.png");
506        std::fs::write(&original, b"not really a png").unwrap();
507
508        let export = dir.path().join("export");
509        let exported = theme_with_wallpaper(&original).export(&export).unwrap();
510
511        let copy = exported.wallpaper.clone().unwrap();
512        assert!(copy.starts_with(&export), "the copy must live in the export: {copy:?}");
513        assert_ne!(copy, original, "the path must be rewritten");
514        assert_eq!(std::fs::read(&copy).unwrap(), b"not really a png");
515        assert!(original.exists(), "the original is left alone");
516    }
517
518    #[test]
519    fn the_exported_file_is_what_gets_loaded_back() {
520        let dir = tempfile::tempdir().unwrap();
521        let source = dir.path().join("w.png");
522        std::fs::write(&source, b"x").unwrap();
523        let export = dir.path().join("export");
524
525        let mut theme = theme_with_wallpaper(&source);
526        theme.rounding = 8;
527        let exported = theme.export(&export).unwrap();
528
529        assert_eq!(Theme::load(&export.join("theme.toml")).unwrap(), exported);
530    }
531
532    /// A dangling path invites someone to debug a permissions problem
533    /// that isn't there, so a wallpaper that doesn't exist is dropped.
534    #[test]
535    fn a_missing_wallpaper_is_dropped_rather_than_exported_dangling() {
536        let dir = tempfile::tempdir().unwrap();
537        let theme = theme_with_wallpaper(&dir.path().join("gone.png"));
538        let exported = theme.export(&dir.path().join("export")).unwrap();
539        assert_eq!(exported.wallpaper, None);
540    }
541
542    /// Exporting twice must replace the wallpaper rather than leave the
543    /// old one beside it in a directory nobody looks at.
544    #[test]
545    fn exporting_again_replaces_the_previous_wallpaper() {
546        let dir = tempfile::tempdir().unwrap();
547        let export = dir.path().join("export");
548        let first = dir.path().join("first.png");
549        let second = dir.path().join("second.png");
550        std::fs::write(&first, b"one").unwrap();
551        std::fs::write(&second, b"two").unwrap();
552
553        theme_with_wallpaper(&first).export(&export).unwrap();
554        let exported = theme_with_wallpaper(&second).export(&export).unwrap();
555
556        assert_eq!(std::fs::read(exported.wallpaper.unwrap()).unwrap(), b"two");
557        let images: Vec<_> = std::fs::read_dir(&export)
558            .unwrap()
559            .flatten()
560            .filter(|e| e.path().extension().is_some_and(|x| x == "png"))
561            .collect();
562        assert_eq!(images.len(), 1, "only one wallpaper should remain");
563    }
564
565    /// The on-disk spelling is a contract between three programs that
566    /// never run at the same time: Settings writes the file, the lock
567    /// screen reads it, and the greeter reads an exported copy as a
568    /// different user. A serde change that quietly altered the
569    /// representation would break the two readers with no compile error
570    /// anywhere, so it is pinned literally.
571    #[test]
572    fn colours_are_written_as_rgba_strings() {
573        let text = toml::to_string(&Theme::default()).unwrap();
574        assert!(text.contains(r#"accent = "rgba(bd93f9ff)""#), "{text}");
575        assert!(text.contains(r#"background = "rgba(16161eff)""#), "{text}");
576        assert!(text.contains(r#"card = "rgba(252731ff)""#), "{text}");
577    }
578
579    /// The default is what shows when everything else has failed. It has
580    /// to be legible on its own.
581    #[test]
582    fn the_default_theme_is_usable_without_any_file() {
583        let theme = Theme::default();
584        assert!(theme.wallpaper.is_none());
585        assert!(theme.font_size > 0.0);
586        // Typed colours make the old "is it a non-empty string" check
587        // meaningless, but the thing it was standing in for is now
588        // directly assertable: a fully transparent background or text
589        // renders nothing at all.
590        assert_eq!(theme.background.a, 0xff, "a transparent background shows nothing");
591        assert_eq!(theme.foreground.a, 0xff, "transparent text shows nothing");
592        assert_ne!(theme.background, theme.foreground, "text must be legible");
593        assert!((0.0..=1.0).contains(&theme.dim));
594    }
595}
596
597#[cfg(test)]
598mod shared_look {
599    use super::*;
600
601    /// The Settings app and the lock screen must resolve the same accent
602    /// from the same input.
603    ///
604    /// This test exists because its absence is precisely how they
605    /// diverged: one hardcoded `#9b8cf5` with a comment saying it
606    /// "matches this desktop's window-border accent", the other
607    /// defaulted to `#bd93f9`, and nothing anywhere compared them. They
608    /// now read one struct, so the only way to reintroduce the split is
609    /// to give one of them a second source — which this would catch.
610    #[test]
611    fn every_host_reads_the_accent_from_the_same_place() {
612        let theme = Theme {
613            accent: Color::rgba(0x12, 0x34, 0x56, 0xff),
614            ..Theme::default()
615        };
616
617        // What both the lock screen and the settings window build their
618        // iced palette from. Kept as the same field rather than a
619        // parallel one, which is the whole point.
620        assert_eq!(theme.accent, Color::parse("rgba(123456ff)").unwrap());
621
622        // And it survives the file the greeter reads, since that is the
623        // one hop where a mismatch would be invisible until login.
624        let round_tripped: Theme = toml::from_str(&toml::to_string(&theme).unwrap()).unwrap();
625        assert_eq!(round_tripped.accent, theme.accent);
626    }
627}
628
629#[cfg(test)]
630mod info_role {
631    use super::*;
632
633    /// A `lock.toml` written before `info` existed must still parse and
634    /// get the default, rather than failing and taking the lock screen
635    /// with it. Same property `#[serde(default)]` exists to guarantee
636    /// for every other field here, pinned for the one most recently
637    /// added — that is the one a future change is most likely to break.
638    #[test]
639    fn a_theme_file_written_before_info_existed_still_parses() {
640        let older = r#"
641            background = "rgba(16161eff)"
642            accent = "rgba(bd93f9ff)"
643            font_size = 15.0
644        "#;
645        let theme: Theme = toml::from_str(older).expect("an older theme file must still load");
646        assert_eq!(theme.accent, Color::rgba(0xbd, 0x93, 0xf9, 0xff), "what it did say is kept");
647        assert_eq!(theme.info, Theme::default().info, "what it did not say gets the default");
648    }
649
650    /// `info` is a state colour, and a state colour that equals another
651    /// one conveys nothing. The design's whole premise is that colour
652    /// means something; two roles sharing a value silently breaks that
653    /// without any test noticing.
654    #[test]
655    fn every_state_colour_is_distinguishable_from_the_others() {
656        let t = Theme::default();
657        let states = [("accent", t.accent), ("error", t.error), ("warning", t.warning), ("success", t.success), ("info", t.info)];
658        for (i, (name_a, a)) in states.iter().enumerate() {
659            for (name_b, b) in &states[i + 1..] {
660                assert_ne!(a, b, "{name_a} and {name_b} are the same colour, so neither means anything");
661            }
662        }
663    }
664}