Skip to main content

user_idle3/
lib.rs

1/*!
2Get the idle time of a user
3
4The time returned is the time since the last user input event
5
6See the [`README.md`](https://github.com/olback/user-idle-rs/blob/master/README.md) for more information
7
8Example:
9```
10use user_idle3::UserIdle;
11let idle = UserIdle::get_time().unwrap();
12let idle_seconds = idle.as_seconds();
13let idle_minutes = idle.as_minutes();
14```
15*/
16
17mod error;
18
19use std::time::Duration;
20
21pub use error::Error;
22
23#[cfg(all(target_os = "linux"))]
24#[path = "linux_impl.rs"]
25mod idle;
26
27#[cfg(target_os = "windows")]
28#[path = "windows_impl.rs"]
29mod idle;
30
31#[cfg(target_os = "macos")]
32#[path = "macos_impl.rs"]
33mod idle;
34
35pub struct UserIdle {
36    duration: Duration,
37}
38
39impl UserIdle {
40    /// Get the idle time
41    pub fn get_time() -> Result<Self, Error> {
42        Ok(UserIdle {
43            duration: idle::get_idle_time()?,
44        })
45    }
46
47    /**
48    Get time in milliseconds
49
50    Note: Only MacOS provides this level of resolution,
51    other Operating Systems will provide the same value as
52    `self.as_milliseconds() * 1_000_000`
53    */
54    pub fn as_nanoseconds(&self) -> u128 {
55        self.duration.as_nanos()
56    }
57
58    /**
59    Get time in milliseconds
60
61    Note: Not all of the dbus screen savers provided
62    this level of resolution, in those cases this will
63    provide the same value as `self.as_seconds() * 1000`
64    */
65    pub fn as_milliseconds(&self) -> u128 {
66        self.duration.as_millis()
67    }
68
69    /// Get time in seconds
70    pub fn as_seconds(&self) -> u64 {
71        self.duration.as_secs()
72    }
73
74    /// Get time in minutes
75    pub fn as_minutes(&self) -> u64 {
76        self.as_seconds() / 60
77    }
78
79    /// Get time in hours
80    pub fn as_hours(&self) -> u64 {
81        self.as_minutes() / 60
82    }
83
84    /// Get time in days
85    pub fn as_days(&self) -> u64 {
86        self.as_hours() / 24
87    }
88
89    /// Get time in weeks
90    pub fn as_weeks(&self) -> u64 {
91        self.as_days() / 7
92    }
93
94    /// Get time in months
95    pub fn as_months(&self) -> u64 {
96        self.as_weeks() / 4
97    }
98
99    /// Get time in years
100    pub fn as_years(&self) -> u64 {
101        self.as_months() / 12
102    }
103
104    /// Convert to a [Duration]
105    pub fn duration(&self) -> Duration {
106        self.duration
107    }
108}
109
110#[cfg(test)]
111mod test {
112    use std::{thread::sleep, time::Duration};
113
114    use super::UserIdle;
115
116    const TEST_SECS: u64 = 10;
117
118    #[test]
119    fn main() {
120        sleep(Duration::from_secs(TEST_SECS));
121        let idle = UserIdle::get_time().unwrap();
122        assert_eq!(idle.as_seconds(), TEST_SECS);
123    }
124}