lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! Read-only geometry retained from the accepted native layout.

use crate::layout::{
    BoundaryRef, PaintBatch, PaintRole, PanelPath, PanelSlot, PanelStep, PixelRect,
};
use crate::{Error, Result};

/// A rectangle in CSS pixels, with a top-left origin and downwards y.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
    left: f64,
    top: f64,
    width: f64,
    height: f64,
}

impl Rect {
    /// Construct a finite rectangle. Empty extents are allowed for measured
    /// geometry; an operation that needs a positive box checks that separately.
    pub fn new(left: f64, top: f64, width: f64, height: f64) -> Result<Self> {
        if ![left, top, width, height, left + width, top + height]
            .into_iter()
            .all(f64::is_finite)
            || width < 0.0
            || height < 0.0
        {
            return Err(Error::Data(
                "rectangle requires finite coordinates and nonnegative extents".into(),
            ));
        }
        Ok(Self {
            left,
            top,
            width,
            height,
        })
    }

    /// Left edge in CSS pixels.
    pub const fn left(self) -> f64 {
        self.left
    }

    /// Top edge in CSS pixels.
    pub const fn top(self) -> f64 {
        self.top
    }

    /// Horizontal extent.
    pub const fn width(self) -> f64 {
        self.width
    }

    /// Vertical extent.
    pub const fn height(self) -> f64 {
        self.height
    }

    pub(crate) fn from_panel(panel: PixelRect, root_height: f64) -> Result<Self> {
        Self::new(
            panel.x0,
            root_height - panel.y1,
            panel.width(),
            panel.height(),
        )
    }

    pub(crate) fn from_canonical(bounds: crate::render::coordinates::CanonicalBox) -> Result<Self> {
        Self::new(
            bounds.x.value(),
            bounds.y.value(),
            bounds.width.value(),
            bounds.height.value(),
        )
    }

    pub(crate) fn union(self, other: Self) -> Self {
        let left = self.left.min(other.left);
        let top = self.top.min(other.top);
        let right = (self.left + self.width).max(other.left + other.width);
        let bottom = (self.top + self.height).max(other.top + other.height);
        Self {
            left,
            top,
            width: right - left,
            height: bottom - top,
        }
    }

    pub(crate) fn intersection(self, other: Self) -> Option<Self> {
        let left = self.left.max(other.left);
        let top = self.top.max(other.top);
        let right = (self.left + self.width).min(other.left + other.width);
        let bottom = (self.top + self.height).min(other.top + other.height);
        (left < right && top < bottom).then_some(Self {
            left,
            top,
            width: right - left,
            height: bottom - top,
        })
    }

    pub(crate) fn contains(self, other: Self) -> bool {
        self.left() <= other.left()
            && self.top() <= other.top()
            && self.left() + self.width() >= other.left() + other.width()
            && self.top() + self.height() >= other.top() + other.height()
    }
}

/// A semantic selector for an actual allocated rectangle in a frozen root.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RectRef(pub(super) RefKind);

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) enum RefKind {
    Viewport,
    Slot(usize, usize),
    Panel(PanelPath),
    PlotArea(PanelPath),
    Decoration(PanelPath, LayoutRole, usize),
}

impl RectRef {
    /// Horizontal coordinate at a finite fraction of the actual rectangle.
    pub fn x(&self, fraction: f64) -> Result<super::RectAxisPosition> {
        super::RectAxisPosition::new(self.clone(), crate::coordinates::AxisRef::X, fraction)
    }

    /// Vertical coordinate at a finite top-down fraction of the actual rectangle.
    pub fn y(&self, fraction: f64) -> Result<super::RectAxisPosition> {
        super::RectAxisPosition::new(self.clone(), crate::coordinates::AxisRef::Y, fraction)
    }

    /// The reserved root-grid anchor selected by this reference, if any.
    pub fn reservation_anchor(&self) -> Option<(usize, usize)> {
        match self.0 {
            RefKind::Slot(row, column) => Some((row, column)),
            _ => None,
        }
    }
    /// The complete output viewport.
    pub const fn viewport() -> Self {
        Self(RefKind::Viewport)
    }

    /// The complete footprint of an empty declared slot in the root grid.
    pub const fn slot(row: usize, column: usize) -> Self {
        Self(RefKind::Slot(row, column))
    }

    /// The allocation of an actual content panel.
    pub fn panel(path: impl Into<PanelPath>) -> Self {
        Self(RefKind::Panel(path.into()))
    }

    /// The actual scientific projection area of a uniquely addressed panel.
    pub fn plot_area(path: impl Into<PanelPath>) -> Self {
        Self(RefKind::PlotArea(path.into()))
    }

    pub(crate) fn decoration(path: &PanelPath, role: LayoutRole, index: usize) -> Self {
        Self(RefKind::Decoration(path.clone(), role, index))
    }
}

/// Semantic role of a retained layout node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LayoutRole {
    /// Complete output root.
    Viewport,
    /// Allocated native grid.
    Grid,
    /// Native chart or compound chart allocation.
    Panel,
    /// Actual scientific plotting region.
    PlotArea,
    /// Allocated title/body text panel.
    TextPanel,
    /// A placed local image asset.
    ImagePanel,
    /// An already finalized native output used as fixed content.
    FrozenPanel,
    /// The actual fixed-source frame inside its allocated panel.
    ObjectFrame,
    /// Deliberate empty reservation.
    ReservedSlot,
    /// A declared, currently unfilled template slot.
    VacantSlot,
    /// Measured plot or root title.
    Title,
    /// Measured plot or root subtitle.
    Subtitle,
    /// Measured plot or root caption.
    Caption,
    /// Actual local guide allocation.
    Legend,
    /// Actual shared guide allocation.
    SharedLegend,
    /// A declared Canvas column header.
    ColumnHeader,
    /// A declared Canvas row header.
    RowHeader,
    /// A declared Canvas row title.
    RowTitle,
    /// A measured facet header text box.
    FacetStrip,
}

/// Whether reliable painted bounds are available for a node.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum InkExtent {
    /// The node has no painted content of its own.
    Empty,
    /// Painted content, if any, is enclosed by this rectangle. In particular,
    /// a conservative bound intersecting a clip need not contain visible ink.
    /// This is not a tight-region result or evidence of a nonempty intersection.
    Bounds(Rect),
    /// The actual painted extent has not been established.
    Unknown,
}

impl InkExtent {
    pub(crate) fn union(self, other: Self) -> Self {
        match (self, other) {
            (Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown,
            (Self::Empty, value) | (value, Self::Empty) => value,
            (Self::Bounds(a), Self::Bounds(b)) => Self::Bounds(a.union(b)),
        }
    }

    pub(crate) fn clipped(self, clip: Rect) -> Self {
        match self {
            Self::Bounds(bounds) => bounds.intersection(clip).map_or(Self::Empty, Self::Bounds),
            other => other,
        }
    }
}

/// One actual assigned owner in the accepted layout.
#[derive(Debug, Clone, PartialEq)]
pub struct LayoutNode {
    pub(crate) owner: PanelPath,
    pub(crate) role: LayoutRole,
    pub(crate) measured: Option<(f64, f64)>,
    pub(crate) allocated: Rect,
    pub(crate) ink: InkExtent,
    pub(crate) clips: Vec<Rect>,
    pub(crate) rect_ref: Option<RectRef>,
    pub(crate) children: Vec<Self>,
}

impl LayoutNode {
    pub(crate) fn new(
        owner: PanelPath,
        role: LayoutRole,
        allocated: Rect,
        rect_ref: Option<RectRef>,
    ) -> Self {
        Self {
            owner,
            role,
            measured: None,
            allocated,
            ink: InkExtent::Unknown,
            clips: Vec::new(),
            rect_ref,
            children: Vec::new(),
        }
    }

    /// Actual native panel address.
    pub fn owner(&self) -> &PanelPath {
        &self.owner
    }

    /// This node's layout role.
    pub const fn role(&self) -> LayoutRole {
        self.role
    }

    /// Retained measured size demand, when supplied by the actual producer.
    pub const fn measured(&self) -> Option<(f64, f64)> {
        self.measured
    }

    /// The actual assigned rectangle.
    pub const fn allocated(&self) -> Rect {
        self.allocated
    }

    /// Reliable painted extent, empty or unknown.
    pub const fn ink(&self) -> InkExtent {
        self.ink
    }

    /// Actual clip rectangles of this owner's captured paint batches.
    pub fn clips(&self) -> &[Rect] {
        &self.clips
    }

    /// A semantic selector if this node has an unambiguous reusable rectangle.
    pub fn rect_ref(&self) -> Option<&RectRef> {
        self.rect_ref.as_ref()
    }

    /// Child layout nodes in their actual layout order.
    pub fn children(&self) -> &[Self] {
        &self.children
    }

    fn find(&self, reference: &RectRef) -> Option<Rect> {
        if self.rect_ref.as_ref() == Some(reference) {
            return Some(self.allocated);
        }
        self.children.iter().find_map(|child| child.find(reference))
    }

    fn accept_paint(
        &mut self,
        batches: &[PaintBatch],
        owners: &std::collections::HashMap<PanelPath, Vec<usize>>,
    ) -> Result<()> {
        if !matches!(
            self.role,
            LayoutRole::ReservedSlot
                | LayoutRole::VacantSlot
                | LayoutRole::Title
                | LayoutRole::Subtitle
                | LayoutRole::Caption
                | LayoutRole::ColumnHeader
                | LayoutRole::RowHeader
                | LayoutRole::RowTitle
                | LayoutRole::FacetStrip
        ) {
            self.ink = InkExtent::Empty;
            if let Some(indices) = owners.get(&self.owner) {
                for &index in indices {
                    let batch = &batches[index];
                    if self.owns_paint(batch) {
                        self.ink = self.ink.union(batch.ink());
                        crate::data::source::reserve_source(&mut self.clips, batch.clips().len())?;
                        self.clips.extend_from_slice(batch.clips());
                    }
                }
            }
        }
        for child in &mut self.children {
            child.accept_paint(batches, owners)?;
        }
        Ok(())
    }

    fn owns_paint(&self, batch: &PaintBatch) -> bool {
        use PaintRole::{
            Annotation, Body, Grid, Headers, Overlay, PanelSurface, Primary, RootProse,
            RootSurface, RowTitles, SharedAxes, SharedLegend,
        };
        match self.role {
            LayoutRole::Viewport => true,
            LayoutRole::Grid => {
                !batch.owner().is_root()
                    || matches!(
                        batch.role(),
                        Headers | RowTitles | SharedAxes | SharedLegend
                    )
            }
            LayoutRole::Panel => !matches!(
                batch.role(),
                RootSurface | RootProse | SharedAxes | SharedLegend | Headers | RowTitles
            ),
            LayoutRole::PlotArea => {
                batch.owner() == &self.owner
                    && matches!(
                        batch.role(),
                        Primary | Overlay | Body | PanelSurface | Grid | Annotation
                    )
            }
            LayoutRole::TextPanel => {
                batch.owner() == &self.owner && batch.role() == PaintRole::TextPanel
            }
            LayoutRole::ImagePanel => {
                batch.owner() == &self.owner && batch.role() == PaintRole::ImagePanel
            }
            LayoutRole::FrozenPanel => {
                batch.owner() == &self.owner && batch.role() == PaintRole::FrozenPanel
            }
            LayoutRole::ObjectFrame => {
                batch.owner() == &self.owner
                    && matches!(batch.role(), PaintRole::ImagePanel | PaintRole::FrozenPanel)
            }
            LayoutRole::Legend => batch.owner() == &self.owner && batch.role() == PaintRole::Legend,
            LayoutRole::SharedLegend => {
                batch.owner() == &self.owner && batch.role() == PaintRole::SharedLegend
            }
            LayoutRole::ReservedSlot
            | LayoutRole::VacantSlot
            | LayoutRole::Title
            | LayoutRole::Subtitle
            | LayoutRole::Caption
            | LayoutRole::ColumnHeader
            | LayoutRole::RowHeader
            | LayoutRole::RowTitle
            | LayoutRole::FacetStrip => false,
        }
    }

    pub(crate) fn text_decoration(
        owner: &PanelPath,
        role: LayoutRole,
        index: usize,
        bounds: PixelRect,
        placement: crate::render::backend::PlannedTextPlacement,
        plan: &crate::layout::ResolvedTextPlan,
        root_height: f64,
    ) -> Result<Self> {
        let mut node = Self::new(
            owner.clone(),
            role,
            Rect::from_panel(bounds, root_height)?,
            Some(RectRef::decoration(owner, role, index)),
        );
        node.measured = Some(plan.occupied_size());
        node.ink = if plan.style.paint.get_alpha() == 0.0 {
            InkExtent::Empty
        } else {
            crate::render::geometry::planned_text_ink_bounds(
                plan,
                placement.position,
                placement.anchor,
                placement.rotation,
                placement.origin,
                placement.reverse_lines,
            )
            .map(|ink| {
                Rect::from_panel(
                    PixelRect::new(ink.left, ink.right, ink.bottom, ink.top),
                    root_height,
                )
            })
            .transpose()?
            .map_or(InkExtent::Empty, InkExtent::Bounds)
        };
        if let Some(clip) = crate::layout::text::placement::paint_clip(placement, plan)? {
            if clip.width() > 0. && clip.height() > 0. {
                node.clips.push(Rect::from_panel(clip, root_height)?);
            }
        }
        Ok(node)
    }

    pub(crate) fn from_plot(
        plot: &crate::decorations::plan::MeasuredPlotPlan,
        source: &crate::builder::PlotDescription,
        allocated: Rect,
        root_height: f64,
    ) -> Result<Self> {
        use crate::layout::interior::MarkPayload;
        let owner = plot.panel_path.clone();
        let mut node = Self::new(
            owner.clone(),
            LayoutRole::Panel,
            allocated,
            Some(RectRef::panel(owner.clone())),
        );
        let marks = plot.result.marks.as_ref().expect("accepted plot has marks");
        match &marks.payload {
            MarkPayload::Matrix(payload) => {
                let variables = source
                    .matrix_variables()
                    .expect("accepted matrix variables");
                crate::data::source::reserve_source(
                    &mut node.children,
                    variables
                        .len()
                        .checked_mul(variables.len())
                        .ok_or_else(|| Error::Render("matrix report shape overflowed".into()))?,
                )?;
                for (index, allocation, area) in payload.layout_regions() {
                    let x = &variables.variables()[index % variables.len()].key;
                    let y = &variables.variables()[index / variables.len()].key;
                    node.children.push(Self::region(
                        owner.clone().matrix(x.clone(), y.clone()),
                        allocation,
                        area,
                        root_height,
                    )?);
                }
            }
            MarkPayload::Marginal(payload) => {
                for (region, area) in payload.layout_regions() {
                    node.children.push(Self::region(
                        owner.clone().marginal(region),
                        area,
                        area,
                        root_height,
                    )?);
                }
            }
            _ => node.children.push(Self::plot_area(
                owner.clone(),
                plot.result.layout.projection.panel_box(),
                root_height,
            )?),
        }
        let guide = match &marks.payload {
            MarkPayload::Matrix(payload) => payload.legend_draw(),
            MarkPayload::Heatmap(payload) => payload.legend_draw(),
            MarkPayload::Beeswarm(payload) => payload.legend_draw(),
            _ => None,
        };
        if let Some(guide) = guide {
            node.children
                .push(guide.report_node(&owner, root_height, false)?);
        }
        Ok(node)
    }

    fn region(
        owner: PanelPath,
        allocation: PixelRect,
        area: PixelRect,
        height: f64,
    ) -> Result<Self> {
        let mut node = Self::new(
            owner.clone(),
            LayoutRole::Panel,
            Rect::from_panel(allocation, height)?,
            Some(RectRef::panel(owner.clone())),
        );
        node.children.push(Self::plot_area(owner, area, height)?);
        Ok(node)
    }

    fn plot_area(owner: PanelPath, area: PixelRect, height: f64) -> Result<Self> {
        Ok(Self::new(
            owner.clone(),
            LayoutRole::PlotArea,
            Rect::from_panel(area, height)?,
            Some(RectRef::plot_area(owner)),
        ))
    }
}

/// Occupancy state of one declared Canvas cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum GridCellState {
    /// Ordinary undeclared space.
    Empty,
    /// An anchor with content.
    Filled,
    /// An anchor with a deliberate size reservation.
    Reserved,
    /// A declared fillable anchor without content.
    Vacant,
    /// A nonanchor cell occupied by a spanning owner.
    Covered,
}

/// One cell of the actual allocated Canvas grid.
#[derive(Debug, Clone, PartialEq)]
pub struct GridCellReport {
    pub(crate) row: usize,
    pub(crate) column: usize,
    pub(crate) state: GridCellState,
    pub(crate) anchor: Option<(usize, usize)>,
    pub(crate) slot: Option<PanelSlot>,
    pub(crate) allocated: Rect,
}

impl GridCellReport {
    /// Zero-based row.
    pub const fn row(&self) -> usize {
        self.row
    }

    /// Zero-based column.
    pub const fn column(&self) -> usize {
        self.column
    }

    /// Actual occupancy.
    pub const fn state(&self) -> GridCellState {
        self.state
    }

    /// The actual owning anchor, including for covered cells.
    pub const fn anchor(&self) -> Option<(usize, usize)> {
        self.anchor
    }

    /// Declaration of this cell if it is an anchor.
    pub fn slot(&self) -> Option<&PanelSlot> {
        self.slot.as_ref()
    }

    /// This cell's own track rectangle, independent of any spanning owner.
    pub const fn allocated(&self) -> Rect {
        self.allocated
    }
}

/// Geometry of one successfully accepted native root.
#[derive(Debug, Clone, PartialEq)]
pub struct LayoutReport {
    viewport: Rect,
    root_padding: [f64; 4],
    root_paper: crate::Color,
    nodes: std::sync::Arc<[LayoutNode]>,
    grid_cells: std::sync::Arc<[GridCellReport]>,
    paint_order: std::sync::Arc<[PaintBatch]>,
    boundaries: std::sync::Arc<[BoundaryRef]>,
}

impl LayoutReport {
    pub(crate) fn new(
        viewport: Rect,
        root: LayoutNode,
        grid_cells: Vec<GridCellReport>,
        root_padding: [f64; 4],
        root_paper: crate::Color,
    ) -> Self {
        Self {
            viewport,
            root_padding,
            root_paper,
            nodes: std::sync::Arc::from([root]),
            grid_cells: grid_cells.into(),
            paint_order: std::sync::Arc::from([]),
            boundaries: std::sync::Arc::from([]),
        }
    }

    pub(crate) fn capture(
        root: &crate::orchestrator::root::Root<'_>,
        plan: &crate::orchestrator::plan::MeasuredOwnedPlan,
    ) -> Result<Self> {
        use crate::orchestrator::{plan::MeasuredRootContent, root::RootSource};
        let (width, viewport_height) = plan.size.dimensions()?;
        let (_, height) = plan.size.layout_dimensions()?;
        let viewport = Rect::new(0., 0., width, viewport_height)?;
        let mut node = LayoutNode::new(
            PanelPath::root(),
            LayoutRole::Viewport,
            viewport,
            Some(RectRef::viewport()),
        );
        let mut cells = Vec::new();
        match (&plan.content, root.source) {
            (MeasuredRootContent::Single { plot, legend }, RootSource::Plot(source)) => {
                let mut panel = LayoutNode::from_plot(
                    plot,
                    source,
                    Rect::from_panel(plot.selected.cell, height)?,
                    height,
                )?;
                if plot.result.decoration_mode == crate::spec::DecorationMode::Standard {
                    if let Some((_, guide)) = legend {
                        panel
                            .children
                            .push(guide.report_node(&plot.panel_path, height, false)?);
                    }
                }
                node.children.push(panel);
            }
            (MeasuredRootContent::Facets(plan), RootSource::Plot(_)) => {
                node.children.push(plan.report_grid(root, height)?);
            }
            (MeasuredRootContent::Canvas(plan), RootSource::Canvas(source)) => {
                let (grid, grid_cells) = source.report_grid(plan, height)?;
                node.children.push(grid);
                cells = grid_cells;
            }
            _ => {
                return Err(Error::Render(
                    "accepted layout does not match its native root".into(),
                ))
            }
        }
        node.children.extend(
            plan.frame
                .root_text
                .report_nodes(&PanelPath::root(), height)?,
        );
        Ok(Self::new(
            viewport,
            node,
            cells,
            plan.frame.root_padding,
            plan.root_paint,
        ))
    }

    /// The root's actual frozen viewport.
    pub const fn viewport(&self) -> Rect {
        self.viewport
    }

    pub(crate) const fn root_padding(&self) -> [f64; 4] {
        self.root_padding
    }

    pub(crate) const fn root_paper(&self) -> crate::Color {
        self.root_paper
    }

    /// The actual native layout tree.
    pub fn nodes(&self) -> &[LayoutNode] {
        &self.nodes
    }

    /// Declared root Canvas cells in row-major order, including holes and coverage.
    /// Empty for a standalone Plot.
    pub fn grid_cells(&self) -> &[GridCellReport] {
        &self.grid_cells
    }

    /// Actual closed drawing batches, in physical bottom-to-top paint order.
    pub fn paint_order(&self) -> &[PaintBatch] {
        &self.paint_order
    }

    /// Stable adjacent gaps in the actual closed native paint scope.
    pub fn boundaries(&self) -> &[BoundaryRef] {
        &self.boundaries
    }

    pub(crate) fn accept_paint(&mut self, mut batches: Vec<PaintBatch>) -> Result<()> {
        batches.sort_by_key(|batch| (batch.buffer, batch.range.start));
        for pair in batches.windows(2) {
            if pair[0].buffer == pair[1].buffer && pair[0].range.end > pair[1].range.start {
                return Err(Error::Render("native paint batches overlap".into()));
            }
        }
        let mut counts = std::collections::HashMap::new();
        counts.try_reserve(batches.len()).map_err(|error| {
            Error::Render(format!("paint identity reservation: {error}").into())
        })?;
        for batch in &batches {
            *counts.entry(batch.reference()).or_insert(0usize) += 1;
        }
        let unique = |batch: &PaintBatch| counts.get(batch.reference()) == Some(&1);
        let mut boundaries = Vec::new();
        crate::data::source::reserve_source(&mut boundaries, batches.len().saturating_add(1))?;
        if let Some(first) = batches.first().filter(|batch| unique(batch)) {
            boundaries.push(BoundaryRef::between(None, Some(first)));
        }
        for pair in batches.windows(2) {
            if unique(&pair[0]) && unique(&pair[1]) {
                boundaries.push(BoundaryRef::between(Some(&pair[0]), Some(&pair[1])));
            }
        }
        if let Some(last) = batches.last().filter(|batch| unique(batch)) {
            boundaries.push(BoundaryRef::between(Some(last), None));
        }
        drop(counts);
        let mut owners = std::collections::HashMap::new();
        for (index, batch) in batches.iter().enumerate() {
            let steps = batch.owner().steps();
            for depth in 0..=steps.len() {
                owners.try_reserve(1).map_err(|error| {
                    Error::Render(format!("paint owner reservation: {error}").into())
                })?;
                let indices = owners
                    .entry(PanelPath::from_steps(&steps[..depth]))
                    .or_insert_with(Vec::new);
                crate::data::source::reserve_source(indices, 1)?;
                indices.push(index);
            }
        }
        for node in std::sync::Arc::make_mut(&mut self.nodes) {
            node.accept_paint(&batches, &owners)?;
        }
        self.paint_order = batches.into();
        self.boundaries = boundaries.into();
        Ok(())
    }

    fn canonical_panel(&self, panel: &PanelPath) -> Result<PanelPath> {
        if let Some(PanelStep::Cell(row, column)) = panel.steps().first() {
            self.check_coverage(*row, *column)?;
        }
        let Some(PanelStep::Named(name)) = panel.steps().first() else {
            return Ok(panel.clone());
        };
        let cell = self
            .grid_cells
            .iter()
            .find(|cell| cell.slot.as_ref().and_then(PanelSlot::name) == Some(name))
            .ok_or_else(|| {
                crate::errors::Diagnostic::new(
                    crate::errors::DiagnosticKind::UnknownKey {
                        key: Some(crate::data::RawKey::from(name.as_str())),
                    },
                    format!("frozen Canvas has no panel named {name:?}"),
                )
            })
            .map_err(Error::Data)?;
        let mut steps = vec![PanelStep::Cell(cell.row, cell.column)];
        steps.extend_from_slice(&panel.steps()[1..]);
        Ok(PanelPath::from_steps(&steps))
    }

    fn check_coverage(&self, row: usize, column: usize) -> Result<()> {
        if let Some(cell) = self
            .grid_cells
            .iter()
            .find(|cell| cell.row == row && cell.column == column)
        {
            if cell.state == GridCellState::Covered {
                let (r, c) = cell.anchor.expect("covered cell has an anchor");
                return Err(Error::Data(
                    format!("Canvas cell ({row}, {column}) is covered by anchor ({r}, {c})").into(),
                ));
            }
        }
        Ok(())
    }

    /// Resolve a reference against this exact accepted layout. Names resolve
    /// within the frozen grid; an edited later configuration cannot affect it.
    pub fn rect(&self, reference: &RectRef) -> Result<Rect> {
        let reference = match &reference.0 {
            RefKind::Slot(row, column) => {
                self.check_coverage(*row, *column)?;
                reference.clone()
            }
            RefKind::Panel(panel) => RectRef::panel(self.canonical_panel(panel)?),
            RefKind::PlotArea(panel) => RectRef::plot_area(self.canonical_panel(panel)?),
            RefKind::Decoration(panel, role, index) => {
                RectRef::decoration(&self.canonical_panel(panel)?, *role, *index)
            }
            RefKind::Viewport => reference.clone(),
        };
        self.nodes
            .iter()
            .find_map(|node| node.find(&reference))
            .ok_or_else(|| {
                Error::Data(format!("no actual allocated rectangle for {reference:?}").into())
            })
    }
}