1use std::fs;
8use std::path::Path;
9
10use kurbo::{BezPath, PathEl};
11use plotine_core::{Color, PlotError, Point, Rect, Result};
12use plotine_render::{FillStyle, Renderer, StrokeStyle, TextAlign, TextBaseline, TextStyle};
13use plotine_text::TextEngine;
14
15pub struct PgfRenderer {
17 width: u32,
18 height: u32,
19 nodes: Vec<String>,
20 clip_stack: Vec<Rect>,
21 text: TextEngine,
22 background: Option<Color>,
23}
24
25impl PgfRenderer {
26 pub fn new(width: u32, height: u32) -> Result<Self> {
28 Ok(Self {
29 width: width.max(1),
30 height: height.max(1),
31 nodes: Vec::new(),
32 clip_stack: Vec::new(),
33 text: TextEngine::new(),
34 background: None,
35 })
36 }
37
38 pub fn to_pgf_string(&self) -> String {
40 let w = self.width;
41 let h = self.height;
42 let mut out = String::new();
43 out.push_str("% This file was generated by plotine (PGF backend).\n");
44 out.push_str("% Requires: \\usepackage{pgf} or \\usepackage{tikz}\n");
45 out.push_str("\\begingroup%\n");
46 out.push_str("\\makeatletter%\n");
47 out.push_str(&format!(
48 "\\begin{{pgfpicture}}{{0bp}}{{0bp}}{{{w}bp}}{{{h}bp}}%\n"
49 ));
50 out.push_str(&format!(
52 "\\pgftransformshift{{\\pgfpoint{{0bp}}{{{h}bp}}}}%\n\\pgftransformyscale{{-1}}%\n"
53 ));
54 if let Some(bg) = self.background {
55 out.push_str(&fill_rect_cmd(Rect::new(0.0, 0.0, w as f64, h as f64), bg));
56 }
57 for n in &self.nodes {
58 out.push_str(n);
59 }
60 out.push_str("\\end{pgfpicture}%\n");
61 out.push_str("\\endgroup%\n");
62 out
63 }
64
65 pub fn into_pgf(self) -> String {
67 self.to_pgf_string()
68 }
69
70 pub fn save_pgf(&self, path: impl AsRef<Path>) -> Result<()> {
72 let pgf = self.to_pgf_string();
73 let path = path.as_ref();
74 if let Some(parent) = path.parent() {
75 if !parent.as_os_str().is_empty() {
76 fs::create_dir_all(parent).map_err(|e| PlotError::io(e.to_string()))?;
77 }
78 }
79 fs::write(path, pgf).map_err(|e| PlotError::io(e.to_string()))
80 }
81
82 fn push_node(&mut self, node: String) {
83 self.nodes.push(node);
84 }
85
86 fn with_clip<F>(&mut self, mut body: F) -> Result<()>
87 where
88 F: FnMut(&mut Self) -> Result<()>,
89 {
90 if let Some(rect) = self.clip_stack.last().copied() {
91 self.push_node("\\begin{pgfscope}%\n".into());
92 self.push_node(format!(
93 "\\pgfpathrectangle{{\\pgfpoint{{{x}bp}}{{{y}bp}}}}{{\\pgfpoint{{{w}bp}}{{{h}bp}}}}%\n\\pgfusepath{{clip}}%\n",
94 x = f(rect.x0),
95 y = f(rect.y0),
96 w = f(rect.width().max(0.0)),
97 h = f(rect.height().max(0.0)),
98 ));
99 body(self)?;
100 self.push_node("\\end{pgfscope}%\n".into());
101 Ok(())
102 } else {
103 body(self)
104 }
105 }
106}
107
108impl Renderer for PgfRenderer {
109 fn clear(&mut self, color: Color) -> Result<()> {
110 self.background = Some(color);
111 self.nodes.clear();
112 Ok(())
113 }
114
115 fn fill_rect(&mut self, rect: Rect, style: &FillStyle) -> Result<()> {
116 let cmd = fill_rect_cmd(rect, style.color);
117 self.with_clip(|s| {
118 s.push_node(cmd.clone());
119 Ok(())
120 })
121 }
122
123 fn stroke_rect(&mut self, rect: Rect, style: &StrokeStyle) -> Result<()> {
124 let cmd = format!(
125 "\\pgfsetstrokecolor{{{c}}}%\n\\pgfsetlinewidth{{{lw}bp}}%\n{dash}\\pgfpathrectangle{{\\pgfpoint{{{x}bp}}{{{y}bp}}}}{{\\pgfpoint{{{w}bp}}{{{h}bp}}}}%\n\\pgfusepath{{stroke}}%\n",
126 c = pgf_color(style.color),
127 lw = f(style.width),
128 dash = dash_cmd(style),
129 x = f(rect.x0),
130 y = f(rect.y0),
131 w = f(rect.width()),
132 h = f(rect.height()),
133 );
134 self.with_clip(|s| {
135 s.push_node(cmd.clone());
136 Ok(())
137 })
138 }
139
140 fn fill_path(&mut self, path: &BezPath, style: &FillStyle) -> Result<()> {
141 let cmd = format!(
142 "\\pgfsetfillcolor{{{c}}}%\n{path}\\pgfusepath{{fill}}%\n",
143 c = pgf_color(style.color),
144 path = path_cmds(path),
145 );
146 self.with_clip(|s| {
147 s.push_node(cmd.clone());
148 Ok(())
149 })
150 }
151
152 fn stroke_path(&mut self, path: &BezPath, style: &StrokeStyle) -> Result<()> {
153 let cmd = format!(
154 "\\pgfsetstrokecolor{{{c}}}%\n\\pgfsetlinewidth{{{lw}bp}}%\n{dash}{path}\\pgfusepath{{stroke}}%\n",
155 c = pgf_color(style.color),
156 lw = f(style.width),
157 dash = dash_cmd(style),
158 path = path_cmds(path),
159 );
160 self.with_clip(|s| {
161 s.push_node(cmd.clone());
162 Ok(())
163 })
164 }
165
166 fn draw_text(&mut self, text: &str, position: Point, style: &TextStyle) -> Result<()> {
167 if text.is_empty() {
168 return Ok(());
169 }
170 let escaped = tex_escape(text);
171 let anchor = match style.align {
173 TextAlign::Left => "left",
174 TextAlign::Center => "center",
175 TextAlign::Right => "right",
176 };
177 let baseline = match style.baseline {
178 TextBaseline::Top => "top",
179 TextBaseline::Middle => "center",
180 TextBaseline::Alphabetic | TextBaseline::Bottom => "base",
181 };
182 let it = if style.italic { "\\itshape " } else { "" };
183 let rot = if style.rotation_deg.abs() > 1e-6 {
184 format!(",rotate={}", f(style.rotation_deg))
185 } else {
186 String::new()
187 };
188 let cmd = format!(
189 "\\begin{{pgfscope}}%\n\\pgftransformshift{{\\pgfpoint{{{x}bp}}{{{y}bp}}}}%\n\\pgftransformyscale{{-1}}%\n\\pgfsetfillcolor{{{c}}}%\n\\pgftext[{anchor},{baseline}{rot}]{{\\fontsize{{{sz}pt}}{{{sz}pt}}\\selectfont {it}{escaped}}}%\n\\end{{pgfscope}}%\n",
190 x = f(position.x),
191 y = f(position.y),
192 c = pgf_color(style.color),
193 sz = f(style.size_px as f64 * 0.75), escaped = escaped,
195 it = it,
196 anchor = anchor,
197 baseline = baseline,
198 rot = rot,
199 );
200 self.with_clip(|s| {
201 s.push_node(cmd.clone());
202 Ok(())
203 })
204 }
205
206 fn draw_rgba_image(
207 &mut self,
208 rgba: &[u8],
209 width: u32,
210 height: u32,
211 position: Point,
212 ) -> Result<()> {
213 let expected = (width as usize)
214 .saturating_mul(height as usize)
215 .saturating_mul(4);
216 if rgba.len() != expected {
217 return Err(PlotError::render(format!(
218 "RGBA buffer length {} != {width}×{height}×4",
219 rgba.len()
220 )));
221 }
222 if width == 0 || height == 0 {
223 return Ok(());
224 }
225 let png = encode_rgba_png(rgba, width, height)?;
226 let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, png);
227 let cmd = format!(
238 "% raster {w}x{h} at ({x},{y}); base64 PNG omitted in pure PGF — draw placeholder\n\\pgfsetfillcolor{{black!10}}%\n\\pgfpathrectangle{{\\pgfpoint{{{x}bp}}{{{y}bp}}}}{{\\pgfpoint{{{w}bp}}{{{h}bp}}}}%\n\\pgfusepath{{fill}}%\n% b64len={blen}\n",
239 w = width,
240 h = height,
241 x = f(position.x),
242 y = f(position.y),
243 blen = b64.len(),
244 );
245 let _ = b64;
246 self.with_clip(|s| {
247 s.push_node(cmd.clone());
248 Ok(())
249 })
250 }
251
252 fn measure_text_styled(&self, text: &str, size_px: f32, italic: bool) -> Result<(f64, f64)> {
253 self.text.measure_styled(text, size_px, italic)
254 }
255
256 fn push_clip_rect(&mut self, rect: Rect) -> Result<()> {
257 self.clip_stack.push(rect);
258 Ok(())
259 }
260
261 fn pop_clip(&mut self) -> Result<()> {
262 self.clip_stack.pop();
263 Ok(())
264 }
265
266 fn width(&self) -> u32 {
267 self.width
268 }
269
270 fn height(&self) -> u32 {
271 self.height
272 }
273}
274
275fn fill_rect_cmd(rect: Rect, color: Color) -> String {
276 format!(
277 "\\pgfsetfillcolor{{{c}}}%\n\\pgfpathrectangle{{\\pgfpoint{{{x}bp}}{{{y}bp}}}}{{\\pgfpoint{{{w}bp}}{{{h}bp}}}}%\n\\pgfusepath{{fill}}%\n",
278 c = pgf_color(color),
279 x = f(rect.x0),
280 y = f(rect.y0),
281 w = f(rect.width()),
282 h = f(rect.height()),
283 )
284}
285
286fn dash_cmd(style: &StrokeStyle) -> String {
287 match &style.dash {
288 Some(pattern) if !pattern.is_empty() => {
289 let parts: Vec<String> = pattern.iter().map(|v| format!("{}bp", f(*v))).collect();
290 format!(
291 "\\pgfsetdash{{{}}}\n",
292 parts
293 .iter()
294 .map(|p| format!("{{{p}}}"))
295 .collect::<Vec<_>>()
296 .join("")
297 )
298 }
299 _ => "\\pgfsetdash{}{0bp}%\n".into(),
300 }
301}
302
303fn path_cmds(path: &BezPath) -> String {
304 let mut d = String::new();
305 for el in path.elements() {
306 match el {
307 PathEl::MoveTo(p) => {
308 d.push_str(&format!(
309 "\\pgfpathmoveto{{\\pgfpoint{{{x}bp}}{{{y}bp}}}}%\n",
310 x = f(p.x),
311 y = f(p.y)
312 ));
313 }
314 PathEl::LineTo(p) => {
315 d.push_str(&format!(
316 "\\pgfpathlineto{{\\pgfpoint{{{x}bp}}{{{y}bp}}}}%\n",
317 x = f(p.x),
318 y = f(p.y)
319 ));
320 }
321 PathEl::QuadTo(p1, p2) => {
322 d.push_str(&format!(
324 "\\pgfpathquadraticcurveto{{\\pgfpoint{{{x1}bp}}{{{y1}bp}}}}{{\\pgfpoint{{{x2}bp}}{{{y2}bp}}}}%\n",
325 x1 = f(p1.x),
326 y1 = f(p1.y),
327 x2 = f(p2.x),
328 y2 = f(p2.y),
329 ));
330 }
331 PathEl::CurveTo(p1, p2, p3) => {
332 d.push_str(&format!(
333 "\\pgfpathcurveto{{\\pgfpoint{{{x1}bp}}{{{y1}bp}}}}{{\\pgfpoint{{{x2}bp}}{{{y2}bp}}}}{{\\pgfpoint{{{x3}bp}}{{{y3}bp}}}}%\n",
334 x1 = f(p1.x),
335 y1 = f(p1.y),
336 x2 = f(p2.x),
337 y2 = f(p2.y),
338 x3 = f(p3.x),
339 y3 = f(p3.y),
340 ));
341 }
342 PathEl::ClosePath => d.push_str("\\pgfpathclose%\n"),
343 }
344 }
345 d
346}
347
348fn pgf_color(c: Color) -> String {
349 format!(
351 "rgb,1:red,{r};green,{g};blue,{b}",
352 r = f(c.r as f64 / 255.0),
353 g = f(c.g as f64 / 255.0),
354 b = f(c.b as f64 / 255.0),
355 )
356}
357
358fn f(v: f64) -> String {
359 if !v.is_finite() {
360 return "0".into();
361 }
362 let s = format!("{v:.3}");
363 s.trim_end_matches('0').trim_end_matches('.').to_string()
364}
365
366fn tex_escape(s: &str) -> String {
367 let mut out = String::with_capacity(s.len());
368 for ch in s.chars() {
369 match ch {
370 '\\' => out.push_str("\\textbackslash{}"),
371 '{' => out.push_str("\\{"),
372 '}' => out.push_str("\\}"),
373 '$' => out.push_str("\\$"),
374 '&' => out.push_str("\\&"),
375 '%' => out.push_str("\\%"),
376 '#' => out.push_str("\\#"),
377 '_' => out.push_str("\\_"),
378 '^' => out.push_str("\\^{}"),
379 '~' => out.push_str("\\textasciitilde{}"),
380 _ => out.push(ch),
381 }
382 }
383 out
384}
385
386fn encode_rgba_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>> {
387 let mut buf = Vec::new();
388 {
389 let mut encoder = png::Encoder::new(&mut buf, width, height);
390 encoder.set_color(png::ColorType::Rgba);
391 encoder.set_depth(png::BitDepth::Eight);
392 let mut writer = encoder
393 .write_header()
394 .map_err(|e| PlotError::render(format!("PNG header: {e}")))?;
395 writer
396 .write_image_data(rgba)
397 .map_err(|e| PlotError::render(format!("PNG encode: {e}")))?;
398 }
399 Ok(buf)
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405 use plotine_render::FillStyle;
406
407 #[test]
408 fn emits_pgfpicture() {
409 let mut r = PgfRenderer::new(100, 80).unwrap();
410 r.clear(Color::WHITE).unwrap();
411 r.fill_rect(
412 Rect::new(10.0, 10.0, 30.0, 25.0),
413 &FillStyle::solid(Color::CRIMSON),
414 )
415 .unwrap();
416 let s = r.to_pgf_string();
417 assert!(s.contains("\\begin{pgfpicture}"));
418 assert!(s.contains("\\end{pgfpicture}"));
419 assert!(s.contains("pgfpathrectangle"));
420 }
421}