Skip to main content

gpui/
interactive.rs

1use crate::{
2    BackGestureEvent, Bounds, Capslock, Context, Empty, IntoElement, Keystroke, LongPressEvent,
3    Modifiers, Pixels, Point, Render, TouchDragEvent, Window, point, seal::Sealed,
4};
5use smallvec::SmallVec;
6use std::{any::Any, fmt::Debug, ops::Deref, path::PathBuf};
7
8/// An event from a platform input source.
9pub trait InputEvent: Sealed + 'static {
10    /// Convert this event into the platform input enum.
11    fn to_platform_input(self) -> PlatformInput;
12}
13
14/// A key event from the platform.
15pub trait KeyEvent: InputEvent {}
16
17/// A mouse event from the platform.
18pub trait MouseEvent: InputEvent {}
19
20/// A gesture event from the platform.
21pub trait GestureEvent: InputEvent {}
22
23/// The key down event equivalent for the platform.
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct KeyDownEvent {
26    /// The keystroke that was generated.
27    pub keystroke: Keystroke,
28
29    /// Whether the key is currently held down.
30    pub is_held: bool,
31
32    /// Whether to prefer character input over keybindings for this keystroke.
33    /// In some cases, like AltGr on Windows, modifiers are significant for character input.
34    pub prefer_character_input: bool,
35}
36
37impl Sealed for KeyDownEvent {}
38impl InputEvent for KeyDownEvent {
39    fn to_platform_input(self) -> PlatformInput {
40        PlatformInput::KeyDown(self)
41    }
42}
43impl KeyEvent for KeyDownEvent {}
44
45/// The key up event equivalent for the platform.
46#[derive(Clone, Debug)]
47pub struct KeyUpEvent {
48    /// The keystroke that was released.
49    pub keystroke: Keystroke,
50}
51
52impl Sealed for KeyUpEvent {}
53impl InputEvent for KeyUpEvent {
54    fn to_platform_input(self) -> PlatformInput {
55        PlatformInput::KeyUp(self)
56    }
57}
58impl KeyEvent for KeyUpEvent {}
59
60/// The modifiers changed event equivalent for the platform.
61#[derive(Clone, Debug, Default)]
62pub struct ModifiersChangedEvent {
63    /// The new state of the modifier keys
64    pub modifiers: Modifiers,
65    /// The new state of the capslock key
66    pub capslock: Capslock,
67}
68
69impl Sealed for ModifiersChangedEvent {}
70impl InputEvent for ModifiersChangedEvent {
71    fn to_platform_input(self) -> PlatformInput {
72        PlatformInput::ModifiersChanged(self)
73    }
74}
75impl KeyEvent for ModifiersChangedEvent {}
76
77impl Deref for ModifiersChangedEvent {
78    type Target = Modifiers;
79
80    fn deref(&self) -> &Self::Target {
81        &self.modifiers
82    }
83}
84
85/// The phase of a touch motion event.
86/// Based on the winit enum of the same name.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88pub enum TouchPhase {
89    /// The touch started.
90    Started,
91    /// The touch event is moving.
92    #[default]
93    Moved,
94    /// The touch phase has ended
95    Ended,
96    /// The touch was cancelled: the system took it and it will not end
97    /// normally. Consumers must fully unwind any in-progress interaction,
98    /// treating the touch as if it never committed.
99    Cancelled,
100}
101
102/// Identifies one touch (finger or stylus contact) for its lifetime, from
103/// [`TouchPhase::Started`] through [`TouchPhase::Ended`] or
104/// [`TouchPhase::Cancelled`].
105///
106/// The value is opaque and assigned by the platform. A platform window must
107/// not reuse an identifier for a later touch.
108#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
109pub struct TouchId(pub u64);
110
111/// A raw touch event from the platform.
112///
113///
114/// Dispatch contract (core implementation pending): a touch is hit-tested
115/// once, at [`TouchPhase::Started`], occlusion-aware; all subsequent events
116/// for the same [`TouchId`] are delivered to the elements under the starting
117/// position, even after the touch moves outside them.
118#[derive(Clone, Debug, Default)]
119pub struct TouchEvent {
120    /// Which touch this event belongs to.
121    pub id: TouchId,
122    /// The phase of the touch.
123    pub phase: TouchPhase,
124    /// The position of the touch in window coordinates.
125    pub position: Point<Pixels>,
126    /// Where the platform predicts the touch will be roughly one frame from
127    /// now, in the same coordinate space as `position`, when the platform
128    /// offers a prediction for a [`TouchPhase::Moved`] event.
129    ///
130    /// Best-effort latency compensation only: it may influence how far a
131    /// recognized pan scrolls within a frame, but never hit testing, gesture
132    /// classification, or velocity estimation, and any error it introduces
133    /// must be corrected by later events for the same touch.
134    pub predicted_position: Option<Point<Pixels>>,
135    /// Normalized touch force in `0.0..=1.0`, if the hardware reports it.
136    pub force: Option<f32>,
137}
138
139impl Sealed for TouchEvent {}
140impl InputEvent for TouchEvent {
141    fn to_platform_input(self) -> PlatformInput {
142        PlatformInput::Touch(self)
143    }
144}
145
146/// A mouse down event from the platform
147#[derive(Clone, Debug, Default)]
148pub struct MouseDownEvent {
149    /// Which mouse button was pressed.
150    pub button: MouseButton,
151
152    /// The position of the mouse on the window.
153    pub position: Point<Pixels>,
154
155    /// The modifiers that were held down when the mouse was pressed.
156    pub modifiers: Modifiers,
157
158    /// The number of times the button has been clicked.
159    pub click_count: usize,
160
161    /// Whether this is the first, focusing click.
162    pub first_mouse: bool,
163}
164
165impl Sealed for MouseDownEvent {}
166impl InputEvent for MouseDownEvent {
167    fn to_platform_input(self) -> PlatformInput {
168        PlatformInput::MouseDown(self)
169    }
170}
171impl MouseEvent for MouseDownEvent {}
172
173impl MouseDownEvent {
174    /// Returns true if this mouse up event should focus the element.
175    pub fn is_focusing(&self) -> bool {
176        match self.button {
177            MouseButton::Left => true,
178            _ => false,
179        }
180    }
181}
182
183/// A mouse up event from the platform
184#[derive(Clone, Debug, Default)]
185pub struct MouseUpEvent {
186    /// Which mouse button was released.
187    pub button: MouseButton,
188
189    /// The position of the mouse on the window.
190    pub position: Point<Pixels>,
191
192    /// The modifiers that were held down when the mouse was released.
193    pub modifiers: Modifiers,
194
195    /// The number of times the button has been clicked.
196    pub click_count: usize,
197}
198
199impl Sealed for MouseUpEvent {}
200impl InputEvent for MouseUpEvent {
201    fn to_platform_input(self) -> PlatformInput {
202        PlatformInput::MouseUp(self)
203    }
204}
205
206impl MouseEvent for MouseUpEvent {}
207
208impl MouseUpEvent {
209    /// Returns true if this mouse up event should focus the element.
210    pub fn is_focusing(&self) -> bool {
211        match self.button {
212            MouseButton::Left => true,
213            _ => false,
214        }
215    }
216}
217
218/// A click event, generated when a mouse button is pressed and released.
219#[derive(Clone, Debug, Default)]
220pub struct MouseClickEvent {
221    /// The mouse event when the button was pressed.
222    pub down: MouseDownEvent,
223
224    /// The mouse event when the button was released.
225    pub up: MouseUpEvent,
226}
227
228/// The stage of a pressure click event.
229#[derive(Clone, Copy, Debug, Default, PartialEq)]
230pub enum PressureStage {
231    /// No pressure.
232    #[default]
233    Zero,
234    /// Normal click pressure.
235    Normal,
236    /// High pressure, enough to trigger a force click.
237    Force,
238}
239
240/// A mouse pressure event from the platform. Generated when a force-sensitive trackpad is pressed hard.
241/// Currently only implemented for macOS trackpads.
242#[derive(Debug, Clone, Default)]
243pub struct MousePressureEvent {
244    /// Pressure of the current stage as a float between 0 and 1
245    pub pressure: f32,
246    /// The pressure stage of the event.
247    pub stage: PressureStage,
248    /// The position of the mouse on the window.
249    pub position: Point<Pixels>,
250    /// The modifiers that were held down when the mouse pressure changed.
251    pub modifiers: Modifiers,
252}
253
254impl Sealed for MousePressureEvent {}
255impl InputEvent for MousePressureEvent {
256    fn to_platform_input(self) -> PlatformInput {
257        PlatformInput::MousePressure(self)
258    }
259}
260impl MouseEvent for MousePressureEvent {}
261
262/// One stylus reading, in window coordinates.
263#[derive(Clone, Copy, Debug, Default, PartialEq)]
264pub struct PenSample {
265    /// Where the tip is.
266    pub position: Point<Pixels>,
267    /// Tip force, `0.0..=1.0`; 0 while hovering.
268    pub pressure: f32,
269    /// Barrel wheel or finger pressure, `-1.0..=1.0`; 0 when the pen has none.
270    pub tangential_pressure: f32,
271    /// Tilt toward +x (right), degrees in `-90.0..=90.0`.
272    pub tilt_x: f32,
273    /// Tilt toward +y (down), degrees in `-90.0..=90.0`.
274    pub tilt_y: f32,
275    /// Clockwise rotation about the pen's axis, degrees in `0.0..360.0`.
276    pub twist: f32,
277    /// Contact size in logical pixels; 0 when the hardware does not say.
278    pub width: f32,
279    /// Contact size in logical pixels; 0 when the hardware does not say.
280    pub height: f32,
281    /// When the hardware took the reading; `None` when the platform does not say.
282    pub time: Option<std::time::Instant>,
283}
284
285/// What a pen adds to the mouse event it stands for.
286#[derive(Clone, Debug, Default, PartialEq)]
287pub struct PenInput {
288    /// Identifies the pen while it is in range; assigned by the platform.
289    pub pointer_id: u32,
290    /// The eraser end is the one in use.
291    pub eraser: bool,
292    /// The barrel button is held.
293    pub barrel: bool,
294    /// The tip (or eraser) touches the surface.
295    pub in_contact: bool,
296    /// The latest reading.
297    pub sample: PenSample,
298    /// Earlier readings this event folds in, oldest first, without `sample`.
299    pub history: Vec<PenSample>,
300}
301
302/// The mouse event a pen event is dispatched as.
303#[derive(Clone, Debug)]
304pub enum PenAction {
305    /// The tip touched, or a barrel press with the tip down.
306    Down(MouseDownEvent),
307    /// The tip lifted.
308    Up(MouseUpEvent),
309    /// The pen moved, touching or hovering in range.
310    Move(MouseMoveEvent),
311    /// The pen left the window or the tablet's range.
312    Exited(MouseExitEvent),
313}
314
315/// Stylus input from the platform: dispatched as its mouse event, with the pen's data available
316/// from [`Window::vn_pen`] while it and later pen events are handled.
317#[derive(Clone, Debug)]
318pub struct PenEvent {
319    /// The mouse event gpui dispatches.
320    pub action: PenAction,
321    /// The stylus data.
322    pub pen: PenInput,
323}
324
325impl PenEvent {
326    pub(crate) fn into_mouse(self) -> (PlatformInput, PenInput) {
327        let input = match self.action {
328            PenAction::Down(e) => PlatformInput::MouseDown(e),
329            PenAction::Up(e) => PlatformInput::MouseUp(e),
330            PenAction::Move(e) => PlatformInput::MouseMove(e),
331            PenAction::Exited(e) => PlatformInput::MouseExited(e),
332        };
333        (input, self.pen)
334    }
335}
336
337impl Sealed for PenEvent {}
338impl InputEvent for PenEvent {
339    fn to_platform_input(self) -> PlatformInput {
340        PlatformInput::Pen(self)
341    }
342}
343
344/// A click event that was generated by a keyboard button being pressed and released.
345#[derive(Clone, Debug, Default)]
346pub struct KeyboardClickEvent {
347    /// The keyboard button that was pressed to trigger the click.
348    pub button: KeyboardButton,
349
350    /// The bounds of the element that was clicked.
351    pub bounds: Bounds<Pixels>,
352}
353
354/// A click event that was generated by a recognized tap gesture on a touch
355/// screen.
356#[derive(Clone, Debug, Default)]
357pub struct TouchClickEvent {
358    /// The position of the tap in window coordinates.
359    pub position: Point<Pixels>,
360    /// The number of consecutive taps at this location (double tap = 2),
361    /// analogous to the mouse `click_count`.
362    pub tap_count: usize,
363    /// Whether this was a long press rather than a tap. Long presses are
364    /// touch's secondary activation: they are delivered to aux-click
365    /// listeners alongside right clicks, not to primary click listeners.
366    pub long_press: bool,
367}
368
369/// A click event, generated when a mouse button or keyboard button is pressed and released,
370/// or when a tap gesture is recognized on a touch screen.
371#[derive(Clone, Debug)]
372pub enum ClickEvent {
373    /// A click event trigger by a mouse button being pressed and released.
374    Mouse(MouseClickEvent),
375    /// A click event trigger by a keyboard button being pressed and released.
376    Keyboard(KeyboardClickEvent),
377    /// A click event triggered by a recognized tap gesture on a touch screen.
378    Touch(TouchClickEvent),
379}
380
381impl Default for ClickEvent {
382    fn default() -> Self {
383        ClickEvent::Keyboard(KeyboardClickEvent::default())
384    }
385}
386
387impl ClickEvent {
388    /// Returns the modifiers that were held during the click event
389    ///
390    /// `Keyboard`: The keyboard click events never have modifiers.
391    /// `Mouse`: Modifiers that were held during the mouse key up event.
392    pub fn modifiers(&self) -> Modifiers {
393        match self {
394            // Click events are only generated from keyboard events _without any modifiers_, so we know the modifiers are always Default
395            ClickEvent::Keyboard(_) => Modifiers::default(),
396            // Click events on the web only reflect the modifiers for the keyup event,
397            // tested via observing the behavior of the `ClickEvent.shiftKey` field in Chrome 138
398            // under various combinations of modifiers and keyUp / keyDown events.
399            ClickEvent::Mouse(event) => event.up.modifiers,
400            // Touch screens have no modifier keys.
401            ClickEvent::Touch(_) => Modifiers::default(),
402        }
403    }
404
405    /// Returns the position of the click event
406    ///
407    /// `Keyboard`: The bottom left corner of the clicked hitbox
408    /// `Mouse`: The position of the mouse when the button was released.
409    /// `Touch`: The position of the tap.
410    pub fn position(&self) -> Point<Pixels> {
411        match self {
412            ClickEvent::Keyboard(event) => event.bounds.bottom_left(),
413            ClickEvent::Mouse(event) => event.up.position,
414            ClickEvent::Touch(event) => event.position,
415        }
416    }
417
418    /// Returns the mouse position of the click event
419    ///
420    /// `Keyboard`: None
421    /// `Mouse`: The position of the mouse when the button was released.
422    /// `Touch`: None, touches are not mouse input and there is no cursor.
423    pub fn mouse_position(&self) -> Option<Point<Pixels>> {
424        match self {
425            ClickEvent::Keyboard(_) => None,
426            ClickEvent::Mouse(event) => Some(event.up.position),
427            ClickEvent::Touch(_) => None,
428        }
429    }
430
431    /// Returns if this was a right click
432    ///
433    /// `Keyboard`: false
434    /// `Mouse`: Whether the right button was pressed and released
435    pub fn is_right_click(&self) -> bool {
436        match self {
437            ClickEvent::Keyboard(_) => false,
438            ClickEvent::Mouse(event) => {
439                event.down.button == MouseButton::Right && event.up.button == MouseButton::Right
440            }
441            ClickEvent::Touch(_) => false,
442        }
443    }
444
445    /// Returns if this was a middle click
446    ///
447    /// `Keyboard`: false
448    /// `Mouse`: Whether the middle button was pressed and released
449    pub fn is_middle_click(&self) -> bool {
450        match self {
451            ClickEvent::Keyboard(_) => false,
452            ClickEvent::Mouse(event) => {
453                event.down.button == MouseButton::Middle && event.up.button == MouseButton::Middle
454            }
455            ClickEvent::Touch(_) => false,
456        }
457    }
458
459    /// Returns whether the click is a secondary activation, i.e. a context
460    /// menu trigger: a right click from a mouse (macOS ctrl-clicks arrive
461    /// already converted to right clicks by the platform layer), or a long
462    /// press on a touch screen.
463    pub fn is_secondary(&self) -> bool {
464        match self {
465            ClickEvent::Keyboard(_) => false,
466            ClickEvent::Mouse(event) => {
467                event.down.button == MouseButton::Right && event.up.button == MouseButton::Right
468            }
469            ClickEvent::Touch(event) => event.long_press,
470        }
471    }
472
473    /// Returns whether the click was a standard click
474    ///
475    /// `Keyboard`: Always true
476    /// `Mouse`: Left button pressed and released
477    /// `Touch`: A tap, but not a long press
478    pub fn standard_click(&self) -> bool {
479        match self {
480            ClickEvent::Keyboard(_) => true,
481            ClickEvent::Mouse(event) => {
482                event.down.button == MouseButton::Left && event.up.button == MouseButton::Left
483            }
484            ClickEvent::Touch(event) => !event.long_press,
485        }
486    }
487
488    /// Returns whether the click focused the element
489    ///
490    /// `Keyboard`: false, keyboard clicks only work if an element is already focused
491    /// `Mouse`: Whether this was the first focusing click
492    /// `Touch`: false, mobile windows are already active when tappable
493    pub fn first_focus(&self) -> bool {
494        match self {
495            ClickEvent::Keyboard(_) => false,
496            ClickEvent::Mouse(event) => event.down.first_mouse,
497            ClickEvent::Touch(_) => false,
498        }
499    }
500
501    /// Returns the click count of the click event
502    ///
503    /// `Keyboard`: Always 1
504    /// `Mouse`: Count of clicks from MouseUpEvent
505    /// `Touch`: Count of consecutive taps
506    pub fn click_count(&self) -> usize {
507        match self {
508            ClickEvent::Keyboard(_) => 1,
509            ClickEvent::Mouse(event) => event.up.click_count,
510            ClickEvent::Touch(event) => event.tap_count,
511        }
512    }
513
514    /// Returns whether the click event is generated by a keyboard event
515    pub fn is_keyboard(&self) -> bool {
516        match self {
517            ClickEvent::Mouse(_) | ClickEvent::Touch(_) => false,
518            ClickEvent::Keyboard(_) => true,
519        }
520    }
521}
522
523/// An enum representing the keyboard button that was pressed for a click event.
524#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug, Default)]
525pub enum KeyboardButton {
526    /// Enter key was clicked
527    #[default]
528    Enter,
529    /// Space key was clicked
530    Space,
531}
532
533/// An enum representing the mouse button that was pressed.
534#[derive(Hash, Default, PartialEq, Eq, Copy, Clone, Debug)]
535pub enum MouseButton {
536    /// The left mouse button.
537    #[default]
538    Left,
539
540    /// The right mouse button.
541    Right,
542
543    /// The middle mouse button.
544    Middle,
545
546    /// A navigation button, such as back or forward.
547    Navigate(NavigationDirection),
548}
549
550impl MouseButton {
551    /// Get all the mouse buttons in a list.
552    pub fn all() -> Vec<Self> {
553        vec![
554            MouseButton::Left,
555            MouseButton::Right,
556            MouseButton::Middle,
557            MouseButton::Navigate(NavigationDirection::Back),
558            MouseButton::Navigate(NavigationDirection::Forward),
559        ]
560    }
561}
562
563/// A navigation direction, such as back or forward.
564#[derive(Hash, Default, PartialEq, Eq, Copy, Clone, Debug)]
565pub enum NavigationDirection {
566    /// The back button.
567    #[default]
568    Back,
569
570    /// The forward button.
571    Forward,
572}
573
574/// A mouse move event from the platform.
575#[derive(Clone, Debug, Default)]
576pub struct MouseMoveEvent {
577    /// The position of the mouse on the window.
578    pub position: Point<Pixels>,
579
580    /// The mouse button that was pressed, if any.
581    pub pressed_button: Option<MouseButton>,
582
583    /// The modifiers that were held down when the mouse was moved.
584    pub modifiers: Modifiers,
585}
586
587impl Sealed for MouseMoveEvent {}
588impl InputEvent for MouseMoveEvent {
589    fn to_platform_input(self) -> PlatformInput {
590        PlatformInput::MouseMove(self)
591    }
592}
593impl MouseEvent for MouseMoveEvent {}
594
595impl MouseMoveEvent {
596    /// Returns true if the left mouse button is currently held down.
597    pub fn dragging(&self) -> bool {
598        self.pressed_button == Some(MouseButton::Left)
599    }
600}
601
602/// One step of scrolling from a mouse wheel, trackpad, or touch pan.
603#[derive(Clone, Debug, Default)]
604pub struct ScrollEvent {
605    /// The position the scroll targets. For touch pans this is where the pan
606    /// started, so the whole gesture stays with the container it began on.
607    pub position: Point<Pixels>,
608
609    /// The change in scroll position for this event.
610    pub delta: ScrollDelta,
611
612    /// The modifiers that were held down when the scroll happened.
613    pub modifiers: Modifiers,
614
615    /// The phase of the scroll gesture.
616    pub touch_phase: TouchPhase,
617
618    /// The kind of input that produced this scroll.
619    pub source: ScrollSource,
620}
621
622/// The former name of [`ScrollEvent`].
623#[deprecated(note = "renamed to `ScrollEvent`")]
624pub type ScrollWheelEvent = ScrollEvent;
625
626/// The kind of input that produced a [`ScrollEvent`].
627#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
628pub enum ScrollSource {
629    /// A scroll the platform reported from a pointing device, such as a mouse
630    /// wheel or a trackpad. [`ScrollDelta::precise`] tells continuous devices
631    /// apart from wheel notches.
632    #[default]
633    Pointer,
634    /// A pan of a finger on a touchscreen, recognized by GPUI, including the
635    /// momentum GPUI synthesizes after the finger lifts.
636    Touch,
637}
638
639impl Sealed for ScrollEvent {}
640impl InputEvent for ScrollEvent {
641    fn to_platform_input(self) -> PlatformInput {
642        PlatformInput::Scroll(self)
643    }
644}
645impl MouseEvent for ScrollEvent {}
646
647impl Deref for ScrollEvent {
648    type Target = Modifiers;
649
650    fn deref(&self) -> &Self::Target {
651        &self.modifiers
652    }
653}
654
655/// The scroll delta for a [`ScrollEvent`].
656#[derive(Clone, Copy, Debug)]
657pub enum ScrollDelta {
658    /// An exact scroll delta in pixels.
659    Pixels(Point<Pixels>),
660    /// An inexact scroll delta in lines.
661    Lines(Point<f32>),
662}
663
664impl Default for ScrollDelta {
665    fn default() -> Self {
666        Self::Lines(Default::default())
667    }
668}
669
670/// A pinch gesture event from the platform, generated when the user performs
671/// a pinch-to-zoom gesture (typically on a trackpad).
672///
673#[derive(Clone, Debug, Default)]
674pub struct PinchEvent {
675    /// The position of the pinch center on the window.
676    pub position: Point<Pixels>,
677
678    /// The zoom delta for this event.
679    /// Positive values indicate zooming in, negative values indicate zooming out.
680    /// For example, 0.1 represents a 10% zoom increase.
681    pub delta: f32,
682
683    /// The modifiers that were held down during the pinch gesture.
684    pub modifiers: Modifiers,
685
686    /// The phase of the pinch gesture.
687    pub phase: TouchPhase,
688}
689
690impl Sealed for PinchEvent {}
691impl InputEvent for PinchEvent {
692    fn to_platform_input(self) -> PlatformInput {
693        PlatformInput::Pinch(self)
694    }
695}
696impl GestureEvent for PinchEvent {}
697impl MouseEvent for PinchEvent {}
698
699impl Deref for PinchEvent {
700    type Target = Modifiers;
701
702    fn deref(&self) -> &Self::Target {
703        &self.modifiers
704    }
705}
706
707impl ScrollDelta {
708    /// Returns true if this is a precise scroll delta in pixels.
709    pub fn precise(&self) -> bool {
710        match self {
711            ScrollDelta::Pixels(_) => true,
712            ScrollDelta::Lines(_) => false,
713        }
714    }
715
716    /// Converts this scroll event into exact pixels.
717    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
718        match self {
719            ScrollDelta::Pixels(delta) => *delta,
720            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
721        }
722    }
723
724    /// Combines two scroll deltas into one.
725    /// If the signs of the deltas are the same (both positive or both negative),
726    /// the deltas are added together. If the signs are opposite, the second delta
727    /// (other) is used, effectively overriding the first delta.
728    pub fn coalesce(self, other: ScrollDelta) -> ScrollDelta {
729        match (self, other) {
730            (ScrollDelta::Pixels(a), ScrollDelta::Pixels(b)) => {
731                let x = if a.x.signum() == b.x.signum() {
732                    a.x + b.x
733                } else {
734                    b.x
735                };
736
737                let y = if a.y.signum() == b.y.signum() {
738                    a.y + b.y
739                } else {
740                    b.y
741                };
742
743                ScrollDelta::Pixels(point(x, y))
744            }
745
746            (ScrollDelta::Lines(a), ScrollDelta::Lines(b)) => {
747                let x = if a.x.signum() == b.x.signum() {
748                    a.x + b.x
749                } else {
750                    b.x
751                };
752
753                let y = if a.y.signum() == b.y.signum() {
754                    a.y + b.y
755                } else {
756                    b.y
757                };
758
759                ScrollDelta::Lines(point(x, y))
760            }
761
762            _ => other,
763        }
764    }
765}
766
767/// A mouse exit event from the platform, generated when the mouse leaves the window.
768#[derive(Clone, Debug, Default)]
769pub struct MouseExitEvent {
770    /// The position of the mouse relative to the window.
771    pub position: Point<Pixels>,
772    /// The mouse button that was pressed, if any.
773    pub pressed_button: Option<MouseButton>,
774    /// The modifiers that were held down when the mouse was moved.
775    pub modifiers: Modifiers,
776}
777
778impl Sealed for MouseExitEvent {}
779impl InputEvent for MouseExitEvent {
780    fn to_platform_input(self) -> PlatformInput {
781        PlatformInput::MouseExited(self)
782    }
783}
784
785impl MouseEvent for MouseExitEvent {}
786
787impl Deref for MouseExitEvent {
788    type Target = Modifiers;
789
790    fn deref(&self) -> &Self::Target {
791        &self.modifiers
792    }
793}
794
795/// A collection of paths from the platform, such as from a file drop.
796#[derive(Debug, Clone, Default, Eq, PartialEq)]
797pub struct ExternalPaths(pub SmallVec<[PathBuf; 2]>);
798
799impl ExternalPaths {
800    /// Convert this collection of paths into a slice.
801    pub fn paths(&self) -> &[PathBuf] {
802        &self.0
803    }
804}
805
806/// Data offered to the platform when an internal drag leaves the window and is
807/// promoted to a native drag session.
808#[derive(Debug, Clone, Eq, PartialEq)]
809pub enum ExternalDragPayload {
810    /// Real on-disk paths, handed to the platform as an outbound file drag.
811    Files(FileDragPaths),
812}
813
814/// Paths handed to the platform for a native file drag. Directory metadata is
815/// provided by the caller to avoid querying it when the platform drag starts.
816#[derive(Debug, Clone, Default, Eq, PartialEq)]
817pub struct FileDragPaths(SmallVec<[(PathBuf, bool); 2]>);
818
819impl FileDragPaths {
820    /// Creates a native file-drag payload from paths paired with whether each path is a directory.
821    pub fn new(entries: impl IntoIterator<Item = (PathBuf, bool)>) -> Self {
822        Self(entries.into_iter().collect())
823    }
824
825    /// The dragged paths, each paired with whether it is a directory.
826    pub fn entries(&self) -> &[(PathBuf, bool)] {
827        &self.0
828    }
829}
830
831impl Render for ExternalPaths {
832    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
833        // the platform will render icons for the dragged files
834        Empty
835    }
836}
837
838/// A file drop event from the platform, generated when files are dragged and dropped onto the window.
839#[derive(Debug, Clone)]
840pub enum FileDropEvent {
841    /// The files have entered the window.
842    Entered {
843        /// The position of the mouse relative to the window.
844        position: Point<Pixels>,
845        /// The paths of the files that are being dragged.
846        paths: ExternalPaths,
847    },
848    /// The files are being dragged over the window
849    Pending {
850        /// The position of the mouse relative to the window.
851        position: Point<Pixels>,
852    },
853    /// The files have been dropped onto the window.
854    Submit {
855        /// The position of the mouse relative to the window.
856        position: Point<Pixels>,
857    },
858    /// The user has stopped dragging the files over the window.
859    Exited,
860    /// The platform-owned drag session has ended.
861    Ended,
862}
863
864impl Sealed for FileDropEvent {}
865impl InputEvent for FileDropEvent {
866    fn to_platform_input(self) -> PlatformInput {
867        PlatformInput::FileDrop(self)
868    }
869}
870impl MouseEvent for FileDropEvent {}
871
872/// An enum corresponding to all kinds of platform input events.
873#[derive(Clone, Debug)]
874pub enum PlatformInput {
875    /// A key was pressed.
876    KeyDown(KeyDownEvent),
877    /// A key was released.
878    KeyUp(KeyUpEvent),
879    /// The keyboard modifiers were changed.
880    ModifiersChanged(ModifiersChangedEvent),
881    /// The mouse was pressed.
882    MouseDown(MouseDownEvent),
883    /// The mouse was released.
884    MouseUp(MouseUpEvent),
885    /// Mouse pressure.
886    MousePressure(MousePressureEvent),
887    /// The mouse was moved.
888    MouseMove(MouseMoveEvent),
889    /// The mouse exited the window.
890    MouseExited(MouseExitEvent),
891    /// A mouse wheel or trackpad scrolled. Touch pans reach the window as
892    /// [`PlatformInput::Touch`] and are recognized into scrolls by GPUI.
893    Scroll(ScrollEvent),
894    /// A pinch gesture was performed.
895    Pinch(PinchEvent),
896    /// A long-press gesture recognized from touch input.
897    LongPress(LongPressEvent),
898    /// A direct touch drag claimed by an element.
899    TouchDrag(TouchDragEvent),
900    /// A back-navigation gesture recognized by the platform.
901    BackGesture(BackGestureEvent),
902    /// Files were dragged and dropped onto the window.
903    FileDrop(FileDropEvent),
904    /// A raw touch event on a touch screen.
905    Touch(TouchEvent),
906    /// Stylus input, dispatched as the mouse event it carries.
907    Pen(PenEvent),
908}
909
910impl PlatformInput {
911    pub(crate) fn mouse_event(&self) -> Option<&dyn Any> {
912        match self {
913            PlatformInput::KeyDown { .. } => None,
914            PlatformInput::KeyUp { .. } => None,
915            PlatformInput::ModifiersChanged { .. } => None,
916            PlatformInput::MouseDown(event) => Some(event),
917            PlatformInput::MouseUp(event) => Some(event),
918            PlatformInput::MouseMove(event) => Some(event),
919            PlatformInput::MousePressure(event) => Some(event),
920            PlatformInput::MouseExited(event) => Some(event),
921            PlatformInput::Scroll(event) => Some(event),
922            PlatformInput::Pinch(event) => Some(event),
923            PlatformInput::LongPress(event) => Some(event),
924            PlatformInput::TouchDrag(event) => Some(event),
925            PlatformInput::BackGesture(event) => Some(event),
926            PlatformInput::FileDrop(event) => Some(event),
927            PlatformInput::Touch(_) => None,
928            PlatformInput::Pen(event) => match &event.action {
929                PenAction::Down(e) => Some(e),
930                PenAction::Up(e) => Some(e),
931                PenAction::Move(e) => Some(e),
932                PenAction::Exited(e) => Some(e),
933            },
934        }
935    }
936
937    pub(crate) fn keyboard_event(&self) -> Option<&dyn Any> {
938        match self {
939            PlatformInput::KeyDown(event) => Some(event),
940            PlatformInput::KeyUp(event) => Some(event),
941            PlatformInput::ModifiersChanged(event) => Some(event),
942            PlatformInput::MouseDown(_) => None,
943            PlatformInput::MouseUp(_) => None,
944            PlatformInput::MouseMove(_) => None,
945            PlatformInput::MousePressure(_) => None,
946            PlatformInput::MouseExited(_) => None,
947            PlatformInput::Scroll(_) => None,
948            PlatformInput::Pinch(_) => None,
949            PlatformInput::LongPress(_) => None,
950            PlatformInput::TouchDrag(_) => None,
951            PlatformInput::BackGesture(_) => None,
952            PlatformInput::FileDrop(_) => None,
953            PlatformInput::Touch(_) => None,
954            PlatformInput::Pen(_) => None,
955        }
956    }
957
958    /// A short static name for this input's variant, for diagnostics and
959    /// telemetry.
960    pub fn kind_name(&self) -> &'static str {
961        match self {
962            PlatformInput::KeyDown(_) => "key_down",
963            PlatformInput::KeyUp(_) => "key_up",
964            PlatformInput::ModifiersChanged(_) => "modifiers_changed",
965            PlatformInput::MouseDown(_) => "mouse_down",
966            PlatformInput::MouseUp(_) => "mouse_up",
967            PlatformInput::MousePressure(_) => "mouse_pressure",
968            PlatformInput::MouseMove(_) => "mouse_move",
969            PlatformInput::MouseExited(_) => "mouse_exited",
970            PlatformInput::Scroll(_) => "scroll",
971            PlatformInput::Pinch(_) => "pinch",
972            PlatformInput::LongPress(_) => "long_press",
973            PlatformInput::TouchDrag(_) => "touch_drag",
974            PlatformInput::BackGesture(_) => "back_gesture",
975            PlatformInput::FileDrop(_) => "file_drop",
976            PlatformInput::Touch(_) => "touch",
977            PlatformInput::Pen(_) => "pen",
978        }
979    }
980
981    /// Returns the touch event contained in this input, if any.
982    pub fn touch_event(&self) -> Option<&TouchEvent> {
983        match self {
984            PlatformInput::Touch(event) => Some(event),
985            _ => None,
986        }
987    }
988}
989
990#[cfg(test)]
991mod test {
992
993    use crate::{
994        self as gpui, AppContext as _, Context, FocusHandle, InteractiveElement, IntoElement,
995        KeyBinding, Keystroke, Modifiers, ParentElement, Render, TestAppContext, Window, div,
996    };
997
998    struct TestView {
999        saw_key_down: bool,
1000        saw_action: bool,
1001        focus_handle: FocusHandle,
1002    }
1003
1004    actions!(test_only, [TestAction]);
1005
1006    impl Render for TestView {
1007        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1008            div().id("testview").child(
1009                div()
1010                    .key_context("parent")
1011                    .on_key_down(cx.listener(|this, _, _, cx| {
1012                        cx.stop_propagation();
1013                        this.saw_key_down = true
1014                    }))
1015                    .on_action(cx.listener(|this: &mut TestView, _: &TestAction, _, _| {
1016                        this.saw_action = true
1017                    }))
1018                    .child(
1019                        div()
1020                            .key_context("nested")
1021                            .track_focus(&self.focus_handle)
1022                            .into_element(),
1023                    ),
1024            )
1025        }
1026    }
1027
1028    #[gpui::test]
1029    fn test_on_events(cx: &mut TestAppContext) {
1030        let window = cx.update(|cx| {
1031            cx.open_window(Default::default(), |_, cx| {
1032                cx.new(|cx| TestView {
1033                    saw_key_down: false,
1034                    saw_action: false,
1035                    focus_handle: cx.focus_handle(),
1036                })
1037            })
1038            .unwrap()
1039        });
1040
1041        cx.update(|cx| {
1042            cx.bind_keys(vec![KeyBinding::new("ctrl-g", TestAction, Some("parent"))]);
1043        });
1044
1045        window
1046            .update(cx, |test_view, window, cx| {
1047                window.focus(&test_view.focus_handle, cx)
1048            })
1049            .unwrap();
1050
1051        cx.dispatch_keystroke(*window, Keystroke::parse("a").unwrap());
1052        cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap());
1053
1054        window
1055            .update(cx, |test_view, _, _| {
1056                assert!(test_view.saw_key_down || test_view.saw_action);
1057                assert!(test_view.saw_key_down);
1058                assert!(test_view.saw_action);
1059            })
1060            .unwrap();
1061    }
1062
1063    #[gpui::test]
1064    fn test_multi_modifier_gesture_does_not_dispatch_standalone_modifier_binding(
1065        cx: &mut TestAppContext,
1066    ) {
1067        let (test_view, cx) = cx.add_window_view(|_, cx| TestView {
1068            saw_key_down: false,
1069            saw_action: false,
1070            focus_handle: cx.focus_handle(),
1071        });
1072
1073        cx.update(|_, cx| {
1074            cx.bind_keys(vec![KeyBinding::new("shift", TestAction, None)]);
1075        });
1076        test_view.update_in(cx, |test_view, window, cx| {
1077            window.focus(&test_view.focus_handle, cx);
1078        });
1079
1080        cx.simulate_modifiers_change(Modifiers::alt());
1081        cx.simulate_modifiers_change(Modifiers::alt() | Modifiers::shift());
1082        cx.simulate_modifiers_change(Modifiers::shift());
1083        cx.simulate_modifiers_change(Modifiers::none());
1084        assert!(!test_view.read_with(cx, |test_view, _| test_view.saw_action));
1085
1086        cx.simulate_modifiers_change(Modifiers::shift());
1087        cx.simulate_modifiers_change(Modifiers::none());
1088        assert!(test_view.read_with(cx, |test_view, _| test_view.saw_action));
1089    }
1090}