1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
use markup5ever::{expanded_name, local_name, namespace_url, ns};

use crate::aspect_ratio::AspectRatio;
use crate::document::{AcquiredNodes, Document, NodeId, Resource};
use crate::drawing_ctx::{DrawingCtx, SvgNesting};
use crate::element::{set_attribute, ElementTrait};
use crate::href::{is_href, set_href};
use crate::image::checked_i32;
use crate::node::{CascadedValues, Node};
use crate::parsers::ParseValue;
use crate::properties::ComputedValues;
use crate::rect::Rect;
use crate::rsvg_log;
use crate::session::Session;
use crate::surface_utils::shared_surface::{Interpolation, SharedImageSurface, SurfaceType};
use crate::viewbox::ViewBox;
use crate::xml::Attributes;

use super::bounds::{Bounds, BoundsBuilder};
use super::context::{FilterContext, FilterOutput};
use super::{
    FilterEffect, FilterError, FilterResolveError, Primitive, PrimitiveParams, ResolvedPrimitive,
};

/// The `feImage` filter primitive.
#[derive(Default)]
pub struct FeImage {
    base: Primitive,
    params: ImageParams,
}

#[derive(Clone, Default)]
struct ImageParams {
    aspect: AspectRatio,
    href: Option<String>,
}

/// Resolved `feImage` primitive for rendering.
pub struct Image {
    aspect: AspectRatio,
    source: Source,
    feimage_values: Box<ComputedValues>,
}

/// What a feImage references for rendering.
enum Source {
    /// Nothing is referenced; ignore the filter.
    None,

    /// Reference to a node.
    Node(Node, String),

    /// Reference to an external image.  This is just a URL.
    ExternalImage(String),
}

impl ElementTrait for FeImage {
    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) {
        self.base.parse_no_inputs(attrs, session);

        for (attr, value) in attrs.iter() {
            match attr.expanded() {
                expanded_name!("", "preserveAspectRatio") => {
                    set_attribute(&mut self.params.aspect, attr.parse(value), session);
                }

                // "path" is used by some older Adobe Illustrator versions
                ref a if is_href(a) || *a == expanded_name!("", "path") => {
                    set_href(a, &mut self.params.href, Some(value.to_string()));
                }

                _ => (),
            }
        }
    }
}

impl Image {
    pub fn render(
        &self,
        bounds_builder: BoundsBuilder,
        ctx: &FilterContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterOutput, FilterError> {
        let bounds = bounds_builder.compute(ctx);

        let surface = match &self.source {
            Source::None => return Err(FilterError::InvalidInput),

            Source::Node(node, ref name) => {
                if let Ok(acquired) = acquired_nodes.acquire_ref(node) {
                    rsvg_log!(draw_ctx.session(), "(feImage \"{}\"", name);
                    let res = self.render_node(
                        ctx,
                        acquired_nodes,
                        draw_ctx,
                        bounds.clipped,
                        acquired.get(),
                    );
                    rsvg_log!(draw_ctx.session(), ")");
                    res?
                } else {
                    return Err(FilterError::InvalidInput);
                }
            }

            Source::ExternalImage(ref href) => {
                self.render_external_image(ctx, acquired_nodes, draw_ctx, &bounds, href)?
            }
        };

        Ok(FilterOutput {
            surface,
            bounds: bounds.clipped.into(),
        })
    }

    /// Renders the filter if the source is an existing node.
    fn render_node(
        &self,
        ctx: &FilterContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        draw_ctx: &mut DrawingCtx,
        bounds: Rect,
        referenced_node: &Node,
    ) -> Result<SharedImageSurface, FilterError> {
        // https://www.w3.org/TR/filter-effects/#feImageElement
        //
        // The filters spec says, "... otherwise [rendering a referenced object], the
        // referenced resource is rendered according to the behavior of the use element."
        // I think this means that we use the same cascading mode as <use>, i.e. the
        // referenced object inherits its properties from the feImage element.
        let cascaded =
            CascadedValues::new_from_values(referenced_node, &self.feimage_values, None, None);

        let interpolation = Interpolation::from(self.feimage_values.image_rendering());

        let image = draw_ctx.draw_node_to_surface(
            referenced_node,
            acquired_nodes,
            &cascaded,
            ctx.paffine(),
            ctx.source_graphic().width(),
            ctx.source_graphic().height(),
        )?;

        let surface = ctx
            .source_graphic()
            .paint_image(bounds, &image, None, interpolation)?;

        Ok(surface)
    }

    /// Renders the filter if the source is an external image.
    fn render_external_image(
        &self,
        ctx: &FilterContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        draw_ctx: &DrawingCtx,
        bounds: &Bounds,
        url: &str,
    ) -> Result<SharedImageSurface, FilterError> {
        match acquired_nodes.lookup_resource(url) {
            Ok(Resource::Image(surface)) => {
                self.render_surface_from_raster_image(&surface, ctx, bounds)
            }

            Ok(Resource::Document(document)) => {
                self.render_surface_from_svg(&document, ctx, bounds, draw_ctx)
            }

            Err(e) => {
                rsvg_log!(
                    draw_ctx.session(),
                    "could not load image \"{}\" for feImage: {}",
                    url,
                    e
                );
                Err(FilterError::InvalidInput)
            }
        }
    }

    fn render_surface_from_raster_image(
        &self,
        image: &SharedImageSurface,
        ctx: &FilterContext,
        bounds: &Bounds,
    ) -> Result<SharedImageSurface, FilterError> {
        let rect = self.aspect.compute(
            &ViewBox::from(Rect::from_size(
                f64::from(image.width()),
                f64::from(image.height()),
            )),
            &bounds.unclipped,
        );

        // FIXME: overflow is not used but it should be
        // let overflow = self.feimage_values.overflow();
        let interpolation = Interpolation::from(self.feimage_values.image_rendering());

        let surface =
            ctx.source_graphic()
                .paint_image(bounds.clipped, image, Some(rect), interpolation)?;

        Ok(surface)
    }

    fn render_surface_from_svg(
        &self,
        document: &Document,
        ctx: &FilterContext,
        bounds: &Bounds,
        draw_ctx: &DrawingCtx,
    ) -> Result<SharedImageSurface, FilterError> {
        // Strategy:
        //
        // Render the document at the size needed for the filter primitive
        // subregion, and then paste that as if we were handling the case for a raster imge.
        //
        // Note that for feImage, x/y/width/height are *attributes*, not the geometry
        // properties from the normal <image> element , and have special handling:
        //
        // - They don't take "auto" as a value.  The defaults are "0 0 100% 100%" but those
        // are with respect to the filter primitive subregion.

        let x = bounds.x.unwrap_or(0.0);
        let y = bounds.y.unwrap_or(0.0);
        let w = bounds.width.unwrap_or(1.0); // default is 100%
        let h = bounds.height.unwrap_or(1.0);

        // https://www.w3.org/TR/filter-effects/#FilterPrimitiveSubRegion
        // "If the filter primitive subregion has a negative or zero width or height, the
        // effect of the filter primitive is disabled."
        if w <= 0.0 || h < 0.0 {
            // In this case just return an empty image the size of the SourceGraphic
            return Ok(SharedImageSurface::empty(
                ctx.source_graphic().width(),
                ctx.source_graphic().height(),
                SurfaceType::SRgb,
            )?);
        }

        let dest_rect = Rect {
            x0: bounds.clipped.x0 + bounds.clipped.width() * x,
            y0: bounds.clipped.y0 + bounds.clipped.height() * y,
            x1: bounds.clipped.x0 + bounds.clipped.width() * w,
            y1: bounds.clipped.y0 + bounds.clipped.height() * h,
        };

        let dest_size = dest_rect.size();

        let surface_dest_rect = Rect::from_size(dest_size.0, dest_size.1);

        // We use ceil() to avoid chopping off the last pixel if it is partially covered.
        let surface_width = checked_i32(dest_size.0.ceil())?;
        let surface_height = checked_i32(dest_size.1.ceil())?;
        let surface =
            cairo::ImageSurface::create(cairo::Format::ARgb32, surface_width, surface_height)?;

        {
            let cr = cairo::Context::new(&surface)?;

            let options = draw_ctx.rendering_options(SvgNesting::ReferencedFromImageElement);

            document.render_document(
                draw_ctx.session(),
                &cr,
                &cairo::Rectangle::from(surface_dest_rect),
                &options,
            )?;
        }

        // Now paste that image as a normal raster image

        let surface = SharedImageSurface::wrap(surface, SurfaceType::SRgb)?;

        self.render_surface_from_raster_image(&surface, ctx, bounds)
    }
}

impl FilterEffect for FeImage {
    fn resolve(
        &self,
        acquired_nodes: &mut AcquiredNodes<'_>,
        node: &Node,
    ) -> Result<Vec<ResolvedPrimitive>, FilterResolveError> {
        let cascaded = CascadedValues::new_from_node(node);
        let feimage_values = cascaded.get().clone();

        let source = match self.params.href {
            None => Source::None,

            Some(ref s) => {
                if let Ok(node_id) = NodeId::parse(s) {
                    acquired_nodes
                        .acquire(&node_id)
                        .map(|acquired| Source::Node(acquired.get().clone(), s.clone()))
                        .unwrap_or(Source::None)
                } else {
                    Source::ExternalImage(s.to_string())
                }
            }
        };

        Ok(vec![ResolvedPrimitive {
            primitive: self.base.clone(),
            params: PrimitiveParams::Image(Image {
                aspect: self.params.aspect,
                source,
                feimage_values: Box::new(feimage_values),
            }),
        }])
    }
}