Skip to main content

ggplot_rs/
size.rs

1//! Physical output sizes (#527): a chart for a document is sized in cm, mm,
2//! inches or points, as `ggsave` does, instead of in pixels.
3//!
4//! The chart is laid out in **points** (1/72 in): the canvas is the physical
5//! size in points, and every theme size (`base_size`, text, line widths) is
6//! read as points. Vector output carries the physical size (SVG `width="16cm"`
7//! over a `viewBox` in points; a PDF page of that size). Raster output draws
8//! the same layout at `dpi / 72` pixels per point, so doubling the dpi
9//! doubles the pixels and keeps the text at its printed size.
10//!
11//! A bare number, or one in `px`, is a pixel size: the layout in pixels as
12//! before (text sizes then read as pixels).
13
14use std::fmt;
15use std::str::FromStr;
16
17/// A length's unit.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum Unit {
20    /// Pixels: a canvas size as before, not a physical one.
21    Px,
22    /// Points, 1/72 in.
23    Pt,
24    In,
25    Cm,
26    Mm,
27}
28
29impl Unit {
30    /// Points per unit (`None` for pixels).
31    fn pt(self) -> Option<f64> {
32        match self {
33            Unit::Px => None,
34            Unit::Pt => Some(1.0),
35            Unit::In => Some(72.0),
36            Unit::Cm => Some(72.0 / 2.54),
37            Unit::Mm => Some(72.0 / 25.4),
38        }
39    }
40
41    fn suffix(self) -> &'static str {
42        match self {
43            Unit::Px => "px",
44            Unit::Pt => "pt",
45            Unit::In => "in",
46            Unit::Cm => "cm",
47            Unit::Mm => "mm",
48        }
49    }
50}
51
52/// A length with its unit: `16cm`, `6.3in`, `160mm`, `450pt`, `800px` or a
53/// bare `800` (pixels).
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct Length {
56    pub value: f64,
57    pub unit: Unit,
58}
59
60impl Length {
61    pub fn new(value: f64, unit: Unit) -> Self {
62        Length { value, unit }
63    }
64    pub fn px(v: f64) -> Self {
65        Length::new(v, Unit::Px)
66    }
67    pub fn pt(v: f64) -> Self {
68        Length::new(v, Unit::Pt)
69    }
70    pub fn inches(v: f64) -> Self {
71        Length::new(v, Unit::In)
72    }
73    pub fn cm(v: f64) -> Self {
74        Length::new(v, Unit::Cm)
75    }
76    pub fn mm(v: f64) -> Self {
77        Length::new(v, Unit::Mm)
78    }
79
80    /// Is this a physical length (not pixels)?
81    pub fn is_physical(&self) -> bool {
82        self.unit != Unit::Px
83    }
84
85    /// The length in points; `None` for pixels.
86    pub fn to_pt(&self) -> Option<f64> {
87        self.unit.pt().map(|k| self.value * k)
88    }
89
90    /// The length in pixels at `dpi` (a pixel length as it is).
91    pub fn to_px(&self, dpi: f64) -> f64 {
92        match self.to_pt() {
93            Some(pt) => pt * dpi / 72.0,
94            None => self.value,
95        }
96    }
97}
98
99impl fmt::Display for Length {
100    /// `16cm`, `6.3in`, … as an SVG `width` takes it (pixels without a unit).
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        let v = (self.value * 10_000.0).round() / 10_000.0;
103        match self.unit {
104            Unit::Px => write!(f, "{v}"),
105            u => write!(f, "{v}{}", u.suffix()),
106        }
107    }
108}
109
110impl FromStr for Length {
111    type Err = String;
112    fn from_str(s: &str) -> Result<Self, String> {
113        let t = s.trim().to_ascii_lowercase();
114        let split = t
115            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
116            .unwrap_or(t.len());
117        let (num, unit) = t.split_at(split);
118        let unit = match unit.trim() {
119            "" | "px" => Unit::Px,
120            "pt" => Unit::Pt,
121            "in" | "inch" | "inches" => Unit::In,
122            "cm" => Unit::Cm,
123            "mm" => Unit::Mm,
124            u => return Err(format!("unknown unit '{u}' in '{s}' (px, pt, in, cm, mm)")),
125        };
126        let value: f64 = num
127            .parse()
128            .map_err(|_| format!("'{s}' is not a length (e.g. 16cm, 6.3in, 800)"))?;
129        if !(value.is_finite() && value > 0.0) {
130            return Err(format!("'{s}': a length must be above 0"));
131        }
132        Ok(Length { value, unit })
133    }
134}
135
136/// An output size: width, height and, for raster output, the dpi.
137#[derive(Clone, Copy, Debug, PartialEq)]
138pub struct PhysicalSize {
139    pub width: Length,
140    pub height: Length,
141    /// Dots per inch for raster output (default 300); vector output ignores it.
142    pub dpi: f64,
143}
144
145impl PhysicalSize {
146    pub fn new(width: Length, height: Length) -> Self {
147        PhysicalSize {
148            width,
149            height,
150            dpi: 300.0,
151        }
152    }
153
154    pub fn with_dpi(mut self, dpi: f64) -> Self {
155        self.dpi = dpi;
156        self
157    }
158
159    /// The layout canvas (whole units): points for a physical size, pixels
160    /// for a pixel size. Both lengths must be of the same kind.
161    pub fn canvas(&self) -> Result<(u32, u32), String> {
162        match (self.width.to_pt(), self.height.to_pt()) {
163            (Some(w), Some(h)) => Ok((w.round().max(1.0) as u32, h.round().max(1.0) as u32)),
164            (None, None) => Ok((
165                self.width.value.round().max(1.0) as u32,
166                self.height.value.round().max(1.0) as u32,
167            )),
168            _ => {
169                Err("width and height must both be physical (cm, mm, in, pt) or both pixels".into())
170            }
171        }
172    }
173
174    /// Pixels per layout unit for raster output: dpi / 72 for a physical size,
175    /// 1 for a pixel size.
176    pub fn raster_scale(&self) -> f64 {
177        if self.width.is_physical() && self.dpi.is_finite() && self.dpi > 0.0 {
178            self.dpi / 72.0
179        } else {
180            1.0
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn lengths_parse_and_convert() {
191        let l: Length = "16cm".parse().unwrap();
192        assert_eq!(l, Length::cm(16.0));
193        assert!((l.to_pt().unwrap() - 453.543).abs() < 1e-3);
194        assert_eq!("6.3in".parse::<Length>().unwrap().to_pt(), Some(6.3 * 72.0));
195        assert_eq!("160 mm".parse::<Length>().unwrap(), Length::mm(160.0));
196        assert_eq!("800".parse::<Length>().unwrap(), Length::px(800.0));
197        assert_eq!("800px".parse::<Length>().unwrap().to_pt(), None);
198        for bad in ["", "cm", "16furlongs", "-3cm", "0in", "1.2.3cm"] {
199            assert!(bad.parse::<Length>().is_err(), "{bad}");
200        }
201        assert_eq!(Length::cm(16.0).to_string(), "16cm");
202        assert_eq!(Length::px(800.0).to_string(), "800");
203        // 1 in at 300 dpi is 300 px; pixels stay pixels
204        assert_eq!(Length::inches(1.0).to_px(300.0), 300.0);
205        assert_eq!(Length::px(640.0).to_px(300.0), 640.0);
206    }
207
208    #[test]
209    fn a_size_gives_its_canvas_and_raster_scale() {
210        let s = PhysicalSize::new(Length::cm(16.0), Length::cm(7.5));
211        assert_eq!(s.canvas().unwrap(), (454, 213));
212        assert!((s.raster_scale() - 300.0 / 72.0).abs() < 1e-12);
213        let px = PhysicalSize::new(Length::px(800.0), Length::px(600.0));
214        assert_eq!((px.canvas().unwrap(), px.raster_scale()), ((800, 600), 1.0));
215        assert!(PhysicalSize::new(Length::cm(16.0), Length::px(600.0))
216            .canvas()
217            .is_err());
218    }
219}