1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! ```rust,no_run
//! use ashpd::desktop::settings::Settings;
//! use futures_util::StreamExt;
//!
//! async fn run() -> ashpd::Result<()> {
//!     let proxy = Settings::new().await?;
//!
//!     let clock_format = proxy
//!         .read::<String>("org.gnome.desktop.interface", "clock-format")
//!         .await?;
//!     println!("{:#?}", clock_format);
//!
//!     let settings = proxy.read_all(&["org.gnome.desktop.interface"]).await?;
//!     println!("{:#?}", settings);
//!
//!     let setting = proxy
//!         .receive_setting_changed()
//!         .await?
//!         .next()
//!         .await
//!         .expect("Stream exhausted");
//!     println!("{}", setting.namespace());
//!     println!("{}", setting.key());
//!     println!("{:#?}", setting.value());
//!
//!     Ok(())
//! }
//! ```

use std::{collections::HashMap, convert::TryFrom, fmt::Debug, future::ready};

use futures_util::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use zbus::zvariant::{OwnedValue, Type, Value};

use crate::{desktop::Color, proxy::Proxy, Error};

/// A HashMap of the <key, value> settings found on a specific namespace.
pub type Namespace = HashMap<String, OwnedValue>;

#[derive(Deserialize, Type)]
/// A specific `namespace.key = value` setting.
pub struct Setting(String, String, OwnedValue);

impl Setting {
    /// The setting namespace.
    pub fn namespace(&self) -> &str {
        &self.0
    }

    /// The setting key.
    pub fn key(&self) -> &str {
        &self.1
    }

    /// The setting value.
    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()
    }
}

/// The system's preferred color scheme
#[cfg_attr(feature = "glib", derive(glib::Enum))]
#[cfg_attr(feature = "glib", enum_type(name = "AshpdColorScheme"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ColorScheme {
    /// No preference
    NoPreference,
    /// Prefers dark appearance
    PreferDark,
    /// Prefers light appearance
    PreferLight,
}

impl TryFrom<OwnedValue> for ColorScheme {
    type Error = Error;

    fn try_from(value: OwnedValue) -> Result<Self, Self::Error> {
        TryFrom::<Value>::try_from(value.into())
    }
}

impl TryFrom<Value<'_>> for ColorScheme {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        Ok(match u32::try_from(value)? {
            1 => Self::PreferDark,
            2 => Self::PreferLight,
            _ => Self::NoPreference,
        })
    }
}

/// The system's preferred contrast level
#[cfg_attr(feature = "glib", derive(glib::Enum))]
#[cfg_attr(feature = "glib", enum_type(name = "AshpdContrast"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Contrast {
    /// No preference
    NoPreference,
    /// Higher contrast
    High,
}

impl TryFrom<OwnedValue> for Contrast {
    type Error = Error;

    fn try_from(value: OwnedValue) -> Result<Self, Self::Error> {
        TryFrom::<Value>::try_from(value.into())
    }
}

impl TryFrom<Value<'_>> for Contrast {
    type Error = Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        Ok(match u32::try_from(value)? {
            1 => Self::High,
            _ => Self::NoPreference,
        })
    }
}

const APPEARANCE_NAMESPACE: &str = "org.freedesktop.appearance";
const COLOR_SCHEME_KEY: &str = "color-scheme";
const ACCENT_COLOR_SCHEME_KEY: &str = "accent-color";
const CONTRAST_KEY: &str = "contrast";

/// The interface provides read-only access to a small number of host settings
/// required for toolkits similar to XSettings. It is not for general purpose
/// settings.
///
/// Wrapper of the DBus interface: [`org.freedesktop.portal.Settings`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html).
#[derive(Debug)]
#[doc(alias = "org.freedesktop.portal.Settings")]
pub struct Settings<'a>(Proxy<'a>);

impl<'a> Settings<'a> {
    /// Create a new instance of [`Settings`].
    pub async fn new() -> Result<Settings<'a>, Error> {
        let proxy = Proxy::new_desktop("org.freedesktop.portal.Settings").await?;
        Ok(Self(proxy))
    }

    /// Reads a single value. Returns an error on any unknown namespace or key.
    ///
    /// # Arguments
    ///
    /// * `namespaces` - List of namespaces to filter results by.
    ///
    /// If `namespaces` is an empty array or contains an empty string it matches
    /// all. Globing is supported but only for trailing sections, e.g.
    /// `org.example.*`.
    ///
    /// # Returns
    ///
    /// A `HashMap` of namespaces to its keys and values.
    ///
    /// # Specifications
    ///
    /// See also [`ReadAll`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html#org-freedesktop-portal-settings-readall).
    #[doc(alias = "ReadAll")]
    pub async fn read_all(
        &self,
        namespaces: &[impl AsRef<str> + Type + Serialize + Debug],
    ) -> Result<HashMap<String, Namespace>, Error> {
        self.0.call("ReadAll", &(namespaces)).await
    }

    /// Reads a single value. Returns an error on any unknown namespace or key.
    ///
    /// # Arguments
    ///
    /// * `namespace` - Namespace to look up key in.
    /// * `key` - The key to get.
    ///
    /// # Returns
    ///
    /// The value for `key` as a `zvariant::OwnedValue`.
    ///
    /// # Specifications
    ///
    /// See also [`Read`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html#org-freedesktop-portal-settings-read).
    #[doc(alias = "Read")]
    #[doc(alias = "ReadOne")]
    pub async fn read<T>(&self, namespace: &str, key: &str) -> Result<T, Error>
    where
        T: TryFrom<OwnedValue>,
        Error: From<<T as TryFrom<OwnedValue>>::Error>,
    {
        let value = self.0.call::<OwnedValue>("Read", &(namespace, key)).await?;
        if let Ok(v) = value.downcast_ref::<Value>() {
            T::try_from(v.try_to_owned()?).map_err(From::from)
        } else {
            T::try_from(value).map_err(From::from)
        }
    }

    /// Retrieves the system's preferred accent color
    pub async fn accent_color(&self) -> Result<Color, Error> {
        self.read::<(f64, f64, f64)>(APPEARANCE_NAMESPACE, ACCENT_COLOR_SCHEME_KEY)
            .await
            .map(Color::new)
    }

    /// Retrieves the system's preferred color scheme
    pub async fn color_scheme(&self) -> Result<ColorScheme, Error> {
        self.read::<ColorScheme>(APPEARANCE_NAMESPACE, COLOR_SCHEME_KEY)
            .await
    }

    /// Retrieves the system's preferred contrast level
    pub async fn contrast(&self) -> Result<Contrast, Error> {
        self.read::<Contrast>(APPEARANCE_NAMESPACE, CONTRAST_KEY)
            .await
    }

    /// Listen to changes of the system's preferred color scheme
    pub async fn receive_color_scheme_changed(
        &self,
    ) -> Result<impl Stream<Item = ColorScheme>, Error> {
        Ok(self
            .receive_setting_changed_with_args(APPEARANCE_NAMESPACE, COLOR_SCHEME_KEY)
            .await?
            .filter_map(|t| ready(t.ok())))
    }

    /// Listen to changes of the system's accent color
    pub async fn receive_accent_color_changed(&self) -> Result<impl Stream<Item = Color>, Error> {
        Ok(self
            .receive_setting_changed_with_args::<(f64, f64, f64)>(
                APPEARANCE_NAMESPACE,
                ACCENT_COLOR_SCHEME_KEY,
            )
            .await?
            .filter_map(|t| ready(t.ok().map(Color::new))))
    }

    /// Listen to changes of the system's contrast level
    pub async fn receive_contrast_changed(&self) -> Result<impl Stream<Item = Contrast>, Error> {
        Ok(self
            .receive_setting_changed_with_args(APPEARANCE_NAMESPACE, CONTRAST_KEY)
            .await?
            .filter_map(|t| ready(t.ok())))
    }

    /// Signal emitted when a setting changes.
    ///
    /// # Specifications
    ///
    /// See also [`SettingChanged`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html#org-freedesktop-portal-settings-settingchanged).
    #[doc(alias = "SettingChanged")]
    pub async fn receive_setting_changed(&self) -> Result<impl Stream<Item = Setting>, Error> {
        self.0.signal("SettingChanged").await
    }

    /// Similar to [Self::receive_setting_changed]
    /// but allows you to filter specific settings.
    ///
    /// # Example
    /// ```rust,no_run
    /// use ashpd::desktop::settings::{ColorScheme, Settings};
    /// use futures_util::StreamExt;
    ///
    /// # async fn run() -> ashpd::Result<()> {
    /// let settings = Settings::new().await?;
    /// while let Some(Ok(scheme)) = settings
    ///     .receive_setting_changed_with_args::<ColorScheme>(
    ///         "org.freedesktop.appearance",
    ///         "color-scheme",
    ///     )
    ///     .await?
    ///     .next()
    ///     .await
    /// {
    ///     println!("{:#?}", scheme);
    /// }
    /// #    Ok(())
    /// # }
    /// ```
    pub async fn receive_setting_changed_with_args<T>(
        &self,
        namespace: &str,
        key: &str,
    ) -> Result<impl Stream<Item = Result<T, Error>>, Error>
    where
        T: TryFrom<OwnedValue>,
        Error: From<<T as TryFrom<OwnedValue>>::Error>,
    {
        Ok(self
            .0
            .signal_with_args::<Setting>("SettingChanged", &[(0, namespace), (1, key)])
            .await?
            .map(|x| T::try_from(x.2).map_err(From::from)))
    }
}

impl<'a> std::ops::Deref for Settings<'a> {
    type Target = zbus::Proxy<'a>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}