use zbus::{dbus_proxy, Connection};
use crate::{
constants::APPLICATION_NAME,
util::errors::{wrap, AnyError},
};
#[dbus_proxy(
interface = "org.freedesktop.PowerManagement.Inhibit",
gen_blocking = false,
default_service = "org.freedesktop.PowerManagement.Inhibit",
default_path = "/org/freedesktop/PowerManagement/Inhibit"
)]
trait PMInhibitor {
#[dbus_proxy(name = "Inhibit")]
fn inhibit(&self, what: &str, why: &str) -> zbus::Result<u32>;
}
#[dbus_proxy(
interface = "org.freedesktop.ScreenSaver",
gen_blocking = false,
default_service = "org.freedesktop.ScreenSaver",
default_path = "/org/freedesktop/ScreenSaver"
)]
trait ScreenSaver {
#[dbus_proxy(name = "Inhibit")]
fn inhibit(&self, what: &str, why: &str) -> zbus::Result<u32>;
}
pub struct SleepInhibitor {
_connection: Connection,
}
impl SleepInhibitor {
pub async fn new() -> Result<Self, AnyError> {
let connection = Connection::session()
.await
.map_err(|e| wrap(e, "error creating dbus session"))?;
macro_rules! try_inhibit {
($proxy:ident) => {
match $proxy::new(&connection).await {
Ok(proxy) => proxy.inhibit(APPLICATION_NAME, "running tunnel").await,
Err(e) => Err(e),
}
};
}
if let Err(e1) = try_inhibit!(PMInhibitorProxy) {
if let Err(e2) = try_inhibit!(ScreenSaverProxy) {
return Err(wrap(
e2,
format!(
"error requesting sleep inhibition, pminhibitor gave {e1}, screensaver gave"
),
)
.into());
}
}
Ok(SleepInhibitor {
_connection: connection,
})
}
}