Skip to main content

lichtung_plot/output/
region.rs

1//! Call-local output framing. Rectangles and references have different
2//! coordinate frames once a composite has expanded its original viewport.
3
4use crate::{
5    layout::{InkExtent, Insets, Length, LengthUnit, PaintBatchRef, Rect, RectRef, RootSize},
6    scene::RenderedScene,
7    Error, Result,
8};
9
10use super::PngSizing;
11mod recipe;
12pub(super) use recipe::pad_schema;
13
14/// An absolute rectangle in the current output, or a rectangle selected from
15/// the actual original native layout and translated once into the output.
16#[derive(Debug, Clone, PartialEq)]
17#[non_exhaustive]
18pub enum RegionTarget {
19    /// Current output CSS coordinates.
20    Rect(Rect),
21    /// Actual frozen layout reference.
22    Reference(RectRef),
23}
24impl From<Rect> for RegionTarget {
25    fn from(rect: Rect) -> Self {
26        Self::Rect(rect)
27    }
28}
29impl From<RectRef> for RegionTarget {
30    fn from(reference: RectRef) -> Self {
31        Self::Reference(reference)
32    }
33}
34impl From<&RectRef> for RegionTarget {
35    fn from(reference: &RectRef) -> Self {
36        Self::Reference(reference.clone())
37    }
38}
39
40#[derive(Debug, Clone, PartialEq)]
41enum Selection {
42    Full,
43    Rect(RegionTarget),
44    Tight,
45}
46
47#[derive(Debug, Clone, PartialEq)]
48enum Padding {
49    Fixed(Insets),
50    Layout,
51}
52
53/// A publication-only frame, optionally derived from actual visible ink.
54/// The selected picture is clipped before its empty padding is added.
55#[derive(Debug, Clone, PartialEq)]
56#[must_use]
57pub struct ExportRegion {
58    selection: Selection,
59    padding: Option<Padding>,
60    include: Vec<RectRef>,
61    exclude: Vec<PaintBatchRef>,
62    within: Option<RegionTarget>,
63    coverage: Option<PngSizing>,
64}
65
66impl Default for ExportRegion {
67    fn default() -> Self {
68        Self::full()
69    }
70}
71
72impl ExportRegion {
73    /// Keep the complete frozen viewport.
74    pub const fn full() -> Self {
75        Self {
76            selection: Selection::Full,
77            padding: None,
78            include: Vec::new(),
79            exclude: Vec::new(),
80            within: None,
81            coverage: None,
82        }
83    }
84    /// Select a positive CSS rectangle or an actual frozen layout reference.
85    pub fn rect(target: impl Into<RegionTarget>) -> Self {
86        Self {
87            selection: Selection::Rect(target.into()),
88            ..Self::full()
89        }
90    }
91    /// Compute the visible content bounds, excluding structural native paper.
92    pub const fn tight() -> Self {
93        Self {
94            selection: Selection::Tight,
95            padding: None,
96            include: Vec::new(),
97            exclude: Vec::new(),
98            within: None,
99            coverage: None,
100        }
101    }
102    /// Add four absolute CSS-pixel padding lengths.
103    pub fn pad(mut self, insets: Insets) -> Self {
104        self.padding = Some(Padding::Fixed(insets));
105        self
106    }
107    /// Use the four actually resolved root-layout padding lengths.
108    pub fn pad_layout(mut self) -> Self {
109        self.padding = Some(Padding::Layout);
110        self
111    }
112    /// Add the selected actual allocation to the tight boundary.
113    /// This can deliberately retain a reserved slot that has no ink.
114    pub fn include(mut self, reference: RectRef) -> Self {
115        self.include.push(reference);
116        self
117    }
118    /// Exclude one actual closed native batch from the boundary computation,
119    /// while retaining its paint in the selected publication.
120    pub fn exclude(mut self, reference: PaintBatchRef) -> Self {
121        self.exclude.push(reference);
122        self
123    }
124    /// Restrict the search for tight bounds to this actual rectangle.
125    pub fn within(mut self, target: impl Into<RegionTarget>) -> Self {
126        self.within = Some(target.into());
127        self
128    }
129    /// Use explicit sampled alpha support rather than continuous vector ink
130    /// for the tight frame, at this independently selected resolution.
131    pub fn pixel_coverage(mut self, sizing: PngSizing) -> Self {
132        self.coverage = Some(sizing);
133        self
134    }
135    /// Whether the author already selected a padding policy.
136    pub fn has_padding(&self) -> bool {
137        self.padding.is_some()
138    }
139
140    pub(super) fn validate(&self) -> Result<()> {
141        if !matches!(self.selection, Selection::Tight)
142            && (!self.include.is_empty()
143                || !self.exclude.is_empty()
144                || self.within.is_some()
145                || self.coverage.is_some())
146        {
147            return Err(Error::Data(
148                "include, exclude, within and pixel coverage require a tight region".into(),
149            ));
150        }
151        if let Some(Padding::Fixed(insets)) = &self.padding {
152            absolute_insets(insets)?;
153        }
154        if let Some(sizing) = self.coverage {
155            crate::render::svg_backend::validate_png_sizing(sizing)?;
156        }
157        Ok(())
158    }
159
160    pub(crate) fn resolve(&self, scene: &RenderedScene) -> Result<RegionPlan> {
161        self.validate()?;
162        let viewport = scene.viewport()?;
163        let selected = match &self.selection {
164            Selection::Full => viewport,
165            Selection::Rect(target) => resolve_target(scene, target)?,
166            Selection::Tight => self.tight_bounds(scene, viewport)?,
167        };
168        if selected.width() <= 0. || selected.height() <= 0. {
169            return Err(Error::Data(
170                "publication region must have positive dimensions".into(),
171            ));
172        }
173        let padding = match &self.padding {
174            Some(Padding::Fixed(insets)) => absolute_insets(insets)?,
175            Some(Padding::Layout) => scene.layout_report()?.root_padding(),
176            None if matches!(self.selection, Selection::Tight) => [9.6; 4],
177            None => [0.; 4],
178        };
179        let size = if selected == viewport && padding.iter().all(|&value| value == 0.) {
180            scene.size()
181        } else {
182            RootSize::new(
183                selected.width() + padding[0] + padding[1],
184                selected.height() + padding[2] + padding[3],
185            )
186        };
187        size.dimensions()?;
188        Ok(RegionPlan {
189            selected,
190            padding,
191            size,
192            viewport,
193        })
194    }
195
196    fn tight_bounds(&self, scene: &RenderedScene, viewport: Rect) -> Result<Rect> {
197        let scope = self
198            .within
199            .as_ref()
200            .map(|target| resolve_target(scene, target))
201            .transpose()?
202            .unwrap_or(viewport);
203        let Some(clip) = scope.intersection(viewport) else {
204            return Err(Error::Data(
205                "tight search region has no intersection with the output viewport".into(),
206            ));
207        };
208        let mut included = InkExtent::Empty;
209        for reference in &self.include {
210            if let Some(rect) = scene.resolve_rect(reference)?.intersection(clip) {
211                included = included.union(InkExtent::Bounds(rect));
212            }
213        }
214        let ink = scene.tight_ink(clip, &self.exclude, self.coverage, included)?;
215        match ink {
216            InkExtent::Empty=>Ok(clip),
217            InkExtent::Bounds(bounds)=>outward(bounds),
218            InkExtent::Unknown=>Err(Error::Render("cannot determine actual visible ink for a tight region; use an explicit rectangle or pixel coverage".into())),
219        }
220    }
221}
222
223fn resolve_target(scene: &RenderedScene, target: &RegionTarget) -> Result<Rect> {
224    match target {
225        RegionTarget::Rect(rect) => Ok(*rect),
226        RegionTarget::Reference(reference) => scene.resolve_rect(reference),
227    }
228}
229
230pub(crate) fn absolute_insets(insets: &Insets) -> Result<[f64; 4]> {
231    let pixels = |length: &Length| {
232        let value = length.value().as_f64();
233        if length.unit() == LengthUnit::Px || value == 0. {
234            Ok(value)
235        } else {
236            Err(Error::Data(
237                "publication padding requires absolute CSS-pixel lengths".into(),
238            ))
239        }
240    };
241    Ok([
242        pixels(insets.get_left())?,
243        pixels(insets.get_right())?,
244        pixels(insets.get_top())?,
245        pixels(insets.get_bottom())?,
246    ])
247}
248
249pub(crate) fn outward(bounds: Rect) -> Result<Rect> {
250    let left = (bounds.left() * 1024.).floor() / 1024.;
251    let top = (bounds.top() * 1024.).floor() / 1024.;
252    let right = ((bounds.left() + bounds.width()) * 1024.).ceil() / 1024.;
253    let bottom = ((bounds.top() + bounds.height()) * 1024.).ceil() / 1024.;
254    Rect::new(left, top, right - left, bottom - top)
255}
256
257#[derive(Debug, Clone, Copy)]
258pub(crate) struct RegionPlan {
259    pub(crate) selected: Rect,
260    /// left, right, top, bottom
261    pub(crate) padding: [f64; 4],
262    pub(crate) size: RootSize,
263    pub(crate) viewport: Rect,
264}
265
266impl RegionPlan {
267    pub(crate) fn full_viewport(self) -> bool {
268        self.selected == self.viewport && self.padding.iter().all(|&value| value == 0.)
269    }
270}