1use num_bigint::{BigInt, BigUint};
4
5use crate::{output::PngSizing, Error, Result};
6
7const CSS_PIXELS_PER_INCH: u32 = 96;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SizeUnit {
12 Inch,
14 Centimeter,
16 Millimeter,
18 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct PhysicalSize {
48 width: u64,
49 height: u64,
50 unit: SizeUnit,
51}
52
53impl PhysicalSize {
54 #[must_use]
56 pub const fn width(&self) -> f64 {
57 f64::from_bits(self.width)
58 }
59
60 #[must_use]
62 pub const fn height(&self) -> f64 {
63 f64::from_bits(self.height)
64 }
65
66 #[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
84struct 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
156pub(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#[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 let viewport = [width.into(), height.into()];
186 Self {
187 viewport: viewport.map(f64::to_bits),
188 budget: viewport.map(|value| ((value * 1024.0).floor() / 1024.0).to_bits()),
189 physical: None,
190 }
191 }
192
193 pub(crate) fn with_unit(width: f64, height: f64, unit: SizeUnit) -> Result<Self> {
194 let physical = PhysicalSize {
195 width: width.to_bits(),
196 height: height.to_bits(),
197 unit,
198 };
199 let [x, y] = physical.exact_lengths()?;
200 let size = Self {
201 viewport: [x.rounded()?.to_bits(), y.rounded()?.to_bits()],
202 budget: [x.layout_budget()?.to_bits(), y.layout_budget()?.to_bits()],
203 physical: Some(physical),
204 };
205 size.dimensions()?;
206 Ok(size)
207 }
208
209 pub(crate) fn dimensions(self) -> Result<(f64, f64)> {
210 let [width, height] = self.viewport.map(f64::from_bits);
211 let valid = |value: f64| value.is_finite() && value > 0.0 && value <= f64::from(u32::MAX);
212 if !valid(width)
213 || !valid(height)
214 || !self.budget.map(f64::from_bits).into_iter().all(valid)
215 {
216 return Err(Error::Render(
217 "layout root dimensions must be finite, positive and representable".into(),
218 ));
219 }
220 Ok((width, height))
221 }
222
223 pub(crate) fn layout_dimensions(self) -> Result<(f64, f64)> {
224 self.dimensions()?;
225 let [width, height] = self.budget.map(f64::from_bits);
226 Ok((width, height))
227 }
228
229 pub(crate) fn finish_height(self, height: f64, automatic: bool) -> Result<Self> {
232 if automatic {
233 return Ok(Self::new(
234 self.dimensions()?.0,
235 super::kernel::root_dimension(height)?,
236 ));
237 }
238 let budget = self.layout_dimensions()?.1;
239 if height <= 0.0
240 || super::kernel::ceil_spatial_quanta(height)?
241 > super::kernel::ceil_spatial_quanta(budget)?
242 {
243 return Err(Error::Render(
244 "measured content exceeds the exact root height".into(),
245 ));
246 }
247 Ok(self)
248 }
249
250 pub(crate) const fn physical_size(self) -> Option<PhysicalSize> {
251 self.physical
252 }
253
254 fn exact_lengths(self) -> Result<[ExactLength; 2]> {
255 if let Some(physical) = self.physical {
256 physical.exact_lengths()
257 } else {
258 let (width, height) = self.dimensions()?;
259 Ok([
260 ExactLength::binary64(width)?,
261 ExactLength::binary64(height)?,
262 ])
263 }
264 }
265
266 pub(crate) fn validate_raster_source(self, max_axis: u32, max_pixels: u32) -> Result<()> {
267 use crate::errors::{
268 BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase,
269 };
270 let [x, y] = self.exact_lengths()?;
271 let ceiling = |numerator: &BigUint, denominator: &BigUint| -> Result<u128> {
272 u128::try_from((numerator + denominator - 1_u32) / denominator).map_err(|_| {
273 Error::Render("PNG source extent exceeds integer resource accounting".into())
274 })
275 };
276 let refused = |resource, required, limit, message| {
277 Error::Render(
278 Diagnostic::new(
279 DiagnosticKind::BudgetExceeded {
280 resource,
281 required,
282 limit,
283 },
284 message,
285 )
286 .with_context(ErrorContext::new().with_operation(OperationPhase::Write)),
287 )
288 };
289 if x.numerator > &x.denominator * max_axis || y.numerator > &y.denominator * max_axis {
290 let (width, height) = self.dimensions()?;
291 let required =
292 ceiling(&x.numerator, &x.denominator)?.max(ceiling(&y.numerator, &y.denominator)?);
293 return Err(refused(BudgetResource::RasterDimension, required, u128::from(max_axis),
294 format!("PNG scene dimensions {width}x{height} exceed the {max_axis}-pixel conversion limit")));
295 }
296 let numerator = &x.numerator * &y.numerator;
297 let denominator = &x.denominator * &y.denominator;
298 if numerator > &denominator * max_pixels {
299 return Err(refused(
300 BudgetResource::Pixels,
301 ceiling(&numerator, &denominator)?,
302 u128::from(max_pixels),
303 format!("PNG scene work exceeds the {max_pixels}-pixel conversion limit"),
304 ));
305 }
306 Ok(())
307 }
308
309 pub(crate) fn raster_dimensions(self, sizing: PngSizing) -> Result<(u32, u32)> {
310 let [x, y] = self.exact_lengths()?;
311 match sizing {
312 PngSizing::Width(width) => Ok((width, y.companion(&x, width)?)),
313 PngSizing::Height(height) => Ok((x.companion(&y, height)?, height)),
314 PngSizing::Source | PngSizing::Scale(_) | PngSizing::Dpi(_) => {
315 let scale = match sizing {
316 PngSizing::Source => 1.0,
317 PngSizing::Scale(scale) | PngSizing::Dpi(scale) => scale,
318 _ => unreachable!("scale-based raster sizing"),
319 };
320 let scale = ExactLength::binary64(scale)?;
321 let dpi = matches!(sizing, PngSizing::Dpi(_));
322 Ok((
323 x.raster_dimension(&scale, dpi)?,
324 y.raster_dimension(&scale, dpi)?,
325 ))
326 }
327 }
328 }
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 #[test]
336 fn equal_mathematical_units_and_inward_budget_preserve_exact_ratios() {
337 let reference = RootSize::with_unit(50.0, 100.0, SizeUnit::Inch).unwrap();
338 for (width, height, unit) in [
339 (127.0, 254.0, SizeUnit::Centimeter),
340 (1270.0, 2540.0, SizeUnit::Millimeter),
341 (3600.0, 7200.0, SizeUnit::Point),
342 ] {
343 let size = RootSize::with_unit(width, height, unit).unwrap();
344 assert_eq!(size.dimensions().unwrap(), reference.dimensions().unwrap());
345 assert_eq!(
346 size.raster_dimensions(PngSizing::Width(700)).unwrap(),
347 (700, 1400)
348 );
349 }
350 let below_inch = f64::from_bits(72.0_f64.to_bits() - 1);
351 let size = RootSize::with_unit(below_inch, 144.0, SizeUnit::Point).unwrap();
352 assert!(size.layout_dimensions().unwrap().0 < 96.0);
353 assert_eq!(
354 size.raster_dimensions(PngSizing::Source).unwrap(),
355 (96, 192)
356 );
357 assert!(size.finish_height(192.0 + 1.0 / 1024.0, false).is_err());
358 }
359
360 #[test]
361 fn exact_pixel_ties_and_source_boundaries_do_not_use_epsilon() {
362 for (width, expected) in [
363 (f64::from_bits(769.0_f64.to_bits() - 1), 1922),
364 (769.0, 1923),
365 (f64::from_bits(769.0_f64.to_bits() + 1), 1923),
366 ] {
367 let size = RootSize::with_unit(width, 288.0, SizeUnit::Point).unwrap();
368 assert_eq!(
369 size.raster_dimensions(PngSizing::Dpi(180.0)).unwrap(),
370 (expected, 720)
371 );
372 }
373 let limit = RootSize::with_unit(24_576.0, 72.0, SizeUnit::Point).unwrap();
374 limit.validate_raster_source(32_768, 100_000_000).unwrap();
375 let beyond = RootSize::with_unit(
376 f64::from_bits(24_576.0_f64.to_bits() + 1),
377 72.0,
378 SizeUnit::Point,
379 )
380 .unwrap();
381 assert!(beyond.validate_raster_source(32_768, 100_000_000).is_err());
382 let density_tie = 7.9375_f64;
383 assert_eq!(
384 dpi_to_pixels_per_meter(f64::from_bits(density_tie.to_bits() - 1)).unwrap(),
385 312
386 );
387 assert_eq!(dpi_to_pixels_per_meter(density_tie).unwrap(), 313);
388 }
389}