Skip to main content

quickgui_system/
power.rs

1use std::{fmt, sync::Arc, time::Duration};
2
3#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
4use crate::SystemIntegrationError;
5use crate::{Result, invalid};
6
7#[cfg(target_os = "linux")]
8#[path = "power/linux.rs"]
9mod platform;
10#[cfg(target_os = "macos")]
11#[path = "power/macos.rs"]
12mod platform;
13#[cfg(target_os = "windows")]
14#[path = "power/windows.rs"]
15mod platform;
16#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
17mod platform {
18    use super::*;
19
20    pub(super) struct PlatformPowerAssertion;
21
22    impl PlatformPowerAssertion {
23        pub(super) fn acquire(_kind: PowerAssertionKind, _reason: &str) -> Result<Self> {
24            Err(SystemIntegrationError::Unsupported)
25        }
26
27        pub(super) fn release(self) -> Result<()> {
28            Ok(())
29        }
30    }
31
32    pub(super) fn snapshot() -> Result<PowerState> {
33        Err(SystemIntegrationError::Unsupported)
34    }
35
36    pub(super) fn system_idle_time() -> Result<Duration> {
37        Err(SystemIntegrationError::Unsupported)
38    }
39
40    pub(super) fn session_state() -> Result<SessionState> {
41        Ok(SessionState::Unknown)
42    }
43}
44
45/// Maximum UTF-8 bytes retained for a native power-assertion reason.
46pub const MAX_POWER_ASSERTION_REASON_BYTES: usize = 1_024;
47/// Largest threshold accepted by [`PowerMonitor::system_idle_state`].
48pub const MAX_IDLE_THRESHOLD: Duration = Duration::from_secs(366 * 24 * 60 * 60);
49
50/// The native sleep behavior prevented while a [`PowerAssertion`] is alive.
51#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
52pub enum PowerAssertionKind {
53    /// Keep the application and system awake while still allowing the display to sleep.
54    PreventApplicationSuspension,
55    /// Keep both the system and display awake.
56    PreventDisplaySleep,
57}
58
59/// A native, reference-counted request that prevents one class of automatic sleep.
60///
61/// The assertion is released when this value is dropped or when [`Self::release`] is called.
62/// Keep the value alive for exactly as long as the work requiring the assertion. Assertions are
63/// process resources and do not schedule a timer or polling task.
64pub struct PowerAssertion {
65    kind: PowerAssertionKind,
66    reason: Arc<str>,
67    inner: Option<platform::PlatformPowerAssertion>,
68}
69
70impl PowerAssertion {
71    /// Acquire a native assertion with a bounded, human-readable diagnostic reason.
72    pub fn acquire(kind: PowerAssertionKind, reason: impl Into<Arc<str>>) -> Result<Self> {
73        let reason = reason.into();
74        validate_reason(&reason)?;
75        let inner = platform::PlatformPowerAssertion::acquire(kind, &reason)?;
76        Ok(Self {
77            kind,
78            reason,
79            inner: Some(inner),
80        })
81    }
82
83    pub const fn kind(&self) -> PowerAssertionKind {
84        self.kind
85    }
86
87    pub fn reason(&self) -> &str {
88        &self.reason
89    }
90
91    pub const fn is_active(&self) -> bool {
92        self.inner.is_some()
93    }
94
95    /// Release the assertion now. Returns `false` when it was already released.
96    pub fn release(&mut self) -> Result<bool> {
97        let Some(inner) = self.inner.take() else {
98            return Ok(false);
99        };
100        inner.release()?;
101        Ok(true)
102    }
103}
104
105impl fmt::Debug for PowerAssertion {
106    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107        formatter
108            .debug_struct("PowerAssertion")
109            .field("kind", &self.kind)
110            .field("reason", &self.reason)
111            .field("active", &self.is_active())
112            .finish()
113    }
114}
115
116impl Drop for PowerAssertion {
117    fn drop(&mut self) {
118        if let Some(inner) = self.inner.take() {
119            let _ = inner.release();
120        }
121    }
122}
123
124/// The source currently powering the system.
125#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
126pub enum PowerSource {
127    Ac,
128    Battery,
129    Unknown,
130}
131
132/// Current charging state reported by the operating system.
133#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
134pub enum BatteryStatus {
135    Charging,
136    Discharging,
137    Full,
138    NotCharging,
139    Unknown,
140}
141
142/// A bounded aggregate battery snapshot.
143#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
144pub struct BatteryState {
145    charge_percent: Option<u8>,
146    status: BatteryStatus,
147}
148
149impl BatteryState {
150    pub(crate) const fn new(charge_percent: Option<u8>, status: BatteryStatus) -> Self {
151        Self {
152            charge_percent,
153            status,
154        }
155    }
156
157    pub const fn charge_percent(self) -> Option<u8> {
158        self.charge_percent
159    }
160
161    pub const fn status(self) -> BatteryStatus {
162        self.status
163    }
164}
165
166/// Coarse system thermal pressure.
167#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
168pub enum ThermalState {
169    Unknown,
170    Nominal,
171    Fair,
172    Serious,
173    Critical,
174}
175
176/// Current login-session activity.
177#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
178pub enum SessionState {
179    Active,
180    Inactive,
181    Locked,
182    Unknown,
183}
184
185/// System idleness classified against an application-supplied threshold.
186#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
187pub enum IdleState {
188    Active,
189    Idle,
190    Locked,
191    Unknown,
192}
193
194/// One immutable power and thermal snapshot.
195#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
196pub struct PowerState {
197    source: PowerSource,
198    battery: Option<BatteryState>,
199    thermal_state: ThermalState,
200    low_power_mode: Option<bool>,
201    cpu_speed_limit_percent: Option<u8>,
202}
203
204impl PowerState {
205    pub(crate) const fn new(
206        source: PowerSource,
207        battery: Option<BatteryState>,
208        thermal_state: ThermalState,
209        low_power_mode: Option<bool>,
210        cpu_speed_limit_percent: Option<u8>,
211    ) -> Self {
212        Self {
213            source,
214            battery,
215            thermal_state,
216            low_power_mode,
217            cpu_speed_limit_percent,
218        }
219    }
220
221    pub const fn source(self) -> PowerSource {
222        self.source
223    }
224
225    pub const fn battery(self) -> Option<BatteryState> {
226        self.battery
227    }
228
229    pub const fn thermal_state(self) -> ThermalState {
230        self.thermal_state
231    }
232
233    /// Whether the operating system reports an energy-saving mode, if supported.
234    pub const fn low_power_mode(self) -> Option<bool> {
235        self.low_power_mode
236    }
237
238    /// Current OS-advertised CPU speed limit, where `100` means no advertised throttling.
239    pub const fn cpu_speed_limit_percent(self) -> Option<u8> {
240        self.cpu_speed_limit_percent
241    }
242}
243
244/// Stateless entry point for native power, idle, thermal, and session queries.
245pub struct PowerMonitor;
246
247impl PowerMonitor {
248    pub fn snapshot() -> Result<PowerState> {
249        platform::snapshot()
250    }
251
252    pub fn is_on_battery_power() -> Result<bool> {
253        Ok(matches!(Self::snapshot()?.source(), PowerSource::Battery))
254    }
255
256    pub fn current_thermal_state() -> Result<ThermalState> {
257        Ok(Self::snapshot()?.thermal_state())
258    }
259
260    pub fn system_idle_time() -> Result<Duration> {
261        platform::system_idle_time()
262    }
263
264    pub fn session_state() -> Result<SessionState> {
265        platform::session_state()
266    }
267
268    pub fn system_idle_state(threshold: Duration) -> Result<IdleState> {
269        if threshold.is_zero() || threshold > MAX_IDLE_THRESHOLD {
270            return Err(invalid(format!(
271                "the idle threshold must be between one nanosecond and {} seconds",
272                MAX_IDLE_THRESHOLD.as_secs()
273            )));
274        }
275        let session = Self::session_state().unwrap_or(SessionState::Unknown);
276        let idle = Self::system_idle_time()?;
277        Ok(classify_idle(idle, session, threshold))
278    }
279}
280
281fn validate_reason(reason: &str) -> Result<()> {
282    if reason.is_empty()
283        || reason.len() > MAX_POWER_ASSERTION_REASON_BYTES
284        || reason.contains('\0')
285        || reason.chars().any(|character| character.is_control())
286    {
287        return Err(invalid(format!(
288            "a power assertion reason must be one non-empty line of at most {MAX_POWER_ASSERTION_REASON_BYTES} UTF-8 bytes"
289        )));
290    }
291    Ok(())
292}
293
294fn classify_idle(idle: Duration, session: SessionState, threshold: Duration) -> IdleState {
295    if session == SessionState::Locked {
296        IdleState::Locked
297    } else if idle >= threshold {
298        IdleState::Idle
299    } else if session == SessionState::Unknown && idle.is_zero() {
300        IdleState::Unknown
301    } else {
302        IdleState::Active
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn assertion_reasons_are_bounded_and_single_line() {
312        assert!(validate_reason("video playback").is_ok());
313        assert!(validate_reason("").is_err());
314        assert!(validate_reason("line one\nline two").is_err());
315        assert!(validate_reason(&"x".repeat(MAX_POWER_ASSERTION_REASON_BYTES + 1)).is_err());
316    }
317
318    #[test]
319    fn idle_classification_prioritizes_a_locked_session() {
320        let threshold = Duration::from_secs(60);
321        assert_eq!(
322            classify_idle(Duration::ZERO, SessionState::Locked, threshold),
323            IdleState::Locked
324        );
325        assert_eq!(
326            classify_idle(Duration::from_secs(90), SessionState::Active, threshold),
327            IdleState::Idle
328        );
329        assert_eq!(
330            classify_idle(Duration::from_secs(5), SessionState::Active, threshold),
331            IdleState::Active
332        );
333        assert_eq!(
334            classify_idle(Duration::ZERO, SessionState::Unknown, threshold),
335            IdleState::Unknown
336        );
337    }
338
339    #[test]
340    fn idle_threshold_rejects_zero_and_unbounded_values_before_native_queries() {
341        assert!(PowerMonitor::system_idle_state(Duration::ZERO).is_err());
342        assert!(
343            PowerMonitor::system_idle_state(MAX_IDLE_THRESHOLD + Duration::from_nanos(1)).is_err()
344        );
345    }
346}