forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

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