Skip to main content

pltrs_render/svg/
mod.rs

1//! The SVG backend: matplotlib's `RendererSVG`.
2//!
3//! The document mirrors matplotlib's: paths with inline CSS styles,
4//! markers and large path collections as reusable `<defs>`, glyphs defined
5//! once as paths in `FreeType` units and placed with `<use>`, clip paths and
6//! hatch patterns written at the end, images inlined as base64 PNG and
7//! Gouraud triangles emulated with three linear gradients. Text is written
8//! as glyph paths or, with `svg.fonttype = "none"`, as text elements
9//! styled with CSS font properties. Images are always inlined
10//! (`svg.image_inline`).
11
12mod defs;
13mod draw;
14mod gouraud;
15mod metadata;
16mod style;
17mod tex;
18mod text;
19mod text_elements;
20mod xml;
21
22use std::collections::{HashMap, HashSet};
23use std::fmt;
24use std::str::FromStr;
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::time::{SystemTime, UNIX_EPOCH};
27
28use pltrs_codec::sha256::sha256_hex;
29use pltrs_core::path::convert::SimplifySettings;
30use pltrs_core::{Affine2D, Path, Point, Rgba};
31use pltrs_text::TextRun;
32use pltrs_text::tex::{TexError, TexText};
33
34use self::defs::{Clips, Hatches};
35pub use self::xml::{Attribute, XmlWriter};
36use crate::collection::PathCollection;
37use crate::gc::GraphicsContext;
38use crate::image::RgbaImage;
39use crate::renderer::Renderer;
40use crate::vector::{FontCache, Metadata, Problems, VectorError, check_canvas, short};
41
42/// The XML declaration and doctype every document starts with
43/// (matplotlib's `svgProlog`).
44pub const PROLOG: &str = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n\
45<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \
46\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
47
48/// How an SVG document writes text (matplotlib's `svg.fonttype`).
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
50pub enum SvgFontType {
51    /// Glyphs as paths (`"path"`).
52    #[default]
53    Path,
54    /// Text elements, rendered with the viewer's fonts (`"none"`).
55    None,
56}
57
58pltrs_core::archive_enum!(SvgFontType { Path, None });
59
60impl SvgFontType {
61    /// matplotlib's name (`path` or `none`).
62    pub const fn name(self) -> &'static str {
63        match self {
64            Self::Path => "path",
65            Self::None => "none",
66        }
67    }
68}
69
70impl fmt::Display for SvgFontType {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(self.name())
73    }
74}
75
76impl FromStr for SvgFontType {
77    type Err = UnknownSvgFontType;
78
79    /// Parses matplotlib's name ([`SvgFontType::name`]).
80    fn from_str(name: &str) -> Result<Self, UnknownSvgFontType> {
81        [Self::Path, Self::None]
82            .into_iter()
83            .find(|fonttype| fonttype.name() == name)
84            .ok_or_else(|| UnknownSvgFontType(name.to_owned()))
85    }
86}
87
88/// A name that is not an [`SvgFontType`].
89#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct UnknownSvgFontType(pub String);
91
92impl fmt::Display for UnknownSvgFontType {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        write!(f, "{:?} is not a valid SVG font type", self.0)
95    }
96}
97
98impl std::error::Error for UnknownSvgFontType {}
99
100/// Settings of an SVG document (matplotlib's `svg.*` rcParams and the
101/// `metadata` argument of `savefig`).
102#[derive(Clone, Debug, PartialEq)]
103pub struct SvgOptions {
104    /// `svg.hashsalt`: salt of the content-derived ids. `None` gives each
105    /// document a salt of its own, as matplotlib's `uuid4` does, so that
106    /// documents embedded in one page do not share ids.
107    pub hashsalt: Option<String>,
108    /// `svg.id`: the `id` of the root element.
109    pub id: Option<String>,
110    /// Title, creator and date (written as Dublin Core metadata).
111    pub metadata: Metadata,
112    /// `path.simplify` and `path.simplify_threshold`.
113    pub simplify: SimplifySettings,
114    /// `image.composite_image`: whether images of one axes are composited
115    /// into one before drawing.
116    pub composite_images: bool,
117    /// `svg.fonttype`: glyphs as paths or text elements.
118    pub fonttype: SvgFontType,
119    /// `svg.image_inline = False`: the file name of the document, beside
120    /// which images go as `<name>.image<N>.png` files the document links
121    /// to, instead of being embedded (`None`).
122    pub image_files: Option<String>,
123}
124
125/// An image written beside an SVG document instead of being embedded in
126/// it (see [`SvgOptions::image_files`]).
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct ImageFile {
129    /// The file name the document links to.
130    pub name: String,
131    /// The PNG file.
132    pub png: Vec<u8>,
133}
134
135impl Default for SvgOptions {
136    fn default() -> Self {
137        Self {
138            hashsalt: None,
139            id: None,
140            metadata: Metadata::default(),
141            simplify: SimplifySettings::default(),
142            composite_images: true,
143            fonttype: SvgFontType::Path,
144            image_files: None,
145        }
146    }
147}
148
149/// Renders into an SVG document exactly like matplotlib's `RendererSVG`.
150///
151/// Coordinates are points (1/72 inch); the canvas has its origin at the
152/// bottom left like every renderer, and the document flips it.
153#[derive(Debug)]
154pub struct SvgRenderer {
155    width: f64,
156    height: f64,
157    image_dpi: f64,
158    writer: XmlWriter,
159    root: usize,
160    salt: String,
161    options: SvgOptions,
162    groups: HashMap<String, usize>,
163    clips: Clips,
164    hatches: Hatches,
165    markers: HashMap<(String, String), String>,
166    path_collection_id: usize,
167    has_gouraud: bool,
168    gradients: usize,
169    glyphs: HashSet<String>,
170    fonts: FontCache,
171    /// The images written beside the document, in drawing order.
172    images: Vec<ImageFile>,
173    problems: Problems,
174}
175
176impl SvgRenderer {
177    /// A document of `width × height` points whose images are rasterized
178    /// at `image_dpi` (matplotlib's `RendererSVG(w, h, fh, image_dpi)`).
179    pub fn new(
180        width: f64,
181        height: f64,
182        image_dpi: f64,
183        options: SvgOptions,
184    ) -> Result<Self, VectorError> {
185        check_canvas(width, height, image_dpi)?;
186        let salt = options.hashsalt.clone().unwrap_or_else(fresh_salt);
187        let mut writer = XmlWriter::new(PROLOG);
188        let (w, h) = (short(width), short(height));
189        let root = writer.start(
190            "svg",
191            &[
192                ("xmlns:xlink", "http://www.w3.org/1999/xlink".to_owned()),
193                ("width", format!("{w}pt")),
194                ("height", format!("{h}pt")),
195                ("viewBox", format!("0 0 {w} {h}")),
196                ("xmlns", "http://www.w3.org/2000/svg".to_owned()),
197                ("version", "1.1".to_owned()),
198                ("id", options.id.clone().unwrap_or_default()),
199            ],
200        );
201        metadata::write(&mut writer, &options.metadata);
202        writer.start("defs", &[]);
203        writer.element(
204            "style",
205            "*{stroke-linejoin: round; stroke-linecap: butt}",
206            &[("type", "text/css".to_owned())],
207        );
208        writer.end(true);
209        Ok(Self {
210            width,
211            height,
212            image_dpi,
213            writer,
214            root,
215            salt,
216            options,
217            groups: HashMap::new(),
218            clips: Clips::default(),
219            hatches: Hatches::default(),
220            markers: HashMap::new(),
221            path_collection_id: 0,
222            has_gouraud: false,
223            gradients: 0,
224            glyphs: HashSet::new(),
225            fonts: FontCache::default(),
226            images: Vec::new(),
227            problems: Problems::default(),
228        })
229    }
230
231    /// Writes the clip paths and hatch patterns and closes the document
232    /// (matplotlib's `finalize`).
233    ///
234    /// # Errors
235    ///
236    /// When a font or image met while drawing could not be written.
237    pub fn finish(self) -> Result<String, VectorError> {
238        self.finish_with_images().map(|(document, _)| document)
239    }
240
241    /// Like [`SvgRenderer::finish`], also returning the images to write
242    /// beside the document (empty unless [`SvgOptions::image_files`]).
243    ///
244    /// # Errors
245    ///
246    /// When a font or image met while drawing could not be written.
247    pub fn finish_with_images(mut self) -> Result<(String, Vec<ImageFile>), VectorError> {
248        self.clips.write(&mut self.writer);
249        self.hatches.write(&mut self.writer);
250        self.writer.close(self.root);
251        let images = std::mem::take(&mut self.images);
252        self.problems
253            .into_result(self.writer.into_string())
254            .map(|document| (document, images))
255    }
256
257    /// `_make_id`: `type` followed by the first ten hex digits of the
258    /// SHA-256 of the salt and `content` (Python's `str` of the key).
259    fn make_id(&self, kind: &str, content: &str) -> String {
260        let digest = sha256_hex(format!("{}{content}", self.salt).as_bytes());
261        format!("{kind}{}", &digest[..10])
262    }
263
264    /// `_make_flip_transform`'s second half: y down from the top.
265    fn flip(&self) -> Affine2D {
266        Affine2D::scaling(1.0, -1.0).translate(0.0, self.height)
267    }
268
269    /// Opens a hyperlink around the next element when `gc` has a URL.
270    fn open_link(&mut self, gc: &GraphicsContext) -> bool {
271        let Some(url) = gc.url.clone() else {
272            return false;
273        };
274        self.writer
275            .start("a", &[("xlink:href", url), ("target", "_blank".to_owned())]);
276        true
277    }
278
279    /// Closes what [`open_link`](Self::open_link) opened.
280    fn close_link(&mut self, opened: bool) {
281        if opened {
282            self.writer.end(true);
283        }
284    }
285}
286
287impl Renderer for SvgRenderer {
288    fn canvas_size(&self) -> (f64, f64) {
289        (self.width, self.height)
290    }
291
292    /// The image resolution, as matplotlib's `MixedModeRenderer.dpi`.
293    fn dpi(&self) -> f64 {
294        self.image_dpi
295    }
296
297    /// Lengths are points already.
298    fn points_to_pixels(&self, points: f64) -> f64 {
299        points
300    }
301
302    fn draw_path(
303        &mut self,
304        gc: &GraphicsContext,
305        path: &Path,
306        transform: &Affine2D,
307        fill: Option<Rgba>,
308    ) {
309        self.svg_path(gc, path, *transform, fill);
310    }
311
312    fn draw_markers(
313        &mut self,
314        gc: &GraphicsContext,
315        marker: &Path,
316        marker_transform: &Affine2D,
317        path: &Path,
318        transform: &Affine2D,
319        fill: Option<Rgba>,
320    ) {
321        self.svg_markers(gc, marker, *marker_transform, path, *transform, fill);
322    }
323
324    fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
325        self.svg_path_collection(gc, collection);
326    }
327
328    fn draw_gouraud_triangles(
329        &mut self,
330        gc: &GraphicsContext,
331        triangles: &[[Point; 3]],
332        colors: &[[Rgba; 3]],
333        transform: &Affine2D,
334    ) {
335        self.svg_gouraud_triangles(gc, triangles, colors, *transform);
336    }
337
338    fn draw_image(
339        &mut self,
340        gc: &GraphicsContext,
341        origin: Point,
342        image: &RgbaImage,
343        transform: Option<&Affine2D>,
344    ) {
345        self.svg_image(gc, origin, image, transform.copied());
346    }
347
348    fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
349        self.svg_text(gc, run, origin, angle);
350    }
351
352    fn draw_tex(
353        &mut self,
354        gc: &GraphicsContext,
355        _run: &TextRun,
356        tex: &TexText,
357        origin: Point,
358        angle: f64,
359    ) -> Result<(), TexError> {
360        self.svg_tex(gc, tex, origin, angle)
361    }
362
363    fn open_group(&mut self, name: &str, gid: Option<&str>) {
364        let id = gid.filter(|g| !g.is_empty()).map_or_else(
365            || {
366                let count = self.groups.entry(name.to_owned()).or_insert(0);
367                *count += 1;
368                format!("{name}_{count}")
369            },
370            str::to_owned,
371        );
372        self.writer.start("g", &[("id", id)]);
373    }
374
375    fn close_group(&mut self, _name: &str) {
376        self.writer.end(true);
377    }
378
379    fn option_image_nocomposite(&self) -> bool {
380        !self.options.composite_images
381    }
382
383    fn option_scale_image(&self) -> bool {
384        true
385    }
386
387    fn image_magnification(&self) -> f64 {
388        self.image_dpi / 72.0
389    }
390}
391
392/// A salt no other document shares, for `svg.hashsalt: None` (matplotlib
393/// draws a random `uuid4`): the time to the nanosecond, the process and
394/// how many documents it salted before.
395fn fresh_salt() -> String {
396    static SALTED: AtomicU64 = AtomicU64::new(0);
397    let nanos = SystemTime::now()
398        .duration_since(UNIX_EPOCH)
399        .map_or(0, |elapsed| elapsed.as_nanos());
400    format!(
401        "pltrs-{nanos}-{}-{}",
402        std::process::id(),
403        SALTED.fetch_add(1, Ordering::Relaxed)
404    )
405}
406
407#[cfg(test)]
408mod tests;