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};
9 mod socket;9 mod socket;
10 pub use socket::{Socket, SOCKET_PATH_ENV};10 pub use socket::{Socket, SOCKET_PATH_ENV};
11 11
12+pub mod state;
13+
12 /// Request from client to niri.14 /// Request from client to niri.
13 #[derive(Debug, Serialize, Deserialize, Clone)]15 #[derive(Debug, Serialize, Deserialize, Clone)]
14 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]16 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
@@ -38,6 +40,11 @@ pub enum Request {
38 FocusedOutput,40 FocusedOutput,
39 /// Request information about the keyboard layout.41 /// Request information about the keyboard layout.
40 KeyboardLayouts,42 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,
41 /// Respond with an error (for testing error handling).48 /// Respond with an error (for testing error handling).
42 ReturnError,49 ReturnError,
43 }50 }
@@ -536,10 +543,18 @@ pub enum Transform {
536 #[derive(Serialize, Deserialize, Debug, Clone)]543 #[derive(Serialize, Deserialize, Debug, Clone)]
537 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]544 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
538 pub struct Window {545 pub struct Window {
546+ /// Unique id of this window.
547+ pub id: u64,
539 /// Title, if set.548 /// Title, if set.
540 pub title: Option<String>,549 pub title: Option<String>,
541 /// Application ID, if set.550 /// Application ID, if set.
542 pub app_id: Option<String>,551 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,
543 }558 }
544 559
545 /// Output configuration change result.560 /// Output configuration change result.
@@ -556,6 +571,10 @@ pub enum OutputConfigChanged {
556 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]571 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
557 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]572 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
558 pub struct Workspace {573 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,
559 /// Index of the workspace on its monitor.578 /// Index of the workspace on its monitor.
560 ///579 ///
561 /// This is the same index you can use for requests like `niri msg action focus-workspace`.580 /// This is the same index you can use for requests like `niri msg action focus-workspace`.
@@ -567,7 +586,15 @@ pub struct Workspace {
567 /// Can be `None` if no outputs are currently connected.586 /// Can be `None` if no outputs are currently connected.
568 pub output: Option<String>,587 pub output: Option<String>,
569 /// Whether the workspace is currently active on its output.588 /// 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.
570 pub is_active: bool,591 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>,
571 }598 }
572 599
573 /// Configured keyboard layouts.600 /// Configured keyboard layouts.
@@ -580,6 +607,77 @@ pub struct KeyboardLayouts {
580 pub current_idx: u8,607 pub current_idx: u8,
581 }608 }
582 609
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+
583 impl FromStr for WorkspaceReferenceArg {681 impl FromStr for WorkspaceReferenceArg {
584 type Err = &'static str;682 type Err = &'static str;
585 683
niri-ipc/src/socket.rsmodified+15 -3
@@ -6,7 +6,7 @@ use std::net::Shutdown;
6 use std::os::unix::net::UnixStream;6 use std::os::unix::net::UnixStream;
7 use std::path::Path;7 use std::path::Path;
8 8
9-use crate::{Reply, Request};9+use crate::{Event, Reply, Request};
10 10
11 /// Name of the environment variable containing the niri IPC socket path.11 /// Name of the environment variable containing the niri IPC socket path.
12 pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";12 pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";
@@ -47,7 +47,11 @@ impl Socket {
47 /// * `Ok(Ok(response))`: successful [`Response`](crate::Response) from niri47 /// * `Ok(Ok(response))`: successful [`Response`](crate::Response) from niri
48 /// * `Ok(Err(message))`: error message from niri48 /// * `Ok(Err(message))`: error message from niri
49 /// * `Err(error)`: error communicating with niri49 /// * `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>)> {
51 let Self { mut stream } = self;55 let Self { mut stream } = self;
52 56
53 let mut buf = serde_json::to_string(&request).unwrap();57 let mut buf = serde_json::to_string(&request).unwrap();
@@ -60,6 +64,14 @@ impl Socket {
60 reader.read_line(&mut buf)?;64 reader.read_line(&mut buf)?;
61 65
62 let reply = serde_json::from_str(&buf)?;66 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))
64 }76 }
65 }77 }
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 {
88 },88 },
89 /// Get the configured keyboard layouts.89 /// Get the configured keyboard layouts.
90 KeyboardLayouts,90 KeyboardLayouts,
91+ /// Start continuously receiving events from the compositor.
92+ EventStream,
91 /// Print the version of the running niri instance.93 /// Print the version of the running niri instance.
92 Version,94 Version,
93 /// Request an error from the running niri instance.95 /// Request an error from the running niri instance.
src/input/mod.rsmodified+11 -6
@@ -16,7 +16,7 @@ use smithay::backend::input::{
16 TabletToolProximityEvent, TabletToolTipEvent, TabletToolTipState, TouchEvent,16 TabletToolProximityEvent, TabletToolTipEvent, TabletToolTipState, TouchEvent,
17 };17 };
18 use smithay::backend::libinput::LibinputInputBackend;18 use smithay::backend::libinput::LibinputInputBackend;
19-use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState};19+use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState, XkbContextHandler};
20 use smithay::input::pointer::{20 use smithay::input::pointer::{
21 AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent,21 AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent,
22 GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,22 GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
@@ -539,13 +539,18 @@ impl State {
539 }539 }
540 }540 }
541 Action::SwitchLayout(action) => {541 Action::SwitchLayout(action) => {
542- self.niri.seat.get_keyboard().unwrap().with_xkb_state(542+ let keyboard = &self.niri.seat.get_keyboard().unwrap();
543- self,543+ let new_idx = keyboard.with_xkb_state(self, |mut state| {
544- |mut state| match action {544+ match action {
545 LayoutSwitchTarget::Next => state.cycle_next_layout(),545 LayoutSwitchTarget::Next => state.cycle_next_layout(),
546 LayoutSwitchTarget::Prev => state.cycle_prev_layout(),546 LayoutSwitchTarget::Prev => state.cycle_prev_layout(),
547- },547+ };
548- );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+ }
549 }554 }
550 Action::MoveColumnLeft => {555 Action::MoveColumnLeft => {
551 self.niri.layout.move_left();556 self.niri.layout.move_left();
src/ipc/client.rsmodified+61 -3
@@ -1,7 +1,7 @@
1 use anyhow::{anyhow, bail, Context};1 use anyhow::{anyhow, bail, Context};
2 use niri_ipc::{2 use niri_ipc::{
3- KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Request, Response, Socket,3+ Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Request, Response,
4- Transform,4+ Socket, Transform,
5 };5 };
6 use serde_json::json;6 use serde_json::json;
7 7
@@ -21,12 +21,13 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
21 },21 },
22 Msg::Workspaces => Request::Workspaces,22 Msg::Workspaces => Request::Workspaces,
23 Msg::KeyboardLayouts => Request::KeyboardLayouts,23 Msg::KeyboardLayouts => Request::KeyboardLayouts,
24+ Msg::EventStream => Request::EventStream,
24 Msg::RequestError => Request::ReturnError,25 Msg::RequestError => Request::ReturnError,
25 };26 };
26 27
27 let socket = Socket::connect().context("error connecting to the niri socket")?;28 let socket = Socket::connect().context("error connecting to the niri socket")?;
28 29
29- let reply = socket30+ let (reply, mut read_event) = socket
30 .send(request)31 .send(request)
31 .context("error communicating with niri")?;32 .context("error communicating with niri")?;
32 33
@@ -37,6 +38,7 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
37 Socket::connect()38 Socket::connect()
38 .and_then(|socket| socket.send(Request::Version))39 .and_then(|socket| socket.send(Request::Version))
39 .ok()40 .ok()
41+ .map(|(reply, _read_event)| reply)
40 }42 }
41 _ => None,43 _ => None,
42 };44 };
@@ -261,6 +263,62 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
261 println!("{is_active}{idx} {name}");263 println!("{is_active}{idx} {name}");
262 }264 }
263 }265 }
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+ }
264 }322 }
265 323
266 Ok(())324 Ok(())
src/ipc/server.rsmodified+371 -45
@@ -1,15 +1,20 @@
1+use std::cell::RefCell;
2+use std::collections::HashSet;
1 use std::os::unix::net::{UnixListener, UnixStream};3 use std::os::unix::net::{UnixListener, UnixStream};
2 use std::path::PathBuf;4 use std::path::PathBuf;
5+use std::rc::Rc;
3 use std::sync::{Arc, Mutex};6 use std::sync::{Arc, Mutex};
4 use std::{env, io, process};7 use std::{env, io, process};
5 8
6 use anyhow::Context;9 use anyhow::Context;
10+use async_channel::{Receiver, Sender, TrySendError};
11+use calloop::futures::Scheduler;
7 use calloop::io::Async;12 use calloop::io::Async;
8 use directories::BaseDirs;13 use directories::BaseDirs;
9 use futures_util::io::{AsyncReadExt, BufReader};14 use futures_util::io::{AsyncReadExt, BufReader};
10-use futures_util::{AsyncBufReadExt, AsyncWriteExt};15+use futures_util::{select_biased, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, FutureExt as _};
11-use niri_ipc::{KeyboardLayouts, OutputConfigChanged, Reply, Request, Response};16+use niri_ipc::state::{EventStreamState, EventStreamStatePart as _};
12-use smithay::desktop::Window;17+use niri_ipc::{Event, KeyboardLayouts, OutputConfigChanged, Reply, Request, Response, Workspace};
13 use smithay::input::keyboard::XkbContextHandler;18 use smithay::input::keyboard::XkbContextHandler;
14 use smithay::reexports::calloop::generic::Generic;19 use smithay::reexports::calloop::generic::Generic;
15 use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};20 use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
@@ -18,17 +23,38 @@ use smithay::wayland::compositor::with_states;
18 use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;23 use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;
19 24
20 use crate::backend::IpcOutputMap;25 use crate::backend::IpcOutputMap;
26+use crate::layout::workspace::WorkspaceId;
21 use crate::niri::State;27 use crate::niri::State;
22 use crate::utils::version;28 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;
23 34
24 pub struct IpcServer {35 pub struct IpcServer {
25 pub socket_path: PathBuf,36 pub socket_path: PathBuf,
37+ event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
38+ event_stream_state: Rc<RefCell<EventStreamState>>,
26 }39 }
27 40
28 struct ClientCtx {41 struct ClientCtx {
29 event_loop: LoopHandle<'static, State>,42 event_loop: LoopHandle<'static, State>,
43+ scheduler: Scheduler<()>,
30 ipc_outputs: Arc<Mutex<IpcOutputMap>>,44 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<()>,
32 }58 }
33 59
34 impl IpcServer {60 impl IpcServer {
@@ -60,7 +86,43 @@ impl IpcServer {
60 })86 })
61 .unwrap();87 .unwrap();
62 88
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);
64 }126 }
65 }127 }
66 128
@@ -90,10 +152,14 @@ fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
90 }152 }
91 };153 };
92 154
155+ let ipc_server = state.niri.ipc_server.as_ref().unwrap();
156+
93 let ctx = ClientCtx {157 let ctx = ClientCtx {
94 event_loop: state.niri.event_loop.clone(),158 event_loop: state.niri.event_loop.clone(),
159+ scheduler: state.niri.scheduler.clone(),
95 ipc_outputs: state.backend.ipc_outputs(),160 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(),
97 };163 };
98 164
99 let future = async move {165 let future = async move {
@@ -106,7 +172,7 @@ fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
106 }172 }
107 }173 }
108 174
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<()> {
110 let (read, mut write) = stream.split();176 let (read, mut write) = stream.split();
111 let mut buf = String::new();177 let mut buf = String::new();
112 178
@@ -120,6 +186,7 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
120 .context("error parsing request")186 .context("error parsing request")
121 .map_err(|err| err.to_string());187 .map_err(|err| err.to_string());
122 let requested_error = matches!(request, Ok(Request::ReturnError));188 let requested_error = matches!(request, Ok(Request::ReturnError));
189+ let requested_event_stream = matches!(request, Ok(Request::EventStream));
123 190
124 let reply = match request {191 let reply = match request {
125 Ok(request) => process(&ctx, request).await,192 Ok(request) => process(&ctx, request).await,
@@ -136,6 +203,46 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
136 buf.push(b'\n');203 buf.push(b'\n');
137 write.write_all(&buf).await.context("error writing reply")?;204 write.write_all(&buf).await.context("error writing reply")?;
138 205
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+
139 Ok(())246 Ok(())
140 }247 }
141 248
@@ -149,23 +256,9 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
149 Response::Outputs(outputs.collect())256 Response::Outputs(outputs.collect())
150 }257 }
151 Request::FocusedWindow => {258 Request::FocusedWindow => {
152- let window = ctx.ipc_focused_window.lock().unwrap().clone();259+ let state = ctx.event_stream_state.borrow();
153- let window = window.map(|window| {260+ let windows = &state.windows.windows;
154- let wl_surface = window.toplevel().expect("no X11 support").wl_surface();261+ let window = windows.values().find(|win| win.is_focused).cloned();
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- });
169 Response::FocusedWindow(window)262 Response::FocusedWindow(window)
170 }263 }
171 Request::Action(action) => {264 Request::Action(action) => {
@@ -202,13 +295,8 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
202 Response::OutputConfigChanged(response)295 Response::OutputConfigChanged(response)
203 }296 }
204 Request::Workspaces => {297 Request::Workspaces => {
205- let (tx, rx) = async_channel::bounded(1);298+ let state = ctx.event_stream_state.borrow();
206- ctx.event_loop.insert_idle(move |state| {299+ let workspaces = state.workspaces.workspaces.values().cloned().collect();
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"))?;
212 Response::Workspaces(workspaces)300 Response::Workspaces(workspaces)
213 }301 }
214 Request::FocusedOutput => {302 Request::FocusedOutput => {
@@ -238,23 +326,261 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
238 Response::FocusedOutput(output)326 Response::FocusedOutput(output)
239 }327 }
240 Request::KeyboardLayouts => {328 Request::KeyboardLayouts => {
241- let (tx, rx) = async_channel::bounded(1);329+ let state = ctx.event_stream_state.borrow();
242- ctx.event_loop.insert_idle(move |state| {330+ let layout = state.keyboard_layouts.keyboard_layouts.clone();
243- let keyboard = state.niri.seat.get_keyboard().unwrap();331+ let layout = layout.expect("keyboard layouts should be set at startup");
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"))?;
255 Response::KeyboardLayouts(layout)332 Response::KeyboardLayouts(layout)
256 }333 }
334+ Request::EventStream => Response::Handled,
257 };335 };
258 336
259 Ok(response)337 Ok(response)
260 }338 }
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};
42 use smithay::output::{self, Output};42 use smithay::output::{self, Output};
43 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;43 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
44 use smithay::utils::{Logical, Point, Scale, Serial, Size, Transform};44 use smithay::utils::{Logical, Point, Scale, Serial, Size, Transform};
45+use workspace::WorkspaceId;
45 46
46 pub use self::monitor::MonitorRenderElement;47 pub use self::monitor::MonitorRenderElement;
47 use self::monitor::{Monitor, WorkspaceSwitch};48 use self::monitor::{Monitor, WorkspaceSwitch};
@@ -1094,13 +1095,13 @@ impl<W: LayoutElement> Layout<W> {
1094 mon.workspaces.iter().flat_map(|ws| ws.windows())1095 mon.workspaces.iter().flat_map(|ws| ws.windows())
1095 }1096 }
1096 1097
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)) {
1098 match &self.monitor_set {1099 match &self.monitor_set {
1099 MonitorSet::Normal { monitors, .. } => {1100 MonitorSet::Normal { monitors, .. } => {
1100 for mon in monitors {1101 for mon in monitors {
1101 for ws in &mon.workspaces {1102 for ws in &mon.workspaces {
1102 for win in ws.windows() {1103 for win in ws.windows() {
1103- f(win, Some(&mon.output));1104+ f(win, Some(&mon.output), ws.id());
1104 }1105 }
1105 }1106 }
1106 }1107 }
@@ -1108,7 +1109,7 @@ impl<W: LayoutElement> Layout<W> {
1108 MonitorSet::NoOutputs { workspaces } => {1109 MonitorSet::NoOutputs { workspaces } => {
1109 for ws in workspaces {1110 for ws in workspaces {
1110 for win in ws.windows() {1111 for win in ws.windows() {
1111- f(win, None);1112+ f(win, None, ws.id());
1112 }1113 }
1113 }1114 }
1114 }1115 }
@@ -2484,39 +2485,38 @@ impl<W: LayoutElement> Layout<W> {
2484 }2485 }
2485 }2486 }
2486 2487
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+
2488 match &self.monitor_set {2494 match &self.monitor_set {
2489- MonitorSet::Normal {2495+ MonitorSet::Normal { monitors, .. } => {
2490- monitors,2496+ let it = monitors.iter().flat_map(|mon| {
2491- primary_idx: _,2497+ mon.workspaces
2492- active_monitor_idx: _,2498+ .iter()
2493- } => {2499+ .enumerate()
2494- let mut workspaces = Vec::new();2500+ .map(move |(idx, ws)| (Some(mon), idx, ws))
2495-2501+ });
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- }
2506 2502
2507- workspaces2503+ 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);
2508 }2514 }
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(),
2519 }2515 }
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)
2520 }2520 }
2521 }2521 }
2522 2522
src/layout/workspace.rsmodified+10 -1
@@ -123,7 +123,7 @@ pub struct OutputId(String);
123 static WORKSPACE_ID_COUNTER: IdCounter = IdCounter::new();123 static WORKSPACE_ID_COUNTER: IdCounter = IdCounter::new();
124 124
125 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]125 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126-pub struct WorkspaceId(u32);126+pub struct WorkspaceId(pub u32);
127 127
128 impl WorkspaceId {128 impl WorkspaceId {
129 fn next() -> WorkspaceId {129 fn next() -> WorkspaceId {
@@ -528,6 +528,15 @@ impl<W: LayoutElement> Workspace<W> {
528 self.output.as_ref()528 self.output.as_ref()
529 }529 }
530 530
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+
531 pub fn set_output(&mut self, output: Option<Output>) {540 pub fn set_output(&mut self, output: Option<Output>) {
532 if self.output == output {541 if self.output == output {
533 return;542 return;
src/niri.rsmodified+18 -13
@@ -291,7 +291,6 @@ pub struct Niri {
291 291
292 pub ipc_server: Option<IpcServer>,292 pub ipc_server: Option<IpcServer>,
293 pub ipc_outputs_changed: bool,293 pub ipc_outputs_changed: bool,
294- pub ipc_focused_window: Arc<Mutex<Option<Window>>>,
295 294
296 // Casts are dropped before PipeWire to prevent a double-free (yay).295 // Casts are dropped before PipeWire to prevent a double-free (yay).
297 pub casts: Vec<Cast>,296 pub casts: Vec<Cast>,
@@ -502,7 +501,12 @@ impl State {
502 let mut niri = Niri::new(config.clone(), event_loop, stop_signal, display, &backend);501 let mut niri = Niri::new(config.clone(), event_loop, stop_signal, display, &backend);
503 backend.init(&mut niri);502 backend.init(&mut niri);
504 503
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)
506 }510 }
507 511
508 pub fn refresh_and_flush_clients(&mut self) {512 pub fn refresh_and_flush_clients(&mut self) {
@@ -538,6 +542,7 @@ impl State {
538 foreign_toplevel::refresh(self);542 foreign_toplevel::refresh(self);
539 self.niri.refresh_window_rules();543 self.niri.refresh_window_rules();
540 self.refresh_ipc_outputs();544 self.refresh_ipc_outputs();
545+ self.ipc_refresh_layout();
541 546
542 #[cfg(feature = "xdp-gnome-screencast")]547 #[cfg(feature = "xdp-gnome-screencast")]
543 self.niri.refresh_mapped_cast_outputs();548 self.niri.refresh_mapped_cast_outputs();
@@ -839,8 +844,6 @@ impl State {
839 focus844 focus
840 );845 );
841 846
842- let mut newly_focused_window = None;
843-
844 // Tell the windows their new focus state for window rule purposes.847 // Tell the windows their new focus state for window rule purposes.
845 if let KeyboardFocus::Layout {848 if let KeyboardFocus::Layout {
846 surface: Some(surface),849 surface: Some(surface),
@@ -856,12 +859,9 @@ impl State {
856 {859 {
857 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {860 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
858 mapped.set_is_focused(true);861 mapped.set_is_focused(true);
859- newly_focused_window = Some(mapped.window.clone());
860 }862 }
861 }863 }
862 864
863- *self.niri.ipc_focused_window.lock().unwrap() = newly_focused_window;
864-
865 if let Some(grab) = self.niri.popup_grab.as_mut() {865 if let Some(grab) = self.niri.popup_grab.as_mut() {
866 if Some(&grab.root) != focus.surface() {866 if Some(&grab.root) != focus.surface() {
867 trace!(867 trace!(
@@ -911,6 +911,10 @@ impl State {
911 keyboard.with_xkb_state(self, |mut context| {911 keyboard.with_xkb_state(self, |mut context| {
912 context.set_layout(new_layout);912 context.set_layout(new_layout);
913 });913 });
914+
915+ if let Some(server) = &self.niri.ipc_server {
916+ server.keyboard_layout_switched(new_layout.0 as u8);
917+ }
914 }918 }
915 }919 }
916 920
@@ -1076,6 +1080,8 @@ impl State {
1076 if let Err(err) = keyboard.set_xkb_config(self, xkb.to_xkb_config()) {1080 if let Err(err) = keyboard.set_xkb_config(self, xkb.to_xkb_config()) {
1077 warn!("error updating xkb config: {err:?}");1081 warn!("error updating xkb config: {err:?}");
1078 }1082 }
1083+
1084+ self.ipc_keyboard_layouts_changed();
1079 }1085 }
1080 1086
1081 if libinput_config_changed {1087 if libinput_config_changed {
@@ -1372,7 +1378,7 @@ impl State {
1372 }1378 }
1373 StreamTargetId::Window { id } => {1379 StreamTargetId::Window { id } => {
1374 let mut window = None;1380 let mut window = None;
1375- self.niri.layout.with_windows(|mapped, _| {1381+ self.niri.layout.with_windows(|mapped, _, _| {
1376 if u64::from(mapped.id().get()) != id {1382 if u64::from(mapped.id().get()) != id {
1377 return;1383 return;
1378 }1384 }
@@ -1489,7 +1495,7 @@ impl State {
1489 1495
1490 let mut windows = HashMap::new();1496 let mut windows = HashMap::new();
1491 1497
1492- self.niri.layout.with_windows(|mapped, _| {1498+ self.niri.layout.with_windows(|mapped, _, _| {
1493 let wl_surface = mapped1499 let wl_surface = mapped
1494 .window1500 .window
1495 .toplevel()1501 .toplevel()
@@ -1843,7 +1849,6 @@ impl Niri {
1843 1849
1844 ipc_server,1850 ipc_server,
1845 ipc_outputs_changed: false,1851 ipc_outputs_changed: false,
1846- ipc_focused_window: Arc::new(Mutex::new(None)),
1847 1852
1848 pipewire,1853 pipewire,
1849 casts: vec![],1854 casts: vec![],
@@ -2811,7 +2816,7 @@ impl Niri {
2811 let mut seen = HashSet::new();2816 let mut seen = HashSet::new();
2812 let mut output_changed = vec![];2817 let mut output_changed = vec![];
2813 2818
2814- self.layout.with_windows(|mapped, output| {2819+ self.layout.with_windows(|mapped, output, _| {
2815 seen.insert(mapped.window.clone());2820 seen.insert(mapped.window.clone());
2816 2821
2817 let Some(output) = output else {2822 let Some(output) = output else {
@@ -3510,7 +3515,7 @@ impl Niri {
3510 3515
3511 let frame_callback_time = get_monotonic_time();3516 let frame_callback_time = get_monotonic_time();
3512 3517
3513- self.layout.with_windows(|mapped, _| {3518+ self.layout.with_windows(|mapped, _, _| {
3514 mapped.window.send_frame(3519 mapped.window.send_frame(
3515 output,3520 output,
3516 frame_callback_time,3521 frame_callback_time,
@@ -3753,7 +3758,7 @@ impl Niri {
3753 let _span = tracy_client::span!("Niri::render_window_for_screen_cast");3758 let _span = tracy_client::span!("Niri::render_window_for_screen_cast");
3754 3759
3755 let mut window = None;3760 let mut window = None;
3756- self.layout.with_windows(|mapped, _| {3761+ self.layout.with_windows(|mapped, _, _| {
3757 if u64::from(mapped.id().get()) != window_id {3762 if u64::from(mapped.id().get()) != window_id {
3758 return;3763 return;
3759 }3764 }
src/protocols/foreign_toplevel.rsmodified+1 -1
@@ -95,7 +95,7 @@ pub fn refresh(state: &mut State) {
95 // Save the focused window for last, this way when the focus changes, we will first deactivate95 // Save the focused window for last, this way when the focus changes, we will first deactivate
96 // the previous window and only then activate the newly focused window.96 // the previous window and only then activate the newly focused window.
97 let mut focused = None;97 let mut focused = None;
98- state.niri.layout.with_windows(|mapped, output| {98+ state.niri.layout.with_windows(|mapped, output, _| {
99 let wl_surface = mapped.toplevel().wl_surface();99 let wl_surface = mapped.toplevel().wl_surface();
100 100
101 with_states(wl_surface, |states| {101 with_states(wl_surface, |states| {
wiki/IPC.mdmodified+20 -0
@@ -11,6 +11,26 @@ The communication over the IPC socket happens in JSON.
11 > If you're getting parsing errors from `niri msg` after upgrading niri, make sure that you've restarted niri itself.11 > If you're getting parsing errors from `niri msg` after upgrading niri, make sure that you've restarted niri itself.
12 > You might be trying to run a newer `niri msg` against an older `niri` compositor.12 > You might be trying to run a newer `niri msg` against an older `niri` compositor.
13 13
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+
14 ### Backwards Compatibility34 ### Backwards Compatibility
15 35
16 The JSON output *should* remain stable, as in:36 The JSON output *should* remain stable, as in: