use std::cell::RefCell;
use std::collections::HashMap;
use anyhow::{Context, Result, anyhow, bail};
use scx_loader::SchedMode;
use zbus::blocking::Connection;
use zbus::blocking::fdo::{DBusProxy, PropertiesProxy};
use zbus::names::{BusName, InterfaceName};
use zbus::proxy::CacheProperties;
use zbus::zvariant::OwnedValue;
use super::{Capabilities, ModeArgs, SchedulerBackend, Status};
const UNKNOWN: &str = "unknown";
const SERVICE: &str = "org.scx.Loader";
#[zbus::proxy(
interface = "org.scx.Loader",
default_service = "org.scx.Loader",
default_path = "/org/scx/Loader"
)]
trait Loader {
fn start_scheduler(&self, scx_name: &str, sched_mode: SchedMode) -> zbus::Result<()>;
fn switch_scheduler(&self, scx_name: &str, sched_mode: SchedMode) -> zbus::Result<()>;
fn start_scheduler_with_args(&self, scx_name: &str, scx_args: &[String]) -> zbus::Result<()>;
fn switch_scheduler_with_args(&self, scx_name: &str, scx_args: &[String]) -> zbus::Result<()>;
fn stop_scheduler(&self) -> zbus::Result<()>;
fn restart_scheduler(&self) -> zbus::Result<()>;
fn restore_default(&self) -> zbus::Result<()>;
fn scheduler_mode_args(&self, scx_name: &str) -> zbus::Result<ModeArgs>;
#[zbus(property)]
fn current_scheduler(&self) -> zbus::Result<String>;
#[zbus(property)]
fn scheduler_mode(&self) -> zbus::Result<SchedMode>;
#[zbus(property)]
fn current_scheduler_args(&self) -> zbus::Result<Vec<String>>;
#[zbus(property)]
fn supported_schedulers(&self) -> zbus::Result<Vec<String>>;
#[zbus(property)]
fn default_scheduler(&self) -> zbus::Result<String>;
#[zbus(property)]
fn default_mode(&self) -> zbus::Result<SchedMode>;
}
pub struct LoaderBackend {
proxy: LoaderProxyBlocking<'static>,
dbus: DBusProxy<'static>,
props: PropertiesProxy<'static>,
initial_schedulers: RefCell<Option<Vec<String>>>,
}
impl LoaderBackend {
pub fn connect() -> Result<Self> {
let conn = Connection::system().context("failed to connect to the system D-Bus")?;
let dbus = DBusProxy::new(&conn).context("failed to create the D-Bus proxy")?;
let name = BusName::from_static_str(SERVICE).expect("valid bus name literal");
let owned = dbus
.name_has_owner(name)
.map_err(|err| anyhow!("{err}"))
.context("failed to query the bus for org.scx.Loader")?;
if !owned {
let activatable = dbus
.list_activatable_names()
.map_err(|err| anyhow!("{err}"))
.context("failed to list activatable bus names")?
.iter()
.any(|n| n.as_str() == SERVICE);
if !activatable {
bail!(
"org.scx.Loader is neither running nor D-Bus-activatable — \
is the scx_loader service installed?"
);
}
}
let proxy = LoaderProxyBlocking::builder(&conn)
.cache_properties(CacheProperties::No)
.build()
.context("failed to create the org.scx.Loader proxy")?;
let schedulers = proxy
.supported_schedulers()
.map_err(|err| anyhow!("{err}"))
.context(
"org.scx.Loader did not respond — is the scx_loader service installed and running?",
)?;
let props = PropertiesProxy::builder(&conn)
.destination(SERVICE)
.context("invalid destination for the Properties proxy")?
.path("/org/scx/Loader")
.context("invalid path for the Properties proxy")?
.build()
.context("failed to create the Properties proxy")?;
Ok(Self {
proxy,
props,
dbus,
initial_schedulers: RefCell::new(Some(schedulers)),
})
}
}
fn take_prop<T>(props: &mut HashMap<String, OwnedValue>, name: &str) -> Result<T>
where
T: TryFrom<OwnedValue>,
T::Error: std::error::Error + Send + Sync + 'static,
{
let value = props
.remove(name)
.with_context(|| format!("daemon did not report the {name} property"))?;
T::try_from(value).with_context(|| format!("unexpected type for the {name} property"))
}
fn none_if_unknown(value: String) -> Option<String> {
if value == UNKNOWN { None } else { Some(value) }
}
impl SchedulerBackend for LoaderBackend {
fn label(&self) -> &'static str {
"scx_loader (D-Bus)"
}
fn capabilities(&self) -> Capabilities {
Capabilities {
live_switch: true,
modes: true,
custom_args: true,
restore_default: true,
}
}
fn instance_token(&self) -> Option<String> {
let name = BusName::from_static_str(SERVICE).expect("valid bus name literal");
self.dbus
.get_name_owner(name)
.ok()
.map(|owner| owner.to_string())
}
fn status(&self) -> Result<Status> {
let iface = InterfaceName::from_static_str(SERVICE).expect("valid interface literal");
let mut props = self
.props
.get_all(iface)
.map_err(|err| anyhow!("{err}"))
.context("GetAll on org.scx.Loader failed")?;
Ok(Status {
current: none_if_unknown(take_prop::<String>(&mut props, "CurrentScheduler")?),
mode: take_prop(&mut props, "SchedulerMode")?,
args: take_prop(&mut props, "CurrentSchedulerArgs")?,
default_sched: none_if_unknown(take_prop::<String>(&mut props, "DefaultScheduler")?),
default_mode: take_prop(&mut props, "DefaultMode")?,
})
}
fn supported_schedulers(&self) -> Result<Vec<String>> {
if let Some(cached) = self.initial_schedulers.borrow_mut().take() {
return Ok(cached);
}
Ok(self.proxy.supported_schedulers()?)
}
fn mode_args(&self, sched: &str) -> Result<ModeArgs> {
Ok(self.proxy.scheduler_mode_args(sched)?)
}
fn start(&self, sched: &str, mode: SchedMode) -> Result<()> {
Ok(self.proxy.start_scheduler(sched, mode)?)
}
fn switch(&self, sched: &str, mode: SchedMode) -> Result<()> {
Ok(self.proxy.switch_scheduler(sched, mode)?)
}
fn start_with_args(&self, sched: &str, args: &[String]) -> Result<()> {
Ok(self.proxy.start_scheduler_with_args(sched, args)?)
}
fn switch_with_args(&self, sched: &str, args: &[String]) -> Result<()> {
Ok(self.proxy.switch_scheduler_with_args(sched, args)?)
}
fn stop(&self) -> Result<()> {
Ok(self.proxy.stop_scheduler()?)
}
fn restart(&self) -> Result<()> {
Ok(self.proxy.restart_scheduler()?)
}
fn restore_default(&self) -> Result<()> {
Ok(self.proxy.restore_default()?)
}
}