| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use gpui_kit::{DispatchPhase, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas}; |
| 6 | use tokio::sync::watch; |
| 7 | |
| 8 | pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60); |
| 9 | const SAMPLE_INTERVAL: Duration = Duration::from_secs(15); |
| 10 | |
| 11 | pub struct UserInput { |
| 12 | origin: Instant, |
| 13 | last_input_millis: AtomicU64, |
| 14 | } |
| 15 | |
| 16 | const NO_INPUT: u64 = u64::MAX; |
| 17 | |
| 18 | impl 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 | |
| 39 | pub 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 | let typed = input.clone(); |
| 62 | window.on_key_event(move |_: &KeyDownEvent, phase, _, _| { |
| 63 | if phase == DispatchPhase::Capture { |
| 64 | typed.touch(); |
| 65 | } |
| 66 | }); |
| 67 | }, |
| 68 | ) |
| 69 | } |
| 70 | |
| 71 | pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> { |
| 72 | let system_input = system_idle.and_then(|idle| now.checked_sub(idle)); |
| 73 | app_input.max(system_input) |
| 74 | } |
| 75 | |
| 76 | pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool { |
| 77 | last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after) |
| 78 | } |
| 79 | |
| 80 | pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> { |
| 81 | let current = is_active(last_input, now, idle_after); |
| 82 | (current != previous).then_some(current) |
| 83 | } |
| 84 | |
| 85 | pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> { |
| 86 | let (sender, receiver) = watch::channel(false); |
| 87 | crate::runtime::handle().spawn(async move { |
| 88 | let mut interval = tokio::time::interval(SAMPLE_INTERVAL); |
| 89 | loop { |
| 90 | interval.tick().await; |
| 91 | let now = Instant::now(); |
| 92 | let last_input = latest_input(input.last_input(), system_idle(), now); |
| 93 | let previous = *sender.borrow(); |
| 94 | if let Some(current) = activity_change(previous, last_input, now, IDLE_AFTER) { |
| 95 | sender.send_replace(current); |
| 96 | } |
| 97 | } |
| 98 | }); |
| 99 | receiver |
| 100 | } |
| 101 | |
| 102 | #[cfg(windows)] |
| 103 | fn system_idle() -> Option<Duration> { |
| 104 | use windows::Win32::System::SystemInformation::GetTickCount; |
| 105 | use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO}; |
| 106 | |
| 107 | let mut info = LASTINPUTINFO { |
| 108 | cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32, |
| 109 | dwTime: 0, |
| 110 | }; |
| 111 | unsafe { GetLastInputInfo(&mut info) }.as_bool().then(|| { |
| 112 | let idle_millis = unsafe { GetTickCount() }.wrapping_sub(info.dwTime); |
| 113 | Duration::from_millis(u64::from(idle_millis)) |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | #[cfg(not(windows))] |
| 118 | fn system_idle() -> Option<Duration> { |
| 119 | None |
| 120 | } |
| 121 | |
| 122 | #[cfg(test)] |
| 123 | mod tests { |
| 124 | use super::*; |
| 125 | |
| 126 | fn seconds(count: u64) -> Duration { |
| 127 | Duration::from_secs(count) |
| 128 | } |
| 129 | |
| 130 | #[test] |
| 131 | fn active_until_the_idle_threshold() { |
| 132 | let last_input = Instant::now(); |
| 133 | assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER)); |
| 134 | assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER)); |
| 135 | assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER)); |
| 136 | } |
| 137 | |
| 138 | #[test] |
| 139 | fn without_any_input_the_user_is_inactive() { |
| 140 | assert!(!is_active(None, Instant::now(), IDLE_AFTER)); |
| 141 | assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None); |
| 142 | } |
| 143 | |
| 144 | #[test] |
| 145 | fn only_a_change_of_state_is_reported() { |
| 146 | let last_input = Some(Instant::now()); |
| 147 | let at = |offset: u64| last_input.unwrap() + seconds(offset); |
| 148 | assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None); |
| 149 | assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false)); |
| 150 | assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None); |
| 151 | assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true)); |
| 152 | assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true)); |
| 153 | } |
| 154 | |
| 155 | #[test] |
| 156 | fn system_input_counts_when_newer_than_app_input() { |
| 157 | let now = Instant::now() + seconds(1000); |
| 158 | let app_input = Some(now - seconds(900)); |
| 159 | assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20))); |
| 160 | assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input); |
| 161 | assert_eq!(latest_input(app_input, None, now), app_input); |
| 162 | assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20))); |
| 163 | assert_eq!(latest_input(None, None, now), None); |
| 164 | } |
| 165 | |
| 166 | #[test] |
| 167 | fn touch_sets_and_moves_the_last_input_forward() { |
| 168 | let input = UserInput::new(); |
| 169 | assert_eq!(input.last_input(), None); |
| 170 | input.touch(); |
| 171 | let first = input.last_input().unwrap(); |
| 172 | std::thread::sleep(Duration::from_millis(5)); |
| 173 | input.touch(); |
| 174 | assert!(input.last_input().unwrap() > first); |
| 175 | } |
| 176 | } |