Truly independent web browser
LibWeb+LibCompositing: Keep each recorded run as a named chunk
Aliaksandr Kalenikaf544c7d6b50
diff --git a/Libraries/LibCompositing/Rust/src/display_list/builder.rs b/Libraries/LibCompositing/Rust/src/display_list/builder.rsindex 6f6245139e4..01caad2d669 100644--- a/Libraries/LibCompositing/Rust/src/display_list/builder.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/builder.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+use super::chunks::{Chunk, ChunkId, DisplayListChunk, chunk_id, chunks_of};use super::commands::*;use crate::display_list::ffi_bytes::FfiBytes;use libgfx_rust::path::Path;@@ -113,23 +114,50 @@ impl PendingInlineClip {}}-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-pub struct CommandRange {- pub offset: u32,- pub size: u32,+// A finished tape together with the run table summarizing it and the chunks it is cut into.+#[derive(Clone, Default)]+pub struct RecordedDisplayList {+ pub bytes: Vec<u8>,+ pub command_runs: Vec<DisplayListCommandRun>,+ pub chunks: Vec<DisplayListChunk>,}-impl CommandRange {- pub const fn is_empty(self) -> bool {- self.size == 0+impl RecordedDisplayList {+ /// The tape that holds `chunks` one after another, cut into them.+ pub fn of_chunks<'a>(chunks: impl IntoIterator<Item = &'a Chunk>) -> Self {+ let mut list = Self::default();+ for chunk in chunks {+ if chunk.records.is_empty() {+ continue;+ }+ let chunk_start = u32::try_from(list.bytes.len()).expect("display list exceeds u32");+ list.bytes.extend_from_slice(&chunk.records);+ list.command_runs+ .extend(chunk.runs.iter().map(|run| DisplayListCommandRun {+ offset: run.offset + chunk_start,+ ..*run+ }));+ list.chunks.push(DisplayListChunk {+ id: chunk.id,+ byte_end: u32::try_from(list.bytes.len()).expect("display list exceeds u32"),+ run_end: u32::try_from(list.command_runs.len()).expect("display list exceeds u32"),+ });+ }+ list}}-// A finished tape together with the run table summarizing it.-#[derive(Clone, Default)]-pub struct RecordedDisplayList {- pub bytes: Vec<u8>,- pub command_runs: Vec<DisplayListCommandRun>,+fn name_unnamed_chunks(bytes: &[u8], runs: &[DisplayListCommandRun], chunks: &mut [DisplayListChunk]) {+ let mut ids = Vec::new();+ for (index, (chunk, chunk_bytes, chunk_runs)) in chunks_of(bytes, runs, chunks).enumerate() {+ if chunk.id == ChunkId::UNSET {+ let chunk_start = chunk.byte_end - chunk_bytes.len() as u32;+ ids.push((index, chunk_id(chunk_bytes, chunk_runs, chunk_start)));+ }+ }+ for (index, id) in ids {+ chunks[index].id = id;+ }}pub struct OpenGroup {@@ -162,6 +190,9 @@ impl OpenGroup {pub struct DisplayListBuilder {bytes: Vec<u8>,runs: Vec<DisplayListCommandRun>,+ // The chunks ended so far. What was appended since the last one ends is the chunk still open, whose runs are+ // the only ones a command can extend.+ chunks: Vec<DisplayListChunk>,open_group_depth: usize,open_group_context: Option<ContextRef>,}@@ -179,11 +210,61 @@ impl DisplayListBuilder {&self.runs}- pub fn finish(self) -> RecordedDisplayList {+ pub fn chunks(&self) -> &[DisplayListChunk] {+ &self.chunks+ }++ /// Ends the tape with the chunk still open and names every chunk.+ pub fn finish(mut self) -> RecordedDisplayList {+ self.end_chunk();+ name_unnamed_chunks(&self.bytes, &self.runs, &mut self.chunks);RecordedDisplayList {bytes: self.bytes,command_runs: self.runs,+ chunks: self.chunks,+ }+ }++ /// Takes everything appended so far out as one chunk, named by what it holds, and starts again with nothing.+ /// What is appended next starts a run of its own.+ pub fn take_chunk(&mut self) -> Chunk {+ debug_assert_eq!(self.open_group_depth, 0, "a chunk holds whole records");+ debug_assert!(+ self.chunks.is_empty(),+ "a builder cuts its tape into chunks or takes them out, not both"+ );+ Chunk::named(std::mem::take(&mut self.bytes), std::mem::take(&mut self.runs))+ }++ /// Ends a chunk with what was appended since the last one ended, if anything was. What is appended next starts+ /// a run of its own.+ pub fn end_chunk(&mut self) {+ debug_assert_eq!(self.open_group_depth, 0, "a chunk holds whole records");+ let byte_end = u32::try_from(self.bytes.len()).expect("display list exceeds u32");+ if self.chunks.last().map_or(0, |chunk| chunk.byte_end) == byte_end {+ return;+ }+ self.chunks.push(DisplayListChunk {+ id: ChunkId::UNSET,+ byte_end,+ run_end: u32::try_from(self.runs.len()).expect("display list exceeds u32"),+ });+ }++ fn note_command(&mut self, header: &DisplayListCommandHeader, context: ContextRef, offset: usize, size: usize) {+ // Every run so far belongs to a chunk that has ended.+ if self+ .chunks+ .last()+ .is_some_and(|chunk| chunk.run_end as usize == self.runs.len())+ {+ self.runs.push(DisplayListCommandRun {+ offset: u32::try_from(offset).expect("display list exceeds u32"),+ context,+ ..Default::default()+ });}+ note_command(&mut self.runs, header, context, offset, size);}pub fn byte_size(&self) -> usize {@@ -238,7 +319,7 @@ impl DisplayListBuilder {&header,);if self.open_group_depth == 0 {- note_command(&mut self.runs, &header, context, start, padded_record_size);+ self.note_command(&header, context, start, padded_record_size);} else {self.note_group_context(context);}@@ -341,7 +422,7 @@ impl DisplayListBuilder {command.write_ffi_bytes(&mut self.bytes[payload_start..payload_start + std::mem::size_of::<C>()]);self.write_tail_entries(&inline_clips, None, &path_spans, payload_start, entries_offset, &header);if self.open_group_depth == 0 {- note_command(&mut self.runs, &header, context, group.record_start, padded_record_size);+ self.note_command(&header, context, group.record_start, padded_record_size);self.open_group_context = None;}}@@ -455,61 +536,6 @@ impl DisplayListBuilder {entry.write_ffi_bytes(&mut self.bytes[entry_start..entry_start + INLINE_CLIP_ENTRY_SIZE]);}}-- pub fn append_command_range(&mut self, source: &RecordedDisplayList, range: CommandRange) -> u32 {- debug_assert_eq!(self.open_group_depth, 0, "captures are never spliced inside a group");- debug_assert_eq!(self.bytes.len() % COMMAND_ALIGNMENT, 0);- debug_assert_eq!(range.size as usize % COMMAND_ALIGNMENT, 0);- let destination_offset = self.bytes.len();- if range.is_empty() {- return u32::try_from(destination_offset).expect("display list exceeds u32");- }- let source_range = &source.bytes[range.offset as usize..(range.offset + range.size) as usize];- self.bytes.extend_from_slice(source_range);- self.note_runs_copied_from_source(&source.command_runs, range, destination_offset);- u32::try_from(destination_offset).expect("display list exceeds u32")- }-- fn note_runs_copied_from_source(- &mut self,- source_runs: &[DisplayListCommandRun],- range: CommandRange,- destination_offset: usize,- ) {- let range_end = range.offset + range.size;- let first = source_runs.partition_point(|run| run.offset + run.size <= range.offset);- for run in &source_runs[first..] {- if run.offset >= range_end {- break;- }- let start = run.offset.max(range.offset);- let end = (run.offset + run.size).min(range_end);- let destination_start = destination_offset + (start - range.offset) as usize;- let context = run.context;- if start == run.offset && end == run.offset + run.size {- push_or_merge_run(- &mut self.runs,- DisplayListCommandRun {- offset: u32::try_from(destination_start).expect("display list exceeds u32"),- context,- ..*run- },- );- continue;- }- let Self { bytes, runs, .. } = self;- let destination_end = destination_offset + (end - range.offset) as usize;- for_each_command(&bytes[destination_start..destination_end], |header, offset, payload| {- note_command(- runs,- header,- context,- destination_start + offset,- HEADER_SIZE + payload.len(),- );- });- }- }}/// Appends one record, with neither inline clips nor an inline transform, to a tape without a run table, which the@@ -528,19 +554,6 @@ pub fn append_record<C: DisplayListCommand>(bytes: &mut Vec<u8>, command: &C, inbytes[inline_start..inline_start + inline_data.len()].copy_from_slice(inline_data);}-fn push_or_merge_run(runs: &mut Vec<DisplayListCommandRun>, run: DisplayListCommandRun) {- if let Some(last) = runs.last_mut()- && last.context == run.context- {- debug_assert_eq!(last.offset + last.size, run.offset);- last.size += run.size;- last.has_compositor_metadata |= run.has_compositor_metadata;- last.ink_bounds = last.ink_bounds.united(run.ink_bounds);- return;- }- runs.push(run);-}-pub(crate) fn note_command(runs: &mut Vec<DisplayListCommandRun>,header: &DisplayListCommandHeader,@@ -695,20 +708,6 @@ mod tests {}}- fn finished(builder: &DisplayListBuilder) -> RecordedDisplayList {- RecordedDisplayList {- bytes: builder.bytes().to_vec(),- command_runs: builder.command_runs().to_vec(),- }- }-- fn whole_tape(builder: &DisplayListBuilder) -> CommandRange {- CommandRange {- offset: 0,- size: u32::try_from(builder.byte_size()).unwrap(),- }- }-fn assert_runs_cover_tape(builder: &DisplayListBuilder) {let mut expected_offset = 0;for run in builder.command_runs() {@@ -880,10 +879,10 @@ mod tests {}#[test]- fn spliced_records_keep_inline_clip_entries_byte_identical() {- let mut source = DisplayListBuilder::new();+ fn a_chunk_keeps_its_records_byte_identical_wherever_a_tape_holds_it() {+ let mut builder = DisplayListBuilder::new();let recorded = context(4, None);- source.append_with_inline_clips(+ builder.append_with_inline_clips(&fill_rect(0, 0, 100, 100),&[1, 2, 3],recorded,@@ -891,118 +890,87 @@ mod tests {10, 10, 20, 20,))],);+ let chunk = builder.take_chunk();+ let mut before = DisplayListBuilder::new();+ before.append(&fill_rect(0, 0, 1, 1), &[], context(1, None));+ let before = before.take_chunk();- let mut builder = DisplayListBuilder::new();- let destination_offset = builder.append_command_range(&finished(&source), whole_tape(&source));- let source_header = read_header(source.bytes());- let spliced_header = read_header(&builder.bytes()[destination_offset as usize..]);- assert_eq!(builder.command_runs()[0].context, recorded);- assert_eq!(builder.bytes(), source.bytes());- assert_eq!(spliced_header.inline_clip_count, source_header.inline_clip_count);- let payload_of = |bytes: &[u8], offset: usize| {- let header = read_header(&bytes[offset..]);- bytes[offset + HEADER_SIZE..offset + HEADER_SIZE + header.payload_size as usize].to_vec()- };- assert_eq!(- payload_of(source.bytes(), 0),- payload_of(builder.bytes(), destination_offset as usize)- );+ let tape = RecordedDisplayList::of_chunks([&before, &chunk]);+ let chunk_start = tape.chunks[0].byte_end as usize;+ assert_eq!(&tape.bytes[chunk_start..], &chunk.records[..]);+ assert_eq!(tape.command_runs[1].offset as usize, chunk_start);+ assert_eq!(tape.command_runs[1].context, recorded);+ assert_eq!(read_header(&tape.bytes[chunk_start..]).inline_clip_count, 1);+ assert_eq!(tape.chunks[1].id, chunk.id);}#[test]- fn a_verbatim_splice_reproduces_the_source_runs_rebased() {- let mut source = DisplayListBuilder::new();- let a = context(2, None);- let b = context(3, Some(0));- source.append(&fill_rect(0, 0, 10, 10), &[], a);- source.append(&fill_rect(20, 20, 10, 10), &[], b);- source.append(&fill_rect(40, 40, 10, 10), &[], b);- let source_runs = source.command_runs().to_vec();- assert_eq!(source_runs.len(), 2);-+ fn a_chunk_boundary_separates_runs_in_one_context() {let mut builder = DisplayListBuilder::new();- builder.append(&fill_rect(0, 0, 1, 1), &[], context(9, None));- let destination_offset = builder.append_command_range(&finished(&source), whole_tape(&source));+ let a = context(2, None);+ builder.append(&fill_rect(0, 0, 10, 10), &[], a);+ builder.append(&fill_rect(20, 0, 10, 10), &[], a);+ let first = builder.take_chunk();+ // Taking a chunk that holds nothing gives an empty one, which a tape leaves out.+ let empty = builder.take_chunk();+ builder.append(&fill_rect(40, 0, 10, 10), &[], a);+ builder.append(&fill_rect(60, 0, 10, 10), &[], a);assert_runs_cover_tape(&builder);- let spliced_runs = &builder.command_runs()[1..];- assert_eq!(spliced_runs.len(), source_runs.len());- for (spliced, original) in spliced_runs.iter().zip(&source_runs) {- assert_eq!(spliced.offset, original.offset + destination_offset);- assert_eq!(- DisplayListCommandRun {- offset: original.offset,- ..*spliced- },- *original- );- }+ let second = builder.take_chunk();+ assert!(empty.records.is_empty() && empty.runs.is_empty());+ assert_eq!(first.runs.len(), 1);+ assert_eq!(second.runs[0].offset, 0);+ let tape = RecordedDisplayList::of_chunks([&first, &empty, &second]);+ assert_eq!(tape.command_runs.len(), 2);+ assert_eq!(tape.chunks.len(), 2);+ assert_eq!(tape.chunks[0].run_end, 1);+ assert_eq!(tape.chunks[0].byte_end, tape.command_runs[1].offset);+ assert_eq!(tape.chunks[1].run_end, 2);+ assert_eq!(tape.chunks[1].byte_end as usize, tape.bytes.len());+ assert_eq!(tape.command_runs[0].ink_bounds, IntRect::new(0, 0, 30, 10));+ assert_eq!(tape.command_runs[1].ink_bounds, IntRect::new(40, 0, 30, 10));}#[test]- fn copied_runs_match_a_walk_of_the_copied_records_for_every_range() {- let mut source = DisplayListBuilder::new();- let contexts = [- context(1, None),- context(1, None),- context(2, Some(0)),- context(1, None),- context(1, None),- ];- for (index, run_context) in contexts.iter().enumerate() {- let size = 10 * (index as i32 + 1);- source.append(&fill_rect(size, size, size, size), &[], *run_context);- if index == 2 {- source.append(+ fn a_tape_of_taken_chunks_is_the_tape_that_cutting_one_recording_gives() {+ // One chunk for each row: rects in two contexts, where the first context of a row is the last of the row+ // before it, and a metadata command in the third row.+ let record_row = |builder: &mut DisplayListBuilder, row: usize| {+ let y = row as i32 * 10;+ let (first_context, second_context) = if row.is_multiple_of(2) { (1, 2) } else { (2, 1) };+ builder.append(&fill_rect(0, y, 10, 10), &[], context(first_context, None));+ builder.append(&fill_rect(20, y, 10, 10), &[], context(second_context, Some(0)));+ if row == 2 {+ builder.append(&CompositorBlockingWheelEventRegion {rect: FloatRect::new(0.0, 0.0, 500.0, 500.0),},&[],- *run_context,+ context(second_context, Some(0)),);}- }- let source = finished(&source);- let mut record_offsets = Vec::new();- for_each_command(&source.bytes, |_, offset, _| record_offsets.push(offset as u32));- record_offsets.push(source.bytes.len() as u32);-- for (start_index, &start) in record_offsets.iter().enumerate() {- for &end in &record_offsets[start_index + 1..] {- let range = CommandRange {- offset: start,- size: end - start,- };- let mut copied = DisplayListBuilder::new();- copied.append(&fill_rect(0, 0, 1, 1), &[], context(1, None));- copied.append_command_range(&source, range);-- let mut walked = DisplayListBuilder::new();- walked.append(&fill_rect(0, 0, 1, 1), &[], context(1, None));- let destination_offset = walked.bytes.len();- walked- .bytes- .extend_from_slice(&source.bytes[start as usize..end as usize]);- for run in &source.command_runs {- let run_start = run.offset.max(start) as usize;- let run_end = (run.offset + run.size).min(end) as usize;- if run_start >= run_end {- continue;- }- for_each_command(&source.bytes[run_start..run_end], |header, offset, payload| {- note_command(- &mut walked.runs,- header,- run.context,- destination_offset + run_start - start as usize + offset,- HEADER_SIZE + payload.len(),- );- });- }-- assert_eq!(copied.bytes(), walked.bytes());- assert_eq!(copied.command_runs(), walked.command_runs(), "range {range:?}");- assert_runs_cover_tape(&copied);- }- }+ };+ let row_count = 5;+ let mut taken = DisplayListBuilder::new();+ let chunks: Vec<Chunk> = (0..row_count)+ .map(|row| {+ record_row(&mut taken, row);+ taken.take_chunk()+ })+ .collect();+ let mut cut = DisplayListBuilder::new();+ for row in 0..row_count {+ record_row(&mut cut, row);+ cut.end_chunk();+ }+ let cut = cut.finish();++ let of_chunks = RecordedDisplayList::of_chunks(&chunks);+ assert_eq!(of_chunks.bytes, cut.bytes);+ assert_eq!(of_chunks.command_runs, cut.command_runs);+ assert_eq!(of_chunks.chunks, cut.chunks);+ // A chunk is named by what it holds, wherever a tape holds it.+ let reversed = RecordedDisplayList::of_chunks(chunks.iter().rev());+ assert_eq!(reversed.chunks.last().unwrap().id, of_chunks.chunks[0].id);}}diff --git a/Libraries/LibCompositing/Rust/src/display_list/chunks.rs b/Libraries/LibCompositing/Rust/src/display_list/chunks.rsnew file mode 100644index 00000000000..12b5487c509--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/chunks.rs@@ -0,0 +1,149 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The chunks a tape is cut into.+//!+//! A producer of tapes ends a chunk where what it records next can change without what it recorded before. The tape+//! that replaces another is then mostly the same chunks, a recording reuses whole chunks of the one before it, and a+//! chunk is named by what it holds, so two tapes can be told apart chunk by chunk.++use super::commands::DisplayListCommandRun;+use super::storage::write_run;+use std::hash::{BuildHasher, Hasher};++/// Names a chunk by what it holds: chunks with one id hold the same records in the same runs.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub struct ChunkId(pub [u64; 2]);++impl ChunkId {+ /// The id of a chunk whose records can still change.+ pub const UNSET: Self = Self([0, 0]);+}++/// A stretch of whole records with the runs that cover them, which name the records by their offsets from where the+/// chunk starts. A chunk is immutable once named, so that every holder of one name draws the same.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Chunk {+ pub id: ChunkId,+ pub records: Vec<u8>,+ pub runs: Vec<DisplayListCommandRun>,+}++impl Chunk {+ /// The chunk that holds `records` in `runs`, named by them.+ pub fn named(records: Vec<u8>, runs: Vec<DisplayListCommandRun>) -> Self {+ Self {+ id: chunk_id(&records, &runs, 0),+ records,+ runs,+ }+ }+}++/// Where a chunk of a tape ends. Chunks cover a tape, each starting where the one before it ends, and hold whole+/// runs: a run never continues into the next chunk, even where that one begins in the same visual context.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct DisplayListChunk {+ pub id: ChunkId,+ pub byte_end: u32,+ pub run_end: u32,+}++const RUN_SIZE: usize = std::mem::size_of::<DisplayListCommandRun>();++/// The id of the chunk that holds `bytes` in `runs`, which name the bytes by their offsets in the tape the chunk+/// starts at `chunk_start` of.+pub fn chunk_id(bytes: &[u8], runs: &[DisplayListCommandRun], chunk_start: u32) -> ChunkId {+ let write_runs = |hasher: &mut crate::fast_hash::FastHasher| {+ let mut run_bytes = [0; RUN_SIZE];+ for run in runs {+ write_run(+ &DisplayListCommandRun {+ offset: run.offset - chunk_start,+ ..*run+ },+ &mut run_bytes,+ );+ hasher.write(&run_bytes);+ }+ };+ // Two digests that differ in their seed and in the order they read the chunk in.+ let mut records_first = foldhash::fast::FixedState::with_seed(0x6368_756e_6b5f_6964).build_hasher();+ records_first.write(bytes);+ write_runs(&mut records_first);+ let mut runs_first = foldhash::fast::FixedState::with_seed(0x7461_7065_5f63_7574).build_hasher();+ write_runs(&mut runs_first);+ runs_first.write(bytes);+ ChunkId([records_first.finish(), runs_first.finish()])+}++/// The bytes and runs of each chunk of a tape, in tape order.+pub fn chunks_of<'a>(+ bytes: &'a [u8],+ runs: &'a [DisplayListCommandRun],+ chunks: &'a [DisplayListChunk],+) -> impl Iterator<Item = (&'a DisplayListChunk, &'a [u8], &'a [DisplayListCommandRun])> {+ let mut byte_start = 0;+ let mut run_start = 0;+ chunks.iter().map(move |chunk| {+ let chunk_bytes = &bytes[byte_start..chunk.byte_end as usize];+ let chunk_runs = &runs[run_start..chunk.run_end as usize];+ byte_start = chunk.byte_end as usize;+ run_start = chunk.run_end as usize;+ (chunk, chunk_bytes, chunk_runs)+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::display_list::builder::{DisplayListBuilder, RecordedDisplayList};+ use crate::display_list::commands::{ClipNodeIndex, ContextRef, EffectNodeIndex, FillRect, SpatialNodeIndex};+ use libgfx_rust::{Color, CompositingAndBlendingOperator, IntRect};++ fn context(spatial: u32) -> ContextRef {+ ContextRef {+ spatial: SpatialNodeIndex(spatial),+ clip: ClipNodeIndex::NONE,+ effect: EffectNodeIndex::NONE,+ }+ }++ fn fill_rect(y: i32) -> FillRect {+ FillRect {+ rect: IntRect::new(0, y, 10, 10),+ color: Color::default(),+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ }+ }++ // A tape of one chunk for each of `rows`, each a rect at that row in one context and one in another.+ fn tape_of_rows(rows: &[i32]) -> RecordedDisplayList {+ let mut builder = DisplayListBuilder::new();+ for &row in rows {+ builder.append(&fill_rect(row), &[], context(1));+ builder.append(&fill_rect(row + 1), &[], context(2));+ builder.end_chunk();+ }+ builder.finish()+ }++ #[test]+ fn a_chunk_is_named_by_its_records_and_runs_wherever_it_is_in_a_tape() {+ let tape = tape_of_rows(&[10, 20, 10]);+ assert_eq!(tape.chunks.len(), 3);+ assert_eq!(tape.chunks[0].id, tape.chunks[2].id);+ assert_ne!(tape.chunks[0].id, tape.chunks[1].id);+ assert_ne!(tape.chunks[0].id, ChunkId::UNSET);++ // The same records in another visual context are another chunk.+ let mut builder = DisplayListBuilder::new();+ builder.append(&fill_rect(10), &[], context(1));+ builder.append(&fill_rect(11), &[], context(3));+ assert_ne!(builder.finish().chunks[0].id, tape.chunks[0].id);+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/mod.rs b/Libraries/LibCompositing/Rust/src/display_list/mod.rsindex 0009d3d3fff..13e54126448 100644--- a/Libraries/LibCompositing/Rust/src/display_list/mod.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/mod.rs@@ -7,6 +7,7 @@pub mod builder;pub mod canvas_2d;pub mod canvas_2d_recorder;+pub mod chunks;pub mod commands;pub mod damage;pub mod depth_sorted_plan;diff --git a/Libraries/LibCompositing/Rust/src/display_list/tape.rs b/Libraries/LibCompositing/Rust/src/display_list/tape.rsindex 9c37c67e0b7..7f833fa9e10 100644--- a/Libraries/LibCompositing/Rust/src/display_list/tape.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/tape.rs@@ -83,9 +83,10 @@ ffi_bytes_fields!(DisplayListInlineTransform { transform, padding });pub const INLINE_TRANSFORM_ENTRY_SIZE: usize = std::mem::size_of::<DisplayListInlineTransform>();const _: () = assert!(INLINE_TRANSFORM_ENTRY_SIZE == 32);-// A maximal sequence of consecutive commands sharing one visual context, summarized as the tape is-// built so that replay can enter a context, cull, and depth-sort per run. The run owns the visual-// context of its commands, including records nested inside groups. Runs cover the whole tape.+// A sequence of consecutive commands sharing one visual context, summarized as the tape is built so+// that replay can enter a context, cull, and depth-sort per run. The run owns the visual context of+// its commands, including records nested inside groups. Runs cover the whole tape, and a run ends+// where its context does or where the chunk of the tape that holds it does.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]#[repr(C)]pub struct DisplayListCommandRun {diff --git a/Libraries/LibCompositing/Rust/src/display_list/validate.rs b/Libraries/LibCompositing/Rust/src/display_list/validate.rsindex 6c4b0e8aa0d..51ba1152d2b 100644--- a/Libraries/LibCompositing/Rust/src/display_list/validate.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/validate.rs@@ -783,12 +783,6 @@ pub fn validate_tape(tape: &[u8], run_bytes: &[u8]) -> Result<Vec<DisplayListComif size > tape.len() - next_offset {return Err("Display list command runs exceed the tape");}- if runs- .last()- .is_some_and(|previous: &DisplayListCommandRun| previous.context == run.context)- {- return Err("Adjacent display list command runs share a visual context");- }let mut summary = RunSummary::default();validate_records(&tape[next_offset..next_offset + size],diff --git a/Libraries/LibWeb/HTML/PaintConfig.h b/Libraries/LibWeb/HTML/PaintConfig.hindex 9b6ab46a369..3d9f5ec4e6b 100644--- a/Libraries/LibWeb/HTML/PaintConfig.h+++ b/Libraries/LibWeb/HTML/PaintConfig.h@@ -18,6 +18,9 @@ inline constexpr i32 default_force_dark_background_threshold = 205;struct PaintConfig {bool paint_overlay { false };+ // Cuts what a recording keeps for the next one to copy from as finely as it goes. Tests of what a change records+ // again ask for it: their pages are too small to span the rows a recording is otherwise cut along.+ bool records_in_finest_runs { false };bool should_show_line_box_borders { false };bool should_show_caret_hit_test_debug_overlay { false };bool force_dark_enabled { false };diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 8070cc64ea1..113be973623 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -1741,7 +1741,7 @@ bool Internals::recorded_display_list_blocks_wheel_event_at(double x, double y)return Layout::RustFFI::render_state_recorded_blocks_wheel_event_at(document.layout_node_arena().host(), position);}-void Internals::record_display_list_for_testing(bool paint_overlay, bool cold)+void Internals::record_display_list_for_testing(bool paint_overlay, bool cold, bool finest_runs){auto& document = window().associated_document();Layout::ForcedReadScope read { document };@@ -1751,7 +1751,7 @@ void Internals::record_display_list_for_testing(bool paint_overlay, bool cold)// A recording against a visual context tree built fresh copies nothing from the published one.if (cold)document.schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::FreshTree);- (void)document.record_display_list(read, HTML::PaintConfig { .paint_overlay = paint_overlay }, Painting::PaintCommandCacheMode::ReadWrite);+ (void)document.record_display_list(read, HTML::PaintConfig { .paint_overlay = paint_overlay, .records_in_finest_runs = finest_runs }, Painting::PaintCommandCacheMode::ReadWrite);}void Internals::set_autoplay_policy(Utf16String const& policy)diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex e6591dbc35d..f4748974dcd 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -198,7 +198,7 @@ public:GC::Ref<JS::Object> recorded_display_list_wheel_target_at(double x, double y, double delta_x, double delta_y);bool recorded_display_list_blocks_wheel_event_at(double x, double y);GC::Ref<JS::Object> recorded_async_scrolling_state_object();- void record_display_list_for_testing(bool paint_overlay, bool cold);+ void record_display_list_for_testing(bool paint_overlay, bool cold, bool finest_runs);void set_autoplay_policy(Utf16String const& policy);Utf16String get_computed_role(DOM::Element& element);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex 019413450c8..e4b1b6ff94e 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -222,7 +222,7 @@ interface Internals {// position.boolean recordedDisplayListBlocksWheelEventAt(double x, double y);[ImplementedAs=recorded_async_scrolling_state_object] object recordedAsyncScrollingState();- undefined recordDisplayListForTesting(optional boolean paintOverlay = false, optional boolean cold = false);+ undefined recordDisplayListForTesting(optional boolean paintOverlay = false, optional boolean cold = false, optional boolean finestRuns = false);undefined setAutoplayPolicy(DOMString policy);DOMString getComputedRole(Element element);diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cppindex 971076fa24b..427924eb22d 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp@@ -536,6 +536,7 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunReinputs.force_dark_foreground_threshold = config.force_dark_foreground_threshold;inputs.force_dark_background_threshold = config.force_dark_background_threshold;inputs.should_paint_overlay = config.paint_overlay;+ inputs.records_in_finest_runs = config.records_in_finest_runs;inputs.has_blocking_wheel_event_region_covering_viewport = wheel_event_region_state.has_blocking_wheel_event_region_covering_viewport;inputs.wheel_event_listener_state_generation = document.page().wheel_event_listener_state_generation();inputs.chrome_metrics = document.page().chrome_metrics();diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/recorder.rs b/Libraries/LibWeb/Rust/src/painting/display_list/recorder.rsindex 089b7474e7f..4a0c77d1228 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list/recorder.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list/recorder.rs@@ -4,9 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/-use super::builder::{- CommandRange, DisplayListBuilder, HEADER_SIZE, OpenGroup, PendingInlineClip, RecordedDisplayList,-};+use super::builder::{DisplayListBuilder, HEADER_SIZE, OpenGroup, PendingInlineClip};+use super::chunks::Chunk;use super::commands::*;use crate::painting::display_list::ffi_bytes::FfiBytes;use crate::painting::force_dark::{ForceDarkResolver, ForceDarkRole, ForceDarkSettings};@@ -477,16 +476,10 @@ impl DisplayListRecorder {);}- /// Copies the commands in `bytes` of `source` as they were recorded. The caller must establish- /// that their visual-context indices are still valid for the current visual context tree.- pub fn append_cached_commands(&mut self, source: &RecordedDisplayList, bytes: std::ops::Range<u32>) {- self.builder.append_command_range(- source,- CommandRange {- offset: bytes.start,- size: bytes.end - bytes.start,- },- );+ /// Takes everything recorded so far out as one chunk, named by what it holds. What is recorded next starts a run+ /// of its own.+ pub fn take_chunk(&mut self) -> Chunk {+ self.builder.take_chunk()}pub fn fill_rect(&mut self, rect: IntRect, color: Color, force_dark_role: ForceDarkRole) {diff --git a/Libraries/LibWeb/Rust/src/painting/host/paint.rs b/Libraries/LibWeb/Rust/src/painting/host/paint.rsindex a2e3a82e94d..89449452764 100644--- a/Libraries/LibWeb/Rust/src/painting/host/paint.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/paint.rs@@ -22,6 +22,7 @@ pub struct FfiRecordingInputs {pub force_dark_foreground_threshold: i32,pub force_dark_background_threshold: i32,pub should_paint_overlay: bool,+ pub records_in_finest_runs: bool,pub has_blocking_wheel_event_region_covering_viewport: bool,pub has_navigable_container_with_composited_context: bool,pub wheel_event_listener_state_generation: u64,@@ -177,6 +178,7 @@ impl FfiRecordingInputs {background_brightness_threshold: self.force_dark_background_threshold,},should_paint_overlay: self.should_paint_overlay,+ records_in_finest_runs: self.records_in_finest_runs,canvas_fill_rect: self.canvas_fill_rect.has_value.then_some(self.canvas_fill_rect.value),opaque_canvas: self.opaque_canvas,bitmap_rect: self.bitmap_rect,diff --git a/Libraries/LibWeb/Rust/src/painting/paint_order_plan.rs b/Libraries/LibWeb/Rust/src/painting/paint_order_plan.rsindex 3f70c454c39..82b5cfc59d0 100644--- a/Libraries/LibWeb/Rust/src/painting/paint_order_plan.rs+++ b/Libraries/LibWeb/Rust/src/painting/paint_order_plan.rs@@ -26,10 +26,6 @@ pub(crate) enum StackingContextPaintPhase {Foreground = 3,}-impl StackingContextPaintPhase {- pub(crate) const COUNT: usize = Self::Foreground as usize + 1;-}-const _: () = assert!(StackingContextPaintPhase::Floats as usize == StackingContextPaintPhase::BackgroundAndBorders as usize + 1&& StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced as usize@@ -95,7 +91,7 @@ pub(crate) enum PaintProducer {ScopePreamble,}-#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub(crate) enum PaintOrderItem {Producer(PaintProducer),Scope(PaintScope),diff --git a/Libraries/LibWeb/Rust/src/painting/paint_read.rs b/Libraries/LibWeb/Rust/src/painting/paint_read.rsindex 725c3af28ab..62c332d4372 100644--- a/Libraries/LibWeb/Rust/src/painting/paint_read.rs+++ b/Libraries/LibWeb/Rust/src/painting/paint_read.rs@@ -592,10 +592,6 @@ impl<'a> PaintSource<'a> {pub(crate) fn paint_damage_of_row(&self, row: NodeSlotId) -> PaintDamage {self.frame().damage().of_row(row)}-- pub(crate) fn damaged_paint_rows(&self) -> impl Iterator<Item = NodeSlotId> + 'a {- self.frame().damage().rows()- }}impl GeometryRead for PaintSource<'_> {diff --git a/Libraries/LibWeb/Rust/src/painting/record/assemble.rs b/Libraries/LibWeb/Rust/src/painting/record/assemble.rsindex c9f02b6dcc3..7205df1e234 100644--- a/Libraries/LibWeb/Rust/src/painting/record/assemble.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/assemble.rs@@ -4,21 +4,25 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Assembles a frame from the retained paint-order tree and the pushed damage. Scopes on a-//! damaged path are walked, clean children are copied from the published recording by range, and-//! damaged producers are recorded again under explicit contexts. Nothing is validated on the-//! way: when assembly starts, the damage set is complete by construction.+//! Assembles a frame from the scopes the published recording walked and the pushed damage. A walked scope whose+//! owner has no damage below it and has not moved is reused whole. Otherwise its plan is walked: each run of items+//! reuses the chunk the published recording recorded it into, or is recorded again into a chunk of its own, from its+//! first item to its last, when damage reaches it or an ancestor moved it. Nothing is validated on the way: when+//! assembly starts, the damage set is complete by construction.use super::PaintPhase;use super::order_tree::{- ChildEntry, ChildKey, OutputSize, PaintOrderTree, PaintOrderTreeAccess, ProducerKind, ScopeId, ScopeMarks,+ OutputFacts, ProducerKind, RecordedChunk, RecordedRun, RecordedScope, RecordedSegment, RowPlacement, Segment,+ SegmentedPlan,};use crate::css::style::fast_hash::FastMap;use crate::layout::node_data::NodeSlotId;-use crate::painting::paint_order_plan::{PaintOrderItem, PaintProducer, PaintScope, PaintScopeKind};+use crate::painting::paint_order_plan::{+ PaintOrderItem, PaintProducer, PaintScope, PaintScopeKind, StackingContextPaintPhase,+};use crate::painting::record::damage::PaintDamage;use smallvec::SmallVec;-use std::ops::Range;+use std::sync::Arc;/// The planner's items for one scope in paint order. Every producer belongs to the scope's/// owner. An inactive plan is a stacking context that does not paint; its scope records nothing.@@ -28,10 +32,9 @@ pub(crate) struct ScopePlan {pub items: SmallVec<[PaintOrderItem; 16]>,}-/// A box phase in paint order is up to two producers: the scroll metadata recorded with the-/// background, and its commands. An SVG root paints its background, border and then all of its-/// content as one producer. What a hit test finds where a box paints nothing is no producer: hit-/// testing walks the rows.+/// A box phase in paint order is up to two producers: the scroll metadata recorded with the background, and its+/// commands. An SVG root paints its background, border and then all of its content as one producer. What a box can+/// be hit by is not recorded: hit testing walks the paint order over the rows.pub(crate) fn producer_kinds(producer: PaintProducer) -> SmallVec<[ProducerKind; 4]> {use ProducerKind::*;match producer {@@ -57,6 +60,17 @@ pub(crate) struct ProducerOutcome {pub live: bool,// Recorded again when the window gains or loses focus.pub reads_window_focus: bool,+ pub blocking_wheel_event_regions: u32,+}++impl ProducerOutcome {+ fn facts(self) -> OutputFacts {+ OutputFacts {+ blocking_wheel_event_regions: self.blocking_wheel_event_regions,+ live: self.live,+ reads_window_focus: self.reads_window_focus,+ }+ }}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -79,364 +93,317 @@ pub(crate) enum AssemblyEvent {ProducerCopied(NodeSlotId, ProducerKind),}-/// The end of the output being assembled: command bytes and blocking wheel regions so far.-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-pub(crate) struct OutputPosition {- pub bytes: u32,- pub blocking_wheel_event_regions: u32,+/// Where the plan of a walked scope is cut at one of its items.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum ItemCut {+ /// A child scope that is walked on its own.+ Walked,+ /// An item recorded in a run. Runs are cut along a grid, so an item that knows which row of it it starts in+ /// says so; one that does not stays with the items before it.+ InRun { grid_row: Option<i32> },}+/// A run never holds more items than this, however little room they take.+const MAX_ITEMS_IN_A_RUN: usize = 512;+/// What assembly needs from the recorder, which owns the output and the published recording.pub(crate) trait AssemblyHost {fn plan_scope(&mut self, scope: PaintScope) -> ScopePlan;+ /// Where the plan of a walked scope is cut at `item`.+ fn cut_at(&mut self, scope: PaintScope, item: PaintOrderItem) -> ItemCut;+/// Records one producer of `owner` under the contexts it needs.fn record_producer(&mut self, owner: NodeSlotId, kind: ProducerKind) -> ProducerOutcome;- fn output_position(&self) -> OutputPosition;-- /// Appends the published recording's command bytes in the given range.- fn copy_published(&mut self, bytes: Range<u32>, blocking_wheel_event_regions: u32);+ /// Takes what was recorded since the last run ended out as the chunk of the run that recorded it, or none where+ /// nothing was.+ fn take_run_chunk(&mut self) -> Option<Arc<RecordedChunk>>;- /// Every damaged row, including the rows of subtrees whose root moved.- fn damaged_rows(&mut self) -> Vec<NodeSlotId>;+ /// The damage pushed for a row since the published recording, with the hint that something below it was+ /// damaged.+ fn damage_of_row(&mut self, row: NodeSlotId) -> PaintDamage;- /// The damage of a row with a moved ancestor's subtree expansion folded in.- fn effective_damage(&mut self, row: NodeSlotId) -> PaintDamage;+ /// Where a row's boxes are. A row an ancestor moved records again though nothing was pushed for it.+ fn placement_of_row(&mut self, row: NodeSlotId) -> RowPlacement;fn producer_reads_descendants(&mut self, owner: NodeSlotId, kind: ProducerKind) -> bool;fn observe(&mut self, _event: AssemblyEvent) {}}-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-struct SourceCursor {- bytes: u32,-}--impl SourceCursor {- fn advance(&mut self, output: OutputSize) {- self.bytes += output.bytes;- }+#[derive(PartialEq, Eq, Hash)]+enum SegmentKey {+ RunStartingAt(PaintOrderItem),+ Walked(PaintScope),}-// Consecutive clean children are copied with one range append.-#[derive(Clone, Copy)]-struct PendingCopy {- start: SourceCursor,- end: SourceCursor,- blocking_wheel_event_regions: u32,+/// Whether the published recording can be returned as it is: nothing was pushed, and nothing in it is recorded every+/// frame or read a window focus that changed.+pub(crate) fn frame_is_unchanged(published_root: &RecordedScope, has_damage: bool, window_focus_changed: bool) -> bool {+ let facts = published_root.facts;+ !has_damage && !facts.live && !(window_focus_changed && facts.reads_window_focus)}-/// Whether the published recording can be returned as it is: nothing was pushed, nothing in it is-/// recorded every frame or read a window focus that changed, and there is a published tree at all.-pub(crate) fn frame_is_unchanged(tree: &PaintOrderTree, has_damage: bool, window_focus_changed: bool) -> bool {- let root = tree.root_entry();- !tree.root().is_none() && !has_damage && !root.is_live() && !(window_focus_changed && root.reads_window_focus())+// The damage of a scope's owner that cannot change what the scope records. The scope of a box's backgrounds and+// borders holds none of the foreground, outline and overlay producers of the box, and none of its SVG content.+fn owner_damage_that_misses(kind: PaintScopeKind) -> PaintDamage {+ match kind {+ PaintScopeKind::Descendants(StackingContextPaintPhase::BackgroundAndBorders) => {+ PaintDamage::DRAW_FOREGROUND | PaintDamage::DRAW_OUTLINE | PaintDamage::DRAW_OVERLAY | PaintDamage::SVG+ }+ _ => PaintDamage::NONE,+ }}pub(crate) struct Assembler<'a, H: AssemblyHost> {host: &'a mut H,- // A frame that publishes nothing still marks damaged paths, but the tree's structure keeps- // describing the published recording.- tree: PaintOrderTreeAccess<'a>,- marks: &'a mut ScopeMarks,- // The byte offset of the published root scope, when a published recording can be copied from.- source_prologue_bytes: Option<u32>,// The published recording was made in the other window focus state.window_focus_changed: bool,- pending_copy: Option<PendingCopy>,}impl<'a, H: AssemblyHost> Assembler<'a, H> {- pub(crate) fn new(- host: &'a mut H,- tree: PaintOrderTreeAccess<'a>,- marks: &'a mut ScopeMarks,- source_prologue_bytes: Option<u32>,- window_focus_changed: bool,- ) -> Self {+ pub(crate) fn new(host: &'a mut H, window_focus_changed: bool) -> Self {Self {host,- tree,- marks,- source_prologue_bytes,window_focus_changed,- pending_copy: None,}}- // Copying an entry would keep output that is recorded every frame, or that read the window- // focus before it changed.- fn records_again(&self, entry: &ChildEntry) -> bool {- entry.is_live() || (self.window_focus_changed && entry.reads_window_focus())+ // Reusing a part would keep output that is recorded every frame, or that read the window focus before it+ // changed.+ fn records_again(&self, facts: OutputFacts) -> bool {+ facts.live || (self.window_focus_changed && facts.reads_window_focus)+ }++ /// Records the frame's root scope. `published_root` is the root the published recording walked, when that+ /// recording can be reused from.+ pub(crate) fn assemble_root(+ mut self,+ root_scope: PaintScope,+ published_root: Option<&Arc<RecordedScope>>,+ ) -> Arc<RecordedScope> {+ let published = published_root.filter(|root| root.scope == root_scope);+ self.walk_scope(root_scope, published)+ }++ fn scope_is_clean(&mut self, scope: PaintScope, recorded_placement: RowPlacement) -> bool {+ self.host+ .damage_of_row(scope.owner)+ .without(owner_damage_that_misses(scope.kind))+ .is_empty()+ && self.host.placement_of_row(scope.owner) == recorded_placement}- /// Records the frame's root scope after the prologue and returns its output. A frame that- /// rewrites the tree leaves the assembled structure there as pending changes for the caller- /// to publish or discard.- pub(crate) fn assemble_root(mut self, root_scope: PaintScope) -> OutputSize {- self.marks.begin_recording();- // Damage only steers what a frame copies; a frame without a published recording to copy- // from records everything and never consults it.- if self.source_prologue_bytes.is_some() {- for row in self.host.damaged_rows() {- let tree = self.tree.read();- for scope in tree.scopes_owned_by(row) {- tree.mark_path_to_root_damaged(scope, self.marks);+ fn producer_is_damaged(&mut self, owner: NodeSlotId, kind: ProducerKind, damage: PaintDamage) -> bool {+ damage.intersects(kind.damage() | PaintDamage::MOVED)+ || (damage.contains(PaintDamage::DESCENDANT_READERS) && self.host.producer_reads_descendants(owner, kind))+ }++ fn plan_and_cut(&mut self, scope: PaintScope) -> SegmentedPlan {+ let plan = self.host.plan_scope(scope);+ self.cut(scope, plan.active, plan.items.into_vec().into())+ }++ fn cut(&mut self, scope: PaintScope, active: bool, items: Arc<[PaintOrderItem]>) -> SegmentedPlan {+ let mut segments = Vec::new();+ let mut run_start = 0;+ let mut grid_row_of_run = None;+ for (index, item) in items.iter().enumerate() {+ let cut = self.host.cut_at(scope, *item);+ let starts_another_run = match cut {+ ItemCut::Walked => true,+ ItemCut::InRun { grid_row } => {+ let leaves_grid_row =+ grid_row.is_some() && grid_row_of_run.is_some() && grid_row != grid_row_of_run;+ leaves_grid_row || index - run_start == MAX_ITEMS_IN_A_RUN}- }- }- let published_root = self.tree.read().root();- let output = match self.source_prologue_bytes {- Some(prologue_bytes)- if !published_root.is_none() && self.tree.read().scope_of(published_root) == root_scope =>- {- let cursor = SourceCursor { bytes: prologue_bytes };- let entry = self.assemble_scope(published_root, cursor);- self.flush_pending_copy();- if let Some(tree) = self.tree.rewrites() {- tree.finish_recording(published_root, entry);+ };+ if starts_another_run {+ if run_start < index {+ segments.push(Segment::Run(run_start as u32..index as u32));}- entry.output()+ run_start = index;+ grid_row_of_run = None;}- _ if self.tree.is_rewriting() => {- let tree = self.rewritten_tree();- if !published_root.is_none() {- tree.detach_scope(published_root);+ match cut {+ ItemCut::Walked => {+ segments.push(Segment::Walked(index as u32));+ run_start = index + 1;}- let root = tree.allocate_scope(root_scope, ScopeId::NONE);- let entry = self.record_scope_fresh(root);- self.rewritten_tree().finish_recording(root, entry);- entry.output()+ ItemCut::InRun { grid_row } => grid_row_of_run = grid_row_of_run.or(grid_row),}- _ => self.record_scope_outside_tree(root_scope),- };- debug_assert!(self.pending_copy.is_none());- output- }-- fn rewritten_tree(&mut self) -> &mut PaintOrderTree {- self.tree- .rewrites()- .expect("only a frame that rewrites the tree records into it")+ }+ if run_start < items.len() {+ segments.push(Segment::Run(run_start as u32..items.len() as u32));+ }+ SegmentedPlan {+ active,+ items,+ segments,+ }}- fn assemble_scope(&mut self, id: ScopeId, cursor: SourceCursor) -> ChildEntry {- let scope = self.tree.read().scope_of(id);- let damage = self.host.effective_damage(scope.owner);+ /// Walks the plan of `scope`, which damage reaches or the published recording did not walk.+ fn walk_scope(&mut self, scope: PaintScope, published: Option<&Arc<RecordedScope>>) -> Arc<RecordedScope> {+ let owner_damage = self.host.damage_of_row(scope.owner);+ let owner_placement = self.host.placement_of_row(scope.owner);let order_damage = match scope.kind {PaintScopeKind::PaintedAsStackingContext => {PaintDamage::ORDER | PaintDamage::CONTEXT_ORDER | PaintDamage::ELIGIBILITY}PaintScopeKind::Descendants(_) => PaintDamage::ORDER,};- if damage.intersects(order_damage) {- return self.rebuild_scope(id, cursor, damage);- }- self.host- .observe(AssemblyEvent::ScopeBegin(scope, ScopeAction::Assembled));- let published: SmallVec<[ChildEntry; 16]> = self.tree.read().children(id).iter().copied().collect();- let mut entries: SmallVec<[ChildEntry; 16]> = SmallVec::with_capacity(published.len());- let mut total = OutputSize::default();- let mut child_cursor = cursor;- for entry in published {- let published_output = entry.output();- let assembled = match entry.key() {- ChildKey::Scope(child) => {- if self.marks.is_on_damaged_path(child) || self.records_again(&entry) {- self.assemble_scope(child, child_cursor)- } else {- self.copy(child_cursor, published_output);- let child_scope = self.tree.read().scope_of(child);- self.host.observe(AssemblyEvent::ScopeCopied(child_scope));- entry- }- }- ChildKey::Producer(kind) => {- if self.producer_is_damaged(scope.owner, kind, damage, &entry) {- self.record_producer(scope.owner, kind)- } else {- self.copy(child_cursor, published_output);- self.host.observe(AssemblyEvent::ProducerCopied(scope.owner, kind));- entry+ let owner_moved = published.is_some_and(|published| published.owner_placement != owner_placement);+ let published_plan = published+ .filter(|_| !owner_damage.intersects(order_damage))+ .map(|published| &published.plan);+ let items_were_kept = published_plan.is_some();+ // Nothing was pushed for the owner or anything below it, and nothing moved it: every item is where it was.+ let cuts_were_kept = items_were_kept && owner_damage.is_empty() && !owner_moved;+ let plan = match published_plan {+ Some(published_plan) if cuts_were_kept => Arc::clone(published_plan),+ Some(published_plan) => Arc::new(self.cut(scope, published_plan.active, Arc::clone(&published_plan.items))),+ None => Arc::new(self.plan_and_cut(scope)),+ };+ let action = match (published.is_some(), items_were_kept, plan.active) {+ (_, _, false) => ScopeAction::Inactive,+ (true, true, true) => ScopeAction::Assembled,+ (true, false, true) => ScopeAction::Replanned,+ (false, _, true) => ScopeAction::Recorded,+ };+ self.host.observe(AssemblyEvent::ScopeBegin(scope, action));+ let mut recorded = RecordedScope {+ scope,+ plan: Arc::clone(&plan),+ segments: Vec::with_capacity(plan.segments.len()),+ facts: OutputFacts::default(),+ owner_placement,+ };+ if plan.active {+ let published_segments = published.map(|published| PublishedSegments::new(published, cuts_were_kept));+ for (index, segment) in plan.segments.iter().enumerate() {+ let published_segment = published_segments+ .as_ref()+ .and_then(|segments| segments.matching(index, segment, &plan));+ let assembled = match segment {+ Segment::Run(run) => RecordedSegment::Run(self.assemble_run(+ scope,+ plan.items_of(run),+ published_segment,+ owner_damage,+ owner_moved,+ )),+ Segment::Walked(item) => {+ RecordedSegment::Walked(self.assemble_walked_child(plan.walked_scope(*item), published_segment))}- }- };- child_cursor.advance(published_output);- total.add(assembled.output());- entries.push(assembled);- }- if let Some(tree) = self.tree.rewrites() {- tree.set_children(id, &entries);+ };+ recorded.facts.add(assembled.facts());+ recorded.segments.push(assembled);+ }}self.host.observe(AssemblyEvent::ScopeEnd(scope));- ChildEntry::scope(id, total)+ Arc::new(recorded)}- fn producer_is_damaged(- &mut self,- owner: NodeSlotId,- kind: ProducerKind,- damage: PaintDamage,- entry: &ChildEntry,- ) -> bool {- damage.intersects(kind.damage())- || self.records_again(entry)- || (damage.contains(PaintDamage::DESCENDANT_READERS) && self.host.producer_reads_descendants(owner, kind))+ fn assemble_walked_child(&mut self, child: PaintScope, published: Option<&RecordedSegment>) -> Arc<RecordedScope> {+ let published = published.and_then(|segment| match segment {+ RecordedSegment::Walked(scope) => Some(scope),+ RecordedSegment::Run(_) => None,+ });+ if let Some(published) = published+ && !self.records_again(published.facts)+ && self.scope_is_clean(child, published.owner_placement)+ {+ self.host.observe(AssemblyEvent::ScopeCopied(child));+ return Arc::clone(published);+ }+ self.walk_scope(child, published)}- // The plan is rebuilt; published children it still lists are copied or walked from their- // old positions, the rest are recorded, and published children it no longer lists retire.- fn rebuild_scope(&mut self, id: ScopeId, cursor: SourceCursor, damage: PaintDamage) -> ChildEntry {- let scope = self.tree.read().scope_of(id);- let plan = self.host.plan_scope(scope);- let published: SmallVec<[ChildEntry; 16]> = self.tree.read().children(id).iter().copied().collect();- let mut published_cursors: SmallVec<[SourceCursor; 16]> = SmallVec::with_capacity(published.len());- let mut child_cursor = cursor;- for entry in &published {- published_cursors.push(child_cursor);- child_cursor.advance(entry.output());- }- let mut matched: SmallVec<[bool; 16]> = SmallVec::from_elem(false, published.len());- // A stacking context with thousands of hoisted children is replanned when one of them- // appears or disappears; matching by key must not scan the list per item.- let published_index_by_key: Option<FastMap<ChildKey, usize>> = (published.len() > 16).then(|| {- published- .iter()- .enumerate()- .map(|(index, entry)| (entry.key(), index))- .collect()+ fn assemble_run(+ &mut self,+ scope: PaintScope,+ items: &[PaintOrderItem],+ published: Option<&RecordedSegment>,+ owner_damage: PaintDamage,+ owner_moved: bool,+ ) -> RecordedRun {+ let published = published.and_then(|segment| match segment {+ RecordedSegment::Run(run) => Some(run),+ RecordedSegment::Walked(_) => None,});- let published_index_of = |key: ChildKey| match &published_index_by_key {- Some(index_by_key) => index_by_key.get(&key).copied(),- None => published.iter().position(|entry| entry.key() == key),- };- if !plan.active {- self.host- .observe(AssemblyEvent::ScopeBegin(scope, ScopeAction::Inactive));- self.install_replanned_children(id, &published, &matched, &[]);- self.host.observe(AssemblyEvent::ScopeEnd(scope));- return ChildEntry::scope(id, OutputSize::default());+ // Only a chunk without placeholders for SVG images can be drawn by another recording than the one that made+ // it, which the publication of a recording finishes every chunk of.+ if let Some(run) = published+ && !owner_moved+ && !self.records_again(run.facts)+ && run.chunk.as_ref().is_none_or(|chunk| chunk.finished().is_some())+ && self.run_is_clean(scope, items, run, owner_damage)+ {+ for item in items {+ match *item {+ PaintOrderItem::Producer(producer) => {+ for kind in producer_kinds(producer) {+ self.host.observe(AssemblyEvent::ProducerCopied(scope.owner, kind));+ }+ }+ PaintOrderItem::Scope(child) => self.host.observe(AssemblyEvent::ScopeCopied(child)),+ }+ }+ return RecordedRun {+ chunk: run.chunk.clone(),+ facts: run.facts,+ child_scope_placements: run.child_scope_placements.clone(),+ };}- self.host- .observe(AssemblyEvent::ScopeBegin(scope, ScopeAction::Replanned));- let mut entries: SmallVec<[ChildEntry; 16]> = SmallVec::with_capacity(plan.items.len());- let mut total = OutputSize::default();- for item in plan.items {- match item {+ let mut facts = OutputFacts::default();+ let mut child_scope_placements = Vec::new();+ for item in items {+ match *item {PaintOrderItem::Producer(producer) => {for kind in producer_kinds(producer) {- let assembled = match published_index_of(ChildKey::Producer(kind)) {- Some(index) if !self.producer_is_damaged(scope.owner, kind, damage, &published[index]) => {- matched[index] = true;- self.copy(published_cursors[index], published[index].output());- self.host.observe(AssemblyEvent::ProducerCopied(scope.owner, kind));- published[index]- }- Some(index) => {- matched[index] = true;- self.record_producer(scope.owner, kind)- }- None => self.record_producer(scope.owner, kind),- };- total.add(assembled.output());- entries.push(assembled);+ facts.add(self.host.record_producer(scope.owner, kind).facts());}}- PaintOrderItem::Scope(child_scope) => {- let found = self- .tree- .read()- .published_scope(child_scope, id)- .and_then(|child| published_index_of(ChildKey::Scope(child)).map(|index| (child, index)));- let assembled = match found {- Some((child, index)) => {- matched[index] = true;- if self.marks.is_on_damaged_path(child) || self.records_again(&published[index]) {- self.assemble_scope(child, published_cursors[index])- } else {- self.copy(published_cursors[index], published[index].output());- self.host.observe(AssemblyEvent::ScopeCopied(child_scope));- published[index]- }- }- None if self.tree.is_rewriting() => {- let child = self.rewritten_tree().allocate_scope(child_scope, id);- self.record_scope_fresh(child)- }- None => {- total.add(self.record_scope_outside_tree(child_scope));- continue;- }- };- total.add(assembled.output());- entries.push(assembled);+ PaintOrderItem::Scope(child) => {+ child_scope_placements.push(self.host.placement_of_row(child.owner));+ facts.add(self.record_whole_scope(child));}}}- self.install_replanned_children(id, &published, &matched, &entries);- self.host.observe(AssemblyEvent::ScopeEnd(scope));- ChildEntry::scope(id, total)- }-- fn install_replanned_children(- &mut self,- id: ScopeId,- published: &[ChildEntry],- matched: &[bool],- entries: &[ChildEntry],- ) {- let Some(tree) = self.tree.rewrites() else {- return;- };- for (entry, matched) in published.iter().zip(matched) {- if let (ChildKey::Scope(child), false) = (entry.key(), *matched) {- tree.detach_scope(child);- }+ RecordedRun {+ chunk: self.host.take_run_chunk(),+ facts,+ child_scope_placements: child_scope_placements.into_boxed_slice(),}- tree.set_children(id, entries);}- fn record_scope_fresh(&mut self, id: ScopeId) -> ChildEntry {- let scope = self.rewritten_tree().scope_of(id);- let plan = self.host.plan_scope(scope);- if !plan.active {- self.host- .observe(AssemblyEvent::ScopeBegin(scope, ScopeAction::Inactive));- self.rewritten_tree().set_children(id, &[]);- self.host.observe(AssemblyEvent::ScopeEnd(scope));- return ChildEntry::scope(id, OutputSize::default());- }- self.host- .observe(AssemblyEvent::ScopeBegin(scope, ScopeAction::Recorded));- let mut entries: SmallVec<[ChildEntry; 16]> = SmallVec::with_capacity(plan.items.len());- let mut total = OutputSize::default();- for item in plan.items {- match item {- PaintOrderItem::Producer(producer) => {- for kind in producer_kinds(producer) {- let recorded = self.record_producer(scope.owner, kind);- total.add(recorded.output());- entries.push(recorded);- }- }- PaintOrderItem::Scope(child_scope) => {- let child = self.rewritten_tree().allocate_scope(child_scope, id);- let recorded = self.record_scope_fresh(child);- total.add(recorded.output());- entries.push(recorded);- }+ fn run_is_clean(+ &mut self,+ scope: PaintScope,+ items: &[PaintOrderItem],+ published: &RecordedRun,+ owner_damage: PaintDamage,+ ) -> bool {+ let mut child_scope_placements = published.child_scope_placements.iter();+ items.iter().all(|item| match *item {+ PaintOrderItem::Producer(producer) => !producer_kinds(producer)+ .into_iter()+ .any(|kind| self.producer_is_damaged(scope.owner, kind, owner_damage)),+ PaintOrderItem::Scope(child) => {+ let recorded_placement = child_scope_placements+ .next()+ .expect("a run keeps the origin of each of its child scopes");+ self.scope_is_clean(child, *recorded_placement)}- }- self.rewritten_tree().set_children(id, &entries);- self.host.observe(AssemblyEvent::ScopeEnd(scope));- ChildEntry::scope(id, total)+ })}- fn record_scope_outside_tree(&mut self, scope: PaintScope) -> OutputSize {+ /// Records a scope with everything below it, as part of a run.+ fn record_whole_scope(&mut self, scope: PaintScope) -> OutputFacts {let plan = self.host.plan_scope(scope);- let mut total = OutputSize::default();+ let mut total = OutputFacts::default();if !plan.active {self.host.observe(AssemblyEvent::ScopeBegin(scope, ScopeAction::Inactive));@@ -449,71 +416,75 @@ impl<'a, H: AssemblyHost> Assembler<'a, H> {match item {PaintOrderItem::Producer(producer) => {for kind in producer_kinds(producer) {- total.add(self.record_producer(scope.owner, kind).output());+ total.add(self.host.record_producer(scope.owner, kind).facts());}}- PaintOrderItem::Scope(child_scope) => total.add(self.record_scope_outside_tree(child_scope)),+ PaintOrderItem::Scope(child_scope) => total.add(self.record_whole_scope(child_scope)),}}self.host.observe(AssemblyEvent::ScopeEnd(scope));total}+}- fn record_producer(&mut self, owner: NodeSlotId, kind: ProducerKind) -> ChildEntry {- self.flush_pending_copy();- let before = self.host.output_position();- let outcome = self.host.record_producer(owner, kind);- let after = self.host.output_position();- let output = OutputSize {- bytes: after.bytes - before.bytes,- blocking_wheel_event_regions: after.blocking_wheel_event_regions - before.blocking_wheel_event_regions,- live: outcome.live,- reads_window_focus: outcome.reads_window_focus,- };- ChildEntry::producer(kind, output)+/// The segments a walked scope had in the published recording. A plan whose cuts were kept has the same segments as+/// then. One that was cut again is matched by what its segments begin with: a run is the published one when it lists+/// the same items from the same first item.+struct PublishedSegments<'a> {+ published: &'a RecordedScope,+ index_by_key: Option<FastMap<SegmentKey, usize>>,+}++impl<'a> PublishedSegments<'a> {+ fn new(published: &'a RecordedScope, cuts_were_kept: bool) -> Self {+ let index_by_key = (!cuts_were_kept).then(|| {+ published+ .plan+ .segments+ .iter()+ .enumerate()+ .map(|(index, segment)| (Self::key(&published.plan, segment), index))+ .collect()+ });+ Self {+ published,+ index_by_key,+ }}- fn copy(&mut self, cursor: SourceCursor, output: OutputSize) {- debug_assert!(- self.source_prologue_bytes.is_some(),- "clean output is copied from a published recording"- );- let mut end = cursor;- end.advance(output);- match &mut self.pending_copy {- Some(pending) if pending.end == cursor => {- pending.end = end;- pending.blocking_wheel_event_regions += output.blocking_wheel_event_regions;- }- _ => {- self.flush_pending_copy();- self.pending_copy = Some(PendingCopy {- start: cursor,- end,- blocking_wheel_event_regions: output.blocking_wheel_event_regions,- });- }+ fn key(plan: &SegmentedPlan, segment: &Segment) -> SegmentKey {+ match segment {+ Segment::Run(run) => SegmentKey::RunStartingAt(plan.items[run.start as usize]),+ Segment::Walked(item) => SegmentKey::Walked(plan.walked_scope(*item)),}}- fn flush_pending_copy(&mut self) {- let Some(pending) = self.pending_copy.take() else {- return;+ fn matching(&self, index: usize, segment: &Segment, plan: &SegmentedPlan) -> Option<&'a RecordedSegment> {+ let published = self.published;+ let published_index = match &self.index_by_key {+ None => index,+ Some(index_by_key) => {+ let published_index = *index_by_key.get(&Self::key(plan, segment))?;+ if let (Segment::Run(run), Segment::Run(published_run)) =+ (segment, &published.plan.segments[published_index])+ && plan.items_of(run) != published.plan.items_of(published_run)+ {+ return None;+ }+ published_index+ }};- self.host.copy_published(- pending.start.bytes..pending.end.bytes,- pending.blocking_wheel_event_regions,- );+ published.segments.get(published_index)}}#[cfg(test)]mod tests {use super::*;+ use crate::css::css_pixels::{CssPixelPoint, CssPixels};use crate::painting::display_list::builder::RecordedDisplayList;use crate::painting::display_list::recorder::DisplayListRecorder;use crate::painting::force_dark::ForceDarkRole;- use crate::painting::paint_order_plan::StackingContextPaintPhase;use libgfx_rust::{Color, IntRect};use std::collections::{HashMap, HashSet};@@ -521,10 +492,26 @@ mod tests {NodeSlotId::new(index, 1)}+ // Tells the output of one producer kind from another's.+ fn code_of(kind: ProducerKind) -> u8 {+ match kind {+ ProducerKind::DrawBackground => 0,+ ProducerKind::DrawForeground => 1,+ _ => 2,+ }+ }+fn context(owner: NodeSlotId) -> PaintScope {PaintScope::stacking_context(owner)}+ fn backgrounds(owner: NodeSlotId) -> PaintScope {+ PaintScope {+ owner,+ kind: PaintScopeKind::Descendants(StackingContextPaintPhase::BackgroundAndBorders),+ }+ }+fn foreground(owner: NodeSlotId) -> PaintScope {PaintScope {owner,@@ -536,10 +523,6 @@ mod tests {PaintOrderItem::Producer(PaintProducer::BoxPhase(phase))}- fn svg() -> PaintOrderItem {- PaintOrderItem::Producer(PaintProducer::SvgBoxForeground)- }-fn child(scope: PaintScope) -> PaintOrderItem {PaintOrderItem::Scope(scope)}@@ -549,6 +532,7 @@ mod tests {rects: u32,version: u8,live: bool,+ reads_window_focus: bool,blocking: u32,}@@ -557,37 +541,31 @@ mod tests {rects,version: 1,live: false,+ reads_window_focus: false,blocking: 0,}}struct Frame {display_list: RecordedDisplayList,- prologue_bytes: u32,- root_output: OutputSize,+ root: Arc<RecordedScope>,}- struct Output {- recorder: DisplayListRecorder,- blocking_wheel_event_region_count: u32,- }-- fn new_output() -> Output {- Output {- recorder: DisplayListRecorder::new(None),- blocking_wheel_event_region_count: 0,- }+ fn new_output() -> DisplayListRecorder {+ DisplayListRecorder::new(None)}struct TestHost {plans: HashMap<PaintScope, ScopePlan>,contents: HashMap<(NodeSlotId, ProducerKind), Content>,damage: HashMap<NodeSlotId, PaintDamage>,- moved_subtrees: HashSet<NodeSlotId>,+ origins: HashMap<NodeSlotId, i64>,+ walked: HashSet<PaintScope>,+ grid_rows: HashMap<NodeSlotId, i32>,descendant_readers: HashSet<(NodeSlotId, ProducerKind)>,recorded: Vec<(NodeSlotId, ProducerKind)>,events: Vec<AssemblyEvent>,- output: Output,+ output: DisplayListRecorder,source: Option<Frame>,}@@ -597,7 +575,9 @@ mod tests {plans: HashMap::new(),contents: HashMap::new(),damage: HashMap::new(),- moved_subtrees: HashSet::new(),+ origins: HashMap::new(),+ walked: HashSet::new(),+ grid_rows: HashMap::new(),descendant_readers: HashSet::new(),recorded: Vec::new(),events: Vec::new(),@@ -626,11 +606,27 @@ mod tests {*self.damage.entry(owner).or_default() |= damage;}- fn clear_damage(&mut self) {- self.damage.clear();- self.moved_subtrees.clear();- self.recorded.clear();- self.events.clear();+ fn recorded_rows(&self) -> Vec<u32> {+ let mut rows: Vec<u32> = self.recorded.iter().map(|(owner, _)| owner.slot_index()).collect();+ rows.dedup();+ rows+ }++ fn copied_scopes(&self) -> Vec<PaintScope> {+ self.events+ .iter()+ .filter_map(|event| match event {+ AssemblyEvent::ScopeCopied(scope) => Some(*scope),+ _ => None,+ })+ .collect()+ }++ fn action_of(&self, scope: PaintScope) -> Option<ScopeAction> {+ self.events.iter().find_map(|event| match event {+ AssemblyEvent::ScopeBegin(begun, action) if *begun == scope => Some(*action),+ _ => None,+ })}}@@ -639,58 +635,58 @@ mod tests {self.plans.get(&scope).cloned().unwrap_or_default()}+ fn cut_at(&mut self, _scope: PaintScope, item: PaintOrderItem) -> ItemCut {+ match item {+ PaintOrderItem::Scope(child) if self.walked.contains(&child) => ItemCut::Walked,+ PaintOrderItem::Scope(child) => ItemCut::InRun {+ grid_row: self.grid_rows.get(&child.owner).copied(),+ },+ PaintOrderItem::Producer(_) => ItemCut::InRun { grid_row: None },+ }+ }+fn record_producer(&mut self, owner: NodeSlotId, kind: ProducerKind) -> ProducerOutcome {let Some(content) = self.contents.get(&(owner, kind)).copied() else {return ProducerOutcome::default();};self.recorded.push((owner, kind));- let output = &mut self.output;+ let origin = self.origins.get(&owner).copied().unwrap_or_default() as i32;for index in 0..content.rects {- output.recorder.fill_rect(+ self.output.fill_rect(IntRect {- x: owner.slot_index() as i32,- y: kind.code() as i32 * 100 + index as i32,+ x: owner.slot_index() as i32 + origin,+ y: i32::from(code_of(kind)) * 100 + index as i32,width: 10,height: i32::from(content.version),},- Color::from_rgb(content.version, kind.code() as u8, 7),+ Color::from_rgb(content.version, code_of(kind), 7),ForceDarkRole::Background,);}- output.blocking_wheel_event_region_count += content.blocking;ProducerOutcome {live: content.live,- ..Default::default()+ reads_window_focus: content.reads_window_focus,+ blocking_wheel_event_regions: content.blocking,}}- fn output_position(&self) -> OutputPosition {- OutputPosition {- bytes: self.output.recorder.byte_size() as u32,- blocking_wheel_event_regions: self.output.blocking_wheel_event_region_count,- }+ fn take_run_chunk(&mut self) -> Option<Arc<RecordedChunk>> {+ let chunk = self.output.take_chunk();+ (!chunk.records.is_empty()).then(|| RecordedChunk::new(chunk, false))}- fn copy_published(&mut self, bytes: Range<u32>, blocking_wheel_event_regions: u32) {- let source = self.source.as_ref().expect("a published recording to copy from");- self.output.recorder.append_cached_commands(&source.display_list, bytes);- self.output.blocking_wheel_event_region_count += blocking_wheel_event_regions;+ fn damage_of_row(&mut self, row: NodeSlotId) -> PaintDamage {+ self.damage.get(&row).copied().unwrap_or_default()}- fn damaged_rows(&mut self) -> Vec<NodeSlotId> {- let mut rows: Vec<NodeSlotId> = self.damage.keys().copied().collect();- rows.extend(self.moved_subtrees.iter().copied());- rows.sort_unstable_by_key(|row| row.slot_index());- rows.dedup();- rows- }-- fn effective_damage(&mut self, row: NodeSlotId) -> PaintDamage {- let mut damage = self.damage.get(&row).copied().unwrap_or_default();- if self.moved_subtrees.contains(&row) {- damage |= PaintDamage::ALL_PRODUCERS | PaintDamage::MOVED;+ fn placement_of_row(&mut self, row: NodeSlotId) -> RowPlacement {+ RowPlacement {+ origin: CssPixelPoint::new(+ CssPixels::from_integer(self.origins.get(&row).copied().unwrap_or_default()),+ CssPixels::default(),+ ),+ later_fragments: 0,}- damage}fn producer_reads_descendants(&mut self, owner: NodeSlotId, kind: ProducerKind) -> bool {@@ -702,15 +698,12 @@ mod tests {}}- // Records the canvas prologue and assembles the viewport context from the host's source- // frame.- fn record_frame(host: &mut TestHost, tree: &mut PaintOrderTree) -> Frame {- record_frame_rewriting_tree(host, tree, true)- }-- fn record_frame_rewriting_tree(host: &mut TestHost, tree: &mut PaintOrderTree, rewrites_tree: bool) -> Frame {+ // Records the canvas prologue and assembles the viewport context from the host's source frame.+ fn record_frame_with_focus_change(host: &mut TestHost, window_focus_changed: bool) -> Frame {host.output = new_output();- host.output.recorder.fill_rect(+ host.recorded.clear();+ host.events.clear();+ host.output.fill_rect(IntRect {x: 0,y: 0,@@ -720,41 +713,32 @@ mod tests {Color::from_rgb(255, 255, 255),ForceDarkRole::Background,);- let prologue_bytes = host.output.recorder.byte_size() as u32;- let source_prologue_bytes = host.source.as_ref().map(|frame| frame.prologue_bytes);- let mut marks = ScopeMarks::default();- let access = match rewrites_tree {- true => PaintOrderTreeAccess::Rewrites(tree),- false => PaintOrderTreeAccess::Reads(tree),- };- let root_output =- Assembler::new(host, access, &mut marks, source_prologue_bytes, false).assemble_root(context(row(0)));- let output = std::mem::replace(&mut host.output, new_output());+ let prologue = host.output.take_chunk();+ let published = host.source.as_ref().map(|frame| Arc::clone(&frame.root));+ let root = Assembler::new(host, window_focus_changed).assemble_root(context(row(0)), published.as_ref());+ let mut chunks = vec![Arc::new(prologue)];+ root.for_each_chunk(&mut |chunk| chunks.push(Arc::clone(chunk.latest())));Frame {- display_list: output.recorder.into_builder().finish(),- prologue_bytes,- root_output,+ display_list: RecordedDisplayList::of_chunks(chunks.iter().map(|chunk| &**chunk)),+ root,}}- // Assembles the next frame from the source frame and keeps it as the source in turn.- fn record_next_frame(host: &mut TestHost, tree: &mut PaintOrderTree) -> Frame {- let frame = record_frame(host, tree);- let previous = host.source.replace(Frame {- display_list: frame.display_list.clone(),- prologue_bytes: frame.prologue_bytes,- root_output: frame.root_output,- });- assert!(previous.is_some(), "a next frame copies from a first frame");- frame+ fn record_frame(host: &mut TestHost) -> Frame {+ record_frame_with_focus_change(host, false)+ }++ // Publishes `frame`: the next frame copies from it, and the damage it painted is consumed.+ fn publish(host: &mut TestHost, frame: Frame) {+ host.source = Some(frame);+ host.damage.clear();}fn assert_matches_from_scratch(host: &mut TestHost, assembled: &Frame) {let recorded = std::mem::take(&mut host.recorded);let events = std::mem::take(&mut host.events);let source = host.source.take();- let mut fresh_tree = PaintOrderTree::default();- let fresh = record_frame(host, &mut fresh_tree);+ let fresh = record_frame(host);host.source = source;host.recorded = recorded;host.events = events;@@ -763,34 +747,24 @@ mod tests {"command bytes differ");assert_eq!(assembled.display_list.command_runs, fresh.display_list.command_runs);- assert_eq!(assembled.root_output, fresh.root_output);+ assert_eq!(assembled.display_list.chunks, fresh.display_list.chunks);+ assert_eq!(assembled.root.facts, fresh.root.facts);}- // A viewport context (row 0) with a background and a foreground scope listing three- // card scopes (rows 1..=3) that each draw a background and a foreground.+ // A viewport context (row 0) that draws a background and lists the backgrounds and then the foregrounds of+ // six cards (rows 1..=6), two to a grid row. A card draws a background and a foreground.fn cards_host() -> TestHost {let mut host = TestHost::default();- host.plan(- context(row(0)),- true,- &[phase(PaintPhase::Background), child(foreground(row(0)))],- );+ let cards = 1..=6;+ let mut items = vec![phase(PaintPhase::Background)];+ items.extend(cards.clone().map(|card| child(backgrounds(row(card)))));+ items.extend(cards.clone().map(|card| child(foreground(row(card)))));+ host.plan(context(row(0)), true, &items);host.produce(row(0), ProducerKind::DrawBackground, content(1));- host.plan(- foreground(row(0)),- true,- &[- child(foreground(row(1))),- child(foreground(row(2))),- child(foreground(row(3))),- ],- );- for card in 1..=3 {- host.plan(- foreground(row(card)),- true,- &[phase(PaintPhase::Background), phase(PaintPhase::Foreground)],- );+ for card in cards {+ host.grid_rows.insert(row(card), (card as i32 - 1) / 2);+ host.plan(backgrounds(row(card)), true, &[phase(PaintPhase::Background)]);+ host.plan(foreground(row(card)), true, &[phase(PaintPhase::Foreground)]);host.produce(row(card), ProducerKind::DrawBackground, content(1));host.produce(row(card), ProducerKind::DrawForeground, content(card));}@@ -798,660 +772,200 @@ mod tests {}#[test]- fn a_quiet_frame_is_unchanged_and_a_fresh_frame_records_everything() {+ fn a_plan_is_cut_where_its_items_leave_a_grid_row_and_around_walked_children() {let mut host = cards_host();- let mut tree = PaintOrderTree::default();- assert!(!frame_is_unchanged(&tree, false, false));+ host.walked.insert(foreground(row(4)));- let frame = record_frame(&mut host, &mut tree);+ let frame = record_frame(&mut host);- assert_eq!(host.recorded.len(), 1 + 3 * 2);+ // The background and the backgrounds of the cards of a grid row, three times, and then the foregrounds,+ // where the grid starts over and the walked card stands alone.assert_eq!(- frame.root_output.bytes as usize,- frame.display_list.bytes.len() - frame.prologue_bytes as usize+ frame.root.plan.segments,+ vec![+ Segment::Run(0..3),+ Segment::Run(3..5),+ Segment::Run(5..7),+ Segment::Run(7..9),+ Segment::Run(9..10),+ Segment::Walked(10),+ Segment::Run(11..13),+ ]);- assert!(frame_is_unchanged(&tree, false, false));- assert!(!frame_is_unchanged(&tree, true, false));+ // A chunk for the prologue, one for each of the six runs and one for the run of the walked card.+ assert_eq!(frame.display_list.chunks.len(), 1 + 6 + 1);+ assert!(frame_is_unchanged(&frame.root, false, false));+ assert!(!frame_is_unchanged(&frame.root, true, false));}#[test]- fn one_damaged_producer_records_alone_and_the_rest_is_copied_in_two_runs() {- let mut host = cards_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-- host.produce(row(2), ProducerKind::DrawForeground, content(2));- host.contents- .get_mut(&(row(2), ProducerKind::DrawForeground))- .unwrap()- .version = 2;- host.push(row(2), PaintDamage::DRAW_FOREGROUND);- host.push(row(0), PaintDamage::DESCENDANT_READERS);- let second = record_next_frame(&mut host, &mut tree);-- assert_eq!(host.recorded, vec![(row(2), ProducerKind::DrawForeground)]);- let copied_scopes: Vec<AssemblyEvent> = host- .events- .iter()- .copied()- .filter(|event| matches!(event, AssemblyEvent::ScopeCopied(_)))+ fn a_run_never_holds_more_items_than_the_cap() {+ let mut host = TestHost::default();+ let items: Vec<_> = (1..=MAX_ITEMS_IN_A_RUN as u32 + 2)+ .map(|card| child(foreground(row(card)))).collect();- assert_eq!(copied_scopes.len(), 2);- assert_matches_from_scratch(&mut host, &second);- }+ host.plan(context(row(0)), true, &items);- #[test]- fn a_growing_child_shifts_its_later_siblings_without_recording_them() {- let mut host = cards_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();+ let frame = record_frame(&mut host);- host.produce(row(1), ProducerKind::DrawForeground, content(5));- host.push(row(1), PaintDamage::DRAW_FOREGROUND);- host.push(row(0), PaintDamage::DESCENDANT_READERS);- let grown = record_next_frame(&mut host, &mut tree);- assert_eq!(host.recorded, vec![(row(1), ProducerKind::DrawForeground)]);- assert_matches_from_scratch(&mut host, &grown);- host.clear_damage();-- host.produce(row(1), ProducerKind::DrawForeground, content(0));- host.push(row(1), PaintDamage::DRAW_FOREGROUND);- host.push(row(0), PaintDamage::DESCENDANT_READERS);- let shrunk = record_next_frame(&mut host, &mut tree);- assert_eq!(host.recorded, vec![(row(1), ProducerKind::DrawForeground)]);- assert_matches_from_scratch(&mut host, &shrunk);+ let cap = MAX_ITEMS_IN_A_RUN as u32;+ assert_eq!(+ frame.root.plan.segments,+ vec![Segment::Run(0..cap), Segment::Run(cap..cap + 2)]+ );}#[test]- fn a_replanned_parent_copies_kept_children_and_retires_the_removed_one() {+ fn damage_records_the_run_it_reaches_and_the_runs_beside_it_are_copied() {let mut host = cards_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- let removed = tree- .published_scope(- foreground(row(2)),- tree.published_scope(foreground(row(0)), tree.root()).unwrap(),- )- .unwrap();- host.clear_damage();+ let first = record_frame(&mut host);+ publish(&mut host, first);+ host.contents+ .get_mut(&(row(3), ProducerKind::DrawForeground))+ .unwrap()+ .version = 2;+ host.push(row(3), PaintDamage::DRAW_FOREGROUND);+ host.push(row(0), PaintDamage::DESCENDANT_READERS);- host.plan(- foreground(row(0)),- true,- &[child(foreground(row(3))), child(foreground(row(1)))],- );- host.push(row(0), PaintDamage::ORDER | PaintDamage::DESCENDANT_READERS);- let second = record_next_frame(&mut host, &mut tree);+ let frame = record_frame(&mut host);- assert!(host.recorded.is_empty());- assert_matches_from_scratch(&mut host, &second);- let parent = tree.published_scope(foreground(row(0)), tree.root()).unwrap();- assert_eq!(tree.children(parent).len(), 2);- assert_eq!(tree.published_scope(foreground(row(2)), parent), None);- assert_eq!(tree.scope_count(), 4);- assert_ne!(tree.published_scope(foreground(row(3)), parent), Some(removed));+ // Only the foregrounds of the second grid row record again: foreground damage misses the run of the+ // card's background.+ assert_eq!(host.recorded_rows(), vec![3, 4]);+ assert_eq!(host.action_of(context(row(0))), Some(ScopeAction::Assembled));+ assert!(host.copied_scopes().contains(&backgrounds(row(3))));+ assert!(host.copied_scopes().contains(&foreground(row(2))));+ assert!(!host.copied_scopes().contains(&foreground(row(4))));+ assert_matches_from_scratch(&mut host, &frame);}#[test]- fn a_new_child_is_recorded_under_the_replanned_parent() {+ fn a_walked_child_is_copied_whole_until_damage_reaches_below_it() {let mut host = cards_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-- host.plan(- foreground(row(0)),- true,- &[- child(foreground(row(1))),- child(foreground(row(4))),- child(foreground(row(2))),- child(foreground(row(3))),- ],- );+ host.walked.insert(foreground(row(4)));host.plan(foreground(row(4)),true,- &[phase(PaintPhase::Background), phase(PaintPhase::Foreground)],+ &[phase(PaintPhase::Foreground), child(foreground(row(7)))],);- host.produce(row(4), ProducerKind::DrawBackground, content(2));- host.produce(row(4), ProducerKind::DrawForeground, content(1));- host.push(row(4), PaintDamage::ORDER | PaintDamage::ALL_PRODUCERS);- host.push(row(0), PaintDamage::ORDER | PaintDamage::DESCENDANT_READERS);- let second = record_next_frame(&mut host, &mut tree);+ host.plan(foreground(row(7)), true, &[phase(PaintPhase::Foreground)]);+ host.produce(row(7), ProducerKind::DrawForeground, content(2));+ let first = record_frame(&mut host);+ publish(&mut host, first);- assert_eq!(- host.recorded,- vec![- (row(4), ProducerKind::DrawBackground),- (row(4), ProducerKind::DrawForeground)- ]- );+ // Damage beside the walked child leaves it copied as one piece, with the node the published recording+ // kept for it.+ host.push(row(1), PaintDamage::DRAW_FOREGROUND);+ host.push(row(0), PaintDamage::DESCENDANT_READERS);+ let second = record_frame(&mut host);+ assert!(host.copied_scopes().contains(&foreground(row(4))));+ assert_eq!(host.action_of(foreground(row(4))), None);+ let walked_child_of = |frame: &Frame| {+ frame+ .root+ .segments+ .iter()+ .find_map(|segment| match segment {+ RecordedSegment::Walked(scope) => Some(Arc::clone(scope)),+ RecordedSegment::Run(_) => None,+ })+ .unwrap()+ };+ assert!(Arc::ptr_eq(+ &walked_child_of(&second),+ &walked_child_of(host.source.as_ref().unwrap())+ ));assert_matches_from_scratch(&mut host, &second);- assert_eq!(tree.scope_count(), 6);- }+ publish(&mut host, second);- #[test]- fn a_frame_that_publishes_nothing_copies_clean_output_and_leaves_the_tree_as_published() {- let mut host = cards_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();- let published_structure = tree.structure();- let published_root_entry = tree.root_entry();-- host.produce(row(2), ProducerKind::DrawForeground, content(3));- host.push(row(2), PaintDamage::DRAW_FOREGROUND);- let unpublished = record_frame_rewriting_tree(&mut host, &mut tree, false);-- assert_eq!(host.recorded, vec![(row(2), ProducerKind::DrawForeground)]);- assert_matches_from_scratch(&mut host, &unpublished);- assert_eq!(tree.structure(), published_structure);- assert_eq!(tree.root_entry(), published_root_entry);-- // The damage it read is still pending for the frame that publishes next.- host.recorded.clear();- let published = record_next_frame(&mut host, &mut tree);- assert_eq!(host.recorded, vec![(row(2), ProducerKind::DrawForeground)]);- assert_matches_from_scratch(&mut host, &published);- assert_eq!(published.display_list.bytes, unpublished.display_list.bytes);+ // Damage below it has it walked, and the run the damage reaches recorded. The hint that something below the+ // card was damaged does not say in which of its scopes, so the run with the card's backgrounds records too.+ host.contents+ .get_mut(&(row(7), ProducerKind::DrawForeground))+ .unwrap()+ .version = 2;+ host.push(row(7), PaintDamage::DRAW_FOREGROUND);+ host.push(row(4), PaintDamage::DESCENDANT_READERS);+ host.push(row(0), PaintDamage::DESCENDANT_READERS);+ let third = record_frame(&mut host);+ assert_eq!(host.action_of(foreground(row(4))), Some(ScopeAction::Assembled));+ assert_eq!(host.recorded_rows(), vec![3, 4, 7]);+ assert_matches_from_scratch(&mut host, &third);}#[test]- fn a_frame_that_publishes_nothing_records_a_new_child_outside_the_tree() {+ fn a_child_scope_an_ancestor_moved_records_again_though_nothing_was_pushed_for_it() {let mut host = cards_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();- let published_structure = tree.structure();- let published_scope_count = tree.scope_count();-- // Card 4 takes card 2's place.- host.plan(- foreground(row(0)),- true,- &[- child(foreground(row(1))),- child(foreground(row(4))),- child(foreground(row(3))),- ],- );- host.plan(- foreground(row(4)),- true,- &[phase(PaintPhase::Background), phase(PaintPhase::Foreground)],- );- host.produce(row(4), ProducerKind::DrawBackground, content(2));- host.produce(row(4), ProducerKind::DrawForeground, content(1));- host.push(row(4), PaintDamage::ORDER | PaintDamage::ALL_PRODUCERS);- host.push(row(0), PaintDamage::ORDER | PaintDamage::DESCENDANT_READERS);- let unpublished = record_frame_rewriting_tree(&mut host, &mut tree, false);+ let first = record_frame(&mut host);+ publish(&mut host, first);+ host.origins.insert(row(5), 40);- assert_eq!(- host.recorded,- vec![- (row(4), ProducerKind::DrawBackground),- (row(4), ProducerKind::DrawForeground)- ]- );- assert_matches_from_scratch(&mut host, &unpublished);- assert_eq!(tree.structure(), published_structure);- assert_eq!(tree.scope_count(), published_scope_count);+ let frame = record_frame(&mut host);- let published = record_next_frame(&mut host, &mut tree);- assert_matches_from_scratch(&mut host, &published);+ assert_eq!(host.recorded_rows(), vec![5, 6, 5, 6]);+ assert!(host.copied_scopes().contains(&foreground(row(4))));+ assert_matches_from_scratch(&mut host, &frame);}#[test]- fn a_first_frame_that_publishes_nothing_leaves_the_tree_empty() {+ fn a_plan_that_gains_an_item_still_copies_the_runs_it_did_not_touch() {let mut host = cards_host();- let mut tree = PaintOrderTree::default();-- let frame = record_frame_rewriting_tree(&mut host, &mut tree, false);-- assert!(tree.root().is_none());- assert_eq!(tree.scope_count(), 0);+ let first = record_frame(&mut host);+ publish(&mut host, first);+ let mut items = host.plans[&context(row(0))].items.to_vec();+ items.push(child(foreground(row(7))));+ host.plan(context(row(0)), true, &items);+ host.grid_rows.insert(row(7), 3);+ host.plan(foreground(row(7)), true, &[phase(PaintPhase::Foreground)]);+ host.produce(row(7), ProducerKind::DrawForeground, content(1));+ host.push(row(0), PaintDamage::ORDER);++ let frame = record_frame(&mut host);++ assert_eq!(host.action_of(context(row(0))), Some(ScopeAction::Replanned));+ assert_eq!(host.recorded_rows(), vec![7]);assert_matches_from_scratch(&mut host, &frame);}#[test]- fn nested_damage_walks_only_the_damaged_path() {+ fn output_recorded_every_frame_or_read_from_the_window_focus_is_not_copied() {let mut host = cards_host();- // Card 3 gets a nested scope of its own.- host.plan(- foreground(row(3)),- true,- &[- phase(PaintPhase::Background),- child(foreground(row(5))),- phase(PaintPhase::Foreground),- ],- );- host.plan(foreground(row(5)), true, &[phase(PaintPhase::Foreground)]);- host.produce(row(5), ProducerKind::DrawForeground, content(3));- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-+ host.contents+ .get_mut(&(row(1), ProducerKind::DrawForeground))+ .unwrap()+ .live = true;host.contents.get_mut(&(row(5), ProducerKind::DrawForeground)).unwrap()- .version = 9;- host.push(row(5), PaintDamage::DRAW_FOREGROUND);- for ancestor in [row(3), row(0)] {- host.push(ancestor, PaintDamage::DESCENDANT_READERS);- }- let second = record_next_frame(&mut host, &mut tree);-- assert_eq!(host.recorded, vec![(row(5), ProducerKind::DrawForeground)]);- let assembled: Vec<PaintScope> = host- .events- .iter()- .filter_map(|event| match event {- AssemblyEvent::ScopeBegin(scope, ScopeAction::Assembled) => Some(*scope),- _ => None,- })- .collect();- assert_eq!(- assembled.len(),- 4,- "viewport, its foreground, card 3 and its nested scope"- );- assert_matches_from_scratch(&mut host, &second);- }+ .reads_window_focus = true;+ let first = record_frame(&mut host);+ assert!(!frame_is_unchanged(&first.root, false, false));+ publish(&mut host, first);- #[test]- fn a_moved_subtree_records_every_producer_inside_it() {- let mut host = cards_host();- host.plan(- foreground(row(3)),- true,- &[phase(PaintPhase::Background), child(foreground(row(5)))],- );- host.plan(foreground(row(5)), true, &[phase(PaintPhase::Foreground)]);- host.produce(row(5), ProducerKind::DrawForeground, content(2));- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-- host.moved_subtrees.extend([row(3), row(5)]);- host.push(row(0), PaintDamage::DESCENDANT_READERS);- let second = record_next_frame(&mut host, &mut tree);-- assert_eq!(- host.recorded,- vec![- (row(3), ProducerKind::DrawBackground),- (row(5), ProducerKind::DrawForeground)- ]- );- assert_matches_from_scratch(&mut host, &second);- }-- #[test]- fn descendant_readers_record_when_something_below_them_changed() {- let mut host = cards_host();- host.plan(foreground(row(3)), true, &[svg(), child(foreground(row(5)))]);- host.produce(row(3), ProducerKind::Svg, content(1));- host.descendant_readers.insert((row(3), ProducerKind::Svg));- host.plan(foreground(row(5)), true, &[phase(PaintPhase::Foreground)]);- host.produce(row(5), ProducerKind::DrawForeground, content(1));- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-- host.push(row(5), PaintDamage::DRAW_FOREGROUND);- host.push(row(3), PaintDamage::DESCENDANT_READERS);- host.push(row(0), PaintDamage::DESCENDANT_READERS);- let second = record_next_frame(&mut host, &mut tree);+ let quiet = record_frame(&mut host);+ assert_eq!(host.recorded_rows(), vec![1, 2]);+ assert_matches_from_scratch(&mut host, &quiet);+ publish(&mut host, quiet);- assert_eq!(- host.recorded,- vec![(row(3), ProducerKind::Svg), (row(5), ProducerKind::DrawForeground)]- );- assert_matches_from_scratch(&mut host, &second);+ let refocused = record_frame_with_focus_change(&mut host, true);+ assert_eq!(host.recorded_rows(), vec![1, 2, 5, 6]);+ assert_matches_from_scratch(&mut host, &refocused);}#[test]- fn live_producers_record_every_frame_and_keep_the_frame_changing() {+ fn a_stacking_context_that_stops_painting_records_nothing() {let mut host = cards_host();- host.produce(- row(2),- ProducerKind::DrawBackground,- Content {- live: true,- ..content(1)- },- );- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();- assert!(!frame_is_unchanged(&tree, false, false));-- let second = record_next_frame(&mut host, &mut tree);-- assert_eq!(host.recorded, vec![(row(2), ProducerKind::DrawBackground)]);- assert_matches_from_scratch(&mut host, &second);- }-- #[test]- fn an_inactive_context_records_nothing_and_retires_its_children() {- let mut host = cards_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-- let mut hidden = host.plans[&context(row(0))].clone();- hidden.active = false;- host.plans.insert(context(row(0)), hidden);+ let first = record_frame(&mut host);+ publish(&mut host, first);+ let items = host.plans[&context(row(0))].items.to_vec();+ host.plan(context(row(0)), false, &items);host.push(row(0), PaintDamage::ELIGIBILITY);- let second = record_next_frame(&mut host, &mut tree);-- assert!(host.recorded.is_empty());- assert_eq!(second.root_output, OutputSize::default());- assert_eq!(second.display_list.bytes.len(), second.prologue_bytes as usize);- assert_eq!(tree.scope_count(), 1);- assert_matches_from_scratch(&mut host, &second);- }-- #[test]- fn blocking_wheel_regions_are_counted_through_copies() {- let mut host = cards_host();- host.produce(- row(1),- ProducerKind::DrawForeground,- Content {- blocking: 1,- ..content(1)- },- );- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- assert_eq!(first.root_output.blocking_wheel_event_regions, 1);- assert_eq!(tree.root_entry().output().blocking_wheel_event_regions, 1);- host.source = Some(first);- host.clear_damage();- host.push(row(3), PaintDamage::DRAW_FOREGROUND);- host.push(row(0), PaintDamage::DESCENDANT_READERS);- let second = record_next_frame(&mut host, &mut tree);-- assert_eq!(host.recorded, vec![(row(3), ProducerKind::DrawForeground)]);- assert_eq!(second.root_output.blocking_wheel_event_regions, 1);- assert_eq!(tree.root_entry().output().blocking_wheel_event_regions, 1);- }-- struct Lcg(u32);-- impl Lcg {- fn next(&mut self, limit: u32) -> u32 {- self.0 = self.0.wrapping_mul(1_103_515_245).wrapping_add(12345);- (self.0 >> 8) % limit- }- }-- const CARD_ROWS: [u32; 6] = [1, 2, 3, 4, 5, 6];-- fn nested_row(card: u32) -> Option<u32> {- matches!(card, 2 | 3 | 5).then_some(10 + card)- }+ let frame = record_frame(&mut host);- fn parent_row(row_index: u32) -> Option<u32> {- match row_index {- 0 => None,- index if index >= 10 => Some(index - 10),- _ => Some(0),- }- }-- fn push_with_hints(host: &mut TestHost, row_index: u32, damage: PaintDamage) {- host.push(row(row_index), damage);- let mut ancestor = parent_row(row_index);- while let Some(index) = ancestor {- host.push(row(index), PaintDamage::DESCENDANT_READERS);- ancestor = parent_row(index);- }- }-- fn producer_kinds_of(host: &TestHost, row_index: u32) -> Vec<ProducerKind> {- let mut kinds: Vec<ProducerKind> = host- .contents- .keys()- .filter(|(owner, _)| *owner == row(row_index))- .map(|(_, kind)| *kind)- .collect();- kinds.sort_unstable_by_key(|kind| kind.code());- kinds- }-- fn bump_version(host: &mut TestHost, row_index: u32, kind: ProducerKind) {- let content = host.contents.get_mut(&(row(row_index), kind)).unwrap();- content.version = content.version.wrapping_add(1).max(1);- }-- // Six card contexts under the viewport foreground. Cards 2 and 5 nest a context of their- // own; card 3 paints an svg whose output depends on the foreground scope nested below it.- fn random_tree_host() -> TestHost {- let mut host = TestHost::default();- host.plan(- context(row(0)),- true,- &[phase(PaintPhase::Background), child(foreground(row(0)))],- );- host.produce(row(0), ProducerKind::DrawBackground, content(1));- let cards: Vec<PaintOrderItem> = CARD_ROWS.iter().map(|card| child(context(row(*card)))).collect();- host.plan(foreground(row(0)), true, &cards);- for card in CARD_ROWS {- host.plan(- context(row(card)),- true,- &[phase(PaintPhase::Background), child(foreground(row(card)))],- );- host.produce(row(card), ProducerKind::DrawBackground, content(1));- host.produce(row(card), ProducerKind::DrawForeground, content(card));- let mut foreground_items = vec![phase(PaintPhase::Foreground)];- match nested_row(card) {- Some(nested) if card == 3 => {- foreground_items = vec![svg(), child(foreground(row(nested)))];- host.produce(row(card), ProducerKind::Svg, content(1));- host.descendant_readers.insert((row(card), ProducerKind::Svg));- host.plan(foreground(row(nested)), true, &[phase(PaintPhase::Foreground)]);- host.produce(row(nested), ProducerKind::DrawForeground, content(1));- }- Some(nested) => {- foreground_items.push(child(context(row(nested))));- host.plan(- context(row(nested)),- true,- &[phase(PaintPhase::Background), phase(PaintPhase::Foreground)],- );- host.produce(row(nested), ProducerKind::DrawBackground, content(2));- host.produce(row(nested), ProducerKind::DrawForeground, content(1));- }- None => {}- }- host.plan(foreground(row(card)), true, &foreground_items);- }- host- }-- // The svg of card 3 reads the scope nested below it, so a change there changes the svg's- // output without a push of its own.- fn change_content(host: &mut TestHost, random: &mut Lcg, row_index: u32) {- let kinds = producer_kinds_of(host, row_index);- let kind = kinds[random.next(kinds.len() as u32) as usize];- let content = host.contents.get_mut(&(row(row_index), kind)).unwrap();- match random.next(3) {- 0 => content.version = content.version.wrapping_add(1).max(1),- _ => content.rects = random.next(4),- }- push_with_hints(host, row_index, kind.damage());- if row_index == 13 {- bump_version(host, 3, ProducerKind::Svg);- }- }-- // Random changes to the tree `random_tree_host` makes: to contents, to the cards listed and their order, to whether- // a card paints, and to where a card's subtree is.- struct RandomChanges {- random: Lcg,- listed: Vec<u32>,- removed: Vec<u32>,- inactive: HashSet<u32>,- }-- impl RandomChanges {- fn new(seed: u32) -> Self {- Self {- random: Lcg(seed),- listed: CARD_ROWS.to_vec(),- removed: Vec::new(),- inactive: HashSet::new(),- }- }-- fn plan_listed_cards(&self, host: &mut TestHost) {- let items: Vec<PaintOrderItem> = self.listed.iter().map(|card| child(context(row(*card)))).collect();- host.plan(foreground(row(0)), true, &items);- host.push(row(0), PaintDamage::ORDER);- }-- fn apply(&mut self, host: &mut TestHost) {- let rows_with_content = [1, 2, 3, 4, 5, 6, 12, 13, 15];- for _ in 0..=self.random.next(3) {- match self.random.next(7) {- 0 | 1 => {- let row_index = rows_with_content[self.random.next(rows_with_content.len() as u32) as usize];- change_content(host, &mut self.random, row_index);- }- 2 => {- for index in (1..self.listed.len()).rev() {- self.listed.swap(index, self.random.next(index as u32 + 1) as usize);- }- self.plan_listed_cards(host);- }- 3 if self.listed.len() > 1 => {- let card = self.listed.remove(self.random.next(self.listed.len() as u32) as usize);- self.removed.push(card);- self.plan_listed_cards(host);- }- 4 if !self.removed.is_empty() => {- let card = self- .removed- .remove(self.random.next(self.removed.len() as u32) as usize);- self.listed- .insert(self.random.next(self.listed.len() as u32 + 1) as usize, card);- push_with_hints(host, card, PaintDamage::ORDER | PaintDamage::ALL_PRODUCERS);- if let Some(nested) = nested_row(card) {- push_with_hints(host, nested, PaintDamage::ORDER | PaintDamage::ALL_PRODUCERS);- }- self.plan_listed_cards(host);- }- 5 => {- let card = self.listed[self.random.next(self.listed.len() as u32) as usize];- if !self.inactive.remove(&card) {- self.inactive.insert(card);- }- host.plans.get_mut(&context(row(card))).unwrap().active = !self.inactive.contains(&card);- push_with_hints(host, card, PaintDamage::ELIGIBILITY);- }- 6 => {- let card = self.listed[self.random.next(self.listed.len() as u32) as usize];- let mut subtree = vec![card];- subtree.extend(nested_row(card));- for row_index in subtree {- for kind in producer_kinds_of(host, row_index) {- bump_version(host, row_index, kind);- }- host.moved_subtrees.insert(row(row_index));- }- push_with_hints(host, card, PaintDamage::MOVED);- }- _ => {}- }- }- }- }-- #[test]- fn random_damage_over_a_synthetic_tree_always_matches_from_scratch() {- let mut changes = RandomChanges::new(0x2545_f491);- let mut host = random_tree_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-- for step in 0..400 {- changes.apply(&mut host);-- // Frames that publish nothing are recorded between two published frames.- let published_structure = tree.structure();- for _ in 0..step % 3 {- let unpublished = record_frame_rewriting_tree(&mut host, &mut tree, false);- assert_matches_from_scratch(&mut host, &unpublished);- assert_eq!(tree.structure(), published_structure);- }-- let frame = record_next_frame(&mut host, &mut tree);- assert_matches_from_scratch(&mut host, &frame);- host.clear_damage();- assert!(tree.scope_count() <= 32, "retired scopes are freed at once");- }- }-- #[test]- fn frames_that_publish_nothing_match_from_scratch_as_damage_accumulates_over_them() {- let mut changes = RandomChanges::new(0x9e37_79b9);- let mut host = random_tree_host();- let mut tree = PaintOrderTree::default();- let first = record_frame(&mut host, &mut tree);- host.source = Some(first);- host.clear_damage();-- for _ in 0..80 {- let published_structure = tree.structure();- let published_root_entry = tree.root_entry();- let removed_when_published = changes.removed.clone();- for _ in 0..6 {- changes.apply(&mut host);- // A card that left and comes back since the published frame is still in the tree, and what it published- // still stands: its parent's new order is all that changes.- if changes.random.next(2) == 0- && let Some(position) = changes- .removed- .iter()- .position(|card| !removed_when_published.contains(card))- {- let card = changes.removed.remove(position);- let at = changes.random.next(changes.listed.len() as u32 + 1) as usize;- changes.listed.insert(at, card);- changes.plan_listed_cards(&mut host);- }- let unpublished = record_frame_rewriting_tree(&mut host, &mut tree, false);- assert_matches_from_scratch(&mut host, &unpublished);- assert_eq!(tree.structure(), published_structure);- assert_eq!(tree.root_entry(), published_root_entry);- host.recorded.clear();- host.events.clear();- }-- let frame = record_next_frame(&mut host, &mut tree);- assert_matches_from_scratch(&mut host, &frame);- host.clear_damage();- }+ assert_eq!(host.action_of(context(row(0))), Some(ScopeAction::Inactive));+ assert!(host.recorded.is_empty());+ assert_eq!(frame.root.facts, OutputFacts::default());+ assert_eq!(frame.display_list.chunks.len(), 1);}}diff --git a/Libraries/LibWeb/Rust/src/painting/record/damage.rs b/Libraries/LibWeb/Rust/src/painting/record/damage.rsindex a894efbdfe5..af0c1f801d8 100644--- a/Libraries/LibWeb/Rust/src/painting/record/damage.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/damage.rs@@ -67,6 +67,10 @@ impl PaintDamage {self.0 & other.0 == other.0}+ pub(crate) const fn without(self, other: Self) -> Self {+ Self(self.0 & !other.0)+ }+pub(crate) const fn intersects(self, other: Self) -> bool {self.0 & other.0 != 0}@@ -181,6 +185,7 @@ impl FrameDamage {.map_or(PaintDamage::NONE, |index| self.rows[index].1)}+ #[cfg(test)]pub(crate) fn rows(&self) -> impl Iterator<Item = NodeSlotId> + '_ {self.rows.iter().map(|(row, _)| *row)}diff --git a/Libraries/LibWeb/Rust/src/painting/record/frame_inputs.rs b/Libraries/LibWeb/Rust/src/painting/record/frame_inputs.rsindex a8ecf6a6467..5c9ead5eb78 100644--- a/Libraries/LibWeb/Rust/src/painting/record/frame_inputs.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/frame_inputs.rs@@ -21,6 +21,7 @@ pub(crate) struct FrameInputs {pub(crate) force_dark_settings: ForceDarkSettings,pub(crate) should_show_line_box_borders: bool,pub(crate) should_paint_overlay: bool,+ records_in_finest_runs: bool,pub(crate) uncaptured: UncapturedContentInputs,// Whether any box but the viewport could take or keep a wheel event decides if the scroll metadata// inside subtree captures carries per-box wheel hit-test targets.@@ -48,6 +49,7 @@ impl FrameInputs {force_dark_settings: inputs.force_dark_settings,should_show_line_box_borders: inputs.should_show_line_box_borders,should_paint_overlay: inputs.should_paint_overlay,+ records_in_finest_runs: inputs.records_in_finest_runs,uncaptured: inputs.uncaptured,has_non_viewport_wheel_scroll_target_candidate: paint_state.has_non_viewport_wheel_scroll_target_candidate,selection_colors: SelectionColors {diff --git a/Libraries/LibWeb/Rust/src/painting/record/inputs.rs b/Libraries/LibWeb/Rust/src/painting/record/inputs.rsindex c4e6b1b0d25..f76f85e6562 100644--- a/Libraries/LibWeb/Rust/src/painting/record/inputs.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/inputs.rs@@ -65,6 +65,10 @@ pub(crate) struct RecordingInputs {pub force_dark_enabled: bool,pub force_dark_settings: ForceDarkSettings,pub should_paint_overlay: bool,+ /// Cuts the plans a recording walks as finely as they go: every child scope with a bound is walked on its own,+ /// and a run holds only what starts in one pixel row. Tests ask for it to see which boxes a change records+ /// again on pages too small to span the rows a recording is otherwise cut along.+ pub records_in_finest_runs: bool,pub canvas_fill_rect: Option<IntRect>,pub opaque_canvas: bool,pub bitmap_rect: IntRect,diff --git a/Libraries/LibWeb/Rust/src/painting/record/mod.rs b/Libraries/LibWeb/Rust/src/painting/record/mod.rsindex aceb617a164..31e80f28040 100644--- a/Libraries/LibWeb/Rust/src/painting/record/mod.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/mod.rs@@ -28,7 +28,6 @@ pub(crate) mod vector_images;use crate::css::css_enums;use crate::css::css_pixels::CssPixelRect;-use crate::css::style::fast_hash::FastSet;use crate::layout::node_data::{NodeFlag, NodeSlotId};use crate::painting::border_radii::BorderRadii;use crate::painting::display_list::builder::{PendingInlineClip, RecordedDisplayList};@@ -52,13 +51,20 @@ pub struct RecordingOutput {// The area the root background painted: the viewport united with the root's overflow. Only// the root's background reads it, so a change pushes that producer instead of a new frame.pub(crate) root_background_canvas_rect: CssPixelRect,- // The bytes before the viewport's scope: the canvas, recorded outside the tree.- pub(crate) prologue_bytes: u32,+ /// The name of the chunk the canvas was recorded into, outside the walked scopes, or none where it drew nothing.+ pub(crate) prologue_id: Option<crate::painting::display_list::chunks::ChunkId>,pub root_group_color: libgfx_rust::Color,/// The rows' hit-test items stamp of the frame the recording recorded: hit testing walks its rows, which place/// other items in a frame with another stamp or another visual context tree.pub hit_test_items_stamp: u64,+ /// The chunks of the display list in paint order: the canvas, recorded outside the walked scopes, the chunks of+ /// those, and the inspector's overlays.+ pub(crate) chunks: Arc<[Arc<order_tree::RecordedChunk>]>,+ /// The display list's tape: its chunks one after another.pub display_list: Arc<RecordedDisplayList>,+ /// The scopes the recording walked, with what each part of them recorded, which the next recording reuses its+ /// clean output by.+ pub(crate) recorded_root: Option<Arc<order_tree::RecordedScope>>,pub has_blocking_wheel_event_listeners: bool,pub wheel_event_listener_state_generation: u64,pub is_identical_to_published_recording: bool,@@ -86,6 +92,7 @@ pub(crate) struct RecordingResult {// What a recording shares with later recordings.const _: () = {const fn assert_send_and_sync<T: Send + Sync>() {}+ assert_send_and_sync::<order_tree::RecordedChunk>();assert_send_and_sync::<paint::text::SelectionStyleAnswer>();};@@ -116,14 +123,16 @@ pub struct PaintRecorder<'a, O: Observer> {pub(crate) svg_resource_walk: Option<SvgResourceWalk>,pub(crate) viewport: NodeSlotId,ink_bounds_audit: ink_bounds::InkBoundsAudit,- // The published recording whose clean output this recording copies, when its inputs match.+ // The published recording whose clean output this recording reuses, when its inputs match.pub(crate) source_recording: Option<Arc<RecordingOutput>>,+ // Set while a run records a placeholder for the records of an SVG image, which its chunk holds until the+ // publication of the recording finishes it.+ run_draws_vector_image_placeholders: bool,// Set while a producer records output that must record again every frame.live_producer: bool,// Set while a producer records output that depends on whether the window is focused.producer_reads_window_focus: std::cell::Cell<bool>,// Rows of the layout subtrees whose root moved: every producer of theirs records again.- pub(crate) moved_expansion: FastSet<NodeSlotId>,pub(crate) blocking_wheel_event_region_count: u32,pub(crate) records_per_box_wheel_hit_test_targets: bool,pub(crate) observer: O,@@ -225,6 +234,16 @@ impl<O: Observer> PaintRecorder<'_, O> {self.recorder.force_dark_settings()}+ /// The placeholder a command that paints the SVG image of `request` names until publication patches in the id of+ /// the records the host rendered the image as.+ pub(crate) fn vector_image_placeholder(+ &mut self,+ request: vector_images::VectorImageRenderRequest,+ ) -> crate::painting::display_list::commands::DisplayListResourceId {+ self.run_draws_vector_image_placeholders = true;+ self.resources.vector_image_placeholder(request)+ }+pub(crate) fn paint_vector_image(&mut self,source: vector_images::VectorImageSource,@@ -236,17 +255,15 @@ impl<O: Observer> PaintRecorder<'_, O> {) {use libgfx_rust::CompositingAndBlendingOperator;let geometry = vector_images::vector_image_render_geometry(dest_rect, accumulated_scale, has_active_view_box);- let display_list_id = self- .resources- .vector_image_placeholder(vector_images::VectorImageRenderRequest::new(- source,- geometry.css_width,- geometry.css_height,- geometry.raster_scale,- content_identity,- self.vector_image_color_scheme(source.owner()),- self.vector_image_force_dark(),- ));+ let display_list_id = self.vector_image_placeholder(vector_images::VectorImageRenderRequest::new(+ source,+ geometry.css_width,+ geometry.css_height,+ geometry.raster_scale,+ content_identity,+ self.vector_image_color_scheme(source.owner()),+ self.vector_image_force_dark(),+ ));if compositing_and_blending_operator != CompositingAndBlendingOperator::Normal {let dest_device_rect = libgfx_rust::enclosing_int_rect(dest_rect);if dest_device_rect.is_empty() {@@ -734,9 +751,11 @@ impl<O: Observer> PaintRecorder<'_, O> {tile_surface_size_bits: [tile_surface_rect.width.to_bits(), tile_surface_rect.height.to_bits()],force_dark: self.recorder.force_dark_settings().is_some(),};- if let Some(records) = self.scratch.pattern_tile_records.get(&key) {+ if let Some((records, draws_vector_image_placeholders)) = self.scratch.pattern_tile_records.get(&key) {+ self.run_draws_vector_image_placeholders |= *draws_vector_image_placeholders;return records.clone();}+ let run_draws_vector_image_placeholders = std::mem::take(&mut self.run_draws_vector_image_placeholders);let detached = self.recorder.begin_detached_records();// Pattern tiles exclude the root's own transform: patternTransform reaches the replay-side// tile shader instead, so the tiling grid repeats under it rather than the content scaling@@ -745,7 +764,11 @@ impl<O: Observer> PaintRecorder<'_, O> {this.walk_svg_resource(pattern, root_transform, false, false, tile_surface_rect);});let records = Arc::new(self.recorder.finish_detached_records(detached));- self.scratch.pattern_tile_records.insert(key, records.clone());+ let tile_draws_vector_image_placeholders = self.run_draws_vector_image_placeholders;+ self.run_draws_vector_image_placeholders |= run_draws_vector_image_placeholders;+ self.scratch+ .pattern_tile_records+ .insert(key, (records.clone(), tile_draws_vector_image_placeholders));records}}diff --git a/Libraries/LibWeb/Rust/src/painting/record/order_tree.rs b/Libraries/LibWeb/Rust/src/painting/record/order_tree.rsindex 3bdfc14c4cd..4ca3061fa0f 100644--- a/Libraries/LibWeb/Rust/src/painting/record/order_tree.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/order_tree.rs@@ -4,73 +4,24 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The paint-order tree retained from the published recording. Every scope the planner produced is-//! a node with a stable id. A node's child entries name producers of the node's owner and child-//! scopes, each with the size of the output it contributed, so a child's position in the-//! published tape is the sum of the sizes before it and a change inside one scope never touches-//! the entries of another.--use crate::css::style::fast_hash::FastMap;-use crate::layout::node_data::NodeSlotId;-use crate::painting::paint_order_plan::{PaintScope, PaintScopeKind, StackingContextPaintPhase};+//! What a recording keeps of the paint order it recorded, for the next recording to reuse clean output from.+//!+//! The planner's scopes nest to the depth of the document, and keeping every one of them costs more than the display+//! list they describe. So only some scopes are kept as nodes of their own: the ones a recording walks, because they+//! are too tall to be recorded in one piece, scroll, or may paint anywhere. The plan of a walked scope is cut into+//! runs of consecutive items, each recorded whole into a chunk of its own, with the walked child scopes between them.+//! A recording reuses the chunk of every clean run and every walked scope that is clean all the way down, and shares+//! those nodes with the recording it took them from.++use crate::css::css_pixels::CssPixelPoint;+use crate::painting::display_list::chunks::Chunk;+use crate::painting::paint_order_plan::{PaintOrderItem, PaintScope};use crate::painting::record::damage::PaintDamage;-use smallvec::SmallVec;--#[derive(Clone, Copy, PartialEq, Eq, Hash)]-pub(crate) struct ScopeId(u32);--const SCOPE_INDEX_BITS: u32 = 24;-const SCOPE_INDEX_MASK: u32 = (1 << SCOPE_INDEX_BITS) - 1;-// A child entry tells scopes from producers by the top bit of its key, which an id therefore-// never sets: a slot whose generation reaches this many retirements is never reused.-const SCOPE_GENERATION_LIMIT: u8 = 127;--impl ScopeId {- pub(crate) const NONE: Self = Self(u32::MAX);-- fn new(index: usize, generation: u8) -> Self {- assert!(- index < SCOPE_INDEX_MASK as usize,- "paint-order tree exhausted its scope ids"- );- assert!(- (1..=SCOPE_GENERATION_LIMIT).contains(&generation),- "paint scope generation {generation} is out of range"- );- Self(index as u32 | (u32::from(generation) << SCOPE_INDEX_BITS))- }-- fn index(self) -> usize {- (self.0 & SCOPE_INDEX_MASK) as usize- }-- fn generation(self) -> u8 {- (self.0 >> SCOPE_INDEX_BITS) as u8- }+use std::ops::Range;+use std::sync::{Arc, OnceLock};- pub(crate) fn is_none(self) -> bool {- self == Self::NONE- }-}--impl Default for ScopeId {- fn default() -> Self {- Self::NONE- }-}--impl std::fmt::Debug for ScopeId {- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- if self.is_none() {- write!(formatter, "ScopeId(none)")- } else {- write!(formatter, "ScopeId({}g{})", self.index(), self.generation())- }- }-}--/// One unit of recorded output owned by a row. The order of the draw phases mirrors `PaintPhase`,-/// and every kind has the damage bit that makes it record again.+/// One unit of recorded output owned by a row. The order of the draw phases mirrors `PaintPhase`, and every kind has+/// the damage bit that makes it record again.#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]#[repr(u8)]pub(crate) enum ProducerKind {@@ -88,18 +39,6 @@ pub(crate) enum ProducerKind {}impl ProducerKind {- const ALL: [Self; 9] = [- Self::DrawBackground,- Self::DrawBorder,- Self::DrawTableCollapsedBorder,- Self::DrawForeground,- Self::DrawOutline,- Self::DrawOverlay,- Self::ScrollMetadata,- Self::ScopePreamble,- Self::Svg,- ];-pub(crate) fn damage(self) -> PaintDamage {match self {Self::DrawBackground => PaintDamage::DRAW_BACKGROUND,@@ -117,30 +56,11 @@ impl ProducerKind {Self::TextFragment(_) => PaintDamage::DRAW_FOREGROUND,}}-- fn from_code(code: u32) -> Self {- match code & 15 {- 12 => Self::InlinePiece(code >> 4),- 13 => Self::TextFragment(code >> 4),- kind => Self::ALL[kind as usize],- }- }-- pub(super) fn code(self) -> u32 {- match self {- Self::InlinePiece(index) | Self::TextFragment(index) => {- assert!(index < 1 << 27, "inline content exceeds producer key capacity");- (index << 4) | if matches!(self, Self::InlinePiece(_)) { 12 } else { 13 }- }- _ => Self::ALL.iter().position(|kind| *kind == self).unwrap() as u32,- }- }}-/// The output one child contributed to the published recording.+/// What one part of a recording recorded, besides its chunks, that decides whether it can be reused.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-pub(crate) struct OutputSize {- pub bytes: u32,+pub(crate) struct OutputFacts {pub blocking_wheel_event_regions: u32,// Recorded again every frame: scroll-offset-dependent content and resources without// retained output. A scope is live when any child is.@@ -150,693 +70,157 @@ pub(crate) struct OutputSize {pub reads_window_focus: bool,}-impl OutputSize {- pub(crate) fn add(&mut self, other: OutputSize) {- self.bytes += other.bytes;+impl OutputFacts {+ pub(crate) fn add(&mut self, other: OutputFacts) {self.blocking_wheel_event_regions += other.blocking_wheel_event_regions;self.live |= other.live;self.reads_window_focus |= other.reads_window_focus;}}-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub(crate) enum ChildKey {- Scope(ScopeId),- Producer(ProducerKind),+/// Where a row's boxes are, as far as an ancestor can move them without anything pushing damage for the row: the+/// origin of its first fragment, and for a row in several fragments a digest of where the later ones are, which a+/// change of the columns they sit in moves on its own.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(crate) struct RowPlacement {+ pub origin: CssPixelPoint,+ pub later_fragments: u64,}-#[repr(C)]-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(crate) struct ChildEntry {- key: u32,- bytes: u32,- meta: u32,+/// A part of a walked scope's plan.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) enum Segment {+ /// Consecutive items recorded as one piece: producers of the scope's owner, and child scopes with everything+ /// below them.+ Run(Range<u32>),+ /// The item that is a child scope walked on its own.+ Walked(u32),}-const _: () = assert!(std::mem::size_of::<ChildEntry>() == 12);--const SCOPE_KEY_BIT: u32 = 1 << 31;-const META_LIVE: u32 = 1;-const META_READS_WINDOW_FOCUS: u32 = 2;-const META_BLOCKING_REGIONS_SHIFT: u32 = 8;--impl ChildEntry {- pub(crate) fn scope(id: ScopeId, output: OutputSize) -> Self {- debug_assert!(!id.is_none());- Self::with_key(SCOPE_KEY_BIT | id.0, output)- }-- pub(crate) fn producer(kind: ProducerKind, output: OutputSize) -> Self {- Self::with_key(kind.code(), output)- }-- fn with_key(key: u32, output: OutputSize) -> Self {- let meta = (output.blocking_wheel_event_regions << META_BLOCKING_REGIONS_SHIFT)- | if output.live { META_LIVE } else { 0 }- | if output.reads_window_focus {- META_READS_WINDOW_FOCUS- } else {- 0- };- Self {- key,- bytes: output.bytes,- meta,- }- }+/// The plan of a walked scope with where it is cut. The items follow paint order alone, and are shared with the+/// plan they were kept from while that holds. The cuts follow where the items are, so a recording that walks the+/// scope after anything in it changed or moved cuts it again.+#[derive(Debug, PartialEq, Eq)]+pub(crate) struct SegmentedPlan {+ pub active: bool,+ pub items: Arc<[PaintOrderItem]>,+ pub segments: Vec<Segment>,+}- pub(crate) fn key(&self) -> ChildKey {- if self.key & SCOPE_KEY_BIT != 0 {- ChildKey::Scope(ScopeId(self.key & !SCOPE_KEY_BIT))- } else {- ChildKey::Producer(ProducerKind::from_code(self.key))- }+impl SegmentedPlan {+ pub(crate) fn items_of(&self, run: &Range<u32>) -> &[PaintOrderItem] {+ &self.items[run.start as usize..run.end as usize]}- pub(crate) fn output(&self) -> OutputSize {- OutputSize {- bytes: self.bytes,- blocking_wheel_event_regions: self.meta >> META_BLOCKING_REGIONS_SHIFT,- live: self.meta & META_LIVE != 0,- reads_window_focus: self.reads_window_focus(),+ pub(crate) fn walked_scope(&self, item: u32) -> PaintScope {+ match self.items[item as usize] {+ PaintOrderItem::Scope(scope) => scope,+ PaintOrderItem::Producer(_) => unreachable!("a walked segment names a child scope"),}}-- pub(crate) fn is_live(&self) -> bool {- self.meta & META_LIVE != 0- }-- pub(crate) fn reads_window_focus(&self) -> bool {- self.meta & META_READS_WINDOW_FOCUS != 0- }-}--impl Default for ChildEntry {- fn default() -> Self {- Self::scope(ScopeId(SCOPE_INDEX_MASK), OutputSize::default())- }}-const NODE_OCCUPIED: u8 = 1;--#[repr(C)]-#[derive(Clone, Copy)]-struct ScopeNode {- owner: NodeSlotId,- parent: ScopeId,- children_start: u32,- children_len: u32,- kind: u8,- flags: u8,- generation: u8,- _padding: u8,+/// The chunk one recording recorded. Where the chunk draws an SVG image, it holds a placeholder for the records the+/// host renders the image as, until the recording that made it is published and finishes it with their id: only a+/// finished chunk can be drawn by another recording.+#[derive(Debug)]+pub(crate) struct RecordedChunk {+ recorded: Arc<Chunk>,+ draws_vector_image_placeholders: bool,+ finished: OnceLock<Arc<Chunk>>,}-const _: () = assert!(std::mem::size_of::<ScopeNode>() == 20);--fn scope_kind_code(kind: PaintScopeKind) -> u8 {- match kind {- PaintScopeKind::PaintedAsStackingContext => 0,- PaintScopeKind::Descendants(phase) => 1 + phase as u8,+impl RecordedChunk {+ pub(crate) fn new(recorded: Chunk, draws_vector_image_placeholders: bool) -> Arc<Self> {+ Arc::new(Self {+ recorded: Arc::new(recorded),+ draws_vector_image_placeholders,+ finished: OnceLock::new(),+ })}-}-fn scope_kind_from_code(code: u8) -> PaintScopeKind {- match code {- 0 => PaintScopeKind::PaintedAsStackingContext,- 1 => PaintScopeKind::Descendants(StackingContextPaintPhase::BackgroundAndBorders),- 2 => PaintScopeKind::Descendants(StackingContextPaintPhase::Floats),- 3 => PaintScopeKind::Descendants(StackingContextPaintPhase::BackgroundAndBordersForInlineLevelAndReplaced),- 4 => PaintScopeKind::Descendants(StackingContextPaintPhase::Foreground),- _ => unreachable!("unknown paint scope kind code {code}"),+ /// The chunk as the recording that made it recorded it.+ pub(crate) fn recorded(&self) -> &Arc<Chunk> {+ &self.recorded}-}--pub(crate) const SCOPE_KIND_COUNT: u8 = 1 + StackingContextPaintPhase::COUNT as u8;--#[derive(Clone, Default)]-pub(crate) struct PaintOrderTree {- nodes: Vec<ScopeNode>,- free_nodes: Vec<u32>,- children: Vec<ChildEntry>,- live_child_entries: u32,- // The scope of each kind a row owns, indexed by the row's slot. A second scope with the- // same owner and kind, which the planner produces only for unusual inline-level- // configurations, lives in the overflow map.- scopes_by_row: Vec<[ScopeId; SCOPE_KIND_COUNT as usize]>,- duplicate_scopes: FastMap<(NodeSlotId, u8), SmallVec<[ScopeId; 2]>>,- root: ScopeId,- root_entry: ChildEntry,-}-/// What a recording does to the paint-order tree: a recording that publishes rewrites it to describe what it publishes,-/// and any other only reads it, as the map of the published recording it copies from.-pub(crate) enum PaintOrderTreeAccess<'a> {- Reads(&'a PaintOrderTree),- Rewrites(&'a mut PaintOrderTree),-}+ pub(crate) fn draws_vector_image_placeholders(&self) -> bool {+ self.draws_vector_image_placeholders+ }-impl PaintOrderTreeAccess<'_> {- pub(crate) fn read(&self) -> &PaintOrderTree {- match self {- Self::Reads(tree) => tree,- Self::Rewrites(tree) => tree,+ /// The chunk as a display list draws it, where nothing in it is a placeholder any more.+ pub(crate) fn finished(&self) -> Option<&Arc<Chunk>> {+ match self.draws_vector_image_placeholders {+ false => Some(&self.recorded),+ true => self.finished.get(),}}- pub(crate) fn rewrites(&mut self) -> Option<&mut PaintOrderTree> {- match self {- Self::Reads(_) => None,- Self::Rewrites(tree) => Some(tree),- }+ /// The chunk as the recording that made it, or the publication of that recording, left it.+ pub(crate) fn latest(&self) -> &Arc<Chunk> {+ self.finished().unwrap_or(&self.recorded)}- pub(crate) fn is_rewriting(&self) -> bool {- matches!(self, Self::Rewrites(_))+ /// Finishes a chunk that draws placeholders with the chunk the publication of its recording patched them in.+ pub(crate) fn finish(&self, finished: Chunk) -> &Arc<Chunk> {+ debug_assert!(+ self.draws_vector_image_placeholders,+ "only a chunk with placeholders is finished"+ );+ let _ = self.finished.set(Arc::new(finished));+ self.finished.get().expect("the chunk was finished above")}}-/// The scopes on a damaged path of the current recording, which is what makes an ancestor recurse into a scope instead-/// of copying it. A scope counts as on one while its stamp equals the current stamp.-#[derive(Default)]-pub(crate) struct ScopeMarks {- stamps: Vec<u32>,- stamp: u32,+/// What a run recorded, and where the owners of its child scopes were when it did: a child that an ancestor moved+/// since records again though nothing pushed damage for it.+#[derive(Debug)]+pub(crate) struct RecordedRun {+ /// None where the run recorded nothing.+ pub chunk: Option<Arc<RecordedChunk>>,+ pub facts: OutputFacts,+ pub child_scope_placements: Box<[RowPlacement]>,}-impl ScopeMarks {- /// Starts a recording: the stamp advances so no scope counts as being on a damaged path yet.- pub(crate) fn begin_recording(&mut self) {- self.stamp = match self.stamp.checked_add(1) {- Some(stamp) => stamp,- None => {- self.stamps.clear();- 1- }- };- }-- /// Marks a scope, answering whether it was not marked yet.- fn mark(&mut self, id: ScopeId) -> bool {- if self.stamps.len() <= id.index() {- self.stamps.resize(id.index() + 1, 0);- }- std::mem::replace(&mut self.stamps[id.index()], self.stamp) != self.stamp- }-- pub(crate) fn is_on_damaged_path(&self, id: ScopeId) -> bool {- self.stamps.get(id.index()) == Some(&self.stamp)- }+#[derive(Debug)]+pub(crate) enum RecordedSegment {+ Run(RecordedRun),+ Walked(Arc<RecordedScope>),}-impl PaintOrderTree {- pub(crate) fn root(&self) -> ScopeId {- self.root- }-- pub(crate) fn root_entry(&self) -> ChildEntry {- self.root_entry- }-- #[cfg(test)]- pub(crate) fn scope_count(&self) -> usize {- self.nodes.iter().filter(|node| node.flags & NODE_OCCUPIED != 0).count()- }-- #[cfg(test)]- pub(crate) fn child_entry_capacity(&self) -> usize {- self.children.len()- }-- /// Every scope reachable from the root, in tree order, with its child list.- #[cfg(test)]- pub(crate) fn structure(&self) -> Vec<(ScopeId, PaintScope, Vec<ChildEntry>)> {- let mut structure = Vec::new();- let mut stack = vec![self.root];- while let Some(id) = stack.pop() {- if id.is_none() {- continue;- }- let children = self.children(id).to_vec();- for entry in children.iter().rev() {- if let ChildKey::Scope(child) = entry.key() {- stack.push(child);- }- }- structure.push((id, self.scope_of(id), children));- }- structure- }-- fn node(&self, id: ScopeId) -> &ScopeNode {- let node = &self.nodes[id.index()];- assert_eq!(node.generation, id.generation(), "stale paint scope id {id:?}");- debug_assert!(node.flags & NODE_OCCUPIED != 0, "freed paint scope id {id:?}");- node- }-- fn node_mut(&mut self, id: ScopeId) -> &mut ScopeNode {- let node = &mut self.nodes[id.index()];- assert_eq!(node.generation, id.generation(), "stale paint scope id {id:?}");- debug_assert!(node.flags & NODE_OCCUPIED != 0, "freed paint scope id {id:?}");- node- }-- pub(crate) fn scope_of(&self, id: ScopeId) -> PaintScope {- let node = self.node(id);- PaintScope {- owner: node.owner,- kind: scope_kind_from_code(node.kind),- }- }-- #[cfg(test)]- pub(crate) fn parent(&self, id: ScopeId) -> ScopeId {- self.node(id).parent- }-- pub(crate) fn children(&self, id: ScopeId) -> &[ChildEntry] {- let node = self.node(id);- let start = node.children_start as usize;- &self.children[start..start + node.children_len as usize]- }-- fn scope_in_slot(&self, owner: NodeSlotId, kind_code: u8) -> Option<ScopeId> {- let id = self.scopes_by_row.get(owner.slot_index() as usize)?[kind_code as usize];- if id.is_none() {- return None;- }- let node = &self.nodes[id.index()];- (node.generation == id.generation() && node.flags & NODE_OCCUPIED != 0 && node.owner == owner).then_some(id)- }-- /// The scope for a plan item under `parent`, if the tree has one. A scope allocated by the- /// current recording qualifies too; a caller copying from the published recording tells the- /// two apart by the parent's published child list.- pub(crate) fn published_scope(&self, scope: PaintScope, parent: ScopeId) -> Option<ScopeId> {- let kind_code = scope_kind_code(scope.kind);- if let Some(id) = self.scope_in_slot(scope.owner, kind_code)- && self.node(id).parent == parent- {- return Some(id);- }- let ids = self.duplicate_scopes.get(&(scope.owner, kind_code))?;- ids.iter().copied().find(|id| self.node(*id).parent == parent)- }-- /// Every scope a row owns, in kind order.- pub(crate) fn scopes_owned_by(&self, owner: NodeSlotId) -> SmallVec<[ScopeId; 5]> {- let mut scopes = SmallVec::new();- for code in 0..SCOPE_KIND_COUNT {- if let Some(id) = self.scope_in_slot(owner, code) {- scopes.push(id);- }- if !self.duplicate_scopes.is_empty()- && let Some(ids) = self.duplicate_scopes.get(&(owner, code))- {- scopes.extend(ids.iter().copied());- }- }- scopes- }-- fn register_scope(&mut self, id: ScopeId) {- let node = self.nodes[id.index()];- let index = node.owner.slot_index() as usize;- if self.scopes_by_row.len() <= index {- self.scopes_by_row- .resize(index + 1, [ScopeId::NONE; SCOPE_KIND_COUNT as usize]);- }- if self.scope_in_slot(node.owner, node.kind).is_some() {- self.duplicate_scopes- .entry((node.owner, node.kind))- .or_default()- .push(id);- } else {- self.scopes_by_row[index][node.kind as usize] = id;- }- }-- fn unregister_scope(&mut self, id: ScopeId) {- let node = self.nodes[id.index()];- let index = node.owner.slot_index() as usize;- let key = (node.owner, node.kind);- if self.scopes_by_row[index][node.kind as usize] == id {- // A duplicate of the same owner and kind, such as the replacement a scope gets when- // it moves to another parent, takes over the slot.- let promoted = self- .duplicate_scopes- .get_mut(&key)- .and_then(|ids| ids.pop())- .unwrap_or(ScopeId::NONE);- self.scopes_by_row[index][node.kind as usize] = promoted;- } else if let Some(ids) = self.duplicate_scopes.get_mut(&key) {- ids.retain(|candidate| *candidate != id);- }- if self.duplicate_scopes.get(&key).is_some_and(|ids| ids.is_empty()) {- self.duplicate_scopes.remove(&key);- }- }-- /// Marks the path from a scope to the root as damaged for this recording, stopping at the- /// first ancestor already marked.- pub(crate) fn mark_path_to_root_damaged(&self, id: ScopeId, marks: &mut ScopeMarks) {- let mut current = id;- while !current.is_none() {- let parent = self.node(current).parent;- if !marks.mark(current) {- break;- }- current = parent;- }- }-- /// Allocates a scope for this recording and registers it for its owner and kind.- pub(crate) fn allocate_scope(&mut self, scope: PaintScope, parent: ScopeId) -> ScopeId {- let node = ScopeNode {- owner: scope.owner,- parent,- children_start: 0,- children_len: 0,- kind: scope_kind_code(scope.kind),- flags: NODE_OCCUPIED,- generation: 1,- _padding: 0,- };- let id = if let Some(index) = self.free_nodes.pop() {- let slot = &mut self.nodes[index as usize];- debug_assert_eq!(slot.flags & NODE_OCCUPIED, 0);- let generation = slot.generation;- *slot = ScopeNode { generation, ..node };- ScopeId::new(index as usize, generation)- } else {- self.nodes.push(node);- ScopeId::new(self.nodes.len() - 1, 1)- };- self.register_scope(id);- id- }-- /// Installs the child list assembled for a scope. A list of the same length overwrites the- /// previous one in place; any other length takes new entries at the end of the arena.- pub(crate) fn set_children(&mut self, id: ScopeId, entries: &[ChildEntry]) {- let node = *self.node(id);- let len = u32::try_from(entries.len()).expect("paint-order tree exceeds u32 entries");- if node.children_len == len {- let start = node.children_start as usize;- self.children[start..start + entries.len()].copy_from_slice(entries);- } else {- let start = u32::try_from(self.children.len()).expect("paint-order tree exceeds u32 entries");- self.children.extend_from_slice(entries);- self.live_child_entries = self.live_child_entries - node.children_len + len;- let node = self.node_mut(id);- node.children_start = start;- node.children_len = len;- }- }-- /// Retires a scope no plan item matched, with its subtree. Its ids never match again and- /// its slots are free for the scopes this recording allocates next.- pub(crate) fn detach_scope(&mut self, id: ScopeId) {- let mut stack = vec![id];- while let Some(id) = stack.pop() {- let node = *self.node(id);- let start = node.children_start as usize;- for entry in &self.children[start..start + node.children_len as usize] {- if let ChildKey::Scope(child) = entry.key() {- stack.push(child);- }- }- self.live_child_entries -= node.children_len;- self.unregister_scope(id);- let slot = &mut self.nodes[id.index()];- slot.flags = 0;- slot.children_len = 0;- // A retired id never matches again; slots whose generation ran out stay unused.- if slot.generation < SCOPE_GENERATION_LIMIT {- slot.generation += 1;- self.free_nodes.push(id.index() as u32);- }- }- }-- /// Ends the recording with the root's entry, which describes the whole frame, and compacts- /// the child arena when garbage outgrows the live entries.- pub(crate) fn finish_recording(&mut self, root: ScopeId, entry: ChildEntry) {- self.root = root;- self.root_entry = entry;- if self.children.len() as u32 - self.live_child_entries > self.live_child_entries {- self.compact_child_entries();- }- }-- // Rebuilds the child arena from the live lists in tree order; nodes keep their ids.- fn compact_child_entries(&mut self) {- let mut compacted = Vec::with_capacity(self.live_child_entries as usize);- let mut stack = vec![self.root];- while let Some(id) = stack.pop() {- if id.is_none() {- continue;- }- let node = *self.node(id);- let start = node.children_start as usize;- let new_start = compacted.len() as u32;- compacted.extend_from_slice(&self.children[start..start + node.children_len as usize]);- self.nodes[id.index()].children_start = new_start;- for entry in compacted[new_start as usize..].iter().rev() {- if let ChildKey::Scope(child) = entry.key() {- stack.push(child);- }- }+impl RecordedSegment {+ pub(crate) fn facts(&self) -> OutputFacts {+ match self {+ Self::Run(run) => run.facts,+ Self::Walked(scope) => scope.facts,}- self.children = compacted;}}-#[cfg(test)]-mod tests {- use super::*;-- fn row(index: u32) -> NodeSlotId {- NodeSlotId::new(index, 1)- }-- fn output(bytes: u32) -> OutputSize {- OutputSize {- bytes,- ..OutputSize::default()- }- }-- fn context_scope(owner: NodeSlotId) -> PaintScope {- PaintScope::stacking_context(owner)- }-- fn foreground_scope(owner: NodeSlotId) -> PaintScope {- PaintScope {- owner,- kind: PaintScopeKind::Descendants(StackingContextPaintPhase::Foreground),- }- }-- // A root context with one foreground scope holding `leaf_count` leaf scopes of one- // producer each, recorded as the first frame.- fn record_first_frame(tree: &mut PaintOrderTree, leaf_count: u32) -> (ScopeId, ScopeId, Vec<ScopeId>) {- let root = tree.allocate_scope(context_scope(row(0)), ScopeId::NONE);- let foreground = tree.allocate_scope(foreground_scope(row(0)), root);- let mut leaves = Vec::new();- let mut foreground_children = Vec::new();- let mut foreground_output = OutputSize::default();- for index in 0..leaf_count {- let leaf = tree.allocate_scope(foreground_scope(row(1 + index)), foreground);- let leaf_output = output(16);- tree.set_children(leaf, &[ChildEntry::producer(ProducerKind::DrawForeground, leaf_output)]);- foreground_children.push(ChildEntry::scope(leaf, leaf_output));- foreground_output.add(leaf_output);- leaves.push(leaf);- }- tree.set_children(foreground, &foreground_children);- let mut root_output = output(32);- root_output.add(foreground_output);- tree.set_children(- root,- &[- ChildEntry::producer(ProducerKind::DrawBackground, output(32)),- ChildEntry::scope(foreground, foreground_output),- ],- );- tree.finish_recording(root, ChildEntry::scope(root, root_output));- (root, foreground, leaves)- }-- #[test]- fn scopes_keep_their_ids_and_sizes_add_up() {- let mut tree = PaintOrderTree::default();- let (root, foreground, leaves) = record_first_frame(&mut tree, 3);-- assert_eq!(tree.root(), root);- assert_eq!(tree.root_entry().output(), output(32 + 3 * 16));- assert_eq!(tree.published_scope(foreground_scope(row(0)), root), Some(foreground));- assert_eq!(- tree.published_scope(foreground_scope(row(2)), foreground),- Some(leaves[1])- );- assert_eq!(tree.published_scope(foreground_scope(row(2)), root), None);- assert_eq!(tree.scopes_owned_by(row(0)).as_slice(), &[root, foreground]);- assert_eq!(tree.children(foreground).len(), 3);- assert_eq!(tree.scope_of(leaves[0]), foreground_scope(row(1)));- assert_eq!(tree.parent(leaves[0]), foreground);- assert_eq!(tree.scope_count(), 5);- }-- #[test]- fn damaged_paths_are_marked_up_to_the_first_marked_ancestor() {- let mut tree = PaintOrderTree::default();- let (root, foreground, leaves) = record_first_frame(&mut tree, 2);- let mut marks = ScopeMarks::default();- marks.begin_recording();-- tree.mark_path_to_root_damaged(leaves[0], &mut marks);- assert!(marks.is_on_damaged_path(leaves[0]));- assert!(marks.is_on_damaged_path(foreground));- assert!(marks.is_on_damaged_path(root));- assert!(!marks.is_on_damaged_path(leaves[1]));-- marks.begin_recording();- assert!(!marks.is_on_damaged_path(leaves[0]));- assert!(!marks.is_on_damaged_path(root));- }-- #[test]- fn a_recording_replaces_child_lists_and_retires_detached_subtrees_at_once() {- let mut tree = PaintOrderTree::default();- let (root, foreground, leaves) = record_first_frame(&mut tree, 2);-- let added = tree.allocate_scope(foreground_scope(row(9)), foreground);- tree.set_children(added, &[ChildEntry::producer(ProducerKind::DrawForeground, output(8))]);- let children = [- ChildEntry::scope(leaves[1], output(16)),- ChildEntry::scope(added, output(8)),- ];- tree.set_children(foreground, &children);- tree.detach_scope(leaves[0]);- assert_eq!(tree.published_scope(foreground_scope(row(1)), foreground), None);- assert_eq!(tree.scope_count(), 4);- tree.finish_recording(root, ChildEntry::scope(root, output(32 + 16 + 8)));-- assert_eq!(tree.children(foreground), &children);- assert_eq!(tree.root_entry().output(), output(56));- assert_eq!(tree.published_scope(foreground_scope(row(9)), foreground), Some(added));-- // The retired slot is reused with a new generation, so the old id can never match.- let reused = tree.allocate_scope(foreground_scope(row(7)), foreground);- assert_eq!(reused.index(), leaves[0].index());- assert_ne!(reused, leaves[0]);- }-- #[test]- fn a_scope_moving_to_another_parent_takes_over_the_slot_its_predecessor_leaves() {- let mut tree = PaintOrderTree::default();- let (root, foreground, leaves) = record_first_frame(&mut tree, 2);-- // Row 1's foreground scope is listed under the root now; the old one is still there.- let moved = tree.allocate_scope(foreground_scope(row(1)), root);- assert_eq!(tree.published_scope(foreground_scope(row(1)), root), Some(moved));- assert_eq!(- tree.published_scope(foreground_scope(row(1)), foreground),- Some(leaves[0])- );- assert_eq!(tree.scopes_owned_by(row(1)).len(), 2);-- tree.detach_scope(leaves[0]);- assert_eq!(tree.published_scope(foreground_scope(row(1)), root), Some(moved));- assert_eq!(tree.scopes_owned_by(row(1)).as_slice(), &[moved]);- assert!(tree.duplicate_scopes.is_empty());- }+/// A walked scope as one recording recorded it.+#[derive(Debug)]+pub(crate) struct RecordedScope {+ pub scope: PaintScope,+ pub plan: Arc<SegmentedPlan>,+ /// One for each segment of the plan.+ pub segments: Vec<RecordedSegment>,+ pub facts: OutputFacts,+ /// Where the scope's owner was, which the producers of the owner in the scope's runs were recorded against.+ pub owner_placement: RowPlacement,+}- #[test]- fn a_slot_retired_many_times_keeps_its_ids_distinguishable_from_producers() {- let mut tree = PaintOrderTree::default();- let (root, foreground, _) = record_first_frame(&mut tree, 1);- for round in 0..300u32 {- for child in tree.children(foreground).to_vec() {- if let ChildKey::Scope(previous) = child.key() {- tree.detach_scope(previous);+impl RecordedScope {+ /// Hands `visit` the chunks of the scope in paint order.+ pub(crate) fn for_each_chunk(&self, visit: &mut impl FnMut(&Arc<RecordedChunk>)) {+ for segment in &self.segments {+ match segment {+ RecordedSegment::Run(run) => {+ if let Some(chunk) = &run.chunk {+ visit(chunk);+ }}+ RecordedSegment::Walked(scope) => scope.for_each_chunk(visit),}- let added = tree.allocate_scope(foreground_scope(row(100 + round)), foreground);- tree.set_children(added, &[ChildEntry::producer(ProducerKind::DrawForeground, output(8))]);- let entry = ChildEntry::scope(added, output(8));- assert_eq!(entry.key(), ChildKey::Scope(added));- tree.set_children(foreground, &[entry]);- tree.finish_recording(root, ChildEntry::scope(root, output(40)));- assert_eq!(- tree.published_scope(foreground_scope(row(100 + round)), foreground),- Some(added)- );}- assert_eq!(tree.scope_count(), 3);- }-- #[test]- fn same_length_child_lists_are_overwritten_in_place() {- let mut tree = PaintOrderTree::default();- let (root, foreground, leaves) = record_first_frame(&mut tree, 2);- let capacity = tree.child_entry_capacity();-- let grown = output(24);- tree.set_children(leaves[0], &[ChildEntry::producer(ProducerKind::DrawForeground, grown)]);- let children = [- ChildEntry::scope(leaves[0], grown),- ChildEntry::scope(leaves[1], output(16)),- ];- tree.set_children(foreground, &children);- tree.finish_recording(root, ChildEntry::scope(root, output(32 + 24 + 16)));-- assert_eq!(tree.children(foreground), &children);- assert_eq!(tree.child_entry_capacity(), capacity);- }-- #[test]- fn the_child_arena_stays_bounded_under_staggered_updates() {- let mut tree = PaintOrderTree::default();- let (root, foreground, leaves) = record_first_frame(&mut tree, 8);- let mut peak = 0;- for round in 0..4000u32 {- let leaf = leaves[(round % 8) as usize];- let leaf_output = output(16 + round % 3);- // Every other round the leaf gains or loses a producer, so its list changes length.- let leaf_children: Vec<ChildEntry> = if round % 2 == 0 {- vec![ChildEntry::producer(ProducerKind::DrawForeground, leaf_output)]- } else {- vec![- ChildEntry::producer(ProducerKind::DrawBackground, output(0)),- ChildEntry::producer(ProducerKind::DrawForeground, leaf_output),- ]- };- tree.set_children(leaf, &leaf_children);- let children: Vec<ChildEntry> = tree- .children(foreground)- .iter()- .map(|entry| match entry.key() {- ChildKey::Scope(id) if id == leaf => ChildEntry::scope(leaf, leaf_output),- _ => *entry,- })- .collect();- tree.set_children(foreground, &children);- let mut total = output(32);- for entry in &children {- total.add(entry.output());- }- tree.finish_recording(root, ChildEntry::scope(root, total));- peak = peak.max(tree.child_entry_capacity());- assert_eq!(tree.root_entry().output(), total);- }- let live = 2 + 8 + 2 * 8;- assert!(- peak <= live * 2 + 16,- "child arena grew to {peak} entries for {live} live ones"- );- assert_eq!(tree.scope_count(), 10);}}diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/background.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/background.rsindex 43b491c59d6..8b3ea9e1432 100644--- a/Libraries/LibWeb/Rust/src/painting/record/paint/background.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/background.rs@@ -891,7 +891,7 @@ fn paint_image_layer_in_current_space<O: Observer>((dest_rect.width, dest_rect.height),(dest_rect.width, dest_rect.height),);- let display_list_id = recorder.resources.vector_image_placeholder(+ let display_list_id = recorder.vector_image_placeholder(crate::painting::record::vector_images::VectorImageRenderRequest::new(vector_image_source,CssPixels::from_integer(i64::from(dest_rect.width)),diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/border_image.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/border_image.rsindex 711b6e1352a..188b7bcc8ad 100644--- a/Libraries/LibWeb/Rust/src/painting/record/paint/border_image.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/border_image.rs@@ -297,17 +297,15 @@ fn paint_vector_border_image_slice<O: Observer>(1.max((source_rect.width * rendered_scale.width).round() as i32),1.max((source_rect.height * rendered_scale.height).round() as i32),);- let display_list_id = recorder- .resources- .vector_image_placeholder(VectorImageRenderRequest::new(- image.source,- geometry.css_width,- geometry.css_height,- geometry.raster_scale,- image.content_identity,- recorder.vector_image_color_scheme(image.source.owner()),- recorder.vector_image_force_dark(),- ));+ let display_list_id = recorder.vector_image_placeholder(VectorImageRenderRequest::new(+ image.source,+ geometry.css_width,+ geometry.css_height,+ geometry.raster_scale,+ image.content_identity,+ recorder.vector_image_color_scheme(image.source.owner()),+ recorder.vector_image_force_dark(),+ ));let group = recorder.recorder.begin_repeated_tile();// The tile holds the whole image, offset so that the slice fills it, and clips away the rest.recorder.recorder.paint_vector_image_records(diff --git a/Libraries/LibWeb/Rust/src/painting/record/producers.rs b/Libraries/LibWeb/Rust/src/painting/record/producers.rsindex 1cb51696736..5b1a68e33ce 100644--- a/Libraries/LibWeb/Rust/src/painting/record/producers.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/producers.rs@@ -5,24 +5,31 @@*///! The producers of a frame: each records one kind of output for one row under the contexts it-//! needs, starting and ending at a closed group boundary with no ambient state, so its bytes can-//! be copied verbatim by a later frame. The recorder implements the assembly host with them.+//! needs, starting and ending at a closed group boundary with no ambient state, so the run of+//! producers a chunk holds can be drawn by a later frame as it is. The recorder implements the+//! assembly host with them.-use super::assemble::{AssemblyEvent, AssemblyHost, OutputPosition, ProducerOutcome, ScopeAction, ScopePlan};-use super::order_tree::ProducerKind;+use super::assemble::{AssemblyEvent, AssemblyHost, ItemCut, ProducerOutcome, ScopeAction, ScopePlan};+use super::order_tree::{ProducerKind, RecordedChunk, RowPlacement};use super::trace::{Action, Observer, Operation};use super::{PaintPhase, PaintRecorder};-use crate::css::css_pixels::CssPixelRect;+use crate::css::css_pixels::{CssPixelRect, CssPixels};use crate::layout::node_data::NodeSlotId;use crate::painting::display_list::commands::ContextRef;use crate::painting::force_dark::ForceDarkRole;-use crate::painting::paint_order_plan::{PaintScope, PaintScopePlan};-use crate::painting::paint_read::{GeometryRead, PaintRead};+use crate::painting::paint_order_plan::{PaintOrderItem, PaintProducer, PaintScope, PaintScopePlan};+use crate::painting::paint_read::GeometryRead;use crate::painting::record::damage::PaintDamage;use crate::painting::record::svg_resources::MaskLayerSet;+use crate::painting::{node_painting, paintable_geometry};use libgfx_rust::Color;use smallvec::SmallVec;-use std::ops::Range;+use std::sync::Arc;++/// The height in CSS pixels of a row of the grid the plans of walked scopes are cut along. A child scope taller+/// than a row is walked on its own, and a run ends where the next item starts in another row, so a run records about+/// a row of the document.+const GRID_ROW_HEIGHT_IN_CSS_PIXELS: i64 = 512;fn draw_phase(kind: ProducerKind) -> Option<PaintPhase> {match kind {@@ -171,7 +178,8 @@ impl<O: Observer> AssemblyHost for PaintRecorder<'_, O> {}self.live_producer = false;self.producer_reads_window_focus.set(false);- let start = self.output_position();+ let start = self.recorder.byte_size();+ let blocking_wheel_event_regions_before = self.blocking_wheel_event_region_count;self.observer.observe(|log| log.begin(Operation::Producer(owner, kind), Action::Record));match kind {@@ -199,12 +207,12 @@ impl<O: Observer> AssemblyHost for PaintRecorder<'_, O> {}}}- let end = self.output_position();+ let end = self.recorder.byte_size();if self.ink_bounds_audit.enabled {- self.verify_producer_ink(owner, kind, start.bytes as usize..end.bytes as usize);- self.verify_producer_against_open_scopes(owner, kind, start.bytes as usize..end.bytes as usize);+ self.verify_producer_ink(owner, kind, start..end);+ self.verify_producer_against_open_scopes(owner, kind, start..end);}- self.observer.observe(|log| log.end(end.bytes == start.bytes));+ self.observer.observe(|log| log.end(end == start));debug_assert!(self.recorder.is_producer_boundary(),"a producer ends at a closed group boundary without ambient state"@@ -212,64 +220,107 @@ impl<O: Observer> AssemblyHost for PaintRecorder<'_, O> {ProducerOutcome {live: self.live_producer,reads_window_focus: self.producer_reads_window_focus.get(),+ blocking_wheel_event_regions: self.blocking_wheel_event_region_count - blocking_wheel_event_regions_before,}}- fn output_position(&self) -> OutputPosition {- OutputPosition {- bytes: u32::try_from(self.recorder.byte_size()).expect("display list exceeds u32"),- blocking_wheel_event_regions: self.blocking_wheel_event_region_count,- }+ fn take_run_chunk(&mut self) -> Option<Arc<RecordedChunk>> {+ let chunk = self.recorder.take_chunk();+ let draws_vector_image_placeholders = std::mem::take(&mut self.run_draws_vector_image_placeholders);+ (!chunk.records.is_empty()).then(|| RecordedChunk::new(chunk, draws_vector_image_placeholders))}- fn copy_published(&mut self, bytes: Range<u32>, blocking_wheel_event_regions: u32) {- let frame = self- .source_recording- .as_ref()- .expect("clean output is copied from a published recording");- self.recorder.append_cached_commands(&frame.display_list, bytes);- self.blocking_wheel_event_region_count += blocking_wheel_event_regions;+ fn damage_of_row(&mut self, row: NodeSlotId) -> PaintDamage {+ // Nothing is recorded for what a box can be hit by: hit testing walks the rows.+ self.source.paint_damage_of_row(row).without(PaintDamage::ALL_HIT)}- fn damaged_rows(&mut self) -> Vec<NodeSlotId> {- let mut rows: Vec<NodeSlotId> = self.source.damaged_paint_rows().collect();- // A moved row moves its whole layout subtree, whose rows were not pushed themselves. A- // moved row inside that subtree is listed already and expands its own subtree, so the- // walk stops there, and a row expanded from another moved ancestor stops it as well.- let mut expanded = Vec::new();- for row in &rows {- if !self.source.paint_damage_of_row(*row).contains(PaintDamage::MOVED) {- continue;+ fn placement_of_row(&mut self, row: NodeSlotId) -> RowPlacement {+ use crate::painting::paintable_data::PaintableFlag;+ use std::hash::Hasher;+ // A fragmented inline is placed by the pieces its line root holds, and the offset of its own fragment is+ // the one layout left there last.+ let placed_with = if node_painting::is_fragmented_inline(self.source, row) {+ self.source.inline_pieces_root(row).unwrap_or(row)+ } else {+ row+ };+ let mut later_fragments = 0;+ if self+ .source+ .paintable_data(placed_with)+ .has_flag(PaintableFlag::HasLaterBoxFragments)+ {+ let mut digest = crate::fast_hash::fast_hasher();+ for fragment in paintable_geometry::absolute_border_box_rects_of_fragments(self.source, placed_with)+ .iter()+ .skip(1)+ {+ for coordinate in [fragment.x, fragment.y, fragment.width, fragment.height] {+ digest.write_i32(coordinate.raw_value());+ }}- let root = *row;- self.source- .for_each_node_in_layout_subtree_in_pre_order_with_pruning(root, |node| {- if node == root {- return true;- }- if self.source.paint_damage_of_row(node).contains(PaintDamage::MOVED) {- return false;- }- if !self.source.paintable_row_is_populated(node) {- return true;- }- let newly_expanded = self.moved_expansion.insert(node);- if newly_expanded {- expanded.push(node);- }- newly_expanded- });+ later_fragments = digest.finish();+ }+ RowPlacement {+ origin: paintable_geometry::absolute_rect(self.source, placed_with).location(),+ later_fragments,}- rows.extend(expanded);- rows}- fn effective_damage(&mut self, row: NodeSlotId) -> PaintDamage {- let mut damage = self.source.paint_damage_of_row(row);- if self.moved_expansion.contains(&row) {- damage |= PaintDamage::ALL_PRODUCERS | PaintDamage::MOVED;+ fn cut_at(&mut self, scope: PaintScope, item: PaintOrderItem) -> ItemCut {+ let rows = self.source;+ let grid_row_height = CssPixels::from_integer(if self.inputs.records_in_finest_runs {+ 1+ } else {+ GRID_ROW_HEIGHT_IN_CSS_PIXELS+ });+ let grid_row_at = |block_start: CssPixels| {+ Some(i64::from(block_start.raw_value()).div_euclid(i64::from(grid_row_height.raw_value())) as i32)+ };+ let line_root = || {+ if node_painting::has_lines(rows, scope.owner) {+ scope.owner+ } else {+ rows.paintable_data(scope.owner).containing_block+ }+ };+ match item {+ PaintOrderItem::Scope(child) => {+ // The pieces of an inline box are spread over its line root's lines: it stays with what is next+ // to it in the plan.+ if node_painting::is_fragmented_inline(rows, child.owner) {+ return ItemCut::InRun { grid_row: None };+ }+ if crate::painting::style_queries::is_scroll_container(rows, child.owner) {+ return ItemCut::Walked;+ }+ match rows.absolute_ink_overflow_rect(child.owner) {+ Some(ink) if ink.height <= grid_row_height => ItemCut::InRun {+ grid_row: grid_row_at(ink.y),+ },+ _ => ItemCut::Walked,+ }+ }+ PaintOrderItem::Producer(PaintProducer::TextFragment(index)) => {+ let side = rows.committed_side_data(line_root());+ let fragment = &side.fragments()[index as usize];+ ItemCut::InRun {+ grid_row: grid_row_at(crate::painting::text_fragment::absolute_rect(rows, fragment).y),+ }+ }+ PaintOrderItem::Producer(PaintProducer::InlinePiece(index)) => {+ let root = line_root();+ let positions = self.line_root_positions(root);+ let side = rows.committed_side_data(root);+ let piece = &side.inline_box_pieces()[index as usize];+ let line = positions.of_line(side.lines(), piece.line_index as usize);+ ItemCut::InRun {+ grid_row: grid_row_at(piece.border_box_rect.y + line.y),+ }+ }+ PaintOrderItem::Producer(_) => ItemCut::InRun { grid_row: None },}- damage}// SVG content is recorded by its root.diff --git a/Libraries/LibWeb/Rust/src/painting/record/publish.rs b/Libraries/LibWeb/Rust/src/painting/record/publish.rsindex 8f411a8a99a..2fa4df072d1 100644--- a/Libraries/LibWeb/Rust/src/painting/record/publish.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/publish.rs@@ -5,6 +5,7 @@*/use crate::layout::LayoutNodeArena;+use crate::painting::display_list::chunks::Chunk;use crate::painting::display_list::commands::{DisplayListCommandType, DisplayListResourceId, PaintVectorImage};use crate::painting::display_list_resources::{DisplayListResources, summary_of};use crate::painting::host::FfiRecordingPublishCallbacks;@@ -56,29 +57,51 @@ pub(crate) fn render_vector_images(.collect()}-/// Patches the placeholders of SVG images in `output` with the ids of `vector_images`, one for each image.+/// Patches the placeholders of SVG images in `output` with the ids of `vector_images`, one for each image: finishes+/// every chunk of the recording that draws one, and the display list's tape with it.fn patch_vector_image_placeholders(output: &mut RecordingOutput, vector_images: &[Arc<VectorImageRecords>]) {- let display_list = std::sync::Arc::make_mut(&mut output.display_list);let id_field_offset = std::mem::offset_of!(PaintVectorImage, vector_image_id);- let mut patch_offsets = Vec::new();- crate::painting::display_list::nested_records::for_each_command_including_nested(- &display_list.bytes,- &mut |command_type, payload_offset, payload| {- if command_type != DisplayListCommandType::PaintVectorImage {- return;- }- let id = crate::painting::display_list::builder::read_command::<PaintVectorImage>(payload).vector_image_id;- if is_vector_image_placeholder(id) {- patch_offsets.push((- payload_offset + id_field_offset,- vector_images[vector_image_placeholder_index(id)].id(),- ));- }- },+ let chunks = Arc::clone(&output.chunks);+ let display_list = Arc::make_mut(&mut output.display_list);+ debug_assert_eq!(+ chunks.len(),+ display_list.chunks.len(),+ "a tape holds one chunk for each of the list's");- for (offset, resolved_id) in patch_offsets {- display_list.bytes[offset..offset + std::mem::size_of::<u64>()]- .copy_from_slice(&DisplayListResourceId(resolved_id).0.to_ne_bytes());+ let mut chunk_start = 0;+ for (index, chunk) in chunks.iter().enumerate() {+ let chunk_end = display_list.chunks[index].byte_end as usize;+ let records = chunk_start..chunk_end;+ chunk_start = chunk_end;+ if !chunk.draws_vector_image_placeholders() || chunk.finished().is_some() {+ continue;+ }+ let mut patch_offsets = Vec::new();+ crate::painting::display_list::nested_records::for_each_command_including_nested(+ &display_list.bytes[records.clone()],+ &mut |command_type, payload_offset, payload| {+ if command_type != DisplayListCommandType::PaintVectorImage {+ return;+ }+ let id =+ crate::painting::display_list::builder::read_command::<PaintVectorImage>(payload).vector_image_id;+ if is_vector_image_placeholder(id) {+ patch_offsets.push((+ records.start + payload_offset + id_field_offset,+ vector_images[vector_image_placeholder_index(id)].id(),+ ));+ }+ },+ );+ for &(offset, resolved_id) in &patch_offsets {+ display_list.bytes[offset..offset + std::mem::size_of::<u64>()]+ .copy_from_slice(&DisplayListResourceId(resolved_id).0.to_ne_bytes());+ }+ let finished = chunk.finish(Chunk::named(+ display_list.bytes[records].to_vec(),+ chunk.recorded().runs.clone(),+ ));+ display_list.chunks[index].id = finished.id;}}@@ -307,7 +330,7 @@ impl HitTestItemsOnScreen {}/// Takes the output of a recording that presented itself in: what hit testing reads of the frame on screen, and for a-/// recording that publishes, the source the next recording copies from. Resource callbacks and verification have+/// recording that publishes, the source the next recording reuses from. Resource callbacks and verification have/// finished, so the new recording may become the source.pub(crate) fn take_in_presented_output(recorder: &mut RecorderState,diff --git a/Libraries/LibWeb/Rust/src/painting/record/recorder_state.rs b/Libraries/LibWeb/Rust/src/painting/record/recorder_state.rsindex 172b5b63264..70b646e0bc5 100644--- a/Libraries/LibWeb/Rust/src/painting/record/recorder_state.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/recorder_state.rs@@ -8,64 +8,45 @@ use crate::css::css_pixels::CssPixelRect;use crate::layout::node_data::NodeSlotId;use crate::painting::record::RecordingOutput;use crate::painting::record::inputs::RecordingInputs;-use crate::painting::record::order_tree::{PaintOrderTree, PaintOrderTreeAccess};use crate::painting::record::scratch::RecordingScratch;use std::cell::RefCell;-use std::sync::{Arc, Mutex, MutexGuard, PoisonError};+use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};+/// Counts the recordings of a document's host that published. A fork of the recorder state copies from the+/// recording that was published when it forked, and tells by the count when the host has published another since.#[derive(Default)]-struct VersionedPaintOrderTree {- tree: PaintOrderTree,- rewrites: u64,+pub(crate) struct PublishedRecordingCount {+ shared: Arc<AtomicU64>,+ as_of_fork: Option<u64>,}-/// A hold on a document's one paint-order tree, which only the recordings of its host rewrite. A fork of the recorder-/// state reads the tree as the recording it forked from left it, up to the next recording that rewrites it.-#[derive(Default)]-pub(crate) struct PaintOrderTreeHandle {- shared: Arc<Mutex<VersionedPaintOrderTree>>,- reads_as_of: Option<u64>,-}--impl PaintOrderTreeHandle {- fn lock(&self) -> MutexGuard<'_, VersionedPaintOrderTree> {- self.shared.lock().unwrap_or_else(PoisonError::into_inner)- }-- fn reader(&self) -> Self {+impl PublishedRecordingCount {+ fn fork(&self) -> Self {Self {shared: Arc::clone(&self.shared),- reads_as_of: Some(self.lock().rewrites),+ as_of_fork: Some(self.shared.load(Ordering::Acquire)),}}- pub(crate) fn is_reader(&self) -> bool {- self.reads_as_of.is_some()+ pub(crate) fn is_of_a_fork(&self) -> bool {+ self.as_of_fork.is_some()}- /// Whether the tree is as this hold first found it, or this hold is the host's, which always reads it as it is.- pub(crate) fn reads_current_tree(&self) -> bool {- self.reads_as_of.is_none_or(|rewrites| rewrites == self.lock().rewrites)+ /// Whether the host published no recording since this fork was made. The host's own count is always current.+ pub(crate) fn is_current(&self) -> bool {+ self.as_of_fork+ .is_none_or(|count| count == self.shared.load(Ordering::Acquire))}- /// Runs `recording` on the tree, which it rewrites where `publishes_recording` and this hold is the host's, and- /// otherwise only reads. Answers what it answered, and whether it rewrote the tree.- pub(crate) fn with_access<R>(- &self,- publishes_recording: bool,- recording: impl FnOnce(PaintOrderTreeAccess<'_>) -> R,- ) -> (R, bool) {- let mut held = self.lock();- let held = &mut *held;- let rewrites = publishes_recording && !self.is_reader();- let access = match rewrites {- true => {- held.rewrites += 1;- PaintOrderTreeAccess::Rewrites(&mut held.tree)- }- false => PaintOrderTreeAccess::Reads(&held.tree),- };- (recording(access), rewrites)+ /// Answers whether a recording that asks to publish does: only the host's recordings publish. Counts it where+ /// it does.+ pub(crate) fn note_recording(&self, asks_to_publish: bool) -> bool {+ let publishes = asks_to_publish && !self.is_of_a_fork();+ if publishes {+ self.shared.fetch_add(1, Ordering::AcqRel);+ }+ publishes}}@@ -74,11 +55,9 @@ impl PaintOrderTreeHandle {/// is in it, so it moves with the recording rather than being shared with what it reads.#[derive(Default)]pub(crate) struct RecorderState {- /// The last recording that published, which the next one copies clean output from.+ /// The last recording that published, which the next one reuses clean output from.pub(crate) published_recording: Option<Arc<RecordingOutput>>,- /// The paint-order tree describing the published recording; a recording that publishes- /// appends to it and publication or discarding decides what stays.- pub(crate) paint_order_tree: PaintOrderTreeHandle,+ pub(crate) published_recording_count: PublishedRecordingCount,/// The recording's workspace, whose tables one recording leaves for the next to reuse.pub(crate) scratch: RecordingScratch,/// The absolute rects the recordings computed, which stay valid while the document's geometry@@ -90,11 +69,11 @@ pub(crate) struct RecorderState {impl RecorderState {/// A fork of the recorder state, for a fork of the document's render state to record with: it copies clean output- /// from the same recording, reads the same paint-order tree, and keeps no scratch or memo of its own.+ /// from the same recording, and keeps no scratch or memo of its own.pub(crate) fn fork(&self) -> Self {Self {published_recording: self.published_recording.clone(),- paint_order_tree: self.paint_order_tree.reader(),+ published_recording_count: self.published_recording_count.fork(),scratch: Default::default(),absolute_rects: Default::default(),published_inputs: self.published_inputs.clone(),@@ -129,63 +108,34 @@ const _: () = {};impl RecorderState {- /// A recording that publishes assembles its frame in the retained paint-order tree, which no- /// longer describes the published recording once that recording is dropped: the next recording- /// copies nothing from it and records from scratch into a tree of its own.+ /// Forgets the published recording: the next recording copies nothing and records from scratch.pub(crate) fn forget_published_recording(&mut self) {self.published_recording = None;- self.paint_order_tree = Default::default();}}#[cfg(test)]mod tests {use super::*;- use crate::painting::paint_order_plan::PaintScope;- use crate::painting::record::order_tree::{ChildEntry, OutputSize, ScopeId};-- fn publish_a_tree(handle: &PaintOrderTreeHandle) -> bool {- let (_, rewrote) = handle.with_access(true, |mut access| {- if let Some(tree) = access.rewrites() {- let scope = PaintScope::stacking_context(NodeSlotId::new(1, 1));- let root = tree.allocate_scope(scope, ScopeId::NONE);- tree.finish_recording(root, ChildEntry::scope(root, OutputSize::default()));- }- });- rewrote- }-- fn scope_count(handle: &PaintOrderTreeHandle) -> usize {- handle.with_access(false, |access| access.read().scope_count()).0- }#[test]- fn a_fork_reads_the_tree_of_its_frame_until_the_host_rewrites_it() {- let mut host = RecorderState::default();- assert!(publish_a_tree(&host.paint_order_tree));+ fn a_fork_copies_from_its_recording_until_the_host_publishes_another() {+ let host = RecorderState::default();+ assert!(host.published_recording_count.note_recording(true));let fork = host.fork();- assert!(fork.paint_order_tree.is_reader());- assert!(!host.paint_order_tree.is_reader());- assert_eq!(scope_count(&fork.paint_order_tree), 1);+ assert!(fork.published_recording_count.is_of_a_fork());+ assert!(!host.published_recording_count.is_of_a_fork());- // A recording of the host that publishes nothing leaves the tree as the fork read it.- scope_count(&host.paint_order_tree);- assert!(fork.paint_order_tree.reads_current_tree());+ // A recording of the host that publishes nothing leaves the fork's recording the published one.+ assert!(!host.published_recording_count.note_recording(false));+ assert!(fork.published_recording_count.is_current());- // The fork never rewrites the tree, whatever its recording publishes.- assert!(!publish_a_tree(&fork.paint_order_tree));- assert!(fork.paint_order_tree.reads_current_tree());+ // The fork never publishes, whatever its recording asks.+ assert!(!fork.published_recording_count.note_recording(true));+ assert!(fork.published_recording_count.is_current());- assert!(publish_a_tree(&host.paint_order_tree));- assert!(!fork.paint_order_tree.reads_current_tree());- assert!(host.paint_order_tree.reads_current_tree());-- // Forgetting the published recording starts a tree of the host's own, and leaves the one the fork holds.- let fork = host.fork();- let scopes_the_fork_reads = scope_count(&fork.paint_order_tree);- host.forget_published_recording();- assert_eq!(scope_count(&host.paint_order_tree), 0);- assert_eq!(scope_count(&fork.paint_order_tree), scopes_the_fork_reads);- assert!(fork.paint_order_tree.reads_current_tree());+ assert!(host.published_recording_count.note_recording(true));+ assert!(!fork.published_recording_count.is_current());+ assert!(host.published_recording_count.is_current());}}diff --git a/Libraries/LibWeb/Rust/src/painting/record/scratch.rs b/Libraries/LibWeb/Rust/src/painting/record/scratch.rsindex 0b0b04dc62a..f3cbc4d736d 100644--- a/Libraries/LibWeb/Rust/src/painting/record/scratch.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/scratch.rs@@ -7,7 +7,6 @@use crate::layout::node_data::NodeSlotId;use crate::painting::display_list::commands::SpatialNodeIndex;use crate::painting::record::hit_test_items::HitTestFacts;-use crate::painting::record::order_tree::ScopeMarks;use crate::painting::record::paint::text::SelectionStyleAnswer;use crate::painting::record::{BasePaintFacts, PatternTileKey};use std::collections::HashMap;@@ -37,8 +36,8 @@ pub(crate) struct RecordingScratch {recording_stamp: u32,base_paint_facts: Vec<StampedEntry<BasePaintFacts>>,hit_test_facts: Vec<StampedEntry<HitTestFacts>>,- pub(super) scope_marks: ScopeMarks,- pub(super) pattern_tile_records: HashMap<PatternTileKey, Arc<Vec<u8>>>,+ /// The records of each pattern tile, and whether they draw a placeholder for an SVG image.+ pub(super) pattern_tile_records: HashMap<PatternTileKey, (Arc<Vec<u8>>, bool)>,pub(super) selection_style_cache: HashMap<u32, Arc<SelectionStyleAnswer>>,pub(super) search_text_style_cache: HashMap<u32, Arc<SelectionStyleAnswer>>,pub(super) search_text_current_style_cache: HashMap<u32, Arc<SelectionStyleAnswer>>,diff --git a/Libraries/LibWeb/Rust/src/painting/record/traversal.rs b/Libraries/LibWeb/Rust/src/painting/record/traversal.rsindex 5314c95d9ca..5e7fb5cf814 100644--- a/Libraries/LibWeb/Rust/src/painting/record/traversal.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/traversal.rs@@ -7,8 +7,8 @@use crate::painting::record::trace::Observer;use super::{PaintPhase, PaintRecorder};-use crate::css::style::fast_hash::FastSet;use crate::layout::node_data::NodeSlotId;+use crate::painting::display_list::builder::RecordedDisplayList;use crate::painting::display_list::commands::ContextRef;use crate::painting::display_list::device_pixels::DevicePixelConverter;use crate::painting::display_list::recorder::DisplayListRecorder;@@ -16,9 +16,9 @@ use crate::painting::node_painting;use crate::painting::paint_order_plan::PaintScope;use crate::painting::paint_read::{GeometryRead, PaintSource};use crate::painting::record::RecordingInputs;-use crate::painting::record::assemble::{Assembler, frame_is_unchanged};+use crate::painting::record::assemble::{Assembler, AssemblyHost, frame_is_unchanged};use crate::painting::record::frame_inputs::FrameInputs;-use crate::painting::record::order_tree::{PaintOrderTreeAccess, ProducerKind};+use crate::painting::record::order_tree::{ProducerKind, RecordedChunk};use crate::painting::record::paint::background_resolution::root_background_canvas_rect;use crate::painting::record::resources::RecordingResourceManifest;use crate::painting::record::scratch::RecordingScratch;@@ -30,7 +30,6 @@ use std::sync::Arc;pub(crate) fn record_display_list(source: &PaintSource<'_>,scratch: &mut RecordingScratch,- tree: PaintOrderTreeAccess<'_>,viewport: NodeSlotId,inputs: &RecordingInputs,source_recording: Option<Arc<RecordingOutput>>,@@ -39,7 +38,7 @@ pub(crate) fn record_display_list(scratch.begin_recording(source.frame().paintable_row_capacity());macro_rules! record {($observer:ty) => {- record_display_list_impl::<$observer>(source, scratch, tree, viewport, inputs, source_recording)+ record_display_list_impl::<$observer>(source, scratch, viewport, inputs, source_recording)};}let result = if trace {@@ -51,10 +50,16 @@ pub(crate) fn record_display_list(result}+/// The tape of a display list of `chunks`, each as its recording or the publication of that recording left it.+fn tape_of(chunks: &[Arc<RecordedChunk>]) -> Arc<RecordedDisplayList> {+ Arc::new(RecordedDisplayList::of_chunks(+ chunks.iter().map(|chunk| &**chunk.latest()),+ ))+}+fn record_display_list_impl<O: Observer>(source: &PaintSource<'_>,scratch: &mut RecordingScratch,- tree: PaintOrderTreeAccess<'_>,viewport: NodeSlotId,inputs: &RecordingInputs,source_recording: Option<Arc<RecordingOutput>>,@@ -67,7 +72,7 @@ fn record_display_list_impl<O: Observer>(inputs.uncaptured.root_background_source.root_layout_node,inputs.css_viewport_rect,);- // The published recording is copied from while every input its producers read is unchanged and+ // The published recording is reused from while every input its producers read is unchanged and// no push asked for everything; otherwise this frame records from scratch.let source_is_usable = source_recording.as_ref()@@ -89,10 +94,10 @@ fn record_display_list_impl<O: Observer>(viewport,ink_bounds_audit: super::ink_bounds::InkBoundsAudit::new(),source_recording,+ run_draws_vector_image_placeholders: false,live_producer: false,producer_reads_window_focus: std::cell::Cell::new(false),line_root_positions: None,- moved_expansion: FastSet::default(),blocking_wheel_event_region_count: 0,records_per_box_wheel_hit_test_targets: frame_inputs.records_per_box_wheel_hit_test_targets(),observer: O::default(),@@ -103,70 +108,86 @@ fn record_display_list_impl<O: Observer>(.observer.observe(|log| log.damage = Some(source.frame().damage().summary()));let root_group_color = recorder.record_canvas();- let prologue_bytes = u32::try_from(recorder.recorder.byte_size()).expect("display list exceeds u32");+ let prologue = recorder.take_run_chunk();+ let prologue_id = prologue.as_ref().map(|chunk| chunk.recorded().id);let has_inspector_overlays = inputs.inspector_highlight.is_some()|| inputs.grid_overlays.is_some()|| !inputs.flex_overlays.is_empty()|| inputs.caret_debug_rect.is_some();let root_scope = PaintScope::stacking_context(viewport);- // Nothing was pushed and nothing records every frame: the published tape is this frame,- // which lets the compositor skip its update as well.+ // The scopes the published recording walked, where it can be reused from.+ let published_root = recorder+ .source_recording+ .as_ref()+ .and_then(|frame| frame.recorded_root.clone());+ // Nothing was pushed and nothing records every frame: the published chunks are this frame's, which lets the+ // compositor skip its update as well.let unchanged_frame = recorder.source_recording.as_ref()- .filter(|frame| {- frame_is_unchanged(tree.read(), !source.frame().damage().is_empty(), window_focus_changed)+ .zip(published_root.as_ref())+ .filter(|(frame, root)| {+ frame_is_unchanged(root, !source.frame().damage().is_empty(), window_focus_changed)&& !has_inspector_overlays- && frame.prologue_bytes == prologue_bytes- && recorder.recorder.bytes() == &frame.display_list.bytes[..prologue_bytes as usize]+ && frame.prologue_id == prologue_id})- .map(|frame| frame.display_list.clone());- let display_list = match unchanged_frame {- Some(display_list) => {+ .map(|(frame, root)| {+ (+ Arc::clone(&frame.chunks),+ Arc::clone(&frame.display_list),+ Arc::clone(root),+ )+ });+ let reuses_from_published_recording = published_root.is_some() && unchanged_frame.is_none();+ let (chunks, display_list, recorded_root) = match unchanged_frame {+ Some((chunks, display_list, root)) => {recorder.observer.observe(|log| log.leaf(Operation::Scope(root_scope), Action::Copy, false));- recorder.blocking_wheel_event_region_count = tree.read().root_entry().output().blocking_wheel_event_regions;- display_list+ (chunks, display_list, Some(root))}None if inputs.records_without_visual_contexts => {recorder.trace_paint(Operation::Named(None, "svg-image-document"), |recorder| {recorder.record_svg_image_document(viewport);});- Arc::new(recorder.recorder.into_builder().finish())+ let chunks: Arc<[Arc<RecordedChunk>]> = prologue.into_iter().chain(recorder.take_run_chunk()).collect();+ let display_list = tape_of(&chunks);+ (chunks, display_list, None)}None => {- let source_prologue_bytes = recorder.source_recording.as_ref().map(|frame| frame.prologue_bytes);- let mut marks = std::mem::take(&mut recorder.scratch.scope_marks);- Assembler::new(- &mut recorder,- tree,- &mut marks,- source_prologue_bytes,- window_focus_changed,- )- .assemble_root(root_scope);- recorder.scratch.scope_marks = marks;+ let recorded_root =+ Assembler::new(&mut recorder, window_focus_changed).assemble_root(root_scope, published_root.as_ref());+ let mut chunks: Vec<Arc<RecordedChunk>> = prologue.into_iter().collect();+ recorded_root.for_each_chunk(&mut |chunk| chunks.push(Arc::clone(chunk)));if has_inspector_overlays {recorder.trace_paint(Operation::Named(None, "inspector-overlays"),crate::painting::record::paint::inspector_overlay::record_inspector_overlays,);+ chunks.extend(recorder.take_run_chunk());}- Arc::new(recorder.recorder.into_builder().finish())+ let chunks: Arc<[Arc<RecordedChunk>]> = chunks.into();+ let display_list = tape_of(&chunks);+ (chunks, display_list, Some(recorded_root))}};recorder.ink_bounds_audit.report();+ let has_blocking_wheel_event_listeners = match &recorded_root {+ Some(root) => root.facts.blocking_wheel_event_regions > 0,+ None => recorder.blocking_wheel_event_region_count > 0,+ };let output = RecordingOutput {recorded_structural_epoch: structural_epoch,visual_context_tree: paint_state.visual_context_tree.clone(),frame_inputs,root_background_canvas_rect,- prologue_bytes,+ prologue_id,root_group_color,hit_test_items_stamp: source.hit_test_items_stamp(),+ chunks,display_list,- has_blocking_wheel_event_listeners: recorder.blocking_wheel_event_region_count > 0,+ recorded_root,+ has_blocking_wheel_event_listeners,wheel_event_listener_state_generation: inputs.wheel_event_listener_state_generation,is_identical_to_published_recording: false,window_is_focused: inputs.window_is_focused,@@ -177,10 +198,100 @@ fn record_display_list_impl<O: Observer>(surface_clear_color: None,async_scrolling_metadata: None,};- RecordingResult {- output,- resources: recorder.resources,+ let resources = recorder.resources;+ if reuses_from_published_recording && reused_output_is_verified() {+ let from_scratch =+ record_display_list_impl::<super::trace::NoTrace>(source, scratch, viewport, inputs, None).output;+ require_same_recording(&output, &from_scratch);+ }+ RecordingResult { output, resources }+}++fn reused_output_is_verified() -> bool {+ static VERIFIED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *VERIFIED.get_or_init(|| cfg!(debug_assertions) || std::env::var_os("LIBWEB_VERIFY_PAINT_REUSE").is_some())+}++/// Requires a recording that reused clean output of the published one to be the recording the same frame gives when+/// everything is recorded: a difference is output that was reused though what it shows changed.+fn require_same_recording(assembled: &RecordingOutput, from_scratch: &RecordingOutput) {+ use crate::painting::display_list::builder::for_each_command;+ use crate::painting::display_list::chunks::{chunk_id, chunks_of};+ use crate::painting::display_list::commands::{DisplayListCommandType, PaintVectorImage};+ // A command that paints an SVG image is recorded with a placeholder for the image's records, which publication+ // replaces with the id of the records the host rendered. A reused command names those records already.+ let without_vector_image_ids = |bytes: &[u8]| {+ let mut bytes = bytes.to_vec();+ let id_field = std::mem::offset_of!(PaintVectorImage, vector_image_id);+ let mut id_offsets = Vec::new();+ crate::painting::display_list::nested_records::for_each_command_including_nested(+ &bytes,+ &mut |command_type, payload_offset, _| {+ if command_type == DisplayListCommandType::PaintVectorImage {+ id_offsets.push(payload_offset + id_field);+ }+ },+ );+ for offset in id_offsets {+ bytes[offset..offset + std::mem::size_of::<u64>()].fill(0);+ }+ bytes+ };+ let (assembled_list, scratch_list) = (&assembled.display_list, &from_scratch.display_list);+ let assembled_bytes = without_vector_image_ids(&assembled_list.bytes);+ let scratch_bytes = without_vector_image_ids(&scratch_list.bytes);+ if assembled_bytes != scratch_bytes {+ let first_differing_byte = assembled_bytes+ .iter()+ .zip(&scratch_bytes)+ .position(|(copied, recorded)| copied != recorded)+ .unwrap_or(assembled_bytes.len().min(scratch_bytes.len()));+ let command_at = |bytes: &[u8]| {+ let mut found = None;+ for_each_command(bytes, |header, offset, _| {+ if offset <= first_differing_byte {+ found = Some((offset, header.command_type.name(), header.bounding_rect));+ }+ });+ found+ };+ panic!(+ "A recording reused output that recording from scratch replaces: {} bytes against {}, differing from byte {first_differing_byte}, in {:?} where recording from scratch has {:?}",+ assembled_list.bytes.len(),+ scratch_list.bytes.len(),+ command_at(&assembled_list.bytes),+ command_at(&scratch_list.bytes)+ );}+ assert!(+ assembled_list.command_runs == scratch_list.command_runs,+ "A recording reused command runs that recording from scratch replaces"+ );+ let chunk_ends = |list: &RecordedDisplayList| -> Vec<(u32, u32)> {+ list.chunks+ .iter()+ .map(|chunk| (chunk.byte_end, chunk.run_end))+ .collect()+ };+ assert!(+ chunk_ends(assembled_list) == chunk_ends(scratch_list),+ "A recording cut its tape into other chunks than recording from scratch does"+ );+ for (chunk, bytes, runs) in chunks_of(+ &assembled_list.bytes,+ &assembled_list.command_runs,+ &assembled_list.chunks,+ ) {+ let chunk_start = chunk.byte_end - bytes.len() as u32;+ assert!(+ chunk.id == chunk_id(bytes, runs, chunk_start),+ "A recording reused a chunk under a name that is not the name of what it holds"+ );+ }+ assert!(+ assembled.has_blocking_wheel_event_listeners == from_scratch.has_blocking_wheel_event_listeners,+ "A recording reused wheel regions that recording from scratch replaces"+ );}impl<O: Observer> PaintRecorder<'_, O> {diff --git a/Libraries/LibWeb/Rust/src/painting/recording_slot.rs b/Libraries/LibWeb/Rust/src/painting/recording_slot.rsindex 9046f937582..92fc33e3d0a 100644--- a/Libraries/LibWeb/Rust/src/painting/recording_slot.rs+++ b/Libraries/LibWeb/Rust/src/painting/recording_slot.rs@@ -474,23 +474,21 @@ pub(crate) fn record_frame() -> (PendingRecording, Option<PendingRecordingTrace>) {let RecorderState {published_recording,- paint_order_tree,+ published_recording_count,scratch,absolute_rects,published_inputs,} = recorder;let source = PaintSource::new(&frame, absolute_rects);- let (mut recording, publishes_recording) = paint_order_tree.with_access(inputs.publishes_recording, |tree| {- crate::painting::record::traversal::record_display_list(- &source,- scratch,- tree,- viewport,- &inputs,- published_recording.clone(),- trace_recordings,- )- });+ let publishes_recording = published_recording_count.note_recording(inputs.publishes_recording);+ let mut recording = crate::painting::record::traversal::record_display_list(+ &source,+ scratch,+ viewport,+ &inputs,+ published_recording.clone(),+ trace_recordings,+ );let output = &mut recording.output;output.surface_clear_color = inputs.surface_clear_color;output.async_scrolling_metadata = inputs.async_scrolling_metadata.clone().map(|mut metadata| {diff --git a/Libraries/LibWeb/Rust/src/painting/vector_image_records.rs b/Libraries/LibWeb/Rust/src/painting/vector_image_records.rsindex 50e2ca50d9a..176ab350363 100644--- a/Libraries/LibWeb/Rust/src/painting/vector_image_records.rs+++ b/Libraries/LibWeb/Rust/src/painting/vector_image_records.rs@@ -10,6 +10,7 @@use crate::painting::display_list::builder::{HEADER_SIZE, RecordedDisplayList, for_each_command, read_command, read_header,};+use crate::painting::display_list::chunks::DisplayListChunk;use crate::painting::display_list::commands::{DeclareMaskContent, DisplayListCommandHeader, DisplayListCommandRun, DisplayListCommandType, DisplayListDataSpan,DisplayListGradientColorStops, DisplayListGradientPaintStyle, DisplayListInlineClip, DisplayListPaintStyle,@@ -314,7 +315,22 @@ pub(crate) fn display_list_holding_vector_image_records(debug_assert!(display_list.command_runs.is_empty() || read_header(&bytes).payload_size as usize + HEADER_SIZE <= bytes.len());- RecordedDisplayList { bytes, command_runs }+ let chunks = display_list+ .chunks+ .iter()+ .map(|chunk| DisplayListChunk {+ byte_end: chunk.run_end.checked_sub(1).map_or(0, |last_run| {+ let run = &command_runs[last_run as usize];+ run.offset + run.size+ }),+ ..*chunk+ })+ .collect();+ RecordedDisplayList {+ bytes,+ command_runs,+ chunks,+ }}#[cfg(test)]diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rsindex e2fc79af6b4..d07149a3981 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs@@ -1693,8 +1693,8 @@ impl ClockRecorder {/// Paint thread. Only the host renders an SVG image: the frame draws those the recording published last drew, as the/// host rendered them for it, and leaves the frame to the host where it draws another.fn record(mut self, frame: SampledFrame<RecordedFrame>, presenting: &mut Presenting) -> Self {- debug_assert!(self.recorder.paint_order_tree.is_reader());- if !self.recorder.paint_order_tree.reads_current_tree() {+ debug_assert!(self.recorder.published_recording_count.is_of_a_fork());+ if !self.recorder.published_recording_count.is_current() {self.leave_frame_to_host();return self;}diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex e873621946c..681579865ff 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -108,6 +108,7 @@ RENDER_STATE_ALLOWED = {"painting/hit_test/walk.rs:VERIFIED","painting/paint_passes.rs:PAINTING_TIMING_ENABLED","painting/record/ink_bounds.rs:VERIFICATION",+ "painting/record/traversal.rs:VERIFIED","render_state/clock/hover.rs:LOGS",],),diff --git a/Tests/LibWeb/Text/input/display_list/paint-cache-interior-change-after-quiet-frame.html b/Tests/LibWeb/Text/input/display_list/paint-cache-interior-change-after-quiet-frame.htmlindex b79c19e561d..2ea15637827 100644--- a/Tests/LibWeb/Text/input/display_list/paint-cache-interior-change-after-quiet-frame.html+++ b/Tests/LibWeb/Text/input/display_list/paint-cache-interior-change-after-quiet-frame.html@@ -50,7 +50,7 @@ displayListTest({BlockContainer<DIV>#container/background COPYBlockContainer<DIV>#container/border COPYBlockContainer<DIV>#card0.card/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#card0.card/scroll-metadata COPY+ BlockContainer<DIV>#card0.card/scroll-metadata RECORD (empty)BlockContainer<DIV>#card0.card/background SKIPBlockContainer<DIV>#card0.card/border RECORDBlockContainer<DIV>#card1.card/descendants(background-and-borders) COPY@@ -108,7 +108,7 @@ displayListTest({BlockContainer<DIV>#container/background COPYBlockContainer<DIV>#container/border COPYBlockContainer<DIV>#card0.card/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#card0.card/scroll-metadata COPY+ BlockContainer<DIV>#card0.card/scroll-metadata RECORD (empty)BlockContainer<DIV>#card0.card/background SKIPBlockContainer<DIV>#card0.card/border RECORDBlockContainer<DIV>#card1.card/descendants(background-and-borders) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/paint-cache-relayout-paint-inputs.html b/Tests/LibWeb/Text/input/display_list/paint-cache-relayout-paint-inputs.htmlindex 2aeb9d4ed65..5c575598b83 100644--- a/Tests/LibWeb/Text/input/display_list/paint-cache-relayout-paint-inputs.html+++ b/Tests/LibWeb/Text/input/display_list/paint-cache-relayout-paint-inputs.html@@ -66,24 +66,24 @@ displayListTest({BlockContainer<DIV>#target/scroll-metadata RECORD (empty)BlockContainer<DIV>#target/background RECORDBlockContainer<DIV>#target/border SKIP- InlineNode<SPAN>#inline/descendants(background-and-borders) ASSEMBLE+ InlineNode<SPAN>#inline/descendants(background-and-borders) RECORDCanvasBox<CANVAS>#trigger/descendants(background-and-borders) COPYBlockContainer<BODY>#body/descendants(inline-background-and-borders) ASSEMBLEBlockContainer<DIV>#target/descendants(inline-background-and-borders) ASSEMBLE- InlineNode<SPAN>#inline/descendants(inline-background-and-borders) ASSEMBLE+ InlineNode<SPAN>#inline/descendants(inline-background-and-borders) RECORDCanvasBox<CANVAS>#trigger/descendants(inline-background-and-borders) COPYBlockContainer<HTML>#html/foreground COPYBlockContainer<BODY>#body/descendants(foreground) ASSEMBLEBlockContainer<BODY>#body/foreground COPYBlockContainer<DIV>#target/descendants(foreground) ASSEMBLEBlockContainer<DIV>#target/foreground RECORD (empty)- InlineNode<SPAN>#inline/descendants(foreground) ASSEMBLE+ InlineNode<SPAN>#inline/descendants(foreground) RECORDBlockContainer<DIV>#target/outline SKIPBlockContainer<DIV>#target/overlay SKIPCanvasBox<CANVAS>#trigger/descendants(foreground) COPYBlockContainer<BODY>#body/outline COPYBlockContainer<BODY>#body/overlay COPY- InlineNode<SPAN>#inline ASSEMBLE+ InlineNode<SPAN>#inline RECORDInlineNode<SPAN>#inline/scroll-metadata RECORD (empty)InlineNode<SPAN>#inline/background SKIPInlineNode<SPAN>#inline/border SKIP@@ -92,7 +92,7 @@ displayListTest({InlineNode<SPAN>#inline/foreground RECORD (empty)InlineNode<SPAN>#inline/outline SKIPInlineNode<SPAN>#inline/overlay SKIP- BlockContainer<HTML>#html/outline COPY+ BlockContainer<HTML>#html/outline SKIP@viewport/outline COPY`,},@@ -134,28 +134,28 @@ displayListTest({BlockContainer<BODY>#body/background COPYBlockContainer<BODY>#body/border COPYBlockContainer<DIV>#target/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#target/scroll-metadata COPY+ BlockContainer<DIV>#target/scroll-metadata RECORD (empty)BlockContainer<DIV>#target/background RECORDBlockContainer<DIV>#target/border SKIP- InlineNode<SPAN>#inline/descendants(background-and-borders) ASSEMBLE+ InlineNode<SPAN>#inline/descendants(background-and-borders) RECORDCanvasBox<CANVAS>#trigger/descendants(background-and-borders) COPYBlockContainer<BODY>#body/descendants(inline-background-and-borders) ASSEMBLEBlockContainer<DIV>#target/descendants(inline-background-and-borders) ASSEMBLE- InlineNode<SPAN>#inline/descendants(inline-background-and-borders) ASSEMBLE+ InlineNode<SPAN>#inline/descendants(inline-background-and-borders) RECORDCanvasBox<CANVAS>#trigger/descendants(inline-background-and-borders) COPYBlockContainer<HTML>#html/foreground COPYBlockContainer<BODY>#body/descendants(foreground) ASSEMBLEBlockContainer<BODY>#body/foreground COPYBlockContainer<DIV>#target/descendants(foreground) ASSEMBLEBlockContainer<DIV>#target/foreground RECORD (empty)- InlineNode<SPAN>#inline/descendants(foreground) ASSEMBLE+ InlineNode<SPAN>#inline/descendants(foreground) RECORDBlockContainer<DIV>#target/outline SKIPBlockContainer<DIV>#target/overlay SKIPCanvasBox<CANVAS>#trigger/descendants(foreground) COPYBlockContainer<BODY>#body/outline COPYBlockContainer<BODY>#body/overlay COPY- InlineNode<SPAN>#inline ASSEMBLE- InlineNode<SPAN>#inline/scroll-metadata COPY+ InlineNode<SPAN>#inline RECORD+ InlineNode<SPAN>#inline/scroll-metadata RECORD (empty)InlineNode<SPAN>#inline/background SKIPInlineNode<SPAN>#inline/border SKIPInlineNode<SPAN>#inline/inline-piece RECORD (empty)@@ -163,7 +163,7 @@ displayListTest({InlineNode<SPAN>#inline/foreground RECORD (empty)InlineNode<SPAN>#inline/outline SKIPInlineNode<SPAN>#inline/overlay SKIP- BlockContainer<HTML>#html/outline COPY+ BlockContainer<HTML>#html/outline SKIP@viewport/outline COPY`,},diff --git a/Tests/LibWeb/Text/input/display_list/paint-cache-scrollability-flip-scope.html b/Tests/LibWeb/Text/input/display_list/paint-cache-scrollability-flip-scope.htmlindex 4dc32738d26..d08b5b8da73 100644--- a/Tests/LibWeb/Text/input/display_list/paint-cache-scrollability-flip-scope.html+++ b/Tests/LibWeb/Text/input/display_list/paint-cache-scrollability-flip-scope.html@@ -92,7 +92,7 @@ displayListTest({BlockContainer<DIV>#row-0.box COPYBlockContainer<DIV>#outer.box COPYBlockContainer<DIV>#row-2.box ASSEMBLE- BlockContainer<DIV>#row-2.box/scroll-metadata COPY+ BlockContainer<DIV>#row-2.box/scroll-metadata RECORDBlockContainer<DIV>#row-2.box/background SKIPBlockContainer<DIV>#row-2.box/border RECORDBlockContainer<DIV>#row-2.box/foreground RECORD@@ -161,8 +161,8 @@ displayListTest({BlockContainer<DIV>#inner/border SKIPBlockContainer<DIV>#inner-content.tall/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#inner-content.tall/scroll-metadata RECORD- BlockContainer<DIV>#inner-content.tall/background COPY- BlockContainer<DIV>#inner-content.tall/border COPY+ BlockContainer<DIV>#inner-content.tall/background SKIP+ BlockContainer<DIV>#inner-content.tall/border SKIPBlockContainer<DIV>#filler.tall/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#filler.tall/scroll-metadata RECORDBlockContainer<DIV>#filler.tall/background SKIPdiff --git a/Tests/LibWeb/Text/input/display_list/paint-cache-viewport-scroll.html b/Tests/LibWeb/Text/input/display_list/paint-cache-viewport-scroll.htmlindex 0cf369e09a4..a39941b41b1 100644--- a/Tests/LibWeb/Text/input/display_list/paint-cache-viewport-scroll.html+++ b/Tests/LibWeb/Text/input/display_list/paint-cache-viewport-scroll.html@@ -4,7 +4,9 @@<style>html { background: #eee; }body { margin: 0; width: 1600px; height: 2400px; }- #stable { position: absolute; z-index: 1; left: 100px; top: 400px; width: 120px; height: 80px; background: green; }+ /* A recording keeps what it recorded in runs about half a screen tall, and records a run again as a whole:+ the boxes are far enough apart to be in runs of their own. */+ #stable { position: absolute; z-index: 1; left: 100px; top: 560px; width: 120px; height: 30px; background: green; }#changed { position: absolute; z-index: 1; left: 260px; top: 400px; width: 120px; height: 80px; background: blue; }#fixed { position: fixed; left: 10px; top: 10px; width: 40px; height: 40px; background: purple; }</style>@@ -29,7 +31,7 @@ promiseTest(async () => {output.push(`FAIL: scrolling ${x},${y} recorded the unchanged sibling\n${trace}`);} else if (document.elementFromPoint(20, 20)?.id !== "fixed") {output.push(`FAIL: fixed hit target after scrolling ${x},${y}`);- } else if (document.elementFromPoint(110 - x, 410 - y)?.id !== "stable") {+ } else if (document.elementFromPoint(110 - x, 570 - y)?.id !== "stable") {output.push(`FAIL: document hit target after scrolling ${x},${y}`);} else {output.push(`PASS: scroll ${x},${y} retains unchanged output and hit targets`);diff --git a/Tests/LibWeb/Text/input/display_list/paint-damage-dirty-while-skipped.html b/Tests/LibWeb/Text/input/display_list/paint-damage-dirty-while-skipped.htmlindex b0fa0d7fecf..c6d153cddf1 100644--- a/Tests/LibWeb/Text/input/display_list/paint-damage-dirty-while-skipped.html+++ b/Tests/LibWeb/Text/input/display_list/paint-damage-dirty-while-skipped.html@@ -81,7 +81,7 @@ displayListTest({BlockContainer<DIV>#root/descendants(foreground) ASSEMBLEBlockContainer<BODY>#body/outline COPYBlockContainer<BODY>#body/overlay COPY- BlockContainer<DIV>#root ASSEMBLE+ BlockContainer<DIV>#root SKIPBlockContainer<HTML>#html/outline COPY@viewport/outline COPY`diff --git a/Tests/LibWeb/Text/input/display_list/paint-damage-root-overflow-growth.html b/Tests/LibWeb/Text/input/display_list/paint-damage-root-overflow-growth.htmlindex 61880ce5478..1b82b0c4fc8 100644--- a/Tests/LibWeb/Text/input/display_list/paint-damage-root-overflow-growth.html+++ b/Tests/LibWeb/Text/input/display_list/paint-damage-root-overflow-growth.html@@ -32,18 +32,18 @@ displayListTest({@viewport/foreground RECORD (empty)BlockContainer<HTML>#html/descendants(foreground) ASSEMBLEBlockContainer<HTML>#html ASSEMBLE- BlockContainer<HTML>#html/preamble COPY+ BlockContainer<HTML>#html/preamble RECORD (empty)BlockContainer<HTML>#html/scroll-metadata RECORD (empty)BlockContainer<HTML>#html/background RECORD- BlockContainer<HTML>#html/border COPY+ BlockContainer<HTML>#html/border SKIPBlockContainer<BODY>#body/descendants(background-and-borders) ASSEMBLEBlockContainer<BODY>#body/scroll-metadata RECORD (empty)- BlockContainer<BODY>#body/background COPY- BlockContainer<BODY>#body/border COPY+ BlockContainer<BODY>#body/background SKIP+ BlockContainer<BODY>#body/border SKIPBlockContainer<DIV>#text/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#text/scroll-metadata RECORD (empty)- BlockContainer<DIV>#text/background COPY- BlockContainer<DIV>#text/border COPY+ BlockContainer<DIV>#text/background SKIP+ BlockContainer<DIV>#text/border SKIPBlockContainer<DIV>#far/descendants(background-and-borders) ASSEMBLEBlockContainer<HTML>#html/foreground COPYBlockContainer<BODY>#body/descendants(foreground) ASSEMBLEdiff --git a/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-content-move.html b/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-content-move.htmlindex 45bb92a5cf8..4744973cc00 100644--- a/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-content-move.html+++ b/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-content-move.html@@ -41,8 +41,8 @@ displayListTest({BlockContainer<BODY>#body/border COPYBlockContainer<DIV>#scroller/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#scroller/scroll-metadata RECORD- BlockContainer<DIV>#scroller/background COPY- BlockContainer<DIV>#scroller/border COPY+ BlockContainer<DIV>#scroller/background SKIP+ BlockContainer<DIV>#scroller/border SKIPBlockContainer<DIV>#row0.row/descendants(background-and-borders) COPYBlockContainer<DIV>#row1.row/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#row1.row/scroll-metadata RECORD@@ -66,7 +66,7 @@ displayListTest({BlockContainer<DIV>#row2.row/foreground RECORD (empty)BlockContainer<DIV>#row2.row/outline SKIPBlockContainer<DIV>#row2.row/overlay SKIP- BlockContainer<DIV>#scroller/outline COPY+ BlockContainer<DIV>#scroller/outline SKIPBlockContainer<DIV>#scroller/overlay RECORDBlockContainer<BODY>#body/outline COPYBlockContainer<BODY>#body/overlay COPY@@ -103,7 +103,7 @@ displayListTest({BlockContainer<DIV>#scroller/border COPYBlockContainer<DIV>#row0.row/descendants(background-and-borders) COPYBlockContainer<DIV>#row1.row/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#row1.row/scroll-metadata COPY+ BlockContainer<DIV>#row1.row/scroll-metadata RECORDBlockContainer<DIV>#row1.row/background RECORDBlockContainer<DIV>#row1.row/border SKIPBlockContainer<DIV>#row2.row/descendants(background-and-borders) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-slot-reuse.html b/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-slot-reuse.htmlindex 1caf919f32d..d5b132e98cc 100644--- a/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-slot-reuse.html+++ b/Tests/LibWeb/Text/input/display_list/paint-damage-scroller-slot-reuse.html@@ -15,7 +15,7 @@// another box scrollable reuses it, and the rows below that box must point at the new scroller.// The first scroller stays so the document keeps a non-viewport wheel target throughout.const wheelTargetAt = (x, y) => {- internals.recordDisplayListForTesting();+ internals.recordDisplayListForTesting(false, false, true);return wheelTargetToString(internals.recordedDisplayListWheelTargetAt(x, y, 0, 10));};displayListTest({@@ -107,14 +107,14 @@ displayListTest({@viewport/foreground COPYBlockContainer<HTML>#html/descendants(foreground) ASSEMBLEBlockContainer<HTML>#html ASSEMBLE- BlockContainer<HTML>#html/preamble COPY+ BlockContainer<HTML>#html/preamble RECORD (empty)BlockContainer<HTML>#html/scroll-metadata RECORD- BlockContainer<HTML>#html/background COPY- BlockContainer<HTML>#html/border COPY+ BlockContainer<HTML>#html/background RECORD (empty)+ BlockContainer<HTML>#html/border SKIPBlockContainer<BODY>#body/descendants(background-and-borders) ASSEMBLEBlockContainer<BODY>#body/scroll-metadata RECORD- BlockContainer<BODY>#body/background COPY- BlockContainer<BODY>#body/border COPY+ BlockContainer<BODY>#body/background SKIP+ BlockContainer<BODY>#body/border SKIPBlockContainer<DIV>#keep.box.scroller/descendants(background-and-borders) COPYBlockContainer<DIV>#outer.box/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#outer.box/scroll-metadata RECORD@@ -136,7 +136,7 @@ displayListTest({BlockContainer<DIV>#outer-content.content/overlay SKIPBlockContainer<DIV>#outer.box/outline SKIPBlockContainer<DIV>#outer.box/overlay RECORD- BlockContainer<BODY>#body/outline COPY+ BlockContainer<BODY>#body/outline SKIPBlockContainer<BODY>#body/overlay SKIPBlockContainer<HTML>#html/outline COPY@viewport/outline COPY@@ -176,7 +176,7 @@ displayListTest({BlockContainer<DIV>#outer.box/background COPYBlockContainer<DIV>#outer.box/border COPYBlockContainer<DIV>#outer-content.content/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#outer-content.content/scroll-metadata COPY+ BlockContainer<DIV>#outer-content.content/scroll-metadata RECORDBlockContainer<DIV>#outer-content.content/background SKIPBlockContainer<DIV>#outer-content.content/border SKIPBlockContainer<HTML>#html/foreground COPYdiff --git a/Tests/LibWeb/Text/input/display_list/paint-damage-selection-change.html b/Tests/LibWeb/Text/input/display_list/paint-damage-selection-change.htmlindex 27b780c2391..0ab51491673 100644--- a/Tests/LibWeb/Text/input/display_list/paint-damage-selection-change.html+++ b/Tests/LibWeb/Text/input/display_list/paint-damage-selection-change.html@@ -22,7 +22,7 @@ displayListTest({@canvas RECORD (empty)@viewport ASSEMBLE@viewport/preamble RECORD (empty)- @viewport/scroll-metadata COPY+ @viewport/scroll-metadata RECORD (empty)@viewport/background SKIP@viewport/border SKIPBlockContainer<HTML>#html/descendants(background-and-borders) ASSEMBLE@@ -43,7 +43,7 @@ displayListTest({BlockContainer<DIV>#outer/border COPYBlockContainer<DIV>#before.section/descendants(background-and-borders) COPYBlockContainer<DIV>#target.section/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#target.section/scroll-metadata COPY+ BlockContainer<DIV>#target.section/scroll-metadata RECORD (empty)BlockContainer<DIV>#target.section/background SKIPBlockContainer<DIV>#target.section/border SKIPBlockContainer<DIV>#after.section/descendants(background-and-borders) COPY@@ -74,7 +74,7 @@ displayListTest({@canvas RECORD (empty)@viewport ASSEMBLE@viewport/preamble RECORD (empty)- @viewport/scroll-metadata COPY+ @viewport/scroll-metadata RECORD (empty)@viewport/background SKIP@viewport/border SKIPBlockContainer<HTML>#html/descendants(background-and-borders) ASSEMBLE@@ -95,7 +95,7 @@ displayListTest({BlockContainer<DIV>#outer/border COPYBlockContainer<DIV>#before.section/descendants(background-and-borders) COPYBlockContainer<DIV>#target.section/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#target.section/scroll-metadata COPY+ BlockContainer<DIV>#target.section/scroll-metadata RECORD (empty)BlockContainer<DIV>#target.section/background SKIPBlockContainer<DIV>#target.section/border SKIPBlockContainer<DIV>#after.section/descendants(background-and-borders) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/paint-damage-shifted-siblings.html b/Tests/LibWeb/Text/input/display_list/paint-damage-shifted-siblings.htmlindex b2bee4b17df..e97b8be8583 100644--- a/Tests/LibWeb/Text/input/display_list/paint-damage-shifted-siblings.html+++ b/Tests/LibWeb/Text/input/display_list/paint-damage-shifted-siblings.html@@ -56,7 +56,7 @@ displayListTest({BlockContainer<DIV>#c1-inner.inner/scroll-metadata RECORD (empty)BlockContainer<DIV>#c1-inner.inner/background SKIPBlockContainer<DIV>#c1-inner.inner/border SKIP- InlineNode<SPAN>#c1-text/descendants(background-and-borders) ASSEMBLE+ InlineNode<SPAN>#c1-text/descendants(background-and-borders) RECORDBlockContainer<DIV>#c2.card/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#c2.card/scroll-metadata RECORD (empty)BlockContainer<DIV>#c2.card/background SKIP@@ -66,7 +66,7 @@ displayListTest({BlockContainer<DIV>#c0.card/descendants(inline-background-and-borders) ASSEMBLEBlockContainer<DIV>#c1.card/descendants(inline-background-and-borders) ASSEMBLEBlockContainer<DIV>#c1-inner.inner/descendants(inline-background-and-borders) ASSEMBLE- InlineNode<SPAN>#c1-text/descendants(inline-background-and-borders) ASSEMBLE+ InlineNode<SPAN>#c1-text/descendants(inline-background-and-borders) RECORDInlineNode<SPAN>#c1-text/scroll-metadata RECORD (empty)InlineNode<SPAN>#c1-text/background SKIPInlineNode<SPAN>#c1-text/border SKIP@@ -86,7 +86,7 @@ displayListTest({BlockContainer<DIV>#c1-inner.inner/inline-piece RECORD (empty)BlockContainer<DIV>#c1-inner.inner/text-fragment RECORDBlockContainer<DIV>#c1-inner.inner/foreground RECORD (empty)- InlineNode<SPAN>#c1-text/descendants(foreground) ASSEMBLE+ InlineNode<SPAN>#c1-text/descendants(foreground) RECORDInlineNode<SPAN>#c1-text/foreground RECORD (empty)InlineNode<SPAN>#c1-text/outline SKIPInlineNode<SPAN>#c1-text/overlay SKIPdiff --git a/Tests/LibWeb/Text/input/display_list/paint-damage-snap-area-move.html b/Tests/LibWeb/Text/input/display_list/paint-damage-snap-area-move.htmlindex a7d68f7d25c..b8f04493d3c 100644--- a/Tests/LibWeb/Text/input/display_list/paint-damage-snap-area-move.html+++ b/Tests/LibWeb/Text/input/display_list/paint-damage-snap-area-move.html@@ -55,8 +55,8 @@ displayListTest({BlockContainer<BODY>#body/border COPYBlockContainer<DIV>#snap/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#snap/scroll-metadata RECORD- BlockContainer<DIV>#snap/background COPY- BlockContainer<DIV>#snap/border COPY+ BlockContainer<DIV>#snap/background SKIP+ BlockContainer<DIV>#snap/border SKIPBlockContainer<DIV>#area0.area/descendants(background-and-borders) COPYBlockContainer<DIV>#area1.area/descendants(background-and-borders) ASSEMBLEBlockContainer<DIV>#area1.area/scroll-metadata RECORD@@ -80,7 +80,7 @@ displayListTest({BlockContainer<DIV>#area2.area/foreground RECORD (empty)BlockContainer<DIV>#area2.area/outline SKIPBlockContainer<DIV>#area2.area/overlay SKIP- BlockContainer<DIV>#snap/outline COPY+ BlockContainer<DIV>#snap/outline SKIPBlockContainer<DIV>#snap/overlay RECORDBlockContainer<BODY>#body/outline COPYBlockContainer<BODY>#body/overlay COPYdiff --git a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-clean-sibling-context.html b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-clean-sibling-context.htmlindex e99499fa36a..86a9ae466e7 100644--- a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-clean-sibling-context.html+++ b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-clean-sibling-context.html@@ -69,7 +69,7 @@ displayListTest({BlockContainer<DIV>#b/background COPYBlockContainer<DIV>#b/border COPYBlockContainer<DIV>#b0.row/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#b0.row/scroll-metadata COPY+ BlockContainer<DIV>#b0.row/scroll-metadata RECORD (empty)BlockContainer<DIV>#b0.row/background SKIPBlockContainer<DIV>#b0.row/border RECORDBlockContainer<DIV>#b1.row/descendants(background-and-borders) COPY@@ -126,7 +126,7 @@ displayListTest({BlockContainer<DIV>#a/background COPYBlockContainer<DIV>#a/border COPYBlockContainer<DIV>#a0.row/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#a0.row/scroll-metadata COPY+ BlockContainer<DIV>#a0.row/scroll-metadata RECORD (empty)BlockContainer<DIV>#a0.row/background SKIPBlockContainer<DIV>#a0.row/border RECORDBlockContainer<DIV>#a1.row/descendants(background-and-borders) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-iframe.html b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-iframe.htmlindex b7926d1c8e0..04a3e4be3b5 100644--- a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-iframe.html+++ b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-iframe.html@@ -61,7 +61,7 @@ displayListTest({BlockContainer<DIV>#root/border COPYNavigableContainerViewport<IFRAME>#frame/descendants(background-and-borders) COPYBlockContainer<DIV>#after/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#after/scroll-metadata COPY+ BlockContainer<DIV>#after/scroll-metadata RECORDBlockContainer<DIV>#after/background SKIPBlockContainer<DIV>#after/border SKIPNavigableContainerViewport<IFRAME>#frame/descendants(floats) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-interior-change-after-quiet-frames.html b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-interior-change-after-quiet-frames.htmlindex 0a43672bfb0..21d4958046b 100644--- a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-interior-change-after-quiet-frames.html+++ b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-interior-change-after-quiet-frames.html@@ -61,7 +61,7 @@ displayListTest({BlockContainer<DIV>#b/background COPYBlockContainer<DIV>#b/border COPYBlockContainer<DIV>#b0.row/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#b0.row/scroll-metadata COPY+ BlockContainer<DIV>#b0.row/scroll-metadata RECORD (empty)BlockContainer<DIV>#b0.row/background SKIPBlockContainer<DIV>#b0.row/border RECORDBlockContainer<DIV>#b1.row/descendants(background-and-borders) COPY@@ -135,7 +135,7 @@ displayListTest({BlockContainer<DIV>#b/background COPYBlockContainer<DIV>#b/border COPYBlockContainer<DIV>#b0.row/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#b0.row/scroll-metadata COPY+ BlockContainer<DIV>#b0.row/scroll-metadata RECORD (empty)BlockContainer<DIV>#b0.row/background SKIPBlockContainer<DIV>#b0.row/border RECORDBlockContainer<DIV>#b1.row/descendants(background-and-borders) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-masked-box.html b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-masked-box.htmlindex bc046785d77..a651ea2f300 100644--- a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-masked-box.html+++ b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-masked-box.html@@ -59,7 +59,7 @@ displayListTest({BlockContainer<DIV>#root/border COPYBlockContainer<DIV>#r0.row/descendants(background-and-borders) COPYBlockContainer<DIV>#r1.row/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#r1.row/scroll-metadata COPY+ BlockContainer<DIV>#r1.row/scroll-metadata RECORD (empty)BlockContainer<DIV>#r1.row/background SKIPBlockContainer<DIV>#r1.row/border SKIPBlockContainer<DIV>#r2.row/descendants(background-and-borders) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-moved-box.html b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-moved-box.htmlindex ab2c4fd20e0..c19e2a7c633 100644--- a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-moved-box.html+++ b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-moved-box.html@@ -40,14 +40,14 @@ displayListTest({@viewport/foreground COPYBlockContainer<HTML>#html/descendants(foreground) ASSEMBLEBlockContainer<HTML>#html ASSEMBLE- BlockContainer<HTML>#html/preamble COPY+ BlockContainer<HTML>#html/preamble RECORD (empty)BlockContainer<HTML>#html/scroll-metadata RECORD (empty)- BlockContainer<HTML>#html/background COPY- BlockContainer<HTML>#html/border COPY+ BlockContainer<HTML>#html/background RECORD (empty)+ BlockContainer<HTML>#html/border SKIPBlockContainer<BODY>#body/descendants(background-and-borders) ASSEMBLEBlockContainer<BODY>#body/scroll-metadata RECORD (empty)- BlockContainer<BODY>#body/background COPY- BlockContainer<BODY>#body/border COPY+ BlockContainer<BODY>#body/background SKIP+ BlockContainer<BODY>#body/border SKIPBlockContainer<DIV>#a/descendants(background-and-borders) COPYBlockContainer<DIV>#b/descendants(background-and-borders) ASSEMBLEBlockContainer<HTML>#html/foreground COPY@@ -55,7 +55,7 @@ displayListTest({BlockContainer<BODY>#body/foreground COPYBlockContainer<DIV>#a/descendants(foreground) COPYBlockContainer<DIV>#b/descendants(foreground) ASSEMBLE- BlockContainer<BODY>#body/outline COPY+ BlockContainer<BODY>#body/outline SKIPBlockContainer<BODY>#body/overlay SKIPBlockContainer<DIV>#a COPYBlockContainer<DIV>#b ASSEMBLEdiff --git a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-self-contained-svg.html b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-self-contained-svg.htmlindex 27b445a3f22..2e6b2fe81f5 100644--- a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-self-contained-svg.html+++ b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-self-contained-svg.html@@ -63,9 +63,9 @@ displayListTest({SVGSVGBox<svg>#svg/descendants(inline-background-and-borders) ASSEMBLEBlockContainer<DIV>#root/foreground COPYSVGSVGBox<svg>#svg/descendants(foreground) ASSEMBLE- SVGSVGBox<svg>#svg/scroll-metadata COPY- SVGSVGBox<svg>#svg/background COPY- SVGSVGBox<svg>#svg/border COPY+ SVGSVGBox<svg>#svg/scroll-metadata RECORD (empty)+ SVGSVGBox<svg>#svg/background SKIP+ SVGSVGBox<svg>#svg/border SKIPSVGSVGBox<svg>#svg/svg RECORDSVGSVGBox<svg>#svg/foreground RECORD (empty)SVGGeometryBox<path>#p/svg RECORDdiff --git a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-svg-context.html b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-svg-context.htmlindex adf034d6317..5306f056d93 100644--- a/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-svg-context.html+++ b/Tests/LibWeb/Text/input/display_list/painted-as-stacking-context-capture-svg-context.html@@ -69,15 +69,15 @@ displayListTest({BlockContainer<DIV>#root/outline COPYBlockContainer<DIV>#root/overlay COPYSVGSVGBox<svg>#svg ASSEMBLE- SVGSVGBox<svg>#svg/preamble COPY- SVGSVGBox<svg>#svg/scroll-metadata COPY- SVGSVGBox<svg>#svg/background COPY- SVGSVGBox<svg>#svg/border COPY+ SVGSVGBox<svg>#svg/preamble RECORD (empty)+ SVGSVGBox<svg>#svg/scroll-metadata RECORD (empty)+ SVGSVGBox<svg>#svg/background SKIP+ SVGSVGBox<svg>#svg/border SKIPSVGSVGBox<svg>#svg/svg RECORDSVGSVGBox<svg>#svg/foreground RECORD (empty)SVGGeometryBox<rect>#rect/svg RECORDSVGGeometryBox<rect>#rect/foreground RECORD- SVGSVGBox<svg>#svg/outline COPY+ SVGSVGBox<svg>#svg/outline SKIPBlockContainer<HTML>#html/outline COPY@viewport/outline COPY`diff --git a/Tests/LibWeb/Text/input/display_list/recording-trace-owner-names.html b/Tests/LibWeb/Text/input/display_list/recording-trace-owner-names.htmlindex 270130f36f3..150b25e132f 100644--- a/Tests/LibWeb/Text/input/display_list/recording-trace-owner-names.html+++ b/Tests/LibWeb/Text/input/display_list/recording-trace-owner-names.html@@ -57,15 +57,15 @@ displayListTest({BlockContainer<DIV>#first/border COPYBlockContainer(anonymous)/descendants(background-and-borders) COPYBlockContainer<DIV>#item/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#item/scroll-metadata COPY+ BlockContainer<DIV>#item/scroll-metadata RECORD (empty)BlockContainer<DIV>#item/background SKIPBlockContainer<DIV>#item/border SKIPBlockContainer(anonymous)/descendants(background-and-borders) ASSEMBLE- BlockContainer(anonymous)/scroll-metadata COPY+ BlockContainer(anonymous)/scroll-metadata RECORD (empty)BlockContainer(anonymous)/background RECORDBlockContainer(anonymous)/border SKIPBlockContainer(anonymous)/descendants(background-and-borders) ASSEMBLE- BlockContainer(anonymous)/scroll-metadata COPY+ BlockContainer(anonymous)/scroll-metadata RECORD (empty)BlockContainer(anonymous)/background SKIPBlockContainer(anonymous)/border SKIPBlockContainer(anonymous)/descendants(background-and-borders) COPYdiff --git a/Tests/LibWeb/Text/input/display_list/stacking-context-capture-nested-clean-sibling.html b/Tests/LibWeb/Text/input/display_list/stacking-context-capture-nested-clean-sibling.htmlindex eb550004adc..3147ce4a85c 100644--- a/Tests/LibWeb/Text/input/display_list/stacking-context-capture-nested-clean-sibling.html+++ b/Tests/LibWeb/Text/input/display_list/stacking-context-capture-nested-clean-sibling.html@@ -76,7 +76,7 @@ displayListTest({BlockContainer<DIV>#b-detail.detail/descendants(foreground) ASSEMBLEBlockContainer<DIV>#b-detail.detail ASSEMBLEBlockContainer<DIV>#b-detail.detail/preamble RECORD (empty)- BlockContainer<DIV>#b-detail.detail/scroll-metadata COPY+ BlockContainer<DIV>#b-detail.detail/scroll-metadata RECORD (empty)BlockContainer<DIV>#b-detail.detail/background RECORDBlockContainer<DIV>#b-detail.detail/border SKIPBlockContainer<DIV>#b-detail.detail/foreground RECORD@@ -136,7 +136,7 @@ displayListTest({BlockContainer<DIV>#a.context/border COPYBlockContainer<DIV>#a-underlay.underlay COPYBlockContainer<DIV>#a-label.label/descendants(background-and-borders) ASSEMBLE- BlockContainer<DIV>#a-label.label/scroll-metadata COPY+ BlockContainer<DIV>#a-label.label/scroll-metadata RECORD (empty)BlockContainer<DIV>#a-label.label/background RECORDBlockContainer<DIV>#a-label.label/border RECORDBlockContainer<DIV>#a-underlay.underlay/descendants(background-and-borders) COPY@@ -197,7 +197,7 @@ displayListTest({BlockContainer<DIV>#b.context/border COPYBlockContainer<DIV>#b-underlay.underlay ASSEMBLEBlockContainer<DIV>#b-underlay.underlay/preamble RECORD (empty)- BlockContainer<DIV>#b-underlay.underlay/scroll-metadata COPY+ BlockContainer<DIV>#b-underlay.underlay/scroll-metadata RECORD (empty)BlockContainer<DIV>#b-underlay.underlay/background RECORDBlockContainer<DIV>#b-underlay.underlay/border SKIPBlockContainer<DIV>#b-underlay.underlay/foreground RECORDdiff --git a/Tests/LibWeb/Text/input/display_list/svg-resource-filter-change.html b/Tests/LibWeb/Text/input/display_list/svg-resource-filter-change.htmlindex 247dd07231d..f367e078d8c 100644--- a/Tests/LibWeb/Text/input/display_list/svg-resource-filter-change.html+++ b/Tests/LibWeb/Text/input/display_list/svg-resource-filter-change.html@@ -114,11 +114,11 @@ displayListTest({BlockContainer<BODY>#body/overlay COPYBlockContainer<DIV>#filtered ASSEMBLEBlockContainer<DIV>#filtered/preamble RECORD- BlockContainer<DIV>#filtered/scroll-metadata COPY- BlockContainer<DIV>#filtered/background COPY- BlockContainer<DIV>#filtered/border COPY- BlockContainer<DIV>#filtered/foreground COPY- BlockContainer<DIV>#filtered/outline COPY+ BlockContainer<DIV>#filtered/scroll-metadata RECORD (empty)+ BlockContainer<DIV>#filtered/background SKIP+ BlockContainer<DIV>#filtered/border SKIP+ BlockContainer<DIV>#filtered/foreground RECORD (empty)+ BlockContainer<DIV>#filtered/outline SKIPBlockContainer<HTML>#html/outline COPY@viewport/outline COPY`diff --git a/Tests/LibWeb/Text/input/display_list/svg-resource-gradient-change.html b/Tests/LibWeb/Text/input/display_list/svg-resource-gradient-change.htmlindex e12e5cfea93..8f63d376b12 100644--- a/Tests/LibWeb/Text/input/display_list/svg-resource-gradient-change.html+++ b/Tests/LibWeb/Text/input/display_list/svg-resource-gradient-change.html@@ -56,9 +56,9 @@ displayListTest({BlockContainer<BODY>#body/descendants(foreground) ASSEMBLEBlockContainer<BODY>#body/foreground COPYSVGSVGBox<svg>#svg/descendants(foreground) ASSEMBLE- SVGSVGBox<svg>#svg/scroll-metadata COPY- SVGSVGBox<svg>#svg/background COPY- SVGSVGBox<svg>#svg/border COPY+ SVGSVGBox<svg>#svg/scroll-metadata RECORD (empty)+ SVGSVGBox<svg>#svg/background SKIP+ SVGSVGBox<svg>#svg/border SKIPSVGSVGBox<svg>#svg/svg RECORDSVGSVGBox<svg>#svg/foreground RECORD (empty)SVGGeometryBox<rect>#rect/svg RECORDdiff --git a/Tests/LibWeb/Text/input/display_list/svg-resource-pattern-stays-live.html b/Tests/LibWeb/Text/input/display_list/svg-resource-pattern-stays-live.htmlindex 1fa793582d2..6a9ddadfee3 100644--- a/Tests/LibWeb/Text/input/display_list/svg-resource-pattern-stays-live.html+++ b/Tests/LibWeb/Text/input/display_list/svg-resource-pattern-stays-live.html@@ -40,9 +40,9 @@ displayListTest({BlockContainer<BODY>#body/descendants(foreground) ASSEMBLEBlockContainer<BODY>#body/foreground COPYSVGSVGBox<svg>#svg/descendants(foreground) ASSEMBLE- SVGSVGBox<svg>#svg/scroll-metadata COPY- SVGSVGBox<svg>#svg/background COPY- SVGSVGBox<svg>#svg/border COPY+ SVGSVGBox<svg>#svg/scroll-metadata RECORD (empty)+ SVGSVGBox<svg>#svg/background SKIP+ SVGSVGBox<svg>#svg/border SKIPSVGSVGBox<svg>#svg/svg RECORDSVGSVGBox<svg>#svg/foreground RECORD (empty)SVGGeometryBox<rect>#rect/svg RECORD@@ -95,9 +95,9 @@ displayListTest({BlockContainer<BODY>#body/descendants(foreground) ASSEMBLEBlockContainer<BODY>#body/foreground COPYSVGSVGBox<svg>#svg/descendants(foreground) ASSEMBLE- SVGSVGBox<svg>#svg/scroll-metadata COPY- SVGSVGBox<svg>#svg/background COPY- SVGSVGBox<svg>#svg/border COPY+ SVGSVGBox<svg>#svg/scroll-metadata RECORD (empty)+ SVGSVGBox<svg>#svg/background SKIP+ SVGSVGBox<svg>#svg/border SKIPSVGSVGBox<svg>#svg/svg RECORDSVGSVGBox<svg>#svg/foreground RECORD (empty)SVGGeometryBox<rect>#rect/svg RECORDdiff --git a/Tests/LibWeb/Text/input/display_list/window-focus-change-records-caret.html b/Tests/LibWeb/Text/input/display_list/window-focus-change-records-caret.htmlindex 486ce5716e7..ab86f3a589c 100644--- a/Tests/LibWeb/Text/input/display_list/window-focus-change-records-caret.html+++ b/Tests/LibWeb/Text/input/display_list/window-focus-change-records-caret.html@@ -34,8 +34,8 @@ const focusChangeTrace = `BlockContainer<BODY>#body/foreground COPYBlockContainer<DIV>#editor/descendants(foreground) ASSEMBLEBlockContainer<DIV>#editor/foreground RECORD- BlockContainer<DIV>#editor/outline COPY- BlockContainer<DIV>#editor/overlay COPY+ BlockContainer<DIV>#editor/outline SKIP+ BlockContainer<DIV>#editor/overlay SKIPBlockContainer<DIV>#plain/descendants(foreground) COPYBlockContainer<BODY>#body/outline COPYBlockContainer<BODY>#body/overlay COPYdiff --git a/Tests/LibWeb/Text/input/display_list/window-focus-change-records-focus-dependent-output.html b/Tests/LibWeb/Text/input/display_list/window-focus-change-records-focus-dependent-output.htmlindex 96530e13f0c..538bf525adc 100644--- a/Tests/LibWeb/Text/input/display_list/window-focus-change-records-focus-dependent-output.html+++ b/Tests/LibWeb/Text/input/display_list/window-focus-change-records-focus-dependent-output.html@@ -33,13 +33,13 @@ const focusChangeTrace = ringOutline => `BlockContainer<BODY>#body/descendants(foreground) ASSEMBLEBlockContainer<BODY>#body/foreground COPYBlockContainer<DIV>#ring/descendants(foreground) ASSEMBLE- BlockContainer<DIV>#ring/foreground COPY+ BlockContainer<DIV>#ring/foreground RECORD (empty)BlockContainer<DIV>#ring/outline ${ringOutline}- BlockContainer<DIV>#ring/overlay COPY+ BlockContainer<DIV>#ring/overlay SKIPBlockContainer<DIV>#selected/descendants(foreground) ASSEMBLEBlockContainer<DIV>#selected/foreground RECORD- BlockContainer<DIV>#selected/outline COPY- BlockContainer<DIV>#selected/overlay COPY+ BlockContainer<DIV>#selected/outline SKIP+ BlockContainer<DIV>#selected/overlay SKIPBlockContainer<DIV>#plain/descendants(foreground) COPYBlockContainer<BODY>#body/outline COPYBlockContainer<BODY>#body/overlay COPYdiff --git a/Tests/LibWeb/Text/input/inspector-overlay-visual-context-tree-growth.html b/Tests/LibWeb/Text/input/inspector-overlay-visual-context-tree-growth.htmlindex 17b0c672b6a..39087371bea 100644--- a/Tests/LibWeb/Text/input/inspector-overlay-visual-context-tree-growth.html+++ b/Tests/LibWeb/Text/input/inspector-overlay-visual-context-tree-growth.html@@ -124,7 +124,7 @@BlockContainer<BODY>/overlay COPYBlockContainer<DIV>#box ASSEMBLEBlockContainer<DIV>#box/preamble RECORD (empty)- BlockContainer<DIV>#box/scroll-metadata COPY+ BlockContainer<DIV>#box/scroll-metadata RECORD (empty)BlockContainer<DIV>#box/background RECORDBlockContainer<DIV>#box/border SKIPBlockContainer<DIV>#box/foreground RECORD (empty)diff --git a/Tests/LibWeb/Text/input/work-test.js b/Tests/LibWeb/Text/input/work-test.jsindex 56c772e2ff3..db175d23956 100644--- a/Tests/LibWeb/Text/input/work-test.js+++ b/Tests/LibWeb/Text/input/work-test.js@@ -60,8 +60,11 @@ const workStages = [name: "displayList",begin: testInternals => testInternals.beginDisplayListTrace(),take: testInternals => testInternals.takeDisplayListTrace(),+ // A recording keeps what it recorded in runs about a screen row of the document tall, and records a run again+ // as a whole. Test pages are much smaller than one run, so the recordings here are cut as finely as they go,+ // which shows which boxes a change reaches.settle: (testInternals, step) =>- testInternals.recordDisplayListForTesting(step.paintOverlay ?? false, step.cold ?? false),+ testInternals.recordDisplayListForTesting(step.paintOverlay ?? false, step.cold ?? false, true),expected: (step, trace) => `recording (overlay=${step.paintOverlay ?? false})\n${normalizeTrace(trace)}`,},];