Skip to main content

lichtung_plot/
canvas.rs

1//! Heterogeneous plot composition on one canvas.
2
3use std::fmt::Write as _;
4use std::path::Path;
5use std::sync::Arc;
6
7use crate::Error;
8
9use crate::decorations::legend::discrete::scoped::{
10    GuideAllocation, GuideConsumption, SUPPRESSED_GUIDES,
11};
12use crate::decorations::legend::Legend;
13use crate::decorations::plan::children::MeasurementPhase;
14use crate::layout::canvas::EdgeSpaceRequirements;
15use crate::layout::fit::{FitFailure, FitOutcome, FitScope};
16use crate::layout::kernel::{FeedbackKind, FitKind};
17use crate::layout::{PixelRect, RootFramePlan};
18use crate::orchestrator::assignment::{
19    GuideTrialAssignment, ParentInsets, PlotAllocationInputs, PlotMeasureAssignmentFactory,
20    PlotMeasureDimensions, RootAssignment,
21};
22use crate::orchestrator::plan::{MeasuredOwnedPlan, MeasuredRootContent};
23use crate::orchestrator::registration::{PlotOccurrenceId, PlotRegistration};
24use crate::orchestrator::root::{
25    CanvasAnchor, CanvasHeaderRole, CanvasHeaderSource, CompositionIntrinsics, GridSlot,
26    PreparedCanvasTopology, PreparedComposition, Root, RootSource,
27};
28use crate::render::backend::{with_layer, Backend, SurfaceRole};
29use crate::scene::RenderedScene;
30use crate::spec::AxisDomain;
31use crate::spec::PlotMeasureContext;
32use crate::theme::ResolvedTheme;
33use crate::{CanvasLegendPolicy, Labels, LegendComposition, Output, Plot, PlotKind, Theme};
34
35mod dependencies;
36mod placement;
37mod plot_text;
38mod sizing;
39pub(crate) use sizing::HeightMeasurements;
40mod text_clear;
41pub(crate) mod text_panel;
42mod tracks;
43
44#[cfg(test)]
45pub(crate) mod lifecycle_tests;
46
47#[cfg(test)]
48thread_local! {
49    pub(crate) static CANVAS_SCENE_RENDER_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
50    pub(crate) static CANVAS_ASSIGNED_PANEL_EVIDENCE: std::cell::RefCell<Vec<(PixelRect, PixelRect)>> = const { std::cell::RefCell::new(Vec::new()) };
51}
52
53struct OwnedCanvasPlot {
54    anchor: crate::orchestrator::root::GridSlot,
55    plot: Arc<crate::decorations::plan::MeasuredPlotPlan>,
56    prose: crate::decorations::title_block::plan::RootTitleBlockPlan,
57    prose_layer: String,
58    legend: Option<(String, crate::decorations::legend::LegendDrawPlan)>,
59}
60
61use crate::decorations::legend::discrete::PreparedGuide;
62
63pub(crate) struct OwnedCanvasPlan {
64    grid: tracks::CanvasGridAssignment,
65    plots: Vec<OwnedCanvasPlot>,
66    text_panels: Vec<TextPanelPlan>,
67    shared_guide: Option<crate::decorations::legend::LegendDrawPlan>,
68}
69
70impl Root<'_> {
71    fn canvas_topology(&self) -> &PreparedCanvasTopology {
72        let PreparedComposition::Canvas(topology) = &self.composition else {
73            unreachable!("Canvas root topology")
74        };
75        topology
76    }
77
78    fn canvas_plot(&self, index: usize) -> Option<&PlotRegistration<'_>> {
79        plot_at(&self.plots, &self.canvas_topology().slots, index)
80    }
81
82    fn canvas_guide(&self) -> Option<&Arc<PreparedGuide>> {
83        self.canvas_topology()
84            .shared_guide
85            .as_ref()
86            .map(|slot| &slot.descriptor)
87    }
88
89    fn canvas_text(&self) -> &[Option<text_panel::TextPanelIntrinsics>] {
90        let CompositionIntrinsics::Canvas { text, .. } = &self.composition_intrinsics else {
91            unreachable!("Canvas text intrinsics")
92        };
93        text
94    }
95
96    fn canvas_prose(
97        &self,
98        id: &PlotOccurrenceId,
99    ) -> crate::decorations::title_block::plan::RootTitleBlockIntrinsics {
100        let CompositionIntrinsics::Canvas { prose, .. } = &self.composition_intrinsics else {
101            unreachable!("Canvas prose intrinsics")
102        };
103        prose
104            .iter()
105            .find(|(found, _)| found == id)
106            .expect("configured Canvas Plot text intrinsics")
107            .1
108    }
109}
110
111fn plot_at<'v, 'src>(
112    plots: &'v [crate::orchestrator::registration::PlotRegistration<'src>],
113    slots: &[Option<crate::orchestrator::root::CanvasAnchor>],
114    index: usize,
115) -> Option<&'v crate::orchestrator::registration::PlotRegistration<'src>> {
116    match slots[index].as_ref()? {
117        crate::orchestrator::root::CanvasAnchor::Plot(id) => Some(&plots[id.slot]),
118        crate::orchestrator::root::CanvasAnchor::Text => None,
119    }
120}
121
122fn resolve_appearances(
123    root: &crate::theme::Theme,
124    placements: &placement::Placements,
125    guide_layouts: &[Option<crate::TextLayout>; 3],
126) -> Result<(ResolvedTheme, Vec<Option<ResolvedTheme>>), Error> {
127    let mut root = root.resolve()?;
128    root.text_layouts.guide.clone_from(guide_layouts);
129    let plots = placements
130        .plots()
131        .map(|plot| {
132            plot.map(|plot| {
133                let mut theme = match plot.theme_spec() {
134                    None => root.clone(),
135                    Some(theme) => {
136                        let mut theme = theme.resolve()?;
137                        theme.canvas_surface_override = Some(root.surfaces.canvas_root);
138                        theme
139                    }
140                };
141                theme.text_layouts = plot.text_layouts().clone();
142                theme.apply_text_defaults(plot.kind());
143                Ok(theme)
144            })
145            .transpose()
146        })
147        .collect::<Result<Vec<_>, Error>>()?;
148    Ok((root, plots))
149}
150
151struct CanvasHeaderPlan {
152    request: crate::Text,
153    text: crate::render::backend::PlacedText,
154}
155
156/// Categorical tick-label policy for composed canvas grids.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
158pub enum CanvasCategoryLabels {
159    /// Render categorical tick labels in every panel.
160    #[default]
161    EveryPlot,
162    /// Render categorical tick labels only in the first column of each row.
163    FirstColumnPerRow,
164}
165
166#[derive(Debug, Clone)]
167struct CanvasHeader {
168    start: usize,
169    span: usize,
170    text: crate::Text,
171}
172
173struct TextPanelPlan {
174    layer: String,
175    cell: PixelRect,
176    title: crate::layout::TextBlock,
177    body: crate::layout::TextBlock,
178    title_placement: crate::render::backend::PlannedTextPlacement,
179    body_placement: crate::render::backend::PlannedTextPlacement,
180}
181
182/// Validated prose content for one composed-canvas grid cell.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct TextPanel {
185    title: crate::Text,
186    body: crate::Text,
187}
188
189impl TextPanel {
190    /// Construct a text panel, retaining verbatim title/body and mandatory breaks.
191    pub fn new(title: impl Into<crate::Text>, body: impl Into<crate::Text>) -> Result<Self, Error> {
192        let title = title.into();
193        let body = body.into();
194        title.required_source("text panel title")?;
195        body.required_source("text panel body")?;
196        Ok(Self { title, body })
197    }
198
199    /// Panel title rendered above the body.
200    #[must_use]
201    pub fn title(&self) -> &str {
202        self.title.as_str()
203    }
204
205    /// Panel body rendered with deterministic wrapping.
206    #[must_use]
207    pub fn body(&self) -> &str {
208        self.body.as_str()
209    }
210}
211
212fn canvas_header(
213    start: usize,
214    span: usize,
215    text: crate::Text,
216    limit: usize,
217    role: &str,
218) -> Result<CanvasHeader, Error> {
219    if span == 0 || start.checked_add(span).is_none_or(|end| end > limit) {
220        return Err(Error::Data(format!(
221            "canvas {role} header range {start}..{} is outside 0..{limit}",
222            start.saturating_add(span)
223        )));
224    }
225    text.required_source(&format!("canvas {role} header"))?;
226    Ok(CanvasHeader { start, span, text })
227}
228
229fn validate_header_overlap(
230    headers: &[CanvasHeader],
231    candidate: &CanvasHeader,
232    role: &str,
233) -> Result<(), Error> {
234    let end = candidate.start + candidate.span;
235    if headers.iter().any(|header| {
236        let other_end = header.start + header.span;
237        candidate.start < other_end && header.start < end
238    }) {
239        return Err(Error::Data(format!(
240            "canvas {role} headers must not overlap"
241        )));
242    }
243    Ok(())
244}
245
246/// A typed grid of independently configured charts rendered on one canvas.
247///
248/// Canvas owns one root theme, which defaults to [`Theme::publication`]. Plots
249/// without an explicit theme inherit that root. Dimensions are derived from
250/// content unless [`Self::width`], [`Self::max_width`] or [`Self::size`] replaces
251/// the sizing request. Clones share immutable placements until a placement edit
252/// separates them. Terminal exports borrow the configuration and render a fresh
253/// scene per call.
254#[derive(Clone)]
255pub struct Canvas {
256    guide_text_layouts: [Option<crate::TextLayout>; 3],
257    rows: usize,
258    columns: usize,
259    placements: Arc<placement::Placements>,
260    theme: Arc<crate::theme::Theme>,
261    legend_policy: CanvasLegendPolicy,
262    legend_composition: LegendComposition,
263    root_size: crate::layout::RootRequest,
264    title: crate::Text,
265    subtitle: crate::Text,
266    // Parent defaults apply only to embedded Plot prose, never Canvas root headings.
267    pub(crate) panel_title_alignment: Option<crate::TextAlignment>,
268    pub(crate) panel_subtitle_alignment: Option<crate::TextAlignment>,
269    caption: crate::Text,
270    labels: Option<Labels>,
271    category_labels: CanvasCategoryLabels,
272    column_headers: Vec<CanvasHeader>,
273    row_headers: Vec<CanvasHeader>,
274    row_titles: Vec<CanvasHeader>,
275    x_range_groups: Vec<Vec<usize>>,
276}
277
278fn push_text_requirement(
279    requirements: &mut Vec<crate::layout::PreparedTextRequirement>,
280    address: crate::layout::ComponentAddress,
281    role: crate::layout::PreparedTextRole,
282    local_index: u32,
283    source: &str,
284    appearance: &crate::theme::TextTheme,
285    prepared_stage: &mut crate::layout::kernel::PreparedStage<'_>,
286) -> Result<(), Error> {
287    crate::layout::PreparedTextRequirement::push_into(
288        requirements,
289        address,
290        role,
291        local_index,
292        source,
293        &[],
294        appearance,
295        Some(prepared_stage),
296    )
297    .map_err(|error| Error::Render(format!("prepared canvas text census: {error}")))
298}
299
300impl Canvas {
301    /// Replace one Canvas-owned Shared guide role's complete layout default.
302    #[must_use]
303    pub fn guide_text_layout(
304        mut self,
305        role: crate::GuideTextRole,
306        layout: crate::TextLayout,
307    ) -> Self {
308        self.guide_text_layouts[role.index()] = Some(layout);
309        self
310    }
311    /// Construct a non-empty panel grid.
312    pub fn grid(rows: usize, columns: usize) -> Result<Self, Error> {
313        if rows == 0 || columns == 0 {
314            return Err(Error::Data(
315                "canvas grid rows and columns must both be greater than zero".into(),
316            ));
317        }
318        Ok(Self {
319            rows,
320            guide_text_layouts: [None, None, None],
321            columns,
322            placements: Arc::new(placement::Placements::new(rows, columns)?),
323            theme: Arc::new(crate::theme::Theme::publication()),
324            legend_policy: CanvasLegendPolicy::PerPlot,
325            legend_composition: LegendComposition::Combined,
326            root_size: crate::layout::RootRequest::Natural,
327            title: crate::Text::UNSET,
328            subtitle: crate::Text::UNSET,
329            panel_title_alignment: None,
330            panel_subtitle_alignment: None,
331            caption: crate::Text::UNSET,
332            labels: None,
333            category_labels: CanvasCategoryLabels::EveryPlot,
334            column_headers: Vec::new(),
335            row_headers: Vec::new(),
336            row_titles: Vec::new(),
337            x_range_groups: Vec::new(),
338        })
339    }
340
341    /// Whether this cell is the top-left anchor of a placed Plot.
342    ///
343    /// Covered cells, TextPanels, empty cells and out-of-range coordinates return false.
344    #[must_use]
345    pub fn contains_plot_anchor(&self, row: usize, column: usize) -> bool {
346        if row >= self.rows || column >= self.columns {
347            return false;
348        }
349        self.placements.plot(row * self.columns + column).is_some()
350    }
351
352    /// Place one exact-family chart in an unoccupied zero-based grid cell.
353    ///
354    /// An already erased plot cannot be inserted:
355    ///
356    /// ```compile_fail
357    /// use lichtung_plot::{Canvas, NumericValues, Plot};
358    /// let erased: Plot = Plot::scatter(
359    ///     NumericValues::new("x", [1.0]),
360    ///     NumericValues::new("y", [2.0]),
361    /// ).erase();
362    /// let _ = Canvas::grid(1, 1).unwrap().panel(0, 0, erased);
363    /// ```
364    pub fn panel<K: crate::kind::ExactFamily>(
365        self,
366        row: usize,
367        column: usize,
368        plot: Plot<K>,
369    ) -> Result<Self, Error> {
370        self.panel_span(row, column, 1, 1, plot)
371    }
372
373    /// Place one Plot across a checked rectangle, including internal track gaps.
374    /// Only the top-left anchor owns preparation, prose, guides and capture.
375    /// ```
376    /// use lichtung_plot::{Canvas, NumericValues, Plot};
377    /// let plot = || Plot::scatter(NumericValues::new("x",[0.0,1.0]),NumericValues::new("y",[1.0,0.0]));
378    /// let canvas = Canvas::grid(2,2)?
379    ///     .panel(0,0,plot())?.panel(1,0,plot())?
380    ///     .panel_span(0,1,2,1,plot())?;
381    /// # let _ = canvas;
382    /// # Ok::<(), lichtung_plot::Error>(())
383    /// ```
384    pub fn panel_span<K: crate::kind::ExactFamily>(
385        mut self,
386        row: usize,
387        column: usize,
388        row_span: usize,
389        column_span: usize,
390        plot: Plot<K>,
391    ) -> Result<Self, Error> {
392        self.place_panel(row, column, row_span, column_span, plot, false)?;
393        Ok(self)
394    }
395
396    /// Place a chart in one cell, removing every intersecting placement in full.
397    /// Cells outside this new footprint are freed if their old owner intersects it.
398    /// Use [`Self::panel`] instead to reject all overlap.
399    ///
400    /// ```
401    /// use lichtung_plot::{Canvas, NumericValues, Plot};
402    /// let plot = || Plot::scatter(NumericValues::new("x", [0., 1.]), NumericValues::new("y", [1., 2.]));
403    /// let canvas = Canvas::grid(2, 3)?.panel_span(0, 0, 2, 2, plot())?
404    ///     .set_panel(1, 1, plot())?.panel(0, 0, plot())?;
405    /// # let _ = canvas;
406    /// # Ok::<(), lichtung_plot::Error>(())
407    /// ```
408    pub fn set_panel<K: crate::kind::ExactFamily>(
409        self,
410        row: usize,
411        column: usize,
412        plot: Plot<K>,
413    ) -> Result<Self, Error> {
414        self.set_panel_span(row, column, 1, 1, plot)
415    }
416
417    /// Replace an occupied region with one chart, removing whole intersecting
418    /// Plot or TextPanel owners, even when their anchors lie outside the region.
419    /// Edge-touching owners remain intact. Empty space permits ordinary insertion.
420    ///
421    /// Footprint validation and fallible placement resources precede any removal.
422    /// Grid dimensions, headers and explicit range-group requests are unchanged;
423    /// their normal preflight checks apply to the resulting topology.
424    pub fn set_panel_span<K: crate::kind::ExactFamily>(
425        mut self,
426        row: usize,
427        column: usize,
428        row_span: usize,
429        column_span: usize,
430        plot: Plot<K>,
431    ) -> Result<Self, Error> {
432        self.place_panel(row, column, row_span, column_span, plot, true)?;
433        Ok(self)
434    }
435
436    /// Place an owned exact-family Plot without consuming this Canvas on error.
437    ///
438    /// `overwrite=false` requires an entirely empty footprint; `true` removes
439    /// complete intersecting owners as documented by [`Self::set_panel_span`].
440    /// Validation/resources precede mutation. Existing Canvas clones are unchanged,
441    /// and an unshared Canvas edits its placements without copying the owner set.
442    /// Consuming placement builders delegate to this same operation.
443    pub fn place_panel<K: crate::kind::ExactFamily>(
444        &mut self,
445        row: usize,
446        column: usize,
447        row_span: usize,
448        column_span: usize,
449        plot: Plot<K>,
450        overwrite: bool,
451    ) -> Result<(), Error> {
452        let footprint = placement::Footprint {
453            row,
454            column,
455            row_span,
456            column_span,
457        };
458        let payload = placement::Payload::Plot(plot.into_description());
459        let placements = Arc::make_mut(&mut self.placements);
460        if overwrite {
461            placements.replace(footprint, payload)
462        } else {
463            placements.insert(footprint, payload)
464        }
465    }
466
467    pub(crate) fn owner_topology(&self, index: usize) -> Option<[usize; 6]> {
468        let owner = self.placements.footprint(index)?;
469        Some([
470            self.rows,
471            self.columns,
472            owner.row,
473            owner.column,
474            owner.row_span,
475            owner.column_span,
476        ])
477    }
478
479    pub(crate) fn owner_topology_at(&self, (row, column): (usize, usize)) -> Option<[usize; 6]> {
480        self.owner_topology(row * self.columns + column)
481    }
482
483    pub(crate) fn range_group_contains(&self, index: usize) -> bool {
484        self.x_range_groups
485            .iter()
486            .any(|group| group.contains(&index))
487    }
488
489    fn category_bands(&self) -> Result<Vec<Vec<usize>>, Error> {
490        let mut bands = Vec::new();
491        let mut row = 0;
492        while row < self.rows {
493            let first = self
494                .placements
495                .anchor(row, 0)
496                .filter(|&index| self.placements.plot(index).is_some())
497                .ok_or_else(|| {
498                    Error::Data("shared category band requires a first-column Plot owner".into())
499                })?;
500            let band = self.placements.footprint(first).expect("occupied anchor");
501            if band.row != row {
502                return Err(Error::Data(
503                    "shared category row intervals do not agree".into(),
504                ));
505            }
506            let mut members = Vec::new();
507            let mut column = 0;
508            while column < self.columns {
509                let index = self
510                    .placements
511                    .anchor(row, column)
512                    .filter(|&index| self.placements.plot(index).is_some())
513                    .ok_or_else(|| {
514                        Error::Data(
515                            "shared category band requires Plot peers across every column".into(),
516                        )
517                    })?;
518                let footprint = self.placements.footprint(index).expect("occupied anchor");
519                if footprint.row != band.row || footprint.row_span != band.row_span {
520                    return Err(Error::Data(
521                        "shared category owners must cover the same row interval".into(),
522                    ));
523                }
524                crate::data::source::reserve_source(&mut members, 1)?;
525                members.push(index);
526                column += footprint.column_span;
527            }
528            crate::data::source::reserve_source(&mut bands, 1)?;
529            bands.push(members);
530            row += band.row_span;
531        }
532        Ok(bands)
533    }
534
535    /// Place one validated text panel in an unoccupied zero-based grid cell.
536    pub fn text_panel(
537        mut self,
538        row: usize,
539        column: usize,
540        panel: TextPanel,
541    ) -> Result<Self, Error> {
542        self.place_text_panel(row, column, panel)?;
543        Ok(self)
544    }
545
546    /// Insert a strict single-cell TextPanel without consuming the Canvas on error.
547    /// Other configuration copies and occupied placements remain unchanged on failure.
548    pub fn place_text_panel(
549        &mut self,
550        row: usize,
551        column: usize,
552        panel: TextPanel,
553    ) -> Result<(), Error> {
554        Arc::make_mut(&mut self.placements).insert(
555            placement::Footprint::cell(row, column),
556            placement::Payload::Text(panel),
557        )
558    }
559
560    /// Set per-panel, shared, or hidden legend behavior.
561    #[must_use]
562    pub fn legend_policy(mut self, policy: CanvasLegendPolicy) -> Self {
563        self.legend_policy = policy;
564        self
565    }
566
567    /// Replace the semantic composition of a Shared discrete guide.
568    ///
569    /// Combined is the default. Under Shared this selection owns every
570    /// contribution; stored child selections remain unchanged. PerPlot, Hidden
571    /// and all-continuous guides leave this value inactive. Theme, placement and
572    /// legend-policy call order are independent.
573    /// ```
574    /// use lichtung_plot::{Canvas, CanvasLegendPolicy, LegendComposition};
575    /// let canvas = Canvas::grid(1, 2)?
576    ///     .legend_composition(LegendComposition::Separate)
577    ///     .legend_policy(CanvasLegendPolicy::Shared);
578    /// # let _ = canvas;
579    /// # Ok::<(), lichtung_plot::Error>(())
580    /// ```
581    #[must_use]
582    pub const fn legend_composition(mut self, composition: LegendComposition) -> Self {
583        self.legend_composition = composition;
584        self
585    }
586
587    /// Set the title alignment default for embedded Plots, independently of Canvas prose.
588    ///
589    /// An explicit Plot title instruction wins; otherwise this wins over that
590    /// Plot's theme default. Start and End mean the physical left and right edges
591    /// of each Plot's inset content span. Headers and TextPanel text are unaffected.
592    /// ```
593    /// use lichtung_plot::{Canvas, NumericValues, Plot, Theme, TextAlignment};
594    /// let canvas = Canvas::grid(1, 1)?
595    ///     .panel_title_alignment(TextAlignment::Start)
596    ///     .panel_subtitle_alignment(TextAlignment::End)
597    ///     .theme(Theme::nature())
598    ///     .panel(0, 0, Plot::scatter(
599    ///         NumericValues::new("x", [1.0, 2.0]),
600    ///         NumericValues::new("y", [2.0, 1.0]),
601    ///     ).title("Panel title").subtitle("Panel subtitle"))?;
602    /// # let _ = canvas;
603    /// # Ok::<(), lichtung_plot::Error>(())
604    /// ```
605    #[must_use]
606    pub const fn panel_title_alignment(mut self, alignment: crate::TextAlignment) -> Self {
607        self.panel_title_alignment = Some(alignment);
608        self
609    }
610
611    /// Set the subtitle alignment default for embedded Plots only.
612    ///
613    /// An explicit Plot subtitle instruction wins; otherwise this wins over the
614    /// optional Plot-theme subtitle default and final effective title alignment.
615    /// Theme and alignment attachment order is independent. Canvas-owned prose
616    /// and captions use their own Text instructions over their complete theme roles.
617    #[must_use]
618    pub const fn panel_subtitle_alignment(mut self, alignment: crate::TextAlignment) -> Self {
619        self.panel_subtitle_alignment = Some(alignment);
620        self
621    }
622
623    /// Add one measured header spanning contiguous canvas columns.
624    /// Text can replace the complete Canvas header style and align its lines;
625    /// the block remains centered over the declared span.
626    pub fn column_header(
627        mut self,
628        start_column: usize,
629        span: usize,
630        text: impl Into<crate::Text>,
631    ) -> Result<Self, Error> {
632        let header = canvas_header(start_column, span, text.into(), self.columns, "column")?;
633        validate_header_overlap(&self.column_headers, &header, "column")?;
634        self.column_headers.push(header);
635        Ok(self)
636    }
637
638    /// Add one measured header spanning contiguous canvas rows.
639    /// Local Text style owns its font-relative padding. Line alignment defaults
640    /// to Center inside the block positioned beside the declared rows.
641    pub fn row_header(
642        mut self,
643        start_row: usize,
644        span: usize,
645        text: impl Into<crate::Text>,
646    ) -> Result<Self, Error> {
647        let header = canvas_header(start_row, span, text.into(), self.rows, "row")?;
648        validate_header_overlap(&self.row_headers, &header, "row")?;
649        self.row_headers.push(header);
650        Ok(self)
651    }
652
653    /// Add one measured title centered above every panel in one canvas row.
654    /// Text retains an independent complete style and line alignment, defaulting
655    /// to the Canvas header role and Center.
656    pub fn row_title(mut self, row: usize, text: impl Into<crate::Text>) -> Result<Self, Error> {
657        let title = canvas_header(row, 1, text.into(), self.rows, "row title")?;
658        validate_header_overlap(&self.row_titles, &title, "row title")?;
659        self.row_titles.push(title);
660        Ok(self)
661    }
662
663    /// Configure duplicate categorical-label handling across the grid.
664    #[must_use]
665    pub const fn category_labels(mut self, policy: CanvasCategoryLabels) -> Self {
666        self.category_labels = policy;
667        self
668    }
669
670    /// Couple the automatic continuous horizontal range of explicit panel cells.
671    ///
672    /// Grouped cells must contain configured plots without explicit x limits or
673    /// categorical x domains.
674    pub fn x_range_group(
675        mut self,
676        cells: impl IntoIterator<Item = (usize, usize)>,
677    ) -> Result<Self, Error> {
678        let mut indices = Vec::new();
679        for (row, column) in cells {
680            if row >= self.rows || column >= self.columns {
681                return Err(Error::Data(format!(
682                    "canvas x-range group cell ({row}, {column}) is outside {}x{} grid",
683                    self.rows, self.columns
684                )));
685            }
686            let index = row * self.columns + column;
687            if indices.contains(&index)
688                || self
689                    .x_range_groups
690                    .iter()
691                    .any(|group| group.contains(&index))
692            {
693                return Err(Error::Data(format!(
694                    "canvas x-range group repeats panel ({row}, {column})"
695                )));
696            }
697            indices.push(index);
698        }
699        if indices.is_empty() {
700            return Err(Error::Data(
701                "canvas x-range group must contain at least one panel".into(),
702            ));
703        }
704        self.x_range_groups.push(indices);
705        Ok(self)
706    }
707
708    /// Allocate exactly this width in CSS pixels and derive height from content.
709    ///
710    /// This replaces the complete request, clearing any height set by
711    /// [`Self::size`]. Without a sizing call, both dimensions derive from content.
712    /// Zero is rejected during preflight, without a setter panic.
713    #[must_use]
714    pub const fn width(mut self, width: u32) -> Self {
715        self.root_size = crate::layout::RootRequest::ExactWidth(width);
716        self
717    }
718
719    /// Cap the natural complete Canvas width; height remains content-driven.
720    ///
721    /// This replaces any prior sizing request, retains declared topology and
722    /// never fills a cap wider than natural content. Embedded Plot sizing requests
723    /// remain ignored. Zero rejects during owning-root preflight.
724    #[must_use]
725    pub const fn max_width(mut self, maximum: u32) -> Self {
726        self.root_size = crate::layout::RootRequest::MaxWidth(maximum);
727        self
728    }
729
730    /// Allocate exactly this width and height in CSS pixels.
731    ///
732    /// This replaces the complete sizing request. All content must fit without
733    /// changing either dimension; zero dimensions reject during preflight.
734    /// Embedded Plots do not contribute standalone sizing requests.
735    #[must_use]
736    pub const fn size(mut self, width: u32, height: u32) -> Self {
737        self.root_size = crate::layout::RootRequest::ExactSize { width, height };
738        self
739    }
740
741    /// Set one canvas-level title.
742    ///
743    /// A plain string replaces content while retaining earlier local style and
744    /// layout. Present Text instructions replace the complete style or layout;
745    /// an explicit default layout restores owner defaults.
746    #[must_use]
747    pub fn title(mut self, title: impl Into<crate::Text>) -> Self {
748        self.title
749            .replace_from(title.into())
750            .expect("public Text always has a source");
751        self
752    }
753
754    /// Set one canvas-level subtitle.
755    /// Content and instruction replacement follow [`Self::title`].
756    #[must_use]
757    pub fn subtitle(mut self, subtitle: impl Into<crate::Text>) -> Self {
758        self.subtitle
759            .replace_from(subtitle.into())
760            .expect("public Text always has a source");
761        self
762    }
763
764    /// Set one canvas-level caption.
765    /// Content and instruction replacement follow [`Self::title`].
766    #[must_use]
767    pub fn caption(mut self, caption: impl Into<crate::Text>) -> Self {
768        self.caption
769            .replace_from(caption.into())
770            .expect("public Text always has a source");
771        self
772    }
773
774    fn prose(&self) -> [Option<&crate::Text>; 3] {
775        [&self.title, &self.subtitle, &self.caption].map(crate::Text::provided)
776    }
777
778    fn prose_alignments(&self) -> [Option<crate::TextAlignment>; 3] {
779        [&self.title, &self.subtitle, &self.caption].map(crate::Text::alignment_request)
780    }
781
782    /// Apply one reusable automatic-label policy to every configured panel.
783    #[must_use]
784    pub fn labels(mut self, labels: Labels) -> Self {
785        self.labels = Some(labels);
786        self
787    }
788
789    /// Set the Canvas root theme.
790    ///
791    /// Plots without an explicit theme inherit this theme. A theme selected with
792    /// [`Plot::theme`] completely replaces it for that Plot. If this method is
793    /// omitted, the Canvas root uses [`Theme::publication`].
794    #[must_use]
795    ///
796    /// Shared legend spacing is configured only in the complete theme:
797    /// ```compile_fail
798    /// let _ = lichtung_plot::Canvas::grid(1, 1).unwrap().shared_legend_gap(8.0);
799    /// ```
800    pub fn theme(mut self, theme: Theme) -> Self {
801        self.theme = Arc::new(theme);
802        self
803    }
804
805    fn render_preflighted(
806        root: &crate::layout::FrozenRoot<crate::orchestrator::TextReplayPlan>,
807        backend: &mut dyn Backend,
808    ) -> Result<(), Error> {
809        let (width, height) = root.dimensions();
810        root.plan()
811            .replay(width, height, backend, "prepared canvas scene replay")
812    }
813
814    /// Validate the complete composed canvas without opening a backend or creating files.
815    ///
816    /// This checks canvas and grid layout, every chart's plot-specific data and
817    /// representability preflight, channel and interval contracts, shared legend
818    /// compatibility, and nested self-managed plot restrictions.
819    pub fn preflight(&self) -> Result<(), Error> {
820        self.preflight_plan().map(drop)
821    }
822
823    /// Render one immutable canonical composed SVG scene without creating a file.
824    ///
825    /// # Errors
826    ///
827    /// Returns an error when canvas preflight or SVG rendering fails.
828    fn render_scene(&self) -> Result<RenderedScene, Error> {
829        #[cfg(test)]
830        CANVAS_SCENE_RENDER_CALLS.with(|calls| calls.set(calls.get() + 1));
831        let preflight = self.preflight_plan()?;
832        let (width, height) = preflight.dimensions();
833        let mut backend = preflight.plan().take_svg_backend()?;
834        Self::render_preflighted(&preflight, &mut backend)?;
835        RenderedScene::new(width, height, backend.into_output())
836    }
837
838    /// Render once, publish an outlined SVG, and return a reusable output.
839    /// The output filename is completed with `.svg` after conversion.
840    pub fn svg(&self, path: impl AsRef<Path>) -> Result<Output, Error> {
841        let output = Output::new(self.render_scene()?);
842        output.svg(path)
843    }
844
845    /// Render once, publish SVG with selectable text, and return a reusable output.
846    /// The output filename is completed with `.svg` after rendering.
847    pub fn svg_preserve_text(&self, path: impl AsRef<Path>) -> Result<Output, Error> {
848        let output = Output::new(self.render_scene()?);
849        output.svg_preserve_text(path)
850    }
851
852    /// Render once, publish a balanced 300-DPI PNG, and return a reusable output.
853    /// The output filename is completed with `.png` after rasterization.
854    pub fn png(&self, path: impl AsRef<Path>) -> Result<Output, Error> {
855        let output = Output::new(self.render_scene()?);
856        output.png(path)
857    }
858
859    /// Render once, publish a balanced source-sized PNG without density metadata.
860    /// The output filename is completed with `.png` after rasterization.
861    pub fn png_preview(&self, path: impl AsRef<Path>) -> Result<Output, Error> {
862        let output = Output::new(self.render_scene()?);
863        output.png_preview(path)
864    }
865
866    /// Render once and publish a PNG using the exact caller-provided options.
867    /// The output filename is completed with `.png` after rasterization.
868    pub fn png_with_options(
869        &self,
870        path: impl AsRef<Path>,
871        options: crate::PngOptions,
872    ) -> Result<Output, Error> {
873        let output = Output::new(self.render_scene()?);
874        output.png_with_options(path, options)
875    }
876
877    fn validate_structure(&self) -> Result<Vec<Vec<usize>>, Error> {
878        let bands = if self.category_labels == CanvasCategoryLabels::FirstColumnPerRow {
879            self.category_bands()?
880        } else {
881            Vec::new()
882        };
883        for source in [
884            self.title.provided().map(crate::Text::as_str),
885            self.subtitle.provided().map(crate::Text::as_str),
886            self.caption.provided().map(crate::Text::as_str),
887        ]
888        .into_iter()
889        .flatten()
890        {
891            crate::text::validate_for(source, "canvas prose")?;
892        }
893        if self.placements.plots().all(|plot| plot.is_none())
894            && self.placements.texts().all(|text| text.is_none())
895        {
896            return Err(Error::Data(
897                "canvas requires at least one configured panel".into(),
898            ));
899        }
900        for plot in self.placements.plots().flatten() {
901            let kind = plot.kind();
902            plot.validate_configuration(kind)?;
903            crate::layout::interior::CompositionChildPolicy::Canvas.validate_child(plot)?;
904            if self.legend_policy == CanvasLegendPolicy::Shared
905                && matches!(
906                    plot.legend_policy_spec(),
907                    crate::LegendPolicy::Visible(position) if position != crate::LegendPosition::Auto
908                )
909            {
910                return Err(Error::Data(
911                    "Canvas shared legend cannot honor explicit per-Plot placement".into(),
912                ));
913            }
914        }
915        for group in &self.x_range_groups {
916            for &index in group {
917                let plot = self.placements.plot(index).ok_or_else(|| {
918                    Error::Data(format!(
919                        "canvas x-range group references unconfigured panel {index}"
920                    ))
921                })?;
922                if plot.x_axis_spec().window.is_some() {
923                    return Err(Error::Data(format!(
924                        "canvas x-range group panel {index} has explicit x limits"
925                    )));
926                }
927                if plot
928                    .automatic_axis_category_values(plot.kind(), true)
929                    .is_some()
930                {
931                    return Err(Error::Data(format!(
932                        "canvas x-range group panel {index} has a categorical x axis"
933                    )));
934                }
935            }
936        }
937        for title in &self.row_titles {
938            for (index, plot) in self.placements.plots().enumerate() {
939                let Some(plot) = plot else {
940                    continue;
941                };
942                let footprint = self.placements.footprint(index).expect("Plot owner");
943                let end = footprint.row + footprint.row_span;
944                if footprint.row < title.start && title.start < end {
945                    return Err(Error::Data(
946                        "Canvas row title would cut through a Plot footprint".into(),
947                    ));
948                }
949                if footprint.row == title.start
950                    && (plot.title_text().is_some() || plot.subtitle_text().is_some())
951                {
952                    return Err(Error::Data(format!(
953                        "canvas row title cannot coexist with a panel title or subtitle in row {}",
954                        title.start
955                    )));
956                }
957            }
958        }
959        Ok(bands)
960    }
961
962    fn prepare_continuous_shared_guide(
963        &self,
964        registry: &crate::orchestrator::registration::PlotRegistryBuilder<'_>,
965        slots: &[Option<crate::orchestrator::root::CanvasAnchor>],
966        operation: &crate::font::canonical::OperationContext,
967    ) -> Result<Option<crate::decorations::legend::descriptor::ContinuousDescriptor>, Error> {
968        if self.legend_policy != CanvasLegendPolicy::Shared {
969            return Ok(None);
970        }
971        let Some(_) = self.placements.plots().flatten().next() else {
972            return Ok(None);
973        };
974
975        let mut contributors = Vec::new();
976        crate::data::source::reserve_source(&mut contributors, self.placements.len())?;
977        for (index, plot) in self.placements.plots().enumerate() {
978            let Some(plot) = plot else { continue };
979            if !matches!(plot.kind(), PlotKind::Heatmap | PlotKind::Beeswarm) {
980                continue;
981            }
982            let Some(crate::orchestrator::root::CanvasAnchor::Plot(id)) = &slots[index] else {
983                return Err(Error::Render(
984                    "shared continuous guide has no prepared interior".into(),
985                ));
986            };
987            let registered = &registry.panels[id.slot];
988            let contributor =
989                crate::decorations::legend::descriptor::ContinuousContributor::for_plot(
990                    registered,
991                    registered.scope.axis_numeric_binding(
992                        registered.source,
993                        &registered.row_source,
994                        operation,
995                    )?,
996                )?
997                .ok_or_else(|| {
998                    Error::Render("shared continuous guide has no color identity".into())
999                })?;
1000            contributors.push(contributor);
1001        }
1002        crate::decorations::legend::descriptor::merge_continuous(
1003            &operation.root_identity(),
1004            operation,
1005            contributors,
1006        )
1007    }
1008
1009    fn install_shared_continuous_domain(
1010        &self,
1011        registry: &mut crate::orchestrator::registration::PlotRegistryBuilder<'_>,
1012        slots: &[Option<crate::orchestrator::root::CanvasAnchor>],
1013        descriptor: &crate::decorations::legend::descriptor::ContinuousDescriptor,
1014    ) -> Result<(), Error> {
1015        for (index, plot) in self.placements.plots().enumerate() {
1016            let Some(plot) = plot else { continue };
1017            let Some(crate::orchestrator::root::CanvasAnchor::Plot(id)) = &slots[index] else {
1018                continue;
1019            };
1020            let registered = &mut registry.panels[id.slot];
1021            match plot.kind() {
1022                PlotKind::Heatmap => {
1023                    if let Some(crate::orchestrator::registration::PreparedFamily::Heatmap(marks)) =
1024                        &mut registered.family
1025                    {
1026                        marks.install_shared_domain(descriptor)?;
1027                    }
1028                }
1029                PlotKind::Beeswarm => {
1030                    if let Some(crate::orchestrator::registration::PreparedFamily::Beeswarm(
1031                        marks,
1032                    )) = &mut registered.family
1033                    {
1034                        marks.install_shared_domain(descriptor)?;
1035                    }
1036                }
1037                _ => {}
1038            }
1039        }
1040        Ok(())
1041    }
1042
1043    /// Coordinate scientific categorical color identities before fonts,
1044    /// independently of guide visibility and section contribution.
1045    fn prepare_color_domains(
1046        &self,
1047        registry: &crate::orchestrator::registration::PlotRegistryBuilder<'_>,
1048        slots: &[Option<crate::orchestrator::root::CanvasAnchor>],
1049    ) -> Result<Vec<(String, Arc<crate::data::category::CategoryDomain>)>, Error> {
1050        if self.legend_policy != CanvasLegendPolicy::Shared {
1051            return Ok(Vec::new());
1052        }
1053        let mut groups = Vec::new();
1054        crate::data::source::reserve_source(&mut groups, self.placements.len())?;
1055        for (index, plot) in self.placements.plots().enumerate() {
1056            let Some(plot) = plot else { continue };
1057            let Some(dimension) = plot.categorical_color_field() else {
1058                continue;
1059            };
1060
1061            let Some(crate::orchestrator::root::CanvasAnchor::Plot(id)) = &slots[index] else {
1062                return Err(Error::Render(
1063                    "Canvas color domain is missing prepared semantics".into(),
1064                ));
1065            };
1066            let group_index =
1067                crate::data::source::source_position(&groups, |(field, _)| field == dimension);
1068            let levels = if let Some(group_index) = group_index {
1069                &mut groups[group_index].1
1070            } else {
1071                groups.push((
1072                    crate::data::source::copy_source_string(dimension)?,
1073                    Vec::new(),
1074                ));
1075                &mut groups.last_mut().expect("new guide field").1
1076            };
1077            for level in crate::layout::interior::guide::observed_color_levels(
1078                plot,
1079                std::slice::from_ref(&registry.panels[id.slot]),
1080            )? {
1081                if crate::data::source::source_position(levels, |existing| existing == &level)
1082                    .is_none()
1083                {
1084                    crate::data::source::reserve_source(levels, 1)?;
1085                    levels.push(level);
1086                }
1087            }
1088        }
1089        crate::data::source::collect_source(groups.into_iter().map(|(field, values)| {
1090            let domain = crate::data::category::CategoryDomain::from_values(
1091                Some(&crate::data::category::RawField::new(&field)?),
1092                values,
1093            )?;
1094            Ok((field, crate::data::source::source_arc(domain)?))
1095        }))
1096    }
1097
1098    /// Prepare every local contribution or explicit absence, then retain the
1099    /// one Shared union when selected. No body or font work determines presence.
1100    fn prepare_discrete_guides(
1101        &self,
1102        registry: &mut crate::orchestrator::registration::PlotRegistryBuilder<'_>,
1103        slots: &[Option<crate::orchestrator::root::CanvasAnchor>],
1104        hue_groups: &[(String, Arc<crate::data::category::CategoryDomain>)],
1105        resources: &crate::font::canonical::OperationContext,
1106    ) -> Result<Option<Arc<PreparedGuide>>, Error> {
1107        let mut contributions = Vec::new();
1108        crate::data::source::reserve_source(&mut contributions, self.placements.len())?;
1109        for (index, plot) in self.placements.plots().enumerate() {
1110            let Some(source) = plot else {
1111                continue;
1112            };
1113            let Some(crate::orchestrator::root::CanvasAnchor::Plot(id)) = &slots[index] else {
1114                return Err(Error::Render(
1115                    "Canvas point/path guide is missing prepared semantics".into(),
1116                ));
1117            };
1118            let registered = &mut registry.panels[id.slot];
1119            if let Some((_, domain)) = hue_groups
1120                .iter()
1121                .find(|(field, _)| Some(field.as_str()) == source.categorical_color_field())
1122            {
1123                registered.set_parent_colors(Arc::clone(domain));
1124            }
1125            let root_guide = crate::layout::interior::guide::prepare_discrete_guides(
1126                source,
1127                std::slice::from_mut(registered),
1128                resources,
1129                false,
1130            )?;
1131            if self.legend_policy == CanvasLegendPolicy::Shared {
1132                if let Some(descriptor) = &root_guide {
1133                    contributions.push(Arc::clone(descriptor));
1134                }
1135            }
1136        }
1137        PreparedGuide::merge(&contributions, &[], "shared canvas legend")
1138    }
1139
1140    fn prepare_shared_x(
1141        &self,
1142        stage: &mut crate::layout::kernel::PreparedStage<'_>,
1143        registry: &mut crate::orchestrator::registration::PlotRegistryBuilder<'_>,
1144        composition: &PreparedComposition,
1145    ) -> Result<Vec<Option<(f64, f64)>>, Error> {
1146        let mut ranges = Vec::new();
1147        if self.x_range_groups.is_empty() {
1148            return Ok(ranges);
1149        }
1150
1151        stage.reserve_prepared(&mut ranges, self.placements.len(), "shared x domains")?;
1152        ranges.resize(self.placements.len(), None);
1153        crate::plots::shared_x::complete_shared_bases(&mut registry.panels, composition)?;
1154        let PreparedComposition::Canvas(topology) = composition else {
1155            unreachable!("Canvas shared bases")
1156        };
1157        for group in &topology.range_groups {
1158            for id in group {
1159                let panel = &registry.panels[id.slot];
1160                let index = usize::try_from(panel.scope.address.leaf_slot_index())
1161                    .expect("Canvas slot fits usize");
1162                // Some families complete y later. Only x exists at this point.
1163                ranges[index] = Some(
1164                    panel.axes.as_ref().expect("shared x axes").sources()[0]
1165                        .base_seed
1166                        .expect("shared x seed")
1167                        .pair(),
1168                );
1169            }
1170        }
1171        Ok(ranges)
1172    }
1173
1174    #[expect(
1175        clippy::too_many_lines,
1176        reason = "root component inputs and their coordinated x domains are prepared together before fonts"
1177    )]
1178    fn prepare_interiors(
1179        &self,
1180        stage: &mut crate::layout::kernel::PreparedStage<'_>,
1181        appearances: Vec<Option<ResolvedTheme>>,
1182    ) -> Result<
1183        (
1184            crate::orchestrator::registration::PlotRegistryBuilder<'_>,
1185            PreparedCanvasTopology,
1186        ),
1187        Error,
1188    > {
1189        let resources = stage.operation();
1190        let mut registry =
1191            crate::orchestrator::registration::PlotRegistryBuilder::new(resources.root_identity());
1192        stage.reserve_prepared(
1193            &mut registry.panels,
1194            self.placements.len(),
1195            "Canvas interior inputs",
1196        )?;
1197        let mut slots = Vec::new();
1198        stage.reserve_prepared(&mut slots, self.placements.len(), "Canvas plot occurrences")?;
1199        for (index, (plot, appearance)) in self.placements.plots().zip(appearances).enumerate() {
1200            let Some(source) = plot else {
1201                slots.push(
1202                    self.placements
1203                        .text(index)
1204                        .map(|_| crate::orchestrator::root::CanvasAnchor::Text),
1205                );
1206                continue;
1207            };
1208            let plot = plot.expect("configured Canvas source");
1209            let mut scope = crate::orchestrator::registration::Scope::new(
1210                plot,
1211                &resources,
1212                index,
1213                crate::layout::ComponentAddress::root().child(
1214                    crate::layout::AddressRole::CanvasCell,
1215                    u32::try_from(index)
1216                        .map_err(|_| Error::Render("canvas address overflowed".into()))?,
1217                )?,
1218                crate::orchestrator::registration::RowSelection::Full,
1219                None,
1220                None,
1221            )?;
1222            scope.numeric_owner.canvas = Some((index / self.columns, index % self.columns));
1223            scope.axis_numeric_owner.canvas = scope.numeric_owner.canvas;
1224            if plot.kind() == PlotKind::Matrix {
1225                slots.push(None);
1226                continue;
1227            }
1228            let policy =
1229                crate::orchestrator::registration::PlotScopePolicy::for_source(source, None);
1230            let id = registry.reserve(
1231                source,
1232                scope.address,
1233                scope.numeric_owner,
1234                scope.axis_numeric_owner,
1235                scope.rows,
1236                scope.render_name,
1237                policy,
1238                appearance.expect("configured Canvas panel has a resolved theme"),
1239                &resources,
1240            )?;
1241            let panel = &mut registry.panels[id.slot];
1242            if let Some(labels) = &self.labels {
1243                panel.policy.labels.clone_from(labels);
1244            }
1245            let guide_use = match self.legend_policy {
1246                CanvasLegendPolicy::Hidden => {
1247                    crate::decorations::legend::discrete::scoped::GuideUse::Hidden
1248                }
1249                CanvasLegendPolicy::Shared
1250                    if plot.legend_policy_spec() != crate::LegendPolicy::Hidden =>
1251                {
1252                    crate::decorations::legend::discrete::scoped::GuideUse::SharedSuppressed
1253                }
1254                CanvasLegendPolicy::PerPlot | CanvasLegendPolicy::Shared => {
1255                    panel.policy.discrete_guide_use
1256                }
1257            };
1258            panel.policy.discrete_guide_use = guide_use;
1259            panel.policy.continuous_guide_use = guide_use;
1260            panel.policy.gutter_owner = crate::orchestrator::registration::GutterOwner::Composition;
1261            panel.policy.axis_text.tick_labels[1] = self.category_labels
1262                != CanvasCategoryLabels::FirstColumnPerRow
1263                || index.is_multiple_of(self.columns);
1264            if self.legend_policy == CanvasLegendPolicy::Shared {
1265                panel.policy.guide_composition = self.legend_composition;
1266            }
1267            panel.policy.continuous_materialization = match self.legend_policy {
1268                CanvasLegendPolicy::Hidden => {
1269                    crate::orchestrator::registration::ContinuousMaterialization::Suppressed
1270                }
1271                CanvasLegendPolicy::Shared
1272                    if matches!(plot.kind(), PlotKind::Heatmap | PlotKind::Beeswarm) =>
1273                {
1274                    crate::orchestrator::registration::ContinuousMaterialization::SharedFinal
1275                }
1276                CanvasLegendPolicy::PerPlot | CanvasLegendPolicy::Shared => {
1277                    crate::orchestrator::registration::ContinuousMaterialization::Local
1278                }
1279            };
1280            let family = match plot.kind() {
1281                PlotKind::Line | PlotKind::Trajectory | PlotKind::LinePath => {
1282                    plot.configured_source_rows()?;
1283                    let (marks, ranges, conditions, hues) = crate::plots::line::PreparedLine::new(
1284                        plot,
1285                        panel.data(&resources)?,
1286                        None,
1287                        panel
1288                            .parent_orders
1289                            .collectives
1290                            .as_deref()
1291                            .map(Vec::as_slice),
1292                    )?;
1293                    panel
1294                        .categorical
1295                        .as_mut()
1296                        .expect("prepared color binding")
1297                        .set_local_keys(hues)?;
1298                    panel.axes = Some(crate::plots::shared_x::prepare_pair_axes(
1299                        panel,
1300                        ranges.map(Some),
1301                        [conditions, None],
1302                    )?);
1303                    crate::orchestrator::registration::PreparedFamily::Line {
1304                        kind: plot.kind(),
1305                        marks,
1306                    }
1307                }
1308                PlotKind::Scatter => {
1309                    plot.configured_source_rows()?;
1310                    let (marks, ranges) =
1311                        crate::plots::scatter::PreparedScatter::new(plot, panel.data(&resources)?)?;
1312                    panel.axes = Some(crate::plots::shared_x::prepare_pair_axes(
1313                        panel,
1314                        ranges.map(Some),
1315                        [None, None],
1316                    )?);
1317                    crate::orchestrator::registration::PreparedFamily::Scatter(marks)
1318                }
1319                _ => {
1320                    plot.configured_source_rows()?;
1321                    crate::plots::shared_x::prepare_plot_registration(panel, &resources)?;
1322                    panel.family.take().expect("prepared reference family")
1323                }
1324            };
1325            panel.family = Some(family);
1326            slots.push(Some(crate::orchestrator::root::CanvasAnchor::Plot(id)));
1327        }
1328        let producers = crate::data::source::collect_source(
1329            slots
1330                .iter()
1331                .enumerate()
1332                .filter(|(_, anchor)| anchor.is_some())
1333                .map(|(index, _)| Ok(GridSlot(index))),
1334        )?;
1335        let range_groups =
1336            crate::data::source::collect_source(self.x_range_groups.iter().map(|group| {
1337                crate::data::source::collect_source(group.iter().map(|&index| {
1338                    let Some(CanvasAnchor::Plot(id)) = &slots[index] else {
1339                        unreachable!("validated Canvas range group")
1340                    };
1341                    Ok(id.clone())
1342                }))
1343            }))?;
1344        let composition = PreparedComposition::Canvas(PreparedCanvasTopology {
1345            slots,
1346            producers,
1347            range_groups,
1348            headers: Vec::new(),
1349            category_bands: Vec::new(),
1350            shared_guide: None,
1351        });
1352        let shared_x = self.prepare_shared_x(stage, &mut registry, &composition)?;
1353        let PreparedComposition::Canvas(topology) = composition else {
1354            unreachable!("Canvas composition")
1355        };
1356        let slots = &topology.slots;
1357        for (index, plot) in self.placements.plots().enumerate() {
1358            let Some(crate::orchestrator::root::CanvasAnchor::Plot(id)) = &slots[index] else {
1359                continue;
1360            };
1361            let plot = plot.expect("Canvas producer source");
1362            let panel = &mut registry.panels[id.slot];
1363            if let Some(
1364                crate::orchestrator::registration::PreparedFamily::Scatter(_)
1365                | crate::orchestrator::registration::PreparedFamily::Line { .. },
1366            ) = &panel.family
1367            {
1368                let mut scope = String::new();
1369                crate::data::source::reserve_source_string(&mut scope, 32)?;
1370                write!(scope, "panel-{index}").expect("admitted scope");
1371                panel
1372                    .scope
1373                    .set_render_name(crate::data::source::copy_source_string(&scope)?)?;
1374                let shared_x_window = shared_x.get(index).copied().flatten();
1375                if plot.kind() == PlotKind::Scatter {
1376                    crate::plots::shared_x::prepare_scatter_plot(plot, panel, shared_x_window)?;
1377                } else {
1378                    crate::plots::shared_x::prepare_line_plot(plot, panel, shared_x_window)?;
1379                }
1380            } else {
1381                let scope_bytes = 6 + index
1382                    .checked_ilog10()
1383                    .map_or(1, |digits| digits as usize + 1);
1384                let mut scope = String::new();
1385                crate::data::source::reserve_source_string(&mut scope, scope_bytes)?;
1386                std::fmt::Write::write_fmt(&mut scope, format_args!("panel-{index}"))
1387                    .map_err(|error| Error::Render(format!("Canvas scope: {error}")))?;
1388                panel.scope.set_render_name(scope)?;
1389                crate::plots::shared_x::prepare_reference_plot(
1390                    plot,
1391                    panel,
1392                    shared_x.get(index).copied().flatten(),
1393                    self.labels.is_some(),
1394                    &resources,
1395                )?;
1396            }
1397        }
1398        for group in &self.x_range_groups {
1399            if !group.iter().any(|&index| {
1400                self.placements
1401                    .plot(index)
1402                    .is_some_and(|plot| plot.x_axis_spec().window.is_none())
1403            }) {
1404                continue;
1405            }
1406            for &index in group {
1407                let Some(crate::orchestrator::root::CanvasAnchor::Plot(id)) = &slots[index] else {
1408                    continue;
1409                };
1410                let registered = &mut registry.panels[id.slot];
1411                if let Some(crate::orchestrator::registration::PreparedFamily::Waterfall(marks)) =
1412                    &mut registered.family
1413                {
1414                    let numeric = registered.scope.numeric_binding(
1415                        registered.source,
1416                        &registered.row_source,
1417                        &resources,
1418                    )?;
1419                    let axes = registered.axes.as_ref().ok_or_else(|| {
1420                        Error::Render("Waterfall total window scope missing".into())
1421                    })?;
1422                    let source = registered.source;
1423                    marks.prepare_totals(
1424                        crate::plots::waterfall::WaterfallTotalsPrepare {
1425                            numeric,
1426                            axes: [axes.axis(source, 0), axes.axis(source, 1)],
1427                            format: source.total_format_spec(),
1428                        },
1429                        true,
1430                    )?;
1431                }
1432            }
1433        }
1434        Ok((registry, topology))
1435    }
1436
1437    fn preflight_plan(
1438        &self,
1439    ) -> Result<crate::layout::FrozenRoot<crate::orchestrator::TextReplayPlan>, Error> {
1440        crate::orchestrator::plan_scene(RootSource::Canvas(self))
1441    }
1442
1443    pub(crate) const fn sizing_request(&self) -> crate::layout::RootRequest {
1444        self.root_size
1445    }
1446
1447    #[expect(
1448        clippy::too_many_lines,
1449        reason = "one ordered semantic, font, intrinsic, allocation, and capture lifecycle"
1450    )]
1451    pub(crate) fn prepare_root<'src>(
1452        &'src self,
1453        stage: &mut crate::layout::kernel::PreparedStage<'_>,
1454    ) -> Result<Root<'src>, Error> {
1455        let (root_appearance, appearances) =
1456            resolve_appearances(&self.theme, &self.placements, &self.guide_text_layouts)?;
1457        let text = crate::text::TextService::default();
1458        let request = crate::text::TextRequestContext::new(&root_appearance, &text);
1459        let bands = self.validate_structure()?;
1460        let (mut registry, mut topology) = self.prepare_interiors(stage, appearances)?;
1461        let slots = &topology.slots;
1462        let color_domains = self.prepare_color_domains(&registry, slots)?;
1463        for (index, plot) in self.placements.plots().enumerate() {
1464            if let (Some(plot), Some(CanvasAnchor::Plot(id))) = (plot, slots[index].as_ref()) {
1465                let panel = &registry.panels[id.slot];
1466                let global_hues = color_domains
1467                    .iter()
1468                    .find(|(field, _)| Some(field.as_str()) == plot.categorical_color_field())
1469                    .map(|(_, domain)| domain.as_ref());
1470                crate::layout::interior::guide::validate_categorical_scale(
1471                    plot,
1472                    std::slice::from_ref(panel),
1473                    &panel.appearance,
1474                    global_hues,
1475                )?;
1476            }
1477        }
1478        let operation = stage.operation();
1479        let continuous = self.prepare_continuous_shared_guide(&registry, slots, &operation)?;
1480        if let Some(descriptor) = &continuous {
1481            self.install_shared_continuous_domain(&mut registry, slots, descriptor)?;
1482        }
1483        let shared_guide =
1484            self.prepare_discrete_guides(&mut registry, slots, &color_domains, &operation)?;
1485        let plots = registry.finish()?;
1486        let plot_intrinsics = crate::data::source::collect_source(plots.iter().map(|plot| {
1487            Ok((
1488                plot.scope.id.clone(),
1489                crate::orchestrator::root::PlotIntrinsics::for_kind(plot.kind()),
1490            ))
1491        }))?;
1492        let (mut census, presence) =
1493            self.foundational_text_census(&request, &plots, slots, shared_guide.as_ref(), stage)?;
1494        text.prepare_font_environment_from_census(&mut census, presence, stage)?;
1495        let (root_text, text_panels, prose) =
1496            self.prepare_intrinsics(&request, &plots, slots, &plot_intrinsics, &operation)?;
1497        let headers = crate::data::source::collect_source(
1498            [
1499                (CanvasHeaderRole::Column, self.column_headers.len()),
1500                (CanvasHeaderRole::Row, self.row_headers.len()),
1501                (CanvasHeaderRole::RowTitle, self.row_titles.len()),
1502            ]
1503            .into_iter()
1504            .flat_map(|(role, count)| {
1505                (0..count).map(move |declaration| {
1506                    Ok(CanvasHeaderSource {
1507                        role: match role {
1508                            CanvasHeaderRole::Column => CanvasHeaderRole::Column,
1509                            CanvasHeaderRole::Row => CanvasHeaderRole::Row,
1510                            CanvasHeaderRole::RowTitle => CanvasHeaderRole::RowTitle,
1511                        },
1512                        declaration,
1513                    })
1514                })
1515            }),
1516        )?;
1517        let ids = |groups: &[Vec<usize>]| {
1518            crate::data::source::collect_source(groups.iter().map(|group| {
1519                crate::data::source::collect_source(group.iter().map(|&index| {
1520                    let Some(CanvasAnchor::Plot(id)) = &slots[index] else {
1521                        unreachable!("validated Canvas group member")
1522                    };
1523                    Ok(id.clone())
1524                }))
1525            }))
1526        };
1527        let category_bands = ids(&bands)?;
1528        let shared_guide = shared_guide
1529            .map(|descriptor| {
1530                Ok::<_, Error>(crate::decorations::legend::discrete::GuideSlot {
1531                    descriptor,
1532                    owner: crate::layout::ComponentAddress::root()
1533                        .child(crate::layout::AddressRole::CanvasSharedLegend, 0)?,
1534                })
1535            })
1536            .transpose()?;
1537        topology.headers = headers;
1538        topology.category_bands = category_bands;
1539        topology.shared_guide = shared_guide;
1540        Ok(Root {
1541            source: RootSource::Canvas(self),
1542            identity: operation.root_identity(),
1543            operation,
1544            next_candidate: std::cell::Cell::new(0),
1545            root_appearance,
1546            plots,
1547            composition: PreparedComposition::Canvas(topology),
1548            census,
1549            root_text,
1550            text,
1551            plot_intrinsics,
1552            composition_intrinsics: CompositionIntrinsics::Canvas {
1553                text: text_panels,
1554                prose,
1555            },
1556            caches: std::cell::RefCell::new(crate::orchestrator::root::RootLayoutCaches::new(
1557                crate::decorations::plan::children::ChildPlans::canvas(),
1558            )),
1559        })
1560    }
1561
1562    pub(crate) fn measure_root(
1563        &self,
1564        root: &Root<'_>,
1565        requested: crate::layout::RootRequest,
1566        round: &mut crate::layout::kernel::FeedbackRound,
1567        children: &mut crate::decorations::plan::children::ChildPlans,
1568        heights: &mut sizing::HeightMeasurements,
1569    ) -> Result<MeasuredOwnedPlan, Error> {
1570        let assigned = sizing::measure(self, root, requested, round, heights)?;
1571        if let Some(guide) = root.canvas_guide() {
1572            round.observe_guide(guide)?;
1573        }
1574        root.root_text
1575            .check_width(
1576                f64::from(assigned.dimensions()?.0) - 32.0,
1577                &FitScope::root(),
1578            )
1579            .map_err(crate::layout::fit::PlanError::into_error)?;
1580        #[cfg(test)]
1581        let backend_begins =
1582            crate::render::geometry::GEOMETRY_BACKEND_BEGINS.with(std::cell::Cell::get);
1583        let measurement = root.assignment_factory().assign(assigned);
1584        let plan = self.build_canvas_plan(
1585            root,
1586            measurement,
1587            round,
1588            children,
1589            self.root_size.automatic_height(),
1590            Some(heights),
1591        )?;
1592        #[cfg(test)]
1593        assert_eq!(
1594            crate::render::geometry::GEOMETRY_BACKEND_BEGINS.with(std::cell::Cell::get),
1595            backend_begins,
1596            "Canvas measurement must not open a backend",
1597        );
1598        Ok(plan)
1599    }
1600
1601    #[expect(
1602        clippy::type_complexity,
1603        reason = "one prepared root and both cell-intrinsic inventories are retained before parent allocation"
1604    )]
1605    fn prepare_intrinsics(
1606        &self,
1607        request: &crate::text::TextRequestContext<'_, '_>,
1608        plots: &[crate::orchestrator::registration::PlotRegistration<'_>],
1609        slots: &[Option<crate::orchestrator::root::CanvasAnchor>],
1610        intrinsics: &[(
1611            crate::orchestrator::registration::PlotOccurrenceId,
1612            crate::orchestrator::root::PlotIntrinsics,
1613        )],
1614        operation: &crate::font::canonical::OperationContext,
1615    ) -> Result<
1616        (
1617            crate::decorations::title_block::plan::RootTitleBlockIntrinsics,
1618            Vec<Option<text_panel::TextPanelIntrinsics>>,
1619            Vec<(
1620                PlotOccurrenceId,
1621                crate::decorations::title_block::plan::RootTitleBlockIntrinsics,
1622            )>,
1623        ),
1624        Error,
1625    > {
1626        // All summaries use the prepared labels and the actual owner theme,
1627        // after the font census and before any parent allocation or child probe.
1628        for index in 0..slots.len() {
1629            if let Some(registered) = plot_at(plots, slots, index) {
1630                crate::layout::interior::InteriorRoute::classify(registered.source.kind())
1631                    .validate(registered.source)?;
1632                if registered.axes.coordinate().is_none() {
1633                    continue;
1634                }
1635                crate::orchestrator::root::prepare_plot_intrinsics(
1636                    &intrinsics[registered.scope.id.slot].1,
1637                    &crate::orchestrator::root::PlotIntrinsicInputs {
1638                        registered,
1639                        request: crate::text::TextRequestContext::new(
1640                            &registered.appearance,
1641                            request.text,
1642                        ),
1643                        operation,
1644                        diagnostic_scope: registered.scope.render_name.as_deref(),
1645                        y_visible: registered.policy.axis_text.tick_labels[1],
1646                    },
1647                )?;
1648            }
1649        }
1650        let mut text_panels = Vec::new();
1651        crate::layout::fit::reserve(
1652            &mut text_panels,
1653            self.placements.len(),
1654            "TextPanel intrinsic summaries",
1655        )?;
1656        for panel in self.placements.texts() {
1657            text_panels.push(
1658                panel
1659                    .as_ref()
1660                    .map(|panel| text_panel::TextPanelIntrinsics::prepare(panel, request))
1661                    .transpose()?,
1662            );
1663        }
1664        let mut plot_titles = Vec::new();
1665        crate::layout::fit::reserve(
1666            &mut plot_titles,
1667            self.placements.len(),
1668            "Canvas Plot text intrinsics",
1669        )?;
1670
1671        for (index, plot) in self.placements.plots().enumerate() {
1672            if let Some(plot) = plot {
1673                let mut scope = String::new();
1674                crate::data::source::reserve_source_string(&mut scope, 32)?;
1675                write!(scope, "panel-{index}").expect("reserved Canvas scope");
1676                let summary =
1677                    crate::decorations::title_block::plan::RootTitleBlockPlan::intrinsic_widths(
1678                        &crate::text::TextRequestContext::new(
1679                            &plot_at(plots, slots, index)
1680                                .expect("configured Canvas Plot theme")
1681                                .appearance,
1682                            request.text,
1683                        ),
1684                        plot.prose(),
1685                        Some(&scope),
1686                    )?;
1687                plot_titles.push((
1688                    plot_at(plots, slots, index)
1689                        .expect("configured Canvas prose")
1690                        .scope
1691                        .id
1692                        .clone(),
1693                    summary,
1694                ));
1695            }
1696        }
1697        let root = crate::decorations::title_block::plan::RootTitleBlockPlan::intrinsic_widths(
1698            request,
1699            self.prose(),
1700            None,
1701        )?;
1702        Ok((root, text_panels, plot_titles))
1703    }
1704
1705    #[expect(
1706        clippy::too_many_lines,
1707        reason = "the Canvas census keeps canonical root, composition, and panel preorder explicit"
1708    )]
1709    fn foundational_text_census(
1710        &self,
1711        request: &crate::text::TextRequestContext<'_, '_>,
1712        plots: &[crate::orchestrator::registration::PlotRegistration<'_>],
1713        slots: &[Option<crate::orchestrator::root::CanvasAnchor>],
1714        shared_guide: Option<&Arc<PreparedGuide>>,
1715        prepared_stage: &mut crate::layout::kernel::PreparedStage<'_>,
1716    ) -> Result<(crate::layout::PreparedTextCensus, Vec<u64>), Error> {
1717        let root = crate::layout::ComponentAddress::root();
1718        let mut requirements = Vec::new();
1719        for (source, role, address_role, appearance) in [
1720            (
1721                self.title.provided(),
1722                crate::layout::PreparedTextRole::Title,
1723                crate::layout::AddressRole::RootTitle,
1724                &request.typography.root.title,
1725            ),
1726            (
1727                self.subtitle.provided(),
1728                crate::layout::PreparedTextRole::Subtitle,
1729                crate::layout::AddressRole::RootSubtitle,
1730                &request.typography.root.subtitle,
1731            ),
1732            (
1733                self.caption.provided(),
1734                crate::layout::PreparedTextRole::Caption,
1735                crate::layout::AddressRole::RootCaption,
1736                &request.typography.root.caption,
1737            ),
1738        ] {
1739            if let Some(source) = source {
1740                let address = root.child(address_role, 0)?;
1741                crate::layout::PreparedTextRequirement::push_authored(
1742                    &mut requirements,
1743                    address,
1744                    role,
1745                    Some(source),
1746                    appearance,
1747                    true,
1748                    Some(prepared_stage),
1749                )?;
1750            }
1751        }
1752
1753        if let Some(guide) = shared_guide {
1754            guide.append_requirements(
1755                &mut requirements,
1756                request,
1757                &root.child(crate::layout::AddressRole::CanvasSharedLegend, 0)?,
1758                Some(prepared_stage),
1759            )?;
1760        }
1761        let composition_title = &request.typography.composition.composition_header;
1762        for (index, header) in self.column_headers.iter().enumerate() {
1763            let address = root.child(
1764                crate::layout::AddressRole::CanvasHeader,
1765                u32::try_from(index).map_err(|_| {
1766                    Error::Render("canvas column-header census index overflowed".into())
1767                })?,
1768            )?;
1769            crate::layout::PreparedTextRequirement::push_authored(
1770                &mut requirements,
1771                address,
1772                crate::layout::PreparedTextRole::Header,
1773                Some(&header.text),
1774                composition_title,
1775                false,
1776                Some(prepared_stage),
1777            )?;
1778        }
1779        for (index, header) in self.row_headers.iter().enumerate() {
1780            let address = root.child(
1781                crate::layout::AddressRole::CanvasHeader,
1782                u32::try_from(self.column_headers.len() + index).map_err(|_| {
1783                    Error::Render("canvas row-header census index overflowed".into())
1784                })?,
1785            )?;
1786            crate::layout::PreparedTextRequirement::push_authored(
1787                &mut requirements,
1788                address,
1789                crate::layout::PreparedTextRole::Header,
1790                Some(&header.text),
1791                composition_title,
1792                false,
1793                Some(prepared_stage),
1794            )?;
1795        }
1796        for (index, title) in self.row_titles.iter().enumerate() {
1797            let address = root.child(
1798                crate::layout::AddressRole::CanvasRowTitle,
1799                u32::try_from(index).map_err(|_| {
1800                    Error::Render("canvas row-title census index overflowed".into())
1801                })?,
1802            )?;
1803            crate::layout::PreparedTextRequirement::push_authored(
1804                &mut requirements,
1805                address,
1806                crate::layout::PreparedTextRole::Header,
1807                Some(&title.text),
1808                composition_title,
1809                false,
1810                Some(prepared_stage),
1811            )?;
1812        }
1813        for (index, panel) in self.placements.texts().enumerate() {
1814            let Some(panel) = panel else { continue };
1815            let address = root.child(
1816                crate::layout::AddressRole::TextPanelContent,
1817                u32::try_from(index)
1818                    .map_err(|_| Error::Render("text-panel census index overflowed".into()))?,
1819            )?;
1820            let [title_style, body_style] = panel.appearances(request);
1821            for (slot, role, source, appearance) in [
1822                (
1823                    0,
1824                    crate::layout::PreparedTextRole::Header,
1825                    panel.title(),
1826                    title_style.theme,
1827                ),
1828                (
1829                    1,
1830                    crate::layout::PreparedTextRole::Body,
1831                    panel.body(),
1832                    body_style.theme,
1833                ),
1834            ] {
1835                let requirement_address = address.clone();
1836                push_text_requirement(
1837                    &mut requirements,
1838                    requirement_address,
1839                    role,
1840                    0,
1841                    source,
1842                    appearance,
1843                    prepared_stage,
1844                )?;
1845                push_text_requirement(
1846                    &mut requirements,
1847                    address.child(crate::layout::AddressRole::PreferenceMetric, slot)?,
1848                    crate::layout::PreparedTextRole::PreferenceMetric,
1849                    0,
1850                    "0",
1851                    appearance,
1852                    prepared_stage,
1853                )?;
1854            }
1855        }
1856
1857        for (index, plot) in self.placements.plots().enumerate() {
1858            let Some(plot) = plot else { continue };
1859
1860            let registered =
1861                plot_at(plots, slots, index).expect("configured canvas panel has a resolved theme");
1862            let theme = &crate::text::TextRequestContext::new(&registered.appearance, request.text);
1863            let cell = root.child(
1864                crate::layout::AddressRole::CanvasCell,
1865                u32::try_from(index)
1866                    .map_err(|_| Error::Render("canvas text census index overflowed".into()))?,
1867            )?;
1868            let filter_point_label_x_to_limits = !self
1869                .x_range_groups
1870                .iter()
1871                .any(|group| group.contains(&index));
1872            crate::layout::PreparedTextRequirement::append_plot(
1873                Some(std::slice::from_ref(registered)),
1874                registered.guide.descriptor.as_ref(),
1875                &mut requirements,
1876                plot,
1877                plot.kind(),
1878                theme,
1879                &cell,
1880                true,
1881                filter_point_label_x_to_limits,
1882                true,
1883                Some(prepared_stage),
1884            )?;
1885        }
1886        crate::layout::PreparedTextRequirement::append_preference_metrics(
1887            &mut requirements,
1888            request,
1889            &root,
1890            prepared_stage,
1891        )?;
1892        for (index, plot) in self.placements.plots().enumerate() {
1893            if plot.is_some() {
1894                let owner = root.child(
1895                    crate::layout::AddressRole::CanvasCell,
1896                    u32::try_from(index).map_err(|_| {
1897                        Error::Render("Canvas metric census owner overflowed".into())
1898                    })?,
1899                )?;
1900                crate::layout::PreparedTextRequirement::append_preference_metrics(
1901                    &mut requirements,
1902                    &crate::text::TextRequestContext::new(
1903                        &plot_at(plots, slots, index)
1904                            .expect("configured Canvas Plot retains theme")
1905                            .appearance,
1906                        request.text,
1907                    ),
1908                    &owner,
1909                    prepared_stage,
1910                )?;
1911            }
1912        }
1913        let text_topology =
1914            crate::layout::PreparedTextCensus::structural_address_count(&requirements)
1915                .map_err(|error| Error::Render(format!("prepared canvas text census: {error}")))?;
1916        let mut scalar_presence = prepared_stage.reserve_scalar_presence_map()?;
1917        let census = crate::layout::PreparedTextCensus::materialize(
1918            requirements,
1919            Some(prepared_stage),
1920            Some(&mut scalar_presence),
1921        )
1922        .map_err(|error| Error::Render(format!("prepared canvas text census: {error}")))?;
1923        if census.counts.structural_addresses != text_topology {
1924            return Err(Error::Render(format!(
1925                "prepared canvas text topology counted {text_topology} addresses but materialized {}",
1926                census.counts.structural_addresses
1927            )));
1928        }
1929        Ok((census, scalar_presence))
1930    }
1931
1932    #[expect(
1933        clippy::too_many_lines,
1934        reason = "one Canvas round consumes separate retained domains, hue identities, and child inputs"
1935    )]
1936    fn build_canvas_plan(
1937        &self,
1938        root: &Root<'_>,
1939        measurement: RootAssignment,
1940        round: &mut crate::layout::kernel::FeedbackRound,
1941        children: &mut crate::decorations::plan::children::ChildPlans,
1942        content_sizing: bool,
1943        mut measurements: Option<&mut sizing::HeightMeasurements>,
1944    ) -> Result<MeasuredOwnedPlan, Error> {
1945        use crate::layout::fit::FitOutcome;
1946        use crate::layout::kernel::TrialOutcome;
1947        let assigned = measurement.measurement_size;
1948        let canvas_layout = self.prepare_canvas_frame(root, assigned, round)?;
1949        let body_probes = if self.legend_policy == CanvasLegendPolicy::Shared {
1950            self.preflight_shared_legend(
1951                root,
1952                &measurement,
1953                canvas_layout.panel_box,
1954                children,
1955                round,
1956            )?
1957        } else {
1958            Vec::new()
1959        };
1960        let shared_legend = root.canvas_topology().shared_guide.as_ref();
1961        let mut compact_changes = true;
1962        if self.legend_policy != CanvasLegendPolicy::Shared || shared_legend.is_none() {
1963            return match self.build_canvas_attempt(
1964                root,
1965                measurement,
1966                &canvas_layout,
1967                &body_probes,
1968                content_sizing,
1969                round,
1970                None,
1971                &mut compact_changes,
1972                children,
1973                measurements.as_deref_mut(),
1974            )? {
1975                FitOutcome::Measured(plan) => Ok(plan),
1976                FitOutcome::Miss(reason) => Err(reason.into_error()),
1977            };
1978        }
1979        let owner = crate::layout::ComponentAddress::root()
1980            .child(crate::layout::AddressRole::CanvasSharedLegend, 0)?;
1981        let mut first_miss = None;
1982        for (edge_index, edge) in [
1983            crate::LegendPosition::OutsideRight,
1984            crate::LegendPosition::OutsideTop,
1985            crate::LegendPosition::OutsideBottom,
1986            crate::LegendPosition::OutsideLeft,
1987        ]
1988        .into_iter()
1989        .enumerate()
1990        {
1991            compact_changes = true;
1992            for compact in [false, true] {
1993                if compact && !compact_changes {
1994                    continue;
1995                }
1996                round.claim_guide_trial(
1997                    &owner,
1998                    8,
1999                    u32::try_from(edge_index * 2 + usize::from(compact))
2000                        .map_err(|_| Error::Render("Canvas guide ordinal overflowed".into()))?,
2001                )?;
2002                let checkpoint = round.begin_trial()?;
2003                round.observe_count(edge as usize)?;
2004                round.observe_count(usize::from(compact))?;
2005                let outcome = self.build_canvas_attempt(
2006                    root,
2007                    RootAssignment {
2008                        candidate: measurement.candidate.clone(),
2009                        request: measurement.request,
2010                        measurement_size: measurement.measurement_size,
2011                    },
2012                    &canvas_layout,
2013                    &body_probes,
2014                    content_sizing,
2015                    round,
2016                    Some((edge, compact)),
2017                    &mut compact_changes,
2018                    children,
2019                    measurements.as_deref_mut(),
2020                )?;
2021                match outcome {
2022                    FitOutcome::Measured(plan) => match round.finish_trial(checkpoint) {
2023                        _outcome @ (TrialOutcome::Fit | TrialOutcome::Provisional) => {
2024                            return Ok(plan);
2025                        }
2026                        TrialOutcome::Miss(reason) => {
2027                            FitFailure::retain_least(&mut first_miss, reason);
2028                        }
2029                    },
2030                    FitOutcome::Miss(reason) => {
2031                        round.record_failure(reason)?;
2032                        if let TrialOutcome::Miss(reason) = round.finish_trial(checkpoint) {
2033                            FitFailure::retain_least(&mut first_miss, reason);
2034                        }
2035                    }
2036                }
2037            }
2038        }
2039        Err(first_miss
2040            .unwrap_or_else(|| {
2041                FitScope::new(&owner, 0).failure(
2042                    FitKind::LegendOrGuide,
2043                    "shared guide cannot fit its containing Canvas frame",
2044                )
2045            })
2046            .into_error())
2047    }
2048
2049    fn prepare_canvas_frame(
2050        &self,
2051        root: &Root<'_>,
2052        assigned: crate::layout::RootSize,
2053        round: &mut crate::layout::kernel::FeedbackRound,
2054    ) -> Result<RootFramePlan, Error> {
2055        let (width, height) = assigned.dimensions()?;
2056        let request = &root.request();
2057
2058        let canvas_layout = RootFramePlan::measure(
2059            (width, height),
2060            request,
2061            self.prose(),
2062            crate::decorations::title_block::plan::RootAlignments::resolve(
2063                request,
2064                self.prose_alignments(),
2065                [None; 2],
2066            ),
2067            (
2068                crate::layout::canvas::MINIMUM_PANEL_SPAN,
2069                crate::layout::canvas::MINIMUM_PANEL_SPAN,
2070            ),
2071        )
2072        .map_err(crate::layout::fit::PlanError::into_error)?;
2073        round.observe_canvas(&canvas_layout)?;
2074        for (index, source) in self.placements.plots().enumerate() {
2075            let Some(source) = source else { continue };
2076            if let Some(registered) = root.canvas_plot(index) {
2077                crate::layout::interior::InteriorRoute::classify(registered.source.kind())
2078                    .validate(source)?;
2079            }
2080        }
2081        Ok(canvas_layout)
2082    }
2083
2084    /// Retain the parent reduction and its finite-domain error at the original
2085    /// coordination boundary. Assignments consume these same real members.
2086    fn coordinate_domains(
2087        &self,
2088        root: &Root<'_>,
2089        round: &crate::layout::kernel::FeedbackRound,
2090    ) -> Result<(), Error> {
2091        for group in &root.canvas_topology().range_groups {
2092            let mut shared: Option<(f64, f64)> = None;
2093            for id in group {
2094                let registered = &root.plots[id.slot];
2095                let index = registered.scope.address.leaf_slot_index();
2096                let base = registered.axes.ranges()[0];
2097                let address = crate::layout::ComponentAddress::root()
2098                    .child(crate::layout::AddressRole::CanvasCell, index)?;
2099                let range = round
2100                    .feedback_domain(&address, FeedbackKind::AutomaticDomainX)
2101                    .map_or(base, |range| (base.0.min(range.0), base.1.max(range.1)));
2102                shared = Some(shared.map_or(range, |current| {
2103                    (current.0.min(range.0), current.1.max(range.1))
2104                }));
2105            }
2106            let shared = shared.expect("validated nonempty x-range group");
2107            if !shared.0.is_finite() || !shared.1.is_finite() || shared.0 >= shared.1 {
2108                return Err(Error::Render(
2109                    "Canvas shared x domain must be finite and ascending".into(),
2110                ));
2111            }
2112        }
2113        for (index, source) in self.placements.plots().enumerate() {
2114            if source.is_none() {
2115                continue;
2116            }
2117            let _ = crate::layout::ComponentAddress::root().child(
2118                crate::layout::AddressRole::CanvasCell,
2119                u32::try_from(index)
2120                    .map_err(|_| Error::Render("Canvas coordinated address overflowed".into()))?,
2121            )?;
2122        }
2123        Ok(())
2124    }
2125
2126    #[expect(
2127        clippy::too_many_arguments,
2128        reason = "gutter probes consume assigned cells and the selected Shared residual allocation"
2129    )]
2130    fn complete_cell_gutters(
2131        &self,
2132        root: &Root<'_>,
2133        measurement: &RootAssignment,
2134        dimensions: PlotMeasureDimensions,
2135        cells: &[Option<PixelRect>],
2136        request: &crate::text::TextRequestContext<'_, '_>,
2137        children: &mut crate::decorations::plan::children::ChildPlans,
2138        round: &crate::layout::kernel::FeedbackRound,
2139        requirements: &mut [(usize, usize, EdgeSpaceRequirements)],
2140        shared_allocation: Option<GuideAllocation>,
2141    ) -> Result<FitOutcome<()>, Error> {
2142        for GridSlot(index) in &root.canvas_topology().producers {
2143            let index = *index;
2144            let Some(registered) = root.canvas_plot(index) else {
2145                continue;
2146            };
2147            let theme = &crate::text::TextRequestContext::new(&registered.appearance, request.text);
2148            let dependencies = self.consumed_guide_dependencies(
2149                index,
2150                cells[index].expect("configured owner assignment").width(),
2151                shared_allocation,
2152                round,
2153            )?;
2154            let guides = GuideConsumption {
2155                dependencies: &dependencies,
2156                ..SUPPRESSED_GUIDES
2157            };
2158            let factory = root.plot_assignment_factory(measurement, &registered.scope.id)?;
2159            let entry = factory.assign(
2160                probe_allocation(
2161                    dimensions,
2162                    cells[index].expect("configured owner assignment"),
2163                    round,
2164                    &registered.scope.address,
2165                ),
2166                round,
2167                Some(MeasurementPhase::Probe),
2168            )?;
2169            let scope = FitScope::root();
2170            let context = factory.context(&entry, guides, &scope)?;
2171            let probe = match canvas_probe(
2172                &factory,
2173                &context,
2174                children,
2175                index,
2176                MeasurementPhase::Probe,
2177                round,
2178            )? {
2179                FitOutcome::Measured(probe) => probe,
2180                FitOutcome::Miss(failure) => return Ok(FitOutcome::Miss(failure)),
2181            };
2182            let measured = EdgeSpaceRequirements::measure_header(
2183                probe
2184                    .axes
2185                    .as_ref()
2186                    .ok_or_else(|| Error::Render("Canvas probe is missing measured axes".into()))?,
2187                theme,
2188            )
2189            .map_err(crate::layout::fit::PlanError::into_error)?;
2190            let target = &mut requirements[index].2;
2191            target.left = target.left.max(measured.left);
2192            target.right = target.right.max(measured.right);
2193            target.bottom = target.bottom.max(measured.bottom);
2194            target.top = target.top.max(measured.top);
2195        }
2196        Ok(FitOutcome::Measured(()))
2197    }
2198
2199    #[expect(
2200        clippy::too_many_lines,
2201        clippy::too_many_arguments,
2202        reason = "one Canvas trial allocates declared tracks and measures every affected child"
2203    )]
2204    fn build_canvas_attempt(
2205        &self,
2206        root: &Root<'_>,
2207        measurement: RootAssignment,
2208        initial_frame: &RootFramePlan,
2209        body_probes: &[Option<Arc<crate::spec::PlotRenderResult>>],
2210        content_sizing: bool,
2211        round: &mut crate::layout::kernel::FeedbackRound,
2212        guide_trial: Option<(crate::LegendPosition, bool)>,
2213        compact_changes: &mut bool,
2214        children: &mut crate::decorations::plan::children::ChildPlans,
2215        mut measurements: Option<&mut sizing::HeightMeasurements>,
2216    ) -> Result<crate::layout::fit::FitOutcome<MeasuredOwnedPlan>, Error> {
2217        use crate::layout::fit;
2218        let root_address = crate::layout::ComponentAddress::root();
2219        let guide_owner = root_address.child(crate::layout::AddressRole::CanvasSharedLegend, 0)?;
2220        let scope = FitScope::new(&root_address, round.attempt_ordinal(&guide_owner));
2221        let guide_scope = FitScope::new(&guide_owner, scope.ordinal);
2222        let request = &root.request();
2223        let assigned = measurement.measurement_size;
2224        let mut canvas_layout = initial_frame.clone();
2225        let mut full_outer = canvas_layout.panel_box;
2226        self.coordinate_domains(root, round)?;
2227        let natural_grid_height = |width: f64,
2228                                   shared: bool,
2229                                   round: &crate::layout::kernel::FeedbackRound|
2230         -> Result<FitOutcome<f64>, Error> {
2231            // Both height composition and final allocation consume the same
2232            // root-owned gutters. A probe at a provisional height can choose
2233            // different ticks and must not replace those scoped inputs locally.
2234            let gutters = sizing::grid_gutters(self, root, round)?;
2235            let grid = tracks::allocate(
2236                PixelRect::new(0.0, width, 0.0, 0.0),
2237                &self.placements,
2238                root,
2239                Some(round),
2240                &self.column_headers,
2241                &self.row_headers,
2242                &self.row_titles,
2243                &gutters,
2244                request,
2245                &scope,
2246                Some(&tracks::ContentSizing {
2247                    source: self,
2248                    root,
2249                    output_dimensions: Some(assigned),
2250                    initial_sizing: false,
2251                    round,
2252                    measurements: measurements.as_deref(),
2253                    shared_allocation: shared.then(|| GuideAllocation::width(width)).transpose()?,
2254                    natural_width: false,
2255                    natural_height: true,
2256                }),
2257            )?;
2258            Ok(match grid {
2259                FitOutcome::Measured(grid) => FitOutcome::Measured(grid.size.1),
2260                FitOutcome::Miss(reason) => FitOutcome::Miss(reason),
2261            })
2262        };
2263        let mut outer = full_outer;
2264        let shared_legend = if let Some(slot) = &root.canvas_topology().shared_guide {
2265            let descriptor = &slot.descriptor;
2266            let (edge, compact) = guide_trial.expect("shared guide has an owned trial");
2267            let horizontal = matches!(
2268                edge,
2269                crate::LegendPosition::OutsideTop | crate::LegendPosition::OutsideBottom
2270            );
2271            let gap = request.legend_shared_gap()?;
2272            let minimum = match tracks::minimum(&self.placements, root, round, request, &scope)? {
2273                FitOutcome::Measured(minimum) => minimum,
2274                FitOutcome::Miss(failure) => return Ok(FitOutcome::Miss(failure)),
2275            };
2276            let frame = crate::decorations::plan::AssignedGuideFrame::new(edge, minimum, gap);
2277            let available = frame.available(full_outer, [0.0; 4]);
2278            let measured = match Legend::measure_assigned(
2279                Arc::clone(descriptor),
2280                (available.0, (!content_sizing).then_some(available.1)),
2281                horizontal,
2282                compact,
2283                request,
2284                compact_changes,
2285                &guide_scope,
2286            )? {
2287                FitOutcome::Measured(legend) => legend,
2288                FitOutcome::Miss(reason) => return Ok(FitOutcome::Miss(reason)),
2289            };
2290            let (w, h) = (measured.compute_box_width(), measured.compute_box_height());
2291            if content_sizing {
2292                let grid_width = full_outer.width() - if horizontal { 0.0 } else { w + gap };
2293                let height = match natural_grid_height(grid_width, true, round)? {
2294                    FitOutcome::Measured(height) => height,
2295                    FitOutcome::Miss(reason) => return Ok(FitOutcome::Miss(reason)),
2296                };
2297                let height = if horizontal {
2298                    height + h + gap
2299                } else {
2300                    height.max(h)
2301                };
2302                canvas_layout =
2303                    sizing::content_frame(self, request, assigned.dimensions()?.0, height)?;
2304                full_outer = canvas_layout.panel_box;
2305            }
2306            outer = match frame.assign_fit(full_outer, Some((w, h)), [0.0; 4], &scope)? {
2307                FitOutcome::Measured(panel) => panel,
2308                FitOutcome::Miss(reason) => return Ok(FitOutcome::Miss(reason)),
2309            };
2310            let placed = frame.place(outer, (w, h));
2311            let (left, bottom) = (placed.x0, placed.y0);
2312            Some(crate::decorations::plan::ResolvedLegend {
2313                bounds: measured.box_at(left, bottom),
2314                legend: measured,
2315            })
2316        } else {
2317            if content_sizing {
2318                let height = match natural_grid_height(full_outer.width(), false, round)? {
2319                    FitOutcome::Measured(height) => height,
2320                    FitOutcome::Miss(reason) => return Ok(FitOutcome::Miss(reason)),
2321                };
2322                canvas_layout =
2323                    sizing::content_frame(self, request, assigned.dimensions()?.0, height)?;
2324                full_outer = canvas_layout.panel_box;
2325                outer = full_outer;
2326            }
2327            None
2328        };
2329        let shared_allocation = shared_legend
2330            .as_ref()
2331            .map(|_| GuideAllocation::bounds(outer))
2332            .transpose()?;
2333        let shared_width = shared_legend
2334            .as_ref()
2335            .map(|_| GuideAllocation::width(outer.width()))
2336            .transpose()?;
2337        let current_height = crate::layout::kernel::root_dimension(
2338            canvas_layout.panel_box.y1 + canvas_layout.insets.top,
2339        )?;
2340        let dimensions = PlotMeasureDimensions {
2341            canvas: crate::layout::RootSize::new(assigned.dimensions()?.0, current_height),
2342            output_override: Some(assigned),
2343        };
2344        let provisional = match tracks::allocate(
2345            outer,
2346            &self.placements,
2347            root,
2348            Some(round),
2349            &self.column_headers,
2350            &self.row_headers,
2351            &self.row_titles,
2352            &[],
2353            request,
2354            &scope.child(crate::layout::AddressRole::CanvasGrid, 0)?,
2355            content_sizing
2356                .then_some(tracks::ContentSizing {
2357                    source: self,
2358                    root,
2359                    output_dimensions: dimensions.output_override,
2360                    initial_sizing: false,
2361                    round,
2362                    measurements: measurements.as_deref(),
2363                    shared_allocation: shared_width,
2364                    natural_width: false,
2365                    natural_height: false,
2366                })
2367                .as_ref(),
2368        )? {
2369            FitOutcome::Measured(grid) => grid.owners,
2370            FitOutcome::Miss(reason) => return Ok(FitOutcome::Miss(reason)),
2371        };
2372        if self.category_labels == CanvasCategoryLabels::FirstColumnPerRow {
2373            let _ = self.category_bands()?;
2374            for band in &root.canvas_topology().category_bands {
2375                let first = root.plot(&band[0])?;
2376                let first_index = usize::try_from(first.scope.address.leaf_slot_index())
2377                    .expect("Canvas slot fits usize");
2378                let row = first_index / self.columns;
2379                let dependencies = self.consumed_guide_dependencies(
2380                    first_index,
2381                    provisional[first_index]
2382                        .expect("configured owner assignment")
2383                        .width(),
2384                    shared_allocation,
2385                    round,
2386                )?;
2387                let guides = GuideConsumption {
2388                    dependencies: &dependencies,
2389                    ..SUPPRESSED_GUIDES
2390                };
2391                let expected = category_probe(
2392                    root,
2393                    &measurement,
2394                    dimensions,
2395                    provisional[first_index].expect("configured owner assignment"),
2396                    guides,
2397                    children,
2398                    first_index,
2399                    round,
2400                )?;
2401                let expected_selection = first.source.y_axis_spec().category_labels.clone();
2402                for id in &band[1..] {
2403                    let registered = root.plot(id)?;
2404                    let index = usize::try_from(registered.scope.address.leaf_slot_index())
2405                        .expect("Canvas slot fits usize");
2406                    if expected_selection != registered.source.y_axis_spec().category_labels {
2407                        return Err(Error::Data(
2408                            "shared category axes require identical label selection policies"
2409                                .into(),
2410                        ));
2411                    }
2412                    let dependencies = self.consumed_guide_dependencies(
2413                        index,
2414                        provisional[index]
2415                            .expect("configured owner assignment")
2416                            .width(),
2417                        shared_allocation,
2418                        round,
2419                    )?;
2420                    let guides = GuideConsumption {
2421                        dependencies: &dependencies,
2422                        ..SUPPRESSED_GUIDES
2423                    };
2424                    if category_probe(
2425                        root,
2426                        &measurement,
2427                        dimensions,
2428                        provisional[index].expect("configured owner assignment"),
2429                        guides,
2430                        children,
2431                        index,
2432                        round,
2433                    )? != expected
2434                    {
2435                        return Err(Error::Data(format!(
2436                            "canvas row {row} category domains differ across panels"
2437                        )));
2438                    }
2439                }
2440            }
2441        }
2442        let grid_address = crate::layout::ComponentAddress::root()
2443            .child(crate::layout::AddressRole::CanvasGrid, 0)?;
2444        round.begin_owner(&grid_address)?;
2445        round.observe_box(outer)?;
2446        let mut requirements = Vec::new();
2447        fit::reserve(
2448            &mut requirements,
2449            self.placements.len(),
2450            "Canvas gutter requirements",
2451        )?;
2452        for index in 0..self.placements.len() {
2453            let address = grid_address.child(
2454                crate::layout::AddressRole::CanvasCell,
2455                u32::try_from(index)
2456                    .map_err(|_| Error::Render("canvas grid address overflowed".into()))?,
2457            )?;
2458            let [left, right, bottom, top] = round.insets(&address, FeedbackKind::AxisGutter);
2459            let owned = round.insets(&address, FeedbackKind::OwnedInk);
2460            let top = top + owned[3];
2461            requirements.push((
2462                index / self.columns,
2463                index % self.columns,
2464                EdgeSpaceRequirements {
2465                    left,
2466                    right,
2467                    bottom,
2468                    top,
2469                },
2470            ));
2471        }
2472        for (group_index, group) in root.canvas_topology().range_groups.iter().enumerate() {
2473            let address = grid_address.child(
2474                crate::layout::AddressRole::CanvasRangeGroup,
2475                u32::try_from(group_index)
2476                    .map_err(|_| Error::Render("canvas group address overflowed".into()))?,
2477            )?;
2478            let alignment = round.insets(&address, FeedbackKind::SharedAlignment);
2479            for id in group {
2480                let index = usize::try_from(root.plots[id.slot].scope.address.leaf_slot_index())
2481                    .expect("Canvas slot fits usize");
2482                requirements[index].2.left = requirements[index].2.left.max(alignment[0]);
2483                requirements[index].2.right = requirements[index].2.right.max(alignment[1]);
2484            }
2485        }
2486        if !content_sizing {
2487            if let FitOutcome::Miss(failure) = self.complete_cell_gutters(
2488                root,
2489                &measurement,
2490                dimensions,
2491                &provisional,
2492                request,
2493                children,
2494                round,
2495                &mut requirements,
2496                shared_allocation,
2497            )? {
2498                return Ok(FitOutcome::Miss(failure));
2499            }
2500        }
2501        let grid = match tracks::allocate(
2502            outer,
2503            &self.placements,
2504            root,
2505            Some(round),
2506            &self.column_headers,
2507            &self.row_headers,
2508            &self.row_titles,
2509            &requirements,
2510            request,
2511            &scope.child(crate::layout::AddressRole::CanvasGrid, 0)?,
2512            content_sizing
2513                .then_some(tracks::ContentSizing {
2514                    source: self,
2515                    root,
2516                    output_dimensions: dimensions.output_override,
2517                    initial_sizing: false,
2518                    round,
2519                    measurements: measurements.as_deref(),
2520                    shared_allocation: shared_width,
2521                    natural_width: false,
2522                    natural_height: false,
2523                })
2524                .as_ref(),
2525        )? {
2526            FitOutcome::Measured(grid) => grid,
2527            FitOutcome::Miss(reason) => return Ok(FitOutcome::Miss(reason)),
2528        };
2529        grid.tracks.observe(round)?;
2530        let cells = &grid.owners;
2531        let content_insets = &grid.content_insets;
2532        let headers = &grid.headers;
2533        let row_titles = &grid.row_titles;
2534        let mut measured = Vec::new();
2535        let mut requirements = Vec::new();
2536        fit::reserve(
2537            &mut measured,
2538            self.placements.len(),
2539            "Canvas measured children",
2540        )?;
2541        fit::reserve(
2542            &mut requirements,
2543            self.placements.len(),
2544            "Canvas measured requirements",
2545        )?;
2546        let mut child_miss = None;
2547        for GridSlot(index) in &root.canvas_topology().producers {
2548            let index = *index;
2549            let Some(registered) = root.canvas_plot(index) else {
2550                continue;
2551            };
2552            let plot = registered.source;
2553            let intrinsic = root.plot_intrinsic(&registered.scope.id)?;
2554            let row = index / self.columns;
2555            let column = index % self.columns;
2556            let kind = plot.kind();
2557            let theme = &crate::text::TextRequestContext::new(&registered.appearance, request.text);
2558            let child_scope = scope.child(crate::layout::AddressRole::CanvasCell, index)?;
2559            let cell = cells[index].expect("configured owner assignment");
2560            for value in self.owner_topology(index).expect("Plot topology") {
2561                round.observe_count(value)?;
2562            }
2563            let local = match plot_text::PlotLocalTextPlan::measure(
2564                registered,
2565                intrinsic,
2566                &root.operation,
2567                cell,
2568                theme,
2569                [self.panel_title_alignment, self.panel_subtitle_alignment],
2570                root.canvas_prose(&registered.scope.id),
2571                &child_scope,
2572                sizing::axis_inputs(root, registered, round, false).0,
2573            )? {
2574                FitOutcome::Measured(local) => local,
2575                FitOutcome::Miss(reason) => {
2576                    FitFailure::retain_least(&mut child_miss, reason);
2577                    continue;
2578                }
2579            };
2580            let owner = &registered.scope.address;
2581            let fill_content_height = content_sizing
2582                && self.legend_policy == CanvasLegendPolicy::PerPlot
2583                && !matches!(kind, PlotKind::Heatmap | PlotKind::Beeswarm);
2584            let factory = root.plot_assignment_factory(&measurement, &registered.scope.id)?;
2585            let mut allocation = probe_allocation(dimensions, local.body, round, owner);
2586            allocation.content_height = fill_content_height;
2587            allocation.fill_content_height = fill_content_height;
2588            allocation.guide.edge = plot.legend_position_spec();
2589            let entry = factory.assign(allocation, round, None)?;
2590            if shared_legend.is_some() {
2591                let base = body_probes[index]
2592                    .as_ref()
2593                    .expect("shared guide body probe");
2594                if let FitOutcome::Miss(reason) = crate::decorations::plan::check_assigned_body(
2595                    &factory.context(&entry, SUPPRESSED_GUIDES, &child_scope)?,
2596                    base,
2597                    full_outer,
2598                    local.body,
2599                    theme,
2600                    &scope.child(crate::layout::AddressRole::CanvasCell, index)?,
2601                )? {
2602                    FitFailure::retain_least(&mut child_miss, reason);
2603                }
2604            }
2605            plot.configured_source_rows()?;
2606            let dependencies =
2607                self.consumed_guide_dependencies(index, cell.width(), shared_allocation, round)?;
2608            let role = if self.legend_policy == CanvasLegendPolicy::PerPlot {
2609                crate::decorations::plan::LegendRole::Panel
2610            } else {
2611                crate::decorations::plan::LegendRole::Suppressed
2612            };
2613            let guide = if role == crate::decorations::plan::LegendRole::Panel {
2614                registered.local_guide_slot()?
2615            } else {
2616                None
2617            };
2618            let guides = GuideConsumption {
2619                dependencies: &dependencies,
2620                use_kind: if registered.source.legend_policy_spec() == crate::LegendPolicy::Hidden {
2621                    crate::decorations::legend::discrete::scoped::GuideUse::Hidden
2622                } else if role == crate::decorations::plan::LegendRole::Panel {
2623                    crate::decorations::legend::discrete::scoped::GuideUse::Local
2624                } else {
2625                    crate::decorations::legend::discrete::scoped::GuideUse::SharedSuppressed
2626                },
2627                local_guide: guide.as_ref(),
2628            };
2629            let panel_plan =
2630                match children.plan(&factory, entry, role, guides, &child_scope, round, owner)? {
2631                    FitOutcome::Measured(result) => result,
2632                    FitOutcome::Miss(failure) => {
2633                        FitFailure::retain_least(&mut child_miss, failure);
2634                        continue;
2635                    }
2636                };
2637            if fill_content_height {
2638                let target = grid_address.child(
2639                    crate::layout::AddressRole::CanvasCell,
2640                    u32::try_from(index).map_err(|_| {
2641                        Error::Render("Canvas content height address overflowed".into())
2642                    })?,
2643                )?;
2644                let preferred = sizing::measured_preference(
2645                    registered,
2646                    intrinsic,
2647                    &root.operation,
2648                    &panel_plan,
2649                    cell.height() - local.body.height(),
2650                    round,
2651                    owner,
2652                    theme,
2653                    sizing::axis_inputs(root, registered, round, false).0,
2654                )?;
2655                if let Some(measurements) = measurements.as_deref_mut() {
2656                    let (ranges, provenance, resolved_x) =
2657                        sizing::axis_inputs(root, registered, round, false);
2658                    measurements.record(
2659                        registered,
2660                        Some(self),
2661                        dimensions.output_override,
2662                        ranges,
2663                        provenance,
2664                        resolved_x,
2665                        cell.width(),
2666                        preferred,
2667                        content_insets[index],
2668                        round,
2669                        &target,
2670                        guides.dependencies,
2671                    )?;
2672                }
2673                let request = round.request_insets(
2674                    owner,
2675                    &target,
2676                    FeedbackKind::ContentHeight,
2677                    [cell.width(), 0.0, preferred, 0.0],
2678                )?;
2679                if request.is_some() || preferred > cell.height() + 1.0 / 1024.0 {
2680                    round.miss(
2681                        &target,
2682                        crate::layout::kernel::FitKind::TrackOrResidual,
2683                        &[request],
2684                        "selected Plot guide and prose require their measured content row",
2685                    )?;
2686                }
2687            }
2688            #[cfg(test)]
2689            CANVAS_ASSIGNED_PANEL_EVIDENCE.with(|evidence| {
2690                assert_eq!(panel_plan.selected.cell, local.body);
2691                evidence
2692                    .borrow_mut()
2693                    .push((local.body, panel_plan.result.layout.projection.panel_box()));
2694            });
2695            let requirement = match fit::outcome(EdgeSpaceRequirements::measure_header(
2696                panel_plan.result.axes.as_ref().ok_or_else(|| {
2697                    Error::Render("composed panel is missing its measured axes".into())
2698                })?,
2699                theme,
2700            ))? {
2701                FitOutcome::Measured(requirement) => requirement,
2702                FitOutcome::Miss(failure) => {
2703                    FitFailure::retain_least(&mut child_miss, failure);
2704                    continue;
2705                }
2706            };
2707            measured.push((index, panel_plan, local));
2708            requirements.push((row, column, requirement));
2709        }
2710        if let Some(failure) = child_miss {
2711            return Ok(FitOutcome::Miss(failure));
2712        }
2713        for (group_index, group) in root.canvas_topology().range_groups.iter().enumerate() {
2714            let address = grid_address.child(
2715                crate::layout::AddressRole::CanvasRangeGroup,
2716                u32::try_from(group_index)
2717                    .map_err(|_| Error::Render("canvas group address overflowed".into()))?,
2718            )?;
2719            let mut alignment = [0.0_f64; 4];
2720            for id in group {
2721                let index = usize::try_from(root.plots[id.slot].scope.address.leaf_slot_index())
2722                    .expect("Canvas slot fits usize");
2723                if let Some((_, _, requirement)) = requirements
2724                    .iter()
2725                    .find(|(row, column, _)| row * self.columns + column == index)
2726                {
2727                    alignment[0] = alignment[0].max(requirement.left);
2728                    alignment[1] = alignment[1].max(requirement.right);
2729                }
2730            }
2731            if let Some(request) = round.request_insets(
2732                &address,
2733                &address,
2734                FeedbackKind::SharedAlignment,
2735                alignment,
2736            )? {
2737                round.miss(
2738                    &address,
2739                    FitKind::TrackOrResidual,
2740                    &[Some(request)],
2741                    "shared range group requires aligned panel edges",
2742                )?;
2743            }
2744        }
2745        for (row, column, requirement) in requirements {
2746            let index = row * self.columns + column;
2747            let address = grid_address.child(
2748                crate::layout::AddressRole::CanvasCell,
2749                u32::try_from(index)
2750                    .map_err(|_| Error::Render("canvas grid address overflowed".into()))?,
2751            )?;
2752            round.observe_box(cells[index].expect("measured owner assignment"))?;
2753            if let Some(request) = round.request_insets(
2754                &address,
2755                &address,
2756                crate::layout::kernel::FeedbackKind::AxisGutter,
2757                [
2758                    requirement.left,
2759                    requirement.right,
2760                    requirement.bottom,
2761                    requirement.top,
2762                ],
2763            )? {
2764                round.miss(
2765                    &address,
2766                    crate::layout::kernel::FitKind::Tick,
2767                    &[Some(request)],
2768                    "canvas cell requires measured decoration gutters",
2769                )?;
2770            }
2771        }
2772
2773        let mut text_panels = Vec::new();
2774        crate::render::backend::reserve_text_records(
2775            &mut text_panels,
2776            self.placements.texts().flatten().count(),
2777        )?;
2778        for (index, text_panel) in self.placements.texts().enumerate() {
2779            let Some(text_panel) = text_panel else {
2780                continue;
2781            };
2782            let intrinsic = root.canvas_text()[index]
2783                .expect("configured TextPanel retains prepared intrinsics");
2784            match TextPanelPlan::measure(
2785                text_panel,
2786                index,
2787                cells[index].expect("configured TextPanel assignment"),
2788                request,
2789                intrinsic,
2790                &scope,
2791            )? {
2792                FitOutcome::Measured(plan) => text_panels.push(plan),
2793                FitOutcome::Miss(reason) => return Ok(FitOutcome::Miss(reason)),
2794            }
2795        }
2796
2797        for text_panel in &text_panels {
2798            round.observe_box(text_panel.cell)?;
2799            round.observe_text_block(&text_panel.title)?;
2800            round.observe_text_block(&text_panel.body)?;
2801        }
2802        for header in headers.iter().chain(row_titles) {
2803            round.observe_authored_text(&header.request)?;
2804            round.observe_text(&header.text.plan)?;
2805            round.observe_number(header.text.placement.position.x)?;
2806            round.observe_number(header.text.placement.position.y)?;
2807        }
2808        round.observe_count(usize::from(shared_legend.is_some()))?;
2809        if let Some(legend) = &shared_legend {
2810            legend.observe_feedback(round, legend.legend.available_width())?;
2811        }
2812
2813        let mut panels = Vec::new();
2814        fit::reserve(&mut panels, measured.len(), "Canvas selected panels")?;
2815        for (index, panel_plan, local) in measured {
2816            let _ = cells[index].expect("measured owner assignment");
2817            let mut layers = [String::new(), String::new()];
2818            for (layer, suffix) in layers.iter_mut().zip(["legend", "title"]) {
2819                crate::data::source::reserve_source_string(layer, 40)?;
2820                write!(layer, "panel-{index}-{suffix}").expect("admitted Canvas layer name");
2821            }
2822            let [legend, header_layer] = layers;
2823            let legend = panel_plan
2824                .legend
2825                .as_ref()
2826                .map(|guide| {
2827                    let (x, y) = guide.bounds.anchor();
2828                    guide.legend.select(x, y)
2829                })
2830                .transpose()?
2831                .map(|draw| (legend, draw));
2832            panels.push(OwnedCanvasPlot {
2833                anchor: crate::orchestrator::root::GridSlot(index),
2834                plot: panel_plan,
2835                prose: local.text,
2836                prose_layer: header_layer,
2837                legend,
2838            });
2839        }
2840        let size = crate::layout::RootSize::new(
2841            assigned.dimensions()?.0,
2842            crate::layout::kernel::root_dimension(
2843                canvas_layout.panel_box.y1 + canvas_layout.insets.top,
2844            )?,
2845        );
2846        let content = OwnedCanvasPlan {
2847            grid,
2848            plots: panels,
2849            text_panels,
2850            shared_guide: shared_legend
2851                .as_ref()
2852                .map(|legend| {
2853                    let (x, y) = legend.bounds.anchor();
2854                    legend.legend.select(x, y)
2855                })
2856                .transpose()?,
2857        };
2858        let plan = MeasuredOwnedPlan {
2859            measurement,
2860            size,
2861            frame: canvas_layout.into_shared(),
2862            root_paint: request.surfaces.canvas_root,
2863            content: MeasuredRootContent::Canvas(content),
2864        };
2865        let MeasuredRootContent::Canvas(content) = &plan.content else {
2866            unreachable!("measured Canvas content")
2867        };
2868        Self::observe_arranged(content, round)?;
2869        Ok(FitOutcome::Measured(plan))
2870    }
2871
2872    fn observe_arranged(
2873        content: &OwnedCanvasPlan,
2874        round: &mut crate::layout::kernel::FeedbackRound,
2875    ) -> Result<(), Error> {
2876        let mut geometry = crate::render::geometry::GeometrySnapshot::new();
2877        for panel in &content.text_panels {
2878            geometry.text(panel.title_placement, panel.title.plan(), None)?;
2879            geometry.text(panel.body_placement, panel.body.plan(), None)?;
2880        }
2881        for header in content.grid.row_titles.iter().chain(&content.grid.headers) {
2882            geometry.text(header.text.placement, &header.text.plan, None)?;
2883        }
2884        if let Some(legend) = &content.shared_guide {
2885            legend.geometry(&mut geometry)?;
2886        }
2887        geometry.observe_feedback(round)?;
2888        for panel in &content.plots {
2889            round.observe_box(
2890                content.grid.owners[panel.anchor.0].expect("measured owner assignment"),
2891            )?;
2892            round.observe_box(panel.plot.selected.cell)?;
2893            panel.prose.observe(round)?;
2894
2895            let mut geometry = crate::render::geometry::GeometrySnapshot::new();
2896            panel.prose.geometry(&mut geometry)?;
2897            if let Some((_, legend)) = &panel.legend {
2898                legend.geometry(&mut geometry)?;
2899            }
2900            geometry.observe_feedback(round)?;
2901        }
2902        Ok(())
2903    }
2904
2905    pub(crate) fn render_planned_canvas(
2906        &self,
2907        plan: &MeasuredOwnedPlan,
2908        width: u32,
2909        height: u32,
2910        backend: &mut dyn Backend,
2911    ) -> Result<(), Error> {
2912        backend.draw_surface(
2913            PixelRect::new(0.0, f64::from(width), 0.0, f64::from(height)),
2914            plan.root_paint,
2915            SurfaceRole::CanvasRoot,
2916        )?;
2917        let MeasuredRootContent::Canvas(content) = &plan.content else {
2918            unreachable!("measured Canvas content")
2919        };
2920        for panel in &content.plots {
2921            backend.draw_surface(
2922                panel.plot.panel_box,
2923                panel.plot.surface,
2924                SurfaceRole::PlotPanel,
2925            )?;
2926        }
2927        for panel in &content.plots {
2928            crate::render::backend::with_layer_role(
2929                backend,
2930                &panel.plot.layers.as_ref().expect("Canvas plot layers").grid,
2931                crate::render::backend::LayerRole::Grid,
2932                |backend| {
2933                    panel
2934                        .plot
2935                        .result
2936                        .axes
2937                        .as_ref()
2938                        .ok_or_else(|| {
2939                            Error::Render("Canvas plan is missing immutable axes".into())
2940                        })?
2941                        .draw_grid(backend)
2942                },
2943            )?;
2944        }
2945        for panel in &content.plots {
2946            let plot = self.placements.plot(panel.anchor.0).ok_or_else(|| {
2947                Error::Render("composed canvas panel disappeared during render".into())
2948            })?;
2949            plot.configured_source_rows()?;
2950            crate::layout::interior::InteriorRoute::classify(plot.kind()).validate(plot)?;
2951            panel.plot.result.draw_body(backend)?;
2952            crate::significance::render_selected(&panel.plot.result, backend)?;
2953            with_layer(
2954                backend,
2955                &panel.plot.layers.as_ref().expect("Canvas plot layers").axes,
2956                |backend| {
2957                    panel
2958                        .plot
2959                        .result
2960                        .axes
2961                        .as_ref()
2962                        .ok_or_else(|| {
2963                            Error::Render("Canvas plan is missing immutable axes".into())
2964                        })?
2965                        .draw(backend)
2966                },
2967            )?;
2968            if let Some((layer, legend)) = &panel.legend {
2969                with_layer(backend, layer, |backend| legend.draw(backend))?;
2970            }
2971            with_layer(backend, &panel.prose_layer, |backend| {
2972                panel.prose.draw_retained(backend)
2973            })?;
2974        }
2975        for panel in &content.text_panels {
2976            draw_text_panel(panel, backend)?;
2977        }
2978        if !content.grid.row_titles.is_empty() {
2979            draw_canvas_row_titles(&content.grid.row_titles, backend)?;
2980        }
2981        if !content.grid.headers.is_empty() {
2982            draw_canvas_headers(&content.grid.headers, backend)?;
2983        }
2984        if let Some(legend) = &content.shared_guide {
2985            with_layer(backend, "canvas-shared-legend", |backend| {
2986                legend.draw(backend)
2987            })?;
2988        }
2989        plan.frame.root_text.draw_retained(backend)
2990    }
2991
2992    fn preflight_shared_legend(
2993        &self,
2994        root: &Root<'_>,
2995        measurement: &RootAssignment,
2996        panel: PixelRect,
2997        children: &mut crate::decorations::plan::children::ChildPlans,
2998        round: &crate::layout::kernel::FeedbackRound,
2999    ) -> Result<Vec<Option<Arc<crate::spec::PlotRenderResult>>>, Error> {
3000        let mut probes = Vec::new();
3001        crate::layout::fit::reserve(
3002            &mut probes,
3003            self.placements.len(),
3004            "shared guide body probes",
3005        )?;
3006        probes.resize_with(self.placements.len(), || None);
3007        for GridSlot(index) in &root.canvas_topology().producers {
3008            let index = *index;
3009            let Some(registered) = root.canvas_plot(index) else {
3010                continue;
3011            };
3012            let factory = root.plot_assignment_factory(measurement, &registered.scope.id)?;
3013            let entry = factory.assign(
3014                probe_allocation(
3015                    PlotMeasureDimensions {
3016                        canvas: measurement.measurement_size,
3017                        output_override: Some(measurement.measurement_size),
3018                    },
3019                    panel,
3020                    round,
3021                    &registered.scope.address,
3022                ),
3023                round,
3024                Some(MeasurementPhase::Legend),
3025            )?;
3026            let scope = FitScope::root();
3027            let context = factory.context(&entry, SUPPRESSED_GUIDES, &scope)?;
3028            let result = crate::layout::fit::measured(canvas_probe(
3029                &factory,
3030                &context,
3031                children,
3032                index,
3033                MeasurementPhase::Legend,
3034                round,
3035            ))
3036            .map_err(crate::layout::fit::PlanError::into_error)?;
3037            probes[index] = Some(result);
3038        }
3039        Ok(probes)
3040    }
3041}
3042
3043#[expect(
3044    clippy::too_many_arguments,
3045    reason = "the category probe consumes one existing assigned cell and its exact parent guide operands"
3046)]
3047fn category_probe(
3048    root: &Root<'_>,
3049    measurement: &RootAssignment,
3050    dimensions: PlotMeasureDimensions,
3051    cell: PixelRect,
3052    guides: GuideConsumption<'_>,
3053    children: &mut crate::decorations::plan::children::ChildPlans,
3054    index: usize,
3055    round: &crate::layout::kernel::FeedbackRound,
3056) -> Result<Vec<String>, Error> {
3057    let registered = root.canvas_plot(index).expect("prepared Canvas plot");
3058    if !matches!(
3059        registered.kind(),
3060        PlotKind::HorizontalBar | PlotKind::StackedHorizontalBar
3061    ) {
3062        return Err(Error::Data(
3063            "shared category labels are supported only by horizontal bar families".into(),
3064        ));
3065    }
3066    let factory = root.plot_assignment_factory(measurement, &registered.scope.id)?;
3067    let entry = factory.assign(
3068        probe_allocation(dimensions, cell, round, &registered.scope.address),
3069        round,
3070        Some(MeasurementPhase::Category),
3071    )?;
3072    let scope = FitScope::root();
3073    let context = factory.context(&entry, guides, &scope)?;
3074    plot_category_domain(&factory, &context, children, index, round)
3075}
3076
3077fn probe_allocation(
3078    dimensions: PlotMeasureDimensions,
3079    cell: PixelRect,
3080    round: &crate::layout::kernel::FeedbackRound,
3081    owner: &crate::layout::ComponentAddress,
3082) -> PlotAllocationInputs {
3083    PlotAllocationInputs {
3084        dimensions,
3085        cell,
3086        frame: cell,
3087        body: cell,
3088        axis_label_width: cell.width(),
3089        content_height: false,
3090        fill_content_height: false,
3091        content_preference: None,
3092        insets: ParentInsets::consumed(round, owner),
3093        guide: GuideTrialAssignment {
3094            edge: crate::LegendPosition::Auto,
3095            compact: false,
3096            allocation: None,
3097        },
3098    }
3099}
3100
3101fn canvas_probe(
3102    factory: &PlotMeasureAssignmentFactory<'_, '_>,
3103    context: &PlotMeasureContext<'_, '_>,
3104    children: &mut crate::decorations::plan::children::ChildPlans,
3105    index: usize,
3106    phase: MeasurementPhase,
3107    round: &crate::layout::kernel::FeedbackRound,
3108) -> Result<FitOutcome<Arc<crate::spec::PlotRenderResult>>, Error> {
3109    let owner = crate::layout::ComponentAddress::root().child(
3110        crate::layout::AddressRole::CanvasCell,
3111        u32::try_from(index).map_err(|_| Error::Render("canvas address overflowed".into()))?,
3112    )?;
3113    children.measure(context, &owner, phase, round, || {
3114        crate::layout::fit::outcome(
3115            crate::orchestrator::measure_probe(
3116                factory,
3117                context.assignment.local.clone(),
3118                context.guides,
3119                context.fit_scope,
3120            )
3121            .map(|(_, result)| result),
3122        )
3123    })
3124}
3125
3126fn plot_category_domain(
3127    factory: &PlotMeasureAssignmentFactory<'_, '_>,
3128    context: &PlotMeasureContext<'_, '_>,
3129    children: &mut crate::decorations::plan::children::ChildPlans,
3130    index: usize,
3131    round: &crate::layout::kernel::FeedbackRound,
3132) -> Result<Vec<String>, Error> {
3133    let kind = context.registered.kind();
3134    if !matches!(
3135        kind,
3136        PlotKind::HorizontalBar | PlotKind::StackedHorizontalBar
3137    ) {
3138        return Err(Error::Data(
3139            "shared category labels are supported only by horizontal bar families".into(),
3140        ));
3141    }
3142    let result = crate::layout::fit::measured(canvas_probe(
3143        factory,
3144        context,
3145        children,
3146        index,
3147        MeasurementPhase::Category,
3148        round,
3149    ))
3150    .map_err(crate::layout::fit::PlanError::into_error)?;
3151    if result.y_domain != AxisDomain::Categorical {
3152        return Err(Error::Data(
3153            "shared category labels require a categorical y-axis".into(),
3154        ));
3155    }
3156
3157    match &result.y_tick_keys {
3158        Some(keys) => crate::data::source::collect_source(
3159            keys.iter()
3160                .map(|key| crate::data::source::copy_source_string(key)),
3161        ),
3162        None => crate::data::source::collect_source(
3163            result
3164                .layout
3165                .y_axis
3166                .ticks
3167                .iter()
3168                .map(|tick| crate::data::source::copy_source_string(&tick.label)),
3169        ),
3170    }
3171}
3172
3173fn draw_canvas_headers(
3174    headers: &[CanvasHeaderPlan],
3175    backend: &mut dyn Backend,
3176) -> Result<(), Error> {
3177    if headers.is_empty() {
3178        return Ok(());
3179    }
3180    with_layer(backend, "canvas-shared-headers", |backend| {
3181        for header in headers {
3182            header.text.draw(backend)?;
3183        }
3184        Ok(())
3185    })
3186}
3187
3188fn draw_canvas_row_titles(
3189    titles: &[CanvasHeaderPlan],
3190    backend: &mut dyn Backend,
3191) -> Result<(), Error> {
3192    if titles.is_empty() {
3193        return Ok(());
3194    }
3195    with_layer(backend, "canvas-row-titles", |backend| {
3196        for title in titles {
3197            title.text.draw(backend)?;
3198        }
3199        Ok(())
3200    })
3201}
3202
3203fn draw_text_panel(panel: &TextPanelPlan, backend: &mut dyn Backend) -> Result<(), Error> {
3204    with_layer(backend, &panel.layer, |backend| {
3205        backend.draw_planned_text(panel.title_placement, panel.title.plan())?;
3206        backend.draw_planned_text(panel.body_placement, panel.body.plan())
3207    })
3208}