Truly independent web browser
Compositor: Run the scroll and input logic in Rust
Aliaksandr Kalenikdcd3a531f3c6
diff --git a/Cargo.lock b/Cargo.lockindex e1983ccb736..6b96cdbe5ec 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -609,6 +609,7 @@ name = "compositor_core"version = "0.1.0"dependencies = ["ak",+ "cbindgen","ladybird_allocator","libcompositing_rust","libgfx_rust",diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.cpp b/Libraries/LibCompositing/DisplayList/DisplayList.cppindex 8e94472926d..843eca50576 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.cpp+++ b/Libraries/LibCompositing/DisplayList/DisplayList.cpp@@ -56,7 +56,7 @@ NonnullRefPtr<DisplayList> DisplayList::share_rust_command_storage(AccumulatedViNonnullRefPtr<DisplayList> DisplayList::adopt_received_storage(Properties properties, void const* storage){- return adopt_ref(*new DisplayList(properties.compatible_visual_context_tree_structural_epoch, properties.id, storage, properties.surface_clear_color, properties.root_group_color, move(properties.async_scrolling_metadata)));+ return adopt_ref(*new DisplayList(properties.compatible_visual_context_tree_structural_epoch, properties.id, storage, properties.surface_clear_color, properties.root_group_color, {}));}// Copies a tape and run table that came from another process into Rust memory through `fill`, then checks them and@@ -166,7 +166,16 @@ DisplayList::Properties DisplayList::properties() const.compatible_visual_context_tree_structural_epoch = m_compatible_visual_context_tree_structural_epoch,.surface_clear_color = m_surface_clear_color,.root_group_color = m_root_group_color,- .async_scrolling_metadata = m_async_scrolling_metadata,+ };+}++RustFFI::FfiDisplayList DisplayList::for_scroll_logic(ReadonlyBytes encoded_async_scrolling_metadata) const+{+ return {+ .storage = m_storage,+ .id = m_id,+ .compatible_visual_context_tree_structural_epoch = m_compatible_visual_context_tree_structural_epoch,+ .async_scrolling_metadata = encoded_async_scrolling_metadata,};}diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.h b/Libraries/LibCompositing/DisplayList/DisplayList.hindex 428ba7fdf7a..19601bc3c96 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.h+++ b/Libraries/LibCompositing/DisplayList/DisplayList.h@@ -28,6 +28,7 @@ namespace Compositing {namespace RustFFI {+struct FfiDisplayList;struct FfiDisplayListReplayCallbacks;}@@ -52,13 +53,12 @@ public:Compositing::KeyboardScrollState keyboard_scroll_state {};};- // Everything about a list that travels alongside its tape when it is sent to the Compositor.+ // What travels alongside the tape of a list for whatever plays the list.struct Properties {u64 id { 0 };u64 compatible_visual_context_tree_structural_epoch { 0 };Optional<Gfx::Color> surface_clear_color;Gfx::Color root_group_color { Gfx::Color::Transparent };- Optional<AsyncScrollingMetadata> async_scrolling_metadata;};// An empty list.@@ -75,7 +75,6 @@ public:// write to, and checks the copies. Fails when the sizes do not fit the buffer or the tape is malformed.static ErrorOr<NonnullRefPtr<DisplayList>> create_from_shared_buffer(Properties, Core::AnonymousBuffer, u64 tape_size, u64 run_count);- // Taken at send time: the async scrolling metadata is restamped on every send.Properties properties() const;u64 compatible_visual_context_tree_structural_epoch() const { return m_compatible_visual_context_tree_structural_epoch; }@@ -83,6 +82,9 @@ public:// The Rust storage that holds the list's tape.void const* rust_handle() const { return m_storage; }+ // The list as the scroll logic takes it, with the async scrolling metadata it goes with as IPC encodes an+ // Optional of it.+ RustFFI::FfiDisplayList for_scroll_logic(ReadonlyBytes encoded_async_scrolling_metadata) const;// The sizes a receiver needs to unpack the list from its shared buffer.u64 tape_size() const;diff --git a/Libraries/LibCompositing/DisplayList/DisplayListProperties.ipc b/Libraries/LibCompositing/DisplayList/DisplayListProperties.ipcindex 470b95c59ee..16e29980be2 100644--- a/Libraries/LibCompositing/DisplayList/DisplayListProperties.ipc+++ b/Libraries/LibCompositing/DisplayList/DisplayListProperties.ipc@@ -26,5 +26,4 @@ struct Compositing::DisplayList::Properties {u64 compatible_visual_context_tree_structural_epoch;Optional<Gfx::Color> surface_clear_color;Gfx::Color root_group_color;- Optional<Compositing::DisplayList::AsyncScrollingMetadata> async_scrolling_metadata;}diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex c293c73f936..eaac4085363 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -299,10 +299,18 @@ fn generate_ipc_definitions(manifest_dir: &Path, out_dir: &Path) -> Result<(), B"Services/Compositor/CompositorWebContentClient.ipc","CompositorWebContentClientEndpoint.rs",),+ (+ "Services/Compositor/CompositorWebContentServer.ipc",+ "CompositorWebContentServerEndpoint.rs",+ ),("Services/Compositor/CompositorPresentationClient.ipc","CompositorPresentationClientEndpoint.rs",),+ (+ "Services/Compositor/CompositorPresentationServer.ipc",+ "CompositorPresentationServerEndpoint.rs",+ ),("Services/Compositor/RenderClockClient.ipc","RenderClockClientEndpoint.rs",@@ -350,8 +358,13 @@ fn main() -> Result<(), Box<dyn Error>> {.export.rename.insert("Span".to_string(), "AK::ReadonlySpan".to_string());+ ffi_config+ .export+ .rename+ .insert("EncodedValue".to_string(), "AK::ReadonlyBytes".to_string());ffi_config.includes.push("AK/Span.h".to_string());- // The values WebContent's own entry points take and return, which its headers refer to here.+ // The values the entry points of WebContent and of the compositor's scroll logic take and return, which their+ // headers refer to here.ffi_config.export.include = ["NodeSlotId","FfiFilterFunction",@@ -366,6 +379,7 @@ fn main() -> Result<(), Box<dyn Error>> {"FfiAnimatedContentViewportEffect","FfiTestStickyConstraints","FfiDisplayListReplayCallbacks",+ "FfiDisplayList","FfiEasingDescriptor","FfiEasingKind","FfiLinearEasingPoint",diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rsindex a515d2bd463..fb28d9a89a5 100644--- a/Libraries/LibCompositing/Rust/src/ffi.rs+++ b/Libraries/LibCompositing/Rust/src/ffi.rs@@ -10,7 +10,11 @@use crate::display_list::commands::{ClipNodeIndex, ContextRef, EffectNodeIndex, SpatialNodeIndex};use crate::display_list::storage::storage_from_handle;use crate::node_slot_id::NodeSlotId;+use crate::scrolling::{AccumulatedVisualContextTree, DisplayList};+use libipc_rust::DecodeError;+use libipc_rust::cpp_connection::EncodedValue;use std::ffi::c_void;+use std::sync::Arc;/// # Safety///@@ -756,3 +760,46 @@ pub unsafe extern "C" fn visual_context_tree_test_builder_destroy(builder: *mut// SAFETY: The caller hands over the boxed tree the create call returned.drop(unsafe { Box::from_raw(builder.cast::<crate::visual_context::VisualContextTree>()) });}++/// A C++ display list as the scroll logic takes it: its tape, and what travels beside the tape that the logic reads.+#[repr(C)]+pub struct FfiDisplayList<'a> {+ pub storage: *const c_void,+ pub id: u64,+ pub compatible_visual_context_tree_structural_epoch: u64,+ /// A `Compositing::DisplayList::AsyncScrollingMetadata`, or none.+ pub async_scrolling_metadata: EncodedValue<'a>,+}++impl FfiDisplayList<'_> {+ /// # Safety+ ///+ /// `storage` must be a live display list storage handle.+ pub unsafe fn share(&self) -> Result<DisplayList, DecodeError> {+ let async_scrolling_metadata = self.async_scrolling_metadata.decode()?;+ let storage = self.storage.cast::<crate::display_list::storage::DisplayListStorage>();+ // SAFETY: The caller lends a strong reference to the storage, of which this takes one more.+ let storage = unsafe {+ Arc::increment_strong_count(storage);+ Arc::from_raw(storage)+ };+ Ok(DisplayList::new(+ storage,+ self.id,+ self.compatible_visual_context_tree_structural_epoch,+ async_scrolling_metadata,+ ))+ }+}++/// # Safety+///+/// `visual_context_tree` must be a live retained tree handle.+pub unsafe fn tree_sharing_handle(visual_context_tree: *const c_void) -> AccumulatedVisualContextTree {+ let tree = visual_context_tree.cast::<crate::visual_context::VisualContextTree>();+ // SAFETY: The caller lends a strong reference to the tree, of which this takes one more.+ AccumulatedVisualContextTree::from_arc(unsafe {+ Arc::increment_strong_count(tree);+ Arc::from_raw(tree)+ })+}diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex 4c9bc72e573..7c53276bf58 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -17,6 +17,7 @@ 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;@@ -127,58 +128,9 @@ include!(concat!(env!("OUT_DIR"), "/MouseButton.rs"));include!(concat!(env!("OUT_DIR"), "/TextEditingCommand.rs"));include!(concat!(env!("OUT_DIR"), "/Types.rs"));+include!(concat!(env!("OUT_DIR"), "/CompositorPresentationClientEndpoint.rs"));+include!(concat!(env!("OUT_DIR"), "/CompositorPresentationServerEndpoint.rs"));+include!(concat!(env!("OUT_DIR"), "/CompositorWebContentClientEndpoint.rs"));+include!(concat!(env!("OUT_DIR"), "/CompositorWebContentServerEndpoint.rs"));include!(concat!(env!("OUT_DIR"), "/RenderClockClientEndpoint.rs"));include!(concat!(env!("OUT_DIR"), "/RenderClockServerEndpoint.rs"));--#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-#[repr(transparent)]-pub struct Compositing_ScreenshotRequestId(pub u64);--impl Encode for Compositing_ScreenshotRequestId {- fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {- encoder.encode(&self.0)- }-}--impl Decode for Compositing_ScreenshotRequestId {- const MIN_ENCODED_SIZE: usize = size_of::<u64>();-- fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {- Ok(Self(decoder.decode()?))- }-}--pub type Compositing_CanvasId = crate::display_list::commands::CanvasId;--impl Encode for Compositing_CanvasId {- fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {- encoder.encode(&self.0)- }-}--impl Decode for Compositing_CanvasId {- const MIN_ENCODED_SIZE: usize = size_of::<u64>();-- fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {- Ok(Self(decoder.decode()?))- }-}--include!(concat!(env!("OUT_DIR"), "/CompositorWebContentClientEndpoint.rs"));--#[derive(Clone, Debug, PartialEq, Eq)]-pub struct Gfx_SharedImage(std::convert::Infallible);--impl Encode for Gfx_SharedImage {- fn encode(&self, _encoder: &mut Encoder) -> Result<(), EncodeError> {- match self.0 {}- }-}--impl Decode for Gfx_SharedImage {- fn decode(_decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {- Err(DecodeError::InvalidValue("Gfx::SharedImage"))- }-}--include!(concat!(env!("OUT_DIR"), "/CompositorPresentationClientEndpoint.rs"));diff --git a/Libraries/LibCompositing/Types.ipc b/Libraries/LibCompositing/Types.ipcindex 2799e2a1199..49c5c5a7083 100644--- a/Libraries/LibCompositing/Types.ipc+++ b/Libraries/LibCompositing/Types.ipc@@ -127,7 +127,7 @@ struct Compositing::AppliedScrollRequest {bool moved_the_box;}-[ExistingCpp]+[ExistingCpp, RustDerive=Default]struct Compositing::PendingAsyncScrollUpdates {Optional<Web::UniqueNodeID> document_id;u64 sequence;@@ -174,7 +174,7 @@ struct Compositing::ScrollRequest {bool takes_over_from_momentum;}-[ExistingCpp]+[ExistingCpp, RustDerive=Default]struct Compositing::WheelEventAnswer {bool performed_default_action;Optional<Web::WheelGestureMark> wheel_gesture_mark;diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex ea3aba343f6..60bd961a18d 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(), update.visual_context_tree, update.resource_transaction, 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, IPC::Encoded { update.scroll_state_snapshot }));if (!post(encoded_message))return false;if (display_list_timing_enabled())diff --git a/Services/Compositor/AsyncScrollUpdateOutbox.cpp b/Services/Compositor/AsyncScrollUpdateOutbox.cppdeleted file mode 100644index bd48c7c36ed..00000000000--- a/Services/Compositor/AsyncScrollUpdateOutbox.cpp+++ /dev/null@@ -1,66 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/StdLibExtras.h>-#include <Compositor/AsyncScrollUpdateOutbox.h>--namespace Compositor {--static void set_or_append_pending_scroll_offset(- Vector<Compositing::AsyncScrollOffset>& pending_scroll_offsets,- Compositing::AsyncScrollOffset const& scroll_offset)-{- for (auto& existing : pending_scroll_offsets) {- if (existing.stable_node_id == scroll_offset.stable_node_id) {- existing.merge_later_scroll(scroll_offset);- return;- }- }- pending_scroll_offsets.append(scroll_offset);-}--void AsyncScrollUpdateOutbox::record_scroll_offsets(ReadonlySpan<Compositing::AsyncScrollOffset> scroll_offsets)-{- for (auto const& scroll_offset : scroll_offsets)- set_or_append_pending_scroll_offset(m_pending_scroll_offsets, scroll_offset);-}--void AsyncScrollUpdateOutbox::note_user_scroll_gesture_ended(ReadonlySpan<Web::AsyncScrollNodeStableID> stable_node_ids)-{- for (auto stable_node_id : stable_node_ids) {- if (!m_boxes_whose_user_scroll_gesture_ended.contains_slow(stable_node_id))- m_boxes_whose_user_scroll_gesture_ended.append(stable_node_id);- }-}--bool AsyncScrollUpdateOutbox::has_updates(UserScrollGestureState const& user_scroll_gesture_state) const-{- return !m_pending_scroll_offsets.is_empty()- || !m_completed_operation_ids.is_empty()- || !m_operation_ids_taken_over_by_user_input.is_empty()- || !m_started_user_scrolls.is_empty()- || !m_applied_scroll_requests.is_empty()- || !m_boxes_whose_user_scroll_gesture_ended.is_empty()- || user_scroll_gesture_state != m_published_user_scroll_gesture_state;-}--Compositing::PendingAsyncScrollUpdates AsyncScrollUpdateOutbox::take_updates(UserScrollGestureState user_scroll_gesture_state)-{- Compositing::PendingAsyncScrollUpdates updates;- updates.sequence = ++m_last_publication_sequence;- AK::swap(updates.scroll_offsets, m_pending_scroll_offsets);- AK::swap(updates.completed_operation_ids, m_completed_operation_ids);- AK::swap(updates.operation_ids_taken_over_by_user_input, m_operation_ids_taken_over_by_user_input);- AK::swap(updates.started_user_scrolls, m_started_user_scrolls);- AK::swap(updates.applied_scroll_requests, m_applied_scroll_requests);- AK::swap(updates.boxes_whose_user_scroll_gesture_ended, m_boxes_whose_user_scroll_gesture_ended);- updates.boxes_in_user_scroll_gesture = user_scroll_gesture_state.boxes_in_user_scroll_gesture;- updates.wheel_latched_scroller = user_scroll_gesture_state.wheel_latched_scroller;- m_published_user_scroll_gesture_state = move(user_scroll_gesture_state);- return updates;-}--}diff --git a/Services/Compositor/AsyncScrollUpdateOutbox.h b/Services/Compositor/AsyncScrollUpdateOutbox.hdeleted file mode 100644index c90dcab5cb8..00000000000--- a/Services/Compositor/AsyncScrollUpdateOutbox.h+++ /dev/null@@ -1,48 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Span.h>-#include <AK/Vector.h>-#include <LibCompositing/Scrolling/AsyncScrollingState.h>-#include <LibCompositing/Types.h>--namespace Compositor {--class AsyncScrollUpdateOutbox {-public:- Compositing::AsyncScrollOperationID allocate_operation_id() { return ++m_last_allocated_operation_id; }- void complete_operation(Compositing::AsyncScrollOperationID operation_id) { m_completed_operation_ids.append(operation_id); }- void note_operation_taken_over_by_user_input(Compositing::AsyncScrollOperationID operation_id) { m_operation_ids_taken_over_by_user_input.append(operation_id); }- void record_scroll_offsets(ReadonlySpan<Compositing::AsyncScrollOffset>);- void record_started_user_scroll(Compositing::StartedUserScroll started_user_scroll) { m_started_user_scrolls.append(move(started_user_scroll)); }- void note_user_scroll_gesture_ended(ReadonlySpan<Web::AsyncScrollNodeStableID>);- void note_scroll_request_applied(Compositing::AppliedScrollRequest applied_scroll_request) { m_applied_scroll_requests.append(applied_scroll_request); }-- // What the compositor holds on to, published whenever it changes.- struct UserScrollGestureState {- Vector<Web::AsyncScrollNodeStableID> boxes_in_user_scroll_gesture;- Optional<Web::AsyncScrollNodeStableID> wheel_latched_scroller;-- bool operator==(UserScrollGestureState const&) const = default;- };- bool has_updates(UserScrollGestureState const&) const;- Compositing::PendingAsyncScrollUpdates take_updates(UserScrollGestureState);--private:- Vector<Compositing::AsyncScrollOffset> m_pending_scroll_offsets;- u64 m_last_publication_sequence { 0 };- Compositing::AsyncScrollOperationID m_last_allocated_operation_id { 0 };- Vector<Compositing::AsyncScrollOperationID> m_completed_operation_ids;- Vector<Compositing::AsyncScrollOperationID> m_operation_ids_taken_over_by_user_input;- Vector<Compositing::StartedUserScroll> m_started_user_scrolls;- Vector<Compositing::AppliedScrollRequest> m_applied_scroll_requests;- Vector<Web::AsyncScrollNodeStableID> m_boxes_whose_user_scroll_gesture_ended;- UserScrollGestureState m_published_user_scroll_gesture_state;-};--}diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 0dbca7bb360..546abe4fbe0 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -1,6 +1,5 @@set(SOURCESAnimatedImage.cpp- AsyncScrollUpdateOutbox.cppBackingStoreManager.cppBitmapExport.cppCanvas2DCommandPlayer.cpp@@ -9,8 +8,6 @@ set(SOURCESCompositorCore.cppCompositorState.cppContextPresenter.cpp- ContextScene.cpp- ContextState.cppDisplayListPlayer.cppDisplayListPlayerSkia.cppDisplayListRasterCache.cpp@@ -18,26 +15,20 @@ set(SOURCESConnectionFromClient.cppConnectionFromPresentation.cppConnectionFromWebContent.cpp- ElasticOverscrollController.cppFramePacer.cppHostWebGLContext.cpp- KeyboardScrollController.cppOpenGLContext.cppPaintingSurface.cppPausedDebuggerOverlay.cppPictureInPictureControls.cppRasterizeDisplayList.cppRenderClockConnection.cpp- ScrollFlingController.cpp- ScrollSnapController.cpp- ScrollbarController.cppSkiaBackendContext.cppSkiaUtils.cppVideoFrameHolds.cppVideoFrameSkia.cppVSyncScheduler.cppWebGLObjectMap.cpp- WheelGestureRouting.cpp)invoke_py_generator(@@ -63,7 +54,7 @@ set(GENERATED_SOURCESWebGLCommandReplayer.cpp)-import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME compositor_core FEATURES allocator)+import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME compositor_core FEATURES allocator FFI_HEADER CompositorCoreRustFFI.h)target_link_libraries(compositor_core INTERFACE LibGfx)test_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME compositor_core)diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cppindex e792cfa5320..b0c9fd74d66 100644--- a/Services/Compositor/CompositorCore.cpp+++ b/Services/Compositor/CompositorCore.cpp@@ -5,1176 +5,217 @@*/#include <AK/StdLibExtras.h>-#include <AK/TemporaryChange.h>#include <Compositor/CompositorCore.h>-#include <Compositor/CompositorPresentationClientEndpoint.h>+#include <LibCompositing/RustFFI.h>+#include <LibIPC/Message.h>+#include <LibIPC/RawAttachment.h>+#include <LibIPC/RawMessage.h>namespace Compositor {-CompositorCore::CompositorCore(CompositorCoreHost& host)- : m_host(host)-{-}--void CompositorCore::create_context(Web::CompositorContextId context_id, Optional<u64> page_id, WebContentClientId web_content_client_id)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- VERIFY(!m_contexts.contains(context_id));- if (page_id.has_value())- VERIFY(context_id == Web::compositor_context_id_for_page(*page_id));-- m_contexts.ensure(context_id, [&] {- return make<ContextState>(context_id, page_id, web_content_client_id, m_host);- });-}--void CompositorCore::destroy_context(Web::CompositorContextId context_id)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- VERIFY(context_if_present(context_id));- for (auto& context_entry : m_contexts) {- if (context_entry.key == context_id)- continue;- auto& possible_child_context = *context_entry.value;- auto parent_context_id = possible_child_context.parent_context_id();- if (parent_context_id.has_value() && *parent_context_id == context_id)- possible_child_context.set_parent_context({});- }- m_contexts.remove(context_id);-}--CompositorCore::ContextOwnerCheckResult CompositorCore::check_context_owner(Web::CompositorContextId context_id, WebContentClientId client) const-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto const* context = context_if_present(context_id);- if (!context)- return ContextOwnerCheckResult::ContextUnavailable;- if (!context->is_owned_by(client))- return ContextOwnerCheckResult::ConflictingOwner;-- return ContextOwnerCheckResult::OwnedByClient;-}--void CompositorCore::set_parent_context(Web::CompositorContextId context_id, Optional<Web::CompositorContextId> parent_context_id)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- context->set_parent_context(parent_context_id);-}--void CompositorCore::stop_presenting_to_client(Web::CompositorContextId context_id)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- context->stop_presenting_to_client();-}--void CompositorCore::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- if (!context)- return;- context->viewport_size_updated(viewport_size);-}--void CompositorCore::set_paused_debugger_overlay_is_shown(Web::CompositorContextId context_id, bool is_shown)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- if (!context)- return;- context->set_paused_debugger_overlay_is_shown(is_shown);-}--void CompositorCore::set_bound_presentation(Web::CompositorContextId context_id, Optional<PresentationId> presentation_id)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- context->set_bound_presentation(presentation_id);-}--void CompositorCore::set_scroll_capabilities(Web::CompositorContextId context_id, ContextState::ScrollCapabilities const& capabilities)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- context->set_scroll_capabilities(capabilities);-}+static_assert(IsTriviallyCopyable<Gfx::IntRect>);+static_assert(IsTriviallyCopyable<Gfx::IntSize>);+static_assert(IsTriviallyCopyable<Gfx::FloatPoint>);+static_assert(IsTriviallyCopyable<Gfx::FloatRect>);+static_assert(IsTriviallyCopyable<Gfx::Color>);+static_assert(IsTriviallyCopyable<Compositing::SpatialNodeIndex>);+static_assert(IsTriviallyCopyable<ReadonlyBytes>);-void CompositorCore::install_display_list_update(Web::CompositorContextId context_id, NonnullRefPtr<Compositing::DisplayList> display_list, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::ScrollStateSnapshot&& scroll_state_snapshot, MonotonicTime now)+static void post_message_to_web_content(void* host, u64 client_id, ReadonlyBytes bytes, ReadonlySpan<IPC::RawAttachment> attachments){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- context->install_display_list_update(move(display_list), move(visual_context_tree), move(scroll_state_snapshot), now);+ auto buffer = IPC::adopt_encoded_message(bytes, attachments);+ static_cast<CompositorCoreHost*>(host)->post_message_to_web_content(WebContentClientId { client_id }, buffer);}-bool CompositorCore::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, MonotonicTime now)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- return context->update_visual_context_tree(move(visual_context_tree), now);-}--bool CompositorCore::needs_animation_frames(Web::CompositorContextId context_id, MonotonicTime now)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- return context->needs_animation_frames(now);-}--Optional<FrameInputs> CompositorCore::frame_inputs(Web::CompositorContextId context_id, MonotonicTime now)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- return context->frame_inputs(now);-}--ContextState::ScreenshotInputs CompositorCore::frame_inputs_for_screenshot(Web::CompositorContextId context_id, MonotonicTime now)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- return context->frame_inputs_for_screenshot(now);-}--void CompositorCore::set_visibility(Web::CompositorContextId context_id, Compositing::ContextVisibility visibility, MonotonicTime now)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- if (!context)- return;- if (visibility == Compositing::ContextVisibility::Hidden)- dispatch_scroll_fling_step(context_id, *context, context->end_scroll_fling(), now);- context->set_visibility(visibility);-}--void CompositorCore::timer_fired(Web::CompositorContextId context_id, ContextTimer timer, MonotonicTime now)+static void post_message_to_render_clock_of_web_content(void* host, u64 client_id, ReadonlyBytes bytes, ReadonlySpan<IPC::RawAttachment> attachments){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- if (!context)- return;- auto caret_damage_rect = context->timer_fired(timer, now);- if (caret_damage_rect.has_value())- m_present_requests.append({ context_id, {}, *caret_damage_rect });-}--Vector<PresentRequest> CompositorCore::take_present_requests()-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- return move(m_present_requests);-}--void CompositorCore::update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot&& scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);-- context->update_scroll_state(move(scroll_state_snapshot), move(keyboard_scroll_state));-}--void CompositorCore::invalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);- context->invalidate_wheel_event_listener_state(generation);-}--void CompositorCore::invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- if (auto* context = context_if_present(context_id))- context->invalidate_keyboard_scroll_state(generation);-}--void CompositorCore::handle_and_dispatch_key_event(Web::CompositorContextId context_id, Web::KeyEvent event, bool allow_keyboard_scroll, MonotonicTime now)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- // NB: The presentation connection only passes on input for the contexts bound to it.- auto* context = context_if_present(context_id);- VERIFY(context);- VERIFY(context->bound_presentation().has_value());- auto presentation_id = *context->bound_presentation();- if (!context->can_dispatch_input_to_web_content()) {- // No context could take the event; the UI sends it to WebContent itself.- post_to_presentation<Messages::CompositorPresentationClient::DidNotDispatchInputEvent>(presentation_id, context_id, event.id);- return;- }-- bool later_keys_need_not_wait = false;- if (allow_keyboard_scroll) {- if (auto box = context->box_scrolled_for_key_event(event); box.has_value())- dispatch_scroll_fling_step(context_id, *context, context->end_momentum_scrolling(box.value()), now);- auto result = context->handle_key_event(event, now);- later_keys_need_not_wait = apply_context_update_result(context_id, *context, result) && event.type == Web::KeyEvent::Type::KeyDown;- event.async_scroll_performed_default_action = later_keys_need_not_wait && !result.key_found_nothing_to_scroll;- if (later_keys_need_not_wait && result.key_found_nothing_to_scroll)- event.user_input_scroll_count_with_nothing_to_scroll = context->user_input_scroll_count();- }-- // The scroll updates the event produced reach WebContent ahead of the event itself on the same connection.- publish_pending_async_scroll_updates(context_id, *context);- context->dispatch_key_event_to_web_content(event);- // The compositor forwarded the key event to WebContent, after performing its default action by scrolling if it says so.- post_to_presentation<Messages::CompositorPresentationClient::DidDispatchInputEvent>(presentation_id, context_id, event.id, later_keys_need_not_wait);+ auto buffer = IPC::adopt_encoded_message(bytes, attachments);+ static_cast<CompositorCoreHost*>(host)->post_message_to_render_clock_of_web_content(WebContentClientId { client_id }, buffer);}-void CompositorCore::handle_and_dispatch_mouse_event(Web::CompositorContextId context_id, Web::MouseEvent event, MonotonicTime now)+static void post_message_to_presentation(void* host, u64 presentation_id, ReadonlyBytes bytes, ReadonlySpan<IPC::RawAttachment> attachments){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- // NB: The presentation connection only passes on input for the contexts bound to it.- auto* context = context_if_present(context_id);- VERIFY(context);- VERIFY(context->bound_presentation().has_value());- auto presentation_id = *context->bound_presentation();- auto record_routing = [&](Web::InputRoutingDecision decision, Optional<Web::AsyncScrollNodeStableID> scroller = {}) {- context->input_trace().record({ .input_event_id = event.id, .stage = Web::InputTraceStage::Compositor, .decision = decision, .scroller = scroller });- };- if (!context->can_dispatch_input_to_web_content()) {- record_routing(Web::InputRoutingDecision::NotDispatchedByCompositor);- post_to_presentation<Messages::CompositorPresentationClient::DidNotDispatchInputEvent>(presentation_id, context_id, event.id);- return;- }-- if (event.type == Web::MouseEvent::Type::MouseMove)- context->note_pointer_position(Gfx::FloatPoint { static_cast<float>(event.position.x().value()), static_cast<float>(event.position.y().value()) });- else if (first_is_one_of(event.type, Web::MouseEvent::Type::MouseLeave, Web::MouseEvent::Type::MouseCancel))- context->note_pointer_position({});-- if (event.type == Web::MouseEvent::Type::MouseDown)- dispatch_scroll_fling_step(context_id, *context, context->end_scroll_fling(), now);-- auto is_wheel_event = event.type == Web::MouseEvent::Type::MouseWheel;- bool is_first_wheel_event_with_delta = false;- if (is_wheel_event) {- // A key, or a script's smooth scroll, takes over from momentum, until wheel input other than the momentum takes- // over again.- if (context->absorbs_wheel_event_of_interrupted_momentum(event)) {- record_routing(Web::InputRoutingDecision::MomentumInterrupted);- // The compositor performed the event's whole default action, so the UI hears nothing more about it.- post_to_presentation<Messages::CompositorPresentationClient::DidConsumeInputEvent>(presentation_id, context_id, event.id);- return;- }- auto noted = context->note_wheel_event_from_ui(event, now);- event.wheel_gesture_mark = noted.wheel_gesture_mark;- is_first_wheel_event_with_delta = noted.is_first_wheel_event_with_delta;-- // The UI can send the end of a gesture more than once. An end that arrives during a fling belongs to the- // flicked gesture, so it does not stop the fling.- if (event.scroll_gesture_phase == Web::ScrollGesturePhase::Ended && context->has_active_scroll_fling()) {- record_routing(Web::InputRoutingDecision::GestureEndAbsorbedByFling);- post_to_presentation<Messages::CompositorPresentationClient::DidConsumeInputEvent>(presentation_id, context_id, event.id);- return;- }-- // A new gesture must not continue the gesture of the fling, so the fling ends first.- dispatch_scroll_fling_step(context_id, *context, context->interrupt_scroll_fling(event, now), now);-- // If the gesture continues as a fling, the end of the fling is the end of the gesture.- if (context->presentation_synthesizes_scroll_momentum() && event.scroll_gesture_phase == Web::ScrollGesturePhase::Ended && context->start_scroll_fling_if_flicked(event, now)) {- record_routing(Web::InputRoutingDecision::FlingStarted);- post_to_presentation<Messages::CompositorPresentationClient::DidConsumeInputEvent>(presentation_id, context_id, event.id);- context->request_display_ticks_if_needed(now);- return;- }- }-- ContextState::ContextUpdateResult result;- if (is_wheel_event)- result = scroll_for_wheel_step(context_id, *context, event, WheelStepOrigin::UI, is_first_wheel_event_with_delta, Compositing::AsyncScrollOperationTracking::No, now);- else- result = handle_mouse_event_in_nested_contexts(context_id, *context, event, now);- if (result.nested_context_hand_off.has_value())- record_routing(*result.nested_context_hand_off);- if (result.routing_decision.has_value()) {- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} routed input event {}: {}", context_id, event.id, Web::input_routing_decision_name(*result.routing_decision));- record_routing(*result.routing_decision, result.routed_scroller);- }-- // Asks for the present, publishes the scroll updates the event produced and asks for a rendering update, the last- // two of which reach WebContent ahead of the event itself on the same connection. Those of a nested context- // another process owns go on that process's connection instead, while the event reaches it through the UI.- auto handled = apply_context_update_result(context_id, *context, result);- // A wheel event that lets go of a stretched scroller presents nothing itself; the rebound does from here on. A press- // beside the thumb of a scrollbar scrolls there in an animation too.- context->request_display_ticks_if_needed(now);- if (is_wheel_event) {- event.async_scroll_performed_default_action = handled;- if (!handled)- context->note_wheel_event_left_to_the_page(event);- } else if (handled) {- // The page still sees the events of a drag the compositor scrolls for a scrollbar the display list paints.- if (!result.scrollbar_dragged_by_compositor.has_value()) {- record_routing(Web::InputRoutingDecision::ConsumedByCompositor);- post_to_presentation<Messages::CompositorPresentationClient::DidConsumeInputEvent>(presentation_id, context_id, event.id);- return;- }- event.scrollbar_dragged_by_compositor = result.scrollbar_dragged_by_compositor;- }- record_routing(Web::InputRoutingDecision::ForwardedToPage);- context->dispatch_mouse_event_to_web_content(event, nested_context_scrolled_since_last_frame(context_id));+ auto buffer = IPC::adopt_encoded_message(bytes, attachments);+ static_cast<CompositorCoreHost*>(host)->post_message_to_presentation(PresentationId { presentation_id }, buffer);}-// The content box of a nested context is drawn scaled to the size of its viewport.-static Optional<Gfx::FloatPoint> position_in_nested_context(Compositing::NestedContextHit const& hit, ContextState const& nested_context)+static void request_display_ticks(void* host, u64 context_id){- auto viewport_size = nested_context.viewport_size().to_type<float>();- if (hit.content_box_size.is_empty() || viewport_size.is_empty())- return {};- return Gfx::FloatPoint {- hit.position_in_content_box.x() * viewport_size.width() / hit.content_box_size.width(),- hit.position_in_content_box.y() * viewport_size.height() / hit.content_box_size.height(),- };+ static_cast<CompositorCoreHost*>(host)->request_display_ticks(Web::CompositorContextId { context_id });}-ContextState* CompositorCore::context_still_nested_in(Web::CompositorContextId containing_context_id, Optional<Web::CompositorContextId> context_id)+static void set_timer(void* host, u64 context_id, ContextTimer timer, i64 delay_nanoseconds){- if (!context_id.has_value())- return nullptr;- auto* context = context_if_present(*context_id);- if (!context || !is_nested_in(containing_context_id, *context))- return nullptr;- return context;+ static_cast<CompositorCoreHost*>(host)->set_timer(Web::CompositorContextId { context_id }, timer, AK::Duration::from_nanoseconds(delay_nanoseconds));}-Optional<Gfx::FloatPoint> CompositorCore::position_in_nested_context_ignoring_clips(Web::CompositorContextId presenting_context_id, ContextState& presenting_context, ContextState& nested_context, Gfx::FloatPoint position)+static void cancel_timer(void* host, u64 context_id, ContextTimer timer){- Vector<ContextState*, 4> contexts_from_nested_context_outward;- auto* context = &nested_context;- // A walk up the parents that outlasts the number of contexts went around a loop.- for (size_t remaining_contexts = m_contexts.size(); context != &presenting_context; --remaining_contexts) {- if (remaining_contexts == 0)- return {};- contexts_from_nested_context_outward.append(context);- auto parent_context_id = context->parent_context_id();- if (!parent_context_id.has_value())- return {};- context = *parent_context_id == presenting_context_id ? &presenting_context : context_if_present(*parent_context_id);- if (!context)- return {};- }-- auto* containing_context = &presenting_context;- for (auto* context_in_between : contexts_from_nested_context_outward.in_reverse()) {- auto hit = containing_context->position_in_content_of_nested_context(context_in_between->context_id(), position);- if (!hit.has_value())- return {};- auto position_in_context = position_in_nested_context(*hit, *context_in_between);- if (!position_in_context.has_value())- return {};- position = *position_in_context;- containing_context = context_in_between;- }- return position;+ static_cast<CompositorCoreHost*>(host)->cancel_timer(Web::CompositorContextId { context_id }, timer);}-ContextState::ContextUpdateResult CompositorCore::handle_mouse_event_in_nested_contexts(Web::CompositorContextId context_id, ContextState& context, Web::MouseEvent const& event, MonotonicTime now)+CompositorCore::CompositorCore(CompositorCoreHost& host, bool scrollbars_always_shown){- using Type = Web::MouseEvent::Type;- auto& pointer = context.pointer_in_nested_contexts();-- auto* context_with_captured_scrollbar = context_still_nested_in(context_id, pointer.context_with_captured_scrollbar);- if (!context_with_captured_scrollbar || !context_with_captured_scrollbar->has_captured_scrollbar()) {- pointer.context_with_captured_scrollbar.clear();- context_with_captured_scrollbar = nullptr;- }-- // The nested context presents and publishes what the event changed, and this context reports how the event went.- auto result_of_nested_context = [&](Web::CompositorContextId nested_context_id, ContextState& nested_context, ContextState::ContextUpdateResult const& nested_result, Optional<PendingFrame> frame_of_this_context) {- apply_context_update_result(nested_context_id, nested_context, nested_result);- nested_context.request_display_ticks_if_needed(now);- // Node ids are only unique within the process that made them.- bool ids_are_of_this_process = nested_context.is_owned_by(context.web_content_client_id());- return ContextState::ContextUpdateResult {- .accepted = nested_result.accepted,- .frame_to_present = move(frame_of_this_context),- .scrollbar_dragged_by_compositor = nested_result.scrollbar_dragged_by_compositor,- .routing_decision = nested_result.routing_decision,- .routed_scroller = ids_are_of_this_process ? nested_result.routed_scroller : Optional<Web::AsyncScrollNodeStableID> {},- .nested_context_hand_off = Web::InputRoutingDecision::HandedToNestedContext,- };- };-- auto send_to_context_with_captured_scrollbar = [&](Web::MouseEvent const& event_to_send) {- auto nested_context_id = *pointer.context_with_captured_scrollbar;- auto position = Gfx::FloatPoint {- static_cast<float>(event_to_send.position.x().value()),- static_cast<float>(event_to_send.position.y().value()),- };- // A leave or a cancel has no position of its own.- if (first_is_one_of(event_to_send.type, Type::MouseDown, Type::MouseMove, Type::MouseUp)) {- if (auto position_in_nested_context = position_in_nested_context_ignoring_clips(context_id, context, *context_with_captured_scrollbar, position); position_in_nested_context.has_value())- pointer.last_position_in_context_with_captured_scrollbar = *position_in_nested_context;- }- auto nested_result = context_with_captured_scrollbar->handle_mouse_event_from_containing_context(event_to_send, pointer.last_position_in_context_with_captured_scrollbar, now);- auto result = result_of_nested_context(nested_context_id, *context_with_captured_scrollbar, nested_result, {});- if (!context_with_captured_scrollbar->has_captured_scrollbar()) {- pointer.context_with_captured_scrollbar.clear();- context_with_captured_scrollbar = nullptr;- pointer.context_under_pointer = nested_context_id;- }- return result;- };-- // The scrollbar the pointer was over in the nested context it left is no longer hovered.- auto note_context_under_pointer = [&](Optional<Web::CompositorContextId> nested_context_id) {- if (pointer.context_under_pointer == nested_context_id)- return;- if (auto* context_left = context_still_nested_in(context_id, pointer.context_under_pointer)) {- context_left->note_pointer_position({});- if (auto frame_to_present = context_left->clear_scrollbar_hover(); frame_to_present.has_value())- request_present(*pointer.context_under_pointer, *frame_to_present);- }- pointer.context_under_pointer = nested_context_id;+ RustFFI::FfiCompositorCoreHost ffi_host {+ .host = &host,+ .post_message_to_web_content = Compositor::post_message_to_web_content,+ .post_message_to_render_clock_of_web_content = Compositor::post_message_to_render_clock_of_web_content,+ .post_message_to_presentation = Compositor::post_message_to_presentation,+ .request_display_ticks = Compositor::request_display_ticks,+ .set_timer = Compositor::set_timer,+ .cancel_timer = Compositor::cancel_timer,};-- switch (event.type) {- case Type::MouseDown:- case Type::MouseMove: {- if (context_with_captured_scrollbar) {- if (event.type == Type::MouseMove)- return send_to_context_with_captured_scrollbar(event);- // A press while a drag is still held means the release of that drag never came, so the drag ends there.- auto cancel_event = event.clone_without_browser_data();- cancel_event.type = Type::MouseCancel;- (void)send_to_context_with_captured_scrollbar(cancel_event);- }-- auto result = context.handle_mouse_event(event, now);- if (!result.nested_context_mouse_hit.has_value()) {- note_context_under_pointer({});- return result;- }-- auto frame_of_this_context = result.frame_to_present;- auto containing_context_id = context_id;- auto* containing_context = &context;- Gfx::FloatPoint position;- while (result.nested_context_mouse_hit.has_value()) {- auto hit = *result.nested_context_mouse_hit;- // WebContent names the contexts its display lists draw, so a context only reaches those nested in it.- auto* nested_context = context_if_present(hit.child_context_id);- Optional<Gfx::FloatPoint> position_in_nested_context_content;- if (nested_context && nested_context->parent_context_id() == containing_context_id)- position_in_nested_context_content = position_in_nested_context(hit, *nested_context);- if (!position_in_nested_context_content.has_value()) {- note_context_under_pointer({});- auto declined = ContextState::ContextUpdateResult::declined(Web::InputRoutingDecision::NestedContextUnavailable);- declined.frame_to_present = frame_of_this_context;- declined.nested_context_hand_off = Web::InputRoutingDecision::HandedToNestedContext;- return declined;- }- if (containing_context != &context) {- apply_context_update_result(containing_context_id, *containing_context, result);- containing_context->request_display_ticks_if_needed(now);- }- containing_context_id = hit.child_context_id;- containing_context = nested_context;- position = *position_in_nested_context_content;- result = nested_context->handle_mouse_event_from_containing_context(event, position, now);- }-- note_context_under_pointer(containing_context_id);- if (event.type == Type::MouseDown && containing_context->has_captured_scrollbar()) {- pointer.context_with_captured_scrollbar = containing_context_id;- pointer.last_position_in_context_with_captured_scrollbar = position;- }- return result_of_nested_context(containing_context_id, *containing_context, result, move(frame_of_this_context));- }- case Type::MouseUp:- if (context_with_captured_scrollbar)- return send_to_context_with_captured_scrollbar(event);- return context.handle_mouse_event(event, now);- case Type::MouseLeave:- case Type::MouseCancel: {- // The pointer leaves every nested context it was in, and a cancel ends the drag of one, as in this context.- Optional<ContextState::ContextUpdateResult> result_of_context_with_captured_scrollbar;- Optional<Web::CompositorContextId> context_with_captured_scrollbar_id;- if (context_with_captured_scrollbar) {- context_with_captured_scrollbar_id = pointer.context_with_captured_scrollbar;- result_of_context_with_captured_scrollbar = send_to_context_with_captured_scrollbar(event);- }- if (auto* context_under_pointer = context_still_nested_in(context_id, pointer.context_under_pointer); context_under_pointer && pointer.context_under_pointer != context_with_captured_scrollbar_id) {- auto nested_result = context_under_pointer->handle_mouse_event_from_containing_context(event, {}, now);- apply_context_update_result(*pointer.context_under_pointer, *context_under_pointer, nested_result);- context_under_pointer->request_display_ticks_if_needed(now);- }- pointer.context_under_pointer.clear();-- auto result = context.handle_mouse_event(event, now);- if (!result_of_context_with_captured_scrollbar.has_value())- return result;- result_of_context_with_captured_scrollbar->frame_to_present = result.frame_to_present;- return result_of_context_with_captured_scrollbar.release_value();- }- case Type::MouseWheel:- return context.handle_mouse_event(event, now);- }- VERIFY_NOT_REACHED();+ m_core = RustFFI::compositor_core_create(ffi_host, scrollbars_always_shown);}-// Whether a context nested in the context `context_id` scrolled since the last frame its WebContent presented: the lane-// of the context's document hands a pointer move to the lane of a same-process iframe, which hit tests it in the iframe.-bool CompositorCore::nested_context_scrolled_since_last_frame(Web::CompositorContextId context_id) const+CompositorCore::~CompositorCore(){- for (auto const& entry : m_contexts) {- if (entry.value->scrolled_since_last_frame() && is_nested_in(context_id, *entry.value))- return true;- }- return false;+ RustFFI::compositor_core_destroy(m_core);}-bool CompositorCore::is_nested_in(Web::CompositorContextId containing_context_id, ContextState const& context) const+void CompositorCore::create_context(Web::CompositorContextId context_id, Optional<u64> page_id, WebContentClientId web_content_client_id){- // A walk up the parents that outlasts the number of contexts went around a loop.- auto const* ancestor = &context;- for (size_t remaining_ancestors = m_contexts.size(); ancestor && remaining_ancestors > 0; --remaining_ancestors) {- auto parent_context_id = ancestor->parent_context_id();- if (!parent_context_id.has_value())- return false;- if (*parent_context_id == containing_context_id)- return true;- ancestor = context_if_present(*parent_context_id);- }- return false;+ RustFFI::compositor_core_create_context(m_core, context_id.value(), page_id.has_value(), page_id.value_or(0), web_content_client_id.value());}-ContextState::ContextUpdateResult CompositorCore::scroll_for_wheel_step(Web::CompositorContextId context_id, ContextState& context, Web::MouseEvent const& event, WheelStepOrigin origin, bool is_first_wheel_event_with_delta, Compositing::AsyncScrollOperationTracking operation_tracking, MonotonicTime now)+void CompositorCore::destroy_context(Web::CompositorContextId context_id){- auto gesture_id = context.wheel_gesture_id();- auto listener_context_id = context.wheel_event_listener_context().value_or(context_id);- auto* listener_context = listener_context_id == context_id ? &context : context_still_nested_in(context_id, listener_context_id);- auto listener_gate = listener_context- ? listener_context->wheel_event_listener_gate(gesture_id)- : ContextState::WheelEventListenerGate { .reason_to_hold_latched_steps_back = Web::InputRoutingDecision::NestedContextUnavailable };-- ContextState::ContextUpdateResult result;- bool presents_frame = false;- if (listener_context && listener_context != &context && listener_gate.page_let_the_gesture_through && !context.has_wheel_latch_for_gesture(gesture_id)) {- // The page of a nested context let the gesture through while nothing took its steps, so they go to that context- // again rather than to the page.- auto step = ContextState::WheelStep::for_wheel_event(event, gesture_id, operation_tracking);- auto position = position_in_nested_context_ignoring_clips(context_id, context, *listener_context, step.position);- if (!position.has_value())- return ContextState::ContextUpdateResult::declined(Web::InputRoutingDecision::NestedContextUnavailable);- step.position = *position;- auto applied_step = route_wheel_step_the_page_let_through(context_id, context, listener_context_id, *listener_context, step, {}, {}, now);- result = move(applied_step.result);- result.nested_context_hand_off = Web::InputRoutingDecision::HandedToNestedContext;- presents_frame = applied_step.presents_frame;- } else {- switch (origin) {- case WheelStepOrigin::UI:- result = context.handle_wheel_event(event, is_first_wheel_event_with_delta, listener_gate, now);- break;- case WheelStepOrigin::Fling:- result = context.scroll_for_fling_step(event, listener_gate, now);- break;- case WheelStepOrigin::MainThread:- result = context.scroll_for_wheel_event_from_main_thread(event, is_first_wheel_event_with_delta, listener_gate, operation_tracking, now);- break;- }- presents_frame = result.frame_to_present.has_value();- if (result.nested_context_wheel_step.has_value()) {- auto applied_step = hand_wheel_step_to_nested_context(context_id, context, event, *result.nested_context_wheel_step, listener_gate, operation_tracking, now);- result = move(applied_step.result);- presents_frame = applied_step.presents_frame;- }- }-- // If the compositor accepts a momentum step of the fling but does not scroll, the scroller is at its edge.- // Alternatively, a snap scroll uses the step. The next display tick ends the fling.- if (origin == WheelStepOrigin::Fling && event.scroll_gesture_phase == Web::ScrollGesturePhase::Momentum && result.accepted && !presents_frame)- context.end_scroll_fling_on_next_step();- return result;+ RustFFI::compositor_core_destroy_context(m_core, context_id.value());}-CompositorCore::AppliedWheelStep CompositorCore::apply_wheel_step_result(Web::CompositorContextId context_id, ContextState& context, ContextState::ContextUpdateResult const& result, WebContentClientId reporting_client, MonotonicTime now)+CompositorCore::ContextOwnerCheckResult CompositorCore::check_context_owner(Web::CompositorContextId context_id, WebContentClientId client) const{- apply_context_update_result(context_id, context, result);- context.request_display_ticks_if_needed(now);- // Node ids are only unique within the process that made them, and only that process follows the operations of the- // context.- bool ids_are_of_reporting_process = context.is_owned_by(reporting_client);- return {- .result = {- .accepted = result.accepted,- .routing_decision = result.routing_decision,- .routed_scroller = ids_are_of_reporting_process ? result.routed_scroller : Optional<Web::AsyncScrollNodeStableID> {},- .tracked_scroll_operation = ids_are_of_reporting_process ? result.tracked_scroll_operation : Optional<ContextState::TrackedScrollOperation> {},- },- .presents_frame = result.frame_to_present.has_value(),- };+ return RustFFI::compositor_core_check_context_owner(m_core, context_id.value(), client.value());}-CompositorCore::AppliedWheelStep CompositorCore::hand_wheel_step_to_nested_context(Web::CompositorContextId context_id, ContextState& context, Web::MouseEvent const& event, ContextState::NestedContextWheelStep const& nested_step, ContextState::WheelEventListenerGate const& listener_gate, Compositing::AsyncScrollOperationTracking operation_tracking, MonotonicTime now)+void CompositorCore::set_parent_context(Web::CompositorContextId context_id, Optional<Web::CompositorContextId> parent_context_id){- auto step = ContextState::WheelStep::for_wheel_event(event, context.wheel_gesture_id(), operation_tracking);-- if (!nested_step.hit.has_value()) {- auto* nested_context = context_if_present(nested_step.context_id);- if (!nested_context || !is_nested_in(context_id, *nested_context)) {- context.forget_wheel_gesture_latch();- return { ContextState::ContextUpdateResult::declined(Web::InputRoutingDecision::NestedContextUnavailable) };- }- // A blocking listener added during the gesture holds its later steps back until the page lets one through.- if (listener_gate.reason_to_hold_latched_steps_back.has_value())- return { ContextState::ContextUpdateResult::declined(*listener_gate.reason_to_hold_latched_steps_back) };- auto admission = listener_gate.page_let_the_gesture_through ? ContextState::WheelStepAdmission::LetThroughByThePage : ContextState::WheelStepAdmission::ByThisPage;- auto nested_result = nested_context->take_latched_wheel_step_from_containing_context(step, admission, now);- if (nested_result.routing_decision == Web::InputRoutingDecision::NestedContextUnavailable)- context.forget_wheel_gesture_latch();- return apply_wheel_step_result(nested_step.context_id, *nested_context, nested_result, context.web_content_client_id(), now);- }-- auto first_step = first_wheel_step_in_nested_contexts(context_id, *nested_step.hit, step.delta_in_css_pixels, step.wheel_delta_precision);- context.set_wheel_event_listener_context(first_step.innermost_context_id);- auto& taking_context = first_step.taking_context;- if (!taking_context.has_value()) {- auto result = context.scroll_for_wheel_event_passed_on_by_nested_context(event, operation_tracking, now);- result.nested_context_hand_off = Web::InputRoutingDecision::NestedContextPassedStepOn;- return { .result = result, .presents_frame = result.frame_to_present.has_value() };- }-- AppliedWheelStep applied_step;- if (taking_context->context && taking_context->route.kind != ContextState::FirstWheelStepRoute::Kind::Declined) {- step.position = taking_context->position;- auto nested_result = taking_context->context->take_first_wheel_step_from_containing_context(taking_context->route, step, now);- applied_step = apply_wheel_step_result(taking_context->context_id, *taking_context->context, nested_result, context.web_content_client_id(), now);- context.latch_wheel_gesture_to_nested_context(taking_context->context_id, applied_step.result.routed_scroller, step.scroll_gesture_phase);- } else {- applied_step.result = ContextState::ContextUpdateResult::declined(taking_context->route.decision);- }- applied_step.result.nested_context_hand_off = Web::InputRoutingDecision::HandedToNestedContext;- return applied_step;+ RustFFI::compositor_core_set_parent_context(m_core, context_id.value(), parent_context_id.has_value(), parent_context_id.value_or({}).value());}-CompositorCore::FirstWheelStepInNestedContexts CompositorCore::first_wheel_step_in_nested_contexts(Web::CompositorContextId context_id, Compositing::NestedContextHit hit, Gfx::FloatPoint delta_in_css_pixels, Web::WheelDeltaPrecision wheel_delta_precision)+void CompositorCore::stop_presenting_to_client(Web::CompositorContextId context_id){- using Kind = ContextState::FirstWheelStepRoute::Kind;- // The contexts the step went into, outermost first, each nested in the one before.- Vector<NestedContextTakingWheelStep, 4> contexts;- auto containing_context_id = context_id;- while (true) {- auto declined_by_unavailable_context = [&] {- return FirstWheelStepInNestedContexts {- .innermost_context_id = hit.child_context_id,- .taking_context = NestedContextTakingWheelStep { .context_id = hit.child_context_id, .route = { Kind::Declined, Web::InputRoutingDecision::NestedContextUnavailable } },- };- };- // WebContent names the contexts its display lists draw, so a context only reaches those nested in it.- auto* nested_context = context_if_present(hit.child_context_id);- if (!nested_context || nested_context->parent_context_id() != containing_context_id)- return declined_by_unavailable_context();- auto position = position_in_nested_context(hit, *nested_context);- if (!position.has_value())- return declined_by_unavailable_context();- auto route = nested_context->route_first_wheel_step_from_containing_context(*position, delta_in_css_pixels, wheel_delta_precision, Compositing::NestedContextRegions::HandToNestedContext, ContextState::WheelStepAdmission::ByThisPage);- contexts.append({ .context_id = hit.child_context_id, .context = nested_context, .position = *position, .route = route });- if (route.kind != Kind::NestedContext)- break;- containing_context_id = hit.child_context_id;- hit = *route.nested_context_hit;- }-- // What a nested context passes on goes to whatever is painted under it in the context it is nested in, whose page- // does not see the step.- auto innermost_context_id = contexts.last().context_id;- while (contexts.last().route.kind == Kind::PassedOn) {- contexts.take_last();- if (contexts.is_empty())- return { .innermost_context_id = innermost_context_id };- auto& containing_context = contexts.last();- containing_context.route = containing_context.context->route_first_wheel_step_from_containing_context(containing_context.position, delta_in_css_pixels, wheel_delta_precision, Compositing::NestedContextRegions::Ignore, ContextState::WheelStepAdmission::PassedOnByNestedContext);- }- return { .innermost_context_id = innermost_context_id, .taking_context = contexts.take_last() };+ RustFFI::compositor_core_stop_presenting_to_client(m_core, context_id.value());}-// The page of one process scrolls a context of another process only by what the UI left to the page in the gesture, so-// that a page cannot scroll the document around it at will.-static bool page_may_scroll_in(ContextState const& context, ContextState& routing_context, Optional<WebContentClientId> page_client, ContextState::WheelStep const& step)+void CompositorCore::set_visibility(Web::CompositorContextId context_id, Compositing::ContextVisibility visibility, MonotonicTime now){- return !page_client.has_value() || context.is_owned_by(*page_client) || routing_context.take_wheel_delta_left_to_the_page(step.delta_in_css_pixels);+ RustFFI::compositor_core_set_visibility(m_core, context_id.value(), visibility == Compositing::ContextVisibility::Visible, now.nanoseconds());}-CompositorCore::AppliedWheelStep CompositorCore::route_wheel_step_the_page_let_through(Web::CompositorContextId routing_context_id, ContextState& routing_context, Web::CompositorContextId listener_context_id, ContextState& listener_context, ContextState::WheelStep step, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, Optional<WebContentClientId> page_client, MonotonicTime now)+void CompositorCore::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size){- using Kind = ContextState::FirstWheelStepRoute::Kind;- auto const& reporting_client = page_client.has_value() ? *page_client : routing_context.web_content_client_id();- auto declined = [](Web::InputRoutingDecision decision) {- return AppliedWheelStep { .result = ContextState::ContextUpdateResult::declined(decision) };- };-- auto context_id = listener_context_id;- auto* context = &listener_context;- // A walk up the parents that outlasts the number of contexts went around a loop.- for (size_t remaining_contexts = m_contexts.size(); remaining_contexts > 0; --remaining_contexts) {- if (context == &routing_context) {- if (!page_may_scroll_in(routing_context, routing_context, page_client, step))- return declined(Web::InputRoutingDecision::StepExceedsInputLeftToThePage);- auto result = routing_context.scroll_for_first_wheel_step_the_page_let_through(step, scroll_chain, now);- return apply_wheel_step_result(routing_context_id, routing_context, result, reporting_client, now);- }-- auto route = context->route_first_wheel_step_from_containing_context(step.position, step.delta_in_css_pixels, step.wheel_delta_precision, Compositing::NestedContextRegions::Ignore, ContextState::WheelStepAdmission::LetThroughByThePage, scroll_chain);- if (first_is_one_of(route.kind, Kind::ScrollNode, Kind::Kept)) {- if (!page_may_scroll_in(*context, routing_context, page_client, step))- return declined(Web::InputRoutingDecision::StepExceedsInputLeftToThePage);- auto nested_result = context->take_first_wheel_step_from_containing_context(route, step, now);- auto latched_scroller = context->is_owned_by(routing_context.web_content_client_id()) ? nested_result.routed_scroller : Optional<Web::AsyncScrollNodeStableID> {};- routing_context.latch_wheel_gesture_to_nested_context(context_id, latched_scroller, step.scroll_gesture_phase);- return apply_wheel_step_result(context_id, *context, nested_result, reporting_client, now);- }- if (route.kind != Kind::PassedOn)- return declined(route.decision);-- // What a nested context passes on goes to whatever is painted under it in the context it is nested in.- auto parent_context_id = context->parent_context_id();- auto* parent_context = parent_context_id.has_value() ? context_if_present(*parent_context_id) : nullptr;- if (!parent_context)- return declined(Web::InputRoutingDecision::NestedContextUnavailable);- auto position = parent_context->position_of_nested_context_position(context_id, step.position, context->viewport_size());- if (!position.has_value())- return declined(Web::InputRoutingDecision::NestedContextUnavailable);- step.position = *position;- scroll_chain = {};- context_id = *parent_context_id;- context = parent_context;- }- return declined(Web::InputRoutingDecision::NestedContextUnavailable);+ RustFFI::compositor_core_viewport_size_updated(m_core, context_id.value(), viewport_size);}-Optional<Web::CompositorContextId> CompositorCore::routing_context_of_wheel_gesture(Web::CompositorContextId context_id, u64 gesture_id)+void CompositorCore::set_paused_debugger_overlay_is_shown(Web::CompositorContextId context_id, bool is_shown){- // A walk up the parents that outlasts the number of contexts went around a loop.- Optional<Web::CompositorContextId> candidate_context_id = context_id;- for (size_t remaining_contexts = m_contexts.size(); candidate_context_id.has_value() && remaining_contexts > 0; --remaining_contexts) {- auto* candidate_context = context_if_present(*candidate_context_id);- if (!candidate_context)- return {};- if (candidate_context->wheel_gesture_id() == gesture_id)- return candidate_context_id;- candidate_context_id = candidate_context->parent_context_id();- }- return {};+ RustFFI::compositor_core_set_paused_debugger_overlay_is_shown(m_core, context_id.value(), is_shown);}-void CompositorCore::dispatch_scroll_fling_step(Web::CompositorContextId context_id, ContextState& context, Optional<Web::MouseEvent> event, MonotonicTime now)+void CompositorCore::set_bound_presentation(Web::CompositorContextId context_id, Optional<PresentationId> presentation_id){- // Send each fling step on the same route as a wheel event from the UI.- if (!event.has_value())- return;- auto result = scroll_for_wheel_step(context_id, context, *event, WheelStepOrigin::Fling, false, Compositing::AsyncScrollOperationTracking::No, now);- if (result.nested_context_hand_off.has_value())- context.input_trace().record({ .input_event_id = event->id, .stage = Web::InputTraceStage::Compositor, .decision = *result.nested_context_hand_off });- if (result.routing_decision.has_value())- context.input_trace().record({ .input_event_id = event->id, .stage = Web::InputTraceStage::Compositor, .decision = *result.routing_decision, .scroller = result.routed_scroller });- event->async_scroll_performed_default_action = apply_context_update_result(context_id, context, result);- if (!event->async_scroll_performed_default_action)- context.note_wheel_event_left_to_the_page(*event);- context.request_display_ticks_if_needed(now);- context.dispatch_mouse_event_to_web_content(*event);+ RustFFI::compositor_core_set_bound_presentation(m_core, context_id.value(), presentation_id.has_value(), presentation_id.value_or({}).value());}-// A pinch is a ctrl+wheel event first, to the document under it, whose blocking wheel event listeners may cancel it-// before anything zooms. Only the documents at the position can see that event.-bool CompositorCore::page_under_pinch_may_cancel_it(Web::CompositorContextId context_id, ContextState& context, Gfx::FloatPoint position)+void CompositorCore::set_scroll_capabilities(Web::CompositorContextId context_id, ScrollCapabilities const& capabilities){- auto containing_context_id = context_id;- auto* containing_context = &context;- // A walk down the nested contexts that outlasts the number of contexts went around a loop.- for (size_t remaining_contexts = m_contexts.size(); remaining_contexts > 0; --remaining_contexts) {- if (containing_context->page_may_cancel_pinch_at(position))- return true;- auto hit = containing_context->nested_context_for_wheel_at(position);- if (!hit.has_value())- return false;- // NB: Nothing is known yet of the listeners of a context that is not available.- auto* nested_context = context_if_present(hit->child_context_id);- if (!nested_context || nested_context->parent_context_id() != containing_context_id)- return true;- auto position_in_nested = position_in_nested_context(*hit, *nested_context);- if (!position_in_nested.has_value())- return true;- containing_context_id = hit->child_context_id;- containing_context = nested_context;- position = *position_in_nested;- }- return true;+ RustFFI::compositor_core_set_scroll_capabilities(m_core, context_id.value(), capabilities);}-void CompositorCore::handle_and_dispatch_pinch_event(Web::CompositorContextId context_id, Web::PinchEvent event)+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){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- // NB: The presentation connection only passes on input for the contexts bound to it.- auto* context = context_if_present(context_id);- VERIFY(context);- VERIFY(context->bound_presentation().has_value());- auto presentation_id = *context->bound_presentation();- if (!context->can_dispatch_input_to_web_content()) {- post_to_presentation<Messages::CompositorPresentationClient::DidNotDispatchInputEvent>(presentation_id, context_id, event.id);- return;- }-- // The first step of a gesture decides for the steps after it: a gesture the page let through zooms from here on,- // whatever listeners have appeared since, and any other leaves each step to the page, wherever the pinch has moved.- // A page that already let this step through leaves only the zoom to do.- Gfx::FloatPoint position { static_cast<float>(event.position.x().value()), static_cast<float>(event.position.y().value()) };- auto may_zoom = event.continues_gesture ? context->pinch_gesture_was_let_through() : !page_under_pinch_may_cancel_it(context_id, *context, position);- if (event.wheel_event_was_dispatched || may_zoom)- event.async_zoom_performed_default_action = apply_context_update_result(context_id, *context, context->handle_pinch_event(event));- context->set_pinch_gesture_was_let_through(event.async_zoom_performed_default_action);-- // The scroll updates the event produced reach WebContent ahead of the event itself on the same connection.- publish_pending_async_scroll_updates(context_id, *context);- context->dispatch_pinch_event_to_web_content(event);- post_to_presentation<Messages::CompositorPresentationClient::DidDispatchInputEvent>(presentation_id, context_id, event.id, event.async_zoom_performed_default_action);+ 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());}-Compositing::WheelEventAnswer CompositorCore::wheel_event_answer_for(AppliedWheelStep const& applied_step, Optional<Web::WheelGestureMark> wheel_gesture_mark)+bool CompositorCore::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree const& visual_context_tree, MonotonicTime now){- auto const& tracked_scroll_operation = applied_step.result.tracked_scroll_operation;- return {- .performed_default_action = applied_step.result.accepted,- .wheel_gesture_mark = wheel_gesture_mark,- .operation_id = tracked_scroll_operation.map([](auto const& operation) { return operation.operation_id; }),- .operation_context_id = tracked_scroll_operation.map([](auto const& operation) { return operation.context_id; }),- .routing_decision = applied_step.result.routing_decision,- .routed_scroller = applied_step.result.routed_scroller,- };+ return RustFFI::compositor_core_update_visual_context_tree(m_core, context_id.value(), visual_context_tree.rust_handle(), now.nanoseconds());}-Compositing::WheelEventAnswer CompositorCore::take_wheel_event_from_main_thread(Web::CompositorContextId context_id, Web::MouseEvent const& event, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelEventRouting routing, MonotonicTime now)+bool CompositorCore::needs_animation_frames(Web::CompositorContextId context_id, MonotonicTime now){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);-- auto noted = context->note_wheel_event_from_main_thread(event, now);- if (routing == Compositing::WheelEventRouting::AfterDispatch)- return { .wheel_gesture_mark = noted.wheel_gesture_mark };- auto result = scroll_for_wheel_step(context_id, *context, event, WheelStepOrigin::MainThread, noted.is_first_wheel_event_with_delta, operation_tracking, now);- return wheel_event_answer_for(apply_wheel_step_result(context_id, *context, result, context->web_content_client_id(), now), noted.wheel_gesture_mark);+ return RustFFI::compositor_core_needs_animation_frames(m_core, context_id.value(), now.nanoseconds());}-Compositing::WheelEventAnswer CompositorCore::scroll_for_wheel_event_the_page_let_through(Web::CompositorContextId listener_context_id, Compositing::WheelStepLetThrough const& let_through, Compositing::AsyncScrollOperationTracking operation_tracking, WebContentClientId page_client, MonotonicTime now)+static void receive_frame_inputs(void* receiver, RustFFI::FfiFrameInputs const* lent){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* listener_context = context_if_present(listener_context_id);- VERIFY(listener_context);- if (listener_context->document_id() != let_through.document_id)- return { .routing_decision = Web::InputRoutingDecision::ScrollerInOtherDocument };-- auto gesture_id = let_through.wheel_gesture_mark.gesture_id;- // A step that moves along no axis goes to the page as no wheel event, so the page had no say in letting it through,- // and it decides nothing for the steps after it.- if (!let_through.delta_in_css_pixels.is_zero())- listener_context->note_page_let_wheel_gesture_through(gesture_id);- ContextState::WheelStep step {- .position = let_through.position,- .delta_in_css_pixels = let_through.delta_in_css_pixels,- .wheel_delta_precision = let_through.wheel_delta_precision,- .scroll_gesture_phase = let_through.scroll_gesture_phase,- .gesture_id = gesture_id,- .operation_tracking = operation_tracking,+ 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,};- auto scroll_chain = let_through.scroll_chain.span();- auto answer = [&](AppliedWheelStep const& applied_step) { return wheel_event_answer_for(applied_step, let_through.wheel_gesture_mark); };- auto declined = [&](Web::InputRoutingDecision decision) { return answer({ .result = ContextState::ContextUpdateResult::declined(decision) }); };-- // A step of a gesture that the contexts around the page have moved past still scrolls, as the page let it.- auto routing_context_id = routing_context_of_wheel_gesture(listener_context_id, gesture_id);- auto* routing_context = routing_context_id.has_value() ? context_if_present(*routing_context_id) : nullptr;- if (!routing_context || routing_context->wheel_step_was_overtaken(step.scroll_gesture_phase, let_through.wheel_gesture_mark.step_number)) {- auto result = listener_context->scroll_for_overtaken_wheel_step(step, scroll_chain, now);- return answer(apply_wheel_step_result(listener_context_id, *listener_context, result, page_client, now));- }-- routing_context->set_wheel_event_listener_context(listener_context_id);- // The end of a gesture lets go of the scroller it stretched.- if (step.scroll_gesture_phase == Web::ScrollGesturePhase::Ended)- routing_context->end_wheel_gesture_stretch(now);-- // A latched scroller that the page no longer has around the target of the step is gone from the page, and the step- // is routed afresh.- bool latch_is_to_scroller_of_this_page = *routing_context_id == listener_context_id && !routing_context->nested_context_of_wheel_latch().has_value();- if (latch_is_to_scroller_of_this_page && !scroll_chain.is_empty()) {- if (auto latched_scroller = routing_context->wheel_latched_scroller(); latched_scroller.has_value() && !scroll_chain.contains_slow(*latched_scroller))- routing_context->forget_wheel_latch_of_gesture(gesture_id);- }-- if (routing_context->has_wheel_latch_for_gesture(gesture_id)) {- if (auto nested_context_id = routing_context->nested_context_of_wheel_latch(); nested_context_id.has_value()) {- auto* nested_context = context_still_nested_in(*routing_context_id, nested_context_id);- if (!nested_context) {- routing_context->forget_wheel_latch_of_gesture(gesture_id);- return declined(Web::InputRoutingDecision::NestedContextUnavailable);- }- if (!page_may_scroll_in(*nested_context, *routing_context, page_client, step))- return declined(Web::InputRoutingDecision::StepExceedsInputLeftToThePage);- auto nested_result = nested_context->take_latched_wheel_step_from_containing_context(step, ContextState::WheelStepAdmission::LetThroughByThePage, now);- return answer(apply_wheel_step_result(*nested_context_id, *nested_context, nested_result, page_client, now));- }- if (!page_may_scroll_in(*routing_context, *routing_context, page_client, step))- return declined(Web::InputRoutingDecision::StepExceedsInputLeftToThePage);- if (auto result = routing_context->scroll_for_latched_wheel_step_the_page_let_through(step, now); result.has_value())- return answer(apply_wheel_step_result(*routing_context_id, *routing_context, *result, page_client, now));- }-- return answer(route_wheel_step_the_page_let_through(*routing_context_id, *routing_context, listener_context_id, *listener_context, step, scroll_chain, page_client, now));-}--void CompositorCore::forget_wheel_gesture_the_page_canceled(Web::CompositorContextId listener_context_id, u64 gesture_id)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* listener_context = context_if_present(listener_context_id);- if (!listener_context)- return;- listener_context->forget_page_let_wheel_gesture_through(gesture_id);- // The listener scrolls by itself, so the next step of the gesture is routed afresh.- if (auto routing_context_id = routing_context_of_wheel_gesture(listener_context_id, gesture_id); routing_context_id.has_value())- context_if_present(*routing_context_id)->forget_wheel_latch_of_gesture(gesture_id);}-static bool scroll_request_smoothly_scrolls_for_script(Compositing::ScrollRequest const& scroll_request)-{- return scroll_request.smooth_scroll.has_value() && scroll_request.smooth_scroll->initiator == Compositing::SmoothScrollInitiator::Programmatic;-}--void CompositorCore::apply_scroll_requests(Web::CompositorContextId context_id, ReadonlySpan<Compositing::ScrollRequest> scroll_requests, MonotonicTime now)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- if (!context)- return;-- // A script's smooth scroll of a box ends the momentum scrolling it, as a key's does. A script's instant scroll only- // moves the box, and the momentum goes on from there: pages keep their content in place under a flick that way.- for (auto const& scroll_request : scroll_requests) {- if (scroll_request.takes_over_from_momentum || scroll_request_smoothly_scrolls_for_script(scroll_request))- dispatch_scroll_fling_step(context_id, *context, context->end_momentum_scrolling(scroll_request.stable_node_id), now);- }- if (auto frame_to_present = context->apply_scroll_requests(scroll_requests, now); frame_to_present.has_value())- request_present(context_id, frame_to_present.value());- context->request_display_ticks_if_needed(now);- publish_pending_async_scroll_updates(context_id, *context);-}--Compositing::PendingAsyncScrollUpdates CompositorCore::take_pending_async_scroll_updates(Web::CompositorContextId context_id)-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- VERIFY(context);-- return context->take_pending_async_scroll_updates();-}--void CompositorCore::publish_pending_async_scroll_updates(Web::CompositorContextId, ContextState& context)+Optional<FrameInputs> CompositorCore::frame_inputs(Web::CompositorContextId context_id, MonotonicTime now){- context.publish_pending_async_scroll_updates();+ Optional<FrameInputs> frame_inputs;+ RustFFI::compositor_core_frame_inputs(m_core, context_id.value(), now.nanoseconds(), &frame_inputs, receive_frame_inputs);+ return frame_inputs;}-void CompositorCore::request_present(Web::CompositorContextId context_id, PendingFrame const& frame)+CompositorCore::ScreenshotInputs CompositorCore::frame_inputs_for_screenshot(Web::CompositorContextId context_id, MonotonicTime now){- m_present_requests.append({ context_id, frame.viewport_rect, frame.forced_damage_rect });+ 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 };}DisplayTickResult CompositorCore::display_tick(Web::CompositorContextId context_id, MonotonicTime frame_time, MonotonicTime now, DisplayTickInputs const& inputs){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context_pointer = context_if_present(context_id);- VERIFY(context_pointer);- auto& context = *context_pointer;-- auto has_active_animation_on_display = (context.needs_animation_frames(now) || inputs.ui_overlay_fades_need_frame) && inputs.context_is_on_tick_display;- auto presents_on_display = inputs.present_is_scheduled_on_tick_display || has_active_animation_on_display;- if (presents_on_display) {- if (inputs.context_is_on_tick_display)- dispatch_scroll_fling_step(context_id, context, context.take_scroll_fling_step(frame_time), frame_time);- if (auto animation_frame = context.advance_smooth_scroll_animations(frame_time); animation_frame.has_value())- m_present_requests.append({ context_id, *animation_frame, {}, PresentScheduling::WithDisplayTickInProgress });- if (auto rebound_frame = context.advance_elastic_overscroll_rebounds(frame_time); rebound_frame.has_value())- m_present_requests.append({ context_id, *rebound_frame, {}, PresentScheduling::WithDisplayTickInProgress });- if (auto damage_rect = context.advance_scrollbar_fades_and_return_damage_rect(frame_time); !damage_rect.is_empty())- m_present_requests.append({ context_id, {}, damage_rect, PresentScheduling::WithDisplayTickInProgress });- }-- // A render clock tick goes to the process's render clock thread, beside what its main thread is doing, with- // where the compositor has scrolled to for this vsync, which that main thread may not have taken in yet.- if (inputs.clock_tick_interval_in_milliseconds.has_value())- context.post_clock_tick(frame_time, *inputs.clock_tick_interval_in_milliseconds);-- if (presents_on_display) {- publish_pending_async_scroll_updates(context_id, context);- if (context.visual_animations_need_frame(now)) {- context.advance_visual_animations(frame_time);- m_present_requests.append({ context_id, {}, {}, PresentScheduling::WithDisplayTickInProgress });- }- }- return { .presents_on_display = presents_on_display, .needs_animation_frames = context.needs_animation_frames(now) };-}--ContextState* CompositorCore::context_if_present(Web::CompositorContextId context_id)-{- auto it = m_contexts.find(context_id);- if (it == m_contexts.end())- return nullptr;- return it->value.ptr();-}--ContextState const* CompositorCore::context_if_present(Web::CompositorContextId context_id) const-{- auto it = m_contexts.find(context_id);- if (it == m_contexts.end())- return nullptr;- return it->value.ptr();+ return RustFFI::compositor_core_display_tick(+ m_core, context_id.value(), frame_time.nanoseconds(), now.nanoseconds(),+ {+ .context_is_on_tick_display = inputs.context_is_on_tick_display,+ .present_is_scheduled_on_tick_display = inputs.present_is_scheduled_on_tick_display,+ .ui_overlay_fades_need_frame = inputs.ui_overlay_fades_need_frame,+ .clock_tick_is_due = inputs.clock_tick_interval_in_milliseconds.has_value(),+ .clock_tick_interval_in_milliseconds = inputs.clock_tick_interval_in_milliseconds.value_or(0),+ });}-String CompositorCore::scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller) const-{- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto const* context = context_if_present(context_id);- if (!context)- return {};- return context->scroll_state_for_testing(stretched_scroller);-}--Optional<Compositing::FirstWheelStepRouteForTesting> CompositorCore::route_first_wheel_step_for_testing(Web::CompositorContextId context_id, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels)+void CompositorCore::timer_fired(Web::CompositorContextId context_id, ContextTimer timer, MonotonicTime now){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- if (!context)- return {};- if (!context->presents_to_client() || !context->may_hand_first_wheel_steps_to_nested_contexts())- return context->route_first_wheel_step_for_testing(position, delta_in_css_pixels, Compositing::NestedContextRegions::LeaveToMainThread);- auto hit = context->nested_context_for_wheel_at(position);- if (!hit.has_value())- return context->route_first_wheel_step_for_testing(position, delta_in_css_pixels, Compositing::NestedContextRegions::HandToNestedContext);- auto taking_context = first_wheel_step_in_nested_contexts(context_id, *hit, delta_in_css_pixels, Web::WheelDeltaPrecision::Precise).taking_context;- if (!taking_context.has_value())- return context->route_first_wheel_step_for_testing(position, delta_in_css_pixels, Compositing::NestedContextRegions::Ignore);- // Node ids are only unique within the process that made them.- bool ids_are_of_this_process = taking_context->context && taking_context->context->is_owned_by(context->web_content_client_id());- Compositing::FirstWheelStepRouteForTesting route { .route = { taking_context->route.decision }, .document_id = {} };- if (ids_are_of_this_process) {- route.route.scroller = taking_context->route.scroller;- route.document_id = taking_context->context->document_id();- }- return route;+ RustFFI::compositor_core_timer_fired(m_core, context_id.value(), timer, now.nanoseconds());}-void CompositorCore::begin_input_trace_for_testing(Web::CompositorContextId context_id)+static void receive_present_request(void* receiver, RustFFI::FfiPresentRequest request){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- if (auto* context = context_if_present(context_id))- context->input_trace().begin();+ Optional<Gfx::IntRect> viewport_rect;+ if (request.has_viewport_rect)+ viewport_rect = request.viewport_rect;+ static_cast<Vector<PresentRequest>*>(receiver)->append({ Web::CompositorContextId { request.context_id }, viewport_rect, request.forced_damage_rect, request.scheduling });}-void CompositorCore::clear_per_test_input_state_for_testing(Web::CompositorContextId context_id)+Vector<PresentRequest> CompositorCore::take_present_requests(){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- if (auto* context = context_if_present(context_id))- context->clear_per_test_input_state();+ Vector<PresentRequest> requests;+ RustFFI::compositor_core_take_present_requests(m_core, &requests, receive_present_request);+ return requests;}-Vector<Web::InputTraceRecord> CompositorCore::take_input_trace_for_testing(Web::CompositorContextId context_id)+IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_web_content(WebContentClientId client_id, IPC::RawMessage& message, MonotonicTime now){- VERIFY(!m_is_entered);- TemporaryChange entered { m_is_entered, true };-- auto* context = context_if_present(context_id);- if (!context)- return {};- return context->input_trace().take();+ return message.hand_to_rust([&](IPC::FfiRawMessage raw_message) {+ RustFFI::compositor_core_handle_web_content_message(m_core, client_id.value(), raw_message, now.nanoseconds());+ });}-bool CompositorCore::apply_context_update_result(- Web::CompositorContextId context_id,- ContextState& context,- ContextState::ContextUpdateResult const& result)+IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_presentation(PresentationId presentation_id, IPC::RawMessage& message, MonotonicTime now){- if (result.frame_to_present.has_value())- request_present(context_id, *result.frame_to_present);- publish_pending_async_scroll_updates(context_id, context);- if (result.should_request_rendering_update)- context.request_rendering_update();- return result.accepted;+ return message.hand_to_rust([&](IPC::FfiRawMessage raw_message) {+ RustFFI::compositor_core_handle_presentation_message(m_core, presentation_id.value(), raw_message, now.nanoseconds());+ });}}diff --git a/Services/Compositor/CompositorCore.h b/Services/Compositor/CompositorCore.hindex 6dfc374d2af..3d48ce915bd 100644--- a/Services/Compositor/CompositorCore.h+++ b/Services/Compositor/CompositorCore.h@@ -6,27 +6,35 @@#pragma once-#include <AK/HashMap.h>#include <AK/Noncopyable.h>-#include <AK/OwnPtr.h>+#include <AK/Optional.h>#include <AK/Vector.h>#include <Compositor/CompositorCoreHost.h>-#include <Compositor/ContextState.h>+#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>+#include <LibIPC/RawMessage.h>namespace Compositor {+// The scroll and input logic of the contexts and the routing of input between them, which is Rust (compositor_core).+// It talks to the process through its host, hands the frames it wants presented back as requests, and is never+// entered while one of its own calls runs.class CompositorCore {AK_MAKE_NONCOPYABLE(CompositorCore);AK_MAKE_NONMOVABLE(CompositorCore);public:- explicit CompositorCore(CompositorCoreHost&);+ CompositorCore(CompositorCoreHost&, bool scrollbars_always_shown);+ ~CompositorCore();- enum class ContextOwnerCheckResult : u8 {- OwnedByClient,- ContextUnavailable,- ConflictingOwner,- };+ using ContextOwnerCheckResult = RustFFI::ContextOwnerCheckResult;+ // What the presentation a context is shown through makes of the user's scrolling.+ using ScrollCapabilities = RustFFI::FfiScrollCapabilities;void create_context(Web::CompositorContextId, Optional<u64> page_id, WebContentClientId);// Also leaves the contexts nested in it without a parent.@@ -39,112 +47,35 @@ public:void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize);void set_paused_debugger_overlay_is_shown(Web::CompositorContextId, bool);void set_bound_presentation(Web::CompositorContextId, Optional<PresentationId>);- void set_scroll_capabilities(Web::CompositorContextId, ContextState::ScrollCapabilities const&);+ void set_scroll_capabilities(Web::CompositorContextId, ScrollCapabilities const&);- void install_display_list_update(Web::CompositorContextId, NonnullRefPtr<Compositing::DisplayList>, Compositing::AccumulatedVisualContextTree, Compositing::ScrollStateSnapshot&&, MonotonicTime now);+ // 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);// 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, MonotonicTime now);+ bool update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree const&, MonotonicTime now);bool needs_animation_frames(Web::CompositorContextId, MonotonicTime now);+ // Each frame shows the scrollbars as of when it is painted, so this updates which of them are shown. Empty until a+ // display list is installed.Optional<FrameInputs> frame_inputs(Web::CompositorContextId, MonotonicTime now);- ContextState::ScreenshotInputs frame_inputs_for_screenshot(Web::CompositorContextId, MonotonicTime now);+ struct ScreenshotInputs {+ FrameInputs frame_inputs;+ // The scrollbar fade damage that the screenshot does not present on screen.+ Gfx::IntRect scrollbar_fade_damage_rect;+ };+ ScreenshotInputs frame_inputs_for_screenshot(Web::CompositorContextId, MonotonicTime now);DisplayTickResult display_tick(Web::CompositorContextId, MonotonicTime frame_time, MonotonicTime now, DisplayTickInputs const&);void timer_fired(Web::CompositorContextId, ContextTimer, MonotonicTime now);// The frames asked for since the last call, in the order they were asked for.Vector<PresentRequest> take_present_requests();- void handle_and_dispatch_key_event(Web::CompositorContextId context_id, Web::KeyEvent event, bool allow_keyboard_scroll, MonotonicTime now);- void handle_and_dispatch_mouse_event(Web::CompositorContextId context_id, Web::MouseEvent event, MonotonicTime now);- void handle_and_dispatch_pinch_event(Web::CompositorContextId context_id, Web::PinchEvent event);- Compositing::WheelEventAnswer take_wheel_event_from_main_thread(Web::CompositorContextId context_id, Web::MouseEvent const& event, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelEventRouting routing, MonotonicTime now);- Compositing::WheelEventAnswer scroll_for_wheel_event_the_page_let_through(Web::CompositorContextId listener_context_id, Compositing::WheelStepLetThrough const& let_through, Compositing::AsyncScrollOperationTracking operation_tracking, WebContentClientId page_client, MonotonicTime now);- void forget_wheel_gesture_the_page_canceled(Web::CompositorContextId listener_context_id, u64 gesture_id);- void apply_scroll_requests(Web::CompositorContextId context_id, ReadonlySpan<Compositing::ScrollRequest> scroll_requests, MonotonicTime now);- Compositing::PendingAsyncScrollUpdates take_pending_async_scroll_updates(Web::CompositorContextId context_id);- void invalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation);- void invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation);- void update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot&& scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state);- String scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller) const;- Optional<Compositing::FirstWheelStepRouteForTesting> route_first_wheel_step_for_testing(Web::CompositorContextId context_id, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels);- void begin_input_trace_for_testing(Web::CompositorContextId context_id);- void clear_per_test_input_state_for_testing(Web::CompositorContextId context_id);- Vector<Web::InputTraceRecord> take_input_trace_for_testing(Web::CompositorContextId context_id);--private:- template<typename Message, typename... Arguments>- void post_to_presentation(PresentationId presentation_id, Arguments&&... arguments)- {- auto buffer = MUST(Message::static_encode(forward<Arguments>(arguments)...));- m_host.post_message_to_presentation(presentation_id, buffer);- }-- bool apply_context_update_result(- Web::CompositorContextId,- ContextState&,- ContextState::ContextUpdateResult const&);- enum class WheelStepOrigin : u8 {- UI,- Fling,- MainThread,- };- // A fling step is scrolled at the frame time the fling synthesized it for.- ContextState::ContextUpdateResult scroll_for_wheel_step(Web::CompositorContextId, ContextState&, Web::MouseEvent const&, WheelStepOrigin, bool is_first_wheel_event_with_delta, Compositing::AsyncScrollOperationTracking, MonotonicTime now);- // How a wheel step went in a context that presented and published what the step changed itself.- struct AppliedWheelStep {- // What is left for the context that routes the step to present and report.- ContextState::ContextUpdateResult result;- bool presents_frame { false };- };- // A process only knows the ids of its own nodes, and only follows the operations of its own contexts.- AppliedWheelStep apply_wheel_step_result(Web::CompositorContextId, ContextState&, ContextState::ContextUpdateResult const&, WebContentClientId reporting_client, MonotonicTime now);- static Compositing::WheelEventAnswer wheel_event_answer_for(AppliedWheelStep const&, Optional<Web::WheelGestureMark>);- AppliedWheelStep hand_wheel_step_to_nested_context(Web::CompositorContextId, ContextState&, Web::MouseEvent const&, ContextState::NestedContextWheelStep const&, ContextState::WheelEventListenerGate const&, Compositing::AsyncScrollOperationTracking, MonotonicTime now);- struct NestedContextTakingWheelStep {- Web::CompositorContextId context_id;- // Null when the step cannot be handed to the context.- ContextState* context { nullptr };- Gfx::FloatPoint position {};- ContextState::FirstWheelStepRoute route;- };- struct FirstWheelStepInNestedContexts {- // The innermost context that the step went into, whose page sees the step.- Web::CompositorContextId innermost_context_id;- // The context that takes the step, which is empty when each of them passes the step on.- Optional<NestedContextTakingWheelStep> taking_context {};- };- // Where the first step of a gesture over the content of a context nested in the context `context_id` goes, among- // that context and the contexts nested in it.- FirstWheelStepInNestedContexts first_wheel_step_in_nested_contexts(Web::CompositorContextId, Compositing::NestedContextHit, Gfx::FloatPoint delta_in_css_pixels, Web::WheelDeltaPrecision);- // Routes the first step of a gesture that the page of the listener context let through: in that context, from the- // scrollers the page found around the target, and on to the contexts around it for what a context passes on, up to- // the routing context, which latches the gesture. A page of another process than a context's scrolls it only by- // what the UI left to the page in the gesture.- AppliedWheelStep route_wheel_step_the_page_let_through(Web::CompositorContextId routing_context_id, ContextState& routing_context, Web::CompositorContextId listener_context_id, ContextState& listener_context, ContextState::WheelStep, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, Optional<WebContentClientId> page_client, MonotonicTime now);- // The nearest context, from the given one out to the presenting one, that noted the gesture.- Optional<Web::CompositorContextId> routing_context_of_wheel_gesture(Web::CompositorContextId, u64 gesture_id);- // The scrollbars of a context nested in the presenting context `context_id` take the pointer over that context's- // content, and a drag of one of them takes the pointer wherever it goes until the drag ends.- ContextState::ContextUpdateResult handle_mouse_event_in_nested_contexts(Web::CompositorContextId, ContextState&, Web::MouseEvent const&, MonotonicTime now);- ContextState* context_still_nested_in(Web::CompositorContextId containing_context_id, Optional<Web::CompositorContextId>);- // Where the position in the presenting context lands in the nested context, through each context in between and- // without regard to where their content is or what clips it.- Optional<Gfx::FloatPoint> position_in_nested_context_ignoring_clips(Web::CompositorContextId presenting_context_id, ContextState& presenting_context, ContextState& nested_context, Gfx::FloatPoint position);- bool is_nested_in(Web::CompositorContextId containing_context_id, ContextState const&) const;- bool page_under_pinch_may_cancel_it(Web::CompositorContextId, ContextState&, Gfx::FloatPoint position);- void dispatch_scroll_fling_step(Web::CompositorContextId, ContextState&, Optional<Web::MouseEvent>, MonotonicTime now);- ContextState* context_if_present(Web::CompositorContextId);- // Hands the context's async scroll updates to its WebContent process as soon as they exist,- // so a rendering update reads them locally instead of asking for them over a synchronous call.- void publish_pending_async_scroll_updates(Web::CompositorContextId, ContextState&);- ContextState const* context_if_present(Web::CompositorContextId) const;- bool nested_context_scrolled_since_last_frame(Web::CompositorContextId) const;- void request_present(Web::CompositorContextId, PendingFrame const&);+ // The messages of CompositorWebContentServer and CompositorPresentationServer that are marked [RustReceiver].+ IPC::RawMessage::OutcomeInRust handle_message_from_web_content(WebContentClientId, IPC::RawMessage&, MonotonicTime now);+ IPC::RawMessage::OutcomeInRust handle_message_from_presentation(PresentationId, IPC::RawMessage&, MonotonicTime now);- CompositorCoreHost& m_host;- HashMap<Web::CompositorContextId, OwnPtr<ContextState>> m_contexts;- Vector<PresentRequest> m_present_requests;- mutable bool m_is_entered { false };+private:+ RustFFI::CompositorCore* m_core { nullptr };};}diff --git a/Services/Compositor/CompositorCoreHost.h b/Services/Compositor/CompositorCoreHost.hindex c768250ea32..46307862035 100644--- a/Services/Compositor/CompositorCoreHost.h+++ b/Services/Compositor/CompositorCoreHost.h@@ -9,6 +9,7 @@#include <AK/DistinctNumeric.h>#include <AK/Optional.h>#include <AK/Time.h>+#include <Compositor/CompositorCoreRustFFI.h>#include <LibGfx/Rect.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Page/CompositorContextId.h>@@ -26,12 +27,7 @@ struct PendingFrame {static PendingFrame repainting_changes(Gfx::IntRect viewport_rect) { return { viewport_rect, {} }; }};-enum class PresentScheduling : u8 {- // The frame is presented on the next tick of the context's display, which the request asks for.- OnNextDisplayTick,- // The frame joins what the display tick in progress presents.- WithDisplayTickInProgress,-};+using PresentScheduling = RustFFI::PresentScheduling;// A frame that the scroll and input logic of a context wants presented. The compositor schedules it once the call that// asked for it has returned.@@ -52,18 +48,9 @@ struct DisplayTickInputs {Optional<double> clock_tick_interval_in_milliseconds;};-struct DisplayTickResult {- bool presents_on_display { false };- // As of the end of the tick, and without the fades of the UI overlays.- bool needs_animation_frames { false };-};+using DisplayTickResult = RustFFI::DisplayTickResult;-enum class ContextTimer : u8 {- ScrollStepGestureInput,- ScrollbarPaging,- ScrollbarFadeOut,- CaretBlink,-};+using ContextTimer = RustFFI::ContextTimer;// What the scroll and input logic of the contexts asks of the process around it. None of these calls comes back into// that logic before it returns.diff --git a/Services/Compositor/CompositorPresentationClient.ipc b/Services/Compositor/CompositorPresentationClient.ipcindex d1da78ed003..6aaa62ea045 100644--- a/Services/Compositor/CompositorPresentationClient.ipc+++ b/Services/Compositor/CompositorPresentationClient.ipc@@ -8,7 +8,7 @@ endpoint CompositorPresentationClientdid_add_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) =|did_retire_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids) =|did_present_frame(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) =|- did_consume_input_event(Web::CompositorContextId context_id, u64 event_id) =|- did_not_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id) =|- did_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id, bool performed_default_action) =|+ [RustSender] did_consume_input_event(Web::CompositorContextId context_id, u64 event_id) =|+ [RustSender] did_not_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id) =|+ [RustSender] did_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id, bool performed_default_action) =|}diff --git a/Services/Compositor/CompositorPresentationServer.ipc b/Services/Compositor/CompositorPresentationServer.ipcindex 910f4f54a02..4b61e79137c 100644--- a/Services/Compositor/CompositorPresentationServer.ipc+++ b/Services/Compositor/CompositorPresentationServer.ipc@@ -3,9 +3,9 @@endpoint CompositorPresentationServer{- handle_and_dispatch_key_event(Web::CompositorContextId context_id, Web::KeyEvent event, bool allow_keyboard_scroll) =|- handle_and_dispatch_pinch_event(Web::CompositorContextId context_id, Web::PinchEvent event) =|- handle_and_dispatch_mouse_event(Web::CompositorContextId context_id, Web::MouseEvent event) =|+ [RustReceiver] handle_and_dispatch_key_event(Web::CompositorContextId context_id, Web::KeyEvent event, bool allow_keyboard_scroll) =|+ [RustReceiver] handle_and_dispatch_pinch_event(Web::CompositorContextId context_id, Web::PinchEvent event) =|+ [RustReceiver] handle_and_dispatch_mouse_event(Web::CompositorContextId context_id, Web::MouseEvent event) =|presented_bitmap_ready_to_paint(Web::CompositorContextId context_id, i32 bitmap_id) =|set_client_gpu_presentation_capability(bool supported, u64 adapter_luid) =|set_scrollbar_track_press_jumps(bool jumps) =|diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex cda0c609153..f933dc02bc7 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -18,17 +18,32 @@ namespace Compositor {static constexpr int gpu_completion_check_interval_ms = 1;-NonnullRefPtr<CompositorState> CompositorState::create(RefPtr<Gfx::SkiaBackendContext> skia_backend_context)+NonnullRefPtr<CompositorState> CompositorState::create(RefPtr<Gfx::SkiaBackendContext> skia_backend_context, bool scrollbars_always_shown){- return adopt_ref(*new CompositorState(move(skia_backend_context)));+ return adopt_ref(*new CompositorState(move(skia_backend_context), scrollbars_always_shown));}-CompositorState::CompositorState(RefPtr<Gfx::SkiaBackendContext> skia_backend_context)+CompositorState::CompositorState(RefPtr<Gfx::SkiaBackendContext> skia_backend_context, bool scrollbars_always_shown): m_skia_backend_context(move(skia_backend_context)), m_display_list_player(make<DisplayListPlayerSkia>(m_skia_backend_context))+ , m_core(*this, scrollbars_always_shown){}+IPC::RawMessage::OutcomeInRust CompositorState::handle_message_from_web_content(WebContentClientId client_id, IPC::RawMessage& message)+{+ auto outcome = m_core.handle_message_from_web_content(client_id, message, MonotonicTime::now());+ schedule_requested_presents();+ return outcome;+}++IPC::RawMessage::OutcomeInRust CompositorState::handle_message_from_presentation(PresentationId presentation_id, IPC::RawMessage& message)+{+ auto outcome = m_core.handle_message_from_presentation(presentation_id, message, MonotonicTime::now());+ schedule_requested_presents();+ return outcome;+}+CompositorState::PresentedContext::PresentedContext(Optional<u64> page_id, CompositorStateWebContentClient& web_content_client, OwnedCanvasSurfaces canvas_surfaces): page_id(page_id), web_content_client(web_content_client)@@ -350,7 +365,7 @@ void CompositorState::stop_presenting_to_client(Web::CompositorContextId contextcontext->presenter.stop_presenting_to_client();}-void CompositorState::update_display_list(Web::CompositorContextId context_id, NonnullRefPtr<Compositing::DisplayList> display_list, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction, Compositing::ScrollStateSnapshot&& 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, IPC::Encoded<Compositing::ScrollStateSnapshot> const& scroll_state_snapshot){auto now = MonotonicTime::now();auto* context = presented_context_if_present(context_id);@@ -360,20 +375,22 @@ void CompositorState::update_display_list(Web::CompositorContextId context_id, Ndbgln("Compositor: Dropping inconsistent display list update (display list epoch {}, tree epoch {})",display_list->compatible_visual_context_tree_structural_epoch(),visual_context_tree.structural_epoch());- return;+ return true;}if (auto validation = Compositing::validate_display_list_references_live_visual_context_nodes(*display_list, visual_context_tree); validation.is_error()) {dbgln("Compositor: Dropping display list update: {}", validation.error());- return;+ return true;}+ if (!m_core.install_display_list_update(context_id, *display_list, async_scrolling_metadata, visual_context_tree, scroll_state_snapshot, now))+ return false;context->presenter.apply_resource_transaction(move(resource_transaction));context->presenter.set_display_list(display_list);- m_core.install_display_list_update(context_id, move(display_list), move(visual_context_tree), move(scroll_state_snapshot), now);resolve_video_sinks(*context);show_animated_image_frames_in(*context);update_unpainted_video_update_scheduling();+ return true;}void CompositorState::update_display_list_resources(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction&& resource_transaction)@@ -390,17 +407,11 @@ void CompositorState::update_visual_context_tree(Web::CompositorContextId contexauto* context = presented_context_if_present(context_id);VERIFY(context);- if (m_core.update_visual_context_tree(context_id, move(visual_context_tree), now))+ if (m_core.update_visual_context_tree(context_id, visual_context_tree, now))context->presenter.apply_resource_transaction(move(resource_transaction));show_animated_image_frames_in(*context);}-void CompositorState::update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot&& scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state)-{- m_core.update_scroll_state(context_id, move(scroll_state_snapshot), move(keyboard_scroll_state));- schedule_requested_presents();-}-CompositorState::VideoSinkState* CompositorState::video_sink_state(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle){auto client_sinks = m_video_sink_states.get(&client);@@ -834,74 +845,6 @@ double CompositorState::display_refresh_rate_for_context(PresentedContext const&return context.display_refresh_rate;}-void CompositorState::invalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation)-{- m_core.invalidate_wheel_event_listener_state(context_id, generation);- schedule_requested_presents();-}--void CompositorState::invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation)-{- m_core.invalidate_keyboard_scroll_state(context_id, generation);- schedule_requested_presents();-}--void CompositorState::handle_and_dispatch_key_event(Web::CompositorContextId context_id, Web::KeyEvent event, bool allow_keyboard_scroll)-{- auto now = MonotonicTime::now();- m_core.handle_and_dispatch_key_event(context_id, move(event), allow_keyboard_scroll, now);- schedule_requested_presents();-}--void CompositorState::handle_and_dispatch_mouse_event(Web::CompositorContextId context_id, Web::MouseEvent event)-{- auto now = MonotonicTime::now();- m_core.handle_and_dispatch_mouse_event(context_id, move(event), now);- schedule_requested_presents();-}--void CompositorState::handle_and_dispatch_pinch_event(Web::CompositorContextId context_id, Web::PinchEvent event)-{- m_core.handle_and_dispatch_pinch_event(context_id, move(event));- schedule_requested_presents();-}--Compositing::WheelEventAnswer CompositorState::take_wheel_event_from_main_thread(Web::CompositorContextId context_id, Web::MouseEvent const& event, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelEventRouting routing)-{- auto now = MonotonicTime::now();- auto answer = m_core.take_wheel_event_from_main_thread(context_id, event, operation_tracking, routing, now);- schedule_requested_presents();- return answer;-}--Compositing::WheelEventAnswer CompositorState::scroll_for_wheel_event_the_page_let_through(Web::CompositorContextId listener_context_id, Compositing::WheelStepLetThrough const& let_through, Compositing::AsyncScrollOperationTracking operation_tracking, WebContentClientId page_client)-{- auto now = MonotonicTime::now();- auto answer = m_core.scroll_for_wheel_event_the_page_let_through(listener_context_id, let_through, operation_tracking, page_client, now);- schedule_requested_presents();- return answer;-}--void CompositorState::forget_wheel_gesture_the_page_canceled(Web::CompositorContextId listener_context_id, u64 gesture_id)-{- m_core.forget_wheel_gesture_the_page_canceled(listener_context_id, gesture_id);- schedule_requested_presents();-}--void CompositorState::apply_scroll_requests(Web::CompositorContextId context_id, ReadonlySpan<Compositing::ScrollRequest> scroll_requests)-{- auto now = MonotonicTime::now();- m_core.apply_scroll_requests(context_id, scroll_requests, now);- schedule_requested_presents();-}--Compositing::PendingAsyncScrollUpdates CompositorState::take_pending_async_scroll_updates(Web::CompositorContextId context_id)-{- auto answer = m_core.take_pending_async_scroll_updates(context_id);- schedule_requested_presents();- return answer;-}-void CompositorState::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress){auto* context = presented_context_if_present(context_id);@@ -1506,14 +1449,13 @@ BackingStoreManager::GpuSharing CompositorState::gpu_sharing_for_context(Web::Covoid CompositorState::update_scroll_capabilities(){for (auto& [context_id, context] : m_presented_contexts) {- ContextState::ScrollCapabilities capabilities;+ CompositorCore::ScrollCapabilities capabilities {};if (auto* presentation = presentation_for_context(root_context_id_of(context_id))) {auto const& presentation_capabilities = *m_presentations.get(presentation);capabilities.synthesizes_scroll_momentum = presentation_capabilities.synthesizes_scroll_momentum;capabilities.scrolls_elastically = presentation_capabilities.scrolls_elastically;capabilities.scrollbar_track_press_jumps = presentation_capabilities.scrollbar_track_press_jumps;- if (!presentation_capabilities.synthesizes_scroll_momentum)- capabilities.touchpad_gesture_end = Compositing::TouchpadGestureEnd::WhenFingersLift;+ capabilities.touchpad_gestures_end_when_fingers_lift = !presentation_capabilities.synthesizes_scroll_momentum;}m_core.set_scroll_capabilities(context_id, capabilities);}@@ -1525,37 +1467,6 @@ void CompositorState::set_scrollbar_track_press_jumps(CompositorStateClient& preupdate_scroll_capabilities();}-String CompositorState::scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller) const-{- return m_core.scroll_state_for_testing(context_id, stretched_scroller);-}--Optional<Compositing::FirstWheelStepRouteForTesting> CompositorState::route_first_wheel_step_for_testing(Web::CompositorContextId context_id, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels)-{- auto answer = m_core.route_first_wheel_step_for_testing(context_id, position, delta_in_css_pixels);- schedule_requested_presents();- return answer;-}--void CompositorState::begin_input_trace_for_testing(Web::CompositorContextId context_id)-{- m_core.begin_input_trace_for_testing(context_id);- schedule_requested_presents();-}--void CompositorState::clear_per_test_input_state_for_testing(Web::CompositorContextId context_id)-{- m_core.clear_per_test_input_state_for_testing(context_id);- schedule_requested_presents();-}--Vector<Web::InputTraceRecord> CompositorState::take_input_trace_for_testing(Web::CompositorContextId context_id)-{- auto answer = m_core.take_input_trace_for_testing(context_id);- schedule_requested_presents();- return answer;-}-void CompositorState::set_client_gpu_presentation_capability(CompositorStateClient& presentation, bool supported, u64 adapter_luid){Optional<u64> new_adapter_luid;diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 90b19cf3751..04077c7f800 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -75,7 +75,7 @@ class CompositorState final: public RefCounted<CompositorState>, public CompositorCoreHost {public:- static NonnullRefPtr<CompositorState> create(RefPtr<Gfx::SkiaBackendContext>);+ static NonnullRefPtr<CompositorState> create(RefPtr<Gfx::SkiaBackendContext>, bool scrollbars_always_shown = false);~CompositorState();enum class ContextOwnerCheckResult {@@ -113,10 +113,10 @@ public:void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId> parent_context_id);void stop_presenting_to_client(Web::CompositorContextId);- void update_display_list(Web::CompositorContextId, NonnullRefPtr<Compositing::DisplayList>, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction&&, Compositing::ScrollStateSnapshot&&);+ // 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&);void update_display_list_resources(Web::CompositorContextId, Compositing::DisplayListResourceTransaction&&);void update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction&&);- void update_scroll_state(Web::CompositorContextId, Compositing::ScrollStateSnapshot&&, Compositing::KeyboardScrollState);void add_video_sink(CompositorStateWebContentClient&, Media::VideoSinkHandle);// For a presentation channel that arrives after the sinks did, or that replaces the one their edges were on.void create_video_edges(CompositorStateWebContentClient&);@@ -132,19 +132,9 @@ public:// The client's images lost the decoder their sessions were on. Each keeps the frame it shows.void animated_image_decoder_lost(CompositorStateWebContentClient&);AnimatedImage const* animated_image(CompositorStateWebContentClient&, Compositing::ImageFrameResourceId) const;- void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation);- void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);- void handle_and_dispatch_key_event(Web::CompositorContextId, Web::KeyEvent, bool allow_keyboard_scroll);- void handle_and_dispatch_mouse_event(Web::CompositorContextId, Web::MouseEvent);- void handle_and_dispatch_pinch_event(Web::CompositorContextId, Web::PinchEvent);- // Routes a wheel event the UI did not send here, such as one a test makes, as the UI's wheel events are routed.- Compositing::WheelEventAnswer take_wheel_event_from_main_thread(Web::CompositorContextId, Web::MouseEvent const&, Compositing::AsyncScrollOperationTracking, Compositing::WheelEventRouting);- // Scrolls by a step that the page of the context dispatched and did not cancel. The context that routes the- // gesture is the nearest one, from that context out to the presenting one, that noted the gesture, and the steps the- // compositor still has to route of the gesture no longer wait for the page.- Compositing::WheelEventAnswer scroll_for_wheel_event_the_page_let_through(Web::CompositorContextId, Compositing::WheelStepLetThrough const&, Compositing::AsyncScrollOperationTracking, WebContentClientId page_client);- void forget_wheel_gesture_the_page_canceled(Web::CompositorContextId, u64 gesture_id);- void apply_scroll_requests(Web::CompositorContextId, ReadonlySpan<Compositing::ScrollRequest>);+ // The messages of WebContent and of a presentation that the scroll and input logic takes undecoded.+ IPC::RawMessage::OutcomeInRust handle_message_from_web_content(WebContentClientId, IPC::RawMessage&);+ IPC::RawMessage::OutcomeInRust handle_message_from_presentation(PresentationId, IPC::RawMessage&);void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize, double device_pixel_ratio, Compositing::WindowResizingInProgress);void request_rendering_opportunity(Web::CompositorContextId, double maximum_frames_per_second);void set_ui_overlays(Web::CompositorContextId, Compositing::UIOverlays);@@ -161,11 +151,6 @@ public:void presented_bitmap_ready_to_paint(Web::CompositorContextId, i32 bitmap_id);void set_client_gpu_presentation_capability(CompositorStateClient&, bool supported, u64 adapter_luid);void set_scrollbar_track_press_jumps(CompositorStateClient&, bool jumps);- String scroll_state_for_testing(Web::CompositorContextId, Web::AsyncScrollNodeStableID stretched_scroller) const;- Optional<Compositing::FirstWheelStepRouteForTesting> route_first_wheel_step_for_testing(Web::CompositorContextId, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels);- void begin_input_trace_for_testing(Web::CompositorContextId);- void clear_per_test_input_state_for_testing(Web::CompositorContextId);- Vector<Web::InputTraceRecord> take_input_trace_for_testing(Web::CompositorContextId);struct PlaceholderCanvasAllocation {Compositing::CanvasId canvas_id;@@ -181,7 +166,7 @@ public:PlaceholderCanvasPixels read_placeholder_canvas_pixels(CompositorStateWebContentClient&, Compositing::CanvasId, Gfx::IntRect);private:- CompositorState(RefPtr<Gfx::SkiaBackendContext>);+ CompositorState(RefPtr<Gfx::SkiaBackendContext>, bool scrollbars_always_shown);CompositorStateWebContentClient* web_content_client_if_present(WebContentClientId) const;virtual void post_message_to_web_content(WebContentClientId, IPC::MessageBuffer&) override;@@ -240,9 +225,6 @@ public:void present_pending_frames_for_testing() { present_pending_frames_on_vsync({}, MonotonicTime::now()); }size_t pending_async_present_count_for_testing() const { return m_pending_async_presents.size(); }- // What was not published yet, for a caller that needs the compositor's state as of now.- Compositing::PendingAsyncScrollUpdates take_pending_async_scroll_updates(Web::CompositorContextId);-private:PresentedContext* presented_context_if_present(Web::CompositorContextId);PresentedContext const* presented_context_if_present(Web::CompositorContextId) const;@@ -347,7 +329,7 @@ private:};HashMap<Compositing::CanvasId, PlaceholderCanvas> m_placeholder_canvases;- CompositorCore m_core { *this };+ CompositorCore m_core;};}diff --git a/Services/Compositor/CompositorWebContentClient.ipc b/Services/Compositor/CompositorWebContentClient.ipcindex 1d13509cad2..f15431f39d6 100644--- a/Services/Compositor/CompositorWebContentClient.ipc+++ b/Services/Compositor/CompositorWebContentClient.ipc@@ -5,16 +5,16 @@endpoint CompositorWebContentClient{- mouse_event(u64 page_id, Web::MouseEvent event) =|- key_event(u64 page_id, Web::KeyEvent event) =|- pinch_event(u64 page_id, Web::PinchEvent event) =|- request_rendering_update() =|+ [RustSender] mouse_event(u64 page_id, Web::MouseEvent event) =|+ [RustSender] key_event(u64 page_id, Web::KeyEvent event) =|+ [RustSender] pinch_event(u64 page_id, Web::PinchEvent event) =|+ [RustSender] request_rendering_update() =|rendering_opportunity(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds) =|- async_scroll_updates(Web::CompositorContextId context_id, Compositing::PendingAsyncScrollUpdates updates) =|+ [RustSender] async_scroll_updates(Web::CompositorContextId context_id, Compositing::PendingAsyncScrollUpdates updates) =|// A frame of a transform animation the compositor runs moved content under the pointer at rest, or away from it,// as of the frame's time.- animated_content_moved_under_pointer(Web::CompositorContextId context_id, i64 frame_time_nanoseconds) =|- overlay_scrollbar_visibilities_changed(Vector<Web::OverlayScrollbarVisibility> visibilities) =|+ [RustSender] animated_content_moved_under_pointer(Web::CompositorContextId context_id, i64 frame_time_nanoseconds) =|+ [RustSender] overlay_scrollbar_visibilities_changed(Vector<Web::OverlayScrollbarVisibility> visibilities) =|did_complete_screenshot(Compositing::ScreenshotRequestId request_id) =|did_fail_screenshot(Compositing::ScreenshotRequestId request_id) =|did_lose_compositor() =|diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex f4f6aa2c044..c4d8dbd8ace 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -17,6 +17,7 @@#include <LibGfx/Rect.h>#include <LibGfx/ShareableBitmap.h>#include <LibGfx/Size.h>+#include <LibIPC/Encoded.h>#include <LibIPC/TransportHandle.h>#include <LibMedia/VideoSinkHandle.h>#include <LibWebCommon/Page/InputEvent.h>@@ -42,10 +43,11 @@ endpoint CompositorWebContentServerstop_presenting_to_client(Web::CompositorContextId context_id) =|destroy_context(Web::CompositorContextId context_id) =|- update_display_list(Web::CompositorContextId context_id, Core::AnonymousBuffer display_list_buffer, u64 tape_size, u64 run_count, Compositing::DisplayList::Properties display_list_properties, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, Compositing::ScrollStateSnapshot scroll_state_snapshot) =|+ // 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) =|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) =|- 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, Compositing::ScrollStateSnapshot scroll_state_snapshot, 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)@@ -76,21 +78,21 @@ endpoint CompositorWebContentServerwebgl_read_pixels(Compositing::CanvasId canvas_id, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, Core::AnonymousBuffer pixels) => (i32 length, i32 columns, i32 rows)webgl_read_buffer_sub_data(Compositing::CanvasId canvas_id, u32 target, i64 offset, i64 size, Core::AnonymousBuffer data) => (bool success)- invalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation) =|- invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation) => ()- take_wheel_event_from_main_thread(Web::CompositorContextId context_id, Web::MouseEvent event, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelEventRouting routing) => (Compositing::WheelEventAnswer answer)- wheel_event_let_through(Web::CompositorContextId context_id, Compositing::WheelStepLetThrough step, Compositing::AsyncScrollOperationTracking operation_tracking) => (Compositing::WheelEventAnswer answer)- wheel_event_canceled(Web::CompositorContextId context_id, u64 wheel_gesture_id) =|- apply_scroll_requests(Web::CompositorContextId context_id, Vector<Compositing::ScrollRequest> scroll_requests) =|- scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller) => (String scroll_state)+ [RustReceiver] invalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation) =|+ [RustReceiver] invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation) => ()+ [RustReceiver] take_wheel_event_from_main_thread(Web::CompositorContextId context_id, Web::MouseEvent event, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelEventRouting routing) => (Compositing::WheelEventAnswer answer)+ [RustReceiver] wheel_event_let_through(Web::CompositorContextId context_id, Compositing::WheelStepLetThrough step, Compositing::AsyncScrollOperationTracking operation_tracking) => (Compositing::WheelEventAnswer answer)+ [RustReceiver] wheel_event_canceled(Web::CompositorContextId context_id, u64 wheel_gesture_id) =|+ [RustReceiver] apply_scroll_requests(Web::CompositorContextId context_id, Vector<Compositing::ScrollRequest> scroll_requests) =|+ [RustReceiver] scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller) => (String scroll_state)// Returns once the compositor has handled every message WebContent sent before it.synchronize_for_testing() => ()- route_first_wheel_step_for_testing(Web::CompositorContextId context_id, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels) => (Optional<Web::InputRoutingDecision> decision, Optional<Web::AsyncScrollNodeStableID> scroller, Optional<Web::UniqueNodeID> document_id)- begin_input_trace_for_testing(Web::CompositorContextId context_id) => ()- clear_per_test_input_state_for_testing(Web::CompositorContextId context_id) => ()- take_input_trace_for_testing(Web::CompositorContextId context_id) => (Vector<Web::InputTraceRecord> records)+ [RustReceiver] route_first_wheel_step_for_testing(Web::CompositorContextId context_id, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels) => (Optional<Web::InputRoutingDecision> decision, Optional<Web::AsyncScrollNodeStableID> scroller, Optional<Web::UniqueNodeID> document_id)+ [RustReceiver] begin_input_trace_for_testing(Web::CompositorContextId context_id) => ()+ [RustReceiver] clear_per_test_input_state_for_testing(Web::CompositorContextId context_id) => ()+ [RustReceiver] take_input_trace_for_testing(Web::CompositorContextId context_id) => (Vector<Web::InputTraceRecord> records)- take_pending_async_scroll_updates(Web::CompositorContextId context_id) => (Compositing::PendingAsyncScrollUpdates updates)+ [RustReceiver] take_pending_async_scroll_updates(Web::CompositorContextId context_id) => (Compositing::PendingAsyncScrollUpdates updates)viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress) =|request_rendering_opportunity(Web::CompositorContextId context_id, double maximum_frames_per_second) =|hurry_rendering_opportunity(Web::CompositorContextId context_id) =|diff --git a/Services/Compositor/ConnectionFromClient.cpp b/Services/Compositor/ConnectionFromClient.cppindex d7bc6b5e557..e499f3cd4d6 100644--- a/Services/Compositor/ConnectionFromClient.cpp+++ b/Services/Compositor/ConnectionFromClient.cpp@@ -18,9 +18,9 @@ namespace Compositor {static IDAllocator s_web_content_connection_ids;-ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, RefPtr<Gfx::SkiaBackendContext> skia_backend_context)+ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, RefPtr<Gfx::SkiaBackendContext> skia_backend_context, bool scrollbars_always_shown): IPC::ConnectionFromClient<CompositorControlClientEndpoint, CompositorControlServerEndpoint>(*this, move(transport), 1)- , m_compositor_state(CompositorState::create(move(skia_backend_context)))+ , m_compositor_state(CompositorState::create(move(skia_backend_context), scrollbars_always_shown)){}diff --git a/Services/Compositor/ConnectionFromClient.h b/Services/Compositor/ConnectionFromClient.hindex 411d2e89343..1516166ef40 100644--- a/Services/Compositor/ConnectionFromClient.h+++ b/Services/Compositor/ConnectionFromClient.h@@ -25,7 +25,7 @@ public:virtual ~ConnectionFromClient() override = default;private:- ConnectionFromClient(NonnullOwnPtr<IPC::Transport>, RefPtr<Gfx::SkiaBackendContext>);+ ConnectionFromClient(NonnullOwnPtr<IPC::Transport>, RefPtr<Gfx::SkiaBackendContext>, bool scrollbars_always_shown);virtual void die() override;diff --git a/Services/Compositor/ConnectionFromPresentation.cpp b/Services/Compositor/ConnectionFromPresentation.cppindex 829b44013bc..cd9ceb40ce2 100644--- a/Services/Compositor/ConnectionFromPresentation.cpp+++ b/Services/Compositor/ConnectionFromPresentation.cpp@@ -4,70 +4,11 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/NumericLimits.h>#include <Compositor/ConnectionFromPresentation.h>#include <LibIPC/Transport.h>-#include <math.h>namespace Compositor {-// NB: The IPC decoder already rejects event types, wheel delta precisions and scroll gesture phases that do not-// exist, and pinch scales that are not finite. These check the rest of what the UI sends.--static bool is_valid_key_code(Web::UIEvents::KeyCode key)-{- switch (key) {-#define __ENUMERATE_KEY_CODE(name, ui_name, code) case Web::UIEvents::Key_##name:- ENUMERATE_KEY_CODES-#undef __ENUMERATE_KEY_CODE- return true;- }- return false;-}--static bool is_valid_modifiers(Web::UIEvents::KeyModifier modifiers)-{- // NB: KeyModifier has no fixed underlying type, so ~Mod_Mask is out of its range; mask the integers instead.- return (to_underlying(modifiers) & ~to_underlying(Web::UIEvents::Mod_Mask)) == 0;-}--static bool is_valid_key_event(Web::KeyEvent const& event)-{- return is_valid_key_code(event.key)- && is_valid_modifiers(event.modifiers)- && event.code_point <= 0x10ffff- // Only the compositor sets this, on its way to WebContent.- && !event.async_scroll_performed_default_action;-}--static bool is_valid_mouse_event(Web::MouseEvent const& event)-{- // Wheel deltas are scrolled by as floats.- auto is_valid_wheel_delta = [](double delta) {- return isfinite(delta) && fabs(delta) <= NumericLimits<float>::max();- };- constexpr auto all_buttons = Web::UIEvents::Primary | Web::UIEvents::Secondary | Web::UIEvents::Middle | Web::UIEvents::Backward | Web::UIEvents::Forward;- return first_is_one_of(event.button, Web::UIEvents::None, Web::UIEvents::Primary, Web::UIEvents::Secondary, Web::UIEvents::Middle, Web::UIEvents::Backward, Web::UIEvents::Forward)- && (event.buttons & ~all_buttons) == 0- && is_valid_modifiers(event.modifiers)- && is_valid_wheel_delta(event.wheel_delta_x)- && is_valid_wheel_delta(event.wheel_delta_y)- && is_valid_wheel_delta(event.wheel_tick_120ths_x)- && is_valid_wheel_delta(event.wheel_tick_120ths_y)- && event.click_count >= 0- // Only the compositor sets these, on its way to WebContent.- && !event.async_scroll_performed_default_action- && !event.scrollbar_dragged_by_compositor.has_value()- && !event.wheel_gesture_mark.has_value();-}--static bool is_valid_pinch_event(Web::PinchEvent const& event)-{- return is_valid_modifiers(event.modifiers)- // Only the compositor sets this, on its way to WebContent.- && !event.async_zoom_performed_default_action;-}-ConnectionFromPresentation::ConnectionFromPresentation(NonnullOwnPtr<IPC::Transport> transport, NonnullRefPtr<CompositorState> compositor_state, CompositorState::PresentationCapabilities capabilities): IPC::ConnectionFromClient<CompositorPresentationClientEndpoint, CompositorPresentationServerEndpoint>(*this, move(transport), 1), m_compositor_state(move(compositor_state))@@ -118,43 +59,12 @@ void ConnectionFromPresentation::post_message_to_presentation(IPC::MessageBuffer(void)post_message(buffer);}-void ConnectionFromPresentation::handle_and_dispatch_key_event(Web::CompositorContextId context_id, Web::KeyEvent event, bool allow_keyboard_scroll)-{- if (!is_valid_key_event(event)) {- did_misbehave("Invalid key event");- return;- }- if (!is_bound_to(context_id)) {- async_did_not_dispatch_input_event(context_id, event.id);- return;- }- m_compositor_state->handle_and_dispatch_key_event(context_id, move(event), allow_keyboard_scroll);-}--void ConnectionFromPresentation::handle_and_dispatch_pinch_event(Web::CompositorContextId context_id, Web::PinchEvent event)+ErrorOr<OwnPtr<IPC::MessageBuffer>> ConnectionFromPresentation::handle_raw(IPC::RawMessage& message){- if (!is_valid_pinch_event(event)) {- did_misbehave("Invalid pinch event");- return;- }- if (!is_bound_to(context_id)) {- async_did_not_dispatch_input_event(context_id, event.id);- return;- }- m_compositor_state->handle_and_dispatch_pinch_event(context_id, event);-}--void ConnectionFromPresentation::handle_and_dispatch_mouse_event(Web::CompositorContextId context_id, Web::MouseEvent event)-{- if (!is_valid_mouse_event(event)) {- did_misbehave("Invalid mouse event");- return;- }- if (!is_bound_to(context_id)) {- async_did_not_dispatch_input_event(context_id, event.id);- return;- }- m_compositor_state->handle_and_dispatch_mouse_event(context_id, move(event));+ auto outcome = m_compositor_state->handle_message_from_presentation(m_presentation_id, message);+ if (outcome.misbehavior.has_value())+ did_misbehave(outcome.misbehavior->characters());+ return nullptr;}void ConnectionFromPresentation::presented_bitmap_ready_to_paint(Web::CompositorContextId context_id, i32 bitmap_id)diff --git a/Services/Compositor/ConnectionFromPresentation.h b/Services/Compositor/ConnectionFromPresentation.hindex 67c443f446b..8ba52bf5640 100644--- a/Services/Compositor/ConnectionFromPresentation.h+++ b/Services/Compositor/ConnectionFromPresentation.h@@ -37,9 +37,7 @@ private:virtual void did_retire_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids) override;virtual void did_present_frame(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) override;- virtual void handle_and_dispatch_key_event(Web::CompositorContextId, Web::KeyEvent, bool allow_keyboard_scroll) override;- virtual void handle_and_dispatch_pinch_event(Web::CompositorContextId, Web::PinchEvent) override;- virtual void handle_and_dispatch_mouse_event(Web::CompositorContextId, Web::MouseEvent) override;+ virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_raw(IPC::RawMessage&) override;virtual void presented_bitmap_ready_to_paint(Web::CompositorContextId, i32 bitmap_id) override;virtual void set_client_gpu_presentation_capability(bool supported, u64 adapter_luid) override;virtual void set_scrollbar_track_press_jumps(bool jumps) override;diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex 1bcbced0030..c7c327017a3 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -213,6 +213,16 @@ void ConnectionFromWebContent::rendering_opportunity(Web::CompositorContextId coasync_rendering_opportunity(context_id, frame_time_nanoseconds, frame_interval_milliseconds);}+ErrorOr<OwnPtr<IPC::MessageBuffer>> ConnectionFromWebContent::handle_raw(IPC::RawMessage& message)+{+ auto outcome = m_compositor_state->handle_message_from_web_content(web_content_client_id(), message);+ if (outcome.misbehavior.has_value()) {+ did_misbehave(outcome.misbehavior->characters());+ return nullptr;+ }+ return move(outcome.response);+}+bool ConnectionFromWebContent::context_is_owned_by_this_connection(Web::CompositorContextId context_id){switch (m_compositor_state->check_context_owner(context_id, web_content_client_id())) {@@ -276,7 +286,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, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction resource_transaction, 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, IPC::Encoded<Compositing::ScrollStateSnapshot> scroll_state_snapshot){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);@@ -288,7 +298,10 @@ void ConnectionFromWebContent::update_display_list(Web::CompositorContextId contauto adopt_time = timer.elapsed_time();if (!context_is_owned_by_this_connection(context_id))return;- m_compositor_state->update_display_list(context_id, display_list.release_value(), move(visual_context_tree), move(resource_transaction), move(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_snapshot)) {+ did_misbehave("WebContent published a display list with scrolling state that does not decode");+ return;+ }if (display_list_timing_enabled())dbgln("DISPLAY_LIST_RECEIVE bytes={} adopt={} µs install={} µs", tape_size, adopt_time.to_microseconds(), (timer.elapsed_time() - adopt_time).to_microseconds());}@@ -307,13 +320,6 @@ void ConnectionFromWebContent::update_visual_context_tree(Web::CompositorContextm_compositor_state->update_visual_context_tree(context_id, move(visual_context_tree), move(resource_transaction));}-void ConnectionFromWebContent::update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state)-{- if (!context_is_owned_by_this_connection(context_id))- return;- m_compositor_state->update_scroll_state(context_id, move(scroll_state_snapshot), move(keyboard_scroll_state));-}-Messages::CompositorWebContentServer::ReserveCanvasIdsResponse ConnectionFromWebContent::reserve_canvas_ids(){static constexpr u64 reserved_canvas_id_count = 1 << 20;@@ -511,143 +517,6 @@ Messages::CompositorWebContentServer::WebglReadBufferSubDataResponse ConnectionFreturn { m_canvas_host.webgl_read_buffer_sub_data(canvas_id, target, offset, size, move(data)) };}-void ConnectionFromWebContent::invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation)-{- if (context_is_owned_by_this_connection(context_id))- m_compositor_state->invalidate_keyboard_scroll_state(context_id, generation);-}--void ConnectionFromWebContent::invalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation)-{- if (!context_is_owned_by_this_connection(context_id))- return;- m_compositor_state->invalidate_wheel_event_listener_state(context_id, generation);-}--// Wheel deltas are scrolled by as floats.-static bool is_valid_wheel_delta(double delta)-{- return isfinite(delta) && fabs(delta) <= NumericLimits<float>::max();-}--static bool is_valid_wheel_event(Web::MouseEvent const& event)-{- return event.type == Web::MouseEvent::Type::MouseWheel- && is_valid_wheel_delta(event.wheel_delta_x)- && is_valid_wheel_delta(event.wheel_delta_y);-}--static bool is_valid_wheel_step_let_through(Compositing::WheelStepLetThrough const& step)-{- return isfinite(step.position.x()) && isfinite(step.position.y())- && isfinite(step.delta_in_css_pixels.x()) && isfinite(step.delta_in_css_pixels.y());-}--Messages::CompositorWebContentServer::TakeWheelEventFromMainThreadResponse ConnectionFromWebContent::take_wheel_event_from_main_thread(Web::CompositorContextId context_id, Web::MouseEvent event, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelEventRouting routing)-{- if (!context_is_owned_by_this_connection(context_id) || !is_valid_wheel_event(event))- return Compositing::WheelEventAnswer {};- return m_compositor_state->take_wheel_event_from_main_thread(context_id, event, operation_tracking, routing);-}--Messages::CompositorWebContentServer::WheelEventLetThroughResponse ConnectionFromWebContent::wheel_event_let_through(Web::CompositorContextId context_id, Compositing::WheelStepLetThrough step, Compositing::AsyncScrollOperationTracking operation_tracking)-{- if (!context_is_owned_by_this_connection(context_id) || !is_valid_wheel_step_let_through(step))- return Compositing::WheelEventAnswer {};- return m_compositor_state->scroll_for_wheel_event_the_page_let_through(context_id, step, operation_tracking, web_content_client_id());-}--void ConnectionFromWebContent::wheel_event_canceled(Web::CompositorContextId context_id, u64 wheel_gesture_id)-{- if (!context_is_owned_by_this_connection(context_id))- return;- m_compositor_state->forget_wheel_gesture_the_page_canceled(context_id, wheel_gesture_id);-}--static bool is_valid_scroll_request(Compositing::ScrollRequest const& scroll_request)-{- auto is_finite = [](Gfx::FloatPoint point) { return isfinite(point.x()) && isfinite(point.y()); };- if (scroll_request.jump_offset.has_value() && !is_finite(scroll_request.jump_offset.value()))- return false;- if (auto const& relative_scroll = scroll_request.relative_scroll; relative_scroll.has_value()) {- if (!is_finite(relative_scroll->delta) || !is_finite(relative_scroll->lower_bound) || !is_finite(relative_scroll->upper_bound))- return false;- if (relative_scroll->lower_bound.x() > relative_scroll->upper_bound.x() || relative_scroll->lower_bound.y() > relative_scroll->upper_bound.y())- return false;- }- if (scroll_request.visual_viewport_scale.has_value()) {- auto scale = scroll_request.visual_viewport_scale.value();- if (!isfinite(scale) || scale <= 0)- return false;- }- if (auto const& smooth_scroll = scroll_request.smooth_scroll; smooth_scroll.has_value()) {- if (!is_finite(smooth_scroll->destination_offset))- return false;- if (!(smooth_scroll->relative_lower_bound.x() <= smooth_scroll->relative_upper_bound.x() && smooth_scroll->relative_lower_bound.y() <= smooth_scroll->relative_upper_bound.y()))- return false;- // WebContent names the compositor's own scrolls only to head them somewhere else.- if (smooth_scroll->operation_id < Compositing::first_operation_id_the_main_thread_requests && !smooth_scroll->retargets_operation)- return false;- }- return true;-}--void ConnectionFromWebContent::apply_scroll_requests(Web::CompositorContextId context_id, Vector<Compositing::ScrollRequest> scroll_requests)-{- if (!context_is_owned_by_this_connection(context_id))- return;- if (!all_of(scroll_requests, is_valid_scroll_request)) {- did_misbehave("Invalid scroll request");- return;- }- m_compositor_state->apply_scroll_requests(context_id, scroll_requests);-}--Messages::CompositorWebContentServer::ScrollStateForTestingResponse ConnectionFromWebContent::scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller)-{- if (!context_is_owned_by_this_connection(context_id))- return String {};- return m_compositor_state->scroll_state_for_testing(context_id, stretched_scroller);-}--Messages::CompositorWebContentServer::RouteFirstWheelStepForTestingResponse ConnectionFromWebContent::route_first_wheel_step_for_testing(Web::CompositorContextId context_id, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels)-{- if (!context_is_owned_by_this_connection(context_id))- return { {}, {}, {} };- auto result = m_compositor_state->route_first_wheel_step_for_testing(context_id, position, delta_in_css_pixels);- if (!result.has_value())- return { {}, {}, {} };- return { result->route.decision, result->route.scroller, result->document_id };-}--void ConnectionFromWebContent::begin_input_trace_for_testing(Web::CompositorContextId context_id)-{- if (!context_is_owned_by_this_connection(context_id))- return;- m_compositor_state->begin_input_trace_for_testing(context_id);-}--void ConnectionFromWebContent::clear_per_test_input_state_for_testing(Web::CompositorContextId context_id)-{- if (!context_is_owned_by_this_connection(context_id))- return;- m_compositor_state->clear_per_test_input_state_for_testing(context_id);-}--Messages::CompositorWebContentServer::TakeInputTraceForTestingResponse ConnectionFromWebContent::take_input_trace_for_testing(Web::CompositorContextId context_id)-{- if (!context_is_owned_by_this_connection(context_id))- return Vector<Web::InputTraceRecord> {};- return m_compositor_state->take_input_trace_for_testing(context_id);-}--Messages::CompositorWebContentServer::TakePendingAsyncScrollUpdatesResponse ConnectionFromWebContent::take_pending_async_scroll_updates(Web::CompositorContextId context_id)-{- if (!context_is_owned_by_this_connection(context_id))- return Compositing::PendingAsyncScrollUpdates {};- return m_compositor_state->take_pending_async_scroll_updates(context_id);-}-void ConnectionFromWebContent::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress){if (!context_is_owned_by_this_connection(context_id))diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex cc86557724e..4fb92f71b2a 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -57,9 +57,8 @@ 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, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction, 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, IPC::Encoded<Compositing::ScrollStateSnapshot>) override;virtual void update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree, Compositing::DisplayListResourceTransaction) override;- virtual void update_scroll_state(Web::CompositorContextId, Compositing::ScrollStateSnapshot, Compositing::KeyboardScrollState) override;virtual void update_display_list_resources(Web::CompositorContextId, Compositing::DisplayListResourceTransaction) override;virtual Messages::CompositorWebContentServer::ReserveCanvasIdsResponse reserve_canvas_ids() override;virtual void create_canvas_2d_context(Compositing::CanvasId, Gfx::IntSize, bool alpha, bool will_read_frequently, Gfx::ColorSpace) override;@@ -82,20 +81,9 @@ private:virtual Messages::CompositorWebContentServer::WebglSyncCallResponse webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request) override;virtual Messages::CompositorWebContentServer::WebglReadPixelsResponse webgl_read_pixels(Compositing::CanvasId canvas_id, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, Core::AnonymousBuffer pixels) override;virtual Messages::CompositorWebContentServer::WebglReadBufferSubDataResponse webgl_read_buffer_sub_data(Compositing::CanvasId canvas_id, u32 target, i64 offset, i64 size, Core::AnonymousBuffer data) override;- virtual void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation) override;- virtual void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation) override;- virtual Messages::CompositorWebContentServer::TakeWheelEventFromMainThreadResponse take_wheel_event_from_main_thread(Web::CompositorContextId, Web::MouseEvent, Compositing::AsyncScrollOperationTracking, Compositing::WheelEventRouting) override;- virtual Messages::CompositorWebContentServer::WheelEventLetThroughResponse wheel_event_let_through(Web::CompositorContextId, Compositing::WheelStepLetThrough, Compositing::AsyncScrollOperationTracking) override;- virtual void wheel_event_canceled(Web::CompositorContextId, u64 wheel_gesture_id) override;- virtual void apply_scroll_requests(Web::CompositorContextId, Vector<Compositing::ScrollRequest>) override;- virtual Messages::CompositorWebContentServer::ScrollStateForTestingResponse scroll_state_for_testing(Web::CompositorContextId, Web::AsyncScrollNodeStableID) override;virtual void synchronize_for_testing() override { }- virtual Messages::CompositorWebContentServer::RouteFirstWheelStepForTestingResponse route_first_wheel_step_for_testing(Web::CompositorContextId, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels) override;- virtual void begin_input_trace_for_testing(Web::CompositorContextId) override;- virtual void clear_per_test_input_state_for_testing(Web::CompositorContextId) override;- virtual Messages::CompositorWebContentServer::TakeInputTraceForTestingResponse take_input_trace_for_testing(Web::CompositorContextId) override;- virtual Messages::CompositorWebContentServer::TakePendingAsyncScrollUpdatesResponse take_pending_async_scroll_updates(Web::CompositorContextId) override;virtual void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress) override;+ virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_raw(IPC::RawMessage&) override;virtual void request_rendering_opportunity(Web::CompositorContextId, double maximum_frames_per_second) override;virtual void hurry_rendering_opportunity(Web::CompositorContextId) override;virtual void present_frame(Web::CompositorContextId, Gfx::IntRect viewport_rect) override;diff --git a/Services/Compositor/ContextScene.cpp b/Services/Compositor/ContextScene.cppdeleted file mode 100644index 570f34ed722..00000000000--- a/Services/Compositor/ContextScene.cpp+++ /dev/null@@ -1,143 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <Compositor/ContextScene.h>-#include <LibCompositing/DisplayList/DisplayListDamage.h>--namespace Compositor {--static void update_visual_animation_sampling_state(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Optional<i64>& sample_time_ns, bool& has_active_animations, MonotonicTime now)-{- has_active_animations = visual_context_tree.has_active_visual_animation_at(now.nanoseconds());- // A replacement tree can be presented before the next vsync. Keep the most recent sample so that presentation- // remains continuous, but sample dormant and completed descriptors at the current boundary when necessary.- if (!visual_context_tree.has_visual_animations())- sample_time_ns.clear();- else if (!has_active_animations)- sample_time_ns = now.nanoseconds();-}--void ContextScene::install(NonnullRefPtr<Compositing::DisplayList> display_list, Compositing::AccumulatedVisualContextTree visual_context_tree, MonotonicTime now)-{- invalidate_visual_context_tree_for_compositing();- m_display_list = move(display_list);- m_visual_context_tree = move(visual_context_tree);- update_visual_animation_sampling_state(*m_visual_context_tree, m_visual_animation_sample_time_ns, m_has_active_visual_animations, now);-}--bool ContextScene::replace_visual_context_tree(Compositing::AccumulatedVisualContextTree visual_context_tree, MonotonicTime now)-{- if (!m_display_list || m_display_list->compatible_visual_context_tree_structural_epoch() != visual_context_tree.structural_epoch()) {- dbgln("Compositor: Dropping stale visual context tree update (tree epoch {}, display list epoch {})",- visual_context_tree.structural_epoch(),- m_display_list ? m_display_list->compatible_visual_context_tree_structural_epoch() : 0);- return false;- }- invalidate_visual_context_tree_for_compositing();- m_visual_context_tree = move(visual_context_tree);- update_visual_animation_sampling_state(*m_visual_context_tree, m_visual_animation_sample_time_ns, m_has_active_visual_animations, now);- return true;-}--Compositing::AccumulatedVisualContextTree const& ContextScene::current_visual_context_tree() const-{- VERIFY(m_display_list);- VERIFY(m_visual_context_tree.has_value());- return m_visual_context_tree.value();-}--Compositing::AccumulatedVisualContextTree const& ContextScene::visual_context_tree_for_compositing()-{- if (m_async_visual_viewport_transform.has_value() && !m_visual_context_tree_for_compositing.has_value()) {- m_sampled_visual_context_tree.clear();- m_visual_context_tree_for_compositing = current_visual_context_tree().with_visual_viewport_transform(*m_async_visual_viewport_transform);- }-- auto const& unsampled_tree = m_visual_context_tree_for_compositing.has_value()- ? *m_visual_context_tree_for_compositing- : *m_visual_context_tree;- if (!m_visual_animation_sample_time_ns.has_value())- return unsampled_tree;- if (!m_sampled_visual_context_tree.has_value())- m_sampled_visual_context_tree = unsampled_tree.with_visual_animation_samples(*m_visual_animation_sample_time_ns);- return *m_sampled_visual_context_tree;-}--Compositing::TransformWithOrigin ContextScene::visual_viewport_transform() const-{- if (m_async_visual_viewport_transform.has_value())- return *m_async_visual_viewport_transform;- if (m_visual_context_tree.has_value())- return m_visual_context_tree->visual_viewport_transform();- return { Gfx::FloatMatrix4x4::identity(), {} };-}--Optional<float> ContextScene::visual_viewport_scale() const-{- if (!m_visual_context_tree.has_value())- return {};-- if (m_async_visual_viewport_transform.has_value())- return m_async_visual_viewport_transform->matrix[0, 0];-- return m_visual_context_tree->visual_viewport_transform().matrix[0, 0];-}--float ContextScene::visual_viewport_magnification() const-{- return max(visual_viewport_scale().value_or(1.0f), 1.0f);-}--void ContextScene::set_async_visual_viewport_transform(Compositing::TransformWithOrigin transform)-{- invalidate_visual_context_tree_for_compositing();- m_async_visual_viewport_transform = transform;-}--void ContextScene::drop_async_visual_viewport_transform()-{- invalidate_visual_context_tree_for_compositing();- m_async_visual_viewport_transform.clear();-}--bool ContextScene::advance_visual_animations(MonotonicTime now)-{- if (!m_visual_context_tree->has_visual_animations())- return false;- m_sampled_visual_context_tree.clear();- m_visual_animation_sample_time_ns = now.nanoseconds();- visual_context_tree_for_compositing();-- m_has_active_visual_animations = m_visual_context_tree->has_active_visual_animation_at(now.nanoseconds());- return m_has_active_visual_animations;-}--bool ContextScene::visual_animations_need_frame(Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::IntSize viewport_size, MonotonicTime now)-{- if (!m_has_active_visual_animations)- return false;- if (m_animated_content_may_affect_viewport.has_value())- return *m_animated_content_may_affect_viewport;-- auto sample_time_ns = m_visual_animation_sample_time_ns.value_or(now.nanoseconds());- auto tree = m_async_visual_viewport_transform.has_value()- ? current_visual_context_tree().with_visual_viewport_transform(*m_async_visual_viewport_transform)- : current_visual_context_tree();- auto effect = Compositing::animated_content_may_affect_viewport(- *m_display_list, tree, scroll_state_snapshot, { {}, viewport_size }, sample_time_ns);- if (effect.stable_until_scene_changes)- m_animated_content_may_affect_viewport = effect.may_affect_viewport;- return effect.may_affect_viewport;-}--void ContextScene::invalidate_visual_context_tree_for_compositing()-{- m_animated_content_may_affect_viewport.clear();- m_sampled_visual_context_tree.clear();- m_visual_context_tree_for_compositing.clear();-}--}diff --git a/Services/Compositor/ContextScene.h b/Services/Compositor/ContextScene.hdeleted file mode 100644index 252110712c1..00000000000--- a/Services/Compositor/ContextScene.h+++ /dev/null@@ -1,66 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Noncopyable.h>-#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>-#include <AK/RefPtr.h>-#include <AK/Time.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/ScrollState.h>-#include <LibGfx/Size.h>--namespace Compositor {--// What WebContent last sent a context to draw, and the visual context tree it is drawn with: the one WebContent sent,-// with the visual viewport this context has pinch-zoomed or panned since, and with its visual animations sampled.-class ContextScene {- AK_MAKE_NONCOPYABLE(ContextScene);- AK_MAKE_NONMOVABLE(ContextScene);--public:- ContextScene() = default;-- void install(NonnullRefPtr<Compositing::DisplayList>, Compositing::AccumulatedVisualContextTree, MonotonicTime now);- // Returns false, leaving everything as it was, for a tree that does not fit the installed display list.- bool replace_visual_context_tree(Compositing::AccumulatedVisualContextTree, MonotonicTime now);-- RefPtr<Compositing::DisplayList const> const& display_list() const { return m_display_list; }- Optional<Compositing::AccumulatedVisualContextTree> const& visual_context_tree() const { return m_visual_context_tree; }- Compositing::AccumulatedVisualContextTree const& current_visual_context_tree() const;- Compositing::AccumulatedVisualContextTree const& visual_context_tree_for_compositing();-- Compositing::TransformWithOrigin visual_viewport_transform() const;- Optional<float> visual_viewport_scale() const;- // How many screen pixels a zoomed visual viewport shows one pixel of the layout viewport with. Scrollers scroll and- // stretch in the pixels of the layout viewport.- float visual_viewport_magnification() const;- bool has_async_visual_viewport_transform() const { return m_async_visual_viewport_transform.has_value(); }- void set_async_visual_viewport_transform(Compositing::TransformWithOrigin);- void drop_async_visual_viewport_transform();-- bool advance_visual_animations(MonotonicTime now);- bool visual_animations_need_frame(Compositing::ScrollStateSnapshot const&, Gfx::IntSize viewport_size, MonotonicTime now);- void forget_whether_animated_content_may_affect_viewport() { m_animated_content_may_affect_viewport.clear(); }--private:- void invalidate_visual_context_tree_for_compositing();-- RefPtr<Compositing::DisplayList const> m_display_list;- Optional<Compositing::AccumulatedVisualContextTree> m_visual_context_tree;- Optional<Compositing::TransformWithOrigin> m_async_visual_viewport_transform;- Optional<Compositing::AccumulatedVisualContextTree> m_visual_context_tree_for_compositing;- Optional<Compositing::AccumulatedVisualContextTree> m_sampled_visual_context_tree;- Optional<i64> m_visual_animation_sample_time_ns;- bool m_has_active_visual_animations { false };- Optional<bool> m_animated_content_may_affect_viewport;-};--}diff --git a/Services/Compositor/ContextState.cpp b/Services/Compositor/ContextState.cppdeleted file mode 100644index ada362b6c70..00000000000--- a/Services/Compositor/ContextState.cpp+++ /dev/null@@ -1,2605 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/GenericShorthands.h>-#include <AK/JsonObject.h>-#include <AK/Math.h>-#include <AK/ScopeGuard.h>-#include <AK/StdLibExtras.h>-#include <Compositor/CompositorWebContentClientEndpoint.h>-#include <Compositor/ContextState.h>-#include <Compositor/RenderClockClientEndpoint.h>-#include <LibWebCommon/Page/InputEvent.h>-#include <math.h>--namespace Compositor {--// INTEROP: Holding a press beside the thumb pages again after these delays, as in Chromium and Firefox.-static constexpr auto scrollbar_paging_initial_delay = AK::Duration::from_milliseconds(250);-static constexpr auto scrollbar_paging_repeat_interval = AK::Duration::from_milliseconds(50);--// INTEROP: The modifier that makes a press beside the thumb page instead of jumping there or the other way around, as in-// Chromium and Firefox.-#if defined(AK_OS_MACOS)-static constexpr auto scrollbar_track_press_inverting_modifier = Web::UIEvents::Mod_Alt;-#else-static constexpr auto scrollbar_track_press_inverting_modifier = Web::UIEvents::Mod_Shift;-#endif--// The offset of the visual viewport in the layout viewport, in device pixels of the content it scales.-static Gfx::FloatPoint visual_viewport_scroll_offset(Compositing::TransformWithOrigin const& transform)-{- auto scale = transform.matrix[0, 0];- return Gfx::FloatPoint { -transform.matrix[0, 3], -transform.matrix[1, 3] }.scaled(1.0f / scale);-}--static void clamp_visual_viewport_transform_to_viewport(Compositing::TransformWithOrigin& transform, Gfx::IntRect viewport_rect)-{- auto scale = transform.matrix[0, 0];- if (scale <= 1.0f) {- transform.matrix[0, 3] = 0;- transform.matrix[1, 3] = 0;- return;- }-- auto min_x = -static_cast<float>(viewport_rect.width()) * (scale - 1.0f);- auto min_y = -static_cast<float>(viewport_rect.height()) * (scale - 1.0f);- transform.matrix[0, 3] = clamp(transform.matrix[0, 3], min_x, 0.0f);- transform.matrix[1, 3] = clamp(transform.matrix[1, 3], min_y, 0.0f);-}--ContextState::ContextState(Web::CompositorContextId context_id, Optional<u64> page_id, WebContentClientId web_content_client_id, CompositorCoreHost& host)- : m_host(host)- , m_web_content_client_id(web_content_client_id)- , m_context_id(context_id)- , m_page_id(page_id)- , m_presents_to_client(page_id.has_value())-{-}--bool ContextState::is_owned_by(WebContentClientId web_content_client_id) const-{- return m_web_content_client_id == web_content_client_id;-}--void ContextState::request_display_ticks_if_needed(MonotonicTime now)-{- if (needs_animation_frames(now))- m_host.request_display_ticks(m_context_id);-}--Optional<Gfx::IntRect> ContextState::timer_fired(ContextTimer timer, MonotonicTime now)-{- switch (timer) {- case ContextTimer::ScrollStepGestureInput:- end_scroll_step_gestures_whose_input_ran_out(now);- break;- case ContextTimer::ScrollbarPaging:- m_scrollbar_paging_timer_is_armed = false;- // Paging ends with the press, and with the scrollbar the press holds.- if (!m_scrollbar_paging.has_value() || !m_scrollbar_controller.has_captured_scrollbar()) {- stop_scrollbar_paging();- return {};- }- // Once the thumb reaches the pointer, paging waits for the pointer to move.- if (!page_captured_scrollbar(now).has_value())- return {};- request_rendering_update();- request_display_ticks_if_needed(now);- m_host.set_timer(m_context_id, ContextTimer::ScrollbarPaging, scrollbar_paging_repeat_interval);- m_scrollbar_paging_timer_is_armed = true;- break;- case ContextTimer::ScrollbarFadeOut:- request_display_ticks_if_needed(now);- break;- case ContextTimer::CaretBlink: {- auto damage_rect = damage_rect_of_blinking_carets();- schedule_next_caret_blink(now);- if (!damage_rect.is_empty())- return damage_rect;- break;- }- }- return {};-}--void ContextState::request_rendering_update()-{- // The rendering update this asks for adopts the scroll updates it finds pushed by then. What is pending here goes- // ahead of the request on the wire, so that an update run on the request never misses it.- if (has_pending_async_scroll_updates())- post_to_web_content<Messages::CompositorWebContentClient::AsyncScrollUpdates>(m_context_id, take_pending_async_scroll_updates());- post_to_web_content<Messages::CompositorWebContentClient::RequestRenderingUpdate>();-}--void ContextState::post_clock_tick(MonotonicTime frame_time, double frame_interval_milliseconds)-{- post_to_render_clock_of_web_content<Messages::RenderClockClient::ClockTick>(m_context_id, frame_time.nanoseconds(), frame_interval_milliseconds, scroll_offsets());-}--void ContextState::dispatch_mouse_event_to_web_content(Web::MouseEvent const& event, bool nested_context_scrolled_since_last_frame)-{- VERIFY(m_page_id.has_value());- post_to_web_content<Messages::CompositorWebContentClient::MouseEvent>(*m_page_id, event);-- // The render clock hears where the pointer went too, without waiting for WebContent's main thread, so that hover- // can follow the pointer while that thread runs a task. The lanes hit test it in the frames on screen, which a- // scroll since, here or in a nested context, has moved. A button going up ends the drag a lane follows, whether or- // not a move comes after it.- if (event.type == Web::MouseEvent::Type::MouseMove || event.type == Web::MouseEvent::Type::MouseUp)- post_to_render_clock_of_web_content<Messages::RenderClockClient::PointerMoved>(m_context_id, event.position, to_underlying(event.buttons), scrolled_since_last_frame() || nested_context_scrolled_since_last_frame, event.id);- else if (event.type == Web::MouseEvent::Type::MouseLeave)- post_to_render_clock_of_web_content<Messages::RenderClockClient::PointerLeft>(m_context_id, event.id);-}--bool ContextState::scrolled_since_last_frame() const-{- return has_pending_async_scroll_updates() || m_scroll_offsets_differ_from_last_frame || has_active_smooth_scroll_animations() || has_active_scroll_fling();-}--void ContextState::dispatch_key_event_to_web_content(Web::KeyEvent const& event)-{- VERIFY(m_page_id.has_value());- post_to_web_content<Messages::CompositorWebContentClient::KeyEvent>(*m_page_id, event);-}--void ContextState::dispatch_pinch_event_to_web_content(Web::PinchEvent const& event)-{- VERIFY(m_page_id.has_value());- post_to_web_content<Messages::CompositorWebContentClient::PinchEvent>(*m_page_id, event);-}--void ContextState::stop_presenting_to_client()-{- m_pointer_in_nested_contexts = {};- end_keyboard_scroll_gesture();- m_elastic_overscroll_controller.forget();- m_presents_to_client = false;-}--void ContextState::set_parent_context(Optional<Web::CompositorContextId> parent_context_id)-{- m_parent_context_id = parent_context_id;-}--void ContextState::install_display_list_update(- NonnullRefPtr<Compositing::DisplayList> display_list,- Compositing::AccumulatedVisualContextTree visual_context_tree,- Compositing::ScrollStateSnapshot&& scroll_state_snapshot,- MonotonicTime now)-{- VERIFY(display_list->compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());- auto scroll_offsets_of_known_nodes = scroll_offsets_by_stable_id();- m_scene.install(move(display_list), move(visual_context_tree), now);- m_keyboard_scroll_controller.forget_target();- m_scroll_state_snapshot = move(scroll_state_snapshot);- m_scroll_state_snapshot.set_node_count(m_scene.visual_context_tree()->spatial_node_count());- restart_caret_blink_for(*m_scene.display_list(), now);-- auto async_scrolling_state = Compositing::async_scrolling_state_from_display_list(*m_scene.display_list());- auto async_scrolling_viewport_rect = async_scrolling_state.viewport_rect;- m_wheel_gesture_routing.did_install_scrolling_state(async_scrolling_state);- // The visual viewport of another document is where that document's visual context tree has it.- if (m_scene.has_async_visual_viewport_transform() && async_scrolling_state.document_id != m_visual_viewport_document_id) {- m_scene.drop_async_visual_viewport_transform();- m_visual_viewport_document_id.clear();- }-- // NB: What the page of one document let through of a pinch says nothing about the page of the next.- if (async_scrolling_state.document_id != m_async_scroll_tree.document_id())- m_pinch_gesture_was_let_through = false;-- auto box_of_dragged_scrollbar = box_of_captured_scrollbar();- m_scrollbar_controller.set_scrollbars(async_scrolling_state.scrollbars);- if (!m_scrollbar_controller.has_captured_scrollbar())- stop_scrollbar_paging();- note_user_scroll_gesture_end_if_drag_ended(box_of_dragged_scrollbar);- m_async_scroll_tree.set_state(move(async_scrolling_state));- m_elastic_overscroll_controller.did_install_scrolling_state(m_async_scroll_tree);- m_scroll_snap_controller.did_install_scrolling_state(m_async_scroll_tree);- if (auto viewport_scroll_offset = keep_scroll_offsets_of_known_nodes(scroll_offsets_of_known_nodes); viewport_scroll_offset.has_value())- async_scrolling_viewport_rect.set_location(viewport_scroll_offset->to_type<int>());- rebuild_wheel_hit_test_targets();- m_async_scrolling_viewport_rect = async_scrolling_viewport_rect;- m_has_async_scrolling_state = true;- if (auto const& metadata = m_scene.display_list()->async_scrolling_metadata(); metadata.has_value())- adopt_keyboard_scroll_state(metadata->keyboard_scroll_state);-}--// Repaints the blinking caret of a display list each time its blink cycle turns it on or off.-void ContextState::restart_caret_blink_for(Compositing::DisplayList const& display_list, MonotonicTime now)-{- Optional<i64> blink_cycle_start_time_ns;- display_list.for_each_caret([&](auto, auto, auto const& caret) {- if (caret.should_blink)- blink_cycle_start_time_ns = caret.blink_cycle_start_time_ns;- });-- if (blink_cycle_start_time_ns == m_caret_blink_cycle_start_time_ns)- return;- m_caret_blink_cycle_start_time_ns = blink_cycle_start_time_ns;-- m_host.cancel_timer(m_context_id, ContextTimer::CaretBlink);- if (!m_caret_blink_cycle_start_time_ns.has_value())- return;-- schedule_next_caret_blink(now);-}--void ContextState::schedule_next_caret_blink(MonotonicTime now)-{- if (!m_caret_blink_cycle_start_time_ns.has_value())- return;-- auto now_ns = now.nanoseconds();- auto elapsed_ns = now_ns > *m_caret_blink_cycle_start_time_ns- ? now_ns - *m_caret_blink_cycle_start_time_ns- : 0;- auto delay_ns = Compositing::caret_blink_interval_ns - elapsed_ns % Compositing::caret_blink_interval_ns;- m_host.set_timer(m_context_id, ContextTimer::CaretBlink, AK::Duration::from_nanoseconds(delay_ns));-}--Gfx::IntRect ContextState::damage_rect_of_blinking_carets()-{- if (!m_scene.display_list() || !m_scene.visual_context_tree().has_value())- return {};-- auto const& visual_context_tree = m_scene.visual_context_tree_for_compositing();- auto stretched_scroll_state_snapshot = scroll_state_snapshot_stretched_by_elastic_overscrolls();- auto const& presented_scroll_state_snapshot = stretched_scroll_state_snapshot.has_value() ? *stretched_scroll_state_snapshot : m_scroll_state_snapshot;- Gfx::IntRect damage_rect;- m_scene.display_list()->for_each_caret([&](auto context, auto bounding_rect, auto const& caret) {- if (!caret.should_blink)- return;- auto rect = visual_context_tree.transform_rect_to_viewport(context.spatial, bounding_rect.template to_type<float>(), presented_scroll_state_snapshot);- if (!isfinite(rect.x()) || !isfinite(rect.y()) || !isfinite(rect.width()) || !isfinite(rect.height())) {- damage_rect = { {}, m_viewport_size };- return;- }- rect.intersect(Gfx::IntRect { {}, m_viewport_size }.to_type<float>());- if (!rect.is_empty())- damage_rect.unite(Gfx::enclosing_int_rect(rect).inflated(1, 1, 1, 1));- });- damage_rect.intersect({ {}, m_viewport_size });- return damage_rect;-}--bool ContextState::update_visual_context_tree(Compositing::AccumulatedVisualContextTree visual_context_tree, MonotonicTime now)-{- if (!m_scene.replace_visual_context_tree(move(visual_context_tree), now))- return false;- // A constraints refresh changes sticky payloads without a new snapshot, and the snapshot that- // pairs with this tree arrives in a separate message.- Compositing::resolve_sticky_offsets(*m_scene.visual_context_tree(), m_scroll_state_snapshot);-- if (m_has_async_scrolling_state)- rebuild_wheel_hit_test_targets();- return true;-}--void ContextState::update_scroll_state(Compositing::ScrollStateSnapshot&& scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state)-{- m_scene.forget_whether_animated_content_may_affect_viewport();- auto scroll_offsets_of_known_nodes = scroll_offsets_by_stable_id();- m_scroll_state_snapshot = move(scroll_state_snapshot);- m_scroll_state_snapshot.set_node_count(m_scene.visual_context_tree().has_value() ? m_scene.visual_context_tree()->spatial_node_count() : 0);- if (!m_has_async_scrolling_state)- return;-- auto kept_viewport_scroll_offset = keep_scroll_offsets_of_known_nodes(scroll_offsets_of_known_nodes);- rebuild_wheel_hit_test_targets();- if (kept_viewport_scroll_offset.has_value())- m_async_scrolling_viewport_rect.set_location(kept_viewport_scroll_offset->to_type<int>());- adopt_keyboard_scroll_state(move(keyboard_scroll_state));-}--void ContextState::invalidate_wheel_event_listener_state(u64 generation)-{- m_wheel_gesture_routing.invalidate_wheel_event_listener_state(generation);-}--void ContextState::invalidate_keyboard_scroll_state(u64 generation)-{- m_keyboard_scroll_controller.invalidate_state(generation);-}--void ContextState::adopt_keyboard_scroll_state(Compositing::KeyboardScrollState state)-{- if (m_keyboard_scroll_controller.adopt_state(move(state)) && !m_keyboard_scroll_controller.has_target())- end_keyboard_scroll_gesture();-}--void ContextState::end_keyboard_scroll_gesture()-{- if (!m_keyboard_scroll_controller.release_all_keys())- return;- end_user_scroll_gesture_of_held_keys();- request_rendering_update();-}--Optional<ContextState::KeyScroll> ContextState::key_scroll_for(Web::KeyEvent const& event) const-{- if (!presents_to_client() || m_paused_debugger_overlay_is_shown- || m_visibility != Compositing::ContextVisibility::Visible- || !Web::is_keyboard_scroll_key(event.key, event.modifiers)- || !m_keyboard_scroll_controller.has_target()- || !m_scene.visual_context_tree().has_value()- || !m_keyboard_scroll_controller.state_matches_visual_context_tree_epoch(m_scene.current_visual_context_tree().structural_epoch()))- return {};-- auto key_step = m_keyboard_scroll_controller.step_for_key(event, m_async_scroll_tree);- if (!key_step.has_value())- return {};- auto target_scroll_node_index = m_async_scroll_tree.scroll_node_for_keyboard_scroll(key_step->keyboard_scroll_target, key_step->delta, scroll_state_snapshot_at_keyboard_step_starts());- // If every destination is at its boundary, consume repeats while a scrolling box can still move toward it.- // Falling back would cancel the running animation and lose the steps already accumulated in its destination.- if (!target_scroll_node_index.has_value())- target_scroll_node_index = m_async_scroll_tree.scroll_node_for_keyboard_scroll(key_step->keyboard_scroll_target, key_step->delta, m_scroll_state_snapshot);- return KeyScroll { .step = key_step.release_value(), .target_scroll_node_index = target_scroll_node_index };-}--Optional<Web::AsyncScrollNodeStableID> ContextState::box_scrolled_for_key_event(Web::KeyEvent const& event) const-{- if (event.type != Web::KeyEvent::Type::KeyDown)- return {};- auto key_scroll = key_scroll_for(event);- if (!key_scroll.has_value() || !key_scroll->target_scroll_node_index.has_value())- return {};- return m_async_scroll_tree.scroll_node_for_index(*key_scroll->target_scroll_node_index)->stable_node_id;-}--ContextState::ContextUpdateResult ContextState::handle_key_event(Web::KeyEvent const& event, MonotonicTime now)-{- if (!Web::is_keyboard_scroll_key(event.key, Web::UIEvents::Mod_None))- return {};-- // Release the key even if focus, modifiers, or routing eligibility changed while it was held. Other scroll- // keys may still be held, so only end the gesture when the last one is released.- if (event.type == Web::KeyEvent::Type::KeyUp) {- auto release = m_keyboard_scroll_controller.release_key(event);- if (release == KeyboardScrollController::KeyRelease::Ignored)- return {};- if (release == KeyboardScrollController::KeyRelease::ReleasedLastHeldKey)- end_user_scroll_gesture_of_held_keys();- return { .accepted = true, .frame_to_present = {}, .should_request_rendering_update = true };- }-- auto key_scroll = key_scroll_for(event);- if (!key_scroll.has_value())- return {};- auto const& key_step = key_scroll->step;- auto delta = key_step.delta;-- // https://drafts.csswg.org/cssom-view/#viewport-perform-a-scroll- // The visual viewport takes as much of the scroll as it can before the layout viewport takes the rest.- bool panned_visual_viewport = false;- if (!key_scroll->target_scroll_node_index.has_value() || m_async_scroll_tree.scroll_node_is_viewport(*key_scroll->target_scroll_node_index)) {- auto magnification = m_scene.visual_viewport_magnification();- auto delta_in_screen_pixels = delta.scaled(magnification);- auto panned_delta = pan_visual_viewport_by(delta_in_screen_pixels);- panned_visual_viewport = !panned_delta.is_zero();- delta = (delta_in_screen_pixels - panned_delta).scaled(1.0f / magnification);- }- auto result_of_pan = [&]() -> ContextUpdateResult {- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_changes(m_async_scrolling_viewport_rect),- .should_request_rendering_update = true,- };- };-- // NB: With nothing to scroll here, the main thread must not hold back the keys after this one. It still gets to- // scroll for this one, as content it added may have extended the scroll range since the compositor last heard.- if (!key_scroll->target_scroll_node_index.has_value()) {- if (panned_visual_viewport)- return result_of_pan();- return { .accepted = true, .key_found_nothing_to_scroll = true };- }- if (delta.is_zero())- return result_of_pan();- auto scrolls_to_extent = key_step.scrolls_to_extent;- auto target_scroll_node_index = *key_scroll->target_scroll_node_index;-- m_keyboard_scroll_controller.hold_key(event.key);-- auto stable_node_id = m_async_scroll_tree.scroll_node_for_index(target_scroll_node_index)->stable_node_id;- if (!m_boxes_scrolled_by_held_keys.contains_slow(stable_node_id))- m_boxes_scrolled_by_held_keys.append(stable_node_id);- Optional<Gfx::FloatPoint> scroll_in_flight_destination;- for (auto const& running_animation : m_smooth_scroll_animations) {- if (running_animation.stable_node_id == stable_node_id && running_animation.is_user_scroll && running_animation.animation.kind() == Compositing::ScrollAnimationKind::SmoothScroll)- scroll_in_flight_destination = running_animation.animation.destination_offset();- }- auto css_scroll_in_flight_destination = scroll_in_flight_destination.map([&](auto offset) { return m_async_scroll_tree.css_pixels_from_device_offset(offset); });- if (auto decision = m_scroll_snap_controller.decide_key_step(m_async_scroll_tree, m_scroll_state_snapshot, target_scroll_node_index, m_async_scroll_tree.css_pixels_from_device_offset(delta), key_step.snap_selection_intent, css_scroll_in_flight_destination, now); decision.has_value()) {- schedule_end_of_scroll_step_gestures(now);- if (auto* snap_scroll = decision->get_pointer<ScrollSnapController::SnapScrollStart>()) {- snap_scroll->is_absolute_scroll = scrolls_to_extent;- start_snap_scroll(target_scroll_node_index, move(*snap_scroll), false, now);- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_changes(m_async_scrolling_viewport_rect),- .should_request_rendering_update = true,- };- }- if (auto& updated_scroll = decision->get<ScrollSnapController::StepConsumed>().updated_scroll; updated_scroll.has_value()) {- updated_scroll->is_absolute_scroll = scrolls_to_extent;- note_user_input_scrolled(updated_scroll->stable_node_id);- m_async_scroll_update_outbox.record_started_user_scroll(updated_scroll.release_value());- }- return { .accepted = true, .frame_to_present = {}, .should_request_rendering_update = true };- }-- auto current_offset = m_async_scroll_tree.scroll_offset_for_node(target_scroll_node_index, m_scroll_state_snapshot);- VERIFY(current_offset.has_value());- // A plain step continues toward the animation's destination, including any snap on the other axis.- auto step_start = scroll_in_flight_destination.value_or(*current_offset);- auto destination = m_async_scroll_tree.clamped_scroll_offset_for_node(target_scroll_node_index, { step_start.x() + delta.x(), step_start.y() + delta.y() });- if (destination == step_start) {- if (panned_visual_viewport)- return result_of_pan();- return { .accepted = true, .frame_to_present = {}, .should_request_rendering_update = true };- }-- for (auto& animation : m_smooth_scroll_animations) {- if (animation.stable_node_id != stable_node_id || !animation.is_user_scroll || animation.animation.kind() != Compositing::ScrollAnimationKind::SmoothScroll)- continue;- retarget_user_scroll(animation, destination, now);- animation.heads_to_an_extent = scrolls_to_extent;- report_started_user_scroll(animation.operation_id, stable_node_id, step_start, destination, Compositing::ScrollAnimationKind::SmoothScroll, scrolls_to_extent);- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_changes(m_async_scrolling_viewport_rect),- .should_request_rendering_update = true,- };- }-- cancel_smooth_scroll_taken_over_by_user_input(target_scroll_node_index);- auto operation_id = m_async_scroll_update_outbox.allocate_operation_id();- m_smooth_scroll_animations.append({- .stable_node_id = stable_node_id,- .operation_id = operation_id,- .animation = Compositing::SmoothScrollAnimation { *current_offset, destination, m_async_scroll_tree.device_pixels_per_css_pixel() },- .started_at = now,- .is_user_scroll = true,- .heads_to_an_extent = scrolls_to_extent,- });- report_started_user_scroll(operation_id, stable_node_id, step_start, destination, Compositing::ScrollAnimationKind::SmoothScroll, scrolls_to_extent);- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_changes(m_async_scrolling_viewport_rect),- .should_request_rendering_update = true,- };-}--Compositing::ScrollStateSnapshot ContextState::scroll_state_snapshot_at_keyboard_step_starts() const-{- Compositing::ScrollStateSnapshot snapshot { m_scroll_state_snapshot };- for (auto const& running_animation : m_smooth_scroll_animations) {- // A key continues a keyboard animation, but takes over other animations from the presented offset.- if (!running_animation.is_user_scroll || running_animation.animation.kind() != Compositing::ScrollAnimationKind::SmoothScroll)- continue;- auto scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(running_animation.stable_node_id);- if (!scroll_node_index.has_value())- continue;- auto destination = running_animation.animation.destination_offset();- // A snap destination at the boundary can still consume steps until their accumulated input reaches it.- if (auto unsnapped_destination = m_scroll_snap_controller.unsnapped_destination_for_snap_scroll(running_animation.stable_node_id, running_animation.operation_id); unsnapped_destination.has_value())- destination = m_async_scroll_tree.device_offset_from_css_pixels(*unsnapped_destination);- snapshot.set_device_offset_for_index(*scroll_node_index, { -destination.x(), -destination.y() });- }- return snapshot;-}--ContextState::ContextUpdateResult ContextState::handle_mouse_event(Web::MouseEvent const& event, MonotonicTime now)-{- if (!presents_to_client())- return ContextUpdateResult::declined(Web::InputRoutingDecision::ContextNotPresenting);-- auto position = Gfx::FloatPoint {- static_cast<float>(event.position.x().value()),- static_cast<float>(event.position.y().value()),- };- return handle_mouse_event_at(event, position, now);-}--ContextState::ContextUpdateResult ContextState::handle_mouse_event_from_containing_context(Web::MouseEvent const& event, Gfx::FloatPoint position, MonotonicTime now)-{- if (event.type == Web::MouseEvent::Type::MouseMove)- note_pointer_position(position);- else if (first_is_one_of(event.type, Web::MouseEvent::Type::MouseLeave, Web::MouseEvent::Type::MouseCancel))- note_pointer_position({});- return handle_mouse_event_at(event, position, now);-}--void ContextState::note_pointer_position(Optional<Gfx::FloatPoint> position)-{- m_pointer_position = position;-}--// The compositor presents how scrollbars expand, outside of what damage tracking sees.-Optional<PendingFrame> ContextState::frame_repainting_scrollbars() const-{- if (m_async_scrolling_viewport_rect.is_empty())- return {};- return PendingFrame::repainting_everything(m_async_scrolling_viewport_rect);-}--Optional<PendingFrame> ContextState::clear_scrollbar_hover()-{- if (!m_scrollbar_controller.set_hovered_scrollbar({}))- return {};- return frame_repainting_scrollbars();-}--Optional<size_t> ContextState::scrollbar_under_pointer(Gfx::FloatPoint position)-{- if (auto scrollbar_index = m_scrollbar_controller.hit_test_scrollbar_painted_by_compositor(m_async_scroll_tree, m_scroll_state_snapshot, position); scrollbar_index.has_value())- return scrollbar_index;- return m_scrollbar_controller.hit_test_scrollbar_painted_by_display_list(m_async_scroll_tree, m_scene.visual_context_tree_for_compositing(), m_scroll_state_snapshot, position);-}--// The compositor paints its own scrollbars over everything, so a nested context only takes the pointer where none of-// them is under it, and where no scrollbar the display list paints comes after the nested context's content in paint-// order. A press passes by a scrollbar that has faded out, as it does here.-Optional<Compositing::NestedContextHit> ContextState::nested_context_taking_mouse_event_at(Web::MouseEvent::Type type, Gfx::FloatPoint position)-{- if (!m_has_async_scrolling_state)- return {};- auto const& visual_context_tree = m_scene.visual_context_tree_for_compositing();- auto hit = m_async_scroll_tree.nested_context_at(visual_context_tree, position);- if (!hit.has_value())- return {};- if (auto scrollbar_index = m_scrollbar_controller.hit_test_scrollbar_painted_by_compositor(m_async_scroll_tree, m_scroll_state_snapshot, position); scrollbar_index.has_value()) {- if (type != Web::MouseEvent::Type::MouseDown || m_scrollbar_controller.is_shown(*scrollbar_index))- return {};- }- if (auto scrollbar_index = m_scrollbar_controller.hit_test_scrollbar_painted_by_display_list(m_async_scroll_tree, visual_context_tree, m_scroll_state_snapshot, position); scrollbar_index.has_value()) {- if (m_scrollbar_controller.scrollbars()[*scrollbar_index].paint_order_index > hit->paint_order_index)- return {};- }- return hit;-}--Optional<Compositing::NestedContextHit> ContextState::position_in_content_of_nested_context(Web::CompositorContextId nested_context_id, Gfx::FloatPoint position)-{- if (!m_has_async_scrolling_state)- return {};- return m_async_scroll_tree.position_in_content_of_nested_context(nested_context_id, m_scene.visual_context_tree_for_compositing(), position);-}--ContextState::ContextUpdateResult ContextState::handle_mouse_event_at(Web::MouseEvent const& event, Gfx::FloatPoint position, MonotonicTime now)-{- if (m_scrollbar_controller.is_empty() && !m_async_scroll_tree.has_nested_contexts())- return ContextUpdateResult::declined(Web::InputRoutingDecision::NotOverAScrollbar);-- auto scroller_of_scrollbar = [&](size_t scrollbar_index) {- return m_scrollbar_controller.scrollbars()[scrollbar_index].scroller_stable_node_id;- };-- // The pointer goes on into a nested context, and leaves the scrollbar here it was over.- auto hand_to_nested_context = [&](Compositing::NestedContextHit const& hit) {- return ContextUpdateResult {- .frame_to_present = clear_scrollbar_hover(),- .nested_context_mouse_hit = hit,- };- };-- switch (event.type) {- case Web::MouseEvent::Type::MouseDown: {- if (event.button != Web::UIEvents::MouseButton::Primary)- return ContextUpdateResult::declined(Web::InputRoutingDecision::NotPrimaryButton);-- if (auto hit = nested_context_taking_mouse_event_at(event.type, position); hit.has_value())- return hand_to_nested_context(*hit);-- auto drag = m_scrollbar_controller.begin_drag(m_async_scroll_tree, m_scene.visual_context_tree_for_compositing(), m_scroll_state_snapshot, position);- if (!drag.has_value())- return ContextUpdateResult::declined(Web::InputRoutingDecision::NotOverAScrollbar);- m_scrollbar_press_scroll_operation.clear();- stop_scrollbar_paging();-- ContextUpdateResult result;- result.accepted = true;- result.routing_decision = Web::InputRoutingDecision::BeganScrollbarDrag;- result.routed_scroller = scroller_of_scrollbar(drag->scrollbar_index);- result.scrollbar_dragged_by_compositor = m_scrollbar_controller.captured_scrollbar_painted_by_display_list(m_context_id);- result.frame_to_present = frame_repainting_scrollbars();-- // A press beside the thumb pages toward the pointer or jumps there, as the platform says, and a modifier swaps- // the two.- auto press_jumps = m_scrollbar_track_press_jumps != static_cast<bool>(event.modifiers & scrollbar_track_press_inverting_modifier);- if (drag->is_press_beside_thumb && !press_jumps) {- auto const& scrollbar = m_scrollbar_controller.scrollbars()[drag->scrollbar_index];- auto scroll_offset = m_async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, m_scroll_state_snapshot);- VERIFY(scroll_offset.has_value());- m_scrollbar_paging = ScrollbarPaging {- .direction = m_scrollbar_controller.paging_direction(drag->scrollbar_index, drag->primary_position, *scroll_offset),- .primary_position = drag->primary_position,- };- if (auto frame_to_present = page_captured_scrollbar(now); frame_to_present.has_value()) {- result.frame_to_present = *frame_to_present;- result.should_request_rendering_update = true;- }- m_host.set_timer(m_context_id, ContextTimer::ScrollbarPaging, scrollbar_paging_initial_delay);- m_scrollbar_paging_timer_is_armed = true;- return result;- }-- if (auto frame_to_present = apply_scrollbar_drag(*drag, now); frame_to_present.has_value()) {- result.frame_to_present = *frame_to_present;- result.should_request_rendering_update = true;- }- return result;- }- case Web::MouseEvent::Type::MouseMove: {- if (m_scrollbar_controller.has_captured_scrollbar()) {- auto scrollbar_dragged_by_compositor = m_scrollbar_controller.captured_scrollbar_painted_by_display_list(m_context_id);- auto drag = m_scrollbar_controller.captured_drag(m_scene.visual_context_tree_for_compositing(), m_scroll_state_snapshot, position);- VERIFY(drag.has_value());- // While paging, the pointer only says where the thumb pages to.- Optional<PendingFrame> frame_to_present;- if (m_scrollbar_paging.has_value()) {- m_scrollbar_paging->primary_position = drag->primary_position;- if (!m_scrollbar_paging_timer_is_armed) {- m_host.set_timer(m_context_id, ContextTimer::ScrollbarPaging, scrollbar_paging_repeat_interval);- m_scrollbar_paging_timer_is_armed = true;- }- } else {- frame_to_present = apply_scrollbar_drag(*drag, now);- }- return {- .accepted = true,- .frame_to_present = frame_to_present,- .should_request_rendering_update = frame_to_present.has_value(),- .scrollbar_dragged_by_compositor = scrollbar_dragged_by_compositor,- .routing_decision = Web::InputRoutingDecision::ContinuedScrollbarDrag,- .routed_scroller = scroller_of_scrollbar(drag->scrollbar_index),- };- }-- if (auto hit = nested_context_taking_mouse_event_at(event.type, position); hit.has_value())- return hand_to_nested_context(*hit);-- auto hovered_scrollbar_index = scrollbar_under_pointer(position);- Optional<PendingFrame> frame_to_present;- if (m_scrollbar_controller.set_hovered_scrollbar(hovered_scrollbar_index))- frame_to_present = frame_repainting_scrollbars();- if (!hovered_scrollbar_index.has_value())- return { .frame_to_present = frame_to_present, .routing_decision = Web::InputRoutingDecision::NotOverAScrollbar };- // The page sees the pointer move over a scrollbar the display list paints, as it is part of the page's content.- auto is_painted_by_compositor = m_scrollbar_controller.scrollbars()[*hovered_scrollbar_index].is_painted_by_compositor;- return {- .accepted = is_painted_by_compositor,- .frame_to_present = frame_to_present,- .should_request_rendering_update = false,- .routing_decision = is_painted_by_compositor ? Web::InputRoutingDecision::HoveringScrollbarPaintedByCompositor : Web::InputRoutingDecision::HoveringScrollbarPaintedByDisplayList,- .routed_scroller = scroller_of_scrollbar(*hovered_scrollbar_index),- };- }- case Web::MouseEvent::Type::MouseUp: {- if (event.button != Web::UIEvents::MouseButton::Primary)- return ContextUpdateResult::declined(Web::InputRoutingDecision::NotPrimaryButton);-- auto box_of_dragged_scrollbar = box_of_captured_scrollbar();- auto scrollbar_dragged_by_compositor = m_scrollbar_controller.captured_scrollbar_painted_by_display_list(m_context_id);- auto drag = m_scrollbar_controller.release_captured_drag(m_scene.visual_context_tree_for_compositing(), m_scroll_state_snapshot, position);- auto was_paging = m_scrollbar_paging.has_value();- stop_scrollbar_paging();- if (!drag.has_value())- return ContextUpdateResult::declined(Web::InputRoutingDecision::NoScrollbarDrag);-- note_user_scroll_gesture_end_if_drag_ended(box_of_dragged_scrollbar);-- ContextUpdateResult result;- result.accepted = true;- result.routing_decision = Web::InputRoutingDecision::EndedScrollbarDrag;- result.routed_scroller = scroller_of_scrollbar(drag->scrollbar_index);- result.scrollbar_dragged_by_compositor = scrollbar_dragged_by_compositor;- // The main thread learns of the release from the next update it takes, so one is asked for even when the- // release scrolls nothing.- result.should_request_rendering_update = true;- result.frame_to_present = frame_repainting_scrollbars();- if (!was_paging) {- if (auto frame_to_present = apply_scrollbar_drag(*drag, now); frame_to_present.has_value())- result.frame_to_present = *frame_to_present;- }-- if (m_scrollbar_controller.set_hovered_scrollbar(scrollbar_under_pointer(position))) {- if (auto frame_to_present = frame_repainting_scrollbars(); frame_to_present.has_value())- result.frame_to_present = frame_to_present;- }-- return result;- }- case Web::MouseEvent::Type::MouseLeave: {- auto had_capture = m_scrollbar_controller.has_captured_scrollbar();- Optional<PendingFrame> frame_to_present;- if (m_scrollbar_controller.set_hovered_scrollbar({}))- frame_to_present = frame_repainting_scrollbars();- return {- .accepted = had_capture,- .frame_to_present = frame_to_present,- .should_request_rendering_update = false,- .scrollbar_dragged_by_compositor = m_scrollbar_controller.captured_scrollbar_painted_by_display_list(m_context_id),- .routing_decision = had_capture ? Web::InputRoutingDecision::LeftDuringScrollbarDrag : Web::InputRoutingDecision::NoScrollbarDrag,- };- }- case Web::MouseEvent::Type::MouseCancel: {- // A cancel ends a drag where it last scrolled to, as a cancel has no position of its own, and the pointer then- // counts as having left. The page still sees the cancel, so it is not accepted.- auto was_dragging_scrollbar = m_scrollbar_controller.has_captured_scrollbar();- auto box_of_dragged_scrollbar = box_of_captured_scrollbar();- (void)m_scrollbar_controller.release_captured_drag(m_scene.visual_context_tree_for_compositing(), m_scroll_state_snapshot, position);- stop_scrollbar_paging();- note_user_scroll_gesture_end_if_drag_ended(box_of_dragged_scrollbar);- auto hovered_scrollbar_changed = m_scrollbar_controller.set_hovered_scrollbar({});-- ContextUpdateResult result;- // As for a release, the main thread learns that the drag ended from the next update it takes.- result.should_request_rendering_update = was_dragging_scrollbar;- if (was_dragging_scrollbar || hovered_scrollbar_changed)- result.frame_to_present = frame_repainting_scrollbars();- return result;- }- case Web::MouseEvent::Type::MouseWheel:- return {};- }-- VERIFY_NOT_REACHED();-}--ContextState::ContextUpdateResult ContextState::handle_pinch_event(Web::PinchEvent const& event)-{- if (!presents_to_client() || !m_has_async_scrolling_state)- return {};- if (!m_scene.visual_context_tree().has_value())- return {};-- // NB: A step with nothing to zoom, as at a limit of the scale, is the compositor's all the same: the main thread,- // whose scale may lag behind, must not zoom for it.- auto scale = 1.0 + event.scale_delta;- if (scale == 1.0)- return { .accepted = true };-- auto transform = m_scene.visual_viewport_transform();- auto old_scale = transform.matrix[0, 0];- if (old_scale <= 0)- return {};-- auto new_scale = clamp(static_cast<double>(old_scale) * scale, 1.0, 5.0);- auto applied_scale = static_cast<float>(new_scale / old_scale);- if (applied_scale == 1.0f)- return { .accepted = true };-- auto position = Gfx::FloatPoint {- static_cast<float>(event.position.x().value()),- static_cast<float>(event.position.y().value()),- };- auto gesture_transform = Gfx::translation_matrix(Gfx::FloatVector3 { position.x(), position.y(), 0 })- * Gfx::scale_matrix(Gfx::FloatVector3 { applied_scale, applied_scale, 1 })- * Gfx::translation_matrix(Gfx::FloatVector3 { -position.x(), -position.y(), 0 });-- auto old_scroll_offset = visual_viewport_scroll_offset(transform);- transform.matrix = gesture_transform * transform.matrix;- clamp_visual_viewport_transform_to_viewport(transform, m_async_scrolling_viewport_rect);- m_scene.set_async_visual_viewport_transform(transform);- rebuild_wheel_hit_test_targets();-- m_visual_viewport_document_id = m_async_scroll_tree.document_id();- if (auto document_id = m_async_scroll_tree.document_id(); document_id.has_value()) {- note_user_input_scrolled({ .node_id = document_id.value(), .kind = Web::AsyncScrollNodeKind::VisualViewport });- auto new_scroll_offset = visual_viewport_scroll_offset(transform);- Compositing::AsyncScrollOffset scroll_offset {- .stable_node_id = { .node_id = document_id.value(), .kind = Web::AsyncScrollNodeKind::VisualViewport },- .compositor_scroll_offset = new_scroll_offset,- .unadopted_scroll_delta = new_scroll_offset - old_scroll_offset,- .last_relative_scroll_delta = {},- .visual_viewport_scale = transform.matrix[0, 0],- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- };- store_pending_async_scroll_offsets({ &scroll_offset, 1 });- }-- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_everything(m_async_scrolling_viewport_rect),- .should_request_rendering_update = false,- };-}--Compositing::AsyncScrollOperationID ContextState::start_snap_scroll(Compositing::SpatialNodeIndex scroll_node_index, ScrollSnapController::SnapScrollStart&& snap_scroll, bool settles_gesture, MonotonicTime now)-{- auto const& stable_node_id = snap_scroll.stable_node_id;- // A snap scroll of this context's own that is still running is replaced by the new one; any other scroll of the- // box is taken over by the input.- auto running_animation = m_smooth_scroll_animations.find_if([&](auto const& animation) { return animation.stable_node_id == stable_node_id; });- if (running_animation != m_smooth_scroll_animations.end()) {- if (!m_scroll_snap_controller.is_snap_scroll(stable_node_id, running_animation->operation_id))- m_async_scroll_update_outbox.note_operation_taken_over_by_user_input(running_animation->operation_id);- // Keep the accumulation state the controller just recorded when selecting this snap destination.- retire_smooth_scroll_animation(stable_node_id);- }-- auto current_offset = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index, m_scroll_state_snapshot);- VERIFY(current_offset.has_value());- auto destination = snap_scroll.selection.position;- auto operation_id = m_async_scroll_update_outbox.allocate_operation_id();- m_smooth_scroll_animations.append({- .stable_node_id = stable_node_id,- .operation_id = operation_id,- .animation = Compositing::SmoothScrollAnimation { *current_offset, m_async_scroll_tree.device_offset_from_css_pixels(destination), m_async_scroll_tree.device_pixels_per_css_pixel(), snap_scroll.animation_kind },- .started_at = now,- .is_user_scroll = true,- .heads_to_an_extent = false,- });- m_scroll_snap_controller.did_start_snap_scroll(stable_node_id, operation_id, destination);- note_user_input_scrolled(stable_node_id);- m_async_scroll_update_outbox.record_started_user_scroll({- .stable_node_id = stable_node_id,- .operation_id = operation_id,- .initial_scroll_offset = snap_scroll.initial_scroll_offset,- .unsnapped_scroll_destination = snap_scroll.unsnapped_scroll_destination,- .relative_scroll_delta = snap_scroll.relative_scroll_delta,- .selection = move(snap_scroll.selection),- .settles_gesture = settles_gesture,- .is_absolute_scroll = snap_scroll.is_absolute_scroll,- .animation_kind = snap_scroll.animation_kind,- });- return operation_id;-}--// The end of a gesture snaps the boxes it panned; the first snap scroll it starts is the operation a caller follows.-Optional<Compositing::AsyncScrollOperationID> ContextState::snap_at_gesture_end(MonotonicTime now)-{- Optional<Compositing::AsyncScrollOperationID> operation_id;- for (auto& snap : m_scroll_snap_controller.decide_gesture_end(m_async_scroll_tree, m_scroll_state_snapshot)) {- auto started_operation_id = start_snap_scroll(snap.scroll_node_index, move(snap.snap_scroll), true, now);- if (!operation_id.has_value())- operation_id = started_operation_id;- }- return operation_id;-}--// The viewport rect a wheel scroll presents, moved along with the viewport when the scroll moved it.-Gfx::IntRect ContextState::note_async_scrolling_viewport_rect(Gfx::IntRect viewport_rect, Optional<Compositing::AsyncScrollOffset> const& scroll_offset)-{- if (scroll_offset.has_value()) {- auto scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(scroll_offset->stable_node_id);- if (scroll_node_index.has_value() && m_async_scroll_tree.scroll_node_is_viewport(*scroll_node_index))- viewport_rect.set_location(scroll_offset->compositor_scroll_offset.to_type<int>());- }- m_async_scrolling_viewport_rect = viewport_rect;- return viewport_rect;-}--ContextState::WheelScrollOutcome ContextState::perform_wheel_scroll_of_node(Compositing::SpatialNodeIndex scroll_node_index, Gfx::FloatPoint delta, Web::WheelDeltaPrecision wheel_delta_precision, Web::ScrollGesturePhase scroll_gesture_phase, Compositing::AsyncScrollOperationTracking operation_tracking, Gfx::IntRect viewport_rect, Compositing::ScrollChaining scroll_chaining, VisualViewportPanning visual_viewport_panning, MonotonicTime now)-{- bool pans_visual_viewport = visual_viewport_panning == VisualViewportPanning::BeforeScrolling;- auto magnification = pans_visual_viewport ? m_scene.visual_viewport_magnification() : 1.0f;- auto step_delta = delta.scaled(1.0f / magnification);-- auto const* latched_node = m_async_scroll_tree.scroll_node_for_index(scroll_node_index);- bool step_can_stretch_elastically = wheel_step_can_stretch_elastically(wheel_delta_precision, scroll_gesture_phase);- bool fingers_can_stretch_latched_scroller = step_can_stretch_elastically && scroll_gesture_phase == Web::ScrollGesturePhase::Ongoing && latched_node;- bool momentum_can_bounce_latched_scroller = step_can_stretch_elastically && scroll_gesture_phase == Web::ScrollGesturePhase::Momentum && latched_node- && m_wheel_gesture_routing.momentum_of_latched_gesture_can_spring_scroller_back();- auto presented_stretch_of_latched_scroller = [&]() -> Gfx::FloatPoint {- if (!latched_node)- return {};- return m_elastic_overscroll_controller.stretch_of(latched_node->stable_node_id);- };- auto stretch_before_step = presented_stretch_of_latched_scroller();-- // Momentum only arrives once the fingers have lifted, and its first step can be the first sign that they did.- if (step_can_stretch_elastically && scroll_gesture_phase == Web::ScrollGesturePhase::Momentum)- m_elastic_overscroll_controller.release_held_by_fingers(now);- if (momentum_can_bounce_latched_scroller && m_elastic_overscroll_controller.has_active_overscroll_of(latched_node->stable_node_id)) {- // The fingers lifted from a stretched scroller, which this momentum already springs back with.- m_wheel_gesture_routing.set_momentum_of_latched_gesture_has_sprung_scroller_back(true);- momentum_can_bounce_latched_scroller = false;- }-- // A stretched scroller is past the edge of everything the gesture moves, so the fingers relax the stretch before- // they pan the visual viewport away from its own edge.- auto delta_left = delta;- if (fingers_can_stretch_latched_scroller) {- m_wheel_gesture_routing.set_momentum_of_latched_gesture_has_sprung_scroller_back(false);- auto step_delta_left = m_elastic_overscroll_controller.relax_by(latched_node->stable_node_id, step_delta);- if (step_delta_left != step_delta)- delta_left = step_delta_left.scaled(magnification);- }-- WheelScrollOutcome outcome;- bool visual_viewport_took_rest_of_step = false;- if (pans_visual_viewport) {- auto panned_delta = pan_visual_viewport_by(delta_left);- if (!panned_delta.is_zero()) {- delta_left -= panned_delta;- visual_viewport_took_rest_of_step = delta_left.is_zero();- outcome.viewport_rect_to_present = note_async_scrolling_viewport_rect(viewport_rect, {});- }- }-- Optional<Gfx::FloatPoint> delta_the_scroller_did_not_scroll_by;- if (!visual_viewport_took_rest_of_step) {- auto node_scroll = scroll_node_by_wheel_delta(scroll_node_index, delta_left.scaled(1.0f / magnification), wheel_delta_precision, scroll_gesture_phase, operation_tracking, viewport_rect, scroll_chaining, now);- outcome.operation_id = node_scroll.outcome.operation_id;- if (node_scroll.outcome.viewport_rect_to_present.has_value())- outcome.viewport_rect_to_present = node_scroll.outcome.viewport_rect_to_present;- delta_the_scroller_did_not_scroll_by = node_scroll.delta_the_node_did_not_scroll_by;- }-- if (delta_the_scroller_did_not_scroll_by.has_value()) {- if (fingers_can_stretch_latched_scroller) {- pull_elastic_overscroll_by(*latched_node, step_delta, *delta_the_scroller_did_not_scroll_by);- } else if (momentum_can_bounce_latched_scroller && pull_elastic_overscroll_by(*latched_node, step_delta, *delta_the_scroller_did_not_scroll_by)) {- // Momentum that carries a scroller into its edge bounces it: the velocity it arrives with takes the- // rebound out past the edge before the rebound brings it back.- m_elastic_overscroll_controller.release_held_by_fingers(now);- m_wheel_gesture_routing.set_momentum_of_latched_gesture_has_sprung_scroller_back(true);- }- }-- if (!outcome.viewport_rect_to_present.has_value() && presented_stretch_of_latched_scroller() != stretch_before_step) {- outcome.viewport_rect_to_present = note_async_scrolling_viewport_rect(viewport_rect, {});- outcome.only_elastic_overscroll_changed = true;- }- return outcome;-}--ContextState::NodeScrollByWheelDelta ContextState::scroll_node_by_wheel_delta(Compositing::SpatialNodeIndex scroll_node_index, Gfx::FloatPoint delta, Web::WheelDeltaPrecision wheel_delta_precision, Web::ScrollGesturePhase scroll_gesture_phase, Compositing::AsyncScrollOperationTracking operation_tracking, Gfx::IntRect viewport_rect, Compositing::ScrollChaining scroll_chaining, MonotonicTime now)-{- WheelScrollOutcome outcome;- Optional<Compositing::WheelScrollTarget> wheel_scroll_target;- if (wheel_delta_precision == Web::WheelDeltaPrecision::Discrete) {- wheel_scroll_target = m_async_scroll_tree.select_wheel_scroll_target(scroll_node_index, delta, m_scroll_state_snapshot, [this](auto stable_node_id) { return in_flight_wheel_destination(stable_node_id); }, scroll_chaining);- if (wheel_scroll_target.has_value()) {- scroll_node_index = *m_async_scroll_tree.scroll_node_index_for_stable_id(wheel_scroll_target->stable_node_id);- m_wheel_gesture_routing.relatch_to(wheel_scroll_target->stable_node_id);- }- }- auto css_delta = m_async_scroll_tree.css_pixels_from_device_offset(delta);-- Optional<ScrollSnapController::StepDecision> decision;- if (wheel_delta_precision == Web::WheelDeltaPrecision::Discrete) {- Optional<Web::CSSPixelPoint> scroll_in_flight_destination;- if (auto const* node = m_async_scroll_tree.scroll_node_for_index(scroll_node_index))- scroll_in_flight_destination = in_flight_wheel_destination(node->stable_node_id).map([&](auto offset) { return m_async_scroll_tree.css_pixels_from_device_offset(offset); });- decision = m_scroll_snap_controller.decide_discrete_step(m_async_scroll_tree, m_scroll_state_snapshot, scroll_node_index, css_delta, scroll_in_flight_destination, now);- } else if (scroll_gesture_phase == Web::ScrollGesturePhase::Momentum) {- decision = m_scroll_snap_controller.decide_momentum_delta(m_async_scroll_tree, m_scroll_state_snapshot, scroll_node_index, css_delta);- }-- if (decision.has_value()) {- schedule_end_of_scroll_step_gestures(now);- if (auto* snap_scroll = decision->get_pointer<ScrollSnapController::SnapScrollStart>()) {- if (wheel_delta_precision == Web::WheelDeltaPrecision::Discrete)- snap_scroll->animation_kind = Compositing::ScrollAnimationKind::Wheel;- auto operation_id = start_snap_scroll(scroll_node_index, move(*snap_scroll), false, now);- if (operation_tracking == Compositing::AsyncScrollOperationTracking::Yes)- outcome.operation_id = operation_id;- outcome.viewport_rect_to_present = note_async_scrolling_viewport_rect(viewport_rect, {});- return { outcome, {} };- }- if (operation_tracking == Compositing::AsyncScrollOperationTracking::Yes) {- outcome.operation_id = m_async_scroll_update_outbox.allocate_operation_id();- m_async_scroll_update_outbox.complete_operation(*outcome.operation_id);- }- return { outcome, {} };- }-- if (wheel_delta_precision == Web::WheelDeltaPrecision::Discrete) {- auto result = smooth_wheel_scroll_by(wheel_scroll_target, viewport_rect, now);- outcome.operation_id = result.enqueue_result.operation_id;- if (result.frame_to_present.has_value())- outcome.viewport_rect_to_present = viewport_rect;- return { outcome, {} };- }-- cancel_smooth_scroll_taken_over_by_user_input(scroll_node_index);- if (operation_tracking == Compositing::AsyncScrollOperationTracking::Yes)- outcome.operation_id = m_async_scroll_update_outbox.allocate_operation_id();-- auto scroll_offset = m_async_scroll_tree.apply_scroll_delta(scroll_node_index, delta, m_scene.current_visual_context_tree(), m_scroll_state_snapshot, scroll_chaining);- if (!scroll_offset.has_value()) {- if (outcome.operation_id.has_value())- m_async_scroll_update_outbox.complete_operation(*outcome.operation_id);- return { outcome, delta };- }-- note_user_input_scrolled(scroll_offset->stable_node_id);-- // On the first step of a gesture, scroll node chaining may have scrolled an ancestor instead, which took the delta.- auto const* node = m_async_scroll_tree.scroll_node_for_index(scroll_node_index);- bool an_ancestor_scrolled = node && scroll_offset->stable_node_id != node->stable_node_id;- Optional<Gfx::FloatPoint> delta_the_node_did_not_scroll_by;- if (!an_ancestor_scrolled)- delta_the_node_did_not_scroll_by = delta - scroll_offset->unadopted_scroll_delta;-- // The box the delta moved is the one a gesture pans; on the first step of a gesture, scroll node chaining may have- // moved an ancestor of the node the gesture latched to.- auto scroll_offset_before_scroll = scroll_offset->compositor_scroll_offset - scroll_offset->unadopted_scroll_delta;- m_scroll_snap_controller.did_scroll_node_plainly(scroll_offset->stable_node_id, scroll_gesture_phase, m_async_scroll_tree.css_pixels_from_device_offset(scroll_offset_before_scroll));-- // https://drafts.csswg.org/css-scroll-snap-1/#scroll-types- // A wheel or panning scroll is relative, which scroll-state(scrolled) queries observe.- scroll_offset->last_relative_scroll_delta = scroll_offset->unadopted_scroll_delta;-- rebuild_wheel_hit_test_targets();- store_pending_async_scroll_offsets({ &*scroll_offset, 1 }, outcome.operation_id);- outcome.viewport_rect_to_present = note_async_scrolling_viewport_rect(viewport_rect, scroll_offset);- return { outcome, delta_the_node_did_not_scroll_by };-}--void ContextState::note_user_input_scrolled(Web::AsyncScrollNodeStableID stable_node_id)-{- m_user_input_scroll_counts.ensure(stable_node_id)++;- m_context_user_input_scroll_count++;-}--Optional<Gfx::Orientation> ContextState::axis_held_by_scrollbar_of(Compositing::SpatialNodeIndex scroll_node_index) const-{- // Paging steps toward the pointer like keys do, and takes a script's scroll along like them.- auto scrollbar_index = m_scrollbar_controller.captured_scrollbar_index();- if (!scrollbar_index.has_value() || m_scrollbar_paging.has_value())- return {};- auto const& scrollbar = m_scrollbar_controller.scrollbars()[scrollbar_index.value()];- if (scrollbar.scroll_node_index != scroll_node_index)- return {};- return scrollbar.vertical ? Gfx::Orientation::Vertical : Gfx::Orientation::Horizontal;-}--Optional<PendingFrame> ContextState::apply_scroll_requests(ReadonlySpan<Compositing::ScrollRequest> scroll_requests, MonotonicTime now)-{- Vector<Compositing::AsyncScrollOffset> answers;- for (auto const& scroll_request : scroll_requests) {- // The box's offsets are reported as of this request from here on, whether or not the box is here yet.- m_applied_scroll_request_ids.set(scroll_request.stable_node_id, scroll_request.request_id);- bool moved_the_box = false;- ScopeGuard note_request_applied = [&] {- m_async_scroll_update_outbox.note_scroll_request_applied({ scroll_request.stable_node_id, scroll_request.request_id, moved_the_box });- };- if (scroll_request.stable_node_id.kind == Web::AsyncScrollNodeKind::VisualViewport) {- moved_the_box = apply_visual_viewport_scroll_request(scroll_request, answers);- continue;- }-- Optional<Compositing::SpatialNodeIndex> scroll_node_index;- if (m_has_async_scrolling_state)- scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(scroll_request.stable_node_id);- auto old_offset = scroll_node_index.has_value() ? m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot) : Optional<Gfx::FloatPoint> {};- if (!old_offset.has_value()) {- if (scroll_request.smooth_scroll.has_value())- m_async_scroll_update_outbox.complete_operation(scroll_request.smooth_scroll->operation_id);- continue;- }-- // The answer tells the main thread where the box went for the request, even where it stayed where it was.- auto answer_with_the_offset_of_the_box = [&] {- auto new_offset = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot).value();- moved_the_box = new_offset != old_offset.value();- if (m_async_scroll_tree.scroll_node_is_viewport(scroll_node_index.value()))- m_async_scrolling_viewport_rect.set_location(new_offset.to_type<int>());- answers.append({- .stable_node_id = scroll_request.stable_node_id,- .compositor_scroll_offset = new_offset,- .unadopted_scroll_delta = new_offset - old_offset.value(),- .last_relative_scroll_delta = {},- .visual_viewport_scale = {},- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- });- };-- // A request aborts the box's smooth scroll, unless it heads that very scroll somewhere else.- Optional<Compositing::AsyncScrollOperationID> retargeted_operation_id;- if (scroll_request.smooth_scroll.has_value() && scroll_request.smooth_scroll->retargets_operation)- retargeted_operation_id = scroll_request.smooth_scroll->operation_id;- auto running_animation = m_smooth_scroll_animations.find_if([&](auto const& animation) { return animation.stable_node_id == scroll_request.stable_node_id; });- bool retargets_running_animation = running_animation != m_smooth_scroll_animations.end() && running_animation->operation_id == retargeted_operation_id;- // A step of the user's by a distance goes on from where the user's scroll of the same kind is headed, unless the- // box jumped or scrolled elsewhere first.- Optional<Gfx::FloatPoint> destination_of_running_user_scroll;- if (running_animation != m_smooth_scroll_animations.end() && running_animation->is_user_scroll && scroll_request.smooth_scroll.has_value()- && running_animation->animation.kind() == scroll_request.smooth_scroll->animation_kind- && !scroll_request.jump_offset.has_value() && !scroll_request.relative_scroll.has_value())- destination_of_running_user_scroll = running_animation->animation.destination_offset();-- // The main thread settled the user's gesture once it heard of no more input for the box. User input this- // context took since then carries the gesture on, and the box goes where that input takes it instead.- auto smooth_scroll = scroll_request.smooth_scroll;- if (smooth_scroll.has_value() && smooth_scroll->settled_user_input_scroll_count.has_value() && !retargets_running_animation- && m_user_input_scroll_counts.get(scroll_request.stable_node_id).value_or(0) > smooth_scroll->settled_user_input_scroll_count.value()) {- m_async_scroll_update_outbox.note_operation_taken_over_by_user_input(smooth_scroll->operation_id);- m_async_scroll_update_outbox.complete_operation(smooth_scroll->operation_id);- smooth_scroll.clear();- if (!scroll_request.jump_offset.has_value() && !scroll_request.relative_scroll.has_value()) {- answer_with_the_offset_of_the_box();- continue;- }- }-- bool has_instant_scroll = scroll_request.jump_offset.has_value() || scroll_request.relative_scroll.has_value();- bool instant_scroll_is_for_script = has_instant_scroll && !scroll_request.instant_scroll_is_for_user_input;- bool smooth_scroll_is_for_script = smooth_scroll.has_value() && smooth_scroll->initiator == Compositing::SmoothScrollInitiator::Programmatic;-- // The thumb of a scrollbar that the user holds stays under the pointer: the user scrolls the box along that axis- // from the moment a script does, which aborts a smooth scroll of the script's.- auto axis_held_by_scrollbar = axis_held_by_scrollbar_of(scroll_node_index.value());- if (axis_held_by_scrollbar.has_value() && smooth_scroll_is_for_script) {- m_async_scroll_update_outbox.note_operation_taken_over_by_user_input(smooth_scroll->operation_id);- m_async_scroll_update_outbox.complete_operation(smooth_scroll->operation_id);- smooth_scroll.clear();- smooth_scroll_is_for_script = false;- }-- // A smooth scroll in progress is aborted by any other, and by an instant scroll, except that a script's instant- // scroll carries the steps of the user's scroll along with it. A request that only aborts is for the main- // thread's own scrolls.- bool shifts_running_animation = false;- if (running_animation != m_smooth_scroll_animations.end() && !retargets_running_animation) {- bool running_animation_is_requested = running_animation->operation_id >= Compositing::first_operation_id_the_main_thread_requests;- bool running_animation_is_user_step = running_animation->is_user_scroll- && running_animation->animation.kind() != Compositing::ScrollAnimationKind::Momentum- && !m_scroll_snap_controller.is_snap_scroll(scroll_request.stable_node_id, running_animation->operation_id);- if (smooth_scroll.has_value())- cancel_smooth_scroll(scroll_request.stable_node_id);- else if (has_instant_scroll && instant_scroll_is_for_script && running_animation_is_user_step)- shifts_running_animation = true;- else if (has_instant_scroll || running_animation_is_requested)- cancel_smooth_scroll(scroll_request.stable_node_id);- } else if (!retargets_running_animation && smooth_scroll.has_value()) {- m_scroll_snap_controller.did_start_main_thread_scroll(scroll_request.stable_node_id);- }-- auto offset_before_instant_scroll = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot).value();- if (scroll_request.jump_offset.has_value())- (void)m_async_scroll_tree.set_scroll_offset(scroll_node_index.value(), scroll_request.jump_offset.value(), m_scene.current_visual_context_tree(), m_scroll_state_snapshot);- // A box new to this context took its offset from the frame's snapshot, which has the frame's scrolls in it.- bool offset_has_the_request_in_it = m_scroll_nodes_seeded_by_last_frame.contains(scroll_request.stable_node_id);- if (auto const& relative_scroll = scroll_request.relative_scroll; relative_scroll.has_value() && !offset_has_the_request_in_it) {- if (scroll_request.relative_scroll_moves_visual_viewport_first && m_async_scroll_tree.scroll_node_is_viewport(scroll_node_index.value())) {- scroll_visual_viewport_position_in_page(scroll_node_index.value(), relative_scroll.value(), answers);- } else {- auto offset = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot).value();- (void)m_async_scroll_tree.set_scroll_offset(scroll_node_index.value(), relative_scroll->applied_to(offset), m_scene.current_visual_context_tree(), m_scroll_state_snapshot);- }- }- if (axis_held_by_scrollbar.has_value() && instant_scroll_is_for_script) {- auto offset = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot).value();- offset.set_primary_offset_for_orientation(axis_held_by_scrollbar.value(), offset_before_instant_scroll.primary_offset_for_orientation(axis_held_by_scrollbar.value()));- (void)m_async_scroll_tree.set_scroll_offset(scroll_node_index.value(), offset, m_scene.current_visual_context_tree(), m_scroll_state_snapshot);- }- auto instant_scroll_delta = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot).value() - offset_before_instant_scroll;-- if (shifts_running_animation) {- // A step that goes to an end of the scroll range still goes there.- if (!running_animation->heads_to_an_extent) {- running_animation->animation.shift_by(instant_scroll_delta);- auto destination_offset = running_animation->animation.destination_offset();- auto clamped_destination_offset = m_async_scroll_tree.clamped_scroll_offset_for_node(scroll_node_index.value(), destination_offset);- if (clamped_destination_offset != destination_offset)- running_animation->animation.retarget(clamped_destination_offset, now - running_animation->started_at);- }- }-- if (instant_scroll_is_for_script)- m_elastic_overscroll_controller.drop_stretch_moved_by(scroll_request.stable_node_id, instant_scroll_delta);- if (smooth_scroll_is_for_script)- m_elastic_overscroll_controller.release_stretch_of(scroll_request.stable_node_id, now);-- if (smooth_scroll.has_value()) {- auto destination_offset = smooth_scroll->destination_offset;- if (smooth_scroll->destination_is_relative) {- auto relative_scroll_start = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot).value();- if (smooth_scroll->initiator == Compositing::SmoothScrollInitiator::UserInput && destination_of_running_user_scroll.has_value())- relative_scroll_start = destination_of_running_user_scroll.value();- destination_offset = smooth_scroll->relative_scroll().applied_to(relative_scroll_start);- }- destination_offset = m_async_scroll_tree.clamped_scroll_offset_for_node(scroll_node_index.value(), destination_offset);- if (retargets_running_animation) {- retarget_user_scroll(*running_animation, destination_offset, now);- } else {- auto start_offset = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index.value(), m_scroll_state_snapshot).value();- Compositing::SmoothScrollAnimation animation { start_offset, destination_offset, m_async_scroll_tree.device_pixels_per_css_pixel(), smooth_scroll->animation_kind };- if (animation.duration().is_zero()) {- m_async_scroll_update_outbox.complete_operation(smooth_scroll->operation_id);- } else {- m_smooth_scroll_animations.append({- .stable_node_id = scroll_request.stable_node_id,- .operation_id = smooth_scroll->operation_id,- .animation = move(animation),- .started_at = now,- .is_user_scroll = smooth_scroll->initiator == Compositing::SmoothScrollInitiator::UserInput,- .heads_to_an_extent = false,- });- }- }- }-- answer_with_the_offset_of_the_box();- }-- if (answers.is_empty()) {- request_rendering_update();- return {};- }- store_pending_async_scroll_offsets(answers);- if (m_has_async_scrolling_state)- rebuild_wheel_hit_test_targets();- request_rendering_update();- return PendingFrame::repainting_changes(m_async_scrolling_viewport_rect);-}--// https://drafts.csswg.org/cssom-view/#viewport-perform-a-scroll-// The visual viewport takes as much of the scroll as it can before the layout viewport takes the rest.-void ContextState::scroll_visual_viewport_position_in_page(Compositing::SpatialNodeIndex viewport_scroll_node_index, Compositing::RequestedRelativeScroll const& relative_scroll, Vector<Compositing::AsyncScrollOffset>& answers)-{- auto layout_viewport_offset = m_async_scroll_tree.scroll_offset_for_node(viewport_scroll_node_index, m_scroll_state_snapshot).value();- auto transform = m_scene.visual_viewport_transform();- auto scale = transform.matrix[0, 0];- auto old_visual_viewport_offset = visual_viewport_scroll_offset(transform);- auto page_position = layout_viewport_offset.translated(old_visual_viewport_offset);- auto delta = relative_scroll.applied_to(page_position) - page_position;-- auto share_of_viewport_the_visual_viewport_moves_over = scale <= 1.0f ? 0.0f : (scale - 1.0f) / scale;- Gfx::FloatPoint maximum_visual_viewport_offset {- static_cast<float>(m_async_scrolling_viewport_rect.width()) * share_of_viewport_the_visual_viewport_moves_over,- static_cast<float>(m_async_scrolling_viewport_rect.height()) * share_of_viewport_the_visual_viewport_moves_over,- };- Gfx::FloatPoint new_visual_viewport_offset {- AK::clamp(old_visual_viewport_offset.x() + delta.x(), 0.0f, maximum_visual_viewport_offset.x()),- AK::clamp(old_visual_viewport_offset.y() + delta.y(), 0.0f, maximum_visual_viewport_offset.y()),- };- auto visual_delta = new_visual_viewport_offset - old_visual_viewport_offset;- (void)m_async_scroll_tree.set_scroll_offset(viewport_scroll_node_index, layout_viewport_offset.translated(delta - visual_delta), m_scene.current_visual_context_tree(), m_scroll_state_snapshot);- if (visual_delta.is_zero())- return;-- transform.matrix[0, 3] = -new_visual_viewport_offset.x() * scale;- transform.matrix[1, 3] = -new_visual_viewport_offset.y() * scale;- m_scene.set_async_visual_viewport_transform(transform);- m_visual_viewport_document_id = m_async_scroll_tree.document_id();- answers.append({- .stable_node_id = { .node_id = m_async_scroll_tree.document_id().value(), .kind = Web::AsyncScrollNodeKind::VisualViewport },- .compositor_scroll_offset = new_visual_viewport_offset,- .unadopted_scroll_delta = visual_delta,- .last_relative_scroll_delta = {},- .visual_viewport_scale = scale,- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- });-}--bool ContextState::apply_visual_viewport_scroll_request(Compositing::ScrollRequest const& scroll_request, Vector<Compositing::AsyncScrollOffset>& answers)-{- // The main thread animates the visual viewport itself, one jump at a time.- if (scroll_request.smooth_scroll.has_value())- m_async_scroll_update_outbox.complete_operation(scroll_request.smooth_scroll->operation_id);- if (!m_scene.visual_context_tree().has_value() || scroll_request.stable_node_id.node_id != m_async_scroll_tree.document_id())- return false;-- auto transform = m_scene.visual_viewport_transform();- auto old_scroll_offset = visual_viewport_scroll_offset(transform);- if (scroll_request.jump_offset.has_value()) {- auto scale = scroll_request.visual_viewport_scale.value_or(transform.matrix[0, 0]);- transform.matrix[0, 0] = scale;- transform.matrix[1, 1] = scale;- transform.matrix[0, 3] = -scroll_request.jump_offset->x() * scale;- transform.matrix[1, 3] = -scroll_request.jump_offset->y() * scale;- clamp_visual_viewport_transform_to_viewport(transform, m_async_scrolling_viewport_rect);- m_scene.set_async_visual_viewport_transform(transform);- m_visual_viewport_document_id = scroll_request.stable_node_id.node_id;- rebuild_wheel_hit_test_targets();- }-- auto new_scroll_offset = visual_viewport_scroll_offset(transform);- answers.append({- .stable_node_id = scroll_request.stable_node_id,- .compositor_scroll_offset = new_scroll_offset,- .unadopted_scroll_delta = new_scroll_offset - old_scroll_offset,- .last_relative_scroll_delta = {},- .visual_viewport_scale = transform.matrix[0, 0],- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- });- return new_scroll_offset != old_scroll_offset;-}--Optional<Gfx::FloatPoint> ContextState::in_flight_wheel_destination(Web::AsyncScrollNodeStableID stable_node_id) const-{- for (auto const& animation : m_smooth_scroll_animations) {- if (animation.stable_node_id == stable_node_id && animation.animation.kind() == Compositing::ScrollAnimationKind::Wheel)- return animation.animation.destination_offset();- }- return {};-}--ContextState::AsyncScrollResult ContextState::smooth_wheel_scroll_by(Optional<Compositing::WheelScrollTarget> const& scroll_target, Gfx::IntRect viewport_rect, MonotonicTime now)-{- if (!scroll_target.has_value()) {- auto operation_id = m_async_scroll_update_outbox.allocate_operation_id();- m_async_scroll_update_outbox.complete_operation(operation_id);- return {- .enqueue_result = { true, operation_id },- .frame_to_present = {},- };- }-- for (auto& active_animation : m_smooth_scroll_animations) {- if (active_animation.stable_node_id != scroll_target->stable_node_id)- continue;- if (active_animation.animation.kind() == Compositing::ScrollAnimationKind::Wheel) {- retarget_user_scroll(active_animation, scroll_target->destination_offset, now);- report_started_user_scroll(active_animation.operation_id, scroll_target->stable_node_id, scroll_target->start_offset, scroll_target->destination_offset, active_animation.animation.kind());- m_async_scrolling_viewport_rect = viewport_rect;- return {- .enqueue_result = { true, active_animation.operation_id },- .frame_to_present = PendingFrame::repainting_changes(viewport_rect),- };- }- m_async_scroll_update_outbox.note_operation_taken_over_by_user_input(active_animation.operation_id);- cancel_smooth_scroll(scroll_target->stable_node_id);- break;- }-- auto operation_id = m_async_scroll_update_outbox.allocate_operation_id();- m_smooth_scroll_animations.append({- .stable_node_id = scroll_target->stable_node_id,- .operation_id = operation_id,- .animation = Compositing::SmoothScrollAnimation { scroll_target->current_offset, scroll_target->destination_offset, m_async_scroll_tree.device_pixels_per_css_pixel(), Compositing::ScrollAnimationKind::Wheel },- .started_at = now,- .is_user_scroll = true,- .heads_to_an_extent = false,- });- report_started_user_scroll(operation_id, scroll_target->stable_node_id, scroll_target->start_offset, scroll_target->destination_offset, Compositing::ScrollAnimationKind::Wheel);- m_async_scrolling_viewport_rect = viewport_rect;- return {- .enqueue_result = { true, operation_id },- .frame_to_present = PendingFrame::repainting_changes(viewport_rect),- };-}--void ContextState::retarget_user_scroll(ActiveSmoothScrollAnimation& running_animation, Gfx::FloatPoint destination_offset, MonotonicTime now)-{- m_scroll_snap_controller.did_retarget_scroll(running_animation.stable_node_id, running_animation.operation_id);- running_animation.animation.retarget(destination_offset, now - running_animation.started_at);-}--void ContextState::cancel_smooth_scroll(Web::AsyncScrollNodeStableID stable_node_id)-{- retire_smooth_scroll_animation(stable_node_id);- m_scroll_snap_controller.did_start_main_thread_scroll(stable_node_id);-}--void ContextState::retire_smooth_scroll_animation(Web::AsyncScrollNodeStableID stable_node_id)-{- for (size_t index = 0; index < m_smooth_scroll_animations.size(); ++index) {- auto const& smooth_scroll_animation = m_smooth_scroll_animations[index];- if (smooth_scroll_animation.stable_node_id != stable_node_id)- continue;- if (m_scroll_snap_controller.is_snap_scroll(stable_node_id, smooth_scroll_animation.operation_id)) {- Optional<Web::CSSPixelPoint> scroll_offset;- if (auto scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(stable_node_id); scroll_node_index.has_value())- scroll_offset = m_async_scroll_tree.css_scroll_offset_for_node(*scroll_node_index, m_scroll_state_snapshot);- m_scroll_snap_controller.did_end_snap_scroll(stable_node_id, smooth_scroll_animation.operation_id, scroll_offset);- }- m_async_scroll_update_outbox.complete_operation(smooth_scroll_animation.operation_id);- m_smooth_scroll_animations.remove(index);- request_rendering_update();- return;- }-}--Optional<Gfx::IntRect> ContextState::advance_smooth_scroll_animations(MonotonicTime now)-{- Vector<Compositing::AsyncScrollOffset> scroll_offsets;- bool changed_scroll_offset = false;- bool completed_operation = false;-- for (size_t index = 0; index < m_smooth_scroll_animations.size();) {- auto& active_animation = m_smooth_scroll_animations[index];- auto scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(active_animation.stable_node_id);- if (!scroll_node_index.has_value()) {- m_async_scroll_update_outbox.complete_operation(active_animation.operation_id);- completed_operation = true;- m_smooth_scroll_animations.remove(index);- continue;- }-- auto old_offset = m_async_scroll_tree.scroll_offset_for_node(*scroll_node_index, m_scroll_state_snapshot);- if (!old_offset.has_value()) {- m_async_scroll_update_outbox.complete_operation(active_animation.operation_id);- completed_operation = true;- m_smooth_scroll_animations.remove(index);- continue;- }-- auto sample = active_animation.animation.sample(now - active_animation.started_at);- auto new_offset = m_async_scroll_tree.set_scroll_offset(*scroll_node_index, sample.offset, m_scene.current_visual_context_tree(), m_scroll_state_snapshot);- VERIFY(new_offset.has_value());- auto scroll_delta = *new_offset - *old_offset;- if (!scroll_delta.is_zero()) {- scroll_offsets.append({- .stable_node_id = active_animation.stable_node_id,- .compositor_scroll_offset = *new_offset,- .unadopted_scroll_delta = scroll_delta,- .last_relative_scroll_delta = {},- .visual_viewport_scale = {},- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- });- changed_scroll_offset = true;- if (m_async_scroll_tree.scroll_node_is_viewport(*scroll_node_index))- m_async_scrolling_viewport_rect.set_location(new_offset->to_type<int>());- }-- if (sample.complete) {- m_scroll_snap_controller.did_end_snap_scroll(active_animation.stable_node_id, active_animation.operation_id, m_async_scroll_tree.css_pixels_from_device_offset(*new_offset));- m_async_scroll_update_outbox.complete_operation(active_animation.operation_id);- completed_operation = true;- m_smooth_scroll_animations.remove(index);- } else {- ++index;- }- }-- if (!scroll_offsets.is_empty()) {- rebuild_wheel_hit_test_targets();- store_pending_async_scroll_offsets(scroll_offsets);- }- if (changed_scroll_offset || completed_operation)- request_rendering_update();- if (changed_scroll_offset)- return m_async_scrolling_viewport_rect;- return {};-}--ContextState::ContextUpdateResult ContextState::handle_wheel_event(Web::MouseEvent const& event, bool is_first_wheel_event_with_delta, WheelEventListenerGate const& listener_gate, MonotonicTime now)-{- VERIFY(event.type == Web::MouseEvent::Type::MouseWheel);- if (!presents_to_client())- return ContextUpdateResult::declined(Web::InputRoutingDecision::ContextNotPresenting);- m_scroll_fling_controller.note_wheel_event(event, now);- return scroll_for_wheel_event(event, is_first_wheel_event_with_delta, listener_gate, Compositing::AsyncScrollOperationTracking::No, now);-}--ContextState::ContextUpdateResult ContextState::scroll_for_wheel_event_from_main_thread(Web::MouseEvent const& event, bool is_first_wheel_event_with_delta, WheelEventListenerGate const& listener_gate, Compositing::AsyncScrollOperationTracking operation_tracking, MonotonicTime now)-{- VERIFY(event.type == Web::MouseEvent::Type::MouseWheel);- return scroll_for_wheel_event(event, is_first_wheel_event_with_delta, listener_gate, operation_tracking, now);-}--static Gfx::FloatPoint wheel_event_position(Web::MouseEvent const& event)-{- return {- static_cast<float>(event.position.x().value()),- static_cast<float>(event.position.y().value()),- };-}--Gfx::FloatPoint ContextState::wheel_event_delta_in_device_pixels(Web::MouseEvent const& event) const-{- auto wheel_delta_x = event.wheel_delta_x;- auto wheel_delta_y = event.wheel_delta_y;- if (event.modifiers & Web::UIEvents::KeyModifier::Mod_Shift)- swap(wheel_delta_x, wheel_delta_y);- return Gfx::FloatPoint { static_cast<float>(wheel_delta_x), static_cast<float>(wheel_delta_y) }- .scaled(static_cast<float>(m_async_scroll_tree.device_pixels_per_css_pixel()));-}--ContextState::WheelEventListenerGate ContextState::wheel_event_listener_gate(Optional<u64> gesture_id) const-{- return {- .page_let_the_gesture_through = m_wheel_gesture_routing.page_let_gesture_through(gesture_id),- .reason_to_hold_latched_steps_back = m_wheel_gesture_routing.reason_to_hold_latched_steps_back(gesture_id),- };-}--void ContextState::note_wheel_event_left_to_the_page(Web::MouseEvent const& event)-{- m_wheel_gesture_routing.note_delta_left_to_the_page(WheelStep::for_wheel_event(event, {}, Compositing::AsyncScrollOperationTracking::No).delta_in_css_pixels);-}--ContextState::NotedWheelEvent ContextState::note_wheel_event(Web::MouseEvent const& event, MonotonicTime now)-{- VERIFY(event.type == Web::MouseEvent::Type::MouseWheel);- // The end of the gesture before this one may never have arrived.- auto noted = m_wheel_gesture_routing.note_wheel_event(event, wheel_event_position(event), m_async_scroll_tree, now);- if (noted.starts_gesture)- m_elastic_overscroll_controller.end_gesture(now);- return {- .wheel_gesture_mark = {- .gesture_id = m_wheel_gesture_routing.gesture_id().value(),- .lasts_until_fingers_lift = m_wheel_gesture_routing.gesture_lasts_until_fingers_lift(),- .step_number = noted.step_number,- },- .is_first_wheel_event_with_delta = noted.is_first_wheel_event_with_delta,- };-}--ContextState::NotedWheelEvent ContextState::note_wheel_event_from_ui(Web::MouseEvent const& event, MonotonicTime now)-{- auto phase = event.scroll_gesture_phase;- auto noted = note_wheel_event(event, now);-- if (phase == Web::ScrollGesturePhase::Momentum) {- m_last_reported_scroll_momentum_step = event.clone_without_browser_data();- m_last_reported_scroll_momentum_step->wheel_gesture_mark = noted.wheel_gesture_mark;- } else {- m_last_reported_scroll_momentum_step.clear();- }-- // A stretch is released with the velocity of the steps as they arrived from the UI, not as they were scrolled.- // Fling steps are not timed here, which leaves them out of the velocity; no platform both flings and stretches.- if (wheel_step_can_stretch_elastically(event.wheel_delta_precision, phase))- m_elastic_overscroll_controller.note_step_from_ui(wheel_event_delta_in_device_pixels(event).scaled(1.0f / m_scene.visual_viewport_magnification()), now);- return noted;-}--ContextState::NotedWheelEvent ContextState::note_wheel_event_from_main_thread(Web::MouseEvent const& event, MonotonicTime now)-{- return note_wheel_event(event, now);-}--bool ContextState::start_scroll_fling_if_flicked(Web::MouseEvent const& gesture_end_event, MonotonicTime now)-{- return m_scroll_fling_controller.start_if_flicked(gesture_end_event, now);-}--Optional<Web::MouseEvent> ContextState::interrupt_scroll_fling(Web::MouseEvent const& event, MonotonicTime now)-{- return m_scroll_fling_controller.interrupt(event, now);-}--Optional<Web::MouseEvent> ContextState::interrupt_reported_scroll_momentum()-{- if (!m_last_reported_scroll_momentum_step.has_value())- return {};-- // WebContent holds the gesture open while momentum events arrive. The end of the gesture releases it.- auto gesture_end = m_last_reported_scroll_momentum_step.release_value();- gesture_end.wheel_delta_x = 0;- gesture_end.wheel_delta_y = 0;- gesture_end.wheel_tick_120ths_x = 0;- gesture_end.wheel_tick_120ths_y = 0;- gesture_end.scroll_gesture_phase = Web::ScrollGesturePhase::Ended;- gesture_end.async_scroll_performed_default_action = false;- // The IDs of UI input events start at 1. Thus, ID 0 does not match a UI event.- gesture_end.id = 0;- m_reported_scroll_momentum_was_interrupted = true;- return gesture_end;-}--Optional<Web::MouseEvent> ContextState::end_momentum_scrolling(Web::AsyncScrollNodeStableID stable_node_id)-{- if (m_wheel_gesture_routing.latched_scroller() != stable_node_id)- return {};- if (has_active_scroll_fling())- return end_scroll_fling();- return interrupt_reported_scroll_momentum();-}--void ContextState::clear_per_test_input_state()-{- // A gesture held by fingers never ends by itself, so one a test left unended would take in the next test's steps.- m_wheel_gesture_routing.forget_gesture();- m_pointer_in_nested_contexts = {};- m_last_reported_scroll_momentum_step.clear();- m_reported_scroll_momentum_was_interrupted = false;-}--bool ContextState::absorbs_wheel_event_of_interrupted_momentum(Web::MouseEvent const& event)-{- if (!m_reported_scroll_momentum_was_interrupted)- return false;- if (first_is_one_of(event.scroll_gesture_phase, Web::ScrollGesturePhase::Momentum, Web::ScrollGesturePhase::Ended))- return true;- m_reported_scroll_momentum_was_interrupted = false;- return false;-}--Optional<Web::MouseEvent> ContextState::take_scroll_fling_step(MonotonicTime frame_time)-{- return m_scroll_fling_controller.take_step(frame_time);-}--Optional<Web::MouseEvent> ContextState::end_scroll_fling()-{- return m_scroll_fling_controller.end();-}--ContextState::ContextUpdateResult ContextState::scroll_for_fling_step(Web::MouseEvent const& event, WheelEventListenerGate const& listener_gate, MonotonicTime now)-{- if (!presents_to_client())- return ContextUpdateResult::declined(Web::InputRoutingDecision::ContextNotPresenting);- return scroll_for_wheel_event(event, false, listener_gate, Compositing::AsyncScrollOperationTracking::No, now);-}--void ContextState::end_scroll_fling_on_next_step()-{- m_scroll_fling_controller.end_on_next_step();-}--ContextState::ContextUpdateResult ContextState::scroll_for_wheel_event(Web::MouseEvent const& event, bool is_first_wheel_event_with_delta, WheelEventListenerGate const& listener_gate, Compositing::AsyncScrollOperationTracking operation_tracking, MonotonicTime now)-{- auto step = WheelStep::for_wheel_event(event, m_wheel_gesture_routing.gesture_id(), operation_tracking);- // The end of a gesture lets go of the scroller it stretched even if the context has stopped taking wheel events.- if (step.scroll_gesture_phase == Web::ScrollGesturePhase::Ended)- m_elastic_overscroll_controller.end_gesture(now);-- auto latch = resolve_wheel_scroll_latch(step.scroll_gesture_phase, step.gesture_id);- if (latch.nested_context_id.has_value())- return { .nested_context_wheel_step = NestedContextWheelStep { .context_id = *latch.nested_context_id } };- if (latch.scroll_node_index.has_value()) {- // A blocking listener added during the gesture holds its later steps back until the page lets one through.- if (listener_gate.reason_to_hold_latched_steps_back.has_value())- return ContextUpdateResult::declined(*listener_gate.reason_to_hold_latched_steps_back);- auto admission = listener_gate.page_let_the_gesture_through ? WheelStepAdmission::LetThroughByThePage : WheelStepAdmission::ByThisPage;- return scroll_for_wheel_step_in_this_context(step, latch.scroll_node_index, Compositing::NestedContextRegions::LeaveToMainThread, admission, {}, now);- }-- if (listener_gate.page_let_the_gesture_through)- return scroll_for_wheel_step_in_this_context(step, {}, Compositing::NestedContextRegions::Ignore, WheelStepAdmission::LetThroughByThePage, {}, now);-- // The first step of a gesture over the content of a nested context goes to that context. A gesture whose first step- // went elsewhere is not handed to a nested context that comes under the pointer later.- auto nested_context_regions = Compositing::NestedContextRegions::LeaveToMainThread;- if (is_first_wheel_event_with_delta && may_hand_first_wheel_steps_to_nested_contexts()) {- nested_context_regions = Compositing::NestedContextRegions::HandToNestedContext;- if (auto hit = nested_context_for_wheel_at(step.position); hit.has_value())- return { .nested_context_wheel_step = NestedContextWheelStep { .context_id = hit->child_context_id, .hit = hit } };- }- return scroll_for_wheel_step_in_this_context(step, {}, nested_context_regions, WheelStepAdmission::ByThisPage, {}, now);-}--ContextState::ContextUpdateResult ContextState::scroll_for_wheel_event_passed_on_by_nested_context(Web::MouseEvent const& event, Compositing::AsyncScrollOperationTracking operation_tracking, MonotonicTime now)-{- auto step = WheelStep::for_wheel_event(event, m_wheel_gesture_routing.gesture_id(), operation_tracking);- return scroll_for_wheel_step_in_this_context(step, {}, Compositing::NestedContextRegions::Ignore, WheelStepAdmission::PassedOnByNestedContext, {}, now);-}--ContextState::ContextUpdateResult ContextState::scroll_for_first_wheel_step_the_page_let_through(WheelStep const& step, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, MonotonicTime now)-{- return scroll_for_wheel_step_in_this_context(step, {}, Compositing::NestedContextRegions::Ignore, WheelStepAdmission::LetThroughByThePage, scroll_chain, now);-}--Optional<ContextState::ContextUpdateResult> ContextState::scroll_for_latched_wheel_step_the_page_let_through(WheelStep const& step, MonotonicTime now)-{- auto latch = resolve_wheel_scroll_latch(step.scroll_gesture_phase, step.gesture_id);- if (!latch.scroll_node_index.has_value())- return {};- return scroll_for_wheel_step_in_this_context(step, latch.scroll_node_index, Compositing::NestedContextRegions::Ignore, WheelStepAdmission::LetThroughByThePage, {}, now);-}--ContextState::ContextUpdateResult ContextState::scroll_for_overtaken_wheel_step(WheelStep const& step, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, MonotonicTime now)-{- if (!m_has_async_scrolling_state)- return ContextUpdateResult::declined(Web::InputRoutingDecision::NoAsyncScrollingState);- auto delta = step.delta_in_css_pixels.scaled(static_cast<float>(m_async_scroll_tree.device_pixels_per_css_pixel()));- if (delta.is_zero())- return ContextUpdateResult::declined(Web::InputRoutingDecision::StepOvertaken);- auto scroll_target = route_first_wheel_step(step.position, delta, step.wheel_delta_precision, Compositing::WheelStepDispatch::DispatchedAndNotCanceled, Compositing::NestedContextRegions::Ignore, scroll_chain);- if (!scroll_target.scroll_node_index.has_value())- return ContextUpdateResult::declined(Web::InputRoutingDecision::StepOvertaken);-- m_scroll_snap_controller.note_gesture_phase(step.scroll_gesture_phase);- auto node_scroll = scroll_node_by_wheel_delta(*scroll_target.scroll_node_index, delta, step.wheel_delta_precision, step.scroll_gesture_phase, step.operation_tracking, m_async_scrolling_viewport_rect, Compositing::ScrollChaining::ToScrollableAncestors, now);- auto const& outcome = node_scroll.outcome;- return {- .accepted = true,- .frame_to_present = outcome.viewport_rect_to_present.map([](auto const& rect) { return PendingFrame::repainting_changes(rect); }),- .should_request_rendering_update = outcome.viewport_rect_to_present.has_value(),- .routing_decision = Web::InputRoutingDecision::StepOvertaken,- .tracked_scroll_operation = tracked_scroll_operation(step.operation_tracking, outcome.operation_id),- };-}--Optional<ContextState::TrackedScrollOperation> ContextState::tracked_scroll_operation(Compositing::AsyncScrollOperationTracking operation_tracking, Optional<Compositing::AsyncScrollOperationID> operation_id) const-{- if (operation_tracking == Compositing::AsyncScrollOperationTracking::No || !operation_id.has_value())- return {};- return TrackedScrollOperation { .context_id = m_context_id, .operation_id = *operation_id };-}--ContextState::ContextUpdateResult ContextState::scroll_for_wheel_step_in_this_context(WheelStep const& step, Optional<Compositing::SpatialNodeIndex> latched_scroll_node_index, Compositing::NestedContextRegions nested_context_regions, WheelStepAdmission admission, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, MonotonicTime now)-{- auto delta = step.delta_in_css_pixels.scaled(static_cast<float>(m_async_scroll_tree.device_pixels_per_css_pixel()));- bool is_first_step_of_gesture = !latched_scroll_node_index.has_value();- auto found_nothing_to_scroll = [&](Web::InputRoutingDecision decision) {- bool there_is_nothing_to_scroll = first_is_one_of(decision, Web::InputRoutingDecision::NoScrollTarget, Web::InputRoutingDecision::NoScrollNode, Web::InputRoutingDecision::GestureEndWithNothingToSnap);- if (admission == WheelStepAdmission::LetThroughByThePage && there_is_nothing_to_scroll)- return ContextUpdateResult { .accepted = true, .routing_decision = decision };- return ContextUpdateResult::declined(decision);- };-- if (is_first_step_of_gesture) {- auto routing_admission = m_wheel_gesture_routing.admission();- // A page without scroll nodes still has a visual viewport to pan once it is zoomed in.- auto can_pan_zoomed_visual_viewport = routing_admission == Compositing::WheelRoutingAdmission::NoScrollNode- && m_scene.visual_viewport_scale().value_or(1.0f) > 1.0f;- // Only the listeners of the page that sees the step may hold it back.- bool is_admitted = routing_admission == Compositing::WheelRoutingAdmission::Accepted- || (admission != WheelStepAdmission::ByThisPage && first_is_one_of(routing_admission, Compositing::WheelRoutingAdmission::BlockingWheelEventListeners, Compositing::WheelRoutingAdmission::StaleWheelEventListeners));- if (!is_admitted && !can_pan_zoomed_visual_viewport) {- auto decision = Compositing::input_routing_decision_for_wheel_step_not_admitted_by(routing_admission);- if (routing_admission == Compositing::WheelRoutingAdmission::NoScrollNode)- return found_nothing_to_scroll(decision);- return ContextUpdateResult::declined(decision);- }- }-- m_scroll_snap_controller.note_gesture_phase(step.scroll_gesture_phase);-- if (step.scroll_gesture_phase == Web::ScrollGesturePhase::Ended && delta.is_zero()) {- auto operation_id = snap_at_gesture_end(now);- if (!operation_id.has_value())- return found_nothing_to_scroll(Web::InputRoutingDecision::GestureEndWithNothingToSnap);- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_changes(m_async_scrolling_viewport_rect),- .should_request_rendering_update = true,- .routing_decision = Web::InputRoutingDecision::SnappedAtGestureEnd,- .tracked_scroll_operation = tracked_scroll_operation(step.operation_tracking, operation_id),- };- }-- // Whether a gesture waits for the page is decided by its first step; the steps of a latched gesture are not held- // back by regions the cursor moves over later.- auto wheel_step_dispatch = admission == WheelStepAdmission::ByThisPage ? Compositing::WheelStepDispatch::NotYetDispatched : Compositing::WheelStepDispatch::DispatchedAndNotCanceled;- if (is_first_step_of_gesture && wheel_step_dispatch == Compositing::WheelStepDispatch::NotYetDispatched) {- auto initial_scroll_target = m_async_scroll_tree.hit_test_scroll_node_for_wheel(m_scene.visual_context_tree_for_compositing(), step.position, delta, {}, wheel_step_dispatch, nested_context_regions);- if (initial_scroll_target.is_blocked_by_a_region())- return ContextUpdateResult::declined(Compositing::input_routing_decision_for_first_wheel_step(initial_scroll_target.outcome));- }-- if (delta.is_zero()) {- return {- .accepted = true,- .frame_to_present = {},- .should_request_rendering_update = false,- .routing_decision = Web::InputRoutingDecision::StepWithoutDelta,- .routed_scroller = m_wheel_gesture_routing.latched_scroller(),- };- }-- // A gesture is latched before its first step pans the visual viewport, so that the scroller it belongs to is known- // for as long as the gesture only pans.- auto routing_decision = Web::InputRoutingDecision::ContinuedLatch;- if (is_first_step_of_gesture) {- auto latch_attempt = route_and_latch_wheel_gesture(step.position, delta.scaled(1.0f / m_scene.visual_viewport_magnification()), step.wheel_delta_precision, step.scroll_gesture_phase, step.gesture_id, wheel_step_dispatch, nested_context_regions, scroll_chain);- latched_scroll_node_index = latch_attempt.latched_scroll_node_index;- routing_decision = latch_attempt.decision;- }-- // A zoomed page still pans its visual viewport by a gesture that no scroller takes.- if (!latched_scroll_node_index.has_value()) {- if (pan_visual_viewport_by(delta).is_zero())- return found_nothing_to_scroll(routing_decision);- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_changes(m_async_scrolling_viewport_rect),- .should_request_rendering_update = true,- .routing_decision = Web::InputRoutingDecision::PannedVisualViewport,- };- }-- auto scroll_chaining = is_first_step_of_gesture ? Compositing::ScrollChaining::ToScrollableAncestors : Compositing::ScrollChaining::None;- auto outcome = perform_wheel_scroll_of_node(*latched_scroll_node_index, delta, step.wheel_delta_precision, step.scroll_gesture_phase, step.operation_tracking, m_async_scrolling_viewport_rect, scroll_chaining, VisualViewportPanning::BeforeScrolling, now);- return {- .accepted = true,- .frame_to_present = outcome.viewport_rect_to_present.map([](auto const& rect) { return PendingFrame::repainting_changes(rect); }),- .should_request_rendering_update = outcome.viewport_rect_to_present.has_value() && !outcome.only_elastic_overscroll_changed,- .routing_decision = routing_decision,- .routed_scroller = m_wheel_gesture_routing.latched_scroller(),- .tracked_scroll_operation = tracked_scroll_operation(step.operation_tracking, outcome.operation_id),- };-}--bool ContextState::may_hand_first_wheel_steps_to_nested_contexts() const-{- // A zoomed page pans its visual viewport before anything scrolls. This document's wheel event listeners never see- // the wheel events over a document nested in it, whatever state they are in.- return m_has_async_scrolling_state && m_scene.visual_viewport_scale().value_or(1.0f) == 1.0f;-}--bool ContextState::page_may_cancel_pinch_at(Gfx::FloatPoint position)-{- if (!m_has_async_scrolling_state || !m_wheel_gesture_routing.admits_async_pinch())- return true;- auto const& visual_context_tree = m_scene.visual_context_tree_for_compositing();- // NB: The main thread takes the wheel events of a nested document the compositor cannot reach.- return m_async_scroll_tree.blocks_wheel_event_at_position(visual_context_tree, position)- || m_async_scroll_tree.main_thread_wheel_event_region_contains(visual_context_tree, position);-}--Optional<Compositing::NestedContextHit> ContextState::nested_context_for_wheel_at(Gfx::FloatPoint position)-{- if (!m_has_async_scrolling_state)- return {};- return m_async_scroll_tree.nested_context_for_wheel_at(m_scene.visual_context_tree_for_compositing(), position);-}--void ContextState::latch_wheel_gesture_to_nested_context(Web::CompositorContextId nested_context_id, Optional<Web::AsyncScrollNodeStableID> scroller, Web::ScrollGesturePhase scroll_gesture_phase)-{- m_wheel_gesture_routing.latch_to_nested_context(nested_context_id, scroller, scroll_gesture_phase, m_wheel_gesture_routing.gesture_id());-}--Optional<Gfx::FloatPoint> ContextState::position_of_nested_context_position(Web::CompositorContextId nested_context_id, Gfx::FloatPoint position_in_nested_context, Gfx::IntSize nested_context_viewport_size)-{- if (!m_has_async_scrolling_state)- return {};- return m_async_scroll_tree.position_of_nested_context_position(nested_context_id, position_in_nested_context, nested_context_viewport_size.to_type<float>(), m_scene.visual_context_tree_for_compositing());-}--ContextState::WheelStep ContextState::WheelStep::for_wheel_event(Web::MouseEvent const& event, Optional<u64> gesture_id, Compositing::AsyncScrollOperationTracking operation_tracking)-{- Gfx::FloatPoint delta_in_css_pixels { static_cast<float>(event.wheel_delta_x), static_cast<float>(event.wheel_delta_y) };- if (event.modifiers & Web::UIEvents::KeyModifier::Mod_Shift)- delta_in_css_pixels = { delta_in_css_pixels.y(), delta_in_css_pixels.x() };- return {- .position = wheel_event_position(event),- .delta_in_css_pixels = delta_in_css_pixels,- .wheel_delta_precision = event.wheel_delta_precision,- .scroll_gesture_phase = event.scroll_gesture_phase,- .gesture_id = gesture_id,- .operation_tracking = operation_tracking,- };-}--ContextState::FirstWheelStepRoute ContextState::route_first_wheel_step_from_containing_context(Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels, Web::WheelDeltaPrecision wheel_delta_precision, Compositing::NestedContextRegions nested_context_regions, WheelStepAdmission admission, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain)-{- using Kind = FirstWheelStepRoute::Kind;- auto routing_admission = m_wheel_gesture_routing.admission();- if (!m_has_async_scrolling_state || routing_admission == Compositing::WheelRoutingAdmission::NoAsyncScrollingState)- return { Kind::Declined, Web::InputRoutingDecision::NoAsyncScrollingState };-- // A document's wheel event listeners never see the wheel events over a document nested in it.- auto const& visual_context_tree = m_scene.visual_context_tree_for_compositing();- if (nested_context_regions == Compositing::NestedContextRegions::HandToNestedContext) {- if (auto hit = m_async_scroll_tree.nested_context_for_wheel_at(visual_context_tree, position); hit.has_value())- return { .kind = Kind::NestedContext, .decision = Web::InputRoutingDecision::HandedToNestedContext, .nested_context_hit = hit };- }- bool listeners_of_this_page_see_the_step = admission == WheelStepAdmission::ByThisPage;- if (listeners_of_this_page_see_the_step && first_is_one_of(routing_admission, Compositing::WheelRoutingAdmission::BlockingWheelEventListeners, Compositing::WheelRoutingAdmission::StaleWheelEventListeners))- return { Kind::Declined, Compositing::input_routing_decision_for_wheel_step_not_admitted_by(routing_admission) };-- auto delta = delta_in_css_pixels.scaled(static_cast<float>(m_async_scroll_tree.device_pixels_per_css_pixel()));- auto wheel_step_dispatch = listeners_of_this_page_see_the_step ? Compositing::WheelStepDispatch::NotYetDispatched : Compositing::WheelStepDispatch::DispatchedAndNotCanceled;- auto scroll_target = route_first_wheel_step(position, delta, wheel_delta_precision, wheel_step_dispatch, nested_context_regions, scroll_chain);- auto scroller_of = [&](Optional<Compositing::SpatialNodeIndex> scroll_node_index) {- return scroll_node_index.map([&](auto index) { return m_async_scroll_tree.scroll_node_for_index(index)->stable_node_id; });- };- if (scroll_target.outcome == Compositing::WheelHitTestOutcome::FoundScrollTarget)- return { .kind = Kind::ScrollNode, .decision = Web::InputRoutingDecision::Latched, .scroll_node_index = scroll_target.scroll_node_index, .scroller = scroller_of(scroll_target.scroll_node_index) };- if (scroll_target.outcome != Compositing::WheelHitTestOutcome::NoScrollTarget)- return { Kind::Declined, Compositing::input_routing_decision_for_first_wheel_step(scroll_target.outcome) };-- // https://drafts.csswg.org/css-overscroll-1/#scroll-chaining-and-boundary-default-actions- // A nested context does not stretch at its edge. It passes the step on to the document around it unless a scroller- // keeps it, the viewport included.- bool viewport_keeps_the_scroll = m_async_scroll_tree.viewport_keeps_scrolls_along_main_axis_of(delta);- if (!scroll_target.scroll_node_index_keeping_the_scroll.has_value() && !viewport_keeps_the_scroll)- return { Kind::PassedOn, Web::InputRoutingDecision::NestedContextPassedStepOn };- auto scroll_node_index_keeping_the_scroll = scroll_target.scroll_node_index_keeping_the_scroll.has_value() ? scroll_target.scroll_node_index_keeping_the_scroll : m_async_scroll_tree.viewport_scroll_node_index();- return { .kind = Kind::Kept, .decision = Web::InputRoutingDecision::ScrollKeptByOverscrollBehavior, .scroll_node_index = scroll_node_index_keeping_the_scroll, .scroller = scroller_of(scroll_node_index_keeping_the_scroll) };-}--ContextState::ContextUpdateResult ContextState::take_first_wheel_step_from_containing_context(FirstWheelStepRoute const& route, WheelStep const& step, MonotonicTime now)-{- VERIFY(first_is_one_of(route.kind, FirstWheelStepRoute::Kind::ScrollNode, FirstWheelStepRoute::Kind::Kept));- if (route.kind == FirstWheelStepRoute::Kind::Kept) {- if (route.scroller.has_value())- m_wheel_gesture_routing.latch(*route.scroller, step.scroll_gesture_phase, step.gesture_id);- else- m_wheel_gesture_routing.latch_keeping_steps(step.scroll_gesture_phase, step.gesture_id);- return { .accepted = true, .routing_decision = route.decision, .routed_scroller = route.scroller };- }- m_wheel_gesture_routing.latch(*route.scroller, step.scroll_gesture_phase, step.gesture_id);- return take_wheel_step_from_containing_context(*route.scroll_node_index, route.decision, step, Compositing::ScrollChaining::ToScrollableAncestors, now);-}--ContextState::ContextUpdateResult ContextState::take_latched_wheel_step_from_containing_context(WheelStep const& step, WheelStepAdmission admission, MonotonicTime now)-{- if (!m_has_async_scrolling_state)- return ContextUpdateResult::declined(Web::InputRoutingDecision::NoAsyncScrollingState);-- auto latch = m_wheel_gesture_routing.resolve_latch(m_async_scroll_tree, m_scene.current_visual_context_tree(), step.scroll_gesture_phase, step.gesture_id);- if (latch.keeps_steps)- return { .accepted = true, .routing_decision = Web::InputRoutingDecision::ScrollKeptByOverscrollBehavior };- if (!latch.scroll_node_index.has_value())- return ContextUpdateResult::declined(Web::InputRoutingDecision::NestedContextUnavailable);-- if (step.scroll_gesture_phase == Web::ScrollGesturePhase::Ended && step.delta_in_css_pixels.is_zero()) {- m_scroll_snap_controller.note_gesture_phase(step.scroll_gesture_phase);- auto operation_id = snap_at_gesture_end(now);- if (!operation_id.has_value()) {- if (admission == WheelStepAdmission::LetThroughByThePage)- return { .accepted = true, .routing_decision = Web::InputRoutingDecision::GestureEndWithNothingToSnap };- return ContextUpdateResult::declined(Web::InputRoutingDecision::GestureEndWithNothingToSnap);- }- return {- .accepted = true,- .frame_to_present = PendingFrame::repainting_changes(m_async_scrolling_viewport_rect),- .should_request_rendering_update = true,- .routing_decision = Web::InputRoutingDecision::SnappedAtGestureEnd,- .routed_scroller = m_wheel_gesture_routing.latched_scroller(),- .tracked_scroll_operation = tracked_scroll_operation(step.operation_tracking, operation_id),- };- }- return take_wheel_step_from_containing_context(*latch.scroll_node_index, Web::InputRoutingDecision::ContinuedLatch, step, Compositing::ScrollChaining::None, now);-}--ContextState::ContextUpdateResult ContextState::take_wheel_step_from_containing_context(Compositing::SpatialNodeIndex scroll_node_index, Web::InputRoutingDecision decision, WheelStep const& step, Compositing::ScrollChaining scroll_chaining, MonotonicTime now)-{- m_scroll_snap_controller.note_gesture_phase(step.scroll_gesture_phase);- auto delta = step.delta_in_css_pixels.scaled(static_cast<float>(m_async_scroll_tree.device_pixels_per_css_pixel()));- auto outcome = perform_wheel_scroll_of_node(scroll_node_index, delta, step.wheel_delta_precision, step.scroll_gesture_phase, step.operation_tracking, m_async_scrolling_viewport_rect, scroll_chaining, VisualViewportPanning::No, now);- return {- .accepted = true,- .frame_to_present = outcome.viewport_rect_to_present.map([](auto const& rect) { return PendingFrame::repainting_changes(rect); }),- .should_request_rendering_update = outcome.viewport_rect_to_present.has_value() && !outcome.only_elastic_overscroll_changed,- .routing_decision = decision,- .routed_scroller = m_wheel_gesture_routing.latched_scroller(),- .tracked_scroll_operation = tracked_scroll_operation(step.operation_tracking, outcome.operation_id),- };-}--bool ContextState::wheel_step_can_stretch_elastically(Web::WheelDeltaPrecision wheel_delta_precision, Web::ScrollGesturePhase scroll_gesture_phase) const-{- return presents_to_client() && m_elastic_overscroll_controller.step_can_stretch(wheel_delta_precision, scroll_gesture_phase);-}--bool ContextState::pull_elastic_overscroll_by(Compositing::AsyncScrollNode const& node, Gfx::FloatPoint step_delta, Gfx::FloatPoint delta_the_scroller_did_not_scroll_by)-{- auto scroll_offset = m_async_scroll_tree.scroll_offset_for_node(node.scroll_node_index, m_scroll_state_snapshot);- if (!scroll_offset.has_value())- return false;- return m_elastic_overscroll_controller.pull_by(node, *scroll_offset, step_delta, delta_the_scroller_did_not_scroll_by, m_scene.visual_viewport_magnification());-}--void ContextState::set_scroll_capabilities(ScrollCapabilities const& capabilities)-{- m_presentation_synthesizes_scroll_momentum = capabilities.synthesizes_scroll_momentum;- m_elastic_overscroll_controller.set_enabled(capabilities.scrolls_elastically);- m_scrollbar_track_press_jumps = capabilities.scrollbar_track_press_jumps;- m_wheel_gesture_routing.set_touchpad_gesture_end(capabilities.touchpad_gesture_end);-}--Optional<Gfx::IntRect> ContextState::advance_elastic_overscroll_rebounds(MonotonicTime frame_time)-{- if (!m_elastic_overscroll_controller.advance_rebounds(frame_time))- return {};- return m_async_scrolling_viewport_rect;-}--Compositing::FirstWheelStepRouteForTesting ContextState::route_first_wheel_step_for_testing(Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels, Compositing::NestedContextRegions nested_context_regions)-{- auto document_id = m_async_scroll_tree.document_id();- if (!presents_to_client())- return { { Web::InputRoutingDecision::ContextNotPresenting }, document_id };- if (!m_scene.display_list() || !m_scene.visual_context_tree().has_value())- return { { Web::InputRoutingDecision::NoAsyncScrollingState }, document_id };- auto delta = delta_in_css_pixels.scaled(static_cast<float>(m_async_scroll_tree.device_pixels_per_css_pixel()) / m_scene.visual_viewport_magnification());- return { m_async_scroll_tree.route_first_wheel_step(m_wheel_gesture_routing.admission(), m_scene.visual_context_tree_for_compositing(), position, delta, nested_context_regions), document_id };-}--String ContextState::scroll_state_for_testing(Web::AsyncScrollNodeStableID scroller) const-{- auto const& display_list = m_scene.display_list();- auto scroll_state = Compositing::async_scrolling_state_to_json(display_list ? Compositing::async_scrolling_state_from_display_list(*display_list) : Compositing::AsyncScrollingState {});-- auto admission = m_wheel_gesture_routing.admission();- auto admission_name = admission == Compositing::WheelRoutingAdmission::Accepted- ? "accepted"sv- : Web::input_routing_decision_name(Compositing::input_routing_decision_for_wheel_step_not_admitted_by(admission));- scroll_state.set("wheelRoutingAdmission"sv, admission_name);-- if (auto scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(scroller); scroll_node_index.has_value()) {- if (auto offset = m_async_scroll_tree.css_scroll_offset_for_node(*scroll_node_index, m_scroll_state_snapshot); offset.has_value()) {- JsonObject offset_object;- offset_object.set("x"sv, offset->x().to_double());- offset_object.set("y"sv, offset->y().to_double());- scroll_state.set("scrollOffset"sv, move(offset_object));- }- }-- auto stretch = m_elastic_overscroll_controller.stretch_of(scroller).scaled(1.0f / static_cast<float>(m_async_scroll_tree.device_pixels_per_css_pixel()));- JsonObject stretch_object;- stretch_object.set("x"sv, stretch.x());- stretch_object.set("y"sv, stretch.y());- scroll_state.set("stretch"sv, move(stretch_object));- scroll_state.set("visualViewportScale"sv, m_scene.visual_viewport_scale().value_or(1.0f));- auto visual_viewport_offset = visual_viewport_scroll_offset(m_scene.visual_viewport_transform());- JsonObject visual_viewport_offset_object;- visual_viewport_offset_object.set("x"sv, visual_viewport_offset.x());- visual_viewport_offset_object.set("y"sv, visual_viewport_offset.y());- scroll_state.set("visualViewportOffset"sv, move(visual_viewport_offset_object));- return scroll_state.serialized();-}--Optional<Compositing::ScrollStateSnapshot> ContextState::scroll_state_snapshot_stretched_by_elastic_overscrolls() const-{- return m_elastic_overscroll_controller.stretched_scroll_state_snapshot(m_scroll_state_snapshot, m_async_scroll_tree);-}--Compositing::PendingAsyncScrollUpdates ContextState::take_pending_async_scroll_updates()-{- auto updates = m_async_scroll_update_outbox.take_updates(user_scroll_gesture_state());- updates.document_id = m_async_scroll_tree.document_id();- return updates;-}--bool ContextState::has_pending_async_scroll_updates() const-{- return m_async_scroll_update_outbox.has_updates(user_scroll_gesture_state());-}--void ContextState::publish_pending_async_scroll_updates()-{- if (!has_pending_async_scroll_updates())- return;- post_to_web_content<Messages::CompositorWebContentClient::AsyncScrollUpdates>(m_context_id, take_pending_async_scroll_updates());-}--void ContextState::viewport_size_updated(Gfx::IntSize viewport_size)-{- m_scene.forget_whether_animated_content_may_affect_viewport();- if (m_viewport_size != viewport_size)- m_keyboard_scroll_controller.forget_target();- m_viewport_size = viewport_size;-}--void ContextState::set_paused_debugger_overlay_is_shown(bool is_shown)-{- if (is_shown)- end_keyboard_scroll_gesture();- m_paused_debugger_overlay_is_shown = is_shown;-}--bool ContextState::set_visibility(Compositing::ContextVisibility visibility)-{- if (m_visibility == visibility)- return false;- m_visibility = visibility;- if (visibility == Compositing::ContextVisibility::Hidden) {- end_keyboard_scroll_gesture();- m_elastic_overscroll_controller.forget();- }- return true;-}--Vector<Web::CompositorScrollOffset> ContextState::scroll_offsets() const-{- auto scroll_nodes = m_async_scroll_tree.scroll_nodes();- Vector<Web::CompositorScrollOffset> scroll_offsets;- scroll_offsets.ensure_capacity(scroll_nodes.size());- for (auto const& node : scroll_nodes)- scroll_offsets.unchecked_append({ node.stable_node_id, m_async_scroll_tree.css_scroll_offset_for_node(node, m_scroll_state_snapshot) });- return scroll_offsets;-}--FrameInputs ContextState::frame_inputs_as_presented_now()-{- auto stretched_scroll_state_snapshot = scroll_state_snapshot_stretched_by_elastic_overscrolls();- auto presented_scroll_state_snapshot = stretched_scroll_state_snapshot.has_value() ? stretched_scroll_state_snapshot.release_value() : m_scroll_state_snapshot;- auto scrollbars = m_scrollbar_controller.scrollbars_of_frame(presented_scroll_state_snapshot);- return {- .visual_context_tree = m_scene.visual_context_tree_for_compositing(),- .presented_scroll_state_snapshot = move(presented_scroll_state_snapshot),- .scrollbars = move(scrollbars),- .viewport_scroll_node_index = m_async_scroll_tree.viewport_scroll_node_index(),- };-}--// Each frame shows the scrollbars as of when it is painted. An elastic overscroll moves the presented scroll offsets-// only, and shows the scrollbars of the stretched scroller as a scroll does.-void ContextState::update_scrollbar_visibility(MonotonicTime now)-{- auto stretched_scroll_state_snapshot = scroll_state_snapshot_stretched_by_elastic_overscrolls();- auto const& presented_scroll_state_snapshot = stretched_scroll_state_snapshot.has_value() ? *stretched_scroll_state_snapshot : m_scroll_state_snapshot;- m_scrollbar_controller.update_visibility(presented_scroll_state_snapshot, now);- report_scrollbar_visibility_changes();-- // A hovered scrollbar starts to grow here, which needs display ticks before anything else asks for a frame.- if (m_scrollbar_controller.fades_need_frame(now))- m_host.request_display_ticks(m_context_id);-- // The fade out runs on display ticks, which the wait before it does not need.- auto fade_out_time = m_scrollbar_controller.next_fade_out_time();- if (!fade_out_time.has_value()) {- m_host.cancel_timer(m_context_id, ContextTimer::ScrollbarFadeOut);- return;- }- auto delay = max(AK::Duration::zero(), *fade_out_time - now);- m_host.set_timer(m_context_id, ContextTimer::ScrollbarFadeOut, delay);-}--// NB: This goes on the connection the compositor forwards input on, so the main thread knows which scrollbars have-// faded out before it hit tests any later press. A nested context another process owns reports to that process,-// which gets its input through the UI instead.-void ContextState::report_scrollbar_visibility_changes()-{- auto changes = m_scrollbar_controller.take_visibility_changes();- if (!changes.is_empty())- post_to_web_content<Messages::CompositorWebContentClient::OverlayScrollbarVisibilitiesChanged>(changes);-}--Gfx::IntRect ContextState::advance_scrollbar_fades_and_return_damage_rect(MonotonicTime frame_time)-{- if (!m_scene.visual_context_tree().has_value())- return {};- auto stretched_scroll_state_snapshot = scroll_state_snapshot_stretched_by_elastic_overscrolls();- auto const& presented_scroll_state_snapshot = stretched_scroll_state_snapshot.has_value() ? *stretched_scroll_state_snapshot : m_scroll_state_snapshot;- auto damage_rect = m_scrollbar_controller.advance_fades(m_scene.visual_context_tree_for_compositing(), presented_scroll_state_snapshot, frame_time);- report_scrollbar_visibility_changes();- return damage_rect;-}--Optional<FrameInputs> ContextState::frame_inputs(MonotonicTime now)-{- update_scrollbar_visibility(now);- if (!m_scene.display_list())- return {};- return frame_inputs_as_presented_now();-}--ContextState::ScreenshotInputs ContextState::frame_inputs_for_screenshot(MonotonicTime now)-{- VERIFY(m_scene.display_list());-- // Screenshot requests can arrive between display ticks, so sample animations and scrollbar visibility at capture- // time.- auto capture_time = now;- advance_visual_animations(capture_time);- update_scrollbar_visibility(now);- auto scrollbar_fade_damage_rect = advance_scrollbar_fades_and_return_damage_rect(capture_time);-- return { .frame_inputs = frame_inputs_as_presented_now(), .scrollbar_fade_damage_rect = scrollbar_fade_damage_rect };-}--Optional<ContextState::VisualViewportScrollDelta> ContextState::apply_visual_viewport_scroll_delta(Gfx::FloatPoint delta)-{- if (delta.is_zero())- return {};- if (!m_scene.visual_context_tree().has_value())- return {};-- auto document_id = m_async_scroll_tree.document_id();- if (!document_id.has_value())- return {};-- auto transform = m_scene.visual_viewport_transform();- auto scale = transform.matrix[0, 0];- if (scale <= 1.0f)- return {};-- auto min_x = -static_cast<float>(m_async_scrolling_viewport_rect.width()) * (scale - 1.0f);- auto min_y = -static_cast<float>(m_async_scrolling_viewport_rect.height()) * (scale - 1.0f);-- auto old_x = transform.matrix[0, 3];- auto old_y = transform.matrix[1, 3];- auto new_x = clamp(old_x - delta.x(), min_x, 0.0f);- auto new_y = clamp(old_y - delta.y(), min_y, 0.0f);- Gfx::FloatPoint consumed_delta { old_x - new_x, old_y - new_y };- if (consumed_delta.is_zero())- return {};-- transform.matrix[0, 3] = new_x;- transform.matrix[1, 3] = new_y;- m_scene.set_async_visual_viewport_transform(transform);- m_visual_viewport_document_id = document_id;- note_user_input_scrolled({ .node_id = document_id.value(), .kind = Web::AsyncScrollNodeKind::VisualViewport });- rebuild_wheel_hit_test_targets();-- return VisualViewportScrollDelta {- .scroll_offset = {- .stable_node_id = { .node_id = document_id.value(), .kind = Web::AsyncScrollNodeKind::VisualViewport },- .compositor_scroll_offset = visual_viewport_scroll_offset(transform),- .unadopted_scroll_delta = consumed_delta.scaled(1.0f / scale),- .last_relative_scroll_delta = {},- .visual_viewport_scale = scale,- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- },- .consumed_delta = consumed_delta,- };-}--Gfx::FloatPoint ContextState::pan_visual_viewport_by(Gfx::FloatPoint delta_in_screen_pixels)-{- auto visual_viewport_scroll_delta = apply_visual_viewport_scroll_delta(delta_in_screen_pixels);- if (!visual_viewport_scroll_delta.has_value())- return {};- store_pending_async_scroll_offsets({ &visual_viewport_scroll_delta->scroll_offset, 1 });- return visual_viewport_scroll_delta->consumed_delta;-}--HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> ContextState::scroll_offsets_by_stable_id() const-{- HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> scroll_offsets;- if (!m_has_async_scrolling_state)- return scroll_offsets;- for (auto const& node : m_async_scroll_tree.scroll_nodes())- scroll_offsets.set(node.stable_node_id, m_async_scroll_tree.scroll_offset_for_node(node, m_scroll_state_snapshot));- return scroll_offsets;-}--// The main thread asks for every scroll of its own, so the offsets a snapshot of its scroll state has for the boxes-// this context already scrolls are what it last heard of them. Only a box new to this context takes its offset from-// the snapshot.-Optional<Gfx::FloatPoint> ContextState::keep_scroll_offsets_of_known_nodes(HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> const& scroll_offsets_of_known_nodes)-{- Optional<Gfx::FloatPoint> viewport_scroll_offset;- Vector<Compositing::AsyncScrollOffset> clamped_scroll_offsets;- bool kept_any_scroll_offset = false;- m_scroll_offsets_differ_from_last_frame = false;- m_scroll_nodes_seeded_by_last_frame.clear();- for (auto const& node : m_async_scroll_tree.scroll_nodes()) {- auto known_scroll_offset = scroll_offsets_of_known_nodes.get(node.stable_node_id);- if (!known_scroll_offset.has_value()) {- m_scroll_nodes_seeded_by_last_frame.set(node.stable_node_id);- continue;- }- if (m_async_scroll_tree.scroll_offset_for_node(node, m_scroll_state_snapshot) != known_scroll_offset.value())- m_scroll_offsets_differ_from_last_frame = true;- auto kept_scroll_offset = m_async_scroll_tree.set_scroll_offset_leaving_sticky_offsets_unresolved(node, known_scroll_offset.value(), m_scroll_state_snapshot);- kept_any_scroll_offset = true;- if (node.is_viewport)- viewport_scroll_offset = kept_scroll_offset;- // A box whose scroll range shrank past its offset is told where it ended up.- if (kept_scroll_offset != known_scroll_offset.value()) {- clamped_scroll_offsets.append({- .stable_node_id = node.stable_node_id,- .compositor_scroll_offset = kept_scroll_offset,- .unadopted_scroll_delta = kept_scroll_offset - known_scroll_offset.value(),- .last_relative_scroll_delta = {},- .visual_viewport_scale = {},- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- });- }- }- // Resolving sticky offsets walks the whole visual context tree, so it runs once, after every offset is kept.- if (kept_any_scroll_offset)- Compositing::resolve_sticky_offsets(m_scene.current_visual_context_tree(), m_scroll_state_snapshot);- if (!clamped_scroll_offsets.is_empty())- store_pending_async_scroll_offsets(clamped_scroll_offsets);- return viewport_scroll_offset;-}--void ContextState::store_pending_async_scroll_offsets(- ReadonlySpan<Compositing::AsyncScrollOffset> scroll_offsets,- Optional<Compositing::AsyncScrollOperationID> operation_id)-{- m_scene.forget_whether_animated_content_may_affect_viewport();- Vector<Compositing::AsyncScrollOffset> stamped_scroll_offsets;- stamped_scroll_offsets.ensure_capacity(scroll_offsets.size());- for (auto scroll_offset : scroll_offsets) {- scroll_offset.applied_scroll_request_id = m_applied_scroll_request_ids.get(scroll_offset.stable_node_id).value_or(0);- scroll_offset.user_input_scroll_count = m_user_input_scroll_counts.get(scroll_offset.stable_node_id).value_or(0);- scroll_offset.context_user_input_scroll_count = m_context_user_input_scroll_count;- stamped_scroll_offsets.unchecked_append(scroll_offset);- }- m_async_scroll_update_outbox.record_scroll_offsets(stamped_scroll_offsets);- m_scroll_offsets_differ_from_last_frame = true;- if (operation_id.has_value())- m_async_scroll_update_outbox.complete_operation(*operation_id);-}--WheelGestureRouting::ResolvedLatch ContextState::resolve_wheel_scroll_latch(Web::ScrollGesturePhase scroll_gesture_phase, Optional<u64> gesture_id)-{- // Only a hit test takes a latch, and it needs the tree of an installed display list.- if (!m_wheel_gesture_routing.has_latch())- return {};- return m_wheel_gesture_routing.resolve_latch(m_async_scroll_tree, m_scene.current_visual_context_tree(), scroll_gesture_phase, gesture_id);-}--Compositing::WheelHitTestResult ContextState::route_first_wheel_step(Gfx::FloatPoint position, Gfx::FloatPoint delta, Web::WheelDeltaPrecision wheel_delta_precision, Compositing::WheelStepDispatch wheel_step_dispatch, Compositing::NestedContextRegions nested_context_regions, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain)-{- auto in_flight_destination_for = [this, wheel_delta_precision](Web::AsyncScrollNodeStableID stable_node_id) -> Optional<Gfx::FloatPoint> {- if (wheel_delta_precision == Web::WheelDeltaPrecision::Discrete)- return in_flight_wheel_destination(stable_node_id);- return {};- };- for (auto stable_node_id : scroll_chain) {- if (auto scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(stable_node_id); scroll_node_index.has_value())- return m_async_scroll_tree.hit_test_result_for_scroll_node(*scroll_node_index, delta, move(in_flight_destination_for));- }- return m_async_scroll_tree.hit_test_scroll_node_for_wheel(m_scene.visual_context_tree_for_compositing(), position, delta, move(in_flight_destination_for), wheel_step_dispatch, nested_context_regions);-}--ContextState::WheelGestureLatchAttempt ContextState::route_and_latch_wheel_gesture(Gfx::FloatPoint position, Gfx::FloatPoint delta, Web::WheelDeltaPrecision wheel_delta_precision, Web::ScrollGesturePhase scroll_gesture_phase, Optional<u64> gesture_id, Compositing::WheelStepDispatch wheel_step_dispatch, Compositing::NestedContextRegions nested_context_regions, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain)-{- auto scroll_target = route_first_wheel_step(position, delta, wheel_delta_precision, wheel_step_dispatch, nested_context_regions, scroll_chain);- if (scroll_target.is_blocked_by_a_region())- return { Compositing::input_routing_decision_for_first_wheel_step(scroll_target.outcome) };-- auto scroll_node_index_to_latch = scroll_target.scroll_node_index;- auto decision = Web::InputRoutingDecision::Latched;- // Fingers that start to pull where every scroller under them is already at its edge stretch the outermost one. A- // context nested in another one turns the gesture away instead, which passes it on to the document around it.- bool fingers_start_a_gesture_at_an_edge = !scroll_node_index_to_latch.has_value() && scroll_target.innermost_scroll_node_index.has_value() && !delta.is_zero()- && scroll_gesture_phase == Web::ScrollGesturePhase::Ongoing && wheel_step_can_stretch_elastically(wheel_delta_precision, scroll_gesture_phase);- if (fingers_start_a_gesture_at_an_edge) {- scroll_node_index_to_latch = m_async_scroll_tree.outermost_scroll_node_wheel_scrollable_along_main_axis_of(*scroll_target.innermost_scroll_node_index, delta);- decision = Web::InputRoutingDecision::LatchedOutermostScrollerToStretch;- }-- if (!scroll_node_index_to_latch.has_value())- return { Compositing::input_routing_decision_for_first_wheel_step(scroll_target.outcome) };- auto const* node = m_async_scroll_tree.scroll_node_for_index(*scroll_node_index_to_latch);- VERIFY(node);- m_wheel_gesture_routing.latch(node->stable_node_id, scroll_gesture_phase, gesture_id);- return { decision, scroll_node_index_to_latch };-}--void ContextState::report_started_user_scroll(Compositing::AsyncScrollOperationID operation_id, Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint step_start_offset, Gfx::FloatPoint destination_offset, Compositing::ScrollAnimationKind animation_kind, bool is_absolute_scroll)-{- auto scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(stable_node_id);- VERIFY(scroll_node_index.has_value());- auto current_offset = m_async_scroll_tree.css_scroll_offset_for_node(*scroll_node_index, m_scroll_state_snapshot);- VERIFY(current_offset.has_value());- auto destination = m_async_scroll_tree.css_pixels_from_device_offset(destination_offset);- note_user_input_scrolled(stable_node_id);- m_async_scroll_update_outbox.record_started_user_scroll({- .stable_node_id = stable_node_id,- .operation_id = operation_id,- .initial_scroll_offset = *current_offset,- .unsnapped_scroll_destination = destination,- .relative_scroll_delta = destination - m_async_scroll_tree.css_pixels_from_device_offset(step_start_offset),- .selection = { .position = destination },- .settles_gesture = false,- .is_absolute_scroll = is_absolute_scroll,- .animation_kind = animation_kind,- });-}--void ContextState::cancel_smooth_scroll_taken_over_by_user_input(Compositing::SpatialNodeIndex scroll_node_index)-{- for (auto const& smooth_scroll_animation : m_smooth_scroll_animations) {- auto animated_scroll_node_index = m_async_scroll_tree.scroll_node_index_for_stable_id(smooth_scroll_animation.stable_node_id);- if (animated_scroll_node_index != scroll_node_index)- continue;- m_async_scroll_update_outbox.note_operation_taken_over_by_user_input(smooth_scroll_animation.operation_id);- cancel_smooth_scroll(smooth_scroll_animation.stable_node_id);- return;- }-}--Optional<Web::AsyncScrollNodeStableID> ContextState::box_of_captured_scrollbar() const-{- auto scrollbar_index = m_scrollbar_controller.captured_scrollbar_index();- if (!scrollbar_index.has_value())- return {};- return m_scrollbar_controller.scrollbars()[scrollbar_index.value()].scroller_stable_node_id;-}--void ContextState::note_user_scroll_gesture_end_if_drag_ended(Optional<Web::AsyncScrollNodeStableID> box_of_dragged_scrollbar)-{- if (box_of_dragged_scrollbar.has_value() && !m_scrollbar_controller.has_captured_scrollbar())- m_async_scroll_update_outbox.note_user_scroll_gesture_ended({ &box_of_dragged_scrollbar.value(), 1 });-}--void ContextState::end_user_scroll_gesture_of_held_keys()-{- m_async_scroll_update_outbox.note_user_scroll_gesture_ended(m_boxes_scrolled_by_held_keys);- m_boxes_scrolled_by_held_keys.clear();-}--AsyncScrollUpdateOutbox::UserScrollGestureState ContextState::user_scroll_gesture_state() const-{- AsyncScrollUpdateOutbox::UserScrollGestureState state;- if (auto box = box_of_captured_scrollbar(); box.has_value())- state.boxes_in_user_scroll_gesture.append(box.value());- for (auto box : m_boxes_scrolled_by_held_keys) {- if (!state.boxes_in_user_scroll_gesture.contains_slow(box))- state.boxes_in_user_scroll_gesture.append(box);- }- for (auto box : m_scroll_snap_controller.boxes_with_gesture_awaiting_input()) {- if (!state.boxes_in_user_scroll_gesture.contains_slow(box))- state.boxes_in_user_scroll_gesture.append(box);- }- if (auto box = m_wheel_gesture_routing.scroller_held_by_fingers(); box.has_value() && !state.boxes_in_user_scroll_gesture.contains_slow(box.value()))- state.boxes_in_user_scroll_gesture.append(box.value());- state.wheel_latched_scroller = m_wheel_gesture_routing.latched_scroller();- return state;-}--void ContextState::schedule_end_of_scroll_step_gestures(MonotonicTime now)-{- auto deadline = m_scroll_snap_controller.earliest_gesture_input_deadline();- if (!deadline.has_value()) {- m_host.cancel_timer(m_context_id, ContextTimer::ScrollStepGestureInput);- return;- }- m_host.set_timer(m_context_id, ContextTimer::ScrollStepGestureInput, max(*deadline - now, AK::Duration::zero()));-}--void ContextState::end_scroll_step_gestures_whose_input_ran_out(MonotonicTime now)-{- if (auto ended_boxes = m_scroll_snap_controller.end_gestures_whose_input_ran_out(now); !ended_boxes.is_empty()) {- m_async_scroll_update_outbox.note_user_scroll_gesture_ended(ended_boxes);- request_rendering_update();- }- schedule_end_of_scroll_step_gestures(now);-}--Optional<PendingFrame> ContextState::start_scrollbar_press_scroll(Compositing::AsyncScrollNode const& node, Gfx::FloatPoint old_scroll_offset, Gfx::FloatPoint destination, bool is_absolute_scroll, MonotonicTime now)-{- auto operation_id = m_async_scroll_update_outbox.allocate_operation_id();- m_smooth_scroll_animations.append({- .stable_node_id = node.stable_node_id,- .operation_id = operation_id,- .animation = Compositing::SmoothScrollAnimation { old_scroll_offset, destination, m_async_scroll_tree.device_pixels_per_css_pixel() },- .started_at = now,- .is_user_scroll = true,- .heads_to_an_extent = false,- });- report_started_user_scroll(operation_id, node.stable_node_id, old_scroll_offset, destination, Compositing::ScrollAnimationKind::SmoothScroll, is_absolute_scroll);- m_scrollbar_press_scroll_operation = operation_id;- return PendingFrame::repainting_changes(m_async_scrolling_viewport_rect);-}--// https://source.chromium.org/chromium/chromium/src/+/main:cc/input/scroll_utils.cc-// INTEROP: A page is most of the scrollport, keeping as much of the last page in view as Chromium does.-static float scrollbar_page_step(float scrollport_length, float device_pixels_per_css_pixel)-{- static constexpr float min_fraction_to_step_when_paging = 0.875f;- static constexpr float max_overlap_between_pages = 40;- return max(1.0f, max(scrollport_length * min_fraction_to_step_when_paging, scrollport_length - max_overlap_between_pages * device_pixels_per_css_pixel));-}--// Pages the scroller of the captured scrollbar once toward the pointer, from where a page scroll in flight goes, unless-// the thumb has reached the pointer there.-Optional<PendingFrame> ContextState::page_captured_scrollbar(MonotonicTime now)-{- auto scrollbar_index = m_scrollbar_controller.captured_scrollbar_index();- if (!scrollbar_index.has_value() || !m_scrollbar_paging.has_value() || m_scrollbar_paging->direction == 0)- return {};- auto const& scrollbar = m_scrollbar_controller.scrollbars()[*scrollbar_index];- auto const* node = m_async_scroll_tree.scroll_node_for_index(scrollbar.scroll_node_index);- auto old_scroll_offset = m_async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, m_scroll_state_snapshot);- if (!node || !old_scroll_offset.has_value())- return {};-- auto* running_animation = running_scrollbar_press_scroll();- auto step_start = running_animation ? running_animation->animation.destination_offset() : *old_scroll_offset;- if (m_scrollbar_controller.paging_direction(*scrollbar_index, m_scrollbar_paging->primary_position, step_start) != m_scrollbar_paging->direction)- return {};-- auto orientation = scrollbar.vertical ? Gfx::Orientation::Vertical : Gfx::Orientation::Horizontal;- auto step = scrollbar_page_step(static_cast<float>(node->scrollport_rect.primary_size_for_orientation(orientation)), m_async_scroll_tree.device_pixels_per_css_pixel());- auto destination = step_start;- destination.set_primary_offset_for_orientation(orientation, step_start.primary_offset_for_orientation(orientation) + static_cast<float>(m_scrollbar_paging->direction) * step);- destination = m_async_scroll_tree.clamped_scroll_offset_for_node(scrollbar.scroll_node_index, destination);- if (destination == step_start)- return {};-- if (running_animation) {- retarget_user_scroll(*running_animation, destination, now);- report_started_user_scroll(running_animation->operation_id, node->stable_node_id, step_start, destination, Compositing::ScrollAnimationKind::SmoothScroll, false);- return PendingFrame::repainting_changes(m_async_scrolling_viewport_rect);- }- cancel_smooth_scroll_taken_over_by_user_input(scrollbar.scroll_node_index);- return start_scrollbar_press_scroll(*node, *old_scroll_offset, destination, false, now);-}--ContextState::ActiveSmoothScrollAnimation* ContextState::running_scrollbar_press_scroll()-{- if (!m_scrollbar_press_scroll_operation.has_value())- return nullptr;- auto animation = m_smooth_scroll_animations.first_matching([&](auto const& animation) { return animation.operation_id == *m_scrollbar_press_scroll_operation; });- if (!animation.has_value()) {- m_scrollbar_press_scroll_operation.clear();- return nullptr;- }- return &animation.value();-}--void ContextState::stop_scrollbar_paging()-{- m_scrollbar_paging.clear();- m_host.cancel_timer(m_context_id, ContextTimer::ScrollbarPaging);- m_scrollbar_paging_timer_is_armed = false;-}--Optional<PendingFrame> ContextState::apply_scrollbar_drag(ScrollbarController::Drag const& drag, MonotonicTime now)-{- auto dragged_to = m_scrollbar_controller.scroll_offset_for_drag(m_async_scroll_tree, m_scroll_state_snapshot, drag);- if (!dragged_to.has_value())- return {};-- // A scrollbar scrolls its own scroller to where the thumb was dragged, and never hands any of that to an ancestor.- auto scroll_node_index = dragged_to->scroll_node_index;- auto const* node = m_async_scroll_tree.scroll_node_for_index(scroll_node_index);- auto old_scroll_offset = m_async_scroll_tree.scroll_offset_for_node(scroll_node_index, m_scroll_state_snapshot);- if (!node || !old_scroll_offset.has_value())- return {};- auto destination = m_async_scroll_tree.clamped_scroll_offset_for_node(scroll_node_index, dragged_to->scroll_offset);-- // A press beside the thumb scrolls there smoothly, as a page step does. Dragging on before that scroll has ended- // moves where it goes.- if (auto* running_animation = running_scrollbar_press_scroll()) {- if (running_animation->animation.destination_offset() == destination)- return {};- retarget_user_scroll(*running_animation, destination, now);- report_started_user_scroll(running_animation->operation_id, node->stable_node_id, *old_scroll_offset, destination, Compositing::ScrollAnimationKind::SmoothScroll, true);- return PendingFrame::repainting_changes(m_async_scrolling_viewport_rect);- }-- if (destination == *old_scroll_offset)- return {};-- cancel_smooth_scroll_taken_over_by_user_input(scroll_node_index);-- if (drag.is_press_beside_thumb)- return start_scrollbar_press_scroll(*node, *old_scroll_offset, destination, true, now);-- auto new_scroll_offset = m_async_scroll_tree.set_scroll_offset(scroll_node_index, dragged_to->scroll_offset, m_scene.current_visual_context_tree(), m_scroll_state_snapshot);- note_user_input_scrolled(node->stable_node_id);- VERIFY(new_scroll_offset.has_value());- rebuild_wheel_hit_test_targets();-- Vector<Compositing::AsyncScrollOffset> scroll_offsets;- scroll_offsets.append({- .stable_node_id = node->stable_node_id,- .compositor_scroll_offset = *new_scroll_offset,- .unadopted_scroll_delta = *new_scroll_offset - *old_scroll_offset,- .last_relative_scroll_delta = {},- .visual_viewport_scale = {},- .applied_scroll_request_id = 0,- .user_input_scroll_count = 0,- .context_user_input_scroll_count = 0,- });- store_pending_async_scroll_offsets(scroll_offsets);-- if (!node->is_viewport)- return PendingFrame::repainting_changes(m_async_scrolling_viewport_rect);- m_async_scrolling_viewport_rect.set_location(new_scroll_offset->to_type<int>());- return PendingFrame::repainting_everything(m_async_scrolling_viewport_rect);-}--void ContextState::rebuild_wheel_hit_test_targets()-{- VERIFY(m_scene.display_list());- m_async_scroll_tree.rebuild_wheel_hit_test_targets(- m_scene.display_list(),- &m_scene.visual_context_tree_for_compositing(),- m_scroll_state_snapshot);-}--bool ContextState::visual_animations_need_frame(MonotonicTime now)-{- return m_scene.visual_animations_need_frame(m_scroll_state_snapshot, m_viewport_size, now);-}--bool ContextState::advance_visual_animations(MonotonicTime now)-{- auto animations_are_active = m_scene.advance_visual_animations(now);- // The main thread hovers what is under the pointer at rest again as a transform animation moves content under it,- // with the animation sampled at the frame's time, and once more as the content moves away. So does the clock lane- // of the frame, at its next tick, while the main thread runs a task.- auto animated_content_is_under_pointer = animations_are_active && m_pointer_position.has_value()- && m_scene.visual_context_tree_for_compositing().running_transform_animation_covers_point(now.nanoseconds(), *m_pointer_position, m_scroll_state_snapshot);- if (animated_content_is_under_pointer || m_animated_content_was_under_pointer) {- post_to_web_content<Messages::CompositorWebContentClient::AnimatedContentMovedUnderPointer>(m_context_id, now.nanoseconds());- post_to_render_clock_of_web_content<Messages::RenderClockClient::PointerRestsOnMovingContent>(m_context_id);- }- m_animated_content_was_under_pointer = animated_content_is_under_pointer;- return animations_are_active;-}--}diff --git a/Services/Compositor/ContextState.h b/Services/Compositor/ContextState.hdeleted file mode 100644index 6bab8371a88..00000000000--- a/Services/Compositor/ContextState.h+++ /dev/null@@ -1,534 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <AK/Noncopyable.h>-#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>-#include <AK/RefPtr.h>-#include <AK/Span.h>-#include <AK/StdLibExtras.h>-#include <AK/Try.h>-#include <AK/Vector.h>-#include <Compositor/AsyncScrollUpdateOutbox.h>-#include <Compositor/CompositorCoreHost.h>-#include <Compositor/ContextScene.h>-#include <Compositor/ElasticOverscrollController.h>-#include <Compositor/Forward.h>-#include <Compositor/FrameInputs.h>-#include <Compositor/KeyboardScrollController.h>-#include <Compositor/ScrollFlingController.h>-#include <Compositor/ScrollSnapController.h>-#include <Compositor/ScrollbarController.h>-#include <Compositor/WheelGestureRouting.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/AsyncScrollTree.h>-#include <LibCompositing/Scrolling/AsyncScrollingState.h>-#include <LibCompositing/Scrolling/ScrollState.h>-#include <LibCompositing/Scrolling/SmoothScrollAnimation.h>-#include <LibCompositing/Types.h>-#include <LibGfx/Point.h>-#include <LibGfx/Rect.h>-#include <LibGfx/Size.h>-#include <LibWebCommon/Page/InputEvent.h>-#include <LibWebCommon/Page/InputTrace.h>-#include <LibWebCommon/UIEvents/KeyCode.h>--namespace Gfx {--class SkiaBackendContext;--}--namespace Compositor {--class ContextState {- AK_MAKE_NONCOPYABLE(ContextState);- AK_MAKE_NONMOVABLE(ContextState);--public:- AK_ALLOC_WITH_KMALLOC;-- struct AsyncScrollResult {- Compositing::AsyncScrollEnqueueResult enqueue_result;- Optional<PendingFrame> frame_to_present {};-- static AsyncScrollResult declined(Web::InputRoutingDecision decision) { return { .enqueue_result = { .routing_decision = decision } }; }- };-- // A wheel step that goes to a context nested in this one: the first step of a gesture over the content of the- // nested context, or a step of a gesture latched to a context nested here.- struct NestedContextWheelStep {- Web::CompositorContextId context_id;- // Where the first step lands in the content of the nested context.- Optional<Compositing::NestedContextHit> hit {};- };-- // An operation that a wheel step asked to follow, whose end the scroll updates of the context report.- struct TrackedScrollOperation {- Web::CompositorContextId context_id;- Compositing::AsyncScrollOperationID operation_id;- };-- struct ContextUpdateResult {- bool accepted { false };- Optional<PendingFrame> frame_to_present {};- bool should_request_rendering_update { false };- // Whether a key event found nothing to scroll by the compositor's scroll range, which may lag behind the page's.- bool key_found_nothing_to_scroll { false };- Optional<Web::ScrollbarDraggedByCompositor> scrollbar_dragged_by_compositor {};- // Why a wheel or mouse event was taken or turned away, and the scroller it was routed to.- Optional<Web::InputRoutingDecision> routing_decision {};- Optional<Web::AsyncScrollNodeStableID> routed_scroller {};- // How the first step of a wheel gesture went by a nested context, ahead of `routing_decision`.- Optional<Web::InputRoutingDecision> nested_context_hand_off {};- // Set instead of everything else for a wheel step that a nested context is to take.- Optional<NestedContextWheelStep> nested_context_wheel_step {};- // Set, with at most the frame of the scrollbar the pointer left here, for a mouse event that the nested context- // under the pointer is to take.- Optional<Compositing::NestedContextHit> nested_context_mouse_hit {};- Optional<TrackedScrollOperation> tracked_scroll_operation {};-- static ContextUpdateResult declined(Web::InputRoutingDecision decision) { return { .routing_decision = decision }; }- };-- // A step of a wheel gesture at a position in this context's device pixels. The delta is in CSS pixels, with the axes- // already swapped for Shift.- struct WheelStep {- Gfx::FloatPoint position;- Gfx::FloatPoint delta_in_css_pixels;- Web::WheelDeltaPrecision wheel_delta_precision { Web::WheelDeltaPrecision::Discrete };- Web::ScrollGesturePhase scroll_gesture_phase { Web::ScrollGesturePhase::None };- // The gesture the step is in, which the latch a context takes for the step is for. A context nested in another- // one takes it for the gesture of the containing context.- Optional<u64> gesture_id {};- Compositing::AsyncScrollOperationTracking operation_tracking { Compositing::AsyncScrollOperationTracking::No };-- static WheelStep for_wheel_event(Web::MouseEvent const&, Optional<u64> gesture_id, Compositing::AsyncScrollOperationTracking);- };-- // What the wheel event listeners of the page that dispatches a gesture's wheel events let through without waiting- // for the page. That page may be the page of a context nested in this one.- struct WheelEventListenerGate {- // The page dispatched a step of the gesture and did not cancel it, and the listeners are as they were then.- bool page_let_the_gesture_through { false };- // Why the listeners hold the steps of a latched gesture back for the page, if they do.- Optional<Web::InputRoutingDecision> reason_to_hold_latched_steps_back {};- };-- // What may hold a step back for the page before this context scrolls by it.- enum class WheelStepAdmission : u8 {- // The wheel event listeners of this context's page see the step, which waits for the page if they may cancel it.- ByThisPage,- // A context nested in this one passed the step on. Only the page of that context sees the step.- PassedOnByNestedContext,- // The page let the gesture through. Nothing holds the step back, and a step that finds nothing to scroll is done- // with all the same, so that the page is not asked about the gesture again.- LetThroughByThePage,- };-- // Where the first step of a gesture that the containing context hands in goes in this context. A nested context- // passes a step on to the document around it unless one of its scrollers takes or keeps it.- struct FirstWheelStepRoute {- enum class Kind : u8 {- Declined,- ScrollNode,- NestedContext,- Kept,- PassedOn,- };- Kind kind;- Web::InputRoutingDecision decision;- Optional<Compositing::SpatialNodeIndex> scroll_node_index {};- Optional<Web::AsyncScrollNodeStableID> scroller {};- Optional<Compositing::NestedContextHit> nested_context_hit {};- };-- ContextState(Web::CompositorContextId, Optional<u64> page_id, WebContentClientId, CompositorCoreHost&);-- bool is_owned_by(WebContentClientId) const;- WebContentClientId web_content_client_id() const { return m_web_content_client_id; }- void request_rendering_update();- void dispatch_mouse_event_to_web_content(Web::MouseEvent const&, bool nested_context_scrolled_since_last_frame = false);- void dispatch_key_event_to_web_content(Web::KeyEvent const&);- void dispatch_pinch_event_to_web_content(Web::PinchEvent const&);- // Whether the scroll offsets here moved past those of the last frame WebContent presented.- bool scrolled_since_last_frame() const;- bool can_dispatch_input_to_web_content() const { return m_page_id.has_value(); }- Optional<u64> page_id() const { return m_page_id; }- void set_bound_presentation(Optional<PresentationId> presentation_id) { m_bound_presentation = presentation_id; }- Optional<PresentationId> bound_presentation() const { return m_bound_presentation; }-- bool presents_to_client() const { return m_presents_to_client; }- void stop_presenting_to_client();-- void set_parent_context(Optional<Web::CompositorContextId>);- Web::CompositorContextId context_id() const { return m_context_id; }- Optional<Web::CompositorContextId> parent_context_id() const { return m_parent_context_id; }-- void install_display_list_update(- NonnullRefPtr<Compositing::DisplayList>,- Compositing::AccumulatedVisualContextTree,- Compositing::ScrollStateSnapshot&&,- 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(Compositing::AccumulatedVisualContextTree, MonotonicTime now);- void update_scroll_state(Compositing::ScrollStateSnapshot&&, Compositing::KeyboardScrollState);-- void invalidate_wheel_event_listener_state(u64 generation);- void invalidate_keyboard_scroll_state(u64 generation);- ContextUpdateResult handle_key_event(Web::KeyEvent const&, MonotonicTime now);- Optional<Web::AsyncScrollNodeStableID> box_scrolled_for_key_event(Web::KeyEvent const&) const;- ContextUpdateResult handle_mouse_event(Web::MouseEvent const&, MonotonicTime now);- // A mouse event that the context this one is nested in hands to it, at a position in this context's device pixels.- ContextUpdateResult handle_mouse_event_from_containing_context(Web::MouseEvent const&, Gfx::FloatPoint position, MonotonicTime now);- bool has_captured_scrollbar() const { return m_scrollbar_controller.has_captured_scrollbar(); }- // The pointer left the scrollbar it was over here for a context nested in this one, or for the one around it.- Optional<PendingFrame> clear_scrollbar_hover();- Optional<Compositing::NestedContextHit> position_in_content_of_nested_context(Web::CompositorContextId, Gfx::FloatPoint position);- // What a presenting context keeps of the contexts nested in it that the pointer is in, with positions in the device- // pixels of those contexts.- struct PointerInNestedContexts {- // The context whose scrollbar the pointer is dragging, which takes the pointer wherever it goes until the drag- // ends.- Optional<Web::CompositorContextId> context_with_captured_scrollbar;- Gfx::FloatPoint last_position_in_context_with_captured_scrollbar;- Optional<Web::CompositorContextId> context_under_pointer;- };- PointerInNestedContexts& pointer_in_nested_contexts() { return m_pointer_in_nested_contexts; }- // What this context noted of a wheel event as the event arrived.- struct NotedWheelEvent {- Web::WheelGestureMark wheel_gesture_mark;- // Only the first step of a gesture that moves anything goes to a nested context.- bool is_first_wheel_event_with_delta { false };- };- // Takes note of a wheel event from the UI as it arrives, ahead of anything that may turn it away or leave it to- // the page.- NotedWheelEvent note_wheel_event_from_ui(Web::MouseEvent const&, MonotonicTime now);- // Takes note of a wheel event that the main thread has and the UI did not send here, as the UI's events are noted.- // Such an event adds nothing to the velocity of a flick or of a stretch release.- NotedWheelEvent note_wheel_event_from_main_thread(Web::MouseEvent const&, MonotonicTime now);- // The UI's wheel deltas are in CSS pixels; this scales them for the scroll tree, which works in device pixels.- ContextUpdateResult handle_wheel_event(Web::MouseEvent const&, bool is_first_wheel_event_with_delta, WheelEventListenerGate const&, MonotonicTime now);- // Routes the event like one from the UI, also in a context that is nested in another one.- ContextUpdateResult scroll_for_wheel_event_from_main_thread(Web::MouseEvent const&, bool is_first_wheel_event_with_delta, WheelEventListenerGate const&, Compositing::AsyncScrollOperationTracking, MonotonicTime now);- Optional<u64> wheel_gesture_id() const { return m_wheel_gesture_routing.gesture_id(); }- bool wheel_step_was_overtaken(Web::ScrollGesturePhase phase, u64 step_number) const { return m_wheel_gesture_routing.step_was_overtaken(phase, step_number); }- Optional<Web::CompositorContextId> wheel_event_listener_context() const { return m_wheel_gesture_routing.wheel_event_listener_context(); }- void set_wheel_event_listener_context(Web::CompositorContextId context_id) { m_wheel_gesture_routing.set_wheel_event_listener_context(context_id); }- WheelEventListenerGate wheel_event_listener_gate(Optional<u64> gesture_id) const;- void note_page_let_wheel_gesture_through(u64 gesture_id) { m_wheel_gesture_routing.note_page_let_gesture_through(gesture_id); }- void forget_page_let_wheel_gesture_through(u64 gesture_id) { m_wheel_gesture_routing.forget_page_let_gesture_through(gesture_id); }- // A wheel event of the UI that this context did not scroll by is left to its page, which then answers whether it let- // the event through.- void note_wheel_event_left_to_the_page(Web::MouseEvent const&);- bool take_wheel_delta_left_to_the_page(Gfx::FloatPoint delta_in_css_pixels) { return m_wheel_gesture_routing.take_delta_left_to_the_page(delta_in_css_pixels); }- bool has_wheel_latch_for_gesture(Optional<u64> gesture_id) const { return m_wheel_gesture_routing.has_latch_for_gesture(gesture_id); }- Optional<Web::CompositorContextId> nested_context_of_wheel_latch() const { return m_wheel_gesture_routing.nested_context_of_latch(); }- Optional<Web::AsyncScrollNodeStableID> wheel_latched_scroller() const { return m_wheel_gesture_routing.latched_scroller(); }- void forget_wheel_latch_of_gesture(u64 gesture_id) { m_wheel_gesture_routing.clear_latch_of_gesture(gesture_id); }- void end_wheel_gesture_stretch(MonotonicTime now) { m_elastic_overscroll_controller.end_gesture(now); }- ContextUpdateResult handle_pinch_event(Web::PinchEvent const&);- bool admits_async_pinch() const { return m_wheel_gesture_routing.admits_async_pinch(); }- // Whether this context's page may cancel the ctrl+wheel event of a pinch at the position, or has yet to tell.- bool page_may_cancel_pinch_at(Gfx::FloatPoint position);- bool pinch_gesture_was_let_through() const { return m_pinch_gesture_was_let_through; }- u64 user_input_scroll_count() const { return m_context_user_input_scroll_count; }- void set_pinch_gesture_was_let_through(bool was_let_through) { m_pinch_gesture_was_let_through = was_let_through; }-- bool may_hand_first_wheel_steps_to_nested_contexts() const;- Optional<Compositing::NestedContextHit> nested_context_for_wheel_at(Gfx::FloatPoint position);- ContextUpdateResult scroll_for_wheel_event_passed_on_by_nested_context(Web::MouseEvent const&, Compositing::AsyncScrollOperationTracking, MonotonicTime now);- void latch_wheel_gesture_to_nested_context(Web::CompositorContextId, Optional<Web::AsyncScrollNodeStableID> scroller, Web::ScrollGesturePhase);- // Where a position in the viewport of a context nested in this one lies in this context's viewport.- Optional<Gfx::FloatPoint> position_of_nested_context_position(Web::CompositorContextId, Gfx::FloatPoint position_in_nested_context, Gfx::IntSize nested_context_viewport_size);- void forget_wheel_gesture_latch() { m_wheel_gesture_routing.clear_latch(); }- void clear_per_test_input_state();-- // The scrollers the page found around the target of a step that it let through, innermost first, go before a hit- // test at the position of the step.- FirstWheelStepRoute route_first_wheel_step_from_containing_context(Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels, Web::WheelDeltaPrecision, Compositing::NestedContextRegions, WheelStepAdmission, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain = {});- // Latches the gesture to the scroller the route found, or to the one that keeps the step, and scrolls by the step.- ContextUpdateResult take_first_wheel_step_from_containing_context(FirstWheelStepRoute const&, WheelStep const&, MonotonicTime now);- ContextUpdateResult take_latched_wheel_step_from_containing_context(WheelStep const&, WheelStepAdmission, MonotonicTime now);- // The first step of a gesture that the page let through, routed from the scrollers the page found around its target,- // innermost first, if this context knows one, and by a hit test otherwise.- ContextUpdateResult scroll_for_first_wheel_step_the_page_let_through(WheelStep const&, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, MonotonicTime now);- // A step of a gesture that the page let through and that is latched to a scroller of this context. Empty once the- // scroller is gone.- Optional<ContextUpdateResult> scroll_for_latched_wheel_step_the_page_let_through(WheelStep const&, MonotonicTime now);- // A step of a gesture that this context has moved past scrolls once along its route, latching and stretching- // nothing.- ContextUpdateResult scroll_for_overtaken_wheel_step(WheelStep const&, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, MonotonicTime now);- Optional<Web::UniqueNodeID> document_id() const { return m_async_scroll_tree.document_id(); }- Optional<PendingFrame> apply_scroll_requests(ReadonlySpan<Compositing::ScrollRequest>, MonotonicTime now);- void cancel_smooth_scroll(Web::AsyncScrollNodeStableID);- Optional<Gfx::IntRect> advance_smooth_scroll_animations(MonotonicTime now);- bool needs_animation_frames(MonotonicTime now) { return has_active_smooth_scroll_animations() || has_active_scroll_fling() || m_elastic_overscroll_controller.has_rebound() || visual_animations_need_frame(now) || m_scrollbar_controller.fades_need_frame(now); }- void request_display_ticks_if_needed(MonotonicTime now);- Optional<Gfx::IntRect> timer_fired(ContextTimer, MonotonicTime now);-- bool has_active_scroll_fling() const { return m_scroll_fling_controller.is_active(); }- // The wheel event of the next step of the fling, which is scrolled by like a wheel event from the UI.- Optional<Web::MouseEvent> take_scroll_fling_step(MonotonicTime frame_time);- Optional<Web::MouseEvent> end_scroll_fling();- ContextUpdateResult scroll_for_fling_step(Web::MouseEvent const&, WheelEventListenerGate const&, MonotonicTime now);- void end_scroll_fling_on_next_step();- // Starts a fling if the gesture that the event ends was a flick. Use only on platforms that send no momentum- // scroll events.- bool start_scroll_fling_if_flicked(Web::MouseEvent const& gesture_end_event, MonotonicTime now);- // Ends the fling before a wheel event from a new gesture or other input.- Optional<Web::MouseEvent> interrupt_scroll_fling(Web::MouseEvent const&, MonotonicTime now);- // Ends the fling, or the gesture whose momentum the platform is reporting, if it scrolls the box, so that the rest of- // its momentum scrolls nothing. Returns the end of the gesture to send on to WebContent.- Optional<Web::MouseEvent> end_momentum_scrolling(Web::AsyncScrollNodeStableID);- // Whether the wheel event from the UI is momentum, or the end, of a gesture whose momentum was interrupted.- bool absorbs_wheel_event_of_interrupted_momentum(Web::MouseEvent const&);- // What the presentation a context is shown through makes of the user's scrolling.- struct ScrollCapabilities {- bool synthesizes_scroll_momentum { false };- bool scrolls_elastically { false };- bool scrollbar_track_press_jumps { false };- Compositing::TouchpadGestureEnd touchpad_gesture_end { Compositing::TouchpadGestureEnd::AfterIdleDelay };- };- void set_scroll_capabilities(ScrollCapabilities const&);- bool presentation_synthesizes_scroll_momentum() const { return m_presentation_synthesizes_scroll_momentum; }- Optional<Gfx::IntRect> advance_elastic_overscroll_rebounds(MonotonicTime frame_time);- Gfx::IntRect advance_scrollbar_fades_and_return_damage_rect(MonotonicTime frame_time);- // The installed scrolling state, its routing admission, and how far the given scroller is stretched, as JSON.- String scroll_state_for_testing(Web::AsyncScrollNodeStableID scroller) const;- Web::InputTraceRecorder& input_trace() { return m_input_trace; }- // Where the first step of a wheel gesture at the position, by the delta in CSS pixels, would go.- Compositing::FirstWheelStepRouteForTesting route_first_wheel_step_for_testing(Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels, Compositing::NestedContextRegions);- bool advance_visual_animations(MonotonicTime now);- bool visual_animations_need_frame(MonotonicTime now);- // Where the pointer is in this context's device pixels, as the mouse event the context takes or hands on says, or- // nowhere, as the pointer leaves it.- void note_pointer_position(Optional<Gfx::FloatPoint>);- Compositing::PendingAsyncScrollUpdates take_pending_async_scroll_updates();- bool has_pending_async_scroll_updates() const;- void publish_pending_async_scroll_updates();-- Gfx::IntSize viewport_size() const { return m_viewport_size; }- void viewport_size_updated(Gfx::IntSize);- void set_paused_debugger_overlay_is_shown(bool);-- bool set_visibility(Compositing::ContextVisibility);- Compositing::ContextVisibility visibility() const { return m_visibility; }- void post_clock_tick(MonotonicTime frame_time, double frame_interval_milliseconds);- // Where the compositor has scrolled each scroll node to.- Vector<Web::CompositorScrollOffset> scroll_offsets() const;-- // Each frame shows the scrollbars as of when it is painted, so this updates which of them are shown. Empty until a- // display list is installed.- Optional<FrameInputs> frame_inputs(MonotonicTime now);- struct ScreenshotInputs {- FrameInputs frame_inputs;- // The scrollbar fade damage that the screenshot does not present on screen.- Gfx::IntRect scrollbar_fade_damage_rect;- };- ScreenshotInputs frame_inputs_for_screenshot(MonotonicTime now);--private:- template<typename Message, typename... Arguments>- void post_to_web_content(Arguments&&... arguments)- {- auto buffer = MUST(Message::static_encode(forward<Arguments>(arguments)...));- m_host.post_message_to_web_content(m_web_content_client_id, buffer);- }-- template<typename Message, typename... Arguments>- void post_to_render_clock_of_web_content(Arguments&&... arguments)- {- auto buffer = MUST(Message::static_encode(forward<Arguments>(arguments)...));- m_host.post_message_to_render_clock_of_web_content(m_web_content_client_id, buffer);- }-- struct ActiveSmoothScrollAnimation {- Web::AsyncScrollNodeStableID stable_node_id;- Compositing::AsyncScrollOperationID operation_id;- Compositing::SmoothScrollAnimation animation;- MonotonicTime started_at;- bool is_user_scroll { false };- // Whether the scroll goes to an end of the scroll range, as the Home and End keys scroll.- bool heads_to_an_extent { false };- };-- struct VisualViewportScrollDelta {- Compositing::AsyncScrollOffset scroll_offset;- Gfx::FloatPoint consumed_delta;- };-- void end_keyboard_scroll_gesture();- struct KeyScroll {- KeyboardScrollController::KeyStep step;- // Empty if every box the key could scroll is at the end of its scroll range.- Optional<Compositing::SpatialNodeIndex> target_scroll_node_index;- };- Optional<KeyScroll> key_scroll_for(Web::KeyEvent const&) const;- Optional<Web::MouseEvent> interrupt_reported_scroll_momentum();- Compositing::ScrollStateSnapshot scroll_state_snapshot_at_keyboard_step_starts() const;- void adopt_keyboard_scroll_state(Compositing::KeyboardScrollState);- Optional<VisualViewportScrollDelta> apply_visual_viewport_scroll_delta(Gfx::FloatPoint);- void note_user_input_scrolled(Web::AsyncScrollNodeStableID);- Optional<Gfx::Orientation> axis_held_by_scrollbar_of(Compositing::SpatialNodeIndex) const;- void scroll_visual_viewport_position_in_page(Compositing::SpatialNodeIndex viewport_scroll_node_index, Compositing::RequestedRelativeScroll const&, Vector<Compositing::AsyncScrollOffset>& answers);- // Returns whether the request moved the visual viewport.- bool apply_visual_viewport_scroll_request(Compositing::ScrollRequest const&, Vector<Compositing::AsyncScrollOffset>& answers);- // Pans the visual viewport of a zoomed page by as much of a delta in screen pixels as it has room for, and returns- // that part of the delta.- Gfx::FloatPoint pan_visual_viewport_by(Gfx::FloatPoint delta_in_screen_pixels);- HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> scroll_offsets_by_stable_id() const;- Optional<Gfx::FloatPoint> keep_scroll_offsets_of_known_nodes(HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> const&);- void store_pending_async_scroll_offsets(ReadonlySpan<Compositing::AsyncScrollOffset>, Optional<Compositing::AsyncScrollOperationID> = {});- enum class VisualViewportPanning : u8 {- // The step is in the pixels of the scroller, and only scrolls it.- No,- // The step is in screen pixels, and pans the visual viewport of a zoomed page before it scrolls anything.- BeforeScrolling,- };- struct WheelScrollOutcome {- Optional<Compositing::AsyncScrollOperationID> operation_id;- // The viewport to present, when the step panned the visual viewport, moved a scrolling box or started a snap- // scroll of one.- Optional<Gfx::IntRect> viewport_rect_to_present;- // What is presented differs only by an elastic overscroll, which WebContent has nothing to update for.- bool only_elastic_overscroll_changed { false };- };- // A step of a wheel gesture that is latched to the node. A stretch of the node is relaxed before the visual- // viewport is panned, the node only scrolls by what both leave of the step, and what the node cannot scroll by- // either is what pulls it past its edge.- WheelScrollOutcome perform_wheel_scroll_of_node(Compositing::SpatialNodeIndex, Gfx::FloatPoint delta, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, Compositing::AsyncScrollOperationTracking, Gfx::IntRect viewport_rect, Compositing::ScrollChaining, VisualViewportPanning, MonotonicTime now);- struct NodeScrollByWheelDelta {- WheelScrollOutcome outcome;- // Empty when a wheel animation or a snap scroll took the delta, and when it scrolled an ancestor of the node.- Optional<Gfx::FloatPoint> delta_the_node_did_not_scroll_by;- };- NodeScrollByWheelDelta scroll_node_by_wheel_delta(Compositing::SpatialNodeIndex, Gfx::FloatPoint delta, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, Compositing::AsyncScrollOperationTracking, Gfx::IntRect viewport_rect, Compositing::ScrollChaining, MonotonicTime now);- WheelGestureRouting::ResolvedLatch resolve_wheel_scroll_latch(Web::ScrollGesturePhase, Optional<u64> gesture_id);- struct WheelGestureLatchAttempt {- Web::InputRoutingDecision decision;- Optional<Compositing::SpatialNodeIndex> latched_scroll_node_index {};- };- // The scroller the first step of a wheel gesture is routed to, which the gesture is latched to.- WheelGestureLatchAttempt route_and_latch_wheel_gesture(Gfx::FloatPoint position, Gfx::FloatPoint delta, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, Optional<u64> gesture_id, Compositing::WheelStepDispatch, Compositing::NestedContextRegions, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain);- // The scroller the first step of a gesture goes to, as the hit test at the position finds it, or as it is found- // from the innermost of the scrollers the page found around the target that this context knows.- Compositing::WheelHitTestResult route_first_wheel_step(Gfx::FloatPoint position, Gfx::FloatPoint delta, Web::WheelDeltaPrecision, Compositing::WheelStepDispatch, Compositing::NestedContextRegions, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain);- ContextUpdateResult take_wheel_step_from_containing_context(Compositing::SpatialNodeIndex, Web::InputRoutingDecision, WheelStep const&, Compositing::ScrollChaining, MonotonicTime now);- Gfx::IntRect note_async_scrolling_viewport_rect(Gfx::IntRect viewport_rect, Optional<Compositing::AsyncScrollOffset> const&);- Optional<Compositing::AsyncScrollOperationID> snap_at_gesture_end(MonotonicTime now);- Compositing::AsyncScrollOperationID start_snap_scroll(Compositing::SpatialNodeIndex, ScrollSnapController::SnapScrollStart&&, bool settles_gesture, MonotonicTime now);- bool has_active_smooth_scroll_animations() const { return !m_smooth_scroll_animations.is_empty(); }- void retire_smooth_scroll_animation(Web::AsyncScrollNodeStableID);- void cancel_smooth_scroll_taken_over_by_user_input(Compositing::SpatialNodeIndex);- bool wheel_step_can_stretch_elastically(Web::WheelDeltaPrecision, Web::ScrollGesturePhase) const;- bool pull_elastic_overscroll_by(Compositing::AsyncScrollNode const&, Gfx::FloatPoint step_delta, Gfx::FloatPoint delta_the_scroller_did_not_scroll_by);- Optional<Compositing::ScrollStateSnapshot> scroll_state_snapshot_stretched_by_elastic_overscrolls() const;- NotedWheelEvent note_wheel_event(Web::MouseEvent const&, MonotonicTime now);- ContextUpdateResult scroll_for_wheel_event(Web::MouseEvent const&, bool is_first_wheel_event_with_delta, WheelEventListenerGate const&, Compositing::AsyncScrollOperationTracking, MonotonicTime now);- // A step of the gesture latched to the scroller, or the first step, which latches the gesture to the scroller it is- // routed to.- ContextUpdateResult scroll_for_wheel_step_in_this_context(WheelStep const&, Optional<Compositing::SpatialNodeIndex> latched_scroll_node_index, Compositing::NestedContextRegions, WheelStepAdmission, ReadonlySpan<Web::AsyncScrollNodeStableID> scroll_chain, MonotonicTime now);- Optional<TrackedScrollOperation> tracked_scroll_operation(Compositing::AsyncScrollOperationTracking, Optional<Compositing::AsyncScrollOperationID>) const;- Gfx::FloatPoint wheel_event_delta_in_device_pixels(Web::MouseEvent const&) const;- Optional<Gfx::FloatPoint> in_flight_wheel_destination(Web::AsyncScrollNodeStableID) const;- AsyncScrollResult smooth_wheel_scroll_by(Optional<Compositing::WheelScrollTarget> const&, Gfx::IntRect viewport_rect, MonotonicTime now);- void retarget_user_scroll(ActiveSmoothScrollAnimation&, Gfx::FloatPoint destination_offset, MonotonicTime now);- void report_started_user_scroll(Compositing::AsyncScrollOperationID, Web::AsyncScrollNodeStableID, Gfx::FloatPoint step_start_offset, Gfx::FloatPoint destination_offset, Compositing::ScrollAnimationKind, bool is_absolute_scroll = false);- Optional<Web::AsyncScrollNodeStableID> box_of_captured_scrollbar() const;- void note_user_scroll_gesture_end_if_drag_ended(Optional<Web::AsyncScrollNodeStableID> box_of_dragged_scrollbar);- void end_user_scroll_gesture_of_held_keys();- AsyncScrollUpdateOutbox::UserScrollGestureState user_scroll_gesture_state() const;- void schedule_end_of_scroll_step_gestures(MonotonicTime now);- // A gesture whose steps this context chains ends once they stop arriving, which is reported to WebContent so- // that it settles the gesture then rather than on a clock of its own.- void end_scroll_step_gestures_whose_input_ran_out(MonotonicTime now);- ContextUpdateResult handle_mouse_event_at(Web::MouseEvent const&, Gfx::FloatPoint position, MonotonicTime now);- Optional<Compositing::NestedContextHit> nested_context_taking_mouse_event_at(Web::MouseEvent::Type, Gfx::FloatPoint position);- Optional<PendingFrame> frame_repainting_scrollbars() const;- Optional<size_t> scrollbar_under_pointer(Gfx::FloatPoint position);- Optional<PendingFrame> apply_scrollbar_drag(ScrollbarController::Drag const&, MonotonicTime now);- Optional<PendingFrame> start_scrollbar_press_scroll(Compositing::AsyncScrollNode const&, Gfx::FloatPoint old_scroll_offset, Gfx::FloatPoint destination, bool is_absolute_scroll, MonotonicTime now);- Optional<PendingFrame> page_captured_scrollbar(MonotonicTime now);- void stop_scrollbar_paging();- // The smooth scroll that a press beside the thumb started, while it lasts.- ActiveSmoothScrollAnimation* running_scrollbar_press_scroll();- void rebuild_wheel_hit_test_targets();- FrameInputs frame_inputs_as_presented_now();- Gfx::IntRect damage_rect_of_blinking_carets();- void restart_caret_blink_for(Compositing::DisplayList const&, MonotonicTime now);- void schedule_next_caret_blink(MonotonicTime now);- void update_scrollbar_visibility(MonotonicTime now);- void report_scrollbar_visibility_changes();-- CompositorCoreHost& m_host;- WebContentClientId m_web_content_client_id;- Web::CompositorContextId m_context_id;- Optional<u64> m_page_id;- Optional<PresentationId> m_bound_presentation;-- Optional<Web::CompositorContextId> m_parent_context_id;-- ContextScene m_scene;- bool m_presents_to_client { false };- Gfx::IntSize m_viewport_size;- bool m_paused_debugger_overlay_is_shown { false };- Compositing::ScrollStateSnapshot m_scroll_state_snapshot;-- Compositing::AsyncScrollTree m_async_scroll_tree;- ScrollbarController m_scrollbar_controller;- ScrollSnapController m_scroll_snap_controller;-- AsyncScrollUpdateOutbox m_async_scroll_update_outbox;- // The last of the main thread's scroll requests applied to each box, which the box's reported offsets are marked with.- HashMap<Web::AsyncScrollNodeStableID, u64> m_applied_scroll_request_ids;- // How many times this context scrolled each box for user input of its own, which the reports are marked with too.- HashMap<Web::AsyncScrollNodeStableID, u64> m_user_input_scroll_counts;- u64 m_context_user_input_scroll_count { 0 };- // The boxes the last frame brought, whose offsets came from that frame's snapshot.- HashTable<Web::AsyncScrollNodeStableID> m_scroll_nodes_seeded_by_last_frame;- // Whether this context has scrolled boxes to offsets that WebContent's last frame does not have them at.- bool m_scroll_offsets_differ_from_last_frame { false };- // The document whose visual viewport this context zoomed or panned, which it presents as it left it from then on.- Optional<Web::UniqueNodeID> m_visual_viewport_document_id;- bool m_pinch_gesture_was_let_through { false };- KeyboardScrollController m_keyboard_scroll_controller;- // The boxes that the keys held since none was have scrolled, whose gesture lasts until the last of them is released.- Vector<Web::AsyncScrollNodeStableID> m_boxes_scrolled_by_held_keys;- WheelGestureRouting m_wheel_gesture_routing;- Vector<ActiveSmoothScrollAnimation> m_smooth_scroll_animations;- // The smooth scroll that a press beside the thumb of the captured scrollbar started.- Optional<Compositing::AsyncScrollOperationID> m_scrollbar_press_scroll_operation;- // A press beside the thumb that pages toward the pointer for as long as it is held.- struct ScrollbarPaging {- int direction { 0 };- float primary_position { 0 };- };- Optional<ScrollbarPaging> m_scrollbar_paging;- bool m_scrollbar_track_press_jumps { false };- bool m_presentation_synthesizes_scroll_momentum { false };- bool m_scrollbar_paging_timer_is_armed { false };- PointerInNestedContexts m_pointer_in_nested_contexts;- Optional<Gfx::FloatPoint> m_pointer_position;- bool m_animated_content_was_under_pointer { false };- ScrollFlingController m_scroll_fling_controller;- Optional<Web::MouseEvent> m_last_reported_scroll_momentum_step;- bool m_reported_scroll_momentum_was_interrupted { false };- ElasticOverscrollController m_elastic_overscroll_controller;- Gfx::IntRect m_async_scrolling_viewport_rect;- bool m_has_async_scrolling_state { false };-- Optional<i64> m_caret_blink_cycle_start_time_ns;- Web::InputTraceRecorder m_input_trace;- Compositing::ContextVisibility m_visibility { Compositing::ContextVisibility::Visible };-};--}diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex d161bd42e61..4dc2b598d13 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -37,7 +37,6 @@#include <Compositor/CanvasSurfaceRegistry.h>#include <Compositor/DisplayListPlayerSkia.h>#include <Compositor/DisplayListRasterCache.h>-#include <Compositor/ScrollbarController.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/SkiaUtils.h>#include <LibGfx/Bitmap.h>diff --git a/Services/Compositor/ElasticOverscrollController.cpp b/Services/Compositor/ElasticOverscrollController.cppdeleted file mode 100644index 72593995b9e..00000000000--- a/Services/Compositor/ElasticOverscrollController.cpp+++ /dev/null@@ -1,189 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Math.h>-#include <Compositor/ElasticOverscrollController.h>-#include <LibCompositing/Scrolling/AsyncScrollTree.h>--namespace Compositor {--void ElasticOverscrollController::set_enabled(bool enabled)-{- m_enabled = enabled;- if (!enabled)- forget();-}--bool ElasticOverscrollController::step_can_stretch(Web::WheelDeltaPrecision wheel_delta_precision, Web::ScrollGesturePhase scroll_gesture_phase) const-{- if (!m_enabled)- return false;- // Only a touchpad gesture says when the fingers lift, which is when a stretch has to spring back.- if (wheel_delta_precision != Web::WheelDeltaPrecision::Precise)- return false;- return scroll_gesture_phase == Web::ScrollGesturePhase::Ongoing || scroll_gesture_phase == Web::ScrollGesturePhase::Momentum;-}--void ElasticOverscrollController::note_step_from_ui(Gfx::FloatPoint delta, MonotonicTime now)-{- m_step_velocity_tracker.add_step(delta, now);-}--ElasticOverscrollController::ActiveOverscroll* ElasticOverscrollController::active_overscroll_of(Web::AsyncScrollNodeStableID stable_node_id)-{- for (auto& active : m_active_overscrolls) {- if (active.stable_node_id == stable_node_id)- return &active;- }- return nullptr;-}--bool ElasticOverscrollController::has_active_overscroll_of(Web::AsyncScrollNodeStableID stable_node_id) const-{- return any_of(m_active_overscrolls, [&](auto const& active) { return active.stable_node_id == stable_node_id; });-}--Gfx::FloatPoint ElasticOverscrollController::stretch_of(Web::AsyncScrollNodeStableID stable_node_id) const-{- for (auto const& active : m_active_overscrolls) {- if (active.stable_node_id == stable_node_id)- return active.overscroll.stretch();- }- return {};-}--Gfx::FloatPoint ElasticOverscrollController::relax_by(Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint step_delta)-{- auto* active = active_overscroll_of(stable_node_id);- if (!active)- return step_delta;- auto delta_left_to_scroll_with = active->overscroll.relax_by(step_delta);- if (active->overscroll.is_at_rest())- m_active_overscrolls.remove_all_matching([&](auto const& candidate) { return candidate.stable_node_id == stable_node_id; });- return delta_left_to_scroll_with;-}--bool ElasticOverscrollController::pull_by(Compositing::AsyncScrollNode const& node, Gfx::FloatPoint scroll_offset, Gfx::FloatPoint step_delta, Gfx::FloatPoint delta_the_scroller_did_not_scroll_by, float visual_viewport_magnification)-{- // A touchpad step is rarely along one axis exactly. Only its main direction pulls, so that a vertical pan next to- // a side edge does not creep past that edge.- Gfx::FloatPoint overscroll_delta;- bool step_is_mainly_vertical = AK::abs(step_delta.y()) >= AK::abs(step_delta.x());- if (step_is_mainly_vertical) {- auto delta_y = delta_the_scroller_did_not_scroll_by.y();- bool is_at_the_edge_the_delta_points_past = (delta_y < 0 && scroll_offset.y() <= node.min_scroll_offset.y())- || (delta_y > 0 && scroll_offset.y() >= node.max_scroll_offset.y());- if (node.can_be_wheel_scrolled_vertically && node.shows_overscroll_effect_vertically && is_at_the_edge_the_delta_points_past)- overscroll_delta.set_y(delta_y);- } else {- auto delta_x = delta_the_scroller_did_not_scroll_by.x();- bool is_at_the_edge_the_delta_points_past = (delta_x < 0 && scroll_offset.x() <= node.min_scroll_offset.x())- || (delta_x > 0 && scroll_offset.x() >= node.max_scroll_offset.x());- if (node.can_be_wheel_scrolled_horizontally && node.shows_overscroll_effect_horizontally && is_at_the_edge_the_delta_points_past)- overscroll_delta.set_x(delta_x);- }- if (overscroll_delta.is_zero())- return false;-- auto* active = active_overscroll_of(node.stable_node_id);- if (!active) {- // A zoomed page shows only the part of the viewport's scrollport that its visual viewport is on, and that part- // is what bounds how far the viewport stretches.- auto scrollport_size = node.scrollport_rect.size().to_type<float>();- if (node.is_viewport)- scrollport_size.scale_by(1.0f / visual_viewport_magnification);- m_active_overscrolls.append({ node.stable_node_id, Compositing::ElasticOverscroll { scrollport_size, visual_viewport_magnification } });- active = &m_active_overscrolls.last();- }- active->overscroll.pull_by(overscroll_delta);- return true;-}--void ElasticOverscrollController::release_held_by_fingers(MonotonicTime now)-{- auto velocity = m_step_velocity_tracker.velocity_at_lift(now).value_or({});- for (auto& active : m_active_overscrolls)- active.overscroll.release(velocity, now);-}--void ElasticOverscrollController::drop_stretch_moved_by(Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint scroll_delta)-{- auto stretch = stretch_of(stable_node_id);- if ((stretch.x() != 0 && scroll_delta.x() != 0) || (stretch.y() != 0 && scroll_delta.y() != 0))- m_active_overscrolls.remove_all_matching([&](auto const& active) { return active.stable_node_id == stable_node_id; });-}--void ElasticOverscrollController::release_stretch_of(Web::AsyncScrollNodeStableID stable_node_id, MonotonicTime now)-{- if (auto* active = active_overscroll_of(stable_node_id); active && !active->overscroll.is_rebounding())- active->overscroll.release({}, now);-}--void ElasticOverscrollController::end_gesture(MonotonicTime now)-{- release_held_by_fingers(now);- m_step_velocity_tracker.reset();-}--void ElasticOverscrollController::forget()-{- m_active_overscrolls.clear();- m_step_velocity_tracker.reset();-}--void ElasticOverscrollController::did_install_scrolling_state(Compositing::AsyncScrollTree const& async_scroll_tree)-{- m_active_overscrolls.remove_all_matching([&](auto const& active) {- auto scroll_node_index = async_scroll_tree.scroll_node_index_for_stable_id(active.stable_node_id);- auto const* node = scroll_node_index.has_value() ? async_scroll_tree.scroll_node_for_index(*scroll_node_index) : nullptr;- if (!node)- return true;- // A scroller that has been told not to stretch along an axis since it was pulled lets go at once.- auto stretch = active.overscroll.stretch();- return (stretch.x() != 0 && !node->shows_overscroll_effect_horizontally) || (stretch.y() != 0 && !node->shows_overscroll_effect_vertically);- });-}--bool ElasticOverscrollController::has_rebound() const-{- return any_of(m_active_overscrolls, [](auto const& active) { return active.overscroll.is_rebounding(); });-}--bool ElasticOverscrollController::advance_rebounds(MonotonicTime frame_time)-{- bool a_presented_stretch_changed = false;- m_active_overscrolls.remove_all_matching([&](auto& active) {- if (!active.overscroll.is_rebounding())- return false;- auto stretch_before = active.overscroll.stretch();- bool is_still_rebounding = active.overscroll.advance_rebound_to(frame_time);- if (active.overscroll.stretch() != stretch_before)- a_presented_stretch_changed = true;- return !is_still_rebounding;- });- return a_presented_stretch_changed;-}--Optional<Compositing::ScrollStateSnapshot> ElasticOverscrollController::stretched_scroll_state_snapshot(Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Compositing::AsyncScrollTree const& async_scroll_tree) const-{- Optional<Compositing::ScrollStateSnapshot> stretched_scroll_state_snapshot;- for (auto const& active : m_active_overscrolls) {- auto stretch = active.overscroll.stretch();- if (stretch.is_zero())- continue;- auto scroll_node_index = async_scroll_tree.scroll_node_index_for_stable_id(active.stable_node_id);- if (!scroll_node_index.has_value())- continue;- if (!stretched_scroll_state_snapshot.has_value())- stretched_scroll_state_snapshot = scroll_state_snapshot;- // Only the scroller's own entry moves. The sticky boxes in it keep the shifts resolved for the scroll offset- // it really has, so they move with its content.- stretched_scroll_state_snapshot->set_device_offset_for_index(*scroll_node_index, stretched_scroll_state_snapshot->device_offset_for_index(*scroll_node_index) - stretch);- }- return stretched_scroll_state_snapshot;-}--}diff --git a/Services/Compositor/ElasticOverscrollController.h b/Services/Compositor/ElasticOverscrollController.hdeleted file mode 100644index 82ceb92828a..00000000000--- a/Services/Compositor/ElasticOverscrollController.h+++ /dev/null@@ -1,70 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Time.h>-#include <AK/Vector.h>-#include <LibCompositing/Scrolling/AsyncScrollingState.h>-#include <LibCompositing/Scrolling/ElasticOverscroll.h>-#include <LibCompositing/Scrolling/ScrollFling.h>-#include <LibCompositing/Scrolling/ScrollState.h>-#include <LibGfx/Point.h>-#include <LibWebCommon/Page/InputEvent.h>--namespace Compositing {--class AsyncScrollTree;--}--namespace Compositor {--class ElasticOverscrollController {-public:- void set_enabled(bool);- bool step_can_stretch(Web::WheelDeltaPrecision, Web::ScrollGesturePhase) const;- void note_step_from_ui(Gfx::FloatPoint delta, MonotonicTime now);-- bool has_active_overscroll_of(Web::AsyncScrollNodeStableID) const;- Gfx::FloatPoint stretch_of(Web::AsyncScrollNodeStableID) const;- // Uses the part of a finger step that points back to the scroll range to relax the stretch of the scroller, and- // returns the rest of the step.- Gfx::FloatPoint relax_by(Web::AsyncScrollNodeStableID, Gfx::FloatPoint step_delta);- // Returns whether the scroller is at an edge that the step points past, which is what lets the step pull it.- bool pull_by(Compositing::AsyncScrollNode const&, Gfx::FloatPoint scroll_offset, Gfx::FloatPoint step_delta, Gfx::FloatPoint delta_the_scroller_did_not_scroll_by, float visual_viewport_magnification);- void release_held_by_fingers(MonotonicTime now);- // A scroller that something else scrolls along an axis it is stretched in lets go of the stretch at once, while one- // that something else scrolls smoothly springs back from it.- void drop_stretch_moved_by(Web::AsyncScrollNodeStableID, Gfx::FloatPoint scroll_delta);- void release_stretch_of(Web::AsyncScrollNodeStableID, MonotonicTime now);- void end_gesture(MonotonicTime now);- void forget();- void did_install_scrolling_state(Compositing::AsyncScrollTree const&);-- bool has_rebound() const;- bool advance_rebounds(MonotonicTime frame_time);-- // The scroll offsets to present when a scroller is stretched, which are the only ones that leave a scroll range.- Optional<Compositing::ScrollStateSnapshot> stretched_scroll_state_snapshot(Compositing::ScrollStateSnapshot const&, Compositing::AsyncScrollTree const&) const;--private:- // A scroller that a touchpad gesture holds past an edge of its scroll range, or that is springing back from there.- // The stretch is only presented: it is in no scroll offset that the scroll tree or WebContent sees.- struct ActiveOverscroll {- Web::AsyncScrollNodeStableID stable_node_id;- Compositing::ElasticOverscroll overscroll;- };-- ActiveOverscroll* active_overscroll_of(Web::AsyncScrollNodeStableID);-- bool m_enabled { false };- Vector<ActiveOverscroll> m_active_overscrolls;- Compositing::ScrollVelocityTracker m_step_velocity_tracker;-};--}diff --git a/Services/Compositor/FrameInputs.h b/Services/Compositor/FrameInputs.hindex 1bb34cd7d5d..e6f9e0b0974 100644--- a/Services/Compositor/FrameInputs.h+++ b/Services/Compositor/FrameInputs.h@@ -8,6 +8,7 @@#include <AK/Optional.h>#include <AK/Vector.h>+#include <Compositor/CompositorCoreRustFFI.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/Scrolling/ScrollState.h>#include <LibGfx/Color.h>@@ -26,19 +27,7 @@ struct PresentedScrollbar {float opacity { 1 };};-struct ScrollbarOfFrame {- Compositing::SpatialNodeIndex scroll_node_index;- bool vertical { false };- bool is_painted_by_compositor { false };- Gfx::FloatRect gutter_rect;- Gfx::FloatRect thumb_rect;- float expansion { 0 };- float opacity { 1 };- Color thumb_color;- Color thumb_outline_color;- Color track_color;- Gfx::IntRect thin_and_expanded_gutter_rect;-};+using ScrollbarOfFrame = RustFFI::ScrollbarOfFrame;// A scroll offset outside the scroll range moves the thumb past an end of its track, where it is cut short instead.inline Gfx::IntRect thumb_rect_kept_inside_track(Gfx::IntRect thumb_rect, Gfx::IntRect const& track_rect, bool vertical)diff --git a/Services/Compositor/KeyboardScrollController.cpp b/Services/Compositor/KeyboardScrollController.cppdeleted file mode 100644index 8d44eac0afd..00000000000--- a/Services/Compositor/KeyboardScrollController.cpp+++ /dev/null@@ -1,90 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/GenericShorthands.h>-#include <Compositor/KeyboardScrollController.h>-#include <LibCompositing/Scrolling/AsyncScrollTree.h>-#include <math.h>--namespace Compositor {--void KeyboardScrollController::invalidate_state(u64 generation)-{- if (generation < m_state.generation)- return;- m_state.generation = generation;- m_state.target.clear();-}--bool KeyboardScrollController::adopt_state(Compositing::KeyboardScrollState state)-{- if (state.generation < m_state.generation)- return false;- m_state = move(state);- return true;-}--Optional<KeyboardScrollController::KeyStep> KeyboardScrollController::step_for_key(Web::KeyEvent const& event, Compositing::AsyncScrollTree const& async_scroll_tree) const-{- VERIFY(m_state.target.has_value());- auto modifiers_without_keypad = static_cast<u32>(event.modifiers) & ~Web::UIEvents::Mod_Keypad;- bool scrolls_to_start = event.key == Web::UIEvents::Key_Home || (event.key == Web::UIEvents::Key_Up && modifiers_without_keypad == Web::UIEvents::Mod_PlatformCtrl);- bool scrolls_to_end = event.key == Web::UIEvents::Key_End || (event.key == Web::UIEvents::Key_Down && modifiers_without_keypad == Web::UIEvents::Mod_PlatformCtrl);- bool scrolls_to_extent = scrolls_to_start || scrolls_to_end;- bool is_arrow = !scrolls_to_extent && first_is_one_of(event.key, Web::UIEvents::Key_Up, Web::UIEvents::Key_Down, Web::UIEvents::Key_Left, Web::UIEvents::Key_Right);- Gfx::FloatPoint delta;- if (scrolls_to_extent) {- delta = async_scroll_tree.device_offset_from_css_pixels({ 0, scrolls_to_start ? -Web::CSSPixels::max() : Web::CSSPixels::max() });- } else {- auto distance = is_arrow ? m_state.arrow_scroll_distance : m_state.page_scroll_distance;- if (!isfinite(distance) || distance <= 0)- return {};- if (event.key == Web::UIEvents::KeyCode::Key_PageUp- || event.key == Web::UIEvents::KeyCode::Key_Up || event.key == Web::UIEvents::KeyCode::Key_Left- || (event.key == Web::UIEvents::KeyCode::Key_Space && (event.modifiers & Web::UIEvents::Mod_Shift)))- distance = -distance;- bool is_horizontal = first_is_one_of(event.key, Web::UIEvents::Key_Left, Web::UIEvents::Key_Right);- delta = is_horizontal ? Gfx::FloatPoint { distance, 0 } : Gfx::FloatPoint { 0, distance };- }-- auto snap_selection_intent = Compositing::SnapSelectionStrategy::Type::EndPositionAndDirection;- if (scrolls_to_extent)- snap_selection_intent = Compositing::SnapSelectionStrategy::Type::EndPosition;- else if (is_arrow)- snap_selection_intent = Compositing::SnapSelectionStrategy::Type::Direction;-- return KeyStep {- .keyboard_scroll_target = *m_state.target,- .delta = delta,- .scrolls_to_extent = scrolls_to_extent,- .snap_selection_intent = snap_selection_intent,- };-}--void KeyboardScrollController::hold_key(Web::UIEvents::KeyCode key)-{- if (!m_held_keys.contains_slow(key))- m_held_keys.append(key);-}--KeyboardScrollController::KeyRelease KeyboardScrollController::release_key(Web::KeyEvent const& event)-{- if (event.repeat || !m_held_keys.remove_first_matching([&](auto key) { return key == event.key; }))- return KeyRelease::Ignored;- if (m_held_keys.is_empty())- return KeyRelease::ReleasedLastHeldKey;- return KeyRelease::ReleasedWhileOtherKeysAreHeld;-}--bool KeyboardScrollController::release_all_keys()-{- if (m_held_keys.is_empty())- return false;- m_held_keys.clear();- return true;-}--}diff --git a/Services/Compositor/KeyboardScrollController.h b/Services/Compositor/KeyboardScrollController.hdeleted file mode 100644index fd8de63286e..00000000000--- a/Services/Compositor/KeyboardScrollController.h+++ /dev/null@@ -1,61 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Vector.h>-#include <LibCompositing/Scrolling/ScrollSnapSelection.h>-#include <LibCompositing/Types.h>-#include <LibGfx/Point.h>-#include <LibWebCommon/Page/AsyncScrollNodeStableID.h>-#include <LibWebCommon/Page/InputEvent.h>--namespace Compositing {--class AsyncScrollTree;--}--namespace Compositor {--class KeyboardScrollController {-public:- struct KeyStep {- // Where the scroller chain the key scrolls starts.- Web::AsyncScrollNodeStableID keyboard_scroll_target;- Gfx::FloatPoint delta;- bool scrolls_to_extent { false };- Compositing::SnapSelectionStrategy::Type snap_selection_intent { Compositing::SnapSelectionStrategy::Type::EndPositionAndDirection };- };-- enum class KeyRelease : u8 {- Ignored,- ReleasedWhileOtherKeysAreHeld,- ReleasedLastHeldKey,- };-- void invalidate_state(u64 generation);- // Returns whether the state is not older than the one already adopted.- bool adopt_state(Compositing::KeyboardScrollState);- void forget_target() { m_state.target.clear(); }- bool has_target() const { return m_state.target.has_value(); }- bool state_matches_visual_context_tree_epoch(u64 visual_context_tree_structural_epoch) const { return m_state.visual_context_tree_structural_epoch == visual_context_tree_structural_epoch; }-- Optional<KeyStep> step_for_key(Web::KeyEvent const&, Compositing::AsyncScrollTree const&) const;-- void hold_key(Web::UIEvents::KeyCode);- KeyRelease release_key(Web::KeyEvent const&);- // Returns whether any key was held.- bool release_all_keys();- bool has_held_keys() const { return !m_held_keys.is_empty(); }--private:- Compositing::KeyboardScrollState m_state;- Vector<Web::UIEvents::KeyCode, 3> m_held_keys;-};--}diff --git a/Services/Compositor/RenderClockClient.ipc b/Services/Compositor/RenderClockClient.ipcindex 83b49a73311..1579eca4e13 100644--- a/Services/Compositor/RenderClockClient.ipc+++ b/Services/Compositor/RenderClockClient.ipc@@ -5,14 +5,14 @@endpoint RenderClockClient{// With where the compositor has scrolled the context's scroll nodes to at the tick.- [RustReceiver] clock_tick(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds, Vector<Web::CompositorScrollOffset> scroll_offsets) =|+ [RustReceiver, RustSender] clock_tick(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds, Vector<Web::CompositorScrollOffset> scroll_offsets) =|// The pointer moved to `position`, in the context's device pixels, beside the mouse event the main thread takes,// whose input event id `input_event_id` is. `buttons` are the buttons held, and `scrolled_since_frame` says whether// the compositor scrolled the context since the last frame WebContent presented, whose scroll offsets a hit test// there would not know.- [RustReceiver] pointer_moved(Web::CompositorContextId context_id, Web::DevicePixelPoint position, u32 buttons, bool scrolled_since_frame, u64 input_event_id) =|+ [RustReceiver, RustSender] pointer_moved(Web::CompositorContextId context_id, Web::DevicePixelPoint position, u32 buttons, bool scrolled_since_frame, u64 input_event_id) =|// The pointer left the context, beside the mouse event with the input event id `input_event_id`.- [RustReceiver] pointer_left(Web::CompositorContextId context_id, u64 input_event_id) =|- [RustReceiver] pointer_rests_on_moving_content(Web::CompositorContextId context_id) =|+ [RustReceiver, RustSender] pointer_left(Web::CompositorContextId context_id, u64 input_event_id) =|+ [RustReceiver, RustSender] pointer_rests_on_moving_content(Web::CompositorContextId context_id) =|}diff --git a/Services/Compositor/Rust/Cargo.toml b/Services/Compositor/Rust/Cargo.tomlindex b6609da2d46..8ba0491a27c 100644--- a/Services/Compositor/Rust/Cargo.toml+++ b/Services/Compositor/Rust/Cargo.toml@@ -19,5 +19,8 @@ libgfx_rust = { path = "../../../Libraries/LibGfx/Rust", default-features = falslibipc_rust = { path = "../../../Libraries/LibIPC/Rust" }rustc-demangle = "0.1"+[build-dependencies]+cbindgen = "0.29"+[lints]workspace = truediff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsnew file mode 100644index 00000000000..4dce67f3e53--- /dev/null+++ b/Services/Compositor/Rust/build.rs@@ -0,0 +1,60 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::env;+use std::error::Error;+use std::path::PathBuf;++fn main() -> Result<(), Box<dyn Error>> {+ let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);+ let out_dir = PathBuf::from(env::var("OUT_DIR")?);++ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=cbindgen.toml");++ let mut config = cbindgen::Config::from_file(manifest_dir.join("cbindgen.toml"))?;+ config.namespaces = Some(vec!["Compositor".to_string(), "RustFFI".to_string()]);+ // An ak::Span is laid out as an AK ReadonlySpan, which C++ passes it as.+ for (rust_name, cpp_name) in [+ ("Span", "AK::ReadonlySpan"),+ ("Color", "Gfx::Color"),+ ("FloatPoint", "Gfx::FloatPoint"),+ ("FloatRect", "Gfx::FloatRect"),+ ("IntRect", "Gfx::IntRect"),+ ("IntSize", "Gfx::IntSize"),+ ("SpatialNodeIndex", "Compositing::SpatialNodeIndex"),+ ("RawAttachment", "IPC::RawAttachment"),+ ("RawMessage", "IPC::FfiRawMessage"),+ ("EncodedValue", "AK::ReadonlyBytes"),+ ("FfiDisplayList", "Compositing::RustFFI::FfiDisplayList"),+ ] {+ config.export.rename.insert(rust_name.to_string(), cpp_name.to_string());+ }+ config.includes.extend(+ [+ "AK/Span.h",+ "LibCompositing/DisplayList/ContextRef.h",+ "LibGfx/Color.h",+ "LibGfx/Point.h",+ "LibGfx/Rect.h",+ "LibGfx/Size.h",+ "LibIPC/RawAttachment.h",+ "LibCompositing/RustFFI.h",+ "LibIPC/RawMessage.h",+ ]+ .map(String::from),+ );++ let mut builder = cbindgen::Builder::new().with_config(config);+ for source in ["src/ffi.rs", "src/host.rs", "src/frame_inputs.rs", "src/core/mod.rs"] {+ println!("cargo:rerun-if-changed={source}");+ builder = builder.with_src(manifest_dir.join(source));+ }+ builder+ .generate()?+ .write_to_file(out_dir.join("CompositorCoreRustFFI.h"));+ Ok(())+}diff --git a/Services/Compositor/Rust/cbindgen.toml b/Services/Compositor/Rust/cbindgen.tomlnew file mode 100644index 00000000000..b355945eabf--- /dev/null+++ b/Services/Compositor/Rust/cbindgen.toml@@ -0,0 +1,22 @@+language = "C++"+header = """/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */"""+pragma_once = true+include_version = true+line_length = 120+tab_width = 4+no_includes = true+sys_includes = ["stdint.h", "stddef.h"]+usize_is_size_t = true++[parse]+parse_deps = false++[parse.expand]+all_features = false++[export.mangle]+rename_types = "PascalCase"diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsnew file mode 100644index 00000000000..763ee011cc7--- /dev/null+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -0,0 +1,419 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The stubs of the messages of WebContent and of a presentation that reach the scroll and input logic: what their+//! sender may ask for, and the answer a synchronous one gets.++use super::{CompositorCore, ContextOwnerCheckResult};+use crate::host::{PresentationId, WebContentClientId};+use libcompositing_rust::ipc_types::compositor_presentation_client::messages::DidNotDispatchInputEvent;+use libcompositing_rust::ipc_types::compositor_presentation_server::messages::{+ HandleAndDispatchKeyEvent, HandleAndDispatchMouseEvent, HandleAndDispatchPinchEvent,+};+use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{+ ApplyScrollRequests, BeginInputTraceForTesting, BeginInputTraceForTestingResponse,+ ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, InvalidateKeyboardScrollState,+ InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState, RouteFirstWheelStepForTesting,+ RouteFirstWheelStepForTestingResponse, ScrollStateForTesting, ScrollStateForTestingResponse,+ TakeInputTraceForTesting, TakeInputTraceForTestingResponse, TakePendingAsyncScrollUpdates,+ TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread, TakeWheelEventFromMainThreadResponse,+ UpdateScrollState, WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,+};+use libcompositing_rust::ipc_types::{+ Compositing_WheelEventAnswer as WheelEventAnswer, Compositing_WheelStepLetThrough as WheelStepLetThrough,+ compositor_presentation_server, compositor_web_content_server,+};+use libcompositing_rust::scrolling::async_scrolling_state::AsyncScrollOperationID;+use libcompositing_rust::scrolling::{+ CompositorContextId, KeyEvent, KeyModifier, MouseButton, MouseEvent, MouseEventType, PendingAsyncScrollUpdates,+ PinchEvent, ScrollRequest,+};+use libcompositing_rust::time::MonotonicTime;+use libgfx_rust::FloatPoint;+use libipc_rust::Misbehavior;++// The main thread allocates the ids of the scrolls it requests from here up, so that they never meet the ids the+// compositor allocates for scrolls of its own.+const FIRST_OPERATION_ID_THE_MAIN_THREAD_REQUESTS: AsyncScrollOperationID = 1 << 63;++// Wheel deltas are scrolled by as floats.+fn is_valid_wheel_delta(delta: f64) -> bool {+ delta.is_finite() && delta.abs() <= f32::MAX as f64+}++fn is_valid_wheel_event(event: &MouseEvent) -> bool {+ event.r#type == MouseEventType::MouseWheel+ && is_valid_wheel_delta(event.wheel_delta_x)+ && is_valid_wheel_delta(event.wheel_delta_y)+}++fn is_valid_wheel_step_let_through(step: &WheelStepLetThrough) -> bool {+ step.position.x.is_finite()+ && step.position.y.is_finite()+ && step.delta_in_css_pixels.x.is_finite()+ && step.delta_in_css_pixels.y.is_finite()+}++fn is_valid_scroll_request(scroll_request: &ScrollRequest) -> bool {+ let is_finite = |point: FloatPoint| point.x.is_finite() && point.y.is_finite();+ if scroll_request+ .jump_offset+ .is_some_and(|jump_offset| !is_finite(jump_offset))+ {+ return false;+ }+ if let Some(relative_scroll) = &scroll_request.relative_scroll {+ if !is_finite(relative_scroll.delta)+ || !is_finite(relative_scroll.lower_bound)+ || !is_finite(relative_scroll.upper_bound)+ {+ return false;+ }+ if relative_scroll.lower_bound.x > relative_scroll.upper_bound.x+ || relative_scroll.lower_bound.y > relative_scroll.upper_bound.y+ {+ return false;+ }+ }+ if let Some(scale) = scroll_request.visual_viewport_scale+ && (!scale.is_finite() || scale <= 0.0)+ {+ return false;+ }+ if let Some(smooth_scroll) = &scroll_request.smooth_scroll {+ if !is_finite(smooth_scroll.destination_offset) {+ return false;+ }+ if !(smooth_scroll.relative_lower_bound.x <= smooth_scroll.relative_upper_bound.x+ && smooth_scroll.relative_lower_bound.y <= smooth_scroll.relative_upper_bound.y)+ {+ return false;+ }+ // WebContent names the compositor's own scrolls only to head them somewhere else.+ if smooth_scroll.operation_id < FIRST_OPERATION_ID_THE_MAIN_THREAD_REQUESTS+ && !smooth_scroll.retargets_operation+ {+ return false;+ }+ }+ true+}++// NB: The IPC decoder already rejects key codes, event types, wheel delta precisions and scroll gesture phases that do+// not exist, and pinch scales that are not finite. These check the rest of what the UI sends.++fn is_valid_modifiers(modifiers: KeyModifier) -> bool {+ (modifiers & !KeyModifier::Mod_Mask).is_empty()+}++fn is_valid_key_event(event: &KeyEvent) -> bool {+ is_valid_modifiers(event.modifiers)+ && event.code_point <= 0x10ffff+ // Only the compositor sets this, on its way to WebContent.+ && !event.async_scroll_performed_default_action+}++fn is_valid_mouse_event(event: &MouseEvent) -> bool {+ let all_buttons = MouseButton::Primary+ | MouseButton::Secondary+ | MouseButton::Middle+ | MouseButton::Backward+ | MouseButton::Forward;+ [+ MouseButton::None,+ MouseButton::Primary,+ MouseButton::Secondary,+ MouseButton::Middle,+ MouseButton::Backward,+ MouseButton::Forward,+ ]+ .contains(&event.button)+ && (event.buttons & !all_buttons).is_empty()+ && is_valid_modifiers(event.modifiers)+ && is_valid_wheel_delta(event.wheel_delta_x)+ && is_valid_wheel_delta(event.wheel_delta_y)+ && is_valid_wheel_delta(event.wheel_tick_120ths_x)+ && is_valid_wheel_delta(event.wheel_tick_120ths_y)+ && event.click_count >= 0+ // Only the compositor sets these, on its way to WebContent.+ && !event.async_scroll_performed_default_action+ && event.scrollbar_dragged_by_compositor.is_none()+ && event.wheel_gesture_mark.is_none()+}++fn is_valid_pinch_event(event: &PinchEvent) -> bool {+ is_valid_modifiers(event.modifiers)+ // Only the compositor sets this, on its way to WebContent.+ && !event.async_zoom_performed_default_action+}++impl CompositorCore {+ fn context_is_owned_by(+ &self,+ context_id: CompositorContextId,+ client_id: WebContentClientId,+ ) -> Result<bool, Misbehavior> {+ match self.check_context_owner(context_id, client_id) {+ ContextOwnerCheckResult::OwnedByClient => Ok(true),+ ContextOwnerCheckResult::ContextUnavailable => Ok(false),+ ContextOwnerCheckResult::ConflictingOwner => Err(Misbehavior(+ "WebContent tried to use a compositor context owned by another connection",+ )),+ }+ }++ fn is_bound_to(&self, context_id: CompositorContextId, presentation_id: PresentationId) -> bool {+ self.context_if_present(context_id)+ .is_some_and(|context| context.borrow().bound_presentation() == Some(presentation_id))+ }+}++pub struct MessagesFromWebContent<'a> {+ pub core: &'a CompositorCore,+ pub client_id: WebContentClientId,+ pub now: MonotonicTime,+}++impl MessagesFromWebContent<'_> {+ fn context_is_owned_by_sender(&self, context_id: CompositorContextId) -> Result<bool, Misbehavior> {+ self.core.context_is_owned_by(context_id, self.client_id)+ }+}++impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {+ fn update_scroll_state(&mut self, message: UpdateScrollState) -> Result<(), Misbehavior> {+ 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,+ );+ }+ Ok(())+ }++ fn invalidate_wheel_event_listener_state(+ &mut self,+ message: InvalidateWheelEventListenerState,+ ) -> Result<(), Misbehavior> {+ if self.context_is_owned_by_sender(message.context_id)? {+ self.core+ .invalidate_wheel_event_listener_state(message.context_id, message.generation);+ }+ Ok(())+ }++ fn invalidate_keyboard_scroll_state(+ &mut self,+ message: InvalidateKeyboardScrollState,+ ) -> Result<InvalidateKeyboardScrollStateResponse, Misbehavior> {+ if self.context_is_owned_by_sender(message.context_id)? {+ self.core+ .invalidate_keyboard_scroll_state(message.context_id, message.generation);+ }+ Ok(InvalidateKeyboardScrollStateResponse)+ }++ fn take_wheel_event_from_main_thread(+ &mut self,+ message: TakeWheelEventFromMainThread,+ ) -> Result<TakeWheelEventFromMainThreadResponse, Misbehavior> {+ let answer = if self.context_is_owned_by_sender(message.context_id)? && is_valid_wheel_event(&message.event) {+ self.core.take_wheel_event_from_main_thread(+ message.context_id,+ &message.event,+ message.operation_tracking,+ message.routing,+ self.now,+ )+ } else {+ WheelEventAnswer::default()+ };+ Ok(TakeWheelEventFromMainThreadResponse { answer })+ }++ fn wheel_event_let_through(+ &mut self,+ message: WheelEventLetThrough,+ ) -> Result<WheelEventLetThroughResponse, Misbehavior> {+ let answer =+ if self.context_is_owned_by_sender(message.context_id)? && is_valid_wheel_step_let_through(&message.step) {+ self.core.scroll_for_wheel_event_the_page_let_through(+ message.context_id,+ &message.step,+ message.operation_tracking,+ self.client_id,+ self.now,+ )+ } else {+ WheelEventAnswer::default()+ };+ Ok(WheelEventLetThroughResponse { answer })+ }++ fn wheel_event_canceled(&mut self, message: WheelEventCanceled) -> Result<(), Misbehavior> {+ if self.context_is_owned_by_sender(message.context_id)? {+ self.core+ .forget_wheel_gesture_the_page_canceled(message.context_id, message.wheel_gesture_id);+ }+ Ok(())+ }++ fn apply_scroll_requests(&mut self, message: ApplyScrollRequests) -> Result<(), Misbehavior> {+ if !self.context_is_owned_by_sender(message.context_id)? {+ return Ok(());+ }+ if !message.scroll_requests.iter().all(is_valid_scroll_request) {+ return Err(Misbehavior("Invalid scroll request"));+ }+ self.core+ .apply_scroll_requests(message.context_id, &message.scroll_requests, self.now);+ Ok(())+ }++ fn scroll_state_for_testing(+ &mut self,+ message: ScrollStateForTesting,+ ) -> Result<ScrollStateForTestingResponse, Misbehavior> {+ let scroll_state = if self.context_is_owned_by_sender(message.context_id)? {+ self.core+ .scroll_state_for_testing(message.context_id, message.stretched_scroller)+ } else {+ String::new()+ };+ Ok(ScrollStateForTestingResponse {+ scroll_state: scroll_state.into(),+ })+ }++ fn route_first_wheel_step_for_testing(+ &mut self,+ message: RouteFirstWheelStepForTesting,+ ) -> Result<RouteFirstWheelStepForTestingResponse, Misbehavior> {+ let route = if self.context_is_owned_by_sender(message.context_id)? {+ self.core.route_first_wheel_step_for_testing(+ message.context_id,+ message.position,+ message.delta_in_css_pixels,+ )+ } else {+ None+ };+ Ok(match route {+ Some(route) => RouteFirstWheelStepForTestingResponse {+ decision: Some(route.route.decision),+ scroller: route.route.scroller,+ document_id: route.document_id,+ },+ None => RouteFirstWheelStepForTestingResponse {+ decision: None,+ scroller: None,+ document_id: None,+ },+ })+ }++ fn begin_input_trace_for_testing(+ &mut self,+ message: BeginInputTraceForTesting,+ ) -> Result<BeginInputTraceForTestingResponse, Misbehavior> {+ if self.context_is_owned_by_sender(message.context_id)? {+ self.core.begin_input_trace_for_testing(message.context_id);+ }+ Ok(BeginInputTraceForTestingResponse)+ }++ fn clear_per_test_input_state_for_testing(+ &mut self,+ message: ClearPerTestInputStateForTesting,+ ) -> Result<ClearPerTestInputStateForTestingResponse, Misbehavior> {+ if self.context_is_owned_by_sender(message.context_id)? {+ self.core.clear_per_test_input_state_for_testing(message.context_id);+ }+ Ok(ClearPerTestInputStateForTestingResponse)+ }++ fn take_input_trace_for_testing(+ &mut self,+ message: TakeInputTraceForTesting,+ ) -> Result<TakeInputTraceForTestingResponse, Misbehavior> {+ let records = if self.context_is_owned_by_sender(message.context_id)? {+ self.core.take_input_trace_for_testing(message.context_id)+ } else {+ Vec::new()+ };+ Ok(TakeInputTraceForTestingResponse { records })+ }++ fn take_pending_async_scroll_updates(+ &mut self,+ message: TakePendingAsyncScrollUpdates,+ ) -> Result<TakePendingAsyncScrollUpdatesResponse, Misbehavior> {+ let updates = if self.context_is_owned_by_sender(message.context_id)? {+ self.core.take_pending_async_scroll_updates(message.context_id)+ } else {+ PendingAsyncScrollUpdates::default()+ };+ Ok(TakePendingAsyncScrollUpdatesResponse { updates })+ }+}++pub struct MessagesFromPresentation<'a> {+ pub core: &'a CompositorCore,+ pub presentation_id: PresentationId,+ pub now: MonotonicTime,+}++impl MessagesFromPresentation<'_> {+ fn sender_gives_input_to(&self, context_id: CompositorContextId, event_id: u64) -> bool {+ if self.core.is_bound_to(context_id, self.presentation_id) {+ return true;+ }+ self.core+ .host+ .post_to_presentation(self.presentation_id, DidNotDispatchInputEvent { context_id, event_id });+ false+ }+}++impl compositor_presentation_server::Stub for MessagesFromPresentation<'_> {+ fn handle_and_dispatch_key_event(&mut self, message: HandleAndDispatchKeyEvent) -> Result<(), Misbehavior> {+ if !is_valid_key_event(&message.event) {+ return Err(Misbehavior("Invalid key event"));+ }+ if self.sender_gives_input_to(message.context_id, message.event.id) {+ self.core.handle_and_dispatch_key_event(+ message.context_id,+ message.event,+ message.allow_keyboard_scroll,+ self.now,+ );+ }+ Ok(())+ }++ fn handle_and_dispatch_pinch_event(&mut self, message: HandleAndDispatchPinchEvent) -> Result<(), Misbehavior> {+ if !is_valid_pinch_event(&message.event) {+ return Err(Misbehavior("Invalid pinch event"));+ }+ if self.sender_gives_input_to(message.context_id, message.event.id) {+ self.core+ .handle_and_dispatch_pinch_event(message.context_id, message.event);+ }+ Ok(())+ }++ fn handle_and_dispatch_mouse_event(&mut self, message: HandleAndDispatchMouseEvent) -> Result<(), Misbehavior> {+ if !is_valid_mouse_event(&message.event) {+ return Err(Misbehavior("Invalid mouse event"));+ }+ if self.sender_gives_input_to(message.context_id, message.event.id) {+ self.core+ .handle_and_dispatch_mouse_event(message.context_id, message.event, self.now);+ }+ Ok(())+ }+}diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rsindex 5aa32def1ee..b26aacf5c94 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -7,6 +7,7 @@//! Context lifecycle, frame scheduling, and input routing for the compositor.mod input;+pub mod messages;mod testing;mod wheel;diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsnew file mode 100644index 00000000000..482dd048add--- /dev/null+++ b/Services/Compositor/Rust/src/ffi.rs@@ -0,0 +1,456 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The entry points of the scroll and input logic for the C++ of the Compositor around it.++use crate::context_state::ScrollCapabilities;+use crate::core::messages::{MessagesFromPresentation, MessagesFromWebContent};+use crate::core::{CompositorCore, ContextOwnerCheckResult};+use crate::frame_inputs::{FrameInputs, ScrollbarOfFrame};+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::ipc_types::{+ Compositing_ContextVisibility as ContextVisibility, compositor_presentation_server, compositor_web_content_server,+};+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 libipc_rust::cpp_connection::{EncodedValue, RawMessage};+use std::ffi::c_void;+use std::rc::Rc;+use std::sync::Arc;++/// # Safety+///+/// `host.host` must outlive the core, and none of the host's entry points may call back into the core.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_create(+ host: FfiCompositorCoreHost,+ scrollbars_always_shown: bool,+) -> *mut CompositorCore {+ // SAFETY: The caller keeps the host alive for as long as the core, and its entry points out of the core.+ let host = Rc::new(unsafe { Host::new(host) });+ Box::into_raw(Box::new(CompositorCore::new(host, scrollbars_always_shown)))+}++/// # Safety+///+/// `core` must be a core from `compositor_core_create` that nothing uses afterwards.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_destroy(core: *mut CompositorCore) {+ // SAFETY: The caller hands over the core `compositor_core_create` made.+ drop(unsafe { Box::from_raw(core) });+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_create_context(+ core: &mut CompositorCore,+ context_id: u64,+ has_page_id: bool,+ page_id: u64,+ web_content_client_id: u64,+) {+ core.create_context(+ CompositorContextId(context_id),+ has_page_id.then_some(page_id),+ WebContentClientId(web_content_client_id),+ );+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_destroy_context(core: &mut CompositorCore, context_id: u64) {+ core.destroy_context(CompositorContextId(context_id));+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_check_context_owner(+ core: &CompositorCore,+ context_id: u64,+ web_content_client_id: u64,+) -> ContextOwnerCheckResult {+ core.check_context_owner(+ CompositorContextId(context_id),+ WebContentClientId(web_content_client_id),+ )+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_parent_context(+ core: &CompositorCore,+ context_id: u64,+ has_parent_context: bool,+ parent_context_id: u64,+) {+ core.set_parent_context(+ CompositorContextId(context_id),+ has_parent_context.then_some(CompositorContextId(parent_context_id)),+ );+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_stop_presenting_to_client(core: &CompositorCore, context_id: u64) {+ core.stop_presenting_to_client(CompositorContextId(context_id));+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_visibility(+ core: &CompositorCore,+ context_id: u64,+ is_visible: bool,+ now_nanoseconds: i64,+) {+ let visibility = if is_visible {+ ContextVisibility::Visible+ } else {+ ContextVisibility::Hidden+ };+ core.set_visibility(+ CompositorContextId(context_id),+ visibility,+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_viewport_size_updated(+ core: &CompositorCore,+ context_id: u64,+ viewport_size: IntSize,+) {+ core.viewport_size_updated(CompositorContextId(context_id), viewport_size);+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_paused_debugger_overlay_is_shown(+ core: &CompositorCore,+ context_id: u64,+ is_shown: bool,+) {+ core.set_paused_debugger_overlay_is_shown(CompositorContextId(context_id), is_shown);+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_bound_presentation(+ core: &CompositorCore,+ context_id: u64,+ is_bound: bool,+ presentation_id: u64,+) {+ core.set_bound_presentation(+ CompositorContextId(context_id),+ is_bound.then_some(PresentationId(presentation_id)),+ );+}++/// What the presentation a context is shown through makes of the user's scrolling.+#[repr(C)]+pub struct FfiScrollCapabilities {+ pub synthesizes_scroll_momentum: bool,+ pub scrolls_elastically: bool,+ pub scrollbar_track_press_jumps: bool,+ pub touchpad_gestures_end_when_fingers_lift: bool,+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_scroll_capabilities(+ core: &CompositorCore,+ context_id: u64,+ capabilities: FfiScrollCapabilities,+) {+ core.set_scroll_capabilities(+ CompositorContextId(context_id),+ &ScrollCapabilities {+ synthesizes_scroll_momentum: capabilities.synthesizes_scroll_momentum,+ scrolls_elastically: capabilities.scrolls_elastically,+ scrollbar_track_press_jumps: capabilities.scrollbar_track_press_jumps,+ touchpad_gesture_end: if capabilities.touchpad_gestures_end_when_fingers_lift {+ TouchpadGestureEnd::WhenFingersLift+ } else {+ TouchpadGestureEnd::AfterIdleDelay+ },+ },+ );+}++/// Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode.+///+/// # Safety+///+/// The storage of `display_list` must be a live display list storage handle, and `visual_context_tree` a live retained+/// tree handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_install_display_list_update(+ core: &CompositorCore,+ context_id: u64,+ display_list: &FfiDisplayList<'_>,+ visual_context_tree: *const c_void,+ scroll_state_snapshot: 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 {+ return false;+ };+ core.install_display_list_update(+ CompositorContextId(context_id),+ Rc::new(display_list),+ // SAFETY: The caller lends a strong reference to the tree.+ unsafe { tree_sharing_handle(visual_context_tree) },+ scroll_state_snapshot,+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+ true+}++/// Answers false, leaving everything as it was, for a tree that does not fit the installed display list.+///+/// # Safety+///+/// `visual_context_tree` must be a live retained tree handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_update_visual_context_tree(+ core: &CompositorCore,+ context_id: u64,+ visual_context_tree: *const c_void,+ now_nanoseconds: i64,+) -> bool {+ core.update_visual_context_tree(+ CompositorContextId(context_id),+ // SAFETY: The caller lends a strong reference to the tree.+ unsafe { tree_sharing_handle(visual_context_tree) },+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ )+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_needs_animation_frames(+ core: &CompositorCore,+ context_id: u64,+ now_nanoseconds: i64,+) -> bool {+ core.needs_animation_frames(+ CompositorContextId(context_id),+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ )+}++/// 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,+}++type ReceiveFrameInputs = unsafe extern "C" fn(*mut c_void, &FfiFrameInputs<'_>);++/// # 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) };+}++/// Answers false, without calling `receive`, for a context that has no display list yet.+///+/// # 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.+#[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+}++/// Answers with the scrollbar fade damage that the screenshot does not present on screen.+///+/// # 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.+#[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,+) {+ let screenshot_inputs = core.frame_inputs_for_screenshot(+ CompositorContextId(context_id),+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+ // 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;+}++/// What the presentation knows of a context as a tick of a display begins.+#[repr(C)]+pub struct FfiDisplayTickInputs {+ pub context_is_on_tick_display: bool,+ pub present_is_scheduled_on_tick_display: bool,+ pub ui_overlay_fades_need_frame: bool,+ /// Whether the render clock of the context is due a tick now, of the interval that follows.+ pub clock_tick_is_due: bool,+ pub clock_tick_interval_in_milliseconds: f64,+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_display_tick(+ core: &CompositorCore,+ context_id: u64,+ frame_time_nanoseconds: i64,+ now_nanoseconds: i64,+ inputs: FfiDisplayTickInputs,+) -> DisplayTickResult {+ core.display_tick(+ CompositorContextId(context_id),+ MonotonicTime::from_nanoseconds(frame_time_nanoseconds),+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ &DisplayTickInputs {+ context_is_on_tick_display: inputs.context_is_on_tick_display,+ present_is_scheduled_on_tick_display: inputs.present_is_scheduled_on_tick_display,+ ui_overlay_fades_need_frame: inputs.ui_overlay_fades_need_frame,+ clock_tick_interval_in_milliseconds: inputs+ .clock_tick_is_due+ .then_some(inputs.clock_tick_interval_in_milliseconds),+ },+ )+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_timer_fired(+ core: &CompositorCore,+ context_id: u64,+ timer: ContextTimer,+ now_nanoseconds: i64,+) {+ core.timer_fired(+ CompositorContextId(context_id),+ timer,+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+}++/// A frame that the scroll and input logic of a context wants presented.+#[repr(C)]+pub struct FfiPresentRequest {+ pub context_id: u64,+ /// When false, the frame is at the viewport rect the context is presented at.+ pub has_viewport_rect: bool,+ pub viewport_rect: IntRect,+ pub forced_damage_rect: IntRect,+ pub scheduling: PresentScheduling,+}++/// Hands over the frames asked for since the last call, in the order they were asked for.+///+/// # Safety+///+/// `receive` must not call back into the core.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_take_present_requests(+ core: &CompositorCore,+ receiver: *mut c_void,+ receive: unsafe extern "C" fn(*mut c_void, FfiPresentRequest),+) {+ for request in core.take_present_requests() {+ // SAFETY: The caller's receiver stays out of the core.+ unsafe {+ receive(+ receiver,+ FfiPresentRequest {+ context_id: request.context_id.0,+ has_viewport_rect: request.viewport_rect.is_some(),+ viewport_rect: request.viewport_rect.unwrap_or_default(),+ forced_damage_rect: request.forced_damage_rect,+ scheduling: request.scheduling,+ },+ );+ }+ }+}++/// Takes a message of the CompositorWebContentServer endpoint that is marked [RustReceiver].+///+/// # Safety+///+/// `message` must be one `IPC::RawMessage::hand_to_rust()` made.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_handle_web_content_message(+ core: &CompositorCore,+ web_content_client_id: u64,+ message: RawMessage<'_>,+ now_nanoseconds: i64,+) {+ let mut stub = MessagesFromWebContent {+ core,+ client_id: WebContentClientId(web_content_client_id),+ now: MonotonicTime::from_nanoseconds(now_nanoseconds),+ };+ // SAFETY: The caller hands over a message of that endpoint.+ unsafe {+ message.hand_to(|bytes, attachments| compositor_web_content_server::dispatch(&mut stub, bytes, attachments));+ };+}++/// Takes a message of the CompositorPresentationServer endpoint that is marked [RustReceiver].+///+/// # Safety+///+/// `message` must be one `IPC::RawMessage::hand_to_rust()` made.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_handle_presentation_message(+ core: &CompositorCore,+ presentation_id: u64,+ message: RawMessage<'_>,+ now_nanoseconds: i64,+) {+ let mut stub = MessagesFromPresentation {+ core,+ presentation_id: PresentationId(presentation_id),+ now: MonotonicTime::from_nanoseconds(now_nanoseconds),+ };+ // SAFETY: The caller hands over a message of that endpoint.+ unsafe {+ message.hand_to(|bytes, attachments| compositor_presentation_server::dispatch(&mut stub, bytes, attachments));+ };+}diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsindex 03f9f76feee..945580bb310 100644--- a/Services/Compositor/Rust/src/lib.rs+++ b/Services/Compositor/Rust/src/lib.rs@@ -20,6 +20,7 @@ pub mod context_scene;pub mod context_state;pub mod core;pub mod elastic_overscroll_controller;+pub mod ffi;pub mod frame_inputs;pub mod host;pub mod input_event;diff --git a/Services/Compositor/ScrollFlingController.cpp b/Services/Compositor/ScrollFlingController.cppdeleted file mode 100644index 4a6e31c9efe..00000000000--- a/Services/Compositor/ScrollFlingController.cpp+++ /dev/null@@ -1,115 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <Compositor/ScrollFlingController.h>--namespace Compositor {--static bool is_touchpad_step(Web::MouseEvent const& event)-{- return event.wheel_delta_precision == Web::WheelDeltaPrecision::Precise && event.scroll_gesture_phase == Web::ScrollGesturePhase::Ongoing;-}--void ScrollFlingController::note_wheel_event(Web::MouseEvent const& event, MonotonicTime now)-{- if (is_touchpad_step(event)) {- m_velocity_tracker.add_step({ static_cast<float>(event.wheel_delta_x), static_cast<float>(event.wheel_delta_y) }, now);- return;- }- m_velocity_tracker.reset();- // Other wheel input cancels the boost of the next fling.- if (event.scroll_gesture_phase != Web::ScrollGesturePhase::Ended)- m_booster.reset();-}--bool ScrollFlingController::start_if_flicked(Web::MouseEvent const& gesture_end_event, MonotonicTime now)-{- VERIFY(gesture_end_event.scroll_gesture_phase == Web::ScrollGesturePhase::Ended);- auto velocity = m_velocity_tracker.velocity_at_lift(now);- m_velocity_tracker.reset();- if (!velocity.has_value())- return false;-- auto fling = Compositing::ScrollFling::start(m_booster.boosted_velocity(*velocity, now), now);- if (!fling.has_value())- return false;- m_active_fling = ActiveFling {- .fling = fling.release_value(),- .position = gesture_end_event.position,- .screen_position = gesture_end_event.screen_position,- .modifiers = gesture_end_event.modifiers,- .wheel_gesture_mark = gesture_end_event.wheel_gesture_mark,- };- return true;-}--Optional<Web::MouseEvent> ScrollFlingController::take_step(MonotonicTime frame_time)-{- if (!m_active_fling.has_value())- return {};- if (m_active_fling->ends_on_next_step)- return end();-- auto delta = m_active_fling->fling.step(frame_time);- if (!delta.has_value())- return end();- if (delta->is_zero())- return {};- return event_of_active_fling(*delta, Web::ScrollGesturePhase::Momentum);-}--void ScrollFlingController::end_on_next_step()-{- VERIFY(m_active_fling.has_value());- m_active_fling->ends_on_next_step = true;-}--Optional<Web::MouseEvent> ScrollFlingController::end()-{- if (!m_active_fling.has_value())- return {};-- // WebContent holds the gesture open while momentum events arrive. The end of the gesture releases it.- auto event = event_of_active_fling({}, Web::ScrollGesturePhase::Ended);- m_active_fling.clear();- return event;-}--Optional<Web::MouseEvent> ScrollFlingController::interrupt(Web::MouseEvent const& event, MonotonicTime now)-{- if (!m_active_fling.has_value())- return {};-- // A new touchpad step stops the fling. The next flick can add the velocity of this fling.- if (is_touchpad_step(event))- m_booster.fling_was_interrupted(m_active_fling->fling.velocity_at(now), now);- return end();-}--Web::MouseEvent ScrollFlingController::event_of_active_fling(Gfx::FloatPoint delta, Web::ScrollGesturePhase phase) const-{- VERIFY(m_active_fling.has_value());- return {- .type = Web::MouseEvent::Type::MouseWheel,- .position = m_active_fling->position,- .screen_position = m_active_fling->screen_position,- .modifiers = m_active_fling->modifiers,- .wheel_delta_x = delta.x(),- .wheel_delta_y = delta.y(),- .wheel_tick_120ths_x = Web::wheel_tick_120ths_from_pixel_delta(delta.x(), Web::WheelDeltaPrecision::Precise),- .wheel_tick_120ths_y = Web::wheel_tick_120ths_from_pixel_delta(delta.y(), Web::WheelDeltaPrecision::Precise),- .wheel_delta_precision = Web::WheelDeltaPrecision::Precise,- .scroll_gesture_phase = phase,- .click_count = 0,- .browser_data = nullptr,- .async_scroll_performed_default_action = false,- // The IDs of UI input events start at 1. Thus, ID 0 does not match a UI event.- .id = 0,- .wheel_gesture_mark = m_active_fling->wheel_gesture_mark,- };-}--}diff --git a/Services/Compositor/ScrollFlingController.h b/Services/Compositor/ScrollFlingController.hdeleted file mode 100644index 7358e993af5..00000000000--- a/Services/Compositor/ScrollFlingController.h+++ /dev/null@@ -1,51 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Time.h>-#include <LibCompositing/Scrolling/ScrollFling.h>-#include <LibGfx/Point.h>-#include <LibWebCommon/Page/InputEvent.h>--namespace Compositor {--// Synthesizes the momentum of a touchpad flick as wheel events, for platforms that send no momentum scroll events.-class ScrollFlingController {-public:- void note_wheel_event(Web::MouseEvent const&, MonotonicTime now);- // Starts a fling if the gesture that the event ends was a flick.- bool start_if_flicked(Web::MouseEvent const& gesture_end_event, MonotonicTime now);- bool is_active() const { return m_active_fling.has_value(); }-- // The next momentum step of the fling, or the end of its gesture once the fling has run out or was told to end.- Optional<Web::MouseEvent> take_step(MonotonicTime frame_time);- void end_on_next_step();- // The end of the gesture of the fling, if one is active.- Optional<Web::MouseEvent> end();- // Ends the fling before a wheel event from a new gesture or other input.- Optional<Web::MouseEvent> interrupt(Web::MouseEvent const&, MonotonicTime now);--private:- struct ActiveFling {- Compositing::ScrollFling fling;- // The fling steps use the position, modifiers and gesture of the gesture end event.- Web::DevicePixelPoint position;- Web::DevicePixelPoint screen_position;- Web::UIEvents::KeyModifier modifiers { Web::UIEvents::KeyModifier::Mod_None };- Optional<Web::WheelGestureMark> wheel_gesture_mark;- bool ends_on_next_step { false };- };-- Web::MouseEvent event_of_active_fling(Gfx::FloatPoint delta, Web::ScrollGesturePhase) const;-- Compositing::ScrollVelocityTracker m_velocity_tracker;- Compositing::ScrollFlingBooster m_booster;- Optional<ActiveFling> m_active_fling;-};--}diff --git a/Services/Compositor/ScrollSnapController.cpp b/Services/Compositor/ScrollSnapController.cppdeleted file mode 100644index 98916427d31..00000000000--- a/Services/Compositor/ScrollSnapController.cpp+++ /dev/null@@ -1,399 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <Compositor/ScrollSnapController.h>-#include <LibCompositing/Scrolling/AsyncScrollTree.h>-#include <LibCompositing/Scrolling/ScrollState.h>--namespace Compositor {--void ScrollSnapController::did_install_scrolling_state(Compositing::AsyncScrollTree const& scroll_tree)-{- m_candidates.clear();- m_nodes.remove_all_matching([&](auto const& stable_node_id, auto const&) {- return !scroll_tree.scroll_node_index_for_stable_id(stable_node_id).has_value();- });-}--void ScrollSnapController::note_gesture_phase(Web::ScrollGesturePhase phase)-{- switch (phase) {- case Web::ScrollGesturePhase::None:- end_gesture();- break;- case Web::ScrollGesturePhase::Ongoing:- reset_momentum_fling_state();- break;- case Web::ScrollGesturePhase::Momentum:- case Web::ScrollGesturePhase::Ended:- break;- }-}--void ScrollSnapController::reset_momentum_fling_state()-{- m_momentum_snap_position_selection = MomentumSnapPositionSelection::NotSelectedYet;- m_momentum_fling_estimator.reset();-}--void ScrollSnapController::end_gesture()-{- reset_momentum_fling_state();- for (auto& [stable_node_id, state] : m_nodes)- state.gesture_start = {};-}--Vector<Web::AsyncScrollNodeStableID> ScrollSnapController::boxes_with_gesture_awaiting_input() const-{- Vector<Web::AsyncScrollNodeStableID> boxes;- for (auto const& [stable_node_id, state] : m_nodes) {- if (state.gesture_input_deadline.has_value())- boxes.append(stable_node_id);- }- return boxes;-}--Optional<MonotonicTime> ScrollSnapController::earliest_gesture_input_deadline() const-{- Optional<MonotonicTime> earliest;- for (auto const& [stable_node_id, state] : m_nodes) {- if (!state.gesture_input_deadline.has_value())- continue;- if (!earliest.has_value() || *state.gesture_input_deadline < *earliest)- earliest = state.gesture_input_deadline;- }- return earliest;-}--Vector<Web::AsyncScrollNodeStableID> ScrollSnapController::end_gestures_whose_input_ran_out(MonotonicTime now)-{- Vector<Web::AsyncScrollNodeStableID> ended_boxes;- for (auto& [stable_node_id, state] : m_nodes) {- if (!state.gesture_input_deadline.has_value() || now <= *state.gesture_input_deadline)- continue;- state.gesture_input_deadline = {};- state.unsnapped_scroll_destination = {};- ended_boxes.append(stable_node_id);- }- return ended_boxes;-}--void ScrollSnapController::did_scroll_node_plainly(Web::AsyncScrollNodeStableID stable_node_id, Web::ScrollGesturePhase phase, Web::CSSPixelPoint scroll_offset_before_scroll)-{- if (phase != Web::ScrollGesturePhase::Ongoing && phase != Web::ScrollGesturePhase::Momentum)- return;- auto& state = node_state(stable_node_id);- if (!state.gesture_start.has_value())- state.gesture_start = GestureStart { .offset = scroll_offset_before_scroll };- if (phase == Web::ScrollGesturePhase::Momentum)- state.gesture_start->travels_under_momentum = true;-}--void ScrollSnapController::did_start_main_thread_scroll(Web::AsyncScrollNodeStableID stable_node_id)-{- // A scroll started for any reason other than this controller's input is going somewhere the gesture never asked- // for, so the gesture's steps then travel from the scrolling box itself.- m_nodes.remove(stable_node_id);-}--void ScrollSnapController::did_start_snap_scroll(Web::AsyncScrollNodeStableID stable_node_id, Compositing::AsyncScrollOperationID operation_id, Web::CSSPixelPoint destination)-{- auto& state = node_state(stable_node_id);- state.snap_scroll = InFlightSnapScroll { .operation_id = operation_id, .destination = destination };- state.expected_scroll_offset = destination;-}--void ScrollSnapController::did_end_snap_scroll(Web::AsyncScrollNodeStableID stable_node_id, Compositing::AsyncScrollOperationID operation_id, Optional<Web::CSSPixelPoint> scroll_offset)-{- if (!is_snap_scroll(stable_node_id, operation_id))- return;- auto& state = node_state(stable_node_id);- state.snap_scroll = {};- state.expected_scroll_offset = scroll_offset;-}--void ScrollSnapController::did_retarget_scroll(Web::AsyncScrollNodeStableID stable_node_id, Compositing::AsyncScrollOperationID operation_id)-{- // A snap scroll sent somewhere other than the snap position selected for it no longer goes where the gesture's- // input asked, so the gesture's steps then travel from where the scroll is headed instead.- if (is_snap_scroll(stable_node_id, operation_id))- m_nodes.remove(stable_node_id);-}--bool ScrollSnapController::is_snap_scroll(Web::AsyncScrollNodeStableID stable_node_id, Compositing::AsyncScrollOperationID operation_id) const-{- auto state = m_nodes.get(stable_node_id);- return state.has_value() && state->snap_scroll.has_value() && state->snap_scroll->operation_id == operation_id;-}--Optional<Web::CSSPixelPoint> ScrollSnapController::unsnapped_destination_for_snap_scroll(Web::AsyncScrollNodeStableID stable_node_id, Compositing::AsyncScrollOperationID operation_id) const-{- if (!is_snap_scroll(stable_node_id, operation_id))- return {};- return m_nodes.get(stable_node_id)->unsnapped_scroll_destination;-}--ScrollSnapController::NodeState& ScrollSnapController::node_state(Web::AsyncScrollNodeStableID stable_node_id)-{- return m_nodes.ensure(stable_node_id);-}--Compositing::SnapAxisCandidates const& ScrollSnapController::candidates_for(Web::AsyncScrollNodeStableID stable_node_id, Compositing::AsyncSnapContainer const& snap_container)-{- return m_candidates.ensure(stable_node_id, [&] {- return Compositing::build_snap_candidates(snap_container.geometry, snap_container.areas, snap_container.geometry.axes);- });-}--Optional<ScrollSnapController::SnapTarget> ScrollSnapController::snap_target_for(Compositing::AsyncScrollTree const& scroll_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Compositing::SpatialNodeIndex scroll_node_index)-{- auto const* node = scroll_tree.scroll_node_for_index(scroll_node_index);- auto const* snap_container = scroll_tree.snap_container_for_node(scroll_node_index);- auto current_scroll_offset = scroll_tree.css_scroll_offset_for_node(scroll_node_index, scroll_state_snapshot);- if (!node || !snap_container || !current_scroll_offset.has_value())- return {};- return SnapTarget { .stable_node_id = node->stable_node_id, .snap_container = snap_container, .current_scroll_offset = *current_scroll_offset };-}--static Web::CSSPixelPoint clamp_scroll_offset(Web::CSSPixelPoint offset, Compositing::SnapContainerGeometry const& geometry)-{- return {- clamp(offset.x(), geometry.min_scroll_offset.x(), geometry.max_scroll_offset.x()),- clamp(offset.y(), geometry.min_scroll_offset.y(), geometry.max_scroll_offset.y()),- };-}--// A scroll travels only along axes the container selects no snap position in is left to the ordinary relative scroll.-static bool selected_snap_position_along_travel(Compositing::SnapDestination const& selection, Web::CSSPixelPoint displacement)-{- return (selection.snapped_x && displacement.x() != 0) || (selection.snapped_y && displacement.y() != 0);-}--Optional<ScrollSnapController::StepDecision> ScrollSnapController::decide_discrete_step(Compositing::AsyncScrollTree const& scroll_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Compositing::SpatialNodeIndex scroll_node_index, Web::CSSPixelPoint delta, Optional<Web::CSSPixelPoint> scroll_in_flight_destination, MonotonicTime now)-{- auto target = snap_target_for(scroll_tree, scroll_state_snapshot, scroll_node_index);- if (!target.has_value())- return {};- auto const& geometry = target->snap_container->geometry;-- // The step selects a snap position only along the axes it travels in that the container snaps in.- if (!(geometry.axes.x && delta.x() != 0) && !(geometry.axes.y && delta.y() != 0))- return {};-- auto current_scroll_offset = target->current_scroll_offset;- auto& state = node_state(target->stable_node_id);-- // A gesture ends once its steps stop arriving, and once anything but this controller has moved the scrolling box.- bool gesture_ended = (state.gesture_input_deadline.has_value() && now > *state.gesture_input_deadline)- || (!state.snap_scroll.has_value() && state.expected_scroll_offset != current_scroll_offset);- if (gesture_ended)- state.unsnapped_scroll_destination = {};-- // A step selects its snap position from the offset the gesture's input deltas have reached, which a wheel scroll in- // flight is headed for, rather than from the snap position it is scrolling to.- auto step_start = state.unsnapped_scroll_destination.value_or(scroll_in_flight_destination.value_or(current_scroll_offset));- auto unsnapped_destination = clamp_scroll_offset(step_start + delta, geometry);-- // NB: A step with only an intended direction ignores every snap position up to the offset its input asked for.- Compositing::SnapSelectionStrategy strategy {- .type = Compositing::SnapSelectionStrategy::Type::Direction,- .start_offset = step_start,- .displacement = delta,- .starting_positions_boundary = unsnapped_destination,- };- auto evaluated_axes = Compositing::axes_to_evaluate(geometry.axes, strategy);- auto selection = Compositing::select_snap_destination(geometry, candidates_for(target->stable_node_id, *target->snap_container), unsnapped_destination, strategy, evaluated_axes);- if (!selected_snap_position_along_travel(selection, delta))- return {};-- state.unsnapped_scroll_destination = unsnapped_destination;- state.gesture_input_deadline = now + Compositing::user_scroll_settle_delay;-- auto in_flight_destination = state.snap_scroll.map([](auto const& snap_scroll) { return snap_scroll.destination; });- if (!in_flight_destination.has_value())- in_flight_destination = scroll_in_flight_destination;- if (selection.position == in_flight_destination.value_or(current_scroll_offset)) {- if (!state.snap_scroll.has_value())- state.expected_scroll_offset = current_scroll_offset;- return StepDecision { StepConsumed {} };- }-- return StepDecision { SnapScrollStart {- .stable_node_id = target->stable_node_id,- .initial_scroll_offset = current_scroll_offset,- .unsnapped_scroll_destination = unsnapped_destination,- .relative_scroll_delta = unsnapped_destination - step_start,- .selection = move(selection),- .animation_kind = Compositing::ScrollAnimationKind::SmoothScroll,- } };-}--Optional<ScrollSnapController::StepDecision> ScrollSnapController::decide_key_step(Compositing::AsyncScrollTree const& scroll_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Compositing::SpatialNodeIndex scroll_node_index, Web::CSSPixelPoint delta, Compositing::SnapSelectionStrategy::Type strategy_type, Optional<Web::CSSPixelPoint> scroll_in_flight_destination, MonotonicTime now)-{- auto target = snap_target_for(scroll_tree, scroll_state_snapshot, scroll_node_index);- if (!target.has_value())- return {};- auto const& geometry = target->snap_container->geometry;- if (!(geometry.axes.x && delta.x() != 0) && !(geometry.axes.y && delta.y() != 0))- return {};-- auto current_scroll_offset = target->current_scroll_offset;- auto& state = node_state(target->stable_node_id);- auto in_flight_destination = state.snap_scroll.map([](auto const& snap_scroll) { return snap_scroll.destination; });- if (!in_flight_destination.has_value())- in_flight_destination = scroll_in_flight_destination;- auto step_start = state.snap_scroll.has_value()- ? state.unsnapped_scroll_destination.value_or(state.snap_scroll->destination)- : scroll_in_flight_destination.value_or(current_scroll_offset);- auto unsnapped_destination = clamp_scroll_offset(step_start + delta, geometry);-- Compositing::SnapSelectionStrategy strategy {- .type = strategy_type,- .start_offset = step_start,- .displacement = delta,- .starting_positions_boundary = {},- };- if (strategy_type == Compositing::SnapSelectionStrategy::Type::Direction)- strategy.starting_positions_boundary = unsnapped_destination;- auto evaluated_axes = Compositing::axes_to_evaluate(geometry.axes, strategy);- auto selection = Compositing::select_snap_destination(geometry, candidates_for(target->stable_node_id, *target->snap_container), unsnapped_destination, strategy, evaluated_axes);- if (!selected_snap_position_along_travel(selection, delta))- return {};-- state.unsnapped_scroll_destination = unsnapped_destination;- state.gesture_input_deadline = now + Compositing::user_scroll_settle_delay;-- if (selection.position == in_flight_destination.value_or(current_scroll_offset)) {- if (!state.snap_scroll.has_value())- state.expected_scroll_offset = current_scroll_offset;- Optional<Compositing::StartedUserScroll> updated_scroll;- if (state.snap_scroll.has_value()) {- updated_scroll = Compositing::StartedUserScroll {- .stable_node_id = target->stable_node_id,- .operation_id = state.snap_scroll->operation_id,- .initial_scroll_offset = current_scroll_offset,- .unsnapped_scroll_destination = unsnapped_destination,- .relative_scroll_delta = unsnapped_destination - step_start,- .selection = move(selection),- .settles_gesture = false,- .animation_kind = {},- };- }- return StepDecision { StepConsumed { move(updated_scroll) } };- }-- return StepDecision { SnapScrollStart {- .stable_node_id = target->stable_node_id,- .initial_scroll_offset = current_scroll_offset,- .unsnapped_scroll_destination = unsnapped_destination,- .relative_scroll_delta = unsnapped_destination - step_start,- .selection = move(selection),- .animation_kind = Compositing::ScrollAnimationKind::SmoothScroll,- } };-}--Optional<ScrollSnapController::StepDecision> ScrollSnapController::decide_momentum_delta(Compositing::AsyncScrollTree const& scroll_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Compositing::SpatialNodeIndex scroll_node_index, Web::CSSPixelPoint momentum_delta)-{- if (m_momentum_snap_position_selection == MomentumSnapPositionSelection::ScrollingToSelectedPosition)- return StepDecision { StepConsumed {} };- if (m_momentum_snap_position_selection == MomentumSnapPositionSelection::NoPositionSelected)- return {};-- auto remaining_displacement = m_momentum_fling_estimator.estimate_remaining_displacement(momentum_delta);- if (!remaining_displacement.has_value())- return {};-- auto target = snap_target_for(scroll_tree, scroll_state_snapshot, scroll_node_index);- if (!target.has_value()) {- m_momentum_snap_position_selection = MomentumSnapPositionSelection::NoPositionSelected;- return {};- }- auto const& geometry = target->snap_container->geometry;- auto& state = node_state(target->stable_node_id);-- // The momentum travels on from the snap position a snap scroll already in flight is headed for.- auto in_flight_destination = state.snap_scroll.map([](auto const& snap_scroll) { return snap_scroll.destination; });- auto step_start = in_flight_destination.value_or(target->current_scroll_offset);- auto unsnapped_destination = clamp_scroll_offset(step_start + *remaining_displacement, geometry);-- Compositing::SnapSelectionStrategy strategy {- .type = Compositing::SnapSelectionStrategy::Type::EndPositionAndDirection,- .start_offset = step_start,- .displacement = *remaining_displacement,- .starting_positions_boundary = {},- };- auto evaluated_axes = Compositing::axes_to_evaluate(geometry.axes, strategy);- auto selection = Compositing::select_snap_destination(geometry, candidates_for(target->stable_node_id, *target->snap_container), unsnapped_destination, strategy, evaluated_axes);- if (!selected_snap_position_along_travel(selection, *remaining_displacement)) {- m_momentum_snap_position_selection = MomentumSnapPositionSelection::NoPositionSelected;- return {};- }-- m_momentum_snap_position_selection = MomentumSnapPositionSelection::ScrollingToSelectedPosition;- if (selection.position == step_start)- return StepDecision { StepConsumed {} };- return StepDecision { SnapScrollStart {- .stable_node_id = target->stable_node_id,- .initial_scroll_offset = target->current_scroll_offset,- .unsnapped_scroll_destination = unsnapped_destination,- .relative_scroll_delta = unsnapped_destination - step_start,- .selection = move(selection),- .animation_kind = Compositing::ScrollAnimationKind::Momentum,- } };-}--Vector<ScrollSnapController::GestureEndSnap> ScrollSnapController::decide_gesture_end(Compositing::AsyncScrollTree const& scroll_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot)-{- Vector<GestureEndSnap> snaps;- for (auto& [stable_node_id, state] : m_nodes) {- if (!state.gesture_start.has_value())- continue;- // Momentum that selected a snap position is still scrolling to it.- if (state.snap_scroll.has_value())- continue;-- auto scroll_node_index = scroll_tree.scroll_node_index_for_stable_id(stable_node_id);- if (!scroll_node_index.has_value())- continue;- auto target = snap_target_for(scroll_tree, scroll_state_snapshot, *scroll_node_index);- if (!target.has_value())- continue;- auto const& geometry = target->snap_container->geometry;- auto current_scroll_offset = target->current_scroll_offset;-- // https://drafts.csswg.org/css-scroll-snap-1/#scroll-types- // A pan reports where the user's input came to rest, so it settles as an absolute scroll; the momentum a flick- // traveled under must not have passed a snap position that always stops on the way from where it started.- Compositing::SnapSelectionStrategy strategy {- .type = Compositing::SnapSelectionStrategy::Type::EndPosition,- .start_offset = state.gesture_start->travels_under_momentum ? Optional<Web::CSSPixelPoint> { state.gesture_start->offset } : Optional<Web::CSSPixelPoint> {},- .displacement = current_scroll_offset - state.gesture_start->offset,- .starting_positions_boundary = {},- };- auto evaluated_axes = Compositing::axes_to_evaluate(geometry.axes, strategy);- if (evaluated_axes.is_empty())- continue;- auto selection = Compositing::select_snap_destination(geometry, candidates_for(stable_node_id, *target->snap_container), current_scroll_offset, strategy, evaluated_axes);- if (selection.position == current_scroll_offset)- continue;-- snaps.append({- .scroll_node_index = *scroll_node_index,- .snap_scroll = {- .stable_node_id = stable_node_id,- .initial_scroll_offset = current_scroll_offset,- .unsnapped_scroll_destination = current_scroll_offset,- .relative_scroll_delta = {},- .selection = move(selection),- .animation_kind = Compositing::ScrollAnimationKind::SmoothScroll,- },- });- }- end_gesture();- return snaps;-}--}diff --git a/Services/Compositor/ScrollSnapController.h b/Services/Compositor/ScrollSnapController.hdeleted file mode 100644index 72d6ce6b6aa..00000000000--- a/Services/Compositor/ScrollSnapController.h+++ /dev/null@@ -1,152 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <AK/Optional.h>-#include <AK/Time.h>-#include <AK/Variant.h>-#include <LibCompositing/Scrolling/AsyncScrollingState.h>-#include <LibCompositing/Scrolling/ScrollSnapSelection.h>-#include <LibCompositing/Types.h>-#include <LibWebCommon/Page/InputEvent.h>-#include <LibWebCommon/PixelUnits.h>--namespace Compositing {--class AsyncScrollTree;--}--namespace Compositing {--class ScrollStateSnapshot;--}--namespace Compositor {--// Selects the snap positions of the wheel scrolls the compositor performs on snap containers, from the geometry the-// display list carries, the way the main thread selects them for the scrolls it performs itself. The context owns the-// scroll animations; this controller decides where they go and remembers what a gesture has asked for so far.-class ScrollSnapController {-public:- // A snap scroll to start for a wheel delta.- struct SnapScrollStart {- Web::AsyncScrollNodeStableID stable_node_id;- Web::CSSPixelPoint initial_scroll_offset;- Web::CSSPixelPoint unsnapped_scroll_destination;- Web::CSSPixelPoint relative_scroll_delta;- Compositing::SnapDestination selection;- Compositing::ScrollAnimationKind animation_kind { Compositing::ScrollAnimationKind::SmoothScroll };- bool is_absolute_scroll { false };- };-- // A step that selected the snap position the scrolling box already rests at, or is already scrolling to, is- // consumed without disturbing where the box is going. Keys can still advance the input for that scroll.- struct StepConsumed {- Optional<Compositing::StartedUserScroll> updated_scroll;- };-- // What a scroll step over a snap container does with the snap position it selected; a step that selects none- // scrolls the box by itself.- using StepDecision = Variant<StepConsumed, SnapScrollStart>;-- struct GestureEndSnap {- Compositing::SpatialNodeIndex scroll_node_index;- SnapScrollStart snap_scroll;- };-- void did_install_scrolling_state(Compositing::AsyncScrollTree const&);- void did_start_main_thread_scroll(Web::AsyncScrollNodeStableID);- void did_start_snap_scroll(Web::AsyncScrollNodeStableID, Compositing::AsyncScrollOperationID, Web::CSSPixelPoint destination);- void did_end_snap_scroll(Web::AsyncScrollNodeStableID, Compositing::AsyncScrollOperationID, Optional<Web::CSSPixelPoint> scroll_offset);- void did_retarget_scroll(Web::AsyncScrollNodeStableID, Compositing::AsyncScrollOperationID);- bool is_snap_scroll(Web::AsyncScrollNodeStableID, Compositing::AsyncScrollOperationID) const;- Optional<Web::CSSPixelPoint> unsnapped_destination_for_snap_scroll(Web::AsyncScrollNodeStableID, Compositing::AsyncScrollOperationID) const;-- // Input that scrolls with a gesture reports its phases; the momentum of a flick and the end of a gesture snap- // from what the gesture has done so far.- void note_gesture_phase(Web::ScrollGesturePhase);- void did_scroll_node_plainly(Web::AsyncScrollNodeStableID, Web::ScrollGesturePhase, Web::CSSPixelPoint scroll_offset_before_scroll);-- // https://drafts.csswg.org/css-scroll-snap-1/#scroll-types- // A discrete wheel step is a relative scroll with only an intended direction.- Optional<StepDecision> decide_discrete_step(Compositing::AsyncScrollTree const&, Compositing::ScrollStateSnapshot const&, Compositing::SpatialNodeIndex, Web::CSSPixelPoint delta, Optional<Web::CSSPixelPoint> scroll_in_flight_destination, MonotonicTime now);- // The momentum of a flick is a relative scroll with an intended direction and, once its decay tells where it is- // headed, an intended end position.- Optional<StepDecision> decide_momentum_delta(Compositing::AsyncScrollTree const&, Compositing::ScrollStateSnapshot const&, Compositing::SpatialNodeIndex, Web::CSSPixelPoint delta);- // A scroll key is a command of its own rather than a step of a gesture: while a scroll is in flight it travels on- // from the offset the steps before it asked for, otherwise from the scrolling box itself. An arrow key has only- // an intended direction; a paging key has an intended end position as well.- Optional<StepDecision> decide_key_step(Compositing::AsyncScrollTree const&, Compositing::ScrollStateSnapshot const&, Compositing::SpatialNodeIndex, Web::CSSPixelPoint delta, Compositing::SnapSelectionStrategy::Type, Optional<Web::CSSPixelPoint> scroll_in_flight_destination, MonotonicTime now);- // The end of a gesture snaps each scrolling box it panned to the snap position nearest where it was released,- // and ends the gesture.- Vector<GestureEndSnap> decide_gesture_end(Compositing::AsyncScrollTree const&, Compositing::ScrollStateSnapshot const&);-- // A gesture whose steps this controller chains awaits its next step until its input deadline passes, and ends- // once that happens without one.- Vector<Web::AsyncScrollNodeStableID> boxes_with_gesture_awaiting_input() const;- Optional<MonotonicTime> earliest_gesture_input_deadline() const;- // Returns the boxes whose gesture ended.- Vector<Web::AsyncScrollNodeStableID> end_gestures_whose_input_ran_out(MonotonicTime now);--private:- struct InFlightSnapScroll {- Compositing::AsyncScrollOperationID operation_id;- Web::CSSPixelPoint destination;- };-- // Where the scrolling box rested when the gesture's input started moving it, from which the end of the gesture- // snaps; momentum that traveled over the box must not pass a snap position that always stops.- struct GestureStart {- Web::CSSPixelPoint offset;- bool travels_under_momentum { false };- };-- struct NodeState {- // The offset the gesture's steps have asked for without snapping, which its next step travels from, so that a- // burst of steps advances by the distance they asked for rather than by one snap position each.- Optional<Web::CSSPixelPoint> unsnapped_scroll_destination;- Optional<MonotonicTime> gesture_input_deadline;- // The offset this controller last left the scrolling box at; a box resting anywhere else has been scrolled by- // something else since, which ends the gesture.- Optional<Web::CSSPixelPoint> expected_scroll_offset;- // The snap scroll of this controller's own that the box is scrolling under.- Optional<InFlightSnapScroll> snap_scroll;- Optional<GestureStart> gesture_start;- };-- // Momentum that selects no snap position is scrolled by for the rest of the gesture rather than being asked again- // for each delta it produces.- enum class MomentumSnapPositionSelection : u8 {- NotSelectedYet,- ScrollingToSelectedPosition,- NoPositionSelected,- };-- // A scroll node a snap position can be selected for: one with snap geometry and a current offset.- struct SnapTarget {- Web::AsyncScrollNodeStableID stable_node_id;- Compositing::AsyncSnapContainer const* snap_container;- Web::CSSPixelPoint current_scroll_offset;- };- static Optional<SnapTarget> snap_target_for(Compositing::AsyncScrollTree const&, Compositing::ScrollStateSnapshot const&, Compositing::SpatialNodeIndex);-- NodeState& node_state(Web::AsyncScrollNodeStableID);- Compositing::SnapAxisCandidates const& candidates_for(Web::AsyncScrollNodeStableID, Compositing::AsyncSnapContainer const&);-- void reset_momentum_fling_state();- void end_gesture();-- HashMap<Web::AsyncScrollNodeStableID, NodeState> m_nodes;- HashMap<Web::AsyncScrollNodeStableID, Compositing::SnapAxisCandidates> m_candidates;- MomentumSnapPositionSelection m_momentum_snap_position_selection { MomentumSnapPositionSelection::NotSelectedYet };- Compositing::MomentumFlingEstimator m_momentum_fling_estimator;-};--}diff --git a/Services/Compositor/ScrollbarController.cpp b/Services/Compositor/ScrollbarController.cppdeleted file mode 100644index bf8cf42c61d..00000000000--- a/Services/Compositor/ScrollbarController.cpp+++ /dev/null@@ -1,484 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Math.h>-#include <Compositor/ScrollbarController.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/Scrolling/AsyncScrollTree.h>-#include <LibCompositing/Scrolling/ScrollState.h>--namespace Compositor {--static Gfx::Orientation orientation_for_scrollbar(Compositing::AsyncScrollbar const& scrollbar)-{- return scrollbar.vertical ? Gfx::Orientation::Vertical : Gfx::Orientation::Horizontal;-}--// A scroll node index can be given to another scroller by the next display list, so a scrollbar is recognized by the-// stable id of its scroller wherever both display lists name one.-struct ScrollbarIdentity {- Optional<Web::AsyncScrollNodeStableID> scroller_stable_node_id;- Compositing::SpatialNodeIndex scroll_node_index;- bool vertical { false };-};--static ScrollbarIdentity scrollbar_identity(Compositing::AsyncScrollbar const& scrollbar)-{- return { scrollbar.scroller_stable_node_id, scrollbar.scroll_node_index, scrollbar.vertical };-}--static Optional<ScrollbarIdentity> scrollbar_identity_at(ReadonlySpan<Compositing::AsyncScrollbar> scrollbars, Optional<size_t> scrollbar_index)-{- if (!scrollbar_index.has_value())- return {};- return scrollbar_identity(scrollbars[*scrollbar_index]);-}--static bool scrollbar_has_identity(Compositing::AsyncScrollbar const& scrollbar, ScrollbarIdentity const& identity)-{- if (scrollbar.vertical != identity.vertical)- return false;- if (scrollbar.scroller_stable_node_id.has_value() && identity.scroller_stable_node_id.has_value())- return *scrollbar.scroller_stable_node_id == *identity.scroller_stable_node_id;- return scrollbar.scroll_node_index == identity.scroll_node_index;-}--static Optional<size_t> find_scrollbar_index(ReadonlySpan<Compositing::AsyncScrollbar> scrollbars, ScrollbarIdentity const& identity)-{- for (size_t i = 0; i < scrollbars.size(); ++i) {- if (scrollbar_has_identity(scrollbars[i], identity))- return i;- }- return {};-}--// The rects of a scrollbar the compositor paints are in the viewport's space already.-static Optional<Gfx::FloatPoint> position_in_space_of_scrollbar(Compositing::AsyncScrollbar const& scrollbar, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position, Compositing::AccumulatedVisualContextTree::ClipBehavior clip_behavior)-{- if (scrollbar.is_painted_by_compositor)- return position;- if (!visual_context_tree.context_is_valid(scrollbar.context))- return {};- return visual_context_tree.transform_point_for_hit_test(scrollbar.context, position, scroll_state_snapshot, clip_behavior);-}--static Gfx::IntRect scrollbar_gutter_rect(Compositing::AsyncScrollbar const& scrollbar, bool expanded)-{- return expanded ? scrollbar.expanded_gutter_rect : scrollbar.gutter_rect;-}--static double scrollbar_scroll_size(Compositing::AsyncScrollbar const& scrollbar, bool expanded)-{- return expanded ? scrollbar.expanded_scroll_size : scrollbar.scroll_size;-}--static Gfx::IntRect translated_thumb_rect(Compositing::AsyncScrollbar const& scrollbar, Gfx::FloatPoint scroll_offset, bool expanded)-{- auto orientation = orientation_for_scrollbar(scrollbar);- auto thumb_rect = expanded ? scrollbar.expanded_thumb_rect : scrollbar.thumb_rect;- thumb_rect.translate_primary_offset_for_orientation(orientation, static_cast<int>(scroll_offset.primary_offset_for_orientation(orientation) * scrollbar_scroll_size(scrollbar, expanded)));- return thumb_rect;-}--static Gfx::IntRect translated_thumb_rect(Compositing::AsyncScrollbar const& scrollbar, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, bool expanded)-{- auto thumb_rect = expanded ? scrollbar.expanded_thumb_rect : scrollbar.thumb_rect;- auto scroll_size = scrollbar_scroll_size(scrollbar, expanded);- auto device_offset = scroll_state_snapshot.device_offset_for_index(scrollbar.scroll_node_index);- if (scrollbar.vertical)- thumb_rect.translate_by(0, static_cast<int>(-device_offset.y() * scroll_size));- else- thumb_rect.translate_by(static_cast<int>(-device_offset.x() * scroll_size), 0);- return thumb_rect;-}--static Gfx::IntRect scrollbar_hit_rect(Compositing::AsyncScrollbar const& scrollbar, Gfx::FloatPoint scroll_offset)-{- static constexpr int scrollbar_hit_slop = 4;-- auto rect = translated_thumb_rect(scrollbar, scroll_offset, false).united(translated_thumb_rect(scrollbar, scroll_offset, true));- auto expanded_gutter_rect = scrollbar_gutter_rect(scrollbar, true);- if (!expanded_gutter_rect.is_empty())- rect.unite(expanded_gutter_rect);- rect.inflate(scrollbar_hit_slop, scrollbar_hit_slop);- return rect;-}--void ScrollbarController::clear()-{- m_scrollbars.clear();- m_visibilities.clear();- m_hovered_scrollbar_index.clear();- m_captured_scrollbar_index.clear();- m_thumb_grab_position = 0;- m_last_primary_position_of_captured_drag = 0;-}--void ScrollbarController::set_scrollbars(Vector<Compositing::AsyncScrollbar> const& scrollbars)-{- auto hovered_scrollbar_identity = scrollbar_identity_at(m_scrollbars, m_hovered_scrollbar_index);- auto captured_scrollbar_identity = scrollbar_identity_at(m_scrollbars, m_captured_scrollbar_index);-- Vector<Visibility> visibilities;- visibilities.ensure_capacity(scrollbars.size());- for (auto const& scrollbar : scrollbars) {- auto previous_index = find_scrollbar_index(m_scrollbars, scrollbar_identity(scrollbar));- visibilities.unchecked_append(previous_index.has_value() ? m_visibilities[*previous_index] : Visibility {});- }-- m_scrollbars = scrollbars;- m_visibilities = move(visibilities);- m_hovered_scrollbar_index = hovered_scrollbar_identity.has_value() ? find_scrollbar_index(m_scrollbars, *hovered_scrollbar_identity) : Optional<size_t> {};- m_captured_scrollbar_index = captured_scrollbar_identity.has_value() ? find_scrollbar_index(m_scrollbars, *captured_scrollbar_identity) : Optional<size_t> {};- if (!m_captured_scrollbar_index.has_value())- m_thumb_grab_position = 0;-}--Optional<Web::ScrollbarDraggedByCompositor> ScrollbarController::captured_scrollbar_painted_by_display_list(Web::CompositorContextId context_id) const-{- if (!m_captured_scrollbar_index.has_value())- return {};- auto const& scrollbar = m_scrollbars[*m_captured_scrollbar_index];- if (scrollbar.is_painted_by_compositor || !scrollbar.scroller_stable_node_id.has_value())- return {};- return Web::ScrollbarDraggedByCompositor {- .context_id = context_id,- .scroller_stable_node_id = *scrollbar.scroller_stable_node_id,- };-}--Optional<size_t> ScrollbarController::hit_test_scrollbar_painted_by_compositor(Compositing::AsyncScrollTree const& async_scroll_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position) const-{- for (size_t i = 0; i < m_scrollbars.size(); ++i) {- auto const& scrollbar = m_scrollbars[i];- if (!scrollbar.is_painted_by_compositor)- continue;- auto scroll_offset = async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot);- if (!scroll_offset.has_value())- continue;-- if (scrollbar_hit_rect(scrollbar, *scroll_offset).to_type<float>().contains(position))- return i;- }- return {};-}--// A scrollbar the display list paints takes the pointer inside the rect of the scrollbar as it is presented now, and only-// with nothing that takes pointer input painted over it there. A scrollbar that has faded out takes none, as the main-// thread passes it by.-Optional<size_t> ScrollbarController::hit_test_scrollbar_painted_by_display_list(Compositing::AsyncScrollTree const& async_scroll_tree, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position) const-{- for (size_t i = m_scrollbars.size(); i-- > 0;) {- auto const& scrollbar = m_scrollbars[i];- if (scrollbar.is_painted_by_compositor || !scrollbar.scroller_stable_node_id.has_value() || !is_shown(i))- continue;- if (!async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot).has_value())- continue;-- auto position_in_scrollbar_space = position_in_space_of_scrollbar(scrollbar, visual_context_tree, scroll_state_snapshot, position, Compositing::AccumulatedVisualContextTree::ClipBehavior::Respect);- if (!position_in_scrollbar_space.has_value())- continue;- auto const& presented_scrollbar_rect = expansion(i) > 0 ? scrollbar.expanded_gutter_rect : scrollbar.track_rect;- if (!presented_scrollbar_rect.to_type<float>().contains(*position_in_scrollbar_space))- continue;-- if (async_scroll_tree.is_covered_by_hit_test_target_painted_after(scrollbar.paint_order_index, visual_context_tree, position))- return {};- return i;- }- return {};-}--Optional<ScrollbarController::Drag> ScrollbarController::begin_drag(Compositing::AsyncScrollTree const& async_scroll_tree, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position)-{- auto scrollbar_index = hit_test_scrollbar_painted_by_compositor(async_scroll_tree, scroll_state_snapshot, position);- if (!scrollbar_index.has_value())- scrollbar_index = hit_test_scrollbar_painted_by_display_list(async_scroll_tree, visual_context_tree, scroll_state_snapshot, position);- // A scrollbar that has faded out takes no press, as in Chromium.- if (!scrollbar_index.has_value() || opacity(*scrollbar_index) <= 0)- return {};-- auto const& scrollbar = m_scrollbars[*scrollbar_index];- auto scroll_offset = async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot);- VERIFY(scroll_offset.has_value());- auto position_in_scrollbar_space = position_in_space_of_scrollbar(scrollbar, visual_context_tree, scroll_state_snapshot, position, Compositing::AccumulatedVisualContextTree::ClipBehavior::Respect);- VERIFY(position_in_scrollbar_space.has_value());-- auto orientation = orientation_for_scrollbar(scrollbar);-- // A successful press captures and expands the scrollbar before its drag delta is applied.- static constexpr auto expanded = true;- auto thumb_rect = translated_thumb_rect(scrollbar, *scroll_offset, expanded);- auto thumb_hit_rect = thumb_rect.to_type<float>();-- auto primary_position = position_in_scrollbar_space->primary_offset_for_orientation(orientation);- auto position_is_along_thumb = orientation == Gfx::Orientation::Vertical- ? thumb_hit_rect.contains_vertically(primary_position)- : thumb_hit_rect.contains_horizontally(primary_position);-- float thumb_grab_position = 0;- if (position_is_along_thumb) {- thumb_grab_position = primary_position - static_cast<float>(thumb_rect.primary_offset_for_orientation(orientation));- } else {- auto gutter_rect = scrollbar_gutter_rect(scrollbar, true);- auto thumb_size = static_cast<float>(thumb_rect.primary_size_for_orientation(orientation));- auto gutter_start = static_cast<float>(gutter_rect.primary_offset_for_orientation(orientation));- auto gutter_size = static_cast<float>(gutter_rect.primary_size_for_orientation(orientation));- auto offset_relative_to_gutter = primary_position - gutter_start;- thumb_grab_position = max(min(offset_relative_to_gutter, thumb_size / 2), offset_relative_to_gutter - gutter_size + thumb_size);- }-- m_captured_scrollbar_index = *scrollbar_index;- m_hovered_scrollbar_index = *scrollbar_index;- m_thumb_grab_position = thumb_grab_position;- m_last_primary_position_of_captured_drag = primary_position;- return Drag { *scrollbar_index, primary_position, thumb_grab_position, !position_is_along_thumb };-}--// A drag usually leaves the clip of its scrollbar, and the spaces above the scrollbar may move while it lasts, so the-// position is mapped anew for every event without regard to clips. A position that cannot be mapped moves nothing.-float ScrollbarController::primary_position_of_captured_drag(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position)-{- auto const& scrollbar = m_scrollbars[*m_captured_scrollbar_index];- auto position_in_scrollbar_space = position_in_space_of_scrollbar(scrollbar, visual_context_tree, scroll_state_snapshot, position, Compositing::AccumulatedVisualContextTree::ClipBehavior::Ignore);- if (position_in_scrollbar_space.has_value())- m_last_primary_position_of_captured_drag = position_in_scrollbar_space->primary_offset_for_orientation(orientation_for_scrollbar(scrollbar));- return m_last_primary_position_of_captured_drag;-}--Optional<ScrollbarController::Drag> ScrollbarController::captured_drag(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position)-{- if (!m_captured_scrollbar_index.has_value())- return {};- auto primary_position = primary_position_of_captured_drag(visual_context_tree, scroll_state_snapshot, position);- return Drag { *m_captured_scrollbar_index, primary_position, m_thumb_grab_position };-}--Optional<ScrollbarController::Drag> ScrollbarController::release_captured_drag(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position)-{- if (!m_captured_scrollbar_index.has_value())- return {};- auto scrollbar_index = *m_captured_scrollbar_index;- auto thumb_grab_position = m_thumb_grab_position;- auto primary_position = primary_position_of_captured_drag(visual_context_tree, scroll_state_snapshot, position);- m_captured_scrollbar_index.clear();- m_thumb_grab_position = 0;- return Drag { scrollbar_index, primary_position, thumb_grab_position };-}--bool ScrollbarController::set_hovered_scrollbar(Optional<size_t> scrollbar_index)-{- if (m_hovered_scrollbar_index == scrollbar_index)- return false;-- m_hovered_scrollbar_index = scrollbar_index;- return true;-}--Optional<ScrollbarController::ScrollOffset> ScrollbarController::scroll_offset_for_drag(Compositing::AsyncScrollTree const& async_scroll_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Drag const& drag) const-{- auto const& scrollbar = m_scrollbars[drag.scrollbar_index];- auto expanded = is_expanded(drag.scrollbar_index);- auto scroll_size = scrollbar_scroll_size(scrollbar, expanded);- if (scroll_size == 0)- return {};-- auto current_scroll_offset = async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot);- if (!current_scroll_offset.has_value())- return {};-- auto orientation = orientation_for_scrollbar(scrollbar);- auto thumb_rect = expanded ? scrollbar.expanded_thumb_rect : scrollbar.thumb_rect;- auto zero_offset_thumb_position = static_cast<float>(thumb_rect.primary_offset_for_orientation(orientation));- auto min_thumb_position = zero_offset_thumb_position + scrollbar.min_scroll_offset * static_cast<float>(scroll_size);- auto max_thumb_position = zero_offset_thumb_position + scrollbar.max_scroll_offset * static_cast<float>(scroll_size);- auto target_thumb_position = AK::clamp(drag.primary_position - drag.thumb_grab_position, min_thumb_position, max_thumb_position);- auto target_scroll_offset = (target_thumb_position - zero_offset_thumb_position) / static_cast<float>(scroll_size);- // A thumb at either end of its track scrolls exactly to that end, whatever rounding the division above suffers.- if (target_thumb_position == min_thumb_position)- target_scroll_offset = scrollbar.min_scroll_offset;- else if (target_thumb_position == max_thumb_position)- target_scroll_offset = scrollbar.max_scroll_offset;-- auto scroll_offset = *current_scroll_offset;- scroll_offset.set_primary_offset_for_orientation(orientation, target_scroll_offset);- return ScrollOffset { scrollbar.scroll_node_index, scroll_offset };-}--int ScrollbarController::paging_direction(size_t scrollbar_index, float primary_position, Gfx::FloatPoint scroll_offset) const-{- auto const& scrollbar = m_scrollbars[scrollbar_index];- auto orientation = orientation_for_scrollbar(scrollbar);- auto thumb_rect = translated_thumb_rect(scrollbar, scroll_offset, is_expanded(scrollbar_index));- if (primary_position < static_cast<float>(thumb_rect.primary_offset_for_orientation(orientation)))- return -1;- if (primary_position >= static_cast<float>(thumb_rect.primary_offset_for_orientation(orientation) + thumb_rect.primary_size_for_orientation(orientation)))- return 1;- return 0;-}--void ScrollbarController::update_visibility(Compositing::ScrollStateSnapshot const& scroll_state_snapshot, MonotonicTime now)-{- for (size_t i = 0; i < m_scrollbars.size(); ++i) {- auto& visibility = m_visibilities[i];- auto const& scrollbar = m_scrollbars[i];- auto scroll_offset = scroll_state_snapshot.device_offset_for_index(scrollbar.scroll_node_index);- auto scrolled = visibility.scroll_offset.has_value() && *visibility.scroll_offset != scroll_offset;- visibility.scroll_offset = scroll_offset;-- auto was_held_shown = visibility.is_held_shown;- // Hovering a hidden scrollbar does not show it. Only a scroll does.- visibility.is_held_shown = is_expanded(i) && (scrolled || visibility.fade.opacity() > 0);- if (visibility.is_held_shown) {- visibility.fade.jump_to(1);- visibility.fade_out_time.clear();- visibility.expansion.fade_to(1, now);- continue;- }- if (scrolled)- visibility.fade.jump_to(1);- if (scrolled || was_held_shown)- visibility.fade_out_time = now + shown_duration_after_activity;- }-}--Optional<MonotonicTime> ScrollbarController::next_fade_out_time() const-{- Optional<MonotonicTime> next_fade_out_time;- for (auto const& visibility : m_visibilities) {- if (visibility.fade_out_time.has_value() && (!next_fade_out_time.has_value() || *visibility.fade_out_time < *next_fade_out_time))- next_fade_out_time = visibility.fade_out_time;- }- return next_fade_out_time;-}--Vector<Web::OverlayScrollbarVisibility> ScrollbarController::take_visibility_changes()-{- Vector<Web::OverlayScrollbarVisibility> changes;- for (size_t i = 0; i < m_scrollbars.size(); ++i) {- auto const& scrollbar = m_scrollbars[i];- auto& visibility = m_visibilities[i];- auto hidden = opacity(i) <= 0;- if (!scrollbar.scroller_stable_node_id.has_value() || hidden == visibility.reported_hidden)- continue;- visibility.reported_hidden = hidden;- changes.append({ .scroller_stable_node_id = *scrollbar.scroller_stable_node_id, .vertical = scrollbar.vertical, .hidden = hidden });- }- return changes;-}--bool ScrollbarController::fades_need_frame(MonotonicTime now) const-{- for (auto const& visibility : m_visibilities) {- if (visibility.fade.is_fading() || visibility.expansion.is_fading() || (visibility.fade_out_time.has_value() && *visibility.fade_out_time <= now))- return true;- }- return false;-}--Gfx::IntRect ScrollbarController::advance_fades(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, MonotonicTime frame_time)-{- Gfx::IntRect damage_rect;- for (size_t i = 0; i < m_scrollbars.size(); ++i) {- auto& visibility = m_visibilities[i];- if (visibility.fade_out_time.has_value() && *visibility.fade_out_time <= frame_time) {- visibility.fade_out_time.clear();- visibility.fade.fade_to(0, frame_time);- }- auto changed = visibility.fade.advance_to(frame_time);- // A scrollbar that has faded out is thin again when it is next shown.- if (visibility.fade.opacity() <= 0)- visibility.expansion.jump_to(0);- changed |= visibility.expansion.advance_to(frame_time);- if (!changed)- continue;-- if (auto rect = rect_in_viewport(i, visual_context_tree, scroll_state_snapshot); rect.has_value())- damage_rect.unite(*rect);- }- return damage_rect;-}--Optional<Gfx::IntRect> ScrollbarController::rect_in_viewport(size_t scrollbar_index, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot) const-{- auto const& scrollbar = m_scrollbars[scrollbar_index];- auto rect = scrollbar.gutter_rect.united(scrollbar.track_rect).united(scrollbar.expanded_gutter_rect);- if (scrollbar.is_painted_by_compositor)- return rect.inflated(2, 2);- if (!visual_context_tree.context_is_valid(scrollbar.context))- return {};- auto rect_in_viewport = visual_context_tree.transform_rect_to_viewport(scrollbar.context.spatial, rect.to_type<float>(), scroll_state_snapshot);- if (!isfinite(rect_in_viewport.x()) || !isfinite(rect_in_viewport.y()) || !isfinite(rect_in_viewport.width()) || !isfinite(rect_in_viewport.height()))- return {};- return Gfx::enclosing_int_rect(rect_in_viewport).inflated(2, 2);-}--static Gfx::FloatRect interpolated_rect(Gfx::IntRect const& from, Gfx::IntRect const& to, float progress)-{- auto interpolate = [progress](int from, int to) {- return static_cast<float>(from) + static_cast<float>(to - from) * progress;- };- return {- interpolate(from.x(), to.x()),- interpolate(from.y(), to.y()),- interpolate(from.width(), to.width()),- interpolate(from.height(), to.height()),- };-}--Vector<ScrollbarOfFrame> ScrollbarController::scrollbars_of_frame(Compositing::ScrollStateSnapshot const& scroll_state_snapshot) const-{- Vector<ScrollbarOfFrame> scrollbars_of_frame;- scrollbars_of_frame.ensure_capacity(m_scrollbars.size());- for (size_t i = 0; i < m_scrollbars.size(); ++i) {- auto const& scrollbar = m_scrollbars[i];- auto progress = expansion(i);-- auto thin_thumb_rect = thumb_rect_kept_inside_track(translated_thumb_rect(scrollbar, scroll_state_snapshot, false), scrollbar.track_rect, scrollbar.vertical);- auto expanded_thumb_rect = thumb_rect_kept_inside_track(translated_thumb_rect(scrollbar, scroll_state_snapshot, true), scrollbar.expanded_gutter_rect, scrollbar.vertical);- // An empty thumb has nothing to grow from or to.- if (thin_thumb_rect.is_empty())- thin_thumb_rect = expanded_thumb_rect;- if (expanded_thumb_rect.is_empty())- expanded_thumb_rect = thin_thumb_rect;-- scrollbars_of_frame.unchecked_append({- .scroll_node_index = scrollbar.scroll_node_index,- .vertical = scrollbar.vertical,- .is_painted_by_compositor = scrollbar.is_painted_by_compositor,- .gutter_rect = interpolated_rect(scrollbar.track_rect, scrollbar.expanded_gutter_rect, progress),- .thumb_rect = interpolated_rect(thin_thumb_rect, expanded_thumb_rect, progress),- .expansion = progress,- .opacity = opacity(i),- .thumb_color = scrollbar.thumb_color,- .thumb_outline_color = scrollbar.thumb_outline_color,- .track_color = scrollbar.track_color,- .thin_and_expanded_gutter_rect = scrollbar.gutter_rect.united(scrollbar.expanded_gutter_rect),- });- }- return scrollbars_of_frame;-}--bool ScrollbarController::is_expanded(size_t scrollbar_index) const-{- return m_hovered_scrollbar_index == scrollbar_index || m_captured_scrollbar_index == scrollbar_index;-}--float ScrollbarController::opacity(size_t scrollbar_index) const-{- if (s_scrollbars_always_shown)- return 1;- return m_visibilities[scrollbar_index].fade.opacity();-}--float ScrollbarController::expansion(size_t scrollbar_index) const-{- if (s_scrollbars_always_shown)- return is_expanded(scrollbar_index) ? 1 : 0;- return m_visibilities[scrollbar_index].expansion.opacity();-}--}diff --git a/Services/Compositor/ScrollbarController.h b/Services/Compositor/ScrollbarController.hdeleted file mode 100644index 00317d27d6a..00000000000--- a/Services/Compositor/ScrollbarController.h+++ /dev/null@@ -1,129 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Time.h>-#include <AK/Vector.h>-#include <Compositor/Forward.h>-#include <Compositor/FrameInputs.h>-#include <LibCompositing/OverlayFade.h>-#include <LibCompositing/Scrolling/AsyncScrollingState.h>-#include <LibGfx/Color.h>-#include <LibGfx/Forward.h>-#include <LibGfx/Point.h>-#include <LibGfx/Rect.h>--namespace Compositing {--class AsyncScrollTree;--}--namespace Compositing {--class AccumulatedVisualContextTree;-class ScrollStateSnapshot;--}--namespace Compositor {--class ScrollbarController {-public:- struct Drag {- size_t scrollbar_index { 0 };- float primary_position { 0 };- float thumb_grab_position { 0 };- // Whether this is the press that began the drag, beside the thumb rather than on it.- bool is_press_beside_thumb { false };- };-- struct ScrollOffset {- Compositing::SpatialNodeIndex scroll_node_index;- Gfx::FloatPoint scroll_offset;- };-- // Overlay scrollbars are hidden until their scroller scrolls. A scrollbar stays shown for this long after its- // scroller last scrolled or the pointer left it, and then fades out.- static constexpr auto shown_duration_after_activity = AK::Duration::from_milliseconds(1000);-- // Tests see every scrollbar at all times, as when it is shown depends on the time.- static void show_scrollbars_always_for_testing() { s_scrollbars_always_shown = true; }-- void clear();- void set_scrollbars(Vector<Compositing::AsyncScrollbar> const&);-- // Shows each scrollbar whose scroller scrolled since the last call, keeps a shown scrollbar that is hovered or- // dragged shown, and starts the wait before a scrollbar that is no longer hovered or dragged fades out. A hovered or- // dragged scrollbar that is shown grows to its expanded geometry, and keeps it until it has faded out.- void update_visibility(Compositing::ScrollStateSnapshot const&, MonotonicTime now);- // When the next scrollbar starts to fade out.- Optional<MonotonicTime> next_fade_out_time() const;- // The scrollbars that faded out or were shown again since the last call. The main thread hit tests the scrollbars- // too, and passes by the ones that have faded out.- Vector<Web::OverlayScrollbarVisibility> take_visibility_changes();- bool fades_need_frame(MonotonicTime now) const;- // Returns the rect in the viewport of the scrollbars whose opacity or geometry changed.- Gfx::IntRect advance_fades(Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&, MonotonicTime frame_time);- Vector<ScrollbarOfFrame> scrollbars_of_frame(Compositing::ScrollStateSnapshot const&) const;-- bool is_empty() const { return m_scrollbars.is_empty(); }- Vector<Compositing::AsyncScrollbar> const& scrollbars() const { return m_scrollbars; }- bool has_captured_scrollbar() const { return m_captured_scrollbar_index.has_value(); }- Optional<size_t> captured_scrollbar_index() const { return m_captured_scrollbar_index; }- // Which way a press beside the thumb pages: -1 or 1 toward the pointer from where the thumb is at the given scroll- // offset, or 0 when the thumb is under the pointer.- int paging_direction(size_t scrollbar_index, float primary_position, Gfx::FloatPoint scroll_offset) const;- // The main thread still takes the mouse events of a drag that holds a scrollbar the display list paints. The- // context is the one this controller belongs to.- Optional<Web::ScrollbarDraggedByCompositor> captured_scrollbar_painted_by_display_list(Web::CompositorContextId) const;-- Optional<size_t> hit_test_scrollbar_painted_by_compositor(Compositing::AsyncScrollTree const&, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint position) const;- // A scrollbar the display list paints takes the pointer where it is presented, unless something that takes pointer- // input is painted over it there.- Optional<size_t> hit_test_scrollbar_painted_by_display_list(Compositing::AsyncScrollTree const&, Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint position) const;- // Whether the scrollbar is shown, rather than hidden until its scroller next scrolls.- bool is_shown(size_t scrollbar_index) const { return opacity(scrollbar_index) > 0; }- Optional<Drag> begin_drag(Compositing::AsyncScrollTree const&, Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint position);- Optional<Drag> captured_drag(Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint position);- Optional<Drag> release_captured_drag(Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint position);- bool set_hovered_scrollbar(Optional<size_t>);-- Optional<ScrollOffset> scroll_offset_for_drag(Compositing::AsyncScrollTree const&, Compositing::ScrollStateSnapshot const&, Drag const&) const;--private:- struct Visibility {- Compositing::OverlayFade fade;- // The scroll offset of the scroller as of the last update, which a scroll changes.- Optional<Gfx::FloatPoint> scroll_offset;- bool is_held_shown { false };- Optional<MonotonicTime> fade_out_time;- // How far the scrollbar has grown from its thin geometry to its expanded one.- Compositing::OverlayFade expansion;- // Whether the main thread was last told that the scrollbar has faded out.- bool reported_hidden { false };- };-- bool is_expanded(size_t scrollbar_index) const;- float opacity(size_t scrollbar_index) const;- float expansion(size_t scrollbar_index) const;- Optional<Gfx::IntRect> rect_in_viewport(size_t scrollbar_index, Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&) const;- float primary_position_of_captured_drag(Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint position);-- Vector<Compositing::AsyncScrollbar> m_scrollbars;- // One for each scrollbar, in the same order.- Vector<Visibility> m_visibilities;- Optional<size_t> m_hovered_scrollbar_index;- Optional<size_t> m_captured_scrollbar_index;- float m_thumb_grab_position { 0 };- float m_last_primary_position_of_captured_drag { 0 };-- static inline bool s_scrollbars_always_shown { false };-};--}diff --git a/Services/Compositor/WheelGestureRouting.cpp b/Services/Compositor/WheelGestureRouting.cppdeleted file mode 100644index 06c8c2daa40..00000000000--- a/Services/Compositor/WheelGestureRouting.cpp+++ /dev/null@@ -1,285 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/GenericShorthands.h>-#include <Compositor/WheelGestureRouting.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/Scrolling/AsyncScrollTree.h>--namespace Compositor {--static u64 allocate_wheel_gesture_id()-{- static u64 last_wheel_gesture_id = 0;- return ++last_wheel_gesture_id;-}--// Every wheel step a context notes gets the next number, whether the UI sent it or the main thread made it, so the-// numbers order all of them as the compositor first saw them.-static u64 allocate_wheel_step_number()-{- static u64 last_wheel_step_number = 0;- return ++last_wheel_step_number;-}--static float position_slop_in_device_pixels(Compositing::AsyncScrollTree const& async_scroll_tree)-{- return Compositing::wheel_gesture_position_slop_in_css_pixels * static_cast<float>(async_scroll_tree.device_pixels_per_css_pixel());-}--void WheelGestureRouting::did_install_scrolling_state(Compositing::AsyncScrollingState const& async_scrolling_state)-{- m_admission = Compositing::wheel_routing_admission_for(async_scrolling_state, m_wheel_event_listener_state_generation);- m_wheel_event_listener_state_generation = max(m_wheel_event_listener_state_generation, async_scrolling_state.wheel_event_listener_state_generation);-}--void WheelGestureRouting::invalidate_wheel_event_listener_state(u64 generation)-{- m_wheel_event_listener_state_generation = max(m_wheel_event_listener_state_generation, generation);- m_admission = Compositing::WheelRoutingAdmission::StaleWheelEventListeners;-}--bool WheelGestureRouting::admits_async_pinch() const-{- // Pinch zoom scales the visual viewport, which a page whose viewport cannot be scrolled has too.- return first_is_one_of(m_admission, Compositing::WheelRoutingAdmission::Accepted, Compositing::WheelRoutingAdmission::NoScrollNode);-}--WheelGestureRouting::NotedWheelEvent WheelGestureRouting::note_wheel_event(Web::MouseEvent const& event, Gfx::FloatPoint position, Compositing::AsyncScrollTree const& async_scroll_tree, MonotonicTime now)-{- auto phase = event.scroll_gesture_phase;- auto step_number = allocate_wheel_step_number();- if (phase == Web::ScrollGesturePhase::Ongoing)- m_newest_step_numbers.ongoing = step_number;- else if (phase == Web::ScrollGesturePhase::Momentum)- m_newest_step_numbers.momentum = step_number;- else if (phase == Web::ScrollGesturePhase::Ended)- m_newest_step_numbers.ended = step_number;-- bool starts_gesture = !m_gesture.has_value() || !m_gesture->identity.is_continued_by(position, phase, event.modifiers, now, position_slop_in_device_pixels(async_scroll_tree), m_touchpad_gesture_end);- if (starts_gesture) {- m_gesture = Gesture {- .id = allocate_wheel_gesture_id(),- .identity = Compositing::WheelGestureIdentity::started_by(position, phase, event.modifiers, now),- };- m_gesture_had_wheel_event_with_delta = false;- m_latch.clear();- } else {- m_gesture->identity.advance_to(phase, now);- }- bool is_first_wheel_event_with_delta = !m_gesture_had_wheel_event_with_delta && (event.wheel_delta_x != 0 || event.wheel_delta_y != 0);- if (is_first_wheel_event_with_delta)- m_gesture_had_wheel_event_with_delta = true;- return { .starts_gesture = starts_gesture, .is_first_wheel_event_with_delta = is_first_wheel_event_with_delta, .step_number = step_number };-}--Optional<u64> WheelGestureRouting::gesture_id() const-{- if (!m_gesture.has_value())- return {};- return m_gesture->id;-}--Optional<Web::CompositorContextId> WheelGestureRouting::wheel_event_listener_context() const-{- if (!m_gesture.has_value())- return {};- return m_gesture->wheel_event_listener_context;-}--void WheelGestureRouting::set_wheel_event_listener_context(Web::CompositorContextId context_id)-{- if (m_gesture.has_value())- m_gesture->wheel_event_listener_context = context_id;-}--void WheelGestureRouting::note_delta_left_to_the_page(Gfx::FloatPoint delta_in_css_pixels)-{- if (m_gesture.has_value())- m_gesture->delta_left_to_the_page += { AK::abs(delta_in_css_pixels.x()), AK::abs(delta_in_css_pixels.y()) };-}--bool WheelGestureRouting::take_delta_left_to_the_page(Gfx::FloatPoint delta_in_css_pixels)-{- if (!m_gesture.has_value())- return false;- // The page sends back the deltas it was given, which may have been summed up on the way.- constexpr float rounding_slack = 0.01f;- auto& delta_left = m_gesture->delta_left_to_the_page;- Gfx::FloatPoint step { AK::abs(delta_in_css_pixels.x()), AK::abs(delta_in_css_pixels.y()) };- if (step.x() > delta_left.x() + rounding_slack || step.y() > delta_left.y() + rounding_slack)- return false;- delta_left = { max(0.0f, delta_left.x() - step.x()), max(0.0f, delta_left.y() - step.y()) };- return true;-}--void WheelGestureRouting::forget_gesture()-{- m_gesture.clear();- m_gesture_had_wheel_event_with_delta = false;- m_latch.clear();-}--// Whether this context noted a later wheel step that this step cannot come before in one gesture, which makes it a step-// of a gesture this context has already ended or moved past.-bool WheelGestureRouting::step_was_overtaken(Web::ScrollGesturePhase phase, u64 step_number) const-{- auto const& newest = m_newest_step_numbers;- switch (phase) {- case Web::ScrollGesturePhase::None:- return false;- case Web::ScrollGesturePhase::Ongoing:- // The fingers lifted after this step.- return newest.momentum > step_number || newest.ended > step_number;- case Web::ScrollGesturePhase::Momentum:- // The momentum ended, or the fingers touched down again, after this step.- return newest.ended > step_number || newest.ongoing > step_number;- case Web::ScrollGesturePhase::Ended:- // Another gesture started after this end.- return newest.ongoing > step_number;- }- VERIFY_NOT_REACHED();-}--WheelGestureRouting::ResolvedLatch WheelGestureRouting::resolve_latch(Compositing::AsyncScrollTree const& async_scroll_tree, Compositing::AccumulatedVisualContextTree const& current_visual_context_tree, Web::ScrollGesturePhase scroll_gesture_phase, Optional<u64> gesture_id)-{- if (!m_latch.has_value())- return {};- if (m_latch->gesture_id != gesture_id) {- m_latch.clear();- return {};- }- if (m_latch->nested_context_id.has_value() || !m_latch->stable_node_id.has_value()) {- m_latch->last_scroll_gesture_phase = scroll_gesture_phase;- return { .nested_context_id = m_latch->nested_context_id, .keeps_steps = !m_latch->nested_context_id.has_value() };- }- auto scroll_node_index = async_scroll_tree.scroll_node_index_for_stable_id(*m_latch->stable_node_id);- if (!scroll_node_index.has_value()) {- m_latch.clear();- return {};- }- // The hit test a latched step skips would refuse a tree the wheel hit-test targets were not built for.- if (!async_scroll_tree.has_wheel_hit_test_targets_for(current_visual_context_tree))- return {};- m_latch->last_scroll_gesture_phase = scroll_gesture_phase;- return { .scroll_node_index = scroll_node_index };-}--Optional<Web::AsyncScrollNodeStableID> WheelGestureRouting::latched_scroller() const-{- if (!m_latch.has_value())- return {};- return m_latch->stable_node_id;-}--bool WheelGestureRouting::gesture_lasts_until_fingers_lift() const-{- return m_touchpad_gesture_end == Compositing::TouchpadGestureEnd::WhenFingersLift && m_gesture.has_value() && m_gesture->identity.is_held_by_fingers();-}--Optional<Web::AsyncScrollNodeStableID> WheelGestureRouting::scroller_held_by_fingers() const-{- if (m_touchpad_gesture_end != Compositing::TouchpadGestureEnd::WhenFingersLift || !m_latch.has_value())- return {};- // The gesture here has every event; a context nested in another has only the steps handed to it, on its latch.- bool held_by_fingers = m_gesture.has_value() ? m_gesture->identity.is_held_by_fingers() : m_latch->last_scroll_gesture_phase == Web::ScrollGesturePhase::Ongoing;- if (!held_by_fingers)- return {};- return m_latch->stable_node_id;-}--void WheelGestureRouting::latch(Web::AsyncScrollNodeStableID stable_node_id, Web::ScrollGesturePhase scroll_gesture_phase, Optional<u64> gesture_id)-{- m_latch = Latch {- .gesture_id = gesture_id,- .stable_node_id = stable_node_id,- .last_scroll_gesture_phase = scroll_gesture_phase,- };-}--void WheelGestureRouting::latch_to_nested_context(Web::CompositorContextId nested_context_id, Optional<Web::AsyncScrollNodeStableID> scroller, Web::ScrollGesturePhase scroll_gesture_phase, Optional<u64> gesture_id)-{- m_latch = Latch {- .gesture_id = gesture_id,- .stable_node_id = scroller,- .last_scroll_gesture_phase = scroll_gesture_phase,- .nested_context_id = nested_context_id,- };-}--void WheelGestureRouting::latch_keeping_steps(Web::ScrollGesturePhase scroll_gesture_phase, Optional<u64> gesture_id)-{- m_latch = Latch {- .gesture_id = gesture_id,- .stable_node_id = {},- .last_scroll_gesture_phase = scroll_gesture_phase,- };-}--void WheelGestureRouting::relatch_to(Web::AsyncScrollNodeStableID stable_node_id)-{- if (m_latch.has_value() && m_latch->stable_node_id.has_value() && !m_latch->nested_context_id.has_value())- m_latch->stable_node_id = stable_node_id;-}--Optional<Web::CompositorContextId> WheelGestureRouting::nested_context_of_latch() const-{- if (!m_latch.has_value())- return {};- return m_latch->nested_context_id;-}--void WheelGestureRouting::clear_latch_of_gesture(u64 gesture_id)-{- if (has_latch_for_gesture(gesture_id))- m_latch.clear();-}--void WheelGestureRouting::note_page_let_gesture_through(u64 gesture_id)-{- m_gesture_the_page_let_through = GestureThePageLetThrough {- .gesture_id = gesture_id,- .wheel_event_listener_state_generation = m_wheel_event_listener_state_generation,- };-}--void WheelGestureRouting::forget_page_let_gesture_through(u64 gesture_id)-{- if (m_gesture_the_page_let_through.has_value() && m_gesture_the_page_let_through->gesture_id == gesture_id)- m_gesture_the_page_let_through.clear();-}--bool WheelGestureRouting::page_let_gesture_through(Optional<u64> gesture_id) const-{- return gesture_id.has_value()- && m_gesture_the_page_let_through.has_value()- && m_gesture_the_page_let_through->gesture_id == *gesture_id- && m_gesture_the_page_let_through->wheel_event_listener_state_generation == m_wheel_event_listener_state_generation;-}--Optional<Web::InputRoutingDecision> WheelGestureRouting::reason_to_hold_latched_steps_back(Optional<u64> gesture_id) const-{- if (page_let_gesture_through(gesture_id))- return {};- // Blocking listeners over all of the viewport hold every step back, and so do listeners that a context without a- // current display list cannot place.- if (first_is_one_of(m_admission, Compositing::WheelRoutingAdmission::Accepted, Compositing::WheelRoutingAdmission::NoScrollNode))- return {};- return Compositing::input_routing_decision_for_wheel_step_not_admitted_by(m_admission);-}--bool WheelGestureRouting::momentum_of_latched_gesture_can_spring_scroller_back() const-{- return m_latch.has_value() && !m_latch->momentum_has_sprung_the_scroller_back;-}--void WheelGestureRouting::set_momentum_of_latched_gesture_has_sprung_scroller_back(bool has_sprung_back)-{- if (m_latch.has_value())- m_latch->momentum_has_sprung_the_scroller_back = has_sprung_back;-}--}diff --git a/Services/Compositor/WheelGestureRouting.h b/Services/Compositor/WheelGestureRouting.hdeleted file mode 100644index d8d7fee5748..00000000000--- a/Services/Compositor/WheelGestureRouting.h+++ /dev/null@@ -1,146 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Time.h>-#include <LibCompositing/Forward.h>-#include <LibCompositing/Scrolling/AsyncScrollingState.h>-#include <LibCompositing/Scrolling/WheelGestureIdentity.h>-#include <LibGfx/Point.h>-#include <LibWebCommon/Page/CompositorContextId.h>-#include <LibWebCommon/Page/InputEvent.h>--namespace Compositing {--class AsyncScrollTree;--}--namespace Compositor {--class WheelGestureRouting {-public:- void did_install_scrolling_state(Compositing::AsyncScrollingState const&);- void invalidate_wheel_event_listener_state(u64 generation);- Compositing::WheelRoutingAdmission admission() const { return m_admission; }- bool admits_async_wheel() const { return m_admission == Compositing::WheelRoutingAdmission::Accepted; }- bool admits_async_pinch() const;-- struct NotedWheelEvent {- // The event starts another gesture than the one before it, which lets go of the latch.- bool starts_gesture { false };- // The event is the first step of its gesture that moves anything. A touchpad gesture can start with a step that- // has no delta.- bool is_first_wheel_event_with_delta { false };- u64 step_number { 0 };- };- // Every wheel event is noted as this context first sees it: from the UI, or from the main thread for one the UI did- // not send.- NotedWheelEvent note_wheel_event(Web::MouseEvent const&, Gfx::FloatPoint position, Compositing::AsyncScrollTree const&, MonotonicTime now);- // The id of the gesture of the wheel events this context notes. No gesture of any context in the process has the- // same id, so a context nested in another one can tell the gestures of the containing context from its own.- Optional<u64> gesture_id() const;- // The context whose page dispatches the wheel events of the gesture: the innermost one under the pointer as the- // gesture started, which may be nested in this one. Empty for this context.- Optional<Web::CompositorContextId> wheel_event_listener_context() const;- void set_wheel_event_listener_context(Web::CompositorContextId);- // The UI's input of the gesture that this context left to the page. It bounds what the page of another process may- // scroll here, and in the contexts nested here, for the gesture.- void note_delta_left_to_the_page(Gfx::FloatPoint delta_in_css_pixels);- bool take_delta_left_to_the_page(Gfx::FloatPoint delta_in_css_pixels);- bool step_was_overtaken(Web::ScrollGesturePhase, u64 step_number) const;-- bool has_latch() const { return m_latch.has_value(); }- bool has_latch_for_gesture(Optional<u64> gesture_id) const { return m_latch.has_value() && m_latch->gesture_id == gesture_id; }- Optional<Web::CompositorContextId> nested_context_of_latch() const;- Optional<Web::AsyncScrollNodeStableID> latched_scroller() const;- void set_touchpad_gesture_end(Compositing::TouchpadGestureEnd touchpad_gesture_end) { m_touchpad_gesture_end = touchpad_gesture_end; }- // Whether the fingers of the gesture are on the touchpad, where the gesture lasts until they lift.- bool gesture_lasts_until_fingers_lift() const;- // The scroller of such a gesture, or of one a containing context hands the steps of to this one.- Optional<Web::AsyncScrollNodeStableID> scroller_held_by_fingers() const;- // What a gesture is latched to: a scroller in the current scroll tree, a context nested in this one that latched the- // gesture to a scroller of its own, or nothing that scrolls, when this context keeps the steps from the document- // around it.- struct ResolvedLatch {- Optional<Compositing::SpatialNodeIndex> scroll_node_index {};- Optional<Web::CompositorContextId> nested_context_id {};- bool keeps_steps { false };- };- // The latch of the gesture a step continues, advanced to the step's phase. A latch whose scroller the current- // display list no longer has, or that was taken for another gesture than the step's, is dropped here.- ResolvedLatch resolve_latch(Compositing::AsyncScrollTree const&, Compositing::AccumulatedVisualContextTree const& current_visual_context_tree, Web::ScrollGesturePhase, Optional<u64> gesture_id);- void latch(Web::AsyncScrollNodeStableID, Web::ScrollGesturePhase, Optional<u64> gesture_id);- void latch_to_nested_context(Web::CompositorContextId, Optional<Web::AsyncScrollNodeStableID> scroller, Web::ScrollGesturePhase, Optional<u64> gesture_id);- void latch_keeping_steps(Web::ScrollGesturePhase, Optional<u64> gesture_id);- void clear_latch() { m_latch.clear(); }- void clear_latch_of_gesture(u64 gesture_id);- void forget_gesture();- void relatch_to(Web::AsyncScrollNodeStableID);- // This context's page dispatched a step of the gesture and did not cancel it, or canceled one.- void note_page_let_gesture_through(u64 gesture_id);- void forget_page_let_gesture_through(u64 gesture_id);- // Whether the page let the gesture through, and its wheel event listeners are as they were then.- bool page_let_gesture_through(Optional<u64> gesture_id) const;- // Why this context's wheel event listeners hold the steps of a latched gesture back for the page, if they do. Once- // the page let the gesture through, they only do so after they change.- Optional<Web::InputRoutingDecision> reason_to_hold_latched_steps_back(Optional<u64> gesture_id) const;- bool momentum_of_latched_gesture_can_spring_scroller_back() const;- void set_momentum_of_latched_gesture_has_sprung_scroller_back(bool);--private:- // The scroller the first step of a wheel gesture was routed to. Every later step of the gesture scrolls it without- // hit testing, and stops at its edge rather than handing the rest of the gesture to an ancestor.- struct Latch {- // The gesture the latch was taken for, which only the steps of that gesture continue. A context nested in- // another one takes it for the gesture of the containing context. Empty when the step that took it was in no- // gesture the compositor knows of.- Optional<u64> gesture_id;- // Empty for a latch that keeps the steps without a scroller.- Optional<Web::AsyncScrollNodeStableID> stable_node_id;- // The phase of the last step that reached the latch, which says whether the fingers of its gesture are down.- Web::ScrollGesturePhase last_scroll_gesture_phase { Web::ScrollGesturePhase::None };- Optional<Web::CompositorContextId> nested_context_id {};- // The momentum of the gesture has gone into a rebound of the scroller. Momentum outlasts that rebound, and the- // rest of it must not start another one.- bool momentum_has_sprung_the_scroller_back { false };- };-- struct NewestStepNumbers {- u64 ongoing { 0 };- u64 momentum { 0 };- u64 ended { 0 };- };-- Compositing::WheelRoutingAdmission m_admission { Compositing::WheelRoutingAdmission::NoAsyncScrollingState };- u64 m_wheel_event_listener_state_generation { 0 };- struct Gesture {- u64 id;- Compositing::WheelGestureIdentity identity;- Optional<Web::CompositorContextId> wheel_event_listener_context {};- // Summed per axis, whatever the direction.- Gfx::FloatPoint delta_left_to_the_page {};- };- // The gesture of the wheel events this context sees first: the UI's, or ones the UI never sent that the main- // thread makes. It says which gesture a step is in, whether the page lets the step through before or after this- // context scrolls by it.- Optional<Gesture> m_gesture;- NewestStepNumbers m_newest_step_numbers;- bool m_gesture_had_wheel_event_with_delta { false };- Optional<Latch> m_latch;- // The gesture whose step this context's page dispatched and did not cancel, and the state of the page's wheel event- // listeners then. The later steps of the gesture do not wait for the page for as long as the listeners stay so.- struct GestureThePageLetThrough {- u64 gesture_id { 0 };- u64 wheel_event_listener_state_generation { 0 };- };- Optional<GestureThePageLetThrough> m_gesture_the_page_let_through;- Compositing::TouchpadGestureEnd m_touchpad_gesture_end { Compositing::TouchpadGestureEnd::AfterIdleDelay };-};--}diff --git a/Services/Compositor/main.cpp b/Services/Compositor/main.cppindex dad98161b6d..953f3820516 100644--- a/Services/Compositor/main.cpp+++ b/Services/Compositor/main.cpp@@ -8,7 +8,6 @@#include <Compositor/ConnectionFromClient.h>#include <Compositor/FontSkia.h>#include <Compositor/Sandbox.h>-#include <Compositor/ScrollbarController.h>#include <Compositor/SkiaBackendContext.h>#include <LibCore/ArgsParser.h>#include <LibCore/CrashHandler.h>@@ -91,10 +90,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)if (auto result = Core::Platform::set_current_thread_qos(Core::Platform::ThreadQoS::UserInteractive); result.is_error())warnln("Could not set main thread QoS: {}", result.error());- if (enable_test_mode) {+ if (enable_test_mode)Compositor::force_font_hinting_for_testing();- Compositor::ScrollbarController::show_scrollbars_always_for_testing();- }Core::ResourceImplementation::install(make<Core::ResourceImplementationFile>(TRY(String::from_utf8(resource_root))));if (force_fontconfig)@@ -123,7 +120,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)#endifauto client = TRY(IPC::take_over_accepted_client_from_system_server<Compositor::ConnectionFromClient>(- mach_server_name, move(skia_backend_context)));+ mach_server_name, move(skia_backend_context), enable_test_mode));client->async_gpu_device_identity_reported(move(gpu_device_identity));if (stats_log)diff --git a/Tests/Compositor/CMakeLists.txt b/Tests/Compositor/CMakeLists.txtindex 195665c8a3c..574a163e12a 100644--- a/Tests/Compositor/CMakeLists.txt+++ b/Tests/Compositor/CMakeLists.txt@@ -4,7 +4,6 @@ set(TEST_SOURCESTestAsyncScrollTree.cppTestBitmapExport.cppTestCanvasSurfaceRegistry.cpp- TestScrollbarController.cppTestVideoFrameHolds.cppTestVSyncScheduler.cpp)diff --git a/Tests/Compositor/TestScrollbarController.cpp b/Tests/Compositor/TestScrollbarController.cppdeleted file mode 100644index b0ec7308aa3..00000000000--- a/Tests/Compositor/TestScrollbarController.cpp+++ /dev/null@@ -1,378 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <Compositor/ScrollbarController.h>-#include <LibCompositing/DisplayList/VisualContextTreeTestBuilder.h>-#include <LibCompositing/Scrolling/AsyncScrollTree.h>-#include <LibCompositing/Scrolling/ScrollState.h>-#include <LibTest/TestCase.h>--// A scroll shows the scrollbars, which only take a press while shown. Scrolling back leaves them where they started.-static void show_scrollbars_by_scrolling_away_and_back(Compositor::ScrollbarController& controller, Compositing::SpatialNodeIndex scroll_node_index)-{- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto now = MonotonicTime::now();- controller.update_visibility(scroll_state_snapshot, now);- scroll_state_snapshot.set_device_offset_for_index(scroll_node_index, { 1, 1 });- controller.update_visibility(scroll_state_snapshot, now);- scroll_state_snapshot.set_device_offset_for_index(scroll_node_index, { 0, 0 });- controller.update_visibility(scroll_state_snapshot, now);-}--static Compositor::ScrollbarController::Drag begin_scrollbar_drag(Gfx::Orientation orientation, Gfx::FloatPoint position, Optional<Gfx::IntRect> expanded_thumb_rect = {})-{- auto vertical = orientation == Gfx::Orientation::Vertical;- auto scroll_node_index = Compositing::SpatialNodeIndex { 1 };-- Compositing::AsyncScrollingState scrolling_state;- scrolling_state.scroll_nodes.append({- .scroll_node_index = scroll_node_index,- .stable_node_id = {- .node_id = Web::UniqueNodeID { 2 },- .kind = Web::AsyncScrollNodeKind::Viewport,- .pseudo_element_type = 0,- },- .parent_scroll_node_index = {},- .scrollport_rect = { 0, 0, 100, 100 },- .min_scroll_offset = { 0, 0 },- .max_scroll_offset = { 100, 100 },- .is_viewport = true,- .can_be_wheel_scrolled_horizontally = true,- .can_be_wheel_scrolled_vertically = true,- });-- Compositing::AsyncScrollTree scroll_tree;- scroll_tree.set_state(move(scrolling_state));- Compositing::ScrollStateSnapshot scroll_state_snapshot;-- Vector<Compositing::AsyncScrollbar> scrollbars;- scrollbars.append({- .scroller_stable_node_id = {},- .scroll_node_index = scroll_node_index,- .context = {},- .paint_order_index = 0,- .gutter_rect = vertical ? Gfx::IntRect { 96, 0, 4, 100 } : Gfx::IntRect { 0, 96, 100, 4 },- .thumb_rect = vertical ? Gfx::IntRect { 98, 20, 2, 20 } : Gfx::IntRect { 20, 98, 20, 2 },- .track_rect = vertical ? Gfx::IntRect { 96, 0, 4, 100 } : Gfx::IntRect { 0, 96, 100, 4 },- .expanded_gutter_rect = vertical ? Gfx::IntRect { 92, 0, 8, 100 } : Gfx::IntRect { 0, 92, 100, 8 },- .expanded_thumb_rect = expanded_thumb_rect.value_or(vertical ? Gfx::IntRect { 94, 20, 6, 20 } : Gfx::IntRect { 20, 94, 20, 6 }),- .scroll_size = 0.8,- .expanded_scroll_size = 0.8,- .min_scroll_offset = 0,- .max_scroll_offset = 100,- .thumb_color = Gfx::Color::Black,- .thumb_outline_color = Gfx::Color::White,- .track_color = Gfx::Color::Transparent,- .vertical = vertical,- .is_painted_by_compositor = true,- });-- Compositing::VisualContextTreeTestBuilder visual_context_tree_builder;- visual_context_tree_builder.append_scroll(Compositing::VISUAL_VIEWPORT_NODE_INDEX);- auto visual_context_tree = visual_context_tree_builder.finish();-- Compositor::ScrollbarController controller;- controller.set_scrollbars(scrollbars);- show_scrollbars_by_scrolling_away_and_back(controller, scroll_node_index);- auto drag = controller.begin_drag(scroll_tree, visual_context_tree, scroll_state_snapshot, position);- VERIFY(drag.has_value());- return drag.release_value();-}--TEST_CASE(clicking_scrollbar_beside_thumb_grabs_thumb_at_that_position)-{- auto vertical_drag = begin_scrollbar_drag(Gfx::Orientation::Vertical, { 97, 25 });- EXPECT_EQ(vertical_drag.primary_position, 25);- EXPECT_EQ(vertical_drag.thumb_grab_position, 5);-- auto horizontal_drag = begin_scrollbar_drag(Gfx::Orientation::Horizontal, { 25, 97 });- EXPECT_EQ(horizontal_drag.primary_position, 25);- EXPECT_EQ(horizontal_drag.thumb_grab_position, 5);-}--TEST_CASE(clicking_scrollbar_track_outside_thumb_grabs_thumb_at_center)-{- auto vertical_drag = begin_scrollbar_drag(Gfx::Orientation::Vertical, { 97, 60 });- EXPECT_EQ(vertical_drag.primary_position, 60);- EXPECT_EQ(vertical_drag.thumb_grab_position, 10);-- auto horizontal_drag = begin_scrollbar_drag(Gfx::Orientation::Horizontal, { 60, 97 });- EXPECT_EQ(horizontal_drag.primary_position, 60);- EXPECT_EQ(horizontal_drag.thumb_grab_position, 10);-}--TEST_CASE(starting_scrollbar_drag_uses_expanded_thumb_geometry)-{- auto vertical_drag = begin_scrollbar_drag(Gfx::Orientation::Vertical, { 97, 25 }, Gfx::IntRect { 94, 18, 6, 24 });- EXPECT_EQ(vertical_drag.thumb_grab_position, 7);-- auto horizontal_drag = begin_scrollbar_drag(Gfx::Orientation::Horizontal, { 25, 97 }, Gfx::IntRect { 18, 94, 24, 6 });- EXPECT_EQ(horizontal_drag.thumb_grab_position, 7);-}--static Compositing::AsyncScrollbar scrollbar_painted_by_display_list()-{- return {- .scroller_stable_node_id = Web::AsyncScrollNodeStableID {- .node_id = Web::UniqueNodeID { 2 },- .kind = Web::AsyncScrollNodeKind::Element,- .pseudo_element_type = 0,- },- .scroll_node_index = Compositing::SpatialNodeIndex { 1 },- .context = {},- .paint_order_index = 0,- .gutter_rect = {},- .thumb_rect = { 98, 20, 2, 20 },- .track_rect = { 96, 0, 4, 100 },- .expanded_gutter_rect = { 92, 0, 8, 100 },- .expanded_thumb_rect = { 94, 20, 6, 20 },- .scroll_size = 0.8,- .expanded_scroll_size = 0.8,- .min_scroll_offset = 0,- .max_scroll_offset = 100,- .thumb_color = Gfx::Color::Black,- .thumb_outline_color = Gfx::Color::White,- .track_color = Gfx::Color::Transparent,- .vertical = true,- .is_painted_by_compositor = false,- };-}--static Compositor::PresentedScrollbar presented_scrollbar(Compositor::ScrollbarController const& controller, Compositing::ScrollStateSnapshot const& scroll_state_snapshot = {})-{- for (auto const& scrollbar : controller.scrollbars_of_frame(scroll_state_snapshot)) {- if (!scrollbar.is_painted_by_compositor && scrollbar.scroll_node_index == Compositing::SpatialNodeIndex { 1 } && scrollbar.vertical)- return Compositor::presented_scrollbar_with_colors(scrollbar, Gfx::Color(0, 0, 0, 100), Gfx::Color(255, 255, 255, 64), Gfx::Color(0, 0, 0, 20));- }- VERIFY_NOT_REACHED();-}--static float opacity_of_scrollbar(Compositor::ScrollbarController const& controller)-{- return presented_scrollbar(controller).opacity;-}--static auto const half_fade_duration = AK::Duration::from_milliseconds(Compositing::OverlayFade::duration.to_milliseconds() / 2);--static Compositing::AccumulatedVisualContextTree visual_context_tree_with_scroller()-{- Compositing::VisualContextTreeTestBuilder visual_context_tree_builder;- visual_context_tree_builder.append_scroll(Compositing::VISUAL_VIEWPORT_NODE_INDEX);- return visual_context_tree_builder.finish();-}--TEST_CASE(scrollbar_is_hidden_until_its_scroller_scrolls)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto start = MonotonicTime::now();-- controller.update_visibility(scroll_state_snapshot, start);- EXPECT_EQ(opacity_of_scrollbar(controller), 0);- EXPECT(!controller.next_fade_out_time().has_value());-- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 10 });- controller.update_visibility(scroll_state_snapshot, start);- EXPECT_EQ(opacity_of_scrollbar(controller), 1);- EXPECT(controller.next_fade_out_time() == start + Compositor::ScrollbarController::shown_duration_after_activity);-}--TEST_CASE(scrollbar_fades_out_after_its_scroller_stops_scrolling)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto visual_context_tree = visual_context_tree_with_scroller();- auto start = MonotonicTime::now();- controller.update_visibility(scroll_state_snapshot, start);- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 10 });- controller.update_visibility(scroll_state_snapshot, start);-- auto shown_until = start + Compositor::ScrollbarController::shown_duration_after_activity;- EXPECT(!controller.fades_need_frame(shown_until - AK::Duration::from_milliseconds(1)));- EXPECT(controller.fades_need_frame(shown_until));-- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until);- EXPECT_EQ(opacity_of_scrollbar(controller), 1);- EXPECT(!controller.next_fade_out_time().has_value());-- auto damage_rect = controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until + half_fade_duration);- EXPECT(opacity_of_scrollbar(controller) > 0);- EXPECT(opacity_of_scrollbar(controller) < 1);- EXPECT(damage_rect.contains(Gfx::IntRect { 92, 0, 8, 100 }));-- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until + Compositing::OverlayFade::duration);- EXPECT_EQ(opacity_of_scrollbar(controller), 0);- EXPECT(!controller.fades_need_frame(shown_until + Compositing::OverlayFade::duration));-}--TEST_CASE(scroll_while_fading_out_shows_scrollbar_again)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto visual_context_tree = visual_context_tree_with_scroller();- auto start = MonotonicTime::now();- controller.update_visibility(scroll_state_snapshot, start);- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 10 });- controller.update_visibility(scroll_state_snapshot, start);-- auto shown_until = start + Compositor::ScrollbarController::shown_duration_after_activity;- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until);- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until + half_fade_duration);- EXPECT(opacity_of_scrollbar(controller) < 1);-- auto scrolled_again_at = shown_until + half_fade_duration;- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 20 });- controller.update_visibility(scroll_state_snapshot, scrolled_again_at);- EXPECT_EQ(opacity_of_scrollbar(controller), 1);- EXPECT(!controller.fades_need_frame(scrolled_again_at));- EXPECT(controller.next_fade_out_time() == scrolled_again_at + Compositor::ScrollbarController::shown_duration_after_activity);-}--TEST_CASE(hovering_hidden_scrollbar_does_not_show_it)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto start = MonotonicTime::now();- controller.update_visibility(scroll_state_snapshot, start);-- controller.set_hovered_scrollbar(0);- controller.update_visibility(scroll_state_snapshot, start);- EXPECT_EQ(opacity_of_scrollbar(controller), 0);- EXPECT(!controller.fades_need_frame(start));-- // A scroll shows it, and the hover then keeps it shown and grows it.- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 10 });- controller.update_visibility(scroll_state_snapshot, start);- EXPECT_EQ(opacity_of_scrollbar(controller), 1);- EXPECT(!controller.next_fade_out_time().has_value());- EXPECT(controller.fades_need_frame(start));-}--TEST_CASE(hovered_scrollbar_stays_shown_until_the_pointer_leaves_it)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto start = MonotonicTime::now();- controller.update_visibility(scroll_state_snapshot, start);- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 10 });- controller.update_visibility(scroll_state_snapshot, start);-- controller.set_hovered_scrollbar(0);- controller.update_visibility(scroll_state_snapshot, start);- EXPECT_EQ(opacity_of_scrollbar(controller), 1);- EXPECT(!controller.next_fade_out_time().has_value());-- auto much_later = start + AK::Duration::from_seconds(10);- controller.update_visibility(scroll_state_snapshot, much_later);- (void)controller.advance_fades(visual_context_tree_with_scroller(), scroll_state_snapshot, much_later);- EXPECT_EQ(opacity_of_scrollbar(controller), 1);- EXPECT(!controller.fades_need_frame(much_later));-- controller.set_hovered_scrollbar({});- controller.update_visibility(scroll_state_snapshot, much_later);- EXPECT_EQ(opacity_of_scrollbar(controller), 1);- EXPECT(controller.next_fade_out_time() == much_later + Compositor::ScrollbarController::shown_duration_after_activity);-}--TEST_CASE(hovered_scrollbar_grows_and_stays_expanded_until_it_has_faded_out)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto visual_context_tree = visual_context_tree_with_scroller();- auto start = MonotonicTime::now();- controller.update_visibility(scroll_state_snapshot, start);-- // A scroll shows the thin scrollbar.- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 10 });- controller.update_visibility(scroll_state_snapshot, start);- EXPECT_EQ(presented_scrollbar(controller).thumb_rect.width(), 2);- EXPECT_EQ(presented_scrollbar(controller).thumb_color.alpha(), 100);- EXPECT_EQ(presented_scrollbar(controller).track_color.alpha(), 0);-- // Hovering it grows it over the duration of a fade.- controller.set_hovered_scrollbar(0);- controller.update_visibility(scroll_state_snapshot, start);- EXPECT(controller.fades_need_frame(start));- auto damage_rect = controller.advance_fades(visual_context_tree, scroll_state_snapshot, start + half_fade_duration);- EXPECT(damage_rect.contains(Gfx::IntRect { 92, 0, 8, 100 }));- EXPECT(presented_scrollbar(controller).thumb_rect.width() > 2);- EXPECT(presented_scrollbar(controller).thumb_rect.width() < 6);- auto grown_at = start + Compositing::OverlayFade::duration;- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, grown_at);- EXPECT_EQ(presented_scrollbar(controller, scroll_state_snapshot).thumb_rect, Gfx::FloatRect(94, 12, 6, 20));- EXPECT_EQ(presented_scrollbar(controller).gutter_rect, Gfx::FloatRect(92, 0, 8, 100));- EXPECT_EQ(presented_scrollbar(controller).thumb_color.alpha(), 100);- EXPECT_EQ(presented_scrollbar(controller).track_color.alpha(), 20);- EXPECT(!controller.fades_need_frame(grown_at));-- // It stays expanded after the pointer leaves it, while it is shown and while it fades out.- controller.set_hovered_scrollbar({});- controller.update_visibility(scroll_state_snapshot, grown_at);- auto shown_until = grown_at + Compositor::ScrollbarController::shown_duration_after_activity;- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until);- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until + half_fade_duration);- EXPECT(opacity_of_scrollbar(controller) > 0);- EXPECT_EQ(presented_scrollbar(controller).thumb_rect.width(), 6);-- // Once it has faded out, it is thin again.- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until + Compositing::OverlayFade::duration);- EXPECT_EQ(opacity_of_scrollbar(controller), 0);- EXPECT_EQ(presented_scrollbar(controller).thumb_rect.width(), 2);- EXPECT(!controller.fades_need_frame(shown_until + Compositing::OverlayFade::duration));-}--TEST_CASE(press_beside_thumb_pages_toward_pointer_until_thumb_reaches_it)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });-- // The thumb spans 20 to 40 at no scroll offset, and moves 0.8 for each unit scrolled.- EXPECT_EQ(controller.paging_direction(0, 10, { 0, 0 }), -1);- EXPECT_EQ(controller.paging_direction(0, 30, { 0, 0 }), 0);- EXPECT_EQ(controller.paging_direction(0, 60, { 0, 0 }), 1);- EXPECT_EQ(controller.paging_direction(0, 60, { 0, 30 }), 0);- EXPECT_EQ(controller.paging_direction(0, 60, { 0, 60 }), -1);-}--TEST_CASE(scrollbar_that_has_faded_out_is_reported_hidden)-{- Compositor::ScrollbarController controller;- controller.set_scrollbars({ scrollbar_painted_by_display_list() });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- auto visual_context_tree = visual_context_tree_with_scroller();- auto start = MonotonicTime::now();-- // A scrollbar starts out hidden, which the main thread hears once.- controller.update_visibility(scroll_state_snapshot, start);- auto changes = controller.take_visibility_changes();- EXPECT_EQ(changes.size(), 1u);- EXPECT(changes[0].vertical);- EXPECT(changes[0].hidden);- EXPECT(controller.take_visibility_changes().is_empty());-- // A scroll shows it.- scroll_state_snapshot.set_device_offset_for_index(Compositing::SpatialNodeIndex { 1 }, { 0, 10 });- controller.update_visibility(scroll_state_snapshot, start);- changes = controller.take_visibility_changes();- EXPECT_EQ(changes.size(), 1u);- EXPECT(!changes[0].hidden);-- // It is still shown while it fades out, and hidden once it has.- auto shown_until = start + Compositor::ScrollbarController::shown_duration_after_activity;- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until);- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until + half_fade_duration);- EXPECT(controller.take_visibility_changes().is_empty());- (void)controller.advance_fades(visual_context_tree, scroll_state_snapshot, shown_until + Compositing::OverlayFade::duration);- changes = controller.take_visibility_changes();- EXPECT_EQ(changes.size(), 1u);- EXPECT(changes[0].hidden);-}