Skip to main content

usvg/parser/svgtree/
parse.rs

1// Copyright 2021 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::collections::{HashMap, HashSet};
5
6use roxmltree::Error;
7use simplecss::Declaration;
8use svgtypes::FontShorthand;
9
10use super::{AId, Attribute, Document, EId, NodeData, NodeId, NodeKind, ShortRange, SvgNode};
11
12const SVG_NS: &str = "http://www.w3.org/2000/svg";
13const XLINK_NS: &str = "http://www.w3.org/1999/xlink";
14const XML_NAMESPACE_NS: &str = "http://www.w3.org/XML/1998/namespace";
15
16impl<'input> Document<'input> {
17    /// Parses a [`Document`] from a [`roxmltree::Document`].
18    pub fn parse_tree(
19        xml: &roxmltree::Document<'input>,
20        injected_stylesheet: Option<&'input str>,
21        max_depth: u32,
22    ) -> Result<Document<'input>, Error> {
23        parse(xml, injected_stylesheet, max_depth)
24    }
25
26    pub(crate) fn append(&mut self, parent_id: NodeId, kind: NodeKind) -> NodeId {
27        let new_child_id = NodeId::from(self.nodes.len());
28        self.nodes.push(NodeData {
29            parent: Some(parent_id),
30            next_sibling: None,
31            children: None,
32            kind,
33        });
34
35        let last_child_id = self.nodes[parent_id.get_usize()].children.map(|(_, id)| id);
36
37        if let Some(id) = last_child_id {
38            self.nodes[id.get_usize()].next_sibling = Some(new_child_id);
39        }
40
41        self.nodes[parent_id.get_usize()].children = Some(
42            if let Some((first_child_id, _)) = self.nodes[parent_id.get_usize()].children {
43                (first_child_id, new_child_id)
44            } else {
45                (new_child_id, new_child_id)
46            },
47        );
48
49        new_child_id
50    }
51
52    fn append_attribute(
53        &mut self,
54        name: AId,
55        value: roxmltree::StringStorage<'input>,
56        important: bool,
57    ) {
58        self.attrs.push(Attribute {
59            name,
60            value,
61            important,
62        });
63    }
64}
65
66fn parse<'input>(
67    xml: &roxmltree::Document<'input>,
68    injected_stylesheet: Option<&'input str>,
69    max_depth: u32,
70) -> Result<Document<'input>, Error> {
71    let mut doc = Document {
72        nodes: Vec::new(),
73        attrs: Vec::new(),
74        links: HashMap::new(),
75        circular_references: HashSet::new(),
76    };
77
78    // build a map of id -> node for resolve_href
79    let mut id_map = HashMap::new();
80    for node in xml.descendants() {
81        if let Some(id) = node.attribute("id") {
82            id_map.entry(id).or_insert(node);
83        }
84    }
85
86    // Add a root node.
87    doc.nodes.push(NodeData {
88        parent: None,
89        next_sibling: None,
90        children: None,
91        kind: NodeKind::Root,
92    });
93
94    let style_texts = style_texts(xml);
95    let style_sheet = resolve_css(&style_texts, injected_stylesheet);
96
97    parse_xml_node_children(
98        xml.root(),
99        xml.root(),
100        doc.root().id,
101        &style_sheet,
102        false,
103        0,
104        max_depth,
105        &mut doc,
106        &id_map,
107    )?;
108
109    // Check that the root element is `svg`.
110    match doc.root().first_element_child() {
111        Some(child) => {
112            if child.tag_name() != Some(EId::Svg) {
113                return Err(roxmltree::Error::NoRootNode);
114            }
115        }
116        None => return Err(roxmltree::Error::NoRootNode),
117    }
118
119    let mut links = HashMap::new();
120    for node in doc.descendants() {
121        if let Some(id) = node.attribute::<&str>(AId::Id) {
122            links.insert(id.to_string(), node.id);
123        }
124    }
125    doc.links = links;
126
127    doc.circular_references = find_circular_references(&doc);
128
129    Ok(doc)
130}
131
132pub(crate) fn parse_tag_name(node: roxmltree::Node) -> Option<EId> {
133    if !node.is_element() {
134        return None;
135    }
136
137    if !matches!(node.tag_name().namespace(), None | Some(SVG_NS)) {
138        return None;
139    }
140
141    EId::from_str(node.tag_name().name())
142}
143
144fn parse_xml_node_children<'input>(
145    parent: roxmltree::Node<'_, 'input>,
146    origin: roxmltree::Node,
147    parent_id: NodeId,
148    style_sheet: &simplecss::StyleSheet,
149    ignore_ids: bool,
150    depth: u32,
151    max_depth: u32,
152    doc: &mut Document<'input>,
153    id_map: &HashMap<&str, roxmltree::Node<'_, 'input>>,
154) -> Result<(), Error> {
155    for node in parent.children() {
156        parse_xml_node(
157            node,
158            origin,
159            parent_id,
160            style_sheet,
161            ignore_ids,
162            depth,
163            max_depth,
164            doc,
165            id_map,
166        )?;
167    }
168
169    Ok(())
170}
171
172fn parse_xml_node<'input>(
173    node: roxmltree::Node<'_, 'input>,
174    origin: roxmltree::Node,
175    parent_id: NodeId,
176    style_sheet: &simplecss::StyleSheet,
177    ignore_ids: bool,
178    depth: u32,
179    max_depth: u32,
180    doc: &mut Document<'input>,
181    id_map: &HashMap<&str, roxmltree::Node<'_, 'input>>,
182) -> Result<(), Error> {
183    if depth > max_depth {
184        return Err(Error::NodesLimitReached);
185    }
186
187    let mut tag_name = match parse_tag_name(node) {
188        Some(id) => id,
189        None => return Ok(()),
190    };
191
192    if tag_name == EId::Style {
193        return Ok(());
194    }
195
196    // TODO: remove?
197    // Treat links as groups.
198    if tag_name == EId::A {
199        tag_name = EId::G;
200    }
201
202    let node_id = parse_svg_element(node, parent_id, tag_name, style_sheet, ignore_ids, doc)?;
203    if tag_name == EId::Text {
204        super::text::parse_svg_text_element(node, node_id, style_sheet, doc)?;
205    } else if tag_name == EId::Use {
206        parse_svg_use_element(
207            node,
208            origin,
209            node_id,
210            style_sheet,
211            depth + 1,
212            max_depth,
213            doc,
214            id_map,
215        )?;
216    } else {
217        parse_xml_node_children(
218            node,
219            origin,
220            node_id,
221            style_sheet,
222            ignore_ids,
223            depth + 1,
224            max_depth,
225            doc,
226            id_map,
227        )?;
228    }
229
230    Ok(())
231}
232
233pub(crate) fn parse_svg_element<'input>(
234    xml_node: roxmltree::Node<'_, 'input>,
235    parent_id: NodeId,
236    tag_name: EId,
237    style_sheet: &simplecss::StyleSheet,
238    ignore_ids: bool,
239    doc: &mut Document<'input>,
240) -> Result<NodeId, Error> {
241    let attrs_start_idx = doc.attrs.len();
242    let mut href_idx: Option<usize> = None;
243
244    // Copy presentational attributes first.
245    for attr in xml_node.attributes() {
246        match attr.namespace() {
247            None | Some(SVG_NS) | Some(XLINK_NS) | Some(XML_NAMESPACE_NS) => {}
248            _ => continue,
249        }
250
251        let aid = match AId::from_str(attr.name()) {
252            Some(v) => v,
253            None => continue,
254        };
255
256        // During a `use` resolving, all `id` attributes must be ignored.
257        // Otherwise we will get elements with duplicated id's.
258        if ignore_ids && aid == AId::Id {
259            continue;
260        }
261
262        // For some reason those properties are allowed only inside a `style` attribute and CSS.
263        if matches!(aid, AId::MixBlendMode | AId::Isolation | AId::FontKerning) {
264            continue;
265        } else if aid == AId::ImageRendering
266            && matches!(
267                attr.value(),
268                "smooth" | "high-quality" | "crisp-edges" | "pixelated"
269            )
270        {
271            continue;
272        }
273
274        // SVG 2: when both `href` and `xlink:href` are present, the unprefixed
275        // `href` takes precedence and the XLink one must be ignored, regardless
276        // of their order in the source document.
277        // https://www.w3.org/TR/SVG2/linking.html#XLinkRefAttrs
278        if aid == AId::Href {
279            let is_unprefixed = attr.namespace().is_none();
280            let is_xlink = attr.namespace() == Some(XLINK_NS);
281            if !is_unprefixed && !is_xlink {
282                continue;
283            }
284
285            if let Some(idx) = href_idx {
286                // An `href` was already stored. Only an unprefixed `href` is
287                // allowed to override it; an `xlink:href` is ignored.
288                if is_unprefixed {
289                    doc.attrs[idx].value = attr.value_storage().clone();
290                }
291                continue;
292            }
293        }
294
295        let added = append_attribute(
296            parent_id,
297            tag_name,
298            aid,
299            attr.value_storage().clone(),
300            false,
301            doc,
302        );
303        if added && aid == AId::Href {
304            href_idx = Some(doc.attrs.len() - 1);
305        }
306    }
307
308    let mut insert_attribute = |aid, value: roxmltree::StringStorage<'input>, important: bool| {
309        // Check that attribute already exists.
310        let idx = doc.attrs[attrs_start_idx..]
311            .iter_mut()
312            .position(|a| a.name == aid);
313
314        // Append an attribute as usual.
315        let added = append_attribute(parent_id, tag_name, aid, value, important, doc);
316
317        // Check that attribute was actually added, because it could be skipped.
318        if added {
319            if let Some(idx) = idx {
320                let last_idx = doc.attrs.len() - 1;
321                let existing_idx = attrs_start_idx + idx;
322
323                // See https://developer.mozilla.org/en-US/docs/Web/CSS/important
324                // When a declaration is important, the order of precedence is reversed.
325                // Declarations marked as important in the user-agent style sheets override
326                // all important declarations in the user style sheets. Similarly, all important
327                // declarations in the user style sheets override all important declarations in the
328                // author's style sheets. Finally, all important declarations take precedence over
329                // all animations.
330                //
331                // Which means:
332                // 1) Existing is not important, new is not important -> swap
333                // 2) Existing is important, new is not important -> don't swap
334                // 3) Existing is not important, new is important -> swap
335                // 4) Existing is important, new is important -> don't swap (since the order
336                // is reversed, so existing important attributes take precedence over new
337                // important attributes)
338                let has_precedence = !doc.attrs[existing_idx].important;
339
340                if has_precedence {
341                    doc.attrs.swap(existing_idx, last_idx);
342                }
343
344                // Remove last.
345                doc.attrs.pop();
346            }
347        }
348    };
349
350    // Apply CSS.
351    for rule in &style_sheet.rules {
352        if rule.selector.matches(&XmlNode(xml_node)) {
353            for declaration in &rule.declarations {
354                write_declaration(
355                    declaration,
356                    roxmltree::StringStorage::new_owned,
357                    &mut insert_attribute,
358                );
359            }
360        }
361    }
362
363    // Split a `style` attribute.
364    if let Some(style) = xml_node.attribute_node("style") {
365        match style.value_storage() {
366            roxmltree::StringStorage::Borrowed(value) => write_declarations(
367                value,
368                roxmltree::StringStorage::Borrowed,
369                &mut insert_attribute,
370            ),
371            roxmltree::StringStorage::Owned(_) => write_declarations(
372                style.value(),
373                roxmltree::StringStorage::new_owned,
374                &mut insert_attribute,
375            ),
376        }
377    }
378
379    if doc.nodes.len() > 1_000_000 {
380        return Err(Error::NodesLimitReached);
381    }
382
383    let node_id = doc.append(
384        parent_id,
385        NodeKind::Element {
386            tag_name,
387            attributes: ShortRange::new(attrs_start_idx as u32, doc.attrs.len() as u32),
388        },
389    );
390
391    Ok(node_id)
392}
393
394fn write_declarations<'a, 'input>(
395    text: &'a str,
396    storage: fn(&'a str) -> roxmltree::StringStorage<'input>,
397    insert: &mut impl FnMut(AId, roxmltree::StringStorage<'input>, bool),
398) {
399    for declaration in simplecss::DeclarationTokenizer::from(text) {
400        write_declaration(&declaration, storage, insert);
401    }
402}
403
404fn write_declaration<'a, 'input>(
405    declaration: &Declaration<'a>,
406    storage: fn(&'a str) -> roxmltree::StringStorage<'input>,
407    insert: &mut impl FnMut(AId, roxmltree::StringStorage<'input>, bool),
408) {
409    // TODO: perform XML attribute normalization
410    let imp = declaration.important;
411    let val = declaration.value;
412
413    if declaration.name == "marker" {
414        insert(AId::MarkerStart, storage(val), imp);
415        insert(AId::MarkerMid, storage(val), imp);
416        insert(AId::MarkerEnd, storage(val), imp);
417    } else if declaration.name == "font" {
418        if let Ok(shorthand) = FontShorthand::from_str(val) {
419            // First we need to reset all values to their default.
420            for (aid, value) in [
421                (AId::FontStyle, "normal"),
422                (AId::FontVariant, "normal"),
423                (AId::FontWeight, "normal"),
424                (AId::FontStretch, "normal"),
425                (AId::LineHeight, "normal"),
426                (AId::FontSizeAdjust, "none"),
427                (AId::FontKerning, "auto"),
428                (AId::FontVariantCaps, "normal"),
429                (AId::FontVariantLigatures, "normal"),
430                (AId::FontVariantNumeric, "normal"),
431                (AId::FontVariantEastAsian, "normal"),
432                (AId::FontVariantPosition, "normal"),
433            ] {
434                insert(aid, roxmltree::StringStorage::Borrowed(value), imp);
435            }
436
437            // Then, we set the properties that have been declared.
438            if let Some(s) = shorthand.font_stretch {
439                insert(AId::FontStretch, storage(s), imp);
440            }
441            if let Some(s) = shorthand.font_weight {
442                insert(AId::FontWeight, storage(s), imp);
443            }
444            if let Some(s) = shorthand.font_variant {
445                insert(AId::FontVariant, storage(s), imp);
446            }
447            if let Some(s) = shorthand.font_style {
448                insert(AId::FontStyle, storage(s), imp);
449            }
450            insert(AId::FontSize, storage(shorthand.font_size), imp);
451            insert(AId::FontFamily, storage(shorthand.font_family), imp);
452        } else {
453            log::warn!(
454                "Failed to parse {} value: '{}'",
455                AId::Font,
456                declaration.value
457            );
458        }
459    } else if let Some(aid) = AId::from_str(declaration.name) {
460        // Parse only the presentation attributes.
461        if aid.is_presentation() {
462            insert(aid, storage(val), imp);
463        }
464    }
465}
466
467fn append_attribute<'input>(
468    parent_id: NodeId,
469    tag_name: EId,
470    aid: AId,
471    value: roxmltree::StringStorage<'input>,
472    important: bool,
473    doc: &mut Document<'input>,
474) -> bool {
475    match aid {
476        // The `style` attribute will be split into attributes, so we don't need it.
477        AId::Style |
478        // No need to copy a `class` attribute since CSS were already resolved.
479        AId::Class => return false,
480        _ => {}
481    }
482
483    // Ignore `xlink:href` on `tspan` (which was originally `tref` or `a`),
484    // because we will convert `tref` into `tspan` anyway.
485    if tag_name == EId::Tspan && aid == AId::Href {
486        return false;
487    }
488
489    if aid.allows_inherit_value() && &*value == "inherit" {
490        return resolve_inherit(parent_id, aid, doc);
491    }
492
493    doc.append_attribute(aid, value, important);
494    true
495}
496
497fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {
498    if aid.is_inheritable() {
499        // Inheritable attributes can inherit a value from an any ancestor.
500        let node_id = doc
501            .get(parent_id)
502            .ancestors()
503            .find(|n| n.has_attribute(aid))
504            .map(|n| n.id);
505        if let Some(node_id) = node_id {
506            if let Some(attr) = doc
507                .get(node_id)
508                .attributes()
509                .iter()
510                .find(|a| a.name == aid)
511                .cloned()
512            {
513                doc.attrs.push(Attribute {
514                    name: aid,
515                    value: attr.value,
516                    important: attr.important,
517                });
518
519                return true;
520            }
521        }
522    } else {
523        // Non-inheritable attributes can inherit a value only from a direct parent.
524        if let Some(attr) = doc
525            .get(parent_id)
526            .attributes()
527            .iter()
528            .find(|a| a.name == aid)
529            .cloned()
530        {
531            doc.attrs.push(Attribute {
532                name: aid,
533                value: attr.value,
534                important: attr.important,
535            });
536
537            return true;
538        }
539    }
540
541    // Fallback to a default value if possible.
542    let value = match aid {
543        AId::ImageRendering | AId::ShapeRendering | AId::TextRendering => "auto",
544
545        AId::ClipPath
546        | AId::Filter
547        | AId::MarkerEnd
548        | AId::MarkerMid
549        | AId::MarkerStart
550        | AId::Mask
551        | AId::Stroke
552        | AId::StrokeDasharray
553        | AId::TextDecoration => "none",
554
555        AId::FontStretch
556        | AId::FontStyle
557        | AId::FontVariant
558        | AId::FontWeight
559        | AId::LetterSpacing
560        | AId::WordSpacing => "normal",
561
562        AId::Fill | AId::FloodColor | AId::StopColor => "black",
563
564        AId::FillOpacity
565        | AId::FloodOpacity
566        | AId::Opacity
567        | AId::StopOpacity
568        | AId::StrokeOpacity => "1",
569
570        AId::ClipRule | AId::FillRule => "nonzero",
571
572        AId::BaselineShift => "baseline",
573        AId::ColorInterpolationFilters => "linearRGB",
574        AId::Direction => "ltr",
575        AId::Display => "inline",
576        AId::FontSize => "medium",
577        AId::Overflow => "visible",
578        AId::StrokeDashoffset => "0",
579        AId::StrokeLinecap => "butt",
580        AId::StrokeLinejoin => "miter",
581        AId::StrokeMiterlimit => "4",
582        AId::StrokeWidth => "1",
583        AId::TextAnchor => "start",
584        AId::Visibility => "visible",
585        AId::WritingMode => "lr-tb",
586        _ => return false,
587    };
588
589    doc.append_attribute(aid, roxmltree::StringStorage::Borrowed(value), false);
590    true
591}
592
593fn resolve_href<'a, 'input: 'a>(
594    node: roxmltree::Node<'a, 'input>,
595    id_map: &HashMap<&str, roxmltree::Node<'a, 'input>>,
596) -> Option<roxmltree::Node<'a, 'input>> {
597    // See the comment in `parse_svg_element` about `href` precedence.
598    //
599    // Note: `roxmltree::Node::attribute("href")` matches by local name only and
600    // would return whichever `href`/`xlink:href` comes first, so we have to
601    // filter by namespace explicitly.
602    let link_value = node
603        .attributes()
604        .find(|a| a.name() == "href" && a.namespace().is_none())
605        .or_else(|| {
606            node.attributes()
607                .find(|a| a.name() == "href" && a.namespace() == Some(XLINK_NS))
608        })
609        .map(|a| a.value())?;
610
611    let link_id = svgtypes::IRI::from_str(link_value).ok()?.0;
612
613    id_map.get(link_id).copied()
614}
615
616fn parse_svg_use_element<'input>(
617    node: roxmltree::Node<'_, 'input>,
618    origin: roxmltree::Node,
619    parent_id: NodeId,
620    style_sheet: &simplecss::StyleSheet,
621    depth: u32,
622    max_depth: u32,
623    doc: &mut Document<'input>,
624    id_map: &HashMap<&str, roxmltree::Node<'_, 'input>>,
625) -> Result<(), Error> {
626    let link = match resolve_href(node, id_map) {
627        Some(v) => v,
628        None => return Ok(()),
629    };
630
631    if link == node || link == origin {
632        log::warn!(
633            "Recursive 'use' detected. '{}' will be skipped.",
634            node.attribute((SVG_NS, "id")).unwrap_or_default()
635        );
636        return Ok(());
637    }
638
639    // Make sure we're linked to an SVG element.
640    if parse_tag_name(link).is_none() {
641        return Ok(());
642    }
643
644    // Check that none of the linked node's children reference current `use` node
645    // via other `use` node.
646    //
647    // Example:
648    // <g id="g1">
649    //     <use xlink:href="#use1" id="use2"/>
650    // </g>
651    // <use xlink:href="#g1" id="use1"/>
652    //
653    // `use2` should be removed.
654    //
655    // Also, child should not reference its parent:
656    // <g id="g1">
657    //     <use xlink:href="#g1" id="use1"/>
658    // </g>
659    //
660    // `use1` should be removed.
661    let mut is_recursive = false;
662    for link_child in link
663        .descendants()
664        .skip(1)
665        .filter(|n| n.has_tag_name((SVG_NS, "use")))
666    {
667        if let Some(link2) = resolve_href(link_child, id_map) {
668            if link2 == node || link2 == link {
669                is_recursive = true;
670                break;
671            }
672        }
673    }
674
675    if is_recursive {
676        log::warn!(
677            "Recursive 'use' detected. '{}' will be skipped.",
678            node.attribute((SVG_NS, "id")).unwrap_or_default()
679        );
680        return Ok(());
681    }
682
683    parse_xml_node(
684        link,
685        node,
686        parent_id,
687        style_sheet,
688        true,
689        depth + 1,
690        max_depth,
691        doc,
692        id_map,
693    )
694}
695
696/// The child text content of each CSS `style` element.
697fn style_texts(xml: &roxmltree::Document) -> Vec<String> {
698    xml.descendants()
699        .filter(|n| n.has_tag_name("style"))
700        .filter(|n| {
701            n.attribute("type")
702                .is_none_or(|t| t.is_empty() || t.eq_ignore_ascii_case("text/css"))
703        })
704        .map(|n| {
705            n.children()
706                .filter(|c| c.is_text())
707                .filter_map(|c| c.text())
708                .collect()
709        })
710        .collect()
711}
712
713fn resolve_css<'a>(
714    style_texts: &'a [String],
715    style_sheet: Option<&'a str>,
716) -> simplecss::StyleSheet<'a> {
717    let mut sheet = simplecss::StyleSheet::new();
718
719    // Injected style sheets do not override internal ones (we mimic the logic of rsvg-convert),
720    // so we need to parse it first.
721    if let Some(style_sheet) = style_sheet {
722        sheet.parse_more(style_sheet);
723    }
724
725    for text in style_texts {
726        sheet.parse_more(text);
727    }
728
729    sheet
730}
731
732struct XmlNode<'a, 'input: 'a>(roxmltree::Node<'a, 'input>);
733
734impl simplecss::Element for XmlNode<'_, '_> {
735    fn parent_element(&self) -> Option<Self> {
736        self.0.parent_element().map(XmlNode)
737    }
738
739    fn prev_sibling_element(&self) -> Option<Self> {
740        self.0.prev_sibling_element().map(XmlNode)
741    }
742
743    fn has_local_name(&self, local_name: &str) -> bool {
744        self.0.tag_name().name() == local_name
745    }
746
747    fn attribute_matches(&self, local_name: &str, operator: simplecss::AttributeOperator) -> bool {
748        match self.0.attribute(local_name) {
749            Some(value) => operator.matches(value),
750            None => false,
751        }
752    }
753
754    fn pseudo_class_matches(&self, class: simplecss::PseudoClass) -> bool {
755        match class {
756            simplecss::PseudoClass::FirstChild => self.prev_sibling_element().is_none(),
757            // TODO: lang
758            _ => false, // Since we are querying a static SVG we can ignore other pseudo-classes.
759        }
760    }
761}
762
763fn find_circular_references(doc: &Document) -> HashSet<(NodeId, AId)> {
764    let mut search = CycleSearch::default();
765    for node in doc.descendants().filter(|n| is_resource(*n)) {
766        search.visit(node);
767    }
768
769    search.circular_references
770}
771
772#[derive(PartialEq)]
773enum Visit {
774    InProgress,
775    Done,
776}
777
778#[derive(Default)]
779struct CycleSearch {
780    visits: HashMap<NodeId, Visit>,
781    templates: HashMap<NodeId, NodeId>,
782    chain: Vec<NodeId>,
783    circular_references: HashSet<(NodeId, AId)>,
784}
785
786impl CycleSearch {
787    fn visit(&mut self, node: SvgNode) {
788        let node = self.with_content(node);
789        if self.visits.contains_key(&node.id) {
790            return;
791        }
792
793        self.visits.insert(node.id, Visit::InProgress);
794        let mut stack = vec![(node.id, references(node).into_iter())];
795        while let Some((node_id, references_left)) = stack.last_mut() {
796            match references_left.next() {
797                Some((user, aid, target)) => {
798                    let content = self.with_content(target);
799                    match self.visits.get(&content.id) {
800                        Some(Visit::InProgress) => {
801                            log::warn!(
802                                "Circular reference to '{}' via '{}' ignored.",
803                                target.element_id(),
804                                aid
805                            );
806                            self.circular_references.insert((user.id, aid));
807                        }
808                        Some(Visit::Done) => {}
809                        None => {
810                            self.visits.insert(content.id, Visit::InProgress);
811                            stack.push((content.id, references(content).into_iter()));
812                        }
813                    }
814                }
815                None => {
816                    self.visits.insert(*node_id, Visit::Done);
817                    stack.pop();
818                }
819            }
820        }
821    }
822
823    /// Returns the first element in the `xlink:href` chain of a pattern or filter that has
824    /// children, since its children are used instead. Elements sharing a template are resolved to
825    /// the same element, so its content is only walked once, and results are cached along the
826    /// chain.
827    fn with_content<'a, 'input: 'a>(&mut self, node: SvgNode<'a, 'input>) -> SvgNode<'a, 'input> {
828        if !matches!(node.tag_name(), Some(EId::Pattern | EId::Filter)) {
829            return node;
830        }
831
832        let mut current = node;
833        let content = loop {
834            if let Some(id) = self.templates.get(&current.id) {
835                break node.document().get(*id);
836            }
837
838            if current.has_children() {
839                break current;
840            }
841
842            // Resolves to `node` until the chain is done, which also ends an `xlink:href` cycle.
843            self.templates.insert(current.id, node.id);
844            self.chain.push(current.id);
845            match current.node_attribute(AId::Href) {
846                Some(link) if link.tag_name() == node.tag_name() => current = link,
847                _ => break node,
848            }
849        };
850
851        for id in self.chain.drain(..) {
852            self.templates.insert(id, content.id);
853        }
854
855        content
856    }
857}
858
859type Reference<'a, 'input> = (SvgNode<'a, 'input>, AId, SvgNode<'a, 'input>);
860
861/// Returns the references that are followed when rendering `node`,
862/// as `(element that uses the reference, attribute, referenced element)`.
863fn references<'a, 'input: 'a>(node: SvgNode<'a, 'input>) -> Vec<Reference<'a, 'input>> {
864    let mut references = Vec::new();
865    match node.tag_name() {
866        // Masks, filters, paint servers and markers are ignored inside clip paths.
867        Some(EId::ClipPath) => {
868            push_link(node, AId::ClipPath, EId::ClipPath, &mut references);
869            for_each_content_descendant(node, &mut |child| {
870                push_link(child, AId::ClipPath, EId::ClipPath, &mut references)
871            });
872        }
873        Some(EId::Mask) => {
874            push_link(node, AId::Mask, EId::Mask, &mut references);
875            for_each_content_descendant(node, &mut |child| push_references(child, &mut references));
876        }
877        Some(EId::Pattern) => {
878            for_each_content_descendant(node, &mut |child| push_references(child, &mut references));
879        }
880        Some(EId::Filter) => {
881            for child in node.descendants() {
882                if child.tag_name() == Some(EId::FeImage) {
883                    if let Some(link) = child.node_attribute(AId::Href) {
884                        if link.tag_name().is_some_and(|tag| {
885                            tag.is_graphic() || matches!(tag, EId::G | EId::Switch | EId::Svg)
886                        }) {
887                            references.push((child, AId::Href, link));
888                        }
889                    }
890                }
891            }
892        }
893        Some(EId::Marker) => {
894            for_each_content_descendant(node, &mut |child| push_references(child, &mut references));
895        }
896        // An element referenced by `feImage`.
897        _ => {
898            push_references(node, &mut references);
899            for_each_content_descendant(node, &mut |child| push_references(child, &mut references));
900        }
901    }
902
903    references
904}
905
906/// Calls `f` for each descendant of `node`, skipping nested resources and other definitions.
907/// Those are only rendered where they are referenced, and resources are visited on their own.
908fn for_each_content_descendant<'a, 'input: 'a>(
909    node: SvgNode<'a, 'input>,
910    f: &mut impl FnMut(SvgNode<'a, 'input>),
911) {
912    for child in node.children() {
913        // A `use` stores a copy of the `symbol` it references as its child.
914        let is_definition = is_resource(child)
915            || child.tag_name() == Some(EId::Defs)
916            || (child.tag_name() == Some(EId::Symbol) && node.tag_name() != Some(EId::Use));
917        if !is_definition {
918            f(child);
919            for_each_content_descendant(child, f);
920        }
921    }
922}
923
924fn is_resource(node: SvgNode) -> bool {
925    matches!(
926        node.tag_name(),
927        Some(EId::ClipPath | EId::Mask | EId::Pattern | EId::Filter | EId::Marker)
928    )
929}
930
931fn push_references<'a, 'input: 'a>(
932    node: SvgNode<'a, 'input>,
933    references: &mut Vec<Reference<'a, 'input>>,
934) {
935    if !node.is_element() {
936        return;
937    }
938
939    push_link(node, AId::ClipPath, EId::ClipPath, references);
940    push_link(node, AId::Mask, EId::Mask, references);
941
942    if let Some(value) = node.attribute::<&str>(AId::Filter) {
943        for filter in svgtypes::FilterValueListParser::from(value).flatten() {
944            if let svgtypes::FilterValue::Url(id) = filter {
945                if let Some(link) = node.document().element_by_id(id) {
946                    if link.tag_name() == Some(EId::Filter) {
947                        references.push((node, AId::Filter, link));
948                    }
949                }
950            }
951        }
952    }
953
954    // Paint and markers are inherited, so they have to be resolved like during conversion.
955    for aid in [AId::Fill, AId::Stroke] {
956        if let Some(value) = node.find_attribute::<&str>(aid) {
957            if let Ok(svgtypes::Paint::FuncIRI(id, _)) = svgtypes::Paint::from_str(value) {
958                if let Some(link) = node.document().element_by_id(id) {
959                    if link.tag_name() == Some(EId::Pattern) {
960                        references.push((node, aid, link));
961                    }
962                }
963            }
964        }
965    }
966
967    let is_shape = matches!(
968        node.tag_name(),
969        Some(
970            EId::Rect
971                | EId::Circle
972                | EId::Ellipse
973                | EId::Line
974                | EId::Polyline
975                | EId::Polygon
976                | EId::Path
977        )
978    );
979    // Markers are never drawn inside a clip path.
980    if is_shape
981        && !node
982            .ancestors()
983            .any(|n| n.tag_name() == Some(EId::ClipPath))
984    {
985        for aid in [AId::MarkerStart, AId::MarkerMid, AId::MarkerEnd] {
986            if let Some(link) = node.find_attribute::<SvgNode>(aid) {
987                if link.tag_name() == Some(EId::Marker) {
988                    references.push((node, aid, link));
989                }
990            }
991        }
992    }
993}
994
995fn push_link<'a, 'input: 'a>(
996    node: SvgNode<'a, 'input>,
997    aid: AId,
998    tag_name: EId,
999    references: &mut Vec<Reference<'a, 'input>>,
1000) {
1001    if let Some(link) = node.node_attribute(aid) {
1002        if link.tag_name() == Some(tag_name) {
1003            references.push((node, aid, link));
1004        }
1005    }
1006}