Debian Codegraph @

src/desktop/session.rs

raw
1 use std::{collections::HashMap, fmt::Debug, marker::PhantomData};
2
3 use futures_util::Stream;
4 use serde::{Deserialize, Serialize, Serializer};
5 use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Type, as_value};
6
7 use crate::{Error, desktop::HandleToken, proxy::Proxy};
8
9 /// Shared by all portal interfaces that involve long lived sessions.
10 ///
11 /// When a method that creates a session is called, if successful, the reply
12 /// will include a session handle (i.e. object path) for a Session object, which
13 /// will stay alive for the duration of the session.
14 ///
15 /// The duration of the session is defined by the interface that creates it.
16 /// For convenience, the interface contains a method [`Session::close`],
17 /// and a signal [`Session::receive_closed`]. Whether it is allowed to
18 /// directly call [`Session::close`] depends on the interface.
19 ///
20 /// Wrapper of the DBus interface: [`org.freedesktop.portal.Session`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Session.html).
21 #[derive(Type)]
22 #[doc(alias = "org.freedesktop.portal.Session")]
23 #[zvariant(signature = "o")]
24 pub struct Session<T>(Proxy<'static>, PhantomData<T>)
25 where
26 T: SessionPortal;
27
28 impl<T> Session<T>
29 where
30 T: SessionPortal,
31 {
32 /// Create a new instance of [`Session`].
33 ///
34 /// **Note** A [`Session`] is not supposed to be created manually.
35 pub(crate) async fn with_connection<P>(
36 connection: zbus::Connection,
37 path: P,
38 ) -> Result<Self, Error>
39 where
40 P: TryInto<ObjectPath<'static>>,
41 P::Error: Into<zbus::Error>,
42 {
43 let proxy =
44 Proxy::new_desktop_with_path(connection, "org.freedesktop.portal.Session", path)
45 .await?;
46 Ok(Self(proxy, PhantomData))
47 }
48
49 pub(crate) async fn from_unique_name(
50 connection: zbus::Connection,
51 handle_token: &HandleToken,
52 ) -> Result<Self, crate::Error> {
53 let path = Proxy::unique_name(
54 &connection,
55 "/org/freedesktop/portal/desktop/session",
56 handle_token,
57 )
58 .await?;
59 #[cfg(feature = "tracing")]
60 tracing::info!("Creating a org.freedesktop.portal.Session {}", path);
61 Self::with_connection(connection, path).await
62 }
63
64 /// Emitted when a session is closed.
65 ///
66 /// # Specifications
67 ///
68 /// See also [`Closed`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Session.html#org-freedesktop-portal-session-closed).
69 #[doc(alias = "Closed")]
70 pub async fn receive_closed(
71 &self,
72 ) -> Result<impl Stream<Item = HashMap<String, OwnedValue>>, Error> {
73 self.0.signal("Closed").await
74 }
75
76 /// Closes the portal session to which this object refers and ends all
77 /// related user interaction (dialogs, etc).
78 ///
79 /// # Specifications
80 ///
81 /// See also [`Close`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Session.html#org-freedesktop-portal-session-close).
82 #[doc(alias = "Close")]
83 pub async fn close(&self) -> Result<(), Error> {
84 self.0.call("Close", &()).await
85 }
86
87 pub(crate) fn path(&self) -> &ObjectPath<'_> {
88 self.0.path()
89 }
90 }
91
92 impl<T> Serialize for Session<T>
93 where
94 T: SessionPortal,
95 {
96 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
97 where
98 S: Serializer,
99 {
100 ObjectPath::serialize(self.path(), serializer)
101 }
102 }
103
104 impl<T> Debug for Session<T>
105 where
106 T: SessionPortal,
107 {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 f.debug_tuple("Session")
110 .field(&self.path().as_str())
111 .finish()
112 }
113 }
114
115 /// Portals that have a long-lived interaction
116 pub trait SessionPortal: crate::Sealed {}
117
118 /// A response to a `create_session` request.
119 #[derive(Type, Debug)]
120 #[zvariant(signature = "dict")]
121 pub(crate) struct CreateSessionResponse {
122 pub(crate) session_handle: OwnedObjectPath,
123 }
124
125 // Context: Various portal were expected to actually return an OwnedObjectPath
126 // but unfortunately this wasn't the case when the portals were implemented in
127 // xdp. Fixing that would be an API break as well...
128 // See <https://github.com/flatpak/xdg-desktop-portal/pull/609>
129 // The Location, ScreenCast, Remote Desktop, Global Shortcuts and Inhibit
130 // portals `CreateSession` calls are all affected.
131 //
132 // So in order to be future proof, we try to deserialize the `session_handle`
133 // key as a string and fallback to an object path in case the situation gets
134 // resolved in the future.
135 impl<'de> Deserialize<'de> for CreateSessionResponse {
136 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
137 where
138 D: serde::Deserializer<'de>,
139 {
140 let map: HashMap<String, OwnedValue> = HashMap::deserialize(deserializer)?;
141 let session_handle = map.get("session_handle").ok_or_else(|| {
142 serde::de::Error::custom(
143 "CreateSessionResponse failed to deserialize. Couldn't find a session_handle",
144 )
145 })?;
146
147 let path = if let Ok(object_path_str) = session_handle.downcast_ref::<&str>() {
148 ObjectPath::try_from(object_path_str).unwrap()
149 } else if let Ok(object_path) = session_handle.downcast_ref::<ObjectPath<'_>>() {
150 object_path
151 } else {
152 return Err(serde::de::Error::custom(
153 "Wrong session_handle type. Expected `s` or `o`.",
154 ));
155 };
156
157 Ok(Self {
158 session_handle: path.into(),
159 })
160 }
161 }
162
163 #[derive(Serialize, Deserialize, Type, Debug, Default)]
164 #[zvariant(signature = "dict")]
165 /// Specified options for creating a session.
166 pub struct CreateSessionOptions {
167 #[serde(default, with = "as_value", skip_deserializing)]
168 pub(crate) handle_token: HandleToken,
169 #[serde(default, with = "as_value", skip_deserializing)]
170 pub(crate) session_handle_token: HandleToken,
171 }