Skip to main content

devpage_design/wire/
mod.rs

1//! Scenes and their edits on the wire: a scene to its `proto::Scene` and
2//! back, and [`Edits`](crate::scene::Edits) to the `proto::Patch` the watch
3//! stream sends and back ([`patch`]). Each image file and font file travels
4//! once: a scene carries every one its nodes use, a patch only those the
5//! scene before it didn't have. It does no I/O.
6
7use std::collections::BTreeSet;
8use std::sync::Arc;
9
10use crate::fonts::{FontFile, FontFiles, FontId};
11use crate::proto;
12use crate::scene::{
13    Align, Color, Fill, Image, ImageFile, ImageFiles, ImageId, Kind, Layout, Node, Origin, Rgba,
14    Scene, Shadow, Size, TextAlign, TextStyle, Vector,
15};
16use crate::tree::{Children, NodeId};
17
18/// A color for the wire: its red, green, blue and alpha as one word, red the
19/// highest byte.
20fn word(c: Rgba) -> u32 {
21    u32::from_be_bytes([c.r, c.g, c.b, c.a])
22}
23
24/// A color from the wire's word, red its highest byte.
25fn unword(v: u32) -> Rgba {
26    let [r, g, b, a] = v.to_be_bytes();
27    Rgba { r, g, b, a }
28}
29
30/// A color for the wire: its light and its dark value.
31fn rgba(c: Color) -> proto::Color {
32    proto::Color {
33        light: word(c.light),
34        dark: word(c.dark),
35    }
36}
37
38/// A color from the wire; one the stream left out is transparent.
39fn color(c: Option<proto::Color>) -> Color {
40    let c = c.unwrap_or_default();
41    Color {
42        light: unword(c.light),
43        dark: unword(c.dark),
44    }
45}
46
47/// A size for the wire: pixels as they are, `-1` for hug and `-2` for fill.
48fn size(s: Size) -> f32 {
49    match s {
50        Size::Px(v) => v,
51        Size::Hug => -1.0,
52        Size::Fill => -2.0,
53    }
54}
55
56/// A size from the wire: `-1` is hug, `-2` fill and anything else pixels.
57fn unsize(v: f32) -> Size {
58    if v == -1.0 {
59        Size::Hug
60    } else if v == -2.0 {
61        Size::Fill
62    } else {
63        Size::Px(v)
64    }
65}
66
67/// `a` as the wire's enum, one value for each.
68fn align(a: Align) -> proto::Align {
69    match a {
70        Align::Start => proto::Align::Start,
71        Align::Center => proto::Align::Center,
72        Align::End => proto::Align::End,
73        Align::SpaceBetween => proto::Align::SpaceBetween,
74    }
75}
76
77/// An alignment from the wire; one it doesn't know is the start.
78fn unalign(a: i32) -> Align {
79    match proto::Align::try_from(a).unwrap_or(proto::Align::Start) {
80        proto::Align::Start => Align::Start,
81        proto::Align::Center => Align::Center,
82        proto::Align::End => Align::End,
83        proto::Align::SpaceBetween => Align::SpaceBetween,
84    }
85}
86
87/// A node for the wire, with everything under it.
88pub fn encode(n: &Node) -> proto::Node {
89    proto::Node {
90        kind: match n.kind {
91            Kind::Frame => proto::Kind::Frame,
92            Kind::Text => proto::Kind::Text,
93            Kind::Rect => proto::Kind::Rect,
94            Kind::Ellipse => proto::Kind::Ellipse,
95            Kind::Vector => proto::Kind::Vector,
96            Kind::Image => proto::Kind::Image,
97        } as i32,
98        name: n.name.clone(),
99        x: n.x,
100        y: n.y,
101        width: size(n.width),
102        height: size(n.height),
103        opacity: n.opacity,
104        on_click: n.on_click.clone().unwrap_or_default(),
105        fill: match &n.fill {
106            Some(Fill::Solid(c)) => Some(rgba(*c)),
107            _ => None,
108        },
109        gradient: match &n.fill {
110            Some(Fill::Linear { angle, stops }) => Some(proto::Gradient {
111                angle: *angle,
112                stops: stops
113                    .iter()
114                    .map(|(c, at)| proto::Stop {
115                        color: Some(rgba(*c)),
116                        at: *at,
117                    })
118                    .collect(),
119            }),
120            _ => None,
121        },
122        vector: n.vector.as_ref().map(|v| proto::Vector {
123            d: v.d.clone(),
124            view_box: v.view_box.to_vec(),
125        }),
126        image: n.image.as_ref().map(|i| proto::Image {
127            src: i.src.clone(),
128            id: i.id.0.to_vec(),
129        }),
130        stroke: n.stroke.map(rgba),
131        stroke_width: n.stroke_width,
132        radius: n.radius.to_vec(),
133        shadow: n.shadow.as_ref().map(|s| proto::Shadow {
134            x: s.x,
135            y: s.y,
136            blur: s.blur,
137            spread: s.spread,
138            color: Some(rgba(s.color)),
139        }),
140        clip: n.clip,
141        layout: match n.layout {
142            Layout::None => proto::Layout::None,
143            Layout::Row => proto::Layout::Row,
144            Layout::Column => proto::Layout::Column,
145        } as i32,
146        gap: n.gap,
147        padding: n.padding.to_vec(),
148        align: align(n.align) as i32,
149        justify: align(n.justify) as i32,
150        text: n.text.as_ref().map(|t| proto::Text {
151            font: t.font.map(|id| id.0.to_vec()).unwrap_or_default(),
152            content: t.content.clone(),
153            size: t.size,
154            weight: t.weight as u32,
155            color: Some(rgba(t.color)),
156            line_height: t.line_height,
157            align: match t.align {
158                TextAlign::Left => proto::TextAlign::Left,
159                TextAlign::Center => proto::TextAlign::Center,
160                TextAlign::Right => proto::TextAlign::Right,
161            } as i32,
162        }),
163        children: n.children.iter().map(encode).collect(),
164        id: Some(node_id(&n.id)),
165    }
166}
167
168/// A node's own attributes for the wire: its children aside.
169pub fn encode_own(n: &Node) -> proto::Node {
170    let mut own = n.clone();
171    own.children.clear();
172    encode(&own)
173}
174
175/// `id` for the wire: its path of element ids, from the root through each
176/// instance, copied as is.
177fn node_id(id: &NodeId) -> proto::NodeId {
178    proto::NodeId { path: id.0.clone() }
179}
180
181/// A node's id from the wire, or that the node has none.
182fn unnode_id(id: Option<&proto::NodeId>) -> Result<NodeId, String> {
183    id.map(|i| NodeId(i.path.clone()))
184        .ok_or_else(|| "a node with no id".to_string())
185}
186
187/// An image file's id from the wire's `bytes` — its SHA-256, so 32 of them;
188/// any other length is an error naming it.
189fn image_id(bytes: &[u8]) -> Result<ImageId, String> {
190    bytes
191        .try_into()
192        .map(ImageId)
193        .map_err(|_| format!("an image file id of {} bytes, not 32", bytes.len()))
194}
195
196/// A font file's id from the wire's `bytes` — its SHA-256, so 32 of them;
197/// any other length is an error naming it.
198fn font_id(bytes: &[u8]) -> Result<FontId, String> {
199    bytes
200        .try_into()
201        .map(FontId)
202        .map_err(|_| format!("a font file id of {} bytes, not 32", bytes.len()))
203}
204
205/// A node from the wire, or why it isn't one.
206pub fn decode(n: &proto::Node) -> Result<Node, String> {
207    let four = |v: &[f32]| [0, 1, 2, 3].map(|i| v.get(i).copied().unwrap_or(0.0));
208    Ok(Node {
209        id: unnode_id(n.id.as_ref())?,
210        kind: match proto::Kind::try_from(n.kind).unwrap_or(proto::Kind::Frame) {
211            proto::Kind::Frame => Kind::Frame,
212            proto::Kind::Text => Kind::Text,
213            proto::Kind::Rect => Kind::Rect,
214            proto::Kind::Ellipse => Kind::Ellipse,
215            proto::Kind::Vector => Kind::Vector,
216            proto::Kind::Image => Kind::Image,
217        },
218        name: n.name.clone(),
219        x: n.x,
220        y: n.y,
221        width: unsize(n.width),
222        height: unsize(n.height),
223        opacity: n.opacity,
224        on_click: Some(n.on_click.clone()).filter(|s| !s.is_empty()),
225        fill: match (&n.fill, &n.gradient) {
226            (Some(c), _) => Some(Fill::Solid(color(Some(*c)))),
227            (None, Some(g)) => Some(Fill::Linear {
228                angle: g.angle,
229                stops: g.stops.iter().map(|s| (color(s.color), s.at)).collect(),
230            }),
231            (None, None) => None,
232        },
233        stroke: n.stroke.map(|c| color(Some(c))),
234        stroke_width: n.stroke_width,
235        radius: four(&n.radius),
236        shadow: n.shadow.as_ref().map(|s| Shadow {
237            x: s.x,
238            y: s.y,
239            blur: s.blur,
240            spread: s.spread,
241            color: color(s.color),
242            at: Origin::default(),
243        }),
244        clip: n.clip,
245        layout: match proto::Layout::try_from(n.layout).unwrap_or(proto::Layout::None) {
246            proto::Layout::None => Layout::None,
247            proto::Layout::Row => Layout::Row,
248            proto::Layout::Column => Layout::Column,
249        },
250        gap: n.gap,
251        padding: four(&n.padding),
252        align: unalign(n.align),
253        justify: unalign(n.justify),
254        text: match &n.text {
255            Some(t) => Some(TextStyle {
256                font: if t.font.is_empty() {
257                    None
258                } else {
259                    Some(font_id(&t.font)?)
260                },
261                content: t.content.clone(),
262                size: t.size,
263                weight: t.weight as u16,
264                color: color(t.color),
265                line_height: t.line_height,
266                align: match proto::TextAlign::try_from(t.align).unwrap_or(proto::TextAlign::Left) {
267                    proto::TextAlign::Left => TextAlign::Left,
268                    proto::TextAlign::Center => TextAlign::Center,
269                    proto::TextAlign::Right => TextAlign::Right,
270                },
271            }),
272            None => None,
273        },
274        vector: n.vector.as_ref().map(|v| Vector {
275            d: v.d.clone(),
276            view_box: four(&v.view_box),
277        }),
278        image: match &n.image {
279            Some(i) => Some(Image {
280                src: i.src.clone(),
281                id: image_id(&i.id)?,
282                at: Origin::default(),
283            }),
284            None => None,
285        },
286        children: Children::from_vec(n.children.iter().map(decode).collect::<Result<_, _>>()?),
287    })
288}
289
290/// A whole scene for the wire: its tree and every image file it shows.
291pub fn scene(scene: &Scene) -> proto::Scene {
292    proto::Scene {
293        root: Some(encode(&scene.root)),
294        images: scene.images.values().map(|f| file(f)).collect(),
295        fonts: scene.fonts.values().map(|f| font_file(f)).collect(),
296        themed: scene.themed,
297    }
298}
299
300/// A font file for the wire: its id and its bytes.
301fn font_file(f: &FontFile) -> proto::FontFile {
302    proto::FontFile {
303        id: f.id.0.to_vec(),
304        data: f.bytes.to_vec(),
305    }
306}
307
308/// An image file for the wire: its id and its bytes.
309fn file(f: &ImageFile) -> proto::ImageFile {
310    proto::ImageFile {
311        id: f.id.0.to_vec(),
312        data: f.bytes.clone(),
313    }
314}
315
316/// The image files `files` carries, decoded — each taken from `held` instead
317/// when it is already there, so a file is decoded once however often it is
318/// sent.
319fn files(files: &[proto::ImageFile], held: &ImageFiles) -> Result<ImageFiles, String> {
320    let mut out = ImageFiles::new();
321    for f in files {
322        let id = image_id(&f.id)?;
323        let decoded = match held.get(&id) {
324            Some(known) => known.clone(),
325            // The server decoded the same bytes, so they decode here too.
326            None => Arc::new(ImageFile::with_id(id, f.data.clone())?),
327        };
328        out.insert(id, decoded);
329    }
330    Ok(out)
331}
332
333/// The font files `files` carries, checked — each taken from `held` instead
334/// when it is already there, so a file is checked once however often it is
335/// sent.
336fn font_files(files: &[proto::FontFile], held: &FontFiles) -> Result<FontFiles, String> {
337    let mut out = FontFiles::new();
338    for f in files {
339        let id = font_id(&f.id)?;
340        let checked = match held.get(&id) {
341            Some(known) => known.clone(),
342            // The server checked the same bytes, so they pass here too.
343            None => Arc::new(
344                FontFile::with_id(id, f.data.clone()).map_err(|e| format!("a font file {e}"))?,
345            ),
346        };
347        out.insert(id, checked);
348    }
349    Ok(out)
350}
351
352/// Keeps only the image and font files `root` uses, and says if it uses one
353/// that isn't there.
354fn settle(root: &Node, images: &mut ImageFiles, fonts: &mut FontFiles) -> Result<(), String> {
355    fn used(n: &Node, images: &mut BTreeSet<ImageId>, fonts: &mut BTreeSet<FontId>) {
356        if let Some(i) = &n.image {
357            images.insert(i.id);
358        }
359        if let Some(font) = n.text.as_ref().and_then(|t| t.font) {
360            fonts.insert(font);
361        }
362        for c in &n.children {
363            used(c, images, fonts);
364        }
365    }
366    let (mut image_ids, mut font_ids) = (BTreeSet::new(), BTreeSet::new());
367    used(root, &mut image_ids, &mut font_ids);
368    if let Some(missing) = image_ids.iter().find(|id| !images.contains_key(id)) {
369        return Err(format!("the stream never sent the image file {missing:?}"));
370    }
371    if let Some(missing) = font_ids.iter().find(|id| !fonts.contains_key(id)) {
372        return Err(format!("the stream never sent the font file {missing:?}"));
373    }
374    images.retain(|id, _| image_ids.contains(id));
375    fonts.retain(|id, _| font_ids.contains(id));
376    Ok(())
377}
378
379/// The scene a stream message carries; image and font files `held` already
380/// has aren't decoded or checked again.
381pub fn decode_scene(
382    message: &proto::Scene,
383    held: (&ImageFiles, &FontFiles),
384) -> Result<Scene, String> {
385    let root = decode(message.root.as_ref().ok_or("a scene with no root")?)?;
386    let mut images = files(&message.images, held.0)?;
387    let mut fonts = font_files(&message.fonts, held.1)?;
388    settle(&root, &mut images, &mut fonts)?;
389    let scene = Scene::new(root, images, fonts, message.themed);
390    if scene.ids.len() != count(&scene.root) {
391        return Err("a scene with two nodes of the same id".into());
392    }
393    Ok(scene)
394}
395
396/// How many nodes the subtree of `n` holds, `n` included.
397fn count(n: &Node) -> usize {
398    1 + n.children.iter().map(count).sum::<usize>()
399}
400
401mod patch;
402pub(crate) use patch::edits;
403pub use patch::{apply, patch};
404
405#[cfg(test)]
406mod tests;