1mod 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
38const LATEX_POINTS_PER_INCH: f64 = 72.27;
40const POINTS_PER_INCH: f64 = 72.0;
42
43#[derive(Clone, Debug, PartialEq)]
46pub struct PgfOptions {
47 pub simplify: SimplifySettings,
49 pub composite_images: bool,
51 pub rcfonts: bool,
54 pub font_names: Vec<String>,
57 pub preamble: String,
60 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#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct PgfDocument {
81 pub text: String,
83 pub images: Vec<ImageFile>,
85}
86
87#[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 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 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 pub fn take_ignored_fonts(&mut self) -> Vec<String> {
143 std::mem::take(&mut self.ignored_fonts)
144 }
145
146 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 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 fn inches(&self, pixels: f64) -> f64 {
201 pixels / self.dpi
202 }
203}
204
205const 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
228fn writeln_pgf(out: &mut String, line: &str) {
231 out.push_str(line);
232 out.push_str("%\n");
233}
234
235fn num(value: f64) -> String {
238 fixed(value, 6)
239}
240
241fn 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 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 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}