Skip to main content

pltrs_render/vector/
mod.rs

1//! Infrastructure shared by the SVG, PDF and PostScript backends: Python's
2//! number formatting, embedded-font data, glyph tracking, run analysis,
3//! images, metadata and the error type.
4
5mod font;
6mod format;
7mod image;
8mod metadata;
9mod text;
10mod tracker;
11
12use std::fmt;
13
14use pltrs_codec::CompressionLevel;
15use pltrs_codec::checksum::crc32;
16use pltrs_codec::png::EncodeError;
17use pltrs_core::Path;
18use pltrs_core::alloc::{self, OutOfMemory};
19use pltrs_core::path::convert::VertexSource;
20use pltrs_core::{Affine2D, Bbox, Point};
21use pltrs_text::TextError;
22use pltrs_text::tex::TexError;
23
24pub(crate) use font::{FontCache, FontInfo};
25pub(crate) use format::{fixed, general, hex, repr, repr_bytes, repr_str, short, trimmed};
26pub(crate) use image::{flipped_rows, png_idat};
27pub use metadata::{Metadata, PNG_SOFTWARE, PngMetadata, SvgMetadata, Timestamp, Trapped};
28pub(crate) use text::{POINTS_DPI, glyph_chars, in_points, prev_kerns};
29pub(crate) use tracker::{CharacterTracker, Subset};
30
31/// How PDF and PostScript documents embed TrueType fonts (matplotlib's
32/// `pdf.fonttype` and `ps.fonttype`).
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum FontType {
35    /// Type 3 fonts drawing the glyph outlines, 256 glyphs per font.
36    #[default]
37    Type3,
38    /// Type 42 fonts: subsets of the TrueType font program itself.
39    Type42,
40}
41
42impl FontType {
43    /// The font type numbered `number` (3 or 42).
44    pub const fn from_number(number: u32) -> Option<Self> {
45        match number {
46            3 => Some(Self::Type3),
47            42 => Some(Self::Type42),
48            _ => None,
49        }
50    }
51
52    /// How many character codes one embedded font may use (matplotlib's
53    /// `_FONT_MAX_GLYPH`).
54    pub(crate) const fn subset_size(self) -> u32 {
55        match self {
56            Self::Type3 => 256,
57            Self::Type42 => 65536,
58        }
59    }
60}
61
62/// Why a vector document could not be produced.
63#[derive(Debug)]
64pub enum VectorError {
65    /// The page size or resolution is not positive and finite.
66    InvalidCanvas {
67        /// Requested width.
68        width: f64,
69        /// Requested height.
70        height: f64,
71        /// Requested image resolution.
72        dpi: f64,
73    },
74    /// A font could not be read.
75    Font(TextError),
76    /// An image could not be encoded.
77    Image(EncodeError),
78    /// A number the format cannot represent (PDF has no NaN or infinity).
79    NonFinite(&'static str),
80    /// Something the format cannot hold.
81    Unsupported(&'static str),
82    /// A PGF picture written to no file has an image, which can only be
83    /// written beside the picture's file (matplotlib's `ValueError`).
84    StreamedImage,
85    /// TeX text could not be typeset or its fonts embedded.
86    Tex(TexError),
87    /// A PDF object was reserved but never written before the
88    /// cross-reference table.
89    UnwrittenObject(usize),
90    /// A PDF stream was begun while another is open (matplotlib's
91    /// assertion in `beginStream`).
92    StreamOpen,
93    /// The memory for the document cannot be allocated.
94    OutOfMemory(OutOfMemory),
95}
96
97impl fmt::Display for VectorError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            Self::InvalidCanvas { width, height, dpi } => write!(
101                f,
102                "invalid page {width} x {height} at {dpi} dpi: all must be positive"
103            ),
104            Self::Font(err) => write!(f, "cannot embed font: {err}"),
105            Self::Image(err) => write!(f, "cannot encode image: {err}"),
106            Self::NonFinite(what) => write!(f, "cannot write a non-finite {what}"),
107            Self::Unsupported(what) => f.write_str(what),
108            Self::StreamedImage => f.write_str(
109                "streamed pgf-code does not support raster graphics, consider using the \
110                 pgf-to-pdf option",
111            ),
112            Self::Tex(err) => write!(f, "cannot draw TeX text: {err}"),
113            Self::UnwrittenObject(id) => {
114                write!(f, "PDF object {id} was reserved but never written")
115            }
116            Self::StreamOpen => f.write_str("a PDF stream is open already"),
117            Self::OutOfMemory(err) => write!(f, "cannot write the document: {err}"),
118        }
119    }
120}
121
122impl std::error::Error for VectorError {
123    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
124        match self {
125            Self::Font(err) => Some(err),
126            Self::Image(err) => Some(err),
127            Self::Tex(err) => Some(err),
128            Self::OutOfMemory(err) => Some(err),
129            Self::InvalidCanvas { .. }
130            | Self::NonFinite(_)
131            | Self::Unsupported(_)
132            | Self::StreamedImage
133            | Self::UnwrittenObject(_)
134            | Self::StreamOpen => None,
135        }
136    }
137}
138
139impl From<TextError> for VectorError {
140    fn from(err: TextError) -> Self {
141        Self::Font(err)
142    }
143}
144
145impl From<TexError> for VectorError {
146    fn from(err: TexError) -> Self {
147        Self::Tex(err)
148    }
149}
150
151impl From<OutOfMemory> for VectorError {
152    fn from(err: OutOfMemory) -> Self {
153        Self::OutOfMemory(err)
154    }
155}
156
157impl From<EncodeError> for VectorError {
158    fn from(err: EncodeError) -> Self {
159        Self::Image(err)
160    }
161}
162
163/// Validates a page size and image resolution.
164pub(crate) fn check_canvas(width: f64, height: f64, dpi: f64) -> Result<(), VectorError> {
165    let valid = |v: f64| v.is_finite() && v > 0.0;
166    if valid(width) && valid(height) && valid(dpi) {
167        Ok(())
168    } else {
169        Err(VectorError::InvalidCanvas { width, height, dpi })
170    }
171}
172
173/// Problems met while drawing, reported when the document is finished.
174#[derive(Debug, Default)]
175pub(crate) struct Problems(Option<VectorError>);
176
177impl Problems {
178    /// Records `result`'s error unless an earlier one is kept.
179    pub(crate) fn record<T>(&mut self, result: Result<T, VectorError>) -> Option<T> {
180        match result {
181            Ok(value) => Some(value),
182            Err(err) => {
183                self.0.get_or_insert(err);
184                None
185            }
186        }
187    }
188
189    /// `Ok(value)` unless a problem was recorded.
190    pub(crate) fn into_result<T>(self, value: T) -> Result<T, VectorError> {
191        self.0.map_or(Ok(value), Err)
192    }
193}
194
195/// The marker positions of `path` (matplotlib's `iter_segments(trans,
196/// clip=clip, simplify=False)`): the last vertex of every segment after
197/// transforming, dropping non-finite points and clipping to `clip`.
198pub(crate) fn segment_ends(path: &Path, transform: Affine2D, clip: Option<Bbox>) -> Vec<Point> {
199    segment_points(path, transform, clip, false)
200}
201
202/// The first vertex of every segment of `path`, conditioned as for
203/// [`segment_ends`] (where the PGF backend places markers).
204pub(crate) fn segment_starts(path: &Path, transform: Affine2D, clip: Option<Bbox>) -> Vec<Point> {
205    segment_points(path, transform, clip, true)
206}
207
208/// The first or last vertex of every segment of the conditioned path.
209fn segment_points(path: &Path, transform: Affine2D, clip: Option<Bbox>, first: bool) -> Vec<Point> {
210    let mut stream = path
211        .iter_vertices()
212        .transform(transform)
213        .remove_nans(true, path.codes().is_some())
214        .clip_to(clip);
215    let mut points = Vec::new();
216    while let Some(vertex) = stream.next() {
217        let mut point = vertex.point;
218        for _ in 1..vertex.code.vertex_count() {
219            if let Some(next) = stream.next()
220                && !first
221            {
222                point = next.point;
223            }
224        }
225        points.push(point);
226    }
227    points
228}
229
230/// A gzip member (RFC 1952) holding `data`, as Python's `gzip.GzipFile`
231/// writes it at its default level 9 (used for `.svgz`).
232///
233/// # Errors
234///
235/// When the memory for the member cannot be allocated.
236pub fn gzip(data: &[u8]) -> Result<Vec<u8>, OutOfMemory> {
237    // Magic, deflate, no flags, no modification time, maximum compression,
238    // unknown operating system.
239    let mut out = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 2, 255];
240    pltrs_codec::deflate::compress_into(data, CompressionLevel::BEST, &mut out)?;
241    alloc::try_reserve(&mut out, 8)?;
242    out.extend_from_slice(&crc32(data).to_le_bytes());
243    out.extend_from_slice(&(data.len() as u32).to_le_bytes());
244    Ok(out)
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn gzip_members_round_trip() {
253        let data = b"<svg/>\n".repeat(20);
254        let member = gzip(&data).unwrap();
255        assert_eq!(&member[..3], &[0x1f, 0x8b, 8]);
256        let body = &member[10..member.len() - 8];
257        assert_eq!(pltrs_codec::deflate::decompress(body).unwrap(), data);
258        assert_eq!(
259            member[member.len() - 4..],
260            (data.len() as u32).to_le_bytes()
261        );
262    }
263
264    #[test]
265    fn segment_ends_skip_nans_and_clip() {
266        let path = Path::polyline(vec![
267            Point::new(1.0, 1.0),
268            Point::new(f64::NAN, 2.0),
269            Point::new(3.0, 3.0),
270            Point::new(50.0, 3.0),
271        ]);
272        let clip = Bbox::from_extents(0.0, 0.0, 10.0, 10.0);
273        let ends = segment_ends(&path, Affine2D::scaling(2.0, 1.0), Some(clip));
274        assert_eq!(ends[0], Point::new(2.0, 1.0));
275        assert_eq!(ends[1], Point::new(6.0, 3.0));
276        assert_eq!(ends.last().map(|p| p.x), Some(11.0), "clipped one unit out");
277    }
278
279    #[test]
280    fn canvas_validation_and_problems() {
281        assert!(check_canvas(10.0, 10.0, 72.0).is_ok());
282        assert!(matches!(
283            check_canvas(0.0, 10.0, 72.0),
284            Err(VectorError::InvalidCanvas { .. })
285        ));
286        let mut problems = Problems::default();
287        assert_eq!(problems.record(Ok::<_, VectorError>(3)), Some(3));
288        assert_eq!(
289            problems.record(Err::<(), _>(VectorError::NonFinite("x"))),
290            None
291        );
292        assert!(problems.into_result(()).is_err());
293    }
294}