Skip to main content

pltrs_render/ps/
page.rs

1//! The page a PostScript document is printed on and how the figure sits
2//! on it (matplotlib's `papertype` and `orientation`).
3
4use std::fmt;
5use std::str::FromStr;
6
7use pltrs_core::archive::{Archive, ArchiveError, Decoder, Encoder};
8
9/// matplotlib's paper sizes in inches (`backend_ps.papersize`).
10const PAPER_SIZES: [(&str, f64, f64); 25] = [
11    ("letter", 8.5, 11.0),
12    ("legal", 8.5, 14.0),
13    ("ledger", 11.0, 17.0),
14    ("a0", 33.11, 46.81),
15    ("a1", 23.39, 33.11),
16    ("a2", 16.54, 23.39),
17    ("a3", 11.69, 16.54),
18    ("a4", 8.27, 11.69),
19    ("a5", 5.83, 8.27),
20    ("a6", 4.13, 5.83),
21    ("a7", 2.91, 4.13),
22    ("a8", 2.05, 2.91),
23    ("a9", 1.46, 2.05),
24    ("a10", 1.02, 1.46),
25    ("b0", 40.55, 57.32),
26    ("b1", 28.66, 40.55),
27    ("b2", 20.27, 28.66),
28    ("b3", 14.33, 20.27),
29    ("b4", 10.11, 14.33),
30    ("b5", 7.16, 10.11),
31    ("b6", 5.04, 7.16),
32    ("b7", 3.58, 5.04),
33    ("b8", 2.51, 3.58),
34    ("b9", 1.76, 2.51),
35    ("b10", 1.26, 1.76),
36];
37
38/// The page a PostScript document is printed on (`ps.papersize`, or
39/// `savefig`'s `papertype`).
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub enum Paper {
42    /// A page the size of the figure.
43    Figure,
44    /// A named paper size, in inches (portrait).
45    Named {
46        /// matplotlib's name, e.g. `"letter"` or `"a4"`.
47        name: &'static str,
48        /// Width in inches.
49        width: f64,
50        /// Height in inches.
51        height: f64,
52    },
53}
54
55/// Archived as its name.
56impl Archive for Paper {
57    fn encode(&self, encoder: &mut Encoder<'_>) -> Result<(), ArchiveError> {
58        encoder.write_str(&self.to_string());
59        Ok(())
60    }
61
62    fn decode(decoder: &mut Decoder<'_>) -> Result<Self, ArchiveError> {
63        let name = decoder.read_str()?;
64        Self::from_name(&name).ok_or_else(|| ArchiveError::invalid(format!("no paper {name:?}")))
65    }
66}
67
68impl Paper {
69    /// The paper called `name` (case-insensitive), or `"figure"`.
70    pub fn from_name(name: &str) -> Option<Self> {
71        let name = name.to_ascii_lowercase();
72        if name == "figure" {
73            return Some(Self::Figure);
74        }
75        PAPER_SIZES
76            .iter()
77            .find(|(n, _, _)| *n == name)
78            .map(|&(name, width, height)| Self::Named {
79                name,
80                width,
81                height,
82            })
83    }
84}
85
86impl FromStr for Paper {
87    type Err = PageSetupError;
88
89    /// Parses a paper name as [`Paper::from_name`] does; matplotlib's
90    /// former `"auto"` is refused like any unknown name.
91    ///
92    /// ```
93    /// use pltrs_render::Paper;
94    /// assert!(matches!("A4".parse(), Ok(Paper::Named { name: "a4", .. })));
95    /// assert_eq!("figure".parse(), Ok(Paper::Figure));
96    /// assert!("auto".parse::<Paper>().is_err());
97    /// ```
98    fn from_str(name: &str) -> Result<Self, PageSetupError> {
99        Self::from_name(name).ok_or_else(|| PageSetupError::Papertype(name.to_owned()))
100    }
101}
102
103impl fmt::Display for Paper {
104    /// matplotlib's name of the paper (`figure`, `letter`, `a4`, ...).
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        f.write_str(match self {
107            Self::Figure => "figure",
108            Self::Named { name, .. } => name,
109        })
110    }
111}
112
113/// How the figure sits on the page (`savefig.orientation`).
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115pub enum PageOrientation {
116    /// Upright.
117    #[default]
118    Portrait,
119    /// Rotated by 90°.
120    Landscape,
121}
122
123pltrs_core::archive_enum!(PageOrientation {
124    Portrait,
125    Landscape,
126});
127
128impl PageOrientation {
129    /// matplotlib's name of the orientation.
130    pub const fn name(self) -> &'static str {
131        match self {
132            Self::Portrait => "portrait",
133            Self::Landscape => "landscape",
134        }
135    }
136}
137
138impl fmt::Display for PageOrientation {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        f.write_str(self.name())
141    }
142}
143
144impl FromStr for PageOrientation {
145    type Err = PageSetupError;
146
147    /// Parses `"portrait"` or `"landscape"`.
148    ///
149    /// ```
150    /// use pltrs_render::PageOrientation;
151    /// assert_eq!("landscape".parse(), Ok(PageOrientation::Landscape));
152    /// assert!("sideways".parse::<PageOrientation>().is_err());
153    /// ```
154    fn from_str(name: &str) -> Result<Self, PageSetupError> {
155        match name {
156            "portrait" => Ok(Self::Portrait),
157            "landscape" => Ok(Self::Landscape),
158            _ => Err(PageSetupError::Orientation(name.to_owned())),
159        }
160    }
161}
162
163/// A paper or orientation name that does not exist.
164#[derive(Clone, Debug, PartialEq, Eq)]
165pub enum PageSetupError {
166    /// An unknown paper name.
167    Papertype(String),
168    /// An unknown orientation.
169    Orientation(String),
170}
171
172impl fmt::Display for PageSetupError {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        match self {
175            Self::Papertype(name) => {
176                write!(
177                    f,
178                    "{name:?} is not a valid value for papertype; supported values are \"figure\""
179                )?;
180                PAPER_SIZES
181                    .iter()
182                    .try_for_each(|(paper, _, _)| write!(f, ", {paper:?}"))
183            }
184            Self::Orientation(name) => write!(
185                f,
186                "{name:?} is not a valid value for orientation; supported values are \"portrait\", \"landscape\""
187            ),
188        }
189    }
190}
191
192impl std::error::Error for PageSetupError {}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn unknown_names_are_refused() {
200        let auto = "auto".parse::<Paper>().unwrap_err();
201        assert!(auto.to_string().starts_with(
202            "\"auto\" is not a valid value for papertype; supported values are \"figure\", \"letter\""
203        ));
204        assert_eq!(
205            "Landscape".parse::<PageOrientation>(),
206            Err(PageSetupError::Orientation("Landscape".to_owned()))
207        );
208        assert_eq!(PageOrientation::Landscape.to_string(), "landscape");
209        assert_eq!(
210            "A4".parse::<Paper>().map(|paper| paper.to_string()),
211            Ok("a4".to_owned())
212        );
213        assert_eq!(Paper::Figure.to_string(), "figure");
214    }
215}