Skip to content

Truly independent web browser

LibCompositing: Port the scrolling state and the scroll tree to Rust

Aliaksandr Kalenik79cda6274789
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/async_scroll_tree.rs b/Libraries/LibCompositing/Rust/src/scrolling/async_scroll_tree.rs
new file mode 100644
index 00000000000..6b58e7a61f1
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/async_scroll_tree.rs
@@ -0,0 +1,1144 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Mutable compositor-side copy of AsyncScrollingState. Current scroll offsets live in ScrollStateSnapshot; this tree owns scroll node geometry and derived hit-test targets.
+
+use super::*;
+use crate::css_pixels::{CssPixelPoint, CssPixels};
+use libgfx_rust::{CornerRadii, FloatPoint, FloatRect, FloatSize, IntPoint, IntRect};
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum WheelHitTestOutcome {
+ FoundScrollTarget,
+ #[default]
+ NoScrollTarget,
+ BlockedByMainThreadRegion,
+ BlockedByWheelEventRegion,
+ HitTestTargetsOfAnotherVisualContextTree,
+}
+
+#[derive(Clone, Copy, Debug, Default)]
+pub struct WheelHitTestResult {
+ pub outcome: WheelHitTestOutcome,
+ // Set exactly when the outcome is FoundScrollTarget.
+ pub scroll_node_index: Option<SpatialNodeIndex>,
+ // The scroller the wheel is over, which is where the search for `scroll_node_index` started. It is set even if
+ // neither it nor any scroller around it can scroll by the delta.
+ pub innermost_scroll_node_index: Option<SpatialNodeIndex>,
+ // The scroller that keeps the delta from the scrollers around it, when the outcome is NoScrollTarget for that
+ // reason rather than because no scroller is left to offer it to.
+ pub scroll_node_index_keeping_the_scroll: Option<SpatialNodeIndex>,
+}
+
+impl WheelHitTestResult {
+ pub fn is_blocked_by_a_region(&self) -> bool {
+ self.outcome == WheelHitTestOutcome::BlockedByMainThreadRegion
+ || self.outcome == WheelHitTestOutcome::BlockedByWheelEventRegion
+ }
+}
+
+// Where the first step of a wheel gesture over a position goes, as far as the admission and the hit test decide it.
+pub struct FirstWheelStepRoute {
+ pub decision: InputRoutingDecision,
+ pub scroller: Option<AsyncScrollNodeStableID>,
+}
+
+pub struct FirstWheelStepRouteForTesting {
+ pub route: FirstWheelStepRoute,
+ // The document whose scrolling state decided the route.
+ pub document_id: Option<UniqueNodeId>,
+}
+
+// What the wheel hit test does where a nested context's content is painted.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum NestedContextRegions {
+ // The step is left to the page, which hands it to the nested navigable.
+ LeaveToMainThread,
+ // The step is handed to the nested context under it, which only gets here if there is none.
+ HandToNestedContext,
+ // The nested context passed the step on, so it goes to whatever is under the nested context.
+ Ignore,
+}
+
+// Where a wheel or the pointer over the content of a nested context lands in it.
+pub struct NestedContextHit {
+ pub child_context_id: CompositorContextId,
+ // Relative to the origin of the nested context's content box, in the device pixels of the containing context.
+ pub position_in_content_box: FloatPoint,
+ pub content_box_size: FloatSize,
+ // Where the nested context's content is painted among the other things in the containing context that take
+ // pointer input.
+ pub paint_order_index: u32,
+}
+
+pub struct WheelScrollTarget {
+ pub stable_node_id: AsyncScrollNodeStableID,
+ pub current_offset: FloatPoint,
+ pub start_offset: FloatPoint,
+ pub destination_offset: FloatPoint,
+}
+
+pub struct CachedWheelHitTestTarget {
+ pub target_scroll_node_index: Option<SpatialNodeIndex>,
+ pub context: ContextRef,
+ pub rect: FloatRect,
+ pub corner_radii: CornerRadii,
+ pub viewport_rect: Option<FloatRect>,
+ pub paint_order_index: u32,
+}
+
+pub struct CachedMainThreadWheelEventTarget {
+ pub context: ContextRef,
+ pub rect: FloatRect,
+ pub viewport_rect: Option<FloatRect>,
+}
+
+pub struct CachedNestedContextWheelRegion {
+ pub region: NestedContextWheelRegion,
+ pub viewport_rect: Option<FloatRect>,
+}
+
+pub struct CachedBlockingWheelEventTarget {
+ pub context: ContextRef,
+ pub rect: FloatRect,
+ pub viewport_rect: Option<FloatRect>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ScrollChaining {
+ ToScrollableAncestors,
+ None,
+}
+
+pub struct AsyncScrollTree {
+ document_id: Option<UniqueNodeId>,
+ scroll_nodes: Vec<AsyncScrollNode>,
+ snap_containers: Vec<AsyncSnapContainer>,
+ device_pixels_per_css_pixel: f64,
+ wheel_hit_test_regions: Vec<WheelHitTestTarget>,
+ main_thread_wheel_event_regions: Vec<MainThreadWheelEventRegion>,
+ nested_context_wheel_regions: Vec<NestedContextWheelRegion>,
+ cached_wheel_hit_test_targets: Vec<CachedWheelHitTestTarget>,
+ blocking_wheel_event_regions: Vec<BlockingWheelEventRegion>,
+ cached_main_thread_wheel_event_targets: Vec<CachedMainThreadWheelEventTarget>,
+ cached_nested_context_wheel_regions: Vec<CachedNestedContextWheelRegion>,
+ cached_blocking_wheel_event_targets: Vec<CachedBlockingWheelEventTarget>,
+ visual_context_tree_structural_epoch: Option<u64>,
+ scroll_state_snapshot: ScrollStateSnapshot,
+ has_blocking_wheel_event_region_covering_viewport: bool,
+ viewport_keeps_horizontal_scrolls: bool,
+ viewport_keeps_vertical_scrolls: bool,
+}
+
+impl Default for AsyncScrollTree {
+ fn default() -> Self {
+ Self {
+ document_id: None,
+ scroll_nodes: Vec::new(),
+ snap_containers: Vec::new(),
+ device_pixels_per_css_pixel: 1.0,
+ wheel_hit_test_regions: Vec::new(),
+ main_thread_wheel_event_regions: Vec::new(),
+ nested_context_wheel_regions: Vec::new(),
+ cached_wheel_hit_test_targets: Vec::new(),
+ blocking_wheel_event_regions: Vec::new(),
+ cached_main_thread_wheel_event_targets: Vec::new(),
+ cached_nested_context_wheel_regions: Vec::new(),
+ cached_blocking_wheel_event_targets: Vec::new(),
+ visual_context_tree_structural_epoch: None,
+ scroll_state_snapshot: ScrollStateSnapshot::default(),
+ has_blocking_wheel_event_region_covering_viewport: false,
+ viewport_keeps_horizontal_scrolls: false,
+ viewport_keeps_vertical_scrolls: false,
+ }
+ }
+}
+
+struct NestedContextWheelRegionHit<'a> {
+ region: &'a NestedContextWheelRegion,
+ position_in_context: FloatPoint,
+}
+
+impl AsyncScrollTree {
+ pub fn document_id(&self) -> Option<UniqueNodeId> {
+ self.document_id
+ }
+ pub fn scroll_nodes(&self) -> &[AsyncScrollNode] {
+ &self.scroll_nodes
+ }
+
+ // Scroll offsets are held in the device pixels of the display list; snap geometry is in the CSS pixels it was
+ // recorded from, at the scale the display list carries.
+ pub fn device_pixels_per_css_pixel(&self) -> f64 {
+ self.device_pixels_per_css_pixel
+ }
+ pub fn has_nested_contexts(&self) -> bool {
+ !self.nested_context_wheel_regions.is_empty()
+ }
+ pub fn has_wheel_hit_test_targets_for(&self, visual_context_tree: &AccumulatedVisualContextTree) -> bool {
+ self.visual_context_tree_structural_epoch == Some(visual_context_tree.structural_epoch())
+ }
+
+ pub fn set_state(&mut self, state: AsyncScrollingState) {
+ self.document_id = state.document_id;
+ self.scroll_nodes = state.scroll_nodes;
+ self.snap_containers = state.snap_containers;
+ self.device_pixels_per_css_pixel = state.device_pixels_per_css_pixel;
+ self.wheel_hit_test_regions = state.wheel_hit_test_targets;
+ self.main_thread_wheel_event_regions = state.main_thread_wheel_event_regions;
+ self.nested_context_wheel_regions = state.nested_context_wheel_regions;
+ self.blocking_wheel_event_regions = state.blocking_wheel_event_regions;
+ self.has_blocking_wheel_event_region_covering_viewport =
+ state.has_blocking_wheel_event_region_covering_viewport;
+ self.viewport_keeps_horizontal_scrolls = state.viewport_keeps_horizontal_scrolls;
+ self.viewport_keeps_vertical_scrolls = state.viewport_keeps_vertical_scrolls;
+ self.cached_wheel_hit_test_targets.clear();
+ self.cached_main_thread_wheel_event_targets.clear();
+ self.cached_nested_context_wheel_regions.clear();
+ self.cached_blocking_wheel_event_targets.clear();
+ self.visual_context_tree_structural_epoch = None;
+ }
+}
+
+// A first step of a wheel gesture is latched to the scroller the hit test found, and is otherwise left to the page for
+// the outcome's reason.
+pub fn input_routing_decision_for_first_wheel_step(outcome: WheelHitTestOutcome) -> InputRoutingDecision {
+ match outcome {
+ WheelHitTestOutcome::FoundScrollTarget => InputRoutingDecision::Latched,
+ WheelHitTestOutcome::NoScrollTarget => InputRoutingDecision::NoScrollTarget,
+ WheelHitTestOutcome::BlockedByMainThreadRegion => InputRoutingDecision::BlockedByMainThreadRegion,
+ WheelHitTestOutcome::BlockedByWheelEventRegion => InputRoutingDecision::BlockedByWheelEventRegion,
+ WheelHitTestOutcome::HitTestTargetsOfAnotherVisualContextTree => {
+ InputRoutingDecision::HitTestTargetsOfAnotherVisualContextTree
+ }
+ }
+}
+
+impl AsyncScrollTree {
+ pub fn scroll_node_for_index(&self, scroll_node_index: SpatialNodeIndex) -> Option<&AsyncScrollNode> {
+ self.scroll_nodes
+ .iter()
+ .find(|node| node.scroll_node_index == scroll_node_index)
+ }
+}
+
+fn delta_is_mainly_vertical(delta: FloatPoint) -> bool {
+ delta.y.abs() >= delta.x.abs()
+}
+
+// https://drafts.csswg.org/css-overscroll-1/#overscroll-behavior-properties
+// A step is taken by one scroller, and a touchpad rarely moves along one axis exactly, so the main axis of the step
+// decides whether a scroller that cannot take it passes it on.
+fn node_chains_scroll_to_ancestors(node: &AsyncScrollNode, delta: FloatPoint) -> bool {
+ if delta_is_mainly_vertical(delta) {
+ node.chains_scroll_to_ancestors_vertically
+ } else {
+ node.chains_scroll_to_ancestors_horizontally
+ }
+}
+
+impl AsyncScrollTree {
+ // The scroller, of the given one and those it passes a scroll by the delta on to, that takes a wheel step by it, as
+ // the hit test finds one for a step over the given scroller.
+ pub fn hit_test_result_for_scroll_node(
+ &self,
+ scroll_node_index: SpatialNodeIndex,
+ delta: FloatPoint,
+ in_flight_destination_for: &dyn Fn(AsyncScrollNodeStableID) -> Option<FloatPoint>,
+ ) -> WheelHitTestResult {
+ let can_take_step = |node: &AsyncScrollNode| {
+ let in_flight_destination = in_flight_destination_for(node.stable_node_id);
+ Self::can_scroll_node_from_offset_by_delta(
+ node,
+ in_flight_destination.unwrap_or(Self::scroll_offset_for_scroll_node(node, &self.scroll_state_snapshot)),
+ delta,
+ )
+ };
+ let mut node = self.scroll_node_for_index(scroll_node_index);
+ while let Some(current) = node {
+ if can_take_step(current) {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::FoundScrollTarget,
+ scroll_node_index: Some(current.scroll_node_index),
+ innermost_scroll_node_index: Some(scroll_node_index),
+ ..Default::default()
+ };
+ }
+ // https://drafts.csswg.org/css-overscroll-1/#scroll-chaining-and-boundary-default-actions
+ // If a scroll container has no potential to scroll, because it does not overflow in the direction of the
+ // scroll, the element is always considered to be at the scroll boundary.
+ // NB: A scroll container that keeps its scrolls has a scroll node even when it has nothing to scroll.
+ if !node_chains_scroll_to_ancestors(current, delta) {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::NoScrollTarget,
+ innermost_scroll_node_index: Some(scroll_node_index),
+ scroll_node_index_keeping_the_scroll: Some(current.scroll_node_index),
+ ..Default::default()
+ };
+ }
+ let Some(parent) = current.parent_scroll_node_index else {
+ break;
+ };
+ node = self.scroll_node_for_index(parent);
+ }
+ WheelHitTestResult {
+ outcome: WheelHitTestOutcome::NoScrollTarget,
+ innermost_scroll_node_index: Some(scroll_node_index),
+ ..Default::default()
+ }
+ }
+
+ // Of the scroller and the scrollers around it that a scroll by the delta may be passed on to, the outermost one a
+ // wheel can scroll along the main axis of the delta at all, wherever it is scrolled to.
+ pub fn outermost_scroll_node_wheel_scrollable_along_main_axis_of(
+ &self,
+ innermost_scroll_node_index: SpatialNodeIndex,
+ delta: FloatPoint,
+ ) -> Option<SpatialNodeIndex> {
+ let mut outermost_scroll_node_index = None;
+ let mut scroll_node_index = innermost_scroll_node_index;
+ for _ in 0..self.scroll_nodes.len() {
+ let Some(node) = self.scroll_node_for_index(scroll_node_index) else {
+ break;
+ };
+ if if delta_is_mainly_vertical(delta) {
+ node.can_be_wheel_scrolled_vertically
+ } else {
+ node.can_be_wheel_scrolled_horizontally
+ } {
+ outermost_scroll_node_index = Some(node.scroll_node_index);
+ }
+ if !node_chains_scroll_to_ancestors(node, delta) {
+ break;
+ }
+ let Some(parent) = node.parent_scroll_node_index else {
+ break;
+ };
+ scroll_node_index = parent;
+ }
+ outermost_scroll_node_index
+ }
+
+ pub fn snap_container_for_node(&self, scroll_node_index: SpatialNodeIndex) -> Option<&AsyncSnapContainer> {
+ self.snap_containers
+ .iter()
+ .find(|snap_container| snap_container.scroll_node_index == scroll_node_index)
+ }
+
+ fn scroll_node_for_stable_id(&self, stable_node_id: AsyncScrollNodeStableID) -> Option<&AsyncScrollNode> {
+ self.scroll_nodes
+ .iter()
+ .find(|node| node.stable_node_id == stable_node_id)
+ }
+
+ fn clamp_scroll_offset_to_node(node: &AsyncScrollNode, mut scroll_offset: FloatPoint) -> FloatPoint {
+ scroll_offset.x = max(node.min_scroll_offset.x, min(scroll_offset.x, node.max_scroll_offset.x));
+ scroll_offset.y = max(node.min_scroll_offset.y, min(scroll_offset.y, node.max_scroll_offset.y));
+ scroll_offset
+ }
+
+ pub fn scroll_offset_for_scroll_node(
+ node: &AsyncScrollNode,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ ) -> FloatPoint {
+ let device_offset = scroll_state_snapshot.device_offset_for_index(node.scroll_node_index);
+ FloatPoint {
+ x: -device_offset.x,
+ y: -device_offset.y,
+ }
+ }
+
+ fn can_scroll_node_by_delta(
+ node: &AsyncScrollNode,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ delta: FloatPoint,
+ ) -> bool {
+ Self::can_scroll_node_from_offset_by_delta(
+ node,
+ Self::scroll_offset_for_scroll_node(node, scroll_state_snapshot),
+ delta,
+ )
+ }
+
+ fn can_scroll_node_from_offset_by_delta(
+ node: &AsyncScrollNode,
+ scroll_offset: FloatPoint,
+ delta: FloatPoint,
+ ) -> bool {
+ if node.can_be_wheel_scrolled_horizontally && delta.x < 0.0 && scroll_offset.x > node.min_scroll_offset.x {
+ return true;
+ }
+ if node.can_be_wheel_scrolled_horizontally && delta.x > 0.0 && scroll_offset.x < node.max_scroll_offset.x {
+ return true;
+ }
+ if node.can_be_wheel_scrolled_vertically && delta.y < 0.0 && scroll_offset.y > node.min_scroll_offset.y {
+ return true;
+ }
+ if node.can_be_wheel_scrolled_vertically && delta.y > 0.0 && scroll_offset.y < node.max_scroll_offset.y {
+ return true;
+ }
+ false
+ }
+
+ fn scrollable_ancestor_for_node(
+ &self,
+ scroll_node_index: SpatialNodeIndex,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ delta: FloatPoint,
+ ) -> Option<SpatialNodeIndex> {
+ let mut node = self.scroll_node_for_index(scroll_node_index)?;
+ while node_chains_scroll_to_ancestors(node, delta) && node.parent_scroll_node_index.is_some() {
+ node = self.scroll_node_for_index(node.parent_scroll_node_index?)?;
+ if Self::can_scroll_node_by_delta(node, scroll_state_snapshot, delta) {
+ return Some(node.scroll_node_index);
+ }
+ }
+ None
+ }
+
+ fn apply_scroll_delta_to_node(
+ &self,
+ node: &AsyncScrollNode,
+ delta: FloatPoint,
+ scroll_state_snapshot: &mut ScrollStateSnapshot,
+ ) -> FloatPoint {
+ let old_scroll_offset = Self::scroll_offset_for_scroll_node(node, scroll_state_snapshot);
+ let wheel_scrollable_delta = FloatPoint {
+ x: if node.can_be_wheel_scrolled_horizontally {
+ delta.x
+ } else {
+ 0.0
+ },
+ y: if node.can_be_wheel_scrolled_vertically {
+ delta.y
+ } else {
+ 0.0
+ },
+ };
+ let new_scroll_offset = Self::clamp_scroll_offset_to_node(node, old_scroll_offset + wheel_scrollable_delta);
+ if new_scroll_offset == old_scroll_offset {
+ return delta;
+ }
+ scroll_state_snapshot.set_device_offset_for_index(
+ node.scroll_node_index,
+ FloatPoint {
+ x: -new_scroll_offset.x,
+ y: -new_scroll_offset.y,
+ },
+ );
+ let consumed_delta = FloatPoint {
+ x: new_scroll_offset.x - old_scroll_offset.x,
+ y: new_scroll_offset.y - old_scroll_offset.y,
+ };
+ FloatPoint {
+ x: delta.x - consumed_delta.x,
+ y: delta.y - consumed_delta.y,
+ }
+ }
+
+ pub fn apply_scroll_delta(
+ &mut self,
+ mut scroll_node_index: SpatialNodeIndex,
+ delta: FloatPoint,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ scroll_state_snapshot: &mut ScrollStateSnapshot,
+ scroll_chaining: ScrollChaining,
+ ) -> Option<AsyncScrollOffset> {
+ // The compositor can advance only the scroll offsets it owns in this snapshot. Hit testing already selects an
+ // ancestor when the target cannot scroll in the wheel direction at all, so once a node moves it consumes the event.
+ for _ in 0..self.scroll_nodes.len() {
+ if delta.is_zero() {
+ break;
+ }
+ let Some(node) = self.scroll_node_for_index(scroll_node_index) else {
+ break;
+ };
+ let remaining_delta = self.apply_scroll_delta_to_node(node, delta, scroll_state_snapshot);
+ if remaining_delta != delta {
+ resolve_sticky_offsets(visual_context_tree, scroll_state_snapshot);
+ return Some(AsyncScrollOffset {
+ stable_node_id: node.stable_node_id,
+ compositor_scroll_offset: Self::scroll_offset_for_scroll_node(node, scroll_state_snapshot),
+ unadopted_scroll_delta: delta - remaining_delta,
+ last_relative_scroll_delta: FloatPoint::default(),
+ visual_viewport_scale: None,
+ applied_scroll_request_id: 0,
+ user_input_scroll_count: 0,
+ context_user_input_scroll_count: 0,
+ });
+ }
+ if scroll_chaining == ScrollChaining::None {
+ break;
+ }
+ let Some(ancestor_scroll_node_index) =
+ self.scrollable_ancestor_for_node(scroll_node_index, scroll_state_snapshot, delta)
+ else {
+ break;
+ };
+ scroll_node_index = ancestor_scroll_node_index;
+ }
+ None
+ }
+
+ pub fn select_wheel_scroll_target(
+ &self,
+ mut scroll_node_index: SpatialNodeIndex,
+ delta: FloatPoint,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ in_flight_destination_for: &dyn Fn(AsyncScrollNodeStableID) -> Option<FloatPoint>,
+ scroll_chaining: ScrollChaining,
+ ) -> Option<WheelScrollTarget> {
+ // Each box is measured from where its scroll in flight is headed, so a box already headed for its extent passes the
+ // first step of a gesture on to an ancestor.
+ for _ in 0..self.scroll_nodes.len() {
+ let node = self.scroll_node_for_index(scroll_node_index)?;
+ let start_offset = in_flight_destination_for(node.stable_node_id)
+ .unwrap_or(Self::scroll_offset_for_scroll_node(node, scroll_state_snapshot));
+ let wheel_scrollable_delta = FloatPoint {
+ x: if node.can_be_wheel_scrolled_horizontally {
+ delta.x
+ } else {
+ 0.0
+ },
+ y: if node.can_be_wheel_scrolled_vertically {
+ delta.y
+ } else {
+ 0.0
+ },
+ };
+ let destination_offset = Self::clamp_scroll_offset_to_node(node, start_offset + wheel_scrollable_delta);
+ if destination_offset != start_offset {
+ return Some(WheelScrollTarget {
+ stable_node_id: node.stable_node_id,
+ current_offset: Self::scroll_offset_for_scroll_node(node, scroll_state_snapshot),
+ start_offset,
+ destination_offset,
+ });
+ }
+ if scroll_chaining == ScrollChaining::None || !node_chains_scroll_to_ancestors(node, delta) {
+ return None;
+ }
+ scroll_node_index = node.parent_scroll_node_index?;
+ }
+ None
+ }
+
+ pub fn rebuild_wheel_hit_test_targets(
+ &mut self,
+ display_list: Option<&DisplayList>,
+ visual_context_tree: Option<&AccumulatedVisualContextTree>,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ ) {
+ self.cached_wheel_hit_test_targets.clear();
+ self.cached_main_thread_wheel_event_targets.clear();
+ self.cached_nested_context_wheel_regions.clear();
+ self.cached_blocking_wheel_event_targets.clear();
+ self.visual_context_tree_structural_epoch = None;
+ self.scroll_state_snapshot = scroll_state_snapshot.clone();
+ let (Some(display_list), Some(visual_context_tree)) = (display_list, visual_context_tree) else {
+ return;
+ };
+ assert_eq!(
+ display_list.compatible_visual_context_tree_structural_epoch(),
+ visual_context_tree.structural_epoch()
+ );
+ self.visual_context_tree_structural_epoch = Some(visual_context_tree.structural_epoch());
+ let context_is_valid = |context| visual_context_tree.context_is_valid(context);
+ let spatial_context_has_visual_animation =
+ visual_context_tree.spatial_nodes_in_subtrees_of_transform_animations();
+ let viewport_rect_for_context = |context: ContextRef, rect| {
+ if *spatial_context_has_visual_animation.get(context.spatial.0 as usize)? {
+ return None;
+ }
+ Some(visual_context_tree.transform_rect_to_viewport(
+ context.spatial,
+ rect,
+ scroll_state_snapshot,
+ IncludeVisualViewportTransform::Yes,
+ ))
+ };
+ self.cached_wheel_hit_test_targets
+ .reserve(self.wheel_hit_test_regions.len());
+ for target in &self.wheel_hit_test_regions {
+ if !context_is_valid(target.context) {
+ continue;
+ }
+ self.cached_wheel_hit_test_targets.push(CachedWheelHitTestTarget {
+ target_scroll_node_index: target.target_scroll_node_index,
+ context: target.context,
+ rect: target.rect,
+ corner_radii: target.corner_radii,
+ viewport_rect: viewport_rect_for_context(target.context, target.rect),
+ paint_order_index: target.paint_order_index,
+ });
+ }
+ self.cached_main_thread_wheel_event_targets
+ .reserve(self.main_thread_wheel_event_regions.len());
+ for region in &self.main_thread_wheel_event_regions {
+ if !context_is_valid(region.context) {
+ continue;
+ }
+ self.cached_main_thread_wheel_event_targets
+ .push(CachedMainThreadWheelEventTarget {
+ context: region.context,
+ rect: region.rect,
+ viewport_rect: viewport_rect_for_context(region.context, region.rect),
+ });
+ }
+ self.cached_nested_context_wheel_regions
+ .reserve(self.nested_context_wheel_regions.len());
+ for region in &self.nested_context_wheel_regions {
+ if !context_is_valid(region.context) {
+ continue;
+ }
+ self.cached_nested_context_wheel_regions
+ .push(CachedNestedContextWheelRegion {
+ region: *region,
+ viewport_rect: viewport_rect_for_context(region.context, region.rect),
+ });
+ }
+ for region in &self.blocking_wheel_event_regions {
+ // Keep invalid blockers so hit testing fails closed when their extent cannot be determined.
+ self.cached_blocking_wheel_event_targets
+ .push(CachedBlockingWheelEventTarget {
+ context: region.context,
+ rect: region.rect,
+ viewport_rect: if context_is_valid(region.context) {
+ viewport_rect_for_context(region.context, region.rect)
+ } else {
+ None
+ },
+ });
+ }
+ }
+}
+
+fn rounded_rect_contains_point(rect: FloatRect, corner_radii: CornerRadii, position_in_context: FloatPoint) -> bool {
+ if !rect.contains_point(position_in_context) {
+ return false;
+ }
+ if !corner_radii.has_any_radius() {
+ return true;
+ }
+ corner_radii.contains_int_point(
+ IntPoint {
+ x: position_in_context.x as i32,
+ y: position_in_context.y as i32,
+ },
+ IntRect::new(rect.x as i32, rect.y as i32, rect.width as i32, rect.height as i32),
+ )
+}
+
+fn wheel_hit_test_target_contains_point(target: &CachedWheelHitTestTarget, position_in_context: FloatPoint) -> bool {
+ rounded_rect_contains_point(target.rect, target.corner_radii, position_in_context)
+}
+
+impl AsyncScrollTree {
+ pub fn scroll_offset_for_node(
+ &self,
+ scroll_node_index: SpatialNodeIndex,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ ) -> Option<FloatPoint> {
+ if let Some(node) = self.scroll_node_for_index(scroll_node_index) {
+ return Some(Self::scroll_offset_for_scroll_node(node, scroll_state_snapshot));
+ }
+ None
+ }
+
+ pub fn css_pixels_from_device_offset(&self, device_offset: FloatPoint) -> CssPixelPoint {
+ CssPixelPoint {
+ x: CssPixels::nearest_value_for(device_offset.x as f64 / self.device_pixels_per_css_pixel),
+ y: CssPixels::nearest_value_for(device_offset.y as f64 / self.device_pixels_per_css_pixel),
+ }
+ }
+
+ pub fn device_offset_from_css_pixels(&self, offset: CssPixelPoint) -> FloatPoint {
+ FloatPoint {
+ x: (offset.x.to_double() * self.device_pixels_per_css_pixel) as f32,
+ y: (offset.y.to_double() * self.device_pixels_per_css_pixel) as f32,
+ }
+ }
+
+ pub fn css_scroll_offset_for_node(
+ &self,
+ scroll_node_index: SpatialNodeIndex,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ ) -> Option<CssPixelPoint> {
+ self.scroll_offset_for_node(scroll_node_index, scroll_state_snapshot)
+ .map(|device_offset| self.css_pixels_from_device_offset(device_offset))
+ }
+
+ pub fn css_scroll_offset_for_scroll_node(
+ &self,
+ node: &AsyncScrollNode,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ ) -> CssPixelPoint {
+ self.css_pixels_from_device_offset(Self::scroll_offset_for_scroll_node(node, scroll_state_snapshot))
+ }
+
+ pub fn viewport_scroll_node_index(&self) -> Option<SpatialNodeIndex> {
+ for node in &self.scroll_nodes {
+ if node.is_viewport {
+ return Some(node.scroll_node_index);
+ }
+ }
+ None
+ }
+
+ pub fn scroll_node_index_for_stable_id(&self, stable_node_id: AsyncScrollNodeStableID) -> Option<SpatialNodeIndex> {
+ if let Some(node) = self.scroll_node_for_stable_id(stable_node_id) {
+ return Some(node.scroll_node_index);
+ }
+ None
+ }
+
+ pub fn blocks_wheel_event_at_position(
+ &self,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ ) -> bool {
+ if self.has_blocking_wheel_event_region_covering_viewport
+ || !self.has_wheel_hit_test_targets_for(visual_context_tree)
+ {
+ return true;
+ }
+ for target in &self.cached_blocking_wheel_event_targets {
+ if !visual_context_tree.context_is_valid(target.context) {
+ return true;
+ }
+ if target.viewport_rect.is_some_and(|rect| !rect.contains_point(position)) {
+ continue;
+ }
+ let position_in_context = visual_context_tree.transform_point_for_hit_test(
+ target.context,
+ position,
+ &self.scroll_state_snapshot,
+ ClipBehavior::Respect,
+ );
+ if position_in_context.is_some_and(|point| target.rect.contains_point(point)) {
+ return true;
+ }
+ }
+ false
+ }
+
+ pub fn main_thread_wheel_event_region_contains(
+ &self,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ ) -> bool {
+ for target in &self.cached_main_thread_wheel_event_targets {
+ if target.viewport_rect.is_some_and(|rect| !rect.contains_point(position)) {
+ continue;
+ }
+ if !visual_context_tree.context_is_valid(target.context) {
+ continue;
+ }
+ let position_in_context = visual_context_tree.transform_point_for_hit_test(
+ target.context,
+ position,
+ &self.scroll_state_snapshot,
+ ClipBehavior::Respect,
+ );
+ if position_in_context.is_some_and(|point| target.rect.contains_point(point)) {
+ return true;
+ }
+ }
+ false
+ }
+
+ fn topmost_nested_context_wheel_region_at(
+ &self,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ ) -> Option<NestedContextWheelRegionHit<'_>> {
+ for cached_region in self.cached_nested_context_wheel_regions.iter().rev() {
+ let region = &cached_region.region;
+ if cached_region
+ .viewport_rect
+ .is_some_and(|rect| !rect.contains_point(position))
+ {
+ continue;
+ }
+ if !visual_context_tree.context_is_valid(region.context) {
+ continue;
+ }
+ let position_in_context = visual_context_tree.transform_point_for_hit_test(
+ region.context,
+ position,
+ &self.scroll_state_snapshot,
+ ClipBehavior::Respect,
+ );
+ if let Some(point) = position_in_context
+ && rounded_rect_contains_point(region.rect, region.corner_radii, point)
+ {
+ return Some(NestedContextWheelRegionHit {
+ region,
+ position_in_context: point,
+ });
+ }
+ }
+ None
+ }
+}
+
+fn nested_context_hit_in_region(
+ region: &NestedContextWheelRegion,
+ position_in_context: FloatPoint,
+) -> NestedContextHit {
+ NestedContextHit {
+ child_context_id: region.child_context_id,
+ position_in_content_box: position_in_context
+ - FloatPoint {
+ x: region.rect.x,
+ y: region.rect.y,
+ },
+ content_box_size: FloatSize {
+ width: region.rect.width,
+ height: region.rect.height,
+ },
+ paint_order_index: region.paint_order_index,
+ }
+}
+
+impl AsyncScrollTree {
+ // The nested context whose content is the topmost thing taking pointer input at the position, if any.
+ pub fn nested_context_at(
+ &self,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ ) -> Option<NestedContextHit> {
+ if self.visual_context_tree_structural_epoch != Some(visual_context_tree.structural_epoch()) {
+ return None;
+ }
+ let hit = self.topmost_nested_context_wheel_region_at(visual_context_tree, position)?;
+ if self.is_covered_by_hit_test_target_painted_after(hit.region.paint_order_index, visual_context_tree, position)
+ {
+ return None;
+ }
+ Some(nested_context_hit_in_region(hit.region, hit.position_in_context))
+ }
+
+ // As above, unless the main thread takes the wheel events at the position.
+ pub fn nested_context_for_wheel_at(
+ &self,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ ) -> Option<NestedContextHit> {
+ if self.visual_context_tree_structural_epoch != Some(visual_context_tree.structural_epoch()) {
+ return None;
+ }
+ if self.main_thread_wheel_event_region_contains(visual_context_tree, position) {
+ return None;
+ }
+ self.nested_context_at(visual_context_tree, position)
+ }
+
+ // Where the position lands in the content of the nested context, even outside of that content and its clips, as
+ // the pointer of a drag that began in there moves on.
+ pub fn position_in_content_of_nested_context(
+ &self,
+ child_context_id: CompositorContextId,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ ) -> Option<NestedContextHit> {
+ if self.visual_context_tree_structural_epoch != Some(visual_context_tree.structural_epoch()) {
+ return None;
+ }
+ for cached_region in self.cached_nested_context_wheel_regions.iter().rev() {
+ let region = &cached_region.region;
+ if region.child_context_id != child_context_id {
+ continue;
+ }
+ if !visual_context_tree.context_is_valid(region.context) {
+ return None;
+ }
+ let position_in_context = visual_context_tree.transform_point_for_hit_test(
+ region.context,
+ position,
+ &self.scroll_state_snapshot,
+ ClipBehavior::Ignore,
+ )?;
+ return Some(nested_context_hit_in_region(region, position_in_context));
+ }
+ None
+ }
+
+ // Where a position in the viewport of the nested context lies in this context's viewport.
+ pub fn position_of_nested_context_position(
+ &self,
+ child_context_id: CompositorContextId,
+ position_in_nested_context: FloatPoint,
+ nested_context_viewport_size: FloatSize,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ ) -> Option<FloatPoint> {
+ if self.visual_context_tree_structural_epoch != Some(visual_context_tree.structural_epoch())
+ || nested_context_viewport_size.is_empty()
+ {
+ return None;
+ }
+ for cached_region in self.cached_nested_context_wheel_regions.iter().rev() {
+ let region = &cached_region.region;
+ if region.child_context_id != child_context_id {
+ continue;
+ }
+ if !visual_context_tree.context_is_valid(region.context) {
+ return None;
+ }
+ // The content box of a nested context is drawn scaled to the size of its viewport.
+ let position_in_content_box = FloatPoint {
+ x: position_in_nested_context.x * region.rect.width / nested_context_viewport_size.width,
+ y: position_in_nested_context.y * region.rect.height / nested_context_viewport_size.height,
+ };
+ let location = FloatPoint {
+ x: region.rect.x,
+ y: region.rect.y,
+ } + position_in_content_box;
+ let point_in_context = FloatRect::new(location.x, location.y, 0.0, 0.0);
+ let result = visual_context_tree.transform_rect_to_viewport(
+ region.context.spatial,
+ point_in_context,
+ &self.scroll_state_snapshot,
+ IncludeVisualViewportTransform::Yes,
+ );
+ return Some(FloatPoint {
+ x: result.x,
+ y: result.y,
+ });
+ }
+ None
+ }
+
+ pub fn hit_test_scroll_node_for_wheel(
+ &self,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ delta: FloatPoint,
+ in_flight_destination_for: &dyn Fn(AsyncScrollNodeStableID) -> Option<FloatPoint>,
+ wheel_step_dispatch: WheelStepDispatch,
+ nested_context_regions: NestedContextRegions,
+ ) -> WheelHitTestResult {
+ if self.visual_context_tree_structural_epoch != Some(visual_context_tree.structural_epoch()) {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::HitTestTargetsOfAnotherVisualContextTree,
+ ..Default::default()
+ };
+ }
+ let context_is_valid = |context| visual_context_tree.context_is_valid(context);
+ // Neither the listeners nor the main thread have anything left to say about a step the page let through.
+ let page_has_yet_to_see_the_step = wheel_step_dispatch == WheelStepDispatch::NotYetDispatched;
+ if page_has_yet_to_see_the_step && self.has_blocking_wheel_event_region_covering_viewport {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::BlockedByWheelEventRegion,
+ ..Default::default()
+ };
+ }
+ if page_has_yet_to_see_the_step && self.main_thread_wheel_event_region_contains(visual_context_tree, position) {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::BlockedByMainThreadRegion,
+ ..Default::default()
+ };
+ }
+ if nested_context_regions == NestedContextRegions::LeaveToMainThread
+ && self
+ .topmost_nested_context_wheel_region_at(visual_context_tree, position)
+ .is_some()
+ {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::BlockedByMainThreadRegion,
+ ..Default::default()
+ };
+ }
+ if page_has_yet_to_see_the_step && self.blocks_wheel_event_at_position(visual_context_tree, position) {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::BlockedByWheelEventRegion,
+ ..Default::default()
+ };
+ }
+ for target in self.cached_wheel_hit_test_targets.iter().rev() {
+ if target.viewport_rect.is_some_and(|rect| !rect.contains_point(position)) {
+ continue;
+ }
+ if !context_is_valid(target.context) {
+ continue;
+ }
+ let position_in_context = visual_context_tree.transform_point_for_hit_test(
+ target.context,
+ position,
+ &self.scroll_state_snapshot,
+ ClipBehavior::Respect,
+ );
+ if !position_in_context.is_some_and(|point| wheel_hit_test_target_contains_point(target, point)) {
+ continue;
+ }
+ let Some(index) = target.target_scroll_node_index else {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::NoScrollTarget,
+ ..Default::default()
+ };
+ };
+ return self.hit_test_result_for_scroll_node(index, delta, in_flight_destination_for);
+ }
+ let Some(index_of_viewport_scroll_node) = self.viewport_scroll_node_index() else {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::NoScrollTarget,
+ ..Default::default()
+ };
+ };
+ let viewport_node = self.scroll_node_for_index(index_of_viewport_scroll_node);
+ if !viewport_node.is_some_and(|node| node.scrollport_rect.to_float().contains_point(position)) {
+ return WheelHitTestResult {
+ outcome: WheelHitTestOutcome::NoScrollTarget,
+ ..Default::default()
+ };
+ }
+ self.hit_test_result_for_scroll_node(index_of_viewport_scroll_node, delta, in_flight_destination_for)
+ }
+
+ // Leaves out what only a compositor holding a gesture decides: whether a step continues a latched gesture, which
+ // scroller fingers at its edge stretch, and whether a zoomed page pans its visual viewport.
+ pub fn route_first_wheel_step(
+ &self,
+ admission: WheelRoutingAdmission,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ delta: FloatPoint,
+ nested_context_regions: NestedContextRegions,
+ ) -> FirstWheelStepRoute {
+ if admission != WheelRoutingAdmission::Accepted {
+ return FirstWheelStepRoute {
+ decision: input_routing_decision_for_wheel_step_not_admitted_by(admission),
+ scroller: None,
+ };
+ }
+ let scroll_target = self.hit_test_scroll_node_for_wheel(
+ visual_context_tree,
+ position,
+ delta,
+ &|_| None,
+ WheelStepDispatch::NotYetDispatched,
+ nested_context_regions,
+ );
+ let mut route = FirstWheelStepRoute {
+ decision: input_routing_decision_for_first_wheel_step(scroll_target.outcome),
+ scroller: None,
+ };
+ if let Some(index) = scroll_target.scroll_node_index
+ && let Some(node) = self.scroll_node_for_index(index)
+ {
+ route.scroller = Some(node.stable_node_id);
+ }
+ route
+ }
+
+ // Whether something painted above the given place in paint order takes pointer input at the position. It is taken
+ // to be covered whenever that cannot be told.
+ pub fn is_covered_by_hit_test_target_painted_after(
+ &self,
+ paint_order_index: u32,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ position: FloatPoint,
+ ) -> bool {
+ if self.visual_context_tree_structural_epoch != Some(visual_context_tree.structural_epoch()) {
+ return true;
+ }
+ for target in self.cached_wheel_hit_test_targets.iter().rev() {
+ if target.paint_order_index < paint_order_index {
+ break;
+ }
+ if target.viewport_rect.is_some_and(|rect| !rect.contains_point(position)) {
+ continue;
+ }
+ if !visual_context_tree.context_is_valid(target.context) {
+ continue;
+ }
+ let position_in_context = visual_context_tree.transform_point_for_hit_test(
+ target.context,
+ position,
+ &self.scroll_state_snapshot,
+ ClipBehavior::Respect,
+ );
+ if position_in_context.is_some_and(|point| wheel_hit_test_target_contains_point(target, point)) {
+ return true;
+ }
+ }
+ false
+ }
+
+ pub fn scroll_node_for_keyboard_scroll(
+ &self,
+ stable_node_id: AsyncScrollNodeStableID,
+ delta: FloatPoint,
+ scroll_state_snapshot: &ScrollStateSnapshot,
+ ) -> Option<SpatialNodeIndex> {
+ let node = self.scroll_node_for_stable_id(stable_node_id)?;
+ // Keyboard routing does not depend on pointer or wheel-listener regions.
+ if Self::can_scroll_node_by_delta(node, scroll_state_snapshot, delta) {
+ return Some(node.scroll_node_index);
+ }
+ self.scrollable_ancestor_for_node(node.scroll_node_index, scroll_state_snapshot, delta)
+ }
+
+ pub fn clamped_scroll_offset_for_node(
+ &self,
+ scroll_node_index: SpatialNodeIndex,
+ scroll_offset: FloatPoint,
+ ) -> FloatPoint {
+ let Some(node) = self.scroll_node_for_index(scroll_node_index) else {
+ return scroll_offset;
+ };
+ Self::clamp_scroll_offset_to_node(node, scroll_offset)
+ }
+
+ pub fn scroll_node_is_viewport(&self, scroll_node_index: SpatialNodeIndex) -> bool {
+ self.scroll_node_for_index(scroll_node_index)
+ .is_some_and(|node| node.is_viewport)
+ }
+
+ // Whether the viewport keeps a scroll by the delta from the document it is nested in, whether or not it has a
+ // scroll node.
+ pub fn viewport_keeps_scrolls_along_main_axis_of(&self, delta: FloatPoint) -> bool {
+ if delta_is_mainly_vertical(delta) {
+ self.viewport_keeps_vertical_scrolls
+ } else {
+ self.viewport_keeps_horizontal_scrolls
+ }
+ }
+
+ pub fn set_scroll_offset(
+ &mut self,
+ scroll_node_index: SpatialNodeIndex,
+ scroll_offset: FloatPoint,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ scroll_state_snapshot: &mut ScrollStateSnapshot,
+ ) -> Option<FloatPoint> {
+ let node = self.scroll_node_for_index(scroll_node_index)?;
+ let new_scroll_offset =
+ self.set_scroll_offset_leaving_sticky_offsets_unresolved(node, scroll_offset, scroll_state_snapshot);
+ resolve_sticky_offsets(visual_context_tree, scroll_state_snapshot);
+ Some(new_scroll_offset)
+ }
+
+ pub fn set_scroll_offset_leaving_sticky_offsets_unresolved(
+ &self,
+ node: &AsyncScrollNode,
+ scroll_offset: FloatPoint,
+ scroll_state_snapshot: &mut ScrollStateSnapshot,
+ ) -> FloatPoint {
+ let new_scroll_offset = Self::clamp_scroll_offset_to_node(node, scroll_offset);
+ scroll_state_snapshot.set_device_offset_for_index(
+ node.scroll_node_index,
+ FloatPoint {
+ x: -new_scroll_offset.x,
+ y: -new_scroll_offset.y,
+ },
+ );
+ new_scroll_offset
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/async_scrolling_state.rs b/Libraries/LibCompositing/Rust/src/scrolling/async_scrolling_state.rs
new file mode 100644
index 00000000000..b5f51482437
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/async_scrolling_state.rs
@@ -0,0 +1,522 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The scrolling state a display list carries for the compositor: scroll nodes, snap containers, wheel regions and
+//! scrollbars.
+
+use super::scroll_snap_selection::{SnapAlign, SnapAreaGeometry, SnapAxes, SnapContainerGeometry, SnapStrictness};
+use super::{
+ AsyncScrollNodeKind, AsyncScrollNodeStableID, AsyncScrollOffset, CompositorContextId, CompositorScrollNodeKind,
+ ContextRef, DisplayList, InputRoutingDecision, SnapAreaIdentity, SpatialNodeIndex, UniqueNodeId,
+};
+use crate::css_pixels::{CssPixelPoint, CssPixelRect};
+use crate::display_list::builder::read_command;
+use crate::display_list::commands::*;
+use libgfx_rust::{Color, CornerRadii, FloatPoint, FloatRect, IntRect};
+use std::io::Write;
+
+pub type AsyncScrollOperationID = u64;
+
+impl AsyncScrollOffset {
+ pub fn merge_later_scroll(&mut self, later: &Self) {
+ self.compositor_scroll_offset = later.compositor_scroll_offset;
+ // The last of the main thread's scroll requests for the box that the compositor applied before it reported this.
+ self.applied_scroll_request_id = later.applied_scroll_request_id;
+ // How many times the compositor had scrolled the box for user input of its own when it reported this.
+ self.user_input_scroll_count = later.user_input_scroll_count;
+ // How many times the compositor had scrolled any box of the context for user input of its own when it reported
+ // this. Not every such scroll is reported, as one the next input turns back moves no box.
+ self.context_user_input_scroll_count = later.context_user_input_scroll_count;
+ // The scale the visual viewport was zoomed to, which only its scroll node reports.
+ if later.visual_viewport_scale.is_some() {
+ self.visual_viewport_scale = later.visual_viewport_scale;
+ }
+ self.unadopted_scroll_delta.translate_by(later.unadopted_scroll_delta);
+ // The most recent nonzero delta of a relative scroll in each axis, such as a wheel or panning scroll. Absolute
+ // scrolls, such as dragging a scrollbar thumb, leave it as it is.
+ if later.last_relative_scroll_delta.x != 0.0 {
+ self.last_relative_scroll_delta.x = later.last_relative_scroll_delta.x;
+ }
+ if later.last_relative_scroll_delta.y != 0.0 {
+ self.last_relative_scroll_delta.y = later.last_relative_scroll_delta.y;
+ }
+ }
+}
+
+// One scrollable area from the paint snapshot, or a scroll container with nothing to scroll that keeps its scrolls.
+#[derive(Clone, Copy)]
+pub struct AsyncScrollNode {
+ pub scroll_node_index: SpatialNodeIndex,
+ pub stable_node_id: AsyncScrollNodeStableID,
+ pub parent_scroll_node_index: Option<SpatialNodeIndex>,
+ pub scrollport_rect: IntRect,
+ pub min_scroll_offset: FloatPoint,
+ pub max_scroll_offset: FloatPoint,
+ pub is_viewport: bool,
+ pub can_be_wheel_scrolled_horizontally: bool,
+ pub can_be_wheel_scrolled_vertically: bool,
+ // Whether a scroll the scroller cannot scroll by is passed on to the scrollers around it.
+ pub chains_scroll_to_ancestors_horizontally: bool,
+ pub chains_scroll_to_ancestors_vertically: bool,
+ // Whether a touchpad may pull the scroller past the edges of its scroll range.
+ pub shows_overscroll_effect_horizontally: bool,
+ pub shows_overscroll_effect_vertically: bool,
+}
+
+// A region with a non-passive wheel listener. Wheels inside it must stay on the main thread because script may cancel.
+#[derive(Clone, Copy, Default)]
+pub struct BlockingWheelEventRegion {
+ pub context: ContextRef,
+ pub rect: FloatRect,
+}
+
+#[derive(Clone, Copy, Default)]
+pub struct WheelHitTestTarget {
+ pub context: ContextRef,
+ pub rect: FloatRect,
+ pub corner_radii: CornerRadii,
+ pub target_scroll_node_index: Option<SpatialNodeIndex>,
+ // Position among the wheel hit test targets and scrollbars of the display list, which are recorded in paint order.
+ pub paint_order_index: u32,
+}
+
+// A region that must always use main-thread wheel routing even without a blocking listener, such as a nested navigable.
+#[derive(Clone, Copy, Default)]
+pub struct MainThreadWheelEventRegion {
+ pub context: ContextRef,
+ pub rect: FloatRect,
+}
+
+// Where a nested context's content is painted. A wheel inside it that no wheel hit test target painted later covers
+// can be handed to the nested context.
+#[derive(Clone, Copy, Default)]
+pub struct NestedContextWheelRegion {
+ pub context: ContextRef,
+ pub rect: FloatRect,
+ pub corner_radii: CornerRadii,
+ pub child_context_id: CompositorContextId,
+ pub paint_order_index: u32,
+}
+
+#[derive(Clone, Copy, Default)]
+pub struct AsyncScrollbar {
+ pub scroller_stable_node_id: Option<AsyncScrollNodeStableID>,
+ pub scroll_node_index: SpatialNodeIndex,
+ // The rects of a scrollbar the display list paints are in the space of this context.
+ pub context: ContextRef,
+ pub paint_order_index: u32,
+ pub gutter_rect: IntRect,
+ pub thumb_rect: IntRect,
+ pub track_rect: IntRect,
+ pub expanded_gutter_rect: IntRect,
+ pub expanded_thumb_rect: IntRect,
+ pub scroll_size: f64,
+ pub expanded_scroll_size: f64,
+ pub min_scroll_offset: f32,
+ pub max_scroll_offset: f32,
+ pub thumb_color: Color,
+ pub thumb_outline_color: Color,
+ pub track_color: Color,
+ pub vertical: bool,
+ // The compositor paints the viewport's scrollbars itself. The display list paints every other scrollbar thin, which
+ // the compositor presents growing as it is hovered, as it does its own.
+ pub is_painted_by_compositor: bool,
+}
+
+// A scroll node that is a snap container, with the geometry snap positions are selected from.
+pub struct AsyncSnapContainer {
+ pub scroll_node_index: SpatialNodeIndex,
+ pub geometry: SnapContainerGeometry,
+ pub areas: Vec<SnapAreaGeometry>,
+}
+
+pub struct AsyncScrollingState {
+ pub document_id: Option<UniqueNodeId>,
+ pub scroll_nodes: Vec<AsyncScrollNode>,
+ pub snap_containers: Vec<AsyncSnapContainer>,
+ pub wheel_hit_test_targets: Vec<WheelHitTestTarget>,
+ pub main_thread_wheel_event_regions: Vec<MainThreadWheelEventRegion>,
+ pub nested_context_wheel_regions: Vec<NestedContextWheelRegion>,
+ pub scrollbars: Vec<AsyncScrollbar>,
+
+ // Non-passive wheel listeners can cancel scrolling, so async scrolling must treat them as hard barriers.
+ // Viewport-wide barriers cover listeners on the root targets; element regions let input hit-testing accept
+ // async scrolling elsewhere.
+ pub blocking_wheel_event_regions: Vec<BlockingWheelEventRegion>,
+ pub viewport_rect: IntRect,
+
+ // Bumped whenever wheel listener state changes so queued compositor snapshots
+ // cannot re-enable async wheel routing after a non-passive listener has been
+ // added.
+ pub wheel_event_listener_state_generation: u64,
+ pub has_blocking_wheel_event_listeners: bool,
+ pub has_blocking_wheel_event_region_covering_viewport: bool,
+ pub viewport_keeps_horizontal_scrolls: bool,
+ pub viewport_keeps_vertical_scrolls: bool,
+ pub device_pixels_per_css_pixel: f64,
+}
+
+impl Default for AsyncScrollingState {
+ fn default() -> Self {
+ Self {
+ document_id: Default::default(),
+ scroll_nodes: Default::default(),
+ snap_containers: Default::default(),
+ wheel_hit_test_targets: Default::default(),
+ main_thread_wheel_event_regions: Default::default(),
+ nested_context_wheel_regions: Default::default(),
+ scrollbars: Default::default(),
+ blocking_wheel_event_regions: Default::default(),
+ viewport_rect: Default::default(),
+ wheel_event_listener_state_generation: Default::default(),
+ has_blocking_wheel_event_listeners: false,
+ has_blocking_wheel_event_region_covering_viewport: false,
+ viewport_keeps_horizontal_scrolls: false,
+ viewport_keeps_vertical_scrolls: false,
+ device_pixels_per_css_pixel: 1.0,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum WheelRoutingAdmission {
+ Accepted,
+ NoAsyncScrollingState,
+ BlockingWheelEventListeners,
+ NoScrollNode,
+ StaleWheelEventListeners,
+}
+
+pub fn async_scroll_node_kind_for(kind: CompositorScrollNodeKind) -> AsyncScrollNodeKind {
+ match kind {
+ CompositorScrollNodeKind::Viewport => AsyncScrollNodeKind::Viewport,
+ CompositorScrollNodeKind::Element => AsyncScrollNodeKind::Element,
+ CompositorScrollNodeKind::PseudoElement => AsyncScrollNodeKind::PseudoElement,
+ }
+}
+
+fn stable_scroll_node_id_for(
+ scrollable_node_id: UniqueNodeId,
+ kind: CompositorScrollNodeKind,
+ pseudo_element_type: u8,
+) -> AsyncScrollNodeStableID {
+ AsyncScrollNodeStableID {
+ node_id: scrollable_node_id,
+ kind: async_scroll_node_kind_for(kind),
+ pseudo_element_type,
+ }
+}
+
+pub fn async_scrolling_state_from_display_list(display_list: &DisplayList) -> AsyncScrollingState {
+ let mut async_scrolling_state = AsyncScrollingState::default();
+ let mut next_paint_order_index = 0u32;
+ if let Some(metadata) = display_list.async_scrolling_metadata() {
+ async_scrolling_state.document_id = metadata.document_id;
+ async_scrolling_state.viewport_rect = metadata.viewport_rect;
+ async_scrolling_state.wheel_event_listener_state_generation = metadata.wheel_event_listener_state_generation;
+ async_scrolling_state.has_blocking_wheel_event_listeners = metadata.has_blocking_wheel_event_listeners;
+ async_scrolling_state.has_blocking_wheel_event_region_covering_viewport =
+ metadata.has_blocking_wheel_event_region_covering_viewport;
+ async_scrolling_state.viewport_keeps_horizontal_scrolls = metadata.viewport_keeps_horizontal_scrolls;
+ async_scrolling_state.viewport_keeps_vertical_scrolls = metadata.viewport_keeps_vertical_scrolls;
+ async_scrolling_state.device_pixels_per_css_pixel = metadata.device_pixels_per_css_pixel;
+ }
+ display_list.for_each_compositor_metadata(|context, command_type, payload| {
+ let mut append_wheel_hit_test_target = |target_scroll_node_index: SpatialNodeIndex, rect, corner_radii| {
+ let target_scroll_node_index = if target_scroll_node_index.0 != 0 {
+ Some(target_scroll_node_index)
+ } else {
+ None
+ };
+ async_scrolling_state.wheel_hit_test_targets.push(WheelHitTestTarget {
+ context,
+ rect,
+ corner_radii,
+ target_scroll_node_index,
+ paint_order_index: next_paint_order_index,
+ });
+ next_paint_order_index = next_paint_order_index.wrapping_add(1);
+ };
+ match command_type {
+ DisplayListCommandType::CompositorBlockingWheelEventRegion => {
+ let command = read_command::<CompositorBlockingWheelEventRegion>(payload);
+ async_scrolling_state.has_blocking_wheel_event_listeners = true;
+ async_scrolling_state
+ .blocking_wheel_event_regions
+ .push(BlockingWheelEventRegion {
+ context,
+ rect: command.rect,
+ });
+ }
+ DisplayListCommandType::CompositorScrollNode => {
+ let command = read_command::<CompositorScrollNode>(payload);
+ let parent_scroll_node_index = if command.parent_scroll_node_index.0 != 0 {
+ Some(command.parent_scroll_node_index)
+ } else {
+ None
+ };
+ async_scrolling_state.scroll_nodes.push(AsyncScrollNode {
+ scroll_node_index: command.scroll_node_index,
+ stable_node_id: stable_scroll_node_id_for(
+ command.scrollable_node_id,
+ command.scroll_node_kind,
+ command.pseudo_element_type,
+ ),
+ parent_scroll_node_index,
+ scrollport_rect: command.scrollport_rect,
+ min_scroll_offset: command.min_scroll_offset,
+ max_scroll_offset: command.max_scroll_offset,
+ is_viewport: command.is_viewport,
+ can_be_wheel_scrolled_horizontally: command.can_be_wheel_scrolled_horizontally,
+ can_be_wheel_scrolled_vertically: command.can_be_wheel_scrolled_vertically,
+ chains_scroll_to_ancestors_horizontally: command.chains_scroll_to_ancestors_horizontally,
+ chains_scroll_to_ancestors_vertically: command.chains_scroll_to_ancestors_vertically,
+ shows_overscroll_effect_horizontally: command.shows_overscroll_effect_horizontally,
+ shows_overscroll_effect_vertically: command.shows_overscroll_effect_vertically,
+ });
+ }
+ DisplayListCommandType::CompositorWheelHitTestTarget => {
+ let command = read_command::<CompositorWheelHitTestTarget>(payload);
+ append_wheel_hit_test_target(command.target_scroll_node_index, command.rect, CornerRadii::default());
+ }
+ DisplayListCommandType::CompositorWheelHitTestTargetWithCornerRadii => {
+ let command = read_command::<CompositorWheelHitTestTargetWithCornerRadii>(payload);
+ append_wheel_hit_test_target(command.target_scroll_node_index, command.rect, command.corner_radii);
+ }
+ DisplayListCommandType::CompositorMainThreadWheelEventRegion => {
+ let command = read_command::<CompositorMainThreadWheelEventRegion>(payload);
+ async_scrolling_state
+ .main_thread_wheel_event_regions
+ .push(MainThreadWheelEventRegion {
+ context,
+ rect: command.rect,
+ });
+ }
+ DisplayListCommandType::CompositorNestedContextWheelRegion => {
+ let command = read_command::<CompositorNestedContextWheelRegion>(payload);
+ async_scrolling_state
+ .nested_context_wheel_regions
+ .push(NestedContextWheelRegion {
+ context,
+ rect: command.rect,
+ corner_radii: command.corner_radii,
+ child_context_id: command.child_context_id,
+ paint_order_index: next_paint_order_index,
+ });
+ next_paint_order_index = next_paint_order_index.wrapping_add(1);
+ }
+ DisplayListCommandType::CompositorScrollbar => {
+ let command = read_command::<CompositorScrollbar>(payload);
+ async_scrolling_state.scrollbars.push(AsyncScrollbar {
+ scroller_stable_node_id: None,
+ scroll_node_index: command.scroll_node_index,
+ context,
+ paint_order_index: next_paint_order_index,
+ gutter_rect: command.gutter_rect,
+ thumb_rect: command.thumb_rect,
+ track_rect: command.track_rect,
+ expanded_gutter_rect: command.expanded_gutter_rect,
+ expanded_thumb_rect: command.expanded_thumb_rect,
+ scroll_size: command.scroll_size,
+ expanded_scroll_size: command.expanded_scroll_size,
+ min_scroll_offset: command.min_scroll_offset,
+ max_scroll_offset: command.max_scroll_offset,
+ thumb_color: command.thumb_color,
+ thumb_outline_color: command.thumb_outline_color,
+ track_color: command.track_color,
+ vertical: command.vertical,
+ is_painted_by_compositor: command.is_painted_by_compositor,
+ });
+ next_paint_order_index = next_paint_order_index.wrapping_add(1);
+ }
+ DisplayListCommandType::CompositorSnapContainer => {
+ let command = read_command::<CompositorSnapContainer>(payload);
+ let strictness = match command.strictness {
+ 0 => SnapStrictness::None,
+ 1 => SnapStrictness::Proximity,
+ 2 => SnapStrictness::Mandatory,
+ _ => return,
+ };
+ async_scrolling_state.snap_containers.push(AsyncSnapContainer {
+ scroll_node_index: command.scroll_node_index,
+ geometry: SnapContainerGeometry {
+ snapport: command.snapport.into(),
+ min_scroll_offset: command.min_scroll_offset.into(),
+ max_scroll_offset: command.max_scroll_offset.into(),
+ strictness,
+ axes: SnapAxes {
+ x: command.snaps_x,
+ y: command.snaps_y,
+ },
+ horizontal_writing_mode: command.horizontal_writing_mode,
+ },
+ areas: Vec::new(),
+ });
+ }
+ DisplayListCommandType::CompositorSnapArea => {
+ let command = read_command::<CompositorSnapArea>(payload);
+ let snap_containers = &mut async_scrolling_state.snap_containers;
+ // A snap container's areas are recorded right after it.
+ let Some(container) = snap_containers
+ .last_mut()
+ .filter(|c| c.scroll_node_index == command.scroll_node_index)
+ else {
+ let _ = writeln!(
+ std::io::stderr(),
+ "Ignoring a snap area recorded without its snap container"
+ );
+ return;
+ };
+ let align = |value| match value {
+ 0 => Some(SnapAlign::None),
+ 1 => Some(SnapAlign::Start),
+ 2 => Some(SnapAlign::End),
+ 3 => Some(SnapAlign::Center),
+ _ => None,
+ };
+ let (Some(align_x), Some(align_y)) = (align(command.align_x), align(command.align_y)) else {
+ return;
+ };
+ container.areas.push(SnapAreaGeometry {
+ identity: SnapAreaIdentity {
+ node_id: command.area_node_id,
+ pseudo_element_type: command.pseudo_element_type,
+ },
+ rect: command.rect.into(),
+ align_x,
+ align_y,
+ always_stop: command.always_stop,
+ });
+ }
+ _ => {}
+ }
+ });
+ for scrollbar in &mut async_scrolling_state.scrollbars {
+ for scroll_node in &async_scrolling_state.scroll_nodes {
+ if scroll_node.scroll_node_index == scrollbar.scroll_node_index {
+ scrollbar.scroller_stable_node_id = Some(scroll_node.stable_node_id);
+ break;
+ }
+ }
+ }
+ async_scrolling_state
+}
+
+fn snap_strictness_name(strictness: SnapStrictness) -> &'static str {
+ match strictness {
+ SnapStrictness::None => "none",
+ SnapStrictness::Proximity => "proximity",
+ SnapStrictness::Mandatory => "mandatory",
+ }
+}
+
+fn snap_align_name(align: SnapAlign) -> &'static str {
+ match align {
+ SnapAlign::None => "none",
+ SnapAlign::Start => "start",
+ SnapAlign::End => "end",
+ SnapAlign::Center => "center",
+ }
+}
+
+fn rect_to_json(rect: CssPixelRect) -> String {
+ format!(
+ r#"{{"x":{},"y":{},"width":{},"height":{}}}"#,
+ rect.x.to_double(),
+ rect.y.to_double(),
+ rect.width.to_double(),
+ rect.height.to_double()
+ )
+}
+
+fn point_to_json(point: CssPixelPoint) -> String {
+ format!(r#"{{"x":{},"y":{}}}"#, point.x.to_double(), point.y.to_double())
+}
+
+pub fn async_scrolling_state_to_json(state: &AsyncScrollingState) -> String {
+ let mut scroll_nodes = Vec::new();
+ for scroll_node in &state.scroll_nodes {
+ scroll_nodes.push(format!(
+ r#"{{"scrollNodeIndex":{},"parentScrollNodeIndex":{},"isViewport":{}}}"#,
+ scroll_node.scroll_node_index.0,
+ scroll_node.parent_scroll_node_index.map_or(0, |index| index.0),
+ scroll_node.is_viewport
+ ));
+ }
+ let mut snap_containers = Vec::new();
+ for snap_container in &state.snap_containers {
+ let mut areas = Vec::new();
+ for snap_area in &snap_container.areas {
+ areas.push(format!(
+ r#"{{"nodeID":{},"pseudoElementType":{},"rect":{},"alignX":"{}","alignY":"{}","alwaysStop":{}}}"#,
+ snap_area.identity.node_id.0,
+ snap_area.identity.pseudo_element_type,
+ rect_to_json(snap_area.rect),
+ snap_align_name(snap_area.align_x),
+ snap_align_name(snap_area.align_y),
+ snap_area.always_stop
+ ));
+ }
+ snap_containers.push(format!(r#"{{"scrollNodeIndex":{},"snapport":{},"minScrollOffset":{},"maxScrollOffset":{},"strictness":"{}","snapsX":{},"snapsY":{},"horizontalWritingMode":{},"areas":[{}]}}"#,
+ snap_container.scroll_node_index.0, rect_to_json(snap_container.geometry.snapport), point_to_json(snap_container.geometry.min_scroll_offset),
+ point_to_json(snap_container.geometry.max_scroll_offset), snap_strictness_name(snap_container.geometry.strictness), snap_container.geometry.axes.x,
+ snap_container.geometry.axes.y, snap_container.geometry.horizontal_writing_mode, areas.join(",")));
+ }
+ format!(
+ r#"{{"documentID":{},"scrollNodeCount":{},"scrollNodes":[{}],"snapContainers":[{}],"devicePixelsPerCssPixel":{},"hasBlockingWheelEventListeners":{},"blockingWheelEventRegionCount":{},"mainThreadWheelEventRegionCount":{},"nestedContextWheelRegionCount":{},"wheelEventListenerStateGeneration":{},"hasBlockingWheelEventRegionCoveringViewport":{}}}"#,
+ state
+ .document_id
+ .map_or_else(|| "null".to_owned(), |id| id.0.to_string()),
+ state.scroll_nodes.len(),
+ scroll_nodes.join(","),
+ snap_containers.join(","),
+ if state.device_pixels_per_css_pixel.is_finite() {
+ state.device_pixels_per_css_pixel.to_string()
+ } else {
+ "null".to_owned()
+ },
+ state.has_blocking_wheel_event_listeners,
+ state.blocking_wheel_event_regions.len(),
+ state.main_thread_wheel_event_regions.len(),
+ state.nested_context_wheel_regions.len(),
+ state.wheel_event_listener_state_generation,
+ state.has_blocking_wheel_event_region_covering_viewport
+ )
+}
+
+pub fn wheel_routing_admission_for(state: &AsyncScrollingState) -> WheelRoutingAdmission {
+ if state.has_blocking_wheel_event_region_covering_viewport {
+ return WheelRoutingAdmission::BlockingWheelEventListeners;
+ }
+ if state.scroll_nodes.is_empty() {
+ return WheelRoutingAdmission::NoScrollNode;
+ }
+ WheelRoutingAdmission::Accepted
+}
+
+// Why a wheel step that the admission does not let the compositor scroll before the page dispatches it is left to the
+// page.
+pub fn input_routing_decision_for_wheel_step_not_admitted_by(admission: WheelRoutingAdmission) -> InputRoutingDecision {
+ match admission {
+ WheelRoutingAdmission::Accepted => unreachable!(),
+ WheelRoutingAdmission::NoAsyncScrollingState => InputRoutingDecision::NoAsyncScrollingState,
+ WheelRoutingAdmission::BlockingWheelEventListeners => InputRoutingDecision::BlockingWheelEventListeners,
+ WheelRoutingAdmission::NoScrollNode => InputRoutingDecision::NoScrollNode,
+ WheelRoutingAdmission::StaleWheelEventListeners => InputRoutingDecision::StaleWheelEventListeners,
+ }
+}
+
+// The admission of a scrolling state recorded before the newest change to the page's blocking wheel event listeners is
+// stale, as the state may not have the regions that change made.
+pub fn wheel_routing_admission_for_with_generation(
+ state: &AsyncScrollingState,
+ newest_wheel_event_listener_state_generation: u64,
+) -> WheelRoutingAdmission {
+ if state.wheel_event_listener_state_generation < newest_wheel_event_listener_state_generation {
+ return WheelRoutingAdmission::StaleWheelEventListeners;
+ }
+ wheel_routing_admission_for(state)
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs b/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs
new file mode 100644
index 00000000000..002de60637b
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Everything about a list that travels alongside its tape when it is sent to the Compositor.
+
+use super::ContextRef;
+use crate::display_list::builder::read_command;
+use crate::display_list::commands::{DisplayListCommandType, PaintCaret};
+use crate::display_list::storage::DisplayListStorage;
+use crate::display_list::summary::{for_each_compositor_metadata, for_each_indexed_record};
+use libgfx_rust::IntRect;
+use std::sync::Arc;
+
+pub use crate::ipc_types::Compositing_DisplayList_AsyncScrollingMetadata as AsyncScrollingMetadata;
+
+pub struct DisplayList {
+ // One strong reference to the Rust storage, which owns the tape.
+ pub(crate) storage: Arc<DisplayListStorage>,
+ id: u64,
+ compatible_visual_context_tree_structural_epoch: u64,
+ async_scrolling_metadata: Option<AsyncScrollingMetadata>,
+}
+
+impl DisplayList {
+ pub fn new(
+ storage: Arc<DisplayListStorage>,
+ id: u64,
+ compatible_visual_context_tree_structural_epoch: u64,
+ async_scrolling_metadata: Option<AsyncScrollingMetadata>,
+ ) -> Self {
+ Self {
+ storage,
+ id,
+ compatible_visual_context_tree_structural_epoch,
+ async_scrolling_metadata,
+ }
+ }
+
+ pub fn compatible_visual_context_tree_structural_epoch(&self) -> u64 {
+ self.compatible_visual_context_tree_structural_epoch
+ }
+
+ pub fn id(&self) -> u64 {
+ self.id
+ }
+
+ pub fn async_scrolling_metadata(&self) -> Option<&AsyncScrollingMetadata> {
+ self.async_scrolling_metadata.as_ref()
+ }
+
+ // Visits the compositor metadata commands with the context of their run and their payload, in tape order.
+ pub fn for_each_compositor_metadata(&self, visit: impl FnMut(ContextRef, DisplayListCommandType, &[u8])) {
+ for_each_compositor_metadata(self.storage.bytes(), self.storage.command_runs(), visit);
+ }
+
+ // Visits the carets the list draws outside of any group, with the context of their run and their bounding rect.
+ pub fn for_each_caret(&self, mut visit: impl FnMut(ContextRef, IntRect, &PaintCaret)) {
+ for_each_indexed_record(
+ self.storage.bytes(),
+ self.storage.command_runs(),
+ &self.storage.summary().carets,
+ |context, header, payload| {
+ let command = read_command::<PaintCaret>(payload);
+ visit(context, header.bounding_rect, &command);
+ },
+ );
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/mod.rs b/Libraries/LibCompositing/Rust/src/scrolling/mod.rs
index db40737bd2e..6dc11a0ca89 100644
--- a/Libraries/LibCompositing/Rust/src/scrolling/mod.rs
+++ b/Libraries/LibCompositing/Rust/src/scrolling/mod.rs
@@ -4,20 +4,42 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+pub mod async_scroll_tree;
+pub mod async_scrolling_state;
+pub mod display_list;
pub mod elastic_overscroll;
pub mod overlay_fade;
pub mod scroll_fling;
pub mod scroll_snap_selection;
+pub mod scroll_state_snapshot;
pub mod smooth_scroll_animation;
+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_AsyncScrollOffset as AsyncScrollOffset;
+pub use crate::ipc_types::Compositing_KeyboardScrollState as KeyboardScrollState;
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_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_InputRoutingDecision as InputRoutingDecision;
pub use crate::ipc_types::Web_ScrollGesturePhase as ScrollGesturePhase;
+pub use crate::ipc_types::Web_UniqueNodeID as UniqueNodeId;
+pub use async_scroll_tree::*;
+pub use async_scrolling_state::*;
+pub use display_list::{AsyncScrollingMetadata, DisplayList};
pub use libgfx_rust::Orientation;
+pub use scroll_state_snapshot::{ScrollStateSnapshot, WorldTransformsCache};
+pub use visual_context_tree::{
+ AccumulatedVisualContextTree, AnimatedContentViewportEffect, ClipBehavior, IncludeVisualViewportTransform,
+ TransformWithOrigin, animated_content_may_affect_viewport, resolve_sticky_offsets,
+};
pub const USER_SCROLL_SETTLE_DELAY: crate::time::Duration = crate::time::Duration::from_milliseconds(500);
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/scroll_fling.rs b/Libraries/LibCompositing/Rust/src/scrolling/scroll_fling.rs
index 6760c78277b..cf0138d2912 100644
--- a/Libraries/LibCompositing/Rust/src/scrolling/scroll_fling.rs
+++ b/Libraries/LibCompositing/Rust/src/scrolling/scroll_fling.rs
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Calculates the velocity of a touchpad scroll gesture when the fingers lift.
+//! The momentum of a touchpad flick: its velocity as the fingers lift, and how it decays.
// Velocities are in wheel delta units per second. Displacements are in wheel delta units.
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/scroll_state_snapshot.rs b/Libraries/LibCompositing/Rust/src/scrolling/scroll_state_snapshot.rs
new file mode 100644
index 00000000000..58400ee5a04
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/scroll_state_snapshot.rs
@@ -0,0 +1,190 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Device-pixel offsets keyed by SpatialNodeIndex: the scroll containers' offsets as produced by the document, plus the sticky nodes' offsets derived from them and the tree (by the document's scroll state refresh in process, by resolve_sticky_offsets() in the compositor).
+
+use super::{AccumulatedVisualContextTree, SpatialNodeIndex};
+use crate::visual_context::WorldTransforms;
+use libgfx_rust::FloatPoint;
+use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};
+use std::cell::RefCell;
+use std::sync::Arc;
+
+// The world transforms built for one visual context tree under a snapshot's offsets. A copy starts empty, so the table
+// never outlives the offsets it was built for. A move takes the table along with the offsets.
+#[derive(Default)]
+pub struct WorldTransformsCache {
+ // The cache retains the tree, so the tree it describes cannot change under it: a write to a shared tree copies it.
+ cached: RefCell<Option<(AccumulatedVisualContextTree, Arc<WorldTransforms>)>>,
+}
+
+impl Clone for WorldTransformsCache {
+ fn clone(&self) -> Self {
+ Self::default()
+ }
+}
+
+impl WorldTransformsCache {
+ pub fn get_or_build(
+ &self,
+ tree: &AccumulatedVisualContextTree,
+ device_offsets: &[FloatPoint],
+ ) -> Arc<WorldTransforms> {
+ let mut cached = self.cached.borrow_mut();
+ if let Some((retained_tree, world)) = cached.as_ref()
+ && Arc::ptr_eq(retained_tree.as_arc(), tree.as_arc())
+ {
+ return world.clone();
+ }
+ *cached = None;
+ let world = Arc::new(WorldTransforms::new(tree.as_arc(), device_offsets, None));
+ *cached = Some((tree.clone(), world.clone()));
+ world
+ }
+
+ pub fn clear(&self) {
+ *self.cached.borrow_mut() = None;
+ }
+}
+
+// Stored dense in process so display list replay and hit testing index it directly;
+// indices that are not scroll-like nodes read as zero offsets. The IPC representation is sparse
+// (index, offset) pairs.
+//
+// The dense store must never grow past the spatial node count. A compromised WebContent renderer controls the
+// indices that reach it — both as decoded wire pairs and as scroll-node indices replayed from the display list. So,
+// set_device_offset_for_index() drops any index at or past m_node_count. The compositor supplies that bound from the
+// AccumulatedVisualContextTree that owns these nodes. Until it does, the bound is unlimited — which is what the
+// trusted in-process snapshot built from live scroll nodes needs.
+#[derive(Clone)]
+pub struct ScrollStateSnapshot {
+ device_offsets: Vec<FloatPoint>,
+ staged_offsets: Vec<StagedOffset>,
+ node_count: usize,
+ world_transforms_cache: WorldTransformsCache,
+}
+
+impl Default for ScrollStateSnapshot {
+ fn default() -> Self {
+ Self {
+ device_offsets: Vec::new(),
+ staged_offsets: Vec::new(),
+ node_count: usize::MAX,
+ world_transforms_cache: WorldTransformsCache::default(),
+ }
+ }
+}
+
+impl ScrollStateSnapshot {
+ pub fn device_offsets(&self) -> &[FloatPoint] {
+ &self.device_offsets
+ }
+
+ // The world transforms of the tree under these offsets, in the layout viewport's space, kept until either changes.
+ pub fn world_transforms(&self, tree: &AccumulatedVisualContextTree) -> Arc<WorldTransforms> {
+ self.world_transforms_cache.get_or_build(tree, &self.device_offsets)
+ }
+
+ pub fn device_offset_for_index(&self, index: SpatialNodeIndex) -> FloatPoint {
+ self.device_offsets.get(index.0 as usize).copied().unwrap_or_default()
+ }
+
+ pub fn set_device_offset_for_index(&mut self, index: SpatialNodeIndex, offset: FloatPoint) {
+ let index = index.0 as usize;
+ if index >= self.node_count {
+ return;
+ }
+ self.world_transforms_cache.clear();
+ if index >= self.device_offsets.len() {
+ self.device_offsets.resize(index + 1, FloatPoint::default());
+ }
+ self.device_offsets[index] = offset;
+ }
+
+ // Replaces every offset with a freshly derived dense array, keeping the node count bound.
+ pub fn assign_device_offsets(&mut self, offsets: &[FloatPoint]) {
+ self.world_transforms_cache.clear();
+ self.device_offsets.clear();
+ self.device_offsets
+ .extend_from_slice(&offsets[..offsets.len().min(self.node_count)]);
+ }
+
+ // Bind the snapshot to the authoritative node count from the AccumulatedVisualContextTree that owns these nodes.
+ // Wire-decoded offsets are staged rather than densified. So, this is where a decoded index is first validated:
+ // staged pairs are applied through the bounded setter above, dropping any whose index is at or past the node count.
+ // And any offset already stored past the count is discarded. Every later mutation stays bounded by the count.
+ pub fn set_node_count(&mut self, node_count: usize) {
+ self.world_transforms_cache.clear();
+ self.node_count = node_count;
+ self.device_offsets.truncate(node_count);
+ let staged_offsets = std::mem::take(&mut self.staged_offsets);
+ for staged in staged_offsets {
+ self.set_device_offset_for_index(SpatialNodeIndex(staged.index), staged.offset);
+ }
+ }
+}
+
+// A sparse wire pair captured by the decoder before the node count is known. Held apart from the dense store — so
+// that a single decoded pair cannot grow the store to an arbitrary size.
+#[derive(Clone)]
+struct StagedOffset {
+ index: u32,
+ offset: FloatPoint,
+}
+
+// The dense in-process vector spans the whole spatial node index space, but only scroll and
+// sticky node indices can hold non-zero offsets, so the wire format is sparse (index, offset)
+// pairs; holes decode back to zero offsets.
+impl Encode for ScrollStateSnapshot {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ let device_offsets = self.device_offsets();
+ let mut non_zero_offset_count = 0u64;
+ for offset in device_offsets {
+ if !offset.is_zero() {
+ non_zero_offset_count += 1;
+ }
+ }
+ encoder.encode(&non_zero_offset_count)?;
+ for (index, offset) in device_offsets.iter().enumerate() {
+ if offset.is_zero() {
+ continue;
+ }
+ encoder.encode(&(index as u64))?;
+ encoder.encode(offset)?;
+ }
+ Ok(())
+ }
+}
+
+impl Decode for ScrollStateSnapshot {
+ const MIN_ENCODED_SIZE: usize = size_of::<u64>();
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let pair_count = decoder.decode::<u64>()?;
+ if pair_count > (decoder.remaining_bytes() / (size_of::<u64>() + FloatPoint::MIN_ENCODED_SIZE)) as u64 {
+ return Err(DecodeError::UnexpectedEnd);
+ }
+ let mut snapshot = Self::default();
+ for _ in 0..pair_count {
+ let index = decoder.decode::<u64>()?;
+ let offset = decoder.decode::<FloatPoint>()?;
+ if index >= u32::MAX as u64 {
+ return Err(DecodeError::InvalidValue(
+ "IPC decode: ScrollStateSnapshot index out of range",
+ ));
+ }
+ snapshot
+ .staged_offsets
+ .try_reserve(1)
+ .map_err(|_| DecodeError::AllocationFailed)?;
+ snapshot.staged_offsets.push(StagedOffset {
+ index: index as u32,
+ offset,
+ });
+ }
+ Ok(snapshot)
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs b/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs
new file mode 100644
index 00000000000..b1243badd18
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/scrolling/visual_context_tree.rs
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The visual context tree as the scroll and input logic reads it, under the method names of the C++ facade.
+
+use super::{ContextRef, DisplayList, ScrollStateSnapshot, SpatialNodeIndex};
+use crate::visual_context::VisualContextTree;
+use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, IntRect};
+use std::sync::Arc;
+
+pub use crate::visual_context::ffi_types::FfiVisualViewportTransform as TransformWithOrigin;
+pub use crate::visual_context::{ClipBehavior, IncludeVisualViewportTransform};
+
+#[derive(Clone)]
+pub struct AccumulatedVisualContextTree(Arc<VisualContextTree>);
+
+impl AccumulatedVisualContextTree {
+ pub fn from_arc(tree: Arc<VisualContextTree>) -> Self {
+ Self(tree)
+ }
+
+ pub fn as_arc(&self) -> &Arc<VisualContextTree> {
+ &self.0
+ }
+
+ pub fn structural_epoch(&self) -> u64 {
+ self.0.structural_epoch
+ }
+
+ // Node counts cover all slots, live or dead, or only live slots.
+ pub fn spatial_node_count(&self) -> usize {
+ self.0.spatial_nodes.len()
+ }
+
+ pub fn context_is_valid(&self, context: ContextRef) -> bool {
+ self.0.context_is_valid(context)
+ }
+
+ pub fn visual_viewport_transform(&self) -> TransformWithOrigin {
+ let crate::visual_context::SpatialData::Transform(transform) =
+ &self.0.spatial_nodes[crate::display_list::commands::VISUAL_VIEWPORT_NODE_INDEX.0 as usize].data
+ else {
+ unreachable!("the visual viewport node is a transform");
+ };
+ TransformWithOrigin {
+ matrix: transform.matrix,
+ origin: transform.origin,
+ }
+ }
+
+ pub fn with_visual_viewport_transform(&self, transform: &TransformWithOrigin) -> Self {
+ let mut copy = self.0.as_ref().clone();
+ copy.set_visual_viewport_matrix_and_origin(transform.matrix, transform.origin);
+ Self(Arc::new(copy))
+ }
+
+ pub fn has_visual_animations(&self) -> bool {
+ self.0.has_visual_animations()
+ }
+
+ pub fn has_active_visual_animation_at(&self, monotonic_time_ns: i64) -> bool {
+ self.0.has_active_visual_animation_at(monotonic_time_ns)
+ }
+
+ // Whether the point lies in the bounds of a node that a transform animation running at the time moves, through the
+ // values this tree holds: those of a sample at the time, where a frame shows it.
+ pub fn running_transform_animation_covers_point(
+ &self,
+ monotonic_time_ns: i64,
+ screen_point: FloatPoint,
+ scroll_state: &ScrollStateSnapshot,
+ ) -> bool {
+ self.0
+ .running_transform_animation_covers_point(monotonic_time_ns, screen_point, scroll_state.device_offsets())
+ }
+
+ // One flag per spatial node: whether a transform animation moves the node or an ancestor.
+ pub fn spatial_nodes_in_subtrees_of_transform_animations(&self) -> Vec<bool> {
+ self.0.spatial_nodes_in_subtrees_of_transform_animations()
+ }
+
+ // A copy whose nodes carry the values the animations take at the time.
+ pub fn with_visual_animation_samples(&self, monotonic_time_ns: i64) -> Self {
+ Self(Arc::new(self.0.with_visual_animation_samples(monotonic_time_ns)))
+ }
+
+ // Whether the node's scroll translations and the origins drawn in its space round to whole device pixels: no
+ // transform but identities lies above it.
+ pub fn translations_snap_to_device_pixels(
+ &self,
+ spatial_node_index: SpatialNodeIndex,
+ scroll_state: &ScrollStateSnapshot,
+ ) -> bool {
+ scroll_state
+ .world_transforms(self)
+ .translations_snap_to_device_pixels(spatial_node_index)
+ }
+
+ pub fn transform_point_for_hit_test(
+ &self,
+ context: ContextRef,
+ screen_point: FloatPoint,
+ scroll_state: &ScrollStateSnapshot,
+ clip_behavior: ClipBehavior,
+ ) -> Option<FloatPoint> {
+ self.0.transform_point_for_hit_test(
+ &scroll_state.world_transforms(self),
+ context,
+ screen_point,
+ clip_behavior,
+ )
+ }
+
+ pub fn transform_rect_to_viewport(
+ &self,
+ index: SpatialNodeIndex,
+ source_rect: FloatRect,
+ scroll_state: &ScrollStateSnapshot,
+ include_visual_viewport_transform: IncludeVisualViewportTransform,
+ ) -> FloatRect {
+ scroll_state.world_transforms(self).transform_rect_to_viewport(
+ index,
+ source_rect,
+ include_visual_viewport_transform,
+ )
+ }
+
+ // Sum of the snapshot entries along the scroll-parent chain from the given scroll-like node.
+ pub fn accumulated_matrix(
+ &self,
+ index: SpatialNodeIndex,
+ scroll_state: &ScrollStateSnapshot,
+ include_visual_viewport_transform: IncludeVisualViewportTransform,
+ ) -> FloatMatrix4x4 {
+ scroll_state
+ .world_transforms(self)
+ .to_viewport_matrix(index, include_visual_viewport_transform)
+ }
+}
+
+// Fills the snapshot entries of the tree's sticky nodes from the scroll containers' entries.
+pub fn resolve_sticky_offsets(tree: &AccumulatedVisualContextTree, scroll_state: &mut ScrollStateSnapshot) {
+ let resolved_sticky_entries = tree.0.resolve_sticky_offsets(scroll_state.device_offsets());
+ for (node_index, offset) in resolved_sticky_entries {
+ scroll_state.set_device_offset_for_index(node_index, offset);
+ }
+}
+
+pub struct AnimatedContentViewportEffect {
+ pub may_affect_viewport: bool,
+ // The answer holds until the scene changes: no finite animation is still running, so none can stop
+ // contributing on its own.
+ pub stable_until_scene_changes: bool,
+}
+
+impl Default for AnimatedContentViewportEffect {
+ fn default() -> Self {
+ Self {
+ may_affect_viewport: true,
+ stable_until_scene_changes: false,
+ }
+ }
+}
+
+// Whether the content the tree's animations move at the sample time can reach the viewport.
+pub fn animated_content_may_affect_viewport(
+ display_list: &DisplayList,
+ visual_context_tree: &AccumulatedVisualContextTree,
+ scroll_state: &ScrollStateSnapshot,
+ viewport_rect: IntRect,
+ sample_time_ns: i64,
+) -> AnimatedContentViewportEffect {
+ let effect = crate::display_list::damage::animated_content_may_affect_viewport_at(
+ display_list.storage.bytes(),
+ display_list.storage.command_runs(),
+ visual_context_tree.as_arc(),
+ scroll_state.device_offsets(),
+ viewport_rect,
+ sample_time_ns,
+ );
+ AnimatedContentViewportEffect {
+ may_affect_viewport: effect.may_affect_viewport,
+ stable_until_scene_changes: effect.stable_until_scene_changes,
+ }
+}
diff --git a/Libraries/LibGfx/Rust/src/geometry.rs b/Libraries/LibGfx/Rust/src/geometry.rs
index e87175d9aa2..02732c81dc8 100644
--- a/Libraries/LibGfx/Rust/src/geometry.rs
+++ b/Libraries/LibGfx/Rust/src/geometry.rs
@@ -42,6 +42,12 @@ pub struct FloatSize {
pub height: f32,
}
+impl FloatSize {
+ pub fn is_empty(self) -> bool {
+ self.width <= 0.0 || self.height <= 0.0
+ }
+}
+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct IntRect {