Skip to main content

usvg/parser/
style.rs

1// Copyright 2018 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use super::converter::{self, SvgColorExt};
5use super::paint_server;
6use super::svgtree::{AId, FromValue, SvgNode};
7use crate::tree::ContextElement;
8use crate::{
9    ApproxEqUlps, Color, Fill, FillRule, LineCap, LineJoin, Opacity, Paint, Stroke,
10    StrokeMiterlimit, Units,
11};
12
13impl<'a, 'input: 'a> FromValue<'a, 'input> for LineCap {
14    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
15        match value {
16            "butt" => Some(LineCap::Butt),
17            "round" => Some(LineCap::Round),
18            "square" => Some(LineCap::Square),
19            _ => None,
20        }
21    }
22}
23
24impl<'a, 'input: 'a> FromValue<'a, 'input> for LineJoin {
25    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
26        match value {
27            "miter" => Some(LineJoin::Miter),
28            "miter-clip" => Some(LineJoin::MiterClip),
29            "round" => Some(LineJoin::Round),
30            "bevel" => Some(LineJoin::Bevel),
31            _ => None,
32        }
33    }
34}
35
36impl<'a, 'input: 'a> FromValue<'a, 'input> for FillRule {
37    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
38        match value {
39            "nonzero" => Some(FillRule::NonZero),
40            "evenodd" => Some(FillRule::EvenOdd),
41            _ => None,
42        }
43    }
44}
45
46pub(crate) fn resolve_fill(
47    node: SvgNode,
48    has_bbox: bool,
49    state: &converter::State,
50    cache: &mut converter::Cache,
51) -> Option<Fill> {
52    if state.parent_clip_path.is_some() {
53        // A `clipPath` child can be filled only with a black color.
54        return Some(Fill {
55            paint: Paint::Color(Color::black()),
56            opacity: Opacity::ONE,
57            rule: node.find_attribute(AId::ClipRule).unwrap_or_default(),
58            context_element: None,
59        });
60    }
61
62    let mut sub_opacity = Opacity::ONE;
63    let (paint, context_element) = if node.ancestors().any(|n| n.has_attribute(AId::Fill)) {
64        let value: &str = node.find_attribute(AId::Fill)?;
65        convert_paint(
66            node,
67            value,
68            AId::Fill,
69            has_bbox,
70            state,
71            &mut sub_opacity,
72            cache,
73        )?
74    } else {
75        (Paint::Color(Color::black()), None)
76    };
77
78    let fill_opacity = node
79        .find_attribute::<Opacity>(AId::FillOpacity)
80        .unwrap_or(Opacity::ONE);
81
82    Some(Fill {
83        paint,
84        opacity: sub_opacity * fill_opacity,
85        rule: node.find_attribute(AId::FillRule).unwrap_or_default(),
86        context_element,
87    })
88}
89
90pub(crate) fn resolve_stroke(
91    node: SvgNode,
92    has_bbox: bool,
93    state: &converter::State,
94    cache: &mut converter::Cache,
95) -> Option<Stroke> {
96    if state.parent_clip_path.is_some() {
97        // A `clipPath` child cannot be stroked.
98        return None;
99    }
100
101    let mut sub_opacity = Opacity::ONE;
102    let value: &str = node.find_attribute(AId::Stroke)?;
103    let (paint, context_element) = convert_paint(
104        node,
105        value,
106        AId::Stroke,
107        has_bbox,
108        state,
109        &mut sub_opacity,
110        cache,
111    )?;
112
113    let width = node.resolve_valid_length(AId::StrokeWidth, state, 1.0)?;
114
115    // Must be bigger than 1.
116    let miterlimit = node.find_attribute(AId::StrokeMiterlimit).unwrap_or(4.0);
117    let miterlimit = if miterlimit < 1.0 { 1.0 } else { miterlimit };
118    let miterlimit = StrokeMiterlimit::new(miterlimit);
119
120    let stroke_opacity = node
121        .find_attribute::<Opacity>(AId::StrokeOpacity)
122        .unwrap_or(Opacity::ONE);
123
124    let stroke = Stroke {
125        paint,
126        dasharray: conv_dasharray(node, state),
127        dashoffset: node.resolve_length(AId::StrokeDashoffset, state, 0.0),
128        miterlimit,
129        opacity: sub_opacity * stroke_opacity,
130        width,
131        linecap: node.find_attribute(AId::StrokeLinecap).unwrap_or_default(),
132        linejoin: node.find_attribute(AId::StrokeLinejoin).unwrap_or_default(),
133        context_element,
134    };
135
136    Some(stroke)
137}
138
139fn convert_paint(
140    node: SvgNode,
141    value: &str,
142    aid: AId,
143    has_bbox: bool,
144    state: &converter::State,
145    opacity: &mut Opacity,
146    cache: &mut converter::Cache,
147) -> Option<(Paint, Option<ContextElement>)> {
148    let paint = match svgtypes::Paint::from_str(value) {
149        Ok(v) => v,
150        Err(_) => {
151            if aid == AId::Fill {
152                log::warn!(
153                    "Failed to parse fill value: '{}'. Fallback to black.",
154                    value
155                );
156                svgtypes::Paint::Color(svgtypes::Color::black())
157            } else if aid == AId::Stroke {
158                log::warn!(
159                    "Failed to parse stroke value: '{}'. Fallback to no stroke.",
160                    value
161                );
162                return None;
163            } else {
164                return None;
165            }
166        }
167    };
168
169    match paint {
170        svgtypes::Paint::None => None,
171        svgtypes::Paint::Inherit => None, // already resolved by svgtree
172        svgtypes::Paint::ContextFill => state
173            .context_element
174            .clone()
175            .and_then(|(f, _)| f)
176            .map(|f| (f.paint, f.context_element)),
177        svgtypes::Paint::ContextStroke => state
178            .context_element
179            .clone()
180            .and_then(|(_, s)| s)
181            .map(|s| (s.paint, s.context_element)),
182        svgtypes::Paint::CurrentColor => {
183            let svg_color: svgtypes::Color = node
184                .find_attribute(AId::Color)
185                .unwrap_or_else(svgtypes::Color::black);
186            let (color, alpha) = svg_color.split_alpha();
187            *opacity = alpha;
188            Some((Paint::Color(color), None))
189        }
190        svgtypes::Paint::Color(svg_color) => {
191            let (color, alpha) = svg_color.split_alpha();
192            *opacity = alpha;
193            Some((Paint::Color(color), None))
194        }
195        svgtypes::Paint::FuncIRI(func_iri, fallback) => {
196            if let Some(link) = node.document().element_by_id(func_iri) {
197                let tag_name = link.tag_name().unwrap();
198                if tag_name.is_paint_server() {
199                    match paint_server::convert(link, state, cache) {
200                        Some(paint_server::ServerOrColor::Server(paint)) => {
201                            // We can use a paint server node with ObjectBoundingBox units
202                            // for painting only when the shape itself has a bbox.
203                            //
204                            // See SVG spec 7.11 for details.
205
206                            if !has_bbox && paint.units() == Units::ObjectBoundingBox {
207                                from_fallback(node, fallback, opacity).map(|p| (p, None))
208                            } else {
209                                Some((paint, None))
210                            }
211                        }
212                        Some(paint_server::ServerOrColor::Color { color, opacity: so }) => {
213                            *opacity = so;
214                            Some((Paint::Color(color), None))
215                        }
216                        None => from_fallback(node, fallback, opacity).map(|p| (p, None)),
217                    }
218                } else {
219                    log::warn!("'{}' cannot be used to {} a shape.", tag_name, aid);
220                    None
221                }
222            } else {
223                from_fallback(node, fallback, opacity).map(|p| (p, None))
224            }
225        }
226    }
227}
228
229fn from_fallback(
230    node: SvgNode,
231    fallback: Option<svgtypes::PaintFallback>,
232    opacity: &mut Opacity,
233) -> Option<Paint> {
234    match fallback? {
235        svgtypes::PaintFallback::None => None,
236        svgtypes::PaintFallback::CurrentColor => {
237            let svg_color: svgtypes::Color = node
238                .find_attribute(AId::Color)
239                .unwrap_or_else(svgtypes::Color::black);
240            let (color, alpha) = svg_color.split_alpha();
241            *opacity = alpha;
242            Some(Paint::Color(color))
243        }
244        svgtypes::PaintFallback::Color(svg_color) => {
245            let (color, alpha) = svg_color.split_alpha();
246            *opacity = alpha;
247            Some(Paint::Color(color))
248        }
249    }
250}
251
252// Prepare the 'stroke-dasharray' according to:
253// https://www.w3.org/TR/SVG11/painting.html#StrokeDasharrayProperty
254fn conv_dasharray(node: SvgNode, state: &converter::State) -> Option<Vec<f32>> {
255    let node = node
256        .ancestors()
257        .find(|n| n.has_attribute(AId::StrokeDasharray))?;
258    let list = super::units::convert_list(node, AId::StrokeDasharray, state)?;
259
260    // `A negative value is an error`
261    if list.iter().any(|n| n.is_sign_negative()) {
262        return None;
263    }
264
265    // `If the sum of the values is zero, then the stroke is rendered
266    // as if a value of none were specified.`
267    {
268        // no Iter::sum(), because of f64
269
270        let mut sum: f32 = 0.0;
271        for n in list.iter() {
272            sum += *n;
273        }
274
275        if sum.approx_eq_ulps(&0.0, 4) {
276            return None;
277        }
278    }
279
280    // `If an odd number of values is provided, then the list of values
281    // is repeated to yield an even number of values.`
282    if list.len() % 2 != 0 {
283        let mut tmp_list = list.clone();
284        tmp_list.extend_from_slice(&list);
285        return Some(tmp_list);
286    }
287
288    Some(list)
289}