1use 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
18fn word(c: Rgba) -> u32 {
21 u32::from_be_bytes([c.r, c.g, c.b, c.a])
22}
23
24fn unword(v: u32) -> Rgba {
26 let [r, g, b, a] = v.to_be_bytes();
27 Rgba { r, g, b, a }
28}
29
30fn rgba(c: Color) -> proto::Color {
32 proto::Color {
33 light: word(c.light),
34 dark: word(c.dark),
35 }
36}
37
38fn 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
47fn 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
56fn 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
67fn 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
77fn 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
87pub 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
168pub fn encode_own(n: &Node) -> proto::Node {
170 let mut own = n.clone();
171 own.children.clear();
172 encode(&own)
173}
174
175fn node_id(id: &NodeId) -> proto::NodeId {
178 proto::NodeId { path: id.0.clone() }
179}
180
181fn 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
187fn 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
196fn 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
205pub 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
290pub 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
300fn 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
308fn file(f: &ImageFile) -> proto::ImageFile {
310 proto::ImageFile {
311 id: f.id.0.to_vec(),
312 data: f.bytes.clone(),
313 }
314}
315
316fn 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 None => Arc::new(ImageFile::with_id(id, f.data.clone())?),
327 };
328 out.insert(id, decoded);
329 }
330 Ok(out)
331}
332
333fn 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 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
352fn 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
379pub 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
396fn 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;