1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::{Keybindings, Pointer, WidgetId, World};
use crossterm::event::{KeyEvent, MouseEvent, MouseEventKind};
#[derive(Debug)]
pub enum InputEvent {
Key(KeyEvent),
Mouse(MouseEvent),
Tick,
}
impl InputEvent {
/// Handles the event by dispatching to the appropriate handler.
///
/// # Panics
///
/// Panics if the `Keybindings` resource is not present in the world.
pub fn handle(self, world: &mut World, ids: &[WidgetId]) {
match self {
InputEvent::Key(key) => {
let binding = (&key).into();
let keybindings = world.remove::<Keybindings>().unwrap();
keybindings.handle(&binding, world, ids);
world.insert(keybindings);
}
InputEvent::Mouse(mouse) => {
let x = mouse.column;
let y = mouse.row;
match mouse.kind {
MouseEventKind::Down(_) => {
let hit = world.get::<Pointer>().hit_test(x, y);
world.get_mut::<Pointer>().set_active(hit);
if let Some(widget_id) = hit {
let pointer = world.get::<Pointer>();
let area = pointer.get(widget_id).copied();
let handler = pointer.get_handler_for(widget_id, mouse.kind);
if let (Some(area), Some(f)) = (area, handler) {
f(world, area, x, y);
}
}
}
MouseEventKind::Drag(_) => {
// Drag events go to the widget that received mouse down
let active = world.get::<Pointer>().active();
if let Some(widget_id) = active {
let pointer = world.get::<Pointer>();
let area = pointer.get(widget_id).copied();
let handler = pointer.get_handler_for(widget_id, mouse.kind);
if let (Some(area), Some(f)) = (area, handler) {
f(world, area, x, y);
}
}
}
MouseEventKind::Up(_) => {
// Up events go to the widget that received mouse down
let active = world.get::<Pointer>().active();
if let Some(widget_id) = active {
let pointer = world.get::<Pointer>();
let area = pointer.get(widget_id).copied();
let handler = pointer.get_handler_for(widget_id, mouse.kind);
if let (Some(area), Some(f)) = (area, handler) {
f(world, area, x, y);
}
}
// Clear active widget on mouse up
world.get_mut::<Pointer>().set_active(None);
}
_ => {}
}
}
InputEvent::Tick => {}
}
}
}