interactive.rs

  1use crate::{
  2    point, seal::Sealed, Empty, IntoElement, Keystroke, Modifiers, Pixels, Point, Render,
  3    ViewContext,
  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/// The key down event equivalent for the platform.
 21#[derive(Clone, Debug, Eq, PartialEq)]
 22pub struct KeyDownEvent {
 23    /// The keystroke that was generated.
 24    pub keystroke: Keystroke,
 25
 26    /// Whether the key is currently held down.
 27    pub is_held: bool,
 28}
 29
 30impl Sealed for KeyDownEvent {}
 31impl InputEvent for KeyDownEvent {
 32    fn to_platform_input(self) -> PlatformInput {
 33        PlatformInput::KeyDown(self)
 34    }
 35}
 36impl KeyEvent for KeyDownEvent {}
 37
 38/// The key up event equivalent for the platform.
 39#[derive(Clone, Debug)]
 40pub struct KeyUpEvent {
 41    /// The keystroke that was released.
 42    pub keystroke: Keystroke,
 43}
 44
 45impl Sealed for KeyUpEvent {}
 46impl InputEvent for KeyUpEvent {
 47    fn to_platform_input(self) -> PlatformInput {
 48        PlatformInput::KeyUp(self)
 49    }
 50}
 51impl KeyEvent for KeyUpEvent {}
 52
 53/// The modifiers changed event equivalent for the platform.
 54#[derive(Clone, Debug, Default)]
 55pub struct ModifiersChangedEvent {
 56    /// The new state of the modifier keys
 57    pub modifiers: Modifiers,
 58}
 59
 60impl Sealed for ModifiersChangedEvent {}
 61impl InputEvent for ModifiersChangedEvent {
 62    fn to_platform_input(self) -> PlatformInput {
 63        PlatformInput::ModifiersChanged(self)
 64    }
 65}
 66impl KeyEvent for ModifiersChangedEvent {}
 67
 68impl Deref for ModifiersChangedEvent {
 69    type Target = Modifiers;
 70
 71    fn deref(&self) -> &Self::Target {
 72        &self.modifiers
 73    }
 74}
 75
 76/// The phase of a touch motion event.
 77/// Based on the winit enum of the same name.
 78#[derive(Clone, Copy, Debug, Default)]
 79pub enum TouchPhase {
 80    /// The touch started.
 81    Started,
 82    /// The touch event is moving.
 83    #[default]
 84    Moved,
 85    /// The touch phase has ended
 86    Ended,
 87}
 88
 89/// A mouse down event from the platform
 90#[derive(Clone, Debug, Default)]
 91pub struct MouseDownEvent {
 92    /// Which mouse button was pressed.
 93    pub button: MouseButton,
 94
 95    /// The position of the mouse on the window.
 96    pub position: Point<Pixels>,
 97
 98    /// The modifiers that were held down when the mouse was pressed.
 99    pub modifiers: Modifiers,
100
101    /// The number of times the button has been clicked.
102    pub click_count: usize,
103
104    /// Whether this is the first, focusing click.
105    pub first_mouse: bool,
106}
107
108impl Sealed for MouseDownEvent {}
109impl InputEvent for MouseDownEvent {
110    fn to_platform_input(self) -> PlatformInput {
111        PlatformInput::MouseDown(self)
112    }
113}
114impl MouseEvent for MouseDownEvent {}
115
116/// A mouse up event from the platform
117#[derive(Clone, Debug, Default)]
118pub struct MouseUpEvent {
119    /// Which mouse button was released.
120    pub button: MouseButton,
121
122    /// The position of the mouse on the window.
123    pub position: Point<Pixels>,
124
125    /// The modifiers that were held down when the mouse was released.
126    pub modifiers: Modifiers,
127
128    /// The number of times the button has been clicked.
129    pub click_count: usize,
130}
131
132impl Sealed for MouseUpEvent {}
133impl InputEvent for MouseUpEvent {
134    fn to_platform_input(self) -> PlatformInput {
135        PlatformInput::MouseUp(self)
136    }
137}
138impl MouseEvent for MouseUpEvent {}
139
140/// A click event, generated when a mouse button is pressed and released.
141#[derive(Clone, Debug, Default)]
142pub struct ClickEvent {
143    /// The mouse event when the button was pressed.
144    pub down: MouseDownEvent,
145
146    /// The mouse event when the button was released.
147    pub up: MouseUpEvent,
148}
149
150/// An enum representing the mouse button that was pressed.
151#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
152pub enum MouseButton {
153    /// The left mouse button.
154    Left,
155
156    /// The right mouse button.
157    Right,
158
159    /// The middle mouse button.
160    Middle,
161
162    /// A navigation button, such as back or forward.
163    Navigate(NavigationDirection),
164}
165
166impl MouseButton {
167    /// Get all the mouse buttons in a list.
168    pub fn all() -> Vec<Self> {
169        vec![
170            MouseButton::Left,
171            MouseButton::Right,
172            MouseButton::Middle,
173            MouseButton::Navigate(NavigationDirection::Back),
174            MouseButton::Navigate(NavigationDirection::Forward),
175        ]
176    }
177}
178
179impl Default for MouseButton {
180    fn default() -> Self {
181        Self::Left
182    }
183}
184
185/// A navigation direction, such as back or forward.
186#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
187pub enum NavigationDirection {
188    /// The back button.
189    Back,
190
191    /// The forward button.
192    Forward,
193}
194
195impl Default for NavigationDirection {
196    fn default() -> Self {
197        Self::Back
198    }
199}
200
201/// A mouse move event from the platform
202#[derive(Clone, Debug, Default)]
203pub struct MouseMoveEvent {
204    /// The position of the mouse on the window.
205    pub position: Point<Pixels>,
206
207    /// The mouse button that was pressed, if any.
208    pub pressed_button: Option<MouseButton>,
209
210    /// The modifiers that were held down when the mouse was moved.
211    pub modifiers: Modifiers,
212}
213
214impl Sealed for MouseMoveEvent {}
215impl InputEvent for MouseMoveEvent {
216    fn to_platform_input(self) -> PlatformInput {
217        PlatformInput::MouseMove(self)
218    }
219}
220impl MouseEvent for MouseMoveEvent {}
221
222impl MouseMoveEvent {
223    /// Returns true if the left mouse button is currently held down.
224    pub fn dragging(&self) -> bool {
225        self.pressed_button == Some(MouseButton::Left)
226    }
227}
228
229/// A mouse wheel event from the platform
230#[derive(Clone, Debug, Default)]
231pub struct ScrollWheelEvent {
232    /// The position of the mouse on the window.
233    pub position: Point<Pixels>,
234
235    /// The change in scroll wheel position for this event.
236    pub delta: ScrollDelta,
237
238    /// The modifiers that were held down when the mouse was moved.
239    pub modifiers: Modifiers,
240
241    /// The phase of the touch event.
242    pub touch_phase: TouchPhase,
243}
244
245impl Sealed for ScrollWheelEvent {}
246impl InputEvent for ScrollWheelEvent {
247    fn to_platform_input(self) -> PlatformInput {
248        PlatformInput::ScrollWheel(self)
249    }
250}
251impl MouseEvent for ScrollWheelEvent {}
252
253impl Deref for ScrollWheelEvent {
254    type Target = Modifiers;
255
256    fn deref(&self) -> &Self::Target {
257        &self.modifiers
258    }
259}
260
261/// The scroll delta for a scroll wheel event.
262#[derive(Clone, Copy, Debug)]
263pub enum ScrollDelta {
264    /// An exact scroll delta in pixels.
265    Pixels(Point<Pixels>),
266    /// An inexact scroll delta in lines.
267    Lines(Point<f32>),
268}
269
270impl Default for ScrollDelta {
271    fn default() -> Self {
272        Self::Lines(Default::default())
273    }
274}
275
276impl ScrollDelta {
277    /// Returns true if this is a precise scroll delta in pixels.
278    pub fn precise(&self) -> bool {
279        match self {
280            ScrollDelta::Pixels(_) => true,
281            ScrollDelta::Lines(_) => false,
282        }
283    }
284
285    /// Converts this scroll event into exact pixels.
286    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
287        match self {
288            ScrollDelta::Pixels(delta) => *delta,
289            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
290        }
291    }
292
293    /// Combines two scroll deltas into one.
294    pub fn coalesce(self, other: ScrollDelta) -> ScrollDelta {
295        match (self, other) {
296            (ScrollDelta::Pixels(px_a), ScrollDelta::Pixels(px_b)) => {
297                ScrollDelta::Pixels(px_a + px_b)
298            }
299
300            (ScrollDelta::Lines(lines_a), ScrollDelta::Lines(lines_b)) => {
301                ScrollDelta::Lines(lines_a + lines_b)
302            }
303
304            _ => other,
305        }
306    }
307}
308
309/// A mouse exit event from the platform, generated when the mouse leaves the window.
310/// The position generated should be just outside of the window's bounds.
311#[derive(Clone, Debug, Default)]
312pub struct MouseExitEvent {
313    /// The position of the mouse relative to the window.
314    pub position: Point<Pixels>,
315    /// The mouse button that was pressed, if any.
316    pub pressed_button: Option<MouseButton>,
317    /// The modifiers that were held down when the mouse was moved.
318    pub modifiers: Modifiers,
319}
320
321impl Sealed for MouseExitEvent {}
322impl InputEvent for MouseExitEvent {
323    fn to_platform_input(self) -> PlatformInput {
324        PlatformInput::MouseExited(self)
325    }
326}
327impl MouseEvent for MouseExitEvent {}
328
329impl Deref for MouseExitEvent {
330    type Target = Modifiers;
331
332    fn deref(&self) -> &Self::Target {
333        &self.modifiers
334    }
335}
336
337/// A collection of paths from the platform, such as from a file drop.
338#[derive(Debug, Clone, Default)]
339pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
340
341impl ExternalPaths {
342    /// Convert this collection of paths into a slice.
343    pub fn paths(&self) -> &[PathBuf] {
344        &self.0
345    }
346}
347
348impl Render for ExternalPaths {
349    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
350        // the platform will render icons for the dragged files
351        Empty
352    }
353}
354
355/// A file drop event from the platform, generated when files are dragged and dropped onto the window.
356#[derive(Debug, Clone)]
357pub enum FileDropEvent {
358    /// The files have entered the window.
359    Entered {
360        /// The position of the mouse relative to the window.
361        position: Point<Pixels>,
362        /// The paths of the files that are being dragged.
363        paths: ExternalPaths,
364    },
365    /// The files are being dragged over the window
366    Pending {
367        /// The position of the mouse relative to the window.
368        position: Point<Pixels>,
369    },
370    /// The files have been dropped onto the window.
371    Submit {
372        /// The position of the mouse relative to the window.
373        position: Point<Pixels>,
374    },
375    /// The user has stopped dragging the files over the window.
376    Exited,
377}
378
379impl Sealed for FileDropEvent {}
380impl InputEvent for FileDropEvent {
381    fn to_platform_input(self) -> PlatformInput {
382        PlatformInput::FileDrop(self)
383    }
384}
385impl MouseEvent for FileDropEvent {}
386
387/// An enum corresponding to all kinds of platform input events.
388#[derive(Clone, Debug)]
389pub enum PlatformInput {
390    /// A key was pressed.
391    KeyDown(KeyDownEvent),
392    /// A key was released.
393    KeyUp(KeyUpEvent),
394    /// The keyboard modifiers were changed.
395    ModifiersChanged(ModifiersChangedEvent),
396    /// The mouse was pressed.
397    MouseDown(MouseDownEvent),
398    /// The mouse was released.
399    MouseUp(MouseUpEvent),
400    /// The mouse was moved.
401    MouseMove(MouseMoveEvent),
402    /// The mouse exited the window.
403    MouseExited(MouseExitEvent),
404    /// The scroll wheel was used.
405    ScrollWheel(ScrollWheelEvent),
406    /// Files were dragged and dropped onto the window.
407    FileDrop(FileDropEvent),
408}
409
410impl PlatformInput {
411    pub(crate) fn mouse_event(&self) -> Option<&dyn Any> {
412        match self {
413            PlatformInput::KeyDown { .. } => None,
414            PlatformInput::KeyUp { .. } => None,
415            PlatformInput::ModifiersChanged { .. } => None,
416            PlatformInput::MouseDown(event) => Some(event),
417            PlatformInput::MouseUp(event) => Some(event),
418            PlatformInput::MouseMove(event) => Some(event),
419            PlatformInput::MouseExited(event) => Some(event),
420            PlatformInput::ScrollWheel(event) => Some(event),
421            PlatformInput::FileDrop(event) => Some(event),
422        }
423    }
424
425    pub(crate) fn keyboard_event(&self) -> Option<&dyn Any> {
426        match self {
427            PlatformInput::KeyDown(event) => Some(event),
428            PlatformInput::KeyUp(event) => Some(event),
429            PlatformInput::ModifiersChanged(event) => Some(event),
430            PlatformInput::MouseDown(_) => None,
431            PlatformInput::MouseUp(_) => None,
432            PlatformInput::MouseMove(_) => None,
433            PlatformInput::MouseExited(_) => None,
434            PlatformInput::ScrollWheel(_) => None,
435            PlatformInput::FileDrop(_) => None,
436        }
437    }
438}
439
440#[cfg(test)]
441mod test {
442
443    use crate::{
444        self as gpui, div, Element, FocusHandle, InteractiveElement, IntoElement, KeyBinding,
445        Keystroke, ParentElement, Render, TestAppContext, VisualContext,
446    };
447
448    struct TestView {
449        saw_key_down: bool,
450        saw_action: bool,
451        focus_handle: FocusHandle,
452    }
453
454    actions!(test, [TestAction]);
455
456    impl Render for TestView {
457        fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> impl Element {
458            div().id("testview").child(
459                div()
460                    .key_context("parent")
461                    .on_key_down(cx.listener(|this, _, cx| {
462                        cx.stop_propagation();
463                        this.saw_key_down = true
464                    }))
465                    .on_action(
466                        cx.listener(|this: &mut TestView, _: &TestAction, _| {
467                            this.saw_action = true
468                        }),
469                    )
470                    .child(
471                        div()
472                            .key_context("nested")
473                            .track_focus(&self.focus_handle)
474                            .into_element(),
475                    ),
476            )
477        }
478    }
479
480    #[gpui::test]
481    fn test_on_events(cx: &mut TestAppContext) {
482        let window = cx.update(|cx| {
483            cx.open_window(Default::default(), |cx| {
484                cx.new_view(|cx| TestView {
485                    saw_key_down: false,
486                    saw_action: false,
487                    focus_handle: cx.focus_handle(),
488                })
489            })
490        });
491
492        cx.update(|cx| {
493            cx.bind_keys(vec![KeyBinding::new("ctrl-g", TestAction, Some("parent"))]);
494        });
495
496        window
497            .update(cx, |test_view, cx| cx.focus(&test_view.focus_handle))
498            .unwrap();
499
500        cx.dispatch_keystroke(*window, Keystroke::parse("a").unwrap());
501        cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap());
502
503        window
504            .update(cx, |test_view, _| {
505                assert!(test_view.saw_key_down || test_view.saw_action);
506                assert!(test_view.saw_key_down);
507                assert!(test_view.saw_action);
508            })
509            .unwrap();
510    }
511}