Truly independent web browser
LibWeb: Lay out SVG elements in records their calls own
Aliaksandr Kalenik8d1b40601473
diff --git a/Libraries/LibWeb/Rust/src/layout/run_records.rs b/Libraries/LibWeb/Rust/src/layout/run_records.rsindex 359806a2d8e..46a5e373266 100644--- a/Libraries/LibWeb/Rust/src/layout/run_records.rs+++ b/Libraries/LibWeb/Rust/src/layout/run_records.rs@@ -135,6 +135,9 @@ struct KeptBox {enum KeptBoxHolding {/// A box this run lays out itself, with its record on the record stack.LaidOutByThisRun { record: u32 },+ /// A box this run lays out itself, in a record that the layout of the box owns: the call laying it out, or the+ /// formatting context it lays the box out for.+ LaidOutInRecordItsLayoutOwns,/// A child this run hands to a run of its own, with the cells it starts out with, until that run returns.ChildNotYetLaidOut {cells_before_its_run: used_values::RootInputCells,@@ -679,6 +682,13 @@ impl<'arena> RunRecords<'arena> {unsafe { record.as_ref() }}+ /// Keeps `node`, a box this run lays out in a record that the layout of the box owns, for what the box's parent+ /// decides about it.+ pub(crate) fn keep_box_laid_out_in_record_its_layout_owns(&self, node: Node) {+ self.assert_registers_in_innermost_run(node);+ self.keep(node, KeptBoxHolding::LaidOutInRecordItsLayoutOwns);+ }+/// Keeps `child`, which this run hands to a run of its own, with the cells it starts out with, which it returns.pub(crate) fn keep_child_for_its_run(&self,@@ -710,7 +720,7 @@ impl<'arena> RunRecords<'arena> {};!matches!(self.scratch.kept_boxes.borrow()[index as usize].holding,- KeptBoxHolding::LaidOutByThisRun { .. }+ KeptBoxHolding::LaidOutByThisRun { .. } | KeptBoxHolding::LaidOutInRecordItsLayoutOwns)}@@ -734,7 +744,10 @@ impl<'arena> RunRecords<'arena> {let (record_index, record) = self.scratch.run_record_stack.push(cells.materialize_record(frame));let holding = &mut self.scratch.kept_boxes.borrow_mut()[index as usize].holding;assert!(- !matches!(holding, KeptBoxHolding::LaidOutByThisRun { .. }),+ !matches!(+ holding,+ KeptBoxHolding::LaidOutByThisRun { .. } | KeptBoxHolding::LaidOutInRecordItsLayoutOwns+ ),"slot {} already has a record in the run rooted at slot {}",child.slot_index(),self.root.slot_index()@@ -810,7 +823,9 @@ impl<'arena> RunRecords<'arena> {KeptBoxHolding::LaidOutByThisRun { record } => {Some(unsafe { self.scratch.run_record_stack.get(record).as_ref() })}- KeptBoxHolding::ChildNotYetLaidOut { .. } | KeptBoxHolding::ChildHandedBack => None,+ KeptBoxHolding::LaidOutInRecordItsLayoutOwns+ | KeptBoxHolding::ChildNotYetLaidOut { .. }+ | KeptBoxHolding::ChildHandedBack => None,},}}@@ -830,6 +845,16 @@ impl<'arena> RunRecords<'arena> {)}+ #[track_caller]+ fn panic_for_box_read_outside_the_layout_owning_its_record(&self, node: Node) -> ! {+ panic!(+ "the run rooted at slot {} reads slot {}, whose layout keeps it in a record of its own (read at {})",+ self.root.slot_index(),+ node.slot_index(),+ std::panic::Location::caller(),+ )+ }+#[track_caller]fn panic_for_box_not_held(&self, node: Node) -> ! {panic!(@@ -1104,7 +1129,10 @@ impl<'arena> RunRecords<'arena> {};let holding = &mut self.scratch.kept_boxes.borrow_mut()[index as usize].holding;assert!(- !matches!(holding, KeptBoxHolding::LaidOutByThisRun { .. }),+ !matches!(+ holding,+ KeptBoxHolding::LaidOutByThisRun { .. } | KeptBoxHolding::LaidOutInRecordItsLayoutOwns+ ),"{child:?} is handed back by a run of its own to a parent that lays it out itself");*holding = KeptBoxHolding::ChildHandedBack;@@ -1139,6 +1167,9 @@ impl<'arena> RunRecords<'arena> {return Some(BoxMetrics::NotYetLaidOut(*cells_before_its_run));}KeptBoxHolding::ChildHandedBack => self.panic_for_child_read_after_its_run_handed_it_back(node),+ KeptBoxHolding::LaidOutInRecordItsLayoutOwns => {+ self.panic_for_box_read_outside_the_layout_owning_its_record(node)+ }};// SAFETY: This run registered the record, and it stays on the stack until this run returns.Some(BoxMetrics::LaidOutByThisRun(@@ -1191,6 +1222,9 @@ impl<'arena> RunRecords<'arena> {return Some(*cells_before_its_run);}KeptBoxHolding::ChildHandedBack => self.panic_for_child_read_after_its_run_handed_it_back(node),+ KeptBoxHolding::LaidOutInRecordItsLayoutOwns => {+ self.panic_for_box_read_outside_the_layout_owning_its_record(node)+ }};// SAFETY: This run registered the record, and it stays on the stack until this run returns.Some(cells_of_record(unsafe {@@ -1222,6 +1256,9 @@ impl<'arena> RunRecords<'arena> {KeptBoxHolding::ChildNotYetLaidOut { .. } | KeptBoxHolding::ChildHandedBack => {panic!("the fragment of {node:?} is built from the box its run hands back to its parent")}+ KeptBoxHolding::LaidOutInRecordItsLayoutOwns => {+ self.panic_for_box_read_outside_the_layout_owning_its_record(node)+ }};// SAFETY: This run registered the record, and it stays on the stack until this run returns.geometry_of_record(unsafe { self.scratch.run_record_stack.get(record).as_ref() })diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rsindex c022c886b19..a5588d81e6f 100644--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs@@ -325,6 +325,14 @@ fn kind_is_svg_container_element(kind: NodeKind) -> bool {)}+/// What the layout of an SVG element hands its parent: the element's sizes and box sides, and the offset of its content+/// box.+#[derive(Clone, Copy)]+struct LaidOutSvgElement {+ cells: used_values::RootInputCells,+ content_offset: FfiCssPixelPoint,+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]struct SvgCssPixelRect {x: CssPixels,@@ -1829,13 +1837,14 @@ impl<'pass> SvgFormattingContext<'pass> {self.run.records.used_values(node)}- fn create_used_values(&self, node: Node) -> &'pass UsedValues {+ /// A record for `node`, a box this context lays out in it, which the run keeps the box for without.+ fn create_used_values(&self, node: Node) -> UsedValues {// SVG descendants deliberately carry no percentage basis.// SVG layout resolves percentages against the SVG viewport, not a CSS containing// block, so boxes inside the SVG subtree carry no percentage basis.- self.run- .records- .create_used_values(&self.run.callbacks, node, ContainingBlockConstraints::default())+ let record = used_values::create_used_values(&self.run.callbacks, node, ContainingBlockConstraints::default());+ self.run.records.keep_box_laid_out_in_record_its_layout_owns(node);+ record}fn set_svg_viewport_transform(&self, node: Node, transform: FfiAffineTransform) {@@ -1869,10 +1878,16 @@ impl<'pass> SvgFormattingContext<'pass> {});}- /// Places `node`, a box this context lays out in its record.- fn place_child(&self, node: Node, x: CssPixels, y: CssPixels) {- let placed_child = formatting_context::PlacedChild::of_record(self.used_values(node), &self.run);+ /// Places `node`, a box this context lays out in `record`, whose metrics are final once the box is placed, and+ /// returns what the parent of the box reads of it.+ fn place_child(&self, node: Node, record: &UsedValues, x: CssPixels, y: CssPixels) -> LaidOutSvgElement {+ let placed_child = formatting_context::PlacedChild::of_record(record, &self.run);self.place_laid_out_child(node, placed_child, x, y, None);+ record.seal_own_metrics();+ LaidOutSvgElement {+ cells: used_values::RootInputCells::capture(record),+ content_offset: FfiCssPixelPoint { x, y },+ }}fn place_laid_out_child(@@ -1893,17 +1908,16 @@ impl<'pass> SvgFormattingContext<'pass> {);}- /// Gives `node` a content size that is definite in both axes.- fn set_definite_content_size(&self, node: Node, width: CssPixels, height: CssPixels) {- let used = self.used_values(node);+ /// Gives the box laid out in `used` a content size that is definite in both axes.+ fn set_definite_content_size(used: &UsedValues, width: CssPixels, height: CssPixels) {used.set_content_inline_size(width);used.set_content_block_size(height);used.has_definite_block_size.set(true);}- fn set_content_rect(&self, node: Node, rect: SvgCssPixelRect) {- self.set_definite_content_size(node, rect.width, rect.height);- self.place_child(node, rect.x, rect.y);+ fn set_content_rect(&self, node: Node, used: &UsedValues, rect: SvgCssPixelRect) -> LaidOutSvgElement {+ Self::set_definite_content_size(used, rect.width, rect.height);+ self.place_child(node, used, rect.x, rect.y)}fn first_child_of_kind(&self, node: Node, kind: NodeKind) -> Option<Node> {@@ -1914,13 +1928,17 @@ impl<'pass> SvgFormattingContext<'pass> {}pub(super) fn run(&mut self, run: &FormattingContextRun<'pass>, input: LayoutInput) {+ let used = self.used_values(self.run.box_);+ self.lay_out_contents(run, input, used);+ }++ /// Lays out the contents of this context's box, which is laid out in `used`.+ fn lay_out_contents(&mut self, run: &FormattingContextRun<'pass>, input: LayoutInput, used: &UsedValues) {// NOTE: SVG doesn't have a "formatting context" in the spec, but this is the most// obvious way to drive SVG layout in our engine at the moment.let kind = self.node_kind(self.run.box_);let facts = self.svg_facts(self.run.box_);let attributes = self.svg_attributes(self.run.box_);- let used_pointer = self.used_values(self.run.box_);- let used = &used_pointer;self.commit_svg_element_facts(self.run.box_, facts, attributes);if facts.is_document_element@@ -2035,16 +2053,11 @@ impl<'pass> SvgFormattingContext<'pass> {}}- /// Lays out and places `child`, and returns its sizes and box sides where a run of its own laid it out, as that- /// run handed them back.- fn layout_svg_element(- &mut self,- run: &FormattingContextRun<'pass>,- child: Node,- ) -> Option<used_values::RootInputCells> {+ /// Lays out and places `child`, and returns what its parent reads of it, if it laid it out.+ fn layout_svg_element(&mut self, run: &FormattingContextRun<'pass>, child: Node) -> Option<LaidOutSvgElement> {let kind = self.node_kind(child);if self.svg_attributes(child).is_fit_to_view_box {- self.layout_nested_viewport(run, child);+ return Some(self.layout_nested_viewport(run, child));} else if kind == NodeKind::SVGForeignObjectBox {// SVG descendants carry no percentage basis, as `create_used_values` explains.let mut child_cells = self.run.records.keep_child_for_its_run(@@ -2107,17 +2120,20 @@ impl<'pass> SvgFormattingContext<'pass> {if let Some(clip) = self.first_child_of_kind(child, NodeKind::SVGClipBox) {self.layout_mask_or_clip(run, clip, &laid_out_box.cells);}- return Some(laid_out_box.cells);+ return Some(LaidOutSvgElement {+ cells: laid_out_box.cells,+ content_offset: FfiCssPixelPoint { x: rect.x, y: rect.y },+ });} else if kind_is_svg_graphics_box(kind) {- self.layout_graphics_element(run, child);+ return Some(self.layout_graphics_element(run, child));}None}- fn layout_nested_viewport(&mut self, run: &FormattingContextRun<'pass>, viewport: Node) {+ fn layout_nested_viewport(&mut self, run: &FormattingContextRun<'pass>, viewport: Node) -> LaidOutSvgElement {// Layout for a nested SVG viewport.// https://svgwg.org/svg2-draft/coords.html#EstablishingANewSVGViewport.- self.create_used_values(viewport);+ let used = self.create_used_values(viewport);let style = self.style(viewport);let nested_viewport_x = style.x().to_px(self.viewport_width);let nested_viewport_y = style.y().to_px(self.viewport_height);@@ -2134,10 +2150,10 @@ impl<'pass> SvgFormattingContext<'pass> {style.height().to_px(self.viewport_height)};- self.set_definite_content_size(viewport, nested_viewport_width, nested_viewport_height);+ Self::set_definite_content_size(&used, nested_viewport_width, nested_viewport_height);let mut nested_context = Self::new_nested(run, viewport);- nested_context.run(run, self.nested_layout_input());+ nested_context.lay_out_contents(run, self.nested_layout_input(), &used);self.set_svg_viewport_size(viewport,FfiCssPixelSize {@@ -2145,14 +2161,14 @@ impl<'pass> SvgFormattingContext<'pass> {height: nested_viewport_height,},);- self.place_child(viewport, nested_viewport_x, nested_viewport_y);+ self.place_child(viewport, &used, nested_viewport_x, nested_viewport_y)}- fn layout_graphics_element(&mut self, run: &FormattingContextRun<'pass>, graphics_box: Node) {- self.create_used_values(graphics_box);+ fn layout_graphics_element(&mut self, run: &FormattingContextRun<'pass>, graphics_box: Node) -> LaidOutSvgElement {+ let used = self.create_used_values(graphics_box);let facts = self.svg_facts(graphics_box);- if self.place_unchanged_committed_shape(graphics_box, facts) {- return;+ if let Some(laid_out) = self.place_unchanged_committed_shape(graphics_box, &used, facts) {+ return laid_out;}self.commit_svg_element_facts(graphics_box, facts, self.svg_attributes(graphics_box));let kind = self.node_kind(graphics_box);@@ -2161,75 +2177,70 @@ impl<'pass> SvgFormattingContext<'pass> {// container element// An element which can have graphics elements and other container elements as child elements.// Specifically: ‘a’, ‘clipPath’, ‘defs’, ‘g’, ‘marker’, ‘mask’, ‘pattern’, ‘svg’, ‘switch’ and ‘symbol’.- if kind_is_svg_container_element(kind) {+ let laid_out = if kind_is_svg_container_element(kind) {// https://svgwg.org/svg2-draft/struct.html#Groups// 5.2. Grouping: the ‘g’ element// The ‘g’ element is a container element for grouping together related graphics elements.- self.layout_container_element(run, graphics_box);+ self.layout_container_element(run, graphics_box, &used)} else if kind == NodeKind::SVGImageBox {- self.layout_image_element(graphics_box);+ self.layout_image_element(graphics_box, &used)} else {// Assume this is a path-like element.- self.layout_path_like_element(run, graphics_box, facts);- }+ self.layout_path_like_element(run, graphics_box, &used, facts)+ };- // NB: The graphics element is laid out by this run, in the record it keeps.- let graphics_box_metrics = || run.records.box_metrics_of(graphics_box).input_cells();if let Some(mask) = self.first_child_of_kind(graphics_box, NodeKind::SVGMaskBox) {- self.layout_mask_or_clip(run, mask, &graphics_box_metrics());+ self.layout_mask_or_clip(run, mask, &laid_out.cells);}if let Some(clip) = self.first_child_of_kind(graphics_box, NodeKind::SVGClipBox) {- self.layout_mask_or_clip(run, clip, &graphics_box_metrics());+ self.layout_mask_or_clip(run, clip, &laid_out.cells);}for child in self.run.callbacks.children(graphics_box) {if self.node_kind(child) == NodeKind::SVGPatternBox {- self.layout_mask_or_clip(run, child, &graphics_box_metrics());+ self.layout_mask_or_clip(run, child, &laid_out.cells);}}+ laid_out}/// Places a shape with the fragment it last committed, where laying it out again would produce that fragment: the/// shape has no boxes below it, nothing marked it for layout since that commit, and it resolves against the viewport/// it was committed in. Then neither this pass nor the commit redoes a shape that a change to a sibling did not- /// touch. Answers whether it placed the shape.- fn place_unchanged_committed_shape(&self, shape: Node, facts: SvgElementFacts) -> bool {+ /// touch. Returns what the parent of the shape reads of it, if it placed the shape, which is laid out in `used`.+ fn place_unchanged_committed_shape(+ &self,+ shape: Node,+ used: &UsedValues,+ facts: SvgElementFacts,+ ) -> Option<LaidOutSvgElement> {if !self.viewport_is_committed_viewport|| self.node_kind(shape) != NodeKind::SVGGeometryBox|| !self.first_child(shape).is_invalid(){- return false;+ return None;}// An anchor registers itself only when its box is placed with a fragment of its own.if NodeFacts::new(&self.run.callbacks, shape).has_anchor_names() {- return false;+ return None;}// A line's coordinates are attribute lengths resolved here against the initial containing block, the root font// and size query containers, and a change to any of those does not mark the line for layout.if self.svg_attributes(shape).geometry_kind == SVG_GEOMETRY_KIND_LINE {- return false;- }- if self.run.fragments.is_none() {- return false;+ return None;}+ self.run.fragments.as_ref()?;// A committed fragment stops being current when something marks its box for layout.- let Some(fragment) = self+ let fragment = self.run.callbacks.arena()- .with_current_committed_fragment(shape, |fragment| fragment.clone())- else {- return false;- };- if fragment.computed_svg_path.is_none() {- return false;- }- let Some(committed_offset) = crate::painting::paint_read::GeometryRead::with_committed_fragment_link(+ .with_current_committed_fragment(shape, |fragment| fragment.clone())?;+ fragment.computed_svg_path.as_ref()?;+ let committed_offset = crate::painting::paint_read::GeometryRead::with_committed_fragment_link(self.run.callbacks.arena(),shape,|link| link.map(|link| link.committed_offset),- ) else {- return false;- };+ )?;// The transforms and the stroke's percentage basis are what the shape's facts take from outside its own// geometry.let committed = fragment.svg.as_deref().copied().unwrap_or_default();@@ -2238,9 +2249,8 @@ impl<'pass> SvgFormattingContext<'pass> {!= (!facts.additional_element_transform.is_identity()).then_some(facts.additional_element_transform)|| committed.viewport_percentage_basis != facts.viewport_percentage_basis{- return false;+ return None;}- let used = self.used_values(shape);used.set_box_metrics_from_fragment(&fragment);used.has_definite_block_size.set(true);self.place_laid_out_child(@@ -2253,15 +2263,20 @@ impl<'pass> SvgFormattingContext<'pass> {reuses_subtree: false,}),);- true+ used.seal_own_metrics();+ Some(LaidOutSvgElement {+ cells: used_values::RootInputCells::capture(used),+ content_offset: committed_offset,+ })}fn layout_path_like_element(&mut self,run: &FormattingContextRun<'pass>,graphics_box: Node,+ used: &UsedValues,facts: SvgElementFacts,- ) {+ ) -> LaidOutSvgElement {// A shape's geometry is its own attributes and computed style against the viewport, and// text is its own character data shaped with its own font cascade, so the pass draws both.let kind = self.node_kind(graphics_box);@@ -2301,14 +2316,13 @@ impl<'pass> SvgFormattingContext<'pass> {// <text> and <tspan> elements can contain more text elements, whose glyph cells count toward this box too.for child in self.run.callbacks.children(graphics_box) {if matches!(self.node_kind(child), NodeKind::SVGTextBox | NodeKind::SVGTextPathBox) {- self.layout_graphics_element(run, child);- let child_used = self.used_values(child);- let offset = self.run.records.content_offset_or_origin(child);+ let laid_out_child = self.layout_graphics_element(run, child);+ let offset = laid_out_child.content_offset;bounding_box.unite(SvgCssPixelRect {x: offset.x,y: offset.y,- width: child_used.content_inline_size.get(),- height: child_used.content_block_size.get(),+ width: laid_out_child.cells.content_inline_size,+ height: laid_out_child.cells.content_block_size,});}}@@ -2318,7 +2332,7 @@ impl<'pass> SvgFormattingContext<'pass> {payloads.computed_svg_path = Some(std::sync::Arc::new(path));payloads.svg_text_character_cells = character_cells.map(std::sync::Arc::new);});- self.set_content_rect(graphics_box, bounding_box);+ self.set_content_rect(graphics_box, used, bounding_box)}// https://w3c.github.io/svgwg/svg2-draft/embedded.html#Placement@@ -2365,8 +2379,8 @@ impl<'pass> SvgFormattingContext<'pass> {}}- fn layout_image_element(&self, image_box: Node) {- self.set_content_rect(image_box, self.svg_image_bounding_box(image_box));+ fn layout_image_element(&self, image_box: Node, used: &UsedValues) -> LaidOutSvgElement {+ self.set_content_rect(image_box, used, self.svg_image_bounding_box(image_box))}/// Lays out `resource`, a mask, clip or pattern of a box whose sizes and box sides are `parent_metrics`.@@ -2381,7 +2395,7 @@ impl<'pass> SvgFormattingContext<'pass> {let attributes = self.svg_attributes(resource);assert!(node_facts::kind_is_svg_resource_box(kind));// FIXME: Somehow limit <clipPath> contents to: shape elements, <text>, and <use>.- self.create_used_values(resource);+ let used = self.create_used_values(resource);self.commit_svg_element_facts(resource, facts, attributes);let (width, height) = if kind == NodeKind::SVGPatternBox && attributes.has_active_view_box {@@ -2420,15 +2434,20 @@ impl<'pass> SvgFormattingContext<'pass> {} else {(self.viewport_width, self.viewport_height)};- self.set_definite_content_size(resource, width, height);+ Self::set_definite_content_size(&used, width, height);// Resource content lays out in its own user space; objectBoundingBox content scaling is a// paint-time transform in the resource's nested visual context tree.let mut nested_context = Self::new_nested(run, resource);- nested_context.run(run, self.nested_layout_input());- self.place_child(resource, CssPixels::default(), CssPixels::default());+ nested_context.lay_out_contents(run, self.nested_layout_input(), &used);+ self.place_child(resource, &used, CssPixels::default(), CssPixels::default());}- fn layout_container_element(&mut self, run: &FormattingContextRun<'pass>, container: Node) {+ fn layout_container_element(+ &mut self,+ run: &FormattingContextRun<'pass>,+ container: Node,+ used: &UsedValues,+ ) -> LaidOutSvgElement {let mut has_points = false;let mut min_x = CssPixels::default();let mut min_y = CssPixels::default();@@ -2439,14 +2458,13 @@ impl<'pass> SvgFormattingContext<'pass> {if NodeFacts::new(&self.run.callbacks, child).is_box()&& !node_facts::kind_is_svg_resource_box(self.node_kind(child)){- let child_handed_back_by_its_run = self.layout_svg_element(run, child);- // NB: A child its own run laid out has the metrics that run handed back, and any other those of its- // record here.- let child_metrics = child_handed_back_by_its_run- .unwrap_or_else(|| self.run.records.box_metrics_of(child).input_cells());+ let laid_out_child = self+ .layout_svg_element(run, child)+ .expect("a box below an SVG container element is laid out");+ let child_metrics = laid_out_child.cells;// The container's bounding box includes descendants' transforms; children lay out// untransformed, so each child rect maps through the child's own transform here.- let child_content_offset = self.run.records.content_offset_or_origin(child);+ let child_content_offset = laid_out_child.content_offset;let mapped_child_rect = self.svg_element_transform(child).map_rect(FfiFloatRect {x: child_content_offset.x.raw_value() as f32 / 64.0,y: child_content_offset.y.raw_value() as f32 / 64.0,@@ -2474,13 +2492,14 @@ impl<'pass> SvgFormattingContext<'pass> {self.set_content_rect(container,+ used,SvgCssPixelRect {x: min_x,y: min_y,width: max_x - min_x,height: max_y - min_y,},- );+ )}}