Skip to main content

pltrs_render/pgf/
mod.rs

1//! The PGF backend: matplotlib's `RendererPgf`, which writes a figure as
2//! the drawing commands of a LaTeX `pgfpicture` environment.
3//!
4//! Paths become `\pgfpath…` commands in inches, markers are defined once
5//! per draw call as a PGF object and placed at every vertex, hatches are
6//! tiled one-inch pattern objects, images are written as PNG files beside
7//! the document and included with `\includegraphics`, and text is left to
8//! LaTeX: each line becomes a `\pgftext` with font commands for its
9//! family, size, style and weight, anchored where and as matplotlib
10//! anchors it. Mathtext is passed through for LaTeX to typeset.
11//!
12//! The writer places text where the figure's layout put it: matplotlib
13//! measures text with LaTeX while laying the figure out, which pltrs does
14//! when a save asks for it (the `pltrs` crate's `PgfTextMetrics`), and
15//! otherwise with its own text engine, text positions then following the
16//! metrics of the fonts it finds. Images go beside the document as PNG
17//! files with their rows from the top, as matplotlib writes them.
18
19mod path;
20mod text;
21
22pub use text::{pgf_text, pgf_unknown_family};
23
24use std::fmt::Write as _;
25
26use pltrs_core::alloc::OutOfMemory;
27use pltrs_core::path::convert::SimplifySettings;
28use pltrs_core::{Affine2D, Path, Point, Rgba};
29use pltrs_text::TextRun;
30use pltrs_text::tex::{TexError, TexText};
31
32use crate::gc::GraphicsContext;
33use crate::image::RgbaImage;
34use crate::renderer::Renderer;
35use crate::svg::ImageFile;
36use crate::vector::{Problems, VectorError, check_canvas, fixed};
37
38/// LaTeX points per inch (TeX's `pt`), as opposed to PostScript points.
39const LATEX_POINTS_PER_INCH: f64 = 72.27;
40/// matplotlib's points per inch.
41const POINTS_PER_INCH: f64 = 72.0;
42
43/// Settings of a PGF document (matplotlib's `pgf.*` rcParams and the
44/// file it is written to).
45#[derive(Clone, Debug, PartialEq)]
46pub struct PgfOptions {
47    /// `path.simplify` and `path.simplify_threshold`.
48    pub simplify: SimplifySettings,
49    /// `image.composite_image`.
50    pub composite_images: bool,
51    /// `pgf.rcfonts`: select fonts by name through `fontspec`; otherwise
52    /// families other than the generic ones use LaTeX's default.
53    pub rcfonts: bool,
54    /// The family names of the installed fonts, which `pgf.rcfonts`
55    /// selects by name (matplotlib's `fontManager.ttflist`).
56    pub font_names: Vec<String>,
57    /// The LaTeX preamble the figure assumes, recorded in the header
58    /// (matplotlib's `_get_preamble()`).
59    pub preamble: String,
60    /// The stem of the document's file name: images go beside it as
61    /// `<stem>-img<N>.png`. Without one, images cannot be written.
62    pub image_stem: Option<String>,
63}
64
65impl Default for PgfOptions {
66    fn default() -> Self {
67        Self {
68            simplify: SimplifySettings::default(),
69            composite_images: true,
70            rcfonts: true,
71            font_names: Vec::new(),
72            preamble: String::new(),
73            image_stem: None,
74        }
75    }
76}
77
78/// A finished PGF document and the images to write beside it.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct PgfDocument {
81    /// The `pgfpicture` and its header.
82    pub text: String,
83    /// The PNG files the picture includes, in drawing order.
84    pub images: Vec<ImageFile>,
85}
86
87/// Renders into a PGF picture exactly like matplotlib's `RendererPgf`.
88///
89/// Coordinates are display pixels at the figure's resolution, written in
90/// inches.
91#[derive(Debug)]
92pub struct PgfRenderer {
93    width: f64,
94    height: f64,
95    dpi: f64,
96    options: PgfOptions,
97    body: String,
98    images: Vec<ImageFile>,
99    ignored_fonts: Vec<String>,
100    problems: Problems,
101}
102
103impl PgfRenderer {
104    /// A picture of `width × height` inches drawn at `dpi`.
105    ///
106    /// # Errors
107    ///
108    /// When the size or resolution is not positive and finite.
109    pub fn new(
110        width: f64,
111        height: f64,
112        dpi: f64,
113        options: PgfOptions,
114    ) -> Result<Self, VectorError> {
115        check_canvas(width, height, dpi)?;
116        Ok(Self {
117            width: width * dpi,
118            height: height * dpi,
119            dpi,
120            options,
121            body: String::new(),
122            images: Vec::new(),
123            ignored_fonts: Vec::new(),
124            problems: Problems::default(),
125        })
126    }
127
128    /// The picture commands drawn since the picture began or the last
129    /// call, with the images they include, which leaves the picture empty
130    /// (matplotlib's `RendererPgf` writes them to its file as it goes).
131    pub fn take_body(&mut self) -> (String, Vec<ImageFile>) {
132        (
133            std::mem::take(&mut self.body),
134            std::mem::take(&mut self.images),
135        )
136    }
137
138    /// The families no font has that the texts drawn since the picture
139    /// began or the last call asked for, one per text in drawing order,
140    /// which leaves none: those matplotlib's `draw_text` logs as "Ignoring
141    /// unknown font" (see [`pgf_unknown_family`]).
142    pub fn take_ignored_fonts(&mut self) -> Vec<String> {
143        std::mem::take(&mut self.ignored_fonts)
144    }
145
146    /// The document (matplotlib's `_print_pgf_to_fh`).
147    ///
148    /// # Errors
149    ///
150    /// When an image could not be encoded or written.
151    pub fn finish(self) -> Result<PgfDocument, VectorError> {
152        let mut text = String::from(HEADER);
153        text.push_str("%% pltrs used the following preamble\n");
154        for line in self.options.preamble.lines() {
155            let _ = writeln!(text, "%%   {line}");
156        }
157        text.push_str("%%\n");
158        writeln_pgf(&mut text, r"\begingroup");
159        writeln_pgf(&mut text, r"\makeatletter");
160        writeln_pgf(&mut text, r"\begin{pgfpicture}");
161        writeln_pgf(
162            &mut text,
163            &format!(
164                r"\pgfpathrectangle{{\pgfpointorigin}}{{\pgfqpoint{{{}in}}{{{}in}}}}",
165                num(self.width / self.dpi),
166                num(self.height / self.dpi)
167            ),
168        );
169        writeln_pgf(&mut text, r"\pgfusepath{use as bounding box, clip}");
170        if text.try_reserve(self.body.len()).is_err() {
171            let bytes = text.len().saturating_add(self.body.len());
172            return Err(OutOfMemory { bytes }.into());
173        }
174        text.push_str(&self.body);
175        writeln_pgf(&mut text, r"\end{pgfpicture}");
176        writeln_pgf(&mut text, r"\makeatother");
177        writeln_pgf(&mut text, r"\endgroup");
178        self.problems.into_result(PgfDocument {
179            text,
180            images: self.images,
181        })
182    }
183
184    /// Writes one line of the picture. A picture larger than the memory
185    /// the system gives (a hatch tile written for each of thousands of
186    /// paths, as matplotlib writes it) stops growing, and the print fails
187    /// as running out of memory does.
188    fn line(&mut self, line: &str) {
189        let needed = line.len() + 2;
190        if self.body.try_reserve(needed).is_err() {
191            let bytes = self.body.len().saturating_add(needed);
192            self.problems
193                .record::<()>(Err(OutOfMemory { bytes }.into()));
194            return;
195        }
196        writeln_pgf(&mut self.body, line);
197    }
198
199    /// Display pixels to inches.
200    fn inches(&self, pixels: f64) -> f64 {
201        pixels / self.dpi
202    }
203}
204
205/// The header comment of every document.
206const HEADER: &str = r"%% Creator: pltrs, PGF backend
207%%
208%% To include the figure in your LaTeX document, write
209%%   \input{<filename>.pgf}
210%%
211%% Make sure the required packages are loaded in your preamble
212%%   \usepackage{pgf}
213%%
214%% Also ensure that all the required font packages are loaded; for instance,
215%% the lmodern package is sometimes necessary when using math font.
216%%   \usepackage{lmodern}
217%%
218%% Figures using additional raster images can only be included by \input if
219%% they are in the same directory as the main LaTeX file. For loading figures
220%% from other directories you can use the `import` package
221%%   \usepackage{import}
222%%
223%% and then include the figures with
224%%   \import{<path to file>}{<filename>.pgf}
225%%
226";
227
228/// Writes `line` ending in `%`, which keeps TeX from inserting spurious
229/// spaces (`_writeln`).
230fn writeln_pgf(out: &mut String, line: &str) {
231    out.push_str(line);
232    out.push_str("%\n");
233}
234
235/// A number as `%f` writes it: six decimals (TeX knows no scientific
236/// notation).
237fn num(value: f64) -> String {
238    fixed(value, 6)
239}
240
241/// A length in matplotlib points as TeX points (`pt`), as matplotlib
242/// converts line widths.
243fn latex_points(points: f64) -> f64 {
244    points / POINTS_PER_INCH * LATEX_POINTS_PER_INCH
245}
246
247impl Renderer for PgfRenderer {
248    fn canvas_size(&self) -> (f64, f64) {
249        (self.width, self.height)
250    }
251
252    fn dpi(&self) -> f64 {
253        self.dpi
254    }
255
256    fn draw_path(
257        &mut self,
258        gc: &GraphicsContext,
259        path: &Path,
260        transform: &Affine2D,
261        fill: Option<Rgba>,
262    ) {
263        self.pgf_path(gc, path, transform, fill);
264    }
265
266    fn draw_markers(
267        &mut self,
268        gc: &GraphicsContext,
269        marker: &Path,
270        marker_transform: &Affine2D,
271        path: &Path,
272        transform: &Affine2D,
273        fill: Option<Rgba>,
274    ) {
275        self.pgf_markers(gc, marker, marker_transform, path, transform, fill);
276    }
277
278    fn draw_gouraud_triangles(
279        &mut self,
280        _gc: &GraphicsContext,
281        _triangles: &[[Point; 3]],
282        _colors: &[[Rgba; 3]],
283        _transform: &Affine2D,
284    ) {
285        // matplotlib's `RendererBase.draw_gouraud_triangles` raises.
286        self.problems.record::<()>(Err(VectorError::Unsupported(
287            "PGF cannot draw Gouraud-shaded triangles",
288        )));
289    }
290
291    fn draw_image(
292        &mut self,
293        gc: &GraphicsContext,
294        origin: Point,
295        image: &RgbaImage,
296        transform: Option<&Affine2D>,
297    ) {
298        self.pgf_image(gc, origin, image, transform);
299    }
300
301    fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
302        self.pgf_text(gc, run, origin, angle);
303    }
304
305    /// TeX text goes to LaTeX as it is, like any text (matplotlib's
306    /// `draw_tex` calls `draw_text`).
307    fn draw_tex(
308        &mut self,
309        gc: &GraphicsContext,
310        run: &TextRun,
311        _tex: &TexText,
312        origin: Point,
313        angle: f64,
314    ) -> Result<(), TexError> {
315        self.pgf_text(gc, run, origin, angle);
316        Ok(())
317    }
318
319    fn option_image_nocomposite(&self) -> bool {
320        !self.options.composite_images
321    }
322
323    fn option_scale_image(&self) -> bool {
324        true
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    #[test]
333    fn documents_hold_one_clipped_picture() {
334        let renderer = PgfRenderer::new(2.0, 1.0, 100.0, PgfOptions::default()).unwrap();
335        let document = renderer.finish().unwrap();
336        assert!(
337            document
338                .text
339                .starts_with("%% Creator: pltrs, PGF backend\n")
340        );
341        assert!(document.text.contains(
342            "\\begin{pgfpicture}%\n\\pgfpathrectangle{\\pgfpointorigin}{\\pgfqpoint{2.000000in}{1.000000in}}%\n\\pgfusepath{use as bounding box, clip}%\n\\end{pgfpicture}%\n"
343        ));
344        assert!(document.text.ends_with("\\makeatother%\n\\endgroup%\n"));
345        assert_eq!(document.images, []);
346    }
347
348    #[test]
349    fn numbers_and_widths() {
350        assert_eq!(num(1.0 / 3.0), "0.333333");
351        assert_eq!(num(-0.0), "-0.000000");
352        assert_eq!(num(1e20), "100000000000000000000.000000");
353        assert!((latex_points(72.0) - 72.27).abs() < 1e-12);
354    }
355
356    #[test]
357    fn gouraud_shading_is_an_error() {
358        let mut renderer = PgfRenderer::new(1.0, 1.0, 72.0, PgfOptions::default()).unwrap();
359        renderer.draw_gouraud_triangles(
360            &GraphicsContext::default(),
361            &[[Point::new(0.0, 0.0); 3]],
362            &[[Rgba::BLACK; 3]],
363            &Affine2D::IDENTITY,
364        );
365        assert!(matches!(
366            renderer.finish(),
367            Err(VectorError::Unsupported(_))
368        ));
369    }
370}