Skip to main content

usvg/parser/
filter.rs

1// Copyright 2022 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! A collection of SVG filters.
5
6use std::collections::HashSet;
7use std::sync::Arc;
8
9use strict_num::PositiveF32;
10use svgtypes::{AspectRatio, Length, LengthUnit as Unit};
11
12use crate::{
13    ApproxZeroUlps, Color, Group, Node, NonEmptyString, NonZeroF32, NonZeroRect, Opacity, Size,
14    Transform, Units,
15    filter::{self, *},
16};
17
18use super::OptionLog;
19use super::converter::{self, SvgColorExt};
20use super::paint_server::{convert_units, resolve_number};
21use super::svgtree::{AId, EId, FromValue, SvgNode};
22
23impl<'a, 'input: 'a> FromValue<'a, 'input> for filter::ColorInterpolation {
24    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
25        match value {
26            "sRGB" => Some(filter::ColorInterpolation::SRGB),
27            "linearRGB" => Some(filter::ColorInterpolation::LinearRGB),
28            _ => None,
29        }
30    }
31}
32
33pub(crate) fn convert(
34    node: SvgNode,
35    state: &converter::State,
36    object_bbox: Option<NonZeroRect>,
37    cache: &mut converter::Cache,
38) -> Result<Vec<Arc<Filter>>, ()> {
39    let value = match node.attribute::<&str>(AId::Filter) {
40        Some(v) => v,
41        None => return Ok(Vec::new()),
42    };
43
44    let mut has_invalid_urls = false;
45    let mut filters = Vec::new();
46
47    let create_base_filter_func =
48        |kind, filters: &mut Vec<Arc<Filter>>, cache: &mut converter::Cache| {
49            // Filter functions, unlike `filter` elements, do not have a filter region.
50            // We're currently do not support an unlimited region, so we simply use a fairly large one.
51            // This if far from ideal, but good for now.
52            // TODO: Should be fixed eventually.
53            let mut rect = match kind {
54                Kind::DropShadow(_) | Kind::GaussianBlur(_) => {
55                    NonZeroRect::from_xywh(-0.5, -0.5, 2.0, 2.0).unwrap()
56                }
57                _ => NonZeroRect::from_xywh(-0.1, -0.1, 1.2, 1.2).unwrap(),
58            };
59
60            let object_bbox = match object_bbox {
61                Some(v) => v,
62                None => {
63                    log::warn!(
64                        "Filter '{}' has an invalid region. Skipped.",
65                        node.element_id()
66                    );
67                    return;
68                }
69            };
70
71            rect = rect.bbox_transform(object_bbox);
72
73            filters.push(Arc::new(Filter {
74                id: cache.gen_filter_id(),
75                rect,
76                primitives: vec![Primitive {
77                    rect,
78                    // Unlike `filter` elements, filter functions use sRGB colors by default.
79                    color_interpolation: ColorInterpolation::SRGB,
80                    result: "result".to_string(),
81                    kind,
82                }],
83            }));
84        };
85
86    for func in svgtypes::FilterValueListParser::from(value) {
87        let func = match func {
88            Ok(v) => v,
89            Err(e) => {
90                // Skip the whole attribute list on error.
91                log::warn!("Failed to parse a filter value cause {}. Skipping.", e);
92                return Ok(Vec::new());
93            }
94        };
95
96        match func {
97            svgtypes::FilterValue::Blur(std_dev) => create_base_filter_func(
98                convert_blur_function(node, std_dev, state),
99                &mut filters,
100                cache,
101            ),
102            svgtypes::FilterValue::DropShadow {
103                color,
104                dx,
105                dy,
106                std_dev,
107            } => create_base_filter_func(
108                convert_drop_shadow_function(node, color, dx, dy, std_dev, state),
109                &mut filters,
110                cache,
111            ),
112            svgtypes::FilterValue::Brightness(amount) => {
113                create_base_filter_func(convert_brightness_function(amount), &mut filters, cache);
114            }
115            svgtypes::FilterValue::Contrast(amount) => {
116                create_base_filter_func(convert_contrast_function(amount), &mut filters, cache);
117            }
118            svgtypes::FilterValue::Grayscale(amount) => {
119                create_base_filter_func(convert_grayscale_function(amount), &mut filters, cache);
120            }
121            svgtypes::FilterValue::HueRotate(angle) => {
122                create_base_filter_func(convert_hue_rotate_function(angle), &mut filters, cache);
123            }
124            svgtypes::FilterValue::Invert(amount) => {
125                create_base_filter_func(convert_invert_function(amount), &mut filters, cache);
126            }
127            svgtypes::FilterValue::Opacity(amount) => {
128                create_base_filter_func(convert_opacity_function(amount), &mut filters, cache);
129            }
130            svgtypes::FilterValue::Sepia(amount) => {
131                create_base_filter_func(convert_sepia_function(amount), &mut filters, cache);
132            }
133            svgtypes::FilterValue::Saturate(amount) => {
134                create_base_filter_func(convert_saturate_function(amount), &mut filters, cache);
135            }
136            svgtypes::FilterValue::Url(url) => {
137                if let Some(link) = node.document().element_by_id(url) {
138                    if let Ok(res) = convert_url(link, state, object_bbox, cache) {
139                        if let Some(f) = res {
140                            filters.push(f);
141                        }
142                    } else {
143                        has_invalid_urls = true;
144                    }
145                } else {
146                    has_invalid_urls = true;
147                }
148            }
149        }
150    }
151
152    // If a `filter` attribute had urls pointing to a missing elements
153    // and there are no valid filters at all - this is an error.
154    //
155    // Note that an invalid url is not an error in general.
156    if filters.is_empty() && has_invalid_urls {
157        return Err(());
158    }
159
160    Ok(filters)
161}
162
163fn convert_url(
164    node: SvgNode,
165    state: &converter::State,
166    object_bbox: Option<NonZeroRect>,
167    cache: &mut converter::Cache,
168) -> Result<Option<Arc<Filter>>, ()> {
169    let units = convert_units(node, AId::FilterUnits, Units::ObjectBoundingBox);
170    let primitive_units = convert_units(node, AId::PrimitiveUnits, Units::UserSpaceOnUse);
171
172    // Check if this element was already converted.
173    //
174    // Only `userSpaceOnUse` clipPaths can be shared,
175    // because `objectBoundingBox` one will be converted into user one
176    // and will become node-specific.
177    let cacheable = units == Units::UserSpaceOnUse && primitive_units == Units::UserSpaceOnUse;
178    if cacheable {
179        if let Some(filter) = cache.filters.get(node.element_id()) {
180            return Ok(Some(filter.clone()));
181        }
182    }
183
184    let rect = NonZeroRect::from_xywh(
185        resolve_number(
186            node,
187            AId::X,
188            units,
189            state,
190            Length::new(-10.0, Unit::Percent),
191        ),
192        resolve_number(
193            node,
194            AId::Y,
195            units,
196            state,
197            Length::new(-10.0, Unit::Percent),
198        ),
199        resolve_number(
200            node,
201            AId::Width,
202            units,
203            state,
204            Length::new(120.0, Unit::Percent),
205        ),
206        resolve_number(
207            node,
208            AId::Height,
209            units,
210            state,
211            Length::new(120.0, Unit::Percent),
212        ),
213    );
214
215    let mut rect = rect
216        .log_none(|| {
217            log::warn!(
218                "Filter '{}' has an invalid region. Skipped.",
219                node.element_id()
220            );
221        })
222        .ok_or(())?;
223
224    if units == Units::ObjectBoundingBox {
225        if let Some(object_bbox) = object_bbox {
226            rect = rect.bbox_transform(object_bbox);
227        } else {
228            log::warn!("Filters on zero-sized shapes are not allowed.");
229            return Err(());
230        }
231    }
232
233    let node_with_primitives = match find_filter_with_primitives(node) {
234        Some(v) => v,
235        None => return Err(()),
236    };
237    let primitives = collect_children(
238        &node_with_primitives,
239        primitive_units,
240        state,
241        object_bbox,
242        rect,
243        cache,
244    );
245    if primitives.is_empty() {
246        return Err(());
247    }
248
249    let mut id = NonEmptyString::new(node.element_id().to_string()).ok_or(())?;
250    // Generate ID only when we're parsing `objectBoundingBox` filter for the second time.
251    if !cacheable && cache.filters.contains_key(id.get()) {
252        id = cache.gen_filter_id();
253    }
254    let id_copy = id.get().to_string();
255
256    let filter = Arc::new(Filter {
257        id,
258        rect,
259        primitives,
260    });
261
262    cache.filters.insert(id_copy, filter.clone());
263
264    Ok(Some(filter))
265}
266
267fn find_filter_with_primitives<'a>(node: SvgNode<'a, 'a>) -> Option<SvgNode<'a, 'a>> {
268    for link in node.href_iter() {
269        if link.tag_name() != Some(EId::Filter) {
270            log::warn!(
271                "Filter '{}' cannot reference '{}' via 'xlink:href'.",
272                node.element_id(),
273                link.tag_name().unwrap()
274            );
275            return None;
276        }
277
278        if link.has_children() {
279            return Some(link);
280        }
281    }
282
283    None
284}
285
286struct FilterResults {
287    names: HashSet<String>,
288    idx: usize,
289}
290
291fn collect_children(
292    filter: &SvgNode,
293    units: Units,
294    state: &converter::State,
295    object_bbox: Option<NonZeroRect>,
296    filter_region: NonZeroRect,
297    cache: &mut converter::Cache,
298) -> Vec<Primitive> {
299    let mut primitives = Vec::new();
300
301    let mut results = FilterResults {
302        names: HashSet::new(),
303        idx: 1,
304    };
305
306    let scale = if units == Units::ObjectBoundingBox {
307        if let Some(object_bbox) = object_bbox {
308            object_bbox.size()
309        } else {
310            // No need to warn. Already checked.
311            return Vec::new();
312        }
313    } else {
314        Size::from_wh(1.0, 1.0).unwrap()
315    };
316
317    for child in filter.children() {
318        let tag_name = match child.tag_name() {
319            Some(v) => v,
320            None => continue,
321        };
322
323        let filter_subregion =
324            match resolve_primitive_region(child, units, state, object_bbox, filter_region) {
325                Some(v) => v,
326                None => break,
327            };
328
329        let kind =
330            match tag_name {
331                EId::FeDropShadow => convert_drop_shadow(child, scale, &primitives),
332                EId::FeGaussianBlur => convert_gaussian_blur(child, scale, &primitives),
333                EId::FeOffset => convert_offset(child, scale, &primitives),
334                EId::FeBlend => convert_blend(child, &primitives),
335                EId::FeFlood => convert_flood(child),
336                EId::FeComposite => convert_composite(child, &primitives),
337                EId::FeMerge => convert_merge(child, &primitives),
338                EId::FeTile => convert_tile(child, &primitives),
339                EId::FeImage => convert_image(child, filter_subregion, state, cache),
340                EId::FeComponentTransfer => convert_component_transfer(child, &primitives),
341                EId::FeColorMatrix => convert_color_matrix(child, &primitives),
342                EId::FeConvolveMatrix => convert_convolve_matrix(child, &primitives)
343                    .unwrap_or_else(create_dummy_primitive),
344                EId::FeMorphology => convert_morphology(child, scale, &primitives),
345                EId::FeDisplacementMap => convert_displacement_map(child, scale, &primitives),
346                EId::FeTurbulence => convert_turbulence(child),
347                EId::FeDiffuseLighting => convert_diffuse_lighting(child, &primitives)
348                    .unwrap_or_else(create_dummy_primitive),
349                EId::FeSpecularLighting => convert_specular_lighting(child, &primitives)
350                    .unwrap_or_else(create_dummy_primitive),
351                tag_name => {
352                    log::warn!("'{}' is not a valid filter primitive. Skipped.", tag_name);
353                    continue;
354                }
355            };
356
357        let color_interpolation = child
358            .find_attribute(AId::ColorInterpolationFilters)
359            .unwrap_or_default();
360
361        primitives.push(Primitive {
362            rect: filter_subregion,
363            color_interpolation,
364            result: gen_result(child, &mut results),
365            kind,
366        });
367    }
368
369    // TODO: remove primitives which results are not used
370
371    primitives
372}
373
374fn resolve_primitive_region(
375    fe: SvgNode,
376    units: Units,
377    state: &converter::State,
378    bbox: Option<NonZeroRect>,
379    filter_region: NonZeroRect,
380) -> Option<NonZeroRect> {
381    let mut x = fe.try_convert_length(AId::X, units, state);
382    let mut y = fe.try_convert_length(AId::Y, units, state);
383    let mut width = fe.try_convert_length(AId::Width, units, state);
384    let mut height = fe.try_convert_length(AId::Height, units, state);
385
386    if units == Units::ObjectBoundingBox {
387        let bbox = bbox?;
388        x = x.map(|v| bbox.x() + v * bbox.width());
389        y = y.map(|v| bbox.y() + v * bbox.height());
390        width = width.map(|v| v * bbox.width());
391        height = height.map(|v| v * bbox.height());
392    }
393
394    NonZeroRect::from_xywh(
395        x.unwrap_or(filter_region.x()),
396        y.unwrap_or(filter_region.y()),
397        width.unwrap_or(filter_region.width()),
398        height.unwrap_or(filter_region.height()),
399    )
400}
401
402// A malformed filter primitive usually should produce a transparent image.
403// But since `FilterKind` structs are designed to always be valid,
404// we are using `FeFlood` as fallback.
405#[inline(never)]
406pub(crate) fn create_dummy_primitive() -> Kind {
407    Kind::Flood(Flood {
408        color: Color::black(),
409        opacity: Opacity::ZERO,
410    })
411}
412
413#[inline(never)]
414fn resolve_input(node: SvgNode, aid: AId, primitives: &[Primitive]) -> Input {
415    match node.attribute(aid) {
416        Some(s) => {
417            let input = parse_in(s);
418
419            // If `in` references an unknown `result` than fallback
420            // to previous result or `SourceGraphic`.
421            if let Input::Reference(ref name) = input {
422                if !primitives.iter().any(|p| p.result == *name) {
423                    return if let Some(prev) = primitives.last() {
424                        Input::Reference(prev.result.clone())
425                    } else {
426                        Input::SourceGraphic
427                    };
428                }
429            }
430
431            input
432        }
433        None => {
434            if let Some(prev) = primitives.last() {
435                // If `in` is not set and this is not the first primitive
436                // than the input is a result of the previous primitive.
437                Input::Reference(prev.result.clone())
438            } else {
439                // If `in` is not set and this is the first primitive
440                // than the input is `SourceGraphic`.
441                Input::SourceGraphic
442            }
443        }
444    }
445}
446
447fn parse_in(s: &str) -> Input {
448    match s {
449        "SourceGraphic" => Input::SourceGraphic,
450        "SourceAlpha" => Input::SourceAlpha,
451        "BackgroundImage" | "BackgroundAlpha" | "FillPaint" | "StrokePaint" => {
452            log::warn!("{} filter input isn't supported and not planed.", s);
453            Input::SourceGraphic
454        }
455        _ => Input::Reference(s.to_string()),
456    }
457}
458
459fn gen_result(node: SvgNode, results: &mut FilterResults) -> String {
460    match node.attribute::<&str>(AId::Result) {
461        Some(s) => {
462            // Remember predefined result.
463            results.names.insert(s.to_string());
464            results.idx += 1;
465
466            s.to_string()
467        }
468        None => {
469            // Generate an unique name for `result`.
470            loop {
471                let name = format!("result{}", results.idx);
472                results.idx += 1;
473
474                if !results.names.contains(&name) {
475                    return name;
476                }
477            }
478        }
479    }
480}
481
482fn convert_blend(fe: SvgNode, primitives: &[Primitive]) -> Kind {
483    let mode = fe.attribute(AId::Mode).unwrap_or_default();
484    let input1 = resolve_input(fe, AId::In, primitives);
485    let input2 = resolve_input(fe, AId::In2, primitives);
486    Kind::Blend(Blend {
487        mode,
488        input1,
489        input2,
490    })
491}
492
493fn convert_color_matrix(fe: SvgNode, primitives: &[Primitive]) -> Kind {
494    let kind = convert_color_matrix_kind(fe).unwrap_or_default();
495    Kind::ColorMatrix(ColorMatrix {
496        input: resolve_input(fe, AId::In, primitives),
497        kind,
498    })
499}
500
501fn convert_color_matrix_kind(fe: SvgNode) -> Option<ColorMatrixKind> {
502    match fe.attribute(AId::Type) {
503        Some("saturate") => {
504            if let Some(list) = fe.attribute::<Vec<f32>>(AId::Values) {
505                if !list.is_empty() {
506                    let n = crate::f32_bound(0.0, list[0], 1.0);
507                    return Some(ColorMatrixKind::Saturate(PositiveF32::new(n).unwrap()));
508                } else {
509                    return Some(ColorMatrixKind::Saturate(PositiveF32::new(1.0).unwrap()));
510                }
511            }
512        }
513        Some("hueRotate") => {
514            if let Some(list) = fe.attribute::<Vec<f32>>(AId::Values) {
515                if !list.is_empty() {
516                    return Some(ColorMatrixKind::HueRotate(list[0]));
517                } else {
518                    return Some(ColorMatrixKind::HueRotate(0.0));
519                }
520            }
521        }
522        Some("luminanceToAlpha") => {
523            return Some(ColorMatrixKind::LuminanceToAlpha);
524        }
525        _ => {
526            // Fallback to `matrix`.
527            if let Some(list) = fe.attribute::<Vec<f32>>(AId::Values) {
528                if list.len() == 20 {
529                    return Some(ColorMatrixKind::Matrix(list));
530                }
531            }
532        }
533    }
534
535    None
536}
537
538fn convert_component_transfer(fe: SvgNode, primitives: &[Primitive]) -> Kind {
539    let mut kind = ComponentTransfer {
540        input: resolve_input(fe, AId::In, primitives),
541        func_r: TransferFunction::Identity,
542        func_g: TransferFunction::Identity,
543        func_b: TransferFunction::Identity,
544        func_a: TransferFunction::Identity,
545    };
546
547    for child in fe.children().filter(|n| n.is_element()) {
548        if let Some(func) = convert_transfer_function(child) {
549            match child.tag_name().unwrap() {
550                EId::FeFuncR => kind.func_r = func,
551                EId::FeFuncG => kind.func_g = func,
552                EId::FeFuncB => kind.func_b = func,
553                EId::FeFuncA => kind.func_a = func,
554                _ => {}
555            }
556        }
557    }
558
559    Kind::ComponentTransfer(kind)
560}
561
562fn convert_transfer_function(node: SvgNode) -> Option<TransferFunction> {
563    match node.attribute(AId::Type)? {
564        "identity" => Some(TransferFunction::Identity),
565        "table" => match node.attribute::<Vec<f32>>(AId::TableValues) {
566            Some(values) => Some(TransferFunction::Table(values)),
567            None => Some(TransferFunction::Table(Vec::new())),
568        },
569        "discrete" => match node.attribute::<Vec<f32>>(AId::TableValues) {
570            Some(values) => Some(TransferFunction::Discrete(values)),
571            None => Some(TransferFunction::Discrete(Vec::new())),
572        },
573        "linear" => Some(TransferFunction::Linear {
574            slope: node.attribute(AId::Slope).unwrap_or(1.0),
575            intercept: node.attribute(AId::Intercept).unwrap_or(0.0),
576        }),
577        "gamma" => Some(TransferFunction::Gamma {
578            amplitude: node.attribute(AId::Amplitude).unwrap_or(1.0),
579            exponent: node.attribute(AId::Exponent).unwrap_or(1.0),
580            offset: node.attribute(AId::Offset).unwrap_or(0.0),
581        }),
582        _ => None,
583    }
584}
585
586fn convert_composite(fe: SvgNode, primitives: &[Primitive]) -> Kind {
587    let operator = match fe.attribute(AId::Operator).unwrap_or("over") {
588        "in" => CompositeOperator::In,
589        "out" => CompositeOperator::Out,
590        "atop" => CompositeOperator::Atop,
591        "xor" => CompositeOperator::Xor,
592        "lighter" => CompositeOperator::Lighter,
593        "arithmetic" => CompositeOperator::Arithmetic {
594            k1: fe.attribute(AId::K1).unwrap_or(0.0),
595            k2: fe.attribute(AId::K2).unwrap_or(0.0),
596            k3: fe.attribute(AId::K3).unwrap_or(0.0),
597            k4: fe.attribute(AId::K4).unwrap_or(0.0),
598        },
599        _ => CompositeOperator::Over,
600    };
601
602    let input1 = resolve_input(fe, AId::In, primitives);
603    let input2 = resolve_input(fe, AId::In2, primitives);
604
605    Kind::Composite(Composite {
606        operator,
607        input1,
608        input2,
609    })
610}
611
612fn convert_convolve_matrix(fe: SvgNode, primitives: &[Primitive]) -> Option<Kind> {
613    fn parse_target(target: Option<f32>, order: u32) -> Option<u32> {
614        let default_target = (order as f32 / 2.0).floor() as u32;
615        let target = target.unwrap_or(default_target as f32) as i32;
616        if target < 0 || target >= order as i32 {
617            None
618        } else {
619            Some(target as u32)
620        }
621    }
622
623    let mut order_x = 3;
624    let mut order_y = 3;
625    if let Some(value) = fe.attribute::<&str>(AId::Order) {
626        let mut s = svgtypes::NumberListParser::from(value);
627        let x = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(3);
628        let y = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(x);
629        if x > 0 && y > 0 {
630            order_x = x as u32;
631            order_y = y as u32;
632        }
633    }
634
635    let mut matrix = Vec::new();
636    if let Some(list) = fe.attribute::<Vec<f32>>(AId::KernelMatrix) {
637        if list.len() == (order_x * order_y) as usize {
638            matrix = list;
639        }
640    }
641
642    let mut kernel_sum: f32 = matrix.iter().sum();
643    // Round up to prevent float precision issues.
644    kernel_sum = (kernel_sum * 1_000_000.0).round() / 1_000_000.0;
645    if kernel_sum.approx_zero_ulps(4) {
646        kernel_sum = 1.0;
647    }
648
649    let divisor = fe.attribute(AId::Divisor).unwrap_or(kernel_sum);
650    if divisor.approx_zero_ulps(4) {
651        return None;
652    }
653
654    let bias = fe.attribute(AId::Bias).unwrap_or(0.0);
655
656    let target_x = parse_target(fe.attribute(AId::TargetX), order_x)?;
657    let target_y = parse_target(fe.attribute(AId::TargetY), order_y)?;
658
659    let kernel_matrix = ConvolveMatrixData::new(target_x, target_y, order_x, order_y, matrix)?;
660
661    let edge_mode = match fe.attribute(AId::EdgeMode).unwrap_or("duplicate") {
662        "none" => EdgeMode::None,
663        "wrap" => EdgeMode::Wrap,
664        _ => EdgeMode::Duplicate,
665    };
666
667    let preserve_alpha = fe.attribute(AId::PreserveAlpha).unwrap_or("false") == "true";
668
669    Some(Kind::ConvolveMatrix(ConvolveMatrix {
670        input: resolve_input(fe, AId::In, primitives),
671        matrix: kernel_matrix,
672        divisor: NonZeroF32::new(divisor).unwrap(),
673        bias,
674        edge_mode,
675        preserve_alpha,
676    }))
677}
678
679fn convert_displacement_map(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {
680    let parse_channel = |aid| match fe.attribute(aid).unwrap_or("A") {
681        "R" => ColorChannel::R,
682        "G" => ColorChannel::G,
683        "B" => ColorChannel::B,
684        _ => ColorChannel::A,
685    };
686
687    // TODO: should probably split scale to scale_x and scale_y
688    //       to handle `primitiveUnits=objectBoundingBox` with a non-square bbox.
689    let scale = (scale.width() + scale.height()) / 2.0;
690
691    Kind::DisplacementMap(DisplacementMap {
692        input1: resolve_input(fe, AId::In, primitives),
693        input2: resolve_input(fe, AId::In2, primitives),
694        scale: fe.attribute(AId::Scale).unwrap_or(0.0) * scale,
695        x_channel_selector: parse_channel(AId::XChannelSelector),
696        y_channel_selector: parse_channel(AId::YChannelSelector),
697    })
698}
699
700fn convert_drop_shadow(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {
701    let (std_dev_x, std_dev_y) = convert_std_dev_attr(fe, scale, "2 2");
702
703    let (color, opacity) = fe
704        .attribute(AId::FloodColor)
705        .unwrap_or_else(svgtypes::Color::black)
706        .split_alpha();
707
708    let flood_opacity = fe
709        .attribute::<Opacity>(AId::FloodOpacity)
710        .unwrap_or(Opacity::ONE);
711
712    Kind::DropShadow(DropShadow {
713        input: resolve_input(fe, AId::In, primitives),
714        dx: fe.attribute(AId::Dx).unwrap_or(2.0) * scale.width(),
715        dy: fe.attribute(AId::Dy).unwrap_or(2.0) * scale.height(),
716        std_dev_x,
717        std_dev_y,
718        color,
719        opacity: opacity * flood_opacity,
720    })
721}
722
723fn convert_flood(fe: SvgNode) -> Kind {
724    let (color, opacity) = fe
725        .attribute(AId::FloodColor)
726        .unwrap_or_else(svgtypes::Color::black)
727        .split_alpha();
728
729    let flood_opacity = fe
730        .attribute::<Opacity>(AId::FloodOpacity)
731        .unwrap_or(Opacity::ONE);
732
733    Kind::Flood(Flood {
734        color,
735        opacity: opacity * flood_opacity,
736    })
737}
738
739fn convert_gaussian_blur(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {
740    let (std_dev_x, std_dev_y) = convert_std_dev_attr(fe, scale, "0 0");
741    Kind::GaussianBlur(GaussianBlur {
742        input: resolve_input(fe, AId::In, primitives),
743        std_dev_x,
744        std_dev_y,
745    })
746}
747
748fn convert_std_dev_attr(fe: SvgNode, scale: Size, default: &str) -> (PositiveF32, PositiveF32) {
749    let text = fe.attribute(AId::StdDeviation).unwrap_or(default);
750    let mut parser = svgtypes::NumberListParser::from(text);
751
752    let n1 = parser.next().and_then(|n| n.ok());
753    let n2 = parser.next().and_then(|n| n.ok());
754    // `stdDeviation` must have no more than two values.
755    // Otherwise we should fallback to `0 0`.
756    let n3 = parser.next().and_then(|n| n.ok());
757
758    let (std_dev_x, std_dev_y) = match (n1, n2, n3) {
759        (Some(n1), Some(n2), None) => (n1, n2),
760        (Some(n1), None, None) => (n1, n1),
761        _ => (0.0, 0.0),
762    };
763
764    let std_dev_x = (std_dev_x as f32) * scale.width();
765    let std_dev_y = (std_dev_y as f32) * scale.height();
766
767    let std_dev_x = PositiveF32::new(std_dev_x).unwrap_or(PositiveF32::ZERO);
768    let std_dev_y = PositiveF32::new(std_dev_y).unwrap_or(PositiveF32::ZERO);
769
770    (std_dev_x, std_dev_y)
771}
772
773fn convert_image(
774    fe: SvgNode,
775    filter_subregion: NonZeroRect,
776    state: &converter::State,
777    cache: &mut converter::Cache,
778) -> Kind {
779    match convert_image_inner(fe, filter_subregion, state, cache) {
780        Some(kind) => kind,
781        None => create_dummy_primitive(),
782    }
783}
784
785fn convert_image_inner(
786    fe: SvgNode,
787    filter_subregion: NonZeroRect,
788    state: &converter::State,
789    cache: &mut converter::Cache,
790) -> Option<Kind> {
791    let rendering_mode = fe
792        .find_attribute(AId::ImageRendering)
793        .unwrap_or(state.opt.image_rendering);
794
795    if let Some(node) = fe.try_attribute::<SvgNode>(AId::Href) {
796        let mut state = state.clone();
797        state.fe_image_link = true;
798        let mut root = Group::empty();
799        super::converter::convert_element(node, &state, cache, &mut root);
800        return if root.has_children() {
801            super::paint_server::update_paint_servers(
802                &mut root,
803                Transform::default(),
804                None,
805                None,
806                cache,
807            );
808            // Transfer node id from group's child to the group itself if needed.
809            if let Some(Node::Group(g)) = root.children.first_mut() {
810                if let Some(child2) = g.children.first_mut() {
811                    g.id = child2.id().to_string();
812                    match child2 {
813                        Node::Group(g2) => g2.id.clear(),
814                        Node::Path(path) => path.id = Box::default(),
815                        Node::Image(image) => image.id.clear(),
816                        Node::Text(text) => text.id.clear(),
817                    }
818                }
819            }
820
821            Some(Kind::Image(Image { root }))
822        } else {
823            None
824        };
825    }
826
827    let href = fe.try_attribute(AId::Href).log_none(|| {
828        log::warn!("The 'feImage' element lacks the 'xlink:href' attribute. Skipped.");
829    })?;
830    let img_data = super::image::get_href_data(href, state)?;
831    let actual_size = img_data.actual_size()?;
832
833    let aspect: AspectRatio = fe.attribute(AId::PreserveAspectRatio).unwrap_or_default();
834
835    let mut root = Group::empty();
836    super::image::convert_inner(
837        img_data,
838        cache.gen_image_id().take(),
839        true,
840        rendering_mode,
841        aspect,
842        actual_size,
843        filter_subregion.translate_to(0.0, 0.0)?,
844        cache,
845        &mut root,
846    );
847
848    Some(Kind::Image(Image { root }))
849}
850
851fn convert_diffuse_lighting(fe: SvgNode, primitives: &[Primitive]) -> Option<Kind> {
852    let light_source = convert_light_source(fe)?;
853    Some(Kind::DiffuseLighting(DiffuseLighting {
854        input: resolve_input(fe, AId::In, primitives),
855        surface_scale: fe.attribute(AId::SurfaceScale).unwrap_or(1.0),
856        diffuse_constant: fe.attribute(AId::DiffuseConstant).unwrap_or(1.0),
857        lighting_color: convert_lighting_color(fe),
858        light_source,
859    }))
860}
861
862fn convert_specular_lighting(fe: SvgNode, primitives: &[Primitive]) -> Option<Kind> {
863    let light_source = convert_light_source(fe)?;
864
865    let specular_exponent = fe.attribute(AId::SpecularExponent).unwrap_or(1.0);
866    if !(1.0..=128.0).contains(&specular_exponent) {
867        // When exponent is out of range, the whole filter primitive should be ignored.
868        return None;
869    }
870
871    let specular_exponent = crate::f32_bound(1.0, specular_exponent, 128.0);
872
873    Some(Kind::SpecularLighting(SpecularLighting {
874        input: resolve_input(fe, AId::In, primitives),
875        surface_scale: fe.attribute(AId::SurfaceScale).unwrap_or(1.0),
876        specular_constant: fe.attribute(AId::SpecularConstant).unwrap_or(1.0),
877        specular_exponent,
878        lighting_color: convert_lighting_color(fe),
879        light_source,
880    }))
881}
882
883#[inline(never)]
884fn convert_lighting_color(node: SvgNode) -> Color {
885    // Color's alpha doesn't affect lighting-color. Simply skip it.
886    node.attribute::<svgtypes::Color>(AId::LightingColor)
887        .map_or(Color::white(), |c| c.split_alpha().0)
888}
889
890#[inline(never)]
891fn convert_light_source(parent: SvgNode) -> Option<LightSource> {
892    let child = parent.children().find(|n| {
893        matches!(
894            n.tag_name(),
895            Some(EId::FeDistantLight) | Some(EId::FePointLight) | Some(EId::FeSpotLight)
896        )
897    })?;
898
899    match child.tag_name() {
900        Some(EId::FeDistantLight) => Some(LightSource::DistantLight(DistantLight {
901            azimuth: child.attribute(AId::Azimuth).unwrap_or(0.0),
902            elevation: child.attribute(AId::Elevation).unwrap_or(0.0),
903        })),
904        Some(EId::FePointLight) => Some(LightSource::PointLight(PointLight {
905            x: child.attribute(AId::X).unwrap_or(0.0),
906            y: child.attribute(AId::Y).unwrap_or(0.0),
907            z: child.attribute(AId::Z).unwrap_or(0.0),
908        })),
909        Some(EId::FeSpotLight) => {
910            let specular_exponent = child.attribute(AId::SpecularExponent).unwrap_or(1.0);
911            let specular_exponent = PositiveF32::new(specular_exponent)
912                .unwrap_or_else(|| PositiveF32::new(1.0).unwrap());
913
914            Some(LightSource::SpotLight(SpotLight {
915                x: child.attribute(AId::X).unwrap_or(0.0),
916                y: child.attribute(AId::Y).unwrap_or(0.0),
917                z: child.attribute(AId::Z).unwrap_or(0.0),
918                points_at_x: child.attribute(AId::PointsAtX).unwrap_or(0.0),
919                points_at_y: child.attribute(AId::PointsAtY).unwrap_or(0.0),
920                points_at_z: child.attribute(AId::PointsAtZ).unwrap_or(0.0),
921                specular_exponent,
922                limiting_cone_angle: child.attribute(AId::LimitingConeAngle),
923            }))
924        }
925        _ => None,
926    }
927}
928
929fn convert_merge(fe: SvgNode, primitives: &[Primitive]) -> Kind {
930    let mut inputs = Vec::new();
931    for child in fe.children() {
932        inputs.push(resolve_input(child, AId::In, primitives));
933    }
934
935    Kind::Merge(Merge { inputs })
936}
937
938fn convert_morphology(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {
939    let operator = match fe.attribute(AId::Operator).unwrap_or("erode") {
940        "dilate" => MorphologyOperator::Dilate,
941        _ => MorphologyOperator::Erode,
942    };
943
944    let mut radius_x = PositiveF32::new(scale.width()).unwrap();
945    let mut radius_y = PositiveF32::new(scale.height()).unwrap();
946    if let Some(list) = fe.attribute::<Vec<f32>>(AId::Radius) {
947        let mut rx = 0.0;
948        let mut ry = 0.0;
949        if list.len() == 2 {
950            rx = list[0];
951            ry = list[1];
952        } else if list.len() == 1 {
953            rx = list[0];
954            ry = list[0]; // The same as `rx`.
955        }
956
957        if rx.approx_zero_ulps(4) && ry.approx_zero_ulps(4) {
958            rx = 1.0;
959            ry = 1.0;
960        }
961
962        // If only one of the values is zero, reset it to 1.0
963        // This is not specified in the spec, but this is how Chrome and Safari work.
964        if rx.approx_zero_ulps(4) && !ry.approx_zero_ulps(4) {
965            rx = 1.0;
966        }
967        if !rx.approx_zero_ulps(4) && ry.approx_zero_ulps(4) {
968            ry = 1.0;
969        }
970
971        // Both values must be positive.
972        if rx.is_sign_positive() && ry.is_sign_positive() {
973            radius_x = PositiveF32::new(rx * scale.width()).unwrap();
974            radius_y = PositiveF32::new(ry * scale.height()).unwrap();
975        }
976    }
977
978    Kind::Morphology(Morphology {
979        input: resolve_input(fe, AId::In, primitives),
980        operator,
981        radius_x,
982        radius_y,
983    })
984}
985
986fn convert_offset(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {
987    Kind::Offset(Offset {
988        input: resolve_input(fe, AId::In, primitives),
989        dx: fe.attribute(AId::Dx).unwrap_or(0.0) * scale.width(),
990        dy: fe.attribute(AId::Dy).unwrap_or(0.0) * scale.height(),
991    })
992}
993
994fn convert_tile(fe: SvgNode, primitives: &[Primitive]) -> Kind {
995    Kind::Tile(Tile {
996        input: resolve_input(fe, AId::In, primitives),
997    })
998}
999
1000fn convert_turbulence(fe: SvgNode) -> Kind {
1001    let mut base_frequency_x = PositiveF32::ZERO;
1002    let mut base_frequency_y = PositiveF32::ZERO;
1003    if let Some(list) = fe.attribute::<Vec<f32>>(AId::BaseFrequency) {
1004        let mut x = 0.0;
1005        let mut y = 0.0;
1006        if list.len() == 2 {
1007            x = list[0];
1008            y = list[1];
1009        } else if list.len() == 1 {
1010            x = list[0];
1011            y = list[0]; // The same as `x`.
1012        }
1013
1014        if x.is_sign_positive() && y.is_sign_positive() {
1015            base_frequency_x = PositiveF32::new(x).unwrap();
1016            base_frequency_y = PositiveF32::new(y).unwrap();
1017        }
1018    }
1019
1020    let mut num_octaves = fe.attribute(AId::NumOctaves).unwrap_or(1.0);
1021    if num_octaves.is_sign_negative() {
1022        num_octaves = 0.0;
1023    }
1024
1025    let kind = match fe.attribute(AId::Type).unwrap_or("turbulence") {
1026        "fractalNoise" => TurbulenceKind::FractalNoise,
1027        _ => TurbulenceKind::Turbulence,
1028    };
1029
1030    Kind::Turbulence(Turbulence {
1031        base_frequency_x,
1032        base_frequency_y,
1033        num_octaves: num_octaves.round() as u32,
1034        seed: fe.attribute::<f32>(AId::Seed).unwrap_or(0.0).trunc() as i32,
1035        stitch_tiles: fe.attribute(AId::StitchTiles) == Some("stitch"),
1036        kind,
1037    })
1038}
1039
1040#[inline(never)]
1041fn convert_grayscale_function(amount: f64) -> Kind {
1042    let amount = amount.min(1.0) as f32;
1043    Kind::ColorMatrix(ColorMatrix {
1044        input: Input::SourceGraphic,
1045        kind: ColorMatrixKind::Matrix(vec![
1046            (0.2126 + 0.7874 * (1.0 - amount)),
1047            (0.7152 - 0.7152 * (1.0 - amount)),
1048            (0.0722 - 0.0722 * (1.0 - amount)),
1049            0.0,
1050            0.0,
1051            (0.2126 - 0.2126 * (1.0 - amount)),
1052            (0.7152 + 0.2848 * (1.0 - amount)),
1053            (0.0722 - 0.0722 * (1.0 - amount)),
1054            0.0,
1055            0.0,
1056            (0.2126 - 0.2126 * (1.0 - amount)),
1057            (0.7152 - 0.7152 * (1.0 - amount)),
1058            (0.0722 + 0.9278 * (1.0 - amount)),
1059            0.0,
1060            0.0,
1061            0.0,
1062            0.0,
1063            0.0,
1064            1.0,
1065            0.0,
1066        ]),
1067    })
1068}
1069
1070#[inline(never)]
1071fn convert_sepia_function(amount: f64) -> Kind {
1072    let amount = amount.min(1.0) as f32;
1073    Kind::ColorMatrix(ColorMatrix {
1074        input: Input::SourceGraphic,
1075        kind: ColorMatrixKind::Matrix(vec![
1076            (0.393 + 0.607 * (1.0 - amount)),
1077            (0.769 - 0.769 * (1.0 - amount)),
1078            (0.189 - 0.189 * (1.0 - amount)),
1079            0.0,
1080            0.0,
1081            (0.349 - 0.349 * (1.0 - amount)),
1082            (0.686 + 0.314 * (1.0 - amount)),
1083            (0.168 - 0.168 * (1.0 - amount)),
1084            0.0,
1085            0.0,
1086            (0.272 - 0.272 * (1.0 - amount)),
1087            (0.534 - 0.534 * (1.0 - amount)),
1088            (0.131 + 0.869 * (1.0 - amount)),
1089            0.0,
1090            0.0,
1091            0.0,
1092            0.0,
1093            0.0,
1094            1.0,
1095            0.0,
1096        ]),
1097    })
1098}
1099
1100#[inline(never)]
1101fn convert_saturate_function(amount: f64) -> Kind {
1102    let amount = PositiveF32::new(amount as f32).unwrap_or(PositiveF32::ZERO);
1103    Kind::ColorMatrix(ColorMatrix {
1104        input: Input::SourceGraphic,
1105        kind: ColorMatrixKind::Saturate(amount),
1106    })
1107}
1108
1109#[inline(never)]
1110fn convert_hue_rotate_function(amount: svgtypes::Angle) -> Kind {
1111    Kind::ColorMatrix(ColorMatrix {
1112        input: Input::SourceGraphic,
1113        kind: ColorMatrixKind::HueRotate(amount.to_degrees() as f32),
1114    })
1115}
1116
1117#[inline(never)]
1118fn convert_invert_function(amount: f64) -> Kind {
1119    let amount = amount.min(1.0) as f32;
1120    Kind::ComponentTransfer(ComponentTransfer {
1121        input: Input::SourceGraphic,
1122        func_r: TransferFunction::Table(vec![amount, 1.0 - amount]),
1123        func_g: TransferFunction::Table(vec![amount, 1.0 - amount]),
1124        func_b: TransferFunction::Table(vec![amount, 1.0 - amount]),
1125        func_a: TransferFunction::Identity,
1126    })
1127}
1128
1129#[inline(never)]
1130fn convert_opacity_function(amount: f64) -> Kind {
1131    let amount = amount.min(1.0) as f32;
1132    Kind::ComponentTransfer(ComponentTransfer {
1133        input: Input::SourceGraphic,
1134        func_r: TransferFunction::Identity,
1135        func_g: TransferFunction::Identity,
1136        func_b: TransferFunction::Identity,
1137        func_a: TransferFunction::Table(vec![0.0, amount]),
1138    })
1139}
1140
1141#[inline(never)]
1142fn convert_brightness_function(amount: f64) -> Kind {
1143    let amount = amount as f32;
1144    Kind::ComponentTransfer(ComponentTransfer {
1145        input: Input::SourceGraphic,
1146        func_r: TransferFunction::Linear {
1147            slope: amount,
1148            intercept: 0.0,
1149        },
1150        func_g: TransferFunction::Linear {
1151            slope: amount,
1152            intercept: 0.0,
1153        },
1154        func_b: TransferFunction::Linear {
1155            slope: amount,
1156            intercept: 0.0,
1157        },
1158        func_a: TransferFunction::Identity,
1159    })
1160}
1161
1162#[inline(never)]
1163fn convert_contrast_function(amount: f64) -> Kind {
1164    let amount = amount as f32;
1165    Kind::ComponentTransfer(ComponentTransfer {
1166        input: Input::SourceGraphic,
1167        func_r: TransferFunction::Linear {
1168            slope: amount,
1169            intercept: -(0.5 * amount) + 0.5,
1170        },
1171        func_g: TransferFunction::Linear {
1172            slope: amount,
1173            intercept: -(0.5 * amount) + 0.5,
1174        },
1175        func_b: TransferFunction::Linear {
1176            slope: amount,
1177            intercept: -(0.5 * amount) + 0.5,
1178        },
1179        func_a: TransferFunction::Identity,
1180    })
1181}
1182
1183#[inline(never)]
1184fn convert_blur_function(node: SvgNode, std_dev: Length, state: &converter::State) -> Kind {
1185    let std_dev = PositiveF32::new(super::units::convert_user_length(
1186        std_dev,
1187        node,
1188        AId::Dx,
1189        state,
1190    ))
1191    .unwrap_or(PositiveF32::ZERO);
1192    Kind::GaussianBlur(GaussianBlur {
1193        input: Input::SourceGraphic,
1194        std_dev_x: std_dev,
1195        std_dev_y: std_dev,
1196    })
1197}
1198
1199#[inline(never)]
1200fn convert_drop_shadow_function(
1201    node: SvgNode,
1202    color: Option<svgtypes::Color>,
1203    dx: Length,
1204    dy: Length,
1205    std_dev: Length,
1206    state: &converter::State,
1207) -> Kind {
1208    let std_dev = PositiveF32::new(super::units::convert_user_length(
1209        std_dev,
1210        node,
1211        AId::Dx,
1212        state,
1213    ))
1214    .unwrap_or(PositiveF32::ZERO);
1215
1216    let (color, opacity) = color
1217        .unwrap_or_else(|| {
1218            node.find_attribute(AId::Color)
1219                .unwrap_or_else(svgtypes::Color::black)
1220        })
1221        .split_alpha();
1222
1223    Kind::DropShadow(DropShadow {
1224        input: Input::SourceGraphic,
1225        dx: super::units::convert_user_length(dx, node, AId::Dx, state),
1226        dy: super::units::convert_user_length(dy, node, AId::Dy, state),
1227        std_dev_x: std_dev,
1228        std_dev_y: std_dev,
1229        color,
1230        opacity,
1231    })
1232}