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
8pub trait InputEvent: Sealed + 'static {
10 fn to_platform_input(self) -> PlatformInput;
12}
13
14pub trait KeyEvent: InputEvent {}
16
17pub trait MouseEvent: InputEvent {}
19
20#[derive(Clone, Debug, Eq, PartialEq)]
22pub struct KeyDownEvent {
23 pub keystroke: Keystroke,
25
26 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#[derive(Clone, Debug)]
40pub struct KeyUpEvent {
41 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#[derive(Clone, Debug, Default)]
55pub struct ModifiersChangedEvent {
56 pub modifiers: Modifiers,
58 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#[derive(Clone, Copy, Debug, Default)]
81pub enum TouchPhase {
82 Started,
84 #[default]
86 Moved,
87 Ended,
89}
90
91#[derive(Clone, Debug, Default)]
93pub struct MouseDownEvent {
94 pub button: MouseButton,
96
97 pub position: Point<Pixels>,
99
100 pub modifiers: Modifiers,
102
103 pub click_count: usize,
105
106 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#[derive(Clone, Debug, Default)]
120pub struct MouseUpEvent {
121 pub button: MouseButton,
123
124 pub position: Point<Pixels>,
126
127 pub modifiers: Modifiers,
129
130 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#[derive(Clone, Debug, Default)]
144pub struct MouseClickEvent {
145 pub down: MouseDownEvent,
147
148 pub up: MouseUpEvent,
150}
151
152#[derive(Clone, Debug, Default)]
154pub struct KeyboardClickEvent {
155 pub button: KeyboardButton,
157
158 pub bounds: Bounds<Pixels>,
160}
161
162#[derive(Clone, Debug)]
164pub enum ClickEvent {
165 Mouse(MouseClickEvent),
167 Keyboard(KeyboardClickEvent),
169}
170
171impl Default for ClickEvent {
172 fn default() -> Self {
173 ClickEvent::Keyboard(KeyboardClickEvent::default())
174 }
175}
176
177impl ClickEvent {
178 pub fn modifiers(&self) -> Modifiers {
183 match self {
184 ClickEvent::Keyboard(_) => Modifiers::default(),
186 ClickEvent::Mouse(event) => event.up.modifiers,
190 }
191 }
192
193 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 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 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 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 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 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 pub fn is_keyboard(&self) -> bool {
265 match self {
266 ClickEvent::Mouse(_) => false,
267 ClickEvent::Keyboard(_) => true,
268 }
269 }
270}
271
272#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug, Default)]
274pub enum KeyboardButton {
275 #[default]
277 Enter,
278 Space,
280}
281
282#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
284pub enum MouseButton {
285 Left,
287
288 Right,
290
291 Middle,
293
294 Navigate(NavigationDirection),
296}
297
298impl MouseButton {
299 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#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
319pub enum NavigationDirection {
320 Back,
322
323 Forward,
325}
326
327impl Default for NavigationDirection {
328 fn default() -> Self {
329 Self::Back
330 }
331}
332
333#[derive(Clone, Debug, Default)]
335pub struct MouseMoveEvent {
336 pub position: Point<Pixels>,
338
339 pub pressed_button: Option<MouseButton>,
341
342 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 pub fn dragging(&self) -> bool {
357 self.pressed_button == Some(MouseButton::Left)
358 }
359}
360
361#[derive(Clone, Debug, Default)]
363pub struct ScrollWheelEvent {
364 pub position: Point<Pixels>,
366
367 pub delta: ScrollDelta,
369
370 pub modifiers: Modifiers,
372
373 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#[derive(Clone, Copy, Debug)]
395pub enum ScrollDelta {
396 Pixels(Point<Pixels>),
398 Lines(Point<f32>),
400}
401
402impl Default for ScrollDelta {
403 fn default() -> Self {
404 Self::Lines(Default::default())
405 }
406}
407
408impl ScrollDelta {
409 pub fn precise(&self) -> bool {
411 match self {
412 ScrollDelta::Pixels(_) => true,
413 ScrollDelta::Lines(_) => false,
414 }
415 }
416
417 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 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#[derive(Clone, Debug, Default)]
470pub struct MouseExitEvent {
471 pub position: Point<Pixels>,
473 pub pressed_button: Option<MouseButton>,
475 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#[derive(Debug, Clone, Default)]
497pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
498
499impl ExternalPaths {
500 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 Empty
510 }
511}
512
513#[derive(Debug, Clone)]
515pub enum FileDropEvent {
516 Entered {
518 position: Point<Pixels>,
520 paths: ExternalPaths,
522 },
523 Pending {
525 position: Point<Pixels>,
527 },
528 Submit {
530 position: Point<Pixels>,
532 },
533 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#[derive(Clone, Debug)]
547pub enum PlatformInput {
548 KeyDown(KeyDownEvent),
550 KeyUp(KeyUpEvent),
552 ModifiersChanged(ModifiersChangedEvent),
554 MouseDown(MouseDownEvent),
556 MouseUp(MouseUpEvent),
558 MouseMove(MouseMoveEvent),
560 MouseExited(MouseExitEvent),
562 ScrollWheel(ScrollWheelEvent),
564 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}