forge
Explore
Log in

Don't you dare go Hollow

Implement the event stream IPC

Browse files at this commit

30b213601a4f71d65a2227fa68ffb1ab2a69f671Ivan MolodetskikhParent: 8eb34b2
niri-ipc/src/lib.rsmodified+98 -0
@@ -9,6 +9,8 @@ use serde::{Deserialize, Serialize};
99 mod socket;
1010 pub use socket::{Socket, SOCKET_PATH_ENV};
1111
12+pub mod state;
13+
1214 /// Request from client to niri.
1315 #[derive(Debug, Serialize, Deserialize, Clone)]
1416 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
@@ -38,6 +40,11 @@ pub enum Request {
3840 FocusedOutput,
3941 /// Request information about the keyboard layout.
4042 KeyboardLayouts,
43+ /// Start continuously receiving events from the compositor.
44+ ///
45+ /// The compositor should reply with `Reply::Ok(Response::Handled)`, then continuously send
46+ /// [`Event`]s, one per line.
47+ EventStream,
4148 /// Respond with an error (for testing error handling).
4249 ReturnError,
4350 }
@@ -536,10 +543,18 @@ pub enum Transform {
536543 #[derive(Serialize, Deserialize, Debug, Clone)]
537544 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
538545 pub struct Window {
546+ /// Unique id of this window.
547+ pub id: u64,
539548 /// Title, if set.
540549 pub title: Option<String>,
541550 /// Application ID, if set.
542551 pub app_id: Option<String>,
552+ /// Id of the workspace this window is on, if any.
553+ pub workspace_id: Option<u64>,
554+ /// Whether this window is currently focused.
555+ ///
556+ /// There can be either one focused window or zero (e.g. when a layer-shell surface has focus).
557+ pub is_focused: bool,
543558 }
544559
545560 /// Output configuration change result.
@@ -556,6 +571,10 @@ pub enum OutputConfigChanged {
556571 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
557572 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
558573 pub struct Workspace {
574+ /// Unique id of this workspace.
575+ ///
576+ /// This id remains constant regardless of the workspace moving around and across monitors.
577+ pub id: u64,
559578 /// Index of the workspace on its monitor.
560579 ///
561580 /// This is the same index you can use for requests like `niri msg action focus-workspace`.
@@ -567,7 +586,15 @@ pub struct Workspace {
567586 /// Can be `None` if no outputs are currently connected.
568587 pub output: Option<String>,
569588 /// Whether the workspace is currently active on its output.
589+ ///
590+ /// Every output has one active workspace, the one that is currently visible on that output.
570591 pub is_active: bool,
592+ /// Whether the workspace is currently focused.
593+ ///
594+ /// There's only one focused workspace across all outputs.
595+ pub is_focused: bool,
596+ /// Id of the active window on this workspace, if any.
597+ pub active_window_id: Option<u64>,
571598 }
572599
573600 /// Configured keyboard layouts.
@@ -580,6 +607,77 @@ pub struct KeyboardLayouts {
580607 pub current_idx: u8,
581608 }
582609
610+/// A compositor event.
611+#[derive(Serialize, Deserialize, Debug, Clone)]
612+#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
613+pub enum Event {
614+ /// The workspace configuration has changed.
615+ WorkspacesChanged {
616+ /// The new workspace configuration.
617+ ///
618+ /// This configuration completely replaces the previous configuration. I.e. if any
619+ /// workspaces are missing from here, then they were deleted.
620+ workspaces: Vec<Workspace>,
621+ },
622+ /// A workspace was activated on an output.
623+ ///
624+ /// This doesn't always mean the workspace became focused, just that it's now the active
625+ /// workspace on its output. All other workspaces on the same output become inactive.
626+ WorkspaceActivated {
627+ /// Id of the newly active workspace.
628+ id: u64,
629+ /// Whether this workspace also became focused.
630+ ///
631+ /// If `true`, this is now the single focused workspace. All other workspaces are no longer
632+ /// focused, but they may remain active on their respective outputs.
633+ focused: bool,
634+ },
635+ /// An active window changed on a workspace.
636+ WorkspaceActiveWindowChanged {
637+ /// Id of the workspace on which the active window changed.
638+ workspace_id: u64,
639+ /// Id of the new active window, if any.
640+ active_window_id: Option<u64>,
641+ },
642+ /// The window configuration has changed.
643+ WindowsChanged {
644+ /// The new window configuration.
645+ ///
646+ /// This configuration completely replaces the previous configuration. I.e. if any windows
647+ /// are missing from here, then they were closed.
648+ windows: Vec<Window>,
649+ },
650+ /// A new toplevel window was opened, or an existing toplevel window changed.
651+ WindowOpenedOrChanged {
652+ /// The new or updated window.
653+ ///
654+ /// If the window is focused, all other windows are no longer focused.
655+ window: Window,
656+ },
657+ /// A toplevel window was closed.
658+ WindowClosed {
659+ /// Id of the removed window.
660+ id: u64,
661+ },
662+ /// Window focus changed.
663+ ///
664+ /// All other windows are no longer focused.
665+ WindowFocusChanged {
666+ /// Id of the newly focused window, or `None` if no window is now focused.
667+ id: Option<u64>,
668+ },
669+ /// The configured keyboard layouts have changed.
670+ KeyboardLayoutsChanged {
671+ /// The new keyboard layout configuration.
672+ keyboard_layouts: KeyboardLayouts,
673+ },
674+ /// The keyboard layout switched.
675+ KeyboardLayoutSwitched {
676+ /// Index of the newly active layout.
677+ idx: u8,
678+ },
679+}
680+
583681 impl FromStr for WorkspaceReferenceArg {
584682 type Err = &'static str;
585683
niri-ipc/src/socket.rsmodified+15 -3
@@ -6,7 +6,7 @@ use std::net::Shutdown;
66 use std::os::unix::net::UnixStream;
77 use std::path::Path;
88
9-use crate::{Reply, Request};
9+use crate::{Event, Reply, Request};
1010
1111 /// Name of the environment variable containing the niri IPC socket path.
1212 pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";
@@ -47,7 +47,11 @@ impl Socket {
4747 /// * `Ok(Ok(response))`: successful [`Response`](crate::Response) from niri
4848 /// * `Ok(Err(message))`: error message from niri
4949 /// * `Err(error)`: error communicating with niri
50- pub fn send(self, request: Request) -> io::Result<Reply> {
50+ ///
51+ /// This method also returns a blocking function that you can call to keep reading [`Event`]s
52+ /// after requesting an [`EventStream`][Request::EventStream]. This function is not useful
53+ /// otherwise.
54+ pub fn send(self, request: Request) -> io::Result<(Reply, impl FnMut() -> io::Result<Event>)> {
5155 let Self { mut stream } = self;
5256
5357 let mut buf = serde_json::to_string(&request).unwrap();
@@ -60,6 +64,14 @@ impl Socket {
6064 reader.read_line(&mut buf)?;
6165
6266 let reply = serde_json::from_str(&buf)?;
63- Ok(reply)
67+
68+ let events = move || {
69+ buf.clear();
70+ reader.read_line(&mut buf)?;
71+ let event = serde_json::from_str(&buf)?;
72+ Ok(event)
73+ };
74+
75+ Ok((reply, events))
6476 }
6577 }
niri-ipc/src/state.rsadded+188 -0
@@ -0,0 +1,188 @@
1+//! Helpers for keeping track of the event stream state.
2+
3+use std::collections::hash_map::Entry;
4+use std::collections::HashMap;
5+
6+use crate::{Event, KeyboardLayouts, Window, Workspace};
7+
8+/// Part of the state communicated via the event stream.
9+pub trait EventStreamStatePart {
10+ /// Returns a sequence of events that replicates this state from default initialization.
11+ fn replicate(&self) -> Vec<Event>;
12+
13+ /// Applies the event to this state.
14+ ///
15+ /// Returns `None` after applying the event, and `Some(event)` if the event is ignored by this
16+ /// part of the state.
17+ fn apply(&mut self, event: Event) -> Option<Event>;
18+}
19+
20+/// The full state communicated over the event stream.
21+///
22+/// Different parts of the state are not guaranteed to be consistent across every single event
23+/// sent by niri. For example, you may receive the first [`Event::WindowOpenedOrChanged`] for a
24+/// just-opened window *after* an [`Event::WorkspaceActiveWindowChanged`] for that window. Between
25+/// these two events, the workspace active window id refers to a window that does not yet exist in
26+/// the windows state part.
27+#[derive(Debug, Default)]
28+pub struct EventStreamState {
29+ /// State of workspaces.
30+ pub workspaces: WorkspacesState,
31+
32+ /// State of workspaces.
33+ pub windows: WindowsState,
34+
35+ /// State of the keyboard layouts.
36+ pub keyboard_layouts: KeyboardLayoutsState,
37+}
38+
39+/// The workspaces state communicated over the event stream.
40+#[derive(Debug, Default)]
41+pub struct WorkspacesState {
42+ /// Map from a workspace id to the workspace.
43+ pub workspaces: HashMap<u64, Workspace>,
44+}
45+
46+/// The windows state communicated over the event stream.
47+#[derive(Debug, Default)]
48+pub struct WindowsState {
49+ /// Map from a window id to the window.
50+ pub windows: HashMap<u64, Window>,
51+}
52+
53+/// The keyboard layout state communicated over the event stream.
54+#[derive(Debug, Default)]
55+pub struct KeyboardLayoutsState {
56+ /// Configured keyboard layouts.
57+ pub keyboard_layouts: Option<KeyboardLayouts>,
58+}
59+
60+impl EventStreamStatePart for EventStreamState {
61+ fn replicate(&self) -> Vec<Event> {
62+ let mut events = Vec::new();
63+ events.extend(self.workspaces.replicate());
64+ events.extend(self.windows.replicate());
65+ events.extend(self.keyboard_layouts.replicate());
66+ events
67+ }
68+
69+ fn apply(&mut self, event: Event) -> Option<Event> {
70+ let event = self.workspaces.apply(event)?;
71+ let event = self.windows.apply(event)?;
72+ let event = self.keyboard_layouts.apply(event)?;
73+ Some(event)
74+ }
75+}
76+
77+impl EventStreamStatePart for WorkspacesState {
78+ fn replicate(&self) -> Vec<Event> {
79+ let workspaces = self.workspaces.values().cloned().collect();
80+ vec![Event::WorkspacesChanged { workspaces }]
81+ }
82+
83+ fn apply(&mut self, event: Event) -> Option<Event> {
84+ match event {
85+ Event::WorkspacesChanged { workspaces } => {
86+ self.workspaces = workspaces.into_iter().map(|ws| (ws.id, ws)).collect();
87+ }
88+ Event::WorkspaceActivated { id, focused } => {
89+ let ws = self.workspaces.get(&id);
90+ let ws = ws.expect("activated workspace was missing from the map");
91+ let output = ws.output.clone();
92+
93+ for ws in self.workspaces.values_mut() {
94+ let got_activated = ws.id == id;
95+ if ws.output == output {
96+ ws.is_active = got_activated;
97+ }
98+
99+ if focused {
100+ ws.is_focused = got_activated;
101+ }
102+ }
103+ }
104+ Event::WorkspaceActiveWindowChanged {
105+ workspace_id,
106+ active_window_id,
107+ } => {
108+ let ws = self.workspaces.get_mut(&workspace_id);
109+ let ws = ws.expect("changed workspace was missing from the map");
110+ ws.active_window_id = active_window_id;
111+ }
112+ event => return Some(event),
113+ }
114+ None
115+ }
116+}
117+
118+impl EventStreamStatePart for WindowsState {
119+ fn replicate(&self) -> Vec<Event> {
120+ let windows = self.windows.values().cloned().collect();
121+ vec![Event::WindowsChanged { windows }]
122+ }
123+
124+ fn apply(&mut self, event: Event) -> Option<Event> {
125+ match event {
126+ Event::WindowsChanged { windows } => {
127+ self.windows = windows.into_iter().map(|win| (win.id, win)).collect();
128+ }
129+ Event::WindowOpenedOrChanged { window } => {
130+ let (id, is_focused) = match self.windows.entry(window.id) {
131+ Entry::Occupied(mut entry) => {
132+ let entry = entry.get_mut();
133+ *entry = window;
134+ (entry.id, entry.is_focused)
135+ }
136+ Entry::Vacant(entry) => {
137+ let entry = entry.insert(window);
138+ (entry.id, entry.is_focused)
139+ }
140+ };
141+
142+ if is_focused {
143+ for win in self.windows.values_mut() {
144+ if win.id != id {
145+ win.is_focused = false;
146+ }
147+ }
148+ }
149+ }
150+ Event::WindowClosed { id } => {
151+ let win = self.windows.remove(&id);
152+ win.expect("closed window was missing from the map");
153+ }
154+ Event::WindowFocusChanged { id } => {
155+ for win in self.windows.values_mut() {
156+ win.is_focused = Some(win.id) == id;
157+ }
158+ }
159+ event => return Some(event),
160+ }
161+ None
162+ }
163+}
164+
165+impl EventStreamStatePart for KeyboardLayoutsState {
166+ fn replicate(&self) -> Vec<Event> {
167+ if let Some(keyboard_layouts) = self.keyboard_layouts.clone() {
168+ vec![Event::KeyboardLayoutsChanged { keyboard_layouts }]
169+ } else {
170+ vec![]
171+ }
172+ }
173+
174+ fn apply(&mut self, event: Event) -> Option<Event> {
175+ match event {
176+ Event::KeyboardLayoutsChanged { keyboard_layouts } => {
177+ self.keyboard_layouts = Some(keyboard_layouts);
178+ }
179+ Event::KeyboardLayoutSwitched { idx } => {
180+ let kb = self.keyboard_layouts.as_mut();
181+ let kb = kb.expect("keyboard layouts must be set before a layout can be switched");
182+ kb.current_idx = idx;
183+ }
184+ event => return Some(event),
185+ }
186+ None
187+ }
188+}
src/cli.rsmodified+2 -0
@@ -88,6 +88,8 @@ pub enum Msg {
8888 },
8989 /// Get the configured keyboard layouts.
9090 KeyboardLayouts,
91+ /// Start continuously receiving events from the compositor.
92+ EventStream,
9193 /// Print the version of the running niri instance.
9294 Version,
9395 /// Request an error from the running niri instance.
src/input/mod.rsmodified+11 -6
@@ -16,7 +16,7 @@ use smithay::backend::input::{
1616 TabletToolProximityEvent, TabletToolTipEvent, TabletToolTipState, TouchEvent,
1717 };
1818 use smithay::backend::libinput::LibinputInputBackend;
19-use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState};
19+use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState, XkbContextHandler};
2020 use smithay::input::pointer::{
2121 AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent,
2222 GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
@@ -539,13 +539,18 @@ impl State {
539539 }
540540 }
541541 Action::SwitchLayout(action) => {
542- self.niri.seat.get_keyboard().unwrap().with_xkb_state(
543- self,
544- |mut state| match action {
542+ let keyboard = &self.niri.seat.get_keyboard().unwrap();
543+ let new_idx = keyboard.with_xkb_state(self, |mut state| {
544+ match action {
545545 LayoutSwitchTarget::Next => state.cycle_next_layout(),
546546 LayoutSwitchTarget::Prev => state.cycle_prev_layout(),
547- },
548- );
547+ };
548+ state.active_layout().0
549+ });
550+
551+ if let Some(server) = &self.niri.ipc_server {
552+ server.keyboard_layout_switched(new_idx as u8);
553+ }
549554 }
550555 Action::MoveColumnLeft => {
551556 self.niri.layout.move_left();
src/ipc/client.rsmodified+61 -3
@@ -1,7 +1,7 @@
11 use anyhow::{anyhow, bail, Context};
22 use niri_ipc::{
3- KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Request, Response, Socket,
4- Transform,
3+ Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Request, Response,
4+ Socket, Transform,
55 };
66 use serde_json::json;
77
@@ -21,12 +21,13 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
2121 },
2222 Msg::Workspaces => Request::Workspaces,
2323 Msg::KeyboardLayouts => Request::KeyboardLayouts,
24+ Msg::EventStream => Request::EventStream,
2425 Msg::RequestError => Request::ReturnError,
2526 };
2627
2728 let socket = Socket::connect().context("error connecting to the niri socket")?;
2829
29- let reply = socket
30+ let (reply, mut read_event) = socket
3031 .send(request)
3132 .context("error communicating with niri")?;
3233
@@ -37,6 +38,7 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
3738 Socket::connect()
3839 .and_then(|socket| socket.send(Request::Version))
3940 .ok()
41+ .map(|(reply, _read_event)| reply)
4042 }
4143 _ => None,
4244 };
@@ -261,6 +263,62 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
261263 println!("{is_active}{idx} {name}");
262264 }
263265 }
266+ Msg::EventStream => {
267+ let Response::Handled = response else {
268+ bail!("unexpected response: expected Handled, got {response:?}");
269+ };
270+
271+ if !json {
272+ println!("Started reading events.");
273+ }
274+
275+ loop {
276+ let event = read_event().context("error reading event from niri")?;
277+
278+ if json {
279+ let event = serde_json::to_string(&event).context("error formatting event")?;
280+ println!("{event}");
281+ continue;
282+ }
283+
284+ match event {
285+ Event::WorkspacesChanged { workspaces } => {
286+ println!("Workspaces changed: {workspaces:?}");
287+ }
288+ Event::WorkspaceActivated { id, focused } => {
289+ let word = if focused { "focused" } else { "activated" };
290+ println!("Workspace {word}: {id}");
291+ }
292+ Event::WorkspaceActiveWindowChanged {
293+ workspace_id,
294+ active_window_id,
295+ } => {
296+ println!(
297+ "Workspace {workspace_id}: \
298+ active window changed to {active_window_id:?}"
299+ );
300+ }
301+ Event::WindowsChanged { windows } => {
302+ println!("Windows changed: {windows:?}");
303+ }
304+ Event::WindowOpenedOrChanged { window } => {
305+ println!("Window opened or changed: {window:?}");
306+ }
307+ Event::WindowClosed { id } => {
308+ println!("Window closed: {id}");
309+ }
310+ Event::WindowFocusChanged { id } => {
311+ println!("Window focus changed: {id:?}");
312+ }
313+ Event::KeyboardLayoutsChanged { keyboard_layouts } => {
314+ println!("Keyboard layouts changed: {keyboard_layouts:?}");
315+ }
316+ Event::KeyboardLayoutSwitched { idx } => {
317+ println!("Keyboard layout switched: {idx}");
318+ }
319+ }
320+ }
321+ }
264322 }
265323
266324 Ok(())
src/ipc/server.rsmodified+371 -45
@@ -1,15 +1,20 @@
1+use std::cell::RefCell;
2+use std::collections::HashSet;
13 use std::os::unix::net::{UnixListener, UnixStream};
24 use std::path::PathBuf;
5+use std::rc::Rc;
36 use std::sync::{Arc, Mutex};
47 use std::{env, io, process};
58
69 use anyhow::Context;
10+use async_channel::{Receiver, Sender, TrySendError};
11+use calloop::futures::Scheduler;
712 use calloop::io::Async;
813 use directories::BaseDirs;
914 use futures_util::io::{AsyncReadExt, BufReader};
10-use futures_util::{AsyncBufReadExt, AsyncWriteExt};
11-use niri_ipc::{KeyboardLayouts, OutputConfigChanged, Reply, Request, Response};
12-use smithay::desktop::Window;
15+use futures_util::{select_biased, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, FutureExt as _};
16+use niri_ipc::state::{EventStreamState, EventStreamStatePart as _};
17+use niri_ipc::{Event, KeyboardLayouts, OutputConfigChanged, Reply, Request, Response, Workspace};
1318 use smithay::input::keyboard::XkbContextHandler;
1419 use smithay::reexports::calloop::generic::Generic;
1520 use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
@@ -18,17 +23,38 @@ use smithay::wayland::compositor::with_states;
1823 use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;
1924
2025 use crate::backend::IpcOutputMap;
26+use crate::layout::workspace::WorkspaceId;
2127 use crate::niri::State;
2228 use crate::utils::version;
29+use crate::window::Mapped;
30+
31+// If an event stream client fails to read events fast enough that we accumulate more than this
32+// number in our buffer, we drop that event stream client.
33+const EVENT_STREAM_BUFFER_SIZE: usize = 64;
2334
2435 pub struct IpcServer {
2536 pub socket_path: PathBuf,
37+ event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
38+ event_stream_state: Rc<RefCell<EventStreamState>>,
2639 }
2740
2841 struct ClientCtx {
2942 event_loop: LoopHandle<'static, State>,
43+ scheduler: Scheduler<()>,
3044 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
31- ipc_focused_window: Arc<Mutex<Option<Window>>>,
45+ event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
46+ event_stream_state: Rc<RefCell<EventStreamState>>,
47+}
48+
49+struct EventStreamClient {
50+ events: Receiver<Event>,
51+ disconnect: Receiver<()>,
52+ write: Box<dyn AsyncWrite + Unpin>,
53+}
54+
55+struct EventStreamSender {
56+ events: Sender<Event>,
57+ disconnect: Sender<()>,
3258 }
3359
3460 impl IpcServer {
@@ -60,7 +86,43 @@ impl IpcServer {
6086 })
6187 .unwrap();
6288
63- Ok(Self { socket_path })
89+ Ok(Self {
90+ socket_path,
91+ event_streams: Rc::new(RefCell::new(Vec::new())),
92+ event_stream_state: Rc::new(RefCell::new(EventStreamState::default())),
93+ })
94+ }
95+
96+ fn send_event(&self, event: Event) {
97+ let mut streams = self.event_streams.borrow_mut();
98+ let mut to_remove = Vec::new();
99+ for (idx, stream) in streams.iter_mut().enumerate() {
100+ match stream.events.try_send(event.clone()) {
101+ Ok(()) => (),
102+ Err(TrySendError::Closed(_)) => to_remove.push(idx),
103+ Err(TrySendError::Full(_)) => {
104+ warn!(
105+ "disconnecting IPC event stream client \
106+ because it is reading events too slowly"
107+ );
108+ to_remove.push(idx);
109+ }
110+ }
111+ }
112+
113+ for idx in to_remove.into_iter().rev() {
114+ let stream = streams.swap_remove(idx);
115+ let _ = stream.disconnect.send_blocking(());
116+ }
117+ }
118+
119+ pub fn keyboard_layout_switched(&self, new_idx: u8) {
120+ let mut state = self.event_stream_state.borrow_mut();
121+ let state = &mut state.keyboard_layouts;
122+
123+ let event = Event::KeyboardLayoutSwitched { idx: new_idx };
124+ state.apply(event.clone());
125+ self.send_event(event);
64126 }
65127 }
66128
@@ -90,10 +152,14 @@ fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
90152 }
91153 };
92154
155+ let ipc_server = state.niri.ipc_server.as_ref().unwrap();
156+
93157 let ctx = ClientCtx {
94158 event_loop: state.niri.event_loop.clone(),
159+ scheduler: state.niri.scheduler.clone(),
95160 ipc_outputs: state.backend.ipc_outputs(),
96- ipc_focused_window: state.niri.ipc_focused_window.clone(),
161+ event_streams: ipc_server.event_streams.clone(),
162+ event_stream_state: ipc_server.event_stream_state.clone(),
97163 };
98164
99165 let future = async move {
@@ -106,7 +172,7 @@ fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
106172 }
107173 }
108174
109-async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow::Result<()> {
175+async fn handle_client(ctx: ClientCtx, stream: Async<'static, UnixStream>) -> anyhow::Result<()> {
110176 let (read, mut write) = stream.split();
111177 let mut buf = String::new();
112178
@@ -120,6 +186,7 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
120186 .context("error parsing request")
121187 .map_err(|err| err.to_string());
122188 let requested_error = matches!(request, Ok(Request::ReturnError));
189+ let requested_event_stream = matches!(request, Ok(Request::EventStream));
123190
124191 let reply = match request {
125192 Ok(request) => process(&ctx, request).await,
@@ -136,6 +203,46 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
136203 buf.push(b'\n');
137204 write.write_all(&buf).await.context("error writing reply")?;
138205
206+ if requested_event_stream {
207+ let (events_tx, events_rx) = async_channel::bounded(EVENT_STREAM_BUFFER_SIZE);
208+ let (disconnect_tx, disconnect_rx) = async_channel::bounded(1);
209+
210+ // Spawn a task for the client.
211+ let client = EventStreamClient {
212+ events: events_rx,
213+ disconnect: disconnect_rx,
214+ write: Box::new(write) as _,
215+ };
216+ let future = async move {
217+ if let Err(err) = handle_event_stream_client(client).await {
218+ warn!("error handling IPC event stream client: {err:?}");
219+ }
220+ };
221+ if let Err(err) = ctx.scheduler.schedule(future) {
222+ warn!("error scheduling IPC event stream future: {err:?}");
223+ }
224+
225+ // Send the initial state.
226+ {
227+ let state = ctx.event_stream_state.borrow();
228+ for event in state.replicate() {
229+ events_tx
230+ .try_send(event)
231+ .expect("initial event burst had more events than buffer size");
232+ }
233+ }
234+
235+ // Add it to the list.
236+ {
237+ let mut streams = ctx.event_streams.borrow_mut();
238+ let sender = EventStreamSender {
239+ events: events_tx,
240+ disconnect: disconnect_tx,
241+ };
242+ streams.push(sender);
243+ }
244+ }
245+
139246 Ok(())
140247 }
141248
@@ -149,23 +256,9 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
149256 Response::Outputs(outputs.collect())
150257 }
151258 Request::FocusedWindow => {
152- let window = ctx.ipc_focused_window.lock().unwrap().clone();
153- let window = window.map(|window| {
154- let wl_surface = window.toplevel().expect("no X11 support").wl_surface();
155- with_states(wl_surface, |states| {
156- let role = states
157- .data_map
158- .get::<XdgToplevelSurfaceData>()
159- .unwrap()
160- .lock()
161- .unwrap();
162-
163- niri_ipc::Window {
164- title: role.title.clone(),
165- app_id: role.app_id.clone(),
166- }
167- })
168- });
259+ let state = ctx.event_stream_state.borrow();
260+ let windows = &state.windows.windows;
261+ let window = windows.values().find(|win| win.is_focused).cloned();
169262 Response::FocusedWindow(window)
170263 }
171264 Request::Action(action) => {
@@ -202,13 +295,8 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
202295 Response::OutputConfigChanged(response)
203296 }
204297 Request::Workspaces => {
205- let (tx, rx) = async_channel::bounded(1);
206- ctx.event_loop.insert_idle(move |state| {
207- let workspaces = state.niri.layout.ipc_workspaces();
208- let _ = tx.send_blocking(workspaces);
209- });
210- let result = rx.recv().await;
211- let workspaces = result.map_err(|_| String::from("error getting workspace info"))?;
298+ let state = ctx.event_stream_state.borrow();
299+ let workspaces = state.workspaces.workspaces.values().cloned().collect();
212300 Response::Workspaces(workspaces)
213301 }
214302 Request::FocusedOutput => {
@@ -238,23 +326,261 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
238326 Response::FocusedOutput(output)
239327 }
240328 Request::KeyboardLayouts => {
241- let (tx, rx) = async_channel::bounded(1);
242- ctx.event_loop.insert_idle(move |state| {
243- let keyboard = state.niri.seat.get_keyboard().unwrap();
244- let layout = keyboard.with_xkb_state(state, |context| {
245- let layouts = context.keymap().layouts();
246- KeyboardLayouts {
247- names: layouts.map(str::to_owned).collect(),
248- current_idx: context.active_layout().0 as u8,
249- }
250- });
251- let _ = tx.send_blocking(layout);
252- });
253- let result = rx.recv().await;
254- let layout = result.map_err(|_| String::from("error getting layout info"))?;
329+ let state = ctx.event_stream_state.borrow();
330+ let layout = state.keyboard_layouts.keyboard_layouts.clone();
331+ let layout = layout.expect("keyboard layouts should be set at startup");
255332 Response::KeyboardLayouts(layout)
256333 }
334+ Request::EventStream => Response::Handled,
257335 };
258336
259337 Ok(response)
260338 }
339+
340+async fn handle_event_stream_client(client: EventStreamClient) -> anyhow::Result<()> {
341+ let EventStreamClient {
342+ events,
343+ disconnect,
344+ mut write,
345+ } = client;
346+
347+ while let Ok(event) = events.recv().await {
348+ let mut buf = serde_json::to_vec(&event).context("error formatting event")?;
349+ buf.push(b'\n');
350+
351+ let res = select_biased! {
352+ _ = disconnect.recv().fuse() => return Ok(()),
353+ res = write.write_all(&buf).fuse() => res,
354+ };
355+
356+ match res {
357+ Ok(()) => (),
358+ // Normal client disconnection.
359+ Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
360+ res @ Err(_) => res.context("error writing event")?,
361+ }
362+ }
363+
364+ Ok(())
365+}
366+
367+fn make_ipc_window(mapped: &Mapped, workspace_id: Option<WorkspaceId>) -> niri_ipc::Window {
368+ let wl_surface = mapped.toplevel().wl_surface();
369+ with_states(wl_surface, |states| {
370+ let role = states
371+ .data_map
372+ .get::<XdgToplevelSurfaceData>()
373+ .unwrap()
374+ .lock()
375+ .unwrap();
376+
377+ niri_ipc::Window {
378+ id: u64::from(mapped.id().get()),
379+ title: role.title.clone(),
380+ app_id: role.app_id.clone(),
381+ workspace_id: workspace_id.map(|id| u64::from(id.0)),
382+ is_focused: mapped.is_focused(),
383+ }
384+ })
385+}
386+
387+impl State {
388+ pub fn ipc_keyboard_layouts_changed(&mut self) {
389+ let keyboard = self.niri.seat.get_keyboard().unwrap();
390+ let keyboard_layouts = keyboard.with_xkb_state(self, |context| {
391+ let layouts = context.keymap().layouts();
392+ KeyboardLayouts {
393+ names: layouts.map(str::to_owned).collect(),
394+ current_idx: context.active_layout().0 as u8,
395+ }
396+ });
397+
398+ let Some(server) = &self.niri.ipc_server else {
399+ return;
400+ };
401+
402+ let mut state = server.event_stream_state.borrow_mut();
403+ let state = &mut state.keyboard_layouts;
404+
405+ let event = Event::KeyboardLayoutsChanged { keyboard_layouts };
406+ state.apply(event.clone());
407+ server.send_event(event);
408+ }
409+
410+ pub fn ipc_refresh_layout(&mut self) {
411+ self.ipc_refresh_workspaces();
412+ self.ipc_refresh_windows();
413+ }
414+
415+ fn ipc_refresh_workspaces(&mut self) {
416+ let Some(server) = &self.niri.ipc_server else {
417+ return;
418+ };
419+
420+ let _span = tracy_client::span!("State::ipc_refresh_workspaces");
421+
422+ let mut state = server.event_stream_state.borrow_mut();
423+ let state = &mut state.workspaces;
424+
425+ let mut events = Vec::new();
426+ let layout = &self.niri.layout;
427+ let focused_ws_id = layout.active_workspace().map(|ws| u64::from(ws.id().0));
428+
429+ // Check for workspace changes.
430+ let mut seen = HashSet::new();
431+ let mut need_workspaces_changed = false;
432+ for (mon, ws_idx, ws) in layout.workspaces() {
433+ let id = u64::from(ws.id().0);
434+ seen.insert(id);
435+
436+ let Some(ipc_ws) = state.workspaces.get(&id) else {
437+ // A new workspace was added.
438+ need_workspaces_changed = true;
439+ break;
440+ };
441+
442+ // Check for any changes that we can't signal as individual events.
443+ let output_name = mon.map(|mon| mon.output_name());
444+ if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
445+ || ipc_ws.name != ws.name
446+ || ipc_ws.output.as_ref() != output_name
447+ {
448+ need_workspaces_changed = true;
449+ break;
450+ }
451+
452+ let active_window_id = ws.active_window().map(|win| u64::from(win.id().get()));
453+ if ipc_ws.active_window_id != active_window_id {
454+ events.push(Event::WorkspaceActiveWindowChanged {
455+ workspace_id: id,
456+ active_window_id,
457+ });
458+ }
459+
460+ // Check if this workspace became focused.
461+ let is_focused = Some(id) == focused_ws_id;
462+ if is_focused && !ipc_ws.is_focused {
463+ events.push(Event::WorkspaceActivated { id, focused: true });
464+ continue;
465+ }
466+
467+ // Check if this workspace became active.
468+ let is_active = mon.map_or(false, |mon| mon.active_workspace_idx == ws_idx);
469+ if is_active && !ipc_ws.is_active {
470+ events.push(Event::WorkspaceActivated { id, focused: false });
471+ }
472+ }
473+
474+ // Check if any workspaces were removed.
475+ if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
476+ need_workspaces_changed = true;
477+ }
478+
479+ if need_workspaces_changed {
480+ events.clear();
481+
482+ let workspaces = layout
483+ .workspaces()
484+ .map(|(mon, ws_idx, ws)| {
485+ let id = u64::from(ws.id().0);
486+ Workspace {
487+ id,
488+ idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
489+ name: ws.name.clone(),
490+ output: mon.map(|mon| mon.output_name().clone()),
491+ is_active: mon.map_or(false, |mon| mon.active_workspace_idx == ws_idx),
492+ is_focused: Some(id) == focused_ws_id,
493+ active_window_id: ws.active_window().map(|win| u64::from(win.id().get())),
494+ }
495+ })
496+ .collect();
497+
498+ events.push(Event::WorkspacesChanged { workspaces });
499+ }
500+
501+ for event in events {
502+ state.apply(event.clone());
503+ server.send_event(event);
504+ }
505+ }
506+
507+ fn ipc_refresh_windows(&mut self) {
508+ let Some(server) = &self.niri.ipc_server else {
509+ return;
510+ };
511+
512+ let _span = tracy_client::span!("State::ipc_refresh_windows");
513+
514+ let mut state = server.event_stream_state.borrow_mut();
515+ let state = &mut state.windows;
516+
517+ let mut events = Vec::new();
518+ let layout = &self.niri.layout;
519+
520+ // Check for window changes.
521+ let mut seen = HashSet::new();
522+ let mut focused_id = None;
523+ layout.with_windows(|mapped, _, ws_id| {
524+ let id = u64::from(mapped.id().get());
525+ seen.insert(id);
526+
527+ if mapped.is_focused() {
528+ focused_id = Some(id);
529+ }
530+
531+ let Some(ipc_win) = state.windows.get(&id) else {
532+ let window = make_ipc_window(mapped, Some(ws_id));
533+ events.push(Event::WindowOpenedOrChanged { window });
534+ return;
535+ };
536+
537+ let workspace_id = Some(u64::from(ws_id.0));
538+ let mut changed = ipc_win.workspace_id != workspace_id;
539+
540+ let wl_surface = mapped.toplevel().wl_surface();
541+ changed |= with_states(wl_surface, |states| {
542+ let role = states
543+ .data_map
544+ .get::<XdgToplevelSurfaceData>()
545+ .unwrap()
546+ .lock()
547+ .unwrap();
548+
549+ ipc_win.title != role.title || ipc_win.app_id != role.app_id
550+ });
551+
552+ if changed {
553+ let window = make_ipc_window(mapped, Some(ws_id));
554+ events.push(Event::WindowOpenedOrChanged { window });
555+ return;
556+ }
557+
558+ if mapped.is_focused() && !ipc_win.is_focused {
559+ events.push(Event::WindowFocusChanged { id: Some(id) });
560+ }
561+ });
562+
563+ // Check for closed windows.
564+ let mut ipc_focused_id = None;
565+ for (id, ipc_win) in &state.windows {
566+ if !seen.contains(id) {
567+ events.push(Event::WindowClosed { id: *id });
568+ }
569+
570+ if ipc_win.is_focused {
571+ ipc_focused_id = Some(id);
572+ }
573+ }
574+
575+ // Extra check for focus becoming None, since the checks above only work for focus becoming
576+ // a different window.
577+ if focused_id.is_none() && ipc_focused_id.is_some() {
578+ events.push(Event::WindowFocusChanged { id: None });
579+ }
580+
581+ for event in events {
582+ state.apply(event.clone());
583+ server.send_event(event);
584+ }
585+ }
586+}
src/layout/mod.rsmodified+32 -32
@@ -42,6 +42,7 @@ use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
4242 use smithay::output::{self, Output};
4343 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
4444 use smithay::utils::{Logical, Point, Scale, Serial, Size, Transform};
45+use workspace::WorkspaceId;
4546
4647 pub use self::monitor::MonitorRenderElement;
4748 use self::monitor::{Monitor, WorkspaceSwitch};
@@ -1094,13 +1095,13 @@ impl<W: LayoutElement> Layout<W> {
10941095 mon.workspaces.iter().flat_map(|ws| ws.windows())
10951096 }
10961097
1097- pub fn with_windows(&self, mut f: impl FnMut(&W, Option<&Output>)) {
1098+ pub fn with_windows(&self, mut f: impl FnMut(&W, Option<&Output>, WorkspaceId)) {
10981099 match &self.monitor_set {
10991100 MonitorSet::Normal { monitors, .. } => {
11001101 for mon in monitors {
11011102 for ws in &mon.workspaces {
11021103 for win in ws.windows() {
1103- f(win, Some(&mon.output));
1104+ f(win, Some(&mon.output), ws.id());
11041105 }
11051106 }
11061107 }
@@ -1108,7 +1109,7 @@ impl<W: LayoutElement> Layout<W> {
11081109 MonitorSet::NoOutputs { workspaces } => {
11091110 for ws in workspaces {
11101111 for win in ws.windows() {
1111- f(win, None);
1112+ f(win, None, ws.id());
11121113 }
11131114 }
11141115 }
@@ -2484,39 +2485,38 @@ impl<W: LayoutElement> Layout<W> {
24842485 }
24852486 }
24862487
2487- pub fn ipc_workspaces(&self) -> Vec<niri_ipc::Workspace> {
2488+ pub fn workspaces(
2489+ &self,
2490+ ) -> impl Iterator<Item = (Option<&Monitor<W>>, usize, &Workspace<W>)> + '_ {
2491+ let iter_normal;
2492+ let iter_no_outputs;
2493+
24882494 match &self.monitor_set {
2489- MonitorSet::Normal {
2490- monitors,
2491- primary_idx: _,
2492- active_monitor_idx: _,
2493- } => {
2494- let mut workspaces = Vec::new();
2495-
2496- for monitor in monitors {
2497- for (idx, workspace) in monitor.workspaces.iter().enumerate() {
2498- workspaces.push(niri_ipc::Workspace {
2499- idx: u8::try_from(idx + 1).unwrap_or(u8::MAX),
2500- name: workspace.name.clone(),
2501- output: Some(monitor.output.name()),
2502- is_active: monitor.active_workspace_idx == idx,
2503- })
2504- }
2505- }
2495+ MonitorSet::Normal { monitors, .. } => {
2496+ let it = monitors.iter().flat_map(|mon| {
2497+ mon.workspaces
2498+ .iter()
2499+ .enumerate()
2500+ .map(move |(idx, ws)| (Some(mon), idx, ws))
2501+ });
25062502
2507- workspaces
2503+ iter_normal = Some(it);
2504+ iter_no_outputs = None;
2505+ }
2506+ MonitorSet::NoOutputs { workspaces } => {
2507+ let it = workspaces
2508+ .iter()
2509+ .enumerate()
2510+ .map(|(idx, ws)| (None, idx, ws));
2511+
2512+ iter_normal = None;
2513+ iter_no_outputs = Some(it);
25082514 }
2509- MonitorSet::NoOutputs { workspaces } => workspaces
2510- .iter()
2511- .enumerate()
2512- .map(|(idx, ws)| niri_ipc::Workspace {
2513- idx: u8::try_from(idx + 1).unwrap_or(u8::MAX),
2514- name: ws.name.clone(),
2515- output: None,
2516- is_active: false,
2517- })
2518- .collect(),
25192515 }
2516+
2517+ let iter_normal = iter_normal.into_iter().flatten();
2518+ let iter_no_outputs = iter_no_outputs.into_iter().flatten();
2519+ iter_normal.chain(iter_no_outputs)
25202520 }
25212521 }
25222522
src/layout/workspace.rsmodified+10 -1
@@ -123,7 +123,7 @@ pub struct OutputId(String);
123123 static WORKSPACE_ID_COUNTER: IdCounter = IdCounter::new();
124124
125125 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126-pub struct WorkspaceId(u32);
126+pub struct WorkspaceId(pub u32);
127127
128128 impl WorkspaceId {
129129 fn next() -> WorkspaceId {
@@ -528,6 +528,15 @@ impl<W: LayoutElement> Workspace<W> {
528528 self.output.as_ref()
529529 }
530530
531+ pub fn active_window(&self) -> Option<&W> {
532+ if self.columns.is_empty() {
533+ return None;
534+ }
535+
536+ let col = &self.columns[self.active_column_idx];
537+ Some(col.tiles[col.active_tile_idx].window())
538+ }
539+
531540 pub fn set_output(&mut self, output: Option<Output>) {
532541 if self.output == output {
533542 return;
src/niri.rsmodified+18 -13
@@ -291,7 +291,6 @@ pub struct Niri {
291291
292292 pub ipc_server: Option<IpcServer>,
293293 pub ipc_outputs_changed: bool,
294- pub ipc_focused_window: Arc<Mutex<Option<Window>>>,
295294
296295 // Casts are dropped before PipeWire to prevent a double-free (yay).
297296 pub casts: Vec<Cast>,
@@ -502,7 +501,12 @@ impl State {
502501 let mut niri = Niri::new(config.clone(), event_loop, stop_signal, display, &backend);
503502 backend.init(&mut niri);
504503
505- Ok(Self { backend, niri })
504+ let mut state = Self { backend, niri };
505+
506+ // Initialize some IPC server state.
507+ state.ipc_keyboard_layouts_changed();
508+
509+ Ok(state)
506510 }
507511
508512 pub fn refresh_and_flush_clients(&mut self) {
@@ -538,6 +542,7 @@ impl State {
538542 foreign_toplevel::refresh(self);
539543 self.niri.refresh_window_rules();
540544 self.refresh_ipc_outputs();
545+ self.ipc_refresh_layout();
541546
542547 #[cfg(feature = "xdp-gnome-screencast")]
543548 self.niri.refresh_mapped_cast_outputs();
@@ -839,8 +844,6 @@ impl State {
839844 focus
840845 );
841846
842- let mut newly_focused_window = None;
843-
844847 // Tell the windows their new focus state for window rule purposes.
845848 if let KeyboardFocus::Layout {
846849 surface: Some(surface),
@@ -856,12 +859,9 @@ impl State {
856859 {
857860 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
858861 mapped.set_is_focused(true);
859- newly_focused_window = Some(mapped.window.clone());
860862 }
861863 }
862864
863- *self.niri.ipc_focused_window.lock().unwrap() = newly_focused_window;
864-
865865 if let Some(grab) = self.niri.popup_grab.as_mut() {
866866 if Some(&grab.root) != focus.surface() {
867867 trace!(
@@ -911,6 +911,10 @@ impl State {
911911 keyboard.with_xkb_state(self, |mut context| {
912912 context.set_layout(new_layout);
913913 });
914+
915+ if let Some(server) = &self.niri.ipc_server {
916+ server.keyboard_layout_switched(new_layout.0 as u8);
917+ }
914918 }
915919 }
916920
@@ -1076,6 +1080,8 @@ impl State {
10761080 if let Err(err) = keyboard.set_xkb_config(self, xkb.to_xkb_config()) {
10771081 warn!("error updating xkb config: {err:?}");
10781082 }
1083+
1084+ self.ipc_keyboard_layouts_changed();
10791085 }
10801086
10811087 if libinput_config_changed {
@@ -1372,7 +1378,7 @@ impl State {
13721378 }
13731379 StreamTargetId::Window { id } => {
13741380 let mut window = None;
1375- self.niri.layout.with_windows(|mapped, _| {
1381+ self.niri.layout.with_windows(|mapped, _, _| {
13761382 if u64::from(mapped.id().get()) != id {
13771383 return;
13781384 }
@@ -1489,7 +1495,7 @@ impl State {
14891495
14901496 let mut windows = HashMap::new();
14911497
1492- self.niri.layout.with_windows(|mapped, _| {
1498+ self.niri.layout.with_windows(|mapped, _, _| {
14931499 let wl_surface = mapped
14941500 .window
14951501 .toplevel()
@@ -1843,7 +1849,6 @@ impl Niri {
18431849
18441850 ipc_server,
18451851 ipc_outputs_changed: false,
1846- ipc_focused_window: Arc::new(Mutex::new(None)),
18471852
18481853 pipewire,
18491854 casts: vec![],
@@ -2811,7 +2816,7 @@ impl Niri {
28112816 let mut seen = HashSet::new();
28122817 let mut output_changed = vec![];
28132818
2814- self.layout.with_windows(|mapped, output| {
2819+ self.layout.with_windows(|mapped, output, _| {
28152820 seen.insert(mapped.window.clone());
28162821
28172822 let Some(output) = output else {
@@ -3510,7 +3515,7 @@ impl Niri {
35103515
35113516 let frame_callback_time = get_monotonic_time();
35123517
3513- self.layout.with_windows(|mapped, _| {
3518+ self.layout.with_windows(|mapped, _, _| {
35143519 mapped.window.send_frame(
35153520 output,
35163521 frame_callback_time,
@@ -3753,7 +3758,7 @@ impl Niri {
37533758 let _span = tracy_client::span!("Niri::render_window_for_screen_cast");
37543759
37553760 let mut window = None;
3756- self.layout.with_windows(|mapped, _| {
3761+ self.layout.with_windows(|mapped, _, _| {
37573762 if u64::from(mapped.id().get()) != window_id {
37583763 return;
37593764 }
src/protocols/foreign_toplevel.rsmodified+1 -1
@@ -95,7 +95,7 @@ pub fn refresh(state: &mut State) {
9595 // Save the focused window for last, this way when the focus changes, we will first deactivate
9696 // the previous window and only then activate the newly focused window.
9797 let mut focused = None;
98- state.niri.layout.with_windows(|mapped, output| {
98+ state.niri.layout.with_windows(|mapped, output, _| {
9999 let wl_surface = mapped.toplevel().wl_surface();
100100
101101 with_states(wl_surface, |states| {
wiki/IPC.mdmodified+20 -0
@@ -11,6 +11,26 @@ The communication over the IPC socket happens in JSON.
1111 > If you're getting parsing errors from `niri msg` after upgrading niri, make sure that you've restarted niri itself.
1212 > You might be trying to run a newer `niri msg` against an older `niri` compositor.
1313
14+### Event Stream
15+
16+<sup>Since: 0.1.9</sup>
17+
18+While most niri IPC requests return a single response, the event stream request will make niri continuously stream events into the IPC connection until it is closed.
19+This is useful for implementing various bars and indicators that update as soon as something happens, without continuous polling.
20+
21+The event stream IPC is designed to give you the complete current state up-front, then follow up with updates to that state.
22+This way, your state can never "desync" from niri, and you don't need to make any other IPC information requests.
23+
24+Where reasonable, event stream state updates are atomic, though this is not always the case.
25+For example, a window may end up with a workspace id for a workspace that had already been removed.
26+This can happen if the corresponding workspaces-changed event arrives before the corresponding window-changed event.
27+
28+To get a taste of the events, run `niri msg event-stream`.
29+Though, this is more of a debug function than anything.
30+You can get raw events from `niri msg --json event-stream`, or by connecting to the niri socket and requesting an event stream manually.
31+
32+You can find the full list of events along with documentation in the [niri-ipc sub-crate](./niri-ipc/).
33+
1434 ### Backwards Compatibility
1535
1636 The JSON output *should* remain stable, as in: