Skip to main content

pushrod/
controllers.rs

1// Controllers
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Controllers
17//!
18//! Reusable input controllers.  A controller owns one input pattern (click, drag, scroll, hover,
19//! long-press, key), watches the raw [`Event`]s a `Widget` receives, and reports high-level
20//! [`ControllerEvent`]s, so a `Widget` never re-implements "press, track, release inside",
21//! dragging thresholds, or press timing.
22//!
23//! A `Widget` keeps its controllers in its [`WidgetCore`](crate::widget::WidgetCore) with
24//! [`WidgetCore::add_controller`](crate::widget::WidgetCore::add_controller).  The default
25//! [`Widget::handle_event`](crate::widget::Widget::handle_event) feeds every event to them and calls
26//! [`Widget::on_controller_event`](crate::widget::Widget::on_controller_event) once per result:
27//!
28//! ```rust,no_run
29//! use pushrod::controllers::{ControllerEvent, DragController};
30//! use pushrod::event::{EventCtx, Propagation};
31//! use pushrod::geometry::{point, size};
32//! use pushrod::paint::{self, Painter};
33//! use pushrod::widget::{Widget, WidgetCore};
34//!
35//! pub struct Handle {
36//!     core: WidgetCore,
37//! }
38//!
39//! impl Handle {
40//!     pub fn new() -> Self {
41//!         let mut core = WidgetCore::new(point(0, 0), size(10, 10));
42//!         core.add_controller(DragController::new());
43//!         Self { core }
44//!     }
45//! }
46//!
47//! impl Widget for Handle {
48//!     fn core(&self) -> &WidgetCore { &self.core }
49//!     fn core_mut(&mut self) -> &mut WidgetCore { &mut self.core }
50//!     fn paint(&self, p: &mut dyn Painter) { paint::fill(p, self.get_color()); }
51//!
52//!     fn on_controller_event(&mut self, event: &ControllerEvent, _ctx: &mut EventCtx) -> Propagation {
53//!         if let ControllerEvent::DragUpdated { offset, .. } = event {
54//!             println!("dragged by {}, {}", offset.x, offset.y);
55//!             return Propagation::Stop;
56//!         }
57//!
58//!         Propagation::Continue
59//!     }
60//! }
61//! ```
62//!
63//! Controllers are plain state machines: they never touch the `Widget`, the clock, or SDL2, so
64//! they are tested by feeding events in.  Time comes from [`Event::Tick`] only.
65
66use crate::event::{Event, EventMask};
67use crate::geometry::{Point, point};
68use crate::input::{Key, Modifiers, MouseButton};
69use crate::widget::WidgetId;
70use std::time::Duration;
71
72/// A high-level result reported by a controller.
73#[derive(Debug, Clone, PartialEq)]
74pub enum ControllerEvent {
75    /// [`ClickController`]: the button went down on the `Widget`.
76    ClickPressed,
77    /// [`ClickController`]: while pressed, the pointer re-entered (`true`) or left (`false`) the
78    /// `Widget`.  A release is a click only while armed.
79    ClickArmed(bool),
80    /// [`ClickController`]: the button was released inside the `Widget` it was pressed on.
81    Clicked {
82        /// The button used.
83        button: MouseButton,
84        /// The click count (1 single, 2 double).
85        count: u8,
86    },
87    /// [`ClickController`]: the button was released outside the `Widget`; no click.
88    ClickCancelled,
89
90    /// [`DragController`]: the pointer moved past the threshold while pressed.
91    DragStarted {
92        /// Where the press happened, in window coordinates.
93        start: Point,
94    },
95    /// [`DragController`]: the pointer moved while dragging.
96    DragUpdated {
97        /// Where the press happened.
98        start: Point,
99        /// The movement since the press (`x` and `y` can be negative).
100        offset: Point,
101    },
102    /// [`DragController`]: the button was released after a drag.
103    DragEnded {
104        /// Where the press happened.
105        start: Point,
106        /// The total movement.
107        offset: Point,
108    },
109
110    /// [`ScrollController`]: the wheel or trackpad scrolled.
111    Scrolled {
112        /// How far it scrolled, horizontally (`x`) and vertically (`y`).
113        delta: Point,
114    },
115
116    /// [`HoverController`]: the pointer entered the `Widget`.
117    HoverEntered,
118    /// [`HoverController`]: the pointer left the `Widget`.
119    HoverExited,
120
121    /// [`LongPressController`]: the button was held, without moving, for the delay.
122    LongPressed {
123        /// Where the press happened.
124        position: Point,
125    },
126
127    /// [`KeyController`]: a key went down (or repeated).
128    KeyPressed {
129        /// The key.
130        key: Key,
131        /// The modifier keys held.
132        modifiers: Modifiers,
133        /// `true` if this is an auto-repeat.
134        repeat: bool,
135    },
136    /// [`KeyController`]: a key went up.
137    KeyReleased {
138        /// The key.
139        key: Key,
140        /// The modifier keys held.
141        modifiers: Modifiers,
142    },
143}
144
145/// An input pattern that turns raw [`Event`]s into [`ControllerEvent`]s.
146///
147/// Implement it to add a pattern of your own; the `Widget` side is unchanged.
148pub trait Controller {
149    /// Examines one event.
150    ///
151    /// # Arguments
152    ///
153    /// * `widget` - The ID of the `Widget` that owns the controller.
154    /// * `event` - The event the `Widget` received.
155    /// * `out` - Where to push the results, in order.
156    fn handle(&mut self, widget: WidgetId, event: &Event, out: &mut Vec<ControllerEvent>);
157
158    /// Returns the event classes the controller needs.
159    ///
160    /// # Returns
161    ///
162    /// The mask [`WidgetCore::add_controller`](crate::widget::WidgetCore::add_controller) adds to
163    /// the `Widget`'s event mask.
164    fn event_mask(&self) -> EventMask;
165}
166
167/// The list of controllers a `Widget` owns.
168#[derive(Default)]
169pub struct Controllers {
170    list: Vec<Box<dyn Controller>>,
171}
172
173impl Controllers {
174    /// Adds a controller.  Controllers see events in the order they were added.
175    ///
176    /// # Arguments
177    ///
178    /// * `controller` - The controller to add.
179    pub fn push(&mut self, controller: Box<dyn Controller>) {
180        self.list.push(controller);
181    }
182
183    /// Returns how many controllers there are.
184    ///
185    /// # Returns
186    ///
187    /// The count.
188    pub fn len(&self) -> usize {
189        self.list.len()
190    }
191
192    /// Returns whether there are no controllers.
193    ///
194    /// # Returns
195    ///
196    /// `true` if the list is empty.
197    pub fn is_empty(&self) -> bool {
198        self.list.is_empty()
199    }
200
201    /// Feeds one event to every controller.
202    ///
203    /// # Arguments
204    ///
205    /// * `widget` - The ID of the owning `Widget`.
206    /// * `event` - The event it received.
207    ///
208    /// # Returns
209    ///
210    /// The results of every controller, in order.  Empty if no controller reacted.
211    pub fn feed(&mut self, widget: WidgetId, event: &Event) -> Vec<ControllerEvent> {
212        let mut out = Vec::new();
213
214        for controller in &mut self.list {
215            controller.handle(widget, event, &mut out);
216        }
217
218        out
219    }
220}
221
222/// Reports clicks: press, track in and out of the `Widget`, release.
223///
224/// The press is "captured" by the engine, so the release arrives even when the pointer is outside.
225/// Reports [`ControllerEvent::ClickPressed`], [`ControllerEvent::ClickArmed`] as the pointer
226/// leaves and re-enters, then [`ControllerEvent::Clicked`] if released while armed, otherwise
227/// [`ControllerEvent::ClickCancelled`].  Only events addressed to the owning `Widget` count, so a
228/// press that bubbles up from a child is not a click on the parent.
229pub struct ClickController {
230    button: MouseButton,
231    pressed: bool,
232    armed: bool,
233}
234
235impl ClickController {
236    /// Creates a controller for the left mouse button.
237    ///
238    /// # Returns
239    ///
240    /// The controller.
241    pub fn new() -> Self {
242        Self::for_button(MouseButton::Left)
243    }
244
245    /// Creates a controller for a given mouse button.
246    ///
247    /// # Arguments
248    ///
249    /// * `button` - The button to watch.
250    ///
251    /// # Returns
252    ///
253    /// The controller.
254    pub fn for_button(button: MouseButton) -> Self {
255        Self {
256            button,
257            pressed: false,
258            armed: false,
259        }
260    }
261}
262
263impl Default for ClickController {
264    /// Creates the controller with its defaults.
265    ///
266    /// # Returns
267    ///
268    /// The controller.
269    fn default() -> Self {
270        Self::new()
271    }
272}
273
274impl Controller for ClickController {
275    /// Examines one event and reports any result.
276    ///
277    /// # Arguments
278    ///
279    /// * `widget` - The ID of the owning `Widget`.
280    /// * `event` - The event the `Widget` received.
281    /// * `out` - Where results are pushed.
282    fn handle(&mut self, widget: WidgetId, event: &Event, out: &mut Vec<ControllerEvent>) {
283        match event {
284            Event::PointerPressed { id, button, .. } if *id == widget && *button == self.button => {
285                self.pressed = true;
286                self.armed = true;
287                out.push(ControllerEvent::ClickPressed);
288            }
289
290            Event::PointerEntered { id } if *id == widget && self.pressed && !self.armed => {
291                self.armed = true;
292                out.push(ControllerEvent::ClickArmed(true));
293            }
294
295            Event::PointerExited { id } if *id == widget && self.pressed && self.armed => {
296                self.armed = false;
297                out.push(ControllerEvent::ClickArmed(false));
298            }
299
300            Event::PointerReleased {
301                id, button, count, ..
302            } if *id == widget && *button == self.button && self.pressed => {
303                out.push(if self.armed {
304                    ControllerEvent::Clicked {
305                        button: *button,
306                        count: *count,
307                    }
308                } else {
309                    ControllerEvent::ClickCancelled
310                });
311                self.pressed = false;
312                self.armed = false;
313            }
314
315            _ => {}
316        }
317    }
318
319    /// Returns the event classes this controller needs.
320    ///
321    /// # Returns
322    ///
323    /// The mask added to the `Widget`'s event mask.
324    fn event_mask(&self) -> EventMask {
325        EventMask::POINTER_BUTTONS | EventMask::HOVER
326    }
327}
328
329/// Reports drags: a press followed by movement past a threshold.
330///
331/// Reports [`ControllerEvent::DragStarted`] followed by [`ControllerEvent::DragUpdated`] when the
332/// pointer first moves `threshold` pixels from the press, then an update per move, then
333/// [`ControllerEvent::DragEnded`] on release.  A press and release without crossing the threshold
334/// reports nothing, so it can still be a click.
335pub struct DragController {
336    button: MouseButton,
337    threshold: u32,
338    start: Option<Point>,
339    dragging: bool,
340}
341
342impl DragController {
343    /// The default distance, in pixels, the pointer must move before a drag starts.
344    pub const DEFAULT_THRESHOLD: u32 = 4;
345
346    /// Creates a controller for the left mouse button and the default threshold.
347    ///
348    /// # Returns
349    ///
350    /// The controller.
351    pub fn new() -> Self {
352        Self::with_threshold(Self::DEFAULT_THRESHOLD)
353    }
354
355    /// Creates a controller for the left mouse button.
356    ///
357    /// # Arguments
358    ///
359    /// * `threshold` - The distance in pixels, measured in a straight line, that starts a drag.
360    ///   `0` starts the drag on the first movement.
361    ///
362    /// # Returns
363    ///
364    /// The controller.
365    pub fn with_threshold(threshold: u32) -> Self {
366        Self {
367            button: MouseButton::Left,
368            threshold,
369            start: None,
370            dragging: false,
371        }
372    }
373
374    /// Returns whether a drag is in progress.
375    ///
376    /// # Returns
377    ///
378    /// `true` between `DragStarted` and `DragEnded`.
379    pub fn is_dragging(&self) -> bool {
380        self.dragging
381    }
382}
383
384impl Default for DragController {
385    /// Creates the controller with its defaults.
386    ///
387    /// # Returns
388    ///
389    /// The controller.
390    fn default() -> Self {
391        Self::new()
392    }
393}
394
395impl Controller for DragController {
396    /// Examines one event and reports any result.
397    ///
398    /// # Arguments
399    ///
400    /// * `widget` - The ID of the owning `Widget`.
401    /// * `event` - The event the `Widget` received.
402    /// * `out` - Where results are pushed.
403    fn handle(&mut self, widget: WidgetId, event: &Event, out: &mut Vec<ControllerEvent>) {
404        match event {
405            Event::PointerPressed {
406                id,
407                button,
408                position,
409                ..
410            } if *id == widget && *button == self.button => {
411                self.start = Some(*position);
412                self.dragging = false;
413            }
414
415            Event::PointerMoved { id, position } if *id == widget => {
416                let Some(start) = self.start else { return };
417                let offset = point(position.x - start.x, position.y - start.y);
418
419                if !self.dragging {
420                    let (dx, dy) = (offset.x as i64, offset.y as i64);
421                    let limit = self.threshold as i64;
422
423                    if dx * dx + dy * dy < limit * limit || (dx == 0 && dy == 0) {
424                        return;
425                    }
426
427                    self.dragging = true;
428                    out.push(ControllerEvent::DragStarted { start });
429                }
430
431                out.push(ControllerEvent::DragUpdated { start, offset });
432            }
433
434            Event::PointerReleased {
435                id,
436                button,
437                position,
438                ..
439            } if *id == widget && *button == self.button => {
440                if let (Some(start), true) = (self.start, self.dragging) {
441                    out.push(ControllerEvent::DragEnded {
442                        start,
443                        offset: point(position.x - start.x, position.y - start.y),
444                    });
445                }
446
447                self.start = None;
448                self.dragging = false;
449            }
450
451            _ => {}
452        }
453    }
454
455    /// Returns the event classes this controller needs.
456    ///
457    /// # Returns
458    ///
459    /// The mask added to the `Widget`'s event mask.
460    fn event_mask(&self) -> EventMask {
461        EventMask::POINTER_BUTTONS | EventMask::POINTER_MOTION
462    }
463}
464
465/// Reports wheel and trackpad scrolling.
466///
467/// Scrolls bubble, so a scrolling container sees scrolls over its children too.
468#[derive(Default)]
469pub struct ScrollController;
470
471impl ScrollController {
472    /// Creates the controller.
473    ///
474    /// # Returns
475    ///
476    /// The controller.
477    pub fn new() -> Self {
478        Self
479    }
480}
481
482impl Controller for ScrollController {
483    /// Examines one event and reports any result.
484    ///
485    /// # Arguments
486    ///
487    /// * `_widget` - The ID of the owning `Widget` (unused).
488    /// * `event` - The event the `Widget` received.
489    /// * `out` - Where results are pushed.
490    fn handle(&mut self, _widget: WidgetId, event: &Event, out: &mut Vec<ControllerEvent>) {
491        if let Event::Scrolled { delta, .. } = event {
492            out.push(ControllerEvent::Scrolled { delta: *delta });
493        }
494    }
495
496    /// Returns the event classes this controller needs.
497    ///
498    /// # Returns
499    ///
500    /// The mask added to the `Widget`'s event mask.
501    fn event_mask(&self) -> EventMask {
502        EventMask::SCROLL
503    }
504}
505
506/// Reports the pointer entering and leaving the `Widget`.
507#[derive(Default)]
508pub struct HoverController {
509    hovered: bool,
510}
511
512impl HoverController {
513    /// Creates the controller.
514    ///
515    /// # Returns
516    ///
517    /// The controller.
518    pub fn new() -> Self {
519        Self::default()
520    }
521}
522
523impl Controller for HoverController {
524    /// Examines one event and reports any result.
525    ///
526    /// # Arguments
527    ///
528    /// * `widget` - The ID of the owning `Widget`.
529    /// * `event` - The event the `Widget` received.
530    /// * `out` - Where results are pushed.
531    fn handle(&mut self, widget: WidgetId, event: &Event, out: &mut Vec<ControllerEvent>) {
532        match event {
533            Event::PointerEntered { id } if *id == widget && !self.hovered => {
534                self.hovered = true;
535                out.push(ControllerEvent::HoverEntered);
536            }
537
538            Event::PointerExited { id } if *id == widget && self.hovered => {
539                self.hovered = false;
540                out.push(ControllerEvent::HoverExited);
541            }
542
543            _ => {}
544        }
545    }
546
547    /// Returns the event classes this controller needs.
548    ///
549    /// # Returns
550    ///
551    /// The mask added to the `Widget`'s event mask.
552    fn event_mask(&self) -> EventMask {
553        EventMask::HOVER
554    }
555}
556
557/// Reports a press held in place for a delay.
558///
559/// Time advances only through [`Event::Tick`], so the `Widget` must receive ticks (the
560/// [`EventMask::TIMER`] class).  The press is cancelled by a release, or by moving more than
561/// `slop` pixels.  It reports [`ControllerEvent::LongPressed`] at most once per press.
562pub struct LongPressController {
563    button: MouseButton,
564    delay: Duration,
565    slop: u32,
566    press: Option<Point>,
567    held: Duration,
568    fired: bool,
569}
570
571impl LongPressController {
572    /// The default hold time.
573    pub const DEFAULT_DELAY: Duration = Duration::from_millis(500);
574    /// The default distance, in pixels, the pointer may wander during a long press.
575    pub const DEFAULT_SLOP: u32 = 6;
576
577    /// Creates a controller for the left mouse button with the default delay and slop.
578    ///
579    /// # Returns
580    ///
581    /// The controller.
582    pub fn new() -> Self {
583        Self::with_delay(Self::DEFAULT_DELAY)
584    }
585
586    /// Creates a controller for the left mouse button with the default slop.
587    ///
588    /// # Arguments
589    ///
590    /// * `delay` - How long the button must be held.
591    ///
592    /// # Returns
593    ///
594    /// The controller.
595    pub fn with_delay(delay: Duration) -> Self {
596        Self {
597            button: MouseButton::Left,
598            delay,
599            slop: Self::DEFAULT_SLOP,
600            press: None,
601            held: Duration::ZERO,
602            fired: false,
603        }
604    }
605}
606
607impl Default for LongPressController {
608    /// Creates the controller with its defaults.
609    ///
610    /// # Returns
611    ///
612    /// The controller.
613    fn default() -> Self {
614        Self::new()
615    }
616}
617
618impl Controller for LongPressController {
619    /// Examines one event and reports any result.
620    ///
621    /// # Arguments
622    ///
623    /// * `widget` - The ID of the owning `Widget`.
624    /// * `event` - The event the `Widget` received.
625    /// * `out` - Where results are pushed.
626    fn handle(&mut self, widget: WidgetId, event: &Event, out: &mut Vec<ControllerEvent>) {
627        match event {
628            Event::PointerPressed {
629                id,
630                button,
631                position,
632                ..
633            } if *id == widget && *button == self.button => {
634                self.press = Some(*position);
635                self.held = Duration::ZERO;
636                self.fired = false;
637            }
638
639            Event::PointerMoved { id, position } if *id == widget => {
640                if let Some(start) = self.press {
641                    let (dx, dy) = ((position.x - start.x) as i64, (position.y - start.y) as i64);
642                    let limit = self.slop as i64;
643
644                    if dx * dx + dy * dy > limit * limit {
645                        self.press = None;
646                    }
647                }
648            }
649
650            Event::PointerReleased { id, button, .. }
651                if *id == widget && *button == self.button =>
652            {
653                self.press = None;
654            }
655
656            Event::Tick { elapsed } if !self.fired => {
657                if let Some(position) = self.press {
658                    self.held += *elapsed;
659
660                    if self.held >= self.delay {
661                        self.fired = true;
662                        out.push(ControllerEvent::LongPressed { position });
663                    }
664                }
665            }
666
667            _ => {}
668        }
669    }
670
671    /// Returns the event classes this controller needs.
672    ///
673    /// # Returns
674    ///
675    /// The mask added to the `Widget`'s event mask.
676    fn event_mask(&self) -> EventMask {
677        EventMask::POINTER_BUTTONS | EventMask::POINTER_MOTION | EventMask::TIMER
678    }
679}
680
681/// Reports key presses and releases, optionally only for chosen keys.
682///
683/// Key events bubble, so a container can handle keys its focused child ignored.
684#[derive(Default)]
685pub struct KeyController {
686    keys: Option<Vec<Key>>,
687}
688
689impl KeyController {
690    /// Creates a controller that reports every key.
691    ///
692    /// # Returns
693    ///
694    /// The controller.
695    pub fn new() -> Self {
696        Self::default()
697    }
698
699    /// Creates a controller that reports only the given keys.
700    ///
701    /// # Arguments
702    ///
703    /// * `keys` - The keys to report.
704    ///
705    /// # Returns
706    ///
707    /// The controller.
708    pub fn for_keys(keys: &[Key]) -> Self {
709        Self {
710            keys: Some(keys.to_vec()),
711        }
712    }
713
714    /// Returns whether `key` is reported.
715    fn wants(&self, key: Key) -> bool {
716        self.keys.as_ref().is_none_or(|keys| keys.contains(&key))
717    }
718}
719
720impl Controller for KeyController {
721    /// Examines one event and reports any result.
722    ///
723    /// # Arguments
724    ///
725    /// * `_widget` - The ID of the owning `Widget` (unused).
726    /// * `event` - The event the `Widget` received.
727    /// * `out` - Where results are pushed.
728    fn handle(&mut self, _widget: WidgetId, event: &Event, out: &mut Vec<ControllerEvent>) {
729        match event {
730            Event::KeyPressed {
731                key,
732                modifiers,
733                repeat,
734                ..
735            } if self.wants(*key) => out.push(ControllerEvent::KeyPressed {
736                key: *key,
737                modifiers: *modifiers,
738                repeat: *repeat,
739            }),
740
741            Event::KeyReleased { key, modifiers, .. } if self.wants(*key) => {
742                out.push(ControllerEvent::KeyReleased {
743                    key: *key,
744                    modifiers: *modifiers,
745                })
746            }
747
748            _ => {}
749        }
750    }
751
752    /// Returns the event classes this controller needs.
753    ///
754    /// # Returns
755    ///
756    /// The mask added to the `Widget`'s event mask.
757    fn event_mask(&self) -> EventMask {
758        EventMask::KEYBOARD
759    }
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    const ID: WidgetId = 7;
767
768    fn press(position: Point) -> Event {
769        Event::PointerPressed {
770            id: ID,
771            button: MouseButton::Left,
772            position,
773            count: 1,
774        }
775    }
776
777    fn release(position: Point, count: u8) -> Event {
778        Event::PointerReleased {
779            id: ID,
780            button: MouseButton::Left,
781            position,
782            count,
783        }
784    }
785
786    fn moved(position: Point) -> Event {
787        Event::PointerMoved { id: ID, position }
788    }
789
790    fn run(controller: &mut dyn Controller, events: &[Event]) -> Vec<ControllerEvent> {
791        let mut out = Vec::new();
792
793        for event in events {
794            controller.handle(ID, event, &mut out);
795        }
796
797        out
798    }
799
800    #[test]
801    fn click_inside_reports_pressed_then_clicked() {
802        let mut c = ClickController::new();
803        let out = run(&mut c, &[press(point(1, 1)), release(point(1, 1), 2)]);
804
805        assert_eq!(
806            out,
807            vec![
808                ControllerEvent::ClickPressed,
809                ControllerEvent::Clicked {
810                    button: MouseButton::Left,
811                    count: 2
812                }
813            ]
814        );
815    }
816
817    #[test]
818    fn click_released_outside_is_cancelled() {
819        let mut c = ClickController::new();
820        let out = run(
821            &mut c,
822            &[
823                press(point(1, 1)),
824                Event::PointerExited { id: ID },
825                release(point(99, 99), 1),
826            ],
827        );
828
829        assert_eq!(
830            out,
831            vec![
832                ControllerEvent::ClickPressed,
833                ControllerEvent::ClickArmed(false),
834                ControllerEvent::ClickCancelled
835            ]
836        );
837    }
838
839    #[test]
840    fn click_rearms_when_pointer_returns() {
841        let mut c = ClickController::new();
842        let out = run(
843            &mut c,
844            &[
845                press(point(1, 1)),
846                Event::PointerExited { id: ID },
847                Event::PointerEntered { id: ID },
848                release(point(1, 1), 1),
849            ],
850        );
851
852        assert_eq!(out[2], ControllerEvent::ClickArmed(true));
853        assert!(matches!(out[3], ControllerEvent::Clicked { .. }));
854    }
855
856    #[test]
857    fn click_ignores_other_buttons_other_widgets_and_stray_releases() {
858        let mut c = ClickController::new();
859        let right = Event::PointerPressed {
860            id: ID,
861            button: MouseButton::Right,
862            position: point(0, 0),
863            count: 1,
864        };
865        let child = Event::PointerPressed {
866            id: ID + 1,
867            button: MouseButton::Left,
868            position: point(0, 0),
869            count: 1,
870        };
871
872        assert!(run(&mut c, &[right, child, release(point(0, 0), 1)]).is_empty());
873    }
874
875    #[test]
876    fn drag_starts_past_threshold_and_ends_on_release() {
877        let mut c = DragController::with_threshold(5);
878        let start = point(10, 10);
879        let out = run(
880            &mut c,
881            &[
882                press(start),
883                moved(point(12, 12)),
884                moved(point(20, 10)),
885                moved(point(25, 8)),
886                release(point(25, 8), 1),
887            ],
888        );
889
890        assert_eq!(
891            out,
892            vec![
893                ControllerEvent::DragStarted { start },
894                ControllerEvent::DragUpdated {
895                    start,
896                    offset: point(10, 0)
897                },
898                ControllerEvent::DragUpdated {
899                    start,
900                    offset: point(15, -2)
901                },
902                ControllerEvent::DragEnded {
903                    start,
904                    offset: point(15, -2)
905                },
906            ]
907        );
908        assert!(!c.is_dragging());
909    }
910
911    #[test]
912    fn drag_below_threshold_reports_nothing() {
913        let mut c = DragController::new();
914        let out = run(
915            &mut c,
916            &[
917                press(point(0, 0)),
918                moved(point(1, 1)),
919                release(point(1, 1), 1),
920            ],
921        );
922
923        assert!(out.is_empty());
924    }
925
926    #[test]
927    fn drag_needs_a_press_first() {
928        let mut c = DragController::with_threshold(0);
929
930        assert!(run(&mut c, &[moved(point(50, 50))]).is_empty());
931    }
932
933    #[test]
934    fn drag_with_zero_threshold_starts_on_first_movement_only() {
935        let mut c = DragController::with_threshold(0);
936        let out = run(
937            &mut c,
938            &[press(point(0, 0)), moved(point(0, 0)), moved(point(1, 0))],
939        );
940
941        assert_eq!(out.len(), 2);
942        assert!(matches!(out[0], ControllerEvent::DragStarted { .. }));
943    }
944
945    #[test]
946    fn scroll_reports_delta_even_for_bubbled_events() {
947        let mut c = ScrollController::new();
948        let out = run(
949            &mut c,
950            &[Event::Scrolled {
951                id: ID + 5,
952                delta: point(0, -3),
953            }],
954        );
955
956        assert_eq!(
957            out,
958            vec![ControllerEvent::Scrolled {
959                delta: point(0, -3)
960            }]
961        );
962    }
963
964    #[test]
965    fn hover_reports_enter_and_exit_once() {
966        let mut c = HoverController::new();
967        let out = run(
968            &mut c,
969            &[
970                Event::PointerEntered { id: ID },
971                Event::PointerEntered { id: ID },
972                Event::PointerExited { id: ID },
973                Event::PointerExited { id: ID },
974            ],
975        );
976
977        assert_eq!(
978            out,
979            vec![ControllerEvent::HoverEntered, ControllerEvent::HoverExited]
980        );
981    }
982
983    fn tick(ms: u64) -> Event {
984        Event::Tick {
985            elapsed: Duration::from_millis(ms),
986        }
987    }
988
989    #[test]
990    fn long_press_fires_once_after_the_delay() {
991        let mut c = LongPressController::with_delay(Duration::from_millis(300));
992        let out = run(
993            &mut c,
994            &[press(point(3, 4)), tick(200), tick(100), tick(100)],
995        );
996
997        assert_eq!(
998            out,
999            vec![ControllerEvent::LongPressed {
1000                position: point(3, 4)
1001            }]
1002        );
1003    }
1004
1005    #[test]
1006    fn long_press_is_cancelled_by_release_or_movement() {
1007        let delay = Duration::from_millis(100);
1008        let mut released = LongPressController::with_delay(delay);
1009        let mut wandered = LongPressController::with_delay(delay);
1010
1011        assert!(
1012            run(
1013                &mut released,
1014                &[press(point(0, 0)), release(point(0, 0), 1), tick(500)]
1015            )
1016            .is_empty()
1017        );
1018        assert!(
1019            run(
1020                &mut wandered,
1021                &[press(point(0, 0)), moved(point(40, 0)), tick(500)]
1022            )
1023            .is_empty()
1024        );
1025        assert!(run(&mut LongPressController::new(), &[tick(5000)]).is_empty());
1026    }
1027
1028    #[test]
1029    fn long_press_allows_small_movement() {
1030        let mut c = LongPressController::with_delay(Duration::from_millis(100));
1031        let out = run(&mut c, &[press(point(0, 0)), moved(point(2, 2)), tick(100)]);
1032
1033        assert_eq!(out.len(), 1);
1034    }
1035
1036    #[test]
1037    fn long_press_can_fire_again_on_the_next_press() {
1038        let mut c = LongPressController::with_delay(Duration::from_millis(10));
1039        let out = run(
1040            &mut c,
1041            &[
1042                press(point(0, 0)),
1043                tick(10),
1044                release(point(0, 0), 1),
1045                press(point(0, 0)),
1046                tick(10),
1047            ],
1048        );
1049
1050        assert_eq!(out.len(), 2);
1051    }
1052
1053    #[test]
1054    fn key_reports_all_keys_or_only_the_chosen_ones() {
1055        let down = |key| Event::KeyPressed {
1056            id: ID,
1057            key,
1058            modifiers: Modifiers::empty(),
1059            repeat: false,
1060        };
1061        let up = Event::KeyReleased {
1062            id: ID,
1063            key: Key::Return,
1064            modifiers: Modifiers::empty(),
1065        };
1066
1067        assert_eq!(
1068            run(&mut KeyController::new(), &[down(Key::Char('a'))]).len(),
1069            1
1070        );
1071
1072        let mut only_return = KeyController::for_keys(&[Key::Return]);
1073        let out = run(
1074            &mut only_return,
1075            &[down(Key::Char('a')), down(Key::Return), up],
1076        );
1077
1078        assert_eq!(out.len(), 2);
1079        assert!(matches!(
1080            out[1],
1081            ControllerEvent::KeyReleased {
1082                key: Key::Return,
1083                ..
1084            }
1085        ));
1086    }
1087
1088    #[test]
1089    fn controllers_feed_in_order_and_report_masks() {
1090        let mut list = Controllers::default();
1091
1092        assert!(list.is_empty());
1093
1094        list.push(Box::new(HoverController::new()));
1095        list.push(Box::new(ClickController::new()));
1096
1097        assert_eq!(list.len(), 2);
1098        assert_eq!(
1099            list.feed(ID, &Event::PointerEntered { id: ID }),
1100            vec![ControllerEvent::HoverEntered]
1101        );
1102        assert!(
1103            LongPressController::new()
1104                .event_mask()
1105                .contains(EventMask::TIMER)
1106        );
1107        assert_eq!(ScrollController::new().event_mask(), EventMask::SCROLL);
1108    }
1109}