Truly independent web browser
LibWeb: Read committed SVG geometry for getBBox, getCTM and lengths
Aliaksandr Kalenik2f08653dc25a
diff --git a/Libraries/LibWeb/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cppindex 9fedc4cb83d..476ef40efa2 100644--- a/Libraries/LibWeb/Painting/BoxViews.cpp+++ b/Libraries/LibWeb/Painting/BoxViews.cpp@@ -291,11 +291,6 @@ static bool is_inline_paintable(Layout::Node const& node)return has_committed_box(node) && node.is_fragmented_inline();}-bool is_svg_svg_paintable(Layout::Node const& node)-{- return has_committed_box(node) && node.kind() == Layout::RustFFI::NodeKind::SVGSVGBox;-}-bool has_accumulated_visual_context(Layout::Node const& node){auto row = committed_row(node);@@ -320,12 +315,12 @@ Compositing::SpatialNodeIndex own_scroll_node_index(Layout::Node const& node)return row.has_value() ? row->own_scroll_node_index : Compositing::VISUAL_VIEWPORT_NODE_INDEX;}-Optional<Gfx::FloatRect> committed_svg_path_bounding_box(Layout::Node const& node)+Optional<Layout::RustFFI::SvgGeometry> svg_geometry(Layout::Node const& node){- Gfx::FloatRect bounding_box;- if (!Layout::RustFFI::render_state_paintable_computed_svg_path_bounding_box(node.document_host(), committed_row_slot(node), &bounding_box))+ Layout::RustFFI::SvgGeometry geometry;+ if (!Layout::RustFFI::render_state_svg_geometry(node.document_host(), committed_row_slot(node), &geometry))return {};- return bounding_box;+ return geometry;}// The glyph cells a text content element's box committed for its own characters, one per code unit, copied out@@ -340,13 +335,6 @@ Vector<Layout::RustFFI::FfiSvgTextCharacterCell> svg_text_character_cells(Layoutreturn cells;}-CSSPixelSize svg_viewport_size(Layout::Node const& node)-{- CSSPixelSize size;- Layout::RustFFI::render_state_paintable_svg_viewport_size(node.document_host(), committed_row_slot(node), &size);- return size;-}-Optional<Gfx::AffineTransform> svg_viewport_transform(Layout::Node const& node){auto result = Layout::RustFFI::render_state_paintable_svg_viewport_transform(node.document_host(), committed_row_slot(node));diff --git a/Libraries/LibWeb/Painting/BoxViews.h b/Libraries/LibWeb/Painting/BoxViews.hindex 5a62daa06cb..bae40c956b3 100644--- a/Libraries/LibWeb/Painting/BoxViews.h+++ b/Libraries/LibWeb/Painting/BoxViews.h@@ -58,7 +58,6 @@ WEB_API CSS::StyleRecordID style_record_identity(Layout::Node const&);WEB_API bool is_navigable_container_viewport_paintable(Layout::Node const&);WEB_API bool is_viewport_paintable(Layout::Node const&);WEB_API bool is_paintable_with_lines(Layout::Node const&);-WEB_API bool is_svg_svg_paintable(Layout::Node const&);WEB_API CSSPixelRect transform_rect_to_viewport(Layout::Node const&, CSSPixelRect const&, Compositing::AccumulatedVisualContextTree::IncludeVisualViewportTransform = Compositing::AccumulatedVisualContextTree::IncludeVisualViewportTransform::Yes);WEB_API CSSPixelPoint inverse_transform_point(Layout::Node const&, CSSPixelPoint);@@ -72,9 +71,8 @@ WEB_API Compositing::ContextRef accumulated_visual_context(Layout::Node const&);WEB_API Compositing::ContextRef accumulated_visual_context_for_descendants(Layout::Node const&);WEB_API Compositing::SpatialNodeIndex own_scroll_node_index(Layout::Node const&);-WEB_API Optional<Gfx::FloatRect> committed_svg_path_bounding_box(Layout::Node const&);+WEB_API Optional<Layout::RustFFI::SvgGeometry> svg_geometry(Layout::Node const&);WEB_API Vector<Layout::RustFFI::FfiSvgTextCharacterCell> svg_text_character_cells(Layout::Node const&);-WEB_API CSSPixelSize svg_viewport_size(Layout::Node const&);WEB_API Optional<Gfx::AffineTransform> svg_viewport_transform(Layout::Node const&);WEB_API Gfx::AffineTransform svg_element_transform(Layout::Node const&);WEB_API CSS::RustStyleValueHandle used_value_for_grid_template(Layout::Node const&, CSS::PropertyID);diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rsindex e1748c0d988..248c04e67bd 100644--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs@@ -179,7 +179,6 @@ pub const SVG_LENGTH_KIND_PERCENTAGE: u8 = 3;struct SvgElementFacts {is_document_element: bool,document_is_decoded_svg: bool,- element_transform: FfiAffineTransform,additional_element_transform: FfiAffineTransform,visible_stroke_width: f32,}@@ -314,18 +313,20 @@ fn kind_is_svg_container_element(kind: NodeKind) -> bool {/// The geometry layout found for an SVG element, in the user units of the SVG viewport the element is laid out in.#[derive(Clone, Copy, Debug, Default, PartialEq)]-pub(crate) struct SvgGeometry {+#[repr(C)]+pub struct SvgGeometry {/// The bounding box of the element's fill: its path or glyph cells, or the union of its children's object bounding/// boxes, each mapped through the child's local transform.- pub(crate) object_bounding_box: FloatRect,+ pub object_bounding_box: FloatRect,/// The bounding box that covers the element's stroke too, which is the element's box.- pub(crate) stroke_bounding_box: FloatRect,+ pub stroke_bounding_box: FloatRect,/// The element's transform about its transform origin, with a <use> element's translation.- pub(crate) local_transform: FfiAffineTransform,+ pub local_transform: FfiAffineTransform,/// The SVG viewport that the element's own lengths resolve against.- pub(crate) viewport_user_rect: FloatRect,+ pub viewport_user_rect: FloatRect,/// The SVG viewport that the element lays its contents out in, where it lays out contents of its own.- pub(crate) established_viewport_user_rect: Option<FloatRect>,+ pub establishes_viewport: bool,+ pub established_viewport_user_rect: FloatRect,}impl SvgGeometry {@@ -1772,7 +1773,6 @@ impl<'pass> SvgFormattingContext<'pass> {// the defaults.if self.svg_attributes(node).is_graphics_element {facts.additional_element_transform = self.svg_additional_element_transform(node);- facts.element_transform = self.svg_graphics_element_transform(node, facts.additional_element_transform);facts.visible_stroke_width = self.visible_stroke_width(node);}facts@@ -1793,22 +1793,6 @@ impl<'pass> SvgFormattingContext<'pass> {)}- /// The element's own CSS transform, reduced to the 2D affine SVG geometry works in, with- /// `additional_element_transform`, a <use> element's translation, multiplied in.- fn svg_graphics_element_transform(- &self,- node: Node,- additional_element_transform: FfiAffineTransform,- ) -> FfiAffineTransform {- let style = self.style(node);- let matrix = crate::css::transform_functions::multiply_transform_functions(- libgfx_rust::FloatMatrix4x4::identity(),- style.transform().resolved_transforms.as_slice(),- CssPixelRect::default(),- );- libgfx_rust::multiply_affine(matrix.extract_2d_affine(), additional_element_transform.into()).into()- }-/// The stroke width the path's bounding box has to grow by: an invisible stroke takes up no/// room.// NB: CSS geometry-effect metadata relies on this reading only stroke color and width.@@ -1852,10 +1836,6 @@ impl<'pass> SvgFormattingContext<'pass> {self.update_svg_payload_of(node, |svg| svg.facts.viewport_transform = Some(transform));}- fn set_svg_viewport_size(&self, node: Node, viewport_size: FfiCssPixelSize) {- self.update_svg_payload_of(node, |svg| svg.facts.viewport_size = Some(viewport_size));- }-fn commit_svg_element_facts(&self, node: Node, facts: SvgElementFacts, attributes: FfiSvgAttributeFacts) {let mask_area_facts = (self.node_kind(node) == NodeKind::SVGMaskBox).then_some(SvgMaskAreaFacts {units_are_object_bounding_box: attributes.mask_units == SVG_UNITS_OBJECT_BOUNDING_BOX,@@ -1866,7 +1846,6 @@ impl<'pass> SvgFormattingContext<'pass> {});self.update_svg_payload_of(node, |svg| {let svg = &mut svg.facts;- svg.element_transform = (!facts.element_transform.is_identity()).then_some(facts.element_transform);svg.additional_element_transform =(!facts.additional_element_transform.is_identity()).then_some(facts.additional_element_transform);svg.mask_area_facts = mask_area_facts;@@ -1917,6 +1896,7 @@ impl<'pass> SvgFormattingContext<'pass> {fn commit_svg_geometry(&self, node: Node, geometry: SvgGeometry) {self.update_svg_payload_of(node, |svg| {svg.geometry = SvgGeometry {+ establishes_viewport: svg.geometry.establishes_viewport,established_viewport_user_rect: svg.geometry.established_viewport_user_rect,..geometry};@@ -2020,16 +2000,6 @@ impl<'pass> SvgFormattingContext<'pass> {return;}- if kind == NodeKind::SVGSVGBox {- self.set_svg_viewport_size(- self.run.box_,- FfiCssPixelSize {- width: cells.content_inline_size(),- height: cells.content_block_size(),- },- );- }-// Viewport-establishing boxes publish their viewBox/preserveAspectRatio transform for the// visual context tree; content below lays out in the viewport's user units. The value is// published even without a viewBox so viewBox changes stay value-only for the tree. A@@ -2089,11 +2059,15 @@ impl<'pass> SvgFormattingContext<'pass> {self.run.box_,|link| {link.and_then(|link| link.fragment.svg().map(|svg| svg.geometry))- .is_some_and(|committed| committed.established_viewport_user_rect == Some(viewport_user_rect))+ .is_some_and(|committed| {+ committed.establishes_viewport+ && committed.established_viewport_user_rect == viewport_user_rect+ })},);self.update_svg_payload_of(self.run.box_, |svg| {- svg.geometry.established_viewport_user_rect = Some(viewport_user_rect);+ svg.geometry.establishes_viewport = true;+ svg.geometry.established_viewport_user_rect = viewport_user_rect;});self.available_space = Some(input.available_space);self.quirks_mode_percentage_basis_block_size = input@@ -2224,13 +2198,6 @@ impl<'pass> SvgFormattingContext<'pass> {self.percentage_block_insets_of_run_root_children_have_definite_basis,);nested_context.lay_out_contents(run, self.nested_layout_input(), &viewport_cells);- self.set_svg_viewport_size(- viewport,- FfiCssPixelSize {- width: nested_viewport_width,- height: nested_viewport_height,- },- );let viewport_rect = SvgCssPixelRect {x: nested_viewport_x,y: nested_viewport_y,diff --git a/Libraries/LibWeb/Rust/src/layout/used_values.rs b/Libraries/LibWeb/Rust/src/layout/used_values.rsindex 59121bfa623..8ef7d14edef 100644--- a/Libraries/LibWeb/Rust/src/layout/used_values.rs+++ b/Libraries/LibWeb/Rust/src/layout/used_values.rs@@ -120,8 +120,6 @@ impl LineDataState {#[derive(Clone, Copy, Debug, Default, PartialEq)]pub(crate) struct CommittedSvgFacts {pub(crate) viewport_transform: Option<svg_formatting_context::FfiAffineTransform>,- pub(crate) viewport_size: Option<FfiCssPixelSize>,- pub(crate) element_transform: Option<svg_formatting_context::FfiAffineTransform>,pub(crate) additional_element_transform: Option<svg_formatting_context::FfiAffineTransform>,pub(crate) mask_area_facts: Option<svg_formatting_context::SvgMaskAreaFacts>,pub(crate) resource_content_units_are_object_bounding_box: bool,diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex 880b38ad9fd..e4bc7788e71 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -209,21 +209,25 @@ pub struct FfiBoxModelMetrics {pub inset: crate::painting::paintable_data::FfiPixelBox,}+/// The geometry the box of an SVG element committed, in the user units of the SVG viewport it is laid out in. Returns+/// false, writing nothing, for a box without one.#[unsafe(no_mangle)]-pub extern "C" fn render_state_paintable_svg_viewport_size(+pub extern "C" fn render_state_svg_geometry(host: &DocumentHost,slot: NodeSlotId,- out: &mut FfiCssPixelSize,-) {- *out = {- read_arena(host, node_read(), slot, |arena, slot| {- let paintable_rows = arena.paintable_rows();- if !paintable_rows.paintable_row_is_populated(slot) {- return FfiCssPixelSize::default();- }- crate::painting::paintable_geometry::committed_svg_viewport_size(&paintable_rows, slot)- })+ out: &mut svg_formatting_context::SvgGeometry,+) -> bool {+ let geometry = read_arena(host, node_read(), slot, |arena, slot| {+ if !arena.paintable_row_is_populated(slot) {+ return None;+ }+ crate::painting::paintable_geometry::committed_svg_geometry(arena, slot)+ });+ let Some(geometry) = geometry else {+ return false;};+ *out = geometry;+ true}#[repr(C)]@@ -250,19 +254,16 @@ pub extern "C" fn render_state_paintable_svg_viewport_transform(})}-/// The transform an SVG element's box was laid out with: its own CSS transform reduced to 2D, with a <use> element's-/// x/y translation multiplied in.+/// The transform an SVG element's box was laid out with: its own CSS transform about its transform origin, reduced to+/// 2D, with a <use> element's x/y translation multiplied in.#[unsafe(no_mangle)]pub extern "C" fn render_state_paintable_svg_element_transform(host: &DocumentHost,slot: NodeSlotId,) -> svg_formatting_context::FfiAffineTransform {- read_arena(host, node_read(), slot, |arena, slot| {- if !arena.paintable_row_is_populated(slot) {- return svg_formatting_context::FfiAffineTransform::default();- }- crate::painting::paintable_geometry::committed_svg_element_transform(arena, slot).unwrap_or_default()- })+ let mut geometry = svg_formatting_context::SvgGeometry::default();+ render_state_svg_geometry(host, slot, &mut geometry);+ geometry.local_transform}#[unsafe(no_mangle)]@@ -686,28 +687,6 @@ pub unsafe extern "C" fn ladybird_web_record_image_paint_display_list(}}-/// The bounds of the geometry that a path-like SVG element's box committed. Returns false for any other box.-#[unsafe(no_mangle)]-pub extern "C" fn render_state_paintable_computed_svg_path_bounding_box(- host: &DocumentHost,- paintable: NodeSlotId,- out: &mut libgfx_rust::FloatRect,-) -> bool {- let bounding_box = read_arena(host, node_read(), paintable, |arena, paintable| {- let paintable_rows = arena.paintable_rows();- if !paintable_rows.paintable_row_is_populated(paintable) {- return None;- }- crate::painting::paintable_geometry::committed_svg_path(&paintable_rows, paintable)- .map(|path| path.bounding_box())- });- let Some(bounding_box) = bounding_box else {- return false;- };- *out = libgfx_rust::FloatRect::from_array(bounding_box);- true-}-/// The glyph cells a text content element's box committed for its own characters, one per code/// unit. The cells belong to the committed fragment, so they are read before the next commit.#[repr(C)]diff --git a/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rs b/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rsindex 85e2842f21d..9a5d541226f 100644--- a/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rs+++ b/Libraries/LibWeb/Rust/src/painting/paintable_geometry.rs@@ -186,25 +186,6 @@ pub(crate) fn committed_svg_viewport_transform(})}-pub(crate) fn committed_svg_viewport_size(arena: &impl GeometryRead, slot: NodeSlotId) -> used_values::FfiCssPixelSize {- if arena.node_kind_if_live(slot) != Some(crate::layout::node_data::NodeKind::SVGSVGBox) {- return used_values::FfiCssPixelSize::default();- }- arena.with_committed_fragment_link(slot, |link| {- link.and_then(|link| link.fragment.svg()?.facts.viewport_size)- .unwrap_or_default()- })-}--pub(crate) fn committed_svg_element_transform(- arena: &impl GeometryRead,- slot: NodeSlotId,-) -> Option<svg_formatting_context::FfiAffineTransform> {- arena.with_committed_fragment_link(slot, |link| {- link.and_then(|link| link.fragment.svg()?.facts.element_transform)- })-}-pub(crate) fn committed_svg_additional_element_transform(arena: &impl GeometryRead,slot: NodeSlotId,diff --git a/Libraries/LibWeb/SVG/SVGElement.cpp b/Libraries/LibWeb/SVG/SVGElement.cppindex 92a0871248e..d9df6fecb7c 100644--- a/Libraries/LibWeb/SVG/SVGElement.cpp+++ b/Libraries/LibWeb/SVG/SVGElement.cpp@@ -757,41 +757,28 @@ GC::Ptr<SVGElement> SVGElement::viewport_element()Gfx::Size<double> SVGElement::viewport_size_for_percentage_resolution(Layout::BegunRead const& read){- auto viewport_size_from_layout = [&](SVGSVGElement const& viewport_element) -> Gfx::Size<double> {+ auto committed_geometry = [&](SVGElement const& element) -> Optional<Layout::RustFFI::SvgGeometry> {// NB: A disconnected element may have stale layout objects from before it was removed.- if (!viewport_element.is_connected())+ auto const* layout_node = element.is_connected() ? element.layout_node(read) : nullptr;+ if (!layout_node)return {};-- auto const* layout_node = viewport_element.layout_node(read);- if (layout_node && Painting::has_committed_box(*layout_node) && Painting::is_svg_svg_paintable(*layout_node))- return Painting::svg_viewport_size(*layout_node).to_type<double>();-- return {};+ return Painting::svg_geometry(*layout_node);};- // NB: Percentages for SVGSVGElements are resolved irrespective of it's own viewBox (which only affects the internal- // coordinate system)- if (auto* svg_element = as_if<SVGSVGElement>(*this)) {- auto const* parent = svg_element->parent_or_shadow_host_element();-- // https://w3c.github.io/svgwg/svg2-draft/coords.html#InitialViewport- if (!parent || !is<SVGElement>(*parent))- return viewport_size_from_layout(*svg_element);-- // https://w3c.github.io/svgwg/svg2-draft/coords.html#EstablishingANewSVGViewport- if (is<SVGForeignObjectElement>(*parent))- return viewport_size_from_layout(*svg_element);- }-- auto const& viewport_element = const_cast<SVGElement*>(this)->owner_svg_element().ptr();+ // NB: Layout committed the SVG viewport that a rendered element's own lengths resolve against. An outermost svg+ // element resolves against its own size, irrespective of its viewBox.+ if (auto geometry = committed_geometry(*this); geometry.has_value())+ return geometry->viewport_user_rect.size().to_type<double>();+ // An element without geometry resolves against the SVG viewport that its nearest svg ancestor establishes.+ auto viewport_element = owner_svg_element();if (!viewport_element)return {};-+ if (auto geometry = committed_geometry(*viewport_element); geometry.has_value() && geometry->establishes_viewport)+ return geometry->established_viewport_user_rect.size().to_type<double>();if (auto view_box = viewport_element->active_view_box(); view_box.has_value() && view_box->width > 0 && view_box->height > 0)return { view_box->width, view_box->height };-- return viewport_size_from_layout(*viewport_element);+ return {};}GC::Ref<SVGAnimatedLength> SVGElement::svg_animated_length_for_attribute(Utf16FlyString const& attribute_name, SVGLength::Directionality directionality, SVGLengthValue default_value)diff --git a/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp b/Libraries/LibWeb/SVG/SVGGraphicsElement.cppindex 7530b36334b..3622deffa46 100644--- a/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp+++ b/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp@@ -227,70 +227,38 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMRect>> SVGGraphicsElement::get_b_box(Biauto const* self_layout_node = layout_node(read);if (!self_layout_node)return Geometry::DOMRect::create();- auto owner_svg_element = this->owner_svg_element();- // The outermost svg element has no ancestor svg element to measure against; per the bounding box- // algorithm its bounding box is the union of its children's bounding boxes in its own user- // coordinate system, with each child's own transforms kept.- if (!owner_svg_element) {- if (!is<SVGSVGElement>(*this))- return Geometry::DOMRect::create();- if (!Painting::has_committed_box(*self_layout_node))- return Geometry::DOMRect::create();- Gfx::FloatRect united_rect;- for (auto const* child = self_layout_node->first_child_ptr(); child; child = child->next_sibling_ptr()) {- switch (child->kind()) {- case Layout::RustFFI::NodeKind::SVGMaskBox:- case Layout::RustFFI::NodeKind::SVGClipBox:- case Layout::RustFFI::NodeKind::SVGPatternBox:- continue;- default:- break;- }- if (!Painting::has_committed_box(*child))- continue;- auto child_rect = Painting::svg_element_transform(*child).map(Painting::absolute_rect(*child).to_type<float>());- united_rect.unite(child_rect);+ auto owner_svg_element = this->owner_svg_element();+ if (owner_svg_element) {+ auto const* owner_layout_node = owner_svg_element->layout_node(read);+ if (!owner_layout_node || !Painting::has_committed_box(*owner_layout_node) || !Painting::has_committed_box(*self_layout_node)) {+ // Throw only for non-rendered *graphics* elements where geometry isn't computable+ // (e.g. elements inside <marker>, <pattern>, etc.).+ if (is<SVGSVGElement>(*this))+ return Geometry::DOMRect::create();+ return WebIDL::InvalidStateError::create(+ HTML::relevant_realm(*this),+ "Element is not rendered and geometry is not computable"_utf16);}- if (united_rect.is_empty())- return Geometry::DOMRect::create();- return Geometry::DOMRect::create(united_rect);- }-- auto const* owner_layout_node = owner_svg_element->layout_node(read);- if (!owner_layout_node || !Painting::has_committed_box(*owner_layout_node) || !Painting::has_committed_box(*self_layout_node)) {- // Throw only for non-rendered *graphics* elements where geometry isn't computable- // (e.g. elements inside <marker>, <pattern>, etc.).- if (is<SVGSVGElement>(*this))- return Geometry::DOMRect::create();- return WebIDL::InvalidStateError::create(- HTML::relevant_realm(*this),- "Element is not rendered and geometry is not computable"_utf16);+ } else if (!is<SVGSVGElement>(*this)) {+ return Geometry::DOMRect::create();}// https://svgwg.org/svg2-draft/coords.html#BoundingBoxes- // Let fill-shape be the equivalent path of element if it is a shape, or a shape that includes each of the glyph- // cells corresponding to the text within the elements otherwise.- // NB: Layout sizes a text content element's box to exactly that: The glyph cells of all the text within it.- if (self_layout_node->kind() == Layout::RustFFI::NodeKind::SVGTextBox || self_layout_node->kind() == Layout::RustFFI::NodeKind::SVGTextPathBox) {- auto rect = Painting::absolute_rect(*self_layout_node).to_type<float>();- if (rect.is_empty())- return Geometry::DOMRect::create();- return Geometry::DOMRect::create(rect);- }-- // A path-like element's bounding box covers its geometry alone; the committed content rect is- // inflated by the visible stroke width, so take the unstroked path bounds directly.- if (auto committed_path_bounding_box = Painting::committed_svg_path_bounding_box(*self_layout_node); committed_path_bounding_box.has_value())- return Geometry::DOMRect::create(*committed_path_bounding_box);-- auto rect = Painting::absolute_rect(*self_layout_node).to_type<float>();- // An element with a non-positive geometry dimension is not rendered and- // therefore contributes an empty bounding box, regardless of its- // positioning rectangle's origin.- if (rect.width() <= 0 || rect.height() <= 0)+ // NB: Layout commits each element's object bounding box in its user coordinate system: a shape's path, the glyph+ // cells of text, and for a container, including the outermost svg element, the union of its children's, each+ // through the child's own transform. A foreign object's box comes from a layout of its own, which commits no SVG+ // geometry; the box is its bounding box.+ auto geometry = Painting::svg_geometry(*self_layout_node);+ if (!geometry.has_value() && !owner_svg_element)+ return Geometry::DOMRect::create();+ auto bounding_box = geometry.has_value() ? geometry->object_bounding_box : Painting::absolute_rect(*self_layout_node).to_type<float>();+ // An element other than a shape or a container with a non-positive geometry dimension is not rendered and+ // therefore contributes an empty bounding box, regardless of its positioning rectangle's origin.+ auto kind = self_layout_node->kind();+ if (kind != Layout::RustFFI::NodeKind::SVGGeometryBox && kind != Layout::RustFFI::NodeKind::SVGGraphicsBox && bounding_box.is_empty())return Geometry::DOMRect::create();- return Geometry::DOMRect::create(rect);+ return Geometry::DOMRect::create(bounding_box);}// https://svgwg.org/svg2-draft/types.html#__svg__SVGGraphicsElement__transformdiff --git a/Tests/LibWeb/Text/expected/SVG/getCTM-transform-origin.txt b/Tests/LibWeb/Text/expected/SVG/getCTM-transform-origin.txtnew file mode 100644index 00000000000..8fd73d66604--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/getCTM-transform-origin.txt@@ -0,0 +1,13 @@+attribute-transform-with-origin: getCTM=[0, 1, -1, 0, 100, 0] getScreenCTM=[0, 1, -1, 0, 100, 0]+ getBoundingClientRect=(80, 0, 20, 40)+style-transform-with-origin: getCTM=[0, 1, -1, 0, 100, 0] getScreenCTM=[0, 1, -1, 0, 100, 0]+ getBoundingClientRect=(80, 0, 20, 40)+fill-box-center: getCTM=[0, 1, -1, 0, 30, -10] getScreenCTM=[0, 1, -1, 0, 30, -10]+ getBoundingClientRect=(10, -10, 20, 40)+stroked-stroke-box-top-left: getCTM=[0, 1, -1, 0, -10, 0] getScreenCTM=[0, 1, -1, 0, -10, 0]+offset-svg-fill-box-center: getCTM=[0, 1, -1, 0, 60, 0] getScreenCTM=[0, 1, -1, 0, 110, 230]+ getBoundingClientRect=(70, 240, 20, 40)+nested-viewport-view-box-center: getCTM=[0, 2, -2, 0, 120, 10] getScreenCTM=[0, 2, -2, 0, 170, 240]+ getBoundingClientRect=(150, 240, 20, 20)+nested-viewport-in-scaled-group: getCTM=[4, 0, 0, 4, 20, -10] getScreenCTM=[4, 0, 0, 4, 70, 220]+ getBoundingClientRect=(70, 220, 40, 40)diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-01.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-01.txtindex fd265dbe758..7cf44b3cdd1 100644--- a/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-01.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-01.txt@@ -2,8 +2,8 @@ Harness status: OKFound 19 tests-8 Pass-11 Fail+9 Pass+10 FailPass getBBox on detached elementPass getBBox on polygon with no points attributePass getBBox on polyline with no points attribute@@ -19,7 +19,7 @@ Fail polyline doesn't contribute to parent bboxFail polygon with no valid points doesn't contribute to parent bboxFail polyline with no valid points doesn't contribute to parent bboxPass getBBox on path with no height-Fail path with no height should contribute to parent bbox+Pass path with no height should contribute to parent bboxFail arc bbox should be tightFail empty foreignObject does not contribute to parent bboxFail empty image does not contribute to parent bbox\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-04.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-04.txtnew file mode 100644index 00000000000..c0d93b852b1--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-04.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass SVGGraphicsElement.prototype.getBBox for containers that have children added/removed\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-06.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-06.txtnew file mode 100644index 00000000000..388db813527--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-06.txt@@ -0,0 +1,8 @@+Harness status: OK++Found 3 tests++3 Pass+Pass Non-rendered symbol with rect returns zero bbox+Pass display:none <g> with rect returns zero bbox+Pass display:none <rect> returns zero bbox\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/SVG/getCTM-transform-origin.html b/Tests/LibWeb/Text/input/SVG/getCTM-transform-origin.htmlnew file mode 100644index 00000000000..b65c2b2c963--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/getCTM-transform-origin.html@@ -0,0 +1,39 @@+<!DOCTYPE html>+<style>+ body {+ margin: 0;+ }+ svg {+ display: block;+ }+</style>+<svg width="200" height="200">+ <rect id="attribute-transform-with-origin" width="40" height="20" transform="rotate(90)" style="transform-origin: 50px 50px" />+ <rect id="style-transform-with-origin" width="40" height="20" style="transform: rotate(90deg); transform-origin: 50px 50px" />+ <rect id="fill-box-center" width="40" height="20" style="transform: rotate(90deg); transform-box: fill-box; transform-origin: center" />+ <rect id="stroked-stroke-box-top-left" width="40" height="20" stroke="black" stroke-width="10" style="transform: rotate(90deg); transform-box: stroke-box; transform-origin: left top" />+</svg>+<svg width="200" height="200" style="margin: 30px 0 0 50px">+ <rect id="offset-svg-fill-box-center" x="10" y="20" width="40" height="20" style="transform: rotate(90deg); transform-box: fill-box; transform-origin: center" />+ <svg x="20" y="10" width="100" height="100" viewBox="0 0 50 50">+ <rect id="nested-viewport-view-box-center" width="10" height="10" style="transform: rotate(90deg); transform-box: view-box; transform-origin: center" />+ <g style="transform: scale(2); transform-origin: 10px 10px">+ <rect id="nested-viewport-in-scaled-group" width="10" height="10" style="transform: translate(50%, 0); transform-box: fill-box" />+ </g>+ </svg>+</svg>+<script src="../include.js"></script>+<script>+ test(() => {+ const round = value => Math.round(value * 1000) / 1000 || 0;+ const matrix = m => `[${[m.a, m.b, m.c, m.d, m.e, m.f].map(round).join(", ")}]`;+ for (const element of document.querySelectorAll("rect[id]")) {+ println(`${element.id}: getCTM=${matrix(element.getCTM())} getScreenCTM=${matrix(element.getScreenCTM())}`);+ // NB: Only the transforms of the stroked shape are checked.+ if (!element.hasAttribute("stroke")) {+ const rect = element.getBoundingClientRect();+ println(` getBoundingClientRect=(${rect.x}, ${rect.y}, ${rect.width}, ${rect.height})`);+ }+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-04.html b/Tests/LibWeb/Text/input/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-04.htmlnew file mode 100644index 00000000000..f0866dcc8de--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-04.html@@ -0,0 +1,55 @@+<!DOCTYPE html>+<title>SVGGraphicsElement.prototype.getBBox for containers that have children added/removed</title>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/geometry.html#Sizing">+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/types.html#__svg__SVGGraphicsElement__getBBox">+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/coords.html#BoundingBoxes">+<svg>+ <g>+ <rect width="10" height="20"/>+ <rect x="20" y="20" width="20" height="20"/>+ </g>+ <rect x="50" y="50" width="50" height="50"/>+</svg>+<script>+function assert_bbox(element, x, y, width, height, description) {+ const bbox = element.getBBox();+ assert_equals(bbox.x, x, `x:${description ?? ''}`);+ assert_equals(bbox.y, y, `y:${description ?? ''}`);+ assert_equals(bbox.width, width, `width:${description ?? ''}`);+ assert_equals(bbox.height, height, `height:${description ?? ''}`);+}++test(t => {+ const svg = document.querySelector('svg');+ const g = document.querySelector('svg > g');+ const rects = Array.from(document.getElementsByTagName('rect'));+ assert_bbox(g, 0, 0, 40, 40);+ assert_bbox(svg, 0, 0, 100, 100);++ rects[0].remove();+ assert_bbox(g, 20, 20, 20, 20, 'removed rect 1');+ assert_bbox(svg, 20, 20, 80, 80, 'removed rect 1');++ rects[2].remove();+ assert_bbox(g, 20, 20, 20, 20, 'removed rect 3');+ assert_bbox(svg, 20, 20, 20, 20, 'removed rect 3');++ rects[1].remove();+ assert_bbox(g, 0, 0, 0, 0, 'removed rect 2');+ assert_bbox(svg, 0, 0, 0, 0, 'removed rect 2');++ g.appendChild(rects[1]);+ assert_bbox(g, 20, 20, 20, 20, 'added rect 2');+ assert_bbox(svg, 20, 20, 20, 20, 'added rect 2');++ svg.appendChild(rects[2]);+ assert_bbox(g, 20, 20, 20, 20, 'added rect 3');+ assert_bbox(svg, 20, 20, 80, 80, 'added rect 3');++ g.appendChild(rects[0]);+ assert_bbox(g, 0, 0, 40, 40, 'added rect 1');+ assert_bbox(svg, 0, 0, 100, 100, 'added rect 1');+});+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-06.html b/Tests/LibWeb/Text/input/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-06.htmlnew file mode 100644index 00000000000..7811cb5891d--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/svg/types/scripted/SVGGraphicsElement.getBBox-06.html@@ -0,0 +1,41 @@+<!DOCTYPE html>+<title>SVGGraphicsElement.prototype.getBBox for non-rendered elements</title>+<link rel="help" href="https://w3c.github.io/svgwg/svg2-draft/coords.html#BoundingBoxes">+<link rel="help" href="https://github.com/w3c/svgwg/issues/1018">+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" width="500px" height="500px">+ <symbol id="symbol1">+ <rect id="symbol1_rect" x="50" y="60" width="100" height="150"></rect>+ </symbol>+ <g id="g_none" style="display:none">+ <rect id="g_none_rect" x="70" y="80" width="200" height="250"></rect>+ </g>+ <rect id="none_rect" x="90" y="100" width="20" height="25" display="none"></rect>+</svg>+<script>+ function assert_bbox(id, x, y, width, height) {+ let bbox = document.getElementById(id).getBBox();+ assert_equals(bbox.x, x, id + ".getBBox().x");+ assert_equals(bbox.y, y, id + ".getBBox().y");+ assert_equals(bbox.width, width, id + ".getBBox().width");+ assert_equals(bbox.height, height, id + ".getBBox().height");+ }++ // Per resolution (issue #1018): non-rendered elements return zero bbox+ // instead of throwing InvalidStateError.++ test(() => {+ assert_bbox("symbol1", 0, 0, 0, 0);+ assert_bbox("symbol1_rect", 0, 0, 0, 0);+ }, "Non-rendered symbol with rect returns zero bbox");++ test(() => {+ assert_bbox("g_none", 0, 0, 0, 0);+ assert_bbox("g_none_rect", 0, 0, 0, 0);+ }, "display:none <g> with rect returns zero bbox");++ test(() => {+ assert_bbox("none_rect", 0, 0, 0, 0);+ }, "display:none <rect> returns zero bbox");+</script>