Debian Codegraph @

src/desktop/usb.rs

raw
1 // Copyright (C) 2024-2025 GNOME Foundation
2 //
3 // Authors:
4 // Hubert Figuière <[email protected]>
5 //
6
7 //! Provide an interface to USB device. Allow enumerating devices
8 //! and requiring access to.
9 //! ```rust,no_run
10 //! use ashpd::desktop::usb::UsbProxy;
11 //! use futures_util::StreamExt;
12 //!
13 //! async fn watch_devices() -> ashpd::Result<()> {
14 //! let usb = UsbProxy::new().await?;
15 //! let session = usb.create_session(Default::default()).await?;
16 //! if let Some(response) = usb.receive_device_events().await?.next().await {
17 //! let events = response.events();
18 //! for ev in events {
19 //! println!(
20 //! "Received event: {:#?} for device {}",
21 //! ev.action(),
22 //! ev.device_id()
23 //! );
24 //! }
25 //! }
26 //!
27 //! Ok(())
28 //! }
29 //! ```
30
31 use std::collections::HashMap;
32
33 use futures_util::Stream;
34 use serde::{Deserialize, Serialize};
35 use zbus::zvariant::{
36 ObjectPath, OwnedFd, OwnedObjectPath, OwnedValue, Type,
37 as_value::{self, optional},
38 };
39
40 use crate::{
41 Error, WindowIdentifier,
42 desktop::{CreateSessionOptions, HandleToken, Session, SessionPortal},
43 proxy::Proxy,
44 };
45
46 #[derive(Debug, Clone, Hash, Serialize, Deserialize, Type, PartialEq, Eq)]
47 #[zvariant(signature = "s")]
48 /// A device identifier.
49 pub struct DeviceID(String);
50
51 impl DeviceID {
52 /// Gets the ID as a string.
53 pub fn as_str(&self) -> &str {
54 &self.0
55 }
56 }
57
58 impl AsRef<str> for DeviceID {
59 fn as_ref(&self) -> &str {
60 &self.0
61 }
62 }
63
64 impl std::ops::Deref for DeviceID {
65 type Target = str;
66
67 fn deref(&self) -> &Self::Target {
68 &self.0
69 }
70 }
71
72 impl From<String> for DeviceID {
73 fn from(s: String) -> Self {
74 Self(s)
75 }
76 }
77
78 impl std::fmt::Display for DeviceID {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 write!(f, "{}", self.0)
81 }
82 }
83
84 #[derive(Serialize, Type, Debug, Default)]
85 #[zvariant(signature = "dict")]
86 /// Specified options for a [`UsbProxy::enumerate_devices`] request.
87 pub struct EnumerateDevicesOptions {}
88
89 #[derive(Serialize, Type, Debug, Default)]
90 #[zvariant(signature = "dict")]
91 /// Specified options for a [`UsbProxy::release_devices`] request.
92 pub struct ReleaseDevicesOptions {}
93
94 #[derive(Serialize, Type, Debug, Default)]
95 #[zvariant(signature = "dict")]
96 /// Specified options for a [`UsbProxy::finish_acquire_devices`] request.
97 struct FinishAcquireDevicesOptions {}
98
99 /// USB device description
100 #[derive(Serialize, Deserialize, Clone, Type, Debug, Default)]
101 #[zvariant(signature = "dict")]
102 pub struct UsbDevice {
103 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
104 parent: Option<DeviceID>,
105 /// Device can be opened for reading. Default is false.
106 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
107 readable: Option<bool>,
108 /// Device can be opened for writing. Default is false.
109 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
110 writable: Option<bool>,
111 /// The device node for the USB.
112 #[serde(
113 default,
114 rename = "device-file",
115 with = "optional",
116 skip_serializing_if = "Option::is_none"
117 )]
118 device_file: Option<String>,
119 /// Device properties
120 #[serde(default, with = "as_value", skip_serializing_if = "HashMap::is_empty")]
121 properties: HashMap<String, OwnedValue>,
122 }
123
124 impl UsbDevice {
125 /// Device ID of the parent device
126 pub fn parent(&self) -> Option<&DeviceID> {
127 self.parent.as_ref()
128 }
129
130 /// Return if the device is readable.
131 pub fn is_readable(&self) -> bool {
132 self.readable.unwrap_or(false)
133 }
134
135 /// Return if the device is writable.
136 pub fn is_writable(&self) -> bool {
137 self.writable.unwrap_or(false)
138 }
139
140 /// Return the optional device file.
141 pub fn device_file(&self) -> Option<&str> {
142 self.device_file.as_deref()
143 }
144
145 /// Return the vendor string property for display.
146 pub fn vendor(&self) -> Option<String> {
147 self.properties
148 .get("ID_VENDOR_FROM_DATABASE")
149 .or_else(|| self.properties.get("ID_VENDOR_ENC"))
150 .and_then(|v| v.downcast_ref::<String>().ok())
151 }
152
153 /// Return the model string property for display.
154 pub fn model(&self) -> Option<String> {
155 self.properties
156 .get("ID_MODEL_FROM_DATABASE")
157 .or_else(|| self.properties.get("ID_MODEL_ENC"))
158 .and_then(|v| v.downcast_ref::<String>().ok())
159 .map(|model| {
160 model
161 .replace("\\x20", " ") // Unescape the literal \x20 to space
162 .split_whitespace()
163 .collect::<Vec<_>>()
164 .join(" ")
165 })
166 }
167
168 /// Return the device properties.
169 pub fn properties(&self) -> &HashMap<String, OwnedValue> {
170 &self.properties
171 }
172 }
173
174 /// USB error for acquiring device.
175 #[derive(Debug)]
176 pub struct UsbError(pub Option<String>);
177
178 impl std::fmt::Display for UsbError {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 write!(f, "{}", self.0.as_deref().unwrap_or(""))
181 }
182 }
183
184 impl std::error::Error for UsbError {}
185
186 impl From<AcquiredDevice> for Result<OwnedFd, UsbError> {
187 fn from(v: AcquiredDevice) -> Result<OwnedFd, UsbError> {
188 if let Some(fd) = v.fd {
189 if v.success {
190 Ok(fd)
191 } else {
192 Err(UsbError(v.error))
193 }
194 } else {
195 Err(UsbError(None))
196 }
197 }
198 }
199
200 /// Device to acquire.
201 #[derive(Serialize, Type, Debug, Default)]
202 #[zvariant(signature = "dict")]
203 struct AcquireDevice {
204 #[serde(with = "as_value")]
205 writable: bool,
206 }
207
208 /// Device to acquire. Tuple with the device ID and whether the
209 /// requested permission should be to write.
210 pub struct Device(DeviceID, bool /* writable */);
211
212 impl Device {
213 /// Create a new `Device`.
214 pub fn new(id: DeviceID, writable: bool) -> Self {
215 Self(id, writable)
216 }
217
218 /// Get the device ID.
219 pub fn id(&self) -> &DeviceID {
220 &self.0
221 }
222
223 /// Return whether the device is writable.
224 pub fn is_writable(&self) -> bool {
225 self.1
226 }
227 }
228
229 #[derive(Serialize, Type, Debug, Default)]
230 #[zvariant(signature = "dict")]
231 /// Specified options for a [`UsbProxy::acquire_devices`] request.
232 pub struct AcquireDevicesOptions {
233 #[serde(with = "as_value")]
234 handle_token: HandleToken,
235 }
236
237 /// Finished device acquired.
238 #[derive(Deserialize, Type, Debug, Default)]
239 #[zvariant(signature = "dict")]
240 struct AcquiredDevice {
241 #[serde(with = "as_value")]
242 success: bool,
243 #[serde(default, with = "optional")]
244 fd: Option<OwnedFd>,
245 #[serde(default, with = "optional")]
246 error: Option<String>,
247 }
248
249 #[derive(Debug, Deserialize, Type)]
250 /// A USB event received part of the `device_event` signal response.
251 /// An event is composed of an `action`, a device `id` and the
252 /// [`UsbDevice`] description.
253 pub struct UsbEvent(UsbEventAction, DeviceID, UsbDevice);
254
255 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Type)]
256 #[zvariant(signature = "s")]
257 #[serde(rename_all = "lowercase")]
258 /// A USB event action.
259 pub enum UsbEventAction {
260 /// Add.
261 Add,
262 /// Change.
263 Change,
264 /// Remove.
265 Remove,
266 }
267
268 impl UsbEvent {
269 /// The action.
270 pub fn action(&self) -> UsbEventAction {
271 self.0
272 }
273
274 /// The device ID string.
275 pub fn device_id(&self) -> &DeviceID {
276 &self.1
277 }
278
279 /// The [`UsbDevice`] properties.
280 pub fn device(&self) -> &UsbDevice {
281 &self.2
282 }
283 }
284
285 #[derive(Debug, Deserialize, Type)]
286 /// A response received when the `device_event` signal is received.
287 pub struct UsbDeviceEvent(OwnedObjectPath, Vec<UsbEvent>);
288
289 impl UsbDeviceEvent {
290 /// The session that triggered the state change
291 pub fn session_handle(&self) -> ObjectPath<'_> {
292 self.0.as_ref()
293 }
294
295 /// Events received
296 pub fn events(&self) -> &[UsbEvent] {
297 &self.1
298 }
299 }
300
301 /// This interface provides access to USB devices.
302 #[derive(Debug)]
303 #[doc(alias = "org.freedesktop.portal.Usb")]
304 pub struct UsbProxy(Proxy<'static>);
305
306 impl UsbProxy {
307 /// Create a new instance of [`UsbProxy`].
308 pub async fn new() -> Result<Self, Error> {
309 let proxy = Proxy::new_desktop("org.freedesktop.portal.Usb").await?;
310 Ok(Self(proxy))
311 }
312
313 /// Create a new instance of [`UsbProxy`].
314 pub async fn with_connection(connection: zbus::Connection) -> Result<Self, Error> {
315 let proxy =
316 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.Usb").await?;
317 Ok(Self(proxy))
318 }
319
320 /// Returns the version of the portal interface.
321 pub fn version(&self) -> u32 {
322 self.0.version()
323 }
324
325 /// Create a USB session.
326 ///
327 /// While this session is active, the caller will receive
328 /// `DeviceEvents` signals with device addition and removal.
329 ///
330 /// # Specifications
331 ///
332 /// See also [`CreateSession`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Usb.html#org-freedesktop-portal-usb-createsession).
333 #[doc(alias = "CreateSession")]
334 pub async fn create_session(
335 &self,
336 options: CreateSessionOptions,
337 ) -> Result<Session<Self>, Error> {
338 let session: OwnedObjectPath = self.0.call("CreateSession", &(&options)).await?;
339 Session::with_connection(self.0.connection().clone(), session).await
340 }
341
342 /// Enumerate USB devices.
343 ///
344 /// Return a vector of tuples with the device ID and the [`UsbDevice`]
345 ///
346 /// # Specifications
347 ///
348 /// See also [`EnumerateDevices`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Usb.html#org-freedesktop-portal-usb-enumeratedevices).
349 #[doc(alias = "EnumerateDevices")]
350 pub async fn enumerate_devices(
351 &self,
352 options: EnumerateDevicesOptions,
353 ) -> Result<Vec<(DeviceID, UsbDevice)>, Error> {
354 self.0.call("EnumerateDevices", &(&options)).await
355 }
356
357 /// Acquire devices
358 ///
359 /// The portal will perform the permission request. In case of
360 /// success, ie permission is granted, it returns a vector of
361 /// tuples containing the device ID and the file descriptor or
362 /// error.
363 ///
364 /// # Specifications
365 ///
366 /// See also [`AcquireDevices`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Usb.html#org-freedesktop-portal-usb-acquiredevices).
367 #[doc(alias = "AcquireDevices")]
368 pub async fn acquire_devices(
369 &self,
370 parent_window: Option<&WindowIdentifier>,
371 devices: &[Device],
372 options: AcquireDevicesOptions,
373 ) -> Result<Vec<(DeviceID, Result<OwnedFd, UsbError>)>, Error> {
374 let parent_window = parent_window.map(|i| i.to_string()).unwrap_or_default();
375 let acquire_devices: Vec<(DeviceID, AcquireDevice)> = devices
376 .iter()
377 .map(|dev| {
378 let device = AcquireDevice { writable: dev.1 };
379 (dev.id().clone(), device)
380 })
381 .collect();
382 let request = self
383 .0
384 .empty_request(
385 &options.handle_token,
386 "AcquireDevices",
387 &(&parent_window, &acquire_devices, &options),
388 )
389 .await?;
390 let mut devices: Vec<(DeviceID, Result<OwnedFd, UsbError>)> = vec![];
391 if request.response().is_ok() {
392 let path = request.path();
393 loop {
394 let (mut new_devices, finished) = self
395 .finish_acquire_devices(path, Default::default())
396 .await?;
397 devices.append(&mut new_devices);
398 if finished {
399 break;
400 }
401 }
402 }
403 Ok(devices)
404 }
405
406 /// Call on success of acquire_devices. This never need to be called
407 /// by client applications.
408 ///
409 /// # Specifications
410 ///
411 /// See also [`FinishAcquireDevices`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Usb.html#org-freedesktop-portal-usb-finishacquiredevices).
412 #[doc(alias = "FinishAcquireDevices")]
413 async fn finish_acquire_devices(
414 &self,
415 request_path: &ObjectPath<'_>,
416 options: FinishAcquireDevicesOptions,
417 ) -> Result<(Vec<(DeviceID, Result<OwnedFd, UsbError>)>, bool), Error> {
418 self.0
419 .call("FinishAcquireDevices", &(request_path, &options))
420 .await
421 .map(|result: (Vec<(DeviceID, AcquiredDevice)>, bool)| {
422 let finished = result.1;
423 (
424 result
425 .0
426 .into_iter()
427 .map(|item| (item.0, item.1.into()))
428 .collect::<Vec<_>>(),
429 finished,
430 )
431 })
432 }
433
434 /// Release devices
435 ///
436 /// Release all the devices whose ID is specified in `devices`.
437 ///
438 /// # Specifications
439 ///
440 /// See also [`ReleaseDevices`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Usb.html#org-freedesktop-portal-usb-releasedevices).
441 #[doc(alias = "ReleaseDevices")]
442 pub async fn release_devices(
443 &self,
444 devices: &[&DeviceID],
445 options: ReleaseDevicesOptions,
446 ) -> Result<(), Error> {
447 self.0.call("ReleaseDevices", &(devices, &options)).await
448 }
449
450 /// Signal emitted on a device event
451 ///
452 /// Will emit [`UsbDeviceEvent`].
453 ///
454 /// # Specifications
455 ///
456 /// See also [`DeviceEvents`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Usb.html#org-freedesktop-portal-usb-deviceevents).
457 #[doc(alias = "DeviceEvents")]
458 pub async fn receive_device_events(
459 &self,
460 ) -> Result<impl Stream<Item = UsbDeviceEvent> + use<>, Error> {
461 self.0.signal("DeviceEvents").await
462 }
463 }
464
465 impl crate::Sealed for UsbProxy {}
466 impl SessionPortal for UsbProxy {}