Skip to content

Truly independent web browser

Compositor: Port CompositorCore to Rust

Aliaksandr Kalenik969a6142858d
diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rs
index 92fe3e4597a..c293c73f936 100644
--- a/Libraries/LibCompositing/Rust/build.rs
+++ b/Libraries/LibCompositing/Rust/build.rs
@@ -299,6 +299,10 @@ fn generate_ipc_definitions(manifest_dir: &Path, out_dir: &Path) -> Result<(), B
"Services/Compositor/CompositorWebContentClient.ipc",
"CompositorWebContentClientEndpoint.rs",
),
+ (
+ "Services/Compositor/CompositorPresentationClient.ipc",
+ "CompositorPresentationClientEndpoint.rs",
+ ),
(
"Services/Compositor/RenderClockClient.ipc",
"RenderClockClientEndpoint.rs",
diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rs
index fe15a001a3a..4c9bc72e573 100644
--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs
+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs
@@ -165,3 +165,20 @@ impl Decode for Compositing_CanvasId {
}
include!(concat!(env!("OUT_DIR"), "/CompositorWebContentClientEndpoint.rs"));
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Gfx_SharedImage(std::convert::Infallible);
+
+impl Encode for Gfx_SharedImage {
+ fn encode(&self, _encoder: &mut Encoder) -> Result<(), EncodeError> {
+ match self.0 {}
+ }
+}
+
+impl Decode for Gfx_SharedImage {
+ fn decode(_decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ Err(DecodeError::InvalidValue("Gfx::SharedImage"))
+ }
+}
+
+include!(concat!(env!("OUT_DIR"), "/CompositorPresentationClientEndpoint.rs"));
diff --git a/Services/Compositor/Rust/src/context_state/mod.rs b/Services/Compositor/Rust/src/context_state/mod.rs
index 08f95440823..334c1a360db 100644
--- a/Services/Compositor/Rust/src/context_state/mod.rs
+++ b/Services/Compositor/Rust/src/context_state/mod.rs
@@ -465,6 +465,18 @@ impl ContextState {
pub fn pointer_in_nested_contexts(&mut self) -> &mut PointerInNestedContexts {
&mut self.pointer_in_nested_contexts
}
+ pub fn pointer_in_nested_contexts_copy(&self) -> PointerInNestedContexts {
+ PointerInNestedContexts {
+ context_with_captured_scrollbar: self.pointer_in_nested_contexts.context_with_captured_scrollbar,
+ last_position_in_context_with_captured_scrollbar: self
+ .pointer_in_nested_contexts
+ .last_position_in_context_with_captured_scrollbar,
+ context_under_pointer: self.pointer_in_nested_contexts.context_under_pointer,
+ }
+ }
+ pub fn set_pointer_in_nested_contexts(&mut self, pointer: PointerInNestedContexts) {
+ self.pointer_in_nested_contexts = pointer;
+ }
pub fn wheel_gesture_id(&self) -> Option<u64> {
self.wheel_gesture_routing.gesture_id()
}
@@ -536,6 +548,9 @@ impl ContextState {
pub fn input_trace(&mut self) -> &mut InputTraceRecorder {
&mut self.input_trace
}
+ pub fn input_trace_mut(&mut self) -> &mut InputTraceRecorder {
+ &mut self.input_trace
+ }
pub fn viewport_size(&self) -> IntSize {
self.viewport_size
}
diff --git a/Services/Compositor/Rust/src/core/input.rs b/Services/Compositor/Rust/src/core/input.rs
new file mode 100644
index 00000000000..48324d0fa34
--- /dev/null
+++ b/Services/Compositor/Rust/src/core/input.rs
@@ -0,0 +1,599 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Keyboard, mouse, and pinch input routing between compositor contexts.
+
+use super::*;
+use crate::context_state::PointerInNestedContexts;
+use libcompositing_rust::ipc_types::{
+ Compositing_AsyncScrollOperationTracking as AsyncScrollOperationTracking, Web_InputTraceRecord as InputTraceRecord,
+ Web_InputTraceStage as InputTraceStage, compositor_presentation_client,
+};
+use libcompositing_rust::scrolling::{
+ InputRoutingDecision, KeyEvent, KeyEventType, MouseEvent, MouseEventType, NestedContextHit, PinchEvent,
+ ScrollGesturePhase,
+};
+
+impl CompositorCore {
+ pub fn handle_and_dispatch_key_event(
+ &self,
+ context_id: CompositorContextId,
+ mut event: KeyEvent,
+ allow_keyboard_scroll: bool,
+ now: MonotonicTime,
+ ) {
+ let _entered = self.enter();
+
+ // NB: The presentation connection only passes on input for the contexts bound to it.
+ let context = self.context_if_present(context_id).expect("context exists");
+ assert!(context.borrow().bound_presentation().is_some());
+ let presentation_id = context.borrow().bound_presentation().unwrap();
+ if !context.borrow().can_dispatch_input_to_web_content() {
+ // No context could take the event; the UI sends it to WebContent itself.
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidNotDispatchInputEvent {
+ context_id,
+ event_id: event.id,
+ },
+ );
+ return;
+ }
+
+ let mut later_keys_need_not_wait = false;
+ if allow_keyboard_scroll {
+ let scroll_box = context.borrow().box_scrolled_for_key_event(&event);
+ if let Some(scroll_box) = scroll_box {
+ let end_event = context.borrow_mut().end_momentum_scrolling(scroll_box);
+ self.dispatch_scroll_fling_step(context_id, context, end_event, now);
+ }
+ let result = context.borrow_mut().handle_key_event(&event, now);
+ later_keys_need_not_wait =
+ self.apply_context_update_result(context_id, context, &result) && event.r#type == KeyEventType::KeyDown;
+ event.async_scroll_performed_default_action =
+ later_keys_need_not_wait && !result.key_found_nothing_to_scroll;
+ if later_keys_need_not_wait && result.key_found_nothing_to_scroll {
+ event.user_input_scroll_count_with_nothing_to_scroll = Some(context.borrow().user_input_scroll_count());
+ }
+ }
+
+ // The scroll updates the event produced reach WebContent ahead of the event itself on the same connection.
+ self.publish_pending_async_scroll_updates(context_id, context);
+ context.borrow().dispatch_key_event_to_web_content(&event);
+ // The compositor forwarded the key event to WebContent, after performing its default action by scrolling if it says so.
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidDispatchInputEvent {
+ context_id,
+ event_id: event.id,
+ performed_default_action: later_keys_need_not_wait,
+ },
+ );
+ }
+
+ pub fn handle_and_dispatch_mouse_event(
+ &self,
+ context_id: CompositorContextId,
+ mut event: MouseEvent,
+ now: MonotonicTime,
+ ) {
+ let _entered = self.enter();
+
+ // NB: The presentation connection only passes on input for the contexts bound to it.
+ let context = self.context_if_present(context_id).expect("context exists");
+ assert!(context.borrow().bound_presentation().is_some());
+ let presentation_id = context.borrow().bound_presentation().unwrap();
+ let record_routing = |decision, scroller| {
+ context.borrow_mut().input_trace_mut().record(InputTraceRecord {
+ input_event_id: event.id,
+ stage: InputTraceStage::Compositor,
+ decision,
+ scroller,
+ dom_target: None,
+ });
+ };
+ if !context.borrow().can_dispatch_input_to_web_content() {
+ record_routing(InputRoutingDecision::NotDispatchedByCompositor, None);
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidNotDispatchInputEvent {
+ context_id,
+ event_id: event.id,
+ },
+ );
+ return;
+ }
+
+ if event.r#type == MouseEventType::MouseMove {
+ context.borrow_mut().note_pointer_position(Some(FloatPoint {
+ x: event.position.x as f32,
+ y: event.position.y as f32,
+ }));
+ } else if matches!(event.r#type, MouseEventType::MouseLeave | MouseEventType::MouseCancel) {
+ context.borrow_mut().note_pointer_position(None);
+ }
+
+ if event.r#type == MouseEventType::MouseDown {
+ let end_event = context.borrow_mut().end_scroll_fling();
+ self.dispatch_scroll_fling_step(context_id, context, end_event, now);
+ }
+
+ let is_wheel_event = event.r#type == MouseEventType::MouseWheel;
+ let mut is_first_wheel_event_with_delta = false;
+ if is_wheel_event {
+ // A key, or a script's smooth scroll, takes over from momentum, until wheel input other than the momentum takes
+ // over again.
+ let absorbs_event = context.borrow_mut().absorbs_wheel_event_of_interrupted_momentum(&event);
+ if absorbs_event {
+ record_routing(InputRoutingDecision::MomentumInterrupted, None);
+ // The compositor performed the event's whole default action, so the UI hears nothing more about it.
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidConsumeInputEvent {
+ context_id,
+ event_id: event.id,
+ },
+ );
+ return;
+ }
+ let noted = context.borrow_mut().note_wheel_event_from_ui(&event, now);
+ event.wheel_gesture_mark = Some(noted.wheel_gesture_mark);
+ is_first_wheel_event_with_delta = noted.is_first_wheel_event_with_delta;
+
+ // The UI can send the end of a gesture more than once. An end that arrives during a fling belongs to the
+ // flicked gesture, so it does not stop the fling.
+ if event.scroll_gesture_phase == ScrollGesturePhase::Ended && context.borrow().has_active_scroll_fling() {
+ record_routing(InputRoutingDecision::GestureEndAbsorbedByFling, None);
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidConsumeInputEvent {
+ context_id,
+ event_id: event.id,
+ },
+ );
+ return;
+ }
+
+ // A new gesture must not continue the gesture of the fling, so the fling ends first.
+ let end_event = context.borrow_mut().interrupt_scroll_fling(&event, now);
+ self.dispatch_scroll_fling_step(context_id, context, end_event, now);
+
+ // If the gesture continues as a fling, the end of the fling is the end of the gesture.
+ let synthesizes_scroll_momentum = context.borrow().presentation_synthesizes_scroll_momentum();
+ let starts_fling = synthesizes_scroll_momentum
+ && event.scroll_gesture_phase == ScrollGesturePhase::Ended
+ && context.borrow_mut().start_scroll_fling_if_flicked(&event, now);
+ if starts_fling {
+ record_routing(InputRoutingDecision::FlingStarted, None);
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidConsumeInputEvent {
+ context_id,
+ event_id: event.id,
+ },
+ );
+ context.borrow_mut().request_display_ticks_if_needed(now);
+ return;
+ }
+ }
+
+ let result = if is_wheel_event {
+ self.scroll_for_wheel_step(
+ context_id,
+ context,
+ &event,
+ WheelStepOrigin::UI,
+ is_first_wheel_event_with_delta,
+ AsyncScrollOperationTracking::No,
+ now,
+ )
+ } else {
+ self.handle_mouse_event_in_nested_contexts(context_id, context, &event, now)
+ };
+ if let Some(decision) = result.nested_context_hand_off {
+ record_routing(decision, None);
+ }
+ if let Some(decision) = result.routing_decision {
+ record_routing(decision, result.routed_scroller);
+ }
+
+ // Asks for the present, publishes the scroll updates the event produced and asks for a rendering update, the last
+ // two of which reach WebContent ahead of the event itself on the same connection. Those of a nested context
+ // another process owns go on that process's connection instead, while the event reaches it through the UI.
+ let handled = self.apply_context_update_result(context_id, context, &result);
+ // A wheel event that lets go of a stretched scroller presents nothing itself; the rebound does from here on. A press
+ // beside the thumb of a scrollbar scrolls there in an animation too.
+ context.borrow_mut().request_display_ticks_if_needed(now);
+ if is_wheel_event {
+ event.async_scroll_performed_default_action = handled;
+ if !handled {
+ context.borrow_mut().note_wheel_event_left_to_the_page(&event);
+ }
+ } else if handled {
+ // The page still sees the events of a drag the compositor scrolls for a scrollbar the display list paints.
+ if result.scrollbar_dragged_by_compositor.is_none() {
+ record_routing(InputRoutingDecision::ConsumedByCompositor, None);
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidConsumeInputEvent {
+ context_id,
+ event_id: event.id,
+ },
+ );
+ return;
+ }
+ event.scrollbar_dragged_by_compositor = result.scrollbar_dragged_by_compositor;
+ }
+ record_routing(InputRoutingDecision::ForwardedToPage, None);
+ context
+ .borrow()
+ .dispatch_mouse_event_to_web_content(&event, self.nested_context_scrolled_since_last_frame(context_id));
+ }
+}
+
+// The content box of a nested context is drawn scaled to the size of its viewport.
+pub(super) fn position_in_nested_context(
+ hit: &NestedContextHit,
+ nested_context: &RefCell<ContextState>,
+) -> Option<FloatPoint> {
+ let viewport_size = nested_context.borrow().viewport_size();
+ if hit.content_box_size.is_empty() || viewport_size.width <= 0 || viewport_size.height <= 0 {
+ return None;
+ }
+ Some(FloatPoint {
+ x: hit.position_in_content_box.x * viewport_size.width as f32 / hit.content_box_size.width,
+ y: hit.position_in_content_box.y * viewport_size.height as f32 / hit.content_box_size.height,
+ })
+}
+
+impl CompositorCore {
+ // Where the position in the presenting context lands in the nested context, through each context in between and
+ // without regard to where their content is or what clips it.
+ pub(super) fn position_in_nested_context_ignoring_clips(
+ &self,
+ presenting_context_id: CompositorContextId,
+ presenting_context: &RefCell<ContextState>,
+ nested_context: &RefCell<ContextState>,
+ mut position: FloatPoint,
+ ) -> Option<FloatPoint> {
+ let mut contexts_from_nested_context_outward = Vec::new();
+ let mut context = nested_context;
+ // A walk up the parents that outlasts the number of contexts went around a loop.
+ let mut remaining_contexts = self.contexts.len();
+ while !std::ptr::eq(context, presenting_context) {
+ if remaining_contexts == 0 {
+ return None;
+ }
+ contexts_from_nested_context_outward.push(context);
+ let parent_context_id = context.borrow().parent_context_id()?;
+ context = if parent_context_id == presenting_context_id {
+ presenting_context
+ } else {
+ self.context_if_present(parent_context_id)?
+ };
+ remaining_contexts -= 1;
+ }
+
+ let mut containing_context = presenting_context;
+ for context_in_between in contexts_from_nested_context_outward.into_iter().rev() {
+ let context_in_between_id = context_in_between.borrow().context_id();
+ let hit = containing_context
+ .borrow_mut()
+ .position_in_content_of_nested_context(context_in_between_id, position)?;
+ let position_in_context = position_in_nested_context(&hit, context_in_between)?;
+ position = position_in_context;
+ containing_context = context_in_between;
+ }
+ Some(position)
+ }
+
+ // The scrollbars of a context nested in the presenting context `context_id` take the pointer over that context's
+ // content, and a drag of one of them takes the pointer wherever it goes until the drag ends.
+ fn handle_mouse_event_in_nested_contexts(
+ &self,
+ context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ event: &MouseEvent,
+ now: MonotonicTime,
+ ) -> ContextUpdateResult {
+ let mut pointer = context.borrow().pointer_in_nested_contexts_copy();
+ let result = (|| {
+ let mut context_with_captured_scrollbar =
+ self.context_still_nested_in(context_id, pointer.context_with_captured_scrollbar);
+ if context_with_captured_scrollbar.is_none_or(|context| !context.borrow().has_captured_scrollbar()) {
+ pointer.context_with_captured_scrollbar = None;
+ context_with_captured_scrollbar = None;
+ }
+
+ // The nested context presents and publishes what the event changed, and this context reports how the event went.
+ let result_of_nested_context = |nested_context_id,
+ nested_context: &RefCell<ContextState>,
+ nested_result: &ContextUpdateResult,
+ frame_of_this_context| {
+ self.apply_context_update_result(nested_context_id, nested_context, nested_result);
+ nested_context.borrow_mut().request_display_ticks_if_needed(now);
+ // Node ids are only unique within the process that made them.
+ let client = context.borrow().web_content_client_id();
+ let ids_are_of_this_process = nested_context.borrow().is_owned_by(client);
+ ContextUpdateResult {
+ accepted: nested_result.accepted,
+ frame_to_present: frame_of_this_context,
+ scrollbar_dragged_by_compositor: nested_result.scrollbar_dragged_by_compositor,
+ routing_decision: nested_result.routing_decision,
+ routed_scroller: if ids_are_of_this_process {
+ nested_result.routed_scroller
+ } else {
+ None
+ },
+ nested_context_hand_off: Some(InputRoutingDecision::HandedToNestedContext),
+ ..Default::default()
+ }
+ };
+
+ let send_to_context_with_captured_scrollbar =
+ |event_to_send: &MouseEvent,
+ pointer: &mut PointerInNestedContexts,
+ captured_context: &mut Option<&RefCell<ContextState>>| {
+ let nested_context_id = pointer.context_with_captured_scrollbar.unwrap();
+ let position = FloatPoint {
+ x: event_to_send.position.x as f32,
+ y: event_to_send.position.y as f32,
+ };
+ // A leave or a cancel has no position of its own.
+ if matches!(
+ event_to_send.r#type,
+ MouseEventType::MouseDown | MouseEventType::MouseMove | MouseEventType::MouseUp
+ ) {
+ let position_in_nested_context = self.position_in_nested_context_ignoring_clips(
+ context_id,
+ context,
+ captured_context.unwrap(),
+ position,
+ );
+ if let Some(position_in_nested_context) = position_in_nested_context {
+ pointer.last_position_in_context_with_captured_scrollbar = position_in_nested_context;
+ }
+ }
+ let nested_context = captured_context.unwrap();
+ let nested_result = nested_context.borrow_mut().handle_mouse_event_from_containing_context(
+ event_to_send,
+ pointer.last_position_in_context_with_captured_scrollbar,
+ now,
+ );
+ let result = result_of_nested_context(nested_context_id, nested_context, &nested_result, None);
+ if !nested_context.borrow().has_captured_scrollbar() {
+ pointer.context_with_captured_scrollbar = None;
+ *captured_context = None;
+ pointer.context_under_pointer = Some(nested_context_id);
+ }
+ result
+ };
+
+ // The scrollbar the pointer was over in the nested context it left is no longer hovered.
+ let note_context_under_pointer = |nested_context_id, pointer: &mut PointerInNestedContexts| {
+ if pointer.context_under_pointer == nested_context_id {
+ return;
+ }
+ if let Some(context_left) = self.context_still_nested_in(context_id, pointer.context_under_pointer) {
+ context_left.borrow_mut().note_pointer_position(None);
+ let frame_to_present = context_left.borrow_mut().clear_scrollbar_hover();
+ if let Some(frame_to_present) = frame_to_present {
+ self.request_present(pointer.context_under_pointer.unwrap(), &frame_to_present);
+ }
+ }
+ pointer.context_under_pointer = nested_context_id;
+ };
+
+ match event.r#type {
+ MouseEventType::MouseDown | MouseEventType::MouseMove => {
+ if context_with_captured_scrollbar.is_some() {
+ if event.r#type == MouseEventType::MouseMove {
+ return send_to_context_with_captured_scrollbar(
+ event,
+ &mut pointer,
+ &mut context_with_captured_scrollbar,
+ );
+ }
+ // A press while a drag is still held means the release of that drag never came, so the drag ends there.
+ let mut cancel_event = event.clone();
+ cancel_event.r#type = MouseEventType::MouseCancel;
+ send_to_context_with_captured_scrollbar(
+ &cancel_event,
+ &mut pointer,
+ &mut context_with_captured_scrollbar,
+ );
+ }
+
+ let mut result = context.borrow_mut().handle_mouse_event(event, now);
+ if result.nested_context_mouse_hit.is_none() {
+ note_context_under_pointer(None, &mut pointer);
+ return result;
+ }
+
+ let frame_of_this_context = result.frame_to_present;
+ let mut containing_context_id = context_id;
+ let mut containing_context = context;
+ let mut position = FloatPoint::default();
+ while let Some(hit) = result.nested_context_mouse_hit.as_ref() {
+ // WebContent names the contexts its display lists draw, so a context only reaches those nested in it.
+ let nested_context = self.context_if_present(hit.child_context_id);
+ let mut position_in_nested_context_content = None;
+ if let Some(nested_context) = nested_context
+ && nested_context.borrow().parent_context_id() == Some(containing_context_id)
+ {
+ position_in_nested_context_content = position_in_nested_context(hit, nested_context);
+ }
+ let Some(position_in_nested_context_content) = position_in_nested_context_content else {
+ note_context_under_pointer(None, &mut pointer);
+ let mut declined =
+ ContextUpdateResult::declined(InputRoutingDecision::NestedContextUnavailable);
+ declined.frame_to_present = frame_of_this_context;
+ declined.nested_context_hand_off = Some(InputRoutingDecision::HandedToNestedContext);
+ return declined;
+ };
+ if !std::ptr::eq(containing_context, context) {
+ self.apply_context_update_result(containing_context_id, containing_context, &result);
+ containing_context.borrow_mut().request_display_ticks_if_needed(now);
+ }
+ containing_context_id = hit.child_context_id;
+ containing_context = nested_context.unwrap();
+ position = position_in_nested_context_content;
+ result = containing_context
+ .borrow_mut()
+ .handle_mouse_event_from_containing_context(event, position, now);
+ }
+
+ note_context_under_pointer(Some(containing_context_id), &mut pointer);
+ if event.r#type == MouseEventType::MouseDown && containing_context.borrow().has_captured_scrollbar()
+ {
+ pointer.context_with_captured_scrollbar = Some(containing_context_id);
+ pointer.last_position_in_context_with_captured_scrollbar = position;
+ }
+ result_of_nested_context(
+ containing_context_id,
+ containing_context,
+ &result,
+ frame_of_this_context,
+ )
+ }
+ MouseEventType::MouseUp => {
+ if context_with_captured_scrollbar.is_some() {
+ return send_to_context_with_captured_scrollbar(
+ event,
+ &mut pointer,
+ &mut context_with_captured_scrollbar,
+ );
+ }
+ context.borrow_mut().handle_mouse_event(event, now)
+ }
+ MouseEventType::MouseLeave | MouseEventType::MouseCancel => {
+ // The pointer leaves every nested context it was in, and a cancel ends the drag of one, as in this context.
+ let mut result_of_context_with_captured_scrollbar = None;
+ let mut context_with_captured_scrollbar_id = None;
+ if context_with_captured_scrollbar.is_some() {
+ context_with_captured_scrollbar_id = pointer.context_with_captured_scrollbar;
+ result_of_context_with_captured_scrollbar = Some(send_to_context_with_captured_scrollbar(
+ event,
+ &mut pointer,
+ &mut context_with_captured_scrollbar,
+ ));
+ }
+ if let Some(context_under_pointer) =
+ self.context_still_nested_in(context_id, pointer.context_under_pointer)
+ && pointer.context_under_pointer != context_with_captured_scrollbar_id
+ {
+ let nested_result = context_under_pointer
+ .borrow_mut()
+ .handle_mouse_event_from_containing_context(event, FloatPoint::default(), now);
+ self.apply_context_update_result(
+ pointer.context_under_pointer.unwrap(),
+ context_under_pointer,
+ &nested_result,
+ );
+ context_under_pointer.borrow_mut().request_display_ticks_if_needed(now);
+ }
+ pointer.context_under_pointer = None;
+
+ let result = context.borrow_mut().handle_mouse_event(event, now);
+ let Some(mut result_of_context_with_captured_scrollbar) = result_of_context_with_captured_scrollbar
+ else {
+ return result;
+ };
+ result_of_context_with_captured_scrollbar.frame_to_present = result.frame_to_present;
+ result_of_context_with_captured_scrollbar
+ }
+ MouseEventType::MouseWheel => context.borrow_mut().handle_mouse_event(event, now),
+ }
+ })();
+ context.borrow_mut().set_pointer_in_nested_contexts(pointer);
+ result
+ }
+
+ // A pinch is a ctrl+wheel event first, to the document under it, whose blocking wheel event listeners may cancel it
+ // before anything zooms. Only the documents at the position can see that event.
+ fn page_under_pinch_may_cancel_it(
+ &self,
+ context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ mut position: FloatPoint,
+ ) -> bool {
+ let mut containing_context_id = context_id;
+ let mut containing_context = context;
+ // A walk down the nested contexts that outlasts the number of contexts went around a loop.
+ for _ in 0..self.contexts.len() {
+ if containing_context.borrow_mut().page_may_cancel_pinch_at(position) {
+ return true;
+ }
+ let hit = containing_context.borrow_mut().nested_context_for_wheel_at(position);
+ let Some(hit) = hit else { return false };
+ // NB: Nothing is known yet of the listeners of a context that is not available.
+ let Some(nested_context) = self.context_if_present(hit.child_context_id) else {
+ return true;
+ };
+ if nested_context.borrow().parent_context_id() != Some(containing_context_id) {
+ return true;
+ }
+ let Some(position_in_nested) = position_in_nested_context(&hit, nested_context) else {
+ return true;
+ };
+ containing_context_id = hit.child_context_id;
+ containing_context = nested_context;
+ position = position_in_nested;
+ }
+ true
+ }
+
+ pub fn handle_and_dispatch_pinch_event(&self, context_id: CompositorContextId, mut event: PinchEvent) {
+ let _entered = self.enter();
+
+ // NB: The presentation connection only passes on input for the contexts bound to it.
+ let context = self.context_if_present(context_id).expect("context exists");
+ assert!(context.borrow().bound_presentation().is_some());
+ let presentation_id = context.borrow().bound_presentation().unwrap();
+ if !context.borrow().can_dispatch_input_to_web_content() {
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidNotDispatchInputEvent {
+ context_id,
+ event_id: event.id,
+ },
+ );
+ return;
+ }
+
+ // The first step of a gesture decides for the steps after it: a gesture the page let through zooms from here on,
+ // whatever listeners have appeared since, and any other leaves each step to the page, wherever the pinch has moved.
+ // A page that already let this step through leaves only the zoom to do.
+ let position = FloatPoint {
+ x: event.position.x as f32,
+ y: event.position.y as f32,
+ };
+ let may_zoom = if event.continues_gesture {
+ context.borrow().pinch_gesture_was_let_through()
+ } else {
+ !self.page_under_pinch_may_cancel_it(context_id, context, position)
+ };
+ if event.wheel_event_was_dispatched || may_zoom {
+ let result = context.borrow_mut().handle_pinch_event(&event);
+ event.async_zoom_performed_default_action = self.apply_context_update_result(context_id, context, &result);
+ }
+ context
+ .borrow_mut()
+ .set_pinch_gesture_was_let_through(event.async_zoom_performed_default_action);
+
+ // The scroll updates the event produced reach WebContent ahead of the event itself on the same connection.
+ self.publish_pending_async_scroll_updates(context_id, context);
+ context.borrow().dispatch_pinch_event_to_web_content(&event);
+ self.host.post_to_presentation(
+ presentation_id,
+ compositor_presentation_client::messages::DidDispatchInputEvent {
+ context_id,
+ event_id: event.id,
+ performed_default_action: event.async_zoom_performed_default_action,
+ },
+ );
+ }
+}
diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rs
new file mode 100644
index 00000000000..5aa32def1ee
--- /dev/null
+++ b/Services/Compositor/Rust/src/core/mod.rs
@@ -0,0 +1,461 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Context lifecycle, frame scheduling, and input routing for the compositor.
+
+mod input;
+mod testing;
+mod wheel;
+
+use crate::context_state::{
+ ContextState, ContextUpdateResult, FirstWheelStepRoute, ScreenshotInputs, ScrollCapabilities,
+};
+use crate::frame_inputs::FrameInputs;
+use crate::host::{
+ ContextTimer, DisplayTickInputs, DisplayTickResult, Host, PendingFrame, PresentRequest, PresentScheduling,
+ PresentationId, WebContentClientId,
+};
+use crate::wheel_gesture_routing::WheelGestureIdAllocator;
+use libcompositing_rust::ipc_types::Compositing_ContextVisibility as ContextVisibility;
+use libcompositing_rust::scrolling::{
+ AccumulatedVisualContextTree, CompositorContextId, DisplayList, ScrollStateSnapshot,
+};
+use libcompositing_rust::time::MonotonicTime;
+use libgfx_rust::{FloatPoint, IntSize};
+use std::cell::{Cell, RefCell};
+use std::collections::HashMap;
+use std::rc::Rc;
+
+pub struct CompositorCore {
+ host: Rc<Host>,
+ contexts: HashMap<CompositorContextId, RefCell<ContextState>>,
+ present_requests: RefCell<Vec<PresentRequest>>,
+ is_entered: Cell<bool>,
+ wheel_gesture_id_allocator: Rc<WheelGestureIdAllocator>,
+ scrollbars_always_shown: bool,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ContextOwnerCheckResult {
+ OwnedByClient,
+ ContextUnavailable,
+ ConflictingOwner,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum WheelStepOrigin {
+ UI,
+ Fling,
+ MainThread,
+}
+
+// How a wheel step went in a context that presented and published what the step changed itself.
+#[derive(Default)]
+struct AppliedWheelStep {
+ // What is left for the context that routes the step to present and report.
+ result: ContextUpdateResult,
+ presents_frame: bool,
+}
+
+struct NestedContextTakingWheelStep<'a> {
+ context_id: CompositorContextId,
+ // Null when the step cannot be handed to the context.
+ context: Option<&'a RefCell<ContextState>>,
+ position: FloatPoint,
+ route: FirstWheelStepRoute,
+}
+
+struct FirstWheelStepInNestedContexts<'a> {
+ // The innermost context that the step went into, whose page sees the step.
+ innermost_context_id: CompositorContextId,
+ // The context that takes the step, which is empty when each of them passes the step on.
+ taking_context: Option<NestedContextTakingWheelStep<'a>>,
+}
+
+struct Entered<'a>(&'a Cell<bool>);
+
+impl<'a> Entered<'a> {
+ fn new(is_entered: &'a Cell<bool>) -> Self {
+ assert!(!is_entered.get());
+ is_entered.set(true);
+ Self(is_entered)
+ }
+}
+
+impl Drop for Entered<'_> {
+ fn drop(&mut self) {
+ self.0.set(false);
+ }
+}
+
+impl CompositorCore {
+ pub fn new(host: Rc<Host>, scrollbars_always_shown: bool) -> Self {
+ Self {
+ host,
+ contexts: HashMap::new(),
+ present_requests: RefCell::new(Vec::new()),
+ is_entered: Cell::new(false),
+ wheel_gesture_id_allocator: Rc::new(WheelGestureIdAllocator::default()),
+ scrollbars_always_shown,
+ }
+ }
+
+ pub fn create_context(
+ &mut self,
+ context_id: CompositorContextId,
+ page_id: Option<u64>,
+ web_content_client_id: WebContentClientId,
+ ) {
+ let _entered = Entered::new(&self.is_entered);
+
+ assert!(!self.contexts.contains_key(&context_id));
+ if let Some(page_id) = page_id {
+ assert!(page_id > 0);
+ assert_eq!(context_id.0, page_id);
+ }
+
+ self.contexts.entry(context_id).or_insert_with(|| {
+ RefCell::new(ContextState::new(
+ context_id,
+ page_id,
+ web_content_client_id,
+ self.host.clone(),
+ self.wheel_gesture_id_allocator.clone(),
+ self.scrollbars_always_shown,
+ ))
+ });
+ }
+
+ // Also leaves the contexts nested in it without a parent.
+ pub fn destroy_context(&mut self, context_id: CompositorContextId) {
+ let _entered = Entered::new(&self.is_entered);
+
+ assert!(self.context_if_present(context_id).is_some());
+ for (&id, possible_child_context) in &self.contexts {
+ if id == context_id {
+ continue;
+ }
+ let parent_context_id = possible_child_context.borrow().parent_context_id();
+ if parent_context_id == Some(context_id) {
+ possible_child_context.borrow_mut().set_parent_context(None);
+ }
+ }
+ self.contexts.remove(&context_id);
+ }
+
+ pub fn check_context_owner(
+ &self,
+ context_id: CompositorContextId,
+ client: WebContentClientId,
+ ) -> ContextOwnerCheckResult {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return ContextOwnerCheckResult::ContextUnavailable;
+ };
+ if !context.borrow().is_owned_by(client) {
+ return ContextOwnerCheckResult::ConflictingOwner;
+ }
+
+ ContextOwnerCheckResult::OwnedByClient
+ }
+
+ pub fn set_parent_context(&self, context_id: CompositorContextId, parent_context_id: Option<CompositorContextId>) {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().set_parent_context(parent_context_id);
+ }
+
+ pub fn stop_presenting_to_client(&self, context_id: CompositorContextId) {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().stop_presenting_to_client();
+ }
+
+ pub fn viewport_size_updated(&self, context_id: CompositorContextId, viewport_size: IntSize) {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return;
+ };
+ context.borrow_mut().viewport_size_updated(viewport_size);
+ }
+
+ pub fn set_paused_debugger_overlay_is_shown(&self, context_id: CompositorContextId, is_shown: bool) {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return;
+ };
+ context.borrow_mut().set_paused_debugger_overlay_is_shown(is_shown);
+ }
+
+ pub fn set_bound_presentation(&self, context_id: CompositorContextId, presentation_id: Option<PresentationId>) {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().set_bound_presentation(presentation_id);
+ }
+
+ pub fn set_scroll_capabilities(&self, context_id: CompositorContextId, capabilities: &ScrollCapabilities) {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().set_scroll_capabilities(capabilities);
+ }
+
+ pub fn install_display_list_update(
+ &self,
+ context_id: CompositorContextId,
+ display_list: Rc<DisplayList>,
+ visual_context_tree: AccumulatedVisualContextTree,
+ scroll_state_snapshot: ScrollStateSnapshot,
+ now: MonotonicTime,
+ ) {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context
+ .borrow_mut()
+ .install_display_list_update(display_list, visual_context_tree, scroll_state_snapshot, now);
+ }
+
+ // Returns false, leaving everything as it was, for a tree that does not fit the installed display list.
+ pub fn update_visual_context_tree(
+ &self,
+ context_id: CompositorContextId,
+ visual_context_tree: AccumulatedVisualContextTree,
+ now: MonotonicTime,
+ ) -> bool {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context
+ .borrow_mut()
+ .update_visual_context_tree(visual_context_tree, now)
+ }
+
+ pub fn needs_animation_frames(&self, context_id: CompositorContextId, now: MonotonicTime) -> bool {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().needs_animation_frames(now)
+ }
+
+ pub fn frame_inputs(&self, context_id: CompositorContextId, now: MonotonicTime) -> Option<FrameInputs> {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().frame_inputs(now)
+ }
+
+ pub fn frame_inputs_for_screenshot(&self, context_id: CompositorContextId, now: MonotonicTime) -> ScreenshotInputs {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().frame_inputs_for_screenshot(now)
+ }
+
+ // Ends the fling of a context that is hidden, whether or not it was visible.
+ pub fn set_visibility(&self, context_id: CompositorContextId, visibility: ContextVisibility, now: MonotonicTime) {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return;
+ };
+ if visibility == ContextVisibility::Hidden {
+ let event = context.borrow_mut().end_scroll_fling();
+ self.dispatch_scroll_fling_step(context_id, context, event, now);
+ }
+ context.borrow_mut().set_visibility(visibility);
+ }
+
+ pub fn timer_fired(&self, context_id: CompositorContextId, timer: ContextTimer, now: MonotonicTime) {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return;
+ };
+ let caret_damage_rect = context.borrow_mut().timer_fired(timer, now);
+ if let Some(caret_damage_rect) = caret_damage_rect {
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: None,
+ forced_damage_rect: caret_damage_rect,
+ scheduling: PresentScheduling::OnNextDisplayTick,
+ });
+ }
+ }
+
+ // The frames asked for since the last call, in the order they were asked for.
+ pub fn take_present_requests(&self) -> Vec<PresentRequest> {
+ let _entered = self.enter();
+
+ std::mem::take(&mut *self.present_requests.borrow_mut())
+ }
+
+ pub(super) fn context_still_nested_in(
+ &self,
+ containing_context_id: CompositorContextId,
+ context_id: Option<CompositorContextId>,
+ ) -> Option<&RefCell<ContextState>> {
+ let context_id = context_id?;
+ let context = self.context_if_present(context_id)?;
+ if !self.is_nested_in(containing_context_id, context) {
+ return None;
+ }
+ Some(context)
+ }
+
+ // Whether a context nested in the context `context_id` scrolled since the last frame its WebContent presented: the lane
+ // of the context's document hands a pointer move to the lane of a same-process iframe, which hit tests it in the iframe.
+ pub(super) fn nested_context_scrolled_since_last_frame(&self, context_id: CompositorContextId) -> bool {
+ for context in self.contexts.values() {
+ if context.borrow().scrolled_since_last_frame() && self.is_nested_in(context_id, context) {
+ return true;
+ }
+ }
+ false
+ }
+
+ pub(super) fn is_nested_in(
+ &self,
+ containing_context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ ) -> bool {
+ // A walk up the parents that outlasts the number of contexts went around a loop.
+ let mut ancestor = Some(context);
+ for _ in 0..self.contexts.len() {
+ let Some(current_ancestor) = ancestor else { break };
+ let Some(parent_context_id) = current_ancestor.borrow().parent_context_id() else {
+ return false;
+ };
+ if parent_context_id == containing_context_id {
+ return true;
+ }
+ ancestor = self.context_if_present(parent_context_id);
+ }
+ false
+ }
+
+ // Hands the context's async scroll updates to its WebContent process as soon as they exist,
+ // so a rendering update reads them locally instead of asking for them over a synchronous call.
+ pub(super) fn publish_pending_async_scroll_updates(&self, _: CompositorContextId, context: &RefCell<ContextState>) {
+ context.borrow_mut().publish_pending_async_scroll_updates();
+ }
+
+ pub(super) fn request_present(&self, context_id: CompositorContextId, frame: &PendingFrame) {
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: Some(frame.viewport_rect),
+ forced_damage_rect: frame.forced_damage_rect,
+ scheduling: PresentScheduling::OnNextDisplayTick,
+ });
+ }
+
+ pub fn display_tick(
+ &self,
+ context_id: CompositorContextId,
+ frame_time: MonotonicTime,
+ now: MonotonicTime,
+ inputs: &DisplayTickInputs,
+ ) -> DisplayTickResult {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+
+ let has_active_animation_on_display = (context.borrow_mut().needs_animation_frames(now)
+ || inputs.ui_overlay_fades_need_frame)
+ && inputs.context_is_on_tick_display;
+ let presents_on_display = inputs.present_is_scheduled_on_tick_display || has_active_animation_on_display;
+ if presents_on_display {
+ if inputs.context_is_on_tick_display {
+ let event = context.borrow_mut().take_scroll_fling_step(frame_time);
+ self.dispatch_scroll_fling_step(context_id, context, event, frame_time);
+ }
+ let animation_frame = context.borrow_mut().advance_smooth_scroll_animations(frame_time);
+ if let Some(animation_frame) = animation_frame {
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: Some(animation_frame),
+ forced_damage_rect: Default::default(),
+ scheduling: PresentScheduling::WithDisplayTickInProgress,
+ });
+ }
+ let rebound_frame = context.borrow_mut().advance_elastic_overscroll_rebounds(frame_time);
+ if let Some(rebound_frame) = rebound_frame {
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: Some(rebound_frame),
+ forced_damage_rect: Default::default(),
+ scheduling: PresentScheduling::WithDisplayTickInProgress,
+ });
+ }
+ let damage_rect = context
+ .borrow_mut()
+ .advance_scrollbar_fades_and_return_damage_rect(frame_time);
+ if !damage_rect.is_empty() {
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: None,
+ forced_damage_rect: damage_rect,
+ scheduling: PresentScheduling::WithDisplayTickInProgress,
+ });
+ }
+ }
+
+ // A render clock tick goes to the process's render clock thread, beside what its main thread is doing, with
+ // where the compositor has scrolled to for this vsync, which that main thread may not have taken in yet.
+ if let Some(interval) = inputs.clock_tick_interval_in_milliseconds {
+ context.borrow().post_clock_tick(frame_time, interval);
+ }
+
+ if presents_on_display {
+ self.publish_pending_async_scroll_updates(context_id, context);
+ let needs_frame = context.borrow_mut().visual_animations_need_frame(now);
+ if needs_frame {
+ context.borrow_mut().advance_visual_animations(frame_time);
+ self.present_requests.borrow_mut().push(PresentRequest {
+ context_id,
+ viewport_rect: None,
+ forced_damage_rect: Default::default(),
+ scheduling: PresentScheduling::WithDisplayTickInProgress,
+ });
+ }
+ }
+ DisplayTickResult {
+ presents_on_display,
+ needs_animation_frames: context.borrow_mut().needs_animation_frames(now),
+ }
+ }
+
+ pub(super) fn context_if_present(&self, context_id: CompositorContextId) -> Option<&RefCell<ContextState>> {
+ self.contexts.get(&context_id)
+ }
+
+ pub(super) fn apply_context_update_result(
+ &self,
+ context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ result: &ContextUpdateResult,
+ ) -> bool {
+ if let Some(frame) = result.frame_to_present {
+ self.request_present(context_id, &frame);
+ }
+ self.publish_pending_async_scroll_updates(context_id, context);
+ if result.should_request_rendering_update {
+ context.borrow_mut().request_rendering_update();
+ }
+ result.accepted
+ }
+
+ fn enter(&self) -> Entered<'_> {
+ Entered::new(&self.is_entered)
+ }
+}
diff --git a/Services/Compositor/Rust/src/core/testing.rs b/Services/Compositor/Rust/src/core/testing.rs
new file mode 100644
index 00000000000..0787aa118ca
--- /dev/null
+++ b/Services/Compositor/Rust/src/core/testing.rs
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Test queries and input tracing for compositor contexts.
+
+use super::*;
+use libcompositing_rust::ipc_types::Web_InputTraceRecord as InputTraceRecord;
+use libcompositing_rust::scrolling::{
+ AsyncScrollNodeStableID, FirstWheelStepRouteForTesting, NestedContextRegions, WheelDeltaPrecision,
+};
+
+impl CompositorCore {
+ pub fn scroll_state_for_testing(
+ &self,
+ context_id: CompositorContextId,
+ stretched_scroller: AsyncScrollNodeStableID,
+ ) -> String {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return String::new();
+ };
+ context.borrow().scroll_state_for_testing(stretched_scroller)
+ }
+
+ pub fn route_first_wheel_step_for_testing(
+ &self,
+ context_id: CompositorContextId,
+ position: FloatPoint,
+ delta_in_css_pixels: FloatPoint,
+ ) -> Option<FirstWheelStepRouteForTesting> {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id)?;
+ let may_hand_to_nested_contexts =
+ context.borrow().presents_to_client() && context.borrow().may_hand_first_wheel_steps_to_nested_contexts();
+ if !may_hand_to_nested_contexts {
+ return Some(context.borrow_mut().route_first_wheel_step_for_testing(
+ position,
+ delta_in_css_pixels,
+ NestedContextRegions::LeaveToMainThread,
+ ));
+ }
+ let hit = context.borrow_mut().nested_context_for_wheel_at(position);
+ let Some(hit) = hit else {
+ return Some(context.borrow_mut().route_first_wheel_step_for_testing(
+ position,
+ delta_in_css_pixels,
+ NestedContextRegions::HandToNestedContext,
+ ));
+ };
+ let taking_context = self
+ .first_wheel_step_in_nested_contexts(context_id, hit, delta_in_css_pixels, WheelDeltaPrecision::Precise)
+ .taking_context;
+ let Some(taking_context) = taking_context else {
+ return Some(context.borrow_mut().route_first_wheel_step_for_testing(
+ position,
+ delta_in_css_pixels,
+ NestedContextRegions::Ignore,
+ ));
+ };
+ // Node ids are only unique within the process that made them.
+ let ids_are_of_this_process = taking_context.context.is_some_and(|taking_context| {
+ taking_context
+ .borrow()
+ .is_owned_by(context.borrow().web_content_client_id())
+ });
+ let mut route = FirstWheelStepRouteForTesting {
+ route: libcompositing_rust::scrolling::FirstWheelStepRoute {
+ decision: taking_context.route.decision,
+ scroller: None,
+ },
+ document_id: None,
+ };
+ if ids_are_of_this_process {
+ route.route.scroller = taking_context.route.scroller;
+ route.document_id = taking_context.context.unwrap().borrow().document_id();
+ }
+ Some(route)
+ }
+
+ pub fn begin_input_trace_for_testing(&self, context_id: CompositorContextId) {
+ let _entered = self.enter();
+
+ if let Some(context) = self.context_if_present(context_id) {
+ context.borrow_mut().input_trace_mut().begin();
+ }
+ }
+
+ pub fn clear_per_test_input_state_for_testing(&self, context_id: CompositorContextId) {
+ let _entered = self.enter();
+
+ if let Some(context) = self.context_if_present(context_id) {
+ context.borrow_mut().clear_per_test_input_state();
+ }
+ }
+
+ pub fn take_input_trace_for_testing(&self, context_id: CompositorContextId) -> Vec<InputTraceRecord> {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return Vec::new();
+ };
+ context.borrow_mut().input_trace_mut().take()
+ }
+}
diff --git a/Services/Compositor/Rust/src/core/wheel.rs b/Services/Compositor/Rust/src/core/wheel.rs
new file mode 100644
index 00000000000..a9e1468a203
--- /dev/null
+++ b/Services/Compositor/Rust/src/core/wheel.rs
@@ -0,0 +1,858 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Wheel gestures, nested scroll routing, and scroll requests for compositor contexts.
+
+use super::input::position_in_nested_context;
+use super::*;
+use crate::context_state::{
+ FirstWheelStepRouteKind, NestedContextWheelStep, TrackedScrollOperation, WheelEventListenerGate, WheelStep,
+ WheelStepAdmission,
+};
+use libcompositing_rust::ipc_types::{
+ Compositing_AsyncScrollOperationTracking as AsyncScrollOperationTracking,
+ Compositing_SmoothScrollInitiator as SmoothScrollInitiator, Compositing_WheelEventAnswer as WheelEventAnswer,
+ Compositing_WheelEventRouting as WheelEventRouting, Compositing_WheelStepLetThrough as WheelStepLetThrough,
+ Web_InputTraceRecord as InputTraceRecord, Web_InputTraceStage as InputTraceStage,
+};
+use libcompositing_rust::scrolling::{
+ AsyncScrollNodeStableID, InputRoutingDecision, KeyboardScrollState, MouseEvent, NestedContextHit,
+ NestedContextRegions, PendingAsyncScrollUpdates, ScrollGesturePhase, ScrollRequest, WheelDeltaPrecision,
+ WheelGestureMark,
+};
+
+impl CompositorCore {
+ pub fn update_scroll_state(
+ &self,
+ context_id: CompositorContextId,
+ scroll_state_snapshot: ScrollStateSnapshot,
+ keyboard_scroll_state: KeyboardScrollState,
+ ) {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+
+ context
+ .borrow_mut()
+ .update_scroll_state(scroll_state_snapshot, keyboard_scroll_state);
+ }
+
+ pub fn invalidate_wheel_event_listener_state(&self, context_id: CompositorContextId, generation: u64) {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+ context.borrow_mut().invalidate_wheel_event_listener_state(generation);
+ }
+
+ pub fn invalidate_keyboard_scroll_state(&self, context_id: CompositorContextId, generation: u64) {
+ let _entered = self.enter();
+
+ if let Some(context) = self.context_if_present(context_id) {
+ context.borrow_mut().invalidate_keyboard_scroll_state(generation);
+ }
+ }
+
+ // A fling step is scrolled at the frame time the fling synthesized it for.
+ #[allow(clippy::too_many_arguments)]
+ pub(super) fn scroll_for_wheel_step(
+ &self,
+ context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ event: &MouseEvent,
+ origin: WheelStepOrigin,
+ is_first_wheel_event_with_delta: bool,
+ operation_tracking: AsyncScrollOperationTracking,
+ now: MonotonicTime,
+ ) -> ContextUpdateResult {
+ let gesture_id = context.borrow().wheel_gesture_id();
+ let listener_context_id = context.borrow().wheel_event_listener_context().unwrap_or(context_id);
+ let listener_context = if listener_context_id == context_id {
+ Some(context)
+ } else {
+ self.context_still_nested_in(context_id, Some(listener_context_id))
+ };
+ let listener_gate = if let Some(listener_context) = listener_context {
+ listener_context.borrow().wheel_event_listener_gate(gesture_id)
+ } else {
+ WheelEventListenerGate {
+ reason_to_hold_latched_steps_back: Some(InputRoutingDecision::NestedContextUnavailable),
+ ..Default::default()
+ }
+ };
+
+ let mut result;
+ let mut presents_frame;
+ let route_from_listener = listener_context
+ .is_some_and(|listener_context| !std::ptr::eq(listener_context, context))
+ && listener_gate.page_let_the_gesture_through
+ && !context.borrow().has_wheel_latch_for_gesture(gesture_id);
+ if route_from_listener {
+ let listener_context = listener_context.unwrap();
+ // The page of a nested context let the gesture through while nothing took its steps, so they go to that context
+ // again rather than to the page.
+ let mut step = WheelStep::for_wheel_event(event, gesture_id, operation_tracking);
+ let position =
+ self.position_in_nested_context_ignoring_clips(context_id, context, listener_context, step.position);
+ let Some(position) = position else {
+ return ContextUpdateResult::declined(InputRoutingDecision::NestedContextUnavailable);
+ };
+ step.position = position;
+ let applied_step = self.route_wheel_step_the_page_let_through(
+ context_id,
+ context,
+ listener_context_id,
+ listener_context,
+ step,
+ &[],
+ None,
+ now,
+ );
+ result = applied_step.result;
+ result.nested_context_hand_off = Some(InputRoutingDecision::HandedToNestedContext);
+ presents_frame = applied_step.presents_frame;
+ } else {
+ result = match origin {
+ WheelStepOrigin::UI => {
+ context
+ .borrow_mut()
+ .handle_wheel_event(event, is_first_wheel_event_with_delta, &listener_gate, now)
+ }
+ WheelStepOrigin::Fling => context.borrow_mut().scroll_for_fling_step(event, &listener_gate, now),
+ WheelStepOrigin::MainThread => context.borrow_mut().scroll_for_wheel_event_from_main_thread(
+ event,
+ is_first_wheel_event_with_delta,
+ &listener_gate,
+ operation_tracking,
+ now,
+ ),
+ };
+ presents_frame = result.frame_to_present.is_some();
+ if let Some(nested_step) = &result.nested_context_wheel_step {
+ let applied_step = self.hand_wheel_step_to_nested_context(
+ context_id,
+ context,
+ event,
+ nested_step,
+ &listener_gate,
+ operation_tracking,
+ now,
+ );
+ result = applied_step.result;
+ presents_frame = applied_step.presents_frame;
+ }
+ }
+
+ // If the compositor accepts a momentum step of the fling but does not scroll, the scroller is at its edge.
+ // Alternatively, a snap scroll uses the step. The next display tick ends the fling.
+ if origin == WheelStepOrigin::Fling
+ && event.scroll_gesture_phase == ScrollGesturePhase::Momentum
+ && result.accepted
+ && !presents_frame
+ {
+ context.borrow_mut().end_scroll_fling_on_next_step();
+ }
+ result
+ }
+
+ // A process only knows the ids of its own nodes, and only follows the operations of its own contexts.
+ fn apply_wheel_step_result(
+ &self,
+ context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ result: &ContextUpdateResult,
+ reporting_client: WebContentClientId,
+ now: MonotonicTime,
+ ) -> AppliedWheelStep {
+ self.apply_context_update_result(context_id, context, result);
+ context.borrow_mut().request_display_ticks_if_needed(now);
+ // Node ids are only unique within the process that made them, and only that process follows the operations of the
+ // context.
+ let ids_are_of_reporting_process = context.borrow().is_owned_by(reporting_client);
+ AppliedWheelStep {
+ result: ContextUpdateResult {
+ accepted: result.accepted,
+ routing_decision: result.routing_decision,
+ routed_scroller: if ids_are_of_reporting_process {
+ result.routed_scroller
+ } else {
+ None
+ },
+ tracked_scroll_operation: if ids_are_of_reporting_process {
+ result
+ .tracked_scroll_operation
+ .as_ref()
+ .map(|operation| TrackedScrollOperation {
+ context_id: operation.context_id,
+ operation_id: operation.operation_id,
+ })
+ } else {
+ None
+ },
+ ..Default::default()
+ },
+ presents_frame: result.frame_to_present.is_some(),
+ }
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn hand_wheel_step_to_nested_context(
+ &self,
+ context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ event: &MouseEvent,
+ nested_step: &NestedContextWheelStep,
+ listener_gate: &WheelEventListenerGate,
+ operation_tracking: AsyncScrollOperationTracking,
+ now: MonotonicTime,
+ ) -> AppliedWheelStep {
+ let mut step = WheelStep::for_wheel_event(event, context.borrow().wheel_gesture_id(), operation_tracking);
+
+ if nested_step.hit.is_none() {
+ let nested_context = self.context_if_present(nested_step.context_id);
+ if nested_context.is_none_or(|context| !self.is_nested_in(context_id, context)) {
+ context.borrow_mut().forget_wheel_gesture_latch();
+ return AppliedWheelStep {
+ result: ContextUpdateResult::declined(InputRoutingDecision::NestedContextUnavailable),
+ ..Default::default()
+ };
+ }
+ let nested_context = nested_context.unwrap();
+ // A blocking listener added during the gesture holds its later steps back until the page lets one through.
+ if let Some(reason) = listener_gate.reason_to_hold_latched_steps_back {
+ return AppliedWheelStep {
+ result: ContextUpdateResult::declined(reason),
+ ..Default::default()
+ };
+ }
+ let admission = if listener_gate.page_let_the_gesture_through {
+ WheelStepAdmission::LetThroughByThePage
+ } else {
+ WheelStepAdmission::ByThisPage
+ };
+ let nested_result = nested_context
+ .borrow_mut()
+ .take_latched_wheel_step_from_containing_context(&step, admission, now);
+ if nested_result.routing_decision == Some(InputRoutingDecision::NestedContextUnavailable) {
+ context.borrow_mut().forget_wheel_gesture_latch();
+ }
+ let reporting_client = context.borrow().web_content_client_id();
+ return self.apply_wheel_step_result(
+ nested_step.context_id,
+ nested_context,
+ &nested_result,
+ reporting_client,
+ now,
+ );
+ }
+
+ let first_step = self.first_wheel_step_in_nested_contexts(
+ context_id,
+ {
+ let hit = nested_step.hit.as_ref().unwrap();
+ NestedContextHit {
+ child_context_id: hit.child_context_id,
+ position_in_content_box: hit.position_in_content_box,
+ content_box_size: hit.content_box_size,
+ paint_order_index: hit.paint_order_index,
+ }
+ },
+ step.delta_in_css_pixels,
+ step.wheel_delta_precision,
+ );
+ context
+ .borrow_mut()
+ .set_wheel_event_listener_context(first_step.innermost_context_id);
+ let Some(taking_context) = first_step.taking_context else {
+ let mut result =
+ context
+ .borrow_mut()
+ .scroll_for_wheel_event_passed_on_by_nested_context(event, operation_tracking, now);
+ result.nested_context_hand_off = Some(InputRoutingDecision::NestedContextPassedStepOn);
+ let presents_frame = result.frame_to_present.is_some();
+ return AppliedWheelStep { result, presents_frame };
+ };
+
+ let mut applied_step;
+ if let Some(nested_context) = taking_context.context
+ && taking_context.route.kind != FirstWheelStepRouteKind::Declined
+ {
+ step.position = taking_context.position;
+ let nested_result = nested_context
+ .borrow_mut()
+ .take_first_wheel_step_from_containing_context(&taking_context.route, &step, now);
+ let reporting_client = context.borrow().web_content_client_id();
+ applied_step = self.apply_wheel_step_result(
+ taking_context.context_id,
+ nested_context,
+ &nested_result,
+ reporting_client,
+ now,
+ );
+ context.borrow_mut().latch_wheel_gesture_to_nested_context(
+ taking_context.context_id,
+ applied_step.result.routed_scroller,
+ step.scroll_gesture_phase,
+ );
+ } else {
+ applied_step = AppliedWheelStep {
+ result: ContextUpdateResult::declined(taking_context.route.decision),
+ ..Default::default()
+ };
+ }
+ applied_step.result.nested_context_hand_off = Some(InputRoutingDecision::HandedToNestedContext);
+ applied_step
+ }
+
+ // Where the first step of a gesture over the content of a context nested in the context `context_id` goes, among
+ // that context and the contexts nested in it.
+ pub(super) fn first_wheel_step_in_nested_contexts(
+ &self,
+ context_id: CompositorContextId,
+ mut hit: NestedContextHit,
+ delta_in_css_pixels: FloatPoint,
+ wheel_delta_precision: WheelDeltaPrecision,
+ ) -> FirstWheelStepInNestedContexts<'_> {
+ use FirstWheelStepRouteKind as Kind;
+ // The contexts the step went into, outermost first, each nested in the one before.
+ let mut contexts = Vec::new();
+ let mut containing_context_id = context_id;
+ loop {
+ let declined_by_unavailable_context = || FirstWheelStepInNestedContexts {
+ innermost_context_id: hit.child_context_id,
+ taking_context: Some(NestedContextTakingWheelStep {
+ context_id: hit.child_context_id,
+ context: None,
+ position: FloatPoint::default(),
+ route: FirstWheelStepRoute {
+ kind: Kind::Declined,
+ decision: InputRoutingDecision::NestedContextUnavailable,
+ scroll_node_index: None,
+ scroller: None,
+ nested_context_hit: None,
+ },
+ }),
+ };
+ // WebContent names the contexts its display lists draw, so a context only reaches those nested in it.
+ let Some(nested_context) = self.context_if_present(hit.child_context_id) else {
+ return declined_by_unavailable_context();
+ };
+ if nested_context.borrow().parent_context_id() != Some(containing_context_id) {
+ return declined_by_unavailable_context();
+ }
+ let Some(position) = position_in_nested_context(&hit, nested_context) else {
+ return declined_by_unavailable_context();
+ };
+ let route = nested_context
+ .borrow_mut()
+ .route_first_wheel_step_from_containing_context(
+ position,
+ delta_in_css_pixels,
+ wheel_delta_precision,
+ NestedContextRegions::HandToNestedContext,
+ WheelStepAdmission::ByThisPage,
+ &[],
+ );
+ let kind = route.kind;
+ let nested_context_hit = route.nested_context_hit.as_ref().map(|hit| NestedContextHit {
+ child_context_id: hit.child_context_id,
+ position_in_content_box: hit.position_in_content_box,
+ content_box_size: hit.content_box_size,
+ paint_order_index: hit.paint_order_index,
+ });
+ contexts.push(NestedContextTakingWheelStep {
+ context_id: hit.child_context_id,
+ context: Some(nested_context),
+ position,
+ route,
+ });
+ if kind != Kind::NestedContext {
+ break;
+ }
+ containing_context_id = hit.child_context_id;
+ hit = nested_context_hit.unwrap();
+ }
+
+ // What a nested context passes on goes to whatever is painted under it in the context it is nested in, whose page
+ // does not see the step.
+ let innermost_context_id = contexts.last().unwrap().context_id;
+ while contexts.last().unwrap().route.kind == Kind::PassedOn {
+ contexts.pop();
+ if contexts.is_empty() {
+ return FirstWheelStepInNestedContexts {
+ innermost_context_id,
+ taking_context: None,
+ };
+ }
+ let containing_context = contexts.last_mut().unwrap();
+ containing_context.route = containing_context
+ .context
+ .unwrap()
+ .borrow_mut()
+ .route_first_wheel_step_from_containing_context(
+ containing_context.position,
+ delta_in_css_pixels,
+ wheel_delta_precision,
+ NestedContextRegions::Ignore,
+ WheelStepAdmission::PassedOnByNestedContext,
+ &[],
+ );
+ }
+ FirstWheelStepInNestedContexts {
+ innermost_context_id,
+ taking_context: contexts.pop(),
+ }
+ }
+}
+
+// The page of one process scrolls a context of another process only by what the UI left to the page in the gesture, so
+// that a page cannot scroll the document around it at will.
+fn page_may_scroll_in(
+ context: &RefCell<ContextState>,
+ routing_context: &RefCell<ContextState>,
+ page_client: Option<WebContentClientId>,
+ step: &WheelStep,
+) -> bool {
+ let Some(page_client) = page_client else { return true };
+ if context.borrow().is_owned_by(page_client) {
+ return true;
+ }
+ routing_context
+ .borrow_mut()
+ .take_wheel_delta_left_to_the_page(step.delta_in_css_pixels)
+}
+
+impl CompositorCore {
+ // Routes the first step of a gesture that the page of the listener context let through: in that context, from the
+ // scrollers the page found around the target, and on to the contexts around it for what a context passes on, up to
+ // the routing context, which latches the gesture. A page of another process than a context's scrolls it only by
+ // what the UI left to the page in the gesture.
+ #[allow(clippy::too_many_arguments)]
+ fn route_wheel_step_the_page_let_through(
+ &self,
+ routing_context_id: CompositorContextId,
+ routing_context: &RefCell<ContextState>,
+ listener_context_id: CompositorContextId,
+ listener_context: &RefCell<ContextState>,
+ mut step: WheelStep,
+ mut scroll_chain: &[AsyncScrollNodeStableID],
+ page_client: Option<WebContentClientId>,
+ now: MonotonicTime,
+ ) -> AppliedWheelStep {
+ use FirstWheelStepRouteKind as Kind;
+ let reporting_client = page_client.unwrap_or_else(|| routing_context.borrow().web_content_client_id());
+ let declined = |decision| AppliedWheelStep {
+ result: ContextUpdateResult::declined(decision),
+ ..Default::default()
+ };
+
+ let mut context_id = listener_context_id;
+ let mut context = listener_context;
+ // A walk up the parents that outlasts the number of contexts went around a loop.
+ for _ in 0..self.contexts.len() {
+ if std::ptr::eq(context, routing_context) {
+ if !page_may_scroll_in(routing_context, routing_context, page_client, &step) {
+ return declined(InputRoutingDecision::StepExceedsInputLeftToThePage);
+ }
+ let result = routing_context
+ .borrow_mut()
+ .scroll_for_first_wheel_step_the_page_let_through(&step, scroll_chain, now);
+ return self.apply_wheel_step_result(
+ routing_context_id,
+ routing_context,
+ &result,
+ reporting_client,
+ now,
+ );
+ }
+
+ let route = context.borrow_mut().route_first_wheel_step_from_containing_context(
+ step.position,
+ step.delta_in_css_pixels,
+ step.wheel_delta_precision,
+ NestedContextRegions::Ignore,
+ WheelStepAdmission::LetThroughByThePage,
+ scroll_chain,
+ );
+ if matches!(route.kind, Kind::ScrollNode | Kind::Kept) {
+ if !page_may_scroll_in(context, routing_context, page_client, &step) {
+ return declined(InputRoutingDecision::StepExceedsInputLeftToThePage);
+ }
+ let nested_result = context
+ .borrow_mut()
+ .take_first_wheel_step_from_containing_context(&route, &step, now);
+ let client = routing_context.borrow().web_content_client_id();
+ let latched_scroller = if context.borrow().is_owned_by(client) {
+ nested_result.routed_scroller
+ } else {
+ None
+ };
+ routing_context.borrow_mut().latch_wheel_gesture_to_nested_context(
+ context_id,
+ latched_scroller,
+ step.scroll_gesture_phase,
+ );
+ return self.apply_wheel_step_result(context_id, context, &nested_result, reporting_client, now);
+ }
+ if route.kind != Kind::PassedOn {
+ return declined(route.decision);
+ }
+
+ // What a nested context passes on goes to whatever is painted under it in the context it is nested in.
+ let parent_context_id = context.borrow().parent_context_id();
+ let parent_context = parent_context_id.and_then(|id| self.context_if_present(id));
+ let Some(parent_context) = parent_context else {
+ return declined(InputRoutingDecision::NestedContextUnavailable);
+ };
+ let viewport_size = context.borrow().viewport_size();
+ let position = parent_context.borrow_mut().position_of_nested_context_position(
+ context_id,
+ step.position,
+ viewport_size,
+ );
+ let Some(position) = position else {
+ return declined(InputRoutingDecision::NestedContextUnavailable);
+ };
+ step.position = position;
+ scroll_chain = &[];
+ context_id = parent_context_id.unwrap();
+ context = parent_context;
+ }
+ declined(InputRoutingDecision::NestedContextUnavailable)
+ }
+
+ // The nearest context, from the given one out to the presenting one, that noted the gesture.
+ fn routing_context_of_wheel_gesture(
+ &self,
+ context_id: CompositorContextId,
+ gesture_id: u64,
+ ) -> Option<CompositorContextId> {
+ // A walk up the parents that outlasts the number of contexts went around a loop.
+ let mut candidate_context_id = Some(context_id);
+ for _ in 0..self.contexts.len() {
+ let id = candidate_context_id?;
+ let candidate_context = self.context_if_present(id)?;
+ if candidate_context.borrow().wheel_gesture_id() == Some(gesture_id) {
+ return candidate_context_id;
+ }
+ candidate_context_id = candidate_context.borrow().parent_context_id();
+ }
+ None
+ }
+
+ pub(super) fn dispatch_scroll_fling_step(
+ &self,
+ context_id: CompositorContextId,
+ context: &RefCell<ContextState>,
+ event: Option<MouseEvent>,
+ now: MonotonicTime,
+ ) {
+ // Send each fling step on the same route as a wheel event from the UI.
+ let Some(mut event) = event else { return };
+ let result = self.scroll_for_wheel_step(
+ context_id,
+ context,
+ &event,
+ WheelStepOrigin::Fling,
+ false,
+ AsyncScrollOperationTracking::No,
+ now,
+ );
+ if let Some(decision) = result.nested_context_hand_off {
+ context.borrow_mut().input_trace_mut().record(InputTraceRecord {
+ input_event_id: event.id,
+ stage: InputTraceStage::Compositor,
+ decision,
+ scroller: None,
+ dom_target: None,
+ });
+ }
+ if let Some(decision) = result.routing_decision {
+ context.borrow_mut().input_trace_mut().record(InputTraceRecord {
+ input_event_id: event.id,
+ stage: InputTraceStage::Compositor,
+ decision,
+ scroller: result.routed_scroller,
+ dom_target: None,
+ });
+ }
+ event.async_scroll_performed_default_action = self.apply_context_update_result(context_id, context, &result);
+ if !event.async_scroll_performed_default_action {
+ context.borrow_mut().note_wheel_event_left_to_the_page(&event);
+ }
+ context.borrow_mut().request_display_ticks_if_needed(now);
+ context.borrow().dispatch_mouse_event_to_web_content(&event, false);
+ }
+
+ fn wheel_event_answer_for(
+ &self,
+ applied_step: &AppliedWheelStep,
+ wheel_gesture_mark: Option<WheelGestureMark>,
+ ) -> WheelEventAnswer {
+ let tracked_scroll_operation = &applied_step.result.tracked_scroll_operation;
+ WheelEventAnswer {
+ performed_default_action: applied_step.result.accepted,
+ wheel_gesture_mark,
+ operation_id: tracked_scroll_operation
+ .as_ref()
+ .map(|operation| operation.operation_id),
+ operation_context_id: tracked_scroll_operation.as_ref().map(|operation| operation.context_id),
+ routing_decision: applied_step.result.routing_decision,
+ routed_scroller: applied_step.result.routed_scroller,
+ }
+ }
+
+ pub fn take_wheel_event_from_main_thread(
+ &self,
+ context_id: CompositorContextId,
+ event: &MouseEvent,
+ operation_tracking: AsyncScrollOperationTracking,
+ routing: WheelEventRouting,
+ now: MonotonicTime,
+ ) -> WheelEventAnswer {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+
+ let noted = context.borrow_mut().note_wheel_event_from_main_thread(event, now);
+ if routing == WheelEventRouting::AfterDispatch {
+ return WheelEventAnswer {
+ performed_default_action: false,
+ wheel_gesture_mark: Some(noted.wheel_gesture_mark),
+ operation_id: None,
+ operation_context_id: None,
+ routing_decision: None,
+ routed_scroller: None,
+ };
+ }
+ let result = self.scroll_for_wheel_step(
+ context_id,
+ context,
+ event,
+ WheelStepOrigin::MainThread,
+ noted.is_first_wheel_event_with_delta,
+ operation_tracking,
+ now,
+ );
+ let reporting_client = context.borrow().web_content_client_id();
+ self.wheel_event_answer_for(
+ &self.apply_wheel_step_result(context_id, context, &result, reporting_client, now),
+ Some(noted.wheel_gesture_mark),
+ )
+ }
+
+ pub fn scroll_for_wheel_event_the_page_let_through(
+ &self,
+ listener_context_id: CompositorContextId,
+ let_through: &WheelStepLetThrough,
+ operation_tracking: AsyncScrollOperationTracking,
+ page_client: WebContentClientId,
+ now: MonotonicTime,
+ ) -> WheelEventAnswer {
+ let _entered = self.enter();
+
+ let listener_context = self.context_if_present(listener_context_id).expect("context exists");
+ if listener_context.borrow().document_id() != Some(let_through.document_id) {
+ return WheelEventAnswer {
+ performed_default_action: false,
+ wheel_gesture_mark: None,
+ operation_id: None,
+ operation_context_id: None,
+ routing_decision: Some(InputRoutingDecision::ScrollerInOtherDocument),
+ routed_scroller: None,
+ };
+ }
+
+ let gesture_id = let_through.wheel_gesture_mark.gesture_id;
+ // A step that moves along no axis goes to the page as no wheel event, so the page had no say in letting it through,
+ // and it decides nothing for the steps after it.
+ if !let_through.delta_in_css_pixels.is_zero() {
+ listener_context
+ .borrow_mut()
+ .note_page_let_wheel_gesture_through(gesture_id);
+ }
+ let step = WheelStep {
+ position: let_through.position,
+ delta_in_css_pixels: let_through.delta_in_css_pixels,
+ wheel_delta_precision: let_through.wheel_delta_precision,
+ scroll_gesture_phase: let_through.scroll_gesture_phase,
+ gesture_id: Some(gesture_id),
+ operation_tracking,
+ };
+ let scroll_chain = let_through.scroll_chain.as_slice();
+ let answer = |applied_step: &AppliedWheelStep| {
+ self.wheel_event_answer_for(applied_step, Some(let_through.wheel_gesture_mark.clone()))
+ };
+ let declined = |decision| {
+ answer(&AppliedWheelStep {
+ result: ContextUpdateResult::declined(decision),
+ ..Default::default()
+ })
+ };
+
+ // A step of a gesture that the contexts around the page have moved past still scrolls, as the page let it.
+ let routing_context_id = self.routing_context_of_wheel_gesture(listener_context_id, gesture_id);
+ let routing_context = routing_context_id.and_then(|id| self.context_if_present(id));
+ if routing_context.is_none_or(|context| {
+ context
+ .borrow()
+ .wheel_step_was_overtaken(step.scroll_gesture_phase, let_through.wheel_gesture_mark.step_number)
+ }) {
+ let result = listener_context
+ .borrow_mut()
+ .scroll_for_overtaken_wheel_step(&step, scroll_chain, now);
+ return answer(&self.apply_wheel_step_result(
+ listener_context_id,
+ listener_context,
+ &result,
+ page_client,
+ now,
+ ));
+ }
+ let routing_context = routing_context.unwrap();
+ let routing_context_id = routing_context_id.unwrap();
+
+ routing_context
+ .borrow_mut()
+ .set_wheel_event_listener_context(listener_context_id);
+ // The end of a gesture lets go of the scroller it stretched.
+ if step.scroll_gesture_phase == ScrollGesturePhase::Ended {
+ routing_context.borrow_mut().end_wheel_gesture_stretch(now);
+ }
+
+ // A latched scroller that the page no longer has around the target of the step is gone from the page, and the step
+ // is routed afresh.
+ let latch_is_to_scroller_of_this_page = routing_context_id == listener_context_id
+ && routing_context.borrow().nested_context_of_wheel_latch().is_none();
+ if latch_is_to_scroller_of_this_page && !scroll_chain.is_empty() {
+ let latched_scroller = routing_context.borrow().wheel_latched_scroller();
+ if let Some(latched_scroller) = latched_scroller
+ && !scroll_chain.contains(&latched_scroller)
+ {
+ routing_context.borrow_mut().forget_wheel_latch_of_gesture(gesture_id);
+ }
+ }
+
+ let has_latch = routing_context.borrow().has_wheel_latch_for_gesture(Some(gesture_id));
+ if has_latch {
+ let nested_context_id = routing_context.borrow().nested_context_of_wheel_latch();
+ if let Some(nested_context_id) = nested_context_id {
+ let nested_context = self.context_still_nested_in(routing_context_id, Some(nested_context_id));
+ let Some(nested_context) = nested_context else {
+ routing_context.borrow_mut().forget_wheel_latch_of_gesture(gesture_id);
+ return declined(InputRoutingDecision::NestedContextUnavailable);
+ };
+ if !page_may_scroll_in(nested_context, routing_context, Some(page_client), &step) {
+ return declined(InputRoutingDecision::StepExceedsInputLeftToThePage);
+ }
+ let nested_result = nested_context
+ .borrow_mut()
+ .take_latched_wheel_step_from_containing_context(
+ &step,
+ WheelStepAdmission::LetThroughByThePage,
+ now,
+ );
+ return answer(&self.apply_wheel_step_result(
+ nested_context_id,
+ nested_context,
+ &nested_result,
+ page_client,
+ now,
+ ));
+ }
+ if !page_may_scroll_in(routing_context, routing_context, Some(page_client), &step) {
+ return declined(InputRoutingDecision::StepExceedsInputLeftToThePage);
+ }
+ let result = routing_context
+ .borrow_mut()
+ .scroll_for_latched_wheel_step_the_page_let_through(&step, now);
+ if let Some(result) = result {
+ return answer(&self.apply_wheel_step_result(
+ routing_context_id,
+ routing_context,
+ &result,
+ page_client,
+ now,
+ ));
+ }
+ }
+
+ answer(&self.route_wheel_step_the_page_let_through(
+ routing_context_id,
+ routing_context,
+ listener_context_id,
+ listener_context,
+ step,
+ scroll_chain,
+ Some(page_client),
+ now,
+ ))
+ }
+
+ pub fn forget_wheel_gesture_the_page_canceled(&self, listener_context_id: CompositorContextId, gesture_id: u64) {
+ let _entered = self.enter();
+
+ let Some(listener_context) = self.context_if_present(listener_context_id) else {
+ return;
+ };
+ listener_context
+ .borrow_mut()
+ .forget_page_let_wheel_gesture_through(gesture_id);
+ // The listener scrolls by itself, so the next step of the gesture is routed afresh.
+ if let Some(routing_context_id) = self.routing_context_of_wheel_gesture(listener_context_id, gesture_id) {
+ self.context_if_present(routing_context_id)
+ .expect("routing context exists")
+ .borrow_mut()
+ .forget_wheel_latch_of_gesture(gesture_id);
+ }
+ }
+}
+
+fn scroll_request_smoothly_scrolls_for_script(scroll_request: &ScrollRequest) -> bool {
+ scroll_request
+ .smooth_scroll
+ .as_ref()
+ .is_some_and(|scroll| scroll.initiator == SmoothScrollInitiator::Programmatic)
+}
+
+impl CompositorCore {
+ pub fn apply_scroll_requests(
+ &self,
+ context_id: CompositorContextId,
+ scroll_requests: &[ScrollRequest],
+ now: MonotonicTime,
+ ) {
+ let _entered = self.enter();
+
+ let Some(context) = self.context_if_present(context_id) else {
+ return;
+ };
+
+ // A script's smooth scroll of a box ends the momentum scrolling it, as a key's does. A script's instant scroll only
+ // moves the box, and the momentum goes on from there: pages keep their content in place under a flick that way.
+ for scroll_request in scroll_requests {
+ if scroll_request.takes_over_from_momentum || scroll_request_smoothly_scrolls_for_script(scroll_request) {
+ let event = context
+ .borrow_mut()
+ .end_momentum_scrolling(scroll_request.stable_node_id);
+ self.dispatch_scroll_fling_step(context_id, context, event, now);
+ }
+ }
+ let frame_to_present = context.borrow_mut().apply_scroll_requests(scroll_requests, now);
+ if let Some(frame_to_present) = frame_to_present {
+ self.request_present(context_id, &frame_to_present);
+ }
+ context.borrow_mut().request_display_ticks_if_needed(now);
+ self.publish_pending_async_scroll_updates(context_id, context);
+ }
+
+ pub fn take_pending_async_scroll_updates(&self, context_id: CompositorContextId) -> PendingAsyncScrollUpdates {
+ let _entered = self.enter();
+
+ let context = self.context_if_present(context_id).expect("context exists");
+
+ context.borrow_mut().take_pending_async_scroll_updates()
+ }
+}
diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rs
index 1e5518301ad..03f9f76feee 100644
--- a/Services/Compositor/Rust/src/lib.rs
+++ b/Services/Compositor/Rust/src/lib.rs
@@ -18,6 +18,7 @@ mod rust_panic;
pub mod async_scroll_update_outbox;
pub mod context_scene;
pub mod context_state;
+pub mod core;
pub mod elastic_overscroll_controller;
pub mod frame_inputs;
pub mod host;