ashpd/backend/
usb.rs

1use std::sync::Arc;
2
3use async_trait::async_trait;
4
5use crate::{
6    backend::{
7        request::{Request, RequestImpl},
8        MaybeAppID, MaybeWindowIdentifier, Result,
9    },
10    desktop::{request::Response, usb::UsbDevice, HandleToken},
11    zvariant::{DeserializeDict, OwnedObjectPath, SerializeDict, Type},
12    AppID, WindowIdentifierType,
13};
14
15#[derive(Debug, DeserializeDict, Type)]
16#[zvariant(signature = "dict")]
17pub struct AcquireDevicesOptions {}
18
19#[derive(Debug, SerializeDict, DeserializeDict, Type)]
20#[zvariant(signature = "dict")]
21pub struct AccessOptions {
22    writable: Option<bool>,
23}
24
25impl AccessOptions {
26    pub fn new(is_writable: bool) -> Self {
27        Self {
28            writable: Some(is_writable),
29        }
30    }
31
32    pub fn is_writable(&self) -> Option<bool> {
33        self.writable
34    }
35}
36
37#[async_trait]
38pub trait UsbImpl: RequestImpl {
39    async fn acquire_devices(
40        &self,
41        token: HandleToken,
42        window_identifier: Option<WindowIdentifierType>,
43        app_id: Option<AppID>,
44        devices: Vec<(String, UsbDevice, AccessOptions)>,
45        options: AcquireDevicesOptions,
46    ) -> Result<Vec<(String, AccessOptions)>>;
47}
48
49pub(crate) struct UsbInterface {
50    imp: Arc<dyn UsbImpl>,
51    cnx: zbus::Connection,
52}
53
54impl UsbInterface {
55    pub fn new(imp: Arc<dyn UsbImpl>, cnx: zbus::Connection) -> Self {
56        Self { imp, cnx }
57    }
58}
59
60#[zbus::interface(name = "org.freedesktop.impl.portal.Usb")]
61impl UsbInterface {
62    #[zbus(property(emits_changed_signal = "const"), name = "version")]
63    fn version(&self) -> u32 {
64        1
65    }
66
67    #[zbus(name = "AcquireDevices")]
68    #[zbus(out_args("response", "results"))]
69    async fn acquire_devices(
70        &self,
71        handle: OwnedObjectPath,
72        window_identifier: MaybeWindowIdentifier,
73        app_id: MaybeAppID,
74        devices: Vec<(String, UsbDevice, AccessOptions)>,
75        options: AcquireDevicesOptions,
76    ) -> Result<Response<Vec<(String, AccessOptions)>>> {
77        let imp = Arc::clone(&self.imp);
78
79        Request::spawn(
80            "Usb::AcquireDevices",
81            &self.cnx,
82            handle.clone(),
83            Arc::clone(&self.imp),
84            async move {
85                imp.acquire_devices(
86                    HandleToken::try_from(&handle).unwrap(),
87                    window_identifier.inner(),
88                    app_id.inner(),
89                    devices,
90                    options,
91                )
92                .await
93            },
94        )
95        .await
96    }
97}