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