ashpd/desktop/
device.rs

1//! Request access to specific devices such as camera, speakers or microphone.
2//!
3//! **Note** This portal doesn't work for sandboxed applications.
4//!
5//! ### Examples
6//!
7//! Access a [`Device`]
8//!
9//! ```rust,no_run
10//! use ashpd::desktop::device::{Device, DeviceProxy};
11//!
12//! async fn run() -> ashpd::Result<()> {
13//!     let proxy = DeviceProxy::new().await?;
14//!     proxy.access_device(6879, &[Device::Speakers]).await?;
15//!     Ok(())
16//! }
17//! ```
18
19use std::{fmt, str::FromStr};
20
21use serde::{Deserialize, Serialize};
22use zbus::zvariant::{SerializeDict, Type};
23
24use super::{HandleToken, Request};
25use crate::{proxy::Proxy, Error, Pid};
26
27#[derive(SerializeDict, Type, Debug, Default)]
28/// Specified options for a [`DeviceProxy::access_device`] request.
29#[zvariant(signature = "dict")]
30struct AccessDeviceOptions {
31    /// A string that will be used as the last element of the handle.
32    handle_token: HandleToken,
33}
34
35#[cfg_attr(feature = "glib", derive(glib::Enum))]
36#[cfg_attr(feature = "glib", enum_type(name = "AshpdDevice"))]
37#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Type)]
38#[zvariant(signature = "s")]
39#[serde(rename_all = "lowercase")]
40/// The possible device to request access to.
41pub enum Device {
42    /// A microphone.
43    Microphone,
44    /// Speakers.
45    Speakers,
46    /// A Camera.
47    Camera,
48}
49
50impl fmt::Display for Device {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::Microphone => write!(f, "Microphone"),
54            Self::Speakers => write!(f, "Speakers"),
55            Self::Camera => write!(f, "Camera"),
56        }
57    }
58}
59
60impl AsRef<str> for Device {
61    fn as_ref(&self) -> &str {
62        match self {
63            Self::Microphone => "Microphone",
64            Self::Speakers => "Speakers",
65            Self::Camera => "Camera",
66        }
67    }
68}
69
70impl From<Device> for &'static str {
71    fn from(d: Device) -> Self {
72        match d {
73            Device::Microphone => "Microphone",
74            Device::Speakers => "Speakers",
75            Device::Camera => "Camera",
76        }
77    }
78}
79
80impl FromStr for Device {
81    type Err = Error;
82
83    fn from_str(s: &str) -> Result<Self, Self::Err> {
84        match s {
85            "Microphone" | "microphone" => Ok(Device::Microphone),
86            "Speakers" | "speakers" => Ok(Device::Speakers),
87            "Camera" | "camera" => Ok(Device::Camera),
88            _ => Err(Error::ParseError("Failed to parse device, invalid value")),
89        }
90    }
91}
92
93/// The interface lets services ask if an application should get access to
94/// devices such as microphones, speakers or cameras.
95///
96/// Not a portal in the strict sense, since the API is not directly
97/// accessible to applications inside the sandbox.
98///
99/// Wrapper of the DBus interface:
100/// [`org.freedesktop.portal.Device`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Device.html).
101#[derive(Debug)]
102#[doc(alias = "org.freedesktop.portal.Device")]
103pub struct DeviceProxy<'a>(Proxy<'a>);
104
105impl<'a> DeviceProxy<'a> {
106    /// Create a new instance of [`DeviceProxy`].
107    pub async fn new() -> Result<DeviceProxy<'a>, Error> {
108        let proxy = Proxy::new_desktop("org.freedesktop.portal.Device").await?;
109        Ok(Self(proxy))
110    }
111
112    /// Asks for access to a device.
113    ///
114    /// # Arguments
115    ///
116    /// * `pid` - The pid of the application on whose behalf the request is
117    ///   made.
118    /// * `devices` - A list of devices to request access to.
119    ///
120    /// *Note* Asking for multiple devices at the same time may or may not be
121    /// supported
122    ///
123    /// # Specifications
124    ///
125    /// See also [`AccessDevice`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Device.html#org-freedesktop-portal-device-accessdevice).
126    #[doc(alias = "AccessDevice")]
127    pub async fn access_device(&self, pid: Pid, devices: &[Device]) -> Result<Request<()>, Error> {
128        let options = AccessDeviceOptions::default();
129        self.0
130            .empty_request(
131                &options.handle_token,
132                "AccessDevice",
133                &(pid, devices, &options),
134            )
135            .await
136    }
137}
138
139impl<'a> std::ops::Deref for DeviceProxy<'a> {
140    type Target = zbus::Proxy<'a>;
141
142    fn deref(&self) -> &Self::Target {
143        &self.0
144    }
145}