Truly independent web browser
Everywhere: Send main-thread scrolls to the compositor as requests
Zaggy10240ff4b4624333
diff --git a/Libraries/LibCompositing/Scrolling/AsyncScrollTree.cpp b/Libraries/LibCompositing/Scrolling/AsyncScrollTree.cppindex 1c48e6a38fc..b26a85f2747 100644--- a/Libraries/LibCompositing/Scrolling/AsyncScrollTree.cpp+++ b/Libraries/LibCompositing/Scrolling/AsyncScrollTree.cpp@@ -229,6 +229,8 @@ Optional<AsyncScrollOffset> AsyncScrollTree::apply_scroll_delta(AsyncScrollNodeI.unadopted_scroll_delta = delta - remaining_delta,.last_relative_scroll_delta = {},.visual_viewport_scale = {},+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,};}diff --git a/Libraries/LibCompositing/Scrolling/AsyncScrollingState.h b/Libraries/LibCompositing/Scrolling/AsyncScrollingState.hindex bef9cf8737d..91b213b0845 100644--- a/Libraries/LibCompositing/Scrolling/AsyncScrollingState.h+++ b/Libraries/LibCompositing/Scrolling/AsyncScrollingState.h@@ -49,10 +49,16 @@ struct AsyncScrollOffset {Gfx::FloatPoint last_relative_scroll_delta;// The scale the visual viewport was zoomed to, which only its scroll node reports.Optional<float> visual_viewport_scale;+ // The last of the main thread's scroll requests for the box that the compositor applied before it reported this.+ u64 applied_scroll_request_id { 0 };+ // How many times the compositor had scrolled the box for user input of its own when it reported this.+ u64 user_input_scroll_count { 0 };void merge_later_scroll(AsyncScrollOffset const& later){compositor_scroll_offset = later.compositor_scroll_offset;+ applied_scroll_request_id = later.applied_scroll_request_id;+ user_input_scroll_count = later.user_input_scroll_count;if (later.visual_viewport_scale.has_value())visual_viewport_scale = later.visual_viewport_scale;unadopted_scroll_delta.translate_by(later.unadopted_scroll_delta);diff --git a/Libraries/LibCompositing/Scrolling/ScrollState.cpp b/Libraries/LibCompositing/Scrolling/ScrollState.cppindex 0becfe1e648..33b894bcbf9 100644--- a/Libraries/LibCompositing/Scrolling/ScrollState.cpp+++ b/Libraries/LibCompositing/Scrolling/ScrollState.cpp@@ -31,7 +31,6 @@ ErrorOr<void> encode(Encoder& encoder, Compositing::ScrollStateSnapshot const& sTRY(encoder.encode(static_cast<u64>(index)));TRY(encoder.encode(device_offsets[index]));}- TRY(encoder.encode(snapshot.adopted_async_scroll_sequence()));return {};}@@ -47,7 +46,6 @@ ErrorOr<Compositing::ScrollStateSnapshot> decode(Decoder& decoder)return Error::from_string_literal("IPC decode: ScrollStateSnapshot index out of range");TRY(snapshot.m_staged_offsets.try_append({ static_cast<u32>(index), offset }));}- snapshot.set_adopted_async_scroll_sequence(TRY(decoder.decode<u64>()));return snapshot;}diff --git a/Libraries/LibCompositing/Scrolling/ScrollState.h b/Libraries/LibCompositing/Scrolling/ScrollState.hindex 1c5f8c08b2b..f29bf983807 100644--- a/Libraries/LibCompositing/Scrolling/ScrollState.h+++ b/Libraries/LibCompositing/Scrolling/ScrollState.h@@ -34,11 +34,6 @@ class ScrollStateSnapshot {public:ReadonlySpan<Gfx::FloatPoint> device_offsets() const { return m_device_offsets; }- // The latest publication of the compositor's async scroll updates that WebContent had adopted- // when it took this snapshot; the compositor keeps reapplying its later scrolls over it.- u64 adopted_async_scroll_sequence() const { return m_adopted_async_scroll_sequence; }- void set_adopted_async_scroll_sequence(u64 sequence) { m_adopted_async_scroll_sequence = sequence; }-Gfx::FloatPoint device_offset_for_index(SpatialNodeIndex index) const{if (index.value() >= m_device_offsets.size())@@ -55,8 +50,7 @@ public:m_device_offsets[index.value()] = offset;}- // Replaces every offset with a freshly derived dense array, keeping the adopted async scroll- // sequence and the node count bound.+ // Replaces every offset with a freshly derived dense array, keeping the node count bound.void assign_device_offsets(ReadonlySpan<Gfx::FloatPoint> offsets){m_device_offsets.clear_with_capacity();@@ -93,7 +87,6 @@ private:Vector<Gfx::FloatPoint> m_device_offsets;Vector<StagedOffset> m_staged_offsets;size_t m_node_count { NumericLimits<size_t>::max() };- u64 m_adopted_async_scroll_sequence { 0 };};}diff --git a/Libraries/LibCompositing/Types.cpp b/Libraries/LibCompositing/Types.cppindex 056d678b074..4c5ae77f06f 100644--- a/Libraries/LibCompositing/Types.cpp+++ b/Libraries/LibCompositing/Types.cpp@@ -41,6 +41,8 @@ ErrorOr<void> encode(Encoder& encoder, Compositing::AsyncScrollOffset const& offTRY(encoder.encode(offset.unadopted_scroll_delta));TRY(encoder.encode(offset.last_relative_scroll_delta));TRY(encoder.encode(offset.visual_viewport_scale));+ TRY(encoder.encode(offset.applied_scroll_request_id));+ TRY(encoder.encode(offset.user_input_scroll_count));return {};}@@ -53,6 +55,8 @@ ErrorOr<Compositing::AsyncScrollOffset> decode(Decoder& decoder).unadopted_scroll_delta = TRY(decoder.decode<Gfx::FloatPoint>()),.last_relative_scroll_delta = TRY(decoder.decode<Gfx::FloatPoint>()),.visual_viewport_scale = TRY(decoder.decode<Optional<float>>()),+ .applied_scroll_request_id = TRY(decoder.decode<u64>()),+ .user_input_scroll_count = TRY(decoder.decode<u64>()),};}@@ -163,6 +167,54 @@ ErrorOr<Compositing::PendingAsyncScrollUpdates> decode(Decoder& decoder)};}+template<>+ErrorOr<void> encode(Encoder& encoder, Compositing::RequestedSmoothScroll const& smooth_scroll)+{+ TRY(encoder.encode(smooth_scroll.operation_id));+ TRY(encoder.encode(smooth_scroll.destination_offset));+ TRY(encoder.encode(smooth_scroll.animation_kind));+ TRY(encoder.encode(smooth_scroll.initiator));+ TRY(encoder.encode(smooth_scroll.retargets_operation));+ TRY(encoder.encode(smooth_scroll.settled_user_input_scroll_count));+ return {};+}++template<>+ErrorOr<Compositing::RequestedSmoothScroll> decode(Decoder& decoder)+{+ return Compositing::RequestedSmoothScroll {+ .operation_id = TRY(decoder.decode<Compositing::AsyncScrollOperationID>()),+ .destination_offset = TRY(decoder.decode<Gfx::FloatPoint>()),+ .animation_kind = TRY(decoder.decode<Compositing::ScrollAnimationKind>()),+ .initiator = TRY(decoder.decode<Compositing::SmoothScrollInitiator>()),+ .retargets_operation = TRY(decoder.decode<bool>()),+ .settled_user_input_scroll_count = TRY(decoder.decode<Optional<u64>>()),+ };+}++template<>+ErrorOr<void> encode(Encoder& encoder, Compositing::ScrollRequest const& request)+{+ TRY(encoder.encode(request.stable_node_id));+ TRY(encoder.encode(request.request_id));+ TRY(encoder.encode(request.jump_offset));+ TRY(encoder.encode(request.visual_viewport_scale));+ TRY(encoder.encode(request.smooth_scroll));+ return {};+}++template<>+ErrorOr<Compositing::ScrollRequest> decode(Decoder& decoder)+{+ return Compositing::ScrollRequest {+ .stable_node_id = TRY(decoder.decode<Web::AsyncScrollNodeStableID>()),+ .request_id = TRY(decoder.decode<u64>()),+ .jump_offset = TRY(decoder.decode<Optional<Gfx::FloatPoint>>()),+ .visual_viewport_scale = TRY(decoder.decode<Optional<float>>()),+ .smooth_scroll = TRY(decoder.decode<Optional<Compositing::RequestedSmoothScroll>>()),+ };+}+template<>ErrorOr<void> encode(Encoder& encoder, Compositing::AsyncScrollEnqueueResult const& result){diff --git a/Libraries/LibCompositing/Types.h b/Libraries/LibCompositing/Types.hindex 414937ac535..f4202728199 100644--- a/Libraries/LibCompositing/Types.h+++ b/Libraries/LibCompositing/Types.h@@ -116,6 +116,46 @@ enum class SmoothScrollInitiator : u8 {UserInput,};+// The main thread allocates the ids of the scrolls it requests from here up, so that they never meet the ids the+// compositor allocates for scrolls of its own.+inline constexpr AsyncScrollOperationID first_operation_id_the_main_thread_requests = AsyncScrollOperationID { 1 } << 63;++// A smooth scroll that the main thread requests, from wherever the box is once the request's instant scroll is done.+struct RequestedSmoothScroll {+ AsyncScrollOperationID operation_id { 0 };+ Gfx::FloatPoint destination_offset;+ ScrollAnimationKind animation_kind { ScrollAnimationKind::SmoothScroll };+ SmoothScrollInitiator initiator { SmoothScrollInitiator::Programmatic };+ // User input that heads the user input scroll of the same operation somewhere else, rather than starting another.+ bool retargets_operation { false };+ // For the scroll that settles a user's gesture, the count of the box's scrolls for the compositor's own user input+ // that the main thread had heard of. User input the compositor took since carries the gesture on instead.+ Optional<u64> settled_user_input_scroll_count;+};++// What the main thread asks of the compositor for one scrolling box, carried with the frame it changed the box in. A+// request aborts the box's smooth scrolls, jumps the box to an offset, then starts a smooth scroll of it, in that+// order. The compositor marks the offsets it reports for the box with the id of the last request it applied to it.+struct ScrollRequest {+ Web::AsyncScrollNodeStableID stable_node_id;+ u64 request_id { 0 };+ Optional<Gfx::FloatPoint> jump_offset;+ // The scale the visual viewport jumps to along with its offset.+ Optional<float> visual_viewport_scale;+ Optional<RequestedSmoothScroll> smooth_scroll;++ // A request made later in the same frame aborts the smooth scroll of this one, which never got under way.+ void fold_later(ScrollRequest const& later)+ {+ request_id = later.request_id;+ if (later.jump_offset.has_value()) {+ jump_offset = later.jump_offset;+ visual_viewport_scale = later.visual_viewport_scale;+ }+ smooth_scroll = later.smooth_scroll;+ }+};+// AD-HOC: Wheel events carry no gesture phase information, so a wheel gesture is considered finished once no input of// it has moved a scrolling box for this long. The side that scrolled the gesture's steps decides when its// input ran out: the compositor reports the end of a gesture whose steps it chained, and the main thread@@ -156,6 +196,16 @@ COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::PendingAsyncScrollUptemplate<>COMPOSITING_API ErrorOr<Compositing::PendingAsyncScrollUpdates> decode(Decoder&);+template<>+COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::RequestedSmoothScroll const&);+template<>+COMPOSITING_API ErrorOr<Compositing::RequestedSmoothScroll> decode(Decoder&);++template<>+COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::ScrollRequest const&);+template<>+COMPOSITING_API ErrorOr<Compositing::ScrollRequest> decode(Decoder&);+template<>COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::AsyncScrollEnqueueResult const&);template<>diff --git a/Libraries/LibWeb/CSS/VisualViewport.cpp b/Libraries/LibWeb/CSS/VisualViewport.cppindex 5c61fb48fa5..926b734a261 100644--- a/Libraries/LibWeb/CSS/VisualViewport.cpp+++ b/Libraries/LibWeb/CSS/VisualViewport.cpp@@ -156,8 +156,16 @@ void VisualViewport::scroll_by(CSSPixelPoint delta)return;m_offset += delta;did_scroll();+ did_change_offset_or_scale();+}++// The compositor zooms and pans the visual viewport too, and hears of every change made to it here.+void VisualViewport::did_change_offset_or_scale()+{update_accumulated_visual_context();m_document->set_needs_repaint(Badge<CSS::VisualViewport> {}, InvalidateDisplayList::No);+ if (auto navigable = m_document->navigable())+ navigable->did_change_scroll_offset({ .node_id = m_document->unique_id(), .kind = Web::AsyncScrollNodeKind::VisualViewport });}// https://drafts.csswg.org/cssom-view-1/#scrolling-events@@ -204,8 +212,7 @@ void VisualViewport::zoom(CSSPixelPoint position, double scale_delta)m_offset = (new_offset / m_scale).to_type<CSSPixels>();if (m_offset != old_offset)did_scroll();- update_accumulated_visual_context();- m_document->set_needs_repaint(Badge<CSS::VisualViewport> {}, InvalidateDisplayList::No);+ did_change_offset_or_scale();}void VisualViewport::set_scale_zoomed_by_compositor(double scale)@@ -213,8 +220,7 @@ void VisualViewport::set_scale_zoomed_by_compositor(double scale)if (scale == m_scale)return;m_scale = scale;- update_accumulated_visual_context();- m_document->set_needs_repaint(Badge<CSS::VisualViewport> {}, InvalidateDisplayList::No);+ did_change_offset_or_scale();}CSSPixelPoint VisualViewport::map_to_layout_viewport(CSSPixelPoint position) const@@ -243,8 +249,7 @@ void VisualViewport::reset()// Resetting performs an instant scroll, so its scrollend event is queued immediately.m_document->append_pending_scroll_event({ *this, HTML::EventNames::scrollend });}- update_accumulated_visual_context();- m_document->set_needs_repaint(Badge<CSS::VisualViewport> {}, InvalidateDisplayList::No);+ did_change_offset_or_scale();}void VisualViewport::update_accumulated_visual_context()diff --git a/Libraries/LibWeb/CSS/VisualViewport.h b/Libraries/LibWeb/CSS/VisualViewport.hindex 49ba4c86ea1..749ddc56e5d 100644--- a/Libraries/LibWeb/CSS/VisualViewport.h+++ b/Libraries/LibWeb/CSS/VisualViewport.h@@ -63,6 +63,7 @@ private:virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;void did_scroll();+ void did_change_offset_or_scale();void update_accumulated_visual_context();GC::Ref<DOM::Document> m_document;diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex aa5bc3f94d1..94699126702 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -225,6 +225,11 @@ bool CompositorConnectionFrameSink::submit(CompositorFrame&& frame)if (!post(encoded_message))return false;}+ if (!frame.scroll_requests.is_empty()) {+ auto encoded_message = MUST(Messages::CompositorWebContentServer::ApplyScrollRequests::static_encode(context_id, frame.scroll_requests));+ if (!post(encoded_message))+ return false;+ }if (frame.present_viewport_rect.has_value()) {auto encoded_message = MUST(Messages::CompositorWebContentServer::PresentFrame::static_encode(context_id, *frame.present_viewport_rect));if (!post(encoded_message))@@ -494,19 +499,6 @@ Compositing::AsyncScrollEnqueueResult CompositorConnection::async_scroll_by(Web:return response->take_result();}-Compositing::AsyncScrollEnqueueResult CompositorConnection::smooth_scroll_to(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind animation_kind, Compositing::SmoothScrollInitiator initiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue)-{- if (!can_send_message_to_compositor())- return {};-- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::SmoothScrollTo>(context_id, stable_node_id, offset, main_thread_offset, viewport_rect, animation_kind, initiator, operation_to_continue);- if (!response) {- did_lose_compositor();- return {};- }- return response->take_result();-}-String CompositorConnection::scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller){if (!can_send_message_to_compositor())@@ -562,13 +554,6 @@ Vector<Web::InputTraceRecord> CompositorConnection::take_input_trace_for_testingreturn response->take_records();}-void CompositorConnection::cancel_smooth_scroll(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id)-{- if (!can_send_message_to_compositor())- return;- async_cancel_smooth_scroll(context_id, stable_node_id);-}-Compositing::PendingAsyncScrollUpdates CompositorConnection::take_pending_async_scroll_updates(Web::CompositorContextId context_id, Compositing::AsyncScrollUpdateFreshness freshness){// The compositor process pushes its scroll updates as it makes them, in order with the input@@ -634,8 +619,7 @@ void CompositorConnection::merge_async_scroll_updates(Web::CompositorContextId cfor (auto const& scroll_offset : updates.scroll_offsets) {auto existing = pending.scroll_offsets.find_if([&](auto const& existing) { return existing.stable_node_id == scroll_offset.stable_node_id; });if (existing != pending.scroll_offsets.end()) {- existing->compositor_scroll_offset = scroll_offset.compositor_scroll_offset;- existing->unadopted_scroll_delta.translate_by(scroll_offset.unadopted_scroll_delta);+ existing->merge_later_scroll(scroll_offset);} else {pending.scroll_offsets.append(scroll_offset);}diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex cf2dc1f9e22..75491a15832 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -67,8 +67,6 @@ public:void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation);void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);Compositing::AsyncScrollEnqueueResult async_scroll_by(Web::CompositorContextId, Web::UniqueNodeID document_id, Gfx::FloatPoint position, Gfx::FloatPoint delta, Gfx::IntRect viewport_rect, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, u32 modifiers, Compositing::AsyncScrollOperationTracking, Compositing::WheelStepDispatch, u64 input_event_id);- Compositing::AsyncScrollEnqueueResult smooth_scroll_to(Web::CompositorContextId, Web::AsyncScrollNodeStableID, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind, Compositing::SmoothScrollInitiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue);- void cancel_smooth_scroll(Web::CompositorContextId, Web::AsyncScrollNodeStableID);String scroll_state_for_testing(Web::CompositorContextId, Web::AsyncScrollNodeStableID stretched_scroller);void synchronize_for_testing();Optional<Compositing::FirstWheelStepRouteForTesting> route_first_wheel_step_for_testing(Web::CompositorContextId, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels);diff --git a/Libraries/LibWeb/Compositor/CompositorFrame.h b/Libraries/LibWeb/Compositor/CompositorFrame.hindex 35d55bcb6e8..b67a5e40f50 100644--- a/Libraries/LibWeb/Compositor/CompositorFrame.h+++ b/Libraries/LibWeb/Compositor/CompositorFrame.h@@ -51,6 +51,8 @@ struct CompositorFrame {Optional<DisplayListUpdate> display_list_update;Optional<VisualContextTreeUpdate> visual_context_tree_update;Optional<ScrollStateUpdate> scroll_state_update;+ // The scrolls the main thread asked for, which go after the frame's boxes.+ Vector<Compositing::ScrollRequest> scroll_requests;// Set when the frame is presented once the compositor has applied it.Optional<Gfx::IntRect> present_viewport_rect;diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex b91513cc9e5..f4ae83285cf 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -67,16 +67,6 @@ Compositing::AsyncScrollEnqueueResult CompositorContextHandle::async_scroll_by(Ureturn m_host.async_scroll_by(m_context_id, expected_document_id, position, delta_in_device_pixels, viewport_rect, wheel_delta_precision, scroll_gesture_phase, modifiers, operation_tracking, wheel_step_dispatch, input_event_id);}-Compositing::AsyncScrollEnqueueResult CompositorContextHandle::smooth_scroll_to(Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint offset_in_device_pixels, Gfx::FloatPoint main_thread_offset_in_device_pixels, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind animation_kind, Compositing::SmoothScrollInitiator initiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue)-{- return m_host.smooth_scroll_to(m_context_id, stable_node_id, offset_in_device_pixels, main_thread_offset_in_device_pixels, viewport_rect, animation_kind, initiator, operation_to_continue);-}--void CompositorContextHandle::cancel_smooth_scroll(Web::AsyncScrollNodeStableID stable_node_id)-{- m_host.cancel_smooth_scroll(m_context_id, stable_node_id);-}-String CompositorContextHandle::scroll_state_for_testing(Web::AsyncScrollNodeStableID stretched_scroller){return m_host.scroll_state_for_testing(m_context_id, stretched_scroller);@@ -475,19 +465,6 @@ Compositing::AsyncScrollEnqueueResult CompositorHost::async_scroll_by(Web::Comporeturn {};}-Compositing::AsyncScrollEnqueueResult CompositorHost::smooth_scroll_to(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint offset_in_device_pixels, Gfx::FloatPoint main_thread_offset_in_device_pixels, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind animation_kind, Compositing::SmoothScrollInitiator initiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue)-{- if (auto* connection = compositor_connection())- return connection->smooth_scroll_to(context_id, stable_node_id, offset_in_device_pixels, main_thread_offset_in_device_pixels, viewport_rect, animation_kind, initiator, operation_to_continue);- return {};-}--void CompositorHost::cancel_smooth_scroll(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id)-{- if (auto* connection = compositor_connection())- connection->cancel_smooth_scroll(context_id, stable_node_id);-}-String CompositorHost::scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller){if (auto* connection = compositor_connection())diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.hindex 45158f0d209..755426d2293 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.h+++ b/Libraries/LibWeb/Compositor/CompositorHost.h@@ -61,8 +61,6 @@ public:void invalidate_keyboard_scroll_state(u64 generation);Compositing::AsyncScrollEnqueueResult async_scroll_by(UniqueNodeID expected_document_id, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_device_pixels,Gfx::IntRect viewport_rect, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, u32 modifiers, Compositing::AsyncScrollOperationTracking, Compositing::WheelStepDispatch, u64 input_event_id);- Compositing::AsyncScrollEnqueueResult smooth_scroll_to(Web::AsyncScrollNodeStableID, Gfx::FloatPoint offset_in_device_pixels, Gfx::FloatPoint main_thread_offset_in_device_pixels, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind, Compositing::SmoothScrollInitiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue);- void cancel_smooth_scroll(Web::AsyncScrollNodeStableID);String scroll_state_for_testing(Web::AsyncScrollNodeStableID stretched_scroller);void synchronize_for_testing();Optional<Compositing::FirstWheelStepRouteForTesting> route_first_wheel_step_for_testing(Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels);@@ -124,8 +122,6 @@ public:void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);Compositing::AsyncScrollEnqueueResult async_scroll_by(Web::CompositorContextId, UniqueNodeID expected_document_id, Gfx::FloatPoint position,Gfx::FloatPoint delta_in_device_pixels, Gfx::IntRect viewport_rect, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, u32 modifiers, Compositing::AsyncScrollOperationTracking, Compositing::WheelStepDispatch, u64 input_event_id);- Compositing::AsyncScrollEnqueueResult smooth_scroll_to(Web::CompositorContextId, Web::AsyncScrollNodeStableID, Gfx::FloatPoint offset_in_device_pixels, Gfx::FloatPoint main_thread_offset_in_device_pixels, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind, Compositing::SmoothScrollInitiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue);- void cancel_smooth_scroll(Web::CompositorContextId, Web::AsyncScrollNodeStableID);String scroll_state_for_testing(Web::CompositorContextId, Web::AsyncScrollNodeStableID stretched_scroller);void synchronize_for_testing();Optional<Compositing::FirstWheelStepRouteForTesting> route_first_wheel_step_for_testing(Web::CompositorContextId, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels);diff --git a/Libraries/LibWeb/Compositor/NavigablePresenter.cpp b/Libraries/LibWeb/Compositor/NavigablePresenter.cppindex 84ec0b6dd54..70f9ef7ddfb 100644--- a/Libraries/LibWeb/Compositor/NavigablePresenter.cpp+++ b/Libraries/LibWeb/Compositor/NavigablePresenter.cpp@@ -35,6 +35,7 @@ struct PresenterFFI {if (is_stale(presenter, sealed))return;auto frame = presenter.build_frame_beside_event_loop(sealed, move(display_list));+ frame.scroll_requests = move(sealed.scroll_requests);note_presented(presenter, sealed);if (sink)sink->submit(move(frame));@@ -46,6 +47,7 @@ struct PresenterFFI {if (is_stale(presenter, sealed))return;auto frame = presenter.build_frame(sealed, {});+ frame.scroll_requests = move(sealed.scroll_requests);note_presented(presenter, sealed);if (sink)sink->submit(move(frame));diff --git a/Libraries/LibWeb/Compositor/NavigablePresenter.h b/Libraries/LibWeb/Compositor/NavigablePresenter.hindex cc00d2e28da..38e22aa3311 100644--- a/Libraries/LibWeb/Compositor/NavigablePresenter.h+++ b/Libraries/LibWeb/Compositor/NavigablePresenter.h@@ -59,8 +59,11 @@ struct SealedPresentation {Optional<Compositing::AccumulatedVisualContextTree> visual_context_tree;// Whether the document's tree changed since the compositor took one.bool sends_visual_context_tree { false };- // The scroll state, with the async scroll sequence the navigable adopted.+ // The scroll state, which seeds the offsets of the boxes new to the compositor.Compositing::ScrollStateSnapshot scroll_state_snapshot;+ // The scrolls the navigable asked for since the frame before, which the compositor applies once it has the frame's+ // boxes. Only the frame a rendering update commits carries them.+ Vector<Compositing::ScrollRequest> scroll_requests;// What keyboard scrolling targets, for a top-level traversable.Optional<Compositing::KeyboardScrollState> keyboard_scroll_state;// The display list a recording copies paint commands from, and the resources it references, which stay live whilediff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 6be821587bf..8bd0d69e349 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -6265,19 +6265,24 @@ void Element::set_last_relative_scroll_direction(u8 direction)// That is why the unchecked layout node accessor is the right one here.void Element::set_scroll_offset(Optional<CSS::PseudoElement> pseudo_element_type, CSSPixelPoint offset){+ Web::AsyncScrollNodeStableID stable_node_id { .node_id = unique_id(), .kind = Web::AsyncScrollNodeKind::Element };if (pseudo_element_type.has_value()) {auto pseudo_element = get_synthetic_pseudo_element(*pseudo_element_type);if (!pseudo_element.has_value())return;pseudo_element->set_scroll_offset(offset);- return;+ stable_node_id.kind = Web::AsyncScrollNodeKind::PseudoElement;+ stable_node_id.pseudo_element_type = static_cast<u8>(to_underlying(pseudo_element_type.value()));+ } else {+ if (!offset.is_zero())+ ensure_element_rare_data().scroll_offset = offset;+ else if (auto* rare_data = element_rare_data())+ rare_data->scroll_offset = {};+ Layout::publish_element_scroll_offset(*this);}- if (!offset.is_zero())- ensure_element_rare_data().scroll_offset = offset;- else if (auto* rare_data = element_rare_data())- rare_data->scroll_offset = {};- Layout::publish_element_scroll_offset(*this);+ if (auto navigable = document().navigable())+ navigable->did_change_scroll_offset(stable_node_id);}Optional<Element::Dir> Element::dir() constdiff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 606faa01adf..9a4eab1fee6 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -4760,6 +4760,7 @@ void LocalNavigable::perform_scroll_of_viewport_scrolling_box(CSSPixelPoint new_Layout::RustFFI::render_state_set_viewport_scroll_offset(arena->host(), new_position);document->set_needs_repaint(Badge<HTML::LocalNavigable> {}, InvalidateDisplayList::No);document->inform_all_viewport_clients_about_the_current_viewport_rect();+ did_change_scroll_offset({ .node_id = document->unique_id(), .kind = Web::AsyncScrollNodeKind::Viewport });}}@@ -4793,7 +4794,7 @@ static DOM::Element* element_for_async_scroll_node_stable_id(DOM::Document& docureturn element;}-static GC::Ptr<DOM::Element> adopt_async_element_scroll_delta(DOM::Document& document, Web::AsyncScrollNodeStableID const& stable_id, CSSPixelPoint scroll_delta)+static GC::Ptr<DOM::Element> adopt_async_element_scroll_offset(DOM::Document& document, Web::AsyncScrollNodeStableID const& stable_id, CSSPixelPoint scroll_offset){auto* element = element_for_async_scroll_node_stable_id(document, stable_id);if (!element)@@ -4815,8 +4816,6 @@ static GC::Ptr<DOM::Element> adopt_async_element_scroll_delta(DOM::Document& docbreak;}- auto scroll_offset = element->scroll_offset(pseudo_element);- scroll_offset.translate_by(scroll_delta);if (element->scroll_offset(pseudo_element) == scroll_offset)return {};@@ -5594,7 +5593,7 @@ void LocalNavigable::user_scroll_did_settle(UserScrollSettlement settlement)if (snap_destination.position != *current_scroll_offset) {// The snap animation queues this target's scrollend event once it completes.TemporaryExecutionContext temporary_execution_context { HTML::relevant_realm(*document) };- perform_a_scroll_of_a_scrolling_box(*stable_node_id, snap_destination.position, Bindings::ScrollBehavior::Smooth, nullptr, ScrollTrigger::UserInput);+ perform_a_scroll_of_a_scrolling_box(*stable_node_id, snap_destination.position, Bindings::ScrollBehavior::Smooth, nullptr, ScrollTrigger::GestureEndSnap);continue;}}@@ -5678,20 +5677,23 @@ void LocalNavigable::process_main_thread_smooth_scrolls()page().client().request_frame();}-bool LocalNavigable::adopt_async_viewport_scroll_delta(CSSPixelPoint scroll_delta)+bool LocalNavigable::adopt_async_viewport_scroll_offset(CSSPixelPoint scroll_offset){- if (!active_document())+ auto document = active_document();+ if (!document)return false;defer_user_scroll_settlement();- auto viewport_scroll_offset = m_viewport_scroll_offset;- // The direction of the scroll was recorded from the compositor's report, which knows whether it was relative.- perform_a_scroll_of_the_layout_viewport(scroll_delta, Bindings::ScrollBehavior::Instant, ScrollTrigger::UserInput, {}, Painting::ScrollKind::Absolute, Compositing::ScrollAnimationKind::SmoothScroll);- return m_viewport_scroll_offset != viewport_scroll_offset;+ auto scroll_offset_before_scroll = m_viewport_scroll_offset;+ perform_scroll_of_viewport_scrolling_box(scroll_offset);+ if (m_viewport_scroll_offset == scroll_offset_before_scroll)+ return false;+ queue_scrollend_event({ .node_id = document->unique_id(), .kind = Web::AsyncScrollNodeKind::Viewport }, ScrollTrigger::UserInput, scroll_offset_before_scroll);+ return true;}-bool LocalNavigable::adopt_async_visual_viewport_scroll(Optional<float> scale, CSSPixelPoint scroll_delta)+bool LocalNavigable::adopt_async_visual_viewport_scroll(Optional<float> scale, CSSPixelPoint scroll_offset){auto document = active_document();if (!document)@@ -5699,20 +5701,12 @@ bool LocalNavigable::adopt_async_visual_viewport_scroll(Optional<float> scale, Cdefer_user_scroll_settlement();- // A zoom moves the offset as well, which is then only in range for the new scale.auto visual_viewport = document->visual_viewport();auto scale_before_adoption = visual_viewport->scale();if (scale.has_value())visual_viewport->set_scale_zoomed_by_compositor(scale.value());- auto max_x = m_viewport_size.width().to_double() - visual_viewport->width();- auto max_y = m_viewport_size.height().to_double() - visual_viewport->height();- auto visual_x = visual_viewport->offset_left();- auto visual_y = visual_viewport->offset_top();- CSSPixelPoint visual_delta {- min(max_x, max(0.0, visual_x + scroll_delta.x().to_double())) - visual_x,- min(max_y, max(0.0, visual_y + scroll_delta.y().to_double())) - visual_y,- };+ auto visual_delta = scroll_offset - visual_viewport->offset();if (visual_delta.is_zero())return visual_viewport->scale() != scale_before_adoption;@@ -5729,7 +5723,6 @@ void LocalNavigable::adopt_pending_async_scroll_offsets(Compositing::AsyncScroll// The compositor process may have already presented newer scroll offsets. Adopt the latest ones before running// rendering-update observers so they see the same scroll positions as the user.auto async_scroll_updates = compositor_context().take_pending_async_scroll_updates(freshness);- m_adopted_async_scroll_sequence = max(m_adopted_async_scroll_sequence, async_scroll_updates.sequence);// A gesture the compositor reports for a document that is no longer active ended with that document; updates// published before the active document's scroll tree was installed still describe the previous one.@@ -5783,7 +5776,16 @@ void LocalNavigable::adopt_pending_async_scroll_offsets(Compositing::AsyncScrollauto device_pixels_per_css_pixel = page().client().device_pixels_per_css_pixel();bool adopted_any_scroll_offset = false;for (auto const& async_scroll_offset : async_scroll_updates.scroll_offsets) {- auto css_scroll_delta = async_scroll_offset_to_css_pixels(async_scroll_offset.unadopted_scroll_delta, device_pixels_per_css_pixel);+ auto& user_input_scroll_count = m_compositor_user_input_scroll_counts.ensure(async_scroll_offset.stable_node_id);+ user_input_scroll_count = max(user_input_scroll_count, async_scroll_offset.user_input_scroll_count);++ // What the compositor reported of a box before it applied the last scroll this navigable asked of it describes+ // what that scroll replaced. Once it applied it, the compositor has the box's offset.+ if (async_scroll_offset.applied_scroll_request_id < last_scroll_request_id_for(async_scroll_offset.stable_node_id))+ continue;+ TemporaryChange adopting_compositor_scroll_offsets { m_is_adopting_compositor_scroll_offsets, true };++ auto css_scroll_offset = async_scroll_offset_to_css_pixels(async_scroll_offset.compositor_scroll_offset, device_pixels_per_css_pixel);bool has_in_flight_smooth_scroll = false;for (auto const& pending_operation : m_pending_async_scroll_operations) {if (pending_operation.stable_node_id == async_scroll_offset.stable_node_id) {@@ -5792,12 +5794,8 @@ void LocalNavigable::adopt_pending_async_scroll_offsets(Compositing::AsyncScroll}}- // NB: A smooth scroll of this box has an absolute destination. Adopt the- // compositor's absolute position so that replacing scroll snapshots- // during the animation cannot cause overlapping deltas to accumulate.if (has_in_flight_smooth_scroll) {auto scroll_offset_before_scroll = scroll_offset_for(async_scroll_offset.stable_node_id);- auto css_scroll_offset = async_scroll_offset_to_css_pixels(async_scroll_offset.compositor_scroll_offset, device_pixels_per_css_pixel);if (set_scroll_offset_for(async_scroll_offset.stable_node_id, css_scroll_offset)) {adopted_any_scroll_offset = true;dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Main thread adopting async programmatic scroll offset {},{}",@@ -5816,10 +5814,10 @@ void LocalNavigable::adopt_pending_async_scroll_offsets(Compositing::AsyncScrollif (async_scroll_offset.stable_node_id.kind == Web::AsyncScrollNodeKind::VisualViewport) {if (async_scroll_offset.stable_node_id.node_id != document->unique_id())continue;- if (adopt_async_visual_viewport_scroll(async_scroll_offset.visual_viewport_scale, css_scroll_delta)) {+ if (adopt_async_visual_viewport_scroll(async_scroll_offset.visual_viewport_scale, css_scroll_offset)) {adopted_any_scroll_offset = true;- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Main thread adopting async visual viewport delta {},{}",- async_scroll_offset.unadopted_scroll_delta.x(), async_scroll_offset.unadopted_scroll_delta.y());+ dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Main thread adopting async visual viewport offset {},{}",+ async_scroll_offset.compositor_scroll_offset.x(), async_scroll_offset.compositor_scroll_offset.y());}continue;}@@ -5830,20 +5828,20 @@ void LocalNavigable::adopt_pending_async_scroll_offsets(Compositing::AsyncScrollif (async_scroll_offset.stable_node_id.kind == Web::AsyncScrollNodeKind::Viewport) {if (async_scroll_offset.stable_node_id.node_id != document->unique_id())continue;- if (adopt_async_viewport_scroll_delta(css_scroll_delta)) {+ if (adopt_async_viewport_scroll_offset(css_scroll_offset)) {adopted_any_scroll_offset = true;- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Main thread adopting async viewport delta {},{}",- async_scroll_offset.unadopted_scroll_delta.x(), async_scroll_offset.unadopted_scroll_delta.y());+ dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Main thread adopting async viewport offset {},{}",+ async_scroll_offset.compositor_scroll_offset.x(), async_scroll_offset.compositor_scroll_offset.y());}continue;}auto scroll_offset_before_scroll = scroll_offset_for(async_scroll_offset.stable_node_id);- if (auto element = adopt_async_element_scroll_delta(*document, async_scroll_offset.stable_node_id, css_scroll_delta)) {+ if (auto element = adopt_async_element_scroll_offset(*document, async_scroll_offset.stable_node_id, css_scroll_offset)) {adopted_any_scroll_offset = true;queue_scrollend_event_after_user_scroll(*element, async_scroll_offset.stable_node_id, scroll_offset_before_scroll);- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Main thread adopting async element delta {},{}",- async_scroll_offset.unadopted_scroll_delta.x(), async_scroll_offset.unadopted_scroll_delta.y());+ dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Main thread adopting async element offset {},{}",+ async_scroll_offset.compositor_scroll_offset.x(), async_scroll_offset.compositor_scroll_offset.y());}}@@ -6620,9 +6618,9 @@ OwnPtr<Compositor::CompositorContextHandle> LocalNavigable::take_compositor_contvoid LocalNavigable::repaint_after_compositor_process_reconnect(){resolve_all_pending_async_scroll_operations();- // A new compositor process publishes its scroll updates from a fresh sequence; what this navigable- // adopted from the old one acknowledges nothing of it.- m_adopted_async_scroll_sequence = 0;+ // A new compositor process has applied none of the scrolls this navigable asked the old one for.+ m_scroll_request_states.clear();+ m_compositor_user_input_scroll_counts.clear();if (has_compositor_context()) {if (auto parent = this->parent()) {@@ -6900,7 +6898,6 @@ Compositor::SealedPresentation LocalNavigable::seal_presentation(DOM::Document&visual_context_tree = paint_state.visual_context_tree(document);paint_state.did_update_visual_context_tree_in_compositor();Compositing::ScrollStateSnapshot scroll_state_snapshot { paint_state.scroll_state_snapshot() };- scroll_state_snapshot.set_adopted_async_scroll_sequence(m_adopted_async_scroll_sequence);// A keyboard scroll reads the layout, which one the host knows is stale leaves to the next frame that lays it out.Optional<Compositing::KeyboardScrollState> keyboard_scroll_state;if (is_top_level_traversable() && !document.layout_is_known_stale())@@ -6910,6 +6907,7 @@ Compositor::SealedPresentation LocalNavigable::seal_presentation(DOM::Document&.visual_context_tree = move(visual_context_tree),.sends_visual_context_tree = sends_visual_context_tree,.scroll_state_snapshot = move(scroll_state_snapshot),+ .scroll_requests = take_unsent_scroll_requests(),.keyboard_scroll_state = move(keyboard_scroll_state),.paint_command_cache_source = paint_state.display_list_used_as_paint_command_cache_source(),.paint_command_cache_source_resources = paint_state.paint_command_cache_source_referenced_resources(),@@ -6923,10 +6921,11 @@ Compositor::SealedPresentation LocalNavigable::seal_presentation(DOM::Document&// Hands `document` back what a sealed frame took of it, where no frame is built from the seal. A document whose layout// tree was torn down since (one destroyed beside the seal) has no paint state to take it back: the next tree comes with// a paint state of its own.-void LocalNavigable::unseal_presentation(DOM::Document& document, Compositor::SealedPresentation const& sealed)+void LocalNavigable::unseal_presentation(DOM::Document& document, Compositor::SealedPresentation& sealed){if (sealed.sends_visual_context_tree && document.has_paint_state())document.paint_state().did_update_visual_context_values();+ give_back_unsent_scroll_requests(move(sealed.scroll_requests));}bool LocalNavigable::take_recording_in_flight_in(TakeIn take_in)@@ -7070,10 +7069,106 @@ void LocalNavigable::render_screenshot(NonnullRefPtr<Gfx::Bitmap> target, PaintCvoid LocalNavigable::abort_in_flight_smooth_scrolls(Web::AsyncScrollNodeStableID stable_node_id, SmoothScrollAbortCause abort_cause){if (has_compositor_context())- compositor_context().cancel_smooth_scroll(stable_node_id);+ request_abort_of_smooth_scroll(stable_node_id);resolve_pending_smooth_scrolls(stable_node_id, abort_cause);}+Compositing::ScrollRequest& LocalNavigable::unsent_scroll_request_for(Web::AsyncScrollNodeStableID stable_node_id)+{+ auto& state = m_scroll_request_states.ensure(stable_node_id);+ if (!state.unsent_request.has_value()) {+ state.last_request_id = ++m_last_scroll_request_id;+ state.unsent_request = Compositing::ScrollRequest { .stable_node_id = stable_node_id, .request_id = state.last_request_id, .jump_offset = {}, .visual_viewport_scale = {}, .smooth_scroll = {} };+ // The request goes with the next frame, which it takes one being committed for.+ if (auto document = active_document())+ document->set_needs_repaint(Badge<HTML::LocalNavigable> {}, InvalidateDisplayList::No);+ }+ return state.unsent_request.value();+}++u64 LocalNavigable::last_scroll_request_id_for(Web::AsyncScrollNodeStableID stable_node_id) const+{+ auto state = m_scroll_request_states.get(stable_node_id);+ return state.has_value() ? state->last_request_id : 0;+}++// A smooth scroll that a later scroll of the same frame takes the place of never reaches the compositor, which is never+// to report its end.+void LocalNavigable::drop_unsent_smooth_scroll(Compositing::ScrollRequest& scroll_request)+{+ if (!scroll_request.smooth_scroll.has_value())+ return;+ auto operation_id = scroll_request.smooth_scroll->operation_id;+ scroll_request.smooth_scroll.clear();+ Optional<FinishedScroll> finished;+ m_pending_async_scroll_operations.remove_first_matching([&](auto const& pending) {+ if (pending.operation_id != operation_id)+ return false;+ finished = finished_scroll(pending);+ return true;+ });+ if (finished.has_value())+ queue_scrollend_event_and_promise_resolution_for_finished_scroll(finished->stable_node_id, finished->trigger, {}, finished->promises);+}++void LocalNavigable::request_scroll_jump(Web::AsyncScrollNodeStableID stable_node_id)+{+ auto scroll_offset = scroll_offset_for(stable_node_id);+ if (!scroll_offset.has_value())+ return;+ auto& scroll_request = unsent_scroll_request_for(stable_node_id);+ drop_unsent_smooth_scroll(scroll_request);+ scroll_request.jump_offset = device_scroll_offset(scroll_offset.value());+ if (stable_node_id.kind == Web::AsyncScrollNodeKind::VisualViewport)+ scroll_request.visual_viewport_scale = active_document()->visual_viewport()->scale();+}++void LocalNavigable::request_smooth_scroll(Web::AsyncScrollNodeStableID stable_node_id, Compositing::RequestedSmoothScroll smooth_scroll)+{+ auto& scroll_request = unsent_scroll_request_for(stable_node_id);+ // A scroll that continues the same operation replaces the request for it, whose promises carry over.+ if (scroll_request.smooth_scroll.has_value() && scroll_request.smooth_scroll->operation_id == smooth_scroll.operation_id)+ smooth_scroll.retargets_operation |= scroll_request.smooth_scroll->retargets_operation;+ else+ drop_unsent_smooth_scroll(scroll_request);+ scroll_request.smooth_scroll = smooth_scroll;+}++void LocalNavigable::request_abort_of_smooth_scroll(Web::AsyncScrollNodeStableID stable_node_id)+{+ drop_unsent_smooth_scroll(unsent_scroll_request_for(stable_node_id));+}++void LocalNavigable::did_change_scroll_offset(Web::AsyncScrollNodeStableID stable_node_id)+{+ if (m_is_adopting_compositor_scroll_offsets || !has_compositor_context())+ return;+ request_scroll_jump(stable_node_id);+}++Vector<Compositing::ScrollRequest> LocalNavigable::take_unsent_scroll_requests()+{+ Vector<Compositing::ScrollRequest> scroll_requests;+ for (auto& [stable_node_id, state] : m_scroll_request_states) {+ if (state.unsent_request.has_value())+ scroll_requests.append(state.unsent_request.release_value());+ }+ return scroll_requests;+}++// A frame that went nowhere gives its requests back to be sent with the next one, ahead of anything asked for since.+void LocalNavigable::give_back_unsent_scroll_requests(Vector<Compositing::ScrollRequest> scroll_requests)+{+ for (auto& scroll_request : scroll_requests) {+ auto& state = m_scroll_request_states.ensure(scroll_request.stable_node_id);+ if (state.unsent_request.has_value())+ scroll_request.fold_later(state.unsent_request.value());+ state.unsent_request = move(scroll_request);+ }+ if (auto document = active_document(); document && !scroll_requests.is_empty())+ document->set_needs_repaint(Badge<HTML::LocalNavigable> {}, InvalidateDisplayList::No);+}+void LocalNavigable::abort_in_flight_smooth_scrolls_taken_over_by_user_input(Web::AsyncScrollNodeStableID stable_node_id, CSSPixelPoint scroll_offset_at_gesture_start){auto document = active_document();@@ -7096,6 +7191,11 @@ GC::Ref<WebIDL::Promise> LocalNavigable::perform_a_scroll_of_a_scrolling_box(Webauto document = active_document();VERIFY(document);+ // The scroll that settles a gesture is the user's, and runs as one with the user's scrolls in flight.+ bool settles_user_scroll_gesture = trigger == ScrollTrigger::GestureEndSnap;+ if (settles_user_scroll_gesture)+ trigger = ScrollTrigger::UserInput;+// A gesture latched for this scrolling box may run out of input while this scroll is being started, so its// settlement waits until this scroll is under way rather than enqueuing a scroll of its own alongside it.++m_scrolls_being_started;@@ -7188,6 +7288,10 @@ GC::Ref<WebIDL::Promise> LocalNavigable::perform_a_scroll_of_a_scrolling_box(Web// smooth, perform a smooth scroll. Otherwise, perform an instant scroll.if (!should_scroll_smoothly) {auto did_scroll = set_scroll_offset_for(stable_node_id, position);+ // The compositor may have scrolled the box elsewhere since the main thread last heard, so the box jumps to the+ // position even where its offset here is unchanged.+ if (has_compositor_context())+ request_scroll_jump(stable_node_id);if (did_scroll)queue_scrollend_event(stable_node_id, trigger, initial_scroll_offset);WebIDL::resolve_promise(scroll_promise);@@ -7195,44 +7299,31 @@ GC::Ref<WebIDL::Promise> LocalNavigable::perform_a_scroll_of_a_scrolling_box(Web}// NB: The compositor has no scroll node for the visual viewport, so the main thread animates it.- bool compositor_can_animate = has_compositor_context() && stable_node_id.kind != Web::AsyncScrollNodeKind::VisualViewport;- if (compositor_can_animate) {- // NB: Do not adopt compositor progress while replacing one smooth scroll- // with another. All listeners in the current JavaScript task must- // observe the same main-thread scroll offset. The compositor starts- // the replacement from its own current visual offset.- auto target_offset = device_scroll_offset(position);- auto main_thread_offset = device_scroll_offset(*initial_scroll_offset);- auto viewport_rect = page().css_to_device_rect(this->viewport_rect()).to_type<int>();- auto initiator = trigger == ScrollTrigger::UserInput ? Compositing::SmoothScrollInitiator::UserInput : Compositing::SmoothScrollInitiator::Programmatic;- auto enqueue_result = compositor_context().smooth_scroll_to(stable_node_id, target_offset, main_thread_offset, viewport_rect, animation_kind, initiator, {});- if (enqueue_result.accepted) {- VERIFY(enqueue_result.operation_id.has_value());- m_pending_async_scroll_operations.append(PendingAsyncScrollOperation {- .operation_id = *enqueue_result.operation_id,- .promises = { scroll_promise },- .stable_node_id = stable_node_id,- .initial_scroll_offset = *initial_scroll_offset,- .destination_scroll_offset = position,- .trigger = trigger,- .animation_kind = animation_kind,- });- return scroll_promise;- }+ if (has_compositor_context() && stable_node_id.kind != Web::AsyncScrollNodeKind::VisualViewport) {+ auto operation_id = ++m_last_requested_operation_id;+ Optional<u64> settled_user_input_scroll_count;+ if (settles_user_scroll_gesture)+ settled_user_input_scroll_count = m_compositor_user_input_scroll_counts.get(stable_node_id).value_or(0);+ request_smooth_scroll(stable_node_id, {+ .operation_id = operation_id,+ .destination_offset = device_scroll_offset(position),+ .animation_kind = animation_kind,+ .initiator = trigger == ScrollTrigger::UserInput ? Compositing::SmoothScrollInitiator::UserInput : Compositing::SmoothScrollInitiator::Programmatic,+ .retargets_operation = false,+ .settled_user_input_scroll_count = settled_user_input_scroll_count,+ });+ m_pending_async_scroll_operations.append(PendingAsyncScrollOperation {+ .operation_id = operation_id,+ .promises = { scroll_promise },+ .stable_node_id = stable_node_id,+ .initial_scroll_offset = *initial_scroll_offset,+ .destination_scroll_offset = position,+ .trigger = trigger,+ .animation_kind = animation_kind,+ });+ return scroll_promise;}- // NB: A page can lack compositor scroll state before its first paint. Keep- // the same algorithm on the main thread in that case.- if (compositor_can_animate) {- // NB: The compositor rejected the replacement, so consume its last- // offset before falling back to a main-thread animation.- adopt_pending_async_scroll_offsets(Compositing::AsyncScrollUpdateFreshness::FromCompositor);- initial_scroll_offset = scroll_offset_for(stable_node_id);- if (!initial_scroll_offset.has_value()) {- WebIDL::resolve_promise(scroll_promise);- return scroll_promise;- }- }if (position == *initial_scroll_offset) {WebIDL::resolve_promise(scroll_promise);return scroll_promise;@@ -7272,15 +7363,14 @@ GC::Ptr<WebIDL::Promise> LocalNavigable::continue_in_flight_user_smooth_scroll(Wif (!has_compositor_context())return nullptr;- auto current_scroll_offset = scroll_offset_for(stable_node_id);- if (!current_scroll_offset.has_value())- return nullptr;-- auto viewport_rect = page().css_to_device_rect(this->viewport_rect()).to_type<int>();- auto enqueue_result = compositor_context().smooth_scroll_to(stable_node_id, device_scroll_offset(position), device_scroll_offset(*current_scroll_offset), viewport_rect, animation_kind, Compositing::SmoothScrollInitiator::UserInput, pending.operation_id);- if (!enqueue_result.accepted)- return nullptr;-+ request_smooth_scroll(stable_node_id, {+ .operation_id = pending.operation_id,+ .destination_offset = device_scroll_offset(position),+ .animation_kind = animation_kind,+ .initiator = Compositing::SmoothScrollInitiator::UserInput,+ .retargets_operation = true,+ .settled_user_input_scroll_count = {},+ });pending.destination_scroll_offset = position;auto scroll_promise = WebIDL::create_promise_for(*document);pending.promises.append(scroll_promise);diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.hindex d97d9b82b72..8ce486d7115 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.h+++ b/Libraries/LibWeb/HTML/LocalNavigable.h@@ -8,6 +8,7 @@#pragma once#include <AK/Assertions.h>+#include <AK/HashMap.h>#include <AK/HashTable.h>#include <AK/OwnPtr.h>#include <AK/Time.h>@@ -246,6 +247,8 @@ public:Optional<CSSPixelRect> viewport_intersection() const;void set_viewport_intersection(CSSPixelRect);void perform_scroll_of_viewport_scrolling_box(CSSPixelPoint position);+ // Every change of a scroll offset here, other than one the compositor made, goes to the compositor as a request.+ void did_change_scroll_offset(Web::AsyncScrollNodeStableID);void adopt_pending_async_scroll_offsets(Compositing::AsyncScrollUpdateFreshness = Compositing::AsyncScrollUpdateFreshness::Pushed);void adopt_started_user_scroll(DOM::Document&, Compositing::StartedUserScroll const&);void process_main_thread_smooth_scrolls();@@ -375,6 +378,8 @@ public:enum class ScrollTrigger {Programmatic,UserInput,+ // The scroll to the snap position a user's gesture ends at, which goes on with the gesture as the user's own.+ GestureEndSnap,};// Whether the snap position a gesture ends at is selected as each of its scrolls runs, or once from the offsets@@ -451,7 +456,7 @@ private:Compositor::FlightPresentation take_presentation(Compositor::SealedPresentation);void commit_unrecorded_frame(Layout::BegunRead const&, DOM::Document&, Compositor::SealedPresentation);Compositor::SealedPresentation seal_presentation(DOM::Document&, PaintConfig const&, bool records_display_list);- void unseal_presentation(DOM::Document&, Compositor::SealedPresentation const&);+ void unseal_presentation(DOM::Document&, Compositor::SealedPresentation&);void finish_recording_in_flight(RecordingInFlight&, Layout::RustFFI::FfiRecordingLanding, Layout::RustFFI::FfiPresentation);Gfx::IntRect present_viewport_rect() const;@@ -494,8 +499,8 @@ private:};GC::Ref<WebIDL::Promise> perform_a_scroll_of_a_scrolling_box(Web::AsyncScrollNodeStableID, CSSPixelPoint position, Bindings::ScrollBehavior, GC::Ptr<DOM::Element> associated_element, ScrollTrigger, Optional<CSSPixelPoint> relative_displacement = {}, DestinationSnapping = DestinationSnapping::SelectSnapPosition, Compositing::ScrollAnimationKind = Compositing::ScrollAnimationKind::SmoothScroll, Painting::ScrollKind = Painting::ScrollKind::Absolute);GC::Ref<WebIDL::Promise> perform_a_scroll_of_the_layout_viewport(CSSPixelPoint delta, Bindings::ScrollBehavior, ScrollTrigger, Optional<CSSPixelPoint> relative_displacement, Painting::ScrollKind, Compositing::ScrollAnimationKind);- bool adopt_async_viewport_scroll_delta(CSSPixelPoint);- bool adopt_async_visual_viewport_scroll(Optional<float> scale, CSSPixelPoint scroll_delta);+ bool adopt_async_viewport_scroll_offset(CSSPixelPoint);+ bool adopt_async_visual_viewport_scroll(Optional<float> scale, CSSPixelPoint scroll_offset);Gfx::FloatPoint device_scroll_offset(CSSPixelPoint) const;GC::Ptr<WebIDL::Promise> continue_in_flight_user_smooth_scroll(Web::AsyncScrollNodeStableID, CSSPixelPoint position, Compositing::ScrollAnimationKind);Optional<CSSPixelPoint> scroll_offset_for(Web::AsyncScrollNodeStableID) const;@@ -660,8 +665,27 @@ private:// The registry entry of an operation, whether the scroll was registered when it was started or is first heard of// from the compositor's report of it.PendingAsyncScrollOperation& ensure_pending_async_scroll_operation(Compositing::AsyncScrollOperationID);- // The latest publication of the compositor's async scroll updates this navigable adopted.- u64 m_adopted_async_scroll_sequence { 0 };+ // The scrolls this navigable asks the compositor for, per scrolling box: the request still to go with the next frame,+ // and the id of the last request made, which the compositor's reports of the box are older than until it applies it.+ struct ScrollRequestState {+ u64 last_request_id { 0 };+ Optional<Compositing::ScrollRequest> unsent_request;+ };+ HashMap<Web::AsyncScrollNodeStableID, ScrollRequestState> m_scroll_request_states;+ u64 m_last_scroll_request_id { 0 };+ Compositing::AsyncScrollOperationID m_last_requested_operation_id { Compositing::first_operation_id_the_main_thread_requests };+ // How many times the compositor reported having scrolled each box for its own user input.+ HashMap<Web::AsyncScrollNodeStableID, u64> m_compositor_user_input_scroll_counts;+ // Set while this navigable takes the compositor's offsets, which it asks for nothing about.+ bool m_is_adopting_compositor_scroll_offsets { false };+ Compositing::ScrollRequest& unsent_scroll_request_for(Web::AsyncScrollNodeStableID);+ u64 last_scroll_request_id_for(Web::AsyncScrollNodeStableID) const;+ void request_scroll_jump(Web::AsyncScrollNodeStableID);+ void request_smooth_scroll(Web::AsyncScrollNodeStableID, Compositing::RequestedSmoothScroll);+ void request_abort_of_smooth_scroll(Web::AsyncScrollNodeStableID);+ void drop_unsent_smooth_scroll(Compositing::ScrollRequest&);+ Vector<Compositing::ScrollRequest> take_unsent_scroll_requests();+ void give_back_unsent_scroll_requests(Vector<Compositing::ScrollRequest>);struct MainThreadSmoothScroll {Web::AsyncScrollNodeStableID stable_node_id;diff --git a/Services/Compositor/AsyncScrollUpdateOutbox.cpp b/Services/Compositor/AsyncScrollUpdateOutbox.cppindex d834e8fdbad..8622e4504fb 100644--- a/Services/Compositor/AsyncScrollUpdateOutbox.cpp+++ b/Services/Compositor/AsyncScrollUpdateOutbox.cpp@@ -43,20 +43,6 @@ Compositing::PendingAsyncScrollUpdates AsyncScrollUpdateOutbox::take_updates(booCompositing::PendingAsyncScrollUpdates updates;updates.sequence = ++m_last_publication_sequence;AK::swap(updates.scroll_offsets, m_pending_scroll_offsets);- for (auto const& scroll_offset : updates.scroll_offsets) {- bool replaced = false;- for (auto& unreconciled : m_unreconciled_scroll_offsets) {- if (unreconciled.stable_node_id != scroll_offset.stable_node_id)- continue;- unreconciled.sequence = updates.sequence;- unreconciled.compositor_scroll_offset = scroll_offset.compositor_scroll_offset;- unreconciled.visual_viewport_scale = scroll_offset.visual_viewport_scale;- replaced = true;- break;- }- if (!replaced)- m_unreconciled_scroll_offsets.append({ updates.sequence, scroll_offset.stable_node_id, scroll_offset.compositor_scroll_offset, scroll_offset.visual_viewport_scale });- }AK::swap(updates.completed_operation_ids, m_completed_operation_ids);AK::swap(updates.operation_ids_taken_over_by_user_input, m_operation_ids_taken_over_by_user_input);AK::swap(updates.started_user_scrolls, m_started_user_scrolls);@@ -67,24 +53,4 @@ Compositing::PendingAsyncScrollUpdates AsyncScrollUpdateOutbox::take_updates(booreturn updates;}-Optional<AsyncScrollUpdateOutbox::VisualViewportState> AsyncScrollUpdateOutbox::unadopted_visual_viewport_state(Web::UniqueNodeID document_id) const-{- Web::AsyncScrollNodeStableID visual_viewport { .node_id = document_id, .kind = Web::AsyncScrollNodeKind::VisualViewport };- // The updates that are still to be published are the latest.- for (auto const& pending : m_pending_scroll_offsets) {- if (pending.stable_node_id == visual_viewport && pending.visual_viewport_scale.has_value())- return VisualViewportState { pending.compositor_scroll_offset, pending.visual_viewport_scale.value() };- }- for (auto const& unreconciled : m_unreconciled_scroll_offsets) {- if (unreconciled.stable_node_id == visual_viewport && unreconciled.visual_viewport_scale.has_value())- return VisualViewportState { unreconciled.compositor_scroll_offset, unreconciled.visual_viewport_scale.value() };- }- return {};-}--void AsyncScrollUpdateOutbox::retire_scroll_offsets_adopted_by(u64 adopted_sequence)-{- m_unreconciled_scroll_offsets.remove_all_matching([&](auto const& unreconciled) { return unreconciled.sequence <= adopted_sequence; });-}-}diff --git a/Services/Compositor/AsyncScrollUpdateOutbox.h b/Services/Compositor/AsyncScrollUpdateOutbox.hindex 16ad2ac8b25..81895b5fee4 100644--- a/Services/Compositor/AsyncScrollUpdateOutbox.h+++ b/Services/Compositor/AsyncScrollUpdateOutbox.h@@ -15,20 +15,6 @@ namespace Compositor {class AsyncScrollUpdateOutbox {public:- // Offsets handed to WebContent that no snapshot of its has incorporated yet; the compositor keeps- // reapplying them over the main-thread state that arrives in the meantime.- struct UnreconciledScrollOffset {- u64 sequence { 0 };- Web::AsyncScrollNodeStableID stable_node_id;- Gfx::FloatPoint compositor_scroll_offset;- Optional<float> visual_viewport_scale;- };-- struct VisualViewportState {- Gfx::FloatPoint scroll_offset;- float scale { 1 };- };-Compositing::AsyncScrollOperationID allocate_operation_id() { return ++m_last_allocated_operation_id; }void complete_operation(Compositing::AsyncScrollOperationID operation_id) { m_completed_operation_ids.append(operation_id); }void note_operation_taken_over_by_user_input(Compositing::AsyncScrollOperationID operation_id) { m_operation_ids_taken_over_by_user_input.append(operation_id); }@@ -39,14 +25,8 @@ public:bool has_updates(bool user_scroll_gesture_in_progress) const;Compositing::PendingAsyncScrollUpdates take_updates(bool user_scroll_gesture_in_progress);- ReadonlySpan<UnreconciledScrollOffset> unreconciled_scroll_offsets() const { return m_unreconciled_scroll_offsets; }- // Where the compositor zoomed and panned the document's visual viewport to, until WebContent has adopted it.- Optional<VisualViewportState> unadopted_visual_viewport_state(Web::UniqueNodeID document_id) const;- void retire_scroll_offsets_adopted_by(u64 adopted_sequence);-private:Vector<Compositing::AsyncScrollOffset> m_pending_scroll_offsets;- Vector<UnreconciledScrollOffset> m_unreconciled_scroll_offsets;u64 m_last_publication_sequence { 0 };Compositing::AsyncScrollOperationID m_last_allocated_operation_id { 0 };Vector<Compositing::AsyncScrollOperationID> m_completed_operation_ids;diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 47c9de6a297..8a377d42058 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -884,24 +884,15 @@ Compositing::AsyncScrollEnqueueResult CompositorState::async_scroll_by(Web::Compreturn result.enqueue_result;}-Compositing::AsyncScrollEnqueueResult CompositorState::smooth_scroll_to(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind animation_kind, Compositing::SmoothScrollInitiator initiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue)-{- auto* context = context_if_present(context_id);- VERIFY(context);-- auto result = context->smooth_scroll_to(stable_node_id, offset, main_thread_offset, viewport_rect, animation_kind, initiator, operation_to_continue);- if (result.frame_to_present.has_value())- schedule_present_frame(context_id, *context, *result.frame_to_present);- publish_pending_async_scroll_updates(context_id, *context);- return result.enqueue_result;-}--void CompositorState::cancel_smooth_scroll(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id)+void CompositorState::apply_scroll_requests(Web::CompositorContextId context_id, ReadonlySpan<Compositing::ScrollRequest> scroll_requests){auto* context = context_if_present(context_id);if (!context)return;- context->cancel_smooth_scroll(stable_node_id);++ if (auto frame_to_present = context->apply_scroll_requests(scroll_requests); frame_to_present.has_value())+ schedule_present_frame(context_id, *context, frame_to_present.value());+ schedule_animation_frames_if_needed(*context);publish_pending_async_scroll_updates(context_id, *context);}diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 4c0a977206c..5642327a117 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -129,8 +129,7 @@ public:void handle_and_dispatch_mouse_event(Web::CompositorContextId, Web::MouseEvent);void handle_and_dispatch_pinch_event(Web::CompositorContextId, Web::PinchEvent);Compositing::AsyncScrollEnqueueResult async_scroll_by(Web::CompositorContextId, Web::UniqueNodeID document_id, Gfx::FloatPoint position, Gfx::FloatPoint delta, Gfx::IntRect viewport_rect, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, u32 modifiers, Compositing::AsyncScrollOperationTracking, Compositing::WheelStepDispatch, u64 input_event_id);- Compositing::AsyncScrollEnqueueResult smooth_scroll_to(Web::CompositorContextId, Web::AsyncScrollNodeStableID, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind, Compositing::SmoothScrollInitiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue);- void cancel_smooth_scroll(Web::CompositorContextId, Web::AsyncScrollNodeStableID);+ void apply_scroll_requests(Web::CompositorContextId, ReadonlySpan<Compositing::ScrollRequest>);void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize, double device_pixel_ratio, Compositing::WindowResizingInProgress);void request_rendering_opportunity(Web::CompositorContextId, double maximum_frames_per_second);void set_ui_overlays(Web::CompositorContextId, Compositing::UIOverlays);diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex 1aeb6d34969..4da39f3e063 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -70,8 +70,7 @@ endpoint CompositorWebContentServerinvalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation) =|invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation) => ()async_scroll_by(Web::CompositorContextId context_id, Web::UniqueNodeID document_id, Gfx::FloatPoint position, Gfx::FloatPoint delta, Gfx::IntRect viewport_rect, Web::WheelDeltaPrecision wheel_delta_precision, Web::ScrollGesturePhase scroll_gesture_phase, u32 modifiers, Compositing::AsyncScrollOperationTracking operation_tracking, Compositing::WheelStepDispatch wheel_step_dispatch, u64 input_event_id) => (Compositing::AsyncScrollEnqueueResult result)- smooth_scroll_to(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind animation_kind, Compositing::SmoothScrollInitiator initiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue) => (Compositing::AsyncScrollEnqueueResult result)- cancel_smooth_scroll(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id) =|+ apply_scroll_requests(Web::CompositorContextId context_id, Vector<Compositing::ScrollRequest> scroll_requests) =|scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller) => (String scroll_state)// Returns once the compositor has handled every message WebContent sent before it.synchronize_for_testing() => ()diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex 7e136721e5c..4b15226440c 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -493,14 +493,35 @@ Messages::CompositorWebContentServer::AsyncScrollByResponse ConnectionFromWebConreturn result;}-Messages::CompositorWebContentServer::SmoothScrollToResponse ConnectionFromWebContent::smooth_scroll_to(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind animation_kind, Compositing::SmoothScrollInitiator initiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue)+static bool is_valid_scroll_request(Compositing::ScrollRequest const& scroll_request)+{+ auto is_finite = [](Gfx::FloatPoint point) { return isfinite(point.x()) && isfinite(point.y()); };+ if (scroll_request.jump_offset.has_value() && !is_finite(scroll_request.jump_offset.value()))+ return false;+ if (scroll_request.visual_viewport_scale.has_value()) {+ auto scale = scroll_request.visual_viewport_scale.value();+ if (!isfinite(scale) || scale <= 0)+ return false;+ }+ if (auto const& smooth_scroll = scroll_request.smooth_scroll; smooth_scroll.has_value()) {+ if (!is_finite(smooth_scroll->destination_offset))+ return false;+ // WebContent names the compositor's own scrolls only to head them somewhere else.+ if (smooth_scroll->operation_id < Compositing::first_operation_id_the_main_thread_requests && !smooth_scroll->retargets_operation)+ return false;+ }+ return true;+}++void ConnectionFromWebContent::apply_scroll_requests(Web::CompositorContextId context_id, Vector<Compositing::ScrollRequest> scroll_requests){if (!context_is_owned_by_this_connection(context_id))- return Compositing::AsyncScrollEnqueueResult {};- auto result = m_compositor_state->smooth_scroll_to(context_id, stable_node_id, offset, main_thread_offset, viewport_rect, animation_kind, initiator, operation_to_continue);- if (result.accepted)- async_request_rendering_update();- return result;+ return;+ if (!all_of(scroll_requests, is_valid_scroll_request)) {+ did_misbehave("Invalid scroll request");+ return;+ }+ m_compositor_state->apply_scroll_requests(context_id, scroll_requests);}Messages::CompositorWebContentServer::ScrollStateForTestingResponse ConnectionFromWebContent::scroll_state_for_testing(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stretched_scroller)@@ -534,13 +555,6 @@ Messages::CompositorWebContentServer::TakeInputTraceForTestingResponse Connectioreturn m_compositor_state->take_input_trace_for_testing(context_id);}-void ConnectionFromWebContent::cancel_smooth_scroll(Web::CompositorContextId context_id, Web::AsyncScrollNodeStableID stable_node_id)-{- if (!context_is_owned_by_this_connection(context_id))- return;- m_compositor_state->cancel_smooth_scroll(context_id, stable_node_id);-}-Messages::CompositorWebContentServer::TakePendingAsyncScrollUpdatesResponse ConnectionFromWebContent::take_pending_async_scroll_updates(Web::CompositorContextId context_id){if (!context_is_owned_by_this_connection(context_id))diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex 9531bbba998..9c03638fe51 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -78,13 +78,12 @@ private:virtual void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation) override;virtual void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation) override;virtual Messages::CompositorWebContentServer::AsyncScrollByResponse async_scroll_by(Web::CompositorContextId, Web::UniqueNodeID document_id, Gfx::FloatPoint position, Gfx::FloatPoint delta, Gfx::IntRect viewport_rect, Web::WheelDeltaPrecision, Web::ScrollGesturePhase, u32 modifiers, Compositing::AsyncScrollOperationTracking, Compositing::WheelStepDispatch, u64 input_event_id) override;- virtual Messages::CompositorWebContentServer::SmoothScrollToResponse smooth_scroll_to(Web::CompositorContextId, Web::AsyncScrollNodeStableID, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind, Compositing::SmoothScrollInitiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue) override;+ virtual void apply_scroll_requests(Web::CompositorContextId, Vector<Compositing::ScrollRequest>) override;virtual Messages::CompositorWebContentServer::ScrollStateForTestingResponse scroll_state_for_testing(Web::CompositorContextId, Web::AsyncScrollNodeStableID) override;virtual void synchronize_for_testing() override { }virtual Messages::CompositorWebContentServer::RouteFirstWheelStepForTestingResponse route_first_wheel_step_for_testing(Web::CompositorContextId, Gfx::FloatPoint position, Gfx::FloatPoint delta_in_css_pixels) override;virtual void begin_input_trace_for_testing(Web::CompositorContextId) override;virtual Messages::CompositorWebContentServer::TakeInputTraceForTestingResponse take_input_trace_for_testing(Web::CompositorContextId) override;- virtual void cancel_smooth_scroll(Web::CompositorContextId, Web::AsyncScrollNodeStableID) override;virtual Messages::CompositorWebContentServer::TakePendingAsyncScrollUpdatesResponse take_pending_async_scroll_updates(Web::CompositorContextId) override;virtual void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress) override;virtual void request_rendering_opportunity(Web::CompositorContextId, double maximum_frames_per_second) override;diff --git a/Services/Compositor/ContextState.cpp b/Services/Compositor/ContextState.cppindex bd16416330b..95975141c00 100644--- a/Services/Compositor/ContextState.cpp+++ b/Services/Compositor/ContextState.cpp@@ -110,7 +110,7 @@ void ContextState::dispatch_mouse_event_to_web_content(Web::MouseEvent const& evbool ContextState::scrolled_since_last_frame() const{- return has_pending_async_scroll_updates() || !m_async_scroll_update_outbox.unreconciled_scroll_offsets().is_empty() || has_active_smooth_scroll_animations() || has_active_scroll_fling();+ return has_pending_async_scroll_updates() || m_scroll_offsets_differ_from_last_frame || has_active_smooth_scroll_animations() || has_active_scroll_fling();}void ContextState::dispatch_key_event_to_web_content(Web::KeyEvent const& event)@@ -148,17 +148,21 @@ void ContextState::install_display_list_update(Compositing::ScrollStateSnapshot&& scroll_state_snapshot){VERIFY(display_list->compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());+ auto scroll_offsets_of_known_nodes = scroll_offsets_by_stable_id();m_scene.install(move(display_list), move(visual_context_tree));m_keyboard_scroll_controller.forget_target();m_scroll_state_snapshot = move(scroll_state_snapshot);m_scroll_state_snapshot.set_node_count(m_scene.visual_context_tree()->spatial_node_count());- m_async_scroll_update_outbox.retire_scroll_offsets_adopted_by(m_scroll_state_snapshot.adopted_async_scroll_sequence());m_caret_blink_timer.did_install_display_list(*m_scene.display_list());auto async_scrolling_state = Compositing::async_scrolling_state_from_display_list(*m_scene.display_list());auto async_scrolling_viewport_rect = async_scrolling_state.viewport_rect;m_wheel_gesture_routing.did_install_scrolling_state(async_scrolling_state);- reapply_unadopted_visual_viewport_state();+ // The visual viewport of another document is where that document's visual context tree has it.+ if (m_scene.has_async_visual_viewport_transform() && async_scrolling_state.document_id != m_visual_viewport_document_id) {+ m_scene.drop_async_visual_viewport_transform();+ m_visual_viewport_document_id.clear();+ }auto was_dragging_scrollbar = m_scrollbar_controller.has_captured_scrollbar();m_scrollbar_controller.set_scrollbars(async_scrolling_state.scrollbars);@@ -168,7 +172,7 @@ void ContextState::install_display_list_update(m_async_scroll_tree.set_state(move(async_scrolling_state));m_elastic_overscroll_controller.did_install_scrolling_state(m_async_scroll_tree);m_scroll_snap_controller.did_install_scrolling_state(m_async_scroll_tree);- if (auto viewport_scroll_offset = reapply_unreconciled_async_scroll_offsets(); viewport_scroll_offset.has_value())+ if (auto viewport_scroll_offset = keep_scroll_offsets_of_known_nodes(scroll_offsets_of_known_nodes); viewport_scroll_offset.has_value())async_scrolling_viewport_rect.set_location(viewport_scroll_offset->to_type<int>());rebuild_wheel_hit_test_targets();m_async_scrolling_viewport_rect = async_scrolling_viewport_rect;@@ -217,20 +221,16 @@ void ContextState::update_visual_context_tree(Compositing::AccumulatedVisualContvoid ContextState::update_scroll_state(Compositing::ScrollStateSnapshot&& scroll_state_snapshot, Compositing::KeyboardScrollState keyboard_scroll_state){m_scene.forget_whether_animated_content_may_affect_viewport();+ auto scroll_offsets_of_known_nodes = scroll_offsets_by_stable_id();m_scroll_state_snapshot = move(scroll_state_snapshot);m_scroll_state_snapshot.set_node_count(m_scene.visual_context_tree().has_value() ? m_scene.visual_context_tree()->spatial_node_count() : 0);- m_async_scroll_update_outbox.retire_scroll_offsets_adopted_by(m_scroll_state_snapshot.adopted_async_scroll_sequence());if (!m_has_async_scrolling_state)return;- reapply_unadopted_visual_viewport_state();- auto reconciled_viewport_scroll_offset = reapply_unreconciled_async_scroll_offsets();+ auto kept_viewport_scroll_offset = keep_scroll_offsets_of_known_nodes(scroll_offsets_of_known_nodes);rebuild_wheel_hit_test_targets();- if (reconciled_viewport_scroll_offset.has_value()) {- auto reconciled_viewport_rect = m_async_scrolling_viewport_rect;- reconciled_viewport_rect.set_location(reconciled_viewport_scroll_offset->to_type<int>());- m_async_scrolling_viewport_rect = reconciled_viewport_rect;- }+ if (kept_viewport_scroll_offset.has_value())+ m_async_scrolling_viewport_rect.set_location(kept_viewport_scroll_offset->to_type<int>());adopt_keyboard_scroll_state(move(keyboard_scroll_state));}@@ -327,6 +327,7 @@ ContextState::ContextUpdateResult ContextState::handle_key_event(Web::KeyEvent c}if (auto& updated_scroll = decision->get<ScrollSnapController::StepConsumed>().updated_scroll; updated_scroll.has_value()) {updated_scroll->is_absolute_scroll = scrolls_to_extent;+ note_user_input_scrolled(updated_scroll->stable_node_id);m_async_scroll_update_outbox.record_started_user_scroll(updated_scroll.release_value());}return { .accepted = true, .frame_to_present = {}, .should_request_rendering_update = true };@@ -622,7 +623,9 @@ ContextState::ContextUpdateResult ContextState::handle_pinch_event(Web::PinchEvem_scene.set_async_visual_viewport_transform(transform);rebuild_wheel_hit_test_targets();+ m_visual_viewport_document_id = m_async_scroll_tree.document_id();if (auto document_id = m_async_scroll_tree.document_id(); document_id.has_value()) {+ note_user_input_scrolled({ .node_id = document_id.value(), .kind = Web::AsyncScrollNodeKind::VisualViewport });auto new_scroll_offset = visual_viewport_scroll_offset(transform);Compositing::AsyncScrollOffset scroll_offset {.stable_node_id = { .node_id = document_id.value(), .kind = Web::AsyncScrollNodeKind::VisualViewport },@@ -630,6 +633,8 @@ ContextState::ContextUpdateResult ContextState::handle_pinch_event(Web::PinchEve.unadopted_scroll_delta = new_scroll_offset - old_scroll_offset,.last_relative_scroll_delta = {},.visual_viewport_scale = transform.matrix[0, 0],+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,};store_pending_async_scroll_offsets({ &scroll_offset, 1 });}@@ -666,6 +671,7 @@ Compositing::AsyncScrollOperationID ContextState::start_snap_scroll(Compositing:.is_user_scroll = true,});m_scroll_snap_controller.did_start_snap_scroll(stable_node_id, operation_id, destination);+ note_user_input_scrolled(stable_node_id);m_async_scroll_update_outbox.record_started_user_scroll({.stable_node_id = stable_node_id,.operation_id = operation_id,@@ -839,6 +845,8 @@ ContextState::NodeScrollByWheelDelta ContextState::scroll_node_by_wheel_delta(Coreturn { outcome, delta };}+ note_user_input_scrolled(scroll_offset->stable_node_id);+// On the first step of a gesture, scroll node chaining may have scrolled an ancestor instead, which took the delta.auto const* node = m_async_scroll_tree.scroll_node_for_id(node_id);bool an_ancestor_scrolled = node && scroll_offset->stable_node_id != node->stable_node_id;@@ -964,61 +972,142 @@ ContextState::AsyncScrollResult ContextState::async_scroll_by(};}-ContextState::AsyncScrollResult ContextState::smooth_scroll_to(Web::AsyncScrollNodeStableID stable_node_id, Gfx::FloatPoint destination_offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind animation_kind, Compositing::SmoothScrollInitiator initiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue)+void ContextState::note_user_input_scrolled(Web::AsyncScrollNodeStableID stable_node_id){- if (!m_has_async_scrolling_state)- return {};+ m_user_input_scroll_counts.ensure(stable_node_id)++;+}- if (operation_to_continue.has_value()) {- auto running_animation = m_smooth_scroll_animations.find_if([&](auto const& animation) { return animation.operation_id == *operation_to_continue; });- if (running_animation == m_smooth_scroll_animations.end())- return {};- retarget_user_scroll(*running_animation, destination_offset, MonotonicTime::now());- m_async_scrolling_viewport_rect = viewport_rect;- return {- .enqueue_result = { true, running_animation->operation_id },- .frame_to_present = PendingFrame::repainting_changes(viewport_rect),+Optional<PendingFrame> ContextState::apply_scroll_requests(ReadonlySpan<Compositing::ScrollRequest> scroll_requests)+{+ Vector<Compositing::AsyncScrollOffset> answers;+ for (auto const& scroll_request : scroll_requests) {+ // The box's offsets are reported as of this request from here on, whether or not the box is here yet.+ m_applied_scroll_request_ids.set(scroll_request.stable_node_id, scroll_request.request_id);+ if (scroll_request.stable_node_id.kind == Web::AsyncScrollNodeKind::VisualViewport) {+ apply_visual_viewport_scroll_request(scroll_request, answers);+ continue;+ }++ Optional<Compositing::AsyncScrollNodeID> node_id;+ if (m_has_async_scrolling_state)+ node_id = m_async_scroll_tree.scroll_node_id_for_stable_id(scroll_request.stable_node_id);+ auto old_offset = node_id.has_value() ? m_async_scroll_tree.scroll_offset_for_node(node_id.value(), m_scroll_state_snapshot) : Optional<Gfx::FloatPoint> {};+ if (!old_offset.has_value()) {+ if (scroll_request.smooth_scroll.has_value())+ m_async_scroll_update_outbox.complete_operation(scroll_request.smooth_scroll->operation_id);+ continue;+ }++ // The answer tells the main thread where the box went for the request, even where it stayed where it was.+ auto answer_with_the_offset_of_the_box = [&] {+ auto new_offset = m_async_scroll_tree.scroll_offset_for_node(node_id.value(), m_scroll_state_snapshot).value();+ if (m_async_scroll_tree.scroll_node_is_viewport(node_id.value()))+ m_async_scrolling_viewport_rect.set_location(new_offset.to_type<int>());+ answers.append({+ .stable_node_id = scroll_request.stable_node_id,+ .compositor_scroll_offset = new_offset,+ .unadopted_scroll_delta = new_offset - old_offset.value(),+ .last_relative_scroll_delta = {},+ .visual_viewport_scale = {},+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,+ });};++ // A request aborts the box's smooth scroll, unless it heads that very scroll somewhere else.+ Optional<Compositing::AsyncScrollOperationID> retargeted_operation_id;+ if (scroll_request.smooth_scroll.has_value() && scroll_request.smooth_scroll->retargets_operation)+ retargeted_operation_id = scroll_request.smooth_scroll->operation_id;+ auto running_animation = m_smooth_scroll_animations.find_if([&](auto const& animation) { return animation.stable_node_id == scroll_request.stable_node_id; });+ bool retargets_running_animation = running_animation != m_smooth_scroll_animations.end() && running_animation->operation_id == retargeted_operation_id;++ // The main thread settled the user's gesture once it heard of no more input for the box. User input this+ // context took since then carries the gesture on, and the box goes where that input takes it instead.+ auto smooth_scroll = scroll_request.smooth_scroll;+ if (smooth_scroll.has_value() && smooth_scroll->settled_user_input_scroll_count.has_value() && !retargets_running_animation+ && m_user_input_scroll_counts.get(scroll_request.stable_node_id).value_or(0) > smooth_scroll->settled_user_input_scroll_count.value()) {+ m_async_scroll_update_outbox.note_operation_taken_over_by_user_input(smooth_scroll->operation_id);+ m_async_scroll_update_outbox.complete_operation(smooth_scroll->operation_id);+ smooth_scroll.clear();+ if (!scroll_request.jump_offset.has_value()) {+ answer_with_the_offset_of_the_box();+ continue;+ }+ }++ if (running_animation != m_smooth_scroll_animations.end() && !retargets_running_animation)+ cancel_smooth_scroll(scroll_request.stable_node_id);+ else if (!retargets_running_animation && smooth_scroll.has_value())+ m_scroll_snap_controller.did_start_main_thread_scroll(scroll_request.stable_node_id);++ if (scroll_request.jump_offset.has_value())+ (void)m_async_scroll_tree.set_scroll_offset(node_id.value(), scroll_request.jump_offset.value(), m_scene.current_visual_context_tree(), m_scroll_state_snapshot);++ if (smooth_scroll.has_value()) {+ auto destination_offset = m_async_scroll_tree.clamped_scroll_offset_for_node(node_id.value(), smooth_scroll->destination_offset);+ if (retargets_running_animation) {+ retarget_user_scroll(*running_animation, destination_offset, MonotonicTime::now());+ } else {+ auto start_offset = m_async_scroll_tree.scroll_offset_for_node(node_id.value(), m_scroll_state_snapshot).value();+ Compositing::SmoothScrollAnimation animation { start_offset, destination_offset, m_async_scroll_tree.device_pixels_per_css_pixel(), smooth_scroll->animation_kind };+ if (animation.duration().is_zero()) {+ m_async_scroll_update_outbox.complete_operation(smooth_scroll->operation_id);+ } else {+ m_smooth_scroll_animations.append({+ .stable_node_id = scroll_request.stable_node_id,+ .operation_id = smooth_scroll->operation_id,+ .animation = move(animation),+ .started_at = MonotonicTime::now(),+ .is_user_scroll = smooth_scroll->initiator == Compositing::SmoothScrollInitiator::UserInput,+ });+ }+ }+ }++ answer_with_the_offset_of_the_box();}- auto node_id = m_async_scroll_tree.scroll_node_id_for_stable_id(stable_node_id);- if (!node_id.has_value())- return {};- auto current_offset = m_async_scroll_tree.scroll_offset_for_node(*node_id, m_scroll_state_snapshot);- if (!current_offset.has_value())+ if (answers.is_empty())return {};+ store_pending_async_scroll_offsets(answers);+ if (m_has_async_scrolling_state)+ rebuild_wheel_hit_test_targets();+ request_rendering_update();+ return PendingFrame::repainting_changes(m_async_scrolling_viewport_rect);+}- cancel_smooth_scroll(stable_node_id);-- // The main thread can apply instant input scrolls that this context has not learned about yet, so a scroll whose- // presented offset already matches the destination starts from the main thread's offset to converge on it.- auto start_offset = *current_offset;- if (start_offset == destination_offset)- start_offset = main_thread_offset;+void ContextState::apply_visual_viewport_scroll_request(Compositing::ScrollRequest const& scroll_request, Vector<Compositing::AsyncScrollOffset>& answers)+{+ // The main thread animates the visual viewport itself, one jump at a time.+ if (scroll_request.smooth_scroll.has_value())+ m_async_scroll_update_outbox.complete_operation(scroll_request.smooth_scroll->operation_id);+ if (!m_scene.visual_context_tree().has_value() || scroll_request.stable_node_id.node_id != m_async_scroll_tree.document_id())+ return;- auto operation_id = m_async_scroll_update_outbox.allocate_operation_id();- Compositing::SmoothScrollAnimation animation { start_offset, destination_offset, m_async_scroll_tree.device_pixels_per_css_pixel(), animation_kind };- if (animation.duration().is_zero()) {- m_async_scroll_update_outbox.complete_operation(operation_id);- request_rendering_update();- return {- .enqueue_result = { true, operation_id },- .frame_to_present = {},- };+ auto transform = m_scene.visual_viewport_transform();+ auto old_scroll_offset = visual_viewport_scroll_offset(transform);+ if (scroll_request.jump_offset.has_value()) {+ auto scale = scroll_request.visual_viewport_scale.value_or(transform.matrix[0, 0]);+ transform.matrix[0, 0] = scale;+ transform.matrix[1, 1] = scale;+ transform.matrix[0, 3] = -scroll_request.jump_offset->x() * scale;+ transform.matrix[1, 3] = -scroll_request.jump_offset->y() * scale;+ clamp_visual_viewport_transform_to_viewport(transform, m_async_scrolling_viewport_rect);+ m_scene.set_async_visual_viewport_transform(transform);+ m_visual_viewport_document_id = scroll_request.stable_node_id.node_id;+ rebuild_wheel_hit_test_targets();}- m_smooth_scroll_animations.append({- .stable_node_id = stable_node_id,- .operation_id = operation_id,- .animation = move(animation),- .started_at = MonotonicTime::now(),- .is_user_scroll = initiator == Compositing::SmoothScrollInitiator::UserInput,+ auto new_scroll_offset = visual_viewport_scroll_offset(transform);+ answers.append({+ .stable_node_id = scroll_request.stable_node_id,+ .compositor_scroll_offset = new_scroll_offset,+ .unadopted_scroll_delta = new_scroll_offset - old_scroll_offset,+ .last_relative_scroll_delta = {},+ .visual_viewport_scale = transform.matrix[0, 0],+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,});- m_async_scrolling_viewport_rect = viewport_rect;- return {- .enqueue_result = { true, operation_id },- .frame_to_present = PendingFrame::repainting_changes(viewport_rect),- };}Optional<Gfx::FloatPoint> ContextState::in_flight_wheel_destination(Web::AsyncScrollNodeStableID stable_node_id) const@@ -1140,6 +1229,8 @@ Optional<Gfx::IntRect> ContextState::advance_smooth_scroll_animations(MonotonicT.unadopted_scroll_delta = scroll_delta,.last_relative_scroll_delta = {},.visual_viewport_scale = {},+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,});changed_scroll_offset = true;if (m_async_scroll_tree.scroll_node_is_viewport(*node_id))@@ -1746,6 +1837,8 @@ Optional<ContextState::VisualViewportScrollDelta> ContextState::apply_visual_vietransform.matrix[0, 3] = new_x;transform.matrix[1, 3] = new_y;m_scene.set_async_visual_viewport_transform(transform);+ m_visual_viewport_document_id = document_id;+ note_user_input_scrolled({ .node_id = document_id.value(), .kind = Web::AsyncScrollNodeKind::VisualViewport });rebuild_wheel_hit_test_targets();return VisualViewportScrollDelta {@@ -1755,6 +1848,8 @@ Optional<ContextState::VisualViewportScrollDelta> ContextState::apply_visual_vie.unadopted_scroll_delta = consumed_delta.scaled(1.0f / scale),.last_relative_scroll_delta = {},.visual_viewport_scale = scale,+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,},.consumed_delta = consumed_delta,};@@ -1769,43 +1864,52 @@ Gfx::FloatPoint ContextState::pan_visual_viewport_by(Gfx::FloatPoint delta_in_screturn visual_viewport_scroll_delta->consumed_delta;}-// The visual context tree carries the visual viewport as the main thread last left it, which the zooming and panning-// that it has yet to adopt still go over.-void ContextState::reapply_unadopted_visual_viewport_state()+HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> ContextState::scroll_offsets_by_stable_id() const{- Optional<AsyncScrollUpdateOutbox::VisualViewportState> state;- if (auto document_id = m_async_scroll_tree.document_id(); document_id.has_value())- state = m_async_scroll_update_outbox.unadopted_visual_viewport_state(document_id.value());- if (!state.has_value() || !m_scene.visual_context_tree().has_value()) {- if (m_scene.has_async_visual_viewport_transform())- m_scene.drop_async_visual_viewport_transform();- return;+ HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> scroll_offsets;+ if (!m_has_async_scrolling_state)+ return scroll_offsets;+ for (auto const& node : m_async_scroll_tree.scroll_nodes()) {+ if (auto offset = m_async_scroll_tree.scroll_offset_for_node(node.node_id, m_scroll_state_snapshot); offset.has_value())+ scroll_offsets.set(node.stable_node_id, offset.value());}-- auto transform = m_scene.current_visual_context_tree().visual_viewport_transform();- auto scale = state.value().scale;- transform.matrix[0, 0] = scale;- transform.matrix[1, 1] = scale;- transform.matrix[0, 3] = -state.value().scroll_offset.x() * scale;- transform.matrix[1, 3] = -state.value().scroll_offset.y() * scale;- m_scene.set_async_visual_viewport_transform(transform);+ return scroll_offsets;}-Optional<Gfx::FloatPoint> ContextState::reapply_unreconciled_async_scroll_offsets()+// The main thread asks for every scroll of its own, so the offsets a snapshot of its scroll state has for the boxes+// this context already scrolls are what it last heard of them. Only a box new to this context takes its offset from+// the snapshot.+Optional<Gfx::FloatPoint> ContextState::keep_scroll_offsets_of_known_nodes(HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> const& scroll_offsets_of_known_nodes){Optional<Gfx::FloatPoint> viewport_scroll_offset;- for (auto const& unreconciled : m_async_scroll_update_outbox.unreconciled_scroll_offsets()) {- auto node_id = m_async_scroll_tree.scroll_node_id_for_stable_id(unreconciled.stable_node_id);- if (!node_id.has_value())+ Vector<Compositing::AsyncScrollOffset> clamped_scroll_offsets;+ m_scroll_offsets_differ_from_last_frame = false;+ for (auto const& node : m_async_scroll_tree.scroll_nodes()) {+ auto known_scroll_offset = scroll_offsets_of_known_nodes.get(node.stable_node_id);+ if (!known_scroll_offset.has_value())continue;- auto reconciled_scroll_offset = m_async_scroll_tree.set_scroll_offset(- *node_id,- unreconciled.compositor_scroll_offset,- m_scene.current_visual_context_tree(),- m_scroll_state_snapshot);- if (reconciled_scroll_offset.has_value() && m_async_scroll_tree.scroll_node_is_viewport(*node_id))- viewport_scroll_offset = *reconciled_scroll_offset;+ if (m_async_scroll_tree.scroll_offset_for_node(node.node_id, m_scroll_state_snapshot) != known_scroll_offset)+ m_scroll_offsets_differ_from_last_frame = true;+ auto kept_scroll_offset = m_async_scroll_tree.set_scroll_offset(node.node_id, known_scroll_offset.value(), m_scene.current_visual_context_tree(), m_scroll_state_snapshot);+ if (!kept_scroll_offset.has_value())+ continue;+ if (node.is_viewport)+ viewport_scroll_offset = kept_scroll_offset;+ // A box whose scroll range shrank past its offset is told where it ended up.+ if (kept_scroll_offset.value() != known_scroll_offset.value()) {+ clamped_scroll_offsets.append({+ .stable_node_id = node.stable_node_id,+ .compositor_scroll_offset = kept_scroll_offset.value(),+ .unadopted_scroll_delta = kept_scroll_offset.value() - known_scroll_offset.value(),+ .last_relative_scroll_delta = {},+ .visual_viewport_scale = {},+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,+ });+ }}+ if (!clamped_scroll_offsets.is_empty())+ store_pending_async_scroll_offsets(clamped_scroll_offsets);return viewport_scroll_offset;}@@ -1814,7 +1918,15 @@ void ContextState::store_pending_async_scroll_offsets(Optional<Compositing::AsyncScrollOperationID> operation_id){m_scene.forget_whether_animated_content_may_affect_viewport();- m_async_scroll_update_outbox.record_scroll_offsets(scroll_offsets);+ Vector<Compositing::AsyncScrollOffset> stamped_scroll_offsets;+ stamped_scroll_offsets.ensure_capacity(scroll_offsets.size());+ for (auto scroll_offset : scroll_offsets) {+ scroll_offset.applied_scroll_request_id = m_applied_scroll_request_ids.get(scroll_offset.stable_node_id).value_or(0);+ scroll_offset.user_input_scroll_count = m_user_input_scroll_counts.get(scroll_offset.stable_node_id).value_or(0);+ stamped_scroll_offsets.unchecked_append(scroll_offset);+ }+ m_async_scroll_update_outbox.record_scroll_offsets(stamped_scroll_offsets);+ m_scroll_offsets_differ_from_last_frame = true;if (operation_id.has_value())m_async_scroll_update_outbox.complete_operation(*operation_id);}@@ -1864,6 +1976,7 @@ void ContextState::report_started_user_scroll(Compositing::AsyncScrollOperationIauto current_offset = m_async_scroll_tree.css_scroll_offset_for_node(*node_id, m_scroll_state_snapshot);VERIFY(current_offset.has_value());auto destination = m_async_scroll_tree.css_pixels_from_device_offset(destination_offset);+ note_user_input_scrolled(stable_node_id);m_async_scroll_update_outbox.record_started_user_scroll({.stable_node_id = stable_node_id,.operation_id = operation_id,@@ -2038,6 +2151,7 @@ Optional<PendingFrame> ContextState::apply_scrollbar_drag(ScrollbarController::Dreturn start_scrollbar_press_scroll(*node, *old_scroll_offset, destination, true);auto new_scroll_offset = m_async_scroll_tree.set_scroll_offset(node_id, dragged_to->scroll_offset, m_scene.current_visual_context_tree(), m_scroll_state_snapshot);+ note_user_input_scrolled(node->stable_node_id);VERIFY(new_scroll_offset.has_value());rebuild_wheel_hit_test_targets();@@ -2048,6 +2162,8 @@ Optional<PendingFrame> ContextState::apply_scrollbar_drag(ScrollbarController::D.unadopted_scroll_delta = *new_scroll_offset - *old_scroll_offset,.last_relative_scroll_delta = {},.visual_viewport_scale = {},+ .applied_scroll_request_id = 0,+ .user_input_scroll_count = 0,});store_pending_async_scroll_offsets(scroll_offsets);diff --git a/Services/Compositor/ContextState.h b/Services/Compositor/ContextState.hindex 26d70588627..c9f323a0729 100644--- a/Services/Compositor/ContextState.h+++ b/Services/Compositor/ContextState.h@@ -191,7 +191,7 @@ public:// The id the UI gave the wheel event, or 0 for a step that did not come from the UI.u64 input_event_id,Optional<MonotonicTime> now_for_testing = {});- AsyncScrollResult smooth_scroll_to(Web::AsyncScrollNodeStableID, Gfx::FloatPoint offset, Gfx::FloatPoint main_thread_offset, Gfx::IntRect viewport_rect, Compositing::ScrollAnimationKind, Compositing::SmoothScrollInitiator, Optional<Compositing::AsyncScrollOperationID> operation_to_continue);+ Optional<PendingFrame> apply_scroll_requests(ReadonlySpan<Compositing::ScrollRequest>);void cancel_smooth_scroll(Web::AsyncScrollNodeStableID);Optional<Gfx::IntRect> advance_smooth_scroll_animations(MonotonicTime now);bool needs_animation_frames() { return has_active_smooth_scroll_animations() || has_active_scroll_fling() || m_elastic_overscroll_controller.has_rebound() || visual_animations_need_frame() || m_presenter.ui_overlay_fades_need_frame() || m_scrollbar_controller.fades_need_frame(MonotonicTime::now()); }@@ -270,11 +270,13 @@ private:Compositing::ScrollStateSnapshot scroll_state_snapshot_at_keyboard_step_starts() const;void adopt_keyboard_scroll_state(Compositing::KeyboardScrollState);Optional<VisualViewportScrollDelta> apply_visual_viewport_scroll_delta(Gfx::FloatPoint);- void reapply_unadopted_visual_viewport_state();+ void note_user_input_scrolled(Web::AsyncScrollNodeStableID);+ void apply_visual_viewport_scroll_request(Compositing::ScrollRequest const&, Vector<Compositing::AsyncScrollOffset>& answers);// Pans the visual viewport of a zoomed page by as much of a delta in screen pixels as it has room for, and returns// that part of the delta.Gfx::FloatPoint pan_visual_viewport_by(Gfx::FloatPoint delta_in_screen_pixels);- Optional<Gfx::FloatPoint> reapply_unreconciled_async_scroll_offsets();+ HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> scroll_offsets_by_stable_id() const;+ Optional<Gfx::FloatPoint> keep_scroll_offsets_of_known_nodes(HashMap<Web::AsyncScrollNodeStableID, Gfx::FloatPoint> const&);void store_pending_async_scroll_offsets(ReadonlySpan<Compositing::AsyncScrollOffset>, Optional<Compositing::AsyncScrollOperationID> = {});enum class VisualViewportPanning : u8 {// The step is in the pixels of the scroller, and only scrolls it.@@ -358,6 +360,14 @@ private:ScrollSnapController m_scroll_snap_controller;AsyncScrollUpdateOutbox m_async_scroll_update_outbox;+ // The last of the main thread's scroll requests applied to each box, which the box's reported offsets are marked with.+ HashMap<Web::AsyncScrollNodeStableID, u64> m_applied_scroll_request_ids;+ // How many times this context scrolled each box for user input of its own, which the reports are marked with too.+ HashMap<Web::AsyncScrollNodeStableID, u64> m_user_input_scroll_counts;+ // Whether this context has scrolled boxes to offsets that WebContent's last frame does not have them at.+ bool m_scroll_offsets_differ_from_last_frame { false };+ // The document whose visual viewport this context zoomed or panned, which it presents as it left it from then on.+ Optional<Web::UniqueNodeID> m_visual_viewport_document_id;KeyboardScrollController m_keyboard_scroll_controller;RefPtr<Core::Timer> m_scroll_step_gesture_input_timer;WheelGestureRouting m_wheel_gesture_routing;diff --git a/Tests/Compositor/TestContextState.cpp b/Tests/Compositor/TestContextState.cppindex 9b57c1e42c3..db95a6fb327 100644--- a/Tests/Compositor/TestContextState.cpp+++ b/Tests/Compositor/TestContextState.cpp@@ -30,15 +30,13 @@ public:static Web::UniqueNodeID const document_id { 7 };// A display list of a page whose viewport cannot be scrolled, so it records no scroll node.-static void install_display_list_without_scroll_nodes(Compositor::ContextState& context, u64 adopted_async_scroll_sequence = 0)+static void install_display_list_without_scroll_nodes(Compositor::ContextState& context){Compositing::VisualContextTreeTestBuilder builder;auto visual_context_tree = builder.finish();auto display_list = Compositing::DisplayList::create(visual_context_tree);display_list->set_async_scrolling_metadata({ .document_id = document_id, .viewport_rect = { 0, 0, 800, 600 } });- Compositing::ScrollStateSnapshot scroll_state_snapshot;- scroll_state_snapshot.set_adopted_async_scroll_sequence(adopted_async_scroll_sequence);- context.install_display_list_update(display_list, move(visual_context_tree), move(scroll_state_snapshot));+ context.install_display_list_update(display_list, move(visual_context_tree), {});}static Web::PinchEvent pinch_event(double scale_delta)@@ -95,22 +93,27 @@ TEST_CASE(pinch_zoom_is_reported_on_the_visual_viewport)EXPECT_EQ(scroll_offset.unadopted_scroll_delta, Gfx::FloatPoint(200, 150));}-TEST_CASE(pinch_zoom_is_presented_until_the_main_thread_adopts_it)+TEST_CASE(pinch_zoom_is_presented_until_the_main_thread_asks_for_another){NullWebContentClient client;Compositor::CanvasSurfaceRegistry canvas_surface_registry;Compositor::ContextState context { Web::CompositorContextId { 1 }, 1, client, Compositor::OwnedCanvasSurfaces { canvas_surface_registry, client.canvas_surface_owner_id() } };install_display_list_without_scroll_nodes(context);+ // A display list the main thread recorded without the zoom keeps it at its maximum.EXPECT(context.handle_pinch_event(pinch_event(4.0)).accepted);- auto updates = context.take_pending_async_scroll_updates();-- // A display list recorded before the main thread adopted the zoom keeps it at its maximum.- install_display_list_without_scroll_nodes(context, updates.sequence - 1);+ install_display_list_without_scroll_nodes(context);EXPECT(!context.handle_pinch_event(pinch_event(1.0)).accepted);- // Once the main thread has adopted the zoom, its display list says where the visual viewport is, here reset since.- install_display_list_without_scroll_nodes(context, updates.sequence);+ // A request of the main thread's own, such as resetting the zoom, is what moves the visual viewport from there.+ Compositing::ScrollRequest reset_zoom {+ .stable_node_id = { .node_id = document_id, .kind = Web::AsyncScrollNodeKind::VisualViewport },+ .request_id = 1,+ .jump_offset = Gfx::FloatPoint {},+ .visual_viewport_scale = 1.0f,+ .smooth_scroll = {},+ };+ (void)context.apply_scroll_requests({ &reset_zoom, 1 });EXPECT(context.handle_pinch_event(pinch_event(1.0)).accepted);}diff --git a/Tests/LibCompositing/TestScrollState.cpp b/Tests/LibCompositing/TestScrollState.cppindex a79fd490c0d..d66bfb62e8e 100644--- a/Tests/LibCompositing/TestScrollState.cpp+++ b/Tests/LibCompositing/TestScrollState.cpp@@ -38,7 +38,6 @@ static ScrollStateSnapshot decode_snapshot(Vector<WirePair> const& pairs)MUST(encoder.encode(pair.index));MUST(encoder.encode(pair.offset));}- MUST(encoder.encode(u64 { 0 })); // adopted_async_scroll_sequenceauto data = message_buffer.take_data();FixedMemoryStream stream { data.span() };@@ -140,11 +139,10 @@ TEST_CASE(async_scroll_tree_ignores_out_of_range_scroll_node_index)EXPECT_EQ(snapshot.device_offset_for_index(out_of_range_index), Gfx::FloatPoint {});}-TEST_CASE(ipc_round_trip_preserves_scroll_offsets_and_adopted_sequence)+TEST_CASE(ipc_round_trip_preserves_scroll_offsets){ScrollStateSnapshot snapshot;snapshot.set_device_offset_for_index(SpatialNodeIndex { 3 }, Gfx::FloatPoint { 10, 20 });- snapshot.set_adopted_async_scroll_sequence(0x1'0000'0001);IPC::MessageBuffer message_buffer;IPC::Encoder encoder { message_buffer };@@ -156,7 +154,6 @@ TEST_CASE(ipc_round_trip_preserves_scroll_offsets_and_adopted_sequence)IPC::Decoder decoder { stream, attachments };auto decoded = MUST(IPC::decode<ScrollStateSnapshot>(decoder));- EXPECT_EQ(decoded.adopted_async_scroll_sequence(), snapshot.adopted_async_scroll_sequence());decoded.set_node_count(8);EXPECT_EQ(decoded.device_offset_for_index(SpatialNodeIndex { 3 }), (Gfx::FloatPoint { 10, 20 }));// Indices that were never set are holes that decode back to zero offsets.diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex afae61def5c..ba610aeff99 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -1086,6 +1086,7 @@ Text/input/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.html; Ends a smooth scroll once 20 frames see no change, which frames faster than the compositor's ticks doText/input/wpt-import/css/cssom-view/scroll-behavior-default-css.htmlText/input/wpt-import/css/cssom-view/scroll-behavior-scrollintoview-nested.html+Text/input/wpt-import/css/cssom-view/position-sticky-root-scroller-with-scroll-behavior.html; Expects an animation's 1ms delay to elapse within two framesText/input/wpt-import/css/css-animations/event-dispatch.tentative.html; Waits for scrolls that animate in real time, which uncapped frames only spin throughdiff --git a/Tests/LibWeb/Text/expected/async-scrolling/instant-script-scroll-during-a-pan.txt b/Tests/LibWeb/Text/expected/async-scrolling/instant-script-scroll-during-a-pan.txtnew file mode 100644index 00000000000..9506d88fae1--- /dev/null+++ b/Tests/LibWeb/Text/expected/async-scrolling/instant-script-scroll-during-a-pan.txt@@ -0,0 +1,3 @@+right after scrolling to 50: 50+once the compositor has the scroll: 50+once the pan has ended: 50diff --git a/Tests/LibWeb/Text/expected/async-scrolling/main-thread-scroll-rebase.txt b/Tests/LibWeb/Text/expected/async-scrolling/script-scroll-replaces-unadopted-user-scroll.txtsimilarity index 51%rename from Tests/LibWeb/Text/expected/async-scrolling/main-thread-scroll-rebase.txtrename to Tests/LibWeb/Text/expected/async-scrolling/script-scroll-replaces-unadopted-user-scroll.txtindex 3905f1ebced..8987d31bd81 100644--- a/Tests/LibWeb/Text/expected/async-scrolling/main-thread-scroll-rebase.txt+++ b/Tests/LibWeb/Text/expected/async-scrolling/script-scroll-replaces-unadopted-user-scroll.txt@@ -1,2 +1,2 @@script scrollTop: 200-final scrollTop: 300+final scrollTop: 200diff --git a/Tests/LibWeb/Text/input/async-scrolling/instant-script-scroll-during-a-pan.html b/Tests/LibWeb/Text/input/async-scrolling/instant-script-scroll-during-a-pan.htmlnew file mode 100644index 00000000000..e26e5dac29f--- /dev/null+++ b/Tests/LibWeb/Text/input/async-scrolling/instant-script-scroll-during-a-pan.html@@ -0,0 +1,37 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body {+ margin: 0;+ height: 5000px;+ }+</style>+<script>+ promiseTest(async () => {+ await animationFrame();+ await animationFrame();++ const busyWait = milliseconds => {+ const end = performance.now() + milliseconds;+ while (performance.now() < end) {}+ };++ // The compositor pans the page by 100 while the main thread is busy, so the main thread has not heard of the+ // pan when the page scrolls itself to 50. The page goes to 50 rather than 50 past where the pan took it.+ internals.wheelThroughUIProcess(50, 50, 0, 0, true, "began");+ await animationFrame();+ await animationFrame();+ internals.wheelThroughUIProcess(50, 50, 0, 100, true, "ongoing");+ busyWait(200);+ window.scrollTo(0, 50);+ println(`right after scrolling to 50: ${window.scrollY}`);+ for (let frame = 0; frame < 4; frame++)+ await animationFrame();+ println(`once the compositor has the scroll: ${window.scrollY}`);++ await internals.wheelThroughUIProcess(50, 50, 0, 0, true, "ended");+ for (let frame = 0; frame < 4; frame++)+ await animationFrame();+ println(`once the pan has ended: ${window.scrollY}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/async-scrolling/main-thread-scroll-rebase.html b/Tests/LibWeb/Text/input/async-scrolling/script-scroll-replaces-unadopted-user-scroll.htmlsimilarity index 77%rename from Tests/LibWeb/Text/input/async-scrolling/main-thread-scroll-rebase.htmlrename to Tests/LibWeb/Text/input/async-scrolling/script-scroll-replaces-unadopted-user-scroll.htmlindex e16218ef08d..6b7fcb938c7 100644--- a/Tests/LibWeb/Text/input/async-scrolling/main-thread-scroll-rebase.html+++ b/Tests/LibWeb/Text/input/async-scrolling/script-scroll-replaces-unadopted-user-scroll.html@@ -21,6 +21,8 @@await animationFrame();await animationFrame();+ // The compositor takes the pan before the script scrolls, whose position the box goes to all the same. The+ // layout dirtied before the compositor's offset is adopted must not get in the way.const wheelPromise = internals.wheel(50, 50, 0, 100, true);scroller.scrollTop = 200;println(`script scrollTop: ${scroller.scrollTop}`);