Truly independent web browser
LibCompositing+LibWeb+Compositor: Receive display lists in Rust
Aliaksandr Kalenikcd5faa99ae3a
diff --git a/Libraries/LibCompositing/Rust/src/display_list/storage.rs b/Libraries/LibCompositing/Rust/src/display_list/storage.rsindex e82264d03cc..cca2fb8b9e3 100644--- a/Libraries/LibCompositing/Rust/src/display_list/storage.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/storage.rs@@ -66,6 +66,11 @@ impl AlignedBytes {// SAFETY: The words hold at least `size` initialized bytes.unsafe { ak::slice_from_raw_parts(self.words.as_ptr().cast(), self.size) }}++ fn as_mut_slice(&mut self) -> &mut [u8] {+ // SAFETY: The words hold at least `size` initialized bytes, which this borrows uniquely.+ unsafe { ak::slice_from_raw_parts_mut(self.words.as_mut_ptr().cast(), self.size) }+ }}enum Tape {@@ -217,7 +222,8 @@ pub unsafe extern "C" fn display_list_storage_run_count(storage: *const c_void)}// The tape and its run table packed together for transport: the tape first, then the runs.-fn packed_size(tape_size: usize, run_count: usize) -> Option<usize> {+/// 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)@@ -266,6 +272,43 @@ pub(super) fn write_run(run: &DisplayListCommandRun, out: &mut [u8]) {);}+impl DisplayListStorage {+ /// The tape and run table packed for transport.+ pub fn packed(&self) -> Vec<u8> {+ let (tape, runs) = (self.bytes(), self.command_runs());+ let size = packed_size(tape.len(), runs.len()).expect("a stored tape fits in memory");+ let mut packed = vec![0; size];+ let (tape_destination, runs_destination) = packed.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) {+ write_run(run, out);+ }+ packed+ }+}++/// 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");+ }+ // 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");+ }+ 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 }))+}+/// The size of the storage's tape and run table packed for transport.////// # Safety@@ -315,37 +358,54 @@ pub unsafe extern "C" fn display_list_storage_receive_packed(error: *mut *const u8,error_size: *mut usize,) -> *const c_void {- let fail = |message: &'static str| {- // SAFETY: The caller guarantees both are writable.- unsafe {- *error = message.as_ptr();- *error_size = message.len();+ // SAFETY: The caller guarantees `packed` addresses `packed_size_in_bytes` readable bytes.+ match unsafe { receive_packed_from_shared_memory(packed, packed_size_in_bytes, tape_size, run_count) } {+ Ok(storage) => into_handle(storage),+ Err(message) => {+ // SAFETY: The caller guarantees both are writable.+ unsafe {+ *error = message.as_ptr();+ *error_size = message.len();+ }+ std::ptr::null()}- std::ptr::null()- };- let Some(size) = packed_size(tape_size, run_count) else {- return fail("Display list sizes overflow");- };+ }+}++/// Copies a packed tape and run table out of memory that another process can still write to, and checks the copy.+///+/// # 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(+ 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 fail("Display list sizes exceed the buffer that holds it");+ return Err("Display list sizes exceed the buffer that holds it");}// 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 fail("Display list run table is larger than its tape allows");- }- let pending = display_list_storage_begin(tape_size, run_count);- if pending.pending.is_null() {- return fail("Display list is too large to receive");+ return Err("Display list run table is larger than its tape allows");}+ 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 `begin` made room- // for both parts.+ // SAFETY: The caller guarantees `packed` addresses at least `size` bytes, and both copies have room for their+ // part.unsafe {- std::ptr::copy_nonoverlapping(packed, pending.tape, tape_size);- std::ptr::copy_nonoverlapping(packed.add(tape_size), pending.run_bytes, size - tape_size);+ 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);}}- unsafe { display_list_storage_finish(pending.pending, error, error_size) }+ let command_runs = validate_tape(bytes.as_slice(), &run_bytes)?;+ Ok(DisplayListStorage::new(Tape::Received { bytes, command_runs }))}#[derive(Clone, Copy, Debug)]diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rsindex 06fb5679ae9..1400b0e168d 100644--- a/Libraries/LibCompositing/Rust/src/ffi.rs+++ b/Libraries/LibCompositing/Rust/src/ffi.rs@@ -93,9 +93,11 @@ pub unsafe extern "C" fn display_list_replay(time_nanoseconds: i64,painter: *const crate::host::FfiRasterPainter,) {- // SAFETY: The caller guarantees `painter` is live for the call.- let nested_display_lists = unsafe { (*painter).nested_display_lists() };- let frame = crate::display_list::replay::ReplayFrame::unscrolled(time_nanoseconds, &nested_display_lists);+ // NB: The compositor replays the display lists that nest others itself, with the lists they nest.+ let frame = crate::display_list::replay::ReplayFrame::unscrolled(+ time_nanoseconds,+ &crate::display_list::replay::NoNestedDisplayLists,+ );// SAFETY: The caller guarantees live handles and a live painter for the duration of the call.unsafe {replay_display_list_storage(@@ -256,19 +258,8 @@ pub unsafe extern "C" fn visual_context_tree_for_each_effects_filter_image_framevisit: unsafe extern "C" fn(*mut c_void, u64),) {let tree = unsafe { tree_from_handle(tree) };- for node in &tree.effect_nodes {- let crate::visual_context::EffectNodeData::Effects(effects) = &node.data else {- continue;- };- let backdrop_filter_bytes = effects.backdrop_filter.as_ref().map(|backdrop| &backdrop.filter);- for filter_bytes in effects.filter.iter().chain(backdrop_filter_bytes) {- let Some(filter) = libgfx_rust::filter::Filter::deserialize(filter_bytes) else {- continue;- };- // SAFETY: The caller guarantees `visit` accepts `context`.- filter.for_each_image_frame_id(&mut |id| unsafe { visit(context, id) });- }- }+ // SAFETY: The caller guarantees `visit` accepts `context`.+ tree.for_each_effects_filter_image_frame_id(&mut |id| unsafe { visit(context, id) });}/// # Safetydiff --git a/Libraries/LibCompositing/Rust/src/host/replay.rs b/Libraries/LibCompositing/Rust/src/host/replay.rsindex 0285fe3b2aa..a9d5b25b717 100644--- a/Libraries/LibCompositing/Rust/src/host/replay.rs+++ b/Libraries/LibCompositing/Rust/src/host/replay.rs@@ -5,7 +5,7 @@*/use crate::display_list::commands::{ClipMode, DisplayListCommandType, ReplayClip, ReplayLayer, ReplayMask};-use crate::display_list::replay::{NestedDisplayList, NestedDisplayLists, ReplayPainter, ReplaySelection};+use crate::display_list::replay::{ReplayPainter, ReplaySelection};use libgfx_rust::path::Path;use libgfx_rust::path::ffi::PathGeometryData;use libgfx_rust::{@@ -142,17 +142,6 @@ pub enum NestedDisplayListReplay {Directly,}-/// A display list nested in another, as the painter's resources hold it: the storage of its tape, the tree it was-/// recorded against, and whether a raster of it can differ from replaying it.-#[derive(Clone, Copy)]-#[repr(C)]-pub struct FfiNestedDisplayList {- pub storage: *const c_void,- pub visual_context_tree: *const c_void,- pub root_group_color: Color,- pub requires_direct_replay: bool,-}-/// The raster primitives the replay drives a C++ painter through. The painter knows nothing of the visual context/// tree, of scroll offsets or of the frame: every value it gets is resolved for what it draws.#[derive(Clone, Copy)]@@ -194,52 +183,6 @@ pub struct FfiRasterPainter {pub begin_nested_display_list:unsafe extern "C" fn(*mut c_void, *const NestedDisplayListPlacement, bool) -> NestedDisplayListReplay,pub end_nested_display_list: unsafe extern "C" fn(*mut c_void),- /// Looks a nested display list up by its resource id, answering false where the resources hold none.- pub nested_display_list: unsafe extern "C" fn(*mut c_void, u64, *mut FfiNestedDisplayList) -> bool,-}--impl FfiRasterPainter {- /// The nested display lists that the resources of this painter hold.- pub fn nested_display_lists(&self) -> FfiNestedDisplayLists {- FfiNestedDisplayLists {- context: self.context,- nested_display_list: self.nested_display_list,- }- }-}--/// The nested display lists of a C++ painter's resources, looked up through the painter.-pub struct FfiNestedDisplayLists {- context: *mut c_void,- nested_display_list: unsafe extern "C" fn(*mut c_void, u64, *mut FfiNestedDisplayList) -> bool,-}--impl NestedDisplayLists for FfiNestedDisplayLists {- fn nested_display_list(&self, display_list_id: u64) -> Option<NestedDisplayList<'_>> {- let mut nested = FfiNestedDisplayList {- storage: std::ptr::null(),- visual_context_tree: std::ptr::null(),- root_group_color: Color::TRANSPARENT,- requires_direct_replay: true,- };- // SAFETY: The C++ painter answers synchronously.- if !unsafe { (self.nested_display_list)(self.context, display_list_id, &raw mut nested) } {- return None;- }- // SAFETY: The painter's resources keep the storage and the tree alive for as long as the replay runs.- let (storage, tree) = unsafe {- (- crate::display_list::storage::storage_from_handle(nested.storage),- crate::ffi::tree_from_handle(nested.visual_context_tree),- )- };- Some(NestedDisplayList {- storage,- tree,- root_group_color: nested.root_group_color,- requires_direct_replay: nested.requires_direct_replay,- })- }}impl ReplayPainter for FfiRasterPainter {diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex fcca8ad9f6b..98645e3591c 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -12,7 +12,10 @@use crate::css_pixels::{CssPixelPoint, CssPixels};use crate::display_list::commands::{CompositorContextId, UniqueNodeId};-use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};+use crate::display_list::storage::{DisplayListStorage, packed_size, receive_packed};+use crate::visual_context::VisualContextTree;+use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder, File};+use std::sync::Arc;pub type Web_CompositorContextId = CompositorContextId;pub type Web_UniqueNodeID = UniqueNodeId;@@ -117,6 +120,175 @@ impl Web_InputRoutingDecision {}}+/// `Core::AnonymousBuffer`: shared memory, which goes as its size and a descriptor of it, or as nothing for a buffer+/// that holds nothing.+#[derive(Debug)]+pub struct Core_AnonymousBuffer {+ pub shared_memory: Option<(u64, File)>,+}++impl Encode for Core_AnonymousBuffer {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.shared_memory.is_some())?;+ if let Some((size, file)) = &self.shared_memory {+ encoder.encode(size)?;+ encoder.encode(file)?;+ }+ Ok(())+ }+}++impl Decode for Core_AnonymousBuffer {+ const MIN_ENCODED_SIZE: usize = size_of::<bool>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ if !decoder.decode::<bool>()? {+ return Ok(Self { shared_memory: None });+ }+ let size = decoder.decode()?;+ let file = decoder.decode()?;+ Ok(Self {+ shared_memory: Some((size, file)),+ })+ }+}++/// `Compositing::AccumulatedVisualContextTree`, which goes as its serialized bytes.+#[derive(Clone)]+pub struct Compositing_AccumulatedVisualContextTree(pub Arc<VisualContextTree>);++impl Encode for Compositing_AccumulatedVisualContextTree {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.0.to_bytes())+ }+}++impl Decode for Compositing_AccumulatedVisualContextTree {+ const MIN_ENCODED_SIZE: usize = <Vec<u8> as Decode>::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ let bytes: Vec<u8> = decoder.decode()?;+ Ok(Self(Arc::new(VisualContextTree::from_bytes(&bytes)?)))+ }+}++/// A display list that another one nests, with the tree it was recorded against.+#[derive(Clone)]+pub struct NestedDisplayListResource {+ pub properties: Compositing_DisplayList_Properties,+ pub storage: Arc<DisplayListStorage>,+ pub tree: Arc<VisualContextTree>,+}++impl std::fmt::Debug for NestedDisplayListResource {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("NestedDisplayListResource")+ .field("properties", &self.properties)+ .finish_non_exhaustive()+ }+}++/// `Compositing::DisplayListResourceTransaction` as it reaches the compositor's logic, which holds no fonts and no+/// image frames: those go ahead of it, in messages that the C++ of the compositor takes.+#[derive(Clone, Debug, Default)]+pub struct Compositing_DisplayListResourceTransaction {+ // The resource ID of each video sink, and the handle of the sink.+ pub video_sinks: Vec<(u64, u64)>,+ pub display_lists: Vec<NestedDisplayListResource>,+ pub font_ids_to_remove: Vec<u64>,+ pub image_frame_ids_to_remove: Vec<u64>,+ pub video_sink_ids_to_remove: Vec<u64>,+ pub display_list_ids_to_remove: Vec<u64>,+}++impl Compositing_DisplayListResourceTransaction {+ pub fn removes_anything(&self) -> bool {+ !self.font_ids_to_remove.is_empty()+ || !self.image_frame_ids_to_remove.is_empty()+ || !self.video_sink_ids_to_remove.is_empty()+ || !self.display_list_ids_to_remove.is_empty()+ }+}++impl Encode for Compositing_DisplayListResourceTransaction {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ // No fonts, and no image frames.+ encoder.encode_size(0)?;+ encoder.encode_size(0)?;+ encoder.encode_size(self.video_sinks.len())?;+ for (id, handle) in &self.video_sinks {+ encoder.encode(id)?;+ encoder.encode(handle)?;+ }+ encoder.encode_size(self.display_lists.len())?;+ for display_list in &self.display_lists {+ encoder.encode(&display_list.properties)?;+ let storage = &display_list.storage;+ encoder.encode_size(storage.bytes().len())?;+ encoder.encode_size(storage.command_runs().len())?;+ encoder.append_bytes(&storage.packed());+ encoder.encode(&display_list.tree.to_bytes())?;+ }+ encoder.encode(&self.font_ids_to_remove)?;+ encoder.encode(&self.image_frame_ids_to_remove)?;+ encoder.encode(&self.video_sink_ids_to_remove)?;+ encoder.encode(&self.display_list_ids_to_remove)+ }+}++impl Decode for Compositing_DisplayListResourceTransaction {+ const MIN_ENCODED_SIZE: usize = 0;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ if decoder.decode_size()? != 0 || decoder.decode_size()? != 0 {+ return Err(DecodeError::InvalidValue(+ "a display list's fonts and image frames go ahead of it",+ ));+ }+ let video_sink_count = decoder.decode_size()?;+ let mut video_sinks = Vec::new();+ for _ in 0..video_sink_count {+ video_sinks.push((decoder.decode()?, decoder.decode()?));+ }+ let display_list_count = decoder.decode_size()?;+ let mut display_lists = Vec::new();+ for _ in 0..display_list_count {+ let properties: Compositing_DisplayList_Properties = decoder.decode()?;+ let tape_size = decoder.decode_size()?;+ let run_count = decoder.decode_size()?;+ let packed_size =+ packed_size(tape_size, run_count).ok_or(DecodeError::InvalidValue("Display list sizes overflow"))?;+ let packed = decoder.read_bytes(packed_size)?;+ let storage = receive_packed(packed, tape_size, run_count).map_err(DecodeError::InvalidValue)?;+ let tree = Arc::new(VisualContextTree::from_bytes(&decoder.decode::<Vec<u8>>()?)?);+ if properties.compatible_visual_context_tree_structural_epoch != tree.structural_epoch {+ return Err(DecodeError::InvalidValue(+ "Display list resource does not match its visual context tree",+ ));+ }+ if !tree.display_list_references_only_live_nodes(storage.command_runs()) {+ return Err(DecodeError::InvalidValue(+ "Display list resource references nodes its visual context tree does not hold",+ ));+ }+ display_lists.push(NestedDisplayListResource {+ properties,+ storage,+ tree,+ });+ }+ Ok(Self {+ video_sinks,+ display_lists,+ font_ids_to_remove: decoder.decode()?,+ image_frame_ids_to_remove: decoder.decode()?,+ video_sink_ids_to_remove: decoder.decode()?,+ display_list_ids_to_remove: 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/LibCompositing/Rust/src/visual_context/queries.rs b/Libraries/LibCompositing/Rust/src/visual_context/queries.rsindex c18304cadfe..2d810697462 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs@@ -574,6 +574,22 @@ impl VisualContextTree {|| self.clip_is_none_or_live(self.effect_nodes[context.effect.0 as usize].local_clip))}+ /// Visits the id of every image frame that a filter or backdrop filter of an effect node draws.+ pub fn for_each_effects_filter_image_frame_id(&self, visit: &mut dyn FnMut(u64)) {+ for node in &self.effect_nodes {+ let EffectNodeData::Effects(effects) = &node.data else {+ continue;+ };+ let backdrop_filter_bytes = effects.backdrop_filter.as_ref().map(|backdrop| &backdrop.filter);+ for filter_bytes in effects.filter.iter().chain(backdrop_filter_bytes) {+ let Some(filter) = libgfx_rust::filter::Filter::deserialize(filter_bytes) else {+ continue;+ };+ filter.for_each_image_frame_id(&mut |id| visit(id));+ }+ }+ }+pub fn display_list_references_only_live_nodes(&self,command_runs: &[crate::display_list::commands::DisplayListCommandRun],diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex ed2425def82..0b3778ae9e8 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -199,7 +199,7 @@ bool CompositorConnectionFrameSink::post_display_list_update(Web::CompositorCont}auto copy_time = timer.elapsed_time();- auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateDisplayList::static_encode(context_id, shared_tape_buffer.value(), display_list.tape_size(), display_list.run_count(), display_list.properties(), IPC::Encoded { display_list.async_scrolling_metadata() }, update.visual_context_tree, update.resource_transaction, update.encoded_scroll_state));+ auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateDisplayList::static_encode(context_id, shared_tape_buffer.value(), display_list.tape_size(), display_list.run_count(), display_list.properties(), display_list.async_scrolling_metadata(), update.visual_context_tree, update.resource_transaction, update.encoded_scroll_state));if (!post(encoded_message))return false;if (display_list_timing_enabled())@@ -221,7 +221,7 @@ bool CompositorConnectionFrameSink::submit(CompositorFrame&& frame)if (auto& update = frame.visual_context_tree_update; update.has_value()) {if (!post_resource_additions_in_batches(context_id, update->resource_transaction))return false;- auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateVisualContextTree::static_encode(context_id, update->visual_context_tree, update->resource_transaction, update->encoded_scroll_state, IPC::Encoded { update->keyboard_scroll_state }));+ auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateVisualContextTree::static_encode(context_id, update->visual_context_tree, update->resource_transaction, update->encoded_scroll_state, update->keyboard_scroll_state));if (!post(encoded_message))return false;}@@ -510,14 +510,21 @@ bool CompositorConnection::rasterize_display_list(Compositing::DisplayList constdbgln("WebContent: Could not place a {} byte display list to rasterize in shared memory: {}", display_list.tape_size(), shared_tape_buffer.error());return false;}+ // The display lists it nests go with the list, and the rest of its resources are staged ahead of it.+ auto token = m_next_rasterization_token++;+ Compositing::DisplayListResourceTransaction staged_resources;+ staged_resources.fonts = move(resource_transaction.fonts);+ staged_resources.image_frames = move(resource_transaction.image_frames);+ staged_resources.video_sinks = move(resource_transaction.video_sinks);+ async_stage_rasterization(token, staged_resources, Gfx::ShareableBitmap { move(target), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap });auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::RasterizeDisplayList>(+ token,shared_tape_buffer.release_value(),display_list.tape_size(),display_list.run_count(),display_list.properties(),visual_context_tree,- move(resource_transaction),- Gfx::ShareableBitmap { move(target), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap });+ move(resource_transaction));return response && response->success();}diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex 9743ea10472..212f04d8682 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -6,6 +6,7 @@#pragma once+#include <AK/Atomic.h>#include <AK/Function.h>#include <AK/HashMap.h>#include <AK/NonnullRefPtr.h>@@ -150,6 +151,7 @@ private:// What the compositor process scrolled since the last rendering update adopted it, per context.HashMap<Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates> m_pending_async_scroll_updates;u64 m_next_screenshot_request_id { 1 };+ Atomic<u64> m_next_rasterization_token { 1 };bool m_has_lost_compositor { false };// The media server whose presentation channel the Compositor holds; a replacement server needs a new channel.Optional<u64> m_video_presentation_channel_media_client_generation;diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex a99e7cb7024..74b3195919a 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -18,7 +18,6 @@ set(SOURCESOpenGLContext.cppPaintingSurface.cppPresentableSurface.cpp- RasterizeDisplayList.cppRenderClockConnection.cppSkiaBackendContext.cppSkiaUtils.cppdiff --git a/Services/Compositor/CanvasHost.cpp b/Services/Compositor/CanvasHost.cppindex 368f8eb3b15..7ada8d222e8 100644--- a/Services/Compositor/CanvasHost.cpp+++ b/Services/Compositor/CanvasHost.cpp@@ -15,7 +15,6 @@#include <Compositor/VideoFrameSkia.h>#include <LibCompositing/CanvasSize.h>#include <LibCompositing/DisplayList/Canvas2DCommandStream.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibGfx/Bitmap.h>#include <LibGfx/ColorSpace.h>#include <LibMediaCodecs/VideoFrame.h>diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cppindex ea522c0f292..733ee1377b1 100644--- a/Services/Compositor/CompositorCore.cpp+++ b/Services/Compositor/CompositorCore.cpp@@ -286,17 +286,6 @@ Optional<CompositorCore::PresentedFrame> CompositorCore::presented_frame_for_snareturn PresentedFrame { adopt_ref(*static_cast<Gfx::PaintingSurface*>(surface)), frame_size };}-bool CompositorCore::install_display_list_update(Web::CompositorContextId context_id, Compositing::DisplayList const& display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state)-{- auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());- return RustFFI::compositor_core_install_display_list_update(m_core, context_id.value(), &display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state, now().nanoseconds());-}--CompositorCore::VisualContextTreeUpdateResult CompositorCore::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const& keyboard_scroll_state)-{- return RustFFI::compositor_core_update_visual_context_tree(m_core, context_id.value(), visual_context_tree.rust_handle(), encoded_scroll_state, keyboard_scroll_state.bytes(), now().nanoseconds());-}-void CompositorCore::timer_fired(Web::CompositorContextId context_id, ContextTimer timer){RustFFI::compositor_core_timer_fired(m_core, context_id.value(), timer, now().nanoseconds());diff --git a/Services/Compositor/CompositorCore.h b/Services/Compositor/CompositorCore.hindex 8c20ce31ac6..897b71fb074 100644--- a/Services/Compositor/CompositorCore.h+++ b/Services/Compositor/CompositorCore.h@@ -11,11 +11,8 @@#include <AK/Optional.h>#include <Compositor/CompositorCoreHost.h>#include <Compositor/PaintingSurface.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/Types.h>#include <LibCompositing/UIOverlays.h>-#include <LibIPC/Encoded.h>#include <LibIPC/Message.h>#include <LibIPC/RawMessage.h>@@ -33,7 +30,6 @@ public:~CompositorCore();using ContextOwnerCheckResult = RustFFI::ContextOwnerCheckResult;- using VisualContextTreeUpdateResult = RustFFI::VisualContextTreeUpdateResult;using PresentationCapabilities = RustFFI::FfiPresentationCapabilities;void create_context(Web::CompositorContextId, Optional<u64> page_id, WebContentClientId);@@ -85,12 +81,6 @@ public:// The surface that holds the frame on screen as a whole, and the size of the frame in it.Optional<PresentedFrame> presented_frame_for_snapshot(Web::CompositorContextId);- // Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode.- bool install_display_list_update(Web::CompositorContextId, Compositing::DisplayList const&, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state);- // Changes nothing for a scroll state or keyboard scroll state that do not decode. Of a tree that does not fit the- // installed display list, only the scroll state is taken.- VisualContextTreeUpdateResult update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const&);-void timer_fired(Web::CompositorContextId, ContextTimer);// The messages of CompositorWebContentServer and CompositorPresentationServer that are marked [RustReceiver].diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 0a7d980b932..db982cec6e2 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -11,6 +11,8 @@#include <Compositor/CanvasHost.h>#include <Compositor/CompositorState.h>#include <Compositor/SkiaUtils.h>+#include <LibCompositing/DisplayList/DisplayList.h>+#include <LibCore/AnonymousBuffer.h>#include <LibCore/EventLoop.h>#include <LibCore/StatsLog.h>#include <LibCore/Timer.h>@@ -354,6 +356,7 @@ void CompositorState::destroy_contexts_for_web_content_client(CompositorStateWebm_video_sink_states.remove(&client);m_animated_images.remove(&client);+ m_staged_rasterizations.remove(client.web_content_client_id());m_placeholder_canvases.remove_all_matching([&](auto canvas_id, auto const& placeholder) {if (placeholder.owner != &client)@@ -480,30 +483,6 @@ void CompositorState::stop_presenting_to_client(Web::CompositorContextId contextm_core.stop_presenting_to_client(context_id);}-bool CompositorState::update_display_list(Web::CompositorContextId context_id, NonnullRefPtr<Compositing::DisplayList> display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction, ReadonlyBytes encoded_scroll_state)-{- auto& context = presented_context(context_id);-- if (display_list->compatible_visual_context_tree_structural_epoch() != visual_context_tree.structural_epoch()) {- dbgln("Compositor: Dropping inconsistent display list update (display list epoch {}, tree epoch {})",- display_list->compatible_visual_context_tree_structural_epoch(),- visual_context_tree.structural_epoch());- return true;- }- if (auto validation = Compositing::validate_display_list_references_live_visual_context_nodes(*display_list, visual_context_tree); validation.is_error()) {- dbgln("Compositor: Dropping display list update: {}", validation.error());- return true;- }-- if (!m_core.install_display_list_update(context_id, *display_list, async_scrolling_metadata, visual_context_tree, encoded_scroll_state))- return false;- context.raster_targets.apply_resource_transaction(move(resource_transaction));- resolve_video_sinks(context);- show_animated_image_frames_in(context);- update_unpainted_video_update_scheduling();- return true;-}-void CompositorState::update_display_list_resources(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction&& resource_transaction){auto& context = presented_context(context_id);@@ -511,23 +490,6 @@ void CompositorState::update_display_list_resources(Web::CompositorContextId conshow_animated_image_frames_in(context);}-bool CompositorState::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const& keyboard_scroll_state)-{- auto& context = presented_context(context_id);-- switch (m_core.update_visual_context_tree(context_id, visual_context_tree, encoded_scroll_state, keyboard_scroll_state)) {- case CompositorCore::VisualContextTreeUpdateResult::TreeReplaced:- context.raster_targets.apply_resource_transaction(move(resource_transaction));- break;- case CompositorCore::VisualContextTreeUpdateResult::TreeDropped:- break;- case CompositorCore::VisualContextTreeUpdateResult::InvalidScrollState:- return false;- }- show_animated_image_frames_in(context);- return true;-}-CompositorState::VideoSinkState* CompositorState::video_sink_state(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle){auto client_sinks = m_video_sink_states.get(&client);@@ -1233,6 +1195,112 @@ bool CompositorState::retire_idle_surplus_stores(Web::CompositorContextId contexreturn backing_stores.has_surplus_backing_stores();}+void CompositorState::apply_resource_changes(Web::CompositorContextId context_id, RustFFI::FfiResourceChanges const& changes)+{+ auto& context = presented_context(context_id);+ Compositing::DisplayListResourceTransaction transaction;+ for (auto const& video_sink : changes.video_sinks)+ transaction.video_sinks.append({ .id = Compositing::VideoSinkResourceId { video_sink.id }, .sink_handle = Media::VideoSinkHandle { video_sink.sink_handle } });+ for (auto id : changes.font_ids_to_remove)+ transaction.font_ids_to_remove.append(Compositing::FontResourceId { id });+ for (auto id : changes.image_frame_ids_to_remove)+ transaction.image_frame_ids_to_remove.append(Compositing::ImageFrameResourceId { id });+ for (auto id : changes.video_sink_ids_to_remove)+ transaction.video_sink_ids_to_remove.append(Compositing::VideoSinkResourceId { id });+ auto& raster_targets = context.raster_targets;+ raster_targets.apply_resource_transaction(move(transaction));+ // The display lists that the context's lists nest are held by the logic in Rust, and only their rasters here.+ Compositing::DisplayListResourceSet removed_display_lists;+ for (auto id : changes.display_list_ids_to_remove)+ removed_display_lists.display_lists.set(Compositing::DisplayListResourceId { id });+ raster_targets.raster_cache().evict(removed_display_lists);+ resolve_video_sinks(context);+ show_animated_image_frames_in(context);+ update_unpainted_video_update_scheduling();+}++bool CompositorState::stage_rasterization(CompositorStateWebContentClient& client, u64 token, Compositing::DisplayListResourceTransaction&& resources, Gfx::ShareableBitmap target_bitmap)+{+ if (!resources.display_lists.is_empty() || !resources.font_ids_to_remove.is_empty() || !resources.image_frame_ids_to_remove.is_empty() || !resources.video_sink_ids_to_remove.is_empty() || !resources.display_list_ids_to_remove.is_empty())+ return false;+ // WebContent waits for each rasterization it stages, so it has only the one in flight per thread that rasterizes.+ static constexpr size_t maximum_staged_rasterizations_per_client = 16;+ auto& staged = m_staged_rasterizations.ensure(client.web_content_client_id());+ if (staged.contains(token) || staged.size() >= maximum_staged_rasterizations_per_client)+ return false;+ auto rasterization = make<StagedRasterization>();+ rasterization->resource_storage.apply_transaction(move(resources));+ rasterization->target_bitmap = move(target_bitmap);+ staged.set(token, move(rasterization));+ return true;+}++CompositorState::StagedRasterization* CompositorState::staged_rasterization(WebContentClientId client, u64 token)+{+ auto staged = m_staged_rasterizations.find(client);+ if (staged == m_staged_rasterizations.end())+ return nullptr;+ auto rasterization = staged->value.find(token);+ if (rasterization == staged->value.end())+ return nullptr;+ return rasterization->value.ptr();+}++bool CompositorState::staged_rasterization_has_resources(WebContentClientId client, u64 token, ReadonlySpan<u64> font_ids, ReadonlySpan<u64> image_frame_ids)+{+ auto* rasterization = staged_rasterization(client, token);+ if (!rasterization)+ return false;+ auto const& resource_storage = rasterization->resource_storage;+ for (auto id : font_ids) {+ if (!resource_storage.has_font(Compositing::FontResourceId { id }))+ return false;+ }+ for (auto id : image_frame_ids) {+ if (!resource_storage.has_image_frame(Compositing::ImageFrameResourceId { id }))+ return false;+ }+ return true;+}++// The largest frame WebContent rasterizes for an SVG image.+static constexpr int max_rasterization_target_dimension = 16384;++bool CompositorState::begin_staged_rasterization(WebContentClientId client, u64 token, Compositing::RustFFI::FfiRasterPainter& painter)+{+ auto* rasterization = staged_rasterization(client, token);+ if (!rasterization || !rasterization->target_bitmap.is_valid() || !rasterization->target_bitmap.bitmap())+ return false;+ auto& target = *rasterization->target_bitmap.bitmap();+ if (target.format() != Gfx::BitmapFormat::BGRA8888 || target.alpha_type() != Gfx::AlphaType::Premultiplied) {+ dbgln("Compositor: Not rasterizing display list from WebContent: Target bitmap is not BGRA8888 with premultiplied alpha");+ return false;+ }+ if (target.width() > max_rasterization_target_dimension || target.height() > max_rasterization_target_dimension) {+ dbgln("Compositor: Not rasterizing display list from WebContent: Target bitmap is too large");+ return false;+ }+ __builtin_memset(target.scanline_u8(0), 0, target.size_in_bytes());+ rasterization->target_surface = Gfx::PaintingSurface::wrap_bitmap(target);+ rasterization->player = make<DisplayListPlayerSkia>(RefPtr<Gfx::SkiaBackendContext> {});+ painter = rasterization->player->begin_painting(*rasterization->target_surface, rasterization->resource_storage, rasterization->raster_cache, nullptr);+ return true;+}++void CompositorState::finish_staged_rasterization(WebContentClientId client, u64 token)+{+ auto staged = m_staged_rasterizations.find(client);+ if (staged == m_staged_rasterizations.end())+ return;+ auto rasterization = staged->value.take(token);+ if (!rasterization.has_value())+ return;+ if (auto& player = (*rasterization)->player) {+ player->end_painting();+ DisplayListPlayerSkia::flush(*(*rasterization)->target_surface);+ }+}+static bool video_frame_holds_high_dynamic_range(Media::VideoFrame const& frame){auto transfer_characteristics = frame.cicp().transfer_characteristics();@@ -1531,6 +1599,21 @@ VSyncScheduler& CompositorState::vsync_scheduler_for_display(Optional<u64> displ});}+namespace {++struct SharedMemoryMapping {+ AK_ALLOC_WITH_KMALLOC;++ explicit SharedMemoryMapping(Core::AnonymousBuffer buffer)+ : buffer(move(buffer))+ {+ }++ Core::AnonymousBuffer buffer;+};++}+static CompositorState& state_of(void* host){return *static_cast<CompositorState*>(host);@@ -1668,6 +1751,26 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state)receive(receiver, contexts_with_new_video_frames.span()); },.context_video_sinks_require_updates = [](void* host, u64 context_id) { return state_of(host).context_video_sinks_require_updates(Context { context_id }); },.set_maximum_display_refresh_rate = [](void* host, double refresh_rate) { state_of(host).set_maximum_display_refresh_rate(refresh_rate); },+ .map_shared_memory = [](void*, i32 descriptor, u64 size, u8 const** data, size_t* data_size) -> void* {+ auto buffer = Core::AnonymousBuffer::create_from_anon_fd(descriptor, size);+ if (buffer.is_error()) {+ dbgln("Compositor: Could not map shared memory from WebContent: {}", buffer.error());+ return nullptr;+ }+ if (auto validation = buffer.value().validate_backing_size(); validation.is_error()) {+ dbgln("Compositor: Could not map shared memory from WebContent: {}", validation.error());+ return nullptr;+ }+ auto mapping = make<SharedMemoryMapping>(buffer.release_value());+ *data = mapping->buffer.bytes().data();+ *data_size = mapping->buffer.bytes().size();+ return mapping.leak_ptr();+ },+ .unmap_shared_memory = [](void* mapping) { delete static_cast<SharedMemoryMapping*>(mapping); },+ .apply_resource_changes = [](void* host, u64 context_id, RustFFI::FfiResourceChanges const* changes) { state_of(host).apply_resource_changes(Context { context_id }, *changes); },+ .staged_rasterization_has_resources = [](void* host, u64 client, u64 token, ReadonlySpan<u64> font_ids, ReadonlySpan<u64> image_frame_ids) { return state_of(host).staged_rasterization_has_resources(WebContentClientId { client }, token, font_ids, image_frame_ids); },+ .begin_staged_rasterization = [](void* host, u64 client, u64 token, Compositing::RustFFI::FfiRasterPainter* painter) { return state_of(host).begin_staged_rasterization(WebContentClientId { client }, token, *painter); },+ .finish_staged_rasterization = [](void* host, u64 client, u64 token) { state_of(host).finish_staged_rasterization(WebContentClientId { client }, token); },};}diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 032cbf59db8..becc748d4ed 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -21,8 +21,6 @@#include <Compositor/SkiaBackendContext.h>#include <Compositor/VSyncScheduler.h>#include <Compositor/WindowServer.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/Forward.h>#include <LibCompositing/Types.h>@@ -115,11 +113,11 @@ public:bool context_can_be_nested_in(Web::CompositorContextId, Web::CompositorContextId parent_context_id) const;void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId> parent_context_id);void stop_presenting_to_client(Web::CompositorContextId);- // Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode.- bool update_display_list(Web::CompositorContextId, NonnullRefPtr<Compositing::DisplayList>, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction&&, ReadonlyBytes encoded_scroll_state);void update_display_list_resources(Web::CompositorContextId, Compositing::DisplayListResourceTransaction&&);- // Answers false, changing nothing, for a scroll state or keyboard scroll state that do not decode.- bool update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction&&, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const&);+ // The fonts, image frames and video sinks that the display list of the next rasterization under the token draws, and+ // the bitmap it is rasterized into. Answers false for a token in use, for more rasterizations than a client can have+ // in flight, or for resources that a rasterization does not stage.+ bool stage_rasterization(CompositorStateWebContentClient&, u64 token, Compositing::DisplayListResourceTransaction&&, Gfx::ShareableBitmap target_bitmap);void add_video_sink(CompositorStateWebContentClient&, Media::VideoSinkHandle);// For a presentation channel that arrives after the sinks did, or that replaces the one their edges were on.void create_video_edges(CompositorStateWebContentClient&);@@ -231,6 +229,12 @@ private:RustFFI::StoreResizeOutcome resize_stores(Web::CompositorContextId, RustFFI::FfiStoreResize const&);bool add_store_if_window_server_reads_every_released_store(Web::CompositorContextId, Optional<PresentationId>);bool retire_idle_surplus_stores(Web::CompositorContextId, Optional<PresentationId>);+ void apply_resource_changes(Web::CompositorContextId, RustFFI::FfiResourceChanges const&);+ struct StagedRasterization;+ StagedRasterization* staged_rasterization(WebContentClientId, u64 token);+ bool staged_rasterization_has_resources(WebContentClientId, u64 token, ReadonlySpan<u64> font_ids, ReadonlySpan<u64> image_frame_ids);+ bool begin_staged_rasterization(WebContentClientId, u64 token, Compositing::RustFFI::FfiRasterPainter&);+ void finish_staged_rasterization(WebContentClientId, u64 token);void report_live_content(Web::CompositorContextId, ReadonlySpan<u64> canvas_ids, void* receiver, void (*receive)(void*, RustFFI::FfiLiveContent const*));Optional<RemoteLayer::Content> remote_layer_content(PresentedContext&, RustFFI::MediaKind, u64 media_id);bool remote_layer_can_show(Web::CompositorContextId, RustFFI::MediaKind, u64 media_id, RustFFI::FfiSublayerPlacement const&, double device_pixel_ratio);@@ -261,6 +265,24 @@ private:HashMap<Web::CompositorContextId, NonnullOwnPtr<PresentedContext>> m_presented_contexts;+ struct StagedRasterization {+ AK_MAKE_NONCOPYABLE(StagedRasterization);+ AK_MAKE_NONMOVABLE(StagedRasterization);++ public:+ AK_ALLOC_WITH_KMALLOC;++ StagedRasterization() = default;++ Compositing::DisplayListResourceStorage resource_storage;+ DisplayListRasterCache raster_cache;+ Gfx::ShareableBitmap target_bitmap;+ RefPtr<Gfx::PaintingSurface> target_surface;+ // Rasters on the CPU, so the pixels match a raster of the same list in any other process.+ OwnPtr<DisplayListPlayerSkia> player;+ };+ HashMap<WebContentClientId, HashMap<u64, NonnullOwnPtr<StagedRasterization>>> m_staged_rasterizations;+// A screenshot whose context has descendants in other processes, which waits for those processes to paint them.struct ScreenshotPreparation {WebContentClientId requester;diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex 787557bbfc6..8625b7df54b 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -16,7 +16,6 @@#include <LibGfx/Rect.h>#include <LibGfx/ShareableBitmap.h>#include <LibGfx/Size.h>-#include <LibIPC/Encoded.h>#include <LibIPC/TransportHandle.h>#include <LibMedia/VideoSinkHandle.h>#include <LibWebCommon/Page/InputEvent.h>@@ -42,11 +41,12 @@ endpoint CompositorWebContentServerstop_presenting_to_client(Web::CompositorContextId context_id) =|destroy_context(Web::CompositorContextId context_id) =|- // The async scrolling metadata, the scroll state and the keyboard scroll state that comes with a visual context tree- // go encoded: the scroll logic, which is Rust, decodes them, and Rust encoded the scroll state.- update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state) =|+ // The fonts and image frames that a display list or a visual context tree draws go ahead of it, in+ // update_display_list_resources, and the resource transaction that comes with it holds none. Rust encoded the scroll+ // state.+ [RustReceiver] update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, Optional<Compositing::DisplayList::AsyncScrollingMetadata> async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state) =|update_display_list_resources(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction resource_transaction) =|- update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> keyboard_scroll_state) =|+ [RustReceiver] update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state) =|[RustReceiver] update_scroll_state(Web::CompositorContextId context_id, ByteBuffer scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state) =|// Hands WebContent a range of canvas IDs it may name its own 2D contexts with, so creating one needs no round trip.@@ -65,7 +65,10 @@ endpoint CompositorWebContentServercommit_placeholder_canvas(Compositing::CanvasId canvas_id, u64 secret, Optional<Compositing::CanvasId> source_canvas_id, Gfx::IntSize size, bool origin_clean) =|get_placeholder_canvas_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect) => (Gfx::ShareableBitmap pixels, bool origin_clean)- rasterize_display_list(Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, Gfx::ShareableBitmap target_bitmap) => (bool success)+ // A display list is rasterized into the target bitmap with the fonts, image frames and video sinks staged for it under+ // a token that the next rasterize_display_list names, and with the display lists it nests, which come with it.+ stage_rasterization(u64 token, Compositing::DisplayListResourceTransaction resources, Gfx::ShareableBitmap target_bitmap) =|+ [RustReceiver] rasterize_display_list(u64 token, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction nested_display_lists) => (bool success)create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias) => (bool success, Compositing::CanvasId canvas_id, Vector<String> supported_extensions)webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer) =|diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex fbbaf41fa65..c6a2ea3f7c4 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -7,11 +7,8 @@#include <AK/Debug.h>#include <AK/Math.h>#include <Compositor/ConnectionFromWebContent.h>-#include <Compositor/RasterizeDisplayList.h>#include <LibCompositing/DisplayList/Canvas2DTape.h>#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>-#include <LibCore/ElapsedTimer.h>-#include <LibCore/Environment.h>#include <LibGfx/ColorSpace.h>#include <LibWebCommon/Page/InputEvent.h>@@ -276,35 +273,6 @@ void ConnectionFromWebContent::destroy_context(Web::CompositorContextId context_m_compositor_state->destroy_context(context_id);}-static bool display_list_timing_enabled()-{- static bool enabled = [] {- auto value = Core::Environment::get("LADYBIRD_DISPLAY_LIST_TIMING"sv);- return value.has_value() && !value->is_empty() && *value != "0"sv;- }();- return enabled;-}--void ConnectionFromWebContent::update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state)-{- auto timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);- auto display_list = Compositing::DisplayList::create_from_shared_buffer(move(display_list_properties), move(display_list_buffer), tape_size, run_count);- if (display_list.is_error()) {- dbgln("Compositor: Rejecting display list from WebContent: {}", display_list.error());- did_misbehave("WebContent published a display list its shared buffer does not hold");- return;- }- auto adopt_time = timer.elapsed_time();- if (!context_is_owned_by_this_connection(context_id))- return;- if (!m_compositor_state->update_display_list(context_id, display_list.release_value(), async_scrolling_metadata, move(visual_context_tree), move(resource_transaction), scroll_state.bytes())) {- did_misbehave("WebContent published a display list with scrolling state the compositor cannot use");- return;- }- if (display_list_timing_enabled())- dbgln("DISPLAY_LIST_RECEIVE bytes={} adopt={} µs install={} µs", tape_size, adopt_time.to_microseconds(), (timer.elapsed_time() - adopt_time).to_microseconds());-}-void ConnectionFromWebContent::update_display_list_resources(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction resource_transaction){if (!context_is_owned_by_this_connection(context_id))@@ -312,14 +280,6 @@ void ConnectionFromWebContent::update_display_list_resources(Web::CompositorContm_compositor_state->update_display_list_resources(context_id, move(resource_transaction));}-void ConnectionFromWebContent::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> keyboard_scroll_state)-{- if (!context_is_owned_by_this_connection(context_id))- return;- if (!m_compositor_state->update_visual_context_tree(context_id, move(visual_context_tree), move(resource_transaction), scroll_state.bytes(), keyboard_scroll_state))- did_misbehave("WebContent published a visual context tree with a scroll state the compositor cannot use");-}-Messages::CompositorWebContentServer::ReserveCanvasIdsResponse ConnectionFromWebContent::reserve_canvas_ids(){static constexpr u64 reserved_canvas_id_count = 1 << 20;@@ -392,21 +352,10 @@ Messages::CompositorWebContentServer::GetCanvasPixelsResponse ConnectionFromWebCreturn m_canvas_host.read_back_pixels(canvas_id, rect, alpha_type, color_space);}-Messages::CompositorWebContentServer::RasterizeDisplayListResponse ConnectionFromWebContent::rasterize_display_list(Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, Gfx::ShareableBitmap target_bitmap)+void ConnectionFromWebContent::stage_rasterization(u64 token, Compositing::DisplayListResourceTransaction resources, Gfx::ShareableBitmap target_bitmap){- auto display_list = Compositing::DisplayList::create_from_shared_buffer(move(display_list_properties), move(display_list_buffer), tape_size, run_count);- if (display_list.is_error()) {- dbgln("Compositor: Rejecting display list to rasterize from WebContent: {}", display_list.error());- did_misbehave("WebContent asked to rasterize a display list its shared buffer does not hold");- return false;- }- if (!target_bitmap.is_valid())- return false;- if (auto result = Compositor::rasterize_display_list(*display_list.value(), visual_context_tree, move(resource_transaction), *target_bitmap.bitmap()); result.is_error()) {- dbgln("Compositor: Not rasterizing display list from WebContent: {}", result.error());- return false;- }- return true;+ if (!m_compositor_state->stage_rasterization(*this, token, move(resources), move(target_bitmap)))+ did_misbehave("WebContent staged a rasterization under a token in use, or with resources a rasterization does not stage");}Messages::CompositorWebContentServer::AllocatePlaceholderCanvasResponse ConnectionFromWebContent::allocate_placeholder_canvas()diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex f253b48d040..01c9cbbb0b9 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -57,8 +57,6 @@ private:virtual void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>) override;virtual void stop_presenting_to_client(Web::CompositorContextId) override;virtual void destroy_context(Web::CompositorContextId) override;- virtual void update_display_list(Web::CompositorContextId, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>>, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction, ByteBuffer scroll_state) override;- virtual void update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction, ByteBuffer scroll_state, IPC::Encoded<Compositing::KeyboardScrollState>) override;virtual void update_display_list_resources(Web::CompositorContextId, Compositing::DisplayListResourceTransaction) override;virtual Messages::CompositorWebContentServer::ReserveCanvasIdsResponse reserve_canvas_ids() override;virtual void create_canvas_2d_context(Compositing::CanvasId, Gfx::IntSize, bool alpha, bool will_read_frequently, Gfx::ColorSpace) override;@@ -69,7 +67,7 @@ private:virtual void release_placeholder_canvas(Compositing::CanvasId) override;virtual void commit_placeholder_canvas(Compositing::CanvasId, u64 secret, Optional<Compositing::CanvasId> source_canvas_id, Gfx::IntSize, bool origin_clean) override;virtual Messages::CompositorWebContentServer::GetPlaceholderCanvasPixelsResponse get_placeholder_canvas_pixels(Compositing::CanvasId, Gfx::IntRect) override;- virtual Messages::CompositorWebContentServer::RasterizeDisplayListResponse rasterize_display_list(Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction, Gfx::ShareableBitmap target_bitmap) override;+ virtual void stage_rasterization(u64 token, Compositing::DisplayListResourceTransaction, Gfx::ShareableBitmap target_bitmap) override;virtual Messages::CompositorWebContentServer::CreateWebglContextResponse create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias) override;virtual void webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer) override;diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex 7ec1ce9a79a..46e03e6db78 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -124,7 +124,6 @@ struct DisplayListPlayerSkia::PainterCallbacks {.end_tile_raster = [](void* context) { PainterCallbacks::player(context).end_tile_raster(); },.begin_nested_display_list = [](void* context, RustFFI::NestedDisplayListPlacement const* placement, bool requires_direct_replay) { return PainterCallbacks::player(context).begin_nested_display_list(*placement, requires_direct_replay); },.end_nested_display_list = [](void* context) { PainterCallbacks::player(context).end_nested_display_list(); },- .nested_display_list = [](void* context, u64 display_list_id, RustFFI::FfiNestedDisplayList* nested_display_list) -> bool { return PainterCallbacks::player(context).nested_display_list(display_list_id, *nested_display_list); },};}};@@ -168,19 +167,6 @@ void DisplayListPlayerSkia::play_command_bytes(DisplayListCommandType command_ty}}-bool DisplayListPlayerSkia::nested_display_list(u64 display_list_id, RustFFI::FfiNestedDisplayList& nested_display_list) const-{- DisplayListResourceId id { display_list_id };- if (!resource_storage().has_display_list(id))- return false;- auto const& resource = resource_storage().display_list_resource(id);- nested_display_list.storage = resource.display_list->rust_handle();- nested_display_list.visual_context_tree = resource.visual_context_tree.rust_handle();- nested_display_list.root_group_color = resource.display_list->root_group_color();- nested_display_list.requires_direct_replay = resource_storage().display_list_requires_direct_replay(id);- return true;-}-static SkRRect to_skia_rrect(auto const& rect, Gfx::CornerRadii const& corner_radii){SkRRect rrect;diff --git a/Services/Compositor/DisplayListPlayerSkia.h b/Services/Compositor/DisplayListPlayerSkia.hindex 1fa29055982..88c39562424 100644--- a/Services/Compositor/DisplayListPlayerSkia.h+++ b/Services/Compositor/DisplayListPlayerSkia.h@@ -108,7 +108,6 @@ private:void end_tile_raster();Compositing::RustFFI::NestedDisplayListReplay begin_nested_display_list(Compositing::RustFFI::NestedDisplayListPlacement const&, bool requires_direct_replay);void end_nested_display_list();- bool nested_display_list(u64 display_list_id, Compositing::RustFFI::FfiNestedDisplayList&) const;void clip_path(SkPath, Gfx::WindingRule, bool anti_aliased);diff --git a/Services/Compositor/RasterizeDisplayList.cpp b/Services/Compositor/RasterizeDisplayList.cppdeleted file mode 100644index 18f01f16ed8..00000000000--- a/Services/Compositor/RasterizeDisplayList.cpp+++ /dev/null@@ -1,45 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <Compositor/DisplayListPlayerSkia.h>-#include <Compositor/DisplayListRasterCache.h>-#include <Compositor/PaintingSurface.h>-#include <Compositor/RasterizeDisplayList.h>-#include <Compositor/SkiaBackendContext.h>-#include <LibGfx/Bitmap.h>--namespace Compositor {--// The largest frame WebContent rasterizes for an SVG image.-static constexpr int max_target_dimension = 16384;--ErrorOr<void> rasterize_display_list(Compositing::DisplayList const& display_list, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::DisplayListResourceTransaction&& resources, Gfx::Bitmap& target)-{- if (target.format() != Gfx::BitmapFormat::BGRA8888 || target.alpha_type() != Gfx::AlphaType::Premultiplied)- return Error::from_string_literal("Target bitmap is not BGRA8888 with premultiplied alpha");- if (target.width() > max_target_dimension || target.height() > max_target_dimension)- return Error::from_string_literal("Target bitmap is too large");- if (!resources.font_ids_to_remove.is_empty() || !resources.image_frame_ids_to_remove.is_empty() || !resources.video_sink_ids_to_remove.is_empty() || !resources.display_list_ids_to_remove.is_empty())- return Error::from_string_literal("Resource transaction removes resources");-- Compositing::DisplayListResourceStorage resource_storage;- resource_storage.apply_transaction(move(resources));- TRY(resource_storage.validate_for_replay(display_list, visual_context_tree));-- __builtin_memset(target.scanline_u8(0), 0, target.size_in_bytes());- auto surface = Gfx::PaintingSurface::wrap_bitmap(target);-- // Raster on the CPU, so the pixels match a raster of the same list in any other process.- DisplayListPlayerSkia display_list_player { RefPtr<Gfx::SkiaBackendContext> {} };- DisplayListRasterCache raster_cache;- auto painter = display_list_player.begin_painting(*surface, resource_storage, raster_cache, nullptr);- display_list.replay(visual_context_tree, painter, MonotonicTime::now().nanoseconds());- display_list_player.end_painting();- display_list_player.flush(*surface);- return {};-}--}diff --git a/Services/Compositor/RasterizeDisplayList.h b/Services/Compositor/RasterizeDisplayList.hdeleted file mode 100644index 2ea4edb835a..00000000000--- a/Services/Compositor/RasterizeDisplayList.h+++ /dev/null@@ -1,21 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Error.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibGfx/Forward.h>--namespace Compositor {--// Plays a display list that WebContent recorded outside any compositor context, such as one frame of an SVG image,-// into a bitmap it shares with this process. The transaction must carry every resource the list refers to.-ErrorOr<void> rasterize_display_list(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&, Compositing::DisplayListResourceTransaction&&, Gfx::Bitmap& target);--}diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex 3bc60104d9b..5bc5e0b3225 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -30,7 +30,6 @@ fn main() -> Result<(), Box<dyn Error>> {("RawAttachment", "IPC::RawAttachment"),("RawMessage", "IPC::FfiRawMessage"),("EncodedValue", "AK::ReadonlyBytes"),- ("FfiDisplayList", "Compositing::RustFFI::FfiDisplayList"),("FfiRasterPainter", "Compositing::RustFFI::FfiRasterPainter"),("FfiReplaySelection", "Compositing::RustFFI::FfiReplaySelection"),("RecordSpan", "Compositing::RustFFI::RecordSpan"),diff --git a/Services/Compositor/Rust/src/context_state/mod.rs b/Services/Compositor/Rust/src/context_state/mod.rsindex 675a12ec45a..68752a4efb1 100644--- a/Services/Compositor/Rust/src/context_state/mod.rs+++ b/Services/Compositor/Rust/src/context_state/mod.rs@@ -19,6 +19,7 @@ use crate::frame_inputs::FrameInputs;use crate::host::{ContextTimer, Host, PendingFrame, PresentationId, WebContentClientId};use crate::input_event::is_keyboard_scroll_key;use crate::keyboard_scroll_controller::{KeyRelease, KeyStep, KeyboardScrollController};+use crate::nested_display_lists::NestedDisplayListStore;use crate::overlays::{ContextOverlays, UIOverlays};use crate::scroll_fling_controller::ScrollFlingController;use crate::scroll_snap_controller::{ScrollSnapController, SnapScrollStart, StepDecision};@@ -299,6 +300,8 @@ pub struct ContextState {parent_context_id: Option<CompositorContextId>,scene: ContextScene,+ // Shared with the frames painted with it, so a change makes a store of its own.+ nested_display_lists: Rc<NestedDisplayListStore>,presents_to_client: bool,viewport_size: IntSize,device_pixel_ratio: f64,@@ -399,6 +402,7 @@ impl ContextState {bound_presentation: Default::default(),parent_context_id: Default::default(),scene: Default::default(),+ nested_display_lists: Default::default(),presents_to_client: page_id.is_some(),viewport_size: Default::default(),device_pixel_ratio: 1.0,@@ -459,6 +463,12 @@ impl ContextState {pub fn display_list(&self) -> Option<Rc<DisplayList>> {self.scene.display_list().clone()}+ pub fn nested_display_lists(&self) -> Rc<NestedDisplayListStore> {+ self.nested_display_lists.clone()+ }+ pub fn nested_display_lists_mut(&mut self) -> &mut NestedDisplayListStore {+ Rc::make_mut(&mut self.nested_display_lists)+ }pub fn context_id(&self) -> CompositorContextId {self.context_id}diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex 3362377e029..1833418f0b7 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -9,6 +9,8 @@use super::{CompositorCore, ContextOwnerCheckResult};use crate::host::{PresentationId, WebContentClientId};+use crate::nested_display_lists::{NestedDisplayListStore, ReferencedResources};+use libcompositing_rust::display_list::replay::{ReplayFrame, ReplaySelection, replay_display_list};use libcompositing_rust::ipc_types::compositor_presentation_client::messages::DidNotDispatchInputEvent;use libcompositing_rust::ipc_types::compositor_presentation_server::messages::{HandleAndDispatchKeyEvent, HandleAndDispatchMouseEvent, HandleAndDispatchPinchEvent,@@ -16,17 +18,19 @@ use libcompositing_rust::ipc_types::compositor_presentation_server::messages::{use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{ApplyScrollRequests, BeginInputTraceForTesting, BeginInputTraceForTestingResponse,ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, InvalidateKeyboardScrollState,- InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState, RouteFirstWheelStepForTesting,- RouteFirstWheelStepForTestingResponse, ScrollStateForTesting, ScrollStateForTestingResponse,- TakeInputTraceForTesting, TakeInputTraceForTestingResponse, TakePendingAsyncScrollUpdates,- TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread, TakeWheelEventFromMainThreadResponse,- UpdateScrollState, WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,+ InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState, RasterizeDisplayList,+ RasterizeDisplayListResponse, RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse,+ ScrollStateForTesting, ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,+ TakePendingAsyncScrollUpdates, TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread,+ TakeWheelEventFromMainThreadResponse, UpdateDisplayList, UpdateScrollState, UpdateVisualContextTree,+ WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,};use libcompositing_rust::ipc_types::{Compositing_WheelEventAnswer as WheelEventAnswer, Compositing_WheelStepLetThrough as WheelStepLetThrough,compositor_presentation_server, compositor_web_content_server,};use libcompositing_rust::scrolling::async_scrolling_state::AsyncScrollOperationID;+use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, DisplayList};use libcompositing_rust::scrolling::{CompositorContextId, KeyEvent, KeyModifier, MouseButton, MouseEvent, MouseEventType, PendingAsyncScrollUpdates,PinchEvent, ScrollRequest, ScrollStateSnapshot,@@ -34,6 +38,20 @@ use libcompositing_rust::scrolling::{use libcompositing_rust::time::MonotonicTime;use libgfx_rust::FloatPoint;use libipc_rust::Misbehavior;+use std::io::Write;+use std::rc::Rc;++// The time a display list takes to be taken in, which WebContent's time to publish it is logged next to.+fn display_list_timing_enabled() -> bool {+ static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *ENABLED.get_or_init(|| {+ std::env::var_os("LADYBIRD_DISPLAY_LIST_TIMING").is_some_and(|value| !value.is_empty() && value != "0")+ })+}++const NESTED_DISPLAY_LISTS_THAT_NEST_THEMSELVES: &str = "WebContent published display lists that nest themselves";+const DISPLAY_LIST_WITH_UNUSABLE_SCROLLING_STATE: &str =+ "WebContent published a display list with scrolling state the compositor cannot use";// The main thread allocates the ids of the scrolls it requests from here up, so that they never meet the ids the// compositor allocates for scrolls of its own.@@ -184,6 +202,190 @@ impl MessagesFromWebContent<'_> {}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 tape_size = message.tape_size;+ let storage = match self.core.raster().receive_display_list_storage(+ message.display_list_buffer,+ message.tape_size,+ message.run_count,+ ) {+ Ok(storage) => storage,+ Err(error) => {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Rejecting display list from WebContent: {error}"+ );+ return Err(Misbehavior(+ "WebContent published a display list its shared buffer does not hold",+ ));+ }+ };+ let adopt_time = started_at.elapsed();+ if !self.context_is_owned_by_sender(message.context_id)? {+ return Ok(());+ }+ let properties = message.display_list_properties;+ let tree = message.visual_context_tree.0;+ if properties.compatible_visual_context_tree_structural_epoch != tree.structural_epoch {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Dropping inconsistent display list update (display list epoch {}, tree epoch {})",+ properties.compatible_visual_context_tree_structural_epoch,+ tree.structural_epoch+ );+ return Ok(());+ }+ if !tree.display_list_references_only_live_nodes(storage.command_runs()) {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Dropping display list update that names nodes its visual context tree does not hold"+ );+ return Ok(());+ }+ let Ok(scroll_state_snapshot) = ScrollStateSnapshot::from_encoded_bytes(&message.scroll_state) else {+ return Err(Misbehavior(DISPLAY_LIST_WITH_UNUSABLE_SCROLLING_STATE));+ };+ let display_list = DisplayList::new(+ storage,+ properties.id,+ properties.compatible_visual_context_tree_structural_epoch,+ message.async_scrolling_metadata,+ properties.surface_clear_color,+ properties.root_group_color,+ );+ if !self.core.install_display_list_update(+ message.context_id,+ Rc::new(display_list),+ AccumulatedVisualContextTree::from_arc(tree),+ scroll_state_snapshot,+ self.now,+ ) {+ return Err(Misbehavior(DISPLAY_LIST_WITH_UNUSABLE_SCROLLING_STATE));+ }+ if !self+ .core+ .apply_resource_transaction(message.context_id, message.resource_transaction)+ {+ return Err(Misbehavior(NESTED_DISPLAY_LISTS_THAT_NEST_THEMSELVES));+ }+ if display_list_timing_enabled() {+ let _ = writeln!(+ std::io::stderr(),+ "DISPLAY_LIST_RECEIVE bytes={tape_size} adopt={} µs install={} µs",+ adopt_time.as_micros(),+ (started_at.elapsed() - adopt_time).as_micros()+ );+ }+ Ok(())+ }++ fn update_visual_context_tree(&mut self, message: UpdateVisualContextTree) -> Result<(), Misbehavior> {+ let unusable_scroll_state =+ Misbehavior("WebContent published a visual context tree with a scroll state the compositor cannot use");+ let Ok(scroll_state_snapshot) = ScrollStateSnapshot::from_encoded_bytes(&message.scroll_state) else {+ return Err(unusable_scroll_state);+ };+ if !scroll_state_snapshot.has_only_finite_offsets() {+ return Err(unusable_scroll_state);+ }+ if !self.context_is_owned_by_sender(message.context_id)? {+ return Ok(());+ }+ let tree_was_replaced = self.core.update_visual_context_tree(+ message.context_id,+ AccumulatedVisualContextTree::from_arc(message.visual_context_tree.0),+ scroll_state_snapshot,+ message.keyboard_scroll_state,+ self.now,+ );+ if tree_was_replaced+ && !self+ .core+ .apply_resource_transaction(message.context_id, message.resource_transaction)+ {+ return Err(Misbehavior(NESTED_DISPLAY_LISTS_THAT_NEST_THEMSELVES));+ }+ Ok(())+ }++ fn rasterize_display_list(+ &mut self,+ message: RasterizeDisplayList,+ ) -> Result<RasterizeDisplayListResponse, Misbehavior> {+ let raster = self.core.raster();+ let (client, token) = (self.client_id.0, message.token);+ let not_rasterized = |reason: &str| {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Not rasterizing display list from WebContent: {reason}"+ );+ raster.discard_staged_rasterization(client, token);+ Ok(RasterizeDisplayListResponse { success: false })+ };+ let storage = match raster.receive_display_list_storage(+ message.display_list_buffer,+ message.tape_size,+ message.run_count,+ ) {+ Ok(storage) => storage,+ Err(error) => {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Rejecting display list to rasterize from WebContent: {error}"+ );+ raster.discard_staged_rasterization(client, token);+ return Err(Misbehavior(+ "WebContent asked to rasterize a display list its shared buffer does not hold",+ ));+ }+ };+ let transaction = message.nested_display_lists;+ if transaction.removes_anything() || !transaction.video_sinks.is_empty() {+ return not_rasterized("Resource transaction holds more than the display lists it nests");+ }+ let mut nested_display_lists = NestedDisplayListStore::default();+ for display_list in transaction.display_lists {+ nested_display_lists.add(display_list);+ }+ let properties = message.display_list_properties;+ let tree = message.visual_context_tree.0;+ if properties.compatible_visual_context_tree_structural_epoch != tree.structural_epoch+ || !tree.display_list_references_only_live_nodes(storage.command_runs())+ {+ return not_rasterized("Display list does not match its visual context tree");+ }+ let mut resources = ReferencedResources::default();+ nested_display_lists.collect_referenced_resources(&storage, &tree, &mut resources);+ if !nested_display_lists.nested_display_lists_are_replayable(&resources) {+ return not_rasterized("Nested display list is missing or refers to itself");+ }+ let ids = |set: &std::collections::HashSet<u64>| set.iter().copied().collect::<Vec<u64>>();+ if !raster.staged_rasterization_has_resources(+ client,+ token,+ &ids(&resources.font_ids),+ &ids(&resources.image_frame_ids),+ ) {+ return not_rasterized("Display list draws resources that were not staged for it");+ }+ let time_ns = self.now.nanoseconds();+ let success = raster.rasterize_staged(client, token, |painter| {+ let frame = ReplayFrame::unscrolled(time_ns, &nested_display_lists);+ replay_display_list(+ &tree,+ storage.bytes(),+ storage.command_runs(),+ storage.effect_clip_plan(&tree),+ properties.root_group_color,+ &frame,+ ReplaySelection::default(),+ painter,+ );+ });+ Ok(RasterizeDisplayListResponse { success })+ }+fn update_scroll_state(&mut self, message: UpdateScrollState) -> Result<(), Misbehavior> {let Ok(scroll_state_snapshot) = ScrollStateSnapshot::from_encoded_bytes(&message.scroll_state) else {return Err(Misbehavior("Invalid scroll state"));diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rsindex ae0720ae2ce..b29af7e4613 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -19,9 +19,10 @@ use crate::host::{};use crate::overlays::UIOverlays;use crate::presenting::ContextPresenting;-use crate::raster_host::{RasterHost, SurfaceHandle};+use crate::raster_host::{FfiResourceChanges, FfiVideoSinkResource, RasterHost, SurfaceHandle};use crate::wheel_gesture_routing::WheelGestureIdAllocator;use libcompositing_rust::ipc_types::Compositing_ContextVisibility as ContextVisibility;+use libcompositing_rust::ipc_types::Compositing_DisplayListResourceTransaction;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, CompositorContextId, DisplayList, KeyboardScrollState, ScrollStateSnapshot,};@@ -55,16 +56,6 @@ pub enum ContextOwnerCheckResult {ConflictingOwner,}-// What became of a visual context tree that came with the scroll state pairing with it.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u8)]-pub enum VisualContextTreeUpdateResult {- TreeReplaced,- // The tree does not fit the installed display list, so only its scroll state was taken.- TreeDropped,- InvalidScrollState,-}-#[derive(Clone, Copy, PartialEq, Eq)]enum WheelStepOrigin {UI,@@ -704,6 +695,50 @@ impl CompositorCore {installed}+ /// Adds and removes the resources that a display list or a visual context tree that the context took comes with.+ /// Answers false, changing nothing, for display lists that would nest themselves.+ pub fn apply_resource_transaction(+ &self,+ context_id: CompositorContextId,+ transaction: Compositing_DisplayListResourceTransaction,+ ) -> bool {+ let _entered = self.enter();++ let Some(context) = self.context_if_present(context_id) else {+ return true;+ };+ let changes_resources_held_by_the_host = !transaction.video_sinks.is_empty() || transaction.removes_anything();+ if !transaction.display_lists.is_empty() || !transaction.display_list_ids_to_remove.is_empty() {+ let mut context = context.borrow_mut();+ let nested_display_lists = context.nested_display_lists_mut();+ if !nested_display_lists.add_all(transaction.display_lists) {+ return false;+ }+ for &display_list_id in &transaction.display_list_ids_to_remove {+ nested_display_lists.remove(display_list_id);+ }+ }+ if !changes_resources_held_by_the_host {+ return true;+ }+ let video_sinks: Vec<FfiVideoSinkResource> = transaction+ .video_sinks+ .iter()+ .map(|&(id, sink_handle)| FfiVideoSinkResource { id, sink_handle })+ .collect();+ self.raster.apply_resource_changes(+ context_id,+ &FfiResourceChanges {+ video_sinks: ak::Span::new(&video_sinks),+ font_ids_to_remove: ak::Span::new(&transaction.font_ids_to_remove),+ image_frame_ids_to_remove: ak::Span::new(&transaction.image_frame_ids_to_remove),+ video_sink_ids_to_remove: ak::Span::new(&transaction.video_sink_ids_to_remove),+ display_list_ids_to_remove: ak::Span::new(&transaction.display_list_ids_to_remove),+ },+ );+ true+ }+// Returns false for a tree that does not fit the installed display list, of which only the scroll state is taken.pub fn update_visual_context_tree(&self,diff --git a/Services/Compositor/Rust/src/core/presenting.rs b/Services/Compositor/Rust/src/core/presenting.rsindex 7815a6bd288..ed2d2f2a9eb 100644--- a/Services/Compositor/Rust/src/core/presenting.rs+++ b/Services/Compositor/Rust/src/core/presenting.rs@@ -353,9 +353,13 @@ impl CompositorCore {));}if child_presenting.needs_rasterization() {- let (display_list, frame_inputs) = {+ let (display_list, nested_display_lists, frame_inputs) = {let mut child_state = child_state.try_borrow_mut().ok()?;- (child_state.display_list(), child_state.frame_inputs(now))+ (+ child_state.display_list(),+ child_state.nested_display_lists(),+ child_state.frame_inputs(now),+ )};let nested_contexts = ContextsNestedIn {core: self,@@ -363,7 +367,12 @@ impl CompositorCore {now,};let environment = self.environment(child_context_id, now, &nested_contexts);- child_presenting.present_synchronously(&environment, display_list.as_ref(), frame_inputs);+ child_presenting.present_synchronously(+ &environment,+ display_list.as_ref(),+ &nested_display_lists,+ frame_inputs,+ );}child_presenting.composited_surface()}@@ -380,10 +389,11 @@ impl CompositorCore {let Some(presenting) = self.presenting_of(context_id) else {return;};- let (display_list, frame_inputs, bound_presentation) = {+ let (display_list, nested_display_lists, frame_inputs, bound_presentation) = {let mut context = context.borrow_mut();(context.display_list(),+ context.nested_display_lists(),context.frame_inputs(now),context.bound_presentation(),)@@ -395,9 +405,13 @@ impl CompositorCore {};let environment = self.environment(context_id, now, &nested_contexts);let mut presenting = presenting.borrow_mut();- let Some(prepared_frame) =- presenting.prepare_frame(&environment, pending_frame, display_list.as_ref(), frame_inputs)- else {+ let Some(prepared_frame) = presenting.prepare_frame(+ &environment,+ pending_frame,+ display_list.as_ref(),+ &nested_display_lists,+ frame_inputs,+ ) else {return;};@@ -1057,6 +1071,7 @@ impl CompositorCore {let Some(display_list) = context.borrow().display_list() else {return false;};+ let nested_display_lists = context.borrow().nested_display_lists();let screenshot_inputs = context.borrow_mut().frame_inputs_for_screenshot(now);let nested_contexts = ContextsNestedIn {core: self,@@ -1064,9 +1079,13 @@ impl CompositorCore {now,};let environment = self.environment(context_id, now, &nested_contexts);- presenting- .borrow_mut()- .paint_screenshot(&environment, target, &display_list, &screenshot_inputs.frame_inputs);+ presenting.borrow_mut().paint_screenshot(+ &environment,+ target,+ &display_list,+ &nested_display_lists,+ &screenshot_inputs.frame_inputs,+ );if !screenshot_inputs.scrollbar_fade_damage_rect.is_empty() {let viewport_rect = presenting.borrow().viewport_rect_of_current_frame();if let Some(viewport_rect) = viewport_rect {diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsindex 22f4c3018da..2a0c8387654 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -9,7 +9,7 @@use crate::core::messages::{MessagesFromPresentation, MessagesFromWebContent};use crate::core::presenting::{GpuBackend, PresentationCapabilities};-use crate::core::{CompositorCore, ContextOwnerCheckResult, VisualContextTreeUpdateResult};+use crate::core::{CompositorCore, ContextOwnerCheckResult};use crate::host::{ContextTimer, FfiCompositorCoreHost, Host, PresentationId, WebContentClientId};use crate::overlays::{PausedDebuggerOverlayAction, PausedDebuggerOverlayState, PictureInPictureControl, PictureInPictureControlsState,@@ -17,14 +17,12 @@ use crate::overlays::{};use crate::raster_host::{FfiRasterHost, RasterHost};use libcompositing_rust::display_list::commands::CompositorContextId;-use libcompositing_rust::ffi::{FfiDisplayList, tree_sharing_handle};use libcompositing_rust::ipc_types::{Compositing_ContextVisibility as ContextVisibility, compositor_presentation_server, compositor_web_content_server,};-use libcompositing_rust::scrolling::{KeyboardScrollState, ScrollStateSnapshot};use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{IntRect, IntSize};-use libipc_rust::cpp_connection::{EncodedValue, RawMessage};+use libipc_rust::cpp_connection::RawMessage;use std::ffi::c_void;use std::rc::Rc;@@ -502,78 +500,6 @@ pub struct FfiUIOverlays<'a> {pub picture_in_picture_controls_hovered_control: u8,}-/// Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode, or that hold-/// numbers no scroll can be calculated with.-///-/// # Safety-///-/// The storage of `display_list` must be a live display list storage handle, and `visual_context_tree` a live retained-/// tree handle.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_core_install_display_list_update(- core: &CompositorCore,- context_id: u64,- display_list: &FfiDisplayList<'_>,- visual_context_tree: *const c_void,- scroll_state: EncodedValue<'_>,- now_nanoseconds: i64,-) -> bool {- // SAFETY: The caller lends a strong reference to the storage.- let Ok(display_list) = (unsafe { display_list.share() }) else {- return false;- };- let Ok(scroll_state_snapshot) = scroll_state.decode::<ScrollStateSnapshot>() else {- return false;- };- core.install_display_list_update(- CompositorContextId(context_id),- Rc::new(display_list),- // SAFETY: The caller lends a strong reference to the tree.- unsafe { tree_sharing_handle(visual_context_tree) },- scroll_state_snapshot,- MonotonicTime::from_nanoseconds(now_nanoseconds),- )-}--/// Changes nothing for a scroll state or keyboard scroll state that do not decode, or a scroll state with offsets that-/// are not finite.-///-/// # Safety-///-/// `visual_context_tree` must be a live retained tree handle.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_core_update_visual_context_tree(- core: &CompositorCore,- context_id: u64,- visual_context_tree: *const c_void,- scroll_state: EncodedValue<'_>,- keyboard_scroll_state: EncodedValue<'_>,- now_nanoseconds: i64,-) -> VisualContextTreeUpdateResult {- let (Ok(scroll_state_snapshot), Ok(keyboard_scroll_state)) = (- scroll_state.decode::<ScrollStateSnapshot>(),- keyboard_scroll_state.decode::<KeyboardScrollState>(),- ) else {- return VisualContextTreeUpdateResult::InvalidScrollState;- };- if !scroll_state_snapshot.has_only_finite_offsets() {- return VisualContextTreeUpdateResult::InvalidScrollState;- }- let tree_was_replaced = core.update_visual_context_tree(- CompositorContextId(context_id),- // SAFETY: The caller lends a strong reference to the tree.- unsafe { tree_sharing_handle(visual_context_tree) },- scroll_state_snapshot,- keyboard_scroll_state,- MonotonicTime::from_nanoseconds(now_nanoseconds),- );- if tree_was_replaced {- VisualContextTreeUpdateResult::TreeReplaced- } else {- VisualContextTreeUpdateResult::TreeDropped- }-}-#[unsafe(no_mangle)]pub extern "C" fn compositor_core_set_visibility(core: &CompositorCore,diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsindex d90cb049e23..bbba0f8a028 100644--- a/Services/Compositor/Rust/src/lib.rs+++ b/Services/Compositor/Rust/src/lib.rs@@ -25,6 +25,7 @@ pub mod frame_inputs;pub mod host;pub mod input_event;pub mod keyboard_scroll_controller;+pub mod nested_display_lists;pub mod overlays;pub mod presenting;pub mod raster_host;diff --git a/Services/Compositor/Rust/src/nested_display_lists.rs b/Services/Compositor/Rust/src/nested_display_lists.rsnew file mode 100644index 00000000000..082c3f25949--- /dev/null+++ b/Services/Compositor/Rust/src/nested_display_lists.rs@@ -0,0 +1,175 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The display lists that the display lists of a context nest, such as those of its SVG images, which the replays of+//! its frames draw.++use libcompositing_rust::display_list::replay::{NestedDisplayList, NestedDisplayLists};+use libcompositing_rust::display_list::storage::DisplayListStorage;+use libcompositing_rust::display_list::summary::requires_direct_replay_without_nested_lists;+use libcompositing_rust::ipc_types::NestedDisplayListResource;+use libcompositing_rust::visual_context::VisualContextTree;+use libgfx_rust::Color;+use std::cell::RefCell;+use std::collections::{HashMap, HashSet};+use std::sync::Arc;++#[derive(Clone)]+struct StoredDisplayList {+ storage: Arc<DisplayListStorage>,+ tree: Arc<VisualContextTree>,+ root_group_color: Color,+}++/// The fonts and image frames that a display list draws, with those of the lists it nests, and the lists it nests.+#[derive(Default)]+pub struct ReferencedResources {+ pub font_ids: HashSet<u64>,+ pub image_frame_ids: HashSet<u64>,+ pub display_list_ids: HashSet<u64>,+}++#[derive(Clone, Default)]+pub struct NestedDisplayListStore {+ display_lists: HashMap<u64, StoredDisplayList>,+ // Whether a raster of a list can differ from replaying it, which is intrinsic to the list and the lists it nests.+ requires_direct_replay: RefCell<HashMap<u64, bool>>,+}++impl NestedDisplayListStore {+ /// A list that the store holds already keeps the tape it was added with.+ pub fn add(&mut self, resource: NestedDisplayListResource) {+ if self.display_lists.contains_key(&resource.properties.id) {+ return;+ }+ self.display_lists.insert(+ resource.properties.id,+ StoredDisplayList {+ storage: resource.storage,+ tree: resource.tree,+ root_group_color: resource.properties.root_group_color,+ },+ );+ self.requires_direct_replay.get_mut().clear();+ }++ /// Adds the lists, answering false, with none of them added, where one of them would reach itself, as replay follows+ /// nested lists with no depth limit.+ pub fn add_all(&mut self, resources: Vec<NestedDisplayListResource>) -> bool {+ let mut added = Vec::new();+ for resource in resources {+ let display_list_id = resource.properties.id;+ if self.display_lists.contains_key(&display_list_id) {+ continue;+ }+ self.add(resource);+ added.push(display_list_id);+ }+ // NB: A list held already does not reach itself, so only a new list can close a loop.+ if !added+ .iter()+ .any(|&display_list_id| self.reaches_itself(display_list_id))+ {+ return true;+ }+ for display_list_id in added {+ self.remove(display_list_id);+ }+ false+ }++ fn reaches_itself(&self, display_list_id: u64) -> bool {+ let stored = &self.display_lists[&display_list_id];+ let mut reached = ReferencedResources::default();+ self.collect_referenced_resources(&stored.storage, &stored.tree, &mut reached);+ reached.display_list_ids.contains(&display_list_id)+ }++ pub fn remove(&mut self, display_list_id: u64) {+ if self.display_lists.remove(&display_list_id).is_some() {+ self.requires_direct_replay.get_mut().clear();+ }+ }++ pub fn contains(&self, display_list_id: u64) -> bool {+ self.display_lists.contains_key(&display_list_id)+ }++ /// Adds what the list draws, and what the lists it nests that the store holds draw.+ pub fn collect_referenced_resources(+ &self,+ storage: &DisplayListStorage,+ tree: &VisualContextTree,+ resources: &mut ReferencedResources,+ ) {+ let summary = storage.summary();+ resources.font_ids.extend(&summary.font_ids);+ resources.image_frame_ids.extend(&summary.image_frame_ids);+ tree.for_each_effects_filter_image_frame_id(&mut |id| {+ resources.image_frame_ids.insert(id);+ });+ for &display_list_id in &summary.display_list_ids {+ if !resources.display_list_ids.insert(display_list_id) {+ continue;+ }+ if let Some(nested) = self.display_lists.get(&display_list_id) {+ self.collect_referenced_resources(&nested.storage, &nested.tree, resources);+ }+ }+ }++ /// Whether the lists that a list nests are all held, and none of them reaches itself, as replay follows nested lists+ /// with no depth limit.+ pub fn nested_display_lists_are_replayable(&self, resources: &ReferencedResources) -> bool {+ resources.display_list_ids.iter().all(|&display_list_id| {+ self.display_lists.contains_key(&display_list_id) && !self.reaches_itself(display_list_id)+ })+ }++ // A raster of a list can differ from replaying it in place when a destination-reading operation can see what was+ // painted before the list began, or when the list draws live content that changes under its immutable commands.+ // A nested list's live content matters at any depth, and its unisolated destination reads matter when its command+ // is not enclosed in a layer; recursing unconditionally is slightly conservative for the latter.+ fn list_requires_direct_replay(&self, display_list_id: u64, visited: &mut HashSet<u64>) -> bool {+ if let Some(&memoized) = self.requires_direct_replay.borrow().get(&display_list_id) {+ return memoized;+ }+ visited.insert(display_list_id);+ let stored = &self.display_lists[&display_list_id];+ let mut requires_direct_replay = requires_direct_replay_without_nested_lists(+ stored.storage.bytes(),+ stored.storage.command_runs(),+ &stored.tree,+ );+ for &nested_id in &stored.storage.summary().display_list_ids {+ if requires_direct_replay {+ break;+ }+ if !visited.insert(nested_id) {+ continue;+ }+ if self.display_lists.contains_key(&nested_id) {+ requires_direct_replay = self.list_requires_direct_replay(nested_id, visited);+ }+ }+ self.requires_direct_replay+ .borrow_mut()+ .insert(display_list_id, requires_direct_replay);+ requires_direct_replay+ }+}++impl NestedDisplayLists for NestedDisplayListStore {+ fn nested_display_list(&self, display_list_id: u64) -> Option<NestedDisplayList<'_>> {+ let stored = self.display_lists.get(&display_list_id)?;+ Some(NestedDisplayList {+ storage: &stored.storage,+ tree: &stored.tree,+ root_group_color: stored.root_group_color,+ requires_direct_replay: self.list_requires_direct_replay(display_list_id, &mut HashSet::new()),+ })+ }+}diff --git a/Services/Compositor/Rust/src/presenting/damage.rs b/Services/Compositor/Rust/src/presenting/damage.rsindex 8f1fb203885..028689a5196 100644--- a/Services/Compositor/Rust/src/presenting/damage.rs+++ b/Services/Compositor/Rust/src/presenting/damage.rs@@ -10,6 +10,7 @@ use super::layers::{LayerUpdate, MediaUpdate};use super::{ContextPresenting, FrameToPaint, PresentingEnvironment, rect_of_size};use crate::frame_inputs::FrameInputs;use crate::host::PendingFrame;+use crate::nested_display_lists::NestedDisplayListStore;use crate::raster_host::LiveContent;use libcompositing_rust::display_list::commands::{CanvasId, ImageFrameResourceId, VideoSinkResourceId};use libcompositing_rust::display_list::damage::{DisplayListDamage, LayerPlans, LiveContentChanges};@@ -23,6 +24,7 @@ use std::rc::Rc;/// lists cannot see change.pub struct PaintedFrame {pub display_list: Rc<DisplayList>,+ pub nested_display_lists: Rc<NestedDisplayListStore>,pub frame_inputs: FrameInputs,pub viewport_size: IntSize,canvas_content_generations: HashMap<u64, u64>,@@ -108,6 +110,7 @@ impl ContextPresenting {&mut self,viewport_rect: IntRect,display_list: &Rc<DisplayList>,+ nested_display_lists: &Rc<NestedDisplayListStore>,frame_inputs: FrameInputs,live_content: &LiveContent,) {@@ -133,6 +136,7 @@ impl ContextPresenting {let image_frame_pixel_generations = live_content.image_frames.clone();self.painted_frame = Some(PaintedFrame {display_list: display_list.clone(),+ nested_display_lists: nested_display_lists.clone(),frame_inputs,viewport_size: IntSize {width: viewport_rect.width,diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rsindex fd84adf7c10..feffd4a349e 100644--- a/Services/Compositor/Rust/src/presenting/mod.rs+++ b/Services/Compositor/Rust/src/presenting/mod.rs@@ -14,6 +14,7 @@ pub mod pacing;use crate::frame_inputs::FrameInputs;use crate::host::{ContextTimer, Host, PendingFrame};+use crate::nested_display_lists::NestedDisplayListStore;use crate::raster_host::{FfiStoreResize, FfiSublayer, PaintingResources, RasterHost, StorePublication, StoreResizeOutcome, SurfaceBlend,SurfaceHandle,@@ -56,9 +57,10 @@ pub struct PreparedFrame {pub sublayers: Vec<FfiSublayer>,}-// The display list and the frame inputs a frame is painted with.+// The display list, the display lists it nests and the frame inputs a frame is painted with.pub(crate) struct FrameToPaint<'a> {pub display_list: &'a Rc<DisplayList>,+ pub nested_display_lists: &'a Rc<NestedDisplayListStore>,pub frame_inputs: &'a FrameInputs,}@@ -515,6 +517,7 @@ impl ContextPresenting {env: &PresentingEnvironment<'_>,pending_frame: PendingFrame,display_list: Option<&Rc<DisplayList>>,+ nested_display_lists: &Rc<NestedDisplayListStore>,frame_inputs: Option<FrameInputs>,) -> Option<PreparedFrame> {if self.is_present_blocked(env.raster, env.context_id) {@@ -530,6 +533,7 @@ impl ContextPresenting {let live_content = self.live_content(env, display_list);let frame = FrameToPaint {display_list,+ nested_display_lists,frame_inputs: &frame_inputs,};let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);@@ -539,7 +543,13 @@ impl ContextPresenting {let only_media_shown_by_window_server_changed =frame_damage.layers.shown_by_window_server && frame_damage.live_media_changed;self.commit_layer_update(env, frame_damage.layers);- self.remember_painted_frame(pending_frame.viewport_rect, display_list, frame_inputs, &live_content);+ self.remember_painted_frame(+ pending_frame.viewport_rect,+ display_list,+ nested_display_lists,+ frame_inputs,+ &live_content,+ );if !only_media_shown_by_window_server_changed {return None;}@@ -567,7 +577,13 @@ impl ContextPresenting {});}self.commit_layer_update(env, frame_damage.layers);- self.remember_painted_frame(pending_frame.viewport_rect, display_list, frame_inputs, &live_content);+ self.remember_painted_frame(+ pending_frame.viewport_rect,+ display_list,+ nested_display_lists,+ frame_inputs,+ &live_content,+ );Some(PreparedFrame {rendered_surface: Some(store),bitmap_id,@@ -582,6 +598,7 @@ impl ContextPresenting {&mut self,env: &PresentingEnvironment<'_>,display_list: Option<&Rc<DisplayList>>,+ nested_display_lists: &Rc<NestedDisplayListStore>,frame_inputs: Option<FrameInputs>,) -> bool {if !self.can_render_frame(display_list, env.raster, env.context_id) {@@ -603,6 +620,7 @@ impl ContextPresenting {let live_content = self.live_content(env, display_list);let frame = FrameToPaint {display_list,+ nested_display_lists,frame_inputs: &frame_inputs,};let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);@@ -614,7 +632,13 @@ impl ContextPresenting {let repaint_rect = self.store_damage.take(bitmap_id, raster_damage_rect, store_rect);let _ = self.paint_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);self.commit_layer_update(env, frame_damage.layers);- self.remember_painted_frame(pending_frame.viewport_rect, display_list, frame_inputs, &live_content);+ self.remember_painted_frame(+ pending_frame.viewport_rect,+ display_list,+ nested_display_lists,+ frame_inputs,+ &live_content,+ );env.raster.flush(&store);env.raster.complete_rendering(env.context_id, bitmap_id);self.latest_rendered_surface = env.raster.latest_rendered_store_surface(env.context_id);@@ -634,10 +658,12 @@ impl ContextPresenting {env: &PresentingEnvironment<'_>,target: &SurfaceHandle,display_list: &Rc<DisplayList>,+ nested_display_lists: &Rc<NestedDisplayListStore>,frame_inputs: &FrameInputs,) {let frame = FrameToPaint {display_list,+ nested_display_lists,frame_inputs,};self.paint_current_display_list(env, target, &frame, None, false, false);@@ -665,6 +691,7 @@ impl ContextPresenting {.draw_surface(&composited, &source, source_rect, source_rect, SurfaceBlend::Source);let frame = FrameToPaint {display_list: &painted_frame.display_list,+ nested_display_lists: &painted_frame.nested_display_lists,frame_inputs: &painted_frame.frame_inputs,};let snapshot_env = PresentingEnvironment {@@ -805,13 +832,12 @@ pub(crate) fn replay_into();env.raster.paint(env.context_id, target, PaintingResources::Page, |painter| {- let nested_display_lists = painter.nested_display_lists();let scrollbars = frame_inputs.scrollbars_shown_for_the_page();let replay_frame = ReplayFrame {scroll_offsets: frame_inputs.presented_scroll_state_snapshot.device_offsets(),scrollbars: &scrollbars,time_ns: frame_inputs.painted_at.nanoseconds(),- nested_display_lists: &nested_display_lists,+ nested_display_lists: frame.nested_display_lists.as_ref(),composited_contexts: env.composited_contexts,};let storage = display_list.storage();diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex e4e3f64f2eb..e893b5dc163 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -9,12 +9,15 @@//! 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::host::FfiRasterPainter;+use libcompositing_rust::ipc_types::Core_AnonymousBuffer;use libcompositing_rust::time::MonotonicTime;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)]@@ -111,6 +114,25 @@ pub struct FfiVideoSinkContent {pub frame_has_surface: bool,}+/// A video sink that a display list draws: its resource ID, and the handle of the sink.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(C)]+pub struct FfiVideoSinkResource {+ pub id: u64,+ pub sink_handle: u64,+}++/// The resources of a context that a display list or a visual context tree it accepted adds or removes, apart from the+/// fonts and image frames that went ahead of it.+#[repr(C)]+pub struct FfiResourceChanges<'a> {+ pub video_sinks: ak::Span<'a, FfiVideoSinkResource>,+ pub font_ids_to_remove: ak::Span<'a, u64>,+ pub image_frame_ids_to_remove: ak::Span<'a, u64>,+ pub video_sink_ids_to_remove: ak::Span<'a, u64>,+ pub display_list_ids_to_remove: ak::Span<'a, u64>,+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]#[repr(C)]pub struct FfiImageFrameContent {@@ -289,6 +311,22 @@ pub struct FfiRasterHost {unsafe extern "C" fn(*mut c_void, *mut c_void, unsafe extern "C" fn(*mut c_void, ak::Span<'_, u64>)),pub context_video_sinks_require_updates: unsafe extern "C" fn(*mut c_void, u64) -> bool,pub set_maximum_display_refresh_rate: unsafe extern "C" fn(*mut c_void, f64),++ /// Maps the shared memory of the descriptor, which it takes over, answering a mapping that `unmap_shared_memory`+ /// drops, or null where the descriptor does not hold that much. Writes where the memory is and its size.+ pub map_shared_memory: unsafe extern "C" fn(*mut c_void, i32, u64, *mut *const u8, *mut usize) -> *mut c_void,+ pub unmap_shared_memory: unsafe extern "C" fn(*mut c_void),+ pub apply_resource_changes: unsafe extern "C" fn(*mut c_void, u64, *const FfiResourceChanges<'_>),+ /// Arguments: the client, the token it staged the rasterization under, and the fonts and image frames the display+ /// list draws. Answers whether the rasterization is staged with all of them. A video sink drawn without a handle+ /// draws nothing, so the sinks are not asked about.+ pub staged_rasterization_has_resources:+ unsafe extern "C" fn(*mut c_void, u64, u64, ak::Span<'_, u64>, ak::Span<'_, u64>) -> bool,+ /// Writes the painter that paints into the target of the staged rasterization, with its resources, until+ /// `finish_staged_rasterization`. Answers false for a target that cannot be painted into.+ pub begin_staged_rasterization: unsafe extern "C" fn(*mut c_void, u64, u64, *mut FfiRasterPainter) -> bool,+ /// Ends the painting that began, flushes it into the target, and drops what was staged.+ pub finish_staged_rasterization: unsafe extern "C" fn(*mut c_void, u64, u64),}/// A surface of the C++ side, which this keeps alive.@@ -777,4 +815,82 @@ impl RasterHost {// SAFETY: The host outlives this.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(+ &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");+ };+ 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) };+ };+ #[cfg(unix)]+ let descriptor = std::os::fd::IntoRawFd::into_raw_fd(file.0);+ #[cfg(windows)]+ let descriptor = file.0.into_raw();+ let mut data = std::ptr::null();+ let mut data_size = 0;+ // SAFETY: The host outlives this, and takes the descriptor over.+ let mapping =+ unsafe { (self.0.map_shared_memory)(self.host(), descriptor, size, &raw mut data, &raw mut data_size) };+ 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) };+ // SAFETY: The mapping came from the host, which drops it once.+ unsafe { (self.0.unmap_shared_memory)(mapping) };+ storage+ }++ pub fn apply_resource_changes(&self, context_id: CompositorContextId, changes: &FfiResourceChanges<'_>) {+ // SAFETY: The host outlives this, and reads the changes during the call.+ unsafe { (self.0.apply_resource_changes)(self.host(), context_id.0, changes) };+ }++ pub fn staged_rasterization_has_resources(+ &self,+ client: u64,+ token: u64,+ font_ids: &[u64],+ image_frame_ids: &[u64],+ ) -> bool {+ // SAFETY: The host outlives this, and reads the IDs during the call.+ unsafe {+ (self.0.staged_rasterization_has_resources)(+ self.host(),+ client,+ token,+ ak::Span::new(font_ids),+ ak::Span::new(image_frame_ids),+ )+ }+ }++ /// Drops what the client staged under the token, without painting it.+ pub fn discard_staged_rasterization(&self, client: u64, token: u64) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.finish_staged_rasterization)(self.host(), client, token) };+ }++ /// Paints into the target of a staged rasterization through a painter, which `paint` drives, and drops what was+ /// staged. Answers whether the target was painted.+ pub fn rasterize_staged(&self, client: u64, token: u64, paint: impl FnOnce(&mut FfiRasterPainter)) -> bool {+ let mut painter = std::mem::MaybeUninit::<FfiRasterPainter>::uninit();+ // SAFETY: The host outlives this, and writes the painter where it answers true.+ let began = unsafe { (self.0.begin_staged_rasterization)(self.host(), client, token, painter.as_mut_ptr()) };+ if began {+ // SAFETY: The host wrote the painter.+ paint(unsafe { painter.assume_init_mut() });+ }+ // SAFETY: The host outlives this.+ unsafe { (self.0.finish_staged_rasterization)(self.host(), client, token) };+ began+ }}