forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB055a94dIvan Molodetskikh1 year ago2247 commits

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