Skip to main content

lichtung_plot/render/
backend.rs

1//! `lichtung-plot::render::backend` — the `Backend` trait.
2//!
3//! A `Backend` implementation draws a chart onto some 2D surface
4//! (SVG file, PNG bitmap, in-memory image). The sole Backend impl
5//! lives in `svg_backend.rs` and emits SVG directly. PNG output is
6//! produced by rasterizing the SVG through `resvg` (see the `png`
7//! Cargo feature). Future backends (skia, vello) can drop in behind
8//! the same trait.
9
10#![deny(missing_docs)]
11
12#[cfg(test)]
13use crate::theme::color_from_rgb;
14use crate::theme::Color;
15use crate::Error;
16
17use super::primitives::{
18    CanonicalFillStyle, CanonicalGradientFill, CanonicalLineStyle, CanonicalPlannedBracket,
19    CanonicalPlannedText, CanonicalScatter,
20};
21use crate::layout::{
22    DeferredAnnotationTextPlan, PhysicalTextAlignment, PixelRect, ResolvedTextPlan,
23};
24use crate::render::coordinates::{
25    self, CanonicalBracket, CanonicalGradient, CanonicalPoint, CanonicalRect, CanonicalRoundedRect,
26    CanonicalText,
27};
28use crate::PointShape;
29
30/// A 2D point in math-style canvas coordinates after data projection.
31///
32/// X increases rightward and Y increases upward from the canvas bottom. A
33/// backend converts this canonical canvas space to its native coordinates.
34#[derive(Debug, Clone, Copy, PartialEq)]
35pub struct Point2D {
36    /// X coordinate.
37    pub x: f64,
38    /// Y coordinate.
39    pub y: f64,
40}
41
42impl Point2D {
43    /// Construct a point.
44    #[must_use]
45    pub fn new(x: f64, y: f64) -> Self {
46        Self { x, y }
47    }
48}
49
50/// Visual style for a scatter point.
51#[derive(Debug, Clone, PartialEq)]
52pub(crate) struct PointStyle {
53    /// Complete point fill paint.
54    pub(crate) color: Color,
55    /// Radius in pixels.
56    pub(crate) radius: u32,
57    /// Optional outline stroke.
58    pub(crate) outline: Option<PointOutline>,
59    /// Marker geometry.
60    pub(crate) shape: PointShape,
61}
62
63impl PointStyle {
64    /// Construct a backend fixture with the default publication point outline.
65    #[cfg(test)]
66    #[must_use]
67    pub(crate) fn new(color: (u8, u8, u8), radius: u32) -> Self {
68        Self {
69            color: color_from_rgb(color).alpha(209),
70            radius,
71            outline: Some(PointOutline::publication().unwrap()),
72            shape: PointShape::Circle,
73        }
74    }
75
76    /// Set the marker geometry.
77    #[must_use]
78    pub const fn with_shape(mut self, shape: PointShape) -> Self {
79        self.shape = shape;
80        self
81    }
82}
83
84/// Outline stroke for scatter-like point marks.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub(crate) struct PointOutline {
87    /// Independent complete outline paint.
88    pub(crate) color: Color,
89    /// Stroke width as a proportion of the point radius.
90    pub(crate) width_ratio: crate::theme::RelativeSpacing,
91}
92
93impl PointOutline {
94    /// Construct the validated publication outline.
95    #[cfg(test)]
96    pub(crate) fn publication() -> Result<Self, Error> {
97        Ok(crate::theme::PointOutlineTheme::publication()?.backend_style())
98    }
99
100    /// Resolve the outline stroke width for the given point radius.
101    pub(crate) fn width_for_radius(
102        &self,
103        radius: u32,
104    ) -> Result<coordinates::CanonicalCoordinate, Error> {
105        let width = self
106            .width_ratio
107            .product(crate::theme::LocalMetric::css_pixels(f64::from(radius))?)
108            .round(crate::layout::kernel::SpatialRounding::NearestEven)?
109            .quanta();
110        if width > (1_i64 << 53) - 1 || (width == 0 && !self.width_ratio.is_zero()) {
111            return Err(Error::Render("point outline width exceeds canonical coordinates or its positive extent collapses".into()));
112        }
113        Ok(coordinates::CanonicalCoordinate::from_quanta(width))
114    }
115}
116
117/// Visual style for a line (used by regression fits, axis lines).
118#[derive(Debug, Clone, PartialEq)]
119pub struct LineStyle {
120    /// Complete stroke paint.
121    pub(crate) color: Color,
122    /// Stroke width in pixels (supports sub-pixel, e.g. 0.8).
123    pub width: f32,
124    /// Closed stroke pattern.
125    pub pattern: StrokePattern,
126}
127
128impl LineStyle {
129    /// Create a solid line style.
130    #[must_use]
131    #[cfg(test)]
132    pub(crate) fn solid(color: Color, width: f32) -> Self {
133        Self {
134            color,
135            width,
136            pattern: StrokePattern::Solid,
137        }
138    }
139}
140
141/// Closed line-stroke patterns accepted by the private backend protocol.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum StrokePattern {
144    /// Continuous stroke.
145    Solid,
146    /// Fixed `3 2` dash and gap lengths.
147    ShortDash,
148    /// Fixed `4 3` dash and gap lengths.
149    MediumDash,
150    /// Fixed `5 3` dash and gap lengths.
151    LongDash,
152}
153
154impl StrokePattern {
155    pub(crate) const fn svg_dasharray(self) -> Option<&'static str> {
156        match self {
157            Self::Solid => None,
158            Self::ShortDash => Some("3 2"),
159            Self::MediumDash => Some("4 3"),
160            Self::LongDash => Some("5 3"),
161        }
162    }
163}
164
165/// Independent complete fill and stroke paints for a polygon or rectangle.
166#[derive(Debug, Clone)]
167pub(crate) struct FillStyle {
168    pub(crate) color: Color,
169    pub(crate) stroke: Color,
170    /// Stroke width in pixels (0.0 for no outline).
171    pub(crate) stroke_width: f32,
172}
173
174impl FillStyle {
175    pub(crate) const fn new(color: Color, stroke: Color, stroke_width: f32) -> Self {
176        // Width zero is the operational encoding of structural absence. Its
177        // unused paint cannot become guide/cache/feedback identity.
178        if stroke_width == 0.0 {
179            return Self {
180                color,
181                stroke: Color::rgba(0, 0, 0, 0),
182                stroke_width: 0.0,
183            };
184        }
185        Self {
186            color,
187            stroke,
188            stroke_width,
189        }
190    }
191}
192
193/// One color in a linear gradient at a normalized offset.
194#[derive(Debug, Clone, Copy, PartialEq)]
195pub struct GradientStop {
196    /// Position along the gradient vector, in the inclusive range `[0, 1]`.
197    pub offset: f64,
198    /// Color at this position (R, G, B).
199    pub color: (u8, u8, u8),
200}
201
202impl GradientStop {
203    /// Construct a gradient stop.
204    #[must_use]
205    pub const fn new(offset: f64, color: (u8, u8, u8)) -> Self {
206        Self { offset, color }
207    }
208}
209
210/// Text anchor alignment.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
212pub enum TextAnchor {
213    /// Left-aligned (SVG default).
214    #[default]
215    Start,
216    /// Center-aligned.
217    Middle,
218    /// Right-aligned.
219    End,
220}
221
222/// Visual style for a text label.
223#[derive(Debug, Clone, PartialEq)]
224pub struct TextStyle {
225    /// Complete text paint.
226    pub(crate) color: Color,
227    /// Font family.
228    pub(crate) font_family: crate::font::canonical::FontStack,
229    /// Font size in actual CSS pixels.
230    pub font_size: f64,
231    /// Closed font-weight policy.
232    pub weight: crate::TextWeight,
233    /// Horizontal alignment anchor. Default: `Start`.
234    pub anchor: TextAnchor,
235    /// Rotation angle in degrees (clockwise). Default: `0.0`.
236    pub rotation: f64,
237}
238
239/// A significance bracket drawn inside the plot panel: a horizontal
240/// line spanning two x-positions, with a vertical tick at each end
241/// and a glyph (e.g. "***") above the midpoint.
242#[derive(Debug, Clone)]
243pub struct SignificanceBracket {
244    /// X position of the left tick.
245    pub x_left: f64,
246    /// X position of the right tick.
247    pub x_right: f64,
248    /// Y position of the bracket.
249    pub y: f64,
250    /// Glyph string ("ns", "*", "**", "***", "****").
251    pub label: String,
252    /// Whether the span runs along x above marks or along y to their right.
253    pub orientation: BracketOrientation,
254}
255
256/// Semantic role of a named backend layer.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
258pub enum LayerRole {
259    /// Ordinary layer emitted in call order.
260    #[default]
261    Generic,
262    /// Grid layer that must render behind data marks.
263    Grid,
264}
265
266/// Ownership role for an ordered painted surface.
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub(crate) enum SurfaceRole {
269    /// Canvas-owned root surface.
270    CanvasRoot,
271    /// Plot-owned panel surface.
272    PlotPanel,
273}
274
275/// Orientation of a pairwise significance bracket.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum BracketOrientation {
278    /// Span two x anchors at a fixed y position.
279    Vertical,
280    /// Span two y anchors at a fixed x position. In this orientation,
281    /// `x_left`/`x_right` store bottom/top y anchors and `y` stores x.
282    Horizontal,
283}
284
285pub(crate) const POLYGON_MITER_LIMIT: f64 = 4.0;
286
287/// Visual style for a significance bracket.
288#[derive(Debug, Clone)]
289pub struct BracketStyle {
290    /// Complete bracket-path stroke paint.
291    pub(crate) color: Color,
292    /// Complete bracket-label text paint.
293    pub(crate) label_color: Color,
294    /// Stroke width in pixels.
295    pub width: f32,
296    /// Label font family.
297    pub(crate) font_family: crate::font::canonical::FontStack,
298    /// Label font size in pixels.
299    pub font_size: f64,
300    /// Label line height in pixels.
301    pub(crate) line_height: f64,
302    /// Label font weight.
303    pub weight: crate::TextWeight,
304    /// Gap between the bracket line and its label.
305    pub label_gap: f64,
306    /// Retained selected tick height; canonical validation has no default.
307    pub(crate) tick_height: f64,
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub(crate) enum PlannedTextOrigin {
312    Middle,
313    Baseline,
314}
315
316#[derive(Debug, Clone, Copy, PartialEq)]
317pub(crate) struct PlannedTextPlacement {
318    pub(crate) position: Point2D,
319    pub(crate) anchor: TextAnchor,
320    pub(crate) rotation: f64,
321    pub(crate) origin: PlannedTextOrigin,
322    /// Physical column order for existing outward-stacked rotated axis titles.
323    pub(crate) reverse_lines: bool,
324}
325
326#[derive(Debug, Clone)]
327pub(crate) struct PlacedText {
328    pub(crate) plan: ResolvedTextPlan,
329    pub(crate) placement: PlannedTextPlacement,
330}
331
332pub(crate) fn reserve_text_records<T>(
333    records: &mut Vec<T>,
334    additional: usize,
335) -> Result<(), Error> {
336    if additional > records.capacity() - records.len() {
337        let capacity = records
338            .len()
339            .checked_add(additional)
340            .zip(records.capacity().checked_mul(2))
341            .map(|(required, doubled)| required.max(doubled).max(4))
342            .ok_or_else(|| Error::Render("producer text capacity overflow".into()))?;
343
344        records
345            .try_reserve_exact(capacity - records.len())
346            .map_err(|_| Error::Render("producer text allocation failed".into()))?;
347    }
348    Ok(())
349}
350
351impl PlacedText {
352    pub(crate) fn middle(
353        plan: ResolvedTextPlan,
354        position: Point2D,
355        anchor: TextAnchor,
356        rotation: f64,
357    ) -> Result<Self, Error> {
358        Ok(Self {
359            placement: crate::layout::text::placement::resolve(
360                PlannedTextPlacement::middle(position, anchor, rotation),
361                &plan,
362                None,
363            )?,
364            plan,
365        })
366    }
367    pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
368        backend.draw_planned_text(self.placement, &self.plan)
369    }
370
371    pub(crate) fn with_reversed_lines(mut self) -> Self {
372        self.placement.reverse_lines = true;
373        self
374    }
375}
376
377impl PlannedTextPlacement {
378    pub(crate) fn line_y(self, plan: &ResolvedTextPlan, y: i64) -> Result<i64, Error> {
379        if !self.reverse_lines {
380            return Ok(y);
381        }
382        plan.last_baseline_quanta
383            .unwrap_or(0)
384            .checked_sub(y)
385            .and_then(|offset| plan.first_baseline_quanta.unwrap_or(0).checked_add(offset))
386            .ok_or_else(|| Error::Render("reversed text line placement overflowed".into()))
387    }
388    pub(crate) const fn middle(position: Point2D, anchor: TextAnchor, rotation: f64) -> Self {
389        Self {
390            position,
391            anchor,
392            rotation,
393            origin: PlannedTextOrigin::Middle,
394            reverse_lines: false,
395        }
396    }
397
398    pub(crate) const fn baseline(position: Point2D, anchor: TextAnchor, rotation: f64) -> Self {
399        Self {
400            position,
401            anchor,
402            rotation,
403            origin: PlannedTextOrigin::Baseline,
404            reverse_lines: false,
405        }
406    }
407}
408
409#[derive(Debug, Clone, Copy)]
410pub(crate) struct PlannedSignificanceCall<'a> {
411    pub(crate) bracket: &'a SignificanceBracket,
412    pub(crate) style: &'a BracketStyle,
413    pub(crate) label: &'a DeferredAnnotationTextPlan,
414}
415
416/// The `Backend` trait. Every concrete renderer (Plotters,
417/// future Skia, future Vello) implements this.
418///
419/// All draw methods take a mutable `&mut self` and return
420/// `Result<(), Error>`. Backends may buffer internally and
421/// only emit output on `end()` (or `finalize()`).
422///
423/// Geometry passed to raw draw methods is already projected into math-style
424/// canvas coordinates: X increases rightward and Y increases upward. Data
425/// scaling and panel placement are renderer responsibilities, not backend
426/// responsibilities. Canonical methods consume retained top-down operands for
427/// the selected canvas and must not delegate back through raw draw methods.
428pub trait Backend {
429    /// Draw retained line, run and glyph placement without layout or conversion.
430    fn draw_canonical_text(&mut self, _text: &CanonicalPlannedText) -> Result<(), Error> {
431        Err(Error::Render(
432            "backend does not support canonical text".into(),
433        ))
434    }
435
436    /// Draw a retained bracket and its canonical label placement.
437    fn draw_canonical_bracket(&mut self, _bracket: &CanonicalPlannedBracket) -> Result<(), Error> {
438        Err(Error::Render(
439            "backend does not support canonical bracket".into(),
440        ))
441    }
442
443    /// Draw retained top-down markers without raw geometry conversion.
444    fn draw_canonical_scatter(&mut self, _scatter: &CanonicalScatter) -> Result<(), Error> {
445        Err(Error::Render(
446            "backend does not support canonical scatter".into(),
447        ))
448    }
449
450    /// Draw retained top-down line points and stroke operands.
451    fn draw_canonical_line(
452        &mut self,
453        _points: &[CanonicalPoint],
454        _style: &CanonicalLineStyle,
455    ) -> Result<(), Error> {
456        Err(Error::Render(
457            "backend does not support canonical lines".into(),
458        ))
459    }
460
461    /// Draw retained top-down polygon points and paint operands.
462    fn draw_canonical_polygon(
463        &mut self,
464        _points: &[CanonicalPoint],
465        _style: &CanonicalFillStyle,
466    ) -> Result<(), Error> {
467        Err(Error::Render(
468            "backend does not support canonical polygons".into(),
469        ))
470    }
471
472    /// Draw retained top-down gradient geometry and normalized stops.
473    fn draw_canonical_gradient(&mut self, _gradient: &CanonicalGradientFill) -> Result<(), Error> {
474        Err(Error::Render(
475            "backend does not support canonical gradients".into(),
476        ))
477    }
478
479    /// Begin a clip from retained, checked top-down spatial operands.
480    fn begin_canonical_clip(&mut self, _region: coordinates::CanonicalBox) -> Result<(), Error> {
481        Err(Error::Render(
482            "backend does not support canonical clips".into(),
483        ))
484    }
485
486    /// Paint a surface from retained, checked top-down spatial operands.
487    fn draw_canonical_surface(
488        &mut self,
489        _bounds: coordinates::CanonicalBox,
490        _paint: Color,
491        _role: SurfaceRole,
492    ) -> Result<(), Error> {
493        Err(Error::Render(
494            "backend does not support canonical surfaces".into(),
495        ))
496    }
497
498    /// Draw a rectangle from retained top-down geometry, stroke, and paint.
499    fn draw_canonical_rounded_rect(
500        &mut self,
501        _rounded: coordinates::CanonicalRoundedBox,
502    ) -> Result<(), Error> {
503        Err(Error::Render(
504            "backend does not support canonical rectangles".into(),
505        ))
506    }
507
508    /// Begin a chart of the given pixel size. Must be called before
509    /// any draw method.
510    fn begin(&mut self, width: u32, height: u32) -> Result<(), Error>;
511
512    /// Begin a named SVG layer (`<g id="...">`). Draw calls between
513    /// `begin_layer` and `end_layer` are grouped. Layers control
514    /// z-order: earlier layers render behind later ones.
515    fn begin_layer(&mut self, _name: &str) -> Result<(), Error> {
516        Ok(())
517    }
518
519    /// Begin a named layer with an explicit semantic role.
520    ///
521    /// Backends that do not reorder layers may use the default delegation to
522    /// [`Backend::begin_layer`].
523    fn begin_layer_with_role(&mut self, name: &str, _role: LayerRole) -> Result<(), Error> {
524        self.begin_layer(name)
525    }
526
527    /// End the current SVG layer.
528    fn end_layer(&mut self) -> Result<(), Error> {
529        Ok(())
530    }
531
532    /// Begin clipping subsequent draw calls to a math-style canvas rectangle.
533    /// Clip scopes may nest with layers and must be closed in last-in-first-out
534    /// order with [`Backend::end_clip`].
535    fn begin_clip(&mut self, region: PixelRect) -> Result<(), Error>;
536
537    /// End the current clip scope.
538    fn end_clip(&mut self) -> Result<(), Error>;
539
540    /// Paint a validated math-style rectangular surface in semantic surface
541    /// order rather than ordinary draw-call order.
542    fn draw_surface(
543        &mut self,
544        bounds: PixelRect,
545        paint: Color,
546        role: SurfaceRole,
547    ) -> Result<(), Error>;
548
549    /// Draw a scatter cloud.
550    fn draw_scatter(&mut self, points: &[Point2D], style: &PointStyle) -> Result<(), Error>;
551
552    /// Draw a line strip (e.g. a regression fit).
553    fn draw_line(&mut self, points: &[Point2D], style: &LineStyle) -> Result<(), Error>;
554
555    /// Draw a filled polygon (bar body, violin body).
556    fn draw_polygon(&mut self, points: &[Point2D], style: &FillStyle) -> Result<(), Error>;
557
558    /// Fill a rectangle with a native linear gradient.
559    ///
560    /// `bounds` and the gradient vector use math-style canvas coordinates.
561    /// Stops must begin at 0, end at 1, and have strictly increasing offsets.
562    fn draw_linear_gradient(
563        &mut self,
564        bounds: PixelRect,
565        start: Point2D,
566        end: Point2D,
567        stops: &[GradientStop],
568    ) -> Result<(), Error>;
569
570    /// Draw a text label at finite signed math-style canvas coordinates with
571    /// alignment and optional rotation.
572    fn draw_text(&mut self, position: Point2D, text: &str, style: &TextStyle) -> Result<(), Error>;
573
574    /// Draw one immutable operation-owned text plan.
575    #[doc(hidden)]
576    #[allow(
577        private_interfaces,
578        reason = "immutable text plans are a crate-private renderer transition"
579    )]
580    fn draw_planned_text(
581        &mut self,
582        placement: PlannedTextPlacement,
583        plan: &ResolvedTextPlan,
584    ) -> Result<(), Error> {
585        self.draw_text(
586            placement.position,
587            &plan.source,
588            &planned_text_style(placement, plan)?,
589        )
590    }
591
592    /// Draw a rounded rectangle. Coordinates are in math-coordinate space
593    /// (y increases upward). `x` and `y` are the bottom-left corner,
594    /// `w` and `h` are width and height, `r` is the corner radius.
595    ///
596    fn draw_rounded_rect(
597        &mut self,
598        x: f64,
599        y: f64,
600        w: f64,
601        h: f64,
602        r: f64,
603        style: &FillStyle,
604    ) -> Result<(), Error>;
605
606    /// Draw a significance bracket.
607    fn draw_bracket(
608        &mut self,
609        bracket: &SignificanceBracket,
610        style: &BracketStyle,
611    ) -> Result<(), Error>;
612
613    /// Draw one significance bracket with its immutable planned label.
614    #[doc(hidden)]
615    #[allow(
616        private_interfaces,
617        reason = "immutable significance plans are a crate-private renderer transition"
618    )]
619    fn draw_planned_bracket(&mut self, call: PlannedSignificanceCall<'_>) -> Result<(), Error> {
620        self.draw_bracket(call.bracket, call.style)
621    }
622
623    /// End the chart. Flushes any buffered output. After `end()`,
624    /// no more draw methods may be called until the next `begin()`.
625    fn end(&mut self) -> Result<(), Error>;
626}
627
628pub(crate) fn validate_clip_region(region: PixelRect) -> Result<CanonicalRect, Error> {
629    coordinates::canonical_clip(region)
630}
631
632pub(crate) fn validate_surface_bounds(bounds: PixelRect) -> Result<CanonicalRect, Error> {
633    coordinates::canonical_clip(bounds)
634}
635
636pub(crate) fn validate_points(
637    points: &[Point2D],
638    context: &str,
639) -> Result<Vec<CanonicalPoint>, Error> {
640    coordinates::canonical_points(points, context)
641}
642
643pub(crate) fn points_share_canonical_position(
644    first: Point2D,
645    second: Point2D,
646    context: &str,
647) -> Result<bool, Error> {
648    let points = coordinates::canonical_points(&[first, second], context)?;
649    Ok(points[0].same_position(points[1]))
650}
651
652pub(crate) fn validate_line_points(points: &[Point2D]) -> Result<Vec<CanonicalPoint>, Error> {
653    coordinates::canonical_line_points(points)
654}
655
656pub(crate) fn validate_polygon_points(points: &[Point2D]) -> Result<Vec<CanonicalPoint>, Error> {
657    coordinates::canonical_polygon_points(points)
658}
659
660pub(crate) fn validate_triangle_points(
661    points: &[Point2D],
662    radius: u32,
663) -> Result<Vec<[CanonicalPoint; 3]>, Error> {
664    coordinates::canonical_triangles(points, radius)
665}
666
667pub(crate) fn validate_point_style(style: &PointStyle) -> Result<(), Error> {
668    if style.outline.is_some() && style.radius == 0 {
669        return Err(Error::Render(
670            "outlined point radius must be positive".into(),
671        ));
672    }
673    Ok(())
674}
675
676pub(crate) fn validate_line_style(style: &LineStyle) -> Result<(), Error> {
677    if style.width.is_finite() && style.width >= 0.0 {
678        Ok(())
679    } else {
680        Err(Error::Render(format!(
681            "line width must be finite and non-negative; got {}",
682            style.width
683        )))
684    }
685}
686
687pub(crate) fn validate_fill_style(style: &FillStyle) -> Result<(), Error> {
688    if !style.stroke_width.is_finite() || style.stroke_width < 0.0 {
689        return Err(Error::Render(format!(
690            "fill stroke width must be finite and non-negative; got {}",
691            style.stroke_width
692        )));
693    }
694    Ok(())
695}
696
697pub(crate) fn validate_linear_gradient(
698    bounds: PixelRect,
699    start: Point2D,
700    end: Point2D,
701    stops: &[GradientStop],
702) -> Result<CanonicalGradient, Error> {
703    coordinates::canonical_gradient(bounds, start, end, stops)
704}
705
706pub(crate) fn validate_text_style(style: &TextStyle) -> Result<(), Error> {
707    if style.rotation.is_finite() {
708        Ok(())
709    } else {
710        Err(Error::Render(format!(
711            "text rotation must be finite; got {}",
712            style.rotation
713        )))
714    }
715}
716
717pub(crate) fn validate_text(position: Point2D, style: &TextStyle) -> Result<CanonicalText, Error> {
718    validate_text_style(style)?;
719    coordinates::canonical_text(
720        position,
721        style.rotation,
722        coordinates::CoordinatePrecision::CssQuantum,
723    )
724}
725
726pub(crate) fn planned_text_style(
727    placement: PlannedTextPlacement,
728    plan: &ResolvedTextPlan,
729) -> Result<TextStyle, Error> {
730    Ok(TextStyle {
731        color: plan.style.paint,
732        font_family: plan
733            .copy_stack()
734            .map_err(|error| Error::Render(error.to_string()))?,
735        font_size: plan.style.font_size,
736        weight: plan.style.weight,
737        anchor: placement.anchor,
738        rotation: placement.rotation,
739    })
740}
741
742pub(crate) const fn nearest_even_text_half(value: i64) -> Option<i64> {
743    if value < 0 {
744        return None;
745    }
746    let quotient = value / 2;
747    if value % 2 == 0 || quotient % 2 == 0 {
748        Some(quotient)
749    } else {
750        quotient.checked_add(1)
751    }
752}
753
754pub(crate) fn validate_planned_text(
755    placement: PlannedTextPlacement,
756    plan: &ResolvedTextPlan,
757) -> Result<CanonicalText, Error> {
758    let canonical = coordinates::canonical_text(
759        placement.position,
760        placement.rotation,
761        coordinates::CoordinatePrecision::CssQuantum,
762    )?;
763    validate_text_plan(placement, plan)?;
764    Ok(canonical)
765}
766
767#[expect(
768    clippy::too_many_lines,
769    reason = "one protocol validator checks linked immutable style, line, discretionary-break, and glyph spans"
770)]
771pub(crate) fn validate_text_plan(
772    placement: PlannedTextPlacement,
773    plan: &ResolvedTextPlan,
774) -> Result<(), Error> {
775    let expected_alignment = match placement.anchor {
776        TextAnchor::Start => PhysicalTextAlignment::Start,
777        TextAnchor::Middle => PhysicalTextAlignment::Center,
778        TextAnchor::End => PhysicalTextAlignment::End,
779    };
780    if plan.style.alignment != expected_alignment {
781        return Err(Error::Render(
782            "planned text alignment does not match its backend placement".into(),
783        ));
784    }
785    if !plan.style.font_size.is_finite()
786        || plan.style.font_size <= 0.0
787        || plan.style.stack_source.is_empty()
788        || plan.style.stack.is_empty()
789        || plan.style.line_height_quanta <= 0
790        || plan.line_pitch_quanta <= 0
791        || plan.width_quanta < 0
792        || plan.height_quanta < 0
793    {
794        return Err(Error::Render(
795            "planned text has invalid resolved style or dimensions".into(),
796        ));
797    }
798    let valid_span = |start: u32, end: u32| {
799        let start = start as usize;
800        let end = end as usize;
801        start <= end
802            && end <= plan.source.len()
803            && plan.source.is_char_boundary(start)
804            && plan.source.is_char_boundary(end)
805    };
806    let valid_ink = |left: i64, bottom: i64, right: i64, top: i64| left <= right && bottom <= top;
807    match (plan.lines.first(), plan.lines.last()) {
808        (Some(first), Some(last)) => {
809            if plan.first_baseline_quanta != Some(first.translation_y_quanta)
810                || plan.last_baseline_quanta != Some(last.translation_y_quanta)
811                || plan.height_quanta == 0
812            {
813                return Err(Error::Render(
814                    "planned text baselines do not match its stored lines".into(),
815                ));
816            }
817        }
818        (None, None) => {
819            if plan.first_baseline_quanta.is_some()
820                || plan.last_baseline_quanta.is_some()
821                || plan.width_quanta != 0
822                || plan.height_quanta != 0
823            {
824                return Err(Error::Render(
825                    "empty planned text has nonempty metrics".into(),
826                ));
827            }
828        }
829        _ => unreachable!("a slice cannot have only one of first/last"),
830    }
831    for (index, line) in plan.lines.iter().enumerate() {
832        placement.line_y(plan, line.translation_y_quanta)?;
833        if let Some(soft) = line.selected_soft_hyphen {
834            if !valid_span(soft.start_byte, soft.end_byte)
835                || soft.start_byte < line.source_span.start_byte
836                || soft.end_byte != line.source_span.end_byte
837                || &plan.source[soft.start_byte as usize..soft.end_byte as usize] != "\u{ad}"
838                || !line.runs.iter().any(|run| {
839                    run.source_span.start_byte <= soft.start_byte
840                        && run.source_span.end_byte >= soft.end_byte
841                })
842            {
843                return Err(Error::Render(
844                    "planned text has an invalid selected soft-hyphen span or run".into(),
845                ));
846            }
847        }
848        let expected_y = plan
849            .first_baseline_quanta
850            .and_then(|first| {
851                i64::try_from(index)
852                    .ok()
853                    .and_then(|index| plan.line_pitch_quanta.checked_mul(index))
854                    .and_then(|offset| first.checked_add(offset))
855            })
856            .ok_or_else(|| Error::Render("planned text line offset overflow".into()))?;
857        if line.translation_y_quanta != expected_y
858            || !valid_span(line.source_span.start_byte, line.source_span.end_byte)
859            || line
860                .ink_quanta
861                .is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
862        {
863            return Err(Error::Render(
864                "planned text has an invalid line span, translation, or ink box".into(),
865            ));
866        }
867        for run in &line.runs {
868            if !valid_span(run.source_span.start_byte, run.source_span.end_byte)
869                || run.source_span.start_byte < line.source_span.start_byte
870                || run.source_span.end_byte > line.source_span.end_byte
871                || run.units_per_em == 0
872                || run
873                    .ink_quanta
874                    .is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
875                || run.glyphs.iter().any(|glyph| {
876                    glyph
877                        .ink_quanta
878                        .is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
879                })
880            {
881                return Err(Error::Render(
882                    "planned text has an invalid shaped run or glyph ink box".into(),
883                ));
884            }
885        }
886    }
887    Ok(())
888}
889
890pub(crate) fn validate_rounded_rect(
891    x: f64,
892    y: f64,
893    width: f64,
894    height: f64,
895    radius: f64,
896) -> Result<CanonicalRoundedRect, Error> {
897    coordinates::canonical_rounded_rect(x, y, width, height, radius)
898}
899
900pub(crate) fn validate_bracket(
901    bracket: &SignificanceBracket,
902    style: &BracketStyle,
903) -> Result<CanonicalBracket, Error> {
904    if !style.width.is_finite() || style.width < 0.0 {
905        return Err(Error::Render(format!(
906            "bracket width must be finite and non-negative; got {}",
907            style.width
908        )));
909    }
910    if !style.font_size.is_finite()
911        || style.font_size <= 0.0
912        || !style.line_height.is_finite()
913        || style.line_height <= 0.0
914        || !style.label_gap.is_finite()
915        || style.label_gap < 0.0
916        || !style.tick_height.is_finite()
917        || style.tick_height < 0.0
918    {
919        return Err(Error::Render(
920            "bracket style requires positive font size and line height and finite nonnegative gap and tick height"
921                .into(),
922        ));
923    }
924    coordinates::canonical_bracket(bracket, style.tick_height, style.label_gap)
925}
926
927pub(crate) fn planned_bracket_placement(
928    canonical: CanonicalBracket,
929    plan: &ResolvedTextPlan,
930) -> Result<PlannedTextPlacement, Error> {
931    let position = canonical.label_position.value();
932    let default = match canonical.orientation {
933        BracketOrientation::Vertical => {
934            PlannedTextPlacement::baseline(position, TextAnchor::Middle, 0.0)
935        }
936        BracketOrientation::Horizontal => {
937            PlannedTextPlacement::middle(position, TextAnchor::Start, 0.0)
938        }
939    };
940    crate::layout::text::placement::resolve(default, plan, None)
941}
942
943pub(crate) fn validate_planned_bracket(
944    call: PlannedSignificanceCall<'_>,
945) -> Result<CanonicalBracket, Error> {
946    let canonical = validate_bracket(call.bracket, call.style)?;
947    validate_bracket_label(canonical, call)?;
948    Ok(canonical)
949}
950
951pub(crate) fn validate_bracket_label(
952    canonical: CanonicalBracket,
953    call: PlannedSignificanceCall<'_>,
954) -> Result<(), Error> {
955    let plan = &call.label.plan;
956    validate_text_plan(planned_bracket_placement(canonical, plan)?, plan)?;
957    if call.label.exact_override != plan.style.exact_override
958        || call.bracket.label != plan.original_source()
959        || call.style.label_color != plan.style.paint
960        || !plan.same_stack(&call.style.font_family)
961        || call.style.font_size.to_bits() != plan.style.font_size.to_bits()
962        || call.style.weight != plan.style.weight
963    {
964        return Err(Error::Render(
965            "planned significance label does not match its frozen source and style".into(),
966        ));
967    }
968    Ok(())
969}
970
971pub(crate) fn with_clip<T>(
972    backend: &mut dyn Backend,
973    region: PixelRect,
974    draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
975) -> Result<T, Error> {
976    backend.begin_clip(region)?;
977    finish_scope(draw(backend), backend.end_clip(), "clip scope")
978}
979
980pub(crate) fn with_layer<T>(
981    backend: &mut dyn Backend,
982    name: &str,
983    draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
984) -> Result<T, Error> {
985    backend.begin_layer(name)?;
986    finish_scope(
987        draw(backend),
988        backend.end_layer(),
989        &format!("layer {name:?}"),
990    )
991}
992
993pub(crate) fn with_layer_role<T>(
994    backend: &mut dyn Backend,
995    name: &str,
996    role: LayerRole,
997    draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
998) -> Result<T, Error> {
999    backend.begin_layer_with_role(name, role)?;
1000    finish_scope(
1001        draw(backend),
1002        backend.end_layer(),
1003        &format!("layer {name:?}"),
1004    )
1005}
1006
1007pub(crate) fn finish_scope<T>(
1008    primary: Result<T, Error>,
1009    cleanup: Result<(), Error>,
1010    scope: &str,
1011) -> Result<T, Error> {
1012    match (primary, cleanup) {
1013        (Ok(value), Ok(())) => Ok(value),
1014        (Err(primary), Ok(())) => Err(primary),
1015        (Ok(_), Err(cleanup)) => Err(Error::Render(format!("failed to close {scope}: {cleanup}"))),
1016        (Err(primary), Err(cleanup)) => Err(Error::Render(format!(
1017            "{primary}; additionally failed to close {scope}: {cleanup}"
1018        ))),
1019    }
1020}