Skip to content

Truly independent web browser

LibWeb: Clip SVG filters to their filter region and subregions

sideshowbarker78354620b706
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rs
index 25796a90f92..18cb841dade 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs
@@ -1445,8 +1445,22 @@ pub unsafe extern "C" fn layout_arena_paint_push_svg_filter_primitive(
sink: *mut c_void,
primitive: *const FfiSvgFilterPrimitive,
) {
- let primitives = unsafe { &mut *sink.cast::<Vec<SvgFilterPrimitive>>() };
- primitives.push(unsafe { svg_filter_primitive_from_ffi(&*primitive) });
+ let filter = unsafe { &mut *sink.cast::<crate::painting::svg_paint_resources::PublishedSvgFilter>() };
+ filter
+ .primitives
+ .push(unsafe { svg_filter_primitive_from_ffi(&*primitive) });
+}
+
+/// # Safety
+///
+/// `sink` must be the pointer handed to the callback, used synchronously, and `region` must be readable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn layout_arena_paint_set_svg_filter_region(
+ sink: *mut c_void,
+ region: *const crate::painting::host::visual_context::FfiSvgFilterRegion,
+) {
+ let filter = unsafe { &mut *sink.cast::<crate::painting::svg_paint_resources::PublishedSvgFilter>() };
+ filter.region = unsafe { *region };
}
/// Notes that the SVG paint resources the document's rows enrolled may have changed, and answers whether any row
diff --git a/Libraries/LibWeb/Rust/src/painting/host/mod.rs b/Libraries/LibWeb/Rust/src/painting/host/mod.rs
index 340997558b2..4d4e54e1617 100644
--- a/Libraries/LibWeb/Rust/src/painting/host/mod.rs
+++ b/Libraries/LibWeb/Rust/src/painting/host/mod.rs
@@ -110,17 +110,17 @@ impl FfiPaintPreparationHostCallbacks {
viewport
}
- /// Pushes the primitives of the SVG filter that the `url()` value `url` of the row in `slot` names into `primitives`,
- /// and answers whether it names one.
+ /// Writes the region and the primitives of the SVG filter that the `url()` value `url` of the row in `slot` names to
+ /// `filter`, and answers whether it names one.
pub(crate) fn resolve_svg_filter(
&self,
_: &crate::stage::MainThread,
read: &crate::render_state::BegunRead,
slot: crate::layout::node_data::NodeSlotId,
url: *const std::ffi::c_void,
- primitives: &mut Vec<crate::painting::svg_filter::SvgFilterPrimitive>,
+ filter: &mut crate::painting::svg_paint_resources::PublishedSvgFilter,
) -> bool {
- (self.resolve_svg_filter)(self.context, read, slot, url, (&raw mut *primitives).cast())
+ (self.resolve_svg_filter)(self.context, read, slot, url, (&raw mut *filter).cast())
}
/// Writes the paint server that the fill, or with `is_stroke` the stroke, of the row in `slot` names to `published`.
diff --git a/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs b/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs
index da06fd94fad..b5418bd7255 100644
--- a/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs
+++ b/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs
@@ -6,6 +6,7 @@
use crate::css::easing::FfiEasingDescriptor;
use crate::css::ffi_support::FfiUtf16View;
+use crate::layout::svg_formatting_context::FfiSvgNumberPercentage;
use crate::layout::used_values::OptionalCssPixelRect;
use libgfx_rust::filter::Filter;
use libgfx_rust::{Color, CompositingAndBlendingOperator, IntRect, InterpolationColorSpace};
@@ -91,11 +92,67 @@ pub struct SvgFilterPrimitiveValues {
pub seed: f32,
pub stitch_tile_width: f32,
pub stitch_tile_height: f32,
+ /// feTurbulence: whether `stitchTiles` is `stitch`.
+ pub turbulence_stitches_tiles: bool,
/// feDisplacementMap: the scale and the channel selector constants.
pub scale: f32,
pub x_channel_selector: u16,
pub y_channel_selector: u16,
pub image_src_rect: IntRect,
+ /// feImage: the image's natural size, zero along an axis where it has none.
+ pub image_natural_width: f32,
+ pub image_natural_height: f32,
+ /// feImage: how the image fits its subregion, in the encoding of its `preserveAspectRatio`
+ /// attribute facts.
+ pub image_preserve_aspect_ratio_align: u8,
+ pub image_preserve_aspect_ratio_meet_or_slice: u8,
+ /// The primitive's `x`, `y`, `width` and `height`, in `primitiveUnits`, each of them only where
+ /// [`Self::subregion_specified`] has its bit set.
+ pub subregion_x: FfiSvgNumberPercentage,
+ pub subregion_y: FfiSvgNumberPercentage,
+ pub subregion_width: FfiSvgNumberPercentage,
+ pub subregion_height: FfiSvgNumberPercentage,
+ /// Which of the subregion attributes the primitive specifies: x, y, width and height, from the
+ /// lowest bit up.
+ pub subregion_specified: u8,
+}
+
+pub(crate) const SUBREGION_SPECIFIES_X: u8 = 1 << 0;
+pub(crate) const SUBREGION_SPECIFIES_Y: u8 = 1 << 1;
+pub(crate) const SUBREGION_SPECIFIES_WIDTH: u8 = 1 << 2;
+pub(crate) const SUBREGION_SPECIFIES_HEIGHT: u8 = 1 << 3;
+
+/// The attribute facts of an SVG `<filter>` element itself: its filter region and the units its
+/// region and its primitives' lengths are in.
+// https://drafts.csswg.org/filter-effects-1/#FilterEffectsRegion
+#[derive(Clone, Copy, Debug, PartialEq)]
+#[repr(C)]
+pub struct FfiSvgFilterRegion {
+ pub filter_units_are_object_bounding_box: bool,
+ pub primitive_units_are_object_bounding_box: bool,
+ pub x: FfiSvgNumberPercentage,
+ pub y: FfiSvgNumberPercentage,
+ pub width: FfiSvgNumberPercentage,
+ pub height: FfiSvgNumberPercentage,
+}
+
+impl Default for FfiSvgFilterRegion {
+ // https://drafts.csswg.org/filter-effects-1/#element-attrdef-filter-x
+ // If the attribute is not specified, the effect is as if a value of -10% were specified.
+ fn default() -> Self {
+ let percentage = |value| FfiSvgNumberPercentage {
+ value,
+ is_percentage: true,
+ };
+ Self {
+ filter_units_are_object_bounding_box: true,
+ primitive_units_are_object_bounding_box: false,
+ x: percentage(-0.1),
+ y: percentage(-0.1),
+ width: percentage(1.2),
+ height: percentage(1.2),
+ }
+ }
}
/// One primitive of an SVG `<filter>` as the host flattens it: its values, and the names, lists
diff --git a/Libraries/LibWeb/Rust/src/painting/paint_passes.rs b/Libraries/LibWeb/Rust/src/painting/paint_passes.rs
index f068472574c..e094e392c74 100644
--- a/Libraries/LibWeb/Rust/src/painting/paint_passes.rs
+++ b/Libraries/LibWeb/Rust/src/painting/paint_passes.rs
@@ -519,12 +519,16 @@ fn sync_svg_paint_resources(
SvgPaintResourceRequest::Filter { slot, kind, urls } => {
let mut published = PublishedSvgFilter::default();
for url in &urls {
- let mut primitives = Vec::new();
+ let mut candidate = PublishedSvgFilter::default();
let found =
- callbacks.resolve_svg_filter(main_thread, read, slot, url.pointer().cast(), &mut primitives);
- published = PublishedSvgFilter {
- failed: !found,
- primitives: if found { primitives } else { Vec::new() },
+ callbacks.resolve_svg_filter(main_thread, read, slot, url.pointer().cast(), &mut candidate);
+ published = if found {
+ candidate
+ } else {
+ PublishedSvgFilter {
+ failed: true,
+ ..Default::default()
+ }
};
if published.failed {
break;
diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs
index 580f3960243..28327370651 100644
--- a/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs
+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/svg.rs
@@ -549,7 +549,12 @@ pub(crate) fn svg_image_unquantized_device_rect(
// https://svgwg.org/svg2-draft/coords.html#PreserveAspectRatioAttribute
// Where an image of `natural_size` is drawn to fit `image_rect` as its preserveAspectRatio says, taking its own size as
// its view box.
-fn image_draw_rect(image_rect: FloatRect, natural_size: (f32, f32), align: u8, meet_or_slice: u8) -> FloatRect {
+pub(crate) fn image_draw_rect(
+ image_rect: FloatRect,
+ natural_size: (f32, f32),
+ align: u8,
+ meet_or_slice: u8,
+) -> FloatRect {
use crate::layout::svg_formatting_context::{
MEET_OR_SLICE_SLICE, PRESERVE_ASPECT_RATIO_NONE, PRESERVE_ASPECT_RATIO_X_MIN_Y_MIN,
};
diff --git a/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs b/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs
index d49912454fe..7fd762985a5 100644
--- a/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs
+++ b/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs
@@ -345,7 +345,12 @@ fn captured_snap_area_rect(
None
}
-fn map_rect_through_node_transform(arena: &impl PaintRead, node: NodeSlotId, rect: CssPixelRect) -> CssPixelRect {
+/// `rect` mapped through the CSS transform of `node`, or as it is when `node` has none.
+pub(crate) fn map_rect_through_node_transform(
+ arena: &impl PaintRead,
+ node: NodeSlotId,
+ rect: CssPixelRect,
+) -> CssPixelRect {
if !arena.paintable_row_is_populated(node) {
return rect;
}
diff --git a/Libraries/LibWeb/Rust/src/painting/svg_filter.rs b/Libraries/LibWeb/Rust/src/painting/svg_filter.rs
index ce2ed48163f..7a902914b6a 100644
--- a/Libraries/LibWeb/Rust/src/painting/svg_filter.rs
+++ b/Libraries/LibWeb/Rust/src/painting/svg_filter.rs
@@ -14,9 +14,13 @@
use std::collections::HashMap;
use libgfx_rust::filter::{ChannelSelector, ChannelTable, Filter, TurbulenceType};
-use libgfx_rust::{CompositingAndBlendingOperator, IntRect, IntSize, InterpolationColorSpace};
+use libgfx_rust::{CompositingAndBlendingOperator, FloatRect, IntSize, InterpolationColorSpace};
-use crate::painting::host::visual_context::{FfiSvgFilterPrimitiveKind, SvgFilterPrimitiveValues};
+use crate::layout::svg_formatting_context::FfiSvgNumberPercentage;
+use crate::painting::host::visual_context::{
+ FfiSvgFilterPrimitiveKind, FfiSvgFilterRegion, SUBREGION_SPECIFIES_HEIGHT, SUBREGION_SPECIFIES_WIDTH,
+ SUBREGION_SPECIFIES_X, SUBREGION_SPECIFIES_Y, SvgFilterPrimitiveValues,
+};
// https://drafts.fxtf.org/filter-effects-1/#InterfaceSVGFEColorMatrixElement
const COLOR_MATRIX_TYPE_MATRIX: u16 = 1;
@@ -71,12 +75,58 @@ pub(crate) struct SvgFilterPrimitive {
pub image_frame: Option<libgfx_rust::image_frame::ImageFrameHandle>,
}
+/// Where an element that a `<filter>` applies to puts the filter: what the filter region and the
+/// primitive subregions resolve against, in the space the element paints in before the device
+/// pixel scale.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct SvgFilterTarget {
+ pub region: FfiSvgFilterRegion,
+ pub object_bounding_box: FloatRect,
+ /// The origin of the userSpaceOnUse coordinate system.
+ pub user_space_origin: (f32, f32),
+ /// The size that userSpaceOnUse percentages resolve against.
+ pub user_space_viewport: (f32, f32),
+}
+
+impl SvgFilterTarget {
+ /// A rect given in `units_are_object_bounding_box` units, in the target's paint space.
+ // https://svgwg.org/svg2-draft/coords.html#ObjectBoundingBoxUnits
+ fn resolve(
+ &self,
+ units_are_object_bounding_box: bool,
+ x: FfiSvgNumberPercentage,
+ y: FfiSvgNumberPercentage,
+ width: FfiSvgNumberPercentage,
+ height: FfiSvgNumberPercentage,
+ ) -> (f32, f32, f32, f32) {
+ if units_are_object_bounding_box {
+ // A number and a percentage alike are a fraction of the bounding box.
+ let bounding_box = self.object_bounding_box;
+ return (
+ bounding_box.x + x.value * bounding_box.width,
+ bounding_box.y + y.value * bounding_box.height,
+ width.value * bounding_box.width,
+ height.value * bounding_box.height,
+ );
+ }
+ let (viewport_width, viewport_height) = self.user_space_viewport;
+ (
+ self.user_space_origin.0 + x.resolve_relative_to(viewport_width),
+ self.user_space_origin.1 + y.resolve_relative_to(viewport_height),
+ width.resolve_relative_to(viewport_width),
+ height.resolve_relative_to(viewport_height),
+ )
+ }
+}
+
/// An intermediate result of the graph: the filter producing it, or the source graphic when
-/// absent, and the color space its pixels are in. The default is the source graphic itself.
+/// absent, the color space its pixels are in, and the subregion it covers, in device pixels,
+/// where the graph knows its target. The default is the source graphic itself.
#[derive(Clone, Default)]
struct FilterResult {
filter: Option<Filter>,
color_space: InterpolationColorSpace,
+ subregion: Option<FloatRect>,
}
impl FilterResult {
@@ -84,6 +134,7 @@ impl FilterResult {
Self {
filter: Some(filter),
color_space,
+ subregion: None,
}
}
@@ -125,7 +176,13 @@ pub(crate) struct SvgFilterGraphBuilder {
/// latter. The layer replaying the filter applies the accumulated transform, so only the
/// device pixel ratio converts here.
scale: f32,
- image_target: Option<(IntRect, u8)>,
+ image_rendering: u8,
+ /// Where an feImage draws when the graph doesn't know its target.
+ image_rect_without_target: Option<FloatRect>,
+ /// The filter region, in device pixels, once the graph knows its target. Without one, the graph
+ /// neither clips to a region nor to subregions, and has nowhere to draw an feImage.
+ filter_region: Option<FloatRect>,
+ target: Option<SvgFilterTarget>,
results_by_name: HashMap<Vec<u16>, FilterResult>,
/// The output of the last primitive, which is what an unnamed `in` refers to and what the
/// filter as a whole produces.
@@ -136,20 +193,73 @@ impl SvgFilterGraphBuilder {
pub(crate) fn new(device_pixels_per_css_pixel: f64) -> Self {
Self {
scale: device_pixels_per_css_pixel as f32,
- image_target: None,
+ image_rendering: 0,
+ image_rect_without_target: None,
+ filter_region: None,
+ target: None,
results_by_name: HashMap::new(),
last_result: FilterResult::default(),
}
}
- pub(crate) fn set_image_target(&mut self, dest_rect: IntRect, image_rendering: u8) {
- self.image_target = Some((dest_rect, image_rendering));
+ pub(crate) fn set_target(&mut self, target: SvgFilterTarget, image_rendering: u8) {
+ let region = target.region;
+ let (x, y, width, height) = target.resolve(
+ region.filter_units_are_object_bounding_box,
+ region.x,
+ region.y,
+ region.width,
+ region.height,
+ );
+ self.filter_region = Some(self.to_device_rect(x, y, width, height));
+ self.target = Some(target);
+ self.image_rendering = image_rendering;
+ }
+
+ /// Draws an feImage over `rect` for a graph that has no target to resolve subregions against.
+ pub(crate) fn set_image_rect_without_target(&mut self, rect: FloatRect, image_rendering: u8) {
+ self.image_rect_without_target = Some(rect);
+ self.image_rendering = image_rendering;
+ }
+
+ fn to_device_rect(&self, x: f32, y: f32, width: f32, height: f32) -> FloatRect {
+ FloatRect::new(x * self.scale, y * self.scale, width * self.scale, height * self.scale)
}
pub(crate) fn push(&mut self, mut primitive: SvgFilterPrimitive) {
let result_name = std::mem::take(&mut primitive.result);
- let Some(result) = self.primitive_result(primitive) else {
- return;
+ let subregion = self.subregion_of(&primitive);
+ let result = match subregion {
+ // https://drafts.csswg.org/filter-effects-1/#FilterPrimitiveSubRegion
+ // If the filter primitive subregion has a negative or zero width or height, the effect of the filter
+ // primitive is disabled.
+ // NB: Its result is then transparent black, which the rest of the graph still takes as an input.
+ Some(subregion) if subregion.width <= 0.0 || subregion.height <= 0.0 => FilterResult {
+ filter: Some(Filter::Crop {
+ rect: FloatRect::new(0.0, 0.0, 0.0, 0.0),
+ input: None,
+ }),
+ color_space: InterpolationColorSpace::SRGB,
+ subregion: Some(subregion),
+ },
+ _ => {
+ let Some(mut result) = self.primitive_result(primitive, subregion) else {
+ return;
+ };
+ // The filter primitive subregion acts as a hard clip clipping rectangle on the filter primitive result.
+ // All intermediate offscreens are defined to not exceed the intersection of the filter primitive
+ // subregion with the filter region.
+ // NB: The result keeps the subregion as defined rather than as clipped, since that's what a later
+ // primitive's default subregion is the union of.
+ if let (Some(subregion), Some(filter_region)) = (subregion, self.filter_region) {
+ result.filter = Some(Filter::Crop {
+ rect: subregion.intersected(filter_region),
+ input: boxed(result.filter),
+ });
+ result.subregion = Some(subregion);
+ }
+ result
+ }
};
if !result_name.is_empty() {
self.results_by_name.insert(result_name, result.clone());
@@ -163,25 +273,128 @@ impl SvgFilterGraphBuilder {
self.last_result.converted_to(InterpolationColorSpace::SRGB)
}
+ /// The source graphic, clipped to the filter region.
+ // https://drafts.csswg.org/filter-effects-1/#FilterPrimitiveSubRegion
+ // The filter region acts as a hard clip clipping rectangle on the filter primitive's input image(s).
+ fn source_graphic(&self) -> Option<Filter> {
+ self.filter_region.map(|region| Filter::Crop {
+ rect: region,
+ input: None,
+ })
+ }
+
+ fn is_standard_input(name: &[u16]) -> bool {
+ name == SOURCE_GRAPHIC || name == SOURCE_ALPHA
+ }
+
// https://www.w3.org/TR/filter-effects-1/#element-attrdef-filter-primitive-in
fn resolve_input(&self, name: &[u16]) -> FilterResult {
// FIXME: Add missing inputs (BackgroundImage, BackgroundAlpha, FillPaint and StrokePaint).
if name == SOURCE_GRAPHIC {
- return FilterResult::default();
+ return FilterResult {
+ filter: self.source_graphic(),
+ color_space: InterpolationColorSpace::SRGB,
+ subregion: self.filter_region,
+ };
}
if name == SOURCE_ALPHA {
- return FilterResult::new(
- Filter::ColorMatrix {
+ return FilterResult {
+ filter: Some(Filter::ColorMatrix {
matrix: ALPHA_ONLY_MATRIX,
- input: None,
- },
- InterpolationColorSpace::SRGB,
- );
+ input: boxed(self.source_graphic()),
+ }),
+ color_space: InterpolationColorSpace::SRGB,
+ subregion: self.filter_region,
+ };
+ }
+ if let Some(result) = self.results_by_name.get(name) {
+ return result.clone();
+ }
+ // An unnamed or unknown input takes the previous result, which before the first primitive is the source
+ // graphic.
+ if self.last_result.filter.is_none() && self.last_result.subregion.is_none() {
+ return self.resolve_input(&SOURCE_GRAPHIC);
}
- self.results_by_name
- .get(name)
- .cloned()
- .unwrap_or_else(|| self.last_result.clone())
+ self.last_result.clone()
+ }
+
+ /// The names of the inputs `primitive` reads.
+ fn input_names(primitive: &SvgFilterPrimitive) -> Vec<&[u16]> {
+ match primitive.values.kind {
+ FfiSvgFilterPrimitiveKind::Flood
+ | FfiSvgFilterPrimitiveKind::Image
+ | FfiSvgFilterPrimitiveKind::Turbulence => Vec::new(),
+ FfiSvgFilterPrimitiveKind::Blend
+ | FfiSvgFilterPrimitiveKind::Composite
+ | FfiSvgFilterPrimitiveKind::DisplacementMap => vec![&primitive.in1, &primitive.in2],
+ FfiSvgFilterPrimitiveKind::Merge => primitive.merge_inputs.iter().map(Vec::as_slice).collect(),
+ FfiSvgFilterPrimitiveKind::ColorMatrix
+ | FfiSvgFilterPrimitiveKind::ComponentTransfer
+ | FfiSvgFilterPrimitiveKind::DropShadow
+ | FfiSvgFilterPrimitiveKind::GaussianBlur
+ | FfiSvgFilterPrimitiveKind::Morphology
+ | FfiSvgFilterPrimitiveKind::Offset => vec![&primitive.in1],
+ }
+ }
+
+ /// The filter primitive subregion of `primitive`, in device pixels, or `None` where the graph
+ /// doesn't know its target.
+ // https://drafts.csswg.org/filter-effects-1/#FilterPrimitiveSubRegion
+ fn subregion_of(&self, primitive: &SvgFilterPrimitive) -> Option<FloatRect> {
+ let target = self.target?;
+ let filter_region = self.filter_region?;
+ // x, y, width and height default to the union (i.e., tightest fitting bounding box) of the subregions defined
+ // for all referenced nodes. If there are no referenced nodes (e.g., for feImage or feTurbulence), or one or
+ // more of the referenced nodes is a standard input (one of SourceGraphic, SourceAlpha, BackgroundImage,
+ // BackgroundAlpha, FillPaint or StrokePaint), or for feTile (which is special because its principal function
+ // is to replicate the referenced node in X and Y and thereby produce a usually larger result), the default
+ // subregion is 0%, 0%, 100%, 100%, where as a special-case the percentages are relative to the dimensions of
+ // the filter region, thus making the default filter primitive subregion equal to the filter region.
+ let input_names = Self::input_names(primitive);
+ let default_subregion =
+ if input_names.is_empty() || input_names.iter().any(|name| Self::is_standard_input(name)) {
+ filter_region
+ } else {
+ input_names
+ .iter()
+ .map(|name| self.resolve_input(name).subregion.unwrap_or(filter_region))
+ .reduce(FloatRect::united)
+ .unwrap_or(filter_region)
+ };
+
+ let values = &primitive.values;
+ let units_are_object_bounding_box = target.region.primitive_units_are_object_bounding_box;
+ let (x, y, width, height) = target.resolve(
+ units_are_object_bounding_box,
+ values.subregion_x,
+ values.subregion_y,
+ values.subregion_width,
+ values.subregion_height,
+ );
+ let specified = |bit| values.subregion_specified & bit != 0;
+ let resolved = self.to_device_rect(x, y, width, height);
+ Some(FloatRect::new(
+ if specified(SUBREGION_SPECIFIES_X) {
+ resolved.x
+ } else {
+ default_subregion.x
+ },
+ if specified(SUBREGION_SPECIFIES_Y) {
+ resolved.y
+ } else {
+ default_subregion.y
+ },
+ if specified(SUBREGION_SPECIFIES_WIDTH) {
+ resolved.width
+ } else {
+ default_subregion.width
+ },
+ if specified(SUBREGION_SPECIFIES_HEIGHT) {
+ resolved.height
+ } else {
+ default_subregion.height
+ },
+ ))
}
fn resolve_input_in(&self, name: &[u16], color_space: InterpolationColorSpace) -> Option<Filter> {
@@ -190,7 +403,7 @@ impl SvgFilterGraphBuilder {
/// The result of one primitive, or `None` for a primitive that produces nothing and leaves the
/// graph as it was.
- fn primitive_result(&self, primitive: SvgFilterPrimitive) -> Option<FilterResult> {
+ fn primitive_result(&self, primitive: SvgFilterPrimitive, subregion: Option<FloatRect>) -> Option<FilterResult> {
let values = primitive.values;
let space = values.operating_color_space;
let in_space = |filter| FilterResult::new(filter, space);
@@ -273,19 +486,57 @@ impl SvgFilterGraphBuilder {
_ => return None,
}
}
+ // https://drafts.csswg.org/filter-effects-1/#feImageElement
+ // The image is rendered according to the behavior of the image element, which fits it into the filter
+ // primitive subregion as its preserveAspectRatio attribute says.
FfiSvgFilterPrimitiveKind::Image => {
- let (dest_rect, image_rendering) = self.image_target?;
- let frame = primitive.image_frame.as_ref()?;
+ // An image that can't be rendered produces transparent black.
+ let Some(frame) = primitive.image_frame.as_ref() else {
+ return Some(FilterResult::new(
+ Filter::Crop {
+ rect: FloatRect::new(0.0, 0.0, 0.0, 0.0),
+ input: None,
+ },
+ InterpolationColorSpace::SRGB,
+ ));
+ };
let src_rect = values.image_src_rect;
+ let Some(subregion) = subregion else {
+ let dest_rect = self.image_rect_without_target?;
+ return Some(FilterResult::new(
+ Filter::Image {
+ frame_id: frame.id(),
+ src_rect,
+ dest_rect,
+ scaling_mode: crate::painting::record::paint::background::to_gfx_scaling_mode(
+ self.image_rendering,
+ (src_rect.width, src_rect.height),
+ (dest_rect.width.round() as i32, dest_rect.height.round() as i32),
+ ),
+ },
+ InterpolationColorSpace::SRGB,
+ ));
+ };
+ let natural_size = if values.image_natural_width > 0.0 && values.image_natural_height > 0.0 {
+ (values.image_natural_width, values.image_natural_height)
+ } else {
+ (src_rect.width as f32, src_rect.height as f32)
+ };
+ let draw_rect = crate::painting::record::paint::svg::image_draw_rect(
+ subregion,
+ natural_size,
+ values.image_preserve_aspect_ratio_align,
+ values.image_preserve_aspect_ratio_meet_or_slice,
+ );
FilterResult::new(
Filter::Image {
frame_id: frame.id(),
src_rect,
- dest_rect: dest_rect.to_float(),
+ dest_rect: draw_rect,
scaling_mode: crate::painting::record::paint::background::to_gfx_scaling_mode(
- image_rendering,
+ self.image_rendering,
(src_rect.width, src_rect.height),
- (dest_rect.width, dest_rect.height),
+ (draw_rect.width.round() as i32, draw_rect.height.round() as i32),
),
},
InterpolationColorSpace::SRGB,
@@ -399,9 +650,18 @@ impl SvgFilterGraphBuilder {
base_frequency_y: values.base_frequency_y / self.scale,
num_octaves: values.num_octaves,
seed: values.seed,
- tile_stitch_size: IntSize {
- width: (values.stitch_tile_width * self.scale).round() as i32,
- height: (values.stitch_tile_height * self.scale).round() as i32,
+ // https://drafts.csswg.org/filter-effects-1/#element-attrdef-feturbulence-stitchtiles
+ // stitch: the user agent will automatically attempt to synthesize Perlin noise functions that are
+ // continuous at the border of the filter primitive subregion.
+ tile_stitch_size: match subregion {
+ Some(subregion) if values.turbulence_stitches_tiles => IntSize {
+ width: subregion.width.round() as i32,
+ height: subregion.height.round() as i32,
+ },
+ _ => IntSize {
+ width: (values.stitch_tile_width * self.scale).round() as i32,
+ height: (values.stitch_tile_height * self.scale).round() as i32,
+ },
},
}),
FfiSvgFilterPrimitiveKind::DisplacementMap => {
@@ -490,6 +750,174 @@ mod tests {
builder.finish()
}
+ fn number(value: f32) -> FfiSvgNumberPercentage {
+ FfiSvgNumberPercentage {
+ value,
+ is_percentage: false,
+ }
+ }
+
+ // A 100x50 box at (10, 20), and a filter region of x=0, y=0, width=200%, height=200% around it.
+ fn target(primitive_units_are_object_bounding_box: bool) -> SvgFilterTarget {
+ SvgFilterTarget {
+ region: FfiSvgFilterRegion {
+ filter_units_are_object_bounding_box: true,
+ primitive_units_are_object_bounding_box,
+ x: number(0.0),
+ y: number(0.0),
+ width: number(2.0),
+ height: number(2.0),
+ },
+ object_bounding_box: FloatRect::new(10.0, 20.0, 100.0, 50.0),
+ user_space_origin: (10.0, 20.0),
+ user_space_viewport: (100.0, 50.0),
+ }
+ }
+
+ fn targeted_graph(
+ target: SvgFilterTarget,
+ primitives: impl IntoIterator<Item = SvgFilterPrimitive>,
+ ) -> Option<Filter> {
+ let mut builder = SvgFilterGraphBuilder::new(2.0);
+ builder.set_target(target, 0);
+ for primitive in primitives {
+ builder.push(primitive);
+ }
+ builder.finish()
+ }
+
+ fn flood() -> SvgFilterPrimitive {
+ let mut flood = primitive(FfiSvgFilterPrimitiveKind::Flood, InterpolationColorSpace::SRGB);
+ flood.values.flood_opacity = 1.0;
+ flood
+ }
+
+ fn with_subregion(
+ mut primitive: SvgFilterPrimitive,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ ) -> SvgFilterPrimitive {
+ primitive.values.subregion_x = number(x);
+ primitive.values.subregion_y = number(y);
+ primitive.values.subregion_width = number(width);
+ primitive.values.subregion_height = number(height);
+ primitive.values.subregion_specified =
+ SUBREGION_SPECIFIES_X | SUBREGION_SPECIFIES_Y | SUBREGION_SPECIFIES_WIDTH | SUBREGION_SPECIFIES_HEIGHT;
+ primitive
+ }
+
+ fn flood_filter() -> Filter {
+ Filter::Flood {
+ color: Default::default(),
+ opacity: 1.0,
+ }
+ }
+
+ #[test]
+ fn a_primitive_without_inputs_fills_the_filter_region() {
+ assert_eq!(
+ targeted_graph(target(false), [flood()]),
+ Some(Filter::Crop {
+ rect: FloatRect::new(20.0, 40.0, 400.0, 200.0),
+ input: Some(Box::new(flood_filter())),
+ })
+ );
+ }
+
+ #[test]
+ fn a_subregion_resolves_in_primitive_units() {
+ // Fractions of the bounding box under objectBoundingBox, user units from the box's origin under userSpaceOnUse.
+ assert_eq!(
+ targeted_graph(target(true), [with_subregion(flood(), 0.25, 0.5, 0.5, 0.25)]),
+ Some(Filter::Crop {
+ rect: FloatRect::new(70.0, 90.0, 100.0, 25.0),
+ input: Some(Box::new(flood_filter())),
+ })
+ );
+ assert_eq!(
+ targeted_graph(target(false), [with_subregion(flood(), 5.0, 5.0, 20.0, 10.0)]),
+ Some(Filter::Crop {
+ rect: FloatRect::new(30.0, 50.0, 40.0, 20.0),
+ input: Some(Box::new(flood_filter())),
+ })
+ );
+ }
+
+ #[test]
+ fn an_empty_subregion_disables_the_primitive_but_not_the_graph() {
+ let mut empty_flood = with_subregion(flood(), 0.0, 0.0, 0.0, 10.0);
+ empty_flood.result = name("empty");
+ let mut merge = primitive(FfiSvgFilterPrimitiveKind::Merge, InterpolationColorSpace::SRGB);
+ merge.merge_inputs = vec![name("empty"), name("SourceGraphic")];
+ let region = FloatRect::new(20.0, 40.0, 400.0, 200.0);
+ assert_eq!(
+ targeted_graph(target(false), [empty_flood, merge]),
+ Some(Filter::Crop {
+ rect: region,
+ input: Some(Box::new(Filter::Merge {
+ inputs: vec![
+ Some(Filter::Crop {
+ rect: FloatRect::new(0.0, 0.0, 0.0, 0.0),
+ input: None,
+ }),
+ Some(Filter::Crop {
+ rect: region,
+ input: None,
+ }),
+ ],
+ })),
+ })
+ );
+ }
+
+ #[test]
+ fn a_default_subregion_is_the_union_of_the_input_subregions() {
+ let mut half = with_subregion(flood(), 0.0, 0.0, 50.0, 50.0);
+ half.result = name("half");
+ let half_rect = FloatRect::new(20.0, 40.0, 100.0, 100.0);
+ assert_eq!(
+ targeted_graph(target(false), [half, blur("half", 1.0, "")]),
+ Some(Filter::Crop {
+ rect: half_rect,
+ input: Some(Box::new(Filter::gaussian_blur(
+ 2.0,
+ 2.0,
+ Some(Filter::Crop {
+ rect: half_rect,
+ input: Some(Box::new(flood_filter())),
+ }),
+ ))),
+ })
+ );
+ }
+
+ #[test]
+ fn a_default_subregion_takes_the_input_subregion_as_defined_not_as_clipped() {
+ // The flood's subregion reaches past the left edge of the filter region, which clips its output but not the
+ // width the blur's subregion defaults to.
+ let mut overhanging = with_subregion(flood(), -50.0, 0.0, 100.0, 100.0);
+ overhanging.result = name("overhanging");
+ let mut shifted = blur("overhanging", 1.0, "");
+ shifted.values.subregion_x = number(0.0);
+ shifted.values.subregion_specified = SUBREGION_SPECIFIES_X;
+ assert_eq!(
+ targeted_graph(target(false), [overhanging, shifted]),
+ Some(Filter::Crop {
+ rect: FloatRect::new(20.0, 40.0, 200.0, 200.0),
+ input: Some(Box::new(Filter::gaussian_blur(
+ 2.0,
+ 2.0,
+ Some(Filter::Crop {
+ rect: FloatRect::new(20.0, 40.0, 100.0, 200.0),
+ input: Some(Box::new(flood_filter())),
+ }),
+ ))),
+ })
+ );
+ }
+
#[test]
fn an_empty_filter_produces_nothing() {
assert_eq!(graph([], 1.0), None);
diff --git a/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rs b/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rs
index 16d8f42fc4f..ed80d4e0107 100644
--- a/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rs
+++ b/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rs
@@ -58,6 +58,7 @@ pub enum PublishedSvgPaintServer {
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct PublishedSvgFilter {
pub failed: bool,
+ pub region: crate::painting::host::visual_context::FfiSvgFilterRegion,
pub primitives: Vec<SvgFilterPrimitive>,
}
@@ -344,7 +345,7 @@ mod tests {
let slot = NodeSlotId::new(1, 1);
let filter = |failed| PublishedSvgFilter {
failed,
- primitives: Vec::new(),
+ ..Default::default()
};
resources.set_enrolled_kinds(slot, SvgPaintResourceKind::Filter.bit());
assert!(resources.publish_filter(slot, SvgPaintResourceKind::Filter, filter(false)));
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/node_values.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/node_values.rs
index aaa9850bb6a..061bcbf0164 100644
--- a/Libraries/LibWeb/Rust/src/painting/visual_context/node_values.rs
+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/node_values.rs
@@ -580,6 +580,144 @@ fn svg_filter_bounds(layout_arena: &impl PaintRead, slot: NodeSlotId) -> Option<
.map(|geometry| crate::layout::svg_formatting_context::css_pixel_rect_of(geometry.viewport_user_rect))
}
+/// What a `<filter>` applied to the box in `slot` resolves its region and subregions against. An SVG element's own user
+/// space is the space it paints in, and its object bounding box comes from its geometry. Any other box has its user
+/// space start at its border box's top-left corner, one unit to a CSS pixel, with its border box as the viewport its
+/// percentages resolve against. Its object bounding box is its border box, grown to what overflows it unclipped (a
+/// transformed child, e.g.), so the filter region covers what the box paints.
+// https://drafts.csswg.org/filter-effects-1/#FilterEffectsRegion
+fn svg_filter_target(
+ layout_arena: &impl PaintRead,
+ slot: NodeSlotId,
+ region: crate::painting::host::visual_context::FfiSvgFilterRegion,
+) -> crate::painting::svg_filter::SvgFilterTarget {
+ // NB: An outer <svg> element is a CSS box, whose effects apply above the transform its viewBox sets up.
+ let is_outer_svg_element =
+ layout_arena.node_kind_if_live(slot) == Some(crate::layout::node_data::NodeKind::SVGSVGBox);
+ if let Some(geometry) = paintable_geometry::committed_svg_geometry(layout_arena, slot)
+ && !is_outer_svg_element
+ {
+ return crate::painting::svg_filter::SvgFilterTarget {
+ region,
+ object_bounding_box: geometry.object_bounding_box,
+ user_space_origin: (0.0, 0.0),
+ user_space_viewport: (geometry.viewport_user_rect.width, geometry.viewport_user_rect.height),
+ };
+ }
+ let to_float_rect = |rect: crate::css::css_pixels::CssPixelRect| {
+ libgfx_rust::FloatRect::new(
+ rect.x.to_float(),
+ rect.y.to_float(),
+ rect.width.to_float(),
+ rect.height.to_float(),
+ )
+ };
+ let border_box = to_float_rect(paintable_geometry::absolute_border_box_rect(layout_arena, slot));
+ // The axes along which a box clips what overflows it. Only "overflow: clip" can clip one axis alone.
+ let clipped_axes = |node: NodeSlotId| {
+ layout_arena.node_style_if_live(node).map_or((false, false), |style| {
+ use crate::css::css_enums::overflow;
+ (
+ style.overflow_x() != overflow::VISIBLE,
+ style.overflow_y() != overflow::VISIBLE,
+ )
+ })
+ };
+ let mut object_bounding_box = border_box;
+ let (clips_x, clips_y) = clipped_axes(slot);
+ if !(clips_x && clips_y) && !is_outer_svg_element {
+ let own_clip = AxisClip {
+ x: clips_x.then_some((border_box.x, border_box.x + border_box.width)),
+ y: clips_y.then_some((border_box.y, border_box.y + border_box.height)),
+ };
+ let mut grow = |rect: libgfx_rust::FloatRect, clip: AxisClip| {
+ let rect = clip.applied_to(rect);
+ if !rect.is_empty() {
+ object_bounding_box = object_bounding_box.united(rect);
+ }
+ };
+ // NB: Scrollable overflow covers transformed descendants, but not what overflows up or to the left, which
+ // the border boxes of the descendants cover once mapped through their transforms and their ancestors'.
+ if let Some(overflow) = paintable_geometry::scrollable_overflow_rect(layout_arena, slot) {
+ grow(to_float_rect(overflow), own_clip);
+ }
+ let mut pending: Vec<(NodeSlotId, AxisClip)> =
+ layout_arena.children(slot).map(|child| (child, own_clip)).collect();
+ while let Some((descendant, clip)) = pending.pop() {
+ let mut children_clip = clip;
+ if layout_arena.paintable_row_is_populated(descendant)
+ && layout_arena
+ .node_kind_if_live(descendant)
+ .is_some_and(crate::layout::node_facts::kind_is_box)
+ {
+ let mut rect = paintable_geometry::absolute_border_box_rect(layout_arena, descendant);
+ let mut transformed = Some(descendant);
+ while let Some(node) = transformed.filter(|node| *node != slot) {
+ rect = crate::painting::scroll_snap::map_rect_through_node_transform(layout_arena, node, rect);
+ transformed = layout_arena.node_parent_if_live(node);
+ }
+ let rect = to_float_rect(rect);
+ grow(rect, clip);
+ // What a descendant clips doesn't paint beyond it along the axes it clips.
+ let (descendant_clips_x, descendant_clips_y) = clipped_axes(descendant);
+ if descendant_clips_x && descendant_clips_y {
+ continue;
+ }
+ children_clip = clip.narrowed_to(rect, descendant_clips_x, descendant_clips_y);
+ }
+ pending.extend(layout_arena.children(descendant).map(|child| (child, children_clip)));
+ }
+ }
+ crate::painting::svg_filter::SvgFilterTarget {
+ region,
+ object_bounding_box,
+ user_space_origin: (border_box.x, border_box.y),
+ user_space_viewport: (border_box.width, border_box.height),
+ }
+}
+
+/// The ranges a box's descendants are cut down to along the axes some box between them clips, as start and end
+/// coordinates.
+#[derive(Clone, Copy)]
+struct AxisClip {
+ x: Option<(f32, f32)>,
+ y: Option<(f32, f32)>,
+}
+
+impl AxisClip {
+ fn applied_to(self, rect: libgfx_rust::FloatRect) -> libgfx_rust::FloatRect {
+ let clamp = |start: f32, size: f32, range: Option<(f32, f32)>| match range {
+ Some((low, high)) => {
+ let clamped_start = start.max(low);
+ (clamped_start, ((start + size).min(high) - clamped_start).max(0.0))
+ }
+ None => (start, size),
+ };
+ let (x, width) = clamp(rect.x, rect.width, self.x);
+ let (y, height) = clamp(rect.y, rect.height, self.y);
+ libgfx_rust::FloatRect::new(x, y, width, height)
+ }
+
+ /// This clip, further limited to `rect` along the axes a box with that border box clips.
+ fn narrowed_to(self, rect: libgfx_rust::FloatRect, clips_x: bool, clips_y: bool) -> Self {
+ let narrowed = |range: Option<(f32, f32)>, low: f32, high: f32| {
+ Some(range.map_or((low, high), |(start, end)| (start.max(low), end.min(high))))
+ };
+ Self {
+ x: if clips_x {
+ narrowed(self.x, rect.x, rect.x + rect.width)
+ } else {
+ self.x
+ },
+ y: if clips_y {
+ narrowed(self.y, rect.y, rect.y + rect.height)
+ } else {
+ self.y
+ },
+ }
+ }
+}
+
fn published_svg_filter(
layout_arena: &impl PaintRead,
slot: NodeSlotId,
@@ -601,14 +739,24 @@ fn published_svg_filter(
}
let mut builder = crate::painting::svg_filter::SvgFilterGraphBuilder::new(device_pixels_per_css_pixel);
if layout_arena.paintable_row_is_populated(slot) {
- let absolute_rect = paintable_geometry::absolute_rect(layout_arena, slot);
- let dest_rect = libgfx_rust::enclosing_int_rect(libgfx_rust::FloatRect::new(
- absolute_rect.x.to_float(),
- absolute_rect.y.to_float(),
- absolute_rect.width.to_float(),
- absolute_rect.height.to_float(),
- ));
- builder.set_image_target(dest_rect, style.image_rendering());
+ if kind == crate::painting::svg_paint_resources::SvgPaintResourceKind::Filter {
+ builder.set_target(
+ svg_filter_target(layout_arena, slot, published.region),
+ style.image_rendering(),
+ );
+ } else {
+ // FIXME: Resolve the filter region and subregions of a backdrop filter too, once it's settled what they're
+ // relative to there. Until then, an feImage draws over the box.
+ let absolute_rect = paintable_geometry::absolute_rect(layout_arena, slot);
+ let scale = device_pixels_per_css_pixel as f32;
+ let image_rect = libgfx_rust::enclosing_int_rect(libgfx_rust::FloatRect::new(
+ absolute_rect.x.to_float() * scale,
+ absolute_rect.y.to_float() * scale,
+ absolute_rect.width.to_float() * scale,
+ absolute_rect.height.to_float() * scale,
+ ));
+ builder.set_image_rect_without_target(image_rect.to_float(), style.image_rendering());
+ }
}
for primitive in published.primitives.iter().cloned() {
builder.push(primitive);
diff --git a/Libraries/LibWeb/SVG/SVGFilterElement.cpp b/Libraries/LibWeb/SVG/SVGFilterElement.cpp
index 04c6c3fe6b3..a7c613b8584 100644
--- a/Libraries/LibWeb/SVG/SVGFilterElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGFilterElement.cpp
@@ -11,9 +11,11 @@
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/DOM/Text.h>
#include <LibWeb/HTML/DecodedImageData.h>
+#include <LibWeb/Layout/LayoutRustBridge.h>
#include <LibWeb/Layout/LayoutRustFFI.h>
#include <LibWeb/Layout/Node.h>
#include <LibWeb/Painting/BoxViews.h>
+#include <LibWeb/SVG/AttributeParsing.h>
#include <LibWeb/SVG/SVGComponentTransferFunctionElement.h>
#include <LibWeb/SVG/SVGFEBlendElement.h>
#include <LibWeb/SVG/SVGFEColorMatrixElement.h>
@@ -34,6 +36,7 @@
#include <LibWeb/SVG/SVGFEOffsetElement.h>
#include <LibWeb/SVG/SVGFETurbulenceElement.h>
#include <LibWeb/SVG/SVGFilterElement.h>
+#include <LibWeb/SVG/SVGLength.h>
#include <LibWeb/SVG/SVGUnitTypes.h>
namespace Web::SVG {
@@ -77,11 +80,64 @@ void SVGFilterElement::push_primitives(void* sink, Gfx::IntSize dest_size)
return CSS::to_interpolation_color_space(color_interpolation_filters);
};
+ // https://drafts.csswg.org/filter-effects-1/#FilterEffectsRegion
+ // A coordinate or length attribute, as a number of user units or a percentage.
+ // FIXME: Resolve font-relative lengths and math functions too.
+ auto parsed_attribute = [](DOM::Element const& element, Utf16FlyString const& name) -> Optional<NumberPercentage> {
+ auto value = element.get_attribute(name);
+ if (!value.has_value())
+ return {};
+ auto parsed = SVGLength::parse_scalar_value(*value);
+ if (!parsed.has_value())
+ return {};
+ switch (parsed->kind()) {
+ case SVGLengthValue::Kind::Number:
+ return NumberPercentage::create_number(parsed->value());
+ case SVGLengthValue::Kind::Percentage:
+ return NumberPercentage::create_percentage(parsed->value());
+ case SVGLengthValue::Kind::Length: {
+ auto length = parsed->to_length();
+ // A zero length is zero in any unit, so it resolves even where its unit doesn't yet.
+ if (length.raw_value() == 0)
+ return NumberPercentage::create_number(0);
+ if (!length.is_absolute())
+ return {};
+ return NumberPercentage::create_number(length.absolute_length_to_px_without_rounding());
+ }
+ }
+ VERIFY_NOT_REACHED();
+ };
+ Layout::RustFFI::FfiSvgFilterRegion region {
+ .filter_units_are_object_bounding_box = filter_units()->base_val() == to_underlying(SVGUnitType::ObjectBoundingBox),
+ .primitive_units_are_object_bounding_box = primitive_units()->base_val() == to_underlying(SVGUnitType::ObjectBoundingBox),
+ // If the attribute is not specified, the effect is as if a value of -10% (x, y) or 120% (width, height) were
+ // specified.
+ .x = Layout::to_ffi_number_percentage(parsed_attribute(*this, AttributeNames::x).value_or(NumberPercentage::create_percentage(-10))),
+ .y = Layout::to_ffi_number_percentage(parsed_attribute(*this, AttributeNames::y).value_or(NumberPercentage::create_percentage(-10))),
+ .width = Layout::to_ffi_number_percentage(parsed_attribute(*this, AttributeNames::width).value_or(NumberPercentage::create_percentage(120))),
+ .height = Layout::to_ffi_number_percentage(parsed_attribute(*this, AttributeNames::height).value_or(NumberPercentage::create_percentage(120))),
+ };
+ Layout::RustFFI::layout_arena_paint_set_svg_filter_region(sink, &region);
+
for_each_child_of_type<DOM::Element>([&](auto& node) {
Layout::RustFFI::FfiSvgFilterPrimitive primitive {};
auto& values = primitive.values;
values.operating_color_space = operating_color_space(node);
+ // https://drafts.csswg.org/filter-effects-1/#FilterPrimitiveSubRegion
+ // An attribute the primitive doesn't specify takes its value from the default subregion, which depends on the
+ // primitive's inputs, so the builder resolves that.
+ auto set_subregion_attribute = [&](Utf16FlyString const& name, auto& field, u8 specified_bit) {
+ if (auto value = parsed_attribute(node, name); value.has_value()) {
+ field = Layout::to_ffi_number_percentage(*value);
+ values.subregion_specified |= specified_bit;
+ }
+ };
+ set_subregion_attribute(AttributeNames::x, values.subregion_x, 1 << 0);
+ set_subregion_attribute(AttributeNames::y, values.subregion_y, 1 << 1);
+ set_subregion_attribute(AttributeNames::width, values.subregion_width, 1 << 2);
+ set_subregion_attribute(AttributeNames::height, values.subregion_height, 1 << 3);
+
// The builder copies what the primitive's views point at while it is pushed, so this
// storage only has to outlive the push.
Utf16String in1;
@@ -162,19 +218,58 @@ void SVGFilterElement::push_primitives(void* sink, Gfx::IntSize dest_size)
set_in1(*colormatrix_primitive);
set_result(*colormatrix_primitive);
} else if (auto* image_primitive = as_if<SVGFEImageElement>(node)) {
+ // https://drafts.csswg.org/filter-effects-1/#feImageElement
+ // An feImage whose image can't be rendered produces transparent black, which the builder makes of an Image
+ // primitive without a frame.
+ values.kind = PrimitiveKind::Image;
+ set_result(*image_primitive);
auto image_data = image_primitive->image_data();
- if (!image_data)
- return IterationDecision::Continue;
-
- // FIXME: Use the filter primitive subregion's size once we support primitive subregions.
- image_frame = image_data->default_frame(dest_size);
- if (!image_frame.has_value())
+ // A vector image draws at whatever size it's asked for, letterboxing itself into a size of another aspect
+ // ratio. So ask for a frame of the image's own aspect ratio, large enough to cover the filtered element,
+ // but no larger along either axis than the largest frame that size would ask for anyway.
+ auto natural_width = image_data ? image_data->intrinsic_width().map([](auto width) { return width.to_float(); }).value_or(0) : 0;
+ auto natural_height = image_data ? image_data->intrinsic_height().map([](auto height) { return height.to_float(); }).value_or(0) : 0;
+ // An image missing a width or a height (an SVG with only a viewBox, e.g.) still has an aspect ratio, which
+ // the missing dimensions follow — so it fits the subregion at that ratio.
+ if (image_data && (natural_width <= 0 || natural_height <= 0)) {
+ if (auto aspect_ratio = image_data->intrinsic_aspect_ratio(); aspect_ratio.has_value() && aspect_ratio->to_float() > 0) {
+ auto ratio = aspect_ratio->to_float();
+ if (natural_width > 0) {
+ natural_height = natural_width / ratio;
+ } else if (natural_height > 0) {
+ natural_width = natural_height * ratio;
+ } else {
+ natural_width = ratio;
+ natural_height = 1;
+ }
+ }
+ }
+ auto frame_size = dest_size;
+ if (natural_width > 0 && natural_height > 0 && !dest_size.is_empty()) {
+ auto largest_side = static_cast<float>(max(dest_size.width(), dest_size.height()));
+ auto scale = max(dest_size.width() / natural_width, dest_size.height() / natural_height);
+ scale = min(scale, largest_side / max(natural_width, natural_height));
+ frame_size = { max(1, static_cast<int>(ceilf(natural_width * scale))), max(1, static_cast<int>(ceilf(natural_height * scale))) };
+ }
+ if (image_data)
+ image_frame = image_data->default_frame(frame_size);
+ if (!image_frame.has_value()) {
+ primitive.in1 = view_of(in1);
+ primitive.in2 = view_of(in2);
+ primitive.result = view_of(result);
+ Layout::RustFFI::layout_arena_paint_push_svg_filter_primitive(sink, &primitive);
return IterationDecision::Continue;
+ }
- values.kind = PrimitiveKind::Image;
values.image_src_rect = { 0, 0, image_frame->width(), image_frame->height() };
+ values.image_natural_width = natural_width;
+ values.image_natural_height = natural_height;
+ PreserveAspectRatio preserve_aspect_ratio {};
+ if (auto value = image_primitive->get_attribute(AttributeNames::preserveAspectRatio); value.has_value())
+ preserve_aspect_ratio = parse_preserve_aspect_ratio(*value).value_or({});
+ values.image_preserve_aspect_ratio_align = to_underlying(preserve_aspect_ratio.align);
+ values.image_preserve_aspect_ratio_meet_or_slice = to_underlying(preserve_aspect_ratio.meet_or_slice);
primitive.image_frame = &image_frame.value();
- set_result(*image_primitive);
} else if (auto* merge_primitive = as_if<SVGFEMergeElement>(node)) {
values.kind = PrimitiveKind::Merge;
merge_primitive->template for_each_child_of_type<SVGFEMergeNodeElement>([&](auto& merge_node) {
@@ -221,7 +316,8 @@ void SVGFilterElement::push_primitives(void* sink, Gfx::IntSize dest_size)
values.base_frequency_y = turbulence->base_frequency_y()->base_val();
values.num_octaves = turbulence->num_octaves()->base_val();
values.seed = turbulence->seed()->base_val();
- if (turbulence->stitch_tiles()->base_val() == to_underlying(SVGFETurbulenceElement::StitchType::Stitch)) {
+ values.turbulence_stitches_tiles = turbulence->stitch_tiles()->base_val() == to_underlying(SVGFETurbulenceElement::StitchType::Stitch);
+ if (values.turbulence_stitches_tiles) {
// FIXME: Use the correct width and height
auto maybe_width = turbulence->width()->base_val()->value();
auto maybe_height = turbulence->height()->base_val()->value();
diff --git a/Tests/LibWeb/Ref/expected/svg/backdrop-filter-feimage-at-high-dpi-ref.html b/Tests/LibWeb/Ref/expected/svg/backdrop-filter-feimage-at-high-dpi-ref.html
new file mode 100644
index 00000000000..a700dd90323
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg/backdrop-filter-feimage-at-high-dpi-ref.html
@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<script>
+ if (window.internals)
+ internals.setDevicePixelRatio(2);
+</script>
+<style>
+ body { margin: 0; }
+ div { position: absolute; left: 50px; top: 50px; width: 100px; height: 100px; background: green; }
+</style>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/svg/blend-filter-ref.html b/Tests/LibWeb/Ref/expected/svg/blend-filter-ref.html
index d20e7afe3b4..1e64199ed57 100644
--- a/Tests/LibWeb/Ref/expected/svg/blend-filter-ref.html
+++ b/Tests/LibWeb/Ref/expected/svg/blend-filter-ref.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
- <rect x="0" y="0" width="100" height="100" fill="green"/>
+ <rect x="0" y="0" width="100" height="100" fill="blue"/>
+ <rect x="20" y="20" width="60" height="60" fill="green"/>
<rect x="25" y="25" width="50" height="50" fill="black" />
</svg>
diff --git a/Tests/LibWeb/Ref/expected/svg/feimage-without-natural-size-keeps-its-aspect-ratio-ref.html b/Tests/LibWeb/Ref/expected/svg/feimage-without-natural-size-keeps-its-aspect-ratio-ref.html
new file mode 100644
index 00000000000..073af6c1cc3
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg/feimage-without-natural-size-keeps-its-aspect-ratio-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ div { position: absolute; left: 0; top: 0; width: 200px; height: 100px; background: green; }
+</style>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/svg/filter-default-subregion-is-the-input-subregion-as-defined-ref.html b/Tests/LibWeb/Ref/expected/svg/filter-default-subregion-is-the-input-subregion-as-defined-ref.html
new file mode 100644
index 00000000000..48950fe36ab
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg/filter-default-subregion-is-the-input-subregion-as-defined-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ div { position: absolute; left: 50px; top: 0; width: 50px; height: 100px; background: green; }
+</style>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/svg/filter-primitive-zero-length-in-a-relative-unit-ref.html b/Tests/LibWeb/Ref/expected/svg/filter-primitive-zero-length-in-a-relative-unit-ref.html
new file mode 100644
index 00000000000..cb10ceb5401
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg/filter-primitive-zero-length-in-a-relative-unit-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ div { width: 100px; height: 100px; background: green; }
+</style>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/svg/filter-region-covers-child-transformed-before-start-ref.html b/Tests/LibWeb/Ref/expected/svg/filter-region-covers-child-transformed-before-start-ref.html
new file mode 100644
index 00000000000..cb10ceb5401
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg/filter-region-covers-child-transformed-before-start-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ div { width: 100px; height: 100px; background: green; }
+</style>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/svg/filter-region-covers-overflow-along-an-unclipped-axis-ref.html b/Tests/LibWeb/Ref/expected/svg/filter-region-covers-overflow-along-an-unclipped-axis-ref.html
new file mode 100644
index 00000000000..cb10ceb5401
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg/filter-region-covers-overflow-along-an-unclipped-axis-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ div { width: 100px; height: 100px; background: green; }
+</style>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/filter-subregion-01-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/filter-subregion-01-ref.html
new file mode 100644
index 00000000000..0685b0d9550
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/filter-subregion-01-ref.html
@@ -0,0 +1,45 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>filter primitive subregion: Clip to filter primitive subregion</title>
+<link rel="author" title="Chris Lilley" href="mailto:[email protected]">
+<p>Test passes if two semi-transparent green rectangles are on top of the
+blue boxes to the left, and one opaque green rectangle on the blue box
+to the right.</p>
+<svg width="400" height="400">
+ <defs>
+ <filter id="blend">
+ <feBlend in2="SourceGraphic" mode="multiply"/>
+ </filter>
+ <filter id="merge">
+ <feMerge>
+ <feMergeNode in="SourceGraphic"/>
+ <feMergeNode in="FillPaint"/>
+ </feMerge>
+ </filter>
+ </defs>
+
+ <g fill="none" stroke="blue" stroke-width="4">
+ <rect width="200" height="200"/>
+ <line x2="200" y2="200"/>
+ <line x1="200" y2="200"/>
+ </g>
+ <rect fill="green" fill-opacity="0.75" x="60" y="60" width="80" height="80"/>
+
+ <g transform="translate(200 0)">
+ <g fill="none" stroke="blue" stroke-width="4">
+ <rect width="200" height="200"/>
+ <line x2="200" y2="200"/>
+ <line x1="200" y2="200"/>
+ </g>
+ <rect fill="green" filter="url(#blend)" x="60" y="60" width="80" height="80"/>
+ </g>
+
+ <g transform="translate(0 200)">
+ <g fill="none" stroke="blue" stroke-width="4">
+ <rect width="200" height="200"/>
+ <line x2="200" y2="200"/>
+ <line x1="200" y2="200"/>
+ </g>
+ <rect fill="green" fill-opacity="0.5" filter="url(#merge)" x="60" y="60" width="80" height="80"/>
+ </g>
+</svg>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-002-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-002-ref.html
new file mode 100644
index 00000000000..72250a1cf80
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-002-ref.html
@@ -0,0 +1,2 @@
+<!DOCTYPE html>
+<img src="../support/color-palette.png" style="will-change: transform;">
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-003-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-003-ref.html
new file mode 100644
index 00000000000..9b982b3cfb4
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-003-ref.html
@@ -0,0 +1,2 @@
+<!DOCTYPE html>
+<img src="../support/color-palette.png">
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-004-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-004-ref.html
new file mode 100644
index 00000000000..0aa3378e590
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-004-ref.html
@@ -0,0 +1,2 @@
+<!DOCTYPE html>
+<img src="../support/color-palette.png" style="will-change: filter;">
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/filter-region-negative-positioned-child-001-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/filter-region-negative-positioned-child-001-ref.html
new file mode 100644
index 00000000000..c9da47b1b43
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/filter-region-negative-positioned-child-001-ref.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" version="1.1">
+ <defs>
+ <filter id="f1" color-interpolation-filters="sRGB">
+ <feColorMatrix type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0"/>
+ </filter>
+ </defs>
+</svg>
+<style>
+.box {
+ width: 100px;
+ height: 100px;
+ position: absolute;
+}
+.green {
+ background-color: green;
+}
+.blue {
+ background-color: blue;
+}
+.below {
+ top: 100px;
+}
+.parent {
+ filter: url(#f1);
+ background-color: white;
+ position: relative;
+}
+</style>
+<div class="parent">
+<div class="blue box"></div>
+<div class="green box below"></div>
+</div>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/filter-region-transformed-child-001-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/filter-region-transformed-child-001-ref.html
new file mode 100644
index 00000000000..bcf64941193
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/filter-region-transformed-child-001-ref.html
@@ -0,0 +1,23 @@
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="0" height="0">
+ <defs>
+ <filter id="filter" x="25%" y="0%" width="50%" height="100%">
+ <feComponentTransfer>
+ <feFuncR type="linear" intercept="0" slope="1"/>
+ <feFuncG type="linear" intercept="0" slope="0"/>
+ <feFuncB type="linear" intercept="0" slope="0"/>
+ <feFuncA type="linear" intercept="0" slope="1"/>
+ </feComponentTransfer>
+ </filter>
+ </defs>
+</svg>
+<style>
+div {
+ display: inline-block;
+ filter: url(#filter);
+ background-color: gray;
+ width: 50px;
+ height: 50px;
+ transform: translate(25px, 25px) scale(2);
+}
+</style>
+<div></div>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/svg-filter-filter-units-user-space-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/svg-filter-filter-units-user-space-ref.html
new file mode 100644
index 00000000000..679aae39801
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/svg-filter-filter-units-user-space-ref.html
@@ -0,0 +1,56 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <style>
+ .container {
+ width: 200px;
+ height: 200px;
+ display: inline-block;
+ vertical-align: top;
+ margin-right: 2px;
+ margin-bottom: 4px;
+ background-color: lightgray;
+ }
+
+ .green-box {
+ background-color: red;
+ width: 50px;
+ height: 50px;
+ background-color: green;
+ transform: translate(10px, 10px);
+ }
+
+ svg {
+ background-color: rgb(160, 160, 160);
+ }
+ </style>
+</head>
+<body>
+ <div>
+ <div class="container"></div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="0" y="0" width="75" height="75" fill="green" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="green-box"></div>
+ </div>
+ </div>
+ <div>
+ <div class="container">
+ <svg width="200" height="200">
+ <rect x="0" y="0" width="100" height="100" fill="green" />
+ </svg>
+ </div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="0" y="0" width="75" height="75" fill="green" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="green-box"></div>
+ </div>
+ </div>
+</body>
+</html>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/svg-filter-primitive-units-user-space-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/svg-filter-primitive-units-user-space-ref.html
new file mode 100644
index 00000000000..f1dafa48c00
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/filter-effects/reference/svg-filter-primitive-units-user-space-ref.html
@@ -0,0 +1,54 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <style>
+ .container {
+ width: 200px;
+ height: 200px;
+ display: inline-block;
+ vertical-align: top;
+ margin-right: 2px;
+ margin-bottom: 4px;
+ background-color: lightgray;
+ }
+
+ .filtered-box {
+ background-color: green;
+ width: 100px;
+ height: 100px;
+ }
+
+ svg {
+ background-color: rgb(160, 160, 160);
+ }
+ </style>
+</head>
+<body>
+ <div>
+ <div class="container"></div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="0" y="0" width="120" height="120" fill="green" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="filtered-box"></div>
+ </div>
+ </div>
+ <div>
+ <div class="container">
+ <svg width="200" height="200">
+ <rect x="0" y="0" width="120" height="120" fill="green" />
+ </svg>
+ </div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="0" y="0" width="120" height="120" fill="green" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="filtered-box"></div>
+ </div>
+ </div>
+</body>
+</html>
diff --git a/Tests/LibWeb/Ref/input/svg/backdrop-filter-feimage-at-high-dpi.html b/Tests/LibWeb/Ref/input/svg/backdrop-filter-feimage-at-high-dpi.html
new file mode 100644
index 00000000000..179c636678d
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg/backdrop-filter-feimage-at-high-dpi.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<script>
+ if (window.internals)
+ internals.setDevicePixelRatio(2);
+</script>
+<link rel="match" href="../../expected/svg/backdrop-filter-feimage-at-high-dpi-ref.html" />
+<style>
+ body { margin: 0; }
+ div { position: absolute; left: 50px; top: 50px; width: 100px; height: 100px; backdrop-filter: url(#image); }
+</style>
+<svg width="0" height="0" style="position: absolute">
+ <filter id="image">
+ <feImage href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='green'/%3E%3C/svg%3E" />
+ </filter>
+</svg>
+<!-- A backdrop filter's feImage draws over the box, in device pixels at any device pixel ratio. -->
+<div></div>
diff --git a/Tests/LibWeb/Ref/input/svg/feimage-without-natural-size-keeps-its-aspect-ratio.html b/Tests/LibWeb/Ref/input/svg/feimage-without-natural-size-keeps-its-aspect-ratio.html
new file mode 100644
index 00000000000..60efff12fee
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg/feimage-without-natural-size-keeps-its-aspect-ratio.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/svg/feimage-without-natural-size-keeps-its-aspect-ratio-ref.html" />
+<style>
+ body { margin: 0; }
+ div { width: 100px; height: 100px; background: red; filter: url(#image); }
+</style>
+<svg width="0" height="0" style="position: absolute">
+ <filter id="image" filterUnits="userSpaceOnUse" primitiveUnits="userSpaceOnUse" x="0" y="0" width="200" height="100">
+ <feImage x="0" y="0" width="200" height="100" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 100'%3E%3Crect width='200' height='100' fill='green'/%3E%3C/svg%3E" />
+ </filter>
+</svg>
+<!-- The image has a viewBox but no width or height, so it has a 2:1 aspect ratio and fills the 200x100 subregion. -->
+<div></div>
diff --git a/Tests/LibWeb/Ref/input/svg/filter-default-subregion-is-the-input-subregion-as-defined.html b/Tests/LibWeb/Ref/input/svg/filter-default-subregion-is-the-input-subregion-as-defined.html
new file mode 100644
index 00000000000..2d79b204353
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg/filter-default-subregion-is-the-input-subregion-as-defined.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/svg/filter-default-subregion-is-the-input-subregion-as-defined-ref.html" />
+<style>
+ body { margin: 0; }
+ div { width: 100px; height: 100px; background: red; filter: url(#shifted); }
+</style>
+<svg width="0" height="0" style="position: absolute">
+ <filter id="shifted" filterUnits="userSpaceOnUse" primitiveUnits="userSpaceOnUse" x="0" y="0" width="100" height="100">
+ <feFlood flood-color="green" x="-50" y="0" width="100" height="100" result="flood" />
+ <feOffset in="flood" dx="50" x="0" />
+ </filter>
+</svg>
+<!-- The flood's subregion reaches past the filter region's left edge. The offset's width defaults to the flood's
+ subregion as defined (100), not as the filter region clips it (50), so the shifted half of the flood shows. -->
+<div></div>
diff --git a/Tests/LibWeb/Ref/input/svg/filter-primitive-zero-length-in-a-relative-unit.html b/Tests/LibWeb/Ref/input/svg/filter-primitive-zero-length-in-a-relative-unit.html
new file mode 100644
index 00000000000..623247a88c6
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg/filter-primitive-zero-length-in-a-relative-unit.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/svg/filter-primitive-zero-length-in-a-relative-unit-ref.html" />
+<style>
+ body { margin: 0; }
+ div { position: absolute; left: 0; top: 0; width: 100px; height: 100px; }
+ #under { background: green; }
+ #filtered { background: red; filter: url(#empty); }
+</style>
+<svg width="0" height="0" style="position: absolute">
+ <filter id="empty" filterUnits="userSpaceOnUse" primitiveUnits="userSpaceOnUse" x="0" y="0" width="100" height="100">
+ <feFlood flood-color="red" width="0em" />
+ </filter>
+</svg>
+<!-- A zero width disables the flood whatever its unit, so the filter produces transparent black. -->
+<div id="under"></div>
+<div id="filtered"></div>
diff --git a/Tests/LibWeb/Ref/input/svg/filter-region-covers-child-transformed-before-start.html b/Tests/LibWeb/Ref/input/svg/filter-region-covers-child-transformed-before-start.html
new file mode 100644
index 00000000000..f59c552b0fc
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg/filter-region-covers-child-transformed-before-start.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/svg/filter-region-covers-child-transformed-before-start-ref.html" />
+<style>
+ body { margin: 0; }
+ #parent { margin-left: 100px; width: 100px; height: 100px; filter: url(#identity); }
+ #child { width: 100px; height: 100px; background: green; transform: translateX(-100px); }
+</style>
+<svg width="0" height="0" style="position: absolute">
+ <filter id="identity" x="0" y="0" width="1" height="1">
+ <feOffset dx="0" dy="0" />
+ </filter>
+</svg>
+<!-- The child's transform moves it out past the parent's left edge, where the filter region still covers it. -->
+<div id="parent"><div id="child"></div></div>
diff --git a/Tests/LibWeb/Ref/input/svg/filter-region-covers-overflow-along-an-unclipped-axis.html b/Tests/LibWeb/Ref/input/svg/filter-region-covers-overflow-along-an-unclipped-axis.html
new file mode 100644
index 00000000000..dbc46037016
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg/filter-region-covers-overflow-along-an-unclipped-axis.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/svg/filter-region-covers-overflow-along-an-unclipped-axis-ref.html" />
+<style>
+ body { margin: 0; }
+ #parent { margin-top: 100px; width: 100px; height: 100px; overflow-x: clip; overflow-y: visible; filter: url(#identity); }
+ #child { position: relative; top: -100px; width: 100px; height: 100px; background: green; }
+</style>
+<svg width="0" height="0" style="position: absolute">
+ <filter id="identity" x="0" y="0" width="1" height="1">
+ <feOffset dx="0" dy="0" />
+ </filter>
+</svg>
+<!-- The parent clips only horizontally, so the child above it still counts toward its filter region. -->
+<div id="parent"><div id="child"></div></div>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-002.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-002.html
new file mode 100644
index 00000000000..23a307487ad
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-002.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<title>CSS Filters: feImage and CSS reference filters.</title>
+<link rel="help" href="https://drafts.fxtf.org/filter-effects-1/#feImageElement">
+<link rel="help" href="https://drafts.fxtf.org/filter-effects-1/#FilterProperty">
+<link rel="match" href="../../../../expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-002-ref.html">
+<meta name="assert" content="This test ensures that CSS reference filters with 'will-change: transform' supports feImage."/>
+<meta name="fuzzy" content="maxDifference=0-11; totalPixels=0-17278"/>
+<style>
+ #filtered {
+ width: 160px;
+ height: 90px;
+ filter: url(#imagereplace);
+ will-change: transform;
+ }
+</style>
+<div id="filtered"></div>
+<svg width="0" height="0">
+ <filter id="imagereplace" color-interpolation-filters="sRGB" x="0%" y="0%" width="100%" height="100%">
+ <feimage xlink:href="support/color-palette.png"/>
+ </filter>
+</svg>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-003.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-003.html
new file mode 100644
index 00000000000..0c37cde5d46
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-003.html
@@ -0,0 +1,34 @@
+<!DOCTYPE html>
+<title>CSS Filters: feImage and CSS reference filters.</title>
+<link rel="help" href="https://drafts.fxtf.org/filter-effects-1/#feImageElement">
+<link rel="help" href="https://drafts.fxtf.org/filter-effects-1/#FilterProperty">
+<link rel="match" href="../../../../expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-003-ref.html">
+<meta name="assert" content="This test ensures that CSS reference filters support a dynamically attached feImage."/>
+<meta name="fuzzy" content="maxDifference=0-11; totalPixels=0-17278"/>
+<body>
+
+<style>
+ #filtered {
+ width: 160px;
+ height: 90px;
+ filter: url(#imagereplace);
+ }
+</style>
+
+<script type="text/html" id="source">
+ <div id="filtered"></div>
+ <svg width="0" height="0">
+ <filter id="imagereplace" x="0%" y="0" width="100%" height="100%">
+ <feimage xlink:href="support/color-palette.png"/>
+ </filter>
+ </svg>
+</script>
+
+<script>
+ document.body.offsetLeft;
+ var div = document.createElement('div');
+ div.innerHTML = document.getElementById('source').textContent;
+ document.body.appendChild(div);
+</script>
+
+</body>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-004.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-004.html
new file mode 100644
index 00000000000..02248e8b85d
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/effect-reference-feimage-004.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<title>CSS Filters: feImage and CSS reference filters.</title>
+<link rel="help" href="https://drafts.fxtf.org/filter-effects-1/#feImageElement">
+<link rel="help" href="https://drafts.fxtf.org/filter-effects-1/#FilterProperty">
+<link rel="match" href="../../../../expected/wpt-import/css/filter-effects/reference/effect-reference-feimage-004-ref.html">
+<meta name="assert" content="This test ensures that CSS reference filters with 'will-change: filter' supports feImage."/>
+<meta name="fuzzy" content="maxDifference=0-11; totalPixels=0-17278"/>
+<style>
+ #filtered {
+ width: 160px;
+ height: 90px;
+ filter: url(#imagereplace);
+ will-change: filter;
+ }
+</style>
+<div id="filtered"></div>
+<svg width="0" height="0">
+ <filter id="imagereplace" color-interpolation-filters="sRGB" x="0%" y="0%" width="100%" height="100%">
+ <feimage xlink:href="support/color-palette.png"/>
+ </filter>
+</svg>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-region-negative-positioned-child-001.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-region-negative-positioned-child-001.html
new file mode 100644
index 00000000000..6aa9fc3b215
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-region-negative-positioned-child-001.html
@@ -0,0 +1,41 @@
+<!DOCTYPE html>
+<title>SVG Filters: CSS reference filters with negative positioned children</title>
+<link rel="help" href="https://drafts.fxtf.org/filter-effects/#FilterProperty">
+<link rel="help" href="https://drafts.fxtf.org/filter-effects/#ColorInterpolationFiltersProperty">
+<link rel="help" href="https://drafts.fxtf.org/filter-effects/#feColorMatrixElement">
+<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=638091">
+<link rel="match" href="../../../../expected/wpt-import/css/filter-effects/reference/filter-region-negative-positioned-child-001-ref.html">
+<meta name="assert" content="CSS reference filters with negative positioned children"/>
+<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" version="1.1">
+ <defs>
+ <filter id="f1" color-interpolation-filters="sRGB">
+ <feColorMatrix type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0"/>
+ </filter>
+ </defs>
+</svg>
+<style>
+.box {
+ width: 100px;
+ height: 100px;
+ position: absolute;
+}
+.green {
+ background-color: green;
+}
+.blue {
+ background-color: blue;
+}
+.above {
+ top: -100px;
+}
+.parent {
+ filter: url(#f1);
+ background-color: white;
+ position: relative;
+ top: 100px;
+}
+</style>
+<div class="parent">
+<div class="green box"></div>
+<div class="blue box above"></div>
+</div>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-region-transformed-child-001.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-region-transformed-child-001.html
new file mode 100644
index 00000000000..4c8956c478f
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-region-transformed-child-001.html
@@ -0,0 +1,30 @@
+<title>CSS Filter: Scale a transformed child element"></title>
+<link rel="help" href="https://drafts.fxtf.org/filter-effects-1/#feComponentTransferElement">
+<link rel="issue" href="https://bugs.chromium.org/p/chromium/issues/detail?id=333014">
+<link rel="match" href="../../../../expected/wpt-import/css/filter-effects/reference/filter-region-transformed-child-001-ref.html">
+<meta name="assert" content="This test ensures that the feComponentTransfer filter scales a child with CSS scale transform.">
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="0" height="0">
+ <defs>
+ <filter id="filter" x="25%" y="0%" width="50%" height="100%">
+ <feComponentTransfer>
+ <feFuncR type="linear" intercept="0" slope="1"/>
+ <feFuncG type="linear" intercept="0" slope="0"/>
+ <feFuncB type="linear" intercept="0" slope="0"/>
+ <feFuncA type="linear" intercept="0" slope="1"/>
+ </feComponentTransfer>
+ </filter>
+ </defs>
+</svg>
+<style>
+#parent {
+ display: inline-block;
+ filter: url(#filter);
+}
+#child {
+ background-color: gray;
+ width: 50px;
+ height: 50px;
+ transform: translate(25px, 25px) scale(2);
+}
+</style>
+<div id="parent"><div id="child"></div></div>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-subregion-01.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-subregion-01.html
new file mode 100644
index 00000000000..c1b2757a928
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/filter-subregion-01.html
@@ -0,0 +1,54 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>filter primitive subregion: Clip to filter primitive subregion</title>
+<link rel="author" title="Chris Lilley" href="mailto:[email protected]">
+<link rel="help" href="https://drafts.fxtf.org/filter-effects/#FilterPrimitiveSubRegion">
+<link rel="match" href="../../../../expected/wpt-import/css/filter-effects/filter-subregion-01-ref.html">
+<meta name="fuzzy" content="maxDifference=0-5; totalPixels=0-1000"/>
+<p>Test passes if two semi-transparent green rectangles are on top of the
+blue boxes to the left, and one opaque green rectangle on the blue box
+to the right.</p>
+<!-- this is example filtersubregion00.svg from the specification -->
+<svg width="400" height="400">
+ <defs>
+ <filter id="flood" x="0" y="0" width="100%" height="100%" primitiveUnits="objectBoundingBox">
+ <feFlood x="25%" y="25%" width="50%" height="50%"
+ flood-color="green" flood-opacity="0.75"/>
+ </filter>
+ <filter id="blend" primitiveUnits="objectBoundingBox">
+ <feBlend x="25%" y="25%" width="50%" height="50%"
+ in2="SourceGraphic" mode="multiply"/>
+ </filter>
+ <filter id="merge" primitiveUnits="objectBoundingBox">
+ <feMerge x="25%" y="25%" width="50%" height="50%">
+ <feMergeNode in="SourceGraphic"/>
+ <feMergeNode in="FillPaint"/>
+ </feMerge>
+ </filter>
+ </defs>
+
+ <g fill="none" stroke="blue" stroke-width="4">
+ <rect width="200" height="200"/>
+ <line x2="200" y2="200"/>
+ <line x1="200" y2="200"/>
+ </g>
+ <circle fill="green" filter="url(#flood)" cx="100" cy="100" r="80"/>
+
+ <g transform="translate(200 0)">
+ <g fill="none" stroke="blue" stroke-width="4">
+ <rect width="200" height="200"/>
+ <line x2="200" y2="200"/>
+ <line x1="200" y2="200"/>
+ </g>
+ <circle fill="green" filter="url(#blend)" cx="100" cy="100" r="80"/>
+ </g>
+
+ <g transform="translate(0 200)">
+ <g fill="none" stroke="blue" stroke-width="4">
+ <rect width="200" height="200"/>
+ <line x2="200" y2="200"/>
+ <line x1="200" y2="200"/>
+ </g>
+ <circle fill="green" fill-opacity="0.5" filter="url(#merge)" cx="100" cy="100" r="80"/>
+ </g>
+</svg>
\ No newline at end of file
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/svg-filter-filter-units-user-space.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/svg-filter-filter-units-user-space.html
new file mode 100644
index 00000000000..2bff808b42d
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/svg-filter-filter-units-user-space.html
@@ -0,0 +1,73 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <link rel="author" title="Said Abou-Hallawa" href="mailto:[email protected]>">
+ <link rel="help" href="https://drafts.fxtf.org/filter-effects/#element-attrdef-filter-primitiveunits">
+ <link rel="help" href="https://drafts.csswg.org/css-transforms-1/#local-coordinate-system">
+ <link rel="match" href="../../../../expected/wpt-import/css/filter-effects/reference/svg-filter-filter-units-user-space-ref.html">
+ <style>
+ .container {
+ width: 200px;
+ height: 200px;
+ display: inline-block;
+ vertical-align: top;
+ margin-right: 2px;
+ margin-bottom: 4px;
+ background-color: lightgray;
+ }
+
+ .filtered-box {
+ background-color: red;
+ width: 100px;
+ height: 100px;
+ transform: translate(10px, 10px);
+ }
+
+ svg {
+ background-color: rgb(160, 160, 160);
+ }
+ </style>
+</head>
+<body>
+ <div>
+ <div class="container">
+ <svg width="0" height="0" style="position: absolute;">
+ <defs>
+ <filter id="floodFilter-1" filterUnits="userSpaceOnUse" x="0" y="0" width="100%" height="100%">
+ <feFlood flood-color="green" width="50%" height="50%" />
+ </filter>
+ </defs>
+ </svg>
+ </div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="10" y="10" width="100" height="100" fill="red" filter="url(#floodFilter-1)" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="filtered-box" style="filter: url(#floodFilter-1);"></div>
+ </div>
+ </div>
+ <div>
+ <div class="container">
+ <svg width="200" height="200">
+ <defs>
+ <filter id="floodFilter-2" filterUnits="userSpaceOnUse" x="0" y="0" width="100%" height="100%">
+ <feFlood flood-color="green" width="50%" height="50%" />
+ </filter>
+ </defs>
+ <rect x="10" y="10" width="100" height="100" fill="red" filter="url(#floodFilter-2)" />
+ </svg>
+ </div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="10" y="10" width="100" height="100" fill="red" filter="url(#floodFilter-2)" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="filtered-box" style="filter: url(#floodFilter-2);"></div>
+ </div>
+ </div>
+</body>
+</html>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/svg-filter-primitive-units-user-space.html b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/svg-filter-primitive-units-user-space.html
new file mode 100644
index 00000000000..9533a69b300
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/filter-effects/svg-filter-primitive-units-user-space.html
@@ -0,0 +1,74 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <meta name="fuzzy" content="maxDifference=0-160; totalPixels=0-723">
+ <link rel="author" title="Said Abou-Hallawa" href="mailto:[email protected]>">
+ <link rel="help" href="https://drafts.fxtf.org/filter-effects/#element-attrdef-filter-primitiveunits">
+ <link rel="help" href="https://drafts.csswg.org/css-transforms-1/#local-coordinate-system">
+ <link rel="match" href="../../../../expected/wpt-import/css/filter-effects/reference/svg-filter-primitive-units-user-space-ref.html">
+ <style>
+ .container {
+ width: 200px;
+ height: 200px;
+ display: inline-block;
+ vertical-align: top;
+ margin-right: 2px;
+ margin-bottom: 4px;
+ background-color: lightgray;
+ }
+
+ .filtered-box {
+ background-color: red;
+ width: 100px;
+ height: 100px;
+ transform: translate(10px, 10px);
+ }
+
+ svg {
+ background-color: rgb(160, 160, 160);
+ }
+ </style>
+</head>
+<body>
+ <div>
+ <div class="container">
+ <svg width="0" height="0" style="position: absolute;">
+ <defs>
+ <filter id="floodFilter-1" primitiveUnits="userSpaceOnUse">
+ <feFlood flood-color="green" width="100%" height="100%" />
+ </filter>
+ </defs>
+ </svg>
+ </div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="10" y="10" width="100" height="100" fill="red" filter="url(#floodFilter-1)" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="filtered-box" style="filter: url(#floodFilter-1);"></div>
+ </div>
+ </div>
+ <div>
+ <div class="container">
+ <svg width="200" height="200">
+ <defs>
+ <filter id="floodFilter-2" primitiveUnits="userSpaceOnUse">
+ <feFlood flood-color="green" width="100%" height="100%" />
+ </filter>
+ </defs>
+ <rect x="10" y="10" width="100" height="100" fill="red" filter="url(#floodFilter-2)" />
+ </svg>
+ </div>
+ <div class="container">
+ <svg width="150" height="150">
+ <rect x="10" y="10" width="100" height="100" fill="red" filter="url(#floodFilter-2)" />
+ </svg>
+ </div>
+ <div class="container">
+ <div class="filtered-box" style="filter: url(#floodFilter-2);"></div>
+ </div>
+ </div>
+</body>
+</html>