use std::{borrow::Cow, fmt};
use super::{percent::decode_percents_str, DBusAddr, KeyValFmt, KeyValFmtAdd};
use crate::{Error, Result};
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AutolaunchScope<'a> {
InstallPath,
User,
Other(Cow<'a, str>),
}
impl fmt::Display for AutolaunchScope<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InstallPath => write!(f, "*install-path"),
Self::User => write!(f, "*user"),
Self::Other(o) => write!(f, "{o}"),
}
}
}
impl<'a> TryFrom<Cow<'a, str>> for AutolaunchScope<'a> {
type Error = Error;
fn try_from(s: Cow<'a, str>) -> Result<Self> {
match s.as_ref() {
"*install-path" => Ok(Self::InstallPath),
"*user" => Ok(Self::User),
_ => Ok(Self::Other(s)),
}
}
}
#[derive(Debug, PartialEq, Eq, Default)]
pub struct Autolaunch<'a> {
scope: Option<AutolaunchScope<'a>>,
}
impl<'a> Autolaunch<'a> {
pub fn scope(&self) -> Option<&AutolaunchScope<'a>> {
self.scope.as_ref()
}
}
impl<'a> TryFrom<&'a DBusAddr<'a>> for Autolaunch<'a> {
type Error = Error;
fn try_from(s: &'a DBusAddr<'a>) -> Result<Self> {
let mut res = Autolaunch::default();
for (k, v) in s.key_val_iter() {
match (k, v) {
("scope", Some(v)) => {
res.scope = Some(decode_percents_str(v)?.try_into()?);
}
_ => continue,
}
}
Ok(res)
}
}
impl KeyValFmtAdd for Autolaunch<'_> {
fn key_val_fmt_add<'a: 'b, 'b>(&'a self, kv: KeyValFmt<'b>) -> KeyValFmt<'b> {
kv.add("scope", self.scope())
}
}