forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

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