Skip to main content

lichtung_plot/layout/
root_geometry.rs

1//! Exact authored paper sizes, layout budgets and device sampling geometry.
2
3use num_bigint::{BigInt, BigUint};
4
5use crate::{output::PngSizing, Error, Result};
6
7const CSS_PIXELS_PER_INCH: u32 = 96;
8
9/// Absolute publication units. A point is 1/72 inch (CSS/PDF point).
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SizeUnit {
12    /// International inch.
13    Inch,
14    /// Centimeter (2.54 per inch).
15    Centimeter,
16    /// Millimeter (25.4 per inch).
17    Millimeter,
18    /// CSS or PDF point, not a TeX point.
19    Point,
20}
21
22impl SizeUnit {
23    const fn css_ratio(self) -> (u32, u32) {
24        match self {
25            Self::Inch => (CSS_PIXELS_PER_INCH, 1),
26            Self::Centimeter => (4800, 127),
27            Self::Millimeter => (480, 127),
28            Self::Point => (4, 3),
29        }
30    }
31
32    pub(crate) const fn suffix(self) -> &'static str {
33        match self {
34            Self::Inch => "in",
35            Self::Centimeter => "cm",
36            Self::Millimeter => "mm",
37            Self::Point => "pt",
38        }
39    }
40}
41
42/// The original physical size request of an uncropped frozen page.
43///
44/// Width and height are the exact represented author inputs, in the selected
45/// unit. They are independent of layout quantization and raster density.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct PhysicalSize {
48    width: u64,
49    height: u64,
50    unit: SizeUnit,
51}
52
53impl PhysicalSize {
54    /// The authored width in `unit()`.
55    #[must_use]
56    pub const fn width(&self) -> f64 {
57        f64::from_bits(self.width)
58    }
59
60    /// The authored height in `unit()`.
61    #[must_use]
62    pub const fn height(&self) -> f64 {
63        f64::from_bits(self.height)
64    }
65
66    /// The authored absolute publication unit.
67    #[must_use]
68    pub const fn unit(&self) -> SizeUnit {
69        self.unit
70    }
71
72    fn exact_lengths(self) -> Result<[ExactLength; 2]> {
73        let (numerator, denominator) = self.unit.css_ratio();
74        let length = |value| -> Result<ExactLength> {
75            let mut length = ExactLength::binary64(value)?;
76            length.numerator *= numerator;
77            length.denominator *= denominator;
78            Ok(length)
79        };
80        Ok([length(self.width())?, length(self.height())?])
81    }
82}
83
84/// Exact mathematical CSS length; scratch arithmetic is bounded by the
85/// original finite binary64 operands and the small absolute-unit ratios.
86struct ExactLength {
87    numerator: BigUint,
88    denominator: BigUint,
89}
90
91impl ExactLength {
92    fn binary64(value: f64) -> Result<Self> {
93        if !value.is_finite() || value <= 0.0 {
94            return Err(Error::Render(
95                "page and device dimensions must be positive and finite".into(),
96            ));
97        }
98        Ok(Self {
99            numerator: crate::numeric::binary::units(value)?.into_parts().1,
100            denominator: BigUint::from(1_u8) << 1074,
101        })
102    }
103
104    fn rounded(&self) -> Result<f64> {
105        crate::numeric::binary::signed_ratio(
106            BigInt::from(self.numerator.clone()),
107            self.denominator.clone(),
108        )
109    }
110
111    #[expect(
112        clippy::cast_precision_loss,
113        reason = "the layout budget is bounded by u32::MAX CSS pixels in spatial quanta"
114    )]
115    fn layout_budget(&self) -> Result<f64> {
116        if self.numerator > &self.denominator * u32::MAX {
117            return Err(Error::Render(
118                "physical page exceeds the layout coordinate range".into(),
119            ));
120        }
121        let quanta =
122            u64::try_from((&self.numerator << 10_usize) / &self.denominator).map_err(|_| {
123                Error::Render("physical page exceeds the layout coordinate range".into())
124            })?;
125        Ok(quanta as f64 / 1024.0)
126    }
127
128    fn raster_dimension(&self, scale: &Self, dpi: bool) -> Result<u32> {
129        let numerator = &self.numerator * &scale.numerator;
130        let mut denominator = &self.denominator * &scale.denominator;
131        if dpi {
132            denominator *= CSS_PIXELS_PER_INCH;
133        }
134        round_pixels(numerator, &denominator, false)
135    }
136
137    fn companion(&self, fixed: &Self, pixels: u32) -> Result<u32> {
138        let numerator = &self.numerator * &fixed.denominator * pixels;
139        let denominator = &self.denominator * &fixed.numerator;
140        round_pixels(numerator, &denominator, true)
141    }
142}
143
144fn round_pixels(numerator: BigUint, denominator: &BigUint, ceil: bool) -> Result<u32> {
145    let quotient = &numerator / denominator;
146    let remainder = numerator % denominator;
147    let increment = if ceil {
148        remainder.bits() != 0
149    } else {
150        (&remainder << 1_usize) >= *denominator
151    };
152    u32::try_from(quotient + u32::from(increment))
153        .map_err(|_| Error::Render("computed PNG dimensions exceed the conversion limit".into()))
154}
155
156/// PNG pHYs is integer pixels per meter. An inch is exactly 127/5000 m.
157pub(crate) fn dpi_to_pixels_per_meter(dpi: f64) -> Result<u32> {
158    let density = ExactLength::binary64(dpi)?;
159    let pixels = round_pixels(
160        density.numerator * 5000_u32,
161        &(density.denominator * 127_u32),
162        false,
163    )
164    .map_err(|_| Error::Render(format!("png dpi is too large to encode: {dpi}").into()))?;
165    if pixels == 0 {
166        return Err(Error::Render(
167            format!("png dpi is too small to encode: {dpi}").into(),
168        ));
169    }
170    Ok(pixels)
171}
172
173/// One immutable root geometry. The viewport is the actual CSS page size;
174/// the layout budget is the largest inward quantum-aligned rectangle. The
175/// residual belongs to the root, never to a raster target or child allocation.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub(crate) struct RootSize {
178    viewport: [u64; 2],
179    budget: [u64; 2],
180    physical: Option<PhysicalSize>,
181}
182
183impl RootSize {
184    pub(crate) fn new(width: impl Into<f64>, height: impl Into<f64>) -> Self {
185        Self::css(width.into(), height.into())
186    }
187
188    pub(crate) const fn css(width: f64, height: f64) -> Self {
189        Self {
190            viewport: [width.to_bits(), height.to_bits()],
191            budget: [
192                ((width * 1024.0).floor() / 1024.0).to_bits(),
193                ((height * 1024.0).floor() / 1024.0).to_bits(),
194            ],
195            physical: None,
196        }
197    }
198
199    pub(crate) fn with_unit(width: f64, height: f64, unit: SizeUnit) -> Result<Self> {
200        let physical = PhysicalSize {
201            width: width.to_bits(),
202            height: height.to_bits(),
203            unit,
204        };
205        let [x, y] = physical.exact_lengths()?;
206        let size = Self {
207            viewport: [x.rounded()?.to_bits(), y.rounded()?.to_bits()],
208            budget: [x.layout_budget()?.to_bits(), y.layout_budget()?.to_bits()],
209            physical: Some(physical),
210        };
211        size.dimensions()?;
212        Ok(size)
213    }
214
215    pub(crate) fn dimensions(self) -> Result<(f64, f64)> {
216        let [width, height] = self.viewport.map(f64::from_bits);
217        let valid = |value: f64| value.is_finite() && value > 0.0 && value <= f64::from(u32::MAX);
218        if !valid(width)
219            || !valid(height)
220            || !self.budget.map(f64::from_bits).into_iter().all(valid)
221        {
222            return Err(Error::Render(
223                "layout root dimensions must be finite, positive and representable".into(),
224            ));
225        }
226        Ok((width, height))
227    }
228
229    pub(crate) fn layout_dimensions(self) -> Result<(f64, f64)> {
230        self.dimensions()?;
231        let [width, height] = self.budget.map(f64::from_bits);
232        Ok((width, height))
233    }
234
235    /// Finish a root's content-driven height, or retain its original exact
236    /// viewport after proving the measured frame stays inside its inward budget.
237    pub(crate) fn finish_height(self, height: f64, automatic: bool) -> Result<Self> {
238        if automatic {
239            return Ok(Self::new(
240                self.dimensions()?.0,
241                super::kernel::root_dimension(height)?,
242            ));
243        }
244        let budget = self.layout_dimensions()?.1;
245        if height <= 0.0
246            || super::kernel::ceil_spatial_quanta(height)?
247                > super::kernel::ceil_spatial_quanta(budget)?
248        {
249            return Err(Error::Render(
250                "measured content exceeds the exact root height".into(),
251            ));
252        }
253        Ok(self)
254    }
255
256    pub(crate) const fn physical_size(self) -> Option<PhysicalSize> {
257        self.physical
258    }
259
260    fn exact_lengths(self) -> Result<[ExactLength; 2]> {
261        if let Some(physical) = self.physical {
262            physical.exact_lengths()
263        } else {
264            let (width, height) = self.dimensions()?;
265            Ok([
266                ExactLength::binary64(width)?,
267                ExactLength::binary64(height)?,
268            ])
269        }
270    }
271
272    pub(crate) fn raster_dimensions(self, sizing: PngSizing) -> Result<(u32, u32)> {
273        let [x, y] = self.exact_lengths()?;
274        match sizing {
275            PngSizing::Width(width) => Ok((width, y.companion(&x, width)?)),
276            PngSizing::Height(height) => Ok((x.companion(&y, height)?, height)),
277            PngSizing::Source | PngSizing::Scale(_) | PngSizing::Dpi(_) => {
278                let scale = match sizing {
279                    PngSizing::Source => 1.0,
280                    PngSizing::Scale(scale) | PngSizing::Dpi(scale) => scale,
281                    _ => unreachable!("scale-based raster sizing"),
282                };
283                let scale = ExactLength::binary64(scale)?;
284                let dpi = matches!(sizing, PngSizing::Dpi(_));
285                Ok((
286                    x.raster_dimension(&scale, dpi)?,
287                    y.raster_dimension(&scale, dpi)?,
288                ))
289            }
290        }
291    }
292
293    // The target supplies both rounded dimensions. Admit a pair if a
294    // uniform sampling scale can give it, or if it is the exact pair from
295    // one dimension plus the existing outward companion rounding.
296    pub(crate) fn supports_raster_dimensions(self, width: u32, height: u32) -> Result<bool> {
297        let [x_length, y_length] = self.exact_lengths()?;
298        let x = &x_length.numerator * &y_length.denominator;
299        let y = &y_length.numerator * &x_length.denominator;
300        let w = u64::from(width);
301        let h = u64::from(height);
302        if w == 0 || h == 0 {
303            return Ok(false);
304        }
305        let nearest = &y * (2 * w - 1) < &x * (2 * h + 1) && &x * (2 * h - 1) < &y * (2 * w + 1);
306        let by_width = &x * (h - 1) < &y * w && &y * w <= &x * h;
307        let by_height = &y * (w - 1) < &x * h && &x * h <= &y * w;
308        Ok(nearest || by_width || by_height)
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn equal_mathematical_units_and_inward_budget_preserve_exact_ratios() {
318        let reference = RootSize::with_unit(50.0, 100.0, SizeUnit::Inch).unwrap();
319        for (width, height, unit) in [
320            (127.0, 254.0, SizeUnit::Centimeter),
321            (1270.0, 2540.0, SizeUnit::Millimeter),
322            (3600.0, 7200.0, SizeUnit::Point),
323        ] {
324            let size = RootSize::with_unit(width, height, unit).unwrap();
325            assert_eq!(size.dimensions().unwrap(), reference.dimensions().unwrap());
326            assert_eq!(
327                size.raster_dimensions(PngSizing::Width(700)).unwrap(),
328                (700, 1400)
329            );
330        }
331        let below_inch = f64::from_bits(72.0_f64.to_bits() - 1);
332        let size = RootSize::with_unit(below_inch, 144.0, SizeUnit::Point).unwrap();
333        assert!(size.layout_dimensions().unwrap().0 < 96.0);
334        assert_eq!(
335            size.raster_dimensions(PngSizing::Source).unwrap(),
336            (96, 192)
337        );
338        assert!(size.finish_height(192.0 + 1.0 / 1024.0, false).is_err());
339    }
340
341    #[test]
342    fn exact_pixel_and_density_ties_do_not_use_epsilon() {
343        for (width, expected) in [
344            (f64::from_bits(769.0_f64.to_bits() - 1), 1922),
345            (769.0, 1923),
346            (f64::from_bits(769.0_f64.to_bits() + 1), 1923),
347        ] {
348            let size = RootSize::with_unit(width, 288.0, SizeUnit::Point).unwrap();
349            assert_eq!(
350                size.raster_dimensions(PngSizing::Dpi(180.0)).unwrap(),
351                (expected, 720)
352            );
353        }
354        let density_tie = 7.9375_f64;
355        assert_eq!(
356            dpi_to_pixels_per_meter(f64::from_bits(density_tie.to_bits() - 1)).unwrap(),
357            312
358        );
359        assert_eq!(dpi_to_pixels_per_meter(density_tie).unwrap(), 313);
360    }
361}