Truly independent web browser
LibWeb: Build a run root's fragment at the end of its run
Aliaksandr Kalenik70a7a3a51de4
diff --git a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rsindex 20bc8d7e333..242d26d4d3b 100644--- a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs@@ -3289,14 +3289,14 @@ impl<'pass> BlockFormattingContext<'pass> {node,formatting_context::PlacedChild::new(fragment_tree::FragmentGeometry {cells: self.metrics_of(sized_child),- line_data: None,+ line_data: fragment.line_data.clone(),}).with_in_flow_box_insets(insets),content_offset,None,Some(fragment_tree::ChildFragmentArrival::CommittedFragment {fragment,- reuses_subtree: true,+ reuses_committed_subtree: true,}),);self.block_offset_of_current_block_container@@ -4349,7 +4349,7 @@ impl<'pass> BlockFormattingContext<'pass> {consumed_block_size: outputs.result.automatic_content_block_size,baselines: outputs.result.baselines,root_line_data: outputs.root_outcome.line_data,- root: outputs.root,+ root: fragmentainer.take_contents(),};}}diff --git a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rsindex b3165176fb3..79433b8d84d 100644--- a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs@@ -123,14 +123,6 @@ impl FcRunCacheKey {}}- pub(super) fn fc_type(&self) -> formatting_context::FormattingContextType {- self.fc_type- }-- pub(super) fn has_no_table_cell_intrinsic_block_padding(&self) -> bool {- self.input.sizing.table_cell_intrinsic_block_padding.is_none()- }-/// The key with the intrinsic block padding a table hands its cell taken out of the root's block paddings.fn without_table_cell_intrinsic_block_padding(&self) -> Self {let mut key = *self;@@ -302,9 +294,9 @@ pub(super) struct FcRunCacheEntry {/// How many layouts the arena had committed when the run was stored. The subtrees the run took from the cache as/// they were committed are only known to be so while no layout was committed since.layout_commits_when_stored: u64,- /// The committed subtree token of the box when its committed fragments were found to be the stored ones, after- /// which the entry keeps no descendant fragments: they stay the stored ones while the token does.- committed_subtree_token_when_descendants_dropped: Option<u32>,+ /// The committed subtree token of the box when its committed fragments were found to be the stored ones, which+ /// they stay while the token does.+ committed_subtree_token_when_found_committed: Option<u32>,last_used_at_layout_commit: std::sync::atomic::AtomicU64,structural_epoch_bumps_when_stored: u32,}@@ -343,9 +335,9 @@ impl FcRunCacheEntry {}).unwrap_or(false);root_fragment_is_the_stored_one- && match self.committed_subtree_token_when_descendants_dropped {+ && match self.committed_subtree_token_when_found_committed {Some(token) => arena.committed_subtree_token(box_) == token,- None => links_are_committed(arena, &root.scoped_descendants),+ None => links_are_committed(arena, &root.fragment.children),}}@@ -368,23 +360,22 @@ impl FcRunCacheEntry {/// Whether the stored fragments can be replayed. Those of the subtrees the stored run took from the cache are the/// committed ones, so such a run is replayed only before anything else is committed.fn can_be_replayed(&self, callbacks: &LayoutPass<'_>) -> bool {- self.committed_subtree_token_when_descendants_dropped.is_none()+ self.committed_subtree_token_when_found_committed.is_none()&& self.outputs.root.as_ref().is_none_or(|root| {root.reused_subtree_roots.is_empty()|| callbacks.arena().layout_commit_count() == self.layout_commits_when_stored})}- /// This entry without its descendant fragments, which are the box's committed ones while its committed subtree- /// token is `token`.- fn without_descendant_fragments(&self, token: u32) -> Self {+ /// This entry as the one whose fragments the box committed, while its committed subtree token is `token`.+ fn found_committed(&self, token: u32) -> Self {Self {key: self.key,validity: self.validity,- outputs: outputs_without_descendant_fragments(&self.outputs),+ outputs: self.outputs_reusing_committed_subtree(),table_cell_intrinsic_block_padding_unobserved: self.table_cell_intrinsic_block_padding_unobserved,layout_commits_when_stored: self.layout_commits_when_stored,- committed_subtree_token_when_descendants_dropped: Some(token),+ committed_subtree_token_when_found_committed: Some(token),last_used_at_layout_commit: std::sync::atomic::AtomicU64::new(self.last_used_at_layout_commit()),structural_epoch_bumps_when_stored: self.structural_epoch_bumps_when_stored,}@@ -401,6 +392,19 @@ impl FcRunCacheEntry {}}+ /// The outputs of a hit that keeps the committed subtree. Commit stops at the reused root, so the reuse markers of+ /// the subtrees below it never enter its scopes.+ fn outputs_reusing_committed_subtree(&self) -> formatting_context::RunOutputs {+ formatting_context::RunOutputs {+ root: self+ .outputs+ .root+ .as_ref()+ .map(fragment_tree::RunRootFragment::without_reused_subtree_roots),+ ..self.outputs_without_fragments()+ }+ }+fn last_used_at_layout_commit(&self) -> u64 {self.last_used_at_layout_commit.load(std::sync::atomic::Ordering::Relaxed)@@ -412,7 +416,7 @@ impl FcRunCacheEntry {}fn holds_uncommitted_fragments(&self) -> bool {- self.outputs.root.is_some() && self.committed_subtree_token_when_descendants_dropped.is_none()+ self.outputs.root.is_some() && self.committed_subtree_token_when_found_committed.is_none()}fn may_have_been_committed_by_the_last_layout(&self, layout_commit_count: u64) -> bool {@@ -435,11 +439,10 @@ impl FcRunCacheEntry {.matches(&key.without_table_cell_intrinsic_block_padding(), unobserved))}- /// The outputs a hit absorbs: the stored ones, or only what escapes the stored run where the hit keeps the- /// committed subtree.+ /// The outputs a hit absorbs.pub(super) fn outputs_to_replay(&self, reuses_committed_subtree: bool) -> formatting_context::RunOutputs {if reuses_committed_subtree {- outputs_without_descendant_fragments(&self.outputs)+ self.outputs_reusing_committed_subtree()} else {self.outputs.clone()}@@ -475,29 +478,6 @@ fn links_are_committed(arena: &LayoutNodeArena, links: &[fragment_tree::Fragment})}-fn outputs_without_descendant_fragments(outputs: &formatting_context::RunOutputs) -> formatting_context::RunOutputs {- let root = outputs.root.as_ref().map(|root| fragment_tree::UnplacedRootFragment {- node: root.node,- // Commit stops at the reused root, so descendant fragments and nested reuse markers never- // enter its scopes. Only payloads that escape the run still have to reach the parent.- scoped_descendants: Vec::new(),- reused_subtree_roots: HashSet::default(),- propagated_pending_abspos: root.propagated_pending_abspos.clone(),- propagated_anchor_candidates: root.propagated_anchor_candidates.clone(),- propagated_inline_containing_block_rects: root.propagated_inline_containing_block_rects.clone(),- propagated_abspos_containing_block_info: root.propagated_abspos_containing_block_info.clone(),- root_payloads: root.root_payloads.clone(),- });- formatting_context::RunOutputs {- result: outputs.result,- root,- root_outcome: outputs.root_outcome.clone(),- inputs_never_observed: outputs.inputs_never_observed,- host_findings: outputs.host_findings.clone(),- laid_out_abspos_contained_by_root: outputs.laid_out_abspos_contained_by_root,- }-}-#[derive(Clone, Copy, Default)]struct InlineLayoutDamage {generation: u8,@@ -674,7 +654,7 @@ impl FcRunCacheStore {let mut displaced = entries.committed.take_if(|committed| committed.key == entry.key);match entries.latest.take() {Some(latest) if latest.key == entry.key => displaced = Some(latest),- Some(latest) if latest.committed_subtree_token_when_descendants_dropped.is_some() => {+ Some(latest) if latest.committed_subtree_token_when_found_committed.is_some() => {displaced = entries.committed.replace(latest).or(displaced);}Some(latest) => {@@ -697,10 +677,10 @@ impl FcRunCacheStore {self.enqueue_for_sweep(slot);}- /// Releases stale entries after their last chance to supply reusable inline line data. Drops the descendant- /// fragments of the entry whose fragments the box committed, for which `committed_subtree_token` gives the token,- /// and the entries holding fragments the box did not commit once they went unused for a while, except the latest- /// entry of a box that committed none.+ /// Releases stale entries after their last chance to supply reusable inline line data. Marks the entry whose+ /// fragments the box committed, for which `committed_subtree_token` gives the token, and drops the entries holding+ /// fragments the box did not commit once they went unused for a while, except the latest entry of a box that+ /// committed none.pub(super) fn sweep_pending_entries(&self,mut keep: impl FnMut(u32, FcRunCacheValidity) -> bool,@@ -728,11 +708,11 @@ impl FcRunCacheStore {&& latest.may_have_been_committed_by_the_last_layout(layout_commit_count)&& let Some(token) = token_of(latest){- *latest = std::sync::Arc::new(latest.without_descendant_fragments(token));+ *latest = std::sync::Arc::new(latest.found_committed(token));entries.committed = None;} else {entries.latest.take_if(|latest| {- latest.committed_subtree_token_when_descendants_dropped.is_some() && token_of(latest).is_none()+ latest.committed_subtree_token_when_found_committed.is_some() && token_of(latest).is_none()});if let Some((index, token)) = earlier.iter().enumerate().find_map(|(index, earlier)| {earlier@@ -741,9 +721,7 @@ impl FcRunCacheStore {.flatten().map(|token| (index, token))}) {- entries.committed = Some(std::sync::Arc::new(- earlier.remove(index).without_descendant_fragments(token),- ));+ entries.committed = Some(std::sync::Arc::new(earlier.remove(index).found_committed(token)));} else {entries.committed.take_if(|committed| token_of(committed).is_none());}@@ -928,7 +906,7 @@ impl FcRunCacheAttempt {outputs: outputs.clone(),table_cell_intrinsic_block_padding_unobserved: false,layout_commits_when_stored: callbacks.arena().layout_commit_count(),- committed_subtree_token_when_descendants_dropped: None,+ committed_subtree_token_when_found_committed: None,last_used_at_layout_commit: std::sync::atomic::AtomicU64::new(callbacks.arena().layout_commit_count(),),@@ -947,9 +925,9 @@ impl FcRunCacheAttempt {let Some(root) = &outputs.root else {return;};- // A committed-subtree hit omits that subtree's descendant fragments. Do not embed such a- // skeletal result in an entry that exports an out-of-flow descendant: replaying the parent- // has to rebuild its paintable subtree so the freshly laid-out descendant can commit.+ // Commit stops at the subtrees a run reused. Do not store a run that reused one and exports an+ // out-of-flow descendant: replaying the parent has to commit the subtree again so the freshly+ // laid-out descendant can commit.if !root.propagated_pending_abspos.is_empty() && !root.reused_subtree_roots.is_empty() {return;}@@ -965,7 +943,7 @@ impl FcRunCacheAttempt {&& outputs.root_outcome.parent_owns_root_input_cells()&& !run_observes_root_block_padding(callbacks, box_, outputs),layout_commits_when_stored: callbacks.arena().layout_commit_count(),- committed_subtree_token_when_descendants_dropped: None,+ committed_subtree_token_when_found_committed: None,last_used_at_layout_commit: std::sync::atomic::AtomicU64::new(callbacks.arena().layout_commit_count()),structural_epoch_bumps_when_stored: 0,};@@ -1071,23 +1049,18 @@ mod tests {key(AvailableSize::definite(px(inline_size)), Some(px(inline_size)))}- fn root_with_a_descendant() -> fragment_tree::UnplacedRootFragment {- fragment_tree::UnplacedRootFragment {- node: Node::new(0, 1),- scoped_descendants: vec![fragment_tree::FragmentLink::for_test(Node::new(1, 1))],- reused_subtree_roots: HashSet::default(),- propagated_pending_abspos: Vec::new(),- propagated_anchor_candidates: Vec::new(),- propagated_inline_containing_block_rects: Vec::new(),- propagated_abspos_containing_block_info: Vec::new(),- root_payloads: None,- }+ fn root_with_a_descendant() -> fragment_tree::RunRootFragment {+ let mut root = fragment_tree::FragmentLink::for_test(Node::new(0, 1)).fragment;+ std::sync::Arc::get_mut(&mut root)+ .expect("a fresh fragment is not shared")+ .children = vec![fragment_tree::FragmentLink::for_test(Node::new(1, 1))];+ fragment_tree::RunRootFragment::propagating_nothing(root)}fn entry(key: FcRunCacheKey,fragment_cache_epoch: u32,- root: Option<fragment_tree::UnplacedRootFragment>,+ root: Option<fragment_tree::RunRootFragment>,layout_commit_count: u64,) -> FcRunCacheEntry {FcRunCacheEntry {@@ -1113,7 +1086,7 @@ mod tests {},table_cell_intrinsic_block_padding_unobserved: false,layout_commits_when_stored: layout_commit_count,- committed_subtree_token_when_descendants_dropped: None,+ committed_subtree_token_when_found_committed: None,last_used_at_layout_commit: std::sync::atomic::AtomicU64::new(layout_commit_count),structural_epoch_bumps_when_stored: 0,}@@ -1203,7 +1176,7 @@ mod tests {}#[test]- fn the_sweep_marks_the_entry_whose_fragments_the_box_committed_and_drops_its_descendant_fragments() {+ fn the_sweep_marks_the_entry_whose_fragments_the_box_committed_and_keeps_its_fragments() {let store = FcRunCacheStore::default();let box_ = Node::new(0, 1);store.store(box_, entry(at(300), 1, Some(root_with_a_descendant()), 0));@@ -1217,8 +1190,8 @@ mod tests {committed.key.input.available_space.inline_size,AvailableSize::definite(px(300)));- assert_eq!(committed.committed_subtree_token_when_descendants_dropped, Some(7));- assert!(committed.outputs.root.as_ref().unwrap().scoped_descendants.is_empty());+ assert_eq!(committed.committed_subtree_token_when_found_committed, Some(7));+ assert_eq!(committed.outputs.root.as_ref().unwrap().fragment.children.len(), 1);assert_eq!(widths_of_entries(&store, 0), widths(&[300, 320]));let both_are_committed =diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rsindex 2742b19bc49..37e386141fe 100644--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs@@ -470,49 +470,8 @@ pub(crate) fn place_child(.is_none_or(|arrival| arrival.node() == node && !fragments.left_child_unplaced(node)),"a box is placed with fragments handed to it for another box, or after it was left unplaced");- let mut child_run_root = None;- let committed_fragment = match fragment_arrival {- Some(fragment_tree::ChildFragmentArrival::CommittedFragment {- fragment,- reuses_subtree,- }) => Some((fragment, reuses_subtree)),- Some(fragment_tree::ChildFragmentArrival::RunRoot {- root,- reuses_committed_subtree,- }) => {- child_run_root = Some((root, reuses_committed_subtree));- None- }- None => None,- };- if let Some((fragment, reuses_subtree)) = committed_fragment {- fragments.attach_committed_fragment(- node,- fragment.clone(),- reuses_subtree,- (!containing_block.is_invalid()).then_some(containing_block),- facts_decided_by_parent,- &geometry.cells,- abspos_layout_inputs,- resolve_containing_line_box_index(callbacks, node, containing_line_box_fragment),- point_add(- offset,- committed_offset_delta_at_placement(- callbacks,- node,- facts_decided_by_parent.used_insets,- offset_from_relatively_positioned_inline_ancestors,- ),- ),- callbacks.frame,- );- return Some(fragment_tree::PlacedFragment {- fragment,- exports_payloads: false,- abspos_boxes_placed_with_it: Vec::new(),- });- }- match child_run_root {+ let child_root = fragment_arrival.map(fragment_tree::ChildFragmentArrival::into_root);+ match child_root {Some((root, reuses_committed_subtree)) => {fragments.take_in_child_root_at_placement(node, root, reuses_committed_subtree, callbacks);}@@ -1086,7 +1045,8 @@ impl RunRootOutcome {#[derive(Clone)]pub(crate) struct RunOutputs {pub(crate) result: ChildLayoutResult,- pub(crate) root: Option<fragment_tree::UnplacedRootFragment>,+ /// The fragment of the root, where the run builds fragments and is not a fragmentainer's.+ pub(crate) root: Option<fragment_tree::RunRootFragment>,pub(crate) root_outcome: RunRootOutcome,pub(crate) inputs_never_observed: fc_run_cache::RunInputsTheStoredRunNeverObserved,/// Boxed, as most runs find out nothing for the host.@@ -1348,7 +1308,7 @@ impl<'pass> FormattingContextRun<'pass> {pub(crate) fn outputs(&self,result: ChildLayoutResult,- root: Option<fragment_tree::UnplacedRootFragment>,+ root: Option<fragment_tree::RunRootFragment>,root_cells_left_by_run: used_values::RootInputCells,root_line_data: Option<std::sync::Arc<inline_content::InlineContent>>,inputs_never_observed: fc_run_cache::RunInputsTheStoredRunNeverObserved,@@ -2039,17 +1999,6 @@ pub(super) fn run_formatting_context() {Ok(attempt) => attempt,Err(hit) => {- if let Some(outcome) = reuse_committed_subtree_as_it_is(- parent_fragments,- box_,- &input,- root_cells,- &callbacks,- &cache_key,- &hit,- ) {- return outcome;- }let reuses_committed_subtree = hit.reuses_committed_subtree;let action = if !builds_fragments {"READ RESULT"@@ -2151,68 +2100,6 @@ pub(super) fn run_formatting_context()}-/// Takes a committing run of `box_` from the cache hit `hit` with nothing replayed: the box gets what the stored run-/// left, and the run's placement attaches the box's committed fragment as it is. That is exact where the committed-/// subtree is the one the stored run produced, the box is plain, and nothing from the stored run reaches past its root.-fn reuse_committed_subtree_as_it_is(- parent_fragments: Option<&fragment_tree::RunFragmentBuilder>,- box_: Node,- input: &LayoutInput,- root_cells: used_values::RootInputCells,- callbacks: &LayoutPass<'_>,- cache_key: &fc_run_cache::FcRunCacheKey,- hit: &fc_run_cache::FcRunCacheHit,-) -> Option<ChildRunOutcome> {- parent_fragments?;- let entry = &*hit.entry;- if !hit.reuses_committed_subtree- || !cache_key.has_no_table_cell_intrinsic_block_padding()- || entry- .outputs- .root- .as_ref()- .is_some_and(|root| !root.propagates_nothing())- || NodeFacts::new(callbacks, box_).has_anchor_names()- {- return None;- }- let fragment = callbacks- .arena()- .with_current_committed_fragment(box_, |fragment| fragment.is_plain_box().then(|| fragment.clone()))- .flatten()?;- let content_block_size_adopted_after_run =- content_block_size_adopted_after_run(input, entry.outputs.result.automatic_content_block_size);- let mut laid_out_box = entry.outputs.root_outcome.laid_out_child_box(- root_cells,- &entry.outputs.result,- content_block_size_adopted_after_run,- );- keep_inline_margins_resolved_now_where_unobserved(- &mut laid_out_box,- root_cells,- entry.outputs.inputs_never_observed,- );- let geometry = fragment_tree::FragmentGeometry {- cells: laid_out_box.cells,- line_data: laid_out_box.line_data.clone(),- };- if !geometry.shows_box_of_fragment(&fragment) {- return None;- }- let _trace = callbacks- .layout_trace()- .run(box_, cache_key.fc_type(), || "REUSE SUBTREE");- callbacks.receive_host_findings(entry.outputs.host_findings.clone());- Some(ChildRunOutcome {- result: entry.outputs.result,- laid_out_box,- fragment_arrival: Some(fragment_tree::ChildFragmentArrival::CommittedFragment {- fragment,- reuses_subtree: true,- }),- })-}-fn keep_inline_margins_resolved_now_where_unobserved(laid_out_box: &mut run_state::LaidOutChildBox,root_cells: used_values::RootInputCells,@@ -2632,11 +2519,25 @@ fn lay_out_run_root_and_contents<'pass>(&& !fc_type.registers_abspos_children_against_its_final_block_size(),};- // NB: The root's descendants are laid out in the frame the root establishes.+ // NB: The root's descendants are laid out in the frame the root establishes. A fragmentainer has no fragment of its+ // own, so the run hands what it laid out there to the run of the box the fragmentainer belongs to. Any other+ // run builds its root's fragment around what it laid out inside it.let take_run_fragments = || {- run.fragments+ let contents = run+ .fragments.as_ref()- .map(|fragments| fragments.take_unplaced_root(&body_run.callbacks))+ .map(|fragments| fragments.take_unplaced_root(&body_run.callbacks))?;+ if let Some(fragmentainer) = &run.fragmentainer {+ fragmentainer.keep_contents(contents);+ return None;+ }+ Some(contents.into_run_root_fragment(+ &callbacks,+ fragment_tree::FragmentGeometry {+ cells: root_cells_left_by_run,+ line_data: root_line_data.clone(),+ },+ ))};let registered_abspos_children_could_never_be_laid_out = run.fragments.is_none();@@ -3001,22 +2902,12 @@ pub(crate) fn layout_inside_child_with_input_cells(input.containing_block_constraints,child_run_builds_fragments,);- // OPTIMIZATION: A box that took its metrics from its committed fragment is placed with that fragment, where- // it shows the box as its cells hold it.+ // OPTIMIZATION: A box that took its metrics from its committed fragment hands that fragment to its placement.let fragment_arrival = committed_fragment- .filter(|fragment| {- run.fragments.is_some()- && fragment.is_plain_box()- && fragment_tree::FragmentGeometry {- cells: cells_of_this_layout.get(),- line_data: None,- }- .shows_box_of_fragment(fragment)- && !facts.has_anchor_names()- })+ .filter(|fragment| run.fragments.is_some() && fragment.is_plain_box()).map(|fragment| fragment_tree::ChildFragmentArrival::CommittedFragment {fragment,- reuses_subtree: false,+ reuses_committed_subtree: false,});let laid_out_box =run_state::LaidOutChildBox::sized_here(cells_of_this_layout.get(), DerivedBaselines::default());@@ -3461,8 +3352,17 @@ fn child_run_outcome_from_outputs(if outputs_are_stored_ones {keep_inline_margins_resolved_now_where_unobserved(&mut laid_out_box, root_cells, inputs_never_observed);}- let fragment_arrival = parent_fragments.and(root).map(|root| {- debug_assert!(root.node == child, "a child run returned a root for a different box");+ let fragment_arrival = parent_fragments.and(root).map(|mut root| {+ debug_assert!(+ root.fragment.node == child,+ "a child run returned a root for a different box"+ );+ // NB: A stored run's fragment can show the box as it was committed since through another fragment.+ if outputs_are_stored_ones+ && let Some(committed) = fragment_tree::previously_committed_fragment_matching(callbacks, &root.fragment)+ {+ root.fragment = committed;+ }fragment_tree::ChildFragmentArrival::RunRoot {root,reuses_committed_subtree,@@ -3904,13 +3804,13 @@ fn layout_subtree_with_frozen_root_geometry(run: &FormattingContextRun<'_>) {// The retained offset already includes relative positioning. Publish it directly instead// of applying placement adjustments a second time.let Some(fragment_tree::ChildFragmentArrival::RunRoot {- root: unplaced_root,+ root: run_root_fragment,reuses_committed_subtree,}) = fragment_arrivalelse {panic!("the root of a partial relayout is laid out by a run of its own");};- fragments.take_in_child_root_at_placement(root, unplaced_root, reuses_committed_subtree, callbacks);+ fragments.take_in_child_root_at_placement(root, run_root_fragment, reuses_committed_subtree, callbacks);fragments.build_fragment_for_placed_box(callbacks,root,diff --git a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rsindex cf24493d981..bd6c3013872 100644--- a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs+++ b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs@@ -97,14 +97,15 @@ impl PayloadComparison {impl Fragment {fn builds_identically_to(&self, previous: &Fragment) -> bool {- self.has_same_box_properties(previous)- && same_allocation(self.line_data.as_ref(), previous.line_data.as_ref())- && self.children.len() == previous.children.len()- && self- .children- .iter()- .zip(&previous.children)- .all(|(link, previous_link)| link.places_same_fragment_identically_to(previous_link))+ std::ptr::eq(self, previous)+ || self.has_same_box_properties(previous)+ && same_allocation(self.line_data.as_ref(), previous.line_data.as_ref())+ && self.children.len() == previous.children.len()+ && self+ .children+ .iter()+ .zip(&previous.children)+ .all(|(link, previous_link)| link.places_same_fragment_identically_to(previous_link))}/// Whether the fragment holds nothing beyond a plain box's metrics, line data and children: no table, grid, flex,@@ -462,11 +463,16 @@ impl PlacedBoxes {}}-fn previously_committed_fragment_matching(+/// The fragment the box of `candidate` committed, where `candidate` builds identically to it. A fragment that continues+/// in another fragment of its box matches none.+pub(crate) fn previously_committed_fragment_matching(callbacks: &LayoutPass<'_>,candidate: &Fragment,) -> Option<std::sync::Arc<Fragment>> {- if !callbacks.has_committed_fragment_link(candidate.node) {+ if candidate.continues_from_previous_fragment+ || candidate.continues_in_next_fragment+ || !callbacks.has_committed_fragment_link(candidate.node)+ {return None;}callbacks@@ -497,7 +503,7 @@ pub(crate) struct FragmentPayloads {}impl FragmentPayloads {- fn of_fragment(fragment: &Fragment) -> Self {+ pub(crate) fn of_fragment(fragment: &Fragment) -> Self {Self {collapsed_table_borders: fragment.collapsed_table_borders.clone(),grid_layout_data: fragment.grid_layout_data.clone(),@@ -594,16 +600,47 @@ fn snapshot_fragment(continues_in_next_fragment: fragment_facts.continues_in_next_fragment,children,};- if !fragment.continues_from_previous_fragment- && !fragment.continues_in_next_fragment- && let Some(previous) = previously_committed_fragment_matching(callbacks, &fragment)- {+ if let Some(previous) = previously_committed_fragment_matching(callbacks, &fragment) {return previous;}fragment.identity = NEXT_IDENTITY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);std::sync::Arc::new(fragment)}+/// The fragment of a placed box: `arrived`, the fragment its own run built or the committed one, where that shows the+/// box as placed and nothing else was placed in it, or else a fragment of the box's `geometry` around the arrived+/// fragment's children and the `children` placed in it here.+fn fragment_of_placed_box(+ callbacks: &LayoutPass<'_>,+ node: crate::layout::node_data::NodeSlotId,+ arrived: Option<std::sync::Arc<Fragment>>,+ children: Vec<FragmentLink>,+ geometry: FragmentGeometry,+ fragment_facts: run_state::FragmentFactsDecidedByParent,+ payloads: Option<Box<FragmentPayloads>>,+) -> std::sync::Arc<Fragment> {+ let Some(arrived) = arrived else {+ return snapshot_fragment(callbacks, node, children, geometry, fragment_facts, payloads);+ };+ let shows_box_as_placed = children.is_empty()+ && geometry.shows_box_of_fragment(&arrived)+ && arrived.continues_from_previous_fragment == fragment_facts.continues_from_previous_fragment+ && arrived.continues_in_next_fragment == fragment_facts.continues_in_next_fragment;+ if shows_box_as_placed {+ return arrived;+ }+ let mut all_children = arrived.children.clone();+ all_children.extend(children);+ snapshot_fragment(+ callbacks,+ node,+ all_children,+ geometry,+ fragment_facts,+ Some(Box::new(FragmentPayloads::of_fragment(&arrived))),+ )+}+/// The fragment a placement built, and whether anything from its subtree went on to its containing block.pub(crate) struct PlacedFragment {pub(crate) fragment: std::sync::Arc<Fragment>,@@ -722,7 +759,8 @@ struct ChildLeftUnplaced {unplaced_child: crate::layout::formatting_context::PlacedChild,}-#[derive(Clone)]+/// What a run laid out inside its root, before the root's fragment exists: the links at the top of the run's+/// fragments, and what goes past the run.pub(crate) struct UnplacedRootFragment {pub(crate) node: crate::layout::node_data::NodeSlotId,pub(crate) scoped_descendants: Vec<FragmentLink>,@@ -736,6 +774,77 @@ pub(crate) struct UnplacedRootFragment {}impl UnplacedRootFragment {+ /// The root's fragment around what the run laid out inside it, showing the root's own layout `geometry`.+ pub(crate) fn into_run_root_fragment(+ self,+ callbacks: &LayoutPass<'_>,+ geometry: FragmentGeometry,+ ) -> RunRootFragment {+ let Self {+ node,+ scoped_descendants,+ reused_subtree_roots,+ propagated_pending_abspos,+ propagated_anchor_candidates,+ propagated_inline_containing_block_rects,+ propagated_abspos_containing_block_info,+ root_payloads,+ } = self;+ RunRootFragment {+ fragment: snapshot_fragment(+ callbacks,+ node,+ scoped_descendants,+ geometry,+ run_state::FragmentFactsDecidedByParent::default(),+ root_payloads,+ ),+ reused_subtree_roots,+ propagated_pending_abspos,+ propagated_anchor_candidates,+ propagated_inline_containing_block_rects,+ propagated_abspos_containing_block_info,+ }+ }+}++/// What a run hands its parent of its root: the root's fragment, the subtrees the run took from the cache as they+/// were committed, and what goes past the run toward boxes outside it.+#[derive(Clone)]+pub(crate) struct RunRootFragment {+ pub(crate) fragment: std::sync::Arc<Fragment>,+ pub(crate) reused_subtree_roots: HashSet<u32>,+ pub(crate) propagated_pending_abspos: Vec<abspos_inputs::PendingAbsposChild>,+ pub(crate) propagated_anchor_candidates: Vec<AnchorCandidate>,+ pub(crate) propagated_inline_containing_block_rects: Vec<InlineContainingBlockRect>,+ pub(crate) propagated_abspos_containing_block_info: Vec<AbsposContainingBlockInfoContribution>,+}++impl RunRootFragment {+ /// The root fragment of a run that hands nothing past `fragment`.+ pub(crate) fn propagating_nothing(fragment: std::sync::Arc<Fragment>) -> Self {+ Self {+ fragment,+ reused_subtree_roots: HashSet::default(),+ propagated_pending_abspos: Vec::new(),+ propagated_anchor_candidates: Vec::new(),+ propagated_inline_containing_block_rects: Vec::new(),+ propagated_abspos_containing_block_info: Vec::new(),+ }+ }++ /// This root without the subtrees its run took from the cache as they were committed.+ pub(crate) fn without_reused_subtree_roots(&self) -> Self {+ Self {+ fragment: self.fragment.clone(),+ reused_subtree_roots: HashSet::default(),+ propagated_pending_abspos: self.propagated_pending_abspos.clone(),+ propagated_anchor_candidates: self.propagated_anchor_candidates.clone(),+ propagated_inline_containing_block_rects: self.propagated_inline_containing_block_rects.clone(),+ propagated_abspos_containing_block_info: self.propagated_abspos_containing_block_info.clone(),+ }+ }+/// Whether the root hands its ancestors no payload.pub(crate) fn propagates_nothing(&self) -> bool {self.propagated_pending_abspos.is_empty()@@ -745,25 +854,45 @@ impl UnplacedRootFragment {}}-/// What the layout of a child hands the child's placement: the unplaced root fragment of the child's run, or a-/// committed fragment the child is placed with as it is.+/// What the layout of a child hands the child's placement: the root fragment of the child's run, or a committed+/// fragment. The placement takes in either as the fragment of a child run's root, and keeps it where it shows the box+/// as placed.#[must_use = "a child's fragments are lost unless its placement takes them"]pub(crate) enum ChildFragmentArrival {RunRoot {- root: UnplacedRootFragment,+ root: RunRootFragment,reuses_committed_subtree: bool,},CommittedFragment {fragment: std::sync::Arc<Fragment>,- reuses_subtree: bool,+ reuses_committed_subtree: bool,},}impl ChildFragmentArrival {+ pub(crate) fn fragment(&self) -> &std::sync::Arc<Fragment> {+ match self {+ Self::RunRoot { root, .. } => &root.fragment,+ Self::CommittedFragment { fragment, .. } => fragment,+ }+ }+pub(crate) fn node(&self) -> crate::layout::node_data::NodeSlotId {+ self.fragment().node+ }++ /// The child's fragment as the root fragment of a run, and whether it keeps the committed subtree. Nothing goes past+ /// a committed fragment.+ pub(crate) fn into_root(self) -> (RunRootFragment, bool) {match self {- Self::RunRoot { root, .. } => root.node,- Self::CommittedFragment { fragment, .. } => fragment.node,+ Self::RunRoot {+ root,+ reuses_committed_subtree,+ } => (root, reuses_committed_subtree),+ Self::CommittedFragment {+ fragment,+ reuses_committed_subtree,+ } => (RunRootFragment::propagating_nothing(fragment), reuses_committed_subtree),}}}@@ -907,6 +1036,8 @@ impl CompletedPassFragments {struct PendingFragment {node: crate::layout::node_data::NodeSlotId,+ /// The fragment the box's layout handed its placement: the root fragment of its own run, or its committed fragment.+ arrived: Option<std::sync::Arc<Fragment>>,children: Vec<FragmentLink>,pending_abspos: Vec<abspos_inputs::PendingAbsposChild>,anchor_candidates: Vec<AnchorCandidate>,@@ -918,6 +1049,7 @@ impl PendingFragment {fn new(node: crate::layout::node_data::NodeSlotId) -> Self {Self {node,+ arrived: None,children: Vec::new(),pending_abspos: Vec::new(),anchor_candidates: Vec::new(),@@ -1398,12 +1530,11 @@ impl RunFragmentBuilder {inner.receive_abspos_containing_block_info(root.propagated_abspos_containing_block_info);}- /// Takes in the unplaced root of the run that laid out `node`, which is being placed, so that its fragment is built- /// around the root's descendants.+ /// Takes in the root fragment of the run that laid out `node`, which is being placed, and what goes past that run.pub(crate) fn take_in_child_root_at_placement(&self,node: crate::layout::node_data::NodeSlotId,- root: UnplacedRootFragment,+ root: RunRootFragment,reuses_committed_subtree: bool,callbacks: &LayoutPass<'_>,) {@@ -1439,12 +1570,8 @@ impl RunFragmentBuilder {fragment_arrival: Option<ChildFragmentArrival>,) {debug_assert!(!self.left_child_unplaced(node), "a child left unplaced is discarded");- let arrived_payloads = fragment_arrival.and_then(|arrival| match arrival {- ChildFragmentArrival::RunRoot { root, .. } => root.root_payloads,- ChildFragmentArrival::CommittedFragment { fragment, .. } => {- Some(Box::new(FragmentPayloads::of_fragment(&fragment)))- }- });+ let arrived_payloads =+ fragment_arrival.map(|arrival| Box::new(FragmentPayloads::of_fragment(arrival.fragment())));let mut inner = self.inner.borrow_mut();let slot = node.slot_index();let mut payloads_of_box = arrived_payloads;@@ -1485,7 +1612,7 @@ impl RunFragmentBuilder {fn merge_child_root_into_pending_fragment(&self,node: crate::layout::node_data::NodeSlotId,- root: UnplacedRootFragment,+ root: RunRootFragment,callbacks: &LayoutPass<'_>,) {let mut inner = self.inner.borrow_mut();@@ -1494,16 +1621,15 @@ impl RunFragmentBuilder {.pending_fragments.entry(slot).or_insert_with(|| PendingFragment::new(node));- debug_assert!(root.node == node, "a box took in the root of another box's run");debug_assert!(- pending_fragment.children.is_empty() || root.scoped_descendants.is_empty(),+ root.fragment.node == node,+ "a box took in the root of another box's run"+ );+ debug_assert!(+ pending_fragment.children.is_empty() || root.fragment.children.is_empty(),"a child run's root and an open pending fragment both carry children for slot {slot}");- if pending_fragment.children.is_empty() {- pending_fragment.children = root.scoped_descendants;- } else {- pending_fragment.children.extend(root.scoped_descendants);- }+ pending_fragment.arrived = Some(root.fragment);pending_fragment.pending_abspos.extend(root.propagated_pending_abspos.into_iter().map(|mut entry| {@@ -1516,7 +1642,6 @@ impl RunFragmentBuilder {pending_fragment.inline_containing_block_rects.extend(root.propagated_inline_containing_block_rects);- pending_fragment.payloads = root.root_payloads;inner.receive_abspos_containing_block_info(root.propagated_abspos_containing_block_info);}@@ -1538,6 +1663,7 @@ impl RunFragmentBuilder {let slot = node.slot_index();let PendingFragment {node: _,+ arrived,children,pending_abspos: pending_abspos_from_placed_box,anchor_candidates: anchor_candidates_from_placed_box,@@ -1556,7 +1682,15 @@ impl RunFragmentBuilder {committed_offset,callbacks.frame,);- let fragment = snapshot_fragment(callbacks, node, children, geometry, facts.fragment_facts, payloads);+ let fragment = fragment_of_placed_box(+ callbacks,+ node,+ arrived,+ children,+ geometry,+ facts.fragment_facts,+ payloads,+ );let link = link_fragment(fragment.clone(), link_placement);self.attach(&mut inner, link, containing_block);let exports_payloads = !pending_abspos_from_placed_box.is_empty()@@ -1627,49 +1761,6 @@ impl RunFragmentBuilder {}}- /// Places the committed fragment of a box as it is, with the margins in `cells_of_placed_box`. Where the box's- /// subtree is reused as it is, commit stops at the box, so its committed descendants stay as they are.- #[expect(clippy::too_many_arguments)]- pub(crate) fn attach_committed_fragment(- &self,- node: crate::layout::node_data::NodeSlotId,- fragment: std::sync::Arc<Fragment>,- reuses_subtree: bool,- containing_block: Option<crate::layout::node_data::NodeSlotId>,- facts: run_state::FactsDecidedByParent,- cells_of_placed_box: &used_values::RootInputCells,- abspos_layout_inputs: Option<abspos_inputs::AbsposLayoutInputs>,- containing_line_box_index: Option<usize>,- committed_offset: FfiCssPixelPoint,- frame: geometry::Frame,- ) {- assert!(- facts.placement.is_some(),- "a box is placed before its fragment is attached"- );- let mut inner = self.inner.borrow_mut();- let slot = node.slot_index();- debug_assert!(- !inner.pending_fragments.contains_key(&slot),- "a reused subtree's box has fragments of its own in this run (slot {slot})"- );- let link = link_fragment(- fragment,- PlacementData::of_box(- &facts,- cells_of_placed_box,- abspos_layout_inputs,- containing_line_box_index,- committed_offset,- frame,- ),- );- self.attach(&mut inner, link, containing_block);- if reuses_subtree {- inner.reused_subtree_roots.insert(slot);- }- }-/// How many abspos containing block contributions the run has collected so far./// How many abspos containing block info contributions the run has received so far, which only grows.pub(crate) fn abspos_containing_block_info_contributions_received(&self) -> u64 {@@ -1748,60 +1839,40 @@ impl RunFragmentBuilder {pending_fragment.node);}- // NB: A reused subtree root its run never placed has no children of its own in this run, as an empty child run- // root has, and closes the same way.- // An empty box that was never placed has no fragment in this run.- let mut child_run_roots_left_unplaced = Vec::new();+ // NB: A child run's root or a reused subtree root that the run never placed keeps its fragment at the top of the+ // run's fragments, as its subtree goes with it. An empty box that was never placed has no fragment here.for ChildLeftUnplaced {arrival,unplaced_child,} in std::mem::take(&mut inner.children_left_unplaced){- match arrival {+ if matches!(+ arrival,ChildFragmentArrival::CommittedFragment {- fragment,- reuses_subtree: true,- } => {- let node = fragment.node;- inner.reused_subtree_roots.insert(node.slot_index());- let placement = PlacementData::of_unplaced_child(&unplaced_child, callbacks.frame);- inner.top_scope_links.push(link_fragment(- snapshot_fragment(- callbacks,- node,- Vec::new(),- unplaced_child.geometry,- unplaced_child.facts_decided_by_parent.fragment_facts,- Some(Box::new(FragmentPayloads::of_fragment(&fragment))),- ),- placement,- ));+ reuses_committed_subtree: false,+ ..}- ChildFragmentArrival::CommittedFragment {- reuses_subtree: false, ..- } => {}- ChildFragmentArrival::RunRoot {- root,- reuses_committed_subtree,- } => child_run_roots_left_unplaced.push((root, reuses_committed_subtree, unplaced_child)),+ ) {+ continue;}- }- for (root, reuses_committed_subtree, unplaced_child) in child_run_roots_left_unplaced {+ let (root, reuses_committed_subtree) = arrival.into_root();inner.reused_subtree_roots.extend(root.reused_subtree_roots.iter().copied());+ let node = root.fragment.node;if reuses_committed_subtree {- inner.reused_subtree_roots.insert(root.node.slot_index());+ inner.reused_subtree_roots.insert(node.slot_index());}let placement = PlacementData::of_unplaced_child(&unplaced_child, callbacks.frame);inner.top_scope_links.push(link_fragment(- snapshot_fragment(+ fragment_of_placed_box(callbacks,- root.node,- root.scoped_descendants,+ node,+ Some(root.fragment),+ Vec::new(),unplaced_child.geometry,unplaced_child.facts_decided_by_parent.fragment_facts,- root.root_payloads,+ None,),placement,));diff --git a/Libraries/LibWeb/Rust/src/layout/fragmentation.rs b/Libraries/LibWeb/Rust/src/layout/fragmentation.rsindex 38e07749ced..3e087463133 100644--- a/Libraries/LibWeb/Rust/src/layout/fragmentation.rs+++ b/Libraries/LibWeb/Rust/src/layout/fragmentation.rs@@ -239,6 +239,9 @@ pub(crate) struct FragmentainerContext {pub(crate) early_break_before: Option<Node>,pub(crate) allows_early_break_requests: bool,outcome: RefCell<FragmentainerOutcome>,+ /// What the run laid out in the fragmentainer, which the run of the box it belongs to takes in, as the+ /// fragmentainer has no fragment of its own.+ contents: RefCell<Option<super::fragment_tree::UnplacedRootFragment>>,}impl FragmentainerContext {@@ -258,9 +261,18 @@ impl FragmentainerContext {early_break_before,allows_early_break_requests,outcome: RefCell::new(FragmentainerOutcome::default()),+ contents: RefCell::new(None),}}+ pub(crate) fn keep_contents(&self, contents: super::fragment_tree::UnplacedRootFragment) {+ *self.contents.borrow_mut() = Some(contents);+ }++ pub(crate) fn take_contents(&self) -> Option<super::fragment_tree::UnplacedRootFragment> {+ self.contents.take()+ }+pub(crate) fn outcome_mut(&self) -> RefMut<'_, FragmentainerOutcome> {self.outcome.borrow_mut()}diff --git a/Libraries/LibWeb/Rust/src/layout/run_repeatability.rs b/Libraries/LibWeb/Rust/src/layout/run_repeatability.rsindex 81a989ca69d..4a6e4bbf532 100644--- a/Libraries/LibWeb/Rust/src/layout/run_repeatability.rs+++ b/Libraries/LibWeb/Rust/src/layout/run_repeatability.rs@@ -222,7 +222,8 @@ impl ComparedLayouts<'_> {"{checked}: {reference} reused a subtree");assert!(- checked_root.root_payloads == reference_root.root_payloads,+ fragment_tree::FragmentPayloads::of_fragment(&checked_root.fragment)+ == fragment_tree::FragmentPayloads::of_fragment(&reference_root.fragment),"{checked} hands its root's fragment payloads {reference} does not");assert!(@@ -242,7 +243,7 @@ impl ComparedLayouts<'_> {"{checked} propagates payloads {reference} does not");let mut nodes_laid_out_afresh = HashSet::default();- collect_nodes_of_fragment_subtrees(&reference_root.scoped_descendants, &mut nodes_laid_out_afresh);+ collect_nodes_of_fragment_subtrees(&reference_root.fragment.children, &mut nodes_laid_out_afresh);let comparison = FreshDescendantComparison {callbacks,reused_subtree_roots: &checked_root.reused_subtree_roots,@@ -250,8 +251,8 @@ impl ComparedLayouts<'_> {};if let Err(difference) = comparison.compare_children(box_,- &checked_root.scoped_descendants,- &reference_root.scoped_descendants,+ &checked_root.fragment.children,+ &reference_root.fragment.children,false,) {panic!("{checked} lays out descendants unlike {reference}: {difference}");diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rsindex e8248a54953..a46c54954d9 100644--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs@@ -2233,10 +2233,6 @@ impl<'pass> SvgFormattingContext<'pass> {{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 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 {@@ -2273,7 +2269,7 @@ impl<'pass> SvgFormattingContext<'pass> {committed_offset.y,Some(fragment_tree::ChildFragmentArrival::CommittedFragment {fragment,- reuses_subtree: false,+ reuses_committed_subtree: false,}),);Some(LaidOutSvgElement {