forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB99bf2dfIvan Molodetskikh1 year ago2106 commits

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