Skip to main content

mochi_protocol/
theme.rs

1//! Design tokens the UI reads from its `Theme` singleton. Users override them
2//! in `theme.toml`; anything they leave out keeps the default below.
3
4use std::fmt;
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use crate::Area;
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
12#[serde(default, deny_unknown_fields)]
13pub struct Theme {
14    /// A named palette for every color role, in a dark and a light
15    /// version; `wallpaper` makes one from the wallpaper. What `[colors]`
16    /// sets goes over it.
17    #[schemars(extend("enum" = ["obsidian", "catppuccin", "nord", "gruvbox", "rose-pine", "tokyo-night", "wallpaper"]))]
18    pub preset: String,
19    pub appearance: Appearance,
20    /// The image the `wallpaper` preset reads, or `auto` for the one awww,
21    /// swww or hyprpaper shows.
22    #[schemars(extend("x-source" = "file", "x-filter" = "image"))]
23    pub wallpaper: String,
24    pub colors: Colors,
25    pub layout: Layout,
26    pub motion: Motion,
27    pub text: Text,
28}
29
30impl Default for Theme {
31    fn default() -> Self {
32        Self {
33            preset: "obsidian".to_owned(),
34            appearance: Appearance::default(),
35            wallpaper: "auto".to_owned(),
36            colors: Colors::default(),
37            layout: Layout::default(),
38            motion: Motion::default(),
39            text: Text::default(),
40        }
41    }
42}
43
44/// Which of a preset's palettes to use.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
46#[serde(rename_all = "lowercase")]
47pub enum Appearance {
48    /// The dark palette.
49    #[default]
50    Dark,
51    /// The light palette.
52    Light,
53    /// Light or dark as the system prefers, through the desktop portal.
54    Auto,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
58#[serde(default, deny_unknown_fields)]
59/// Color roles. The defaults are "Obsidian": a black island that blends into
60/// the bezel, graphite layers on it, and one accent used sparingly.
61pub struct Colors {
62    /// The island and the control center panel.
63    pub background: Color,
64    /// Cards and tiles on the background.
65    pub surface: Color,
66    /// Controls, tracks and dividers: one step above `surface`.
67    pub raised: Color,
68    /// Hovered or pressed controls: one step above `raised`.
69    pub highlight: Color,
70    pub foreground: Color,
71    /// Secondary text and icons.
72    pub muted: Color,
73    /// Active, selected or important things, and nothing else.
74    pub accent: Color,
75    /// Text and icons on `accent`.
76    pub on_accent: Color,
77    /// Destructive actions, like a shut down waiting for its second click.
78    pub danger: Color,
79    pub success: Color,
80    /// The hairline around the island and the bubbles.
81    pub border: Color,
82    /// The shadow under them. Transparent turns it off.
83    pub shadow: Color,
84}
85
86impl Default for Colors {
87    fn default() -> Self {
88        Self {
89            background: Color::fixed("#f5000000"),
90            surface: Color::fixed("#1c1c1e"),
91            raised: Color::fixed("#2c2c2e"),
92            highlight: Color::fixed("#3a3a3c"),
93            foreground: Color::fixed("#ffffff"),
94            muted: Color::fixed("#8e8e93"),
95            accent: Color::fixed("#ff9f0a"),
96            on_accent: Color::fixed("#000000"),
97            danger: Color::fixed("#ff453a"),
98            success: Color::fixed("#30d158"),
99            border: Color::fixed("#0dffffff"),
100            shadow: Color::fixed("#59000000"),
101        }
102    }
103}
104
105/// Where the island sits and what shape it takes. Sizes in logical pixels.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
107#[serde(default, deny_unknown_fields)]
108pub struct Layout {
109    pub mode: Mode,
110    /// The screen edge the island and the bubbles sit against.
111    pub anchor: Anchor,
112    /// The area the island sits in.
113    pub island: Area,
114    /// Gap between the screen edges and everything on them in island mode.
115    /// Notch and bar modes always touch the edge.
116    #[serde(alias = "top_margin")]
117    #[schemars(range(min = 0, max = 48))]
118    pub margin: u32,
119    /// Gap between the island and bubbles, and between areas that meet.
120    #[schemars(range(min = 0, max = 32))]
121    pub spacing: u32,
122    /// Height of the idle island and of bubbles. Windows make room for this
123    /// much.
124    #[schemars(range(min = 20, max = 64))]
125    pub idle_height: u32,
126    #[schemars(range(min = 4, max = 32))]
127    pub padding: u32,
128    /// Largest corner radius. Short islands are fully rounded pills.
129    #[schemars(range(min = 0, max = 48))]
130    pub max_radius: u32,
131    /// Corners of small controls: chips, badges, icon buttons.
132    #[schemars(range(min = 0, max = 24))]
133    pub radius_small: u32,
134    /// Corners of rows and buttons.
135    #[schemars(range(min = 0, max = 32))]
136    pub radius_medium: u32,
137    /// Corners of cards and tiles.
138    #[schemars(range(min = 0, max = 40))]
139    pub radius_large: u32,
140    /// The tallest the island can grow, in pixels.
141    #[schemars(range(min = 200, max = 1600))]
142    pub surface_height: u32,
143    pub notch: Notch,
144}
145
146impl Default for Layout {
147    fn default() -> Self {
148        Self {
149            mode: Mode::Island,
150            anchor: Anchor::Top,
151            island: Area::Center,
152            margin: 6,
153            spacing: 8,
154            idle_height: 34,
155            padding: 14,
156            max_radius: 34,
157            radius_small: 8,
158            radius_medium: 14,
159            radius_large: 20,
160            surface_height: 640,
161            notch: Notch::default(),
162        }
163    }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
167#[serde(rename_all = "kebab-case")]
168pub enum Mode {
169    /// Floats apart from the edge, rounded all around.
170    #[default]
171    Island,
172    /// Attached to the edge, with concave corners flaring into it.
173    Notch,
174    /// A strip along the whole edge with the bubbles on it, and the island
175    /// in it, growing out of it like a notch.
176    Bar,
177}
178
179/// The screen edge everything sits against.
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
181#[serde(rename_all = "kebab-case")]
182pub enum Anchor {
183    #[default]
184    Top,
185    Bottom,
186}
187
188/// Settings for notch and bar modes.
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
190#[serde(default, deny_unknown_fields)]
191pub struct Notch {
192    /// Radius of the concave corners where the notch meets the edge, and
193    /// where the island leaves the bar.
194    #[schemars(range(min = 0, max = 32))]
195    pub ear_radius: u32,
196}
197
198impl Default for Notch {
199    fn default() -> Self {
200        Self { ear_radius: 10 }
201    }
202}
203
204/// Animation constants. The spring values feed QML's `SpringAnimation`.
205#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
206#[serde(default, deny_unknown_fields)]
207pub struct Motion {
208    /// Turns animations off: views appear and change at once, and the
209    /// island takes its new shape without a spring.
210    pub reduced: bool,
211    /// How fast every animation runs: 2 is twice as fast, 0.5 half.
212    #[schemars(range(min = 0.25, max = 3.0))]
213    pub speed: f64,
214    #[schemars(range(min = 0.5, max = 12.0))]
215    pub spring: f64,
216    /// Between 0 and 1. Lower values bounce more.
217    #[schemars(range(min = 0.05, max = 1.0))]
218    pub damping: f64,
219    #[schemars(range(min = 0, max = 1000))]
220    pub fade_in_ms: u32,
221    #[schemars(range(min = 0, max = 1000))]
222    pub fade_out_ms: u32,
223    /// How long the new view waits before fading in, so the shape moves
224    /// first.
225    #[schemars(range(min = 0, max = 500))]
226    pub fade_delay_ms: u32,
227    /// Small state changes: colors, hovers.
228    #[schemars(range(min = 0, max = 600))]
229    pub fast_ms: u32,
230    /// Things moving or resizing inside a view, with a slight overshoot.
231    #[schemars(range(min = 0, max = 1200))]
232    pub move_ms: u32,
233    /// Progress lines and rings wave while something goes on: the media
234    /// line while a track plays, the battery ring while it charges, the
235    /// timer's ring while it runs. Off draws every one of them flat; each
236    /// module with a wave can also turn off its own.
237    pub waves: bool,
238    /// How far a mouse wheel's step scrolls a list, in pixels.
239    #[schemars(range(min = 20, max = 600))]
240    pub scroll_step: u32,
241    /// A wheel's steps glide instead of jumping, and a touchpad's scroll
242    /// coasts on after the fingers lift. Off scrolls the way Qt does by
243    /// itself.
244    pub smooth_scroll: bool,
245}
246
247impl Default for Motion {
248    fn default() -> Self {
249        Self {
250            reduced: false,
251            speed: 1.0,
252            spring: 4.0,
253            damping: 0.32,
254            fade_in_ms: 220,
255            fade_out_ms: 120,
256            fade_delay_ms: 90,
257            fast_ms: 150,
258            move_ms: 350,
259            waves: true,
260            scroll_step: 120,
261            smooth_scroll: true,
262        }
263    }
264}
265
266/// The type scale, in pixels: four sizes and one for big numbers. An empty
267/// `family` uses Inter, which Mochi's packages bring, or the system font
268/// without it; an empty `display_family` keeps `family`.
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
270#[serde(default, deny_unknown_fields)]
271pub struct Text {
272    #[schemars(extend("format" = "font"))]
273    pub family: String,
274    /// For the clocks, on the idle island and in the control center.
275    #[schemars(extend("format" = "font"))]
276    pub display_family: String,
277    /// Labels, metadata and fine print.
278    #[schemars(range(min = 8, max = 20))]
279    pub caption: u32,
280    /// Everything else: rows, buttons, messages.
281    #[schemars(range(min = 9, max = 24))]
282    pub body: u32,
283    /// Card, track and section titles.
284    #[schemars(range(min = 10, max = 32))]
285    pub title: u32,
286    /// Page titles.
287    #[schemars(range(min = 12, max = 48))]
288    pub headline: u32,
289    /// Big numbers, like a clock.
290    #[schemars(range(min = 20, max = 96))]
291    pub display: u32,
292    /// Before 0.0.7's scale: read as `caption`. Not sent to the UI.
293    #[serde(skip_serializing)]
294    #[schemars(skip)]
295    pub label: Option<u32>,
296    /// Before 0.0.7's scale: read as `body`. Not sent to the UI.
297    #[serde(skip_serializing)]
298    #[schemars(skip)]
299    pub subtitle: Option<u32>,
300}
301
302impl Text {
303    /// Applies the keys the scale replaced, and says which ones were used.
304    pub fn migrate(&mut self) -> Vec<String> {
305        let mut notes = Vec::new();
306        if let Some(label) = self.label {
307            self.caption = label;
308            notes.push("`text.label` is now `text.caption`".to_owned());
309        }
310        if let Some(subtitle) = self.subtitle {
311            self.body = subtitle;
312            notes.push("`text.subtitle` is now `text.body`".to_owned());
313        }
314        notes
315    }
316}
317
318impl Default for Text {
319    fn default() -> Self {
320        Self {
321            family: String::new(),
322            display_family: String::new(),
323            caption: 11,
324            body: 13,
325            title: 15,
326            headline: 20,
327            display: 42,
328            label: None,
329            subtitle: None,
330        }
331    }
332}
333
334/// A color in the form QML accepts: `#rrggbb` or `#aarrggbb`.
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(try_from = "String", into = "String")]
337pub struct Color(String);
338
339impl Color {
340    pub fn as_str(&self) -> &str {
341        &self.0
342    }
343
344    /// For the defaults above, which are known to be valid.
345    fn fixed(value: &str) -> Self {
346        Self::try_from(value.to_owned()).expect("default colors are valid")
347    }
348}
349
350impl JsonSchema for Color {
351    fn schema_name() -> std::borrow::Cow<'static, str> {
352        "Color".into()
353    }
354
355    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
356        schemars::json_schema!({ "type": "string", "format": "color" })
357    }
358}
359
360impl TryFrom<String> for Color {
361    type Error = ColorError;
362
363    fn try_from(value: String) -> Result<Self, Self::Error> {
364        let digits = value.strip_prefix('#').ok_or(ColorError(value.clone()))?;
365        let valid = matches!(digits.len(), 6 | 8) && digits.bytes().all(|b| b.is_ascii_hexdigit());
366        if !valid {
367            return Err(ColorError(value));
368        }
369        Ok(Self(value.to_ascii_lowercase()))
370    }
371}
372
373impl From<Color> for String {
374    fn from(color: Color) -> Self {
375        color.0
376    }
377}
378
379impl fmt::Display for Color {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        f.write_str(&self.0)
382    }
383}
384
385#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
386#[error("{0:?} is not a color, expected #rrggbb or #aarrggbb")]
387pub struct ColorError(String);
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    #[test]
394    fn colors_accept_both_qml_forms() {
395        assert!(Color::try_from("#1a2B3c".to_owned()).is_ok());
396        assert!(Color::try_from("#801a2b3c".to_owned()).is_ok());
397        assert_eq!(
398            Color::try_from("#ABCDEF".to_owned()).unwrap().as_str(),
399            "#abcdef"
400        );
401    }
402
403    #[test]
404    fn colors_reject_other_forms() {
405        for value in ["1a2b3c", "#abc", "#1a2b3g", "red", "#1a2b3c4"] {
406            assert!(Color::try_from(value.to_owned()).is_err(), "{value}");
407        }
408    }
409
410    #[test]
411    fn missing_sections_and_fields_keep_their_defaults() {
412        let theme: Theme =
413            serde_json::from_str(r##"{"colors":{"accent":"#30d158"},"motion":{"damping":0.5}}"##)
414                .unwrap();
415        assert_eq!(theme.colors.accent.as_str(), "#30d158");
416        assert_eq!(theme.colors.background, Colors::default().background);
417        assert_eq!(theme.motion.damping, 0.5);
418        assert_eq!(theme.motion.spring, Motion::default().spring);
419        assert_eq!(theme.layout, Layout::default());
420    }
421
422    #[test]
423    fn layout_reads_modes_anchors_and_the_old_margin_name() {
424        let theme: Theme = serde_json::from_str(
425            r#"{"layout":{"mode":"notch","anchor":"bottom","island":"left","top_margin":4,"notch":{"ear_radius":8}}}"#,
426        )
427        .unwrap();
428        assert_eq!(theme.layout.mode, Mode::Notch);
429        assert_eq!(theme.layout.anchor, Anchor::Bottom);
430        assert_eq!(theme.layout.island, Area::Left);
431        assert_eq!(theme.layout.margin, 4);
432        assert_eq!(theme.layout.notch.ear_radius, 8);
433
434        let theme: Theme = serde_json::from_str(r#"{"layout":{"mode":"bar"}}"#).unwrap();
435        assert_eq!(theme.layout.mode, Mode::Bar);
436
437        let error = serde_json::from_str::<Theme>(r#"{"layout":{"anchor":"top-left"}}"#)
438            .unwrap_err()
439            .to_string();
440        assert!(error.contains("top-left"), "{error}");
441    }
442
443    #[test]
444    fn unknown_tokens_are_rejected() {
445        let error = serde_json::from_str::<Theme>(r##"{"colors":{"acent":"#30d158"}}"##)
446            .unwrap_err()
447            .to_string();
448        assert!(error.contains("acent"), "{error}");
449    }
450}