1use std::fs;
4use std::path::Path;
5
6use kurbo::{BezPath, PathEl};
7use plotine_core::{Color, PlotError, Point, Rect, Result};
8use plotine_render::{FillStyle, Renderer, StrokeStyle, TextAlign, TextBaseline, TextStyle};
9use plotine_text::TextEngine;
10
11pub struct SvgRenderer {
13 width: u32,
14 height: u32,
15 nodes: Vec<String>,
16 clip_stack: Vec<usize>,
17 clip_defs: Vec<String>,
18 text: TextEngine,
19 background: Option<Color>,
20}
21
22impl SvgRenderer {
23 pub fn new(width: u32, height: u32) -> Result<Self> {
24 Ok(Self {
25 width: width.max(1),
26 height: height.max(1),
27 nodes: Vec::new(),
28 clip_stack: Vec::new(),
29 clip_defs: Vec::new(),
30 text: TextEngine::new(),
31 background: None,
32 })
33 }
34
35 pub fn to_svg_string(&self) -> String {
37 let mut out = String::new();
38 out.push_str(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
39 out.push('\n');
40 out.push_str(&format!(
41 r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">"#,
42 w = self.width,
43 h = self.height
44 ));
45 out.push('\n');
46 if !self.clip_defs.is_empty() {
47 out.push_str("<defs>\n");
48 for d in &self.clip_defs {
49 out.push_str(d);
50 out.push('\n');
51 }
52 out.push_str("</defs>\n");
53 }
54 if let Some(bg) = self.background {
55 out.push_str(&format!(
56 r#"<rect x="0" y="0" width="{}" height="{}" fill="{}" />"#,
57 self.width,
58 self.height,
59 css_color(bg)
60 ));
61 out.push('\n');
62 }
63 for n in &self.nodes {
64 out.push_str(n);
65 out.push('\n');
66 }
67 out.push_str("</svg>\n");
68 out
69 }
70
71 pub fn into_svg(self) -> String {
73 self.to_svg_string()
74 }
75
76 pub fn save_svg(&self, path: impl AsRef<Path>) -> Result<()> {
77 let svg = self.to_svg_string();
78 let path = path.as_ref();
79 if let Some(parent) = path.parent() {
80 if !parent.as_os_str().is_empty() {
81 fs::create_dir_all(parent).map_err(|e| PlotError::io(e.to_string()))?;
82 }
83 }
84 fs::write(path, svg).map_err(|e| PlotError::io(e.to_string()))
85 }
86
87 fn clip_attr(&self) -> String {
88 match self.clip_stack.last() {
89 Some(id) => format!(r#" clip-path="url(#c{id})""#),
90 None => String::new(),
91 }
92 }
93
94 fn push_node(&mut self, node: String) {
95 self.nodes.push(node);
96 }
97}
98
99impl Renderer for SvgRenderer {
100 fn clear(&mut self, color: Color) -> Result<()> {
101 self.background = Some(color);
102 self.nodes.clear();
103 Ok(())
104 }
105
106 fn fill_rect(&mut self, rect: Rect, style: &FillStyle) -> Result<()> {
107 self.push_node(format!(
108 r#"<rect x="{}" y="{}" width="{}" height="{}" fill="{}"{} />"#,
109 f(rect.x0),
110 f(rect.y0),
111 f(rect.width()),
112 f(rect.height()),
113 css_color(style.color),
114 self.clip_attr()
115 ));
116 Ok(())
117 }
118
119 fn stroke_rect(&mut self, rect: Rect, style: &StrokeStyle) -> Result<()> {
120 self.push_node(format!(
121 r#"<rect x="{}" y="{}" width="{}" height="{}" fill="none" stroke="{}" stroke-width="{}"{}{} />"#,
122 f(rect.x0),
123 f(rect.y0),
124 f(rect.width()),
125 f(rect.height()),
126 css_color(style.color),
127 f(style.width),
128 dash_attr(style),
129 self.clip_attr()
130 ));
131 Ok(())
132 }
133
134 fn fill_path(&mut self, path: &BezPath, style: &FillStyle) -> Result<()> {
135 self.push_node(format!(
136 r#"<path d="{}" fill="{}"{} />"#,
137 path_d(path),
138 css_color(style.color),
139 self.clip_attr()
140 ));
141 Ok(())
142 }
143
144 fn stroke_path(&mut self, path: &BezPath, style: &StrokeStyle) -> Result<()> {
145 self.push_node(format!(
146 r#"<path d="{}" fill="none" stroke="{}" stroke-width="{}" stroke-linecap="{}" stroke-linejoin="{}"{}{} />"#,
147 path_d(path),
148 css_color(style.color),
149 f(style.width),
150 match style.cap {
151 plotine_render::LineCap::Butt => "butt",
152 plotine_render::LineCap::Round => "round",
153 plotine_render::LineCap::Square => "square",
154 },
155 match style.join {
156 plotine_render::LineJoin::Miter => "miter",
157 plotine_render::LineJoin::Round => "round",
158 plotine_render::LineJoin::Bevel => "bevel",
159 },
160 dash_attr(style),
161 self.clip_attr()
162 ));
163 Ok(())
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 anchor = match style.align {
171 TextAlign::Left => "start",
172 TextAlign::Center => "middle",
173 TextAlign::Right => "end",
174 };
175 let baseline = match style.baseline {
177 TextBaseline::Top => "text-before-edge",
178 TextBaseline::Middle => "middle",
179 TextBaseline::Alphabetic => "alphabetic",
180 TextBaseline::Bottom => "text-after-edge",
181 };
182 let transform = if style.rotation_deg.abs() > 1e-6 {
183 format!(
184 r#" transform="rotate({} {} {})""#,
185 f(style.rotation_deg),
186 f(position.x),
187 f(position.y)
188 )
189 } else {
190 String::new()
191 };
192 let escaped = xml_escape(text);
193 let font_style = if style.italic {
194 r#" font-style="italic""#
195 } else {
196 ""
197 };
198 self.push_node(format!(
199 r#"<text x="{}" y="{}" fill="{}" font-family="{}" font-size="{}" text-anchor="{}" dominant-baseline="{}"{}{}{}>{}</text>"#,
200 f(position.x),
201 f(position.y),
202 css_color(style.color),
203 plotine_text::svg_font_family_list(),
204 f(style.size_px as f64),
205 anchor,
206 baseline,
207 font_style,
208 transform,
209 self.clip_attr(),
210 escaped
211 ));
212 Ok(())
213 }
214
215 fn draw_rgba_image(
216 &mut self,
217 rgba: &[u8],
218 width: u32,
219 height: u32,
220 position: Point,
221 ) -> Result<()> {
222 let expected = (width as usize)
223 .saturating_mul(height as usize)
224 .saturating_mul(4);
225 if rgba.len() != expected {
226 return Err(PlotError::render(format!(
227 "RGBA buffer length {} != {width}×{height}×4",
228 rgba.len()
229 )));
230 }
231 if width == 0 || height == 0 {
232 return Ok(());
233 }
234 let png = encode_rgba_png(rgba, width, height)?;
235 let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, png);
236 self.push_node(format!(
237 r#"<image x="{}" y="{}" width="{}" height="{}" preserveAspectRatio="none" href="data:image/png;base64,{}"{} />"#,
238 f(position.x),
239 f(position.y),
240 f(width as f64),
241 f(height as f64),
242 b64,
243 self.clip_attr()
244 ));
245 Ok(())
246 }
247
248 fn measure_text_styled(&self, text: &str, size_px: f32, italic: bool) -> Result<(f64, f64)> {
249 self.text.measure_styled(text, size_px, italic)
250 }
251
252 fn push_clip_rect(&mut self, rect: Rect) -> Result<()> {
253 let id = self.clip_defs.len();
254 self.clip_defs.push(format!(
255 r#"<clipPath id="c{id}"><rect x="{}" y="{}" width="{}" height="{}" /></clipPath>"#,
256 f(rect.x0),
257 f(rect.y0),
258 f(rect.width().max(0.0)),
259 f(rect.height().max(0.0))
260 ));
261 self.clip_stack.push(id);
262 Ok(())
263 }
264
265 fn pop_clip(&mut self) -> Result<()> {
266 self.clip_stack.pop();
267 Ok(())
268 }
269
270 fn width(&self) -> u32 {
271 self.width
272 }
273
274 fn height(&self) -> u32 {
275 self.height
276 }
277}
278
279fn dash_attr(style: &StrokeStyle) -> String {
280 match &style.dash {
281 Some(pattern) if !pattern.is_empty() => {
282 let parts: Vec<String> = pattern.iter().map(|v| f(*v)).collect();
283 format!(r#" stroke-dasharray="{}""#, parts.join(","))
284 }
285 _ => String::new(),
286 }
287}
288
289fn f(v: f64) -> String {
290 if !v.is_finite() {
292 return "0".into();
293 }
294 let s = format!("{v:.3}");
295 s.trim_end_matches('0').trim_end_matches('.').to_string()
296}
297
298fn css_color(c: Color) -> String {
299 if c.a == 255 {
300 format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
301 } else {
302 format!("rgba({},{},{},{:.3})", c.r, c.g, c.b, c.a as f64 / 255.0)
303 }
304}
305
306fn path_d(path: &BezPath) -> String {
307 let mut d = String::new();
308 for el in path.elements() {
309 match el {
310 PathEl::MoveTo(p) => d.push_str(&format!("M{} {} ", f(p.x), f(p.y))),
311 PathEl::LineTo(p) => d.push_str(&format!("L{} {} ", f(p.x), f(p.y))),
312 PathEl::QuadTo(p1, p2) => d.push_str(&format!(
313 "Q{} {} {} {} ",
314 f(p1.x),
315 f(p1.y),
316 f(p2.x),
317 f(p2.y)
318 )),
319 PathEl::CurveTo(p1, p2, p3) => d.push_str(&format!(
320 "C{} {} {} {} {} {} ",
321 f(p1.x),
322 f(p1.y),
323 f(p2.x),
324 f(p2.y),
325 f(p3.x),
326 f(p3.y)
327 )),
328 PathEl::ClosePath => d.push_str("Z "),
329 }
330 }
331 d.trim_end().to_string()
332}
333
334fn encode_rgba_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>> {
335 let mut buf = Vec::new();
336 {
337 let mut encoder = png::Encoder::new(&mut buf, width, height);
338 encoder.set_color(png::ColorType::Rgba);
339 encoder.set_depth(png::BitDepth::Eight);
340 let mut writer = encoder
341 .write_header()
342 .map_err(|e| PlotError::render(format!("PNG header: {e}")))?;
343 writer
344 .write_image_data(rgba)
345 .map_err(|e| PlotError::render(format!("PNG encode: {e}")))?;
346 }
347 Ok(buf)
348}
349
350fn xml_escape(s: &str) -> String {
351 s.replace('&', "&")
352 .replace('<', "<")
353 .replace('>', ">")
354 .replace('"', """)
355}