Debian Codegraph @

src/desktop/inhibit.rs

raw
1 //! # Examples
2 //!
3 //! How to inhibit logout/user switch
4 //!
5 //! ```rust,no_run
6 //! use std::{thread, time};
7 //!
8 //! use ashpd::desktop::inhibit::{InhibitFlags, InhibitOptions, InhibitProxy, SessionState};
9 //! use futures_util::StreamExt;
10 //!
11 //! async fn run() -> ashpd::Result<()> {
12 //! let proxy = InhibitProxy::new().await?;
13 //! let session = proxy.create_monitor(None, Default::default()).await?;
14 //!
15 //! let state = proxy.receive_state_changed().await?.next().await.unwrap();
16 //! match state.session_state() {
17 //! SessionState::Running => (),
18 //! SessionState::QueryEnd => {
19 //! proxy
20 //! .inhibit(
21 //! None,
22 //! InhibitFlags::Logout | InhibitFlags::UserSwitch,
23 //! InhibitOptions::default()
24 //! .set_reason("please save the opened project first"),
25 //! )
26 //! .await?;
27 //! thread::sleep(time::Duration::from_secs(1));
28 //! proxy.query_end_response(&session).await?;
29 //! }
30 //! SessionState::Ending => {
31 //! println!("ending the session");
32 //! }
33 //! }
34 //! Ok(())
35 //! }
36 //! ```
37
38 use enumflags2::{BitFlags, bitflags};
39 use futures_util::Stream;
40 use serde::{Deserialize, Serialize};
41 use serde_repr::{Deserialize_repr, Serialize_repr};
42 use zbus::zvariant::{
43 ObjectPath, Optional, OwnedObjectPath, Type,
44 as_value::{self, optional},
45 };
46
47 use super::{HandleToken, Request, Session, session::SessionPortal};
48 use crate::{Error, WindowIdentifier, desktop::session::CreateSessionResponse, proxy::Proxy};
49
50 #[derive(Serialize, Type, Debug, Default)]
51 /// Specified options for a [`InhibitProxy::create_monitor`] request.
52 #[zvariant(signature = "dict")]
53 pub struct CreateMonitorOptions {
54 #[serde(with = "as_value")]
55 handle_token: HandleToken,
56 #[serde(with = "as_value")]
57 session_handle_token: HandleToken,
58 }
59
60 #[derive(Serialize, Type, Debug, Default)]
61 #[zvariant(signature = "dict")]
62 /// Specified options for a [`InhibitProxy::inhibit`] request.
63 pub struct InhibitOptions {
64 #[serde(with = "as_value")]
65 handle_token: HandleToken,
66 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
67 reason: Option<String>,
68 }
69
70 impl InhibitOptions {
71 /// Sets a user-visible reason for the request.
72 #[must_use]
73 pub fn set_reason<'a>(mut self, reason: impl Into<Option<&'a str>>) -> Self {
74 self.reason = reason.into().map(ToOwned::to_owned);
75 self
76 }
77 }
78
79 #[bitflags]
80 #[derive(Serialize_repr, PartialEq, Eq, Debug, Clone, Copy, Type)]
81 #[repr(u32)]
82 #[doc(alias = "XdpInhibitFlags")]
83 /// The actions to inhibit that can end the user's session
84 pub enum InhibitFlags {
85 #[doc(alias = "XDP_INHIBIT_FLAG_LOGOUT")]
86 /// Logout.
87 Logout,
88 #[doc(alias = "XDP_INHIBIT_FLAG_USER_SWITCH")]
89 /// User switch.
90 UserSwitch,
91 #[doc(alias = "XDP_INHIBIT_FLAG_SUSPEND")]
92 /// Suspend.
93 Suspend,
94 #[doc(alias = "XDP_INHIBIT_FLAG_IDLE")]
95 /// Idle.
96 Idle,
97 }
98
99 #[derive(Debug, Deserialize, Type)]
100 #[zvariant(signature = "dict")]
101 #[serde(rename_all = "kebab-case")]
102 struct State {
103 #[serde(with = "as_value")]
104 screensaver_active: bool,
105 #[serde(with = "as_value")]
106 session_state: SessionState,
107 }
108
109 #[derive(Debug, Deserialize, Type)]
110 /// A response received when the `state_changed` signal is received.
111 pub struct InhibitState(OwnedObjectPath, State);
112
113 impl InhibitState {
114 /// The session triggered the state change
115 pub fn session_handle(&self) -> ObjectPath<'_> {
116 self.0.as_ref()
117 }
118
119 /// Whether screensaver is active or not.
120 pub fn screensaver_active(&self) -> bool {
121 self.1.screensaver_active
122 }
123
124 /// The session state.
125 pub fn session_state(&self) -> SessionState {
126 self.1.session_state
127 }
128 }
129
130 #[cfg_attr(feature = "glib", derive(glib::Enum))]
131 #[cfg_attr(feature = "glib", enum_type(name = "AshpdSessionState"))]
132 #[derive(Serialize_repr, Deserialize_repr, PartialEq, Eq, Debug, Clone, Copy, Type)]
133 #[doc(alias = "XdpLoginSessionState")]
134 #[repr(u32)]
135 /// The current state of the user's session.
136 pub enum SessionState {
137 #[doc(alias = "XDP_LOGIN_SESSION_RUNNING")]
138 /// Running.
139 Running = 1,
140 #[doc(alias = "XDP_LOGIN_SESSION_QUERY_END")]
141 /// The user asked to end the session e.g logout.
142 QueryEnd = 2,
143 #[doc(alias = "XDP_LOGIN_SESSION_ENDING")]
144 /// The session is ending.
145 Ending = 3,
146 }
147
148 /// The interface lets sandboxed applications inhibit the user session from
149 /// ending, suspending, idling or getting switched away.
150 ///
151 /// Wrapper of the DBus interface: [`org.freedesktop.portal.Inhibit`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Inhibit.html).
152 #[derive(Debug)]
153 #[doc(alias = "org.freedesktop.portal.Inhibit")]
154 pub struct InhibitProxy(Proxy<'static>);
155
156 impl InhibitProxy {
157 /// Create a new instance of [`InhibitProxy`].
158 pub async fn new() -> Result<Self, Error> {
159 let proxy = Proxy::new_desktop("org.freedesktop.portal.Inhibit").await?;
160 Ok(Self(proxy))
161 }
162
163 /// Create a new instance of [`InhibitProxy`].
164 pub async fn with_connection(connection: zbus::Connection) -> Result<Self, Error> {
165 let proxy =
166 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.Inhibit")
167 .await?;
168 Ok(Self(proxy))
169 }
170
171 /// Returns the version of the portal interface.
172 pub fn version(&self) -> u32 {
173 self.0.version()
174 }
175
176 /// Creates a monitoring session.
177 /// While this session is active, the caller will receive `state_changed`
178 /// signals with updates on the session state.
179 ///
180 /// # Arguments
181 ///
182 /// * `identifier` - The application window identifier.
183 ///
184 /// # Specifications
185 ///
186 /// See also [`CreateMonitor`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Inhibit.html#org-freedesktop-portal-inhibit-createmonitor).
187 #[doc(alias = "CreateMonitor")]
188 #[doc(alias = "xdp_portal_session_monitor_start")]
189 pub async fn create_monitor(
190 &self,
191 identifier: Option<&WindowIdentifier>,
192 options: CreateMonitorOptions,
193 ) -> Result<Session<Self>, Error> {
194 let identifier = Optional::from(identifier);
195 let body = &(identifier, &options);
196 let (monitor, proxy) = futures_util::try_join!(
197 self.0
198 .request::<CreateSessionResponse>(&options.handle_token, "CreateMonitor", body),
199 Session::from_unique_name(self.0.connection().clone(), &options.session_handle_token),
200 )?;
201 assert_eq!(proxy.path(), &monitor.response()?.session_handle.as_ref());
202 Ok(proxy)
203 }
204
205 /// Inhibits a session status changes.
206 ///
207 /// # Arguments
208 ///
209 /// * `identifier` - The application window identifier.
210 /// * `flags` - The flags determine what changes are inhibited.
211 ///
212 /// # Specifications
213 ///
214 /// See also [`Inhibit`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Inhibit.html#org-freedesktop-portal-inhibit-inhibit).
215 #[doc(alias = "Inhibit")]
216 #[doc(alias = "xdp_portal_session_inhibit")]
217 pub async fn inhibit(
218 &self,
219 identifier: Option<&WindowIdentifier>,
220 flags: BitFlags<InhibitFlags>,
221 options: InhibitOptions,
222 ) -> Result<Request<()>, Error> {
223 let identifier = Optional::from(identifier);
224 self.0
225 .empty_request(
226 &options.handle_token,
227 "Inhibit",
228 &(identifier, flags, &options),
229 )
230 .await
231 }
232
233 /// Signal emitted when the session state changes.
234 ///
235 /// # Specifications
236 ///
237 /// See also [`StateChanged`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Inhibit.html#org-freedesktop-portal-inhibit-statechanged).
238 #[doc(alias = "StateChanged")]
239 #[doc(alias = "XdpPortal::session-state-changed")]
240 pub async fn receive_state_changed(
241 &self,
242 ) -> Result<impl Stream<Item = InhibitState> + use<>, Error> {
243 self.0.signal("StateChanged").await
244 }
245
246 /// Acknowledges that the caller received the "state_changed" signal.
247 /// This method should be called within one second after receiving a
248 /// [`receive_state_changed()`][`InhibitProxy::receive_state_changed`]
249 /// signal with the [`SessionState::QueryEnd`] state.
250 ///
251 /// # Arguments
252 ///
253 /// * `session` - A [`Session`], created with
254 /// [`create_monitor()`][`InhibitProxy::create_monitor`].
255 ///
256 /// # Specifications
257 ///
258 /// See also [`QueryEndResponse`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Inhibit.html#org-freedesktop-portal-inhibit-queryendresponse).
259 #[doc(alias = "QueryEndResponse")]
260 #[doc(alias = "xdp_portal_session_monitor_query_end_response")]
261 pub async fn query_end_response(&self, session: &Session<Self>) -> Result<(), Error> {
262 self.0.call("QueryEndResponse", &(session)).await
263 }
264 }
265
266 impl std::ops::Deref for InhibitProxy {
267 type Target = zbus::Proxy<'static>;
268
269 fn deref(&self) -> &Self::Target {
270 &self.0
271 }
272 }
273
274 impl crate::Sealed for InhibitProxy {}
275 impl SessionPortal for InhibitProxy {}