Truly independent web browser
LibWeb: Tell the host what layout found out once it is committed
Aliaksandr Kalenik0896331fc45b
diff --git a/Libraries/LibWeb/CSS/Length.cpp b/Libraries/LibWeb/CSS/Length.cppindex 8877c546851..5390f058ea2 100644--- a/Libraries/LibWeb/CSS/Length.cpp+++ b/Libraries/LibWeb/CSS/Length.cpp@@ -134,13 +134,19 @@ double Length::container_relative_length_to_px_without_rounding(ResolutionContex}auto& subject = *context.subject_element;- const_cast<DOM::Element&>(subject).set_style_depends_on_size_container_query();+ auto* deferred_marks = context.deferred_container_query_marks();+ if (!deferred_marks)+ const_cast<DOM::Element&>(subject).set_style_depends_on_size_container_query();auto query_container = get_or_compute_query_container_for_axis(context, physical_axis);// A container unit asks about the container's box exactly as a size query does, so the// container has to know that a resize of it is a change for something under it.- if (query_container)- const_cast<DOM::Element&>(*query_container).set_is_size_query_container();+ if (query_container) {+ if (deferred_marks)+ (physical_axis == ContainerRelativeAxis::Width ? deferred_marks->width_query_container : deferred_marks->height_query_container) = query_container;+ else+ const_cast<DOM::Element&>(*query_container).set_is_size_query_container();+ }if (!query_container) {context.record_viewport_relative_length_resolution();auto viewport_length = physical_axis == ContainerRelativeAxis::Width ? context.viewport_rect.width() : context.viewport_rect.height();@@ -156,8 +162,12 @@ double Length::container_relative_length_to_px_without_rounding(ResolutionContex// A running partial relayout pass reports layout as up to date, but a container// with no paintable yet still needs the post-layout evaluation, which routes the// follow-up pass to the full layout path that resolves the container's size.- if (!subject.document().layout_is_up_to_date() || subject.document().is_running_update_layout())- const_cast<DOM::Document&>(subject.document()).set_needs_container_query_evaluation_after_layout(*query_container);+ if (!subject.document().layout_is_up_to_date() || subject.document().is_running_update_layout()) {+ if (deferred_marks)+ (physical_axis == ContainerRelativeAxis::Width ? deferred_marks->width_query_container_awaits_layout : deferred_marks->height_query_container_awaits_layout) = true;+ else+ const_cast<DOM::Document&>(subject.document()).set_needs_container_query_evaluation_after_layout(*query_container);+ }return 0.0;}diff --git a/Libraries/LibWeb/CSS/Length.h b/Libraries/LibWeb/CSS/Length.hindex acafe5455e8..487cddff662 100644--- a/Libraries/LibWeb/CSS/Length.h+++ b/Libraries/LibWeb/CSS/Length.h@@ -58,6 +58,15 @@ public:LengthUnit unit() const { return m_unit; }Utf16FlyString unit_name() const { return CSS::to_string(m_unit); }+ // What resolving container-relative lengths would mark on the DOM, kept for a caller that must not write there+ // while it resolves them, as a layout pass must not.+ struct DeferredContainerQueryMarks {+ GC::Ptr<DOM::Element const> width_query_container;+ GC::Ptr<DOM::Element const> height_query_container;+ bool width_query_container_awaits_layout { false };+ bool height_query_container_awaits_layout { false };+ };+struct ResolutionContext {[[nodiscard]] static ResolutionContext for_document(DOM::Document const&);[[nodiscard]] static ResolutionContext for_element(DOM::AbstractElement const&);@@ -84,6 +93,16 @@ public:return m_did_resolve_viewport_relative_length;}+ void defer_container_query_marks(DeferredContainerQueryMarks& marks) const+ {+ m_deferred_container_query_marks = &marks;+ }++ [[nodiscard]] DeferredContainerQueryMarks* deferred_container_query_marks() const+ {+ return m_deferred_container_query_marks;+ }+void record_viewport_relative_length_resolution() const{if (m_did_resolve_viewport_relative_length)@@ -133,6 +152,7 @@ public:void visit_edges(GC::Cell::Visitor&) const;mutable bool* m_did_resolve_viewport_relative_length { nullptr };+ mutable DeferredContainerQueryMarks* m_deferred_container_query_marks { nullptr };};[[nodiscard]] CSSPixels to_px(ResolutionContext const&) const;diff --git a/Libraries/LibWeb/DOM/CommitMessages.cpp b/Libraries/LibWeb/DOM/CommitMessages.cppindex 4df817356a3..c40a7c38d81 100644--- a/Libraries/LibWeb/DOM/CommitMessages.cpp+++ b/Libraries/LibWeb/DOM/CommitMessages.cpp@@ -69,6 +69,15 @@ void CommitMessages::append(Layout::BegunRead const& read, Layout::RustFFI::FfiCcase Layout::RustFFI::FfiCommitMessageKind::UnstyledElementReached:m_messages.append({ .identity = identity, .kind = Kind::UnstyledElementReached });return;+ case Layout::RustFFI::FfiCommitMessageKind::StyleDependsOnSizeContainerQuery:+ m_messages.append({ .identity = identity, .kind = Kind::StyleDependsOnSizeContainerQuery });+ return;+ case Layout::RustFFI::FfiCommitMessageKind::SizeQueryContainerResolvedAgainst:+ m_messages.append({ .identity = identity, .kind = Kind::SizeQueryContainerResolvedAgainst });+ return;+ case Layout::RustFFI::FfiCommitMessageKind::ContainerQueryEvaluationNeededAfterLayout:+ m_messages.append({ .identity = identity, .kind = Kind::ContainerQueryEvaluationNeededAfterLayout });+ return;case Layout::RustFFI::FfiCommitMessageKind::SvgResourceReferenced:m_messages.append({.identity = identity,@@ -145,6 +154,18 @@ void CommitMessages::apply(Layout::BegunRead const& read, Message const& messageelement->set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::StyleChange);}return;+ case Kind::StyleDependsOnSizeContainerQuery:+ if (auto* element = as_if<Element>(message.identity.resolve(m_document).ptr()))+ element->set_style_depends_on_size_container_query();+ return;+ case Kind::SizeQueryContainerResolvedAgainst:+ if (auto* element = as_if<Element>(message.identity.resolve(m_document).ptr()))+ element->set_is_size_query_container();+ return;+ case Kind::ContainerQueryEvaluationNeededAfterLayout:+ if (auto* element = as_if<Element>(message.identity.resolve(m_document).ptr()))+ m_document->set_needs_container_query_evaluation_after_layout(*element);+ return;}VERIFY_NOT_REACHED();}diff --git a/Libraries/LibWeb/DOM/CommitMessages.h b/Libraries/LibWeb/DOM/CommitMessages.hindex 94e67c75a3a..d4bc195998a 100644--- a/Libraries/LibWeb/DOM/CommitMessages.h+++ b/Libraries/LibWeb/DOM/CommitMessages.h@@ -47,6 +47,9 @@ private:ListItemCounterValueRendered,SvgResourceReferenced,UnstyledElementReached,+ StyleDependsOnSizeContainerQuery,+ SizeQueryContainerResolvedAgainst,+ ContainerQueryEvaluationNeededAfterLayout,};struct Message {diff --git a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp b/Libraries/LibWeb/Layout/LayoutRustBridge.cppindex 350c7caa5a3..174adeeae84 100644--- a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp+++ b/Libraries/LibWeb/Layout/LayoutRustBridge.cpp@@ -542,9 +542,22 @@ void register_layout_host(NodeArena& arena, DOM::Document& document)auto element = document.style_computer().element_for_style_node(style_node);VERIFY(element);auto context = CSS::Length::ResolutionContext::for_element(DOM::AbstractElement { *element });+ // Layout writes nothing on the DOM side: the marks these lengths make reach the document as commit+ // messages, once the layout that resolved them is committed.+ CSS::Length::DeferredContainerQueryMarks marks;+ context.defer_container_query_marks(marks);+ auto width = CSS::Length(100, CSS::LengthUnit::Cqw).to_px_without_rounding(context);+ auto height = CSS::Length(100, CSS::LengthUnit::Cqh).to_px_without_rounding(context);+ auto style_node_of = [](GC::Ptr<DOM::Element const> container) -> u32 {+ return container ? container->style_node_id().value() : 0;+ };return {- .width = CSS::Length(100, CSS::LengthUnit::Cqw).to_px_without_rounding(context),- .height = CSS::Length(100, CSS::LengthUnit::Cqh).to_px_without_rounding(context),+ .width = width,+ .height = height,+ .width_query_container = style_node_of(marks.width_query_container),+ .height_query_container = style_node_of(marks.height_query_container),+ .width_query_container_awaits_layout = marks.width_query_container_awaits_layout,+ .height_query_container_awaits_layout = marks.height_query_container_awaits_layout,}; },.take_built_scroll_containers = [](void* context, BegunRead const* read, RustFFI::FfiBuiltScrollContainer const* built, size_t count) {auto& document = *static_cast<DOM::Document*>(context);diff --git a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rsindex 46f39b45e63..0dba710a9e1 100644--- a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs@@ -3810,6 +3810,11 @@ impl<'pass> BlockFormattingContext<'pass> {(early_break_before, allows_early_break_requests),);}+ // NB: Only the attempt that is kept tells the host what it found out.+ self.run+ .callbacks+ .scratch()+ .receive_host_findings(outputs.host_findings);return ColumnLayout {outcome,consumed_block_size: outputs.result.automatic_content_block_size,diff --git a/Libraries/LibWeb/Rust/src/layout/commit.rs b/Libraries/LibWeb/Rust/src/layout/commit.rsindex 967b55ed766..a9c41f4ae14 100644--- a/Libraries/LibWeb/Rust/src/layout/commit.rs+++ b/Libraries/LibWeb/Rust/src/layout/commit.rs@@ -8,7 +8,7 @@ use super::*;use crate::css::style::tree::StyleNodeID;/// What a commit message tells the document.-#[derive(Clone, Copy, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]pub enum FfiCommitMessageKind {/// The node is a size query container whose content size changed.@@ -32,11 +32,20 @@ pub enum FfiCommitMessageKind {/// settled. The tree build built no box for it: the document styles it and builds its box/// again.UnstyledElementReached,+ /// The node is an element whose layout resolved a container-relative length, so that its+ /// style depends on size container queries.+ StyleDependsOnSizeContainerQuery,+ /// The node is a size query container a container-relative length resolved against.+ SizeQueryContainerResolvedAgainst,+ /// The node is a size query container a container-relative length resolved against before+ /// the container had a committed box, so the document evaluates container queries after+ /// layout.+ ContainerQueryEvaluationNeededAfterLayout,}/// One thing layout has to tell the document. The node it is about is named by the style node the/// style tree gave it, with 0 for the document; no pointer crosses the boundary.-#[derive(Clone, Copy)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(C)]pub struct FfiCommitMessage {pub style_node: u32,@@ -63,6 +72,14 @@ pub(crate) struct CommitNotifications {}impl CommitNotifications {+ /// Adds what the committed layout found out for the document ahead of what the commit itself found, which reads+ /// it: a commit message about a resized container asks whether lengths resolved against it.+ pub(crate) fn prepend_layout_messages(&mut self, messages: Vec<FfiCommitMessage>) {+ if !messages.is_empty() {+ self.messages.splice(0..0, messages);+ }+ }+/// The size query containers whose content size the commit changed.pub(crate) fn resized_size_containers(&self) -> impl Iterator<Item = StyleNodeID> + '_ {self.messagesdiff --git a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rsindex ad757ff7d19..562e89d4328 100644--- a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs@@ -292,6 +292,7 @@ fn outputs_without_descendant_fragments(outputs: &formatting_context::RunOutputsroot_outcome: outputs.root_outcome.clone(),atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above: outputs.atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above,+ host_findings: outputs.host_findings.clone(),}}@@ -828,6 +829,7 @@ mod tests {rare: None,},atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above: None,+ host_findings: None,},uncommitted: false,table_cell_intrinsic_block_padding_unobserved: false,diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rsindex caf7dcc1298..dc0d2dc3759 100644--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs@@ -1066,6 +1066,8 @@ pub(crate) struct RunOutputs {pub(crate) root: Option<fragment_tree::UnplacedRootFragment>,pub(crate) root_outcome: RunRootOutcome,pub(crate) atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above: Option<CssPixels>,+ /// Boxed, as most runs find out nothing for the host.+ pub(crate) host_findings: Option<Box<super::run_records::HostFindings>>,}pub(crate) enum ChildLayoutOutcome {@@ -1289,6 +1291,7 @@ impl<'pass> FormattingContextRun<'pass> {root,root_outcome,atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above,+ host_findings: self.records.take_host_findings(),}}}@@ -1906,7 +1909,7 @@ pub(super) fn run_formatting_context(.scratch().memoized_measurement(box_, purpose, layout_mode, &cache_key){- return absorb_run_outputs(parent_fragments, parent_used, box_, outputs, false);+ return absorb_run_outputs(&callbacks, parent_fragments, parent_used, box_, outputs, false);}let cache_attempt = match fc_run_cache::FcRunCacheAttempt::probe(purpose,@@ -1945,7 +1948,14 @@ pub(super) fn run_formatting_context(if entry.is_uncommitted() {fc_run_cache::store_replayed_uncommitted_entry(&callbacks, box_, cache_key, &entry, &outputs);}- return absorb_run_outputs(parent_fragments, parent_used, box_, outputs, reuses_committed_subtree);+ return absorb_run_outputs(+ &callbacks,+ parent_fragments,+ parent_used,+ box_,+ outputs,+ reuses_committed_subtree,+ );}};let _trace = callbacks@@ -1975,7 +1985,7 @@ pub(super) fn run_formatting_context(.memoize_measurement(box_, purpose, layout_mode, cache_key, &outputs);}cache_attempt.conclude(&callbacks, box_, cache_key, &outputs);- absorb_run_outputs(parent_fragments, parent_used, box_, outputs, false)+ absorb_run_outputs(&callbacks, parent_fragments, parent_used, box_, outputs, false)}/// Takes a committing run of `box_` from the cache entry `entry` with nothing replayed: its root record gets what the@@ -2017,6 +2027,9 @@ fn reuse_committed_subtree_as_it_is(|| "REUSE SUBTREE",);fragments.hold_reused_committed_fragment(box_, root_used, fragment);+ callbacks+ .scratch()+ .receive_host_findings(entry.outputs.host_findings.clone());Some(entry.outputs.result)}@@ -2846,6 +2859,7 @@ pub(crate) fn run_table_cell_ahead_of_its_intrinsic_block_padding(}fn absorb_run_outputs(+ callbacks: &LayoutPass<'_>,parent_fragments: Option<&fragment_tree::RunFragmentBuilder>,parent_used: &UsedValues,child: Node,@@ -2857,7 +2871,9 @@ fn absorb_run_outputs(root,root_outcome,atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above: _,+ host_findings,} = outputs;+ callbacks.scratch().receive_host_findings(host_findings);root_outcome.apply_to_record(parent_used);if let (Some(fragments), Some(root)) = (parent_fragments, root) {debug_assert!(root.node == child, "a child run returned a root for a different box");@@ -3001,8 +3017,11 @@ struct LayoutStageInput<'a> {document_in_quirks_mode: bool,}-/// The fragments a layout stage computed, which its commit consumes.-struct LayoutStageOutput(fragment_tree::CompletedPassFragments);+/// The fragments a layout stage computed, which its commit consumes, and what the stage found out for the host.+struct LayoutStageOutput {+ fragments: fragment_tree::CompletedPassFragments,+ host_findings: super::run_records::HostFindings,+}/// One layout stage: computes the fragments of the whole document from its viewport, or of one/// partial relayout boundary in the containing block the planner found it still has.@@ -3040,8 +3059,22 @@ impl LayoutStageJob {} => compute_root_layout(input, should_collect_devtools_layout_data),LayoutStageKind::Boundary { containing_block } => compute_subtree_layout_fragments(input, containing_block),};- let notifications = commit::commit_replacing(root, state.arena_mut(), &output.0);+ let mut notifications = commit::commit_replacing(root, state.arena_mut(), &output.fragments);+ let super::run_records::HostFindings {+ nodes_with_unresolved_container_lengths,+ messages,+ document_svg_root_natural_size,+ } = output.host_findings;+ if let Some((root_box, natural_size)) = document_svg_root_natural_size {+ state+ .arena_mut()+ .note_document_svg_root_natural_size(root_box, natural_size);+ }+ notifications.prepend_layout_messages(messages);let arena = state.arena();+ for node in nodes_with_unresolved_container_lengths {+ arena.note_unresolved_container_lengths(node);+ }arena.end_layout_pass();state.layout_scratch().end_layout_pass();arena.reset_layout_update_flags_in_subtree(root);@@ -3100,7 +3133,7 @@ fn compute_root_layout(input: LayoutStageInput<'_>, should_collect_devtools_layopercentage_basis_block_size: Some(viewport_block_size),..ContainingBlockConstraints::default()};- let pass_fragments = RunRecords::with_unrooted(scratch, arena, root, NodeSlotId::INVALID, |entry_records| {+ RunRecords::with_unrooted(scratch, arena, root, NodeSlotId::INVALID, |entry_records| {let _trace = arena.layout_trace.pass(None);let viewport_used = entry_records.create_used_values(&callbacks, root, root_constraints);let entry_fragments = std::rc::Rc::new(fragment_tree::RunFragmentBuilder::new_entry_accumulator(root));@@ -3159,8 +3192,7 @@ fn compute_root_layout(input: LayoutStageInput<'_>, should_collect_devtools_layo&callbacks,should_collect_devtools_layout_data,)- });- LayoutStageOutput(pass_fragments)+ })}fn finish_entry_pass(@@ -3168,7 +3200,7 @@ fn finish_entry_pass(entry_fragments: &std::rc::Rc<fragment_tree::RunFragmentBuilder>,callbacks: &LayoutPass<'_>,should_collect_devtools_layout_data: bool,-) -> fragment_tree::CompletedPassFragments {+) -> LayoutStageOutput {abspos_engine::drain_abspos_with_placed_containing_blocks(entry_records,*callbacks,@@ -3180,7 +3212,14 @@ fn finish_entry_pass(!pass_fragments.roots.is_empty(),"an entry pass always produces the entry root's fragment");- pass_fragments+ let mut host_findings = callbacks.scratch().take_host_findings_outside_runs();+ if let Some(found_by_entry_run) = entry_records.take_host_findings() {+ host_findings.receive(*found_by_entry_run);+ }+ LayoutStageOutput {+ fragments: pass_fragments,+ host_findings,+ }}/// The partial layout stage: computes the fragments of one partial relayout boundary in place,@@ -3224,7 +3263,7 @@ fn compute_subtree_layout_fragments(input: LayoutStageInput<'_>, containing_bloc} else {(root, containing_block)};- let pass_fragments = RunRecords::with_unrooted(+ RunRecords::with_unrooted(scratch,arena,entry_root,@@ -3252,8 +3291,7 @@ fn compute_subtree_layout_fragments(input: LayoutStageInput<'_>, containing_bloc}finish_entry_pass(entry_records, &entry_fragments, &callbacks, false)},- );- LayoutStageOutput(pass_fragments)+ )}fn layout_subtree_with_frozen_root_geometry(run: &FormattingContextRun<'_>) {diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rsindex b93e4e0163d..fd14787394e 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs@@ -3104,7 +3104,7 @@ impl LayoutNodeArena {/// Note the natural size layout negotiated for the box of an `<svg>` document element.pub(crate) fn note_document_svg_root_natural_size(- &self,+ &mut self,root_box: NodeSlotId,natural_size: crate::css::style::NaturalSize,) {diff --git a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs b/Libraries/LibWeb/Rust/src/layout/layout_pass.rsindex f49d2bce80f..9f1524a9888 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_pass.rs@@ -7,9 +7,10 @@use super::*;/// The one question a layout pass still asks the document while it runs: what the container-relative-/// lengths on an element resolve against. Answering it notes in the document that the element depends-/// on its query container's size, so the answer cannot be published ahead of the pass. A pass holds-/// this and no other part of the host. Every other host call takes the main thread token, which a+/// lengths on an element resolve against. The answer reads the committed size of the element's query+/// container, so it cannot be published ahead of the pass, and it writes nothing in the document: the+/// dependencies it finds reach the document as commit messages. A pass holds this and no other part+/// of the host. Every other host call takes the main thread token, which a/// pass is not handed, so a pass has no way to make any other call into the document.#[derive(Clone, Copy)]pub(crate) struct ContainerLengthBasesQuery {diff --git a/Libraries/LibWeb/Rust/src/layout/node_facts.rs b/Libraries/LibWeb/Rust/src/layout/node_facts.rsindex 998539ec01d..893776bee0c 100644--- a/Libraries/LibWeb/Rust/src/layout/node_facts.rs+++ b/Libraries/LibWeb/Rust/src/layout/node_facts.rs@@ -889,15 +889,15 @@ impl<'pass> NodeFacts<'pass> {// An <object> showing the document is sized from what its <svg> document element would be// without size containment.if is_document_element_box {- arena.note_document_svg_root_natural_size(- self.node,- NaturalSize {- width: width.map(CssPixels::raw_value),- height: height.map(CssPixels::raw_value),- aspect_ratio: aspect_ratio- .map(|(numerator, denominator)| (numerator.raw_value(), denominator.raw_value())),- },- );+ let natural_size = NaturalSize {+ width: width.map(CssPixels::raw_value),+ height: height.map(CssPixels::raw_value),+ aspect_ratio: aspect_ratio+ .map(|(numerator, denominator)| (numerator.raw_value(), denominator.raw_value())),+ };+ self.callbacks.scratch().note_host_findings(|findings| {+ findings.document_svg_root_natural_size = Some((self.node, natural_size));+ });}if !size_contained {set_auto_content_size(diff --git a/Libraries/LibWeb/Rust/src/layout/run_records.rs b/Libraries/LibWeb/Rust/src/layout/run_records.rsindex 415c6babb77..7d86fcdefad 100644--- a/Libraries/LibWeb/Rust/src/layout/run_records.rs+++ b/Libraries/LibWeb/Rust/src/layout/run_records.rs@@ -28,6 +28,83 @@ pub(crate) struct LayoutScratch {/// https://drafts.csswg.org/css-anchor-position-1/#apply-a-position-optionposition_option_styles: RefCell<Vec<(NodeSlotId, super::node_data::StylePayloadsRef)>>,has_position_option_styles: Cell<bool>,+ /// What each run in progress found out for the host so far, the innermost last, and what the pass found out+ /// outside any run.+ host_findings_of_runs_in_progress: RefCell<Vec<HostFindings>>,+ host_findings_outside_runs: RefCell<HostFindings>,+}++/// What layout found out that the host hears of once the layout that found it is committed: the nodes whose SVG+/// lengths it resolved without the container they are relative to, what the container-relative lengths it resolved+/// depend on, and the natural size it negotiated for the box of an `<svg>` document element. A run hands them to its+/// parent with its result, so a discarded result tells the host nothing.+#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) struct HostFindings {+ pub(crate) nodes_with_unresolved_container_lengths: Vec<NodeSlotId>,+ pub(crate) messages: Vec<super::commit::FfiCommitMessage>,+ pub(crate) document_svg_root_natural_size: Option<(NodeSlotId, crate::css::style::NaturalSize)>,+}++impl HostFindings {+ pub(crate) fn is_empty(&self) -> bool {+ self.nodes_with_unresolved_container_lengths.is_empty()+ && self.messages.is_empty()+ && self.document_svg_root_natural_size.is_none()+ }++ pub(crate) fn note_unresolved_container_lengths(&mut self, node: NodeSlotId) {+ if !self.nodes_with_unresolved_container_lengths.contains(&node) {+ self.nodes_with_unresolved_container_lengths.push(node);+ }+ }++ pub(crate) fn note_container_length_dependencies(+ &mut self,+ element: crate::css::style::tree::StyleNodeID,+ bases: &super::svg_formatting_context::FfiContainerLengthBases,+ ) {+ use super::commit::{FfiCommitMessage, FfiCommitMessageKind};+ self.note_message(FfiCommitMessage::new(+ element.raw(),+ FfiCommitMessageKind::StyleDependsOnSizeContainerQuery,+ ));+ for (container, awaits_layout) in [+ (bases.width_query_container, bases.width_query_container_awaits_layout),+ (bases.height_query_container, bases.height_query_container_awaits_layout),+ ] {+ if container == 0 {+ continue;+ }+ self.note_message(FfiCommitMessage::new(+ container,+ FfiCommitMessageKind::SizeQueryContainerResolvedAgainst,+ ));+ if awaits_layout {+ self.note_message(FfiCommitMessage::new(+ container,+ FfiCommitMessageKind::ContainerQueryEvaluationNeededAfterLayout,+ ));+ }+ }+ }++ fn note_message(&mut self, message: super::commit::FfiCommitMessage) {+ if !self.messages.contains(&message) {+ self.messages.push(message);+ }+ }++ pub(crate) fn receive(&mut self, other: HostFindings) {+ for node in other.nodes_with_unresolved_container_lengths {+ self.note_unresolved_container_lengths(node);+ }+ for message in other.messages {+ self.note_message(message);+ }+ if other.document_svg_root_natural_size.is_some() {+ self.document_svg_root_natural_size = other.document_svg_root_natural_size;+ }+ }}#[derive(Default)]@@ -69,6 +146,8 @@ impl Default for LayoutScratch {measurement_memo: RefCell::new(MeasurementMemo::default()),position_option_styles: RefCell::new(Vec::new()),has_position_option_styles: Cell::new(false),+ host_findings_of_runs_in_progress: RefCell::new(Vec::new()),+ host_findings_outside_runs: RefCell::new(HostFindings::default()),}}}@@ -116,6 +195,27 @@ impl LayoutScratch {self.inline_item_stashes.borrow_mut().remove(&block_container)}+ /// Notes what the innermost run in progress found out for the host, or the pass outside any run.+ pub(crate) fn note_host_findings(&self, note: impl FnOnce(&mut HostFindings)) {+ let mut runs = self.host_findings_of_runs_in_progress.borrow_mut();+ match runs.last_mut() {+ Some(findings) => note(findings),+ None => note(&mut self.host_findings_outside_runs.borrow_mut()),+ }+ }++ /// Hands what a finished run found out to the run in progress that used its result.+ pub(crate) fn receive_host_findings(&self, findings: Option<Box<HostFindings>>) {+ if let Some(findings) = findings {+ self.note_host_findings(|into| into.receive(*findings));+ }+ }++ /// What the pass found out outside any run, which its driver reports itself.+ pub(crate) fn take_host_findings_outside_runs(&self) -> HostFindings {+ std::mem::take(&mut self.host_findings_outside_runs.borrow_mut())+ }+pub(crate) fn begin_measurement_memo(&self) {self.measurement_memo.borrow_mut().depth += 1;}@@ -179,12 +279,16 @@ impl LayoutScratch {self.next_run_nonce.set(nonce.checked_add(1).expect("layout run nonce space exhausted"));self.live_run_nonces.borrow_mut().push(nonce);+ self.host_findings_of_runs_in_progress+ .borrow_mut()+ .push(HostFindings::default());nonce}fn end_run(&self, nonce: u64) {let ended = self.live_run_nonces.borrow_mut().pop();assert_eq!(ended, Some(nonce), "layout runs ended out of order");+ self.host_findings_of_runs_in_progress.borrow_mut().pop();}fn innermost_run_nonce(&self) -> Option<u64> {@@ -308,6 +412,23 @@ impl<'arena> RunRecords<'arena> {run(&records)}+ /// What this run found out for the host, which its outputs carry to the run that uses its result.+ pub(crate) fn take_host_findings(&self) -> Option<Box<HostFindings>> {+ assert_eq!(+ self.scratch.innermost_run_nonce(),+ Some(self.nonce),+ "only the innermost layout run may hand over what it found out"+ );+ let findings = std::mem::take(+ self.scratch+ .host_findings_of_runs_in_progress+ .borrow_mut()+ .last_mut()+ .expect("a run in progress has a findings entry"),+ );+ (!findings.is_empty()).then(|| Box::new(findings))+ }+pub(crate) fn note_omitted_line_layout(&self) {self.omitted_line_layout.set(true);}diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rsindex b2784b1369c..986a2c5d69e 100644--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs@@ -168,12 +168,18 @@ pub struct FfiSvgLengthValue {/// The sizes a container-relative length on an element resolves against, as style answers them/// for that element: per axis, the committed content box of its nearest size query container, or-/// the small viewport size.+/// the small viewport size. Style writes nothing while it answers: it says which containers the+/// lengths depend on, by style node or 0 for the viewport, and whether a container has no committed+/// box yet, so the document must evaluate its container queries after layout.#[derive(Clone, Copy)]#[repr(C)]pub struct FfiContainerLengthBases {pub width: f64,pub height: f64,+ pub width_query_container: u32,+ pub height_query_container: u32,+ pub width_query_container_awaits_layout: bool,+ pub height_query_container_awaits_layout: bool,}pub const SVG_LENGTH_KIND_NONE: u8 = 0;@@ -2547,9 +2553,10 @@ fn length_resolution_context(.dom_node_style_node(node).expect("an SVG element's attribute length is resolved for the element's own box");let bases = callbacks.container_length_bases.bases(element);- if bases.is_none() {- callbacks.arena().note_unresolved_container_lengths(node);- }+ callbacks.scratch().note_host_findings(|findings| match &bases {+ Some(bases) => findings.note_container_length_dependencies(element, bases),+ None => findings.note_unresolved_container_lengths(node),+ });bases} else {None