Skip to content

Truly independent web browser

LibWeb+LibCompositing: Reach the scrolling code through Rust

Aliaksandr Kalenika07fbb26fd60
diff --git a/Libraries/LibCompositing/CMakeLists.txt b/Libraries/LibCompositing/CMakeLists.txt
index d3e3b5499c9..d944320150f 100644
--- a/Libraries/LibCompositing/CMakeLists.txt
+++ b/Libraries/LibCompositing/CMakeLists.txt
@@ -11,14 +11,9 @@ set(SOURCES
DisplayList/RustFFIAssertions.cpp
DisplayList/VisualContextTreeTestBuilder.cpp
FontServiceClient.cpp
- Scrolling/AsyncScrollTree.cpp
- Scrolling/AsyncScrollingState.cpp
- Scrolling/ElasticOverscroll.cpp
- Scrolling/ScrollFling.cpp
- Scrolling/ScrollSnapSelection.cpp
+ Scrolling/RecordedDisplayListScrolling.cpp
Scrolling/ScrollState.cpp
Scrolling/SmoothScrollAnimation.cpp
- Scrolling/WheelGestureIdentity.cpp
UIOverlays.cpp
Video/VideoFrameHold.cpp
Video/VideoFramePresentationPage.cpp
@@ -111,7 +106,7 @@ if(NOT BUILD_SHARED_LIBS)
# POST_BUILD steps don't track inputs, so the bridge files depend on the Rust archive: when it
# changes, LibCompositing re-archives and the merge picks up the fresh objects.
- foreach(bridge IN ITEMS DisplayList/AccumulatedVisualContext.cpp DisplayList/DisplayList.cpp DisplayList/DisplayListDamage.cpp DisplayList/DisplayListResourceStorage.cpp DisplayList/VisualContextTreeTestBuilder.cpp)
+ foreach(bridge IN ITEMS DisplayList/AccumulatedVisualContext.cpp DisplayList/DisplayList.cpp DisplayList/DisplayListDamage.cpp DisplayList/DisplayListResourceStorage.cpp DisplayList/VisualContextTreeTestBuilder.cpp Scrolling/RecordedDisplayListScrolling.cpp Scrolling/SmoothScrollAnimation.cpp)
set_property(SOURCE ${bridge} APPEND PROPERTY OBJECT_DEPENDS ${_libcompositing_rust_lib})
endforeach()
endif()
diff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp
index aa72a20b5ae..1b78b5977f8 100644
--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp
+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp
@@ -88,16 +88,6 @@ ByteBuffer AccumulatedVisualContextTree::serialize_to_bytes() const
return bytes;
}
-size_t AccumulatedVisualContextTree::spatial_node_count() const
-{
- return Compositing::RustFFI::visual_context_tree_spatial_node_count(m_rust_tree);
-}
-
-bool AccumulatedVisualContextTree::context_is_valid(ContextRef context) const
-{
- return Compositing::RustFFI::visual_context_tree_context_is_valid(m_rust_tree, context);
-}
-
size_t AccumulatedVisualContextTree::node_count() const
{
return Compositing::RustFFI::visual_context_tree_node_count(m_rust_tree);
@@ -108,34 +98,11 @@ size_t AccumulatedVisualContextTree::live_node_count() const
return Compositing::RustFFI::visual_context_tree_live_node_count(m_rust_tree);
}
-TransformWithOrigin AccumulatedVisualContextTree::visual_viewport_transform() const
-{
- TransformWithOrigin transform;
- Compositing::RustFFI::visual_context_tree_visual_viewport_transform(m_rust_tree, &transform);
- return transform;
-}
-
-AccumulatedVisualContextTree AccumulatedVisualContextTree::with_visual_viewport_transform(TransformWithOrigin const& transform) const
-{
- return adopt_rust_handle(Compositing::RustFFI::visual_context_tree_with_visual_viewport_transform(m_rust_tree, transform));
-}
-
bool AccumulatedVisualContextTree::has_visual_animations() const
{
return Compositing::RustFFI::visual_context_tree_has_visual_animations(m_rust_tree);
}
-bool AccumulatedVisualContextTree::has_active_visual_animation_at(i64 monotonic_time_ns) const
-{
- return Compositing::RustFFI::visual_context_tree_has_active_visual_animation_at(m_rust_tree, monotonic_time_ns);
-}
-
-bool AccumulatedVisualContextTree::running_transform_animation_covers_point(i64 monotonic_time_ns, Gfx::FloatPoint screen_point, ScrollStateSnapshot const& scroll_state) const
-{
- auto scroll_offsets = scroll_state.device_offsets();
- return Compositing::RustFFI::visual_context_tree_running_transform_animation_covers_point(m_rust_tree, monotonic_time_ns, screen_point, scroll_offsets.data(), scroll_offsets.size());
-}
-
VisualAnimationSummary AccumulatedVisualContextTree::visual_animation_summary() const
{
auto summary = Compositing::RustFFI::visual_context_tree_visual_animation_summary(m_rust_tree);
@@ -147,14 +114,6 @@ VisualAnimationSummary AccumulatedVisualContextTree::visual_animation_summary()
};
}
-Vector<bool> AccumulatedVisualContextTree::spatial_nodes_in_subtrees_of_transform_animations() const
-{
- Vector<bool> in_subtree;
- in_subtree.resize(spatial_node_count());
- Compositing::RustFFI::visual_context_tree_mark_spatial_subtrees_of_transform_animations(m_rust_tree, in_subtree.data(), in_subtree.size());
- return in_subtree;
-}
-
AccumulatedVisualContextTree AccumulatedVisualContextTree::with_visual_animation_samples(i64 monotonic_time_ns) const
{
return adopt_rust_handle(Compositing::RustFFI::visual_context_tree_with_visual_animation_samples(m_rust_tree, monotonic_time_ns));
@@ -173,24 +132,11 @@ bool AccumulatedVisualContextTree::translations_snap_to_device_pixels(SpatialNod
return Compositing::RustFFI::world_transforms_translations_snap_to_device_pixels(scroll_state.world_transforms(*this), spatial_node_index);
}
-Optional<Gfx::FloatPoint> AccumulatedVisualContextTree::transform_point_for_hit_test(ContextRef context, Gfx::FloatPoint screen_point, ScrollStateSnapshot const& scroll_state, ClipBehavior clip_behavior) const
-{
- Gfx::FloatPoint local_point;
- if (!Compositing::RustFFI::visual_context_tree_transform_point_for_hit_test(m_rust_tree, scroll_state.world_transforms(*this), context, screen_point, clip_behavior == ClipBehavior::Respect, &local_point))
- return {};
- return local_point;
-}
-
-Gfx::FloatRect AccumulatedVisualContextTree::transform_rect_to_viewport(SpatialNodeIndex index, Gfx::FloatRect const& source_rect, ScrollStateSnapshot const& scroll_state, IncludeVisualViewportTransform include_visual_viewport_transform) const
-{
- Gfx::FloatRect rect;
- Compositing::RustFFI::world_transforms_transform_rect_to_viewport(scroll_state.world_transforms(*this), index, source_rect, include_visual_viewport_transform == IncludeVisualViewportTransform::Yes, &rect);
- return rect;
-}
-
Gfx::FloatMatrix4x4 AccumulatedVisualContextTree::accumulated_matrix(SpatialNodeIndex index, ScrollStateSnapshot const& scroll_state, IncludeVisualViewportTransform include_visual_viewport_transform) const
{
- return Compositing::RustFFI::world_transforms_accumulated_matrix(scroll_state.world_transforms(*this), index, include_visual_viewport_transform == IncludeVisualViewportTransform::Yes);
+ Gfx::FloatMatrix4x4 matrix;
+ Compositing::RustFFI::world_transforms_accumulated_matrix(scroll_state.world_transforms(*this), index, include_visual_viewport_transform == IncludeVisualViewportTransform::Yes, &matrix);
+ return matrix;
}
void AccumulatedVisualContextTree::for_each_effects_filter_image_frame_id(Function<void(u64)> const& visit) const
@@ -203,16 +149,6 @@ void AccumulatedVisualContextTree::for_each_effects_filter_image_frame_id(Functi
});
}
-void resolve_sticky_offsets(AccumulatedVisualContextTree const& tree, ScrollStateSnapshot& scroll_state)
-{
- auto scroll_offsets = scroll_state.device_offsets();
- Compositing::RustFFI::visual_context_tree_resolve_sticky_offsets(
- tree.rust_handle(), scroll_offsets.data(), scroll_offsets.size(),
- &scroll_state, [](void* sink, SpatialNodeIndex index, Gfx::FloatPoint offset) {
- static_cast<ScrollStateSnapshot*>(sink)->set_device_offset_for_index(index, offset);
- });
-}
-
}
namespace IPC {
diff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h
index b8d46edd940..0709679a35d 100644
--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h
+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h
@@ -25,11 +25,6 @@ namespace Compositing {
class ScrollStateSnapshot;
-struct TransformWithOrigin {
- Gfx::FloatMatrix4x4 matrix;
- Gfx::FloatPoint origin;
-};
-
// What a tree reports about the animations it carries, for test introspection.
struct VisualAnimationSummary {
size_t count { 0 };
@@ -45,13 +40,6 @@ public:
Yes,
};
- enum class ClipBehavior {
- Respect,
- // Transform the point without rejecting it against clip rects and clip paths. Used when searching for the
- // closest caret position within a scope the point may lie entirely outside of.
- Ignore,
- };
-
static AccumulatedVisualContextTree adopt_rust_handle(void const* retained_tree);
static ErrorOr<AccumulatedVisualContextTree> from_serialized_bytes(ReadonlyBytes);
@@ -66,21 +54,11 @@ public:
void const* rust_handle() const { return m_rust_tree; }
bool has_visual_animations() const;
- bool has_active_visual_animation_at(i64 monotonic_time_ns) const;
- // 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.
- bool running_transform_animation_covers_point(i64 monotonic_time_ns, Gfx::FloatPoint screen_point, ScrollStateSnapshot const&) const;
VisualAnimationSummary visual_animation_summary() const;
- // One flag per spatial node: whether a transform animation moves the node or an ancestor.
- Vector<bool> spatial_nodes_in_subtrees_of_transform_animations() const;
// Node counts cover all slots, live or dead, or only live slots.
- size_t spatial_node_count() const;
- bool context_is_valid(ContextRef) const;
size_t node_count() const;
size_t live_node_count() const;
- TransformWithOrigin visual_viewport_transform() const;
- AccumulatedVisualContextTree with_visual_viewport_transform(TransformWithOrigin const&) const;
// A copy whose nodes carry the values the animations take at the time.
AccumulatedVisualContextTree with_visual_animation_samples(i64 monotonic_time_ns) const;
// The sampled background color of a recorded fill's animation effect.
@@ -89,8 +67,6 @@ public:
// transform but identities lies above it.
bool translations_snap_to_device_pixels(SpatialNodeIndex, ScrollStateSnapshot const&) const;
- Optional<Gfx::FloatPoint> transform_point_for_hit_test(ContextRef, Gfx::FloatPoint, ScrollStateSnapshot const&, ClipBehavior = ClipBehavior::Respect) const;
- Gfx::FloatRect transform_rect_to_viewport(SpatialNodeIndex, Gfx::FloatRect const&, ScrollStateSnapshot const&, IncludeVisualViewportTransform = IncludeVisualViewportTransform::Yes) const;
// Sum of the snapshot entries along the scroll-parent chain from the given scroll-like node.
Gfx::FloatMatrix4x4 accumulated_matrix(SpatialNodeIndex, ScrollStateSnapshot const&, IncludeVisualViewportTransform) const;
@@ -104,9 +80,6 @@ private:
void const* m_rust_tree { nullptr };
};
-// Fills the snapshot entries of the tree's sticky nodes from the scroll containers' entries.
-COMPOSITING_API void resolve_sticky_offsets(AccumulatedVisualContextTree const&, ScrollStateSnapshot&);
-
}
namespace IPC {
diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.cpp b/Libraries/LibCompositing/DisplayList/DisplayList.cpp
index 843eca50576..81e53ce52a8 100644
--- a/Libraries/LibCompositing/DisplayList/DisplayList.cpp
+++ b/Libraries/LibCompositing/DisplayList/DisplayList.cpp
@@ -95,21 +95,6 @@ bool DisplayList::requires_direct_replay_without_nested_lists(AccumulatedVisualC
return RustFFI::display_list_storage_requires_direct_replay_without_nested_lists(m_storage, visual_context_tree.rust_handle());
}
-void DisplayList::for_each_compositor_metadata(Function<void(ContextRef, DisplayListCommandType, ReadonlyBytes)> const& callback) const
-{
- RustFFI::display_list_storage_for_each_compositor_metadata(m_storage, const_cast<void*>(static_cast<void const*>(&callback)), [](void* context, ContextRef run_context, DisplayListCommandType command_type, u8 const* payload, size_t payload_size) {
- (*static_cast<Function<void(ContextRef, DisplayListCommandType, ReadonlyBytes)> const*>(context))(run_context, command_type, { payload, payload_size });
- });
-}
-
-void DisplayList::for_each_caret(Function<void(ContextRef, Gfx::IntRect, PaintCaret const&)> const& callback) const
-{
- RustFFI::display_list_storage_for_each_caret(m_storage, const_cast<void*>(static_cast<void const*>(&callback)), [](void* context, ContextRef run_context, Gfx::IntRect bounding_rect, u8 const* payload, size_t payload_size) {
- auto command = read_display_list_object<PaintCaret>({ payload, payload_size });
- (*static_cast<Function<void(ContextRef, Gfx::IntRect, PaintCaret const&)> const*>(context))(run_context, bounding_rect, command);
- });
-}
-
void DisplayList::replay(AccumulatedVisualContextTree const& visual_context_tree, ScrollStateSnapshot const& scroll_state, RustFFI::FfiDisplayListReplayCallbacks const& callbacks) const
{
VERIFY(m_compatible_visual_context_tree_structural_epoch == visual_context_tree.structural_epoch());
diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.h b/Libraries/LibCompositing/DisplayList/DisplayList.h
index 19601bc3c96..c0e8618aed7 100644
--- a/Libraries/LibCompositing/DisplayList/DisplayList.h
+++ b/Libraries/LibCompositing/DisplayList/DisplayList.h
@@ -109,10 +109,6 @@ public:
// Whether reusing a raster of the list can produce different pixels than replaying it in place, leaving out the
// display lists it nests.
bool requires_direct_replay_without_nested_lists(AccumulatedVisualContextTree const&) const;
- // Visits the compositor metadata commands with the context of their run and their payload, in tape order.
- void for_each_compositor_metadata(Function<void(ContextRef, DisplayListCommandType, ReadonlyBytes payload)> const&) const;
- // Visits the carets the list draws outside of any group, with the context of their run and their bounding rect.
- void for_each_caret(Function<void(ContextRef, Gfx::IntRect, PaintCaret const&)> const&) const;
// Replays the list through a player's callbacks, against the visual context tree it was made for.
void replay(AccumulatedVisualContextTree const&, ScrollStateSnapshot const&, RustFFI::FfiDisplayListReplayCallbacks const&) const;
diff --git a/Libraries/LibCompositing/DisplayList/DisplayListDamage.cpp b/Libraries/LibCompositing/DisplayList/DisplayListDamage.cpp
index 9b430b31294..9e602295b91 100644
--- a/Libraries/LibCompositing/DisplayList/DisplayListDamage.cpp
+++ b/Libraries/LibCompositing/DisplayList/DisplayListDamage.cpp
@@ -39,20 +39,4 @@ Optional<Gfx::IntRect> compute_display_list_damage(
return damage_rect;
}
-AnimatedContentViewportEffect animated_content_may_affect_viewport(
- DisplayList const& display_list,
- AccumulatedVisualContextTree const& visual_context_tree,
- ScrollStateSnapshot const& scroll_state,
- Gfx::IntRect viewport_rect,
- i64 sample_time_ns)
-{
- auto scroll_offsets = scroll_state.device_offsets();
- auto effect = Compositing::RustFFI::display_list_animated_content_may_affect_viewport(
- display_list.rust_handle(), visual_context_tree.rust_handle(), scroll_offsets.data(), scroll_offsets.size(), viewport_rect, sample_time_ns);
- return {
- .may_affect_viewport = effect.may_affect_viewport,
- .stable_until_scene_changes = effect.stable_until_scene_changes,
- };
-}
-
}
diff --git a/Libraries/LibCompositing/DisplayList/DisplayListDamage.h b/Libraries/LibCompositing/DisplayList/DisplayListDamage.h
index 9ebf11477b5..d34a34354e3 100644
--- a/Libraries/LibCompositing/DisplayList/DisplayListDamage.h
+++ b/Libraries/LibCompositing/DisplayList/DisplayListDamage.h
@@ -39,19 +39,4 @@ COMPOSITING_API Optional<Gfx::IntRect> compute_display_list_damage(
Gfx::IntRect viewport_rect,
LiveContentChanges);
-struct AnimatedContentViewportEffect {
- bool may_affect_viewport { true };
- // The answer holds until the scene changes: no finite animation is still running, so none can stop
- // contributing on its own.
- bool stable_until_scene_changes { false };
-};
-
-// Whether the content the tree's animations move at the sample time can reach the viewport.
-COMPOSITING_API AnimatedContentViewportEffect animated_content_may_affect_viewport(
- DisplayList const&,
- AccumulatedVisualContextTree const&,
- ScrollStateSnapshot const&,
- Gfx::IntRect viewport_rect,
- i64 sample_time_ns);
-
}
diff --git a/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cpp b/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cpp
index 3a0983110c4..e5550e5c951 100644
--- a/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cpp
+++ b/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cpp
@@ -76,6 +76,10 @@ static_assert(to_underlying(Compositing::RustFFI::ScalingMode::None) == to_under
static_assert(to_underlying(Compositing::RustFFI::ScalingMode::Bilinear) == to_underlying(Gfx::ScalingMode::Bilinear));
static_assert(to_underlying(Compositing::RustFFI::ScalingMode::BilinearMipmap) == to_underlying(Gfx::ScalingMode::BilinearMipmap));
static_assert(to_underlying(Compositing::RustFFI::ScalingMode::NearestNeighbor) == to_underlying(Gfx::ScalingMode::NearestNeighbor));
+static_assert(sizeof(Compositing::RustFFI::SnapSelectionStrategyType) == sizeof(Compositing::SnapSelectionStrategy::Type));
+static_assert(to_underlying(Compositing::RustFFI::SnapSelectionStrategyType::EndPosition) == to_underlying(Compositing::SnapSelectionStrategy::Type::EndPosition));
+static_assert(to_underlying(Compositing::RustFFI::SnapSelectionStrategyType::Direction) == to_underlying(Compositing::SnapSelectionStrategy::Type::Direction));
+static_assert(to_underlying(Compositing::RustFFI::SnapSelectionStrategyType::EndPositionAndDirection) == to_underlying(Compositing::SnapSelectionStrategy::Type::EndPositionAndDirection));
static_assert(sizeof(Compositing::RustFFI::CompositingAndBlendingOperator) == sizeof(Gfx::CompositingAndBlendingOperator));
static_assert(to_underlying(Compositing::RustFFI::CompositingAndBlendingOperator::Normal) == to_underlying(Gfx::CompositingAndBlendingOperator::Normal));
static_assert(to_underlying(Compositing::RustFFI::CompositingAndBlendingOperator::Multiply) == to_underlying(Gfx::CompositingAndBlendingOperator::Multiply));
diff --git a/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.cpp b/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.cpp
index a4a9d52ab6a..9b16b2e109e 100644
--- a/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.cpp
+++ b/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.cpp
@@ -21,40 +21,6 @@ VisualContextTreeTestBuilder::~VisualContextTreeTestBuilder()
Compositing::RustFFI::visual_context_tree_test_builder_destroy(m_builder);
}
-SpatialNodeIndex VisualContextTreeTestBuilder::append_transform(SpatialNodeIndex parent, Gfx::FloatMatrix4x4 const& matrix, Gfx::FloatPoint origin)
-{
- return SpatialNodeIndex { Compositing::RustFFI::visual_context_tree_test_builder_append_transform(m_builder, parent.value(), matrix, origin) };
-}
-
-SpatialNodeIndex VisualContextTreeTestBuilder::append_scroll(SpatialNodeIndex parent)
-{
- return SpatialNodeIndex { Compositing::RustFFI::visual_context_tree_test_builder_append_scroll(m_builder, parent.value()) };
-}
-
-SpatialNodeIndex VisualContextTreeTestBuilder::append_sticky(SpatialNodeIndex parent, StickyConstraints const& constraints)
-{
- Compositing::RustFFI::FfiTestStickyConstraints ffi_constraints {
- .scroller = constraints.scroller.value(),
- .has_parent_sticky = constraints.parent_sticky.has_value(),
- .parent_sticky = constraints.parent_sticky.value_or(VISUAL_VIEWPORT_NODE_INDEX).value(),
- .position_relative_to_scroller = constraints.position_relative_to_scroller,
- .border_box_size = constraints.border_box_size,
- .scrollport_size = constraints.scrollport_size,
- .containing_block_region = constraints.containing_block_region,
- .needs_parent_offset_adjustment = constraints.needs_parent_offset_adjustment,
- .inset_top = constraints.inset_top,
- .inset_right = constraints.inset_right,
- .inset_bottom = constraints.inset_bottom,
- .inset_left = constraints.inset_left,
- };
- return SpatialNodeIndex { Compositing::RustFFI::visual_context_tree_test_builder_append_sticky(m_builder, parent.value(), ffi_constraints) };
-}
-
-ClipNodeIndex VisualContextTreeTestBuilder::append_clip(ClipNodeIndex parent, SpatialNodeIndex spatial, Gfx::FloatRect rect, Gfx::CornerRadii corner_radii, ClipMode mode)
-{
- return ClipNodeIndex { Compositing::RustFFI::visual_context_tree_test_builder_append_clip(m_builder, parent.value(), spatial.value(), rect, corner_radii, mode) };
-}
-
EffectNodeIndex VisualContextTreeTestBuilder::append_image_filter(u64 image_id, Gfx::IntRect rect)
{
return EffectNodeIndex { RustFFI::visual_context_tree_test_builder_append_image_filter(m_builder, image_id, rect) };
diff --git a/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.h b/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.h
index 9d13ac4267b..3a5d01b169d 100644
--- a/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.h
+++ b/Libraries/LibCompositing/DisplayList/VisualContextTreeTestBuilder.h
@@ -28,28 +28,9 @@ class COMPOSITING_API VisualContextTreeTestBuilder {
AK_MAKE_NONMOVABLE(VisualContextTreeTestBuilder);
public:
- struct StickyConstraints {
- SpatialNodeIndex scroller;
- Optional<SpatialNodeIndex> parent_sticky;
- Gfx::FloatPoint position_relative_to_scroller;
- Gfx::FloatSize border_box_size;
- Gfx::FloatSize scrollport_size;
- Gfx::FloatRect containing_block_region;
- bool needs_parent_offset_adjustment { false };
- Optional<float> inset_top;
- Optional<float> inset_right;
- Optional<float> inset_bottom;
- Optional<float> inset_left;
- };
-
VisualContextTreeTestBuilder();
~VisualContextTreeTestBuilder();
- SpatialNodeIndex append_transform(SpatialNodeIndex parent, Gfx::FloatMatrix4x4 const&, Gfx::FloatPoint origin = {});
- SpatialNodeIndex append_scroll(SpatialNodeIndex parent);
- SpatialNodeIndex append_sticky(SpatialNodeIndex parent, StickyConstraints const&);
- ClipNodeIndex append_clip(ClipNodeIndex parent, SpatialNodeIndex spatial, Gfx::FloatRect, Gfx::CornerRadii = {}, ClipMode = ClipMode::Intersect);
-
EffectNodeIndex append_image_filter(u64 image_id, Gfx::IntRect);
static NonnullRefPtr<DisplayList> filled_rect_display_list(AccumulatedVisualContextTree const&, ContextRef, Gfx::IntRect, Gfx::Color);
static NonnullRefPtr<DisplayList> rounded_rect_ring_display_list(AccumulatedVisualContextTree const&, ContextRef, FillRoundedRectRing const&);
diff --git a/Libraries/LibCompositing/OverlayFade.h b/Libraries/LibCompositing/OverlayFade.h
index 9a1cc2ca828..93df8d8f6b6 100644
--- a/Libraries/LibCompositing/OverlayFade.h
+++ b/Libraries/LibCompositing/OverlayFade.h
@@ -26,15 +26,6 @@ public:
m_started_at = now;
}
- // Ends any fade, with the opacity at once where it would end.
- void jump_to(float opacity)
- {
- m_opacity = opacity;
- m_initial_opacity = opacity;
- m_target_opacity = opacity;
- m_started_at.clear();
- }
-
// Returns whether the opacity changed.
bool advance_to(MonotonicTime frame_time)
{
diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rs
index eaac4085363..c03d4e5ba6b 100644
--- a/Libraries/LibCompositing/Rust/build.rs
+++ b/Libraries/LibCompositing/Rust/build.rs
@@ -103,7 +103,6 @@ fn expose_shared_abi_types_as_cpp_types(config: &mut cbindgen::Config) {
"ReplayClip",
"ReplayLayer",
"ReplayMask",
- "FfiVisualViewportTransform",
"CanvasId",
"VideoSinkResourceId",
"Canvas2DPaintKind",
@@ -154,7 +153,6 @@ fn expose_shared_abi_types_as_cpp_types(config: &mut cbindgen::Config) {
("ReplayClip", "Compositing::ReplayClip"),
("ReplayLayer", "Compositing::ReplayLayer"),
("ReplayMask", "Compositing::ReplayMask"),
- ("FfiVisualViewportTransform", "Compositing::TransformWithOrigin"),
("CanvasId", "Compositing::CanvasId"),
("VideoSinkResourceId", "Compositing::VideoSinkResourceId"),
("Canvas2DPaintKind", "Compositing::Canvas2DPaintKind"),
@@ -353,6 +351,11 @@ fn main() -> Result<(), Box<dyn Error>> {
ffi_config.namespaces = Some(vec!["Compositing".to_string(), "RustFFI".to_string()]);
expose_css_pixel_types_as_web_types(&mut ffi_config);
expose_shared_abi_types_as_cpp_types(&mut ffi_config);
+ ffi_config.export.exclude.extend([
+ "MOMENTUM_DISTANCE_SHARE_PER_FRAME".to_string(),
+ "MOMENTUM_FRAME_DURATION_IN_SECONDS".to_string(),
+ "MAXIMUM_MOMENTUM_DURATION_IN_SECONDS".to_string(),
+ ]);
// An ak::Span is laid out as an AK ReadonlySpan, which C++ passes it as.
ffi_config
.export
@@ -362,6 +365,22 @@ fn main() -> Result<(), Box<dyn Error>> {
.export
.rename
.insert("EncodedValue".to_string(), "AK::ReadonlyBytes".to_string());
+ // The IPC compiler checks that these enums have the numbers in C++ that they have in Rust.
+ for (rust_name, cpp_name) in [
+ ("ScrollAnimationKind", "Compositing::ScrollAnimationKind"),
+ ("InputRoutingDecision", "Web::InputRoutingDecision"),
+ ("AsyncScrollNodeKind", "Web::AsyncScrollNodeKind"),
+ ] {
+ ffi_config
+ .export
+ .rename
+ .insert(rust_name.to_string(), cpp_name.to_string());
+ }
+ ffi_config.after_includes = Some(
+ "\nnamespace Compositing { enum class ScrollAnimationKind : uint8_t; }\nnamespace Web { enum class \
+ InputRoutingDecision : uint8_t; enum class AsyncScrollNodeKind : uint8_t; }"
+ .to_string(),
+ );
ffi_config.includes.push("AK/Span.h".to_string());
// The values the entry points of WebContent and of the compositor's scroll logic take and return, which their
// headers refer to here.
@@ -376,13 +395,12 @@ fn main() -> Result<(), Box<dyn Error>> {
"FfiVisualAnimationTransformOperationKind",
"FfiCompositorAnimationPublishOutcome",
"FfiVisualAnimationSummary",
- "FfiAnimatedContentViewportEffect",
- "FfiTestStickyConstraints",
"FfiDisplayListReplayCallbacks",
"FfiDisplayList",
"FfiEasingDescriptor",
"FfiEasingKind",
"FfiLinearEasingPoint",
+ "SnapSelectionStrategyType",
]
.map(String::from)
.to_vec();
@@ -406,6 +424,8 @@ fn main() -> Result<(), Box<dyn Error>> {
manifest_dir.join("src/display_list/storage.rs"),
manifest_dir.join("src/display_list/canvas_2d.rs"),
manifest_dir.join("src/display_list/canvas_2d_recorder.rs"),
+ manifest_dir.join("src/scrolling/smooth_scroll_animation.rs"),
+ manifest_dir.join("src/scrolling/scroll_snap_selection.rs"),
manifest_dir.join("src/ffi.rs"),
],
&out_dir,
diff --git a/Libraries/LibCompositing/Rust/src/display_list/storage.rs b/Libraries/LibCompositing/Rust/src/display_list/storage.rs
index 87d948decc4..e82264d03cc 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/storage.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/storage.rs
@@ -9,12 +9,9 @@
//! it back to the entry points of this crate.
use super::builder::RecordedDisplayList;
-use super::commands::{ContextRef, DisplayListCommandRun, DisplayListCommandType};
+use super::commands::{ContextRef, DisplayListCommandRun};
use super::effect_clip_plan::EffectClipPlan;
-use super::summary::{
- DisplayListSummary, for_each_compositor_metadata, for_each_indexed_record,
- requires_direct_replay_without_nested_lists, summarize,
-};
+use super::summary::{DisplayListSummary, requires_direct_replay_without_nested_lists, summarize};
use super::validate::validate_tape;
use crate::visual_context::VisualContextTree;
use std::ffi::c_void;
@@ -403,58 +400,6 @@ pub unsafe extern "C" fn display_list_storage_requires_direct_replay_without_nes
requires_direct_replay_without_nested_lists(storage.bytes(), storage.command_runs(), tree)
}
-/// Calls `visit` with each compositor metadata command, its run's context and its payload.
-///
-/// # Safety
-/// `storage` must be a live storage handle. `visit` runs synchronously.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn display_list_storage_for_each_compositor_metadata(
- storage: *const c_void,
- context: *mut c_void,
- visit: unsafe extern "C" fn(*mut c_void, ContextRef, DisplayListCommandType, *const u8, usize),
-) {
- let storage = unsafe { storage_from_handle(storage) };
- for_each_compositor_metadata(
- storage.bytes(),
- storage.command_runs(),
- |run_context, command_type, payload| {
- // SAFETY: The caller reads the payload synchronously.
- unsafe { visit(context, run_context, command_type, payload.as_ptr(), payload.len()) };
- },
- );
-}
-
-/// Calls `visit` with each top-level PaintCaret record of the list: its run's context, its bounding
-/// rect, and its payload.
-///
-/// # Safety
-/// `storage` must be a live storage handle. `visit` runs synchronously.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn display_list_storage_for_each_caret(
- storage: *const c_void,
- context: *mut c_void,
- visit: unsafe extern "C" fn(*mut c_void, ContextRef, libgfx_rust::IntRect, *const u8, usize),
-) {
- let storage = unsafe { storage_from_handle(storage) };
- for_each_indexed_record(
- storage.bytes(),
- storage.command_runs(),
- &storage.summary().carets,
- |run_context, header, payload| {
- // SAFETY: The caller reads the payload synchronously.
- unsafe {
- visit(
- context,
- run_context,
- header.bounding_rect,
- payload.as_ptr(),
- payload.len(),
- );
- }
- },
- );
-}
-
// A tape and run table that C++ writes into before they are checked.
pub struct PendingDisplayListStorage {
bytes: AlignedBytes,
diff --git a/Libraries/LibCompositing/Rust/src/display_list/validate.rs b/Libraries/LibCompositing/Rust/src/display_list/validate.rs
index 1e0800d77df..9d19124ca48 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/validate.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/validate.rs
@@ -93,7 +93,7 @@ impl TapeEnum for CompositingAndBlendingOperator {
}
}
-// The values of SnapStrictness and SnapAlign in LibCompositing/Scrolling/ScrollSnapSelection.h.
+// The values of SnapStrictness and SnapAlign in scrolling::scroll_snap_selection.
const SNAP_STRICTNESS_COUNT: u8 = 3;
const SNAP_ALIGN_COUNT: u8 = 4;
diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rs
index fb28d9a89a5..500fdb03a96 100644
--- a/Libraries/LibCompositing/Rust/src/ffi.rs
+++ b/Libraries/LibCompositing/Rust/src/ffi.rs
@@ -7,10 +7,14 @@
//! The entry points the compositor process shares with WebContent: retaining and querying visual
//! context trees, replaying display lists, computing their damage, and the tree builder tests use.
-use crate::display_list::commands::{ClipNodeIndex, ContextRef, EffectNodeIndex, SpatialNodeIndex};
+use crate::display_list::commands::{EffectNodeIndex, SpatialNodeIndex};
use crate::display_list::storage::storage_from_handle;
-use crate::node_slot_id::NodeSlotId;
-use crate::scrolling::{AccumulatedVisualContextTree, DisplayList};
+use crate::scrolling::smooth_scroll_animation::SmoothScrollAnimation;
+use crate::scrolling::{
+ AccumulatedVisualContextTree, AsyncScrollNodeKind, DisplayList, InputRoutingDecision, ScrollAnimationKind,
+};
+use crate::time::Duration;
+use libgfx_rust::FloatPoint;
use libipc_rust::DecodeError;
use libipc_rust::cpp_connection::EncodedValue;
use std::ffi::c_void;
@@ -118,33 +122,6 @@ pub unsafe extern "C" fn display_list_compute_damage(
}
}
-/// # Safety
-///
-/// The storage and the tree must be live handles and `scroll_offsets` must address
-/// `scroll_offsets_len` points.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn display_list_animated_content_may_affect_viewport(
- storage: *const c_void,
- tree: *const c_void,
- scroll_offsets: *const libgfx_rust::FloatPoint,
- scroll_offsets_len: usize,
- viewport_rect: libgfx_rust::IntRect,
- sample_time_ns: i64,
-) -> crate::host::FfiAnimatedContentViewportEffect {
- // SAFETY: The caller guarantees live handles and valid slices for the duration of the call.
- unsafe {
- let storage = storage_from_handle(storage);
- crate::display_list::damage::animated_content_may_affect_viewport_at(
- storage.bytes(),
- storage.command_runs(),
- tree_from_handle(tree),
- ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len),
- viewport_rect,
- sample_time_ns,
- )
- }
-}
-
/// # Safety
///
/// `tree` must be a live retained tree handle of the structural epoch the storage was recorded
@@ -269,22 +246,6 @@ pub unsafe extern "C" fn visual_context_tree_deserialize(bytes: *const u8, lengt
}
}
-/// # Safety
-///
-/// `tree` must be a live retained tree handle.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_spatial_node_count(tree: *const c_void) -> usize {
- unsafe { tree_from_handle(tree) }.spatial_nodes.len()
-}
-
-/// # Safety
-///
-/// `tree` must be a live retained tree handle.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_context_is_valid(tree: *const c_void, context: ContextRef) -> bool {
- unsafe { tree_from_handle(tree) }.context_is_valid(context)
-}
-
/// # Safety
///
/// `tree` must be a live retained tree handle. Every node slot, live or dead.
@@ -350,31 +311,6 @@ pub unsafe extern "C" fn world_transforms_destroy(world: *mut c_void) {
drop(unsafe { Box::from_raw(world.cast::<crate::visual_context::WorldTransforms>()) });
}
-/// # Safety
-///
-/// `tree` must be a live retained tree handle, `world` a live handle made from it, and `out_local_point` must be
-/// writable.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_transform_point_for_hit_test(
- tree: *const c_void,
- world: *const c_void,
- context: crate::display_list::commands::ContextRef,
- screen_point: libgfx_rust::FloatPoint,
- respect_clip: bool,
- out_local_point: *mut libgfx_rust::FloatPoint,
-) -> bool {
- let (tree, world) = unsafe { (tree_from_handle(tree), world_transforms_from_handle(world)) };
- let clip_behavior = crate::visual_context::ClipBehavior::from_respect_clip(respect_clip);
- match tree.transform_point_for_hit_test(world, context, screen_point, clip_behavior) {
- Some(local_point) => {
- // SAFETY: The caller guarantees `out_local_point` is writable.
- unsafe { *out_local_point = local_point };
- true
- }
- None => false,
- }
-}
-
fn include_visual_viewport_transform_from(include: bool) -> crate::visual_context::IncludeVisualViewportTransform {
if include {
crate::visual_context::IncludeVisualViewportTransform::Yes
@@ -383,24 +319,6 @@ fn include_visual_viewport_transform_from(include: bool) -> crate::visual_contex
}
}
-/// # Safety
-///
-/// `world` must be a live handle from `world_transforms_create`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn world_transforms_transform_rect_to_viewport(
- world: *const c_void,
- spatial: SpatialNodeIndex,
- rect: libgfx_rust::FloatRect,
- include_visual_viewport_transform: bool,
- out: &mut libgfx_rust::FloatRect,
-) {
- *out = unsafe { world_transforms_from_handle(world) }.transform_rect_to_viewport(
- spatial,
- rect,
- include_visual_viewport_transform_from(include_visual_viewport_transform),
- );
-}
-
/// # Safety
///
/// `world` must be a live handle from `world_transforms_create`.
@@ -420,70 +338,12 @@ pub unsafe extern "C" fn world_transforms_accumulated_matrix(
world: *const c_void,
spatial: SpatialNodeIndex,
include_visual_viewport_transform: bool,
-) -> libgfx_rust::FloatMatrix4x4 {
- unsafe { world_transforms_from_handle(world) }.to_viewport_matrix(
+ matrix: &mut libgfx_rust::FloatMatrix4x4,
+) {
+ *matrix = unsafe { world_transforms_from_handle(world) }.to_viewport_matrix(
spatial,
include_visual_viewport_transform_from(include_visual_viewport_transform),
- )
-}
-
-/// # Safety
-///
-/// `tree` must be a live retained tree handle; `scroll_offsets` must address `scroll_offsets_len`
-/// points, and `push` is called synchronously with `sink` for every sticky node's resolved entry.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_resolve_sticky_offsets(
- tree: *const c_void,
- scroll_offsets: *const libgfx_rust::FloatPoint,
- scroll_offsets_len: usize,
- sink: *mut c_void,
- push: unsafe extern "C" fn(*mut c_void, SpatialNodeIndex, libgfx_rust::FloatPoint),
-) {
- let resolved_sticky_entries = {
- let tree = unsafe { tree_from_handle(tree) };
- // SAFETY: The caller guarantees the offsets address `scroll_offsets_len` points, and the
- // borrow ends before the sink may grow the same storage.
- let scroll_offsets = unsafe { ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len) };
- tree.resolve_sticky_offsets(scroll_offsets)
- };
- for (node_index, offset) in resolved_sticky_entries {
- // SAFETY: The C++ sink records the entry synchronously.
- unsafe { push(sink, node_index, offset) };
- }
-}
-
-/// # Safety
-///
-/// `tree` must be a live retained tree handle.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_visual_viewport_transform(
- tree: *const c_void,
- out: &mut crate::host::FfiVisualViewportTransform,
-) {
- let tree = unsafe { tree_from_handle(tree) };
- let crate::visual_context::SpatialData::Transform(transform) =
- &tree.spatial_nodes[crate::display_list::commands::VISUAL_VIEWPORT_NODE_INDEX.0 as usize].data
- else {
- unreachable!("the visual viewport node is a transform");
- };
- *out = crate::host::FfiVisualViewportTransform {
- matrix: transform.matrix,
- origin: transform.origin,
- };
-}
-
-/// # Safety
-///
-/// `tree` must be a live retained tree handle. Returns a retained handle to a copy of the tree whose
-/// visual viewport node carries the given transform; the copy keeps the structural epoch.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_with_visual_viewport_transform(
- tree: *const c_void,
- transform: crate::host::FfiVisualViewportTransform,
-) -> *const c_void {
- let mut copy = unsafe { tree_from_handle(tree) }.clone();
- copy.set_visual_viewport_matrix_and_origin(transform.matrix, transform.origin);
- std::sync::Arc::into_raw(std::sync::Arc::new(copy)).cast()
+ );
}
/// # Safety
@@ -508,34 +368,6 @@ pub unsafe extern "C" fn visual_context_tree_has_visual_animations(tree: *const
unsafe { tree_from_handle(tree) }.has_visual_animations()
}
-/// # Safety
-///
-/// `tree` must be a live retained tree handle.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_has_active_visual_animation_at(
- tree: *const c_void,
- sample_time_ns: i64,
-) -> bool {
- unsafe { tree_from_handle(tree) }.has_active_visual_animation_at(sample_time_ns)
-}
-
-/// # Safety
-///
-/// `tree` must be a live retained tree handle, and `scroll_offsets` must address `scroll_offsets_len` points.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_running_transform_animation_covers_point(
- tree: *const c_void,
- sample_time_ns: i64,
- screen_point: libgfx_rust::FloatPoint,
- scroll_offsets: *const libgfx_rust::FloatPoint,
- scroll_offsets_len: usize,
-) -> bool {
- let tree = unsafe { tree_from_handle(tree) };
- // SAFETY: The caller guarantees the offsets address `scroll_offsets_len` points.
- let scroll_offsets = unsafe { ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len) };
- tree.running_transform_animation_covers_point(sample_time_ns, screen_point, scroll_offsets)
-}
-
/// # Safety
///
/// `tree` must be a live retained tree handle.
@@ -546,22 +378,6 @@ pub unsafe extern "C" fn visual_context_tree_visual_animation_summary(
unsafe { tree_from_handle(tree) }.visual_animation_summary()
}
-/// # Safety
-///
-/// `tree` must be a live retained tree handle and `out_flags` must address one writable flag per
-/// spatial node (`flag_count` of them).
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_mark_spatial_subtrees_of_transform_animations(
- tree: *const c_void,
- out_flags: *mut bool,
- flag_count: usize,
-) {
- let in_subtree = unsafe { tree_from_handle(tree) }.spatial_nodes_in_subtrees_of_transform_animations();
- assert_eq!(in_subtree.len(), flag_count);
- // SAFETY: The caller guarantees `out_flags` addresses `flag_count` writable flags.
- unsafe { std::ptr::copy_nonoverlapping(in_subtree.as_ptr(), out_flags, flag_count) };
-}
-
/// # Safety
///
/// `tree` must be a live retained tree handle and `color` must point to writable storage.
@@ -634,109 +450,6 @@ pub(super) unsafe fn test_builder_tree<'a>(builder: *mut c_void) -> &'a mut crat
unsafe { &mut *builder.cast::<crate::visual_context::VisualContextTree>() }
}
-/// # Safety
-///
-/// `builder` must be a live handle from `visual_context_tree_test_builder_create`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_test_builder_append_transform(
- builder: *mut c_void,
- parent: u32,
- matrix: libgfx_rust::FloatMatrix4x4,
- origin: libgfx_rust::FloatPoint,
-) -> u32 {
- let tree = unsafe { test_builder_tree(builder) };
- tree.append_spatial(
- crate::visual_context::SpatialData::Transform(crate::visual_context::TransformData {
- matrix,
- origin,
- sorting_context_root_index: None,
- flattens_inherited_transform: false,
- role: crate::visual_context::TransformDataRole::CssTransform,
- synthetic_plane: false,
- establishes_sorting_context: false,
- bounds: libgfx_rust::FloatRect::default(),
- }),
- SpatialNodeIndex(parent),
- )
- .0
-}
-
-/// # Safety
-///
-/// `builder` must be a live handle from `visual_context_tree_test_builder_create`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_test_builder_append_scroll(builder: *mut c_void, parent: u32) -> u32 {
- let tree = unsafe { test_builder_tree(builder) };
- tree.append_spatial(
- crate::visual_context::SpatialData::Scroll(crate::visual_context::ScrollData {
- state_slot: crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT,
- owner_paintable: NodeSlotId::INVALID,
- }),
- SpatialNodeIndex(parent),
- )
- .0
-}
-
-/// # Safety
-///
-/// `builder` must be a live handle from `visual_context_tree_test_builder_create`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_test_builder_append_sticky(
- builder: *mut c_void,
- parent: u32,
- constraints: crate::host::FfiTestStickyConstraints,
-) -> u32 {
- let tree = unsafe { test_builder_tree(builder) };
- let inset = |value: crate::display_list::commands::OptionalF32| value.has_value.then_some(value.value);
- tree.append_spatial(
- crate::visual_context::SpatialData::Sticky(crate::visual_context::StickyData {
- scroller: SpatialNodeIndex(constraints.scroller),
- parent_sticky: constraints
- .has_parent_sticky
- .then_some(SpatialNodeIndex(constraints.parent_sticky)),
- position_relative_to_scroller: constraints.position_relative_to_scroller,
- border_box_size: constraints.border_box_size,
- scrollport_size: constraints.scrollport_size,
- containing_block_region: constraints.containing_block_region,
- needs_parent_offset_adjustment: constraints.needs_parent_offset_adjustment,
- non_scrolling_scroll_container: NodeSlotId::INVALID,
- inset_top: inset(constraints.inset_top),
- inset_right: inset(constraints.inset_right),
- inset_bottom: inset(constraints.inset_bottom),
- inset_left: inset(constraints.inset_left),
- state_slot: crate::visual_context::scroll_state::NO_SCROLL_STATE_SLOT,
- owner_paintable: NodeSlotId::INVALID,
- }),
- SpatialNodeIndex(parent),
- )
- .0
-}
-
-/// # Safety
-///
-/// `builder` must be a live handle from `visual_context_tree_test_builder_create`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_test_builder_append_clip(
- builder: *mut c_void,
- parent_clip: u32,
- spatial: u32,
- rect: libgfx_rust::FloatRect,
- corner_radii: libgfx_rust::CornerRadii,
- mode: crate::visual_context::ClipMode,
-) -> u32 {
- let tree = unsafe { test_builder_tree(builder) };
- tree.append_clip(
- crate::visual_context::ClipNodeData::Rect(crate::visual_context::ClipData {
- rect,
- corner_radii,
- mode,
- }),
- ClipNodeIndex(parent_clip),
- SpatialNodeIndex(spatial),
- )
- .0
-}
-
/// # Safety
///
/// `builder` must be a live handle from `visual_context_tree_test_builder_create`, consumed by this
@@ -761,6 +474,58 @@ pub unsafe extern "C" fn visual_context_tree_test_builder_destroy(builder: *mut
drop(unsafe { Box::from_raw(builder.cast::<crate::visual_context::VisualContextTree>()) });
}
+#[unsafe(no_mangle)]
+pub extern "C" fn smooth_scroll_animation_create(
+ start_offset: FloatPoint,
+ destination_offset: FloatPoint,
+ pixels_per_css_pixel: f64,
+ kind: ScrollAnimationKind,
+) -> *mut SmoothScrollAnimation {
+ Box::into_raw(Box::new(SmoothScrollAnimation::new(
+ start_offset,
+ destination_offset,
+ pixels_per_css_pixel,
+ kind,
+ )))
+}
+
+/// # Safety
+///
+/// `animation` must be null or a handle from `smooth_scroll_animation_create` that nothing uses afterwards.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn smooth_scroll_animation_destroy(animation: *mut SmoothScrollAnimation) {
+ if animation.is_null() {
+ return;
+ }
+ // SAFETY: The caller hands over the animation the create call returned.
+ drop(unsafe { Box::from_raw(animation) });
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn smooth_scroll_animation_kind(animation: &SmoothScrollAnimation) -> ScrollAnimationKind {
+ animation.kind()
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn smooth_scroll_animation_sample(
+ animation: &SmoothScrollAnimation,
+ elapsed_nanoseconds: i64,
+ offset: &mut FloatPoint,
+) -> bool {
+ let sample = animation.sample(Duration::from_nanoseconds(elapsed_nanoseconds));
+ *offset = sample.offset;
+ sample.complete
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn smooth_scroll_animation_retarget(
+ animation: &mut SmoothScrollAnimation,
+ destination_offset: FloatPoint,
+ elapsed_nanoseconds: i64,
+) {
+ animation.retarget(destination_offset, Duration::from_nanoseconds(elapsed_nanoseconds));
+}
+
/// A C++ display list as the scroll logic takes it: its tape, and what travels beside the tape that the logic reads.
#[repr(C)]
pub struct FfiDisplayList<'a> {
@@ -803,3 +568,139 @@ pub unsafe fn tree_sharing_handle(visual_context_tree: *const c_void) -> Accumul
Arc::from_raw(tree)
})
}
+
+const ENCODED_IN_THIS_PROCESS: &str = "a value this process encoded for itself decodes";
+
+/// The scrolling state of no display list is the empty one.
+///
+/// # Safety
+///
+/// The storage of `display_list` must be a live display list storage handle. `receive` must copy the UTF-8 bytes it
+/// keeps synchronously.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn recorded_display_list_async_scrolling_state_json(
+ display_list: Option<&FfiDisplayList<'_>>,
+ receiver: *mut c_void,
+ receive: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),
+) {
+ let state = match display_list {
+ None => crate::scrolling::AsyncScrollingState::default(),
+ Some(display_list) => {
+ // SAFETY: The caller lends a live storage handle.
+ let display_list = unsafe { display_list.share() }.expect(ENCODED_IN_THIS_PROCESS);
+ crate::scrolling::async_scrolling_state_from_display_list(&display_list)
+ }
+ };
+ let json = crate::scrolling::async_scrolling_state_to_json(&state);
+ // SAFETY: The caller copies what it keeps of the JSON synchronously.
+ unsafe { receive(receiver, ak::Span::new(json.as_bytes())) };
+}
+
+/// The scroll tree of the display list the document last recorded, as the compositor builds it once the list reaches
+/// it.
+///
+/// # Safety
+///
+/// The storage of `display_list` and `visual_context_tree` must be live handles.
+unsafe fn recorded_scroll_tree_of(
+ display_list: &FfiDisplayList<'_>,
+ visual_context_tree: *const c_void,
+ scroll_state_snapshot: EncodedValue<'_>,
+ newest_wheel_event_listener_state_generation: u64,
+) -> (
+ crate::scrolling::AsyncScrollTree,
+ AccumulatedVisualContextTree,
+ crate::scrolling::WheelRoutingAdmission,
+) {
+ // SAFETY: The caller lends live storage and tree handles.
+ let (display_list, visual_context_tree) = unsafe {
+ (
+ display_list.share().expect(ENCODED_IN_THIS_PROCESS),
+ tree_sharing_handle(visual_context_tree),
+ )
+ };
+ let mut snapshot = scroll_state_snapshot
+ .decode::<crate::scrolling::ScrollStateSnapshot>()
+ .expect(ENCODED_IN_THIS_PROCESS);
+ snapshot.set_node_count(visual_context_tree.spatial_node_count());
+ let async_scrolling_state = crate::scrolling::async_scrolling_state_from_display_list(&display_list);
+ let admission = crate::scrolling::wheel_routing_admission_for_with_generation(
+ &async_scrolling_state,
+ newest_wheel_event_listener_state_generation,
+ );
+ let mut scroll_tree = crate::scrolling::AsyncScrollTree::default();
+ scroll_tree.set_state(async_scrolling_state);
+ scroll_tree.rebuild_wheel_hit_test_targets(Some(&display_list), Some(&visual_context_tree), &snapshot);
+ (scroll_tree, visual_context_tree, admission)
+}
+
+/// Where the first step of a wheel gesture goes, as `Compositing::FirstWheelStepRouteForTesting` holds it.
+#[repr(C)]
+pub struct FfiFirstWheelStepRouteForTesting {
+ pub decision: InputRoutingDecision,
+ pub has_scroller: bool,
+ pub scroller_node_id: i64,
+ pub scroller_kind: AsyncScrollNodeKind,
+ pub scroller_pseudo_element_type: u8,
+ pub has_document_id: bool,
+ pub document_id: i64,
+}
+
+/// # Safety
+///
+/// The storage of `display_list` and `visual_context_tree` must be live handles.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn recorded_display_list_route_first_wheel_step(
+ display_list: &FfiDisplayList<'_>,
+ visual_context_tree: *const c_void,
+ scroll_state_snapshot: EncodedValue<'_>,
+ newest_wheel_event_listener_state_generation: u64,
+ position: FloatPoint,
+ delta_in_css_pixels: FloatPoint,
+) -> FfiFirstWheelStepRouteForTesting {
+ // SAFETY: The caller lends live handles.
+ let (scroll_tree, visual_context_tree, admission) = unsafe {
+ recorded_scroll_tree_of(
+ display_list,
+ visual_context_tree,
+ scroll_state_snapshot,
+ newest_wheel_event_listener_state_generation,
+ )
+ };
+ let delta = delta_in_css_pixels.scaled(scroll_tree.device_pixels_per_css_pixel() as f32);
+ let first_step = scroll_tree.route_first_wheel_step(
+ admission,
+ &visual_context_tree,
+ position,
+ delta,
+ crate::scrolling::NestedContextRegions::LeaveToMainThread,
+ );
+ let document_id = scroll_tree.document_id();
+ FfiFirstWheelStepRouteForTesting {
+ decision: first_step.decision,
+ has_scroller: first_step.scroller.is_some(),
+ scroller_node_id: first_step.scroller.map_or(0, |scroller| scroller.node_id.0),
+ scroller_kind: first_step
+ .scroller
+ .map_or(AsyncScrollNodeKind::Element, |scroller| scroller.kind),
+ scroller_pseudo_element_type: first_step.scroller.map_or(0, |scroller| scroller.pseudo_element_type),
+ has_document_id: document_id.is_some(),
+ document_id: document_id.map_or(0, |document_id| document_id.0),
+ }
+}
+
+/// # Safety
+///
+/// The storage of `display_list` and `visual_context_tree` must be live handles.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn recorded_display_list_blocks_wheel_event_at(
+ display_list: &FfiDisplayList<'_>,
+ visual_context_tree: *const c_void,
+ scroll_state_snapshot: EncodedValue<'_>,
+ position: FloatPoint,
+) -> bool {
+ // SAFETY: The caller lends live handles.
+ let (scroll_tree, visual_context_tree, _) =
+ unsafe { recorded_scroll_tree_of(display_list, visual_context_tree, scroll_state_snapshot, 0) };
+ scroll_tree.blocks_wheel_event_at_position(&visual_context_tree, position)
+}
diff --git a/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs b/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs
index 1598a20b45a..7b03910fd27 100644
--- a/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs
@@ -7,8 +7,7 @@
//! The plain FFI types the visual context tree hands across the C++ boundary on both sides of the
//! compositor process boundary.
-use crate::display_list::commands::OptionalF32;
-use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, FloatSize};
+use libgfx_rust::{FloatMatrix4x4, FloatPoint};
#[derive(Clone, Copy, Debug)]
#[repr(C)]
@@ -101,20 +100,3 @@ pub struct FfiAnimatedContentViewportEffect {
pub may_affect_viewport: bool,
pub stable_until_scene_changes: bool,
}
-
-#[derive(Clone, Copy, Debug)]
-#[repr(C)]
-pub struct FfiTestStickyConstraints {
- pub scroller: u32,
- pub has_parent_sticky: bool,
- pub parent_sticky: u32,
- pub position_relative_to_scroller: FloatPoint,
- pub border_box_size: FloatSize,
- pub scrollport_size: FloatSize,
- pub containing_block_region: FloatRect,
- pub needs_parent_offset_adjustment: bool,
- pub inset_top: OptionalF32,
- pub inset_right: OptionalF32,
- pub inset_bottom: OptionalF32,
- pub inset_left: OptionalF32,
-}
diff --git a/Libraries/LibCompositing/Scrolling/AsyncScrollTree.cpp b/Libraries/LibCompositing/Scrolling/AsyncScrollTree.cpp
deleted file mode 100644
index 2a0e9555713..00000000000
--- a/Libraries/LibCompositing/Scrolling/AsyncScrollTree.cpp
+++ /dev/null
@@ -1,652 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCompositing/DisplayList/DisplayList.h>
-#include <LibCompositing/Scrolling/AsyncScrollTree.h>
-
-#include <AK/Debug.h>
-
-namespace Compositing {
-
-void AsyncScrollTree::set_state(AsyncScrollingState&& state)
-{
- m_document_id = state.document_id;
- m_scroll_nodes = move(state.scroll_nodes);
- m_snap_containers = move(state.snap_containers);
- m_device_pixels_per_css_pixel = state.device_pixels_per_css_pixel;
- m_wheel_hit_test_regions = move(state.wheel_hit_test_targets);
- m_main_thread_wheel_event_regions = move(state.main_thread_wheel_event_regions);
- m_nested_context_wheel_regions = move(state.nested_context_wheel_regions);
- m_blocking_wheel_event_regions = move(state.blocking_wheel_event_regions);
- m_has_blocking_wheel_event_region_covering_viewport = state.has_blocking_wheel_event_region_covering_viewport;
- m_viewport_keeps_horizontal_scrolls = state.viewport_keeps_horizontal_scrolls;
- m_viewport_keeps_vertical_scrolls = state.viewport_keeps_vertical_scrolls;
- m_cached_wheel_hit_test_targets.clear();
- m_cached_main_thread_wheel_event_targets.clear();
- m_cached_nested_context_wheel_regions.clear();
- m_cached_blocking_wheel_event_targets.clear();
- m_visual_context_tree_structural_epoch.clear();
-}
-
-Web::InputRoutingDecision input_routing_decision_for_first_wheel_step(WheelHitTestOutcome outcome)
-{
- switch (outcome) {
- case WheelHitTestOutcome::FoundScrollTarget:
- return Web::InputRoutingDecision::Latched;
- case WheelHitTestOutcome::NoScrollTarget:
- return Web::InputRoutingDecision::NoScrollTarget;
- case WheelHitTestOutcome::BlockedByMainThreadRegion:
- return Web::InputRoutingDecision::BlockedByMainThreadRegion;
- case WheelHitTestOutcome::BlockedByWheelEventRegion:
- return Web::InputRoutingDecision::BlockedByWheelEventRegion;
- case WheelHitTestOutcome::HitTestTargetsOfAnotherVisualContextTree:
- return Web::InputRoutingDecision::HitTestTargetsOfAnotherVisualContextTree;
- }
- VERIFY_NOT_REACHED();
-}
-
-AsyncScrollNode const* AsyncScrollTree::scroll_node_for_index(Compositing::SpatialNodeIndex scroll_node_index) const
-{
- for (auto const& node : m_scroll_nodes) {
- if (node.scroll_node_index == scroll_node_index)
- return &node;
- }
- return nullptr;
-}
-
-static bool delta_is_mainly_vertical(Gfx::FloatPoint delta)
-{
- return AK::abs(delta.y()) >= AK::abs(delta.x());
-}
-
-// 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.
-static bool node_chains_scroll_to_ancestors(AsyncScrollNode const& node, Gfx::FloatPoint delta)
-{
- return delta_is_mainly_vertical(delta) ? node.chains_scroll_to_ancestors_vertically : node.chains_scroll_to_ancestors_horizontally;
-}
-
-WheelHitTestResult AsyncScrollTree::hit_test_result_for_scroll_node(Compositing::SpatialNodeIndex scroll_node_index, Gfx::FloatPoint delta, Function<Optional<Gfx::FloatPoint>(Web::AsyncScrollNodeStableID)> const& in_flight_destination_for) const
-{
- auto can_take_step = [&](AsyncScrollNode const& node) {
- Optional<Gfx::FloatPoint> in_flight_destination;
- if (in_flight_destination_for)
- in_flight_destination = in_flight_destination_for(node.stable_node_id);
- return can_scroll_node_from_offset_by_delta(node, in_flight_destination.value_or(scroll_offset_for_node(node, m_scroll_state_snapshot)), delta);
- };
-
- for (auto const* node = scroll_node_for_index(scroll_node_index); node;) {
- if (can_take_step(*node))
- return { .outcome = WheelHitTestOutcome::FoundScrollTarget, .scroll_node_index = node->scroll_node_index, .innermost_scroll_node_index = scroll_node_index };
- // 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(*node, delta))
- return { .outcome = WheelHitTestOutcome::NoScrollTarget, .innermost_scroll_node_index = scroll_node_index, .scroll_node_index_keeping_the_scroll = node->scroll_node_index };
- if (!node->parent_scroll_node_index.has_value())
- break;
- node = scroll_node_for_index(*node->parent_scroll_node_index);
- }
- return { .outcome = WheelHitTestOutcome::NoScrollTarget, .innermost_scroll_node_index = scroll_node_index };
-}
-
-Optional<Compositing::SpatialNodeIndex> AsyncScrollTree::outermost_scroll_node_wheel_scrollable_along_main_axis_of(Compositing::SpatialNodeIndex innermost_scroll_node_index, Gfx::FloatPoint delta) const
-{
- Optional<Compositing::SpatialNodeIndex> outermost_scroll_node_index;
- auto scroll_node_index = innermost_scroll_node_index;
- for (size_t remaining_ancestors = m_scroll_nodes.size(); remaining_ancestors > 0; --remaining_ancestors) {
- auto const* node = scroll_node_for_index(scroll_node_index);
- if (!node)
- break;
- if (delta_is_mainly_vertical(delta) ? node->can_be_wheel_scrolled_vertically : node->can_be_wheel_scrolled_horizontally)
- outermost_scroll_node_index = node->scroll_node_index;
- if (!node_chains_scroll_to_ancestors(*node, delta) || !node->parent_scroll_node_index.has_value())
- break;
- scroll_node_index = *node->parent_scroll_node_index;
- }
- return outermost_scroll_node_index;
-}
-
-AsyncSnapContainer const* AsyncScrollTree::snap_container_for_node(Compositing::SpatialNodeIndex scroll_node_index) const
-{
- for (auto const& snap_container : m_snap_containers) {
- if (snap_container.scroll_node_index == scroll_node_index)
- return &snap_container;
- }
- return nullptr;
-}
-
-AsyncScrollNode const* AsyncScrollTree::scroll_node_for_stable_id(Web::AsyncScrollNodeStableID stable_node_id) const
-{
- for (auto const& node : m_scroll_nodes) {
- if (node.stable_node_id == stable_node_id)
- return &node;
- }
- return nullptr;
-}
-
-Gfx::FloatPoint AsyncScrollTree::clamp_scroll_offset_to_node(AsyncScrollNode const& node, Gfx::FloatPoint scroll_offset)
-{
- scroll_offset.set_x(max(node.min_scroll_offset.x(), min(scroll_offset.x(), node.max_scroll_offset.x())));
- scroll_offset.set_y(max(node.min_scroll_offset.y(), min(scroll_offset.y(), node.max_scroll_offset.y())));
- return scroll_offset;
-}
-
-Gfx::FloatPoint AsyncScrollTree::scroll_offset_for_node(AsyncScrollNode const& node, Compositing::ScrollStateSnapshot const& scroll_state_snapshot)
-{
- auto device_offset = scroll_state_snapshot.device_offset_for_index(node.scroll_node_index);
- return { -device_offset.x(), -device_offset.y() };
-}
-
-bool AsyncScrollTree::can_scroll_node_by_delta(AsyncScrollNode const& node, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint delta)
-{
- return can_scroll_node_from_offset_by_delta(node, scroll_offset_for_node(node, scroll_state_snapshot), delta);
-}
-
-bool AsyncScrollTree::can_scroll_node_from_offset_by_delta(AsyncScrollNode const& node, Gfx::FloatPoint scroll_offset, Gfx::FloatPoint delta)
-{
- if (node.can_be_wheel_scrolled_horizontally && delta.x() < 0 && scroll_offset.x() > node.min_scroll_offset.x())
- return true;
- if (node.can_be_wheel_scrolled_horizontally && delta.x() > 0 && scroll_offset.x() < node.max_scroll_offset.x())
- return true;
- if (node.can_be_wheel_scrolled_vertically && delta.y() < 0 && scroll_offset.y() > node.min_scroll_offset.y())
- return true;
- if (node.can_be_wheel_scrolled_vertically && delta.y() > 0 && scroll_offset.y() < node.max_scroll_offset.y())
- return true;
- return false;
-}
-
-Optional<Compositing::SpatialNodeIndex> AsyncScrollTree::scrollable_ancestor_for_node(Compositing::SpatialNodeIndex scroll_node_index, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint delta) const
-{
- auto const* node = scroll_node_for_index(scroll_node_index);
- if (!node)
- return {};
-
- while (node_chains_scroll_to_ancestors(*node, delta) && node->parent_scroll_node_index.has_value()) {
- node = scroll_node_for_index(*node->parent_scroll_node_index);
- if (!node)
- return {};
- if (can_scroll_node_by_delta(*node, scroll_state_snapshot, delta))
- return node->scroll_node_index;
- }
- return {};
-}
-
-Gfx::FloatPoint AsyncScrollTree::apply_scroll_delta_to_node(AsyncScrollNode const& node, Gfx::FloatPoint delta, Compositing::ScrollStateSnapshot& scroll_state_snapshot)
-{
- auto old_scroll_offset = scroll_offset_for_node(node, scroll_state_snapshot);
- Gfx::FloatPoint wheel_scrollable_delta {
- node.can_be_wheel_scrolled_horizontally ? delta.x() : 0,
- node.can_be_wheel_scrolled_vertically ? delta.y() : 0,
- };
- auto new_scroll_offset = clamp_scroll_offset_to_node(node, old_scroll_offset.translated(wheel_scrollable_delta));
- if (new_scroll_offset == old_scroll_offset) {
- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Async scroll node {} did not move for delta {},{} (offset={},{} max={},{})",
- node.scroll_node_index.value(), delta.x(), delta.y(), old_scroll_offset.x(), old_scroll_offset.y(), node.max_scroll_offset.x(), node.max_scroll_offset.y());
- return delta;
- }
-
- scroll_state_snapshot.set_device_offset_for_index(node.scroll_node_index, { -new_scroll_offset.x(), -new_scroll_offset.y() });
-
- Gfx::FloatPoint consumed_delta {
- new_scroll_offset.x() - old_scroll_offset.x(),
- new_scroll_offset.y() - old_scroll_offset.y()
- };
- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Async scroll node {} moved from {},{} to {},{} (consumed={},{} remaining={},{})",
- node.scroll_node_index.value(),
- old_scroll_offset.x(), old_scroll_offset.y(),
- new_scroll_offset.x(), new_scroll_offset.y(),
- consumed_delta.x(), consumed_delta.y(),
- delta.x() - consumed_delta.x(), delta.y() - consumed_delta.y());
- return {
- delta.x() - consumed_delta.x(),
- delta.y() - consumed_delta.y()
- };
-}
-
-Optional<AsyncScrollOffset> AsyncScrollTree::apply_scroll_delta(Compositing::SpatialNodeIndex scroll_node_index, Gfx::FloatPoint delta, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot& scroll_state_snapshot, ScrollChaining scroll_chaining)
-{
- // 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 (size_t remaining_handoffs = m_scroll_nodes.size(); remaining_handoffs > 0 && !delta.is_zero(); --remaining_handoffs) {
- auto const* node = scroll_node_for_index(scroll_node_index);
- if (!node)
- break;
-
- auto remaining_delta = apply_scroll_delta_to_node(*node, delta, scroll_state_snapshot);
- if (remaining_delta != delta) {
- Compositing::resolve_sticky_offsets(visual_context_tree, scroll_state_snapshot);
- return AsyncScrollOffset {
- .stable_node_id = node->stable_node_id,
- .compositor_scroll_offset = scroll_offset_for_node(*node, scroll_state_snapshot),
- .unadopted_scroll_delta = delta - remaining_delta,
- .last_relative_scroll_delta = {},
- .visual_viewport_scale = {},
- .applied_scroll_request_id = 0,
- .user_input_scroll_count = 0,
- .context_user_input_scroll_count = 0,
- };
- }
-
- if (scroll_chaining == ScrollChaining::None)
- break;
- auto ancestor_scroll_node_index = scrollable_ancestor_for_node(scroll_node_index, scroll_state_snapshot, delta);
- if (!ancestor_scroll_node_index.has_value())
- break;
- scroll_node_index = *ancestor_scroll_node_index;
- }
-
- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Async scroll tree did not scroll any node for delta {},{}",
- delta.x(), delta.y());
- return {};
-}
-
-Optional<WheelScrollTarget> AsyncScrollTree::select_wheel_scroll_target(Compositing::SpatialNodeIndex scroll_node_index, Gfx::FloatPoint delta, Compositing::ScrollStateSnapshot const& scroll_state_snapshot, Function<Optional<Gfx::FloatPoint>(Web::AsyncScrollNodeStableID)> const& in_flight_destination_for, ScrollChaining scroll_chaining) const
-{
- // 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 (size_t remaining_handoffs = m_scroll_nodes.size(); remaining_handoffs > 0; --remaining_handoffs) {
- auto const* node = scroll_node_for_index(scroll_node_index);
- if (!node)
- return {};
-
- auto start_offset = in_flight_destination_for(node->stable_node_id).value_or(scroll_offset_for_node(*node, scroll_state_snapshot));
- Gfx::FloatPoint wheel_scrollable_delta {
- node->can_be_wheel_scrolled_horizontally ? delta.x() : 0,
- node->can_be_wheel_scrolled_vertically ? delta.y() : 0,
- };
- auto destination_offset = clamp_scroll_offset_to_node(*node, start_offset + wheel_scrollable_delta);
- if (destination_offset != start_offset) {
- return WheelScrollTarget {
- .stable_node_id = node->stable_node_id,
- .current_offset = scroll_offset_for_node(*node, scroll_state_snapshot),
- .start_offset = start_offset,
- .destination_offset = destination_offset,
- };
- }
-
- if (scroll_chaining == ScrollChaining::None || !node_chains_scroll_to_ancestors(*node, delta) || !node->parent_scroll_node_index.has_value())
- return {};
- scroll_node_index = *node->parent_scroll_node_index;
- }
- return {};
-}
-
-void AsyncScrollTree::rebuild_wheel_hit_test_targets(RefPtr<Compositing::DisplayList const> const& display_list, Compositing::AccumulatedVisualContextTree const* visual_context_tree, Compositing::ScrollStateSnapshot const& scroll_state_snapshot)
-{
- m_cached_wheel_hit_test_targets.clear();
- m_cached_main_thread_wheel_event_targets.clear();
- m_cached_nested_context_wheel_regions.clear();
- m_cached_blocking_wheel_event_targets.clear();
- m_visual_context_tree_structural_epoch.clear();
- m_scroll_state_snapshot = scroll_state_snapshot;
- if (!display_list || !visual_context_tree)
- return;
-
- VERIFY(display_list->compatible_visual_context_tree_structural_epoch() == visual_context_tree->structural_epoch());
- m_visual_context_tree_structural_epoch = visual_context_tree->structural_epoch();
-
- auto context_is_valid = [&](Compositing::ContextRef context) {
- return visual_context_tree->context_is_valid(context);
- };
-
- auto spatial_context_has_visual_animation = visual_context_tree->spatial_nodes_in_subtrees_of_transform_animations();
- auto viewport_rect_for_context = [&](Compositing::ContextRef context, Gfx::FloatRect const& rect) -> Optional<Gfx::FloatRect> {
- if (spatial_context_has_visual_animation[context.spatial.value()])
- return {};
- return visual_context_tree->transform_rect_to_viewport(context.spatial, rect, scroll_state_snapshot);
- };
-
- m_cached_wheel_hit_test_targets.ensure_capacity(m_wheel_hit_test_regions.size());
- for (auto const& target : m_wheel_hit_test_regions) {
- if (!context_is_valid(target.context))
- continue;
- m_cached_wheel_hit_test_targets.append({
- .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,
- });
- }
-
- m_cached_main_thread_wheel_event_targets.ensure_capacity(m_main_thread_wheel_event_regions.size());
- for (auto const& region : m_main_thread_wheel_event_regions) {
- if (!context_is_valid(region.context))
- continue;
- m_cached_main_thread_wheel_event_targets.append({
- .context = region.context,
- .rect = region.rect,
- .viewport_rect = viewport_rect_for_context(region.context, region.rect),
- });
- }
-
- m_cached_nested_context_wheel_regions.ensure_capacity(m_nested_context_wheel_regions.size());
- for (auto const& region : m_nested_context_wheel_regions) {
- if (!context_is_valid(region.context))
- continue;
- m_cached_nested_context_wheel_regions.append({
- .region = region,
- .viewport_rect = viewport_rect_for_context(region.context, region.rect),
- });
- }
-
- for (auto const& region : m_blocking_wheel_event_regions) {
- // Keep invalid blockers so hit testing fails closed when their extent cannot be determined.
- m_cached_blocking_wheel_event_targets.append({
- .context = region.context,
- .rect = region.rect,
- .viewport_rect = context_is_valid(region.context) ? viewport_rect_for_context(region.context, region.rect) : Optional<Gfx::FloatRect> {},
- });
- }
-}
-
-static bool rounded_rect_contains_point(Gfx::FloatRect const& rect, Gfx::CornerRadii const& corner_radii, Gfx::FloatPoint position_in_context)
-{
- if (!rect.contains(position_in_context))
- return false;
- if (!corner_radii.has_any_radius())
- return true;
- return corner_radii.contains(position_in_context.to_type<int>(), rect.to_type<int>());
-}
-
-static bool wheel_hit_test_target_contains_point(CachedWheelHitTestTarget const& target, Gfx::FloatPoint position_in_context)
-{
- return rounded_rect_contains_point(target.rect, target.corner_radii, position_in_context);
-}
-
-Optional<Gfx::FloatPoint> AsyncScrollTree::scroll_offset_for_node(Compositing::SpatialNodeIndex scroll_node_index, Compositing::ScrollStateSnapshot const& scroll_state_snapshot) const
-{
- if (auto const* node = scroll_node_for_index(scroll_node_index))
- return scroll_offset_for_node(*node, scroll_state_snapshot);
- return {};
-}
-
-Web::CSSPixelPoint AsyncScrollTree::css_pixels_from_device_offset(Gfx::FloatPoint device_offset) const
-{
- return {
- Web::CSSPixels { device_offset.x() / m_device_pixels_per_css_pixel },
- Web::CSSPixels { device_offset.y() / m_device_pixels_per_css_pixel },
- };
-}
-
-Gfx::FloatPoint AsyncScrollTree::device_offset_from_css_pixels(Web::CSSPixelPoint offset) const
-{
- return {
- static_cast<float>(offset.x().to_double() * m_device_pixels_per_css_pixel),
- static_cast<float>(offset.y().to_double() * m_device_pixels_per_css_pixel),
- };
-}
-
-Optional<Web::CSSPixelPoint> AsyncScrollTree::css_scroll_offset_for_node(Compositing::SpatialNodeIndex scroll_node_index, Compositing::ScrollStateSnapshot const& scroll_state_snapshot) const
-{
- return scroll_offset_for_node(scroll_node_index, scroll_state_snapshot).map([&](auto device_offset) { return css_pixels_from_device_offset(device_offset); });
-}
-
-Web::CSSPixelPoint AsyncScrollTree::css_scroll_offset_for_node(AsyncScrollNode const& node, Compositing::ScrollStateSnapshot const& scroll_state_snapshot) const
-{
- return css_pixels_from_device_offset(scroll_offset_for_node(node, scroll_state_snapshot));
-}
-
-Optional<Compositing::SpatialNodeIndex> AsyncScrollTree::viewport_scroll_node_index() const
-{
- for (auto const& node : m_scroll_nodes) {
- if (node.is_viewport)
- return node.scroll_node_index;
- }
- return {};
-}
-
-Optional<Compositing::SpatialNodeIndex> AsyncScrollTree::scroll_node_index_for_stable_id(Web::AsyncScrollNodeStableID stable_node_id) const
-{
- if (auto const* node = scroll_node_for_stable_id(stable_node_id))
- return node->scroll_node_index;
- return {};
-}
-
-bool AsyncScrollTree::blocks_wheel_event_at_position(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position) const
-{
- if (m_has_blocking_wheel_event_region_covering_viewport || !has_wheel_hit_test_targets_for(visual_context_tree))
- return true;
-
- for (auto const& target : m_cached_blocking_wheel_event_targets) {
- if (!visual_context_tree.context_is_valid(target.context))
- return true;
- if (target.viewport_rect.has_value() && !target.viewport_rect->contains(position))
- continue;
- auto position_in_context = visual_context_tree.transform_point_for_hit_test(target.context, position, m_scroll_state_snapshot);
- if (position_in_context.has_value() && target.rect.contains(*position_in_context))
- return true;
- }
- return false;
-}
-
-bool AsyncScrollTree::main_thread_wheel_event_region_contains(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position) const
-{
- for (auto const& target : m_cached_main_thread_wheel_event_targets) {
- if (target.viewport_rect.has_value() && !target.viewport_rect->contains(position))
- continue;
- if (!visual_context_tree.context_is_valid(target.context))
- continue;
- auto position_in_context = visual_context_tree.transform_point_for_hit_test(target.context, position, m_scroll_state_snapshot);
- if (position_in_context.has_value() && target.rect.contains(*position_in_context))
- return true;
- }
- return false;
-}
-
-Optional<AsyncScrollTree::NestedContextWheelRegionHit> AsyncScrollTree::topmost_nested_context_wheel_region_at(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position) const
-{
- for (auto const& cached_region : m_cached_nested_context_wheel_regions.in_reverse()) {
- auto const& region = cached_region.region;
- if (cached_region.viewport_rect.has_value() && !cached_region.viewport_rect->contains(position))
- continue;
- if (!visual_context_tree.context_is_valid(region.context))
- continue;
- auto position_in_context = visual_context_tree.transform_point_for_hit_test(region.context, position, m_scroll_state_snapshot);
- if (position_in_context.has_value() && rounded_rect_contains_point(region.rect, region.corner_radii, *position_in_context))
- return NestedContextWheelRegionHit { region, *position_in_context };
- }
- return {};
-}
-
-static NestedContextHit nested_context_hit_in_region(NestedContextWheelRegion const& region, Gfx::FloatPoint position_in_context)
-{
- return NestedContextHit {
- .child_context_id = region.child_context_id,
- .position_in_content_box = position_in_context - region.rect.location(),
- .content_box_size = region.rect.size(),
- .paint_order_index = region.paint_order_index,
- };
-}
-
-Optional<NestedContextHit> AsyncScrollTree::nested_context_at(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position) const
-{
- if (m_visual_context_tree_structural_epoch != visual_context_tree.structural_epoch())
- return {};
- auto hit = topmost_nested_context_wheel_region_at(visual_context_tree, position);
- if (!hit.has_value() || is_covered_by_hit_test_target_painted_after(hit->region.paint_order_index, visual_context_tree, position))
- return {};
- return nested_context_hit_in_region(hit->region, hit->position_in_context);
-}
-
-Optional<NestedContextHit> AsyncScrollTree::nested_context_for_wheel_at(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position) const
-{
- if (m_visual_context_tree_structural_epoch != visual_context_tree.structural_epoch())
- return {};
- if (main_thread_wheel_event_region_contains(visual_context_tree, position))
- return {};
- return nested_context_at(visual_context_tree, position);
-}
-
-Optional<NestedContextHit> AsyncScrollTree::position_in_content_of_nested_context(Web::CompositorContextId child_context_id, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position) const
-{
- if (m_visual_context_tree_structural_epoch != visual_context_tree.structural_epoch())
- return {};
- for (auto const& cached_region : m_cached_nested_context_wheel_regions.in_reverse()) {
- auto const& region = cached_region.region;
- if (region.child_context_id != child_context_id)
- continue;
- if (!visual_context_tree.context_is_valid(region.context))
- return {};
- auto position_in_context = visual_context_tree.transform_point_for_hit_test(region.context, position, m_scroll_state_snapshot, Compositing::AccumulatedVisualContextTree::ClipBehavior::Ignore);
- if (!position_in_context.has_value())
- return {};
- return nested_context_hit_in_region(region, *position_in_context);
- }
- return {};
-}
-
-Optional<Gfx::FloatPoint> AsyncScrollTree::position_of_nested_context_position(Web::CompositorContextId child_context_id, Gfx::FloatPoint position_in_nested_context, Gfx::FloatSize nested_context_viewport_size, Compositing::AccumulatedVisualContextTree const& visual_context_tree) const
-{
- if (m_visual_context_tree_structural_epoch != visual_context_tree.structural_epoch() || nested_context_viewport_size.is_empty())
- return {};
- for (auto const& cached_region : m_cached_nested_context_wheel_regions.in_reverse()) {
- auto const& region = cached_region.region;
- if (region.child_context_id != child_context_id)
- continue;
- if (!visual_context_tree.context_is_valid(region.context))
- return {};
- // The content box of a nested context is drawn scaled to the size of its viewport.
- Gfx::FloatPoint position_in_content_box {
- position_in_nested_context.x() * region.rect.width() / nested_context_viewport_size.width(),
- position_in_nested_context.y() * region.rect.height() / nested_context_viewport_size.height(),
- };
- Gfx::FloatRect point_in_context { region.rect.location() + position_in_content_box, {} };
- return visual_context_tree.transform_rect_to_viewport(region.context.spatial, point_in_context, m_scroll_state_snapshot).location();
- }
- return {};
-}
-
-WheelHitTestResult AsyncScrollTree::hit_test_scroll_node_for_wheel(Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position, Gfx::FloatPoint delta, Function<Optional<Gfx::FloatPoint>(Web::AsyncScrollNodeStableID)> const& in_flight_destination_for, WheelStepDispatch wheel_step_dispatch, NestedContextRegions nested_context_regions) const
-{
- if (m_visual_context_tree_structural_epoch != visual_context_tree.structural_epoch())
- return { .outcome = WheelHitTestOutcome::HitTestTargetsOfAnotherVisualContextTree };
-
- auto context_is_valid = [&](Compositing::ContextRef context) {
- return 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.
- bool page_has_yet_to_see_the_step = wheel_step_dispatch == WheelStepDispatch::NotYetDispatched;
- if (page_has_yet_to_see_the_step && m_has_blocking_wheel_event_region_covering_viewport)
- return { .outcome = WheelHitTestOutcome::BlockedByWheelEventRegion };
-
- if (page_has_yet_to_see_the_step && main_thread_wheel_event_region_contains(visual_context_tree, position))
- return { .outcome = WheelHitTestOutcome::BlockedByMainThreadRegion };
- if (nested_context_regions == NestedContextRegions::LeaveToMainThread && topmost_nested_context_wheel_region_at(visual_context_tree, position).has_value())
- return { .outcome = WheelHitTestOutcome::BlockedByMainThreadRegion };
-
- if (page_has_yet_to_see_the_step && blocks_wheel_event_at_position(visual_context_tree, position))
- return { .outcome = WheelHitTestOutcome::BlockedByWheelEventRegion };
-
- for (auto const& target : m_cached_wheel_hit_test_targets.in_reverse()) {
- if (target.viewport_rect.has_value() && !target.viewport_rect->contains(position))
- continue;
- if (!context_is_valid(target.context))
- continue;
- auto position_in_context = visual_context_tree.transform_point_for_hit_test(target.context, position, m_scroll_state_snapshot);
- if (!position_in_context.has_value() || !wheel_hit_test_target_contains_point(target, *position_in_context))
- continue;
- if (!target.target_scroll_node_index.has_value())
- return { .outcome = WheelHitTestOutcome::NoScrollTarget };
- return hit_test_result_for_scroll_node(*target.target_scroll_node_index, delta, in_flight_destination_for);
- }
-
- auto index_of_viewport_scroll_node = viewport_scroll_node_index();
- if (!index_of_viewport_scroll_node.has_value())
- return { .outcome = WheelHitTestOutcome::NoScrollTarget };
- auto const* viewport_node = scroll_node_for_index(*index_of_viewport_scroll_node);
- if (!viewport_node || !viewport_node->scrollport_rect.to_type<float>().contains(position))
- return { .outcome = WheelHitTestOutcome::NoScrollTarget };
- return hit_test_result_for_scroll_node(*index_of_viewport_scroll_node, delta, in_flight_destination_for);
-}
-
-FirstWheelStepRoute AsyncScrollTree::route_first_wheel_step(WheelRoutingAdmission admission, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position, Gfx::FloatPoint delta, NestedContextRegions nested_context_regions) const
-{
- if (admission != WheelRoutingAdmission::Accepted)
- return { input_routing_decision_for_wheel_step_not_admitted_by(admission) };
- auto scroll_target = hit_test_scroll_node_for_wheel(visual_context_tree, position, delta, {}, WheelStepDispatch::NotYetDispatched, nested_context_regions);
- FirstWheelStepRoute route { input_routing_decision_for_first_wheel_step(scroll_target.outcome) };
- if (scroll_target.scroll_node_index.has_value()) {
- if (auto const* node = scroll_node_for_index(*scroll_target.scroll_node_index))
- route.scroller = node->stable_node_id;
- }
- return route;
-}
-
-bool AsyncScrollTree::is_covered_by_hit_test_target_painted_after(u32 paint_order_index, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Gfx::FloatPoint position) const
-{
- if (m_visual_context_tree_structural_epoch != visual_context_tree.structural_epoch())
- return true;
-
- for (auto const& target : m_cached_wheel_hit_test_targets.in_reverse()) {
- if (target.paint_order_index < paint_order_index)
- break;
- if (target.viewport_rect.has_value() && !target.viewport_rect->contains(position))
- continue;
- if (!visual_context_tree.context_is_valid(target.context))
- continue;
- auto position_in_context = visual_context_tree.transform_point_for_hit_test(target.context, position, m_scroll_state_snapshot);
- if (position_in_context.has_value() && wheel_hit_test_target_contains_point(target, *position_in_context))
- return true;
- }
- return false;
-}
-
-Optional<Compositing::SpatialNodeIndex> AsyncScrollTree::scroll_node_for_keyboard_scroll(Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint delta, Compositing::ScrollStateSnapshot const& scroll_state_snapshot) const
-{
- auto const* node = scroll_node_for_stable_id(stable_node_id);
- if (!node)
- return {};
-
- // Keyboard routing does not depend on pointer or wheel-listener regions.
- if (can_scroll_node_by_delta(*node, scroll_state_snapshot, delta))
- return node->scroll_node_index;
- return scrollable_ancestor_for_node(node->scroll_node_index, scroll_state_snapshot, delta);
-}
-
-Gfx::FloatPoint AsyncScrollTree::clamped_scroll_offset_for_node(Compositing::SpatialNodeIndex scroll_node_index, Gfx::FloatPoint scroll_offset) const
-{
- auto const* node = scroll_node_for_index(scroll_node_index);
- if (!node)
- return scroll_offset;
- return clamp_scroll_offset_to_node(*node, scroll_offset);
-}
-
-bool AsyncScrollTree::scroll_node_is_viewport(Compositing::SpatialNodeIndex scroll_node_index) const
-{
- auto const* node = scroll_node_for_index(scroll_node_index);
- return node && node->is_viewport;
-}
-
-bool AsyncScrollTree::viewport_keeps_scrolls_along_main_axis_of(Gfx::FloatPoint delta) const
-{
- return delta_is_mainly_vertical(delta) ? m_viewport_keeps_vertical_scrolls : m_viewport_keeps_horizontal_scrolls;
-}
-
-Optional<Gfx::FloatPoint> AsyncScrollTree::set_scroll_offset(Compositing::SpatialNodeIndex scroll_node_index, Gfx::FloatPoint scroll_offset, Compositing::AccumulatedVisualContextTree const& visual_context_tree, Compositing::ScrollStateSnapshot& scroll_state_snapshot)
-{
- auto const* node = scroll_node_for_index(scroll_node_index);
- if (!node)
- return {};
-
- auto new_scroll_offset = set_scroll_offset_leaving_sticky_offsets_unresolved(*node, scroll_offset, scroll_state_snapshot);
- Compositing::resolve_sticky_offsets(visual_context_tree, scroll_state_snapshot);
- return new_scroll_offset;
-}
-
-Gfx::FloatPoint AsyncScrollTree::set_scroll_offset_leaving_sticky_offsets_unresolved(AsyncScrollNode const& node, Gfx::FloatPoint scroll_offset, Compositing::ScrollStateSnapshot& scroll_state_snapshot)
-{
- auto new_scroll_offset = clamp_scroll_offset_to_node(node, scroll_offset);
- scroll_state_snapshot.set_device_offset_for_index(node.scroll_node_index, { -new_scroll_offset.x(), -new_scroll_offset.y() });
- return new_scroll_offset;
-}
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/AsyncScrollTree.h b/Libraries/LibCompositing/Scrolling/AsyncScrollTree.h
deleted file mode 100644
index 73e2a31cdaa..00000000000
--- a/Libraries/LibCompositing/Scrolling/AsyncScrollTree.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Function.h>
-#include <AK/Optional.h>
-#include <AK/RefPtr.h>
-#include <AK/Vector.h>
-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>
-#include <LibCompositing/Export.h>
-#include <LibCompositing/Forward.h>
-#include <LibCompositing/Scrolling/AsyncScrollingState.h>
-#include <LibCompositing/Scrolling/ScrollState.h>
-#include <LibCompositing/Types.h>
-#include <LibGfx/CornerRadii.h>
-#include <LibGfx/Point.h>
-#include <LibGfx/Rect.h>
-
-namespace Compositing {
-
-enum class WheelHitTestOutcome : u8 {
- FoundScrollTarget,
- NoScrollTarget,
- BlockedByMainThreadRegion,
- BlockedByWheelEventRegion,
- HitTestTargetsOfAnotherVisualContextTree,
-};
-
-struct WheelHitTestResult {
- WheelHitTestOutcome outcome { WheelHitTestOutcome::NoScrollTarget };
- // Set exactly when the outcome is FoundScrollTarget.
- Optional<Compositing::SpatialNodeIndex> scroll_node_index {};
- // 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.
- Optional<Compositing::SpatialNodeIndex> innermost_scroll_node_index {};
- // 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.
- Optional<Compositing::SpatialNodeIndex> scroll_node_index_keeping_the_scroll {};
-
- bool is_blocked_by_a_region() const
- {
- return outcome == WheelHitTestOutcome::BlockedByMainThreadRegion || outcome == WheelHitTestOutcome::BlockedByWheelEventRegion;
- }
-};
-
-// 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.
-COMPOSITING_API Web::InputRoutingDecision input_routing_decision_for_first_wheel_step(WheelHitTestOutcome);
-
-// Where the first step of a wheel gesture over a position goes, as far as the admission and the hit test decide it.
-struct FirstWheelStepRoute {
- Web::InputRoutingDecision decision;
- Optional<Web::AsyncScrollNodeStableID> scroller {};
-};
-
-struct FirstWheelStepRouteForTesting {
- FirstWheelStepRoute route;
- // The document whose scrolling state decided the route.
- Optional<Web::UniqueNodeID> document_id;
-};
-
-// What the wheel hit test does where a nested context's content is painted.
-enum class NestedContextRegions : u8 {
- // 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.
-struct NestedContextHit {
- Web::CompositorContextId child_context_id;
- // Relative to the origin of the nested context's content box, in the device pixels of the containing context.
- Gfx::FloatPoint position_in_content_box;
- Gfx::FloatSize content_box_size;
- // Where the nested context's content is painted among the other things in the containing context that take
- // pointer input.
- u32 paint_order_index { 0 };
-};
-
-struct WheelScrollTarget {
- Web::AsyncScrollNodeStableID stable_node_id;
- Gfx::FloatPoint current_offset;
- Gfx::FloatPoint start_offset;
- Gfx::FloatPoint destination_offset;
-};
-
-struct CachedWheelHitTestTarget {
- Optional<Compositing::SpatialNodeIndex> target_scroll_node_index;
- Compositing::ContextRef context;
- Gfx::FloatRect rect;
- Gfx::CornerRadii corner_radii;
- Optional<Gfx::FloatRect> viewport_rect;
- u32 paint_order_index { 0 };
-};
-
-struct CachedMainThreadWheelEventTarget {
- Compositing::ContextRef context;
- Gfx::FloatRect rect;
- Optional<Gfx::FloatRect> viewport_rect;
-};
-
-struct CachedNestedContextWheelRegion {
- NestedContextWheelRegion region;
- Optional<Gfx::FloatRect> viewport_rect;
-};
-
-struct CachedBlockingWheelEventTarget {
- Compositing::ContextRef context;
- Gfx::FloatRect rect;
- Optional<Gfx::FloatRect> viewport_rect;
-};
-
-enum class ScrollChaining : u8 {
- ToScrollableAncestors,
- None,
-};
-
-// Mutable compositor-side copy of AsyncScrollingState. Current scroll offsets live in ScrollStateSnapshot; this tree
-// owns scroll node geometry and derived hit-test targets.
-class COMPOSITING_API AsyncScrollTree {
-public:
- void set_state(AsyncScrollingState&&);
-
- void rebuild_wheel_hit_test_targets(RefPtr<Compositing::DisplayList const> const&, Compositing::AccumulatedVisualContextTree const*, Compositing::ScrollStateSnapshot const&);
-
- Optional<Gfx::FloatPoint> scroll_offset_for_node(Compositing::SpatialNodeIndex, Compositing::ScrollStateSnapshot const&) const;
- static Gfx::FloatPoint scroll_offset_for_node(AsyncScrollNode const&, Compositing::ScrollStateSnapshot const&);
- Optional<Web::UniqueNodeID> document_id() const { return m_document_id; }
- Optional<Compositing::SpatialNodeIndex> viewport_scroll_node_index() const;
- Optional<Compositing::SpatialNodeIndex> scroll_node_index_for_stable_id(Web::AsyncScrollNodeStableID) const;
- AsyncScrollNode const* scroll_node_for_index(Compositing::SpatialNodeIndex) const;
- ReadonlySpan<AsyncScrollNode> scroll_nodes() const { return m_scroll_nodes; }
- AsyncSnapContainer const* snap_container_for_node(Compositing::SpatialNodeIndex) const;
-
- // 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.
- double device_pixels_per_css_pixel() const { return m_device_pixels_per_css_pixel; }
- Web::CSSPixelPoint css_pixels_from_device_offset(Gfx::FloatPoint) const;
- Gfx::FloatPoint device_offset_from_css_pixels(Web::CSSPixelPoint) const;
- Optional<Web::CSSPixelPoint> css_scroll_offset_for_node(Compositing::SpatialNodeIndex, Compositing::ScrollStateSnapshot const&) const;
- Web::CSSPixelPoint css_scroll_offset_for_node(AsyncScrollNode const&, Compositing::ScrollStateSnapshot const&) const;
- bool blocks_wheel_event_at_position(Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position) const;
- bool main_thread_wheel_event_region_contains(Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position) const;
- WheelHitTestResult hit_test_scroll_node_for_wheel(Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position, Gfx::FloatPoint delta, Function<Optional<Gfx::FloatPoint>(Web::AsyncScrollNodeStableID)> const& in_flight_destination_for = {}, WheelStepDispatch = WheelStepDispatch::NotYetDispatched, NestedContextRegions = NestedContextRegions::LeaveToMainThread) const;
- // The nested context whose content is the topmost thing taking pointer input at the position, if any.
- Optional<NestedContextHit> nested_context_at(Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position) const;
- // As above, unless the main thread takes the wheel events at the position.
- Optional<NestedContextHit> nested_context_for_wheel_at(Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position) const;
- // 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.
- Optional<NestedContextHit> position_in_content_of_nested_context(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position) const;
- // Where a position in the viewport of the nested context lies in this context's viewport.
- Optional<Gfx::FloatPoint> position_of_nested_context_position(Web::CompositorContextId, Gfx::FloatPoint position_in_nested_context, Gfx::FloatSize nested_context_viewport_size, Compositing::AccumulatedVisualContextTree const&) const;
- bool has_nested_contexts() const { return !m_nested_context_wheel_regions.is_empty(); }
- bool has_wheel_hit_test_targets_for(Compositing::AccumulatedVisualContextTree const& visual_context_tree) const { return m_visual_context_tree_structural_epoch == visual_context_tree.structural_epoch(); }
- // 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.
- bool is_covered_by_hit_test_target_painted_after(u32 paint_order_index, Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position) const;
- bool scroll_node_is_viewport(Compositing::SpatialNodeIndex) const;
- // Whether the viewport keeps a scroll by the delta from the document it is nested in, whether or not it has a
- // scroll node.
- bool viewport_keeps_scrolls_along_main_axis_of(Gfx::FloatPoint delta) const;
- // 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.
- FirstWheelStepRoute route_first_wheel_step(WheelRoutingAdmission, Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position, Gfx::FloatPoint delta, NestedContextRegions = NestedContextRegions::LeaveToMainThread) const;
- // 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.
- Optional<Compositing::SpatialNodeIndex> outermost_scroll_node_wheel_scrollable_along_main_axis_of(Compositing::SpatialNodeIndex innermost_scroll_node_index, Gfx::FloatPoint delta) const;
- // 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.
- WheelHitTestResult hit_test_result_for_scroll_node(Compositing::SpatialNodeIndex, Gfx::FloatPoint delta, Function<Optional<Gfx::FloatPoint>(Web::AsyncScrollNodeStableID)> const& in_flight_destination_for) const;
- Optional<Compositing::SpatialNodeIndex> scroll_node_for_keyboard_scroll(Web::AsyncScrollNodeStableID, Gfx::FloatPoint delta, Compositing::ScrollStateSnapshot const&) const;
- Gfx::FloatPoint clamped_scroll_offset_for_node(Compositing::SpatialNodeIndex, Gfx::FloatPoint) const;
- Optional<AsyncScrollOffset> apply_scroll_delta(Compositing::SpatialNodeIndex, Gfx::FloatPoint delta, Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot&, ScrollChaining);
- Optional<WheelScrollTarget> select_wheel_scroll_target(Compositing::SpatialNodeIndex, Gfx::FloatPoint delta, Compositing::ScrollStateSnapshot const&, Function<Optional<Gfx::FloatPoint>(Web::AsyncScrollNodeStableID)> const& in_flight_destination_for, ScrollChaining scroll_chaining) const;
- Optional<Gfx::FloatPoint> set_scroll_offset(Compositing::SpatialNodeIndex, Gfx::FloatPoint, Compositing::AccumulatedVisualContextTree const&, Compositing::ScrollStateSnapshot&);
- Gfx::FloatPoint set_scroll_offset_leaving_sticky_offsets_unresolved(AsyncScrollNode const&, Gfx::FloatPoint, Compositing::ScrollStateSnapshot&);
-
-private:
- static Gfx::FloatPoint clamp_scroll_offset_to_node(AsyncScrollNode const&, Gfx::FloatPoint);
- static bool can_scroll_node_by_delta(AsyncScrollNode const&, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint);
- static bool can_scroll_node_from_offset_by_delta(AsyncScrollNode const&, Gfx::FloatPoint scroll_offset, Gfx::FloatPoint delta);
-
- AsyncScrollNode const* scroll_node_for_stable_id(Web::AsyncScrollNodeStableID) const;
- struct NestedContextWheelRegionHit {
- NestedContextWheelRegion const& region;
- Gfx::FloatPoint position_in_context;
- };
- Optional<NestedContextWheelRegionHit> topmost_nested_context_wheel_region_at(Compositing::AccumulatedVisualContextTree const&, Gfx::FloatPoint position) const;
- Optional<Compositing::SpatialNodeIndex> scrollable_ancestor_for_node(Compositing::SpatialNodeIndex, Compositing::ScrollStateSnapshot const&, Gfx::FloatPoint delta) const;
- Gfx::FloatPoint apply_scroll_delta_to_node(AsyncScrollNode const&, Gfx::FloatPoint delta, Compositing::ScrollStateSnapshot&);
-
- Optional<Web::UniqueNodeID> m_document_id;
- Vector<AsyncScrollNode> m_scroll_nodes;
- Vector<AsyncSnapContainer> m_snap_containers;
- double m_device_pixels_per_css_pixel { 1.0 };
- Vector<WheelHitTestTarget> m_wheel_hit_test_regions;
- Vector<MainThreadWheelEventRegion> m_main_thread_wheel_event_regions;
- Vector<NestedContextWheelRegion> m_nested_context_wheel_regions;
- Vector<CachedWheelHitTestTarget> m_cached_wheel_hit_test_targets;
- Vector<BlockingWheelEventRegion> m_blocking_wheel_event_regions;
- Vector<CachedMainThreadWheelEventTarget> m_cached_main_thread_wheel_event_targets;
- Vector<CachedNestedContextWheelRegion> m_cached_nested_context_wheel_regions;
- Vector<CachedBlockingWheelEventTarget> m_cached_blocking_wheel_event_targets;
- Optional<u64> m_visual_context_tree_structural_epoch;
- Compositing::ScrollStateSnapshot m_scroll_state_snapshot;
- bool m_has_blocking_wheel_event_region_covering_viewport { false };
- bool m_viewport_keeps_horizontal_scrolls { false };
- bool m_viewport_keeps_vertical_scrolls { false };
-};
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/AsyncScrollingState.cpp b/Libraries/LibCompositing/Scrolling/AsyncScrollingState.cpp
deleted file mode 100644
index 6305c371297..00000000000
--- a/Libraries/LibCompositing/Scrolling/AsyncScrollingState.cpp
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/JsonArray.h>
-#include <AK/JsonObject.h>
-#include <LibCompositing/DisplayList/DisplayList.h>
-#include <LibCompositing/Scrolling/AsyncScrollingState.h>
-#include <LibCompositing/Scrolling/ScrollState.h>
-
-namespace Compositing {
-
-Web::AsyncScrollNodeKind async_scroll_node_kind_for(Compositing::CompositorScrollNodeKind kind)
-{
- switch (kind) {
- case Compositing::CompositorScrollNodeKind::Viewport:
- return Web::AsyncScrollNodeKind::Viewport;
- case Compositing::CompositorScrollNodeKind::Element:
- return Web::AsyncScrollNodeKind::Element;
- case Compositing::CompositorScrollNodeKind::PseudoElement:
- return Web::AsyncScrollNodeKind::PseudoElement;
- }
- VERIFY_NOT_REACHED();
-}
-
-static Web::AsyncScrollNodeStableID stable_scroll_node_id_for(Web::UniqueNodeID scrollable_node_id, Compositing::CompositorScrollNodeKind kind, u8 pseudo_element_type)
-{
- return {
- .node_id = scrollable_node_id,
- .kind = async_scroll_node_kind_for(kind),
- .pseudo_element_type = pseudo_element_type,
- };
-}
-
-AsyncScrollingState async_scrolling_state_from_display_list(Compositing::DisplayList const& display_list)
-{
- AsyncScrollingState async_scrolling_state;
- u32 next_paint_order_index = 0;
-
- if (auto const& metadata = display_list.async_scrolling_metadata(); metadata.has_value()) {
- 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([&](Compositing::ContextRef context, Compositing::DisplayListCommandType command_type, ReadonlyBytes payload) {
- auto append_wheel_hit_test_target = [&](auto const& command, Gfx::CornerRadii corner_radii) {
- Optional<Compositing::SpatialNodeIndex> target_scroll_node_index;
- if (command.target_scroll_node_index.value())
- target_scroll_node_index = command.target_scroll_node_index;
- async_scrolling_state.wheel_hit_test_targets.append({
- .context = context,
- .rect = command.rect,
- .corner_radii = corner_radii,
- .target_scroll_node_index = target_scroll_node_index,
- .paint_order_index = next_paint_order_index++,
- });
- };
-
- switch (command_type) {
- case Compositing::DisplayListCommandType::CompositorBlockingWheelEventRegion: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorBlockingWheelEventRegion>(payload);
- async_scrolling_state.has_blocking_wheel_event_listeners = true;
- async_scrolling_state.blocking_wheel_event_regions.append({
- .context = context,
- .rect = command.rect,
- });
- break;
- }
- case Compositing::DisplayListCommandType::CompositorScrollNode: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorScrollNode>(payload);
- Optional<Compositing::SpatialNodeIndex> parent_scroll_node_index;
- if (command.parent_scroll_node_index.value())
- parent_scroll_node_index = command.parent_scroll_node_index;
- async_scrolling_state.scroll_nodes.append({
- .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 = 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,
- });
- break;
- }
- case Compositing::DisplayListCommandType::CompositorWheelHitTestTarget: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorWheelHitTestTarget>(payload);
- append_wheel_hit_test_target(command, {});
- break;
- }
- case Compositing::DisplayListCommandType::CompositorWheelHitTestTargetWithCornerRadii: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorWheelHitTestTargetWithCornerRadii>(payload);
- append_wheel_hit_test_target(command, command.corner_radii);
- break;
- }
- case Compositing::DisplayListCommandType::CompositorMainThreadWheelEventRegion: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorMainThreadWheelEventRegion>(payload);
- async_scrolling_state.main_thread_wheel_event_regions.append({
- .context = context,
- .rect = command.rect,
- });
- break;
- }
- case Compositing::DisplayListCommandType::CompositorNestedContextWheelRegion: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorNestedContextWheelRegion>(payload);
- async_scrolling_state.nested_context_wheel_regions.append({
- .context = context,
- .rect = command.rect,
- .corner_radii = command.corner_radii,
- .child_context_id = command.child_context_id,
- .paint_order_index = next_paint_order_index++,
- });
- break;
- }
- case Compositing::DisplayListCommandType::CompositorScrollbar: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorScrollbar>(payload);
- async_scrolling_state.scrollbars.append({
- .scroller_stable_node_id = {},
- .scroll_node_index = command.scroll_node_index,
- .context = 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,
- });
- break;
- }
- case Compositing::DisplayListCommandType::CompositorSnapContainer: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorSnapContainer>(payload);
- async_scrolling_state.snap_containers.append({
- .scroll_node_index = command.scroll_node_index,
- .geometry = {
- .snapport = command.snapport,
- .min_scroll_offset = command.min_scroll_offset,
- .max_scroll_offset = command.max_scroll_offset,
- .strictness = static_cast<SnapStrictness>(command.strictness),
- .axes = { .x = command.snaps_x, .y = command.snaps_y },
- .horizontal_writing_mode = command.horizontal_writing_mode,
- },
- .areas = {},
- });
- break;
- }
- case Compositing::DisplayListCommandType::CompositorSnapArea: {
- auto command = Compositing::read_display_list_object<Compositing::CompositorSnapArea>(payload);
- auto& snap_containers = async_scrolling_state.snap_containers;
- // A snap container's areas are recorded right after it.
- if (snap_containers.is_empty() || snap_containers.last().scroll_node_index != command.scroll_node_index) {
- dbgln("Ignoring a snap area recorded without its snap container");
- break;
- }
- snap_containers.last().areas.append({
- .identity = { .node_id = command.area_node_id, .pseudo_element_type = command.pseudo_element_type },
- .rect = command.rect,
- .align_x = static_cast<SnapAlign>(command.align_x),
- .align_y = static_cast<SnapAlign>(command.align_y),
- .always_stop = command.always_stop,
- });
- break;
- }
- default:
- break;
- }
- });
-
- for (auto& scrollbar : async_scrolling_state.scrollbars) {
- for (auto const& scroll_node : async_scrolling_state.scroll_nodes) {
- if (scroll_node.scroll_node_index == scrollbar.scroll_node_index) {
- scrollbar.scroller_stable_node_id = scroll_node.stable_node_id;
- break;
- }
- }
- }
-
- return async_scrolling_state;
-}
-
-static StringView snap_strictness_name(SnapStrictness strictness)
-{
- switch (strictness) {
- case SnapStrictness::None:
- return "none"sv;
- case SnapStrictness::Proximity:
- return "proximity"sv;
- case SnapStrictness::Mandatory:
- return "mandatory"sv;
- }
- VERIFY_NOT_REACHED();
-}
-
-static StringView snap_align_name(SnapAlign align)
-{
- switch (align) {
- case SnapAlign::None:
- return "none"sv;
- case SnapAlign::Start:
- return "start"sv;
- case SnapAlign::End:
- return "end"sv;
- case SnapAlign::Center:
- return "center"sv;
- }
- VERIFY_NOT_REACHED();
-}
-
-static JsonObject rect_to_json(Web::CSSPixelRect const& rect)
-{
- JsonObject object;
- object.set("x"sv, rect.x().to_double());
- object.set("y"sv, rect.y().to_double());
- object.set("width"sv, rect.width().to_double());
- object.set("height"sv, rect.height().to_double());
- return object;
-}
-
-static JsonObject point_to_json(Web::CSSPixelPoint const& point)
-{
- JsonObject object;
- object.set("x"sv, point.x().to_double());
- object.set("y"sv, point.y().to_double());
- return object;
-}
-
-JsonObject async_scrolling_state_to_json(AsyncScrollingState const& state)
-{
- JsonArray scroll_nodes;
- for (auto const& scroll_node : state.scroll_nodes) {
- JsonObject node;
- node.set("scrollNodeIndex"sv, scroll_node.scroll_node_index.value());
- node.set("parentScrollNodeIndex"sv, scroll_node.parent_scroll_node_index.has_value() ? scroll_node.parent_scroll_node_index->value() : 0);
- node.set("isViewport"sv, scroll_node.is_viewport);
- scroll_nodes.must_append(move(node));
- }
-
- JsonArray snap_containers;
- for (auto const& snap_container : state.snap_containers) {
- JsonObject container;
- container.set("scrollNodeIndex"sv, snap_container.scroll_node_index.value());
- container.set("snapport"sv, rect_to_json(snap_container.geometry.snapport));
- container.set("minScrollOffset"sv, point_to_json(snap_container.geometry.min_scroll_offset));
- container.set("maxScrollOffset"sv, point_to_json(snap_container.geometry.max_scroll_offset));
- container.set("strictness"sv, snap_strictness_name(snap_container.geometry.strictness));
- container.set("snapsX"sv, snap_container.geometry.axes.x);
- container.set("snapsY"sv, snap_container.geometry.axes.y);
- container.set("horizontalWritingMode"sv, snap_container.geometry.horizontal_writing_mode);
- JsonArray areas;
- for (auto const& snap_area : snap_container.areas) {
- JsonObject area;
- area.set("nodeID"sv, snap_area.identity.node_id.value());
- area.set("pseudoElementType"sv, snap_area.identity.pseudo_element_type);
- area.set("rect"sv, rect_to_json(snap_area.rect));
- area.set("alignX"sv, snap_align_name(snap_area.align_x));
- area.set("alignY"sv, snap_align_name(snap_area.align_y));
- area.set("alwaysStop"sv, snap_area.always_stop);
- areas.must_append(move(area));
- }
- container.set("areas"sv, move(areas));
- snap_containers.must_append(move(container));
- }
-
- JsonObject object;
- object.set("documentID"sv, state.document_id.has_value() ? JsonValue { state.document_id->value() } : JsonValue {});
- object.set("scrollNodeCount"sv, state.scroll_nodes.size());
- object.set("scrollNodes"sv, move(scroll_nodes));
- object.set("snapContainers"sv, move(snap_containers));
- object.set("devicePixelsPerCssPixel"sv, state.device_pixels_per_css_pixel);
- object.set("hasBlockingWheelEventListeners"sv, state.has_blocking_wheel_event_listeners);
- object.set("blockingWheelEventRegionCount"sv, state.blocking_wheel_event_regions.size());
- object.set("mainThreadWheelEventRegionCount"sv, state.main_thread_wheel_event_regions.size());
- object.set("nestedContextWheelRegionCount"sv, state.nested_context_wheel_regions.size());
- object.set("wheelEventListenerStateGeneration"sv, state.wheel_event_listener_state_generation);
- object.set("hasBlockingWheelEventRegionCoveringViewport"sv, state.has_blocking_wheel_event_region_covering_viewport);
- return object;
-}
-
-WheelRoutingAdmission wheel_routing_admission_for(AsyncScrollingState const& state)
-{
- if (state.has_blocking_wheel_event_region_covering_viewport)
- return WheelRoutingAdmission::BlockingWheelEventListeners;
-
- if (state.scroll_nodes.is_empty())
- return WheelRoutingAdmission::NoScrollNode;
- return WheelRoutingAdmission::Accepted;
-}
-
-Web::InputRoutingDecision input_routing_decision_for_wheel_step_not_admitted_by(WheelRoutingAdmission admission)
-{
- switch (admission) {
- case WheelRoutingAdmission::Accepted:
- VERIFY_NOT_REACHED();
- case WheelRoutingAdmission::NoAsyncScrollingState:
- return Web::InputRoutingDecision::NoAsyncScrollingState;
- case WheelRoutingAdmission::BlockingWheelEventListeners:
- return Web::InputRoutingDecision::BlockingWheelEventListeners;
- case WheelRoutingAdmission::NoScrollNode:
- return Web::InputRoutingDecision::NoScrollNode;
- case WheelRoutingAdmission::StaleWheelEventListeners:
- return Web::InputRoutingDecision::StaleWheelEventListeners;
- }
- VERIFY_NOT_REACHED();
-}
-
-WheelRoutingAdmission wheel_routing_admission_for(AsyncScrollingState const& state, u64 newest_wheel_event_listener_state_generation)
-{
- if (state.wheel_event_listener_state_generation < newest_wheel_event_listener_state_generation)
- return WheelRoutingAdmission::StaleWheelEventListeners;
- return wheel_routing_admission_for(state);
-}
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/AsyncScrollingState.h b/Libraries/LibCompositing/Scrolling/AsyncScrollingState.h
index e94a7d085fb..6ed5aa5cf78 100644
--- a/Libraries/LibCompositing/Scrolling/AsyncScrollingState.h
+++ b/Libraries/LibCompositing/Scrolling/AsyncScrollingState.h
@@ -6,32 +6,15 @@
#pragma once
-#include <AK/Forward.h>
-#include <AK/HashFunctions.h>
#include <AK/Optional.h>
-#include <AK/StringView.h>
-#include <AK/Traits.h>
#include <AK/Types.h>
-#include <AK/Vector.h>
-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>
-#include <LibCompositing/Export.h>
-#include <LibCompositing/Forward.h>
-#include <LibCompositing/Scrolling/ScrollSnapSelection.h>
-#include <LibCompositing/Scrolling/ScrollState.h>
-#include <LibGfx/Color.h>
-#include <LibGfx/CornerRadii.h>
#include <LibGfx/Point.h>
-#include <LibGfx/Rect.h>
#include <LibWebCommon/Page/AsyncScrollNodeStableID.h>
-#include <LibWebCommon/Page/CompositorContextId.h>
-#include <LibWebCommon/Page/InputRoutingDecision.h>
namespace Compositing {
using AsyncScrollOperationID = u64;
-COMPOSITING_API Web::AsyncScrollNodeKind async_scroll_node_kind_for(Compositing::CompositorScrollNodeKind);
-
struct AsyncScrollOffset {
Web::AsyncScrollNodeStableID stable_node_id;
Gfx::FloatPoint compositor_scroll_offset;
@@ -65,130 +48,4 @@ struct AsyncScrollOffset {
}
};
-// One scrollable area from the paint snapshot, or a scroll container with nothing to scroll that keeps its scrolls.
-struct AsyncScrollNode {
- Compositing::SpatialNodeIndex scroll_node_index;
- Web::AsyncScrollNodeStableID stable_node_id;
- Optional<Compositing::SpatialNodeIndex> parent_scroll_node_index;
- Gfx::IntRect scrollport_rect;
- Gfx::FloatPoint min_scroll_offset;
- Gfx::FloatPoint max_scroll_offset;
- bool is_viewport { false };
- bool can_be_wheel_scrolled_horizontally { false };
- bool can_be_wheel_scrolled_vertically { false };
- // Whether a scroll the scroller cannot scroll by is passed on to the scrollers around it.
- bool chains_scroll_to_ancestors_horizontally { true };
- bool chains_scroll_to_ancestors_vertically { true };
- // Whether a touchpad may pull the scroller past the edges of its scroll range.
- bool shows_overscroll_effect_horizontally { true };
- bool shows_overscroll_effect_vertically { true };
-};
-
-// A region with a non-passive wheel listener. Wheels inside it must stay on the main thread because script may cancel.
-struct BlockingWheelEventRegion {
- Compositing::ContextRef context;
- Gfx::FloatRect rect;
-};
-
-struct WheelHitTestTarget {
- Compositing::ContextRef context;
- Gfx::FloatRect rect;
- Gfx::CornerRadii corner_radii;
- Optional<Compositing::SpatialNodeIndex> target_scroll_node_index;
- // Position among the wheel hit test targets and scrollbars of the display list, which are recorded in paint order.
- u32 paint_order_index { 0 };
-};
-
-// A region that must always use main-thread wheel routing even without a blocking listener, such as a nested navigable.
-struct MainThreadWheelEventRegion {
- Compositing::ContextRef context;
- Gfx::FloatRect rect;
-};
-
-// 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.
-struct NestedContextWheelRegion {
- Compositing::ContextRef context;
- Gfx::FloatRect rect;
- Gfx::CornerRadii corner_radii;
- Web::CompositorContextId child_context_id;
- u32 paint_order_index { 0 };
-};
-
-struct AsyncScrollbar {
- Optional<Web::AsyncScrollNodeStableID> scroller_stable_node_id;
- Compositing::SpatialNodeIndex scroll_node_index;
- // The rects of a scrollbar the display list paints are in the space of this context.
- Compositing::ContextRef context;
- u32 paint_order_index { 0 };
- Gfx::IntRect gutter_rect;
- Gfx::IntRect thumb_rect;
- Gfx::IntRect track_rect;
- Gfx::IntRect expanded_gutter_rect;
- Gfx::IntRect expanded_thumb_rect;
- double scroll_size { 0 };
- double expanded_scroll_size { 0 };
- float min_scroll_offset { 0 };
- float max_scroll_offset { 0 };
- Color thumb_color;
- Color thumb_outline_color;
- Color track_color;
- bool vertical { false };
- // 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.
- bool is_painted_by_compositor { false };
-};
-
-// A scroll node that is a snap container, with the geometry snap positions are selected from.
-struct AsyncSnapContainer {
- Compositing::SpatialNodeIndex scroll_node_index;
- SnapContainerGeometry geometry;
- Vector<SnapAreaGeometry> areas;
-};
-
-struct AsyncScrollingState {
- Optional<Web::UniqueNodeID> document_id;
- Vector<AsyncScrollNode> scroll_nodes;
- Vector<AsyncSnapContainer> snap_containers;
- Vector<WheelHitTestTarget> wheel_hit_test_targets;
- Vector<MainThreadWheelEventRegion> main_thread_wheel_event_regions;
- Vector<NestedContextWheelRegion> nested_context_wheel_regions;
- Vector<AsyncScrollbar> scrollbars;
-
- // 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.
- Vector<BlockingWheelEventRegion> blocking_wheel_event_regions;
- Gfx::IntRect viewport_rect;
-
- // Bumped whenever wheel listener state changes so queued compositor snapshots
- // cannot re-enable async wheel routing after a non-passive listener has been
- // added.
- u64 wheel_event_listener_state_generation { 0 };
- bool has_blocking_wheel_event_listeners { false };
- bool has_blocking_wheel_event_region_covering_viewport { false };
- bool viewport_keeps_horizontal_scrolls { false };
- bool viewport_keeps_vertical_scrolls { false };
- double device_pixels_per_css_pixel { 1.0 };
-};
-
-enum class WheelRoutingAdmission {
- Accepted,
- NoAsyncScrollingState,
- BlockingWheelEventListeners,
- NoScrollNode,
- StaleWheelEventListeners,
-};
-
-COMPOSITING_API AsyncScrollingState async_scrolling_state_from_display_list(Compositing::DisplayList const&);
-// The scrolling state as tests read it, from WebContent and from the compositor alike.
-COMPOSITING_API JsonObject async_scrolling_state_to_json(AsyncScrollingState const&);
-COMPOSITING_API WheelRoutingAdmission wheel_routing_admission_for(AsyncScrollingState const&);
-// 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.
-COMPOSITING_API WheelRoutingAdmission wheel_routing_admission_for(AsyncScrollingState const&, u64 newest_wheel_event_listener_state_generation);
-// Why a wheel step that the admission does not let the compositor scroll before the page dispatches it is left to the
-// page.
-COMPOSITING_API Web::InputRoutingDecision input_routing_decision_for_wheel_step_not_admitted_by(WheelRoutingAdmission);
-
}
diff --git a/Libraries/LibCompositing/Scrolling/ElasticOverscroll.cpp b/Libraries/LibCompositing/Scrolling/ElasticOverscroll.cpp
deleted file mode 100644
index b976ec3f8d2..00000000000
--- a/Libraries/LibCompositing/Scrolling/ElasticOverscroll.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-#include <LibCompositing/Scrolling/ElasticOverscroll.h>
-
-namespace Compositing {
-
-// 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.
-static constexpr double rubber_band_stiffness = 20;
-static constexpr double rubber_band_amplitude = 0.31;
-static constexpr double rubber_band_period = 1.6;
-static constexpr double rebound_decay_per_second = rubber_band_stiffness / rubber_band_period;
-
-static constexpr double largest_bounce_as_share_of_scrollport = 0.2;
-static constexpr float screen_pixels_of_stretch_that_count_as_sprung_back = 1;
-
-// 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.
-static float fastest_release_speed_for(float scrollport_length)
-{
- return static_cast<float>(largest_bounce_as_share_of_scrollport * scrollport_length * rebound_decay_per_second * AK::E<double> / rubber_band_amplitude);
-}
-
-ElasticOverscroll::ElasticOverscroll(Gfx::FloatSize scrollport_size, float screen_pixels_per_pixel)
- : m_scrollport_size(scrollport_size)
- , m_screen_pixels_per_pixel(screen_pixels_per_pixel)
-{
-}
-
-Gfx::FloatPoint ElasticOverscroll::stretch() const
-{
- auto unrounded_stretch = m_rebound.has_value() ? m_rebound->current_stretch : m_held_stretch;
- return {
- AK::trunc(unrounded_stretch.x() * m_screen_pixels_per_pixel) / m_screen_pixels_per_pixel,
- AK::trunc(unrounded_stretch.y() * m_screen_pixels_per_pixel) / m_screen_pixels_per_pixel,
- };
-}
-
-static float relax_axis_by(float& stretch, float delta)
-{
- bool delta_points_back_to_scroll_range = (stretch > 0 && delta < 0) || (stretch < 0 && delta > 0);
- if (!delta_points_back_to_scroll_range)
- return delta;
- if (AK::abs(delta) <= AK::abs(stretch)) {
- stretch += delta;
- return 0;
- }
- auto delta_left_to_scroll_with = delta + stretch;
- stretch = 0;
- return delta_left_to_scroll_with;
-}
-
-Gfx::FloatPoint ElasticOverscroll::relax_by(Gfx::FloatPoint delta)
-{
- if (m_rebound.has_value()) {
- m_held_stretch = m_rebound->current_stretch;
- m_rebound.clear();
- }
-
- auto held_stretch_x = m_held_stretch.x();
- auto held_stretch_y = m_held_stretch.y();
- Gfx::FloatPoint delta_left_to_scroll_with {
- relax_axis_by(held_stretch_x, delta.x()),
- relax_axis_by(held_stretch_y, delta.y()),
- };
- m_held_stretch = { held_stretch_x, held_stretch_y };
- return delta_left_to_scroll_with;
-}
-
-void ElasticOverscroll::pull_by(Gfx::FloatPoint overscroll_delta)
-{
- VERIFY(!m_rebound.has_value());
- auto stretch_delta = overscroll_delta.scaled(static_cast<float>(1 / rubber_band_stiffness));
- m_held_stretch = {
- clamp(m_held_stretch.x() + stretch_delta.x(), -m_scrollport_size.width(), m_scrollport_size.width()),
- clamp(m_held_stretch.y() + stretch_delta.y(), -m_scrollport_size.height(), m_scrollport_size.height()),
- };
-}
-
-void ElasticOverscroll::release(Gfx::FloatPoint velocity, MonotonicTime now)
-{
- if (m_rebound.has_value())
- return;
-
- auto initial_stretch = m_held_stretch;
- m_held_stretch = {};
-
- // Only an axis that is stretched is at its edge. The other one must not bounce off an edge it is not at.
- auto release_velocity_for_axis = [](float stretch, float velocity, float scrollport_length) -> float {
- if (stretch == 0)
- return 0;
- auto fastest_release_speed = fastest_release_speed_for(scrollport_length);
- return clamp(velocity, -fastest_release_speed, fastest_release_speed);
- };
- m_rebound = Rebound {
- .started_at = now,
- .initial_stretch = initial_stretch,
- .initial_velocity = {
- release_velocity_for_axis(initial_stretch.x(), velocity.x(), m_scrollport_size.width()),
- release_velocity_for_axis(initial_stretch.y(), velocity.y(), m_scrollport_size.height()),
- },
- .current_stretch = initial_stretch,
- };
-}
-
-struct ReboundAxisSample {
- float stretch { 0 };
- bool has_sprung_back { true };
-};
-
-static ReboundAxisSample sample_rebound_axis(float initial_stretch, float initial_velocity, float scrollport_length, float stretch_that_counts_as_sprung_back, double elapsed_seconds)
-{
- if (initial_stretch == 0)
- return {};
-
- auto stretch_before_decay = initial_stretch + rubber_band_amplitude * initial_velocity * elapsed_seconds;
- // A release velocity that points back to the scroll range must not carry the content past the edge it left.
- bool crossed_the_edge = (stretch_before_decay > 0) != (initial_stretch > 0);
- if (crossed_the_edge)
- return {};
-
- auto stretch = static_cast<float>(stretch_before_decay * AK::exp(-elapsed_seconds * rebound_decay_per_second));
- stretch = clamp(stretch, -scrollport_length, scrollport_length);
-
- // A bounce starts with almost no stretch, so a small stretch only means the rebound is over once it shrinks.
- auto stretch_growth_before_decay = rubber_band_amplitude * initial_velocity - rebound_decay_per_second * stretch_before_decay;
- bool is_still_stretching = stretch_before_decay * stretch_growth_before_decay > 0;
- return {
- .stretch = stretch,
- .has_sprung_back = !is_still_stretching && AK::abs(stretch) < stretch_that_counts_as_sprung_back,
- };
-}
-
-bool ElasticOverscroll::advance_rebound_to(MonotonicTime frame_time)
-{
- if (!m_rebound.has_value())
- return false;
-
- // The time of a display tick can be earlier than the event that released the stretch.
- auto elapsed_seconds = max(0.0, (frame_time - m_rebound->started_at).to_seconds_f64());
- auto stretch_that_counts_as_sprung_back = screen_pixels_of_stretch_that_count_as_sprung_back / m_screen_pixels_per_pixel;
- auto horizontal = sample_rebound_axis(m_rebound->initial_stretch.x(), m_rebound->initial_velocity.x(), m_scrollport_size.width(), stretch_that_counts_as_sprung_back, elapsed_seconds);
- auto vertical = sample_rebound_axis(m_rebound->initial_stretch.y(), m_rebound->initial_velocity.y(), m_scrollport_size.height(), stretch_that_counts_as_sprung_back, elapsed_seconds);
- if (horizontal.has_sprung_back && vertical.has_sprung_back) {
- m_rebound.clear();
- return false;
- }
- m_rebound->current_stretch = {
- horizontal.has_sprung_back ? 0 : horizontal.stretch,
- vertical.has_sprung_back ? 0 : vertical.stretch,
- };
- return true;
-}
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/ElasticOverscroll.h b/Libraries/LibCompositing/Scrolling/ElasticOverscroll.h
deleted file mode 100644
index ab411270b58..00000000000
--- a/Libraries/LibCompositing/Scrolling/ElasticOverscroll.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Time.h>
-#include <LibCompositing/Export.h>
-#include <LibGfx/Point.h>
-#include <LibGfx/Size.h>
-
-namespace Compositing {
-
-// 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.
-class COMPOSITING_API ElasticOverscroll {
-public:
- // A scroller that is shown magnified takes up `screen_pixels_per_pixel` pixels of the screen with each of its own.
- explicit ElasticOverscroll(Gfx::FloatSize scrollport_size, float screen_pixels_per_pixel = 1);
-
- // Whole pixels of the screen, like the scroll offsets the stretch is presented with.
- Gfx::FloatPoint stretch() const;
- bool is_at_rest() const { return !m_rebound.has_value() && m_held_stretch.is_zero(); }
- bool is_rebounding() const { return m_rebound.has_value(); }
-
- // 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.
- Gfx::FloatPoint relax_by(Gfx::FloatPoint delta);
-
- // The fingers moved by `overscroll_delta` further past an edge the scroller is already at.
- void pull_by(Gfx::FloatPoint overscroll_delta);
-
- // The fingers lifted, or momentum carried the scroller into its edge.
- void release(Gfx::FloatPoint velocity, MonotonicTime now);
-
- // Returns false once the scroller has sprung back.
- bool advance_rebound_to(MonotonicTime frame_time);
-
-private:
- struct Rebound {
- MonotonicTime started_at;
- Gfx::FloatPoint initial_stretch;
- Gfx::FloatPoint initial_velocity;
- Gfx::FloatPoint current_stretch;
- };
-
- Gfx::FloatSize m_scrollport_size;
- float m_screen_pixels_per_pixel { 1 };
- Gfx::FloatPoint m_held_stretch;
- Optional<Rebound> m_rebound;
-};
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp
new file mode 100644
index 00000000000..ad1f1333e19
--- /dev/null
+++ b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>
+#include <LibCompositing/DisplayList/DisplayList.h>
+#include <LibCompositing/RustFFI.h>
+#include <LibCompositing/Scrolling/RecordedDisplayListScrolling.h>
+#include <LibIPC/Encoded.h>
+
+namespace Compositing {
+
+using EncodedAsyncScrollingMetadata = IPC::Encoded<Optional<DisplayList::AsyncScrollingMetadata>>;
+
+String async_scrolling_state_as_json(DisplayList const* display_list)
+{
+ String json;
+ auto receive_json = [](void* receiver, ReadonlyBytes bytes) {
+ *static_cast<String*>(receiver) = MUST(String::from_utf8(bytes));
+ };
+ if (!display_list) {
+ RustFFI::recorded_display_list_async_scrolling_state_json(nullptr, &json, receive_json);
+ return json;
+ }
+ EncodedAsyncScrollingMetadata async_scrolling_metadata { display_list->async_scrolling_metadata() };
+ auto display_list_for_scroll_logic = display_list->for_scroll_logic(async_scrolling_metadata.bytes());
+ RustFFI::recorded_display_list_async_scrolling_state_json(&display_list_for_scroll_logic, &json, receive_json);
+ return json;
+}
+
+FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_list(DisplayList const& display_list, AccumulatedVisualContextTree const& visual_context_tree, ScrollStateSnapshot const& scroll_state_snapshot, u64 newest_wheel_event_listener_state_generation, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels)
+{
+ EncodedAsyncScrollingMetadata async_scrolling_metadata { display_list.async_scrolling_metadata() };
+ auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());
+ IPC::Encoded<ScrollStateSnapshot> encoded_scroll_state_snapshot { scroll_state_snapshot };
+ auto route = RustFFI::recorded_display_list_route_first_wheel_step(&display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state_snapshot.bytes(), newest_wheel_event_listener_state_generation, position, delta_in_css_pixels);
+
+ FirstWheelStepRouteForTesting result { .route = { route.decision }, .document_id = {} };
+ if (route.has_scroller) {
+ result.route.scroller = Web::AsyncScrollNodeStableID {
+ .node_id = Web::UniqueNodeID { route.scroller_node_id },
+ .kind = route.scroller_kind,
+ .pseudo_element_type = route.scroller_pseudo_element_type,
+ };
+ }
+ if (route.has_document_id)
+ result.document_id = Web::UniqueNodeID { route.document_id };
+ return result;
+}
+
+bool recorded_display_list_blocks_wheel_event_at(DisplayList const& display_list, AccumulatedVisualContextTree const& visual_context_tree, ScrollStateSnapshot const& scroll_state_snapshot, Gfx::FloatPoint position)
+{
+ EncodedAsyncScrollingMetadata async_scrolling_metadata { display_list.async_scrolling_metadata() };
+ auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());
+ IPC::Encoded<ScrollStateSnapshot> encoded_scroll_state_snapshot { scroll_state_snapshot };
+ return RustFFI::recorded_display_list_blocks_wheel_event_at(&display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state_snapshot.bytes(), position);
+}
+
+}
diff --git a/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h
new file mode 100644
index 00000000000..2ef58b1a456
--- /dev/null
+++ b/Libraries/LibCompositing/Scrolling/RecordedDisplayListScrolling.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/String.h>
+#include <LibCompositing/Export.h>
+#include <LibCompositing/Forward.h>
+#include <LibCompositing/Scrolling/ScrollState.h>
+#include <LibCompositing/Types.h>
+
+namespace Compositing {
+
+COMPOSITING_API String async_scrolling_state_as_json(DisplayList const*);
+COMPOSITING_API FirstWheelStepRouteForTesting route_first_wheel_step_through_recorded_display_list(DisplayList const&, AccumulatedVisualContextTree const&, ScrollStateSnapshot const&, u64 newest_wheel_event_listener_state_generation, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels);
+COMPOSITING_API bool recorded_display_list_blocks_wheel_event_at(DisplayList const&, AccumulatedVisualContextTree const&, ScrollStateSnapshot const&, Gfx::FloatPoint position);
+
+}
diff --git a/Libraries/LibCompositing/Scrolling/ScrollFling.cpp b/Libraries/LibCompositing/Scrolling/ScrollFling.cpp
deleted file mode 100644
index ceda03df35e..00000000000
--- a/Libraries/LibCompositing/Scrolling/ScrollFling.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-#include <LibCompositing/Scrolling/ScrollFling.h>
-#include <LibCompositing/Scrolling/SmoothScrollAnimation.h>
-
-namespace Compositing {
-
-// Use only the most recent steps to find the velocity at the lift.
-static constexpr AK::Duration velocity_sampling_window = AK::Duration::from_milliseconds(100);
-
-// If the fingers stop for longer than this before they lift, no fling starts.
-static constexpr AK::Duration maximum_pause_before_lift = AK::Duration::from_milliseconds(100);
-
-static constexpr double minimum_fling_start_speed = 50;
-static constexpr double minimum_fling_speed = 20;
-static constexpr double maximum_fling_speed = 20000;
-
-// A boost occurs only if the stopped fling was fast and a fast flick in the same direction starts soon after.
-static constexpr double minimum_boosted_fling_speed = 350;
-static constexpr double minimum_boosting_flick_speed = 150;
-static constexpr AK::Duration maximum_boost_delay = AK::Duration::from_milliseconds(500);
-
-static double speed_of(Gfx::FloatPoint velocity)
-{
- return AK::hypot(static_cast<double>(velocity.x()), static_cast<double>(velocity.y()));
-}
-
-static Gfx::FloatPoint with_speed_capped(Gfx::FloatPoint velocity)
-{
- auto speed = speed_of(velocity);
- if (speed <= maximum_fling_speed)
- return velocity;
- return velocity.scaled(static_cast<float>(maximum_fling_speed / speed));
-}
-
-void ScrollVelocityTracker::add_step(Gfx::FloatPoint delta, MonotonicTime time)
-{
- m_steps.enqueue(Step { delta, time });
-}
-
-Optional<Gfx::FloatPoint> ScrollVelocityTracker::velocity_at_lift(MonotonicTime lift_time) const
-{
- if (m_steps.is_empty())
- return {};
- auto last_step_time = m_steps.last().time;
- if (lift_time - last_step_time > maximum_pause_before_lift)
- return {};
-
- // Steps from before the window are not used. After a pause, they would make the velocity much too low.
- size_t first_index = m_steps.size() - 1;
- while (first_index > 0 && last_step_time - m_steps.at(first_index - 1).time <= velocity_sampling_window)
- --first_index;
- auto point_count = m_steps.size() - first_index;
- if (point_count < 2)
- return {};
-
- // 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.
- double sum_t = 0;
- double sum_tt = 0;
- double sum_x = 0;
- double sum_y = 0;
- double sum_tx = 0;
- double sum_ty = 0;
- double x = 0;
- double y = 0;
- for (size_t i = first_index; i < m_steps.size(); ++i) {
- auto const& step = m_steps.at(i);
- x += step.delta.x();
- y += step.delta.y();
- auto 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;
- }
-
- auto n = static_cast<double>(point_count);
- auto determinant = n * sum_tt - sum_t * sum_t;
- // If all steps have the same time, there is no velocity.
- if (determinant <= 0)
- return {};
- return Gfx::FloatPoint {
- static_cast<float>((n * sum_tx - sum_t * sum_x) / determinant),
- static_cast<float>((n * sum_ty - sum_t * sum_y) / determinant),
- };
-}
-
-Optional<ScrollFling> ScrollFling::start(Gfx::FloatPoint velocity, MonotonicTime now)
-{
- if (speed_of(velocity) < minimum_fling_start_speed)
- return {};
- return ScrollFling { with_speed_capped(velocity), now };
-}
-
-ScrollFling::ScrollFling(Gfx::FloatPoint velocity, MonotonicTime now)
- : m_initial_velocity(velocity)
- , m_initial_speed(speed_of(velocity))
- , m_started_at(now)
-{
-}
-
-// The fraction of the initial speed that remains after the given time.
-double ScrollFling::decay_at(double elapsed_seconds) const
-{
- return AK::pow(momentum_distance_share_per_frame, elapsed_seconds / momentum_frame_duration_in_seconds);
-}
-
-Gfx::FloatPoint ScrollFling::velocity_at(MonotonicTime time) const
-{
- if (m_finished)
- return {};
- auto elapsed_seconds = max(0.0, (time - m_started_at).to_seconds_f64());
- return m_initial_velocity.scaled(static_cast<float>(decay_at(elapsed_seconds)));
-}
-
-Optional<Gfx::FloatPoint> ScrollFling::step(MonotonicTime now)
-{
- if (m_finished)
- return {};
-
- auto elapsed_seconds = min((now - m_started_at).to_seconds_f64(), maximum_momentum_duration_in_seconds);
- if (elapsed_seconds <= m_last_step_elapsed_seconds)
- return Gfx::FloatPoint {};
-
- // If v(t) = v0 * decay(t), the distance at time t is v0 * time_constant * (1 - decay(t)).
- static double const time_constant = momentum_frame_duration_in_seconds / -AK::log(momentum_distance_share_per_frame);
- auto decay = decay_at(elapsed_seconds);
- auto displacement = m_initial_velocity.scaled(static_cast<float>(time_constant * (m_last_step_decay - decay)));
- m_last_step_elapsed_seconds = elapsed_seconds;
- m_last_step_decay = decay;
-
- if (m_initial_speed * decay < minimum_fling_speed || elapsed_seconds >= maximum_momentum_duration_in_seconds)
- m_finished = true;
- return displacement;
-}
-
-void ScrollFlingBooster::fling_was_interrupted(Gfx::FloatPoint velocity, MonotonicTime now)
-{
- if (speed_of(velocity) < minimum_boosted_fling_speed) {
- m_interrupted_fling.clear();
- return;
- }
- m_interrupted_fling = InterruptedFling { velocity, now };
-}
-
-Gfx::FloatPoint ScrollFlingBooster::boosted_velocity(Gfx::FloatPoint velocity, MonotonicTime now)
-{
- auto interrupted_fling = m_interrupted_fling;
- m_interrupted_fling.clear();
- if (!interrupted_fling.has_value())
- return velocity;
- if (now - interrupted_fling->interrupted_at > maximum_boost_delay)
- return velocity;
- if (speed_of(velocity) < minimum_boosting_flick_speed)
- return velocity;
- auto direction_agreement = velocity.x() * interrupted_fling->velocity.x() + velocity.y() * interrupted_fling->velocity.y();
- if (direction_agreement <= 0)
- return velocity;
- return with_speed_capped(velocity + interrupted_fling->velocity);
-}
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/ScrollFling.h b/Libraries/LibCompositing/Scrolling/ScrollFling.h
deleted file mode 100644
index 9a0378c53bc..00000000000
--- a/Libraries/LibCompositing/Scrolling/ScrollFling.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/CircularQueue.h>
-#include <AK/Optional.h>
-#include <AK/Time.h>
-#include <LibCompositing/Export.h>
-#include <LibGfx/Point.h>
-
-namespace Compositing {
-
-// Velocities are in wheel delta units per second. Displacements are in wheel delta units.
-
-// Calculates the velocity of a touchpad scroll gesture when the fingers lift.
-class COMPOSITING_API ScrollVelocityTracker {
-public:
- void add_step(Gfx::FloatPoint delta, MonotonicTime);
- void reset() { m_steps.clear(); }
-
- // Returns no value if the fingers stopped for too long before the lift.
- Optional<Gfx::FloatPoint> velocity_at_lift(MonotonicTime lift_time) const;
-
-private:
- struct Step {
- Gfx::FloatPoint delta;
- MonotonicTime time;
- };
-
- CircularQueue<Step, 20> m_steps;
-};
-
-// 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.
-class COMPOSITING_API ScrollFling {
-public:
- static Optional<ScrollFling> start(Gfx::FloatPoint velocity, MonotonicTime now);
-
- // Returns the displacement since the previous step, or no value after the fling stops.
- Optional<Gfx::FloatPoint> step(MonotonicTime now);
- Gfx::FloatPoint velocity_at(MonotonicTime) const;
-
-private:
- ScrollFling(Gfx::FloatPoint velocity, MonotonicTime now);
-
- double decay_at(double elapsed_seconds) const;
-
- Gfx::FloatPoint m_initial_velocity;
- double m_initial_speed { 0 };
- MonotonicTime m_started_at;
- double m_last_step_elapsed_seconds { 0 };
- double m_last_step_decay { 1 };
- bool m_finished { false };
-};
-
-// If the user flicks again while a fling is fast, the new fling gets the velocity of the old fling added.
-class COMPOSITING_API ScrollFlingBooster {
-public:
- void fling_was_interrupted(Gfx::FloatPoint velocity, MonotonicTime now);
- Gfx::FloatPoint boosted_velocity(Gfx::FloatPoint velocity, MonotonicTime now);
- void reset() { m_interrupted_fling.clear(); }
-
-private:
- struct InterruptedFling {
- Gfx::FloatPoint velocity;
- MonotonicTime interrupted_at;
- };
- Optional<InterruptedFling> m_interrupted_fling;
-};
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/ScrollSnapSelection.cpp b/Libraries/LibCompositing/Scrolling/ScrollSnapSelection.cpp
deleted file mode 100644
index f66d3cfff96..00000000000
--- a/Libraries/LibCompositing/Scrolling/ScrollSnapSelection.cpp
+++ /dev/null
@@ -1,485 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/AnyOf.h>
-#include <AK/Math.h>
-#include <AK/QuickSort.h>
-#include <LibCompositing/Scrolling/ScrollSnapSelection.h>
-
-namespace Compositing {
-
-struct SnapAxisGeometry {
- Web::CSSPixels snapport_start;
- Web::CSSPixels snapport_size;
- Web::CSSPixels min_offset;
- Web::CSSPixels max_offset;
-};
-
-static SnapAxisGeometry x_axis_geometry(SnapContainerGeometry const& geometry)
-{
- return {
- .snapport_start = geometry.snapport.left(),
- .snapport_size = geometry.snapport.width(),
- .min_offset = geometry.min_scroll_offset.x(),
- .max_offset = geometry.max_scroll_offset.x(),
- };
-}
-
-static SnapAxisGeometry y_axis_geometry(SnapContainerGeometry const& geometry)
-{
- return {
- .snapport_start = geometry.snapport.top(),
- .snapport_size = geometry.snapport.height(),
- .min_offset = geometry.min_scroll_offset.y(),
- .max_offset = geometry.max_scroll_offset.y(),
- };
-}
-
-static Optional<SnapPositionCandidate> snap_position_candidate_for_axis(SnapAlign alignment, Web::CSSPixels area_start, Web::CSSPixels area_size, SnapAxisGeometry const& geometry)
-{
- Web::CSSPixels offset;
- switch (alignment) {
- case SnapAlign::None:
- return {};
- case SnapAlign::Start:
- offset = area_start - geometry.snapport_start;
- break;
- case SnapAlign::End:
- offset = area_start + area_size - (geometry.snapport_start + geometry.snapport_size);
- break;
- case SnapAlign::Center:
- offset = area_start + area_size / 2 - (geometry.snapport_start + geometry.snapport_size / 2);
- break;
- }
-
- // 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.
- SnapPositionCandidate candidate { .offset = clamp(offset, geometry.min_offset, geometry.max_offset), .covering_ranges = {} };
-
- if (area_size > geometry.snapport_size) {
- candidate.covering_ranges.append({
- .start = clamp(area_start - geometry.snapport_start, geometry.min_offset, geometry.max_offset),
- .end = clamp(area_start + area_size - (geometry.snapport_start + geometry.snapport_size), geometry.min_offset, geometry.max_offset),
- });
- }
-
- return candidate;
-}
-
-static void restrict_covering_ranges_to_valid_snap_positions(Vector<SnapPositionCandidate>& candidates, Web::CSSPixels snapport_size)
-{
- Vector<Web::CSSPixels> snap_positions;
- snap_positions.ensure_capacity(candidates.size());
- for (auto const& candidate : candidates)
- snap_positions.unchecked_append(candidate.offset);
- quick_sort(snap_positions);
-
- for (auto& candidate : candidates) {
- if (candidate.covering_ranges.is_empty())
- continue;
-
- auto covering_range = candidate.covering_ranges.first();
- candidate.covering_ranges.clear_with_capacity();
-
- auto append_valid_offsets_between = [&](Web::CSSPixels start, Web::CSSPixels end) {
- start = max(start, covering_range.start);
- end = min(end, covering_range.end);
- if (start <= end)
- candidate.covering_ranges.append({ .start = start, .end = end });
- };
-
- append_valid_offsets_between(covering_range.start, snap_positions.first());
- for (size_t i = 1; i < snap_positions.size(); ++i) {
- 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.last(), covering_range.end);
- }
-}
-
-// 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.
-static constexpr Web::CSSPixels SNAP_POSITION_BOUNDARY_TOLERANCE = 1;
-
-static bool is_beyond_in_direction(Web::CSSPixels offset, Web::CSSPixels boundary, Web::CSSPixels direction)
-{
- if (direction > 0)
- return offset >= boundary + SNAP_POSITION_BOUNDARY_TOLERANCE;
- return offset <= boundary - SNAP_POSITION_BOUNDARY_TOLERANCE;
-}
-
-static bool is_at_or_beyond_in_direction(Web::CSSPixels offset, Web::CSSPixels boundary, Web::CSSPixels direction)
-{
- if (direction > 0)
- return offset >= boundary;
- return offset <= boundary;
-}
-
-bool snap_area_is_visible_at_cross_axis_offset(SnapPositionCandidate const& candidate, Web::CSSPixels cross_axis_offset)
-{
- return 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.
-bool candidate_has_snap_position_at(SnapPositionCandidate const& candidate, Web::CSSPixels offset)
-{
- if (candidate.offset == offset)
- return true;
- return any_of(candidate.covering_ranges, [&](auto const& covering_range) { return offset >= covering_range.start && offset <= covering_range.end; });
-}
-
-static bool chosen_offset_is_visible_at_cross_axis_offset(Vector<SnapPositionCandidate> const& candidates, Web::CSSPixels offset, Web::CSSPixels cross_axis_offset)
-{
- return any_of(candidates, [&](auto const& candidate) {
- return snap_area_is_visible_at_cross_axis_offset(candidate, cross_axis_offset) && candidate_has_snap_position_at(candidate, offset);
- });
-}
-
-SnapDestination snap_destination_for(Web::CSSPixelPoint unsnapped_destination, Optional<Web::CSSPixels> x_offset, Optional<Web::CSSPixels> y_offset, SnapAxes evaluated_axes)
-{
- return {
- .position = { x_offset.value_or(unsnapped_destination.x()), y_offset.value_or(unsnapped_destination.y()) },
- .snapped_x = x_offset.has_value(),
- .snapped_y = y_offset.has_value(),
- .evaluated_x = evaluated_axes.x,
- .evaluated_y = evaluated_axes.y,
- };
-}
-
-bool chosen_offsets_are_mutually_visible(SnapAxisCandidates const& candidates, Web::CSSPixels x_offset, Web::CSSPixels y_offset)
-{
- return 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);
-}
-
-Optional<SnapAxisChoice> choose_snap_offset_for_axis(Vector<SnapPositionCandidate> const& candidates, SnapAxisSelection const& selection, Web::CSSPixels snapport_size, SnapStrictness strictness, Optional<Web::CSSPixels> cross_axis_offset, Optional<SnapAreaIdentity> only_area)
-{
- // 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.
- auto proximity_range = snapport_size / 3;
-
- Optional<SnapAxisChoice> best_choice;
- Web::CSSPixels best_distance = 0;
- auto consider_candidate = [&](Web::CSSPixels offset, SnapPositionCandidate const& candidate) {
- auto distance = abs(offset - selection.destination);
- if (strictness == SnapStrictness::Proximity && distance > proximity_range)
- return;
- if (!best_choice.has_value() || distance < best_distance) {
- best_choice = SnapAxisChoice { offset, candidate.area };
- best_distance = distance;
- }
- };
-
- Optional<SnapAxisChoice> first_always_stop_choice;
- auto track_always_stop_candidate = [&](SnapPositionCandidate const& candidate) {
- if (!first_always_stop_choice.has_value() || abs(candidate.offset - selection.start) < abs(first_always_stop_choice->offset - selection.start))
- first_always_stop_choice = SnapAxisChoice { candidate.offset, candidate.area };
- };
-
- for (auto const& candidate : candidates) {
- if (only_area.has_value() && candidate.area != *only_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.has_value() && !snap_area_is_visible_at_cross_axis_offset(candidate, *cross_axis_offset))
- continue;
-
- if (selection.direction != 0 && candidate.always_stop && is_beyond_in_direction(candidate.offset, selection.start, selection.direction))
- track_always_stop_candidate(candidate);
-
- if (!selection.starting_positions_boundary.has_value()
- || (is_beyond_in_direction(candidate.offset, selection.start, selection.direction)
- && is_at_or_beyond_in_direction(candidate.offset, *selection.starting_positions_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 (auto const& covering_range : candidate.covering_ranges) {
- auto range_start = covering_range.start;
- auto range_end = covering_range.end;
- if (selection.starting_positions_boundary.has_value()) {
- if (selection.direction > 0) {
- range_start = max(range_start, selection.start + SNAP_POSITION_BOUNDARY_TOLERANCE);
- } else if (selection.direction < 0) {
- range_end = min(range_end, selection.start - SNAP_POSITION_BOUNDARY_TOLERANCE);
- }
- }
- if (range_start > range_end)
- continue;
-
- consider_candidate(clamp(selection.destination, 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.has_value() && selection.starting_positions_boundary.has_value() && strictness == SnapStrictness::Mandatory) {
- SnapAxisSelection fallback_selection {
- .destination = selection.destination,
- .start = selection.destination,
- .direction = 0,
- .starting_positions_boundary = {},
- };
- 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 (best_choice.has_value() && first_always_stop_choice.has_value()) {
- bool always_stop_position_is_passed_over = selection.direction > 0
- ? best_choice->offset > first_always_stop_choice->offset
- : best_choice->offset < first_always_stop_choice->offset;
- if (always_stop_position_is_passed_over)
- best_choice = first_always_stop_choice;
- }
-
- return best_choice;
-}
-
-SnapAxes axes_to_evaluate(SnapAxes container_axes, SnapSelectionStrategy const& strategy)
-{
- // 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.
- auto snaps_in_axis = [&](bool container_snaps_in_axis, Web::CSSPixels axis_displacement) {
- return container_snaps_in_axis && (strategy.displacement.is_zero() || axis_displacement != 0);
- };
- return {
- .x = snaps_in_axis(container_axes.x, strategy.displacement.x()),
- .y = snaps_in_axis(container_axes.y, strategy.displacement.y()),
- };
-}
-
-SnapAxisCandidates build_snap_candidates(SnapContainerGeometry const& geometry, ReadonlySpan<SnapAreaGeometry> areas, SnapAxes collect_axes)
-{
- auto x_geometry = x_axis_geometry(geometry);
- auto y_geometry = y_axis_geometry(geometry);
-
- SnapAxisCandidates candidates;
- for (auto const& area : areas) {
- auto const& area_rect = area.rect;
- if (collect_axes.x) {
- if (auto candidate = snap_position_candidate_for_axis(area.align_x, area_rect.left(), area_rect.width(), x_geometry); candidate.has_value()) {
- 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.append(*candidate);
- }
- }
- if (collect_axes.y) {
- if (auto candidate = snap_position_candidate_for_axis(area.align_y, area_rect.top(), area_rect.height(), y_geometry); candidate.has_value()) {
- 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.append(*candidate);
- }
- }
- }
-
- if (collect_axes.x)
- restrict_covering_ranges_to_valid_snap_positions(candidates.x_candidates, x_geometry.snapport_size);
- if (collect_axes.y)
- restrict_covering_ranges_to_valid_snap_positions(candidates.y_candidates, y_geometry.snapport_size);
-
- return candidates;
-}
-
-Vector<SnapAreaIdentity> snap_areas_at_offset(Vector<SnapPositionCandidate> const& candidates, Web::CSSPixels offset, Web::CSSPixels cross_axis_offset)
-{
- Vector<SnapAreaIdentity> areas;
- for (auto const& candidate : 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.append(candidate.area);
- }
- return areas;
-}
-
-// https://drafts.csswg.org/css-scroll-snap-1/#choosing
-SnapDestination select_snap_destination(SnapContainerGeometry const& geometry, SnapAxisCandidates const& candidates, Web::CSSPixelPoint destination, SnapSelectionStrategy const& strategy, SnapAxes evaluated_axes)
-{
- bool snaps_x = evaluated_axes.x;
- bool snaps_y = evaluated_axes.y;
- if (!snaps_x && !snaps_y)
- return { destination };
-
- auto const& snapport = geometry.snapport;
- auto strictness = geometry.strictness;
-
- auto axis_selection = [&](Web::CSSPixels axis_destination, Web::CSSPixels axis_displacement, Optional<Web::CSSPixels> axis_start, Optional<Web::CSSPixels> axis_boundary) {
- if (!axis_start.has_value() || axis_displacement == 0) {
- return SnapAxisSelection {
- .destination = axis_destination,
- .start = axis_destination,
- .direction = 0,
- .starting_positions_boundary = {},
- };
- }
-
- Optional<Web::CSSPixels> boundary;
- if (strategy.type != SnapSelectionStrategy::Type::EndPosition)
- boundary = axis_boundary.value_or(*axis_start);
-
- return SnapAxisSelection {
- .destination = axis_destination,
- .start = *axis_start,
- .direction = axis_displacement,
- .starting_positions_boundary = boundary,
- };
- };
- auto axis_of = [](Optional<Web::CSSPixelPoint> const& offset, bool horizontal) -> Optional<Web::CSSPixels> {
- if (!offset.has_value())
- return {};
- return horizontal ? offset->x() : offset->y();
- };
- auto x_selection = axis_selection(destination.x(), strategy.displacement.x(), axis_of(strategy.start_offset, true), axis_of(strategy.starting_positions_boundary, true));
- auto y_selection = axis_selection(destination.y(), strategy.displacement.y(), axis_of(strategy.start_offset, false), axis_of(strategy.starting_positions_boundary, false));
-
- auto choose_x = [&](Optional<Web::CSSPixels> cross_axis_offset, Optional<SnapAreaIdentity> only_area = {}) {
- return choose_snap_offset_for_axis(candidates.x_candidates, x_selection, snapport.width(), strictness, cross_axis_offset, only_area);
- };
- auto choose_y = [&](Optional<Web::CSSPixels> cross_axis_offset, Optional<SnapAreaIdentity> only_area = {}) {
- return choose_snap_offset_for_axis(candidates.y_candidates, y_selection, snapport.height(), strictness, cross_axis_offset, only_area);
- };
-
- Optional<SnapAxisChoice> x_choice;
- Optional<SnapAxisChoice> y_choice;
- if (snaps_x && snaps_y) {
- x_choice = choose_x({});
- y_choice = choose_y({});
- if (x_choice.has_value() && y_choice.has_value() && !chosen_offsets_are_mutually_visible(candidates, x_choice->offset, y_choice->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.
- Optional<SnapAxisChoice> y_of_x_area;
- Optional<SnapAxisChoice> x_of_y_area;
- if (x_choice->area.is_valid())
- y_of_x_area = choose_y(x_choice->offset, x_choice->area);
- if (y_choice->area.is_valid())
- x_of_y_area = choose_x(y_choice->offset, y_choice->area);
-
- auto distance_to_destination = [&](SnapAxisChoice const& x_axis_choice, SnapAxisChoice const& y_axis_choice) {
- return AK::hypot((x_axis_choice.offset - x_selection.destination).to_double(), (y_axis_choice.offset - y_selection.destination).to_double());
- };
- bool follows_x_area = y_of_x_area.has_value();
- if (follows_x_area && x_of_y_area.has_value())
- follows_x_area = distance_to_destination(*x_choice, *y_of_x_area) < distance_to_destination(*x_of_y_area, *y_choice);
-
- if (follows_x_area) {
- y_choice = y_of_x_area;
- } else if (x_of_y_area.has_value()) {
- 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_choice->offset - x_selection.destination) <= abs(y_choice->offset - y_selection.destination)) {
- y_choice = choose_y(x_choice->offset);
- } else {
- x_choice = choose_x(y_choice->offset);
- }
- }
- }
- if (x_choice.has_value() && !y_choice.has_value()) {
- x_choice = choose_x(destination.y());
- } else if (y_choice.has_value() && !x_choice.has_value()) {
- y_choice = choose_y(destination.x());
- }
- } else if (snaps_x) {
- x_choice = choose_x(destination.y());
- } else if (snaps_y) {
- y_choice = choose_y(destination.x());
- }
-
- auto x_offset = x_choice.map([](auto const& choice) { return choice.offset; });
- auto y_offset = y_choice.map([](auto const& choice) { return choice.offset; });
-
- auto snap_destination = snap_destination_for(destination, x_offset, y_offset, { snaps_x, snaps_y });
- if (x_offset.has_value())
- snap_destination.snapped_areas.x = snap_areas_at_offset(candidates.x_candidates, *x_offset, snap_destination.position.y());
- if (y_offset.has_value())
- snap_destination.snapped_areas.y = snap_areas_at_offset(candidates.y_candidates, *y_offset, snap_destination.position.x());
- return snap_destination;
-}
-
-SnapDestination select_snap_destination(SnapContainerGeometry const& geometry, ReadonlySpan<SnapAreaGeometry> areas, Web::CSSPixelPoint destination, SnapSelectionStrategy const& strategy)
-{
- auto evaluated_axes = axes_to_evaluate(geometry.axes, strategy);
- if (evaluated_axes.is_empty())
- return { destination };
- auto candidates = build_snap_candidates(geometry, areas, evaluated_axes);
- return select_snap_destination(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.
-static constexpr double maximum_momentum_decay_share = 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.
-static constexpr double maximum_slow_momentum_decay_share = 0.99;
-
-// The number of consecutively smaller momentum deltas after which momentum that decays only slowly is predicted from
-// anyway.
-static constexpr u32 decaying_deltas_before_slow_decay_is_predicted_from = 3;
-
-void MomentumFlingEstimator::reset()
-{
- m_previous_momentum_delta = {};
- m_consecutively_decaying_momentum_deltas = 0;
-}
-
-Optional<Web::CSSPixelPoint> MomentumFlingEstimator::estimate_remaining_displacement(Web::CSSPixelPoint momentum_delta)
-{
- auto previous_momentum_delta = m_previous_momentum_delta;
- m_previous_momentum_delta = 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.
- if (!previous_momentum_delta.has_value())
- return {};
- auto distance = AK::hypot(momentum_delta.x().to_double(), momentum_delta.y().to_double());
- auto previous_distance = AK::hypot(previous_momentum_delta->x().to_double(), previous_momentum_delta->y().to_double());
- if (previous_distance <= 0)
- return {};
- auto decay_share = distance / previous_distance;
-
- if (decay_share < 1) {
- ++m_consecutively_decaying_momentum_deltas;
- } else {
- m_consecutively_decaying_momentum_deltas = 0;
- }
-
- auto momentum_is_decaying = decay_share < maximum_momentum_decay_share
- || (m_consecutively_decaying_momentum_deltas >= decaying_deltas_before_slow_decay_is_predicted_from && decay_share < 1);
- if (!momentum_is_decaying)
- return {};
-
- // 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.
- auto remaining_distance_factor = 1 / (1 - min(decay_share, maximum_slow_momentum_decay_share));
- return Web::CSSPixelPoint {
- Web::CSSPixels::nearest_value_for(momentum_delta.x().to_double() * remaining_distance_factor),
- Web::CSSPixels::nearest_value_for(momentum_delta.y().to_double() * remaining_distance_factor),
- };
-}
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/ScrollSnapSelection.h b/Libraries/LibCompositing/Scrolling/ScrollSnapSelection.h
index 82f96e08191..65fc76b455f 100644
--- a/Libraries/LibCompositing/Scrolling/ScrollSnapSelection.h
+++ b/Libraries/LibCompositing/Scrolling/ScrollSnapSelection.h
@@ -7,32 +7,16 @@
#pragma once
#include <AK/Optional.h>
-#include <AK/Span.h>
#include <AK/Vector.h>
#include <LibCompositing/Export.h>
#include <LibCompositing/Forward.h>
#include <LibWebCommon/PixelUnits.h>
-// 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.
+// What scroll snap position selection is asked and answers, on the main thread and in the compositor process alike.
+// The selection is libcompositing_rust's scrolling::scroll_snap_selection. Everything here is in CSS pixels.
namespace Compositing {
-// 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.
-enum class SnapAlign : u8 {
- None,
- Start,
- End,
- Center,
-};
-
-enum class SnapStrictness : u8 {
- 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.
@@ -47,60 +31,6 @@ struct SnapAreaIdentity {
bool is_pseudo_element() const { return pseudo_element_type != 0; }
};
-struct SnapAxes {
- bool x { false };
- bool y { false };
-
- bool is_empty() const { return !x && !y; }
-};
-
-// https://drafts.csswg.org/css-scroll-snap-1/#scroll-snap-area
-struct SnapAreaGeometry {
- SnapAreaIdentity identity;
- // The transformed border box in the snap container's coordinate space, with the scroll margin added.
- Web::CSSPixelRect rect;
- // The alignment along each physical axis, resolved from the writing mode it applies in.
- SnapAlign align_x { SnapAlign::None };
- SnapAlign align_y { SnapAlign::None };
- bool always_stop { false };
-};
-
-// https://drafts.csswg.org/css-scroll-snap-1/#scroll-snap-container
-struct SnapContainerGeometry {
- // https://drafts.csswg.org/css-scroll-snap-1/#scroll-padding
- Web::CSSPixelRect snapport;
- Web::CSSPixelPoint min_scroll_offset;
- Web::CSSPixelPoint max_scroll_offset;
- SnapStrictness strictness { SnapStrictness::None };
- SnapAxes axes;
- bool horizontal_writing_mode { true };
-};
-
-// A closed range of scroll offsets that are all valid snap positions.
-struct CoveringRange {
- Web::CSSPixels start;
- Web::CSSPixels end;
-};
-
-// A candidate scroll offset in one axis, produced by aligning a snap area with the snapport.
-struct SnapPositionCandidate {
- Web::CSSPixels offset;
- SnapAreaIdentity area {};
-
- Vector<CoveringRange, 1> covering_ranges;
-
- // The open range of scroll offsets in the container's other axis at which the snap area overlaps the snapport.
- Web::CSSPixels cross_axis_visible_range_start { 0 };
- Web::CSSPixels cross_axis_visible_range_end { 0 };
-
- bool always_stop { false };
-};
-
-struct SnapAxisCandidates {
- Vector<SnapPositionCandidate> x_candidates;
- Vector<SnapPositionCandidate> y_candidates;
-};
-
// https://drafts.csswg.org/css-scroll-snap-1/#scroll-types
struct COMPOSITING_API SnapSelectionStrategy {
enum class Type : u8 {
@@ -146,49 +76,4 @@ struct SnapDestination {
SnappedAreas snapped_areas {};
};
-// The selection a scroll makes in one axis.
-struct SnapAxisSelection {
- Web::CSSPixels destination;
- Web::CSSPixels start;
- Web::CSSPixels direction;
- Optional<Web::CSSPixels> starting_positions_boundary;
-};
-
-struct SnapAxisChoice {
- Web::CSSPixels offset;
- SnapAreaIdentity area;
-};
-
-// 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.
-COMPOSITING_API SnapAxes axes_to_evaluate(SnapAxes container_axes, SnapSelectionStrategy const&);
-
-COMPOSITING_API SnapAxisCandidates build_snap_candidates(SnapContainerGeometry const&, ReadonlySpan<SnapAreaGeometry>, SnapAxes collect_axes);
-
-// https://drafts.csswg.org/css-scroll-snap-1/#choosing
-COMPOSITING_API SnapDestination select_snap_destination(SnapContainerGeometry const&, SnapAxisCandidates const&, Web::CSSPixelPoint destination, SnapSelectionStrategy const&, SnapAxes evaluated_axes);
-COMPOSITING_API SnapDestination select_snap_destination(SnapContainerGeometry const&, ReadonlySpan<SnapAreaGeometry>, Web::CSSPixelPoint destination, SnapSelectionStrategy const& = {});
-
-COMPOSITING_API Optional<SnapAxisChoice> choose_snap_offset_for_axis(Vector<SnapPositionCandidate> const&, SnapAxisSelection const&, Web::CSSPixels snapport_size, SnapStrictness, Optional<Web::CSSPixels> cross_axis_offset, Optional<SnapAreaIdentity> only_area = {});
-COMPOSITING_API bool candidate_has_snap_position_at(SnapPositionCandidate const&, Web::CSSPixels offset);
-COMPOSITING_API bool snap_area_is_visible_at_cross_axis_offset(SnapPositionCandidate const&, Web::CSSPixels cross_axis_offset);
-COMPOSITING_API bool chosen_offsets_are_mutually_visible(SnapAxisCandidates const&, Web::CSSPixels x_offset, Web::CSSPixels y_offset);
-COMPOSITING_API SnapDestination snap_destination_for(Web::CSSPixelPoint unsnapped_destination, Optional<Web::CSSPixels> x_offset, Optional<Web::CSSPixels> y_offset, SnapAxes evaluated_axes);
-COMPOSITING_API Vector<SnapAreaIdentity> snap_areas_at_offset(Vector<SnapPositionCandidate> const&, Web::CSSPixels offset, Web::CSSPixels cross_axis_offset);
-
-// The displacement the momentum of a flick has left to travel, estimated from the deltas that momentum has produced
-// so far.
-class COMPOSITING_API MomentumFlingEstimator {
-public:
- void reset();
-
- // 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.
- Optional<Web::CSSPixelPoint> estimate_remaining_displacement(Web::CSSPixelPoint momentum_delta);
-
-private:
- Optional<Web::CSSPixelPoint> m_previous_momentum_delta;
- u32 m_consecutively_decaying_momentum_deltas { 0 };
-};
-
}
diff --git a/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.cpp b/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.cpp
index e6e008d2db8..d74b835519e 100644
--- a/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.cpp
+++ b/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.cpp
@@ -4,201 +4,50 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Math.h>
-#include <AK/StdLibExtras.h>
+#include <LibCompositing/RustFFI.h>
#include <LibCompositing/Scrolling/SmoothScrollAnimation.h>
namespace Compositing {
-static constexpr double scroll_speed_in_pixels_per_second = 1000.0;
-static constexpr double maximum_scroll_duration_in_seconds = 0.2;
-
-// A wheel step takes longer the shorter its distance, within these bounds.
-static constexpr double minimum_wheel_scroll_duration_in_seconds = 0.1;
-static constexpr double maximum_wheel_scroll_duration_in_seconds = 0.2;
-static constexpr double wheel_scroll_distance_covered_at_maximum_duration = 120.0;
-static constexpr double wheel_scroll_duration_reduction_per_pixel = 1.0 / 3600.0;
-
-// 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.
-static constexpr double easing_control_point_x1 = 0.42;
-static constexpr double easing_control_point_x2 = 0.58;
-static constexpr double easing_control_point_y2 = 1.0;
-
-static constexpr double maximum_easing_slope = 1000.0;
-static constexpr double retarget_ease_out_allowance = 2.5;
-
-// https://drafts.csswg.org/css-easing/#cubic-bezier-algo
-static double cubic_bezier(double t, double p1, double p2)
-{
- return 3 * (1 - t) * (1 - t) * t * p1 + 3 * (1 - t) * t * t * p2 + t * t * t;
-}
-
-static double cubic_bezier_derivative(double t, double p1, double p2)
-{
- return 3 * (1 - t) * (1 - t) * p1 + 6 * (1 - t) * t * (p2 - p1) + 3 * t * t * (1 - p2);
-}
-
-static double curve_parameter_for_progress(double progress)
-{
- // 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.
- auto t = progress;
- for (int i = 0; i < 8; ++i) {
- auto x = cubic_bezier(t, easing_control_point_x1, easing_control_point_x2) - progress;
- if (AK::abs(x) < 1e-7)
- return t;
- auto slope = cubic_bezier_derivative(t, easing_control_point_x1, easing_control_point_x2);
- if (AK::abs(slope) < 1e-6)
- break;
- t -= x / slope;
- }
- double low = 0;
- double high = 1;
- while (high - low > 1e-7) {
- t = (low + high) / 2;
- if (cubic_bezier(t, easing_control_point_x1, easing_control_point_x2) < progress)
- low = t;
- else
- high = t;
- }
- return t;
-}
-
-static double momentum_frames_for_distance(double distance)
-{
- auto frames = AK::ceil(-AK::log(1 - distance * (1 - 1 / momentum_distance_share_per_frame)) / AK::log(momentum_distance_share_per_frame));
- return min(frames, maximum_momentum_duration_in_seconds / momentum_frame_duration_in_seconds);
-}
-
SmoothScrollAnimation::SmoothScrollAnimation(Gfx::FloatPoint start_offset, Gfx::FloatPoint destination_offset, double pixels_per_css_pixel, ScrollAnimationKind kind)
- : m_start_offset(start_offset)
- , m_destination_offset(destination_offset)
- , m_pixels_per_css_pixel(pixels_per_css_pixel)
- , m_kind(kind)
+ : m_animation(RustFFI::smooth_scroll_animation_create(start_offset, destination_offset, pixels_per_css_pixel, kind))
{
- VERIFY(pixels_per_css_pixel > 0);
- m_duration = duration_for_distance(destination_offset - start_offset);
}
-AK::Duration SmoothScrollAnimation::duration_for_distance(Gfx::FloatPoint distance) const
+SmoothScrollAnimation::~SmoothScrollAnimation()
{
- auto horizontal_distance = static_cast<double>(distance.x()) / m_pixels_per_css_pixel;
- auto vertical_distance = static_cast<double>(distance.y()) / m_pixels_per_css_pixel;
- auto length = AK::sqrt(horizontal_distance * horizontal_distance + vertical_distance * vertical_distance);
- if (length == 0)
- return AK::Duration::zero();
-
- double duration_in_seconds = 0;
- switch (m_kind) {
- case ScrollAnimationKind::SmoothScroll:
- duration_in_seconds = min(length / scroll_speed_in_pixels_per_second, maximum_scroll_duration_in_seconds);
- break;
- case ScrollAnimationKind::Wheel:
- duration_in_seconds = clamp(
- maximum_wheel_scroll_duration_in_seconds - (length - wheel_scroll_distance_covered_at_maximum_duration) * wheel_scroll_duration_reduction_per_pixel,
- minimum_wheel_scroll_duration_in_seconds, maximum_wheel_scroll_duration_in_seconds);
- break;
- case ScrollAnimationKind::Momentum:
- duration_in_seconds = momentum_frames_for_distance(length) * momentum_frame_duration_in_seconds;
- break;
- }
- return AK::Duration::from_seconds_f64(duration_in_seconds);
+ RustFFI::smooth_scroll_animation_destroy(m_animation);
}
-double SmoothScrollAnimation::eased_progress_at(double progress) const
+SmoothScrollAnimation::SmoothScrollAnimation(SmoothScrollAnimation&& other)
+ : m_animation(exchange(other.m_animation, nullptr))
{
- if (m_kind == ScrollAnimationKind::Momentum) {
- auto frames = m_duration.to_seconds_f64() / momentum_frame_duration_in_seconds;
- auto frames_elapsed = progress * frames;
- return (1 - AK::pow(momentum_distance_share_per_frame, frames_elapsed)) / (1 - AK::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.
- return cubic_bezier(curve_parameter_for_progress(progress), m_easing_control_point_y1, easing_control_point_y2);
}
-double SmoothScrollAnimation::easing_slope_at(double progress) const
+SmoothScrollAnimation& SmoothScrollAnimation::operator=(SmoothScrollAnimation&& other)
{
- if (m_kind == ScrollAnimationKind::Momentum) {
- auto frames = m_duration.to_seconds_f64() / momentum_frame_duration_in_seconds;
- auto frames_elapsed = progress * frames;
- auto decay = AK::log(momentum_distance_share_per_frame);
- return -AK::pow(momentum_distance_share_per_frame, frames_elapsed) * decay * frames / (1 - AK::pow(momentum_distance_share_per_frame, frames));
+ if (this != &other) {
+ RustFFI::smooth_scroll_animation_destroy(m_animation);
+ m_animation = exchange(other.m_animation, nullptr);
}
-
- auto t = curve_parameter_for_progress(progress);
- auto horizontal_slope = cubic_bezier_derivative(t, easing_control_point_x1, easing_control_point_x2);
- if (horizontal_slope == 0)
- return 0;
- return cubic_bezier_derivative(t, m_easing_control_point_y1, easing_control_point_y2) / horizontal_slope;
+ return *this;
}
-Gfx::FloatPoint SmoothScrollAnimation::velocity_at(AK::Duration elapsed) const
+ScrollAnimationKind SmoothScrollAnimation::kind() const
{
- if (m_duration.is_zero())
- return {};
-
- auto duration_in_seconds = m_duration.to_seconds_f64();
- auto progress = clamp((elapsed - m_start_time).to_seconds_f64() / duration_in_seconds, 0.0, 1.0);
- auto speed_per_pixel = easing_slope_at(progress) / duration_in_seconds;
- auto distance = m_destination_offset - m_start_offset;
- return { static_cast<float>(distance.x() * speed_per_pixel), static_cast<float>(distance.y() * speed_per_pixel) };
+ return RustFFI::smooth_scroll_animation_kind(m_animation);
}
SmoothScrollAnimation::Sample SmoothScrollAnimation::sample(AK::Duration elapsed) const
{
- auto elapsed_since_start = elapsed - m_start_time;
- if (m_duration.is_zero() || elapsed_since_start >= m_duration)
- return { m_destination_offset, true };
-
- auto progress = clamp(elapsed_since_start.to_seconds_f64() / m_duration.to_seconds_f64(), 0.0, 1.0);
- auto eased_progress = eased_progress_at(progress);
-
- return {
- {
- static_cast<float>(m_start_offset.x() + (m_destination_offset.x() - m_start_offset.x()) * eased_progress),
- static_cast<float>(m_start_offset.y() + (m_destination_offset.y() - m_start_offset.y()) * eased_progress),
- },
- false,
- };
+ Sample sample;
+ sample.complete = RustFFI::smooth_scroll_animation_sample(m_animation, elapsed.to_nanoseconds(), &sample.offset);
+ return sample;
}
void SmoothScrollAnimation::retarget(Gfx::FloatPoint destination_offset, AK::Duration elapsed)
{
- if (destination_offset == m_destination_offset)
- return;
-
- auto current_offset = sample(elapsed).offset;
- auto remaining_distance = destination_offset - current_offset;
- auto remaining_length = AK::hypot(static_cast<double>(remaining_distance.x()), static_cast<double>(remaining_distance.y()));
-
- // Only the speed along the new path carries over.
- double velocity = 0;
- if (remaining_length != 0) {
- auto velocity_vector = velocity_at(elapsed);
- velocity = (static_cast<double>(velocity_vector.x()) * remaining_distance.x() + static_cast<double>(velocity_vector.y()) * remaining_distance.y()) / remaining_length;
- }
-
- auto duration = duration_for_distance(remaining_distance);
-
- // An animation moving faster than the remaining distance needs would swing past the destination and back.
- if (velocity > 0)
- duration = min(duration, AK::Duration::from_seconds_f64(remaining_length / velocity * retarget_ease_out_allowance));
-
- m_start_offset = current_offset;
- m_destination_offset = destination_offset;
- m_start_time = elapsed;
- m_duration = duration;
- m_easing_control_point_y1 = 0;
-
- if (duration.is_zero() || remaining_length == 0)
- return;
-
- // The curve's starting slope is y1 / x1.
- auto slope = velocity * duration.to_seconds_f64() / remaining_length;
- m_easing_control_point_y1 = easing_control_point_x1 * clamp(slope, -maximum_easing_slope, maximum_easing_slope);
+ RustFFI::smooth_scroll_animation_retarget(m_animation, destination_offset, elapsed.to_nanoseconds());
}
}
diff --git a/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.h b/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.h
index c0a7f61ee46..e426b924d81 100644
--- a/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.h
+++ b/Libraries/LibCompositing/Scrolling/SmoothScrollAnimation.h
@@ -13,10 +13,11 @@
namespace Compositing {
-// During a momentum scroll, each frame moves this fraction of the distance of the frame before it.
-inline constexpr double momentum_distance_share_per_frame = 0.92;
-inline constexpr double momentum_frame_duration_in_seconds = 0.016;
-inline constexpr double maximum_momentum_duration_in_seconds = 5.0;
+namespace RustFFI {
+
+struct SmoothScrollAnimation;
+
+}
class COMPOSITING_API SmoothScrollAnimation {
public:
@@ -27,32 +28,18 @@ public:
SmoothScrollAnimation(Gfx::FloatPoint start_offset, Gfx::FloatPoint destination_offset, double pixels_per_css_pixel, ScrollAnimationKind = ScrollAnimationKind::SmoothScroll);
- AK::Duration duration() const { return m_duration; }
- Gfx::FloatPoint destination_offset() const { return m_destination_offset; }
- ScrollAnimationKind kind() const { return m_kind; }
- Sample sample(AK::Duration elapsed) const;
+ ~SmoothScrollAnimation();
+ SmoothScrollAnimation(SmoothScrollAnimation&&);
+ SmoothScrollAnimation& operator=(SmoothScrollAnimation&&);
+ SmoothScrollAnimation(SmoothScrollAnimation const&) = delete;
+ SmoothScrollAnimation& operator=(SmoothScrollAnimation const&) = delete;
+ ScrollAnimationKind kind() const;
+ Sample sample(AK::Duration elapsed) const;
void retarget(Gfx::FloatPoint destination_offset, AK::Duration elapsed);
- // Moves where the scroll comes from and goes to by the same distance, which keeps its pace.
- void shift_by(Gfx::FloatPoint delta)
- {
- m_start_offset.translate_by(delta);
- m_destination_offset.translate_by(delta);
- }
private:
- AK::Duration duration_for_distance(Gfx::FloatPoint distance) const;
- double eased_progress_at(double progress) const;
- double easing_slope_at(double progress) const;
- Gfx::FloatPoint velocity_at(AK::Duration elapsed) const;
-
- Gfx::FloatPoint m_start_offset;
- Gfx::FloatPoint m_destination_offset;
- double m_pixels_per_css_pixel { 1 };
- AK::Duration m_start_time;
- AK::Duration m_duration;
- ScrollAnimationKind m_kind { ScrollAnimationKind::SmoothScroll };
- double m_easing_control_point_y1 { 0 };
+ RustFFI::SmoothScrollAnimation* m_animation;
};
}
diff --git a/Libraries/LibCompositing/Scrolling/WheelGestureIdentity.cpp b/Libraries/LibCompositing/Scrolling/WheelGestureIdentity.cpp
deleted file mode 100644
index b00ee7556d2..00000000000
--- a/Libraries/LibCompositing/Scrolling/WheelGestureIdentity.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCompositing/Scrolling/WheelGestureIdentity.h>
-#include <LibCompositing/Types.h>
-#include <LibWebCommon/Page/InputEvent.h>
-
-namespace Compositing {
-
-WheelGestureIdentity::WheelGestureIdentity(Kind kind, Gfx::FloatPoint first_position, u32 modifiers, MonotonicTime now)
- : m_kind(kind)
- , m_first_position(first_position)
- , m_modifiers(modifiers)
- , m_last_event_time(now)
-{
-}
-
-WheelGestureIdentity::Kind WheelGestureIdentity::kind_for(Web::ScrollGesturePhase phase)
-{
- return phase == Web::ScrollGesturePhase::None ? Kind::PhaseLess : Kind::Phased;
-}
-
-WheelGestureIdentity WheelGestureIdentity::started_by(Gfx::FloatPoint position, Web::ScrollGesturePhase phase, u32 modifiers, MonotonicTime now)
-{
- WheelGestureIdentity gesture { kind_for(phase), position, modifiers, now };
- gesture.advance_to(phase, now);
- return gesture;
-}
-
-bool WheelGestureIdentity::is_held_by_fingers() const
-{
- return m_kind == Kind::Phased && !m_ended_at.has_value() && !m_momentum_has_started;
-}
-
-bool WheelGestureIdentity::is_continued_by(Gfx::FloatPoint position, Web::ScrollGesturePhase phase, u32 modifiers, MonotonicTime now, float position_slop, TouchpadGestureEnd touchpad_gesture_end) const
-{
- bool lasts_while_fingers_rest = touchpad_gesture_end == TouchpadGestureEnd::WhenFingersLift && is_held_by_fingers();
- if (!lasts_while_fingers_rest && now - m_last_event_time > user_scroll_settle_delay)
- return false;
- if (kind_for(phase) != m_kind)
- return false;
- if (m_kind == Kind::PhaseLess)
- return modifiers == m_modifiers && position.distance_from(m_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 == Web::ScrollGesturePhase::Ongoing && m_momentum_has_started)
- return false;
- if (!m_ended_at.has_value())
- return true;
- bool phase_may_follow_an_ended_gesture = phase == Web::ScrollGesturePhase::Momentum || phase == Web::ScrollGesturePhase::Ended;
- return phase_may_follow_an_ended_gesture && now - *m_ended_at <= wheel_gesture_momentum_grace_after_end;
-}
-
-void WheelGestureIdentity::advance_to(Web::ScrollGesturePhase phase, MonotonicTime now)
-{
- m_last_event_time = now;
- if (phase == Web::ScrollGesturePhase::Momentum)
- m_momentum_has_started = true;
- if (phase != Web::ScrollGesturePhase::Ended) {
- m_ended_at.clear();
- return;
- }
- if (!m_ended_at.has_value())
- m_ended_at = now;
-}
-
-}
diff --git a/Libraries/LibCompositing/Scrolling/WheelGestureIdentity.h b/Libraries/LibCompositing/Scrolling/WheelGestureIdentity.h
deleted file mode 100644
index b5fba19665e..00000000000
--- a/Libraries/LibCompositing/Scrolling/WheelGestureIdentity.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Time.h>
-#include <AK/Types.h>
-#include <LibCompositing/Export.h>
-#include <LibCompositing/Forward.h>
-#include <LibGfx/Point.h>
-
-namespace Compositing {
-
-inline constexpr AK::Duration wheel_gesture_momentum_grace_after_end = AK::Duration::from_milliseconds(100);
-inline constexpr float wheel_gesture_position_slop_in_css_pixels = 10;
-
-// 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.
-enum class TouchpadGestureEnd : u8 {
- AfterIdleDelay,
- WhenFingersLift,
-};
-
-// 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.
-class COMPOSITING_API WheelGestureIdentity {
-public:
- static WheelGestureIdentity started_by(Gfx::FloatPoint position, Web::ScrollGesturePhase, u32 modifiers, MonotonicTime now);
-
- // Positions and the slop are in whatever unit the caller routes in.
- bool is_continued_by(Gfx::FloatPoint position, Web::ScrollGesturePhase, u32 modifiers, MonotonicTime now, float position_slop, TouchpadGestureEnd) const;
- // Whether the fingers of a touchpad gesture are still on the touchpad, before it ends or hands over to momentum.
- bool is_held_by_fingers() const;
- void advance_to(Web::ScrollGesturePhase, MonotonicTime now);
-
-private:
- enum class Kind : u8 {
- PhaseLess,
- Phased,
- };
-
- WheelGestureIdentity(Kind, Gfx::FloatPoint first_position, u32 modifiers, MonotonicTime now);
-
- static Kind kind_for(Web::ScrollGesturePhase);
-
- Kind m_kind;
- Gfx::FloatPoint m_first_position;
- u32 m_modifiers { 0 };
- MonotonicTime m_last_event_time;
- Optional<MonotonicTime> m_ended_at;
- bool m_momentum_has_started { false };
-};
-
-}
diff --git a/Libraries/LibCompositing/Types.h b/Libraries/LibCompositing/Types.h
index 56f3cc384db..fa30a697bd5 100644
--- a/Libraries/LibCompositing/Types.h
+++ b/Libraries/LibCompositing/Types.h
@@ -16,6 +16,7 @@
#include <AK/Vector.h>
#include <LibCompositing/Export.h>
#include <LibCompositing/Scrolling/AsyncScrollingState.h>
+#include <LibCompositing/Scrolling/ScrollSnapSelection.h>
#include <LibIPC/Forward.h>
#include <LibWebCommon/Page/CompositorContextId.h>
#include <LibWebCommon/Page/InputEvent.h>
@@ -51,6 +52,18 @@ enum class ScrollAnimationKind : u8 {
Momentum,
};
+// Where the first step of a wheel gesture over a position goes, as far as the admission and the hit test decide it.
+struct FirstWheelStepRoute {
+ Web::InputRoutingDecision decision;
+ Optional<Web::AsyncScrollNodeStableID> scroller {};
+};
+
+struct FirstWheelStepRouteForTesting {
+ FirstWheelStepRoute route;
+ // The document whose scrolling state decided the route.
+ Optional<Web::UniqueNodeID> document_id;
+};
+
// A scroll the compositor started for user input of its own: the main thread registers it as a user scroll in
// flight. A scroll started for a step of a gesture is owed the scrollend event by that gesture, which continues
// from the offset its steps have asked for; a scroll started for the end of a gesture settles the gesture. The
@@ -102,14 +115,6 @@ struct PendingAsyncScrollUpdates {
Optional<Web::AsyncScrollNodeStableID> wheel_latched_scroller;
};
-struct AsyncScrollEnqueueResult {
- bool accepted { false };
- Optional<AsyncScrollOperationID> operation_id {};
- // Why the compositor took or turned away a wheel step, and the scroller it routed the step to.
- Optional<Web::InputRoutingDecision> routing_decision {};
- Optional<Web::AsyncScrollNodeStableID> routed_scroller {};
-};
-
// What the compositor did with a wheel event that WebContent's main thread passed on to it, as the compositor does with
// the UI's wheel events before the main thread gets them.
struct WheelEventAnswer {
diff --git a/Libraries/LibCompositing/Types.ipc b/Libraries/LibCompositing/Types.ipc
index 49c5c5a7083..34ce233f3b8 100644
--- a/Libraries/LibCompositing/Types.ipc
+++ b/Libraries/LibCompositing/Types.ipc
@@ -20,17 +20,11 @@ enum Compositing::ContextVisibility : u8 {
Hidden,
}
-[ExistingCpp]
-enum Compositing::AsyncScrollUpdateFreshness : u8 {
- Pushed,
- FromCompositor,
-}
-
[ExistingCpp]
enum Compositing::ScrollAnimationKind : u8 {
- SmoothScroll,
- Wheel,
- Momentum,
+ SmoothScroll = 0,
+ Wheel = 1,
+ Momentum = 2,
}
[ExistingCpp]
diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.h
index 0e901fc8b59..b13801702a4 100644
--- a/Libraries/LibWeb/Compositor/CompositorConnection.h
+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h
@@ -16,7 +16,6 @@
#include <LibCompositing/DisplayList/Canvas2DCommandStream.h>
#include <LibCompositing/DisplayList/DisplayList.h>
#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>
-#include <LibCompositing/Scrolling/AsyncScrollTree.h>
#include <LibCompositing/Scrolling/ScrollState.h>
#include <LibCompositing/Types.h>
#include <LibCompositing/WebGL/Types.h>
diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.h
index bdfcd59cccf..de8dea7b887 100644
--- a/Libraries/LibWeb/Compositor/CompositorHost.h
+++ b/Libraries/LibWeb/Compositor/CompositorHost.h
@@ -16,7 +16,6 @@
#include <AK/Vector.h>
#include <AK/Weakable.h>
#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>
-#include <LibCompositing/Scrolling/AsyncScrollTree.h>
#include <LibCompositing/Types.h>
#include <LibCompositing/Video/VideoFrameHold.h>
#include <LibGfx/Bitmap.h>
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 20bc2de5273..89a4eebf9f0 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -14,8 +14,7 @@
#include <AK/Utf16StringBuilder.h>
#include <LibAudio/ClientConnection.h>
#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>
-#include <LibCompositing/Scrolling/AsyncScrollTree.h>
-#include <LibCompositing/Scrolling/AsyncScrollingState.h>
+#include <LibCompositing/Scrolling/RecordedDisplayListScrolling.h>
#include <LibCore/EventLoop.h>
#include <LibCore/System.h>
#include <LibCore/TimeZone.h>
@@ -1081,7 +1080,7 @@ GC::Ref<JS::Object> Internals::compositor_scroll_state(GC::Ptr<DOM::Element> scr
scroll_state = navigable->compositor_context().scroll_state_for_testing(stretched_scroller);
auto report = JsonValue::from_string(scroll_state);
if (report.is_error() || !report.value().is_object())
- return scrolling_state_report_to_object(window(), Compositing::async_scrolling_state_to_json({}));
+ report = JsonValue::from_string(Compositing::async_scrolling_state_as_json(nullptr));
return scrolling_state_report_to_object(window(), report.value().as_object());
}
@@ -1697,60 +1696,30 @@ GC::Ref<JS::Object> Internals::compositor_wheel_target_at(double x, double y, do
return first_wheel_step_route_to_object(result.value_or({ .route = { InputRoutingDecision::NoAnswerFromCompositor }, .document_id = {} }));
}
-namespace {
-
-struct RecordedScrollTree {
- Compositing::AsyncScrollTree scroll_tree;
- Compositing::AccumulatedVisualContextTree visual_context_tree;
- Compositing::WheelRoutingAdmission admission;
-};
-
-}
-
-// The scroll tree of the display list the document last recorded, as the compositor builds it once the list reaches it.
-static Optional<RecordedScrollTree> recorded_scroll_tree_of(DOM::Document& document, Layout::BegunRead const& read)
-{
- auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();
- if (!display_list)
- return {};
- RecordedScrollTree recorded {
- .scroll_tree = {},
- .visual_context_tree = document.paint_state().visual_context_tree_without_update(read, document),
- .admission = {},
- };
- auto async_scrolling_state = Compositing::async_scrolling_state_from_display_list(*display_list);
- recorded.admission = Compositing::wheel_routing_admission_for(async_scrolling_state, document.wheel_event_listener_state_generation());
- recorded.scroll_tree.set_state(move(async_scrolling_state));
- recorded.scroll_tree.rebuild_wheel_hit_test_targets(display_list, &recorded.visual_context_tree, document.scroll_state_snapshot());
- return recorded;
-}
-
GC::Ref<JS::Object> Internals::recorded_display_list_wheel_target_at(double x, double y, double delta_x, double delta_y)
{
// A script reads the render state, which waits for a frame in flight.
Layout::ForcedReadScope read { window().associated_document() };
- auto recorded = recorded_scroll_tree_of(window().associated_document(), read);
- if (!recorded.has_value())
+ auto& document = window().associated_document();
+ auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();
+ if (!display_list)
return first_wheel_step_route_to_object({ .route = { InputRoutingDecision::NoAsyncScrollingState }, .document_id = {} });
- auto const& scroll_tree = recorded->scroll_tree;
-
+ auto visual_context_tree = document.paint_state().visual_context_tree_without_update(read, document);
auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));
- auto delta = Gfx::FloatPoint { static_cast<float>(delta_x), static_cast<float>(delta_y) }.scaled(static_cast<float>(scroll_tree.device_pixels_per_css_pixel()));
- return first_wheel_step_route_to_object({
- .route = scroll_tree.route_first_wheel_step(recorded->admission, recorded->visual_context_tree, position, delta),
- .document_id = scroll_tree.document_id(),
- });
+ return first_wheel_step_route_to_object(Compositing::route_first_wheel_step_through_recorded_display_list(*display_list, visual_context_tree, document.scroll_state_snapshot(), document.wheel_event_listener_state_generation(), position, { static_cast<float>(delta_x), static_cast<float>(delta_y) }));
}
bool Internals::recorded_display_list_blocks_wheel_event_at(double x, double y)
{
// A script reads the render state, which waits for a frame in flight.
Layout::ForcedReadScope read { window().associated_document() };
- auto recorded = recorded_scroll_tree_of(window().associated_document(), read);
- if (!recorded.has_value())
+ auto& document = window().associated_document();
+ auto* display_list = document.paint_state().display_list_used_as_paint_command_cache_source();
+ if (!display_list)
return false;
+ auto visual_context_tree = document.paint_state().visual_context_tree_without_update(read, document);
auto position = device_position_as_float_point(page().css_to_device_point({ x, y }));
- return recorded->scroll_tree.blocks_wheel_event_at_position(recorded->visual_context_tree, position);
+ return Compositing::recorded_display_list_blocks_wheel_event_at(*display_list, visual_context_tree, document.scroll_state_snapshot(), position);
}
void Internals::record_display_list_for_testing(bool paint_overlay, bool cold)
@@ -4071,8 +4040,8 @@ GC::Ref<JS::Object> Internals::style_invalidation_counters_object() const
GC::Ref<JS::Object> Internals::recorded_async_scrolling_state_object()
{
auto* display_list = window().associated_document().paint_state().display_list_used_as_paint_command_cache_source();
- auto state = display_list ? Compositing::async_scrolling_state_from_display_list(*display_list) : Compositing::AsyncScrollingState {};
- return scrolling_state_report_to_object(window(), Compositing::async_scrolling_state_to_json(state));
+ auto report = MUST(JsonValue::from_string(Compositing::async_scrolling_state_as_json(display_list)));
+ return scrolling_state_report_to_object(window(), report.as_object());
}
}
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 384fd03e64a..51e01e0922d 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -6,8 +6,8 @@
#pragma once
-#include <LibCompositing/Scrolling/AsyncScrollTree.h>
#include <LibCompositing/Scrolling/AsyncScrollingState.h>
+#include <LibCompositing/Types.h>
#include <LibGC/Root.h>
#include <LibWeb/Bindings/Internals.h>
#include <LibWeb/DOM/Document.h>
diff --git a/Libraries/LibWeb/Painting/ScrollSnap.cpp b/Libraries/LibWeb/Painting/ScrollSnap.cpp
index b23e444ea3d..6e62ba550b5 100644
--- a/Libraries/LibWeb/Painting/ScrollSnap.cpp
+++ b/Libraries/LibWeb/Painting/ScrollSnap.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/AnyOf.h>
#include <LibWeb/CSS/Enums.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
@@ -15,18 +14,6 @@
namespace Web::Painting {
-using Compositing::SnapAxisCandidates;
-using Compositing::SnapAxisSelection;
-using Compositing::SnapPositionCandidate;
-
-static_assert(to_underlying(CSS::ScrollSnapAlign::None) == to_underlying(Compositing::SnapAlign::None));
-static_assert(to_underlying(CSS::ScrollSnapAlign::Start) == to_underlying(Compositing::SnapAlign::Start));
-static_assert(to_underlying(CSS::ScrollSnapAlign::End) == to_underlying(Compositing::SnapAlign::End));
-static_assert(to_underlying(CSS::ScrollSnapAlign::Center) == to_underlying(Compositing::SnapAlign::Center));
-static_assert(to_underlying(CSS::ScrollSnapStrictness::None) == to_underlying(Compositing::SnapStrictness::None));
-static_assert(to_underlying(CSS::ScrollSnapStrictness::Proximity) == to_underlying(Compositing::SnapStrictness::Proximity));
-static_assert(to_underlying(CSS::ScrollSnapStrictness::Mandatory) == to_underlying(Compositing::SnapStrictness::Mandatory));
-
// The element a snap area's box belongs to, which is the generating element of a pseudo-element's box.
static DOM::Element const* element_of_snap_area(Compositing::SnapAreaIdentity const& area)
{
@@ -35,53 +22,6 @@ static DOM::Element const* element_of_snap_area(Compositing::SnapAreaIdentity co
return as_if<DOM::Element>(DOM::Node::from_unique_id(area.node_id));
}
-// https://drafts.csswg.org/css-scroll-snap-1/#snap-axis
-static Compositing::SnapAxes snap_axes_of_scroll_container(Layout::Node const& snap_container)
-{
- auto axes = Layout::RustFFI::layout_row_scroll_snap_axes(snap_container.document_host(), Layout::Node::slot_id(&snap_container));
- return { .x = axes.x, .y = axes.y };
-}
-
-// The geometry snap position selection runs over, collected from the layout of a snap container and of the snap areas
-// it captures.
-static Optional<Compositing::SnapContainerGeometry> snap_container_geometry(Layout::Node const& snap_container)
-{
- if (!has_committed_box(snap_container))
- return {};
-
- Layout::RustFFI::FfiSnapContainerGeometry geometry {};
- if (!Layout::RustFFI::layout_row_snap_container_geometry(snap_container.document_host(), committed_row_slot(snap_container), &geometry))
- return {};
-
- return Compositing::SnapContainerGeometry {
- .snapport = geometry.snapport,
- .min_scroll_offset = geometry.min_scroll_offset,
- .max_scroll_offset = geometry.max_scroll_offset,
- .strictness = static_cast<Compositing::SnapStrictness>(geometry.strictness),
- .axes = { .x = geometry.axes.x, .y = geometry.axes.y },
- .horizontal_writing_mode = geometry.horizontal_writing_mode,
- };
-}
-
-static Vector<Compositing::SnapAreaGeometry> collect_snap_areas(Layout::Node const& snap_container)
-{
- Vector<Compositing::SnapAreaGeometry> areas;
- if (!has_committed_box(snap_container))
- return areas;
-
- Layout::RustFFI::render_state_for_each_snap_area(
- snap_container.document_host(), committed_row_slot(snap_container), &areas, [](void* context, Layout::RustFFI::FfiSnapAreaGeometry const* area) {
- static_cast<Vector<Compositing::SnapAreaGeometry>*>(context)->append({
- .identity = { UniqueNodeID { area->node_id }, area->pseudo_element_type },
- .rect = area->rect,
- .align_x = static_cast<Compositing::SnapAlign>(area->align_x),
- .align_y = static_cast<Compositing::SnapAlign>(area->align_y),
- .always_stop = area->always_stop,
- });
- });
- return areas;
-}
-
// https://drafts.csswg.org/css-scroll-snap-1/#scroll-snap-container
bool is_scroll_snap_container(Layout::Node const& node)
{
@@ -99,7 +39,8 @@ bool is_scroll_snap_container(Layout::Node const& node)
if (!misc_interaction_values || misc_interaction_values->scroll_snap_strictness_value() == CSS::ScrollSnapStrictness::None)
return false;
}
- return !snap_axes_of_scroll_container(node).is_empty();
+ auto axes = Layout::RustFFI::layout_row_scroll_snap_axes(node.document_host(), Layout::Node::slot_id(&node));
+ return axes.x || axes.y;
}
void take_built_scroll_container(Layout::BegunRead const& read, DOM::Document& document, Compositing::RustFFI::NodeSlotId slot, bool is_scroll_snap_container)
@@ -117,13 +58,43 @@ void take_built_scroll_container(Layout::BegunRead const& read, DOM::Document& d
document.forget_snapped_areas_of_scroll_container(*scroll_container);
}
+static Compositing::SnapAreaIdentity snap_area_identity(Layout::RustFFI::FfiSnapAreaIdentity area)
+{
+ return { UniqueNodeID { area.node_id }, area.pseudo_element_type };
+}
+
+static void receive_snap_destination(void* receiver, Layout::RustFFI::FfiSnapDestination const* destination)
+{
+ Compositing::SnapDestination result {
+ .position = destination->position,
+ .snapped_x = destination->snapped_x,
+ .snapped_y = destination->snapped_y,
+ .evaluated_x = destination->evaluated_x,
+ .evaluated_y = destination->evaluated_y,
+ };
+ for (auto area : destination->snapped_areas_x)
+ result.snapped_areas.x.append(snap_area_identity(area));
+ for (auto area : destination->snapped_areas_y)
+ result.snapped_areas.y.append(snap_area_identity(area));
+ *static_cast<Compositing::SnapDestination*>(receiver) = move(result);
+}
+
// https://drafts.csswg.org/css-scroll-snap-1/#choosing
Compositing::SnapDestination adjust_scroll_destination_for_snapping(Layout::Node const& snap_container, CSSPixelPoint destination, Compositing::SnapSelectionStrategy const& strategy)
{
- auto geometry = snap_container_geometry(snap_container);
- if (!geometry.has_value() || Compositing::axes_to_evaluate(geometry->axes, strategy).is_empty())
- return { destination };
- return Compositing::select_snap_destination(*geometry, collect_snap_areas(snap_container), destination, strategy);
+ Compositing::SnapDestination result { destination };
+ if (!has_committed_box(snap_container))
+ return result;
+ Layout::RustFFI::FfiSnapSelectionStrategy ffi_strategy {
+ .type = strategy.type,
+ .has_start_offset = strategy.start_offset.has_value(),
+ .start_offset = strategy.start_offset.value_or({}),
+ .displacement = strategy.displacement,
+ .has_starting_positions_boundary = strategy.starting_positions_boundary.has_value(),
+ .starting_positions_boundary = strategy.starting_positions_boundary.value_or({}),
+ };
+ Layout::RustFFI::render_state_select_snap_destination(snap_container.document_host(), committed_row_slot(snap_container), destination, &ffi_strategy, &result, receive_snap_destination);
+ return result;
}
static bool snap_area_contains_node(Compositing::SnapAreaIdentity const& area, DOM::Node const& node)
@@ -135,234 +106,51 @@ static bool snap_area_contains_node(Compositing::SnapAreaIdentity const& area, D
return element && element->is_inclusive_ancestor_of(node);
}
-static CSSPixels resnap_offset_for_candidate(Compositing::SnapPositionCandidate const& candidate, CSSPixels axis_current_offset)
+static bool area_contains_focused_node(void* context, Layout::RustFFI::FfiSnapAreaIdentity area)
{
- // A scroll container resting at one of its snapped area's valid snap positions is still snapped to that area and
- // stays where it is.
- if (Compositing::candidate_has_snap_position_at(candidate, axis_current_offset))
- return axis_current_offset;
- return candidate.offset;
+ auto const& selection = *static_cast<ResnapSelection const*>(context);
+ return selection.focused_node && snap_area_contains_node(snap_area_identity(area), *selection.focused_node);
}
-// The box each axis is snapped to, as an index into that axis's candidate list.
-struct SnappedAxisBoxes {
- Optional<size_t> x_candidate;
- Optional<size_t> y_candidate;
-};
-
-// https://drafts.csswg.org/css-scroll-snap-1/#multiple-aligned-snap-areas
-// When snapping to a scroll position that is aligned with multiple scroll snap areas, the following algorithm procedure
-// is used to determined which box is snapped on the block and inline axes for a particular scroll container:
-// NB: Every step treats the block and inline lists alike, so the steps are carried out on the physical axes directly.
-static SnappedAxisBoxes select_between_multiple_aligned_snap_areas(Compositing::SnapAxisCandidates const& candidates, ResnapSelection const& selection, CSSPixelPoint scroll_position)
+static bool area_contains_targeted_element(void* context, Layout::RustFFI::FfiSnapAreaIdentity area)
{
- // 1. Let scroll position be the scroll position of the scroll container
- // NB: The scroll position is the offset the content change left the container resting at.
-
- // 2. Let inline be the set of boxes whose scroll snap areas are aligned at this scroll position in the inline axis.
- // 3. Let block be the set of boxes whose scroll snap areas are aligned at this scroll position in the block axis.
- // AD-HOC: Only the snap areas the container was snapped to before the content change take part, since a re-snap
- // must return the container to those same areas rather than to whichever areas the change left aligned. An
- // area whose snap position would leave it outside the snapport in the other axis no longer offers a valid
- // snap position and does not take part either.
- // NB: A box is held as the index of its snap position candidate in its axis's candidate list, which holds its
- // candidates in tree order.
- auto aligned_boxes = [](Vector<Compositing::SnapPositionCandidate> const& axis_candidates, Vector<Compositing::SnapAreaIdentity> const& snapped_areas, CSSPixels cross_axis_offset) {
- Vector<size_t> boxes;
- for (size_t candidate_index = 0; candidate_index < axis_candidates.size(); ++candidate_index) {
- auto const& candidate = axis_candidates[candidate_index];
- if (!candidate.area.is_valid() || !snapped_areas.contains_slow(candidate.area))
- continue;
- if (!Compositing::snap_area_is_visible_at_cross_axis_offset(candidate, cross_axis_offset))
- continue;
- boxes.append(candidate_index);
- }
- return boxes;
- };
- auto x_boxes = aligned_boxes(candidates.x_candidates, selection.snapped_areas.x, scroll_position.y());
- auto y_boxes = aligned_boxes(candidates.y_candidates, selection.snapped_areas.y, scroll_position.x());
-
- // 4. For each list of block and inline:
- auto remove_superseded_boxes = [&](Vector<size_t>& boxes, Vector<Compositing::SnapPositionCandidate> const& axis_candidates) {
- auto keep_only_boxes_matching = [&](auto const& predicate) {
- if (!any_of(boxes, [&](size_t candidate_index) { return predicate(axis_candidates[candidate_index].area); }))
- return false;
- boxes.remove_all_matching([&](size_t candidate_index) { return !predicate(axis_candidates[candidate_index].area); });
- return true;
- };
-
- // 1. If list contains one or more boxes that are focused or have a focused descendant, remove all other boxes
- // from list
- bool kept_focused_boxes = selection.focused_node && keep_only_boxes_matching([&](Compositing::SnapAreaIdentity const& area) { return snap_area_contains_node(area, *selection.focused_node); });
-
- // 2. Else if list contains one or more boxes that are targetted or have a targetted descendant, remove all
- // other boxes from list.
- if (!kept_focused_boxes && selection.targeted_element)
- keep_only_boxes_matching([&](Compositing::SnapAreaIdentity const& area) { return snap_area_contains_node(area, *selection.targeted_element); });
-
- // 3. For each box in list:
- // 1. Remove any box from list which is an ancestor of box.
- auto boxes_before_ancestor_removal = boxes;
- boxes.remove_all_matching([&](size_t candidate_index) {
- auto const& area = axis_candidates[candidate_index].area;
- if (area.is_pseudo_element())
- return false;
- auto const* element = element_of_snap_area(area);
- if (!element)
- return false;
- return any_of(boxes_before_ancestor_removal, [&](size_t other_index) {
- auto const* other_element = element_of_snap_area(axis_candidates[other_index].area);
- return other_element && other_element != element && element->is_inclusive_ancestor_of(*other_element);
- });
- });
- };
- remove_superseded_boxes(x_boxes, candidates.x_candidates);
- remove_superseded_boxes(y_boxes, candidates.y_candidates);
-
- auto boxes_contain_area = [](Vector<size_t> const& boxes, Vector<Compositing::SnapPositionCandidate> const& axis_candidates, Compositing::SnapAreaIdentity const& area) {
- return any_of(boxes, [&](size_t candidate_index) { return axis_candidates[candidate_index].area == area; });
- };
- bool axis_sets_overlap = any_of(x_boxes, [&](size_t candidate_index) {
- return boxes_contain_area(y_boxes, candidates.y_candidates, candidates.x_candidates[candidate_index].area);
- });
- // 5. If inline and block are overlapping sets:
- if (axis_sets_overlap) {
- // 1. Replace inline with the intersection of inline and block.
- x_boxes.remove_all_matching([&](size_t candidate_index) {
- return !boxes_contain_area(y_boxes, candidates.y_candidates, candidates.x_candidates[candidate_index].area);
- });
-
- // 2. Replace block with the intersection of inline and block.
- // NB: The intersection is unchanged by the step before it, so the narrowed list gives the same result the
- // original one would.
- y_boxes.remove_all_matching([&](size_t candidate_index) {
- return !boxes_contain_area(x_boxes, candidates.x_candidates, candidates.y_candidates[candidate_index].area);
- });
- }
+ auto const& selection = *static_cast<ResnapSelection const*>(context);
+ return selection.targeted_element && snap_area_contains_node(snap_area_identity(area), *selection.targeted_element);
+}
- // 6. Select the first element in tree order from inline as the snapped inline axis box.
- // 7. Select the first element in tree order from block as the snapped block axis box.
- return {
- .x_candidate = x_boxes.is_empty() ? OptionalNone {} : Optional<size_t> { x_boxes.first() },
- .y_candidate = y_boxes.is_empty() ? OptionalNone {} : Optional<size_t> { y_boxes.first() },
- };
+static bool element_of_area_is_ancestor_of_element_of(void*, Layout::RustFFI::FfiSnapAreaIdentity ffi_area, Layout::RustFFI::FfiSnapAreaIdentity other_area)
+{
+ auto area = snap_area_identity(ffi_area);
+ if (area.is_pseudo_element())
+ return false;
+ auto const* element = element_of_snap_area(area);
+ if (!element)
+ return false;
+ auto const* other_element = element_of_snap_area(snap_area_identity(other_area));
+ return other_element && other_element != element && element->is_inclusive_ancestor_of(*other_element);
}
Compositing::SnapDestination select_resnap_destination(Layout::Node const& snap_container, CSSPixelPoint current_offset, ResnapSelection const& selection)
{
- auto geometry = snap_container_geometry(snap_container);
- if (!geometry.has_value() || geometry->axes.is_empty())
- return { current_offset };
- auto snap_axes = geometry->axes;
-
- auto candidates = Compositing::build_snap_candidates(*geometry, collect_snap_areas(snap_container), snap_axes);
-
- // NB: A container that was not snapped before the change, or whose snapped areas are all gone, re-snaps the way a
- // fresh scroll to the current position would.
- auto resnap_afresh = [&] {
- return Compositing::select_snap_destination(*geometry, candidates, current_offset, {}, snap_axes);
- };
- if (selection.snapped_areas.is_empty())
- return resnap_afresh();
-
- auto [x_chosen_candidate, y_chosen_candidate] = select_between_multiple_aligned_snap_areas(candidates, selection, current_offset);
-
- if (!x_chosen_candidate.has_value() && !y_chosen_candidate.has_value())
- return resnap_afresh();
-
- auto fallback_offset_for_axis = [&](Vector<Compositing::SnapPositionCandidate> const& axis_candidates, CSSPixels axis_current_offset, CSSPixels axis_snapport_size, CSSPixels cross_axis_offset) {
- Compositing::SnapAxisSelection axis_selection {
- .destination = axis_current_offset,
- .start = axis_current_offset,
- .direction = 0,
- .starting_positions_boundary = {},
- };
- auto choice = Compositing::choose_snap_offset_for_axis(axis_candidates, axis_selection, axis_snapport_size, geometry->strictness, cross_axis_offset);
- return choice.map([](auto const& axis_choice) { return axis_choice.offset; });
+ Compositing::SnapDestination result { current_offset };
+ if (!has_committed_box(snap_container))
+ return result;
+ auto identities = [](auto const& areas) {
+ Vector<Layout::RustFFI::FfiSnapAreaIdentity> result;
+ for (auto const& area : areas)
+ result.append({ area.node_id.value(), area.pseudo_element_type });
+ return result;
};
-
- // An axis whose snapped areas are all gone re-snaps afresh, from the snap positions reachable while the other
- // axis follows its own snapped area.
- Optional<CSSPixels> x_offset;
- Optional<CSSPixels> y_offset;
- if (x_chosen_candidate.has_value())
- x_offset = resnap_offset_for_candidate(candidates.x_candidates[*x_chosen_candidate], current_offset.x());
- if (y_chosen_candidate.has_value())
- y_offset = resnap_offset_for_candidate(candidates.y_candidates[*y_chosen_candidate], current_offset.y());
- if (snap_axes.x && !x_chosen_candidate.has_value())
- x_offset = fallback_offset_for_axis(candidates.x_candidates, current_offset.x(), geometry->snapport.width(), y_offset.value_or(current_offset.y()));
- if (snap_axes.y && !y_chosen_candidate.has_value())
- y_offset = fallback_offset_for_axis(candidates.y_candidates, current_offset.y(), geometry->snapport.height(), x_offset.value_or(current_offset.x()));
-
- // https://drafts.csswg.org/css-scroll-snap-1/#re-snap
- // If it is not possible to snap to both (e.g. if snapping to one resulted in the other being offscreen), it must
- // prefer the focused box, followed by the targeted box, followed by the block axis if neither box is focused or
- // targeted.
- // NB: The preferred box is snapped in both axes: the other axis takes the box's own snap position when it defines
- // one, and otherwise re-snaps among the positions at which the preferred box remains visible.
- if (x_offset.has_value() && y_offset.has_value() && !Compositing::chosen_offsets_are_mutually_visible(candidates, *x_offset, *y_offset)) {
- bool block_axis_is_y = geometry->horizontal_writing_mode;
-
- struct ResnapAxis {
- Vector<Compositing::SnapPositionCandidate> const& candidates;
- Optional<size_t>& chosen_candidate;
- Optional<CSSPixels>& offset;
- Optional<Compositing::SnapAreaIdentity> area;
- CSSPixels current_offset;
- CSSPixels snapport_size;
- };
- auto x_area = x_chosen_candidate.map([&](size_t candidate_index) { return candidates.x_candidates[candidate_index].area; });
- auto y_area = y_chosen_candidate.map([&](size_t candidate_index) { return candidates.y_candidates[candidate_index].area; });
- ResnapAxis x_axis { candidates.x_candidates, x_chosen_candidate, x_offset, move(x_area), current_offset.x(), geometry->snapport.width() };
- ResnapAxis y_axis { candidates.y_candidates, y_chosen_candidate, y_offset, move(y_area), current_offset.y(), geometry->snapport.height() };
-
- auto area_contains_focus = [&](Optional<Compositing::SnapAreaIdentity> const& area) {
- return area.has_value() && selection.focused_node && snap_area_contains_node(*area, *selection.focused_node);
- };
- auto area_contains_target = [&](Optional<Compositing::SnapAreaIdentity> const& area) {
- return area.has_value() && selection.targeted_element && snap_area_contains_node(*area, *selection.targeted_element);
- };
-
- bool preferred_axis_is_x;
- if (area_contains_focus(x_axis.area) || area_contains_focus(y_axis.area)) {
- preferred_axis_is_x = area_contains_focus(x_axis.area);
- } else if (area_contains_target(x_axis.area) || area_contains_target(y_axis.area)) {
- preferred_axis_is_x = area_contains_target(x_axis.area);
- } else if (x_axis.area.has_value() != y_axis.area.has_value()) {
- preferred_axis_is_x = x_axis.area.has_value();
- } else {
- preferred_axis_is_x = !block_axis_is_y;
- }
- auto const& preferred_axis = preferred_axis_is_x ? x_axis : y_axis;
- auto& other_axis = preferred_axis_is_x ? y_axis : x_axis;
-
- auto preferred_area_candidate_in_other_axis = other_axis.candidates.find_if([&](auto const& candidate) { return candidate.area == *preferred_axis.area; });
- if (preferred_area_candidate_in_other_axis != other_axis.candidates.end()) {
- other_axis.offset = resnap_offset_for_candidate(*preferred_area_candidate_in_other_axis, other_axis.current_offset);
- other_axis.chosen_candidate = preferred_area_candidate_in_other_axis.index();
- } else {
- other_axis.offset = fallback_offset_for_axis(other_axis.candidates, other_axis.current_offset, other_axis.snapport_size, *preferred_axis.offset);
- other_axis.chosen_candidate = {};
- }
- }
-
- auto snap_destination = Compositing::snap_destination_for(current_offset, x_offset, y_offset, snap_axes);
-
- // An axis a re-snap left where it was selected nothing, so an area that happens to have become aligned at the
- // kept position does not take the place of the areas the container was snapped to.
- auto record_snapped_areas = [&](Optional<size_t> const& chosen_candidate, Vector<Compositing::SnapPositionCandidate> const& axis_candidates, Vector<Compositing::SnapAreaIdentity> const& previously_snapped_areas, CSSPixels axis_offset, CSSPixels axis_current_offset, CSSPixels cross_axis_offset) {
- auto areas = Compositing::snap_areas_at_offset(axis_candidates, axis_offset, cross_axis_offset);
- if (chosen_candidate.has_value() && axis_offset == axis_current_offset) {
- auto const& chosen_area = axis_candidates[*chosen_candidate].area;
- areas.remove_all_matching([&](auto const& area) { return area != chosen_area && !previously_snapped_areas.contains_slow(area); });
- }
- return areas;
+ auto x = identities(selection.snapped_areas.x);
+ auto y = identities(selection.snapped_areas.y);
+ Layout::RustFFI::FfiSnapAreaDomRelations relations {
+ .context = const_cast<ResnapSelection*>(&selection),
+ .area_contains_focused_node = area_contains_focused_node,
+ .area_contains_targeted_element = area_contains_targeted_element,
+ .element_of_area_is_ancestor_of_element_of = element_of_area_is_ancestor_of_element_of,
};
- if (x_offset.has_value())
- snap_destination.snapped_areas.x = record_snapped_areas(x_chosen_candidate, candidates.x_candidates, selection.snapped_areas.x, *x_offset, current_offset.x(), snap_destination.position.y());
- if (y_offset.has_value())
- snap_destination.snapped_areas.y = record_snapped_areas(y_chosen_candidate, candidates.y_candidates, selection.snapped_areas.y, *y_offset, current_offset.y(), snap_destination.position.x());
- return snap_destination;
+ Layout::RustFFI::render_state_select_resnap_destination(snap_container.document_host(), committed_row_slot(snap_container), current_offset, x.span(), y.span(), &relations, &result, receive_snap_destination);
+ return result;
}
}
diff --git a/Libraries/LibWeb/Painting/ScrollSnap.h b/Libraries/LibWeb/Painting/ScrollSnap.h
index 55a684e781e..7936b36c858 100644
--- a/Libraries/LibWeb/Painting/ScrollSnap.h
+++ b/Libraries/LibWeb/Painting/ScrollSnap.h
@@ -17,10 +17,7 @@
namespace Web::Painting {
-using Compositing::SnapAreaGeometry;
using Compositing::SnapAreaIdentity;
-using Compositing::SnapAxes;
-using Compositing::SnapContainerGeometry;
using Compositing::SnapDestination;
using Compositing::SnappedAreas;
using Compositing::SnapSelectionStrategy;
diff --git a/Libraries/LibWeb/Painting/Scrolling.cpp b/Libraries/LibWeb/Painting/Scrolling.cpp
index 511ddf0ac22..c54cf95b88d 100644
--- a/Libraries/LibWeb/Painting/Scrolling.cpp
+++ b/Libraries/LibWeb/Painting/Scrolling.cpp
@@ -20,6 +20,19 @@
namespace Web::Painting {
+static Web::AsyncScrollNodeKind async_scroll_node_kind_for(Compositing::CompositorScrollNodeKind kind)
+{
+ switch (kind) {
+ case Compositing::CompositorScrollNodeKind::Viewport:
+ return Web::AsyncScrollNodeKind::Viewport;
+ case Compositing::CompositorScrollNodeKind::Element:
+ return Web::AsyncScrollNodeKind::Element;
+ case Compositing::CompositorScrollNodeKind::PseudoElement:
+ return Web::AsyncScrollNodeKind::PseudoElement;
+ }
+ VERIFY_NOT_REACHED();
+}
+
CSSPixelPoint scroll_offset(Layout::Node const& node)
{
if (!has_committed_box(node))
@@ -195,7 +208,7 @@ Optional<Web::AsyncScrollNodeStableID> async_scroll_node_stable_id(Layout::Node
return Web::AsyncScrollNodeStableID {
.node_id = scrollable_node_id_for(node),
- .kind = Compositing::async_scroll_node_kind_for(*scroll_node_kind),
+ .kind = async_scroll_node_kind_for(*scroll_node_kind),
.pseudo_element_type = pseudo_element_type_for(node),
};
}
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index add81469527..01c8f108db3 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -2332,7 +2332,6 @@ fn expose_shared_abi_types_as_cpp_types(config: &mut cbindgen::Config) {
"ReplayClip",
"ReplayLayer",
"ReplayMask",
- "FfiVisualViewportTransform",
]
.map(String::from),
);
@@ -2373,7 +2372,6 @@ fn expose_shared_abi_types_as_cpp_types(config: &mut cbindgen::Config) {
("ReplayClip", "Compositing::ReplayClip"),
("ReplayLayer", "Compositing::ReplayLayer"),
("ReplayMask", "Compositing::ReplayMask"),
- ("FfiVisualViewportTransform", "Compositing::TransformWithOrigin"),
] {
config.export.rename.insert(rust_name.to_string(), cpp_name.to_string());
}
@@ -2417,8 +2415,6 @@ fn expose_compositing_types_as_cpp_types(config: &mut cbindgen::Config) {
"FfiVisualAnimationTransformOperationKind",
"FfiCompositorAnimationPublishOutcome",
"FfiVisualAnimationSummary",
- "FfiAnimatedContentViewportEffect",
- "FfiTestStickyConstraints",
"FfiDisplayListReplayCallbacks",
"FfiEasingDescriptor",
"FfiEasingKind",
@@ -2430,7 +2426,15 @@ fn expose_compositing_types_as_cpp_types(config: &mut cbindgen::Config) {
.rename
.insert(name.to_string(), format!("Compositing::RustFFI::{name}"));
}
+ config.export.exclude.push("SnapSelectionStrategyType".to_string());
+ config.export.rename.insert(
+ "SnapSelectionStrategyType".to_string(),
+ "Compositing::SnapSelectionStrategy::Type".to_string(),
+ );
config.includes.push("LibCompositing/RustFFI.h".to_string());
+ config
+ .includes
+ .push("LibCompositing/Scrolling/ScrollSnapSelection.h".to_string());
}
/// Names the document host and the begun read as the layout header declares them, for a header whose entries take them.
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
index 90e53fe3a8d..80bb741b0ee 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
@@ -81,19 +81,150 @@ pub extern "C" fn layout_row_paintable_wheel_scrollable_axes(
}
}
+fn snap_container_geometry(
+ host: &crate::render_state::DocumentHost,
+ snap_container: NodeSlotId,
+) -> Option<libcompositing_rust::scrolling::scroll_snap_selection::SnapContainerGeometry> {
+ read_measured_rows(host, super::node_read(), |rows| {
+ crate::painting::scroll_snap::snap_container_geometry(rows, snap_container)
+ })
+ .map(Into::into)
+}
+
+fn snap_areas(
+ host: &crate::render_state::DocumentHost,
+ snap_container: NodeSlotId,
+) -> Vec<libcompositing_rust::scrolling::scroll_snap_selection::SnapAreaGeometry> {
+ read_arena(host, super::node_read(), snap_container, |arena, snap_container| {
+ let mut areas = Vec::new();
+ crate::painting::scroll_snap::for_each_snap_area(&arena.paintable_rows(), snap_container, |slot, mut area| {
+ // A re-snap right after layout runs ahead of the visual context tree that names the area's
+ // element, so the area is named by what the build stamped onto its row.
+ area.node_id = arena.unique_node_ids().id(slot);
+ areas.push(area.into());
+ });
+ areas
+ })
+}
+
+/// # Safety
+///
+/// `receive` must copy what it keeps of the destination synchronously.
+unsafe fn receive_snap_destination(
+ destination: libcompositing_rust::scrolling::SnapDestination,
+ receiver: *mut c_void,
+ receive: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiSnapDestination<'_>),
+) {
+ use crate::painting::host::{FfiSnapAreaIdentity, FfiSnapDestination};
+ let x: Vec<FfiSnapAreaIdentity> = destination.snapped_areas.x.into_iter().map(Into::into).collect();
+ let y: Vec<FfiSnapAreaIdentity> = destination.snapped_areas.y.into_iter().map(Into::into).collect();
+ let destination = FfiSnapDestination {
+ position: destination.position.into(),
+ snapped_x: destination.snapped_x,
+ snapped_y: destination.snapped_y,
+ evaluated_x: destination.evaluated_x,
+ evaluated_y: destination.evaluated_y,
+ snapped_areas_x: ak::Span::new(&x),
+ snapped_areas_y: ak::Span::new(&y),
+ };
+ // SAFETY: The caller copies what it keeps of the destination synchronously.
+ unsafe { receive(receiver, &destination) };
+}
+
+/// Answers false, without calling `receive`, for a box that snaps along none of the axes the scroll selects a snap
+/// position in.
+///
+/// # Safety
+///
+/// `host` must be a live document host, on its document's thread. `receive` must copy what it keeps of the
+/// destination synchronously.
#[unsafe(no_mangle)]
-pub extern "C" fn layout_row_snap_container_geometry(
+pub unsafe extern "C" fn render_state_select_snap_destination(
host: &crate::render_state::DocumentHost,
snap_container: NodeSlotId,
- out_geometry: &mut crate::painting::host::FfiSnapContainerGeometry,
+ destination: FfiCssPixelPoint,
+ strategy: &crate::painting::host::FfiSnapSelectionStrategy,
+ receiver: *mut c_void,
+ receive: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiSnapDestination<'_>),
) -> bool {
- let geometry = read_measured_rows(host, super::node_read(), |rows| {
- crate::painting::scroll_snap::snap_container_geometry(rows, snap_container)
- });
- let Some(geometry) = geometry else {
+ use libcompositing_rust::scrolling::scroll_snap_selection::{axes_to_evaluate, select_snap_destination};
+ let Some(geometry) = snap_container_geometry(host, snap_container) else {
return false;
};
- *out_geometry = geometry;
+ let strategy = strategy.into();
+ if axes_to_evaluate(geometry.axes, &strategy).is_empty() {
+ return false;
+ }
+ let destination = select_snap_destination(
+ &geometry,
+ &snap_areas(host, snap_container),
+ destination.into(),
+ &strategy,
+ );
+ // SAFETY: The caller copies what it keeps of the destination synchronously.
+ unsafe { receive_snap_destination(destination, receiver, receive) };
+ true
+}
+
+struct SnapAreaDomRelationsOfHost<'a>(&'a crate::painting::host::FfiSnapAreaDomRelations);
+
+impl crate::painting::scroll_resnap::SnapAreaDomRelations for SnapAreaDomRelationsOfHost<'_> {
+ fn area_contains_focused_node(&self, area: libcompositing_rust::scrolling::SnapAreaIdentity) -> bool {
+ // SAFETY: The entry point's caller keeps the relation callbacks live for selection.
+ unsafe { (self.0.area_contains_focused_node)(self.0.context, area.into()) }
+ }
+
+ fn area_contains_targeted_element(&self, area: libcompositing_rust::scrolling::SnapAreaIdentity) -> bool {
+ // SAFETY: The entry point's caller keeps the relation callbacks live for selection.
+ unsafe { (self.0.area_contains_targeted_element)(self.0.context, area.into()) }
+ }
+
+ fn element_of_area_is_ancestor_of_element_of(
+ &self,
+ area: libcompositing_rust::scrolling::SnapAreaIdentity,
+ other_area: libcompositing_rust::scrolling::SnapAreaIdentity,
+ ) -> bool {
+ // SAFETY: The entry point's caller keeps the relation callbacks live for selection.
+ unsafe { (self.0.element_of_area_is_ancestor_of_element_of)(self.0.context, area.into(), other_area.into()) }
+ }
+}
+
+/// Answers false, without calling `receive`, for a box that snaps along no axis.
+///
+/// # Safety
+///
+/// `host` must be a live document host, on its document's thread. The relation callbacks must stay live for
+/// selection, and `receive` must copy what it keeps of the destination synchronously.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn render_state_select_resnap_destination(
+ host: &crate::render_state::DocumentHost,
+ snap_container: NodeSlotId,
+ current_offset: FfiCssPixelPoint,
+ snapped_areas_x: ak::Span<'_, crate::painting::host::FfiSnapAreaIdentity>,
+ snapped_areas_y: ak::Span<'_, crate::painting::host::FfiSnapAreaIdentity>,
+ relations: &crate::painting::host::FfiSnapAreaDomRelations,
+ receiver: *mut c_void,
+ receive: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiSnapDestination<'_>),
+) -> bool {
+ let Some(geometry) = snap_container_geometry(host, snap_container) else {
+ return false;
+ };
+ if geometry.axes.is_empty() {
+ return false;
+ }
+ let selection = libcompositing_rust::scrolling::SnappedAreas {
+ x: snapped_areas_x.as_slice().iter().copied().map(Into::into).collect(),
+ y: snapped_areas_y.as_slice().iter().copied().map(Into::into).collect(),
+ };
+ let destination = crate::painting::scroll_resnap::select_resnap_destination(
+ &geometry,
+ &snap_areas(host, snap_container),
+ current_offset.into(),
+ &selection,
+ &SnapAreaDomRelationsOfHost(relations),
+ );
+ // SAFETY: The caller copies what it keeps of the destination synchronously.
+ unsafe { receive_snap_destination(destination, receiver, receive) };
true
}
@@ -375,39 +506,6 @@ pub unsafe extern "C" fn render_state_refresh_scroll_state(
}
}
-/// # Safety
-///
-/// `host` must be a live document host, on its document's thread. The host callback receives each snap area's
-/// geometry, valid for the duration of the call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn render_state_for_each_snap_area(
- host: &crate::render_state::DocumentHost,
- snap_container: NodeSlotId,
- context: *mut c_void,
- push_snap_area: unsafe extern "C" fn(*mut c_void, *const crate::painting::host::FfiSnapAreaGeometry),
-) {
- let areas = {
- read_arena(host, super::node_read(), snap_container, |arena, snap_container| {
- let mut areas = Vec::new();
- crate::painting::scroll_snap::for_each_snap_area(
- &arena.paintable_rows(),
- snap_container,
- |slot, mut area| {
- // A re-snap right after layout runs ahead of the visual context tree that names the area's
- // element, so the area is named by what the build stamped onto its row.
- area.node_id = arena.unique_node_ids().id(slot);
- areas.push(area);
- },
- );
- areas
- })
- };
- for area in &areas {
- // SAFETY: The C++ callback copies the geometry into a caller-owned collection.
- unsafe { push_snap_area(context, area) };
- }
-}
-
/// # Safety
///
/// `host` must be a live document host, on its document's thread; the callbacks in `publish` are called
diff --git a/Libraries/LibWeb/Rust/src/painting/host/paint.rs b/Libraries/LibWeb/Rust/src/painting/host/paint.rs
index 5112bad9017..ce6f7790dc9 100644
--- a/Libraries/LibWeb/Rust/src/painting/host/paint.rs
+++ b/Libraries/LibWeb/Rust/src/painting/host/paint.rs
@@ -8,6 +8,7 @@ use crate::layout::svg_formatting_context::FfiSvgNumberPercentage;
use crate::layout::used_values;
use crate::painting::display_list::commands::{OptionalAffineTransform, OptionalColor};
use crate::stage::MainThread;
+use libcompositing_rust::scrolling::scroll_snap_selection::SnapSelectionStrategyType;
use libgfx_rust::{Color, IntRect, InterpolationColorSpace};
use std::ffi::c_void;
@@ -537,6 +538,43 @@ pub struct FfiSnapAreaGeometry {
pub always_stop: bool,
}
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct FfiSnapAreaIdentity {
+ pub node_id: i64,
+ pub pseudo_element_type: u8,
+}
+
+#[repr(C)]
+pub struct FfiSnapSelectionStrategy {
+ pub r#type: SnapSelectionStrategyType,
+ pub has_start_offset: bool,
+ pub start_offset: used_values::FfiCssPixelPoint,
+ pub displacement: used_values::FfiCssPixelPoint,
+ pub has_starting_positions_boundary: bool,
+ pub starting_positions_boundary: used_values::FfiCssPixelPoint,
+}
+
+#[repr(C)]
+pub struct FfiSnapDestination<'a> {
+ pub position: used_values::FfiCssPixelPoint,
+ pub snapped_x: bool,
+ pub snapped_y: bool,
+ pub evaluated_x: bool,
+ pub evaluated_y: bool,
+ pub snapped_areas_x: ak::Span<'a, FfiSnapAreaIdentity>,
+ pub snapped_areas_y: ak::Span<'a, FfiSnapAreaIdentity>,
+}
+
+#[repr(C)]
+pub struct FfiSnapAreaDomRelations {
+ pub context: *mut c_void,
+ pub area_contains_focused_node: unsafe extern "C" fn(*mut c_void, FfiSnapAreaIdentity) -> bool,
+ pub area_contains_targeted_element: unsafe extern "C" fn(*mut c_void, FfiSnapAreaIdentity) -> bool,
+ pub element_of_area_is_ancestor_of_element_of:
+ unsafe extern "C" fn(*mut c_void, FfiSnapAreaIdentity, FfiSnapAreaIdentity) -> bool,
+}
+
/// Where a recording's resources go once it is published. The fields are private: the callbacks
/// are reached only through the methods below, which take the main thread token.
///
diff --git a/Libraries/LibWeb/Rust/src/painting/mod.rs b/Libraries/LibWeb/Rust/src/painting/mod.rs
index 3fec1324955..6cae9d10d24 100644
--- a/Libraries/LibWeb/Rust/src/painting/mod.rs
+++ b/Libraries/LibWeb/Rust/src/painting/mod.rs
@@ -41,6 +41,7 @@ pub mod record;
pub(crate) mod recording_slot;
pub(crate) mod replaced_paint_facts;
pub(crate) mod scroll_chain;
+pub(crate) mod scroll_resnap;
pub(crate) mod scroll_snap;
pub mod scrollable_overflow;
pub mod selection;
diff --git a/Libraries/LibWeb/Rust/src/painting/scroll_resnap.rs b/Libraries/LibWeb/Rust/src/painting/scroll_resnap.rs
new file mode 100644
index 00000000000..6b9ead7a733
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/painting/scroll_resnap.rs
@@ -0,0 +1,366 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Re-snapping a scroll container to the areas it was snapped to before a content change.
+
+use crate::css::css_pixels::{CssPixelPoint, CssPixels};
+use libcompositing_rust::scrolling::scroll_snap_selection::*;
+use libcompositing_rust::scrolling::{SnapAreaIdentity, SnapDestination, SnappedAreas};
+
+pub(crate) trait SnapAreaDomRelations {
+ fn area_contains_focused_node(&self, area: SnapAreaIdentity) -> bool;
+ fn area_contains_targeted_element(&self, area: SnapAreaIdentity) -> bool;
+ fn element_of_area_is_ancestor_of_element_of(&self, area: SnapAreaIdentity, other_area: SnapAreaIdentity) -> bool;
+}
+
+fn resnap_offset_for_candidate(candidate: &SnapPositionCandidate, axis_current_offset: CssPixels) -> CssPixels {
+ // A scroll container resting at one of its snapped area's valid snap positions is still snapped to that area and
+ // stays where it is.
+ if candidate_has_snap_position_at(candidate, axis_current_offset) {
+ return axis_current_offset;
+ }
+ candidate.offset
+}
+
+// The box each axis is snapped to, as an index into that axis's candidate list.
+struct SnappedAxisBoxes {
+ x_candidate: Option<usize>,
+ y_candidate: Option<usize>,
+}
+
+// https://drafts.csswg.org/css-scroll-snap-1/#multiple-aligned-snap-areas
+// When snapping to a scroll position that is aligned with multiple scroll snap areas, the following algorithm procedure
+// is used to determined which box is snapped on the block and inline axes for a particular scroll container:
+// NB: Every step treats the block and inline lists alike, so the steps are carried out on the physical axes directly.
+fn select_between_multiple_aligned_snap_areas(
+ candidates: &SnapAxisCandidates,
+ selection: &SnappedAreas,
+ relations: &impl SnapAreaDomRelations,
+ scroll_position: CssPixelPoint,
+) -> SnappedAxisBoxes {
+ // 1. Let scroll position be the scroll position of the scroll container
+ // NB: The scroll position is the offset the content change left the container resting at.
+
+ // 2. Let inline be the set of boxes whose scroll snap areas are aligned at this scroll position in the inline axis.
+ // 3. Let block be the set of boxes whose scroll snap areas are aligned at this scroll position in the block axis.
+ // AD-HOC: Only the snap areas the container was snapped to before the content change take part, since a re-snap
+ // must return the container to those same areas rather than to whichever areas the change left aligned. An
+ // area whose snap position would leave it outside the snapport in the other axis no longer offers a valid
+ // snap position and does not take part either.
+ // NB: A box is held as the index of its snap position candidate in its axis's candidate list, which holds its
+ // candidates in tree order.
+ let aligned_boxes = |axis_candidates: &[SnapPositionCandidate],
+ snapped_areas: &[SnapAreaIdentity],
+ cross_axis_offset: CssPixels| {
+ let mut boxes = Vec::new();
+ for (candidate_index, candidate) in axis_candidates.iter().enumerate() {
+ if !candidate.area.is_valid() || !snapped_areas.contains(&candidate.area) {
+ continue;
+ }
+ if !snap_area_is_visible_at_cross_axis_offset(candidate, cross_axis_offset) {
+ continue;
+ }
+ boxes.push(candidate_index);
+ }
+ boxes
+ };
+ let mut x_boxes = aligned_boxes(&candidates.x_candidates, &selection.x, scroll_position.y);
+ let mut y_boxes = aligned_boxes(&candidates.y_candidates, &selection.y, scroll_position.x);
+
+ // 4. For each list of block and inline:
+ let remove_superseded_boxes = |boxes: &mut Vec<usize>, axis_candidates: &[SnapPositionCandidate]| {
+ let mut keep_only_boxes_matching = |predicate: &dyn Fn(SnapAreaIdentity) -> bool| {
+ if !boxes
+ .iter()
+ .any(|&candidate_index| predicate(axis_candidates[candidate_index].area))
+ {
+ return false;
+ }
+ boxes.retain(|&candidate_index| predicate(axis_candidates[candidate_index].area));
+ true
+ };
+
+ // 1. If list contains one or more boxes that are focused or have a focused descendant, remove all other boxes
+ // from list
+ let kept_focused_boxes = keep_only_boxes_matching(&|area| relations.area_contains_focused_node(area));
+
+ // 2. Else if list contains one or more boxes that are targetted or have a targetted descendant, remove all
+ // other boxes from list.
+ if !kept_focused_boxes {
+ keep_only_boxes_matching(&|area| relations.area_contains_targeted_element(area));
+ }
+
+ // 3. For each box in list:
+ // 1. Remove any box from list which is an ancestor of box.
+ let boxes_before_ancestor_removal = boxes.clone();
+ boxes.retain(|&candidate_index| {
+ let area = axis_candidates[candidate_index].area;
+ !boxes_before_ancestor_removal.iter().any(|&other_index| {
+ relations.element_of_area_is_ancestor_of_element_of(area, axis_candidates[other_index].area)
+ })
+ });
+ };
+ remove_superseded_boxes(&mut x_boxes, &candidates.x_candidates);
+ remove_superseded_boxes(&mut y_boxes, &candidates.y_candidates);
+
+ let boxes_contain_area = |boxes: &[usize], axis_candidates: &[SnapPositionCandidate], area: SnapAreaIdentity| {
+ boxes
+ .iter()
+ .any(|&candidate_index| axis_candidates[candidate_index].area == area)
+ };
+ let axis_sets_overlap = x_boxes.iter().any(|&candidate_index| {
+ boxes_contain_area(
+ &y_boxes,
+ &candidates.y_candidates,
+ candidates.x_candidates[candidate_index].area,
+ )
+ });
+ // 5. If inline and block are overlapping sets:
+ if axis_sets_overlap {
+ // 1. Replace inline with the intersection of inline and block.
+ x_boxes.retain(|&candidate_index| {
+ boxes_contain_area(
+ &y_boxes,
+ &candidates.y_candidates,
+ candidates.x_candidates[candidate_index].area,
+ )
+ });
+
+ // 2. Replace block with the intersection of inline and block.
+ // NB: The intersection is unchanged by the step before it, so the narrowed list gives the same result the
+ // original one would.
+ y_boxes.retain(|&candidate_index| {
+ boxes_contain_area(
+ &x_boxes,
+ &candidates.x_candidates,
+ candidates.y_candidates[candidate_index].area,
+ )
+ });
+ }
+
+ // 6. Select the first element in tree order from inline as the snapped inline axis box.
+ // 7. Select the first element in tree order from block as the snapped block axis box.
+ SnappedAxisBoxes {
+ x_candidate: x_boxes.first().copied(),
+ y_candidate: y_boxes.first().copied(),
+ }
+}
+
+pub(crate) fn select_resnap_destination(
+ geometry: &SnapContainerGeometry,
+ areas: &[SnapAreaGeometry],
+ current_offset: CssPixelPoint,
+ selection: &SnappedAreas,
+ relations: &impl SnapAreaDomRelations,
+) -> SnapDestination {
+ if geometry.axes.is_empty() {
+ return SnapDestination {
+ position: current_offset,
+ ..Default::default()
+ };
+ }
+ let snap_axes = geometry.axes;
+
+ let candidates = build_snap_candidates(geometry, areas, snap_axes);
+
+ // NB: A container that was not snapped before the change, or whose snapped areas are all gone, re-snaps the way a
+ // fresh scroll to the current position would.
+ let resnap_afresh = || {
+ select_snap_destination_with_candidates(
+ geometry,
+ &candidates,
+ current_offset,
+ &SnapSelectionStrategy::default(),
+ snap_axes,
+ )
+ };
+ if selection.is_empty() {
+ return resnap_afresh();
+ }
+
+ let SnappedAxisBoxes {
+ x_candidate: mut x_chosen_candidate,
+ y_candidate: mut y_chosen_candidate,
+ } = select_between_multiple_aligned_snap_areas(&candidates, selection, relations, current_offset);
+
+ if x_chosen_candidate.is_none() && y_chosen_candidate.is_none() {
+ return resnap_afresh();
+ }
+
+ let fallback_offset_for_axis = |axis_candidates: &[SnapPositionCandidate],
+ axis_current_offset: CssPixels,
+ axis_snapport_size: CssPixels,
+ cross_axis_offset: CssPixels| {
+ let axis_selection = SnapAxisSelection {
+ destination: axis_current_offset,
+ start: axis_current_offset,
+ direction: CssPixels::default(),
+ starting_positions_boundary: None,
+ };
+ let choice = choose_snap_offset_for_axis(
+ axis_candidates,
+ &axis_selection,
+ axis_snapport_size,
+ geometry.strictness,
+ Some(cross_axis_offset),
+ None,
+ );
+ choice.map(|axis_choice| axis_choice.offset)
+ };
+
+ // An axis whose snapped areas are all gone re-snaps afresh, from the snap positions reachable while the other
+ // axis follows its own snapped area.
+ let mut x_offset = None;
+ let mut y_offset = None;
+ if let Some(index) = x_chosen_candidate {
+ x_offset = Some(resnap_offset_for_candidate(
+ &candidates.x_candidates[index],
+ current_offset.x,
+ ));
+ }
+ if let Some(index) = y_chosen_candidate {
+ y_offset = Some(resnap_offset_for_candidate(
+ &candidates.y_candidates[index],
+ current_offset.y,
+ ));
+ }
+ if snap_axes.x && x_chosen_candidate.is_none() {
+ x_offset = fallback_offset_for_axis(
+ &candidates.x_candidates,
+ current_offset.x,
+ geometry.snapport.width,
+ y_offset.unwrap_or(current_offset.y),
+ );
+ }
+ if snap_axes.y && y_chosen_candidate.is_none() {
+ y_offset = fallback_offset_for_axis(
+ &candidates.y_candidates,
+ current_offset.y,
+ geometry.snapport.height,
+ x_offset.unwrap_or(current_offset.x),
+ );
+ }
+
+ // https://drafts.csswg.org/css-scroll-snap-1/#re-snap
+ // If it is not possible to snap to both (e.g. if snapping to one resulted in the other being offscreen), it must
+ // prefer the focused box, followed by the targeted box, followed by the block axis if neither box is focused or
+ // targeted.
+ // NB: The preferred box is snapped in both axes: the other axis takes the box's own snap position when it defines
+ // one, and otherwise re-snaps among the positions at which the preferred box remains visible.
+ if let (Some(x), Some(y)) = (x_offset, y_offset)
+ && !chosen_offsets_are_mutually_visible(&candidates, x, y)
+ {
+ let block_axis_is_y = geometry.horizontal_writing_mode;
+
+ struct ResnapAxis<'a> {
+ candidates: &'a [SnapPositionCandidate],
+ chosen_candidate: &'a mut Option<usize>,
+ offset: &'a mut Option<CssPixels>,
+ area: Option<SnapAreaIdentity>,
+ current_offset: CssPixels,
+ snapport_size: CssPixels,
+ }
+ let x_area = x_chosen_candidate.map(|candidate_index| candidates.x_candidates[candidate_index].area);
+ let y_area = y_chosen_candidate.map(|candidate_index| candidates.y_candidates[candidate_index].area);
+ let mut x_axis = ResnapAxis {
+ candidates: &candidates.x_candidates,
+ chosen_candidate: &mut x_chosen_candidate,
+ offset: &mut x_offset,
+ area: x_area,
+ current_offset: current_offset.x,
+ snapport_size: geometry.snapport.width,
+ };
+ let mut y_axis = ResnapAxis {
+ candidates: &candidates.y_candidates,
+ chosen_candidate: &mut y_chosen_candidate,
+ offset: &mut y_offset,
+ area: y_area,
+ current_offset: current_offset.y,
+ snapport_size: geometry.snapport.height,
+ };
+
+ let area_contains_focus =
+ |area: Option<SnapAreaIdentity>| area.is_some_and(|area| relations.area_contains_focused_node(area));
+ let area_contains_target =
+ |area: Option<SnapAreaIdentity>| area.is_some_and(|area| relations.area_contains_targeted_element(area));
+
+ let preferred_axis_is_x = if area_contains_focus(x_axis.area) || area_contains_focus(y_axis.area) {
+ area_contains_focus(x_axis.area)
+ } else if area_contains_target(x_axis.area) || area_contains_target(y_axis.area) {
+ area_contains_target(x_axis.area)
+ } else if x_axis.area.is_some() != y_axis.area.is_some() {
+ x_axis.area.is_some()
+ } else {
+ !block_axis_is_y
+ };
+ let (preferred_axis, other_axis) = if preferred_axis_is_x {
+ (&x_axis, &mut y_axis)
+ } else {
+ (&y_axis, &mut x_axis)
+ };
+
+ let preferred_area_candidate_in_other_axis = other_axis
+ .candidates
+ .iter()
+ .position(|candidate| candidate.area == preferred_axis.area.unwrap());
+ if let Some(index) = preferred_area_candidate_in_other_axis {
+ *other_axis.offset = Some(resnap_offset_for_candidate(
+ &other_axis.candidates[index],
+ other_axis.current_offset,
+ ));
+ *other_axis.chosen_candidate = Some(index);
+ } else {
+ *other_axis.offset = fallback_offset_for_axis(
+ other_axis.candidates,
+ other_axis.current_offset,
+ other_axis.snapport_size,
+ preferred_axis.offset.unwrap(),
+ );
+ *other_axis.chosen_candidate = None;
+ }
+ }
+
+ let mut snap_destination = snap_destination_for(current_offset, x_offset, y_offset, snap_axes);
+
+ // An axis a re-snap left where it was selected nothing, so an area that happens to have become aligned at the
+ // kept position does not take the place of the areas the container was snapped to.
+ let record_snapped_areas = |chosen_candidate: Option<usize>,
+ axis_candidates: &[SnapPositionCandidate],
+ previously_snapped_areas: &[SnapAreaIdentity],
+ axis_offset: CssPixels,
+ axis_current_offset: CssPixels,
+ cross_axis_offset: CssPixels| {
+ let mut areas = snap_areas_at_offset(axis_candidates, axis_offset, cross_axis_offset);
+ if let Some(index) = chosen_candidate
+ && axis_offset == axis_current_offset
+ {
+ let chosen_area = axis_candidates[index].area;
+ areas.retain(|area| *area == chosen_area || previously_snapped_areas.contains(area));
+ }
+ areas
+ };
+ if let Some(x_offset) = x_offset {
+ snap_destination.snapped_areas.x = record_snapped_areas(
+ x_chosen_candidate,
+ &candidates.x_candidates,
+ &selection.x,
+ x_offset,
+ current_offset.x,
+ snap_destination.position.y,
+ );
+ }
+ if let Some(y_offset) = y_offset {
+ snap_destination.snapped_areas.y = record_snapped_areas(
+ y_chosen_candidate,
+ &candidates.y_candidates,
+ &selection.y,
+ y_offset,
+ current_offset.y,
+ snap_destination.position.x,
+ );
+ }
+ snap_destination
+}
diff --git a/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs b/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs
index c521b158674..d49912454fe 100644
--- a/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs
+++ b/Libraries/LibWeb/Rust/src/painting/scroll_snap.rs
@@ -6,7 +6,7 @@
//! The geometry scroll snap position selection runs over, collected from the layout of a snap
//! container and of the snap areas it captures. The selection itself lives in
-//! `LibWeb/Compositor/ScrollSnapSelection.cpp`, so that the main thread and the compositor process
+//! `libcompositing_rust::scrolling::scroll_snap_selection`, so that the main thread and the compositor process
//! select from the same geometry.
use crate::css::computed_value_types::ComputedLengthBox;
@@ -18,13 +18,104 @@ use crate::css::css_pixels::{CssPixelRect, CssPixels};
use crate::layout::node_data::{NodeKind, NodeSlotId};
use crate::layout::node_facts;
use crate::painting::chrome_geometry::{maximum_scroll_offset, minimum_scroll_offset};
-use crate::painting::host::{FfiSnapAreaGeometry, FfiSnapAxes, FfiSnapContainerGeometry};
+use crate::painting::host::{
+ FfiSnapAreaGeometry, FfiSnapAreaIdentity, FfiSnapAxes, FfiSnapContainerGeometry, FfiSnapSelectionStrategy,
+};
use crate::painting::paint_read::PaintRead;
use crate::painting::paintable_geometry;
use crate::painting::style_queries;
use crate::painting::visual_context::node_values::compute_transform;
+use libcompositing_rust::display_list::commands::UniqueNodeId;
+use libcompositing_rust::scrolling::SnapAreaIdentity;
+use libcompositing_rust::scrolling::scroll_snap_selection::{
+ SnapAlign, SnapAreaGeometry, SnapAxes, SnapContainerGeometry, SnapSelectionStrategy, SnapStrictness,
+};
use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect};
+const _: () = {
+ assert!(scroll_snap_align::NONE == SnapAlign::None as u8);
+ assert!(scroll_snap_align::START == SnapAlign::Start as u8);
+ assert!(scroll_snap_align::END == SnapAlign::End as u8);
+ assert!(scroll_snap_align::CENTER == SnapAlign::Center as u8);
+ assert!(scroll_snap_strictness::NONE == SnapStrictness::None as u8);
+ assert!(scroll_snap_strictness::PROXIMITY == SnapStrictness::Proximity as u8);
+ assert!(scroll_snap_strictness::MANDATORY == SnapStrictness::Mandatory as u8);
+};
+
+impl From<FfiSnapAreaIdentity> for SnapAreaIdentity {
+ fn from(area: FfiSnapAreaIdentity) -> Self {
+ Self {
+ node_id: UniqueNodeId(area.node_id),
+ pseudo_element_type: area.pseudo_element_type,
+ }
+ }
+}
+
+impl From<SnapAreaIdentity> for FfiSnapAreaIdentity {
+ fn from(area: SnapAreaIdentity) -> Self {
+ Self {
+ node_id: area.node_id.0,
+ pseudo_element_type: area.pseudo_element_type,
+ }
+ }
+}
+
+impl From<FfiSnapContainerGeometry> for SnapContainerGeometry {
+ fn from(geometry: FfiSnapContainerGeometry) -> Self {
+ Self {
+ snapport: geometry.snapport.into(),
+ min_scroll_offset: geometry.min_scroll_offset.into(),
+ max_scroll_offset: geometry.max_scroll_offset.into(),
+ strictness: match geometry.strictness {
+ scroll_snap_strictness::NONE => SnapStrictness::None,
+ scroll_snap_strictness::PROXIMITY => SnapStrictness::Proximity,
+ scroll_snap_strictness::MANDATORY => SnapStrictness::Mandatory,
+ _ => unreachable!("invalid snap strictness"),
+ },
+ axes: SnapAxes {
+ x: geometry.axes.x,
+ y: geometry.axes.y,
+ },
+ horizontal_writing_mode: geometry.horizontal_writing_mode,
+ }
+ }
+}
+
+impl From<FfiSnapAreaGeometry> for SnapAreaGeometry {
+ fn from(area: FfiSnapAreaGeometry) -> Self {
+ let align = |value| match value {
+ scroll_snap_align::NONE => SnapAlign::None,
+ scroll_snap_align::START => SnapAlign::Start,
+ scroll_snap_align::END => SnapAlign::End,
+ scroll_snap_align::CENTER => SnapAlign::Center,
+ _ => unreachable!("invalid snap alignment"),
+ };
+ Self {
+ identity: SnapAreaIdentity {
+ node_id: UniqueNodeId(area.node_id),
+ pseudo_element_type: area.pseudo_element_type,
+ },
+ rect: area.rect.into(),
+ align_x: align(area.align_x),
+ align_y: align(area.align_y),
+ always_stop: area.always_stop,
+ }
+ }
+}
+
+impl From<&FfiSnapSelectionStrategy> for SnapSelectionStrategy {
+ fn from(strategy: &FfiSnapSelectionStrategy) -> Self {
+ Self {
+ r#type: strategy.r#type,
+ start_offset: strategy.has_start_offset.then(|| strategy.start_offset.into()),
+ displacement: strategy.displacement.into(),
+ starting_positions_boundary: strategy
+ .has_starting_positions_boundary
+ .then(|| strategy.starting_positions_boundary.into()),
+ }
+ }
+}
+
/// The box whose style the snap properties of a scroll container come from. The properties
/// specified on the root element apply to the viewport rather than to its own box.
fn snap_style_source(arena: &impl PaintRead, snap_container: NodeSlotId) -> Option<NodeSlotId> {
diff --git a/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipc b/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipc
index d54f4dc5b2a..d765b906dfe 100644
--- a/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipc
+++ b/Libraries/LibWebCommon/Page/AsyncScrollNodeStableID.ipc
@@ -9,10 +9,10 @@
[ExistingCpp, RustDerive=Hash+PartialOrd+Ord]
enum Web::AsyncScrollNodeKind : u8 {
- Viewport,
- Element,
- PseudoElement,
- VisualViewport,
+ Viewport = 0,
+ Element = 1,
+ PseudoElement = 2,
+ VisualViewport = 3,
}
[ExistingCpp, RustDerive=Copy+Eq+Hash+PartialOrd+Ord]
diff --git a/Services/Compositor/CompositedContext.h b/Services/Compositor/CompositedContext.h
index 32d7d039a3d..2b78314f49d 100644
--- a/Services/Compositor/CompositedContext.h
+++ b/Services/Compositor/CompositedContext.h
@@ -10,7 +10,7 @@
#include <AK/RefPtr.h>
#include <Compositor/PaintingSurface.h>
#include <LibCompositing/Types.h>
-#include <LibGfx/Matrix.h>
+#include <LibGfx/Matrix4x4.h>
#include <LibGfx/Rect.h>
namespace Compositor {
diff --git a/Tests/Compositor/CMakeLists.txt b/Tests/Compositor/CMakeLists.txt
index 574a163e12a..d867d160140 100644
--- a/Tests/Compositor/CMakeLists.txt
+++ b/Tests/Compositor/CMakeLists.txt
@@ -1,7 +1,6 @@
ladybird_test_suite(Compositor)
set(TEST_SOURCES
- TestAsyncScrollTree.cpp
TestBitmapExport.cpp
TestCanvasSurfaceRegistry.cpp
TestVideoFrameHolds.cpp
diff --git a/Tests/Compositor/TestAsyncScrollTree.cpp b/Tests/Compositor/TestAsyncScrollTree.cpp
deleted file mode 100644
index 9012a38d1c0..00000000000
--- a/Tests/Compositor/TestAsyncScrollTree.cpp
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Tuple.h>
-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>
-#include <LibCompositing/DisplayList/DisplayList.h>
-#include <LibCompositing/DisplayList/VisualContextTreeTestBuilder.h>
-#include <LibCompositing/Scrolling/AsyncScrollTree.h>
-#include <LibCompositing/Scrolling/ScrollState.h>
-#include <LibTest/TestCase.h>
-
-static Compositing::SpatialNodeIndex const viewport_scroll_node_index { 1 };
-static Web::UniqueNodeID const viewport_document_node_id { 2 };
-
-static Compositing::AsyncScrollingState make_scrolling_state_with_viewport_scroll_node(float max_scroll_offset_y)
-{
- Compositing::AsyncScrollingState state;
- state.scroll_nodes.append({
- .scroll_node_index = viewport_scroll_node_index,
- .stable_node_id = { .node_id = viewport_document_node_id, .kind = Web::AsyncScrollNodeKind::Viewport, .pseudo_element_type = 0 },
- .parent_scroll_node_index = {},
- .scrollport_rect = { 0, 0, 800, 600 },
- .min_scroll_offset = { 0, 0 },
- .max_scroll_offset = { 0, max_scroll_offset_y },
- .is_viewport = true,
- .can_be_wheel_scrolled_horizontally = false,
- .can_be_wheel_scrolled_vertically = true,
- });
- return state;
-}
-
-static Compositing::AsyncScrollTree make_scroll_tree_with_viewport_scroll_node(float max_scroll_offset_y)
-{
- Compositing::AsyncScrollTree scroll_tree;
- scroll_tree.set_state(make_scrolling_state_with_viewport_scroll_node(max_scroll_offset_y));
- return scroll_tree;
-}
-
-static Compositing::AccumulatedVisualContextTree make_visual_context_tree()
-{
- Compositing::VisualContextTreeTestBuilder builder;
- return builder.finish();
-}
-
-static NonnullRefPtr<Compositing::DisplayList> make_empty_display_list(Compositing::AccumulatedVisualContextTree const& visual_context_tree)
-{
- return Compositing::DisplayList::create(visual_context_tree);
-}
-
-TEST_CASE(wheel_hit_testing_rejects_a_different_visual_context_tree_structural_epoch)
-{
- auto visual_context_tree = make_visual_context_tree();
- Compositing::AsyncScrollingState state;
- state.main_thread_wheel_event_regions.append({
- .context = { Compositing::VISUAL_VIEWPORT_NODE_INDEX },
- .rect = { 0, 0, 100, 100 },
- });
-
- Compositing::AsyncScrollTree scroll_tree;
- scroll_tree.set_state(move(state));
- scroll_tree.rebuild_wheel_hit_test_targets(make_empty_display_list(visual_context_tree), &visual_context_tree, {});
- auto current_result = scroll_tree.hit_test_scroll_node_for_wheel(
- visual_context_tree, { 20, 20 }, { 0, 10 });
- EXPECT_EQ(current_result.outcome, Compositing::WheelHitTestOutcome::BlockedByMainThreadRegion);
-
- auto replacement_tree = make_visual_context_tree();
- auto replacement_result = scroll_tree.hit_test_scroll_node_for_wheel(
- replacement_tree, { 20, 20 }, { 0, 10 });
- EXPECT_EQ(replacement_result.outcome, Compositing::WheelHitTestOutcome::HitTestTargetsOfAnotherVisualContextTree);
-}
-
-TEST_CASE(wheel_hit_testing_ignores_invalid_visual_context_indices)
-{
- auto visual_context_tree = make_visual_context_tree();
- Compositing::AsyncScrollingState state;
- state.main_thread_wheel_event_regions.append({
- .context = { Compositing::SpatialNodeIndex { 100 } },
- .rect = { 0, 0, 100, 100 },
- });
-
- Compositing::AsyncScrollTree scroll_tree;
- scroll_tree.set_state(move(state));
- scroll_tree.rebuild_wheel_hit_test_targets(make_empty_display_list(visual_context_tree), &visual_context_tree, {});
- auto result = scroll_tree.hit_test_scroll_node_for_wheel(
- visual_context_tree, { 20, 20 }, { 0, 10 });
- EXPECT_NE(result.outcome, Compositing::WheelHitTestOutcome::BlockedByMainThreadRegion);
-}
-
-TEST_CASE(blocking_wheel_event_hit_testing_fails_closed_for_invalid_visual_context_indices)
-{
- auto visual_context_tree = make_visual_context_tree();
- auto state = make_scrolling_state_with_viewport_scroll_node(2000);
- state.has_blocking_wheel_event_listeners = true;
- state.blocking_wheel_event_regions.append({
- .context = { Compositing::SpatialNodeIndex { 100 } },
- .rect = { 0, 0, 100, 100 },
- });
-
- auto display_list = make_empty_display_list(visual_context_tree);
- Compositing::AsyncScrollTree scroll_tree;
- scroll_tree.set_state(move(state));
- scroll_tree.rebuild_wheel_hit_test_targets(display_list, &visual_context_tree, {});
- EXPECT(scroll_tree.blocks_wheel_event_at_position(visual_context_tree, { 200, 200 }));
- auto result = scroll_tree.hit_test_scroll_node_for_wheel(visual_context_tree, { 200, 200 }, { 0, 10 });
- EXPECT_EQ(result.outcome, Compositing::WheelHitTestOutcome::BlockedByWheelEventRegion);
- EXPECT(!result.scroll_node_index.has_value());
-}
-
-TEST_CASE(first_wheel_step_route_puts_main_thread_region_before_blocking_region_and_viewport_blocker_before_both)
-{
- auto visual_context_tree = make_visual_context_tree();
- auto display_list = make_empty_display_list(visual_context_tree);
- auto state = make_scrolling_state_with_viewport_scroll_node(2000);
- state.has_blocking_wheel_event_listeners = true;
- state.blocking_wheel_event_regions.append({
- .context = { Compositing::VISUAL_VIEWPORT_NODE_INDEX },
- .rect = { 0, 0, 100, 100 },
- });
- state.main_thread_wheel_event_regions.append({
- .context = { Compositing::VISUAL_VIEWPORT_NODE_INDEX },
- .rect = { 0, 0, 100, 100 },
- });
- auto route_first_wheel_step_at = [&](Compositing::AsyncScrollingState state) {
- Compositing::AsyncScrollTree scroll_tree;
- scroll_tree.set_state(move(state));
- scroll_tree.rebuild_wheel_hit_test_targets(display_list, &visual_context_tree, {});
- EXPECT(scroll_tree.blocks_wheel_event_at_position(visual_context_tree, { 20, 20 }));
- return scroll_tree.route_first_wheel_step(Compositing::WheelRoutingAdmission::Accepted, visual_context_tree, { 20, 20 }, { 0, 10 }).decision;
- };
-
- EXPECT_EQ(route_first_wheel_step_at(state), Web::InputRoutingDecision::BlockedByMainThreadRegion);
-
- state.has_blocking_wheel_event_region_covering_viewport = true;
- EXPECT_EQ(route_first_wheel_step_at(state), Web::InputRoutingDecision::BlockedByWheelEventRegion);
-}
-
-TEST_CASE(async_scrolling_resolves_sticky_offsets_from_the_visual_context_tree)
-{
- Compositing::VisualContextTreeTestBuilder builder;
- auto viewport_scroll_node = builder.append_scroll(Compositing::VISUAL_VIEWPORT_NODE_INDEX);
- // A 50px header 100px down the document, sticking to the top of the scrollport within a 2000px containing block.
- auto header_node = builder.append_sticky(viewport_scroll_node,
- {
- .scroller = viewport_scroll_node,
- .parent_sticky = {},
- .position_relative_to_scroller = { 0, 100 },
- .border_box_size = { 800, 50 },
- .scrollport_size = { 800, 600 },
- .containing_block_region = { 0, 0, 800, 2000 },
- .needs_parent_offset_adjustment = true,
- .inset_top = 0.f,
- .inset_right = {},
- .inset_bottom = {},
- .inset_left = {},
- });
- // A 10px bar inside the header, sticking 20px below the scrollport top within the header's box.
- auto bar_node = builder.append_sticky(header_node,
- {
- .scroller = viewport_scroll_node,
- .parent_sticky = header_node,
- .position_relative_to_scroller = { 0, 110 },
- .border_box_size = { 800, 10 },
- .scrollport_size = { 800, 600 },
- .containing_block_region = { 0, 100, 800, 50 },
- .needs_parent_offset_adjustment = true,
- .inset_top = 20.f,
- .inset_right = {},
- .inset_bottom = {},
- .inset_left = {},
- });
- auto visual_context_tree = builder.finish();
-
- auto scroll_tree = make_scroll_tree_with_viewport_scroll_node(2000);
- Compositing::ScrollStateSnapshot snapshot;
-
- auto scroll_offset = scroll_tree.apply_scroll_delta(viewport_scroll_node_index, { 0, 300 }, visual_context_tree, snapshot, Compositing::ScrollChaining::ToScrollableAncestors);
- EXPECT(scroll_offset.has_value());
- EXPECT_EQ(snapshot.device_offset_for_index(viewport_scroll_node), (Gfx::FloatPoint { 0, -300 }));
- // The scrollport top passed the header by 200px, so the header follows it by that much.
- EXPECT_EQ(snapshot.device_offset_for_index(header_node), (Gfx::FloatPoint { 0, 200 }));
- // With the header at 300, the bar sits at 310 and its inset asks for 320.
- EXPECT_EQ(snapshot.device_offset_for_index(bar_node), (Gfx::FloatPoint { 0, 10 }));
-
- // Past the end of the containing block, the header pins to the block's bottom edge and the bar to the header's.
- EXPECT(scroll_tree.set_scroll_offset(viewport_scroll_node_index, { 0, 1960 }, visual_context_tree, snapshot).has_value());
- EXPECT_EQ(snapshot.device_offset_for_index(header_node), (Gfx::FloatPoint { 0, 1850 }));
- EXPECT_EQ(snapshot.device_offset_for_index(bar_node), (Gfx::FloatPoint { 0, 20 }));
-
- // Scrolled back above the header, nothing sticks.
- EXPECT(scroll_tree.set_scroll_offset(viewport_scroll_node_index, { 0, 50 }, visual_context_tree, snapshot).has_value());
- EXPECT_EQ(snapshot.device_offset_for_index(header_node), (Gfx::FloatPoint { 0, 0 }));
- EXPECT_EQ(snapshot.device_offset_for_index(bar_node), (Gfx::FloatPoint { 0, 0 }));
-}
-
-TEST_CASE(a_key_is_not_passed_on_from_a_scroller_that_keeps_its_scrolls)
-{
- Compositing::SpatialNodeIndex const nested_scroll_node_index { 2 };
- Web::AsyncScrollNodeStableID const nested_stable_node_id { .node_id = Web::UniqueNodeID { 3 }, .kind = Web::AsyncScrollNodeKind::Element, .pseudo_element_type = 0 };
-
- auto scroll_tree_with_nested_scroller = [&](bool nested_scroller_chains_vertically) {
- auto state = make_scrolling_state_with_viewport_scroll_node(2000);
- state.scroll_nodes.append({
- .scroll_node_index = nested_scroll_node_index,
- .stable_node_id = nested_stable_node_id,
- .parent_scroll_node_index = viewport_scroll_node_index,
- .scrollport_rect = { 0, 0, 100, 100 },
- .min_scroll_offset = { 0, 0 },
- .max_scroll_offset = { 0, 200 },
- .is_viewport = false,
- .can_be_wheel_scrolled_horizontally = false,
- .can_be_wheel_scrolled_vertically = true,
- .chains_scroll_to_ancestors_horizontally = true,
- .chains_scroll_to_ancestors_vertically = nested_scroller_chains_vertically,
- });
- Compositing::AsyncScrollTree scroll_tree;
- scroll_tree.set_state(move(state));
- return scroll_tree;
- };
-
- // The viewport is scrolled down and the nested scroller is at its top, so only the viewport can scroll up.
- Compositing::ScrollStateSnapshot snapshot;
- snapshot.set_device_offset_for_index(viewport_scroll_node_index, { 0, -300 });
-
- auto target_of_key_that_is_passed_on = scroll_tree_with_nested_scroller(true).scroll_node_for_keyboard_scroll(nested_stable_node_id, { 0, -100 }, snapshot);
- EXPECT(target_of_key_that_is_passed_on.has_value() && *target_of_key_that_is_passed_on == viewport_scroll_node_index);
-
- auto target_of_key_that_is_kept = scroll_tree_with_nested_scroller(false).scroll_node_for_keyboard_scroll(nested_stable_node_id, { 0, -100 }, snapshot);
- EXPECT(!target_of_key_that_is_kept.has_value());
-
- auto target_of_key_the_scroller_can_scroll_by = scroll_tree_with_nested_scroller(false).scroll_node_for_keyboard_scroll(nested_stable_node_id, { 0, 100 }, snapshot);
- EXPECT(target_of_key_the_scroller_can_scroll_by.has_value() && *target_of_key_the_scroller_can_scroll_by == nested_scroll_node_index);
-}
diff --git a/Tests/LibCompositing/CMakeLists.txt b/Tests/LibCompositing/CMakeLists.txt
index 78b23ed4da7..d2415e85339 100644
--- a/Tests/LibCompositing/CMakeLists.txt
+++ b/Tests/LibCompositing/CMakeLists.txt
@@ -1,18 +1,15 @@
ladybird_test_suite(LibCompositing)
set(TEST_SOURCES
- TestElasticOverscroll.cpp
TestOverlayFade.cpp
TestOverlayGeometry.cpp
TestPausedDebuggerOverlay.cpp
TestPictureInPictureControls.cpp
TestScrollRequest.cpp
TestScrollState.cpp
- TestSmoothScrollAnimation.cpp
TestTextureUpload.cpp
TestUIOverlays.cpp
TestVideoFrameHold.cpp
- TestWheelGestureIdentity.cpp
)
target_sources(TestLibCompositing PRIVATE ${TEST_SOURCES})
diff --git a/Tests/LibCompositing/TestElasticOverscroll.cpp b/Tests/LibCompositing/TestElasticOverscroll.cpp
deleted file mode 100644
index d33117a8de8..00000000000
--- a/Tests/LibCompositing/TestElasticOverscroll.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-#include <LibCompositing/Scrolling/ElasticOverscroll.h>
-#include <LibTest/TestCase.h>
-
-using Compositing::ElasticOverscroll;
-
-static constexpr Gfx::FloatSize scrollport_size { 800, 600 };
-
-static MonotonicTime time_after_release(MonotonicTime released_at, i64 milliseconds)
-{
- return released_at + AK::Duration::from_milliseconds(milliseconds);
-}
-
-TEST_CASE(pull_stretches_by_a_fraction_of_the_overscroll_in_whole_pixels)
-{
- ElasticOverscroll overscroll { scrollport_size };
- EXPECT(overscroll.is_at_rest());
-
- overscroll.pull_by({ 0, -19 });
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, 0));
- EXPECT(!overscroll.is_at_rest());
-
- overscroll.pull_by({ 0, -381 });
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, -20));
-}
-
-TEST_CASE(pull_never_stretches_past_the_scrollport_length)
-{
- ElasticOverscroll overscroll { scrollport_size };
- overscroll.pull_by({ 1'000'000, 1'000'000 });
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(800, 600));
-}
-
-TEST_CASE(delta_back_to_the_scroll_range_relaxes_the_stretch_one_to_one_before_it_scrolls)
-{
- ElasticOverscroll overscroll { scrollport_size };
- overscroll.pull_by({ 0, -400 });
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, -20));
-
- EXPECT_EQ(overscroll.relax_by({ 7, 5 }), Gfx::FloatPoint(7, 0));
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, -15));
-
- EXPECT_EQ(overscroll.relax_by({ 0, -50 }), Gfx::FloatPoint(0, -50));
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, -15));
-
- EXPECT_EQ(overscroll.relax_by({ 0, 65 }), Gfx::FloatPoint(0, 50));
- EXPECT(overscroll.is_at_rest());
-}
-
-TEST_CASE(released_stretch_springs_back_without_crossing_the_edge)
-{
- ElasticOverscroll overscroll { scrollport_size };
- overscroll.pull_by({ 0, -2000 });
- auto released_at = MonotonicTime::now();
- overscroll.release({}, released_at);
- EXPECT(overscroll.is_rebounding());
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, -100));
-
- // A display tick from before the release must not rewind the rebound.
- EXPECT(overscroll.advance_rebound_to(released_at - AK::Duration::from_milliseconds(5)));
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, -100));
-
- auto previous_stretch = overscroll.stretch().y();
- bool rebounding = true;
- for (i64 milliseconds = 8; milliseconds <= 1000 && rebounding; milliseconds += 8) {
- rebounding = overscroll.advance_rebound_to(time_after_release(released_at, milliseconds));
- auto stretch = overscroll.stretch().y();
- EXPECT(stretch <= 0);
- EXPECT(stretch >= previous_stretch);
- previous_stretch = stretch;
- }
- EXPECT(!rebounding);
- EXPECT(overscroll.is_at_rest());
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, 0));
-}
-
-TEST_CASE(release_velocity_back_to_the_scroll_range_stops_at_the_edge)
-{
- ElasticOverscroll overscroll { scrollport_size };
- overscroll.pull_by({ 0, -400 });
- auto released_at = MonotonicTime::now();
- overscroll.release({ 0, 5000 }, released_at);
-
- bool rebounding = true;
- for (i64 milliseconds = 8; milliseconds <= 1000 && rebounding; milliseconds += 8) {
- rebounding = overscroll.advance_rebound_to(time_after_release(released_at, milliseconds));
- EXPECT(overscroll.stretch().y() <= 0);
- }
- EXPECT(!rebounding);
-}
-
-TEST_CASE(momentum_into_an_edge_bounces_out_and_back_within_a_share_of_the_scrollport)
-{
- ElasticOverscroll overscroll { scrollport_size };
- overscroll.pull_by({ 0, 4 });
- auto released_at = MonotonicTime::now();
- // The velocity of the unstretched axis is not the velocity of a scroller at an edge.
- overscroll.release({ 1'000'000, 1'000'000 }, released_at);
-
- float furthest_stretch = 0;
- bool rebounding = true;
- for (i64 milliseconds = 8; milliseconds <= 2000 && rebounding; milliseconds += 8) {
- rebounding = overscroll.advance_rebound_to(time_after_release(released_at, milliseconds));
- EXPECT_EQ(overscroll.stretch().x(), 0.0f);
- furthest_stretch = max(furthest_stretch, overscroll.stretch().y());
- }
- EXPECT(!rebounding);
- EXPECT(furthest_stretch > 60);
- EXPECT(furthest_stretch <= 600 * 0.2f + 1);
-}
-
-TEST_CASE(fingers_take_a_rebound_over_from_where_it_has_got_to)
-{
- ElasticOverscroll overscroll { scrollport_size };
- overscroll.pull_by({ 0, -2000 });
- auto released_at = MonotonicTime::now();
- overscroll.release({}, released_at);
- EXPECT(overscroll.advance_rebound_to(time_after_release(released_at, 50)));
- auto stretch_when_taken_over = overscroll.stretch();
- EXPECT(stretch_when_taken_over.y() < 0);
- EXPECT(stretch_when_taken_over.y() > -100);
-
- EXPECT_EQ(overscroll.relax_by({ 0, -40 }), Gfx::FloatPoint(0, -40));
- EXPECT(!overscroll.is_rebounding());
- EXPECT(AK::abs(overscroll.stretch().y() - stretch_when_taken_over.y()) <= 1);
-
- overscroll.pull_by({ 0, -40 });
- EXPECT(overscroll.stretch().y() < stretch_when_taken_over.y());
-}
-
-TEST_CASE(magnified_scroller_stretches_and_springs_back_in_whole_pixels_of_the_screen)
-{
- ElasticOverscroll overscroll { scrollport_size, 2 };
- overscroll.pull_by({ 0, -150 });
- EXPECT_EQ(overscroll.stretch(), Gfx::FloatPoint(0, -7.5f));
-
- overscroll.pull_by({ 0, -1850 });
- auto released_at = MonotonicTime::now();
- overscroll.release({}, released_at);
-
- float smallest_stretch_presented = 100;
- bool rebounding = true;
- for (i64 milliseconds = 1; milliseconds <= 1000 && rebounding; ++milliseconds) {
- rebounding = overscroll.advance_rebound_to(time_after_release(released_at, milliseconds));
- auto stretch = AK::abs(overscroll.stretch().y());
- EXPECT_EQ(stretch * 2, AK::trunc(stretch * 2));
- if (stretch != 0)
- smallest_stretch_presented = min(smallest_stretch_presented, stretch);
- }
- EXPECT(!rebounding);
- EXPECT_EQ(smallest_stretch_presented, 0.5f);
-}
diff --git a/Tests/LibCompositing/TestScrollState.cpp b/Tests/LibCompositing/TestScrollState.cpp
index 4452373d180..0922a4b011b 100644
--- a/Tests/LibCompositing/TestScrollState.cpp
+++ b/Tests/LibCompositing/TestScrollState.cpp
@@ -6,10 +6,6 @@
#include <AK/MemoryStream.h>
#include <AK/Queue.h>
-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>
-#include <LibCompositing/DisplayList/VisualContextTreeTestBuilder.h>
-#include <LibCompositing/Scrolling/AsyncScrollTree.h>
-#include <LibCompositing/Scrolling/AsyncScrollingState.h>
#include <LibCompositing/Scrolling/ScrollState.h>
#include <LibGfx/Point.h>
#include <LibIPC/Attachment.h>
@@ -80,61 +76,6 @@ TEST_CASE(set_device_offset_ignores_index_at_or_past_node_count)
EXPECT(snapshot.device_offsets().size() <= 4u);
}
-static AccumulatedVisualContextTree make_tree_with_four_spatial_nodes()
-{
- VisualContextTreeTestBuilder builder;
- // The builder seeds the viewport node, so three appends leave four.
- builder.append_transform(VISUAL_VIEWPORT_NODE_INDEX, Gfx::FloatMatrix4x4::identity());
- builder.append_transform(VISUAL_VIEWPORT_NODE_INDEX, Gfx::FloatMatrix4x4::identity());
- builder.append_transform(VISUAL_VIEWPORT_NODE_INDEX, Gfx::FloatMatrix4x4::identity());
- return builder.finish();
-}
-
-static Compositing::AsyncScrollNode make_scroll_node(SpatialNodeIndex scroll_node_index)
-{
- return {
- .scroll_node_index = scroll_node_index,
- .stable_node_id = {
- .node_id = Web::UniqueNodeID { 1 },
- .kind = Web::AsyncScrollNodeKind::Element,
- .pseudo_element_type = 0,
- },
- .parent_scroll_node_index = {},
- .scrollport_rect = Gfx::IntRect { 0, 0, 100, 100 },
- .min_scroll_offset = Gfx::FloatPoint { 0, 0 },
- .max_scroll_offset = Gfx::FloatPoint { 100, 100 },
- .is_viewport = false,
- .can_be_wheel_scrolled_horizontally = true,
- .can_be_wheel_scrolled_vertically = true,
- };
-}
-
-TEST_CASE(async_scroll_tree_ignores_out_of_range_scroll_node_index)
-{
- // The second ingress: a crafted CompositorScrollNode command in the display list gives the scroll tree an out-of-
- // range scroll node index — which apply_scroll_delta feeds to the same dense-store setter. The node-count bound on
- // the snapshot drops it, instead of aborting.
- Compositing::AsyncScrollingState state;
- auto out_of_range_index = SpatialNodeIndex { malicious_index };
- state.scroll_nodes.append(make_scroll_node(out_of_range_index));
-
- Compositing::AsyncScrollTree scroll_tree;
- scroll_tree.set_state(move(state));
-
- auto tree = make_tree_with_four_spatial_nodes();
- ScrollStateSnapshot snapshot;
- snapshot.set_node_count(tree.spatial_node_count());
- (void)scroll_tree.apply_scroll_delta(
- out_of_range_index,
- Gfx::FloatPoint { 10, 10 },
- tree,
- snapshot,
- Compositing::ScrollChaining::ToScrollableAncestors);
-
- EXPECT(snapshot.device_offsets().size() <= 4u);
- EXPECT_EQ(snapshot.device_offset_for_index(out_of_range_index), Gfx::FloatPoint {});
-}
-
TEST_CASE(ipc_round_trip_preserves_scroll_offsets)
{
ScrollStateSnapshot snapshot;
diff --git a/Tests/LibCompositing/TestSmoothScrollAnimation.cpp b/Tests/LibCompositing/TestSmoothScrollAnimation.cpp
deleted file mode 100644
index 087f8060c00..00000000000
--- a/Tests/LibCompositing/TestSmoothScrollAnimation.cpp
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCompositing/Scrolling/SmoothScrollAnimation.h>
-#include <LibTest/TestCase.h>
-
-using Compositing::ScrollAnimationKind;
-using Compositing::SmoothScrollAnimation;
-
-TEST_CASE(zero_distance_completes_immediately)
-{
- SmoothScrollAnimation animation({ 20, 40 }, { 20, 40 }, 1.0);
-
- EXPECT_EQ(animation.duration(), AK::Duration::zero());
- auto sample = animation.sample(AK::Duration::zero());
- EXPECT(sample.complete);
- EXPECT_EQ(sample.offset, Gfx::FloatPoint(20, 40));
-}
-
-TEST_CASE(duration_is_based_on_distance_and_capped)
-{
- SmoothScrollAnimation short_animation({ 0, 0 }, { 60, 80 }, 1.0);
- EXPECT_EQ(short_animation.duration(), AK::Duration::from_milliseconds(100));
-
- SmoothScrollAnimation long_animation({ 0, 0 }, { 1000, 1000 }, 1.0);
- EXPECT_EQ(long_animation.duration(), AK::Duration::from_milliseconds(200));
-}
-
-TEST_CASE(samples_an_ease_in_out_curve)
-{
- SmoothScrollAnimation animation({ 10, 20 }, { 110, 220 }, 1.0);
-
- auto start = animation.sample(AK::Duration::zero());
- EXPECT(!start.complete);
- EXPECT_EQ(start.offset, Gfx::FloatPoint(10, 20));
-
- auto midpoint = animation.sample(AK::Duration::from_milliseconds(animation.duration().to_milliseconds() / 2));
- EXPECT(!midpoint.complete);
- EXPECT_APPROXIMATE(midpoint.offset.x(), 60.0f);
- EXPECT_APPROXIMATE(midpoint.offset.y(), 120.0f);
-
- auto end = animation.sample(animation.duration());
- EXPECT(end.complete);
- EXPECT_EQ(end.offset, Gfx::FloatPoint(110, 220));
-}
-
-TEST_CASE(retarget_continues_at_the_speed_the_animation_had)
-{
- SmoothScrollAnimation animation({ 0, 0 }, { 0, 200 }, 1.0);
- auto const retarget_time = AK::Duration::from_milliseconds(100);
- auto const millisecond = AK::Duration::from_milliseconds(1);
- auto offset_before = animation.sample(retarget_time - millisecond).offset.y();
- auto offset_at_retarget = animation.sample(retarget_time).offset.y();
-
- animation.retarget({ 0, 400 }, retarget_time);
-
- EXPECT_APPROXIMATE(animation.sample(retarget_time).offset.y(), offset_at_retarget);
- auto offset_after = animation.sample(retarget_time + millisecond).offset.y();
- EXPECT_APPROXIMATE_WITH_ERROR(offset_after - offset_at_retarget, offset_at_retarget - offset_before, 0.1f);
-
- auto end = animation.sample(retarget_time + animation.duration());
- EXPECT(end.complete);
- EXPECT_EQ(end.offset, Gfx::FloatPoint(0, 400));
-}
-
-TEST_CASE(retarget_to_another_axis_never_moves_backwards)
-{
- SmoothScrollAnimation animation({ 0, 0 }, { 0, 40 }, 1.0);
- auto const retarget_time = AK::Duration::from_milliseconds(20);
- auto offset_at_retarget = animation.sample(retarget_time).offset;
-
- animation.retarget({ offset_at_retarget.x() - 40, 40 }, retarget_time);
-
- for (auto elapsed = retarget_time; elapsed < retarget_time + animation.duration(); elapsed = elapsed + AK::Duration::from_milliseconds(1)) {
- auto offset = animation.sample(elapsed).offset;
- EXPECT(offset.x() <= offset_at_retarget.x());
- EXPECT(offset.y() >= offset_at_retarget.y());
- }
-}
-
-TEST_CASE(duration_is_independent_of_device_scale)
-{
- SmoothScrollAnimation css_pixel_animation({ 0, 0 }, { 60, 80 }, 1.0);
- SmoothScrollAnimation device_pixel_animation({ 0, 0 }, { 120, 160 }, 2.0);
-
- EXPECT_EQ(css_pixel_animation.duration(), device_pixel_animation.duration());
-}
-
-TEST_CASE(wheel_steps_take_less_time_the_further_they_go)
-{
- SmoothScrollAnimation one_step({ 0, 0 }, { 0, 120 }, 1.0, ScrollAnimationKind::Wheel);
- EXPECT_EQ(one_step.duration(), AK::Duration::from_milliseconds(200));
-
- SmoothScrollAnimation burst({ 0, 0 }, { 0, 300 }, 1.0, ScrollAnimationKind::Wheel);
- EXPECT_EQ(burst.duration(), AK::Duration::from_milliseconds(150));
-
- SmoothScrollAnimation long_burst({ 0, 0 }, { 0, 1000 }, 1.0, ScrollAnimationKind::Wheel);
- EXPECT_EQ(long_burst.duration(), AK::Duration::from_milliseconds(100));
-}
-
-TEST_CASE(momentum_travels_for_as_long_as_its_distance_takes)
-{
- // Momentum covers a longer distance over more of its decaying frames rather than at a greater speed.
- SmoothScrollAnimation short_animation({ 0, 0 }, { 0, 200 }, 1.0, ScrollAnimationKind::Momentum);
- SmoothScrollAnimation long_animation({ 0, 0 }, { 0, 1000 }, 1.0, ScrollAnimationKind::Momentum);
-
- EXPECT(short_animation.duration() > AK::Duration::from_milliseconds(200));
- EXPECT(long_animation.duration() > short_animation.duration());
-
- // However fast the momentum was, the scroll that replaces it still comes to rest.
- SmoothScrollAnimation enormous_animation({ 0, 0 }, { 0, 100'000'000 }, 1.0, ScrollAnimationKind::Momentum);
- EXPECT(enormous_animation.duration() <= AK::Duration::from_seconds(5));
-}
-
-TEST_CASE(momentum_decays_towards_its_destination)
-{
- SmoothScrollAnimation animation({ 0, 0 }, { 0, 600 }, 1.0, ScrollAnimationKind::Momentum);
-
- auto start = animation.sample(AK::Duration::zero());
- EXPECT(!start.complete);
- EXPECT_EQ(start.offset, Gfx::FloatPoint(0, 0));
-
- // The distance covered by each frame shrinks, so more than half the way is covered in the first half of the time.
- auto midpoint = animation.sample(AK::Duration::from_milliseconds(animation.duration().to_milliseconds() / 2));
- EXPECT(!midpoint.complete);
- EXPECT(midpoint.offset.y() > 300);
-
- // The scroll never travels backwards on its way to its destination.
- auto previous_offset = 0.0f;
- for (auto elapsed = AK::Duration::zero(); elapsed < animation.duration(); elapsed = elapsed + AK::Duration::from_milliseconds(16)) {
- auto offset = animation.sample(elapsed).offset.y();
- EXPECT(offset >= previous_offset);
- previous_offset = offset;
- }
-
- auto end = animation.sample(animation.duration());
- EXPECT(end.complete);
- EXPECT_EQ(end.offset, Gfx::FloatPoint(0, 600));
-}
diff --git a/Tests/LibCompositing/TestWheelGestureIdentity.cpp b/Tests/LibCompositing/TestWheelGestureIdentity.cpp
deleted file mode 100644
index 08e2d05bc32..00000000000
--- a/Tests/LibCompositing/TestWheelGestureIdentity.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCompositing/Scrolling/WheelGestureIdentity.h>
-#include <LibCompositing/Types.h>
-#include <LibTest/TestCase.h>
-#include <LibWebCommon/Page/InputEvent.h>
-
-using namespace Compositing;
-
-static constexpr Gfx::FloatPoint position { 100, 100 };
-static constexpr float position_slop = wheel_gesture_position_slop_in_css_pixels;
-static auto const rest_longer_than_the_idle_delay = user_scroll_settle_delay + AK::Duration::from_milliseconds(100);
-
-TEST_CASE(fingers_resting_on_the_touchpad_end_the_gesture_after_the_idle_delay)
-{
- auto start = MonotonicTime::now_coarse();
- auto gesture = WheelGestureIdentity::started_by(position, Web::ScrollGesturePhase::Ongoing, 0, start);
- EXPECT(gesture.is_held_by_fingers());
-
- auto after_rest = start + rest_longer_than_the_idle_delay;
- EXPECT(!gesture.is_continued_by(position, Web::ScrollGesturePhase::Ongoing, 0, after_rest, position_slop, TouchpadGestureEnd::AfterIdleDelay));
-}
-
-TEST_CASE(fingers_resting_on_the_touchpad_keep_the_gesture_until_they_lift)
-{
- auto start = MonotonicTime::now_coarse();
- auto gesture = WheelGestureIdentity::started_by(position, Web::ScrollGesturePhase::Ongoing, 0, start);
-
- auto after_rest = start + rest_longer_than_the_idle_delay;
- EXPECT(gesture.is_continued_by(position, Web::ScrollGesturePhase::Ongoing, 0, after_rest, position_slop, TouchpadGestureEnd::WhenFingersLift));
-
- // The fingers lift, and fingers that touch down long after start another gesture.
- gesture.advance_to(Web::ScrollGesturePhase::Ended, after_rest);
- EXPECT(!gesture.is_held_by_fingers());
- auto much_later = after_rest + rest_longer_than_the_idle_delay;
- EXPECT(!gesture.is_continued_by(position, Web::ScrollGesturePhase::Ongoing, 0, much_later, position_slop, TouchpadGestureEnd::WhenFingersLift));
-}
-
-TEST_CASE(momentum_that_pauses_ends_the_gesture_after_the_idle_delay)
-{
- auto start = MonotonicTime::now_coarse();
- auto gesture = WheelGestureIdentity::started_by(position, Web::ScrollGesturePhase::Ongoing, 0, start);
- gesture.advance_to(Web::ScrollGesturePhase::Momentum, start);
- EXPECT(!gesture.is_held_by_fingers());
-
- auto after_pause = start + rest_longer_than_the_idle_delay;
- EXPECT(!gesture.is_continued_by(position, Web::ScrollGesturePhase::Momentum, 0, after_pause, position_slop, TouchpadGestureEnd::WhenFingersLift));
-}
-
-TEST_CASE(a_mouse_wheel_that_pauses_ends_the_gesture_after_the_idle_delay)
-{
- auto start = MonotonicTime::now_coarse();
- auto gesture = WheelGestureIdentity::started_by(position, Web::ScrollGesturePhase::None, 0, start);
- EXPECT(!gesture.is_held_by_fingers());
-
- auto after_pause = start + rest_longer_than_the_idle_delay;
- EXPECT(!gesture.is_continued_by(position, Web::ScrollGesturePhase::None, 0, after_pause, position_slop, TouchpadGestureEnd::WhenFingersLift));
-}