ltk/input/gesture/
fling.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Release velocity of a swipe, so a quick flick commits it whatever its
//! travel and a quick flick back cancels it.

use std::collections::VecDeque;

/// Release speed, logical px/s, that decides a swipe on its own.
pub const FLING_VELOCITY: f32 = 500.0;
/// Travel a forward fling needs, logical px, so a twitch does not commit.
pub const FLING_MIN_TRAVEL: f32 = 24.0;

/// Speed of a finger along one axis over the last `WINDOW_MS` of input,
/// from the events' own timestamps. A finger that rested before lifting
/// has no samples left in the window and reads as still.
#[ derive( Debug, Clone, Default ) ]
pub struct FlingTracker
{
	samples: VecDeque<( u32, f32 )>,
}

impl FlingTracker
{
	const WINDOW_MS: u32 = 100;

	pub fn clear( &mut self ) { self.samples.clear(); }

	pub fn push( &mut self, time_ms: u32, pos: f32 )
	{
		self.samples.push_back( ( time_ms, pos ) );
		while let Some( &( t, _ ) ) = self.samples.front()
		{
			if time_ms.wrapping_sub( t ) <= Self::WINDOW_MS { break; }
			self.samples.pop_front();
		}
	}

	/// Px/s in the unit of the pushed positions; 0 when the window spans
	/// too little time to tell.
	pub fn velocity( &self ) -> f32
	{
		let ( Some( &( t0, p0 ) ), Some( &( t1, p1 ) ) ) = ( self.samples.front(), self.samples.back() ) else
		{
			return 0.0;
		};
		let dt = t1.wrapping_sub( t0 );
		if dt < 8 { return 0.0; }
		( p1 - p0 ) * 1000.0 / dt as f32
	}
}

#[ cfg( test ) ]
mod tests
{
	use super::*;

	#[ test ]
	fn measures_recent_speed()
	{
		let mut t = FlingTracker::default();
		t.push( 0, 0.0 );
		t.push( 20, 10.0 );
		t.push( 40, 20.0 );
		assert!( ( t.velocity() - 500.0 ).abs() < 1e-3 );
	}

	#[ test ]
	fn forgets_a_rest_before_lifting()
	{
		let mut t = FlingTracker::default();
		t.push( 0, 0.0 );
		t.push( 20, 40.0 );
		t.push( 300, 40.0 );
		assert_eq!( t.velocity(), 0.0 );
	}
}