Skip to main content

script/dom/document/
document_event_handler.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::array::from_ref;
6use std::cell::Cell;
7use std::f64::consts::PI;
8use std::mem;
9use std::time::{Duration, Instant};
10
11use embedder_traits::{
12    Cursor, EditingAction, EmbedderMsg, ImeEvent, InputEvent, InputEventId, InputEventOutcome,
13    InputEventResult, KeyboardEvent as EmbedderKeyboardEvent, MouseButton, MouseButtonAction,
14    MouseButtonEvent, MouseLeftViewportEvent, MouseMoveEvent, TouchEvent as EmbedderTouchEvent,
15    TouchEventType, TouchId, TouchPointerType, UntrustedNodeAddress,
16    WheelEvent as EmbedderWheelEvent,
17};
18#[cfg(feature = "gamepad")]
19use embedder_traits::{
20    GamepadEvent as EmbedderGamepadEvent, GamepadSupportedHapticEffects, GamepadUpdateType,
21};
22use euclid::{Point2D, Vector2D};
23use js::context::{JSContext, NoGC};
24use keyboard_types::{
25    Code, CompositionState, Key, KeyState, KeyboardEvent as KeyboardTypesEvent, Modifiers, NamedKey,
26};
27use layout_api::{HitTestFlags, ScrollContainerQueryFlags, node_id_from_scroll_id};
28use rustc_hash::FxHashMap;
29use script_bindings::cell::DomRefCell;
30use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
31use script_bindings::codegen::GenericBindings::ElementBinding::ScrollLogicalPosition;
32use script_bindings::codegen::GenericBindings::EventBinding::EventMethods;
33#[cfg(feature = "gamepad")]
34use script_bindings::codegen::GenericBindings::GamepadBinding::GamepadMappingType;
35use script_bindings::codegen::GenericBindings::HTMLElementBinding::HTMLElementMethods;
36use script_bindings::codegen::GenericBindings::HTMLLabelElementBinding::HTMLLabelElementMethods;
37use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
38use script_bindings::codegen::GenericBindings::TouchBinding::TouchMethods;
39use script_bindings::codegen::GenericBindings::WindowBinding::{ScrollBehavior, WindowMethods};
40use script_bindings::inheritance::Castable;
41use script_bindings::num::Finite;
42use script_bindings::root::{Dom, DomRoot, DomSlice};
43use script_bindings::str::DOMString;
44use script_traits::{ConstellationInputEvent, MouseButtons};
45use servo_config::pref;
46use servo_constellation_traits::{
47    KeyboardScroll, LoadData, NavigationHistoryBehavior, ScriptToConstellationMessage,
48};
49use servo_url::ServoUrl;
50use style::Atom;
51use style_traits::CSSPixel;
52use webrender_api::ExternalScrollId;
53
54#[cfg(feature = "gamepad")]
55use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionName;
56use crate::dom::bindings::inheritance::{ElementTypeId, HTMLElementTypeId, NodeTypeId};
57use crate::dom::bindings::refcounted::Trusted;
58use crate::dom::bindings::root::MutNullableDom;
59use crate::dom::bindings::trace::NoTrace;
60use crate::dom::document::FireMouseEventType;
61use crate::dom::document::editing::{
62    editing_action_from_composition_event, editing_action_from_keyboard_event,
63};
64use crate::dom::document::focus::FocusableArea;
65use crate::dom::document::interactive_element_command::InteractiveElementCommand;
66use crate::dom::event::{EventBubbles, EventCancelable, EventComposed, EventFlags};
67#[cfg(feature = "gamepad")]
68use crate::dom::gamepad::gamepad::{Gamepad, contains_user_gesture};
69#[cfg(feature = "gamepad")]
70use crate::dom::gamepad::gamepadevent::GamepadEventType;
71use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
72use crate::dom::html::htmldialogelement::HTMLDialogElement;
73use crate::dom::inputevent::HitTestResult;
74use crate::dom::iterators::ShadowIncluding;
75use crate::dom::keyboardevent::KeyboardEvent;
76use crate::dom::links::htmlhyperlinkelementutils::HyperlinkElementTraits;
77use crate::dom::node::focus::FocusTrigger;
78use crate::dom::node::{self, Node, NodeTraits};
79use crate::dom::pointerevent::{PointerEvent, PointerId};
80use crate::dom::types::{
81    CompositionEvent, Element, Event, EventTarget, GlobalScope, HTMLAnchorElement, HTMLAreaElement,
82    HTMLElement, HTMLLabelElement, MouseEvent, Touch, TouchEvent, TouchList, WheelEvent, Window,
83};
84use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollRequirement, ScrollingBoxAxis};
85use crate::dom::window::windowproxy::WindowOpenType;
86use crate::drag::drag_gesture::DragGesture;
87use crate::navigation::navigate;
88use crate::realms::enter_auto_realm;
89
90/// A data structure used for tracking the state of a particular mouse button's clicks.
91/// This is used to determine when to fire click events and for click counting. Click
92/// counts can be reset to 0 if a mouse button event happens at a sufficient distance or
93/// time from the previous one.
94///
95/// From <https://w3c.github.io/uievents/#current-click-count>:
96/// > Implementations MUST maintain the current click count when generating mouse
97/// > events. This MUST be a non-negative integer indicating the number of consecutive
98/// > clicks of a pointing device button within a specific time. The delay after which
99/// > the count resets is specific to the environment configuration.
100#[derive(Default, JSTraceable, MallocSizeOf)]
101struct ButtonClickState {
102    #[no_trace]
103    down_point: Option<Point2D<f32, CSSPixel>>,
104    last_click_time: Option<Instant>,
105    #[no_trace]
106    last_click_point: Option<Point2D<f32, CSSPixel>>,
107    click_count: usize,
108}
109
110impl ButtonClickState {
111    fn reset_click_count(&mut self) {
112        self.click_count = 0;
113        self.last_click_time = None;
114        self.last_click_point = None;
115    }
116
117    fn increment_click_count(&mut self, point: Point2D<f32, CSSPixel>) -> usize {
118        self.last_click_time = Some(Instant::now());
119        self.last_click_point = Some(point);
120        self.click_count += 1;
121        self.click_count
122    }
123}
124
125#[derive(Default, JSTraceable, MallocSizeOf)]
126struct MouseClickTracker {
127    state: FxHashMap<NoTrace<MouseButton>, ButtonClickState>,
128}
129
130impl MouseClickTracker {
131    fn on_mouse_down(&mut self, button: MouseButton, point_in_frame: Point2D<f32, CSSPixel>) {
132        for (state_button, state) in &mut self.state {
133            if state_button.0 != button {
134                state.reset_click_count();
135            }
136        }
137
138        let state = self.state.entry(NoTrace(button)).or_default();
139        state.down_point = Some(point_in_frame);
140
141        let (Some(previous_point), Some(previous_time)) =
142            (state.last_click_point, state.last_click_time)
143        else {
144            return;
145        };
146
147        let double_click_timeout =
148            Duration::from_millis(pref!(dom_document_dblclick_timeout) as u64);
149        let double_click_distance_threshold = pref!(dom_document_dblclick_dist) as u64;
150
151        // Calculate distance between this click and the previous click.
152        let line = point_in_frame - previous_point;
153        let distance = (line.dot(line) as f64).sqrt();
154        if Instant::now().duration_since(previous_time) > double_click_timeout ||
155            distance > double_click_distance_threshold as f64
156        {
157            state.reset_click_count();
158        }
159    }
160
161    fn on_mouse_up(
162        &mut self,
163        button: MouseButton,
164        point_in_frame: Point2D<f32, CSSPixel>,
165    ) -> usize {
166        self.state
167            .entry(NoTrace(button))
168            .or_default()
169            .increment_click_count(point_in_frame)
170    }
171
172    fn click_count_for(&self, button: MouseButton) -> usize {
173        self.state
174            .get(&NoTrace(button))
175            .map_or(0, |state| state.click_count)
176    }
177
178    fn take_last_mouse_button_down_point(
179        &mut self,
180        mouse_button: MouseButton,
181    ) -> Option<Point2D<f32, CSSPixel>> {
182        self.state
183            .get_mut(&NoTrace(mouse_button))
184            .and_then(|state| state.down_point.take())
185    }
186
187    fn reset_all(&mut self) {
188        for state in self.state.values_mut() {
189            state.reset_click_count();
190        }
191    }
192}
193
194/// The [`DocumentEventHandler`] is a structure responsible for handling input events for
195/// the [`crate::Document`] and storing data related to event handling. It exists to
196/// decrease the size of the [`crate::Document`] structure.
197#[derive(JSTraceable, MallocSizeOf)]
198#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
199pub(crate) struct DocumentEventHandler {
200    /// The [`Window`] element for this [`DocumentEventHandler`].
201    window: Dom<Window>,
202    /// Pending input events, to be handled at the next rendering opportunity.
203    #[no_trace]
204    pending_input_events: DomRefCell<Vec<ConstellationInputEvent>>,
205    /// The index of the last mouse move event in the pending input events queue.
206    mouse_move_event_index: DomRefCell<Option<usize>>,
207    /// The [`InputEventId`]s of mousemove events that have been coalesced.
208    #[no_trace]
209    coalesced_mouse_move_event_ids: DomRefCell<Vec<InputEventId>>,
210    /// The index of the last wheel event in the pending input events queue.
211    /// This is non-standard behaviour.
212    /// According to <https://www.w3.org/TR/pointerevents/#dfn-coalesced-events>,
213    /// we should only coalesce `pointermove` events.
214    wheel_event_index: DomRefCell<Option<usize>>,
215    /// The [`InputEventId`]s of wheel events that have been coalesced.
216    #[no_trace]
217    coalesced_wheel_event_ids: DomRefCell<Vec<InputEventId>>,
218    /// State that is stored to track and count clicks per-mouse button.
219    button_click_state: DomRefCell<MouseClickTracker>,
220    /// The current button state of the mouse. This is used to ensure that
221    /// `pointerup` and `pointerdown` events are only sent when transitioning from
222    /// having no mouse buttons pressed to having any and vice-versa.
223    #[no_trace]
224    mouse_button_state: Cell<MouseButtons>,
225    /// The element that is currently hovered by the cursor.
226    current_hover_target: MutNullableDom<Element>,
227    /// The element that was most recently activated during a mouse button press or touch
228    /// event.
229    current_active_element: MutNullableDom<Element>,
230    /// The element that was most recently clicked.
231    most_recently_clicked_element: MutNullableDom<Element>,
232    /// The most recent mouse movement point, used for processing `mouseleave` events.
233    #[no_trace]
234    most_recent_mousemove_point: Cell<Option<Point2D<f32, CSSPixel>>>,
235    /// The currently set [`Cursor`] or `None` if the `Document` isn't being hovered
236    /// by the cursor.
237    #[no_trace]
238    current_cursor: Cell<Option<Cursor>>,
239    /// <http://w3c.github.io/touch-events/#dfn-active-touch-point>
240    active_touch_points: DomRefCell<Vec<Dom<Touch>>>,
241    /// Whether the current touch sequence may still generate compatibility mouse events.
242    touch_sequence_click_allowed: Cell<bool>,
243    /// The active keyboard modifiers for the WebView. This is updated when receiving any input event.
244    #[no_trace]
245    active_keyboard_modifiers: Cell<Modifiers>,
246    /// Map from touch identifier to pointer ID for active touch points
247    active_pointer_ids: DomRefCell<FxHashMap<i32, i32>>,
248    /// Counter for generating unique pointer IDs for touch inputs
249    next_touch_pointer_id: Cell<i32>,
250    /// A map holding information about currently registered access key handlers.
251    access_key_handlers: DomRefCell<FxHashMap<NoTrace<Code>, Dom<HTMLElement>>>,
252    /// Map from pointer ID to pending pointer capture target override element.
253    /// This is set by setPointerCapture and cleared by releasePointerCapture.
254    /// <https://w3c.github.io/pointerevents/#pointer-capture>
255    pending_pointer_capture: DomRefCell<FxHashMap<i32, Dom<Element>>>,
256    /// Map from pointer ID to the actual/current pointer capture target.
257    /// Updated during process_pending_pointer_capture when events are dispatched.
258    pointer_capture_target: DomRefCell<FxHashMap<i32, Dom<Element>>>,
259    /// The current drag gesture, if one exists. Events that affect this drag
260    /// gesture will be forwarded to it.
261    drag_gesture: DomRefCell<Option<DragGesture>>,
262}
263
264impl DocumentEventHandler {
265    pub(crate) fn new(window: &Window) -> Self {
266        Self {
267            window: Dom::from_ref(window),
268            pending_input_events: Default::default(),
269            mouse_move_event_index: Default::default(),
270            coalesced_mouse_move_event_ids: Default::default(),
271            wheel_event_index: Default::default(),
272            coalesced_wheel_event_ids: Default::default(),
273            button_click_state: Default::default(),
274            mouse_button_state: Cell::new(MouseButtons::empty()),
275            current_hover_target: Default::default(),
276            current_active_element: Default::default(),
277            most_recently_clicked_element: Default::default(),
278            most_recent_mousemove_point: Default::default(),
279            current_cursor: Default::default(),
280            active_touch_points: Default::default(),
281            touch_sequence_click_allowed: Cell::new(true),
282            active_keyboard_modifiers: Default::default(),
283            active_pointer_ids: Default::default(),
284            next_touch_pointer_id: Cell::new(1),
285            access_key_handlers: Default::default(),
286            pending_pointer_capture: Default::default(),
287            pointer_capture_target: Default::default(),
288            drag_gesture: Default::default(),
289        }
290    }
291
292    /// Note a pending input event, to be processed at the next `update_the_rendering` task.
293    pub(crate) fn note_pending_input_event(&self, event: ConstellationInputEvent) {
294        let mut pending_input_events = self.pending_input_events.borrow_mut();
295        if matches!(event.event.event, InputEvent::MouseMove(..)) {
296            // First try to replace any existing mouse move event.
297            if let Some(mouse_move_event) = self
298                .mouse_move_event_index
299                .borrow()
300                .and_then(|index| pending_input_events.get_mut(index))
301            {
302                self.coalesced_mouse_move_event_ids
303                    .borrow_mut()
304                    .push(mouse_move_event.event.id);
305                *mouse_move_event = event;
306                return;
307            }
308
309            *self.mouse_move_event_index.borrow_mut() = Some(pending_input_events.len());
310        }
311
312        if let InputEvent::Wheel(ref new_wheel_event) = event.event.event {
313            // Coalesce with any existing pending wheel event by summing deltas.
314            if let Some(existing_constellation_wheel_event) = self
315                .wheel_event_index
316                .borrow()
317                .and_then(|index| pending_input_events.get_mut(index)) &&
318                let InputEvent::Wheel(ref mut existing_wheel_event) =
319                    existing_constellation_wheel_event.event.event &&
320                existing_wheel_event.delta.mode == new_wheel_event.delta.mode
321            {
322                self.coalesced_wheel_event_ids
323                    .borrow_mut()
324                    .push(existing_constellation_wheel_event.event.id);
325                existing_wheel_event.delta.x += new_wheel_event.delta.x;
326                existing_wheel_event.delta.y += new_wheel_event.delta.y;
327                existing_wheel_event.delta.z += new_wheel_event.delta.z;
328                existing_wheel_event.point = new_wheel_event.point;
329                existing_constellation_wheel_event.event.id = event.event.id;
330                return;
331            }
332
333            *self.wheel_event_index.borrow_mut() = Some(pending_input_events.len());
334        }
335
336        pending_input_events.push(event);
337    }
338
339    /// Whether or not this [`Document`] has any pending input events to be processed during
340    /// "update the rendering."
341    pub(crate) fn has_pending_input_events(&self) -> bool {
342        !self.pending_input_events.borrow().is_empty()
343    }
344
345    pub(crate) fn alternate_action_keyboard_modifier_active(&self) -> bool {
346        #[cfg(target_os = "macos")]
347        {
348            self.active_keyboard_modifiers
349                .get()
350                .contains(Modifiers::META)
351        }
352        #[cfg(not(target_os = "macos"))]
353        {
354            self.active_keyboard_modifiers
355                .get()
356                .contains(Modifiers::CONTROL)
357        }
358    }
359
360    pub(crate) fn handle_pending_input_events(&self, cx: &mut JSContext) {
361        debug_assert!(
362            !self.pending_input_events.borrow().is_empty(),
363            "handle_pending_input_events called with no events"
364        );
365        let mut realm = enter_auto_realm(cx, &*self.window);
366        let cx = &mut realm.current_realm();
367
368        // Reset the mouse and wheel event indices.
369        *self.mouse_move_event_index.safe_borrow_mut(cx.no_gc()) = None;
370        *self.wheel_event_index.safe_borrow_mut(cx.no_gc()) = None;
371        let pending_input_events =
372            mem::take(&mut *self.pending_input_events.safe_borrow_mut(cx.no_gc()));
373        let mut coalesced_mouse_move_event_ids = mem::take(
374            &mut *self
375                .coalesced_mouse_move_event_ids
376                .safe_borrow_mut(cx.no_gc()),
377        );
378        let mut coalesced_wheel_event_ids =
379            mem::take(&mut *self.coalesced_wheel_event_ids.safe_borrow_mut(cx.no_gc()));
380
381        let mut input_event_outcomes = Vec::with_capacity(
382            pending_input_events.len() +
383                coalesced_mouse_move_event_ids.len() +
384                coalesced_wheel_event_ids.len(),
385        );
386        // TODO: For some of these we still aren't properly calculating whether or not
387        // the event was handled or if `preventDefault()` was called on it. Each of
388        // these cases needs to be examined and some of them either fire more than one
389        // event or fire events later. We have to make a good decision about what to
390        // return to the embedder when that happens.
391        for event in pending_input_events {
392            self.active_keyboard_modifiers
393                .set(event.active_keyboard_modifiers);
394            let result = match event.event.event {
395                InputEvent::MouseButton(mouse_button_event) => {
396                    self.handle_native_mouse_button_event(cx, mouse_button_event, &event);
397                    InputEventResult::default()
398                },
399                InputEvent::MouseMove(_) => {
400                    self.handle_native_mouse_move_event(cx, &event);
401                    input_event_outcomes.extend(
402                        mem::take(&mut coalesced_mouse_move_event_ids)
403                            .into_iter()
404                            .map(|id| InputEventOutcome {
405                                id,
406                                result: InputEventResult::default(),
407                            }),
408                    );
409                    InputEventResult::default()
410                },
411                InputEvent::MouseLeftViewport(mouse_leave_event) => {
412                    self.handle_mouse_left_viewport_event(cx, &event, &mouse_leave_event);
413                    InputEventResult::default()
414                },
415                InputEvent::Touch(touch_event) => self.handle_touch_event(cx, touch_event, &event),
416                InputEvent::Wheel(wheel_event) => {
417                    let result = self.handle_wheel_event(cx, wheel_event, &event);
418                    input_event_outcomes.extend(
419                        mem::take(&mut coalesced_wheel_event_ids)
420                            .into_iter()
421                            .map(|id| InputEventOutcome { id, result }),
422                    );
423                    result
424                },
425                InputEvent::Keyboard(keyboard_event) => {
426                    self.handle_keyboard_event(cx, keyboard_event)
427                },
428                InputEvent::Ime(ime_event) => self.handle_ime_event(cx, ime_event),
429                #[cfg(feature = "gamepad")]
430                InputEvent::Gamepad(gamepad_event) => {
431                    self.handle_gamepad_event(gamepad_event);
432                    InputEventResult::default()
433                },
434                InputEvent::EditingAction(clipboard_action) => {
435                    let document = self.window.Document();
436                    let focused_node = document
437                        .focus_handler()
438                        .focused_area()
439                        .dom_anchor(&document);
440                    let editing_context = document.editing_context(cx.no_gc(), &focused_node);
441                    document.handle_clipboard_action(cx, &editing_context, clipboard_action)
442                },
443            };
444
445            input_event_outcomes.push(InputEventOutcome {
446                id: event.event.id,
447                result,
448            });
449        }
450
451        self.notify_embedder_that_events_were_handled(input_event_outcomes);
452    }
453
454    fn notify_embedder_that_events_were_handled(
455        &self,
456        input_event_outcomes: Vec<InputEventOutcome>,
457    ) {
458        // Wait to to notify the embedder that the event was handled until all pending DOM
459        // event processing is finished.
460        let trusted_window = Trusted::new(&*self.window);
461        self.window
462            .as_global_scope()
463            .task_manager()
464            .dom_manipulation_task_source()
465            .queue_unconditionally(task!(notify_webdriver_input_event_completed: move || {
466                let window = trusted_window.root();
467                window.send_to_embedder(
468                    EmbedderMsg::InputEventsHandled(window.webview_id(), input_event_outcomes));
469            }));
470    }
471
472    /// When an event should be fired on the element that has focus, this returns the target. If
473    /// there is no associated element with the focused area (such as when the viewport is focused),
474    /// then the body is returned. If no body is returned then the `Window` is returned.
475    ///
476    /// From <https://w3c.github.io/uievents/#events-keyboard-event-order>:
477    /// > The event target of a key event is the currently focused element which is
478    /// > processing the keyboard activity. This is often an HTML input element or a textual
479    /// > element which is editable, but MAY be an element defined by the host language to
480    /// > accept keyboard input for non-text purposes, such as the activation of an
481    /// > accelerator key or trigger of some other behavior. If no suitable element is in
482    /// > focus, the event target will be the HTML body element if available, otherwise the
483    /// > root element.
484    pub(crate) fn target_for_events_following_focus(&self) -> DomRoot<EventTarget> {
485        let document = self.window.Document();
486        match &*document.focus_handler().focused_area() {
487            FocusableArea::Node { node, .. } => DomRoot::from_ref(node.upcast()),
488            FocusableArea::IFrameViewport { iframe_element, .. } => {
489                DomRoot::from_ref(iframe_element.upcast())
490            },
491            FocusableArea::Viewport => document
492                .GetBody()
493                .map(DomRoot::upcast)
494                .or_else(|| document.GetDocumentElement().map(DomRoot::upcast))
495                .unwrap_or_else(|| DomRoot::from_ref(self.window.upcast())),
496        }
497    }
498
499    pub(crate) fn set_cursor(&self, cursor: Option<Cursor>) {
500        if cursor == self.current_cursor.get() {
501            return;
502        }
503        self.current_cursor.set(cursor);
504        self.window.send_to_embedder(EmbedderMsg::SetCursor(
505            self.window.webview_id(),
506            cursor.unwrap_or_default(),
507        ));
508    }
509
510    fn handle_mouse_left_viewport_event(
511        &self,
512        cx: &mut JSContext,
513        input_event: &ConstellationInputEvent,
514        mouse_leave_event: &MouseLeftViewportEvent,
515    ) {
516        if let Some(current_hover_target) = self.current_hover_target.get() {
517            let current_hover_target = current_hover_target.upcast::<Node>();
518            for element in current_hover_target
519                .inclusive_ancestors(ShadowIncluding::Yes)
520                .filter_map(DomRoot::downcast::<Element>)
521            {
522                element.set_hover_state(cx.no_gc(), false);
523            }
524
525            if let Some(hit_test_result) =
526                self.most_recent_mousemove_point.get().and_then(|point| {
527                    self.window
528                        .hit_test_from_point_in_viewport(cx, HitTestFlags::empty(), point)
529                })
530            {
531                let mouse_out_event = MouseEvent::new_for_platform_motion_event(
532                    cx,
533                    &self.window,
534                    FireMouseEventType::Out,
535                    &hit_test_result,
536                    input_event,
537                );
538
539                // Fire pointerout before mouseout
540                mouse_out_event
541                    .to_pointer_hover_event(cx, "pointerout")
542                    .upcast::<Event>()
543                    .fire(cx, current_hover_target.upcast());
544
545                mouse_out_event
546                    .upcast::<Event>()
547                    .fire(cx, current_hover_target.upcast());
548
549                self.handle_mouse_enter_leave_event(
550                    cx,
551                    current_hover_target,
552                    None,
553                    FireMouseEventType::Leave,
554                    &hit_test_result,
555                    input_event,
556                );
557            }
558        }
559
560        // We do not want to always inform the embedder that cursor has been set to the
561        // default cursor, in order to avoid a timing issue when moving between `<iframe>`
562        // elements. There is currently no way to control which `SetCursor` message will
563        // reach the embedder first. This is safer when leaving the `WebView` entirely.
564        if !mouse_leave_event.focus_moving_to_another_iframe {
565            // If focus is moving to another frame, it will decide what the new status
566            // text is, but if this mouse leave event is leaving the WebView entirely,
567            // then clear it.
568            self.window
569                .send_to_embedder(EmbedderMsg::Status(self.window.webview_id(), None));
570            self.set_cursor(None);
571        } else {
572            self.current_cursor.set(None);
573        }
574
575        self.current_hover_target.set(None);
576        self.most_recent_mousemove_point.set(None);
577    }
578
579    fn handle_mouse_enter_leave_event(
580        &self,
581        cx: &mut JSContext,
582        event_target: &Node,
583        related_target: Option<&Node>,
584        event_type: FireMouseEventType,
585        hit_test_result: &HitTestResult,
586        input_event: &ConstellationInputEvent,
587    ) {
588        assert!(matches!(
589            event_type,
590            FireMouseEventType::Enter | FireMouseEventType::Leave
591        ));
592
593        let is_compatibility_event_for_touch = input_event.is_compatibility_event_for_touch();
594
595        let common_ancestor = match related_target.as_ref() {
596            Some(related_target) => event_target
597                .common_ancestor_in_flat_tree(cx.no_gc(), related_target)
598                .unwrap_or_else(|| DomRoot::from_ref(event_target)),
599            None => DomRoot::from_ref(event_target),
600        };
601
602        // We need to create a target chain in case the event target shares
603        // its boundaries with its ancestors.
604        let mut targets: Vec<_> = event_target
605            .inclusive_ancestors_in_flat_tree_unrooted(cx.no_gc())
606            .take_while(|node| *node != *common_ancestor)
607            .map(|node| node.as_rooted())
608            .collect();
609
610        // The order for dispatching mouseenter/pointerenter events starts from the topmost
611        // common ancestor of the event target and the related target.
612        if event_type == FireMouseEventType::Enter {
613            targets.reverse();
614        }
615
616        let pointer_event_name = match event_type {
617            FireMouseEventType::Enter => "pointerenter",
618            FireMouseEventType::Leave => "pointerleave",
619            _ => unreachable!(),
620        };
621
622        for target in targets {
623            let mouse_event = MouseEvent::new_for_platform_motion_event(
624                cx,
625                &self.window,
626                event_type,
627                hit_test_result,
628                input_event,
629            );
630            mouse_event
631                .upcast::<Event>()
632                .set_related_target(related_target.as_ref().map(|target| target.upcast()));
633
634            // Fire pointer event before mouse event
635            if !is_compatibility_event_for_touch {
636                mouse_event
637                    .to_pointer_hover_event(cx, pointer_event_name)
638                    .upcast::<Event>()
639                    .fire(cx, target.upcast());
640            }
641
642            // Fire mouse event
643            mouse_event.upcast::<Event>().fire(cx, target.upcast());
644        }
645    }
646
647    /// <https://w3c.github.io/uievents/#handle-native-mouse-move>
648    fn handle_native_mouse_move_event(
649        &self,
650        cx: &mut JSContext,
651        input_event: &ConstellationInputEvent,
652    ) {
653        let is_compatibility_event_for_touch = input_event.is_compatibility_event_for_touch();
654
655        // First check if the capture target is disconnected and release it if so.
656        // This must happen before any pointer event fires.
657        let pointer_id = PointerId::Mouse as i32;
658        let released_disconnected = !is_compatibility_event_for_touch &&
659            self.release_disconnected_pointer_capture(cx, pointer_id, "mouse", true);
660
661        let hit_test_flags = if self
662            .drag_gesture
663            .borrow()
664            .as_ref()
665            .is_some_and(DragGesture::need_dom_position_from_hit_test)
666        {
667            HitTestFlags::IncludeDomPosition
668        } else {
669            HitTestFlags::empty()
670        };
671
672        // Always do full hit test so we can keep `current_hover_target` in sync
673        // with the actual element under the pointer. Boundary events for hover
674        // transitions are suppressed while pointer capture is active: per spec,
675        // pointer events are retargeted to the capture element.
676        let Some(hit_test_result) =
677            self.window
678                .hit_test_from_input_event(cx, hit_test_flags, input_event)
679        else {
680            return;
681        };
682
683        {
684            let mut maybe_drag_gesture = self.drag_gesture.borrow_mut();
685            if maybe_drag_gesture.as_mut().is_some_and(|drag_gesture| {
686                !drag_gesture.handle_mouse_move_event(cx, input_event, &hit_test_result)
687            }) {
688                *maybe_drag_gesture = None;
689            }
690        }
691
692        let old_mouse_move_point = self
693            .most_recent_mousemove_point
694            .replace(Some(hit_test_result.point_in_frame));
695        // Always dispatch compatibility `mousemove` events, even at the same
696        // point as the previous one.
697        if !is_compatibility_event_for_touch &&
698            old_mouse_move_point == Some(hit_test_result.point_in_frame)
699        {
700            return;
701        }
702
703        // Update the cursor when the mouse moves, if it has changed.
704        self.set_cursor(Some(hit_test_result.cursor));
705
706        let Some(new_target) = hit_test_result
707            .node
708            .inclusive_ancestors(ShadowIncluding::Yes)
709            .find_map(DomRoot::downcast::<Element>)
710        else {
711            return;
712        };
713
714        let capture_is_active = !is_compatibility_event_for_touch &&
715            self.get_pointer_capture_target(pointer_id).is_some();
716        let old_hover_target = self.current_hover_target.get();
717        let target_has_changed = old_hover_target
718            .as_ref()
719            .is_none_or(|old_target| *old_target != new_target);
720
721        // Here we know the target has changed, so we must update the state,
722        // dispatch mouseout to the previous one, mouseover to the new one.
723        if target_has_changed {
724            // Dispatch pointerout/mouseout and pointerleave/mouseleave to previous target.
725            if let Some(old_target) = self.current_hover_target.get() {
726                let old_target_is_ancestor_of_new_target = old_target
727                    .upcast::<Node>()
728                    .is_ancestor_of(new_target.upcast::<Node>());
729
730                // If the old target is an ancestor of the new target, this can be skipped
731                // completely, since the node's hover state will be reset below.
732                if !old_target_is_ancestor_of_new_target {
733                    for element in old_target
734                        .upcast::<Node>()
735                        .inclusive_ancestors(ShadowIncluding::Yes)
736                        .filter_map(DomRoot::downcast::<Element>)
737                    {
738                        element.set_hover_state(cx.no_gc(), false);
739                    }
740                }
741
742                if !capture_is_active {
743                    let mouse_out_event = MouseEvent::new_for_platform_motion_event(
744                        cx,
745                        &self.window,
746                        FireMouseEventType::Out,
747                        &hit_test_result,
748                        input_event,
749                    );
750                    mouse_out_event
751                        .upcast::<Event>()
752                        .set_related_target(Some(new_target.upcast()));
753
754                    // Fire pointerout before mouseout
755                    if !is_compatibility_event_for_touch {
756                        mouse_out_event
757                            .to_pointer_hover_event(cx, "pointerout")
758                            .upcast::<Event>()
759                            .fire(cx, old_target.upcast());
760                    }
761
762                    mouse_out_event
763                        .upcast::<Event>()
764                        .fire(cx, old_target.upcast());
765
766                    if !old_target_is_ancestor_of_new_target {
767                        let event_target = old_target.upcast::<Node>();
768                        let moving_into = Some(new_target.upcast::<Node>());
769                        self.handle_mouse_enter_leave_event(
770                            cx,
771                            event_target,
772                            moving_into,
773                            FireMouseEventType::Leave,
774                            &hit_test_result,
775                            input_event,
776                        );
777                    }
778                }
779            }
780
781            // Dispatch pointerover/mouseover and pointerenter/mouseenter to new target.
782            for element in new_target
783                .upcast::<Node>()
784                .inclusive_ancestors(ShadowIncluding::Yes)
785                .filter_map(DomRoot::downcast::<Element>)
786            {
787                element.set_hover_state(cx.no_gc(), true);
788            }
789
790            if !capture_is_active {
791                let mouse_over_event = MouseEvent::new_for_platform_motion_event(
792                    cx,
793                    &self.window,
794                    FireMouseEventType::Over,
795                    &hit_test_result,
796                    input_event,
797                );
798                mouse_over_event
799                    .upcast::<Event>()
800                    .set_related_target(old_hover_target.as_ref().map(|target| target.upcast()));
801
802                // Fire pointerover before mouseover
803                if !is_compatibility_event_for_touch {
804                    mouse_over_event
805                        .to_pointer_hover_event(cx, "pointerover")
806                        .upcast::<Event>()
807                        .dispatch(cx, new_target.upcast(), false);
808                }
809
810                mouse_over_event
811                    .upcast::<Event>()
812                    .dispatch(cx, new_target.upcast(), false);
813
814                let moving_from = old_hover_target
815                    .as_ref()
816                    .map(|old_target| old_target.upcast::<Node>());
817                let event_target = new_target.upcast::<Node>();
818                self.handle_mouse_enter_leave_event(
819                    cx,
820                    event_target,
821                    moving_from,
822                    FireMouseEventType::Enter,
823                    &hit_test_result,
824                    input_event,
825                );
826            }
827        }
828
829        // Send mousemove event to topmost target, unless it's an iframe, in which case
830        // `Paint` should have also sent an event to the inner document.
831        let mouse_event = MouseEvent::new_for_platform_motion_event(
832            cx,
833            &self.window,
834            FireMouseEventType::Move,
835            &hit_test_result,
836            input_event,
837        );
838
839        // Send pointermove event before mousemove.
840        // If pointer capture is active, retarget the pointer/mouse events to
841        // the capture element. Boundary events (pointerover/out/enter/leave)
842        // already fired above use the actual hit-test target. Compatibility
843        // events for touch ignore any capture set by the real mouse.
844        let pointer_target = if is_compatibility_event_for_touch {
845            None
846        } else {
847            self.get_pointer_capture_target(pointer_id)
848        }
849        .map(DomRoot::upcast::<EventTarget>)
850        .unwrap_or_else(|| DomRoot::from_ref(new_target.upcast::<EventTarget>()));
851
852        if !is_compatibility_event_for_touch {
853            let pointer_event = mouse_event.to_pointer_event(cx, Atom::from("pointermove"));
854            pointer_event.upcast::<Event>().set_composed(true);
855            pointer_event.upcast::<Event>().fire(cx, &pointer_target);
856
857            // Process pending pointer capture after firing event, but skip if we just
858            // released a disconnected capture to avoid immediately re-capturing.
859            // https://w3c.github.io/pointerevents/#process-pending-pointer-capture
860            if !released_disconnected {
861                self.process_pending_pointer_capture(cx, pointer_id, "mouse", true);
862            }
863        }
864
865        // Send mousemove event. Routed to the capture target when capture is active.
866        mouse_event.upcast::<Event>().fire(cx, &pointer_target);
867
868        self.update_current_hover_target_and_status(Some(new_target));
869    }
870
871    fn update_current_hover_target_and_status(&self, new_hover_target: Option<DomRoot<Element>>) {
872        let current_hover_target = self.current_hover_target.get();
873        if current_hover_target == new_hover_target {
874            return;
875        }
876
877        let previous_hover_target = self.current_hover_target.get();
878        self.current_hover_target.set(new_hover_target.as_deref());
879
880        // If the new hover target is an anchor with a status value, inform the embedder
881        // of the new value.
882        if let Some(target) = self.current_hover_target.get() &&
883            let Some(anchor) = target
884                .upcast::<Node>()
885                .inclusive_ancestors(ShadowIncluding::Yes)
886                .find_map(DomRoot::downcast::<HTMLAnchorElement>)
887        {
888            let status = anchor
889                .full_href_url_for_user_interface()
890                .map(|url| url.to_string());
891            self.window
892                .send_to_embedder(EmbedderMsg::Status(self.window.webview_id(), status));
893            return;
894        }
895
896        // No state was set above, which means that the new value of the status in the embedder
897        // should be `None`. Set that now. If `previous_hover_target` is `None` that means this
898        // is the first mouse move event we are seeing after getting the cursor. In that case,
899        // we also clear the status.
900        if previous_hover_target.is_none_or(|previous_hover_target| {
901            previous_hover_target
902                .upcast::<Node>()
903                .inclusive_ancestors(ShadowIncluding::Yes)
904                .any(|node| node.is::<HTMLAnchorElement>())
905        }) {
906            self.window
907                .send_to_embedder(EmbedderMsg::Status(self.window.webview_id(), None));
908        }
909    }
910
911    pub(crate) fn handle_refresh_cursor(&self, cx: &mut JSContext) {
912        let Some(most_recent_mousemove_point) = self.most_recent_mousemove_point.get() else {
913            return;
914        };
915
916        let Some(hit_test_result) = self.window.hit_test_from_point_in_viewport(
917            cx,
918            HitTestFlags::empty(),
919            most_recent_mousemove_point,
920        ) else {
921            return;
922        };
923
924        self.set_cursor(Some(hit_test_result.cursor));
925    }
926
927    fn set_active_element(&self, no_gc: &NoGC, original_target: &Element) {
928        let find_element_for_activation = |element: &Element| {
929            let node: &Node = element.upcast();
930            if node.is_in_ua_widget() &&
931                let Some(containing_shadow_root) = node.containing_shadow_root()
932            {
933                return containing_shadow_root.Host();
934            }
935
936            // If the element is a label, the activable element is the control element.
937            if node.type_id() ==
938                NodeTypeId::Element(ElementTypeId::HTMLElement(
939                    HTMLElementTypeId::HTMLLabelElement,
940                ))
941            {
942                let label = element.downcast::<HTMLLabelElement>().unwrap();
943                if let Some(control) = label.GetControl(no_gc) {
944                    return DomRoot::from_ref(control.upcast::<Element>());
945                }
946            }
947
948            DomRoot::from_ref(element)
949        };
950        let element_for_activation = find_element_for_activation(original_target);
951
952        // This might happen if the user is alternating between different pointing devices
953        // such as two mice or a mouse and touch events. Only keep the latest activated.
954        if let Some(currently_active_element) = self.current_active_element.get() {
955            if currently_active_element == element_for_activation {
956                return;
957            }
958            self.unset_active_element(no_gc);
959        }
960
961        element_for_activation.set_active_state(no_gc, true);
962        self.current_active_element
963            .set(Some(&*element_for_activation));
964    }
965
966    fn unset_active_element(&self, no_gc: &NoGC) {
967        if let Some(active_element) = self.current_active_element.take() {
968            active_element.set_active_state(no_gc, false);
969        }
970    }
971
972    /// <https://w3c.github.io/uievents/#mouseevent-algorithms>
973    /// Handles native mouse down, mouse up, mouse click.
974    fn handle_native_mouse_button_event(
975        &self,
976        cx: &mut JSContext,
977        mouse_button_event: MouseButtonEvent,
978        input_event: &ConstellationInputEvent,
979    ) {
980        let is_compatibility_event_for_touch = input_event.is_compatibility_event_for_touch();
981
982        {
983            let mut maybe_drag_gesture = self.drag_gesture.borrow_mut();
984            if maybe_drag_gesture
985                .as_mut()
986                .is_some_and(|drag_gesture| !drag_gesture.handle_mouse_button_event(input_event))
987            {
988                *maybe_drag_gesture = None;
989            }
990        }
991
992        let flags = if input_event.primary_button_is_pressed() ||
993            input_event.auxiliary_button_is_pressed()
994        {
995            HitTestFlags::IncludeDomPosition
996        } else {
997            HitTestFlags::empty()
998        };
999        // Ignore all incoming events without a hit test.
1000        let Some(hit_test_result) = self
1001            .window
1002            .hit_test_from_input_event(cx, flags, input_event)
1003        else {
1004            return;
1005        };
1006
1007        debug!(
1008            "{:?}: at {:?}",
1009            mouse_button_event.action, hit_test_result.point_in_frame
1010        );
1011
1012        // Set the sequential focus navigation starting point for any mouse button down event, no
1013        // matter if the target is not a node.
1014        let document = self.window.Document();
1015        if mouse_button_event.action == MouseButtonAction::Down {
1016            document
1017                .focus_handler()
1018                .set_sequential_focus_navigation_starting_point(&hit_test_result.node);
1019        }
1020
1021        let Some(element) = hit_test_result
1022            .node
1023            .inclusive_ancestors(ShadowIncluding::Yes)
1024            .find_map(DomRoot::downcast::<Element>)
1025        else {
1026            return;
1027        };
1028
1029        let node = element.upcast::<Node>();
1030        debug!("{:?} on {:?}", mouse_button_event.action, node.debug_str());
1031
1032        // <https://html.spec.whatwg.org/multipage/#selector-active>
1033        // > If the element is being actively pointed at the element is being activated.
1034        // Disabled elements can also be activated, so this must happen before the
1035        // early return below.
1036        if mouse_button_event.button == MouseButton::Primary {
1037            if mouse_button_event.action == MouseButtonAction::Down {
1038                self.set_active_element(cx.no_gc(), &element);
1039            }
1040            if mouse_button_event.action == MouseButtonAction::Up {
1041                self.unset_active_element(cx.no_gc());
1042            }
1043        }
1044
1045        // https://w3c.github.io/uievents/#hit-test
1046        // Prevent mouse event if element is disabled.
1047        if element.is_actually_disabled() {
1048            return;
1049        }
1050
1051        let mouse_event_type = match mouse_button_event.action {
1052            embedder_traits::MouseButtonAction::Up => atom!("mouseup"),
1053            embedder_traits::MouseButtonAction::Down => atom!("mousedown"),
1054        };
1055
1056        let mouse_button = mouse_button_event.button;
1057        if mouse_button_event.action == MouseButtonAction::Down {
1058            self.button_click_state
1059                .safe_borrow_mut(cx.no_gc())
1060                .on_mouse_down(mouse_button, hit_test_result.point_in_frame);
1061        }
1062
1063        // From <https://w3c.github.io/pointerevents/#dfn-mousedown>
1064        // and <https://w3c.github.io/pointerevents/#mouseup>:
1065        //
1066        // > UIEvent.detail: indicates the current click count incremented by one. For
1067        // > example, if no click happened before the mousedown, detail will contain
1068        // > the value 1.
1069        let click_count = self
1070            .button_click_state
1071            .borrow()
1072            .click_count_for(mouse_button) +
1073            1;
1074
1075        let mouse_event = MouseEvent::for_platform_button_event(
1076            cx,
1077            mouse_event_type,
1078            mouse_button_event,
1079            input_event.pressed_mouse_buttons,
1080            &self.window,
1081            &hit_test_result,
1082            input_event.active_keyboard_modifiers,
1083            click_count,
1084        );
1085
1086        match mouse_button_event.action {
1087            MouseButtonAction::Down => {
1088                // Step 6. Dispatch pointerdown event.
1089                let pointer_event_result = if is_compatibility_event_for_touch {
1090                    true
1091                } else {
1092                    let pointer_event_name = if self.mouse_button_state.get().is_empty() {
1093                        // From <https://w3c.github.io/pointerevents/#dfn-pointerdown>
1094                        // > The user agent MUST fire a pointer event named pointerdown when a pointer enters
1095                        // > the active buttons state. For mouse, this is when the device transitions from no
1096                        // > buttons depressed to at least one button depressed.
1097                        "pointerdown".into()
1098                    } else {
1099                        // From <https://w3c.github.io/pointerevents/#dfn-pointermove>:
1100                        // > The user agent MUST fire a pointer event named pointermove when a pointer
1101                        // > changes any properties that don't fire pointerdown or pointerup events. This
1102                        // > includes any changes to coordinates, pressure, tangential pressure, tilt, twist,
1103                        // > contact geometry (width and height) or chorded buttons.
1104                        "pointermove".into()
1105                    };
1106                    let pointer_event = mouse_event.to_pointer_event(cx, pointer_event_name);
1107
1108                    // Check for pointer capture target for mouse events
1109                    let pointer_id = PointerId::Mouse as i32;
1110
1111                    // Release any disconnected capture target before firing pointer events
1112                    let released_disconnected =
1113                        self.release_disconnected_pointer_capture(cx, pointer_id, "mouse", true);
1114
1115                    // Get the current capture target (before processing pending changes)
1116                    let pointer_target = self
1117                        .get_pointer_capture_target(pointer_id)
1118                        .map(DomRoot::upcast::<EventTarget>)
1119                        .unwrap_or_else(|| DomRoot::from_ref(node.upcast::<EventTarget>()));
1120
1121                    // Update button state before firing so setPointerCapture works in handler.
1122                    self.mouse_button_state
1123                        .set(input_event.pressed_mouse_buttons);
1124
1125                    let pointer_event_result =
1126                        self.fire_pointer_event(cx, &pointer_event, &pointer_target);
1127
1128                    // Process pending pointer capture after firing event, but skip if we just
1129                    // released a disconnected capture to avoid immediately re-capturing.
1130                    // https://w3c.github.io/pointerevents/#process-pending-pointer-capture
1131                    if !released_disconnected {
1132                        self.process_pending_pointer_capture(cx, pointer_id, "mouse", true);
1133                    }
1134                    pointer_event_result
1135                };
1136
1137                // Step 7. Let result = dispatch event at target
1138                let result = mouse_event
1139                    .upcast::<Event>()
1140                    .dispatch(cx, node.upcast(), false);
1141
1142                // If neither the `mousedown` nor the `pointerdown` event had `preventDefault()`
1143                // called on them, call the default mousdown handler on retargeted node
1144                // (`mouse_event.target` is mutated by `dispatch` above).
1145                if result &&
1146                    pointer_event_result &&
1147                    let Some(node) = mouse_event
1148                        .upcast::<Event>()
1149                        .GetTarget()
1150                        .and_then(DomRoot::downcast::<Node>)
1151                {
1152                    let editing_context = document.editing_context(cx, &node);
1153                    editing_context.handle_mousedown_event(cx, &mouse_event, &hit_test_result);
1154                }
1155
1156                // Step 8. If result is true and target is a focusable area
1157                // that is click focusable, then Run the focusing steps at target.
1158                if result {
1159                    // Note that this differs from the specification, because we are going to look
1160                    // for the first inclusive ancestor that is click focusable and then focus it.
1161                    // See documentation for [`Node::find_click_focusable_area`].
1162                    rooted!(&in(cx) let node_click_focusable_area = node.find_click_focusable_area(cx));
1163                    document.focus_handler().focus(
1164                        cx,
1165                        &node_click_focusable_area,
1166                        FocusTrigger::Click,
1167                    );
1168                }
1169
1170                // Step 9. If mbutton is the secondary mouse button, then
1171                // Maybe show context menu with native, target.
1172                if let MouseButton::Secondary = mouse_button_event.button {
1173                    self.maybe_show_context_menu(cx, node.upcast(), &hit_test_result, input_event);
1174                }
1175            },
1176            // https://w3c.github.io/pointerevents/#dfn-handle-native-mouse-up
1177            MouseButtonAction::Up => {
1178                if !is_compatibility_event_for_touch {
1179                    // Step 6. Dispatch pointerup event.
1180                    let mouse_button_state = self.mouse_button_state.get();
1181                    let exactly_one_button = mouse_button_state.exactly_one_button_pressed();
1182                    let pointer_event_name = if exactly_one_button {
1183                        // From <https://w3c.github.io/pointerevents/#dfn-pointerup>:
1184                        // > The user agent MUST fire a pointer event named pointerup when a pointer leaves
1185                        // > the active buttons state. For mouse, this is when the device transitions from at
1186                        // > least one button depressed to no buttons depressed.
1187                        "pointerup".into()
1188                    } else {
1189                        // From <https://w3c.github.io/pointerevents/#dfn-pointermove>:
1190                        // > The user agent MUST fire a pointer event named pointermove when a pointer
1191                        // > changes any properties that don't fire pointerdown or pointerup events. This
1192                        // > includes any changes to coordinates, pressure, tangential pressure, tilt, twist,
1193                        // > contact geometry (width and height) or chorded buttons.
1194                        "pointermove".into()
1195                    };
1196                    let pointer_event = mouse_event.to_pointer_event(cx, pointer_event_name);
1197
1198                    // Check for pointer capture target for mouse events
1199                    let pointer_id = PointerId::Mouse as i32;
1200
1201                    // Release any disconnected capture target before firing pointer events
1202                    let released_disconnected =
1203                        self.release_disconnected_pointer_capture(cx, pointer_id, "mouse", true);
1204
1205                    // Get the current capture target (before any state changes)
1206                    let pointer_target = self
1207                        .get_pointer_capture_target(pointer_id)
1208                        .map(DomRoot::upcast::<EventTarget>)
1209                        .unwrap_or_else(|| DomRoot::from_ref(node.upcast::<EventTarget>()));
1210
1211                    self.fire_pointer_event(cx, &pointer_event, &pointer_target);
1212
1213                    // Update button state after firing event, so setPointerCapture/releasePointerCapture
1214                    // work during the pointerup handler (pointer is still "active").
1215                    self.mouse_button_state
1216                        .set(input_event.pressed_mouse_buttons);
1217
1218                    // Process pending pointer capture after decrementing button count, but skip
1219                    // if we just released a disconnected capture to avoid immediately re-capturing.
1220                    // https://w3c.github.io/pointerevents/#process-pending-pointer-capture
1221                    if !released_disconnected {
1222                        self.process_pending_pointer_capture(cx, pointer_id, "mouse", true);
1223                    }
1224
1225                    // Implicitly release pointer capture when last button was released
1226                    if exactly_one_button {
1227                        self.implicit_release_pointer_capture(cx, pointer_id, "mouse", true);
1228                    }
1229                }
1230
1231                // Step 7. dispatch event at target.
1232                mouse_event
1233                    .upcast::<Event>()
1234                    .dispatch(cx, node.upcast(), false);
1235
1236                // Click counts should still work for other buttons even though they
1237                // do not trigger "click" and "dblclick" events, so we increment
1238                // even when those events are not fired.
1239                self.button_click_state
1240                    .safe_borrow_mut(cx.no_gc())
1241                    .on_mouse_up(mouse_button_event.button, hit_test_result.point_in_frame);
1242
1243                self.maybe_trigger_click_for_mouse_button_down_event(
1244                    cx,
1245                    mouse_button_event,
1246                    input_event,
1247                    &hit_test_result,
1248                    &element,
1249                );
1250            },
1251        }
1252    }
1253
1254    /// <https://w3c.github.io/pointerevents/#handle-native-mouse-click>
1255    /// <https://w3c.github.io/pointerevents/#handle-native-mouse-double-click>
1256    fn maybe_trigger_click_for_mouse_button_down_event(
1257        &self,
1258        cx: &mut JSContext,
1259        event: MouseButtonEvent,
1260        input_event: &ConstellationInputEvent,
1261        hit_test_result: &HitTestResult,
1262        element: &Element,
1263    ) {
1264        let Some(last_mouse_button_down_point) = self
1265            .button_click_state
1266            .safe_borrow_mut(cx.no_gc())
1267            .take_last_mouse_button_down_point(event.button)
1268        else {
1269            return;
1270        };
1271
1272        let distance = last_mouse_button_down_point.distance_to(hit_test_result.point_in_frame);
1273        let maximum_click_distance = 10.0 * self.window.device_pixel_ratio().get();
1274        if distance > maximum_click_distance {
1275            return;
1276        }
1277
1278        let mut dispatch_button_event = |event_name: Atom, click_count: usize| {
1279            let mouse_event = MouseEvent::for_platform_button_event(
1280                cx,
1281                event_name,
1282                event,
1283                input_event.pressed_mouse_buttons,
1284                &self.window,
1285                hit_test_result,
1286                input_event.active_keyboard_modifiers,
1287                click_count,
1288            );
1289            let event = mouse_event.upcast::<Event>();
1290            event.dispatch(cx, element.upcast(), false);
1291            event.flags()
1292        };
1293
1294        let click_count = self
1295            .button_click_state
1296            .borrow()
1297            .click_count_for(event.button);
1298        match event.button {
1299            MouseButton::Primary => {
1300                // From <https://w3c.github.io/pointerevents/#click>
1301                // > The click event type MUST be dispatched on the topmost event target indicated by the
1302                // > pointer, when the user presses down and releases the primary pointer button.
1303                self.most_recently_clicked_element.set(Some(element));
1304
1305                element.set_click_in_progress(true);
1306                dispatch_button_event(atom!("click"), click_count);
1307                element.set_click_in_progress(false);
1308
1309                // The firing of "dblclick" events is dependent on the platform, so we have
1310                // some flexibility here. Some browsers on some platforms only fire a
1311                // "dblclick" when the click count is 2 and others essentially fire one for
1312                // every 2 clicks in a sequence. In all cases, browsers set the click count
1313                // `detail` property to 2.
1314                //
1315                // We follow the latter approach here, considering that every sequence of
1316                // even numbered clicks is a series of double clicks.
1317                if click_count.is_multiple_of(2) {
1318                    dispatch_button_event(Atom::from("dblclick"), 2);
1319                }
1320            },
1321            // From <https://w3c.github.io/pointerevents/#dfn-auxclick>:
1322            // > The auxclick event type MUST be dispatched on the topmost event target
1323            // > indicated by the pointer, when the user presses down and releases the
1324            // > non-primary pointer button, or otherwise activates the pointer in a manner
1325            // > that simulates such an action. The actuation method of the mouse button
1326            // > depends upon the pointer device and the environment configuration, e.g., it
1327            // > MAY depend on the screen location or the delay between the press and
1328            // > release of the pointing device button.
1329            MouseButton::Auxiliary |
1330            MouseButton::Back |
1331            MouseButton::Forward |
1332            MouseButton::Other(..) => {
1333                let event_flags = dispatch_button_event(Atom::from("auxclick"), click_count);
1334                if !event_flags.intersects(EventFlags::Canceled | EventFlags::Handled) &&
1335                    event.button == MouseButton::Auxiliary
1336                {
1337                    self.maybe_activate_link_due_to_auxiliary_click(cx, element.upcast());
1338                }
1339            },
1340            _ => {},
1341        }
1342    }
1343
1344    /// <https://www.w3.org/TR/pointerevents4/#maybe-show-context-menu>
1345    fn maybe_show_context_menu(
1346        &self,
1347        cx: &mut JSContext,
1348        target: &EventTarget,
1349        hit_test_result: &HitTestResult,
1350        input_event: &ConstellationInputEvent,
1351    ) {
1352        // <https://w3c.github.io/pointerevents/#contextmenu>
1353        let menu_event = PointerEvent::new(
1354            cx,
1355            &self.window,                // window
1356            "contextmenu".into(),        // type
1357            EventBubbles::Bubbles,       // can_bubble
1358            EventCancelable::Cancelable, // cancelable
1359            Some(&self.window),          // view
1360            0,                           // detail
1361            hit_test_result.point_in_frame.to_i32(),
1362            hit_test_result.point_in_frame.to_i32(),
1363            hit_test_result
1364                .point_relative_to_initial_containing_block
1365                .to_i32(),
1366            input_event.active_keyboard_modifiers,
1367            MouseButton::Secondary,
1368            input_event.pressed_mouse_buttons,
1369            None,                            // related_target
1370            None,                            // point_in_target
1371            PointerId::Mouse as i32,         // pointer_id
1372            1,                               // width
1373            1,                               // height
1374            0.5,                             // pressure
1375            0.0,                             // tangential_pressure
1376            0,                               // tilt_x
1377            0,                               // tilt_y
1378            0,                               // twist
1379            PI / 2.0,                        // altitude_angle
1380            0.0,                             // azimuth_angle
1381            DOMString::from_static("mouse"), // pointer_type
1382            true,                            // is_primary
1383            &[],                             // coalesced_events
1384            &[],                             // predicted_events
1385        );
1386        menu_event.upcast::<Event>().set_composed(true);
1387
1388        // Step 3. Let result = dispatch menuevent at target.
1389        let result = menu_event.upcast::<Event>().fire(cx, target);
1390
1391        // Step 4. If result is true, then show the UA context menu
1392        if result {
1393            self.window
1394                .Document()
1395                .embedder_controls()
1396                .show_context_menu(cx, hit_test_result);
1397        };
1398    }
1399
1400    fn handle_touch_event(
1401        &self,
1402        cx: &mut JSContext,
1403        event: EmbedderTouchEvent,
1404        input_event: &ConstellationInputEvent,
1405    ) -> InputEventResult {
1406        let flags = HitTestFlags::empty();
1407        // Ignore all incoming events without a hit test.
1408        let Some(hit_test_result) = self
1409            .window
1410            .hit_test_from_input_event(cx, flags, input_event)
1411        else {
1412            self.update_active_touch_points_when_early_return(event);
1413            return Default::default();
1414        };
1415
1416        let TouchId(identifier) = event.touch_id;
1417
1418        let Some(element) = hit_test_result
1419            .node
1420            .inclusive_ancestors(ShadowIncluding::Yes)
1421            .find_map(DomRoot::downcast::<Element>)
1422        else {
1423            self.update_active_touch_points_when_early_return(event);
1424            return Default::default();
1425        };
1426
1427        let current_target = DomRoot::upcast::<EventTarget>(element.clone());
1428        let window = &*self.window;
1429
1430        let client_x = Finite::wrap(hit_test_result.point_in_frame.x as f64);
1431        let client_y = Finite::wrap(hit_test_result.point_in_frame.y as f64);
1432        let page_x =
1433            Finite::wrap(hit_test_result.point_in_frame.x as f64 + window.PageXOffset(cx) as f64);
1434        let page_y =
1435            Finite::wrap(hit_test_result.point_in_frame.y as f64 + window.PageYOffset(cx) as f64);
1436
1437        // This is used to construct pointerevent and touchdown event.
1438        let pointer_touch = Touch::new(
1439            cx,
1440            window,
1441            identifier,
1442            &current_target,
1443            client_x,
1444            client_y, // TODO: Get real screen coordinates?
1445            client_x,
1446            client_y,
1447            page_x,
1448            page_y,
1449        );
1450
1451        // Dispatch pointer event before updating active touch points and before touch event.
1452        let pointer_event_name = match event.event_type {
1453            TouchEventType::Down => "pointerdown",
1454            TouchEventType::Move => "pointermove",
1455            TouchEventType::Up => "pointerup",
1456            TouchEventType::Cancel => "pointercancel",
1457        };
1458
1459        // Map the embedder-side subtype to the spec `pointerType` string.
1460        let pointer_type = match event.pointer_type {
1461            TouchPointerType::Pen => "pen",
1462            TouchPointerType::Touch => "touch",
1463        };
1464
1465        // Get or create pointer ID for this touch
1466        let pointer_id = self.get_or_create_pointer_id_for_touch(identifier);
1467        let is_primary = self.is_primary_pointer(pointer_id);
1468
1469        // For touch devices (which don't support hover), fire pointerover/pointerenter
1470        // <https://w3c.github.io/pointerevents/#mapping-for-devices-that-do-not-support-hover>
1471        if matches!(event.event_type, TouchEventType::Down) {
1472            // Fire pointerover
1473            let pointer_over = pointer_touch.to_pointer_event(
1474                cx,
1475                window,
1476                "pointerover",
1477                pointer_id,
1478                is_primary,
1479                pointer_type,
1480                input_event.active_keyboard_modifiers,
1481                true, // cancelable
1482                Some(hit_test_result.point_in_node),
1483            );
1484            pointer_over.upcast::<Event>().fire(cx, &current_target);
1485
1486            // Fire pointerenter hierarchically (from topmost ancestor to target)
1487            self.fire_pointer_event_for_touch(
1488                cx,
1489                &element,
1490                &pointer_touch,
1491                pointer_id,
1492                "pointerenter",
1493                is_primary,
1494                pointer_type,
1495                input_event,
1496                &hit_test_result,
1497            );
1498        }
1499
1500        // Release any disconnected capture target before firing pointer events,
1501        // but not for pointercancel: let implicit_release handle that so
1502        // lostpointercapture fires after pointercancel per spec.
1503        let released_disconnected = if matches!(event.event_type, TouchEventType::Cancel) {
1504            false
1505        } else {
1506            self.release_disconnected_pointer_capture(cx, pointer_id, pointer_type, is_primary)
1507        };
1508
1509        // Get the current capture target (before processing pending changes)
1510        let pointer_target = self
1511            .get_pointer_capture_target(pointer_id)
1512            .map(DomRoot::upcast::<EventTarget>)
1513            .unwrap_or_else(|| current_target.clone());
1514
1515        let pointer_event = pointer_touch.to_pointer_event(
1516            cx,
1517            window,
1518            pointer_event_name,
1519            pointer_id,
1520            is_primary,
1521            pointer_type,
1522            input_event.active_keyboard_modifiers,
1523            event.is_cancelable(),
1524            Some(hit_test_result.point_in_node),
1525        );
1526        self.fire_pointer_event(cx, &pointer_event, &pointer_target);
1527
1528        // Process pending pointer capture after firing event, but skip if we just
1529        // released a disconnected capture (to avoid immediately re-capturing).
1530        // Also skip for pointercancel: per spec, process pending only runs for
1531        // pointerdown, pointermove, and pointerup, not pointercancel.
1532        // https://w3c.github.io/pointerevents/#process-pending-pointer-capture
1533        if !released_disconnected && !matches!(event.event_type, TouchEventType::Cancel) {
1534            self.process_pending_pointer_capture(cx, pointer_id, pointer_type, is_primary);
1535        }
1536
1537        // Implicitly release pointer capture on pointerup or pointercancel
1538        // For pointercancel, this fires lostpointercapture after the pointercancel event.
1539        if matches!(
1540            event.event_type,
1541            TouchEventType::Up | TouchEventType::Cancel
1542        ) {
1543            self.implicit_release_pointer_capture(cx, pointer_id, pointer_type, is_primary);
1544        }
1545
1546        // For touch devices, fire pointerout/pointerleave after pointerup/pointercancel
1547        // <https://w3c.github.io/pointerevents/#mapping-for-devices-that-do-not-support-hover>
1548        if matches!(
1549            event.event_type,
1550            TouchEventType::Up | TouchEventType::Cancel
1551        ) {
1552            // Fire pointerout
1553            let pointer_out = pointer_touch.to_pointer_event(
1554                cx,
1555                window,
1556                "pointerout",
1557                pointer_id,
1558                is_primary,
1559                pointer_type,
1560                input_event.active_keyboard_modifiers,
1561                true, // cancelable
1562                Some(hit_test_result.point_in_node),
1563            );
1564            pointer_out.upcast::<Event>().fire(cx, &current_target);
1565
1566            // Fire pointerleave hierarchically (from target to topmost ancestor)
1567            self.fire_pointer_event_for_touch(
1568                cx,
1569                &element,
1570                &pointer_touch,
1571                pointer_id,
1572                "pointerleave",
1573                is_primary,
1574                pointer_type,
1575                input_event,
1576                &hit_test_result,
1577            );
1578        }
1579
1580        let (touch_dispatch_target, changed_touch) = match event.event_type {
1581            TouchEventType::Down => {
1582                self.touch_sequence_click_allowed.set(true);
1583                // Add a new touch point
1584                self.active_touch_points
1585                    .safe_borrow_mut(cx.no_gc())
1586                    .push(Dom::from_ref(&*pointer_touch));
1587                self.set_active_element(cx.no_gc(), &element);
1588                (current_target, pointer_touch)
1589            },
1590            _ => {
1591                // From <https://w3c.github.io/touch-events/#dfn-touchend>:
1592                // > For move/up/cancel:
1593                // > The target of this event must be the same Element on which the touch
1594                // > point started when it was first placed on the surface, even if the touch point
1595                // > has since moved outside the interactive area of the target element.
1596                let active_touch_points = self.active_touch_points.borrow();
1597                let Some(index) = active_touch_points
1598                    .iter()
1599                    .position(|point| point.Identifier() == identifier)
1600                else {
1601                    warn!("No active touch point for {:?}", event.event_type);
1602                    return Default::default();
1603                };
1604                // This is the original target that was selected during `touchstart` event handling.
1605                let original_target = active_touch_points[index].Target();
1606                drop(active_touch_points);
1607
1608                let touch_with_touchstart_target = Touch::new(
1609                    cx,
1610                    window,
1611                    identifier,
1612                    &original_target,
1613                    client_x,
1614                    client_y,
1615                    client_x,
1616                    client_y,
1617                    page_x,
1618                    page_y,
1619                );
1620
1621                let mut active_touch_points = self.active_touch_points.safe_borrow_mut(cx.no_gc());
1622                // Update or remove the stored touch
1623                match event.event_type {
1624                    TouchEventType::Move => {
1625                        active_touch_points[index] = Dom::from_ref(&*touch_with_touchstart_target);
1626                    },
1627                    TouchEventType::Up | TouchEventType::Cancel => {
1628                        active_touch_points.swap_remove(index);
1629                        self.remove_pointer_id_for_touch(identifier);
1630                        self.unset_active_element(cx.no_gc());
1631                    },
1632                    TouchEventType::Down => unreachable!("Should have been handled above"),
1633                }
1634                (original_target, touch_with_touchstart_target)
1635            },
1636        };
1637
1638        rooted_vec!(let mut target_touches);
1639        target_touches.extend(
1640            self.active_touch_points
1641                .borrow()
1642                .iter()
1643                .filter(|touch| touch.Target() == touch_dispatch_target)
1644                .cloned(),
1645        );
1646
1647        let event_name = match event.event_type {
1648            TouchEventType::Down => "touchstart",
1649            TouchEventType::Move => "touchmove",
1650            TouchEventType::Up => "touchend",
1651            TouchEventType::Cancel => "touchcancel",
1652        };
1653
1654        let touches = TouchList::new(cx, window, self.active_touch_points.borrow().as_ref_slice());
1655        let changed_touches = TouchList::new(cx, window, from_ref(&&*changed_touch));
1656        let target_touches = TouchList::new(cx, window, target_touches.as_ref_slice());
1657
1658        let touch_event = TouchEvent::new(
1659            cx,
1660            window,
1661            event_name.into(),
1662            EventBubbles::Bubbles,
1663            EventCancelable::from(event.is_cancelable()),
1664            EventComposed::Composed,
1665            Some(window),
1666            0i32,
1667            &touches,
1668            &changed_touches,
1669            &target_touches,
1670            // FIXME: modifier keys
1671            false,
1672            false,
1673            false,
1674            false,
1675        );
1676        let dom_event = touch_event.upcast::<Event>();
1677        dom_event.fire(cx, &touch_dispatch_target);
1678        let flags = dom_event.flags();
1679
1680        // `preventDefault()` on `touchstart` or `touchend` suppresses compat mouse events.
1681        if flags.contains(EventFlags::Canceled) &&
1682            matches!(event.event_type, TouchEventType::Down | TouchEventType::Up)
1683        {
1684            self.touch_sequence_click_allowed.set(false);
1685        }
1686
1687        // Generate the compatibility mouse events synchronously as part of
1688        // `touchend`, before the embedder is told the touch event was handled.
1689        let synthesizes_mouse_events = matches!(event.event_type, TouchEventType::Up) &&
1690            event.can_synthesize_mouse_events &&
1691            self.touch_sequence_click_allowed.get() &&
1692            !flags.contains(EventFlags::Canceled) &&
1693            self.active_touch_points.borrow().is_empty();
1694
1695        if synthesizes_mouse_events {
1696            self.synthesize_compatibility_mouse_events(cx, &event, input_event);
1697        } else if matches!(
1698            event.event_type,
1699            TouchEventType::Up | TouchEventType::Cancel
1700        ) {
1701            // A touchend that doesn't synthesize compatibility mouse events ends the
1702            // click sequence.
1703            // See https://github.com/servo/servo/issues/46497#issuecomment-6030515485>
1704            self.button_click_state
1705                .safe_borrow_mut(cx.no_gc())
1706                .reset_all();
1707        }
1708
1709        flags.into()
1710    }
1711
1712    /// Generate the compatibility mouse events for a tap while handling `touchend`.
1713    ///
1714    /// <http://w3c.github.io/touch-events/#mouse-events>
1715    fn synthesize_compatibility_mouse_events(
1716        &self,
1717        cx: &mut JSContext,
1718        event: &EmbedderTouchEvent,
1719        input_event: &ConstellationInputEvent,
1720    ) {
1721        // Reuse the touch event's hit test result and keyboard modifiers.
1722        let make_input_event =
1723            |input_event_to_send: InputEvent, pressed_mouse_buttons: MouseButtons| {
1724                ConstellationInputEvent {
1725                    hit_test_result: input_event.hit_test_result.clone(),
1726                    pressed_mouse_buttons,
1727                    active_keyboard_modifiers: input_event.active_keyboard_modifiers,
1728                    event: input_event_to_send.into(),
1729                }
1730            };
1731
1732        let point = event.point;
1733        let mouse_move_input_event = make_input_event(
1734            InputEvent::MouseMove(MouseMoveEvent::new_compatibility_for_touch(point)),
1735            MouseButtons::empty(),
1736        );
1737        self.handle_native_mouse_move_event(cx, &mouse_move_input_event);
1738
1739        for (action, pressed_mouse_buttons) in [
1740            (MouseButtonAction::Down, MouseButtons::Primary),
1741            (MouseButtonAction::Up, MouseButtons::empty()),
1742        ] {
1743            let button_event =
1744                MouseButtonEvent::new_compatibility_for_touch(action, MouseButton::Primary, point);
1745            self.handle_native_mouse_button_event(
1746                cx,
1747                button_event,
1748                &make_input_event(InputEvent::MouseButton(button_event), pressed_mouse_buttons),
1749            );
1750        }
1751    }
1752
1753    /// Updates the active touch points when a hit test fails early.
1754    ///
1755    /// - For `Down`: No action needed; a failed down event won't create an active point.
1756    /// - For `Move`: No action needed; position information is unavailable, so we cannot update.
1757    /// - For `Up`/`Cancel`: Remove the corresponding touch point and its pointer ID mapping.
1758    ///
1759    /// When a touchup or touchcancel occurs at that touch point,
1760    /// a warning is triggered: Received touchup/touchcancel event for a non-active touch point.
1761    fn update_active_touch_points_when_early_return(&self, event: EmbedderTouchEvent) {
1762        match event.event_type {
1763            TouchEventType::Down | TouchEventType::Move => {},
1764            TouchEventType::Up | TouchEventType::Cancel => {
1765                let mut active_touch_points = self.active_touch_points.borrow_mut();
1766                if let Some(index) = active_touch_points
1767                    .iter()
1768                    .position(|t| t.Identifier() == event.touch_id.0)
1769                {
1770                    active_touch_points.swap_remove(index);
1771                    self.remove_pointer_id_for_touch(event.touch_id.0);
1772                } else {
1773                    warn!(
1774                        "Received {:?} for a non-active touch point {}",
1775                        event.event_type, event.touch_id.0
1776                    );
1777                }
1778            },
1779        }
1780    }
1781
1782    /// The entry point for all key processing for web content
1783    fn handle_keyboard_event(
1784        &self,
1785        cx: &mut JSContext,
1786        keyboard_event: EmbedderKeyboardEvent,
1787    ) -> InputEventResult {
1788        let event_type = keyboard_event.event.state.event_type().into();
1789        // We should update the state of the focus handler even if the default action
1790        // of the keyboard event will be prevented. That could be the case where in
1791        // the callback of a keydown event we cancel the event, but also pass on focus
1792        // to another element. In that case, the newly script focused element should
1793        // still match `:focus-visible`.
1794        if event_type == atom!("keydown") {
1795            self.window
1796                .Document()
1797                .focus_handler()
1798                .set_last_user_interaction_was_keyboard(true);
1799        }
1800
1801        let target = &self.target_for_events_following_focus();
1802        let keyevent = KeyboardEvent::new_with_platform_keyboard_event(
1803            cx,
1804            &self.window,
1805            event_type,
1806            &keyboard_event.event,
1807        );
1808
1809        let event = keyevent.upcast::<Event>();
1810        event.set_composed(true);
1811        // <https://html.spec.whatwg.org/multipage/#close-requests>
1812        // > Some example close requests are:
1813        // > - The Esc key on desktop platforms.
1814        // > On platforms where pressing the Esc key is interpreted as a close request, the user agent
1815        // > must interpret the key being pressed down as the close request, instead of the key being
1816        // > released. Thus, in the above algorithm, the "relevant events" that are fired must be the
1817        // > single keydown event.
1818        if keyboard_event.event.state == KeyState::Down &&
1819            keyboard_event.event.key == Key::Named(NamedKey::Escape)
1820        {
1821            self.close_request_steps(cx, Some((event, target)));
1822        } else {
1823            event.fire(cx, target);
1824        }
1825
1826        // From https://w3c.github.io/uievents/#keys-cancelable-keys:
1827        // > Canceling the default action of a keydown event MUST NOT affect its
1828        // > respective keyup event, but it MUST prevent the respective beforeinput and
1829        // > input (and keypress if supported) events from being generated.
1830        let mut flags = event.flags();
1831        if keyboard_event.event.state != KeyState::Down || flags.contains(EventFlags::Canceled) {
1832            return flags.into();
1833        }
1834
1835        // From <https://w3c.github.io/uievents/#keypress-event-order>:
1836        // > The keypress event type MUST be dispatched after the keydown event and before
1837        // > the keyup event associated with the same key.
1838        let fires_keypress_event = keyboard_event_fires_keypress_event(&keyboard_event);
1839        if fires_keypress_event {
1840            let keypress_event = KeyboardEvent::new_with_platform_keyboard_event(
1841                cx,
1842                &self.window,
1843                atom!("keypress"),
1844                &keyboard_event.event,
1845            );
1846            keypress_event.upcast::<Event>().set_composed(true);
1847            let event = keypress_event.upcast::<Event>();
1848            event.fire(cx, target);
1849            flags |= event.flags();
1850        }
1851
1852        // If the event was canceled or consumed during event propagation do not run the
1853        // default keydown event handler.
1854        if flags.intersects(EventFlags::Handled | EventFlags::Canceled) {
1855            return flags.into();
1856        }
1857
1858        self.run_default_keydown_handler(cx, target, &keyboard_event, flags.into())
1859    }
1860
1861    /// <https://html.spec.whatwg.org/multipage/#close-request-steps>
1862    ///
1863    /// `event` is the event to fire for this close request, along with its target, if any.
1864    pub(crate) fn close_request_steps(
1865        &self,
1866        cx: &mut JSContext,
1867        event: Option<(&Event, &EventTarget)>,
1868    ) {
1869        // Step 1. If document's fullscreen element is not null:
1870        let document = self.window.Document();
1871        if document.overlay_handler().fullscreen_element().is_some() {
1872            // Step 1.1. Fully exit fullscreen given document's node navigable's top-level traversable's active document.
1873            // TODO: node navigable's top-level traversable's active document
1874            document.overlay_handler().fully_exit_fullscreen(cx);
1875
1876            // Step 1.2. Return.
1877            return;
1878        }
1879
1880        // Step 2. Optionally, skip to the step labeled alternative processing.
1881
1882        // Step 3. Fire any relevant events, per UI Events or other relevant specifications. [UIEVENTS]
1883        if let Some((event, target)) = event {
1884            event.fire(cx, target);
1885        }
1886
1887        // Step 4. Let event be null if no such events are fired, or the Event object representing one of
1888        // the fired events otherwise. If multiple events are fired, which one is chosen is
1889        // implementation-defined.
1890        let event = event.map(|(event, _)| event);
1891
1892        // Step 5. If event is not null, and its canceled flag is set, then return.
1893        if event.is_some_and(|event| event.flags().contains(EventFlags::Canceled)) {
1894            return;
1895        }
1896
1897        // Step 6. If document is not fully active, then return.
1898        if !document.is_fully_active() {
1899            return;
1900        }
1901
1902        // Step 7. Let closedSomething be the result of processing close watchers on document's
1903        // relevant global object.
1904        self.window.process_close_watchers(cx);
1905
1906        // Step 8. If closedSomething is true, then return.
1907        // Step 9. Alternative processing: Otherwise, there was nothing watching for a close request.
1908        // The user agent may instead interpret this interaction as some other action, instead of
1909        // interpreting it as a close request.
1910    }
1911
1912    fn handle_ime_event(&self, cx: &mut JSContext, event: ImeEvent) -> InputEventResult {
1913        match event {
1914            ImeEvent::Dismissed => {
1915                self.window.Document().focus_handler().focus(
1916                    cx,
1917                    &FocusableArea::Viewport,
1918                    FocusTrigger::Script,
1919                );
1920                Default::default()
1921            },
1922            ImeEvent::Commit(text) => self.handle_ime_commit(cx, text),
1923            ImeEvent::Composition(composition_event) => {
1924                self.handle_ime_composition(cx, composition_event)
1925            },
1926        }
1927    }
1928
1929    fn handle_ime_composition(
1930        &self,
1931        cx: &mut JSContext,
1932        composition_event: keyboard_types::CompositionEvent,
1933    ) -> InputEventResult {
1934        let document = self.window.Document();
1935        // spec: https://w3c.github.io/uievents/#compositionstart
1936        // spec: https://w3c.github.io/uievents/#compositionupdate
1937        // spec: https://w3c.github.io/uievents/#compositionend
1938        // > Event.target : focused element processing the composition
1939        let focused_area = document.focus_handler().focused_area();
1940        let Some(focused_element) = focused_area.element() else {
1941            // Event is only dispatched if there is a focused element.
1942            return Default::default();
1943        };
1944
1945        let cancelable = composition_event.state == CompositionState::Start;
1946        let event = CompositionEvent::new(
1947            cx,
1948            &self.window,
1949            composition_event.state.event_type().into(),
1950            true,
1951            cancelable,
1952            Some(&self.window),
1953            0,
1954            DOMString::from(composition_event.data.as_str()),
1955        );
1956
1957        let event = event.upcast::<Event>();
1958        event.fire(cx, focused_element.upcast());
1959        let composition_event_result: InputEventResult = event.flags().into();
1960
1961        if event
1962            .flags()
1963            .intersects(EventFlags::Canceled | EventFlags::Handled)
1964        {
1965            return composition_event_result;
1966        }
1967
1968        let editing_action = editing_action_from_composition_event(&composition_event);
1969        let editing_host = document.editing_context(cx.no_gc(), focused_element.upcast());
1970        if editing_host.perform_editing_action(cx, editing_action) {
1971            return composition_event_result | InputEventResult::Consumed;
1972        }
1973
1974        composition_event_result
1975    }
1976
1977    fn handle_ime_commit(&self, cx: &mut JSContext, text: String) -> InputEventResult {
1978        let document = self.window.Document();
1979        let focused_area = document.focus_handler().focused_area();
1980        let Some(focused_element) = focused_area.element() else {
1981            // Event is only dispatched if there is a focused element.
1982            return Default::default();
1983        };
1984        let editing_host = document.editing_context(cx.no_gc(), focused_element.upcast());
1985        if editing_host.perform_editing_action(cx, EditingAction::InsertText(text)) {
1986            return InputEventResult::Consumed;
1987        }
1988        Default::default()
1989    }
1990
1991    fn handle_wheel_event(
1992        &self,
1993        cx: &mut JSContext,
1994        event: EmbedderWheelEvent,
1995        input_event: &ConstellationInputEvent,
1996    ) -> InputEventResult {
1997        // Ignore all incoming events without a hit test.
1998        let flags = HitTestFlags::empty();
1999        let Some(hit_test_result) = self
2000            .window
2001            .hit_test_from_input_event(cx, flags, input_event)
2002        else {
2003            return Default::default();
2004        };
2005
2006        let Some(el) = hit_test_result
2007            .node
2008            .inclusive_ancestors(ShadowIncluding::Yes)
2009            .find_map(DomRoot::downcast::<Element>)
2010        else {
2011            return Default::default();
2012        };
2013
2014        let node = el.upcast::<Node>();
2015        debug!(
2016            "wheel: on {:?} at {:?}",
2017            node.debug_str(),
2018            hit_test_result.point_in_frame
2019        );
2020
2021        let event_type = "wheel".into();
2022
2023        let cancelable = EventCancelable::from(
2024            self.window
2025                .upcast::<EventTarget>()
2026                .has_non_passive_listener(&event_type) ||
2027                node.inclusive_ancestors(ShadowIncluding::Yes)
2028                    .any(|target| {
2029                        target
2030                            .upcast::<EventTarget>()
2031                            .has_non_passive_listener(&event_type)
2032                    }),
2033        );
2034        // https://w3c.github.io/uievents/#event-wheelevents
2035        let dom_event = WheelEvent::new(
2036            cx,
2037            &self.window,
2038            event_type,
2039            EventBubbles::Bubbles,
2040            cancelable,
2041            Some(&self.window),
2042            0i32,
2043            hit_test_result.point_in_frame.to_i32(),
2044            hit_test_result.point_in_frame.to_i32(),
2045            hit_test_result
2046                .point_relative_to_initial_containing_block
2047                .to_i32(),
2048            input_event.active_keyboard_modifiers,
2049            MouseButton::Primary,
2050            input_event.pressed_mouse_buttons,
2051            None,
2052            None,
2053            // winit defines positive wheel delta values as revealing more content left/up.
2054            // https://docs.rs/winit-gtk/latest/winit/event/enum.MouseScrollDelta.html
2055            // This is the opposite of wheel delta in uievents
2056            // https://w3c.github.io/uievents/#dom-wheeleventinit-deltaz
2057            Finite::wrap(-event.delta.x),
2058            Finite::wrap(-event.delta.y),
2059            Finite::wrap(-event.delta.z),
2060            event.delta.mode as u32,
2061        );
2062
2063        let dom_event = dom_event.upcast::<Event>();
2064        dom_event.set_trusted(true);
2065        dom_event.set_composed(true);
2066        dom_event.fire(cx, node.upcast());
2067
2068        dom_event.flags().into()
2069    }
2070
2071    #[cfg(feature = "gamepad")]
2072    fn handle_gamepad_event(&self, gamepad_event: EmbedderGamepadEvent) {
2073        match gamepad_event {
2074            EmbedderGamepadEvent::Connected(index, name, bounds, supported_haptic_effects) => {
2075                self.handle_gamepad_connect(
2076                    index.0,
2077                    name,
2078                    bounds.axis_bounds,
2079                    bounds.button_bounds,
2080                    supported_haptic_effects,
2081                );
2082            },
2083            EmbedderGamepadEvent::Disconnected(index) => {
2084                self.handle_gamepad_disconnect(index.0);
2085            },
2086            EmbedderGamepadEvent::Updated(index, update_type) => {
2087                self.receive_new_gamepad_button_or_axis(index.0, update_type);
2088            },
2089        };
2090    }
2091
2092    /// <https://www.w3.org/TR/gamepad/#dfn-gamepadconnected>
2093    #[cfg(feature = "gamepad")]
2094    fn handle_gamepad_connect(
2095        &self,
2096        // As the spec actually defines how to set the gamepad index, the GilRs index
2097        // is currently unused, though in practice it will almost always be the same.
2098        // More infra is currently needed to track gamepads across windows.
2099        _index: usize,
2100        name: String,
2101        axis_bounds: (f64, f64),
2102        button_bounds: (f64, f64),
2103        supported_haptic_effects: GamepadSupportedHapticEffects,
2104    ) {
2105        // Step 1. Let document be the current global object's associated Document; otherwise null.
2106        let doc = self.window.Document();
2107
2108        // Step 2. If document is not null and is not allowed to use the "gamepad" permission,
2109        //         then abort these steps.
2110        if !doc.allowed_to_use_feature(PermissionName::Gamepad) {
2111            return;
2112        }
2113
2114        let trusted_window = Trusted::new(&*self.window);
2115
2116        // Step 3. Queue a global task on the gamepad task source with the current global object
2117        //         to perform the following steps:
2118        self.window
2119            .upcast::<GlobalScope>()
2120            .task_manager()
2121            .gamepad_task_source()
2122            .queue(task!(gamepad_connected: move |cx| {
2123                let window = trusted_window.root();
2124
2125                // Step 3.1. Let gamepad be a new Gamepad representing the gamepad.
2126                // Step 3.2. Let navigator be gamepad's relevant global object's Navigator object.
2127                let navigator = window.Navigator(cx);
2128                let selected_index = navigator.select_gamepad_index();
2129                let gamepad = Gamepad::new(
2130                    cx,
2131                    &window,
2132                    selected_index,
2133                    name,
2134                    GamepadMappingType::Standard,
2135                    axis_bounds,
2136                    button_bounds,
2137                    supported_haptic_effects,
2138                    false,
2139                );
2140
2141                // Step 3.3. Set navigator.[[gamepads]][gamepad.index] to gamepad.
2142                navigator.set_gamepad(selected_index as usize, Some(&gamepad));
2143
2144                // Step 3.4. If navigator.[[hasGamepadGesture]] is true:
2145                if navigator.has_gamepad_gesture() {
2146                    // Step 3.4.1. Set gamepad.[[exposed]] to true.
2147                    gamepad.set_exposed(true);
2148                    // Step 3.4.2. If document is not null and is fully active, then fire an
2149                    //            event named gamepadconnected at gamepad's relevant global
2150                    //            object using GamepadEvent with its gamepad attribute
2151                    //            initialized to gamepad.
2152                    if window.Document().is_fully_active() {
2153                        gamepad.notify_event(cx, GamepadEventType::Connected);
2154                    }
2155                }
2156            }));
2157    }
2158
2159    /// <https://www.w3.org/TR/gamepad/#dfn-gamepaddisconnected>
2160    #[cfg(feature = "gamepad")]
2161    fn handle_gamepad_disconnect(&self, index: usize) {
2162        // Step 1. Let gamepad be the Gamepad representing the unavailable device.
2163        // Step 2. Queue a global task on the gamepad task source with
2164        //         gamepad's relevant global object to perform the following steps:
2165        let trusted_window = Trusted::new(&*self.window);
2166        self.window
2167            .upcast::<GlobalScope>()
2168            .task_manager()
2169            .gamepad_task_source()
2170            .queue(task!(gamepad_disconnected: move |cx| {
2171                let window = trusted_window.root();
2172                let navigator = window.Navigator(cx);
2173
2174                if let Some(gamepad) = navigator.get_gamepad(index) {
2175                    // Step 2.1. Set gamepad.[[connected]] to false.
2176                    gamepad.update_connected(false);
2177                    // Step 2.2. Let document be gamepad's relevant global object's
2178                    //           associated Document; otherwise null.
2179                    // Step 2.3. If gamepad.[[exposed]] is true and document is not null
2180                    //           and is fully active, then fire an event named
2181                    //           gamepaddisconnected at gamepad's relevant global object
2182                    //           using GamepadEvent with its gamepad attribute
2183                    //           initialized to gamepad.
2184                    if gamepad.exposed() && window.Document().is_fully_active() {
2185                        gamepad.notify_event(cx, GamepadEventType::Disconnected);
2186                    }
2187                }
2188
2189                // Step 2.4. Let navigator be gamepad's relevant global object's
2190                //           Navigator object.
2191                // Step 2.5. Set navigator.[[gamepads]][gamepad.index] to null.
2192                navigator.set_gamepad(index, None);
2193                // Step 2.6. While navigator.[[gamepads]] is not empty and the last item of
2194                //           navigator.[[gamepads]] is null, remove the last item of navigator.[[gamepads]].
2195                navigator.shrink_gamepads_list();
2196            }));
2197    }
2198
2199    /// <https://www.w3.org/TR/gamepad/#receiving-inputs>
2200    #[cfg(feature = "gamepad")]
2201    fn receive_new_gamepad_button_or_axis(&self, index: usize, update_type: GamepadUpdateType) {
2202        // Step 1. Let gamepad be the Gamepad object representing the device that received
2203        //         new button or axis input values.
2204        let trusted_window = Trusted::new(&*self.window);
2205
2206        // Step 2. Queue a global task on the gamepad task source with gamepad's
2207        //         relevant global object to update gamepad state for gamepad.
2208        self.window
2209            .upcast::<GlobalScope>()
2210            .task_manager()
2211            .gamepad_task_source()
2212            .queue(task!(update_gamepad_state: move |cx| {
2213                let window = trusted_window.root();
2214                let document = window.Document();
2215                document.event_handler().update_gamepad_state(cx, index, update_type);
2216            }));
2217    }
2218
2219    /// <https://w3c.github.io/gamepad/#dfn-update-gamepad-state>
2220    #[cfg(feature = "gamepad")]
2221    fn update_gamepad_state(
2222        &self,
2223        cx: &mut JSContext,
2224        gamepad_index: usize,
2225        update_type: GamepadUpdateType,
2226    ) {
2227        use script_bindings::codegen::GenericBindings::PerformanceBinding::PerformanceMethods;
2228        // Step 1. Let now be the current high resolution time given
2229        //         gamepad's relevant global object.
2230        let now = *self.window.Performance(cx).Now();
2231
2232        // Step 6. Let navigator be gamepad's relevant global object's
2233        //         Navigator object.
2234        let navigator = self.window.Navigator(cx);
2235
2236        if let Some(gamepad) = navigator.get_gamepad(gamepad_index) {
2237            // Step 2. Set gamepad.[[timestamp]] to now.
2238            gamepad.update_timestamp(now);
2239            // Step 3. Run the steps to map and normalize axes for gamepad.
2240            // Step 4. Run the steps to map and normalize buttons for gamepad.
2241            match update_type {
2242                GamepadUpdateType::Axis(axis_index, value) => {
2243                    gamepad.map_and_normalize_axes(axis_index, value);
2244                },
2245                GamepadUpdateType::Button(button_index, value) => {
2246                    gamepad.map_and_normalize_buttons(button_index, value);
2247                },
2248            };
2249            // TODO Step 5. Run the steps to record touches for gamepad.
2250
2251            // Step 7. If navigator.[[hasGamepadGesture]] is false and
2252            //         gamepad contains a gamepad user gesture:
2253            if !navigator.has_gamepad_gesture() && contains_user_gesture(update_type) {
2254                // Step 7.1. Set navigator.[[hasGamepadGesture]] to true.
2255                navigator.set_has_gamepad_gesture(true);
2256                // Step 7.2. For each connectedGamepad of navigator.[[gamepads]]:
2257                navigator
2258                    .get_connected_gamepad()
2259                    .iter()
2260                    .for_each(|connected_gamepad| {
2261                        // Step 7.2.1. Set connectedGamepad.[[exposed]] to true.
2262                        connected_gamepad.set_exposed(true);
2263                        // Step 7.2.2. Set connectedGamepad.[[timestamp]] to now.
2264                        connected_gamepad.update_timestamp(now);
2265                        // Step 7.2.3. Let document be gamepad's relevant global
2266                        //             object's associated Document; otherwise null.
2267                        // Step 7.2.4. If document is not null and is fully active,
2268                        //             then queue a global task on the gamepad task
2269                        //             source to fire an event named gamepadconnected
2270                        //             at gamepad's relevant global object.
2271                        let trusted_gamepad = Trusted::new(&**connected_gamepad);
2272                        if self.window.Document().is_fully_active() {
2273                            self.window
2274                                .upcast::<GlobalScope>()
2275                                .task_manager()
2276                                .gamepad_task_source()
2277                                .queue(task!(fire_gamepad_connected: move |cx| {
2278                                    let gamepad = trusted_gamepad.root();
2279                                    gamepad.notify_event(cx, GamepadEventType::Connected);
2280                                }));
2281                        }
2282                    });
2283            }
2284        }
2285    }
2286
2287    /// <https://drafts.csswg.org/cssom-view/#scrolling-events>
2288    #[expect(unsafe_code)]
2289    pub(crate) fn handle_embedder_scroll_event(&self, scrolled_node: ExternalScrollId) {
2290        // If it is a viewport scroll.
2291        let document = self.window.Document();
2292        if scrolled_node.is_root() {
2293            document.handle_viewport_scroll_event();
2294        } else {
2295            // Otherwise, check whether it is for a relevant element within the document. For a `::before` or `::after`
2296            // pseudo element we follow Gecko or Chromium's behavior to ensure that the event reaches the originating
2297            // node.
2298            let node_id = node_id_from_scroll_id(scrolled_node.0 as usize);
2299            let node = unsafe {
2300                node::from_untrusted_node_address(UntrustedNodeAddress::from_id(node_id))
2301            };
2302            let Some(element) = node
2303                .inclusive_ancestors(ShadowIncluding::Yes)
2304                .find_map(DomRoot::downcast::<Element>)
2305            else {
2306                return;
2307            };
2308
2309            element.handle_scroll_event();
2310        }
2311    }
2312
2313    /// <https://w3c.github.io/uievents/#keydown>
2314    ///
2315    /// > If the key is the Enter or (Space) key and the current focus is on a state-changing element,
2316    /// > the default action MUST be to dispatch a click event, and a DOMActivate event if that event
2317    /// > type is supported by the user agent.
2318    pub(crate) fn maybe_dispatch_simulated_click(
2319        &self,
2320        cx: &mut JSContext,
2321        node: &Node,
2322        event: &KeyboardEvent,
2323    ) {
2324        if event.key() != Key::Named(NamedKey::Enter) && event.original_code() != Some(Code::Space)
2325        {
2326            return;
2327        }
2328
2329        // Check whether this node is a state-changing element. Note that the specification doesn't
2330        // seem to have a good definition of what "state-changing" means, so we merely check to
2331        // see if the element is activatable here.
2332        //
2333        // However, an input that is text or password is activatable (to be able to click on it),
2334        // but hitting enter should be processed as a character rather than trigger a click. Hence
2335        // we ignore those
2336        if node
2337            .downcast::<Element>()
2338            .and_then(Element::as_maybe_activatable)
2339            .is_none() ||
2340            node.downcast::<HTMLInputElement>()
2341                .is_some_and(|input| input.is_textual_or_password())
2342        {
2343            return;
2344        }
2345
2346        node.fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
2347        event.upcast::<Event>().mark_as_handled();
2348    }
2349
2350    pub(crate) fn run_default_keydown_handler(
2351        &self,
2352        cx: &mut JSContext,
2353        event_target: &EventTarget,
2354        event: &EmbedderKeyboardEvent,
2355        input_event_result: InputEventResult,
2356    ) -> InputEventResult {
2357        let document = self.window.Document();
2358        let node = event_target
2359            .downcast::<Node>()
2360            .unwrap_or_else(|| document.upcast());
2361
2362        let event = &event.event;
2363        if let Some(editing_action) = editing_action_from_keyboard_event(event) {
2364            let editing_host = document.editing_context(cx.no_gc(), node);
2365            if editing_host.perform_editing_action(cx, editing_action) {
2366                return input_event_result | InputEventResult::Consumed;
2367            }
2368        }
2369
2370        if self.maybe_handle_accesskey(cx, event) {
2371            return input_event_result | InputEventResult::Consumed;
2372        }
2373
2374        let mut is_space = false;
2375        let scroll = match &event.key {
2376            Key::Named(NamedKey::ArrowDown) => KeyboardScroll::Down,
2377            Key::Named(NamedKey::ArrowLeft) => KeyboardScroll::Left,
2378            Key::Named(NamedKey::ArrowRight) => KeyboardScroll::Right,
2379            Key::Named(NamedKey::ArrowUp) => KeyboardScroll::Up,
2380            Key::Named(NamedKey::End) => KeyboardScroll::End,
2381            Key::Named(NamedKey::Home) => KeyboardScroll::Home,
2382            Key::Named(NamedKey::PageDown) => KeyboardScroll::PageDown,
2383            Key::Named(NamedKey::PageUp) => KeyboardScroll::PageUp,
2384            Key::Character(string) if string == " " => {
2385                is_space = true;
2386                if event.modifiers.contains(Modifiers::SHIFT) {
2387                    KeyboardScroll::PageUp
2388                } else {
2389                    KeyboardScroll::PageDown
2390                }
2391            },
2392            Key::Named(NamedKey::Tab) => {
2393                // From <https://w3c.github.io/uievents/#keydown>:
2394                //
2395                // > If the key is the Tab key, the default action MUST be to shift the document focus
2396                // > from the currently focused element (if any) to the new focused element, as
2397                // > described in Focus Event Types
2398                self.window
2399                    .Document()
2400                    .focus_handler()
2401                    .sequential_focus_navigation_via_keyboard_event(cx, event);
2402                return input_event_result | InputEventResult::Consumed;
2403            },
2404            _ => return input_event_result,
2405        };
2406
2407        if !event.modifiers.is_empty() && !is_space {
2408            return input_event_result;
2409        }
2410
2411        self.do_keyboard_scroll(cx, scroll);
2412        input_event_result | InputEventResult::Consumed
2413    }
2414
2415    pub(crate) fn do_keyboard_scroll(&self, cx: &mut JSContext, scroll: KeyboardScroll) {
2416        let scroll_axis = match scroll {
2417            KeyboardScroll::Left | KeyboardScroll::Right => ScrollingBoxAxis::X,
2418            _ => ScrollingBoxAxis::Y,
2419        };
2420
2421        let document = self.window.Document();
2422        let mut scrolling_box = document
2423            .focus_handler()
2424            .focused_area()
2425            .element()
2426            .or(self.most_recently_clicked_element.get().as_deref())
2427            .and_then(|element| element.scrolling_box(ScrollContainerQueryFlags::Inclusive))
2428            .unwrap_or_else(|| {
2429                document.viewport_scrolling_box(ScrollContainerQueryFlags::Inclusive)
2430            });
2431
2432        while !scrolling_box.can_keyboard_scroll_in_axis(cx, scroll_axis) {
2433            // Always fall back to trying to scroll the entire document.
2434            if scrolling_box.is_viewport() {
2435                break;
2436            }
2437            let parent = scrolling_box.parent().unwrap_or_else(|| {
2438                document.viewport_scrolling_box(ScrollContainerQueryFlags::Inclusive)
2439            });
2440            scrolling_box = parent;
2441        }
2442
2443        let calculate_current_scroll_offset_and_delta = |cx: &mut JSContext| {
2444            const LINE_HEIGHT: f32 = 76.0;
2445            const LINE_WIDTH: f32 = 76.0;
2446
2447            let current_scroll_offset = scrolling_box.scroll_position(cx);
2448            (
2449                current_scroll_offset,
2450                match scroll {
2451                    KeyboardScroll::Home => Vector2D::new(0.0, -current_scroll_offset.y),
2452                    KeyboardScroll::End => Vector2D::new(
2453                        0.0,
2454                        -current_scroll_offset.y + scrolling_box.content_size(cx).height -
2455                            scrolling_box.size(cx).height,
2456                    ),
2457                    KeyboardScroll::PageDown => {
2458                        Vector2D::new(0.0, scrolling_box.size(cx).height - 2.0 * LINE_HEIGHT)
2459                    },
2460                    KeyboardScroll::PageUp => {
2461                        Vector2D::new(0.0, 2.0 * LINE_HEIGHT - scrolling_box.size(cx).height)
2462                    },
2463                    KeyboardScroll::Up => Vector2D::new(0.0, -LINE_HEIGHT),
2464                    KeyboardScroll::Down => Vector2D::new(0.0, LINE_HEIGHT),
2465                    KeyboardScroll::Left => Vector2D::new(-LINE_WIDTH, 0.0),
2466                    KeyboardScroll::Right => Vector2D::new(LINE_WIDTH, 0.0),
2467                },
2468            )
2469        };
2470
2471        // If trying to scroll the viewport of this `Window` and this is the root `Document`
2472        // of the `WebView`, then send the srolling operation to the renderer, so that it
2473        // can properly pan any pinch zoom viewport.
2474        let parent_pipeline = self.window.parent_info();
2475        if scrolling_box.is_viewport() && parent_pipeline.is_none() {
2476            let (_, delta) = calculate_current_scroll_offset_and_delta(cx);
2477            self.window
2478                .paint_api()
2479                .scroll_viewport_by_delta(self.window.webview_id(), delta);
2480        }
2481
2482        // If this is the viewport and we cannot scroll, try to ask a parent viewport to scroll,
2483        // if we are inside an `<iframe>`.
2484        if !scrolling_box.can_keyboard_scroll_in_axis(cx, scroll_axis) {
2485            assert!(scrolling_box.is_viewport());
2486
2487            let window_proxy = document.window().window_proxy();
2488            if let Some(iframe) = window_proxy.frame_element() {
2489                // When the `<iframe>` is local (in this ScriptThread), we can
2490                // synchronously chain up the keyboard scrolling event.
2491                let iframe_window = iframe.owner_window();
2492                let mut realm = enter_auto_realm(cx, &*iframe_window);
2493                let cx = &mut realm;
2494                iframe_window
2495                    .Document()
2496                    .event_handler()
2497                    .do_keyboard_scroll(cx, scroll);
2498            } else if let Some(parent_pipeline) = parent_pipeline {
2499                // Otherwise, if we have a parent (presumably from a different origin)
2500                // asynchronously ask the Constellation to forward the event to the parent
2501                // pipeline, if we have one.
2502                document.window().send_to_constellation(
2503                    ScriptToConstellationMessage::ForwardKeyboardScroll(parent_pipeline, scroll),
2504                );
2505            };
2506            return;
2507        }
2508
2509        let (current_scroll_offset, delta) = calculate_current_scroll_offset_and_delta(cx);
2510        scrolling_box.scroll_to(cx, delta + current_scroll_offset, ScrollBehavior::Auto);
2511    }
2512
2513    /// Get or create a pointer ID for the given touch identifier.
2514    /// Returns the pointer ID to use for this touch.
2515    fn get_or_create_pointer_id_for_touch(&self, touch_id: i32) -> i32 {
2516        let mut active_pointer_ids = self.active_pointer_ids.borrow_mut();
2517
2518        if let Some(&pointer_id) = active_pointer_ids.get(&touch_id) {
2519            return pointer_id;
2520        }
2521
2522        let pointer_id = self.next_touch_pointer_id.get();
2523        active_pointer_ids.insert(touch_id, pointer_id);
2524        self.next_touch_pointer_id.set(pointer_id + 1);
2525        pointer_id
2526    }
2527
2528    /// Remove the pointer ID mapping for the given touch identifier.
2529    fn remove_pointer_id_for_touch(&self, touch_id: i32) {
2530        self.active_pointer_ids.borrow_mut().remove(&touch_id);
2531    }
2532
2533    /// Check if this is the primary pointer (for touch events).
2534    /// The first touch to make contact is the primary pointer.
2535    fn is_primary_pointer(&self, pointer_id: i32) -> bool {
2536        // For touch, the primary pointer is the one with the smallest pointer ID
2537        // that is still active.
2538        self.active_pointer_ids
2539            .borrow()
2540            .values()
2541            .min()
2542            .is_some_and(|primary_pointer| *primary_pointer == pointer_id)
2543    }
2544
2545    /// Fire pointerenter events hierarchically from topmost ancestor to target element.
2546    /// Fire pointerleave events hierarchically from target element to topmost ancestor.
2547    /// Used for touch devices that don't support hover.
2548    #[expect(clippy::too_many_arguments)]
2549    fn fire_pointer_event_for_touch(
2550        &self,
2551        cx: &mut JSContext,
2552        target_element: &Element,
2553        touch: &Touch,
2554        pointer_id: i32,
2555        event_name: &str,
2556        is_primary: bool,
2557        pointer_type: &str,
2558        input_event: &ConstellationInputEvent,
2559        hit_test_result: &HitTestResult,
2560    ) {
2561        let mut targets: Vec<_> = target_element
2562            .upcast::<Node>()
2563            .inclusive_ancestors_in_flat_tree_unrooted(cx.no_gc())
2564            .map(|node| node.as_rooted())
2565            .collect();
2566
2567        // Reverse to dispatch from topmost ancestor to target
2568        if event_name == "pointerenter" {
2569            targets.reverse();
2570        }
2571
2572        for target in targets {
2573            let pointer_event = touch.to_pointer_event(
2574                cx,
2575                &self.window,
2576                event_name,
2577                pointer_id,
2578                is_primary,
2579                pointer_type,
2580                input_event.active_keyboard_modifiers,
2581                false,
2582                Some(hit_test_result.point_in_node),
2583            );
2584            pointer_event.upcast::<Event>().fire(cx, target.upcast());
2585        }
2586    }
2587
2588    pub(crate) fn has_assigned_access_key(&self, element: &HTMLElement) -> bool {
2589        self.access_key_handlers
2590            .borrow()
2591            .values()
2592            .any(|value| &**value == element)
2593    }
2594
2595    pub(crate) fn unassign_access_key(&self, element: &HTMLElement) {
2596        self.access_key_handlers
2597            .borrow_mut()
2598            .retain(|_, value| &**value != element)
2599    }
2600
2601    pub(crate) fn assign_access_key(&self, element: &HTMLElement, code: Code) {
2602        let mut access_key_handlers = self.access_key_handlers.borrow_mut();
2603        // If an element is already assigned this access key, ignore the request.
2604        access_key_handlers
2605            .entry(code.into())
2606            .or_insert(Dom::from_ref(element));
2607    }
2608
2609    fn maybe_handle_accesskey(&self, cx: &mut JSContext, event: &KeyboardTypesEvent) -> bool {
2610        #[cfg(target_os = "macos")]
2611        let access_key_modifiers = Modifiers::CONTROL | Modifiers::ALT;
2612        #[cfg(not(target_os = "macos"))]
2613        let access_key_modifiers = Modifiers::SHIFT | Modifiers::ALT;
2614
2615        if event.modifiers != access_key_modifiers {
2616            return false;
2617        }
2618
2619        let Some(html_element) = self
2620            .access_key_handlers
2621            .borrow()
2622            .get(&event.code.into())
2623            .map(|html_element| html_element.as_rooted())
2624        else {
2625            return false;
2626        };
2627
2628        // From <https://html.spec.whatwg.org/multipage/#the-accesskey-attribute>:
2629        // > When the user presses the key combination corresponding to the assigned access key for
2630        // > an element, if the element defines a command, the command's Hidden State facet is false
2631        // > (visible), the command's Disabled State facet is also false (enabled), the element is in
2632        // > a document that has a non-null browsing context, and neither the element nor any of its
2633        // > ancestors has a hidden attribute specified, then the user agent must trigger the Action
2634        // > of the command.
2635        let Ok(command) = InteractiveElementCommand::try_from(&*html_element) else {
2636            return false;
2637        };
2638
2639        if command.disabled(cx) || command.hidden() {
2640            return false;
2641        }
2642
2643        let node = html_element.upcast::<Node>();
2644        if !node.is_connected() {
2645            return false;
2646        }
2647
2648        for node in node.inclusive_ancestors_unrooted(cx.no_gc(), ShadowIncluding::Yes) {
2649            if node
2650                .downcast::<HTMLElement>()
2651                .is_some_and(|html_element| html_element.Hidden())
2652            {
2653                return false;
2654            }
2655        }
2656
2657        // This behavior is unspecified, but all browsers do this. When activating the element it is
2658        // focused and scrolled into view.
2659        self.focus_and_scroll_to_element_for_key_event(cx, html_element.upcast());
2660        command.perform_action(cx);
2661        true
2662    }
2663
2664    pub(crate) fn focus_and_scroll_to_element_for_key_event(
2665        &self,
2666        cx: &mut JSContext,
2667        element: &Element,
2668    ) {
2669        element
2670            .upcast::<Node>()
2671            .run_the_focusing_steps(cx, None, FocusTrigger::Keyboard);
2672        let scroll_axis = ScrollAxisState {
2673            position: ScrollLogicalPosition::Center,
2674            requirement: ScrollRequirement::IfNotVisible,
2675        };
2676        element.scroll_into_view_with_options(
2677            cx,
2678            ScrollBehavior::Auto,
2679            scroll_axis,
2680            scroll_axis,
2681            None,
2682            None,
2683        );
2684    }
2685
2686    /// Check if a pointer ID corresponds to an active pointer.
2687    /// <https://w3c.github.io/pointerevents/#dfn-active-pointer>
2688    pub(crate) fn is_active_pointer(&self, pointer_id: i32) -> bool {
2689        if pointer_id == PointerId::Mouse as i32 {
2690            // Mouse is active when buttons are down
2691            !self.mouse_button_state.get().is_empty()
2692        } else {
2693            // Touch pointers are tracked in active_pointer_ids
2694            self.active_pointer_ids
2695                .borrow()
2696                .values()
2697                .any(|&id| id == pointer_id)
2698        }
2699    }
2700
2701    /// Set the pending pointer capture target override for a pointer.
2702    /// <https://w3c.github.io/pointerevents/#setting-pointer-capture>
2703    pub(crate) fn set_pending_pointer_capture(&self, pointer_id: i32, element: &Element) {
2704        self.pending_pointer_capture
2705            .borrow_mut()
2706            .insert(pointer_id, Dom::from_ref(element));
2707    }
2708
2709    /// Clear the pending pointer capture target override for a pointer.
2710    /// <https://w3c.github.io/pointerevents/#releasing-pointer-capture>
2711    pub(crate) fn clear_pending_pointer_capture(&self, pointer_id: i32) {
2712        self.pending_pointer_capture
2713            .borrow_mut()
2714            .remove(&pointer_id);
2715    }
2716
2717    /// Check if an element has pointer capture for a given pointer ID.
2718    /// <https://w3c.github.io/pointerevents/#dom-element-haspointercapture>
2719    pub(crate) fn has_pointer_capture(&self, pointer_id: i32, element: &Element) -> bool {
2720        self.pending_pointer_capture
2721            .borrow()
2722            .get(&pointer_id)
2723            .is_some_and(|el| &**el == element)
2724    }
2725
2726    /// Get the current pointer capture target for event dispatch.
2727    /// Returns the capture target if set and connected, otherwise None.
2728    /// This returns the actual/current target (pointer_capture_target),
2729    /// not the pending target that will be applied after process_pending.
2730    fn get_pointer_capture_target(&self, pointer_id: i32) -> Option<DomRoot<Element>> {
2731        self.pointer_capture_target
2732            .borrow()
2733            .get(&pointer_id)
2734            .map(|el| DomRoot::from_ref(&**el))
2735            .filter(|el| el.upcast::<Node>().is_connected())
2736    }
2737
2738    /// Check if the capture target is disconnected and release it if so.
2739    /// This fires lostpointercapture at the document per spec.
2740    /// Must be called before firing any pointer event.
2741    /// Returns true if a disconnected capture was released.
2742    /// <https://w3c.github.io/pointerevents/#process-pending-pointer-capture>
2743    fn release_disconnected_pointer_capture(
2744        &self,
2745        cx: &mut JSContext,
2746        pointer_id: i32,
2747        pointer_type: &str,
2748        is_primary: bool,
2749    ) -> bool {
2750        let capture_target = self
2751            .pointer_capture_target
2752            .borrow()
2753            .get(&pointer_id)
2754            .map(|el| DomRoot::from_ref(&**el));
2755        if let Some(capture_element) = capture_target &&
2756            !capture_element.upcast::<Node>().is_connected()
2757        {
2758            // Fire lostpointercapture at the document, not the disconnected element.
2759            let document = self.window.Document();
2760            self.fire_pointer_capture_event_at_target(
2761                cx,
2762                "lostpointercapture",
2763                pointer_id,
2764                pointer_type,
2765                is_primary,
2766                document.upcast::<EventTarget>(),
2767            );
2768            // Clear both pending and current capture
2769            self.pending_pointer_capture
2770                .safe_borrow_mut(cx.no_gc())
2771                .remove(&pointer_id);
2772            self.pointer_capture_target
2773                .safe_borrow_mut(cx.no_gc())
2774                .remove(&pointer_id);
2775            return true;
2776        }
2777        false
2778    }
2779
2780    /// Fire a gotpointercapture or lostpointercapture event at an Element.
2781    /// <https://w3c.github.io/pointerevents/#the-gotpointercapture-and-lostpointercapture-events>
2782    fn fire_pointer_capture_event(
2783        &self,
2784        cx: &mut JSContext,
2785        event_type: &str,
2786        pointer_id: i32,
2787        pointer_type: &str,
2788        is_primary: bool,
2789        target: &Element,
2790    ) {
2791        self.fire_pointer_capture_event_at_target(
2792            cx,
2793            event_type,
2794            pointer_id,
2795            pointer_type,
2796            is_primary,
2797            target.upcast::<EventTarget>(),
2798        );
2799    }
2800
2801    /// Fire a pointer capture event at a specific EventTarget (e.g., the document).
2802    fn fire_pointer_capture_event_at_target(
2803        &self,
2804        cx: &mut JSContext,
2805        event_type: &str,
2806        pointer_id: i32,
2807        pointer_type: &str,
2808        is_primary: bool,
2809        target: &EventTarget,
2810    ) {
2811        let pointer_event = PointerEvent::new(
2812            cx,
2813            &self.window,
2814            event_type.into(),
2815            EventBubbles::Bubbles,
2816            EventCancelable::NotCancelable,
2817            Some(&self.window),
2818            0,
2819            Point2D::new(0, 0),
2820            Point2D::new(0, 0),
2821            Point2D::new(0, 0),
2822            Modifiers::empty(),
2823            MouseButton::Primary,
2824            MouseButtons::empty(),
2825            None,
2826            None,
2827            pointer_id,
2828            1,
2829            1,
2830            0.0,
2831            0.0,
2832            0,
2833            0,
2834            0,
2835            PI / 2.0,
2836            0.0,
2837            DOMString::from(pointer_type),
2838            is_primary,
2839            &[],
2840            &[],
2841        );
2842        pointer_event.upcast::<Event>().set_composed(true);
2843        pointer_event.upcast::<Event>().fire(cx, target);
2844    }
2845
2846    /// Fire a single boundary `PointerEvent` (`pointerout`/`pointerleave`/
2847    /// `pointerover`/`pointerenter`) at `target`, with `related_target` set to
2848    /// the element being entered from or left to.
2849    #[expect(clippy::too_many_arguments)]
2850    fn fire_pointer_boundary_event(
2851        &self,
2852        cx: &mut JSContext,
2853        event_type: &str,
2854        bubbles: EventBubbles,
2855        pointer_id: i32,
2856        pointer_type: &str,
2857        is_primary: bool,
2858        target: &Element,
2859        related_target: Option<&Element>,
2860    ) {
2861        let pointer_event = PointerEvent::new(
2862            cx,
2863            &self.window,
2864            event_type.into(),
2865            bubbles,
2866            EventCancelable::NotCancelable,
2867            Some(&self.window),
2868            0,
2869            Point2D::new(0, 0),
2870            Point2D::new(0, 0),
2871            Point2D::new(0, 0),
2872            Modifiers::empty(),
2873            MouseButton::None,
2874            self.mouse_button_state.get(),
2875            related_target.map(|el| el.upcast::<EventTarget>()),
2876            None,
2877            pointer_id,
2878            1,
2879            1,
2880            0.0,
2881            0.0,
2882            0,
2883            0,
2884            0,
2885            PI / 2.0,
2886            0.0,
2887            DOMString::from(pointer_type),
2888            is_primary,
2889            &[],
2890            &[],
2891        );
2892        pointer_event.upcast::<Event>().set_composed(true);
2893        pointer_event.upcast::<Event>().fire(cx, target.upcast());
2894    }
2895
2896    /// Fire the pointer boundary events that accompany a pointer-capture
2897    /// transition from `old_target` to `new_target` for hoverable pointers.
2898    /// Per spec, only fired for pointer types that support hover (mouse, pen
2899    /// with hover); touch is skipped.
2900    fn fire_pointer_capture_boundary_transition(
2901        &self,
2902        cx: &mut JSContext,
2903        pointer_id: i32,
2904        pointer_type: &str,
2905        is_primary: bool,
2906        old_target: &Element,
2907        new_target: &Element,
2908    ) {
2909        if pointer_type != "mouse" {
2910            return;
2911        }
2912        if old_target == new_target {
2913            return;
2914        }
2915        self.fire_pointer_boundary_event(
2916            cx,
2917            "pointerout",
2918            EventBubbles::Bubbles,
2919            pointer_id,
2920            pointer_type,
2921            is_primary,
2922            old_target,
2923            Some(new_target),
2924        );
2925        self.fire_pointer_boundary_event(
2926            cx,
2927            "pointerleave",
2928            EventBubbles::DoesNotBubble,
2929            pointer_id,
2930            pointer_type,
2931            is_primary,
2932            old_target,
2933            Some(new_target),
2934        );
2935        self.fire_pointer_boundary_event(
2936            cx,
2937            "pointerover",
2938            EventBubbles::Bubbles,
2939            pointer_id,
2940            pointer_type,
2941            is_primary,
2942            new_target,
2943            Some(old_target),
2944        );
2945        self.fire_pointer_boundary_event(
2946            cx,
2947            "pointerenter",
2948            EventBubbles::DoesNotBubble,
2949            pointer_id,
2950            pointer_type,
2951            is_primary,
2952            new_target,
2953            Some(old_target),
2954        );
2955    }
2956
2957    /// Implicitly release pointer capture when pointer is lifted or canceled.
2958    /// <https://w3c.github.io/pointerevents/#implicit-release-of-pointer-capture>
2959    fn implicit_release_pointer_capture(
2960        &self,
2961        cx: &mut JSContext,
2962        pointer_id: i32,
2963        pointer_type: &str,
2964        is_primary: bool,
2965    ) {
2966        let capture_element = self
2967            .pointer_capture_target
2968            .borrow()
2969            .get(&pointer_id)
2970            .map(|el| DomRoot::from_ref(&**el));
2971        if let Some(capture_element) = capture_element {
2972            if capture_element.upcast::<Node>().is_connected() {
2973                self.fire_pointer_capture_event(
2974                    cx,
2975                    "lostpointercapture",
2976                    pointer_id,
2977                    pointer_type,
2978                    is_primary,
2979                    &capture_element,
2980                );
2981                // Boundary events: transition hover from released capture
2982                // target back to the actual hover target.
2983                if let Some(hover_target) = self.current_hover_target.get() {
2984                    self.fire_pointer_capture_boundary_transition(
2985                        cx,
2986                        pointer_id,
2987                        pointer_type,
2988                        is_primary,
2989                        &capture_element,
2990                        &hover_target,
2991                    );
2992                }
2993            } else {
2994                let document = self.window.Document();
2995                self.fire_pointer_capture_event_at_target(
2996                    cx,
2997                    "lostpointercapture",
2998                    pointer_id,
2999                    pointer_type,
3000                    is_primary,
3001                    document.upcast::<EventTarget>(),
3002                );
3003            }
3004        }
3005        self.pending_pointer_capture
3006            .safe_borrow_mut(cx.no_gc())
3007            .remove(&pointer_id);
3008        self.pointer_capture_target
3009            .safe_borrow_mut(cx.no_gc())
3010            .remove(&pointer_id);
3011    }
3012
3013    /// Process pending pointer capture before dispatching a pointer event.
3014    /// Fires gotpointercapture/lostpointercapture as needed.
3015    /// <https://w3c.github.io/pointerevents/#process-pending-pointer-capture>
3016    fn process_pending_pointer_capture(
3017        &self,
3018        cx: &mut JSContext,
3019        pointer_id: i32,
3020        pointer_type: &str,
3021        is_primary: bool,
3022    ) {
3023        let pending = self
3024            .pending_pointer_capture
3025            .borrow()
3026            .get(&pointer_id)
3027            .map(|el| DomRoot::from_ref(&**el));
3028        let current = self
3029            .pointer_capture_target
3030            .borrow()
3031            .get(&pointer_id)
3032            .map(|el| DomRoot::from_ref(&**el));
3033
3034        // Disconnected capture targets are handled by release_disconnected_pointer_capture
3035        // before any pointer event fires; by the time we get here they have been released.
3036        let pending_connected = pending
3037            .as_ref()
3038            .is_some_and(|el| el.upcast::<Node>().is_connected());
3039
3040        // If the pointer is no longer active (e.g., last button just released), we should
3041        // not fire gotpointercapture for new captures.
3042        let pointer_is_active = self.is_active_pointer(pointer_id);
3043
3044        match (&pending, &current) {
3045            (Some(pending_el), None) if pending_connected => {
3046                if pointer_is_active {
3047                    // Boundary events: transition hover from current hover target
3048                    // to the new capture target, before firing gotpointercapture.
3049                    if let Some(hover_target) = self.current_hover_target.get() {
3050                        self.fire_pointer_capture_boundary_transition(
3051                            cx,
3052                            pointer_id,
3053                            pointer_type,
3054                            is_primary,
3055                            &hover_target,
3056                            pending_el,
3057                        );
3058                    }
3059                    self.fire_pointer_capture_event(
3060                        cx,
3061                        "gotpointercapture",
3062                        pointer_id,
3063                        pointer_type,
3064                        is_primary,
3065                        pending_el,
3066                    );
3067                    self.pointer_capture_target
3068                        .safe_borrow_mut(cx.no_gc())
3069                        .insert(pointer_id, Dom::from_ref(pending_el));
3070                } else {
3071                    self.pending_pointer_capture
3072                        .safe_borrow_mut(cx.no_gc())
3073                        .remove(&pointer_id);
3074                }
3075            },
3076            (Some(pending_el), Some(current_el))
3077                if pending_connected && pending_el != current_el =>
3078            {
3079                self.fire_pointer_capture_event(
3080                    cx,
3081                    "lostpointercapture",
3082                    pointer_id,
3083                    pointer_type,
3084                    is_primary,
3085                    current_el,
3086                );
3087                if pointer_is_active {
3088                    self.fire_pointer_capture_boundary_transition(
3089                        cx,
3090                        pointer_id,
3091                        pointer_type,
3092                        is_primary,
3093                        current_el,
3094                        pending_el,
3095                    );
3096                    self.fire_pointer_capture_event(
3097                        cx,
3098                        "gotpointercapture",
3099                        pointer_id,
3100                        pointer_type,
3101                        is_primary,
3102                        pending_el,
3103                    );
3104                    self.pointer_capture_target
3105                        .safe_borrow_mut(cx.no_gc())
3106                        .insert(pointer_id, Dom::from_ref(pending_el));
3107                } else {
3108                    self.pending_pointer_capture
3109                        .safe_borrow_mut(cx.no_gc())
3110                        .remove(&pointer_id);
3111                    self.pointer_capture_target
3112                        .safe_borrow_mut(cx.no_gc())
3113                        .remove(&pointer_id);
3114                }
3115            },
3116            (None, Some(current_el)) | (Some(_), Some(current_el)) if !pending_connected => {
3117                self.fire_pointer_capture_event(
3118                    cx,
3119                    "lostpointercapture",
3120                    pointer_id,
3121                    pointer_type,
3122                    is_primary,
3123                    current_el,
3124                );
3125                // Boundary events: transition hover from released capture
3126                // target back to the actual hover target.
3127                if let Some(hover_target) = self.current_hover_target.get() {
3128                    self.fire_pointer_capture_boundary_transition(
3129                        cx,
3130                        pointer_id,
3131                        pointer_type,
3132                        is_primary,
3133                        current_el,
3134                        &hover_target,
3135                    );
3136                }
3137                self.pointer_capture_target
3138                    .safe_borrow_mut(cx.no_gc())
3139                    .remove(&pointer_id);
3140                if !pending_connected {
3141                    self.pending_pointer_capture
3142                        .safe_borrow_mut(cx.no_gc())
3143                        .remove(&pointer_id);
3144                }
3145            },
3146            _ => {},
3147        }
3148    }
3149
3150    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
3151    pub(crate) fn install_drag_gesture(&self, drag_gesture: DragGesture) {
3152        *self.drag_gesture.borrow_mut() = Some(drag_gesture);
3153    }
3154
3155    /// Maybe activate a link in this node or one of its ancestors when it is the target
3156    /// of an auxiliary click.
3157    fn maybe_activate_link_due_to_auxiliary_click(&self, cx: &mut JSContext, node: &Node) {
3158        let no_gc = cx.no_gc();
3159        let Some(url) = node
3160            .inclusive_ancestors_unrooted(no_gc, ShadowIncluding::Yes)
3161            .find_map(|node| {
3162                if let Some(anchor) = node.downcast::<HTMLAnchorElement>() {
3163                    return anchor.full_href_url_for_user_interface();
3164                }
3165                if let Some(area) = node.downcast::<HTMLAreaElement>() {
3166                    return area.full_href_url_for_user_interface();
3167                }
3168                None
3169            })
3170        else {
3171            return;
3172        };
3173        self.open_url_in_new_webview(cx, url);
3174    }
3175
3176    /// Open the URL in a new WebView, if possible.
3177    ///
3178    /// TODO: This should be sending a referrer and not setting `noopener`.
3179    pub(crate) fn open_url_in_new_webview(&self, cx: &mut JSContext, url: ServoUrl) {
3180        let Some(browsing_context) = self.window.document_unrooted(cx.no_gc()).browsing_context()
3181        else {
3182            return;
3183        };
3184        let (browsing_context, window_open_type) = browsing_context.choose_a_navigable(
3185            cx,
3186            &DOMString::from_static("_blank"),
3187            true, /* noopener */
3188        );
3189        let Some(browsing_context) = browsing_context else {
3190            return;
3191        };
3192        assert!(window_open_type != WindowOpenType::ExistingOrNone);
3193        let Some(target_document) = browsing_context.document() else {
3194            return;
3195        };
3196
3197        let target_window = target_document.window();
3198        let target = Trusted::new(target_window);
3199        let load_data = LoadData::new_for_new_unrelated_webview(url);
3200        let task = task!(open_link_in_new_webview: move |cx| {
3201            navigate(cx, &target.root(), NavigationHistoryBehavior::Replace, false, load_data);
3202        });
3203        target_document
3204            .owner_global()
3205            .task_manager()
3206            .dom_manipulation_task_source()
3207            .queue(task);
3208    }
3209
3210    fn fire_pointer_event(
3211        &self,
3212        cx: &mut JSContext,
3213        pointer_event: &PointerEvent,
3214        target: &EventTarget,
3215    ) -> bool {
3216        let result = pointer_event.upcast::<Event>().fire(cx, target);
3217        Self::light_dismiss_activities(cx, pointer_event, target);
3218        result
3219    }
3220
3221    /// <https://html.spec.whatwg.org/multipage/#run-light-dismiss-activities>
3222    ///
3223    /// target is passed explicitly, because it might not be set on event
3224    fn light_dismiss_activities(cx: &mut JSContext, event: &PointerEvent, target: &EventTarget) {
3225        // TODO: Step 1. Run light dismiss open popovers with event.
3226
3227        // Step 2. Run light dismiss open dialogs with event.
3228        HTMLDialogElement::light_dismiss_open_dialogs(cx, event, target);
3229    }
3230}
3231
3232/// Whether a given [`EmbedderKeyboardEvent`] should trigger a `keypress` event.
3233///
3234/// From <https://w3c.github.io/uievents/#keypress>:
3235/// > If supported by a user agent, this event MUST be dispatched when a key is pressed
3236/// > down, if and only if that key normally produces a character value. The keypress event
3237/// > type is device dependent and relies on the capabilities of the input devices and how
3238/// > they are mapped in the operating system.
3239fn keyboard_event_fires_keypress_event(keyboard_event: &EmbedderKeyboardEvent) -> bool {
3240    let is_character_value_key = matches!(
3241        keyboard_event.event.key,
3242        Key::Character(_) | Key::Named(NamedKey::Enter)
3243    );
3244    keyboard_event.event.state == KeyState::Down &&
3245        is_character_value_key &&
3246        !keyboard_event.event.is_composing
3247}
3248
3249pub(crate) fn character_to_code(character: char) -> Option<Code> {
3250    Some(match character.to_ascii_lowercase() {
3251        '`' => Code::Backquote,
3252        '\\' => Code::Backslash,
3253        '[' | '{' => Code::BracketLeft,
3254        ']' | '}' => Code::BracketRight,
3255        ',' | '<' => Code::Comma,
3256        '0' => Code::Digit0,
3257        '1' => Code::Digit1,
3258        '2' => Code::Digit2,
3259        '3' => Code::Digit3,
3260        '4' => Code::Digit4,
3261        '5' => Code::Digit5,
3262        '6' => Code::Digit6,
3263        '7' => Code::Digit7,
3264        '8' => Code::Digit8,
3265        '9' => Code::Digit9,
3266        '=' => Code::Equal,
3267        'a' => Code::KeyA,
3268        'b' => Code::KeyB,
3269        'c' => Code::KeyC,
3270        'd' => Code::KeyD,
3271        'e' => Code::KeyE,
3272        'f' => Code::KeyF,
3273        'g' => Code::KeyG,
3274        'h' => Code::KeyH,
3275        'i' => Code::KeyI,
3276        'j' => Code::KeyJ,
3277        'k' => Code::KeyK,
3278        'l' => Code::KeyL,
3279        'm' => Code::KeyM,
3280        'n' => Code::KeyN,
3281        'o' => Code::KeyO,
3282        'p' => Code::KeyP,
3283        'q' => Code::KeyQ,
3284        'r' => Code::KeyR,
3285        's' => Code::KeyS,
3286        't' => Code::KeyT,
3287        'u' => Code::KeyU,
3288        'v' => Code::KeyV,
3289        'w' => Code::KeyW,
3290        'x' => Code::KeyX,
3291        'y' => Code::KeyY,
3292        'z' => Code::KeyZ,
3293        '-' => Code::Minus,
3294        '.' => Code::Period,
3295        '\'' | '"' => Code::Quote,
3296        ';' => Code::Semicolon,
3297        '/' => Code::Slash,
3298        ' ' => Code::Space,
3299        _ => return None,
3300    })
3301}