forge
Explore
Log in

Don't you dare go Hollow

Extract cast session/stream ID counters to global scope

Browse files at this commit

570ea119bae8e8cd3fa9677b634c173b8f3db8cfIvan MolodetskikhParent: df4614e
Add CastSessionId and CastStreamId newtypes. This lifts the atomic
counters from the D-Bus mutter_screen_cast module to a shared location,
preparing for adding screencopy cast tracking which will need the same
ID types.
src/dbus/mutter_screen_cast.rsmodified+17 -19
@@ -1,6 +1,6 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2 use std::mem;2 use std::mem;
3-use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};3+use std::sync::atomic::{AtomicBool, Ordering};
4 use std::sync::{Arc, Mutex};4 use std::sync::{Arc, Mutex};
5 5
6 use serde::Deserialize;6 use serde::Deserialize;
@@ -11,6 +11,7 @@ use zbus::{fdo, interface, ObjectServer};
11 11
12 use super::Start;12 use super::Start;
13 use crate::backend::IpcOutputMap;13 use crate::backend::IpcOutputMap;
14+use crate::utils::{CastSessionId, CastStreamId};
14 15
15 #[derive(Clone)]16 #[derive(Clone)]
16 pub struct ScreenCast {17 pub struct ScreenCast {
@@ -22,7 +23,7 @@ pub struct ScreenCast {
22 23
23 #[derive(Clone)]24 #[derive(Clone)]
24 pub struct Session {25 pub struct Session {
25- id: usize,26+ id: CastSessionId,
26 ipc_outputs: Arc<Mutex<IpcOutputMap>>,27 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
27 to_niri: calloop::channel::Sender<ScreenCastToNiri>,28 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
28 #[allow(clippy::type_complexity)]29 #[allow(clippy::type_complexity)]
@@ -58,12 +59,10 @@ struct RecordWindowProperties {
58 _is_recording: Option<bool>,59 _is_recording: Option<bool>,
59 }60 }
60 61
61-static STREAM_ID: AtomicUsize = AtomicUsize::new(0);
62-
63 #[derive(Clone)]62 #[derive(Clone)]
64 pub struct Stream {63 pub struct Stream {
65- id: usize,64+ id: CastStreamId,
66- session_id: usize,65+ session_id: CastSessionId,
67 target: StreamTarget,66 target: StreamTarget,
68 cursor_mode: CursorMode,67 cursor_mode: CursorMode,
69 was_started: Arc<AtomicBool>,68 was_started: Arc<AtomicBool>,
@@ -94,14 +93,14 @@ struct StreamParameters {
94 93
95 pub enum ScreenCastToNiri {94 pub enum ScreenCastToNiri {
96 StartCast {95 StartCast {
97- session_id: usize,96+ session_id: CastSessionId,
98- stream_id: usize,97+ stream_id: CastStreamId,
99 target: StreamTargetId,98 target: StreamTargetId,
100 cursor_mode: CursorMode,99 cursor_mode: CursorMode,
101 signal_ctx: SignalEmitter<'static>,100 signal_ctx: SignalEmitter<'static>,
102 },101 },
103 StopCast {102 StopCast {
104- session_id: usize,103+ session_id: CastSessionId,
105 },104 },
106 }105 }
107 106
@@ -118,9 +117,8 @@ impl ScreenCast {
118 ));117 ));
119 }118 }
120 119
121- static NUMBER: AtomicUsize = AtomicUsize::new(0);120+ let session_id = CastSessionId::next();
122- let session_id = NUMBER.fetch_add(1, Ordering::SeqCst);121+ let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id.get());
123- let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{session_id}");
124 let path = OwnedObjectPath::try_from(path).unwrap();122 let path = OwnedObjectPath::try_from(path).unwrap();
125 123
126 let session = Session::new(session_id, self.ipc_outputs.clone(), self.to_niri.clone());124 let session = Session::new(session_id, self.ipc_outputs.clone(), self.to_niri.clone());
@@ -207,8 +205,8 @@ impl Session {
207 return Err(fdo::Error::Failed("monitor is disabled".to_owned()));205 return Err(fdo::Error::Failed("monitor is disabled".to_owned()));
208 }206 }
209 207
210- let stream_id = STREAM_ID.fetch_add(1, Ordering::SeqCst);208+ let stream_id = CastStreamId::next();
211- let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{stream_id}");209+ let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{}", stream_id.get());
212 let path = OwnedObjectPath::try_from(path).unwrap();210 let path = OwnedObjectPath::try_from(path).unwrap();
213 211
214 let cursor_mode = properties.cursor_mode.unwrap_or_default();212 let cursor_mode = properties.cursor_mode.unwrap_or_default();
@@ -244,8 +242,8 @@ impl Session {
244 ) -> fdo::Result<OwnedObjectPath> {242 ) -> fdo::Result<OwnedObjectPath> {
245 debug!(?properties, "record_window");243 debug!(?properties, "record_window");
246 244
247- let stream_id = STREAM_ID.fetch_add(1, Ordering::SeqCst);245+ let stream_id = CastStreamId::next();
248- let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{stream_id}");246+ let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{}", stream_id.get());
249 let path = OwnedObjectPath::try_from(path).unwrap();247 let path = OwnedObjectPath::try_from(path).unwrap();
250 248
251 let cursor_mode = properties.cursor_mode.unwrap_or_default();249 let cursor_mode = properties.cursor_mode.unwrap_or_default();
@@ -337,7 +335,7 @@ impl Start for ScreenCast {
337 335
338 impl Session {336 impl Session {
339 pub fn new(337 pub fn new(
340- id: usize,338+ id: CastSessionId,
341 ipc_outputs: Arc<Mutex<IpcOutputMap>>,339 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
342 to_niri: calloop::channel::Sender<ScreenCastToNiri>,340 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
343 ) -> Self {341 ) -> Self {
@@ -361,8 +359,8 @@ impl Drop for Session {
361 359
362 impl Stream {360 impl Stream {
363 fn new(361 fn new(
364- id: usize,362+ id: CastStreamId,
365- session_id: usize,363+ session_id: CastSessionId,
366 target: StreamTarget,364 target: StreamTarget,
367 cursor_mode: CursorMode,365 cursor_mode: CursorMode,
368 to_niri: calloop::channel::Sender<ScreenCastToNiri>,366 to_niri: calloop::channel::Sender<ScreenCastToNiri>,
src/screencasting/mod.rsmodified+8 -8
@@ -20,7 +20,7 @@ use crate::dbus::mutter_screen_cast::{self, CursorMode, ScreenCastToNiri, Stream
20 use crate::niri::{CastTarget, Niri, OutputRenderElements, PointerRenderElements, State};20 use crate::niri::{CastTarget, Niri, OutputRenderElements, PointerRenderElements, State};
21 use crate::niri_render_elements;21 use crate::niri_render_elements;
22 use crate::render_helpers::RenderTarget;22 use crate::render_helpers::RenderTarget;
23-use crate::utils::get_monotonic_time;23+use crate::utils::{get_monotonic_time, CastSessionId, CastStreamId};
24 use crate::window::mapped::{MappedId, WindowCastRenderElements};24 use crate::window::mapped::{MappedId, WindowCastRenderElements};
25 25
26 mod pw_utils;26 mod pw_utils;
@@ -46,8 +46,8 @@ pub struct Screencasting {
46 46
47 /// A screencast request that hasn't been started yet.47 /// A screencast request that hasn't been started yet.
48 pub struct PendingCast {48 pub struct PendingCast {
49- pub session_id: usize,49+ pub session_id: CastSessionId,
50- pub stream_id: usize,50+ pub stream_id: CastStreamId,
51 pub cursor_mode: CursorMode,51 pub cursor_mode: CursorMode,
52 pub signal_ctx: SignalEmitter<'static>,52 pub signal_ctx: SignalEmitter<'static>,
53 }53 }
@@ -137,7 +137,7 @@ impl State {
137 }137 }
138 }138 }
139 139
140- fn redraw_cast(&mut self, stream_id: usize) {140+ fn redraw_cast(&mut self, stream_id: CastStreamId) {
141 let _span = tracy_client::span!("State::redraw_cast");141 let _span = tracy_client::span!("State::redraw_cast");
142 142
143 let casts = &mut self.niri.casting.casts;143 let casts = &mut self.niri.casting.casts;
@@ -391,7 +391,7 @@ impl State {
391 signal_ctx,391 signal_ctx,
392 } => {392 } => {
393 let _span = tracy_client::span!("StartCast");393 let _span = tracy_client::span!("StartCast");
394- let _span = debug_span!("StartCast", session_id, stream_id).entered();394+ let _span = debug_span!("StartCast", %session_id, %stream_id).entered();
395 395
396 let (target, size, refresh, alpha) = match target {396 let (target, size, refresh, alpha) = match target {
397 StreamTargetId::Output { name } => {397 StreamTargetId::Output { name } => {
@@ -694,9 +694,9 @@ impl Niri {
694 }694 }
695 }695 }
696 696
697- fn stop_cast(&mut self, session_id: usize) {697+ fn stop_cast(&mut self, session_id: CastSessionId) {
698 let _span = tracy_client::span!("Niri::stop_cast");698 let _span = tracy_client::span!("Niri::stop_cast");
699- let _span = debug_span!("stop_cast", session_id).entered();699+ let _span = debug_span!("stop_cast", %session_id).entered();
700 700
701 self.casting701 self.casting
702 .pending_dynamic_casts702 .pending_dynamic_casts
@@ -716,7 +716,7 @@ impl Niri {
716 716
717 let dbus = &self.dbus.as_ref().unwrap();717 let dbus = &self.dbus.as_ref().unwrap();
718 let server = dbus.conn_screen_cast.as_ref().unwrap().object_server();718 let server = dbus.conn_screen_cast.as_ref().unwrap().object_server();
719- let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{session_id}");719+ let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id.get());
720 if let Ok(iface) = server.interface::<_, mutter_screen_cast::Session>(path) {720 if let Ok(iface) = server.interface::<_, mutter_screen_cast::Session>(path) {
721 let _span = tracy_client::span!("invoking Session::stop");721 let _span = tracy_client::span!("invoking Session::stop");
722 722
src/screencasting/pw_utils.rsmodified+15 -15
@@ -55,7 +55,7 @@ use crate::render_helpers::{
55 clear_dmabuf, encompassing_geo, render_and_download, render_to_dmabuf,55 clear_dmabuf, encompassing_geo, render_and_download, render_to_dmabuf,
56 };56 };
57 use crate::screencasting::CastRenderElement;57 use crate::screencasting::CastRenderElement;
58-use crate::utils::get_monotonic_time;58+use crate::utils::{get_monotonic_time, CastSessionId, CastStreamId};
59 59
60 // Give a 0.1 ms allowance for presentation time errors.60 // Give a 0.1 ms allowance for presentation time errors.
61 const CAST_DELAY_ALLOWANCE: Duration = Duration::from_micros(100);61 const CAST_DELAY_ALLOWANCE: Duration = Duration::from_micros(100);
@@ -79,15 +79,15 @@ pub struct PipeWire {
79 }79 }
80 80
81 pub enum PwToNiri {81 pub enum PwToNiri {
82- StopCast { session_id: usize },82+ StopCast { session_id: CastSessionId },
83- Redraw { stream_id: usize },83+ Redraw { stream_id: CastStreamId },
84 FatalError,84 FatalError,
85 }85 }
86 86
87 pub struct Cast {87 pub struct Cast {
88 event_loop: LoopHandle<'static, State>,88 event_loop: LoopHandle<'static, State>,
89- pub session_id: usize,89+ pub session_id: CastSessionId,
90- pub stream_id: usize,90+ pub stream_id: CastStreamId,
91 // Listener is dropped before Stream to prevent a use-after-free.91 // Listener is dropped before Stream to prevent a use-after-free.
92 _listener: StreamListener<()>,92 _listener: StreamListener<()>,
93 pub stream: StreamRc,93 pub stream: StreamRc,
@@ -269,8 +269,8 @@ impl PipeWire {
269 &self,269 &self,
270 gbm: GbmDevice<DrmDeviceFd>,270 gbm: GbmDevice<DrmDeviceFd>,
271 formats: FormatSet,271 formats: FormatSet,
272- session_id: usize,272+ session_id: CastSessionId,
273- stream_id: usize,273+ stream_id: CastStreamId,
274 target: CastTarget,274 target: CastTarget,
275 size: Size<i32, Physical>,275 size: Size<i32, Physical>,
276 refresh: u32,276 refresh: u32,
@@ -283,13 +283,13 @@ impl PipeWire {
283 let to_niri_ = self.to_niri.clone();283 let to_niri_ = self.to_niri.clone();
284 let stop_cast = move || {284 let stop_cast = move || {
285 if let Err(err) = to_niri_.send(PwToNiri::StopCast { session_id }) {285 if let Err(err) = to_niri_.send(PwToNiri::StopCast { session_id }) {
286- warn!(session_id, "error sending StopCast to niri: {err:?}");286+ warn!(%session_id, "error sending StopCast to niri: {err:?}");
287 }287 }
288 };288 };
289 let to_niri_ = self.to_niri.clone();289 let to_niri_ = self.to_niri.clone();
290 let redraw = move || {290 let redraw = move || {
291 if let Err(err) = to_niri_.send(PwToNiri::Redraw { stream_id }) {291 if let Err(err) = to_niri_.send(PwToNiri::Redraw { stream_id }) {
292- warn!(stream_id, "error sending Redraw to niri: {err:?}");292+ warn!(%stream_id, "error sending Redraw to niri: {err:?}");
293 }293 }
294 };294 };
295 let redraw_ = redraw.clone();295 let redraw_ = redraw.clone();
@@ -328,7 +328,7 @@ impl PipeWire {
328 let inner = inner.clone();328 let inner = inner.clone();
329 let stop_cast = stop_cast.clone();329 let stop_cast = stop_cast.clone();
330 move |stream, (), old, new| {330 move |stream, (), old, new| {
331- let _span = debug_span!("state_changed", stream_id).entered();331+ let _span = debug_span!("state_changed", %stream_id).entered();
332 debug!("{old:?} -> {new:?}");332 debug!("{old:?} -> {new:?}");
333 let mut inner = inner.borrow_mut();333 let mut inner = inner.borrow_mut();
334 334
@@ -378,7 +378,7 @@ impl PipeWire {
378 let formats = formats.clone();378 let formats = formats.clone();
379 move |stream, (), id, pod| {379 move |stream, (), id, pod| {
380 let id = ParamType::from_raw(id);380 let id = ParamType::from_raw(id);
381- trace!(stream_id, ?id, "param_changed");381+ trace!(%stream_id, ?id, "param_changed");
382 let mut inner = inner.borrow_mut();382 let mut inner = inner.borrow_mut();
383 let inner = &mut *inner;383 let inner = &mut *inner;
384 384
@@ -386,7 +386,7 @@ impl PipeWire {
386 return;386 return;
387 }387 }
388 388
389- let _span = debug_span!("param_changed", stream_id).entered();389+ let _span = debug_span!("param_changed", %stream_id).entered();
390 390
391 let Some(pod) = pod else { return };391 let Some(pod) = pod else { return };
392 392
@@ -678,7 +678,7 @@ impl PipeWire {
678 let inner = inner.clone();678 let inner = inner.clone();
679 let stop_cast = stop_cast.clone();679 let stop_cast = stop_cast.clone();
680 move |stream, (), buffer| {680 move |stream, (), buffer| {
681- let _span = debug_span!("add_buffer", stream_id).entered();681+ let _span = debug_span!("add_buffer", %stream_id).entered();
682 let mut inner = inner.borrow_mut();682 let mut inner = inner.borrow_mut();
683 683
684 let (size, alpha, modifier) = if let CastState::Ready {684 let (size, alpha, modifier) = if let CastState::Ready {
@@ -758,7 +758,7 @@ impl PipeWire {
758 .remove_buffer({758 .remove_buffer({
759 let inner = inner.clone();759 let inner = inner.clone();
760 move |_stream, (), buffer| {760 move |_stream, (), buffer| {
761- trace!(stream_id, "remove_buffer");761+ trace!(%stream_id, "remove_buffer");
762 let mut inner = inner.borrow_mut();762 let mut inner = inner.borrow_mut();
763 763
764 inner764 inner
@@ -779,7 +779,7 @@ impl PipeWire {
779 .unwrap();779 .unwrap();
780 780
781 trace!(781 trace!(
782- stream_id,782+ %stream_id,
783 "starting pw stream with size={pending_size:?}, refresh={refresh:?}"783 "starting pw stream with size={pending_size:?}, refresh={refresh:?}"
784 );784 );
785 785
src/utils/mod.rsmodified+46 -1
@@ -1,12 +1,13 @@
1 use std::cmp::{max, min};1 use std::cmp::{max, min};
2-use std::f64;
3 use std::ffi::{CString, OsStr};2 use std::ffi::{CString, OsStr};
3+use std::fmt::Display;
4 use std::io::Write;4 use std::io::Write;
5 use std::os::unix::prelude::OsStrExt;5 use std::os::unix::prelude::OsStrExt;
6 use std::path::{Path, PathBuf};6 use std::path::{Path, PathBuf};
7 use std::ptr::null_mut;7 use std::ptr::null_mut;
8 use std::sync::atomic::AtomicBool;8 use std::sync::atomic::AtomicBool;
9 use std::time::Duration;9 use std::time::Duration;
10+use std::{f64, fmt};
10 11
11 use anyhow::{ensure, Context};12 use anyhow::{ensure, Context};
12 use bitflags::bitflags;13 use bitflags::bitflags;
@@ -44,6 +45,50 @@ pub mod xwayland;
44 45
45 pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);46 pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
46 47
48+use id::IdCounter;
49+
50+/// Unique ID for a screencast session.
51+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52+pub struct CastSessionId(u64);
53+
54+impl CastSessionId {
55+ pub fn next() -> Self {
56+ static COUNTER: IdCounter = IdCounter::new();
57+ Self(COUNTER.next())
58+ }
59+
60+ pub fn get(self) -> u64 {
61+ self.0
62+ }
63+}
64+
65+impl Display for CastSessionId {
66+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67+ write!(f, "{}", self.0)
68+ }
69+}
70+
71+/// Unique ID for a screencast stream.
72+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73+pub struct CastStreamId(u64);
74+
75+impl CastStreamId {
76+ pub fn next() -> Self {
77+ static COUNTER: IdCounter = IdCounter::new();
78+ Self(COUNTER.next())
79+ }
80+
81+ pub fn get(self) -> u64 {
82+ self.0
83+ }
84+}
85+
86+impl Display for CastStreamId {
87+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88+ write!(f, "{}", self.0)
89+ }
90+}
91+
47 bitflags! {92 bitflags! {
48 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]93 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
49 pub struct ResizeEdge: u32 {94 pub struct ResizeEdge: u32 {