Skip to main content

devpage_design/render/
drawing.rs

1//! A drawing: a scene laid out and made into its display list in one
2//! theme, kept so later scenes update it; its area and the images it paints.
3
4use std::collections::{BTreeMap, BTreeSet, HashMap};
5
6use kurbo::{Rect as KRect, Vec2};
7use peniko::ImageData;
8
9use crate::display::{
10    Blend, Builder, Chunk, Clip, Effect, Id, List, Order, Placed, RunId, Space, Transform,
11};
12use crate::scene::{self, ImageId, Node, Origin, Scene, Theme};
13use crate::tree::{NodeId as SceneId, OrderKey};
14
15use super::*;
16
17/// An image a drawing paints, and what it shows: an image file, known by
18/// its id, or a shadow's pixels.
19#[derive(Clone)]
20pub(super) struct Painted {
21    /// The decoded pixels the list draws: an image file's, at its own pixel
22    /// size, or a shadow's, blurred — compared byte by byte only for a shadow.
23    pub(super) data: ImageData,
24    /// The image file it shows; `None` for a shadow's pixels.
25    pub(super) file: Option<ImageId>,
26}
27
28impl Painted {
29    /// Whether the two show the same pixels.
30    pub(super) fn same(&self, other: &Painted) -> bool {
31        match (self.file, other.file) {
32            (Some(a), Some(b)) => a == b,
33            (None, None) => {
34                (self.data.width, self.data.height) == (other.data.width, other.data.height)
35                    && self.data.data.data() == other.data.data.data()
36            }
37            _ => false,
38        }
39    }
40}
41
42/// A scene laid out, in one theme, and made into its display list: kept, so
43/// a later scene updates it by what changed. Its layout tree, every node's
44/// box by its id, the property-tree nodes each node made, the list, and the
45/// images the list paints.
46pub struct Drawing {
47    /// The layout: the drawing's own tree and each run's.
48    pub(super) laid: Laid,
49    /// The theme it is drawn in.
50    pub(super) theme: Theme,
51    /// Every node's box, in its space's coordinates.
52    pub(super) frames: BTreeMap<Order, Frame>,
53    /// What each node made, by its order.
54    pub(super) recs: BTreeMap<Order, Rec>,
55    /// Each run's place in the list, by its layout's slot.
56    pub(super) shown: HashMap<u32, RunId>,
57    /// For each run, the least start along it, in the design's coordinates,
58    /// of a child an update took out: where what follows moved from.
59    pub(super) shifts: HashMap<RunId, f64>,
60    /// Each run as the last walk through it found it.
61    pub(super) contexts: HashMap<RunId, RunContext>,
62    /// Each node's order, by its id: where a patch's nodes are in it.
63    pub(super) orders: HashMap<SceneId, Order>,
64    /// The display list: chunks under property trees, and their index.
65    pub(crate) list: List,
66    /// The blob each image file is painted from in this drawing.
67    pub(super) blobs: HashMap<ImageId, ImageData>,
68    /// Every image the list paints, each under a blob of its own, in the
69    /// order the list first paints it: what the GPU's atlas holds for this
70    /// drawing, placed as [`crate::atlas::place`] places them.
71    pub(crate) images: Vec<ImageData>,
72    /// What each of `images` shows.
73    pub(super) shows: Vec<Painted>,
74    /// The nodes whose own commands paint an image, in paint order.
75    pub(super) painters: BTreeSet<Order>,
76    /// Whether `images` fit the GPU's atlas together.
77    pub(super) fits: Result<(), Undrawable>,
78    /// How many nodes the last update visited after laying out.
79    pub(super) visited: usize,
80}
81
82/// What an update did to a drawing's tiles: every one, or those over the
83/// rects it touched.
84#[derive(Debug, Clone, PartialEq)]
85pub enum Damage {
86    /// Every tile: a new scene, or the drawing's top-left moved, which moves
87    /// every tile.
88    All,
89    /// The tiles over `rects`, in the design's coordinates — each chunk the
90    /// update changed, where it was and where it is, and the strips the
91    /// drawing's area gained or lost — of a drawing whose top-left is now
92    /// `origin`.
93    Rects {
94        origin: (f64, f64),
95        rects: Vec<KRect>,
96    },
97}
98
99/// The property-tree nodes a scene node made — its transform, its opacity's
100/// effect and its clip — and the images its own commands paint, in order.
101#[derive(Clone)]
102pub(super) struct Rec {
103    /// The scene node's id, under which `orders` finds the node's order.
104    pub(super) node: SceneId,
105    /// The space its box and chunk are in.
106    pub(super) space: Space,
107    /// Its transform node.
108    pub(super) transform: Id,
109    /// Its opacity's effect; `None` when it makes none.
110    pub(super) effect: Option<Id>,
111    /// Its clip; `None` when it makes none.
112    pub(super) clip: Option<Id>,
113    /// The images its own commands paint, in order, each with where it was
114    /// written, for a problem.
115    pub(super) painted: Vec<(Painted, Origin)>,
116}
117
118impl Drawing {
119    /// The design's drawing: its root's box plus anything painted outside
120    /// it, cut by any clipping frame, in whole pixels.
121    pub fn area(&self) -> Frame {
122        self.list.area
123    }
124
125    /// Every node's box, in tree order, in the design's coordinates.
126    pub fn frames(&self) -> Vec<Frame> {
127        self.frames
128            .iter()
129            .map(|(o, f)| {
130                let at = self.list.space_at(&self.recs[o].space);
131                Frame {
132                    x: f.x + at.x as f32,
133                    y: f.y + at.y as f32,
134                    ..*f
135                }
136            })
137            .collect()
138    }
139
140    /// The theme the drawing is drawn in.
141    pub fn theme(&self) -> Theme {
142        self.theme
143    }
144
145    /// The interaction of the topmost node at `(x, y)` — in the design's
146    /// coordinates — that has one, where its clipping frames show it.
147    pub fn action_at(&self, x: f32, y: f32) -> Option<&str> {
148        self.list.action_at(x as f64, y as f64)
149    }
150
151    /// Updates the drawing to `new` by the patch that made it: `applied`,
152    /// what [`crate::scene::apply`] did to the scene the drawing showed — the
153    /// subtrees removed and placed and the nodes changed, by id. Only those
154    /// are laid out and painted again, and nodes that only moved keep their
155    /// chunks — the work is the patch's, never the scene's. The damage it
156    /// returns is what changed; or why `new` can't be painted — its images
157    /// too many for the GPU's atlas — in which case the drawing is `new`'s
158    /// all the same.
159    pub(crate) fn update(
160        &mut self,
161        renderer: &mut Renderer,
162        new: &Scene,
163        applied: &crate::scene::Applied,
164    ) -> Result<Damage, Undrawable> {
165        renderer.update(self, new, applied)
166    }
167
168    /// Rounds anew, before `area` — in the design's coordinates — is painted,
169    /// hit or read, the children of runs there that an update moved by a
170    /// fraction of a pixel: an update moves them by the sums alone and leaves
171    /// their boxes and chunks as they were, so an edit costs what it changed
172    /// and the rounding costs what is read. `scene` is the scene the drawing
173    /// shows. After it, the drawing there is a fresh one's, box for box.
174    pub(crate) fn prepare(&mut self, renderer: &mut Renderer, scene: &Scene, area: KRect) {
175        let mut rounded = false;
176        loop {
177            let stale = self.list.unrounded(area);
178            if stale.is_empty() {
179                break;
180            }
181            for (drid, key) in stale {
182                renderer.reround(self, scene, drid, &key);
183            }
184            self.list.flush();
185            rounded = true;
186        }
187        if rounded {
188            renderer.settle_area(self);
189        }
190    }
191
192    /// [`Drawing::prepare`] over the whole drawing.
193    #[cfg(test)]
194    pub(crate) fn prepare_all(&mut self, renderer: &mut Renderer, scene: &Scene) {
195        let everything = KRect::new(-1e12, -1e12, 1e12, 1e12);
196        self.prepare(renderer, scene, everything);
197    }
198}
199
200impl Renderer {
201    /// The scene laid out once and made into its display list in `theme` —
202    /// every color its value there — or why it can't be drawn: images and
203    /// shadows that don't fit the GPU's atlas together. What the PNG, the
204    /// canvas and `devpage check` all start from.
205    ///
206    /// Each image is painted under a blob of its own, made in the order the
207    /// drawing first paints it — except that a drawing made `after` the one
208    /// a canvas last showed, painting the same images in the same order,
209    /// paints that drawing's: the GPU then keeps the atlas it has, which
210    /// holds exactly them, placed as a fresh one would.
211    pub fn drawing(
212        &mut self,
213        scene: &Scene,
214        theme: Theme,
215        after: Option<&Drawing>,
216    ) -> Result<Drawing, Undrawable> {
217        self.register(&scene.fonts);
218        let mut laid = Laid::build(self, scene);
219        laid.settle_top(self);
220        let root = laid.root;
221        let mut d = Drawing {
222            laid,
223            theme,
224            frames: BTreeMap::new(),
225            recs: BTreeMap::new(),
226            shown: HashMap::new(),
227            shifts: HashMap::new(),
228            contexts: HashMap::new(),
229            orders: HashMap::new(),
230            list: List::new(),
231            blobs: HashMap::new(),
232            images: Vec::new(),
233            shows: Vec::new(),
234            painters: BTreeSet::new(),
235            fits: Ok(()),
236            visited: 0,
237        };
238        self.blobs.clear();
239        let mut made = Vec::new();
240        let (t, c) = (d.list.root_transform, d.list.root_clip);
241        let mut walk = Walk {
242            scene,
243            dirty: &|_| true,
244            relaid: &|_| true,
245            path: None,
246            damage: None,
247            fresh: Some(&mut made),
248            images: true,
249        };
250        self.sync(
251            &mut d,
252            &mut walk,
253            &scene.root,
254            Vec::new(),
255            Owner::Top,
256            root,
257            t,
258            Place::default(),
259            (&Space::Root, Vec2::ZERO),
260            c,
261            None,
262            None,
263            (false, true),
264            None,
265        );
266        d.list.load(made);
267        d.blobs = std::mem::take(&mut self.blobs);
268        self.settle_area(&mut d);
269        self.settle_images(&mut d)?;
270        if let Some(last) = after
271            && last.shows.len() == d.shows.len()
272            && last.shows.iter().zip(&d.shows).all(|(a, b)| a.same(b))
273        {
274            let last_of: HashMap<u64, ImageData> = d
275                .shows
276                .iter()
277                .zip(&last.shows)
278                .map(|(new, old)| (new.data.data.id(), old.data.clone()))
279                .collect();
280            d.list.swap_images(&last_of);
281            for rec in d.recs.values_mut() {
282                for (p, _) in &mut rec.painted {
283                    if let Some(old) = last_of.get(&p.data.data.id()) {
284                        p.data = old.clone();
285                    }
286                }
287            }
288            for data in d.blobs.values_mut() {
289                if let Some(old) = last_of.get(&data.data.id()) {
290                    *data = old.clone();
291                }
292            }
293            d.shows = last.shows.clone();
294            d.images = d.shows.iter().map(|p| p.data.clone()).collect();
295        }
296        Ok(d)
297    }
298
299    /// The drawing's area from its root's box and what its chunks cover,
300    /// rounded out to whole pixels, ignoring the slivers floating point
301    /// leaves on a curve's bounds.
302    pub(super) fn settle_area(&mut self, d: &mut Drawing) {
303        let root = d.frames[&Vec::new()];
304        let mut area = frame_rect(root);
305        if let Some(covered) = d.list.covered() {
306            area = area.union(covered);
307        }
308        const SLIVER: f64 = 0.01;
309        let area = KRect::new(
310            (area.x0 + SLIVER).floor(),
311            (area.y0 + SLIVER).floor(),
312            (area.x1 - SLIVER).ceil(),
313            (area.y1 - SLIVER).ceil(),
314        );
315        d.list.set_area(Frame {
316            x: area.x0 as f32,
317            y: area.y0 as f32,
318            width: area.width() as f32,
319            height: area.height() as f32,
320        });
321    }
322
323    /// The images the drawing paints, in the order it first paints them —
324    /// each image file once — and whether they fit the GPU's atlas together.
325    pub(super) fn settle_images(&mut self, d: &mut Drawing) -> Result<(), Undrawable> {
326        d.fits = self.fit_images(d);
327        d.fits.clone()
328    }
329
330    /// Gathers the images `d` paints — its painters', in paint order, each
331    /// image file once — and whether they fit the GPU's atlas together: refused
332    /// at the first that doesn't.
333    pub(super) fn fit_images(&mut self, d: &mut Drawing) -> Result<(), Undrawable> {
334        let mut files = BTreeSet::new();
335        let mut painted: Vec<(Painted, Origin)> = Vec::new();
336        for order in &d.painters {
337            for (p, at) in &d.recs[order].painted {
338                if p.file.is_none_or(|id| files.insert(id)) {
339                    painted.push((p.clone(), at.clone()));
340                }
341            }
342        }
343        d.blobs.retain(|id, _| files.contains(id));
344        d.shows = painted.iter().map(|(p, _)| p.clone()).collect();
345        d.images = d.shows.iter().map(|p| p.data.clone()).collect();
346        let sizes: Vec<(u32, u32)> = painted
347            .iter()
348            .map(|(p, _)| (p.data.width, p.data.height))
349            .collect();
350        if let Err(n) = crate::atlas::place(&sizes) {
351            let (Painted { data, .. }, at) = &painted[n];
352            let what = if at.file.is_empty() {
353                "an image"
354            } else {
355                "this"
356            };
357            return Err(Undrawable {
358                message: format!(
359                    "{what} doesn't fit: the images a drawing paints — its image files, \
360                     at most {side} pixels a side, and its shadows — share the GPU's one \
361                     {atlas}×{atlas} atlas, and the {n} before this {w}×{h} fill it",
362                    side = scene::MAX_IMAGE_SIDE,
363                    atlas = crate::atlas::SIDE,
364                    w = data.width,
365                    h = data.height,
366                ),
367                at: Some(at.clone()),
368            });
369        }
370        Ok(())
371    }
372
373    /// Makes `node`'s chunk again when it is dirty, new or another size, or
374    /// moves it when only its place changed; then its children's. `remade`
375    /// says its parent's clip or effect was made anew, which its own
376    /// commands are under; `all` that every node under it is to be visited.
377    /// `space` is the space it is in and where that space's origin is in the
378    /// design's coordinates; `item`, the run and key when it is a run's
379    /// child, whose place the run's sums keep.
380    #[allow(clippy::too_many_arguments)]
381    pub(super) fn sync(
382        &mut self,
383        d: &mut Drawing,
384        w: &mut Walk,
385        node: &Node,
386        order: Order,
387        owner: Owner,
388        id: NodeId,
389        parent_t: Id,
390        parent: Place,
391        (space, space_at): (&Space, Vec2),
392        clip: Id,
393        cut: Option<KRect>,
394        effect: Option<Id>,
395        (remade, all_below): (bool, bool),
396        item: Option<(RunId, OrderKey)>,
397    ) -> bool {
398        let (abs, place) = placed(d.laid.tree(owner), id, parent, order.is_empty());
399        let f = Frame {
400            x: abs.x - space_at.x as f32,
401            y: abs.y - space_at.y as f32,
402            ..abs
403        };
404        let parent_origin = Vec2::new(
405            parent.at.0 as f64 - space_at.x,
406            parent.at.1 as f64 - space_at.y,
407        );
408        let origin = Vec2::new(f.x as f64, f.y as f64);
409        d.visited += 1;
410        let old = d.recs.remove(&order);
411        let is_new = old.is_none();
412        let was = d.frames.insert(order.clone(), f);
413        let resized = was.is_none_or(|was| (was.width, was.height) != (f.width, f.height));
414        let moved = was.is_none_or(|was| (was.x, was.y) != (f.x, f.y));
415        let cut_changed = d.list.chunk(&order).is_none_or(|c| c.cut != cut);
416        let dirty = (w.dirty)(&order);
417        let remake = old.is_none() || remade || dirty || resized;
418        let trees = &mut d.list.trees;
419        let offset = if item.is_some() {
420            Vec2::ZERO
421        } else {
422            origin - parent_origin
423        };
424        // Its transform is kept, and moved: its children's are under it.
425        let transform = match &old {
426            Some(rec) => {
427                let t = trees.transforms.get_mut(rec.transform);
428                t.offset = offset;
429                t.item = item.clone();
430                rec.transform
431            }
432            None => trees.transforms.add(Transform {
433                parent: Some(parent_t),
434                offset,
435                item: item.clone(),
436            }),
437        };
438        let mut children_remade = remade;
439        let (own_effect, own_clip) = if remake {
440            // Its opacity and its clip are changed in place where they stay,
441            // so what its children paint under them still names them.
442            // A frame with children always has its own effect and clip, at
443            // no opacity and no shape when it has neither, so its look
444            // changing — opacity or clip coming or going — changes them in
445            // place and reaches none of its children.
446            let parent_node = !node.children.is_empty();
447            let opacity = (node.opacity < 1.0 || parent_node).then_some(node.opacity);
448            let had = old.as_ref().and_then(|r| r.effect);
449            let new_effect = match (had, opacity) {
450                (Some(e), Some(o)) if !remade => {
451                    trees.effects.get_mut(e).blend = Blend::Opacity(o);
452                    Some(e)
453                }
454                (had, o) => {
455                    if let Some(e) = had {
456                        trees.effects.remove(e);
457                    }
458                    children_remade |= had.is_some() || o.is_some();
459                    o.map(|o| {
460                        trees.effects.add(Effect {
461                            parent: effect,
462                            clip,
463                            transform,
464                            blend: Blend::Opacity(o),
465                            bounds: None,
466                        })
467                    })
468                }
469            };
470            let shape = if node.clip {
471                Some(node_shape(
472                    node,
473                    KRect::new(0.0, 0.0, f.width as f64, f.height as f64),
474                    0.0,
475                ))
476            } else {
477                parent_node.then(kurbo::BezPath::new)
478            };
479            let had = old.as_ref().and_then(|r| r.clip);
480            let new_clip = match (had, shape) {
481                (Some(c), Some(path)) if !remade => {
482                    trees.clips.get_mut(c).path = path;
483                    Some(c)
484                }
485                (had, shape) => {
486                    if let Some(c) = had {
487                        trees.clips.remove(c);
488                    }
489                    children_remade |= had.is_some() || shape.is_some();
490                    shape.map(|path| {
491                        trees.clips.add(Clip {
492                            parent: Some(clip),
493                            transform,
494                            path,
495                        })
496                    })
497                }
498            };
499            (new_effect, new_clip)
500        } else {
501            let rec = old.as_ref().expect("kept");
502            (rec.effect, rec.clip)
503        };
504        let under = own_effect.or(effect);
505        let was = d.list.take(&order);
506        let (chunk, painted) = match was {
507            Some(c) if !remake => {
508                let moved = c.origin != origin || c.cut != cut;
509                let at = d.list.space_at(space);
510                if moved && let Some(damage) = w.damage.as_deref_mut() {
511                    damage.extend(c.bounds.map(|b| b + at));
512                }
513                let c = c.moved(origin, cut);
514                if moved && let Some(damage) = w.damage.as_deref_mut() {
515                    damage.extend(c.bounds.map(|b| b + space_at));
516                }
517                (c, old.expect("kept").painted)
518            }
519            was => {
520                if let Some(c) = &was {
521                    if let Some(damage) = w.damage.as_deref_mut() {
522                        let at = d.list.space_at(&c.space);
523                        damage.extend(c.bounds.map(|b| b + at));
524                    }
525                    d.list.free(&c.made);
526                }
527                let local = Frame {
528                    x: 0.0,
529                    y: 0.0,
530                    width: f.width,
531                    height: f.height,
532                };
533                self.painted.clear();
534                let mut covers = Vec::new();
535                let mut b = Builder::new(&mut d.list.trees, transform, clip, under);
536                self.own(w.scene, node, local, d.theme, &mut b, &mut covers);
537                let mut built = b.finish();
538                let mut painted = std::mem::take(&mut self.painted);
539                // A shadow that paints the very pixels it painted before
540                // keeps its blobs, so the GPU keeps its atlas.
541                if let Some(rec) = &old
542                    && rec.painted.len() == painted.len()
543                    && rec
544                        .painted
545                        .iter()
546                        .zip(&painted)
547                        .all(|(a, b)| a.0.same(&b.0))
548                {
549                    let last_of: HashMap<u64, ImageData> = painted
550                        .iter()
551                        .zip(&rec.painted)
552                        .map(|(new, old)| (new.0.data.data.id(), old.0.data.clone()))
553                        .collect();
554                    swap(&mut built.0, &last_of);
555                    painted = rec.painted.clone();
556                }
557                let action = node
558                    .on_click
559                    .clone()
560                    .map(|a| (a, KRect::new(0.0, 0.0, f.width as f64, f.height as f64)));
561                let c = Chunk::new(transform, space.clone(), origin, built, covers, action, cut);
562                if let Some(damage) = w.damage.as_deref_mut() {
563                    damage.extend(c.bounds.map(|b| b + space_at));
564                }
565                if !painted.is_empty() || old.as_ref().is_some_and(|r| !r.painted.is_empty()) {
566                    w.images = true;
567                }
568                (c, painted)
569            }
570        };
571        if painted.is_empty() {
572            d.painters.remove(&order);
573        } else {
574            d.painters.insert(order.clone());
575        }
576        d.orders.insert(node.id.clone(), order.clone());
577        d.recs.insert(
578            order.clone(),
579            Rec {
580                node: node.id.clone(),
581                space: space.clone(),
582                transform,
583                effect: own_effect,
584                clip: own_clip,
585                painted,
586            },
587        );
588        match w.fresh.as_deref_mut() {
589            Some(fresh) if *space == Space::Root => fresh.push((order.clone(), chunk)),
590            _ => d.list.put(order.clone(), chunk),
591        }
592        let rect = frame_rect(f);
593        let (inner, inner_cut) = match own_clip {
594            Some(c) if node.clip => (c, Some(cut.map_or(rect, |k| rect.intersect(k)))),
595            Some(c) => (c, cut),
596            None => (clip, cut),
597        };
598        // Its children: all of them when what they are placed by or drawn
599        // under changed; otherwise only those on a changed node's path, and
600        // the rest too when one of those changed size, which can move them.
601        let all = w.path.is_none()
602            || all_below
603            || is_new
604            || (w.relaid)(&order)
605            || resized
606            || moved
607            || cut_changed
608            || children_remade;
609        if leaf_of(node, &w.scene.images).is_some() {
610            return resized;
611        }
612        let on_path = match (all, w.path) {
613            (false, Some(path)) => path.get(&order).cloned().unwrap_or_default(),
614            _ => BTreeSet::new(),
615        };
616        let down = Down {
617            transform,
618            place,
619            space,
620            space_at,
621            clip: inner,
622            cut: inner_cut,
623            effect: under,
624            remade: children_remade,
625        };
626        if let Some(&rid) = d.laid.run_of.get(&order) {
627            // A run's children are placed by its sums: its own move or change
628            // of size moves them without a visit — what does need one, a
629            // move by a fraction of a pixel, a new breadth or a new padding,
630            // the run finds itself.
631            let every = w.path.is_none() || all_below || is_new || children_remade;
632            let on_path = match w.path {
633                Some(path) if !every => path.get(&order).cloned().unwrap_or_default(),
634                _ => BTreeSet::new(),
635            };
636            self.sync_run(
637                d, w, node, &order, owner, id, rid, &down, every, &on_path, is_new,
638            );
639            return resized;
640        }
641        let visit = |r: &mut Renderer, d: &mut Drawing, w: &mut Walk, k: &OrderKey, all: bool| {
642            let Some(child) = node.children.get(k) else {
643                return false;
644            };
645            let mut o = order.clone();
646            o.push(k.clone());
647            let (owner, id) = d.laid.nodes[&o];
648            r.sync(
649                d,
650                w,
651                child,
652                o,
653                owner,
654                id,
655                down.transform,
656                down.place,
657                (down.space, down.space_at),
658                down.clip,
659                down.cut,
660                down.effect,
661                (down.remade, all),
662                None,
663            )
664        };
665        // Only in auto layout does one child's size move its siblings.
666        let flows = node.layout != scene::Layout::None;
667        if all {
668            for k in node.children.entries().map(|(k, _)| k) {
669                visit(self, d, w, k, all_below);
670            }
671        } else {
672            let mut moves = false;
673            for k in &on_path {
674                moves |= visit(self, d, w, k, false);
675            }
676            if moves && flows {
677                for k in node.children.entries().map(|(k, _)| k) {
678                    if !on_path.contains(k) {
679                        visit(self, d, w, k, false);
680                    }
681                }
682            }
683        }
684        resized
685    }
686
687    /// A run's children: each placed by the run's sums, those `all` or on
688    /// the path visited, and — when one of them changed size by a fraction
689    /// of a pixel, which moves where every child after it rounds — every
690    /// child after it too. A child that changed size moves the ones after it
691    /// by the sums alone; their damage is one rectangle, from where the
692    /// first change starts to where the run ends.
693    #[allow(clippy::too_many_arguments)]
694    fn sync_run(
695        &mut self,
696        d: &mut Drawing,
697        w: &mut Walk,
698        node: &Node,
699        order: &Order,
700        owner: Owner,
701        id: NodeId,
702        rid: u32,
703        down: &Down,
704        all: bool,
705        on_path: &BTreeSet<OrderKey>,
706        is_new: bool,
707    ) {
708        if d.laid.runs.get(rid).free {
709            return self.sync_free(
710                d, w, node, order, owner, id, rid, down, all, on_path, is_new,
711            );
712        }
713        let size = d.laid.tree(owner).unrounded_layout(id).size;
714        let Some((run, asked, lead, gap)) = d.laid.run_places(rid, size) else {
715            return;
716        };
717        let (pc0, _) = run.padding_across();
718        let (row, line, align) = (run.row, asked.line, run.align);
719        let drid = match d.shown.get(&rid) {
720            Some(&r) => r,
721            None => {
722                let r = d.list.add_run(down.space.clone());
723                d.shown.insert(rid, r);
724                r
725            }
726        };
727        let raw = Vec2::new(
728            down.place.raw.0 as f64 - down.space_at.x,
729            down.place.raw.1 as f64 - down.space_at.y,
730        );
731        let at = Vec2::new(
732            down.place.at.0 as f64 - down.space_at.x,
733            down.place.at.1 as f64 - down.space_at.y,
734        );
735        let old_entry = d.list.run(drid).entry().map(|e| e + down.space_at);
736        let changed = {
737            let dr = d.list.run(drid);
738            // What every child's own layout or record holds: its direction,
739            // the gap each carries, its line's breadth. A move of the run, by
740            // any amount, or of where its first child starts, is only where
741            // the sums place them — rounded again lazily, when read.
742            // A new breadth moves the children across only where they are
743            // centred or set at the end; elsewhere it reaches only the
744            // children it laid out again, which the layout lists.
745            is_new
746                || dr.row != row
747                || (dr.line != line as f64 && run.align != crate::scene::Align::Start)
748        };
749        // Where its children start and how far apart they are are the run's
750        // own: a change of either moves every child by the sums, rounded
751        // anew when read, and damages the run.
752        let spaced = {
753            let dr = d.list.run(drid);
754            !is_new && (dr.gap != gap || dr.start != lead as f64)
755        };
756        // A new `align` moves every child across that doesn't stretch: each
757        // one's box genuinely moves, so each is placed again — its subtree,
758        // in its own coordinates, is not.
759        let realign = !is_new && d.contexts.get(&drid).is_some_and(|c| c.align != align);
760        let relaid = std::mem::take(&mut d.laid.runs.get_mut(rid).relaid);
761        {
762            let dr = d.list.run_mut(drid);
763            dr.raw = raw;
764            dr.at = at;
765            dr.origin = down.space_at;
766            dr.row = row;
767            dr.start = lead as f64;
768            dr.across = pc0 as f64;
769            dr.gap = gap;
770            dr.line = line as f64;
771            dr.cut = down.cut;
772        }
773        d.list.resum(drid);
774        let every = all || changed;
775        let local = |v: (f32, f32)| (v.0 - down.space_at.x as f32, v.1 - down.space_at.y as f32);
776        d.contexts.insert(
777            drid,
778            RunContext {
779                order: order.clone(),
780                owner,
781                id,
782                rid,
783                transform: down.transform,
784                place: Place {
785                    at: local(down.place.at),
786                    raw: local(down.place.raw),
787                },
788                space: down.space.clone(),
789                clip: down.clip,
790                effect: down.effect,
791                align,
792            },
793        );
794        let mut shift: Option<f64> = d.shifts.remove(&drid);
795        let keys: Vec<OrderKey> = if every || realign {
796            node.children.entries().map(|(k, _)| k.clone()).collect()
797        } else {
798            on_path.union(&relaid).cloned().collect()
799        };
800        let mut queue: std::collections::VecDeque<OrderKey> = keys.into();
801        let mut seen = BTreeSet::new();
802        while let Some(k) = queue.pop_front() {
803            if !seen.insert(k.clone()) {
804                continue;
805            }
806            let Some(child) = node.children.get(&k) else {
807                continue;
808            };
809            let (run, asked, _, _) = d.laid.run_places(rid, size).expect("placed");
810            let Some(s) = run.size_of(asked, &k) else {
811                continue;
812            };
813            let stretch = run.children[&k].stretch;
814            let offset = run.across(line, &s, stretch) as f64;
815            let child_node = run.children[&k].node;
816            self.relay(&mut d.laid.runs, rid, &k, line);
817            let (before, old_size) = {
818                let dr = d.list.run(drid);
819                let before = dr.prefix(&k);
820                (before, dr.child(&k).map(|(_, p)| p.size))
821            };
822            let item = child_place(down.place, row, lead as f64 + before, pc0 as f64 + offset);
823            let item_at = Vec2::new(item.at.0 as f64, item.at.1 as f64);
824            let mut o = order.clone();
825            o.push(k.clone());
826            self.sync(
827                d,
828                w,
829                child,
830                o,
831                Owner::Run(rid),
832                child_node,
833                down.transform,
834                item,
835                (&Space::Item(drid, k.clone()), item_at),
836                down.clip,
837                None,
838                down.effect,
839                (down.remade, every),
840                Some((drid, k.clone())),
841            );
842            let delta = {
843                let (raw, at) = d.list.run(drid).place(before, offset);
844                at - raw
845            };
846            d.list.place_child(
847                drid,
848                k.clone(),
849                Some(Placed::new(s.along as f64, offset, delta)),
850            );
851            let grew = old_size.map_or(s.along as f64 + 1.0, |o| s.along as f64 - o);
852            if grew != 0.0 {
853                let start = d.list.space_at(down.space) + d.list.run(drid).place(before, offset).1;
854                let start = if row { start.x } else { start.y };
855                // The children after it move by the sums; any it moves by a
856                // fraction of a pixel round anew when they are next read.
857                shift = Some(shift.map_or(start, |s: f64| s.min(start)));
858            }
859        }
860        d.list.flush();
861        if spaced {
862            let first = d.list.space_at(down.space) + d.list.run(drid).place(0.0, 0.0).1;
863            let first = if row { first.x } else { first.y };
864            shift = Some(shift.map_or(first, |s: f64| s.min(first)));
865        }
866        if let Some(start) = shift
867            && let Some(damage) = w.damage.as_deref_mut()
868        {
869            let new_entry = d.list.run(drid).entry().map(|e| e + down.space_at);
870            if let Some(both) = match (old_entry, new_entry) {
871                (Some(a), Some(b)) => Some(a.union(b)),
872                (a, b) => a.or(b),
873            } {
874                let r = if row {
875                    KRect::new(start.max(both.x0), both.y0, both.x1, both.y1)
876                } else {
877                    KRect::new(both.x0, start.max(both.y0), both.x1, both.y1)
878                };
879                if r.width() > 0.0 && r.height() > 0.0 {
880                    damage.push(r);
881                }
882            }
883        }
884    }
885}
886
887impl Renderer {
888    /// A free run's children: each at its own place in the frame, those on
889    /// the path or laid out again visited — every one when the run is new or
890    /// all are to be — none of them moved by another's change. A move of the
891    /// frame by a fraction of a pixel rounds them anew when read.
892    #[allow(clippy::too_many_arguments)]
893    fn sync_free(
894        &mut self,
895        d: &mut Drawing,
896        w: &mut Walk,
897        node: &Node,
898        order: &Order,
899        owner: Owner,
900        id: NodeId,
901        rid: u32,
902        down: &Down,
903        all: bool,
904        on_path: &BTreeSet<OrderKey>,
905        is_new: bool,
906    ) {
907        let drid = match d.shown.get(&rid) {
908            Some(&r) => r,
909            None => {
910                let r = d.list.add_run(down.space.clone());
911                d.shown.insert(rid, r);
912                r
913            }
914        };
915        let local = |v: (f32, f32)| (v.0 - down.space_at.x as f32, v.1 - down.space_at.y as f32);
916        {
917            let dr = d.list.run_mut(drid);
918            dr.free = true;
919            let (raw, at) = (local(down.place.raw), local(down.place.at));
920            dr.raw = Vec2::new(raw.0 as f64, raw.1 as f64);
921            dr.at = Vec2::new(at.0 as f64, at.1 as f64);
922            dr.origin = down.space_at;
923            dr.cut = down.cut;
924        }
925        d.list.resum(drid);
926        d.contexts.insert(
927            drid,
928            RunContext {
929                order: order.clone(),
930                owner,
931                id,
932                rid,
933                transform: down.transform,
934                place: Place {
935                    at: local(down.place.at),
936                    raw: local(down.place.raw),
937                },
938                space: down.space.clone(),
939                clip: down.clip,
940                effect: down.effect,
941                align: crate::scene::Align::Start,
942            },
943        );
944        let relaid = std::mem::take(&mut d.laid.runs.get_mut(rid).relaid);
945        let keys: Vec<OrderKey> = if all || is_new {
946            node.children.entries().map(|(k, _)| k.clone()).collect()
947        } else {
948            on_path.union(&relaid).cloned().collect()
949        };
950        for k in keys {
951            if node.children.get(&k).is_none() {
952                continue;
953            }
954            self.free_item(d, w, node, order, rid, drid, &k, down, all);
955        }
956        d.list.flush();
957    }
958
959    /// A free run's child `k` synced at its own place: its boxes and chunks
960    /// made where they changed, and its place in the run's index.
961    #[allow(clippy::too_many_arguments)]
962    fn free_item(
963        &mut self,
964        d: &mut Drawing,
965        w: &mut Walk,
966        node: &Node,
967        order: &Order,
968        rid: u32,
969        drid: RunId,
970        k: &OrderKey,
971        down: &Down,
972        all: bool,
973    ) {
974        let child = node.children.get(k).expect("a child");
975        self.relay_free(&mut d.laid.runs, rid, k);
976        let child_node = d.laid.runs.get(rid).children[k].node;
977        let (abs, _) = placed(d.laid.tree(Owner::Run(rid)), child_node, down.place, false);
978        let l = *d.laid.tree(Owner::Run(rid)).unrounded_layout(child_node);
979        let item_at = Vec2::new(abs.x as f64, abs.y as f64);
980        let mut o = order.clone();
981        o.push(k.clone());
982        self.sync(
983            d,
984            w,
985            child,
986            o,
987            Owner::Run(rid),
988            child_node,
989            down.transform,
990            down.place,
991            (&Space::Item(drid, k.clone()), item_at),
992            down.clip,
993            None,
994            down.effect,
995            (down.remade, all),
996            Some((drid, k.clone())),
997        );
998        let at = Vec2::new(l.location.x as f64, l.location.y as f64);
999        let delta = {
1000            let (raw, rounded) = d.list.run(drid).place_at(at);
1001            rounded - raw
1002        };
1003        d.list
1004            .place_child(drid, k.clone(), Some(Placed::at(at, delta)));
1005    }
1006
1007    /// Run `drid`'s child `key` rounded where the run's sums now place it:
1008    /// its subtree's boxes and chunks made again as a walk through its run
1009    /// would make them.
1010    pub(super) fn reround(&mut self, d: &mut Drawing, scene: &Scene, drid: RunId, key: &OrderKey) {
1011        let Some(ctx) = d.contexts.get(&drid).cloned() else {
1012            return;
1013        };
1014        let space_at = d.list.space_at(&ctx.space);
1015        let abs = |v: (f32, f32)| (v.0 + space_at.x as f32, v.1 + space_at.y as f32);
1016        let place = Place {
1017            at: abs(ctx.place.at),
1018            raw: abs(ctx.place.raw),
1019        };
1020        if d.laid.runs.get(ctx.rid).free {
1021            let Some(node) = scene.at(&ctx.order) else {
1022                return;
1023            };
1024            let mut walk = Walk {
1025                scene,
1026                dirty: &|_| false,
1027                relaid: &|_| false,
1028                path: None,
1029                damage: None,
1030                fresh: None,
1031                images: false,
1032            };
1033            let down = Down {
1034                transform: ctx.transform,
1035                place,
1036                space: &ctx.space,
1037                space_at,
1038                clip: ctx.clip,
1039                cut: None,
1040                effect: ctx.effect,
1041                remade: false,
1042            };
1043            self.blobs = std::mem::take(&mut d.blobs);
1044            self.free_item(
1045                d, &mut walk, node, &ctx.order, ctx.rid, drid, key, &down, true,
1046            );
1047            d.blobs = std::mem::take(&mut self.blobs);
1048            if walk.images {
1049                let _ = self.settle_images(d);
1050            }
1051            return;
1052        }
1053        let size = d.laid.tree(ctx.owner).unrounded_layout(ctx.id).size;
1054        let Some((run, asked, lead, _)) = d.laid.run_places(ctx.rid, size) else {
1055            return;
1056        };
1057        let line = asked.line;
1058        let Some(s) = run.size_of(asked, key) else {
1059            return;
1060        };
1061        let offset = run.across(line, &s, run.children[key].stretch) as f64;
1062        let (pc0, _) = run.padding_across();
1063        let (row, child_node) = (run.row, run.children[key].node);
1064        self.relay(&mut d.laid.runs, ctx.rid, key, line);
1065        let before = d.list.run(drid).prefix(key);
1066        let item = child_place(place, row, lead as f64 + before, pc0 as f64 + offset);
1067        let item_at = Vec2::new(item.at.0 as f64, item.at.1 as f64);
1068        let mut order = ctx.order.clone();
1069        order.push(key.clone());
1070        let Some(node) = scene.at(&order) else {
1071            return;
1072        };
1073        let mut walk = Walk {
1074            scene,
1075            dirty: &|_| false,
1076            relaid: &|_| false,
1077            path: None,
1078            damage: None,
1079            fresh: None,
1080            images: false,
1081        };
1082        self.blobs = std::mem::take(&mut d.blobs);
1083        self.sync(
1084            d,
1085            &mut walk,
1086            node,
1087            order,
1088            Owner::Run(ctx.rid),
1089            child_node,
1090            ctx.transform,
1091            item,
1092            (&Space::Item(drid, key.clone()), item_at),
1093            ctx.clip,
1094            None,
1095            ctx.effect,
1096            (false, true),
1097            Some((drid, key.clone())),
1098        );
1099        d.blobs = std::mem::take(&mut self.blobs);
1100        let delta = {
1101            let (raw, at) = d.list.run(drid).place(before, offset);
1102            at - raw
1103        };
1104        d.list.place_child(
1105            drid,
1106            key.clone(),
1107            Some(Placed::new(s.along as f64, offset, delta)),
1108        );
1109        if walk.images {
1110            let _ = self.settle_images(d);
1111        }
1112    }
1113}
1114
1115/// Where a run is and what its children are drawn under, as the last walk
1116/// through it found: what rounding a child of it again, lazily, starts from.
1117/// Its places are in its space's coordinates.
1118#[derive(Clone)]
1119pub(super) struct RunContext {
1120    /// The run's node's order: where the scene finds the node again.
1121    pub(super) order: Order,
1122    /// The layout tree the run's node is in.
1123    pub(super) owner: Owner,
1124    /// The run's node in that tree.
1125    pub(super) id: NodeId,
1126    /// The run's layout, by its slot.
1127    pub(super) rid: u32,
1128    /// The transform node its children are under.
1129    pub(super) transform: Id,
1130    /// The run's node's place, which its children are measured from.
1131    pub(super) place: Place,
1132    /// The space the run is in.
1133    pub(super) space: Space,
1134    /// The clip its children are drawn inside.
1135    pub(super) clip: Id,
1136    /// The layer its children are drawn in; `None` outside any.
1137    pub(super) effect: Option<Id>,
1138    /// The run's `align` when its children were last placed.
1139    pub(super) align: crate::scene::Align,
1140}
1141
1142/// What a node's children are visited under.
1143pub(super) struct Down<'a> {
1144    /// The transform node they are under.
1145    pub(super) transform: Id,
1146    /// The node's place, which they are measured from, in the design's
1147    /// coordinates.
1148    pub(super) place: Place,
1149    /// The space they are in.
1150    pub(super) space: &'a Space,
1151    /// Where that space's origin is, in the design's coordinates.
1152    pub(super) space_at: Vec2,
1153    /// The clip they are drawn inside.
1154    pub(super) clip: Id,
1155    /// What the clipping frames above them cut them to; `None` when none does.
1156    pub(super) cut: Option<KRect>,
1157    /// The layer they are drawn in; `None` outside any.
1158    pub(super) effect: Option<Id>,
1159    /// Whether the node's clip or effect was made anew, which their own
1160    /// commands are under.
1161    pub(super) remade: bool,
1162}
1163
1164/// What a [`Renderer::sync`] walk reads and adds to.
1165pub(super) struct Walk<'a> {
1166    /// The scene being drawn.
1167    pub(super) scene: &'a Scene,
1168    /// Whether a node's own attributes changed.
1169    pub(super) dirty: &'a dyn Fn(&Order) -> bool,
1170    /// Whether a node's attributes that place or cut its children changed:
1171    /// what reaches them, where they are in its own space.
1172    pub(super) relaid: &'a dyn Fn(&Order) -> bool,
1173    /// The nodes whose children were added or removed: all their children
1174    /// may have moved.
1175    /// For an update, the children of each node on a changed node's path
1176    /// that lead to one; `None` walks every node.
1177    pub(super) path: Option<&'a HashMap<Order, BTreeSet<OrderKey>>>,
1178    /// For an update, where each chunk made again was and is, in the design's
1179    /// coordinates; `None` gathers none.
1180    pub(super) damage: Option<&'a mut Vec<KRect>>,
1181    /// For a new drawing, the chunks made, to bulk-load the index with.
1182    pub(super) fresh: Option<&'a mut Vec<(Order, Chunk)>>,
1183    /// Whether a chunk made again paints an image, or painted one.
1184    pub(super) images: bool,
1185}
1186
1187/// The commands' images swapped for the blobs `last_of` names.
1188pub(super) fn swap(commands: &mut [crate::display::Command], last_of: &HashMap<u64, ImageData>) {
1189    for c in commands {
1190        if let Draw::Fill(_, Paint::Image(data, _)) = &mut c.draw
1191            && let Some(old) = last_of.get(&data.data.id())
1192        {
1193            *data = old.clone();
1194        }
1195    }
1196}
1197
1198#[cfg(test)]
1199mod tests;