2024-04-05 11:01:57 -06:00
|
|
|
use cosmic::iced::{
|
|
|
|
|
futures::{channel::mpsc, SinkExt, StreamExt},
|
|
|
|
|
subscription, Subscription,
|
|
|
|
|
};
|
|
|
|
|
use logind_zbus::{manager::ManagerProxy, session::SessionProxy};
|
|
|
|
|
use std::{any::TypeId, error::Error, process};
|
|
|
|
|
use tokio::time;
|
|
|
|
|
use zbus::Connection;
|
2023-11-29 08:02:14 -07:00
|
|
|
|
2024-04-05 11:01:57 -06:00
|
|
|
pub async fn power_off() -> zbus::Result<()> {
|
2023-11-29 08:02:14 -07:00
|
|
|
let connection = Connection::system().await?;
|
|
|
|
|
let manager = ManagerProxy::new(&connection).await?;
|
2024-04-05 06:21:40 -04:00
|
|
|
manager.power_off(false).await
|
2023-11-29 08:02:14 -07:00
|
|
|
}
|
|
|
|
|
|
2024-04-05 11:01:57 -06:00
|
|
|
pub async fn reboot() -> zbus::Result<()> {
|
2023-11-29 08:02:14 -07:00
|
|
|
let connection = Connection::system().await?;
|
|
|
|
|
let manager = ManagerProxy::new(&connection).await?;
|
|
|
|
|
manager.reboot(false).await
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-05 11:01:57 -06:00
|
|
|
pub async fn suspend() -> zbus::Result<()> {
|
2023-11-29 08:02:14 -07:00
|
|
|
let connection = Connection::system().await?;
|
|
|
|
|
let manager = ManagerProxy::new(&connection).await?;
|
|
|
|
|
manager.suspend(false).await
|
|
|
|
|
}
|
2024-04-05 11:01:57 -06:00
|
|
|
|
|
|
|
|
pub fn subscription() -> Subscription<bool> {
|
|
|
|
|
struct LogindSubscription;
|
|
|
|
|
|
|
|
|
|
subscription::channel(
|
|
|
|
|
TypeId::of::<LogindSubscription>(),
|
|
|
|
|
16,
|
|
|
|
|
|mut msg_tx| async move {
|
|
|
|
|
match handler(&mut msg_tx).await {
|
|
|
|
|
Ok(()) => {}
|
|
|
|
|
Err(err) => {
|
|
|
|
|
log::warn!("logind error: {}", err);
|
|
|
|
|
//TODO: send error
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//TODO: should we retry on error?
|
|
|
|
|
loop {
|
|
|
|
|
time::sleep(time::Duration::new(60, 0)).await;
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//TODO: use never type?
|
|
|
|
|
pub async fn handler(msg_tx: &mut mpsc::Sender<bool>) -> Result<(), Box<dyn Error>> {
|
|
|
|
|
let connection = Connection::system().await?;
|
|
|
|
|
let manager = ManagerProxy::new(&connection).await?;
|
|
|
|
|
let session_path = manager.get_session_by_PID(process::id()).await?;
|
|
|
|
|
let session = SessionProxy::builder(&connection)
|
|
|
|
|
.path(&session_path)?
|
|
|
|
|
.build()
|
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
|
|
let mut lock = session.receive_lock().await?;
|
|
|
|
|
let mut unlock = session.receive_unlock().await?;
|
|
|
|
|
loop {
|
|
|
|
|
// Waits until lock or unlock signals have been received
|
|
|
|
|
tokio::select!(_ = lock.next() => {
|
2024-04-05 11:31:15 -06:00
|
|
|
log::info!("logind lock");
|
2024-04-05 11:01:57 -06:00
|
|
|
msg_tx.send(true).await?;
|
|
|
|
|
}, _ = unlock.next() => {
|
2024-04-05 11:31:15 -06:00
|
|
|
log::info!("logind unlock");
|
2024-04-05 11:01:57 -06:00
|
|
|
msg_tx.send(false).await?;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|