Truly independent web browser
Everywhere: Keep the scroll state snapshot on the Rust side
Aliaksandr Kalenikad29cc8aefd0
diff --git a/Libraries/LibCompositing/CMakeLists.txt b/Libraries/LibCompositing/CMakeLists.txtindex d944320150f..8576f293dcc 100644--- a/Libraries/LibCompositing/CMakeLists.txt+++ b/Libraries/LibCompositing/CMakeLists.txt@@ -5,14 +5,12 @@ set(SOURCESDisplayList/Canvas2DCommandStream.cppDisplayList/Canvas2DTape.cppDisplayList/DisplayList.cpp- DisplayList/DisplayListDamage.cppDisplayList/DisplayListResourceStorage.cppDisplayList/DisplayListResourceTransaction.cppDisplayList/RustFFIAssertions.cppDisplayList/VisualContextTreeTestBuilder.cppFontServiceClient.cppScrolling/RecordedDisplayListScrolling.cpp- Scrolling/ScrollState.cppScrolling/SmoothScrollAnimation.cppUIOverlays.cppVideo/VideoFrameHold.cpp@@ -106,7 +104,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/AccumulatedVisualContext.cpp DisplayList/DisplayList.cpp DisplayList/DisplayListDamage.cpp DisplayList/DisplayListResourceStorage.cpp DisplayList/VisualContextTreeTestBuilder.cpp Scrolling/RecordedDisplayListScrolling.cpp Scrolling/SmoothScrollAnimation.cpp)+ foreach(bridge IN ITEMS DisplayList/AccumulatedVisualContext.cpp DisplayList/DisplayList.cpp DisplayList/DisplayListResourceStorage.cpp DisplayList/VisualContextTreeTestBuilder.cpp Scrolling/RecordedDisplayListScrolling.cpp Scrolling/SmoothScrollAnimation.cpp)set_property(SOURCE ${bridge} APPEND PROPERTY OBJECT_DEPENDS ${_libcompositing_rust_lib})endforeach()endif()diff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cppindex 1b78b5977f8..84793ceb3ad 100644--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp@@ -7,7 +7,6 @@#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/RustFFI.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibIPC/Decoder.h>#include <LibIPC/Encoder.h>@@ -127,16 +126,9 @@ Optional<Gfx::Color> AccumulatedVisualContextTree::sampled_background_color(Effereturn color;}-bool AccumulatedVisualContextTree::translations_snap_to_device_pixels(SpatialNodeIndex spatial_node_index, ScrollStateSnapshot const& scroll_state) const+bool AccumulatedVisualContextTree::translations_snap_to_device_pixels(SpatialNodeIndex spatial_node_index) const{- return Compositing::RustFFI::world_transforms_translations_snap_to_device_pixels(scroll_state.world_transforms(*this), spatial_node_index);-}--Gfx::FloatMatrix4x4 AccumulatedVisualContextTree::accumulated_matrix(SpatialNodeIndex index, ScrollStateSnapshot const& scroll_state, IncludeVisualViewportTransform include_visual_viewport_transform) const-{- Gfx::FloatMatrix4x4 matrix;- Compositing::RustFFI::world_transforms_accumulated_matrix(scroll_state.world_transforms(*this), index, include_visual_viewport_transform == IncludeVisualViewportTransform::Yes, &matrix);- return matrix;+ return Compositing::RustFFI::visual_context_tree_translations_snap_to_device_pixels(m_rust_tree, spatial_node_index);}void AccumulatedVisualContextTree::for_each_effects_filter_image_frame_id(Function<void(u64)> const& visit) constdiff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.hindex 0709679a35d..abefe3febe4 100644--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h@@ -12,19 +12,16 @@#include <AK/Function.h>#include <AK/RefCounted.h>#include <AK/RefPtr.h>+#include <LibCompositing/DisplayList/ContextRef.h>#include <LibCompositing/Export.h>#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibGfx/Forward.h>-#include <LibGfx/Matrix4x4.h>#include <LibGfx/Point.h>#include <LibGfx/Rect.h>#include <LibIPC/Forward.h>namespace Compositing {-class ScrollStateSnapshot;-// What a tree reports about the animations it carries, for test introspection.struct VisualAnimationSummary {size_t count { 0 };@@ -35,11 +32,6 @@ struct VisualAnimationSummary {class COMPOSITING_API AccumulatedVisualContextTree {public:- enum class IncludeVisualViewportTransform {- No,- Yes,- };-static AccumulatedVisualContextTree adopt_rust_handle(void const* retained_tree);static ErrorOr<AccumulatedVisualContextTree> from_serialized_bytes(ReadonlyBytes);@@ -65,10 +57,7 @@ public:Optional<Gfx::Color> sampled_background_color(EffectNodeIndex) const;// Whether the node's scroll translations and the origins drawn in its space round to whole device pixels: no// transform but identities lies above it.- bool translations_snap_to_device_pixels(SpatialNodeIndex, ScrollStateSnapshot const&) const;-- // Sum of the snapshot entries along the scroll-parent chain from the given scroll-like node.- Gfx::FloatMatrix4x4 accumulated_matrix(SpatialNodeIndex, ScrollStateSnapshot const&, IncludeVisualViewportTransform) const;+ bool translations_snap_to_device_pixels(SpatialNodeIndex) const;void for_each_effects_filter_image_frame_id(Function<void(u64)> const&) const;diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.cpp b/Libraries/LibCompositing/DisplayList/DisplayList.cppindex 81e53ce52a8..5fa04a7efad 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.cpp+++ b/Libraries/LibCompositing/DisplayList/DisplayList.cpp@@ -95,17 +95,15 @@ bool DisplayList::requires_direct_replay_without_nested_lists(AccumulatedVisualCreturn RustFFI::display_list_storage_requires_direct_replay_without_nested_lists(m_storage, visual_context_tree.rust_handle());}-void DisplayList::replay(AccumulatedVisualContextTree const& visual_context_tree, ScrollStateSnapshot const& scroll_state, RustFFI::FfiDisplayListReplayCallbacks const& callbacks) const+void DisplayList::replay(AccumulatedVisualContextTree const& visual_context_tree, RustFFI::FfiDisplayListReplayCallbacks const& callbacks) const{VERIFY(m_compatible_visual_context_tree_structural_epoch == visual_context_tree.structural_epoch());- auto scroll_offsets = scroll_state.device_offsets();- RustFFI::display_list_replay(visual_context_tree.rust_handle(), m_storage, m_root_group_color, scroll_offsets.data(), scroll_offsets.size(), &callbacks);+ RustFFI::display_list_replay(visual_context_tree.rust_handle(), m_storage, m_root_group_color, &callbacks);}-void DisplayList::replay_records(ReadonlyBytes records, ScrollStateSnapshot const& scroll_state, RustFFI::FfiDisplayListReplayCallbacks const& callbacks)+void DisplayList::replay_records(ReadonlyBytes records, RustFFI::FfiDisplayListReplayCallbacks const& callbacks){- auto scroll_offsets = scroll_state.device_offsets();- RustFFI::display_list_replay_records(records.data(), records.size(), scroll_offsets.data(), scroll_offsets.size(), &callbacks);+ RustFFI::display_list_replay_records(records.data(), records.size(), &callbacks);}u64 DisplayList::tape_size() constdiff --git a/Libraries/LibCompositing/DisplayList/DisplayList.h b/Libraries/LibCompositing/DisplayList/DisplayList.hindex c0e8618aed7..b4a3ec7a9f0 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.h+++ b/Libraries/LibCompositing/DisplayList/DisplayList.h@@ -17,7 +17,6 @@#include <LibCompositing/DisplayList/DisplayListCommand.h>#include <LibCompositing/Export.h>#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>#include <LibCore/AnonymousBuffer.h>#include <LibGfx/Color.h>@@ -110,10 +109,11 @@ public:// display lists it nests.bool requires_direct_replay_without_nested_lists(AccumulatedVisualContextTree const&) const;- // Replays the list through a player's callbacks, against the visual context tree it was made for.- void replay(AccumulatedVisualContextTree const&, ScrollStateSnapshot const&, RustFFI::FfiDisplayListReplayCallbacks const&) const;- // Replays a stream of records that a command of a list being replayed nests.- static void replay_records(ReadonlyBytes records, ScrollStateSnapshot const&, RustFFI::FfiDisplayListReplayCallbacks const&);+ // Replays the list through a player's callbacks, against the visual context tree it was made for, with nothing+ // scrolled.+ void replay(AccumulatedVisualContextTree const&, RustFFI::FfiDisplayListReplayCallbacks const&) const;+ // Replays a stream of records that a command of a list being replayed nests, with nothing scrolled.+ static void replay_records(ReadonlyBytes records, RustFFI::FfiDisplayListReplayCallbacks const&);private:// Takes over the storage of a tape that came from another process and passed its checks.diff --git a/Libraries/LibCompositing/DisplayList/DisplayListDamage.cpp b/Libraries/LibCompositing/DisplayList/DisplayListDamage.cppdeleted file mode 100644index 9e602295b91..00000000000--- a/Libraries/LibCompositing/DisplayList/DisplayListDamage.cpp+++ /dev/null@@ -1,42 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListDamage.h>-#include <LibCompositing/RustFFI.h>-#include <LibCompositing/Scrolling/ScrollState.h>--namespace Compositing {--Optional<Gfx::IntRect> compute_display_list_damage(- DisplayList const& old_display_list,- AccumulatedVisualContextTree const& old_visual_context_tree,- ScrollStateSnapshot const& old_scroll_state,- DisplayList const& new_display_list,- AccumulatedVisualContextTree const& new_visual_context_tree,- ScrollStateSnapshot const& new_scroll_state,- Gfx::IntRect viewport_rect,- LiveContentChanges live_content_changes)-{- auto old_scroll_offsets = old_scroll_state.device_offsets();- auto new_scroll_offsets = new_scroll_state.device_offsets();- Gfx::IntRect damage_rect;- bool damage_is_bounded = Compositing::RustFFI::display_list_compute_damage(- old_display_list.rust_handle(), old_visual_context_tree.rust_handle(), old_scroll_offsets.data(), old_scroll_offsets.size(),- new_display_list.rust_handle(), new_visual_context_tree.rust_handle(), new_scroll_offsets.data(), new_scroll_offsets.size(),- viewport_rect,- live_content_changes.canvases.data(), live_content_changes.canvases.size(),- live_content_changes.video_sinks.data(), live_content_changes.video_sinks.size(),- live_content_changes.image_frames.data(), live_content_changes.image_frames.size(),- live_content_changes.forced_damage_rect,- &damage_rect);- if (!damage_is_bounded)- return {};- return damage_rect;-}--}diff --git a/Libraries/LibCompositing/DisplayList/DisplayListDamage.h b/Libraries/LibCompositing/DisplayList/DisplayListDamage.hdeleted file mode 100644index d34a34354e3..00000000000--- a/Libraries/LibCompositing/DisplayList/DisplayListDamage.h+++ /dev/null@@ -1,42 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Span.h>-#include <LibCompositing/DisplayList/DisplayListResourceIds.h>-#include <LibCompositing/Export.h>-#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>-#include <LibGfx/Rect.h>--namespace Compositing {--class AccumulatedVisualContextTree;-class ScrollStateSnapshot;--// The canvases, video sinks and image frames whose pixels changed since the old list was rasterized. The lists-// draw them with commands that stay the same, so comparing the lists cannot see the change.-struct LiveContentChanges {- ReadonlySpan<CanvasId> canvases;- ReadonlySpan<VideoSinkResourceId> video_sinks;- ReadonlySpan<ImageFrameResourceId> image_frames;- // What the compositor repaints whatever the lists hold, such as a blinking caret.- Gfx::IntRect forced_damage_rect;-};--COMPOSITING_API Optional<Gfx::IntRect> compute_display_list_damage(- DisplayList const& old_display_list,- AccumulatedVisualContextTree const& old_visual_context_tree,- ScrollStateSnapshot const& old_scroll_state,- DisplayList const& new_display_list,- AccumulatedVisualContextTree const& new_visual_context_tree,- ScrollStateSnapshot const& new_scroll_state,- Gfx::IntRect viewport_rect,- LiveContentChanges);--}diff --git a/Libraries/LibCompositing/Forward.h b/Libraries/LibCompositing/Forward.hindex 7232965d7bf..6e5e4b62ae1 100644--- a/Libraries/LibCompositing/Forward.h+++ b/Libraries/LibCompositing/Forward.h@@ -27,6 +27,5 @@ struct DisplayListGlyph;class DisplayListResourceStorage;struct DisplayListResourceSet;enum class CompositorScrollNodeKind : u8;-class ScrollStateSnapshot;}diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rsindex c14f86e3bf4..b627ae00c1c 100644--- a/Libraries/LibCompositing/Rust/src/ffi.rs+++ b/Libraries/LibCompositing/Rust/src/ffi.rs@@ -48,103 +48,21 @@ pub unsafe extern "C" fn ladybird_web_force_dark_should_filter_image(crate::force_dark::should_filter(&features)}-/// # Safety+/// Replays the list `storage` holds against `tree`, with the scroll containers at `scroll_offsets`.///-/// Both storages must be live storage handles, both trees live retained tree handles, and the-/// offset and id pointers must address the stated number of items for the call. Writes the damage-/// rect through `out_damage_rect` and returns whether the damage is bounded; unbounded damage means-/// the whole viewport must repaint.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn display_list_compute_damage(- old_storage: *const c_void,- old_tree: *const c_void,- old_scroll_offsets: *const libgfx_rust::FloatPoint,- old_scroll_offsets_len: usize,- new_storage: *const c_void,- new_tree: *const c_void,- new_scroll_offsets: *const libgfx_rust::FloatPoint,- new_scroll_offsets_len: usize,- viewport_rect: libgfx_rust::IntRect,- canvases_with_new_content: *const crate::display_list::commands::CanvasId,- canvases_with_new_content_len: usize,- video_sinks_with_new_frames: *const crate::display_list::commands::VideoSinkResourceId,- video_sinks_with_new_frames_len: usize,- image_frames_with_new_pixels: *const crate::display_list::commands::ImageFrameResourceId,- image_frames_with_new_pixels_len: usize,- forced_damage_rect: libgfx_rust::IntRect,- out_damage_rect: *mut libgfx_rust::IntRect,-) -> bool {- // SAFETY: The caller guarantees live handles and valid slices for the duration of the call.- let (old_storage, old_tree, old_scroll_offsets, new_storage, new_tree, new_scroll_offsets) = unsafe {- (- storage_from_handle(old_storage),- tree_from_handle(old_tree),- ak::slice_from_raw_parts(old_scroll_offsets, old_scroll_offsets_len),- storage_from_handle(new_storage),- tree_from_handle(new_tree),- ak::slice_from_raw_parts(new_scroll_offsets, new_scroll_offsets_len),- )- };- // SAFETY: As above.- let live_content_changes = unsafe {- crate::display_list::damage::LiveContentChanges {- canvases: ak::slice_from_raw_parts(canvases_with_new_content, canvases_with_new_content_len),- video_sinks: ak::slice_from_raw_parts(video_sinks_with_new_frames, video_sinks_with_new_frames_len),- image_frames: ak::slice_from_raw_parts(image_frames_with_new_pixels, image_frames_with_new_pixels_len),- forced_damage_rect,- }- };- let damage = crate::display_list::damage::compute_display_list_damage(- crate::display_list::damage::DisplayListFrame {- command_bytes: old_storage.bytes(),- command_runs: old_storage.command_runs(),- summary: old_storage.summary(),- visual_context_tree: old_tree,- scroll_offsets: old_scroll_offsets,- },- crate::display_list::damage::DisplayListFrame {- command_bytes: new_storage.bytes(),- command_runs: new_storage.command_runs(),- summary: new_storage.summary(),- visual_context_tree: new_tree,- scroll_offsets: new_scroll_offsets,- },- viewport_rect,- live_content_changes,- );- match damage {- Some(damage_rect) => {- // SAFETY: The caller guarantees `out_damage_rect` is writable.- unsafe { *out_damage_rect = damage_rect };- true- }- None => false,- }-}-/// # Safety///-/// `tree` must be a live retained tree handle of the structural epoch the storage was recorded-/// against, `storage` a live storage handle, `scroll_offsets` must address `scroll_offsets_len`-/// points for the call, and `callbacks` must be live. The painter callbacks run synchronously and-/// may re-enter this function for a nested display list.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn display_list_replay(- tree: *const c_void,+/// `storage` must be a live storage handle of a list recorded against the structural epoch of `tree`, and `callbacks`+/// must be live. The painter callbacks run synchronously and may re-enter a replay for a nested display list.+pub unsafe fn replay_display_list_storage(+ tree: &crate::visual_context::VisualContextTree,storage: *const c_void,root_group_color: libgfx_rust::Color,- scroll_offsets: *const libgfx_rust::FloatPoint,- scroll_offsets_len: usize,+ scroll_offsets: &[FloatPoint],callbacks: *const crate::host::FfiDisplayListReplayCallbacks,) {- // SAFETY: The caller guarantees live handles and a valid slice for the duration of the call.- let (tree, storage, scroll_offsets) = unsafe {- (- tree_from_handle(tree),- storage_from_handle(storage),- ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len),- )- };+ // SAFETY: The caller guarantees a live handle for the duration of the call.+ let storage = unsafe { storage_from_handle(storage) };// SAFETY: The caller guarantees `callbacks` is live for the call.let mut painter = unsafe { *callbacks };crate::display_list::replay::replay_display_list(@@ -158,28 +76,17 @@ pub unsafe extern "C" fn display_list_replay();}-/// Plays a stream of records that a command nests, outside of any run.+/// Plays a stream of records that a command nests, outside of any run, with the scroll containers at `scroll_offsets`.////// # Safety///-/// `records` must address `records_size` bytes of a tape that is valid, and `scroll_offsets`-/// `scroll_offsets_len` points for the call; `callbacks` must be live. The painter callbacks run-/// synchronously and may re-enter this function.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn display_list_replay_records(- records: *const u8,- records_size: usize,- scroll_offsets: *const libgfx_rust::FloatPoint,- scroll_offsets_len: usize,+/// `records` must be a tape that is valid, and `callbacks` must be live. The painter callbacks run synchronously and+/// may re-enter a replay.+pub unsafe fn replay_nested_records(+ records: &[u8],+ scroll_offsets: &[FloatPoint],callbacks: *const crate::host::FfiDisplayListReplayCallbacks,) {- // SAFETY: The caller guarantees the slices address the stated number of values.- let (records, scroll_offsets) = unsafe {- (- ak::slice_from_raw_parts(records, records_size),- ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len),- )- };// SAFETY: The caller guarantees `callbacks` is live for the call.let mut painter = unsafe { *callbacks };// NB: Nested records share the context of the command they are nested in, and none of their inline clips has a@@ -187,6 +94,40 @@ pub unsafe extern "C" fn display_list_replay_records(crate::display_list::replay::replay_records(records, scroll_offsets, &|_| None, &mut painter);}+/// Replays a list with nothing scrolled, as a list nested in another is.+///+/// # Safety+///+/// `tree` must be a live retained tree handle of the structural epoch the storage was recorded+/// against, `storage` a live storage handle, and `callbacks` must be live. The painter callbacks run+/// synchronously and may re-enter this function for a nested display list.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn display_list_replay(+ tree: *const c_void,+ storage: *const c_void,+ root_group_color: libgfx_rust::Color,+ callbacks: *const crate::host::FfiDisplayListReplayCallbacks,+) {+ // SAFETY: The caller guarantees live handles and callbacks for the duration of the call.+ unsafe { replay_display_list_storage(tree_from_handle(tree), storage, root_group_color, &[], callbacks) };+}++/// Plays a stream of records that a command nests, outside of any run, with nothing scrolled.+///+/// # Safety+///+/// `records` must address `records_size` bytes of a tape that is valid for the call; `callbacks` must be+/// live. The painter callbacks run synchronously and may re-enter this function.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn display_list_replay_records(+ records: *const u8,+ records_size: usize,+ callbacks: *const crate::host::FfiDisplayListReplayCallbacks,+) {+ // SAFETY: The caller guarantees the slice addresses the stated number of bytes, and live callbacks.+ unsafe { replay_nested_records(ak::slice_from_raw_parts(records, records_size), &[], callbacks) };+}+/// # Safety////// `tree` must be a retained tree handle (from `layout_arena_main_visual_context_tree_retain`,@@ -275,75 +216,18 @@ pub unsafe extern "C" fn display_list_references_only_live_visual_context_nodes(tree.display_list_references_only_live_nodes(storage.command_runs())}-/// # Safety-///-/// `world` must be a live handle from `world_transforms_create`.-pub unsafe fn world_transforms_from_handle<'a>(world: *const c_void) -> &'a crate::visual_context::WorldTransforms {- // SAFETY: The caller guarantees `world` is a live handle.- unsafe { &*world.cast::<crate::visual_context::WorldTransforms>() }-}--/// The world transforms of `tree` under the scroll offsets, in the layout viewport's space, until-/// `world_transforms_destroy` frees them.+/// Whether the node's scroll translations and the origins drawn in its space round to whole device pixels: no+/// transform but identities lies above it.////// # Safety///-/// `tree` must be a live retained tree handle; `scroll_offsets` must address `scroll_offsets_len` points.+/// `tree` must be a live retained tree handle.#[unsafe(no_mangle)]-pub unsafe extern "C" fn world_transforms_create(+pub unsafe extern "C" fn visual_context_tree_translations_snap_to_device_pixels(tree: *const c_void,- scroll_offsets: *const libgfx_rust::FloatPoint,- scroll_offsets_len: usize,-) -> *mut c_void {- let tree = unsafe { tree_from_handle(tree) };- // SAFETY: The caller guarantees the offsets address `scroll_offsets_len` points.- let scroll_offsets = unsafe { ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len) };- let world = crate::visual_context::WorldTransforms::new(tree, scroll_offsets, None);- Box::into_raw(Box::new(world)).cast()-}--/// # Safety-///-/// `world` must be a handle from `world_transforms_create` that nothing uses afterwards.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn world_transforms_destroy(world: *mut c_void) {- // SAFETY: The caller hands over the handle `world_transforms_create` made.- drop(unsafe { Box::from_raw(world.cast::<crate::visual_context::WorldTransforms>()) });-}--fn include_visual_viewport_transform_from(include: bool) -> crate::visual_context::IncludeVisualViewportTransform {- if include {- crate::visual_context::IncludeVisualViewportTransform::Yes- } else {- crate::visual_context::IncludeVisualViewportTransform::No- }-}--/// # Safety-///-/// `world` must be a live handle from `world_transforms_create`.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn world_transforms_translations_snap_to_device_pixels(- world: *const c_void,spatial: SpatialNodeIndex,) -> bool {- unsafe { world_transforms_from_handle(world) }.translations_snap_to_device_pixels(spatial)-}--/// # Safety-///-/// `world` must be a live handle from `world_transforms_create`.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn world_transforms_accumulated_matrix(- world: *const c_void,- spatial: SpatialNodeIndex,- include_visual_viewport_transform: bool,- matrix: &mut libgfx_rust::FloatMatrix4x4,-) {- *matrix = unsafe { world_transforms_from_handle(world) }.to_viewport_matrix(- spatial,- include_visual_viewport_transform_from(include_visual_viewport_transform),- );+ unsafe { tree_from_handle(tree) }.translations_snap_to_device_pixels(spatial)}/// # Safetydiff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex 7c53276bf58..fcca8ad9f6b 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -17,7 +17,6 @@ use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encodpub type Web_CompositorContextId = CompositorContextId;pub type Web_UniqueNodeID = UniqueNodeId;pub type Web_CSSPixelPoint = CssPixelPoint;-pub type Compositing_ScrollStateSnapshot = crate::scrolling::ScrollStateSnapshot;pub type Gfx_IntPoint = libgfx_rust::IntPoint;pub type Gfx_FloatPoint = libgfx_rust::FloatPoint;pub type Gfx_IntSize = libgfx_rust::IntSize;diff --git a/Libraries/LibCompositing/Rust/src/scrolling/scroll_state_snapshot.rs b/Libraries/LibCompositing/Rust/src/scrolling/scroll_state_snapshot.rsindex 60be8298e72..af7dc10cd6d 100644--- a/Libraries/LibCompositing/Rust/src/scrolling/scroll_state_snapshot.rs+++ b/Libraries/LibCompositing/Rust/src/scrolling/scroll_state_snapshot.rs@@ -79,6 +79,31 @@ impl Default for ScrollStateSnapshot {}impl ScrollStateSnapshot {+ pub fn from_device_offsets(device_offsets: Vec<FloatPoint>) -> Self {+ Self {+ device_offsets,+ ..Self::default()+ }+ }++ // The wire form, for C++ to carry to where Rust decodes it again.+ pub fn to_encoded_bytes(&self) -> Vec<u8> {+ let mut encoder = Encoder::new();+ encoder.encode(self).expect("a scroll state snapshot encodes");+ encoder.finish().0+ }++ pub fn from_encoded_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {+ let mut decoder = Decoder::new(bytes, []);+ let snapshot = decoder.decode()?;+ if !decoder.is_at_end() {+ return Err(DecodeError::InvalidValue(+ "bytes after an encoded scroll state snapshot",+ ));+ }+ Ok(snapshot)+ }+pub fn device_offsets(&self) -> &[FloatPoint] {&self.device_offsets}@@ -193,3 +218,84 @@ impl Decode for ScrollStateSnapshot {Ok(snapshot)}}++#[cfg(test)]+mod tests {+ use super::*;++ // An index far above any real node count, but still inside the range the decoder accepts. Densifying it would+ // allocate (index + 1) * size_of::<FloatPoint>(), i.e. 512 MiB: the allocation the node-count bound exists to stop.+ const MALICIOUS_INDEX: u32 = 0x0400_0000;++ fn decode_snapshot(pairs: &[(u64, FloatPoint)]) -> ScrollStateSnapshot {+ let mut encoder = Encoder::new();+ encoder.encode(&(pairs.len() as u64)).unwrap();+ for (index, offset) in pairs {+ encoder.encode(index).unwrap();+ encoder.encode(offset).unwrap();+ }+ ScrollStateSnapshot::from_encoded_bytes(&encoder.finish().0).unwrap()+ }++ #[test]+ fn binding_to_node_count_keeps_in_range_and_drops_out_of_range() {+ // A single 16-byte wire pair can claim any node index the decoder accepts. The decoder stages the pair instead+ // of densifying, so decoding cannot abort or over-allocate. The index is validated only once the compositor+ // supplies the node count, which drops it.+ let mut snapshot = decode_snapshot(&[+ (3, FloatPoint { x: 10.0, y: 20.0 }),+ (MALICIOUS_INDEX.into(), FloatPoint { x: 30.0, y: 40.0 }),+ ]);++ snapshot.set_node_count(8);++ assert_eq!(+ snapshot.device_offset_for_index(SpatialNodeIndex(3)),+ FloatPoint { x: 10.0, y: 20.0 }+ );+ assert_eq!(+ snapshot.device_offset_for_index(SpatialNodeIndex(MALICIOUS_INDEX)),+ FloatPoint::default()+ );+ assert!(snapshot.device_offsets().len() <= 8);+ }++ #[test]+ fn set_device_offset_ignores_index_at_or_past_node_count() {+ let mut snapshot = ScrollStateSnapshot::default();+ snapshot.set_node_count(4);++ snapshot.set_device_offset_for_index(SpatialNodeIndex(3), FloatPoint { x: 5.0, y: 6.0 });+ snapshot.set_device_offset_for_index(SpatialNodeIndex(4), FloatPoint { x: 7.0, y: 8.0 });+ snapshot.set_device_offset_for_index(SpatialNodeIndex(MALICIOUS_INDEX), FloatPoint { x: 9.0, y: 9.0 });++ assert_eq!(+ snapshot.device_offset_for_index(SpatialNodeIndex(3)),+ FloatPoint { x: 5.0, y: 6.0 }+ );+ assert_eq!(+ snapshot.device_offset_for_index(SpatialNodeIndex(4)),+ FloatPoint::default()+ );+ assert!(snapshot.device_offsets().len() <= 4);+ }++ #[test]+ fn wire_round_trip_preserves_scroll_offsets() {+ let mut snapshot = ScrollStateSnapshot::default();+ snapshot.set_device_offset_for_index(SpatialNodeIndex(3), FloatPoint { x: 10.0, y: 20.0 });++ let mut decoded = ScrollStateSnapshot::from_encoded_bytes(&snapshot.to_encoded_bytes()).unwrap();+ decoded.set_node_count(8);++ assert_eq!(+ decoded.device_offset_for_index(SpatialNodeIndex(3)),+ FloatPoint { x: 10.0, y: 20.0 }+ );+ // Indices that were never set are holes that decode back to zero offsets.+ assert_eq!(+ decoded.device_offset_for_index(SpatialNodeIndex(1)),+ FloatPoint::default()+ );+ }+}diff --git a/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs b/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rsindex 3d3ab1a2d27..e160ce2c664 100644--- a/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs+++ b/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs@@ -8,7 +8,7 @@use super::{ContextRef, DisplayList, ScrollStateSnapshot, SpatialNodeIndex};use crate::visual_context::VisualContextTree;-use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, IntRect};+use libgfx_rust::{FloatPoint, FloatRect, IntRect};use std::sync::Arc;pub use crate::visual_context::ffi_types::FfiVisualViewportTransform as TransformWithOrigin;@@ -92,18 +92,6 @@ impl AccumulatedVisualContextTree {Self(Arc::new(self.0.with_visual_animation_samples(monotonic_time_ns)))}- // Whether the node's scroll translations and the origins drawn in its space round to whole device pixels: no- // transform but identities lies above it.- pub fn translations_snap_to_device_pixels(- &self,- spatial_node_index: SpatialNodeIndex,- scroll_state: &ScrollStateSnapshot,- ) -> bool {- scroll_state- .world_transforms(self)- .translations_snap_to_device_pixels(spatial_node_index)- }-pub fn transform_point_for_hit_test(&self,context: ContextRef,@@ -132,18 +120,6 @@ impl AccumulatedVisualContextTree {include_visual_viewport_transform,)}-- // Sum of the snapshot entries along the scroll-parent chain from the given scroll-like node.- pub fn accumulated_matrix(- &self,- index: SpatialNodeIndex,- scroll_state: &ScrollStateSnapshot,- include_visual_viewport_transform: IncludeVisualViewportTransform,- ) -> FloatMatrix4x4 {- scroll_state- .world_transforms(self)- .to_viewport_matrix(index, include_visual_viewport_transform)- }}// Fills the snapshot entries of the tree's sticky nodes from the scroll containers' entries.diff --git a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs b/Libraries/LibCompositing/Rust/src/visual_context/queries.rsindex a1db89195d7..cbc12232846 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs@@ -274,6 +274,28 @@ impl VisualContextTree {Some(context_walk.point)}+ /// Whether the node's scroll translations and the origins drawn in its space round to whole device pixels: no+ /// transform but identities lies above it. A table of world transforms answers the same for every node at once.+ pub fn translations_snap_to_device_pixels(&self, node: SpatialNodeIndex) -> bool {+ let mut index = node;+ loop {+ let Some(spatial_node) = self.spatial_nodes.get(index.0 as usize) else {+ return false;+ };+ if !spatial_node.data.is_live() {+ return false;+ }+ if index == VISUAL_VIEWPORT_NODE_INDEX {+ return true;+ }+ let local = self.local_transform(index, &[]);+ if local.is_transform_or_perspective() && local.matrix != FloatMatrix4x4::identity() {+ return false;+ }+ index = spatial_node.parent;+ }+ }+/// The sum of the resolved offsets of the sticky nodes on the spatial chain from `index` up to the viewport, in/// device pixels.pub fn accumulated_sticky_offset(&self, index: SpatialNodeIndex, resolved_offsets: &[FloatPoint]) -> FloatPoint {@@ -636,6 +658,40 @@ mod tests {}}+ #[test]+ fn translations_snap_under_identities_as_the_world_transforms_table_says() {+ let mut tree = identity_tree();+ let scroller = tree.append_spatial(scroll(), VISUAL_VIEWPORT_NODE_INDEX);+ let identity = tree.append_spatial(+ SpatialData::Transform(transform_data(FloatMatrix4x4::identity(), FloatPoint::default())),+ scroller,+ );+ let scroller_under_identity = tree.append_spatial(scroll(), identity);+ let scaled = tree.append_spatial(+ SpatialData::Transform(transform_data(scale_matrix(2.0, 2.0, 1.0), FloatPoint::default())),+ scroller,+ );+ let scroller_under_scale = tree.append_spatial(scroll(), scaled);+ let removed = tree.append_spatial(scroll(), VISUAL_VIEWPORT_NODE_INDEX);+ assert!(tree.tombstone_spatial_slot(removed));++ let world = WorldTransforms::new(&tree, &[], None);+ let nodes = [+ (VISUAL_VIEWPORT_NODE_INDEX, true),+ (scroller, true),+ (identity, true),+ (scroller_under_identity, true),+ (scaled, false),+ (scroller_under_scale, false),+ (removed, false),+ (SpatialNodeIndex(tree.spatial_nodes.len() as u32), false),+ ];+ for (node, snaps) in nodes {+ assert_eq!(tree.translations_snap_to_device_pixels(node), snaps, "{node:?}");+ assert_eq!(world.translations_snap_to_device_pixels(node), snaps, "{node:?}");+ }+ }+fn hit_test_point(tree: &VisualContextTree,context: ContextRef,diff --git a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cppindex ad1f1333e19..cddf561707d 100644--- a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp+++ b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp@@ -30,12 +30,11 @@ String async_scrolling_state_as_json(DisplayList const* display_list)return json;}-FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_list(DisplayList const& display_list, AccumulatedVisualContextTree const& visual_context_tree, ScrollStateSnapshot const& scroll_state_snapshot, u64 newest_wheel_event_listener_state_generation, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels)+FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_list(DisplayList const& display_list, AccumulatedVisualContextTree const& visual_context_tree, 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());- IPC::Encoded<ScrollStateSnapshot> encoded_scroll_state_snapshot { scroll_state_snapshot };- auto route = RustFFI::recorded_display_list_route_first_wheel_step(&display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state_snapshot.bytes(), newest_wheel_event_listener_state_generation, position, delta_in_css_pixels);+ auto route = RustFFI::recorded_display_list_route_first_wheel_step(&display_list_for_scroll_logic, visual_context_tree.rust_handle(), 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) {@@ -50,12 +49,11 @@ FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_lireturn result;}-bool recorded_display_list_blocks_wheel_event_at(DisplayList const& display_list, AccumulatedVisualContextTree const& visual_context_tree, ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position)+bool recorded_display_list_blocks_wheel_event_at(DisplayList const& display_list, AccumulatedVisualContextTree const& visual_context_tree, 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());- IPC::Encoded<ScrollStateSnapshot> encoded_scroll_state_snapshot { scroll_state_snapshot };- return RustFFI::recorded_display_list_blocks_wheel_event_at(&display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state_snapshot.bytes(), position);+ return RustFFI::recorded_display_list_blocks_wheel_event_at(&display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state, position);}}diff --git a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.hindex 2ef58b1a456..6a110aa530f 100644--- a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h+++ b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h@@ -9,13 +9,14 @@#include <AK/String.h>#include <LibCompositing/Export.h>#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>+#include <LibGfx/Point.h>namespace Compositing {COMPOSITING_API String async_scrolling_state_as_json(DisplayList const*);-COMPOSITING_API FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_list(DisplayList const&, AccumulatedVisualContextTree const&, ScrollStateSnapshot const&, 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&, AccumulatedVisualContextTree const&, ScrollStateSnapshot const&, Gfx::FloatPoint position);+// 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&, AccumulatedVisualContextTree 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&, AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state, Gfx::FloatPoint position);}diff --git a/Libraries/LibCompositing/Scrolling/ScrollState.cpp b/Libraries/LibCompositing/Scrolling/ScrollState.cppdeleted file mode 100644index d08a21ad7c2..00000000000--- a/Libraries/LibCompositing/Scrolling/ScrollState.cpp+++ /dev/null@@ -1,76 +0,0 @@-/*- * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/NumericLimits.h>-#include <AK/Vector.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/RustFFI.h>-#include <LibCompositing/Scrolling/ScrollState.h>-#include <LibIPC/Decoder.h>-#include <LibIPC/Encoder.h>--namespace Compositing {--void const* WorldTransformsCache::get_or_build(AccumulatedVisualContextTree const& tree, ReadonlySpan<Gfx::FloatPoint> device_offsets)-{- if (m_world_transforms && m_retained_tree == tree.rust_handle())- return m_world_transforms;- clear();- m_retained_tree = RustFFI::visual_context_tree_retain(tree.rust_handle());- m_world_transforms = RustFFI::world_transforms_create(m_retained_tree, device_offsets.data(), device_offsets.size());- return m_world_transforms;-}--void WorldTransformsCache::clear()-{- if (m_world_transforms)- RustFFI::world_transforms_destroy(exchange(m_world_transforms, nullptr));- if (m_retained_tree)- RustFFI::visual_context_tree_release(exchange(m_retained_tree, nullptr));-}--}--namespace IPC {--// The dense in-process vector spans the whole spatial node index space, but only scroll and-// sticky node indices can hold non-zero offsets, so the wire format is sparse (index, offset)-// pairs; holes decode back to zero offsets.-template<>-ErrorOr<void> encode(Encoder& encoder, Compositing::ScrollStateSnapshot const& snapshot)-{- auto device_offsets = snapshot.device_offsets();- u64 non_zero_offset_count = 0;- for (auto const& offset : device_offsets) {- if (!offset.is_zero())- ++non_zero_offset_count;- }- TRY(encoder.encode(non_zero_offset_count));- for (size_t index = 0; index < device_offsets.size(); ++index) {- if (device_offsets[index].is_zero())- continue;- TRY(encoder.encode(static_cast<u64>(index)));- TRY(encoder.encode(device_offsets[index]));- }- return {};-}--template<>-ErrorOr<Compositing::ScrollStateSnapshot> decode(Decoder& decoder)-{- auto pair_count = TRY(decoder.decode<u64>());- Compositing::ScrollStateSnapshot snapshot;- for (u64 i = 0; i < pair_count; ++i) {- auto index = TRY(decoder.decode<u64>());- auto offset = TRY(decoder.decode<Gfx::FloatPoint>());- if (index >= NumericLimits<u32>::max())- return Error::from_string_literal("IPC decode: ScrollStateSnapshot index out of range");- TRY(snapshot.m_staged_offsets.try_append({ static_cast<u32>(index), offset }));- }- return snapshot;-}--}diff --git a/Libraries/LibCompositing/Scrolling/ScrollState.h b/Libraries/LibCompositing/Scrolling/ScrollState.hdeleted file mode 100644index f6210a8b562..00000000000--- a/Libraries/LibCompositing/Scrolling/ScrollState.h+++ /dev/null@@ -1,157 +0,0 @@-/*- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/DistinctNumeric.h>-#include <AK/NumericLimits.h>-#include <AK/Types.h>-#include <AK/Vector.h>-#include <LibCompositing/DisplayList/ContextRef.h>-#include <LibCompositing/Export.h>-#include <LibCompositing/Forward.h>-#include <LibGfx/Point.h>-#include <LibIPC/Forward.h>-#include <LibWebCommon/PixelUnits.h>--namespace Compositing {--// The world transforms built for one visual context tree under a snapshot's offsets. A copy starts empty, so the table-// never outlives the offsets it was built for. A move takes the table along with the offsets.-class COMPOSITING_API WorldTransformsCache {-public:- WorldTransformsCache() = default;- WorldTransformsCache(WorldTransformsCache const&) { }- WorldTransformsCache& operator=(WorldTransformsCache const&)- {- clear();- return *this;- }- WorldTransformsCache(WorldTransformsCache&& other)- : m_retained_tree(exchange(other.m_retained_tree, nullptr))- , m_world_transforms(exchange(other.m_world_transforms, nullptr))- {- }- WorldTransformsCache& operator=(WorldTransformsCache&& other)- {- if (this != &other) {- clear();- m_retained_tree = exchange(other.m_retained_tree, nullptr);- m_world_transforms = exchange(other.m_world_transforms, nullptr);- }- return *this;- }- ~WorldTransformsCache() { clear(); }-- void const* get_or_build(AccumulatedVisualContextTree const&, ReadonlySpan<Gfx::FloatPoint> device_offsets);- void clear();--private:- // The cache retains the tree, so the tree it describes cannot change under it: a write to a shared tree copies it.- void const* m_retained_tree { nullptr };- void* m_world_transforms { nullptr };-};--// Device-pixel offsets keyed by SpatialNodeIndex: the scroll containers' offsets as produced by-// the document, plus the sticky nodes' offsets derived from them and the tree (by the document's-// scroll state refresh in process, by resolve_sticky_offsets() in the compositor). Stored dense in process so display list replay and hit testing index it directly;-// indices that are not scroll-like nodes read as zero offsets. The IPC representation is sparse-// (index, offset) pairs.-//-// The dense store must never grow past the spatial node count. A compromised WebContent renderer controls the-// indices that reach it — both as decoded wire pairs and as scroll-node indices replayed from the display list. So,-// set_device_offset_for_index() drops any index at or past m_node_count. The compositor supplies that bound from the-// AccumulatedVisualContextTree that owns these nodes. Until it does, the bound is unlimited — which is what the-// trusted in-process snapshot built from live scroll nodes needs.-class ScrollStateSnapshot {-public:- ReadonlySpan<Gfx::FloatPoint> device_offsets() const { return m_device_offsets; }-- // The world transforms of the tree under these offsets, in the layout viewport's space, kept until either changes.- void const* world_transforms(AccumulatedVisualContextTree const& tree) const- {- return m_world_transforms_cache.get_or_build(tree, m_device_offsets);- }-- Gfx::FloatPoint device_offset_for_index(SpatialNodeIndex index) const- {- if (index.value() >= m_device_offsets.size())- return {};- return m_device_offsets[index.value()];- }-- void set_device_offset_for_index(SpatialNodeIndex index, Gfx::FloatPoint offset)- {- if (index.value() >= m_node_count)- return;- m_world_transforms_cache.clear();- if (index.value() >= m_device_offsets.size()) {- m_device_offsets.grow_capacity(index.value() + 1);- m_device_offsets.resize(index.value() + 1);- }- m_device_offsets[index.value()] = offset;- }-- // Replaces every offset with a freshly derived dense array, keeping the node count bound.- void assign_device_offsets(ReadonlySpan<Gfx::FloatPoint> offsets)- {- m_world_transforms_cache.clear();- m_device_offsets.clear_with_capacity();- m_device_offsets.append(offsets.data(), min(offsets.size(), m_node_count));- }-- // The world transforms another snapshot built are the ones this snapshot would build while both hold the same- // offsets, so this one takes them over then instead of building its own.- void take_world_transforms_built_for_the_same_offsets_from(ScrollStateSnapshot& other)- {- if (m_device_offsets == other.m_device_offsets)- m_world_transforms_cache = move(other.m_world_transforms_cache);- }-- // Bind the snapshot to the authoritative node count from the AccumulatedVisualContextTree that owns these nodes.- // Wire-decoded offsets are staged rather than densified. So, this is where a decoded index is first validated:- // staged pairs are applied through the bounded setter above, dropping any whose index is at or past the node count.- // And any offset already stored past the count is discarded. Every later mutation stays bounded by the count.- void set_node_count(size_t node_count)- {- m_world_transforms_cache.clear();- m_node_count = node_count;- if (m_device_offsets.size() > node_count)- m_device_offsets.resize(node_count);- auto staged_offsets = move(m_staged_offsets);- for (auto const& staged : staged_offsets)- set_device_offset_for_index(SpatialNodeIndex { staged.index }, staged.offset);- }--private:- template<typename T>- friend ErrorOr<void> IPC::encode(IPC::Encoder&, T const&);- template<typename T>- friend ErrorOr<T> IPC::decode(IPC::Decoder&);-- // A sparse wire pair captured by the decoder before the node count is known. Held apart from the dense store — so- // that a single decoded pair cannot grow the store to an arbitrary size.- struct StagedOffset {- u32 index { 0 };- Gfx::FloatPoint offset;- };-- Vector<Gfx::FloatPoint> m_device_offsets;- Vector<StagedOffset> m_staged_offsets;- size_t m_node_count { NumericLimits<size_t>::max() };- mutable WorldTransformsCache m_world_transforms_cache;-};--}--namespace IPC {--template<>-COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::ScrollStateSnapshot const&);-template<>-COMPOSITING_API ErrorOr<Compositing::ScrollStateSnapshot> decode(Decoder&);--}diff --git a/Libraries/LibWeb/CSS/ScrollStateContainerQuery.cpp b/Libraries/LibWeb/CSS/ScrollStateContainerQuery.cppindex 63fd89d45d9..ac67371105b 100644--- a/Libraries/LibWeb/CSS/ScrollStateContainerQuery.cpp+++ b/Libraries/LibWeb/CSS/ScrollStateContainerQuery.cpp@@ -41,17 +41,15 @@ static Layout::Node* scrolling_box_of(Layout::BegunRead const& read, DOM::Docume}// https://drafts.csswg.org/css-conditional-5/#stuck-static u8 stuck_edges(DOM::Document& document, Layout::Node const& layout_node)+static u8 stuck_edges(Layout::Node const& layout_node){auto const* node_with_style = as_if<Layout::NodeWithStyle>(layout_node);if (!node_with_style || !node_with_style->is_sticky_position())return 0;- auto sticky_node_index = Layout::RustFFI::render_state_sticky_spatial_node_index(layout_node.document_host(), Painting::committed_row_slot(layout_node));- if (sticky_node_index == NumericLimits<u32>::max())- return 0;-// A sticky box is stuck to the edge whose inset moved it from its normal position.- auto offset = document.paint_state().scroll_state_snapshot().device_offset_for_index(Compositing::SpatialNodeIndex { sticky_node_index });+ Gfx::FloatPoint offset;+ if (!Layout::RustFFI::render_state_sticky_device_offset(layout_node.document_host(), Painting::committed_row_slot(layout_node), &offset))+ return 0;u8 edges = 0;if (offset.y() > 0)edges |= SCROLL_STATE_EDGE_TOP;@@ -186,7 +184,7 @@ bool ScrollStateQueryContainers::snapshot_post_layout_state(Layout::BegunRead coScrollStateSnapshot snapshot;if (auto* layout_node = element->unsafe_layout_node(read); layout_node && Painting::has_committed_box(*layout_node)) {- snapshot.stuck = stuck_edges(document, *layout_node);+ snapshot.stuck = stuck_edges(*layout_node);snapshot.snapped = snapped_axes(document, element, *layout_node);}if (auto* scrolling_box = scrolling_box_of(read, document, element)) {diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex 58ddd21a937..a16bc6d1c6a 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -197,7 +197,7 @@ bool CompositorConnectionFrameSink::post_display_list_update(Web::CompositorCont}auto copy_time = timer.elapsed_time();- auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateDisplayList::static_encode(context_id, shared_tape_buffer.value(), display_list.tape_size(), display_list.run_count(), display_list.properties(), IPC::Encoded { display_list.async_scrolling_metadata() }, update.visual_context_tree, update.resource_transaction, IPC::Encoded { update.scroll_state_snapshot }));+ auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateDisplayList::static_encode(context_id, shared_tape_buffer.value(), display_list.tape_size(), display_list.run_count(), display_list.properties(), IPC::Encoded { display_list.async_scrolling_metadata() }, update.visual_context_tree, update.resource_transaction, update.encoded_scroll_state));if (!post(encoded_message))return false;if (display_list_timing_enabled())@@ -224,7 +224,7 @@ bool CompositorConnectionFrameSink::submit(CompositorFrame&& frame)return false;}if (auto& update = frame.scroll_state_update; update.has_value()) {- auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateScrollState::static_encode(context_id, update->scroll_state_snapshot, update->keyboard_scroll_state));+ 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;}diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex b13801702a4..9cd7f9c99fa 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -16,7 +16,6 @@#include <LibCompositing/DisplayList/Canvas2DCommandStream.h>#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>#include <LibCompositing/WebGL/Types.h>#include <LibGfx/Forward.h>diff --git a/Libraries/LibWeb/Compositor/CompositorFrame.h b/Libraries/LibWeb/Compositor/CompositorFrame.hindex b67a5e40f50..5cedf307d5e 100644--- a/Libraries/LibWeb/Compositor/CompositorFrame.h+++ b/Libraries/LibWeb/Compositor/CompositorFrame.h@@ -7,12 +7,12 @@#pragma once#include <AK/AtomicRefCounted.h>+#include <AK/ByteBuffer.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>#include <LibGfx/Rect.h>#include <LibGfx/ShareableBitmap.h>@@ -22,7 +22,8 @@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.+// 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;@@ -31,7 +32,7 @@ struct CompositorFrame {NonnullRefPtr<Compositing::DisplayList> display_list;Compositing::AccumulatedVisualContextTree visual_context_tree;Compositing::DisplayListResourceTransaction resource_transaction;- Compositing::ScrollStateSnapshot scroll_state_snapshot;+ ByteBuffer encoded_scroll_state;};// A new visual context tree for the display list the compositor already has.@@ -42,7 +43,7 @@ struct CompositorFrame {// The scroll state of the display list the compositor already has.struct ScrollStateUpdate {- Compositing::ScrollStateSnapshot scroll_state_snapshot;+ ByteBuffer encoded_scroll_state;Compositing::KeyboardScrollState keyboard_scroll_state;};diff --git a/Libraries/LibWeb/Compositor/NavigablePresenter.cpp b/Libraries/LibWeb/Compositor/NavigablePresenter.cppindex 1bdb283fa0a..c1753a6d6ba 100644--- a/Libraries/LibWeb/Compositor/NavigablePresenter.cpp+++ b/Libraries/LibWeb/Compositor/NavigablePresenter.cpp@@ -29,24 +29,24 @@ struct PresenterFFI {sealed.published->referenced_resources = presenter.m_compositor_display_list_command_resources;}- static void present(NavigablePresenter& presenter, SealedPresentation& sealed, NonnullRefPtr<Compositing::DisplayList> display_list, CompositorFrameSink* sink)+ static void present(NavigablePresenter& presenter, SealedPresentation& sealed, NonnullRefPtr<Compositing::DisplayList> display_list, 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));+ auto frame = presenter.build_frame_beside_event_loop(sealed, move(display_list), encoded_scroll_state);frame.scroll_requests = move(sealed.scroll_requests);note_presented(presenter, sealed);if (sink)sink->submit(move(frame));}- static void present_unrecorded(NavigablePresenter& presenter, SealedPresentation& sealed, CompositorFrameSink* sink)+ static void present_unrecorded(NavigablePresenter& presenter, SealedPresentation& sealed, ReadonlyBytes encoded_scroll_state, CompositorFrameSink* sink){MutexLocker locker(presenter.m_mutex);if (is_stale(presenter, sealed))return;- auto frame = presenter.build_frame(sealed, {});+ auto frame = presenter.build_frame(sealed, {}, encoded_scroll_state);frame.scroll_requests = move(sealed.scroll_requests);note_presented(presenter, sealed);if (sink)@@ -64,7 +64,7 @@ void NavigablePresenter::forget_compositor_display_list()m_compositor_display_list_command_resources = {};}-CompositorFrame NavigablePresenter::build_frame(SealedPresentation const& sealed, Optional<PublishedDisplayList> published)+CompositorFrame NavigablePresenter::build_frame(SealedPresentation const& sealed, Optional<PublishedDisplayList> published, ReadonlyBytes encoded_scroll_state){// 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@@ -108,7 +108,7 @@ CompositorFrame NavigablePresenter::build_frame(SealedPresentation const& sealed.display_list = published->display_list,.visual_context_tree = visual_context_tree,.resource_transaction = m_resource_storage.create_transaction(m_compositor_display_list_resources, resources),- .scroll_state_snapshot = sealed.scroll_state_snapshot,+ .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_compositor_visual_context_tree = visual_context_tree;@@ -138,18 +138,18 @@ CompositorFrame NavigablePresenter::build_frame(SealedPresentation const& sealedm_compositor_visual_context_tree = visual_context_tree;}frame.scroll_state_update = CompositorFrame::ScrollStateUpdate {- .scroll_state_snapshot = sealed.scroll_state_snapshot,+ .encoded_scroll_state = MUST(ByteBuffer::copy(encoded_scroll_state)),.keyboard_scroll_state = move(keyboard_scroll_state),};return frame;}-CompositorFrame NavigablePresenter::build_frame_beside_event_loop(SealedPresentation& sealed, NonnullRefPtr<Compositing::DisplayList> display_list)+CompositorFrame NavigablePresenter::build_frame_beside_event_loop(SealedPresentation& sealed, NonnullRefPtr<Compositing::DisplayList> display_list, ReadonlyBytes encoded_scroll_state){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);+ auto frame = build_frame(sealed, published, 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;@@ -172,7 +172,6 @@ OwnPtr<SealedPresentation> NavigablePresenter::seal_for_clock_lane(SealedPresentauto sealed = make<SealedPresentation>();sealed->paint_config = committed.paint_config;sealed->visual_context_tree = *m_compositor_visual_context_tree;- sealed->scroll_state_snapshot = committed.scroll_state_snapshot;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;@@ -213,16 +212,14 @@ extern "C" WEB_API void web_sealed_presentation_destroy(void* sealed)delete static_cast<Web::Compositor::SealedPresentation*>(sealed);}-extern "C" WEB_API void web_sealed_presentation_take_visual_context_tree(void* sealed_pointer, void const* tree, Gfx::FloatPoint const* restructured_scroll_offsets, size_t scroll_offset_count)+extern "C" WEB_API void web_sealed_presentation_take_visual_context_tree(void* sealed_pointer, void const* tree, bool tree_is_restructured){auto& sealed = *static_cast<Web::Compositor::SealedPresentation*>(sealed_pointer);auto visual_context_tree = Compositing::AccumulatedVisualContextTree::adopt_rust_handle(tree);- // A tree of another structure takes the scroll offsets of its own nodes, and a new display list recorded against it.- // 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 (restructured_scroll_offsets)- sealed.scroll_state_snapshot.assign_device_offsets({ restructured_scroll_offsets, scroll_offset_count });- else if (sealed.visual_context_tree.has_value())+ // 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.has_value())VERIFY(visual_context_tree.structural_epoch() == sealed.visual_context_tree->structural_epoch());if (sealed.recording.has_value())sealed.recording->visual_context_tree = visual_context_tree;@@ -265,17 +262,17 @@ extern "C" WEB_API void web_navigable_presenter_add_video_sink(void* presenter,}// 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, void* sink);-extern "C" WEB_API void web_navigable_presenter_present_unrecorded(void* presenter, void* sealed, void* sink);+extern "C" WEB_API void web_navigable_presenter_present(void* presenter, void* sealed, Web::Layout::RustFFI::FfiPresentedRecording const* presented, 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, 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, void* sink)+extern "C" WEB_API void web_navigable_presenter_present_unrecorded(void* presenter, void* sealed, 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), static_cast<Web::Compositor::CompositorFrameSink*>(sink));+ Web::Compositor::PresenterFFI::present_unrecorded(*static_cast<Web::Compositor::NavigablePresenter*>(presenter), *static_cast<Web::Compositor::SealedPresentation*>(sealed), { encoded_scroll_state, encoded_scroll_state_size }, static_cast<Web::Compositor::CompositorFrameSink*>(sink));}-extern "C" WEB_API void web_navigable_presenter_present(void* presenter, void* sealed_pointer, Web::Layout::RustFFI::FfiPresentedRecording const* presented, void* sink)+extern "C" WEB_API void web_navigable_presenter_present(void* presenter, void* sealed_pointer, Web::Layout::RustFFI::FfiPresentedRecording const* presented, 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), static_cast<Web::Compositor::CompositorFrameSink*>(sink));+ Web::Compositor::PresenterFFI::present(*static_cast<Web::Compositor::NavigablePresenter*>(presenter), sealed, move(display_list), { 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 fd0bd4a212f..dd47d13b94d 100644--- a/Libraries/LibWeb/Compositor/NavigablePresenter.h+++ b/Libraries/LibWeb/Compositor/NavigablePresenter.h@@ -16,7 +16,6 @@#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibWeb/Compositor/CompositorFrame.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>@@ -48,7 +47,8 @@ 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.+// neither of them again before it is presented. What presents the frame holds the document's scroll state beside the+// seal.struct SealedPresentation {AK_ALLOC_WITH_KMALLOC;@@ -61,8 +61,6 @@ struct SealedPresentation {bool sends_visual_context_tree { false };// Whether the document's scroll offsets changed since the frame before.bool scroll_state_changed { false };- // The scroll state, which seeds the offsets of the boxes new to the compositor.- Compositing::ScrollStateSnapshot scroll_state_snapshot;// 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.Vector<Compositing::ScrollRequest> scroll_requests;@@ -151,12 +149,13 @@ private:// 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. Reads no navigable or document.- CompositorFrame build_frame(SealedPresentation const&, Optional<PublishedDisplayList>);+ // `sealed` sealed, 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>, 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>);+ CompositorFrame build_frame_beside_event_loop(SealedPresentation&, NonnullRefPtr<Compositing::DisplayList>, ReadonlyBytes encoded_scroll_state);NavigablePresenter() = default;@@ -193,7 +192,7 @@ 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, void const* tree, Gfx::FloatPoint const* restructured_scroll_offsets, size_t scroll_offset_count);+WEB_API void web_sealed_presentation_take_visual_context_tree(void* sealed, void const* tree, 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);diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 12def2fb91e..c5087f51b9e 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -8489,11 +8489,6 @@ Compositing::AccumulatedVisualContextTree Document::visual_context_tree() constreturn paint_state().visual_context_tree(*this);}-Compositing::ScrollStateSnapshot const& Document::scroll_state_snapshot() const-{- return paint_state().scroll_state_snapshot();-}-// https://html.spec.whatwg.org/multipage/browsing-the-web.html#restore-the-history-object-statevoid Document::restore_the_history_object_state(NonnullRefPtr<HTML::SessionHistoryEntry> entry){@@ -12317,7 +12312,6 @@ Optional<Painting::HitTestQuery> Document::prepare_hit_test_query(Layout::BegunRreturn Painting::HitTestQuery {*m_hit_test_display_list,- scroll_state_snapshot(),page().client().device_pixels_per_css_pixel(),page().chrome_metrics(),visual_animation_sample_time_nanoseconds,diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex b1971cfbab5..df6faa81534 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -690,8 +690,6 @@ public:PaintTiming::DocumentPaintTimingState& paint_timing_state() { return m_paint_timing_state; }- Compositing::ScrollStateSnapshot const& scroll_state_snapshot() const;-GC::Ref<NodeList> get_elements_by_name(Utf16View);GC::Ref<HTMLCollection> applets();diff --git a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cppindex 6283aaec07b..7ef2cb11d52 100644--- a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp@@ -297,7 +297,6 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)}// The lane's ticks may also follow the pointer, and hover what is under it while a task runs.Optional<Layout::RustFFI::FfiHoverPlanInputs> hover;- Span<Gfx::FloatPoint const> scroll_offsets;Vector<u32> effect_timing_nodes;Vector<u64> effect_timing_identities;Vector<CSS::ComputedValuesFFI::FfiEffectTiming> effect_timings;@@ -325,15 +324,12 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)effect_timings.append(timing);}}- scroll_offsets = document.scroll_state_snapshot().device_offsets();Optional<Web::EventHandler::SelectionDragForLanes> selection_drag;if (auto navigable = document.navigable())selection_drag = navigable->event_handler().selection_drag_for_lanes(read);auto scrollport = selection_drag.has_value() ? selection_drag->scrollport.value_or(CSSPixelRect {}) : CSSPixelRect {};hover = Layout::RustFFI::FfiHoverPlanInputs {.device_pixels_per_css_pixel = document.page().client().device_pixels_per_css_pixel(),- .scroll_offsets = scroll_offsets.data(),- .scroll_offset_count = scroll_offsets.size(),.chrome_metrics = document.page().chrome_metrics(),.page_cursor = ffi_page_cursor(document.page().cursor()),.link_reporter = ffi_hover_link_reporter(document),diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex b717ff7a2ab..3f414867f90 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -7100,7 +7100,6 @@ Compositor::SealedPresentation LocalNavigable::seal_presentation(DOM::Document&if (records_display_list)visual_context_tree = paint_state.visual_context_tree(document);paint_state.did_update_visual_context_tree_in_compositor();- Compositing::ScrollStateSnapshot scroll_state_snapshot { paint_state.scroll_state_snapshot() };// A keyboard scroll reads the layout, which one the host knows is stale leaves to the next frame that lays it out.Optional<Compositing::KeyboardScrollState> keyboard_scroll_state;if (is_top_level_traversable() && !document.layout_is_known_stale())@@ -7110,7 +7109,6 @@ Compositor::SealedPresentation LocalNavigable::seal_presentation(DOM::Document&.visual_context_tree = move(visual_context_tree),.sends_visual_context_tree = sends_visual_context_tree,.scroll_state_changed = paint_state.take_scroll_state_change(),- .scroll_state_snapshot = move(scroll_state_snapshot),.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(),diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.hindex efe6a0718fe..f394365ef01 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.h+++ b/Libraries/LibWeb/HTML/LocalNavigable.h@@ -18,7 +18,6 @@#include <AK/Utf16View.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Scrolling/SmoothScrollAnimation.h>#include <LibCore/Forward.h>#include <LibCore/StatsLog.h>diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 8b4e0adbd11..4fd6459f061 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -1716,7 +1716,8 @@ GC::Ref<JS::Object> Internals::recorded_display_list_wheel_target_at(double x, dreturn first_wheel_step_route_to_object({ .route = { InputRoutingDecision::NoAsyncScrollingState }, .document_id = {} });auto visual_context_tree = document.paint_state().visual_context_tree_without_update(read, document);auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));- return first_wheel_step_route_to_object(Compositing::route_first_wheel_step_through_recorded_display_list(*display_list, visual_context_tree, document.scroll_state_snapshot(), document.wheel_event_listener_state_generation(), position, { static_cast<float>(delta_x), static_cast<float>(delta_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, visual_context_tree, encoded_scroll_state, document.wheel_event_listener_state_generation(), position, { static_cast<float>(delta_x), static_cast<float>(delta_y) }));}bool Internals::recorded_display_list_blocks_wheel_event_at(double x, double y)@@ -1729,7 +1730,8 @@ bool Internals::recorded_display_list_blocks_wheel_event_at(double x, double y)return false;auto visual_context_tree = document.paint_state().visual_context_tree_without_update(read, document);auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));- return Compositing::recorded_display_list_blocks_wheel_event_at(*display_list, visual_context_tree, document.scroll_state_snapshot(), position);+ auto encoded_scroll_state = document.paint_state().encoded_scroll_state();+ return Compositing::recorded_display_list_blocks_wheel_event_at(*display_list, visual_context_tree, encoded_scroll_state, position);}void Internals::record_display_list_for_testing(bool paint_overlay, bool cold)diff --git a/Libraries/LibWeb/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cppindex db86be10a86..abbd020f843 100644--- a/Libraries/LibWeb/Painting/BoxViews.cpp+++ b/Libraries/LibWeb/Painting/BoxViews.cpp@@ -498,7 +498,8 @@ Layout::RustFFI::FfiViewportMapping viewport_mapping(DOM::Document const& docume{if (!document.has_committed_viewport_box())return {};- // NB: The scroll state's world transforms retain the tree they were built from.+ // NB: The document's tree outlives the handle made here: the render state holds it, and so does the scroll state,+ // whose world transforms retain the tree they were built from.return viewport_mapping(document, document.visual_context_tree());}@@ -506,15 +507,7 @@ Layout::RustFFI::FfiViewportMapping viewport_mapping(DOM::Document const& docume{if (!document.has_committed_viewport_box())return {};- auto const& scroll_state = document.scroll_state_snapshot();- auto scroll_offsets = scroll_state.device_offsets();- return {- .visual_context_tree = visual_context_tree.rust_handle(),- .world_transforms = scroll_state.world_transforms(visual_context_tree),- .scroll_offsets = scroll_offsets.data(),- .scroll_offsets_len = scroll_offsets.size(),- .device_pixels_per_css_pixel = static_cast<float>(document.page().client().device_pixels_per_css_pixel()),- };+ return document.paint_state().viewport_mapping(visual_context_tree, document.page().client().device_pixels_per_css_pixel());}// NB: Taking the document's visual context tree brings it up to date, which can compact it and move a box's visual@@ -562,7 +555,7 @@ CSSPixelPoint presented_scroll_offset(Layout::Node const& node, CSSPixelPoint scif (!has_committed_box(node) || !document.has_committed_viewport_box())return scroll_offset;auto visual_context_tree = document.visual_context_tree();- if (!visual_context_tree.translations_snap_to_device_pixels(accumulated_visual_context(node).spatial, document.scroll_state_snapshot()))+ if (!visual_context_tree.translations_snap_to_device_pixels(accumulated_visual_context(node).spatial))return scroll_offset;auto pixel_ratio = document.page().client().device_pixels_per_css_pixel();auto snap = [&](CSSPixels value) { return CSSPixels::nearest_value_for(round(value.to_double() * pixel_ratio) / pixel_ratio); };diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.cpp b/Libraries/LibWeb/Painting/DocumentPaintState.cppindex cb3121f5cac..856d49ecd22 100644--- a/Libraries/LibWeb/Painting/DocumentPaintState.cpp+++ b/Libraries/LibWeb/Painting/DocumentPaintState.cpp@@ -26,6 +26,8 @@ namespace Web::Painting {DocumentPaintState::DocumentPaintState(Layout::NodeArena& layout_node_arena): m_layout_node_arena(layout_node_arena){+ // The render state keeps the scroll state, and outlives the layout tree this paint state is for.+ Layout::RustFFI::render_state_forget_scroll_state(m_layout_node_arena->host());}void DocumentPaintState::ensure_visual_context_tree(DOM::Document const& document) const@@ -76,7 +78,7 @@ BlockingWheelEventRegionState DocumentPaintState::collect_root_blocking_wheel_evvoid DocumentPaintState::viewport_row_was_reset(){- m_scroll_state_snapshot = {};+ Layout::RustFFI::render_state_forget_scroll_state(m_layout_node_arena->host());m_boxes_with_auto_content_visibility.clear();m_visual_context_tree_needs_compositor_update = false;}@@ -139,16 +141,24 @@ void DocumentPaintState::append_paint_command_cache_source_resources(Compositingvoid DocumentPaintState::refresh_scroll_state(Layout::BegunRead const& read, DOM::Document& document){- // The render state hands over a new snapshot only where something invalidated the one kept.- Layout::RustFFI::render_state_refresh_scroll_state(- m_layout_node_arena->host(), &read, document.page().client().device_pixels_per_css_pixel(),- this, [](void* sink, Gfx::FloatPoint const* offsets, size_t count) {- auto& paint_state = *static_cast<DocumentPaintState*>(sink);- ReadonlySpan<Gfx::FloatPoint> device_offsets { offsets, count };- if (paint_state.m_scroll_state_snapshot.device_offsets() != device_offsets)- paint_state.m_scroll_state_changed = true;- paint_state.m_scroll_state_snapshot.assign_device_offsets(device_offsets);- });+ if (Layout::RustFFI::render_state_refresh_scroll_state(m_layout_node_arena->host(), &read, document.page().client().device_pixels_per_css_pixel()))+ m_scroll_state_changed = true;+}++Layout::RustFFI::FfiViewportMapping DocumentPaintState::viewport_mapping(Compositing::AccumulatedVisualContextTree const& visual_context_tree, double device_pixels_per_css_pixel) const+{+ Layout::RustFFI::FfiViewportMapping mapping {};+ Layout::RustFFI::render_state_viewport_mapping(m_layout_node_arena->host(), visual_context_tree.rust_handle(), static_cast<float>(device_pixels_per_css_pixel), &mapping);+ return mapping;+}++ByteBuffer DocumentPaintState::encoded_scroll_state() const+{+ ByteBuffer bytes;+ Layout::RustFFI::render_state_encode_scroll_state(m_layout_node_arena->host(), &bytes, [](void* sink, u8 const* data, size_t size) {+ MUST(static_cast<ByteBuffer*>(sink)->try_append(data, size));+ });+ return bytes;}void DocumentPaintState::reset_selection_states(Layout::BegunRead const& read, DOM::Document& document)diff --git a/Libraries/LibWeb/Painting/DocumentPaintState.h b/Libraries/LibWeb/Painting/DocumentPaintState.hindex 5e8c8808e63..7a370cf9cc1 100644--- a/Libraries/LibWeb/Painting/DocumentPaintState.h+++ b/Libraries/LibWeb/Painting/DocumentPaintState.h@@ -6,15 +6,16 @@#pragma once+#include <AK/ByteBuffer.h>#include <AK/Optional.h>#include <AK/RefPtr.h>#include <AK/Vector.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibGC/Ptr.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>+#include <LibWeb/Layout/LayoutRustFFI.h>#include <LibWeb/Layout/NodeArena.h>namespace Web::Painting {@@ -37,6 +38,10 @@ public:// Called from Document::update_paint_and_hit_testing_properties_if_needed() once the visual// context tree is settled; every other consumer reaches the scroll state through that update.void refresh_scroll_state(Layout::BegunRead const& read, DOM::Document&);+ // The mapping reads the tree and the scroll state where it is used, so the tree has to outlive it.+ Layout::RustFFI::FfiViewportMapping viewport_mapping(Compositing::AccumulatedVisualContextTree const&, double device_pixels_per_css_pixel) const;+ // Only the scroll logic of the compositor, which is Rust, decodes it.+ ByteBuffer encoded_scroll_state() const;void did_update_visual_context_values() { m_visual_context_tree_needs_compositor_update = true; }void update_accumulated_visual_contexts(Layout::BegunRead const& read, DOM::Document&);@@ -69,8 +74,6 @@ public:void recompute_custom_highlight_states(Layout::BegunRead const& read, DOM::Document&, CSS::HighlightRegistry&);void reset_custom_highlight_states();- Compositing::ScrollStateSnapshot const& scroll_state_snapshot() const { return m_scroll_state_snapshot; }-void set_boxes_with_auto_content_visibility(Vector<Compositing::RustFFI::NodeSlotId> boxes) { m_boxes_with_auto_content_visibility = move(boxes); }Vector<Compositing::RustFFI::NodeSlotId> const& boxes_with_auto_content_visibility() const { return m_boxes_with_auto_content_visibility; }@@ -95,8 +98,6 @@ private:NonnullRefPtr<Layout::NodeArena> m_layout_node_arena;- Compositing::ScrollStateSnapshot m_scroll_state_snapshot;-Vector<Compositing::RustFFI::NodeSlotId> m_boxes_with_auto_content_visibility;RefPtr<Compositing::DisplayList> m_display_list_used_as_paint_command_cache_source;diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp b/Libraries/LibWeb/Painting/HitTestDisplayList.cppindex ad2c3bf0093..d06b63b1141 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.cpp@@ -61,27 +61,15 @@ HitTestDisplayList::Item HitTestDisplayList::item(Layout::BegunRead const& read,return { index, facts };}-struct HitTestDisplayList::QueryContext {- HitTestQuery const* query { nullptr };-- Layout::RustFFI::FfiHitTestQueryCallbacks callbacks()- {- auto scroll_offsets = query ? query->scroll_state().device_offsets() : ReadonlySpan<Gfx::FloatPoint> {};- Layout::RustFFI::FfiHitTestQueryCallbacks callbacks {- .device_pixels_per_css_pixel = query ? query->device_pixels_per_css_pixel() : 1,- .scroll_offsets = scroll_offsets.data(),- .scroll_offsets_len = scroll_offsets.size(),- .world_transforms = nullptr,- .has_chrome_metrics = query != nullptr,- .chrome_metrics = {},- .has_visual_animation_sample_time = query && query->visual_animation_sample_time_nanoseconds().has_value(),- .visual_animation_sample_time_ns = query ? query->visual_animation_sample_time_nanoseconds().value_or(0) : 0,- };- if (query)- callbacks.chrome_metrics = query->chrome_metrics();- return callbacks;- }-};+static Layout::RustFFI::FfiHitTestQuery ffi_query(HitTestQuery const& query)+{+ return {+ .device_pixels_per_css_pixel = query.device_pixels_per_css_pixel(),+ .chrome_metrics = query.chrome_metrics(),+ .has_visual_animation_sample_time = query.visual_animation_sample_time_nanoseconds().has_value(),+ .visual_animation_sample_time_ns = query.visual_animation_sample_time_nanoseconds().value_or(0),+ };+}Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::topmost_item_from(Layout::RustFFI::FfiTopmostItem const& item){@@ -92,17 +80,15 @@ Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::topmost_item_from(Optional<HitTestDisplayList::TopmostItem> HitTestDisplayList::find_topmost_item(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query) const{- QueryContext context { &query };Layout::RustFFI::FfiTopmostItem item;- Layout::RustFFI::layout_hit_test_find_topmost_item(m_arena->host(), &read, context.callbacks(), point, &item);+ Layout::RustFFI::layout_hit_test_find_topmost_item(m_arena->host(), &read, ffi_query(query), point, &item);return topmost_item_from(item);}Vector<HitTestDisplayList::TopmostItem> HitTestDisplayList::hit_items_topmost_first(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query) const{- QueryContext context { &query };Vector<TopmostItem> hits;- Layout::RustFFI::layout_hit_test_all(m_arena->host(), &read, context.callbacks(), point, &hits, [](void* sink, size_t index, CSSPixelPoint local_point) {+ Layout::RustFFI::layout_hit_test_all(m_arena->host(), &read, ffi_query(query), point, &hits, [](void* sink, size_t index, CSSPixelPoint local_point) {static_cast<Vector<TopmostItem>*>(sink)->append({ index, local_point });});return hits;@@ -243,11 +229,10 @@ Optional<CaretPosition> HitTestDisplayList::caret_position_from(Layout::RustFFI:Optional<CaretPosition> HitTestDisplayList::caret_position_from_point(Layout::BegunRead const& read, CSSPixelPoint point, HitTestQuery const& query, GC::Ptr<DOM::Node const> constraint_scope) const{- QueryContext context { &query };auto const* scope_layout_node = constraint_scope ? constraint_scope->unsafe_layout_node(read) : nullptr;auto scope = scope_layout_node ? Layout::Node::slot_id(scope_layout_node) : Compositing::RustFFI::NodeSlotId { Compositing::RustFFI::INVALID_NODE_SLOT_INDEX };Layout::RustFFI::FfiCaretAt caret_at;- Layout::RustFFI::layout_hit_test_caret_position_from_point(m_arena->host(), &read, context.callbacks(), point, scope, &caret_at);+ Layout::RustFFI::layout_hit_test_caret_position_from_point(m_arena->host(), &read, ffi_query(query), point, scope, &caret_at);return caret_position_from(caret_at);}diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.h b/Libraries/LibWeb/Painting/HitTestDisplayList.hindex d0b1344268d..33c7b6af444 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.h+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.h@@ -23,14 +23,13 @@ namespace Web::Painting {class HitTestDisplayList;-// A query of a document's hit test list, with what it reads besides the list: the scroll state its points and rects-// convert through, and the time it samples the compositor's animations at. Only the document makes one, once it has-// prepared its paint properties and found the list current against the visual context tree, so every item a query-// looks at reads the same preparation, and nothing in a query prepares the document again.+// A query of a document's hit test list, with what it reads besides the list and the document's scroll state, such as+// the time it samples the compositor's animations at. Only the document makes one, once it has prepared its paint+// properties and found the list current against the visual context tree, so every item a query looks at reads the same+// preparation, and nothing in a query prepares the document again.class HitTestQuery {public:HitTestDisplayList const& list() const { return m_list; }- Compositing::ScrollStateSnapshot const& scroll_state() const { return m_scroll_state; }double device_pixels_per_css_pixel() const { return m_device_pixels_per_css_pixel; }ChromeMetrics const& chrome_metrics() const { return m_chrome_metrics; }// The time the query reads the compositor's animations at, as a frame of the compositor's shows them, if any.@@ -39,9 +38,8 @@ public:private:friend class DOM::Document;- HitTestQuery(HitTestDisplayList const& list, Compositing::ScrollStateSnapshot const& scroll_state, double device_pixels_per_css_pixel, ChromeMetrics chrome_metrics, Optional<i64> visual_animation_sample_time_nanoseconds)+ HitTestQuery(HitTestDisplayList const& list, double device_pixels_per_css_pixel, ChromeMetrics chrome_metrics, Optional<i64> visual_animation_sample_time_nanoseconds): m_list(list)- , m_scroll_state(scroll_state), m_device_pixels_per_css_pixel(device_pixels_per_css_pixel), m_chrome_metrics(chrome_metrics), m_visual_animation_sample_time_nanoseconds(visual_animation_sample_time_nanoseconds)@@ -49,7 +47,6 @@ private:}HitTestDisplayList const& m_list;- Compositing::ScrollStateSnapshot const& m_scroll_state;double m_device_pixels_per_css_pixel { 1 };ChromeMetrics m_chrome_metrics;Optional<i64> m_visual_animation_sample_time_nanoseconds;@@ -86,7 +83,6 @@ private:CSSPixelPoint local_point;};- struct QueryContext;static Optional<TopmostItem> topmost_item_from(Layout::RustFFI::FfiTopmostItem const&);[[nodiscard]] Item item(Layout::BegunRead const& read, size_t index) const;diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rsindex 00a9a9f5d6a..f3453492164 100644--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs@@ -48,6 +48,7 @@ pub unsafe extern "C" fn layout_script_client_rects(context: *mut c_void,push_rect: unsafe extern "C" fn(*mut c_void, FfiCssPixelRect),) {+ let viewport_mapping = viewport_mapping.resolve();read_rows(host, |arena| {crate::painting::client_rects::for_each_client_rect(arena, layout_node, &viewport_mapping.mapping(), |rect| {// SAFETY: The consumer copies the plain-data rect synchronously.@@ -63,6 +64,7 @@ pub extern "C" fn layout_script_bounding_client_rect(viewport_mapping: FfiViewportMapping<'_>,out: &mut FfiCssPixelRect,) {+ let viewport_mapping = viewport_mapping.resolve();*out = read_rows(host, |arena| {crate::painting::client_rects::bounding_client_rect(arena, layout_node, &viewport_mapping.mapping()).into()});@@ -75,6 +77,7 @@ pub extern "C" fn layout_script_transform_subtree_is_clipped_outside(root_bounds: FfiCssPixelRect,viewport_mapping: FfiViewportMapping<'_>,) -> bool {+ let viewport_mapping = viewport_mapping.resolve();read_rows(host, |arena| {crate::painting::intersection_observer::transform_subtree_is_clipped_outside(arena,@@ -103,6 +106,7 @@ pub unsafe extern "C" fn layout_script_intersection_observer_intersection_rect() -> FfiCssPixelRect,out: &mut FfiCssPixelRect,) {+ let viewport_mapping = viewport_mapping.resolve();*out = read_rows(host, |arena| {crate::painting::intersection_observer::intersection_rect(arena,@@ -151,6 +155,7 @@ pub unsafe extern "C" fn layout_script_text_range_rects(context: *mut c_void,push_rect: unsafe extern "C" fn(*mut c_void, FfiCssPixelRect),) {+ let viewport_mapping = viewport_mapping.resolve();read_rows(host, |arena| {let paintable_rows = arena;let viewport_mapping = viewport_mapping.mapping();@@ -368,6 +373,7 @@ pub extern "C" fn layout_script_caret(viewport_mapping: FfiViewportMapping<'_>,out: &mut FfiCaret,) {+ let viewport_mapping = viewport_mapping.resolve();*out = read_rows(host, |arena| {let cursor = InlineCursor::new(arena);let Some(caret) = position@@ -469,6 +475,7 @@ pub extern "C" fn layout_script_accumulated_sticky_offset(viewport_mapping: FfiViewportMapping<'_>,out: &mut FfiCssPixelPoint,) {+ let viewport_mapping = viewport_mapping.resolve();*out = read_rows(host, |arena| viewport_mapping.mapping().sticky_offset(arena, slot)).into();}@@ -480,6 +487,7 @@ pub extern "C" fn layout_script_offset_to_viewport_ignoring_transforms(viewport_mapping: FfiViewportMapping<'_>,out: &mut FfiCssPixelPoint,) {+ let viewport_mapping = viewport_mapping.resolve();*out = read_rows(host, |arena| {viewport_mapping.mapping()diff --git a/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rsindex 50bff196075..471ada17993 100644--- a/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rs@@ -101,7 +101,9 @@ pub unsafe extern "C" fn render_state_seal_clock_plan(.collect();// SAFETY: Guaranteed by the caller.let mut hover = unsafe { hover.as_ref() }.map(|inputs| {- unsafe { crate::render_state::HoverPlan::from_ffi(inputs) }.with_style_inputs(host.style_inputs())+ let scroll_offsets = host.scroll_state().device_offsets().to_vec();+ unsafe { crate::render_state::HoverPlan::from_ffi(inputs, scroll_offsets) }+ .with_style_inputs(host.style_inputs())});let round = seal_clock_round(&main_thread, host, read);if elements.is_empty()diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex 0605b888e15..eff6abadd60 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -377,12 +377,16 @@ pub(super) fn apply_walk_assignments(}}-/// The index of the sticky node the accumulated visual context tree holds for `paintable`, which-/// is where the scroll state snapshot keeps its resolved sticky offset, or `u32::MAX` when the tree-/// holds none.+/// How far sticky positioning moved `paintable` from its normal position, in device pixels, as the scroll state of+/// `host`'s document resolved it. Answers false when the accumulated visual context tree holds no sticky node for+/// `paintable`.#[unsafe(no_mangle)]-pub extern "C" fn render_state_sticky_spatial_node_index(host: &DocumentHost, paintable: NodeSlotId) -> u32 {- read_arena(host, node_read(), paintable, |arena, paintable| {+pub extern "C" fn render_state_sticky_device_offset(+ host: &DocumentHost,+ paintable: NodeSlotId,+ out: &mut libgfx_rust::FloatPoint,+) -> bool {+ let sticky_node_index = read_arena(host, node_read(), paintable, |arena, paintable| {let paint_state = arena.paint_state();paint_state.visual_context@@ -390,8 +394,13 @@ pub extern "C" fn render_state_sticky_spatial_node_index(host: &DocumentHost, pa.states().iter().find(|state| state.is_sticky && state.paintable == paintable)- .map_or(u32::MAX, |state| state.node_index.0)- })+ .map(|state| state.node_index)+ });+ let Some(sticky_node_index) = sticky_node_index else {+ return false;+ };+ *out = host.scroll_state().device_offset_for_index(sticky_node_index);+ true}/// Marks the entry the event loop calls between two tasks to take a finished recording in.@@ -729,6 +738,7 @@ pub extern "C" fn render_state_visible_rect_in_containing_blocks(space: crate::painting::viewport_mapping::ViewportSpace,out: &mut FfiCssPixelRect,) {+ let viewport_mapping = viewport_mapping.resolve();let viewport_mapping = viewport_mapping.mapping();*out = host.read_rows(node_read(), false, |rows| {let visible =diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex 80bb741b0ee..ff902144953 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -482,28 +482,40 @@ pub unsafe extern "C" fn render_state_sync_svg_paint_resources(}/// Re-reads the scroll containers' offsets when something invalidated them since the last refresh, resolves the-/// sticky nodes' offsets on top of them, and hands the dense device-pixel snapshot to `publish`; otherwise the caller-/// keeps its copy.+/// sticky nodes' offsets on top of them, and has `host` keep them as its document's scroll state; otherwise the host+/// keeps the one it has. Answers whether the offsets changed.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_refresh_scroll_state(+ host: &crate::render_state::DocumentHost,+ read: &crate::render_state::BegunRead,+ device_pixels_per_css_pixel: f64,+) -> bool {+ let device_offsets = run_paint_pass(read, host, PassEffect::RewritesRows, |arena| {+ crate::painting::paint_passes::refresh_scroll_state(arena, device_pixels_per_css_pixel)+ });+ device_offsets.is_some_and(|device_offsets| host.refresh_scroll_state(device_offsets))+}++/// Has `host` forget its document's scroll state, as the viewport's row or the document's paint state starts over.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_forget_scroll_state(host: &crate::render_state::DocumentHost) {+ host.forget_scroll_state();+}++/// Hands `append` the scroll state of `host`'s document as the scroll logic of the compositor reads it.////// # Safety///-/// `host` must be a live document host, on its document's thread; `publish` is called synchronously with `sink` and a-/// view of the snapshot that is valid only for the duration of that call.+/// `append` is called synchronously with `sink`, and must copy the bytes it keeps.#[unsafe(no_mangle)]-pub unsafe extern "C" fn render_state_refresh_scroll_state(+pub unsafe extern "C" fn render_state_encode_scroll_state(host: &crate::render_state::DocumentHost,- read: &crate::render_state::BegunRead,- device_pixels_per_css_pixel: f64,sink: *mut c_void,- publish: unsafe extern "C" fn(*mut c_void, *const libgfx_rust::FloatPoint, usize),+ append: unsafe extern "C" fn(*mut c_void, *const u8, usize),) {- let snapshot = run_paint_pass(read, host, PassEffect::RewritesRows, |arena| {- crate::painting::paint_passes::refresh_scroll_state(arena, device_pixels_per_css_pixel)- });- if let Some(snapshot) = snapshot {- // SAFETY: The C++ sink copies the offsets synchronously.- unsafe { publish(sink, snapshot.as_ptr(), snapshot.len()) };- }+ let bytes = host.scroll_state().to_encoded_bytes();+ // SAFETY: The C++ sink copies the bytes synchronously.+ unsafe { append(sink, bytes.as_ptr(), bytes.len()) };}/// # Safety@@ -659,7 +671,7 @@ unsafe fn commit_frame(content,recorder,// SAFETY: Guaranteed by the caller.- presentation: unsafe { crate::painting::presentation::Presentation::adopt(presentation) }+ presentation: unsafe { crate::painting::presentation::Presentation::adopt(presentation, &host.scroll_state()) }.expect("a committed frame is presented"),timestamp,held_for_testing,@@ -1053,10 +1065,13 @@ pub extern "C" fn layout_hit_test_resolve_hit(pub unsafe extern "C" fn layout_hit_test_find_topmost_item(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,- callbacks: crate::painting::host::FfiHitTestQueryCallbacks,+ query: crate::painting::host::FfiHitTestQuery,point: FfiCssPixelPoint,out: &mut crate::painting::host::FfiTopmostItem,) {+ let scroll_state = host.scroll_state();+ let callbacks =+ crate::painting::host::FfiHitTestQueryCallbacks::for_host_query(&query, scroll_state.device_offsets());*out = with_hit_test_list_spatial_indexes_and_visual_context_tree(host,read,@@ -1077,11 +1092,14 @@ pub unsafe extern "C" fn layout_hit_test_find_topmost_item(pub unsafe extern "C" fn layout_hit_test_all(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,- callbacks: crate::painting::host::FfiHitTestQueryCallbacks,+ query: crate::painting::host::FfiHitTestQuery,point: FfiCssPixelPoint,push_context: *mut c_void,push: unsafe extern "C" fn(*mut c_void, usize, FfiCssPixelPoint),) {+ let scroll_state = host.scroll_state();+ let callbacks =+ crate::painting::host::FfiHitTestQueryCallbacks::for_host_query(&query, scroll_state.device_offsets());let hits =with_hit_test_list_spatial_indexes_and_visual_context_tree(host, read, Vec::new(), |list, tree, arena| {let mut sampled = None;@@ -1104,11 +1122,14 @@ pub unsafe extern "C" fn layout_hit_test_all(pub unsafe extern "C" fn layout_hit_test_caret_position_from_point(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,- callbacks: crate::painting::host::FfiHitTestQueryCallbacks,+ query: crate::painting::host::FfiHitTestQuery,point: FfiCssPixelPoint,constraint_scope: NodeSlotId,out: &mut FfiCaretAt,) {+ let scroll_state = host.scroll_state();+ let callbacks =+ crate::painting::host::FfiHitTestQueryCallbacks::for_host_query(&query, scroll_state.device_offsets());*out = with_hit_test_list_spatial_indexes_and_visual_context_tree(host, read, None, |list, tree, arena| {let world = callbacks.build_world_transforms(tree);list.caret_position_from_point(diff --git a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rsindex 51e4a47bf4c..cb0e6f2a11d 100644--- a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs@@ -9,13 +9,27 @@ use crate::layout::used_values;use crate::painting::display_list::commands::ContextRef;use std::ffi::c_void;+/// What the host gives a query of its document's hit test list. The query finds the document scrolled where the scroll+/// state the host keeps has it.#[derive(Clone, Copy)]#[repr(C)]+pub struct FfiHitTestQuery {+ pub device_pixels_per_css_pixel: f64,+ pub chrome_metrics: crate::painting::ffi::FfiChromeMetrics,+ /// Where set, the query reads the compositor's animations at this time, as a frame of the compositor's shows them.+ pub has_visual_animation_sample_time: bool,+ pub visual_animation_sample_time_ns: i64,+}++/// What a query of a hit test list reads besides the list, as an entry point put it together.+#[derive(Clone, Copy)]pub struct FfiHitTestQueryCallbacks {pub device_pixels_per_css_pixel: f64,- pub scroll_offsets: *const libgfx_rust::FloatPoint,- pub scroll_offsets_len: usize,- /// Private: the world transforms a Rust entry point builds for the query, from the tree it reads and the offsets.+ /// Where the query finds the document scrolled to: the scroll state the host keeps, or the offsets a clock lane+ /// sealed.+ scroll_offsets: *const libgfx_rust::FloatPoint,+ scroll_offsets_len: usize,+ /// The world transforms an entry point builds for the query, from the tree it reads and the offsets.world_transforms: *const c_void,pub has_chrome_metrics: bool,pub chrome_metrics: crate::painting::ffi::FfiChromeMetrics,@@ -44,6 +58,21 @@ impl FfiHitTestQueryCallbacks {}}+ /// Callbacks for `query`, a query of the host's, which finds the document scrolled to `scroll_offsets`. The entry+ /// point keeps the offsets for the query.+ pub(crate) fn for_host_query(query: &FfiHitTestQuery, scroll_offsets: &[libgfx_rust::FloatPoint]) -> Self {+ Self {+ device_pixels_per_css_pixel: query.device_pixels_per_css_pixel,+ scroll_offsets: scroll_offsets.as_ptr(),+ scroll_offsets_len: scroll_offsets.len(),+ world_transforms: std::ptr::null(),+ has_chrome_metrics: true,+ chrome_metrics: query.chrome_metrics,+ has_visual_animation_sample_time: query.has_visual_animation_sample_time,+ visual_animation_sample_time_ns: query.visual_animation_sample_time_ns,+ }+ }+pub(crate) fn visual_animation_sample_time_ns(&self) -> Option<i64> {self.has_visual_animation_sample_time.then_some(self.visual_animation_sample_time_ns)@@ -83,14 +112,18 @@ impl FfiHitTestQueryCallbacks {"the query's entry point builds its world transforms");// SAFETY: The entry point keeps the table alive for the synchronous query.- unsafe { libcompositing_rust::ffi::world_transforms_from_handle(self.world_transforms) }+ unsafe {+ &*self+ .world_transforms+ .cast::<crate::painting::visual_context::WorldTransforms>()+ }}pub(crate) fn scroll_offsets(&self) -> &[libgfx_rust::FloatPoint] {if self.scroll_offsets.is_null() {return &[];}- // SAFETY: QueryContext keeps the document and its resolved scroll snapshot alive for the synchronous query.+ // SAFETY: The entry point keeps the offsets alive for the synchronous query.unsafe { ak::slice_from_raw_parts(self.scroll_offsets, self.scroll_offsets_len) }}}diff --git a/Libraries/LibWeb/Rust/src/painting/presentation.rs b/Libraries/LibWeb/Rust/src/painting/presentation.rsindex 0ef08f0b12e..4443d33529a 100644--- a/Libraries/LibWeb/Rust/src/painting/presentation.rs+++ b/Libraries/LibWeb/Rust/src/painting/presentation.rs@@ -16,7 +16,7 @@ use crate::painting::ffi::{FfiPresentation, FfiPresentedRecording};use crate::painting::paint_passes::ClockTickVisualContexts;use crate::painting::record::publish::RecordingResourceSink;use crate::painting::visual_context::VisualContextTree;-use libgfx_rust::FloatPoint;+use libcompositing_rust::scrolling::ScrollStateSnapshot;use std::ffi::c_void;use std::ptr::NonNull;use std::sync::Arc;@@ -28,8 +28,7 @@ unsafe extern "C" {fn web_sealed_presentation_take_visual_context_tree(sealed: *mut c_void,tree: *const c_void,- scroll_offsets: *const FloatPoint,- scroll_offset_count: usize,+ 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);@@ -38,9 +37,17 @@ unsafe extern "C" {presenter: *mut c_void,sealed: *mut c_void,presented: *const FfiPresentedRecording,+ 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,+ 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, 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,@@ -135,17 +142,22 @@ impl PresenterBox {pub(crate) struct Presentation {pub(crate) presenter: PresenterBox,sealed: SealedPresentationBox,+ /// 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>,}impl Presentation {- /// Takes over the presenter and the seal `ffi` names, which the host gives up, or none where it names none.+ /// 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.////// # Safety/// `ffi` must name a presenter and a seal the host made and gives up, or neither.- pub(crate) unsafe fn adopt(ffi: FfiPresentation) -> Option<Self> {+ 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)?),+ encoded_scroll_state: scroll_state.to_encoded_bytes(),})}@@ -160,15 +172,20 @@ impl Presentation {Some(Self {presenter: PresenterBox(self.presenter.0),sealed: SealedPresentationBox(sealed),+ encoded_scroll_state: self.encoded_scroll_state.clone(),})}/// Gives the presenter and the seal back to the host, which takes them over.pub(crate) fn into_ffi(self) -> FfiPresentation {- let this = std::mem::ManuallyDrop::new(self);+ let Self { presenter, sealed, .. } = self;+ let (presenter, sealed) = (+ std::mem::ManuallyDrop::new(presenter),+ std::mem::ManuallyDrop::new(sealed),+ );FfiPresentation {- presenter: this.presenter.0.as_ptr(),- sealed: this.sealed.0.as_ptr(),+ presenter: presenter.0.as_ptr(),+ sealed: sealed.0.as_ptr(),}}@@ -179,14 +196,17 @@ impl Presentation {tree,restructured_scroll_offsets,} = visual_contexts;- let offsets = restructured_scroll_offsets.as_deref();- // SAFETY: The presentation owns the seal, which takes over the reference and copies the offsets.+ // A tree of another structure takes the scroll offsets of its own nodes.+ 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, which takes over the reference.unsafe {web_sealed_presentation_take_visual_context_tree(self.sealed.0.as_ptr(),Arc::into_raw(tree).cast(),- offsets.map_or(std::ptr::null(), <[FloatPoint]>::as_ptr),- offsets.map_or(0, <[FloatPoint]>::len),+ tree_is_restructured,);}}@@ -204,11 +224,14 @@ impl Presentation {restructured_scroll_offsets: None,});}- // SAFETY: The presentation owns both objects, and the stage holds the sink.+ // SAFETY: The presentation owns both objects, the presenter copies the scroll state, and the stage holds the+ // sink.unsafe {web_navigable_presenter_present_unrecorded(self.presenter.0.as_ptr(),self.sealed.0.as_ptr(),+ self.encoded_scroll_state.as_ptr(),+ self.encoded_scroll_state.len(),presenting.sink(),);}@@ -216,13 +239,15 @@ impl Presentation {/// Presents the sealed frame with the recording `presented` describes, whose resources the presenter took already.pub(crate) fn present(&mut self, presented: &FfiPresentedRecording, presenting: &mut Presenting) {- // SAFETY: The presentation owns both objects, the recording's display list is live for the call, and the stage- // holds the sink.+ // SAFETY: The presentation owns both objects, the recording's display list is live for the call, the presenter+ // copies the scroll state, and the stage holds the sink.unsafe {web_navigable_presenter_present(self.presenter.0.as_ptr(),self.sealed.0.as_ptr(),presented,+ self.encoded_scroll_state.as_ptr(),+ self.encoded_scroll_state.len(),presenting.sink(),);}@@ -246,13 +271,7 @@ mod ffi_test_stubs {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,- _: *const c_void,- _: *const libgfx_rust::FloatPoint,- _: usize,- ) {- }+ extern "C" fn web_sealed_presentation_take_visual_context_tree(_: *mut c_void, _: *const c_void, _: bool) {}#[unsafe(no_mangle)]extern "C" fn web_navigable_presenter_add_font(_: *mut c_void, _: *const c_void) {}@@ -268,12 +287,21 @@ mod ffi_test_stubs {_: *mut c_void,_: *mut c_void,_: *const FfiPresentedRecording,+ _: *const u8,+ _: usize,_: *mut c_void,) {}#[unsafe(no_mangle)]- extern "C" fn web_navigable_presenter_present_unrecorded(_: *mut c_void, _: *mut c_void, _: *mut c_void) {}+ extern "C" fn web_navigable_presenter_present_unrecorded(+ _: *mut c_void,+ _: *mut c_void,+ _: *const u8,+ _: usize,+ _: *mut c_void,+ ) {+ }#[unsafe(no_mangle)]extern "C" fn web_vector_image_resources_destroy(_: *mut c_void) {}diff --git a/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rs b/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rsindex 6f5a02ccc88..b3162c3b167 100644--- a/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rs+++ b/Libraries/LibWeb/Rust/src/painting/viewport_mapping.rs@@ -17,9 +17,13 @@ use crate::painting::visual_context::{VisualContextTree, WorldTransforms,};use crate::painting::visual_context::{basic_shapes, node_values};-use libcompositing_rust::ffi::{tree_from_handle, world_transforms_from_handle};-use libgfx_rust::{FloatPoint, FloatRect};+use crate::render_state::DocumentHost;+use libcompositing_rust::ffi::tree_sharing_handle;+use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, ScrollStateSnapshot};+use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect};use std::ffi::c_void;+use std::rc::Rc;+use std::sync::Arc;#[repr(u8)]#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -231,6 +235,15 @@ impl<'a> ViewportMapping<'a> {})}+ /// The matrix that takes the local space of `spatial` into the viewport, both in device pixels, or the identity for+ /// a document that has no visual context tree.+ pub(crate) fn matrix_to_viewport(&self, spatial: SpatialNodeIndex, space: ViewportSpace) -> FloatMatrix4x4 {+ match &self.transforms {+ Some(transforms) => transforms.world_transforms.to_viewport_matrix(spatial, space.into()),+ None => FloatMatrix4x4::identity(),+ }+ }+/// The offset by which sticky positioning moves `node`, as the sum of the offsets of the sticky positioned box and/// its sticky positioned ancestors.pub(crate) fn sticky_offset(&self, arena: &impl PaintRead, node: NodeSlotId) -> CssPixelPoint {@@ -276,36 +289,101 @@ impl<'a> ViewportMapping<'a> {}}-/// A [`ViewportMapping`] as C++ lends it for `'a`: a non-null `visual_context_tree` is a live retained tree handle with-/// `world_transforms` a live table built from it, and `scroll_offsets` addresses `scroll_offsets_len` points. A null-/// tree leaves geometry as it is. Rust never makes one.+/// A [`ViewportMapping`] as C++ carries it for `'a`, which only [`render_state_viewport_mapping`] makes: C++ hands it+/// back as it got it, or one it left zeroed, which leaves geometry as it is. `visual_context_tree` is a tree handle+/// that stays live for `'a`. Where the document is scrolled to, and the world transforms of the tree there, are read+/// from `host` where the mapping is used.#[repr(C)]pub struct FfiViewportMapping<'a> {+ host: Option<&'a DocumentHost>,visual_context_tree: *const c_void,- world_transforms: *const c_void,- scroll_offsets: *const FloatPoint,- scroll_offsets_len: usize,device_pixels_per_css_pixel: f32,- lent: std::marker::PhantomData<&'a [FloatPoint]>,}-impl<'a> FfiViewportMapping<'a> {- pub(crate) fn mapping(&self) -> ViewportMapping<'a> {- if self.visual_context_tree.is_null() {- return ViewportMapping::default();+impl FfiViewportMapping<'_> {+ /// What the mapping maps through as the host has it now, kept for as long as an entry point reads the mapping.+ pub(crate) fn resolve(&self) -> ResolvedViewportMapping {+ let Some(host) = self.host.filter(|_| !self.visual_context_tree.is_null()) else {+ return ResolvedViewportMapping { transforms: None };+ };+ // SAFETY: C++ keeps the tree live for as long as it carries the mapping.+ let tree = unsafe { tree_sharing_handle(self.visual_context_tree) };+ let scroll_state = host.scroll_state();+ let world_transforms = scroll_state.world_transforms(&tree);+ ResolvedViewportMapping {+ transforms: Some(ResolvedTransforms {+ tree,+ scroll_state,+ world_transforms,+ device_pixels_per_css_pixel: self.device_pixels_per_css_pixel,+ }),}- // SAFETY: C++ lends a live tree, its world transforms and the scroll offsets for 'a.- unsafe {- ViewportMapping::new(- tree_from_handle(self.visual_context_tree),- world_transforms_from_handle(self.world_transforms),- ak::slice_from_raw_parts(self.scroll_offsets, self.scroll_offsets_len),- self.device_pixels_per_css_pixel,- )+ }+}++struct ResolvedTransforms {+ tree: AccumulatedVisualContextTree,+ scroll_state: Rc<ScrollStateSnapshot>,+ world_transforms: Arc<WorldTransforms>,+ device_pixels_per_css_pixel: f32,+}++/// A mapping C++ carries, with a share of its own in everything it maps through: nothing another mapping or a refresh+/// of the host's scroll state does takes that away while an entry point reads it.+pub(crate) struct ResolvedViewportMapping {+ transforms: Option<ResolvedTransforms>,+}++impl ResolvedViewportMapping {+ pub(crate) fn mapping(&self) -> ViewportMapping<'_> {+ match &self.transforms {+ Some(transforms) => ViewportMapping::new(+ transforms.tree.as_arc(),+ &transforms.world_transforms,+ transforms.scroll_state.device_offsets(),+ transforms.device_pixels_per_css_pixel,+ ),+ None => ViewportMapping::default(),}}}+/// The mapping between the viewport of `host`'s document and the spaces of `visual_context_tree`, where the document's+/// boxes are scrolled to as the host has it when the mapping is used.+///+/// # Safety+///+/// `visual_context_tree` must be a live retained tree handle, which stays live for as long as C++ carries the mapping:+/// the caller keeps it, or it is the document's own, which the scroll state retains from here on, with the world+/// transforms it builds for it, until the host refreshes the scroll state or builds those of another tree.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_viewport_mapping<'a>(+ host: &'a DocumentHost,+ visual_context_tree: *const c_void,+ device_pixels_per_css_pixel: f32,+ out: &mut FfiViewportMapping<'a>,+) {+ // SAFETY: The caller lends a strong reference to the tree.+ let tree = unsafe { tree_sharing_handle(visual_context_tree) };+ host.scroll_state().world_transforms(&tree);+ *out = FfiViewportMapping {+ host: Some(host),+ visual_context_tree,+ device_pixels_per_css_pixel,+ };+}++/// The matrix that takes the local space of `spatial` into the viewport, both in device pixels.+#[unsafe(no_mangle)]+pub extern "C" fn viewport_mapping_matrix_to_viewport(+ mapping: FfiViewportMapping<'_>,+ spatial: SpatialNodeIndex,+ space: ViewportSpace,+ out: &mut FloatMatrix4x4,+) {+ *out = mapping.resolve().mapping().matrix_to_viewport(spatial, space);+}+#[unsafe(no_mangle)]pub extern "C" fn viewport_mapping_rect_in_space_to_viewport(mapping: FfiViewportMapping<'_>,@@ -315,6 +393,7 @@ pub extern "C" fn viewport_mapping_rect_in_space_to_viewport(out: &mut FfiCssPixelRect,) {*out = mapping+ .resolve().mapping().rect_in_space_to_viewport(spatial, rect.into(), space).into();@@ -331,6 +410,7 @@ pub extern "C" fn viewport_mapping_point_to_local(out: &mut FfiCssPixelPoint,) -> bool {let Some(local) = mapping+ .resolve().mapping().point_to_local(context, point.into(), space, ClipBehavior::Ignore)else {@@ -339,3 +419,71 @@ pub extern "C" fn viewport_mapping_point_to_local(*out = to_css_point(local).into();true}++#[cfg(test)]+mod tests {+ use super::*;+ use libcompositing_rust::node_slot_id::NodeSlotId;+ use libcompositing_rust::visual_context::scroll_state::NO_SCROLL_STATE_SLOT;+ use libcompositing_rust::visual_context::{ScrollData, SpatialData, TransformData, TransformDataRole};++ fn tree_with_scroller() -> (Arc<VisualContextTree>, SpatialNodeIndex) {+ let mut tree = VisualContextTree::create(TransformData {+ matrix: FloatMatrix4x4::identity(),+ origin: FloatPoint::default(),+ sorting_context_root_index: None,+ flattens_inherited_transform: false,+ role: TransformDataRole::CssTransform,+ synthetic_plane: false,+ establishes_sorting_context: false,+ bounds: FloatRect::default(),+ });+ let scroller = tree.append_spatial(+ SpatialData::Scroll(ScrollData {+ state_slot: NO_SCROLL_STATE_SLOT,+ owner_paintable: NodeSlotId::INVALID,+ }),+ VISUAL_VIEWPORT_NODE_INDEX,+ );+ (Arc::new(tree), scroller)+ }++ #[test]+ fn a_mapping_stands_after_a_mapping_over_another_tree_and_a_scroll_state_refresh() {+ let host = DocumentHost::for_test();+ let (tree, scroller) = tree_with_scroller();+ let (other_tree, _) = tree_with_scroller();+ let scrolled_to = |y: f32| vec![FloatPoint::default(), FloatPoint { x: 0.0, y }];+ let mapping_over = |tree: &Arc<VisualContextTree>| {+ let mut mapping = FfiViewportMapping {+ host: None,+ visual_context_tree: std::ptr::null(),+ device_pixels_per_css_pixel: 0.0,+ };+ // SAFETY: The test keeps the tree for as long as it uses the mapping.+ unsafe { render_state_viewport_mapping(&host, Arc::as_ptr(tree).cast(), 1.0, &mut mapping) };+ mapping+ };+ let ten = CssPixels::from_integer(10);+ let rect = CssPixelRect::new(CssPixels::default(), CssPixels::default(), ten, ten);+ let top_in_viewport = |mapping: &FfiViewportMapping<'_>| {+ mapping+ .resolve()+ .mapping()+ .rect_in_space_to_viewport(scroller, rect, ViewportSpace::LayoutViewport)+ .y+ };++ host.refresh_scroll_state(scrolled_to(-30.0));+ let mapping = mapping_over(&tree);+ assert_eq!(top_in_viewport(&mapping), CssPixels::from_integer(-30));++ // The scroll state keeps the world transforms of one tree, which are those of the other tree from here on.+ let other_mapping = mapping_over(&other_tree);+ assert_eq!(top_in_viewport(&other_mapping), CssPixels::from_integer(-30));+ assert_eq!(top_in_viewport(&mapping), CssPixels::from_integer(-30));++ host.refresh_scroll_state(scrolled_to(-50.0));+ assert_eq!(top_in_viewport(&mapping), CssPixels::from_integer(-50));+ }+}diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rsindex 3c4ec14b2fa..639ebc65442 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs@@ -34,9 +34,6 @@ use std::sync::Arc;#[repr(C)]pub struct FfiHoverPlanInputs {pub device_pixels_per_css_pixel: f64,- /// The scroll offsets of the frame the rendering update presented, in device pixels, by scroll frame.- pub scroll_offsets: *const libgfx_rust::FloatPoint,- pub scroll_offset_count: usize,pub chrome_metrics: FfiChromeMetrics,/// The cursor of the document's page, which the hover asks to show the cursor of what it hovers.pub page_cursor: FfiPageCursor,@@ -241,20 +238,15 @@ pub(crate) struct HoverPlan {}impl HoverPlan {- /// The plan `inputs` describes.+ /// The plan `inputs` describes, with `scroll_offsets`, the scroll offsets of the frame the rendering update+ /// presented, in device pixels, by scroll frame.////// # Safety///- /// `inputs.scroll_offsets` must point at `inputs.scroll_offset_count` offsets, or be null, the effect timing- /// arrays at `inputs.effect_timing_count` entries each, or be null, `inputs.page_cursor` must name a live page- /// cursor, or none, and `inputs.link_reporter` a live link reporter, or none.- pub(crate) unsafe fn from_ffi(inputs: &FfiHoverPlanInputs) -> Self {- let scroll_offsets = if inputs.scroll_offsets.is_null() {- Vec::new()- } else {- // SAFETY: Guaranteed by the caller.- unsafe { ak::slice_from_raw_parts(inputs.scroll_offsets, inputs.scroll_offset_count) }.to_vec()- };+ /// The effect timing arrays of `inputs` must point at `inputs.effect_timing_count` entries each, or be null,+ /// `inputs.page_cursor` must name a live page cursor, or none, and `inputs.link_reporter` a live link reporter, or+ /// none.+ pub(crate) unsafe fn from_ffi(inputs: &FfiHoverPlanInputs, scroll_offsets: Vec<FloatPoint>) -> Self {let effect_timings = if inputs.effect_timing_count == 0 {Vec::new()} else {diff --git a/Libraries/LibWeb/Rust/src/render_state/document_host.rs b/Libraries/LibWeb/Rust/src/render_state/document_host.rsindex ed6e46e7346..4c43a3885d3 100644--- a/Libraries/LibWeb/Rust/src/render_state/document_host.rs+++ b/Libraries/LibWeb/Rust/src/render_state/document_host.rs@@ -28,6 +28,7 @@ use crate::painting::recording_slot::{RecordingAnswer, RecordingSlot};use crate::painting::visual_animation::VisualAnimation;use crate::render_state::TaskBoundary;use crate::stage_thread::InFlight;+use libcompositing_rust::scrolling::ScrollStateSnapshot;use libgfx_rust::FloatPoint;use std::cell::{Cell, RefCell, RefMut};use std::rc::Rc;@@ -80,6 +81,9 @@ pub struct DocumentHost {/// The compositor animations the document's effects published in the current update pass, which the host hands/// the render state as the pass ends.compositor_animations: RefCell<Vec<VisualAnimation>>,+ /// Where the document's boxes are scrolled to, as the host refreshed it last: what its queries map through, and its+ /// frames take to the compositor. It is handed out by reference count, as the rows are.+ scroll_state: RefCell<Rc<ScrollStateSnapshot>>,/// 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.@@ -200,6 +204,7 @@ impl DocumentHost {fresh_transition_sample: Cell::default(),absolute_rects: RefCell::default(),compositor_animations: RefCell::default(),+ scroll_state: RefCell::default(),begun_read: BegunRead::of_host(),changes: ChangeQueue::default(),flown_style: RefCell::default(),@@ -1512,6 +1517,25 @@ impl DocumentHost {pub(crate) fn recording(&self) -> RefMut<'_, RecordingSlot> {self.recording.borrow_mut()}++ /// Where the document's boxes are scrolled to, as the host refreshed it last.+ pub(crate) fn scroll_state(&self) -> Rc<ScrollStateSnapshot> {+ self.scroll_state.borrow().clone()+ }++ /// Takes `device_offsets`, the offsets the render state refreshed, as the document's scroll state. Answers whether+ /// they differ from the ones the host had.+ pub(crate) fn refresh_scroll_state(&self, device_offsets: Vec<FloatPoint>) -> bool {+ let changed = self.scroll_state.borrow().device_offsets() != device_offsets.as_slice();+ self.scroll_state+ .replace(Rc::new(ScrollStateSnapshot::from_device_offsets(device_offsets)));+ changed+ }++ /// Forgets where the document's boxes were scrolled to: nothing is scrolled until the next refresh.+ pub(crate) fn forget_scroll_state(&self) {+ self.scroll_state.take();+ }}/// Creates the host of a new document.diff --git a/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp b/Libraries/LibWeb/SVG/SVGGraphicsElement.cppindex 3622deffa46..50dddeac092 100644--- a/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp+++ b/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp@@ -304,10 +304,8 @@ GC::Ptr<Geometry::DOMMatrix> SVGGraphicsElement::get_screen_ctm()auto visual_context = Painting::svg_viewport_transform(*layout_node).has_value()? Painting::accumulated_visual_context_for_descendants(*layout_node): Painting::accumulated_visual_context(*layout_node);- auto ctm = visual_context_tree.accumulated_matrix(- visual_context.spatial,- document().scroll_state_snapshot(),- Compositing::AccumulatedVisualContextTree::IncludeVisualViewportTransform::No);+ Gfx::FloatMatrix4x4 ctm;+ Layout::RustFFI::viewport_mapping_matrix_to_viewport(Painting::viewport_mapping(document(), visual_context_tree), visual_context.spatial, Layout::RustFFI::ViewportSpace::LayoutViewport, &ctm);// NB: Accumulated visual-context matrices operate in device-pixel space. Conjugate the matrix by the device scale// to expose CSS-pixel coordinates through the DOM API, then project any 3D transform onto the SVG plane.diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 546abe4fbe0..f7814403c21 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -12,6 +12,7 @@ set(SOURCESDisplayListPlayerSkia.cppDisplayListRasterCache.cppFontSkia.cpp+ FrameInputs.cppConnectionFromClient.cppConnectionFromPresentation.cppConnectionFromWebContent.cppdiff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cppindex b0c9fd74d66..f52c8c7126c 100644--- a/Services/Compositor/CompositorCore.cpp+++ b/Services/Compositor/CompositorCore.cpp@@ -123,10 +123,10 @@ void CompositorCore::set_scroll_capabilities(Web::CompositorContextId context_idRustFFI::compositor_core_set_scroll_capabilities(m_core, context_id.value(), capabilities);}-bool CompositorCore::install_display_list_update(Web::CompositorContextId context_id, Compositing::DisplayList const& display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree const& visual_context_tree, IPC::Encoded<Compositing::ScrollStateSnapshot> const& scroll_state_snapshot, MonotonicTime now)+bool CompositorCore::install_display_list_update(Web::CompositorContextId context_id, Compositing::DisplayList const& display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state, MonotonicTime now){auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());- return RustFFI::compositor_core_install_display_list_update(m_core, context_id.value(), &display_list_for_scroll_logic, visual_context_tree.rust_handle(), scroll_state_snapshot.bytes(), now.nanoseconds());+ return RustFFI::compositor_core_install_display_list_update(m_core, context_id.value(), &display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state, now.nanoseconds());}bool CompositorCore::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree const& visual_context_tree, MonotonicTime now)@@ -139,36 +139,19 @@ bool CompositorCore::needs_animation_frames(Web::CompositorContextId context_id,return RustFFI::compositor_core_needs_animation_frames(m_core, context_id.value(), now.nanoseconds());}-static void receive_frame_inputs(void* receiver, RustFFI::FfiFrameInputs const* lent)-{- Compositing::ScrollStateSnapshot presented_scroll_state_snapshot;- presented_scroll_state_snapshot.assign_device_offsets(lent->presented_device_offsets);- Vector<ScrollbarOfFrame> scrollbars;- scrollbars.append(lent->scrollbars.data(), lent->scrollbars.size());- Optional<Compositing::SpatialNodeIndex> viewport_scroll_node_index;- if (lent->has_viewport_scroll_node_index)- viewport_scroll_node_index = lent->viewport_scroll_node_index;- *static_cast<Optional<FrameInputs>*>(receiver) = FrameInputs {- .visual_context_tree = Compositing::AccumulatedVisualContextTree::adopt_rust_handle(lent->visual_context_tree),- .presented_scroll_state_snapshot = move(presented_scroll_state_snapshot),- .scrollbars = move(scrollbars),- .viewport_scroll_node_index = viewport_scroll_node_index,- };-}-Optional<FrameInputs> CompositorCore::frame_inputs(Web::CompositorContextId context_id, MonotonicTime now){- Optional<FrameInputs> frame_inputs;- RustFFI::compositor_core_frame_inputs(m_core, context_id.value(), now.nanoseconds(), &frame_inputs, receive_frame_inputs);- return frame_inputs;+ auto* frame_inputs = RustFFI::compositor_core_frame_inputs(m_core, context_id.value(), now.nanoseconds());+ if (!frame_inputs)+ return {};+ return FrameInputs::adopt(frame_inputs);}CompositorCore::ScreenshotInputs CompositorCore::frame_inputs_for_screenshot(Web::CompositorContextId context_id, MonotonicTime now){- Optional<FrameInputs> frame_inputs;Gfx::IntRect scrollbar_fade_damage_rect;- RustFFI::compositor_core_frame_inputs_for_screenshot(m_core, context_id.value(), now.nanoseconds(), &frame_inputs, receive_frame_inputs, &scrollbar_fade_damage_rect);- return { .frame_inputs = frame_inputs.release_value(), .scrollbar_fade_damage_rect = scrollbar_fade_damage_rect };+ auto* frame_inputs = RustFFI::compositor_core_frame_inputs_for_screenshot(m_core, context_id.value(), now.nanoseconds(), &scrollbar_fade_damage_rect);+ return { .frame_inputs = FrameInputs::adopt(frame_inputs), .scrollbar_fade_damage_rect = scrollbar_fade_damage_rect };}DisplayTickResult CompositorCore::display_tick(Web::CompositorContextId context_id, MonotonicTime frame_time, MonotonicTime now, DisplayTickInputs const& inputs)diff --git a/Services/Compositor/CompositorCore.h b/Services/Compositor/CompositorCore.hindex 3d48ce915bd..4e92e50ecd6 100644--- a/Services/Compositor/CompositorCore.h+++ b/Services/Compositor/CompositorCore.h@@ -13,7 +13,6 @@#include <Compositor/FrameInputs.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>#include <LibIPC/Encoded.h>#include <LibIPC/Message.h>@@ -50,7 +49,7 @@ public:void set_scroll_capabilities(Web::CompositorContextId, ScrollCapabilities const&);// Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode.- bool install_display_list_update(Web::CompositorContextId, Compositing::DisplayList const&, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree const&, IPC::Encoded<Compositing::ScrollStateSnapshot> const&, MonotonicTime now);+ bool install_display_list_update(Web::CompositorContextId, Compositing::DisplayList const&, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state, MonotonicTime now);// Returns false, leaving everything as it was, for a tree that does not fit the installed display list.bool update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree const&, MonotonicTime now);diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 93164be6243..d09d72e3ce2 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -373,7 +373,7 @@ void CompositorState::stop_presenting_to_client(Web::CompositorContextId contextcontext->presenter.stop_presenting_to_client();}-bool CompositorState::update_display_list(Web::CompositorContextId context_id, NonnullRefPtr<Compositing::DisplayList> display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction, IPC::Encoded<Compositing::ScrollStateSnapshot> const& scroll_state_snapshot)+bool CompositorState::update_display_list(Web::CompositorContextId context_id, NonnullRefPtr<Compositing::DisplayList> display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction, ReadonlyBytes encoded_scroll_state){auto now = MonotonicTime::now();auto* context = presented_context_if_present(context_id);@@ -390,7 +390,7 @@ bool CompositorState::update_display_list(Web::CompositorContextId context_id, Nreturn true;}- if (!m_core.install_display_list_update(context_id, *display_list, async_scrolling_metadata, visual_context_tree, scroll_state_snapshot, now))+ if (!m_core.install_display_list_update(context_id, *display_list, async_scrolling_metadata, visual_context_tree, encoded_scroll_state, now))return false;context->presenter.apply_resource_transaction(move(resource_transaction));context->presenter.set_display_list(display_list);diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 0f4ab5db429..b8a3390f115 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -25,7 +25,6 @@#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>#include <LibCore/Forward.h>#include <LibGfx/Point.h>@@ -115,7 +114,7 @@ public:void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId> parent_context_id);void stop_presenting_to_client(Web::CompositorContextId);// Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode.- bool update_display_list(Web::CompositorContextId, NonnullRefPtr<Compositing::DisplayList>, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction&&, IPC::Encoded<Compositing::ScrollStateSnapshot> const&);+ bool update_display_list(Web::CompositorContextId, NonnullRefPtr<Compositing::DisplayList>, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction&&, ReadonlyBytes encoded_scroll_state);void update_display_list_resources(Web::CompositorContextId, Compositing::DisplayListResourceTransaction&&);void update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction&&);void add_video_sink(CompositorStateWebContentClient&, Media::VideoSinkHandle);diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex c4d8dbd8ace..ddff7194c73 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -5,7 +5,6 @@#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>#include <LibCompositing/Video/VideoFramePresentationPage.h>#include <LibCompositing/WebGL/ImageSourceFrame.h>@@ -43,11 +42,12 @@ endpoint CompositorWebContentServerstop_presenting_to_client(Web::CompositorContextId context_id) =|destroy_context(Web::CompositorContextId context_id) =|- // The async scrolling metadata and the scroll state go still encoded: the scroll logic, which is Rust, decodes them.- update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, IPC::Encoded<Compositing::ScrollStateSnapshot> scroll_state_snapshot) =|+ // The async scrolling metadata and the scroll state go encoded: the scroll logic, which is Rust, decodes them, and+ // Rust encoded the scroll state.+ update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state) =|update_display_list_resources(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction resource_transaction) =|update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction) =|- [RustReceiver] update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state) =|+ [RustReceiver] update_scroll_state(Web::CompositorContextId context_id, ByteBuffer scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state) =|// Hands WebContent a range of canvas IDs it may name its own 2D contexts with, so creating one needs no round trip.reserve_canvas_ids() => (Compositing::CanvasId first_canvas_id, u64 count)diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex b6ba0688230..9ee061ae0ec 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -290,7 +290,7 @@ static bool display_list_timing_enabled()return enabled;}-void ConnectionFromWebContent::update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, IPC::Encoded<Compositing::ScrollStateSnapshot> scroll_state_snapshot)+void ConnectionFromWebContent::update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, ByteBuffer scroll_state){auto timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);auto display_list = Compositing::DisplayList::create_from_shared_buffer(move(display_list_properties), move(display_list_buffer), tape_size, run_count);@@ -302,7 +302,7 @@ void ConnectionFromWebContent::update_display_list(Web::CompositorContextId contauto adopt_time = timer.elapsed_time();if (!context_is_owned_by_this_connection(context_id))return;- if (!m_compositor_state->update_display_list(context_id, display_list.release_value(), async_scrolling_metadata, move(visual_context_tree), move(resource_transaction), scroll_state_snapshot)) {+ if (!m_compositor_state->update_display_list(context_id, display_list.release_value(), async_scrolling_metadata, move(visual_context_tree), move(resource_transaction), scroll_state.bytes())) {did_misbehave("WebContent published a display list with scrolling state the compositor cannot use");return;}diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex 4fb92f71b2a..501b8127484 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -57,7 +57,7 @@ private:virtual void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>) override;virtual void stop_presenting_to_client(Web::CompositorContextId) override;virtual void destroy_context(Web::CompositorContextId) override;- virtual void update_display_list(Web::CompositorContextId, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>>, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction, IPC::Encoded<Compositing::ScrollStateSnapshot>) override;+ virtual void update_display_list(Web::CompositorContextId, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>>, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction, ByteBuffer scroll_state) override;virtual void update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction) override;virtual void update_display_list_resources(Web::CompositorContextId, Compositing::DisplayListResourceTransaction) override;virtual Messages::CompositorWebContentServer::ReserveCanvasIdsResponse reserve_canvas_ids() override;diff --git a/Services/Compositor/ContextPresenter.cpp b/Services/Compositor/ContextPresenter.cppindex 8a6cfab730d..fcfbf8ecfe0 100644--- a/Services/Compositor/ContextPresenter.cpp+++ b/Services/Compositor/ContextPresenter.cpp@@ -11,7 +11,6 @@#include <Compositor/PausedDebuggerOverlay.h>#include <Compositor/PictureInPictureControls.h>#include <Compositor/SkiaUtils.h>-#include <LibCompositing/DisplayList/DisplayListDamage.h>#include <LibCore/Timer.h>#include <LibGfx/Bitmap.h>#include <LibMedia/Sinks/VideoSink.h>@@ -312,7 +311,6 @@ Optional<PreparedFrame> ContextPresenter::prepare_frame(DisplayListPlayerSkia& dVERIFY(frame_inputs.has_value());auto damage_rect = frame_damage_for(pending_frame, *frame_inputs);- keep_world_transforms_of_last_rasterized_frame(*frame_inputs);// NB: A changed content rect must still reach the client even if the pixels are identical.if (damage_rect.is_empty() && m_presented_frame == pending_frame.viewport_rect) {remember_rasterized_frame(pending_frame.viewport_rect.size(), frame_inputs.release_value());@@ -358,7 +356,6 @@ bool ContextPresenter::present_synchronously(DisplayListPlayerSkia& display_listauto render_target = m_backing_store_manager.acquire_render_target(raster_damage_rect(frame_damage_for(*pending_frame, *frame_inputs)));if (!render_target.has_value())return false;- keep_world_transforms_of_last_rasterized_frame(*frame_inputs);auto& back_store = render_target->surface;paint_current_display_list(display_list_player, back_store, *frame_inputs, composited_context_resolver, render_target->damage_rect);remember_rasterized_frame(pending_frame->viewport_rect.size(), frame_inputs.release_value());@@ -440,7 +437,6 @@ Gfx::IntRect ContextPresenter::frame_damage_for(PendingFrame const& pending_framGfx::IntRect ContextPresenter::damage_since_last_raster(Gfx::IntSize viewport_size, FrameInputs const& frame_inputs, Gfx::IntRect forced_damage_rect){- auto const& presented_scroll_state_snapshot = frame_inputs.presented_scroll_state_snapshot;Gfx::IntRect viewport_rect { {}, viewport_size };if (!m_last_rasterized_frame.has_value())return viewport_rect;@@ -449,10 +445,6 @@ Gfx::IntRect ContextPresenter::damage_since_last_raster(Gfx::IntSize viewport_sireturn viewport_rect;if (last_frame.display_list->surface_clear_color() != m_display_list->surface_clear_color())return viewport_rect;- if (auto index = frame_inputs.viewport_scroll_node_index; index.has_value()) {- if (last_frame.scroll_state_snapshot.device_offset_for_index(*index) != presented_scroll_state_snapshot.device_offset_for_index(*index))- return viewport_rect;- }Vector<Compositing::CanvasId> canvases_with_new_content;for (auto const& [canvas_id, content_generation] : last_frame.canvas_content_generations) {@@ -480,20 +472,10 @@ Gfx::IntRect ContextPresenter::damage_since_last_raster(Gfx::IntSize viewport_sireturn viewport_rect;image_frames_with_new_pixels.append(Compositing::ImageFrameResourceId { image_frame_id });}- for (auto const& scrollbar : frame_inputs.scrollbars) {- if (!scrollbar.is_painted_by_compositor)- continue;- if (last_frame.scroll_state_snapshot.device_offset_for_index(scrollbar.scroll_node_index) == presented_scroll_state_snapshot.device_offset_for_index(scrollbar.scroll_node_index))- continue;- forced_damage_rect.unite(scrollbar.thin_and_expanded_gutter_rect);- }- auto display_list_damage = Compositing::compute_display_list_damage(- *last_frame.display_list,- last_frame.visual_context_tree,- last_frame.scroll_state_snapshot,+ auto display_list_damage = frame_inputs.damage_since(*m_display_list,- frame_inputs.visual_context_tree,- presented_scroll_state_snapshot,+ last_frame.frame_inputs,+ *last_frame.display_list,viewport_rect,{ .canvases = canvases_with_new_content, .video_sinks = video_sinks_with_new_frames, .image_frames = image_frames_with_new_pixels, .forced_damage_rect = forced_damage_rect });if (!display_list_damage.has_value())@@ -501,12 +483,6 @@ Gfx::IntRect ContextPresenter::damage_since_last_raster(Gfx::IntSize viewport_sireturn display_list_damage->intersected(viewport_rect);}-void ContextPresenter::keep_world_transforms_of_last_rasterized_frame(FrameInputs& frame_inputs)-{- if (m_last_rasterized_frame.has_value())- frame_inputs.presented_scroll_state_snapshot.take_world_transforms_built_for_the_same_offsets_from(m_last_rasterized_frame->scroll_state_snapshot);-}-void ContextPresenter::remember_rasterized_frame(Gfx::IntSize viewport_size, FrameInputs&& frame_inputs){HashMap<Compositing::CanvasId, u64> canvas_content_generations;@@ -522,8 +498,7 @@ void ContextPresenter::remember_rasterized_frame(Gfx::IntSize viewport_size, Fra}m_last_rasterized_frame = RasterizedFrame {.display_list = NonnullRefPtr { *m_display_list },- .visual_context_tree = move(frame_inputs.visual_context_tree),- .scroll_state_snapshot = move(frame_inputs.presented_scroll_state_snapshot),+ .frame_inputs = move(frame_inputs),.viewport_size = viewport_size,.canvas_content_generations = move(canvas_content_generations),.video_frame_ids = move(video_frame_ids),@@ -549,15 +524,14 @@ void ContextPresenter::paint_current_display_list(DisplayListPlayerSkia& displayauto paint_display_list = [&](Gfx::PaintingSurface& target_surface) {display_list_player.execute(*m_display_list,- frame_inputs.visual_context_tree,+ frame_inputs.visual_context_tree(),m_resource_storage,m_raster_cache,- frame_inputs.presented_scroll_state_snapshot,+ &frame_inputs,target_surface,&m_canvas_surfaces,- composited_context_resolver,- frame_inputs.scrollbars);- display_list_player.paint_scrollbars_painted_by_compositor(target_surface, frame_inputs.scrollbars);+ composited_context_resolver);+ display_list_player.paint_scrollbars_painted_by_compositor(target_surface, frame_inputs.scrollbars());if (paint_ui_overlay == PaintUIOverlay::No)return;diff --git a/Services/Compositor/ContextPresenter.h b/Services/Compositor/ContextPresenter.hindex 0e0b5e12941..13c73faa4ce 100644--- a/Services/Compositor/ContextPresenter.h+++ b/Services/Compositor/ContextPresenter.h@@ -26,7 +26,6 @@#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/Forward.h>#include <LibCompositing/OverlayFade.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibCompositing/Types.h>#include <LibCompositing/UIOverlays.h>#include <LibCore/Forward.h>@@ -116,8 +115,7 @@ public:private:struct RasterizedFrame {NonnullRefPtr<Compositing::DisplayList const> display_list;- Compositing::AccumulatedVisualContextTree visual_context_tree;- Compositing::ScrollStateSnapshot scroll_state_snapshot;+ FrameInputs frame_inputs;Gfx::IntSize viewport_size;HashMap<Compositing::CanvasId, u64> canvas_content_generations;HashMap<Compositing::VideoSinkResourceId, Optional<u64>> video_frame_ids;@@ -136,7 +134,6 @@ private:Gfx::IntRect raster_damage_rect(Gfx::IntRect) const;Gfx::IntRect frame_damage_for(PendingFrame const&, FrameInputs const&);Gfx::IntRect damage_since_last_raster(Gfx::IntSize viewport_size, FrameInputs const&, Gfx::IntRect forced_damage_rect);- void keep_world_transforms_of_last_rasterized_frame(FrameInputs&);void remember_rasterized_frame(Gfx::IntSize viewport_size, FrameInputs&&);Optional<u64> current_video_frame_id(Compositing::VideoSinkResourceId);void stop_backing_store_shrink_timer();diff --git a/Services/Compositor/DisplayListPlayer.cpp b/Services/Compositor/DisplayListPlayer.cppindex dc2bc51065a..1d9988f8a5a 100644--- a/Services/Compositor/DisplayListPlayer.cpp+++ b/Services/Compositor/DisplayListPlayer.cpp@@ -18,7 +18,7 @@ void DisplayListPlayer::execute(DisplayList const& display_list,AccumulatedVisualContextTree const& visual_context_tree,DisplayListResourceStorage const& resource_storage,- ScrollStateSnapshot const& scroll_state_snapshot,+ FrameInputs const* frame_inputs,RefPtr<Gfx::PaintingSurface> surface,OwnedCanvasSurfaces const* canvas_surfaces){@@ -28,7 +28,7 @@ void DisplayListPlayer::execute(m_active_visual_context_tree = &visual_context_tree;m_resource_storage = &resource_storage;m_canvas_surfaces = canvas_surfaces;- execute_impl(display_list, scroll_state_snapshot);+ execute_impl(display_list, frame_inputs);m_canvas_surfaces = nullptr;m_resource_storage = nullptr;m_active_visual_context_tree = nullptr;@@ -43,27 +43,18 @@ void DisplayListPlayer::execute_display_list_into_surface(DisplayList const& disTemporaryChange display_list_change { m_active_display_list, &display_list };TemporaryChange visual_context_tree_change { m_active_visual_context_tree, &visual_context_tree };VERIFY(m_resource_storage);- ScrollStateSnapshot scroll_state_snapshot;- execute_impl(display_list, scroll_state_snapshot);-}--void DisplayListPlayer::execute_command_bytes_into_surface(ReadonlyBytes command_bytes, Gfx::PaintingSurface& target_surface)-{- TemporaryChange surface_change { m_surface, RefPtr<Gfx::PaintingSurface> { target_surface } };- ScrollStateSnapshot scroll_state_snapshot;- execute_command_bytes(command_bytes, scroll_state_snapshot);+ execute_impl(display_list, nullptr);}void DisplayListPlayer::execute_nested_display_list(DisplayList const& display_list,- AccumulatedVisualContextTree const& visual_context_tree,- ScrollStateSnapshot const& scroll_state_snapshot)+ AccumulatedVisualContextTree const& visual_context_tree){VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());TemporaryChange display_list_change { m_active_display_list, &display_list };TemporaryChange visual_context_tree_change { m_active_visual_context_tree, &visual_context_tree };VERIFY(m_resource_storage);- execute_impl(display_list, scroll_state_snapshot);+ execute_impl(display_list, nullptr);}// Builds the callbacks the Rust replay drives a player through.@@ -109,9 +100,19 @@ void DisplayListPlayer::play_command_bytes(DisplayListCommandType command_type,}}-void DisplayListPlayer::execute_command_bytes(ReadonlyBytes command_bytes, ScrollStateSnapshot const& scroll_state)+void DisplayListPlayer::execute_command_bytes(ReadonlyBytes command_bytes){- DisplayList::replay_records(command_bytes, scroll_state, ReplayCallbacks::for_player(*this));+ auto callbacks = ReplayCallbacks::for_player(*this);+ if (m_active_frame_inputs)+ m_active_frame_inputs->replay_records(command_bytes, callbacks);+ else+ DisplayList::replay_records(command_bytes, callbacks);+}++void DisplayListPlayer::execute_command_bytes_into_surface(ReadonlyBytes command_bytes, Gfx::PaintingSurface& target_surface)+{+ TemporaryChange surface_change { m_surface, RefPtr<Gfx::PaintingSurface> { target_surface } };+ DisplayList::replay_records(command_bytes, ReplayCallbacks::for_player(*this));}void DisplayListPlayer::declare_mask_content(EffectNodeIndex effect, ReadonlyBytes content)@@ -124,16 +125,21 @@ Optional<ReadonlyBytes> DisplayListPlayer::declared_mask_content(EffectNodeIndexreturn m_declared_mask_contents.get(effect.value());}-void DisplayListPlayer::execute_impl(DisplayList const& display_list, ScrollStateSnapshot const& scroll_state)+void DisplayListPlayer::execute_impl(DisplayList const& display_list, FrameInputs const* frame_inputs){- TemporaryChange active_scroll_state_change { m_active_scroll_state, &scroll_state };+ TemporaryChange active_frame_inputs_change { m_active_frame_inputs, frame_inputs };TemporaryChange declared_mask_contents_change { m_declared_mask_contents, HashMap<u32, ReadonlyBytes> {} };auto const& visual_context_tree = active_visual_context_tree();VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());VERIFY(m_surface);auto callbacks = ReplayCallbacks::for_player(*this);- display_list.replay(visual_context_tree, scroll_state, callbacks);+ if (frame_inputs) {+ VERIFY(frame_inputs->visual_context_tree().rust_handle() == visual_context_tree.rust_handle());+ frame_inputs->replay(display_list, callbacks);+ } else {+ display_list.replay(visual_context_tree, callbacks);+ }}}diff --git a/Services/Compositor/DisplayListPlayer.h b/Services/Compositor/DisplayListPlayer.hindex 4685b7433f7..9d5e3935433 100644--- a/Services/Compositor/DisplayListPlayer.h+++ b/Services/Compositor/DisplayListPlayer.h@@ -11,12 +11,12 @@#include <AK/RefPtr.h>#include <AK/Span.h>#include <Compositor/Forward.h>+#include <Compositor/FrameInputs.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListCommand.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>#include <LibGfx/Forward.h>namespace Compositor {@@ -25,7 +25,8 @@ class DisplayListPlayer {public:virtual ~DisplayListPlayer() = default;- void execute(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&, Compositing::DisplayListResourceStorage const&, Compositing::ScrollStateSnapshot const&, RefPtr<Gfx::PaintingSurface>, OwnedCanvasSurfaces const* = nullptr);+ // The frame inputs say where the frame presents what scrolls. Without them, nothing is scrolled.+ void execute(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&, Compositing::DisplayListResourceStorage const&, FrameInputs const*, RefPtr<Gfx::PaintingSurface>, OwnedCanvasSurfaces const* = nullptr);virtual void flush(Gfx::PaintingSurface&) = 0;protected:@@ -48,14 +49,14 @@ protected:VERIFY(reinterpret_cast<FlatPtr>(bytes.data()) % alignof(T) == 0);return { reinterpret_cast<T const*>(bytes.data()), bytes.size() / sizeof(T) };}- void execute_impl(Compositing::DisplayList const&, Compositing::ScrollStateSnapshot const& scroll_state);- void execute_command_bytes(ReadonlyBytes, Compositing::ScrollStateSnapshot const& scroll_state);- Compositing::ScrollStateSnapshot const& active_scroll_state() const { return *m_active_scroll_state; }+ void execute_impl(Compositing::DisplayList const&, FrameInputs const*);+ // Plays records that a command of the list being played nests, scrolled as that list is.+ void execute_command_bytes(ReadonlyBytes);void execute_display_list_into_surface(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&, Gfx::PaintingSurface&);void execute_command_bytes_into_surface(ReadonlyBytes, Gfx::PaintingSurface&);void declare_mask_content(Compositing::EffectNodeIndex, ReadonlyBytes content);Optional<ReadonlyBytes> declared_mask_content(Compositing::EffectNodeIndex) const;- void execute_nested_display_list(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&);+ void execute_nested_display_list(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&);private:struct ReplayCallbacks;@@ -86,7 +87,7 @@ private:OwnedCanvasSurfaces const* m_canvas_surfaces { nullptr };RefPtr<Gfx::PaintingSurface> m_surface;ReadonlyBytes m_current_command_payload;- Compositing::ScrollStateSnapshot const* m_active_scroll_state { nullptr };+ FrameInputs const* m_active_frame_inputs { nullptr };HashMap<u32, ReadonlyBytes> m_declared_mask_contents;};diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex 4dc2b598d13..fee008824b4 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -67,21 +67,20 @@ void DisplayListPlayerSkia::execute(AccumulatedVisualContextTree const& visual_context_tree,DisplayListResourceStorage const& resource_storage,DisplayListRasterCache& raster_cache,- ScrollStateSnapshot const& scroll_state_snapshot,+ FrameInputs const* frame_inputs,RefPtr<Gfx::PaintingSurface> surface,OwnedCanvasSurfaces const* canvas_surfaces,- CompositedContextResolver const* composited_context_resolver,- ReadonlySpan<ScrollbarOfFrame> scrollbars_of_frame)+ CompositedContextResolver const* composited_context_resolver){TemporaryChange composited_context_resolver_change { m_composited_context_resolver, composited_context_resolver };- TemporaryChange scrollbars_of_frame_change { m_scrollbars_of_frame, scrollbars_of_frame };+ TemporaryChange scrollbars_of_frame_change { m_scrollbars_of_frame, frame_inputs ? frame_inputs->scrollbars() : ReadonlySpan<ScrollbarOfFrame> {} };raster_cache.drop_clip_paths_not_used_since_last_frame();TemporaryChange raster_cache_change { m_raster_cache, &raster_cache };DisplayListPlayer::execute(display_list,visual_context_tree,resource_storage,- scroll_state_snapshot,+ frame_inputs,move(surface),canvas_surfaces);}@@ -294,7 +293,7 @@ void DisplayListPlayerSkia::play_command(DrawCompositedContext const& command)// Snap iframe origins to device pixels for browser compatibility when transforms are absent or identity.// Preserve fractional placement under other transforms to retain the raster phase of surrounding content.- if (command.snap_origin_if_untransformed && active_visual_context_tree().translations_snap_to_device_pixels(command.spatial_node_index, active_scroll_state())) {+ if (command.snap_origin_if_untransformed && active_visual_context_tree().translations_snap_to_device_pixels(command.spatial_node_index)) {destination_rect.set_x(roundf(destination_rect.x()));destination_rect.set_y(roundf(destination_rect.y()));}@@ -1308,14 +1307,14 @@ void DisplayListPlayerSkia::play_command(DrawIsolatedGroup const& command)if (command.filter.size != 0)group_paint.setImageFilter(image_filter_from_bytes(inline_data(command.filter)));canvas.saveLayer(nullptr, &group_paint);- execute_command_bytes(inline_data(command.content), active_scroll_state());+ execute_command_bytes(inline_data(command.content));if (command.mask.size != 0) {SkPaint mask_paint;mask_paint.setBlender(Gfx::to_skia_blender(Gfx::CompositingAndBlendingOperator::DestinationIn));if (command.mask_kind == Gfx::MaskKind::Luminance)mask_paint.setColorFilter(SkLumaColorFilter::Make());canvas.saveLayer(nullptr, &mask_paint);- execute_command_bytes(inline_data(command.mask), active_scroll_state());+ execute_command_bytes(inline_data(command.mask));canvas.restore();}canvas.restore();@@ -1431,8 +1430,7 @@ void DisplayListPlayerSkia::play_command(PaintNestedDisplayList const& command)if (!list_bounds.is_empty() && !command.rect.is_empty())canvas.scale(command.rect.width() / command.list_size.width(), command.rect.height() / command.list_size.height());}- ScrollStateSnapshot scroll_state_snapshot;- execute_nested_display_list(*nested_display_list.display_list, nested_display_list.visual_context_tree, scroll_state_snapshot);+ execute_nested_display_list(*nested_display_list.display_list, nested_display_list.visual_context_tree);canvas.restore();}@@ -1672,7 +1670,7 @@ void DisplayListPlayerSkia::pop_mask(ReplayMask const& mask, EffectNodeIndex effif (auto content = declared_mask_content(effect); content.has_value()) {canvas.save();canvas.clipRect(to_skia_rect(mask.rect.to_type<float>()));- execute_command_bytes(*content, active_scroll_state());+ execute_command_bytes(*content);canvas.restore();}canvas.restore();diff --git a/Services/Compositor/DisplayListPlayerSkia.h b/Services/Compositor/DisplayListPlayerSkia.hindex 21decaf2ee4..9e371f42770 100644--- a/Services/Compositor/DisplayListPlayerSkia.h+++ b/Services/Compositor/DisplayListPlayerSkia.h@@ -48,11 +48,10 @@ public:Compositing::AccumulatedVisualContextTree const&,Compositing::DisplayListResourceStorage const&,DisplayListRasterCache&,- Compositing::ScrollStateSnapshot const&,+ FrameInputs const*,RefPtr<Gfx::PaintingSurface>,OwnedCanvasSurfaces const*,- CompositedContextResolver const*,- ReadonlySpan<ScrollbarOfFrame> = {});+ CompositedContextResolver const*);void flush(Gfx::PaintingSurface&) override;void flush_async(Gfx::PaintingSurface&, Function<void()>&&);diff --git a/Services/Compositor/FrameInputs.cpp b/Services/Compositor/FrameInputs.cppnew file mode 100644index 00000000000..cdde3efdf0c--- /dev/null+++ b/Services/Compositor/FrameInputs.cpp@@ -0,0 +1,82 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/StdLibExtras.h>+#include <Compositor/FrameInputs.h>++namespace Compositor {++FrameInputs::FrameInputs(RustFFI::FrameInputs* frame_inputs, Compositing::AccumulatedVisualContextTree visual_context_tree)+ : m_frame_inputs(frame_inputs)+ , m_visual_context_tree(move(visual_context_tree))+{+}++FrameInputs FrameInputs::adopt(RustFFI::FrameInputs* frame_inputs)+{+ VERIFY(frame_inputs);+ return { frame_inputs, Compositing::AccumulatedVisualContextTree::adopt_rust_handle(RustFFI::compositor_frame_inputs_retain_visual_context_tree(frame_inputs)) };+}++FrameInputs::FrameInputs(FrameInputs&& other)+ : m_frame_inputs(exchange(other.m_frame_inputs, nullptr))+ , m_visual_context_tree(move(other.m_visual_context_tree))+{+}++FrameInputs& FrameInputs::operator=(FrameInputs&& other)+{+ if (this == &other)+ return *this;+ if (m_frame_inputs)+ RustFFI::compositor_frame_inputs_destroy(m_frame_inputs);+ m_frame_inputs = exchange(other.m_frame_inputs, nullptr);+ m_visual_context_tree = move(other.m_visual_context_tree);+ return *this;+}++FrameInputs::~FrameInputs()+{+ if (m_frame_inputs)+ RustFFI::compositor_frame_inputs_destroy(m_frame_inputs);+}++ReadonlySpan<ScrollbarOfFrame> FrameInputs::scrollbars() const+{+ size_t count = 0;+ auto const* scrollbars = RustFFI::compositor_frame_inputs_scrollbars(m_frame_inputs, &count);+ return { scrollbars, count };+}++void FrameInputs::replay(Compositing::DisplayList const& display_list, Compositing::RustFFI::FfiDisplayListReplayCallbacks const& callbacks) const+{+ VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == m_visual_context_tree.structural_epoch());+ RustFFI::compositor_frame_inputs_replay(m_frame_inputs, display_list.rust_handle(), display_list.root_group_color(), &callbacks);+}++void FrameInputs::replay_records(ReadonlyBytes records, Compositing::RustFFI::FfiDisplayListReplayCallbacks const& callbacks) const+{+ RustFFI::compositor_frame_inputs_replay_records(m_frame_inputs, records.data(), records.size(), &callbacks);+}++Optional<Gfx::IntRect> FrameInputs::damage_since(Compositing::DisplayList const& display_list, FrameInputs const& last_frame_inputs, Compositing::DisplayList const& last_display_list, Gfx::IntRect viewport_rect, LiveContentChanges live_content_changes) const+{+ Gfx::IntRect damage_rect;+ bool damage_is_bounded = RustFFI::compositor_frame_inputs_damage_since(+ m_frame_inputs, display_list.rust_handle(),+ last_frame_inputs.m_frame_inputs, last_display_list.rust_handle(),+ viewport_rect,+ live_content_changes.canvases.data(), live_content_changes.canvases.size(),+ live_content_changes.video_sinks.data(), live_content_changes.video_sinks.size(),+ live_content_changes.image_frames.data(), live_content_changes.image_frames.size(),+ live_content_changes.forced_damage_rect,+ &damage_rect);+ if (!damage_is_bounded)+ return {};+ return damage_rect;+}++}diff --git a/Services/Compositor/FrameInputs.h b/Services/Compositor/FrameInputs.hindex e6f9e0b0974..75ac1fcae10 100644--- a/Services/Compositor/FrameInputs.h+++ b/Services/Compositor/FrameInputs.h@@ -6,11 +6,13 @@#pragma once+#include <AK/Noncopyable.h>#include <AK/Optional.h>-#include <AK/Vector.h>+#include <AK/Span.h>#include <Compositor/CompositorCoreRustFFI.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/Scrolling/ScrollState.h>+#include <LibCompositing/DisplayList/DisplayList.h>+#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibGfx/Color.h>#include <LibGfx/Rect.h>#include <math.h>@@ -60,12 +62,44 @@ inline PresentedScrollbar presented_scrollbar_with_colors(ScrollbarOfFrame const};}-// What a frame is painted with besides the display list and its resources.-struct FrameInputs {- Compositing::AccumulatedVisualContextTree visual_context_tree;- Compositing::ScrollStateSnapshot presented_scroll_state_snapshot;- Vector<ScrollbarOfFrame> scrollbars;- Optional<Compositing::SpatialNodeIndex> viewport_scroll_node_index;+// The canvases, video sinks and image frames whose pixels changed since a display list was rasterized. The list draws+// them with commands that stay the same, so comparing lists cannot see the change.+struct LiveContentChanges {+ ReadonlySpan<Compositing::CanvasId> canvases;+ ReadonlySpan<Compositing::VideoSinkResourceId> video_sinks;+ ReadonlySpan<Compositing::ImageFrameResourceId> image_frames;+ // What the compositor repaints whatever the lists hold, such as a blinking caret.+ Gfx::IntRect forced_damage_rect;+};++// What a frame is painted with besides the display list and its resources, which the scroll and input logic holds:+// where the frame presents everything that scrolls is known to it alone.+class FrameInputs {+ AK_MAKE_NONCOPYABLE(FrameInputs);++public:+ static FrameInputs adopt(RustFFI::FrameInputs*);+ FrameInputs(FrameInputs&&);+ FrameInputs& operator=(FrameInputs&&);+ ~FrameInputs();++ Compositing::AccumulatedVisualContextTree const& visual_context_tree() const { return m_visual_context_tree; }+ ReadonlySpan<ScrollbarOfFrame> scrollbars() const;++ // Replays the list through a player's callbacks as the frame shows it.+ void replay(Compositing::DisplayList const&, Compositing::RustFFI::FfiDisplayListReplayCallbacks const&) const;+ // Replays a stream of records that a command of the list being replayed nests.+ void replay_records(ReadonlyBytes records, Compositing::RustFFI::FfiDisplayListReplayCallbacks const&) const;++ // What painting the list with these inputs repaints of the last frame, which painted its list with its inputs.+ // Empty where the damage has no bounds.+ Optional<Gfx::IntRect> damage_since(Compositing::DisplayList const&, FrameInputs const& last_frame_inputs, Compositing::DisplayList const& last_display_list, Gfx::IntRect viewport_rect, LiveContentChanges) const;++private:+ FrameInputs(RustFFI::FrameInputs*, Compositing::AccumulatedVisualContextTree);++ RustFFI::FrameInputs* m_frame_inputs { nullptr };+ Compositing::AccumulatedVisualContextTree m_visual_context_tree;};}diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex 4dce67f3e53..e5159aae401 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -30,6 +30,13 @@ fn main() -> Result<(), Box<dyn Error>> {("RawMessage", "IPC::FfiRawMessage"),("EncodedValue", "AK::ReadonlyBytes"),("FfiDisplayList", "Compositing::RustFFI::FfiDisplayList"),+ (+ "FfiDisplayListReplayCallbacks",+ "Compositing::RustFFI::FfiDisplayListReplayCallbacks",+ ),+ ("CanvasId", "Compositing::CanvasId"),+ ("VideoSinkResourceId", "Compositing::VideoSinkResourceId"),+ ("ImageFrameResourceId", "Compositing::ImageFrameResourceId"),] {config.export.rename.insert(rust_name.to_string(), cpp_name.to_string());}@@ -37,6 +44,7 @@ fn main() -> Result<(), Box<dyn Error>> {["AK/Span.h","LibCompositing/DisplayList/ContextRef.h",+ "LibCompositing/DisplayList/DisplayListResourceIds.h","LibGfx/Color.h","LibGfx/Point.h","LibGfx/Rect.h",diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex f862df1ba05..3362377e029 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -29,7 +29,7 @@ use libcompositing_rust::ipc_types::{use libcompositing_rust::scrolling::async_scrolling_state::AsyncScrollOperationID;use libcompositing_rust::scrolling::{CompositorContextId, KeyEvent, KeyModifier, MouseButton, MouseEvent, MouseEventType, PendingAsyncScrollUpdates,- PinchEvent, ScrollRequest,+ PinchEvent, ScrollRequest, ScrollStateSnapshot,};use libcompositing_rust::time::MonotonicTime;use libgfx_rust::FloatPoint;@@ -185,15 +185,15 @@ impl MessagesFromWebContent<'_> {impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {fn update_scroll_state(&mut self, message: UpdateScrollState) -> Result<(), Misbehavior> {- if !message.scroll_state_snapshot.has_only_finite_offsets() {+ let Ok(scroll_state_snapshot) = ScrollStateSnapshot::from_encoded_bytes(&message.scroll_state) else {+ return Err(Misbehavior("Invalid scroll state"));+ };+ if !scroll_state_snapshot.has_only_finite_offsets() {return Err(Misbehavior("Invalid scroll state"));}if self.context_is_owned_by_sender(message.context_id)? {- self.core.update_scroll_state(- message.context_id,- message.scroll_state_snapshot,- message.keyboard_scroll_state,- );+ self.core+ .update_scroll_state(message.context_id, scroll_state_snapshot, message.keyboard_scroll_state);}Ok(())}diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsindex ef0ab831246..8dea9239889 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -14,15 +14,22 @@ use crate::host::{ContextTimer, DisplayTickInputs, DisplayTickResult, FfiCompositorCoreHost, Host, PresentScheduling, PresentationId,WebContentClientId,};-use libcompositing_rust::display_list::commands::CompositorContextId;-use libcompositing_rust::ffi::{FfiDisplayList, tree_sharing_handle};+use libcompositing_rust::display_list::commands::{+ CanvasId, CompositorContextId, ImageFrameResourceId, VideoSinkResourceId,+};+use libcompositing_rust::display_list::damage::LiveContentChanges;+use libcompositing_rust::display_list::storage::storage_from_handle;+use libcompositing_rust::ffi::{+ FfiDisplayList, replay_display_list_storage, replay_nested_records, tree_sharing_handle,+};+use libcompositing_rust::host::FfiDisplayListReplayCallbacks;use libcompositing_rust::ipc_types::{Compositing_ContextVisibility as ContextVisibility, compositor_presentation_server, compositor_web_content_server,};+use libcompositing_rust::scrolling::ScrollStateSnapshot;use libcompositing_rust::scrolling::wheel_gesture_identity::TouchpadGestureEnd;-use libcompositing_rust::scrolling::{ScrollStateSnapshot, SpatialNodeIndex};use libcompositing_rust::time::MonotonicTime;-use libgfx_rust::{FloatPoint, IntRect, IntSize};+use libgfx_rust::{Color, IntRect, IntSize};use libipc_rust::cpp_connection::{EncodedValue, RawMessage};use std::ffi::c_void;use std::rc::Rc;@@ -193,14 +200,14 @@ pub unsafe extern "C" fn compositor_core_install_display_list_update(context_id: u64,display_list: &FfiDisplayList<'_>,visual_context_tree: *const c_void,- scroll_state_snapshot: EncodedValue<'_>,+ scroll_state: EncodedValue<'_>,now_nanoseconds: i64,) -> bool {// SAFETY: The caller lends a strong reference to the storage.let Ok(display_list) = (unsafe { display_list.share() }) else {return false;};- let Ok(scroll_state_snapshot) = scroll_state_snapshot.decode::<ScrollStateSnapshot>() else {+ let Ok(scroll_state_snapshot) = scroll_state.decode::<ScrollStateSnapshot>() else {return false;};core.install_display_list_update(@@ -245,81 +252,164 @@ pub extern "C" fn compositor_core_needs_animation_frames()}-/// What a frame is painted with besides the display list and its resources, lent for the duration of a call.-#[repr(C)]-pub struct FfiFrameInputs<'a> {- /// One strong reference to the tree, which the receiver takes over.- pub visual_context_tree: *const c_void,- pub presented_device_offsets: ak::Span<'a, FloatPoint>,- pub scrollbars: ak::Span<'a, ScrollbarOfFrame>,- pub has_viewport_scroll_node_index: bool,- pub viewport_scroll_node_index: SpatialNodeIndex,+/// What a frame of the context is painted with besides the display list and its resources, until+/// `compositor_frame_inputs_destroy` frees it. Each frame shows the scrollbars as of when it is painted, so this updates+/// which of them are shown. Null for a context that has no display list yet.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_frame_inputs(+ core: &CompositorCore,+ context_id: u64,+ now_nanoseconds: i64,+) -> *mut FrameInputs {+ core.frame_inputs(+ CompositorContextId(context_id),+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ )+ .map_or(std::ptr::null_mut(), |frame_inputs| {+ Box::into_raw(Box::new(frame_inputs))+ })}-type ReceiveFrameInputs = unsafe extern "C" fn(*mut c_void, &FfiFrameInputs<'_>);+/// What a screenshot of the context is painted with, until `compositor_frame_inputs_destroy` frees it, with the+/// scrollbar fade damage that the screenshot does not present on screen. The context must have a display list.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_frame_inputs_for_screenshot(+ core: &CompositorCore,+ context_id: u64,+ now_nanoseconds: i64,+ scrollbar_fade_damage_rect: &mut IntRect,+) -> *mut FrameInputs {+ let screenshot_inputs = core.frame_inputs_for_screenshot(+ CompositorContextId(context_id),+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+ *scrollbar_fade_damage_rect = screenshot_inputs.scrollbar_fade_damage_rect;+ Box::into_raw(Box::new(screenshot_inputs.frame_inputs))+}/// # Safety///-/// `receive` must take over the tree reference and copy what it keeps of the rest.-unsafe fn lend_frame_inputs(frame_inputs: &FrameInputs, receiver: *mut c_void, receive: ReceiveFrameInputs) {- let lent = FfiFrameInputs {- visual_context_tree: Arc::into_raw(frame_inputs.visual_context_tree.as_arc().clone()).cast(),- presented_device_offsets: ak::Span::new(frame_inputs.presented_scroll_state_snapshot.device_offsets()),- scrollbars: ak::Span::new(&frame_inputs.scrollbars),- has_viewport_scroll_node_index: frame_inputs.viewport_scroll_node_index.is_some(),- viewport_scroll_node_index: frame_inputs.viewport_scroll_node_index.unwrap_or_default(),- };- // SAFETY: The receiver takes the tree reference over and copies the rest before it returns.- unsafe { receive(receiver, &lent) };+/// `frame_inputs` must be inputs the core handed out that nothing uses afterwards.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_frame_inputs_destroy(frame_inputs: *mut FrameInputs) {+ // SAFETY: The caller hands over the inputs the core made.+ drop(unsafe { Box::from_raw(frame_inputs) });+}++/// One strong reference to the visual context tree the frame is painted with, which the caller takes over.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_frame_inputs_retain_visual_context_tree(frame_inputs: &FrameInputs) -> *const c_void {+ Arc::into_raw(frame_inputs.visual_context_tree.as_arc().clone()).cast()+}++/// The scrollbars the frame shows, of which there are `count`, lent for as long as the inputs live.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_frame_inputs_scrollbars(+ frame_inputs: &FrameInputs,+ count: &mut usize,+) -> *const ScrollbarOfFrame {+ *count = frame_inputs.scrollbars.len();+ frame_inputs.scrollbars.as_ptr()}-/// Answers false, without calling `receive`, for a context that has no display list yet.+/// Replays the list `display_list_storage` holds as the frame shows it, scrolled where the frame presents it.////// # Safety///-/// `receive` must take over the tree reference of the inputs it is lent, copy what it keeps of the rest, and not call-/// back into the core.+/// `display_list_storage` must be a live storage handle of the list the context holds, and `callbacks` must be live.+/// The painter callbacks run synchronously and may re-enter a replay.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_core_frame_inputs(- core: &CompositorCore,- context_id: u64,- now_nanoseconds: i64,- receiver: *mut c_void,- receive: ReceiveFrameInputs,-) -> bool {- let Some(frame_inputs) = core.frame_inputs(- CompositorContextId(context_id),- MonotonicTime::from_nanoseconds(now_nanoseconds),- ) else {- return false;- };- // SAFETY: The caller's receiver does as this function asks of it.- unsafe { lend_frame_inputs(&frame_inputs, receiver, receive) };- true+pub unsafe extern "C" fn compositor_frame_inputs_replay(+ frame_inputs: &FrameInputs,+ display_list_storage: *const c_void,+ root_group_color: Color,+ callbacks: *const FfiDisplayListReplayCallbacks,+) {+ // SAFETY: The caller lends a live storage handle and live callbacks.+ unsafe {+ replay_display_list_storage(+ frame_inputs.visual_context_tree.as_arc(),+ display_list_storage,+ root_group_color,+ frame_inputs.presented_scroll_state_snapshot.device_offsets(),+ callbacks,+ );+ }}-/// Answers with the scrollbar fade damage that the screenshot does not present on screen.+/// Plays a stream of records that a command of the list being replayed nests, scrolled where the frame presents it.////// # Safety///-/// The context must have a display list. `receive` must take over the tree reference of the inputs it is lent, copy-/// what it keeps of the rest, and not call back into the core.+/// `records` must address `records_size` bytes of a tape that is valid for the call, and `callbacks` must be live.+/// The painter callbacks run synchronously and may re-enter a replay.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_core_frame_inputs_for_screenshot(- core: &CompositorCore,- context_id: u64,- now_nanoseconds: i64,- receiver: *mut c_void,- receive: ReceiveFrameInputs,- scrollbar_fade_damage_rect: &mut IntRect,+pub unsafe extern "C" fn compositor_frame_inputs_replay_records(+ frame_inputs: &FrameInputs,+ records: *const u8,+ records_size: usize,+ callbacks: *const FfiDisplayListReplayCallbacks,) {- let screenshot_inputs = core.frame_inputs_for_screenshot(- CompositorContextId(context_id),- MonotonicTime::from_nanoseconds(now_nanoseconds),+ // SAFETY: The caller lends the stated number of bytes and live callbacks.+ unsafe {+ replay_nested_records(+ ak::slice_from_raw_parts(records, records_size),+ frame_inputs.presented_scroll_state_snapshot.device_offsets(),+ callbacks,+ );+ }+}++/// What a frame painted with `frame_inputs` repaints of the frame painted last, with `last_frame_inputs` and the list+/// `last_display_list_storage` holds. Writes the damage rect through `damage_rect` and returns whether the damage is+/// bounded; unbounded damage means the whole viewport must repaint.+///+/// # Safety+///+/// Both storages must be live storage handles, and the id pointers must address the stated number of ids for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_frame_inputs_damage_since(+ frame_inputs: &FrameInputs,+ display_list_storage: *const c_void,+ last_frame_inputs: &FrameInputs,+ last_display_list_storage: *const c_void,+ viewport_rect: IntRect,+ canvases_with_new_content: *const CanvasId,+ canvases_with_new_content_len: usize,+ video_sinks_with_new_frames: *const VideoSinkResourceId,+ video_sinks_with_new_frames_len: usize,+ image_frames_with_new_pixels: *const ImageFrameResourceId,+ image_frames_with_new_pixels_len: usize,+ forced_damage_rect: IntRect,+ damage_rect: &mut IntRect,+) -> bool {+ // SAFETY: The caller guarantees live handles and valid slices for the duration of the call.+ let (display_list, last_display_list, live_content_changes) = unsafe {+ (+ storage_from_handle(display_list_storage),+ storage_from_handle(last_display_list_storage),+ LiveContentChanges {+ canvases: ak::slice_from_raw_parts(canvases_with_new_content, canvases_with_new_content_len),+ video_sinks: ak::slice_from_raw_parts(video_sinks_with_new_frames, video_sinks_with_new_frames_len),+ image_frames: ak::slice_from_raw_parts(image_frames_with_new_pixels, image_frames_with_new_pixels_len),+ forced_damage_rect,+ },+ )+ };+ let damage = frame_inputs.damage_since(+ display_list,+ last_frame_inputs,+ last_display_list,+ viewport_rect,+ live_content_changes,);- // SAFETY: The caller's receiver does as this function asks of it.- unsafe { lend_frame_inputs(&screenshot_inputs.frame_inputs, receiver, receive) };- *scrollbar_fade_damage_rect = screenshot_inputs.scrollbar_fade_damage_rect;+ match damage {+ Some(bounded_damage_rect) => {+ *damage_rect = bounded_damage_rect;+ true+ }+ None => false,+ }}/// What the presentation knows of a context as a tick of a display begins.diff --git a/Services/Compositor/Rust/src/frame_inputs.rs b/Services/Compositor/Rust/src/frame_inputs.rsindex 332cbb0ff5a..2efcbb20017 100644--- a/Services/Compositor/Rust/src/frame_inputs.rs+++ b/Services/Compositor/Rust/src/frame_inputs.rs@@ -6,6 +6,8 @@//! What a frame is painted with besides the display list and its resources.+use libcompositing_rust::display_list::damage::{DisplayListFrame, LiveContentChanges, compute_display_list_damage};+use libcompositing_rust::display_list::storage::DisplayListStorage;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, ScrollStateSnapshot, SpatialNodeIndex};use libgfx_rust::{Color, FloatRect, IntRect};@@ -91,3 +93,49 @@ pub struct FrameInputs {pub scrollbars: Vec<ScrollbarOfFrame>,pub viewport_scroll_node_index: Option<SpatialNodeIndex>,}++impl FrameInputs {+ // What a frame painted with these inputs repaints of the frame `last_frame_inputs` painted `last_display_list`+ // with, or none where that has no bounds.+ pub fn damage_since(+ &self,+ display_list: &DisplayListStorage,+ last_frame_inputs: &FrameInputs,+ last_display_list: &DisplayListStorage,+ viewport_rect: IntRect,+ mut live_content_changes: LiveContentChanges<'_>,+ ) -> Option<IntRect> {+ let scroll_offset_changed = |index: SpatialNodeIndex| {+ last_frame_inputs+ .presented_scroll_state_snapshot+ .device_offset_for_index(index)+ != self.presented_scroll_state_snapshot.device_offset_for_index(index)+ };+ if self.viewport_scroll_node_index.is_some_and(scroll_offset_changed) {+ return None;+ }+ for scrollbar in &self.scrollbars {+ if scrollbar.is_painted_by_compositor && scroll_offset_changed(scrollbar.scroll_node_index) {+ live_content_changes.forced_damage_rect = live_content_changes+ .forced_damage_rect+ .united(scrollbar.thin_and_expanded_gutter_rect);+ }+ }+ compute_display_list_damage(+ last_frame_inputs.frame_of(last_display_list),+ self.frame_of(display_list),+ viewport_rect,+ live_content_changes,+ )+ }++ fn frame_of<'a>(&'a self, display_list: &'a DisplayListStorage) -> DisplayListFrame<'a> {+ DisplayListFrame {+ command_bytes: display_list.bytes(),+ command_runs: display_list.command_runs(),+ summary: display_list.summary(),+ visual_context_tree: self.visual_context_tree.as_arc(),+ scroll_offsets: self.presented_scroll_state_snapshot.device_offsets(),+ }+ }+}diff --git a/Tests/LibCompositing/CMakeLists.txt b/Tests/LibCompositing/CMakeLists.txtindex d2415e85339..8467077769d 100644--- a/Tests/LibCompositing/CMakeLists.txt+++ b/Tests/LibCompositing/CMakeLists.txt@@ -6,7 +6,6 @@ set(TEST_SOURCESTestPausedDebuggerOverlay.cppTestPictureInPictureControls.cppTestScrollRequest.cpp- TestScrollState.cppTestTextureUpload.cppTestUIOverlays.cppTestVideoFrameHold.cppdiff --git a/Tests/LibCompositing/TestScrollState.cpp b/Tests/LibCompositing/TestScrollState.cppdeleted file mode 100644index 0922a4b011b..00000000000--- a/Tests/LibCompositing/TestScrollState.cpp+++ /dev/null@@ -1,98 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/MemoryStream.h>-#include <AK/Queue.h>-#include <LibCompositing/Scrolling/ScrollState.h>-#include <LibGfx/Point.h>-#include <LibIPC/Attachment.h>-#include <LibIPC/Decoder.h>-#include <LibIPC/Encoder.h>-#include <LibIPC/Message.h>-#include <LibTest/TestCase.h>--using namespace Compositing;--// An index far above any real node count, but still inside the range the decoder accepts. Densifying it would-// allocate (index + 1) * sizeof(Gfx::FloatPoint), i.e. 512 MiB — the allocation the node-count bound exists to stop.-static constexpr u32 malicious_index = 0x04000000; // 2^26--struct WirePair {- u64 index { 0 };- Gfx::FloatPoint offset;-};--static ScrollStateSnapshot decode_snapshot(Vector<WirePair> const& pairs)-{- IPC::MessageBuffer message_buffer;- IPC::Encoder encoder { message_buffer };- MUST(encoder.encode(static_cast<u64>(pairs.size()))); // pair_count- for (auto const& pair : pairs) {- MUST(encoder.encode(pair.index));- MUST(encoder.encode(pair.offset));- }-- auto data = message_buffer.take_data();- FixedMemoryStream stream { data.span() };- Queue<IPC::Attachment> attachments;- IPC::Decoder decoder { stream, attachments };- return MUST(IPC::decode<ScrollStateSnapshot>(decoder));-}--TEST_CASE(binding_to_node_count_keeps_in_range_and_drops_out_of_range)-{- // #10847: a single 16-byte wire pair can claim any node index the decoder accepts. The decoder stages the pair- // instead of densifying — so decoding cannot abort or over-allocate. The index is validated only once the- // compositor supplies the node count, which drops it.- auto snapshot = decode_snapshot({- { 3, Gfx::FloatPoint { 10, 20 } },- { malicious_index, Gfx::FloatPoint { 30, 40 } },- });-- snapshot.set_node_count(8);-- // The in-range pair survives, the out-of-range pair is gone, and the dense store never spans more than the node count.- EXPECT_EQ(snapshot.device_offset_for_index(SpatialNodeIndex { 3 }), (Gfx::FloatPoint { 10, 20 }));- EXPECT_EQ(snapshot.device_offset_for_index(SpatialNodeIndex { malicious_index }), Gfx::FloatPoint {});- EXPECT(snapshot.device_offsets().size() <= 8u);-}--TEST_CASE(set_device_offset_ignores_index_at_or_past_node_count)-{- ScrollStateSnapshot snapshot;- snapshot.set_node_count(4);-- // A valid index is stored; an index at the bound and one far past it are both ignored, so the dense store cannot- // extend past the node count.- snapshot.set_device_offset_for_index(SpatialNodeIndex { 3 }, Gfx::FloatPoint { 5, 6 });- snapshot.set_device_offset_for_index(SpatialNodeIndex { 4 }, Gfx::FloatPoint { 7, 8 });- snapshot.set_device_offset_for_index(SpatialNodeIndex { malicious_index }, Gfx::FloatPoint { 9, 9 });-- EXPECT_EQ(snapshot.device_offset_for_index(SpatialNodeIndex { 3 }), (Gfx::FloatPoint { 5, 6 }));- EXPECT_EQ(snapshot.device_offset_for_index(SpatialNodeIndex { 4 }), Gfx::FloatPoint {});- EXPECT(snapshot.device_offsets().size() <= 4u);-}--TEST_CASE(ipc_round_trip_preserves_scroll_offsets)-{- ScrollStateSnapshot snapshot;- snapshot.set_device_offset_for_index(SpatialNodeIndex { 3 }, Gfx::FloatPoint { 10, 20 });-- IPC::MessageBuffer message_buffer;- IPC::Encoder encoder { message_buffer };- MUST(encoder.encode(snapshot));-- auto data = message_buffer.take_data();- FixedMemoryStream stream { data.span() };- Queue<IPC::Attachment> attachments;- IPC::Decoder decoder { stream, attachments };-- auto decoded = MUST(IPC::decode<ScrollStateSnapshot>(decoder));- decoded.set_node_count(8);- EXPECT_EQ(decoded.device_offset_for_index(SpatialNodeIndex { 3 }), (Gfx::FloatPoint { 10, 20 }));- // Indices that were never set are holes that decode back to zero offsets.- EXPECT_EQ(decoded.device_offset_for_index(SpatialNodeIndex { 1 }), Gfx::FloatPoint {});-}