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 colors, 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/// Cap (13.15+): the client takes screenshots of its window for the model
21/// ([`crate::ServerMsg::Capture`], answered with [`crate::ClientMsg::Captured`]).
22pub const CAP_CAPTURE: &str = "capture";
23
24/// Longest side of a screenshot a client sends, in pixels. Clients scale theirs down to it.
25pub const CAPTURE_SIDE: u32 = 1568;
26
27/// Most settings in a report, and the longest key, description and value text.
28pub const MAX_FIELDS: usize = 128;
29pub const MAX_KEY: usize = 64;
30pub const MAX_DESCRIBE: usize = 400;
31pub const MAX_THEMES: usize = 200;
32pub const MAX_PROBLEMS: usize = 32;
33/// Most notes in a report, and the longest note.
34pub const MAX_NOTES: usize = 8;
35pub const MAX_NOTE: usize = 20 * 1024;
36
37/// One setting of a window's look.
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct LookField {
40    /// Its key in [`crate::ServerMsg::SetLook`] (`accent`, `corners`, `color.app_bg`, …).
41    pub key: String,
42    /// What it is now (a string, number or bool).
43    pub value: Value,
44    /// What it is and what it may be, for the model.
45    pub describe: String,
46}
47
48/// A theme a window can use.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct ThemeChoice {
51    pub id: String,
52    pub name: String,
53    pub dark: bool,
54}
55
56/// A window's look: [`crate::ClientMsg::ReportLook`].
57#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
58pub struct LookReport {
59    pub fields: Vec<LookField>,
60    #[serde(default, skip_serializing_if = "Vec::is_empty")]
61    pub themes: Vec<ThemeChoice>,
62    /// The [`crate::ServerMsg::SetLook`] this report answers.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub answered: Option<u64>,
65    /// What of that request couldn't be applied, and why.
66    #[serde(default, skip_serializing_if = "Vec::is_empty")]
67    pub problems: Vec<String>,
68    /// Longer texts for the model, by name: how to write a setting's value (a backdrop
69    /// shader's guide), or a value too long for a field (the backdrop's source).
70    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
71    pub notes: BTreeMap<String, String>,
72}
73
74impl LookReport {
75    /// Cut what a client sent to size.
76    #[must_use]
77    pub fn sanitized(mut self) -> Self {
78        let cut = |s: &mut String, n: usize| {
79            if s.len() > n {
80                let mut end = n;
81                while !s.is_char_boundary(end) {
82                    end -= 1;
83                }
84                s.truncate(end);
85            }
86        };
87        self.fields.truncate(MAX_FIELDS);
88        self.fields.retain(|f| !f.key.is_empty() && f.key.len() <= MAX_KEY && !matches!(f.value, Value::Object(_) | Value::Array(_)));
89        for f in &mut self.fields {
90            cut(&mut f.describe, MAX_DESCRIBE);
91            if let Value::String(s) = &mut f.value {
92                cut(s, MAX_DESCRIBE);
93            }
94        }
95        self.themes.truncate(MAX_THEMES);
96        for t in &mut self.themes {
97            cut(&mut t.id, MAX_KEY * 2);
98            cut(&mut t.name, MAX_KEY * 2);
99        }
100        self.problems.truncate(MAX_PROBLEMS);
101        for p in &mut self.problems {
102            cut(p, MAX_DESCRIBE);
103        }
104        let keys: Vec<String> = self.notes.keys().skip(MAX_NOTES).cloned().collect();
105        for k in keys {
106            self.notes.remove(&k);
107        }
108        self.notes.retain(|k, _| !k.is_empty() && k.len() <= MAX_KEY);
109        for n in self.notes.values_mut() {
110            cut(n, MAX_NOTE);
111        }
112        self
113    }
114
115    pub fn get(&self, key: &str) -> Option<&Value> {
116        self.fields.iter().find(|f| f.key == key).map(|f| &f.value)
117    }
118
119    /// What differs from `before`: (key, before, now).
120    pub fn changes_since(&self, before: &Self) -> Vec<(String, Value, Value)> {
121        self.fields
122            .iter()
123            .filter_map(|f| {
124                let old = before.get(&f.key).cloned().unwrap_or(Value::Null);
125                (old != f.value).then(|| (f.key.clone(), old, f.value.clone()))
126            })
127            .collect()
128    }
129}
130
131/// Changes to a look by key: [`crate::ServerMsg::SetLook`].
132pub type LookChanges = BTreeMap<String, Value>;
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use serde_json::json;
138
139    fn field(key: &str, value: Value) -> LookField {
140        LookField { key: key.into(), value, describe: String::new() }
141    }
142
143    #[test]
144    fn reports_are_cut_to_size_and_diffed() {
145        let mut r =
146            LookReport { fields: vec![field("accent", json!("theme")), field("corners", json!(8)), field("bad", json!({"a": 1}))], ..Default::default() };
147        r.fields.push(LookField { key: "x".repeat(MAX_KEY + 1), value: json!(1), describe: String::new() });
148        r.problems = vec!["é".repeat(MAX_DESCRIBE)];
149        r.notes = (0..MAX_NOTES + 2).map(|i| (format!("n{i:02}"), "w".repeat(MAX_NOTE + 1))).collect();
150        let r = r.sanitized();
151        assert_eq!(r.fields.len(), 2);
152        assert!(r.problems[0].len() <= MAX_DESCRIBE);
153        assert_eq!(r.notes.len(), MAX_NOTES);
154        assert!(r.notes.values().all(|n| n.len() == MAX_NOTE));
155        let mut now = r.clone();
156        now.fields[1].value = json!(12);
157        assert_eq!(now.changes_since(&r), [("corners".to_owned(), json!(8), json!(12))]);
158    }
159}