| 1 | use std::collections::VecDeque; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | const HISTORY_LIMIT: Duration = Duration::from_millis(150); |
| 5 | const DECELERATION_TOUCHPAD: f64 = 0.997; |
| 6 | |
| 7 | #[derive(Debug)] |
| 8 | pub struct SwipeTracker { |
| 9 | history: VecDeque<Event>, |
| 10 | pos: f64, |
| 11 | } |
| 12 | |
| 13 | #[derive(Debug, Clone, Copy)] |
| 14 | struct Event { |
| 15 | delta: f64, |
| 16 | timestamp: Duration, |
| 17 | } |
| 18 | |
| 19 | impl 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 | |
| 29 | pub fn push(&mut self, delta: f64, timestamp: Duration) { |
| 30 | |
| 31 | |
| 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 | |
| 49 | pub fn pos(&self) -> f64 { |
| 50 | self.pos |
| 51 | } |
| 52 | |
| 53 | |
| 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 | |
| 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 | } |