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