Debian Codegraph @

src/proxy.rs

raw
1 #![allow(missing_docs)]
2 use std::{fmt::Debug, future::ready, ops::Deref, sync::OnceLock};
3
4 use futures_util::{Stream, StreamExt};
5 use serde::{Deserialize, Serialize};
6 #[cfg(feature = "tracing")]
7 use zbus::Message;
8 use zbus::zvariant::{ObjectPath, OwnedValue, Type};
9
10 use crate::{
11 Error, PortalError,
12 desktop::{HandleToken, Request},
13 };
14
15 pub(crate) const DESKTOP_DESTINATION: &str = "org.freedesktop.portal.Desktop";
16 pub(crate) const DESKTOP_PATH: &str = "/org/freedesktop/portal/desktop";
17
18 pub(crate) const DOCUMENTS_DESTINATION: &str = "org.freedesktop.portal.Documents";
19 pub(crate) const DOCUMENTS_PATH: &str = "/org/freedesktop/portal/documents";
20
21 pub(crate) const FLATPAK_DESTINATION: &str = "org.freedesktop.portal.Flatpak";
22 pub(crate) const FLATPAK_PATH: &str = "/org/freedesktop/portal/Flatpak";
23
24 pub(crate) const FLATPAK_DEVELOPMENT_DESTINATION: &str = "org.freedesktop.Flatpak";
25 pub(crate) const FLATPAK_DEVELOPMENT_PATH: &str = "/org/freedesktop/Flatpak/Development";
26
27 static SESSION: OnceLock<zbus::Connection> = OnceLock::new();
28
29 #[derive(Debug, Clone)]
30 pub struct Proxy<'a> {
31 inner: zbus::Proxy<'a>,
32 version: u32,
33 }
34
35 impl<'a> Proxy<'a> {
36 pub(crate) async fn connection() -> zbus::Result<zbus::Connection> {
37 if let Some(cnx) = SESSION.get() {
38 Ok(cnx.clone())
39 } else {
40 let cnx = zbus::Connection::session().await?;
41 // during `await` another task may have initialized the cell
42 Ok(SESSION.get_or_init(|| cnx).clone())
43 }
44 }
45
46 pub async fn unique_name(
47 connection: &zbus::Connection,
48 prefix: &str,
49 handle_token: &HandleToken,
50 ) -> Result<ObjectPath<'static>, Error> {
51 let unique_name = connection.unique_name().unwrap();
52 let unique_identifier = unique_name.trim_start_matches(':').replace('.', "_");
53 ObjectPath::try_from(format!("{prefix}/{unique_identifier}/{handle_token}"))
54 .map_err(From::from)
55 }
56
57 pub async fn new<P>(
58 interface: &'a str,
59 path: P,
60 destination: &'a str,
61 ) -> Result<Proxy<'a>, Error>
62 where
63 P: TryInto<ObjectPath<'a>>,
64 P::Error: Into<zbus::Error>,
65 {
66 let connection = Self::connection().await?;
67 Self::with_connection(connection, interface, path, destination).await
68 }
69
70 pub async fn with_connection<P>(
71 connection: zbus::Connection,
72 interface: &'a str,
73 path: P,
74 destination: &'a str,
75 ) -> Result<Proxy<'a>, Error>
76 where
77 P: TryInto<ObjectPath<'a>>,
78 P::Error: Into<zbus::Error>,
79 {
80 let inner: zbus::Proxy = zbus::proxy::Builder::new(&connection)
81 .interface(interface)?
82 .path(path)?
83 .destination(destination)?
84 .build()
85 .await?;
86
87 let version = match inner
88 .get_property::<u32>("version")
89 .await
90 .map_err(zbus::fdo::Error::from)
91 {
92 Ok(v) => Ok(v),
93 Err(zbus::fdo::Error::InvalidArgs(details)) => {
94 if details.contains(interface) {
95 Err(crate::Error::PortalNotFound(
96 // We are sure it is a valid interface name, should fix the type system
97 // here
98 zbus::names::OwnedInterfaceName::try_from(interface).unwrap(),
99 ))
100 } else {
101 Ok(1)
102 }
103 }
104 _ => Ok(1),
105 }?;
106 Ok(Self { inner, version })
107 }
108
109 pub async fn new_desktop_with_path<P>(
110 connection: zbus::Connection,
111 interface: &'a str,
112 path: P,
113 ) -> Result<Proxy<'a>, Error>
114 where
115 P: TryInto<ObjectPath<'a>>,
116 P::Error: Into<zbus::Error>,
117 {
118 Self::with_connection(connection, interface, path, DESKTOP_DESTINATION).await
119 }
120
121 pub async fn new_desktop(interface: &'a str) -> Result<Proxy<'a>, Error> {
122 Self::new(interface, DESKTOP_PATH, DESKTOP_DESTINATION).await
123 }
124
125 pub async fn new_desktop_with_connection(
126 connection: zbus::Connection,
127 interface: &'a str,
128 ) -> Result<Proxy<'a>, Error> {
129 Self::with_connection(connection, interface, DESKTOP_PATH, DESKTOP_DESTINATION).await
130 }
131
132 pub async fn new_documents(interface: &'a str) -> Result<Proxy<'a>, Error> {
133 Self::new(interface, DOCUMENTS_PATH, DOCUMENTS_DESTINATION).await
134 }
135
136 pub async fn new_documents_with_connection(
137 connection: zbus::Connection,
138 interface: &'a str,
139 ) -> Result<Proxy<'a>, Error> {
140 Self::with_connection(connection, interface, DOCUMENTS_PATH, DOCUMENTS_DESTINATION).await
141 }
142
143 pub async fn new_flatpak(interface: &'a str) -> Result<Proxy<'a>, Error> {
144 Self::new(interface, FLATPAK_PATH, FLATPAK_DESTINATION).await
145 }
146
147 pub async fn new_flatpak_with_connection(
148 connection: zbus::Connection,
149 interface: &'a str,
150 ) -> Result<Proxy<'a>, Error> {
151 Self::with_connection(connection, interface, FLATPAK_PATH, FLATPAK_DESTINATION).await
152 }
153
154 pub async fn new_flatpak_with_path<P>(
155 connection: zbus::Connection,
156 interface: &'a str,
157 path: P,
158 ) -> Result<Proxy<'a>, Error>
159 where
160 P: TryInto<ObjectPath<'a>>,
161 P::Error: Into<zbus::Error>,
162 {
163 Self::with_connection(connection, interface, path, FLATPAK_DESTINATION).await
164 }
165
166 pub async fn new_flatpak_development(interface: &'a str) -> Result<Proxy<'a>, Error> {
167 Self::new(
168 interface,
169 FLATPAK_DEVELOPMENT_PATH,
170 FLATPAK_DEVELOPMENT_DESTINATION,
171 )
172 .await
173 }
174
175 pub async fn new_flatpak_development_with_connection(
176 connection: zbus::Connection,
177 interface: &'a str,
178 ) -> Result<Proxy<'a>, Error> {
179 Self::with_connection(
180 connection,
181 interface,
182 FLATPAK_DEVELOPMENT_PATH,
183 FLATPAK_DEVELOPMENT_DESTINATION,
184 )
185 .await
186 }
187
188 pub async fn request_versioned<T>(
189 &self,
190 handle_token: &HandleToken,
191 method_name: &'static str,
192 body: impl Serialize + Type + Debug,
193 req_version: u32,
194 ) -> Result<Request<T>, Error>
195 where
196 T: for<'de> Deserialize<'de> + Type + Debug,
197 {
198 let version = self.version();
199 if version >= req_version {
200 self.request(handle_token, method_name, body).await
201 } else {
202 Err(Error::RequiresVersion(req_version, version))
203 }
204 }
205
206 pub async fn request<T>(
207 &self,
208 handle_token: &HandleToken,
209 method_name: &'static str,
210 body: impl Serialize + Type + Debug,
211 ) -> Result<Request<T>, Error>
212 where
213 T: for<'de> Deserialize<'de> + Type + Debug,
214 {
215 let connection = self.inner.connection();
216 let mut request = Request::from_unique_name(connection.clone(), handle_token).await?;
217 futures_util::try_join!(request.prepare_response(), async {
218 self.call_method(method_name, &body)
219 .await
220 .map_err::<PortalError, _>(From::from)
221 .map_err(From::from)
222 })?;
223 Ok(request)
224 }
225
226 pub(crate) async fn empty_request(
227 &self,
228 handle_token: &HandleToken,
229 method_name: &'static str,
230 body: impl Serialize + Type + Debug,
231 ) -> Result<Request<()>, Error> {
232 self.request(handle_token, method_name, body).await
233 }
234
235 /// Returns the version of the interface
236 pub fn version(&self) -> u32 {
237 self.version
238 }
239
240 pub(crate) async fn call<R>(
241 &self,
242 method_name: &'static str,
243 body: impl Serialize + Type + Debug,
244 ) -> Result<R, Error>
245 where
246 R: for<'de> Deserialize<'de> + Type,
247 {
248 #[cfg(feature = "tracing")]
249 {
250 tracing::info!("Calling method {}:{}", self.interface(), method_name);
251 tracing::debug!("With body {:#?}", body);
252 }
253 let msg = self
254 .call_method(method_name, &body)
255 .await
256 .map_err::<PortalError, _>(From::from)?;
257 let reply = msg.body().deserialize::<R>()?;
258
259 Ok(reply)
260 }
261
262 pub(crate) async fn call_versioned<R>(
263 &self,
264 method_name: &'static str,
265 body: impl Serialize + Type + Debug,
266 req_version: u32,
267 ) -> Result<R, Error>
268 where
269 R: for<'de> Deserialize<'de> + Type,
270 {
271 let version = self.version();
272 if version >= req_version {
273 self.call::<R>(method_name, body).await
274 } else {
275 Err(Error::RequiresVersion(req_version, version))
276 }
277 }
278
279 pub async fn property<T>(&self, property_name: &'static str) -> Result<T, Error>
280 where
281 T: TryFrom<OwnedValue>,
282 zbus::Error: From<<T as TryFrom<OwnedValue>>::Error>,
283 {
284 self.inner
285 .get_property::<T>(property_name)
286 .await
287 .map_err(From::from)
288 }
289
290 pub(crate) async fn property_versioned<T>(
291 &self,
292 property_name: &'static str,
293 req_version: u32,
294 ) -> Result<T, Error>
295 where
296 T: TryFrom<OwnedValue>,
297 zbus::Error: From<<T as TryFrom<OwnedValue>>::Error>,
298 {
299 let version = self.version();
300 if version >= req_version {
301 self.property::<T>(property_name).await
302 } else {
303 Err(Error::RequiresVersion(req_version, version))
304 }
305 }
306
307 pub(crate) async fn signal_with_args<I>(
308 &self,
309 name: &'static str,
310 args: &[(u8, &str)],
311 ) -> Result<impl Stream<Item = I> + use<I>, Error>
312 where
313 I: for<'de> Deserialize<'de> + Type + Debug,
314 {
315 Ok(self
316 .inner
317 .receive_signal_with_args(name, args)
318 .await?
319 .filter_map({
320 #[cfg(not(feature = "tracing"))]
321 {
322 move |msg| ready(msg.body().deserialize().ok())
323 }
324 #[cfg(feature = "tracing")]
325 {
326 let ifc = self.interface().to_owned();
327 move |msg| ready(trace_body(name, &ifc, msg))
328 }
329 }))
330 }
331
332 pub(crate) async fn signal<I>(
333 &self,
334 name: &'static str,
335 ) -> Result<impl Stream<Item = I> + use<I>, Error>
336 where
337 I: for<'de> Deserialize<'de> + Type + Debug,
338 {
339 Ok(self.inner.receive_signal(name).await?.filter_map({
340 #[cfg(not(feature = "tracing"))]
341 {
342 move |msg| ready(msg.body().deserialize().ok())
343 }
344 #[cfg(feature = "tracing")]
345 {
346 let ifc = self.interface().to_owned();
347 move |msg| ready(trace_body(name, &ifc, msg))
348 }
349 }))
350 }
351 }
352
353 #[cfg(feature = "tracing")]
354 fn trace_body<I>(name: &'static str, ifc: &str, msg: Message) -> Option<I>
355 where
356 I: for<'de> Deserialize<'de> + Type + Debug,
357 {
358 tracing::info!("Received signal '{name}' on '{ifc}'");
359 match msg.body().deserialize() {
360 Ok(body) => {
361 tracing::debug!("With body {body:#?}");
362 Some(body)
363 }
364 Err(e) => {
365 tracing::warn!("Error obtaining body: {e:#?}");
366 None
367 }
368 }
369 }
370
371 impl<'a> Deref for Proxy<'a> {
372 type Target = zbus::Proxy<'a>;
373
374 fn deref(&self) -> &Self::Target {
375 &self.inner
376 }
377 }