1use crate::scene::{LayerName, Primitive, Scene, TextAnchor, Viewport};
4
5fn esc(s: &str) -> String {
6 s.replace('&', "&")
7 .replace('"', """)
8 .replace('<', "<")
9 .replace('>', ">")
10}
11
12fn fmt(n: f64) -> String {
13 if !n.is_finite() {
14 return "0".into();
15 }
16 let t = (n * 100.0).round() / 100.0;
17 let s = format!("{t}");
18 if s == "-0" {
19 "0".into()
20 } else {
21 s
22 }
23}
24
25fn fmt_path_d(d: &str) -> String {
26 let mut out = String::with_capacity(d.len());
27 let bytes = d.as_bytes();
28 let mut i = 0;
29 while i < bytes.len() {
30 let c = bytes[i] as char;
31 let start_num = c == '-' || c == '+' || c == '.' || c.is_ascii_digit();
32 if start_num {
33 let start = i;
34 i += 1;
35 while i < bytes.len() {
36 let ch = bytes[i] as char;
37 if ch.is_ascii_digit() || ch == '.' {
38 i += 1;
39 continue;
40 }
41 if (ch == 'e' || ch == 'E') && i + 1 < bytes.len() {
42 let n = bytes[i + 1] as char;
43 if n == '+' || n == '-' || n.is_ascii_digit() {
44 i += 2;
45 while i < bytes.len() && (bytes[i] as char).is_ascii_digit() {
46 i += 1;
47 }
48 break;
49 }
50 }
51 break;
52 }
53 let token = &d[start..i];
54 if let Ok(v) = token.parse::<f64>() {
55 out.push_str(&fmt(v));
56 } else {
57 out.push_str(token);
58 }
59 } else {
60 out.push(c);
61 i += 1;
62 }
63 }
64 out
65}
66
67fn attr(name: &str, value: Option<&str>) -> String {
68 match value {
69 Some(v) if !v.is_empty() => format!(" {name}=\"{}\"", esc(v)),
70 _ => String::new(),
71 }
72}
73
74fn attr_num(name: &str, value: f64) -> String {
75 format!(" {name}=\"{}\"", fmt(value))
76}
77
78fn render_primitive(p: &Primitive) -> String {
79 match p {
80 Primitive::Path {
81 d,
82 stroke,
83 fill,
84 stroke_width,
85 opacity,
86 stroke_dasharray,
87 stroke_linecap,
88 class,
89 data_text,
90 } => format!(
91 "<path d=\"{}\"{}{}{}{}{}{}{}{}{}/>",
92 fmt_path_d(d),
93 attr("fill", Some(fill.as_deref().unwrap_or("none"))),
94 attr("stroke", stroke.as_deref()),
95 attr_num("stroke-width", *stroke_width),
96 attr(
97 "stroke-linecap",
98 Some(stroke_linecap.as_deref().unwrap_or("round"))
99 ),
100 " stroke-linejoin=\"round\"",
101 attr_num("opacity", *opacity),
102 attr("stroke-dasharray", stroke_dasharray.as_deref()),
103 attr("class", class.as_deref()),
104 attr("data-text", data_text.as_deref()),
105 ),
106 Primitive::Circle {
107 cx,
108 cy,
109 r,
110 fill,
111 stroke,
112 stroke_width,
113 opacity,
114 class,
115 } => format!(
116 "<circle cx=\"{}\" cy=\"{}\" r=\"{}\"{}{}{}{}{}/>",
117 fmt(*cx),
118 fmt(*cy),
119 fmt(*r),
120 attr("fill", Some(fill.as_deref().unwrap_or("none"))),
121 attr("stroke", stroke.as_deref()),
122 attr_num("stroke-width", *stroke_width),
123 attr_num("opacity", *opacity),
124 attr("class", class.as_deref()),
125 ),
126 Primitive::Text {
127 x,
128 y,
129 text,
130 fill,
131 font_size,
132 anchor,
133 class,
134 rotate,
135 } => {
136 let anchor_s = match anchor {
137 TextAnchor::Start => "start",
138 TextAnchor::Middle => "middle",
139 TextAnchor::End => "end",
140 };
141 let rotated = rotate.filter(|r| r.abs() > 1e-6);
142 let baseline = if rotated.is_some() {
146 "central"
147 } else {
148 "alphabetic"
149 };
150 let rot = rotated
151 .map(|r| format!(" transform=\"rotate({} {} {})\"", fmt(r), fmt(*x), fmt(*y)))
152 .unwrap_or_default();
153 format!(
154 "<text x=\"{}\" y=\"{}\" fill=\"{}\" font-size=\"{}\" \
155 font-family=\"Liberation Sans, Arial, sans-serif\" text-anchor=\"{anchor_s}\" \
156 dominant-baseline=\"{baseline}\"{}{}>{}</text>",
157 fmt(*x),
158 fmt(*y),
159 esc(fill),
160 fmt(*font_size),
161 attr("class", class.as_deref()),
162 rot,
163 esc(text),
164 )
165 }
166 }
167}
168
169fn layer_name(n: LayerName) -> &'static str {
170 match n {
171 LayerName::Shading => "shading",
172 LayerName::Halo => "halo",
173 LayerName::Bonds => "bonds",
174 LayerName::Labels => "labels",
175 LayerName::Marks => "marks",
176 LayerName::Overlay => "overlay",
177 }
178}
179
180fn render_viewport_layers(vp: &Viewport) -> String {
181 let mut layers: Vec<&crate::scene::Layer> = vp
182 .layers
183 .iter()
184 .filter(|l| !l.primitives.is_empty())
185 .collect();
186 layers.sort_by_key(|l| l.name.paint_order());
187 let mut chunks = String::new();
188 for layer in layers {
189 let name = layer_name(layer.name);
190 let body: String = layer.primitives.iter().map(render_primitive).collect();
191 chunks.push_str(&format!("<g class=\"xpict-layer xpict-{name}\">{body}</g>"));
192 }
193 chunks
194}
195
196fn mol_transform(vp: &Viewport) -> String {
197 let t = format!("translate({},{})", fmt(vp.x), fmt(vp.y));
198 if vp.ox.abs() < 1e-12 && vp.oy.abs() < 1e-12 {
199 t
200 } else {
201 format!("{t} translate({},{})", fmt(vp.ox), fmt(vp.oy))
202 }
203}
204
205fn render_viewport(vp: &Viewport) -> String {
207 let body = render_viewport_layers(vp);
208 if body.is_empty() {
209 return String::new();
210 }
211 let mut g = String::from("<g class=\"xpict-mol\"");
212 if let Some(id) = vp.id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
213 g.push_str(&format!(" data-id=\"{}\"", esc(id)));
214 }
215 g.push_str(&format!(" transform=\"{}\">{body}</g>", mol_transform(vp)));
216 g
217}
218
219pub fn scene_to_svg(scene: &Scene) -> String {
224 let w = fmt(scene.width);
225 let h = fmt(scene.height);
226 let mut parts = String::new();
227 if !scene.halo.is_empty() {
228 let body: String = scene.halo.iter().map(render_primitive).collect();
229 parts.push_str(&format!("<g class=\"xpict-halo\" id=\"halo\">{body}</g>"));
230 }
231 for vp in &scene.viewports {
232 parts.push_str(&render_viewport(vp));
233 }
234 if !scene.overlays.is_empty() {
235 let body: String = scene.overlays.iter().map(render_primitive).collect();
236 parts.push_str(&format!(
237 "<g class=\"xpict-overlays\" id=\"overlays\">{body}</g>"
238 ));
239 }
240 let vx = fmt(scene.x);
241 let vy = fmt(scene.y);
242 format!(
243 "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\" \
244 viewBox=\"{vx} {vy} {w} {h}\" class=\"xpict\" \
245 style=\"background:transparent;max-width:100%;max-height:100%\">{parts}</svg>"
246 )
247}
248
249pub fn scene_to_svg_json(scene_json: &str) -> Result<String, String> {
251 let scene: Scene = serde_json::from_str(scene_json).map_err(|e| format!("Scene JSON: {e}"))?;
252 Ok(scene_to_svg(&scene))
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258 use crate::scene::{Layer, LayerName, Primitive};
259
260 fn circle() -> Primitive {
261 Primitive::Circle {
262 cx: 1.0,
263 cy: 2.0,
264 r: 3.0,
265 fill: Some("#000".into()),
266 stroke: None,
267 stroke_width: 1.5,
268 opacity: 1.0,
269 class: None,
270 }
271 }
272
273 fn scene_with_id(id: Option<&str>, x: f64, y: f64) -> Scene {
274 Scene {
275 width: 10.0,
276 height: 20.0,
277 x: 0.0,
278 y: 0.0,
279 viewports: vec![Viewport {
280 id: id.map(str::to_string),
281 x,
282 y,
283 ox: 0.0,
284 oy: 0.0,
285 width: 10.0,
286 height: 20.0,
287 layers: vec![Layer {
288 name: LayerName::Bonds,
289 primitives: vec![circle()],
290 }],
291 }],
292 overlays: vec![],
293 halo: vec![],
294 }
295 }
296
297 #[test]
298 fn mol_group_carries_escaped_data_id_and_transform() {
299 let svg = scene_to_svg(&scene_with_id(Some("m\"3&"), 4.5, 0.0));
300 assert!(
301 svg.contains(
302 r#"<g class="xpict-mol" data-id="m"3&" transform="translate(4.5,0)""#
303 ),
304 "{svg}"
305 );
306 assert!(svg.contains(r#"class="xpict-layer xpict-bonds""#), "{svg}");
307 assert!(!svg.contains("<?xml"), "{svg}");
308 assert!(svg.starts_with("<svg"), "{svg}");
309 }
310
311 #[test]
312 fn missing_id_still_emits_mol_group() {
313 let svg = scene_to_svg(&scene_with_id(None, 0.0, 0.0));
314 assert!(
315 svg.contains(r#"<g class="xpict-mol" transform="translate(0,0)""#),
316 "{svg}"
317 );
318 assert!(!svg.contains("data-id="), "{svg}");
319 }
320
321 #[test]
322 fn json_roundtrip_keeps_id() {
323 let scene = scene_with_id(Some("A"), 1.0, 2.0);
324 let json = serde_json::to_string(&scene).unwrap();
325 let svg = scene_to_svg_json(&json).unwrap();
326 assert!(svg.contains(r#"data-id="A""#), "{svg}");
327 assert!(svg.contains(r#"transform="translate(1,2)""#), "{svg}");
328 }
329
330 #[test]
331 fn shading_nests_inside_one_mol_group() {
332 let mut scene = scene_with_id(Some("m3"), 10.0, 20.0);
333 scene.viewports[0].ox = -6.0;
334 scene.viewports[0].oy = -8.0;
335 scene.viewports[0].layers.insert(
336 0,
337 Layer {
338 name: LayerName::Shading,
339 primitives: vec![circle()],
340 },
341 );
342 let svg = scene_to_svg(&scene);
343 assert_eq!(
344 svg.matches(r#"class="xpict-mol""#).count(),
345 1,
346 "one mol group, not a sibling shade copy: {svg}"
347 );
348 let mol = svg.find(r#"class="xpict-mol""#).expect("mol");
349 let shade = svg
350 .find(r#"class="xpict-layer xpict-shading""#)
351 .expect("shading");
352 let bonds = svg
353 .find(r#"class="xpict-layer xpict-bonds""#)
354 .expect("bonds");
355 assert!(
356 mol < shade && shade < bonds,
357 "layers nest inside mol: {svg}"
358 );
359 assert!(
360 svg.contains(r#"transform="translate(10,20) translate(-6,-8)""#),
361 "leftover origin is a nested translate, not baked coords: {svg}"
362 );
363 }
364
365 #[test]
366 fn rotated_text_spins_about_glyph_center() {
367 let scene = Scene {
368 width: 40.0,
369 height: 20.0,
370 x: 0.0,
371 y: 0.0,
372 viewports: vec![],
373 overlays: vec![Primitive::Text {
374 x: 12.0,
375 y: 8.0,
376 text: "ADH".into(),
377 fill: "#222".into(),
378 font_size: 11.0,
379 anchor: TextAnchor::Middle,
380 class: Some("edge edge-0 label".into()),
381 rotate: Some(35.0),
382 }],
383 halo: vec![],
384 };
385 let svg = scene_to_svg(&scene);
386 assert!(svg.contains(r#"dominant-baseline="central""#), "{svg}");
387 assert!(
388 svg.contains(r#"transform="rotate(35 12 8)""#),
389 "rotate origin must be the text center: {svg}"
390 );
391 let upright = Scene {
392 overlays: vec![Primitive::Text {
393 x: 12.0,
394 y: 8.0,
395 text: "ADH".into(),
396 fill: "#222".into(),
397 font_size: 11.0,
398 anchor: TextAnchor::Middle,
399 class: None,
400 rotate: None,
401 }],
402 ..scene
403 };
404 let u = scene_to_svg(&upright);
405 assert!(u.contains(r#"dominant-baseline="alphabetic""#), "{u}");
406 assert!(!u.contains("rotate("), "{u}");
407 }
408
409 #[test]
410 fn viewbox_uses_scene_origin() {
411 let mut scene = scene_with_id(Some("m"), 0.0, 0.0);
412 scene.x = 12.4;
413 scene.y = -3.1;
414 let svg = scene_to_svg(&scene);
415 assert!(
416 svg.contains(r#"viewBox="12.4 -3.1 10 20""#),
417 "crop is the viewBox, not a leftover translate: {svg}"
418 );
419 assert!(!svg.contains(r#"viewBox="0 0"#), "{svg}");
420 }
421}