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