Skip to main content

niri_ipc/
state.rs

1//! Helpers for keeping track of the event stream state.
2//!
3//! 1. Create an [`EventStreamState`] using `Default::default()`, or any individual state part if
4//!    you only care about part of the state.
5//! 2. Connect to the niri socket and request an event stream.
6//! 3. Pass every [`Event`] to [`EventStreamStatePart::apply`] on your state.
7//! 4. Read the fields of the state as needed.
8
9use std::collections::hash_map::Entry;
10use std::collections::HashMap;
11
12use crate::{Cast, Event, KeyboardLayouts, Window, Workspace};
13
14/// Part of the state communicated via the event stream.
15pub trait EventStreamStatePart {
16    /// Returns a sequence of events that replicates this state from default initialization.
17    fn replicate(&self) -> Vec<Event>;
18
19    /// Applies the event to this state.
20    ///
21    /// Returns `None` after applying the event, and `Some(event)` if the event is ignored by this
22    /// part of the state.
23    fn apply(&mut self, event: Event) -> Option<Event>;
24}
25
26/// The full state communicated over the event stream.
27///
28/// Different parts of the state are not guaranteed to be consistent across every single event
29/// sent by niri. For example, you may receive the first [`Event::WindowOpenedOrChanged`] for a
30/// just-opened window *after* an [`Event::WorkspaceActiveWindowChanged`] for that window. Between
31/// these two events, the workspace active window id refers to a window that does not yet exist in
32/// the windows state part.
33#[derive(Debug, Default)]
34pub struct EventStreamState {
35    /// State of workspaces.
36    pub workspaces: WorkspacesState,
37
38    /// State of windows.
39    pub windows: WindowsState,
40
41    /// State of the keyboard layouts.
42    pub keyboard_layouts: KeyboardLayoutsState,
43
44    /// State of the overview.
45    pub overview: OverviewState,
46
47    /// State of the config.
48    pub config: ConfigState,
49
50    /// State of screencasts.
51    pub casts: CastsState,
52
53    /// State of touchpads.
54    pub touchpad: TouchpadState,
55}
56
57/// The workspaces state communicated over the event stream.
58#[derive(Debug, Default)]
59pub struct WorkspacesState {
60    /// Map from a workspace id to the workspace.
61    pub workspaces: HashMap<u64, Workspace>,
62}
63
64/// The windows state communicated over the event stream.
65#[derive(Debug, Default)]
66pub struct WindowsState {
67    /// Map from a window id to the window.
68    pub windows: HashMap<u64, Window>,
69}
70
71/// The keyboard layout state communicated over the event stream.
72#[derive(Debug, Default)]
73pub struct KeyboardLayoutsState {
74    /// Configured keyboard layouts.
75    pub keyboard_layouts: Option<KeyboardLayouts>,
76}
77
78/// The overview state communicated over the event stream.
79#[derive(Debug, Default)]
80pub struct OverviewState {
81    /// Whether the overview is currently open.
82    pub is_open: bool,
83}
84
85/// The config state communicated over the event stream.
86#[derive(Debug, Default)]
87pub struct ConfigState {
88    /// Whether the last config load attempt had failed.
89    pub failed: bool,
90}
91
92/// The casts state communicated over the event stream.
93#[derive(Debug, Default)]
94pub struct CastsState {
95    /// Map from a stream id to the screencast.
96    pub casts: HashMap<u64, Cast>,
97}
98
99/// The touchpad state communicated over the event stream.
100#[derive(Debug, Default)]
101pub struct TouchpadState {
102    /// Whether the touchpad is currently on.
103    ///
104    /// Note that this only indicates the [`Action::ToggleTouchpad`] state. The touchpad can be
105    /// disabled in hardware, or via `input { touchpad { off; } }`—this is not reflected here.
106    ///
107    /// [`Action::ToggleTouchpad`]: crate::Action::ToggleTouchpad
108    pub on: bool,
109}
110
111impl EventStreamStatePart for EventStreamState {
112    fn replicate(&self) -> Vec<Event> {
113        let mut events = Vec::new();
114        events.extend(self.workspaces.replicate());
115        events.extend(self.windows.replicate());
116        events.extend(self.keyboard_layouts.replicate());
117        events.extend(self.overview.replicate());
118        events.extend(self.config.replicate());
119        events.extend(self.casts.replicate());
120        events.extend(self.touchpad.replicate());
121        events
122    }
123
124    fn apply(&mut self, event: Event) -> Option<Event> {
125        let event = self.workspaces.apply(event)?;
126        let event = self.windows.apply(event)?;
127        let event = self.keyboard_layouts.apply(event)?;
128        let event = self.overview.apply(event)?;
129        let event = self.config.apply(event)?;
130        let event = self.casts.apply(event)?;
131        let event = self.touchpad.apply(event)?;
132        Some(event)
133    }
134}
135
136impl EventStreamStatePart for WorkspacesState {
137    fn replicate(&self) -> Vec<Event> {
138        let workspaces = self.workspaces.values().cloned().collect();
139        vec![Event::WorkspacesChanged { workspaces }]
140    }
141
142    fn apply(&mut self, event: Event) -> Option<Event> {
143        match event {
144            Event::WorkspacesChanged { workspaces } => {
145                self.workspaces = workspaces.into_iter().map(|ws| (ws.id, ws)).collect();
146            }
147            Event::WorkspaceUrgencyChanged { id, urgent } => {
148                for ws in self.workspaces.values_mut() {
149                    if ws.id == id {
150                        ws.is_urgent = urgent;
151                    }
152                }
153            }
154            Event::WorkspaceActivated { id, focused } => {
155                let ws = self.workspaces.get(&id);
156                let ws = ws.expect("activated workspace was missing from the map");
157                let output = ws.output.clone();
158
159                for ws in self.workspaces.values_mut() {
160                    let got_activated = ws.id == id;
161                    if ws.output == output {
162                        ws.is_active = got_activated;
163                    }
164
165                    if focused {
166                        ws.is_focused = got_activated;
167                    }
168                }
169            }
170            Event::WorkspaceActiveWindowChanged {
171                workspace_id,
172                active_window_id,
173            } => {
174                let ws = self.workspaces.get_mut(&workspace_id);
175                let ws = ws.expect("changed workspace was missing from the map");
176                ws.active_window_id = active_window_id;
177            }
178            event => return Some(event),
179        }
180        None
181    }
182}
183
184impl EventStreamStatePart for WindowsState {
185    fn replicate(&self) -> Vec<Event> {
186        let windows = self.windows.values().cloned().collect();
187        vec![Event::WindowsChanged { windows }]
188    }
189
190    fn apply(&mut self, event: Event) -> Option<Event> {
191        match event {
192            Event::WindowsChanged { windows } => {
193                self.windows = windows.into_iter().map(|win| (win.id, win)).collect();
194            }
195            Event::WindowOpenedOrChanged { window } => {
196                let (id, is_focused) = match self.windows.entry(window.id) {
197                    Entry::Occupied(mut entry) => {
198                        let entry = entry.get_mut();
199                        *entry = window;
200                        (entry.id, entry.is_focused)
201                    }
202                    Entry::Vacant(entry) => {
203                        let entry = entry.insert(window);
204                        (entry.id, entry.is_focused)
205                    }
206                };
207
208                if is_focused {
209                    for win in self.windows.values_mut() {
210                        if win.id != id {
211                            win.is_focused = false;
212                        }
213                    }
214                }
215            }
216            Event::WindowClosed { id } => {
217                let win = self.windows.remove(&id);
218                win.expect("closed window was missing from the map");
219            }
220            Event::WindowFocusChanged { id } => {
221                for win in self.windows.values_mut() {
222                    win.is_focused = Some(win.id) == id;
223                }
224            }
225            Event::WindowFocusTimestampChanged {
226                id,
227                focus_timestamp,
228            } => {
229                for win in self.windows.values_mut() {
230                    if win.id == id {
231                        win.focus_timestamp = focus_timestamp;
232                        break;
233                    }
234                }
235            }
236            Event::WindowUrgencyChanged { id, urgent } => {
237                for win in self.windows.values_mut() {
238                    if win.id == id {
239                        win.is_urgent = urgent;
240                        break;
241                    }
242                }
243            }
244            Event::WindowLayoutsChanged { changes } => {
245                for (id, update) in changes {
246                    let win = self.windows.get_mut(&id);
247                    let win = win.expect("changed window was missing from the map");
248                    win.layout = update;
249                }
250            }
251            event => return Some(event),
252        }
253        None
254    }
255}
256
257impl EventStreamStatePart for KeyboardLayoutsState {
258    fn replicate(&self) -> Vec<Event> {
259        if let Some(keyboard_layouts) = self.keyboard_layouts.clone() {
260            vec![Event::KeyboardLayoutsChanged { keyboard_layouts }]
261        } else {
262            vec![]
263        }
264    }
265
266    fn apply(&mut self, event: Event) -> Option<Event> {
267        match event {
268            Event::KeyboardLayoutsChanged { keyboard_layouts } => {
269                self.keyboard_layouts = Some(keyboard_layouts);
270            }
271            Event::KeyboardLayoutSwitched { idx } => {
272                let kb = self.keyboard_layouts.as_mut();
273                let kb = kb.expect("keyboard layouts must be set before a layout can be switched");
274                kb.current_idx = idx;
275            }
276            event => return Some(event),
277        }
278        None
279    }
280}
281
282impl EventStreamStatePart for OverviewState {
283    fn replicate(&self) -> Vec<Event> {
284        vec![Event::OverviewOpenedOrClosed {
285            is_open: self.is_open,
286        }]
287    }
288
289    fn apply(&mut self, event: Event) -> Option<Event> {
290        match event {
291            Event::OverviewOpenedOrClosed { is_open } => {
292                self.is_open = is_open;
293            }
294            event => return Some(event),
295        }
296        None
297    }
298}
299
300impl EventStreamStatePart for ConfigState {
301    fn replicate(&self) -> Vec<Event> {
302        vec![Event::ConfigLoaded {
303            failed: self.failed,
304        }]
305    }
306
307    fn apply(&mut self, event: Event) -> Option<Event> {
308        match event {
309            Event::ConfigLoaded { failed } => {
310                self.failed = failed;
311            }
312            event => return Some(event),
313        }
314        None
315    }
316}
317
318impl EventStreamStatePart for CastsState {
319    fn replicate(&self) -> Vec<Event> {
320        let casts = self.casts.values().cloned().collect();
321        vec![Event::CastsChanged { casts }]
322    }
323
324    fn apply(&mut self, event: Event) -> Option<Event> {
325        match event {
326            Event::CastsChanged { casts } => {
327                self.casts = casts.into_iter().map(|c| (c.stream_id, c)).collect();
328            }
329            Event::CastStartedOrChanged { cast } => {
330                self.casts.insert(cast.stream_id, cast);
331            }
332            Event::CastStopped { stream_id } => {
333                let cast = self.casts.remove(&stream_id);
334                cast.expect("stopped cast was missing from the map");
335            }
336            event => return Some(event),
337        }
338        None
339    }
340}
341
342impl EventStreamStatePart for TouchpadState {
343    fn replicate(&self) -> Vec<Event> {
344        vec![Event::TouchpadToggled { on: self.on }]
345    }
346
347    fn apply(&mut self, event: Event) -> Option<Event> {
348        match event {
349            Event::TouchpadToggled { on } => {
350                self.on = on;
351            }
352            event => return Some(event),
353        }
354        None
355    }
356}