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
use std::{fmt::Debug, future::ready, ops::Deref, sync::OnceLock};

use futures_util::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use zbus::zvariant::{ObjectPath, OwnedValue, Type};
#[cfg(feature = "tracing")]
use zbus::Message;

use crate::{
    desktop::{HandleToken, Request},
    Error, PortalError,
};

pub(crate) const DESKTOP_DESTINATION: &str = "org.freedesktop.portal.Desktop";
pub(crate) const DESKTOP_PATH: &str = "/org/freedesktop/portal/desktop";

pub(crate) const DOCUMENTS_DESTINATION: &str = "org.freedesktop.portal.Documents";
pub(crate) const DOCUMENTS_PATH: &str = "/org/freedesktop/portal/documents";

pub(crate) const FLATPAK_DESTINATION: &str = "org.freedesktop.portal.Flatpak";
pub(crate) const FLATPAK_PATH: &str = "/org/freedesktop/portal/Flatpak";

pub(crate) const FLATPAK_DEVELOPMENT_DESTINATION: &str = "org.freedesktop.Flatpak";
pub(crate) const FLATPAK_DEVELOPMENT_PATH: &str = "/org/freedesktop/Flatpak/Development";

static SESSION: OnceLock<zbus::Connection> = OnceLock::new();

#[derive(Debug)]
pub struct Proxy<'a> {
    inner: zbus::Proxy<'a>,
    version: u32,
}

impl<'a> Proxy<'a> {
    pub(crate) async fn connection() -> zbus::Result<zbus::Connection> {
        if let Some(cnx) = SESSION.get() {
            Ok(cnx.clone())
        } else {
            let cnx = zbus::Connection::session().await?;
            // during `await` another task may have initialized the cell
            Ok(SESSION.get_or_init(|| cnx).clone())
        }
    }

    pub async fn unique_name(
        prefix: &str,
        handle_token: &HandleToken,
    ) -> Result<ObjectPath<'static>, Error> {
        let connection = Self::connection().await?;
        let unique_name = connection.unique_name().unwrap();
        let unique_identifier = unique_name.trim_start_matches(':').replace('.', "_");
        ObjectPath::try_from(format!("{prefix}/{unique_identifier}/{handle_token}"))
            .map_err(From::from)
    }

    pub async fn new<P>(
        interface: &'a str,
        path: P,
        destination: &'a str,
    ) -> Result<Proxy<'a>, Error>
    where
        P: TryInto<ObjectPath<'a>>,
        P::Error: Into<zbus::Error>,
    {
        let connection = Self::connection().await?;
        let inner: zbus::Proxy = zbus::ProxyBuilder::new(&connection)
            .interface(interface)?
            .path(path)?
            .destination(destination)?
            .build()
            .await?;
        let version = match inner.get_property::<u32>("version").await {
            Ok(v) => Ok(v),
            Err(e) => {
                // We forward the `PortalNotFound` error as this the perfect time to do so.
                // As all the interfaces used inside the crate have a `version` property making
                // getting the property would only fail if there is no portal implementation
                // found.
                let err = crate::Error::from(e);
                match err {
                    crate::Error::PortalNotFound(_) => Err(err),
                    _ => Ok(1),
                }
            }
        }?;
        Ok(Self { inner, version })
    }

    pub async fn new_desktop_with_path<P>(interface: &'a str, path: P) -> Result<Proxy<'a>, Error>
    where
        P: TryInto<ObjectPath<'a>>,
        P::Error: Into<zbus::Error>,
    {
        Self::new(interface, path, DESKTOP_DESTINATION).await
    }

    pub async fn new_desktop(interface: &'a str) -> Result<Proxy<'a>, Error> {
        Self::new(interface, DESKTOP_PATH, DESKTOP_DESTINATION).await
    }

    pub async fn new_documents(interface: &'a str) -> Result<Proxy<'a>, Error> {
        Self::new(interface, DOCUMENTS_PATH, DOCUMENTS_DESTINATION).await
    }

    pub async fn new_flatpak(interface: &'a str) -> Result<Proxy<'a>, Error> {
        Self::new(interface, FLATPAK_PATH, FLATPAK_DESTINATION).await
    }

    pub async fn new_flatpak_with_path<P>(interface: &'a str, path: P) -> Result<Proxy<'a>, Error>
    where
        P: TryInto<ObjectPath<'a>>,
        P::Error: Into<zbus::Error>,
    {
        Self::new(interface, path, FLATPAK_DESTINATION).await
    }

    pub async fn new_flatpak_development(interface: &'a str) -> Result<Proxy<'a>, Error> {
        Self::new(
            interface,
            FLATPAK_DEVELOPMENT_PATH,
            FLATPAK_DEVELOPMENT_DESTINATION,
        )
        .await
    }

    pub async fn request<T>(
        &self,
        handle_token: &HandleToken,
        method_name: &'static str,
        body: impl Serialize + Type + Debug,
    ) -> Result<Request<T>, Error>
    where
        T: for<'de> Deserialize<'de> + Type + Debug,
    {
        let mut request = Request::from_unique_name(handle_token).await?;
        futures_util::try_join!(request.prepare_response(), async {
            self.call_method(method_name, &body)
                .await
                .map_err(From::from)
        })?;
        Ok(request)
    }

    pub(crate) async fn empty_request(
        &self,
        handle_token: &HandleToken,
        method_name: &'static str,
        body: impl Serialize + Type + Debug,
    ) -> Result<Request<()>, Error> {
        self.request(handle_token, method_name, body).await
    }

    /// Returns the version of the interface
    pub fn version(&self) -> u32 {
        self.version
    }

    pub(crate) async fn call<R>(
        &self,
        method_name: &'static str,
        body: impl Serialize + Type + Debug,
    ) -> Result<R, Error>
    where
        R: for<'de> Deserialize<'de> + Type,
    {
        #[cfg(feature = "tracing")]
        {
            tracing::info!("Calling method {}:{}", self.interface(), method_name);
            tracing::debug!("With body {:#?}", body);
        }
        let msg = self
            .call_method(method_name, &body)
            .await
            .map_err::<PortalError, _>(From::from)?;
        let reply = msg.body().deserialize::<R>()?;

        Ok(reply)
    }

    pub(crate) async fn call_versioned<R>(
        &self,
        method_name: &'static str,
        body: impl Serialize + Type + Debug,
        req_version: u32,
    ) -> Result<R, Error>
    where
        R: for<'de> Deserialize<'de> + Type,
    {
        let version = self.version();
        if version >= req_version {
            self.call::<R>(method_name, body).await
        } else {
            Err(Error::RequiresVersion(req_version, version))
        }
    }

    pub async fn property<T>(&self, property_name: &'static str) -> Result<T, Error>
    where
        T: TryFrom<OwnedValue>,
        zbus::Error: From<<T as TryFrom<OwnedValue>>::Error>,
    {
        self.inner
            .get_property::<T>(property_name)
            .await
            .map_err(From::from)
    }

    pub(crate) async fn property_versioned<T>(
        &self,
        property_name: &'static str,
        req_version: u32,
    ) -> Result<T, Error>
    where
        T: TryFrom<OwnedValue>,
        zbus::Error: From<<T as TryFrom<OwnedValue>>::Error>,
    {
        let version = self.version();
        if version >= req_version {
            self.property::<T>(property_name).await
        } else {
            Err(Error::RequiresVersion(req_version, version))
        }
    }

    pub(crate) async fn signal_with_args<I>(
        &self,
        name: &'static str,
        args: &[(u8, &str)],
    ) -> Result<impl Stream<Item = I>, Error>
    where
        I: for<'de> Deserialize<'de> + Type + Debug,
    {
        Ok(self
            .inner
            .receive_signal_with_args(name, args)
            .await?
            .filter_map({
                #[cfg(not(feature = "tracing"))]
                {
                    move |msg| ready(msg.body().deserialize().ok())
                }
                #[cfg(feature = "tracing")]
                {
                    let ifc = self.interface().to_owned();
                    move |msg| ready(trace_body(name, &ifc, msg))
                }
            }))
    }

    pub(crate) async fn signal<I>(&self, name: &'static str) -> Result<impl Stream<Item = I>, Error>
    where
        I: for<'de> Deserialize<'de> + Type + Debug,
    {
        Ok(self.inner.receive_signal(name).await?.filter_map({
            #[cfg(not(feature = "tracing"))]
            {
                move |msg| ready(msg.body().deserialize().ok())
            }
            #[cfg(feature = "tracing")]
            {
                let ifc = self.interface().to_owned();
                move |msg| ready(trace_body(name, &ifc, msg))
            }
        }))
    }
}

#[cfg(feature = "tracing")]
fn trace_body<I>(name: &'static str, ifc: &str, msg: Message) -> Option<I>
where
    I: for<'de> Deserialize<'de> + Type + Debug,
{
    tracing::info!("Received signal '{name}' on '{ifc}'");
    match msg.body().deserialize() {
        Ok(body) => {
            tracing::debug!("With body {body:#?}");
            Some(body)
        }
        Err(e) => {
            tracing::warn!("Error obtaining body: {e:#?}");
            None
        }
    }
}

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

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