use super::{DESTINATION, PATH};
use crate::{
helpers::{call_method, receive_signal},
Error,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{collections::HashMap, convert::TryFrom};
use zvariant::OwnedValue;
use zvariant_derive::Type;
pub type Namespace = HashMap<String, OwnedValue>;
#[derive(Serialize, Clone, Deserialize, Type)]
pub struct Setting(String, String, OwnedValue);
impl Setting {
pub fn namespace(&self) -> &str {
&self.0
}
pub fn key(&self) -> &str {
&self.1
}
pub fn value(&self) -> &OwnedValue {
&self.2
}
}
impl std::fmt::Debug for Setting {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Setting")
.field("namespace", &self.namespace())
.field("key", &self.key())
.field("value", self.value())
.finish()
}
}
#[derive(Debug)]
#[doc(alias = "org.freedesktop.portal.Settings")]
pub struct SettingsProxy<'a>(zbus::azync::Proxy<'a>);
impl<'a> SettingsProxy<'a> {
pub async fn new(connection: &zbus::azync::Connection) -> Result<SettingsProxy<'a>, Error> {
let proxy = zbus::ProxyBuilder::new_bare(connection)
.interface("org.freedesktop.portal.Settings")
.path(PATH)?
.destination(DESTINATION)
.build_async()
.await?;
Ok(Self(proxy))
}
pub fn inner(&self) -> &zbus::azync::Proxy<'_> {
&self.0
}
#[doc(alias = "ReadAll")]
pub async fn read_all<S: AsRef<str> + zvariant::Type + Serialize>(
&self,
namespaces: &[S],
) -> Result<HashMap<String, Namespace>, Error> {
call_method(&self.0, "ReadAll", &(namespaces)).await
}
#[doc(alias = "Read")]
pub async fn read<T>(&self, namespace: &str, key: &str) -> Result<T, Error>
where
T: TryFrom<OwnedValue> + DeserializeOwned + zvariant::Type,
{
call_method(&self.0, "Read", &(namespace, key)).await
}
#[doc(alias = "SettingChanged")]
pub async fn receive_setting_changed(&self) -> Result<Setting, Error> {
receive_signal(&self.0, "SettingChanged").await
}
}