1use alloc::vec::Vec;
2
3use crate::{LayoutResult, Pointf, Rectf, Tree, WidgetId};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub struct Modifiers {
7 pub shift: bool,
8 pub ctrl: bool,
9 pub alt: bool,
10 pub meta: bool,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum MouseButton {
15 Left,
16 Right,
17 Middle,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub struct KeyCode(pub u32);
22
23#[derive(Debug, Clone, PartialEq)]
24pub struct MouseEvent {
25 pub button: MouseButton,
26 pub position: Pointf,
27 pub modifiers: Modifiers,
28 pub click_count: u32,
29}
30
31#[derive(Debug, Clone, PartialEq)]
32pub struct KeyEvent {
33 pub key_code: KeyCode,
34 pub modifiers: Modifiers,
35 pub repeat: bool,
36}
37
38#[derive(Debug, Clone, PartialEq)]
39pub struct PointerEvent {
40 pub position: Pointf,
41 pub modifiers: Modifiers,
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub enum Event {
46 MouseDown(MouseEvent),
47 MouseUp(MouseEvent),
48 MouseMove(PointerEvent),
49 KeyDown(KeyEvent),
50 KeyUp(KeyEvent),
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum EventResponse {
55 Handled,
56 Bubble,
57}
58
59pub struct EventDispatcher<'a> {
60 tree: &'a Tree,
61 layout: &'a LayoutResult,
62 capture: Option<WidgetId>,
63}
64
65impl<'a> EventDispatcher<'a> {
66 pub fn new(tree: &'a Tree, layout: &'a LayoutResult) -> Self {
67 Self {
68 tree,
69 layout,
70 capture: None,
71 }
72 }
73
74 pub fn dispatch(&mut self, event: Event) -> EventResponse {
75 match &event {
76 Event::MouseDown(_) | Event::MouseUp(_) | Event::MouseMove(_) => {
77 self.dispatch_pointer(&event)
78 }
79 Event::KeyDown(_) | Event::KeyUp(_) => self.dispatch_keyboard(&event),
80 }
81 }
82
83 pub fn set_capture(&mut self, id: Option<WidgetId>) {
84 self.capture = id;
85 }
86
87 pub fn capture(&self) -> Option<WidgetId> {
88 self.capture
89 }
90
91 fn dispatch_pointer(&mut self, event: &Event) -> EventResponse {
92 let position = match event {
93 Event::MouseDown(e) => e.position,
94 Event::MouseUp(e) => e.position,
95 Event::MouseMove(e) => e.position,
96 _ => return EventResponse::Bubble,
97 };
98
99 let target = self.capture.or_else(|| self.hit_test(position));
100 let Some(target) = target else {
101 return EventResponse::Bubble;
102 };
103
104 self.dispatch_along_chain(target, event)
105 }
106
107 fn dispatch_keyboard(&mut self, event: &Event) -> EventResponse {
108 let Some(target) = self.tree.root() else {
109 return EventResponse::Bubble;
110 };
111 self.dispatch_along_chain(target, event)
112 }
113
114 fn dispatch_along_chain(&mut self, target: WidgetId, event: &Event) -> EventResponse {
115 let mut chain = Vec::new();
116 let mut current = Some(target);
117 while let Some(id) = current {
118 chain.push(id);
119 current = self.tree.find(id).and_then(|n| n.parent);
120 }
121
122 for id in chain {
123 if let Some(node) = self.tree.find(id) {
124 let response = match event {
125 Event::MouseDown(e) => node.widget.borrow_mut().on_mouse_down(e),
126 Event::MouseUp(e) => node.widget.borrow_mut().on_mouse_up(e),
127 Event::MouseMove(e) => node.widget.borrow_mut().on_mouse_move(e),
128 Event::KeyDown(e) => node.widget.borrow_mut().on_key_down(e),
129 Event::KeyUp(e) => node.widget.borrow_mut().on_key_up(e),
130 };
131 if response == EventResponse::Handled {
132 return EventResponse::Handled;
133 }
134 }
135 }
136
137 EventResponse::Bubble
138 }
139
140 pub fn hit_test(&self, point: Pointf) -> Option<WidgetId> {
147 let root = self.tree.root()?;
148 self.hit_test_node(root, point)
149 }
150
151 fn hit_test_node(&self, id: WidgetId, point: Pointf) -> Option<WidgetId> {
152 let layout_box = self.layout.get(id)?;
153 let rect = Rectf::new(layout_box.origin, layout_box.size);
154 if !rect.contains(point) {
155 return None;
156 }
157
158 for &child in self.tree.children_of(id) {
159 if let Some(hit) = self.hit_test_node(child, point) {
160 return Some(hit);
161 }
162 }
163
164 Some(id)
165 }
166}
167
168#[cfg(test)]
169mod tests {
170 use alloc::boxed::Box;
171 use alloc::rc::Rc;
172 use core::cell::Cell;
173
174 use crate::{
175 Insetsf, LayoutConstraints, LayoutEngine, LayoutNode, LayoutResult, Pointf, Sizef, Tree,
176 Widget, WidgetId,
177 };
178
179 use super::*;
180
181 struct Counters {
182 mouse_down: Cell<u32>,
183 mouse_up: Cell<u32>,
184 mouse_move: Cell<u32>,
185 key_down: Cell<u32>,
186 key_up: Cell<u32>,
187 }
188
189 impl Counters {
190 fn new() -> Rc<Self> {
191 Rc::new(Self {
192 mouse_down: Cell::new(0),
193 mouse_up: Cell::new(0),
194 mouse_move: Cell::new(0),
195 key_down: Cell::new(0),
196 key_up: Cell::new(0),
197 })
198 }
199 }
200
201 struct RecordingWidget {
202 id: WidgetId,
203 counters: Rc<Counters>,
204 mouse_down_response: EventResponse,
205 }
206
207 impl RecordingWidget {
208 fn new(counters: Rc<Counters>) -> Self {
209 Self {
210 id: WidgetId::new(),
211 counters,
212 mouse_down_response: EventResponse::Bubble,
213 }
214 }
215
216 fn with_mouse_down_response(mut self, response: EventResponse) -> Self {
217 self.mouse_down_response = response;
218 self
219 }
220 }
221
222 impl Widget for RecordingWidget {
223 fn id(&self) -> WidgetId {
224 self.id
225 }
226
227 fn on_mouse_down(&mut self, _event: &MouseEvent) -> EventResponse {
228 self.counters
229 .mouse_down
230 .set(self.counters.mouse_down.get() + 1);
231 self.mouse_down_response
232 }
233
234 fn on_mouse_up(&mut self, _event: &MouseEvent) -> EventResponse {
235 self.counters.mouse_up.set(self.counters.mouse_up.get() + 1);
236 EventResponse::Bubble
237 }
238
239 fn on_mouse_move(&mut self, _event: &PointerEvent) -> EventResponse {
240 self.counters
241 .mouse_move
242 .set(self.counters.mouse_move.get() + 1);
243 EventResponse::Bubble
244 }
245
246 fn on_key_down(&mut self, _event: &KeyEvent) -> EventResponse {
247 self.counters.key_down.set(self.counters.key_down.get() + 1);
248 EventResponse::Bubble
249 }
250
251 fn on_key_up(&mut self, _event: &KeyEvent) -> EventResponse {
252 self.counters.key_up.set(self.counters.key_up.get() + 1);
253 EventResponse::Bubble
254 }
255 }
256
257 fn fixed_constraints(width: f32, height: f32) -> LayoutConstraints {
258 LayoutConstraints {
259 min_width: Some(width),
260 max_width: Some(width),
261 min_height: Some(height),
262 max_height: Some(height),
263 }
264 }
265
266 fn make_mouse_event(x: f32, y: f32) -> Event {
267 Event::MouseDown(MouseEvent {
268 button: MouseButton::Left,
269 position: Pointf::new(x, y),
270 modifiers: Modifiers::default(),
271 click_count: 1,
272 })
273 }
274
275 type BuildTreeResult = (
276 Tree,
277 LayoutResult,
278 WidgetId,
279 WidgetId,
280 WidgetId,
281 Rc<Counters>,
282 Rc<Counters>,
283 Rc<Counters>,
284 );
285
286 fn build_tree() -> BuildTreeResult {
287 let mut tree = Tree::new();
288
289 let root_counters = Counters::new();
290 let root_widget = RecordingWidget::new(root_counters.clone());
291 let root_id = root_widget.id;
292 tree.insert(Box::new(root_widget), None);
293
294 let child_counters = Counters::new();
295 let child_widget = RecordingWidget::new(child_counters.clone());
296 let child_id = child_widget.id;
297 tree.insert(Box::new(child_widget), Some(root_id));
298
299 let leaf_counters = Counters::new();
300 let leaf_widget = RecordingWidget::new(leaf_counters.clone());
301 let leaf_id = leaf_widget.id;
302 tree.insert(Box::new(leaf_widget), Some(child_id));
303
304 let mut engine = LayoutEngine::new();
305 engine
306 .set_node(LayoutNode {
307 id: root_id,
308 ..LayoutNode::default()
309 })
310 .set_node(LayoutNode {
311 id: child_id,
312 margin: Insetsf::uniform(10.0),
313 preferred_size: Some(Sizef::new(80.0, 80.0)),
314 ..LayoutNode::default()
315 })
316 .set_node(LayoutNode {
317 id: leaf_id,
318 margin: Insetsf::uniform(10.0),
319 preferred_size: Some(Sizef::new(30.0, 30.0)),
320 ..LayoutNode::default()
321 });
322
323 let layout = engine.compute(&tree, fixed_constraints(100.0, 100.0));
324
325 (
326 tree,
327 layout,
328 root_id,
329 child_id,
330 leaf_id,
331 root_counters,
332 child_counters,
333 leaf_counters,
334 )
335 }
336
337 #[test]
338 fn mouse_down_hits_deepest_leaf() {
339 let (
340 tree,
341 layout,
342 _root_id,
343 _child_id,
344 leaf_id,
345 root_counters,
346 child_counters,
347 leaf_counters,
348 ) = build_tree();
349 let mut dispatcher = EventDispatcher::new(&tree, &layout);
350 let response = dispatcher.dispatch(make_mouse_event(25.0, 25.0));
351
352 assert_eq!(response, EventResponse::Bubble);
353 assert_eq!(leaf_counters.mouse_down.get(), 1);
354 assert_eq!(child_counters.mouse_down.get(), 1);
355 assert_eq!(root_counters.mouse_down.get(), 1);
356
357 let leaf_box = layout.get(leaf_id).unwrap();
358 assert_eq!(leaf_box.origin, Pointf::new(20.0, 20.0));
359 assert_eq!(leaf_box.size, Sizef::new(30.0, 30.0));
360 }
361
362 #[test]
363 fn mouse_down_outside_bubbles() {
364 let (
365 tree,
366 layout,
367 _root_id,
368 _child_id,
369 _leaf_id,
370 root_counters,
371 child_counters,
372 leaf_counters,
373 ) = build_tree();
374 let mut dispatcher = EventDispatcher::new(&tree, &layout);
375 let response = dispatcher.dispatch(make_mouse_event(200.0, 200.0));
376
377 assert_eq!(response, EventResponse::Bubble);
378 assert_eq!(root_counters.mouse_down.get(), 0);
379 assert_eq!(child_counters.mouse_down.get(), 0);
380 assert_eq!(leaf_counters.mouse_down.get(), 0);
381 }
382
383 #[test]
384 fn handled_event_stops_bubbling() {
385 let mut tree = Tree::new();
386
387 let root_counters = Counters::new();
388 let root_widget = RecordingWidget::new(root_counters.clone());
389 let root_id = root_widget.id;
390 tree.insert(Box::new(root_widget), None);
391
392 let child_counters = Counters::new();
393 let child_widget = RecordingWidget::new(child_counters.clone())
394 .with_mouse_down_response(EventResponse::Handled);
395 let child_id = child_widget.id;
396 tree.insert(Box::new(child_widget), Some(root_id));
397
398 let mut engine = LayoutEngine::new();
399 engine
400 .set_node(LayoutNode {
401 id: root_id,
402 ..LayoutNode::default()
403 })
404 .set_node(LayoutNode {
405 id: child_id,
406 preferred_size: Some(Sizef::new(50.0, 50.0)),
407 ..LayoutNode::default()
408 });
409
410 let layout = engine.compute(&tree, fixed_constraints(100.0, 100.0));
411 let mut dispatcher = EventDispatcher::new(&tree, &layout);
412 let response = dispatcher.dispatch(make_mouse_event(10.0, 10.0));
413
414 assert_eq!(response, EventResponse::Handled);
415 assert_eq!(child_counters.mouse_down.get(), 1);
416 assert_eq!(root_counters.mouse_down.get(), 0);
417 }
418
419 #[test]
420 fn keyboard_dispatch_reaches_root() {
421 let (
422 tree,
423 layout,
424 _root_id,
425 _child_id,
426 _leaf_id,
427 root_counters,
428 _child_counters,
429 _leaf_counters,
430 ) = build_tree();
431 let mut dispatcher = EventDispatcher::new(&tree, &layout);
432 let event = Event::KeyDown(KeyEvent {
433 key_code: KeyCode(42),
434 modifiers: Modifiers::default(),
435 repeat: false,
436 });
437 let response = dispatcher.dispatch(event);
438
439 assert_eq!(response, EventResponse::Bubble);
440 assert_eq!(root_counters.key_down.get(), 1);
441 }
442
443 #[test]
444 fn mouse_capture_redirects_events() {
445 let (
446 tree,
447 layout,
448 _root_id,
449 child_id,
450 leaf_id,
451 root_counters,
452 child_counters,
453 leaf_counters,
454 ) = build_tree();
455 let mut dispatcher = EventDispatcher::new(&tree, &layout);
456 dispatcher.set_capture(Some(child_id));
457
458 let response = dispatcher.dispatch(make_mouse_event(200.0, 200.0));
459
460 assert_eq!(response, EventResponse::Bubble);
461 assert_eq!(child_counters.mouse_down.get(), 1);
462 assert_eq!(root_counters.mouse_down.get(), 1);
463 assert_eq!(leaf_counters.mouse_down.get(), 0);
464
465 dispatcher.set_capture(Some(leaf_id));
466 let response = dispatcher.dispatch(make_mouse_event(200.0, 200.0));
467 assert_eq!(response, EventResponse::Bubble);
468 assert_eq!(leaf_counters.mouse_down.get(), 1);
469 }
470}