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