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::Error;
15use crate::{style::LinePattern, Color};
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::style::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).with_alpha(209.0 / 255.0),
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: LinePattern,
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: LinePattern::Solid,
137        }
138    }
139}
140
141/// Independent complete fill and stroke paints for a polygon or rectangle.
142#[derive(Debug, Clone)]
143pub(crate) struct FillStyle {
144    pub(crate) color: Color,
145    pub(crate) stroke: Color,
146    /// Stroke width in pixels (0.0 for no outline).
147    pub(crate) stroke_width: f32,
148}
149
150impl FillStyle {
151    pub(crate) const fn new(color: Color, stroke: Color, stroke_width: f32) -> Self {
152        // Width zero is the operational encoding of structural absence. Its
153        // unused paint cannot become guide/cache/feedback identity.
154        if stroke_width == 0.0 {
155            return Self {
156                color,
157                stroke: Color::TRANSPARENT,
158                stroke_width: 0.0,
159            };
160        }
161        Self {
162            color,
163            stroke,
164            stroke_width,
165        }
166    }
167}
168
169/// One color in a linear gradient at a normalized offset.
170#[derive(Debug, Clone, Copy, PartialEq)]
171pub struct GradientStop {
172    /// Position along the gradient vector, in the inclusive range `[0, 1]`.
173    pub offset: f64,
174    /// Color at this position (R, G, B).
175    pub color: (u8, u8, u8),
176}
177
178impl GradientStop {
179    /// Construct a gradient stop.
180    #[must_use]
181    pub const fn new(offset: f64, color: (u8, u8, u8)) -> Self {
182        Self { offset, color }
183    }
184}
185
186/// Text anchor alignment.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
188pub enum TextAnchor {
189    /// Left-aligned (SVG default).
190    #[default]
191    Start,
192    /// Center-aligned.
193    Middle,
194    /// Right-aligned.
195    End,
196}
197
198/// Visual style for a text label.
199#[derive(Debug, Clone, PartialEq)]
200pub struct TextStyle {
201    /// Complete text paint.
202    pub(crate) color: Color,
203    /// Font family.
204    pub(crate) font_family: crate::font::canonical::FontStack,
205    /// Font size in actual CSS pixels.
206    pub font_size: f64,
207    /// Closed font-weight policy.
208    pub weight: crate::text::TextWeight,
209    /// Horizontal alignment anchor. Default: `Start`.
210    pub anchor: TextAnchor,
211    /// Rotation angle in degrees (clockwise). Default: `0.0`.
212    pub rotation: f64,
213}
214
215/// A significance bracket drawn inside the plot panel: a horizontal
216/// line spanning two x-positions, with a vertical tick at each end
217/// and a glyph (e.g. "***") above the midpoint.
218#[derive(Debug, Clone)]
219pub struct SignificanceBracket {
220    /// X position of the left tick.
221    pub x_left: f64,
222    /// X position of the right tick.
223    pub x_right: f64,
224    /// Y position of the bracket.
225    pub y: f64,
226    /// Glyph string ("ns", "*", "**", "***", "****").
227    pub label: String,
228    /// Whether the span runs along x above marks or along y to their right.
229    pub orientation: BracketOrientation,
230}
231
232/// Semantic role of a named backend layer.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
234pub enum LayerRole {
235    /// Ordinary layer emitted in call order.
236    #[default]
237    Generic,
238    /// Grid layer that must render behind data marks.
239    Grid,
240}
241
242/// Ownership role for an ordered painted surface.
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244pub(crate) enum SurfaceRole {
245    /// Canvas-owned root surface.
246    CanvasRoot,
247    /// Plot-owned panel surface.
248    PlotPanel,
249}
250
251/// Orientation of a pairwise significance bracket.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum BracketOrientation {
254    /// Span two x anchors at a fixed y position.
255    Vertical,
256    /// Span two y anchors at a fixed x position. In this orientation,
257    /// `x_left`/`x_right` store bottom/top y anchors and `y` stores x.
258    Horizontal,
259}
260
261pub(crate) const POLYGON_MITER_LIMIT: f64 = 4.0;
262
263/// Visual style for a significance bracket.
264#[derive(Debug, Clone)]
265pub struct BracketStyle {
266    /// Complete bracket-path stroke paint.
267    pub(crate) color: Color,
268    /// Complete bracket-label text paint.
269    pub(crate) label_color: Color,
270    /// Stroke width in pixels.
271    pub width: f32,
272    /// Label font family.
273    pub(crate) font_family: crate::font::canonical::FontStack,
274    /// Label font size in pixels.
275    pub font_size: f64,
276    /// Label line height in pixels.
277    pub(crate) line_height: f64,
278    /// Label font weight.
279    pub weight: crate::text::TextWeight,
280    /// Gap between the bracket line and its label.
281    pub label_gap: f64,
282    /// Retained selected tick height; canonical validation has no default.
283    pub(crate) tick_height: f64,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287pub(crate) enum PlannedTextOrigin {
288    Middle,
289    Baseline,
290}
291
292#[derive(Debug, Clone, Copy, PartialEq)]
293pub(crate) struct PlannedTextPlacement {
294    pub(crate) position: Point2D,
295    pub(crate) anchor: TextAnchor,
296    pub(crate) rotation: f64,
297    pub(crate) origin: PlannedTextOrigin,
298    /// Physical column order for existing outward-stacked rotated axis titles.
299    pub(crate) reverse_lines: bool,
300}
301
302#[derive(Debug, Clone)]
303pub(crate) struct PlacedText {
304    pub(crate) plan: ResolvedTextPlan,
305    pub(crate) placement: PlannedTextPlacement,
306}
307
308pub(crate) fn reserve_text_records<T>(
309    records: &mut Vec<T>,
310    additional: usize,
311) -> Result<(), Error> {
312    if additional > records.capacity() - records.len() {
313        let capacity = records
314            .len()
315            .checked_add(additional)
316            .zip(records.capacity().checked_mul(2))
317            .map(|(required, doubled)| required.max(doubled).max(4))
318            .ok_or_else(|| Error::Render("producer text capacity overflow".into()))?;
319
320        crate::operation::check()?;
321        records
322            .try_reserve_exact(capacity - records.len())
323            .map_err(|_| Error::Render("producer text allocation failed".into()))?;
324    }
325    Ok(())
326}
327
328impl PlacedText {
329    pub(crate) fn middle(
330        plan: ResolvedTextPlan,
331        position: Point2D,
332        anchor: TextAnchor,
333        rotation: f64,
334    ) -> Result<Self, Error> {
335        Ok(Self {
336            placement: crate::layout::text::placement::resolve(
337                PlannedTextPlacement::middle(position, anchor, rotation),
338                &plan,
339                None,
340            )?,
341            plan,
342        })
343    }
344    pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
345        backend.draw_planned_text(self.placement, &self.plan)
346    }
347
348    pub(crate) fn with_reversed_lines(mut self) -> Self {
349        self.placement.reverse_lines = true;
350        self
351    }
352}
353
354impl PlannedTextPlacement {
355    pub(crate) fn line_y(self, plan: &ResolvedTextPlan, y: i64) -> Result<i64, Error> {
356        if !self.reverse_lines {
357            return Ok(y);
358        }
359        plan.last_baseline_quanta
360            .unwrap_or(0)
361            .checked_sub(y)
362            .and_then(|offset| plan.first_baseline_quanta.unwrap_or(0).checked_add(offset))
363            .ok_or_else(|| Error::Render("reversed text line placement overflowed".into()))
364    }
365    pub(crate) const fn middle(position: Point2D, anchor: TextAnchor, rotation: f64) -> Self {
366        Self {
367            position,
368            anchor,
369            rotation,
370            origin: PlannedTextOrigin::Middle,
371            reverse_lines: false,
372        }
373    }
374
375    pub(crate) const fn baseline(position: Point2D, anchor: TextAnchor, rotation: f64) -> Self {
376        Self {
377            position,
378            anchor,
379            rotation,
380            origin: PlannedTextOrigin::Baseline,
381            reverse_lines: false,
382        }
383    }
384}
385
386#[derive(Debug, Clone, Copy)]
387pub(crate) struct PlannedSignificanceCall<'a> {
388    pub(crate) bracket: &'a SignificanceBracket,
389    pub(crate) style: &'a BracketStyle,
390    pub(crate) label: &'a DeferredAnnotationTextPlan,
391}
392
393/// The `Backend` trait. Every concrete renderer (Plotters,
394/// future Skia, future Vello) implements this.
395///
396/// All draw methods take a mutable `&mut self` and return
397/// `Result<(), Error>`. Backends may buffer internally and
398/// only emit output on `end()` (or `finalize()`).
399///
400/// Geometry passed to raw draw methods is already projected into math-style
401/// canvas coordinates: X increases rightward and Y increases upward. Data
402/// scaling and panel placement are renderer responsibilities, not backend
403/// responsibilities. Canonical methods consume retained top-down operands for
404/// the selected canvas and must not delegate back through raw draw methods.
405pub trait Backend {
406    /// Draw a fixed image or frozen scene in its admitted top-down frame.
407    fn draw_fixed_content(
408        &mut self,
409        _content: &crate::composition::PlacedContent,
410    ) -> Result<(), Error> {
411        Err(Error::Render(
412            "backend does not support fixed image content".into(),
413        ))
414    }
415    /// Begin a semantic batch in the actual native capture.
416    #[doc(hidden)]
417    fn begin_paint_batch(
418        &mut self,
419        _reference: &crate::layout::PaintBatchRef,
420    ) -> Result<(), Error> {
421        Ok(())
422    }
423
424    /// Finish the semantic batch after its drawing scopes have closed.
425    #[doc(hidden)]
426    fn end_paint_batch(&mut self) -> Result<(), Error> {
427        Ok(())
428    }
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: f64, height: f64) -> 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(
681            format!(
682                "line width must be finite and non-negative; got {}",
683                style.width
684            )
685            .into(),
686        ))
687    }
688}
689
690pub(crate) fn validate_fill_style(style: &FillStyle) -> Result<(), Error> {
691    if !style.stroke_width.is_finite() || style.stroke_width < 0.0 {
692        return Err(Error::Render(
693            format!(
694                "fill stroke width must be finite and non-negative; got {}",
695                style.stroke_width
696            )
697            .into(),
698        ));
699    }
700    Ok(())
701}
702
703pub(crate) fn validate_linear_gradient(
704    bounds: PixelRect,
705    start: Point2D,
706    end: Point2D,
707    stops: &[GradientStop],
708) -> Result<CanonicalGradient, Error> {
709    coordinates::canonical_gradient(bounds, start, end, stops)
710}
711
712pub(crate) fn validate_text_style(style: &TextStyle) -> Result<(), Error> {
713    if style.rotation.is_finite() {
714        Ok(())
715    } else {
716        Err(Error::Render(
717            format!("text rotation must be finite; got {}", style.rotation).into(),
718        ))
719    }
720}
721
722pub(crate) fn validate_text(position: Point2D, style: &TextStyle) -> Result<CanonicalText, Error> {
723    validate_text_style(style)?;
724    coordinates::canonical_text(
725        position,
726        style.rotation,
727        coordinates::CoordinatePrecision::CssQuantum,
728    )
729}
730
731pub(crate) fn planned_text_style(
732    placement: PlannedTextPlacement,
733    plan: &ResolvedTextPlan,
734) -> Result<TextStyle, Error> {
735    Ok(TextStyle {
736        color: plan.style.paint,
737        font_family: plan
738            .copy_stack()
739            .map_err(|error| Error::Render(error.to_string().into()))?,
740        font_size: plan.style.font_size,
741        weight: plan.style.weight,
742        anchor: placement.anchor,
743        rotation: placement.rotation,
744    })
745}
746
747pub(crate) const fn nearest_even_text_half(value: i64) -> Option<i64> {
748    if value < 0 {
749        return None;
750    }
751    let quotient = value / 2;
752    if value % 2 == 0 || quotient % 2 == 0 {
753        Some(quotient)
754    } else {
755        quotient.checked_add(1)
756    }
757}
758
759pub(crate) fn validate_planned_text(
760    placement: PlannedTextPlacement,
761    plan: &ResolvedTextPlan,
762) -> Result<CanonicalText, Error> {
763    let canonical = coordinates::canonical_text(
764        placement.position,
765        placement.rotation,
766        coordinates::CoordinatePrecision::CssQuantum,
767    )?;
768    validate_text_plan(placement, plan)?;
769    Ok(canonical)
770}
771
772#[expect(
773    clippy::too_many_lines,
774    reason = "one protocol validator checks linked immutable style, line, discretionary-break, and glyph spans"
775)]
776pub(crate) fn validate_text_plan(
777    placement: PlannedTextPlacement,
778    plan: &ResolvedTextPlan,
779) -> Result<(), Error> {
780    let expected_alignment = match placement.anchor {
781        TextAnchor::Start => PhysicalTextAlignment::Start,
782        TextAnchor::Middle => PhysicalTextAlignment::Center,
783        TextAnchor::End => PhysicalTextAlignment::End,
784    };
785    if plan.style.alignment != expected_alignment {
786        return Err(Error::Render(
787            "planned text alignment does not match its backend placement".into(),
788        ));
789    }
790    if !plan.style.font_size.is_finite()
791        || plan.style.font_size <= 0.0
792        || plan.style.stack_source.is_empty()
793        || plan.style.stack.is_empty()
794        || plan.style.line_height_quanta <= 0
795        || plan.line_pitch_quanta <= 0
796        || plan.width_quanta < 0
797        || plan.height_quanta < 0
798    {
799        return Err(Error::Render(
800            "planned text has invalid resolved style or dimensions".into(),
801        ));
802    }
803    let valid_span = |start: u32, end: u32| {
804        let start = start as usize;
805        let end = end as usize;
806        start <= end
807            && end <= plan.source.len()
808            && plan.source.is_char_boundary(start)
809            && plan.source.is_char_boundary(end)
810    };
811    let valid_ink = |left: i64, bottom: i64, right: i64, top: i64| left <= right && bottom <= top;
812    match (plan.lines.first(), plan.lines.last()) {
813        (Some(first), Some(last)) => {
814            if plan.first_baseline_quanta != Some(first.translation_y_quanta)
815                || plan.last_baseline_quanta != Some(last.translation_y_quanta)
816                || plan.height_quanta == 0
817            {
818                return Err(Error::Render(
819                    "planned text baselines do not match its stored lines".into(),
820                ));
821            }
822        }
823        (None, None) => {
824            if plan.first_baseline_quanta.is_some()
825                || plan.last_baseline_quanta.is_some()
826                || plan.width_quanta != 0
827                || plan.height_quanta != 0
828            {
829                return Err(Error::Render(
830                    "empty planned text has nonempty metrics".into(),
831                ));
832            }
833        }
834        _ => unreachable!("a slice cannot have only one of first/last"),
835    }
836    for (index, line) in plan.lines.iter().enumerate() {
837        placement.line_y(plan, line.translation_y_quanta)?;
838        if let Some(soft) = line.selected_soft_hyphen {
839            if !valid_span(soft.start_byte, soft.end_byte)
840                || soft.start_byte < line.source_span.start_byte
841                || soft.end_byte != line.source_span.end_byte
842                || &plan.source[soft.start_byte as usize..soft.end_byte as usize] != "\u{ad}"
843                || !line.runs.iter().any(|run| {
844                    run.source_span.start_byte <= soft.start_byte
845                        && run.source_span.end_byte >= soft.end_byte
846                })
847            {
848                return Err(Error::Render(
849                    "planned text has an invalid selected soft-hyphen span or run".into(),
850                ));
851            }
852        }
853        let expected_y = plan
854            .first_baseline_quanta
855            .and_then(|first| {
856                i64::try_from(index)
857                    .ok()
858                    .and_then(|index| plan.line_pitch_quanta.checked_mul(index))
859                    .and_then(|offset| first.checked_add(offset))
860            })
861            .ok_or_else(|| Error::Render("planned text line offset overflow".into()))?;
862        if line.translation_y_quanta != expected_y
863            || !valid_span(line.source_span.start_byte, line.source_span.end_byte)
864            || line
865                .ink_quanta
866                .is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
867        {
868            return Err(Error::Render(
869                "planned text has an invalid line span, translation, or ink box".into(),
870            ));
871        }
872        for run in &line.runs {
873            if !valid_span(run.source_span.start_byte, run.source_span.end_byte)
874                || run.source_span.start_byte < line.source_span.start_byte
875                || run.source_span.end_byte > line.source_span.end_byte
876                || run.units_per_em == 0
877                || run
878                    .ink_quanta
879                    .is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
880                || run.glyphs.iter().any(|glyph| {
881                    glyph
882                        .ink_quanta
883                        .is_some_and(|ink| !valid_ink(ink.left, ink.bottom, ink.right, ink.top))
884                })
885            {
886                return Err(Error::Render(
887                    "planned text has an invalid shaped run or glyph ink box".into(),
888                ));
889            }
890        }
891    }
892    Ok(())
893}
894
895pub(crate) fn validate_rounded_rect(
896    x: f64,
897    y: f64,
898    width: f64,
899    height: f64,
900    radius: f64,
901) -> Result<CanonicalRoundedRect, Error> {
902    coordinates::canonical_rounded_rect(x, y, width, height, radius)
903}
904
905pub(crate) fn validate_bracket(
906    bracket: &SignificanceBracket,
907    style: &BracketStyle,
908) -> Result<CanonicalBracket, Error> {
909    if !style.width.is_finite() || style.width < 0.0 {
910        return Err(Error::Render(
911            format!(
912                "bracket width must be finite and non-negative; got {}",
913                style.width
914            )
915            .into(),
916        ));
917    }
918    if !style.font_size.is_finite()
919        || style.font_size <= 0.0
920        || !style.line_height.is_finite()
921        || style.line_height <= 0.0
922        || !style.label_gap.is_finite()
923        || style.label_gap < 0.0
924        || !style.tick_height.is_finite()
925        || style.tick_height < 0.0
926    {
927        return Err(Error::Render(
928            "bracket style requires positive font size and line height and finite nonnegative gap and tick height"
929                .into(),
930        ));
931    }
932    coordinates::canonical_bracket(bracket, style.tick_height, style.label_gap)
933}
934
935pub(crate) fn planned_bracket_placement(
936    canonical: CanonicalBracket,
937    plan: &ResolvedTextPlan,
938) -> Result<PlannedTextPlacement, Error> {
939    let position = canonical.label_position.value();
940    let default = match canonical.orientation {
941        BracketOrientation::Vertical => {
942            PlannedTextPlacement::baseline(position, TextAnchor::Middle, 0.0)
943        }
944        BracketOrientation::Horizontal => {
945            PlannedTextPlacement::middle(position, TextAnchor::Start, 0.0)
946        }
947    };
948    crate::layout::text::placement::resolve(default, plan, None)
949}
950
951pub(crate) fn validate_planned_bracket(
952    call: PlannedSignificanceCall<'_>,
953) -> Result<CanonicalBracket, Error> {
954    let canonical = validate_bracket(call.bracket, call.style)?;
955    validate_bracket_label(canonical, call)?;
956    Ok(canonical)
957}
958
959pub(crate) fn validate_bracket_label(
960    canonical: CanonicalBracket,
961    call: PlannedSignificanceCall<'_>,
962) -> Result<(), Error> {
963    let plan = &call.label.plan;
964    validate_text_plan(planned_bracket_placement(canonical, plan)?, plan)?;
965    if call.label.exact_override != plan.style.exact_override
966        || call.bracket.label != plan.original_source()
967        || call.style.label_color != plan.style.paint
968        || !plan.same_stack(&call.style.font_family)
969        || call.style.font_size.to_bits() != plan.style.font_size.to_bits()
970        || call.style.weight != plan.style.weight
971    {
972        return Err(Error::Render(
973            "planned significance label does not match its frozen source and style".into(),
974        ));
975    }
976    Ok(())
977}
978
979pub(crate) fn with_clip<T>(
980    backend: &mut dyn Backend,
981    region: PixelRect,
982    draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
983) -> Result<T, Error> {
984    backend.begin_clip(region)?;
985    finish_scope(draw(backend), backend.end_clip(), "clip scope")
986}
987
988pub(crate) fn with_paint<T>(
989    backend: &mut dyn Backend,
990    owner: &crate::layout::PanelPath,
991    role: crate::layout::PaintRole,
992    layer: Option<crate::elements::LayerSlot>,
993    draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
994) -> Result<T, Error> {
995    backend.begin_paint_batch(&crate::layout::PaintBatchRef::new(owner, role, layer))?;
996    finish_scope(
997        draw(backend),
998        backend.end_paint_batch(),
999        "semantic paint batch",
1000    )
1001}
1002
1003pub(crate) fn with_layer<T>(
1004    backend: &mut dyn Backend,
1005    name: &str,
1006    draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
1007) -> Result<T, Error> {
1008    backend.begin_layer(name)?;
1009    finish_scope(
1010        draw(backend),
1011        backend.end_layer(),
1012        &format!("layer {name:?}"),
1013    )
1014}
1015
1016pub(crate) fn with_layer_role<T>(
1017    backend: &mut dyn Backend,
1018    name: &str,
1019    role: LayerRole,
1020    draw: impl FnOnce(&mut dyn Backend) -> Result<T, Error>,
1021) -> Result<T, Error> {
1022    backend.begin_layer_with_role(name, role)?;
1023    finish_scope(
1024        draw(backend),
1025        backend.end_layer(),
1026        &format!("layer {name:?}"),
1027    )
1028}
1029
1030pub(crate) fn finish_scope<T>(
1031    primary: Result<T, Error>,
1032    cleanup: Result<(), Error>,
1033    scope: &str,
1034) -> Result<T, Error> {
1035    match (primary, cleanup) {
1036        (Ok(value), Ok(())) => Ok(value),
1037        (Err(primary), Ok(())) => Err(primary),
1038        (Ok(_), Err(cleanup)) => Err(Error::Render(
1039            format!("failed to close {scope}: {cleanup}").into(),
1040        )),
1041        (Err(primary), Err(cleanup)) => match primary {
1042            Error::Render(diagnostic) => Err(Error::Render(diagnostic.map_message(|message| {
1043                format!("{message}; additionally failed to close {scope}: {cleanup}")
1044            }))),
1045            Error::Data(diagnostic) => Err(Error::Data(diagnostic.map_message(|message| {
1046                format!("{message}; additionally failed to close {scope}: {cleanup}")
1047            }))),
1048            error => Err(error),
1049        },
1050    }
1051}