Debian Codegraph @

src/desktop/settings.rs

raw
1 //! ```rust,no_run
2 //! use ashpd::desktop::settings::Settings;
3 //! use futures_util::StreamExt;
4 //!
5 //! async fn run() -> ashpd::Result<()> {
6 //! let proxy = Settings::new().await?;
7 //!
8 //! let clock_format = proxy
9 //! .read::<String>("org.gnome.desktop.interface", "clock-format")
10 //! .await?;
11 //! println!("{:#?}", clock_format);
12 //!
13 //! let settings = proxy.read_all(&["org.gnome.desktop.interface"]).await?;
14 //! println!("{:#?}", settings);
15 //!
16 //! let setting = proxy
17 //! .receive_setting_changed()
18 //! .await?
19 //! .next()
20 //! .await
21 //! .expect("Stream exhausted");
22 //! println!("{}", setting.namespace());
23 //! println!("{}", setting.key());
24 //! println!("{:#?}", setting.value());
25 //!
26 //! Ok(())
27 //! }
28 //! ```
29
30 use std::{collections::HashMap, convert::TryFrom, fmt::Debug, future::ready};
31
32 use futures_util::{Stream, StreamExt};
33 use serde::{Deserialize, Serialize};
34 use zbus::zvariant::{OwnedValue, Type, Value};
35
36 use crate::{Error, desktop::Color, proxy::Proxy};
37
38 /// A HashMap of the <key, value> settings found on a specific namespace.
39 pub type Namespace = HashMap<String, OwnedValue>;
40
41 #[derive(Deserialize, Type)]
42 /// A specific `namespace.key = value` setting.
43 pub struct Setting(String, String, OwnedValue);
44
45 impl Setting {
46 /// The setting namespace.
47 pub fn namespace(&self) -> &str {
48 &self.0
49 }
50
51 /// The setting key.
52 pub fn key(&self) -> &str {
53 &self.1
54 }
55
56 /// The setting value.
57 pub fn value(&self) -> &OwnedValue {
58 &self.2
59 }
60 }
61
62 impl std::fmt::Debug for Setting {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.debug_struct("Setting")
65 .field("namespace", &self.namespace())
66 .field("key", &self.key())
67 .field("value", self.value())
68 .finish()
69 }
70 }
71
72 /// The system's preferred color scheme
73 #[cfg_attr(feature = "glib", derive(glib::Enum))]
74 #[cfg_attr(feature = "glib", enum_type(name = "AshpdColorScheme"))]
75 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
76 pub enum ColorScheme {
77 /// No preference
78 #[default]
79 NoPreference,
80 /// Prefers dark appearance
81 PreferDark,
82 /// Prefers light appearance
83 PreferLight,
84 }
85
86 impl From<ColorScheme> for OwnedValue {
87 fn from(value: ColorScheme) -> Self {
88 match value {
89 ColorScheme::PreferDark => 1,
90 ColorScheme::PreferLight => 2,
91 _ => 0,
92 }
93 .into()
94 }
95 }
96
97 impl TryFrom<OwnedValue> for ColorScheme {
98 type Error = Error;
99
100 fn try_from(value: OwnedValue) -> Result<Self, Self::Error> {
101 TryFrom::<Value>::try_from(value.into())
102 }
103 }
104
105 impl TryFrom<Value<'_>> for ColorScheme {
106 type Error = Error;
107
108 fn try_from(value: Value) -> Result<Self, Self::Error> {
109 Ok(match u32::try_from(value)? {
110 1 => Self::PreferDark,
111 2 => Self::PreferLight,
112 _ => Self::NoPreference,
113 })
114 }
115 }
116
117 /// The system's preferred contrast level
118 #[cfg_attr(feature = "glib", derive(glib::Enum))]
119 #[cfg_attr(feature = "glib", enum_type(name = "AshpdContrast"))]
120 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
121 pub enum Contrast {
122 /// No preference
123 #[default]
124 NoPreference,
125 /// Higher contrast
126 High,
127 }
128
129 impl From<Contrast> for OwnedValue {
130 fn from(value: Contrast) -> Self {
131 match value {
132 Contrast::High => 1,
133 _ => 0,
134 }
135 .into()
136 }
137 }
138
139 impl TryFrom<OwnedValue> for Contrast {
140 type Error = Error;
141
142 fn try_from(value: OwnedValue) -> Result<Self, Self::Error> {
143 TryFrom::<Value>::try_from(value.into())
144 }
145 }
146
147 impl TryFrom<Value<'_>> for Contrast {
148 type Error = Error;
149
150 fn try_from(value: Value) -> Result<Self, Self::Error> {
151 Ok(match u32::try_from(value)? {
152 1 => Self::High,
153 _ => Self::NoPreference,
154 })
155 }
156 }
157
158 /// The system's preferred motion
159 #[cfg_attr(feature = "glib", derive(glib::Enum))]
160 #[cfg_attr(feature = "glib", enum_type(name = "AshpdReducedMotion"))]
161 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
162 pub enum ReducedMotion {
163 /// No preference
164 #[default]
165 NoPreference,
166 /// Reduced motion
167 ReducedMotion,
168 }
169
170 impl From<ReducedMotion> for OwnedValue {
171 fn from(value: ReducedMotion) -> Self {
172 match value {
173 ReducedMotion::ReducedMotion => 1,
174 _ => 0,
175 }
176 .into()
177 }
178 }
179
180 impl TryFrom<OwnedValue> for ReducedMotion {
181 type Error = Error;
182
183 fn try_from(value: OwnedValue) -> Result<Self, Self::Error> {
184 TryFrom::<Value>::try_from(value.into())
185 }
186 }
187
188 impl TryFrom<Value<'_>> for ReducedMotion {
189 type Error = Error;
190
191 fn try_from(value: Value) -> Result<Self, Self::Error> {
192 Ok(match u32::try_from(value)? {
193 1 => Self::ReducedMotion,
194 _ => Self::NoPreference,
195 })
196 }
197 }
198
199 /// Appearance namespace
200 pub const APPEARANCE_NAMESPACE: &str = "org.freedesktop.appearance";
201 /// Color scheme key
202 pub const COLOR_SCHEME_KEY: &str = "color-scheme";
203 /// Accent color key
204 pub const ACCENT_COLOR_SCHEME_KEY: &str = "accent-color";
205 /// Contrast key
206 pub const CONTRAST_KEY: &str = "contrast";
207 /// Reduced motion key
208 pub const REDUCED_MOTION_KEY: &str = "reduced-motion";
209
210 /// The interface provides read-only access to a small number of host settings
211 /// required for toolkits similar to XSettings. It is not for general purpose
212 /// settings.
213 ///
214 /// Wrapper of the DBus interface: [`org.freedesktop.portal.Settings`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html).
215 #[derive(Debug)]
216 #[doc(alias = "org.freedesktop.portal.Settings")]
217 pub struct Settings(Proxy<'static>);
218
219 impl Settings {
220 /// Create a new instance of [`Settings`].
221 pub async fn new() -> Result<Settings, Error> {
222 let proxy = Proxy::new_desktop("org.freedesktop.portal.Settings").await?;
223 Ok(Self(proxy))
224 }
225
226 /// Create a new instance of [`Settings`].
227 pub async fn with_connection(connection: zbus::Connection) -> Result<Settings, Error> {
228 let proxy =
229 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.Settings")
230 .await?;
231 Ok(Self(proxy))
232 }
233
234 /// Returns the version of the portal interface.
235 pub fn version(&self) -> u32 {
236 self.0.version()
237 }
238
239 /// Reads a single value. Returns an error on any unknown namespace or key.
240 ///
241 /// # Arguments
242 ///
243 /// * `namespaces` - List of namespaces to filter results by.
244 ///
245 /// If `namespaces` is an empty array or contains an empty string it matches
246 /// all. Globing is supported but only for trailing sections, e.g.
247 /// `org.example.*`.
248 ///
249 /// # Returns
250 ///
251 /// A `HashMap` of namespaces to its keys and values.
252 ///
253 /// # Specifications
254 ///
255 /// See also [`ReadAll`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html#org-freedesktop-portal-settings-readall).
256 #[doc(alias = "ReadAll")]
257 pub async fn read_all(
258 &self,
259 namespaces: &[impl AsRef<str> + Type + Serialize + Debug],
260 ) -> Result<HashMap<String, Namespace>, Error> {
261 self.0.call("ReadAll", &(namespaces)).await
262 }
263
264 /// Reads a single value. Returns an error on any unknown namespace or key.
265 ///
266 /// # Arguments
267 ///
268 /// * `namespace` - Namespace to look up key in.
269 /// * `key` - The key to get.
270 ///
271 /// # Returns
272 ///
273 /// The value for `key` as a `zvariant::OwnedValue`.
274 ///
275 /// # Specifications
276 ///
277 /// See also [`Read`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html#org-freedesktop-portal-settings-read).
278 #[doc(alias = "Read")]
279 #[doc(alias = "ReadOne")]
280 pub async fn read<T>(&self, namespace: &str, key: &str) -> Result<T, Error>
281 where
282 T: TryFrom<OwnedValue>,
283 Error: From<<T as TryFrom<OwnedValue>>::Error>,
284 {
285 let value = self.0.call::<OwnedValue>("Read", &(namespace, key)).await?;
286 if let Ok(v) = value.downcast_ref::<Value>() {
287 T::try_from(v.try_to_owned()?).map_err(From::from)
288 } else {
289 T::try_from(value).map_err(From::from)
290 }
291 }
292
293 /// Retrieves the system's preferred accent color
294 pub async fn accent_color(&self) -> Result<Color, Error> {
295 self.read::<(f64, f64, f64)>(APPEARANCE_NAMESPACE, ACCENT_COLOR_SCHEME_KEY)
296 .await
297 .map(Color::from)
298 }
299
300 /// Retrieves the system's preferred color scheme
301 pub async fn color_scheme(&self) -> Result<ColorScheme, Error> {
302 self.read::<ColorScheme>(APPEARANCE_NAMESPACE, COLOR_SCHEME_KEY)
303 .await
304 }
305
306 /// Retrieves the system's preferred contrast level
307 pub async fn contrast(&self) -> Result<Contrast, Error> {
308 self.read::<Contrast>(APPEARANCE_NAMESPACE, CONTRAST_KEY)
309 .await
310 }
311
312 /// Retrieves the system's reduced motion preference
313 pub async fn reduced_motion(&self) -> Result<ReducedMotion, Error> {
314 self.read::<ReducedMotion>(APPEARANCE_NAMESPACE, REDUCED_MOTION_KEY)
315 .await
316 }
317
318 /// Listen to changes of the system's preferred color scheme
319 pub async fn receive_color_scheme_changed(
320 &self,
321 ) -> Result<impl Stream<Item = ColorScheme>, Error> {
322 Ok(self
323 .receive_setting_changed_with_args(APPEARANCE_NAMESPACE, COLOR_SCHEME_KEY)
324 .await?
325 .filter_map(|t| ready(t.ok())))
326 }
327
328 /// Listen to changes of the system's accent color
329 pub async fn receive_accent_color_changed(&self) -> Result<impl Stream<Item = Color>, Error> {
330 Ok(self
331 .receive_setting_changed_with_args::<(f64, f64, f64)>(
332 APPEARANCE_NAMESPACE,
333 ACCENT_COLOR_SCHEME_KEY,
334 )
335 .await?
336 .filter_map(|t| ready(t.ok().map(Color::from))))
337 }
338
339 /// Listen to changes of the system's contrast level
340 pub async fn receive_contrast_changed(&self) -> Result<impl Stream<Item = Contrast>, Error> {
341 Ok(self
342 .receive_setting_changed_with_args(APPEARANCE_NAMESPACE, CONTRAST_KEY)
343 .await?
344 .filter_map(|t| ready(t.ok())))
345 }
346
347 /// Listen to changes of the system's reduced motion preference
348 pub async fn receive_reduced_motion_changed(
349 &self,
350 ) -> Result<impl Stream<Item = ReducedMotion>, Error> {
351 Ok(self
352 .receive_setting_changed_with_args(APPEARANCE_NAMESPACE, REDUCED_MOTION_KEY)
353 .await?
354 .filter_map(|t| ready(t.ok())))
355 }
356
357 /// Signal emitted when a setting changes.
358 ///
359 /// # Specifications
360 ///
361 /// See also [`SettingChanged`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Settings.html#org-freedesktop-portal-settings-settingchanged).
362 #[doc(alias = "SettingChanged")]
363 pub async fn receive_setting_changed(&self) -> Result<impl Stream<Item = Setting>, Error> {
364 self.0.signal("SettingChanged").await
365 }
366
367 /// Similar to [Self::receive_setting_changed]
368 /// but allows you to filter specific settings.
369 ///
370 /// # Example
371 /// ```rust,no_run
372 /// use ashpd::desktop::settings::{ColorScheme, Settings};
373 /// use futures_util::StreamExt;
374 ///
375 /// # async fn run() -> ashpd::Result<()> {
376 /// let settings = Settings::new().await?;
377 /// while let Some(Ok(scheme)) = settings
378 /// .receive_setting_changed_with_args::<ColorScheme>(
379 /// "org.freedesktop.appearance",
380 /// "color-scheme",
381 /// )
382 /// .await?
383 /// .next()
384 /// .await
385 /// {
386 /// println!("{:#?}", scheme);
387 /// }
388 /// # Ok(())
389 /// # }
390 /// ```
391 pub async fn receive_setting_changed_with_args<T>(
392 &self,
393 namespace: &str,
394 key: &str,
395 ) -> Result<impl Stream<Item = Result<T, Error>> + use<T>, Error>
396 where
397 T: TryFrom<OwnedValue>,
398 Error: From<<T as TryFrom<OwnedValue>>::Error>,
399 {
400 Ok(self
401 .0
402 .signal_with_args::<Setting>("SettingChanged", &[(0, namespace), (1, key)])
403 .await?
404 .map(|x| T::try_from(x.2).map_err(From::from)))
405 }
406 }
407
408 impl std::ops::Deref for Settings {
409 type Target = zbus::Proxy<'static>;
410
411 fn deref(&self) -> &Self::Target {
412 &self.0
413 }
414 }