Truly independent web browser
LibCompositing+LibWeb+Compositor: Keep display lists in Rust
Aliaksandr Kalenikf9bb7d7e6d89
diff --git a/Libraries/LibCompositing/CMakeLists.txt b/Libraries/LibCompositing/CMakeLists.txtindex 603e0015de4..703ce35e440 100644--- a/Libraries/LibCompositing/CMakeLists.txt+++ b/Libraries/LibCompositing/CMakeLists.txt@@ -9,7 +9,6 @@ set(SOURCESDisplayList/RustFFIAssertions.cppDisplayList/VisualContextTreeTestBuilder.cppFontServiceClient.cpp- Scrolling/RecordedDisplayListScrolling.cppScrolling/SmoothScrollAnimation.cppUIOverlays.cppVideo/VideoFrameHold.cpp@@ -103,7 +102,7 @@ if(NOT BUILD_SHARED_LIBS)# POST_BUILD steps don't track inputs, so the bridge files depend on the Rust archive: when it# changes, LibCompositing re-archives and the merge picks up the fresh objects.- foreach(bridge IN ITEMS DisplayList/DisplayList.cpp DisplayList/DisplayListResourceStorage.cpp DisplayList/VisualContextTreeTestBuilder.cpp Scrolling/RecordedDisplayListScrolling.cpp Scrolling/SmoothScrollAnimation.cpp)+ foreach(bridge IN ITEMS DisplayList/DisplayList.cpp DisplayList/DisplayListResourceStorage.cpp DisplayList/VisualContextTreeTestBuilder.cpp Scrolling/SmoothScrollAnimation.cpp)set_property(SOURCE ${bridge} APPEND PROPERTY OBJECT_DEPENDS ${_libcompositing_rust_lib})endforeach()endif()diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.cpp b/Libraries/LibCompositing/DisplayList/DisplayList.cppindex 130836ffc43..33e21ff1a02 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.cpp+++ b/Libraries/LibCompositing/DisplayList/DisplayList.cpp@@ -172,19 +172,6 @@ DisplayListProperties DisplayList::properties() const};}-RustFFI::FfiDisplayList DisplayList::for_scroll_logic(ReadonlyBytes encoded_async_scrolling_metadata) const-{- return {- .storage = m_storage,- .id = m_id,- .compatible_visual_context_tree_structural_epoch = m_compatible_visual_context_tree_structural_epoch,- .async_scrolling_metadata = encoded_async_scrolling_metadata,- .has_surface_clear_color = m_surface_clear_color.has_value(),- .surface_clear_color = m_surface_clear_color.value_or(Gfx::Color::Transparent),- .root_group_color = m_root_group_color,- };-}-}namespace IPC {diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.h b/Libraries/LibCompositing/DisplayList/DisplayList.hindex aabc53b9733..b0dee725648 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.h+++ b/Libraries/LibCompositing/DisplayList/DisplayList.h@@ -28,7 +28,6 @@ namespace Compositing {namespace RustFFI {-struct FfiDisplayList;struct FfiRasterPainter;}@@ -65,7 +64,6 @@ public:void const* rust_handle() const { return m_storage; }// The list as the scroll logic takes it, with the async scrolling metadata it goes with as IPC encodes an// Optional of it.- RustFFI::FfiDisplayList for_scroll_logic(ReadonlyBytes encoded_async_scrolling_metadata) const;// The sizes a receiver needs to unpack the list from its shared buffer.u64 tape_size() const;diff --git a/Libraries/LibCompositing/DisplayList/DisplayListProperties.h b/Libraries/LibCompositing/DisplayList/DisplayListProperties.hdeleted file mode 100644index 3ab7390c2eb..00000000000--- a/Libraries/LibCompositing/DisplayList/DisplayListProperties.h+++ /dev/null@@ -1,45 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Types.h>-#include <LibCompositing/Types.h>-#include <LibGfx/Color.h>-#include <LibGfx/Rect.h>--namespace Compositing {--// What a display list of a document's viewport is stamped with for async scrolling.-struct AsyncScrollingMetadata {- // The document whose viewport this is, which the compositor names when it pans the visual viewport of a page that- // has no scroll node.- Optional<Web::UniqueNodeID> document_id;- Gfx::IntRect viewport_rect;- u64 wheel_event_listener_state_generation { 0 };- bool has_blocking_wheel_event_listeners { false };- bool has_blocking_wheel_event_region_covering_viewport { false };- // Whether the viewport keeps the scrolls along an axis from the document it is nested in. A viewport with nothing to- // scroll has no scroll node to carry its overscroll-behavior.- bool viewport_keeps_horizontal_scrolls { false };- bool viewport_keeps_vertical_scrolls { false };- // Converts the compositor's device pixel offsets to the CSS pixels the snap geometry is in.- double device_pixels_per_css_pixel { 1.0 };- Compositing::KeyboardScrollState keyboard_scroll_state {};-};--// What travels alongside the tape of a display list for whatever plays the list.-struct DisplayListProperties {- u64 id { 0 };- u64 compatible_visual_context_tree_structural_epoch { 0 };- Optional<Gfx::Color> surface_clear_color;- Gfx::Color root_group_color { Gfx::Color::Transparent };-};--}--#include <LibCompositing/DisplayList/DisplayListPropertiesCodecs.h>diff --git a/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.cpp b/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.cppindex fc949ceb58c..8d0f5192186 100644--- a/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.cpp+++ b/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.cpp@@ -6,7 +6,6 @@#include <AK/Function.h>#include <AK/Math.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/RustFFI.h>#include <LibGfx/Bitmap.h>@@ -55,21 +54,6 @@ void DisplayListResourceSet::include(DisplayListResourceSet const& other)display_lists.set(id, AK::HashSetExistingEntryBehavior::Keep);}-DisplayListResource::DisplayListResource(NonnullRefPtr<DisplayList> display_list)- : display_list(move(display_list))-{-}--DisplayListResource::DisplayListResource(NonnullRefPtr<DisplayList const> display_list)- : display_list(move(display_list))-{-}--DisplayListResource::DisplayListResource(DisplayList const& display_list)- : display_list(display_list)-{-}-DisplayListResourceStorage::DisplayListResourceStorage() = default;DisplayListResourceStorage::DisplayListResourceStorage(DisplayListResourceStorage&&) = default;DisplayListResourceStorage& DisplayListResourceStorage::operator=(DisplayListResourceStorage&&) = default;@@ -146,14 +130,6 @@ VideoSinkResourceId DisplayListResourceStorage::add_video_sink(VideoSinkResourcereturn id;}-DisplayListResourceId DisplayListResourceStorage::add_display_list(DisplayListResource&& resource)-{- m_has_resources_added_since_last_retain = true;- auto id = resource.display_list->id();- m_display_lists.set(id, move(resource), AK::HashSetExistingEntryBehavior::Keep);- return { id };-}-void DisplayListResourceStorage::set_font(FontResourceId id, NonnullRefPtr<Gfx::Font const> font){m_has_resources_added_since_last_retain = true;@@ -181,79 +157,6 @@ Gfx::DecodedImageFrame const& DisplayListResourceStorage::image_frame(ImageFramereturn m_image_frames.get(id.value()).value()->frame;}-void DisplayListResourceStorage::collect_referenced_resources(- DisplayList const& display_list,- DisplayListResourceSet& referenced_resources) const-{- auto ids = display_list.referenced_resource_ids();- for (auto id : ids.fonts)- referenced_resources.fonts.set(FontResourceId { id }, AK::HashSetExistingEntryBehavior::Keep);- for (auto id : ids.image_frames)- referenced_resources.image_frames.set(ImageFrameResourceId { id }, AK::HashSetExistingEntryBehavior::Keep);- for (auto id : ids.video_sinks)- referenced_resources.video_sinks.set(VideoSinkResourceId { id }, AK::HashSetExistingEntryBehavior::Keep);- for (auto id : ids.display_lists)- add_referenced_display_list(DisplayListResourceId { id }, referenced_resources);-}--void DisplayListResourceStorage::add_referenced_display_list(DisplayListResourceId id, DisplayListResourceSet& referenced_resources) const-{- if (referenced_resources.display_lists.set(id, AK::HashSetExistingEntryBehavior::Keep) != HashSetResult::InsertedNewEntry)- return;- if (!has_display_list(id))- return;- collect_referenced_resources(display_list(id), referenced_resources);- collect_resources_referenced_by_visual_context_tree(display_list(id), referenced_resources);-}--void DisplayListResourceStorage::collect_resources_referenced_by_visual_context_tree(- DisplayList const& display_list,- DisplayListResourceSet& referenced_resources) const-{- display_list.for_each_visual_context_tree_filter_image_frame_id([&](u64 image_id) {- referenced_resources.image_frames.set(ImageFrameResourceId { image_id }, AK::HashSetExistingEntryBehavior::Keep);- });-}--DisplayListResourceSet DisplayListResourceStorage::collect_resources_referenced_by_visual_context_tree(DisplayList const& display_list) const-{- DisplayListResourceSet referenced_resources;- collect_resources_referenced_by_visual_context_tree(display_list, referenced_resources);- return referenced_resources;-}--DisplayListResourceSet DisplayListResourceStorage::collect_referenced_resources(DisplayList const& display_list) const-{- DisplayListResourceSet referenced_resources;- collect_referenced_resources(display_list, referenced_resources);- return referenced_resources;-}--static ErrorOr<void> validate_resources_are_present(DisplayListResourceStorage const& storage, DisplayListResourceSet const& resources)-{- for (auto id : resources.fonts) {- if (!storage.has_font(id))- return Error::from_string_literal("Display list refers to a font that is not present");- }- for (auto id : resources.image_frames) {- if (!storage.has_image_frame(id))- return Error::from_string_literal("Display list refers to an image frame that is not present");- }- for (auto id : resources.display_lists) {- if (!storage.has_display_list(id))- return Error::from_string_literal("Display list refers to a nested display list that is not present");- }- return {};-}--ErrorOr<DisplayListResourceTransaction> DisplayListResourceStorage::create_self_contained_transaction(DisplayList const& display_list) const-{- auto resources = collect_referenced_resources(display_list);- resources.include(collect_resources_referenced_by_visual_context_tree(display_list));- TRY(validate_resources_are_present(*this, resources));- return create_transaction({}, resources);-}-DisplayListResourceTransaction DisplayListResourceStorage::create_transaction(DisplayListResourceSet const& previous,DisplayListResourceSet const& current) const@@ -274,10 +177,6 @@ DisplayListResourceTransaction DisplayListResourceStorage::create_transaction(if (auto sink_handle = video_sink_handle(id); sink_handle.has_value())transaction.video_sinks.append({ id, *sink_handle });}- for (auto id : current.display_lists) {- if (!previous.display_lists.contains(id))- transaction.display_lists.append({ display_list_resource(id).display_list });- }for (auto id : previous.fonts) {if (!current.fonts.contains(id))@@ -311,8 +210,6 @@ DisplayListResourceSet DisplayListResourceStorage::apply_transaction(DisplayList}for (auto& video_sink : transaction.video_sinks)add_video_sink(video_sink.id, video_sink.sink_handle);- for (auto& display_list : transaction.display_lists)- add_display_list(move(display_list));for (auto id : transaction.font_ids_to_remove) {if (m_fonts.remove(id.value()))@@ -329,10 +226,6 @@ DisplayListResourceSet DisplayListResourceStorage::apply_transaction(DisplayListif (removed_handle || removed_sink)removed_resources.video_sinks.set(id);}- for (auto id : transaction.display_list_ids_to_remove) {- if (m_display_lists.remove(id.value()))- removed_resources.display_lists.set(id);- }return removed_resources;}@@ -360,12 +253,6 @@ DisplayListResourceSet DisplayListResourceStorage::retain_only(DisplayListResour};m_video_sink_handles.remove_all_matching([&](auto id, auto const&) { return remove_video_resource(id); });m_video_sinks.remove_all_matching([&](auto id, auto const&) { return remove_video_resource(id); });- m_display_lists.remove_all_matching([&](auto id, auto const&) {- if (resource_set.display_lists.contains(DisplayListResourceId { id }))- return false;- removed_resources.display_lists.set(DisplayListResourceId { id });- return true;- });m_has_resources_added_since_last_retain = false;return removed_resources;}diff --git a/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.h b/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.hindex 2eeb4cf20a8..e559407fe6d 100644--- a/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.h+++ b/Libraries/LibCompositing/DisplayList/DisplayListResourceStorage.h@@ -71,19 +71,10 @@ struct DisplayListStoredImageFrameResource;struct DisplayListStoredVideoSinkResource;// A display list recorded in this process, which goes with the visual context tree it was recorded against.-struct COMPOSITING_API DisplayListResource {- DisplayListResource(NonnullRefPtr<DisplayList>);- DisplayListResource(NonnullRefPtr<DisplayList const>);- DisplayListResource(DisplayList const&);-- NonnullRefPtr<DisplayList const> display_list;-};-struct DisplayListResourceTransaction {Vector<DisplayListFontResource> fonts;Vector<DisplayListImageFrameResource> image_frames;Vector<DisplayListVideoSinkResource> video_sinks;- Vector<DisplayListResource> display_lists;Vector<FontResourceId> font_ids_to_remove;Vector<ImageFrameResourceId> image_frame_ids_to_remove;@@ -103,20 +94,15 @@ public:FontResourceId add_font(Gfx::Font const&);ImageFrameResourceId add_image_frame(Gfx::DecodedImageFrame const&);VideoSinkResourceId add_video_sink(VideoSinkResourceId, Media::VideoSinkHandle);- DisplayListResourceId add_display_list(DisplayListResource&&);- bool has_display_list(DisplayListResourceId id) const { return m_display_lists.contains(id.value()); }void set_font(FontResourceId, NonnullRefPtr<Gfx::Font const>);// Returns the resources that the transaction removed or replaced, so whatever was made from them can be dropped.DisplayListResourceSet apply_transaction(DisplayListResourceTransaction&&);DisplayListResourceTransaction create_transaction(DisplayListResourceSet const& previous, DisplayListResourceSet const& current) const;// What the list's commands refer to, with what the display lists they nest, and the trees those were recorded// against, refer to.- DisplayListResourceSet collect_referenced_resources(DisplayList const&) const;// What the visual context tree a list recorded in this process was recorded against refers to.- DisplayListResourceSet collect_resources_referenced_by_visual_context_tree(DisplayList const&) const;// Carries everything a list recorded in this process and its tree refer to, for a receiver that holds none of it// yet.- ErrorOr<DisplayListResourceTransaction> create_self_contained_transaction(DisplayList const&) const;// Returns the resources that were removed.DisplayListResourceSet retain_only(DisplayListResourceSet const&);bool has_resources_added_since_last_retain() const { return m_has_resources_added_since_last_retain; }@@ -136,14 +122,9 @@ public:RefPtr<Media::DisplayingVideoSink const> video_sink(VideoSinkResourceId id) const;Optional<Media::VideoSinkHandle> video_sink_handle(VideoSinkResourceId id) const { return m_video_sink_handles.get(id.value()); }HashMap<u64, Media::VideoSinkHandle> const& video_sink_handles() const { return m_video_sink_handles; }- DisplayListResource const& display_list_resource(DisplayListResourceId id) const { return m_display_lists.get(id.value()).value(); }- DisplayList const& display_list(DisplayListResourceId id) const { return *display_list_resource(id).display_list; }private:void set_image_frame(ImageFrameResourceId, Gfx::DecodedImageFrame);- void collect_referenced_resources(DisplayList const&, DisplayListResourceSet&) const;- void collect_resources_referenced_by_visual_context_tree(DisplayList const&, DisplayListResourceSet&) const;- void add_referenced_display_list(DisplayListResourceId, DisplayListResourceSet&) const;bool m_has_resources_added_since_last_retain { false };HashMap<u64, NonnullRefPtr<Gfx::Font const>> m_fonts;@@ -152,7 +133,6 @@ private:u64 m_next_image_frame_pixel_generation { 1 };HashMap<u64, Media::VideoSinkHandle> m_video_sink_handles;HashMap<u64, NonnullOwnPtr<DisplayListStoredVideoSinkResource>> m_video_sinks;- HashMap<u64, DisplayListResource> m_display_lists;};}diff --git a/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cpp b/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cppindex de92264b909..1a02ec7714e 100644--- a/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cpp+++ b/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cpp@@ -5,7 +5,6 @@*/#include <AK/Math.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibGfx/Font/Font.h>#include <LibGfx/Font/Typeface.h>@@ -93,11 +92,8 @@ ErrorOr<void> encode(Encoder& encoder, Compositing::DisplayListResourceTransactiTRY(encoder.encode(transaction.fonts));TRY(encoder.encode(transaction.image_frames));TRY(encoder.encode(transaction.video_sinks));- TRY(encoder.encode_size(transaction.display_lists.size()));- for (auto const& display_list : transaction.display_lists) {- TRY(encoder.encode(*display_list.display_list));- TRY(encoder.encode(display_list.display_list->serialized_visual_context_tree()));- }+ // Only Rust sends nested display lists, which only the compositor's Rust receives.+ TRY(encoder.encode_size(0));TRY(encoder.encode(transaction.font_ids_to_remove));TRY(encoder.encode(transaction.image_frame_ids_to_remove));TRY(encoder.encode(transaction.video_sink_ids_to_remove));@@ -121,7 +117,6 @@ ErrorOr<Compositing::DisplayListResourceTransaction> decode(Decoder& decoder).fonts = move(fonts),.image_frames = move(image_frames),.video_sinks = move(video_sinks),- .display_lists = {},.font_ids_to_remove = TRY(decoder.decode<Vector<Compositing::FontResourceId>>()),.image_frame_ids_to_remove = TRY(decoder.decode<Vector<Compositing::ImageFrameResourceId>>()),.video_sink_ids_to_remove = TRY(decoder.decode<Vector<Compositing::VideoSinkResourceId>>()),diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex 2b65e09d8fb..1d5bc076a09 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -409,7 +409,6 @@ fn main() -> Result<(), Box<dyn Error>> {"FfiRasterPainter","RecordSpan","FfiReplaySelection",- "FfiDisplayList","FfiEasingDescriptor","FfiEasingKind","FfiLinearEasingPoint",diff --git a/Libraries/LibCompositing/Rust/src/display_list/ids.rs b/Libraries/LibCompositing/Rust/src/display_list/ids.rsnew file mode 100644index 00000000000..9097bd6a3b7--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/display_list/ids.rs@@ -0,0 +1,19 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The ids display lists go by, which the display lists that nest others name them with.++unsafe extern "C" {+ fn ladybird_gfx_process_next_display_list_id() -> u64;+}++/// A new display list id, unique in the process.+pub fn allocate_display_list_id() -> u64 {+ // The counter is LibGfx's: this crate is compiled into more than one library, and every copy names display lists+ // from the same counter. See `LibGfx/RustProcessState.cpp`.+ // SAFETY: The counter is an atomic on the other side of the boundary.+ unsafe { ladybird_gfx_process_next_display_list_id() }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/mod.rs b/Libraries/LibCompositing/Rust/src/display_list/mod.rsindex a8591a4f9e9..0009d3d3fff 100644--- a/Libraries/LibCompositing/Rust/src/display_list/mod.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/mod.rs@@ -14,6 +14,7 @@ pub mod device_pixels;pub mod effect_clip_plan;pub mod effect_geometry;pub mod ffi_bytes;+pub mod ids;pub mod layers;pub mod nested_records;pub mod replay;diff --git a/Libraries/LibCompositing/Rust/src/display_list/storage.rs b/Libraries/LibCompositing/Rust/src/display_list/storage.rsindex 9b18d88e174..87cb7c4d9a3 100644--- a/Libraries/LibCompositing/Rust/src/display_list/storage.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/storage.rs@@ -175,10 +175,19 @@ pub fn recorded_storage_handle(recorded: Arc<RecordedDisplayList>,visual_context_tree: Arc<VisualContextTree>,) -> *const c_void {- into_handle(DisplayListStorage::new(- Tape::Recorded(recorded),- Some(visual_context_tree),- ))+ into_handle(DisplayListStorage::recorded(recorded, visual_context_tree))+}++impl DisplayListStorage {+ /// A list this process recorded against `visual_context_tree`.+ pub fn recorded(recorded: Arc<RecordedDisplayList>, visual_context_tree: Arc<VisualContextTree>) -> Arc<Self> {+ Self::new(Tape::Recorded(recorded), Some(visual_context_tree))+ }++ /// An empty list, recorded against a tree with no node but the visual viewport.+ pub fn empty() -> Arc<Self> {+ Self::new(Tape::Empty, Some(Arc::new(VisualContextTree::create_identity())))+ }}/// An empty list, recorded against a tree with no node but the visual viewport.@@ -380,18 +389,28 @@ 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> {+ /// The size of the tape and run table packed for transport.+ pub fn packed_size(&self) -> usize {+ packed_size(self.bytes().len(), self.command_runs().len()).expect("a stored tape fits in memory")+ }++ /// Writes the tape and run table packed for transport to `destination`, which is `packed_size()` bytes long.+ pub fn write_packed(&self, destination: &mut [u8]) {let (tape, runs) = (self.bytes(), self.command_runs());- 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());+ assert_eq!(destination.len(), self.packed_size());+ let (tape_destination, runs_destination) = destination.split_at_mut(tape.len());tape_destination.copy_from_slice(tape);let (run_destinations, _) =runs_destination.as_chunks_mut::<{ std::mem::size_of::<DisplayListCommandRun>() }>();for (run, out) in runs.iter().zip(run_destinations) {write_run(run, out);}+ }++ /// The tape and run table packed for transport.+ pub fn packed(&self) -> Vec<u8> {+ let mut packed = vec![0; self.packed_size()];+ self.write_packed(&mut packed);packed}}diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rsindex 141d17e426f..75c2bd227f5 100644--- a/Libraries/LibCompositing/Rust/src/ffi.rs+++ b/Libraries/LibCompositing/Rust/src/ffi.rs@@ -14,8 +14,6 @@ use crate::scrolling::{};use crate::time::Duration;use libgfx_rust::FloatPoint;-use libipc_rust::DecodeError;-use libipc_rust::cpp_connection::EncodedValue;use std::ffi::c_void;use std::sync::Arc;@@ -205,117 +203,43 @@ pub extern "C" fn smooth_scroll_animation_retarget(animation.retarget(destination_offset, Duration::from_nanoseconds(elapsed_nanoseconds));}-/// A C++ display list as the scroll logic takes it: its tape, and what travels beside the tape that the logic reads.-#[repr(C)]-pub struct FfiDisplayList<'a> {- pub storage: *const c_void,- pub id: u64,- pub compatible_visual_context_tree_structural_epoch: u64,- /// A `Compositing::AsyncScrollingMetadata`, or none.- pub async_scrolling_metadata: EncodedValue<'a>,- pub has_surface_clear_color: bool,- pub surface_clear_color: libgfx_rust::Color,- pub root_group_color: libgfx_rust::Color,-}--impl FfiDisplayList<'_> {- /// # Safety- ///- /// `storage` must be a live display list storage handle.- pub unsafe fn share(&self) -> Result<DisplayList, DecodeError> {- let async_scrolling_metadata = self.async_scrolling_metadata.decode()?;- let storage = self.storage.cast::<crate::display_list::storage::DisplayListStorage>();- // SAFETY: The caller lends a strong reference to the storage, of which this takes one more.- let storage = unsafe {- Arc::increment_strong_count(storage);- Arc::from_raw(storage)- };- Ok(DisplayList::new(- storage,- self.id,- self.compatible_visual_context_tree_structural_epoch,- async_scrolling_metadata,- self.has_surface_clear_color.then_some(self.surface_clear_color),- self.root_group_color,- ))- }-}--const ENCODED_IN_THIS_PROCESS: &str = "a value this process encoded for itself decodes";--/// The list a document of this process recorded, which C++ lends, and the tree it was recorded against.-///-/// # Safety-///-/// The storage of `display_list` must be a live storage handle of a list this process recorded.-unsafe fn recorded_display_list_and_tree(- display_list: &FfiDisplayList<'_>,-) -> (DisplayList, AccumulatedVisualContextTree) {- // SAFETY: The caller lends a live storage handle.- let tree = unsafe { storage_from_handle(display_list.storage) }- .visual_context_tree()- .cloned()- .expect("a list this process recorded holds the tree it was recorded against");- // SAFETY: As above.- let display_list = unsafe { display_list.share() }.expect(ENCODED_IN_THIS_PROCESS);- (display_list, AccumulatedVisualContextTree::from_arc(tree))-}--/// The scrolling state of no display list is the empty one.-///-/// # Safety-///-/// The storage of `display_list` must be a live storage handle of a list this process recorded, where there is a-/// display list. `receive` must copy the UTF-8 bytes it keeps synchronously.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn recorded_display_list_async_scrolling_state_json(- display_list: Option<&FfiDisplayList<'_>>,- receiver: *mut c_void,- receive: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),-) {+/// The scrolling state of `display_list`, a list this process recorded, and the tree it was recorded against, as JSON,+/// or of no list, which is the empty one.+pub fn recorded_display_list_async_scrolling_state_json(+ display_list: Option<(&DisplayList, &Arc<crate::visual_context::VisualContextTree>)>,+) -> String {let state = match display_list {None => crate::scrolling::AsyncScrollingState::default(),- Some(display_list) => {- // SAFETY: The caller lends a live storage handle.- let (display_list, visual_context_tree) = unsafe { recorded_display_list_and_tree(display_list) };- crate::scrolling::async_scrolling_state_from(&display_list, visual_context_tree.as_arc())+ Some((display_list, visual_context_tree)) => {+ crate::scrolling::async_scrolling_state_from(display_list, visual_context_tree)}};- let json = crate::scrolling::async_scrolling_state_to_json(&state);- // SAFETY: The caller copies what it keeps of the JSON synchronously.- unsafe { receive(receiver, ak::Span::new(json.as_bytes())) };+ crate::scrolling::async_scrolling_state_to_json(&state)}-/// The scroll tree of the display list the document last recorded, as the compositor builds it once the list reaches-/// it.-///-/// # Safety-///-/// The storage of `display_list` must be a live storage handle of a list this process recorded.-unsafe fn recorded_scroll_tree_of(- display_list: &FfiDisplayList<'_>,- scroll_state_snapshot: EncodedValue<'_>,+/// The scroll tree of `display_list`, the list the document last recorded, with the tree it was recorded against, as+/// the compositor builds it once the list reaches it.+fn recorded_scroll_tree_of(+ display_list: &DisplayList,+ visual_context_tree: &Arc<crate::visual_context::VisualContextTree>,+ mut snapshot: crate::scrolling::ScrollStateSnapshot,newest_wheel_event_listener_state_generation: u64,) -> (crate::scrolling::AsyncScrollTree,AccumulatedVisualContextTree,crate::scrolling::WheelRoutingAdmission,) {- // SAFETY: The caller lends a live storage handle.- let (display_list, visual_context_tree) = unsafe { recorded_display_list_and_tree(display_list) };- let mut snapshot = scroll_state_snapshot- .decode::<crate::scrolling::ScrollStateSnapshot>()- .expect(ENCODED_IN_THIS_PROCESS);+ let visual_context_tree = AccumulatedVisualContextTree::from_arc(visual_context_tree.clone());snapshot.set_node_count(visual_context_tree.spatial_node_count());let async_scrolling_state =- crate::scrolling::async_scrolling_state_from(&display_list, visual_context_tree.as_arc());+ crate::scrolling::async_scrolling_state_from(display_list, visual_context_tree.as_arc());let admission = crate::scrolling::wheel_routing_admission_for_with_generation(&async_scrolling_state,newest_wheel_event_listener_state_generation,);let mut scroll_tree = crate::scrolling::AsyncScrollTree::default();scroll_tree.set_state(async_scrolling_state);- scroll_tree.rebuild_wheel_hit_test_targets(Some(&display_list), Some(&visual_context_tree), &snapshot);+ scroll_tree.rebuild_wheel_hit_test_targets(Some(display_list), Some(&visual_context_tree), &snapshot);(scroll_tree, visual_context_tree, admission)}@@ -331,25 +255,22 @@ pub struct FfiFirstWheelStepRouteForTesting {pub document_id: i64,}-/// # Safety-///-/// The storage of `display_list` must be a live storage handle of a list this process recorded.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn recorded_display_list_route_first_wheel_step(- display_list: &FfiDisplayList<'_>,- scroll_state_snapshot: EncodedValue<'_>,+/// Where the first step of a wheel gesture at `position` by `delta_in_css_pixels` goes through `display_list`, a list this+/// process recorded, and the tree it was recorded against, with the document scrolled as `snapshot` says.+pub fn recorded_display_list_route_first_wheel_step(+ display_list: &DisplayList,+ visual_context_tree: &Arc<crate::visual_context::VisualContextTree>,+ snapshot: crate::scrolling::ScrollStateSnapshot,newest_wheel_event_listener_state_generation: u64,position: FloatPoint,delta_in_css_pixels: FloatPoint,) -> FfiFirstWheelStepRouteForTesting {- // SAFETY: The caller lends live handles.- let (scroll_tree, visual_context_tree, admission) = unsafe {- recorded_scroll_tree_of(- display_list,- scroll_state_snapshot,- newest_wheel_event_listener_state_generation,- )- };+ let (scroll_tree, visual_context_tree, admission) = recorded_scroll_tree_of(+ display_list,+ visual_context_tree,+ snapshot,+ newest_wheel_event_listener_state_generation,+ );let delta = delta_in_css_pixels.scaled(scroll_tree.device_pixels_per_css_pixel() as f32);let first_step = scroll_tree.route_first_wheel_step(admission,@@ -372,17 +293,14 @@ pub unsafe extern "C" fn recorded_display_list_route_first_wheel_step(}}-/// # Safety-///-/// The storage of `display_list` must be a live storage handle of a list this process recorded.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn recorded_display_list_blocks_wheel_event_at(- display_list: &FfiDisplayList<'_>,- scroll_state_snapshot: EncodedValue<'_>,+/// Whether a box of `display_list`, a list this process recorded, blocks a wheel event at `position`, with the document+/// scrolled as `snapshot` says.+pub fn recorded_display_list_blocks_wheel_event_at(+ display_list: &DisplayList,+ visual_context_tree: &Arc<crate::visual_context::VisualContextTree>,+ snapshot: crate::scrolling::ScrollStateSnapshot,position: FloatPoint,) -> bool {- // SAFETY: The caller lends a live handle.- let (scroll_tree, visual_context_tree, _) =- unsafe { recorded_scroll_tree_of(display_list, scroll_state_snapshot, 0) };+ let (scroll_tree, visual_context_tree, _) = recorded_scroll_tree_of(display_list, visual_context_tree, snapshot, 0);scroll_tree.blocks_wheel_event_at_position(&visual_context_tree, position)}diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex a4898f4ebfd..9cce7b811c9 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -161,6 +161,18 @@ pub struct NestedDisplayListResource {pub tree: Arc<VisualContextTree>,}+impl NestedDisplayListResource {+ /// Encodes the list as a resource transaction carries it: what travels alongside its tape, the tape and run table,+ /// and its tree.+ pub fn encode_into(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.properties)?;+ encoder.encode_size(self.storage.bytes().len())?;+ encoder.encode_size(self.storage.command_runs().len())?;+ encoder.append_bytes(&self.storage.packed());+ encoder.encode(&self.tree.to_bytes())+ }+}+impl std::fmt::Debug for NestedDisplayListResource {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {formatter@@ -204,12 +216,7 @@ impl Encode for Compositing_DisplayListResourceTransaction {}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())?;+ display_list.encode_into(encoder)?;}encoder.encode(&self.font_ids_to_remove)?;encoder.encode(&self.image_frame_ids_to_remove)?;diff --git a/Libraries/LibCompositing/Rust/src/test_stubs.rs b/Libraries/LibCompositing/Rust/src/test_stubs.rsindex ce23df8d4d1..14db4764f07 100644--- a/Libraries/LibCompositing/Rust/src/test_stubs.rs+++ b/Libraries/LibCompositing/Rust/src/test_stubs.rs@@ -20,3 +20,8 @@ extern "C" fn ladybird_gfx_process_next_path_identity() -> u64 {extern "C" fn ladybird_gfx_process_next_structural_epoch() -> u64 {NEXT.fetch_add(1, Ordering::Relaxed)}++#[unsafe(no_mangle)]+extern "C" fn ladybird_gfx_process_next_display_list_id() -> u64 {+ NEXT.fetch_add(1, Ordering::Relaxed)+}diff --git a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cppdeleted file mode 100644index 438b342ec7c..00000000000--- a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp+++ /dev/null@@ -1,63 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/RustFFI.h>-#include <LibCompositing/Scrolling/RecordedDisplayListScrolling.h>-#include <LibIPC/Encoded.h>--namespace Compositing {--using EncodedAsyncScrollingMetadata = IPC::Encoded<Optional<AsyncScrollingMetadata>>;--static void receive_json(void* receiver, ReadonlyBytes bytes)-{- *static_cast<String*>(receiver) = MUST(String::from_utf8(bytes));-}--String async_scrolling_state_as_json(DisplayList const& display_list)-{- String json;- EncodedAsyncScrollingMetadata async_scrolling_metadata { display_list.async_scrolling_metadata() };- auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());- RustFFI::recorded_display_list_async_scrolling_state_json(&display_list_for_scroll_logic, &json, receive_json);- return json;-}--String empty_async_scrolling_state_as_json()-{- String json;- RustFFI::recorded_display_list_async_scrolling_state_json(nullptr, &json, receive_json);- return json;-}--FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_list(DisplayList const& display_list, ReadonlyBytes encoded_scroll_state, u64 newest_wheel_event_listener_state_generation, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels)-{- EncodedAsyncScrollingMetadata async_scrolling_metadata { display_list.async_scrolling_metadata() };- auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());- auto route = RustFFI::recorded_display_list_route_first_wheel_step(&display_list_for_scroll_logic, encoded_scroll_state, newest_wheel_event_listener_state_generation, position, delta_in_css_pixels);-- FirstWheelStepRouteForTesting result { .route = { route.decision }, .document_id = {} };- if (route.has_scroller) {- result.route.scroller = Web::AsyncScrollNodeStableID {- .node_id = Web::UniqueNodeID { route.scroller_node_id },- .kind = route.scroller_kind,- .pseudo_element_type = route.scroller_pseudo_element_type,- };- }- if (route.has_document_id)- result.document_id = Web::UniqueNodeID { route.document_id };- return result;-}--bool recorded_display_list_blocks_wheel_event_at(DisplayList const& display_list, ReadonlyBytes encoded_scroll_state, Gfx::FloatPoint position)-{- EncodedAsyncScrollingMetadata async_scrolling_metadata { display_list.async_scrolling_metadata() };- auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());- return RustFFI::recorded_display_list_blocks_wheel_event_at(&display_list_for_scroll_logic, encoded_scroll_state, position);-}--}diff --git a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.hdeleted file mode 100644index b1a4e12233a..00000000000--- a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h+++ /dev/null@@ -1,24 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/String.h>-#include <LibCompositing/Export.h>-#include <LibCompositing/Forward.h>-#include <LibCompositing/Types.h>-#include <LibGfx/Point.h>--namespace Compositing {--// The display lists are ones this process recorded, which go with the visual context trees they were recorded against.-COMPOSITING_API String async_scrolling_state_as_json(DisplayList const&);-COMPOSITING_API String empty_async_scrolling_state_as_json();-// The scroll state is the document's, as the scroll logic, which is Rust, encoded it.-COMPOSITING_API FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_list(DisplayList const&, ReadonlyBytes encoded_scroll_state, u64 newest_wheel_event_listener_state_generation, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels);-COMPOSITING_API bool recorded_display_list_blocks_wheel_event_at(DisplayList const&, ReadonlyBytes encoded_scroll_state, Gfx::FloatPoint position);--}diff --git a/Libraries/LibGfx/RustProcessState.cpp b/Libraries/LibGfx/RustProcessState.cppindex d9c6a884294..b7401a361d7 100644--- a/Libraries/LibGfx/RustProcessState.cpp+++ b/Libraries/LibGfx/RustProcessState.cpp@@ -30,6 +30,7 @@ namespace Gfx {extern "C" {u64 ladybird_gfx_process_next_path_identity();u64 ladybird_gfx_process_next_structural_epoch();+u64 ladybird_gfx_process_next_display_list_id();void ladybird_gfx_process_note_crate_copy(void const* marker);size_t ladybird_gfx_process_crate_copies_seen();void ladybird_gfx_process_note_wanted_pending_face(u64 face_id);@@ -45,6 +46,9 @@ Atomic<u64> s_next_path_identity { 1 };// context trees it builds with these.Atomic<u64> s_next_structural_epoch { 1 };+// LibCompositing's crate names display lists with these.+Atomic<u64> s_next_display_list_id { 1 };+// The marker of every copy of the crate that has reported itself. There are three at most:// LibGfx's, LibWeb's and LibCompositing's.Array<Atomic<FlatPtr>, 3> s_crate_copies;@@ -77,6 +81,11 @@ extern "C" u64 ladybird_gfx_process_next_structural_epoch()return s_next_structural_epoch.fetch_add(1, AK::memory_order_relaxed);}+extern "C" u64 ladybird_gfx_process_next_display_list_id()+{+ return s_next_display_list_id.fetch_add(1, AK::memory_order_relaxed);+}+extern "C" void ladybird_gfx_process_note_crate_copy(void const* marker){auto address = bit_cast<FlatPtr>(marker);diff --git a/Libraries/LibIPC/Rust/src/cpp_connection.rs b/Libraries/LibIPC/Rust/src/cpp_connection.rsindex e00adf89a5f..7ed7a793a77 100644--- a/Libraries/LibIPC/Rust/src/cpp_connection.rs+++ b/Libraries/LibIPC/Rust/src/cpp_connection.rs@@ -197,6 +197,11 @@ impl ThreadSafeMessagePoster {Ok(self.try_post_encoded(&bytes, attachments))}+ /// The `IPC::ThreadSafeMessagePoster` this holds a reference to, for C++ to post what it encodes through it.+ pub fn as_cpp_poster(&self) -> *mut c_void {+ self.0.poster_with_one_reference+ }+pub fn try_post_encoded(&self, bytes: &[u8], attachments: Vec<Attachment>) -> bool {let raw_attachments: Vec<RawAttachment> = attachments.into_iter().map(RawAttachment::from_attachment).collect();// SAFETY: This holds a reference to the poster, which copies the bytes and takes every attachment over.diff --git a/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cppindex e04673edb33..04185096bf0 100644--- a/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cpp+++ b/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cpp@@ -5,7 +5,6 @@*/#include "CursorStyleValue.h"-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibGfx/Bitmap.h>#include <LibWeb/CSS/Sizing.h>#include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h>@@ -77,8 +76,6 @@ Optional<Gfx::ImageCursor> CursorStyleValue::make_image_cursor(Layout::NodeWithSauto& bitmap = *m_cached_bitmap->bitmap();// Paint the cursor into a bitmap.- Compositing::DisplayListResourceStorage resource_storage;-// A cursor image is not embedded by any element, so it follows the page's own preference.Painting::ImagePaintRequest request {.document = document,@@ -87,15 +84,13 @@ Optional<Gfx::ImageCursor> CursorStyleValue::make_image_cursor(Layout::NodeWithS.color_scheme = current_color_scheme,.gradient_stop_color_resolution_style = ColorResolutionStyle::for_layout_node(layout_node),.accumulated_scale = { 1, 1 },- .resource_storage = resource_storage,};auto image_paint = decoded_image_data ? decoded_image_data->image_paint(request) : image.image_paint(request);bool painted = false;if (image_paint.has_value()) {- auto cursor_display_list = Painting::record_image_paint_display_list(*image_paint, request, document.page().client().device_pixels_per_css_pixel());// The compositor replaces every pixel of the bitmap.if (auto* compositor_host = document.page().client().compositor_host())- painted = compositor_host->rasterize_display_list(cursor_display_list, resource_storage, bitmap);+ painted = Painting::rasterize_image_paint(*compositor_host, *image_paint, request, document.page().client().device_pixels_per_css_pixel(), bitmap);}if (!painted) {// Clear whatever was in the bitmap before, and paint again on the next update.diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex ecaa4f95a1f..d2175498e4a 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -15,6 +15,7 @@#include <LibCore/Environment.h>#include <LibCore/EventLoop.h>#include <LibGfx/Bitmap.h>+#include <LibIPC/File.h>#include <LibIPC/Limits.h>#include <LibIPC/Transport.h>#include <LibIPC/TransportHandle.h>@@ -24,72 +25,20 @@#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/HTMLCanvasElement.h>#include <LibWeb/HTML/LocalNavigable.h>+#include <LibWeb/Layout/LayoutRustFFI.h>#include <LibWeb/Page/EventHandler.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/ImageCodecPlugin.h>-// The Paint stage presents frames, and only the connection hands it the sink it presents them through, and the+// The Paint stage presents frames, and only the connection hands it the poster it presents them through, and the// screenshots it asks for after them.extern "C" {-void paint_stage_adopt_frame_sink(void* sink);+void paint_stage_adopt_compositor_poster(IPC::FfiThreadSafeMessagePoster poster);void paint_stage_request_screenshot(void* request);}namespace Web::Compositor {-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;-}--// Posts frames straight to the connection's transport, which queues messages from any thread for its IO thread to send.-// The rest of the connection stays with the thread that made it.-class CompositorConnectionFrameSink final : public CompositorFrameSink {-public:- AK_ALLOC_WITH_KMALLOC;-- explicit CompositorConnectionFrameSink(IPC::Transport& transport)- : m_transport(&transport)- {- }-- // Called by the connection once the compositor is lost or the connection goes away.- void detach()- {- MutexLocker locker(m_mutex);- m_transport = nullptr;- }--private:- // Only for a test of the transport, which has no Paint thread.- friend class CompositorConnection;-- virtual bool submit(CompositorFrame&&) override;-- bool post(IPC::MessageBuffer&);- bool post_resource_additions_in_batches(Web::CompositorContextId, Compositing::DisplayListResourceTransaction&);- bool post_display_list_update(Web::CompositorContextId, CompositorFrame::DisplayListUpdate&);-- // Held while a frame is posted, so that frames submitted from different threads do not interleave.- Mutex m_mutex;- IPC::Transport* m_transport { nullptr };-};--bool CompositorConnectionFrameSink::post(IPC::MessageBuffer& buffer)-{- // A transport that failed to take a message is closed, and the connection learns of that on its own thread. Until- // then, drop the rest of this frame and every later one.- if (!m_transport->is_open() || buffer.transfer_message(*m_transport).is_error()) {- m_transport = nullptr;- return false;- }- return true;-}-void CompositorConnection::die(){did_lose_compositor();@@ -152,110 +101,48 @@ void CompositorConnection::destroy_context(Web::CompositorContextId context_id)static constexpr size_t max_resources_per_message = 100;static_assert(max_resources_per_message <= IPC::MAX_MESSAGE_FD_COUNT);-bool CompositorConnectionFrameSink::post_resource_additions_in_batches(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction& resource_transaction)-{- auto fonts = move(resource_transaction.fonts);- auto image_frames = move(resource_transaction.image_frames);+// Shared memory Rust writes a message into, which stays mapped until Rust releases it.+struct SharedBufferForRust {+ AK_ALLOC_WITH_KMALLOC;- // Moves up to `room` resources of one kind into `batch`, starting at `taken`, and returns how many it moved.- auto take = [](auto& resources, size_t& taken, size_t room, auto& batch) {- auto count = min(room, resources.size() - taken);- batch.ensure_capacity(count);- for (size_t i = 0; i < count; ++i)- batch.unchecked_append(move(resources[taken + i]));- taken += count;- return count;- };+ Core::AnonymousBuffer buffer;+};+// Posts `fonts` and `image_frames` for the context to hold, in batches, and answers whether the compositor could still be+// reached.+static bool post_fonts_and_image_frames_in_batches(IPC::ThreadSafeMessagePoster& poster, Web::CompositorContextId context_id, ReadonlySpan<Gfx::Font const*> fonts, ReadonlySpan<Gfx::DecodedImageFrame const*> image_frames)+{size_t fonts_taken = 0;size_t image_frames_taken = 0;while (fonts_taken < fonts.size() || image_frames_taken < image_frames.size()) {Compositing::DisplayListResourceTransaction batch;auto room = max_resources_per_message;- room -= take(fonts, fonts_taken, room, batch.fonts);- room -= take(image_frames, image_frames_taken, room, batch.image_frames);+ while (room > 0 && fonts_taken < fonts.size()) {+ auto const& font = *fonts[fonts_taken++];+ batch.fonts.append({ Compositing::FontResourceId { font.id() }, font });+ --room;+ }+ while (room > 0 && image_frames_taken < image_frames.size()) {+ auto const& frame = *image_frames[image_frames_taken++];+ batch.image_frames.append({ Compositing::ImageFrameResourceId { frame.id() }, frame });+ --room;+ }auto encoded_batch = MUST(Messages::CompositorWebContentServer::UpdateDisplayListResources::static_encode(context_id, batch));- if (!post(encoded_batch))- return false;- }- return true;-}--// Returns false once the compositor is lost. A display list that cannot be placed in shared memory is-// skipped, and the rest of the frame still goes over.-bool CompositorConnectionFrameSink::post_display_list_update(Web::CompositorContextId context_id, CompositorFrame::DisplayListUpdate& update)-{- if (!post_resource_additions_in_batches(context_id, update.resource_transaction))- return false;-- // The tape and run table go over in a fresh shared buffer that the Compositor takes ownership of;- // this process keeps no mapping once the message is posted.- auto& display_list = *update.display_list;- auto timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);- auto shared_tape_buffer = display_list.copy_to_shared_buffer();- if (shared_tape_buffer.is_error()) {- dbgln("WebContent: Could not place a {} byte display list in shared memory: {}", display_list.tape_size(), shared_tape_buffer.error());- return true;- }- 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(), 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())- dbgln("DISPLAY_LIST_PUBLISH bytes={} copy={} µs encode+post={} µs", display_list.tape_size(), copy_time.to_microseconds(), (timer.elapsed_time() - copy_time).to_microseconds());- return true;-}--bool CompositorConnectionFrameSink::submit(CompositorFrame&& frame)-{- MutexLocker locker(m_mutex);- if (!m_transport)- return false;-- auto context_id = frame.context_id;- if (auto& update = frame.display_list_update; update.has_value()) {- if (!post_display_list_update(context_id, *update))- return false;- }- 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, update->keyboard_scroll_state));- if (!post(encoded_message))- return false;- }- if (auto& update = frame.scroll_state_update; update.has_value()) {- auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateScrollState::static_encode(context_id, update->encoded_scroll_state, update->keyboard_scroll_state));- if (!post(encoded_message))- return false;- }- if (!frame.scroll_requests.is_empty()) {- auto encoded_message = MUST(Messages::CompositorWebContentServer::ApplyScrollRequests::static_encode(context_id, frame.scroll_requests));- if (!post(encoded_message))- return false;- }- if (frame.present_viewport_rect.has_value()) {- auto encoded_message = MUST(Messages::CompositorWebContentServer::PresentFrame::static_encode(context_id, *frame.present_viewport_rect));- if (!post(encoded_message))+ if (!poster.try_post(encoded_batch))return false;}- if (auto& request = frame.screenshot_request; request.has_value()) {- auto encoded_message = MUST(Messages::CompositorWebContentServer::RequestScreenshot::static_encode(context_id, request->id, request->target));- return post(encoded_message);- }return true;}CompositorConnection::CompositorConnection(NonnullOwnPtr<IPC::Transport> transport): IPC::ConnectionToServer<CompositorWebContentClientEndpoint, CompositorWebContentServerEndpoint>(*this, move(transport))- , m_frame_sink(adopt_ref(*new CompositorConnectionFrameSink(this->transport())))+ , m_poster(IPC::ThreadSafeMessagePoster::create(this->transport())){}CompositorConnection::~CompositorConnection(){- m_frame_sink->detach();+ m_poster->detach_from_transport();}// A screenshot of what the compositor composes for a context, on its way to the Paint thread, which asks for it after@@ -264,22 +151,13 @@ struct ScreenshotRequestForPaintThread {AK_ALLOC_WITH_KMALLOC;Web::CompositorContextId context_id;- CompositorFrame::ScreenshotRequest request;-};--// What the Paint thread presents frames through. Only the Paint stage calls these, which holds the sink.-struct FrameSinkFFI {- static void submit(CompositorFrameSink& sink, CompositorFrame&& frame)- {- // A sink whose compositor is lost drops the frame, and the connection learns of that on its own thread.- (void)sink.submit(move(frame));- }+ Compositing::ScreenshotRequestId request_id;+ Gfx::ShareableBitmap target;};-void CompositorConnection::hand_frame_sink_to_paint_thread()+void CompositorConnection::hand_poster_to_paint_thread(){- NonnullRefPtr<CompositorFrameSink> sink = m_frame_sink;- paint_stage_adopt_frame_sink(&sink.leak_ref());+ paint_stage_adopt_compositor_poster(m_poster->to_ffi_with_one_reference());}// Gives the compositor a connection of its own to this process's image decoder, so that an animated image keeps getting@@ -498,34 +376,30 @@ Web::Compositor::PlaceholderCanvasPixels CompositorConnection::get_placeholder_creturn { pixels.is_valid() ? pixels.bitmap() : nullptr, response->origin_clean() };}-bool CompositorConnection::rasterize_display_list(Compositing::DisplayList const& display_list, Compositing::DisplayListResourceTransaction resource_transaction, NonnullRefPtr<Gfx::Bitmap> target)+bool CompositorConnection::rasterize_image(Layout::RustFFI::FfiImageRasterization const& image, NonnullRefPtr<Gfx::Bitmap> target){if (!can_send_message_to_compositor())return false;// The compositor draws straight into the target, so it has to be memory both processes can map.VERIFY(target->anonymous_buffer().is_valid());- auto shared_tape_buffer = display_list.copy_to_shared_buffer();- if (shared_tape_buffer.is_error()) {- dbgln("WebContent: Could not place a {} byte display list to rasterize in shared memory: {}", display_list.tape_size(), shared_tape_buffer.error());+ auto token = m_next_rasterization_token++;+ if (!Layout::RustFFI::render_state_rasterize_image(m_poster->to_ffi_with_one_reference(), token, &image, target.ptr()))return false;+ while (true) {+ auto answer = wait_for_specific_endpoint_message<Messages::CompositorWebContentClient::DidRasterizeDisplayList>();+ if (!answer) {+ did_lose_compositor();+ return false;+ }+ if (answer->token() == token)+ return answer->success();}- // 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(),- display_list.serialized_visual_context_tree(),- move(resource_transaction));- return response && response->success();+}++void CompositorConnection::did_rasterize_display_list(u64, bool)+{+ // CompositorConnection::rasterize_image() waits for its answer, and an answer it gave up on goes nowhere.}void CompositorConnection::invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation)@@ -892,7 +766,7 @@ void CompositorConnection::request_screenshot(Web::CompositorContextId context_iauto request_id = Compositing::ScreenshotRequestId { m_next_screenshot_request_id++ };m_screenshots.set(request_id, PendingScreenshot { move(target_bitmap), move(callback) });// The screenshot is of what the compositor composes, so it goes after the frames handed to the Paint thread before.- paint_stage_request_screenshot(new ScreenshotRequestForPaintThread { context_id, { request_id, move(shareable_bitmap) } });+ paint_stage_request_screenshot(new ScreenshotRequestForPaintThread { context_id, request_id, move(shareable_bitmap) });}void CompositorConnection::key_event(u64 page_id, Web::KeyEvent event)@@ -1031,7 +905,7 @@ void CompositorConnection::did_lose_compositor()if (m_has_lost_compositor)return;m_has_lost_compositor = true;- m_frame_sink->detach();+ m_poster->detach_from_transport();for (auto& entry : m_screenshots) {if (entry.value.callback)@@ -1059,25 +933,72 @@ Optional<CompositorConnection::PendingScreenshot> CompositorConnection::take_scr}-extern "C" WEB_API void web_frame_sink_release(void* sink);-extern "C" WEB_API void web_frame_sink_request_screenshot(void* sink, void* request);+extern "C" WEB_API bool web_compositor_post_fonts_and_image_frames(void* poster, u64 context_id, void const* const* fonts, size_t font_count, void const* const* image_frames, size_t image_frame_count);+extern "C" WEB_API bool web_compositor_create_shared_buffer(size_t size, Web::Compositor::FfiSharedBuffer* out);+extern "C" WEB_API void web_compositor_shared_buffer_release(void* owner);+extern "C" WEB_API bool web_compositor_post_screenshot_request(void* poster, void* request);extern "C" WEB_API void web_screenshot_request_destroy(void* request);+extern "C" WEB_API bool web_compositor_stage_rasterization(void* poster, u64 token, void const* const* fonts, size_t font_count, void const* const* image_frames, size_t image_frame_count, u64 const* video_sinks, size_t video_sink_count, void const* target_bitmap);++extern "C" WEB_API bool web_compositor_post_fonts_and_image_frames(void* poster, u64 context_id, void const* const* fonts, size_t font_count, void const* const* image_frames, size_t image_frame_count)+{+ return Web::Compositor::post_fonts_and_image_frames_in_batches(+ *static_cast<IPC::ThreadSafeMessagePoster*>(poster),+ Web::CompositorContextId { context_id },+ { reinterpret_cast<Gfx::Font const* const*>(fonts), font_count },+ { reinterpret_cast<Gfx::DecodedImageFrame const* const*>(image_frames), image_frame_count });+}++extern "C" WEB_API bool web_compositor_create_shared_buffer(size_t size, Web::Compositor::FfiSharedBuffer* out)+{+ // Sealed where the platform supports it, so the receiver cannot be faulted by the file shrinking.+ auto buffer = Core::AnonymousBuffer::create_with_size(size);+ if (buffer.is_error())+ return false;+ auto descriptor = IPC::File::clone_fd(buffer.value().fd());+ if (descriptor.is_error())+ return false;+ auto owner = make<Web::Compositor::SharedBufferForRust>(buffer.release_value());+ *out = {+ .data = owner->buffer.data<u8>(),+ .size = owner->buffer.size(),+ .descriptor = descriptor.value().take_fd(),+ .owner = owner.leak_ptr(),+ };+ return true;+}-extern "C" WEB_API void web_frame_sink_release(void* sink)+extern "C" WEB_API void web_compositor_shared_buffer_release(void* owner){- static_cast<Web::Compositor::CompositorFrameSink*>(sink)->unref();+ delete static_cast<Web::Compositor::SharedBufferForRust*>(owner);}-extern "C" WEB_API void web_frame_sink_request_screenshot(void* sink, void* request_pointer)+extern "C" WEB_API bool web_compositor_post_screenshot_request(void* poster, void* request_pointer){auto request = adopt_own(*static_cast<Web::Compositor::ScreenshotRequestForPaintThread*>(request_pointer));- Web::Compositor::CompositorFrame frame;- frame.context_id = request->context_id;- frame.screenshot_request = move(request->request);- Web::Compositor::FrameSinkFFI::submit(*static_cast<Web::Compositor::CompositorFrameSink*>(sink), move(frame));+ auto encoded_message = MUST(Messages::CompositorWebContentServer::RequestScreenshot::static_encode(request->context_id, request->request_id, request->target));+ return static_cast<IPC::ThreadSafeMessagePoster*>(poster)->try_post(encoded_message);}extern "C" WEB_API void web_screenshot_request_destroy(void* request){delete static_cast<Web::Compositor::ScreenshotRequestForPaintThread*>(request);}++extern "C" WEB_API bool web_compositor_stage_rasterization(void* poster, u64 token, void const* const* fonts, size_t font_count, void const* const* image_frames, size_t image_frame_count, u64 const* video_sinks, size_t video_sink_count, void const* target_bitmap)+{+ Compositing::DisplayListResourceTransaction staged_resources;+ for (size_t i = 0; i < font_count; ++i) {+ auto const& font = *static_cast<Gfx::Font const*>(fonts[i]);+ staged_resources.fonts.append({ Compositing::FontResourceId { font.id() }, font });+ }+ for (size_t i = 0; i < image_frame_count; ++i) {+ auto const& frame = *static_cast<Gfx::DecodedImageFrame const*>(image_frames[i]);+ staged_resources.image_frames.append({ Compositing::ImageFrameResourceId { frame.id() }, frame });+ }+ for (size_t i = 0; i < video_sink_count; ++i)+ staged_resources.video_sinks.append({ Compositing::VideoSinkResourceId { video_sinks[2 * i] }, Media::VideoSinkHandle { video_sinks[2 * i + 1] } });+ auto& target = const_cast<Gfx::Bitmap&>(*static_cast<Gfx::Bitmap const*>(target_bitmap));+ auto encoded_message = MUST(Messages::CompositorWebContentServer::StageRasterization::static_encode(token, staged_resources, Gfx::ShareableBitmap { target, Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap }));+ return static_cast<IPC::ThreadSafeMessagePoster*>(poster)->try_post(encoded_message);+}diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex be8111e00e6..08623eedb0c 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -14,7 +14,6 @@#include <Compositor/CompositorWebContentClientEndpoint.h>#include <Compositor/CompositorWebContentServerEndpoint.h>#include <LibCompositing/DisplayList/Canvas2DCommandStream.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/Types.h>#include <LibCompositing/WebGL/Types.h>@@ -24,16 +23,29 @@#include <LibGfx/ShareableBitmap.h>#include <LibGfx/Size.h>#include <LibIPC/ConnectionToServer.h>+#include <LibIPC/ThreadSafeMessagePoster.h>#include <LibMedia/Forward.h>-#include <LibWeb/Compositor/CompositorFrame.h>#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/Export.h>#include <LibWebCommon/Page/InputEvent.h>#include <LibWebCommon/Page/PageId.h>+namespace Web::Layout::RustFFI {++struct FfiImageRasterization;++}+namespace Web::Compositor {-class CompositorConnectionFrameSink;+// Shared memory made for a message that Rust writes and posts.+struct FfiSharedBuffer {+ u8* data;+ size_t size;+ // A descriptor of the memory of its own, which the caller takes over.+ int descriptor;+ void* owner;+};class WEB_API CompositorConnection final: public IPC::ConnectionToServer<CompositorWebContentClientEndpoint, CompositorWebContentServerEndpoint>@@ -48,7 +60,7 @@ public:void stop_presenting_to_client(Web::CompositorContextId);void destroy_context(Web::CompositorContextId);// Has the Paint thread present frames through this connection from now on.- void hand_frame_sink_to_paint_thread();+ void hand_poster_to_paint_thread();void add_animated_image(u64 frame_id, AnimatedImageRegistration const&);void remove_animated_image(u64 frame_id);void start_animated_image(u64 frame_id);@@ -66,7 +78,8 @@ public:void release_placeholder_canvas(Compositing::CanvasId);void commit_placeholder_canvas(Web::Compositor::PlaceholderCanvasLink, Optional<Compositing::CanvasId> source_canvas_id, Gfx::IntSize, bool origin_clean);Web::Compositor::PlaceholderCanvasPixels get_placeholder_canvas_pixels(Compositing::CanvasId, Gfx::IntRect);- bool rasterize_display_list(Compositing::DisplayList const&, Compositing::DisplayListResourceTransaction, NonnullRefPtr<Gfx::Bitmap> target);+ // Has the compositor rasterize `image` into `target`, and waits for it to.+ bool rasterize_image(Layout::RustFFI::FfiImageRasterization const&, NonnullRefPtr<Gfx::Bitmap> target);void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation);void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);Compositing::WheelEventAnswer take_wheel_event_from_main_thread(Web::CompositorContextId, Web::MouseEvent const&, Compositing::AsyncScrollOperationTracking, Compositing::WheelEventRouting);@@ -126,6 +139,7 @@ private:virtual void rendering_opportunity(Web::CompositorContextId, i64 frame_time_nanoseconds, double frame_interval_milliseconds) override;virtual void async_scroll_updates(Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates) override;virtual void animated_content_moved_under_pointer(Web::CompositorContextId, i64 frame_time_nanoseconds) override;+ virtual void did_rasterize_display_list(u64 token, bool success) override;virtual void did_complete_screenshot(Compositing::ScreenshotRequestId) override;virtual void did_fail_screenshot(Compositing::ScreenshotRequestId) override;virtual void paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId>) override;@@ -138,7 +152,8 @@ private:void merge_async_scroll_updates(Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates);Optional<PendingScreenshot> take_screenshot(Compositing::ScreenshotRequestId);- NonnullRefPtr<CompositorConnectionFrameSink> m_frame_sink;+ // Posts to the transport from any thread: the Paint thread presents through it, and Rust posts what it encodes.+ NonnullRefPtr<IPC::ThreadSafeMessagePoster> m_poster;u64 m_next_reserved_canvas_id { 0 };u64 m_reserved_canvas_ids_remaining { 0 };// The compositor holds exactly the fonts of the latest canvas 2D stream batch.diff --git a/Libraries/LibWeb/Compositor/CompositorFrame.h b/Libraries/LibWeb/Compositor/CompositorFrame.hdeleted file mode 100644index fee6604e7d8..00000000000--- a/Libraries/LibWeb/Compositor/CompositorFrame.h+++ /dev/null@@ -1,90 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/AtomicRefCounted.h>-#include <AK/ByteBuffer.h>-#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Types.h>-#include <LibGfx/Rect.h>-#include <LibGfx/ShareableBitmap.h>-#include <LibWeb/Export.h>-#include <LibWebCommon/Page/CompositorContextId.h>--namespace Web::Compositor {--// What a navigable hands its compositor context for one frame. The frame owns everything its messages carry, so it-// can be handed to the compositor from any thread. Only the scroll logic of the compositor, which is Rust, decodes the-// scroll state.-struct CompositorFrame {- AK_ALLOC_WITH_KMALLOC;-- // A newly recorded display list, with the visual context tree, serialized, resources and scroll state it paints- // with.- struct DisplayListUpdate {- NonnullRefPtr<Compositing::DisplayList> display_list;- ByteBuffer visual_context_tree;- Compositing::DisplayListResourceTransaction resource_transaction;- ByteBuffer encoded_scroll_state;- };-- // A new visual context tree, serialized, for the installed display list, with its resources, scroll snapshot and- // keyboard scroll state.- struct VisualContextTreeUpdate {- ByteBuffer visual_context_tree;- Compositing::DisplayListResourceTransaction resource_transaction;- ByteBuffer encoded_scroll_state;- Compositing::KeyboardScrollState keyboard_scroll_state;- };-- // Updated scroll offsets and keyboard scroll state for the installed display list and visual context tree.- struct ScrollStateUpdate {- ByteBuffer encoded_scroll_state;- Compositing::KeyboardScrollState keyboard_scroll_state;- };-- // The context the frame is for, which the context handle submitting it stamps.- Web::CompositorContextId context_id;- Optional<DisplayListUpdate> display_list_update;- Optional<VisualContextTreeUpdate> visual_context_tree_update;- Optional<ScrollStateUpdate> scroll_state_update;- // The scrolls the main thread asked for, which go after the frame's boxes.- Vector<Compositing::ScrollRequest> scroll_requests;- // Set when the frame is presented once the compositor has applied it.- Optional<Gfx::IntRect> present_viewport_rect;-- // A screenshot the compositor takes of the context once it has applied the frame, and of every frame before it.- struct ScreenshotRequest {- Compositing::ScreenshotRequestId id;- Gfx::ShareableBitmap target;- };- Optional<ScreenshotRequest> screenshot_request;-};--struct FrameSinkFFI;-struct PresenterFFI;--// Hands finished frames to the compositor. Unlike the rest of a compositor connection, which belongs to the thread that-// made it, a frame sink takes frames from any thread. The messages of one frame reach the compositor together, and-// frames reach it in the order they were submitted. Only what presents frames submits them.-class WEB_API CompositorFrameSink : public AtomicRefCounted<CompositorFrameSink> {-public:- virtual ~CompositorFrameSink() = default;--private:- // Only the Paint thread presents, through these.- friend struct FrameSinkFFI;- friend struct PresenterFFI;-- // Returns false once the compositor can no longer be reached.- virtual bool submit(CompositorFrame&&) = 0;-};--}diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex 2073bf3cf76..19581170f6b 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -7,12 +7,9 @@#include <AK/NonnullOwnPtr.h>#include <AK/Optional.h>#include <LibCompositing/DisplayList/Canvas2DCommandStream.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibMediaCodecs/VideoFrame.h>#include <LibWeb/Compositor/CompositorConnection.h>-#include <LibWeb/Compositor/CompositorFrame.h>#include <LibWeb/Compositor/CompositorHost.h>-#include <LibWeb/Compositor/NavigablePresenter.h>#include <LibWeb/Compositor/RenderClock.h>#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>#include <LibWeb/WebGL/RemoteWebGLTransport.h>@@ -403,17 +400,12 @@ void CompositorHost::send_canvas_2d_stream(Compositing::Canvas2DCommandStream& sconnection->update_canvas_2d_stream(stream);}-bool CompositorHost::rasterize_display_list(Compositing::DisplayListResource const& display_list, Compositing::DisplayListResourceStorage const& resource_storage, NonnullRefPtr<Gfx::Bitmap> target) const+bool CompositorHost::rasterize_image(Layout::RustFFI::FfiImageRasterization const& image, NonnullRefPtr<Gfx::Bitmap> target) const{auto* connection = compositor_connection();if (!connection)return false;- auto resource_transaction = resource_storage.create_self_contained_transaction(*display_list.display_list);- if (resource_transaction.is_error()) {- dbgln("WebContent: Not rasterizing a display list: {}", resource_transaction.error());- return false;- }- return connection->rasterize_display_list(*display_list.display_list, resource_transaction.release_value(), move(target));+ return connection->rasterize_image(image, move(target));}void CompositorHost::destroy_context(Web::CompositorContextId context_id)diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.hindex fbb22fd5b32..62ac3f93b01 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.h+++ b/Libraries/LibWeb/Compositor/CompositorHost.h@@ -29,12 +29,15 @@#include <LibWeb/Forward.h>#include <LibWebCommon/Page/InputTrace.h>+namespace Web::Layout::RustFFI {++struct FfiImageRasterization;++}+namespace Web::Compositor {-class CompositorFrameSink;class CompositorHost;-class NavigablePresenter;-struct CompositorFrame;// Whether the compositor took a requested screenshot, so painted the bitmap the request handed it.enum class ScreenshotResult : u8 {@@ -137,9 +140,9 @@ public:void commit_placeholder_canvas(PlaceholderCanvasLink, Optional<Compositing::CanvasId> source_canvas_id, Gfx::IntSize, bool origin_clean);PlaceholderCanvasPixels read_placeholder_canvas_pixels(Compositing::CanvasId, Gfx::IntRect);- // Has the compositor draw a display list that belongs to no compositor context into the target, which must be a- // shareable BGRA8888 bitmap with premultiplied alpha. Returns false if nothing was drawn.- bool rasterize_display_list(Compositing::DisplayListResource const&, Compositing::DisplayListResourceStorage const&, NonnullRefPtr<Gfx::Bitmap> target) const;+ // Has the compositor draw an image into the target, which must be a shareable BGRA8888 bitmap with premultiplied+ // alpha. Returns false if nothing was drawn.+ bool rasterize_image(Layout::RustFFI::FfiImageRasterization const&, NonnullRefPtr<Gfx::Bitmap> target) const;void destroy_context(Web::CompositorContextId);void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>);diff --git a/Libraries/LibWeb/Compositor/NavigablePresenter.cpp b/Libraries/LibWeb/Compositor/NavigablePresenter.cppindex 890f781f3a0..7579d5ff9ce 100644--- a/Libraries/LibWeb/Compositor/NavigablePresenter.cpp+++ b/Libraries/LibWeb/Compositor/NavigablePresenter.cpp@@ -4,285 +4,123 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGfx/Font/Font.h>+#include <LibIPC/Encoder.h>+#include <LibIPC/Message.h>#include <LibWeb/Compositor/NavigablePresenter.h>#include <LibWeb/Layout/LayoutRustFFI.h>-#include <LibWeb/Painting/PaintingRustBridge.h>namespace Web::Compositor {-// What the Paint thread presents a frame through. Only Rust calls it, from a job that presents.-struct PresenterFFI {- // A clock lane's frame that starts from an older frame than the last one a rendering update committed shows what the- // screen no longer shows: it is not presented, and the compositor hears nothing of it.- static bool is_stale(NavigablePresenter const& presenter, SealedPresentation const& sealed)- {- return sealed.presented_by == PresentedBy::Clock && sealed.generation < presenter.m_last_committed_generation;- }-- static void note_presented(NavigablePresenter& presenter, SealedPresentation& sealed, ReadonlyBytes encoded_scroll_state)- {- sealed.presented_other_scroll_offsets = presenter.m_last_presented_encoded_scroll_state.bytes() != encoded_scroll_state;- if (sealed.presented_other_scroll_offsets)- presenter.m_last_presented_encoded_scroll_state = MUST(ByteBuffer::copy(encoded_scroll_state));- if (sealed.presented_by == PresentedBy::Commit) {- presenter.m_last_committed_generation = max(presenter.m_last_committed_generation, sealed.generation);- presenter.m_committed_command_resources = presenter.m_compositor_display_list_command_resources;- }- if (sealed.published.has_value())- sealed.published->referenced_resources = presenter.m_compositor_display_list_command_resources;- }-- static void present(NavigablePresenter& presenter, SealedPresentation& sealed, NonnullRefPtr<Compositing::DisplayList> display_list, Layout::RustFFI::FfiPresentedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state, CompositorFrameSink* sink)- {- MutexLocker locker(presenter.m_mutex);- if (is_stale(presenter, sealed))- return;- auto frame = presenter.build_frame_beside_event_loop(sealed, move(display_list), visual_context_tree, encoded_scroll_state);- frame.scroll_requests = move(sealed.scroll_requests);- note_presented(presenter, sealed, encoded_scroll_state);- if (sink)- sink->submit(move(frame));- }-- static void present_unrecorded(NavigablePresenter& presenter, SealedPresentation& sealed, Layout::RustFFI::FfiPresentedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state, CompositorFrameSink* sink)- {- MutexLocker locker(presenter.m_mutex);- if (is_stale(presenter, sealed))- return;- auto frame = presenter.build_frame(sealed, {}, visual_context_tree, encoded_scroll_state);- frame.scroll_requests = move(sealed.scroll_requests);- note_presented(presenter, sealed, encoded_scroll_state);- if (sink)- sink->submit(move(frame));- }-};--void NavigablePresenter::forget_compositor_display_list()+NavigablePresenter::NavigablePresenter()+ : m_presenter(Layout::RustFFI::navigable_presenter_create()){- MutexLocker locker(m_mutex);- m_compositor_display_list_paint_config.clear();- m_compositor_display_list = nullptr;- m_compositor_display_list_resources = {};- m_compositor_display_list_command_resources = {};}-CompositorFrame NavigablePresenter::build_frame(SealedPresentation const& sealed, Optional<PublishedDisplayList> published, Layout::RustFFI::FfiPresentedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state)+NavigablePresenter::~NavigablePresenter(){- // A recording downgraded to cache-read-only leaves the retained source and the cached ranges into it live, so the- // resources they reference must survive the pruning that follows. A recording that replaced the source references- // everything the new source does.- auto resources_with = [&](Compositing::DisplayListResourceSet resources) {- if (!published.has_value() || !published->replaces_paint_command_cache_source)- resources.include(sealed.paint_command_cache_source_resources);- // The next frame a rendering update commits copies paint commands from the one it committed last, whatever a- // clock lane presented since.- if (sealed.presented_by == PresentedBy::Clock)- resources.include(m_committed_command_resources);- for (auto image_frame_id : ReadonlySpan<u64> { visual_context_tree.filter_image_frame_ids, visual_context_tree.filter_image_frame_id_count })- resources.image_frames.set(Compositing::ImageFrameResourceId { image_frame_id }, AK::HashSetExistingEntryBehavior::Keep);- return resources;- };- auto serialized_visual_context_tree = [&] {- VERIFY(visual_context_tree.tree);- ByteBuffer bytes;- Layout::RustFFI::presented_visual_context_tree_serialize(&visual_context_tree, &bytes, [](void* sink, u8 const* data, size_t size) {- MUST(static_cast<ByteBuffer*>(sink)->try_append(data, size));- });- return bytes;- };-- // Keyboard eligibility belongs to this publication, not to the cached paint commands. Refresh it even if recording- // was skipped or returned the same display list, and send it with the corresponding scroll state.- auto& display_list = published.has_value() ? *published->display_list : *m_compositor_display_list;- Compositing::KeyboardScrollState keyboard_scroll_state;- if (sealed.keyboard_scroll_state.has_value()) {- keyboard_scroll_state = *sealed.keyboard_scroll_state;- m_last_keyboard_scroll_state_generation = keyboard_scroll_state.generation;- keyboard_scroll_state.visual_context_tree_structural_epoch = display_list.compatible_visual_context_tree_structural_epoch();- }- auto async_scrolling_metadata = display_list.async_scrolling_metadata().value_or({});- async_scrolling_metadata.keyboard_scroll_state = keyboard_scroll_state;- display_list.set_async_scrolling_metadata(move(async_scrolling_metadata));-- m_last_frame_presented_by = sealed.presented_by;- CompositorFrame frame;- frame.context_id = sealed.context_id;- frame.present_viewport_rect = sealed.present_viewport_rect;- bool const display_list_is_unchanged = published.has_value() && m_compositor_display_list == published->display_list;- if (published.has_value() && !display_list_is_unchanged) {- auto command_resources = published->display_list == sealed.paint_command_cache_source- ? sealed.paint_command_cache_source_resources- : m_resource_storage.collect_referenced_resources(*published->display_list);- auto resources = resources_with(command_resources);- frame.display_list_update = CompositorFrame::DisplayListUpdate {- .display_list = published->display_list,- .visual_context_tree = serialized_visual_context_tree(),- .resource_transaction = m_resource_storage.create_transaction(m_compositor_display_list_resources, resources),- .encoded_scroll_state = MUST(ByteBuffer::copy(encoded_scroll_state)),- };- m_compositor_display_list_visual_context_tree_structural_epoch = published->display_list->compatible_visual_context_tree_structural_epoch();- m_resource_storage.retain_only(resources);- m_compositor_display_list = published->display_list;- m_compositor_display_list_command_resources = move(command_resources);- m_compositor_display_list_resources = move(resources);- m_compositor_display_list_paint_config = sealed.paint_config;- return frame;- }-- if (display_list_is_unchanged) {- m_compositor_display_list_paint_config = sealed.paint_config;- if (m_resource_storage.has_resources_added_since_last_retain())- m_resource_storage.retain_only(m_compositor_display_list_resources);- }- if (sealed.sends_visual_context_tree) {- VERIFY(sealed.visual_context_tree_mismatches_for_testing || visual_context_tree.structural_epoch == m_compositor_display_list_visual_context_tree_structural_epoch);- auto resources = resources_with(m_compositor_display_list_command_resources);- frame.visual_context_tree_update = CompositorFrame::VisualContextTreeUpdate {- .visual_context_tree = serialized_visual_context_tree(),- .resource_transaction = m_resource_storage.create_transaction(m_compositor_display_list_resources, resources),- .encoded_scroll_state = MUST(ByteBuffer::copy(encoded_scroll_state)),- .keyboard_scroll_state = move(keyboard_scroll_state),- };- m_resource_storage.retain_only(resources);- m_compositor_display_list_resources = move(resources);- } else {- frame.scroll_state_update = CompositorFrame::ScrollStateUpdate {- .encoded_scroll_state = MUST(ByteBuffer::copy(encoded_scroll_state)),- .keyboard_scroll_state = move(keyboard_scroll_state),- };- }- return frame;+ Layout::RustFFI::navigable_presenter_release(m_presenter);}-CompositorFrame NavigablePresenter::build_frame_beside_event_loop(SealedPresentation& sealed, NonnullRefPtr<Compositing::DisplayList> display_list, Layout::RustFFI::FfiPresentedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state)+static HTML::PaintConfig paint_config_from_ffi(Layout::RustFFI::FfiPaintConfig const& config){- bool const replaces_paint_command_cache_source = sealed.recording->cache_mode == Painting::PaintCommandCacheMode::ReadWrite- && display_list != sealed.paint_command_cache_source;- PublishedDisplayList published { move(display_list), replaces_paint_command_cache_source, {} };- auto frame = build_frame(sealed, published, visual_context_tree, encoded_scroll_state);- if (replaces_paint_command_cache_source) {- sealed.paint_command_cache_source = published.display_list;- sealed.paint_command_cache_source_resources = m_compositor_display_list_command_resources;- sealed.recording->paint_command_cache_source = published.display_list;- }- sealed.published = move(published);- return frame;-}--OwnPtr<SealedPresentation> NavigablePresenter::seal_for_clock_lane(SealedPresentation const& committed) const+ HTML::PaintConfig paint_config;+ paint_config.paint_overlay = config.paint_overlay;+ paint_config.should_show_line_box_borders = config.should_show_line_box_borders;+ paint_config.should_show_caret_hit_test_debug_overlay = config.should_show_caret_hit_test_debug_overlay;+ paint_config.force_dark_enabled = config.force_dark_enabled;+ paint_config.force_dark_foreground_threshold = config.force_dark_foreground_threshold;+ paint_config.force_dark_background_threshold = config.force_dark_background_threshold;+ if (config.has_canvas_fill_rect)+ paint_config.canvas_fill_rect = config.canvas_fill_rect;+ return paint_config;+}++static Layout::RustFFI::FfiPaintConfig paint_config_to_ffi(HTML::PaintConfig const& config){- MutexLocker locker(m_mutex);- // A lane records the document again as the frame's recording did, or as the one an unrecorded frame keeps, which the- // compositor has to show: a clock frame presented before the committed one may have taken its place.- RefPtr<Compositing::DisplayList> source = committed.paint_command_cache_source;- if (committed.published.has_value())- source = committed.published->display_list;- if (!source || source != m_compositor_display_list)- return nullptr;- auto sealed = make<SealedPresentation>();- sealed->paint_config = committed.paint_config;- sealed->visual_context_tree_structural_epoch = m_compositor_display_list_visual_context_tree_structural_epoch;- sealed->keyboard_scroll_state = committed.keyboard_scroll_state;- sealed->paint_command_cache_source = m_compositor_display_list;- sealed->paint_command_cache_source_resources = m_compositor_display_list_command_resources;- sealed->recording = Painting::DisplayListRecording {- .visual_context_tree_structural_epoch = m_compositor_display_list_visual_context_tree_structural_epoch,- .surface_clear_color = m_compositor_display_list->surface_clear_color(),- .cache_mode = Painting::PaintCommandCacheMode::ReadOnly,- .in_flight = true,- .async_scrolling_metadata = m_compositor_display_list->async_scrolling_metadata(),- .paint_command_cache_source = m_compositor_display_list,+ return {+ .paint_overlay = config.paint_overlay,+ .should_show_line_box_borders = config.should_show_line_box_borders,+ .should_show_caret_hit_test_debug_overlay = config.should_show_caret_hit_test_debug_overlay,+ .force_dark_enabled = config.force_dark_enabled,+ .force_dark_foreground_threshold = config.force_dark_foreground_threshold,+ .force_dark_background_threshold = config.force_dark_background_threshold,+ .has_canvas_fill_rect = config.canvas_fill_rect.has_value(),+ .canvas_fill_rect = config.canvas_fill_rect.value_or({}),};- sealed->context_id = committed.context_id;- sealed->present_viewport_rect = committed.present_viewport_rect;- sealed->presented_by = PresentedBy::Clock;- sealed->generation = committed.generation;- return sealed;-}--}--extern "C" WEB_API void web_navigable_presenter_unref(void* presenter)-{- static_cast<Web::Compositor::NavigablePresenter*>(presenter)->unref();-}--extern "C" WEB_API void* web_navigable_presenter_seal_for_clock_lane(void* presenter, void const* committed)-{- auto const& navigable_presenter = *static_cast<Web::Compositor::NavigablePresenter const*>(presenter);- auto sealed = navigable_presenter.seal_for_clock_lane(*static_cast<Web::Compositor::SealedPresentation const*>(committed));- if (!sealed)- return nullptr;- navigable_presenter.ref();- return sealed.leak_ptr();}-extern "C" WEB_API void web_sealed_presentation_destroy(void* sealed)+Optional<HTML::PaintConfig> NavigablePresenter::compositor_display_list_paint_config() const{- delete static_cast<Web::Compositor::SealedPresentation*>(sealed);+ Layout::RustFFI::FfiPaintConfig config {};+ if (!Layout::RustFFI::navigable_presenter_compositor_display_list_paint_config(m_presenter, &config))+ return {};+ return paint_config_from_ffi(config);}-extern "C" WEB_API void web_sealed_presentation_take_visual_context_tree(void* sealed_pointer, u64 structural_epoch, bool tree_is_restructured)+Optional<u64> NavigablePresenter::compositor_display_list_structural_epoch() const{- auto& sealed = *static_cast<Web::Compositor::SealedPresentation*>(sealed_pointer);- // A tree of another structure takes a new display list recorded against it, and the scroll offsets of its own nodes,- // which what presents the frame holds. A frame that records nothing seals no tree, and takes the render state's: the- // compositor's display list was cut from a tree of its structure.- if (!tree_is_restructured && sealed.visual_context_tree_structural_epoch.has_value())- VERIFY(structural_epoch == *sealed.visual_context_tree_structural_epoch);- if (sealed.recording.has_value())- sealed.recording->visual_context_tree_structural_epoch = structural_epoch;- sealed.visual_context_tree_structural_epoch = structural_epoch;- // A frame whose display list is the one the compositor has takes the tree on its own.- sealed.sends_visual_context_tree = true;+ u64 epoch = 0;+ if (!Layout::RustFFI::navigable_presenter_compositor_display_list_structural_epoch(m_presenter, &epoch))+ return {};+ return epoch;}-extern "C" WEB_API void web_navigable_presenter_add_font(void* presenter, void const* font)+void NavigablePresenter::forget_compositor_display_list(){- static_cast<Web::Compositor::NavigablePresenter*>(presenter)->display_list_resource_storage().add_font(*static_cast<Gfx::Font const*>(font));+ Layout::RustFFI::navigable_presenter_forget_compositor_display_list(m_presenter);}-extern "C" WEB_API void web_navigable_presenter_add_image_frame(void* presenter, void const* frame)+Optional<PresentedBy> NavigablePresenter::last_frame_presented_by() const{- static_cast<Web::Compositor::NavigablePresenter*>(presenter)->display_list_resource_storage().add_image_frame(*static_cast<Gfx::DecodedImageFrame const*>(frame));+ switch (Layout::RustFFI::navigable_presenter_last_frame_presented_by(m_presenter)) {+ case Layout::RustFFI::FfiPresentedBy::None:+ return {};+ case Layout::RustFFI::FfiPresentedBy::Commit:+ return PresentedBy::Commit;+ case Layout::RustFFI::FfiPresentedBy::Clock:+ return PresentedBy::Clock;+ }+ VERIFY_NOT_REACHED();}-extern "C" WEB_API void web_vector_image_resources_destroy(void* resources)+Optional<u64> NavigablePresenter::last_keyboard_scroll_state_generation() const{- delete static_cast<Web::Compositor::VectorImageResources*>(resources);+ u64 generation = 0;+ if (!Layout::RustFFI::navigable_presenter_last_keyboard_scroll_state_generation(m_presenter, &generation))+ return {};+ return generation;}-extern "C" WEB_API void web_navigable_presenter_take_vector_image_resources(void* presenter, void* resources_pointer, u64 const* display_list_ids, size_t display_list_id_count)+template<typename T>+static IPC::MessageBuffer encode_for_rust(T const& value){- auto& storage = static_cast<Web::Compositor::VectorImageResources*>(resources_pointer)->storage;- Compositing::DisplayListResourceSet resources;- for (auto raw_id : ReadonlySpan<u64> { display_list_ids, display_list_id_count }) {- Compositing::DisplayListResourceId id { raw_id };- resources.display_lists.set(id);- resources.include(storage.collect_referenced_resources(storage.display_list(id)));- resources.include(storage.collect_resources_referenced_by_visual_context_tree(storage.display_list(id)));- }- static_cast<Web::Compositor::NavigablePresenter*>(presenter)->display_list_resource_storage().apply_transaction(storage.create_transaction({}, resources));+ IPC::MessageBuffer buffer;+ IPC::Encoder encoder { buffer };+ MUST(encoder.encode(value));+ return buffer;}-extern "C" WEB_API void web_navigable_presenter_add_video_sink(void* presenter, u64 resource_id, u64 sink_handle)+void NavigablePresenter::lend_seal(SealedPresentation const& sealed, Function<void(Layout::RustFFI::FfiSeal const&)> const& take) const{- static_cast<Web::Compositor::NavigablePresenter*>(presenter)->display_list_resource_storage().add_video_sink(Compositing::VideoSinkResourceId { resource_id }, Media::VideoSinkHandle { sink_handle });-}--// Declared here, not in a header, so that no C++ presents a frame through them.-extern "C" WEB_API void web_navigable_presenter_present(void* presenter, void* sealed, Web::Layout::RustFFI::FfiPresentedRecording const* presented, Web::Layout::RustFFI::FfiPresentedVisualContextTree const* visual_context_tree, u8 const* encoded_scroll_state, size_t encoded_scroll_state_size, void* sink);-extern "C" WEB_API void web_navigable_presenter_present_unrecorded(void* presenter, void* sealed, Web::Layout::RustFFI::FfiPresentedVisualContextTree const* visual_context_tree, u8 const* encoded_scroll_state, size_t encoded_scroll_state_size, void* sink);--extern "C" WEB_API void web_navigable_presenter_present_unrecorded(void* presenter, void* sealed, Web::Layout::RustFFI::FfiPresentedVisualContextTree const* visual_context_tree, u8 const* encoded_scroll_state, size_t encoded_scroll_state_size, void* sink)-{- Web::Compositor::PresenterFFI::present_unrecorded(*static_cast<Web::Compositor::NavigablePresenter*>(presenter), *static_cast<Web::Compositor::SealedPresentation*>(sealed), *visual_context_tree, { encoded_scroll_state, encoded_scroll_state_size }, static_cast<Web::Compositor::CompositorFrameSink*>(sink));+ auto scroll_requests = encode_for_rust(sealed.scroll_requests);+ auto keyboard_scroll_state = encode_for_rust(sealed.keyboard_scroll_state);+ Layout::RustFFI::FfiSeal seal {+ .presenter = m_presenter,+ .paint_config = paint_config_to_ffi(sealed.paint_config),+ .has_visual_context_tree_structural_epoch = sealed.visual_context_tree_structural_epoch.has_value(),+ .visual_context_tree_structural_epoch = sealed.visual_context_tree_structural_epoch.value_or(0),+ .sends_visual_context_tree = sealed.sends_visual_context_tree,+ .encoded_scroll_requests = scroll_requests.data().data(),+ .encoded_scroll_requests_size = scroll_requests.data().size(),+ .encoded_keyboard_scroll_state = keyboard_scroll_state.data().data(),+ .encoded_keyboard_scroll_state_size = keyboard_scroll_state.data().size(),+ .context_id = sealed.context_id.value(),+ .has_present_viewport_rect = sealed.present_viewport_rect.has_value(),+ .present_viewport_rect = sealed.present_viewport_rect.value_or({}),+ .generation = sealed.generation,+ .visual_context_tree_mismatches_for_testing = sealed.visual_context_tree_mismatches_for_testing,+ };+ take(seal);}-extern "C" WEB_API void web_navigable_presenter_present(void* presenter, void* sealed_pointer, Web::Layout::RustFFI::FfiPresentedRecording const* presented, Web::Layout::RustFFI::FfiPresentedVisualContextTree const* visual_context_tree, u8 const* encoded_scroll_state, size_t encoded_scroll_state_size, void* sink)-{- auto& sealed = *static_cast<Web::Compositor::SealedPresentation*>(sealed_pointer);- auto display_list = Web::Painting::display_list_of_published_recording(sealed.recording.value(), *presented);- Web::Compositor::PresenterFFI::present(*static_cast<Web::Compositor::NavigablePresenter*>(presenter), sealed, move(display_list), *visual_context_tree, { encoded_scroll_state, encoded_scroll_state_size }, static_cast<Web::Compositor::CompositorFrameSink*>(sink));}diff --git a/Libraries/LibWeb/Compositor/NavigablePresenter.h b/Libraries/LibWeb/Compositor/NavigablePresenter.hindex 0070249ec36..5faef5f78e7 100644--- a/Libraries/LibWeb/Compositor/NavigablePresenter.h+++ b/Libraries/LibWeb/Compositor/NavigablePresenter.h@@ -6,40 +6,25 @@#pragma once-#include <AK/AtomicRefCounted.h>-#include <AK/ByteBuffer.h>-#include <AK/Mutex.h>+#include <AK/Function.h>#include <AK/Noncopyable.h>-#include <AK/NonnullOwnPtr.h>-#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>-#include <AK/RefPtr.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibWeb/Compositor/CompositorFrame.h>+#include <AK/Vector.h>+#include <LibCompositing/Types.h>+#include <LibGfx/Rect.h>#include <LibWeb/Export.h>-#include <LibWeb/Forward.h>#include <LibWeb/HTML/PaintConfig.h>-#include <LibWeb/Painting/DisplayListRecording.h>#include <LibWebCommon/Page/CompositorContextId.h>namespace Web::Layout::RustFFI {-struct FfiPresentedRecording;-struct FfiPresentedVisualContextTree;+struct FfiSeal;+struct NavigablePresenter;}namespace Web::Compositor {-// A display list a recording published, whether the recording made it the next one's paint command cache source, and-// the resources it references, once it is presented.-struct PublishedDisplayList {- NonnullRefPtr<Compositing::DisplayList> display_list;- bool replaces_paint_command_cache_source { false };- Compositing::DisplayListResourceSet referenced_resources;-};-// What presented a navigable's last frame: the recording of a frame a rendering update committed, or a tick of the// document's clock lane.enum class PresentedBy : u8 {@@ -48,157 +33,63 @@ enum class PresentedBy : u8 {};// What a frame is built from that its navigable and document held where the frame began, sealed there: the frame reaches-// neither of them again before it is presented. What presents the frame holds the document's scroll state beside the-// seal.+// neither of them again before it is presented. What presents the frame takes it over as the frame is committed.struct SealedPresentation {- AK_ALLOC_WITH_KMALLOC;-// The recording's paint config.HTML::PaintConfig paint_config;- // The structural epoch of the visual context tree a new display list is cut from, or of the one the compositor's- // display list takes where the document's tree changed since it took one. The tree itself stays with the Rust- // presentation, which lends it as the frame is presented.+ // The structural epoch of the visual context tree a new display list is cut from.Optional<u64> visual_context_tree_structural_epoch;// Whether the document's tree changed since the compositor took one.bool sends_visual_context_tree { false };- // Whether presenting the frame sent the compositor other scroll offsets than the frame presented before it, which the- // presenter notes as it presents.- bool presented_other_scroll_offsets { false };// The scrolls the navigable asked for since the frame before, which the compositor applies once it has the frame's- // boxes. Only the frame a rendering update commits carries them.+ // boxes.Vector<Compositing::ScrollRequest> scroll_requests;// What keyboard scrolling targets, for a top-level traversable.Optional<Compositing::KeyboardScrollState> keyboard_scroll_state;- // The display list a recording copies paint commands from, and the resources it references, which stay live while- // it does.- RefPtr<Compositing::DisplayList> paint_command_cache_source;- Compositing::DisplayListResourceSet paint_command_cache_source_resources;-- // For frames presented beside the event loop: the recording they publish, sealed where the recording began, where- // they go and the rect they are presented in, what presents them, and, once one is presented, the display list it- // published. A clock lane presents a frame from the seal at each tick that records one.- Optional<Painting::DisplayListRecording> recording;Web::CompositorContextId context_id;Optional<Gfx::IntRect> present_viewport_rect;- PresentedBy presented_by { PresentedBy::Commit };- Optional<PublishedDisplayList> published;// Whether the frame sends a visual context tree the compositor's display list was not recorded against, for a test.bool visual_context_tree_mismatches_for_testing { false };- // The frame a rendering update committed, counted per navigable, or the one a clock lane's frames start from: a- // lane's frame of an older one than the presenter presented last shows what the screen no longer shows.+ // The frame a rendering update committed, counted per navigable.u64 generation { 0 };};-// The display lists of the SVG images a frame renders, which the main thread renders for the frame into a resource-// storage of their own, with what they reference: the Paint thread hands them to the frame's presenter.-struct VectorImageResources {- AK_ALLOC_WITH_KMALLOC;-- Compositing::DisplayListResourceStorage storage;-};--// What a navigable presents to its compositor context from: the resource storage its recordings add to, and the-// display list the compositor context holds with the resources it holds for it. The navigable and what presents a frame-// of it beside the event loop share it: the Paint thread presents, and the main thread reads what it presented. Only the-// Paint thread reaches the resource storage, but for a recording of the main thread's own, which holds the document's-// clock lane meanwhile. The presenter holds no GC pointer.-class WEB_API NavigablePresenter : public AtomicRefCounted<NavigablePresenter> {+// A navigable's presenter, which keeps what the navigable's compositor context holds. The Paint thread presents through+// it, and the main thread reads what it presented here.+class WEB_API NavigablePresenter {AK_MAKE_NONCOPYABLE(NavigablePresenter);AK_MAKE_NONMOVABLE(NavigablePresenter);public:AK_ALLOC_WITH_KMALLOC;- static NonnullRefPtr<NavigablePresenter> create() { return adopt_ref(*new NavigablePresenter); }-- Compositing::DisplayListResourceStorage& display_list_resource_storage() { return m_resource_storage; }- Compositing::DisplayListResourceStorage const& display_list_resource_storage() const { return m_resource_storage; }+ NavigablePresenter();+ ~NavigablePresenter();- // The display list the compositor context holds, and the paint config it was recorded with.- RefPtr<Compositing::DisplayList> compositor_display_list() const- {- MutexLocker locker(m_mutex);- return m_compositor_display_list;- }- Optional<HTML::PaintConfig> compositor_display_list_paint_config() const- {- MutexLocker locker(m_mutex);- return m_compositor_display_list_paint_config;- }+ // The paint config of the display list the compositor context holds, and the structural epoch of the visual context+ // tree it was recorded against.+ Optional<HTML::PaintConfig> compositor_display_list_paint_config() const;+ Optional<u64> compositor_display_list_structural_epoch() const;// Forgets what the compositor context holds: a new compositor process holds nothing.void forget_compositor_display_list();- Optional<PresentedBy> last_frame_presented_by() const- {- MutexLocker locker(m_mutex);- return m_last_frame_presented_by;- }+ Optional<PresentedBy> last_frame_presented_by() const;// The generation of the keyboard scroll state the last frame handed the compositor, if it handed one.- Optional<u64> last_keyboard_scroll_state_generation() const- {- MutexLocker locker(m_mutex);- return m_last_keyboard_scroll_state_generation;- }+ Optional<u64> last_keyboard_scroll_state_generation() const;- // The seal a clock lane presents its frames with, which start from `committed`, the frame presented last, or none where- // the compositor shows another display list than the one that frame records from: the lane's recordings copy paint- // commands from it. On the Paint thread.- OwnPtr<SealedPresentation> seal_for_clock_lane(SealedPresentation const& committed) const;+ // Lends `take` the seal of a frame of this presenter as Rust takes it, for the call.+ void lend_seal(SealedPresentation const&, Function<void(Layout::RustFFI::FfiSeal const&)> const& take) const;private:- // Only the Paint thread builds and presents frames.- friend struct PresenterFFI;-- // Builds the frame that brings the compositor context `sealed` names up to date with `published`, the display list a- // recording just published, or with what changed for the one the compositor has where none was published, from what- // `sealed` sealed, the visual context tree the frame goes with, and the scroll state sealed beside it, which seeds- // the offsets of the boxes new to the compositor. Reads no navigable or document.- CompositorFrame build_frame(SealedPresentation const&, Optional<PublishedDisplayList>, Layout::RustFFI::FfiPresentedVisualContextTree const&, ReadonlyBytes encoded_scroll_state);-- // Builds the frame `sealed` sealed, with `display_list`, the display list its recording published, beside the event- // loop, keeping what it published in the seal, which the next frame from the seal copies paint commands from.- CompositorFrame build_frame_beside_event_loop(SealedPresentation&, NonnullRefPtr<Compositing::DisplayList>, Layout::RustFFI::FfiPresentedVisualContextTree const&, ReadonlyBytes encoded_scroll_state);-- NavigablePresenter() = default;-- // Guards what the main thread reads of what the Paint thread presented.- mutable Mutex m_mutex;- Compositing::DisplayListResourceStorage m_resource_storage;- Optional<HTML::PaintConfig> m_compositor_display_list_paint_config;- RefPtr<Compositing::DisplayList> m_compositor_display_list;- u64 m_compositor_display_list_visual_context_tree_structural_epoch { 0 };- Compositing::DisplayListResourceSet m_compositor_display_list_resources;- Compositing::DisplayListResourceSet m_compositor_display_list_command_resources;- Optional<PresentedBy> m_last_frame_presented_by;- Optional<u64> m_last_keyboard_scroll_state_generation;- // The generation of the last frame a rendering update committed that the presenter presented.- u64 m_last_committed_generation { 0 };- // The scroll offsets the last frame the presenter presented sent the compositor.- ByteBuffer m_last_presented_encoded_scroll_state;- // What the display list of the last frame a rendering update committed references, which the frames of a clock lane- // keep beside their own.- Compositing::DisplayListResourceSet m_committed_command_resources;+ Layout::RustFFI::NavigablePresenter const* m_presenter { nullptr };};-// A navigable's presenter and a frame sealed for it, which what presents the frame beside the event loop holds until it-// lands.+// A navigable's presenter and a frame sealed for it, which what presents the frame beside the event loop takes over as+// the frame is committed.struct FlightPresentation {- NonnullRefPtr<NavigablePresenter> presenter;- NonnullOwnPtr<SealedPresentation> sealed;+ NavigablePresenter const* presenter;+ SealedPresentation sealed;};}--// What a recording that presents beside the event loop reaches of its presenter and seal, which it owns meanwhile.-extern "C" {-WEB_API void web_navigable_presenter_unref(void* presenter);-WEB_API void* web_navigable_presenter_seal_for_clock_lane(void* presenter, void const* committed);-WEB_API void web_sealed_presentation_destroy(void* sealed);-WEB_API void web_sealed_presentation_take_visual_context_tree(void* sealed, u64 structural_epoch, bool tree_is_restructured);-WEB_API void web_navigable_presenter_add_font(void* presenter, void const* font);-WEB_API void web_navigable_presenter_add_image_frame(void* presenter, void const* frame);-WEB_API void web_navigable_presenter_add_video_sink(void* presenter, u64 resource_id, u64 sink_handle);-WEB_API void web_vector_image_resources_destroy(void* resources);-WEB_API void web_navigable_presenter_take_vector_image_resources(void* presenter, void* resources, u64 const* display_list_ids, size_t display_list_id_count);-}diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 1ceea6ff576..a679cc32d75 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -24,7 +24,6 @@#include <AK/Utf16StringBuilder.h>#include <AK/Utf16View.h>#include <AK/Utf8View.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCore/Timer.h>#include <LibGC/Heap.h>#include <LibGC/HeapVector.h>@@ -12076,28 +12075,17 @@ void Document::set_needs_to_record_display_list_keeping_hit_test_display_list()navigable->set_needs_to_record_display_list();}-RefPtr<Compositing::DisplayList> Document::record_display_list(Layout::BegunRead const& read, HTML::PaintConfig config, Compositing::DisplayListResourceStorage& resource_storage, Painting::PaintCommandCacheMode cache_mode)+bool Document::record_display_list(Layout::BegunRead const& read, HTML::PaintConfig config, Painting::PaintCommandCacheMode cache_mode){// The host reads this recording right after it, so a recording in flight is taken in first: it has the recorder// state.- // The navigable's resource storage is the Paint thread's while the document's clock lane presents: a recording- // that adds to it holds the lane meanwhile.- auto* host = layout_node_arena().host();- bool holds_clock_lane = false;- if (auto navigable = this->navigable()) {+ if (auto navigable = this->navigable())navigable->take_recording_in_flight_in(HTML::LocalNavigable::TakeIn::Wait);- holds_clock_lane = &resource_storage == &navigable->display_list_resource_storage();- }- if (holds_clock_lane)- Layout::RustFFI::document_host_hold_clock_lane(host);- ScopeGuard release_clock_lane = [&] {- if (holds_clock_lane)- Layout::RustFFI::document_host_release_clock_lane(host);- };auto recording = start_display_list_recording(read, config, cache_mode);if (!recording.has_value())- return nullptr;- return finish_display_list_recording(read, *recording, resource_storage);+ return false;+ finish_display_list_recording(read, *recording);+ return true;}Optional<Painting::DisplayListRecording> Document::start_display_list_recording(Layout::BegunRead const& read, HTML::PaintConfig config, Painting::PaintCommandCacheMode cache_mode)@@ -12156,19 +12144,14 @@ Optional<Painting::DisplayListRecording> Document::start_recording(Layout::Begunreturn Painting::start_rust_display_list_recording(read, *this, visual_context_tree_structural_epoch, surface_clear_color, cache_mode, config, overlay_inputs, move(committed));}-RefPtr<Compositing::DisplayList> Document::finish_display_list_recording(Layout::BegunRead const& read, Painting::DisplayListRecording const& recording, Compositing::DisplayListResourceStorage& resource_storage, Painting::HitTestListStands hit_test_list_stands)+void Document::finish_display_list_recording(Layout::BegunRead const& read, Painting::DisplayListRecording const& recording, Painting::HitTestListStands hit_test_list_stands){- auto display_list = Painting::finish_rust_display_list_recording(read, *this, recording, resource_storage);- if (!display_list)- return nullptr;- adopt_published_recording(hit_test_list_read(read, hit_test_list_stands), recording, *display_list, [&] { return resource_storage.collect_referenced_resources(*display_list); });- return display_list;+ Painting::publish_rust_display_list_recording(read, *this);+ adopt_published_recording(hit_test_list_read(read, hit_test_list_stands), recording);}-Painting::HitTestListAdoption Document::adopt_published_recording(Optional<Layout::BegunRead const&> hit_test_list_read, Painting::DisplayListRecording const& recording, NonnullRefPtr<Compositing::DisplayList> display_list, Function<Compositing::DisplayListResourceSet()> const& referenced_resources)+Painting::HitTestListAdoption Document::adopt_published_recording(Optional<Layout::BegunRead const&> hit_test_list_read, Painting::DisplayListRecording const& recording){- auto& document_paint_state = paint_state();- bool const recording_returned_the_paint_command_cache_source = display_list == document_paint_state.display_list_used_as_paint_command_cache_source();auto adoption = Painting::HitTestListAdoption::Kept;if (!hit_test_list_read.has_value()) {m_hit_test_display_list = nullptr;@@ -12177,9 +12160,6 @@ Painting::HitTestListAdoption Document::adopt_published_recording(Optional<Layoum_hit_test_display_list = Painting::HitTestDisplayList::create_from_rust_recording(*hit_test_list_read, recording.visual_context_tree_structural_epoch, layout_node_arena(), *m_chrome_widget_registry);adoption = Painting::HitTestListAdoption::TookNew;}-- if (recording.cache_mode == Painting::PaintCommandCacheMode::ReadWrite && !recording_returned_the_paint_command_cache_source)- document_paint_state.set_display_list_used_as_paint_command_cache_source(display_list, referenced_resources());return adoption;}@@ -12217,8 +12197,7 @@ Optional<Painting::HitTestQuery> Document::prepare_hit_test_query(Layout::BegunRHTML::PaintConfig paint_config { .paint_overlay = true };if (auto navigable = this->navigable())paint_config = navigable->stamp_paint_config(paint_config);- Compositing::DisplayListResourceStorage throwaway_resource_storage_for_hit_test_only_recording;- (void)record_display_list(read, paint_config, throwaway_resource_storage_for_hit_test_only_recording, Painting::PaintCommandCacheMode::ReadOnly);+ (void)record_display_list(read, paint_config, Painting::PaintCommandCacheMode::ReadOnly);};// The recording in flight replaces the hit-test list once it lands, so a list that is not current waits for it@@ -12671,17 +12650,10 @@ Utf16String Document::dump_display_list()if (paint_state().has_visual_context_tree(read))schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::FreshTree);- // The dump reads the navigable's resource storage after the recording adds to it, which the Paint thread owns while- // the document's clock lane presents: the dump holds the lane until it is done.- auto* host = layout_node_arena().host();- Layout::RustFFI::document_host_hold_clock_lane(host);- ScopeGuard release_clock_lane = [&] { Layout::RustFFI::document_host_release_clock_lane(host); };- auto& resource_storage = navigable()->display_list_resource_storage();- auto display_list = record_display_list(read, HTML::PaintConfig {}, resource_storage, Painting::PaintCommandCacheMode::ReadOnly);- if (!display_list)+ if (!record_display_list(read, HTML::PaintConfig {}, Painting::PaintCommandCacheMode::ReadOnly))return "No display list"_utf16;- return Painting::serialize_painting_dump(read, *this, *display_list, resource_storage);+ return Painting::serialize_painting_dump(read, *this);}Utf16String Document::dump_stacking_context_tree()diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 94a594f5dfb..2b7de949efd 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -1649,8 +1649,9 @@ public:set_needs_repaint(should_invalidate_display_list);}- // Records the document's display list in step with the host, once a recording in flight has been taken in.- RefPtr<Compositing::DisplayList> record_display_list(Layout::BegunRead const& read, HTML::PaintConfig, Compositing::DisplayListResourceStorage&, Painting::PaintCommandCacheMode);+ // Records the document's display list in step with the host, once a recording in flight has been taken in, and+ // answers whether it had a box to record.+ bool record_display_list(Layout::BegunRead const& read, HTML::PaintConfig, Painting::PaintCommandCacheMode);// Starts recording the document's display list as the document is now, beside the event loop where `blocker` is// none, taking `flight`, if any, to present its frame with, and makes the display list of a recording that has// landed.@@ -1658,10 +1659,10 @@ public:// Commits the navigable's next frame, a recording of the document, to the render owner, which presents it with// `presentation` beside the event loop.Painting::DisplayListRecording commit_display_list_recording(Layout::BegunRead const& read, HTML::PaintConfig, Compositor::FlightPresentation&& presentation);- RefPtr<Compositing::DisplayList> finish_display_list_recording(Layout::BegunRead const& read, Painting::DisplayListRecording const&, Compositing::DisplayListResourceStorage&, Painting::HitTestListStands = Painting::HitTestListStands::Yes);- // Takes in `display_list`, which `recording` published: the paint command cache source, and the hit-test list it made,- // read in `hit_test_list_read`, where that still stands for the document's boxes. Where none does, nothing is read.- Painting::HitTestListAdoption adopt_published_recording(Optional<Layout::BegunRead const&> hit_test_list_read, Painting::DisplayListRecording const&, NonnullRefPtr<Compositing::DisplayList>, Function<Compositing::DisplayListResourceSet()> const& referenced_resources);+ void finish_display_list_recording(Layout::BegunRead const& read, Painting::DisplayListRecording const&, Painting::HitTestListStands = Painting::HitTestListStands::Yes);+ // Takes in the hit-test list `recording` made, read in `hit_test_list_read`, where that still stands for the+ // document's boxes. Where none does, nothing is read.+ Painting::HitTestListAdoption adopt_published_recording(Optional<Layout::BegunRead const&> hit_test_list_read, Painting::DisplayListRecording const&);// Indicates whether a query of the hit test list would require a synchronous update to it.[[nodiscard]] bool hit_test_display_list_is_current(Layout::BegunRead const& read);// Where a visual animation sample time is given, the hit test reads the compositor's animations at that time, as adiff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 7a42d9f58fe..94b6fc19625 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -79,7 +79,6 @@ class CompositorConnection;class CompositorContextHandle;class CompositorHost;class NavigablePresenter;-struct CompositorFrame;}diff --git a/Libraries/LibWeb/HTML/DecodedImageData.cpp b/Libraries/LibWeb/HTML/DecodedImageData.cppindex dd221977469..d562268876c 100644--- a/Libraries/LibWeb/HTML/DecodedImageData.cpp+++ b/Libraries/LibWeb/HTML/DecodedImageData.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibGC/Heap.h>#include <LibGC/WeakInlines.h>#include <LibWeb/HTML/DecodedImageData.h>@@ -37,11 +36,6 @@ DecodedImageData::DecodedImageData() = default;DecodedImageData::~DecodedImageData() = default;-Optional<Compositing::DisplayListResource> DecodedImageData::record_display_list(Gfx::IntSize, CSS::PreferredColorScheme, Compositing::DisplayListResourceStorage&) const-{- return {};-}-bool DecodedImageData::has_clients_that_may_render() const{for (auto* client : m_clients) {diff --git a/Libraries/LibWeb/HTML/DecodedImageData.h b/Libraries/LibWeb/HTML/DecodedImageData.hindex 99f79120861..28c5175a9a3 100644--- a/Libraries/LibWeb/HTML/DecodedImageData.h+++ b/Libraries/LibWeb/HTML/DecodedImageData.h@@ -8,7 +8,6 @@#include <AK/Optional.h>#include <AK/RefCounted.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibGC/Weak.h>#include <LibGfx/Color.h>#include <LibGfx/DecodedImageFrame.h>@@ -49,10 +48,6 @@ public:void set_is_cors_cross_origin(bool value) { m_is_cors_cross_origin = value; }virtual Optional<Painting::ImagePaint> image_paint(Painting::ImagePaintRequest const&) const = 0;- // An SVG used as an image resolves `prefers-color-scheme` from the used `color-scheme` of the- // element referencing it, so the scheme is part of what is being asked for rather than a- // property of the page.- virtual Optional<Compositing::DisplayListResource> record_display_list(Gfx::IntSize, CSS::PreferredColorScheme, Compositing::DisplayListResourceStorage&) const;virtual Optional<Gfx::DecodedImageFrame> default_frame(Gfx::IntSize = {}) const = 0;virtual Optional<Gfx::DecodedImageFrame> current_frame(Gfx::IntSize = {}) const = 0;diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 2fa483fc7c1..78757a661df 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -22,7 +22,6 @@#include <LibWeb/CSS/PseudoElement.h>#include <LibWeb/CSS/SerializationMode.h>#include <LibWeb/CSS/VisualViewport.h>-#include <LibWeb/Compositor/CompositorFrame.h>#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/Compositor/RenderClock.h>#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>@@ -744,6 +743,10 @@ struct LocalNavigable::RecordingInFlight {GC::Ref<DOM::Document> document;// What the frame records, unless it keeps the display list the compositor has.Optional<Painting::DisplayListRecording> recording;+ // Whether the frame sends the compositor the document's visual context tree, and the scrolls it hands it, which the+ // navigable takes back where the frame presents nothing.+ bool sends_visual_context_tree { false };+ Vector<Compositing::ScrollRequest> scroll_requests;};LocalNavigable::LocalNavigable(@@ -7151,10 +7154,12 @@ bool LocalNavigable::commit_frame(PaintConfig paint_config)commit_unrecorded_frame(read, *document, move(sealed));return true;}+ bool const sends_visual_context_tree = sealed.sends_visual_context_tree;+ auto scroll_requests = sealed.scroll_requests;auto recording = document->commit_display_list_recording(read, paint_config, take_presentation(move(sealed)));// What asks for another recording once this one has started asks for the next one.m_needs_to_record_display_list = false;- m_recording_in_flight = make<RecordingInFlight>(*document, move(recording));+ m_recording_in_flight = make<RecordingInFlight>(*document, move(recording), sends_visual_context_tree, move(scroll_requests));main_thread_event_loop().did_commit_frame(*this, CommittedFrameRecords::Yes);return true;}@@ -7167,18 +7172,16 @@ Compositor::FlightPresentation LocalNavigable::take_presentation(Compositor::Seasealed.context_id = compositor_context().id();sealed.present_viewport_rect = present_viewport_rect();sealed.generation = ++m_committed_generation;- Compositor::FlightPresentation presentation {- .presenter = m_presenter,- .sealed = make<Compositor::SealedPresentation>(move(sealed)),- };main_thread_event_loop().ensure_frame_completion_registered();- return presentation;+ return { .presenter = m_presenter.ptr(), .sealed = move(sealed) };}void LocalNavigable::commit_unrecorded_frame(Layout::BegunRead const& read, DOM::Document& document, Compositor::SealedPresentation sealed){+ bool const sends_visual_context_tree = sealed.sends_visual_context_tree;+ auto scroll_requests = sealed.scroll_requests;Painting::commit_unrecorded_frame(read, document, take_presentation(move(sealed)));- m_recording_in_flight = make<RecordingInFlight>(document, OptionalNone {});+ m_recording_in_flight = make<RecordingInFlight>(document, OptionalNone {}, sends_visual_context_tree, move(scroll_requests));main_thread_event_loop().did_commit_frame(*this, CommittedFrameRecords::No);}@@ -7270,36 +7273,22 @@ Compositor::SealedPresentation LocalNavigable::seal_presentation(Layout::BegunRe.sends_visual_context_tree = sends_visual_context_tree,.scroll_requests = take_unsent_scroll_requests(),.keyboard_scroll_state = move(keyboard_scroll_state),- .paint_command_cache_source = paint_state.display_list_used_as_paint_command_cache_source(),- .paint_command_cache_source_resources = paint_state.paint_command_cache_source_referenced_resources(),- .recording = {},.context_id = {},.present_viewport_rect = {},- .published = {},};}-// Hands `document` back what a sealed frame took of it, where no frame is built from the seal. A document whose layout-// tree was torn down since (one destroyed beside the seal) has no paint state to take it back: the next tree comes with-// a paint state of its own.-void LocalNavigable::unseal_presentation(DOM::Document& document, Compositor::SealedPresentation& sealed)-{- if (sealed.sends_visual_context_tree && document.has_paint_state())- document.paint_state().did_update_visual_context_values();- give_back_unsent_scroll_requests(move(sealed.scroll_requests));-}-bool LocalNavigable::take_recording_in_flight_in(TakeIn take_in){if (!m_recording_in_flight)return true;GC::Ref<DOM::Document> document = m_recording_in_flight->document;auto* host = document->layout_node_arena().host();- Layout::RustFFI::FfiPresentation given_back {};+ bool presented_other_scroll_offsets = false;auto take_landing = [&] {return take_in == TakeIn::Wait- ? Layout::RustFFI::render_state_join_recording_in_flight(host, &given_back)- : Layout::RustFFI::render_state_take_finished_recording_in(host, &given_back);+ ? Layout::RustFFI::render_state_join_recording_in_flight(host, &presented_other_scroll_offsets)+ : Layout::RustFFI::render_state_take_finished_recording_in(host, &presented_other_scroll_offsets);};auto landing = take_landing();// A frame whose recording renders SVG images waits for the main thread to render them, and flies again with them.@@ -7314,21 +7303,22 @@ bool LocalNavigable::take_recording_in_flight_in(TakeIn take_in)return false;auto in_flight = m_recording_in_flight.release_nonnull();main_thread_event_loop().did_take_frame_in(*this);- finish_recording_in_flight(*in_flight, landing, given_back);+ finish_recording_in_flight(*in_flight, landing, presented_other_scroll_offsets);return true;}// Takes in a frame in flight that has landed, with the presenter it gives back, and what its recording published, where// it still goes to this navigable's active document.-void LocalNavigable::finish_recording_in_flight(RecordingInFlight& in_flight, Layout::RustFFI::FfiRecordingLanding landing, Layout::RustFFI::FfiPresentation given_back)+void LocalNavigable::finish_recording_in_flight(RecordingInFlight& in_flight, Layout::RustFFI::FfiRecordingLanding landing, bool presented_other_scroll_offsets){GC::Ref<DOM::Document> document = in_flight.document;- VERIFY(given_back.presenter == m_presenter.ptr());- static_cast<Compositor::NavigablePresenter*>(given_back.presenter)->unref();- auto sealed = adopt_own(*static_cast<Compositor::SealedPresentation*>(given_back.sealed));- // A frame the render owner found no box to record of presents nothing.+ // A frame the render owner found no box to record of presents nothing: the document takes back what the frame took+ // of it. A document whose layout tree was torn down since (one destroyed beside the seal) has no paint state to take+ // it back: the next tree comes with a paint state of its own.if (landing == Layout::RustFFI::FfiRecordingLanding::NothingRecorded) {- unseal_presentation(document, *sealed);+ if (in_flight.sends_visual_context_tree && document->has_paint_state())+ document->paint_state().did_update_visual_context_values();+ give_back_unsent_scroll_requests(move(in_flight.scroll_requests));if (!has_been_destroyed() && active_document().ptr() == document.ptr())event_handler().note_frame_landed(Web::EventHandler::FramePlacement::Unchanged);return;@@ -7344,7 +7334,7 @@ void LocalNavigable::finish_recording_in_flight(RecordingInFlight& in_flight, La// rows leaves no hit-test list, as the boxes it names may be gone.auto const hit_test_list_stands = landing == Layout::RustFFI::FfiRecordingLanding::LandedBehindRows ? Painting::HitTestListStands::No : Painting::HitTestListStands::Yes;Painting::take_recording_trace_if_pending(read, *document);- hit_test_list_adoption = document->adopt_published_recording(Painting::hit_test_list_read(read, hit_test_list_stands), *in_flight.recording, sealed->published->display_list, [&] { return sealed->published->referenced_resources; });+ hit_test_list_adoption = document->adopt_published_recording(Painting::hit_test_list_read(read, hit_test_list_stands), *in_flight.recording);}// A frame that kept its hit-test items, and sent no visual context tree, placed them as the frame before it did,// unless it sent other scroll offsets. The hover waits for a scroll of the user's to stop instead (see@@ -7354,9 +7344,9 @@ void LocalNavigable::finish_recording_in_flight(RecordingInFlight& in_flight, Lareturn Web::EventHandler::FramePlacement::Changed;if (hit_test_list_adoption != Painting::HitTestListAdoption::Kept)return Web::EventHandler::FramePlacement::Unchanged;- if (sealed->sends_visual_context_tree)+ if (in_flight.sends_visual_context_tree)return Web::EventHandler::FramePlacement::Changed;- if (sealed->presented_other_scroll_offsets && !has_user_scroll_gesture())+ if (presented_other_scroll_offsets && !has_user_scroll_gesture())return Web::EventHandler::FramePlacement::Changed;return Web::EventHandler::FramePlacement::Unchanged;}();diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.hindex 0d10cef698f..e570c910b31 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.h+++ b/Libraries/LibWeb/HTML/LocalNavigable.h@@ -335,7 +335,6 @@ public:// Paints into the target, which must be a shareable bitmap, then calls the callback.void render_screenshot(NonnullRefPtr<Gfx::Bitmap> target, PaintConfig, Function<void(Compositor::ScreenshotResult)>&& callback);- Compositing::DisplayListResourceStorage& display_list_resource_storage() { return presenter().display_list_resource_storage(); }// Tells the clock lanes of the active document whether a task begins or the event loop goes idle: a task that begins// lets them sample the animations they held, at once. Answers whether the navigable still has lanes to tell.@@ -472,8 +471,7 @@ private:Compositor::FlightPresentation take_presentation(Compositor::SealedPresentation);void commit_unrecorded_frame(Layout::BegunRead const&, DOM::Document&, Compositor::SealedPresentation);Compositor::SealedPresentation seal_presentation(Layout::BegunRead const&, DOM::Document&, PaintConfig const&, bool records_display_list);- void unseal_presentation(DOM::Document&, Compositor::SealedPresentation&);- void finish_recording_in_flight(RecordingInFlight&, Layout::RustFFI::FfiRecordingLanding, Layout::RustFFI::FfiPresentation);+ void finish_recording_in_flight(RecordingInFlight&, Layout::RustFFI::FfiRecordingLanding, bool presented_other_scroll_offsets);Gfx::IntRect present_viewport_rect() const;Optional<CSSPixelPoint> to_local_root_viewport_position(CSSPixelPoint);@@ -684,7 +682,7 @@ private:bool m_should_show_caret_hit_test_debug_overlay { false };// The navigable's presenter, which what presents a frame of it beside the event loop shares, and how many frames a// rendering update committed with it.- NonnullRefPtr<Compositor::NavigablePresenter> m_presenter { Compositor::NavigablePresenter::create() };+ NonnullOwnPtr<Compositor::NavigablePresenter> m_presenter { make<Compositor::NavigablePresenter>() };u64 m_committed_generation { 0 };OwnPtr<Compositor::CompositorContextHandle> m_compositor_context;RefPtr<Core::Timer> m_async_scroll_hover_update_timer;diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex 9cb33c9eb15..d9000441e80 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -260,9 +260,7 @@ static ErrorOr<NonnullRefPtr<Gfx::Bitmap>> scale_bitmap(Compositor::CompositorHoreturn Error::from_string_literal("No compositor to scale the bitmap");auto output = TRY(Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, size));- Compositing::DisplayListResourceStorage resource_storage;- auto display_list = Painting::record_image_frame_display_list(TRY(Gfx::DecodedImageFrame::create(input)), output->rect().to_type<float>(), scaling_mode, resource_storage);- if (!compositor_host->rasterize_display_list(display_list, resource_storage, output))+ if (!Painting::rasterize_image_frame(*compositor_host, TRY(Gfx::DecodedImageFrame::create(input)), output->rect().to_type<float>(), scaling_mode, output))return Error::from_string_literal("Unable to scale the bitmap");return output;}diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex bd47a62702c..cdd20bf817d 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -14,7 +14,6 @@#include <AK/Utf16StringBuilder.h>#include <LibAudio/ClientConnection.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Scrolling/RecordedDisplayListScrolling.h>#include <LibCore/EventLoop.h>#include <LibCore/System.h>#include <LibCore/TimeZone.h>@@ -54,7 +53,6 @@#include <LibWeb/CSS/PseudoElement.h>#include <LibWeb/CSS/StyleComputer.h>#include <LibWeb/CSS/StyleSheetState.h>-#include <LibWeb/Compositor/CompositorFrame.h>#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/Compositor/RenderClock.h>#include <LibWeb/DOM/Document.h>@@ -1065,8 +1063,13 @@ GC::Ref<JS::Object> Internals::compositor_scroll_state(GC::Ptr<DOM::Element> scrif (auto navigable = document.navigable(); navigable && navigable->has_compositor_context())scroll_state = navigable->compositor_context().scroll_state_for_testing(stretched_scroller);auto report = JsonValue::from_string(scroll_state);- if (report.is_error() || !report.value().is_object())- report = JsonValue::from_string(Compositing::empty_async_scrolling_state_as_json());+ if (report.is_error() || !report.value().is_object()) {+ String empty_scroll_state;+ Layout::RustFFI::render_state_empty_async_scrolling_state_json(&empty_scroll_state, [](void* receiver, u8 const* bytes, size_t byte_count) {+ *static_cast<String*>(receiver) = MUST(String::from_utf8(StringView { bytes, byte_count }));+ });+ report = JsonValue::from_string(empty_scroll_state);+ }return scrolling_state_report_to_object(window(), report.value().as_object());}@@ -1707,12 +1710,21 @@ GC::Ref<JS::Object> Internals::recorded_display_list_wheel_target_at(double x, d// A script reads the render state, which waits for a frame in flight.Layout::ForcedReadScope read { window().associated_document() };auto& document = window().associated_document();- auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();- if (!display_list)- return first_wheel_step_route_to_object({ .route = { InputRoutingDecision::NoAsyncScrollingState }, .document_id = {} });auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));- auto encoded_scroll_state = document.paint_state().encoded_scroll_state();- return first_wheel_step_route_to_object(Compositing::route_first_wheel_step_through_recorded_display_list(*display_list, encoded_scroll_state, document.wheel_event_listener_state_generation(), position, { static_cast<float>(delta_x), static_cast<float>(delta_y) }));+ Layout::RustFFI::FfiRecordedFirstWheelStepRoute route {};+ if (!Layout::RustFFI::render_state_recorded_route_first_wheel_step(document.layout_node_arena().host(), document.wheel_event_listener_state_generation(), position, { static_cast<float>(delta_x), static_cast<float>(delta_y) }, &route))+ return first_wheel_step_route_to_object({ .route = { InputRoutingDecision::NoAsyncScrollingState }, .document_id = {} });+ Compositing::FirstWheelStepRouteForTesting result { .route = { static_cast<InputRoutingDecision>(route.decision) }, .document_id = {} };+ if (route.has_scroller) {+ result.route.scroller = Web::AsyncScrollNodeStableID {+ .node_id = Web::UniqueNodeID { route.scroller_node_id },+ .kind = static_cast<Web::AsyncScrollNodeKind>(route.scroller_kind),+ .pseudo_element_type = route.scroller_pseudo_element_type,+ };+ }+ if (route.has_document_id)+ result.document_id = Web::UniqueNodeID { route.document_id };+ return first_wheel_step_route_to_object(result);}bool Internals::recorded_display_list_blocks_wheel_event_at(double x, double y)@@ -1720,12 +1732,8 @@ bool Internals::recorded_display_list_blocks_wheel_event_at(double x, double y)// A script reads the render state, which waits for a frame in flight.Layout::ForcedReadScope read { window().associated_document() };auto& document = window().associated_document();- auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();- if (!display_list)- return false;auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));- auto encoded_scroll_state = document.paint_state().encoded_scroll_state();- return Compositing::recorded_display_list_blocks_wheel_event_at(*display_list, encoded_scroll_state, position);+ return Layout::RustFFI::render_state_recorded_blocks_wheel_event_at(document.layout_node_arena().host(), position);}void Internals::record_display_list_for_testing(bool paint_overlay, bool cold)@@ -1738,7 +1746,7 @@ void Internals::record_display_list_for_testing(bool paint_overlay, bool cold)// A recording against a visual context tree built fresh copies nothing from the published one.if (cold)document.schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::FreshTree);- (void)document.record_display_list(read, HTML::PaintConfig { .paint_overlay = paint_overlay }, document.navigable()->display_list_resource_storage(), Painting::PaintCommandCacheMode::ReadWrite);+ (void)document.record_display_list(read, HTML::PaintConfig { .paint_overlay = paint_overlay }, Painting::PaintCommandCacheMode::ReadWrite);}void Internals::set_autoplay_policy(Utf16String const& policy)@@ -3913,10 +3921,10 @@ GC::Ptr<JS::Object> Internals::hit_test_result(double x, double y)GC::Ref<JS::Object> Internals::recorded_async_scrolling_state_object(){auto& document = window().associated_document();- auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();- auto json = display_list- ? Compositing::async_scrolling_state_as_json(*display_list)- : Compositing::empty_async_scrolling_state_as_json();+ String json;+ Layout::RustFFI::render_state_recorded_async_scrolling_state_json(document.layout_node_arena().host(), &json, [](void* receiver, u8 const* bytes, size_t byte_count) {+ *static_cast<String*>(receiver) = MUST(String::from_utf8(StringView { bytes, byte_count }));+ });auto report = MUST(JsonValue::from_string(json));return scrolling_state_report_to_object(window(), report.as_object());}diff --git a/Libraries/LibWeb/NotificationsAPI/Notification.cpp b/Libraries/LibWeb/NotificationsAPI/Notification.cppindex dd54c8818ec..9d3fc9f9a6f 100644--- a/Libraries/LibWeb/NotificationsAPI/Notification.cpp+++ b/Libraries/LibWeb/NotificationsAPI/Notification.cpp@@ -439,9 +439,7 @@ void Notification::fetch_a_notification_resource(URL::URL const& url, GC::Ref<GCauto output = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, scaled_size);auto frame = Gfx::DecodedImageFrame::create(*bitmap);if (!output.is_error() && !frame.is_error()) {- Compositing::DisplayListResourceStorage resource_storage;- auto display_list = Painting::record_image_frame_display_list(frame.value(), Gfx::FloatRect { {}, scaled_size.to_type<float>() }, Gfx::ScalingMode::BilinearMipmap, resource_storage);- if (m_page->compositor_host().rasterize_display_list(display_list, resource_storage, output.value()))+ if (Painting::rasterize_image_frame(m_page->compositor_host(), frame.value(), Gfx::FloatRect { {}, scaled_size.to_type<float>() }, Gfx::ScalingMode::BilinearMipmap, output.value()))bitmap = output.release_value();}}diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex a5732dd3dc8..1d43d6f6269 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -1063,12 +1063,12 @@ EventResult EventHandler::handle_mousewheel(CSSPixelPoint visual_viewport_positiauto local_root = m_navigable->local_root();if (!local_root->needs_to_record_display_list() && !local_root->has_recording_in_flight())return false;- auto display_list = local_root->presenter().compositor_display_list();+ auto compositor_structural_epoch = local_root->presenter().compositor_display_list_structural_epoch();auto root_document = local_root->active_document();- if (!display_list || !root_document || !root_document->has_paint_state())+ if (!compositor_structural_epoch.has_value() || !root_document || !root_document->has_paint_state())return false;Layout::ForcedReadScope root_read { *root_document };- return display_list->compatible_visual_context_tree_structural_epoch() != root_document->paint_state().visual_context_tree_structural_epoch(root_read);+ return *compositor_structural_epoch != root_document->paint_state().visual_context_tree_structural_epoch(root_read);};// An event that no compositor has seen, such as one a test makes, goes there first, as the UI's events do. Thediff --git a/Libraries/LibWeb/Painting/DisplayListRecording.h b/Libraries/LibWeb/Painting/DisplayListRecording.hindex 37b52183653..10ba49a0292 100644--- a/Libraries/LibWeb/Painting/DisplayListRecording.h+++ b/Libraries/LibWeb/Painting/DisplayListRecording.h@@ -6,10 +6,7 @@#pragma once-#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>-#include <AK/RefPtr.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibWeb/Forward.h>#include <LibWeb/Painting/PaintableTypes.h>@@ -38,17 +35,12 @@ inline Optional<Layout::BegunRead const&> hit_test_list_read(Layout::BegunRead c}// A recording of a document's display list, started from the document as it was then: done in step with the host, or-// in flight beside the event loop until the event loop takes it in. Its display list is made once it is published.+// in flight beside the event loop until the event loop takes it in. Rust keeps what it records.struct DisplayListRecording {// The structural epoch of the visual context tree the recording records against, which stays with the render state.u64 visual_context_tree_structural_epoch { 0 };- Optional<Gfx::Color> surface_clear_color;PaintCommandCacheMode cache_mode;bool in_flight { false };- // What its display list is stamped with for async scrolling, sealed where the recording began, and the display list- // it copied paint commands from then, which it publishes again where it recorded the same.- Optional<Compositing::AsyncScrollingMetadata> async_scrolling_metadata;- RefPtr<Compositing::DisplayList> paint_command_cache_source;};}diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.cpp b/Libraries/LibWeb/Painting/DocumentPaintState.cppindex 7b4b2cda18e..1638056908c 100644--- a/Libraries/LibWeb/Painting/DocumentPaintState.cpp+++ b/Libraries/LibWeb/Painting/DocumentPaintState.cpp@@ -105,11 +105,6 @@ void DocumentPaintState::republish_visual_animations(Layout::BegunRead const& reHTML::note_rendering_trace_event("compositor animations updated"sv);}-void DocumentPaintState::append_paint_command_cache_source_resources(Compositing::DisplayListResourceSet& retained_resources) const-{- retained_resources.include(m_paint_command_cache_source_referenced_resources);-}-Layout::RustFFI::FfiViewportMapping DocumentPaintState::viewport_mapping(DOM::Document const& document, Optional<MonotonicTime> visual_animation_sample_time, double device_pixels_per_css_pixel) const{Layout::ForcedReadScope read { document };diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.h b/Libraries/LibWeb/Painting/DocumentPaintState.hindex 50fe27bd0b5..5dcc70dc8be 100644--- a/Libraries/LibWeb/Painting/DocumentPaintState.h+++ b/Libraries/LibWeb/Painting/DocumentPaintState.h@@ -76,25 +76,12 @@ public:u64 visual_context_tree_structural_epoch(Layout::BegunRead const& read) const;- void set_display_list_used_as_paint_command_cache_source(RefPtr<Compositing::DisplayList> display_list, Compositing::DisplayListResourceSet referenced_resources)- {- m_display_list_used_as_paint_command_cache_source = move(display_list);- m_paint_command_cache_source_referenced_resources = move(referenced_resources);- }- Compositing::DisplayList* display_list_used_as_paint_command_cache_source() const { return m_display_list_used_as_paint_command_cache_source.ptr(); }- Compositing::DisplayListResourceSet const& paint_command_cache_source_referenced_resources() const { return m_paint_command_cache_source_referenced_resources; }-- void append_paint_command_cache_source_resources(Compositing::DisplayListResourceSet&) const;-private:Vector<String> m_recording_traces;NonnullRefPtr<Layout::NodeArena> m_layout_node_arena;Vector<Compositing::RustFFI::NodeSlotId> m_boxes_with_auto_content_visibility;-- RefPtr<Compositing::DisplayList> m_display_list_used_as_paint_command_cache_source;- Compositing::DisplayListResourceSet m_paint_command_cache_source_referenced_resources;};}diff --git a/Libraries/LibWeb/Painting/ImagePaint.h b/Libraries/LibWeb/Painting/ImagePaint.hindex 34ea7d02f09..8276832eb98 100644--- a/Libraries/LibWeb/Painting/ImagePaint.h+++ b/Libraries/LibWeb/Painting/ImagePaint.h@@ -7,8 +7,6 @@#pragma once#include <AK/Variant.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibGC/Ptr.h>#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Rect.h>@@ -17,23 +15,41 @@#include <LibWeb/CSS/StyleValues/StyleValue.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>+#include <LibWeb/HTML/PaintConfig.h>#include <LibWebCommon/CSS/PreferredColorScheme.h>+#include <LibWebCommon/PixelUnits.h>++namespace Web::Layout::RustFFI {++struct DocumentHost;++}namespace Web::Painting {+// What an SVG image is rendered for: two renderings for one key show the same.+struct VectorImageKey {+ CSSPixelSize css_size;+ float raster_scale { 1 };+ CSS::PreferredColorScheme color_scheme;+ HTML::PaintConfig paint_config;+};+struct ImagePaint {struct DecodedFrame {Gfx::DecodedImageFrame frame;Gfx::IntSize natural_size;};- struct NestedDisplayList {- Compositing::DisplayListResource resource;+ // An SVG image, which the host of its document keeps rendered for the key.+ struct VectorImage {+ Layout::RustFFI::DocumentHost const* host;+ VectorImageKey key;Gfx::IntSize list_size;};struct Gradient {NonnullRefPtr<CSS::StyleValue const> style_value;};- Variant<DecodedFrame, NestedDisplayList, Gradient> value;+ Variant<DecodedFrame, VectorImage, Gradient> value;};struct ImagePaintRequest {@@ -43,7 +59,6 @@ struct ImagePaintRequest {CSS::PreferredColorScheme color_scheme;CSS::ColorResolutionStyle gradient_stop_color_resolution_style;Gfx::FloatSize accumulated_scale;- Compositing::DisplayListResourceStorage& resource_storage;};}diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cppindex 222ad362aba..c89227969da 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp@@ -6,8 +6,6 @@#include <AK/StdLibExtras.h>#include <AK/StringBuilder.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCore/ElapsedTimer.h>#include <LibCore/Environment.h>#include <LibGfx/CornerRadii.h>@@ -18,6 +16,8 @@#include <LibWeb/CSS/Enums.h>#include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h>#include <LibWeb/CSS/VisualViewport.h>+#include <LibWeb/Compositor/CompositorHost.h>+#include <LibWeb/Compositor/NavigablePresenter.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/DOM/Node.h>@@ -244,25 +244,20 @@ static void push_debug_description(DOM::Document const& document, Compositing::RLayout::RustFFI::layout_arena_paint_push_bytes(description_sink, bytes.data(), bytes.size());}-Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Document const& document, Compositing::DisplayList const& display_list, Compositing::DisplayListResourceStorage const& resource_storage)+Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Document const& document){struct DumpContext {GC::Ref<DOM::Document const> document;- Compositing::DisplayListResourceStorage const& resource_storage;Utf16String dump;- } context { document, resource_storage, {} };+ } context { document, {} };Layout::RustFFI::FfiPaintingDumpCallbacks callbacks {.context = &context,.debug_description = [](void* context_pointer, Compositing::RustFFI::NodeSlotId slot, void* description_sink) { push_debug_description(*static_cast<DumpContext*>(context_pointer)->document, slot, description_sink); },- .nested_display_list = [](void* context_pointer, u64 display_list_id) -> void const* {- auto& context = *static_cast<DumpContext*>(context_pointer);- return context.resource_storage.display_list(Compositing::DisplayListResourceId { display_list_id }).rust_handle();- },.append_text = [](void* context_pointer, u8 const* bytes, size_t byte_count) { static_cast<DumpContext*>(context_pointer)->dump = Utf16String::from_utf8_without_validation(StringView { bytes, byte_count }); },};Gfx::IntRect device_viewport_rect { {}, document.page().css_to_device_rect(document.viewport_rect()).size().to_type<int>() };- Layout::RustFFI::painting_dump(document_host(document), &read, viewport_row_slot(read, document), display_list.rust_handle(), device_viewport_rect, callbacks);+ Layout::RustFFI::painting_dump(document_host(document), &read, viewport_row_slot(read, document), device_viewport_rect, callbacks);return move(context.dump);}@@ -352,10 +347,9 @@ void dump_layout_tree(StringBuilder& builder, Layout::Node const& root, bool intnamespace {-// What a recording's publication adds its resources to, and what an SVG-as-image render is found from: the document's-// host, through which a layout node of the recording is reached.+// What an SVG-as-image render of a recording's publication is found from: the document's host, through which a layout+// node of the recording is reached.struct RecordingPublishContext {- Compositing::DisplayListResourceStorage& resource_storage;Layout::RustFFI::DocumentHost* host;Layout::BegunRead const& read;};@@ -364,20 +358,11 @@ static Layout::RustFFI::FfiRecordingPublishCallbacks recording_publish_callbacks{return {.context = &context,- .add_font = [](void* context_pointer, void const* font) {- auto& context = *static_cast<RecordingPublishContext*>(context_pointer);- context.resource_storage.add_font(*static_cast<Gfx::Font const*>(font)); },- .add_image_frame = [](void* context_pointer, void const* frame) {+ .render_vector_image = [](void* context_pointer, Layout::RustFFI::FfiVectorImageRenderRequest const* request) -> Layout::RustFFI::DocumentHost const* {auto& context = *static_cast<RecordingPublishContext*>(context_pointer);- context.resource_storage.add_image_frame(*static_cast<Gfx::DecodedImageFrame const*>(frame)); },- .resolve_vector_image_display_list = [](void* context_pointer, Layout::RustFFI::FfiVectorImageRenderRequest const* request) -> u64 {- auto& context = *static_cast<RecordingPublishContext*>(context_pointer);- auto empty_display_list = [&] {- return context.resource_storage.add_display_list(Compositing::DisplayListResource { Compositing::DisplayList::create_empty() }).value();- };auto const* layout_node = static_cast<Layout::NodeWithStyle const*>(Layout::RustFFI::render_state_node_shell_if_live(context.host, &context.read, request->owner));if (!layout_node)- return empty_display_list();+ return nullptr;GC::Ptr<HTML::DecodedImageData> decoded_image_data;// A recording that lands after its boxes' elements were removed may draw a box whose element is gone.if (request->is_replaced_content) {@@ -392,20 +377,14 @@ static Layout::RustFFI::FfiRecordingPublishCallbacks recording_publish_callbacks}auto const* svg_image_data = as_if<SVG::SVGDecodedImageData>(decoded_image_data.ptr());if (!svg_image_data)- return empty_display_list();+ return nullptr;// The image's content darkens with the page that draws it, so a force-dark page renders it force-dark too.HTML::PaintConfig paint_config;paint_config.force_dark_enabled = request->force_dark_enabled;paint_config.force_dark_foreground_threshold = request->force_dark_foreground_threshold;paint_config.force_dark_background_threshold = request->force_dark_background_threshold;- auto display_list = svg_image_data->record_display_list_at_scale({ request->css_width, request->css_height }, request->raster_scale, static_cast<CSS::PreferredColorScheme>(request->color_scheme), paint_config, context.resource_storage);- if (!display_list.has_value())- return empty_display_list();- return context.resource_storage.add_display_list(move(*display_list)).value();+ return svg_image_data->render_at_scale({ { request->css_width, request->css_height }, request->raster_scale, static_cast<CSS::PreferredColorScheme>(request->color_scheme), paint_config });},- .add_video_sink = [](void* context_pointer, u64 resource_id, u64 sink_handle) {- auto& context = *static_cast<RecordingPublishContext*>(context_pointer);- context.resource_storage.add_video_sink(Compositing::VideoSinkResourceId { resource_id }, Media::VideoSinkHandle { sink_handle }); },};}@@ -453,16 +432,12 @@ static double rendering_update_timestamp(DOM::Document& document)return -AK::Infinity<double>;}-// Hands the render owner `presentation` and its seal, which the host gives up.-static Layout::RustFFI::FfiPresentation give_up(Compositor::FlightPresentation presentation)-{- return { .presenter = &presentation.presenter.leak_ref(), .sealed = presentation.sealed.leak_ptr() };-}-void commit_unrecorded_frame(Layout::BegunRead const& read, DOM::Document& document, Compositor::FlightPresentation presentation){- bool const sends_visual_context_tree = presentation.sealed->sends_visual_context_tree;- Layout::RustFFI::render_state_commit_unrecorded_frame(document_host(document), &read, sends_visual_context_tree, rendering_update_timestamp(document), give_up(move(presentation)));+ bool const sends_visual_context_tree = presentation.sealed.sends_visual_context_tree;+ presentation.presenter->lend_seal(presentation.sealed, [&](Layout::RustFFI::FfiSeal const& seal) {+ Layout::RustFFI::render_state_commit_unrecorded_frame(document_host(document), &read, sends_visual_context_tree, rendering_update_timestamp(document), &seal);+ });}Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunRead const& read, DOM::Document& document, u64 visual_context_tree_structural_epoch, Optional<Gfx::Color> surface_clear_color, PaintCommandCacheMode cache_mode, HTML::PaintConfig const& config, InspectorOverlayInputs const& overlay_inputs, Optional<Compositor::FlightPresentation> committed)@@ -622,7 +597,7 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunReinputs.background_color = document.background_color(read);}inputs.has_navigable_container_with_composited_context = reconcile_navigable_container_paint_facts(read, document);- Optional<Compositing::AsyncScrollingMetadata> async_scrolling_metadata;+ inputs.surface_clear_color = surface_clear_color;if (auto navigable = document.navigable()) {bool viewport_keeps_horizontal_scrolls = false;bool viewport_keeps_vertical_scrolls = false;@@ -630,8 +605,10 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunReviewport_keeps_horizontal_scrolls = Painting::box_ending_scroll_chain(*viewport_box, 1, 0) == viewport_box;viewport_keeps_vertical_scrolls = Painting::box_ending_scroll_chain(*viewport_box, 0, 1) == viewport_box;}- async_scrolling_metadata = Compositing::AsyncScrollingMetadata {- .document_id = document.unique_id(),+ inputs.has_async_scrolling_metadata = true;+ inputs.async_scrolling_metadata = {+ .has_document_id = true,+ .document_id = document.unique_id().value(),.viewport_rect = device_viewport_rect.to_type<int>(),.wheel_event_listener_state_generation = navigable->page().wheel_event_listener_state_generation(),.has_blocking_wheel_event_listeners = wheel_event_region_state.has_blocking_wheel_event_listeners,@@ -643,19 +620,17 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunRe}DisplayListRecording recording {.visual_context_tree_structural_epoch = visual_context_tree_structural_epoch,- .surface_clear_color = surface_clear_color,.cache_mode = cache_mode,.in_flight = false,- .async_scrolling_metadata = async_scrolling_metadata,- .paint_command_cache_source = document.paint_state().display_list_used_as_paint_command_cache_source(),};// The recording copies what it reads of the overlay arrays and buffers, which live until here.auto viewport = viewport_row_slot(read, document);- // A committed frame takes the presentation it presents with, which the landing gives back.+ // A committed frame hands the render owner what it presents with.if (committed.has_value()) {- committed->sealed->recording = recording;recording.in_flight = true;- Layout::RustFFI::render_state_commit_recorded_frame(host, &read, viewport, inputs, rendering_update_timestamp(document), give_up(committed.release_value()));+ committed->presenter->lend_seal(committed->sealed, [&](Layout::RustFFI::FfiSeal const& seal) {+ Layout::RustFFI::render_state_commit_recorded_frame(host, &read, viewport, inputs, rendering_update_timestamp(document), &seal);+ });return recording;}if (Layout::RustFFI::render_state_record_display_list(host, &read, viewport, inputs) == Layout::RustFFI::FfiRecordingStart::NothingToRecord)@@ -665,108 +640,69 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunRevoid render_vector_images(Layout::BegunRead const& read, DOM::Document& document){- auto resources = make<Compositor::VectorImageResources>();- RecordingPublishContext publish_context { resources->storage, document_host(document), read };- Layout::RustFFI::render_state_render_vector_images(publish_context.host, recording_publish_callbacks(publish_context), resources.leak_ptr());+ RecordingPublishContext publish_context { document_host(document), read };+ Layout::RustFFI::render_state_render_vector_images(publish_context.host, recording_publish_callbacks(publish_context));}-RefPtr<Compositing::DisplayList> finish_rust_display_list_recording(Layout::BegunRead const& read, DOM::Document& document, DisplayListRecording const& recording, Compositing::DisplayListResourceStorage& resource_storage)+void publish_rust_display_list_recording(Layout::BegunRead const& read, DOM::Document& document){- RecordingPublishContext publish_context { resource_storage, document_host(document), read };+ RecordingPublishContext publish_context { document_host(document), read };auto rust_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);- Layout::RustFFI::FfiPresentedRecording presented {};- Layout::RustFFI::render_state_publish_recording(publish_context.host, &read, recording_publish_callbacks(publish_context), &presented);+ Layout::RustFFI::render_state_publish_recording(publish_context.host, recording_publish_callbacks(publish_context));take_recording_trace_if_pending(read, document);- auto display_list = display_list_of_published_recording(recording, presented);if (rust_painting_timing_enabled())- dbgln("PAINT_RECORD rust={} µs commands={} bytes", rust_timer.elapsed_time().to_microseconds(), display_list->tape_size());- return display_list;+ dbgln("PAINT_RECORD rust={} µs", rust_timer.elapsed_time().to_microseconds());}-NonnullRefPtr<Compositing::DisplayList> display_list_of_published_recording(DisplayListRecording const& recording, Layout::RustFFI::FfiPresentedRecording const& presented)+Layout::RustFFI::FfiVectorImageKey vector_image_key_to_ffi(VectorImageKey const& key){- auto stamp_async_scrolling_metadata = [&](Compositing::DisplayList& display_list) {- auto metadata = recording.async_scrolling_metadata;- if (!metadata.has_value())- return;- metadata->has_blocking_wheel_event_listeners |= presented.has_blocking_wheel_event_listeners;- display_list.set_async_scrolling_metadata(*metadata);+ return {+ .css_width = key.css_size.width(),+ .css_height = key.css_size.height(),+ .raster_scale = key.raster_scale,+ .color_scheme = static_cast<u8>(key.color_scheme),+ .force_dark_enabled = key.paint_config.force_dark_enabled,+ .force_dark_foreground_threshold = key.paint_config.force_dark_foreground_threshold,+ .force_dark_background_threshold = key.paint_config.force_dark_background_threshold,};-- if (presented.is_identical_to_published_recording) {- if (auto source = recording.paint_command_cache_source) {- stamp_async_scrolling_metadata(*source);- return source.release_nonnull();- }- }-- auto display_list = Compositing::DisplayList::share_rust_recording(presented.display_list, presented.visual_context_tree);- if (recording.surface_clear_color.has_value())- display_list->set_surface_clear_color(*recording.surface_clear_color);- display_list->set_root_group_color(presented.root_group_color);- stamp_async_scrolling_metadata(*display_list);- return display_list;-}--NonnullRefPtr<Compositing::DisplayList> nestable_display_list_of_last_recording(Layout::BegunRead const& read, DOM::Document const& document, NonnullRefPtr<Compositing::DisplayList> published)-{- Layout::RustFFI::FfiPresentedRecording last {};- Layout::RustFFI::render_state_last_recording(document_host(document), &read, &last);- if (published->was_recorded_against(last.visual_context_tree))- return published;- auto display_list = Compositing::DisplayList::share_rust_recording(last.display_list, last.visual_context_tree);- if (auto surface_clear_color = published->surface_clear_color(); surface_clear_color.has_value())- display_list->set_surface_clear_color(*surface_clear_color);- display_list->set_root_group_color(published->root_group_color());- return display_list;-}--static Compositing::DisplayListResource record_image_paint(Layout::RustFFI::FfiImagePaintRecordInputs const& inputs)-{- Optional<Compositing::DisplayListResource> recorded_display_list;- Layout::RustFFI::ladybird_web_record_image_paint_display_list(&inputs, &recorded_display_list,- [](void* context, void const* retained_commands, void const* retained_tree) {- auto display_list = Compositing::DisplayList::adopt_rust_recording(retained_commands, retained_tree);- *static_cast<Optional<Compositing::DisplayListResource>*>(context) = Compositing::DisplayListResource { move(display_list) };- });- return recorded_display_list.release_value();}-Compositing::DisplayListResource record_image_paint_display_list(ImagePaint const& paint, ImagePaintRequest const& request, double device_pixels_per_css_pixel)+bool rasterize_image_paint(Compositor::CompositorHost const& compositor_host, ImagePaint const& paint, ImagePaintRequest const& request, double device_pixels_per_css_pixel, NonnullRefPtr<Gfx::Bitmap> target){- Layout::RustFFI::FfiImagePaintRecordInputs inputs {};- inputs.dest_rect = request.dest_rect;- inputs.device_pixels_per_css_pixel = device_pixels_per_css_pixel;+ Layout::RustFFI::FfiImageRasterization image {};+ image.dest_rect = request.dest_rect;+ image.device_pixels_per_css_pixel = device_pixels_per_css_pixel;auto gradient_stop_color_resolution_style = request.gradient_stop_color_resolution_style.to_ffi();paint.value.visit([&](ImagePaint::DecodedFrame const& decoded_frame) {- inputs.kind = Layout::RustFFI::FfiImagePaintRecordKind::DecodedFrame;- inputs.frame_id = request.resource_storage.add_image_frame(decoded_frame.frame).value();- inputs.scaling_mode = CSS::to_gfx_scaling_mode(request.image_rendering, decoded_frame.natural_size, request.dest_rect.to_rounded<int>().size());+ image.kind = Layout::RustFFI::FfiImageRasterizationKind::DecodedFrame;+ image.image_frame = &decoded_frame.frame;+ image.scaling_mode = CSS::to_gfx_scaling_mode(request.image_rendering, decoded_frame.natural_size, request.dest_rect.to_rounded<int>().size());},- [&](ImagePaint::NestedDisplayList const& nested) {- inputs.kind = Layout::RustFFI::FfiImagePaintRecordKind::NestedDisplayList;- inputs.nested_display_list_id = request.resource_storage.add_display_list(Compositing::DisplayListResource { nested.resource }).value();- inputs.nested_display_list_size = nested.list_size;+ [&](ImagePaint::VectorImage const& vector_image) {+ image.kind = Layout::RustFFI::FfiImageRasterizationKind::VectorImage;+ image.vector_image_host = vector_image.host;+ image.vector_image_key = vector_image_key_to_ffi(vector_image.key);+ image.vector_image_size = vector_image.list_size;},[&](ImagePaint::Gradient const& gradient) {- inputs.kind = Layout::RustFFI::FfiImagePaintRecordKind::Gradient;- inputs.gradient_style_value = gradient.style_value->rust_style_value_data();- inputs.gradient_tile_size = request.dest_rect.size().to_type<CSSPixels>();- inputs.gradient_stop_color_resolution_style = &gradient_stop_color_resolution_style;+ image.kind = Layout::RustFFI::FfiImageRasterizationKind::Gradient;+ image.gradient_style_value = gradient.style_value->rust_style_value_data();+ image.gradient_tile_size = request.dest_rect.size().to_type<CSSPixels>();+ image.gradient_stop_color_resolution_style = &gradient_stop_color_resolution_style;});- return record_image_paint(inputs);+ return compositor_host.rasterize_image(image, move(target));}-Compositing::DisplayListResource record_image_frame_display_list(Gfx::DecodedImageFrame const& frame, Gfx::FloatRect const& dest_rect, Gfx::ScalingMode scaling_mode, Compositing::DisplayListResourceStorage& resource_storage)+bool rasterize_image_frame(Compositor::CompositorHost const& compositor_host, Gfx::DecodedImageFrame const& frame, Gfx::FloatRect const& dest_rect, Gfx::ScalingMode scaling_mode, NonnullRefPtr<Gfx::Bitmap> target){- Layout::RustFFI::FfiImagePaintRecordInputs inputs {};- inputs.kind = Layout::RustFFI::FfiImagePaintRecordKind::DecodedFrame;- inputs.dest_rect = dest_rect;- inputs.device_pixels_per_css_pixel = 1;- inputs.frame_id = resource_storage.add_image_frame(frame).value();- inputs.scaling_mode = scaling_mode;- return record_image_paint(inputs);+ Layout::RustFFI::FfiImageRasterization image {};+ image.kind = Layout::RustFFI::FfiImageRasterizationKind::DecodedFrame;+ image.dest_rect = dest_rect;+ image.device_pixels_per_css_pixel = 1;+ image.image_frame = &frame;+ image.scaling_mode = scaling_mode;+ return compositor_host.rasterize_image(image, move(target));}}diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.h b/Libraries/LibWeb/Painting/PaintingRustBridge.hindex af423d0d22a..19ebd0681ef 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.h+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.h@@ -7,7 +7,6 @@#pragma once#include <AK/Types.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h>#include <LibWeb/Compositor/NavigablePresenter.h>#include <LibWeb/Export.h>@@ -22,6 +21,7 @@namespace Web::Compositor {+class CompositorHost;struct FlightPresentation;}@@ -64,24 +64,21 @@ WEB_API Optional<DisplayListRecording> start_rust_display_list_recording(Layout:// Commits the navigable's next frame, which keeps the display list the compositor has, to the render owner, which// presents it with `presentation` beside the event loop.WEB_API void commit_unrecorded_frame(Layout::BegunRead const&, DOM::Document&, Compositor::FlightPresentation presentation);-// Renders the SVG images of the document's committed frame that waits for them, which only the main thread renders, into-// a resource storage of their own, and hands the frame back to the Paint thread, which presents it with them.+// Renders the SVG images of the document's committed frame that waits for them, which only the main thread renders, and+// hands the frame back to the Paint thread, which presents it with them.WEB_API void render_vector_images(Layout::BegunRead const&, DOM::Document&);-// Publishes the recording, which has landed and stands, and makes its display list from what was sealed where it began.-WEB_API RefPtr<Compositing::DisplayList> finish_rust_display_list_recording(Layout::BegunRead const&, DOM::Document&, DisplayListRecording const&, Compositing::DisplayListResourceStorage&);+// Publishes the recording, which has landed and stands.+WEB_API void publish_rust_display_list_recording(Layout::BegunRead const&, DOM::Document&);// Hands the document the trace the recording it took in last left, if it left one.WEB_API void take_recording_trace_if_pending(Layout::BegunRead const&, DOM::Document&);-// Makes the display list of `recording`, published as `presented` says, from what the recording sealed where it began.-// Reads no document, so it runs wherever the recording is published.-WEB_API NonnullRefPtr<Compositing::DisplayList> display_list_of_published_recording(DisplayListRecording const&, Layout::RustFFI::FfiPresentedRecording const&);-// `published`, the display list the document's last recording published, as another display list nests it: with the-// visual context tree that recording was recorded against. A recording that repeats the list it published before-// publishes that list again, which holds the tree of the recording before.-WEB_API NonnullRefPtr<Compositing::DisplayList> nestable_display_list_of_last_recording(Layout::BegunRead const&, DOM::Document const&, NonnullRefPtr<Compositing::DisplayList> published);-WEB_API Utf16String serialize_painting_dump(Layout::BegunRead const&, DOM::Document const&, Compositing::DisplayList const&, Compositing::DisplayListResourceStorage const&);+// Dumps the display list the document recorded last.+WEB_API Utf16String serialize_painting_dump(Layout::BegunRead const&, DOM::Document const&);-WEB_API Compositing::DisplayListResource record_image_paint_display_list(ImagePaint const&, ImagePaintRequest const&, double device_pixels_per_css_pixel);-// Records one image frame drawn into the destination rectangle, in device pixels.-WEB_API Compositing::DisplayListResource record_image_frame_display_list(Gfx::DecodedImageFrame const&, Gfx::FloatRect const& dest_rect, Gfx::ScalingMode, Compositing::DisplayListResourceStorage&);+WEB_API Layout::RustFFI::FfiVectorImageKey vector_image_key_to_ffi(VectorImageKey const&);+// Has the compositor rasterize `paint` into `target` as `request` asks, which must be a shareable BGRA8888 bitmap with+// premultiplied alpha. Returns false if nothing was drawn.+WEB_API bool rasterize_image_paint(Compositor::CompositorHost const&, ImagePaint const&, ImagePaintRequest const&, double device_pixels_per_css_pixel, NonnullRefPtr<Gfx::Bitmap> target);+// Has the compositor rasterize one image frame drawn into the destination rectangle, in device pixels, into `target`.+WEB_API bool rasterize_image_frame(Compositor::CompositorHost const&, Gfx::DecodedImageFrame const&, Gfx::FloatRect const& dest_rect, Gfx::ScalingMode, NonnullRefPtr<Gfx::Bitmap> target);}diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex aa1f65e0a67..ca21846ddd0 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -3148,6 +3148,18 @@ fn main() -> Result<(), Box<dyn Error>> {layout_config.includes.push("LibWeb/Layout/TreeBuilderRustFFI.h".to_string());+ // Rust posts to the compositor through a poster C++ made.+ layout_config+ .export+ .exclude+ .push("FfiThreadSafeMessagePoster".to_string());+ layout_config.export.rename.insert(+ "FfiThreadSafeMessagePoster".to_string(),+ "IPC::FfiThreadSafeMessagePoster".to_string(),+ );+ layout_config+ .includes+ .push("LibIPC/ThreadSafeMessagePoster.h".to_string());// A compositor animation effect state is opaque to C++, which holds it by pointer, and so are the paint server an// SVG paint resource callback fills and a parsed SVG path.for name in [@@ -3200,6 +3212,10 @@ fn main() -> Result<(), Box<dyn Error>> {manifest_dir.join("src/painting/paint_changes.rs"),manifest_dir.join("src/painting/ffi/main_thread_entries.rs"),manifest_dir.join("src/painting/paint_passes.rs"),+ manifest_dir.join("src/painting/presentation.rs"),+ manifest_dir.join("src/painting/vector_image_cache.rs"),+ manifest_dir.join("src/painting/recorded_scrolling.rs"),+ manifest_dir.join("src/painting/rasterize.rs"),],&out_dir,Path::new("Layout/LayoutRustFFI.h"),diff --git a/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs b/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rsindex fed6bee81be..14e12b38d63 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs@@ -231,4 +231,9 @@ extern "C" fn ladybird_gfx_process_next_structural_epoch() -> u64 {NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)}#[unsafe(no_mangle)]+extern "C" fn ladybird_gfx_process_next_display_list_id() -> u64 {+ static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);+ NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)+}+#[unsafe(no_mangle)]extern "C" fn unicode_layout_segmenter_destroy(_handle: *mut std::ffi::c_void) {}diff --git a/Libraries/LibWeb/Rust/src/paint_stage.rs b/Libraries/LibWeb/Rust/src/paint_stage.rsindex e3213af43b0..12a5765d1e9 100644--- a/Libraries/LibWeb/Rust/src/paint_stage.rs+++ b/Libraries/LibWeb/Rust/src/paint_stage.rs@@ -4,15 +4,21 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The Paint thread, and the stage it presents frames on: the frame sink frames reach the compositor through.+//! The Paint thread, and the stage it presents frames on: the poster frames reach the compositor through.//!//! Presenting a frame takes a [`Presenting`], which only the jobs this module hands the Paint thread are lent, there,-//! and which alone reaches the frame sink. The Paint thread runs its jobs one at a time and in the order they were-//! handed to it, so frames reach the compositor in the order their jobs were handed out, and code that runs anywhere-//! else cannot present a frame: it has no [`Presenting`] to present with.+//! and which alone reaches the poster. The Paint thread runs its jobs one at a time and in the order they were handed to+//! it, so frames reach the compositor in the order their jobs were handed out, and code that runs anywhere else cannot+//! present a frame: it has no [`Presenting`] to present with.+use crate::painting::display_list::commands::CompositorContextId;use crate::render_state::SampledFrame;use crate::stage_thread::{InFlight, Relay, Riding, StageThread};+use libcompositing_rust::ipc_types::Core_AnonymousBuffer;+use libgfx_rust::font::FontHandle;+use libgfx_rust::image_frame::ImageFrameHandle;+use libipc_rust::cpp_connection::{FfiThreadSafeMessagePoster, ThreadSafeMessagePoster};+use libipc_rust::wire::{EndpointMessage, File};use std::cell::RefCell;use std::ffi::c_void;use std::marker::PhantomData;@@ -20,9 +26,163 @@ use std::ptr::NonNull;use std::sync::OnceLock;unsafe extern "C" {- fn web_frame_sink_release(sink: *mut c_void);- fn web_frame_sink_request_screenshot(sink: *mut c_void, request: *mut c_void);+ fn web_compositor_post_fonts_and_image_frames(+ poster: *mut c_void,+ context_id: u64,+ fonts: *const *const c_void,+ font_count: usize,+ image_frames: *const *const c_void,+ image_frame_count: usize,+ ) -> bool;+ fn web_compositor_create_shared_buffer(size: usize, out: &mut FfiSharedBuffer) -> bool;+ fn web_compositor_shared_buffer_release(owner: *mut c_void);+ fn web_compositor_post_screenshot_request(poster: *mut c_void, request: *mut c_void) -> bool;fn web_screenshot_request_destroy(request: *mut c_void);+ fn web_compositor_stage_rasterization(+ poster: *mut c_void,+ token: u64,+ fonts: *const *const c_void,+ font_count: usize,+ image_frames: *const *const c_void,+ image_frame_count: usize,+ video_sinks: *const u64,+ video_sink_count: usize,+ target_bitmap: *const c_void,+ ) -> bool;+}++/// Shared memory C++ made for a message, which the caller writes and then releases: `Web::Compositor::FfiSharedBuffer`.+#[repr(C)]+pub struct FfiSharedBuffer {+ data: *mut u8,+ size: usize,+ /// A descriptor of the memory of its own, which the caller takes over.+ descriptor: i32,+ owner: *mut c_void,+}++/// Posts messages to the compositor from the thread that holds it: Rust encodes what it can, and C++ the fonts, image+/// frames and screenshot targets, which are C++ objects.+pub(crate) struct CompositorPoster(ThreadSafeMessagePoster);++impl CompositorPoster {+ /// Takes over the reference `ffi` holds.+ ///+ /// # Safety+ ///+ /// `ffi` must hold one reference to a live poster on the transport of the connection to the compositor.+ pub(crate) unsafe fn adopt(ffi: FfiThreadSafeMessagePoster) -> Self {+ // SAFETY: Guaranteed by the caller.+ Self(unsafe { ThreadSafeMessagePoster::adopt(ffi) })+ }++ /// Posts `message`, and answers whether the compositor could still be reached.+ pub(crate) fn post<M: EndpointMessage>(&self, message: M) -> bool {+ self.0.try_post(message).expect("a message to the compositor encodes")+ }++ /// Posts `fonts` and `image_frames` for the compositor context `context_id` names to hold, ahead of the transaction+ /// that names them, and answers whether the compositor could still be reached.+ pub(crate) fn post_fonts_and_image_frames(+ &self,+ context_id: CompositorContextId,+ fonts: &[FontHandle],+ image_frames: &[ImageFrameHandle],+ ) -> bool {+ if fonts.is_empty() && image_frames.is_empty() {+ return true;+ }+ let fonts: Vec<*const c_void> = fonts.iter().map(FontHandle::as_raw).collect();+ let image_frames: Vec<*const c_void> = image_frames.iter().map(ImageFrameHandle::as_raw).collect();+ // SAFETY: This holds a reference to the poster, and the handles keep the fonts and frames live for the call, in+ // which C++ takes references of its own.+ unsafe {+ web_compositor_post_fonts_and_image_frames(+ self.0.as_cpp_poster(),+ context_id.0,+ fonts.as_ptr(),+ fonts.len(),+ image_frames.as_ptr(),+ image_frames.len(),+ )+ }+ }++ /// Shared memory of `size` bytes that `write` fills, as a message carries it, or none where it cannot be made. The+ /// memory is sealed where the platform supports it, so the receiver cannot be faulted by the file shrinking.+ pub(crate) fn shared_buffer_with(+ &self,+ size: usize,+ write: impl FnOnce(&mut [u8]),+ ) -> Option<Core_AnonymousBuffer> {+ if size == 0 {+ return Some(Core_AnonymousBuffer { shared_memory: None });+ }+ let mut buffer = FfiSharedBuffer {+ data: std::ptr::null_mut(),+ size: 0,+ descriptor: -1,+ owner: std::ptr::null_mut(),+ };+ // SAFETY: C++ fills `buffer` where it answers true.+ if !unsafe { web_compositor_create_shared_buffer(size, &mut buffer) } {+ return None;+ }+ assert_eq!(buffer.size, size);+ // SAFETY: C++ mapped `size` writable bytes at `data`, which stay mapped until the owner is released.+ write(unsafe { ak::slice_from_raw_parts_mut(buffer.data, size) });+ // SAFETY: The owner is released once, after the last write.+ unsafe { web_compositor_shared_buffer_release(buffer.owner) };+ #[cfg(unix)]+ // SAFETY: C++ hands over a descriptor of its own.+ let descriptor = unsafe { <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(buffer.descriptor) };+ #[cfg(windows)]+ // SAFETY: C++ hands over a descriptor of its own.+ let descriptor = unsafe { libipc_rust::transport_windows::OwnedDescriptor::from_raw(buffer.descriptor) };+ Some(Core_AnonymousBuffer {+ shared_memory: Some((size as u64, File(descriptor))),+ })+ }++ /// Stages `fonts`, `image_frames` and `video_sinks`, each a resource id and a sink handle, for the rasterization+ /// `token` names into `target_bitmap`, a shareable `Gfx::Bitmap`, and answers whether the compositor could still be+ /// reached.+ ///+ /// # Safety+ ///+ /// `target_bitmap` must be live for the call.+ pub(crate) unsafe fn stage_rasterization(+ &self,+ token: u64,+ fonts: &[FontHandle],+ image_frames: &[ImageFrameHandle],+ video_sinks: &[(u64, u64)],+ target_bitmap: *const c_void,+ ) -> bool {+ let fonts: Vec<*const c_void> = fonts.iter().map(FontHandle::as_raw).collect();+ let image_frames: Vec<*const c_void> = image_frames.iter().map(ImageFrameHandle::as_raw).collect();+ let video_sinks: Vec<u64> = video_sinks.iter().flat_map(|(id, handle)| [*id, *handle]).collect();+ // SAFETY: This holds a reference to the poster, the handles keep the fonts and frames live for the call, in+ // which C++ takes references of its own, and the caller keeps the bitmap live for it.+ unsafe {+ web_compositor_stage_rasterization(+ self.0.as_cpp_poster(),+ token,+ fonts.as_ptr(),+ fonts.len(),+ image_frames.as_ptr(),+ image_frames.len(),+ video_sinks.as_ptr(),+ video_sinks.len() / 2,+ target_bitmap,+ )+ }+ }++ /// The `IPC::ThreadSafeMessagePoster` this posts through, for C++ to post what it encodes.+ pub(crate) fn as_cpp_poster(&self) -> *mut c_void {+ self.0.as_cpp_poster()+ }}/// The Paint thread, which records display lists from the frames the render states publish, and presents frames.@@ -42,8 +202,8 @@ unsafe impl Sync for StageCell {}/// What the Paint thread presents with.#[derive(Default)]struct PaintStage {- /// The frame sink of the connection to the compositor, while there is one.- sink: Option<FrameSinkBox>,+ /// The poster of the connection to the compositor, while it can be reached.+ poster: Option<CompositorPoster>,}fn the_paint_thread() -> &'static PaintThread {@@ -62,29 +222,6 @@ pub(crate) fn paint_thread() -> &'static StageThread {&the_paint_thread().thread}-/// A reference to a `Web::Compositor::CompositorFrameSink`, which only the Paint stage holds. The pointer makes it-/// neither [`Send`] nor [`Sync`]: it never leaves the Paint thread.-struct FrameSinkBox(NonNull<c_void>);--impl Drop for FrameSinkBox {- fn drop(&mut self) {- // SAFETY: The box holds a reference to the sink.- unsafe { web_frame_sink_release(self.0.as_ptr()) };- }-}--/// A reference to a frame sink on its way to the Paint stage.-struct IncomingFrameSink(FrameSinkBox);--// SAFETY: A frame sink takes frames from any thread, and nothing reaches this reference on the way.-unsafe impl Send for IncomingFrameSink {}--impl IncomingFrameSink {- fn arrive(self) -> FrameSinkBox {- self.0- }-}-/// What a job on the Paint thread presents with. Only this module makes one, on the Paint thread, for one job at a time./// The raw pointer marker makes it neither [`Send`] nor [`Sync`], so it cannot leave the job it is lent to.pub(crate) struct Presenting<'stage> {@@ -104,12 +241,15 @@ impl Presenting<'_> {})}- /// The frame sink frames are presented through, as C++ takes it, or null while the compositor cannot be reached.- pub(crate) fn sink(&self) -> *mut c_void {- self.stage- .sink- .as_ref()- .map_or(std::ptr::null_mut(), |sink| sink.0.as_ptr())+ /// The poster frames are presented through, or none while the compositor cannot be reached.+ pub(crate) fn poster(&self) -> Option<&CompositorPoster> {+ self.stage.poster.as_ref()+ }++ /// Drops the poster of a compositor that can no longer be reached: the connection learns of that on its own thread,+ /// and hands over the poster of the next one.+ pub(crate) fn lose_compositor(&mut self) {+ self.stage.poster = None;}}@@ -144,18 +284,25 @@ pub(crate) fn submit_presenting<T: Send + 'static, R: Send + 'static>(paint_thread().submit(move |_| Presenting::lend(|presenting| job(frame, presenting)))}-/// Has the Paint stage present frames through `sink`, a reference to the frame sink of a new connection to the-/// compositor, which the stage takes over, from the frames handed to the Paint thread after this on. Only the-/// connection calls this, which declares it.+/// A poster on the way to the Paint stage.+struct IncomingPoster(CompositorPoster);++// SAFETY: A poster posts from any thread, and nothing reaches it on the way.+unsafe impl Send for IncomingPoster {}++/// Has the Paint stage present frames through `poster`, a poster on the transport of a new connection to the compositor,+/// from the frames handed to the Paint thread after this on. Only the connection calls this, which declares it.////// # Safety///-/// `sink` must be a reference to a frame sink, which the caller gives up.+/// `poster` must hold one reference to a live poster, which the caller gives up.#[unsafe(no_mangle)]-pub unsafe extern "C" fn paint_stage_adopt_frame_sink(sink: NonNull<c_void>) {- let incoming = IncomingFrameSink(FrameSinkBox(sink));+pub unsafe extern "C" fn paint_stage_adopt_compositor_poster(poster: FfiThreadSafeMessagePoster) {+ // SAFETY: Guaranteed by the caller.+ let incoming = IncomingPoster(unsafe { CompositorPoster::adopt(poster) });paint_thread().post(move || {- Presenting::lend(|presenting| presenting.stage.sink = Some(incoming.arrive()));+ let IncomingPoster(poster) = incoming;+ Presenting::lend(|presenting| presenting.stage.poster = Some(poster));});}@@ -184,27 +331,63 @@ pub unsafe extern "C" fn paint_stage_request_screenshot(request: NonNull<c_void>let request = ScreenshotRequest(request);paint_thread().post(move || {Presenting::lend(|presenting| {- let sink = presenting.sink();- if sink.is_null() {+ let Some(poster) = presenting.poster() else {return;- }+ };let request = std::mem::ManuallyDrop::new(request);- // SAFETY: The stage holds the sink, and the sink takes the request over.- unsafe { web_frame_sink_request_screenshot(sink, request.0.as_ptr()) };+ // SAFETY: The stage holds the poster, and C++ takes the request over.+ if !unsafe { web_compositor_post_screenshot_request(poster.as_cpp_poster(), request.0.as_ptr()) } {+ presenting.lose_compositor();+ }});});}#[cfg(test)]mod ffi_test_stubs {+ use super::FfiSharedBuffer;use std::ffi::c_void;#[unsafe(no_mangle)]- extern "C" fn web_frame_sink_release(_: *mut c_void) {}+ extern "C" fn web_compositor_post_fonts_and_image_frames(+ _: *mut c_void,+ _: u64,+ _: *const *const c_void,+ _: usize,+ _: *const *const c_void,+ _: usize,+ ) -> bool {+ true+ }++ #[unsafe(no_mangle)]+ extern "C" fn web_compositor_create_shared_buffer(_: usize, _: &mut FfiSharedBuffer) -> bool {+ false+ }++ #[unsafe(no_mangle)]+ extern "C" fn web_compositor_shared_buffer_release(_: *mut c_void) {}#[unsafe(no_mangle)]- extern "C" fn web_frame_sink_request_screenshot(_: *mut c_void, _: *mut c_void) {}+ extern "C" fn web_compositor_post_screenshot_request(_: *mut c_void, _: *mut c_void) -> bool {+ true+ }#[unsafe(no_mangle)]extern "C" fn web_screenshot_request_destroy(_: *mut c_void) {}++ #[unsafe(no_mangle)]+ extern "C" fn web_compositor_stage_rasterization(+ _: *mut c_void,+ _: u64,+ _: *const *const c_void,+ _: usize,+ _: *const *const c_void,+ _: usize,+ _: *const u64,+ _: usize,+ _: *const c_void,+ ) -> bool {+ true+ }}diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rsindex c5c4f83e8cd..0e2a4379132 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs@@ -9,6 +9,7 @@ use super::commands::*;use super::effect_clip_plan::EffectClipPlan;use super::layers::{LayerPlan, LayerPlanInputs, build_layer_plan};use super::nested_records::{NestedRecordsRole, for_each_nested_record_span, span_bytes};+use super::storage::DisplayListStorage;use super::summary::{LiveContent, summarize};use crate::css::color_resolution::format_to_8bit_compatible;use crate::layout::LayoutNodeArena;@@ -45,8 +46,6 @@ pub struct FfiPaintingDumpCallbacks {context: *mut c_void,/// Describes the row in the slot, as its layout node describes itself.debug_description: extern "C" fn(context: *mut c_void, slot: NodeSlotId, description_sink: *mut c_void),- /// Answers the storage handle of a nested display list.- nested_display_list: extern "C" fn(context: *mut c_void, display_list_id: u64) -> *const c_void,append_text: extern "C" fn(context: *mut c_void, bytes: *const u8, byte_count: usize),}@@ -59,19 +58,24 @@ impl FfiPaintingDumpCallbacks {String::from_utf8_lossy(&description).into_owned()}- fn nested_display_list(&self, _: &MainThread, display_list_id: DisplayListResourceId) -> *const c_void {- // Nested ids come from records the host produced, so they resolve in its storage.- let display_list = (self.nested_display_list)(self.context, display_list_id.0);- assert!(!display_list.is_null());- display_list- }-fn append_text(&self, _: &MainThread, text: &str) {// The C++ sink copies the completed dump synchronously.(self.append_text)(self.context, text.as_ptr(), text.len());}}+/// The display lists the dumped one nests, at any depth.+struct DumpCallbacks<'a> {+ nested_display_lists: &'a HashMap<u64, std::sync::Arc<crate::painting::display_list_resources::NestedDisplayList>>,+}++impl DumpCallbacks<'_> {+ fn nested_display_list(&self, display_list_id: DisplayListResourceId) -> &DisplayListStorage {+ // Nested ids come from records the recording produced, so they resolve in what it draws.+ &self.nested_display_lists[&display_list_id.0].resource.storage+ }+}+struct VisualContextNodeOwners {spatial: HashMap<u32, NodeSlotId>,clip: HashMap<u32, NodeSlotId>,@@ -188,18 +192,30 @@ pub unsafe extern "C" fn painting_dump(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,viewport: NodeSlotId,- display_list: *const c_void,device_viewport_rect: IntRect,callbacks: FfiPaintingDumpCallbacks,) {- assert!(!display_list.is_null());// SAFETY: Guaranteed by the entry point's contract.let main_thread = unsafe { main_thread(host) };// SAFETY: As above.let visual_context_tree = unsafe { crate::painting::ffi::main_visual_context_tree(host, read) }.expect("a document with a committed viewport box has a visual context tree");let visual_context_tree = visual_context_tree.as_ref();- let (tape, command_runs) = unsafe { libcompositing_rust::display_list::storage::tape_of(display_list) };+ let recording =+ crate::painting::ffi::read_arena(host, read, (), |arena, ()| arena.paint_state().last_recording.clone())+ .expect("the dump records the document first");+ let display_list = DisplayListStorage::recorded(+ recording.display_list.clone(),+ recording+ .visual_context_tree+ .clone()+ .expect("a recording was recorded against a tree"),+ );+ let nested_display_lists = recording.resources.with_nested_resources().nested_display_lists;+ let dump_callbacks = DumpCallbacks {+ nested_display_lists: &nested_display_lists,+ };+ let (tape, command_runs) = (display_list.bytes(), display_list.command_runs());let owners = {crate::painting::ffi::read_arena(host, read, viewport, |arena, viewport| {let mut owners = VisualContextNodeOwners::collect(arena, viewport);@@ -225,9 +241,15 @@ pub unsafe extern "C" fn painting_dump(output.push_str("\nDisplayList:\n");match layer_plan {Some(layer_plan) => {- dump_top_level_commands_with_their_layers(&main_thread, &mut output, &callbacks, display_list, &layer_plan);+ dump_top_level_commands_with_their_layers(+ &main_thread,+ &mut output,+ &dump_callbacks,+ &display_list,+ &layer_plan,+ );}- None => dump_commands(&main_thread, &mut output, &callbacks, display_list, 0),+ None => dump_commands(&main_thread, &mut output, &dump_callbacks, &display_list, 0),}callbacks.append_text(&main_thread, &output);}@@ -287,12 +309,11 @@ fn dump_compositor_scroll_table(output: &mut String, table: &CompositorScrollTabfn dump_commands(main_thread: &MainThread,output: &mut String,- callbacks: &FfiPaintingDumpCallbacks,- display_list: *const c_void,+ callbacks: &DumpCallbacks,+ display_list: &DisplayListStorage,base_indent: usize,) {- // SAFETY: The caller keeps the storage live for the dump.- let (bytes, command_runs) = unsafe { libcompositing_rust::display_list::storage::tape_of(display_list) };+ let (bytes, command_runs) = (display_list.bytes(), display_list.command_runs());for run in command_runs {let run_bytes = &bytes[run.offset as usize..(run.offset + run.size) as usize];dump_command_bytes(main_thread, output, callbacks, run_bytes, run.context, base_indent);@@ -350,12 +371,11 @@ fn dump_layers_if_every_canvas_and_video_kept_updating(fn dump_top_level_commands_with_their_layers(main_thread: &MainThread,output: &mut String,- callbacks: &FfiPaintingDumpCallbacks,- display_list: *const c_void,+ callbacks: &DumpCallbacks,+ display_list: &DisplayListStorage,layer_plan: &LayerPlan,) {- // SAFETY: The caller keeps the storage live for the dump.- let (bytes, command_runs) = unsafe { libcompositing_rust::display_list::storage::tape_of(display_list) };+ let (bytes, command_runs) = (display_list.bytes(), display_list.command_runs());for run in command_runs {let run_bytes = &bytes[run.offset as usize..(run.offset + run.size) as usize];for_each_command(run_bytes, |_, offset_in_run, payload| {@@ -379,7 +399,7 @@ fn dump_top_level_commands_with_their_layers(fn dump_command_bytes(main_thread: &MainThread,output: &mut String,- callbacks: &FfiPaintingDumpCallbacks,+ callbacks: &DumpCallbacks,command_bytes: &[u8],context: ContextRef,base_indent: usize,@@ -414,7 +434,7 @@ fn dump_command_bytes(main_thread,output,callbacks,- callbacks.nested_display_list(main_thread, nested.display_list),+ callbacks.nested_display_list(nested.display_list),base_indent + 1,);});@@ -436,7 +456,7 @@ fn nested_display_lists(command_type: DisplayListCommandType, payload: &[u8]) ->fn dump_records_inside(main_thread: &MainThread,output: &mut String,- callbacks: &FfiPaintingDumpCallbacks,+ callbacks: &DumpCallbacks,command_type: DisplayListCommandType,payload: &[u8],context: ContextRef,diff --git a/Libraries/LibWeb/Rust/src/painting/display_list_resources.rs b/Libraries/LibWeb/Rust/src/painting/display_list_resources.rsnew file mode 100644index 00000000000..dbcd88ba828--- /dev/null+++ b/Libraries/LibWeb/Rust/src/painting/display_list_resources.rs@@ -0,0 +1,186 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What a display list draws besides its tape: fonts, image frames, video sinks and the display lists it nests, which+//! the list holds for as long as anything holds the list. The compositor is sent the ones it lacks ahead of the list.++use crate::painting::display_list::builder::RecordedDisplayList;+use crate::painting::display_list::ids::allocate_display_list_id;+use crate::painting::display_list::storage::DisplayListStorage;+use crate::painting::display_list::summary::{DisplayListSummary, summarize};+use crate::painting::visual_context::VisualContextTree;+use libcompositing_rust::ipc_types::{Compositing_DisplayListProperties, NestedDisplayListResource};+use libgfx_rust::font::FontHandle;+use libgfx_rust::image_frame::ImageFrameHandle;+use std::collections::{HashMap, HashSet};+use std::sync::Arc;++/// The resources a display list draws, each under the id its commands name it by.+#[derive(Clone, Default)]+pub(crate) struct DisplayListResources {+ pub(crate) fonts: HashMap<u64, FontHandle>,+ pub(crate) image_frames: HashMap<u64, ImageFrameHandle>,+ /// The handle of each video sink.+ pub(crate) video_sinks: HashMap<u64, u64>,+ pub(crate) nested_display_lists: HashMap<u64, Arc<NestedDisplayList>>,+}++impl DisplayListResources {+ /// Takes what `other` holds that this does not.+ pub(crate) fn include(&mut self, other: &Self) {+ for (id, font) in &other.fonts {+ self.fonts.entry(*id).or_insert_with(|| font.clone());+ }+ for (id, frame) in &other.image_frames {+ self.image_frames.entry(*id).or_insert_with(|| frame.clone());+ }+ for (id, handle) in &other.video_sinks {+ self.video_sinks.entry(*id).or_insert(*handle);+ }+ for (id, display_list) in &other.nested_display_lists {+ self.nested_display_lists+ .entry(*id)+ .or_insert_with(|| display_list.clone());+ }+ }++ /// These and what the display lists they nest draw, at any depth: everything the compositor needs to replay a list+ /// that draws these.+ pub(crate) fn with_nested_resources(&self) -> Self {+ let mut closure = self.clone();+ let mut pending: Vec<Arc<NestedDisplayList>> = self.nested_display_lists.values().cloned().collect();+ let mut visited: HashSet<u64> = closure.nested_display_lists.keys().copied().collect();+ while let Some(display_list) = pending.pop() {+ closure.include_own(&display_list.resources);+ for (id, nested) in &display_list.resources.nested_display_lists {+ if visited.insert(*id) {+ closure.nested_display_lists.insert(*id, nested.clone());+ pending.push(nested.clone());+ }+ }+ }+ closure+ }++ fn include_own(&mut self, other: &Self) {+ let nested = std::mem::take(&mut self.nested_display_lists);+ self.include(&Self {+ nested_display_lists: HashMap::new(),+ ..other.clone()+ });+ self.nested_display_lists = nested;+ }++ /// Takes what `source` holds of what `summary` names and this lacks: what a recording copied from the one it read+ /// paint commands from draws.+ pub(crate) fn complete_from(&mut self, summary: &DisplayListSummary, source: &Self) {+ for id in &summary.font_ids {+ if let Some(font) = source.fonts.get(id) {+ self.fonts.entry(*id).or_insert_with(|| font.clone());+ }+ }+ for id in &summary.image_frame_ids {+ if let Some(frame) = source.image_frames.get(id) {+ self.image_frames.entry(*id).or_insert_with(|| frame.clone());+ }+ }+ for id in &summary.video_sink_ids {+ if let Some(handle) = source.video_sinks.get(id) {+ self.video_sinks.entry(*id).or_insert(*handle);+ }+ }+ for id in &summary.display_list_ids {+ if let Some(display_list) = source.nested_display_lists.get(id) {+ self.nested_display_lists+ .entry(*id)+ .or_insert_with(|| display_list.clone());+ }+ }+ }++ pub(crate) fn ids(&self) -> ResourceIds {+ ResourceIds {+ fonts: self.fonts.keys().copied().collect(),+ image_frames: self.image_frames.keys().copied().collect(),+ video_sinks: self.video_sinks.keys().copied().collect(),+ display_lists: self.nested_display_lists.keys().copied().collect(),+ }+ }+}++/// The ids of resources a receiver holds.+#[derive(Clone, Default, Debug, PartialEq, Eq)]+pub(crate) struct ResourceIds {+ pub(crate) fonts: HashSet<u64>,+ pub(crate) image_frames: HashSet<u64>,+ pub(crate) video_sinks: HashSet<u64>,+ pub(crate) display_lists: HashSet<u64>,+}++/// A display list another one nests, such as an SVG image or an image paint: what the compositor stores under its id,+/// and what it draws.+pub(crate) struct NestedDisplayList {+ pub(crate) resource: NestedDisplayListResource,+ pub(crate) resources: DisplayListResources,+}++impl NestedDisplayList {+ /// The list `display_list` recorded against `visual_context_tree`, under a new id, drawing `resources`.+ pub(crate) fn recorded(+ display_list: Arc<RecordedDisplayList>,+ visual_context_tree: Arc<VisualContextTree>,+ root_group_color: libgfx_rust::Color,+ resources: DisplayListResources,+ ) -> Arc<Self> {+ let storage = DisplayListStorage::recorded(display_list, visual_context_tree.clone());+ Self::new(storage, visual_context_tree, root_group_color, resources)+ }++ /// An empty list, which stands in for an SVG image that has nothing to show.+ pub(crate) fn empty() -> Arc<Self> {+ let storage = DisplayListStorage::empty();+ let visual_context_tree = storage+ .visual_context_tree()+ .cloned()+ .expect("an empty list holds the tree it was recorded against");+ Self::new(+ storage,+ visual_context_tree,+ libgfx_rust::Color::TRANSPARENT,+ DisplayListResources::default(),+ )+ }++ fn new(+ storage: Arc<DisplayListStorage>,+ visual_context_tree: Arc<VisualContextTree>,+ root_group_color: libgfx_rust::Color,+ resources: DisplayListResources,+ ) -> Arc<Self> {+ Arc::new(Self {+ resource: NestedDisplayListResource {+ properties: Compositing_DisplayListProperties {+ id: allocate_display_list_id(),+ compatible_visual_context_tree_structural_epoch: visual_context_tree.structural_epoch,+ surface_clear_color: None,+ root_group_color,+ },+ storage,+ tree: visual_context_tree,+ },+ resources,+ })+ }++ pub(crate) fn id(&self) -> u64 {+ self.resource.properties.id+ }+}++/// The ids of the resources the commands of `display_list` name.+pub(crate) fn summary_of(display_list: &RecordedDisplayList) -> DisplayListSummary {+ summarize(&display_list.bytes, &display_list.command_runs)+}diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex ed6e2bfb343..12bc0484efa 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -13,8 +13,6 @@ use crate::layout::script_entries::FfiCaretPosition;use crate::layout::svg_formatting_context;use crate::layout::used_values::FfiCssPixelPoint;use crate::layout::used_values::FfiCssPixelRect;-use crate::layout::used_values::FfiCssPixelSize;-use crate::painting::force_dark::ForceDarkRole;use crate::painting::host::visual_context::FfiSvgFilterPrimitive;use crate::painting::paint_changes::{PaintChange, queue};use crate::painting::paint_read::{GeometryRead, PaintRead};@@ -455,106 +453,6 @@ pub enum FfiRecordingLanding {NeedsVectorImages,}-/// A navigable's presenter and the seal of the frame it presents next (`Web::Compositor::NavigablePresenter` and-/// `Web::Compositor::SealedPresentation`), which pass between the host and what presents a frame beside it. Both or-/// neither are null.-#[repr(C)]-pub struct FfiPresentation {- pub presenter: *mut c_void,- pub sealed: *mut c_void,-}--impl Default for FfiPresentation {- /// Names no presentation.- fn default() -> Self {- Self {- presenter: std::ptr::null_mut(),- sealed: std::ptr::null_mut(),- }- }-}--/// The visual context tree a presented frame goes with, which the presentation lends the presenter for the call: C++-/// passes it only to the entry points of the compositing crate, and keeps none of it.-#[repr(C)]-pub struct FfiPresentedVisualContextTree {- /// The tree, or null where the frame goes with none.- pub tree: *const c_void,- pub structural_epoch: u64,- /// The image frames the filters and backdrop filters of the tree's effects draw.- pub filter_image_frame_ids: *const u64,- pub filter_image_frame_id_count: usize,-}--/// Serializes the tree a presentation lends, for the compositor.-///-/// # Safety-///-/// `tree` must be what a presentation lends for the call, naming a tree; `append` is called synchronously with `sink`.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn presented_visual_context_tree_serialize(- tree: &FfiPresentedVisualContextTree,- sink: *mut c_void,- append: unsafe extern "C" fn(*mut c_void, *const u8, usize),-) {- assert!(!tree.tree.is_null());- // SAFETY: The presentation lends the tree for the call.- let tree = unsafe { &*tree.tree.cast::<crate::painting::visual_context::VisualContextTree>() };- let bytes = tree.to_bytes();- // SAFETY: The sink copies the bytes synchronously.- unsafe { append(sink, bytes.as_ptr(), bytes.len()) };-}--/// What the host reads of a published recording, to build its display list from.-#[repr(C)]-pub struct FfiPresentedRecording {- pub is_identical_to_published_recording: bool,- pub has_blocking_wheel_event_listeners: bool,- /// The recorded display list, which the document's last recording holds until the next- /// recording replaces it. The host takes a reference of its own to keep it longer.- pub display_list: *const c_void,- /// The visual context tree the display list was recorded against, held as the list is.- pub visual_context_tree: *const c_void,- /// The color the canvas holds below the recording's layers.- pub root_group_color: libgfx_rust::Color,-}--impl FfiPresentedRecording {- /// What the host reads of a recording published with `output`, whose display list `output` holds for as long as- /// the host reads it.- pub(crate) fn of_output(output: &crate::painting::record::RecordingOutput) -> Self {- Self {- is_identical_to_published_recording: output.is_identical_to_published_recording,- has_blocking_wheel_event_listeners: output.has_blocking_wheel_event_listeners,- display_list: std::sync::Arc::as_ptr(&output.display_list).cast(),- visual_context_tree: output- .visual_context_tree- .as_ref()- .map_or(std::ptr::null(), |tree| std::sync::Arc::as_ptr(tree).cast()),- root_group_color: output.root_group_color,- }- }-- /// What the host reads of the last recording the document took in.- pub(crate) fn of_last_recording(arena: &LayoutNodeArena) -> Self {- let paint_state = arena.paint_state();- let recording = paint_state.last_recording.as_deref();- Self {- is_identical_to_published_recording: recording- .is_some_and(|recording| recording.is_identical_to_published_recording),- has_blocking_wheel_event_listeners: recording- .is_some_and(|recording| recording.has_blocking_wheel_event_listeners),- display_list: recording.map_or(std::ptr::null(), |recording| {- std::sync::Arc::as_ptr(&recording.display_list).cast()- }),- visual_context_tree: recording- .and_then(|recording| recording.visual_context_tree.as_ref())- .map_or(std::ptr::null(), |tree| std::sync::Arc::as_ptr(tree).cast()),- root_group_color: recording.map_or(libgfx_rust::Color::TRANSPARENT, |recording| recording.root_group_color),- }- }-}-/// One `<area>` of an image map, as the document hands it over: the style-tree identity to name as/// the hit target, the state of its `shape` attribute, and where its parsed `coords` sit in the/// flat array published beside it.@@ -620,104 +518,6 @@ pub unsafe extern "C" fn layout_arena_svg_paint_resources_push_pattern();}-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u8)]-#[expect(dead_code, reason = "C++ constructs the variants")]-pub enum FfiImagePaintRecordKind {- DecodedFrame,- NestedDisplayList,- Gradient,-}--#[derive(Clone, Copy)]-#[repr(C)]-pub struct FfiImagePaintRecordInputs {- pub kind: FfiImagePaintRecordKind,- pub device_pixels_per_css_pixel: f64,- pub dest_rect: libgfx_rust::FloatRect,- pub frame_id: u64,- pub scaling_mode: libgfx_rust::ScalingMode,- pub nested_display_list_id: u64,- pub nested_display_list_size: libgfx_rust::IntSize,- pub gradient_style_value: *const c_void,- pub gradient_tile_size: FfiCssPixelSize,- /// The `FfiColorResolutionStyle` the gradient's color stops resolve against.- pub gradient_stop_color_resolution_style: *const c_void,-}--/// # Safety-///-/// `inputs`, and the gradient style value and color resolution style it points at, must be-/// live for the call. `consume` is called synchronously and takes ownership of the command-/// storage and visual context tree handles.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn ladybird_web_record_image_paint_display_list(- inputs: &FfiImagePaintRecordInputs,- context: *mut c_void,- consume: unsafe extern "C" fn(*mut c_void, *const c_void, *const c_void),-) {- use crate::css::color_resolution::ColorResolutionInput;- use crate::painting::display_list::commands::{DisplayListResourceId, ImageFrameResourceId};- use crate::painting::display_list::device_pixels::DevicePixelConverter;- use crate::painting::display_list::recorder::DisplayListRecorder;- use crate::painting::record::paint::gradient_resolution::{- record_resolved_gradient_fill, resolve_gradient_paint_with_input,- };- use crate::painting::visual_context::VisualContextTree;- use libgfx_rust::CompositingAndBlendingOperator;- let tree = VisualContextTree::create_identity();- // Force-dark never reaches here: an image is darkened by classifying the image itself — not by inverting the- // fills that raster it.- let mut recorder = DisplayListRecorder::new(None);- let dest_rect = inputs.dest_rect;- match inputs.kind {- FfiImagePaintRecordKind::DecodedFrame => recorder.draw_scaled_decoded_image_frame(- dest_rect,- None,- ImageFrameResourceId(inputs.frame_id),- inputs.scaling_mode,- CompositingAndBlendingOperator::Normal,- None,- ForceDarkRole::None,- ),- FfiImagePaintRecordKind::NestedDisplayList => recorder.paint_nested_display_list(- DisplayListResourceId(inputs.nested_display_list_id),- dest_rect,- inputs.nested_display_list_size,- ),- FfiImagePaintRecordKind::Gradient => {- // SAFETY: the host keeps the gradient style value and the style its color stops- // resolve against live for the duration of the call.- let (gradient_style_value, color_input) = unsafe {- (- &*inputs- .gradient_style_value- .cast::<crate::css::style_value::StyleValueData>(),- ColorResolutionInput::for_ffi_style(inputs.gradient_stop_color_resolution_style.cast()),- )- };- let resolved =- resolve_gradient_paint_with_input(gradient_style_value, inputs.gradient_tile_size.into(), &color_input);- record_resolved_gradient_fill(- &mut recorder,- DevicePixelConverter::new(inputs.device_pixels_per_css_pixel),- &resolved,- dest_rect,- CompositingAndBlendingOperator::Normal,- ForceDarkRole::None,- );- }- }- let recorded = recorder.into_builder().finish();- unsafe {- consume(- context,- std::sync::Arc::into_raw(std::sync::Arc::new(recorded)).cast(),- std::sync::Arc::into_raw(std::sync::Arc::new(tree)).cast(),- );- }-}-/// The glyph cells a text content element's box committed for its own characters, one per code/// unit. The cells belong to the committed fragment, so they are read before the next commit.#[repr(C)]diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex 31bdc794d66..71283b9d7a3 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -618,9 +618,7 @@ pub unsafe extern "C" fn render_state_encode_scroll_state(#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_publish_recording(host: &crate::render_state::DocumentHost,- read: &crate::render_state::BegunRead,publish: crate::painting::host::FfiRecordingPublishCallbacks,- out: &mut crate::painting::ffi::FfiPresentedRecording,) {// SAFETY: Guaranteed by the entry point's contract.let main_thread = unsafe { main_thread(host) };@@ -628,27 +626,6 @@ pub unsafe extern "C" fn render_state_publish_recording(if let Some(publication) = recording.take_publication() {crate::painting::record::publish::publish_recording(host, publication, &main_thread, &publish);}- drop(recording);- let presented = read_arena(host, read, (), |arena, ()| {- crate::painting::ffi::FfiPresentedRecording::of_last_recording(arena)- });- *out = presented;-}--/// What the host reads of the recording `host`'s document took in last.-///-/// # Safety-///-/// `host` must be a live document host, on its document's thread.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn render_state_last_recording(- host: &crate::render_state::DocumentHost,- read: &crate::render_state::BegunRead,- out: &mut crate::painting::ffi::FfiPresentedRecording,-) {- *out = read_arena(host, read, (), |arena, ()| {- crate::painting::ffi::FfiPresentedRecording::of_last_recording(arena)- });}/// # Safety@@ -761,12 +738,12 @@ pub unsafe extern "C" fn render_state_record_display_list(/// Commits the frame of `host`'s document as the rendering update leaves it to the render owner, with `recorder`, which/// samples it beside the event loop at `timestamp`, the time of the document's timeline the update sampled its-/// animations at, and hands it to the Paint thread, which presents it with `presentation`. The frame flies until the+/// animations at, and hands it to the Paint thread, which presents it as `seal` sealed it. The frame flies until the/// host takes it in.////// # Safety///-/// `presentation` must name a presentation the host gives up.+/// `seal` must name a live presenter, and buffers of the sizes it gives.unsafe fn commit_frame(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,@@ -774,14 +751,25 @@ unsafe fn commit_frame(content: crate::render_state::CommittedContent,held_for_testing: bool,timestamp: f64,- presentation: crate::painting::ffi::FfiPresentation,+ seal: &crate::painting::presentation::FfiSeal,) {+ let publishes_recording = match &content {+ crate::render_state::CommittedContent::Recording { frame_inputs, .. } => frame_inputs.publishes_recording,+ crate::render_state::CommittedContent::Unrecorded { .. } => false,+ };+ // SAFETY: Guaranteed by the caller.+ let presentation = unsafe {+ crate::painting::presentation::Presentation::adopt(+ seal,+ &host.scroll_state(),+ recorder.published_recording.clone(),+ publishes_recording,+ )+ };let commit = crate::render_state::CommittedFrame {content,recorder,- // SAFETY: Guaranteed by the caller.- presentation: unsafe { crate::painting::presentation::Presentation::adopt(presentation, &host.scroll_state()) }- .expect("a committed frame is presented"),+ presentation,timestamp,held_for_testing,};@@ -793,7 +781,7 @@ unsafe fn commit_frame(////// # Safety///-/// As for [`render_state_record_display_list`]. `presentation` must name a presentation the host gives up.+/// As for [`render_state_record_display_list`], and `seal` must be as [`commit_frame`] takes it.#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_commit_recorded_frame(host: &crate::render_state::DocumentHost,@@ -801,7 +789,7 @@ pub unsafe extern "C" fn render_state_commit_recorded_frame(viewport: NodeSlotId,inputs: crate::painting::host::FfiRecordingInputs,timestamp: f64,- presentation: crate::painting::ffi::FfiPresentation,+ seal: &crate::painting::presentation::FfiSeal,) {let recorder = take_recorder_for_recording(host, read);let content = crate::render_state::CommittedContent::Recording {@@ -811,7 +799,7 @@ pub unsafe extern "C" fn render_state_commit_recorded_frame(};let held_for_testing = crate::painting::recording_slot::take_recording_hold_for_testing();// SAFETY: Guaranteed by the caller.- unsafe { commit_frame(host, read, recorder, content, held_for_testing, timestamp, presentation) };+ unsafe { commit_frame(host, read, recorder, content, held_for_testing, timestamp, seal) };}/// Commits the frame of `host`'s document as one that keeps the display list the compositor has, and sends the render@@ -819,53 +807,46 @@ pub unsafe extern "C" fn render_state_commit_recorded_frame(////// # Safety///-/// `host` must be a live document host, on its document's thread. `presentation` must name a presentation the host-/// gives up.+/// `host` must be a live document host, on its document's thread, and `seal` must be as [`commit_frame`] takes it.#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_commit_unrecorded_frame(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,sends_visual_context_tree: bool,timestamp: f64,- presentation: crate::painting::ffi::FfiPresentation,+ seal: &crate::painting::presentation::FfiSeal,) {let recorder = take_recorder_for_recording(host, read);let content = crate::render_state::CommittedContent::Unrecorded {sends_visual_context_tree,};// SAFETY: Guaranteed by the caller.- unsafe { commit_frame(host, read, recorder, content, false, timestamp, presentation) };+ unsafe { commit_frame(host, read, recorder, content, false, timestamp, seal) };}/// Renders the SVG images of the committed frame of `host`'s document that waits for them, with the callbacks in-/// `publish`, into `resources`, and hands the frame back to the Paint thread, which presents it with them. The frame-/// flies again until the host takes it in.+/// `publish`, and hands the frame back to the Paint thread, which presents it with them. The frame flies again until the+/// host takes it in.////// # Safety////// `host` must be a live document host, on its document's thread, whose committed frame landed as-/// [`FfiRecordingLanding::NeedsVectorImages`]; the callbacks in `publish` are called synchronously with their context,-/// which adds what they render to `resources`, a `Web::Compositor::VectorImageResources` the host gives up.+/// [`FfiRecordingLanding::NeedsVectorImages`]; the callbacks in `publish` are called synchronously with their context.#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_render_vector_images(host: &crate::render_state::DocumentHost,publish: crate::painting::host::FfiRecordingPublishCallbacks,- resources: std::ptr::NonNull<c_void>,) {// SAFETY: Guaranteed by the entry point's contract.let main_thread = unsafe { main_thread(host) };- // SAFETY: Guaranteed by the caller.- let resources = unsafe { crate::painting::presentation::VectorImageResources::adopt(resources) };let (frame, recorder) = host.recording().take_vector_image_frame().expect("a committed frame waits for its SVG images");- let display_list_ids =+ let display_lists =crate::painting::record::publish::render_vector_images(frame.get().requests(), &main_thread, &publish);let flight = crate::paint_stage::submit_presenting(frame, move |frame, presenting| {- frame- .into_inner()- .present(recorder, &display_list_ids, resources, presenting)+ frame.into_inner().present(recorder, &display_lists, presenting)});host.recording().fly(flight);}@@ -897,17 +878,16 @@ pub extern "C" fn render_state_release_held_recording_for_testing() {}/// Takes the recording in flight of `host`'s document in where it has finished, and answers how it landed. The event-/// loop calls it between two tasks, so it never waits. A recording that landed gives back the presentation it took, if-/// any, through `presentation`.+/// loop calls it between two tasks, so it never waits. A recording that landed writes whether presenting its frame sent+/// the compositor other scroll offsets than the frame before to `presented_other_scroll_offsets`.////// # Safety////// `host` must be a live document host, on its document's thread, and the event loop must call this between two tasks.-/// The host takes over what `presentation` names.#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_take_finished_recording_in(host: &crate::render_state::DocumentHost,- presentation: &mut crate::painting::ffi::FfiPresentation,+ presented_other_scroll_offsets: &mut bool,) -> FfiRecordingLanding {let boundary = crate::render_state::TaskBoundary::at_event_loop_entry(&TAKES_FINISHED_RECORDING_IN);let landing = host.recording().take_finished_recording_in(@@ -917,15 +897,15 @@ pub unsafe extern "C" fn render_state_take_finished_recording_in(take_in_presented_recording(host, output, hit_test_list_changed, publishes_recording);},);- recording_landing(landing, presentation)+ recording_landing(landing, presented_other_scroll_offsets)}/// Waits for the recording in flight of `host`'s document and takes it in, and answers how it landed (see-/// [`render_state_take_finished_recording_in`]). The host takes over what `presentation` names.+/// [`render_state_take_finished_recording_in`]).#[unsafe(no_mangle)]pub extern "C" fn render_state_join_recording_in_flight(host: &crate::render_state::DocumentHost,- presentation: &mut crate::painting::ffi::FfiPresentation,+ presented_other_scroll_offsets: &mut bool,) -> FfiRecordingLanding {let landing = host.recording().join_recording_in_flight(|rows_version| landed_recording_stands(host, rows_version),@@ -933,7 +913,7 @@ pub extern "C" fn render_state_join_recording_in_flight(take_in_presented_recording(host, output, hit_test_list_changed, publishes_recording);},);- recording_landing(landing, presentation)+ recording_landing(landing, presented_other_scroll_offsets)}/// Takes the output of a recording that presented itself in as the document's last.@@ -952,10 +932,11 @@ fn take_in_presented_recording());}-/// Answers how a recording landed, and writes the presentation it gave back to `presentation`.+/// Answers how a recording landed, and writes what the presentation it gave back presented to+/// `presented_other_scroll_offsets`.fn recording_landing(landing: crate::painting::recording_slot::RecordingLanding,- presentation: &mut crate::painting::ffi::FfiPresentation,+ presentation: &mut bool,) -> FfiRecordingLanding {use crate::painting::recording_slot::RecordingLanding;match landing {@@ -981,12 +962,14 @@ fn recording_landing(}}-/// Writes the presentation a recording gave back, if any, to `presentation`.+/// Writes whether the presentation a recording gave back, if any, sent the compositor other scroll offsets than the+/// frame before to `presented_other_scroll_offsets`.fn give_back(given_back: Option<crate::painting::presentation::Presentation>,- presentation: &mut crate::painting::ffi::FfiPresentation,+ presented_other_scroll_offsets: &mut bool,) {- *presentation = given_back.map_or_else(Default::default, crate::painting::presentation::Presentation::into_ffi);+ *presented_other_scroll_offsets =+ given_back.is_some_and(|presentation| presentation.presented_other_scroll_offsets());}/// Whether the rows of `host`'s document are still at `version`, so that the hit-test list of a recording that landeddiff --git a/Libraries/LibWeb/Rust/src/painting/host/paint.rs b/Libraries/LibWeb/Rust/src/painting/host/paint.rsindex 059c9de63df..6f634ae03d7 100644--- a/Libraries/LibWeb/Rust/src/painting/host/paint.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/paint.rs@@ -67,6 +67,44 @@ pub struct FfiRecordingInputs {pub text_fragment_indication_count: usize,pub mark_color: Color,pub mark_text_color: Color,+ /// What the compositor clears the surface with below the recording, for a top-level traversable.+ pub surface_clear_color: OptionalColor,+ pub has_async_scrolling_metadata: bool,+ pub async_scrolling_metadata: FfiAsyncScrollingMetadata,+}++/// What a recording's display list is stamped with for async scrolling, as the host knows it where the recording begins:+/// `Compositing::AsyncScrollingMetadata` but for the keyboard scroll state, which each frame sets.+#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct FfiAsyncScrollingMetadata {+ pub has_document_id: bool,+ pub document_id: i64,+ pub viewport_rect: IntRect,+ pub wheel_event_listener_state_generation: u64,+ pub has_blocking_wheel_event_listeners: bool,+ pub has_blocking_wheel_event_region_covering_viewport: bool,+ pub viewport_keeps_horizontal_scrolls: bool,+ pub viewport_keeps_vertical_scrolls: bool,+ pub device_pixels_per_css_pixel: f64,+}++impl FfiAsyncScrollingMetadata {+ fn to_metadata(self) -> libcompositing_rust::ipc_types::Compositing_AsyncScrollingMetadata {+ libcompositing_rust::ipc_types::Compositing_AsyncScrollingMetadata {+ document_id: self+ .has_document_id+ .then_some(crate::painting::display_list::commands::UniqueNodeId(self.document_id)),+ viewport_rect: self.viewport_rect,+ wheel_event_listener_state_generation: self.wheel_event_listener_state_generation,+ has_blocking_wheel_event_listeners: self.has_blocking_wheel_event_listeners,+ has_blocking_wheel_event_region_covering_viewport: self.has_blocking_wheel_event_region_covering_viewport,+ viewport_keeps_horizontal_scrolls: self.viewport_keeps_horizontal_scrolls,+ viewport_keeps_vertical_scrolls: self.viewport_keeps_vertical_scrolls,+ device_pixels_per_css_pixel: self.device_pixels_per_css_pixel,+ keyboard_scroll_state: crate::painting::presentation::empty_keyboard_scroll_state(),+ }+ }}#[derive(Clone, Copy, Debug)]@@ -142,6 +180,10 @@ impl FfiRecordingInputs {opaque_canvas: self.opaque_canvas,bitmap_rect: self.bitmap_rect,publishes_recording: self.publishes_recording,+ surface_clear_color: self.surface_clear_color.get(),+ async_scrolling_metadata: self+ .has_async_scrolling_metadata+ .then(|| self.async_scrolling_metadata.to_metadata()),window_is_focused: self.window_is_focused,outline_auto_color: self.outline_auto_color,selection_background_from_palette: self.selection_background_from_palette,@@ -575,44 +617,31 @@ pub struct FfiSnapAreaDomRelations {unsafe extern "C" fn(*mut c_void, FfiSnapAreaIdentity, FfiSnapAreaIdentity) -> bool,}-/// Where a recording's resources go once it is published. The fields are private: the callbacks-/// are reached only through the methods below, which take the main thread token.+/// How a recording that is published has the host render its SVG images. The fields are private: the callback is+/// reached only through the method below, which takes the main thread token.///-/// NB: The callbacks are typed as safe functions because the table only comes from the host through an export-/// whose safety contract keeps them callable, and the private fields let nothing else call them.+/// NB: The callback is typed as a safe function because the table only comes from the host through an export whose+/// safety contract keeps it callable, and the private fields let nothing else call it.#[derive(Clone, Copy)]#[repr(C)]pub struct FfiRecordingPublishCallbacks {context: *mut c_void,- add_font: extern "C" fn(*mut c_void, *const c_void),- add_image_frame: extern "C" fn(*mut c_void, *const c_void),- resolve_vector_image_display_list: extern "C" fn(*mut c_void, *const FfiVectorImageRenderRequest) -> u64,- add_video_sink: extern "C" fn(*mut c_void, u64, u64),+ render_vector_image:+ extern "C" fn(*mut c_void, *const FfiVectorImageRenderRequest) -> *const crate::render_state::DocumentHost,}impl FfiRecordingPublishCallbacks {- pub(crate) fn add_font(&self, _: &MainThread, font: &libgfx_rust::font::FontHandle) {- // The C++ host registers the live font synchronously.- (self.add_font)(self.context, font.as_raw());- }-- pub(crate) fn add_image_frame(&self, _: &MainThread, frame: &libgfx_rust::image_frame::ImageFrameHandle) {- // The C++ host copies the live frame synchronously.- (self.add_image_frame)(self.context, frame.as_raw());- }-- pub(crate) fn resolve_vector_image_display_list(+ /// Has the host render the SVG image `request` names, and answers the host of the image's document, which keeps+ /// the image's display list for the request, or none where the image has nothing to show.+ pub(crate) fn render_vector_image<'a>(&self,- _: &MainThread,+ _: &'a MainThread,request: &FfiVectorImageRenderRequest,- ) -> u64 {- // The C++ host records the image's display list synchronously and reads the- // request only for the duration of the call.- (self.resolve_vector_image_display_list)(self.context, request)- }-- pub(crate) fn add_video_sink(&self, _: &MainThread, resource_id: u64, sink_handle: u64) {- // The C++ host registers the sink synchronously.- (self.add_video_sink)(self.context, resource_id, sink_handle);+ ) -> Option<&'a crate::render_state::DocumentHost> {+ // The C++ host renders the image synchronously and reads the request only for the duration of the call. The+ // image's document, and its host, outlive the recording that draws it.+ let host = (self.render_vector_image)(self.context, request);+ // SAFETY: The host answers a live document host or null.+ unsafe { host.as_ref() }}}diff --git a/Libraries/LibWeb/Rust/src/painting/mod.rs b/Libraries/LibWeb/Rust/src/painting/mod.rsindex ea53ed9e34c..b67c017eb9f 100644--- a/Libraries/LibWeb/Rust/src/painting/mod.rs+++ b/Libraries/LibWeb/Rust/src/painting/mod.rs@@ -13,6 +13,7 @@ pub(crate) mod corner_shape;pub(crate) mod css_filter;mod devtools_layout;pub mod display_list;+pub(crate) mod display_list_resources;mod dump;pub mod ffi;pub mod fragment_ownership;@@ -36,7 +37,9 @@ pub mod paintable_geometry;pub(crate) mod paintable_rows;pub(crate) mod presentation;pub(crate) mod published_frame;+pub(crate) mod rasterize;pub mod record;+pub(crate) mod recorded_scrolling;pub(crate) mod recording_slot;pub(crate) mod replaced_paint_facts;pub(crate) mod scroll_chain;@@ -50,6 +53,7 @@ pub(crate) mod svg_filter;pub(crate) mod svg_masking;pub(crate) mod svg_paint_resources;pub mod text_fragment;+pub(crate) mod vector_image_cache;pub mod viewport_mapping;pub mod visual_animation_builder;pub mod visual_context;diff --git a/Libraries/LibWeb/Rust/src/painting/presentation.rs b/Libraries/LibWeb/Rust/src/painting/presentation.rsindex 0de45312132..580aca94bfd 100644--- a/Libraries/LibWeb/Rust/src/painting/presentation.rs+++ b/Libraries/LibWeb/Rust/src/painting/presentation.rs@@ -4,146 +4,168 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! A navigable's presenter, and the seal of the frame it presents next, which what presents a frame beside the event-//! loop owns while they are away from their navigable.+//! A navigable's presenter, which keeps what the navigable's compositor context holds, and the presentation of one frame+//! of the navigable: the presenter and the seal of what the frame is built from, which what presents the frame beside+//! the event loop owns while it is away from the navigable.//!-//! Each box owns one C++ object, which reaches nothing of the thread that made it, and destroys it when dropped. Only-//! the owner of a navigable's presenter presents to its compositor context, so frames reach the compositor in the order-//! their presenter's owners presented them.+//! Only the owner of a frame's presentation presents it, on the Paint thread, so frames reach the compositor in the order+//! their presentations were presented. The navigable reads what the presenter presented on the main thread.use crate::paint_stage::Presenting;-use crate::painting::ffi::{FfiPresentation, FfiPresentedRecording, FfiPresentedVisualContextTree};+use crate::painting::display_list::commands::CompositorContextId;+use crate::painting::display_list::storage::DisplayListStorage;+use crate::painting::display_list_resources::{DisplayListResources, ResourceIds};use crate::painting::paint_passes::ClockTickVisualContexts;-use crate::painting::record::publish::RecordingResourceSink;+use crate::painting::record::RecordingOutput;use crate::painting::visual_context::VisualContextTree;+use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{+ ApplyScrollRequests, PresentFrame, UpdateDisplayList, UpdateScrollState, UpdateVisualContextTree,+};+use libcompositing_rust::ipc_types::{+ Compositing_AsyncScrollingMetadata, Compositing_DisplayListProperties, Compositing_DisplayListResourceTransaction,+ Compositing_KeyboardScrollState, Compositing_ScrollRequest,+};use libcompositing_rust::scrolling::ScrollStateSnapshot;-use std::ffi::c_void;-use std::ptr::NonNull;-use std::sync::Arc;--unsafe extern "C" {- fn web_navigable_presenter_unref(presenter: *mut c_void);- fn web_navigable_presenter_seal_for_clock_lane(presenter: *mut c_void, committed: *const c_void) -> *mut c_void;- fn web_sealed_presentation_destroy(sealed: *mut c_void);- fn web_sealed_presentation_take_visual_context_tree(- sealed: *mut c_void,- structural_epoch: u64,- tree_is_restructured: bool,- );- fn web_navigable_presenter_add_font(presenter: *mut c_void, font: *const c_void);- fn web_navigable_presenter_add_image_frame(presenter: *mut c_void, frame: *const c_void);- fn web_navigable_presenter_add_video_sink(presenter: *mut c_void, resource_id: u64, sink_handle: u64);- fn web_navigable_presenter_present(- presenter: *mut c_void,- sealed: *mut c_void,- presented: *const FfiPresentedRecording,- visual_context_tree: *const FfiPresentedVisualContextTree,- encoded_scroll_state: *const u8,- encoded_scroll_state_size: usize,- sink: *mut c_void,- );- fn web_navigable_presenter_present_unrecorded(- presenter: *mut c_void,- sealed: *mut c_void,- visual_context_tree: *const FfiPresentedVisualContextTree,- encoded_scroll_state: *const u8,- encoded_scroll_state_size: usize,- sink: *mut c_void,- );- fn web_vector_image_resources_destroy(resources: *mut c_void);- fn web_navigable_presenter_take_vector_image_resources(- presenter: *mut c_void,- resources: *mut c_void,- display_list_ids: *const u64,- display_list_id_count: usize,- );-}--/// A reference to a `Web::Compositor::NavigablePresenter`, which its navigable shares.-pub(crate) struct PresenterBox(NonNull<c_void>);--/// A `Web::Compositor::SealedPresentation`, owned.-pub(crate) struct SealedPresentationBox(NonNull<c_void>);--// SAFETY: Each box owns its object, which reaches nothing of the thread that made it, and nothing else reaches the object-// while the box lives.-unsafe impl Send for PresenterBox {}-unsafe impl Send for SealedPresentationBox {}--impl Drop for PresenterBox {- fn drop(&mut self) {- // SAFETY: The box holds a reference to the presenter.- unsafe { web_navigable_presenter_unref(self.0.as_ptr()) };- }+use libgfx_rust::IntRect;+use libgfx_rust::font::FontHandle;+use libgfx_rust::image_frame::ImageFrameHandle;+use libipc_rust::wire::{Decode, Decoder};+use std::collections::HashSet;+use std::sync::{Arc, Mutex, MutexGuard};++/// What presented a navigable's last frame: the recording of a frame a rendering update committed, or a tick of the+/// document's clock lane.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum FfiPresentedBy {+ None,+ Commit,+ Clock,}-impl Drop for SealedPresentationBox {- fn drop(&mut self) {- // SAFETY: The box owns the seal.- unsafe { web_sealed_presentation_destroy(self.0.as_ptr()) };- }+/// `Web::HTML::PaintConfig`, which the presenter keeps for the display list the compositor context holds.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+#[repr(C)]+pub struct FfiPaintConfig {+ pub paint_overlay: bool,+ pub should_show_line_box_borders: bool,+ pub should_show_caret_hit_test_debug_overlay: bool,+ pub force_dark_enabled: bool,+ pub force_dark_foreground_threshold: i32,+ pub force_dark_background_threshold: i32,+ pub has_canvas_fill_rect: bool,+ pub canvas_fill_rect: IntRect,}-impl RecordingResourceSink for PresenterBox {- fn add_font(&mut self, font: &libgfx_rust::font::FontHandle) {- // SAFETY: The box owns the presenter, whose storage takes a reference of its own to the live font.- unsafe { web_navigable_presenter_add_font(self.0.as_ptr(), font.as_raw()) };- }-- fn add_image_frame(&mut self, frame: &libgfx_rust::image_frame::ImageFrameHandle) {- // SAFETY: As above, for the live frame.- unsafe { web_navigable_presenter_add_image_frame(self.0.as_ptr(), frame.as_raw()) };- }-- fn add_video_sink(&mut self, resource_id: u64, sink_handle: u64) {- // SAFETY: As above.- unsafe { web_navigable_presenter_add_video_sink(self.0.as_ptr(), resource_id, sink_handle) };- }+/// The display list a navigable's compositor context holds, which the presenter presented last.+struct CompositorDisplayList {+ output: Arc<RecordingOutput>,+ /// What its commands draw, at any depth.+ command_resources: DisplayListResources,}-/// The SVG images a frame renders, which the host rendered for it: a `Web::Compositor::VectorImageResources`, owned.-pub(crate) struct VectorImageResources(NonNull<c_void>);+/// What a navigable's presenter keeps of the frames it presented.+#[derive(Default)]+struct PresenterState {+ compositor_display_list: Option<CompositorDisplayList>,+ compositor_display_list_paint_config: Option<FfiPaintConfig>,+ /// The resources the compositor context holds.+ compositor_resource_ids: ResourceIds,+ last_frame_presented_by: Option<FfiPresentedBy>,+ last_keyboard_scroll_state_generation: Option<u64>,+ /// The generation of the last frame a rendering update committed that the presenter presented.+ last_committed_generation: u64,+ /// The scroll offsets the last frame the presenter presented sent the compositor.+ last_presented_encoded_scroll_state: Vec<u8>,+ /// What the display list of the last frame a rendering update committed draws, which the frames of a clock lane keep+ /// beside their own.+ committed_command_resources: DisplayListResources,+}-// SAFETY: The box owns its object, which reaches nothing of the thread that made it.-unsafe impl Send for VectorImageResources {}+/// A navigable's presenter, which its navigable and what presents a frame of it beside the event loop share: the Paint+/// thread presents, and the main thread reads what it presented.+#[derive(Default)]+pub struct NavigablePresenter {+ state: Mutex<PresenterState>,+}-impl VectorImageResources {- /// Takes over what `resources` names, which the host gives up.- ///- /// # Safety- /// `resources` must be a `Web::Compositor::VectorImageResources` the host gives up.- pub(crate) unsafe fn adopt(resources: NonNull<c_void>) -> Self {- Self(resources)+impl NavigablePresenter {+ fn state(&self) -> MutexGuard<'_, PresenterState> {+ self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)}}-impl Drop for VectorImageResources {- fn drop(&mut self) {- // SAFETY: The box owns the resources.- unsafe { web_vector_image_resources_destroy(self.0.as_ptr()) };- }+/// What a frame is built from that its navigable and document held where the frame began, sealed there: the frame reaches+/// neither of them again before it is presented.+pub(crate) struct Seal {+ paint_config: FfiPaintConfig,+ /// The structural epoch of the visual context tree a new display list is cut from, or of the one the compositor's+ /// display list takes where the document's tree changed since it took one.+ visual_context_tree_structural_epoch: Option<u64>,+ /// Whether the document's tree changed since the compositor took one.+ sends_visual_context_tree: bool,+ /// Whether presenting the frame sent the compositor other scroll offsets than the frame presented before it.+ presented_other_scroll_offsets: bool,+ /// The scrolls the navigable asked for since the frame before, which the compositor applies once it has the frame's+ /// boxes. Only the frame a rendering update commits carries them.+ scroll_requests: Vec<Compositing_ScrollRequest>,+ /// What keyboard scrolling targets, for a top-level traversable.+ keyboard_scroll_state: Option<Compositing_KeyboardScrollState>,+ /// The recording a recording of the frame copies paint commands from.+ paint_command_cache_source: Option<Arc<RecordingOutput>>,+ /// Whether a recording of the frame becomes the one the next recording copies from.+ publishes_recording: bool,+ context_id: CompositorContextId,+ present_viewport_rect: Option<IntRect>,+ presented_by: FfiPresentedBy,+ /// The recording the frame presented, once it is presented.+ published: Option<Arc<RecordingOutput>>,+ /// Whether the frame sends a visual context tree the compositor's display list was not recorded against, for a test.+ visual_context_tree_mismatches_for_testing: bool,+ /// The frame a rendering update committed, counted per navigable, or the one a clock lane's frames start from: a+ /// lane's frame of an older one than the presenter presented last shows what the screen no longer shows.+ generation: u64,}-impl PresenterBox {- /// Takes over the display lists `display_list_ids` names in `resources`, with what they reference.- pub(crate) fn take_vector_image_resources(&mut self, resources: VectorImageResources, display_list_ids: &[u64]) {- // SAFETY: The box owns the presenter, and `resources` the storage the presenter copies from.- unsafe {- web_navigable_presenter_take_vector_image_resources(- self.0.as_ptr(),- resources.0.as_ptr(),- display_list_ids.as_ptr(),- display_list_ids.len(),- );- }- }+/// What C++ seals of a frame where it begins (see [`Seal`]).+#[repr(C)]+pub struct FfiSeal {+ pub presenter: *const NavigablePresenter,+ pub paint_config: FfiPaintConfig,+ pub has_visual_context_tree_structural_epoch: bool,+ pub visual_context_tree_structural_epoch: u64,+ pub sends_visual_context_tree: bool,+ /// The scroll requests, IPC-encoded as a `Vector<Compositing::ScrollRequest>`.+ pub encoded_scroll_requests: *const u8,+ pub encoded_scroll_requests_size: usize,+ /// The keyboard scroll state, IPC-encoded as an `Optional<Compositing::KeyboardScrollState>`.+ pub encoded_keyboard_scroll_state: *const u8,+ pub encoded_keyboard_scroll_state_size: usize,+ pub context_id: u64,+ pub has_present_viewport_rect: bool,+ pub present_viewport_rect: IntRect,+ pub generation: u64,+ pub visual_context_tree_mismatches_for_testing: bool,+}++/// Decodes `T` from `size` IPC-encoded bytes at `bytes`, which hold no attachment.+///+/// # Safety+///+/// `bytes` must point to `size` bytes, or be null with `size` 0.+unsafe fn decode_ipc_bytes<T: Decode>(bytes: *const u8, size: usize) -> T {+ // SAFETY: Guaranteed by the caller.+ let bytes = unsafe { ak::slice_from_raw_parts(bytes, size) };+ Decoder::new(bytes, std::iter::empty())+ .decode()+ .expect("C++ encodes what it seals")}/// What presents one frame of a navigable beside the event loop: the navigable's presenter, and what the frame is built/// from.pub(crate) struct Presentation {- pub(crate) presenter: PresenterBox,- sealed: SealedPresentationBox,+ presenter: Arc<NavigablePresenter>,+ seal: Box<Seal>,/// Where the document's boxes were scrolled to as the frame was sealed, which seeds the offsets of the boxes new to/// the compositor, as the scroll logic of the compositor reads it.encoded_scroll_state: Vec<u8>,@@ -153,79 +175,416 @@ pub(crate) struct Presentation {taken_visual_context_tree: Option<Arc<VisualContextTree>>,}-/// A tree a presenter reads for the call it is lent to, with the ids it hands it.-struct LentVisualContextTree<'a> {- tree: Option<&'a Arc<VisualContextTree>>,- filter_image_frame_ids: Vec<u64>,+/// What one frame hands the compositor, in the order it hands it.+struct CompositorFrame {+ context_id: CompositorContextId,+ display_list_update: Option<DisplayListUpdate>,+ visual_context_tree_update: Option<VisualContextTreeUpdate>,+ scroll_state_update: Option<ScrollStateUpdate>,+ scroll_requests: Vec<Compositing_ScrollRequest>,+ present_viewport_rect: Option<IntRect>,+}++/// A resource transaction, with the fonts and image frames the compositor lacks, which go ahead of it.+struct ResourceUpdate {+ fonts: Vec<FontHandle>,+ image_frames: Vec<ImageFrameHandle>,+ transaction: Compositing_DisplayListResourceTransaction,+}++struct DisplayListUpdate {+ output: Arc<RecordingOutput>,+ properties: Compositing_DisplayListProperties,+ async_scrolling_metadata: Compositing_AsyncScrollingMetadata,+ visual_context_tree: Vec<u8>,+ resources: ResourceUpdate,+ scroll_state: Vec<u8>,+}++struct VisualContextTreeUpdate {+ visual_context_tree: Vec<u8>,+ resources: ResourceUpdate,+ scroll_state: Vec<u8>,+ keyboard_scroll_state: Compositing_KeyboardScrollState,+}++struct ScrollStateUpdate {+ scroll_state: Vec<u8>,+ keyboard_scroll_state: Compositing_KeyboardScrollState,+}++/// A display list a frame presents, and whether it becomes the one the next recording copies from.+struct Published<'a> {+ output: &'a Arc<RecordingOutput>,+ replaces_paint_command_cache_source: bool,+}++pub(crate) fn empty_keyboard_scroll_state() -> Compositing_KeyboardScrollState {+ Compositing_KeyboardScrollState {+ generation: 0,+ visual_context_tree_structural_epoch: 0,+ target: None,+ page_scroll_distance: 0.0,+ arrow_scroll_distance: 0.0,+ }+}++fn empty_async_scrolling_metadata() -> Compositing_AsyncScrollingMetadata {+ Compositing_AsyncScrollingMetadata {+ document_id: None,+ viewport_rect: IntRect::default(),+ wheel_event_listener_state_generation: 0,+ has_blocking_wheel_event_listeners: false,+ has_blocking_wheel_event_region_covering_viewport: false,+ viewport_keeps_horizontal_scrolls: false,+ viewport_keeps_vertical_scrolls: false,+ device_pixels_per_css_pixel: 1.0,+ keyboard_scroll_state: empty_keyboard_scroll_state(),+ }+}++/// What travels beside the tape of `output`'s display list.+pub(crate) fn display_list_properties_of(output: &RecordingOutput) -> Compositing_DisplayListProperties {+ Compositing_DisplayListProperties {+ id: output.display_list_id,+ compatible_visual_context_tree_structural_epoch: output.recorded_structural_epoch,+ surface_clear_color: output.surface_clear_color,+ root_group_color: output.root_group_color,+ }+}++/// Resources a compositor context keeps for a frame: those `resources` holds, and the image frames of `extra_image_frame_ids`+/// it holds already.+struct KeptResources {+ resources: DisplayListResources,+ extra_image_frame_ids: HashSet<u64>,}-impl<'a> LentVisualContextTree<'a> {- fn new(tree: Option<&'a Arc<VisualContextTree>>) -> Self {- let mut filter_image_frame_ids = Vec::new();- if let Some(tree) = tree {- tree.for_each_effects_filter_image_frame_id(&mut |id| filter_image_frame_ids.push(id));+impl KeptResources {+ fn ids(&self) -> ResourceIds {+ let mut ids = self.resources.ids();+ ids.image_frames.extend(self.extra_image_frame_ids.iter().copied());+ ids+ }+}++impl PresenterState {+ /// A clock lane's frame that starts from an older frame than the last one a rendering update committed shows what the+ /// screen no longer shows: it is not presented, and the compositor hears nothing of it.+ fn is_stale(&self, seal: &Seal) -> bool {+ seal.presented_by == FfiPresentedBy::Clock && seal.generation < self.last_committed_generation+ }++ fn note_presented(&mut self, seal: &mut Seal, encoded_scroll_state: &[u8]) {+ seal.presented_other_scroll_offsets = self.last_presented_encoded_scroll_state != encoded_scroll_state;+ if seal.presented_other_scroll_offsets {+ self.last_presented_encoded_scroll_state = encoded_scroll_state.to_vec();}- Self {- tree,- filter_image_frame_ids,+ if seal.presented_by == FfiPresentedBy::Commit {+ self.last_committed_generation = self.last_committed_generation.max(seal.generation);+ self.committed_command_resources = self+ .compositor_display_list+ .as_ref()+ .map(|display_list| display_list.command_resources.clone())+ .unwrap_or_default();}}- /// What C++ reads of the tree, which borrows the ids: it lives no longer than this.- fn to_ffi(&self) -> FfiPresentedVisualContextTree {- FfiPresentedVisualContextTree {- tree: self.tree.map_or(std::ptr::null(), |tree| Arc::as_ptr(tree).cast()),- structural_epoch: self.tree.map_or(0, |tree| tree.structural_epoch),- filter_image_frame_ids: self.filter_image_frame_ids.as_ptr(),- filter_image_frame_id_count: self.filter_image_frame_ids.len(),+ /// The resources the compositor keeps for a frame of `seal` whose display list draws `command_resources`, with+ /// `visual_context_tree`.+ fn kept_resources(+ &self,+ seal: &Seal,+ published: Option<&Published>,+ command_resources: &DisplayListResources,+ visual_context_tree: &VisualContextTree,+ ) -> KeptResources {+ let mut resources = command_resources.clone();+ // A recording downgraded to cache-read-only leaves the source it copied from live, and what it draws with it. A+ // recording that replaced the source draws everything the new source does.+ if !published.is_some_and(|published| published.replaces_paint_command_cache_source)+ && let Some(source) = &seal.paint_command_cache_source+ {+ resources.include(&source.resources.with_nested_resources());}+ // The next frame a rendering update commits copies paint commands from the one it committed last, whatever a+ // clock lane presented since.+ if seal.presented_by == FfiPresentedBy::Clock {+ resources.include(&self.committed_command_resources);+ }+ let mut extra_image_frame_ids = HashSet::new();+ visual_context_tree.for_each_effects_filter_image_frame_id(&mut |id| {+ if resources.image_frames.contains_key(&id) {+ return;+ }+ let handle = [+ published.map(|published| &published.output.resources),+ self.compositor_display_list+ .as_ref()+ .map(|display_list| &display_list.command_resources),+ ]+ .into_iter()+ .flatten()+ .find_map(|resources| resources.image_frames.get(&id).cloned());+ match handle {+ Some(handle) => {+ resources.image_frames.insert(id, handle);+ }+ None if self.compositor_resource_ids.image_frames.contains(&id) => {+ extra_image_frame_ids.insert(id);+ }+ None => {}+ }+ });+ KeptResources {+ resources,+ extra_image_frame_ids,+ }+ }++ /// What the compositor is sent to hold `kept` in place of what it holds.+ fn resource_update(&mut self, kept: KeptResources) -> ResourceUpdate {+ let held = std::mem::take(&mut self.compositor_resource_ids);+ let kept_ids = kept.ids();+ let KeptResources { resources, .. } = kept;+ let mut update = ResourceUpdate {+ fonts: Vec::new(),+ image_frames: Vec::new(),+ transaction: Compositing_DisplayListResourceTransaction::default(),+ };+ for (id, font) in resources.fonts {+ if !held.fonts.contains(&id) {+ update.fonts.push(font);+ }+ }+ for (id, frame) in resources.image_frames {+ if !held.image_frames.contains(&id) {+ update.image_frames.push(frame);+ }+ }+ for (id, handle) in resources.video_sinks {+ if !held.video_sinks.contains(&id) {+ update.transaction.video_sinks.push((id, handle));+ }+ }+ for (id, display_list) in resources.nested_display_lists {+ if !held.display_lists.contains(&id) {+ update.transaction.display_lists.push(display_list.resource.clone());+ }+ }+ let removed =+ |held: &HashSet<u64>, kept: &HashSet<u64>| -> Vec<u64> { held.difference(kept).copied().collect() };+ update.transaction.font_ids_to_remove = removed(&held.fonts, &kept_ids.fonts);+ update.transaction.image_frame_ids_to_remove = removed(&held.image_frames, &kept_ids.image_frames);+ update.transaction.video_sink_ids_to_remove = removed(&held.video_sinks, &kept_ids.video_sinks);+ update.transaction.display_list_ids_to_remove = removed(&held.display_lists, &kept_ids.display_lists);+ self.compositor_resource_ids = kept_ids;+ update+ }++ /// Builds the frame that brings the compositor context `seal` names up to date with `published`, the display list a+ /// recording just published, or with what changed for the one the compositor has where none was published, from what+ /// `seal` sealed, the visual context tree the frame goes with, and the scroll state sealed beside it, which seeds the+ /// offsets of the boxes new to the compositor.+ fn build_frame(+ &mut self,+ seal: &Seal,+ published: Option<Published>,+ visual_context_tree: &Arc<VisualContextTree>,+ encoded_scroll_state: &[u8],+ ) -> CompositorFrame {+ // Keyboard eligibility belongs to this publication, not to the cached paint commands. Refresh it even if recording+ // was skipped or repeated the display list, and send it with the corresponding scroll state.+ let display_list_output = published+ .as_ref()+ .map(|published| published.output)+ .or(self+ .compositor_display_list+ .as_ref()+ .map(|display_list| &display_list.output))+ .cloned();+ let mut keyboard_scroll_state = empty_keyboard_scroll_state();+ if let Some(sealed_state) = &seal.keyboard_scroll_state {+ keyboard_scroll_state = sealed_state.clone();+ self.last_keyboard_scroll_state_generation = Some(sealed_state.generation);+ keyboard_scroll_state.visual_context_tree_structural_epoch = display_list_output+ .as_ref()+ .map_or(0, |output| output.recorded_structural_epoch);+ }++ self.last_frame_presented_by = Some(seal.presented_by);+ let mut frame = CompositorFrame {+ context_id: seal.context_id,+ display_list_update: None,+ visual_context_tree_update: None,+ scroll_state_update: None,+ scroll_requests: Vec::new(),+ present_viewport_rect: seal.present_viewport_rect,+ };+ let display_list_is_unchanged = published.as_ref().is_some_and(|published| {+ self.compositor_display_list+ .as_ref()+ .is_some_and(|held| held.output.display_list_id == published.output.display_list_id)+ });+ if let Some(published) = published.as_ref().filter(|_| !display_list_is_unchanged) {+ let output = published.output.clone();+ let command_resources = output.resources.with_nested_resources();+ let kept = self.kept_resources(seal, Some(published), &command_resources, visual_context_tree);+ let mut async_scrolling_metadata = output+ .async_scrolling_metadata+ .clone()+ .unwrap_or_else(empty_async_scrolling_metadata);+ async_scrolling_metadata.keyboard_scroll_state = keyboard_scroll_state;+ frame.display_list_update = Some(DisplayListUpdate {+ properties: display_list_properties_of(&output),+ async_scrolling_metadata,+ visual_context_tree: visual_context_tree.to_bytes(),+ resources: self.resource_update(kept),+ scroll_state: encoded_scroll_state.to_vec(),+ output: output.clone(),+ });+ self.compositor_display_list = Some(CompositorDisplayList {+ output,+ command_resources,+ });+ self.compositor_display_list_paint_config = Some(seal.paint_config);+ return frame;+ }++ if display_list_is_unchanged {+ self.compositor_display_list_paint_config = Some(seal.paint_config);+ }+ if seal.sends_visual_context_tree {+ let held_epoch = self+ .compositor_display_list+ .as_ref()+ .map(|display_list| display_list.output.recorded_structural_epoch);+ assert!(+ seal.visual_context_tree_mismatches_for_testing+ || held_epoch.is_none_or(|epoch| epoch == visual_context_tree.structural_epoch),+ "a frame sends a tree of the structure the compositor's display list was recorded against"+ );+ let command_resources = self+ .compositor_display_list+ .as_ref()+ .map(|display_list| display_list.command_resources.clone())+ .unwrap_or_default();+ let kept = self.kept_resources(seal, None, &command_resources, visual_context_tree);+ frame.visual_context_tree_update = Some(VisualContextTreeUpdate {+ visual_context_tree: visual_context_tree.to_bytes(),+ resources: self.resource_update(kept),+ scroll_state: encoded_scroll_state.to_vec(),+ keyboard_scroll_state,+ });+ } else {+ frame.scroll_state_update = Some(ScrollStateUpdate {+ scroll_state: encoded_scroll_state.to_vec(),+ keyboard_scroll_state,+ });+ }+ frame}}impl Presentation {- /// Takes over the presenter and the seal `ffi` names, which the host gives up, or none where it names none, with- /// `scroll_state`, the scroll state of the host's document.+ /// The presentation of a frame `ffi` sealed, with `scroll_state`, the scroll state of the document, and+ /// `paint_command_cache_source`, the recording a recording of the frame copies from, whose recording becomes the+ /// next one's source where `publishes_recording`.////// # Safety- /// `ffi` must name a presenter and a seal the host made and gives up, or neither.- pub(crate) unsafe fn adopt(ffi: FfiPresentation, scroll_state: &ScrollStateSnapshot) -> Option<Self> {- Some(Self {- presenter: PresenterBox(NonNull::new(ffi.presenter)?),- sealed: SealedPresentationBox(NonNull::new(ffi.sealed)?),+ ///+ /// `ffi` must name a live presenter, and buffers of the sizes it gives.+ pub(crate) unsafe fn adopt(+ ffi: &FfiSeal,+ scroll_state: &ScrollStateSnapshot,+ paint_command_cache_source: Option<Arc<RecordingOutput>>,+ publishes_recording: bool,+ ) -> Self {+ // SAFETY: Guaranteed by the caller.+ let presenter = unsafe {+ Arc::increment_strong_count(ffi.presenter);+ Arc::from_raw(ffi.presenter)+ };+ Self {+ presenter,+ seal: Box::new(Seal {+ paint_config: ffi.paint_config,+ visual_context_tree_structural_epoch: ffi+ .has_visual_context_tree_structural_epoch+ .then_some(ffi.visual_context_tree_structural_epoch),+ sends_visual_context_tree: ffi.sends_visual_context_tree,+ presented_other_scroll_offsets: false,+ // SAFETY: Guaranteed by the caller.+ scroll_requests: unsafe {+ decode_ipc_bytes(ffi.encoded_scroll_requests, ffi.encoded_scroll_requests_size)+ },+ // SAFETY: Guaranteed by the caller.+ keyboard_scroll_state: unsafe {+ decode_ipc_bytes(+ ffi.encoded_keyboard_scroll_state,+ ffi.encoded_keyboard_scroll_state_size,+ )+ },+ paint_command_cache_source,+ publishes_recording,+ context_id: CompositorContextId(ffi.context_id),+ present_viewport_rect: ffi.has_present_viewport_rect.then_some(ffi.present_viewport_rect),+ presented_by: FfiPresentedBy::Commit,+ published: None,+ visual_context_tree_mismatches_for_testing: ffi.visual_context_tree_mismatches_for_testing,+ generation: ffi.generation,+ }),encoded_scroll_state: scroll_state.to_encoded_bytes(),taken_visual_context_tree: None,- })+ }+ }++ /// Whether presenting the frame sent the compositor other scroll offsets than the frame presented before it.+ pub(crate) fn presented_other_scroll_offsets(&self) -> bool {+ self.seal.presented_other_scroll_offsets}/// What the clock lane of the frame this presented presents its frames with: the presenter, and a seal of frames/// that start from this one, or none where the compositor shows another display list than this frame records from./// On the Paint thread, once this presented.pub(crate) fn for_clock_lane(&self) -> Option<Self> {- // SAFETY: The presentation owns both objects. A seal the call answers comes with a reference to the presenter.- let sealed = NonNull::new(unsafe {- web_navigable_presenter_seal_for_clock_lane(self.presenter.0.as_ptr(), self.sealed.0.as_ptr())- })?;+ let state = self.presenter.state();+ // A lane records the document again as the frame's recording did, or as the one an unrecorded frame keeps, which+ // the compositor has to show: a clock frame presented before the committed one may have taken its place.+ let committed = &self.seal;+ let source = committed+ .published+ .as_ref()+ .or(committed.paint_command_cache_source.as_ref())?;+ let held = state.compositor_display_list.as_ref()?;+ if held.output.display_list_id != source.display_list_id {+ return None;+ }+ let seal = Seal {+ paint_config: committed.paint_config,+ visual_context_tree_structural_epoch: Some(held.output.recorded_structural_epoch),+ sends_visual_context_tree: false,+ presented_other_scroll_offsets: false,+ scroll_requests: Vec::new(),+ keyboard_scroll_state: committed.keyboard_scroll_state.clone(),+ paint_command_cache_source: Some(held.output.clone()),+ publishes_recording: false,+ context_id: committed.context_id,+ present_viewport_rect: committed.present_viewport_rect,+ presented_by: FfiPresentedBy::Clock,+ published: None,+ visual_context_tree_mismatches_for_testing: false,+ generation: committed.generation,+ };+ drop(state);Some(Self {- presenter: PresenterBox(self.presenter.0),- sealed: SealedPresentationBox(sealed),+ presenter: self.presenter.clone(),+ seal: Box::new(seal),encoded_scroll_state: self.encoded_scroll_state.clone(),taken_visual_context_tree: None,})}- /// Gives the presenter and the seal back to the host, which takes them over.- pub(crate) fn into_ffi(self) -> FfiPresentation {- let Self { presenter, sealed, .. } = self;- let (presenter, sealed) = (- std::mem::ManuallyDrop::new(presenter),- std::mem::ManuallyDrop::new(sealed),- );- FfiPresentation {- presenter: presenter.0.as_ptr(),- sealed: sealed.0.as_ptr(),- }- }-/// Has the frames presented from the seal take `visual_contexts` to the compositor, the tree with which a clock/// tick's update left the one the seal held.pub(crate) fn take_visual_context_tree(&mut self, visual_contexts: ClockTickVisualContexts) {@@ -233,19 +592,22 @@ impl Presentation {tree,restructured_scroll_offsets,} = visual_contexts;- // A tree of another structure takes the scroll offsets of its own nodes.+ // A tree of another structure takes a new display list recorded against it, and the scroll offsets of its own+ // nodes. A frame that records nothing seals no tree, and takes the render state's: the compositor's display list+ // was cut from a tree of its structure.let tree_is_restructured = restructured_scroll_offsets.is_some();if let Some(scroll_offsets) = restructured_scroll_offsets {self.encoded_scroll_state = ScrollStateSnapshot::from_device_offsets(scroll_offsets).to_encoded_bytes();}- // SAFETY: The presentation owns the seal.- unsafe {- web_sealed_presentation_take_visual_context_tree(- self.sealed.0.as_ptr(),- tree.structural_epoch,- tree_is_restructured,+ if !tree_is_restructured && let Some(epoch) = self.seal.visual_context_tree_structural_epoch {+ assert_eq!(+ tree.structural_epoch, epoch,+ "a tree of the same structure keeps its structural epoch");}+ self.seal.visual_context_tree_structural_epoch = Some(tree.structural_epoch);+ // A frame whose display list is the one the compositor has takes the tree on its own.+ self.seal.sends_visual_context_tree = true;self.taken_visual_context_tree = Some(tree);}@@ -262,114 +624,257 @@ impl Presentation {restructured_scroll_offsets: None,});}- let lent_visual_context_tree = LentVisualContextTree::new(self.taken_visual_context_tree.as_ref());- let visual_context_tree = lent_visual_context_tree.to_ffi();- // SAFETY: The presentation owns both objects and the tree it lends, the presenter copies the scroll state and- // what it keeps of the tree, and the stage holds the sink.- unsafe {- web_navigable_presenter_present_unrecorded(- self.presenter.0.as_ptr(),- self.sealed.0.as_ptr(),- &raw const visual_context_tree,- self.encoded_scroll_state.as_ptr(),- self.encoded_scroll_state.len(),- presenting.sink(),- );+ let presenter = self.presenter.clone();+ let mut state = presenter.state();+ if state.is_stale(&self.seal) {+ return;}+ let tree = self+ .taken_visual_context_tree+ .clone()+ .or_else(|| {+ state+ .compositor_display_list+ .as_ref()+ .and_then(|display_list| display_list.output.visual_context_tree.clone())+ })+ .unwrap_or_else(|| Arc::new(VisualContextTree::create_identity()));+ let mut frame = state.build_frame(&self.seal, None, &tree, &self.encoded_scroll_state);+ frame.scroll_requests = std::mem::take(&mut self.seal.scroll_requests);+ state.note_presented(&mut self.seal, &self.encoded_scroll_state);+ presenting.post_frame(frame);}- /// Presents the sealed frame with the recording that left `output`, whose resources the presenter took already. The- /// frame goes with the tree a clock tick's update left, or else the one the recording was recorded against: a- /// recording that repeats the display list it published before publishes that list again, which holds the tree of- /// the recording before.- pub(crate) fn present(&mut self, output: &crate::painting::record::RecordingOutput, presenting: &mut Presenting) {- let presented = FfiPresentedRecording::of_output(output);+ /// Presents the sealed frame with the recording that left `output`. The frame goes with the tree a clock tick's update+ /// left, or else the one the recording was recorded against: a recording that repeats the display list it published+ /// before publishes that list again.+ pub(crate) fn present(&mut self, output: &Arc<RecordingOutput>, presenting: &mut Presenting) {let tree = self.taken_visual_context_tree- .as_ref()- .or(output.visual_context_tree.as_ref());- debug_assert!(- tree.is_some_and(|tree| tree.structural_epoch == output.recorded_structural_epoch),+ .clone()+ .or_else(|| output.visual_context_tree.clone())+ .expect("a recording was recorded against a tree");+ debug_assert_eq!(+ tree.structural_epoch, output.recorded_structural_epoch,"a frame goes with a tree of the structure its recording was recorded against");- let lent_visual_context_tree = LentVisualContextTree::new(tree);- let visual_context_tree = lent_visual_context_tree.to_ffi();- // SAFETY: The presentation owns both objects and the tree it lends, the recording's display list is live for- // the call, the presenter copies the scroll state and what it keeps of the tree, and the stage holds the sink.- unsafe {- web_navigable_presenter_present(- self.presenter.0.as_ptr(),- self.sealed.0.as_ptr(),- &raw const presented,- &raw const visual_context_tree,- self.encoded_scroll_state.as_ptr(),- self.encoded_scroll_state.len(),- presenting.sink(),- );+ let presenter = self.presenter.clone();+ let mut state = presenter.state();+ if state.is_stale(&self.seal) {+ return;}+ let replaces_paint_command_cache_source = self.seal.publishes_recording+ && !self+ .seal+ .paint_command_cache_source+ .as_ref()+ .is_some_and(|source| source.display_list_id == output.display_list_id);+ let mut frame = state.build_frame(+ &self.seal,+ Some(Published {+ output,+ replaces_paint_command_cache_source,+ }),+ &tree,+ &self.encoded_scroll_state,+ );+ if replaces_paint_command_cache_source {+ self.seal.paint_command_cache_source = Some(output.clone());+ }+ self.seal.published = Some(output.clone());+ frame.scroll_requests = std::mem::take(&mut self.seal.scroll_requests);+ state.note_presented(&mut self.seal, &self.encoded_scroll_state);+ presenting.post_frame(frame);}}-#[cfg(test)]-mod ffi_test_stubs {- use super::{FfiPresentedRecording, FfiPresentedVisualContextTree};- use std::ffi::c_void;-- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_unref(_: *mut c_void) {}+/// The fonts and image frames of a resource transaction go ahead of it, in messages the C++ of the compositor takes,+/// which C++ encodes. Answers whether the compositor could still be reached.+fn post_resources_ahead(+ poster: &crate::paint_stage::CompositorPoster,+ context_id: CompositorContextId,+ resources: &ResourceUpdate,+) -> bool {+ poster.post_fonts_and_image_frames(context_id, &resources.fonts, &resources.image_frames)+}- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_seal_for_clock_lane(_: *mut c_void, _: *const c_void) -> *mut c_void {- std::ptr::null_mut()+impl Presenting<'_> {+ /// Hands `frame` to the compositor, or drops it while the compositor cannot be reached.+ fn post_frame(&mut self, frame: CompositorFrame) {+ let Some(poster) = self.poster() else {+ return;+ };+ if !post_frame_through(poster, frame) {+ self.lose_compositor();+ }}+}- #[unsafe(no_mangle)]- extern "C" fn web_sealed_presentation_destroy(_: *mut c_void) {}-- #[unsafe(no_mangle)]- extern "C" fn web_sealed_presentation_take_visual_context_tree(_: *mut c_void, _: u64, _: bool) {}+/// Posts the messages of `frame` through `poster`, in order. Answers whether the compositor could still be reached: a+/// display list that cannot be placed in shared memory is skipped, and the rest of the frame still goes over.+fn post_frame_through(poster: &crate::paint_stage::CompositorPoster, frame: CompositorFrame) -> bool {+ let CompositorFrame {+ context_id,+ display_list_update,+ visual_context_tree_update,+ scroll_state_update,+ scroll_requests,+ present_viewport_rect,+ } = frame;+ if let Some(update) = display_list_update {+ if !post_resources_ahead(poster, context_id, &update.resources) {+ return false;+ }+ let storage = DisplayListStorage::recorded(+ update.output.display_list.clone(),+ update+ .output+ .visual_context_tree+ .clone()+ .unwrap_or_else(|| Arc::new(VisualContextTree::create_identity())),+ );+ match poster.shared_buffer_with(storage.packed_size(), |destination| storage.write_packed(destination)) {+ Some(display_list_buffer) => {+ let message = UpdateDisplayList {+ context_id,+ display_list_buffer,+ tape_size: storage.bytes().len() as u64,+ run_count: storage.command_runs().len() as u64,+ display_list_properties: update.properties,+ async_scrolling_metadata: Some(update.async_scrolling_metadata),+ visual_context_tree: update.visual_context_tree,+ resource_transaction: update.resources.transaction,+ scroll_state: update.scroll_state,+ };+ if !poster.post(message) {+ return false;+ }+ }+ None => {+ eprintln!(+ "WebContent: Could not place a {} byte display list in shared memory",+ storage.bytes().len()+ );+ }+ }+ }+ if let Some(update) = visual_context_tree_update {+ if !post_resources_ahead(poster, context_id, &update.resources) {+ return false;+ }+ let message = UpdateVisualContextTree {+ context_id,+ visual_context_tree: update.visual_context_tree,+ resource_transaction: update.resources.transaction,+ scroll_state: update.scroll_state,+ keyboard_scroll_state: update.keyboard_scroll_state,+ };+ if !poster.post(message) {+ return false;+ }+ }+ if let Some(update) = scroll_state_update {+ let message = UpdateScrollState {+ context_id,+ scroll_state: update.scroll_state,+ keyboard_scroll_state: update.keyboard_scroll_state,+ };+ if !poster.post(message) {+ return false;+ }+ }+ if !scroll_requests.is_empty()+ && !poster.post(ApplyScrollRequests {+ context_id,+ scroll_requests,+ })+ {+ return false;+ }+ if let Some(viewport_rect) = present_viewport_rect+ && !poster.post(PresentFrame {+ context_id,+ viewport_rect,+ })+ {+ return false;+ }+ true+}- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_add_font(_: *mut c_void, _: *const c_void) {}+/// A new presenter, with one reference the caller takes over.+#[unsafe(no_mangle)]+pub extern "C" fn navigable_presenter_create() -> *const NavigablePresenter {+ Arc::into_raw(Arc::new(NavigablePresenter::default()))+}- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_add_image_frame(_: *mut c_void, _: *const c_void) {}+/// Gives up a reference to `presenter`.+///+/// # Safety+///+/// `presenter` must be a reference to a presenter the caller holds.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn navigable_presenter_release(presenter: *const NavigablePresenter) {+ // SAFETY: Guaranteed by the caller.+ drop(unsafe { Arc::from_raw(presenter) });+}- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_add_video_sink(_: *mut c_void, _: u64, _: u64) {}+/// Writes the paint config of the display list the compositor context holds to `out`, and answers whether it holds one.+#[unsafe(no_mangle)]+pub extern "C" fn navigable_presenter_compositor_display_list_paint_config(+ presenter: &NavigablePresenter,+ out: &mut FfiPaintConfig,+) -> bool {+ let Some(paint_config) = presenter.state().compositor_display_list_paint_config else {+ return false;+ };+ *out = paint_config;+ true+}- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_present(- _: *mut c_void,- _: *mut c_void,- _: *const FfiPresentedRecording,- _: *const FfiPresentedVisualContextTree,- _: *const u8,- _: usize,- _: *mut c_void,- ) {- }+/// Writes the structural epoch of the visual context tree the display list the compositor context holds was recorded+/// against to `out`, and answers whether it holds one.+#[unsafe(no_mangle)]+pub extern "C" fn navigable_presenter_compositor_display_list_structural_epoch(+ presenter: &NavigablePresenter,+ out: &mut u64,+) -> bool {+ let state = presenter.state();+ let Some(display_list) = state.compositor_display_list.as_ref() else {+ return false;+ };+ *out = display_list.output.recorded_structural_epoch;+ true+}- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_present_unrecorded(- _: *mut c_void,- _: *mut c_void,- _: *const FfiPresentedVisualContextTree,- _: *const u8,- _: usize,- _: *mut c_void,- ) {- }+/// Forgets what the compositor context holds: a new compositor process holds nothing.+#[unsafe(no_mangle)]+pub extern "C" fn navigable_presenter_forget_compositor_display_list(presenter: &NavigablePresenter) {+ let mut state = presenter.state();+ state.compositor_display_list_paint_config = None;+ state.compositor_display_list = None;+ state.compositor_resource_ids = ResourceIds::default();+}- #[unsafe(no_mangle)]- extern "C" fn web_vector_image_resources_destroy(_: *mut c_void) {}+/// What presented the navigable's last frame.+#[unsafe(no_mangle)]+pub extern "C" fn navigable_presenter_last_frame_presented_by(presenter: &NavigablePresenter) -> FfiPresentedBy {+ presenter+ .state()+ .last_frame_presented_by+ .unwrap_or(FfiPresentedBy::None)+}- #[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_take_vector_image_resources(- _: *mut c_void,- _: *mut c_void,- _: *const u64,- _: usize,- ) {- }+/// Writes the generation of the keyboard scroll state the last frame handed the compositor to `out`, and answers+/// whether it handed one.+#[unsafe(no_mangle)]+pub extern "C" fn navigable_presenter_last_keyboard_scroll_state_generation(+ presenter: &NavigablePresenter,+ out: &mut u64,+) -> bool {+ let Some(generation) = presenter.state().last_keyboard_scroll_state_generation else {+ return false;+ };+ *out = generation;+ true}diff --git a/Libraries/LibWeb/Rust/src/painting/rasterize.rs b/Libraries/LibWeb/Rust/src/painting/rasterize.rsnew file mode 100644index 00000000000..d6132326a81--- /dev/null+++ b/Libraries/LibWeb/Rust/src/painting/rasterize.rs@@ -0,0 +1,203 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Rasterizing an image into a bitmap of the host's, such as a cursor, an image bitmap or a notification icon: a display+//! list that draws the image, which the compositor rasterizes into the bitmap.++use crate::paint_stage::CompositorPoster;+use crate::painting::display_list::builder::RecordedDisplayList;+use crate::painting::display_list::commands::{DisplayListResourceId, ImageFrameResourceId};+use crate::painting::display_list::ids::allocate_display_list_id;+use crate::painting::display_list::storage::DisplayListStorage;+use crate::painting::display_list_resources::{DisplayListResources, NestedDisplayList};+use crate::painting::force_dark::ForceDarkRole;+use crate::painting::vector_image_cache::{FfiVectorImageKey, VectorImageKey};+use crate::painting::visual_context::VisualContextTree;+use crate::render_state::DocumentHost;+use libcompositing_rust::ipc_types::compositor_web_content_server::messages::RasterizeDisplayList;+use libcompositing_rust::ipc_types::{Compositing_DisplayListProperties, Compositing_DisplayListResourceTransaction};+use libgfx_rust::font::FontHandle;+use libgfx_rust::image_frame::ImageFrameHandle;+use libgfx_rust::{CompositingAndBlendingOperator, FloatRect, IntSize, ScalingMode};+use libipc_rust::cpp_connection::FfiThreadSafeMessagePoster;+use std::ffi::c_void;+use std::sync::Arc;++/// What an image is rasterized as.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+#[expect(dead_code, reason = "C++ constructs the variants")]+pub enum FfiImageRasterizationKind {+ DecodedFrame,+ VectorImage,+ Gradient,+}++/// An image to rasterize, and where in the bitmap it goes.+#[derive(Clone, Copy)]+#[repr(C)]+pub struct FfiImageRasterization {+ pub kind: FfiImageRasterizationKind,+ pub device_pixels_per_css_pixel: f64,+ pub dest_rect: FloatRect,+ /// The `Gfx::DecodedImageFrame` a decoded frame draws.+ pub image_frame: *const c_void,+ pub scaling_mode: ScalingMode,+ /// The host of the document of the SVG image an SVG image draws, which keeps its rendering for `vector_image_key`.+ pub vector_image_host: *const DocumentHost,+ pub vector_image_key: FfiVectorImageKey,+ pub vector_image_size: IntSize,+ pub gradient_style_value: *const c_void,+ pub gradient_tile_size: crate::layout::used_values::FfiCssPixelSize,+ /// The `FfiColorResolutionStyle` the gradient's color stops resolve against.+ pub gradient_stop_color_resolution_style: *const c_void,+}++/// The display list that draws `image`, and what it draws besides its tape.+///+/// # Safety+///+/// What `image` points at must be live for the call.+unsafe fn record_image(image: &FfiImageRasterization) -> (RecordedDisplayList, DisplayListResources) {+ use crate::css::color_resolution::ColorResolutionInput;+ use crate::painting::display_list::device_pixels::DevicePixelConverter;+ use crate::painting::display_list::recorder::DisplayListRecorder;+ use crate::painting::record::paint::gradient_resolution::{+ record_resolved_gradient_fill, resolve_gradient_paint_with_input,+ };+ // Force-dark never reaches here: an image is darkened by classifying the image itself — not by inverting the fills+ // that raster it.+ let mut recorder = DisplayListRecorder::new(None);+ let mut resources = DisplayListResources::default();+ let dest_rect = image.dest_rect;+ match image.kind {+ FfiImageRasterizationKind::DecodedFrame => {+ // SAFETY: The caller keeps the frame live for the call.+ let frame = unsafe { ImageFrameHandle::retain(image.image_frame) };+ recorder.draw_scaled_decoded_image_frame(+ dest_rect,+ None,+ ImageFrameResourceId(frame.id()),+ image.scaling_mode,+ CompositingAndBlendingOperator::Normal,+ None,+ ForceDarkRole::None,+ );+ resources.image_frames.insert(frame.id(), frame);+ }+ FfiImageRasterizationKind::VectorImage => {+ // SAFETY: The caller keeps the host live for the call.+ let display_list = unsafe { image.vector_image_host.as_ref() }+ .and_then(|host| host.vector_image(&VectorImageKey::of(&image.vector_image_key)))+ .unwrap_or_else(NestedDisplayList::empty);+ recorder.paint_nested_display_list(+ DisplayListResourceId(display_list.id()),+ dest_rect,+ image.vector_image_size,+ );+ resources.nested_display_lists.insert(display_list.id(), display_list);+ }+ FfiImageRasterizationKind::Gradient => {+ // SAFETY: The caller keeps the gradient style value and the style its color stops resolve against live for+ // the call.+ let (gradient_style_value, color_input) = unsafe {+ (+ &*image+ .gradient_style_value+ .cast::<crate::css::style_value::StyleValueData>(),+ ColorResolutionInput::for_ffi_style(image.gradient_stop_color_resolution_style.cast()),+ )+ };+ let resolved =+ resolve_gradient_paint_with_input(gradient_style_value, image.gradient_tile_size.into(), &color_input);+ record_resolved_gradient_fill(+ &mut recorder,+ DevicePixelConverter::new(image.device_pixels_per_css_pixel),+ &resolved,+ dest_rect,+ CompositingAndBlendingOperator::Normal,+ ForceDarkRole::None,+ );+ }+ }+ (recorder.into_builder().finish(), resources)+}++/// Stages what the display list draws under `token` and hands it to the compositor to rasterize into `target_bitmap`.+/// Answers whether the compositor could still be reached.+fn post_rasterization(+ poster: &CompositorPoster,+ token: u64,+ display_list: RecordedDisplayList,+ resources: DisplayListResources,+ target_bitmap: *const c_void,+) -> bool {+ let resources = resources.with_nested_resources();+ let fonts: Vec<FontHandle> = resources.fonts.values().cloned().collect();+ let image_frames: Vec<ImageFrameHandle> = resources.image_frames.values().cloned().collect();+ let video_sinks: Vec<(u64, u64)> = resources+ .video_sinks+ .iter()+ .map(|(id, handle)| (*id, *handle))+ .collect();+ // SAFETY: The caller keeps the bitmap live for the call.+ if !unsafe { poster.stage_rasterization(token, &fonts, &image_frames, &video_sinks, target_bitmap) } {+ return false;+ }+ let tree = Arc::new(VisualContextTree::create_identity());+ let storage = DisplayListStorage::recorded(Arc::new(display_list), tree.clone());+ let Some(display_list_buffer) =+ poster.shared_buffer_with(storage.packed_size(), |destination| storage.write_packed(destination))+ else {+ eprintln!(+ "WebContent: Could not place a {} byte display list to rasterize in shared memory",+ storage.bytes().len()+ );+ return false;+ };+ poster.post(RasterizeDisplayList {+ token,+ display_list_buffer,+ tape_size: storage.bytes().len() as u64,+ run_count: storage.command_runs().len() as u64,+ display_list_properties: Compositing_DisplayListProperties {+ id: allocate_display_list_id(),+ compatible_visual_context_tree_structural_epoch: tree.structural_epoch,+ surface_clear_color: None,+ root_group_color: libgfx_rust::Color::TRANSPARENT,+ },+ visual_context_tree: tree.to_bytes(),+ nested_display_lists: Compositing_DisplayListResourceTransaction {+ display_lists: resources+ .nested_display_lists+ .values()+ .map(|display_list| display_list.resource.clone())+ .collect(),+ ..Default::default()+ },+ })+}++/// Has the compositor rasterize `image` into `target_bitmap`, a shareable `Gfx::Bitmap`, through `poster`, under `token`,+/// which the compositor's answer names. Answers whether the image went to the compositor.+///+/// # Safety+///+/// `poster` must hold one reference to a live poster on the transport of the connection to the compositor, which the+/// caller gives up, and what `image` points at and `target_bitmap` must be live for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_rasterize_image(+ poster: FfiThreadSafeMessagePoster,+ token: u64,+ image: &FfiImageRasterization,+ target_bitmap: *const c_void,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let poster = unsafe { CompositorPoster::adopt(poster) };+ // SAFETY: As above.+ let (display_list, resources) = unsafe { record_image(image) };+ post_rasterization(&poster, token, display_list, resources, target_bitmap)+}diff --git a/Libraries/LibWeb/Rust/src/painting/record/inputs.rs b/Libraries/LibWeb/Rust/src/painting/record/inputs.rsindex 7037b455979..2632ede9ab3 100644--- a/Libraries/LibWeb/Rust/src/painting/record/inputs.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/inputs.rs@@ -69,6 +69,10 @@ pub(crate) struct RecordingInputs {pub opaque_canvas: bool,pub bitmap_rect: IntRect,pub publishes_recording: bool,+ /// What the compositor clears the surface with below the recording, for a top-level traversable.+ pub surface_clear_color: Option<Color>,+ /// What the recording's display list is stamped with for async scrolling, but for the keyboard scroll state.+ pub async_scrolling_metadata: Option<libcompositing_rust::ipc_types::Compositing_AsyncScrollingMetadata>,pub window_is_focused: bool,pub outline_auto_color: Color,pub selection_background_from_palette: Color,diff --git a/Libraries/LibWeb/Rust/src/painting/record/mod.rs b/Libraries/LibWeb/Rust/src/painting/record/mod.rsindex 9e1a24fb9db..0ffa24734d6 100644--- a/Libraries/LibWeb/Rust/src/painting/record/mod.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/mod.rs@@ -67,6 +67,15 @@ pub struct RecordingOutput {pub(crate) capture_log: Option<trace::CaptureLog>,/// The SVG images whose display lists, which the host rendered, the recording draws, and the ids of those lists.pub(crate) vector_image_display_lists: Vec<(vector_images::VectorImageRenderRequest, u64)>,+ /// What the display list draws besides its tape.+ pub(crate) resources: crate::painting::display_list_resources::DisplayListResources,+ /// The display list's id, which a recording that repeats the one published last shares with it.+ pub display_list_id: u64,+ /// What the compositor clears the surface with below the display list, for a top-level traversable.+ pub surface_clear_color: Option<libgfx_rust::Color>,+ /// What the display list is stamped with for async scrolling, but for the keyboard scroll state, which each frame+ /// sets.+ pub async_scrolling_metadata: Option<libcompositing_rust::ipc_types::Compositing_AsyncScrollingMetadata>,}pub(crate) struct RecordingResult {diff --git a/Libraries/LibWeb/Rust/src/painting/record/publish.rs b/Libraries/LibWeb/Rust/src/painting/record/publish.rsindex 40ebdadff16..a949b89d1d0 100644--- a/Libraries/LibWeb/Rust/src/painting/record/publish.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/publish.rs@@ -6,6 +6,7 @@use crate::layout::LayoutNodeArena;use crate::painting::display_list::commands::{DisplayListCommandType, DisplayListResourceId, PaintNestedDisplayList};+use crate::painting::display_list_resources::{DisplayListResources, NestedDisplayList, summary_of};use crate::painting::hit_test::HitTestList;use crate::painting::host::FfiRecordingPublishCallbacks;use crate::painting::paint_state::PendingRecording;@@ -17,36 +18,46 @@ use crate::painting::record::vector_images::{use crate::painting::record::{RecordingOutput, RecordingResult};use crate::painting::recording_slot::Publication;use crate::painting::svg_paint_resources::published_filter_image_frames_in;+use crate::painting::vector_image_cache::VectorImageKey;use crate::stage::MainThread;+use std::collections::HashMap;+use std::sync::Arc;fn resolve_vector_image_placeholders(output: &mut RecordingOutput,requests: &[VectorImageRenderRequest],main_thread: &MainThread,publish: &FfiRecordingPublishCallbacks,-) -> Vec<u64> {+) -> Vec<Arc<NestedDisplayList>> {if requests.is_empty() {return Vec::new();}- let resolved_ids = render_vector_images(requests, main_thread, publish);- patch_vector_image_placeholders(output, &resolved_ids);- resolved_ids+ let display_lists = render_vector_images(requests, main_thread, publish);+ patch_vector_image_placeholders(output, &display_lists);+ display_lists}-/// Has the host render the SVG images of `requests`, and answers the ids of their display lists, one for each request.+/// Has the host render the SVG images of `requests`, and answers their display lists, one for each request: the one the+/// image's document keeps for the request, or an empty one where the image has nothing to show.pub(crate) fn render_vector_images(requests: &[VectorImageRenderRequest],main_thread: &MainThread,publish: &FfiRecordingPublishCallbacks,-) -> Vec<u64> {+) -> Vec<Arc<NestedDisplayList>> {requests.iter()- .map(|request| publish.resolve_vector_image_display_list(main_thread, &request.to_ffi()))+ .map(|request| {+ let request = request.to_ffi();+ publish+ .render_vector_image(main_thread, &request)+ .and_then(|image_host| image_host.vector_image(&VectorImageKey::of_request(&request)))+ .unwrap_or_else(NestedDisplayList::empty)+ }).collect()}-/// Patches the placeholders of SVG images in `output` with `resolved_ids`, the ids of their display lists.-fn patch_vector_image_placeholders(output: &mut RecordingOutput, resolved_ids: &[u64]) {+/// Patches the placeholders of SVG images in `output` with the ids of `display_lists`, one for each image.+fn patch_vector_image_placeholders(output: &mut RecordingOutput, display_lists: &[Arc<NestedDisplayList>]) {let display_list = std::sync::Arc::make_mut(&mut output.display_list);let id_field_offset = std::mem::offset_of!(PaintNestedDisplayList, display_list_id);let mut patch_offsets = Vec::new();@@ -61,7 +72,7 @@ fn patch_vector_image_placeholders(output: &mut RecordingOutput, resolved_ids: &if is_vector_image_placeholder(id) {patch_offsets.push((payload_offset + id_field_offset,- resolved_ids[vector_image_placeholder_index(id)],+ display_lists[vector_image_placeholder_index(id)].id(),));}},@@ -109,49 +120,17 @@ pub(crate) fn publish_recording(}}-/// Where a published recording's fonts, image frames and video sinks go: the resource storage of the presenter that-/// presents it.-pub(crate) trait RecordingResourceSink {- fn add_font(&mut self, font: &libgfx_rust::font::FontHandle);- fn add_image_frame(&mut self, frame: &libgfx_rust::image_frame::ImageFrameHandle);- fn add_video_sink(&mut self, resource_id: u64, sink_handle: u64);-}--/// The host's resource storage, which it reaches on the main thread through its callbacks.-struct HostResourceSink<'a, 'host> {- main_thread: &'a MainThread<'host>,- publish: &'a FfiRecordingPublishCallbacks,-}--impl RecordingResourceSink for HostResourceSink<'_, '_> {- fn add_font(&mut self, font: &libgfx_rust::font::FontHandle) {- self.publish.add_font(self.main_thread, font);- }-- fn add_image_frame(&mut self, frame: &libgfx_rust::image_frame::ImageFrameHandle) {- self.publish.add_image_frame(self.main_thread, frame);- }-- fn add_video_sink(&mut self, resource_id: u64, sink_handle: u64) {- self.publish.add_video_sink(self.main_thread, resource_id, sink_handle);- }-}--/// Hands a recording's resources to the host and makes its output, reading nothing but the-/// recording and the recorder state it recorded with: what a publication does before the-/// document takes the output in.+/// Makes a recording's output, with the host rendering its SVG images, reading nothing but the recording and the+/// recorder state it recorded with: what a publication does before the document takes the output in.pub(crate) fn publish_to_host(pending: PendingRecording,recorder: &RecorderState,main_thread: &MainThread,publish: &FfiRecordingPublishCallbacks,) -> RecordingOutput {- publish_resources(- pending,- recorder,- &mut HostResourceSink { main_thread, publish },- |output, requests| resolve_vector_image_placeholders(output, requests, main_thread, publish),- )+ publish_resources(pending, recorder, |output, requests| {+ resolve_vector_image_placeholders(output, requests, main_thread, publish)+ })}/// Whether a recording renders an SVG image, which only the host renders, so that only the host publishes it.@@ -159,38 +138,31 @@ pub(crate) fn renders_vector_images(pending: &PendingRecording) -> bool {!pending.recording.resources.vector_image_render_requests.is_empty()}-/// Hands the resources of a recording that renders no SVG image to `presenter` and makes its output, beside the event-/// loop.-pub(crate) fn publish_to_presenter(- pending: PendingRecording,- recorder: &RecorderState,- presenter: &mut crate::painting::presentation::PresenterBox,-) -> RecordingOutput {+/// Makes the output of a recording that renders no SVG image, beside the event loop.+pub(crate) fn publish_to_presenter(pending: PendingRecording, recorder: &RecorderState) -> RecordingOutput {debug_assert!(!renders_vector_images(&pending), "only the host renders an SVG image");- publish_resources(pending, recorder, presenter, |_, _| Vec::new())+ publish_resources(pending, recorder, |_, _| Vec::new())}-/// Hands the resources of a recording that renders SVG images to `presenter` and makes its output, beside the event-/// loop, with `display_list_ids`, the ids of the display lists the host rendered them as, which the presenter has.+/// Makes the output of a recording that renders SVG images, beside the event loop, with `display_lists`, those the host+/// rendered them as, one for each of the images.pub(crate) fn publish_with_vector_images(pending: PendingRecording,recorder: &RecorderState,- presenter: &mut crate::painting::presentation::PresenterBox,- display_list_ids: &[u64],+ display_lists: &[Arc<NestedDisplayList>],) -> RecordingOutput {- publish_resources(pending, recorder, presenter, |output, _| {- patch_vector_image_placeholders(output, display_list_ids);- display_list_ids.to_vec()+ publish_resources(pending, recorder, |output, _| {+ patch_vector_image_placeholders(output, display_lists);+ display_lists.to_vec()})}-/// The ids of the display lists the host rendered the SVG images of `pending` as for the recording published last with-/// `recorder`, which the presenter keeps while the recording it presents draws them, one for each of the images, or-/// none where one of the images is new to that recording.+/// The display lists the host rendered the SVG images of `pending` as for the recording published last with `recorder`,+/// one for each of the images, or none where one of the images is new to that recording.pub(crate) fn published_vector_image_display_lists(pending: &PendingRecording,recorder: &RecorderState,-) -> Option<Vec<u64>> {+) -> Option<Vec<Arc<NestedDisplayList>>> {let published = recorder.published_recording.as_ref()?;pending.recording@@ -198,10 +170,11 @@ pub(crate) fn published_vector_image_display_lists(.vector_image_render_requests.iter().map(|request| {- published+ let id = published.vector_image_display_lists.iter()- .find_map(|(published_request, id)| (published_request == request).then_some(*id))+ .find_map(|(published_request, id)| (published_request == request).then_some(*id))?;+ published.resources.nested_display_lists.get(&id).cloned()}).collect()}@@ -243,13 +216,12 @@ fn drawn_vector_image_display_lists(drawn}-/// Hands a recording's resources to `sink`, has `resolve_vector_images` patch in the SVG images it renders, and makes-/// its output.+/// Makes a recording's output: has `resolve_vector_images` patch in the SVG images it renders, and gathers everything+/// its display list draws besides its tape.fn publish_resources(pending: PendingRecording,recorder: &RecorderState,- sink: &mut impl RecordingResourceSink,- resolve_vector_images: impl FnOnce(&mut RecordingOutput, &[VectorImageRenderRequest]) -> Vec<u64>,+ resolve_vector_images: impl FnOnce(&mut RecordingOutput, &[VectorImageRenderRequest]) -> Vec<Arc<NestedDisplayList>>,) -> RecordingOutput {let PendingRecording {recording: RecordingResult { mut output, resources },@@ -263,19 +235,28 @@ fn publish_resources(vector_image_render_requests,..} = resources;- for font in fonts.values() {- sink.add_font(font);- }- for frame in image_frames.values() {- sink.add_image_frame(frame);- }+ let mut display_list_resources = DisplayListResources {+ fonts: fonts.into_iter().map(|(id, font)| (id.0, font)).collect(),+ image_frames,+ video_sinks,+ nested_display_lists: HashMap::new(),+ };+ // The filters of the visual context tree's effects draw these.for frame in published_filter_image_frames_in(&svg_paint_resources) {- sink.add_image_frame(&frame);+ display_list_resources.image_frames.entry(frame.id()).or_insert(frame);+ }+ let resolved = resolve_vector_images(&mut output, &vector_image_render_requests);+ let resolved_ids: Vec<u64> = resolved.iter().map(|display_list| display_list.id()).collect();+ for display_list in resolved {+ display_list_resources+ .nested_display_lists+ .insert(display_list.id(), display_list);}- for (resource_id, sink_handle) in video_sinks {- sink.add_video_sink(resource_id, sink_handle);+ // What the recording copied from the one it read paint commands from draws what that one drew.+ if let Some(source) = recorder.published_recording.as_deref() {+ display_list_resources.complete_from(&summary_of(&output.display_list), &source.resources);}- let resolved_ids = resolve_vector_images(&mut output, &vector_image_render_requests);+ output.resources = display_list_resources;// Only a recording that publishes becomes the one the next recording copies from, so only it keeps the SVG images// it carried over from the one published last.let published = recorder.published_recording.as_deref().filter(|_| publishes_recording);@@ -292,6 +273,11 @@ fn publish_resources(&& output.wheel_event_listener_state_generation == source.wheel_event_listener_state_generation&& output.has_blocking_wheel_event_listeners == source.has_blocking_wheel_event_listeners});+ // A recording that repeats the one published last publishes its display list again, under its id.+ output.display_list_id = match recorder.published_recording.as_deref() {+ Some(source) if output.is_identical_to_published_recording => source.display_list_id,+ _ => crate::painting::display_list::ids::allocate_display_list_id(),+ };output}diff --git a/Libraries/LibWeb/Rust/src/painting/record/traversal.rs b/Libraries/LibWeb/Rust/src/painting/record/traversal.rsindex bfc81b33a88..fcbcfc25259 100644--- a/Libraries/LibWeb/Rust/src/painting/record/traversal.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/traversal.rs@@ -193,6 +193,10 @@ fn record_display_list_impl<O: Observer>(window_is_focused: inputs.window_is_focused,capture_log: recorder.observer.finish(),vector_image_display_lists: Vec::new(),+ resources: Default::default(),+ display_list_id: 0,+ surface_clear_color: None,+ async_scrolling_metadata: None,};RecordingResult {output,diff --git a/Libraries/LibWeb/Rust/src/painting/recorded_scrolling.rs b/Libraries/LibWeb/Rust/src/painting/recorded_scrolling.rsnew file mode 100644index 00000000000..7b10ea1dd20--- /dev/null+++ b/Libraries/LibWeb/Rust/src/painting/recorded_scrolling.rs@@ -0,0 +1,138 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the scroll logic of the compositor makes of the recording a document published last, before the recording+//! reaches the compositor, for tests.++use crate::painting::display_list::storage::DisplayListStorage;+use crate::painting::presentation::display_list_properties_of;+use crate::painting::record::RecordingOutput;+use crate::render_state::DocumentHost;+use libcompositing_rust::scrolling::DisplayList;+use libgfx_rust::FloatPoint;+use std::ffi::c_void;+use std::sync::Arc;++/// Where the first step of a wheel gesture goes: `Compositing::FirstWheelStepRouteForTesting`, with the routing decision+/// and the scroller's kind as their `Web::InputRoutingDecision` and `Web::AsyncScrollNodeKind` values.+#[repr(C)]+#[derive(Default)]+pub struct FfiRecordedFirstWheelStepRoute {+ pub decision: u8,+ pub has_scroller: bool,+ pub scroller_node_id: i64,+ pub scroller_kind: u8,+ pub scroller_pseudo_element_type: u8,+ pub has_document_id: bool,+ pub document_id: i64,+}++/// The display list `output` published, as the compositor takes it, and the tree it was recorded against.+fn display_list_of(+ output: &RecordingOutput,+) -> Option<(DisplayList, Arc<crate::painting::visual_context::VisualContextTree>)> {+ let tree = output.visual_context_tree.clone()?;+ let properties = display_list_properties_of(output);+ let display_list = DisplayList::new(+ DisplayListStorage::recorded(output.display_list.clone(), tree.clone()),+ properties.id,+ properties.compatible_visual_context_tree_structural_epoch,+ output.async_scrolling_metadata.clone(),+ properties.surface_clear_color,+ properties.root_group_color,+ );+ Some((display_list, tree))+}++/// The recording `host`'s document published last, as the compositor takes it.+fn published_display_list(+ host: &DocumentHost,+) -> Option<(DisplayList, Arc<crate::painting::visual_context::VisualContextTree>)> {+ let recording = host.recording().published_recording()?;+ display_list_of(&recording)+}++/// Hands `receive` the scrolling state of the recording `host`'s document published last, as JSON, or the empty one+/// where it published none.+///+/// # Safety+///+/// `receive` must copy the UTF-8 bytes it keeps synchronously.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_recorded_async_scrolling_state_json(+ host: &DocumentHost,+ receiver: *mut c_void,+ receive: unsafe extern "C" fn(*mut c_void, *const u8, usize),+) {+ let display_list = published_display_list(host);+ let json = libcompositing_rust::ffi::recorded_display_list_async_scrolling_state_json(+ display_list.as_ref().map(|(display_list, tree)| (display_list, tree)),+ );+ // SAFETY: The caller copies what it keeps of the JSON synchronously.+ unsafe { receive(receiver, json.as_ptr(), json.len()) };+}++/// Hands `receive` the scrolling state of no display list, the empty one, as JSON.+///+/// # Safety+///+/// `receive` must copy the UTF-8 bytes it keeps synchronously.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_empty_async_scrolling_state_json(+ receiver: *mut c_void,+ receive: unsafe extern "C" fn(*mut c_void, *const u8, usize),+) {+ let json = libcompositing_rust::ffi::recorded_display_list_async_scrolling_state_json(None);+ // SAFETY: The caller copies what it keeps of the JSON synchronously.+ unsafe { receive(receiver, json.as_ptr(), json.len()) };+}++/// Writes where the first step of a wheel gesture at `position` by `delta_in_css_pixels` goes through the recording+/// `host`'s document published last to `out`, and answers whether it published one.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_recorded_route_first_wheel_step(+ host: &DocumentHost,+ newest_wheel_event_listener_state_generation: u64,+ position: FloatPoint,+ delta_in_css_pixels: FloatPoint,+ out: &mut FfiRecordedFirstWheelStepRoute,+) -> bool {+ let Some((display_list, tree)) = published_display_list(host) else {+ return false;+ };+ let route = libcompositing_rust::ffi::recorded_display_list_route_first_wheel_step(+ &display_list,+ &tree,+ (*host.scroll_state()).clone(),+ newest_wheel_event_listener_state_generation,+ position,+ delta_in_css_pixels,+ );+ *out = FfiRecordedFirstWheelStepRoute {+ decision: route.decision as u8,+ has_scroller: route.has_scroller,+ scroller_node_id: route.scroller_node_id,+ scroller_kind: route.scroller_kind as u8,+ scroller_pseudo_element_type: route.scroller_pseudo_element_type,+ has_document_id: route.has_document_id,+ document_id: route.document_id,+ };+ true+}++/// Whether a box of the recording `host`'s document published last blocks a wheel event at `position`.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_recorded_blocks_wheel_event_at(host: &DocumentHost, position: FloatPoint) -> bool {+ let Some((display_list, tree)) = published_display_list(host) else {+ return false;+ };+ libcompositing_rust::ffi::recorded_display_list_blocks_wheel_event_at(+ &display_list,+ &tree,+ (*host.scroll_state()).clone(),+ position,+ )+}diff --git a/Libraries/LibWeb/Rust/src/painting/recording_slot.rs b/Libraries/LibWeb/Rust/src/painting/recording_slot.rsindex 8343e2f3350..c4b9ef05bcd 100644--- a/Libraries/LibWeb/Rust/src/painting/recording_slot.rs+++ b/Libraries/LibWeb/Rust/src/painting/recording_slot.rs@@ -19,12 +19,12 @@use crate::layout::node_data::NodeSlotId;use crate::layout::{LayoutNodeArena, RowsVersion};use crate::paint_stage::Presenting;+use crate::painting::display_list_resources::NestedDisplayList;use crate::painting::ffi::FfiFlightBlocker;use crate::painting::hit_test::HitTestList;use crate::painting::paint_read::PaintSource;use crate::painting::paint_state::{PendingRecording, PendingRecordingTrace};use crate::painting::presentation::Presentation;-use crate::painting::presentation::VectorImageResources;use crate::painting::published_frame::PublishedFrame;use crate::painting::record::publish::PresentedOutput;use crate::painting::record::recorder_state::RecorderState;@@ -92,13 +92,12 @@ impl VectorImageFrame {&self.pending.recording.resources.vector_image_render_requests}- /// Presents the frame, recorded with `recorder`, with `resources`, the SVG images the host rendered, whose display- /// lists are `display_list_ids`, one for each of the frame's requests, beside the event loop.+ /// Presents the frame, recorded with `recorder`, with `display_lists`, those of the SVG images the host rendered, one+ /// for each of the frame's requests, beside the event loop.pub(crate) fn present(self,recorder: RecorderState,- display_list_ids: &[u64],- resources: VectorImageResources,+ display_lists: &[Arc<NestedDisplayList>],presenting: &mut Presenting,) -> RecordingAnswer {let Self {@@ -107,19 +106,10 @@ impl VectorImageFrame {rows_version,lane,} = self;- presentation- .presenter- .take_vector_image_resources(resources, display_list_ids);let publishes_recording = pending.publishes_recording;- let output = crate::painting::record::publish::publish_with_vector_images(- pending,- &recorder,- &mut presentation.presenter,- display_list_ids,- );- presentation.present(&output, presenting);+ let output = present_with_vector_images(&mut presentation, pending, &recorder, presenting, display_lists);let recorded = Recorded::Presented {- output: PresentedOutput::of(output),+ output,publishes_recording,};let answer = RecordingAnswer {@@ -300,13 +290,13 @@ impl RecordingJob {(Some(presentation), Some(presenting), Some(vector_image_display_lists)) => {let publishes_recording = pending.publishes_recording;let output = match vector_image_display_lists {- Some(display_list_ids) => {- present_with_vector_images(presentation, pending, &recorder, presenting, &display_list_ids)+ Some(display_lists) => {+ present_with_vector_images(presentation, pending, &recorder, presenting, &display_lists)}None => present(presentation, pending, &recorder, presenting),};Recorded::Presented {- output: PresentedOutput::of(output),+ output,publishes_recording,}}@@ -495,7 +485,7 @@ pub(crate) fn record_frame(published_inputs,} = recorder;let source = PaintSource::new(&frame, absolute_rects);- let (recording, publishes_recording) = paint_order_tree.with_access(inputs.publishes_recording, |tree| {+ let (mut recording, publishes_recording) = paint_order_tree.with_access(inputs.publishes_recording, |tree| {crate::painting::record::traversal::record_display_list(&source,scratch,@@ -507,6 +497,12 @@ pub(crate) fn record_frame(trace_recordings,)});+ let output = &mut recording.output;+ output.surface_clear_color = inputs.surface_clear_color;+ output.async_scrolling_metadata = inputs.async_scrolling_metadata.clone().map(|mut metadata| {+ metadata.has_blocking_wheel_event_listeners |= output.has_blocking_wheel_event_listeners;+ metadata+ });let trace = trace_recordings.then_some(PendingRecordingTrace {viewport,should_paint_overlay: inputs.should_paint_overlay,@@ -533,28 +529,29 @@ pub(crate) fn present(pending: PendingRecording,recorder: &RecorderState,presenting: &mut Presenting,-) -> RecordingOutput {- let output = crate::painting::record::publish::publish_to_presenter(pending, recorder, &mut presentation.presenter);- presentation.present(&output, presenting);+) -> PresentedOutput {+ let output = PresentedOutput::of(crate::painting::record::publish::publish_to_presenter(+ pending, recorder,+ ));+ presentation.present(&output.output, presenting);output}/// Presents `pending`, which renders SVG images and was recorded with `recorder`, with `presentation`, beside the event-/// loop, drawing them as the display lists `display_list_ids` names, which the presenter holds, and answers its output.+/// loop, drawing them as `display_lists`, those the host rendered them as, and answers its output.pub(crate) fn present_with_vector_images(presentation: &mut Presentation,pending: PendingRecording,recorder: &RecorderState,presenting: &mut Presenting,- display_list_ids: &[u64],-) -> RecordingOutput {- let output = crate::painting::record::publish::publish_with_vector_images(+ display_lists: &[Arc<NestedDisplayList>],+) -> PresentedOutput {+ let output = PresentedOutput::of(crate::painting::record::publish::publish_with_vector_images(pending,recorder,- &mut presentation.presenter,- display_list_ids,- );- presentation.present(&output, presenting);+ display_lists,+ ));+ presentation.present(&output.output, presenting);output}@@ -744,6 +741,15 @@ impl RecordingSlot {self.pending_recording_trace.take()}+ /// The recording the document published last, which the next recording copies from, while no recording is in+ /// flight.+ pub(crate) fn published_recording(&self) -> Option<Arc<RecordingOutput>> {+ match &self.recorder {+ Recorder::Here(recorder) => recorder.published_recording.clone(),+ Recorder::InFlight(_) => None,+ }+ }+/// Whether a recording of the document is in flight.pub(crate) fn has_recording_in_flight(&self) -> bool {matches!(self.recorder, Recorder::InFlight(_))diff --git a/Libraries/LibWeb/Rust/src/painting/vector_image_cache.rs b/Libraries/LibWeb/Rust/src/painting/vector_image_cache.rsnew file mode 100644index 00000000000..58396658d13--- /dev/null+++ b/Libraries/LibWeb/Rust/src/painting/vector_image_cache.rs@@ -0,0 +1,140 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The display lists an SVG image's document was rendered as, which the document keeps for the sizes, scales, color+//! schemes and force-dark settings the pages that draw it asked for, until what it shows changes.++use crate::css::css_pixels::CssPixels;+use crate::painting::display_list_resources::NestedDisplayList;+use crate::painting::host::FfiVectorImageRenderRequest;+use crate::render_state::DocumentHost;+use std::sync::Arc;++/// What an SVG image is rendered for, as C++ names it.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiVectorImageKey {+ pub css_width: CssPixels,+ pub css_height: CssPixels,+ pub raster_scale: f32,+ pub color_scheme: u8,+ pub force_dark_enabled: bool,+ pub force_dark_foreground_threshold: i32,+ pub force_dark_background_threshold: i32,+}++/// What an SVG image is rendered for: two renderings for one key show the same.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub(crate) struct VectorImageKey {+ css_width_raw: i32,+ css_height_raw: i32,+ raster_scale_bits: u32,+ color_scheme: u8,+ force_dark_enabled: bool,+ force_dark_foreground_threshold: i32,+ force_dark_background_threshold: i32,+}++impl VectorImageKey {+ pub(crate) fn of_request(request: &FfiVectorImageRenderRequest) -> Self {+ Self::of(&FfiVectorImageKey {+ css_width: request.css_width,+ css_height: request.css_height,+ raster_scale: request.raster_scale,+ color_scheme: request.color_scheme,+ force_dark_enabled: request.force_dark_enabled,+ force_dark_foreground_threshold: request.force_dark_foreground_threshold,+ force_dark_background_threshold: request.force_dark_background_threshold,+ })+ }++ pub(crate) fn of(key: &FfiVectorImageKey) -> Self {+ Self {+ css_width_raw: key.css_width.raw_value(),+ css_height_raw: key.css_height.raw_value(),+ raster_scale_bits: key.raster_scale.to_bits(),+ color_scheme: key.color_scheme,+ force_dark_enabled: key.force_dark_enabled,+ force_dark_foreground_threshold: key.force_dark_foreground_threshold,+ force_dark_background_threshold: key.force_dark_background_threshold,+ }+ }+}++/// How many renderings an SVG image's document keeps: the oldest goes first.+const KEPT_RENDERINGS: usize = 10;++/// The renderings of an SVG image's document, oldest first.+#[derive(Default)]+pub(crate) struct VectorImageCache {+ renderings: Vec<(VectorImageKey, Arc<NestedDisplayList>)>,+}++impl VectorImageCache {+ pub(crate) fn get(&self, key: &VectorImageKey) -> Option<Arc<NestedDisplayList>> {+ self.renderings+ .iter()+ .find_map(|(rendered_key, display_list)| (rendered_key == key).then(|| display_list.clone()))+ }++ fn keep(&mut self, key: VectorImageKey, display_list: Arc<NestedDisplayList>) {+ self.renderings.retain(|(rendered_key, _)| *rendered_key != key);+ if self.renderings.len() >= KEPT_RENDERINGS {+ self.renderings.remove(0);+ }+ self.renderings.push((key, display_list));+ }++ pub(crate) fn clear(&mut self) {+ self.renderings.clear();+ }+}++impl DocumentHost {+ /// The display list this SVG image's document was rendered as for `key`, if it keeps one.+ pub(crate) fn vector_image(&self, key: &VectorImageKey) -> Option<Arc<NestedDisplayList>> {+ self.vector_images().get(key)+ }+}++/// Whether the SVG image document of `host` keeps a rendering for `key`.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_has_vector_image(host: &DocumentHost, key: &FfiVectorImageKey) -> bool {+ host.vector_image(&VectorImageKey::of(key)).is_some()+}++/// Has the SVG image document of `host` keep the recording it took in last as its rendering for `key`.+///+/// # Safety+///+/// `host` must be a live document host, on its document's thread.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_keep_last_recording_as_vector_image(+ host: &DocumentHost,+ read: &crate::render_state::BegunRead,+ key: &FfiVectorImageKey,+) {+ let display_list = crate::painting::ffi::read_arena(host, read, (), |arena, ()| {+ let recording = arena.paint_state().last_recording.clone()?;+ let visual_context_tree = recording.visual_context_tree.clone()?;+ Some(NestedDisplayList::recorded(+ recording.display_list.clone(),+ visual_context_tree,+ recording.root_group_color,+ recording.resources.clone(),+ ))+ });+ host.vector_images().keep(+ VectorImageKey::of(key),+ display_list.unwrap_or_else(NestedDisplayList::empty),+ );+}++/// Has the SVG image document of `host` forget its renderings: what it shows changed.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_forget_vector_images(host: &DocumentHost) {+ host.vector_images().clear();+}diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rsindex 9f798b3571b..87362f78f97 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs@@ -47,7 +47,7 @@ use crate::painting::presentation::Presentation;use crate::painting::record::damage::PaintDamage;use crate::painting::record::inputs::UnframedRecordingInputs;use crate::painting::record::publish::{- PresentedOutput, published_vector_image_display_lists, renders_vector_images, take_in_recording,+ published_vector_image_display_lists, renders_vector_images, take_in_recording,};use crate::painting::record::recorder_state::RecorderState;use crate::painting::record::{PublishedHitTestItems, RecordingInputs, RecordingOutput};@@ -58,7 +58,7 @@ use crate::painting::recording_slot::{use crate::painting::visual_context::VisualContextTree;use crate::stage_thread::{Relay, Riding};use smallvec::SmallVec;-use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering};+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};use std::sync::{Arc, Mutex};mod effects;@@ -709,9 +709,6 @@ pub struct ClockTicks {/// How many times script changed the document's animations, after which the animations a plan sealed before no/// longer stand.animation_changes: AtomicU64,- /// How many recordings of the host's own add to the resource storage the lanes present with: none presents- /// meanwhile.- holds: AtomicU32,/// Where the render clock heard the pointer went, until a tick hovers what is there.pointer: Mutex<hover::PointerState>,/// The border boxes of the elements the lane sampled or its hover restyled in the last frame a tick presented, and@@ -767,7 +764,6 @@ impl ClockTicks {animations_held: AtomicBool::new(true),plan_animates: AtomicBool::new(false),animation_changes: AtomicU64::new(0),- holds: AtomicU32::new(0),pointer: Mutex::new(hover::PointerState::default()),presented_boxes: Mutex::default(),})@@ -922,26 +918,6 @@ impl ClockTicks {self.animation_changes.load(Ordering::Relaxed)}- /// Holds the lanes for a recording of the host's own that adds to the resource storage they present with, waiting- /// for what they present meanwhile: they present nothing until [`Self::release`].- pub(super) fn hold(&self) {- self.holds.fetch_add(1, Ordering::AcqRel);- if cfg!(test) {- return;- }- super::wait_for_render_side();- crate::paint_stage::paint_thread().run(|| ());- }-- pub(super) fn release(&self) {- let previous = self.holds.fetch_sub(1, Ordering::AcqRel);- debug_assert!(previous > 0, "a hold of the lanes is released once");- }-- fn is_held(&self) -> bool {- self.holds.load(Ordering::Acquire) > 0- }-/// The border box of `element` in the last frame a tick presented, if it presented one.pub(super) fn presented_border_box(&self, element: StyleNodeID) -> Option<CssPixelRect> {let presented = self.presented_boxes.lock().expect("presented boxes");@@ -1871,7 +1847,7 @@ impl ClockRecorder {let (pending, _) = record_frame(frozen.frame, &mut self.recorder, viewport, false, inputs);let vector_image_display_lists = match renders_vector_images(&pending) {true => match published_vector_image_display_lists(&pending, &self.recorder) {- Some(display_list_ids) => Some(display_list_ids),+ Some(display_lists) => Some(display_lists),None => {self.leave_frame_to_host();return self;@@ -1883,16 +1859,15 @@ impl ClockRecorder {self.presentation.take_visual_context_tree(visual_contexts);}let output = match vector_image_display_lists {- Some(display_list_ids) => present_with_vector_images(+ Some(display_lists) => present_with_vector_images(&mut self.presentation,pending,&self.recorder,presenting,- &display_list_ids,+ &display_lists,),None => present(&mut self.presentation, pending, &self.recorder, presenting),};- let output = PresentedOutput::of(output);self.presented_hit_test_items = Some(output.published_hit_test_items());self.presented = TickPresented::Frame {output: output.output,@@ -2037,19 +2012,6 @@ pub extern "C" fn document_host_lane_hover_target_for(true}-/// Holds the lanes of `host`'s document for a recording of the host's own that adds to the resource storage they-/// present with, until `document_host_release_clock_lane`: they present nothing meanwhile.-#[unsafe(no_mangle)]-pub extern "C" fn document_host_hold_clock_lane(host: &DocumentHost) {- host.clock_ticks().hold();-}--/// Releases a hold of `document_host_hold_clock_lane`.-#[unsafe(no_mangle)]-pub extern "C" fn document_host_release_clock_lane(host: &DocumentHost) {- host.clock_ticks().release();-}-/// What the lane of the frame `host`'s document presented last does, once the lane of a frame presented by then has/// come together. For a test.#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs b/Libraries/LibWeb/Rust/src/render_state/clock/lane.rsindex 70f7e88e677..8609eb5306c 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs@@ -510,11 +510,6 @@ impl LaneSlot {fn tick(&mut self) {self.take_in_scroll_offsets();- // A recording of the host's own adds to the resource storage the lane presents with: a move waits for it.- if self.ticks.is_held() {- self.show_cursor_where_a_move_waits();- return;- }// A rendering update took in what the lanes did, and the frame it presents shows that, at the time it took it// in: the lane of the frame before it presents nothing on from there, which the update's frame would go back// from, and the moves and animation times since wait for the lane of the update's frame.diff --git a/Libraries/LibWeb/Rust/src/render_state/document_host.rs b/Libraries/LibWeb/Rust/src/render_state/document_host.rsindex 705c14156ac..44bb0635029 100644--- a/Libraries/LibWeb/Rust/src/render_state/document_host.rs+++ b/Libraries/LibWeb/Rust/src/render_state/document_host.rs@@ -86,6 +86,8 @@ pub struct DocumentHost {scroll_state: RefCell<Rc<ScrollStateSnapshot>>,/// The visual context trees the viewport mappings the host hands C++ map through.viewport_mapping_trees: RefCell<crate::painting::viewport_mapping::ViewportMappingTrees>,+ /// The display lists the document was rendered as where it is an SVG image's.+ vector_images: RefCell<crate::painting::vector_image_cache::VectorImageCache>,/// What the host's scopes of a read lend the entries they call.begun_read: BegunRead,/// The writes the host queued that the render state has not applied yet, in the order the host made them.@@ -211,6 +213,7 @@ impl DocumentHost {compositor_animations: RefCell::default(),scroll_state: RefCell::default(),viewport_mapping_trees: RefCell::default(),+ vector_images: RefCell::default(),begun_read: BegunRead::of_host(),changes: ChangeQueue::default(),flown_style: RefCell::default(),@@ -1545,6 +1548,11 @@ impl DocumentHost {self.viewport_mapping_trees.borrow_mut()}+ /// The display lists the document was rendered as where it is an SVG image's.+ pub(crate) fn vector_images(&self) -> RefMut<'_, crate::painting::vector_image_cache::VectorImageCache> {+ self.vector_images.borrow_mut()+ }+/// Takes `device_offsets`, the offsets the render state refreshed, as the document's scroll state.pub(crate) fn refresh_scroll_state(&self, device_offsets: Vec<FloatPoint>) {self.scroll_statediff --git a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp b/Libraries/LibWeb/SVG/SVGDecodedImageData.cppindex 6f5ab6e3f5c..1374bdc7054 100644--- a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp+++ b/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp@@ -7,7 +7,6 @@#include <AK/NeverDestroyed.h>#include <AK/ScopeGuard.h>#include <LibAudio/RecordStream.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibGC/Heap.h>#include <LibGC/WeakHashMap.h>#include <LibGfx/Bitmap.h>@@ -228,60 +227,13 @@ size_t SVGDecodedImageData::external_memory_size() constreturn size;}-static void copy_referenced_resources_to(- Compositing::DisplayListResourceStorage& destination,- Compositing::DisplayListResourceStorage const& source,- Compositing::DisplayListResourceSet const& referenced_resources)-{- Compositing::DisplayListResourceSet empty_resource_set;- destination.apply_transaction(source.create_transaction(empty_resource_set, referenced_resources));-}--void SVGDecodedImageData::prune_cached_display_list_resources() const-{- m_page_client->prune_cached_display_list_resources();-}--void SVGDecodedImageData::append_cached_display_list_resources(Compositing::DisplayListResourceSet& retained_resources) const-{- for (auto const& cached_display_list : m_cached_display_lists)- retained_resources.include(cached_display_list.value.referenced_resources);-}--void SVGDecodedImageData::append_paint_command_cache_source_resources(Compositing::DisplayListResourceSet& retained_resources) const-{- if (!m_document->has_committed_viewport_box())- return;- m_document->paint_state().append_paint_command_cache_source_resources(retained_resources);-}--Optional<Compositing::DisplayListResource> SVGDecodedImageData::record_display_list(Gfx::IntSize size, CSS::PreferredColorScheme color_scheme, Compositing::DisplayListResourceStorage& destination_resource_storage) const-{- return record_display_list_at_scale(size.to_type<CSSPixels>(), 1, color_scheme, {}, destination_resource_storage);-}--Optional<Compositing::DisplayListResource> SVGDecodedImageData::record_display_list_at_scale(CSSPixelSize css_size, float raster_scale, CSS::PreferredColorScheme color_scheme, HTML::PaintConfig const& paint_config, Compositing::DisplayListResourceStorage& destination_resource_storage) const+Layout::RustFFI::DocumentHost const* SVGDecodedImageData::render_at_scale(Painting::VectorImageKey const& key) const{ScopedSVGImageDocument scoped_document { *m_document, ScopedSVGImageDocument::FrameRequests::RouteToCurrentImage };auto& navigable = *m_document->navigable();- auto& resource_storage = navigable.display_list_resource_storage();-- RenderKey const key { css_size, raster_scale, color_scheme, paint_config };- if (auto it = m_cached_display_lists.find(key); it != m_cached_display_lists.end()) {- copy_referenced_resources_to(destination_resource_storage, resource_storage, it->value.referenced_resources);- return Compositing::DisplayListResource { *it->value.display_list };- }-- // FIXME: Evict least used entries.- if (m_cached_display_lists.size() > 10) {- m_cached_display_lists.remove(m_cached_display_lists.begin());- prune_cached_display_list_resources();- }-- m_page_client->begin_recording_display_list();- ScopeGuard finish_recording_display_list = [&] {- m_page_client->end_recording_display_list();- };+ auto ffi_key = Painting::vector_image_key_to_ffi(key);+ if (auto const* host = m_document->layout_node_arena_if_created() ? m_document->layout_node_arena().host() : nullptr; host && Layout::RustFFI::render_state_has_vector_image(host, &ffi_key))+ return host;m_is_recording_display_list = true;ScopeGuard clear_recording_flag = [&] {@@ -294,40 +246,32 @@ Optional<Compositing::DisplayListResource> SVGDecodedImageData::record_display_l};auto previous_device_pixels_per_css_pixel = m_page_client->device_pixels_per_css_pixel();- m_page_client->set_device_pixels_per_css_pixel(raster_scale);+ m_page_client->set_device_pixels_per_css_pixel(key.raster_scale);ScopeGuard restore_device_pixels_per_css_pixel = [&] {m_page_client->set_device_pixels_per_css_pixel(previous_device_pixels_per_css_pixel);};// `prefers-color-scheme` inside the image answers with the embedding element's used scheme, so// the media query has to be evaluated again whenever that differs from the last recording.- if (m_color_scheme != color_scheme) {- m_color_scheme = color_scheme;+ if (m_color_scheme != key.color_scheme) {+ m_color_scheme = key.color_scheme;m_cached_rendered_frames.clear();m_natural_size.clear();- m_document->set_svg_image_color_scheme(color_scheme);+ m_document->set_svg_image_color_scheme(key.color_scheme);m_document->style_scope().invalidate_style_cache();m_document->record_style_environment_change(DOM::StyleEnvironmentChange::ColorScheme | DOM::StyleEnvironmentChange::MediaFeatures);}- navigable.set_viewport_size(css_size);+ navigable.set_viewport_size(key.css_size);Layout::ForcedReadScope read { *m_document };m_document->update_layout(DOM::UpdateLayoutReason::SVGDecodedImageDataRender);- auto display_list = m_document->record_display_list(read, paint_config, resource_storage, Painting::PaintCommandCacheMode::ReadWrite);- if (!display_list)- return {};+ if (!m_document->record_display_list(read, key.paint_config, Painting::PaintCommandCacheMode::ReadWrite))+ return nullptr;VERIFY(m_document->has_committed_viewport_box());- auto& document_paint_state = m_document->paint_state();- VERIFY(document_paint_state.display_list_used_as_paint_command_cache_source() == display_list.ptr());- auto nestable_display_list = Painting::nestable_display_list_of_last_recording(read, *m_document, display_list.release_nonnull());- auto referenced_resources = document_paint_state.paint_command_cache_source_referenced_resources();- referenced_resources.include(resource_storage.collect_resources_referenced_by_visual_context_tree(*nestable_display_list));- copy_referenced_resources_to(destination_resource_storage, resource_storage, referenced_resources);- auto display_list_resource = Compositing::DisplayListResource { nestable_display_list };- m_cached_display_lists.set(key, CachedDisplayList { move(nestable_display_list), move(referenced_resources) });- prune_cached_display_list_resources();- return display_list_resource;+ auto* host = m_document->layout_node_arena().host();+ Layout::RustFFI::render_state_keep_last_recording_as_vector_image(host, read, &ffi_key);+ return host;}// An SVG image inside another SVG image has an SVG page as its host. Walk up to the page that shows the outermost one.@@ -349,12 +293,21 @@ RefPtr<Gfx::Bitmap> SVGDecodedImageData::render_frame(Gfx::IntSize size) constif (bitmap.is_error())return nullptr;- Compositing::DisplayListResourceStorage resource_storage;- auto display_list = record_display_list(size, m_color_scheme, resource_storage);- if (!display_list.has_value())+ Painting::VectorImageKey key { size.to_type<CSSPixels>(), 1, m_color_scheme, {} };+ auto const* host = render_at_scale(key);+ if (!host)return nullptr;- if (!compositor_host->rasterize_display_list(*display_list, resource_storage, bitmap.value()))+ Painting::ImagePaint paint { Painting::ImagePaint::VectorImage { .host = host, .key = key, .list_size = size } };+ Painting::ImagePaintRequest request {+ .document = *m_document,+ .dest_rect = { {}, size.to_type<float>() },+ .image_rendering = CSS::ImageRendering::Auto,+ .color_scheme = m_color_scheme,+ .gradient_stop_color_resolution_style = {},+ .accumulated_scale = { 1, 1 },+ };+ if (!Painting::rasterize_image_paint(*compositor_host, paint, request, 1, bitmap.value()))return nullptr;return bitmap.release_value();}@@ -454,39 +407,6 @@ void SVGDecodedImageData::SVGPageClient::register_svg_image_data(SVGDecodedImagem_svg_image_data.set(svg_image_data);}-void SVGDecodedImageData::SVGPageClient::prune_cached_display_list_resources() const-{- if (m_display_list_recording_count > 0) {- m_has_pending_display_list_resource_prune = true;- return;- }-- prune_cached_display_list_resources_now();-}--void SVGDecodedImageData::SVGPageClient::prune_cached_display_list_resources_now() const-{- Compositing::DisplayListResourceSet retained_resources;- for (auto& svg_image_data : m_svg_image_data) {- svg_image_data.append_cached_display_list_resources(retained_resources);- svg_image_data.append_paint_command_cache_source_resources(retained_resources);- }-- m_svg_page->local_traversable()->display_list_resource_storage().retain_only(retained_resources);-}--void SVGDecodedImageData::SVGPageClient::end_recording_display_list()-{- VERIFY(m_display_list_recording_count > 0);- --m_display_list_recording_count;-- if (m_display_list_recording_count > 0 || !m_has_pending_display_list_resource_prune)- return;-- m_has_pending_display_list_resource_prune = false;- prune_cached_display_list_resources_now();-}-HTML::Window& SVGDecodedImageData::SVGPageClient::window() const{auto window = m_svg_page->local_traversable()->active_window();@@ -578,8 +498,8 @@ void SVGDecodedImageData::invalidate_cached_rendering()m_vector_content_identity = next_vector_content_identity();m_natural_size.clear();m_cached_rendered_frames.clear();- m_cached_display_lists.clear();- prune_cached_display_list_resources();+ if (auto* arena = m_document->layout_node_arena_if_created())+ Layout::RustFFI::render_state_forget_vector_images(arena->host());}bool SVGDecodedImageData::has_active_view_box() const@@ -610,10 +530,10 @@ Optional<Painting::ImagePaint> SVGDecodedImageData::image_paint(Painting::ImageP// out directly at the raster size and its recorded coordinates land on the raster's pixel// grid exactly. Without one, the layout viewport determines the content's proportions, so// layout happens at the local size and only the raster resolution follows the scale.- Optional<Compositing::DisplayListResource> display_list;+ Painting::VectorImageKey key;Gfx::IntSize list_size;if (m_root_element->active_view_box().has_value()) {- display_list = record_display_list(raster_size, color_scheme, request.resource_storage);+ key = { raster_size.to_type<CSSPixels>(), 1, color_scheme, {} };list_size = raster_size;} else {auto css_size = CSSPixelSize {@@ -625,16 +545,17 @@ Optional<Painting::ImagePaint> SVGDecodedImageData::image_paint(Painting::ImagePraster_scale = 1;auto maximum_raster_scale = static_cast<float>(maximum_raster_dimension) / max(css_size.width(), css_size.height()).to_float();raster_scale = min(raster_scale, maximum_raster_scale);- display_list = record_display_list_at_scale(css_size, raster_scale, color_scheme, {}, request.resource_storage);+ key = { css_size, raster_scale, color_scheme, {} };list_size = {max(1, static_cast<int>(lroundf(css_size.width().to_float() * raster_scale))),max(1, static_cast<int>(lroundf(css_size.height().to_float() * raster_scale))),};}- if (!display_list.has_value())+ auto const* host = render_at_scale(key);+ if (!host)return {};- return Painting::ImagePaint { Painting::ImagePaint::NestedDisplayList { .resource = *display_list, .list_size = list_size } };+ return Painting::ImagePaint { Painting::ImagePaint::VectorImage { .host = host, .key = key, .list_size = list_size } };}}diff --git a/Libraries/LibWeb/SVG/SVGDecodedImageData.h b/Libraries/LibWeb/SVG/SVGDecodedImageData.hindex 7b8fc398a2a..993137927c8 100644--- a/Libraries/LibWeb/SVG/SVGDecodedImageData.h+++ b/Libraries/LibWeb/SVG/SVGDecodedImageData.h@@ -7,8 +7,6 @@#pragma once#include <AK/Optional.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCore/Promise.h>#include <LibGC/Heap.h>#include <LibGC/WeakHashSet.h>@@ -17,6 +15,7 @@#include <LibWeb/HTML/DecodedImageData.h>#include <LibWeb/HTML/PaintConfig.h>#include <LibWeb/Page/Page.h>+#include <LibWeb/Painting/ImagePaint.h>#include <LibWebCommon/Page/PageId.h>#include <LibWebCommon/Page/QueuedInputEvent.h>@@ -40,9 +39,10 @@ public:virtual Optional<CSSPixelFraction> intrinsic_aspect_ratio() const override;u64 vector_content_identity() const { return m_vector_content_identity; }- virtual Optional<Compositing::DisplayListResource> record_display_list(Gfx::IntSize, CSS::PreferredColorScheme, Compositing::DisplayListResourceStorage&) const override;- // Lays the inner document out at the CSS size and records at css × raster_scale resolution.- Optional<Compositing::DisplayListResource> record_display_list_at_scale(CSSPixelSize css_size, float raster_scale, CSS::PreferredColorScheme, HTML::PaintConfig const&, Compositing::DisplayListResourceStorage&) const;+ // Has the image's document keep a rendering of the image for `key`, laid out at the key's CSS size and recorded at+ // css × raster_scale resolution, and answers the document's host, which keeps it, or none where the image has+ // nothing to show.+ Layout::RustFFI::DocumentHost const* render_at_scale(Painting::VectorImageKey const&) const;// FIXME: Support SVG animations. :^)DOM::Document const& svg_document() const { return *m_document; }@@ -65,9 +65,6 @@ private:CSS::SizeWithAspectRatio const& natural_size() const;Compositor::CompositorHost* host_compositor() const;RefPtr<Gfx::Bitmap> render_frame(Gfx::IntSize) const;- void prune_cached_display_list_resources() const;- void append_cached_display_list_resources(Compositing::DisplayListResourceSet&) const;- void append_paint_command_cache_source_resources(Compositing::DisplayListResourceSet&) const;void did_request_frame();void invalidate_cached_rendering();static u64 next_vector_content_identity();@@ -76,33 +73,6 @@ private:mutable CSS::PreferredColorScheme m_color_scheme { CSS::PreferredColorScheme::Auto };- struct CachedDisplayList {- NonnullRefPtr<Compositing::DisplayList> display_list;- // Precomputed by collect_referenced_resources(); the display list is immutable, so this never changes.- Compositing::DisplayListResourceSet referenced_resources;- };- // An SVG used as an image resolves `prefers-color-scheme` from the used `color-scheme` of the- // element referencing it, so one image can render two ways on one page and the recording is- // keyed by both.- struct RenderKey {- CSSPixelSize css_size;- float raster_scale { 1 };- CSS::PreferredColorScheme color_scheme;- HTML::PaintConfig paint_config;- bool operator==(RenderKey const&) const = default;- };- struct RenderKeyTraits : public Traits<RenderKey> {- static unsigned hash(RenderKey const& key)- {- auto size_hash = pair_int_hash(key.css_size.width().raw_value(), key.css_size.height().raw_value());- auto hash = pair_int_hash(pair_int_hash(size_hash, bit_cast<u32>(key.raster_scale)), to_underlying(key.color_scheme));- if (!key.paint_config.force_dark_enabled)- return hash;- return pair_int_hash(hash, pair_int_hash(key.paint_config.force_dark_foreground_threshold, key.paint_config.force_dark_background_threshold));- }- static bool equals(RenderKey const& a, RenderKey const& b) { return a == b; }- };- mutable HashMap<RenderKey, CachedDisplayList, RenderKeyTraits> m_cached_display_lists;mutable Optional<CSS::SizeWithAspectRatio> m_natural_size;GC::Ref<Page> m_page;@@ -162,10 +132,7 @@ public:virtual NonnullRefPtr<Core::Promise<NonnullRefPtr<Audio::RecordStream>>> create_audio_record_stream(StringView device_id, Function<void(ReadonlyBytes, Audio::SampleSpecification const&)>) override;void register_svg_image_data(SVGDecodedImageData&);- void prune_cached_display_list_resources() const;HTML::Window& window() const;- void begin_recording_display_list() { ++m_display_list_recording_count; }- void end_recording_display_list();GC::Ptr<SVGDecodedImageData> current_svg_image_data() const { return m_current_svg_image_data.ptr(); }void set_current_svg_image_data(GC::Ptr<SVGDecodedImageData>);@@ -185,14 +152,11 @@ private:virtual bool is_svg_page_client() const override { return true; }virtual void visit_edges(Visitor&) override;- void prune_cached_display_list_resources_now() const;double m_device_pixels_per_css_pixel { 1.0 };GC::WeakHashSet<SVGDecodedImageData> m_svg_image_data;GC::Weak<SVGDecodedImageData> m_current_svg_image_data;size_t m_frame_request_suppression_count { 0 };- size_t m_display_list_recording_count { 0 };- mutable bool m_has_pending_display_list_resource_prune { false };};class WEB_API ScopedSVGImageDocument {diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex db982cec6e2..bfc375d37ce 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -1221,7 +1221,7 @@ void CompositorState::apply_resource_changes(Web::CompositorContextId context_idbool 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())+ 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 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;diff --git a/Services/Compositor/CompositorWebContentClient.ipc b/Services/Compositor/CompositorWebContentClient.ipcindex fa4759bbe72..17ec14b7a94 100644--- a/Services/Compositor/CompositorWebContentClient.ipc+++ b/Services/Compositor/CompositorWebContentClient.ipc@@ -15,6 +15,8 @@ endpoint CompositorWebContentClient// as of the frame's time.[RustSender] animated_content_moved_under_pointer(Web::CompositorContextId context_id, i64 frame_time_nanoseconds) =|[RustSender] overlay_scrollbar_visibilities_changed(Vector<Web::OverlayScrollbarVisibility> visibilities) =|+ // The compositor rasterized the display list that the rasterize_display_list() naming `token` handed it, or failed to.+ [RustSender] did_rasterize_display_list(u64 token, bool success) =|did_complete_screenshot(Compositing::ScreenshotRequestId request_id) =|did_fail_screenshot(Compositing::ScreenshotRequestId request_id) =|paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId> context_ids) =|diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex fef20f4ebda..050879c6121 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -41,12 +41,12 @@ endpoint CompositorWebContentServerdestroy_context(Web::CompositorContextId context_id) =|// 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::DisplayListProperties display_list_properties, Optional<Compositing::AsyncScrollingMetadata> async_scrolling_metadata, ByteBuffer visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state) =|+ // update_display_list_resources, and the resource transaction that comes with it holds none. WebContent's Rust sends+ // the display lists, the trees and the scroll state.+ [RustReceiver, RustSender] update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayListProperties display_list_properties, Optional<Compositing::AsyncScrollingMetadata> async_scrolling_metadata, ByteBuffer visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state) =|update_display_list_resources(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction resource_transaction) =|- [RustReceiver] update_visual_context_tree(Web::CompositorContextId context_id, ByteBuffer 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) =|+ [RustReceiver, RustSender] update_visual_context_tree(Web::CompositorContextId context_id, ByteBuffer visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state) =|+ [RustReceiver, RustSender] 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.reserve_canvas_ids() => (Compositing::CanvasId first_canvas_id, u64 count)@@ -65,9 +65,10 @@ endpoint CompositorWebContentServerget_placeholder_canvas_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect) => (Gfx::ShareableBitmap pixels, bool origin_clean)// 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.+ // a token that the next rasterize_display_list names, and with the display lists it nests, which come with it. The+ // compositor answers with did_rasterize_display_list().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::DisplayListProperties display_list_properties, ByteBuffer visual_context_tree, Compositing::DisplayListResourceTransaction nested_display_lists) => (bool success)+ [RustReceiver, RustSender] rasterize_display_list(u64 token, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayListProperties display_list_properties, ByteBuffer visual_context_tree, Compositing::DisplayListResourceTransaction nested_display_lists) =|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) =|@@ -85,7 +86,7 @@ endpoint CompositorWebContentServer[RustReceiver] take_wheel_event_from_main_thread(Web::CompositorContextId context_id, Web::MouseEvent event, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelEventRouting routing) => (Compositing::WheelEventAnswer answer)[RustReceiver] wheel_event_let_through(Web::CompositorContextId context_id, Compositing::WheelStepLetThrough step, Compositing::AsyncScrollOperationTracking operation_tracking) => (Compositing::WheelEventAnswer answer)[RustReceiver] wheel_event_canceled(Web::CompositorContextId context_id, u64 wheel_gesture_id) =|- [RustReceiver] apply_scroll_requests(Web::CompositorContextId context_id, Vector<Compositing::ScrollRequest> scroll_requests) =|+ [RustReceiver, RustSender] apply_scroll_requests(Web::CompositorContextId context_id, Vector<Compositing::ScrollRequest> scroll_requests) =|[RustReceiver] scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller) => (String scroll_state)// Returns once the compositor has handled every message WebContent sent before it.synchronize_for_testing() => ()@@ -98,7 +99,7 @@ endpoint CompositorWebContentServerviewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress) =|request_rendering_opportunity(Web::CompositorContextId context_id, double maximum_frames_per_second) =|hurry_rendering_opportunity(Web::CompositorContextId context_id) =|- present_frame(Web::CompositorContextId context_id, Gfx::IntRect viewport_rect) =|+ [RustSender] present_frame(Web::CompositorContextId context_id, Gfx::IntRect viewport_rect) =|request_screenshot(Web::CompositorContextId context_id, Compositing::ScreenshotRequestId request_id, Gfx::ShareableBitmap target_bitmap) =|// Has the processes that own the context's descendants in other processes paint them, and answers with// remote_descendants_prepared_for_screenshot() once the compositor has their frames.diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex 31fb3ccf26a..be48743a4d8 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -15,12 +15,13 @@ use libcompositing_rust::ipc_types::compositor_presentation_client::messages::Diuse libcompositing_rust::ipc_types::compositor_presentation_server::messages::{HandleAndDispatchKeyEvent, HandleAndDispatchMouseEvent, HandleAndDispatchPinchEvent,};+use libcompositing_rust::ipc_types::compositor_web_content_client::messages::DidRasterizeDisplayList;use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{ApplyScrollRequests, BeginInputTraceForTesting, BeginInputTraceForTestingResponse,ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, InvalidateKeyboardScrollState,InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState, RasterizeDisplayList,- RasterizeDisplayListResponse, RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse,- ScrollStateForTesting, ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,+ RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse, ScrollStateForTesting,+ ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,TakePendingAsyncScrollUpdates, TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread,TakeWheelEventFromMainThreadResponse, UpdateDisplayList, UpdateScrollState, UpdateVisualContextTree,WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,@@ -209,6 +210,89 @@ impl MessagesFromWebContent<'_> {}}+impl MessagesFromWebContent<'_> {+ /// Rasterizes the display list `message` hands over into the bitmap staged for it, and answers whether it did.+ fn rasterize_staged_display_list(&mut self, message: RasterizeDisplayList) -> Result<bool, 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(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 tree = match decode_visual_context_tree(&message.visual_context_tree) {+ Ok(tree) => tree,+ Err(misbehavior) => {+ raster.discard_staged_rasterization(client, token);+ return Err(misbehavior);+ }+ };+ let properties = message.display_list_properties;+ 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(success)+ }+}+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();@@ -318,87 +402,13 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {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 tree = match decode_visual_context_tree(&message.visual_context_tree) {- Ok(tree) => tree,- Err(misbehavior) => {- raster.discard_staged_rasterization(client, token);- return Err(misbehavior);- }- };- let properties = message.display_list_properties;- 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 rasterize_display_list(&mut self, message: RasterizeDisplayList) -> Result<(), Misbehavior> {+ let token = message.token;+ let success = self.rasterize_staged_display_list(message)?;+ self.core+ .host+ .post_to_web_content(self.client_id, DidRasterizeDisplayList { token, success });+ Ok(())}fn update_scroll_state(&mut self, message: UpdateScrollState) -> Result<(), Misbehavior> {diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 6435b6a9e07..30015a40fbe 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -506,7 +506,7 @@ void ConnectionFromClient::connect_to_compositor_process(IPC::TransportHandle ha};m_compositor_connection->attach_render_clock(move(render_clock_handle));- m_compositor_connection->hand_frame_sink_to_paint_thread();+ m_compositor_connection->hand_poster_to_paint_thread();}void ConnectionFromClient::compositor_process_reconnected()