Skip to main content

pltrs_render/ps/
state.rs

1//! The graphics state of a page as matplotlib's `RendererPS` keeps it:
2//! colour, line width, join, cap, dashes and font are written only when
3//! they change (`set_color`, `set_linewidth`, `set_linejoin`,
4//! `set_linecap`, `set_linedash`, `set_font`), hatches are defined once
5//! (`create_hatch`), and what was written so far can be taken out of the
6//! page (`take_body`), as a renderer writing to a program's file does.
7
8use std::fmt::Write as _;
9
10use pltrs_core::Affine2D;
11
12use super::PsRenderer;
13use super::draw::{cap_code, color_cmd, join_code, nums};
14use crate::gc::{CapStyle, GraphicsContext, JoinStyle};
15use crate::vector::general;
16
17impl PsRenderer {
18    /// The PostScript written to the page since the document began or the
19    /// last call, which leaves the page empty (matplotlib's `RendererPS`
20    /// writes it to its `pswriter` as it goes).
21    pub fn take_body(&mut self) -> String {
22        std::mem::take(&mut self.body)
23    }
24
25    /// Sets the colour (`setgray` for greys) when it changed, keeping it
26    /// as the page's when `store` (matplotlib's `set_color`).
27    pub fn set_color(&mut self, rgb: [f64; 3], store: bool) {
28        if self.line.color != Some(rgb) {
29            self.body.push_str(&color_cmd(rgb));
30            self.body.push('\n');
31            if store {
32                self.line.color = Some(rgb);
33            }
34        }
35    }
36
37    /// Sets the line width in points when it changed (matplotlib's
38    /// `set_linewidth`).
39    pub fn set_linewidth(&mut self, width: f64, store: bool) {
40        if self.line.width != Some(width) {
41            let _ = writeln!(self.body, "{} setlinewidth", nums(&[width]));
42            if store {
43                self.line.width = Some(width);
44            }
45        }
46    }
47
48    /// Sets the line join when it changed (matplotlib's `set_linejoin`).
49    pub fn set_linejoin(&mut self, join: JoinStyle, store: bool) {
50        if self.line.join != Some(join) {
51            let _ = writeln!(self.body, "{} setlinejoin", join_code(join));
52            if store {
53                self.line.join = Some(join);
54            }
55        }
56    }
57
58    /// Sets the line cap when it changed (matplotlib's `set_linecap`).
59    pub fn set_linecap(&mut self, cap: CapStyle, store: bool) {
60        if self.line.cap != Some(cap) {
61            let _ = writeln!(self.body, "{} setlinecap", cap_code(cap));
62            if store {
63                self.line.cap = Some(cap);
64            }
65        }
66    }
67
68    /// Sets the dashes, `offset` into `pattern` (none, or an empty one,
69    /// for solid lines), when they changed (matplotlib's `set_linedash`).
70    pub fn set_linedash(&mut self, offset: f64, pattern: Option<&[f64]>, store: bool) {
71        let dash = (
72            offset,
73            pattern
74                .filter(|pattern| !pattern.is_empty())
75                .map(<[f64]>::to_vec),
76        );
77        if self.line.dash.as_ref() == Some(&dash) {
78            return;
79        }
80        if let Some(pattern) = &dash.1 {
81            let _ = writeln!(self.body, "[{}] {} setdash", nums(pattern), nums(&[dash.0]));
82        } else {
83            self.body.push_str("[] 0 setdash\n");
84        }
85        if store {
86            self.line.dash = Some(dash);
87        }
88    }
89
90    /// Selects the font `name` at `size` points when it changed
91    /// (matplotlib's `set_font`).
92    pub fn set_font(&mut self, name: &str, size: f64, store: bool) {
93        let font = (name.to_owned(), size);
94        if self.line.font.as_ref() != Some(&font) {
95            let _ = writeln!(self.body, "/{name} {size:.3} selectfont");
96            if store {
97                self.line.font = Some(font);
98            }
99        }
100    }
101
102    /// The name of the pattern of `hatch`, defined on first use with lines
103    /// `linewidth` points wide (matplotlib's `create_hatch`; hatches are
104    /// told apart by their pattern only).
105    pub fn create_hatch(&mut self, pattern: &str, linewidth: f64) -> String {
106        if let Some(index) = self.hatches.iter().position(|h| h == pattern) {
107            return format!("H{index}");
108        }
109        let name = format!("H{}", self.hatches.len());
110        let tile = pltrs_core::hatch::pattern_path(pattern, pltrs_core::hatch::DEFAULT_DENSITY)
111            .unwrap_or_default();
112        let path = self.convert(&tile, Affine2D::scaling(72.0, 72.0), false, None);
113        let _ = writeln!(
114            self.body,
115            "  << /PatternType 1\n     /PaintType 2\n     /TilingType 2\n     \
116             /BBox[0 0 72 72]\n     /XStep 72\n     /YStep 72\n\n     /PaintProc {{\n        \
117             pop\n        {} setlinewidth\n{path}\n        gsave\n        fill\n        \
118             grestore\n        stroke\n     }} bind\n   >>\n   matrix\n   0 {} translate\n   \
119             makepattern\n   /{name} exch def",
120            general(linewidth),
121            general(self.height * 72.0)
122        );
123        self.hatches.push(pattern.to_owned());
124        name
125    }
126
127    /// The line properties `_draw_ps` sets before stroking.
128    pub(super) fn set_line(&mut self, gc: &GraphicsContext) {
129        self.set_linewidth(gc.linewidth, true);
130        self.set_linejoin(gc.join, true);
131        self.set_linecap(gc.cap, true);
132        self.set_linedash(gc.dashes.offset, gc.dashes.pattern.as_deref(), true);
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use crate::ps::{PsOptions, PsRenderer};
139    use crate::{CapStyle, JoinStyle};
140
141    #[test]
142    fn states_are_written_once_until_they_change() {
143        let mut ps = PsRenderer::new(2.0, 2.0, 72.0, PsOptions::default()).unwrap();
144        ps.set_color([1.0, 0.0, 0.0], true);
145        ps.set_color([1.0, 0.0, 0.0], true);
146        ps.set_linewidth(2.0, true);
147        ps.set_linejoin(JoinStyle::Round, true);
148        ps.set_linecap(CapStyle::Projecting, false);
149        ps.set_linecap(CapStyle::Projecting, false);
150        ps.set_linedash(0.0, Some(&[3.0, 1.5]), true);
151        ps.set_font("DejaVuSans", 12.0, true);
152        assert_eq!(
153            ps.take_body(),
154            "1 0 0 setrgbcolor\n2 setlinewidth\n1 setlinejoin\n2 setlinecap\n\
155             2 setlinecap\n[3 1.5] 0 setdash\n/DejaVuSans 12.000 selectfont\n"
156        );
157        ps.set_linedash(0.0, None, true);
158        assert_eq!(ps.take_body(), "[] 0 setdash\n");
159    }
160
161    #[test]
162    fn hatches_are_defined_once() {
163        let mut ps = PsRenderer::new(2.0, 2.0, 72.0, PsOptions::default()).unwrap();
164        assert_eq!(ps.create_hatch("/", 1.0), "H0");
165        let defined = ps.take_body();
166        assert!(defined.contains("/H0 exch def"), "{defined}");
167        assert_eq!(ps.create_hatch("/", 1.0), "H0");
168        assert_eq!(ps.create_hatch("x", 1.0), "H1");
169        assert!(ps.take_body().contains("/H1 exch def"));
170    }
171}