user_idle/
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_idle::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", not(feature = "dbus")))]
24#[path = "x11_impl.rs"]
25mod idle;
26
27#[cfg(all(target_os = "linux", feature = "dbus"))]
28#[path = "dbus_impl.rs"]
29mod idle;
30
31#[cfg(target_os = "windows")]
32#[path = "windows_impl.rs"]
33mod idle;
34
35#[cfg(target_os = "macos")]
36#[path = "macos_impl.rs"]
37mod idle;
38
39pub struct UserIdle {
40    duration: Duration,
41}
42
43impl UserIdle {
44    /// Get the idle time
45    pub fn get_time() -> Result<Self, Error> {
46        Ok(UserIdle {
47            duration: idle::get_idle_time()?,
48        })
49    }
50
51    /**
52    Get time in milliseconds
53
54    Note: Only MacOS provides this level of resolution,
55    other Operating Systems will provide the same value as
56    `self.as_milliseconds() * 1_000_000`
57    */
58    pub fn as_nanoseconds(&self) -> u128 {
59        self.duration.as_nanos()
60    }
61
62    /**
63    Get time in milliseconds
64
65    Note: Not all of the dbus screen savers provided
66    this level of resolution, in those cases this will
67    provide the same value as `self.as_seconds() * 1000`
68    */
69    pub fn as_milliseconds(&self) -> u128 {
70        self.duration.as_millis()
71    }
72
73    /// Get time in seconds
74    pub fn as_seconds(&self) -> u64 {
75        self.duration.as_secs()
76    }
77
78    /// Get time in minutes
79    pub fn as_minutes(&self) -> u64 {
80        self.as_seconds() / 60
81    }
82
83    /// Get time in hours
84    pub fn as_hours(&self) -> u64 {
85        self.as_minutes() / 60
86    }
87
88    /// Get time in days
89    pub fn as_days(&self) -> u64 {
90        self.as_hours() / 24
91    }
92
93    /// Get time in weeks
94    pub fn as_weeks(&self) -> u64 {
95        self.as_days() / 7
96    }
97
98    /// Get time in months
99    pub fn as_months(&self) -> u64 {
100        self.as_weeks() / 4
101    }
102
103    /// Get time in years
104    pub fn as_years(&self) -> u64 {
105        self.as_months() / 12
106    }
107
108    /// Convert to a [Duration]
109    pub fn duration(&self) -> Duration {
110        self.duration
111    }
112}
113
114#[cfg(test)]
115mod test {
116    use std::{thread::sleep, time::Duration};
117
118    use super::UserIdle;
119
120    const TEST_SECS: u64 = 10;
121
122    #[test]
123    fn main() {
124        sleep(Duration::from_secs(TEST_SECS));
125        let idle = UserIdle::get_time().unwrap();
126        assert_eq!(idle.as_seconds(), TEST_SECS);
127    }
128}