Skip to main content

freya_core/
events_combos.rs

1use std::time::{
2    Duration,
3    Instant,
4};
5
6use torin::prelude::CursorPoint;
7
8use crate::{
9    integration::ScopeId,
10    prelude::{
11        State,
12        *,
13    },
14};
15
16#[derive(Clone, Copy, PartialEq)]
17pub struct EventsCombos {
18    pub(crate) last_press: State<Option<(Instant, CursorPoint, u8)>>,
19}
20
21impl EventsCombos {
22    pub fn get() -> Self {
23        match try_consume_root_context() {
24            Some(rt) => rt,
25            None => {
26                let context_menu_state = EventsCombos {
27                    last_press: State::create_in_scope(None, ScopeId::ROOT),
28                };
29                provide_context_for_scope_id(context_menu_state, ScopeId::ROOT);
30                context_menu_state
31            }
32        }
33    }
34
35    pub fn pressed(location: CursorPoint) -> PressEventType {
36        let mut combos = Self::get();
37        let (event_type, click_count) = match &*combos.last_press.read() {
38            Some((inst, last_location, count)) if inst.elapsed() <= MULTI_PRESS_ELAPSED => {
39                if last_location.distance_to(location) <= LOCATION_THRESHOLD {
40                    match count {
41                        1 => (PressEventType::Double, 2),
42                        2 => (PressEventType::Triple, 3),
43                        3 => (PressEventType::Quadruple, 4),
44                        _ => (PressEventType::Single, 1),
45                    }
46                } else {
47                    (PressEventType::Single, 1)
48                }
49            }
50            _ => (PressEventType::Single, 1),
51        };
52        combos
53            .last_press
54            .set(Some((Instant::now(), location, click_count)));
55        event_type
56    }
57}
58
59const LOCATION_THRESHOLD: f64 = 5.0;
60const MULTI_PRESS_ELAPSED: Duration = Duration::from_millis(500);
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum PressEventType {
64    Single,
65    Double,
66    Triple,
67    Quadruple,
68}
69
70impl PressEventType {
71    pub fn is_single(&self) -> bool {
72        matches!(self, Self::Single)
73    }
74
75    pub fn is_double(&self) -> bool {
76        matches!(self, Self::Double)
77    }
78
79    pub fn is_triple(&self) -> bool {
80        matches!(self, Self::Triple)
81    }
82
83    pub fn is_quadruple(&self) -> bool {
84        matches!(self, Self::Quadruple)
85    }
86}