BlueGit

ict rusty-teams

Files

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

user_activity.rs

fix(presence): review findings
metis Daniel Däschle · pushed by metis · 7 weeks ago
a755adcc History
user_activity.rs 5.9 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::time::{Duration, Instant};
4
5use gpui_kit::{DispatchPhase, IntoElement, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};
6use tokio::sync::watch;
7
8pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
9const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
10
11pub struct UserInput {
12 origin: Instant,
13 last_input_millis: AtomicU64,
14}
15
16const NO_INPUT: u64 = u64::MAX;
17
18impl UserInput {
19 pub fn new() -> Arc<Self> {
20 Arc::new(UserInput {
21 origin: Instant::now(),
22 last_input_millis: AtomicU64::new(NO_INPUT),
23 })
24 }
25
26 pub fn touch(&self) {
27 let elapsed = self.origin.elapsed().as_millis() as u64;
28 self.last_input_millis.store(elapsed, Ordering::Relaxed);
29 }
30
31 fn last_input(&self) -> Option<Instant> {
32 match self.last_input_millis.load(Ordering::Relaxed) {
33 NO_INPUT => None,
34 millis => Some(self.origin + Duration::from_millis(millis)),
35 }
36 }
37}
38
39pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {
40 canvas(
41 |_, _, _| {},
42 move |_, _, window, _| {
43 let moved = input.clone();
44 window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, _| {
45 if phase == DispatchPhase::Capture {
46 moved.touch();
47 }
48 });
49 let pressed = input.clone();
50 window.on_mouse_event(move |_: &MouseDownEvent, phase, _, _| {
51 if phase == DispatchPhase::Capture {
52 pressed.touch();
53 }
54 });
55 let scrolled = input.clone();
56 window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, _| {
57 if phase == DispatchPhase::Capture {
58 scrolled.touch();
59 }
60 });
61 },
62 )
63}
64
65pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {
66 let system_input = system_idle.and_then(|idle| now.checked_sub(idle));
67 app_input.max(system_input)
68}
69
70pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool {
71 last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)
72}
73
74pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {
75 let current = is_active(last_input, now, idle_after);
76 (current != previous).then_some(current)
77}
78
79pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
80 let (sender, receiver) = watch::channel(false);
81 crate::runtime::handle().spawn(async move {
82 let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
83 loop {
84 interval.tick().await;
85 let now = Instant::now();
86 let last_input = latest_input(input.last_input(), system_idle(), now);
87 let previous = *sender.borrow();
88 if let Some(current) = activity_change(previous, last_input, now, IDLE_AFTER) {
89 sender.send_replace(current);
90 }
91 }
92 });
93 receiver
94}
95
96#[cfg(windows)]
97fn system_idle() -> Option<Duration> {
98 use windows::Win32::System::SystemInformation::GetTickCount;
99 use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};
100
101 let mut info = LASTINPUTINFO {
102 cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32,
103 dwTime: 0,
104 };
105 unsafe { GetLastInputInfo(&mut info) }.as_bool().then(|| {
106 let idle_millis = unsafe { GetTickCount() }.wrapping_sub(info.dwTime);
107 Duration::from_millis(u64::from(idle_millis))
108 })
109}
110
111#[cfg(not(windows))]
112fn system_idle() -> Option<Duration> {
113 None
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 fn seconds(count: u64) -> Duration {
121 Duration::from_secs(count)
122 }
123
124 #[test]
125 fn active_until_the_idle_threshold() {
126 let last_input = Instant::now();
127 assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER));
128 assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER));
129 assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER));
130 }
131
132 #[test]
133 fn without_any_input_the_user_is_inactive() {
134 assert!(!is_active(None, Instant::now(), IDLE_AFTER));
135 assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);
136 }
137
138 #[test]
139 fn only_a_change_of_state_is_reported() {
140 let last_input = Some(Instant::now());
141 let at = |offset: u64| last_input.unwrap() + seconds(offset);
142 assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);
143 assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false));
144 assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None);
145 assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true));
146 assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true));
147 }
148
149 #[test]
150 fn system_input_counts_when_newer_than_app_input() {
151 let now = Instant::now() + seconds(1000);
152 let app_input = Some(now - seconds(900));
153 assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));
154 assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
155 assert_eq!(latest_input(app_input, None, now), app_input);
156 assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));
157 assert_eq!(latest_input(None, None, now), None);
158 }
159
160 #[test]
161 fn touch_sets_and_moves_the_last_input_forward() {
162 let input = UserInput::new();
163 assert_eq!(input.last_input(), None);
164 input.touch();
165 let first = input.last_input().unwrap();
166 std::thread::sleep(Duration::from_millis(5));
167 input.touch();
168 assert!(input.last_input().unwrap() > first);
169 }
170}