Skip to main content

devpage_design/scene/
mod.rs

1//! What a resolved design is, and how one becomes the next. A [`Scene`] is
2//! a tree of [`Node`]s — each with its own attributes, colours in both
3//! [`Theme`]s, and an id that survives saves — with the image and font files
4//! it shows, read through the [`Files`] port. An [`Edit`] names its nodes by
5//! id; [`Edits`] are a list of them with the files they bring, and applying
6//! them ([`apply`]) is all or nothing, undone on a refusal, at the cost of
7//! the edits alone. [`Applied`] says what they did, for a drawing kept
8//! beside the scene to follow.
9//!
10//! It is what every other part of the engine speaks: [`crate::resolve`]
11//! makes scenes and their edits, [`crate::render`] draws them, and
12//! [`crate::wire`] carries both to the browser.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use peniko::{Blob, ImageAlphaType, ImageData, ImageFormat};
18
19use crate::Problem;
20use crate::fonts::{FontFile, FontFiles, FontId};
21use crate::parse::{self, Pos};
22use crate::tree::{Children, NodeId, Order, OrderKey};
23
24/// One color's value: straight-alpha RGBA.
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct Rgba {
27    /// The red channel, 0 to 255.
28    pub r: u8,
29    /// The green channel, 0 to 255.
30    pub g: u8,
31    /// The blue channel, 0 to 255.
32    pub b: u8,
33    /// The alpha, 0 transparent to 255 opaque; the other channels are not
34    /// multiplied by it.
35    pub a: u8,
36}
37
38/// Which of a design's two themes it is drawn in.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
40pub enum Theme {
41    /// The light theme, the default: each color's `light` value.
42    #[default]
43    Light,
44    /// The dark theme: each color's `dark` value.
45    Dark,
46}
47
48impl Theme {
49    /// `"light"` or `"dark"` as a theme, as a PNG's `?theme=` names one.
50    pub fn named(name: &str) -> Option<Theme> {
51        match name {
52            "light" => Some(Theme::Light),
53            "dark" => Some(Theme::Dark),
54            _ => None,
55        }
56    }
57}
58
59/// A color in a scene: its value in each theme. A color written as `#…` has
60/// the same value in both; `theme.name` has the themes' two.
61#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct Color {
63    /// The value in the light theme.
64    pub light: Rgba,
65    /// The value in the dark theme.
66    pub dark: Rgba,
67}
68
69impl Color {
70    /// The same value in both themes.
71    pub const fn fixed(c: Rgba) -> Color {
72        Color { light: c, dark: c }
73    }
74
75    /// The value in `theme`.
76    pub fn get(self, theme: Theme) -> Rgba {
77        match theme {
78            Theme::Light => self.light,
79            Theme::Dark => self.dark,
80        }
81    }
82}
83
84/// How a node's width or height is set.
85#[derive(Debug, Clone, Copy, PartialEq)]
86pub enum Size {
87    /// A fixed size, in pixels.
88    Px(f32),
89    /// As large as the node's content.
90    Hug,
91    /// The room its parent's auto layout gives it: the free space along the
92    /// layout, the whole breadth across it. A root, with no parent, hugs.
93    Fill,
94}
95
96/// How a frame places its children.
97#[derive(Debug, Clone, Copy, PartialEq)]
98pub enum Layout {
99    /// Each child where its `x` and `y` say.
100    None,
101    /// Side by side, left to right.
102    Row,
103    /// One under another, top to bottom.
104    Column,
105}
106
107/// Where a frame's auto layout puts its children along one axis.
108#[derive(Debug, Clone, Copy, PartialEq)]
109pub enum Align {
110    /// At the start.
111    Start,
112    /// In the middle.
113    Center,
114    /// At the end.
115    End,
116    /// The first at the start, the last at the end, and the free space shared
117    /// between them; `justify` only.
118    SpaceBetween,
119}
120
121/// What a node is: the element that made it.
122#[derive(Debug, Clone, Copy, PartialEq)]
123pub enum Kind {
124    /// A box that holds children and may lay them out.
125    Frame,
126    /// Text, set in one style.
127    Text,
128    /// A rectangle.
129    Rect,
130    /// An ellipse filling the node's box.
131    Ellipse,
132    /// An SVG path.
133    Vector,
134    /// A PNG or JPEG file.
135    Image,
136}
137
138/// How a box is filled: one color, or a CSS-style linear gradient.
139#[derive(Debug, Clone, PartialEq)]
140pub enum Fill {
141    /// One color over the whole fill, with a value for each theme.
142    Solid(Color),
143    /// `angle` in degrees, CSS's: 0 points up, 90 right, 180 down. Each stop
144    /// is a color at an offset from 0 to 1 along the gradient line.
145    Linear {
146        angle: f32,
147        stops: Vec<(Color, f32)>,
148    },
149}
150
151/// How each line of a text sits across its box.
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub enum TextAlign {
154    /// Against the left edge.
155    Left,
156    /// In the middle.
157    Center,
158    /// Against the right edge.
159    Right,
160}
161
162/// A `Vector`'s path and the box of path coordinates it is drawn from.
163#[derive(Debug, Clone, PartialEq)]
164pub struct Vector {
165    /// The path, as SVG path data.
166    pub d: String,
167    /// `[minX, minY, width, height]`.
168    pub view_box: [f32; 4],
169}
170
171/// An image file's identity: the SHA-256 of its bytes. Two `Image`s showing
172/// the same bytes — the same file used twice, or two copies of it — share one
173/// [`ImageFile`], decoded once and sent once.
174#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
175pub struct ImageId(pub [u8; 32]);
176
177impl ImageId {
178    /// The identity of the file whose bytes are `bytes`.
179    pub fn of(bytes: &[u8]) -> ImageId {
180        use sha2::Digest;
181        ImageId(sha2::Sha256::digest(bytes).into())
182    }
183}
184
185impl std::fmt::Debug for ImageId {
186    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187        for b in &self.0[..6] {
188            write!(f, "{b:02x}")?;
189        }
190        Ok(())
191    }
192}
193
194/// The most pixels a side an image is drawn from. The GPU keeps every image a
195/// drawing paints in one atlas of [`crate::atlas::SIDE`] pixels a side, so a
196/// larger file is resampled to fit this, keeping its aspect, when it is
197/// decoded — and both backends draw those same pixels.
198pub const MAX_IMAGE_SIDE: u32 = 4096;
199
200/// A decoded image file: its bytes, its own size, and the pixels it is drawn
201/// from — the file's own, or resampled to at most [`MAX_IMAGE_SIDE`] a side.
202#[derive(Debug)]
203pub struct ImageFile {
204    /// Its identity: the SHA-256 of its bytes.
205    pub id: ImageId,
206    /// The file's bytes, as read.
207    pub bytes: Vec<u8>,
208    /// The file's size in pixels: what an `Image` hugs by.
209    pub width: u32,
210    /// The file's height in pixels.
211    pub height: u32,
212    /// Straight-alpha RGBA, `pixels_width` × `pixels_height`.
213    pub pixels: Arc<Vec<u8>>,
214    /// The width of `pixels`, in pixels.
215    pub pixels_width: u32,
216    /// The height of `pixels`, in pixels.
217    pub pixels_height: u32,
218}
219
220impl ImageFile {
221    /// Decodes `bytes`, a PNG or JPEG file, or says why it can't.
222    pub fn new(bytes: Vec<u8>) -> Result<ImageFile, String> {
223        ImageFile::with_id(ImageId::of(&bytes), bytes)
224    }
225
226    /// Decodes `bytes`, already known to be the file `id`.
227    pub fn with_id(id: ImageId, bytes: Vec<u8>) -> Result<ImageFile, String> {
228        let decoded = decode(&bytes)?;
229        let (width, height) = (decoded.width, decoded.height);
230        let (pixels, pixels_width, pixels_height) =
231            fit(decoded.data.data(), width, height, MAX_IMAGE_SIDE);
232        Ok(ImageFile {
233            id,
234            bytes,
235            width,
236            height,
237            pixels: Arc::new(pixels),
238            pixels_width,
239            pixels_height,
240        })
241    }
242
243    /// The pixels as an image for one drawing to paint, under a blob of its
244    /// own that shares the pixels: see `render::Renderer::drawing`.
245    pub fn image_data(&self) -> ImageData {
246        ImageData {
247            data: Blob::new(self.pixels.clone()),
248            format: ImageFormat::Rgba8,
249            alpha_type: ImageAlphaType::Alpha,
250            width: self.pixels_width,
251            height: self.pixels_height,
252        }
253    }
254}
255
256/// `rgba`, `width` × `height`, resampled to at most `max` pixels a side with
257/// its aspect kept, or as it is when it already fits. Each new pixel is the
258/// area-weighted average of the pixels under it, in premultiplied alpha so a
259/// transparent pixel lends no color.
260pub fn fit(rgba: &[u8], width: u32, height: u32, max: u32) -> (Vec<u8>, u32, u32) {
261    if width <= max && height <= max {
262        return (rgba.to_vec(), width, height);
263    }
264    let scale = max as f64 / width.max(height) as f64;
265    let w = ((width as f64 * scale).round() as u32).clamp(1, max);
266    let h = ((height as f64 * scale).round() as u32).clamp(1, max);
267    // For each output index along one axis, the input indices it covers and
268    // how much of each.
269    let weights = |from: u32, to: u32| -> Vec<Vec<(usize, f32)>> {
270        let ratio = from as f64 / to as f64;
271        (0..to)
272            .map(|o| {
273                let (a, b) = (o as f64 * ratio, (o + 1) as f64 * ratio);
274                (a.floor() as usize..(b.ceil() as usize).min(from as usize))
275                    .map(|i| {
276                        let cover = (b.min(i as f64 + 1.0) - a.max(i as f64)) / ratio;
277                        (i, cover as f32)
278                    })
279                    .filter(|&(_, c)| c > 0.0)
280                    .collect()
281            })
282            .collect()
283    };
284    let (across, down) = (weights(width, w), weights(height, h));
285    // Across each row first, premultiplied, then down each column.
286    let mut rows = vec![0f32; 4 * w as usize * height as usize];
287    for y in 0..height as usize {
288        let line = &rgba[4 * y * width as usize..][..4 * width as usize];
289        for (x, ws) in across.iter().enumerate() {
290            let mut sum = [0f32; 4];
291            for &(i, c) in ws {
292                let p = &line[4 * i..][..4];
293                let a = p[3] as f32 * c;
294                sum[0] += p[0] as f32 * a;
295                sum[1] += p[1] as f32 * a;
296                sum[2] += p[2] as f32 * a;
297                sum[3] += a;
298            }
299            rows[4 * (y * w as usize + x)..][..4].copy_from_slice(&sum);
300        }
301    }
302    let mut out = vec![0u8; 4 * w as usize * h as usize];
303    for (y, ws) in down.iter().enumerate() {
304        for x in 0..w as usize {
305            let mut sum = [0f32; 4];
306            for &(i, c) in ws {
307                let p = &rows[4 * (i * w as usize + x)..][..4];
308                for k in 0..4 {
309                    sum[k] += p[k] * c;
310                }
311            }
312            let px = &mut out[4 * (y * w as usize + x)..][..4];
313            if sum[3] > 0.0 {
314                for k in 0..3 {
315                    px[k] = (sum[k] / sum[3]).round().clamp(0.0, 255.0) as u8;
316                }
317                px[3] = sum[3].round().clamp(0.0, 255.0) as u8;
318            }
319        }
320    }
321    (out, w, h)
322}
323
324/// Where an attribute was written, for a problem found only once the design
325/// is laid out and painted. It is never part of what a node draws: two nodes
326/// that differ only in it are equal, and it doesn't travel on the wire.
327#[derive(Debug, Clone)]
328pub struct Origin {
329    /// The design file it was written in, by its path from the top of the
330    /// served folder.
331    pub file: String,
332    /// Where in that file it was written.
333    pub pos: Pos,
334}
335
336impl Default for Origin {
337    fn default() -> Origin {
338        Origin {
339            file: String::new(),
340            pos: Pos { line: 1, col: 1 },
341        }
342    }
343}
344
345impl PartialEq for Origin {
346    fn eq(&self, _: &Origin) -> bool {
347        true
348    }
349}
350
351/// An `Image`'s file: its address in the served folder and which
352/// [`ImageFile`] in the scene it shows.
353#[derive(Debug, Clone, PartialEq)]
354pub struct Image {
355    /// The image file's path from the top of the served folder.
356    pub src: String,
357    /// The [`ImageFile`] it shows, by its id in the scene's `images`.
358    pub id: ImageId,
359    /// Where `src` was written.
360    pub at: Origin,
361}
362
363/// A PNG or JPEG file's pixels, as straight-alpha RGBA, or why it has none.
364pub fn decode(data: &[u8]) -> Result<ImageData, String> {
365    let (pixels, width, height) = if data.starts_with(b"\x89PNG\r\n\x1a\n") {
366        let broken = |e: &dyn std::fmt::Display| format!("is a PNG that doesn't decode: {e}");
367        let mut decoder = png::Decoder::new(std::io::Cursor::new(data));
368        decoder.set_transformations(png::Transformations::normalize_to_color8());
369        let mut reader = decoder.read_info().map_err(|e| broken(&e))?;
370        let size = reader
371            .output_buffer_size()
372            .ok_or_else(|| broken(&"too big to hold"))?;
373        let mut buf = vec![0; size];
374        let info = reader.next_frame(&mut buf).map_err(|e| broken(&e))?;
375        buf.truncate(info.buffer_size());
376        let rgba = match info.color_type {
377            png::ColorType::Rgba => buf,
378            png::ColorType::Rgb => buf
379                .chunks(3)
380                .flat_map(|p| [p[0], p[1], p[2], 255])
381                .collect(),
382            png::ColorType::GrayscaleAlpha => buf
383                .chunks(2)
384                .flat_map(|p| [p[0], p[0], p[0], p[1]])
385                .collect(),
386            png::ColorType::Grayscale => buf.iter().flat_map(|&g| [g, g, g, 255]).collect(),
387            // Expanded to RGB by `normalize_to_color8`.
388            png::ColorType::Indexed => return Err(broken(&"an unexpanded palette")),
389        };
390        (rgba, info.width, info.height)
391    } else if data.starts_with(&[0xff, 0xd8, 0xff]) {
392        use zune_jpeg::JpegDecoder;
393        use zune_jpeg::zune_core::colorspace::ColorSpace;
394        use zune_jpeg::zune_core::options::DecoderOptions;
395        let broken = |e: &dyn std::fmt::Display| format!("is a JPEG that doesn't decode: {e}");
396        let options = DecoderOptions::default()
397            .set_strict_mode(true)
398            .jpeg_set_out_colorspace(ColorSpace::RGBA);
399        let mut decoder = JpegDecoder::new_with_options(std::io::Cursor::new(data), options);
400        let pixels = decoder.decode().map_err(|e| broken(&e))?;
401        let info = decoder.info().ok_or_else(|| broken(&"no header"))?;
402        (pixels, info.width as u32, info.height as u32)
403    } else {
404        return Err("is not a PNG or JPEG file".into());
405    };
406    if width == 0 || height == 0 || pixels.len() != width as usize * height as usize * 4 {
407        return Err(format!(
408            "is an image of {width}×{height} pixels that doesn't decode whole"
409        ));
410    }
411    Ok(ImageData {
412        data: Blob::new(Arc::new(pixels)),
413        format: ImageFormat::Rgba8,
414        alpha_type: ImageAlphaType::Alpha,
415        width,
416        height,
417    })
418}
419
420/// A box's drop shadow, as CSS's `box-shadow` draws one: an offset, a blur and a
421/// spread, in pixels, and a color.
422#[derive(Debug, Clone, PartialEq)]
423pub struct Shadow {
424    /// How far right of the box the shadow is, in pixels.
425    pub x: f32,
426    /// How far down from the box the shadow is, in pixels.
427    pub y: f32,
428    /// How far the shadow blurs, in pixels: twice the Gaussian's standard
429    /// deviation.
430    pub blur: f32,
431    /// How far the shadow grows past the box on every side before it blurs,
432    /// in pixels; a negative spread shrinks it.
433    pub spread: f32,
434    /// The shadow's color.
435    pub color: Color,
436    /// Where `shadow` was written.
437    pub at: Origin,
438}
439
440/// A `Text`'s text and how it is set.
441#[derive(Debug, Clone, PartialEq)]
442pub struct TextStyle {
443    /// The font file the text is set in, the face its weight picked; `None`
444    /// for Inter.
445    pub font: Option<FontId>,
446    /// What the text says: the element's text, each `{prop}` in it filled
447    /// in — a number as Rust prints it.
448    pub content: String,
449    /// The font size, in pixels.
450    pub size: f32,
451    /// The font weight: 100 to 900, in steps of 100.
452    pub weight: u16,
453    /// The text's color.
454    pub color: Color,
455    /// The height of a line, as a multiple of `size`.
456    pub line_height: f32,
457    /// How each line sits across the text's box.
458    pub align: TextAlign,
459}
460
461/// One node of a scene.
462#[derive(Debug, Clone, PartialEq)]
463pub struct Node {
464    /// Where the node came from — see [`NodeId`] — which no edit around it
465    /// changes.
466    pub id: NodeId,
467    /// What the node is.
468    pub kind: Kind,
469    /// The node's name: its `name` attribute, or else its element's, as
470    /// problems call it.
471    pub name: String,
472    /// How far right of its parent's top-left the node sits, in pixels; only a
473    /// parent with no auto layout places it by this.
474    pub x: f32,
475    /// How far down from its parent's top-left the node sits, in pixels; only a
476    /// parent with no auto layout places it by this.
477    pub y: f32,
478    /// How the node's width is set.
479    pub width: Size,
480    /// How the node's height is set.
481    pub height: Size,
482    /// How opaque the node and everything in it is, from 0 to 1.
483    pub opacity: f32,
484    /// What a click on the node does: `navigate <path>`, `back`, `overlay
485    /// <path>` or `close`, each path from the top of the served folder. `None`
486    /// when a click does nothing.
487    pub on_click: Option<String>,
488    /// What the node's box is filled with; `None` for nothing.
489    pub fill: Option<Fill>,
490    /// The color of the node's outline; `None` for no outline.
491    pub stroke: Option<Color>,
492    /// How wide the outline is, in pixels.
493    pub stroke_width: f32,
494    /// Each corner's radius, in pixels: top-left, top-right, bottom-right,
495    /// bottom-left.
496    pub radius: [f32; 4],
497    /// The node's drop shadow; `None` for none.
498    pub shadow: Option<Shadow>,
499    /// Whether a frame's children are cut off at its box, rounded corners
500    /// and all.
501    pub clip: bool,
502    /// How a frame places its children.
503    pub layout: Layout,
504    /// The space between a frame's children in its auto layout, in pixels.
505    pub gap: f32,
506    /// The space inside a frame's edges, in pixels: top, right, bottom, left.
507    pub padding: [f32; 4],
508    /// Where a frame's auto layout puts its children across its direction.
509    pub align: Align,
510    /// Where a frame's auto layout puts its children along its direction.
511    pub justify: Align,
512    /// A `Text`'s text and how it is set; `None` for any other kind.
513    pub text: Option<TextStyle>,
514    /// A `Vector`'s path; `None` for any other kind.
515    pub vector: Option<Vector>,
516    /// An `Image`'s file; `None` for any other kind.
517    pub image: Option<Image>,
518    /// The node's children, in order.
519    pub children: Children<Node>,
520}
521
522impl Node {
523    /// Whether two nodes' own attributes are the same, their children aside.
524    pub fn same_own(&self, b: &Node) -> bool {
525        let a = self;
526        a.kind == b.kind
527            && a.name == b.name
528            && a.x == b.x
529            && a.y == b.y
530            && a.width == b.width
531            && a.height == b.height
532            && a.opacity == b.opacity
533            && a.on_click == b.on_click
534            && a.fill == b.fill
535            && a.stroke == b.stroke
536            && a.stroke_width == b.stroke_width
537            && a.radius == b.radius
538            && a.shadow == b.shadow
539            && a.clip == b.clip
540            && a.layout == b.layout
541            && a.gap == b.gap
542            && a.padding == b.padding
543            && a.align == b.align
544            && a.justify == b.justify
545            && a.text == b.text
546            && a.vector == b.vector
547            && a.image == b.image
548    }
549
550    /// The node's own attributes, without its children.
551    pub fn own(&self) -> Node {
552        Node {
553            id: self.id.clone(),
554            kind: self.kind,
555            name: self.name.clone(),
556            x: self.x,
557            y: self.y,
558            width: self.width,
559            height: self.height,
560            opacity: self.opacity,
561            on_click: self.on_click.clone(),
562            fill: self.fill.clone(),
563            stroke: self.stroke,
564            stroke_width: self.stroke_width,
565            radius: self.radius,
566            shadow: self.shadow.clone(),
567            clip: self.clip,
568            layout: self.layout,
569            gap: self.gap,
570            padding: self.padding,
571            align: self.align,
572            justify: self.justify,
573            text: self.text.clone(),
574            vector: self.vector.clone(),
575            image: self.image.clone(),
576            children: Children::new(),
577        }
578    }
579
580    /// A node of `kind` with every attribute at its default.
581    pub(crate) fn new(kind: Kind, name: &str) -> Node {
582        Node {
583            id: NodeId::default(),
584            kind,
585            name: name.to_string(),
586            x: 0.0,
587            y: 0.0,
588            width: Size::Hug,
589            height: Size::Hug,
590            opacity: 1.0,
591            on_click: None,
592            fill: None,
593            stroke: None,
594            stroke_width: 1.0,
595            radius: [0.0; 4],
596            shadow: None,
597            clip: false,
598            layout: Layout::None,
599            gap: 0.0,
600            padding: [0.0; 4],
601            align: Align::Start,
602            justify: Align::Start,
603            text: None,
604            vector: None,
605            image: None,
606            children: Children::new(),
607        }
608    }
609}
610
611/// Reads a design's files by their path from the top of the served folder.
612pub trait Files {
613    /// A file's bytes: a design's text, an `Image`'s file or a font file.
614    fn bytes(&self, path: &str) -> Option<Vec<u8>>;
615    /// The names of the files directly in the folder at `path`, sorted;
616    /// `None` when there is no such folder. A font folder is read this way.
617    fn list(&self, path: &str) -> Option<Vec<String>>;
618    /// A design file's text.
619    fn read(&self, path: &str) -> Option<String> {
620        String::from_utf8(self.bytes(path)?).ok()
621    }
622    /// The design file at `path`, whose text is `source`, parsed. A store
623    /// that keeps files between resolves matches it against the file's last
624    /// parse ([`crate::ids::matched`]), so its elements keep their ids — and
625    /// the nodes they make theirs — across saves.
626    fn parse(&self, path: &str, source: &str) -> Result<Arc<parse::File>, Problem> {
627        let _ = path;
628        parse::parse(source).map(Arc::new)
629    }
630    /// The image file at `path`, decoded, or why it doesn't decode; `None`
631    /// when there is no such file. A store that keeps files between resolves
632    /// keeps their decoded images too, so a save doesn't decode them again.
633    fn image(&self, path: &str) -> Option<Result<Arc<ImageFile>, String>> {
634        self.bytes(path)
635            .map(|bytes| ImageFile::new(bytes).map(Arc::new))
636    }
637    /// The font file at `path`, checked, or why it isn't one; `None` when
638    /// there is no such file. A store that keeps files between resolves
639    /// keeps them checked too.
640    fn font(&self, path: &str) -> Option<Result<Arc<FontFile>, String>> {
641        self.bytes(path)
642            .map(|bytes| FontFile::new(bytes).map(Arc::new))
643    }
644}
645
646/// The names of the files directly in `folder`, from every path a store
647/// holds — `None` when it holds none there.
648pub fn listed<'a>(paths: impl Iterator<Item = &'a String>, folder: &str) -> Option<Vec<String>> {
649    let prefix = format!("{folder}/");
650    let mut names: Vec<String> = paths
651        .filter_map(|p| p.strip_prefix(&prefix))
652        .filter(|rest| !rest.contains('/'))
653        .map(str::to_string)
654        .collect();
655    names.sort();
656    (!names.is_empty()).then_some(names)
657}
658
659impl Files for HashMap<String, String> {
660    fn bytes(&self, path: &str) -> Option<Vec<u8>> {
661        self.get(path).map(|s| s.clone().into_bytes())
662    }
663    fn list(&self, path: &str) -> Option<Vec<String>> {
664        listed(self.keys(), path)
665    }
666}
667
668/// A resolved design: its tree, each distinct image file its `Image`s show and
669/// font file its texts are set in, and whether it is **themed** — whether any
670/// `theme.` reference reached its nodes.
671#[derive(Debug, Clone)]
672pub struct Scene {
673    /// The tree's root node: the root design's `Frame`.
674    pub root: Node,
675    /// Each distinct image file the scene's `Image`s show, by id.
676    pub images: ImageFiles,
677    /// Each font file the scene's texts are set in, by id.
678    pub fonts: FontFiles,
679    /// Whether any `theme.` reference reached the scene's nodes, so its two
680    /// themes can differ.
681    pub themed: bool,
682    /// Where each node is, by its id: what a patch finds its nodes by.
683    pub ids: Ids,
684}
685
686/// Two scenes are the same when they hold the same nodes, image and font
687/// files and themes, however their children were placed.
688impl PartialEq for Scene {
689    fn eq(&self, other: &Scene) -> bool {
690        self.root == other.root
691            && self.images == other.images
692            && self.fonts == other.fonts
693            && self.themed == other.themed
694    }
695}
696
697impl Scene {
698    /// A scene of `root` and its files, its ids indexed.
699    pub fn new(root: Node, images: ImageFiles, fonts: FontFiles, themed: bool) -> Scene {
700        let ids = Ids::of(&root);
701        Scene {
702            root,
703            images,
704            fonts,
705            themed,
706            ids,
707        }
708    }
709
710    /// The node with id `id`, if the scene has it.
711    pub fn node(&self, id: &NodeId) -> Option<&Node> {
712        self.at(self.ids.get(id)?)
713    }
714
715    /// The node at `order`, if any.
716    pub fn at(&self, order: &[OrderKey]) -> Option<&Node> {
717        let mut at = &self.root;
718        for k in order {
719            at = at.children.get(k)?;
720        }
721        Some(at)
722    }
723
724    /// The node at `order`, to change, if any.
725    pub fn at_mut(&mut self, order: &[OrderKey]) -> Option<&mut Node> {
726        let mut at = &mut self.root;
727        for k in order {
728            at = at.children.get_mut(k)?;
729        }
730        Some(at)
731    }
732}
733
734/// Where each node of a scene is, by its id: what a patch finds its nodes
735/// by.
736#[derive(Clone, Debug, Default)]
737pub struct Ids(HashMap<NodeId, Order>);
738
739impl Ids {
740    /// Every node of the tree under `root`.
741    pub fn of(root: &Node) -> Ids {
742        let mut ids = Ids::default();
743        ids.add(root, Vec::new());
744        ids
745    }
746
747    /// `n` and the nodes under it, `n` at `order`.
748    pub fn add(&mut self, n: &Node, order: Order) {
749        for (k, c) in n.children.entries() {
750            let mut o = order.clone();
751            o.push(k.clone());
752            self.add(c, o);
753        }
754        self.0.insert(n.id.clone(), order);
755    }
756
757    /// Forgets `n` and the nodes under it.
758    pub fn remove(&mut self, n: &Node) {
759        self.0.remove(&n.id);
760        for c in &n.children {
761            self.remove(c);
762        }
763    }
764
765    /// Where the node `id` is; `None` when the scene has no such node.
766    pub fn get(&self, id: &NodeId) -> Option<&Order> {
767        self.0.get(id)
768    }
769
770    /// Whether the scene has a node `id`.
771    pub fn contains(&self, id: &NodeId) -> bool {
772        self.0.contains_key(id)
773    }
774
775    /// How many nodes the scene has.
776    pub fn len(&self) -> usize {
777        self.0.len()
778    }
779
780    /// Whether the scene has no nodes.
781    pub fn is_empty(&self) -> bool {
782        self.0.is_empty()
783    }
784}
785
786/// A scene's image files by id, each decoded once however many `Image`s
787/// show it.
788pub type ImageFiles = std::collections::BTreeMap<ImageId, Arc<ImageFile>>;
789
790/// Image files compare by their identity, which is their bytes.
791impl PartialEq for ImageFile {
792    fn eq(&self, other: &ImageFile) -> bool {
793        self.id == other.id
794    }
795}
796
797mod edit;
798#[cfg(test)]
799mod tests;
800#[cfg(test)]
801pub(crate) use edit::Bare;
802pub use edit::{Applied, Edit, Edits, Holder, Undo, Uses, applied, apply, subtree};