Skip to main content

device_tests/
autosleep.rs

1use ql_sleep::Autosleep;
2
3use crate::display::Chain;
4use crate::print::print_stderr;
5
6/// Restores the autosleep setting that the guard found when it was created.
7///
8/// [`AutosleepGuard::restore`] restores it and reports errors. Dropping the
9/// guard restores it too, for example after a panic, and prints errors.
10#[derive(Debug)]
11pub struct AutosleepGuard {
12    autosleep: Autosleep,
13    original: bool,
14    restored: bool,
15}
16
17impl AutosleepGuard {
18    /// Records the current setting.
19    ///
20    /// # Errors
21    ///
22    /// Returns an error if the setting can't be read.
23    pub fn capture() -> Result<Self, ql_sleep::Error> {
24        let autosleep = Autosleep::new();
25        let original = autosleep.is_enabled()?;
26        Ok(Self {
27            autosleep,
28            original,
29            restored: false,
30        })
31    }
32
33    /// Returns the setting when the guard was created.
34    #[must_use]
35    pub const fn original(&self) -> bool {
36        self.original
37    }
38
39    /// Returns whether autosleep is on now.
40    ///
41    /// # Errors
42    ///
43    /// Returns an error if the setting can't be read.
44    pub fn is_enabled(&self) -> Result<bool, ql_sleep::Error> {
45        self.autosleep.is_enabled()
46    }
47
48    /// Writes the original setting back if it changed. Returns whether it
49    /// wrote the setting.
50    ///
51    /// # Errors
52    ///
53    /// Returns an error if the setting can't be read or written.
54    pub fn restore(mut self) -> Result<bool, ql_sleep::Error> {
55        self.restored = true;
56        self.write_back()
57    }
58
59    const fn original_text(&self) -> &'static str {
60        if self.original { "on" } else { "off" }
61    }
62
63    /// Returns whether it wrote the setting.
64    fn write_back(&self) -> Result<bool, ql_sleep::Error> {
65        if self.autosleep.is_enabled()? == self.original {
66            return Ok(false);
67        }
68        self.autosleep.set_enabled(self.original)?;
69        Ok(true)
70    }
71}
72
73impl Drop for AutosleepGuard {
74    fn drop(&mut self) {
75        if self.restored {
76            return;
77        }
78        match self.write_back() {
79            Ok(true) => print_stderr(format_args!(
80                "restored autosleep to {}",
81                self.original_text()
82            )),
83            Ok(false) => {}
84            Err(err) => print_stderr(format_args!("failed to restore autosleep: {}", Chain(&err))),
85        }
86    }
87}