Skip to content

Truly independent web browser

LibCompositing: Port the leaf scrolling math to Rust

Aliaksandr Kalenikfee626b877f7
diff --git a/Libraries/LibCompositing/Rust/src/css_pixels.rs b/Libraries/LibCompositing/Rust/src/css_pixels.rs
index 98cb7be396b..f9db7feb5e5 100644
--- a/Libraries/LibCompositing/Rust/src/css_pixels.rs
+++ b/Libraries/LibCompositing/Rust/src/css_pixels.rs
@@ -359,6 +359,10 @@ pub struct CssPixelPoint {
}
impl CssPixelPoint {
+ pub fn is_zero(self) -> bool {
+ self.x == CssPixels::default() && self.y == CssPixels::default()
+ }
+
pub const fn new(x: CssPixels, y: CssPixels) -> Self {
Self { x, y }
}
diff --git a/Libraries/LibCompositing/Rust/src/lib.rs b/Libraries/LibCompositing/Rust/src/lib.rs
index 52bf9c2047b..98e712a7485 100644
--- a/Libraries/LibCompositing/Rust/src/lib.rs
+++ b/Libraries/LibCompositing/Rust/src/lib.rs
@@ -23,8 +23,10 @@ pub mod force_dark;
pub mod host;
pub mod ipc_types;
pub mod node_slot_id;
+pub mod scrolling;
#[cfg(test)]
mod test_stubs;
+pub mod time;
pub mod visual_animation;
pub mod visual_context;
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/elastic_overscroll.rs b/Libraries/LibCompositing/Rust/src/scrolling/elastic_overscroll.rs
new file mode 100644
index 00000000000..4da402c245e
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/elastic_overscroll.rs
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! How far a touchpad has pulled one scroller past the edges of its scroll range, and how the scroller springs back.
+// A stretch has the sign of the scroll offset direction it extends: a negative y is a scroller pulled past its top.
+// Deltas, stretches and the scrollport are in the same pixels. Velocities are in those pixels per second.
+
+use super::max;
+use crate::time::MonotonicTime;
+use ak::math;
+use libgfx_rust::{FloatPoint, FloatSize};
+
+// A pull stretches by the overscroll divided by the stiffness, and a released stretch S0 with velocity V0 is
+// (S0 + amplitude * V0 * t) * exp(-t * stiffness / period) after t seconds.
+const RUBBER_BAND_STIFFNESS: f64 = 20.0;
+const RUBBER_BAND_AMPLITUDE: f64 = 0.31;
+const RUBBER_BAND_PERIOD: f64 = 1.6;
+const REBOUND_DECAY_PER_SECOND: f64 = RUBBER_BAND_STIFFNESS / RUBBER_BAND_PERIOD;
+
+const LARGEST_BOUNCE_AS_SHARE_OF_SCROLLPORT: f64 = 0.2;
+const SCREEN_PIXELS_OF_STRETCH_THAT_COUNT_AS_SPRUNG_BACK: f32 = 1.0;
+
+pub struct ElasticOverscroll {
+ scrollport_size: FloatSize,
+ screen_pixels_per_pixel: f32,
+ held_stretch: FloatPoint,
+ rebound: Option<Rebound>,
+}
+
+struct Rebound {
+ started_at: MonotonicTime,
+ initial_stretch: FloatPoint,
+ initial_velocity: FloatPoint,
+ current_stretch: FloatPoint,
+}
+
+// A scroller released at its edge with speed V peaks at amplitude * V / (decay * e). Wheel events carry no
+// timestamps, so the speed measured for events that were handled in a burst can be far above any real one.
+fn fastest_release_speed_for(scrollport_length: f32) -> f32 {
+ (LARGEST_BOUNCE_AS_SHARE_OF_SCROLLPORT * scrollport_length as f64 * REBOUND_DECAY_PER_SECOND * std::f64::consts::E
+ / RUBBER_BAND_AMPLITUDE) as f32
+}
+
+impl ElasticOverscroll {
+ /// A scroller that is shown magnified takes up `screen_pixels_per_pixel` pixels of the screen with each of its own.
+ pub fn new(scrollport_size: FloatSize, screen_pixels_per_pixel: f32) -> Self {
+ Self {
+ scrollport_size,
+ screen_pixels_per_pixel,
+ held_stretch: FloatPoint::default(),
+ rebound: None,
+ }
+ }
+
+ /// Whole pixels of the screen, like the scroll offsets the stretch is presented with.
+ pub fn stretch(&self) -> FloatPoint {
+ let unrounded_stretch = self
+ .rebound
+ .as_ref()
+ .map_or(self.held_stretch, |rebound| rebound.current_stretch);
+ FloatPoint {
+ x: (unrounded_stretch.x * self.screen_pixels_per_pixel).trunc() / self.screen_pixels_per_pixel,
+ y: (unrounded_stretch.y * self.screen_pixels_per_pixel).trunc() / self.screen_pixels_per_pixel,
+ }
+ }
+}
+
+fn relax_axis_by(stretch: &mut f32, delta: f32) -> f32 {
+ let delta_points_back_to_scroll_range = (*stretch > 0.0 && delta < 0.0) || (*stretch < 0.0 && delta > 0.0);
+ if !delta_points_back_to_scroll_range {
+ return delta;
+ }
+ if delta.abs() <= stretch.abs() {
+ *stretch += delta;
+ return 0.0;
+ }
+ let delta_left_to_scroll_with = delta + *stretch;
+ *stretch = 0.0;
+ delta_left_to_scroll_with
+}
+
+impl ElasticOverscroll {
+ /// The fingers moved by `delta`. The part of it that points back to the scroll range relaxes the stretch, and the
+ /// rest is returned to scroll with. The fingers take a rebound over from where it has got to.
+ pub fn relax_by(&mut self, delta: FloatPoint) -> FloatPoint {
+ if let Some(rebound) = self.rebound.take() {
+ self.held_stretch = rebound.current_stretch;
+ }
+ let mut held_stretch_x = self.held_stretch.x;
+ let mut held_stretch_y = self.held_stretch.y;
+ let delta_left_to_scroll_with = FloatPoint {
+ x: relax_axis_by(&mut held_stretch_x, delta.x),
+ y: relax_axis_by(&mut held_stretch_y, delta.y),
+ };
+ self.held_stretch = FloatPoint {
+ x: held_stretch_x,
+ y: held_stretch_y,
+ };
+ delta_left_to_scroll_with
+ }
+
+ /// The fingers moved by `overscroll_delta` further past an edge the scroller is already at.
+ pub fn pull_by(&mut self, overscroll_delta: FloatPoint) {
+ assert!(self.rebound.is_none());
+ let stretch_delta = overscroll_delta.scaled((1.0 / RUBBER_BAND_STIFFNESS) as f32);
+ self.held_stretch = FloatPoint {
+ x: (self.held_stretch.x + stretch_delta.x).clamp(-self.scrollport_size.width, self.scrollport_size.width),
+ y: (self.held_stretch.y + stretch_delta.y).clamp(-self.scrollport_size.height, self.scrollport_size.height),
+ };
+ }
+
+ /// The fingers lifted, or momentum carried the scroller into its edge.
+ pub fn release(&mut self, velocity: FloatPoint, now: MonotonicTime) {
+ if self.rebound.is_some() {
+ return;
+ }
+ let initial_stretch = self.held_stretch;
+ self.held_stretch = FloatPoint::default();
+
+ // Only an axis that is stretched is at its edge. The other one must not bounce off an edge it is not at.
+ let release_velocity_for_axis = |stretch: f32, velocity: f32, scrollport_length: f32| -> f32 {
+ if stretch == 0.0 {
+ return 0.0;
+ }
+ let fastest_release_speed = fastest_release_speed_for(scrollport_length);
+ velocity.clamp(-fastest_release_speed, fastest_release_speed)
+ };
+ self.rebound = Some(Rebound {
+ started_at: now,
+ initial_stretch,
+ initial_velocity: FloatPoint {
+ x: release_velocity_for_axis(initial_stretch.x, velocity.x, self.scrollport_size.width),
+ y: release_velocity_for_axis(initial_stretch.y, velocity.y, self.scrollport_size.height),
+ },
+ current_stretch: initial_stretch,
+ });
+ }
+}
+
+struct ReboundAxisSample {
+ stretch: f32,
+ has_sprung_back: bool,
+}
+
+impl Default for ReboundAxisSample {
+ fn default() -> Self {
+ Self {
+ stretch: 0.0,
+ has_sprung_back: true,
+ }
+ }
+}
+
+fn sample_rebound_axis(
+ initial_stretch: f32,
+ initial_velocity: f32,
+ scrollport_length: f32,
+ stretch_that_counts_as_sprung_back: f32,
+ elapsed_seconds: f64,
+) -> ReboundAxisSample {
+ if initial_stretch == 0.0 {
+ return ReboundAxisSample::default();
+ }
+ let stretch_before_decay =
+ initial_stretch as f64 + RUBBER_BAND_AMPLITUDE * initial_velocity as f64 * elapsed_seconds;
+ // A release velocity that points back to the scroll range must not carry the content past the edge it left.
+ let crossed_the_edge = (stretch_before_decay > 0.0) != (initial_stretch > 0.0);
+ if crossed_the_edge {
+ return ReboundAxisSample::default();
+ }
+ let mut stretch = (stretch_before_decay * math::exp(-elapsed_seconds * REBOUND_DECAY_PER_SECOND)) as f32;
+ stretch = stretch.clamp(-scrollport_length, scrollport_length);
+
+ // A bounce starts with almost no stretch, so a small stretch only means the rebound is over once it shrinks.
+ let stretch_growth_before_decay =
+ RUBBER_BAND_AMPLITUDE * initial_velocity as f64 - REBOUND_DECAY_PER_SECOND * stretch_before_decay;
+ let is_still_stretching = stretch_before_decay * stretch_growth_before_decay > 0.0;
+ ReboundAxisSample {
+ stretch,
+ has_sprung_back: !is_still_stretching && stretch.abs() < stretch_that_counts_as_sprung_back,
+ }
+}
+
+impl ElasticOverscroll {
+ /// Returns false once the scroller has sprung back.
+ pub fn advance_rebound_to(&mut self, frame_time: MonotonicTime) -> bool {
+ let Some(rebound) = self.rebound.as_mut() else {
+ return false;
+ };
+
+ // The time of a display tick can be earlier than the event that released the stretch.
+ let elapsed_seconds = max(0.0, (frame_time - rebound.started_at).to_seconds_f64());
+ let stretch_that_counts_as_sprung_back =
+ SCREEN_PIXELS_OF_STRETCH_THAT_COUNT_AS_SPRUNG_BACK / self.screen_pixels_per_pixel;
+ let horizontal = sample_rebound_axis(
+ rebound.initial_stretch.x,
+ rebound.initial_velocity.x,
+ self.scrollport_size.width,
+ stretch_that_counts_as_sprung_back,
+ elapsed_seconds,
+ );
+ let vertical = sample_rebound_axis(
+ rebound.initial_stretch.y,
+ rebound.initial_velocity.y,
+ self.scrollport_size.height,
+ stretch_that_counts_as_sprung_back,
+ elapsed_seconds,
+ );
+ if horizontal.has_sprung_back && vertical.has_sprung_back {
+ self.rebound = None;
+ return false;
+ }
+ rebound.current_stretch = FloatPoint {
+ x: if horizontal.has_sprung_back {
+ 0.0
+ } else {
+ horizontal.stretch
+ },
+ y: if vertical.has_sprung_back {
+ 0.0
+ } else {
+ vertical.stretch
+ },
+ };
+ true
+ }
+
+ pub fn is_at_rest(&self) -> bool {
+ self.rebound.is_none() && self.held_stretch.is_zero()
+ }
+ pub fn is_rebounding(&self) -> bool {
+ self.rebound.is_some()
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/mod.rs b/Libraries/LibCompositing/Rust/src/scrolling/mod.rs
new file mode 100644
index 00000000000..db40737bd2e
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/mod.rs
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+pub mod elastic_overscroll;
+pub mod overlay_fade;
+pub mod scroll_fling;
+pub mod scroll_snap_selection;
+pub mod smooth_scroll_animation;
+pub mod wheel_gesture_identity;
+
+pub use crate::ipc_types::Compositing_ScrollAnimationKind as ScrollAnimationKind;
+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::Web_AsyncScrollNodeStableID as AsyncScrollNodeStableID;
+pub use crate::ipc_types::Web_ScrollGesturePhase as ScrollGesturePhase;
+pub use libgfx_rust::Orientation;
+
+pub const USER_SCROLL_SETTLE_DELAY: crate::time::Duration = crate::time::Duration::from_milliseconds(500);
+
+fn min<T: PartialOrd>(a: T, b: T) -> T {
+ if b < a { b } else { a }
+}
+
+fn max<T: PartialOrd>(a: T, b: T) -> T {
+ if a < b { b } else { a }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/overlay_fade.rs b/Libraries/LibCompositing/Rust/src/scrolling/overlay_fade.rs
new file mode 100644
index 00000000000..bd4d52e5e34
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/overlay_fade.rs
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A fade that turns back from whatever opacity it has reached.
+
+use crate::time::{Duration, MonotonicTime};
+
+#[derive(Default)]
+pub struct OverlayFade {
+ opacity: f32,
+ initial_opacity: f32,
+ target_opacity: f32,
+ started_at: Option<MonotonicTime>,
+}
+
+impl OverlayFade {
+ pub const DURATION: Duration = Duration::from_milliseconds(150);
+
+ pub fn fade_to(&mut self, target_opacity: f32, now: MonotonicTime) {
+ if target_opacity == self.target_opacity {
+ return;
+ }
+ self.initial_opacity = self.opacity;
+ self.target_opacity = target_opacity;
+ self.started_at = Some(now);
+ }
+
+ /// Ends any fade, with the opacity at once where it would end.
+ pub fn jump_to(&mut self, opacity: f32) {
+ self.opacity = opacity;
+ self.initial_opacity = opacity;
+ self.target_opacity = opacity;
+ self.started_at = None;
+ }
+
+ /// Returns whether the opacity changed.
+ pub fn advance_to(&mut self, frame_time: MonotonicTime) -> bool {
+ let opacity = self.opacity_at(frame_time);
+ if opacity == self.opacity {
+ return false;
+ }
+ self.opacity = opacity;
+ true
+ }
+
+ pub fn opacity(&self) -> f32 {
+ self.opacity
+ }
+
+ pub fn is_fading(&self) -> bool {
+ self.opacity != self.target_opacity
+ }
+
+ fn opacity_at(&self, frame_time: MonotonicTime) -> f32 {
+ let Some(started_at) = self.started_at else {
+ return self.target_opacity;
+ };
+ let mut progress = (frame_time - started_at).to_seconds_f64() / Self::DURATION.to_seconds_f64();
+ if progress >= 1.0 {
+ return self.target_opacity;
+ }
+ progress = if progress < 0.0 { 0.0 } else { progress };
+
+ // Smoothstep, so that the fade starts and ends gently.
+ let eased_progress = (progress * progress * (3.0 - 2.0 * progress)) as f32;
+ self.initial_opacity + (self.target_opacity - self.initial_opacity) * eased_progress
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/scroll_fling.rs b/Libraries/LibCompositing/Rust/src/scrolling/scroll_fling.rs
new file mode 100644
index 00000000000..6760c78277b
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/scroll_fling.rs
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Calculates the velocity of a touchpad scroll gesture when the fingers lift.
+
+// Velocities are in wheel delta units per second. Displacements are in wheel delta units.
+
+use super::smooth_scroll_animation::{
+ MAXIMUM_MOMENTUM_DURATION_IN_SECONDS, MOMENTUM_DISTANCE_SHARE_PER_FRAME, MOMENTUM_FRAME_DURATION_IN_SECONDS,
+};
+use super::{max, min};
+use crate::time::{Duration, MonotonicTime};
+use ak::math;
+use libgfx_rust::FloatPoint;
+use std::collections::VecDeque;
+
+// Use only the most recent steps to find the velocity at the lift.
+const VELOCITY_SAMPLING_WINDOW: Duration = Duration::from_milliseconds(100);
+
+// If the fingers stop for longer than this before they lift, no fling starts.
+const MAXIMUM_PAUSE_BEFORE_LIFT: Duration = Duration::from_milliseconds(100);
+
+const MINIMUM_FLING_START_SPEED: f64 = 50.0;
+const MINIMUM_FLING_SPEED: f64 = 20.0;
+const MAXIMUM_FLING_SPEED: f64 = 20000.0;
+
+// A boost occurs only if the stopped fling was fast and a fast flick in the same direction starts soon after.
+const MINIMUM_BOOSTED_FLING_SPEED: f64 = 350.0;
+const MINIMUM_BOOSTING_FLICK_SPEED: f64 = 150.0;
+const MAXIMUM_BOOST_DELAY: Duration = Duration::from_milliseconds(500);
+
+#[derive(Default)]
+pub struct ScrollVelocityTracker {
+ steps: VecDeque<Step>,
+}
+
+struct Step {
+ delta: FloatPoint,
+ time: MonotonicTime,
+}
+
+/// Continues to scroll after a touchpad flick, for platforms that do not send momentum scroll events.
+/// The speed decreases by the same fraction per frame as a momentum smooth scroll.
+/// MomentumFlingEstimator uses this decrease to find where the scroll stops.
+pub struct ScrollFling {
+ initial_velocity: FloatPoint,
+ initial_speed: f64,
+ started_at: MonotonicTime,
+ last_step_elapsed_seconds: f64,
+ last_step_decay: f64,
+ finished: bool,
+}
+
+/// If the user flicks again while a fling is fast, the new fling gets the velocity of the old fling added.
+#[derive(Default)]
+pub struct ScrollFlingBooster {
+ interrupted_fling: Option<InterruptedFling>,
+}
+
+#[derive(Clone, Copy)]
+struct InterruptedFling {
+ velocity: FloatPoint,
+ interrupted_at: MonotonicTime,
+}
+
+fn speed_of(velocity: FloatPoint) -> f64 {
+ math::hypot(velocity.x as f64, velocity.y as f64)
+}
+
+fn with_speed_capped(velocity: FloatPoint) -> FloatPoint {
+ let speed = speed_of(velocity);
+ if speed <= MAXIMUM_FLING_SPEED {
+ return velocity;
+ }
+ velocity.scaled((MAXIMUM_FLING_SPEED / speed) as f32)
+}
+
+impl ScrollVelocityTracker {
+ pub fn add_step(&mut self, delta: FloatPoint, time: MonotonicTime) {
+ if self.steps.len() == 20 {
+ self.steps.pop_front();
+ }
+ self.steps.push_back(Step { delta, time });
+ }
+
+ /// Returns no value if the fingers stopped for too long before the lift.
+ pub fn velocity_at_lift(&self, lift_time: MonotonicTime) -> Option<FloatPoint> {
+ let last_step_time = self.steps.back()?.time;
+ if lift_time - last_step_time > MAXIMUM_PAUSE_BEFORE_LIFT {
+ return None;
+ }
+
+ // Steps from before the window are not used. After a pause, they would make the velocity much too low.
+ let mut first_index = self.steps.len() - 1;
+ while first_index > 0 && last_step_time - self.steps[first_index - 1].time <= VELOCITY_SAMPLING_WINDOW {
+ first_index -= 1;
+ }
+ let point_count = self.steps.len() - first_index;
+ if point_count < 2 {
+ return None;
+ }
+
+ // Fit a least-squares line to the total displacement over time. Thus, one late or early step has less effect on
+ // the velocity.
+ // Times are relative to the last step to keep the sums small.
+ let (mut sum_t, mut sum_tt, mut sum_x, mut sum_y, mut sum_tx, mut sum_ty, mut x, mut y) =
+ (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+ for step in self.steps.iter().skip(first_index) {
+ x += step.delta.x as f64;
+ y += step.delta.y as f64;
+ let t = (step.time - last_step_time).to_seconds_f64();
+ sum_t += t;
+ sum_tt += t * t;
+ sum_x += x;
+ sum_y += y;
+ sum_tx += t * x;
+ sum_ty += t * y;
+ }
+ let n = point_count as f64;
+ let determinant = n * sum_tt - sum_t * sum_t;
+ // If all steps have the same time, there is no velocity.
+ if determinant <= 0.0 {
+ return None;
+ }
+ Some(FloatPoint {
+ x: ((n * sum_tx - sum_t * sum_x) / determinant) as f32,
+ y: ((n * sum_ty - sum_t * sum_y) / determinant) as f32,
+ })
+ }
+
+ pub fn reset(&mut self) {
+ self.steps.clear();
+ }
+}
+
+impl ScrollFling {
+ pub fn start(velocity: FloatPoint, now: MonotonicTime) -> Option<Self> {
+ if speed_of(velocity) < MINIMUM_FLING_START_SPEED {
+ return None;
+ }
+ Some(Self::new(with_speed_capped(velocity), now))
+ }
+
+ fn new(velocity: FloatPoint, now: MonotonicTime) -> Self {
+ Self {
+ initial_velocity: velocity,
+ initial_speed: speed_of(velocity),
+ started_at: now,
+ last_step_elapsed_seconds: 0.0,
+ last_step_decay: 1.0,
+ finished: false,
+ }
+ }
+
+ /// The fraction of the initial speed that remains after the given time.
+ fn decay_at(&self, elapsed_seconds: f64) -> f64 {
+ math::pow(
+ MOMENTUM_DISTANCE_SHARE_PER_FRAME,
+ elapsed_seconds / MOMENTUM_FRAME_DURATION_IN_SECONDS,
+ )
+ }
+
+ pub fn velocity_at(&self, time: MonotonicTime) -> FloatPoint {
+ if self.finished {
+ return FloatPoint::default();
+ }
+ let elapsed_seconds = max(0.0, (time - self.started_at).to_seconds_f64());
+ self.initial_velocity.scaled(self.decay_at(elapsed_seconds) as f32)
+ }
+
+ /// Returns the displacement since the previous step, or no value after the fling stops.
+ pub fn step(&mut self, now: MonotonicTime) -> Option<FloatPoint> {
+ if self.finished {
+ return None;
+ }
+ let elapsed_seconds = min(
+ (now - self.started_at).to_seconds_f64(),
+ MAXIMUM_MOMENTUM_DURATION_IN_SECONDS,
+ );
+ if elapsed_seconds <= self.last_step_elapsed_seconds {
+ return Some(FloatPoint::default());
+ }
+
+ // If v(t) = v0 * decay(t), the distance at time t is v0 * time_constant * (1 - decay(t)).
+ let time_constant = MOMENTUM_FRAME_DURATION_IN_SECONDS / -math::log(MOMENTUM_DISTANCE_SHARE_PER_FRAME);
+ let decay = self.decay_at(elapsed_seconds);
+ let displacement = self
+ .initial_velocity
+ .scaled((time_constant * (self.last_step_decay - decay)) as f32);
+ self.last_step_elapsed_seconds = elapsed_seconds;
+ self.last_step_decay = decay;
+ if self.initial_speed * decay < MINIMUM_FLING_SPEED || elapsed_seconds >= MAXIMUM_MOMENTUM_DURATION_IN_SECONDS {
+ self.finished = true;
+ }
+ Some(displacement)
+ }
+}
+
+impl ScrollFlingBooster {
+ pub fn fling_was_interrupted(&mut self, velocity: FloatPoint, now: MonotonicTime) {
+ if speed_of(velocity) < MINIMUM_BOOSTED_FLING_SPEED {
+ self.interrupted_fling = None;
+ return;
+ }
+ self.interrupted_fling = Some(InterruptedFling {
+ velocity,
+ interrupted_at: now,
+ });
+ }
+
+ pub fn boosted_velocity(&mut self, velocity: FloatPoint, now: MonotonicTime) -> FloatPoint {
+ let Some(interrupted_fling) = self.interrupted_fling.take() else {
+ return velocity;
+ };
+ if now - interrupted_fling.interrupted_at > MAXIMUM_BOOST_DELAY {
+ return velocity;
+ }
+ if speed_of(velocity) < MINIMUM_BOOSTING_FLICK_SPEED {
+ return velocity;
+ }
+ let direction_agreement = velocity.x * interrupted_fling.velocity.x + velocity.y * interrupted_fling.velocity.y;
+ if direction_agreement <= 0.0 {
+ return velocity;
+ }
+ with_speed_capped(velocity + interrupted_fling.velocity)
+ }
+
+ pub fn reset(&mut self) {
+ self.interrupted_fling = None;
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/scroll_snap_selection.rs b/Libraries/LibCompositing/Rust/src/scrolling/scroll_snap_selection.rs
new file mode 100644
index 00000000000..a01de1f8655
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/scroll_snap_selection.rs
@@ -0,0 +1,770 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Scroll snap position selection over geometry that has already been collected from layout, so that the same selection runs on the main thread and in the compositor process. Everything here is in CSS pixels.
+
+use super::{SnapAreaIdentity, SnapDestination, SnappedAreas};
+use crate::css_pixels::{CssPixelPoint, CssPixelRect, CssPixels};
+use ak::math;
+
+/// The values of the scroll-snap-align and scroll-snap-type properties that reach here, in the order the CSS enums
+/// declare them; the recorder writes them as bytes and the main thread checks the two stay in step.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum SnapAlign {
+ #[default]
+ None,
+ Start,
+ End,
+ Center,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum SnapStrictness {
+ #[default]
+ None,
+ Proximity,
+ Mandatory,
+}
+
+// The box a snap area belongs to, which identifies the area across relayouts and across processes. A node's unique ID
+// is never reused, so an area removed from the document keeps an identity no live area ever takes again and is no
+// longer a snap area the container can be returned to.
+impl SnapAreaIdentity {
+ pub fn is_valid(&self) -> bool {
+ self.node_id.0 != 0
+ }
+
+ // 0 for the element's own box; otherwise the pseudo-element the box is generated for, plus one.
+ pub fn is_pseudo_element(&self) -> bool {
+ self.pseudo_element_type != 0
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default)]
+pub struct SnapAxes {
+ pub x: bool,
+ pub y: bool,
+}
+
+impl SnapAxes {
+ pub fn is_empty(self) -> bool {
+ !self.x && !self.y
+ }
+}
+
+/// https://drafts.csswg.org/css-scroll-snap-1/#scroll-snap-area
+#[derive(Default)]
+pub struct SnapAreaGeometry {
+ pub identity: SnapAreaIdentity,
+ /// The transformed border box in the snap container's coordinate space, with the scroll margin added.
+ pub rect: CssPixelRect,
+ /// The alignment along each physical axis, resolved from the writing mode it applies in.
+ pub align_x: SnapAlign,
+ pub align_y: SnapAlign,
+ pub always_stop: bool,
+}
+
+/// https://drafts.csswg.org/css-scroll-snap-1/#scroll-snap-container
+pub struct SnapContainerGeometry {
+ /// https://drafts.csswg.org/css-scroll-snap-1/#scroll-padding
+ pub snapport: CssPixelRect,
+ pub min_scroll_offset: CssPixelPoint,
+ pub max_scroll_offset: CssPixelPoint,
+ pub strictness: SnapStrictness,
+ pub axes: SnapAxes,
+ pub horizontal_writing_mode: bool,
+}
+
+impl Default for SnapContainerGeometry {
+ fn default() -> Self {
+ Self {
+ snapport: Default::default(),
+ min_scroll_offset: Default::default(),
+ max_scroll_offset: Default::default(),
+ strictness: SnapStrictness::None,
+ axes: Default::default(),
+ horizontal_writing_mode: true,
+ }
+ }
+}
+
+/// A closed range of scroll offsets that are all valid snap positions.
+#[derive(Default)]
+pub struct CoveringRange {
+ pub start: CssPixels,
+ pub end: CssPixels,
+}
+
+/// A candidate scroll offset in one axis, produced by aligning a snap area with the snapport.
+#[derive(Default)]
+pub struct SnapPositionCandidate {
+ pub offset: CssPixels,
+ pub area: SnapAreaIdentity,
+ pub covering_ranges: Vec<CoveringRange>,
+ /// The open range of scroll offsets in the container's other axis at which the snap area overlaps the snapport.
+ pub cross_axis_visible_range_start: CssPixels,
+ pub cross_axis_visible_range_end: CssPixels,
+ pub always_stop: bool,
+}
+
+#[derive(Default)]
+pub struct SnapAxisCandidates {
+ pub x_candidates: Vec<SnapPositionCandidate>,
+ pub y_candidates: Vec<SnapPositionCandidate>,
+}
+
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum SnapSelectionStrategyType {
+ /// An absolute scroll, or any other operation with only an intended end position.
+ #[default]
+ EndPosition,
+ /// A relative scroll with only an intended direction, such as a mouse wheel step or an arrow key press.
+ Direction,
+ /// A relative scroll with both an intended direction and end position, such as scrollBy().
+ EndPositionAndDirection,
+}
+
+/// https://drafts.csswg.org/css-scroll-snap-1/#scroll-types
+#[derive(Default)]
+pub struct SnapSelectionStrategy {
+ pub r#type: SnapSelectionStrategyType,
+ /// The scroll offset the operation travels from; a snap position with `scroll-snap-stop: always` must not be
+ /// passed over on the way from there to the selected snap position.
+ pub start_offset: Option<CssPixelPoint>,
+ /// The net offset change the operation's input produced; an axis the operation did not travel in selects no snap
+ /// position.
+ pub displacement: CssPixelPoint,
+ /// Snap positions short of this offset in the direction of travel are not selected; it defaults to the start
+ /// offset.
+ pub starting_positions_boundary: Option<CssPixelPoint>,
+}
+
+// The snap areas a scroll container is snapped to in each axis, so that it can be re-snapped to those same snap areas
+// after a content change.
+impl SnappedAreas {
+ pub fn is_empty(&self) -> bool {
+ self.x.is_empty() && self.y.is_empty()
+ }
+}
+
+/// The selection a scroll makes in one axis.
+#[derive(Default)]
+pub struct SnapAxisSelection {
+ pub destination: CssPixels,
+ pub start: CssPixels,
+ pub direction: CssPixels,
+ pub starting_positions_boundary: Option<CssPixels>,
+}
+
+#[derive(Default)]
+pub struct SnapAxisChoice {
+ pub offset: CssPixels,
+ pub area: SnapAreaIdentity,
+}
+
+struct SnapAxisGeometry {
+ snapport_start: CssPixels,
+ snapport_size: CssPixels,
+ min_offset: CssPixels,
+ max_offset: CssPixels,
+}
+
+fn abs(value: CssPixels) -> CssPixels {
+ if value < CssPixels::default() { -value } else { value }
+}
+
+fn x_axis_geometry(geometry: &SnapContainerGeometry) -> SnapAxisGeometry {
+ SnapAxisGeometry {
+ snapport_start: geometry.snapport.left(),
+ snapport_size: geometry.snapport.width,
+ min_offset: geometry.min_scroll_offset.x,
+ max_offset: geometry.max_scroll_offset.x,
+ }
+}
+
+fn y_axis_geometry(geometry: &SnapContainerGeometry) -> SnapAxisGeometry {
+ SnapAxisGeometry {
+ snapport_start: geometry.snapport.top(),
+ snapport_size: geometry.snapport.height,
+ min_offset: geometry.min_scroll_offset.y,
+ max_offset: geometry.max_scroll_offset.y,
+ }
+}
+
+fn snap_position_candidate_for_axis(
+ alignment: SnapAlign,
+ area_start: CssPixels,
+ area_size: CssPixels,
+ geometry: &SnapAxisGeometry,
+) -> Option<SnapPositionCandidate> {
+ let offset = match alignment {
+ SnapAlign::None => return None,
+ SnapAlign::Start => area_start - geometry.snapport_start,
+ SnapAlign::End => area_start + area_size - (geometry.snapport_start + geometry.snapport_size),
+ SnapAlign::Center => area_start + area_size / 2 - (geometry.snapport_start + geometry.snapport_size / 2),
+ };
+
+ // https://drafts.csswg.org/css-scroll-snap-1/#unreachable
+ // If a snap position is unreachable as specified, such that aligning to it would require scrolling the scroll
+ // container's viewport past the edge of its scrollable overflow area, the used snap position for this snap area is
+ // the position resulting from scrolling as much as possible in each relevant axis toward the desired snap position.
+ let mut candidate = SnapPositionCandidate {
+ offset: offset.clamp(geometry.min_offset, geometry.max_offset),
+ ..Default::default()
+ };
+ if area_size > geometry.snapport_size {
+ candidate.covering_ranges.push(CoveringRange {
+ start: (area_start - geometry.snapport_start).clamp(geometry.min_offset, geometry.max_offset),
+ end: (area_start + area_size - (geometry.snapport_start + geometry.snapport_size))
+ .clamp(geometry.min_offset, geometry.max_offset),
+ });
+ }
+ Some(candidate)
+}
+
+fn restrict_covering_ranges_to_valid_snap_positions(
+ candidates: &mut [SnapPositionCandidate],
+ snapport_size: CssPixels,
+) {
+ let mut snap_positions = Vec::with_capacity(candidates.len());
+ for candidate in candidates.iter() {
+ snap_positions.push(candidate.offset);
+ }
+ snap_positions.sort_unstable();
+ for candidate in candidates {
+ if candidate.covering_ranges.is_empty() {
+ continue;
+ }
+ let covering_range = candidate.covering_ranges.remove(0);
+ candidate.covering_ranges.clear();
+ let mut append_valid_offsets_between = |start: CssPixels, end: CssPixels| {
+ let start = start.max(covering_range.start);
+ let end = end.min(covering_range.end);
+ if start <= end {
+ candidate.covering_ranges.push(CoveringRange { start, end });
+ }
+ };
+ append_valid_offsets_between(covering_range.start, snap_positions[0]);
+ for i in 1..snap_positions.len() {
+ if snap_positions[i] - snap_positions[i - 1] > snapport_size {
+ append_valid_offsets_between(snap_positions[i - 1], snap_positions[i]);
+ }
+ }
+ append_valid_offsets_between(snap_positions[snap_positions.len() - 1], covering_range.end);
+ }
+}
+
+fn is_beyond_in_direction(offset: CssPixels, boundary: CssPixels, direction: CssPixels) -> bool {
+ // AD-HOC: Offsets within one pixel of the offset a scroll travels from count as being at it, so that a fractional
+ // scroll offset cannot re-select the snap position the scroll started from. This matches other engines.
+ #[allow(non_snake_case)]
+ let SNAP_POSITION_BOUNDARY_TOLERANCE: CssPixels = CssPixels::from_integer(1);
+ if direction > CssPixels::default() {
+ offset >= boundary + SNAP_POSITION_BOUNDARY_TOLERANCE
+ } else {
+ offset <= boundary - SNAP_POSITION_BOUNDARY_TOLERANCE
+ }
+}
+
+fn is_at_or_beyond_in_direction(offset: CssPixels, boundary: CssPixels, direction: CssPixels) -> bool {
+ if direction > CssPixels::default() {
+ offset >= boundary
+ } else {
+ offset <= boundary
+ }
+}
+
+pub fn snap_area_is_visible_at_cross_axis_offset(
+ candidate: &SnapPositionCandidate,
+ cross_axis_offset: CssPixels,
+) -> bool {
+ cross_axis_offset > candidate.cross_axis_visible_range_start
+ && cross_axis_offset < candidate.cross_axis_visible_range_end
+}
+
+/// Every offset within a covering range is a valid snap position of the area that contributes it.
+pub fn candidate_has_snap_position_at(candidate: &SnapPositionCandidate, offset: CssPixels) -> bool {
+ if candidate.offset == offset {
+ return true;
+ }
+ candidate
+ .covering_ranges
+ .iter()
+ .any(|range| offset >= range.start && offset <= range.end)
+}
+
+fn chosen_offset_is_visible_at_cross_axis_offset(
+ candidates: &[SnapPositionCandidate],
+ offset: CssPixels,
+ cross_axis_offset: CssPixels,
+) -> bool {
+ candidates.iter().any(|candidate| {
+ snap_area_is_visible_at_cross_axis_offset(candidate, cross_axis_offset)
+ && candidate_has_snap_position_at(candidate, offset)
+ })
+}
+
+pub fn snap_destination_for(
+ unsnapped_destination: CssPixelPoint,
+ x_offset: Option<CssPixels>,
+ y_offset: Option<CssPixels>,
+ evaluated_axes: SnapAxes,
+) -> SnapDestination {
+ SnapDestination {
+ position: CssPixelPoint {
+ x: x_offset.unwrap_or(unsnapped_destination.x),
+ y: y_offset.unwrap_or(unsnapped_destination.y),
+ },
+ snapped_x: x_offset.is_some(),
+ snapped_y: y_offset.is_some(),
+ evaluated_x: evaluated_axes.x,
+ evaluated_y: evaluated_axes.y,
+ snapped_areas: Default::default(),
+ }
+}
+
+pub fn chosen_offsets_are_mutually_visible(
+ candidates: &SnapAxisCandidates,
+ x_offset: CssPixels,
+ y_offset: CssPixels,
+) -> bool {
+ chosen_offset_is_visible_at_cross_axis_offset(&candidates.x_candidates, x_offset, y_offset)
+ && chosen_offset_is_visible_at_cross_axis_offset(&candidates.y_candidates, y_offset, x_offset)
+}
+
+pub fn choose_snap_offset_for_axis(
+ candidates: &[SnapPositionCandidate],
+ selection: &SnapAxisSelection,
+ snapport_size: CssPixels,
+ strictness: SnapStrictness,
+ cross_axis_offset: Option<CssPixels>,
+ only_area: Option<SnapAreaIdentity>,
+) -> Option<SnapAxisChoice> {
+ // AD-HOC: The parameters under which a proximity snap container snaps are left to the user agent. Match the
+ // threshold used by other engines, one third of the snapport size in the snapping axis.
+ let proximity_range = snapport_size / 3;
+ #[allow(non_snake_case)]
+ let SNAP_POSITION_BOUNDARY_TOLERANCE: CssPixels = CssPixels::from_integer(1);
+ let mut best_choice = None;
+ let mut best_distance = CssPixels::default();
+ let mut consider_candidate = |offset: CssPixels, candidate: &SnapPositionCandidate| {
+ let distance = abs(offset - selection.destination);
+ if strictness == SnapStrictness::Proximity && distance > proximity_range {
+ return;
+ }
+ if best_choice.is_none() || distance < best_distance {
+ best_choice = Some(SnapAxisChoice {
+ offset,
+ area: candidate.area,
+ });
+ best_distance = distance;
+ }
+ };
+ let mut first_always_stop_choice: Option<SnapAxisChoice> = None;
+ let mut track_always_stop_candidate = |candidate: &SnapPositionCandidate| {
+ if first_always_stop_choice
+ .as_ref()
+ .is_none_or(|choice| abs(candidate.offset - selection.start) < abs(choice.offset - selection.start))
+ {
+ first_always_stop_choice = Some(SnapAxisChoice {
+ offset: candidate.offset,
+ area: candidate.area,
+ });
+ }
+ };
+ for candidate in candidates {
+ if only_area.as_ref().is_some_and(|area| candidate.area != *area) {
+ continue;
+ }
+
+ // https://drafts.csswg.org/css-scroll-snap-1/#snap-scope
+ // Since the purpose of scroll snapping is to align content within the scrollport for optimal viewing, a
+ // scroll position cannot be considered a valid snap position if snapping to it would leave the contributing
+ // snap area entirely outside the snapport, even if it otherwise satisfies the required alignment of the snap
+ // area.
+ if cross_axis_offset.is_some_and(|offset| !snap_area_is_visible_at_cross_axis_offset(candidate, offset)) {
+ continue;
+ }
+ if selection.direction != CssPixels::default()
+ && candidate.always_stop
+ && is_beyond_in_direction(candidate.offset, selection.start, selection.direction)
+ {
+ track_always_stop_candidate(candidate);
+ }
+ if selection.starting_positions_boundary.is_none_or(|boundary| {
+ is_beyond_in_direction(candidate.offset, selection.start, selection.direction)
+ && is_at_or_beyond_in_direction(candidate.offset, boundary, selection.direction)
+ }) {
+ consider_candidate(candidate.offset, candidate);
+ }
+
+ // NB: Every offset in a covering range is a valid snap position, so such a range contributes the offset in it
+ // nearest the destination. A relative scroll may not select the part of a range it has already traveled
+ // past, which is the part at or behind the offset it started from.
+ // FIXME: Limit covering ranges to the offsets at which no snap area with scroll-snap-stop: always has entered
+ // the snapport yet, so a scroll within a covering snap area still stops ahead of such an area.
+ for covering_range in &candidate.covering_ranges {
+ let mut range_start = covering_range.start;
+ let mut range_end = covering_range.end;
+ if selection.starting_positions_boundary.is_some() {
+ if selection.direction > CssPixels::default() {
+ range_start = range_start.max(selection.start + SNAP_POSITION_BOUNDARY_TOLERANCE);
+ } else if selection.direction < CssPixels::default() {
+ range_end = range_end.min(selection.start - SNAP_POSITION_BOUNDARY_TOLERANCE);
+ }
+ }
+ if range_start > range_end {
+ continue;
+ }
+ consider_candidate(selection.destination.clamp(range_start, range_end), candidate);
+ }
+ }
+
+ // https://drafts.csswg.org/css-scroll-snap-1/#valdef-scroll-snap-type-mandatory
+ // If a valid snap position exists then the scroll container must snap at the termination of a scroll (if none
+ // exist then no snapping occurs).
+ // NB: A mandatory container whose scroll has no snap position ahead of it in the direction of travel therefore
+ // falls back to the snap position nearest the destination.
+ if best_choice.is_none()
+ && selection.starting_positions_boundary.is_some()
+ && strictness == SnapStrictness::Mandatory
+ {
+ let fallback_selection = SnapAxisSelection {
+ destination: selection.destination,
+ start: selection.destination,
+ direction: CssPixels::default(),
+ starting_positions_boundary: None,
+ };
+ best_choice = choose_snap_offset_for_axis(
+ candidates,
+ &fallback_selection,
+ snapport_size,
+ strictness,
+ cross_axis_offset,
+ only_area,
+ );
+ }
+
+ // https://drafts.csswg.org/css-scroll-snap-1/#scroll-snap-stop
+ // always
+ // The scroll container must not pass over a snap position defined by this element during the execution of a
+ // scrolling operation; it must instead snap to the first of this element's snap positions.
+ if let (Some(best), Some(first)) = (best_choice.as_ref(), first_always_stop_choice.as_ref()) {
+ let always_stop_position_is_passed_over = if selection.direction > CssPixels::default() {
+ best.offset > first.offset
+ } else {
+ best.offset < first.offset
+ };
+ if always_stop_position_is_passed_over {
+ best_choice = first_always_stop_choice;
+ }
+ }
+ best_choice
+}
+
+/// The axes a scroll selects a snap position in: those the container snaps in that the scroll traveled in, or every
+/// axis the container snaps in when the scroll traveled in none.
+pub fn axes_to_evaluate(container_axes: SnapAxes, strategy: &SnapSelectionStrategy) -> SnapAxes {
+ // NB: A scroll selects a snap position only in the axes it traveled in, so that the offset of an axis its input
+ // never moved is left where it is. A scroll that traveled in no axis, such as one with only an intended end
+ // position, selects a snap position in every axis the container snaps in.
+ let snaps_in_axis = |container_snaps_in_axis: bool, axis_displacement: CssPixels| {
+ container_snaps_in_axis && (strategy.displacement.is_zero() || axis_displacement != CssPixels::default())
+ };
+ SnapAxes {
+ x: snaps_in_axis(container_axes.x, strategy.displacement.x),
+ y: snaps_in_axis(container_axes.y, strategy.displacement.y),
+ }
+}
+
+pub fn build_snap_candidates(
+ geometry: &SnapContainerGeometry,
+ areas: &[SnapAreaGeometry],
+ collect_axes: SnapAxes,
+) -> SnapAxisCandidates {
+ let x_geometry = x_axis_geometry(geometry);
+ let y_geometry = y_axis_geometry(geometry);
+ let mut candidates = SnapAxisCandidates::default();
+ for area in areas {
+ let area_rect = &area.rect;
+ if collect_axes.x
+ && let Some(mut candidate) =
+ snap_position_candidate_for_axis(area.align_x, area_rect.left(), area_rect.width, &x_geometry)
+ {
+ candidate.area = area.identity;
+ candidate.always_stop = area.always_stop;
+ candidate.cross_axis_visible_range_start =
+ area_rect.top() - y_geometry.snapport_start - y_geometry.snapport_size;
+ candidate.cross_axis_visible_range_end = area_rect.bottom() - y_geometry.snapport_start;
+ candidates.x_candidates.push(candidate);
+ }
+ if collect_axes.y
+ && let Some(mut candidate) =
+ snap_position_candidate_for_axis(area.align_y, area_rect.top(), area_rect.height, &y_geometry)
+ {
+ candidate.area = area.identity;
+ candidate.always_stop = area.always_stop;
+ candidate.cross_axis_visible_range_start =
+ area_rect.left() - x_geometry.snapport_start - x_geometry.snapport_size;
+ candidate.cross_axis_visible_range_end = area_rect.right() - x_geometry.snapport_start;
+ candidates.y_candidates.push(candidate);
+ }
+ }
+ if collect_axes.x {
+ restrict_covering_ranges_to_valid_snap_positions(&mut candidates.x_candidates, x_geometry.snapport_size);
+ }
+ if collect_axes.y {
+ restrict_covering_ranges_to_valid_snap_positions(&mut candidates.y_candidates, y_geometry.snapport_size);
+ }
+ candidates
+}
+
+pub fn snap_areas_at_offset(
+ candidates: &[SnapPositionCandidate],
+ offset: CssPixels,
+ cross_axis_offset: CssPixels,
+) -> Vec<SnapAreaIdentity> {
+ let mut areas = Vec::new();
+ for candidate in candidates {
+ if !snap_area_is_visible_at_cross_axis_offset(candidate, cross_axis_offset) {
+ continue;
+ }
+ if candidate_has_snap_position_at(candidate, offset) && candidate.area.is_valid() {
+ areas.push(candidate.area);
+ }
+ }
+ areas
+}
+
+/// https://drafts.csswg.org/css-scroll-snap-1/#choosing
+pub fn select_snap_destination_with_candidates(
+ geometry: &SnapContainerGeometry,
+ candidates: &SnapAxisCandidates,
+ destination: CssPixelPoint,
+ strategy: &SnapSelectionStrategy,
+ evaluated_axes: SnapAxes,
+) -> SnapDestination {
+ let snaps_x = evaluated_axes.x;
+ let snaps_y = evaluated_axes.y;
+ if !snaps_x && !snaps_y {
+ return SnapDestination {
+ position: destination,
+ ..Default::default()
+ };
+ }
+ let snapport = &geometry.snapport;
+ let strictness = geometry.strictness;
+ let axis_selection = |axis_destination: CssPixels,
+ axis_displacement: CssPixels,
+ axis_start: Option<CssPixels>,
+ axis_boundary: Option<CssPixels>| {
+ let Some(axis_start) = axis_start.filter(|_| axis_displacement != CssPixels::default()) else {
+ return SnapAxisSelection {
+ destination: axis_destination,
+ start: axis_destination,
+ direction: CssPixels::default(),
+ starting_positions_boundary: None,
+ };
+ };
+ let mut boundary = None;
+ if strategy.r#type != SnapSelectionStrategyType::EndPosition {
+ boundary = Some(axis_boundary.unwrap_or(axis_start));
+ }
+ SnapAxisSelection {
+ destination: axis_destination,
+ start: axis_start,
+ direction: axis_displacement,
+ starting_positions_boundary: boundary,
+ }
+ };
+ let axis_of = |offset: Option<CssPixelPoint>, horizontal: bool| {
+ offset.map(|offset| if horizontal { offset.x } else { offset.y })
+ };
+ let x_selection = axis_selection(
+ destination.x,
+ strategy.displacement.x,
+ axis_of(strategy.start_offset, true),
+ axis_of(strategy.starting_positions_boundary, true),
+ );
+ let y_selection = axis_selection(
+ destination.y,
+ strategy.displacement.y,
+ axis_of(strategy.start_offset, false),
+ axis_of(strategy.starting_positions_boundary, false),
+ );
+ let choose_x = |cross_axis_offset: Option<CssPixels>, only_area: Option<SnapAreaIdentity>| {
+ choose_snap_offset_for_axis(
+ &candidates.x_candidates,
+ &x_selection,
+ snapport.width,
+ strictness,
+ cross_axis_offset,
+ only_area,
+ )
+ };
+ let choose_y = |cross_axis_offset: Option<CssPixels>, only_area: Option<SnapAreaIdentity>| {
+ choose_snap_offset_for_axis(
+ &candidates.y_candidates,
+ &y_selection,
+ snapport.height,
+ strictness,
+ cross_axis_offset,
+ only_area,
+ )
+ };
+ let mut x_choice = None;
+ let mut y_choice = None;
+ if snaps_x && snaps_y {
+ x_choice = choose_x(None, None);
+ y_choice = choose_y(None, None);
+ if let (Some(x), Some(y)) = (x_choice.as_ref(), y_choice.as_ref())
+ && !chosen_offsets_are_mutually_visible(candidates, x.offset, y.offset)
+ {
+ // AD-HOC: A snap area is visible at its own snap positions, so one axis keeps the position it chose while
+ // the other gives up its own and takes the one the same area offers. Of the two areas, the one
+ // leaving the scroll container nearest its destination is followed. This matches other engines.
+ let mut y_of_x_area = None;
+ let mut x_of_y_area = None;
+ if x.area.is_valid() {
+ y_of_x_area = choose_y(Some(x.offset), Some(x.area));
+ }
+ if y.area.is_valid() {
+ x_of_y_area = choose_x(Some(y.offset), Some(y.area));
+ }
+ let distance_to_destination = |x_axis_choice: &SnapAxisChoice, y_axis_choice: &SnapAxisChoice| {
+ math::hypot(
+ (x_axis_choice.offset - x_selection.destination).to_double(),
+ (y_axis_choice.offset - y_selection.destination).to_double(),
+ )
+ };
+ let mut follows_x_area = y_of_x_area.is_some();
+ if let (Some(y_of_x), Some(x_of_y)) = (y_of_x_area.as_ref(), x_of_y_area.as_ref()) {
+ follows_x_area = distance_to_destination(x, y_of_x) < distance_to_destination(x_of_y, y);
+ }
+ if follows_x_area {
+ y_choice = y_of_x_area;
+ } else if x_of_y_area.is_some() {
+ x_choice = x_of_y_area;
+ } else {
+ // NB: Neither area offers a snap position in both axes, so the axis whose chosen offset is farther
+ // from its destination is chosen again from the positions visible at the other axis's offset.
+ if abs(x.offset - x_selection.destination) <= abs(y.offset - y_selection.destination) {
+ y_choice = choose_y(Some(x.offset), None);
+ } else {
+ x_choice = choose_x(Some(y.offset), None);
+ }
+ }
+ }
+ if x_choice.is_some() && y_choice.is_none() {
+ x_choice = choose_x(Some(destination.y), None);
+ } else if y_choice.is_some() && x_choice.is_none() {
+ y_choice = choose_y(Some(destination.x), None);
+ }
+ } else if snaps_x {
+ x_choice = choose_x(Some(destination.y), None);
+ } else if snaps_y {
+ y_choice = choose_y(Some(destination.x), None);
+ }
+ let x_offset = x_choice.map(|choice| choice.offset);
+ let y_offset = y_choice.map(|choice| choice.offset);
+ let mut snap_destination =
+ snap_destination_for(destination, x_offset, y_offset, SnapAxes { x: snaps_x, y: snaps_y });
+ if let Some(x_offset) = x_offset {
+ snap_destination.snapped_areas.x =
+ snap_areas_at_offset(&candidates.x_candidates, x_offset, snap_destination.position.y);
+ }
+ if let Some(y_offset) = y_offset {
+ snap_destination.snapped_areas.y =
+ snap_areas_at_offset(&candidates.y_candidates, y_offset, snap_destination.position.x);
+ }
+ snap_destination
+}
+
+/// https://drafts.csswg.org/css-scroll-snap-1/#choosing
+pub fn select_snap_destination(
+ geometry: &SnapContainerGeometry,
+ areas: &[SnapAreaGeometry],
+ destination: CssPixelPoint,
+ strategy: &SnapSelectionStrategy,
+) -> SnapDestination {
+ let evaluated_axes = axes_to_evaluate(geometry.axes, strategy);
+ if evaluated_axes.is_empty() {
+ return SnapDestination {
+ position: destination,
+ ..Default::default()
+ };
+ }
+ let candidates = build_snap_candidates(geometry, areas, evaluated_axes);
+ select_snap_destination_with_candidates(geometry, &candidates, destination, strategy, evaluated_axes)
+}
+
+// The largest share of a momentum delta that the delta after it may keep for the momentum to be considered decaying.
+const MAXIMUM_MOMENTUM_DECAY_SHARE: f64 = 0.96;
+
+// The share a momentum delta keeps of the one before it is treated as no larger than this, so that momentum which
+// barely decays is predicted to travel a hundred times the distance of its latest delta rather than forever.
+const MAXIMUM_SLOW_MOMENTUM_DECAY_SHARE: f64 = 0.99;
+
+// The number of consecutively smaller momentum deltas after which momentum that decays only slowly is predicted from
+// anyway.
+const DECAYING_DELTAS_BEFORE_SLOW_DECAY_IS_PREDICTED_FROM: u32 = 3;
+
+/// The displacement the momentum of a flick has left to travel, estimated from the deltas that momentum has produced
+/// so far.
+#[derive(Default)]
+pub struct MomentumFlingEstimator {
+ previous_momentum_delta: Option<CssPixelPoint>,
+ consecutively_decaying_momentum_deltas: u32,
+}
+
+impl MomentumFlingEstimator {
+ pub fn reset(&mut self) {
+ self.previous_momentum_delta = None;
+ self.consecutively_decaying_momentum_deltas = 0;
+ }
+
+ /// The displacement left to travel, including the delta given; momentum that has not yet decayed far enough to
+ /// tell where it is headed reports no estimate.
+ pub fn estimate_remaining_displacement(&mut self, momentum_delta: CssPixelPoint) -> Option<CssPixelPoint> {
+ let previous_momentum_delta = self.previous_momentum_delta;
+ self.previous_momentum_delta = Some(momentum_delta);
+
+ // The share the delta keeps of the one before it is what the momentum decays by, so the first delta of a flick
+ // says nothing about where it is headed.
+ let previous_momentum_delta = previous_momentum_delta?;
+ let distance = math::hypot(momentum_delta.x.to_double(), momentum_delta.y.to_double());
+ let previous_distance = math::hypot(
+ previous_momentum_delta.x.to_double(),
+ previous_momentum_delta.y.to_double(),
+ );
+ if previous_distance <= 0.0 {
+ return None;
+ }
+ let decay_share = distance / previous_distance;
+ if decay_share < 1.0 {
+ self.consecutively_decaying_momentum_deltas = self.consecutively_decaying_momentum_deltas.wrapping_add(1);
+ } else {
+ self.consecutively_decaying_momentum_deltas = 0;
+ }
+ let momentum_is_decaying = decay_share < MAXIMUM_MOMENTUM_DECAY_SHARE
+ || (self.consecutively_decaying_momentum_deltas >= DECAYING_DELTAS_BEFORE_SLOW_DECAY_IS_PREDICTED_FROM
+ && decay_share < 1.0);
+ if !momentum_is_decaying {
+ return None;
+ }
+
+ // Each delta keeps the same share of the one before it, so the deltas still to come sum to the delta given
+ // divided by the share it loses each time.
+ let remaining_distance_factor = 1.0 / (1.0 - super::min(decay_share, MAXIMUM_SLOW_MOMENTUM_DECAY_SHARE));
+ Some(CssPixelPoint {
+ x: CssPixels::nearest_value_for(momentum_delta.x.to_double() * remaining_distance_factor),
+ y: CssPixels::nearest_value_for(momentum_delta.y.to_double() * remaining_distance_factor),
+ })
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/smooth_scroll_animation.rs b/Libraries/LibCompositing/Rust/src/scrolling/smooth_scroll_animation.rs
new file mode 100644
index 00000000000..1caf1937064
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/smooth_scroll_animation.rs
@@ -0,0 +1,268 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::{ScrollAnimationKind, min};
+use crate::time::Duration;
+use ak::math;
+use libgfx_rust::FloatPoint;
+
+// During a momentum scroll, each frame moves this fraction of the distance of the frame before it.
+pub const MOMENTUM_DISTANCE_SHARE_PER_FRAME: f64 = 0.92;
+pub const MOMENTUM_FRAME_DURATION_IN_SECONDS: f64 = 0.016;
+pub const MAXIMUM_MOMENTUM_DURATION_IN_SECONDS: f64 = 5.0;
+
+const SCROLL_SPEED_IN_PIXELS_PER_SECOND: f64 = 1000.0;
+const MAXIMUM_SCROLL_DURATION_IN_SECONDS: f64 = 0.2;
+
+// A wheel step takes longer the shorter its distance, within these bounds.
+const MINIMUM_WHEEL_SCROLL_DURATION_IN_SECONDS: f64 = 0.1;
+const MAXIMUM_WHEEL_SCROLL_DURATION_IN_SECONDS: f64 = 0.2;
+const WHEEL_SCROLL_DISTANCE_COVERED_AT_MAXIMUM_DURATION: f64 = 120.0;
+const WHEEL_SCROLL_DURATION_REDUCTION_PER_PIXEL: f64 = 1.0 / 3600.0;
+
+// INTEROP: The ease-in-out curve WebKit uses for programmatic smooth scrolling, cubic-bezier(0.42, 0, 0.58, 1). A retargeted
+// scroll changes y1 so that it keeps the speed it had.
+const EASING_CONTROL_POINT_X1: f64 = 0.42;
+const EASING_CONTROL_POINT_X2: f64 = 0.58;
+const EASING_CONTROL_POINT_Y2: f64 = 1.0;
+
+const MAXIMUM_EASING_SLOPE: f64 = 1000.0;
+const RETARGET_EASE_OUT_ALLOWANCE: f64 = 2.5;
+
+#[derive(Default)]
+pub struct Sample {
+ pub offset: FloatPoint,
+ pub complete: bool,
+}
+
+pub struct SmoothScrollAnimation {
+ start_offset: FloatPoint,
+ destination_offset: FloatPoint,
+ pixels_per_css_pixel: f64,
+ start_time: Duration,
+ duration: Duration,
+ kind: ScrollAnimationKind,
+ easing_control_point_y1: f64,
+}
+
+// https://drafts.csswg.org/css-easing/#cubic-bezier-algo
+fn cubic_bezier(t: f64, p1: f64, p2: f64) -> f64 {
+ 3.0 * (1.0 - t) * (1.0 - t) * t * p1 + 3.0 * (1.0 - t) * t * t * p2 + t * t * t
+}
+
+fn cubic_bezier_derivative(t: f64, p1: f64, p2: f64) -> f64 {
+ 3.0 * (1.0 - t) * (1.0 - t) * p1 + 6.0 * (1.0 - t) * t * (p2 - p1) + 3.0 * t * t * (1.0 - p2)
+}
+
+fn curve_parameter_for_progress(progress: f64) -> f64 {
+ // Find the curve parameter whose horizontal position is the progress: a few Newton steps usually land on it, and
+ // bisection finishes the job when the slope gets too flat for them.
+ let mut t = progress;
+ for _ in 0..8 {
+ let x = cubic_bezier(t, EASING_CONTROL_POINT_X1, EASING_CONTROL_POINT_X2) - progress;
+ if x.abs() < 1e-7 {
+ return t;
+ }
+ let slope = cubic_bezier_derivative(t, EASING_CONTROL_POINT_X1, EASING_CONTROL_POINT_X2);
+ if slope.abs() < 1e-6 {
+ break;
+ }
+ t -= x / slope;
+ }
+ let mut low = 0.0;
+ let mut high = 1.0;
+ while high - low > 1e-7 {
+ t = (low + high) / 2.0;
+ if cubic_bezier(t, EASING_CONTROL_POINT_X1, EASING_CONTROL_POINT_X2) < progress {
+ low = t;
+ } else {
+ high = t;
+ }
+ }
+ t
+}
+
+fn momentum_frames_for_distance(distance: f64) -> f64 {
+ let frames = (-math::log(1.0 - distance * (1.0 - 1.0 / MOMENTUM_DISTANCE_SHARE_PER_FRAME))
+ / math::log(MOMENTUM_DISTANCE_SHARE_PER_FRAME))
+ .ceil();
+ min(
+ frames,
+ MAXIMUM_MOMENTUM_DURATION_IN_SECONDS / MOMENTUM_FRAME_DURATION_IN_SECONDS,
+ )
+}
+
+impl SmoothScrollAnimation {
+ pub fn new(
+ start_offset: FloatPoint,
+ destination_offset: FloatPoint,
+ pixels_per_css_pixel: f64,
+ kind: ScrollAnimationKind,
+ ) -> Self {
+ assert!(pixels_per_css_pixel > 0.0);
+ let mut animation = Self {
+ start_offset,
+ destination_offset,
+ pixels_per_css_pixel,
+ start_time: Duration::zero(),
+ duration: Duration::zero(),
+ kind,
+ easing_control_point_y1: 0.0,
+ };
+ animation.duration = animation.duration_for_distance(destination_offset - start_offset);
+ animation
+ }
+
+ fn duration_for_distance(&self, distance: FloatPoint) -> Duration {
+ let horizontal_distance = distance.x as f64 / self.pixels_per_css_pixel;
+ let vertical_distance = distance.y as f64 / self.pixels_per_css_pixel;
+ let length = (horizontal_distance * horizontal_distance + vertical_distance * vertical_distance).sqrt();
+ if length == 0.0 {
+ return Duration::zero();
+ }
+ let duration_in_seconds = match self.kind {
+ ScrollAnimationKind::SmoothScroll => min(
+ length / SCROLL_SPEED_IN_PIXELS_PER_SECOND,
+ MAXIMUM_SCROLL_DURATION_IN_SECONDS,
+ ),
+ ScrollAnimationKind::Wheel => (MAXIMUM_WHEEL_SCROLL_DURATION_IN_SECONDS
+ - (length - WHEEL_SCROLL_DISTANCE_COVERED_AT_MAXIMUM_DURATION)
+ * WHEEL_SCROLL_DURATION_REDUCTION_PER_PIXEL)
+ .clamp(
+ MINIMUM_WHEEL_SCROLL_DURATION_IN_SECONDS,
+ MAXIMUM_WHEEL_SCROLL_DURATION_IN_SECONDS,
+ ),
+ ScrollAnimationKind::Momentum => momentum_frames_for_distance(length) * MOMENTUM_FRAME_DURATION_IN_SECONDS,
+ };
+ Duration::from_seconds_f64(duration_in_seconds)
+ }
+
+ fn eased_progress_at(&self, progress: f64) -> f64 {
+ if self.kind == ScrollAnimationKind::Momentum {
+ let frames = self.duration.to_seconds_f64() / MOMENTUM_FRAME_DURATION_IN_SECONDS;
+ let frames_elapsed = progress * frames;
+ return (1.0 - math::pow(MOMENTUM_DISTANCE_SHARE_PER_FRAME, frames_elapsed))
+ / (1.0 - math::pow(MOMENTUM_DISTANCE_SHARE_PER_FRAME, frames));
+ }
+
+ // https://drafts.csswg.org/cssom-view/#smooth-scroll
+ // A smooth scroll follows a user-agent-defined timing function.
+ cubic_bezier(
+ curve_parameter_for_progress(progress),
+ self.easing_control_point_y1,
+ EASING_CONTROL_POINT_Y2,
+ )
+ }
+
+ fn easing_slope_at(&self, progress: f64) -> f64 {
+ if self.kind == ScrollAnimationKind::Momentum {
+ let frames = self.duration.to_seconds_f64() / MOMENTUM_FRAME_DURATION_IN_SECONDS;
+ let frames_elapsed = progress * frames;
+ let decay = math::log(MOMENTUM_DISTANCE_SHARE_PER_FRAME);
+ return -math::pow(MOMENTUM_DISTANCE_SHARE_PER_FRAME, frames_elapsed) * decay * frames
+ / (1.0 - math::pow(MOMENTUM_DISTANCE_SHARE_PER_FRAME, frames));
+ }
+ let t = curve_parameter_for_progress(progress);
+ let horizontal_slope = cubic_bezier_derivative(t, EASING_CONTROL_POINT_X1, EASING_CONTROL_POINT_X2);
+ if horizontal_slope == 0.0 {
+ return 0.0;
+ }
+ cubic_bezier_derivative(t, self.easing_control_point_y1, EASING_CONTROL_POINT_Y2) / horizontal_slope
+ }
+
+ fn velocity_at(&self, elapsed: Duration) -> FloatPoint {
+ if self.duration.is_zero() {
+ return FloatPoint::default();
+ }
+ let duration_in_seconds = self.duration.to_seconds_f64();
+ let progress = ((elapsed - self.start_time).to_seconds_f64() / duration_in_seconds).clamp(0.0, 1.0);
+ let speed_per_pixel = self.easing_slope_at(progress) / duration_in_seconds;
+ let distance = self.destination_offset - self.start_offset;
+ FloatPoint {
+ x: (distance.x as f64 * speed_per_pixel) as f32,
+ y: (distance.y as f64 * speed_per_pixel) as f32,
+ }
+ }
+
+ pub fn sample(&self, elapsed: Duration) -> Sample {
+ let elapsed_since_start = elapsed - self.start_time;
+ if self.duration.is_zero() || elapsed_since_start >= self.duration {
+ return Sample {
+ offset: self.destination_offset,
+ complete: true,
+ };
+ }
+ let progress = (elapsed_since_start.to_seconds_f64() / self.duration.to_seconds_f64()).clamp(0.0, 1.0);
+ let eased_progress = self.eased_progress_at(progress);
+ Sample {
+ offset: FloatPoint {
+ x: (self.start_offset.x as f64
+ + (self.destination_offset.x - self.start_offset.x) as f64 * eased_progress)
+ as f32,
+ y: (self.start_offset.y as f64
+ + (self.destination_offset.y - self.start_offset.y) as f64 * eased_progress)
+ as f32,
+ },
+ complete: false,
+ }
+ }
+
+ pub fn retarget(&mut self, destination_offset: FloatPoint, elapsed: Duration) {
+ if destination_offset == self.destination_offset {
+ return;
+ }
+ let current_offset = self.sample(elapsed).offset;
+ let remaining_distance = destination_offset - current_offset;
+ let remaining_length = math::hypot(remaining_distance.x as f64, remaining_distance.y as f64);
+
+ // Only the speed along the new path carries over.
+ let mut velocity = 0.0;
+ if remaining_length != 0.0 {
+ let velocity_vector = self.velocity_at(elapsed);
+ velocity = (velocity_vector.x as f64 * remaining_distance.x as f64
+ + velocity_vector.y as f64 * remaining_distance.y as f64)
+ / remaining_length;
+ }
+ let mut duration = self.duration_for_distance(remaining_distance);
+
+ // An animation moving faster than the remaining distance needs would swing past the destination and back.
+ if velocity > 0.0 {
+ duration = min(
+ duration,
+ Duration::from_seconds_f64(remaining_length / velocity * RETARGET_EASE_OUT_ALLOWANCE),
+ );
+ }
+ self.start_offset = current_offset;
+ self.destination_offset = destination_offset;
+ self.start_time = elapsed;
+ self.duration = duration;
+ self.easing_control_point_y1 = 0.0;
+ if duration.is_zero() || remaining_length == 0.0 {
+ return;
+ }
+
+ // The curve's starting slope is y1 / x1.
+ let slope = velocity * duration.to_seconds_f64() / remaining_length;
+ self.easing_control_point_y1 =
+ EASING_CONTROL_POINT_X1 * slope.clamp(-MAXIMUM_EASING_SLOPE, MAXIMUM_EASING_SLOPE);
+ }
+
+ pub fn duration(&self) -> Duration {
+ self.duration
+ }
+ pub fn destination_offset(&self) -> FloatPoint {
+ self.destination_offset
+ }
+ pub fn kind(&self) -> ScrollAnimationKind {
+ self.kind
+ }
+
+ /// Moves where the scroll comes from and goes to by the same distance, which keeps its pace.
+ pub fn shift_by(&mut self, delta: FloatPoint) {
+ self.start_offset.translate_by(delta);
+ self.destination_offset.translate_by(delta);
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/wheel_gesture_identity.rs b/Libraries/LibCompositing/Rust/src/scrolling/wheel_gesture_identity.rs
new file mode 100644
index 00000000000..23126c06660
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/wheel_gesture_identity.rs
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A wheel gesture keeps scrolling the scroller its first event was routed to, so the compositor has to tell whether a wheel event continues the gesture it latched or starts another one.
+
+use super::{ScrollGesturePhase, USER_SCROLL_SETTLE_DELAY};
+use crate::time::{Duration, MonotonicTime};
+use libgfx_rust::FloatPoint;
+
+pub const WHEEL_GESTURE_MOMENTUM_GRACE_AFTER_END: Duration = Duration::from_milliseconds(100);
+pub const WHEEL_GESTURE_POSITION_SLOP_IN_CSS_PIXELS: f32 = 10.0;
+
+/// When a touchpad gesture ends: once its steps stop arriving for a while, or once the platform reports that the fingers
+/// lifted, however long they rest on the touchpad before that.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum TouchpadGestureEnd {
+ AfterIdleDelay,
+ WhenFingersLift,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+enum Kind {
+ PhaseLess,
+ Phased,
+}
+
+pub struct WheelGestureIdentity {
+ kind: Kind,
+ first_position: FloatPoint,
+ modifiers: u32,
+ last_event_time: MonotonicTime,
+ ended_at: Option<MonotonicTime>,
+ momentum_has_started: bool,
+}
+
+impl WheelGestureIdentity {
+ fn new(kind: Kind, first_position: FloatPoint, modifiers: u32, now: MonotonicTime) -> Self {
+ Self {
+ kind,
+ first_position,
+ modifiers,
+ last_event_time: now,
+ ended_at: None,
+ momentum_has_started: false,
+ }
+ }
+
+ fn kind_for(phase: ScrollGesturePhase) -> Kind {
+ if phase == ScrollGesturePhase::None {
+ Kind::PhaseLess
+ } else {
+ Kind::Phased
+ }
+ }
+
+ pub fn started_by(position: FloatPoint, phase: ScrollGesturePhase, modifiers: u32, now: MonotonicTime) -> Self {
+ let mut gesture = Self::new(Self::kind_for(phase), position, modifiers, now);
+ gesture.advance_to(phase, now);
+ gesture
+ }
+
+ /// Whether the fingers of a touchpad gesture are still on the touchpad, before it ends or hands over to momentum.
+ pub fn is_held_by_fingers(&self) -> bool {
+ self.kind == Kind::Phased && self.ended_at.is_none() && !self.momentum_has_started
+ }
+
+ /// Positions and the slop are in whatever unit the caller routes in.
+ pub fn is_continued_by(
+ &self,
+ position: FloatPoint,
+ phase: ScrollGesturePhase,
+ modifiers: u32,
+ now: MonotonicTime,
+ position_slop: f32,
+ touchpad_gesture_end: TouchpadGestureEnd,
+ ) -> bool {
+ let lasts_while_fingers_rest =
+ touchpad_gesture_end == TouchpadGestureEnd::WhenFingersLift && self.is_held_by_fingers();
+ if !lasts_while_fingers_rest && now - self.last_event_time > USER_SCROLL_SETTLE_DELAY {
+ return false;
+ }
+ if Self::kind_for(phase) != self.kind {
+ return false;
+ }
+ if self.kind == Kind::PhaseLess {
+ return modifiers == self.modifiers && position.distance_from(self.first_position) <= position_slop;
+ }
+ // Fingers that touch down while the momentum of the gesture runs start another gesture, whether or not the end of
+ // that momentum arrived first.
+ if phase == ScrollGesturePhase::Ongoing && self.momentum_has_started {
+ return false;
+ }
+ let Some(ended_at) = self.ended_at else {
+ return true;
+ };
+ let phase_may_follow_an_ended_gesture =
+ phase == ScrollGesturePhase::Momentum || phase == ScrollGesturePhase::Ended;
+ phase_may_follow_an_ended_gesture && now - ended_at <= WHEEL_GESTURE_MOMENTUM_GRACE_AFTER_END
+ }
+
+ pub fn advance_to(&mut self, phase: ScrollGesturePhase, now: MonotonicTime) {
+ self.last_event_time = now;
+ if phase == ScrollGesturePhase::Momentum {
+ self.momentum_has_started = true;
+ }
+ if phase != ScrollGesturePhase::Ended {
+ self.ended_at = None;
+ return;
+ }
+ if self.ended_at.is_none() {
+ self.ended_at = Some(now);
+ }
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/time.rs b/Libraries/LibCompositing/Rust/src/time.rs
new file mode 100644
index 00000000000..2f06f7f28df
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/time.rs
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Monotonic time as the compositor's scroll and input logic counts it: in nanoseconds, handed in by whoever calls.
+
+use std::ops::{Add, Sub};
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Duration(i64);
+
+impl Duration {
+ pub const fn zero() -> Self {
+ Self(0)
+ }
+
+ pub const fn from_nanoseconds(nanoseconds: i64) -> Self {
+ Self(nanoseconds)
+ }
+
+ pub const fn from_milliseconds(milliseconds: i64) -> Self {
+ Self(milliseconds.saturating_mul(1_000_000))
+ }
+
+ pub fn from_seconds_f64(seconds: f64) -> Self {
+ assert!(!seconds.is_nan());
+ if seconds >= i64::MAX as f64 {
+ return Self(i64::MAX);
+ }
+ if seconds <= i64::MIN as f64 {
+ return Self(i64::MIN);
+ }
+ let mut integer_seconds = seconds as i64;
+ if integer_seconds as f64 > seconds {
+ integer_seconds = integer_seconds.saturating_sub(1);
+ }
+ let fractional_nanoseconds = (seconds - integer_seconds as f64) * 1_000_000_000.0;
+ let mut integer_nanoseconds = fractional_nanoseconds as u32;
+ if fractional_nanoseconds - integer_nanoseconds as f64 >= 0.5 {
+ integer_nanoseconds += 1;
+ }
+ let nanoseconds = integer_seconds as i128 * 1_000_000_000 + integer_nanoseconds as i128;
+ Self(nanoseconds.clamp(i64::MIN as i128, i64::MAX as i128) as i64)
+ }
+
+ pub const fn nanoseconds(self) -> i64 {
+ self.0
+ }
+
+ pub fn to_seconds_f64(self) -> f64 {
+ self.0.div_euclid(1_000_000_000) as f64 + self.0.rem_euclid(1_000_000_000) as f64 / 1_000_000_000.0
+ }
+
+ pub const fn is_zero(self) -> bool {
+ self.0 == 0
+ }
+}
+
+impl Add for Duration {
+ type Output = Self;
+
+ fn add(self, other: Self) -> Self {
+ Self(self.0.saturating_add(other.0))
+ }
+}
+
+impl Sub for Duration {
+ type Output = Self;
+
+ fn sub(self, other: Self) -> Self {
+ Self(self.0.saturating_sub(other.0))
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct MonotonicTime(i64);
+
+impl MonotonicTime {
+ pub const fn from_nanoseconds(nanoseconds: i64) -> Self {
+ Self(nanoseconds)
+ }
+
+ pub const fn nanoseconds(self) -> i64 {
+ self.0
+ }
+}
+
+impl Add<Duration> for MonotonicTime {
+ type Output = Self;
+
+ fn add(self, duration: Duration) -> Self {
+ Self(self.0.saturating_add(duration.0))
+ }
+}
+
+impl Sub<Duration> for MonotonicTime {
+ type Output = Self;
+
+ fn sub(self, duration: Duration) -> Self {
+ Self(self.0.saturating_sub(duration.0))
+ }
+}
+
+impl Sub for MonotonicTime {
+ type Output = Duration;
+
+ fn sub(self, other: Self) -> Duration {
+ Duration(self.0.saturating_sub(other.0))
+ }
+}
diff --git a/Libraries/LibCompositing/Types.ipc b/Libraries/LibCompositing/Types.ipc
index 6cb0ed5e0d4..2799e2a1199 100644
--- a/Libraries/LibCompositing/Types.ipc
+++ b/Libraries/LibCompositing/Types.ipc
@@ -84,20 +84,20 @@ struct Compositing::AsyncScrollOffset {
u64 context_user_input_scroll_count;
}
-[ExistingCpp]
+[ExistingCpp, RustDerive=Copy+Eq+Hash+Default]
struct Compositing::SnapAreaIdentity {
Web::UniqueNodeID node_id;
u8 pseudo_element_type;
}
-[ExistingCpp]
+[ExistingCpp, RustDerive=Eq+Default]
struct Compositing::SnappedAreas {
Vector<Compositing::SnapAreaIdentity> x;
Vector<Compositing::SnapAreaIdentity> y;
}
// NB: CSS pixel points travel as their raw fixed-point values, so that a destination is exactly the one selected.
-[ExistingCpp]
+[ExistingCpp, RustDerive=Eq+Default]
struct Compositing::SnapDestination {
Web::CSSPixelPoint position;
bool snapped_x;
diff --git a/Libraries/LibGfx/Rust/src/geometry.rs b/Libraries/LibGfx/Rust/src/geometry.rs
index 0f8884ea04b..e87175d9aa2 100644
--- a/Libraries/LibGfx/Rust/src/geometry.rs
+++ b/Libraries/LibGfx/Rust/src/geometry.rs
@@ -68,6 +68,53 @@ pub enum Orientation {
Vertical,
}
+impl FloatPoint {
+ pub fn is_zero(self) -> bool {
+ self.x == 0.0 && self.y == 0.0
+ }
+
+ pub fn translate_by(&mut self, delta: Self) {
+ self.x += delta.x;
+ self.y += delta.y;
+ }
+
+ pub fn scaled(self, factor: f32) -> Self {
+ Self {
+ x: self.x * factor,
+ y: self.y * factor,
+ }
+ }
+
+ pub fn distance_from(self, other: Self) -> f32 {
+ if self == other {
+ return 0.0;
+ }
+ ak::math::hypot(self.x - other.x, self.y - other.y)
+ }
+}
+
+impl Add for FloatPoint {
+ type Output = Self;
+
+ fn add(self, other: Self) -> Self {
+ Self {
+ x: self.x + other.x,
+ y: self.y + other.y,
+ }
+ }
+}
+
+impl Sub for FloatPoint {
+ type Output = Self;
+
+ fn sub(self, other: Self) -> Self {
+ Self {
+ x: self.x - other.x,
+ y: self.y - other.y,
+ }
+ }
+}
+
impl FloatVector3 {
pub fn dot(self, other: Self) -> f32 {
self.x * other.x + self.y * other.y + self.z * other.z