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