devpage-design 0.3.1

The design engine: parses, resolves, lays out and paints devpage designs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Scenes and their edits on the wire: a scene to its `proto::Scene` and
//! back, and [`Edits`](crate::scene::Edits) to the `proto::Patch` the watch
//! stream sends and back ([`patch`]). Each image file and font file travels
//! once: a scene carries every one its nodes use, a patch only those the
//! scene before it didn't have. It does no I/O.

use std::collections::BTreeSet;
use std::sync::Arc;

use crate::fonts::{FontFile, FontFiles, FontId};
use crate::proto;
use crate::scene::{
    Align, Color, Fill, Image, ImageFile, ImageFiles, ImageId, Kind, Layout, Node, Origin, Rgba,
    Scene, Shadow, Size, TextAlign, TextStyle, Vector,
};
use crate::tree::{Children, NodeId};

/// A color for the wire: its red, green, blue and alpha as one word, red the
/// highest byte.
fn word(c: Rgba) -> u32 {
    u32::from_be_bytes([c.r, c.g, c.b, c.a])
}

/// A color from the wire's word, red its highest byte.
fn unword(v: u32) -> Rgba {
    let [r, g, b, a] = v.to_be_bytes();
    Rgba { r, g, b, a }
}

/// A color for the wire: its light and its dark value.
fn rgba(c: Color) -> proto::Color {
    proto::Color {
        light: word(c.light),
        dark: word(c.dark),
    }
}

/// A color from the wire; one the stream left out is transparent.
fn color(c: Option<proto::Color>) -> Color {
    let c = c.unwrap_or_default();
    Color {
        light: unword(c.light),
        dark: unword(c.dark),
    }
}

/// A size for the wire: pixels as they are, `-1` for hug and `-2` for fill.
fn size(s: Size) -> f32 {
    match s {
        Size::Px(v) => v,
        Size::Hug => -1.0,
        Size::Fill => -2.0,
    }
}

/// A size from the wire: `-1` is hug, `-2` fill and anything else pixels.
fn unsize(v: f32) -> Size {
    if v == -1.0 {
        Size::Hug
    } else if v == -2.0 {
        Size::Fill
    } else {
        Size::Px(v)
    }
}

/// `a` as the wire's enum, one value for each.
fn align(a: Align) -> proto::Align {
    match a {
        Align::Start => proto::Align::Start,
        Align::Center => proto::Align::Center,
        Align::End => proto::Align::End,
        Align::SpaceBetween => proto::Align::SpaceBetween,
    }
}

/// An alignment from the wire; one it doesn't know is the start.
fn unalign(a: i32) -> Align {
    match proto::Align::try_from(a).unwrap_or(proto::Align::Start) {
        proto::Align::Start => Align::Start,
        proto::Align::Center => Align::Center,
        proto::Align::End => Align::End,
        proto::Align::SpaceBetween => Align::SpaceBetween,
    }
}

/// A node for the wire, with everything under it.
pub fn encode(n: &Node) -> proto::Node {
    proto::Node {
        kind: match n.kind {
            Kind::Frame => proto::Kind::Frame,
            Kind::Text => proto::Kind::Text,
            Kind::Rect => proto::Kind::Rect,
            Kind::Ellipse => proto::Kind::Ellipse,
            Kind::Vector => proto::Kind::Vector,
            Kind::Image => proto::Kind::Image,
        } as i32,
        name: n.name.clone(),
        x: n.x,
        y: n.y,
        width: size(n.width),
        height: size(n.height),
        opacity: n.opacity,
        on_click: n.on_click.clone().unwrap_or_default(),
        fill: match &n.fill {
            Some(Fill::Solid(c)) => Some(rgba(*c)),
            _ => None,
        },
        gradient: match &n.fill {
            Some(Fill::Linear { angle, stops }) => Some(proto::Gradient {
                angle: *angle,
                stops: stops
                    .iter()
                    .map(|(c, at)| proto::Stop {
                        color: Some(rgba(*c)),
                        at: *at,
                    })
                    .collect(),
            }),
            _ => None,
        },
        vector: n.vector.as_ref().map(|v| proto::Vector {
            d: v.d.clone(),
            view_box: v.view_box.to_vec(),
        }),
        image: n.image.as_ref().map(|i| proto::Image {
            src: i.src.clone(),
            id: i.id.0.to_vec(),
        }),
        stroke: n.stroke.map(rgba),
        stroke_width: n.stroke_width,
        radius: n.radius.to_vec(),
        shadow: n.shadow.as_ref().map(|s| proto::Shadow {
            x: s.x,
            y: s.y,
            blur: s.blur,
            spread: s.spread,
            color: Some(rgba(s.color)),
        }),
        clip: n.clip,
        layout: match n.layout {
            Layout::None => proto::Layout::None,
            Layout::Row => proto::Layout::Row,
            Layout::Column => proto::Layout::Column,
        } as i32,
        gap: n.gap,
        padding: n.padding.to_vec(),
        align: align(n.align) as i32,
        justify: align(n.justify) as i32,
        text: n.text.as_ref().map(|t| proto::Text {
            font: t.font.map(|id| id.0.to_vec()).unwrap_or_default(),
            content: t.content.clone(),
            size: t.size,
            weight: t.weight as u32,
            color: Some(rgba(t.color)),
            line_height: t.line_height,
            align: match t.align {
                TextAlign::Left => proto::TextAlign::Left,
                TextAlign::Center => proto::TextAlign::Center,
                TextAlign::Right => proto::TextAlign::Right,
            } as i32,
        }),
        children: n.children.iter().map(encode).collect(),
        id: Some(node_id(&n.id)),
    }
}

/// A node's own attributes for the wire: its children aside.
pub fn encode_own(n: &Node) -> proto::Node {
    let mut own = n.clone();
    own.children.clear();
    encode(&own)
}

/// `id` for the wire: its path of element ids, from the root through each
/// instance, copied as is.
fn node_id(id: &NodeId) -> proto::NodeId {
    proto::NodeId { path: id.0.clone() }
}

/// A node's id from the wire, or that the node has none.
fn unnode_id(id: Option<&proto::NodeId>) -> Result<NodeId, String> {
    id.map(|i| NodeId(i.path.clone()))
        .ok_or_else(|| "a node with no id".to_string())
}

/// An image file's id from the wire's `bytes` — its SHA-256, so 32 of them;
/// any other length is an error naming it.
fn image_id(bytes: &[u8]) -> Result<ImageId, String> {
    bytes
        .try_into()
        .map(ImageId)
        .map_err(|_| format!("an image file id of {} bytes, not 32", bytes.len()))
}

/// A font file's id from the wire's `bytes` — its SHA-256, so 32 of them;
/// any other length is an error naming it.
fn font_id(bytes: &[u8]) -> Result<FontId, String> {
    bytes
        .try_into()
        .map(FontId)
        .map_err(|_| format!("a font file id of {} bytes, not 32", bytes.len()))
}

/// A node from the wire, or why it isn't one.
pub fn decode(n: &proto::Node) -> Result<Node, String> {
    let four = |v: &[f32]| [0, 1, 2, 3].map(|i| v.get(i).copied().unwrap_or(0.0));
    Ok(Node {
        id: unnode_id(n.id.as_ref())?,
        kind: match proto::Kind::try_from(n.kind).unwrap_or(proto::Kind::Frame) {
            proto::Kind::Frame => Kind::Frame,
            proto::Kind::Text => Kind::Text,
            proto::Kind::Rect => Kind::Rect,
            proto::Kind::Ellipse => Kind::Ellipse,
            proto::Kind::Vector => Kind::Vector,
            proto::Kind::Image => Kind::Image,
        },
        name: n.name.clone(),
        x: n.x,
        y: n.y,
        width: unsize(n.width),
        height: unsize(n.height),
        opacity: n.opacity,
        on_click: Some(n.on_click.clone()).filter(|s| !s.is_empty()),
        fill: match (&n.fill, &n.gradient) {
            (Some(c), _) => Some(Fill::Solid(color(Some(*c)))),
            (None, Some(g)) => Some(Fill::Linear {
                angle: g.angle,
                stops: g.stops.iter().map(|s| (color(s.color), s.at)).collect(),
            }),
            (None, None) => None,
        },
        stroke: n.stroke.map(|c| color(Some(c))),
        stroke_width: n.stroke_width,
        radius: four(&n.radius),
        shadow: n.shadow.as_ref().map(|s| Shadow {
            x: s.x,
            y: s.y,
            blur: s.blur,
            spread: s.spread,
            color: color(s.color),
            at: Origin::default(),
        }),
        clip: n.clip,
        layout: match proto::Layout::try_from(n.layout).unwrap_or(proto::Layout::None) {
            proto::Layout::None => Layout::None,
            proto::Layout::Row => Layout::Row,
            proto::Layout::Column => Layout::Column,
        },
        gap: n.gap,
        padding: four(&n.padding),
        align: unalign(n.align),
        justify: unalign(n.justify),
        text: match &n.text {
            Some(t) => Some(TextStyle {
                font: if t.font.is_empty() {
                    None
                } else {
                    Some(font_id(&t.font)?)
                },
                content: t.content.clone(),
                size: t.size,
                weight: t.weight as u16,
                color: color(t.color),
                line_height: t.line_height,
                align: match proto::TextAlign::try_from(t.align).unwrap_or(proto::TextAlign::Left) {
                    proto::TextAlign::Left => TextAlign::Left,
                    proto::TextAlign::Center => TextAlign::Center,
                    proto::TextAlign::Right => TextAlign::Right,
                },
            }),
            None => None,
        },
        vector: n.vector.as_ref().map(|v| Vector {
            d: v.d.clone(),
            view_box: four(&v.view_box),
        }),
        image: match &n.image {
            Some(i) => Some(Image {
                src: i.src.clone(),
                id: image_id(&i.id)?,
                at: Origin::default(),
            }),
            None => None,
        },
        children: Children::from_vec(n.children.iter().map(decode).collect::<Result<_, _>>()?),
    })
}

/// A whole scene for the wire: its tree and every image file it shows.
pub fn scene(scene: &Scene) -> proto::Scene {
    proto::Scene {
        root: Some(encode(&scene.root)),
        images: scene.images.values().map(|f| file(f)).collect(),
        fonts: scene.fonts.values().map(|f| font_file(f)).collect(),
        themed: scene.themed,
    }
}

/// A font file for the wire: its id and its bytes.
fn font_file(f: &FontFile) -> proto::FontFile {
    proto::FontFile {
        id: f.id.0.to_vec(),
        data: f.bytes.to_vec(),
    }
}

/// An image file for the wire: its id and its bytes.
fn file(f: &ImageFile) -> proto::ImageFile {
    proto::ImageFile {
        id: f.id.0.to_vec(),
        data: f.bytes.clone(),
    }
}

/// The image files `files` carries, decoded — each taken from `held` instead
/// when it is already there, so a file is decoded once however often it is
/// sent.
fn files(files: &[proto::ImageFile], held: &ImageFiles) -> Result<ImageFiles, String> {
    let mut out = ImageFiles::new();
    for f in files {
        let id = image_id(&f.id)?;
        let decoded = match held.get(&id) {
            Some(known) => known.clone(),
            // The server decoded the same bytes, so they decode here too.
            None => Arc::new(ImageFile::with_id(id, f.data.clone())?),
        };
        out.insert(id, decoded);
    }
    Ok(out)
}

/// The font files `files` carries, checked — each taken from `held` instead
/// when it is already there, so a file is checked once however often it is
/// sent.
fn font_files(files: &[proto::FontFile], held: &FontFiles) -> Result<FontFiles, String> {
    let mut out = FontFiles::new();
    for f in files {
        let id = font_id(&f.id)?;
        let checked = match held.get(&id) {
            Some(known) => known.clone(),
            // The server checked the same bytes, so they pass here too.
            None => Arc::new(
                FontFile::with_id(id, f.data.clone()).map_err(|e| format!("a font file {e}"))?,
            ),
        };
        out.insert(id, checked);
    }
    Ok(out)
}

/// Keeps only the image and font files `root` uses, and says if it uses one
/// that isn't there.
fn settle(root: &Node, images: &mut ImageFiles, fonts: &mut FontFiles) -> Result<(), String> {
    fn used(n: &Node, images: &mut BTreeSet<ImageId>, fonts: &mut BTreeSet<FontId>) {
        if let Some(i) = &n.image {
            images.insert(i.id);
        }
        if let Some(font) = n.text.as_ref().and_then(|t| t.font) {
            fonts.insert(font);
        }
        for c in &n.children {
            used(c, images, fonts);
        }
    }
    let (mut image_ids, mut font_ids) = (BTreeSet::new(), BTreeSet::new());
    used(root, &mut image_ids, &mut font_ids);
    if let Some(missing) = image_ids.iter().find(|id| !images.contains_key(id)) {
        return Err(format!("the stream never sent the image file {missing:?}"));
    }
    if let Some(missing) = font_ids.iter().find(|id| !fonts.contains_key(id)) {
        return Err(format!("the stream never sent the font file {missing:?}"));
    }
    images.retain(|id, _| image_ids.contains(id));
    fonts.retain(|id, _| font_ids.contains(id));
    Ok(())
}

/// The scene a stream message carries; image and font files `held` already
/// has aren't decoded or checked again.
pub fn decode_scene(
    message: &proto::Scene,
    held: (&ImageFiles, &FontFiles),
) -> Result<Scene, String> {
    let root = decode(message.root.as_ref().ok_or("a scene with no root")?)?;
    let mut images = files(&message.images, held.0)?;
    let mut fonts = font_files(&message.fonts, held.1)?;
    settle(&root, &mut images, &mut fonts)?;
    let scene = Scene::new(root, images, fonts, message.themed);
    if scene.ids.len() != count(&scene.root) {
        return Err("a scene with two nodes of the same id".into());
    }
    Ok(scene)
}

/// How many nodes the subtree of `n` holds, `n` included.
fn count(n: &Node) -> usize {
    1 + n.children.iter().map(count).sum::<usize>()
}

mod patch;
pub(crate) use patch::edits;
pub use patch::{apply, patch};

#[cfg(test)]
mod tests;