Skip to main content

usvg/parser/svgtree/
mod.rs

1// Copyright 2021 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::collections::{HashMap, HashSet};
5use std::num::NonZeroU32;
6use std::str::FromStr;
7
8#[rustfmt::skip] mod names;
9mod parse;
10mod text;
11
12use tiny_skia_path::Transform;
13
14use crate::{
15    BlendMode, ImageRendering, Opacity, ShapeRendering, SpreadMethod, TextRendering, Units,
16    Visibility,
17};
18pub use names::{AId, EId};
19
20/// An SVG tree container.
21///
22/// Contains only element and text nodes.
23/// Text nodes are present only inside the `text` element.
24pub struct Document<'input> {
25    nodes: Vec<NodeData>,
26    attrs: Vec<Attribute<'input>>,
27    links: HashMap<String, NodeId>,
28    // Keyed by the element that uses a reference rather than the one that sets it, so that an
29    // inherited reference stays valid outside the cycle it closes.
30    circular_references: HashSet<(NodeId, AId)>,
31}
32
33impl<'input> Document<'input> {
34    /// Returns the root node.
35    #[inline]
36    pub fn root<'a>(&'a self) -> SvgNode<'a, 'input> {
37        SvgNode {
38            id: NodeId::new(0),
39            d: &self.nodes[0],
40            doc: self,
41        }
42    }
43
44    /// Returns the root element.
45    #[inline]
46    pub fn root_element<'a>(&'a self) -> SvgNode<'a, 'input> {
47        // `unwrap` is safe, because `Document` is guarantee to have at least one element.
48        self.root().first_element_child().unwrap()
49    }
50
51    /// Returns an iterator over document's descendant nodes.
52    ///
53    /// Shorthand for `doc.root().descendants()`.
54    #[inline]
55    pub fn descendants<'a>(&'a self) -> Descendants<'a, 'input> {
56        self.root().descendants()
57    }
58
59    /// Returns an element by ID.
60    ///
61    /// Unlike the [`Descendants`] iterator, this is just a HashMap lookup.
62    /// Meaning it's way faster.
63    #[inline]
64    pub fn element_by_id<'a>(&'a self, id: &str) -> Option<SvgNode<'a, 'input>> {
65        let node_id = self.links.get(id)?;
66        Some(self.get(*node_id))
67    }
68
69    #[inline]
70    fn get<'a>(&'a self, id: NodeId) -> SvgNode<'a, 'input> {
71        SvgNode {
72            id,
73            d: &self.nodes[id.get_usize()],
74            doc: self,
75        }
76    }
77}
78
79impl std::fmt::Debug for Document<'_> {
80    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
81        if !self.root().has_children() {
82            return write!(f, "Document []");
83        }
84
85        macro_rules! writeln_indented {
86            ($depth:expr, $f:expr, $fmt:expr) => {
87                for _ in 0..$depth { write!($f, "    ")?; }
88                writeln!($f, $fmt)?;
89            };
90            ($depth:expr, $f:expr, $fmt:expr, $($arg:tt)*) => {
91                for _ in 0..$depth { write!($f, "    ")?; }
92                writeln!($f, $fmt, $($arg)*)?;
93            };
94        }
95
96        fn print_children(
97            parent: SvgNode,
98            depth: usize,
99            f: &mut std::fmt::Formatter,
100        ) -> Result<(), std::fmt::Error> {
101            for child in parent.children() {
102                if child.is_element() {
103                    writeln_indented!(depth, f, "Element {{");
104                    writeln_indented!(depth, f, "    tag_name: {:?}", child.tag_name());
105
106                    if !child.attributes().is_empty() {
107                        writeln_indented!(depth + 1, f, "attributes: [");
108                        for attr in child.attributes() {
109                            writeln_indented!(depth + 2, f, "{:?}", attr);
110                        }
111                        writeln_indented!(depth + 1, f, "]");
112                    }
113
114                    if child.has_children() {
115                        writeln_indented!(depth, f, "    children: [");
116                        print_children(child, depth + 2, f)?;
117                        writeln_indented!(depth, f, "    ]");
118                    }
119
120                    writeln_indented!(depth, f, "}}");
121                } else {
122                    writeln_indented!(depth, f, "{:?}", child);
123                }
124            }
125
126            Ok(())
127        }
128
129        writeln!(f, "Document [")?;
130        print_children(self.root(), 1, f)?;
131        writeln!(f, "]")?;
132
133        Ok(())
134    }
135}
136
137#[derive(Clone, Copy, Debug)]
138pub(crate) struct ShortRange {
139    start: u32,
140    end: u32,
141}
142
143impl ShortRange {
144    #[inline]
145    fn new(start: u32, end: u32) -> Self {
146        ShortRange { start, end }
147    }
148
149    #[inline]
150    fn to_urange(self) -> std::ops::Range<usize> {
151        self.start as usize..self.end as usize
152    }
153}
154
155#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
156pub(crate) struct NodeId(NonZeroU32);
157
158impl NodeId {
159    #[inline]
160    fn new(id: u32) -> Self {
161        debug_assert!(id < u32::MAX);
162
163        // We are using `NonZeroU32` to reduce overhead of `Option<NodeId>`.
164        NodeId(NonZeroU32::new(id + 1).unwrap())
165    }
166
167    #[inline]
168    fn get(self) -> u32 {
169        self.0.get() - 1
170    }
171
172    #[inline]
173    fn get_usize(self) -> usize {
174        self.get() as usize
175    }
176}
177
178impl From<usize> for NodeId {
179    #[inline]
180    fn from(id: usize) -> Self {
181        // We already checked that `id` is limited by u32::MAX.
182        debug_assert!(id <= u32::MAX as usize);
183        NodeId::new(id as u32)
184    }
185}
186
187pub(crate) enum NodeKind {
188    Root,
189    Element {
190        tag_name: EId,
191        attributes: ShortRange,
192    },
193    Text(String),
194}
195
196struct NodeData {
197    parent: Option<NodeId>,
198    next_sibling: Option<NodeId>,
199    children: Option<(NodeId, NodeId)>,
200    kind: NodeKind,
201}
202
203/// An attribute.
204#[derive(Clone)]
205pub struct Attribute<'input> {
206    /// Attribute's name.
207    pub name: AId,
208    /// Attribute's value.
209    pub value: roxmltree::StringStorage<'input>,
210    /// Attribute's importance
211    pub important: bool,
212}
213
214impl std::fmt::Debug for Attribute<'_> {
215    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
216        write!(
217            f,
218            "Attribute {{ name: {:?}, value: {}, important: {} }}",
219            self.name, self.value, self.important
220        )
221    }
222}
223
224/// An SVG node.
225#[derive(Clone, Copy)]
226pub struct SvgNode<'a, 'input: 'a> {
227    id: NodeId,
228    doc: &'a Document<'input>,
229    d: &'a NodeData,
230}
231
232impl Eq for SvgNode<'_, '_> {}
233
234impl PartialEq for SvgNode<'_, '_> {
235    #[inline]
236    fn eq(&self, other: &Self) -> bool {
237        self.id == other.id && std::ptr::eq(self.doc, other.doc) && std::ptr::eq(self.d, other.d)
238    }
239}
240
241impl<'a, 'input: 'a> SvgNode<'a, 'input> {
242    #[inline]
243    fn id(&self) -> NodeId {
244        self.id
245    }
246
247    /// Checks if the current node is an element.
248    #[inline]
249    pub fn is_element(&self) -> bool {
250        matches!(self.d.kind, NodeKind::Element { .. })
251    }
252
253    /// Checks if the current node is a text.
254    #[inline]
255    pub fn is_text(&self) -> bool {
256        matches!(self.d.kind, NodeKind::Text(_))
257    }
258
259    /// Returns node's document.
260    #[inline]
261    pub fn document(&self) -> &'a Document<'input> {
262        self.doc
263    }
264
265    /// Returns element's tag name, unless the current node is text.
266    #[inline]
267    pub fn tag_name(&self) -> Option<EId> {
268        match self.d.kind {
269            NodeKind::Element { tag_name, .. } => Some(tag_name),
270            _ => None,
271        }
272    }
273    /// Returns element's `id` attribute value.
274    ///
275    /// Returns an empty string otherwise.
276    #[inline]
277    pub fn element_id(&self) -> &'a str {
278        self.attribute(AId::Id).unwrap_or("")
279    }
280
281    /// Returns an attribute value.
282    pub fn attribute<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {
283        if self.has_circular_reference(aid) {
284            return None;
285        }
286
287        self.attribute_impl(aid)
288    }
289
290    fn attribute_impl<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {
291        let value = self
292            .attributes()
293            .iter()
294            .find(|a| a.name == aid)
295            .map(|a| a.value.as_str())?;
296        // These AId have an initial value of none
297        let is_possible_none = matches!(
298            aid,
299            AId::Mask
300                | AId::MarkerStart
301                | AId::MarkerMid
302                | AId::MarkerEnd
303                | AId::ClipPath
304                | AId::Filter
305                | AId::FontSizeAdjust
306                | AId::TextDecoration
307                | AId::Stroke
308                | AId::StrokeDasharray
309        );
310        if is_possible_none && value == "none" {
311            return None;
312        }
313        match T::parse(*self, aid, value) {
314            Some(v) => Some(v),
315            None => {
316                // TODO: show position in XML
317                log::warn!("Failed to parse {} value: '{}'.", aid, value);
318                None
319            }
320        }
321    }
322
323    /// Returns an attribute value.
324    ///
325    /// Same as `SvgNode::attribute`, but doesn't show a warning.
326    pub fn try_attribute<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {
327        if self.has_circular_reference(aid) {
328            return None;
329        }
330
331        let value = self
332            .attributes()
333            .iter()
334            .find(|a| a.name == aid)
335            .map(|a| a.value.as_str())?;
336        T::parse(*self, aid, value)
337    }
338
339    #[inline]
340    fn has_circular_reference(&self, aid: AId) -> bool {
341        self.doc.circular_references.contains(&(self.id, aid))
342    }
343
344    #[inline]
345    fn node_attribute(&self, aid: AId) -> Option<SvgNode<'a, 'input>> {
346        let value = self.attribute(aid)?;
347        let id = if aid == AId::Href {
348            svgtypes::IRI::from_str(value).ok().map(|v| v.0)
349        } else {
350            svgtypes::FuncIRI::from_str(value).ok().map(|v| v.0)
351        }?;
352
353        self.document().element_by_id(id)
354    }
355
356    /// Checks if an attribute is present.
357    #[inline]
358    pub fn has_attribute(&self, aid: AId) -> bool {
359        self.attributes().iter().any(|a| a.name == aid)
360    }
361
362    /// Returns a list of all element's attributes.
363    #[inline]
364    pub fn attributes(&self) -> &'a [Attribute<'input>] {
365        match self.d.kind {
366            NodeKind::Element { ref attributes, .. } => &self.doc.attrs[attributes.to_urange()],
367            _ => &[],
368        }
369    }
370
371    /// Finds a [`Node`] that contains the required attribute.
372    ///
373    /// For inheritable attributes walks over ancestors until a node with
374    /// the specified attribute is found.
375    ///
376    /// For non-inheritable attributes checks only the current node and the parent one.
377    /// As per SVG spec.
378    pub fn find_attribute<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {
379        if self.has_circular_reference(aid) {
380            return None;
381        }
382
383        // A circular reference on the declaring element doesn't apply to the ones inheriting it,
384        // which are checked on their own.
385        self.find_attribute_impl(aid)?.attribute_impl(aid)
386    }
387
388    fn find_attribute_impl(&self, aid: AId) -> Option<SvgNode<'a, 'input>> {
389        if aid.is_inheritable() {
390            for n in self.ancestors() {
391                if n.has_attribute(aid) {
392                    return Some(n);
393                }
394            }
395
396            None
397        } else {
398            if self.has_attribute(aid) {
399                Some(*self)
400            } else {
401                // Non-inheritable attributes can inherit a value only from a direct parent.
402                let n = self.parent_element()?;
403                if n.has_attribute(aid) { Some(n) } else { None }
404            }
405        }
406    }
407
408    /// Returns node's text data.
409    ///
410    /// For text nodes returns its content. For elements returns the first child node text.
411    #[inline]
412    pub fn text(&self) -> &'a str {
413        match self.d.kind {
414            NodeKind::Element { .. } => match self.first_child() {
415                Some(child) if child.is_text() => match self.doc.nodes[child.id.get_usize()].kind {
416                    NodeKind::Text(ref text) => text,
417                    _ => "",
418                },
419                _ => "",
420            },
421            NodeKind::Text(ref text) => text,
422            _ => "",
423        }
424    }
425
426    /// Returns a parent node.
427    #[inline]
428    pub fn parent(&self) -> Option<Self> {
429        self.d.parent.map(|id| self.doc.get(id))
430    }
431
432    /// Returns the parent element.
433    #[inline]
434    pub fn parent_element(&self) -> Option<Self> {
435        self.ancestors().skip(1).find(|n| n.is_element())
436    }
437
438    /// Returns the next sibling.
439    #[inline]
440    pub fn next_sibling(&self) -> Option<Self> {
441        self.d.next_sibling.map(|id| self.doc.get(id))
442    }
443
444    /// Returns the first child.
445    #[inline]
446    pub fn first_child(&self) -> Option<Self> {
447        self.d.children.map(|(id, _)| self.doc.get(id))
448    }
449
450    /// Returns the first child element.
451    #[inline]
452    pub fn first_element_child(&self) -> Option<Self> {
453        self.children().find(|n| n.is_element())
454    }
455
456    /// Returns the last child.
457    #[inline]
458    pub fn last_child(&self) -> Option<Self> {
459        self.d.children.map(|(_, id)| self.doc.get(id))
460    }
461
462    /// Checks if the node has child nodes.
463    #[inline]
464    pub fn has_children(&self) -> bool {
465        self.d.children.is_some()
466    }
467
468    /// Returns an iterator over ancestor nodes starting at this node.
469    #[inline]
470    pub fn ancestors(&self) -> Ancestors<'a, 'input> {
471        Ancestors(Some(*self))
472    }
473
474    /// Returns an iterator over children nodes.
475    #[inline]
476    pub fn children(&self) -> Children<'a, 'input> {
477        Children {
478            front: self.first_child(),
479            back: self.last_child(),
480        }
481    }
482
483    /// Returns an iterator which traverses the subtree starting at this node.
484    #[inline]
485    fn traverse(&self) -> Traverse<'a, 'input> {
486        Traverse {
487            root: *self,
488            edge: None,
489        }
490    }
491
492    /// Returns an iterator over this node and its descendants.
493    #[inline]
494    pub fn descendants(&self) -> Descendants<'a, 'input> {
495        Descendants(self.traverse())
496    }
497
498    /// Returns an iterator over elements linked via `xlink:href`.
499    #[inline]
500    pub fn href_iter(&self) -> HrefIter<'a, 'input> {
501        HrefIter {
502            doc: self.document(),
503            origin: self.id(),
504            curr: self.id(),
505            is_first: true,
506            is_finished: false,
507            visited: VisitedLinks::new(self.id()),
508        }
509    }
510}
511
512impl std::fmt::Debug for SvgNode<'_, '_> {
513    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
514        match self.d.kind {
515            NodeKind::Root => write!(f, "Root"),
516            NodeKind::Element { .. } => {
517                write!(
518                    f,
519                    "Element {{ tag_name: {:?}, attributes: {:?} }}",
520                    self.tag_name(),
521                    self.attributes()
522                )
523            }
524            NodeKind::Text(ref text) => write!(f, "Text({:?})", text),
525        }
526    }
527}
528
529/// An iterator over ancestor nodes.
530#[derive(Clone, Debug)]
531pub struct Ancestors<'a, 'input: 'a>(Option<SvgNode<'a, 'input>>);
532
533impl<'a, 'input: 'a> Iterator for Ancestors<'a, 'input> {
534    type Item = SvgNode<'a, 'input>;
535
536    #[inline]
537    fn next(&mut self) -> Option<Self::Item> {
538        let node = self.0.take();
539        self.0 = node.as_ref().and_then(SvgNode::parent);
540        node
541    }
542}
543
544/// An iterator over children nodes.
545#[derive(Clone, Debug)]
546pub struct Children<'a, 'input: 'a> {
547    front: Option<SvgNode<'a, 'input>>,
548    back: Option<SvgNode<'a, 'input>>,
549}
550
551impl<'a, 'input: 'a> Iterator for Children<'a, 'input> {
552    type Item = SvgNode<'a, 'input>;
553
554    fn next(&mut self) -> Option<Self::Item> {
555        let node = self.front.take();
556        if self.front == self.back {
557            self.back = None;
558        } else {
559            self.front = node.as_ref().and_then(SvgNode::next_sibling);
560        }
561        node
562    }
563}
564
565#[derive(Clone, Copy, PartialEq, Debug)]
566enum Edge<'a, 'input: 'a> {
567    Open(SvgNode<'a, 'input>),
568    Close(SvgNode<'a, 'input>),
569}
570
571#[derive(Clone, Debug)]
572struct Traverse<'a, 'input: 'a> {
573    root: SvgNode<'a, 'input>,
574    edge: Option<Edge<'a, 'input>>,
575}
576
577impl<'a, 'input: 'a> Iterator for Traverse<'a, 'input> {
578    type Item = Edge<'a, 'input>;
579
580    fn next(&mut self) -> Option<Self::Item> {
581        match self.edge {
582            Some(Edge::Open(node)) => {
583                self.edge = Some(match node.first_child() {
584                    Some(first_child) => Edge::Open(first_child),
585                    None => Edge::Close(node),
586                });
587            }
588            Some(Edge::Close(node)) => {
589                if node == self.root {
590                    self.edge = None;
591                } else if let Some(next_sibling) = node.next_sibling() {
592                    self.edge = Some(Edge::Open(next_sibling));
593                } else {
594                    self.edge = node.parent().map(Edge::Close);
595                }
596            }
597            None => {
598                self.edge = Some(Edge::Open(self.root));
599            }
600        }
601
602        self.edge
603    }
604}
605
606/// A descendants iterator.
607#[derive(Clone, Debug)]
608pub struct Descendants<'a, 'input: 'a>(Traverse<'a, 'input>);
609
610impl<'a, 'input: 'a> Iterator for Descendants<'a, 'input> {
611    type Item = SvgNode<'a, 'input>;
612
613    #[inline]
614    fn next(&mut self) -> Option<Self::Item> {
615        for edge in &mut self.0 {
616            if let Edge::Open(node) = edge {
617                return Some(node);
618            }
619        }
620
621        None
622    }
623}
624
625/// The elements an `xlink:href` chain has visited so far.
626#[derive(Clone, Debug)]
627enum VisitedLinks {
628    Inline([Option<NodeId>; 4]),
629    Heap(HashSet<NodeId>),
630}
631
632impl VisitedLinks {
633    fn new(id: NodeId) -> Self {
634        VisitedLinks::Inline([Some(id), None, None, None])
635    }
636
637    /// Returns `false` if `id` was already visited.
638    fn insert(&mut self, id: NodeId) -> bool {
639        match self {
640            VisitedLinks::Inline(ids) => {
641                if ids.contains(&Some(id)) {
642                    return false;
643                }
644
645                if let Some(slot) = ids.iter_mut().find(|slot| slot.is_none()) {
646                    *slot = Some(id);
647                } else {
648                    let mut set: HashSet<NodeId> = ids.iter().flatten().copied().collect();
649                    set.insert(id);
650                    *self = VisitedLinks::Heap(set);
651                }
652
653                true
654            }
655            VisitedLinks::Heap(set) => set.insert(id),
656        }
657    }
658}
659
660/// An iterator over `xlink:href` references.
661#[derive(Clone, Debug)]
662pub struct HrefIter<'a, 'input: 'a> {
663    doc: &'a Document<'input>,
664    origin: NodeId,
665    curr: NodeId,
666    is_first: bool,
667    is_finished: bool,
668    visited: VisitedLinks,
669}
670
671impl<'a, 'input: 'a> Iterator for HrefIter<'a, 'input> {
672    type Item = SvgNode<'a, 'input>;
673
674    fn next(&mut self) -> Option<Self::Item> {
675        if self.is_finished {
676            return None;
677        }
678
679        if self.is_first {
680            self.is_first = false;
681            return Some(self.doc.get(self.curr));
682        }
683
684        if let Some(link) = self.doc.get(self.curr).node_attribute(AId::Href) {
685            if !self.visited.insert(link.id()) {
686                log::warn!(
687                    "Element '#{}' has a circular 'xlink:href' reference.",
688                    self.doc.get(self.origin).element_id()
689                );
690                self.is_finished = true;
691                return None;
692            }
693
694            self.curr = link.id();
695            Some(link)
696        } else {
697            None
698        }
699    }
700}
701
702impl EId {
703    /// Checks if this is a
704    /// [graphics element](https://www.w3.org/TR/SVG11/intro.html#TermGraphicsElement).
705    pub fn is_graphic(&self) -> bool {
706        matches!(
707            self,
708            EId::Circle
709                | EId::Ellipse
710                | EId::Image
711                | EId::Line
712                | EId::Path
713                | EId::Polygon
714                | EId::Polyline
715                | EId::Rect
716                | EId::Text
717                | EId::Use
718        )
719    }
720
721    /// Checks if this is a
722    /// [gradient element](https://www.w3.org/TR/SVG11/intro.html#TermGradientElement).
723    pub fn is_gradient(&self) -> bool {
724        matches!(self, EId::LinearGradient | EId::RadialGradient)
725    }
726
727    /// Checks if this is a
728    /// [paint server element](https://www.w3.org/TR/SVG11/intro.html#TermPaint).
729    pub fn is_paint_server(&self) -> bool {
730        matches!(
731            self,
732            EId::LinearGradient | EId::RadialGradient | EId::Pattern
733        )
734    }
735}
736
737impl AId {
738    fn is_presentation(&self) -> bool {
739        matches!(
740            self,
741            AId::AlignmentBaseline
742                | AId::BaselineShift
743                | AId::BackgroundColor // non-standard SVG attribute
744                | AId::ClipPath
745                | AId::ClipRule
746                | AId::Color
747                | AId::ColorInterpolation
748                | AId::ColorInterpolationFilters
749                | AId::ColorRendering
750                | AId::Direction
751                | AId::Display
752                | AId::DominantBaseline
753                | AId::Fill
754                | AId::FillOpacity
755                | AId::FillRule
756                | AId::Filter
757                | AId::FloodColor
758                | AId::FloodOpacity
759                | AId::FontFamily
760                | AId::FontKerning // technically not presentation
761                | AId::FontOpticalSizing // technically not presentation
762                | AId::FontSize
763                | AId::FontSizeAdjust
764                | AId::FontStretch
765                | AId::FontStyle
766                | AId::FontVariant
767                | AId::FontWeight
768                | AId::FontVariationSettings
769                | AId::GlyphOrientationHorizontal
770                | AId::GlyphOrientationVertical
771                | AId::ImageRendering
772                | AId::Isolation // technically not presentation
773                | AId::LetterSpacing
774                | AId::LightingColor
775                | AId::MarkerEnd
776                | AId::MarkerMid
777                | AId::MarkerStart
778                | AId::Mask
779                | AId::MaskType
780                | AId::MixBlendMode // technically not presentation
781                | AId::Opacity
782                | AId::Overflow
783                | AId::PaintOrder
784                | AId::ShapeRendering
785                | AId::StopColor
786                | AId::StopOpacity
787                | AId::Stroke
788                | AId::StrokeDasharray
789                | AId::StrokeDashoffset
790                | AId::StrokeLinecap
791                | AId::StrokeLinejoin
792                | AId::StrokeMiterlimit
793                | AId::StrokeOpacity
794                | AId::StrokeWidth
795                | AId::TextAnchor
796                | AId::TextDecoration
797                | AId::TextOverflow
798                | AId::TextRendering
799                | AId::Transform
800                | AId::TransformOrigin
801                | AId::UnicodeBidi
802                | AId::VectorEffect
803                | AId::Visibility
804                | AId::WhiteSpace
805                | AId::WordSpacing
806                | AId::WritingMode
807        )
808    }
809
810    /// Checks if the current attribute is inheritable.
811    fn is_inheritable(&self) -> bool {
812        if self.is_presentation() {
813            !is_non_inheritable(*self)
814        } else {
815            false
816        }
817    }
818
819    fn allows_inherit_value(&self) -> bool {
820        matches!(
821            self,
822            AId::AlignmentBaseline
823                | AId::BaselineShift
824                | AId::ClipPath
825                | AId::ClipRule
826                | AId::Color
827                | AId::ColorInterpolationFilters
828                | AId::Direction
829                | AId::Display
830                | AId::DominantBaseline
831                | AId::Fill
832                | AId::FillOpacity
833                | AId::FillRule
834                | AId::Filter
835                | AId::FloodColor
836                | AId::FloodOpacity
837                | AId::FontFamily
838                | AId::FontKerning
839                | AId::FontOpticalSizing
840                | AId::FontSize
841                | AId::FontStretch
842                | AId::FontStyle
843                | AId::FontVariant
844                | AId::FontWeight
845                | AId::ImageRendering
846                | AId::Kerning
847                | AId::LetterSpacing
848                | AId::MarkerEnd
849                | AId::MarkerMid
850                | AId::MarkerStart
851                | AId::Mask
852                | AId::Opacity
853                | AId::Overflow
854                | AId::ShapeRendering
855                | AId::StopColor
856                | AId::StopOpacity
857                | AId::Stroke
858                | AId::StrokeDasharray
859                | AId::StrokeDashoffset
860                | AId::StrokeLinecap
861                | AId::StrokeLinejoin
862                | AId::StrokeMiterlimit
863                | AId::StrokeOpacity
864                | AId::StrokeWidth
865                | AId::TextAnchor
866                | AId::TextDecoration
867                | AId::TextRendering
868                | AId::Visibility
869                | AId::WordSpacing
870                | AId::WritingMode
871        )
872    }
873}
874
875fn is_non_inheritable(id: AId) -> bool {
876    matches!(
877        id,
878        AId::AlignmentBaseline
879            | AId::BaselineShift
880            | AId::ClipPath
881            | AId::Display
882            | AId::Filter
883            | AId::FloodColor
884            | AId::FloodOpacity
885            | AId::Mask
886            | AId::Opacity
887            | AId::Overflow
888            | AId::LightingColor
889            | AId::StopColor
890            | AId::StopOpacity
891            | AId::TextDecoration
892            | AId::Transform
893            | AId::TransformOrigin
894    )
895}
896
897// TODO: is there a way yo make it less ugly? Too many lifetimes.
898/// A trait for parsing attribute values.
899pub trait FromValue<'a, 'input: 'a>: Sized {
900    /// Parses an attribute value.
901    ///
902    /// When `None` is returned, the attribute value will be logged as a parsing failure.
903    fn parse(node: SvgNode<'a, 'input>, aid: AId, value: &'a str) -> Option<Self>;
904}
905
906impl<'a, 'input: 'a> FromValue<'a, 'input> for &'a str {
907    fn parse(_: SvgNode<'a, 'input>, _: AId, value: &'a str) -> Option<Self> {
908        Some(value)
909    }
910}
911
912impl<'a, 'input: 'a> FromValue<'a, 'input> for f32 {
913    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
914        svgtypes::Number::from_str(value).ok().map(|v| v.0 as f32)
915    }
916}
917
918impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Length {
919    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
920        svgtypes::Length::from_str(value).ok()
921    }
922}
923
924// TODO: to svgtypes?
925impl<'a, 'input: 'a> FromValue<'a, 'input> for Opacity {
926    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
927        let length = svgtypes::Length::from_str(value).ok()?;
928        if length.unit == svgtypes::LengthUnit::Percent {
929            Some(Opacity::new_clamped(length.number as f32 / 100.0))
930        } else if length.unit == svgtypes::LengthUnit::None {
931            Some(Opacity::new_clamped(length.number as f32))
932        } else {
933            None
934        }
935    }
936}
937
938impl<'a, 'input: 'a> FromValue<'a, 'input> for Transform {
939    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
940        let ts = match svgtypes::Transform::from_str(value) {
941            Ok(v) => v,
942            Err(_) => return None,
943        };
944
945        let ts = Transform::from_row(
946            ts.a as f32,
947            ts.b as f32,
948            ts.c as f32,
949            ts.d as f32,
950            ts.e as f32,
951            ts.f as f32,
952        );
953
954        if ts.is_valid() {
955            Some(ts)
956        } else {
957            Some(Transform::default())
958        }
959    }
960}
961
962impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::TransformOrigin {
963    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
964        Self::from_str(value).ok()
965    }
966}
967
968impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::ViewBox {
969    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
970        Self::from_str(value).ok()
971    }
972}
973
974impl<'a, 'input: 'a> FromValue<'a, 'input> for Units {
975    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
976        match value {
977            "userSpaceOnUse" => Some(Units::UserSpaceOnUse),
978            "objectBoundingBox" => Some(Units::ObjectBoundingBox),
979            _ => None,
980        }
981    }
982}
983
984impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::AspectRatio {
985    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
986        Self::from_str(value).ok()
987    }
988}
989
990impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::PaintOrder {
991    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
992        Self::from_str(value).ok()
993    }
994}
995
996impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Color {
997    fn parse(node: SvgNode, aid: AId, value: &str) -> Option<Self> {
998        // TODO: Let svgtypes parse `currentColor` as part of a `<color>` type that `Paint` and
999        // `drop-shadow()` can share, instead of matching the keyword in several places.
1000        if value != "currentColor" {
1001            return Self::from_str(value).ok();
1002        }
1003
1004        // In `color`, `currentColor` resolves to the inherited value.
1005        let color = if aid == AId::Color {
1006            node.parent_element()
1007                .and_then(|parent| parent.find_attribute(AId::Color))
1008        } else {
1009            node.find_attribute(AId::Color)
1010        };
1011
1012        Some(color.unwrap_or_else(Self::black))
1013    }
1014}
1015
1016impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Angle {
1017    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1018        Self::from_str(value).ok()
1019    }
1020}
1021
1022impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::EnableBackground {
1023    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1024        Self::from_str(value).ok()
1025    }
1026}
1027
1028impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Paint<'a> {
1029    fn parse(_: SvgNode, _: AId, value: &'a str) -> Option<Self> {
1030        Self::from_str(value).ok()
1031    }
1032}
1033
1034impl<'a, 'input: 'a> FromValue<'a, 'input> for Vec<f32> {
1035    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1036        let mut list = Vec::new();
1037        for n in svgtypes::NumberListParser::from(value) {
1038            list.push(n.ok()? as f32);
1039        }
1040
1041        Some(list)
1042    }
1043}
1044
1045impl<'a, 'input: 'a> FromValue<'a, 'input> for Vec<svgtypes::Length> {
1046    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1047        let mut list = Vec::new();
1048        for n in svgtypes::LengthListParser::from(value) {
1049            list.push(n.ok()?);
1050        }
1051
1052        Some(list)
1053    }
1054}
1055
1056impl<'a, 'input: 'a> FromValue<'a, 'input> for Visibility {
1057    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1058        match value {
1059            "visible" => Some(Visibility::Visible),
1060            "hidden" => Some(Visibility::Hidden),
1061            "collapse" => Some(Visibility::Collapse),
1062            _ => None,
1063        }
1064    }
1065}
1066
1067impl<'a, 'input: 'a> FromValue<'a, 'input> for SpreadMethod {
1068    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1069        match value {
1070            "pad" => Some(SpreadMethod::Pad),
1071            "reflect" => Some(SpreadMethod::Reflect),
1072            "repeat" => Some(SpreadMethod::Repeat),
1073            _ => None,
1074        }
1075    }
1076}
1077
1078impl<'a, 'input: 'a> FromValue<'a, 'input> for ShapeRendering {
1079    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1080        match value {
1081            "optimizeSpeed" => Some(ShapeRendering::OptimizeSpeed),
1082            "crispEdges" => Some(ShapeRendering::CrispEdges),
1083            "auto" | "geometricPrecision" => Some(ShapeRendering::GeometricPrecision),
1084            _ => None,
1085        }
1086    }
1087}
1088
1089impl<'a, 'input: 'a> FromValue<'a, 'input> for TextRendering {
1090    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1091        match value {
1092            "optimizeSpeed" => Some(TextRendering::OptimizeSpeed),
1093            "auto" | "optimizeLegibility" => Some(TextRendering::OptimizeLegibility),
1094            "geometricPrecision" => Some(TextRendering::GeometricPrecision),
1095            _ => None,
1096        }
1097    }
1098}
1099
1100impl<'a, 'input: 'a> FromValue<'a, 'input> for ImageRendering {
1101    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
1102        match value {
1103            "auto" | "optimizeQuality" => Some(ImageRendering::OptimizeQuality),
1104            "optimizeSpeed" => Some(ImageRendering::OptimizeSpeed),
1105            "smooth" => Some(ImageRendering::Smooth),
1106            "high-quality" => Some(ImageRendering::HighQuality),
1107            "crisp-edges" => Some(ImageRendering::CrispEdges),
1108            "pixelated" => Some(ImageRendering::Pixelated),
1109            _ => None,
1110        }
1111    }
1112}
1113
1114impl<'a, 'input: 'a> FromValue<'a, 'input> for BlendMode {
1115    fn parse(_: SvgNode, aid: AId, value: &str) -> Option<Self> {
1116        match value {
1117            "normal" => Some(BlendMode::Normal),
1118            "multiply" => Some(BlendMode::Multiply),
1119            "screen" => Some(BlendMode::Screen),
1120            "overlay" => Some(BlendMode::Overlay),
1121            "darken" => Some(BlendMode::Darken),
1122            "lighten" => Some(BlendMode::Lighten),
1123            "color-dodge" => Some(BlendMode::ColorDodge),
1124            "color-burn" => Some(BlendMode::ColorBurn),
1125            "hard-light" => Some(BlendMode::HardLight),
1126            "soft-light" => Some(BlendMode::SoftLight),
1127            "difference" => Some(BlendMode::Difference),
1128            "exclusion" => Some(BlendMode::Exclusion),
1129            "hue" => Some(BlendMode::Hue),
1130            "saturation" => Some(BlendMode::Saturation),
1131            "color" => Some(BlendMode::Color),
1132            "luminosity" => Some(BlendMode::Luminosity),
1133            "plus-lighter" if aid == AId::MixBlendMode => Some(BlendMode::PlusLighter),
1134            _ => None,
1135        }
1136    }
1137}
1138
1139impl<'a, 'input: 'a> FromValue<'a, 'input> for SvgNode<'a, 'input> {
1140    fn parse(node: SvgNode<'a, 'input>, aid: AId, value: &str) -> Option<Self> {
1141        let id = if aid == AId::Href {
1142            svgtypes::IRI::from_str(value).ok().map(|v| v.0)
1143        } else {
1144            svgtypes::FuncIRI::from_str(value).ok().map(|v| v.0)
1145        }?;
1146
1147        node.document().element_by_id(id)
1148    }
1149}