Skip to main content

lichtung_plot/layout/
report.rs

1//! Read-only geometry retained from the accepted native layout.
2
3use crate::layout::{
4    BoundaryRef, PaintBatch, PaintRole, PanelPath, PanelSlot, PanelStep, PixelRect,
5};
6use crate::{Error, Result};
7
8/// A rectangle in CSS pixels, with a top-left origin and downwards y.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Rect {
11    left: f64,
12    top: f64,
13    width: f64,
14    height: f64,
15}
16
17impl Rect {
18    /// Construct a finite rectangle. Empty extents are allowed for measured
19    /// geometry; an operation that needs a positive box checks that separately.
20    pub fn new(left: f64, top: f64, width: f64, height: f64) -> Result<Self> {
21        if ![left, top, width, height, left + width, top + height]
22            .into_iter()
23            .all(f64::is_finite)
24            || width < 0.0
25            || height < 0.0
26        {
27            return Err(Error::Data(
28                "rectangle requires finite coordinates and nonnegative extents".into(),
29            ));
30        }
31        Ok(Self {
32            left,
33            top,
34            width,
35            height,
36        })
37    }
38
39    /// Left edge in CSS pixels.
40    pub const fn left(self) -> f64 {
41        self.left
42    }
43
44    /// Top edge in CSS pixels.
45    pub const fn top(self) -> f64 {
46        self.top
47    }
48
49    /// Horizontal extent.
50    pub const fn width(self) -> f64 {
51        self.width
52    }
53
54    /// Vertical extent.
55    pub const fn height(self) -> f64 {
56        self.height
57    }
58
59    pub(crate) fn from_panel(panel: PixelRect, root_height: f64) -> Result<Self> {
60        Self::new(
61            panel.x0,
62            root_height - panel.y1,
63            panel.width(),
64            panel.height(),
65        )
66    }
67
68    pub(crate) fn from_canonical(bounds: crate::render::coordinates::CanonicalBox) -> Result<Self> {
69        Self::new(
70            bounds.x.value(),
71            bounds.y.value(),
72            bounds.width.value(),
73            bounds.height.value(),
74        )
75    }
76
77    pub(crate) fn union(self, other: Self) -> Self {
78        let left = self.left.min(other.left);
79        let top = self.top.min(other.top);
80        let right = (self.left + self.width).max(other.left + other.width);
81        let bottom = (self.top + self.height).max(other.top + other.height);
82        Self {
83            left,
84            top,
85            width: right - left,
86            height: bottom - top,
87        }
88    }
89
90    pub(crate) fn intersection(self, other: Self) -> Option<Self> {
91        let left = self.left.max(other.left);
92        let top = self.top.max(other.top);
93        let right = (self.left + self.width).min(other.left + other.width);
94        let bottom = (self.top + self.height).min(other.top + other.height);
95        (left < right && top < bottom).then_some(Self {
96            left,
97            top,
98            width: right - left,
99            height: bottom - top,
100        })
101    }
102
103    pub(crate) fn contains(self, other: Self) -> bool {
104        self.left() <= other.left()
105            && self.top() <= other.top()
106            && self.left() + self.width() >= other.left() + other.width()
107            && self.top() + self.height() >= other.top() + other.height()
108    }
109}
110
111/// A semantic selector for an actual allocated rectangle in a frozen root.
112#[derive(Debug, Clone, PartialEq, Eq, Hash)]
113pub struct RectRef(pub(super) RefKind);
114
115#[derive(Debug, Clone, PartialEq, Eq, Hash)]
116pub(super) enum RefKind {
117    Viewport,
118    Slot(usize, usize),
119    Panel(PanelPath),
120    PlotArea(PanelPath),
121    Decoration(PanelPath, LayoutRole, usize),
122}
123
124impl RectRef {
125    /// Horizontal coordinate at a finite fraction of the actual rectangle.
126    pub fn x(&self, fraction: f64) -> Result<super::RectAxisPosition> {
127        super::RectAxisPosition::new(self.clone(), crate::coordinates::AxisRef::X, fraction)
128    }
129
130    /// Vertical coordinate at a finite top-down fraction of the actual rectangle.
131    pub fn y(&self, fraction: f64) -> Result<super::RectAxisPosition> {
132        super::RectAxisPosition::new(self.clone(), crate::coordinates::AxisRef::Y, fraction)
133    }
134
135    /// The reserved root-grid anchor selected by this reference, if any.
136    pub fn reservation_anchor(&self) -> Option<(usize, usize)> {
137        match self.0 {
138            RefKind::Slot(row, column) => Some((row, column)),
139            _ => None,
140        }
141    }
142    /// The complete output viewport.
143    pub const fn viewport() -> Self {
144        Self(RefKind::Viewport)
145    }
146
147    /// The complete footprint of an empty declared slot in the root grid.
148    pub const fn slot(row: usize, column: usize) -> Self {
149        Self(RefKind::Slot(row, column))
150    }
151
152    /// The allocation of an actual content panel.
153    pub fn panel(path: impl Into<PanelPath>) -> Self {
154        Self(RefKind::Panel(path.into()))
155    }
156
157    /// The actual scientific projection area of a uniquely addressed panel.
158    pub fn plot_area(path: impl Into<PanelPath>) -> Self {
159        Self(RefKind::PlotArea(path.into()))
160    }
161
162    pub(crate) fn decoration(path: &PanelPath, role: LayoutRole, index: usize) -> Self {
163        Self(RefKind::Decoration(path.clone(), role, index))
164    }
165}
166
167/// Semantic role of a retained layout node.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
169#[non_exhaustive]
170pub enum LayoutRole {
171    /// Complete output root.
172    Viewport,
173    /// Allocated native grid.
174    Grid,
175    /// Native chart or compound chart allocation.
176    Panel,
177    /// Actual scientific plotting region.
178    PlotArea,
179    /// Allocated title/body text panel.
180    TextPanel,
181    /// A placed local image asset.
182    ImagePanel,
183    /// An already finalized native output used as fixed content.
184    FrozenPanel,
185    /// The actual fixed-source frame inside its allocated panel.
186    ObjectFrame,
187    /// Deliberate empty reservation.
188    ReservedSlot,
189    /// A declared, currently unfilled template slot.
190    VacantSlot,
191    /// Measured plot or root title.
192    Title,
193    /// Measured plot or root subtitle.
194    Subtitle,
195    /// Measured plot or root caption.
196    Caption,
197    /// Actual local guide allocation.
198    Legend,
199    /// Actual shared guide allocation.
200    SharedLegend,
201    /// A declared Canvas column header.
202    ColumnHeader,
203    /// A declared Canvas row header.
204    RowHeader,
205    /// A declared Canvas row title.
206    RowTitle,
207    /// A measured facet header text box.
208    FacetStrip,
209}
210
211/// Whether reliable painted bounds are available for a node.
212#[derive(Debug, Clone, Copy, PartialEq)]
213#[non_exhaustive]
214pub enum InkExtent {
215    /// The node has no painted content of its own.
216    Empty,
217    /// Painted content, if any, is enclosed by this rectangle. In particular,
218    /// a conservative bound intersecting a clip need not contain visible ink.
219    /// This is not a tight-region result or evidence of a nonempty intersection.
220    Bounds(Rect),
221    /// The actual painted extent has not been established.
222    Unknown,
223}
224
225impl InkExtent {
226    pub(crate) fn union(self, other: Self) -> Self {
227        match (self, other) {
228            (Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown,
229            (Self::Empty, value) | (value, Self::Empty) => value,
230            (Self::Bounds(a), Self::Bounds(b)) => Self::Bounds(a.union(b)),
231        }
232    }
233
234    pub(crate) fn clipped(self, clip: Rect) -> Self {
235        match self {
236            Self::Bounds(bounds) => bounds.intersection(clip).map_or(Self::Empty, Self::Bounds),
237            other => other,
238        }
239    }
240}
241
242/// One actual assigned owner in the accepted layout.
243#[derive(Debug, Clone, PartialEq)]
244pub struct LayoutNode {
245    pub(crate) owner: PanelPath,
246    pub(crate) role: LayoutRole,
247    pub(crate) measured: Option<(f64, f64)>,
248    pub(crate) allocated: Rect,
249    pub(crate) ink: InkExtent,
250    pub(crate) clips: Vec<Rect>,
251    pub(crate) rect_ref: Option<RectRef>,
252    pub(crate) children: Vec<Self>,
253}
254
255impl LayoutNode {
256    pub(crate) fn new(
257        owner: PanelPath,
258        role: LayoutRole,
259        allocated: Rect,
260        rect_ref: Option<RectRef>,
261    ) -> Self {
262        Self {
263            owner,
264            role,
265            measured: None,
266            allocated,
267            ink: InkExtent::Unknown,
268            clips: Vec::new(),
269            rect_ref,
270            children: Vec::new(),
271        }
272    }
273
274    /// Actual native panel address.
275    pub fn owner(&self) -> &PanelPath {
276        &self.owner
277    }
278
279    /// This node's layout role.
280    pub const fn role(&self) -> LayoutRole {
281        self.role
282    }
283
284    /// Retained measured size demand, when supplied by the actual producer.
285    pub const fn measured(&self) -> Option<(f64, f64)> {
286        self.measured
287    }
288
289    /// The actual assigned rectangle.
290    pub const fn allocated(&self) -> Rect {
291        self.allocated
292    }
293
294    /// Reliable painted extent, empty or unknown.
295    pub const fn ink(&self) -> InkExtent {
296        self.ink
297    }
298
299    /// Actual clip rectangles of this owner's captured paint batches.
300    pub fn clips(&self) -> &[Rect] {
301        &self.clips
302    }
303
304    /// A semantic selector if this node has an unambiguous reusable rectangle.
305    pub fn rect_ref(&self) -> Option<&RectRef> {
306        self.rect_ref.as_ref()
307    }
308
309    /// Child layout nodes in their actual layout order.
310    pub fn children(&self) -> &[Self] {
311        &self.children
312    }
313
314    fn find(&self, reference: &RectRef) -> Option<Rect> {
315        if self.rect_ref.as_ref() == Some(reference) {
316            return Some(self.allocated);
317        }
318        self.children.iter().find_map(|child| child.find(reference))
319    }
320
321    fn accept_paint(
322        &mut self,
323        batches: &[PaintBatch],
324        owners: &std::collections::HashMap<PanelPath, Vec<usize>>,
325    ) -> Result<()> {
326        if !matches!(
327            self.role,
328            LayoutRole::ReservedSlot
329                | LayoutRole::VacantSlot
330                | LayoutRole::Title
331                | LayoutRole::Subtitle
332                | LayoutRole::Caption
333                | LayoutRole::ColumnHeader
334                | LayoutRole::RowHeader
335                | LayoutRole::RowTitle
336                | LayoutRole::FacetStrip
337        ) {
338            self.ink = InkExtent::Empty;
339            if let Some(indices) = owners.get(&self.owner) {
340                for &index in indices {
341                    let batch = &batches[index];
342                    if self.owns_paint(batch) {
343                        self.ink = self.ink.union(batch.ink());
344                        crate::data::source::reserve_source(&mut self.clips, batch.clips().len())?;
345                        self.clips.extend_from_slice(batch.clips());
346                    }
347                }
348            }
349        }
350        for child in &mut self.children {
351            child.accept_paint(batches, owners)?;
352        }
353        Ok(())
354    }
355
356    fn owns_paint(&self, batch: &PaintBatch) -> bool {
357        use PaintRole::{
358            Annotation, Body, Grid, Headers, Overlay, PanelSurface, Primary, RootProse,
359            RootSurface, RowTitles, SharedAxes, SharedLegend,
360        };
361        match self.role {
362            LayoutRole::Viewport => true,
363            LayoutRole::Grid => {
364                !batch.owner().is_root()
365                    || matches!(
366                        batch.role(),
367                        Headers | RowTitles | SharedAxes | SharedLegend
368                    )
369            }
370            LayoutRole::Panel => !matches!(
371                batch.role(),
372                RootSurface | RootProse | SharedAxes | SharedLegend | Headers | RowTitles
373            ),
374            LayoutRole::PlotArea => {
375                batch.owner() == &self.owner
376                    && matches!(
377                        batch.role(),
378                        Primary | Overlay | Body | PanelSurface | Grid | Annotation
379                    )
380            }
381            LayoutRole::TextPanel => {
382                batch.owner() == &self.owner && batch.role() == PaintRole::TextPanel
383            }
384            LayoutRole::ImagePanel => {
385                batch.owner() == &self.owner && batch.role() == PaintRole::ImagePanel
386            }
387            LayoutRole::FrozenPanel => {
388                batch.owner() == &self.owner && batch.role() == PaintRole::FrozenPanel
389            }
390            LayoutRole::ObjectFrame => {
391                batch.owner() == &self.owner
392                    && matches!(batch.role(), PaintRole::ImagePanel | PaintRole::FrozenPanel)
393            }
394            LayoutRole::Legend => batch.owner() == &self.owner && batch.role() == PaintRole::Legend,
395            LayoutRole::SharedLegend => {
396                batch.owner() == &self.owner && batch.role() == PaintRole::SharedLegend
397            }
398            LayoutRole::ReservedSlot
399            | LayoutRole::VacantSlot
400            | LayoutRole::Title
401            | LayoutRole::Subtitle
402            | LayoutRole::Caption
403            | LayoutRole::ColumnHeader
404            | LayoutRole::RowHeader
405            | LayoutRole::RowTitle
406            | LayoutRole::FacetStrip => false,
407        }
408    }
409
410    pub(crate) fn text_decoration(
411        owner: &PanelPath,
412        role: LayoutRole,
413        index: usize,
414        bounds: PixelRect,
415        placement: crate::render::backend::PlannedTextPlacement,
416        plan: &crate::layout::ResolvedTextPlan,
417        root_height: f64,
418    ) -> Result<Self> {
419        let mut node = Self::new(
420            owner.clone(),
421            role,
422            Rect::from_panel(bounds, root_height)?,
423            Some(RectRef::decoration(owner, role, index)),
424        );
425        node.measured = Some(plan.occupied_size());
426        node.ink = if plan.style.paint.get_alpha() == 0.0 {
427            InkExtent::Empty
428        } else {
429            crate::render::geometry::planned_text_ink_bounds(
430                plan,
431                placement.position,
432                placement.anchor,
433                placement.rotation,
434                placement.origin,
435                placement.reverse_lines,
436            )
437            .map(|ink| {
438                Rect::from_panel(
439                    PixelRect::new(ink.left, ink.right, ink.bottom, ink.top),
440                    root_height,
441                )
442            })
443            .transpose()?
444            .map_or(InkExtent::Empty, InkExtent::Bounds)
445        };
446        if let Some(clip) = crate::layout::text::placement::paint_clip(placement, plan)? {
447            if clip.width() > 0. && clip.height() > 0. {
448                node.clips.push(Rect::from_panel(clip, root_height)?);
449            }
450        }
451        Ok(node)
452    }
453
454    pub(crate) fn from_plot(
455        plot: &crate::decorations::plan::MeasuredPlotPlan,
456        source: &crate::builder::PlotDescription,
457        allocated: Rect,
458        root_height: f64,
459    ) -> Result<Self> {
460        use crate::layout::interior::MarkPayload;
461        let owner = plot.panel_path.clone();
462        let mut node = Self::new(
463            owner.clone(),
464            LayoutRole::Panel,
465            allocated,
466            Some(RectRef::panel(owner.clone())),
467        );
468        let marks = plot.result.marks.as_ref().expect("accepted plot has marks");
469        match &marks.payload {
470            MarkPayload::Matrix(payload) => {
471                let variables = source
472                    .matrix_variables()
473                    .expect("accepted matrix variables");
474                crate::data::source::reserve_source(
475                    &mut node.children,
476                    variables
477                        .len()
478                        .checked_mul(variables.len())
479                        .ok_or_else(|| Error::Render("matrix report shape overflowed".into()))?,
480                )?;
481                for (index, allocation, area) in payload.layout_regions() {
482                    let x = &variables.variables()[index % variables.len()].key;
483                    let y = &variables.variables()[index / variables.len()].key;
484                    node.children.push(Self::region(
485                        owner.clone().matrix(x.clone(), y.clone()),
486                        allocation,
487                        area,
488                        root_height,
489                    )?);
490                }
491            }
492            MarkPayload::Marginal(payload) => {
493                for (region, area) in payload.layout_regions() {
494                    node.children.push(Self::region(
495                        owner.clone().marginal(region),
496                        area,
497                        area,
498                        root_height,
499                    )?);
500                }
501            }
502            _ => node.children.push(Self::plot_area(
503                owner.clone(),
504                plot.result.layout.projection.panel_box(),
505                root_height,
506            )?),
507        }
508        let guide = match &marks.payload {
509            MarkPayload::Matrix(payload) => payload.legend_draw(),
510            MarkPayload::Heatmap(payload) => payload.legend_draw(),
511            MarkPayload::Beeswarm(payload) => payload.legend_draw(),
512            _ => None,
513        };
514        if let Some(guide) = guide {
515            node.children
516                .push(guide.report_node(&owner, root_height, false)?);
517        }
518        Ok(node)
519    }
520
521    fn region(
522        owner: PanelPath,
523        allocation: PixelRect,
524        area: PixelRect,
525        height: f64,
526    ) -> Result<Self> {
527        let mut node = Self::new(
528            owner.clone(),
529            LayoutRole::Panel,
530            Rect::from_panel(allocation, height)?,
531            Some(RectRef::panel(owner.clone())),
532        );
533        node.children.push(Self::plot_area(owner, area, height)?);
534        Ok(node)
535    }
536
537    fn plot_area(owner: PanelPath, area: PixelRect, height: f64) -> Result<Self> {
538        Ok(Self::new(
539            owner.clone(),
540            LayoutRole::PlotArea,
541            Rect::from_panel(area, height)?,
542            Some(RectRef::plot_area(owner)),
543        ))
544    }
545}
546
547/// Occupancy state of one declared Canvas cell.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549#[non_exhaustive]
550pub enum GridCellState {
551    /// Ordinary undeclared space.
552    Empty,
553    /// An anchor with content.
554    Filled,
555    /// An anchor with a deliberate size reservation.
556    Reserved,
557    /// A declared fillable anchor without content.
558    Vacant,
559    /// A nonanchor cell occupied by a spanning owner.
560    Covered,
561}
562
563/// One cell of the actual allocated Canvas grid.
564#[derive(Debug, Clone, PartialEq)]
565pub struct GridCellReport {
566    pub(crate) row: usize,
567    pub(crate) column: usize,
568    pub(crate) state: GridCellState,
569    pub(crate) anchor: Option<(usize, usize)>,
570    pub(crate) slot: Option<PanelSlot>,
571    pub(crate) allocated: Rect,
572}
573
574impl GridCellReport {
575    /// Zero-based row.
576    pub const fn row(&self) -> usize {
577        self.row
578    }
579
580    /// Zero-based column.
581    pub const fn column(&self) -> usize {
582        self.column
583    }
584
585    /// Actual occupancy.
586    pub const fn state(&self) -> GridCellState {
587        self.state
588    }
589
590    /// The actual owning anchor, including for covered cells.
591    pub const fn anchor(&self) -> Option<(usize, usize)> {
592        self.anchor
593    }
594
595    /// Declaration of this cell if it is an anchor.
596    pub fn slot(&self) -> Option<&PanelSlot> {
597        self.slot.as_ref()
598    }
599
600    /// This cell's own track rectangle, independent of any spanning owner.
601    pub const fn allocated(&self) -> Rect {
602        self.allocated
603    }
604}
605
606/// Geometry of one successfully accepted native root.
607#[derive(Debug, Clone, PartialEq)]
608pub struct LayoutReport {
609    viewport: Rect,
610    root_padding: [f64; 4],
611    root_paper: crate::Color,
612    nodes: std::sync::Arc<[LayoutNode]>,
613    grid_cells: std::sync::Arc<[GridCellReport]>,
614    paint_order: std::sync::Arc<[PaintBatch]>,
615    boundaries: std::sync::Arc<[BoundaryRef]>,
616}
617
618impl LayoutReport {
619    pub(crate) fn new(
620        viewport: Rect,
621        root: LayoutNode,
622        grid_cells: Vec<GridCellReport>,
623        root_padding: [f64; 4],
624        root_paper: crate::Color,
625    ) -> Self {
626        Self {
627            viewport,
628            root_padding,
629            root_paper,
630            nodes: std::sync::Arc::from([root]),
631            grid_cells: grid_cells.into(),
632            paint_order: std::sync::Arc::from([]),
633            boundaries: std::sync::Arc::from([]),
634        }
635    }
636
637    pub(crate) fn capture(
638        root: &crate::orchestrator::root::Root<'_>,
639        plan: &crate::orchestrator::plan::MeasuredOwnedPlan,
640    ) -> Result<Self> {
641        use crate::orchestrator::{plan::MeasuredRootContent, root::RootSource};
642        let (width, viewport_height) = plan.size.dimensions()?;
643        let (_, height) = plan.size.layout_dimensions()?;
644        let viewport = Rect::new(0., 0., width, viewport_height)?;
645        let mut node = LayoutNode::new(
646            PanelPath::root(),
647            LayoutRole::Viewport,
648            viewport,
649            Some(RectRef::viewport()),
650        );
651        let mut cells = Vec::new();
652        match (&plan.content, root.source) {
653            (MeasuredRootContent::Single { plot, legend }, RootSource::Plot(source)) => {
654                let mut panel = LayoutNode::from_plot(
655                    plot,
656                    source,
657                    Rect::from_panel(plot.selected.cell, height)?,
658                    height,
659                )?;
660                if plot.result.decoration_mode == crate::spec::DecorationMode::Standard {
661                    if let Some((_, guide)) = legend {
662                        panel
663                            .children
664                            .push(guide.report_node(&plot.panel_path, height, false)?);
665                    }
666                }
667                node.children.push(panel);
668            }
669            (MeasuredRootContent::Facets(plan), RootSource::Plot(_)) => {
670                node.children.push(plan.report_grid(root, height)?);
671            }
672            (MeasuredRootContent::Canvas(plan), RootSource::Canvas(source)) => {
673                let (grid, grid_cells) = source.report_grid(plan, height)?;
674                node.children.push(grid);
675                cells = grid_cells;
676            }
677            _ => {
678                return Err(Error::Render(
679                    "accepted layout does not match its native root".into(),
680                ))
681            }
682        }
683        node.children.extend(
684            plan.frame
685                .root_text
686                .report_nodes(&PanelPath::root(), height)?,
687        );
688        Ok(Self::new(
689            viewport,
690            node,
691            cells,
692            plan.frame.root_padding,
693            plan.root_paint,
694        ))
695    }
696
697    /// The root's actual frozen viewport.
698    pub const fn viewport(&self) -> Rect {
699        self.viewport
700    }
701
702    pub(crate) const fn root_padding(&self) -> [f64; 4] {
703        self.root_padding
704    }
705
706    pub(crate) const fn root_paper(&self) -> crate::Color {
707        self.root_paper
708    }
709
710    /// The actual native layout tree.
711    pub fn nodes(&self) -> &[LayoutNode] {
712        &self.nodes
713    }
714
715    /// Declared root Canvas cells in row-major order, including holes and coverage.
716    /// Empty for a standalone Plot.
717    pub fn grid_cells(&self) -> &[GridCellReport] {
718        &self.grid_cells
719    }
720
721    /// Actual closed drawing batches, in physical bottom-to-top paint order.
722    pub fn paint_order(&self) -> &[PaintBatch] {
723        &self.paint_order
724    }
725
726    /// Stable adjacent gaps in the actual closed native paint scope.
727    pub fn boundaries(&self) -> &[BoundaryRef] {
728        &self.boundaries
729    }
730
731    pub(crate) fn accept_paint(&mut self, mut batches: Vec<PaintBatch>) -> Result<()> {
732        batches.sort_by_key(|batch| (batch.buffer, batch.range.start));
733        for pair in batches.windows(2) {
734            if pair[0].buffer == pair[1].buffer && pair[0].range.end > pair[1].range.start {
735                return Err(Error::Render("native paint batches overlap".into()));
736            }
737        }
738        let mut counts = std::collections::HashMap::new();
739        counts.try_reserve(batches.len()).map_err(|error| {
740            Error::Render(format!("paint identity reservation: {error}").into())
741        })?;
742        for batch in &batches {
743            *counts.entry(batch.reference()).or_insert(0usize) += 1;
744        }
745        let unique = |batch: &PaintBatch| counts.get(batch.reference()) == Some(&1);
746        let mut boundaries = Vec::new();
747        crate::data::source::reserve_source(&mut boundaries, batches.len().saturating_add(1))?;
748        if let Some(first) = batches.first().filter(|batch| unique(batch)) {
749            boundaries.push(BoundaryRef::between(None, Some(first)));
750        }
751        for pair in batches.windows(2) {
752            if unique(&pair[0]) && unique(&pair[1]) {
753                boundaries.push(BoundaryRef::between(Some(&pair[0]), Some(&pair[1])));
754            }
755        }
756        if let Some(last) = batches.last().filter(|batch| unique(batch)) {
757            boundaries.push(BoundaryRef::between(Some(last), None));
758        }
759        drop(counts);
760        let mut owners = std::collections::HashMap::new();
761        for (index, batch) in batches.iter().enumerate() {
762            let steps = batch.owner().steps();
763            for depth in 0..=steps.len() {
764                owners.try_reserve(1).map_err(|error| {
765                    Error::Render(format!("paint owner reservation: {error}").into())
766                })?;
767                let indices = owners
768                    .entry(PanelPath::from_steps(&steps[..depth]))
769                    .or_insert_with(Vec::new);
770                crate::data::source::reserve_source(indices, 1)?;
771                indices.push(index);
772            }
773        }
774        for node in std::sync::Arc::make_mut(&mut self.nodes) {
775            node.accept_paint(&batches, &owners)?;
776        }
777        self.paint_order = batches.into();
778        self.boundaries = boundaries.into();
779        Ok(())
780    }
781
782    fn canonical_panel(&self, panel: &PanelPath) -> Result<PanelPath> {
783        if let Some(PanelStep::Cell(row, column)) = panel.steps().first() {
784            self.check_coverage(*row, *column)?;
785        }
786        let Some(PanelStep::Named(name)) = panel.steps().first() else {
787            return Ok(panel.clone());
788        };
789        let cell = self
790            .grid_cells
791            .iter()
792            .find(|cell| cell.slot.as_ref().and_then(PanelSlot::name) == Some(name))
793            .ok_or_else(|| {
794                crate::errors::Diagnostic::new(
795                    crate::errors::DiagnosticKind::UnknownKey {
796                        key: Some(crate::data::RawKey::from(name.as_str())),
797                    },
798                    format!("frozen Canvas has no panel named {name:?}"),
799                )
800            })
801            .map_err(Error::Data)?;
802        let mut steps = vec![PanelStep::Cell(cell.row, cell.column)];
803        steps.extend_from_slice(&panel.steps()[1..]);
804        Ok(PanelPath::from_steps(&steps))
805    }
806
807    fn check_coverage(&self, row: usize, column: usize) -> Result<()> {
808        if let Some(cell) = self
809            .grid_cells
810            .iter()
811            .find(|cell| cell.row == row && cell.column == column)
812        {
813            if cell.state == GridCellState::Covered {
814                let (r, c) = cell.anchor.expect("covered cell has an anchor");
815                return Err(Error::Data(
816                    format!("Canvas cell ({row}, {column}) is covered by anchor ({r}, {c})").into(),
817                ));
818            }
819        }
820        Ok(())
821    }
822
823    /// Resolve a reference against this exact accepted layout. Names resolve
824    /// within the frozen grid; an edited later configuration cannot affect it.
825    pub fn rect(&self, reference: &RectRef) -> Result<Rect> {
826        let reference = match &reference.0 {
827            RefKind::Slot(row, column) => {
828                self.check_coverage(*row, *column)?;
829                reference.clone()
830            }
831            RefKind::Panel(panel) => RectRef::panel(self.canonical_panel(panel)?),
832            RefKind::PlotArea(panel) => RectRef::plot_area(self.canonical_panel(panel)?),
833            RefKind::Decoration(panel, role, index) => {
834                RectRef::decoration(&self.canonical_panel(panel)?, *role, *index)
835            }
836            RefKind::Viewport => reference.clone(),
837        };
838        self.nodes
839            .iter()
840            .find_map(|node| node.find(&reference))
841            .ok_or_else(|| {
842                Error::Data(format!("no actual allocated rectangle for {reference:?}").into())
843            })
844    }
845}