1mod 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#[derive(Clone, Debug, PartialEq)]
55#[expect(
56 clippy::struct_excessive_bools,
57 reason = "mirrors matplotlib's independent rcParams"
58)]
59pub struct PsOptions {
60 pub eps: bool,
62 pub paper: Paper,
64 pub orientation: PageOrientation,
66 pub metadata: Metadata,
68 pub simplify: SimplifySettings,
70 pub composite_images: bool,
72 pub fonttype: FontType,
74 pub afm: bool,
78 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 pub fn afm_directory(&self) -> Option<AfmDirectory> {
106 self.afm.then_some(AfmDirectory::PostScript)
107 }
108}
109
110#[derive(Clone, Debug, PartialEq)]
112pub struct PsDocument {
113 pub text: String,
115 pub bbox: Bbox,
118}
119
120#[derive(Clone, Debug, PartialEq)]
122pub enum PsOutput {
123 Document(PsDocument),
125 Psfrag(PsfragFigure),
128}
129
130#[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#[derive(Debug)]
145pub struct PsRenderer {
146 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 psfrags: Vec<String>,
160 tex_drawn_as_plain: bool,
162 partially_transparent: bool,
164 problems: Problems,
165}
166
167impl PsRenderer {
168 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 pub fn drew_tex_as_plain(&self) -> bool {
200 self.tex_drawn_as_plain
201 }
202
203 pub fn drew_partial_transparency(&self) -> bool {
207 self.partially_transparent
208 }
209
210 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 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 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 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
334const 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 fn dpi(&self) -> f64 {
353 self.image_dpi
354 }
355
356 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;