Debian Codegraph @

src/desktop/screencast.rs

raw
1 //! Start a screencast session and get the PipeWire remote of it.
2 //!
3 //! # Examples
4 //!
5 //! How to create a screen cast session & start it.
6 //! The portal is currently useless without PipeWire & Rust support.
7 //!
8 //! ```rust,no_run
9 //! use ashpd::desktop::{
10 //! PersistMode,
11 //! screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType},
12 //! };
13 //!
14 //! async fn run() -> ashpd::Result<()> {
15 //! let proxy = Screencast::new().await?;
16 //! let session = proxy.create_session(Default::default()).await?;
17 //! proxy
18 //! .select_sources(
19 //! &session,
20 //! SelectSourcesOptions::default()
21 //! .set_cursor_mode(CursorMode::Metadata)
22 //! .set_sources(SourceType::Monitor | SourceType::Window)
23 //! .set_multiple(true)
24 //! .set_persist_mode(PersistMode::DoNot),
25 //! )
26 //! .await?;
27 //!
28 //! let response = proxy
29 //! .start(&session, None, Default::default())
30 //! .await?
31 //! .response()?;
32 //! response.streams().iter().for_each(|stream| {
33 //! println!("node id: {}", stream.pipe_wire_node_id());
34 //! println!("size: {:?}", stream.size());
35 //! println!("position: {:?}", stream.position());
36 //! });
37 //! Ok(())
38 //! }
39 //! ```
40 //! An example on how to connect with Pipewire can be found [here](https://github.com/bilelmoussaoui/ashpd/blob/main/examples/screen_cast_pw.rs), and with GStreamer [here](https://github.com/bilelmoussaoui/ashpd/blob/main/examples/screen_cast_gstreamer.rs).
41
42 use std::{fmt::Debug, os::fd::OwnedFd};
43
44 use enumflags2::{BitFlags, bitflags};
45 use serde::{Deserialize, Serialize};
46 use serde_repr::{Deserialize_repr, Serialize_repr};
47 use zbus::zvariant::{
48 self, Optional, OwnedValue, Type,
49 as_value::{self, optional},
50 };
51
52 use super::{HandleToken, PersistMode, Request, Session, session::SessionPortal};
53 use crate::{
54 Error, WindowIdentifier,
55 desktop::session::{CreateSessionOptions, CreateSessionResponse},
56 proxy::Proxy,
57 };
58
59 #[bitflags]
60 #[derive(Serialize_repr, Deserialize_repr, PartialEq, Eq, Copy, Clone, Debug, Type)]
61 #[repr(u32)]
62 #[doc(alias = "XdpOutputType")]
63 /// A bit flag for the available sources to record.
64 pub enum SourceType {
65 #[doc(alias = "XDP_OUTPUT_MONITOR")]
66 /// A monitor.
67 Monitor,
68 #[doc(alias = "XDP_OUTPUT_WINDOW")]
69 /// A specific window
70 Window,
71 #[doc(alias = "XDP_OUTPUT_VIRTUAL")]
72 /// Virtual
73 Virtual,
74 }
75
76 #[bitflags]
77 #[derive(Serialize_repr, Deserialize_repr, PartialEq, Eq, Debug, Copy, Clone, Type)]
78 #[repr(u32)]
79 #[doc(alias = "XdpCursorMode")]
80 /// A bit flag for the possible cursor modes.
81 pub enum CursorMode {
82 #[doc(alias = "XDP_CURSOR_MODE_HIDDEN")]
83 /// The cursor is not part of the screen cast stream.
84 Hidden,
85 #[doc(alias = "XDP_CURSOR_MODE_EMBEDDED")]
86 /// The cursor is embedded as part of the stream buffers.
87 Embedded,
88 #[doc(alias = "XDP_CURSOR_MODE_METADATA")]
89 /// The cursor is not part of the screen cast stream, but sent as PipeWire
90 /// stream metadata.
91 Metadata,
92 }
93
94 #[derive(Serialize, Type, Debug, Default)]
95 /// Specified options for a [`Screencast::open_pipe_wire_remote`] request.
96 #[zvariant(signature = "dict")]
97 pub struct OpenPipeWireRemoteOptions {}
98
99 #[derive(Serialize, Deserialize, Type, Debug, Default)]
100 /// Specified options for a [`Screencast::select_sources`] request.
101 #[zvariant(signature = "dict")]
102 pub struct SelectSourcesOptions {
103 #[serde(with = "as_value", skip_deserializing)]
104 handle_token: HandleToken,
105 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
106 types: Option<BitFlags<SourceType>>,
107 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
108 multiple: Option<bool>,
109 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
110 cursor_mode: Option<CursorMode>,
111 #[serde(
112 with = "optional",
113 skip_serializing_if = "Option::is_none",
114 skip_deserializing
115 )]
116 restore_token: Option<String>,
117 #[serde(default, with = "optional", skip_serializing)]
118 #[cfg_attr(not(feature = "backend"), allow(dead_code))]
119 restore_data: Option<(String, u32, OwnedValue)>,
120 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
121 persist_mode: Option<PersistMode>,
122 }
123
124 impl SelectSourcesOptions {
125 /// Sets whether to allow selecting multiple sources.
126 #[must_use]
127 pub fn set_multiple(mut self, multiple: impl Into<Option<bool>>) -> Self {
128 self.multiple = multiple.into();
129 self
130 }
131
132 /// Gets whether to allow selecting multiple sources.
133 #[cfg(feature = "backend")]
134 pub fn is_multiple(&self) -> Option<bool> {
135 self.multiple
136 }
137
138 /// Sets how the cursor will be drawn on the screen cast stream.
139 #[must_use]
140 pub fn set_cursor_mode(mut self, cursor_mode: impl Into<Option<CursorMode>>) -> Self {
141 self.cursor_mode = cursor_mode.into();
142 self
143 }
144
145 /// Gets how the cursor will be drawn on the screen cast stream.
146 #[cfg(feature = "backend")]
147 pub fn cursor_mode(&self) -> Option<CursorMode> {
148 self.cursor_mode
149 }
150
151 /// Sets the types of content to record.
152 #[must_use]
153 pub fn set_sources(mut self, types: impl Into<Option<BitFlags<SourceType>>>) -> Self {
154 self.types = types.into();
155 self
156 }
157
158 /// Gets the types of content to record.
159 #[cfg(feature = "backend")]
160 pub fn sources(&self) -> Option<BitFlags<SourceType>> {
161 self.types
162 }
163
164 /// Sets the persist mode.
165 #[must_use]
166 pub fn set_persist_mode(mut self, persist_mode: impl Into<Option<PersistMode>>) -> Self {
167 self.persist_mode = persist_mode.into();
168 self
169 }
170
171 /// Gets the persist mode.
172 #[cfg(feature = "backend")]
173 pub fn persist_mode(&self) -> Option<PersistMode> {
174 self.persist_mode
175 }
176
177 /// Sets the restore token.
178 #[must_use]
179 pub fn set_restore_token<'a>(mut self, token: impl Into<Option<&'a str>>) -> Self {
180 self.restore_token = token.into().map(ToOwned::to_owned);
181 self
182 }
183
184 /// Gets the restore data.
185 #[cfg(feature = "backend")]
186 pub fn restore_data<'a>(&'a self) -> Option<(&'a str, u32, &'a zbus::zvariant::Value<'a>)> {
187 use std::borrow::Borrow;
188 match &self.restore_data {
189 Some((key, version, data)) => Some((key.as_str(), *version, data.borrow())),
190 None => None,
191 }
192 }
193 }
194
195 #[derive(Serialize, Deserialize, Type, Debug, Default)]
196 /// Specified options for a [`Screencast::start`] request.
197 #[zvariant(signature = "dict")]
198 pub struct StartCastOptions {
199 #[serde(with = "as_value", skip_deserializing)]
200 handle_token: HandleToken,
201 }
202
203 #[derive(Default, Serialize, Deserialize, Type)]
204 /// A response to a [`Screencast::start`] request.
205 #[zvariant(signature = "dict")]
206 pub struct Streams {
207 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
208 streams: Vec<Stream>,
209 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
210 restore_token: Option<String>,
211 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
212 #[cfg_attr(not(feature = "backend"), allow(dead_code))]
213 persist_mode: Option<PersistMode>,
214 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
215 #[cfg_attr(not(feature = "backend"), allow(dead_code))]
216 restore_data: Option<(String, u32, OwnedValue)>,
217 }
218
219 impl Streams {
220 /// The session restore token.
221 pub fn restore_token(&self) -> Option<&str> {
222 self.restore_token.as_deref()
223 }
224
225 /// The list of streams.
226 pub fn streams(&self) -> &[Stream] {
227 &self.streams
228 }
229
230 /// The session's persist mode.
231 #[cfg(feature = "backend")]
232 pub fn persist_mode(&self) -> Option<PersistMode> {
233 self.persist_mode
234 }
235
236 /// The session restore data.
237 #[cfg(feature = "backend")]
238 pub fn restore_data(&self) -> Option<&(String, u32, OwnedValue)> {
239 self.restore_data.as_ref()
240 }
241 }
242
243 impl Debug for Streams {
244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245 f.debug_tuple("Streams")
246 .field(&self.restore_token)
247 .field(&self.streams)
248 .finish()
249 }
250 }
251
252 /// A [builder-pattern] type to construct a response to a [`Screencast::start`]
253 /// request.
254 ///
255 /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
256 #[cfg(feature = "backend")]
257 #[cfg_attr(docsrs, doc(cfg(feature = "backend")))]
258 pub struct StreamsBuilder {
259 streams: Streams,
260 }
261
262 #[cfg(feature = "backend")]
263 #[cfg_attr(docsrs, doc(cfg(feature = "backend")))]
264 impl StreamsBuilder {
265 /// Create a new instance of a streams builder.
266 pub fn new(streams: Vec<Stream>) -> Self {
267 Self {
268 streams: Streams {
269 streams,
270 restore_token: None,
271 persist_mode: None,
272 restore_data: None,
273 },
274 }
275 }
276
277 /// Set the streams' persist mode.
278 pub fn persist_mode(mut self, data: Option<impl Into<PersistMode>>) -> Self {
279 self.streams.persist_mode = data.map(|m| m.into());
280 self
281 }
282
283 /// Set the streams' optional restore data.
284 pub fn restore_data(mut self, data: Option<(String, u32, impl Into<OwnedValue>)>) -> Self {
285 self.streams.restore_data = data.map(|(s, u, d)| (s, u, d.into()));
286 self
287 }
288
289 /// Build the [`Streams`].
290 pub fn build(self) -> Streams {
291 self.streams
292 }
293 }
294
295 #[derive(Clone, Serialize, Deserialize, Type)]
296 /// A PipeWire stream.
297 pub struct Stream(u32, StreamProperties);
298
299 impl Stream {
300 /// The PipeWire stream Node ID
301 pub fn pipe_wire_node_id(&self) -> u32 {
302 self.0
303 }
304
305 /// A tuple consisting of the position (x, y) in the compositor coordinate
306 /// space.
307 ///
308 /// **Note** the position may not be equivalent to a position in a pixel
309 /// coordinate space. Only available for monitor streams.
310 pub fn position(&self) -> Option<(i32, i32)> {
311 self.1.position
312 }
313
314 /// A tuple consisting of (width, height).
315 /// The size represents the size of the stream as it is displayed in the
316 /// compositor coordinate space.
317 ///
318 /// **Note** the size may not be equivalent to a size in a pixel coordinate
319 /// space. The size may differ from the size of the stream.
320 pub fn size(&self) -> Option<(i32, i32)> {
321 self.1.size
322 }
323
324 /// The source type of the stream.
325 pub fn source_type(&self) -> Option<SourceType> {
326 self.1.source_type
327 }
328
329 /// The stream identifier.
330 pub fn id(&self) -> Option<&str> {
331 self.1.id.as_deref()
332 }
333
334 /// The stream mapping id.
335 pub fn mapping_id(&self) -> Option<&str> {
336 self.1.mapping_id.as_deref()
337 }
338 }
339
340 impl Debug for Stream {
341 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342 f.debug_struct("Stream")
343 .field("pipewire_node_id", &self.pipe_wire_node_id())
344 .field("position", &self.position())
345 .field("size", &self.size())
346 .field("source_type", &self.source_type())
347 .field("id", &self.id())
348 .finish()
349 }
350 }
351 #[derive(Clone, Serialize, Deserialize, Type, Debug)]
352 /// The stream properties.
353 #[zvariant(signature = "dict")]
354 struct StreamProperties {
355 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
356 id: Option<String>,
357 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
358 position: Option<(i32, i32)>,
359 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
360 size: Option<(i32, i32)>,
361 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
362 source_type: Option<SourceType>,
363 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
364 mapping_id: Option<String>,
365 }
366
367 /// A [builder-pattern] type to construct a PipeWire stream [`Stream`].
368 ///
369 /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
370 #[cfg(feature = "backend")]
371 #[cfg_attr(docsrs, doc(cfg(feature = "backend")))]
372 pub struct StreamBuilder {
373 stream: Stream,
374 }
375
376 #[cfg(feature = "backend")]
377 #[cfg_attr(docsrs, doc(cfg(feature = "backend")))]
378 impl StreamBuilder {
379 /// Create a new instance of a stream builder.
380 pub fn new(pipe_wire_node_id: u32) -> Self {
381 Self {
382 stream: Stream(
383 pipe_wire_node_id,
384 StreamProperties {
385 id: None,
386 position: None,
387 size: None,
388 source_type: None,
389 mapping_id: None,
390 },
391 ),
392 }
393 }
394
395 /// Set the stream's optional id (opaque identifier, local to a given
396 /// session, persisted across restored sessions).
397 pub fn id(mut self, id: impl Into<Option<String>>) -> Self {
398 self.stream.1.id = id.into();
399 self
400 }
401
402 /// Set the stream's optional position (in the compositor coordinate space).
403 pub fn position(mut self, position: impl Into<Option<(i32, i32)>>) -> Self {
404 self.stream.1.position = position.into();
405 self
406 }
407
408 /// Set the stream's optional size (in the compositor coordinate space).
409 pub fn size(mut self, size: impl Into<Option<(i32, i32)>>) -> Self {
410 self.stream.1.size = size.into();
411 self
412 }
413
414 /// Set the stream's optional source type.
415 pub fn source_type(mut self, source_type: impl Into<Option<SourceType>>) -> Self {
416 self.stream.1.source_type = source_type.into();
417 self
418 }
419
420 /// Set the stream's optional mapping id (identifier used to map different
421 /// aspects of the resource this stream corresponds to).
422 pub fn mapping_id(mut self, mapping_id: impl Into<Option<String>>) -> Self {
423 self.stream.1.mapping_id = mapping_id.into();
424 self
425 }
426
427 /// Build the [`Stream`].
428 pub fn build(self) -> Stream {
429 self.stream
430 }
431 }
432
433 /// The interface lets sandboxed applications create screen cast sessions.
434 ///
435 /// Wrapper of the DBus interface: [`org.freedesktop.portal.ScreenCast`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html).
436 #[derive(Debug)]
437 #[doc(alias = "org.freedesktop.portal.ScreenCast")]
438 pub struct Screencast(Proxy<'static>);
439
440 impl Screencast {
441 /// Create a new instance of [`Screencast`].
442 pub async fn new() -> Result<Self, Error> {
443 let proxy = Proxy::new_desktop("org.freedesktop.portal.ScreenCast").await?;
444 Ok(Self(proxy))
445 }
446
447 /// Create a new instance of [`Screencast`].
448 pub async fn with_connection(connection: zbus::Connection) -> Result<Self, Error> {
449 let proxy =
450 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.ScreenCast")
451 .await?;
452 Ok(Self(proxy))
453 }
454
455 /// Returns the version of the portal interface.
456 pub fn version(&self) -> u32 {
457 self.0.version()
458 }
459
460 /// Create a screen cast session.
461 ///
462 /// # Specifications
463 ///
464 /// See also [`CreateSession`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html#org-freedesktop-portal-screencast-createsession).
465 #[doc(alias = "CreateSession")]
466 #[doc(alias = "xdp_portal_create_screencast_session")]
467 pub async fn create_session(
468 &self,
469 options: CreateSessionOptions,
470 ) -> Result<Session<Self>, Error> {
471 let (request, proxy) = futures_util::try_join!(
472 self.0.request::<CreateSessionResponse>(
473 &options.handle_token,
474 "CreateSession",
475 &options
476 ),
477 Session::from_unique_name(self.0.connection().clone(), &options.session_handle_token),
478 )?;
479 assert_eq!(proxy.path(), &request.response()?.session_handle.as_ref());
480 Ok(proxy)
481 }
482
483 /// Open a file descriptor to the PipeWire remote where the screen cast
484 /// streams are available.
485 ///
486 /// # Arguments
487 ///
488 /// * `session` - A [`Session`], created with
489 /// [`create_session()`][`Screencast::create_session`].
490 ///
491 /// # Returns
492 ///
493 /// File descriptor of an open PipeWire remote.
494 ///
495 /// # Specifications
496 ///
497 /// See also [`OpenPipeWireRemote`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html#org-freedesktop-portal-screencast-openpipewireremote).
498 #[doc(alias = "OpenPipeWireRemote")]
499 pub async fn open_pipe_wire_remote(
500 &self,
501 session: &Session<impl IsScreencastSession>,
502 options: OpenPipeWireRemoteOptions,
503 ) -> Result<OwnedFd, Error> {
504 let fd = self
505 .0
506 .call::<zvariant::OwnedFd>("OpenPipeWireRemote", &(session, options))
507 .await?;
508 Ok(fd.into())
509 }
510
511 /// Configure what the screen cast session should record.
512 /// This method must be called before starting the session.
513 ///
514 /// Passing invalid input to this method will cause the session to be
515 /// closed. An application may only attempt to select sources once per
516 /// session.
517 ///
518 /// # Arguments
519 ///
520 /// * `session` - A [`Session`], created with
521 /// [`create_session()`][`Screencast::create_session`].
522 /// * `cursor_mode` - Sets how the cursor will be drawn on the screen cast
523 /// stream.
524 /// * `types` - Sets the types of content to record.
525 /// * `multiple`- Sets whether to allow selecting multiple sources.
526 ///
527 /// # Specifications
528 ///
529 /// See also [`SelectSources`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html#org-freedesktop-portal-screencast-selectsources).
530 #[doc(alias = "SelectSources")]
531 pub async fn select_sources(
532 &self,
533 session: &Session<impl IsScreencastSession>,
534 options: SelectSourcesOptions,
535 ) -> Result<Request<()>, Error> {
536 self.0
537 .empty_request(&options.handle_token, "SelectSources", &(session, &options))
538 .await
539 }
540
541 /// Start the screen cast session.
542 ///
543 /// This will typically result the portal presenting a dialog letting the
544 /// user do the selection set up by `select_sources`.
545 ///
546 /// An application can only attempt start a session once.
547 ///
548 /// # Arguments
549 ///
550 /// * `session` - A [`Session`], created with
551 /// [`create_session()`][`Screencast::create_session`].
552 /// * `identifier` - Identifier for the application window.
553 ///
554 /// # Return
555 ///
556 /// A list of [`Stream`] and an optional restore token.
557 ///
558 /// # Specifications
559 ///
560 /// See also [`Start`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html#org-freedesktop-portal-screencast-start).
561 #[doc(alias = "Start")]
562 pub async fn start(
563 &self,
564 session: &Session<impl IsScreencastSession>,
565 identifier: Option<&WindowIdentifier>,
566 options: StartCastOptions,
567 ) -> Result<Request<Streams>, Error> {
568 let identifier = Optional::from(identifier);
569 self.0
570 .request(
571 &options.handle_token,
572 "Start",
573 &(session, identifier, &options),
574 )
575 .await
576 }
577
578 /// Available cursor mode.
579 ///
580 /// # Specifications
581 ///
582 /// See also [`AvailableCursorModes`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html#org-freedesktop-portal-screencast-availablecursormodes).
583 #[doc(alias = "AvailableCursorModes")]
584 pub async fn available_cursor_modes(&self) -> Result<BitFlags<CursorMode>, Error> {
585 self.0.property_versioned("AvailableCursorModes", 2).await
586 }
587
588 /// Available source types.
589 ///
590 /// # Specifications
591 ///
592 /// See also [`AvailableSourceTypes`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html#org-freedesktop-portal-screencast-availablesourcetypes).
593 #[doc(alias = "AvailableSourceTypes")]
594 pub async fn available_source_types(&self) -> Result<BitFlags<SourceType>, Error> {
595 self.0.property("AvailableSourceTypes").await
596 }
597 }
598
599 impl std::ops::Deref for Screencast {
600 type Target = zbus::Proxy<'static>;
601
602 fn deref(&self) -> &Self::Target {
603 &self.0
604 }
605 }
606
607 impl crate::Sealed for Screencast {}
608 impl SessionPortal for Screencast {}
609
610 /// Defines which portals session can be used in a screen-cast.
611 pub trait IsScreencastSession: SessionPortal {}
612 impl IsScreencastSession for Screencast {}