Skip to main content

pltrs_render/ps/
mod.rs

1//! The PostScript backend: matplotlib's `RendererPS`, writing PostScript
2//! (centred on a page of `ps.papersize`) or Encapsulated PostScript (sized
3//! to the figure).
4//!
5//! Every drawing is wrapped in `gsave`/`grestore`; line properties and
6//! the stroke colour are only written when they change. Markers and large
7//! path collections become procedures, clip paths procedures reused while
8//! the same clip comes back, hatches pattern dictionaries, images hex
9//! `colorimage` data and Gouraud triangles type 4 shadings. Fonts are
10//! embedded in the prolog as Type 3 programs or, with `ps.fonttype = 42`,
11//! as Type 42 fonts over TrueType subsets. With `ps.useafm`, text that is
12//! not mathtext is shown in standard PostScript fonts placed by their AFM
13//! metrics instead, and no font is embedded at all (see `afm`).
14//! PostScript has no transparency: partially transparent colours are drawn
15//! opaque.
16//!
17//! With `text.usetex`, every text is a tag for LaTeX's `psfrag` package
18//! instead, and the renderer makes the figure LaTeX includes
19//! ([`PsfragFigure`]).
20//! The external programs matplotlib then runs (LaTeX, `dvips` and the
21//! distillers of `ps.usedistiller`) are the caller's; [`pstoeps`] turns
22//! what a distiller wrote back into EPS.
23
24mod afm;
25mod draw;
26mod dsc;
27mod fonts;
28mod page;
29mod psfrag;
30mod state;
31mod text;
32mod type42;
33
34use std::fmt::Write as _;
35
36use pltrs_core::path::convert::SimplifySettings;
37use pltrs_core::{Affine2D, Bbox, Path, Point, Rgba};
38use pltrs_text::tex::{TexError, TexText};
39use pltrs_text::{AfmDirectory, TextRun};
40
41use crate::collection::PathCollection;
42use crate::gc::{CapStyle, ClipPath, GraphicsContext, JoinStyle};
43use crate::image::RgbaImage;
44use crate::renderer::Renderer;
45pub use dsc::pstoeps;
46pub use page::{PageOrientation, PageSetupError, Paper};
47pub use psfrag::PsfragFigure;
48
49use crate::vector::{
50    CharacterTracker, FontCache, FontType, Metadata, Problems, VectorError, check_canvas,
51};
52
53/// Settings of a PostScript document.
54#[derive(Clone, Debug, PartialEq)]
55#[expect(
56    clippy::struct_excessive_bools,
57    reason = "mirrors matplotlib's independent rcParams"
58)]
59pub struct PsOptions {
60    /// Encapsulated PostScript: no page, sized to the figure.
61    pub eps: bool,
62    /// `ps.papersize` (ignored for EPS).
63    pub paper: Paper,
64    /// `savefig.orientation`.
65    pub orientation: PageOrientation,
66    /// Title, creator and creation date (DSC comments).
67    pub metadata: Metadata,
68    /// `path.simplify` and `path.simplify_threshold`.
69    pub simplify: SimplifySettings,
70    /// `image.composite_image`.
71    pub composite_images: bool,
72    /// `ps.fonttype`: how TrueType fonts are embedded.
73    pub fonttype: FontType,
74    /// `ps.useafm`: text that is not mathtext is drawn in standard
75    /// PostScript fonts, measured with their AFM metrics, and no font is
76    /// embedded.
77    pub afm: bool,
78    /// `text.usetex`: texts are tags for LaTeX's `psfrag` package, and
79    /// [`PsRenderer::finish`] makes the figure LaTeX includes
80    /// ([`PsOutput::Psfrag`]); with it off, texts marked usetex are drawn
81    /// as plain text, as matplotlib draws them.
82    pub usetex: bool,
83}
84
85impl Default for PsOptions {
86    fn default() -> Self {
87        Self {
88            eps: false,
89            paper: Paper::from_name("letter").unwrap_or(Paper::Figure),
90            orientation: PageOrientation::Portrait,
91            metadata: Metadata::default(),
92            simplify: SimplifySettings::default(),
93            composite_images: true,
94            fonttype: FontType::Type3,
95            afm: false,
96            usetex: false,
97        }
98    }
99}
100
101impl PsOptions {
102    /// The AFM fonts text that is not mathtext is drawn in, and must be
103    /// measured with, if any (`RendererPS._afm_font_dir` when `ps.useafm`
104    /// is set): those of `fonts/afm`, the 35 standard PostScript fonts.
105    pub fn afm_directory(&self) -> Option<AfmDirectory> {
106        self.afm.then_some(AfmDirectory::PostScript)
107    }
108}
109
110/// A finished PostScript document and where the figure sits on its page.
111#[derive(Clone, Debug, PartialEq)]
112pub struct PsDocument {
113    /// The PostScript or EPS document.
114    pub text: String,
115    /// The figure's bounding box on the page in points, turned with the
116    /// page in landscape (the `bbox` of `_print_figure`).
117    pub bbox: Bbox,
118}
119
120/// What a [`PsRenderer`] made of a figure.
121#[derive(Clone, Debug, PartialEq)]
122pub enum PsOutput {
123    /// The document (matplotlib's `_print_figure`).
124    Document(PsDocument),
125    /// With [`PsOptions::usetex`], the figure for LaTeX to finish
126    /// (matplotlib's `_print_figure_tex`).
127    Psfrag(PsfragFigure),
128}
129
130/// The line properties last written (`None` until first set).
131#[derive(Clone, Debug, Default, PartialEq)]
132struct LineState {
133    color: Option<[f64; 3]>,
134    width: Option<f64>,
135    join: Option<JoinStyle>,
136    cap: Option<CapStyle>,
137    dash: Option<(f64, Option<Vec<f64>>)>,
138    font: Option<(String, f64)>,
139}
140
141/// Renders into a PostScript document exactly like matplotlib's
142/// `RendererPS`. Coordinates are points with the origin at the bottom
143/// left.
144#[derive(Debug)]
145pub struct PsRenderer {
146    /// Figure size in inches.
147    width: f64,
148    height: f64,
149    image_dpi: f64,
150    body: String,
151    line: LineState,
152    hatches: Vec<String>,
153    clip_paths: Vec<ClipPath>,
154    path_collection_id: usize,
155    tracker: CharacterTracker,
156    fonts: FontCache,
157    options: PsOptions,
158    /// The `\psfrag` commands of the usetex texts tagged so far.
159    psfrags: Vec<String>,
160    /// Whether usetex text was drawn as plain text.
161    tex_drawn_as_plain: bool,
162    /// Whether a partially transparent colour was drawn.
163    partially_transparent: bool,
164    problems: Problems,
165}
166
167impl PsRenderer {
168    /// A document for a figure of `width × height` inches whose images are
169    /// rasterized at `image_dpi`.
170    pub fn new(
171        width: f64,
172        height: f64,
173        image_dpi: f64,
174        options: PsOptions,
175    ) -> Result<Self, VectorError> {
176        check_canvas(width, height, image_dpi)?;
177        Ok(Self {
178            width,
179            height,
180            image_dpi,
181            body: String::new(),
182            line: LineState::default(),
183            hatches: Vec::new(),
184            clip_paths: Vec::new(),
185            path_collection_id: 0,
186            tracker: CharacterTracker::new(options.fonttype.subset_size()),
187            fonts: FontCache::default(),
188            options,
189            psfrags: Vec::new(),
190            tex_drawn_as_plain: false,
191            partially_transparent: false,
192            problems: Problems::default(),
193        })
194    }
195
196    /// Whether some usetex text was drawn as plain text so far, since
197    /// without [`PsOptions::usetex`] the backend runs no TeX (what
198    /// matplotlib's `draw_tex` logs as it draws, once per document).
199    pub fn drew_tex_as_plain(&self) -> bool {
200        self.tex_drawn_as_plain
201    }
202
203    /// Whether a partially transparent colour was drawn so far, opaque
204    /// (what matplotlib's `_is_transparent` logs as it draws, once per
205    /// document).
206    pub fn drew_partial_transparency(&self) -> bool {
207        self.partially_transparent
208    }
209
210    /// The document: header comments, the prolog with the procedures and
211    /// fonts, then the drawing placed on the page (matplotlib's
212    /// `_print_figure`); with [`PsOptions::usetex`], the figure whose
213    /// texts LaTeX typesets ([`PsOutput::Psfrag`]).
214    ///
215    /// # Errors
216    ///
217    /// When a font met while drawing could not be embedded, or TeX could
218    /// not measure a usetex text.
219    pub fn finish(self) -> Result<PsOutput, VectorError> {
220        if self.options.usetex {
221            self.psfrag_figure().map(PsOutput::Psfrag)
222        } else {
223            self.write_document().map(PsOutput::Document)
224        }
225    }
226
227    /// The `%%Title`, `%%Creator` and `%%CreationDate` comments of the
228    /// metadata, one per line (matplotlib's `dsc_comments`).
229    fn dsc_comments(&self) -> String {
230        let metadata = &self.options.metadata;
231        let mut comments = String::new();
232        if let Some(title) = &metadata.title {
233            let ascii: String = title
234                .chars()
235                .map(|c| if c.is_ascii() { c } else { '?' })
236                .collect();
237            let _ = writeln!(comments, "%%Title: {ascii}");
238        }
239        if let Some(creator) = &metadata.creator {
240            let _ = writeln!(comments, "%%Creator: {creator}");
241        }
242        if let Some(date) = metadata.date {
243            let _ = writeln!(comments, "%%CreationDate: {}", date.ctime());
244        }
245        comments
246    }
247
248    /// The document of [`finish`](Self::finish) without usetex.
249    fn write_document(mut self) -> Result<PsDocument, VectorError> {
250        let (width, height) = (self.width, self.height);
251        let (paper_width, paper_height) = match (self.options.eps, self.options.paper) {
252            (false, Paper::Named { width, height, .. }) => match self.options.orientation {
253                PageOrientation::Portrait => (width, height),
254                PageOrientation::Landscape => (height, width),
255            },
256            _ => (width, height),
257        };
258        let (mut xo, mut yo) = (
259            72.0 * 0.5 * (paper_width - width),
260            72.0 * 0.5 * (paper_height - height),
261        );
262        let (mut llx, mut lly) = (xo, yo);
263        let (mut urx, mut ury) = (llx + width * 72.0, lly + height * 72.0);
264        let landscape = self.options.orientation == PageOrientation::Landscape;
265        if landscape {
266            (llx, lly, urx, ury) = (lly, llx, ury, urx);
267            (xo, yo) = (72.0 * paper_height - yo, xo);
268        }
269        let mut out = String::new();
270        if self.options.eps {
271            out.push_str("%!PS-Adobe-3.0 EPSF-3.0\n");
272        } else {
273            out.push_str("%!PS-Adobe-3.0\n");
274            if let Paper::Named { name, .. } = self.options.paper {
275                let _ = writeln!(out, "%%DocumentPaperSizes: {name}");
276            }
277            out.push_str("%%Pages: 1\n");
278        }
279        out.push_str("%%LanguageLevel: 3\n");
280        out.push_str(&self.dsc_comments());
281        let bbox = Bbox::from_extents(llx, lly, urx, ury);
282        let _ = writeln!(
283            out,
284            "%%Orientation: {}\n{}\n%%EndComments",
285            self.options.orientation.name(),
286            dsc::bbox_header(&bbox)
287        );
288        // With `ps.useafm` matplotlib embeds no font, not even the fonts
289        // mathtext was drawn with.
290        let fonts: Vec<_> = if self.options.afm {
291            Vec::new()
292        } else {
293            self.tracker
294                .fonts()
295                .map(|(id, subsets)| (id, subsets.to_vec()))
296                .collect()
297        };
298        let dictionary_size = PS_DEFS.len() + fonts.iter().map(|(_, s)| s.len()).sum::<usize>();
299        let _ = writeln!(
300            out,
301            "%%BeginProlog\n/mpldict {dictionary_size} dict def\nmpldict begin\n{}",
302            PS_DEFS.join("\n")
303        );
304        for (id, subsets) in fonts {
305            let font = self.fonts.get(id)?;
306            for (index, subset) in subsets.iter().enumerate().filter(|(_, s)| !s.is_empty()) {
307                match self.options.fonttype {
308                    FontType::Type3 => out.push_str(&fonts::type3_font(font, index, subset)),
309                    FontType::Type42 => out.push_str(&type42::type42_font(font, index, subset)?),
310                }
311            }
312        }
313        out.push_str("end\n%%EndProlog\n");
314        if !self.options.eps {
315            out.push_str("%%Page: 1 1\n");
316        }
317        let _ = writeln!(out, "mpldict begin\n{} translate", draw::nums(&[xo, yo]));
318        if landscape {
319            out.push_str("90 rotate\n");
320        }
321        let _ = writeln!(
322            out,
323            "0 0 {} rectclip\n{}\nend\nshowpage",
324            draw::nums(&[width * 72.0, height * 72.0]),
325            self.body
326        );
327        if !self.options.eps {
328            out.push_str("%%EOF\n");
329        }
330        self.problems.into_result(PsDocument { text: out, bbox })
331    }
332}
333
334/// The procedures of `mpldict` (`_psDefs`).
335const PS_DEFS: [&str; 8] = [
336    "/_d { bind def } bind def",
337    "/m { moveto } _d",
338    "/l { lineto } _d",
339    "/r { rlineto } _d",
340    "/c { curveto } _d",
341    "/cl { closepath } _d",
342    "/ce { closepath eofill } _d",
343    "/sc { setcachedevice } _d",
344];
345
346impl Renderer for PsRenderer {
347    fn canvas_size(&self) -> (f64, f64) {
348        (self.width * 72.0, self.height * 72.0)
349    }
350
351    /// The image resolution, as matplotlib's `MixedModeRenderer.dpi`.
352    fn dpi(&self) -> f64 {
353        self.image_dpi
354    }
355
356    /// Lengths are points already.
357    fn points_to_pixels(&self, points: f64) -> f64 {
358        points
359    }
360
361    fn draw_path(
362        &mut self,
363        gc: &GraphicsContext,
364        path: &Path,
365        transform: &Affine2D,
366        fill: Option<Rgba>,
367    ) {
368        self.ps_path(gc, path, *transform, fill);
369    }
370
371    fn draw_markers(
372        &mut self,
373        gc: &GraphicsContext,
374        marker: &Path,
375        marker_transform: &Affine2D,
376        path: &Path,
377        transform: &Affine2D,
378        fill: Option<Rgba>,
379    ) {
380        self.ps_markers(gc, marker, *marker_transform, path, *transform, fill);
381    }
382
383    fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
384        self.ps_path_collection(gc, collection);
385    }
386
387    fn draw_gouraud_triangles(
388        &mut self,
389        _gc: &GraphicsContext,
390        triangles: &[[Point; 3]],
391        colors: &[[Rgba; 3]],
392        transform: &Affine2D,
393    ) {
394        self.ps_gouraud_triangles(triangles, colors, *transform);
395    }
396
397    fn draw_image(
398        &mut self,
399        gc: &GraphicsContext,
400        origin: Point,
401        image: &RgbaImage,
402        transform: Option<&Affine2D>,
403    ) {
404        self.ps_image(gc, origin, image, transform.copied());
405    }
406
407    fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
408        self.ps_text(gc, run, origin, angle);
409    }
410
411    fn draw_tex(
412        &mut self,
413        gc: &GraphicsContext,
414        _run: &TextRun,
415        tex: &TexText,
416        origin: Point,
417        angle: f64,
418    ) -> Result<(), TexError> {
419        self.ps_tex(gc, tex, origin, angle)
420    }
421
422    fn option_image_nocomposite(&self) -> bool {
423        !self.options.composite_images
424    }
425
426    fn option_scale_image(&self) -> bool {
427        true
428    }
429
430    fn image_magnification(&self) -> f64 {
431        self.image_dpi / 72.0
432    }
433}
434
435#[cfg(test)]
436mod tests;