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