1use 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 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 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 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 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 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 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 if ignore_ids && aid == AId::Id {
259 continue;
260 }
261
262 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 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 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 let idx = doc.attrs[attrs_start_idx..]
311 .iter_mut()
312 .position(|a| a.name == aid);
313
314 let added = append_attribute(parent_id, tag_name, aid, value, important, doc);
316
317 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 let has_precedence = !doc.attrs[existing_idx].important;
339
340 if has_precedence {
341 doc.attrs.swap(existing_idx, last_idx);
342 }
343
344 doc.attrs.pop();
346 }
347 }
348 };
349
350 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 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 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 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 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 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 AId::Style |
478 AId::Class => return false,
480 _ => {}
481 }
482
483 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 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 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 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 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 if parse_tag_name(link).is_none() {
641 return Ok(());
642 }
643
644 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
696fn 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 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 _ => false, }
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 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(¤t.id) {
835 break node.document().get(*id);
836 }
837
838 if current.has_children() {
839 break current;
840 }
841
842 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
861fn references<'a, 'input: 'a>(node: SvgNode<'a, 'input>) -> Vec<Reference<'a, 'input>> {
864 let mut references = Vec::new();
865 match node.tag_name() {
866 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 _ => {
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
906fn 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 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 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 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}