1use crate::{
2 Bounds, Capslock, Context, Empty, IntoElement, Keystroke, Modifiers, Pixels, Point, Render,
3 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/// 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 /// Whether to prefer character input over keybindings for this keystroke.
30 /// In some cases, like AltGr on Windows, modifiers are significant for character input.
31 pub prefer_character_input: bool,
32}
33
34impl Sealed for KeyDownEvent {}
35impl InputEvent for KeyDownEvent {
36 fn to_platform_input(self) -> PlatformInput {
37 PlatformInput::KeyDown(self)
38 }
39}
40impl KeyEvent for KeyDownEvent {}
41
42/// The key up event equivalent for the platform.
43#[derive(Clone, Debug)]
44pub struct KeyUpEvent {
45 /// The keystroke that was released.
46 pub keystroke: Keystroke,
47}
48
49impl Sealed for KeyUpEvent {}
50impl InputEvent for KeyUpEvent {
51 fn to_platform_input(self) -> PlatformInput {
52 PlatformInput::KeyUp(self)
53 }
54}
55impl KeyEvent for KeyUpEvent {}
56
57/// The modifiers changed event equivalent for the platform.
58#[derive(Clone, Debug, Default)]
59pub struct ModifiersChangedEvent {
60 /// The new state of the modifier keys
61 pub modifiers: Modifiers,
62 /// The new state of the capslock key
63 pub capslock: Capslock,
64}
65
66impl Sealed for ModifiersChangedEvent {}
67impl InputEvent for ModifiersChangedEvent {
68 fn to_platform_input(self) -> PlatformInput {
69 PlatformInput::ModifiersChanged(self)
70 }
71}
72impl KeyEvent for ModifiersChangedEvent {}
73
74impl Deref for ModifiersChangedEvent {
75 type Target = Modifiers;
76
77 fn deref(&self) -> &Self::Target {
78 &self.modifiers
79 }
80}
81
82/// The phase of a touch motion event.
83/// Based on the winit enum of the same name.
84#[derive(Clone, Copy, Debug, Default)]
85pub enum TouchPhase {
86 /// The touch started.
87 Started,
88 /// The touch event is moving.
89 #[default]
90 Moved,
91 /// The touch phase has ended
92 Ended,
93}
94
95/// A mouse down event from the platform
96#[derive(Clone, Debug, Default)]
97pub struct MouseDownEvent {
98 /// Which mouse button was pressed.
99 pub button: MouseButton,
100
101 /// The position of the mouse on the window.
102 pub position: Point<Pixels>,
103
104 /// The modifiers that were held down when the mouse was pressed.
105 pub modifiers: Modifiers,
106
107 /// The number of times the button has been clicked.
108 pub click_count: usize,
109
110 /// Whether this is the first, focusing click.
111 pub first_mouse: bool,
112}
113
114impl Sealed for MouseDownEvent {}
115impl InputEvent for MouseDownEvent {
116 fn to_platform_input(self) -> PlatformInput {
117 PlatformInput::MouseDown(self)
118 }
119}
120impl MouseEvent for MouseDownEvent {}
121
122impl MouseDownEvent {
123 /// Returns true if this mouse up event should focus the element.
124 pub fn is_focusing(&self) -> bool {
125 match self.button {
126 MouseButton::Left => true,
127 _ => false,
128 }
129 }
130}
131
132/// A mouse up event from the platform
133#[derive(Clone, Debug, Default)]
134pub struct MouseUpEvent {
135 /// Which mouse button was released.
136 pub button: MouseButton,
137
138 /// The position of the mouse on the window.
139 pub position: Point<Pixels>,
140
141 /// The modifiers that were held down when the mouse was released.
142 pub modifiers: Modifiers,
143
144 /// The number of times the button has been clicked.
145 pub click_count: usize,
146}
147
148impl Sealed for MouseUpEvent {}
149impl InputEvent for MouseUpEvent {
150 fn to_platform_input(self) -> PlatformInput {
151 PlatformInput::MouseUp(self)
152 }
153}
154
155impl MouseEvent for MouseUpEvent {}
156
157impl MouseUpEvent {
158 /// Returns true if this mouse up event should focus the element.
159 pub fn is_focusing(&self) -> bool {
160 match self.button {
161 MouseButton::Left => true,
162 _ => false,
163 }
164 }
165}
166
167/// A click event, generated when a mouse button is pressed and released.
168#[derive(Clone, Debug, Default)]
169pub struct MouseClickEvent {
170 /// The mouse event when the button was pressed.
171 pub down: MouseDownEvent,
172
173 /// The mouse event when the button was released.
174 pub up: MouseUpEvent,
175}
176
177/// A click event that was generated by a keyboard button being pressed and released.
178#[derive(Clone, Debug, Default)]
179pub struct KeyboardClickEvent {
180 /// The keyboard button that was pressed to trigger the click.
181 pub button: KeyboardButton,
182
183 /// The bounds of the element that was clicked.
184 pub bounds: Bounds<Pixels>,
185}
186
187/// A click event, generated when a mouse button or keyboard button is pressed and released.
188#[derive(Clone, Debug)]
189pub enum ClickEvent {
190 /// A click event trigger by a mouse button being pressed and released.
191 Mouse(MouseClickEvent),
192 /// A click event trigger by a keyboard button being pressed and released.
193 Keyboard(KeyboardClickEvent),
194}
195
196impl Default for ClickEvent {
197 fn default() -> Self {
198 ClickEvent::Keyboard(KeyboardClickEvent::default())
199 }
200}
201
202impl ClickEvent {
203 /// Returns the modifiers that were held during the click event
204 ///
205 /// `Keyboard`: The keyboard click events never have modifiers.
206 /// `Mouse`: Modifiers that were held during the mouse key up event.
207 pub fn modifiers(&self) -> Modifiers {
208 match self {
209 // Click events are only generated from keyboard events _without any modifiers_, so we know the modifiers are always Default
210 ClickEvent::Keyboard(_) => Modifiers::default(),
211 // Click events on the web only reflect the modifiers for the keyup event,
212 // tested via observing the behavior of the `ClickEvent.shiftKey` field in Chrome 138
213 // under various combinations of modifiers and keyUp / keyDown events.
214 ClickEvent::Mouse(event) => event.up.modifiers,
215 }
216 }
217
218 /// Returns the position of the click event
219 ///
220 /// `Keyboard`: The bottom left corner of the clicked hitbox
221 /// `Mouse`: The position of the mouse when the button was released.
222 pub fn position(&self) -> Point<Pixels> {
223 match self {
224 ClickEvent::Keyboard(event) => event.bounds.bottom_left(),
225 ClickEvent::Mouse(event) => event.up.position,
226 }
227 }
228
229 /// Returns the mouse position of the click event
230 ///
231 /// `Keyboard`: None
232 /// `Mouse`: The position of the mouse when the button was released.
233 pub fn mouse_position(&self) -> Option<Point<Pixels>> {
234 match self {
235 ClickEvent::Keyboard(_) => None,
236 ClickEvent::Mouse(event) => Some(event.up.position),
237 }
238 }
239
240 /// Returns if this was a right click
241 ///
242 /// `Keyboard`: false
243 /// `Mouse`: Whether the right button was pressed and released
244 pub fn is_right_click(&self) -> bool {
245 match self {
246 ClickEvent::Keyboard(_) => false,
247 ClickEvent::Mouse(event) => {
248 event.down.button == MouseButton::Right && event.up.button == MouseButton::Right
249 }
250 }
251 }
252
253 /// Returns whether the click was a standard click
254 ///
255 /// `Keyboard`: Always true
256 /// `Mouse`: Left button pressed and released
257 pub fn standard_click(&self) -> bool {
258 match self {
259 ClickEvent::Keyboard(_) => true,
260 ClickEvent::Mouse(event) => {
261 event.down.button == MouseButton::Left && event.up.button == MouseButton::Left
262 }
263 }
264 }
265
266 /// Returns whether the click focused the element
267 ///
268 /// `Keyboard`: false, keyboard clicks only work if an element is already focused
269 /// `Mouse`: Whether this was the first focusing click
270 pub fn first_focus(&self) -> bool {
271 match self {
272 ClickEvent::Keyboard(_) => false,
273 ClickEvent::Mouse(event) => event.down.first_mouse,
274 }
275 }
276
277 /// Returns the click count of the click event
278 ///
279 /// `Keyboard`: Always 1
280 /// `Mouse`: Count of clicks from MouseUpEvent
281 pub fn click_count(&self) -> usize {
282 match self {
283 ClickEvent::Keyboard(_) => 1,
284 ClickEvent::Mouse(event) => event.up.click_count,
285 }
286 }
287
288 /// Returns whether the click event is generated by a keyboard event
289 pub fn is_keyboard(&self) -> bool {
290 match self {
291 ClickEvent::Mouse(_) => false,
292 ClickEvent::Keyboard(_) => true,
293 }
294 }
295}
296
297/// An enum representing the keyboard button that was pressed for a click event.
298#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug, Default)]
299pub enum KeyboardButton {
300 /// Enter key was clicked
301 #[default]
302 Enter,
303 /// Space key was clicked
304 Space,
305}
306
307/// An enum representing the mouse button that was pressed.
308#[derive(Hash, Default, PartialEq, Eq, Copy, Clone, Debug)]
309pub enum MouseButton {
310 /// The left mouse button.
311 #[default]
312 Left,
313
314 /// The right mouse button.
315 Right,
316
317 /// The middle mouse button.
318 Middle,
319
320 /// A navigation button, such as back or forward.
321 Navigate(NavigationDirection),
322}
323
324impl MouseButton {
325 /// Get all the mouse buttons in a list.
326 pub fn all() -> Vec<Self> {
327 vec![
328 MouseButton::Left,
329 MouseButton::Right,
330 MouseButton::Middle,
331 MouseButton::Navigate(NavigationDirection::Back),
332 MouseButton::Navigate(NavigationDirection::Forward),
333 ]
334 }
335}
336
337/// A navigation direction, such as back or forward.
338#[derive(Hash, Default, PartialEq, Eq, Copy, Clone, Debug)]
339pub enum NavigationDirection {
340 /// The back button.
341 #[default]
342 Back,
343
344 /// The forward button.
345 Forward,
346}
347
348/// A mouse move event from the platform.
349#[derive(Clone, Debug, Default)]
350pub struct MouseMoveEvent {
351 /// The position of the mouse on the window.
352 pub position: Point<Pixels>,
353
354 /// The mouse button that was pressed, if any.
355 pub pressed_button: Option<MouseButton>,
356
357 /// The modifiers that were held down when the mouse was moved.
358 pub modifiers: Modifiers,
359}
360
361impl Sealed for MouseMoveEvent {}
362impl InputEvent for MouseMoveEvent {
363 fn to_platform_input(self) -> PlatformInput {
364 PlatformInput::MouseMove(self)
365 }
366}
367impl MouseEvent for MouseMoveEvent {}
368
369impl MouseMoveEvent {
370 /// Returns true if the left mouse button is currently held down.
371 pub fn dragging(&self) -> bool {
372 self.pressed_button == Some(MouseButton::Left)
373 }
374}
375
376/// A mouse wheel event from the platform.
377#[derive(Clone, Debug, Default)]
378pub struct ScrollWheelEvent {
379 /// The position of the mouse on the window.
380 pub position: Point<Pixels>,
381
382 /// The change in scroll wheel position for this event.
383 pub delta: ScrollDelta,
384
385 /// The modifiers that were held down when the mouse was moved.
386 pub modifiers: Modifiers,
387
388 /// The phase of the touch event.
389 pub touch_phase: TouchPhase,
390}
391
392impl Sealed for ScrollWheelEvent {}
393impl InputEvent for ScrollWheelEvent {
394 fn to_platform_input(self) -> PlatformInput {
395 PlatformInput::ScrollWheel(self)
396 }
397}
398impl MouseEvent for ScrollWheelEvent {}
399
400impl Deref for ScrollWheelEvent {
401 type Target = Modifiers;
402
403 fn deref(&self) -> &Self::Target {
404 &self.modifiers
405 }
406}
407
408/// The scroll delta for a scroll wheel event.
409#[derive(Clone, Copy, Debug)]
410pub enum ScrollDelta {
411 /// An exact scroll delta in pixels.
412 Pixels(Point<Pixels>),
413 /// An inexact scroll delta in lines.
414 Lines(Point<f32>),
415}
416
417impl Default for ScrollDelta {
418 fn default() -> Self {
419 Self::Lines(Default::default())
420 }
421}
422
423impl ScrollDelta {
424 /// Returns true if this is a precise scroll delta in pixels.
425 pub fn precise(&self) -> bool {
426 match self {
427 ScrollDelta::Pixels(_) => true,
428 ScrollDelta::Lines(_) => false,
429 }
430 }
431
432 /// Converts this scroll event into exact pixels.
433 pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
434 match self {
435 ScrollDelta::Pixels(delta) => *delta,
436 ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
437 }
438 }
439
440 /// Combines two scroll deltas into one.
441 /// If the signs of the deltas are the same (both positive or both negative),
442 /// the deltas are added together. If the signs are opposite, the second delta
443 /// (other) is used, effectively overriding the first delta.
444 pub fn coalesce(self, other: ScrollDelta) -> ScrollDelta {
445 match (self, other) {
446 (ScrollDelta::Pixels(a), ScrollDelta::Pixels(b)) => {
447 let x = if a.x.signum() == b.x.signum() {
448 a.x + b.x
449 } else {
450 b.x
451 };
452
453 let y = if a.y.signum() == b.y.signum() {
454 a.y + b.y
455 } else {
456 b.y
457 };
458
459 ScrollDelta::Pixels(point(x, y))
460 }
461
462 (ScrollDelta::Lines(a), ScrollDelta::Lines(b)) => {
463 let x = if a.x.signum() == b.x.signum() {
464 a.x + b.x
465 } else {
466 b.x
467 };
468
469 let y = if a.y.signum() == b.y.signum() {
470 a.y + b.y
471 } else {
472 b.y
473 };
474
475 ScrollDelta::Lines(point(x, y))
476 }
477
478 _ => other,
479 }
480 }
481}
482
483/// A mouse exit event from the platform, generated when the mouse leaves the window.
484#[derive(Clone, Debug, Default)]
485pub struct MouseExitEvent {
486 /// The position of the mouse relative to the window.
487 pub position: Point<Pixels>,
488 /// The mouse button that was pressed, if any.
489 pub pressed_button: Option<MouseButton>,
490 /// The modifiers that were held down when the mouse was moved.
491 pub modifiers: Modifiers,
492}
493
494impl Sealed for MouseExitEvent {}
495impl InputEvent for MouseExitEvent {
496 fn to_platform_input(self) -> PlatformInput {
497 PlatformInput::MouseExited(self)
498 }
499}
500
501impl MouseEvent for MouseExitEvent {}
502
503impl Deref for MouseExitEvent {
504 type Target = Modifiers;
505
506 fn deref(&self) -> &Self::Target {
507 &self.modifiers
508 }
509}
510
511/// A collection of paths from the platform, such as from a file drop.
512#[derive(Debug, Clone, Default)]
513pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
514
515impl ExternalPaths {
516 /// Convert this collection of paths into a slice.
517 pub fn paths(&self) -> &[PathBuf] {
518 &self.0
519 }
520}
521
522impl Render for ExternalPaths {
523 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
524 // the platform will render icons for the dragged files
525 Empty
526 }
527}
528
529/// A file drop event from the platform, generated when files are dragged and dropped onto the window.
530#[derive(Debug, Clone)]
531pub enum FileDropEvent {
532 /// The files have entered the window.
533 Entered {
534 /// The position of the mouse relative to the window.
535 position: Point<Pixels>,
536 /// The paths of the files that are being dragged.
537 paths: ExternalPaths,
538 },
539 /// The files are being dragged over the window
540 Pending {
541 /// The position of the mouse relative to the window.
542 position: Point<Pixels>,
543 },
544 /// The files have been dropped onto the window.
545 Submit {
546 /// The position of the mouse relative to the window.
547 position: Point<Pixels>,
548 },
549 /// The user has stopped dragging the files over the window.
550 Exited,
551}
552
553impl Sealed for FileDropEvent {}
554impl InputEvent for FileDropEvent {
555 fn to_platform_input(self) -> PlatformInput {
556 PlatformInput::FileDrop(self)
557 }
558}
559impl MouseEvent for FileDropEvent {}
560
561/// An enum corresponding to all kinds of platform input events.
562#[derive(Clone, Debug)]
563pub enum PlatformInput {
564 /// A key was pressed.
565 KeyDown(KeyDownEvent),
566 /// A key was released.
567 KeyUp(KeyUpEvent),
568 /// The keyboard modifiers were changed.
569 ModifiersChanged(ModifiersChangedEvent),
570 /// The mouse was pressed.
571 MouseDown(MouseDownEvent),
572 /// The mouse was released.
573 MouseUp(MouseUpEvent),
574 /// The mouse was moved.
575 MouseMove(MouseMoveEvent),
576 /// The mouse exited the window.
577 MouseExited(MouseExitEvent),
578 /// The scroll wheel was used.
579 ScrollWheel(ScrollWheelEvent),
580 /// Files were dragged and dropped onto the window.
581 FileDrop(FileDropEvent),
582}
583
584impl PlatformInput {
585 pub(crate) fn mouse_event(&self) -> Option<&dyn Any> {
586 match self {
587 PlatformInput::KeyDown { .. } => None,
588 PlatformInput::KeyUp { .. } => None,
589 PlatformInput::ModifiersChanged { .. } => None,
590 PlatformInput::MouseDown(event) => Some(event),
591 PlatformInput::MouseUp(event) => Some(event),
592 PlatformInput::MouseMove(event) => Some(event),
593 PlatformInput::MouseExited(event) => Some(event),
594 PlatformInput::ScrollWheel(event) => Some(event),
595 PlatformInput::FileDrop(event) => Some(event),
596 }
597 }
598
599 pub(crate) fn keyboard_event(&self) -> Option<&dyn Any> {
600 match self {
601 PlatformInput::KeyDown(event) => Some(event),
602 PlatformInput::KeyUp(event) => Some(event),
603 PlatformInput::ModifiersChanged(event) => Some(event),
604 PlatformInput::MouseDown(_) => None,
605 PlatformInput::MouseUp(_) => None,
606 PlatformInput::MouseMove(_) => None,
607 PlatformInput::MouseExited(_) => None,
608 PlatformInput::ScrollWheel(_) => None,
609 PlatformInput::FileDrop(_) => None,
610 }
611 }
612}
613
614#[cfg(test)]
615mod test {
616
617 use crate::{
618 self as gpui, AppContext as _, Context, FocusHandle, InteractiveElement, IntoElement,
619 KeyBinding, Keystroke, ParentElement, Render, TestAppContext, Window, div,
620 };
621
622 struct TestView {
623 saw_key_down: bool,
624 saw_action: bool,
625 focus_handle: FocusHandle,
626 }
627
628 actions!(test_only, [TestAction]);
629
630 impl Render for TestView {
631 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
632 div().id("testview").child(
633 div()
634 .key_context("parent")
635 .on_key_down(cx.listener(|this, _, _, cx| {
636 cx.stop_propagation();
637 this.saw_key_down = true
638 }))
639 .on_action(cx.listener(|this: &mut TestView, _: &TestAction, _, _| {
640 this.saw_action = true
641 }))
642 .child(
643 div()
644 .key_context("nested")
645 .track_focus(&self.focus_handle)
646 .into_element(),
647 ),
648 )
649 }
650 }
651
652 #[gpui::test]
653 fn test_on_events(cx: &mut TestAppContext) {
654 let window = cx.update(|cx| {
655 cx.open_window(Default::default(), |_, cx| {
656 cx.new(|cx| TestView {
657 saw_key_down: false,
658 saw_action: false,
659 focus_handle: cx.focus_handle(),
660 })
661 })
662 .unwrap()
663 });
664
665 cx.update(|cx| {
666 cx.bind_keys(vec![KeyBinding::new("ctrl-g", TestAction, Some("parent"))]);
667 });
668
669 window
670 .update(cx, |test_view, window, _cx| {
671 window.focus(&test_view.focus_handle)
672 })
673 .unwrap();
674
675 cx.dispatch_keystroke(*window, Keystroke::parse("a").unwrap());
676 cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap());
677
678 window
679 .update(cx, |test_view, _, _| {
680 assert!(test_view.saw_key_down || test_view.saw_action);
681 assert!(test_view.saw_key_down);
682 assert!(test_view.saw_action);
683 })
684 .unwrap();
685 }
686}