Skip to main content

latexml_post/
svg.rs

1//! SVG rendering processor.
2//!
3//! Port of `LaTeXML::Post::SVG` (522 lines of Perl).
4//! Converts `ltx:picture` elements to SVG by traversing LaTeXML picture
5//! primitives (g, path, line, rect, circle, ellipse, polygon, bezier,
6//! arc, wedge, text, dots) and generating corresponding SVG elements.
7//!
8//! The coordinate system is mirrored: LaTeXML uses a bottom-left origin
9//! with y increasing upward; SVG uses top-left with y increasing downward.
10//! The top-level picture gets `transform="translate(0,h) scale(1,-1)"`.
11
12use std::f64::consts::PI;
13
14use libxml::tree::{Node, NodeType};
15use rustc_hash::FxHashMap as HashMap;
16
17use crate::{
18  document::{NodeData, PostDocument, element_children_iter},
19  processor::{ProcessResult, Processor},
20};
21
22const SVG_URI: &str = "http://www.w3.org/2000/svg";
23const DPI: f64 = 96.0;
24
25/// SVG post-processor.
26///
27/// Port of `LaTeXML::Post::SVG`.
28pub struct SVG {
29  name: String,
30}
31
32impl Default for SVG {
33  fn default() -> Self { Self::new() }
34}
35
36impl SVG {
37  pub fn new() -> Self { SVG { name: "SVG".to_string() } }
38
39  /// Convert a single ltx:picture node to SVG.
40  ///
41  /// Port of `SVG::ProcessSVG`.
42  fn process_svg(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
43    let h = node
44      .get_attribute("height")
45      .map(|s| to_px(&s))
46      .unwrap_or(0.0);
47
48    // Build a group with the y-flip transform
49    let children: Vec<NodeData> = drawn_children(doc, node)
50      .filter_map(|child| self.convert_node(doc, &child))
51      .collect();
52
53    let g_transform = format!("translate(0,{:.2}) scale(1,-1)", h);
54    let g = NodeData::Element {
55      tag: "svg:g".to_string(),
56      attributes: Some(HashMap::from_iter([("transform".to_string(), g_transform)])),
57      children,
58    };
59
60    // Build the outer svg:svg element
61    let width = node.get_attribute("width").map(|s| to_px(&s));
62    let height = node.get_attribute("height").map(|s| to_px(&s));
63    let clip = node.with_attribute(c"clip", |v| v == "true") == Some(true);
64
65    // `SVG.pm::ProcessSVG` L96-97: the picture's own attributes that are
66    // valid on `svg:svg` move onto it (`copy_valid_attributes`, model-checked
67    // in Perl — LaTeXML loads the full svg-structure schema, so `fill`/
68    // `stroke` qualify; the allowlist here is `copy_valid_attrs`): the
69    // `fill="none" stroke="none"` of the picture state, `class`, `style`.
70    // The picture's `xml:id` is NOT carried over — Perl drops it with the
71    // replaced node, and so does this.
72    let mut svg_attrs = self.copy_valid_attrs(node);
73    svg_attrs.remove("width");
74    svg_attrs.remove("height");
75    svg_attrs.insert("version".to_string(), "1.1".to_string());
76    if let Some(w) = width {
77      svg_attrs.insert("width".to_string(), format!("{:.2}", w));
78    }
79    if let Some(h) = height {
80      svg_attrs.insert("height".to_string(), format!("{:.2}", h));
81    }
82    if !clip {
83      svg_attrs.insert("overflow".to_string(), "visible".to_string());
84    }
85
86    Some(NodeData::Element {
87      tag:        "svg:svg".to_string(),
88      attributes: Some(svg_attrs),
89      children:   vec![g],
90    })
91  }
92
93  /// Dispatch conversion of a single element.
94  ///
95  /// Port of `convertNode` + converter dispatch table.
96  fn convert_node(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
97    let tag = doc.get_qname(node)?;
98    match tag.as_str() {
99      "ltx:picture" => self.convert_picture(doc, node),
100      "ltx:g" => self.convert_g(doc, node),
101      "ltx:path" => self.convert_path(doc, node),
102      "ltx:line" => self.convert_line(doc, node),
103      "ltx:polygon" => self.convert_polygon(doc, node),
104      "ltx:rect" => self.convert_rect(doc, node),
105      "ltx:circle" => self.convert_circle(doc, node),
106      "ltx:ellipse" => self.convert_ellipse(doc, node),
107      "ltx:bezier" => self.convert_bezier(doc, node),
108      "ltx:arc" => self.convert_arc(doc, node),
109      "ltx:wedge" => self.convert_wedge(doc, node),
110      "ltx:dots" => self.convert_dots(doc, node),
111      "ltx:text" => self.convert_text(doc, node),
112      _ => {
113        // Foreign element: wrap in svg:foreignObject
114        self.convert_foreign(doc, node)
115      },
116    }
117  }
118
119  /// A picture nested in a picture (`\put(x,y){\begin{picture}…}`). TeX sets the inner box with its
120  /// lower-left corner at the `\put` point, so its content is already in the enclosing picture's y-up
121  /// space: a picture of LaTeXML primitives is a plain group. A picture that is rendered SVG already
122  /// (a tikzpicture's `svg:svg`, y-down) is flipped back once and kept as SVG. Perl's `convertPicture`
123  /// (SVG.pm:191-197) flips every nested picture, mirroring it about its mid-height, and wraps a
124  /// rendered `svg:svg` in a flipped `foreignObject` (`convertNode`'s else branch), mirroring it again:
125  /// uantwerpenexam's title-page tikz overlay came out upside-down (OXIDIZED_DESIGN_DIVERGENCES #414).
126  fn convert_picture(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
127    let children: Vec<Node> = drawn_children(doc, node).collect();
128    let rendered = !children.is_empty()
129      && children.iter().all(|child| {
130        child
131          .get_namespace()
132          .is_some_and(|ns| ns.get_href() == SVG_URI)
133      });
134    if !rendered {
135      return Some(NodeData::Element {
136        tag:        "svg:g".to_string(),
137        attributes: None,
138        children:   self.convert_children(doc, node),
139      });
140    }
141    let h = node
142      .get_attribute("height")
143      .map(|s| to_px(&s))
144      .unwrap_or(0.0);
145    Some(NodeData::Element {
146      tag:        "svg:g".to_string(),
147      attributes: Some(HashMap::from_iter([(
148        "transform".to_string(),
149        format!("translate(0,{:.2}) scale(1,-1)", h),
150      )])),
151      children:   children.into_iter().map(NodeData::XmlNode).collect(),
152    })
153  }
154
155  fn convert_g(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
156    let mut attrs = self.copy_valid_attrs(node);
157    // Check for framed+fillframe
158    if node.with_attribute(c"framed", |v| v == "true") == Some(true)
159      && node.with_attribute(c"fillframe", |v| v == "true") == Some(true)
160    {
161      let fill = node
162        .get_attribute("fill")
163        .unwrap_or_else(|| "white".to_string());
164      attrs.insert(
165        "filter".to_string(),
166        format!("url(#bg{})", fill.replace('#', "")),
167      );
168    }
169    let children = self.convert_children(doc, node);
170    Some(NodeData::Element {
171      tag: "svg:g".to_string(),
172      attributes: if attrs.is_empty() { None } else { Some(attrs) },
173      children,
174    })
175  }
176
177  fn convert_path(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
178    let attrs = self.copy_valid_attrs(node);
179    let children = self.convert_children(doc, node);
180    Some(NodeData::Element {
181      tag: "svg:path".to_string(),
182      attributes: if attrs.is_empty() { None } else { Some(attrs) },
183      children,
184    })
185  }
186
187  fn convert_line(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
188    let mut attrs = self.copy_valid_attrs(node);
189    if let Some(points) = node.get_attribute("points") {
190      attrs.insert("d".to_string(), format!("M {}", points));
191    }
192    let children = self.convert_children(doc, node);
193    Some(NodeData::Element {
194      tag: "svg:path".to_string(),
195      attributes: Some(attrs),
196      children,
197    })
198  }
199
200  fn convert_polygon(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
201    let mut attrs = self.copy_valid_attrs(node);
202    if let Some(points) = node.get_attribute("points") {
203      attrs.insert("d".to_string(), format!("M {} z", points));
204    }
205    let children = self.convert_children(doc, node);
206    Some(NodeData::Element {
207      tag: "svg:path".to_string(),
208      attributes: Some(attrs),
209      children,
210    })
211  }
212
213  fn convert_rect(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
214    let attrs = self.copy_valid_attrs(node);
215    if let Some(part) = node.get_attribute("part") {
216      // Partial rect (rounded corner subset) → path
217      let x = parse_dim(&node.get_attribute("x").unwrap_or_default());
218      let y = parse_dim(&node.get_attribute("y").unwrap_or_default());
219      let w = parse_dim(&node.get_attribute("width").unwrap_or_default());
220      let h = parse_dim(&node.get_attribute("height").unwrap_or_default());
221      let rx = parse_dim(&node.get_attribute("rx").unwrap_or_default());
222      let d = oval_path(&part, x, y, w, h, rx);
223      let mut path_attrs = attrs;
224      path_attrs.insert("d".to_string(), d);
225      Some(NodeData::Element {
226        tag:        "svg:path".to_string(),
227        attributes: Some(path_attrs),
228        children:   self.convert_children(doc, node),
229      })
230    } else {
231      Some(NodeData::Element {
232        tag:        "svg:rect".to_string(),
233        attributes: if attrs.is_empty() { None } else { Some(attrs) },
234        children:   self.convert_children(doc, node),
235      })
236    }
237  }
238
239  fn convert_circle(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
240    let mut attrs = self.copy_valid_attrs(node);
241    if let Some(x) = node.get_attribute("x") {
242      attrs.insert("cx".to_string(), x);
243    }
244    if let Some(y) = node.get_attribute("y") {
245      attrs.insert("cy".to_string(), y);
246    }
247    Some(NodeData::Element {
248      tag:        "svg:circle".to_string(),
249      attributes: Some(attrs),
250      children:   self.convert_children(doc, node),
251    })
252  }
253
254  fn convert_ellipse(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
255    let mut attrs = self.copy_valid_attrs(node);
256    if let Some(x) = node.get_attribute("x") {
257      attrs.insert("cx".to_string(), x);
258    }
259    if let Some(y) = node.get_attribute("y") {
260      attrs.insert("cy".to_string(), y);
261    }
262    Some(NodeData::Element {
263      tag:        "svg:ellipse".to_string(),
264      attributes: Some(attrs),
265      children:   self.convert_children(doc, node),
266    })
267  }
268
269  fn convert_bezier(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
270    let mut attrs = self.copy_valid_attrs(node);
271    if let Some(points) = node.get_attribute("points") {
272      let coords: Vec<f64> = explode_coord(&points);
273      let n = coords.len() / 2;
274      if n >= 2 {
275        let x0 = coords[0];
276        let y0 = coords[1];
277        let cmd = match n {
278          4 => "C",
279          3 => "Q",
280          _ => "T",
281        };
282        let rest: String = coords[2..]
283          .chunks(2)
284          .map(|p| format!("{:.2},{:.2}", p[0], p.get(1).unwrap_or(&0.0)))
285          .collect::<Vec<_>>()
286          .join(" ");
287        attrs.insert(
288          "d".to_string(),
289          format!("M {:.2},{:.2} {} {}", x0, y0, cmd, rest),
290        );
291      }
292    }
293    if node.has_attribute("displayedpoints") {
294      attrs.insert("stroke-dasharray".to_string(), "2".to_string());
295    }
296    Some(NodeData::Element {
297      tag:        "svg:path".to_string(),
298      attributes: Some(attrs),
299      children:   self.convert_children(doc, node),
300    })
301  }
302
303  fn convert_arc(&self, _doc: &PostDocument, node: &Node) -> Option<NodeData> {
304    let x = parse_dim(&node.get_attribute("x").unwrap_or_default());
305    let y = parse_dim(&node.get_attribute("y").unwrap_or_default());
306    let r = parse_dim(&node.get_attribute("r").unwrap_or_default());
307    let a1 = parse_dim(&node.get_attribute("angle1").unwrap_or_default());
308    let a2 = parse_dim(&node.get_attribute("angle2").unwrap_or_default());
309
310    let mut bb = a2 - a1;
311    if bb < 0.0 {
312      bb += 360.0;
313    }
314    let large_arc = if bb > 180.0 { 1 } else { 0 };
315
316    let a1r = a1 * PI / 180.0;
317    let a2r = a2 * PI / 180.0;
318    let x1 = x + r * a1r.cos();
319    let y1 = y + r * a1r.sin();
320    let x2 = x + r * a2r.cos();
321    let y2 = y + r * a2r.sin();
322
323    let d = format!(
324      "M {:.2} {:.2} A {:.2} {:.2} 0 {} 1 {:.2} {:.2}",
325      x1, y1, r, r, large_arc, x2, y2
326    );
327
328    // The arc's own presentation (`stroke`, `stroke-width`, a dash, a
329    // `transform`) carries over, as `SVG.pm::convertArc` copies it
330    // (`copy_valid_attributes($newArc, $node)`, L385-387): without it the arc
331    // inherits the picture's `stroke="none"` and is invisible (`\psarc`,
332    // axodraw's `\CArc`). Its geometry (`x`, `y`, `r`) is not valid on a path.
333    let mut attrs = self.copy_valid_attrs(node);
334    for geometry in ["x", "y", "r"] {
335      attrs.remove(geometry);
336    }
337    attrs.insert("d".to_string(), d);
338    Some(NodeData::Element {
339      tag:        "svg:path".to_string(),
340      attributes: Some(attrs),
341      children:   vec![],
342    })
343  }
344
345  fn convert_wedge(&self, _doc: &PostDocument, node: &Node) -> Option<NodeData> {
346    let x = parse_dim(&node.get_attribute("x").unwrap_or_default());
347    let y = parse_dim(&node.get_attribute("y").unwrap_or_default());
348    let r = parse_dim(&node.get_attribute("r").unwrap_or_default());
349    let a1 = parse_dim(&node.get_attribute("angle1").unwrap_or_default());
350    let a2 = parse_dim(&node.get_attribute("angle2").unwrap_or_default());
351
352    let mut bb = a2 - a1;
353    if bb < 0.0 {
354      bb += 360.0;
355    }
356    let large_arc = if bb > 180.0 { 1 } else { 0 };
357
358    let a1r = a1 * PI / 180.0;
359    let a2r = a2 * PI / 180.0;
360    let x1 = x + r * a1r.cos();
361    let y1 = y + r * a1r.sin();
362    let x2 = x + r * a2r.cos();
363    let y2 = y + r * a2r.sin();
364
365    let d = format!(
366      "M {:.2} {:.2} L {:.2} {:.2} A {:.2} {:.2} 0 {} 1 {:.2} {:.2} z",
367      x, y, x1, y1, r, r, large_arc, x2, y2
368    );
369
370    let attrs = self.copy_valid_attrs(node);
371    let mut all_attrs = attrs;
372    all_attrs.insert("d".to_string(), d);
373
374    Some(NodeData::Element {
375      tag:        "svg:path".to_string(),
376      attributes: Some(all_attrs),
377      children:   vec![],
378    })
379  }
380
381  fn convert_dots(&self, _doc: &PostDocument, node: &Node) -> Option<NodeData> {
382    let points = node.get_attribute("points").unwrap_or_default();
383    let coords = explode_coord(&points);
384    let dotsize = node
385      .get_attribute("dotsize")
386      .unwrap_or_else(|| "2".to_string());
387
388    let mut circles = Vec::new();
389    for chunk in coords.chunks(2) {
390      if chunk.len() == 2 {
391        circles.push(NodeData::Element {
392          tag:        "svg:circle".to_string(),
393          attributes: Some(HashMap::from_iter([
394            ("cx".to_string(), format!("{:.2}", chunk[0])),
395            ("cy".to_string(), format!("{:.2}", chunk[1])),
396            ("r".to_string(), dotsize.clone()),
397          ])),
398          children:   vec![],
399        });
400      }
401    }
402
403    Some(NodeData::Element {
404      tag:        "svg:g".to_string(),
405      attributes: None,
406      children:   circles,
407    })
408  }
409
410  fn convert_text(&self, doc: &PostDocument, node: &Node) -> Option<NodeData> {
411    let x = node.get_attribute("x").unwrap_or_else(|| "0".to_string());
412    let y = node.get_attribute("y").unwrap_or_else(|| "0".to_string());
413    // Mixed content, as `SVG.pm::convertText` (L256-261): a text child is
414    // appended as text, an element child (a nested `<text>`, a `<Math>` or
415    // `<graphics>` label) recurses through `convert_node`. `get_content`
416    // would flatten the subtree to its characters and drop the elements.
417    let children: Vec<NodeData> =
418      std::iter::successors(node.get_first_child(), |c| c.get_next_sibling())
419        .filter_map(|child| match child.get_type() {
420          Some(NodeType::TextNode) => Some(NodeData::Text(child.get_content())),
421          Some(NodeType::ElementNode) => self.convert_node(doc, &child),
422          _ => None,
423        })
424        .collect();
425
426    let mut attrs = HashMap::default();
427    attrs.insert("x".to_string(), x);
428    attrs.insert("y".to_string(), y);
429    // Text needs to be un-flipped
430    attrs.insert("transform".to_string(), "scale(1,-1)".to_string());
431
432    // Font attributes
433    if let Some(fontsize) = node.get_attribute("fontsize") {
434      attrs.insert("font-size".to_string(), fontsize);
435    }
436    if let Some(font) = node.get_attribute("font") {
437      if font.contains("italic") {
438        attrs.insert("font-style".to_string(), "italic".to_string());
439      } else if font.contains("slanted") {
440        attrs.insert("font-style".to_string(), "oblique".to_string());
441      } else if font.contains("bold") {
442        attrs.insert("font-weight".to_string(), "bold".to_string());
443      } else if font.contains("smallcaps") {
444        attrs.insert("font-variant".to_string(), "small-caps".to_string());
445      }
446    }
447    // Black unless the text says otherwise: Perl's font stack starts `{ fill => 'black' }` (SVG.pm:82, applied
448    // by `convertText` L251-254 to an attribute the text does not set). The picture's own `fill="none"` (its
449    // shapes are unfilled, latex_constructs.pool.ltxml:4960) is on the `svg:svg` and is inherited: without
450    // this every picture label (`\put(…){text}`) was invisible in the HTML.
451    attrs.insert(
452      "fill".to_string(),
453      node
454        .get_attribute("fill")
455        .unwrap_or_else(|| "black".to_string()),
456    );
457
458    Some(NodeData::Element {
459      tag: "svg:text".to_string(),
460      attributes: Some(attrs),
461      children,
462    })
463  }
464
465  /// Wrap foreign (non-picture) elements in svg:foreignObject.
466  ///
467  /// Port of `SVG.pm::convertNode`'s else-branch (L148-183): the size comes
468  /// from the node's own `width`/`height`/`depth` (or `imagewidth`/
469  /// `imageheight` for an image), else from the CONTAINING `ltx:g`'s
470  /// `innerwidth`/`innerheight`/`innerdepth`, else its `width`/`height`/
471  /// `depth` — a `\makebox(0,0){$x$}` label's `<Math>` carries no size of its
472  /// own, the `<g>` that `\put` built around it does. `1pt` (non-zero,
473  /// required) when nothing is recorded.
474  fn convert_foreign(&self, _doc: &PostDocument, node: &Node) -> Option<NodeData> {
475    let parent = node.get_parent();
476    let parent_attr = |name: &str| parent.as_ref().and_then(|p| p.get_attribute(name));
477    let width = node
478      .get_attribute("width")
479      .or_else(|| node.get_attribute("imagewidth"))
480      .or_else(|| parent_attr("innerwidth"))
481      .or_else(|| parent_attr("width"))
482      .unwrap_or_else(|| "1pt".to_string());
483    let height = node
484      .get_attribute("height")
485      .or_else(|| node.get_attribute("imageheight"))
486      .or_else(|| parent_attr("innerheight"))
487      .or_else(|| parent_attr("height"))
488      .unwrap_or_else(|| "1pt".to_string());
489    let depth = node
490      .get_attribute("depth")
491      .or_else(|| parent_attr("innerdepth"))
492      .or_else(|| parent_attr("depth"))
493      .unwrap_or_else(|| "0pt".to_string());
494
495    let h_px = to_px(&height);
496    let d_px = to_px(&depth);
497    let y = h_px + d_px;
498
499    let fo = NodeData::Element {
500      tag:        "svg:foreignObject".to_string(),
501      attributes: Some(HashMap::from_iter([
502        ("width".to_string(), format!("{:.2}", to_px(&width))),
503        ("height".to_string(), format!("{:.2}", h_px)),
504        ("overflow".to_string(), "visible".to_string()),
505      ])),
506      children:   vec![NodeData::XmlNode(node.clone())],
507    };
508
509    Some(NodeData::Element {
510      tag:        "svg:g".to_string(),
511      attributes: Some(HashMap::from_iter([(
512        "transform".to_string(),
513        format!("translate(0,{:.2}) scale(1,-1)", y),
514      )])),
515      children:   vec![fo],
516    })
517  }
518
519  /// Convert all element children of a node.
520  fn convert_children(&self, doc: &PostDocument, node: &Node) -> Vec<NodeData> {
521    drawn_children(doc, node)
522      .filter_map(|child| self.convert_node(doc, &child))
523      .collect()
524  }
525
526  /// Copy valid SVG attributes from a LaTeXML node.
527  fn copy_valid_attrs(&self, node: &Node) -> HashMap<String, String> {
528    let mut attrs = HashMap::default();
529    let props = node.get_properties();
530    for (key, value) in &props {
531      match key.as_str() {
532        "d" | "r" | "rx" | "ry" | "x" | "y" | "width" | "height" | "cx" | "cy" | "x1" | "y1"
533        | "x2" | "y2" | "fill" | "stroke" | "stroke-width" | "stroke-dasharray"
534        | "stroke-linecap" | "stroke-linejoin" | "opacity" | "fill-opacity" | "stroke-opacity"
535        | "transform" | "style" | "class" => {
536          attrs.insert(key.clone(), value.clone());
537        },
538        "xml:id" => {},                // Skip: IDs handled separately
539        k if k.starts_with('_') => {}, // Skip internal attributes
540        _ => {},
541      }
542    }
543    attrs
544  }
545}
546
547impl Processor for SVG {
548  fn get_name(&self) -> &str { &self.name }
549
550  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
551    doc.findnodes("//ltx:picture[child::*[not(local-name()='svg') and not(self::ltx:tags)]]")
552  }
553
554  fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
555    if !nodes.is_empty() {
556      doc.add_namespace("svg", SVG_URI);
557    }
558    // Every `ltx:picture` gets converted, as Perl's SVG.pm does: its
559    // `convertNode` MOVES a foreign subtree into the `svg:foreignObject`
560    // (SVG.pm:155-182), so a picture NESTED in that subtree — the
561    // `\makebox(w,h)` inside a `\scalebox`ed box re-opens one — keeps its
562    // identity and is converted by the next iteration in place. Here
563    // `convert_foreign` deep-CLONES the subtree (document.rs `append_clone`)
564    // and `replace_node` detaches the original, so the pre-collected inner
565    // picture was processed detached and its live clone stayed a raw
566    // `ltx:picture` — rendered `as-TeX` into an empty span, its text lost
567    // (`\scalebox{4.5}{\makebox{\parbox{2cm}{…}}}` in a picture; simplecd's
568    // jewel-case labels, sim-os-menus' terminal text). So: convert, then
569    // look for pictures again until none is left — each pass turns at least
570    // one raw picture into `svg:svg`, and nesting is finite.
571    let mut pending = nodes;
572    let mut passes = 0usize;
573    while !pending.is_empty() {
574      for node in &pending {
575        if node.get_parent().is_none() {
576          continue; // detached by an earlier replacement; its clone is live
577        }
578        if let Some(svg) = self.process_svg(&doc, node) {
579          let mut node_mut = node.clone();
580          if node.has_attribute("labels") {
581            // A labelled picture — the box a raw `\refstepcounter` numbered, carrying the step's label and number
582            // (`Document::float_to_label_for`, OXIDIZED_DESIGN_DIVERGENCES #813) — is a reference's target: it stays,
583            // with its id, `labels` and `ltx:tags`, around its drawing made SVG, as a pgf picture's is (rendered
584            // `as-svg`, the id on the `svg`). Witnesses: 2506.01072 (`\newtcbtheorem`), 2505.20088
585            // (`\newtcolorbox[auto counter]`), 2402.06608 (`[blend into=figures]`).
586            let drawn: Vec<Node> = drawn_children(&doc, node).collect();
587            doc.remove_nodes(&drawn);
588            doc.add_nodes(&mut node_mut, &[svg]);
589          } else {
590            doc.replace_node(&node_mut, &[svg]);
591          }
592        }
593      }
594      passes += 1;
595      if passes > 64 {
596        break; // a picture that never converts must not loop forever
597      }
598      pending = self.to_process(&doc);
599    }
600    Ok(vec![doc])
601  }
602}
603
604// ======================================================================
605// Utility functions
606
607/// A picture's element children but its `ltx:tags` (the number a labelled picture carries, OXIDIZED_DESIGN_DIVERGENCES
608/// #813): what it draws.
609fn drawn_children<'a>(doc: &'a PostDocument, node: &Node) -> impl Iterator<Item = Node> + 'a {
610  element_children_iter(node).filter(|child| doc.get_qname(child).as_deref() != Some("ltx:tags"))
611}
612
613/// Convert a TeX dimension string to SVG pixels.
614///
615/// Port of `to_px`.
616fn to_px(s: &str) -> f64 {
617  let trimmed = s.trim();
618  if let Some(pt) = trimmed.strip_suffix("pt") {
619    pt.trim().parse::<f64>().unwrap_or(0.0) * DPI / 72.27
620  } else if let Some(px) = trimmed.strip_suffix("px") {
621    px.trim().parse::<f64>().unwrap_or(0.0)
622  } else if let Some(em) = trimmed.strip_suffix("em") {
623    em.trim().parse::<f64>().unwrap_or(0.0) * 10.0 // rough
624  } else {
625    trimmed.parse::<f64>().unwrap_or(0.0)
626  }
627}
628
629/// Parse a dimension string to a float.
630fn parse_dim(s: &str) -> f64 {
631  let trimmed = s.trim();
632  let num: String = trimmed
633    .chars()
634    .take_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-' || *c == '+')
635    .collect();
636  num.parse::<f64>().unwrap_or(0.0)
637}
638
639/// Explode a space/comma-separated coordinate string into floats.
640fn explode_coord(s: &str) -> Vec<f64> {
641  s.split([' ', ','])
642    .filter(|s| !s.is_empty())
643    .filter_map(|s| s.trim().parse::<f64>().ok())
644    .collect()
645}
646
647/// Generate an SVG path for a partial rounded rectangle.
648///
649/// Port of `ovalPath`.
650fn oval_path(part: &str, x: f64, y: f64, w: f64, h: f64, r: f64) -> String {
651  match part {
652    "t" => format!(
653      "M {} {} L {} {} A {} {} 0 0 1 {} {} L {} {} A {} {} 0 0 1 {} {} L {} {}",
654      x,
655      y - h / 2.0,
656      x,
657      y - r,
658      r,
659      r,
660      x + r,
661      y,
662      x + w - r,
663      y,
664      r,
665      r,
666      x + w,
667      y - r,
668      x + w,
669      y - h / 2.0
670    ),
671    "b" => format!(
672      "M {} {} L {} {} A {} {} 0 0 1 {} {} L {} {} A {} {} 0 0 1 {} {} L {} {}",
673      x + w,
674      y - h / 2.0,
675      x + w,
676      y - h + r,
677      r,
678      r,
679      x + w - r,
680      y - h,
681      x + r,
682      y - h,
683      r,
684      r,
685      x,
686      y - h + r,
687      x,
688      y - h / 2.0
689    ),
690    _ => format!("M {} {} L {} {}", x, y, x + w, y), // fallback
691  }
692}
693
694#[cfg(test)]
695mod tests {
696  use super::*;
697
698  fn approx(a: f64, b: f64) -> bool { (a - b).abs() < 1e-6 }
699
700  #[test]
701  fn to_px_pt_scales_by_dpi_over_72_27() {
702    // 72.27pt = 1 inch = DPI pixels.
703    assert!(approx(to_px("72.27pt"), DPI));
704    assert!(approx(to_px("0pt"), 0.0));
705  }
706
707  #[test]
708  fn to_px_px_is_identity() {
709    assert!(approx(to_px("42px"), 42.0));
710    assert!(approx(to_px("  3.5px "), 3.5));
711  }
712
713  #[test]
714  fn to_px_em_rough_x10() {
715    // Rough approximation per the code comment; lock it in.
716    assert!(approx(to_px("2em"), 20.0));
717  }
718
719  #[test]
720  fn to_px_bare_number_is_f64() {
721    assert!(approx(to_px("7"), 7.0));
722    assert!(approx(to_px("  -1.5 "), -1.5));
723  }
724
725  #[test]
726  fn to_px_unknown_unit_is_zero() {
727    // No known suffix and no leading number → parse fails → 0.0.
728    assert!(approx(to_px("xyz"), 0.0));
729  }
730
731  #[test]
732  fn parse_dim_takes_leading_numeric_prefix() {
733    assert!(approx(parse_dim("12.5pt"), 12.5));
734    assert!(approx(parse_dim("-3.0em"), -3.0));
735    assert!(approx(parse_dim("+7px"), 7.0));
736  }
737
738  #[test]
739  fn parse_dim_no_leading_number_is_zero() {
740    assert!(approx(parse_dim("pt"), 0.0));
741    assert!(approx(parse_dim(""), 0.0));
742  }
743
744  #[test]
745  fn explode_coord_splits_on_space_and_comma() {
746    assert_eq!(explode_coord("1 2 3"), vec![1.0, 2.0, 3.0]);
747    assert_eq!(explode_coord("1,2,3"), vec![1.0, 2.0, 3.0]);
748    assert_eq!(explode_coord("1, 2 3"), vec![1.0, 2.0, 3.0]);
749  }
750
751  #[test]
752  fn explode_coord_skips_empty_and_non_numeric() {
753    // Empty tokens are filtered; non-numeric tokens are filtered by `parse.ok()`.
754    assert_eq!(explode_coord(",, 4  5,,"), vec![4.0, 5.0]);
755    assert_eq!(explode_coord("1 abc 2"), vec![1.0, 2.0]);
756  }
757
758  #[test]
759  fn explode_coord_empty_input_is_empty() {
760    assert!(explode_coord("").is_empty());
761    assert!(explode_coord("   ").is_empty());
762  }
763
764  #[test]
765  fn oval_path_top_starts_and_ends_at_half_height() {
766    // For the 't' branch the path begins at (x, y-h/2) and ends at (x+w, y-h/2).
767    let s = oval_path("t", 10.0, 20.0, 100.0, 40.0, 5.0);
768    assert!(s.starts_with("M 10 0 ")); // y - h/2 = 20 - 20 = 0
769    assert!(s.ends_with(" 110 0")); // x+w, y-h/2
770  }
771
772  #[test]
773  fn oval_path_bottom_traces_reverse_direction() {
774    // For the 'b' branch the path begins at (x+w, y-h/2) and ends at (x, y-h/2).
775    let s = oval_path("b", 10.0, 20.0, 100.0, 40.0, 5.0);
776    assert!(s.starts_with("M 110 0 "));
777    assert!(s.ends_with(" 10 0"));
778  }
779
780  #[test]
781  fn oval_path_unknown_part_uses_simple_line_fallback() {
782    let s = oval_path("?", 0.0, 0.0, 50.0, 10.0, 2.0);
783    assert_eq!(s, "M 0 0 L 50 0");
784  }
785}