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#[derive(Clone, Debug, Default)]
311pub struct MouseExitEvent {
312 /// The position of the mouse relative to the window.
313 pub position: Point<Pixels>,
314 /// The mouse button that was pressed, if any.
315 pub pressed_button: Option<MouseButton>,
316 /// The modifiers that were held down when the mouse was moved.
317 pub modifiers: Modifiers,
318}
319
320impl Sealed for MouseExitEvent {}
321impl InputEvent for MouseExitEvent {
322 fn to_platform_input(self) -> PlatformInput {
323 PlatformInput::MouseExited(self)
324 }
325}
326impl MouseEvent for MouseExitEvent {}
327
328impl Deref for MouseExitEvent {
329 type Target = Modifiers;
330
331 fn deref(&self) -> &Self::Target {
332 &self.modifiers
333 }
334}
335
336/// A collection of paths from the platform, such as from a file drop.
337#[derive(Debug, Clone, Default)]
338pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
339
340impl ExternalPaths {
341 /// Convert this collection of paths into a slice.
342 pub fn paths(&self) -> &[PathBuf] {
343 &self.0
344 }
345}
346
347impl Render for ExternalPaths {
348 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
349 // the platform will render icons for the dragged files
350 Empty
351 }
352}
353
354/// A file drop event from the platform, generated when files are dragged and dropped onto the window.
355#[derive(Debug, Clone)]
356pub enum FileDropEvent {
357 /// The files have entered the window.
358 Entered {
359 /// The position of the mouse relative to the window.
360 position: Point<Pixels>,
361 /// The paths of the files that are being dragged.
362 paths: ExternalPaths,
363 },
364 /// The files are being dragged over the window
365 Pending {
366 /// The position of the mouse relative to the window.
367 position: Point<Pixels>,
368 },
369 /// The files have been dropped onto the window.
370 Submit {
371 /// The position of the mouse relative to the window.
372 position: Point<Pixels>,
373 },
374 /// The user has stopped dragging the files over the window.
375 Exited,
376}
377
378impl Sealed for FileDropEvent {}
379impl InputEvent for FileDropEvent {
380 fn to_platform_input(self) -> PlatformInput {
381 PlatformInput::FileDrop(self)
382 }
383}
384impl MouseEvent for FileDropEvent {}
385
386/// An enum corresponding to all kinds of platform input events.
387#[derive(Clone, Debug)]
388pub enum PlatformInput {
389 /// A key was pressed.
390 KeyDown(KeyDownEvent),
391 /// A key was released.
392 KeyUp(KeyUpEvent),
393 /// The keyboard modifiers were changed.
394 ModifiersChanged(ModifiersChangedEvent),
395 /// The mouse was pressed.
396 MouseDown(MouseDownEvent),
397 /// The mouse was released.
398 MouseUp(MouseUpEvent),
399 /// The mouse was moved.
400 MouseMove(MouseMoveEvent),
401 /// The mouse exited the window.
402 MouseExited(MouseExitEvent),
403 /// The scroll wheel was used.
404 ScrollWheel(ScrollWheelEvent),
405 /// Files were dragged and dropped onto the window.
406 FileDrop(FileDropEvent),
407}
408
409impl PlatformInput {
410 pub(crate) fn mouse_event(&self) -> Option<&dyn Any> {
411 match self {
412 PlatformInput::KeyDown { .. } => None,
413 PlatformInput::KeyUp { .. } => None,
414 PlatformInput::ModifiersChanged { .. } => None,
415 PlatformInput::MouseDown(event) => Some(event),
416 PlatformInput::MouseUp(event) => Some(event),
417 PlatformInput::MouseMove(event) => Some(event),
418 PlatformInput::MouseExited(event) => Some(event),
419 PlatformInput::ScrollWheel(event) => Some(event),
420 PlatformInput::FileDrop(event) => Some(event),
421 }
422 }
423
424 pub(crate) fn keyboard_event(&self) -> Option<&dyn Any> {
425 match self {
426 PlatformInput::KeyDown(event) => Some(event),
427 PlatformInput::KeyUp(event) => Some(event),
428 PlatformInput::ModifiersChanged(event) => Some(event),
429 PlatformInput::MouseDown(_) => None,
430 PlatformInput::MouseUp(_) => None,
431 PlatformInput::MouseMove(_) => None,
432 PlatformInput::MouseExited(_) => None,
433 PlatformInput::ScrollWheel(_) => None,
434 PlatformInput::FileDrop(_) => None,
435 }
436 }
437}
438
439#[cfg(test)]
440mod test {
441
442 use crate::{
443 self as gpui, div, FocusHandle, InteractiveElement, IntoElement, KeyBinding, Keystroke,
444 ParentElement, Render, TestAppContext, VisualContext,
445 };
446
447 struct TestView {
448 saw_key_down: bool,
449 saw_action: bool,
450 focus_handle: FocusHandle,
451 }
452
453 actions!(test, [TestAction]);
454
455 impl Render for TestView {
456 fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> impl IntoElement {
457 div().id("testview").child(
458 div()
459 .key_context("parent")
460 .on_key_down(cx.listener(|this, _, cx| {
461 cx.stop_propagation();
462 this.saw_key_down = true
463 }))
464 .on_action(
465 cx.listener(|this: &mut TestView, _: &TestAction, _| {
466 this.saw_action = true
467 }),
468 )
469 .child(
470 div()
471 .key_context("nested")
472 .track_focus(&self.focus_handle)
473 .into_element(),
474 ),
475 )
476 }
477 }
478
479 #[gpui::test]
480 fn test_on_events(cx: &mut TestAppContext) {
481 let window = cx.update(|cx| {
482 cx.open_window(Default::default(), |cx| {
483 cx.new_view(|cx| TestView {
484 saw_key_down: false,
485 saw_action: false,
486 focus_handle: cx.focus_handle(),
487 })
488 })
489 .unwrap()
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}