use std::sync::Mutex;
use std::time::{Duration, Instant};
use crate::util::UnwrapPoison as _;
const ABSENCE_THRESHOLD: Duration = Duration::from_mins(5);
static LAST_REPORT: Mutex<Option<Instant>> = Mutex::new(None);
pub(crate) fn report_activity() {
*LAST_REPORT.lock().unwrap_poison() = Some(Instant::now());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Location {
AtComputer,
Away,
}
impl Location {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::AtComputer => "active",
Self::Away => "absent",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct State {
pub(crate) location: Location,
pub(crate) by_voice: bool,
}
impl State {
pub(crate) fn label(self) -> &'static str {
if self.by_voice {
"active, by voice"
} else {
self.location.as_str()
}
}
}
pub(crate) fn read() -> Option<State> {
state(
os_idle(),
LAST_REPORT.lock().unwrap_poison().map(|at| at.elapsed()),
)
}
fn state(os_idle: Option<Duration>, since_report: Option<Duration>) -> Option<State> {
let os_idle = os_idle?;
let freshest = since_report.map_or(os_idle, |report| os_idle.min(report));
let location = if freshest >= ABSENCE_THRESHOLD {
Location::Away
} else {
Location::AtComputer
};
Some(State {
location,
by_voice: os_idle >= ABSENCE_THRESHOLD
&& since_report.is_some_and(|report| report < ABSENCE_THRESHOLD),
})
}
pub(crate) fn is_absent() -> bool {
read().is_some_and(|state| state.location == Location::Away)
}
#[cfg(target_os = "macos")]
fn os_idle() -> Option<Duration> {
use objc2_core_graphics::{CGEventSource, CGEventSourceStateID, CGEventType};
crate::util::with_block_in_place(|| {
let seconds = CGEventSource::seconds_since_last_event_type(
CGEventSourceStateID::CombinedSessionState,
CGEventType(u32::MAX),
);
Duration::try_from_secs_f64(seconds).ok()
})
}
#[cfg(target_os = "windows")]
fn os_idle() -> Option<Duration> {
use windows::Win32::System::SystemInformation::GetTickCount;
use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};
#[expect(
clippy::cast_possible_truncation,
reason = "LASTINPUTINFO is two u32 fields"
)]
let size = std::mem::size_of::<LASTINPUTINFO>() as u32;
let mut last = LASTINPUTINFO {
cbSize: size,
dwTime: 0,
};
if !unsafe { GetLastInputInfo(&raw mut last) }.as_bool() {
return None;
}
let now = unsafe { GetTickCount() };
let delta = now.wrapping_sub(last.dwTime);
Some(Duration::from_millis(u64::from(if delta > now {
0
} else {
delta
})))
}
#[cfg(target_os = "linux")]
fn os_idle() -> Option<Duration> {
use x11rb::connection::Connection as _;
use x11rb::protocol::screensaver::ConnectionExt as _;
if crate::util::display_server::wayland() {
return None;
}
crate::util::with_block_in_place(|| {
let (connection, screen) = x11rb::connect(None).ok()?;
let root = connection.setup().roots.get(screen)?.root;
let reply = connection.screensaver_query_info(root).ok()?.reply().ok()?;
Some(Duration::from_millis(u64::from(reply.ms_since_user_input)))
})
}
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
fn os_idle() -> Option<Duration> {
None
}
#[cfg(test)]
mod tests {
use super::*;
const RECENT: Duration = ABSENCE_THRESHOLD.saturating_sub(Duration::from_secs(1));
const STALE: Duration = ABSENCE_THRESHOLD.saturating_add(Duration::from_mins(1));
#[test]
fn activity_stops_counting_at_the_threshold() {
for (idle, expected) in [
(Duration::ZERO, Location::AtComputer),
(RECENT, Location::AtComputer),
(ABSENCE_THRESHOLD, Location::Away),
(STALE, Location::Away),
] {
assert_eq!(state(Some(idle), None).map(|s| s.location), Some(expected));
}
}
#[test]
fn a_machine_that_cannot_tell_is_never_absent() {
for report in [None, Some(RECENT), Some(STALE)] {
assert_eq!(state(None, report), None);
}
}
#[test]
fn speaking_aloud_marks_the_change() {
let spoken = state(Some(STALE), Some(RECENT));
assert_eq!(spoken.map(|s| s.location), Some(Location::AtComputer));
assert!(spoken.is_some_and(|s| s.by_voice));
let typed = state(Some(RECENT), Some(RECENT));
assert_eq!(typed.map(|s| s.location), Some(Location::AtComputer));
assert!(typed.is_some_and(|s| !s.by_voice));
assert_eq!(
state(Some(STALE), None),
Some(State {
location: Location::Away,
by_voice: false,
})
);
}
}