Skip to main content

lichtung_plot/builder/
facets.rs

1use super::{ComposedInputs, Plot, PlotDescription};
2use crate::data::category::CategoryOrderRef;
3use crate::data::{FACET_COLUMN, FACET_ROW, FACET_WRAP};
4use crate::decorations::legend::discrete::scoped::ScopedGuideInputs;
5use crate::decorations::plan::children::MeasurementPhase;
6use crate::layout::kernel::{FeedbackKind, FeedbackRound};
7use crate::layout::{AddressRole, RangeProvenance};
8use crate::orchestrator::assignment::AxisDomainAssignments;
9use crate::spec::{AxisScale, FacetScales, FacetSpec, PlotKind, PlotMeasureContext};
10
11#[cfg(test)]
12mod generation_tests;
13
14impl<K: crate::kind::Marker> Plot<K> {
15    /// Apply one complete generic-facet layout.
16    #[must_use]
17    pub fn facet(mut self, facet: FacetSpec) -> Self
18    where
19        K: crate::kind::Facet,
20    {
21        self.description.payload_mut().facet = Some(facet);
22        self
23    }
24}
25
26impl PlotDescription {
27    pub(crate) fn facet_spec(&self) -> Option<&FacetSpec> {
28        self.payload.facet.as_ref()
29    }
30
31    pub(crate) fn facet_scales_spec(&self) -> FacetScales {
32        self.payload
33            .facet
34            .as_ref()
35            .map_or(FacetScales::Fixed, FacetSpec::scale_policy)
36    }
37
38    pub(crate) fn facet_columns(
39        &self,
40    ) -> (
41        Option<&'static str>,
42        Option<&'static str>,
43        Option<&'static str>,
44        Option<usize>,
45    ) {
46        (
47            self.payload
48                .facet
49                .as_ref()
50                .and_then(FacetSpec::row_values)
51                .map(|_| FACET_ROW),
52            self.payload
53                .facet
54                .as_ref()
55                .and_then(FacetSpec::column_values)
56                .map(|_| FACET_COLUMN),
57            self.payload
58                .facet
59                .as_ref()
60                .and_then(FacetSpec::wrap_values)
61                .map(|_| FACET_WRAP),
62            self.payload
63                .facet
64                .as_ref()
65                .and_then(FacetSpec::wrap_columns),
66        )
67    }
68
69    pub(crate) fn has_facets(&self) -> bool {
70        self.payload.facet.is_some()
71    }
72}
73
74fn same_values<T: PartialEq>(a: Option<&[T]>, b: Option<&[T]>) -> bool {
75    match (a, b) {
76        (None, None) => true,
77        (Some(a), Some(b)) if a.len() == b.len() => a.iter().zip(b).all(|(a, b)| a == b),
78        _ => false,
79    }
80}
81
82fn same_order(order: Option<CategoryOrderRef<'_>>, values: Option<&[String]>) -> bool {
83    match (order, values) {
84        (None, None) => true,
85        (Some(order), Some(values)) if order.len() == values.len() => {
86            order.values().zip(values).all(|(a, b)| a == b)
87        }
88        _ => false,
89    }
90}
91
92/// Recover the old working-window snapshot, not merely its selected display
93/// extent. Forest's resolved-x override deliberately remains a separate value.
94#[expect(
95    clippy::type_complexity,
96    reason = "three original narrow snapshot operands, without another owner"
97)]
98fn working_axes(
99    context: &PlotMeasureContext<'_, '_>,
100    round: &FeedbackRound,
101    measurement_phase: Option<MeasurementPhase>,
102) -> (
103    [Option<(f64, f64)>; 2],
104    [RangeProvenance; 2],
105    Option<(f64, f64)>,
106) {
107    let registered = context.registered;
108    let source = registered.source;
109    let authored = [source.x_axis_spec(), source.y_axis_spec()];
110    let mut windows = authored.map(|axis| axis.window.map(crate::layout::RawWindow::pair));
111    let mut provenance = authored.map(|axis| {
112        if axis.window.is_some() {
113            RangeProvenance::Configured
114        } else {
115            RangeProvenance::Automatic
116        }
117    });
118    let mut resolved_x = None;
119    let forest = source.kind() == PlotKind::Forest && source.axis_scale_spec() == AxisScale::Log10;
120    if let Some(scales) = registered.policy.facet_scales {
121        if context.fit_scope.address.leaf_role() != AddressRole::FacetCell {
122            return (windows, provenance, resolved_x);
123        }
124        for (side, kind) in [
125            FeedbackKind::AutomaticDomainX,
126            FeedbackKind::AutomaticDomainY,
127        ]
128        .into_iter()
129        .enumerate()
130        {
131            let fixed = matches!(scales, FacetScales::Fixed)
132                || side == 0 && scales == FacetScales::FreeY
133                || side == 1 && scales == FacetScales::FreeX;
134            if fixed && registered.axes.categories(side).is_none() {
135                let shared = registered.axes.sources()[side]
136                    .base_seed
137                    .expect("prepared shared facet seed")
138                    .pair();
139                if authored[side].window.is_none() {
140                    provenance[side] = RangeProvenance::Shared;
141                }
142                if side == 0 && forest {
143                    resolved_x = Some(shared);
144                } else {
145                    windows[side] = Some(shared);
146                }
147            }
148            let feedback = if fixed {
149                round.facet_feedback_domain(kind)
150            } else {
151                round.feedback_domain(&registered.scope.address, kind)
152            };
153            if let Some(range) = feedback {
154                windows[side] = Some(range);
155            }
156        }
157    } else if let Some(canvas) = context.canvas {
158        let initial = measurement_phase == Some(MeasurementPhase::Legend);
159        let grouped = canvas.range_group_contains(
160            usize::try_from(registered.scope.address.leaf_slot_index())
161                .expect("Canvas slot fits usize"),
162        );
163        let pair = match &context.assignment.local.domains {
164            AxisDomainAssignments::Pair(pair) => pair,
165            AxisDomainAssignments::Marginal { central, .. } => central,
166            AxisDomainAssignments::Matrix { .. } => return (windows, provenance, resolved_x),
167        };
168        if grouped {
169            let shared = if initial {
170                registered.axes.sources()[0]
171                    .base_seed
172                    .expect("prepared shared Canvas seed")
173                    .pair()
174            } else {
175                pair[0].extent.pair()
176            };
177            if authored[0].window.is_none() {
178                provenance[0] = RangeProvenance::Shared;
179            }
180            if forest {
181                resolved_x = Some(shared);
182            } else {
183                windows[0] = Some(shared);
184            }
185        }
186        if initial {
187            return (windows, provenance, resolved_x);
188        }
189        if !grouped {
190            if let Some(range) =
191                round.feedback_domain(&registered.scope.address, FeedbackKind::AutomaticDomainX)
192            {
193                windows[0] = Some(range);
194            }
195        }
196        if let Some(range) =
197            round.feedback_domain(&registered.scope.address, FeedbackKind::AutomaticDomainY)
198        {
199            windows[1] = Some(range);
200        }
201    }
202    (windows, provenance, resolved_x)
203}
204
205impl ComposedInputs {
206    /// Compare only the original computed inputs of a root-local child owner.
207    pub(crate) fn matches(
208        &self,
209        context: &PlotMeasureContext<'_, '_>,
210        round: &FeedbackRound,
211        guides: &ScopedGuideInputs,
212        measurement_phase: Option<MeasurementPhase>,
213    ) -> bool {
214        let registration = context.registered;
215        let registered = Some(registration);
216        let source = registration.source;
217        let (windows, provenance, resolved_x) = working_axes(context, round, measurement_phase);
218        for (side, other) in [&self.x_axis_spec, &self.y_axis_spec]
219            .into_iter()
220            .enumerate()
221        {
222            let axis = &source.payload.axes[side];
223            if windows[side] != other.0
224                || provenance[side] != other.1
225                || axis.generation != other.2
226                || !same_values(axis.exact_ticks.as_deref(), other.5.as_deref())
227            {
228                return false;
229            }
230        }
231        let range = |value: Option<(f64, f64)>| value.map(|(a, b)| (a.to_bits(), b.to_bits()));
232        source.same_prose(&self.prose)
233            && source.same_axis_titles(&self.axis_titles)
234            && range(windows[0]) == range(self.x_axis_spec.0)
235            && range(windows[1]) == range(self.y_axis_spec.0)
236            && range(resolved_x) == range(self.resolved_facet_x_range)
237            && same_order(
238                crate::orchestrator::registration::parent_hues(registered)
239                    .map(CategoryOrderRef::Keys),
240                self.global_hue_levels.as_deref(),
241            )
242            && same_order(
243                crate::orchestrator::registration::composed_group_levels(registered),
244                self.global_group_levels.as_deref(),
245            )
246            && same_values(
247                crate::orchestrator::registration::collective_pairs(registered),
248                self.global_collective_pairs.as_deref(),
249            )
250            && same_values(
251                crate::orchestrator::registration::line_condition_levels(registered),
252                self.global_line_condition_levels.as_deref(),
253            )
254            && registration.policy.gutter_owner == self.axis_gutter_owner
255            && registration.policy.axis_text.tick_labels[1] == self.y_tick_labels_visible
256            && registration.scope.render_name.as_deref() == self.render_scope.as_deref()
257            && crate::orchestrator::registration::legend_policy(source, registered)
258                == self.legend_policy
259            && crate::orchestrator::registration::continuous_guide_suppressed(registered)
260                == self.suppress_continuous_guide
261            && context
262                .assignment
263                .local
264                .dimensions
265                .canvas
266                .dimensions()
267                .is_ok_and(|(width, height)| {
268                    self.root_size == crate::layout::RootRequest::ExactSize { width, height }
269                })
270            && self.numeric.matches(registration, context.canvas)
271            && source.payload.alpha == self.alpha
272            && source.payload.text_layouts == self.text_layouts
273            && context
274                .assignment
275                .local
276                .dimensions
277                .output_override
278                .map(|size| size.dimensions().expect("assigned output dimensions"))
279                == self.output_dimensions
280            && guides.matches_source(registration)
281            && *guides == self.guides
282    }
283
284    #[expect(
285        clippy::too_many_lines,
286        reason = "original narrow copies retain their fallible order"
287    )]
288    pub(crate) fn retain(
289        context: &PlotMeasureContext<'_, '_>,
290        round: &FeedbackRound,
291        guides: ScopedGuideInputs,
292        measurement_phase: Option<MeasurementPhase>,
293    ) -> Result<Self, crate::Error> {
294        let registration = context.registered;
295        let registered = Some(registration);
296        let source = registration.source;
297        if !guides.matches_source(registration) {
298            return Err(crate::Error::Render(
299                "retained guide inputs do not belong to their computed source".into(),
300            ));
301        }
302        let copy = |source: &str| -> Result<String, crate::Error> {
303            let mut value = String::new();
304            value
305                .try_reserve_exact(source.len())
306                .map_err(|error| crate::Error::Render(error.to_string()))?;
307            value.push_str(source);
308            Ok(value)
309        };
310        let (windows, provenance, resolved_x) = working_axes(context, round, measurement_phase);
311        let mut axes = std::array::from_fn::<_, 2, _>(|_| {
312            (
313                None,
314                RangeProvenance::Automatic,
315                crate::TickGeneration::automatic(),
316                crate::CategoryLabelSelection::all(),
317                None,
318                None,
319            )
320        });
321        for (side, (target, axis)) in axes.iter_mut().zip(&source.payload.axes).enumerate() {
322            target.0 = windows[side];
323            target.1 = provenance[side];
324            target.2.clone_from(&axis.generation);
325            target.3.clone_from(&axis.category_labels);
326            target.4.clone_from(&axis.format);
327            if let Some(ticks) = &axis.exact_ticks {
328                let mut retained = Vec::new();
329                crate::render::backend::reserve_text_records(&mut retained, ticks.len())?;
330                for tick in ticks {
331                    retained.push(crate::AxisTick {
332                        position: tick.position,
333                        label: copy(&tick.label)?,
334                    });
335                }
336                target.5 = Some(retained);
337            }
338        }
339        let mut levels = [None, None, None];
340        for (target, source) in levels.iter_mut().zip([
341            crate::orchestrator::registration::parent_hues(registered).map(CategoryOrderRef::Keys),
342            crate::orchestrator::registration::composed_group_levels(registered),
343            crate::orchestrator::registration::line_condition_levels(registered)
344                .map(CategoryOrderRef::Raw),
345        ]) {
346            if let Some(source) = source {
347                let mut retained = Vec::new();
348                crate::render::backend::reserve_text_records(&mut retained, source.len())?;
349                for value in source.values() {
350                    retained.push(copy(value)?);
351                }
352                *target = Some(retained);
353            }
354        }
355        let pairs =
356            if let Some(source) = crate::orchestrator::registration::collective_pairs(registered) {
357                let mut retained = Vec::new();
358                crate::render::backend::reserve_text_records(&mut retained, source.len())?;
359                for pair in source {
360                    retained.push(crate::data::CollectivePair {
361                        group: pair.group.as_deref().map(&copy).transpose()?,
362                        hue: pair.hue.as_deref().map(&copy).transpose()?,
363                    });
364                }
365                Some(retained)
366            } else {
367                None
368            };
369        let [x_axis_spec, y_axis_spec] = axes;
370        let [global_hue_levels, global_group_levels, global_line_condition_levels] = levels;
371        let dimensions = context.assignment.local.dimensions;
372        let (width, height) = dimensions
373            .canvas
374            .dimensions()
375            .expect("assigned canvas dimensions");
376        Ok(Self {
377            text_layouts: source.payload.text_layouts.clone(),
378            output_dimensions: dimensions
379                .output_override
380                .map(|size| size.dimensions().expect("assigned output dimensions")),
381            prose: source.copy_prose()?,
382            axis_titles: source.copy_axis_titles()?,
383            x_axis_spec,
384            y_axis_spec,
385            global_hue_levels,
386            global_group_levels,
387            global_line_condition_levels,
388            global_collective_pairs: pairs,
389            resolved_facet_x_range: resolved_x,
390            axis_gutter_owner: registration.policy.gutter_owner,
391            y_tick_labels_visible: registration.policy.axis_text.tick_labels[1],
392            render_scope: registration
393                .scope
394                .render_name
395                .as_deref()
396                .map(copy)
397                .transpose()?,
398            legend_policy: crate::orchestrator::registration::legend_policy(source, registered),
399            suppress_continuous_guide:
400                crate::orchestrator::registration::continuous_guide_suppressed(registered),
401            root_size: crate::layout::RootRequest::ExactSize { width, height },
402            numeric: crate::numeric::inputs::NumericInputs::new(registration, context.canvas)?,
403            alpha: source.payload.alpha.clone(),
404            guides,
405        })
406    }
407}