Skip to main content

lichtung_plot/
spec.rs

1//! Shared plot specification and render-result types.
2
3use crate::layout::Layout;
4use crate::significance::SignificancePlan;
5use crate::{NumericFormat, NumericValues};
6
7mod bar;
8mod categorical;
9mod estimate;
10mod facet;
11mod output;
12pub(crate) mod ticks;
13
14pub use bar::{
15    BarInput, BarSamples, Bootstrap, ConfidenceInterval, ErrorBar, PercentileInterval,
16    StandardDeviation, StandardError,
17};
18pub(crate) use bar::{BarSource, ConfidenceIntervalAlgorithm, ErrorBarKind};
19pub use categorical::{CategoricalColorMap, CategoryOrder, ValueSort};
20pub use estimate::{
21    AxisScale, Bounds, CoefficientInput, EstimateStatus, InteractionStyle, LinePathStyle,
22    PointShape, QqLine, RegressionBand, SignificanceMarkStyle, TextWeight,
23};
24pub use facet::{FacetScales, FacetSpec};
25pub use output::{PngCompression, PngOptions, PngSizing};
26pub use ticks::{
27    TickContext, TickGeneration, TickPositions, TickRequirement, TickSingleton, TickSpace,
28};
29mod category_labels;
30pub use category_labels::{CategoryLabelSelection, LabelEndpoints};
31
32/// Spacing preset for multiple series within one bar category.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum BarSpacing {
35    /// Keep visible space between series bars inside each category.
36    #[default]
37    Comfort,
38    /// Make series bars within each category touch side-by-side.
39    Compact,
40}
41
42/// Histogram bin-selection strategy.
43#[derive(Debug, Clone, Copy, PartialEq, Default)]
44pub enum HistogramBins {
45    /// Select a width with the Freedman-Diaconis rule, falling back to Sturges.
46    /// Automatic selection is capped at 512 bins; constant data uses one
47    /// centered bin.
48    #[default]
49    Auto,
50    /// Render exactly this many centered equal-width bins, including for
51    /// constant data, up to the safety limit of 1,000,000 bins.
52    Count(usize),
53    /// Render bins with this data-space width, provided the resulting count
54    /// does not exceed the 1,000,000-bin safety limit. Constant data uses one
55    /// bin centered on the value and rejects widths that are not representable.
56    Width(f64),
57}
58
59/// Histogram vertical-axis normalization.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
61pub enum HistogramStat {
62    /// Raw observations per bin.
63    #[default]
64    Count,
65    /// Fraction of all observations per bin.
66    Probability,
67    /// Probability density; bin area integrates to one.
68    Density,
69}
70
71impl HistogramStat {
72    /// Canonical scientific name of the statistic.
73    pub const fn name(self) -> &'static str {
74        match self {
75            Self::Count => "count",
76            Self::Probability => "probability",
77            Self::Density => "density",
78        }
79    }
80}
81
82/// Density-curve source for an opt-in composite over sample-owned histogram input.
83#[derive(Debug, Clone)]
84pub enum HistogramKde {
85    /// Compute a scale-robust Scott-bandwidth Gaussian KDE from the histogram sample.
86    Internal,
87    /// Draw caller-computed aligned x/y columns in supplied order.
88    ///
89    /// ```
90    /// use lichtung_plot::{NumericValues, plots::HistogramKde};
91    ///
92    /// let kde = HistogramKde::Precomputed {
93    ///     x: NumericValues::new("x", [0.0, 1.0]),
94    ///     y: NumericValues::new("density", [0.1, 0.2]),
95    /// };
96    /// # let _ = kde;
97    /// ```
98    Precomputed {
99        /// Strictly increasing x coordinates within the sample-owned bin support.
100        x: NumericValues,
101        /// Nonnegative densities aligned with x.
102        y: NumericValues,
103    },
104}
105
106impl HistogramKde {
107    /// Borrow the original supplied curve columns, if this is a supplied curve.
108    pub const fn get_precomputed(&self) -> Option<(&NumericValues, &NumericValues)> {
109        match self {
110            Self::Internal => None,
111            Self::Precomputed { x, y } => Some((x, y)),
112        }
113    }
114}
115
116impl PartialEq for HistogramKde {
117    fn eq(&self, other: &Self) -> bool {
118        match (self, other) {
119            (Self::Internal, Self::Internal) => true,
120            (
121                Self::Precomputed { x, y },
122                Self::Precomputed {
123                    x: other_x,
124                    y: other_y,
125                },
126            ) => {
127                crate::geometry::numeric_equal(x, other_x)
128                    && crate::geometry::numeric_equal(y, other_y)
129            }
130            _ => false,
131        }
132    }
133}
134
135/// Optional layers composed on a histogram density axis.
136#[derive(Debug, Clone, PartialEq, Default)]
137pub enum HistogramComposite {
138    /// Draw only histogram bars. This is the byte-inert default.
139    #[default]
140    HistogramOnly,
141    /// Draw a thin KDE density curve and one rug mark per source observation.
142    KdeAndRug(HistogramKde),
143}
144
145impl HistogramComposite {
146    pub(crate) const fn is_enabled(&self) -> bool {
147        matches!(self, Self::KdeAndRug(_))
148    }
149}
150
151/// A corner inside one chart's resolved mark panel.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
153pub enum DataAreaCorner {
154    /// Top-left corner.
155    TopLeft,
156    /// Top-right corner.
157    TopRight,
158    /// Bottom-left corner.
159    BottomLeft,
160    /// Bottom-right corner.
161    BottomRight,
162}
163
164/// Caller-owned text block anchored inside a chart panel.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct PlotTextAnnotation {
167    position: crate::text::TextPosition,
168    text: crate::Text,
169}
170
171impl PlotTextAnnotation {
172    /// Construct one validated panel-corner annotation from plain or styled text.
173    ///
174    /// Local appearance replaces the complete panel-text role. Alignment applies
175    /// within the text block; the selected corner continues to place that block.
176    pub fn new(corner: DataAreaCorner, text: impl Into<crate::Text>) -> Result<Self, crate::Error> {
177        Self::at(crate::text::TextPosition::corner(corner), text)
178    }
179
180    /// Attach authored text to independent typed data, panel or figure references.
181    pub fn at(
182        position: crate::text::TextPosition,
183        text: impl Into<crate::Text>,
184    ) -> Result<Self, crate::Error> {
185        let text = text.into();
186        text.required_source("panel text")?;
187        Ok(Self { position, text })
188    }
189
190    /// Semantic reference that owns this annotation's placement.
191    #[must_use]
192    pub const fn position(&self) -> &crate::text::TextPosition {
193        &self.position
194    }
195
196    /// Verbatim caller-owned annotation text.
197    #[must_use]
198    pub fn text(&self) -> &str {
199        self.text.as_str()
200    }
201
202    pub(crate) const fn content(&self) -> &crate::Text {
203        &self.text
204    }
205}
206
207/// Original-observation overlay for boxplots and violin plots.
208///
209/// Visible modes draw one fixed-style point for every observation in the same
210/// strict sample used by the summary. They do not filter, transform, aggregate,
211/// resample, or create a legend identity.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
213pub enum RawOverlay {
214    /// Draw no raw observations. This is the inert default.
215    #[default]
216    Hidden,
217    /// Draw every observation at its exact category or dodge center.
218    Points,
219    /// Deterministically displace every observation from its center using its
220    /// plot-level source-row identity.
221    Jittered,
222}
223
224impl RawOverlay {
225    /// Whether the overlay draws original observations.
226    #[must_use]
227    pub const fn is_visible(self) -> bool {
228        !matches!(self, Self::Hidden)
229    }
230}
231
232/// Coordinate layout for a categorical heatmap grid.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
234pub enum HeatmapLayout {
235    /// Draw every cell in the Cartesian product of observed x and y levels.
236    #[default]
237    Cartesian,
238    /// Draw the lower triangle of one shared family order.
239    LowerTriangle {
240        /// Whether diagonal coordinates are active cells.
241        diagonal: bool,
242    },
243    /// Draw the upper triangle of one shared family order.
244    UpperTriangle {
245        /// Whether diagonal coordinates are active cells.
246        diagonal: bool,
247    },
248}
249
250/// In-cell value-label policy for heatmaps.
251#[derive(Debug, Clone, PartialEq, Eq, Default)]
252pub enum HeatmapAnnotations {
253    /// Draw no values inside cells.
254    #[default]
255    Hidden,
256    /// Draw finite raw values using one complete panel-local numeric format set.
257    Values(NumericFormat),
258}
259
260/// Caller-owned annotation for one fully-null Cartesian heatmap row.
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub struct HeatmapNullRowAnnotation {
263    row_label: String,
264    text: crate::Text,
265}
266
267impl HeatmapNullRowAnnotation {
268    /// Construct an annotation targeting one normalized heatmap y-category.
269    /// Text can replace the complete selected contrast style and line alignment;
270    /// row identity remains a semantic string and is validated independently.
271    pub fn new(
272        row_label: impl Into<String>,
273        text: impl Into<crate::Text>,
274    ) -> Result<Self, crate::Error> {
275        let annotation = Self {
276            row_label: row_label.into(),
277            text: text.into(),
278        };
279        validate_heatmap_annotation_label(&annotation.row_label, "row label")?;
280        annotation
281            .text
282            .required_source("heatmap fully-null row annotation text")?;
283        Ok(annotation)
284    }
285
286    /// Normalized y-category targeted by this annotation.
287    #[must_use]
288    pub fn row_label(&self) -> &str {
289        &self.row_label
290    }
291
292    /// Verbatim text wrapped inside the merged row.
293    #[must_use]
294    pub fn text(&self) -> &str {
295        self.text.as_str()
296    }
297
298    pub(crate) const fn content(&self) -> &crate::Text {
299        &self.text
300    }
301}
302
303fn validate_heatmap_annotation_label(value: &str, role: &str) -> Result<(), crate::Error> {
304    if value.is_empty() || value.trim() != value || value.chars().any(char::is_control) {
305        return Err(crate::Error::Data(format!(
306            "heatmap fully-null row annotation {role} must be nonempty, trimmed, and contain no control characters"
307        ).into()));
308    }
309    Ok(())
310}
311
312/// Explicit endpoint identities and colors for a dumbbell plot.
313///
314/// Each exact Color replaces the entire endpoint fill and its literal guide
315/// paint. Theme marker geometry and the independent outline still apply.
316/// ```
317/// use lichtung_plot::{Color, plots::DumbbellEndpoints};
318/// let endpoints = DumbbellEndpoints::new(
319///     "Before", Color::rgba(20, 80, 140, 128.0 / 255.0)?, "After", Color::rgb(180, 60, 40),
320/// )?;
321/// assert_eq!(endpoints.left_color().get_alpha(), 128.0 / 255.0);
322/// assert_eq!(endpoints.right_color().get_alpha(), 1.0);
323/// # Ok::<(), lichtung_plot::Error>(())
324/// ```
325///
326/// ```compile_fail
327/// use lichtung_plot::plots::DumbbellEndpoints;
328/// let _ = DumbbellEndpoints::new("Before", (20, 80, 140), "After", (180, 60, 40));
329/// ```
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct DumbbellEndpoints {
332    left_label: String,
333    left_color: crate::Color,
334    right_label: String,
335    right_color: crate::Color,
336}
337
338impl DumbbellEndpoints {
339    /// Construct two explicitly labeled and colored endpoint identities.
340    pub fn new(
341        left_label: impl Into<String>,
342        left_color: crate::Color,
343        right_label: impl Into<String>,
344        right_color: crate::Color,
345    ) -> Result<Self, crate::Error> {
346        let endpoints = Self {
347            left_label: left_label.into(),
348            left_color,
349            right_label: right_label.into(),
350            right_color,
351        };
352        if endpoints.left_label.trim().is_empty() || endpoints.right_label.trim().is_empty() {
353            return Err(crate::Error::Data(
354                "dumbbell endpoint labels must not be empty".into(),
355            ));
356        }
357        if endpoints.left_label.trim() != endpoints.left_label
358            || endpoints.right_label.trim() != endpoints.right_label
359            || endpoints.left_label.chars().any(char::is_control)
360            || endpoints.right_label.chars().any(char::is_control)
361        {
362            return Err(crate::Error::Data(
363                "dumbbell endpoint labels must contain no surrounding whitespace or control characters"
364                    .into(),
365            ));
366        }
367        if endpoints.left_label == endpoints.right_label {
368            return Err(crate::Error::Data(
369                "dumbbell endpoint labels must be distinct".into(),
370            ));
371        }
372        Ok(endpoints)
373    }
374
375    /// Verbatim label for the left-value endpoint.
376    #[must_use]
377    pub fn left_label(&self) -> &str {
378        &self.left_label
379    }
380
381    /// Complete exact RGBA paint for the left-value endpoint and its guide key.
382    #[must_use]
383    pub const fn left_color(&self) -> crate::Color {
384        self.left_color
385    }
386
387    /// Verbatim label for the right-value endpoint.
388    #[must_use]
389    pub fn right_label(&self) -> &str {
390        &self.right_label
391    }
392
393    /// Complete exact RGBA paint for the right-value endpoint and its guide key.
394    #[must_use]
395    pub const fn right_color(&self) -> crate::Color {
396        self.right_color
397    }
398}
399
400/// Caller-owned labels for waterfall base and terminal annotations.
401#[derive(Debug, Clone, PartialEq, Eq)]
402pub struct WaterfallLabels {
403    base: crate::Text,
404    terminal: crate::Text,
405}
406
407impl WaterfallLabels {
408    /// Construct verbatim display labels for the base and terminal values.
409    /// Each Text retains independent complete appearance and line alignment for
410    /// the displayed name plus formatted numeric value. Readers borrow the name.
411    pub fn new(
412        base: impl Into<crate::Text>,
413        terminal: impl Into<crate::Text>,
414    ) -> Result<Self, crate::Error> {
415        let labels = Self {
416            base: base.into(),
417            terminal: terminal.into(),
418        };
419        labels.base.required_source("waterfall base label")?;
420        labels
421            .terminal
422            .required_source("waterfall terminal label")?;
423        Ok(labels)
424    }
425
426    /// Verbatim label for the base or expected output.
427    #[must_use]
428    pub fn base(&self) -> &str {
429        self.base.as_str()
430    }
431
432    /// Verbatim label for the terminal value or final prediction.
433    #[must_use]
434    pub fn terminal(&self) -> &str {
435        self.terminal.as_str()
436    }
437
438    pub(crate) const fn contents(&self) -> [&crate::Text; 2] {
439        [&self.base, &self.terminal]
440    }
441}
442
443/// Legend policy for a heterogeneous composed canvas.
444#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
445pub enum CanvasLegendPolicy {
446    /// Render each panel's own legend.
447    #[default]
448    PerPlot,
449    /// Render one legend after validating that panel legends are compatible.
450    Shared,
451    /// Suppress all panel legends.
452    Hidden,
453}
454
455/// Semantic composition of one discrete legend, independently of its appearance.
456///
457/// Standalone plots and facets use their Plot's selection. Canvas PerPlot uses
458/// each Plot's selection; Shared uses the Canvas selection for every contributor
459/// without changing the stored Plot values. Hidden skips guide-only composition.
460/// Continuous color guides keep their own representation.
461#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
462pub enum LegendComposition {
463    /// Preserve observed identities and complete mark keys in one section.
464    #[default]
465    Combined,
466    /// Explain independent mapped channels in ordered sections within one frame.
467    ///
468    /// Independent group/hue pairs require an explicitly configured group-style
469    /// channel, currently Interaction styles. Unsupported decompositions refuse
470    /// before fonts. Same-field channels remain one complete joint section.
471    Separate,
472}
473
474/// Requested legend placement.
475///
476/// Inside positions are limited to plot edges so layout can reserve data space
477/// without placing the legend in the middle of the main graphic.
478#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
479pub enum LegendPosition {
480    /// Use the plot-type default placement.
481    #[default]
482    Auto,
483    /// Inside the axes at the top-left edge.
484    InsideTopLeft,
485    /// Inside the axes at the top edge.
486    InsideTop,
487    /// Inside the axes at the top-right edge.
488    InsideTopRight,
489    /// Inside the axes at the right-top edge.
490    InsideRightTop,
491    /// Inside the axes at the right edge.
492    InsideRight,
493    /// Inside the axes at the right-bottom edge.
494    InsideRightBottom,
495    /// Inside the axes at the bottom-left edge.
496    InsideBottomLeft,
497    /// Inside the axes at the bottom edge.
498    InsideBottom,
499    /// Inside the axes at the bottom-right edge.
500    InsideBottomRight,
501    /// Inside the axes at the left-top edge.
502    InsideLeftTop,
503    /// Inside the axes at the left edge.
504    InsideLeft,
505    /// Inside the axes at the left-bottom edge.
506    InsideLeftBottom,
507    /// Outside the axes in right-side whitespace, aligned to panel top.
508    OutsideRightTop,
509    /// Outside the axes in right-side whitespace, aligned to panel center.
510    OutsideRight,
511    /// Outside the axes in right-side whitespace, aligned to panel bottom.
512    OutsideRightBottom,
513    /// Outside the axes in top whitespace, aligned to panel left.
514    OutsideTopLeft,
515    /// Outside the axes in top whitespace, aligned to panel center.
516    OutsideTop,
517    /// Outside the axes in top whitespace, aligned to panel right.
518    OutsideTopRight,
519    /// Outside the axes in bottom whitespace, aligned to panel left.
520    OutsideBottomLeft,
521    /// Outside the axes in bottom whitespace, aligned to panel center.
522    OutsideBottom,
523    /// Outside the axes in bottom whitespace, aligned to panel right.
524    OutsideBottomRight,
525    /// Outside the axes in left-side whitespace, aligned to panel top.
526    OutsideLeftTop,
527    /// Outside the axes in left-side whitespace, aligned to panel center.
528    OutsideLeft,
529    /// Outside the axes in left-side whitespace, aligned to panel bottom.
530    OutsideLeftBottom,
531}
532
533/// Visibility and placement policy for a plot legend.
534#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
535pub enum LegendPolicy {
536    /// Use the plot-type default visibility and automatic placement.
537    #[default]
538    Automatic,
539    /// Do not draw a legend.
540    Hidden,
541    /// Draw the legend at the requested placement.
542    Visible(LegendPosition),
543}
544
545impl LegendPolicy {
546    pub(crate) const fn position(self) -> LegendPosition {
547        match self {
548            Self::Visible(position) => position,
549            Self::Automatic | Self::Hidden => LegendPosition::Auto,
550        }
551    }
552}
553
554macro_rules! define_plot_kinds {
555    ($($variant:ident => $documentation:literal),+ $(,)?) => {
556        /// Which plot type a [`crate::Plot`] will produce.
557        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
558        #[non_exhaustive]
559        pub enum PlotKind {
560            $(
561                #[doc = $documentation]
562                $variant,
563            )+
564        }
565    };
566}
567
568define_plot_kinds! {
569    Scatter => "Scatter plot.",
570    Histogram => "Single-series numeric histogram with an optional KDE-and-rug density composite.",
571    Density => "Gaussian kernel density estimate.",
572    Qq => "Quantile-quantile plot against a standard normal distribution.",
573    PointInterval => "Point estimates with explicit lower and upper interval bounds.",
574    Line => "Grouped ordered numeric series with optional precomputed ribbons.",
575    Trajectory => "Explicit-group repeated trajectories with neutral connectors.",
576    LinePath => "Numeric paths in source-row order with optional group keys.",
577    Interaction => "Precomputed interaction profiles with explicit bounds and optional closed trace styles.",
578    Coefficient => "Named model coefficients with optional drawable bounds.",
579    Forest => "Complete interval estimates with an explicit scientific null.",
580    Dumbbell => "Horizontal paired endpoint estimates with optional replicate identity.",
581    Heatmap => "Categorical grid with a continuous numeric fill.",
582    Bar => "Bar plot with CI error bars.",
583    HorizontalBar => "Horizontal bar plot.",
584    StackedBar => "Stacked vertical bar plot using one categorical series.",
585    StackedHorizontalBar => "Stacked horizontal bar plot using one categorical series.",
586    Boxplot => "Box-and-whisker plot.",
587    Violin => "Mirrored KDE violins with centered inner summaries.",
588    Raincloud => "One-sided KDE clouds with separated summaries and complete observation strips.",
589    Regression => "Regression plot (scatter + fit line).",
590    Marginal => "Marginal plot (marginal histograms + central scatter).",
591    Matrix => "Scatter matrix (small multiples).",
592    Beeswarm => "Categorical rows of collision-separated points with continuous x and color values.",
593    Waterfall => "Cumulative signed deltas between a base and terminal value.",
594}
595
596impl PlotKind {
597    /// The canonical name of the actual plot family.
598    pub const fn name(self) -> &'static str {
599        match self {
600            Self::Scatter => "scatter",
601            Self::Histogram => "histogram",
602            Self::Density => "density",
603            Self::Qq => "qq",
604            Self::PointInterval => "point_interval",
605            Self::Line => "line",
606            Self::Trajectory => "trajectory",
607            Self::LinePath => "line_path",
608            Self::Interaction => "interaction",
609            Self::Coefficient => "coefficient",
610            Self::Forest => "forest",
611            Self::Dumbbell => "dumbbell",
612            Self::Heatmap => "heatmap",
613            Self::Bar => "bar",
614            Self::HorizontalBar => "horizontal_bar",
615            Self::StackedBar => "stacked_bar",
616            Self::StackedHorizontalBar => "stacked_horizontal_bar",
617            Self::Boxplot => "boxplot",
618            Self::Violin => "violin",
619            Self::Raincloud => "raincloud",
620            Self::Regression => "regression",
621            Self::Marginal => "marginal",
622            Self::Matrix => "matrix",
623            Self::Beeswarm => "beeswarm",
624            Self::Waterfall => "waterfall",
625        }
626    }
627
628    pub(crate) const fn uses_unified_series(self) -> bool {
629        matches!(
630            self,
631            Self::Bar
632                | Self::HorizontalBar
633                | Self::StackedBar
634                | Self::StackedHorizontalBar
635                | Self::Boxplot
636                | Self::Violin
637                | Self::Raincloud
638        )
639    }
640
641    pub(crate) const fn supports_significance_annotations(self) -> bool {
642        matches!(
643            self,
644            Self::Bar
645                | Self::HorizontalBar
646                | Self::StackedBar
647                | Self::StackedHorizontalBar
648                | Self::Boxplot
649                | Self::Violin
650                | Self::Raincloud
651                | Self::Coefficient
652        )
653    }
654
655    pub(crate) const fn legend_default(self, explicit_y_limits: bool) -> LegendDefault {
656        match self {
657            Self::HorizontalBar | Self::StackedHorizontalBar | Self::Dumbbell => {
658                LegendDefault::TopRight(LegendClearance::HorizontalMaximum)
659            }
660            Self::Bar
661            | Self::StackedBar
662            | Self::Line
663            | Self::Trajectory
664            | Self::LinePath
665            | Self::Interaction
666            | Self::Boxplot
667            | Self::Violin
668            | Self::Raincloud
669            | Self::Regression => LegendDefault::TopRight(LegendClearance::VerticalMaximum),
670            Self::Scatter | Self::Marginal if !explicit_y_limits => {
671                LegendDefault::TopRight(LegendClearance::VerticalMaximum)
672            }
673            Self::Matrix => LegendDefault::SelfManaged,
674            _ => LegendDefault::LowestOverlap,
675        }
676    }
677}
678
679#[derive(Debug, Clone, Copy, PartialEq, Eq)]
680pub(crate) enum LegendDefault {
681    LowestOverlap,
682    TopRight(LegendClearance),
683    SelfManaged,
684}
685
686#[derive(Debug, Clone, Copy, PartialEq, Eq)]
687pub(crate) enum LegendClearance {
688    HorizontalMaximum,
689    VerticalMaximum,
690}
691
692use crate::Error;
693
694/// A short borrow of one root-issued allocation and its canonical occurrence.
695/// Geometry, domains and dimensions have exactly one owner: the allocation.
696pub(crate) struct PlotMeasureContext<'v, 'src> {
697    pub(crate) registered: &'v crate::orchestrator::registration::PlotRegistration<'src>,
698    pub(crate) assignment: crate::orchestrator::assignment::RootPlotAssignmentRef<'v>,
699    pub(crate) canvas: Option<&'src crate::Canvas>,
700    pub(crate) text: &'v crate::text::TextService,
701    pub(crate) operation: &'v crate::font::canonical::OperationContext,
702    pub(crate) intrinsic: &'v crate::orchestrator::root::PlotIntrinsics,
703    pub(crate) guides: crate::decorations::legend::discrete::scoped::GuideConsumption<'v>,
704    pub(crate) fit_scope: &'v crate::layout::fit::FitScope,
705}
706
707impl<'v, 'src> PlotMeasureContext<'v, 'src> {
708    pub(crate) const fn fit_scope(&self) -> &'v crate::layout::fit::FitScope {
709        self.fit_scope
710    }
711
712    pub(crate) const fn intrinsic(&self) -> &'v crate::orchestrator::root::PlotIntrinsics {
713        self.intrinsic
714    }
715
716    pub(crate) fn family(&self) -> Result<crate::orchestrator::registration::FamilyRef<'v>, Error> {
717        crate::layout::interior::InteriorRoute::classify(self.registered.family.kind())
718            .validate(self.registered.source)?;
719        self.registered.family()
720    }
721
722    #[expect(
723        clippy::unnecessary_wraps,
724        reason = "the fixed fallible axis-pair interface projects prepared operands without adding validation"
725    )]
726    pub(crate) fn axis_pair(
727        &self,
728        scope: crate::orchestrator::assignment::AxisPairScope,
729    ) -> Result<crate::orchestrator::assignment::AxisPairRef<'v>, Error> {
730        use crate::layout::AxisSide::{Bottom, Left};
731        use crate::orchestrator::assignment::{AssignedAxisRef, AxisDomainAssignments as D};
732        use crate::orchestrator::assignment::{AxisPairRef, AxisPairScope as S};
733        use crate::orchestrator::registration::{AxisSlot as A, MarginalStrip};
734        let axes = &self.registered.axes;
735        let source = self.registered.source;
736        let pair = match (scope, &self.assignment.local.domains) {
737            (S::Pair, D::Pair(domains)) => {
738                [(A::Pair(Bottom), &domains[0]), (A::Pair(Left), &domains[1])]
739            }
740            (S::MarginalCentral, D::Marginal { central, .. }) => [
741                (A::MarginalCentral(Bottom), &central[0]),
742                (A::MarginalCentral(Left), &central[1]),
743            ],
744            (
745                S::MarginalTop,
746                D::Marginal {
747                    central,
748                    strip_density,
749                },
750            ) => [
751                (A::MarginalCentral(Bottom), &central[0]),
752                (
753                    A::MarginalStripDensity(MarginalStrip::Top),
754                    &strip_density[0],
755                ),
756            ],
757            (
758                S::MarginalRight,
759                D::Marginal {
760                    central,
761                    strip_density,
762                },
763            ) => [
764                (
765                    A::MarginalStripDensity(MarginalStrip::Right),
766                    &strip_density[1],
767                ),
768                (A::MarginalCentral(Left), &central[1]),
769            ],
770            (S::MatrixCell { row, column }, D::Matrix { variables, .. }) => [
771                (A::MatrixVariable(column), &variables[column]),
772                (A::MatrixVariable(row), &variables[row]),
773            ],
774            (
775                S::MatrixDiagonalDensity { variable },
776                D::Matrix {
777                    variables,
778                    diagonal_density,
779                },
780            ) => [
781                (A::MatrixVariable(variable), &variables[variable]),
782                (
783                    A::MatrixDiagonalDensity(variable),
784                    &diagonal_density[variable],
785                ),
786            ],
787            _ => unreachable!("axis pair belongs to the selected interior route"),
788        };
789        Ok(AxisPairRef {
790            axes: pair.map(|(slot, domain)| AssignedAxisRef {
791                base: axes.axis_at(source, slot),
792                domain,
793            }),
794        })
795    }
796
797    pub(crate) fn data(&self) -> Result<crate::data::PlotData<'src, 'v>, Error> {
798        self.registered.data(self.operation)
799    }
800
801    pub(crate) fn request(&self) -> crate::text::TextRequestContext<'v, 'src> {
802        crate::text::TextRequestContext::new(&self.registered.appearance, self.text)
803    }
804
805    #[expect(
806        clippy::unnecessary_wraps,
807        reason = "native measurements share the existing fallible range-reader interface"
808    )]
809    pub(crate) fn axis_range(&self, side: crate::layout::AxisSide) -> Result<(f64, f64), Error> {
810        use crate::orchestrator::assignment::AxisDomainAssignments;
811        let index = usize::from(side == crate::layout::AxisSide::Left);
812        let pair = match &self.assignment.local.domains {
813            AxisDomainAssignments::Pair(pair) => pair,
814            AxisDomainAssignments::Marginal { central, .. } => central,
815            AxisDomainAssignments::Matrix { .. } => {
816                unreachable!("Matrix selects an indexed axis pair")
817            }
818        };
819        Ok(pair[index].extent.pair())
820    }
821
822    pub(crate) fn prepared_category_labels(
823        &self,
824        side: usize,
825    ) -> Option<&'v [crate::layout::AxisTick]> {
826        Some(&self.registered.axes.coordinate()?.categories(side)?.ticks)
827    }
828
829    pub(crate) fn semantic_inputs(
830        &self,
831        scope: crate::orchestrator::assignment::AxisPairScope,
832    ) -> Result<[crate::layout::AxisSemanticInputs; 2], Error> {
833        use crate::orchestrator::assignment::AssignedAxisRef;
834
835        let mut inputs = self
836            .axis_pair(scope)?
837            .axes
838            .map(AssignedAxisRef::semantic_inputs);
839        for (side, input) in inputs.iter_mut().enumerate() {
840            input
841                .text_layout
842                .clone_from(&self.registered.appearance.text_layouts.ticks[side]);
843        }
844        Ok(inputs)
845    }
846}
847
848/// Current constrained interior result. FitOutcome/PlanError distinguish measured,
849/// terminal fit and fatal outcomes; provisional misses belong to FeedbackRound.
850/// Point/path families retain selected marks and annotations; other marks remain combined.
851#[derive(Debug)]
852pub(crate) struct PlotRenderResult {
853    pub(crate) layout: Layout,
854    pub(crate) axes: Option<crate::layout::AxisSystemPlan>,
855    pub(crate) grid_axis_gutters: Option<[f64; 4]>,
856    pub(crate) x_domain: AxisDomain,
857    pub(crate) y_domain: AxisDomain,
858    pub(crate) significance: Option<SignificancePlan>,
859    pub(crate) discrete_guide:
860        Option<std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
861    pub(crate) decoration_mode: DecorationMode,
862    pub(crate) x_tick_keys: Option<Vec<String>>,
863    pub(crate) y_tick_keys: Option<Vec<String>>,
864    pub(crate) deferred_annotation_text: Vec<crate::layout::DeferredAnnotationTextPlan>,
865    pub(crate) producer_text: Vec<crate::render::backend::PlacedText>,
866    pub(crate) panel_text: Vec<crate::decorations::panel_text::PlotTextAnnotationPlan>,
867    pub(crate) self_managed_legend: Option<std::sync::Arc<crate::decorations::legend::Legend>>,
868    pub(crate) matrix_axes: Option<std::sync::Arc<crate::plots::matrix::MatrixAxisPlan>>,
869    pub(crate) marks: Option<std::sync::Arc<crate::layout::interior::SelectedMarkPlan>>,
870    pub(crate) annotations: Option<std::sync::Arc<crate::layout::interior::SelectedAnnotationPlan>>,
871    pub(crate) numeric_presentation:
872        Option<std::sync::Arc<crate::numeric::set::NumericPresentation>>,
873}
874
875/// Semantic kind of one renderer-resolved axis domain.
876#[derive(Debug, Clone, Copy, PartialEq, Eq)]
877pub(crate) enum AxisDomain {
878    Continuous,
879    Categorical,
880}
881
882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
883pub(crate) enum DecorationMode {
884    Standard,
885    SelfManaged,
886}
887
888impl PlotRenderResult {
889    pub(crate) fn draw_body(
890        &self,
891        backend: &mut dyn crate::render::backend::Backend,
892    ) -> Result<DecorationMode, Error> {
893        self.marks
894            .as_ref()
895            .ok_or_else(|| Error::Render("selected mark payload is missing".into()))?
896            .draw(backend)?;
897        self.annotations
898            .as_ref()
899            .ok_or_else(|| Error::Render("selected annotation payload is missing".into()))?
900            .draw(backend)?;
901        Ok(self.decoration_mode)
902    }
903
904    pub(crate) fn new(
905        layout: Layout,
906        discrete_guide: Option<std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
907    ) -> Self {
908        Self {
909            layout,
910            axes: None,
911            grid_axis_gutters: None,
912            x_domain: AxisDomain::Continuous,
913            y_domain: AxisDomain::Continuous,
914            significance: None,
915            discrete_guide,
916            decoration_mode: DecorationMode::Standard,
917            x_tick_keys: None,
918            y_tick_keys: None,
919            deferred_annotation_text: Vec::new(),
920            producer_text: Vec::new(),
921            panel_text: Vec::new(),
922            self_managed_legend: None,
923            matrix_axes: None,
924            marks: None,
925            annotations: None,
926            numeric_presentation: None,
927        }
928    }
929
930    pub(crate) fn with_self_managed_decorations(mut self) -> Self {
931        self.decoration_mode = DecorationMode::SelfManaged;
932        self
933    }
934
935    pub(crate) fn with_resolved_axis_keys(
936        mut self,
937        x_keys: Vec<String>,
938        y_keys: Vec<String>,
939    ) -> Self {
940        self.x_tick_keys = Some(x_keys);
941        self.y_tick_keys = Some(y_keys);
942        self
943    }
944}