BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / user_activity.rs

user_activity.rs

user_activity.rs 4.3 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::time::{Duration, Instant};
4
5use tokio::sync::watch;
6
7pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
8const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
9
10pub struct UserInput {
11 origin: Instant,
12 last_input_millis: AtomicU64,
13}
14
15impl UserInput {
16 pub fn new() -> Arc<Self> {
17 Arc::new(UserInput {
18 origin: Instant::now(),
19 last_input_millis: AtomicU64::new(0),
20 })
21 }
22
23 pub fn touch(&self) {
24 let elapsed = self.origin.elapsed().as_millis() as u64;
25 self.last_input_millis.store(elapsed, Ordering::Relaxed);
26 }
27
28 fn last_input(&self) -> Instant {
29 self.origin + Duration::from_millis(self.last_input_millis.load(Ordering::Relaxed))
30 }
31}
32
33pub fn latest_input(app_input: Instant, system_idle: Option<Duration>, now: Instant) -> Instant {
34 match system_idle.and_then(|idle| now.checked_sub(idle)) {
35 Some(system_input) => app_input.max(system_input),
36 None => app_input,
37 }
38}
39
40pub fn is_active(last_input: Instant, now: Instant, idle_after: Duration) -> bool {
41 now.saturating_duration_since(last_input) < idle_after
42}
43
44pub fn activity_change(previous: bool, last_input: Instant, now: Instant, idle_after: Duration) -> Option<bool> {
45 let current = is_active(last_input, now, idle_after);
46 (current != previous).then_some(current)
47}
48
49pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
50 let (sender, receiver) = watch::channel(true);
51 crate::runtime::handle().spawn(async move {
52 let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
53 loop {
54 interval.tick().await;
55 let now = Instant::now();
56 let last_input = latest_input(input.last_input(), system_idle(), now);
57 let previous = *sender.borrow();
58 if let Some(current) = activity_change(previous, last_input, now, IDLE_AFTER) {
59 sender.send_replace(current);
60 }
61 }
62 });
63 receiver
64}
65
66#[cfg(windows)]
67fn system_idle() -> Option<Duration> {
68 use windows::Win32::System::SystemInformation::GetTickCount;
69 use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};
70
71 let mut info = LASTINPUTINFO {
72 cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32,
73 dwTime: 0,
74 };
75 unsafe { GetLastInputInfo(&mut info) }.as_bool().then(|| {
76 let idle_millis = unsafe { GetTickCount() }.wrapping_sub(info.dwTime);
77 Duration::from_millis(u64::from(idle_millis))
78 })
79}
80
81#[cfg(not(windows))]
82fn system_idle() -> Option<Duration> {
83 None
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 fn seconds(count: u64) -> Duration {
91 Duration::from_secs(count)
92 }
93
94 #[test]
95 fn active_until_the_idle_threshold() {
96 let last_input = Instant::now();
97 assert!(is_active(last_input, last_input + seconds(299), IDLE_AFTER));
98 assert!(!is_active(last_input, last_input + seconds(300), IDLE_AFTER));
99 assert!(is_active(last_input + seconds(10), last_input, IDLE_AFTER));
100 }
101
102 #[test]
103 fn only_a_change_of_state_is_reported() {
104 let last_input = Instant::now();
105 assert_eq!(activity_change(true, last_input, last_input + seconds(10), IDLE_AFTER), None);
106 assert_eq!(activity_change(true, last_input, last_input + seconds(301), IDLE_AFTER), Some(false));
107 assert_eq!(activity_change(false, last_input, last_input + seconds(301), IDLE_AFTER), None);
108 assert_eq!(activity_change(false, last_input + seconds(400), last_input + seconds(401), IDLE_AFTER), Some(true));
109 }
110
111 #[test]
112 fn system_input_counts_when_newer_than_app_input() {
113 let now = Instant::now() + seconds(1000);
114 let app_input = now - seconds(900);
115 assert_eq!(latest_input(app_input, Some(seconds(20)), now), now - seconds(20));
116 assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
117 assert_eq!(latest_input(app_input, None, now), app_input);
118 }
119
120 #[test]
121 fn touch_moves_the_last_input_forward() {
122 let input = UserInput::new();
123 let before = input.last_input();
124 std::thread::sleep(Duration::from_millis(5));
125 input.touch();
126 assert!(input.last_input() > before);
127 }
128}