forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB2d82fddIvan Molodetskikh1 year ago2536 commits

swipe_tracker.rs87 lines, 2.3 KiBHistoryRawDownload
1use std::collections::VecDeque;
2use std::time::Duration;
3
4const HISTORY_LIMIT: Duration = Duration::from_millis(150);
5const DECELERATION_TOUCHPAD: f64 = 0.997;
6
7#[derive(Debug)]
8pub struct SwipeTracker {
9 history: VecDeque<Event>,
10 pos: f64,
11}
12
13#[derive(Debug, Clone, Copy)]
14struct Event {
15 delta: f64,
16 timestamp: Duration,
17}
18
19impl SwipeTracker {
20 #[allow(clippy::new_without_default)]
21 pub fn new() -> Self {
22 Self {
23 history: VecDeque::new(),
24 pos: 0.,
25 }
26 }
27
28 /// Pushes a new reading into the tracker.
29 pub fn push(&mut self, delta: f64, timestamp: Duration) {
30 // For the events that we care about, timestamps should always increase
31 // monotonically.
32 if let Some(last) = self.history.back() {
33 if timestamp < last.timestamp {
34 trace!(
35 "ignoring event with timestamp {timestamp:?} earlier than last {:?}",
36 last.timestamp
37 );
38 return;
39 }
40 }
41
42 self.history.push_back(Event { delta, timestamp });
43 self.pos += delta;
44
45 self.trim_history();
46 }
47
48 /// Returns the current gesture position.
49 pub fn pos(&self) -> f64 {
50 self.pos
51 }
52
53 /// Computes the current gesture velocity.
54 pub fn velocity(&self) -> f64 {
55 let (Some(first), Some(last)) = (self.history.front(), self.history.back()) else {
56 return 0.;
57 };
58
59 let total_time = (last.timestamp - first.timestamp).as_secs_f64();
60 if total_time == 0. {
61 return 0.;
62 }
63
64 let total_delta = self.history.iter().map(|event| event.delta).sum::<f64>();
65 total_delta / total_time
66 }
67
68 /// Computes the gesture end position after decelerating to a halt.
69 pub fn projected_end_pos(&self) -> f64 {
70 let vel = self.velocity();
71 self.pos - vel / (1000. * DECELERATION_TOUCHPAD.ln())
72 }
73
74 fn trim_history(&mut self) {
75 let Some(&Event { timestamp, .. }) = self.history.back() else {
76 return;
77 };
78
79 while let Some(first) = self.history.front() {
80 if timestamp <= first.timestamp + HISTORY_LIMIT {
81 break;
82 }
83
84 let _ = self.history.pop_front();
85 }
86 }
87}