use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct IdleTracker {
stable_needed: Duration,
deadline: Instant,
last_screen: Option<String>,
stable_since: Instant,
}
impl IdleTracker {
pub fn new(stable_secs: f64, timeout_secs: f64) -> Self {
let stable_needed = Duration::from_secs_f64(stable_secs.max(0.0));
let timeout = Duration::from_secs_f64(timeout_secs.max(0.0));
let now = Instant::now();
Self {
stable_needed,
deadline: now + timeout,
last_screen: None,
stable_since: now,
}
}
pub fn observe(&mut self, screen: &str, now: Instant) -> bool {
if self.last_screen.as_deref() != Some(screen) {
self.last_screen = Some(screen.to_string());
self.stable_since = now;
}
now.duration_since(self.stable_since) >= self.stable_needed
}
pub fn expired(&self, now: Instant) -> bool {
now >= self.deadline
}
pub fn remaining(&self, now: Instant) -> Duration {
self.deadline.saturating_duration_since(now)
}
}
pub fn wait_for_idle<F>(stable_secs: f64, timeout_secs: f64, mut poll: F) -> bool
where
F: FnMut() -> String,
{
let mut tracker = IdleTracker::new(stable_secs, timeout_secs);
let start = Instant::now();
let screen = poll();
if tracker.observe(&screen, Instant::now()) && stable_secs == 0.0 {
return true;
}
while !tracker.expired(Instant::now()) {
std::thread::sleep(Duration::from_millis(50));
let now = Instant::now();
let screen = poll();
if tracker.observe(&screen, now) {
return true;
}
if now.duration_since(start).as_secs_f64() >= timeout_secs {
break;
}
}
false
}