BlueGit

ict rusty-teams

Files

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

user_activity.rs

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