use num_bigint::{BigInt, BigUint};
use crate::{output::PngSizing, Error, Result};
const CSS_PIXELS_PER_INCH: u32 = 96;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeUnit {
Inch,
Centimeter,
Millimeter,
Point,
}
impl SizeUnit {
const fn css_ratio(self) -> (u32, u32) {
match self {
Self::Inch => (CSS_PIXELS_PER_INCH, 1),
Self::Centimeter => (4800, 127),
Self::Millimeter => (480, 127),
Self::Point => (4, 3),
}
}
pub(crate) const fn suffix(self) -> &'static str {
match self {
Self::Inch => "in",
Self::Centimeter => "cm",
Self::Millimeter => "mm",
Self::Point => "pt",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PhysicalSize {
width: u64,
height: u64,
unit: SizeUnit,
}
impl PhysicalSize {
#[must_use]
pub const fn width(&self) -> f64 {
f64::from_bits(self.width)
}
#[must_use]
pub const fn height(&self) -> f64 {
f64::from_bits(self.height)
}
#[must_use]
pub const fn unit(&self) -> SizeUnit {
self.unit
}
fn exact_lengths(self) -> Result<[ExactLength; 2]> {
let (numerator, denominator) = self.unit.css_ratio();
let length = |value| -> Result<ExactLength> {
let mut length = ExactLength::binary64(value)?;
length.numerator *= numerator;
length.denominator *= denominator;
Ok(length)
};
Ok([length(self.width())?, length(self.height())?])
}
}
struct ExactLength {
numerator: BigUint,
denominator: BigUint,
}
impl ExactLength {
fn binary64(value: f64) -> Result<Self> {
if !value.is_finite() || value <= 0.0 {
return Err(Error::Render(
"page and device dimensions must be positive and finite".into(),
));
}
Ok(Self {
numerator: crate::numeric::binary::units(value)?.into_parts().1,
denominator: BigUint::from(1_u8) << 1074,
})
}
fn rounded(&self) -> Result<f64> {
crate::numeric::binary::signed_ratio(
BigInt::from(self.numerator.clone()),
self.denominator.clone(),
)
}
#[expect(
clippy::cast_precision_loss,
reason = "the layout budget is bounded by u32::MAX CSS pixels in spatial quanta"
)]
fn layout_budget(&self) -> Result<f64> {
if self.numerator > &self.denominator * u32::MAX {
return Err(Error::Render(
"physical page exceeds the layout coordinate range".into(),
));
}
let quanta =
u64::try_from((&self.numerator << 10_usize) / &self.denominator).map_err(|_| {
Error::Render("physical page exceeds the layout coordinate range".into())
})?;
Ok(quanta as f64 / 1024.0)
}
fn raster_dimension(&self, scale: &Self, dpi: bool) -> Result<u32> {
let numerator = &self.numerator * &scale.numerator;
let mut denominator = &self.denominator * &scale.denominator;
if dpi {
denominator *= CSS_PIXELS_PER_INCH;
}
round_pixels(numerator, &denominator, false)
}
fn companion(&self, fixed: &Self, pixels: u32) -> Result<u32> {
let numerator = &self.numerator * &fixed.denominator * pixels;
let denominator = &self.denominator * &fixed.numerator;
round_pixels(numerator, &denominator, true)
}
}
fn round_pixels(numerator: BigUint, denominator: &BigUint, ceil: bool) -> Result<u32> {
let quotient = &numerator / denominator;
let remainder = numerator % denominator;
let increment = if ceil {
remainder.bits() != 0
} else {
(&remainder << 1_usize) >= *denominator
};
u32::try_from(quotient + u32::from(increment))
.map_err(|_| Error::Render("computed PNG dimensions exceed the conversion limit".into()))
}
pub(crate) fn dpi_to_pixels_per_meter(dpi: f64) -> Result<u32> {
let density = ExactLength::binary64(dpi)?;
let pixels = round_pixels(
density.numerator * 5000_u32,
&(density.denominator * 127_u32),
false,
)
.map_err(|_| Error::Render(format!("png dpi is too large to encode: {dpi}").into()))?;
if pixels == 0 {
return Err(Error::Render(
format!("png dpi is too small to encode: {dpi}").into(),
));
}
Ok(pixels)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RootSize {
viewport: [u64; 2],
budget: [u64; 2],
physical: Option<PhysicalSize>,
}
impl RootSize {
pub(crate) fn new(width: impl Into<f64>, height: impl Into<f64>) -> Self {
Self::css(width.into(), height.into())
}
pub(crate) const fn css(width: f64, height: f64) -> Self {
Self {
viewport: [width.to_bits(), height.to_bits()],
budget: [
((width * 1024.0).floor() / 1024.0).to_bits(),
((height * 1024.0).floor() / 1024.0).to_bits(),
],
physical: None,
}
}
pub(crate) fn with_unit(width: f64, height: f64, unit: SizeUnit) -> Result<Self> {
let physical = PhysicalSize {
width: width.to_bits(),
height: height.to_bits(),
unit,
};
let [x, y] = physical.exact_lengths()?;
let size = Self {
viewport: [x.rounded()?.to_bits(), y.rounded()?.to_bits()],
budget: [x.layout_budget()?.to_bits(), y.layout_budget()?.to_bits()],
physical: Some(physical),
};
size.dimensions()?;
Ok(size)
}
pub(crate) fn dimensions(self) -> Result<(f64, f64)> {
let [width, height] = self.viewport.map(f64::from_bits);
let valid = |value: f64| value.is_finite() && value > 0.0 && value <= f64::from(u32::MAX);
if !valid(width)
|| !valid(height)
|| !self.budget.map(f64::from_bits).into_iter().all(valid)
{
return Err(Error::Render(
"layout root dimensions must be finite, positive and representable".into(),
));
}
Ok((width, height))
}
pub(crate) fn layout_dimensions(self) -> Result<(f64, f64)> {
self.dimensions()?;
let [width, height] = self.budget.map(f64::from_bits);
Ok((width, height))
}
pub(crate) fn finish_height(self, height: f64, automatic: bool) -> Result<Self> {
if automatic {
return Ok(Self::new(
self.dimensions()?.0,
super::kernel::root_dimension(height)?,
));
}
let budget = self.layout_dimensions()?.1;
if height <= 0.0
|| super::kernel::ceil_spatial_quanta(height)?
> super::kernel::ceil_spatial_quanta(budget)?
{
return Err(Error::Render(
"measured content exceeds the exact root height".into(),
));
}
Ok(self)
}
pub(crate) const fn physical_size(self) -> Option<PhysicalSize> {
self.physical
}
fn exact_lengths(self) -> Result<[ExactLength; 2]> {
if let Some(physical) = self.physical {
physical.exact_lengths()
} else {
let (width, height) = self.dimensions()?;
Ok([
ExactLength::binary64(width)?,
ExactLength::binary64(height)?,
])
}
}
pub(crate) fn raster_dimensions(self, sizing: PngSizing) -> Result<(u32, u32)> {
let [x, y] = self.exact_lengths()?;
match sizing {
PngSizing::Width(width) => Ok((width, y.companion(&x, width)?)),
PngSizing::Height(height) => Ok((x.companion(&y, height)?, height)),
PngSizing::Source | PngSizing::Scale(_) | PngSizing::Dpi(_) => {
let scale = match sizing {
PngSizing::Source => 1.0,
PngSizing::Scale(scale) | PngSizing::Dpi(scale) => scale,
_ => unreachable!("scale-based raster sizing"),
};
let scale = ExactLength::binary64(scale)?;
let dpi = matches!(sizing, PngSizing::Dpi(_));
Ok((
x.raster_dimension(&scale, dpi)?,
y.raster_dimension(&scale, dpi)?,
))
}
}
}
pub(crate) fn supports_raster_dimensions(self, width: u32, height: u32) -> Result<bool> {
let [x_length, y_length] = self.exact_lengths()?;
let x = &x_length.numerator * &y_length.denominator;
let y = &y_length.numerator * &x_length.denominator;
let w = u64::from(width);
let h = u64::from(height);
if w == 0 || h == 0 {
return Ok(false);
}
let nearest = &y * (2 * w - 1) < &x * (2 * h + 1) && &x * (2 * h - 1) < &y * (2 * w + 1);
let by_width = &x * (h - 1) < &y * w && &y * w <= &x * h;
let by_height = &y * (w - 1) < &x * h && &x * h <= &y * w;
Ok(nearest || by_width || by_height)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equal_mathematical_units_and_inward_budget_preserve_exact_ratios() {
let reference = RootSize::with_unit(50.0, 100.0, SizeUnit::Inch).unwrap();
for (width, height, unit) in [
(127.0, 254.0, SizeUnit::Centimeter),
(1270.0, 2540.0, SizeUnit::Millimeter),
(3600.0, 7200.0, SizeUnit::Point),
] {
let size = RootSize::with_unit(width, height, unit).unwrap();
assert_eq!(size.dimensions().unwrap(), reference.dimensions().unwrap());
assert_eq!(
size.raster_dimensions(PngSizing::Width(700)).unwrap(),
(700, 1400)
);
}
let below_inch = f64::from_bits(72.0_f64.to_bits() - 1);
let size = RootSize::with_unit(below_inch, 144.0, SizeUnit::Point).unwrap();
assert!(size.layout_dimensions().unwrap().0 < 96.0);
assert_eq!(
size.raster_dimensions(PngSizing::Source).unwrap(),
(96, 192)
);
assert!(size.finish_height(192.0 + 1.0 / 1024.0, false).is_err());
}
#[test]
fn exact_pixel_and_density_ties_do_not_use_epsilon() {
for (width, expected) in [
(f64::from_bits(769.0_f64.to_bits() - 1), 1922),
(769.0, 1923),
(f64::from_bits(769.0_f64.to_bits() + 1), 1923),
] {
let size = RootSize::with_unit(width, 288.0, SizeUnit::Point).unwrap();
assert_eq!(
size.raster_dimensions(PngSizing::Dpi(180.0)).unwrap(),
(expected, 720)
);
}
let density_tie = 7.9375_f64;
assert_eq!(
dpi_to_pixels_per_meter(f64::from_bits(density_tie.to_bits() - 1)).unwrap(),
312
);
assert_eq!(dpi_to_pixels_per_meter(density_tie).unwrap(), 313);
}
}