Skip to main content

pltrs_render/ps/
psfrag.rs

1//! usetex text in PostScript with `text.usetex` on (matplotlib's
2//! `draw_tex` and the first half of `_print_figure_tex`): every text is a
3//! tag shown where it goes, which LaTeX's `psfrag` package replaces by the
4//! typeset text, and the figure is an EPS file without fonts that LaTeX
5//! includes. Running LaTeX, `dvips` and Ghostscript on it is left to the
6//! caller.
7
8use std::fmt::Write as _;
9
10use pltrs_core::{Bbox, Point};
11use pltrs_text::tex::{TexError, TexText};
12
13use super::dsc::bbox_header;
14use super::{PS_DEFS, PageOrientation, PsRenderer, draw};
15use crate::gc::GraphicsContext;
16use crate::vector::{VectorError, fixed, trimmed};
17
18/// A figure whose usetex texts are psfrag tags, ready for LaTeX
19/// (`_print_figure_tex` up to `_convert_psfrags`).
20#[derive(Clone, Debug, PartialEq)]
21pub struct PsfragFigure {
22    /// The figure as an EPS file without fonts, every usetex text a tag
23    /// (the `tmp.ps` LaTeX includes).
24    pub figure: String,
25    /// The `\psfrag` command replacing each tag by its text.
26    pub psfrags: Vec<String>,
27    /// The figure's width in inches.
28    pub width: f64,
29    /// The figure's height in inches.
30    pub height: f64,
31    /// The figure's bounding box in points, from the origin, turned on its
32    /// side in landscape (the `bbox` given to `gs_distill`).
33    pub bbox: Bbox,
34}
35
36/// The LaTeX font family command of the generic family `family`
37/// (`font.family[0]`), as `draw_tex` picks it.
38fn family_command(family: Option<&str>) -> &'static str {
39    match family {
40        Some("sans-serif") => r"\sffamily",
41        Some("monospace") => r"\ttfamily",
42        _ => r"\rmfamily",
43    }
44}
45
46impl PsRenderer {
47    /// `draw_tex` with `text.usetex`: shows the tag `psmarker<n>` at the
48    /// text's bottom left (the baseline moved down by the descent TeX
49    /// measures) and records the `\psfrag` command that puts the text,
50    /// at its size and colour and in the family of `font.family`, in its
51    /// place, rotated by `angle`.
52    pub(super) fn psfrag_mark(
53        &mut self,
54        gc: &GraphicsContext,
55        tex: &TexText,
56        origin: Point,
57        angle: f64,
58    ) -> Result<(), TexError> {
59        let (_, _, descent) = tex
60            .manager
61            .text_width_height_descent(&tex.tex, tex.size(), 1.0)?;
62        let tag = format!("psmarker{}", self.psfrags.len());
63        let rgb = gc.stroke_color();
64        let color = [rgb.r, rgb.g, rgb.b].map(|v| trimmed(v, 3)).join(",");
65        let family = family_command(tex.manager.fonts().family.first().map(String::as_str));
66        let size = tex.size();
67        self.psfrags.push(format!(
68            r"\psfrag{{{tag}}}[bl][bl][1][{}]{{\fontsize{{{}}}{{{}}}\color[rgb]{{{color}}} {{{family} {}}}}}",
69            fixed(angle, 6),
70            fixed(size, 6),
71            fixed(size * 1.25, 6),
72            tex.tex
73        ));
74        let up = (angle + 90.0).to_radians();
75        let position = draw::nums(&[origin.x - descent * up.cos(), origin.y - descent * up.sin()]);
76        let _ = write!(
77            self.body,
78            "gsave\n{position} moveto\n({tag})\nshow\ngrestore\n"
79        );
80        Ok(())
81    }
82
83    /// The figure LaTeX includes (`tmp.ps`): EPS at the origin with the
84    /// procedures but no fonts, the drawing with its tags, and the psfrag
85    /// commands.
86    ///
87    /// # Errors
88    ///
89    /// When something drawn could not be written.
90    pub(super) fn psfrag_figure(self) -> Result<PsfragFigure, VectorError> {
91        let (width, height) = (self.width, self.height);
92        let page = Bbox::from_extents(0.0, 0.0, width * 72.0, height * 72.0);
93        let mut figure = format!(
94            "%!PS-Adobe-3.0 EPSF-3.0\n%%LanguageLevel: 3\n{}",
95            self.dsc_comments()
96        );
97        let _ = write!(
98            figure,
99            "{}\n%%EndComments\n%%BeginProlog\n/mpldict {} dict def\nmpldict begin\n{}\nend\n\
100             %%EndProlog\nmpldict begin\n0 0 translate\n0 0 {} rectclip\n{}\nend\nshowpage\n",
101            bbox_header(&page),
102            PS_DEFS.len(),
103            PS_DEFS.concat(),
104            draw::nums(&[width * 72.0, height * 72.0]),
105            self.body
106        );
107        let bbox = match self.options.orientation {
108            PageOrientation::Portrait => page,
109            PageOrientation::Landscape => Bbox::from_extents(0.0, 0.0, page.y1(), page.x1()),
110        };
111        self.problems.into_result(PsfragFigure {
112            figure,
113            psfrags: self.psfrags,
114            width,
115            height,
116            bbox,
117        })
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn the_first_family_picks_the_command() {
127        assert_eq!(family_command(Some("sans-serif")), r"\sffamily");
128        assert_eq!(family_command(Some("monospace")), r"\ttfamily");
129        assert_eq!(family_command(Some("Sans-Serif")), r"\rmfamily");
130        assert_eq!(family_command(None), r"\rmfamily");
131    }
132}