forge
Explore
Log in

Don't you dare go Hollow

ipc: Add screencast request and events for PipeWire casts

Browse files at this commit

238caaf8dace6aaa49b991a4f416d0d5983510f2Ivan MolodetskikhParent: 9c79108
Allows desktop bars to show when screen recording is active.
niri-ipc/src/lib.rsmodified+68 -0
@@ -117,6 +117,8 @@ pub enum Request {
117 ReturnError,117 ReturnError,
118 /// Request information about the overview.118 /// Request information about the overview.
119 OverviewState,119 OverviewState,
120+ /// Request information about screencasts.
121+ Casts,
120 }122 }
121 123
122 /// Reply from niri to client.124 /// Reply from niri to client.
@@ -161,6 +163,8 @@ pub enum Response {
161 OutputConfigChanged(OutputConfigChanged),163 OutputConfigChanged(OutputConfigChanged),
162 /// Information about the overview.164 /// Information about the overview.
163 OverviewState(Overview),165 OverviewState(Overview),
166+ /// Information about screencasts.
167+ Casts(Vec<Cast>),
164 }168 }
165 169
166 /// Overview information.170 /// Overview information.
@@ -1473,6 +1477,52 @@ pub struct LayerSurface {
1473 pub keyboard_interactivity: LayerSurfaceKeyboardInteractivity,1477 pub keyboard_interactivity: LayerSurfaceKeyboardInteractivity,
1474 }1478 }
1475 1479
1480+/// A screencast.
1481+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1482+#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1483+pub struct Cast {
1484+ /// Stream ID of the screencast that uniquely identifies it.
1485+ pub stream_id: u64,
1486+ /// Session ID of the screencast.
1487+ ///
1488+ /// A session can have multiple screencast streams. Then multiple `Cast`s will have the same
1489+ /// `session_id`. Though, usually there's only one stream per session.
1490+ ///
1491+ /// Do not confuse `session_id` with [`stream_id`](Self::stream_id).
1492+ pub session_id: u64,
1493+ /// Target being captured.
1494+ pub target: CastTarget,
1495+ /// Whether this is a Dynamic Cast Target screencast.
1496+ ///
1497+ /// Meaning that actions like `SetDynamicCastWindow` will act on this screencast.
1498+ ///
1499+ /// Keep in mind that the target can change even if this is `false`.
1500+ pub is_dynamic_target: bool,
1501+ /// Whether the cast is currently streaming frames.
1502+ ///
1503+ /// This can be `false` for example when switching away to a different scene in OBS, which
1504+ /// pauses the stream.
1505+ pub is_active: bool,
1506+}
1507+
1508+/// Target of a screencast.
1509+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1510+#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1511+pub enum CastTarget {
1512+ /// The target is not yet set, or was cleared.
1513+ Nothing {},
1514+ /// Casting an output.
1515+ Output {
1516+ /// Name of the screencasted output.
1517+ name: String,
1518+ },
1519+ /// Casting a window.
1520+ Window {
1521+ /// ID of the screencasted window.
1522+ id: u64,
1523+ },
1524+}
1525+
1476 /// A compositor event.1526 /// A compositor event.
1477 #[derive(Serialize, Deserialize, Debug, Clone)]1527 #[derive(Serialize, Deserialize, Debug, Clone)]
1478 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]1528 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
@@ -1595,6 +1645,24 @@ pub enum Event {
1595 /// be converted to a `String` (e.g. contained invalid UTF-8 bytes).1645 /// be converted to a `String` (e.g. contained invalid UTF-8 bytes).
1596 path: Option<String>,1646 path: Option<String>,
1597 },1647 },
1648+ /// The screencasts have changed.
1649+ CastsChanged {
1650+ /// The new screencast information.
1651+ ///
1652+ /// This configuration completely replaces the previous configuration. I.e. if any casts
1653+ /// are missing from here, then they were stopped.
1654+ casts: Vec<Cast>,
1655+ },
1656+ /// A screencast started, or an existing cast changed.
1657+ CastStartedOrChanged {
1658+ /// The cast that started or changed.
1659+ cast: Cast,
1660+ },
1661+ /// A screencast stopped.
1662+ CastStopped {
1663+ /// Stream ID of the stopped screencast.
1664+ stream_id: u64,
1665+ },
1598 }1666 }
1599 1667
1600 impl From<Duration> for Timestamp {1668 impl From<Duration> for Timestamp {
niri-ipc/src/state.rsmodified+37 -1
@@ -9,7 +9,7 @@
9 use std::collections::hash_map::Entry;9 use std::collections::hash_map::Entry;
10 use std::collections::HashMap;10 use std::collections::HashMap;
11 11
12-use crate::{Event, KeyboardLayouts, Window, Workspace};12+use crate::{Cast, Event, KeyboardLayouts, Window, Workspace};
13 13
14 /// Part of the state communicated via the event stream.14 /// Part of the state communicated via the event stream.
15 pub trait EventStreamStatePart {15 pub trait EventStreamStatePart {
@@ -46,6 +46,9 @@ pub struct EventStreamState {
46 46
47 /// State of the config.47 /// State of the config.
48 pub config: ConfigState,48 pub config: ConfigState,
49+
50+ /// State of screencasts.
51+ pub casts: CastsState,
49 }52 }
50 53
51 /// The workspaces state communicated over the event stream.54 /// The workspaces state communicated over the event stream.
@@ -83,6 +86,13 @@ pub struct ConfigState {
83 pub failed: bool,86 pub failed: bool,
84 }87 }
85 88
89+/// The casts state communicated over the event stream.
90+#[derive(Debug, Default)]
91+pub struct CastsState {
92+ /// Map from a stream id to the screencast.
93+ pub casts: HashMap<u64, Cast>,
94+}
95+
86 impl EventStreamStatePart for EventStreamState {96 impl EventStreamStatePart for EventStreamState {
87 fn replicate(&self) -> Vec<Event> {97 fn replicate(&self) -> Vec<Event> {
88 let mut events = Vec::new();98 let mut events = Vec::new();
@@ -91,6 +101,7 @@ impl EventStreamStatePart for EventStreamState {
91 events.extend(self.keyboard_layouts.replicate());101 events.extend(self.keyboard_layouts.replicate());
92 events.extend(self.overview.replicate());102 events.extend(self.overview.replicate());
93 events.extend(self.config.replicate());103 events.extend(self.config.replicate());
104+ events.extend(self.casts.replicate());
94 events105 events
95 }106 }
96 107
@@ -100,6 +111,7 @@ impl EventStreamStatePart for EventStreamState {
100 let event = self.keyboard_layouts.apply(event)?;111 let event = self.keyboard_layouts.apply(event)?;
101 let event = self.overview.apply(event)?;112 let event = self.overview.apply(event)?;
102 let event = self.config.apply(event)?;113 let event = self.config.apply(event)?;
114+ let event = self.casts.apply(event)?;
103 Some(event)115 Some(event)
104 }116 }
105 }117 }
@@ -285,3 +297,27 @@ impl EventStreamStatePart for ConfigState {
285 None297 None
286 }298 }
287 }299 }
300+
301+impl EventStreamStatePart for CastsState {
302+ fn replicate(&self) -> Vec<Event> {
303+ let casts = self.casts.values().cloned().collect();
304+ vec![Event::CastsChanged { casts }]
305+ }
306+
307+ fn apply(&mut self, event: Event) -> Option<Event> {
308+ match event {
309+ Event::CastsChanged { casts } => {
310+ self.casts = casts.into_iter().map(|c| (c.stream_id, c)).collect();
311+ }
312+ Event::CastStartedOrChanged { cast } => {
313+ self.casts.insert(cast.stream_id, cast);
314+ }
315+ Event::CastStopped { stream_id } => {
316+ let cast = self.casts.remove(&stream_id);
317+ cast.expect("stopped cast was missing from the map");
318+ }
319+ event => return Some(event),
320+ }
321+ None
322+ }
323+}
src/cli.rsmodified+2 -0
@@ -107,6 +107,8 @@ pub enum Msg {
107 RequestError,107 RequestError,
108 /// Print the overview state.108 /// Print the overview state.
109 OverviewState,109 OverviewState,
110+ /// List screencasts.
111+ Casts,
110 }112 }
111 113
112 #[derive(Clone, Debug, clap::ValueEnum)]114 #[derive(Clone, Debug, clap::ValueEnum)]
src/ipc/client.rsmodified+56 -2
@@ -7,8 +7,8 @@ use anyhow::{anyhow, bail, Context};
7 use niri_config::OutputName;7 use niri_config::OutputName;
8 use niri_ipc::socket::Socket;8 use niri_ipc::socket::Socket;
9 use niri_ipc::{9 use niri_ipc::{
10- Action, Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Overview,10+ Action, Cast, CastTarget, Event, KeyboardLayouts, LogicalOutput, Mode, Output,
11- Request, Response, Transform, Window, WindowLayout,11+ OutputConfigChanged, Overview, Request, Response, Transform, Window, WindowLayout,
12 };12 };
13 use serde_json::json;13 use serde_json::json;
14 14
@@ -48,6 +48,7 @@ pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
48 Msg::EventStream => Request::EventStream,48 Msg::EventStream => Request::EventStream,
49 Msg::RequestError => Request::ReturnError,49 Msg::RequestError => Request::ReturnError,
50 Msg::OverviewState => Request::OverviewState,50 Msg::OverviewState => Request::OverviewState,
51+ Msg::Casts => Request::Casts,
51 };52 };
52 53
53 let mut socket = Socket::connect().context("error connecting to the niri socket")?;54 let mut socket = Socket::connect().context("error connecting to the niri socket")?;
@@ -496,6 +497,15 @@ pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
496 let description = parts.join(" and ");497 let description = parts.join(" and ");
497 println!("Screenshot captured: {description}");498 println!("Screenshot captured: {description}");
498 }499 }
500+ Event::CastsChanged { casts } => {
501+ println!("Casts changed: {casts:?}");
502+ }
503+ Event::CastStartedOrChanged { cast } => {
504+ println!("Cast started or changed: {cast:?}");
505+ }
506+ Event::CastStopped { stream_id } => {
507+ println!("Cast stopped: stream id {stream_id}");
508+ }
499 }509 }
500 }510 }
501 }511 }
@@ -518,6 +528,28 @@ pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
518 println!("Overview is closed.");528 println!("Overview is closed.");
519 }529 }
520 }530 }
531+ Msg::Casts => {
532+ let Response::Casts(mut casts) = response else {
533+ bail!("unexpected response: expected Casts, got {response:?}");
534+ };
535+
536+ if json {
537+ let casts = serde_json::to_string(&casts).context("error formatting response")?;
538+ println!("{casts}");
539+ return Ok(());
540+ }
541+
542+ if casts.is_empty() {
543+ println!("No screencasts.");
544+ return Ok(());
545+ }
546+
547+ casts.sort_by_key(|c| (c.session_id, c.stream_id));
548+ for cast in casts {
549+ print_cast(&cast);
550+ println!();
551+ }
552+ }
521 }553 }
522 554
523 Ok(())555 Ok(())
@@ -706,6 +738,28 @@ fn print_window(window: &Window) {
706 );738 );
707 }739 }
708 740
741+fn print_cast(cast: &Cast) {
742+ let active = if cast.is_active { "" } else { " (inactive)" };
743+ println!("Cast stream ID {}:{active}", cast.stream_id);
744+ println!(" Session ID: {}", cast.session_id);
745+
746+ match &cast.target {
747+ CastTarget::Nothing {} => {
748+ println!(" Target: nothing (cleared)");
749+ }
750+ CastTarget::Output { name } => {
751+ println!(" Target: output \"{name}\"");
752+ }
753+ CastTarget::Window { id } => {
754+ println!(" Target: window {id}");
755+ }
756+ }
757+
758+ if cast.is_dynamic_target {
759+ println!(" Dynamic cast target");
760+ }
761+}
762+
709 fn fmt_rounded(x: f64) -> String {763 fn fmt_rounded(x: f64) -> String {
710 let r = x.round();764 let r = x.round();
711 if (r - x).abs() <= 0.005 {765 if (r - x).abs() <= 0.005 {
src/ipc/server.rsmodified+73 -0
@@ -450,6 +450,11 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
450 let is_open = state.overview.is_open;450 let is_open = state.overview.is_open;
451 Response::OverviewState(Overview { is_open })451 Response::OverviewState(Overview { is_open })
452 }452 }
453+ Request::Casts => {
454+ let state = ctx.event_stream_state.borrow();
455+ let casts = state.casts.casts.values().cloned().collect();
456+ Response::Casts(casts)
457+ }
453 };458 };
454 459
455 Ok(response)460 Ok(response)
@@ -793,6 +798,74 @@ impl State {
793 server.send_event(event);798 server.send_event(event);
794 }799 }
795 800
801+ #[cfg(feature = "xdp-gnome-screencast")]
802+ pub fn ipc_refresh_casts(&mut self) {
803+ let Some(server) = &self.niri.ipc_server else {
804+ return;
805+ };
806+
807+ let _span = tracy_client::span!("State::ipc_refresh_casts");
808+
809+ let mut state = server.event_stream_state.borrow_mut();
810+ let state = &mut state.casts;
811+
812+ let mut events = Vec::new();
813+ let mut seen = HashSet::new();
814+
815+ // Check pending dynamic casts.
816+ for pending in &self.niri.casting.pending_dynamic_casts {
817+ let stream_id = pending.stream_id.get();
818+ seen.insert(stream_id);
819+
820+ // Pending dynamic casts don't change any properties, so we only need to check if it's
821+ // missing from the state.
822+ if !state.casts.contains_key(&stream_id) {
823+ let cast = niri_ipc::Cast {
824+ session_id: pending.session_id.get(),
825+ stream_id,
826+ target: niri_ipc::CastTarget::Nothing {},
827+ is_dynamic_target: true,
828+ is_active: false,
829+ };
830+ events.push(Event::CastStartedOrChanged { cast });
831+ }
832+ }
833+
834+ // Check active casts.
835+ for cast in &self.niri.casting.casts {
836+ let stream_id = cast.stream_id.get();
837+ seen.insert(stream_id);
838+
839+ if state.casts.get(&stream_id).is_none_or(|existing| {
840+ // Only these properties can change.
841+ existing.is_active != cast.is_active() || !cast.target.matches(&existing.target)
842+ }) {
843+ let cast = niri_ipc::Cast {
844+ session_id: cast.session_id.get(),
845+ stream_id,
846+ target: cast.target.make_ipc(),
847+ is_dynamic_target: cast.dynamic_target,
848+ is_active: cast.is_active(),
849+ };
850+ events.push(Event::CastStartedOrChanged { cast });
851+ }
852+ }
853+
854+ // Check for stopped casts.
855+ for stream_id in state.casts.keys() {
856+ if !seen.contains(stream_id) {
857+ events.push(Event::CastStopped {
858+ stream_id: *stream_id,
859+ });
860+ }
861+ }
862+
863+ for event in events {
864+ state.apply(event.clone());
865+ server.send_event(event);
866+ }
867+ }
868+
796 pub fn ipc_config_loaded(&mut self, failed: bool) {869 pub fn ipc_config_loaded(&mut self, failed: bool) {
797 let Some(server) = &self.niri.ipc_server else {870 let Some(server) = &self.niri.ipc_server else {
798 return;871 return;
src/niri.rsmodified+23 -0
@@ -592,6 +592,27 @@ impl CastTarget {
592 pub fn matches_output(&self, weak: &WeakOutput) -> bool {592 pub fn matches_output(&self, weak: &WeakOutput) -> bool {
593 matches!(self, CastTarget::Output { output, .. } if output == weak)593 matches!(self, CastTarget::Output { output, .. } if output == weak)
594 }594 }
595+
596+ pub fn matches(&self, ipc: &niri_ipc::CastTarget) -> bool {
597+ use CastTarget::*;
598+ match (self, ipc) {
599+ (Nothing, niri_ipc::CastTarget::Nothing {}) => true,
600+ (Output { name, .. }, niri_ipc::CastTarget::Output { name: ipc_name }) => {
601+ name == ipc_name
602+ }
603+ (Window { id }, niri_ipc::CastTarget::Window { id: ipc_id }) => id == ipc_id,
604+ _ => false,
605+ }
606+ }
607+
608+ pub fn make_ipc(&self) -> niri_ipc::CastTarget {
609+ use CastTarget::*;
610+ match self {
611+ Nothing => niri_ipc::CastTarget::Nothing {},
612+ Output { name, .. } => niri_ipc::CastTarget::Output { name: name.clone() },
613+ Window { id } => niri_ipc::CastTarget::Window { id: *id },
614+ }
615+ }
595 }616 }
596 617
597 /// Pending update to a window's focus timestamp.618 /// Pending update to a window's focus timestamp.
@@ -795,6 +816,8 @@ impl State {
795 // screencasts.816 // screencasts.
796 #[cfg(feature = "xdp-gnome-screencast")]817 #[cfg(feature = "xdp-gnome-screencast")]
797 self.niri.refresh_mapped_cast_window_rules();818 self.niri.refresh_mapped_cast_window_rules();
819+ #[cfg(feature = "xdp-gnome-screencast")]
820+ self.ipc_refresh_casts();
798 821
799 self.niri.refresh_window_rules();822 self.niri.refresh_window_rules();
800 self.refresh_ipc_outputs();823 self.refresh_ipc_outputs();