Truly independent web browser
LibWeb: Keep the chunks and grapheme segmenters of text in scratch
Aliaksandr Kalenike6645a26d83c
diff --git a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rsindex d4d8b3191cb..ae3dec4a900 100644--- a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs@@ -1308,10 +1308,11 @@ mod tests {use crate::layout::memo_invalidations::MemoInvalidations;let store = FcRunCacheStore::default();let in_flow_block_cache = InFlowBlockCacheStore::default();+ let text_memos = crate::layout::rendered_text::TextMemos::default();let node = Node::new(0, 1);let mut notes = MemoInvalidations::default();notes.note_structural_inline_change(node);- notes.apply_to(&store, &in_flow_block_cache);+ notes.apply_to(&store, &in_flow_block_cache, &text_memos);assert_eq!(store.structural_epoch_bumps_of(node), 0);store.store(node, entry(at(100), 1, Some(root_with_a_descendant()), 0));@@ -1319,7 +1320,7 @@ mod tests {notes.note_structural_inline_change(node);notes.note_fragment_cache_epoch_bumped(node);notes.note_structural_inline_change(node);- notes.apply_to(&store, &in_flow_block_cache);+ notes.apply_to(&store, &in_flow_block_cache, &text_memos);assert_eq!(store.structural_epoch_bumps_of(node), 2);let reused = Node::new(0, 2);@@ -1327,7 +1328,7 @@ mod tests {notes.note_structural_inline_change(node);notes.note_slot_freed(node.slot_index());notes.note_structural_inline_change(reused);- notes.apply_to(&store, &in_flow_block_cache);+ notes.apply_to(&store, &in_flow_block_cache, &text_memos);assert!(!store.slot_holds_entries(0));assert_eq!(store.structural_epoch_bumps_of(reused), 0);}diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rsindex a93d555c807..48bae543711 100644--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs@@ -1752,14 +1752,16 @@ impl<'context> InlineFormattingContext<'context> {line_builder.break_line(line_builder::ForcedBreak::No, NodeSlotId::INVALID, None);continue;}- let split_item = item.split_for_overflow_break(- &text_content.text,- text_content.grapheme_segmenter(),- letter_spacing,- word_spacing,- remaining_inline_size,- line_is_empty,- );+ let split_item = self.callbacks.with_grapheme_segmenter(item.node, |grapheme_segmenter| {+ item.split_for_overflow_break(+ &text_content.text,+ grapheme_segmenter,+ letter_spacing,+ word_spacing,+ remaining_inline_size,+ line_is_empty,+ )+ });let Some(mut prefix) = split_item else {if line_is_empty {return false;@@ -3140,12 +3142,16 @@ impl ContentSizingLines {trailing_whitespace_inline_size: CssPixels,) {let text_content = context.callbacks.text_content(item.node);- let cluster_inline_sizes = item.grapheme_cluster_inline_sizes(- &text_content.text,- text_content.grapheme_segmenter(),- style.letter_spacing().to_double() as f32,- style.word_spacing().to_double() as f32,- );+ let cluster_inline_sizes = context+ .callbacks+ .with_grapheme_segmenter(item.node, |grapheme_segmenter| {+ item.grapheme_cluster_inline_sizes(+ &text_content.text,+ grapheme_segmenter,+ style.letter_spacing().to_double() as f32,+ style.word_spacing().to_double() as f32,+ )+ });let border_and_padding_end = item.padding_end + item.border_end;if border_and_padding_start + item.inline_size + border_and_padding_end > CssPixels::default() {self.lines.finish();diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rsindex 1292acfca54..d183f7604df 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs@@ -5302,6 +5302,7 @@ impl LayoutNodeArena {}state.content = Some(content);drop(state);+ self.memo_invalidations.get_mut().note_text_replaced(id.slot_index());self.searchable_text = None;// Publication can happen through a C++ text read before the enrolled// sync runs. Invalidate here so every publication invalidates layout,diff --git a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs b/Libraries/LibWeb/Rust/src/layout/layout_pass.rsindex 93d718c49fd..89186b9f0ff 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_pass.rs@@ -246,6 +246,30 @@ impl<'arena> LayoutPass<'arena> {.expect("text node content must be synced to the arena before layout")}+ /// The chunks of the text row `node` for `key`, made by `compute` where the last run that chunked the row's text did+ /// so for another key.+ pub(crate) fn text_chunks(+ &self,+ node: Node,+ key: &super::rendered_text::TextChunkCacheKey,+ compute: impl FnOnce() -> Vec<super::text_chunker::TextChunk>,+ ) -> std::sync::Arc<super::rendered_text::CachedTextChunks> {+ self.scratch+ .text_memos()+ .text_chunks(node, self.text_content(node).rendered(), key, compute)+ }++ /// Runs `read` with the grapheme segmenter of the text row `node`.+ pub(crate) fn with_grapheme_segmenter<R>(+ &self,+ node: Node,+ read: impl FnOnce(&super::text_chunker::GraphemeSegmenter) -> R,+ ) -> R {+ self.scratch+ .text_memos()+ .with_grapheme_segmenter(node, self.text_content(node).rendered(), read)+ }+#[inline]pub(crate) fn style_payloads(&self, node: Node) -> &'arena FfiStylePayloads {self.style_payloads_if_styled(node)diff --git a/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs b/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rsindex 054330494a7..7f33804e2a0 100644--- a/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs+++ b/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs@@ -15,10 +15,12 @@use super::fc_run_cache::FcRunCacheStore;use super::in_flow_block_cache::InFlowBlockCacheStore;use super::node_data::NodeSlotId;+use super::rendered_text::TextMemos;#[derive(Clone, Copy, Default)]struct SlotNotes {noted: bool,+ text_memos_dropped: bool,run_cache_entries_dropped: bool,in_flow_block_entries_dropped: bool,fragment_cache_epoch_bumped: bool,@@ -58,7 +60,15 @@ impl MemoInvalidations {/// The box in `slot` left the arena, which drops all its memo entries.pub(crate) fn note_slot_freed(&mut self, slot: u32) {self.note_run_cache_entries_dropped(slot);- self.notes_of(slot).in_flow_block_entries_dropped = true;+ let notes = self.notes_of(slot);+ notes.text_memos_dropped = true;+ notes.in_flow_block_entries_dropped = true;+ }++ /// The text row in `slot` got other rendered text, which the chunks and segmenter made of the old text no longer+ /// describe.+ pub(crate) fn note_text_replaced(&mut self, slot: u32) {+ self.notes_of(slot).text_memos_dropped = true;}/// The fragment cache epoch of `node` moved on: its run cache entries need the sweep, and its in-flow block entry,@@ -82,7 +92,12 @@ impl MemoInvalidations {}/// Applies the notes to the memos, in the order the boxes were first noted.- pub(crate) fn apply_to(self, run_cache: &FcRunCacheStore, in_flow_block_cache: &InFlowBlockCacheStore) {+ pub(crate) fn apply_to(+ self,+ run_cache: &FcRunCacheStore,+ in_flow_block_cache: &InFlowBlockCacheStore,+ text_memos: &TextMemos,+ ) {for slot in self.noted_slots {let notes = self.slots[slot as usize];if notes.run_cache_entries_dropped {@@ -99,6 +114,9 @@ impl MemoInvalidations {if notes.in_flow_block_entries_dropped {in_flow_block_cache.remove_entry(slot);}+ if notes.text_memos_dropped {+ text_memos.forget(slot);+ }}}}diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rsindex c38bfe9939b..24a940404a8 100644--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs@@ -8,7 +8,7 @@ use super::node_data::NodeSlotId;use super::text_transform::{TextRenderingOptions, may_require_bidi_processing, render_text};use super::{ComputedValuesView, LayoutNodeArena};use crate::css::css_enums::text_transform;-use std::cell::{OnceCell, RefCell};+use std::cell::RefCell;use std::sync::Arc;/// Selects the beginning or end of a transformed span for offsets inside it.@@ -80,12 +80,10 @@ impl PartialEq for PublishedTextSlot {}}-/// A text row's rendered text, with what layout caches beside it.+/// A text row's rendered text, with what it was rendered for.#[derive(Clone, Default)]pub(crate) struct TextContent {rendered: Arc<RenderedText>,- grapheme_segmenter: crate::fork::ForkReset<OnceCell<super::text_chunker::GraphemeSegmenter>>,- chunks: RefCell<Option<Arc<CachedTextChunks>>>,pub(super) rendering_key: Option<TextRenderingKey>,}@@ -211,16 +209,54 @@ impl TextContent {.as_ref().is_some_and(|key| key.options.is_password_input)}+}++/// What layout keeps beside the rendered text of the text rows it lays out: the chunks the last run that chunked a row+/// made, and the row's grapheme segmenter. Each keeps the rendered text it was made for, which tells whether the row's+/// text is still that text.+#[derive(Default)]+pub(crate) struct TextMemos {+ chunks: RefCell<Vec<Option<ChunksOfText>>>,+ grapheme_segmenters: RefCell<Vec<Option<GraphemeSegmenterOfText>>>,+}+/// The chunks a run made of a row's rendered text, and that text.+#[derive(Clone)]+struct ChunksOfText {+ rendered: Arc<RenderedText>,+ chunks: Arc<CachedTextChunks>,+}++/// A grapheme segmenter and the rendered text it segments, which it points into, and so drops before.+struct GraphemeSegmenterOfText {+ segmenter: super::text_chunker::GraphemeSegmenter,+ rendered: Arc<RenderedText>,+}++impl TextMemos {+ /// The memos of a fork of the arena, which keeps the chunks and makes grapheme segmenters anew.+ pub(crate) fn fork(&self) -> Self {+ Self {+ chunks: self.chunks.clone(),+ grapheme_segmenters: RefCell::default(),+ }+ }++ /// The chunks of the text row `node`, whose rendered text is `rendered`, for `key`, made by `compute` where the last+ /// run that chunked the row's text did so for another key.pub(crate) fn text_chunks(&self,+ node: NodeSlotId,+ rendered: &Arc<RenderedText>,key: &TextChunkCacheKey,compute: impl FnOnce() -> Vec<super::text_chunker::TextChunk>,) -> Arc<CachedTextChunks> {- if let Some(entry) = self.chunks.borrow().as_ref()- && entry.key == *key+ let index = node.slot_index() as usize;+ if let Some(Some(memo)) = self.chunks.borrow().get(index)+ && Arc::ptr_eq(&memo.rendered, rendered)+ && memo.chunks.key == *key{- return entry.clone();+ return memo.chunks.clone();}// A nested measurement can request a different key while an iterator@@ -230,13 +266,47 @@ impl TextContent {key: key.clone(),chunks: compute(),});- *self.chunks.borrow_mut() = Some(entry.clone());+ let mut chunks = self.chunks.borrow_mut();+ if chunks.len() <= index {+ chunks.resize_with(index + 1, || None);+ }+ chunks[index] = Some(ChunksOfText {+ rendered: rendered.clone(),+ chunks: entry.clone(),+ });entry}- pub(crate) fn grapheme_segmenter(&self) -> &super::text_chunker::GraphemeSegmenter {- self.grapheme_segmenter- .get_or_init(|| super::text_chunker::GraphemeSegmenter::new(&self.text))+ /// Runs `read` with the grapheme segmenter of the text row `node`, whose rendered text is `rendered`.+ pub(crate) fn with_grapheme_segmenter<R>(+ &self,+ node: NodeSlotId,+ rendered: &Arc<RenderedText>,+ read: impl FnOnce(&super::text_chunker::GraphemeSegmenter) -> R,+ ) -> R {+ let index = node.slot_index() as usize;+ let mut segmenters = self.grapheme_segmenters.borrow_mut();+ if segmenters.len() <= index {+ segmenters.resize_with(index + 1, || None);+ }+ let memo = &mut segmenters[index];+ if !memo.as_ref().is_some_and(|memo| Arc::ptr_eq(&memo.rendered, rendered)) {+ *memo = Some(GraphemeSegmenterOfText {+ segmenter: super::text_chunker::GraphemeSegmenter::new(&rendered.text),+ rendered: rendered.clone(),+ });+ }+ read(&memo.as_ref().expect("the memo was just made").segmenter)+ }++ /// Lets go of what the memos keep for the row in `slot`, which the arena freed.+ pub(crate) fn forget(&self, slot: u32) {+ if let Some(chunks) = self.chunks.borrow_mut().get_mut(slot as usize) {+ *chunks = None;+ }+ if let Some(segmenter) = self.grapheme_segmenters.borrow_mut().get_mut(slot as usize) {+ *segmenter = None;+ }}}@@ -406,8 +476,6 @@ fn sync_text_content(arena: &mut LayoutNodeArena, id: NodeSlotId) {dom_length_in_code_units: source_range.length,edits: rendered.edits,}),- grapheme_segmenter: crate::fork::ForkReset::default(),- chunks: RefCell::default(),rendering_key: Some(key),};arena.set_text_content(id, content);@@ -452,16 +520,20 @@ mod tests {frozen_font_list: std::sync::Arc::new(libgfx_rust::font::FrozenFontList::empty()),splits_at_orientation_changes: false,};- let mut previous = content.text_chunks(&key, Vec::new);+ let memos = TextMemos::default();+ let node = NodeSlotId::new(0, 1);+ let mut previous = memos.text_chunks(node, content.rendered(), &key, Vec::new);for language in [LineBreakLanguage::Other,LineBreakLanguage::Chinese,LineBreakLanguage::Japanese,] {key.line_break_language = language;- let chunks = content.text_chunks(&key, Vec::new);+ let chunks = memos.text_chunks(node, content.rendered(), &key, Vec::new);assert!(!std::sync::Arc::ptr_eq(&previous, &chunks));- let hit = content.text_chunks(&key, || panic!("unchanged language should reuse chunks"));+ let hit = memos.text_chunks(node, content.rendered(), &key, || {+ panic!("unchanged language should reuse chunks")+ });assert!(std::sync::Arc::ptr_eq(&chunks, &hit));previous = chunks;}@@ -474,8 +546,15 @@ mod tests {use std::sync::Arc;let mut arena = LayoutNodeArena::new();+ let scratch = crate::layout::run_state::LayoutScratch::default();let node = arena.allocate_for_test().slot;arena.set_text_content(node, content("hello", 0, 5, Vec::new()));+ scratch.apply_memo_invalidations(&arena);+ let text_chunks = |arena: &LayoutNodeArena, key: &TextChunkCacheKey, compute: &dyn Fn() -> Vec<TextChunk>| {+ scratch+ .text_memos()+ .text_chunks(node, arena.text_content(node).unwrap().rendered(), key, compute)+ };let key = TextChunkCacheKey {should_wrap_lines: true,should_respect_linebreaks: false,@@ -498,23 +577,18 @@ mod tests {can_break_after: true,text_type: 0,};- let original = arena- .text_content(node)- .unwrap()- .text_chunks(&key, || vec![chunk.clone()]);- let hit = arena- .text_content(node)- .unwrap()- .text_chunks(&key, || panic!("matching chunks should be cached"));+ let original = text_chunks(&arena, &key, &|| vec![chunk.clone()]);+ let hit = text_chunks(&arena, &key, &|| panic!("matching chunks should be cached"));assert!(Arc::ptr_eq(&original, &hit));drop(hit);let original_weak = Arc::downgrade(&original);- let replacement = arena.text_content(node).unwrap().text_chunks(+ let replacement = text_chunks(+ &arena,&TextChunkCacheKey {should_wrap_lines: false,..key.clone()},- Vec::new,+ &Vec::new,);assert!(replacement.is_empty());assert_eq!(&**original, std::slice::from_ref(&chunk));@@ -534,6 +608,7 @@ mod tests {};let published_hello = published_text(&published);arena.set_text_content(node, content("hello", 0, 5, Vec::new()));+ scratch.apply_memo_invalidations(&arena);assert_eq!(Arc::strong_count(&replacement), 2);// The same content keeps the rendered text the publication shares.assert!(std::sync::Arc::ptr_eq(@@ -541,6 +616,7 @@ mod tests {&published_text(&arena.publish_paint_facts().text)));arena.set_text_content(node, content("goodbye", 0, 7, Vec::new()));+ scratch.apply_memo_invalidations(&arena);assert_eq!(Arc::strong_count(&replacement), 1);// A publication keeps the rendered text it was made with.assert_eq!(@@ -551,14 +627,12 @@ mod tests {published_text(&arena.publish_paint_facts().text).text,"goodbye".encode_utf16().collect::<Vec<_>>());- let new_chunks = arena- .text_content(node)- .unwrap()- .text_chunks(&key, || vec![chunk.clone()]);+ let new_chunks = text_chunks(&arena, &key, &|| vec![chunk.clone()]);assert_eq!(&**new_chunks, std::slice::from_ref(&chunk));drop(replacement);assert!(replacement_weak.upgrade().is_none());let _ = arena.free_subtree(node);+ scratch.apply_memo_invalidations(&arena);assert_eq!(Arc::strong_count(&new_chunks), 1);}diff --git a/Libraries/LibWeb/Rust/src/layout/run_state.rs b/Libraries/LibWeb/Rust/src/layout/run_state.rsindex c7c8d8650ed..0335a6ba887 100644--- a/Libraries/LibWeb/Rust/src/layout/run_state.rs+++ b/Libraries/LibWeb/Rust/src/layout/run_state.rs@@ -24,6 +24,8 @@ pub(crate) struct LayoutScratch {/// The document's layout trace while a stage lays the document out, which the stage takes from the arena and hands/// back once it is done.pub(super) layout_trace: super::trace::LayoutTrace,+ /// The chunks and grapheme segmenters of the text rows the passes laid out.+ text_memos: super::rendered_text::TextMemos,}/// What layout found out that the host hears of once the layout that found it is committed: what the@@ -98,6 +100,7 @@ impl Default for LayoutScratch {fc_run_cache_store: Default::default(),in_flow_block_cache_store: Default::default(),layout_trace: Default::default(),+ text_memos: Default::default(),}}}@@ -109,6 +112,7 @@ impl LayoutScratch {Self {fc_run_cache_store: self.fc_run_cache_store.clone(),in_flow_block_cache_store: self.in_flow_block_cache_store.clone(),+ text_memos: self.text_memos.fork(),..Self::default()}}@@ -121,11 +125,17 @@ impl LayoutScratch {&self.in_flow_block_cache_store}+ pub(super) fn text_memos(&self) -> &super::rendered_text::TextMemos {+ &self.text_memos+ }+/// Brings the run memos up to date with what the arena's writes since the last call did to their boxes.pub(super) fn apply_memo_invalidations(&self, arena: &LayoutNodeArena) {- arena- .take_memo_invalidations()- .apply_to(&self.fc_run_cache_store, &self.in_flow_block_cache_store);+ arena.take_memo_invalidations().apply_to(+ &self.fc_run_cache_store,+ &self.in_flow_block_cache_store,+ &self.text_memos,+ );}pub(super) fn store_inline_item_stash(diff --git a/Libraries/LibWeb/Rust/src/layout/text_chunker.rs b/Libraries/LibWeb/Rust/src/layout/text_chunker.rsindex bff2b5a3d2b..47ae50ceca1 100644--- a/Libraries/LibWeb/Rust/src/layout/text_chunker.rs+++ b/Libraries/LibWeb/Rust/src/layout/text_chunker.rs@@ -1121,7 +1121,7 @@ pub(crate) fn text_chunks() && parent_style.text_orientation() == text_orientation::MIXED,};let text = &callbacks.text_content(node).text;- callbacks.text_content(node).text_chunks(&key, || {+ callbacks.text_chunks(node, &key, || {chunk_text(TextChunkInputs {text,frozen_font_list: &key.frozen_font_list,diff --git a/Libraries/LibWeb/Rust/src/painting/paint_read.rs b/Libraries/LibWeb/Rust/src/painting/paint_read.rsindex d335f0304cd..9cc63a08bbb 100644--- a/Libraries/LibWeb/Rust/src/painting/paint_read.rs+++ b/Libraries/LibWeb/Rust/src/painting/paint_read.rs@@ -401,7 +401,7 @@ impl<Live: AsRef<LayoutNodeArena>> PaintRead for Live {fn with_grapheme_segmenter<R>(&self, id: NodeSlotId, read: impl FnOnce(&GraphemeSegmenter) -> R) -> Option<R> {self.as_ref().text_content(id)- .map(|content| read(content.grapheme_segmenter()))+ .map(|content| read(&GraphemeSegmenter::new(&content.text)))}fn text_fragments(&self, primary: NodeSlotId) -> TextFragments {