Skip to content

Truly independent web browser

LibCompositing+LibWeb+Compositor: Send only the chunks a context lacks

Aliaksandr Kalenik5073f57a63ac
diff --git a/Libraries/LibCompositing/Rust/src/display_list/chunks.rs b/Libraries/LibCompositing/Rust/src/display_list/chunks.rs
index 12b5487c509..2806b8eaee2 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/chunks.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/chunks.rs
@@ -43,6 +43,49 @@ impl Chunk {
}
}
+/// How many of the latest display lists of a context both ends of a connection keep the chunks of.
+pub const DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT: usize = 4;
+
+/// The chunks both ends of a connection keep for one context: those its latest display lists name. A sender sends a
+/// display list's chunks that are not kept, and both ends take in each list they send or receive in the same order,
+/// so both always keep the same chunks without telling each other.
+#[derive(Debug, Default)]
+pub struct KeptChunks {
+ latest_lists: std::collections::VecDeque<Box<[ChunkId]>>,
+ lists_naming: std::collections::HashMap<ChunkId, u32>,
+}
+
+impl KeptChunks {
+ pub fn keeps(&self, id: ChunkId) -> bool {
+ self.lists_naming.contains_key(&id)
+ }
+
+ /// Takes in the display list the context presents next, which names `chunks`, and answers the chunks that no list
+ /// still kept names.
+ pub fn take_in(&mut self, chunks: &[ChunkId]) -> Vec<ChunkId> {
+ let mut named_once: Vec<ChunkId> = chunks.to_vec();
+ named_once.sort_unstable_by_key(|id| id.0);
+ named_once.dedup();
+ for id in &named_once {
+ *self.lists_naming.entry(*id).or_default() += 1;
+ }
+ self.latest_lists.push_back(named_once.into_boxed_slice());
+ let mut dropped = Vec::new();
+ while self.latest_lists.len() > DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT {
+ let oldest = self.latest_lists.pop_front().expect("more lists than are kept");
+ for id in oldest {
+ let count = self.lists_naming.get_mut(&id).expect("a kept list names a kept chunk");
+ *count -= 1;
+ if *count == 0 {
+ self.lists_naming.remove(&id);
+ dropped.push(id);
+ }
+ }
+ }
+ dropped
+ }
+}
+
/// 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)]
@@ -132,6 +175,24 @@ mod tests {
builder.finish()
}
+ #[test]
+ fn a_chunk_is_kept_while_one_of_the_latest_lists_names_it() {
+ let id = |value: u64| ChunkId([value, value]);
+ let mut kept = KeptChunks::default();
+ assert!(kept.take_in(&[id(1), id(2), id(1)]).is_empty());
+ assert!(kept.keeps(id(1)) && kept.keeps(id(2)));
+ for _ in 1..DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT {
+ assert!(kept.take_in(&[id(2), id(3)]).is_empty());
+ }
+ // The list that named the first chunk twice leaves, and the one it named alone goes with it.
+ assert_eq!(kept.take_in(&[id(3)]), vec![id(1)]);
+ assert!(!kept.keeps(id(1)) && kept.keeps(id(2)) && kept.keeps(id(3)));
+ for _ in 1..DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT {
+ kept.take_in(&[id(3)]);
+ }
+ assert!(!kept.keeps(id(2)));
+ }
+
#[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]);
diff --git a/Libraries/LibCompositing/Rust/src/display_list/storage.rs b/Libraries/LibCompositing/Rust/src/display_list/storage.rs
index 4144550d071..ceb08132b01 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/storage.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/storage.rs
@@ -8,6 +8,7 @@
//! or a tape that came from another process and passed validation.
use super::builder::RecordedDisplayList;
+use super::chunks::{Chunk, ChunkId, chunk_id};
use super::commands::{ContextRef, DisplayListCommandRun};
use super::effect_clip_plan::EffectClipPlan;
use super::summary::{DisplayListSummary, summarize};
@@ -114,14 +115,6 @@ impl DisplayListStorage {
}
}
-// The tape and its run table packed together for transport: the tape first, then the runs.
-/// The size of a tape and run table packed for transport.
-pub fn packed_size(tape_size: usize, run_count: usize) -> Option<usize> {
- run_count
- .checked_mul(std::mem::size_of::<DisplayListCommandRun>())?
- .checked_add(tape_size)
-}
-
// Writes a run field by field, so its padding is written too.
pub(super) fn write_run(run: &DisplayListCommandRun, out: &mut [u8]) {
use std::mem::offset_of;
@@ -165,93 +158,211 @@ pub(super) fn write_run(run: &DisplayListCommandRun, out: &mut [u8]) {
);
}
-impl DisplayListStorage {
- /// The size of the tape and run table packed for transport.
- pub fn packed_size(&self) -> usize {
- packed_size(self.bytes().len(), self.command_runs().len()).expect("a stored tape fits in memory")
+/// The size of one chunk packed for transport: its records, and then its runs.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct PackedChunkSize {
+ pub record_bytes: u64,
+ pub run_count: u64,
+}
+
+impl PackedChunkSize {
+ pub fn of(chunk: &Chunk) -> Self {
+ Self {
+ record_bytes: chunk.records.len() as u64,
+ run_count: chunk.runs.len() as u64,
+ }
}
- /// Writes the tape and run table packed for transport to `destination`, which is `packed_size()` bytes long.
- pub fn write_packed(&self, destination: &mut [u8]) {
- let (tape, runs) = (self.bytes(), self.command_runs());
- assert_eq!(destination.len(), self.packed_size());
- let (tape_destination, runs_destination) = destination.split_at_mut(tape.len());
- tape_destination.copy_from_slice(tape);
- let (run_destinations, _) =
- runs_destination.as_chunks_mut::<{ std::mem::size_of::<DisplayListCommandRun>() }>();
- for (run, out) in runs.iter().zip(run_destinations) {
+ fn in_bytes(self) -> Option<(usize, usize)> {
+ let record_bytes = usize::try_from(self.record_bytes).ok()?;
+ let run_bytes = usize::try_from(self.run_count)
+ .ok()?
+ .checked_mul(std::mem::size_of::<DisplayListCommandRun>())?;
+ Some((record_bytes, run_bytes))
+ }
+}
+
+/// The size of `chunks` packed for transport one after another.
+pub fn packed_size_of_chunks(chunks: &[&Chunk]) -> usize {
+ chunks
+ .iter()
+ .map(|chunk| chunk.records.len() + chunk.runs.len() * std::mem::size_of::<DisplayListCommandRun>())
+ .sum()
+}
+
+/// Writes `chunks` packed for transport one after another to `destination`, which is
+/// `packed_size_of_chunks(chunks)` bytes long.
+pub fn write_packed_chunks(chunks: &[&Chunk], destination: &mut [u8]) {
+ assert_eq!(destination.len(), packed_size_of_chunks(chunks));
+ let mut rest = destination;
+ for chunk in chunks {
+ let (records, after_records) = rest.split_at_mut(chunk.records.len());
+ records.copy_from_slice(&chunk.records);
+ let (runs, after_runs) =
+ after_records.split_at_mut(chunk.runs.len() * std::mem::size_of::<DisplayListCommandRun>());
+ let (run_destinations, _) = runs.as_chunks_mut::<{ std::mem::size_of::<DisplayListCommandRun>() }>();
+ for (run, out) in chunk.runs.iter().zip(run_destinations) {
write_run(run, out);
}
+ rest = after_runs;
}
+}
- /// The tape and run table packed for transport.
- pub fn packed(&self) -> Vec<u8> {
- let mut packed = vec![0; self.packed_size()];
- self.write_packed(&mut packed);
- packed
- }
+/// A chunk another process sent that passed validation, named by what it holds: its records in memory aligned for
+/// every command struct, and its runs.
+pub struct ReceivedChunk {
+ pub id: ChunkId,
+ records: AlignedBytes,
+ runs: Vec<DisplayListCommandRun>,
}
-/// Copies a packed tape and run table out of the bytes of a message, and checks the copy.
-pub fn receive_packed(
- packed: &[u8],
- tape_size: usize,
- run_count: usize,
-) -> Result<Arc<DisplayListStorage>, &'static str> {
- let size = packed_size(tape_size, run_count).ok_or("Display list sizes overflow")?;
- if size > packed.len() {
- return Err("Display list sizes exceed the bytes that hold it");
+impl ReceivedChunk {
+ pub fn records(&self) -> &[u8] {
+ self.records.as_slice()
}
- // Every run holds at least one record, so more runs than headers cannot describe the tape.
- if run_count > tape_size / super::builder::HEADER_SIZE {
- return Err("Display list run table is larger than its tape allows");
+
+ pub fn runs(&self) -> &[DisplayListCommandRun] {
+ &self.runs
}
- let mut bytes = AlignedBytes::try_zeroed(tape_size).ok_or("Display list is too large to receive")?;
- bytes.as_mut_slice().copy_from_slice(&packed[..tape_size]);
- let command_runs = validate_tape(bytes.as_slice(), &packed[tape_size..size])?;
- Ok(DisplayListStorage::new(Tape::Received { bytes, command_runs }, None))
}
-/// Copies a packed tape and run table out of memory that another process can still write to, and checks the copy.
+/// Copies the chunks packed one after another in the `packed_size_in_bytes` bytes at `packed`, whose sizes `sizes` lists
+/// in order, out of memory that another process can still write to, checks each copy and names it by what it holds.
///
/// # Safety
/// `packed` must address `packed_size_in_bytes` readable bytes, or be null with a size of zero.
-pub unsafe fn receive_packed_from_shared_memory(
+pub unsafe fn receive_packed_chunks_from_shared_memory(
packed: *const u8,
packed_size_in_bytes: usize,
- tape_size: usize,
- run_count: usize,
-) -> Result<Arc<DisplayListStorage>, &'static str> {
- let size = packed_size(tape_size, run_count).ok_or("Display list sizes overflow")?;
- if size > packed_size_in_bytes {
- return Err("Display list sizes exceed the buffer that holds it");
+ sizes: &[PackedChunkSize],
+) -> Result<Vec<ReceivedChunk>, &'static str> {
+ let mut chunks = Vec::new();
+ chunks
+ .try_reserve_exact(sizes.len())
+ .map_err(|_| "Display list has too many chunks to receive")?;
+ let mut offset = 0usize;
+ for size in sizes {
+ let (record_bytes, run_bytes) = size.in_bytes().ok_or("Display list chunk sizes overflow")?;
+ let end = offset
+ .checked_add(record_bytes)
+ .and_then(|end| end.checked_add(run_bytes))
+ .ok_or("Display list chunk sizes overflow")?;
+ if end > packed_size_in_bytes {
+ return Err("Display list chunks exceed the buffer that holds them");
+ }
+ // Every run holds at least one record, so more runs than headers cannot describe the chunk.
+ if run_bytes / std::mem::size_of::<DisplayListCommandRun>() > record_bytes / super::builder::HEADER_SIZE {
+ return Err("Display list chunk has more runs than its records allow");
+ }
+ let mut records = AlignedBytes::try_zeroed(record_bytes).ok_or("Display list chunk is too large to receive")?;
+ let mut packed_runs = Vec::new();
+ packed_runs
+ .try_reserve_exact(run_bytes)
+ .map_err(|_| "Display list chunk is too large to receive")?;
+ packed_runs.resize(run_bytes, 0);
+ if end > offset {
+ // SAFETY: The caller guarantees `packed` addresses `packed_size_in_bytes` bytes, which hold `offset..end`,
+ // and both copies have room for their part.
+ unsafe {
+ std::ptr::copy_nonoverlapping(packed.add(offset), records.as_mut_slice().as_mut_ptr(), record_bytes);
+ std::ptr::copy_nonoverlapping(packed.add(offset + record_bytes), packed_runs.as_mut_ptr(), run_bytes);
+ }
+ }
+ let runs = validate_tape(records.as_slice(), &packed_runs)?;
+ chunks.push(ReceivedChunk {
+ id: chunk_id(records.as_slice(), &runs, 0),
+ records,
+ runs,
+ });
+ offset = end;
}
- // Every run holds at least one record, so more runs than headers cannot describe the tape.
- if run_count > tape_size / super::builder::HEADER_SIZE {
- return Err("Display list run table is larger than its tape allows");
+ if offset != packed_size_in_bytes {
+ return Err("Display list chunks do not fill the buffer that holds them");
}
- let mut bytes = AlignedBytes::try_zeroed(tape_size).ok_or("Display list is too large to receive")?;
- let mut run_bytes = Vec::new();
- run_bytes
- .try_reserve_exact(size - tape_size)
- .map_err(|_| "Display list is too large to receive")?;
- run_bytes.resize(size - tape_size, 0);
- if size > 0 {
- // SAFETY: The caller guarantees `packed` addresses at least `size` bytes, and both copies have room for their
- // part.
- unsafe {
- std::ptr::copy_nonoverlapping(packed, bytes.as_mut_slice().as_mut_ptr(), tape_size);
- std::ptr::copy_nonoverlapping(packed.add(tape_size), run_bytes.as_mut_ptr(), size - tape_size);
+ Ok(chunks)
+}
+
+/// Copies the chunks packed one after another in `packed`, whose sizes `sizes` lists in order, out, checks each copy and
+/// names it by what it holds.
+pub fn receive_packed_chunks(packed: &[u8], sizes: &[PackedChunkSize]) -> Result<Vec<ReceivedChunk>, &'static str> {
+ // SAFETY: The slice addresses its bytes.
+ unsafe { receive_packed_chunks_from_shared_memory(packed.as_ptr(), packed.len(), sizes) }
+}
+
+impl DisplayListStorage {
+ /// The tape of `chunks`, which another process sent, one after another.
+ pub fn of_received_chunks(chunks: &[Arc<ReceivedChunk>]) -> Result<Arc<Self>, &'static str> {
+ let tape_size = chunks.iter().map(|chunk| chunk.records().len()).sum::<usize>();
+ if u32::try_from(tape_size).is_err() {
+ return Err("Display list exceeds the size of a tape");
}
+ let mut bytes = AlignedBytes::try_zeroed(tape_size).ok_or("Display list is too large to receive")?;
+ let mut command_runs = Vec::new();
+ command_runs
+ .try_reserve_exact(chunks.iter().map(|chunk| chunk.runs().len()).sum())
+ .map_err(|_| "Display list is too large to receive")?;
+ let mut chunk_start = 0;
+ for chunk in chunks {
+ let records = chunk.records();
+ bytes.as_mut_slice()[chunk_start..chunk_start + records.len()].copy_from_slice(records);
+ command_runs.extend(chunk.runs().iter().map(|run| DisplayListCommandRun {
+ offset: run.offset + chunk_start as u32,
+ ..*run
+ }));
+ chunk_start += records.len();
+ }
+ Ok(DisplayListStorage::new(Tape::Received { bytes, command_runs }, None))
}
- let command_runs = validate_tape(bytes.as_slice(), &run_bytes)?;
- Ok(DisplayListStorage::new(Tape::Received { bytes, command_runs }, None))
}
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn chunks_packed_for_transport_come_back_as_the_tape_they_make() {
+ use super::super::builder::DisplayListBuilder;
+ use super::super::commands::{ClipNodeIndex, EffectNodeIndex, FillRect, SpatialNodeIndex};
+ use libgfx_rust::{Color, CompositingAndBlendingOperator, IntRect};
+ let context = |spatial| ContextRef {
+ spatial: SpatialNodeIndex(spatial),
+ clip: ClipNodeIndex::NONE,
+ effect: EffectNodeIndex::NONE,
+ };
+ let fill_rect = |y| FillRect {
+ rect: IntRect::new(0, y, 10, 10),
+ color: Color::default(),
+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,
+ background_color_animation_effect: EffectNodeIndex::NONE,
+ };
+ let mut builder = DisplayListBuilder::new();
+ builder.append(&fill_rect(0), &[], context(1));
+ let first = builder.take_chunk();
+ builder.append(&fill_rect(10), &[], context(1));
+ builder.append(&fill_rect(20), &[], context(2));
+ let second = builder.take_chunk();
+ let chunks = [&first, &second];
+ let mut packed = vec![0; packed_size_of_chunks(&chunks)];
+ write_packed_chunks(&chunks, &mut packed);
+ let sizes: Vec<PackedChunkSize> = chunks.iter().map(|chunk| PackedChunkSize::of(chunk)).collect();
+
+ let received = receive_packed_chunks(&packed, &sizes).unwrap();
+ for (received, sent) in received.iter().zip(chunks) {
+ assert_eq!(received.id, sent.id);
+ assert_eq!(received.records(), &sent.records[..]);
+ assert_eq!(received.runs(), &sent.runs[..]);
+ }
+ let received: Vec<Arc<ReceivedChunk>> = received.into_iter().map(Arc::new).collect();
+ let storage = DisplayListStorage::of_received_chunks(&received).unwrap();
+ let tape = RecordedDisplayList::of_chunks(chunks);
+ assert_eq!(storage.bytes(), &tape.bytes[..]);
+ assert_eq!(storage.command_runs(), &tape.command_runs[..]);
+
+ // Sizes that leave bytes over or claim more than the buffer holds are refused.
+ assert!(receive_packed_chunks(&packed, &sizes[..1]).is_err());
+ assert!(receive_packed_chunks(&packed[..packed.len() - 8], &sizes).is_err());
+ }
+
#[test]
fn published_bytes_survive_the_recorder_and_can_be_released_on_another_thread() {
fn assert_send_sync<T: Send + Sync>() {}
diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rs
index 06c17ccfb62..4b3de32a97e 100644
--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs
+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs
@@ -11,7 +11,9 @@
#![allow(non_camel_case_types)]
use crate::css_pixels::{CssPixelPoint, CssPixels};
+use crate::display_list::chunks::ChunkId;
use crate::display_list::commands::{CompositorContextId, UniqueNodeId};
+use crate::display_list::storage::PackedChunkSize;
use crate::visual_context::VisualContextTree;
use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder, File};
use std::sync::Arc;
@@ -155,22 +157,24 @@ impl Decode for Core_AnonymousBuffer {
}
}
-/// `Compositing::DisplayList`: a display list on its way to the compositor, with its tape and run table packed in shared
-/// memory, which the compositor copies out of it, and what travels beside them.
+/// `Compositing::DisplayList`: a display list on its way to the compositor. It names its chunks in paint order, and
+/// carries the records and runs of those the compositor does not keep packed in shared memory, which the compositor
+/// copies out of it, with what travels beside them.
#[derive(Debug)]
pub struct SharedDisplayList {
- pub packed_tape: Core_AnonymousBuffer,
- pub tape_size: u64,
- pub run_count: u64,
+ pub chunks_in_paint_order: Vec<ChunkId>,
+ pub packed_chunks: Core_AnonymousBuffer,
+ /// The size of each chunk packed, in the order they are packed.
+ pub packed_chunk_sizes: Vec<PackedChunkSize>,
pub properties: Compositing_DisplayListProperties,
pub async_scrolling_metadata: Option<Compositing_AsyncScrollingMetadata>,
}
impl Encode for SharedDisplayList {
fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
- encoder.encode(&self.packed_tape)?;
- encoder.encode(&self.tape_size)?;
- encoder.encode(&self.run_count)?;
+ encoder.encode(&self.chunks_in_paint_order)?;
+ encoder.encode(&self.packed_chunks)?;
+ encoder.encode(&self.packed_chunk_sizes)?;
encoder.encode(&self.properties)?;
encoder.encode(&self.async_scrolling_metadata)
}
@@ -179,15 +183,48 @@ impl Encode for SharedDisplayList {
impl Decode for SharedDisplayList {
fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
Ok(Self {
- packed_tape: decoder.decode()?,
- tape_size: decoder.decode()?,
- run_count: decoder.decode()?,
+ chunks_in_paint_order: decoder.decode()?,
+ packed_chunks: decoder.decode()?,
+ packed_chunk_sizes: decoder.decode()?,
properties: decoder.decode()?,
async_scrolling_metadata: decoder.decode()?,
})
}
}
+impl Encode for ChunkId {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.encode(&self.0[0])?;
+ encoder.encode(&self.0[1])
+ }
+}
+
+impl Decode for ChunkId {
+ const MIN_ENCODED_SIZE: usize = 2 * size_of::<u64>();
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ Ok(Self([decoder.decode()?, decoder.decode()?]))
+ }
+}
+
+impl Encode for PackedChunkSize {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.encode(&self.record_bytes)?;
+ encoder.encode(&self.run_count)
+ }
+}
+
+impl Decode for PackedChunkSize {
+ const MIN_ENCODED_SIZE: usize = 2 * size_of::<u64>();
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ Ok(Self {
+ record_bytes: decoder.decode()?,
+ run_count: decoder.decode()?,
+ })
+ }
+}
+
include!(concat!(env!("OUT_DIR"), "/AsyncScrollNodeStableID.rs"));
include!(concat!(env!("OUT_DIR"), "/DisplayListProperties.rs"));
include!(concat!(env!("OUT_DIR"), "/InputEvent.rs"));
diff --git a/Libraries/LibWeb/Rust/src/paint_stage.rs b/Libraries/LibWeb/Rust/src/paint_stage.rs
index ad65d460c18..58933a7214d 100644
--- a/Libraries/LibWeb/Rust/src/paint_stage.rs
+++ b/Libraries/LibWeb/Rust/src/paint_stage.rs
@@ -11,8 +11,10 @@
//! it, so frames reach the compositor in the order their jobs were handed out, and code that runs anywhere else cannot
//! present a frame: it has no [`Presenting`] to present with.
+use crate::painting::display_list::chunks::{Chunk, ChunkId};
use crate::painting::display_list::commands::CompositorContextId;
-use crate::painting::display_list::storage::DisplayListStorage;
+use crate::painting::display_list::storage::{PackedChunkSize, packed_size_of_chunks, write_packed_chunks};
+use crate::painting::presentation::SentDisplayListChunks;
use crate::render_state::SampledFrame;
use crate::stage_thread::{InFlight, Relay, Riding, StageThread};
use libcompositing_rust::ipc_types::{
@@ -110,20 +112,23 @@ impl CompositorPoster {
}
}
- /// The display list `storage` holds, with `properties` and `async_scrolling_metadata`, as a message carries it, or none
- /// where its tape cannot be placed in shared memory.
+ /// The display list that names `chunks_in_paint_order` and carries `new_chunks`, the ones the compositor does not
+ /// keep, with `properties` and `async_scrolling_metadata`, as a message carries it, or none where the chunks cannot
+ /// be placed in shared memory.
pub(crate) fn share_display_list(
&self,
- storage: &DisplayListStorage,
+ chunks_in_paint_order: Vec<ChunkId>,
+ new_chunks: &[&Chunk],
properties: Compositing_DisplayListProperties,
async_scrolling_metadata: Option<Compositing_AsyncScrollingMetadata>,
) -> Option<SharedDisplayList> {
- let packed_tape =
- self.shared_buffer_with(storage.packed_size(), |destination| storage.write_packed(destination))?;
+ let packed_chunks = self.shared_buffer_with(packed_size_of_chunks(new_chunks), |destination| {
+ write_packed_chunks(new_chunks, destination);
+ })?;
Some(SharedDisplayList {
- packed_tape,
- tape_size: storage.bytes().len() as u64,
- run_count: storage.command_runs().len() as u64,
+ chunks_in_paint_order,
+ packed_chunks,
+ packed_chunk_sizes: new_chunks.iter().map(|chunk| PackedChunkSize::of(chunk)).collect(),
properties,
async_scrolling_metadata,
})
@@ -216,6 +221,16 @@ unsafe impl Sync for StageCell {}
struct PaintStage {
/// The poster of the connection to the compositor, while it can be reached.
poster: Option<CompositorPoster>,
+ /// What the compositor at the other end of the poster keeps of the display lists sent for each context, which a
+ /// new connection starts without.
+ sent_display_list_chunks: std::collections::HashMap<CompositorContextId, SentDisplayListChunks>,
+}
+
+impl PaintStage {
+ fn present_through(&mut self, poster: Option<CompositorPoster>) {
+ self.poster = poster;
+ self.sent_display_list_chunks.clear();
+ }
}
fn the_paint_thread() -> &'static PaintThread {
@@ -258,10 +273,22 @@ impl Presenting<'_> {
self.stage.poster.as_ref()
}
+ /// The poster frames are presented through, with what the compositor keeps of the display lists sent for each
+ /// context, or none while the compositor cannot be reached.
+ pub(crate) fn poster_and_sent_display_list_chunks(
+ &mut self,
+ ) -> Option<(
+ &CompositorPoster,
+ &mut std::collections::HashMap<CompositorContextId, SentDisplayListChunks>,
+ )> {
+ let stage = &mut *self.stage;
+ Some((stage.poster.as_ref()?, &mut stage.sent_display_list_chunks))
+ }
+
/// Drops the poster of a compositor that can no longer be reached: the connection learns of that on its own thread,
/// and hands over the poster of the next one.
pub(crate) fn lose_compositor(&mut self) {
- self.stage.poster = None;
+ self.stage.present_through(None);
}
}
@@ -314,7 +341,7 @@ pub unsafe extern "C" fn paint_stage_adopt_compositor_poster(poster: FfiThreadSa
let incoming = IncomingPoster(unsafe { CompositorPoster::adopt(poster) });
paint_thread().post(move || {
let IncomingPoster(poster) = incoming;
- Presenting::lend(|presenting| presenting.stage.poster = Some(poster));
+ Presenting::lend(|presenting| presenting.stage.present_through(Some(poster)));
});
}
diff --git a/Libraries/LibWeb/Rust/src/painting/presentation.rs b/Libraries/LibWeb/Rust/src/painting/presentation.rs
index 0f59a6630d0..d5db9ed75e7 100644
--- a/Libraries/LibWeb/Rust/src/painting/presentation.rs
+++ b/Libraries/LibWeb/Rust/src/painting/presentation.rs
@@ -12,12 +12,13 @@
//! their presentations were presented. The navigable reads what the presenter presented on the main thread.
use crate::paint_stage::Presenting;
+use crate::painting::display_list::chunks::{Chunk, ChunkId, KeptChunks};
use crate::painting::display_list::commands::CompositorContextId;
-use crate::painting::display_list::storage::DisplayListStorage;
use crate::painting::display_list_resources::DisplayListResources;
use crate::painting::paint_passes::ClockTickVisualContexts;
use crate::painting::record::RecordingOutput;
-use crate::painting::vector_image_records::display_list_holding_vector_image_records;
+use crate::painting::record::order_tree::RecordedChunk;
+use crate::painting::vector_image_records::{VectorImageRecords, chunk_holding_vector_image_records};
use crate::painting::visual_context::VisualContextTree;
use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{
ApplyScrollRequests, PresentFrame, UpdateDisplayList, UpdateScrollState, UpdateVisualContextTree,
@@ -31,6 +32,7 @@ use libgfx_rust::IntRect;
use libgfx_rust::font::FontHandle;
use libgfx_rust::image_frame::ImageFrameHandle;
use libipc_rust::wire::{Decode, Decoder};
+use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard};
/// What presented a navigable's last frame: the recording of a frame a rendering update committed, or a tick of the
@@ -598,18 +600,64 @@ fn post_resources_ahead(
impl Presenting<'_> {
/// Hands `frame` to the compositor, or drops it while the compositor cannot be reached.
fn post_frame(&mut self, frame: CompositorFrame) {
- let Some(poster) = self.poster() else {
+ let Some((poster, sent_display_list_chunks)) = self.poster_and_sent_display_list_chunks() else {
return;
};
- if !post_frame_through(poster, frame) {
+ if !post_frame_through(poster, sent_display_list_chunks, frame) {
self.lose_compositor();
}
}
}
-/// Posts the messages of `frame` through `poster`, in order. Answers whether the compositor could still be reached: a
-/// display list that cannot be placed in shared memory is skipped, and the rest of the frame still goes over.
-fn post_frame_through(poster: &crate::paint_stage::CompositorPoster, frame: CompositorFrame) -> bool {
+/// What the compositor keeps of the display lists sent for one context, which a display list sends the chunks it lacks
+/// of, and the chunks that draw SVG images as they were sent, with the records of the images in them.
+#[derive(Default)]
+pub(crate) struct SentDisplayListChunks {
+ kept: KeptChunks,
+ holding_vector_image_records: HashMap<ChunkId, Arc<Chunk>>,
+}
+
+impl SentDisplayListChunks {
+ /// `chunk` as the compositor replays it, with the records of `vector_images`, the SVG images it draws, in it.
+ fn as_sent(&mut self, chunk: &RecordedChunk, vector_images: &HashMap<u64, Arc<VectorImageRecords>>) -> Arc<Chunk> {
+ let latest = chunk.latest();
+ if !chunk.draws_vector_image_placeholders() {
+ return Arc::clone(latest);
+ }
+ // A chunk's name says which SVG images it draws, whose records never change.
+ Arc::clone(
+ self.holding_vector_image_records
+ .entry(latest.id)
+ .or_insert_with(|| Arc::new(chunk_holding_vector_image_records(latest, vector_images))),
+ )
+ }
+
+ /// The chunks of `chunks_as_sent` the compositor does not keep, once each.
+ fn new_chunks<'a>(&self, chunks_as_sent: &'a [Arc<Chunk>]) -> Vec<&'a Chunk> {
+ let mut named = std::collections::HashSet::new();
+ chunks_as_sent
+ .iter()
+ .filter(|chunk| !self.kept.keeps(chunk.id) && named.insert(chunk.id))
+ .map(|chunk| &**chunk)
+ .collect()
+ }
+
+ /// Takes in a display list sent that names `chunks_in_paint_order`.
+ fn take_in(&mut self, chunks_in_paint_order: &[ChunkId]) {
+ self.kept.take_in(chunks_in_paint_order);
+ let kept = &self.kept;
+ self.holding_vector_image_records.retain(|_, sent| kept.keeps(sent.id));
+ }
+}
+
+/// Posts the messages of `frame` through `poster`, in order, where `sent_display_list_chunks` says what the compositor
+/// keeps of the display lists sent before. Answers whether the compositor could still be reached: a display list that
+/// cannot be placed in shared memory is skipped, and the rest of the frame still goes over.
+fn post_frame_through(
+ poster: &crate::paint_stage::CompositorPoster,
+ sent_display_list_chunks: &mut HashMap<CompositorContextId, SentDisplayListChunks>,
+ frame: CompositorFrame,
+) -> bool {
let CompositorFrame {
context_id,
display_list_update,
@@ -622,23 +670,23 @@ fn post_frame_through(poster: &crate::paint_stage::CompositorPoster, frame: Comp
if !post_resources_ahead(poster, context_id, &update.resources) {
return false;
}
- // The compositor replays a tape with the records of the SVG images it draws in it.
- let display_list = match update.output.resources.vector_images.is_empty() {
- true => update.output.display_list.clone(),
- false => Arc::new(display_list_holding_vector_image_records(
- &update.output.display_list,
- &update.output.resources.vector_images,
- )),
- };
- let storage = DisplayListStorage::recorded(
- display_list,
- update
- .output
- .visual_context_tree
- .clone()
- .unwrap_or_else(|| Arc::new(VisualContextTree::create_identity())),
- );
- match poster.share_display_list(&storage, update.properties, Some(update.async_scrolling_metadata)) {
+ // The compositor replays chunks with the records of the SVG images they draw in them.
+ let sent = sent_display_list_chunks.entry(context_id).or_default();
+ let vector_images = &update.output.resources.vector_images;
+ let chunks_as_sent: Vec<Arc<Chunk>> = update
+ .output
+ .chunks
+ .iter()
+ .map(|chunk| sent.as_sent(chunk, vector_images))
+ .collect();
+ let chunks_in_paint_order: Vec<ChunkId> = chunks_as_sent.iter().map(|chunk| chunk.id).collect();
+ let new_chunks = sent.new_chunks(&chunks_as_sent);
+ match poster.share_display_list(
+ chunks_in_paint_order.clone(),
+ &new_chunks,
+ update.properties,
+ Some(update.async_scrolling_metadata),
+ ) {
Some(display_list) => {
let message = UpdateDisplayList {
context_id,
@@ -649,11 +697,12 @@ fn post_frame_through(poster: &crate::paint_stage::CompositorPoster, frame: Comp
if !poster.post(message) {
return false;
}
+ sent.take_in(&chunks_in_paint_order);
}
None => {
eprintln!(
- "WebContent: Could not place a {} byte display list in shared memory",
- storage.bytes().len()
+ "WebContent: Could not place {} new display list chunks in shared memory",
+ new_chunks.len()
);
}
}
diff --git a/Libraries/LibWeb/Rust/src/painting/rasterize.rs b/Libraries/LibWeb/Rust/src/painting/rasterize.rs
index 6378098086d..1f04d0f16f9 100644
--- a/Libraries/LibWeb/Rust/src/painting/rasterize.rs
+++ b/Libraries/LibWeb/Rust/src/painting/rasterize.rs
@@ -9,9 +9,9 @@
use crate::paint_stage::CompositorPoster;
use crate::painting::display_list::builder::RecordedDisplayList;
-use crate::painting::display_list::commands::{DisplayListResourceId, ImageFrameResourceId};
+use crate::painting::display_list::chunks::{Chunk, chunks_of};
+use crate::painting::display_list::commands::{DisplayListCommandRun, DisplayListResourceId, ImageFrameResourceId};
use crate::painting::display_list::ids::allocate_display_list_id;
-use crate::painting::display_list::storage::DisplayListStorage;
use crate::painting::display_list_resources::DisplayListResources;
use crate::painting::force_dark::ForceDarkRole;
use crate::painting::vector_image_cache::{FfiVectorImageKey, VectorImageKey};
@@ -147,17 +147,32 @@ fn post_rasterization(
if !unsafe { poster.stage_rasterization(token, &fonts, &image_frames, target_bitmap) } {
return false;
}
- let storage = DisplayListStorage::recorded(Arc::new(display_list), tree.clone());
+ // The list goes whole, as chunks named by what the compositor replays.
+ let chunks: Vec<Chunk> = chunks_of(&display_list.bytes, &display_list.command_runs, &display_list.chunks)
+ .map(|(chunk, records, runs)| {
+ let chunk_start = chunk.byte_end - records.len() as u32;
+ let runs = runs
+ .iter()
+ .map(|run| DisplayListCommandRun {
+ offset: run.offset - chunk_start,
+ ..*run
+ })
+ .collect();
+ Chunk::named(records.to_vec(), runs)
+ })
+ .collect();
+ let chunks: Vec<&Chunk> = chunks.iter().collect();
let properties = Compositing_DisplayListProperties {
id: allocate_display_list_id(),
compatible_visual_context_tree_structural_epoch: tree.structural_epoch,
surface_clear_color: None,
root_group_color,
};
- let Some(display_list) = poster.share_display_list(&storage, properties, None) else {
+ let chunks_in_paint_order = chunks.iter().map(|chunk| chunk.id).collect();
+ let Some(display_list) = poster.share_display_list(chunks_in_paint_order, &chunks, properties, None) else {
eprintln!(
"WebContent: Could not place a {} byte display list to rasterize in shared memory",
- storage.bytes().len()
+ display_list.bytes.len()
);
return false;
};
diff --git a/Libraries/LibWeb/Rust/src/painting/vector_image_records.rs b/Libraries/LibWeb/Rust/src/painting/vector_image_records.rs
index 176ab350363..c3df75c1bc8 100644
--- a/Libraries/LibWeb/Rust/src/painting/vector_image_records.rs
+++ b/Libraries/LibWeb/Rust/src/painting/vector_image_records.rs
@@ -10,7 +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::chunks::{Chunk, DisplayListChunk};
use crate::painting::display_list::commands::{
DeclareMaskContent, DisplayListCommandHeader, DisplayListCommandRun, DisplayListCommandType, DisplayListDataSpan,
DisplayListGradientColorStops, DisplayListGradientPaintStyle, DisplayListInlineClip, DisplayListPaintStyle,
@@ -333,14 +333,36 @@ pub(crate) fn display_list_holding_vector_image_records(
}
}
+/// `chunk` with the records of `vector_images`, the SVG images its commands name, in the payloads of the commands that
+/// paint them, as the compositor replays it.
+pub(crate) fn chunk_holding_vector_image_records(
+ chunk: &Chunk,
+ vector_images: &HashMap<u64, Arc<VectorImageRecords>>,
+) -> Chunk {
+ let mut bytes = Vec::with_capacity(chunk.records.len());
+ let mut runs = Vec::with_capacity(chunk.runs.len());
+ for run in &chunk.runs {
+ let offset = u32::try_from(bytes.len()).expect("display list exceeds u32");
+ let records = &chunk.records[run.offset as usize..(run.offset + run.size) as usize];
+ append_records_holding_vector_image_records(records, vector_images, &mut bytes);
+ runs.push(DisplayListCommandRun {
+ offset,
+ size: u32::try_from(bytes.len()).expect("display list exceeds u32") - offset,
+ ..*run
+ });
+ }
+ Chunk::named(bytes, runs)
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::painting::display_list::builder::{DisplayListBuilder, PendingInlineClip, inline_clips_of};
use crate::painting::display_list::commands::{ContextRef, DisplayListResourceId, Repeat};
use crate::painting::display_list::nested_records::span_bytes;
- use crate::painting::display_list::storage::{DisplayListStorage, receive_packed};
- use crate::painting::visual_context::VisualContextTree;
+ use crate::painting::display_list::storage::{
+ PackedChunkSize, packed_size_of_chunks, receive_packed_chunks, write_packed_chunks,
+ };
use libgfx_rust::path::Path;
use libgfx_rust::{
Color, CompositingAndBlendingOperator, FloatPoint, FloatRect, FloatSize, IntRect, IntSize, MaskKind,
@@ -393,18 +415,13 @@ mod tests {
path.serialize_to_bytes()
}
- // Checks the tape as the compositor does when it receives it.
+ // Checks the tape as the compositor does when it receives it, as one chunk.
fn assert_is_valid_for_the_compositor(display_list: &RecordedDisplayList) {
- let storage = DisplayListStorage::recorded(
- Arc::new(display_list.clone()),
- Arc::new(VisualContextTree::create_identity()),
- );
- receive_packed(
- &storage.packed(),
- display_list.bytes.len(),
- display_list.command_runs.len(),
- )
- .expect("the tape passes the compositor's validation");
+ let chunk = Chunk::named(display_list.bytes.clone(), display_list.command_runs.clone());
+ let mut packed = vec![0; packed_size_of_chunks(&[&chunk])];
+ write_packed_chunks(&[&chunk], &mut packed);
+ receive_packed_chunks(&packed, &[PackedChunkSize::of(&chunk)])
+ .expect("the tape passes the compositor's validation");
}
#[test]
diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rs
index 7ff3a807009..b4b3be6ad69 100644
--- a/Services/Compositor/Rust/src/core/messages.rs
+++ b/Services/Compositor/Rust/src/core/messages.rs
@@ -8,8 +8,10 @@
//! sender may ask for, and the answer a synchronous one gets.
use super::{CompositorCore, ContextOwnerCheckResult};
+use crate::display_list_chunk_stores::chunks_of_list_sent_whole;
use crate::host::{PresentationId, WebContentClientId};
use libcompositing_rust::display_list::replay::{ReplayFrame, ReplaySelection, replay_display_list};
+use libcompositing_rust::display_list::storage::DisplayListStorage;
use libcompositing_rust::ipc_types::compositor_presentation_client::messages::DidNotDispatchInputEvent;
use libcompositing_rust::ipc_types::compositor_presentation_server::messages::{
HandleAndDispatchKeyEvent, HandleAndDispatchMouseEvent, HandleAndDispatchPinchEvent,
@@ -214,13 +216,17 @@ impl MessagesFromWebContent<'_> {
Ok(false)
};
let SharedDisplayList {
- packed_tape,
- tape_size,
- run_count,
+ chunks_in_paint_order,
+ packed_chunks,
+ packed_chunk_sizes,
properties,
..
} = message.display_list;
- let storage = match raster.receive_display_list_storage(packed_tape, tape_size, run_count) {
+ let storage = match raster
+ .receive_display_list_chunks(packed_chunks, &packed_chunk_sizes)
+ .and_then(|sent| chunks_of_list_sent_whole(sent, &chunks_in_paint_order))
+ .and_then(|chunks| DisplayListStorage::of_received_chunks(&chunks))
+ {
Ok(storage) => storage,
Err(error) => {
let _ = writeln!(
@@ -267,18 +273,18 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {
fn update_display_list(&mut self, message: UpdateDisplayList) -> Result<(), Misbehavior> {
let started_at = std::time::Instant::now();
let SharedDisplayList {
- packed_tape,
- tape_size,
- run_count,
+ chunks_in_paint_order,
+ packed_chunks,
+ packed_chunk_sizes,
properties,
async_scrolling_metadata,
} = message.display_list;
- let storage = match self
+ let sent = match self
.core
.raster()
- .receive_display_list_storage(packed_tape, tape_size, run_count)
+ .receive_display_list_chunks(packed_chunks, &packed_chunk_sizes)
{
- Ok(storage) => storage,
+ Ok(sent) => sent,
Err(error) => {
let _ = writeln!(
std::io::stderr(),
@@ -289,6 +295,29 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {
));
}
};
+ let sent_chunk_count = sent.len();
+ // The chunks are taken in before anything else is checked: the list counts as one of the latest of the context
+ // on both ends whether it is installed or not.
+ let chunks = match self.core.take_in_display_list_chunks(
+ self.client_id,
+ message.context_id,
+ sent,
+ &chunks_in_paint_order,
+ ) {
+ Ok(Some(chunks)) => chunks,
+ Ok(None) => return Ok(()),
+ Err(error) => return Err(Misbehavior(error)),
+ };
+ let storage = match DisplayListStorage::of_received_chunks(&chunks) {
+ Ok(storage) => storage,
+ Err(error) => {
+ let _ = writeln!(
+ std::io::stderr(),
+ "Compositor: Dropping display list update from WebContent: {error}"
+ );
+ return Ok(());
+ }
+ };
let adopt_time = started_at.elapsed();
let tree = message.visual_context_tree;
if !self.context_is_owned_by_sender(message.context_id)? {
@@ -335,6 +364,7 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {
return Ok(());
}
let scroll_state_snapshot = message.scroll_state;
+ let storage_size = storage.bytes().len();
let display_list = DisplayList::new(
storage,
properties.id,
@@ -356,7 +386,9 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {
if display_list_timing_enabled() {
let _ = writeln!(
std::io::stderr(),
- "DISPLAY_LIST_RECEIVE bytes={tape_size} adopt={} µs install={} µs",
+ "DISPLAY_LIST_RECEIVE bytes={} chunks={} sent={sent_chunk_count} adopt={} µs install={} µs",
+ storage_size,
+ chunks.len(),
adopt_time.as_micros(),
(started_at.elapsed() - adopt_time).as_micros()
);
diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rs
index 1a31a5959ef..c5e69b180c7 100644
--- a/Services/Compositor/Rust/src/core/mod.rs
+++ b/Services/Compositor/Rust/src/core/mod.rs
@@ -45,6 +45,7 @@ pub struct CompositorCore {
is_entered: Cell<bool>,
wheel_gesture_id_allocator: Rc<WheelGestureIdAllocator>,
scrollbars_always_shown: bool,
+ display_list_chunk_stores: RefCell<crate::display_list_chunk_stores::DisplayListChunkStores>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -116,9 +117,26 @@ impl CompositorCore {
is_entered: Cell::new(false),
wheel_gesture_id_allocator: Rc::new(WheelGestureIdAllocator::default()),
scrollbars_always_shown,
+ display_list_chunk_stores: RefCell::default(),
}
}
+ /// Takes in the chunks of the display list `client` sent for `context_id` (see [`DisplayListChunkStores::take_in`]).
+ ///
+ /// [`DisplayListChunkStores::take_in`]: crate::display_list_chunk_stores::DisplayListChunkStores::take_in
+ pub fn take_in_display_list_chunks(
+ &self,
+ client: WebContentClientId,
+ context_id: CompositorContextId,
+ sent: Vec<libcompositing_rust::display_list::storage::ReceivedChunk>,
+ chunks_in_paint_order: &[libcompositing_rust::display_list::chunks::ChunkId],
+ ) -> Result<Option<Vec<std::sync::Arc<libcompositing_rust::display_list::storage::ReceivedChunk>>>, &'static str>
+ {
+ self.display_list_chunk_stores
+ .borrow_mut()
+ .take_in(client, context_id, sent, chunks_in_paint_order)
+ }
+
pub fn raster(&self) -> &RasterHost {
&self.raster
}
@@ -179,6 +197,7 @@ impl CompositorCore {
}
self.contexts.remove(&context_id);
self.presenting.remove(&context_id);
+ self.display_list_chunk_stores.borrow_mut().forget_context(context_id);
self.update_scroll_capabilities();
self.raster
.set_maximum_display_refresh_rate(self.maximum_display_refresh_rate());
diff --git a/Services/Compositor/Rust/src/display_list_chunk_stores.rs b/Services/Compositor/Rust/src/display_list_chunk_stores.rs
new file mode 100644
index 00000000000..02cc35df80a
--- /dev/null
+++ b/Services/Compositor/Rust/src/display_list_chunk_stores.rs
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The chunks of the display lists each WebContent client sent for each of its contexts. A client sends the chunks of
+//! a display list that the latest lists of the context do not name, and names the rest: both ends keep the chunks of
+//! the latest lists by the same rule, so neither tells the other what it keeps.
+
+use crate::host::WebContentClientId;
+use libcompositing_rust::display_list::chunks::{ChunkId, KeptChunks};
+use libcompositing_rust::display_list::commands::CompositorContextId;
+use libcompositing_rust::display_list::storage::ReceivedChunk;
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+
+#[derive(Default)]
+struct ContextChunks {
+ kept: KeptChunks,
+ chunks: HashMap<ChunkId, Arc<ReceivedChunk>>,
+}
+
+#[derive(Default)]
+pub struct DisplayListChunkStores {
+ stores: HashMap<(WebContentClientId, CompositorContextId), ContextChunks>,
+ /// Contexts that were destroyed, whose ids never come back: what a client still sends for one goes nowhere.
+ destroyed_contexts: HashSet<CompositorContextId>,
+}
+
+impl DisplayListChunkStores {
+ /// Takes in the display list `client` sent for `context`, which names `chunks_in_paint_order` and carries `sent`:
+ /// keeps what it sent and answers the chunks it names in paint order, or none for a context that is gone. A list
+ /// that names a chunk it did not send and the context does not keep is a protocol error.
+ pub fn take_in(
+ &mut self,
+ client: WebContentClientId,
+ context: CompositorContextId,
+ sent: Vec<ReceivedChunk>,
+ chunks_in_paint_order: &[ChunkId],
+ ) -> Result<Option<Vec<Arc<ReceivedChunk>>>, &'static str> {
+ if self.destroyed_contexts.contains(&context) {
+ return Ok(None);
+ }
+ let store = self.stores.entry((client, context)).or_default();
+ let sent_ids: Vec<ChunkId> = sent.iter().map(|chunk| chunk.id).collect();
+ for chunk in sent {
+ // The bytes a name was first received with are the ones it stands for from then on.
+ store.chunks.entry(chunk.id).or_insert_with(|| Arc::new(chunk));
+ }
+ let list = chunks_in_paint_order
+ .iter()
+ .map(|id| store.chunks.get(id).cloned())
+ .collect::<Option<Vec<_>>>()
+ .ok_or("WebContent published a display list that names a chunk the compositor does not keep");
+ for dropped in store.kept.take_in(chunks_in_paint_order) {
+ store.chunks.remove(&dropped);
+ }
+ for id in sent_ids {
+ if !store.kept.keeps(id) {
+ store.chunks.remove(&id);
+ }
+ }
+ list.map(Some)
+ }
+
+ /// Forgets the chunks every client sent for `context`, which was destroyed.
+ pub fn forget_context(&mut self, context: CompositorContextId) {
+ self.stores.retain(|(_, store_context), _| *store_context != context);
+ self.destroyed_contexts.insert(context);
+ }
+}
+
+/// The chunks a display list sent whole names in paint order, or an error where it names one it did not send.
+pub fn chunks_of_list_sent_whole(
+ sent: Vec<ReceivedChunk>,
+ chunks_in_paint_order: &[ChunkId],
+) -> Result<Vec<Arc<ReceivedChunk>>, &'static str> {
+ let sent: HashMap<ChunkId, Arc<ReceivedChunk>> =
+ sent.into_iter().map(|chunk| (chunk.id, Arc::new(chunk))).collect();
+ chunks_in_paint_order
+ .iter()
+ .map(|id| sent.get(id).cloned())
+ .collect::<Option<Vec<_>>>()
+ .ok_or("WebContent sent a display list that names a chunk it does not carry")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use libcompositing_rust::display_list::builder::DisplayListBuilder;
+ use libcompositing_rust::display_list::chunks::{Chunk, DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT};
+ use libcompositing_rust::display_list::commands::{ContextRef, EffectNodeIndex, FillRect};
+ use libcompositing_rust::display_list::storage::{
+ PackedChunkSize, packed_size_of_chunks, receive_packed_chunks, write_packed_chunks,
+ };
+ use libgfx_rust::{Color, CompositingAndBlendingOperator, IntRect};
+
+ fn chunk(y: i32) -> Chunk {
+ let mut builder = DisplayListBuilder::new();
+ builder.append(
+ &FillRect {
+ rect: IntRect::new(0, y, 10, 10),
+ color: Color::default(),
+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,
+ background_color_animation_effect: EffectNodeIndex::NONE,
+ },
+ &[],
+ ContextRef::default(),
+ );
+ builder.take_chunk()
+ }
+
+ fn sent(chunks: &[&Chunk]) -> Vec<ReceivedChunk> {
+ let mut packed = vec![0; packed_size_of_chunks(chunks)];
+ write_packed_chunks(chunks, &mut packed);
+ let sizes: Vec<PackedChunkSize> = chunks.iter().map(|chunk| PackedChunkSize::of(chunk)).collect();
+ receive_packed_chunks(&packed, &sizes).unwrap()
+ }
+
+ #[test]
+ fn a_list_names_what_the_latest_lists_of_its_context_kept_and_sends_the_rest() {
+ let client = WebContentClientId(1);
+ let context = CompositorContextId(7);
+ let (first, second, third) = (chunk(0), chunk(10), chunk(20));
+ let mut stores = DisplayListChunkStores::default();
+
+ let list = stores
+ .take_in(client, context, sent(&[&first, &second]), &[first.id, second.id])
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ list.iter().map(|chunk| chunk.id).collect::<Vec<_>>(),
+ [first.id, second.id]
+ );
+
+ // The next list sends only what is new to the context.
+ let list = stores
+ .take_in(client, context, sent(&[&third]), &[third.id, first.id])
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ list.iter().map(|chunk| chunk.id).collect::<Vec<_>>(),
+ [third.id, first.id]
+ );
+
+ // Another client, or another context, keeps nothing of it.
+ assert!(
+ stores
+ .take_in(WebContentClientId(2), context, Vec::new(), &[first.id])
+ .is_err()
+ );
+ assert!(
+ stores
+ .take_in(client, CompositorContextId(8), Vec::new(), &[first.id])
+ .is_err()
+ );
+
+ // A chunk no kept list names is gone.
+ for _ in 0..DISPLAY_LISTS_WHOSE_CHUNKS_ARE_KEPT {
+ stores.take_in(client, context, Vec::new(), &[third.id]).unwrap();
+ }
+ assert!(stores.take_in(client, context, Vec::new(), &[second.id]).is_err());
+ }
+
+ #[test]
+ fn what_a_client_sends_for_a_destroyed_context_goes_nowhere() {
+ let client = WebContentClientId(1);
+ let context = CompositorContextId(7);
+ let first = chunk(0);
+ let mut stores = DisplayListChunkStores::default();
+ stores.take_in(client, context, sent(&[&first]), &[first.id]).unwrap();
+ stores.forget_context(context);
+ assert!(
+ stores
+ .take_in(client, context, Vec::new(), &[first.id])
+ .unwrap()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn a_list_sent_whole_names_only_what_it_carries() {
+ let (first, second) = (chunk(0), chunk(10));
+ let list = chunks_of_list_sent_whole(sent(&[&first, &second]), &[second.id, first.id]).unwrap();
+ assert_eq!(
+ list.iter().map(|chunk| chunk.id).collect::<Vec<_>>(),
+ [second.id, first.id]
+ );
+ assert!(chunks_of_list_sent_whole(sent(&[&first]), &[second.id]).is_err());
+ }
+}
diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rs
index d90cb049e23..899c11e3180 100644
--- a/Services/Compositor/Rust/src/lib.rs
+++ b/Services/Compositor/Rust/src/lib.rs
@@ -19,6 +19,7 @@ pub mod async_scroll_update_outbox;
pub mod context_scene;
pub mod context_state;
pub mod core;
+pub mod display_list_chunk_stores;
pub mod elastic_overscroll_controller;
pub mod ffi;
pub mod frame_inputs;
diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rs
index 3be859f4e83..ec86edc395a 100644
--- a/Services/Compositor/Rust/src/raster_host.rs
+++ b/Services/Compositor/Rust/src/raster_host.rs
@@ -9,7 +9,9 @@
//! submission, and the display ticks. None of these calls comes back into the core before it returns.
use libcompositing_rust::display_list::commands::CompositorContextId;
-use libcompositing_rust::display_list::storage::{DisplayListStorage, receive_packed_from_shared_memory};
+use libcompositing_rust::display_list::storage::{
+ PackedChunkSize, ReceivedChunk, receive_packed_chunks_from_shared_memory,
+};
use libcompositing_rust::host::FfiRasterPainter;
use libcompositing_rust::ipc_types::Core_AnonymousBuffer;
use libcompositing_rust::time::MonotonicTime;
@@ -17,7 +19,6 @@ use libgfx_rust::{Color, FloatRect, IntRect, IntSize, ScalingMode};
use std::collections::HashMap;
use std::ffi::c_void;
use std::ptr::NonNull;
-use std::sync::Arc;
/// How a surface is drawn into another.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -814,19 +815,16 @@ impl RasterHost {
unsafe { (self.0.set_maximum_display_refresh_rate)(self.host(), refresh_rate) };
}
- /// Copies the tape and run table out of the shared memory they were sent in, and checks the copy.
- pub fn receive_display_list_storage(
+ /// Copies the chunks packed in the shared memory they were sent in, whose sizes `sizes` lists, out, checks each copy
+ /// and names it by what it holds.
+ pub fn receive_display_list_chunks(
&self,
buffer: Core_AnonymousBuffer,
- tape_size: u64,
- run_count: u64,
- ) -> Result<Arc<DisplayListStorage>, &'static str> {
- let (Ok(tape_size), Ok(run_count)) = (usize::try_from(tape_size), usize::try_from(run_count)) else {
- return Err("Display list sizes do not fit on this platform");
- };
+ sizes: &[PackedChunkSize],
+ ) -> Result<Vec<ReceivedChunk>, &'static str> {
let Some((size, file)) = buffer.shared_memory else {
// SAFETY: Nothing is read from an empty buffer.
- return unsafe { receive_packed_from_shared_memory(std::ptr::null(), 0, tape_size, run_count) };
+ return unsafe { receive_packed_chunks_from_shared_memory(std::ptr::null(), 0, sizes) };
};
#[cfg(unix)]
let descriptor = std::os::fd::IntoRawFd::into_raw_fd(file.0);
@@ -840,11 +838,17 @@ impl RasterHost {
if mapping.is_null() {
return Err("Display list buffer is smaller than it claims");
}
- // SAFETY: The mapping holds `data_size` readable bytes at `data` until it is dropped below.
- let storage = unsafe { receive_packed_from_shared_memory(data, data_size, tape_size, run_count) };
+ // The mapping may hold more than the chunks, which fill the size the buffer was sent with.
+ let chunks = match usize::try_from(size) {
+ Ok(size) if size <= data_size => {
+ // SAFETY: The mapping holds `data_size` readable bytes at `data` until it is dropped below.
+ unsafe { receive_packed_chunks_from_shared_memory(data, size, sizes) }
+ }
+ _ => Err("Display list buffer is smaller than it claims"),
+ };
// SAFETY: The mapping came from the host, which drops it once.
unsafe { (self.0.unmap_shared_memory)(mapping) };
- storage
+ chunks
}
pub fn take_registered_image_frames(&self, context_id: CompositorContextId, image_frame_ids: &[u64]) -> bool {