ggplot-rs 0.69.0

A Rust implementation of ggplot2's Grammar of Graphics
Documentation
//! Physical output sizes (#527): a chart for a document is sized in cm, mm,
//! inches or points, as `ggsave` does, instead of in pixels.
//!
//! The chart is laid out in **points** (1/72 in): the canvas is the physical
//! size in points, and every theme size (`base_size`, text, line widths) is
//! read as points. Vector output carries the physical size (SVG `width="16cm"`
//! over a `viewBox` in points; a PDF page of that size). Raster output draws
//! the same layout at `dpi / 72` pixels per point, so doubling the dpi
//! doubles the pixels and keeps the text at its printed size.
//!
//! A bare number, or one in `px`, is a pixel size: the layout in pixels as
//! before (text sizes then read as pixels).

use std::fmt;
use std::str::FromStr;

/// A length's unit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Unit {
    /// Pixels: a canvas size as before, not a physical one.
    Px,
    /// Points, 1/72 in.
    Pt,
    In,
    Cm,
    Mm,
}

impl Unit {
    /// Points per unit (`None` for pixels).
    fn pt(self) -> Option<f64> {
        match self {
            Unit::Px => None,
            Unit::Pt => Some(1.0),
            Unit::In => Some(72.0),
            Unit::Cm => Some(72.0 / 2.54),
            Unit::Mm => Some(72.0 / 25.4),
        }
    }

    fn suffix(self) -> &'static str {
        match self {
            Unit::Px => "px",
            Unit::Pt => "pt",
            Unit::In => "in",
            Unit::Cm => "cm",
            Unit::Mm => "mm",
        }
    }
}

/// A length with its unit: `16cm`, `6.3in`, `160mm`, `450pt`, `800px` or a
/// bare `800` (pixels).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Length {
    pub value: f64,
    pub unit: Unit,
}

impl Length {
    pub fn new(value: f64, unit: Unit) -> Self {
        Length { value, unit }
    }
    pub fn px(v: f64) -> Self {
        Length::new(v, Unit::Px)
    }
    pub fn pt(v: f64) -> Self {
        Length::new(v, Unit::Pt)
    }
    pub fn inches(v: f64) -> Self {
        Length::new(v, Unit::In)
    }
    pub fn cm(v: f64) -> Self {
        Length::new(v, Unit::Cm)
    }
    pub fn mm(v: f64) -> Self {
        Length::new(v, Unit::Mm)
    }

    /// Is this a physical length (not pixels)?
    pub fn is_physical(&self) -> bool {
        self.unit != Unit::Px
    }

    /// The length in points; `None` for pixels.
    pub fn to_pt(&self) -> Option<f64> {
        self.unit.pt().map(|k| self.value * k)
    }

    /// The length in pixels at `dpi` (a pixel length as it is).
    pub fn to_px(&self, dpi: f64) -> f64 {
        match self.to_pt() {
            Some(pt) => pt * dpi / 72.0,
            None => self.value,
        }
    }
}

impl fmt::Display for Length {
    /// `16cm`, `6.3in`, … as an SVG `width` takes it (pixels without a unit).
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let v = (self.value * 10_000.0).round() / 10_000.0;
        match self.unit {
            Unit::Px => write!(f, "{v}"),
            u => write!(f, "{v}{}", u.suffix()),
        }
    }
}

impl FromStr for Length {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, String> {
        let t = s.trim().to_ascii_lowercase();
        let split = t
            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
            .unwrap_or(t.len());
        let (num, unit) = t.split_at(split);
        let unit = match unit.trim() {
            "" | "px" => Unit::Px,
            "pt" => Unit::Pt,
            "in" | "inch" | "inches" => Unit::In,
            "cm" => Unit::Cm,
            "mm" => Unit::Mm,
            u => return Err(format!("unknown unit '{u}' in '{s}' (px, pt, in, cm, mm)")),
        };
        let value: f64 = num
            .parse()
            .map_err(|_| format!("'{s}' is not a length (e.g. 16cm, 6.3in, 800)"))?;
        if !(value.is_finite() && value > 0.0) {
            return Err(format!("'{s}': a length must be above 0"));
        }
        Ok(Length { value, unit })
    }
}

/// An output size: width, height and, for raster output, the dpi.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PhysicalSize {
    pub width: Length,
    pub height: Length,
    /// Dots per inch for raster output (default 300); vector output ignores it.
    pub dpi: f64,
}

impl PhysicalSize {
    pub fn new(width: Length, height: Length) -> Self {
        PhysicalSize {
            width,
            height,
            dpi: 300.0,
        }
    }

    pub fn with_dpi(mut self, dpi: f64) -> Self {
        self.dpi = dpi;
        self
    }

    /// The layout canvas (whole units): points for a physical size, pixels
    /// for a pixel size. Both lengths must be of the same kind.
    pub fn canvas(&self) -> Result<(u32, u32), String> {
        match (self.width.to_pt(), self.height.to_pt()) {
            (Some(w), Some(h)) => Ok((w.round().max(1.0) as u32, h.round().max(1.0) as u32)),
            (None, None) => Ok((
                self.width.value.round().max(1.0) as u32,
                self.height.value.round().max(1.0) as u32,
            )),
            _ => {
                Err("width and height must both be physical (cm, mm, in, pt) or both pixels".into())
            }
        }
    }

    /// Pixels per layout unit for raster output: dpi / 72 for a physical size,
    /// 1 for a pixel size.
    pub fn raster_scale(&self) -> f64 {
        if self.width.is_physical() && self.dpi.is_finite() && self.dpi > 0.0 {
            self.dpi / 72.0
        } else {
            1.0
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lengths_parse_and_convert() {
        let l: Length = "16cm".parse().unwrap();
        assert_eq!(l, Length::cm(16.0));
        assert!((l.to_pt().unwrap() - 453.543).abs() < 1e-3);
        assert_eq!("6.3in".parse::<Length>().unwrap().to_pt(), Some(6.3 * 72.0));
        assert_eq!("160 mm".parse::<Length>().unwrap(), Length::mm(160.0));
        assert_eq!("800".parse::<Length>().unwrap(), Length::px(800.0));
        assert_eq!("800px".parse::<Length>().unwrap().to_pt(), None);
        for bad in ["", "cm", "16furlongs", "-3cm", "0in", "1.2.3cm"] {
            assert!(bad.parse::<Length>().is_err(), "{bad}");
        }
        assert_eq!(Length::cm(16.0).to_string(), "16cm");
        assert_eq!(Length::px(800.0).to_string(), "800");
        // 1 in at 300 dpi is 300 px; pixels stay pixels
        assert_eq!(Length::inches(1.0).to_px(300.0), 300.0);
        assert_eq!(Length::px(640.0).to_px(300.0), 640.0);
    }

    #[test]
    fn a_size_gives_its_canvas_and_raster_scale() {
        let s = PhysicalSize::new(Length::cm(16.0), Length::cm(7.5));
        assert_eq!(s.canvas().unwrap(), (454, 213));
        assert!((s.raster_scale() - 300.0 / 72.0).abs() < 1e-12);
        let px = PhysicalSize::new(Length::px(800.0), Length::px(600.0));
        assert_eq!((px.canvas().unwrap(), px.raster_scale()), ((800, 600), 1.0));
        assert!(PhysicalSize::new(Length::cm(16.0), Length::px(600.0))
            .canvas()
            .is_err());
    }
}