forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

mutter_screen_cast.rs401 lines, 11.4 KiBHistoryRawDownload
1use std::collections::HashMap;
2use std::mem;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex};
5
6use serde::Deserialize;
7use zbus::object_server::{InterfaceRef, SignalEmitter};
8use zbus::zvariant::{DeserializeDict, OwnedObjectPath, SerializeDict, Type, Value};
9use zbus::{fdo, interface, ObjectServer};
10
11use super::{request_name, Start};
12use crate::backend::IpcOutputMap;
13use crate::utils::{CastSessionId, CastStreamId};
14
15#[derive(Clone)]
16pub struct ScreenCast {
17 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
18 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
19 #[allow(clippy::type_complexity)]
20 sessions: Arc<Mutex<Vec<(Session, InterfaceRef<Session>)>>>,
21}
22
23#[derive(Clone)]
24pub struct Session {
25 id: CastSessionId,
26 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
27 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
28 #[allow(clippy::type_complexity)]
29 streams: Arc<Mutex<Vec<(Stream, InterfaceRef<Stream>)>>>,
30 stopped: Arc<AtomicBool>,
31}
32
33#[derive(Debug, Default, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
34pub enum CursorMode {
35 #[default]
36 Hidden = 0,
37 Embedded = 1,
38 Metadata = 2,
39}
40
41#[derive(Debug, DeserializeDict, Type)]
42#[zvariant(signature = "dict")]
43struct RecordMonitorProperties {
44 #[zvariant(rename = "cursor-mode")]
45 cursor_mode: Option<CursorMode>,
46 #[zvariant(rename = "is-recording")]
47 _is_recording: Option<bool>,
48}
49
50#[derive(Debug, DeserializeDict, Type)]
51#[zvariant(signature = "dict")]
52struct RecordWindowProperties {
53 #[zvariant(rename = "window-id")]
54 window_id: u64,
55 #[zvariant(rename = "cursor-mode")]
56 cursor_mode: Option<CursorMode>,
57 #[zvariant(rename = "is-recording")]
58 _is_recording: Option<bool>,
59}
60
61#[derive(Clone)]
62pub struct Stream {
63 id: CastStreamId,
64 session_id: CastSessionId,
65 target: StreamTarget,
66 cursor_mode: CursorMode,
67 was_started: Arc<AtomicBool>,
68 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
69}
70
71#[derive(Clone)]
72enum StreamTarget {
73 // FIXME: update on scale changes and whatnot.
74 Output(niri_ipc::Output),
75 Window { id: u64 },
76}
77
78#[derive(Debug, Clone)]
79pub enum StreamTargetId {
80 Output { name: String },
81 Window { id: u64 },
82}
83
84#[derive(Debug, SerializeDict, Type, Value)]
85#[zvariant(signature = "dict")]
86struct StreamParameters {
87 /// Position of the stream in logical coordinates.
88 position: (i32, i32),
89 /// Size of the stream in logical coordinates.
90 size: (i32, i32),
91}
92
93pub enum ScreenCastToNiri {
94 StartCast {
95 session_id: CastSessionId,
96 stream_id: CastStreamId,
97 target: StreamTargetId,
98 cursor_mode: CursorMode,
99 signal_ctx: SignalEmitter<'static>,
100 },
101 StopCast {
102 session_id: CastSessionId,
103 },
104}
105
106#[interface(name = "org.gnome.Mutter.ScreenCast")]
107impl ScreenCast {
108 async fn create_session(
109 &self,
110 #[zbus(object_server)] server: &ObjectServer,
111 properties: HashMap<&str, Value<'_>>,
112 ) -> fdo::Result<OwnedObjectPath> {
113 if properties.contains_key("remote-desktop-session-id") {
114 return Err(fdo::Error::Failed(
115 "there are no remote desktop sessions".to_owned(),
116 ));
117 }
118
119 let session_id = CastSessionId::next();
120 let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id.get());
121 let path = OwnedObjectPath::try_from(path).unwrap();
122
123 let session = Session::new(session_id, self.ipc_outputs.clone(), self.to_niri.clone());
124 match server.at(&path, session.clone()).await {
125 Ok(true) => {
126 let iface = server.interface(&path).await.unwrap();
127 self.sessions.lock().unwrap().push((session, iface));
128 }
129 Ok(false) => return Err(fdo::Error::Failed("session path already exists".to_owned())),
130 Err(err) => {
131 return Err(fdo::Error::Failed(format!(
132 "error creating session object: {err:?}"
133 )))
134 }
135 }
136
137 Ok(path)
138 }
139
140 #[zbus(property)]
141 async fn version(&self) -> i32 {
142 4
143 }
144}
145
146#[interface(name = "org.gnome.Mutter.ScreenCast.Session")]
147impl Session {
148 async fn start(&self) {
149 debug!("start");
150
151 for (stream, iface) in &*self.streams.lock().unwrap() {
152 stream.start(iface.signal_emitter().clone());
153 }
154 }
155
156 pub async fn stop(
157 &self,
158 #[zbus(object_server)] server: &ObjectServer,
159 #[zbus(signal_context)] ctxt: SignalEmitter<'_>,
160 ) {
161 debug!("stop");
162
163 if self.stopped.swap(true, Ordering::SeqCst) {
164 // Already stopped.
165 return;
166 }
167
168 Session::closed(&ctxt).await.unwrap();
169
170 if let Err(err) = self.to_niri.send(ScreenCastToNiri::StopCast {
171 session_id: self.id,
172 }) {
173 warn!("error sending StopCast to niri: {err:?}");
174 }
175
176 let streams = mem::take(&mut *self.streams.lock().unwrap());
177 for (_, iface) in streams.iter() {
178 server
179 .remove::<Stream, _>(iface.signal_emitter().path())
180 .await
181 .unwrap();
182 }
183
184 server.remove::<Session, _>(ctxt.path()).await.unwrap();
185 }
186
187 async fn record_monitor(
188 &mut self,
189 #[zbus(object_server)] server: &ObjectServer,
190 connector: &str,
191 properties: RecordMonitorProperties,
192 ) -> fdo::Result<OwnedObjectPath> {
193 debug!(connector, ?properties, "record_monitor");
194
195 let output = {
196 let ipc_outputs = self.ipc_outputs.lock().unwrap();
197 ipc_outputs.values().find(|o| o.name == connector).cloned()
198 };
199 let Some(output) = output else {
200 return Err(fdo::Error::Failed("no such monitor".to_owned()));
201 };
202
203 if output.logical.is_none() {
204 return Err(fdo::Error::Failed("monitor is disabled".to_owned()));
205 }
206
207 let stream_id = CastStreamId::next();
208 let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{}", stream_id.get());
209 let path = OwnedObjectPath::try_from(path).unwrap();
210
211 let cursor_mode = properties.cursor_mode.unwrap_or_default();
212
213 let target = StreamTarget::Output(output);
214 let stream = Stream::new(
215 stream_id,
216 self.id,
217 target,
218 cursor_mode,
219 self.to_niri.clone(),
220 );
221 match server.at(&path, stream.clone()).await {
222 Ok(true) => {
223 let iface = server.interface(&path).await.unwrap();
224 self.streams.lock().unwrap().push((stream, iface));
225 }
226 Ok(false) => return Err(fdo::Error::Failed("stream path already exists".to_owned())),
227 Err(err) => {
228 return Err(fdo::Error::Failed(format!(
229 "error creating stream object: {err:?}"
230 )))
231 }
232 }
233
234 Ok(path)
235 }
236
237 async fn record_window(
238 &mut self,
239 #[zbus(object_server)] server: &ObjectServer,
240 properties: RecordWindowProperties,
241 ) -> fdo::Result<OwnedObjectPath> {
242 debug!(?properties, "record_window");
243
244 let stream_id = CastStreamId::next();
245 let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{}", stream_id.get());
246 let path = OwnedObjectPath::try_from(path).unwrap();
247
248 let cursor_mode = properties.cursor_mode.unwrap_or_default();
249
250 let target = StreamTarget::Window {
251 id: properties.window_id,
252 };
253 let stream = Stream::new(
254 stream_id,
255 self.id,
256 target,
257 cursor_mode,
258 self.to_niri.clone(),
259 );
260 match server.at(&path, stream.clone()).await {
261 Ok(true) => {
262 let iface = server.interface(&path).await.unwrap();
263 self.streams.lock().unwrap().push((stream, iface));
264 }
265 Ok(false) => return Err(fdo::Error::Failed("stream path already exists".to_owned())),
266 Err(err) => {
267 return Err(fdo::Error::Failed(format!(
268 "error creating stream object: {err:?}"
269 )))
270 }
271 }
272
273 Ok(path)
274 }
275
276 #[zbus(signal)]
277 async fn closed(ctxt: &SignalEmitter<'_>) -> zbus::Result<()>;
278}
279
280#[interface(name = "org.gnome.Mutter.ScreenCast.Stream")]
281impl Stream {
282 #[zbus(signal)]
283 pub async fn pipe_wire_stream_added(ctxt: &SignalEmitter<'_>, node_id: u32)
284 -> zbus::Result<()>;
285
286 #[zbus(property)]
287 async fn parameters(&self) -> StreamParameters {
288 match &self.target {
289 StreamTarget::Output(output) => {
290 let logical = output.logical.as_ref().unwrap();
291 StreamParameters {
292 position: (logical.x, logical.y),
293 size: (logical.width as i32, logical.height as i32),
294 }
295 }
296 StreamTarget::Window { .. } => {
297 // Does any consumer need this?
298 StreamParameters {
299 position: (0, 0),
300 size: (1, 1),
301 }
302 }
303 }
304 }
305}
306
307impl ScreenCast {
308 pub fn new(
309 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
310 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
311 ) -> Self {
312 Self {
313 ipc_outputs,
314 to_niri,
315 sessions: Arc::new(Mutex::new(vec![])),
316 }
317 }
318}
319
320impl Start for ScreenCast {
321 fn start(self, monitor: bool) -> anyhow::Result<zbus::blocking::Connection> {
322 let conn = zbus::blocking::Connection::session()?;
323 conn.object_server()
324 .at("/org/gnome/Mutter/ScreenCast", self)?;
325 request_name(&conn, "org.gnome.Mutter.ScreenCast", monitor)?;
326
327 Ok(conn)
328 }
329}
330
331impl Session {
332 pub fn new(
333 id: CastSessionId,
334 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
335 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
336 ) -> Self {
337 Self {
338 id,
339 ipc_outputs,
340 streams: Arc::new(Mutex::new(vec![])),
341 to_niri,
342 stopped: Arc::new(AtomicBool::new(false)),
343 }
344 }
345}
346
347impl Drop for Session {
348 fn drop(&mut self) {
349 let _ = self.to_niri.send(ScreenCastToNiri::StopCast {
350 session_id: self.id,
351 });
352 }
353}
354
355impl Stream {
356 fn new(
357 id: CastStreamId,
358 session_id: CastSessionId,
359 target: StreamTarget,
360 cursor_mode: CursorMode,
361 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
362 ) -> Self {
363 Self {
364 id,
365 session_id,
366 target,
367 cursor_mode,
368 was_started: Arc::new(AtomicBool::new(false)),
369 to_niri,
370 }
371 }
372
373 fn start(&self, ctxt: SignalEmitter<'static>) {
374 if self.was_started.load(Ordering::SeqCst) {
375 return;
376 }
377
378 let msg = ScreenCastToNiri::StartCast {
379 session_id: self.session_id,
380 stream_id: self.id,
381 target: self.target.make_id(),
382 cursor_mode: self.cursor_mode,
383 signal_ctx: ctxt,
384 };
385
386 if let Err(err) = self.to_niri.send(msg) {
387 warn!("error sending StartCast to niri: {err:?}");
388 }
389 }
390}
391
392impl StreamTarget {
393 fn make_id(&self) -> StreamTargetId {
394 match self {
395 StreamTarget::Output(output) => StreamTargetId::Output {
396 name: output.name.clone(),
397 },
398 StreamTarget::Window { id } => StreamTargetId::Window { id: *id },
399 }
400 }
401}