easy_imgui/
idler.rs

1use std::time::{Duration, Instant};
2
3/// This struct handles the main loop going to idle when there is no user input for a while.
4pub struct Idler {
5    idle_time: Duration,
6    idle_frame_count: u32,
7    last_input_time: Instant,
8    last_input_frame: u32,
9}
10
11impl Default for Idler {
12    fn default() -> Idler {
13        let now = Instant::now();
14        Idler {
15            idle_time: Duration::from_secs(1),
16            idle_frame_count: 60,
17            last_input_time: now,
18            last_input_frame: 0,
19        }
20    }
21}
22
23impl Idler {
24    /// Sets the maximum time that the window will be rendered without user input.
25    pub fn set_idle_time(&mut self, time: Duration) {
26        self.idle_time = time;
27    }
28    /// Sets the maximum number of frames time that the window will be rendered without user input.
29    pub fn set_idle_frame_count(&mut self, frame_count: u32) {
30        self.idle_frame_count = frame_count;
31    }
32    /// Call this when the window is renderer.
33    pub fn incr_frame(&mut self) {
34        // An u32 incrementing 60 values/second would overflow after about 2 years, better safe
35        // than sorry.
36        self.last_input_frame = self.last_input_frame.saturating_add(1);
37    }
38    /// Check whether the window should go to idle or keep on rendering.
39    pub fn has_to_render(&self) -> bool {
40        self.last_input_frame < self.idle_frame_count
41            || Instant::now().duration_since(self.last_input_time) < self.idle_time
42    }
43    /// Notify this struct that user input happened.
44    pub fn ping_user_input(&mut self) {
45        self.last_input_time = Instant::now();
46        self.last_input_frame = 0;
47    }
48}