Skip to main content

lichtung_plot/
orchestrator.rs

1//! Render orchestration over stable descriptions and one root operation.
2
3use crate::builder::Plot;
4#[cfg(test)]
5use crate::render::backend::Backend;
6use crate::spec::{PlotKind, PlotMeasureContext, PlotRenderResult};
7use crate::Error;
8
9mod artifacts;
10pub(crate) mod assignment;
11mod backend;
12mod facets;
13pub(crate) use facets::{prepare_discrete_guide, prepare_facet_scopes};
14pub(crate) mod layers;
15mod lifecycle;
16#[cfg(test)]
17pub(crate) use lifecycle::{complete_prepared_plot_for_test, with_prepared_plot_for_test};
18#[cfg(test)]
19pub(crate) mod measurements;
20mod output;
21pub(crate) mod plan;
22pub(crate) mod registration;
23pub(crate) mod root;
24pub(crate) mod science;
25mod validation;
26
27pub(crate) use artifacts::write_atomic;
28pub(crate) use backend::{capture_calls, validate_text_replay_plan, TextReplayPlan};
29pub(crate) use facets::text_census_labels as facet_text_census_labels;
30pub(crate) use lifecycle::{
31    capture_selected, layout_report, plan_scene, render_scene, render_scene_with_results,
32};
33
34#[cfg(test)]
35thread_local! {
36    pub(crate) static SELECTED_INTERIOR_MEASUREMENTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
37    static FINAL_PLOT_RENDER_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
38}
39
40impl<K: crate::kind::Marker> Plot<K> {
41    /// Validate the complete selected chart without publishing an output.
42    ///
43    /// # Errors
44    ///
45    /// Returns an error when preparation, measurement or validating replay fails.
46    pub fn preflight(&self) -> Result<(), Error> {
47        self.preflight_with_operation(&crate::operation::OperationOptions::default())
48    }
49
50    /// Preflight using the cancellation options of this call.
51    pub fn preflight_with_operation(
52        &self,
53        options: &crate::operation::OperationOptions,
54    ) -> Result<(), Error> {
55        crate::operation::run(options, || {
56            plan_scene(root::RootSource::Plot(self.description())).map(drop)
57        })
58    }
59
60    #[cfg(test)]
61    pub(crate) fn render_with_backend(&self, backend: &mut dyn Backend) -> Result<(), Error> {
62        let frozen = plan_scene(root::RootSource::Plot(self.description()))?;
63        let (width, height) = frozen.size().layout_dimensions()?;
64        FINAL_PLOT_RENDER_CALLS.with(|calls| calls.set(calls.get() + 1));
65        frozen
66            .plan()
67            .replay(width, height, backend, "prepared plot scene replay")
68    }
69
70    #[cfg(test)]
71    pub(crate) fn render_kind(
72        &self,
73        kind: PlotKind,
74        backend: &mut dyn Backend,
75    ) -> Result<(), Error> {
76        self.description().validate_configuration(kind)?;
77        self.render_with_backend(backend)
78    }
79}
80
81pub(crate) fn validate_interior_preparation(
82    registered: &registration::PlotRegistration<'_>,
83) -> Result<(), Error> {
84    if crate::layout::interior::InteriorRoute::classify(registered.source.kind()).is_coordinate()
85        && registered.axes.coordinate().is_none()
86    {
87        return Err(Error::Render(
88            "native coordinate panel requires root-prepared axes".into(),
89        ));
90    }
91    Ok(())
92}
93
94pub(crate) fn measure_plot(
95    factory: &assignment::PlotMeasureAssignmentFactory<'_, '_>,
96    entry: assignment::PlotMeasureAssignment,
97    guides: crate::decorations::legend::discrete::scoped::GuideConsumption<'_>,
98    scope: &crate::layout::fit::FitScope,
99) -> Result<(assignment::PlotMeasureAssignment, PlotRenderResult), crate::layout::fit::PlanError> {
100    let request =
101        crate::text::TextRequestContext::new(&factory.registered.appearance, factory.text);
102    measure_plot_with_request(factory, entry, guides, scope, &request)
103}
104
105pub(crate) fn measure_probe(
106    factory: &assignment::PlotMeasureAssignmentFactory<'_, '_>,
107    entry: assignment::PlotMeasureAssignment,
108    guides: crate::decorations::legend::discrete::scoped::GuideConsumption<'_>,
109    scope: &crate::layout::fit::FitScope,
110) -> Result<(assignment::PlotMeasureAssignment, PlotRenderResult), crate::layout::fit::PlanError> {
111    let source = factory.registered.source;
112    crate::layout::interior::InteriorRoute::classify(source.kind()).validate(source)?;
113    let mut frame = crate::layout::Layout::envelope(entry.body);
114    {
115        let context = factory.context(&entry, guides, scope)?;
116        let [x, y] = if matches!(
117            entry.domains,
118            assignment::AxisDomainAssignments::Matrix { .. }
119        ) {
120            [(0.0, 1.0); 2]
121        } else {
122            [
123                context.axis_range(crate::layout::AxisSide::Bottom)?,
124                context.axis_range(crate::layout::AxisSide::Left)?,
125            ]
126        };
127        frame.projection = crate::layout::Projection::new(x, y, entry.body.as_tuple());
128    }
129    let appearance = factory.registered.appearance.clone();
130    let request = crate::text::TextRequestContext::new(&appearance, factory.text);
131    let request = request.with_text_projection(factory.registered, &frame, entry.dimensions);
132    let guides = crate::decorations::legend::discrete::scoped::GuideConsumption {
133        use_kind: registration::discrete_guide_use(source, Some(factory.registered)),
134        ..guides
135    };
136    measure_plot_with_request(factory, entry, guides, scope, &request)
137}
138
139fn measure_plot_with_request(
140    factory: &assignment::PlotMeasureAssignmentFactory<'_, '_>,
141    entry: assignment::PlotMeasureAssignment,
142    guides: crate::decorations::legend::discrete::scoped::GuideConsumption<'_>,
143    scope: &crate::layout::fit::FitScope,
144    request: &crate::text::TextRequestContext<'_, '_>,
145) -> Result<(assignment::PlotMeasureAssignment, PlotRenderResult), crate::layout::fit::PlanError> {
146    validate_interior_preparation(factory.registered)?;
147    #[cfg(test)]
148    SELECTED_INTERIOR_MEASUREMENTS.with(|calls| calls.set(calls.get() + 1));
149    let (entry, explanation) =
150        crate::numeric::values::reserve(factory, entry, guides, request, scope)?;
151    let result = {
152        let context = factory.context(&entry, guides, scope)?;
153        let result = crate::layout::interior::measure(&context, request)?;
154        finish_selected_interior(&context, result, explanation, request)?
155    };
156    Ok((entry, result))
157}
158
159/// Finish the original selected-interior tail after the scientific producer.
160/// The caller supplies its already selected request and explanation, never a
161/// second measurement or a reconstructed context.
162fn finish_selected_interior(
163    context: &PlotMeasureContext<'_, '_>,
164    mut result: PlotRenderResult,
165    explanation: Option<crate::render::backend::PlacedText>,
166    request: &crate::text::TextRequestContext<'_, '_>,
167) -> Result<PlotRenderResult, crate::layout::fit::PlanError> {
168    let source = context.registered.source;
169    let mut geometry = crate::render::geometry::GeometrySnapshot::new();
170    if let Some(explanation) = &explanation {
171        geometry.text(explanation.placement, &explanation.plan, None)?;
172    }
173    if matches!(
174        source.kind(),
175        PlotKind::Boxplot | PlotKind::Violin | PlotKind::Raincloud
176    ) {
177        if let Some(significance) = &result.significance {
178            for bracket in &significance.brackets {
179                geometry.bracket(crate::render::backend::PlannedSignificanceCall {
180                    bracket: &bracket.geometry,
181                    style: &bracket.style,
182                    label: &bracket.label,
183                })?;
184            }
185        }
186    }
187    let guides = layers::GuideSnapshot::measure(
188        source,
189        &result,
190        &context.registered.appearance,
191        &mut geometry,
192    )?;
193    validate_frozen_axes_and_guides(Some(context.registered), &mut result)?;
194    result.panel_text = crate::decorations::panel_text::measure_plans(
195        context.registered,
196        context.assignment.local.dimensions,
197        &result.layout,
198        request,
199        context.fit_scope,
200    )?;
201    let panel_clip = if source.panel_text_annotations().iter().any(|annotation| {
202        annotation.position().as_corner().is_none()
203            || annotation.content().get_layout().is_some_and(|layout| {
204                layout
205                    .instructions()
206                    .overflow
207                    .as_ref()
208                    .is_some_and(|overflow| overflow.failure == crate::text::TextFailure::Visible)
209            })
210    }) {
211        let (width, height) = context
212            .assignment
213            .local
214            .dimensions
215            .figure_size()
216            .dimensions()?;
217        crate::layout::PixelRect::new(0.0, width, 0.0, height)
218    } else {
219        result.layout.projection.panel_box()
220    };
221    let canonical_clip = crate::render::backend::validate_clip_region(panel_clip)?.panel();
222    let text = crate::data::source::collect_source(result.panel_text.iter().map(|plan| {
223        let placed = plan.retained_placement();
224        geometry.text(placed.placement, &placed.plan, Some(canonical_clip))?;
225        Ok(placed)
226    }))?;
227    let panel_layer = if source.panel_text_annotations().is_empty() {
228        None
229    } else {
230        let mut name = String::new();
231        let length = context
232            .registered
233            .scope
234            .render_name
235            .as_ref()
236            .map_or(Some(10), |scope| scope.len().checked_add(11))
237            .ok_or_else(|| Error::Render("panel text layer name overflow".into()))?;
238        crate::data::source::reserve_source_string(&mut name, length)?;
239        if let Some(scope) = &context.registered.scope.render_name {
240            name.push_str(scope);
241            name.push('-');
242        }
243        name.push_str("panel-text");
244        Some(name)
245    };
246    result.annotations = Some(crate::data::source::source_arc(
247        crate::layout::interior::SelectedAnnotationPlan {
248            guides,
249            panel_layer,
250            panel_clip,
251            text,
252            geometry,
253            explanation,
254        },
255    )?);
256    Ok(result)
257}
258
259fn validate_frozen_axes_and_guides(
260    registered: Option<&registration::PlotRegistration<'_>>,
261    result: &mut PlotRenderResult,
262) -> Result<(), crate::layout::fit::PlanError> {
263    if result.decoration_mode != crate::spec::DecorationMode::SelfManaged && result.axes.is_none() {
264        return Err(Error::Render("native panel is missing its frozen axes".into()).into());
265    }
266    if result.discrete_guide != registration::guide_descriptor(registered)? {
267        return Err(
268            Error::Render("selected producer changed its prepared discrete guide".into()).into(),
269        );
270    }
271    Ok(())
272}
273
274#[cfg(test)]
275fn validate_axis_text(
276    layout: &crate::layout::Layout,
277    theme: &crate::text::TextRequestContext<'_, '_>,
278    scope: &crate::layout::fit::FitScope,
279) -> Result<(), crate::layout::fit::PlanError> {
280    layout
281        .measure_axes(theme, scope, layout.test_semantics())
282        .map(|_| ())
283}
284
285#[cfg(test)]
286#[test]
287fn later_axis_font_failure_wins_over_an_earlier_text_fit() {
288    use crate::layout::fit::{FitScope, PlanError};
289    let theme = crate::Theme::publication().resolve().unwrap();
290    let text = crate::text::TextService::default();
291    let theme = crate::text::TextRequestContext::new(&theme, &text);
292    theme.text.prepare_font_environment().unwrap();
293    let mut layout =
294        crate::layout::Layout::envelope(crate::layout::PixelRect::new(80.0, 610.0, 60.0, 450.0));
295    layout.x_axis.label = Some("W".repeat(200).into());
296    let scope = FitScope::root();
297    assert!(matches!(
298        validate_axis_text(&layout, &theme, &scope),
299        Err(PlanError::Fit(_))
300    ));
301    layout.y_axis.label = Some("\u{10ffff}".into());
302    assert!(matches!(
303        validate_axis_text(&layout, &theme, &scope),
304        Err(PlanError::Fatal(_))
305    ));
306}
307
308#[cfg(test)]
309#[path = "orchestrator/tests.rs"]
310mod tests;