Skip to main content

byob_protocol/
look.rs

1//! A window's look on the wire (13.12+, cap [`CAP_LOOK`]): its theme, accent, corners, text
2//! size, bubbles and colours, which each device keeps for itself.
3//!
4//! The client is the authority on its own look: it sends [`crate::ClientMsg::ReportLook`]
5//! once connected and after every change, listing each setting with its value and what it
6//! may be. The engine keeps the latest report of each client and offers them to the model
7//! (the `ui_look` tool); a change the model asks for goes to the windows showing the chat as
8//! [`crate::ServerMsg::SetLook`], and each answers with a fresh report naming the request
9//! (`answered`) and anything it couldn't apply (`problems`). Another kind of client can
10//! report settings of its own: the engine only passes them on.
11
12use std::collections::BTreeMap;
13
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17/// Cap: the peer reports and applies looks.
18pub const CAP_LOOK: &str = "look";
19
20/// Most settings in a report, and the longest key, description and value text.
21pub const MAX_FIELDS: usize = 128;
22pub const MAX_KEY: usize = 64;
23pub const MAX_DESCRIBE: usize = 400;
24pub const MAX_THEMES: usize = 200;
25pub const MAX_PROBLEMS: usize = 32;
26/// Most notes in a report, and the longest note.
27pub const MAX_NOTES: usize = 8;
28pub const MAX_NOTE: usize = 20 * 1024;
29
30/// One setting of a window's look.
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub struct LookField {
33    /// Its key in [`crate::ServerMsg::SetLook`] (`accent`, `corners`, `colour.app_bg`, …).
34    pub key: String,
35    /// What it is now (a string, number or bool).
36    pub value: Value,
37    /// What it is and what it may be, for the model.
38    pub describe: String,
39}
40
41/// A theme a window can use.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct ThemeChoice {
44    pub id: String,
45    pub name: String,
46    pub dark: bool,
47}
48
49/// A window's look: [`crate::ClientMsg::ReportLook`].
50#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
51pub struct LookReport {
52    pub fields: Vec<LookField>,
53    #[serde(default, skip_serializing_if = "Vec::is_empty")]
54    pub themes: Vec<ThemeChoice>,
55    /// The [`crate::ServerMsg::SetLook`] this report answers.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub answered: Option<u64>,
58    /// What of that request couldn't be applied, and why.
59    #[serde(default, skip_serializing_if = "Vec::is_empty")]
60    pub problems: Vec<String>,
61    /// Longer texts for the model, by name: how to write a setting's value (a backdrop
62    /// shader's guide), or a value too long for a field (the backdrop's source).
63    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
64    pub notes: BTreeMap<String, String>,
65}
66
67impl LookReport {
68    /// Cut what a client sent to size.
69    #[must_use]
70    pub fn sanitized(mut self) -> Self {
71        let cut = |s: &mut String, n: usize| {
72            if s.len() > n {
73                let mut end = n;
74                while !s.is_char_boundary(end) {
75                    end -= 1;
76                }
77                s.truncate(end);
78            }
79        };
80        self.fields.truncate(MAX_FIELDS);
81        self.fields.retain(|f| !f.key.is_empty() && f.key.len() <= MAX_KEY && !matches!(f.value, Value::Object(_) | Value::Array(_)));
82        for f in &mut self.fields {
83            cut(&mut f.describe, MAX_DESCRIBE);
84            if let Value::String(s) = &mut f.value {
85                cut(s, MAX_DESCRIBE);
86            }
87        }
88        self.themes.truncate(MAX_THEMES);
89        for t in &mut self.themes {
90            cut(&mut t.id, MAX_KEY * 2);
91            cut(&mut t.name, MAX_KEY * 2);
92        }
93        self.problems.truncate(MAX_PROBLEMS);
94        for p in &mut self.problems {
95            cut(p, MAX_DESCRIBE);
96        }
97        let keys: Vec<String> = self.notes.keys().skip(MAX_NOTES).cloned().collect();
98        for k in keys {
99            self.notes.remove(&k);
100        }
101        self.notes.retain(|k, _| !k.is_empty() && k.len() <= MAX_KEY);
102        for n in self.notes.values_mut() {
103            cut(n, MAX_NOTE);
104        }
105        self
106    }
107
108    pub fn get(&self, key: &str) -> Option<&Value> {
109        self.fields.iter().find(|f| f.key == key).map(|f| &f.value)
110    }
111
112    /// What differs from `before`: (key, before, now).
113    pub fn changes_since(&self, before: &Self) -> Vec<(String, Value, Value)> {
114        self.fields
115            .iter()
116            .filter_map(|f| {
117                let old = before.get(&f.key).cloned().unwrap_or(Value::Null);
118                (old != f.value).then(|| (f.key.clone(), old, f.value.clone()))
119            })
120            .collect()
121    }
122}
123
124/// Changes to a look by key: [`crate::ServerMsg::SetLook`].
125pub type LookChanges = BTreeMap<String, Value>;
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use serde_json::json;
131
132    fn field(key: &str, value: Value) -> LookField {
133        LookField { key: key.into(), value, describe: String::new() }
134    }
135
136    #[test]
137    fn reports_are_cut_to_size_and_diffed() {
138        let mut r =
139            LookReport { fields: vec![field("accent", json!("theme")), field("corners", json!(8)), field("bad", json!({"a": 1}))], ..Default::default() };
140        r.fields.push(LookField { key: "x".repeat(MAX_KEY + 1), value: json!(1), describe: String::new() });
141        r.problems = vec!["é".repeat(MAX_DESCRIBE)];
142        r.notes = (0..MAX_NOTES + 2).map(|i| (format!("n{i:02}"), "w".repeat(MAX_NOTE + 1))).collect();
143        let r = r.sanitized();
144        assert_eq!(r.fields.len(), 2);
145        assert!(r.problems[0].len() <= MAX_DESCRIBE);
146        assert_eq!(r.notes.len(), MAX_NOTES);
147        assert!(r.notes.values().all(|n| n.len() == MAX_NOTE));
148        let mut now = r.clone();
149        now.fields[1].value = json!(12);
150        assert_eq!(now.changes_since(&r), [("corners".to_owned(), json!(8), json!(12))]);
151    }
152}