Skip to main content

embedder_traits/
input_events.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::sync::atomic::{AtomicUsize, Ordering};
6
7use bitflags::bitflags;
8use keyboard_types::{Code, Key, KeyState, Location, Modifiers};
9use malloc_size_of_derive::MallocSizeOf;
10use serde::{Deserialize, Serialize};
11
12use crate::WebViewPoint;
13
14/// An opaque id for an [`InputEvent`].
15#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
16pub struct InputEventId(usize);
17
18static INPUT_EVENT_ID: AtomicUsize = AtomicUsize::new(0);
19
20impl InputEventId {
21    fn new() -> Self {
22        Self(INPUT_EVENT_ID.fetch_add(1, Ordering::Relaxed))
23    }
24}
25
26bitflags! {
27    /// Flags representing the state of an [`InputEvent`] after Servo has handled it.
28    #[derive(Clone, Copy, Default, Deserialize, PartialEq, Serialize)]
29    pub struct InputEventResult: u8 {
30        /// Whether or not this input event's default behavior was prevented via script.
31        const DefaultPrevented = 1 << 0;
32        /// Whether or not the WebView handled this event. Some events have default handlers in
33        /// Servo, such as keyboard events that insert characters in `<input>` areas. When these
34        /// handlers are triggered, this flag is included. This can be used to prevent triggering
35        /// behavior (such as keybindings) when the WebView has already consumed the event for its
36        /// own purpose.
37        const Consumed = 1 << 1;
38        /// Whether or not the input event failed to dispatch. This can happen when an event
39        /// is sent while Servo is shutting down or when it is in an intermediate state.
40        /// Typically these events should be considered to be consumed.
41        const DispatchFailed = 1 << 2;
42    }
43}
44
45#[derive(Deserialize, Serialize)]
46pub struct InputEventOutcome {
47    pub id: InputEventId,
48    pub result: InputEventResult,
49}
50
51/// An input event that is sent from the embedder to Servo.
52#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
53pub enum InputEvent {
54    EditingAction(ClipboardAction),
55    #[cfg(feature = "gamepad")]
56    Gamepad(GamepadEvent),
57    Ime(ImeEvent),
58    Keyboard(KeyboardEvent),
59    MouseButton(MouseButtonEvent),
60    MouseLeftViewport(MouseLeftViewportEvent),
61    MouseMove(MouseMoveEvent),
62    Touch(TouchEvent),
63    Wheel(WheelEvent),
64}
65
66#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
67pub struct InputEventAndId {
68    pub event: InputEvent,
69    pub id: InputEventId,
70}
71
72impl From<InputEvent> for InputEventAndId {
73    fn from(event: InputEvent) -> Self {
74        Self {
75            event,
76            id: InputEventId::new(),
77        }
78    }
79}
80
81/// A direction for an [`EditingAction`].
82#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
83pub enum EditingDirection {
84    Forward,
85    Backward,
86}
87
88/// Describes a unit of movement for an [`EditingAction`].
89#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
90pub enum EditingMotion {
91    Character,
92    Grapheme,
93    Word,
94    Line,
95    LineStartOrEnd,
96    Page,
97    DocumentStartOrEnd,
98}
99
100/// Whether the selection should follow cursor motion when doing an editing action.
101#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
102pub enum ModifySelection {
103    Yes,
104    No,
105}
106
107/// Which type of clipboard operation should be performed for an [`EditingAction::Clipboard`].
108#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
109pub enum ClipboardAction {
110    Copy,
111    Cut,
112    Paste,
113}
114
115/// An action to perform in an [`EditingContext`].
116///
117/// This is public because it is used in external unit tests.
118#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
119pub enum EditingAction {
120    Backspace(EditingMotion),
121    Clipboard(ClipboardAction),
122    Delete,
123    DeleteSurroundingBefore(usize),
124    DeleteSurroundingAfter(usize),
125    EndComposition,
126    InsertCompositionText(String),
127    InsertNewline,
128    InsertParagraph,
129    InsertText(String),
130    MoveCursor(EditingDirection, EditingMotion, ModifySelection),
131    SelectAll,
132    SetCompositionCursor(Option<(usize, usize)>),
133    StartComposition,
134}
135
136impl InputEvent {
137    pub fn point(&self) -> Option<WebViewPoint> {
138        match self {
139            InputEvent::EditingAction(..) => None,
140            #[cfg(feature = "gamepad")]
141            InputEvent::Gamepad(..) => None,
142            InputEvent::Ime(..) => None,
143            InputEvent::Keyboard(..) => None,
144            InputEvent::MouseButton(event) => Some(event.point),
145            InputEvent::MouseMove(event) => Some(event.point),
146            InputEvent::MouseLeftViewport(_) => None,
147            InputEvent::Touch(event) => Some(event.point),
148            InputEvent::Wheel(event) => Some(event.point),
149        }
150    }
151}
152
153#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
154pub struct KeyboardEvent {
155    pub event: ::keyboard_types::KeyboardEvent,
156}
157
158impl KeyboardEvent {
159    pub fn new(keyboard_event: ::keyboard_types::KeyboardEvent) -> Self {
160        Self {
161            event: keyboard_event,
162        }
163    }
164
165    pub fn new_without_event(
166        state: KeyState,
167        key: Key,
168        code: Code,
169        location: Location,
170        modifiers: Modifiers,
171        repeat: bool,
172        is_composing: bool,
173    ) -> Self {
174        Self::new(::keyboard_types::KeyboardEvent {
175            state,
176            key,
177            code,
178            location,
179            modifiers,
180            repeat,
181            is_composing,
182        })
183    }
184
185    pub fn from_state_and_key(state: KeyState, key: Key) -> Self {
186        Self::new(::keyboard_types::KeyboardEvent {
187            state,
188            key,
189            ..::keyboard_types::KeyboardEvent::default()
190        })
191    }
192}
193
194#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
195pub struct MouseButtonEvent {
196    pub action: MouseButtonAction,
197    pub button: MouseButton,
198    pub point: WebViewPoint,
199    #[doc(hidden)]
200    // An internal flag marking a compatibility mouse event synthesized for a
201    // touch/pen tap. Such events must not generate pointer events.
202    pub is_compatibility_event_for_touch: bool,
203}
204
205impl MouseButtonEvent {
206    pub fn new(action: MouseButtonAction, button: MouseButton, point: WebViewPoint) -> Self {
207        Self {
208            action,
209            button,
210            point,
211            is_compatibility_event_for_touch: false,
212        }
213    }
214
215    #[doc(hidden)]
216    pub fn new_compatibility_for_touch(
217        action: MouseButtonAction,
218        button: MouseButton,
219        point: WebViewPoint,
220    ) -> Self {
221        Self {
222            action,
223            button,
224            point,
225            is_compatibility_event_for_touch: true,
226        }
227    }
228}
229
230/// The types of mouse buttons.
231///
232/// <https://w3c.github.io/pointerevents/#the-button-property>
233#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
234pub enum MouseButton {
235    #[doc(hidden)]
236    None,
237    Primary,
238    Auxiliary,
239    Secondary,
240    Back,
241    Forward,
242    Other(u16),
243}
244
245impl<T: Into<i128>> From<T> for MouseButton {
246    fn from(value: T) -> Self {
247        let value = value.into();
248        match value {
249            -1 => MouseButton::None,
250            0 => MouseButton::Primary,
251            1 => MouseButton::Auxiliary,
252            2 => MouseButton::Secondary,
253            3 => MouseButton::Back,
254            4 => MouseButton::Forward,
255            _ => MouseButton::Other(value as u16),
256        }
257    }
258}
259
260impl From<MouseButton> for i16 {
261    fn from(value: MouseButton) -> Self {
262        match value {
263            MouseButton::None => -1,
264            MouseButton::Primary => 0,
265            MouseButton::Auxiliary => 1,
266            MouseButton::Secondary => 2,
267            MouseButton::Back => 3,
268            MouseButton::Forward => 4,
269            MouseButton::Other(value) => value as i16,
270        }
271    }
272}
273
274/// The types of mouse events.
275#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
276pub enum MouseButtonAction {
277    /// Mouse button down.
278    Down,
279    /// Mouse button up.
280    Up,
281}
282
283#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
284pub struct MouseMoveEvent {
285    pub point: WebViewPoint,
286    #[doc(hidden)]
287    // An internal flag used to avoid refreshing the cursor in response to move
288    // events for touch devices since they are simulated in Servo using mouse events.
289    pub is_compatibility_event_for_touch: bool,
290}
291
292impl MouseMoveEvent {
293    pub fn new(point: WebViewPoint) -> Self {
294        Self {
295            point,
296            is_compatibility_event_for_touch: false,
297        }
298    }
299
300    #[doc(hidden)]
301    pub fn new_compatibility_for_touch(point: WebViewPoint) -> Self {
302        Self {
303            point,
304            is_compatibility_event_for_touch: true,
305        }
306    }
307}
308
309#[derive(Clone, Copy, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
310pub struct MouseLeftViewportEvent {
311    pub focus_moving_to_another_iframe: bool,
312}
313
314/// The type of input represented by a multi-touch event.
315#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
316pub enum TouchEventType {
317    /// A new touch point came in contact with the screen.
318    Down,
319    /// An existing touch point changed location.
320    Move,
321    /// A touch point was removed from the screen.
322    Up,
323    /// The system stopped tracking a touch point.
324    Cancel,
325}
326
327/// An opaque identifier for a touch point.
328///
329/// <http://w3c.github.io/touch-events/#widl-Touch-identifier>
330#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
331pub struct TouchId(pub i32);
332
333/// Distinguishes the kind of physical input that produced a [`TouchEvent`].
334/// Servo routes both pen and finger-touch input through the touch event path,
335/// but the originating subtype determines the `pointerType` reported to script.
336#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
337pub enum TouchPointerType {
338    Pen,
339    Touch,
340}
341
342#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
343pub struct TouchEvent {
344    pub event_type: TouchEventType,
345    pub touch_id: TouchId,
346    pub point: WebViewPoint,
347    pub pointer_type: TouchPointerType,
348    /// cancelable default value is true, once the first move has been processed by script disable it.
349    cancelable: bool,
350    /// Whether this `touchend` should generate the compatibility mouse events.
351    pub can_synthesize_mouse_events: bool,
352}
353
354impl TouchEvent {
355    pub fn new(
356        event_type: TouchEventType,
357        touch_id: TouchId,
358        point: WebViewPoint,
359        pointer_type: TouchPointerType,
360    ) -> Self {
361        TouchEvent {
362            event_type,
363            touch_id,
364            point,
365            pointer_type,
366            cancelable: true,
367            can_synthesize_mouse_events: false,
368        }
369    }
370
371    #[doc(hidden)]
372    pub fn disable_cancelable(&mut self) {
373        self.cancelable = false;
374    }
375
376    #[doc(hidden)]
377    pub fn is_cancelable(&self) -> bool {
378        self.cancelable
379    }
380}
381
382/// Unit of a [`WheelDelta`].
383#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
384pub enum WheelMode {
385    /// Delta values are specified in pixels.
386    DeltaPixel = 0x00,
387    /// Delta values are specified in lines.
388    DeltaLine = 0x01,
389    /// Delta values are specified in pages.
390    DeltaPage = 0x02,
391}
392
393/// The wheel event deltas for every direction.
394#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
395pub struct WheelDelta {
396    /// Delta in the left/right direction. A positive value means that the view scrolls left,
397    /// revealing more content to the left of the current viewport.
398    pub x: f64,
399    /// Delta in the up/down direction. A positive value means that the view scrolls up, revealing
400    /// more content above the current viewport.
401    pub y: f64,
402    /// Delta in the direction going into/out of the screen
403    pub z: f64,
404    /// Mode to measure the floats in
405    pub mode: WheelMode,
406}
407
408#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
409pub struct WheelEvent {
410    pub delta: WheelDelta,
411    pub point: WebViewPoint,
412}
413
414impl WheelEvent {
415    /// Create a new [`WheelEvent`]. The modifiers passed should be the current set
416    /// of keyboard modifiers. This is used to adjust the scroll direction with the
417    /// modifiers.
418    pub fn new(mut delta: WheelDelta, point: WebViewPoint, modifiers: Modifiers) -> Self {
419        // If this is a purely vertical scroll, then the shift key should turn it into
420        // a horizontal scroll. Some platforms might do the rotation on their on so it's
421        // important not to unrotate accidentally.
422        if modifiers.contains(Modifiers::SHIFT) && delta.x == 0. && delta.z == 0. {
423            std::mem::swap(&mut delta.x, &mut delta.y);
424        }
425        WheelEvent { delta, point }
426    }
427}
428
429/// The types of an input method event.
430#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
431pub enum ImeEvent {
432    /// Update the composing text of the IME. The second parameter contains the UTF-8 byte offsets
433    /// of the start and end of the selection that should be highlighted, relative to the composing
434    /// text (the same value indicates a caret).
435    Update(String, Option<(usize, usize)>),
436    /// Commit the current state of the IME, ending the composition.
437    ///
438    /// Note that this can be sent without an active text composition, which treats it as a text
439    /// insertion.
440    Commit(String),
441    /// Delete the given number of UTF-8 bytes before the start of the selection and after the end
442    /// of the selection, while leaving the selection itself untouched.
443    DeleteSurrounding { before: usize, after: usize },
444    /// The user dismissed the IME unilaterally.
445    Dismissed,
446}
447
448impl ImeEvent {
449    /// Returns true if and only if the `ImeEvent` corresponds to the end of a composition session.
450    pub fn is_terminating(&self) -> bool {
451        match self {
452            ImeEvent::Update(string, _) if string.is_empty() => true,
453            ImeEvent::Commit(..) => true,
454            _ => false,
455        }
456    }
457}
458
459#[cfg(feature = "gamepad")]
460#[derive(
461    Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize,
462)]
463/// Index of gamepad in list of system's connected gamepads.
464pub struct GamepadIndex(pub usize);
465
466#[cfg(feature = "gamepad")]
467#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
468/// The minimum and maximum values that can be reported for axis or button input from this gamepad.
469pub struct GamepadInputBounds {
470    /// Minimum and maximum axis values.
471    pub axis_bounds: (f64, f64),
472    /// Minimum and maximum button values.
473    pub button_bounds: (f64, f64),
474}
475
476#[cfg(feature = "gamepad")]
477#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
478/// The haptic effects supported by this gamepad.
479pub struct GamepadSupportedHapticEffects {
480    /// Whether gamepad has support for dual rumble effects.
481    pub supports_dual_rumble: bool,
482    /// Whether gamepad has support for trigger rumble effects.
483    pub supports_trigger_rumble: bool,
484}
485
486#[cfg(feature = "gamepad")]
487#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
488/// The types of Gamepad event.
489pub enum GamepadEvent {
490    /// A new gamepad has been connected.
491    ///
492    /// <https://www.w3.org/TR/gamepad/#event-gamepadconnected>
493    Connected(
494        GamepadIndex,
495        String,
496        GamepadInputBounds,
497        GamepadSupportedHapticEffects,
498    ),
499    /// An existing gamepad has been disconnected.
500    ///
501    /// <https://www.w3.org/TR/gamepad/#event-gamepaddisconnected>
502    Disconnected(GamepadIndex),
503    /// An existing gamepad has been updated.
504    ///
505    /// <https://www.w3.org/TR/gamepad/#receiving-inputs>
506    Updated(GamepadIndex, GamepadUpdateType),
507}
508
509#[cfg(feature = "gamepad")]
510#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
511/// The type of Gamepad input being updated.
512pub enum GamepadUpdateType {
513    /// Axis index and input value.
514    ///
515    /// <https://www.w3.org/TR/gamepad/#dfn-represents-a-standard-gamepad-axis>
516    Axis(usize, f64),
517    /// Button index and input value.
518    ///
519    /// <https://www.w3.org/TR/gamepad/#dfn-represents-a-standard-gamepad-button>
520    Button(usize, f64),
521}