Skip to main content

freya_core/
events_combos.rs

1use std::{
2    marker::PhantomData,
3    time::{
4        Duration,
5        Instant,
6    },
7};
8
9use torin::prelude::CursorPoint;
10
11use crate::{
12    integration::ScopeId,
13    prelude::{
14        State,
15        *,
16    },
17};
18
19/// Maximum distance between two presses of the same combo.
20const LOCATION_THRESHOLD: f64 = 5.0;
21
22/// Maximum time between two presses of the same combo.
23const MULTI_PRESS_ELAPSED: Duration = Duration::from_millis(500);
24
25/// Turns consecutive presses into double, triple and quadruple presses.
26///
27/// # Example
28///
29/// ```rust, no_run
30/// # use freya::prelude::*;
31/// # fn app() -> impl IntoElement {
32/// rect().on_pointer_down(|e: Event<PointerEventData>| {
33///     if EventsCombos::<()>::pressed(e.global_location()).is_double() {
34///         println!("Double press");
35///     }
36/// })
37/// # }
38/// ```
39pub struct EventsCombos<Gesture = ()> {
40    pub(crate) last_press: State<Option<(Instant, CursorPoint, u8)>>,
41    pub(crate) pressing: State<bool>,
42    marker: PhantomData<Gesture>,
43}
44
45impl<Gesture> Clone for EventsCombos<Gesture> {
46    fn clone(&self) -> Self {
47        *self
48    }
49}
50
51impl<Gesture> Copy for EventsCombos<Gesture> {}
52
53impl<Gesture> PartialEq for EventsCombos<Gesture> {
54    fn eq(&self, other: &Self) -> bool {
55        self.last_press == other.last_press && self.pressing == other.pressing
56    }
57}
58
59impl<Gesture: Clone + PartialEq + 'static> EventsCombos<Gesture> {
60    /// Get the app-wide combos state, creating it on first use.
61    pub fn get() -> Self {
62        match try_consume_root_context() {
63            Some(rt) => rt,
64            None => {
65                let combos = EventsCombos {
66                    last_press: State::create_in_scope(None, ScopeId::ROOT),
67                    pressing: State::create_in_scope(false, ScopeId::ROOT),
68                    marker: PhantomData,
69                };
70                provide_context_for_scope_id(combos, ScopeId::ROOT);
71                combos
72            }
73        }
74    }
75
76    /// Break the combo when the held pointer drags away from the last press.
77    pub fn moved(location: CursorPoint) -> bool {
78        let mut combos = Self::get();
79        let dragged_away = *combos.pressing.read()
80            && matches!(
81                &*combos.last_press.read(),
82                Some((_, last_location, _)) if last_location.distance_to(location) > LOCATION_THRESHOLD
83            );
84        if dragged_away {
85            combos.last_press.set(None);
86            combos.pressing.set(false);
87        }
88        dragged_away
89    }
90
91    /// Mark the pointer as released.
92    pub fn released() {
93        Self::get().pressing.set(false);
94    }
95
96    /// Register a press and get its position in the combo.
97    pub fn pressed(location: CursorPoint) -> PressEventType {
98        let mut combos = Self::get();
99        let (event_type, click_count) = match &*combos.last_press.read() {
100            Some((inst, last_location, count)) if inst.elapsed() <= MULTI_PRESS_ELAPSED => {
101                if last_location.distance_to(location) <= LOCATION_THRESHOLD {
102                    match count {
103                        1 => (PressEventType::Double, 2),
104                        2 => (PressEventType::Triple, 3),
105                        3 => (PressEventType::Quadruple, 4),
106                        _ => (PressEventType::Single, 1),
107                    }
108                } else {
109                    (PressEventType::Single, 1)
110                }
111            }
112            _ => (PressEventType::Single, 1),
113        };
114        combos
115            .last_press
116            .set(Some((Instant::now(), location, click_count)));
117        combos.pressing.set(true);
118        event_type
119    }
120}
121
122/// Position of a press inside a combo.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum PressEventType {
125    /// First press of a combo.
126    Single,
127    /// Second press of a combo.
128    Double,
129    /// Third press of a combo.
130    Triple,
131    /// Fourth and last press of a combo.
132    Quadruple,
133}
134
135impl PressEventType {
136    pub fn is_single(&self) -> bool {
137        matches!(self, Self::Single)
138    }
139
140    pub fn is_double(&self) -> bool {
141        matches!(self, Self::Double)
142    }
143
144    pub fn is_triple(&self) -> bool {
145        matches!(self, Self::Triple)
146    }
147
148    pub fn is_quadruple(&self) -> bool {
149        matches!(self, Self::Quadruple)
150    }
151}