Skip to main content

crabshell_services/
niri.rs

1//! niri's workspaces, windows, keyboard layouts and overview, over its IPC
2//! socket at `$NIRI_SOCKET`. A request is one JSON line, answered with
3//! one, and `"EventStream"` turns a connection into a stream of events,
4//! a JSON line each, the first ones giving the whole state.
5
6#[cfg(test)]
7mod tests;
8
9use std::cell::{RefCell, RefMut};
10use std::io::{ErrorKind, Read, Write};
11use std::net::Shutdown;
12use std::os::fd::AsFd;
13use std::os::unix::net::UnixStream;
14use std::panic::{self, AssertUnwindSafe, Location};
15use std::path::Path;
16use std::rc::Rc;
17use std::sync::Once;
18
19use calloop::{Interest, RegistrationToken};
20use crabshell_reactive::{Owner, ReadSignal, Signal};
21use crabshell_ui::Cx;
22use serde::de::{DeserializeOwned, Error as _, IgnoredAny};
23use serde::{Deserialize, Deserializer};
24use serde_json::Value;
25
26use crate::Shared;
27use crate::dbus::set_changed;
28use crate::hyprland::{cut, open};
29use crate::lines::{MAX_LINE, panic_message};
30
31/// The most workspaces, windows or layout names kept; the rest are left
32/// out.
33pub(crate) const MAX_LIST: usize = 4096;
34
35/// The longest action sent, as a JSON line.
36pub(crate) const MAX_REQUEST: usize = 8 * 1024;
37
38/// The most actions waiting for niri's reply; one past it isn't sent, so
39/// a config acting in a loop can't pile up connections.
40pub(crate) const MAX_ACTIONS: usize = 64;
41
42/// One of niri's workspaces, as its IPC describes it.
43#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
44pub struct NiriWorkspace {
45  /// niri's id for it, which stays while it exists: the key to give
46  /// `children_keyed`, and what [`Niri::focus_workspace`] takes.
47  pub id: u64,
48  /// Its place on its output, from 1. It changes as workspaces move.
49  pub idx: u32,
50  /// Its name, if the config gave it one.
51  #[serde(default, deserialize_with = "some_text")]
52  pub name: Option<String>,
53  /// The output it is on, such as `DP-1`; `None` while no output is
54  /// connected.
55  #[serde(default, deserialize_with = "some_text")]
56  pub output: Option<String>,
57  /// Whether it is shown on its output.
58  pub is_active: bool,
59  /// Whether it has the focus; one workspace across all outputs does.
60  pub is_focused: bool,
61  /// Whether a window on it asks for attention.
62  #[serde(default)]
63  pub is_urgent: bool,
64  /// The id of the window that is active on it, if any.
65  #[serde(default)]
66  pub active_window_id: Option<u64>,
67}
68
69/// One of niri's windows, as its IPC describes it.
70#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
71pub struct NiriWindow {
72  /// niri's id for it, which stays while it is open: the key to give
73  /// `children_keyed`, and what [`Niri::focus_window`] takes.
74  pub id: u64,
75  /// Its title, if it set one.
76  #[serde(default, deserialize_with = "some_text")]
77  pub title: Option<String>,
78  /// Its app id, if it set one.
79  #[serde(default, deserialize_with = "some_text")]
80  pub app_id: Option<String>,
81  /// The id of the workspace it is on, if any.
82  #[serde(default)]
83  pub workspace_id: Option<u64>,
84  /// Whether it has the keyboard focus.
85  pub is_focused: bool,
86  /// Whether it asks for attention.
87  #[serde(default)]
88  pub is_urgent: bool,
89}
90
91/// niri's keyboard layouts.
92#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
93pub struct NiriKeyboardLayouts {
94  /// Each layout's XKB name, such as `English (US)`.
95  #[serde(deserialize_with = "texts")]
96  pub names: Vec<String>,
97  /// Which of `names` is in use; always one of them.
98  pub current_idx: u32,
99}
100
101/// The niri service, from `cx.niri()`. A clone is cheap and shares the
102/// one connection.
103#[derive(Clone)]
104pub struct Niri {
105  /// `None` when the shell provided no services.
106  service: Option<Rc<Service>>,
107  /// The asking context's owner, which [`on_event`](Self::on_event)'s
108  /// handlers go with.
109  owner: Owner,
110  workspaces: ReadSignal<Vec<NiriWorkspace>>,
111  windows: ReadSignal<Vec<NiriWindow>>,
112  keyboard_layouts: ReadSignal<Option<NiriKeyboardLayouts>>,
113  overview_open: ReadSignal<bool>,
114}
115
116impl Niri {
117  /// Every workspace, by output name and then by `idx`. Empty while niri
118  /// isn't connected.
119  pub fn workspaces(&self) -> ReadSignal<Vec<NiriWorkspace>> {
120    self.workspaces
121  }
122
123  /// Every window, by id. Empty while niri isn't connected.
124  pub fn windows(&self) -> ReadSignal<Vec<NiriWindow>> {
125    self.windows
126  }
127
128  /// The keyboard layouts, once niri has said them.
129  pub fn keyboard_layouts(&self) -> ReadSignal<Option<NiriKeyboardLayouts>> {
130    self.keyboard_layouts
131  }
132
133  /// Whether niri's overview is open.
134  pub fn overview_open(&self) -> ReadSignal<bool> {
135    self.overview_open
136  }
137
138  /// Switches to the workspace with the id `id`.
139  pub fn focus_workspace(&self, id: u64) {
140    self.action(serde_json::json!({ "FocusWorkspace": { "reference": { "Id": id } } }));
141  }
142
143  /// Focuses the window with the id `id`.
144  pub fn focus_window(&self, id: u64) {
145    self.action(serde_json::json!({ "FocusWindow": { "id": id } }));
146  }
147
148  /// Sends niri `{"Action": action}`, as `niri msg action` does, on a
149  /// connection of its own, and never waits for it. `action` is one of
150  /// niri-ipc's `Action`s in JSON, such as
151  /// `json!({ "Spawn": { "command": ["foot"] } })`. niri's refusal is
152  /// logged, and so is an action over 8 KiB, or past 64 waiting for a
153  /// reply, which isn't sent.
154  pub fn action(&self, action: Value) {
155    match &self.service {
156      Some(service) => service.action(action),
157      None => tracing::warn!("no niri to send an action to"),
158    }
159  }
160
161  /// Calls `handler` with every event niri sends, as its JSON, such as
162  /// `{"OverviewOpenedOrClosed":{"is_open":true}}`, until the context
163  /// `cx.niri()` was called on goes. The lists have taken the event in
164  /// by then.
165  ///
166  /// It runs on the main thread. If it panics, that is logged with the
167  /// event's name and where `on_event` was called, and it isn't called
168  /// again. Called on a handle whose context went, it logs that and does
169  /// nothing.
170  #[track_caller]
171  pub fn on_event(&self, handler: impl Fn(&Value) + 'static) {
172    let at = Location::caller();
173    if self.owner.is_disposed() {
174      return tracing::warn!(
175        "niri on_event (called at {at}) on a context that is gone does nothing"
176      );
177    }
178    if let Some(service) = &self.service {
179      let id = service.add_handler(Rc::new(handler), at);
180      self.owner.signal(Unregister(Rc::clone(service), id));
181    }
182  }
183}
184
185/// `cx.niri()`.
186pub(crate) fn niri(cx: &Cx) -> Niri {
187  let Some(service) = cx.service::<Service>() else {
188    static LOGGED: Once = Once::new();
189    LOGGED.call_once(|| {
190      tracing::warn!("cx.niri() needs the services the shell provides; it shows nothing");
191    });
192    return Niri {
193      service: None,
194      owner: cx.owner(),
195      workspaces: cx.signal(Vec::new()).read_only(),
196      windows: cx.signal(Vec::new()).read_only(),
197      keyboard_layouts: cx.signal(None).read_only(),
198      overview_open: cx.signal(false).read_only(),
199    };
200  };
201  let (workspaces, windows, keyboard_layouts, overview_open) = service.start();
202  Niri {
203    service: Some(service),
204    owner: cx.owner(),
205    workspaces: workspaces.read_only(),
206    windows: windows.read_only(),
207    keyboard_layouts: keyboard_layouts.read_only(),
208    overview_open: overview_open.read_only(),
209  }
210}
211
212type Signals = (
213  Signal<Vec<NiriWorkspace>>,
214  Signal<Vec<NiriWindow>>,
215  Signal<Option<NiriKeyboardLayouts>>,
216  Signal<bool>,
217);
218
219/// The one niri connection of a shell, started on first use.
220pub(crate) struct Service {
221  shared: Rc<Shared>,
222  state: RefCell<Option<State>>,
223}
224
225struct State {
226  workspaces: Signal<Vec<NiriWorkspace>>,
227  windows: Signal<Vec<NiriWindow>>,
228  keyboard_layouts: Signal<Option<NiriKeyboardLayouts>>,
229  overview_open: Signal<bool>,
230  /// What niri's events say, shown in the signals after each read.
231  raw: Raw,
232  /// The event stream, while it is open.
233  stream: Option<Stream>,
234  /// Whether the stream was opened again since niri last sent an event
235  /// that isn't one of [`STATE_EVENTS`].
236  reconnected: bool,
237  /// Actions waiting for niri's reply.
238  actions: Vec<Action>,
239  next_action: u64,
240  /// What `on_event` was given, in the order it was.
241  handlers: Vec<Handler>,
242  next_handler: u64,
243}
244
245#[derive(Default)]
246struct Raw {
247  /// By output and `idx`.
248  workspaces: Vec<NiriWorkspace>,
249  /// By id.
250  windows: Vec<NiriWindow>,
251  keyboard_layouts: Option<NiriKeyboardLayouts>,
252  overview_open: bool,
253}
254
255struct Stream {
256  stream: UnixStream,
257  reader: RegistrationToken,
258  /// What was read past the last whole line.
259  inbox: Vec<u8>,
260  /// Whether niri's reply to `"EventStream"`, its first line, came.
261  answered: bool,
262}
263
264struct Action {
265  id: u64,
266  stream: UnixStream,
267  reader: RegistrationToken,
268  reply: Vec<u8>,
269}
270
271/// A config's raw-event handler.
272#[derive(Clone)]
273struct Handler {
274  id: u64,
275  /// Where `on_event` was called, for the log if it panics.
276  at: &'static Location<'static>,
277  handler: Rc<dyn Fn(&Value)>,
278}
279
280/// Drops a handler when the context it was given in goes.
281struct Unregister(Rc<Service>, u64);
282
283impl Drop for Unregister {
284  fn drop(&mut self) {
285    let handler = self.0.remove_handler(self.1);
286    // Dropped outside the borrow: the handler may hold a `Niri`.
287    drop(handler);
288  }
289}
290
291/// niri's reply to a request.
292#[derive(Deserialize)]
293enum Reply {
294  Ok(IgnoredAny),
295  Err(String),
296}
297
298impl Service {
299  pub(crate) fn new(shared: Rc<Shared>) -> Service {
300    Service {
301      shared,
302      state: RefCell::new(None),
303    }
304  }
305
306  /// The signals, connecting to niri if this is the first ask.
307  fn start(self: &Rc<Self>) -> Signals {
308    if self.state.borrow().is_none() {
309      let root = &self.shared.root;
310      *self.state.borrow_mut() = Some(State {
311        workspaces: root.signal(Vec::new()),
312        windows: root.signal(Vec::new()),
313        keyboard_layouts: root.signal(None),
314        overview_open: root.signal(false),
315        raw: Raw::default(),
316        stream: None,
317        reconnected: false,
318        actions: Vec::new(),
319        next_action: 0,
320        handlers: Vec::new(),
321        next_handler: 0,
322      });
323      match &self.shared.config.niri {
324        None => tracing::info!("NIRI_SOCKET is unset, so there is no niri to show"),
325        Some(path) => {
326          self.connect(path);
327        }
328      }
329    }
330    let state = self.state.borrow();
331    let state = state.as_ref().expect("invariant: started above");
332    (
333      state.workspaces,
334      state.windows,
335      state.keyboard_layouts,
336      state.overview_open,
337    )
338  }
339
340  /// Opens the event stream. A failure is logged and never retried, so a
341  /// stale socket never wakes the shell. `false` if it failed.
342  fn connect(self: &Rc<Self>, path: &Path) -> bool {
343    let Some(event_loop) = self.shared.event_loop() else {
344      return false;
345    };
346    let opened = open(path).and_then(|mut stream| {
347      send(&mut stream, b"\"EventStream\"\n")?;
348      let fd = stream.as_fd().try_clone_to_owned()?;
349      Ok((stream, fd))
350    });
351    let (stream, fd) = match opened {
352      Ok(opened) => opened,
353      Err(error) => {
354        let path = path.display();
355        tracing::warn!(%path, %error, "can't connect to niri, so its lists stay empty");
356        return false;
357      }
358    };
359    let service = Rc::clone(self);
360    let Some(reader) =
361      event_loop.insert_fd(fd, Interest::READ, Box::new(move || service.on_stream()))
362    else {
363      return false;
364    };
365    let mut state = self.state.borrow_mut();
366    let state = state
367      .as_mut()
368      .expect("invariant: started before connecting");
369    state.stream = Some(Stream {
370      stream,
371      reader,
372      inbox: Vec::new(),
373      answered: false,
374    });
375    true
376  }
377
378  /// Whether the lists are still there: their owner, the root, isn't
379  /// disposed.
380  fn alive(&self) -> bool {
381    let state = self.state.borrow();
382    let alive = state
383      .as_ref()
384      .and_then(|state| state.workspaces.try_with(|_| ()));
385    alive.is_some()
386  }
387
388  /// Reads what came on the event stream, takes in each whole event and
389  /// shows the lists, then hands the events to the handlers.
390  fn on_stream(self: &Rc<Self>) {
391    if !self.alive() {
392      return self.close();
393    }
394    let mut chunk = [0; 64 * 1024];
395    let mut guard = self.state.borrow_mut();
396    let state = guard
397      .as_mut()
398      .expect("invariant: started before connecting");
399    let Some(stream) = state.stream.as_mut() else {
400      return;
401    };
402    match stream.stream.read(&mut chunk) {
403      Ok(0) => return self.closed(guard, "niri closed the event stream"),
404      Ok(read) => stream.inbox.extend_from_slice(&chunk[..read]),
405      Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {
406        return;
407      }
408      Err(error) => return self.closed(guard, &error.to_string()),
409    }
410    let Some(whole) = whole_lines(&mut stream.inbox) else {
411      // Reconnecting would only read it again.
412      return self.lost(state, "niri sent a line over 1 MiB");
413    };
414    let mut events = Vec::new();
415    let mut touched = 0;
416    for line in whole
417      .split(|&byte| byte == b'\n')
418      .filter(|line| !line.is_empty())
419    {
420      let stream = state
421        .stream
422        .as_mut()
423        .expect("invariant: open while reading");
424      if !std::mem::replace(&mut stream.answered, true) {
425        if let Some(why) = refusal(line) {
426          tracing::warn!(why, "niri refused the event stream");
427          return self.lost(state, "niri refused the event stream");
428        }
429        continue;
430      }
431      let event: Value = match serde_json::from_slice(line) {
432        Ok(event) => event,
433        Err(error) => {
434          tracing::warn!(%error, "a line from niri's event stream that isn't JSON");
435          continue;
436        }
437      };
438      let name = event_name(&event);
439      if !STATE_EVENTS.contains(&name) {
440        // Past niri's state, so a later close is worth a reconnect.
441        state.reconnected = false;
442      }
443      match state.raw.apply(&event) {
444        Ok(parts) => touched |= parts,
445        Err(error) => tracing::warn!(name, %error, "a bad event from niri"),
446      }
447      if !state.handlers.is_empty() {
448        events.push(event);
449      }
450    }
451    state.show(touched);
452    drop(guard);
453    for event in events {
454      self.deliver(&event);
455    }
456  }
457
458  /// Calls each raw-event handler with `event`, with nothing borrowed.
459  fn deliver(&self, event: &Value) {
460    let handlers = match self.state.borrow().as_ref() {
461      Some(state) => state.handlers.clone(),
462      None => return,
463    };
464    for Handler { id, at, handler } in handlers {
465      let registered = self
466        .state
467        .borrow()
468        .as_ref()
469        .is_some_and(|state| state.handlers.iter().any(|handler| handler.id == id));
470      if !registered {
471        // An earlier handler's context went.
472        continue;
473      }
474      if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(|| handler(event))) {
475        let message = panic_message(payload.as_ref());
476        let name = event_name(event);
477        tracing::error!("niri on_event (called at {at}) panicked on {name}: {message}");
478        drop(self.remove_handler(id));
479      }
480    }
481  }
482
483  fn add_handler(&self, handler: Rc<dyn Fn(&Value)>, at: &'static Location<'static>) -> u64 {
484    let mut state = self.state.borrow_mut();
485    let state = state.as_mut().expect("invariant: started by cx.niri()");
486    let id = state.next_handler;
487    state.next_handler += 1;
488    state.handlers.push(Handler { id, at, handler });
489    id
490  }
491
492  /// Takes out the handler `id`, for the caller to drop once nothing is
493  /// borrowed.
494  fn remove_handler(&self, id: u64) -> Option<Handler> {
495    let mut state = self.state.borrow_mut();
496    let handlers = &mut state.as_mut()?.handlers;
497    let at = handlers.iter().position(|handler| handler.id == id)?;
498    Some(handlers.remove(at))
499  }
500
501  /// Sends `{"Action": action}` on a connection of its own.
502  fn action(self: &Rc<Self>, action: Value) {
503    let (Some(path), Some(event_loop)) = (&self.shared.config.niri, self.shared.event_loop())
504    else {
505      return tracing::warn!("no niri to send an action to");
506    };
507    let mut request = serde_json::json!({ "Action": action }).to_string();
508    request.push('\n');
509    if request.len() > MAX_REQUEST {
510      return tracing::warn!("a niri action over 8 KiB is too long to send");
511    }
512    let mut state = self.state.borrow_mut();
513    let state = state.as_mut().expect("invariant: started by cx.niri()");
514    if state.actions.len() >= MAX_ACTIONS {
515      return tracing::warn!("64 actions wait for niri, so this one isn't sent");
516    }
517    let opened = open(path).and_then(|mut stream| {
518      send(&mut stream, request.as_bytes())?;
519      // niri answers, then reads the end and closes.
520      stream.shutdown(Shutdown::Write)?;
521      let fd = stream.as_fd().try_clone_to_owned()?;
522      Ok((stream, fd))
523    });
524    let (stream, fd) = match opened {
525      Ok(opened) => opened,
526      Err(error) => return tracing::warn!(%error, "can't send niri an action"),
527    };
528    let id = state.next_action;
529    state.next_action += 1;
530    let service = Rc::clone(self);
531    let read = Box::new(move || service.on_reply(id));
532    if let Some(reader) = event_loop.insert_fd(fd, Interest::READ, read) {
533      state.actions.push(Action {
534        id,
535        stream,
536        reader,
537        reply: Vec::new(),
538      });
539    }
540  }
541
542  /// Reads what came of an action's reply, and logs a refusal once niri
543  /// closed the connection.
544  fn on_reply(self: &Rc<Self>, id: u64) {
545    if !self.alive() {
546      return self.close();
547    }
548    let mut chunk = [0; 4096];
549    let mut state = self.state.borrow_mut();
550    let state = state.as_mut().expect("invariant: started before acting");
551    let Some(at) = state.actions.iter().position(|action| action.id == id) else {
552      return;
553    };
554    let action = &mut state.actions[at];
555    let failed = match action.stream.read(&mut chunk) {
556      Ok(0) => None,
557      Ok(read) if action.reply.len() + read > MAX_LINE => Some(String::from("over 1 MiB")),
558      Ok(read) => return action.reply.extend_from_slice(&chunk[..read]),
559      Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {
560        return;
561      }
562      Err(error) => Some(error.to_string()),
563    };
564    let action = state.actions.remove(at);
565    if let Some(event_loop) = self.shared.event_loop() {
566      event_loop.remove(action.reader);
567    }
568    if let Some(why) = failed.or_else(|| refusal(&action.reply)) {
569      tracing::warn!(why, "niri refused an action");
570    }
571  }
572
573  /// The event stream ended for `why`. niri closes a client that falls
574  /// behind and runs on, so while its socket is there, this connects once
575  /// again and takes in the whole state niri sends first, keeping the
576  /// lists meanwhile. A stream that ends again before niri sent an event
577  /// past its state is lost.
578  fn closed(self: &Rc<Self>, mut guard: RefMut<'_, Option<State>>, why: &str) {
579    let state = guard
580      .as_mut()
581      .expect("invariant: started before connecting");
582    let path = self.shared.config.niri.as_deref();
583    let Some(path) = path.filter(|path| !state.reconnected && path.exists()) else {
584      return self.lost(state, why);
585    };
586    tracing::warn!(why, "niri's event stream ended; connecting again");
587    state.reconnected = true;
588    self.drop_stream(state);
589    drop(guard);
590    if !self.connect(path)
591      && let Some(state) = self.state.borrow_mut().as_mut()
592    {
593      self.lost(state, "niri's socket can't be reached again");
594    }
595  }
596
597  /// Drops the event stream and empties the lists. A new niri listens at
598  /// a new path, so nothing reconnects.
599  fn lost(&self, state: &mut State, why: &str) {
600    tracing::warn!(why, "lost niri; its lists are empty");
601    self.drop_stream(state);
602    state.raw = Raw::default();
603    state.show(ALL);
604  }
605
606  /// Closes every connection for good, once the lists are gone.
607  fn close(&self) {
608    if let Some(state) = self.state.borrow_mut().as_mut() {
609      self.drop_stream(state);
610      let actions = std::mem::take(&mut state.actions);
611      if let Some(event_loop) = self.shared.event_loop() {
612        for action in actions {
613          event_loop.remove(action.reader);
614        }
615      }
616    }
617  }
618
619  fn drop_stream(&self, state: &mut State) {
620    if let (Some(stream), Some(event_loop)) = (state.stream.take(), self.shared.event_loop()) {
621      event_loop.remove(stream.reader);
622    }
623  }
624}
625
626impl State {
627  /// Sets each signal of the `parts` given whose value changed.
628  fn show(&self, parts: u8) {
629    let raw = &self.raw;
630    if parts & WORKSPACES != 0 {
631      set_changed(self.workspaces, raw.workspaces.clone());
632    }
633    if parts & WINDOWS != 0 {
634      set_changed(self.windows, raw.windows.clone());
635    }
636    if parts & LAYOUTS != 0 {
637      set_changed(self.keyboard_layouts, raw.keyboard_layouts.clone());
638    }
639    if parts & OVERVIEW != 0 {
640      set_changed(self.overview_open, raw.overview_open);
641    }
642  }
643}
644
645/// The parts of [`Raw`] an event can change, as bits.
646const WORKSPACES: u8 = 1;
647const WINDOWS: u8 = 2;
648const LAYOUTS: u8 = 4;
649const OVERVIEW: u8 = 8;
650const ALL: u8 = WORKSPACES | WINDOWS | LAYOUTS | OVERVIEW;
651
652/// The events niri sends a new stream as its whole state, from niri-ipc's
653/// `EventStreamState::replicate`.
654const STATE_EVENTS: [&str; 7] = [
655  "WorkspacesChanged",
656  "WindowsChanged",
657  "KeyboardLayoutsChanged",
658  "OverviewOpenedOrClosed",
659  "ConfigLoaded",
660  "CastsChanged",
661  "TouchpadToggled",
662];
663
664impl Raw {
665  /// Takes in one event, as niri-ipc's `EventStreamState` does. An event
666  /// this doesn't know is skipped, since niri adds events between
667  /// versions, and so is one about a workspace or window it doesn't have.
668  /// Which parts it changed, as bits.
669  fn apply(&mut self, event: &Value) -> Result<u8, serde_json::Error> {
670    let Some((name, body)) = event
671      .as_object()
672      .filter(|event| event.len() == 1)
673      .and_then(|event| event.iter().next())
674    else {
675      return Err(serde_json::Error::custom("not an event"));
676    };
677    match name.as_str() {
678      "WorkspacesChanged" => {
679        self.workspaces = list("workspace", body, "workspaces")?;
680        let order = |workspace: &NiriWorkspace| (workspace.output.clone(), workspace.idx);
681        self.workspaces.sort_by_key(order);
682      }
683      "WorkspaceActivated" => {
684        let id: u64 = get(body, "id")?;
685        let focused: bool = get(body, "focused")?;
686        let Some(output) = self.workspace(id).map(|workspace| workspace.output.clone()) else {
687          return Ok(0);
688        };
689        for workspace in &mut self.workspaces {
690          let activated = workspace.id == id;
691          if workspace.output == output {
692            workspace.is_active = activated;
693          }
694          if focused {
695            workspace.is_focused = activated;
696          }
697        }
698      }
699      "WorkspaceActiveWindowChanged" => {
700        let id: u64 = get(body, "workspace_id")?;
701        let window = get(body, "active_window_id")?;
702        if let Some(workspace) = self.workspace(id) {
703          workspace.active_window_id = window;
704        }
705      }
706      "WorkspaceUrgencyChanged" => {
707        let urgent = get(body, "urgent")?;
708        if let Some(workspace) = self.workspace(get(body, "id")?) {
709          workspace.is_urgent = urgent;
710        }
711      }
712      "WindowsChanged" => {
713        self.windows = list("window", body, "windows")?;
714        self.windows.sort_by_key(|window| window.id);
715      }
716      "WindowOpenedOrChanged" => {
717        let window: NiriWindow = get(body, "window")?;
718        let id = window.id;
719        if window.is_focused {
720          for other in &mut self.windows {
721            other.is_focused = false;
722          }
723        }
724        match self.windows.binary_search_by_key(&id, |window| window.id) {
725          Ok(at) => self.windows[at] = window,
726          Err(_) if self.windows.len() >= MAX_LIST => {
727            tracing::warn!("niri has more windows than the {MAX_LIST} kept");
728          }
729          Err(at) => self.windows.insert(at, window),
730        }
731      }
732      "WindowClosed" => {
733        let id: u64 = get(body, "id")?;
734        self.windows.retain(|window| window.id != id);
735      }
736      "WindowFocusChanged" => {
737        let id: Option<u64> = get(body, "id")?;
738        for window in &mut self.windows {
739          window.is_focused = Some(window.id) == id;
740        }
741      }
742      "WindowUrgencyChanged" => {
743        let (id, urgent): (u64, bool) = (get(body, "id")?, get(body, "urgent")?);
744        if let Some(window) = self.windows.iter_mut().find(|window| window.id == id) {
745          window.is_urgent = urgent;
746        }
747      }
748      "KeyboardLayoutsChanged" => {
749        let layouts: NiriKeyboardLayouts = get(body, "keyboard_layouts")?;
750        in_names(&layouts.names, layouts.current_idx)?;
751        self.keyboard_layouts = Some(layouts);
752      }
753      "KeyboardLayoutSwitched" => {
754        let idx = get(body, "idx")?;
755        if let Some(layouts) = &mut self.keyboard_layouts {
756          in_names(&layouts.names, idx)?;
757          layouts.current_idx = idx;
758        }
759      }
760      "OverviewOpenedOrClosed" => self.overview_open = get(body, "is_open")?,
761      _ => return Ok(0),
762    }
763    Ok(match name.as_str() {
764      name if name.starts_with("Workspace") => WORKSPACES,
765      name if name.starts_with("Window") => WINDOWS,
766      name if name.starts_with("Keyboard") => LAYOUTS,
767      _ => OVERVIEW,
768    })
769  }
770
771  fn workspace(&mut self, id: u64) -> Option<&mut NiriWorkspace> {
772    self
773      .workspaces
774      .iter_mut()
775      .find(|workspace| workspace.id == id)
776  }
777}
778
779/// Refuses a layout index past `names`, as after their cap, so
780/// `names[current_idx]` is always there.
781fn in_names(names: &[String], idx: u32) -> Result<(), serde_json::Error> {
782  match usize::try_from(idx) {
783    Ok(idx) if idx < names.len() => Ok(()),
784    _ => Err(serde_json::Error::custom("a layout index past the names")),
785  }
786}
787
788/// The field `key` of an event's body.
789fn get<'a, T: Deserialize<'a>>(body: &'a Value, key: &str) -> Result<T, serde_json::Error> {
790  T::deserialize(body.get(key).unwrap_or(&Value::Null))
791}
792
793/// The entries of the list at `key`, at most [`MAX_LIST`], leaving out
794/// those that don't parse, which is logged.
795fn list<T: DeserializeOwned>(
796  what: &str,
797  body: &Value,
798  key: &str,
799) -> Result<Vec<T>, serde_json::Error> {
800  let Some(entries) = body.get(key).and_then(Value::as_array) else {
801    return Err(serde_json::Error::custom(format!("no {key} list")));
802  };
803  if entries.len() > MAX_LIST {
804    let listed = entries.len();
805    tracing::warn!(listed, "niri listed more {what}s than the {MAX_LIST} kept");
806  }
807  let mut bad = 0;
808  let list = entries
809    .iter()
810    .take(MAX_LIST)
811    .filter_map(|entry| T::deserialize(entry).inspect_err(|_| bad += 1).ok())
812    .collect();
813  if bad > 0 {
814    tracing::warn!(bad, "niri described some {what}s badly; they are left out");
815  }
816  Ok(list)
817}
818
819/// An event's name, its one key, for a log line.
820fn event_name(event: &Value) -> &str {
821  let keys = event.as_object().and_then(|event| event.keys().next());
822  keys.map_or("an event", String::as_str)
823}
824
825/// What `inbox` holds up to its last line break, leaving the rest.
826/// `None` when a line in it, or the rest, is over [`MAX_LINE`].
827fn whole_lines(inbox: &mut Vec<u8>) -> Option<Vec<u8>> {
828  let end = inbox
829    .iter()
830    .rposition(|&byte| byte == b'\n')
831    .map_or(0, |at| at + 1);
832  let rest = inbox.split_off(end);
833  let whole = std::mem::replace(inbox, rest);
834  let long = whole
835    .split(|&byte| byte == b'\n')
836    .any(|line| line.len() > MAX_LINE);
837  (!long && inbox.len() <= MAX_LINE).then_some(whole)
838}
839
840/// Why niri's `reply` to a request refuses it, or `None` for `Ok`.
841fn refusal(reply: &[u8]) -> Option<String> {
842  match serde_json::from_slice(reply.trim_ascii()) {
843    Ok(Reply::Ok(_)) => None,
844    Ok(Reply::Err(why)) => Some(cut(why)),
845    Err(_) => Some(cut(format!(
846      "a bad reply: {}",
847      String::from_utf8_lossy(reply)
848    ))),
849  }
850}
851
852/// Writes `request` in one write: the socket is new, so it has room.
853fn send(stream: &mut UnixStream, request: &[u8]) -> std::io::Result<()> {
854  if stream.write(request)? < request.len() {
855    return Err(std::io::Error::other("the request didn't fit the socket"));
856  }
857  Ok(())
858}
859
860fn some_text<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<String>, D::Error> {
861  Option::<String>::deserialize(deserializer).map(|text| text.map(cut))
862}
863
864fn texts<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D::Error> {
865  let texts = Vec::<String>::deserialize(deserializer)?;
866  Ok(texts.into_iter().take(MAX_LIST).map(cut).collect())
867}