Skip to main content

lichtung_plot/layout/panel/
axis_frame_grid.rs

1use crate::Error;
2
3use super::sources::SourceKind;
4use super::{cells, AuthoredAxisSpec, Axis, AxisSide, AxisTick, Layout, Projection, TickSource};
5use crate::layout::canvas::EdgeSpaceRequirements;
6use crate::layout::fit::{self, FitKind, FitScope, PlanError};
7use crate::layout::{PhysicalTextAlignment, ResolvedTextPlan};
8use crate::render::backend::{Backend, LineStyle, PlannedTextPlacement, Point2D, TextAnchor};
9use crate::theme::spacing::ExactLength;
10use crate::theme::AxisLengths;
11
12#[cfg(test)]
13mod tests;
14
15impl AuthoredAxisSpec {
16    /// Return a copy with finite, strictly ascending explicit limits.
17    #[must_use]
18    pub fn limits(mut self, min: f64, max: f64) -> Self {
19        self.window = Some(super::RawWindow::from_pair((min, max)));
20        self
21    }
22
23    pub(crate) fn validate(&self, axis: &str) -> Result<(), Error> {
24        if let Some((minimum, maximum)) = self.window.map(super::RawWindow::pair) {
25            if !minimum.is_finite() || !maximum.is_finite() || minimum >= maximum {
26                return Err(Error::Data(format!(
27                    "{axis} limits must be finite and strictly ascending; got {minimum}..{maximum}"
28                )));
29            }
30        }
31        if let Some(ticks) = &self.exact_ticks {
32            Axis::validate_tick_source(ticks, self.window.map(super::RawWindow::pair), axis)?;
33        }
34        Ok(())
35    }
36}
37
38impl AxisTick {
39    /// Construct a tick with an unchanged display label.
40    #[must_use]
41    pub fn new(position: f64, label: impl Into<String>) -> Self {
42        Self {
43            position,
44            label: label.into(),
45        }
46    }
47}
48
49#[derive(Debug, Clone)]
50pub(crate) struct AxisSystemPlan {
51    projection: Projection,
52    semantics: [super::AxisSemanticInputs; 2],
53    standard: super::CoordinateLayoutInputs,
54    x_axis: FrozenAxisPlan,
55    y_axis: FrozenAxisPlan,
56    frame: Option<FramePlan>,
57    grid: Option<GridPlan>,
58    requirements: EdgeSpaceRequirements,
59}
60
61impl AxisSystemPlan {
62    /// Matrix variable-title roles span their edge cells, but never merge axes'
63    /// independent numeric tick groups or the row and column title roles.
64    pub(crate) fn uniform_titles(
65        plans: &mut [&mut Self],
66        side: AxisSide,
67        theme: &crate::text::TextRequestContext<'_, '_>,
68        scope: &FitScope,
69    ) -> Result<(), PlanError> {
70        let mut text = crate::data::source::collect_source(
71            plans
72                .iter()
73                .filter_map(|plan| match side {
74                    AxisSide::Bottom => plan.x_axis.title.as_ref(),
75                    AxisSide::Left => plan.y_axis.title.as_ref(),
76                })
77                .map(|(plan, placement)| {
78                    Ok(crate::render::backend::PlacedText {
79                        plan: plan.clone(),
80                        placement: *placement,
81                    })
82                }),
83        )?;
84        crate::layout::text::font_fit::uniform_placed(theme, &mut text, scope)?;
85        let mut text = text.into_iter();
86        for plan in plans {
87            let title = match side {
88                AxisSide::Bottom => &mut plan.x_axis.title,
89                AxisSide::Left => &mut plan.y_axis.title,
90            };
91            if title.is_some() {
92                let selected = text.next().expect("retained Matrix title");
93                *title = Some((selected.plan, selected.placement));
94            }
95        }
96        Ok(())
97    }
98}
99
100#[derive(Debug, Clone)]
101struct FramePlan {
102    sides: [Option<[Point2D; 2]>; 4],
103    style: LineStyle,
104}
105
106impl FramePlan {
107    fn new(
108        panel: crate::layout::PixelRect,
109        frame: &crate::theme::FrameTheme,
110    ) -> Result<Self, Error> {
111        let selected = frame.get_sides().drawing_order();
112        let segments = [
113            [
114                Point2D::new(panel.x0, panel.y0),
115                Point2D::new(panel.x1, panel.y0),
116            ],
117            [
118                Point2D::new(panel.x1, panel.y0),
119                Point2D::new(panel.x1, panel.y1),
120            ],
121            [
122                Point2D::new(panel.x1, panel.y1),
123                Point2D::new(panel.x0, panel.y1),
124            ],
125            [
126                Point2D::new(panel.x0, panel.y1),
127                Point2D::new(panel.x0, panel.y0),
128            ],
129        ];
130        Ok(Self {
131            sides: std::array::from_fn(|index| selected[index].then_some(segments[index])),
132            style: crate::theme::axis::stroke_style(frame.get_stroke())?,
133        })
134    }
135
136    fn outward_edges(&self) -> [f64; 4] {
137        let [bottom, right, top, left] = self.sides.each_ref().map(Option::is_some);
138        [
139            left || bottom || top,
140            right || bottom || top,
141            bottom || left || right,
142            top || left || right,
143        ]
144        .map(|present| {
145            if present {
146                f64::from(self.style.width) / 2.0
147            } else {
148                0.0
149            }
150        })
151    }
152}
153
154#[derive(Debug, Clone)]
155struct GridPlan {
156    lines: Vec<[Point2D; 2]>,
157    style: LineStyle,
158}
159
160#[derive(Debug, Clone)]
161struct FrozenTick {
162    position: f64,
163    cell: cells::LabelCell,
164    segment: [Point2D; 2],
165    label: Option<(ResolvedTextPlan, PlannedTextPlacement)>,
166}
167
168#[derive(Debug, Clone)]
169struct FrozenAxisPlan {
170    source: TickSource,
171    eligible_labels: Vec<usize>,
172    ticks: Vec<FrozenTick>,
173    title: Option<(ResolvedTextPlan, PlannedTextPlacement)>,
174    explanation: Option<(ResolvedTextPlan, PlannedTextPlacement)>,
175    numeric: Option<std::sync::Arc<crate::numeric::set::FormattedSet>>,
176    tick_style: Option<LineStyle>,
177    gutter: f64,
178    start_overhang: f64,
179    end_overhang: f64,
180}
181
182impl AxisSystemPlan {
183    pub(crate) fn geometry_snapshot(
184        &self,
185    ) -> Result<crate::render::geometry::GeometrySnapshot, Error> {
186        let mut geometry = crate::render::geometry::GeometrySnapshot::new();
187        if let Some(frame) = &self.frame {
188            for side in frame.sides.iter().flatten() {
189                geometry.line(side, &frame.style, None)?;
190            }
191        }
192        for axis in [&self.x_axis, &self.y_axis] {
193            for tick in &axis.ticks {
194                if let Some(style) = &axis.tick_style {
195                    geometry.line(&tick.segment, style, None)?;
196                }
197                if let Some((plan, placement)) = &tick.label {
198                    geometry.text(*placement, plan, None)?;
199                }
200            }
201            if let Some((plan, placement)) = &axis.title {
202                geometry.text(*placement, plan, None)?;
203            }
204            if let Some((plan, placement)) = &axis.explanation {
205                geometry.text(*placement, plan, None)?;
206            }
207        }
208        Ok(geometry)
209    }
210    pub(crate) fn requirements(&self) -> EdgeSpaceRequirements {
211        self.requirements
212    }
213
214    pub(crate) fn draw_grid(&self, backend: &mut dyn Backend) -> Result<(), Error> {
215        if let Some(grid) = &self.grid {
216            for line in &grid.lines {
217                backend.draw_line(line, &grid.style)?;
218            }
219        }
220        Ok(())
221    }
222
223    pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
224        if let Some(frame) = &self.frame {
225            for side in frame.sides.iter().flatten() {
226                backend.draw_line(side, &frame.style)?;
227            }
228        }
229        for axis in [&self.x_axis, &self.y_axis] {
230            for tick in &axis.ticks {
231                if let Some(style) = &axis.tick_style {
232                    backend.draw_line(&tick.segment, style)?;
233                }
234                if let Some((plan, placement)) = &tick.label {
235                    backend.draw_planned_text(*placement, plan)?;
236                }
237            }
238            if let Some((plan, placement)) = &axis.title {
239                backend.draw_planned_text(*placement, plan)?;
240            }
241            if let Some((plan, placement)) = &axis.explanation {
242                backend.draw_planned_text(*placement, plan)?;
243            }
244        }
245        Ok(())
246    }
247
248    pub(crate) fn observe_feedback(
249        &self,
250        round: &mut crate::layout::kernel::FeedbackRound,
251    ) -> Result<(), Error> {
252        self.standard.observe_feedback(round)?;
253        for input in &self.semantics {
254            input.observe_feedback(round)?;
255        }
256        for range in [self.projection.x_range(), self.projection.y_range()] {
257            round.observe_number(range.0)?;
258            round.observe_number(range.1)?;
259        }
260        for axis in [&self.x_axis, &self.y_axis] {
261            if let Some(numeric) = &axis.numeric {
262                numeric.observe_feedback(round)?;
263            }
264            round.observe_count(axis.source.ordinal)?;
265            round.observe_count(axis.eligible_labels.len())?;
266            for &index in &axis.eligible_labels {
267                round.observe_count(index)?;
268            }
269            round.observe_count(axis.source.cap)?;
270            round.observe_count(
271                axis.source
272                    .precision
273                    .map_or(0, |digits| usize::from(digits) + 1),
274            )?;
275            let (kind, parameter) = match axis.source.kind {
276                SourceKind::Supplied => (0, 0.0),
277                SourceKind::Exact => (1, 0.0),
278                SourceKind::Adaptive(seed) => (2, seed as f64),
279                SourceKind::Additive(step) => (3, step),
280                SourceKind::LogIntegral => (4, 0.0),
281                SourceKind::LogSubset(count) => (5, count as f64),
282                SourceKind::LogInterval(step) => {
283                    round.observe_count((step >> 32) as usize)?;
284                    round.observe_count((step & 0xffff_ffff) as usize)?;
285                    (6, 0.0)
286                }
287                SourceKind::Midpoint => (7, 0.0),
288                SourceKind::ExactCount => (8, 0.0),
289                SourceKind::Multiplicative => (9, 0.0),
290                SourceKind::Function => (10, 0.0),
291            };
292            round.observe_count(kind)?;
293            round.observe_number(parameter)?;
294            for tick in &axis.ticks {
295                round.observe_number(tick.position)?;
296                round.observe_number(tick.cell.center)?;
297                if tick.label.is_some() {
298                    round.observe_number(tick.cell.start)?;
299                    round.observe_number(tick.cell.end)?;
300                    round.observe_count(usize::from(tick.cell.inward))?;
301                }
302            }
303            for (plan, _) in axis
304                .ticks
305                .iter()
306                .filter_map(|tick| tick.label.as_ref())
307                .chain(axis.title.iter())
308                .chain(axis.explanation.iter())
309            {
310                round.observe_text(plan)?;
311            }
312        }
313        Ok(())
314    }
315}
316
317impl Layout {
318    #[cfg(test)]
319    pub(crate) fn plan_axes(
320        &self,
321        theme: &crate::text::TextRequestContext<'_, '_>,
322    ) -> Result<AxisSystemPlan, Error> {
323        self.measure_axes(theme, &FitScope::root(), self.test_semantics())
324            .map_err(PlanError::into_error)
325    }
326
327    #[cfg(test)]
328    pub(crate) fn test_semantics(&self) -> [super::AxisSemanticInputs; 2] {
329        [&self.x_axis, &self.y_axis].map(|axis| {
330            super::AxisSemanticInputs::new(
331                crate::orchestrator::registration::AxisIntentRef::MatrixVariable,
332                super::RangeProvenance::Automatic,
333                crate::spec::AxisScale::Linear,
334                if axis.source == TickSource::SUPPLIED {
335                    super::RangePolicy::CategorySlots
336                } else {
337                    super::RangePolicy::ContinuousNice
338                },
339            )
340        })
341    }
342
343    pub(crate) fn measure_axes(
344        &self,
345        theme: &crate::text::TextRequestContext<'_, '_>,
346        scope: &FitScope,
347        semantics: [super::AxisSemanticInputs; 2],
348    ) -> Result<AxisSystemPlan, PlanError> {
349        self.measure_axes_with_inputs(theme, scope, semantics, || {
350            super::CoordinateLayoutInputs::new(theme)
351        })
352    }
353
354    pub(crate) fn measure_axes_with_inputs(
355        &self,
356        theme: &crate::text::TextRequestContext<'_, '_>,
357        scope: &FitScope,
358        semantics: [super::AxisSemanticInputs; 2],
359        standard: impl FnOnce() -> Result<super::CoordinateLayoutInputs, Error>,
360    ) -> Result<AxisSystemPlan, PlanError> {
361        let standard = standard()?;
362        let appearance = theme.theme.clone();
363        let directional = crate::text::TextRequestContext {
364            theme: &appearance,
365            ..*theme
366        }
367        .reproject_text(self);
368        let theme = &directional;
369        // Evaluate both siblings: a later fatal error takes precedence over a fit miss.
370        let x_axis = self.x_axis.measure(
371            &self.projection,
372            AxisSide::Bottom,
373            theme,
374            &standard,
375            &scope.child(crate::layout::AddressRole::AxisBottom, 0)?,
376        );
377        let y_axis = self.y_axis.measure(
378            &self.projection,
379            AxisSide::Left,
380            theme,
381            &standard,
382            &scope.child(crate::layout::AddressRole::AxisLeft, 0)?,
383        );
384        let (x_axis, y_axis) = match (x_axis, y_axis) {
385            (Err(PlanError::Fatal(error)), _) | (_, Err(PlanError::Fatal(error))) => {
386                return Err(error.into())
387            }
388            (Err(error), _) | (_, Err(error)) => return Err(error),
389            (Ok(x), Ok(y)) => (x, y),
390        };
391        let (x0, x1, y0, y1) = self.projection.pixel_box();
392        let frame = standard
393            .axes
394            .get_frame()
395            .map(|frame| FramePlan::new(self.projection.panel_box(), frame))
396            .transpose()?;
397        let grid = if let Some(grid) = standard.axes.get_grid() {
398            let mut lines = Vec::new();
399            let count = x_axis
400                .ticks
401                .len()
402                .checked_add(y_axis.ticks.len())
403                .ok_or_else(|| Error::Render("grid plan count overflow".into()))?;
404            fit::reserve(&mut lines, count, "grid geometry")?;
405            for tick in &x_axis.ticks {
406                lines.push([
407                    Point2D::new(tick.segment[0].x, y0),
408                    Point2D::new(tick.segment[0].x, y1),
409                ]);
410            }
411            for tick in &y_axis.ticks {
412                lines.push([
413                    Point2D::new(x0, tick.segment[0].y),
414                    Point2D::new(x1, tick.segment[0].y),
415                ]);
416            }
417            Some(GridPlan {
418                lines,
419                style: crate::theme::axis::stroke_style(grid)?,
420            })
421        } else {
422            None
423        };
424        let edges = frame.as_ref().map_or([0.0; 4], FramePlan::outward_edges);
425        let mut requirements = EdgeSpaceRequirements {
426            left: y_axis.gutter.max(x_axis.start_overhang).max(edges[0]),
427            right: x_axis.end_overhang.max(edges[1]),
428            bottom: x_axis.gutter.max(y_axis.start_overhang).max(edges[2]),
429            top: y_axis.end_overhang.max(edges[3]),
430        };
431        for extent in [
432            &mut requirements.left,
433            &mut requirements.right,
434            &mut requirements.bottom,
435            &mut requirements.top,
436        ] {
437            *extent = (*extent * 1024.0).ceil() / 1024.0;
438        }
439        Ok(AxisSystemPlan {
440            projection: self.projection.clone(),
441            semantics,
442            standard,
443            x_axis,
444            y_axis,
445            frame,
446            grid,
447            requirements,
448        })
449    }
450}
451
452impl Axis {
453    /// Keep the title block centered on its semantic axis while aligning its lines
454    /// in text-local space, before the existing horizontal/vertical transform.
455    #[expect(
456        clippy::cast_precision_loss,
457        reason = "canonical text quanta convert at placement"
458    )]
459    pub(crate) fn title_placement(
460        plan: &ResolvedTextPlan,
461        center: Point2D,
462        side: AxisSide,
463    ) -> Result<PlannedTextPlacement, Error> {
464        let half = crate::render::backend::nearest_even_text_half(plan.width_quanta)
465            .ok_or_else(|| Error::Render("axis title half extent overflow".into()))?
466            as f64
467            / 1024.0;
468        let (anchor, offset) = match plan.style.alignment {
469            PhysicalTextAlignment::Start => (TextAnchor::Start, -half),
470            PhysicalTextAlignment::Center => (TextAnchor::Middle, 0.0),
471            PhysicalTextAlignment::End => (TextAnchor::End, plan.width() - half),
472        };
473        let default = match side {
474            AxisSide::Bottom => {
475                PlannedTextPlacement::middle(Point2D::new(center.x + offset, center.y), anchor, 0.0)
476            }
477            AxisSide::Left => PlannedTextPlacement::middle(
478                Point2D::new(center.x, center.y + offset),
479                anchor,
480                -90.0,
481            ),
482        };
483        let default = if plan.request.as_ref().is_some_and(|request| {
484            request.instructions().anchor.is_some() || request.instructions().orientation.is_some()
485        }) {
486            PlannedTextPlacement::middle(center, TextAnchor::Middle, default.rotation)
487        } else {
488            default
489        };
490        crate::layout::text::placement::resolve(default, plan, None)
491    }
492
493    pub(crate) fn validate_ticks(
494        ticks: &[AxisTick],
495        range: (f64, f64),
496        axis: &str,
497    ) -> Result<(), Error> {
498        Self::validate_tick_source(ticks, Some(range), axis)
499    }
500
501    fn validate_tick_source(
502        ticks: &[AxisTick],
503        range: Option<(f64, f64)>,
504        axis: &str,
505    ) -> Result<(), Error> {
506        Self::validate_exact_tick_source(
507            &crate::orchestrator::registration::ExactTicksRef {
508                raw: ticks,
509                projected: None,
510            },
511            range,
512            axis,
513        )
514    }
515
516    pub(crate) fn validate_exact_ticks(
517        ticks: &crate::orchestrator::registration::ExactTicksRef<'_>,
518        range: (f64, f64),
519        axis: &str,
520    ) -> Result<(), Error> {
521        Self::validate_exact_tick_source(ticks, Some(range), axis)
522    }
523
524    fn validate_exact_tick_source(
525        ticks: &crate::orchestrator::registration::ExactTicksRef<'_>,
526        range: Option<(f64, f64)>,
527        axis: &str,
528    ) -> Result<(), Error> {
529        if ticks.raw.is_empty() {
530            return Err(Error::Data(format!(
531                "{axis} explicit numeric ticks must not be empty"
532            )));
533        }
534        for index in 0..ticks.raw.len() {
535            let (position, label) = ticks.tick(index)?;
536            crate::text::validate_for(label, axis)?;
537            if !position.is_finite() {
538                return Err(Error::Data(format!(
539                    "{axis} explicit tick {index} position must be finite; got {position}"
540                )));
541            }
542            if let Some(range) = range {
543                if position < range.0 || position > range.1 {
544                    return Err(Error::Data(format!(
545                        "{axis} explicit tick {index} position {} is outside resolved range {}..{}",
546                        position, range.0, range.1
547                    )));
548                }
549            }
550            if index > 0 && ticks.tick(index - 1)?.0 >= position {
551                return Err(Error::Data(format!(
552                    "{axis} explicit tick positions must be strictly ascending"
553                )));
554            }
555        }
556        Ok(())
557    }
558
559    fn vertical_label_width(
560        &self,
561        panel: crate::layout::PixelRect,
562        theme: &crate::text::TextRequestContext<'_, '_>,
563    ) -> Result<f64, Error> {
564        if let Some(width) = self.assigned_tick_width {
565            return Ok(width);
566        }
567        if self.source == TickSource::EXACT {
568            let mut width = 1.0 / 1024.0;
569            let eligible = crate::data::source::collect_source(
570                self.ticks
571                    .iter()
572                    .enumerate()
573                    .filter(|(_, tick)| !tick.label.is_empty())
574                    .map(|(index, _)| Ok(index)),
575            )?;
576            let appearance = theme.tick_text_appearance(AxisSide::Left);
577            for &index in &eligible {
578                if !appearance.includes(index, &eligible) {
579                    continue;
580                }
581                let tick = &self.ticks[index];
582                let plan = theme.measure_appearance_text(
583                    &tick.label,
584                    appearance,
585                    PhysicalTextAlignment::End,
586                    "y-axis exact tick label",
587                )?;
588                width = f64::max(width, plan.occupied_size().0.max(plan.fit_width()));
589            }
590            Ok(width)
591        } else {
592            let eligible = crate::data::source::collect_source(
593                self.category_labels.indices(self.ticks.len()).map(Ok),
594            )?;
595            theme.intrinsic_tick_label_width(
596                eligible
597                    .iter()
598                    .copied()
599                    .filter(|&index| {
600                        theme
601                            .tick_text_appearance(AxisSide::Left)
602                            .includes(index, &eligible)
603                    })
604                    .map(|index| self.ticks[index].label.as_str()),
605                panel.height(),
606            )
607        }
608    }
609
610    #[allow(clippy::too_many_lines)]
611    fn measure(
612        &self,
613        projection: &Projection,
614        side: AxisSide,
615        theme: &crate::text::TextRequestContext<'_, '_>,
616        standard: &super::CoordinateLayoutInputs,
617        scope: &FitScope,
618    ) -> Result<FrozenAxisPlan, PlanError> {
619        if let Some(crate::text::orientation::Orientation::Automatic(angles)) = theme
620            .tick_text_appearance(side)
621            .layout
622            .and_then(|request| request.instructions().orientation.as_ref())
623            .map(|orientation| &orientation.0)
624        {
625            if self.tick_labels_visible
626                && !self.ticks.is_empty()
627                && !theme.tick_text_appearance(side).hidden()
628            {
629                let original = theme
630                    .tick_text_appearance(side)
631                    .layout
632                    .expect("angle request");
633                let mut miss = None;
634                for angle in angles {
635                    let mut selected_appearance = theme.theme.clone();
636                    selected_appearance.text_layouts.ticks[usize::from(side == AxisSide::Left)] =
637                        Some(original.clone().rotation(*angle));
638                    let selected = crate::text::TextRequestContext {
639                        theme: &selected_appearance,
640                        ..*theme
641                    };
642                    match self.measure(projection, side, &selected, standard, scope) {
643                        Ok(mut plan) => {
644                            for tick in &mut plan.ticks {
645                                if let Some((text, _)) = &mut tick.label {
646                                    *text = text.clone().with_request(Some(original));
647                                }
648                            }
649                            return Ok(plan);
650                        }
651                        Err(PlanError::Fit(failure)) => {
652                            fit::FitFailure::retain_least(&mut miss, failure);
653                        }
654                        Err(error) => return Err(error),
655                    }
656                }
657                return Err(miss
658                    .unwrap_or_else(|| {
659                        scope.failure(
660                            FitKind::Tick,
661                            "automatic text orientation has no fitting angle",
662                        )
663                    })
664                    .into());
665            }
666        }
667        let categorical = self.source == TickSource::SUPPLIED;
668        let tick_text = theme.tick_text_appearance(side);
669        let visible = self.tick_labels_visible && !tick_text.hidden();
670        let allow = tick_text.layout.is_some_and(|request| {
671            request.instructions().overlap == Some(crate::TextOverlap::Allow)
672                || request
673                    .instructions()
674                    .visibility
675                    .as_ref()
676                    .is_some_and(crate::TextVisibility::reduces)
677        });
678        let cells = cells::assign(
679            &self.ticks,
680            categorical,
681            visible && !allow,
682            self.assigned_cells.as_deref(),
683            &self.category_labels,
684            projection,
685            side,
686            scope,
687        )?;
688        let panel = projection.panel_box();
689        let vertical_width = if side == AxisSide::Left && visible {
690            self.vertical_label_width(panel, theme)?
691        } else {
692            0.0
693        };
694
695        let title_appearance = self.label.as_ref().map_or_else(
696            || (&standard.axis_title).into(),
697            |text| text.appearance(&standard.axis_title),
698        );
699        let lengths = standard.axes.get_spacing().lengths(
700            standard.tick_label.get_font_size(),
701            title_appearance.theme.get_font_size(),
702        )?;
703        let frame_half = standard
704            .axes
705            .get_frame()
706            .filter(|frame| match side {
707                AxisSide::Bottom => frame.get_sides().get_bottom(),
708                AxisSide::Left => frame.get_sides().get_left(),
709            })
710            .map_or(0.0, |frame| f64::from(frame.get_stroke().get_width()) / 2.0);
711        let tick_appearance = standard.axes.get_ticks().filter(|_| !self.ticks.is_empty());
712        let tick_style = tick_appearance
713            .map(|ticks| crate::theme::axis::stroke_style(ticks.get_stroke()))
714            .transpose()?;
715        let tick_length = tick_appearance.map_or(0.0, |ticks| f64::from(ticks.get_length()));
716        let frame_offset = ExactLength::pixels(frame_half)?;
717        let tick_end = frame_offset.add_pixels(tick_length)?;
718        let outward = tick_end.add_pixels(
719            tick_style
720                .as_ref()
721                .map_or(0.0, |style| f64::from(style.width) / 2.0),
722        )?;
723        let anchor = match side {
724            AxisSide::Bottom => panel.y0,
725            AxisSide::Left => panel.x0,
726        };
727        let segment_start = AxisLengths::before(&frame_offset, anchor)?;
728        let segment_end = AxisLengths::before(&tick_end, anchor)?;
729        let mut ticks = Vec::new();
730        fit::reserve(&mut ticks, self.ticks.len(), "frozen axis ticks")?;
731        let (_gap, title_gap, title_width, tick_role, title_role) = match side {
732            AxisSide::Bottom => (
733                &lengths.x_tick_label_gap,
734                &lengths.x_title_tick_label_gap,
735                panel.width(),
736                "x-axis tick label",
737                "x-axis title",
738            ),
739            AxisSide::Left => (
740                &lengths.y_tick_label_gap,
741                &lengths.y_title_tick_label_gap,
742                panel.height(),
743                "y-axis tick label",
744                "y-axis title",
745            ),
746        };
747        let eligible_labels = crate::data::source::collect_source(
748            self.category_labels
749                .indices(self.ticks.len())
750                .filter(|&index| categorical || !self.ticks[index].label.is_empty())
751                .map(Ok),
752        )?;
753        let label_indices = crate::data::source::collect_source(
754            eligible_labels
755                .iter()
756                .copied()
757                .filter(|&index| visible && tick_text.includes(index, &eligible_labels))
758                .map(Ok),
759        )?;
760        let mut label_plans = fit::collect(
761            "axis text group",
762            label_indices.iter().map(|&index| {
763                let (width, alignment) = match side {
764                    AxisSide::Bottom => (
765                        if allow {
766                            panel.width()
767                        } else {
768                            cells[index].capacity()
769                        },
770                        PhysicalTextAlignment::Center,
771                    ),
772                    AxisSide::Left => (vertical_width, PhysicalTextAlignment::End),
773                };
774                fit::measured(match side {
775                    AxisSide::Bottom => fit::text(
776                        theme,
777                        &self.ticks[index].label,
778                        tick_text,
779                        width,
780                        alignment,
781                        tick_role,
782                        scope,
783                    ),
784                    AxisSide::Left => crate::layout::text::request::measure_height(
785                        theme,
786                        &self.ticks[index].label,
787                        tick_text,
788                        width,
789                        cells[index].capacity(),
790                        alignment,
791                        tick_role,
792                        scope,
793                    ),
794                })
795            }),
796        )?;
797        crate::layout::text::font_fit::uniform(theme, &mut label_plans, scope)?;
798        let mut label_plans = label_indices.iter().zip(label_plans);
799        for (index, (tick, cell)) in self.ticks.iter().zip(cells).enumerate() {
800            let segment = match side {
801                AxisSide::Bottom => [
802                    Point2D::new(cell.center, segment_start),
803                    Point2D::new(cell.center, segment_end),
804                ],
805                AxisSide::Left => [
806                    Point2D::new(segment_start, cell.center),
807                    Point2D::new(segment_end, cell.center),
808                ],
809            };
810            let label = if !visible
811                || !self.category_labels.includes(index, self.ticks.len())
812                || (!categorical && tick.label.is_empty())
813                || tick_text
814                    .layout
815                    .and_then(|request| request.instructions().visibility.as_ref())
816                    .is_some_and(|visibility| !visibility.includes(index, &eligible_labels))
817            {
818                None
819            } else {
820                let (_, mut plan) = label_plans.next().ok_or_else(|| {
821                    crate::Error::Render("axis text group lost a selected member".into())
822                })?;
823                let selected_lengths = standard
824                    .axes
825                    .get_spacing()
826                    .lengths(plan.style.font_size, title_appearance.theme.get_font_size())?;
827                let selected_gap = match side {
828                    AxisSide::Bottom => &selected_lengths.x_tick_label_gap,
829                    AxisSide::Left => &selected_lengths.y_tick_label_gap,
830                };
831                let offset = outward.add_length(selected_gap);
832                let local = cells::LabelCell::local(&plan, side)?;
833                let footprint = crate::layout::text::placement::footprint(local, &plan)?;
834                let perpendicular = match side {
835                    AxisSide::Bottom => {
836                        AxisLengths::before(&offset.add_pixels(footprint.y1.max(0.0))?, panel.y0)?
837                    }
838                    AxisSide::Left => {
839                        AxisLengths::before(&offset.add_pixels(footprint.x1.max(0.0))?, panel.x0)?
840                    }
841                };
842                let placement = cell.placement(&plan, side, perpendicular)?.ok_or_else(|| {
843                    scope.failure(
844                        FitKind::Tick,
845                        format!(
846                            "{tick_role} ink or logical extent exceeds its assigned cell clearance"
847                        ),
848                    )
849                })?;
850                if !allow {
851                    let bounds = crate::layout::text::placement::footprint(placement, &plan)?;
852                    let region = match side {
853                        AxisSide::Bottom => crate::layout::PixelRect::new(
854                            cell.start, cell.end, bounds.y0, bounds.y1,
855                        ),
856                        AxisSide::Left => crate::layout::PixelRect::new(
857                            bounds.x0, bounds.x1, cell.start, cell.end,
858                        ),
859                    };
860                    plan = crate::layout::text::placement::contain(plan, placement, region, scope)?;
861                }
862                Some((plan, placement))
863            };
864            ticks.push(FrozenTick {
865                position: tick.position,
866                cell,
867                segment,
868                label,
869            });
870        }
871        if let Some(policy) = tick_text
872            .layout
873            .and_then(|request| request.instructions().visibility.as_ref())
874        {
875            let candidates = crate::data::source::collect_source(
876                ticks
877                    .iter()
878                    .enumerate()
879                    .filter_map(|(index, tick)| {
880                        tick.label
881                            .as_ref()
882                            .map(|(plan, placement)| (index, tick, plan, placement))
883                    })
884                    .map(|(index, tick, plan, placement)| {
885                        Ok(crate::layout::text::visibility::Candidate {
886                            index,
887                            position: tick.cell.center,
888                            bounds: crate::layout::text::placement::footprint(*placement, plan)?,
889                        })
890                    }),
891            )?;
892            let region = match side {
893                AxisSide::Bottom => {
894                    crate::layout::PixelRect::new(panel.x0, panel.x1, -f64::MAX, f64::MAX)
895                }
896                AxisSide::Left => {
897                    crate::layout::PixelRect::new(-f64::MAX, f64::MAX, panel.y0, panel.y1)
898                }
899            };
900            let failure = tick_text
901                .layout
902                .and_then(|request| request.instructions().overflow.as_ref())
903                .map_or(crate::TextFailure::Error, |overflow| overflow.failure);
904            let selected = crate::layout::text::visibility::reduce(
905                policy,
906                &eligible_labels,
907                &candidates,
908                region,
909                failure,
910                scope,
911            )?;
912            for (candidate, visible) in candidates.iter().zip(selected) {
913                if !visible {
914                    ticks[candidate.index].label = None;
915                }
916            }
917        }
918        let indices = crate::data::source::collect_source(
919            ticks
920                .iter()
921                .enumerate()
922                .filter(|(_, tick)| tick.label.is_some())
923                .map(|(index, _)| Ok(index)),
924        )?;
925        let mut views = crate::data::source::collect_source(indices.iter().map(|&index| {
926            let (plan, placement) = ticks[index].label.as_ref().expect("selected tick text");
927            Ok(crate::render::backend::PlacedText {
928                plan: plan.clone(),
929                placement: *placement,
930            })
931        }))?;
932        crate::layout::text::visibility::require_distinct(&mut views, scope)?;
933        for (&index, view) in indices.iter().zip(views) {
934            ticks[index].label = Some((view.plan, view.placement));
935        }
936        let mut labels_present = false;
937        let mut label_extent = ExactLength::pixels(0.0)?;
938        for tick in &ticks {
939            if let Some((plan, _)) = &tick.label {
940                if plan.lines.is_empty() {
941                    continue;
942                }
943                labels_present = true;
944                // A zero perpendicular reference keeps requirements invariant
945                // under independently rounded parent translations.
946                let mut local_plan = plan.clone();
947                local_plan.clear_paint_region();
948                let local = tick
949                    .cell
950                    .placement(&local_plan, side, 0.0)?
951                    .ok_or_else(|| {
952                        Error::Render("selected axis label lost its local placement".into())
953                    })?;
954                let bounds = crate::layout::text::placement::footprint(local, &local_plan)?;
955                let selected_lengths = standard
956                    .axes
957                    .get_spacing()
958                    .lengths(plan.style.font_size, title_appearance.theme.get_font_size())?;
959                let selected_gap = match side {
960                    AxisSide::Bottom => &selected_lengths.x_tick_label_gap,
961                    AxisSide::Left => &selected_lengths.y_tick_label_gap,
962                };
963                let extent = selected_gap.add_pixels(match side {
964                    AxisSide::Bottom => bounds.height(),
965                    AxisSide::Left => bounds.width(),
966                })?;
967                if extent.compare(&label_extent).is_gt() {
968                    label_extent = extent;
969                }
970            }
971        }
972        let mut gutter = outward;
973        if labels_present {
974            gutter = gutter.add_length(&label_extent);
975        }
976        let title = if let Some(label) = &self.label {
977            let mut plan = fit::measured(fit::single_text(
978                theme,
979                label.as_str(),
980                title_appearance,
981                if side == AxisSide::Left
982                    && title_appearance
983                        .layout
984                        .is_some_and(|request| request.instructions().orientation.is_some())
985                {
986                    f64::from(u32::MAX)
987                } else {
988                    title_width
989                },
990                label
991                    .resolved_alignment(crate::TextAlignment::Center)
992                    .into(),
993                title_role,
994                scope,
995            ))?;
996            let selected_lengths = standard
997                .axes
998                .get_spacing()
999                .lengths(tick_text.theme.get_font_size(), plan.style.font_size)?;
1000            let title_gap = match side {
1001                AxisSide::Bottom => &selected_lengths.x_title_tick_label_gap,
1002                AxisSide::Left => &selected_lengths.y_title_tick_label_gap,
1003            };
1004            let separation = if labels_present {
1005                title_gap
1006            } else {
1007                match side {
1008                    AxisSide::Bottom => &selected_lengths.x_title_without_tick_labels_gap,
1009                    AxisSide::Left => title_gap,
1010                }
1011            };
1012            gutter = gutter.add_length(separation);
1013            let local = Self::title_placement(&plan, Point2D::new(0.0, 0.0), side)?;
1014            let local_bounds = crate::layout::text::placement::footprint(local, &plan)?;
1015            let inward = match side {
1016                AxisSide::Bottom => local_bounds.y1,
1017                AxisSide::Left => local_bounds.x1,
1018            };
1019            let position = AxisLengths::before(&gutter.add_pixels(inward.max(0.0))?, anchor)?;
1020            let center = match side {
1021                AxisSide::Bottom => Point2D::new(f64::midpoint(panel.x0, panel.x1), position),
1022                AxisSide::Left => Point2D::new(position, f64::midpoint(panel.y0, panel.y1)),
1023            };
1024            let mut placement = Self::title_placement(&plan, center, side)?;
1025            let canonical = crate::render::coordinates::canonical_text(
1026                placement.position,
1027                placement.rotation,
1028                crate::render::coordinates::CoordinatePrecision::CssQuantum,
1029            )?;
1030            placement.position = canonical.position.value();
1031            let thickness = match side {
1032                AxisSide::Bottom => local_bounds.height(),
1033                AxisSide::Left => local_bounds.width(),
1034            };
1035            let bounds = crate::layout::text::placement::footprint(placement, &plan)?;
1036            let region = match side {
1037                AxisSide::Bottom => {
1038                    crate::layout::PixelRect::new(panel.x0, panel.x1, bounds.y0, bounds.y1)
1039                }
1040                AxisSide::Left => {
1041                    crate::layout::PixelRect::new(bounds.x0, bounds.x1, panel.y0, panel.y1)
1042                }
1043            };
1044            plan = crate::layout::text::placement::contain(plan, placement, region, scope)?;
1045            gutter = gutter.add_pixels(thickness)?;
1046            Some((plan, placement))
1047        } else {
1048            None
1049        };
1050        let explanation = if let Some(text) = self
1051            .numeric
1052            .as_ref()
1053            .and_then(|set| set.explanation.as_ref())
1054        {
1055            let plan = fit::measured(fit::text(
1056                theme,
1057                text.as_str(),
1058                text.appearance(&standard.tick_label),
1059                title_width,
1060                text.resolved_alignment(crate::TextAlignment::Center).into(),
1061                "numeric axis explanation",
1062                scope,
1063            ))?;
1064            gutter = gutter.add_length(title_gap);
1065            let position = AxisLengths::before(&gutter.add_pixels(plan.height() / 2.0)?, anchor)?;
1066            let center = match side {
1067                AxisSide::Bottom => Point2D::new(f64::midpoint(panel.x0, panel.x1), position),
1068                AxisSide::Left => Point2D::new(position, f64::midpoint(panel.y0, panel.y1)),
1069            };
1070            let placement = Self::title_placement(&plan, center, side)?;
1071            let mut thickness = plan.height();
1072            if let Some(ink) = crate::render::geometry::planned_text_ink_bounds(
1073                &plan,
1074                Point2D::new(0.0, 0.0),
1075                placement.anchor,
1076                placement.rotation,
1077                placement.origin,
1078                placement.reverse_lines,
1079            ) {
1080                thickness = thickness.max(match side {
1081                    AxisSide::Bottom => plan.height() / 2.0 - ink.bottom,
1082                    AxisSide::Left => plan.height() / 2.0 - ink.left,
1083                });
1084            }
1085            gutter = gutter.add_pixels(thickness)?;
1086            Some((plan, placement))
1087        } else {
1088            None
1089        };
1090        if side == AxisSide::Left && (title.is_some() || explanation.is_some()) {
1091            gutter = gutter.add_length(&lengths.y_title_edge_padding);
1092        }
1093        let (start, end) = match side {
1094            AxisSide::Bottom => (panel.x0, panel.x1),
1095            AxisSide::Left => (panel.y0, panel.y1),
1096        };
1097        let half_tick = tick_style
1098            .as_ref()
1099            .map_or(0.0, |style| f64::from(style.width) / 2.0);
1100        let mut start_overhang = ticks
1101            .iter()
1102            .map(|tick| start - tick.cell.center + half_tick)
1103            .fold(0.0_f64, f64::max);
1104        let mut end_overhang = ticks
1105            .iter()
1106            .map(|tick| tick.cell.center + half_tick - end)
1107            .fold(0.0_f64, f64::max);
1108        for (plan, placement) in ticks
1109            .iter()
1110            .filter_map(|tick| tick.label.as_ref())
1111            .chain(title.iter())
1112            .chain(explanation.iter())
1113        {
1114            if let Some(ink) = crate::render::geometry::planned_text_ink_bounds(
1115                plan,
1116                placement.position,
1117                placement.anchor,
1118                placement.rotation,
1119                placement.origin,
1120                placement.reverse_lines,
1121            ) {
1122                let (low, high) = match side {
1123                    AxisSide::Bottom => (ink.left, ink.right),
1124                    AxisSide::Left => (ink.bottom, ink.top),
1125                };
1126                start_overhang = start_overhang.max(start - low);
1127                end_overhang = end_overhang.max(high - end);
1128            }
1129        }
1130        Ok(FrozenAxisPlan {
1131            source: self.source,
1132            eligible_labels,
1133            ticks,
1134            title,
1135            explanation,
1136            numeric: self.numeric.clone(),
1137            tick_style,
1138            gutter: AxisLengths::hard(&gutter)?,
1139            start_overhang,
1140            end_overhang,
1141        })
1142    }
1143}