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
27/// One setting of a window's look.
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct LookField {
30    /// Its key in [`crate::ServerMsg::SetLook`] (`accent`, `corners`, `colour.app_bg`, …).
31    pub key: String,
32    /// What it is now (a string, number or bool).
33    pub value: Value,
34    /// What it is and what it may be, for the model.
35    pub describe: String,
36}
37
38/// A theme a window can use.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct ThemeChoice {
41    pub id: String,
42    pub name: String,
43    pub dark: bool,
44}
45
46/// A window's look: [`crate::ClientMsg::ReportLook`].
47#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
48pub struct LookReport {
49    pub fields: Vec<LookField>,
50    #[serde(default, skip_serializing_if = "Vec::is_empty")]
51    pub themes: Vec<ThemeChoice>,
52    /// The [`crate::ServerMsg::SetLook`] this report answers.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub answered: Option<u64>,
55    /// What of that request couldn't be applied, and why.
56    #[serde(default, skip_serializing_if = "Vec::is_empty")]
57    pub problems: Vec<String>,
58}
59
60impl LookReport {
61    /// Cut what a client sent to size.
62    #[must_use]
63    pub fn sanitized(mut self) -> Self {
64        let cut = |s: &mut String, n: usize| {
65            if s.len() > n {
66                let mut end = n;
67                while !s.is_char_boundary(end) {
68                    end -= 1;
69                }
70                s.truncate(end);
71            }
72        };
73        self.fields.truncate(MAX_FIELDS);
74        self.fields.retain(|f| !f.key.is_empty() && f.key.len() <= MAX_KEY && !matches!(f.value, Value::Object(_) | Value::Array(_)));
75        for f in &mut self.fields {
76            cut(&mut f.describe, MAX_DESCRIBE);
77            if let Value::String(s) = &mut f.value {
78                cut(s, MAX_DESCRIBE);
79            }
80        }
81        self.themes.truncate(MAX_THEMES);
82        for t in &mut self.themes {
83            cut(&mut t.id, MAX_KEY * 2);
84            cut(&mut t.name, MAX_KEY * 2);
85        }
86        self.problems.truncate(MAX_PROBLEMS);
87        for p in &mut self.problems {
88            cut(p, MAX_DESCRIBE);
89        }
90        self
91    }
92
93    pub fn get(&self, key: &str) -> Option<&Value> {
94        self.fields.iter().find(|f| f.key == key).map(|f| &f.value)
95    }
96
97    /// What differs from `before`: (key, before, now).
98    pub fn changes_since(&self, before: &Self) -> Vec<(String, Value, Value)> {
99        self.fields
100            .iter()
101            .filter_map(|f| {
102                let old = before.get(&f.key).cloned().unwrap_or(Value::Null);
103                (old != f.value).then(|| (f.key.clone(), old, f.value.clone()))
104            })
105            .collect()
106    }
107}
108
109/// Changes to a look by key: [`crate::ServerMsg::SetLook`].
110pub type LookChanges = BTreeMap<String, Value>;
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use serde_json::json;
116
117    fn field(key: &str, value: Value) -> LookField {
118        LookField { key: key.into(), value, describe: String::new() }
119    }
120
121    #[test]
122    fn reports_are_cut_to_size_and_diffed() {
123        let mut r =
124            LookReport { fields: vec![field("accent", json!("theme")), field("corners", json!(8)), field("bad", json!({"a": 1}))], ..Default::default() };
125        r.fields.push(LookField { key: "x".repeat(MAX_KEY + 1), value: json!(1), describe: String::new() });
126        r.problems = vec!["é".repeat(MAX_DESCRIBE)];
127        let r = r.sanitized();
128        assert_eq!(r.fields.len(), 2);
129        assert!(r.problems[0].len() <= MAX_DESCRIBE);
130        let mut now = r.clone();
131        now.fields[1].value = json!(12);
132        assert_eq!(now.changes_since(&r), [("corners".to_owned(), json!(8), json!(12))]);
133    }
134}