freya_core/
events_combos.rs1use 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
19const LOCATION_THRESHOLD: f64 = 5.0;
21
22const MULTI_PRESS_ELAPSED: Duration = Duration::from_millis(500);
24
25pub 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 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 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 pub fn released() {
93 Self::get().pressing.set(false);
94 }
95
96 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum PressEventType {
125 Single,
127 Double,
129 Triple,
131 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}