Truly independent web browser
Compositor: Start compositor_core with the scroll controllers
Aliaksandr Kalenike376c6aabd68
diff --git a/Cargo.lock b/Cargo.lockindex 5faa2eaef09..e1983ccb736 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -604,6 +604,18 @@ dependencies = ["memchr",]+[[package]]+name = "compositor_core"+version = "0.1.0"+dependencies = [+ "ak",+ "ladybird_allocator",+ "libcompositing_rust",+ "libgfx_rust",+ "libipc_rust",+ "rustc-demangle",+]+[[package]]name = "const-oid"version = "0.9.6"diff --git a/Cargo.toml b/Cargo.tomlindex 295b418b382..b65977fb9b6 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -27,6 +27,7 @@ members = ["Libraries/LibWeb/HTML/Parser/Rust","Libraries/LibWebRTC/Rust","Libraries/RustAllocator",+ "Services/Compositor/Rust","Services/WebRTCClient","Tests/LibIPC/RustEchoServer",]diff --git a/Libraries/LibCompositing/Rust/src/scrolling/mod.rs b/Libraries/LibCompositing/Rust/src/scrolling/mod.rsindex 6dc11a0ca89..3cffa61346a 100644--- a/Libraries/LibCompositing/Rust/src/scrolling/mod.rs+++ b/Libraries/LibCompositing/Rust/src/scrolling/mod.rs@@ -17,20 +17,37 @@ pub mod visual_context_tree;pub mod wheel_gesture_identity;pub use crate::display_list::commands::{CompositorScrollNodeKind, ContextRef, EffectNodeIndex, SpatialNodeIndex};+pub use crate::ipc_types::Compositing_AppliedScrollRequest as AppliedScrollRequest;pub use crate::ipc_types::Compositing_AsyncScrollOffset as AsyncScrollOffset;pub use crate::ipc_types::Compositing_KeyboardScrollState as KeyboardScrollState;+pub use crate::ipc_types::Compositing_PendingAsyncScrollUpdates as PendingAsyncScrollUpdates;pub use crate::ipc_types::Compositing_ScrollAnimationKind as ScrollAnimationKind;pub use crate::ipc_types::Compositing_ScrollRequest as ScrollRequest;pub use crate::ipc_types::Compositing_SnapAreaIdentity as SnapAreaIdentity;pub use crate::ipc_types::Compositing_SnapDestination as SnapDestination;pub use crate::ipc_types::Compositing_SnappedAreas as SnappedAreas;+pub use crate::ipc_types::Compositing_StartedUserScroll as StartedUserScroll;pub use crate::ipc_types::Compositing_WheelStepDispatch as WheelStepDispatch;pub use crate::ipc_types::Web_AsyncScrollNodeKind as AsyncScrollNodeKind;pub use crate::ipc_types::Web_AsyncScrollNodeStableID as AsyncScrollNodeStableID;pub use crate::ipc_types::Web_CompositorContextId as CompositorContextId;+pub use crate::ipc_types::Web_DevicePixelPoint as DevicePixelPoint;pub use crate::ipc_types::Web_InputRoutingDecision as InputRoutingDecision;+pub use crate::ipc_types::Web_KeyEvent as KeyEvent;+pub use crate::ipc_types::Web_KeyEvent_Type as KeyEventType;+pub use crate::ipc_types::Web_MouseEvent as MouseEvent;+pub use crate::ipc_types::Web_MouseEvent_Type as MouseEventType;+pub use crate::ipc_types::Web_OverlayScrollbarVisibility as OverlayScrollbarVisibility;+pub use crate::ipc_types::Web_PinchEvent as PinchEvent;+pub use crate::ipc_types::Web_PointerInputData as PointerInputData;pub use crate::ipc_types::Web_ScrollGesturePhase as ScrollGesturePhase;+pub use crate::ipc_types::Web_ScrollbarDraggedByCompositor as ScrollbarDraggedByCompositor;+pub use crate::ipc_types::Web_UIEvents_KeyCode as KeyCode;+pub use crate::ipc_types::Web_UIEvents_KeyModifier as KeyModifier;+pub use crate::ipc_types::Web_UIEvents_MouseButton as MouseButton;pub use crate::ipc_types::Web_UniqueNodeID as UniqueNodeId;+pub use crate::ipc_types::Web_WheelDeltaPrecision as WheelDeltaPrecision;+pub use crate::ipc_types::Web_WheelGestureMark as WheelGestureMark;pub use async_scroll_tree::*;pub use async_scrolling_state::*;pub use display_list::{AsyncScrollingMetadata, DisplayList};diff --git a/Libraries/LibCompositing/Rust/src/scrolling/overlay_fade.rs b/Libraries/LibCompositing/Rust/src/scrolling/overlay_fade.rsindex bd4d52e5e34..1d06a52fffd 100644--- a/Libraries/LibCompositing/Rust/src/scrolling/overlay_fade.rs+++ b/Libraries/LibCompositing/Rust/src/scrolling/overlay_fade.rs@@ -8,7 +8,7 @@use crate::time::{Duration, MonotonicTime};-#[derive(Default)]+#[derive(Clone, Copy, Default)]pub struct OverlayFade {opacity: f32,initial_opacity: f32,diff --git a/Libraries/LibGfx/Rust/src/geometry.rs b/Libraries/LibGfx/Rust/src/geometry.rsindex 02732c81dc8..9f71e7c160c 100644--- a/Libraries/LibGfx/Rust/src/geometry.rs+++ b/Libraries/LibGfx/Rust/src/geometry.rs@@ -75,6 +75,20 @@ pub enum Orientation {}impl FloatPoint {+ pub fn primary_offset_for_orientation(self, orientation: Orientation) -> f32 {+ match orientation {+ Orientation::Horizontal => self.x,+ Orientation::Vertical => self.y,+ }+ }++ pub fn set_primary_offset_for_orientation(&mut self, orientation: Orientation, value: f32) {+ match orientation {+ Orientation::Horizontal => self.x = value,+ Orientation::Vertical => self.y = value,+ }+ }+pub fn is_zero(self) -> bool {self.x == 0.0 && self.y == 0.0}@@ -188,6 +202,27 @@ impl Neg for FloatVector3 {}impl IntRect {+ pub fn primary_offset_for_orientation(self, orientation: Orientation) -> i32 {+ match orientation {+ Orientation::Horizontal => self.x,+ Orientation::Vertical => self.y,+ }+ }++ pub fn primary_size_for_orientation(self, orientation: Orientation) -> i32 {+ match orientation {+ Orientation::Horizontal => self.width,+ Orientation::Vertical => self.height,+ }+ }++ pub fn translate_primary_offset_for_orientation(&mut self, orientation: Orientation, delta: i32) {+ match orientation {+ Orientation::Horizontal => self.x += delta,+ Orientation::Vertical => self.y += delta,+ }+ }+pub const fn new(x: i32, y: i32, width: i32, height: i32) -> Self {Self { x, y, width, height }}@@ -254,6 +289,14 @@ impl IntRect {}impl FloatRect {+ pub fn contains_vertically(self, y: f32) -> bool {+ y >= self.y && y < self.bottom()+ }++ pub fn contains_horizontally(self, x: f32) -> bool {+ x >= self.x && x < self.right()+ }+pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {Self { x, y, width, height }}diff --git a/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipc b/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipcindex 123af619ac2..d54f4dc5b2a 100644--- a/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipc+++ b/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipc@@ -7,7 +7,7 @@#include <LibWebCommon/Page/AsyncScrollNodeStableID.h>-[ExistingCpp, RustDerive=Hash]+[ExistingCpp, RustDerive=Hash+PartialOrd+Ord]enum Web::AsyncScrollNodeKind : u8 {Viewport,Element,@@ -15,7 +15,7 @@ enum Web::AsyncScrollNodeKind : u8 {VisualViewport,}-[ExistingCpp, RustDerive=Copy+Eq+Hash]+[ExistingCpp, RustDerive=Copy+Eq+Hash+PartialOrd+Ord]struct Web::AsyncScrollNodeStableID {Web::UniqueNodeID node_id;Web::AsyncScrollNodeKind kind;diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex ef3b19d58d6..0dbca7bb360 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -63,6 +63,10 @@ set(GENERATED_SOURCESWebGLCommandReplayer.cpp)+import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME compositor_core FEATURES allocator)+target_link_libraries(compositor_core INTERFACE LibGfx)+test_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME compositor_core)+add_library(compositorservice STATIC ${SOURCES} ${GENERATED_SOURCES})ladybird_generated_sources(compositorservice)@@ -82,7 +86,11 @@ target_include_directories(compositorservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Servtarget_link_libraries(Compositor PRIVATE compositorservice LibCore LibMain LibSandbox)# ANGLE must precede Skia so macOS GLES symbols bind to ANGLE rather than the# OpenGL framework pulled in by Skia.-target_link_libraries(compositorservice PRIVATE LibCore LibGfx LibImageDecoderClient LibIPC LibMedia LibCompositing ${ANGLE_TARGETS} skia)+target_link_libraries(compositorservice PRIVATE LibCore LibGfx LibImageDecoderClient LibIPC LibMedia LibCompositing compositor_core ${ANGLE_TARGETS} skia)++if ((LINUX OR BSD) AND NOT BUILD_SHARED_LIBS)+ target_link_options(compositorservice INTERFACE LINKER:--allow-multiple-definition)+endif()if (HAS_VULKAN)target_sources(compositorservice PRIVATE SkiaVulkanMemoryAllocator.cpp)diff --git a/Services/Compositor/Rust/Cargo.toml b/Services/Compositor/Rust/Cargo.tomlnew file mode 100644index 00000000000..b6609da2d46--- /dev/null+++ b/Services/Compositor/Rust/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "compositor_core"+version = "0.1.0"+edition = "2024"+publish = false++[lib]+crate-type = ["staticlib"]++[features]+default = []+allocator = ["dep:ladybird_allocator"]++[dependencies]+ak = { path = "../../../AK/Rust" }+ladybird_allocator = { path = "../../../Libraries/RustAllocator", optional = true }+libcompositing_rust = { path = "../../../Libraries/LibCompositing/Rust" }+libgfx_rust = { path = "../../../Libraries/LibGfx/Rust", default-features = false }+libipc_rust = { path = "../../../Libraries/LibIPC/Rust" }+rustc-demangle = "0.1"++[lints]+workspace = truediff --git a/Services/Compositor/Rust/src/async_scroll_update_outbox.rs b/Services/Compositor/Rust/src/async_scroll_update_outbox.rsnew file mode 100644index 00000000000..05a4b73bd3e--- /dev/null+++ b/Services/Compositor/Rust/src/async_scroll_update_outbox.rs@@ -0,0 +1,110 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libcompositing_rust::scrolling::{+ AppliedScrollRequest, AsyncScrollNodeStableID, AsyncScrollOffset, AsyncScrollOperationID,+ PendingAsyncScrollUpdates, StartedUserScroll,+};++#[derive(Default)]+pub struct AsyncScrollUpdateOutbox {+ pending_scroll_offsets: Vec<AsyncScrollOffset>,+ last_publication_sequence: u64,+ last_allocated_operation_id: AsyncScrollOperationID,+ completed_operation_ids: Vec<AsyncScrollOperationID>,+ operation_ids_taken_over_by_user_input: Vec<AsyncScrollOperationID>,+ started_user_scrolls: Vec<StartedUserScroll>,+ applied_scroll_requests: Vec<AppliedScrollRequest>,+ boxes_whose_user_scroll_gesture_ended: Vec<AsyncScrollNodeStableID>,+ published_user_scroll_gesture_state: UserScrollGestureState,+}++// What the compositor holds on to, published whenever it changes.+#[derive(Default, PartialEq, Eq)]+pub struct UserScrollGestureState {+ pub boxes_in_user_scroll_gesture: Vec<AsyncScrollNodeStableID>,+ pub wheel_latched_scroller: Option<AsyncScrollNodeStableID>,+}++impl AsyncScrollUpdateOutbox {+ pub fn allocate_operation_id(&mut self) -> AsyncScrollOperationID {+ self.last_allocated_operation_id = self.last_allocated_operation_id.wrapping_add(1);+ self.last_allocated_operation_id+ }++ pub fn complete_operation(&mut self, operation_id: AsyncScrollOperationID) {+ self.completed_operation_ids.push(operation_id);+ }++ pub fn note_operation_taken_over_by_user_input(&mut self, operation_id: AsyncScrollOperationID) {+ self.operation_ids_taken_over_by_user_input.push(operation_id);+ }++ pub fn record_started_user_scroll(&mut self, started_user_scroll: StartedUserScroll) {+ self.started_user_scrolls.push(started_user_scroll);+ }++ pub fn note_scroll_request_applied(&mut self, applied_scroll_request: AppliedScrollRequest) {+ self.applied_scroll_requests.push(applied_scroll_request);+ }+}++fn set_or_append_pending_scroll_offset(+ pending_scroll_offsets: &mut Vec<AsyncScrollOffset>,+ scroll_offset: &AsyncScrollOffset,+) {+ for existing in &mut *pending_scroll_offsets {+ if existing.stable_node_id == scroll_offset.stable_node_id {+ existing.merge_later_scroll(scroll_offset);+ return;+ }+ }+ pending_scroll_offsets.push(scroll_offset.clone());+}++impl AsyncScrollUpdateOutbox {+ pub fn record_scroll_offsets(&mut self, scroll_offsets: &[AsyncScrollOffset]) {+ for scroll_offset in scroll_offsets {+ set_or_append_pending_scroll_offset(&mut self.pending_scroll_offsets, scroll_offset);+ }+ }++ pub fn note_user_scroll_gesture_ended(&mut self, stable_node_ids: &[AsyncScrollNodeStableID]) {+ for &stable_node_id in stable_node_ids {+ if !self.boxes_whose_user_scroll_gesture_ended.contains(&stable_node_id) {+ self.boxes_whose_user_scroll_gesture_ended.push(stable_node_id);+ }+ }+ }++ pub fn has_updates(&self, user_scroll_gesture_state: &UserScrollGestureState) -> bool {+ !self.pending_scroll_offsets.is_empty()+ || !self.completed_operation_ids.is_empty()+ || !self.operation_ids_taken_over_by_user_input.is_empty()+ || !self.started_user_scrolls.is_empty()+ || !self.applied_scroll_requests.is_empty()+ || !self.boxes_whose_user_scroll_gesture_ended.is_empty()+ || *user_scroll_gesture_state != self.published_user_scroll_gesture_state+ }++ pub fn take_updates(&mut self, user_scroll_gesture_state: UserScrollGestureState) -> PendingAsyncScrollUpdates {+ self.last_publication_sequence = self.last_publication_sequence.wrapping_add(1);+ let updates = PendingAsyncScrollUpdates {+ document_id: None,+ sequence: self.last_publication_sequence,+ scroll_offsets: std::mem::take(&mut self.pending_scroll_offsets),+ completed_operation_ids: std::mem::take(&mut self.completed_operation_ids),+ operation_ids_taken_over_by_user_input: std::mem::take(&mut self.operation_ids_taken_over_by_user_input),+ started_user_scrolls: std::mem::take(&mut self.started_user_scrolls),+ applied_scroll_requests: std::mem::take(&mut self.applied_scroll_requests),+ boxes_whose_user_scroll_gesture_ended: std::mem::take(&mut self.boxes_whose_user_scroll_gesture_ended),+ boxes_in_user_scroll_gesture: user_scroll_gesture_state.boxes_in_user_scroll_gesture.clone(),+ wheel_latched_scroller: user_scroll_gesture_state.wheel_latched_scroller,+ };+ self.published_user_scroll_gesture_state = user_scroll_gesture_state;+ updates+ }+}diff --git a/Services/Compositor/Rust/src/elastic_overscroll_controller.rs b/Services/Compositor/Rust/src/elastic_overscroll_controller.rsnew file mode 100644index 00000000000..6be0a05ed10--- /dev/null+++ b/Services/Compositor/Rust/src/elastic_overscroll_controller.rs@@ -0,0 +1,263 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libcompositing_rust::scrolling::elastic_overscroll::ElasticOverscroll;+use libcompositing_rust::scrolling::scroll_fling::ScrollVelocityTracker;+use libcompositing_rust::scrolling::{+ AsyncScrollNode, AsyncScrollNodeStableID, AsyncScrollTree, ScrollGesturePhase, ScrollStateSnapshot,+ WheelDeltaPrecision,+};+use libcompositing_rust::time::MonotonicTime;+use libgfx_rust::{FloatPoint, FloatSize};++#[derive(Default)]+pub struct ElasticOverscrollController {+ enabled: bool,+ active_overscrolls: Vec<ActiveOverscroll>,+ step_velocity_tracker: ScrollVelocityTracker,+}++// 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 {+ stable_node_id: AsyncScrollNodeStableID,+ overscroll: ElasticOverscroll,+}++impl ElasticOverscrollController {+ pub fn set_enabled(&mut self, enabled: bool) {+ self.enabled = enabled;+ if !enabled {+ self.forget();+ }+ }++ pub fn step_can_stretch(+ &self,+ wheel_delta_precision: WheelDeltaPrecision,+ scroll_gesture_phase: ScrollGesturePhase,+ ) -> bool {+ if !self.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 != WheelDeltaPrecision::Precise {+ return false;+ }+ scroll_gesture_phase == ScrollGesturePhase::Ongoing || scroll_gesture_phase == ScrollGesturePhase::Momentum+ }++ pub fn note_step_from_ui(&mut self, delta: FloatPoint, now: MonotonicTime) {+ self.step_velocity_tracker.add_step(delta, now);+ }++ fn active_overscroll_of(&mut self, stable_node_id: AsyncScrollNodeStableID) -> Option<&mut ActiveOverscroll> {+ self.active_overscrolls+ .iter_mut()+ .find(|active| active.stable_node_id == stable_node_id)+ }++ pub fn has_active_overscroll_of(&self, stable_node_id: AsyncScrollNodeStableID) -> bool {+ self.active_overscrolls+ .iter()+ .any(|active| active.stable_node_id == stable_node_id)+ }++ pub fn stretch_of(&self, stable_node_id: AsyncScrollNodeStableID) -> FloatPoint {+ for active in &self.active_overscrolls {+ if active.stable_node_id == stable_node_id {+ return active.overscroll.stretch();+ }+ }+ FloatPoint::default()+ }++ // 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.+ pub fn relax_by(&mut self, stable_node_id: AsyncScrollNodeStableID, step_delta: FloatPoint) -> FloatPoint {+ let Some(active) = self.active_overscroll_of(stable_node_id) else {+ return step_delta;+ };+ let delta_left_to_scroll_with = active.overscroll.relax_by(step_delta);+ if active.overscroll.is_at_rest() {+ self.active_overscrolls+ .retain(|candidate| candidate.stable_node_id != stable_node_id);+ }+ delta_left_to_scroll_with+ }++ // Returns whether the scroller is at an edge that the step points past, which is what lets the step pull it.+ pub fn pull_by(+ &mut self,+ node: &AsyncScrollNode,+ scroll_offset: FloatPoint,+ step_delta: FloatPoint,+ delta_the_scroller_did_not_scroll_by: FloatPoint,+ visual_viewport_magnification: f32,+ ) -> bool {+ // 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.+ let mut overscroll_delta = FloatPoint::default();+ let step_is_mainly_vertical = step_delta.y.abs() >= step_delta.x.abs();+ if step_is_mainly_vertical {+ let delta_y = delta_the_scroller_did_not_scroll_by.y;+ let is_at_the_edge_the_delta_points_past = (delta_y < 0.0 && scroll_offset.y <= node.min_scroll_offset.y)+ || (delta_y > 0.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.y = delta_y;+ }+ } else {+ let delta_x = delta_the_scroller_did_not_scroll_by.x;+ let is_at_the_edge_the_delta_points_past = (delta_x < 0.0 && scroll_offset.x <= node.min_scroll_offset.x)+ || (delta_x > 0.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.x = delta_x;+ }+ }+ if overscroll_delta.is_zero() {+ return false;+ }++ let active = match self+ .active_overscrolls+ .iter()+ .position(|active| active.stable_node_id == node.stable_node_id)+ {+ Some(index) => &mut self.active_overscrolls[index],+ None => {+ // 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.+ let mut scrollport_size = FloatSize {+ width: node.scrollport_rect.width as f32,+ height: node.scrollport_rect.height as f32,+ };+ if node.is_viewport {+ scrollport_size.width *= 1.0_f32 / visual_viewport_magnification;+ scrollport_size.height *= 1.0_f32 / visual_viewport_magnification;+ }+ if scrollport_size.width.is_nan()+ || scrollport_size.height.is_nan()+ || scrollport_size.width < 0.0+ || scrollport_size.height < 0.0+ {+ return false;+ }+ self.active_overscrolls.push(ActiveOverscroll {+ stable_node_id: node.stable_node_id,+ overscroll: ElasticOverscroll::new(scrollport_size, visual_viewport_magnification),+ });+ self.active_overscrolls.last_mut().unwrap()+ }+ };+ active.overscroll.pull_by(overscroll_delta);+ true+ }++ pub fn release_held_by_fingers(&mut self, now: MonotonicTime) {+ let velocity = self.step_velocity_tracker.velocity_at_lift(now).unwrap_or_default();+ for active in &mut self.active_overscrolls {+ active.overscroll.release(velocity, 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.+ pub fn drop_stretch_moved_by(&mut self, stable_node_id: AsyncScrollNodeStableID, scroll_delta: FloatPoint) {+ let stretch = self.stretch_of(stable_node_id);+ if (stretch.x != 0.0 && scroll_delta.x != 0.0) || (stretch.y != 0.0 && scroll_delta.y != 0.0) {+ self.active_overscrolls+ .retain(|active| active.stable_node_id != stable_node_id);+ }+ }++ pub fn release_stretch_of(&mut self, stable_node_id: AsyncScrollNodeStableID, now: MonotonicTime) {+ if let Some(active) = self.active_overscroll_of(stable_node_id)+ && !active.overscroll.is_rebounding()+ {+ active.overscroll.release(FloatPoint::default(), now);+ }+ }++ pub fn end_gesture(&mut self, now: MonotonicTime) {+ self.release_held_by_fingers(now);+ self.step_velocity_tracker.reset();+ }++ pub fn forget(&mut self) {+ self.active_overscrolls.clear();+ self.step_velocity_tracker.reset();+ }++ pub fn did_install_scrolling_state(&mut self, async_scroll_tree: &AsyncScrollTree) {+ self.active_overscrolls.retain(|active| {+ let node = async_scroll_tree+ .scroll_node_index_for_stable_id(active.stable_node_id)+ .and_then(|index| async_scroll_tree.scroll_node_for_index(index));+ let Some(node) = node else {+ return false;+ };+ // A scroller that has been told not to stretch along an axis since it was pulled lets go at once.+ let stretch = active.overscroll.stretch();+ !((stretch.x != 0.0 && !node.shows_overscroll_effect_horizontally)+ || (stretch.y != 0.0 && !node.shows_overscroll_effect_vertically))+ });+ }++ pub fn has_rebound(&self) -> bool {+ self.active_overscrolls+ .iter()+ .any(|active| active.overscroll.is_rebounding())+ }++ pub fn advance_rebounds(&mut self, frame_time: MonotonicTime) -> bool {+ let mut a_presented_stretch_changed = false;+ self.active_overscrolls.retain_mut(|active| {+ if !active.overscroll.is_rebounding() {+ return true;+ }+ let stretch_before = active.overscroll.stretch();+ let is_still_rebounding = active.overscroll.advance_rebound_to(frame_time);+ if active.overscroll.stretch() != stretch_before {+ a_presented_stretch_changed = true;+ }+ is_still_rebounding+ });+ a_presented_stretch_changed+ }++ // The scroll offsets to present when a scroller is stretched, which are the only ones that leave a scroll range.+ pub fn stretched_scroll_state_snapshot(+ &self,+ scroll_state_snapshot: &ScrollStateSnapshot,+ async_scroll_tree: &AsyncScrollTree,+ ) -> Option<ScrollStateSnapshot> {+ let mut stretched_scroll_state_snapshot = None;+ for active in &self.active_overscrolls {+ let stretch = active.overscroll.stretch();+ if stretch.is_zero() {+ continue;+ }+ let Some(scroll_node_index) = async_scroll_tree.scroll_node_index_for_stable_id(active.stable_node_id)+ else {+ continue;+ };+ let snapshot = stretched_scroll_state_snapshot.get_or_insert_with(|| scroll_state_snapshot.clone());+ // 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.+ snapshot.set_device_offset_for_index(+ scroll_node_index,+ snapshot.device_offset_for_index(scroll_node_index) - stretch,+ );+ }+ stretched_scroll_state_snapshot+ }+}diff --git a/Services/Compositor/Rust/src/frame_inputs.rs b/Services/Compositor/Rust/src/frame_inputs.rsnew file mode 100644index 00000000000..332cbb0ff5a--- /dev/null+++ b/Services/Compositor/Rust/src/frame_inputs.rs@@ -0,0 +1,93 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What a frame is painted with besides the display list and its resources.++use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, ScrollStateSnapshot, SpatialNodeIndex};+use libgfx_rust::{Color, FloatRect, IntRect};++// A scrollbar as it is painted, somewhere between its thin and its expanded geometry.+#[derive(Clone, Copy)]+#[repr(C)]+pub struct PresentedScrollbar {+ pub gutter_rect: FloatRect,+ pub thumb_rect: FloatRect,+ pub thumb_color: Color,+ pub thumb_outline_color: Color,+ pub track_color: Color,+ pub opacity: f32,+}++impl Default for PresentedScrollbar {+ fn default() -> Self {+ Self {+ gutter_rect: Default::default(),+ thumb_rect: Default::default(),+ thumb_color: Default::default(),+ thumb_outline_color: Default::default(),+ track_color: Default::default(),+ opacity: 1.0,+ }+ }+}++#[derive(Clone, Copy)]+#[repr(C)]+pub struct ScrollbarOfFrame {+ pub scroll_node_index: SpatialNodeIndex,+ pub vertical: bool,+ pub is_painted_by_compositor: bool,+ pub gutter_rect: FloatRect,+ pub thumb_rect: FloatRect,+ pub expansion: f32,+ pub opacity: f32,+ pub thumb_color: Color,+ pub thumb_outline_color: Color,+ pub track_color: Color,+ pub thin_and_expanded_gutter_rect: IntRect,+}++impl Default for ScrollbarOfFrame {+ fn default() -> Self {+ Self {+ scroll_node_index: Default::default(),+ vertical: false,+ is_painted_by_compositor: false,+ gutter_rect: Default::default(),+ thumb_rect: Default::default(),+ expansion: 0.0,+ opacity: 1.0,+ thumb_color: Default::default(),+ thumb_outline_color: Default::default(),+ track_color: Default::default(),+ thin_and_expanded_gutter_rect: Default::default(),+ }+ }+}++// A scroll offset outside the scroll range moves the thumb past an end of its track, where it is cut short instead.+pub fn thumb_rect_kept_inside_track(mut thumb_rect: IntRect, track_rect: IntRect, vertical: bool) -> IntRect {+ if vertical {+ let top = thumb_rect.y.max(track_rect.y);+ let bottom = thumb_rect.bottom().min(track_rect.bottom());+ thumb_rect.y = top;+ thumb_rect.height = 0.max(bottom - top);+ } else {+ let left = thumb_rect.x.max(track_rect.x);+ let right = thumb_rect.right().min(track_rect.right());+ thumb_rect.x = left;+ thumb_rect.width = 0.max(right - left);+ }+ thumb_rect+}++// What a frame is painted with besides the display list and its resources.+pub struct FrameInputs {+ pub visual_context_tree: AccumulatedVisualContextTree,+ pub presented_scroll_state_snapshot: ScrollStateSnapshot,+ pub scrollbars: Vec<ScrollbarOfFrame>,+ pub viewport_scroll_node_index: Option<SpatialNodeIndex>,+}diff --git a/Services/Compositor/Rust/src/host.rs b/Services/Compositor/Rust/src/host.rsnew file mode 100644index 00000000000..1a501c55c4d--- /dev/null+++ b/Services/Compositor/Rust/src/host.rs@@ -0,0 +1,167 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! 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.++use libcompositing_rust::scrolling::CompositorContextId;+use libcompositing_rust::time::Duration;+use libgfx_rust::IntRect;+use libipc_rust::cpp_connection::RawAttachment;+use libipc_rust::wire::EndpointMessage;+use std::ffi::c_void;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct WebContentClientId(pub u64);++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct PresentationId(pub u64);++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum ContextTimer {+ ScrollStepGestureInput,+ ScrollbarPaging,+ ScrollbarFadeOut,+ CaretBlink,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PendingFrame {+ pub viewport_rect: IntRect,+ pub forced_damage_rect: IntRect,+}++impl PendingFrame {+ pub fn repainting_everything(viewport_rect: IntRect) -> Self {+ Self {+ viewport_rect,+ forced_damage_rect: IntRect::new(0, 0, viewport_rect.width, viewport_rect.height),+ }+ }++ pub fn repainting_changes(viewport_rect: IntRect) -> Self {+ Self {+ viewport_rect,+ forced_damage_rect: IntRect::default(),+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum PresentScheduling {+ /// 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,+}++/// 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.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PresentRequest {+ pub context_id: CompositorContextId,+ /// Empty for a frame at the viewport rect the context is presented at.+ pub viewport_rect: Option<IntRect>,+ pub forced_damage_rect: IntRect,+ pub scheduling: PresentScheduling,+}++/// What the presentation knows of a context as a tick of a display begins.+#[derive(Clone, Copy, Debug, Default)]+pub struct DisplayTickInputs {+ pub context_is_on_tick_display: bool,+ pub present_is_scheduled_on_tick_display: bool,+ pub ui_overlay_fades_need_frame: bool,+ /// Set when the render clock of the context is due a tick now.+ pub clock_tick_interval_in_milliseconds: Option<f64>,+}++#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub struct DisplayTickResult {+ pub presents_on_display: bool,+ /// As of the end of the tick, and without the fades of the UI overlays.+ pub needs_animation_frames: bool,+}++/// The entry points of the host and the object they are called on: `Compositor::RustFFI::FfiCompositorCoreHost`.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiCompositorCoreHost {+ pub host: *mut c_void,+ pub post_message_to_web_content:+ unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),+ pub post_message_to_render_clock_of_web_content:+ unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),+ pub post_message_to_presentation:+ unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),+ pub request_display_ticks: unsafe extern "C" fn(*mut c_void, u64),+ pub set_timer: unsafe extern "C" fn(*mut c_void, u64, ContextTimer, i64),+ pub cancel_timer: unsafe extern "C" fn(*mut c_void, u64, ContextTimer),+}++type PostEncodedMessage = unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>);++pub struct Host(FfiCompositorCoreHost);++impl Host {+ /// # Safety+ ///+ /// `ffi.host` must outlive the `Host`, and none of its entry points may call back into the core.+ pub unsafe fn new(ffi: FfiCompositorCoreHost) -> Self {+ Self(ffi)+ }++ fn post<M: EndpointMessage>(&self, post_encoded_message: PostEncodedMessage, receiver_id: u64, message: M) {+ let (bytes, attachments) = message+ .encode_message()+ .expect("a message of the compositor fits an IPC message");+ let raw_attachments: Vec<RawAttachment> = attachments.into_iter().map(RawAttachment::from_attachment).collect();+ // SAFETY: The host outlives this, copies the bytes and takes every attachment over.+ unsafe {+ post_encoded_message(+ self.0.host,+ receiver_id,+ ak::Span::new(&bytes),+ ak::Span::new(&raw_attachments),+ );+ }+ }++ /// A message for a client that is gone is dropped.+ pub fn post_to_web_content<M: EndpointMessage>(&self, client_id: WebContentClientId, message: M) {+ self.post(self.0.post_message_to_web_content, client_id.0, message);+ }++ /// A client without a render clock channel hears nothing.+ pub fn post_to_render_clock_of_web_content<M: EndpointMessage>(&self, client_id: WebContentClientId, message: M) {+ self.post(self.0.post_message_to_render_clock_of_web_content, client_id.0, message);+ }++ /// A message for a presentation that is gone is dropped.+ pub fn post_to_presentation<M: EndpointMessage>(&self, presentation_id: PresentationId, message: M) {+ self.post(self.0.post_message_to_presentation, presentation_id.0, message);+ }++ /// Display ticks reach a context whose scroll and input logic says it needs animation frames, while it is visible.+ pub fn request_display_ticks(&self, context_id: CompositorContextId) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.request_display_ticks)(self.0.host, context_id.0) };+ }++ /// Each timer of a context fires once after the delay, and setting it again replaces the delay.+ pub fn set_timer(&self, context_id: CompositorContextId, timer: ContextTimer, delay: Duration) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.set_timer)(self.0.host, context_id.0, timer, delay.nanoseconds()) };+ }++ pub fn cancel_timer(&self, context_id: CompositorContextId, timer: ContextTimer) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.cancel_timer)(self.0.host, context_id.0, timer) };+ }+}diff --git a/Services/Compositor/Rust/src/input_event.rs b/Services/Compositor/Rust/src/input_event.rsnew file mode 100644index 00000000000..45274aa5c91--- /dev/null+++ b/Services/Compositor/Rust/src/input_event.rs@@ -0,0 +1,43 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libcompositing_rust::scrolling::{KeyCode, KeyModifier, WheelDeltaPrecision};++pub fn is_keyboard_scroll_key(key: KeyCode, modifiers: u32) -> bool {+ match key {+ KeyCode::Key_Space => {+ modifiers & !(KeyModifier::Mod_Shift | KeyModifier::Mod_Keypad).0 == KeyModifier::Mod_None.0+ }+ KeyCode::Key_Up | KeyCode::Key_Down => {+ let modifiers = modifiers & !KeyModifier::Mod_Keypad.0;+ modifiers == KeyModifier::Mod_None.0 || modifiers == KeyModifier::Mod_PlatformCtrl.0+ }+ KeyCode::Key_PageUp+ | KeyCode::Key_PageDown+ | KeyCode::Key_Left+ | KeyCode::Key_Right+ | KeyCode::Key_Home+ | KeyCode::Key_End => modifiers & !KeyModifier::Mod_Keypad.0 == KeyModifier::Mod_None.0,+ _ => false,+ }+}++// Besides its pixel delta, wheel input counts how far the wheel turned in 120ths of a tick, the unit of the legacy+// wheelDelta. A tick is a wheel notch, or one line on platforms that accelerate the wheel by whole lines. Input that+// reports only a pixel delta counts its ticks from that: a notch scrolls three 40-pixel lines, and precise input has+// no notches, so it counts one tick per 40-pixel line step.+// INTEROP: For macOS touchpad scrolling, Blink, WebKit, and Gecko all report 3 units per pixel; Blink and WebKit+// truncate, Gecko rounds. For the ctrl-wheel events of a pinch, WebKit and Gecko also report 3 units per+// pixel, while Blink reports 120 units per event.+pub fn wheel_tick_120ths_from_pixel_delta(pixel_delta: f64, precision: WheelDeltaPrecision) -> f64 {+ const TICK_120THS_PER_TICK: f64 = 120.0;+ const PIXELS_PER_NOTCH: f64 = 3.0 * 40.0;+ const PIXELS_PER_PRECISE_TICK: f64 = 40.0;+ if precision == WheelDeltaPrecision::Precise {+ return pixel_delta * (TICK_120THS_PER_TICK / PIXELS_PER_PRECISE_TICK);+ }+ pixel_delta * (TICK_120THS_PER_TICK / PIXELS_PER_NOTCH)+}diff --git a/Services/Compositor/Rust/src/keyboard_scroll_controller.rs b/Services/Compositor/Rust/src/keyboard_scroll_controller.rsnew file mode 100644index 00000000000..d9a4b8d1251--- /dev/null+++ b/Services/Compositor/Rust/src/keyboard_scroll_controller.rs@@ -0,0 +1,183 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libcompositing_rust::css_pixels::{CssPixelPoint, CssPixels};+use libcompositing_rust::scrolling::scroll_snap_selection::SnapSelectionStrategyType;+use libcompositing_rust::scrolling::{+ AsyncScrollNodeStableID, AsyncScrollTree, KeyCode, KeyEvent, KeyModifier, KeyboardScrollState,+};+use libgfx_rust::FloatPoint;++pub struct KeyboardScrollController {+ state: KeyboardScrollState,+ held_keys: Vec<KeyCode>,+}++pub struct KeyStep {+ // Where the scroller chain the key scrolls starts.+ pub keyboard_scroll_target: AsyncScrollNodeStableID,+ pub delta: FloatPoint,+ pub scrolls_to_extent: bool,+ pub snap_selection_intent: SnapSelectionStrategyType,+}++impl Default for KeyStep {+ fn default() -> Self {+ Self {+ keyboard_scroll_target: AsyncScrollNodeStableID {+ node_id: Default::default(),+ kind: libcompositing_rust::scrolling::AsyncScrollNodeKind::Element,+ pseudo_element_type: 0,+ },+ delta: Default::default(),+ scrolls_to_extent: false,+ snap_selection_intent: SnapSelectionStrategyType::EndPositionAndDirection,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum KeyRelease {+ Ignored,+ ReleasedWhileOtherKeysAreHeld,+ ReleasedLastHeldKey,+}++impl Default for KeyboardScrollController {+ fn default() -> Self {+ Self {+ state: KeyboardScrollState {+ generation: 0,+ visual_context_tree_structural_epoch: 0,+ target: None,+ page_scroll_distance: 0.0,+ arrow_scroll_distance: 0.0,+ },+ held_keys: Vec::new(),+ }+ }+}++impl KeyboardScrollController {+ pub fn invalidate_state(&mut self, generation: u64) {+ if generation < self.state.generation {+ return;+ }+ self.state.generation = generation;+ self.state.target = None;+ }++ // Returns whether the state is not older than the one already adopted.+ pub fn adopt_state(&mut self, state: KeyboardScrollState) -> bool {+ if state.generation < self.state.generation {+ return false;+ }+ self.state = state;+ true+ }++ pub fn forget_target(&mut self) {+ self.state.target = None;+ }+ pub fn has_target(&self) -> bool {+ self.state.target.is_some()+ }+ pub fn state_matches_visual_context_tree_epoch(&self, visual_context_tree_structural_epoch: u64) -> bool {+ self.state.visual_context_tree_structural_epoch == visual_context_tree_structural_epoch+ }++ pub fn step_for_key(&self, event: &KeyEvent, async_scroll_tree: &AsyncScrollTree) -> Option<KeyStep> {+ assert!(self.state.target.is_some());+ let modifiers_without_keypad = event.modifiers.0 & !KeyModifier::Mod_Keypad.0;+ let scrolls_to_start = event.key == KeyCode::Key_Home+ || (event.key == KeyCode::Key_Up && modifiers_without_keypad == KeyModifier::Mod_PlatformCtrl.0);+ let scrolls_to_end = event.key == KeyCode::Key_End+ || (event.key == KeyCode::Key_Down && modifiers_without_keypad == KeyModifier::Mod_PlatformCtrl.0);+ let scrolls_to_extent = scrolls_to_start || scrolls_to_end;+ let is_arrow = !scrolls_to_extent+ && matches!(+ event.key,+ KeyCode::Key_Up | KeyCode::Key_Down | KeyCode::Key_Left | KeyCode::Key_Right+ );+ let delta = if scrolls_to_extent {+ async_scroll_tree.device_offset_from_css_pixels(CssPixelPoint {+ x: CssPixels::default(),+ y: if scrolls_to_start {+ -CssPixels::from_raw(i32::MAX)+ } else {+ CssPixels::from_raw(i32::MAX)+ },+ })+ } else {+ let mut distance = if is_arrow {+ self.state.arrow_scroll_distance+ } else {+ self.state.page_scroll_distance+ };+ if !distance.is_finite() || distance <= 0.0 {+ return None;+ }+ if matches!(event.key, KeyCode::Key_PageUp | KeyCode::Key_Up | KeyCode::Key_Left)+ || (event.key == KeyCode::Key_Space && !(event.modifiers & KeyModifier::Mod_Shift).is_empty())+ {+ distance = -distance;+ }+ let is_horizontal = matches!(event.key, KeyCode::Key_Left | KeyCode::Key_Right);+ if is_horizontal {+ FloatPoint { x: distance, y: 0.0 }+ } else {+ FloatPoint { x: 0.0, y: distance }+ }+ };++ let mut snap_selection_intent = SnapSelectionStrategyType::EndPositionAndDirection;+ if scrolls_to_extent {+ snap_selection_intent = SnapSelectionStrategyType::EndPosition;+ } else if is_arrow {+ snap_selection_intent = SnapSelectionStrategyType::Direction;+ }++ Some(KeyStep {+ keyboard_scroll_target: self.state.target.unwrap(),+ delta,+ scrolls_to_extent,+ snap_selection_intent,+ })+ }++ pub fn hold_key(&mut self, key: KeyCode) {+ if !self.held_keys.contains(&key) {+ self.held_keys.push(key);+ }+ }++ pub fn release_key(&mut self, event: &KeyEvent) -> KeyRelease {+ if event.repeat {+ return KeyRelease::Ignored;+ }+ let Some(index) = self.held_keys.iter().position(|&key| key == event.key) else {+ return KeyRelease::Ignored;+ };+ self.held_keys.remove(index);+ if self.held_keys.is_empty() {+ return KeyRelease::ReleasedLastHeldKey;+ }+ KeyRelease::ReleasedWhileOtherKeysAreHeld+ }++ // Returns whether any key was held.+ pub fn release_all_keys(&mut self) -> bool {+ if self.held_keys.is_empty() {+ return false;+ }+ self.held_keys.clear();+ true+ }++ pub fn has_held_keys(&self) -> bool {+ !self.held_keys.is_empty()+ }+}diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsnew file mode 100644index 00000000000..36c3b665821--- /dev/null+++ b/Services/Compositor/Rust/src/lib.rs@@ -0,0 +1,30 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The scroll and input logic of the Compositor's contexts, and the routing of input between them.++#[cfg(feature = "allocator")]+extern crate ladybird_allocator;++#[path = "../../../../Libraries/RustDemangle.rs"]+mod rust_demangle;++#[path = "../../../../Libraries/RustPanic.rs"]+mod rust_panic;++pub mod async_scroll_update_outbox;+pub mod elastic_overscroll_controller;+pub mod frame_inputs;+pub mod host;+pub mod input_event;+pub mod keyboard_scroll_controller;+pub mod scroll_fling_controller;+pub mod scroll_snap_controller;+pub mod scrollbar_controller;+pub mod wheel_gesture_routing;++#[cfg(test)]+mod test_stubs;diff --git a/Services/Compositor/Rust/src/scroll_fling_controller.rs b/Services/Compositor/Rust/src/scroll_fling_controller.rsnew file mode 100644index 00000000000..6418dd096d4--- /dev/null+++ b/Services/Compositor/Rust/src/scroll_fling_controller.rs@@ -0,0 +1,153 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Synthesizes the momentum of a touchpad flick as wheel events, for platforms that send no momentum scroll events.++use crate::input_event::wheel_tick_120ths_from_pixel_delta;+use libcompositing_rust::scrolling::scroll_fling::{ScrollFling, ScrollFlingBooster, ScrollVelocityTracker};+use libcompositing_rust::scrolling::{+ DevicePixelPoint, KeyModifier, MouseButton, MouseEvent, MouseEventType, PointerInputData, ScrollGesturePhase,+ WheelDeltaPrecision, WheelGestureMark,+};+use libcompositing_rust::time::MonotonicTime;+use libgfx_rust::FloatPoint;++#[derive(Default)]+pub struct ScrollFlingController {+ velocity_tracker: ScrollVelocityTracker,+ booster: ScrollFlingBooster,+ active_fling: Option<ActiveFling>,+}++struct ActiveFling {+ fling: ScrollFling,+ // The fling steps use the position, modifiers and gesture of the gesture end event.+ position: DevicePixelPoint,+ screen_position: DevicePixelPoint,+ modifiers: KeyModifier,+ wheel_gesture_mark: Option<WheelGestureMark>,+ ends_on_next_step: bool,+}++fn is_touchpad_step(event: &MouseEvent) -> bool {+ event.wheel_delta_precision == WheelDeltaPrecision::Precise+ && event.scroll_gesture_phase == ScrollGesturePhase::Ongoing+}++impl ScrollFlingController {+ pub fn note_wheel_event(&mut self, event: &MouseEvent, now: MonotonicTime) {+ if is_touchpad_step(event) {+ self.velocity_tracker.add_step(+ FloatPoint {+ x: event.wheel_delta_x as f32,+ y: event.wheel_delta_y as f32,+ },+ now,+ );+ return;+ }+ self.velocity_tracker.reset();+ // Other wheel input cancels the boost of the next fling.+ if event.scroll_gesture_phase != ScrollGesturePhase::Ended {+ self.booster.reset();+ }+ }++ // Starts a fling if the gesture that the event ends was a flick.+ pub fn start_if_flicked(&mut self, gesture_end_event: &MouseEvent, now: MonotonicTime) -> bool {+ assert!(gesture_end_event.scroll_gesture_phase == ScrollGesturePhase::Ended);+ let velocity = self.velocity_tracker.velocity_at_lift(now);+ self.velocity_tracker.reset();+ let Some(velocity) = velocity else {+ return false;+ };++ let Some(fling) = ScrollFling::start(self.booster.boosted_velocity(velocity, now), now) else {+ return false;+ };+ self.active_fling = Some(ActiveFling {+ fling,+ 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.clone(),+ ends_on_next_step: false,+ });+ true+ }++ pub fn is_active(&self) -> bool {+ self.active_fling.is_some()+ }++ // The next momentum step of the fling, or the end of its gesture once the fling has run out or was told to end.+ pub fn take_step(&mut self, frame_time: MonotonicTime) -> Option<MouseEvent> {+ let active = self.active_fling.as_mut()?;+ if active.ends_on_next_step {+ return self.end();+ }++ let Some(delta) = active.fling.step(frame_time) else {+ return self.end();+ };+ if delta.is_zero() {+ return None;+ }+ Some(self.event_of_active_fling(delta, ScrollGesturePhase::Momentum))+ }++ pub fn end_on_next_step(&mut self) {+ assert!(self.active_fling.is_some());+ self.active_fling.as_mut().unwrap().ends_on_next_step = true;+ }++ // The end of the gesture of the fling, if one is active.+ pub fn end(&mut self) -> Option<MouseEvent> {+ self.active_fling.as_ref()?;++ // WebContent holds the gesture open while momentum events arrive. The end of the gesture releases it.+ let event = self.event_of_active_fling(FloatPoint::default(), ScrollGesturePhase::Ended);+ self.active_fling = None;+ Some(event)+ }++ // Ends the fling before a wheel event from a new gesture or other input.+ pub fn interrupt(&mut self, event: &MouseEvent, now: MonotonicTime) -> Option<MouseEvent> {+ let active = self.active_fling.as_ref()?;++ // A new touchpad step stops the fling. The next flick can add the velocity of this fling.+ if is_touchpad_step(event) {+ self.booster.fling_was_interrupted(active.fling.velocity_at(now), now);+ }+ self.end()+ }++ fn event_of_active_fling(&self, delta: FloatPoint, phase: ScrollGesturePhase) -> MouseEvent {+ assert!(self.active_fling.is_some());+ let active = self.active_fling.as_ref().unwrap();+ MouseEvent {+ r#type: MouseEventType::MouseWheel,+ position: active.position,+ screen_position: active.screen_position,+ button: MouseButton::None,+ buttons: MouseButton::None,+ modifiers: active.modifiers,+ wheel_delta_x: delta.x as f64,+ wheel_delta_y: delta.y as f64,+ wheel_tick_120ths_x: wheel_tick_120ths_from_pixel_delta(delta.x as f64, WheelDeltaPrecision::Precise),+ wheel_tick_120ths_y: wheel_tick_120ths_from_pixel_delta(delta.y as f64, WheelDeltaPrecision::Precise),+ wheel_delta_precision: WheelDeltaPrecision::Precise,+ scroll_gesture_phase: phase,+ click_count: 0,+ 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,+ scrollbar_dragged_by_compositor: None,+ pointer_data: PointerInputData { properties: None },+ wheel_gesture_mark: active.wheel_gesture_mark.clone(),+ }+ }+}diff --git a/Services/Compositor/Rust/src/scroll_snap_controller.rs b/Services/Compositor/Rust/src/scroll_snap_controller.rsnew file mode 100644index 00000000000..4af40f8386a--- /dev/null+++ b/Services/Compositor/Rust/src/scroll_snap_controller.rs@@ -0,0 +1,655 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! 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.++use libcompositing_rust::css_pixels::{CssPixelPoint, CssPixels};+use libcompositing_rust::scrolling::scroll_snap_selection::{+ MomentumFlingEstimator, SnapAxisCandidates, SnapContainerGeometry, SnapSelectionStrategy,+ SnapSelectionStrategyType, axes_to_evaluate, build_snap_candidates, select_snap_destination_with_candidates,+};+use libcompositing_rust::scrolling::{+ AsyncScrollNodeStableID, AsyncScrollOperationID, AsyncScrollTree, AsyncSnapContainer, ScrollAnimationKind,+ ScrollGesturePhase, ScrollStateSnapshot, SnapDestination, SpatialNodeIndex, StartedUserScroll,+ USER_SCROLL_SETTLE_DELAY,+};+use libcompositing_rust::time::MonotonicTime;+use std::collections::{BTreeMap, HashMap};++#[derive(Default)]+pub struct ScrollSnapController {+ nodes: BTreeMap<AsyncScrollNodeStableID, NodeState>,+ candidates: HashMap<AsyncScrollNodeStableID, SnapAxisCandidates>,+ momentum_snap_position_selection: MomentumSnapPositionSelection,+ momentum_fling_estimator: MomentumFlingEstimator,+}++// A snap scroll to start for a wheel delta.+pub struct SnapScrollStart {+ pub stable_node_id: AsyncScrollNodeStableID,+ pub initial_scroll_offset: CssPixelPoint,+ pub unsnapped_scroll_destination: CssPixelPoint,+ pub relative_scroll_delta: CssPixelPoint,+ pub selection: SnapDestination,+ pub animation_kind: ScrollAnimationKind,+ pub is_absolute_scroll: bool,+}++impl Default for SnapScrollStart {+ fn default() -> Self {+ Self {+ stable_node_id: AsyncScrollNodeStableID {+ node_id: Default::default(),+ kind: libcompositing_rust::scrolling::AsyncScrollNodeKind::Element,+ pseudo_element_type: 0,+ },+ initial_scroll_offset: Default::default(),+ unsnapped_scroll_destination: Default::default(),+ relative_scroll_delta: Default::default(),+ selection: Default::default(),+ animation_kind: ScrollAnimationKind::SmoothScroll,+ 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.+#[derive(Default)]+pub struct StepConsumed {+ pub updated_scroll: Option<StartedUserScroll>,+}++// 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.+pub enum StepDecision {+ StepConsumed(StepConsumed),+ SnapScrollStart(SnapScrollStart),+}++#[derive(Default)]+pub struct GestureEndSnap {+ pub scroll_node_index: SpatialNodeIndex,+ pub snap_scroll: SnapScrollStart,+}++struct InFlightSnapScroll {+ operation_id: AsyncScrollOperationID,+ destination: CssPixelPoint,+}++// 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.+#[derive(Clone, Copy)]+struct GestureStart {+ offset: CssPixelPoint,+ travels_under_momentum: bool,+}++#[derive(Default)]+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.+ unsnapped_scroll_destination: Option<CssPixelPoint>,+ gesture_input_deadline: Option<MonotonicTime>,+ // 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.+ expected_scroll_offset: Option<CssPixelPoint>,+ // The snap scroll of this controller's own that the box is scrolling under.+ snap_scroll: Option<InFlightSnapScroll>,+ gesture_start: Option<GestureStart>,+}++// 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.+#[derive(Default, PartialEq, Eq)]+enum MomentumSnapPositionSelection {+ #[default]+ NotSelectedYet,+ ScrollingToSelectedPosition,+ NoPositionSelected,+}++// A scroll node a snap position can be selected for: one with snap geometry and a current offset.+struct SnapTarget<'a> {+ stable_node_id: AsyncScrollNodeStableID,+ snap_container: &'a AsyncSnapContainer,+ current_scroll_offset: CssPixelPoint,+}++impl ScrollSnapController {+ pub fn did_install_scrolling_state(&mut self, scroll_tree: &AsyncScrollTree) {+ self.candidates.clear();+ self.nodes+ .retain(|stable_node_id, _| scroll_tree.scroll_node_index_for_stable_id(*stable_node_id).is_some());+ }++ // 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.+ pub fn note_gesture_phase(&mut self, phase: ScrollGesturePhase) {+ match phase {+ ScrollGesturePhase::None => self.end_gesture(),+ ScrollGesturePhase::Ongoing => self.reset_momentum_fling_state(),+ ScrollGesturePhase::Momentum | ScrollGesturePhase::Ended => {}+ }+ }++ fn reset_momentum_fling_state(&mut self) {+ self.momentum_snap_position_selection = MomentumSnapPositionSelection::NotSelectedYet;+ self.momentum_fling_estimator.reset();+ }++ fn end_gesture(&mut self) {+ self.reset_momentum_fling_state();+ for state in self.nodes.values_mut() {+ state.gesture_start = None;+ }+ }++ // A gesture whose steps this controller chains awaits its next step until its input deadline passes, and ends+ // once that happens without one.+ pub fn boxes_with_gesture_awaiting_input(&self) -> Vec<AsyncScrollNodeStableID> {+ let mut boxes = Vec::new();+ for (stable_node_id, state) in &self.nodes {+ if state.gesture_input_deadline.is_some() {+ boxes.push(*stable_node_id);+ }+ }+ boxes+ }++ pub fn earliest_gesture_input_deadline(&self) -> Option<MonotonicTime> {+ let mut earliest = None;+ for state in self.nodes.values() {+ let Some(deadline) = state.gesture_input_deadline else {+ continue;+ };+ if earliest.is_none_or(|earliest| deadline < earliest) {+ earliest = Some(deadline);+ }+ }+ earliest+ }++ // Returns the boxes whose gesture ended.+ pub fn end_gestures_whose_input_ran_out(&mut self, now: MonotonicTime) -> Vec<AsyncScrollNodeStableID> {+ let mut ended_boxes = Vec::new();+ for (stable_node_id, state) in &mut self.nodes {+ if state.gesture_input_deadline.is_none_or(|deadline| now <= deadline) {+ continue;+ }+ state.gesture_input_deadline = None;+ state.unsnapped_scroll_destination = None;+ ended_boxes.push(*stable_node_id);+ }+ ended_boxes+ }++ pub fn did_scroll_node_plainly(+ &mut self,+ stable_node_id: AsyncScrollNodeStableID,+ phase: ScrollGesturePhase,+ scroll_offset_before_scroll: CssPixelPoint,+ ) {+ if phase != ScrollGesturePhase::Ongoing && phase != ScrollGesturePhase::Momentum {+ return;+ }+ let state = self.node_state(stable_node_id);+ let gesture_start = state.gesture_start.get_or_insert(GestureStart {+ offset: scroll_offset_before_scroll,+ travels_under_momentum: false,+ });+ if phase == ScrollGesturePhase::Momentum {+ gesture_start.travels_under_momentum = true;+ }+ }++ pub fn did_start_main_thread_scroll(&mut self, stable_node_id: AsyncScrollNodeStableID) {+ // 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.+ self.nodes.remove(&stable_node_id);+ }++ pub fn did_start_snap_scroll(+ &mut self,+ stable_node_id: AsyncScrollNodeStableID,+ operation_id: AsyncScrollOperationID,+ destination: CssPixelPoint,+ ) {+ let state = self.node_state(stable_node_id);+ state.snap_scroll = Some(InFlightSnapScroll {+ operation_id,+ destination,+ });+ state.expected_scroll_offset = Some(destination);+ }++ pub fn did_end_snap_scroll(+ &mut self,+ stable_node_id: AsyncScrollNodeStableID,+ operation_id: AsyncScrollOperationID,+ scroll_offset: Option<CssPixelPoint>,+ ) {+ if !self.is_snap_scroll(stable_node_id, operation_id) {+ return;+ }+ let state = self.node_state(stable_node_id);+ state.snap_scroll = None;+ state.expected_scroll_offset = scroll_offset;+ }++ pub fn did_retarget_scroll(+ &mut self,+ stable_node_id: AsyncScrollNodeStableID,+ operation_id: AsyncScrollOperationID,+ ) {+ // 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 self.is_snap_scroll(stable_node_id, operation_id) {+ self.nodes.remove(&stable_node_id);+ }+ }++ pub fn is_snap_scroll(+ &self,+ stable_node_id: AsyncScrollNodeStableID,+ operation_id: AsyncScrollOperationID,+ ) -> bool {+ self.nodes.get(&stable_node_id).is_some_and(|state| {+ state+ .snap_scroll+ .as_ref()+ .is_some_and(|scroll| scroll.operation_id == operation_id)+ })+ }++ pub fn unsnapped_destination_for_snap_scroll(+ &self,+ stable_node_id: AsyncScrollNodeStableID,+ operation_id: AsyncScrollOperationID,+ ) -> Option<CssPixelPoint> {+ if !self.is_snap_scroll(stable_node_id, operation_id) {+ return None;+ }+ self.nodes.get(&stable_node_id)?.unsnapped_scroll_destination+ }++ fn node_state(&mut self, stable_node_id: AsyncScrollNodeStableID) -> &mut NodeState {+ self.nodes.entry(stable_node_id).or_default()+ }++ fn candidates_for(+ &mut self,+ stable_node_id: AsyncScrollNodeStableID,+ snap_container: &AsyncSnapContainer,+ ) -> &SnapAxisCandidates {+ self.candidates.entry(stable_node_id).or_insert_with(|| {+ build_snap_candidates(+ &snap_container.geometry,+ &snap_container.areas,+ snap_container.geometry.axes,+ )+ })+ }++ fn snap_target_for<'a>(+ scroll_tree: &'a AsyncScrollTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ scroll_node_index: SpatialNodeIndex,+ ) -> Option<SnapTarget<'a>> {+ let node = scroll_tree.scroll_node_for_index(scroll_node_index);+ let snap_container = scroll_tree.snap_container_for_node(scroll_node_index);+ let current_scroll_offset = scroll_tree.css_scroll_offset_for_node(scroll_node_index, scroll_state_snapshot);+ let snap_container = snap_container?;+ if snap_container.geometry.min_scroll_offset.x > snap_container.geometry.max_scroll_offset.x+ || snap_container.geometry.min_scroll_offset.y > snap_container.geometry.max_scroll_offset.y+ {+ return None;+ }+ Some(SnapTarget {+ stable_node_id: node?.stable_node_id,+ snap_container,+ current_scroll_offset: current_scroll_offset?,+ })+ }+}++fn clamp_scroll_offset(offset: CssPixelPoint, geometry: &SnapContainerGeometry) -> CssPixelPoint {+ CssPixelPoint {+ x: offset+ .x+ .clamp(geometry.min_scroll_offset.x, geometry.max_scroll_offset.x),+ y: offset+ .y+ .clamp(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.+fn selected_snap_position_along_travel(selection: &SnapDestination, displacement: CssPixelPoint) -> bool {+ (selection.snapped_x && displacement.x != CssPixels::default())+ || (selection.snapped_y && displacement.y != CssPixels::default())+}++impl ScrollSnapController {+ // https://drafts.csswg.org/css-scroll-snap-1/#scroll-types+ // A discrete wheel step is a relative scroll with only an intended direction.+ #[allow(clippy::too_many_arguments)]+ pub fn decide_discrete_step(+ &mut self,+ scroll_tree: &AsyncScrollTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ scroll_node_index: SpatialNodeIndex,+ delta: CssPixelPoint,+ scroll_in_flight_destination: Option<CssPixelPoint>,+ now: MonotonicTime,+ ) -> Option<StepDecision> {+ let target = Self::snap_target_for(scroll_tree, scroll_state_snapshot, scroll_node_index)?;+ let 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 != CssPixels::default())+ && !(geometry.axes.y && delta.y != CssPixels::default())+ {+ return None;+ }++ let current_scroll_offset = target.current_scroll_offset;+ let state = self.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.+ let gesture_ended = state.gesture_input_deadline.is_some_and(|deadline| now > deadline)+ || (state.snap_scroll.is_none() && state.expected_scroll_offset != Some(current_scroll_offset));+ if gesture_ended {+ state.unsnapped_scroll_destination = None;+ }+ // 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.+ let step_start = state+ .unsnapped_scroll_destination+ .unwrap_or(scroll_in_flight_destination.unwrap_or(current_scroll_offset));+ let unsnapped_destination = clamp_scroll_offset(step_start.translated(delta.x, delta.y), geometry);++ // NB: A step with only an intended direction ignores every snap position up to the offset its input asked for.+ let strategy = SnapSelectionStrategy {+ r#type: SnapSelectionStrategyType::Direction,+ start_offset: Some(step_start),+ displacement: delta,+ starting_positions_boundary: Some(unsnapped_destination),+ };+ let evaluated_axes = axes_to_evaluate(geometry.axes, &strategy);+ let selection = select_snap_destination_with_candidates(+ geometry,+ self.candidates_for(target.stable_node_id, target.snap_container),+ unsnapped_destination,+ &strategy,+ evaluated_axes,+ );+ if !selected_snap_position_along_travel(&selection, delta) {+ return None;+ }++ let state = self.nodes.get_mut(&target.stable_node_id).unwrap();+ state.unsnapped_scroll_destination = Some(unsnapped_destination);+ state.gesture_input_deadline = Some(now + USER_SCROLL_SETTLE_DELAY);+ let mut in_flight_destination = state.snap_scroll.as_ref().map(|scroll| scroll.destination);+ if in_flight_destination.is_none() {+ in_flight_destination = scroll_in_flight_destination;+ }+ if selection.position == in_flight_destination.unwrap_or(current_scroll_offset) {+ if state.snap_scroll.is_none() {+ state.expected_scroll_offset = Some(current_scroll_offset);+ }+ return Some(StepDecision::StepConsumed(StepConsumed::default()));+ }+ Some(StepDecision::SnapScrollStart(SnapScrollStart {+ stable_node_id: target.stable_node_id,+ initial_scroll_offset: current_scroll_offset,+ unsnapped_scroll_destination: unsnapped_destination,+ relative_scroll_delta: CssPixelPoint {+ x: unsnapped_destination.x - step_start.x,+ y: unsnapped_destination.y - step_start.y,+ },+ selection,+ animation_kind: ScrollAnimationKind::SmoothScroll,+ is_absolute_scroll: false,+ }))+ }++ // 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.+ #[allow(clippy::too_many_arguments)]+ pub fn decide_key_step(+ &mut self,+ scroll_tree: &AsyncScrollTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ scroll_node_index: SpatialNodeIndex,+ delta: CssPixelPoint,+ strategy_type: SnapSelectionStrategyType,+ scroll_in_flight_destination: Option<CssPixelPoint>,+ now: MonotonicTime,+ ) -> Option<StepDecision> {+ let target = Self::snap_target_for(scroll_tree, scroll_state_snapshot, scroll_node_index)?;+ let geometry = &target.snap_container.geometry;+ if !(geometry.axes.x && delta.x != CssPixels::default())+ && !(geometry.axes.y && delta.y != CssPixels::default())+ {+ return None;+ }++ let current_scroll_offset = target.current_scroll_offset;+ let state = self.node_state(target.stable_node_id);+ let mut in_flight_destination = state.snap_scroll.as_ref().map(|scroll| scroll.destination);+ if in_flight_destination.is_none() {+ in_flight_destination = scroll_in_flight_destination;+ }+ let step_start = if let Some(snap_scroll) = state.snap_scroll.as_ref() {+ state.unsnapped_scroll_destination.unwrap_or(snap_scroll.destination)+ } else {+ scroll_in_flight_destination.unwrap_or(current_scroll_offset)+ };+ let unsnapped_destination = clamp_scroll_offset(step_start.translated(delta.x, delta.y), geometry);++ let mut strategy = SnapSelectionStrategy {+ r#type: strategy_type,+ start_offset: Some(step_start),+ displacement: delta,+ starting_positions_boundary: None,+ };+ if strategy_type == SnapSelectionStrategyType::Direction {+ strategy.starting_positions_boundary = Some(unsnapped_destination);+ }+ let evaluated_axes = axes_to_evaluate(geometry.axes, &strategy);+ let selection = select_snap_destination_with_candidates(+ geometry,+ self.candidates_for(target.stable_node_id, target.snap_container),+ unsnapped_destination,+ &strategy,+ evaluated_axes,+ );+ if !selected_snap_position_along_travel(&selection, delta) {+ return None;+ }++ let state = self.nodes.get_mut(&target.stable_node_id).unwrap();+ state.unsnapped_scroll_destination = Some(unsnapped_destination);+ state.gesture_input_deadline = Some(now + USER_SCROLL_SETTLE_DELAY);+ if selection.position == in_flight_destination.unwrap_or(current_scroll_offset) {+ if state.snap_scroll.is_none() {+ state.expected_scroll_offset = Some(current_scroll_offset);+ }+ let updated_scroll = state.snap_scroll.as_ref().map(|snap_scroll| StartedUserScroll {+ stable_node_id: target.stable_node_id,+ operation_id: snap_scroll.operation_id,+ initial_scroll_offset: current_scroll_offset,+ unsnapped_scroll_destination: unsnapped_destination,+ relative_scroll_delta: CssPixelPoint {+ x: unsnapped_destination.x - step_start.x,+ y: unsnapped_destination.y - step_start.y,+ },+ selection,+ settles_gesture: false,+ is_absolute_scroll: false,+ animation_kind: None,+ });+ return Some(StepDecision::StepConsumed(StepConsumed { updated_scroll }));+ }+ Some(StepDecision::SnapScrollStart(SnapScrollStart {+ stable_node_id: target.stable_node_id,+ initial_scroll_offset: current_scroll_offset,+ unsnapped_scroll_destination: unsnapped_destination,+ relative_scroll_delta: CssPixelPoint {+ x: unsnapped_destination.x - step_start.x,+ y: unsnapped_destination.y - step_start.y,+ },+ selection,+ animation_kind: ScrollAnimationKind::SmoothScroll,+ is_absolute_scroll: false,+ }))+ }++ // 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.+ pub fn decide_momentum_delta(+ &mut self,+ scroll_tree: &AsyncScrollTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ scroll_node_index: SpatialNodeIndex,+ momentum_delta: CssPixelPoint,+ ) -> Option<StepDecision> {+ if self.momentum_snap_position_selection == MomentumSnapPositionSelection::ScrollingToSelectedPosition {+ return Some(StepDecision::StepConsumed(StepConsumed::default()));+ }+ if self.momentum_snap_position_selection == MomentumSnapPositionSelection::NoPositionSelected {+ return None;+ }+ let remaining_displacement = self+ .momentum_fling_estimator+ .estimate_remaining_displacement(momentum_delta)?;+ let Some(target) = Self::snap_target_for(scroll_tree, scroll_state_snapshot, scroll_node_index) else {+ self.momentum_snap_position_selection = MomentumSnapPositionSelection::NoPositionSelected;+ return None;+ };+ let geometry = &target.snap_container.geometry;+ let state = self.node_state(target.stable_node_id);+ // The momentum travels on from the snap position a snap scroll already in flight is headed for.+ let in_flight_destination = state.snap_scroll.as_ref().map(|scroll| scroll.destination);+ let step_start = in_flight_destination.unwrap_or(target.current_scroll_offset);+ let unsnapped_destination = clamp_scroll_offset(+ step_start.translated(remaining_displacement.x, remaining_displacement.y),+ geometry,+ );++ let strategy = SnapSelectionStrategy {+ r#type: SnapSelectionStrategyType::EndPositionAndDirection,+ start_offset: Some(step_start),+ displacement: remaining_displacement,+ starting_positions_boundary: None,+ };+ let evaluated_axes = axes_to_evaluate(geometry.axes, &strategy);+ let selection = select_snap_destination_with_candidates(+ geometry,+ self.candidates_for(target.stable_node_id, target.snap_container),+ unsnapped_destination,+ &strategy,+ evaluated_axes,+ );+ if !selected_snap_position_along_travel(&selection, remaining_displacement) {+ self.momentum_snap_position_selection = MomentumSnapPositionSelection::NoPositionSelected;+ return None;+ }+ self.momentum_snap_position_selection = MomentumSnapPositionSelection::ScrollingToSelectedPosition;+ if selection.position == step_start {+ return Some(StepDecision::StepConsumed(StepConsumed::default()));+ }+ Some(StepDecision::SnapScrollStart(SnapScrollStart {+ stable_node_id: target.stable_node_id,+ initial_scroll_offset: target.current_scroll_offset,+ unsnapped_scroll_destination: unsnapped_destination,+ relative_scroll_delta: CssPixelPoint {+ x: unsnapped_destination.x - step_start.x,+ y: unsnapped_destination.y - step_start.y,+ },+ selection,+ animation_kind: ScrollAnimationKind::Momentum,+ is_absolute_scroll: false,+ }))+ }++ // The end of a gesture snaps each scrolling box it panned to the snap position nearest where it was released,+ // and ends the gesture.+ pub fn decide_gesture_end(+ &mut self,+ scroll_tree: &AsyncScrollTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ ) -> Vec<GestureEndSnap> {+ let mut snaps = Vec::new();+ for (stable_node_id, state) in &self.nodes {+ let Some(gesture_start) = state.gesture_start else {+ continue;+ };+ // Momentum that selected a snap position is still scrolling to it.+ if state.snap_scroll.is_some() {+ continue;+ }+ let stable_node_id = *stable_node_id;+ let Some(scroll_node_index) = scroll_tree.scroll_node_index_for_stable_id(stable_node_id) else {+ continue;+ };+ let Some(target) = Self::snap_target_for(scroll_tree, scroll_state_snapshot, scroll_node_index) else {+ continue;+ };+ let geometry = &target.snap_container.geometry;+ let 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.+ let strategy = SnapSelectionStrategy {+ r#type: SnapSelectionStrategyType::EndPosition,+ start_offset: if gesture_start.travels_under_momentum {+ Some(gesture_start.offset)+ } else {+ None+ },+ displacement: CssPixelPoint {+ x: current_scroll_offset.x - gesture_start.offset.x,+ y: current_scroll_offset.y - gesture_start.offset.y,+ },+ starting_positions_boundary: None,+ };+ let evaluated_axes = axes_to_evaluate(geometry.axes, &strategy);+ if evaluated_axes.is_empty() {+ continue;+ }+ let selection = select_snap_destination_with_candidates(+ geometry,+ self.candidates+ .entry(stable_node_id)+ .or_insert_with(|| build_snap_candidates(geometry, &target.snap_container.areas, geometry.axes)),+ current_scroll_offset,+ &strategy,+ evaluated_axes,+ );+ if selection.position == current_scroll_offset {+ continue;+ }+ snaps.push(GestureEndSnap {+ scroll_node_index,+ snap_scroll: SnapScrollStart {+ stable_node_id,+ initial_scroll_offset: current_scroll_offset,+ unsnapped_scroll_destination: current_scroll_offset,+ relative_scroll_delta: CssPixelPoint::default(),+ selection,+ animation_kind: ScrollAnimationKind::SmoothScroll,+ is_absolute_scroll: false,+ },+ });+ }+ self.end_gesture();+ snaps+ }+}diff --git a/Services/Compositor/Rust/src/scrollbar_controller.rs b/Services/Compositor/Rust/src/scrollbar_controller.rsnew file mode 100644index 00000000000..72e4a06ab0a--- /dev/null+++ b/Services/Compositor/Rust/src/scrollbar_controller.rs@@ -0,0 +1,799 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use crate::frame_inputs::{ScrollbarOfFrame, thumb_rect_kept_inside_track};+use libcompositing_rust::scrolling::overlay_fade::OverlayFade;+use libcompositing_rust::scrolling::{+ AccumulatedVisualContextTree, AsyncScrollNodeStableID, AsyncScrollTree, AsyncScrollbar, ClipBehavior,+ CompositorContextId, IncludeVisualViewportTransform, OverlayScrollbarVisibility, ScrollStateSnapshot,+ ScrollbarDraggedByCompositor, SpatialNodeIndex,+};+use libcompositing_rust::time::{Duration, MonotonicTime};+use libgfx_rust::{FloatPoint, FloatRect, IntRect, Orientation, enclosing_int_rect};++#[derive(Default)]+pub struct ScrollbarController {+ scrollbars: Vec<AsyncScrollbar>,+ // One for each scrollbar, in the same order.+ visibilities: Vec<Visibility>,+ hovered_scrollbar_index: Option<usize>,+ captured_scrollbar_index: Option<usize>,+ thumb_grab_position: f32,+ last_primary_position_of_captured_drag: f32,+ scrollbars_always_shown: bool,+}++#[derive(Default)]+pub struct Drag {+ pub scrollbar_index: usize,+ pub primary_position: f32,+ pub thumb_grab_position: f32,+ // Whether this is the press that began the drag, beside the thumb rather than on it.+ pub is_press_beside_thumb: bool,+}++#[derive(Default)]+pub struct ScrollOffset {+ pub scroll_node_index: SpatialNodeIndex,+ pub scroll_offset: FloatPoint,+}++#[derive(Default)]+struct Visibility {+ fade: OverlayFade,+ // The scroll offset of the scroller as of the last update, which a scroll changes.+ scroll_offset: Option<FloatPoint>,+ is_held_shown: bool,+ fade_out_time: Option<MonotonicTime>,+ // How far the scrollbar has grown from its thin geometry to its expanded one.+ expansion: OverlayFade,+ // Whether the main thread was last told that the scrollbar has faded out.+ reported_hidden: bool,+}++impl Clone for Visibility {+ fn clone(&self) -> Self {+ Self {+ fade: self.fade,+ scroll_offset: self.scroll_offset,+ is_held_shown: self.is_held_shown,+ fade_out_time: self.fade_out_time,+ expansion: self.expansion,+ reported_hidden: self.reported_hidden,+ }+ }+}++fn orientation_for_scrollbar(scrollbar: &AsyncScrollbar) -> Orientation {+ if scrollbar.vertical {+ Orientation::Vertical+ } else {+ 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 {+ scroller_stable_node_id: Option<AsyncScrollNodeStableID>,+ scroll_node_index: SpatialNodeIndex,+ vertical: bool,+}++fn scrollbar_identity(scrollbar: &AsyncScrollbar) -> ScrollbarIdentity {+ ScrollbarIdentity {+ scroller_stable_node_id: scrollbar.scroller_stable_node_id,+ scroll_node_index: scrollbar.scroll_node_index,+ vertical: scrollbar.vertical,+ }+}++fn scrollbar_identity_at(scrollbars: &[AsyncScrollbar], scrollbar_index: Option<usize>) -> Option<ScrollbarIdentity> {+ Some(scrollbar_identity(scrollbars.get(scrollbar_index?)?))+}++fn scrollbar_has_identity(scrollbar: &AsyncScrollbar, identity: &ScrollbarIdentity) -> bool {+ if scrollbar.vertical != identity.vertical {+ return false;+ }+ if let (Some(scroller), Some(identity)) = (scrollbar.scroller_stable_node_id, identity.scroller_stable_node_id) {+ return scroller == identity;+ }+ scrollbar.scroll_node_index == identity.scroll_node_index+}++fn find_scrollbar_index(scrollbars: &[AsyncScrollbar], identity: &ScrollbarIdentity) -> Option<usize> {+ scrollbars+ .iter()+ .position(|scrollbar| scrollbar_has_identity(scrollbar, identity))+}++// The rects of a scrollbar the compositor paints are in the viewport's space already.+fn position_in_space_of_scrollbar(+ scrollbar: &AsyncScrollbar,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ position: FloatPoint,+ clip_behavior: ClipBehavior,+) -> Option<FloatPoint> {+ if scrollbar.is_painted_by_compositor {+ return Some(position);+ }+ if !visual_context_tree.context_is_valid(scrollbar.context) {+ return None;+ }+ visual_context_tree.transform_point_for_hit_test(scrollbar.context, position, scroll_state_snapshot, clip_behavior)+}++fn scrollbar_gutter_rect(scrollbar: &AsyncScrollbar, expanded: bool) -> IntRect {+ if expanded {+ scrollbar.expanded_gutter_rect+ } else {+ scrollbar.gutter_rect+ }+}++fn scrollbar_scroll_size(scrollbar: &AsyncScrollbar, expanded: bool) -> f64 {+ if expanded {+ scrollbar.expanded_scroll_size+ } else {+ scrollbar.scroll_size+ }+}++fn translated_thumb_rect(scrollbar: &AsyncScrollbar, scroll_offset: FloatPoint, expanded: bool) -> IntRect {+ let orientation = orientation_for_scrollbar(scrollbar);+ let mut thumb_rect = if expanded {+ scrollbar.expanded_thumb_rect+ } else {+ scrollbar.thumb_rect+ };+ thumb_rect.translate_primary_offset_for_orientation(+ orientation,+ (scroll_offset.primary_offset_for_orientation(orientation) as f64 * scrollbar_scroll_size(scrollbar, expanded))+ as i32,+ );+ thumb_rect+}++fn translated_thumb_rect_with_snapshot(+ scrollbar: &AsyncScrollbar,+ scroll_state_snapshot: &ScrollStateSnapshot,+ expanded: bool,+) -> IntRect {+ let mut thumb_rect = if expanded {+ scrollbar.expanded_thumb_rect+ } else {+ scrollbar.thumb_rect+ };+ let scroll_size = scrollbar_scroll_size(scrollbar, expanded);+ let device_offset = scroll_state_snapshot.device_offset_for_index(scrollbar.scroll_node_index);+ if scrollbar.vertical {+ thumb_rect.y += ((-device_offset.y) as f64 * scroll_size) as i32;+ } else {+ thumb_rect.x += ((-device_offset.x) as f64 * scroll_size) as i32;+ }+ thumb_rect+}++fn scrollbar_hit_rect(scrollbar: &AsyncScrollbar, scroll_offset: FloatPoint) -> IntRect {+ const SCROLLBAR_HIT_SLOP: i32 = 4;+ let mut rect = translated_thumb_rect(scrollbar, scroll_offset, false).united(translated_thumb_rect(+ scrollbar,+ scroll_offset,+ true,+ ));+ let expanded_gutter_rect = scrollbar_gutter_rect(scrollbar, true);+ if !expanded_gutter_rect.is_empty() {+ rect = rect.united(expanded_gutter_rect);+ }+ rect.inflated(SCROLLBAR_HIT_SLOP, SCROLLBAR_HIT_SLOP)+}++impl ScrollbarController {+ // 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.+ pub const SHOWN_DURATION_AFTER_ACTIVITY: Duration = Duration::from_milliseconds(1000);++ // Tests see every scrollbar at all times, as when it is shown depends on the time.+ pub fn new(scrollbars_always_shown: bool) -> Self {+ Self {+ scrollbars_always_shown,+ ..Default::default()+ }+ }++ pub fn clear(&mut self) {+ self.scrollbars.clear();+ self.visibilities.clear();+ self.hovered_scrollbar_index = None;+ self.captured_scrollbar_index = None;+ self.thumb_grab_position = 0.0;+ self.last_primary_position_of_captured_drag = 0.0;+ }++ pub fn set_scrollbars(&mut self, scrollbars: &[AsyncScrollbar]) {+ let hovered_scrollbar_identity = scrollbar_identity_at(&self.scrollbars, self.hovered_scrollbar_index);+ let captured_scrollbar_identity = scrollbar_identity_at(&self.scrollbars, self.captured_scrollbar_index);++ let mut visibilities = Vec::with_capacity(scrollbars.len());+ for scrollbar in scrollbars {+ let previous_index = find_scrollbar_index(&self.scrollbars, &scrollbar_identity(scrollbar));+ visibilities+ .push(previous_index.map_or_else(Visibility::default, |index| self.visibilities[index].clone()));+ }++ self.scrollbars = scrollbars.to_vec();+ self.visibilities = visibilities;+ self.hovered_scrollbar_index =+ hovered_scrollbar_identity.and_then(|identity| find_scrollbar_index(&self.scrollbars, &identity));+ self.captured_scrollbar_index =+ captured_scrollbar_identity.and_then(|identity| find_scrollbar_index(&self.scrollbars, &identity));+ if self.captured_scrollbar_index.is_none() {+ self.thumb_grab_position = 0.0;+ }+ }++ pub fn is_empty(&self) -> bool {+ self.scrollbars.is_empty()+ }+ pub fn scrollbars(&self) -> &[AsyncScrollbar] {+ &self.scrollbars+ }+ pub fn has_captured_scrollbar(&self) -> bool {+ self.captured_scrollbar_index.is_some()+ }+ pub fn captured_scrollbar_index(&self) -> Option<usize> {+ self.captured_scrollbar_index+ }+ // Whether the scrollbar is shown, rather than hidden until its scroller next scrolls.+ pub fn is_shown(&self, scrollbar_index: usize) -> bool {+ self.opacity(scrollbar_index) > 0.0+ }++ // 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.+ pub fn captured_scrollbar_painted_by_display_list(+ &self,+ context_id: CompositorContextId,+ ) -> Option<ScrollbarDraggedByCompositor> {+ let scrollbar = self.scrollbars.get(self.captured_scrollbar_index?)?;+ if scrollbar.is_painted_by_compositor || scrollbar.scroller_stable_node_id.is_none() {+ return None;+ }+ Some(ScrollbarDraggedByCompositor {+ context_id,+ scroller_stable_node_id: scrollbar.scroller_stable_node_id?,+ })+ }++ pub fn hit_test_scrollbar_painted_by_compositor(+ &self,+ async_scroll_tree: &AsyncScrollTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ position: FloatPoint,+ ) -> Option<usize> {+ for (i, scrollbar) in self.scrollbars.iter().enumerate() {+ if !scrollbar.is_painted_by_compositor {+ continue;+ }+ let Some(scroll_offset) =+ async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot)+ else {+ continue;+ };+ if scrollbar_hit_rect(scrollbar, scroll_offset)+ .to_float()+ .contains_point(position)+ {+ return Some(i);+ }+ }+ None+ }++ // 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.+ // A scrollbar the display list paints takes the pointer where it is presented, unless something that takes pointer+ // input is painted over it there.+ pub fn hit_test_scrollbar_painted_by_display_list(+ &self,+ async_scroll_tree: &AsyncScrollTree,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ position: FloatPoint,+ ) -> Option<usize> {+ for (i, scrollbar) in self.scrollbars.iter().enumerate().rev() {+ if scrollbar.is_painted_by_compositor || scrollbar.scroller_stable_node_id.is_none() || !self.is_shown(i) {+ continue;+ }+ if async_scroll_tree+ .scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot)+ .is_none()+ {+ continue;+ }++ let Some(position_in_scrollbar_space) = position_in_space_of_scrollbar(+ scrollbar,+ visual_context_tree,+ scroll_state_snapshot,+ position,+ ClipBehavior::Respect,+ ) else {+ continue;+ };+ let presented_scrollbar_rect = if self.expansion(i) > 0.0 {+ scrollbar.expanded_gutter_rect+ } else {+ scrollbar.track_rect+ };+ if !presented_scrollbar_rect+ .to_float()+ .contains_point(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 None;+ }+ return Some(i);+ }+ None+ }++ pub fn begin_drag(+ &mut self,+ async_scroll_tree: &AsyncScrollTree,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ position: FloatPoint,+ ) -> Option<Drag> {+ let mut scrollbar_index =+ self.hit_test_scrollbar_painted_by_compositor(async_scroll_tree, scroll_state_snapshot, position);+ if scrollbar_index.is_none() {+ scrollbar_index = self.hit_test_scrollbar_painted_by_display_list(+ async_scroll_tree,+ visual_context_tree,+ scroll_state_snapshot,+ position,+ );+ }+ // INTEROP: A scrollbar that has faded out takes no press, as in Chromium.+ let scrollbar_index = scrollbar_index?;+ if self.opacity(scrollbar_index) <= 0.0 {+ return None;+ }++ let scrollbar = &self.scrollbars[scrollbar_index];+ let scroll_offset =+ async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot);+ assert!(scroll_offset.is_some());+ let position_in_scrollbar_space = position_in_space_of_scrollbar(+ scrollbar,+ visual_context_tree,+ scroll_state_snapshot,+ position,+ ClipBehavior::Respect,+ );+ assert!(position_in_scrollbar_space.is_some());++ let orientation = orientation_for_scrollbar(scrollbar);+ // A successful press captures and expands the scrollbar before its drag delta is applied.+ let expanded = true;+ let thumb_rect = translated_thumb_rect(scrollbar, scroll_offset.unwrap(), expanded);+ let thumb_hit_rect = thumb_rect.to_float();++ let primary_position = position_in_scrollbar_space+ .unwrap()+ .primary_offset_for_orientation(orientation);+ let position_is_along_thumb = if orientation == Orientation::Vertical {+ thumb_hit_rect.contains_vertically(primary_position)+ } else {+ thumb_hit_rect.contains_horizontally(primary_position)+ };+ let thumb_grab_position = if position_is_along_thumb {+ primary_position - thumb_rect.primary_offset_for_orientation(orientation) as f32+ } else {+ let gutter_rect = scrollbar_gutter_rect(scrollbar, true);+ let thumb_size = thumb_rect.primary_size_for_orientation(orientation) as f32;+ let gutter_start = gutter_rect.primary_offset_for_orientation(orientation) as f32;+ let gutter_size = gutter_rect.primary_size_for_orientation(orientation) as f32;+ let offset_relative_to_gutter = primary_position - gutter_start;+ max(+ min(offset_relative_to_gutter, thumb_size / 2.0),+ offset_relative_to_gutter - gutter_size + thumb_size,+ )+ };++ self.captured_scrollbar_index = Some(scrollbar_index);+ self.hovered_scrollbar_index = Some(scrollbar_index);+ self.thumb_grab_position = thumb_grab_position;+ self.last_primary_position_of_captured_drag = primary_position;+ Some(Drag {+ scrollbar_index,+ primary_position,+ thumb_grab_position,+ is_press_beside_thumb: !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.+ fn primary_position_of_captured_drag(+ &mut self,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ position: FloatPoint,+ ) -> f32 {+ if let Some(scrollbar) = self+ .captured_scrollbar_index+ .and_then(|index| self.scrollbars.get(index))+ && let Some(position_in_scrollbar_space) = position_in_space_of_scrollbar(+ scrollbar,+ visual_context_tree,+ scroll_state_snapshot,+ position,+ ClipBehavior::Ignore,+ )+ {+ self.last_primary_position_of_captured_drag =+ position_in_scrollbar_space.primary_offset_for_orientation(orientation_for_scrollbar(scrollbar));+ }+ self.last_primary_position_of_captured_drag+ }++ pub fn captured_drag(+ &mut self,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ position: FloatPoint,+ ) -> Option<Drag> {+ let scrollbar_index = self.captured_scrollbar_index?;+ let primary_position =+ self.primary_position_of_captured_drag(visual_context_tree, scroll_state_snapshot, position);+ Some(Drag {+ scrollbar_index,+ primary_position,+ thumb_grab_position: self.thumb_grab_position,+ ..Default::default()+ })+ }++ pub fn release_captured_drag(+ &mut self,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ position: FloatPoint,+ ) -> Option<Drag> {+ let scrollbar_index = self.captured_scrollbar_index?;+ let thumb_grab_position = self.thumb_grab_position;+ let primary_position =+ self.primary_position_of_captured_drag(visual_context_tree, scroll_state_snapshot, position);+ self.captured_scrollbar_index = None;+ self.thumb_grab_position = 0.0;+ Some(Drag {+ scrollbar_index,+ primary_position,+ thumb_grab_position,+ ..Default::default()+ })+ }++ pub fn set_hovered_scrollbar(&mut self, scrollbar_index: Option<usize>) -> bool {+ if self.hovered_scrollbar_index == scrollbar_index {+ return false;+ }+ self.hovered_scrollbar_index = scrollbar_index;+ true+ }++ pub fn scroll_offset_for_drag(+ &self,+ async_scroll_tree: &AsyncScrollTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ drag: &Drag,+ ) -> Option<ScrollOffset> {+ let scrollbar = self.scrollbars.get(drag.scrollbar_index)?;+ let expanded = self.is_expanded(drag.scrollbar_index);+ let scroll_size = scrollbar_scroll_size(scrollbar, expanded);+ if scroll_size == 0.0 {+ return None;+ }++ let current_scroll_offset =+ async_scroll_tree.scroll_offset_for_node(scrollbar.scroll_node_index, scroll_state_snapshot)?;+ let orientation = orientation_for_scrollbar(scrollbar);+ let thumb_rect = if expanded {+ scrollbar.expanded_thumb_rect+ } else {+ scrollbar.thumb_rect+ };+ let zero_offset_thumb_position = thumb_rect.primary_offset_for_orientation(orientation) as f32;+ let min_thumb_position = zero_offset_thumb_position + scrollbar.min_scroll_offset * scroll_size as f32;+ let max_thumb_position = zero_offset_thumb_position + scrollbar.max_scroll_offset * scroll_size as f32;+ if min_thumb_position.is_nan() || max_thumb_position.is_nan() || max_thumb_position < min_thumb_position {+ return None;+ }+ let target_thumb_position = clamp(+ drag.primary_position - drag.thumb_grab_position,+ min_thumb_position,+ max_thumb_position,+ );+ let mut target_scroll_offset = (target_thumb_position - zero_offset_thumb_position) / scroll_size as f32;+ // 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;+ }++ let mut scroll_offset = current_scroll_offset;+ scroll_offset.set_primary_offset_for_orientation(orientation, target_scroll_offset);+ Some(ScrollOffset {+ scroll_node_index: scrollbar.scroll_node_index,+ scroll_offset,+ })+ }++ // 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.+ pub fn paging_direction(&self, scrollbar_index: usize, primary_position: f32, scroll_offset: FloatPoint) -> i32 {+ let Some(scrollbar) = self.scrollbars.get(scrollbar_index) else {+ return 0;+ };+ let orientation = orientation_for_scrollbar(scrollbar);+ let thumb_rect = translated_thumb_rect(scrollbar, scroll_offset, self.is_expanded(scrollbar_index));+ if primary_position < thumb_rect.primary_offset_for_orientation(orientation) as f32 {+ return -1;+ }+ if primary_position+ >= (thumb_rect.primary_offset_for_orientation(orientation)+ + thumb_rect.primary_size_for_orientation(orientation)) as f32+ {+ return 1;+ }+ 0+ }++ // 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.+ pub fn update_visibility(&mut self, scroll_state_snapshot: &ScrollStateSnapshot, now: MonotonicTime) {+ for i in 0..self.scrollbars.len() {+ let expanded = self.is_expanded(i);+ let visibility = &mut self.visibilities[i];+ let scrollbar = &self.scrollbars[i];+ let scroll_offset = scroll_state_snapshot.device_offset_for_index(scrollbar.scroll_node_index);+ let scrolled = visibility.scroll_offset.is_some_and(|offset| offset != scroll_offset);+ visibility.scroll_offset = Some(scroll_offset);++ let was_held_shown = visibility.is_held_shown;+ // Hovering a hidden scrollbar does not show it. Only a scroll does.+ visibility.is_held_shown = expanded && (scrolled || visibility.fade.opacity() > 0.0);+ if visibility.is_held_shown {+ visibility.fade.jump_to(1.0);+ visibility.fade_out_time = None;+ visibility.expansion.fade_to(1.0, now);+ continue;+ }+ if scrolled {+ visibility.fade.jump_to(1.0);+ }+ if scrolled || was_held_shown {+ visibility.fade_out_time = Some(now + Self::SHOWN_DURATION_AFTER_ACTIVITY);+ }+ }+ }++ // When the next scrollbar starts to fade out.+ pub fn next_fade_out_time(&self) -> Option<MonotonicTime> {+ let mut next_fade_out_time = None;+ for visibility in &self.visibilities {+ if let Some(time) = visibility.fade_out_time+ && next_fade_out_time.is_none_or(|next| time < next)+ {+ next_fade_out_time = Some(time);+ }+ }+ next_fade_out_time+ }++ // 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.+ pub fn take_visibility_changes(&mut self) -> Vec<OverlayScrollbarVisibility> {+ let mut changes = Vec::new();+ for i in 0..self.scrollbars.len() {+ let hidden = self.opacity(i) <= 0.0;+ let scrollbar = &self.scrollbars[i];+ let visibility = &mut self.visibilities[i];+ let Some(scroller_stable_node_id) = scrollbar.scroller_stable_node_id else {+ continue;+ };+ if hidden == visibility.reported_hidden {+ continue;+ }+ visibility.reported_hidden = hidden;+ changes.push(OverlayScrollbarVisibility {+ scroller_stable_node_id,+ vertical: scrollbar.vertical,+ hidden,+ });+ }+ changes+ }++ pub fn fades_need_frame(&self, now: MonotonicTime) -> bool {+ for visibility in &self.visibilities {+ if visibility.fade.is_fading()+ || visibility.expansion.is_fading()+ || visibility.fade_out_time.is_some_and(|time| time <= now)+ {+ return true;+ }+ }+ false+ }++ // Returns the rect in the viewport of the scrollbars whose opacity or geometry changed.+ pub fn advance_fades(+ &mut self,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ frame_time: MonotonicTime,+ ) -> IntRect {+ let mut damage_rect = IntRect::default();+ for i in 0..self.scrollbars.len() {+ let visibility = &mut self.visibilities[i];+ if visibility.fade_out_time.is_some_and(|time| time <= frame_time) {+ visibility.fade_out_time = None;+ visibility.fade.fade_to(0.0, frame_time);+ }+ let mut 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.0 {+ visibility.expansion.jump_to(0.0);+ }+ changed |= visibility.expansion.advance_to(frame_time);+ if !changed {+ continue;+ }+ if let Some(rect) = self.rect_in_viewport(i, visual_context_tree, scroll_state_snapshot) {+ damage_rect = damage_rect.united(rect);+ }+ }+ damage_rect+ }++ fn rect_in_viewport(+ &self,+ scrollbar_index: usize,+ visual_context_tree: &AccumulatedVisualContextTree,+ scroll_state_snapshot: &ScrollStateSnapshot,+ ) -> Option<IntRect> {+ let scrollbar = self.scrollbars.get(scrollbar_index)?;+ let rect = scrollbar+ .gutter_rect+ .united(scrollbar.track_rect)+ .united(scrollbar.expanded_gutter_rect);+ if scrollbar.is_painted_by_compositor {+ return Some(rect.inflated(2, 2));+ }+ if !visual_context_tree.context_is_valid(scrollbar.context) {+ return None;+ }+ let rect_in_viewport = visual_context_tree.transform_rect_to_viewport(+ scrollbar.context.spatial,+ rect.to_float(),+ scroll_state_snapshot,+ IncludeVisualViewportTransform::Yes,+ );+ if !rect_in_viewport.x.is_finite()+ || !rect_in_viewport.y.is_finite()+ || !rect_in_viewport.width.is_finite()+ || !rect_in_viewport.height.is_finite()+ {+ return None;+ }+ Some(enclosing_int_rect(rect_in_viewport).inflated(2, 2))+ }+}++fn interpolated_rect(from: IntRect, to: IntRect, progress: f32) -> FloatRect {+ let interpolate = |from: i32, to: i32| from as f32 + (to - from) as f32 * progress;+ FloatRect::new(+ interpolate(from.x, to.x),+ interpolate(from.y, to.y),+ interpolate(from.width, to.width),+ interpolate(from.height, to.height),+ )+}++impl ScrollbarController {+ pub fn scrollbars_of_frame(&self, scroll_state_snapshot: &ScrollStateSnapshot) -> Vec<ScrollbarOfFrame> {+ let mut scrollbars_of_frame = Vec::with_capacity(self.scrollbars.len());+ for (i, scrollbar) in self.scrollbars.iter().enumerate() {+ let progress = self.expansion(i);+ let mut thin_thumb_rect = thumb_rect_kept_inside_track(+ translated_thumb_rect_with_snapshot(scrollbar, scroll_state_snapshot, false),+ scrollbar.track_rect,+ scrollbar.vertical,+ );+ let mut expanded_thumb_rect = thumb_rect_kept_inside_track(+ translated_thumb_rect_with_snapshot(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.push(ScrollbarOfFrame {+ 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: self.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),+ });+ }+ scrollbars_of_frame+ }++ fn is_expanded(&self, scrollbar_index: usize) -> bool {+ self.hovered_scrollbar_index == Some(scrollbar_index) || self.captured_scrollbar_index == Some(scrollbar_index)+ }++ fn opacity(&self, scrollbar_index: usize) -> f32 {+ if self.scrollbars_always_shown {+ return 1.0;+ }+ self.visibilities+ .get(scrollbar_index)+ .map_or(0.0, |visibility| visibility.fade.opacity())+ }++ fn expansion(&self, scrollbar_index: usize) -> f32 {+ if self.scrollbars_always_shown {+ return if self.is_expanded(scrollbar_index) { 1.0 } else { 0.0 };+ }+ self.visibilities+ .get(scrollbar_index)+ .map_or(0.0, |visibility| visibility.expansion.opacity())+ }+}++fn min(a: f32, b: f32) -> f32 {+ if b < a { b } else { a }+}+fn max(a: f32, b: f32) -> f32 {+ if a < b { b } else { a }+}+fn clamp(value: f32, min: f32, max: f32) -> f32 {+ assert!(max >= min);+ if value > max {+ max+ } else if value < min {+ min+ } else {+ value+ }+}diff --git a/Services/Compositor/Rust/src/test_stubs.rs b/Services/Compositor/Rust/src/test_stubs.rsnew file mode 100644index 00000000000..7bd04ea0914--- /dev/null+++ b/Services/Compositor/Rust/src/test_stubs.rs@@ -0,0 +1,17 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Stand-ins for the LibGfx process-wide counters, which the unit tests link without the C++ runtime.++use std::sync::atomic::{AtomicU64, Ordering};++// One counter stands in for each of LibGfx's process-wide counters: their values only need to be unique.+static NEXT: AtomicU64 = AtomicU64::new(1);++#[unsafe(no_mangle)]+extern "C" fn ladybird_gfx_process_next_structural_epoch() -> u64 {+ NEXT.fetch_add(1, Ordering::Relaxed)+}diff --git a/Services/Compositor/Rust/src/wheel_gesture_routing.rs b/Services/Compositor/Rust/src/wheel_gesture_routing.rsnew file mode 100644index 00000000000..009960e1874--- /dev/null+++ b/Services/Compositor/Rust/src/wheel_gesture_routing.rs@@ -0,0 +1,499 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libcompositing_rust::scrolling::wheel_gesture_identity::{+ TouchpadGestureEnd, WHEEL_GESTURE_POSITION_SLOP_IN_CSS_PIXELS, WheelGestureIdentity,+};+use libcompositing_rust::scrolling::{+ AccumulatedVisualContextTree, AsyncScrollNodeStableID, AsyncScrollTree, AsyncScrollingState, CompositorContextId,+ InputRoutingDecision, MouseEvent, ScrollGesturePhase, SpatialNodeIndex, WheelRoutingAdmission,+ input_routing_decision_for_wheel_step_not_admitted_by, wheel_routing_admission_for_with_generation,+};+use libcompositing_rust::time::MonotonicTime;+use libgfx_rust::FloatPoint;+use std::cell::Cell;+use std::rc::Rc;++#[derive(Default)]+pub struct WheelGestureIdAllocator {+ last_wheel_gesture_id: Cell<u64>,+ last_wheel_step_number: Cell<u64>,+}++impl WheelGestureIdAllocator {+ pub fn allocate_wheel_gesture_id(&self) -> u64 {+ let id = self.last_wheel_gesture_id.get().wrapping_add(1);+ self.last_wheel_gesture_id.set(id);+ 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.+ pub fn allocate_wheel_step_number(&self) -> u64 {+ let number = self.last_wheel_step_number.get().wrapping_add(1);+ self.last_wheel_step_number.set(number);+ number+ }+}++pub struct WheelGestureRouting {+ admission: WheelRoutingAdmission,+ wheel_event_listener_state_generation: u64,+ // 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.+ gesture: Option<Gesture>,+ newest_step_numbers: NewestStepNumbers,+ gesture_had_wheel_event_with_delta: bool,+ latch: Option<Latch>,+ gesture_the_page_let_through: Option<GestureThePageLetThrough>,+ touchpad_gesture_end: TouchpadGestureEnd,+ id_allocator: Rc<WheelGestureIdAllocator>,+}++#[derive(Default)]+pub struct NotedWheelEvent {+ // The event starts another gesture than the one before it, which lets go of the latch.+ pub starts_gesture: bool,+ // The event is the first step of its gesture that moves anything. A touchpad gesture can start with a step that+ // has no delta.+ pub is_first_wheel_event_with_delta: bool,+ pub step_number: u64,+}++// 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.+#[derive(Default)]+pub struct ResolvedLatch {+ pub scroll_node_index: Option<SpatialNodeIndex>,+ pub nested_context_id: Option<CompositorContextId>,+ pub keeps_steps: bool,+}++// 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.+ gesture_id: Option<u64>,+ // Empty for a latch that keeps the steps without a scroller.+ stable_node_id: Option<AsyncScrollNodeStableID>,+ // The phase of the last step that reached the latch, which says whether the fingers of its gesture are down.+ last_scroll_gesture_phase: ScrollGesturePhase,+ nested_context_id: Option<CompositorContextId>,+ // 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.+ momentum_has_sprung_the_scroller_back: bool,+}++#[derive(Default)]+struct NewestStepNumbers {+ ongoing: u64,+ momentum: u64,+ ended: u64,+}++struct Gesture {+ id: u64,+ identity: WheelGestureIdentity,+ wheel_event_listener_context: Option<CompositorContextId>,+ // Summed per axis, whatever the direction.+ delta_left_to_the_page: FloatPoint,+}++// 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.+#[derive(Default)]+struct GestureThePageLetThrough {+ gesture_id: u64,+ wheel_event_listener_state_generation: u64,+}++fn position_slop_in_device_pixels(async_scroll_tree: &AsyncScrollTree) -> f32 {+ WHEEL_GESTURE_POSITION_SLOP_IN_CSS_PIXELS * async_scroll_tree.device_pixels_per_css_pixel() as f32+}++impl WheelGestureRouting {+ pub fn new(id_allocator: Rc<WheelGestureIdAllocator>) -> Self {+ Self {+ admission: WheelRoutingAdmission::NoAsyncScrollingState,+ wheel_event_listener_state_generation: 0,+ gesture: None,+ newest_step_numbers: NewestStepNumbers::default(),+ gesture_had_wheel_event_with_delta: false,+ latch: None,+ gesture_the_page_let_through: None,+ touchpad_gesture_end: TouchpadGestureEnd::AfterIdleDelay,+ id_allocator,+ }+ }++ pub fn did_install_scrolling_state(&mut self, async_scrolling_state: &AsyncScrollingState) {+ self.admission = wheel_routing_admission_for_with_generation(+ async_scrolling_state,+ self.wheel_event_listener_state_generation,+ );+ self.wheel_event_listener_state_generation = self+ .wheel_event_listener_state_generation+ .max(async_scrolling_state.wheel_event_listener_state_generation);+ }++ pub fn invalidate_wheel_event_listener_state(&mut self, generation: u64) {+ self.wheel_event_listener_state_generation = self.wheel_event_listener_state_generation.max(generation);+ self.admission = WheelRoutingAdmission::StaleWheelEventListeners;+ }++ pub fn admission(&self) -> WheelRoutingAdmission {+ self.admission+ }+ pub fn admits_async_wheel(&self) -> bool {+ self.admission == WheelRoutingAdmission::Accepted+ }++ pub fn admits_async_pinch(&self) -> bool {+ // Pinch zoom scales the visual viewport, which a page whose viewport cannot be scrolled has too.+ matches!(+ self.admission,+ WheelRoutingAdmission::Accepted | WheelRoutingAdmission::NoScrollNode+ )+ }++ // 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.+ pub fn note_wheel_event(+ &mut self,+ event: &MouseEvent,+ position: FloatPoint,+ async_scroll_tree: &AsyncScrollTree,+ now: MonotonicTime,+ ) -> NotedWheelEvent {+ let phase = event.scroll_gesture_phase;+ let step_number = self.id_allocator.allocate_wheel_step_number();+ if phase == ScrollGesturePhase::Ongoing {+ self.newest_step_numbers.ongoing = step_number;+ } else if phase == ScrollGesturePhase::Momentum {+ self.newest_step_numbers.momentum = step_number;+ } else if phase == ScrollGesturePhase::Ended {+ self.newest_step_numbers.ended = step_number;+ }++ let starts_gesture = self.gesture.as_ref().is_none_or(|gesture| {+ !gesture.identity.is_continued_by(+ position,+ phase,+ event.modifiers.0,+ now,+ position_slop_in_device_pixels(async_scroll_tree),+ self.touchpad_gesture_end,+ )+ });+ if starts_gesture {+ self.gesture = Some(Gesture {+ id: self.id_allocator.allocate_wheel_gesture_id(),+ identity: WheelGestureIdentity::started_by(position, phase, event.modifiers.0, now),+ wheel_event_listener_context: None,+ delta_left_to_the_page: FloatPoint::default(),+ });+ self.gesture_had_wheel_event_with_delta = false;+ self.latch = None;+ } else if let Some(gesture) = self.gesture.as_mut() {+ gesture.identity.advance_to(phase, now);+ }+ let is_first_wheel_event_with_delta =+ !self.gesture_had_wheel_event_with_delta && (event.wheel_delta_x != 0.0 || event.wheel_delta_y != 0.0);+ if is_first_wheel_event_with_delta {+ self.gesture_had_wheel_event_with_delta = true;+ }+ NotedWheelEvent {+ starts_gesture,+ is_first_wheel_event_with_delta,+ step_number,+ }+ }++ // 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.+ pub fn gesture_id(&self) -> Option<u64> {+ Some(self.gesture.as_ref()?.id)+ }++ // 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.+ pub fn wheel_event_listener_context(&self) -> Option<CompositorContextId> {+ self.gesture.as_ref()?.wheel_event_listener_context+ }++ pub fn set_wheel_event_listener_context(&mut self, context_id: CompositorContextId) {+ if let Some(gesture) = self.gesture.as_mut() {+ gesture.wheel_event_listener_context = Some(context_id);+ }+ }++ // 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.+ pub fn note_delta_left_to_the_page(&mut self, delta_in_css_pixels: FloatPoint) {+ if let Some(gesture) = self.gesture.as_mut() {+ gesture.delta_left_to_the_page.translate_by(FloatPoint {+ x: delta_in_css_pixels.x.abs(),+ y: delta_in_css_pixels.y.abs(),+ });+ }+ }++ pub fn take_delta_left_to_the_page(&mut self, delta_in_css_pixels: FloatPoint) -> bool {+ let Some(gesture) = self.gesture.as_mut() else {+ return false;+ };+ // The page sends back the deltas it was given, which may have been summed up on the way.+ const ROUNDING_SLACK: f32 = 0.01;+ let delta_left = &mut gesture.delta_left_to_the_page;+ let step = FloatPoint {+ x: delta_in_css_pixels.x.abs(),+ y: delta_in_css_pixels.y.abs(),+ };+ if step.x > delta_left.x + ROUNDING_SLACK || step.y > delta_left.y + ROUNDING_SLACK {+ return false;+ }+ *delta_left = FloatPoint {+ x: max(0.0, delta_left.x - step.x),+ y: max(0.0, delta_left.y - step.y),+ };+ true+ }++ pub fn forget_gesture(&mut self) {+ self.gesture = None;+ self.gesture_had_wheel_event_with_delta = false;+ self.latch = None;+ }++ // 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.+ pub fn step_was_overtaken(&self, phase: ScrollGesturePhase, step_number: u64) -> bool {+ let newest = &self.newest_step_numbers;+ match phase {+ ScrollGesturePhase::None => false,+ ScrollGesturePhase::Ongoing => {+ // The fingers lifted after this step.+ newest.momentum > step_number || newest.ended > step_number+ }+ ScrollGesturePhase::Momentum => {+ // The momentum ended, or the fingers touched down again, after this step.+ newest.ended > step_number || newest.ongoing > step_number+ }+ ScrollGesturePhase::Ended => {+ // Another gesture started after this end.+ newest.ongoing > step_number+ }+ }+ }++ pub fn has_latch(&self) -> bool {+ self.latch.is_some()+ }+ pub fn has_latch_for_gesture(&self, gesture_id: Option<u64>) -> bool {+ self.latch.as_ref().is_some_and(|latch| latch.gesture_id == gesture_id)+ }+ pub fn set_touchpad_gesture_end(&mut self, touchpad_gesture_end: TouchpadGestureEnd) {+ self.touchpad_gesture_end = touchpad_gesture_end;+ }+ pub fn clear_latch(&mut self) {+ self.latch = None;+ }++ // 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.+ pub fn resolve_latch(+ &mut self,+ async_scroll_tree: &AsyncScrollTree,+ current_visual_context_tree: &AccumulatedVisualContextTree,+ scroll_gesture_phase: ScrollGesturePhase,+ gesture_id: Option<u64>,+ ) -> ResolvedLatch {+ let Some(latch) = self.latch.as_mut() else {+ return ResolvedLatch::default();+ };+ if latch.gesture_id != gesture_id {+ self.latch = None;+ return ResolvedLatch::default();+ }+ if latch.nested_context_id.is_some() || latch.stable_node_id.is_none() {+ latch.last_scroll_gesture_phase = scroll_gesture_phase;+ return ResolvedLatch {+ nested_context_id: latch.nested_context_id,+ keeps_steps: latch.nested_context_id.is_none(),+ ..Default::default()+ };+ }+ let scroll_node_index = async_scroll_tree.scroll_node_index_for_stable_id(latch.stable_node_id.unwrap());+ if scroll_node_index.is_none() {+ self.latch = None;+ return ResolvedLatch::default();+ }+ // 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 ResolvedLatch::default();+ }+ latch.last_scroll_gesture_phase = scroll_gesture_phase;+ ResolvedLatch {+ scroll_node_index,+ ..Default::default()+ }+ }++ pub fn latched_scroller(&self) -> Option<AsyncScrollNodeStableID> {+ self.latch.as_ref()?.stable_node_id+ }++ // Whether the fingers of the gesture are on the touchpad, where the gesture lasts until they lift.+ pub fn gesture_lasts_until_fingers_lift(&self) -> bool {+ self.touchpad_gesture_end == TouchpadGestureEnd::WhenFingersLift+ && self+ .gesture+ .as_ref()+ .is_some_and(|gesture| gesture.identity.is_held_by_fingers())+ }++ // The scroller of such a gesture, or of one a containing context hands the steps of to this one.+ pub fn scroller_held_by_fingers(&self) -> Option<AsyncScrollNodeStableID> {+ if self.touchpad_gesture_end != TouchpadGestureEnd::WhenFingersLift {+ return None;+ }+ let latch = self.latch.as_ref()?;+ // The gesture here has every event; a context nested in another has only the steps handed to it, on its latch.+ let held_by_fingers = self.gesture.as_ref().map_or(+ latch.last_scroll_gesture_phase == ScrollGesturePhase::Ongoing,+ |gesture| gesture.identity.is_held_by_fingers(),+ );+ if !held_by_fingers {+ return None;+ }+ latch.stable_node_id+ }++ pub fn latch(+ &mut self,+ stable_node_id: AsyncScrollNodeStableID,+ scroll_gesture_phase: ScrollGesturePhase,+ gesture_id: Option<u64>,+ ) {+ self.latch = Some(Latch {+ gesture_id,+ stable_node_id: Some(stable_node_id),+ last_scroll_gesture_phase: scroll_gesture_phase,+ nested_context_id: None,+ momentum_has_sprung_the_scroller_back: false,+ });+ }++ pub fn latch_to_nested_context(+ &mut self,+ nested_context_id: CompositorContextId,+ scroller: Option<AsyncScrollNodeStableID>,+ scroll_gesture_phase: ScrollGesturePhase,+ gesture_id: Option<u64>,+ ) {+ self.latch = Some(Latch {+ gesture_id,+ stable_node_id: scroller,+ last_scroll_gesture_phase: scroll_gesture_phase,+ nested_context_id: Some(nested_context_id),+ momentum_has_sprung_the_scroller_back: false,+ });+ }++ pub fn latch_keeping_steps(&mut self, scroll_gesture_phase: ScrollGesturePhase, gesture_id: Option<u64>) {+ self.latch = Some(Latch {+ gesture_id,+ stable_node_id: None,+ last_scroll_gesture_phase: scroll_gesture_phase,+ nested_context_id: None,+ momentum_has_sprung_the_scroller_back: false,+ });+ }++ pub fn relatch_to(&mut self, stable_node_id: AsyncScrollNodeStableID) {+ if let Some(latch) = self.latch.as_mut()+ && latch.stable_node_id.is_some()+ && latch.nested_context_id.is_none()+ {+ latch.stable_node_id = Some(stable_node_id);+ }+ }++ pub fn nested_context_of_latch(&self) -> Option<CompositorContextId> {+ self.latch.as_ref()?.nested_context_id+ }++ pub fn clear_latch_of_gesture(&mut self, gesture_id: u64) {+ if self.has_latch_for_gesture(Some(gesture_id)) {+ self.latch = None;+ }+ }++ // This context's page dispatched a step of the gesture and did not cancel it, or canceled one.+ pub fn note_page_let_gesture_through(&mut self, gesture_id: u64) {+ self.gesture_the_page_let_through = Some(GestureThePageLetThrough {+ gesture_id,+ wheel_event_listener_state_generation: self.wheel_event_listener_state_generation,+ });+ }++ pub fn forget_page_let_gesture_through(&mut self, gesture_id: u64) {+ if self+ .gesture_the_page_let_through+ .as_ref()+ .is_some_and(|gesture| gesture.gesture_id == gesture_id)+ {+ self.gesture_the_page_let_through = None;+ }+ }++ // Whether the page let the gesture through, and its wheel event listeners are as they were then.+ pub fn page_let_gesture_through(&self, gesture_id: Option<u64>) -> bool {+ gesture_id.is_some_and(|id| {+ self.gesture_the_page_let_through.as_ref().is_some_and(|gesture| {+ gesture.gesture_id == id+ && gesture.wheel_event_listener_state_generation == self.wheel_event_listener_state_generation+ })+ })+ }++ // 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.+ pub fn reason_to_hold_latched_steps_back(&self, gesture_id: Option<u64>) -> Option<InputRoutingDecision> {+ if self.page_let_gesture_through(gesture_id) {+ return None;+ }+ // 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 matches!(+ self.admission,+ WheelRoutingAdmission::Accepted | WheelRoutingAdmission::NoScrollNode+ ) {+ return None;+ }+ Some(input_routing_decision_for_wheel_step_not_admitted_by(self.admission))+ }++ pub fn momentum_of_latched_gesture_can_spring_scroller_back(&self) -> bool {+ self.latch+ .as_ref()+ .is_some_and(|latch| !latch.momentum_has_sprung_the_scroller_back)+ }++ pub fn set_momentum_of_latched_gesture_has_sprung_scroller_back(&mut self, has_sprung_back: bool) {+ if let Some(latch) = self.latch.as_mut() {+ latch.momentum_has_sprung_the_scroller_back = has_sprung_back;+ }+ }+}++fn max(a: f32, b: f32) -> f32 {+ if a < b { b } else { a }+}