rich_sdl2_rust/
power.rs

1//! System power monitoring.
2
3use crate::bind;
4
5/// A state of power in the system.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum PowerState {
9    /// A state cannot be known.
10    Unknown,
11    /// It has a battery, not charging.
12    OnBattery,
13    /// It has no batteries.
14    NoBattery,
15    /// It has a battery, charging.
16    Charging,
17    /// It has a battery, completed to charge.
18    Charged,
19}
20
21impl From<bind::SDL_PowerState> for PowerState {
22    fn from(raw: bind::SDL_PowerState) -> Self {
23        match raw {
24            bind::SDL_POWERSTATE_UNKNOWN => PowerState::Unknown,
25            bind::SDL_POWERSTATE_ON_BATTERY => PowerState::OnBattery,
26            bind::SDL_POWERSTATE_NO_BATTERY => PowerState::NoBattery,
27            bind::SDL_POWERSTATE_CHARGING => PowerState::Charging,
28            bind::SDL_POWERSTATE_CHARGED => PowerState::Charged,
29            _ => unreachable!(),
30        }
31    }
32}
33
34/// A detail information of the system battery.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct PowerInfo {
37    /// The battery state of the system.
38    pub state: PowerState,
39    /// The remaining amount of battery in seconds if available.
40    pub remaining_seconds: Option<u32>,
41    /// The remaining amount of battery in percent if available.
42    pub remaining_ratio: Option<u32>,
43}
44
45impl PowerInfo {
46    /// Returns a power information at now.
47    #[must_use]
48    pub fn now() -> Self {
49        let mut remaining_seconds = 0;
50        let mut remaining_ratio = 0;
51        let state = unsafe { bind::SDL_GetPowerInfo(&mut remaining_seconds, &mut remaining_ratio) };
52        Self {
53            state: state.into(),
54            remaining_seconds: (0 <= remaining_seconds).then(|| remaining_seconds as _),
55            remaining_ratio: (0 <= remaining_ratio).then(|| remaining_ratio as _),
56        }
57    }
58}