Skip to main content

crabshell_services/
hyprland.rs

1//! Hyprland's workspaces, monitors and windows, over its two IPC sockets
2//! in `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/`:
3//! `.socket.sock` takes one request per connection, such as
4//! `j/workspaces`, answers and closes, and `.socket2.sock` sends events
5//! as lines of `NAME>>DATA`.
6
7#[cfg(test)]
8mod tests;
9
10use std::cell::{RefCell, RefMut};
11use std::collections::{HashSet, VecDeque};
12use std::io::{ErrorKind, Read, Write};
13use std::net::Shutdown;
14use std::os::fd::AsFd;
15use std::os::unix::net::UnixStream;
16use std::panic::{self, AssertUnwindSafe, Location};
17use std::path::Path;
18use std::rc::Rc;
19use std::sync::Once;
20use std::time::{Duration, Instant};
21
22use calloop::timer::TimeoutAction;
23use calloop::{Interest, RegistrationToken};
24use crabshell_reactive::{Owner, ReadSignal, Signal};
25use crabshell_ui::Cx;
26use serde::de::DeserializeOwned;
27use serde::{Deserialize, Deserializer};
28
29use crate::Shared;
30use crate::dbus::set_changed;
31use crate::lines::{Lines, panic_message};
32
33/// The largest reply read from one request; a larger one is dropped.
34pub(crate) const MAX_REPLY: usize = 8 * 1024 * 1024;
35
36/// The longest request sent; a dispatch past it is refused.
37pub(crate) const MAX_REQUEST: usize = 8 * 1024;
38
39/// The most dispatches waiting to be sent or answered; one past it is
40/// refused, so a config dispatching in a loop can't grow the queue.
41const MAX_DISPATCHES: usize = 64;
42
43/// The most requests out at once. Hyprland's listen backlog holds 10, and
44/// a connect to a full one would block the loop.
45const MAX_IN_FLIGHT: usize = 8;
46
47/// How long a request another program's full backlog holds up waits
48/// before it tries again, when none of the shell's requests is out to
49/// end and make it try sooner: first [`RETRY`], twice as long after
50/// each try that fails, up to [`MAX_RETRY`], and [`RETRY`] again once
51/// a send gets out.
52const RETRY: Duration = Duration::from_millis(100);
53const MAX_RETRY: Duration = Duration::from_secs(2);
54
55/// The longest text kept, cut at a character.
56pub(crate) const MAX_TEXT: usize = 4 * 1024;
57
58/// The most workspaces, monitors or windows kept; the rest are left out.
59pub(crate) const MAX_LIST: usize = 4096;
60
61/// One of Hyprland's workspaces, as `j/workspaces` describes it.
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct HyprlandWorkspace {
64  /// Its number. Named and special workspaces have none from Hyprland
65  /// 0.57 on, and a number below zero before it.
66  pub id: Option<i64>,
67  /// Its name, such as `1`, `web` or `special:magic`: the key to give
68  /// `children_keyed`.
69  pub name: String,
70  /// The name of the monitor it is on, such as `DP-1`.
71  pub monitor: String,
72  /// How many windows it holds.
73  pub windows: u32,
74  /// Whether it is shown on the focused monitor.
75  pub focused: bool,
76  /// Whether it is shown on its monitor, focused or not.
77  pub active: bool,
78  /// Whether a window on it asks for attention.
79  pub urgent: bool,
80}
81
82/// One of Hyprland's monitors, as `j/monitors` describes it.
83#[derive(Clone, Debug, PartialEq)]
84pub struct HyprlandMonitor {
85  /// Hyprland's number for it.
86  pub id: i64,
87  /// Its name, such as `DP-1`, as the output's name.
88  pub name: String,
89  /// Its make, model and serial, as Hyprland puts them.
90  pub description: String,
91  /// Whether it has the focus.
92  pub focused: bool,
93  /// The name of the workspace it shows.
94  pub active_workspace: String,
95  /// Where its left edge is, in the layout's logical pixels.
96  pub x: i32,
97  /// Where its top edge is, in the layout's logical pixels.
98  pub y: i32,
99  /// Its mode's width, in pixels before scaling.
100  pub width: i32,
101  /// Its mode's height, in pixels before scaling.
102  pub height: i32,
103  /// Its scale, such as 1.5.
104  pub scale: f64,
105}
106
107/// One of Hyprland's windows, as `j/clients` describes it.
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct HyprlandToplevel {
110  /// Its address, such as `0x55d4c8a3b0c0`: the key to give
111  /// `children_keyed`, and what a dispatcher names it by, as
112  /// `address:0x55d4c8a3b0c0`.
113  pub address: String,
114  /// Its class, the app id.
115  pub class: String,
116  /// Its title.
117  pub title: String,
118  /// The name of the workspace it is on.
119  pub workspace: String,
120  /// The name of the monitor it is on, or `""` while Hyprland doesn't
121  /// list that monitor.
122  pub monitor: String,
123  /// Whether it floats.
124  pub floating: bool,
125  /// Whether it is fullscreen; a maximized window isn't, except on
126  /// Hyprland 0.41 and older, which say only that it covers the screen.
127  pub fullscreen: bool,
128  /// Whether it has the keyboard focus.
129  pub focused: bool,
130  /// Whether it asks for attention: from its `urgent` event until it is
131  /// focused.
132  pub urgent: bool,
133}
134
135/// One line from Hyprland's event socket, such as `workspacev2>>2,2`,
136/// as Quickshell's `HyprlandEvent`.
137#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct HyprlandEvent {
139  /// What happened, such as `workspacev2` or `submap`.
140  pub name: String,
141  /// What Hyprland sent with it, such as `2,2`: its fields joined by
142  /// commas.
143  pub data: String,
144}
145
146impl HyprlandEvent {
147  /// The data split into at most `fields` fields, as Quickshell's
148  /// `parse(n)`: the last keeps its commas, as a window title in
149  /// `windowtitlev2>>5a1,vim, the editor` does.
150  pub fn parse(&self, fields: usize) -> Vec<&str> {
151    self.data.splitn(fields, ',').collect()
152  }
153}
154
155/// The Hyprland service, from `cx.hyprland()`. A clone is cheap and
156/// shares the one connection.
157#[derive(Clone)]
158pub struct Hyprland {
159  /// `None` when the shell provided no services.
160  service: Option<Rc<Service>>,
161  /// The asking context's owner, which [`on_event`](Self::on_event)'s
162  /// handlers go with.
163  owner: Owner,
164  workspaces: ReadSignal<Vec<HyprlandWorkspace>>,
165  monitors: ReadSignal<Vec<HyprlandMonitor>>,
166  toplevels: ReadSignal<Vec<HyprlandToplevel>>,
167}
168
169impl Hyprland {
170  /// Switches to the workspace `target`, as Hyprland names it: a number
171  /// such as `2`, or `name:web`. Hyprland reads a dispatch as Lua when its
172  /// config is Lua, as `hyprland.lua` can be from 0.55 on and always is
173  /// from 0.57 on, and as `workspace 2` otherwise. So the first call asks
174  /// Hyprland's status, and switches wait for its answer. Under Lua
175  /// `target` goes as a quoted Lua string, so no name runs as code; in the
176  /// old syntax it goes as it is, so a target with whitespace or a control
177  /// character is logged and not sent. Hyprland's refusal is logged.
178  pub fn focus_workspace(&self, target: &str) {
179    match &self.service {
180      Some(service) => service.focus_workspace(target),
181      None => tracing::warn!(target, "no Hyprland to dispatch to"),
182    }
183  }
184
185  /// Sends Hyprland `dispatch command`, as `hyprctl dispatch` does, on a
186  /// connection of its own, and never waits for it. Hyprland's refusal is
187  /// logged, and so is a command over 8 KiB, which isn't sent.
188  ///
189  /// When Hyprland's config is Lua, as `hyprland.lua` can be from 0.55 on
190  /// and always is from 0.57 on, `command` is a Lua expression that
191  /// Hyprland runs inside the compositor, such as
192  /// `hl.dsp.focus({ workspace = "2" })`. Otherwise it is a dispatcher and
193  /// its arguments, such as `workspace 2`. Either way, never put outside
194  /// text, such as a window's title or class or a workspace's name, into
195  /// it: under Lua what it says would run. Switch workspaces with
196  /// [`focus_workspace`](Self::focus_workspace), which quotes them.
197  pub fn dispatch(&self, command: &str) {
198    match &self.service {
199      Some(service) => service.dispatch(command),
200      None => tracing::warn!(command, "no Hyprland to dispatch to"),
201    }
202  }
203
204  /// Calls `handler` with every event Hyprland sends, as Quickshell's
205  /// `rawEvent`, until the context `cx.hyprland()` was called on goes.
206  /// The lists follow once Hyprland answers the reads an event starts,
207  /// after `handler` runs.
208  ///
209  /// It runs on the main thread. If it panics, that is logged with the
210  /// event and where `on_event` was called, and it isn't called again.
211  ///
212  /// Called on a handle whose context went, it logs that and does
213  /// nothing.
214  #[track_caller]
215  pub fn on_event(&self, handler: impl Fn(&HyprlandEvent) + 'static) {
216    let at = Location::caller();
217    if self.owner.is_disposed() {
218      return tracing::warn!(
219        "Hyprland on_event (called at {at}) on a context that is gone does nothing"
220      );
221    }
222    if let Some(service) = &self.service {
223      let id = service.add_handler(Rc::new(handler), at);
224      self.owner.signal(Unregister(Rc::clone(service), id));
225    }
226  }
227  /// Every workspace, numbered ones by number after the named ones.
228  /// Empty while Hyprland isn't connected.
229  pub fn workspaces(&self) -> ReadSignal<Vec<HyprlandWorkspace>> {
230    self.workspaces
231  }
232
233  /// Every monitor, in Hyprland's order.
234  pub fn monitors(&self) -> ReadSignal<Vec<HyprlandMonitor>> {
235    self.monitors
236  }
237
238  /// Every mapped window, in Hyprland's order.
239  pub fn toplevels(&self) -> ReadSignal<Vec<HyprlandToplevel>> {
240    self.toplevels
241  }
242}
243
244/// `cx.hyprland()`.
245pub(crate) fn hyprland(cx: &Cx) -> Hyprland {
246  let Some(service) = cx.service::<Service>() else {
247    static LOGGED: Once = Once::new();
248    LOGGED.call_once(|| {
249      tracing::warn!("cx.hyprland() needs the services the shell provides; it shows nothing");
250    });
251    return Hyprland {
252      service: None,
253      owner: cx.owner(),
254      workspaces: cx.signal(Vec::new()).read_only(),
255      monitors: cx.signal(Vec::new()).read_only(),
256      toplevels: cx.signal(Vec::new()).read_only(),
257    };
258  };
259  let (workspaces, monitors, toplevels) = service.start();
260  Hyprland {
261    service: Some(service),
262    owner: cx.owner(),
263    workspaces: workspaces.read_only(),
264    monitors: monitors.read_only(),
265    toplevels: toplevels.read_only(),
266  }
267}
268
269/// A list read whole with one request.
270#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271enum Query {
272  Workspaces,
273  Monitors,
274  Clients,
275  ActiveWindow,
276}
277
278impl Query {
279  const ALL: [Query; 4] = [
280    Query::Workspaces,
281    Query::Monitors,
282    Query::Clients,
283    Query::ActiveWindow,
284  ];
285
286  fn command(self) -> &'static str {
287    match self {
288      Query::Workspaces => "j/workspaces",
289      Query::Monitors => "j/monitors",
290      Query::Clients => "j/clients",
291      Query::ActiveWindow => "j/activewindow",
292    }
293  }
294
295  /// What reads again after the event `name`. Hyprland sends an event's
296  /// two versions together, and both count, for a Hyprland that lacks
297  /// one.
298  fn after(name: &str) -> &'static [Query] {
299    use Query::{ActiveWindow, Clients, Monitors, Workspaces};
300    match name.strip_suffix("v2").unwrap_or(name) {
301      "workspace" | "focusedmon" | "createworkspace" | "destroyworkspace" | "activespecial" => {
302        &[Workspaces, Monitors]
303      }
304      // Windows name their workspace and monitor too.
305      "moveworkspace" | "renameworkspace" | "changeworkspaceid" | "monitoradded"
306      | "monitorremoved" | "configreloaded" => &[Workspaces, Monitors, Clients],
307      "openwindow" | "closewindow" | "movewindow" => &[Workspaces, Clients],
308      "windowtitle" | "changefloatingmode" | "fullscreen" => &[Clients],
309      // A focused window's new class comes only as `activewindow`.
310      "activewindow" => &[Clients, ActiveWindow],
311      _ => &[],
312    }
313  }
314}
315
316/// Where the reading of one list stands.
317#[derive(Clone, Copy, PartialEq, Eq)]
318enum Reading {
319  Idle,
320  Busy,
321  /// Busy, and an event came meanwhile, which the answer may predate, so
322  /// it reads again when done.
323  Stale,
324}
325
326type Lists = (
327  Signal<Vec<HyprlandWorkspace>>,
328  Signal<Vec<HyprlandMonitor>>,
329  Signal<Vec<HyprlandToplevel>>,
330);
331
332/// The one Hyprland connection of a shell, started on first use.
333pub(crate) struct Service {
334  shared: Rc<Shared>,
335  state: RefCell<Option<State>>,
336}
337
338struct State {
339  workspaces: Signal<Vec<HyprlandWorkspace>>,
340  monitors: Signal<Vec<HyprlandMonitor>>,
341  toplevels: Signal<Vec<HyprlandToplevel>>,
342  /// The event socket, while it is open.
343  events: Option<Events>,
344  /// By [`Query`].
345  reading: [Reading; 4],
346  /// By [`Query`], the burst a list's read in flight was started for, if
347  /// one was: a show waits for the rest of it. A read again after a later
348  /// event belongs to none, so no list that keeps reading holds the others.
349  burst_of: [Option<u64>; 4],
350  /// The bursts whose reads aren't all answered.
351  bursts: Vec<Burst>,
352  next_burst: u64,
353  /// Requests waiting for their reply.
354  requests: Vec<Request>,
355  next_request: u64,
356  /// Whether a request that couldn't connect was logged, so a missing
357  /// request socket logs once.
358  request_failure_logged: bool,
359  raw: Raw,
360  /// The windows that asked for attention since they were last focused,
361  /// by address, as only events say.
362  urgent: HashSet<String>,
363  /// What `on_event` was given, in the order it was.
364  handlers: Vec<Handler>,
365  next_handler: u64,
366  /// Whether Hyprland reads a dispatch as Lua, as it does when its config
367  /// is, once `j/status` said.
368  lua: Option<bool>,
369  /// Whether `j/status` was asked and not answered yet.
370  status_asked: bool,
371  /// What `focus_workspace` was given before the syntax was known.
372  focusing: Vec<String>,
373  /// Requests waiting for fewer than [`MAX_IN_FLIGHT`] to be out.
374  queued: VecDeque<(Asked, String)>,
375  /// The timer that tries the queue again, while another program's
376  /// backlog holds it up and none of the shell's requests is out.
377  retry: Option<RegistrationToken>,
378  /// How long the next retry waits.
379  retry_wait: Duration,
380  /// The urgent windows from before the event socket was connected
381  /// again, which the events Hyprland dropped may have focused or closed.
382  recheck: Option<Recheck>,
383  /// Whether the event socket was connected again since its last event.
384  reconnected: bool,
385}
386
387/// The reads one batch of events, or a connect, started.
388struct Burst {
389  id: u64,
390  started: usize,
391  /// How many aren't answered yet.
392  out: usize,
393}
394
395/// Urgency to check against the first window list and focused window
396/// read after a reconnect.
397struct Recheck {
398  urgent: HashSet<String>,
399  /// The first request sent after the reconnect: earlier ones' answers
400  /// predate it.
401  from: u64,
402  windows: bool,
403  active: bool,
404}
405
406/// What became of a request [`Service::send`] tried.
407enum Sent {
408  Out,
409  /// Hyprland's backlog is full, so it waits.
410  Full,
411  Failed,
412}
413
414/// What a request asks Hyprland.
415#[derive(Clone, Copy, Debug, PartialEq, Eq)]
416enum Asked {
417  List(Query),
418  Status,
419  Dispatch,
420}
421
422/// A config's raw-event handler.
423#[derive(Clone)]
424struct Handler {
425  id: u64,
426  /// Where `on_event` was called, for the log if it panics.
427  at: &'static Location<'static>,
428  handler: Rc<dyn Fn(&HyprlandEvent)>,
429}
430
431/// Drops a handler when the context it was given in goes.
432struct Unregister(Rc<Service>, u64);
433
434impl Drop for Unregister {
435  fn drop(&mut self) {
436    let handler = self.0.remove_handler(self.1);
437    // Dropped outside the borrow: the handler may hold a `Hyprland`.
438    drop(handler);
439  }
440}
441
442/// What Hyprland last said, the lists are built from.
443#[derive(Default)]
444struct Raw {
445  workspaces: Vec<RawWorkspace>,
446  monitors: Vec<RawMonitor>,
447  windows: Vec<RawWindow>,
448  /// The focused window's address.
449  active: Option<String>,
450}
451
452struct Events {
453  stream: UnixStream,
454  reader: RegistrationToken,
455  lines: Lines,
456}
457
458struct Request {
459  id: u64,
460  asked: Asked,
461  stream: UnixStream,
462  reader: RegistrationToken,
463  reply: Vec<u8>,
464}
465
466impl Service {
467  pub(crate) fn new(shared: Rc<Shared>) -> Service {
468    Service {
469      shared,
470      state: RefCell::new(None),
471    }
472  }
473
474  /// The lists, connecting to Hyprland if this is the first ask.
475  fn start(self: &Rc<Self>) -> Lists {
476    if self.state.borrow().is_none() {
477      let root = &self.shared.root;
478      *self.state.borrow_mut() = Some(State {
479        workspaces: root.signal(Vec::new()),
480        monitors: root.signal(Vec::new()),
481        toplevels: root.signal(Vec::new()),
482        events: None,
483        reading: [Reading::Idle; 4],
484        burst_of: [None; 4],
485        bursts: Vec::new(),
486        next_burst: 0,
487        requests: Vec::new(),
488        next_request: 0,
489        request_failure_logged: false,
490        raw: Raw::default(),
491        urgent: HashSet::new(),
492        handlers: Vec::new(),
493        next_handler: 0,
494        lua: None,
495        status_asked: false,
496        focusing: Vec::new(),
497        queued: VecDeque::new(),
498        retry: None,
499        retry_wait: RETRY,
500        reconnected: false,
501        recheck: None,
502      });
503      match &self.shared.config.hyprland {
504        None => tracing::info!(
505          "HYPRLAND_INSTANCE_SIGNATURE or XDG_RUNTIME_DIR is unset, so there is no Hyprland to show"
506        ),
507        Some(dir) => {
508          self.connect(dir);
509        }
510      }
511    }
512    let state = self.state.borrow();
513    let state = state.as_ref().expect("invariant: started above");
514    (state.workspaces, state.monitors, state.toplevels)
515  }
516
517  /// Opens the event socket, then reads every list, so no change between
518  /// the two goes unseen. A failure is logged and never retried, so a
519  /// stale signature never wakes the shell. `false` if it failed.
520  fn connect(self: &Rc<Self>, dir: &Path) -> bool {
521    let Some(event_loop) = self.shared.event_loop() else {
522      return false;
523    };
524    let path = dir.join(".socket2.sock");
525    let opened = open(&path).and_then(|stream| {
526      let fd = stream.as_fd().try_clone_to_owned()?;
527      Ok((stream, fd))
528    });
529    let (stream, fd) = match opened {
530      Ok(opened) => opened,
531      Err(error) => {
532        let path = path.display();
533        tracing::warn!(%path, %error, "can't connect to Hyprland, so its lists stay empty");
534        return false;
535      }
536    };
537    let service = Rc::clone(self);
538    let read = Box::new(move || service.on_events());
539    let Some(reader) = event_loop.insert_fd(fd, Interest::READ, read) else {
540      return false;
541    };
542    let mut state = self.state.borrow_mut();
543    let state = state
544      .as_mut()
545      .expect("invariant: started before connecting");
546    state.events = Some(Events {
547      stream,
548      reader,
549      lines: Lines::default(),
550    });
551    let burst = state.burst();
552    for query in Query::ALL {
553      self.read(state, query, burst);
554    }
555    true
556  }
557
558  /// Reads `query`'s list, or once more after the read under way.
559  fn read(self: &Rc<Self>, state: &mut State, query: Query, burst: u64) {
560    let reading = &mut state.reading[query as usize];
561    if *reading != Reading::Idle {
562      *reading = Reading::Stale;
563      return;
564    }
565    *reading = Reading::Busy;
566    state.burst_of[query as usize] = Some(burst);
567    match state.bursts.iter_mut().find(|open| open.id == burst) {
568      Some(open) => {
569        open.started += 1;
570        open.out += 1;
571      }
572      None => state.bursts.push(Burst {
573        id: burst,
574        started: 1,
575        out: 1,
576      }),
577    }
578    self.request(state, query.command(), Asked::List(query));
579  }
580
581  fn dispatch(self: &Rc<Self>, command: &str) {
582    let request = format!("dispatch {command}");
583    if request.len() > MAX_REQUEST {
584      return tracing::warn!("a dispatch over 8 KiB is too long to send");
585    }
586    let mut state = self.state.borrow_mut();
587    let state = state.as_mut().expect("invariant: started by cx.hyprland()");
588    let sent = state.requests.iter().map(|request| request.asked);
589    let waiting = sent.chain(state.queued.iter().map(|(asked, _)| *asked));
590    if waiting.filter(|asked| *asked == Asked::Dispatch).count() >= MAX_DISPATCHES {
591      return tracing::warn!(
592        command,
593        "64 dispatches wait for Hyprland, so this one isn't sent"
594      );
595    }
596    if self.shared.config.hyprland.is_none() {
597      return tracing::warn!(command, "no Hyprland to dispatch to");
598    }
599    self.request(state, &request, Asked::Dispatch);
600  }
601
602  fn focus_workspace(self: &Rc<Self>, target: &str) {
603    if self.shared.config.hyprland.is_none() {
604      return tracing::warn!(target, "no Hyprland to dispatch to");
605    }
606    let mut guard = self.state.borrow_mut();
607    let state = guard.as_mut().expect("invariant: started by cx.hyprland()");
608    if let Some(lua) = state.lua {
609      drop(guard);
610      return self.switch(lua, target);
611    }
612    if state.focusing.len() >= MAX_DISPATCHES {
613      return tracing::warn!(
614        target,
615        "64 switches wait for Hyprland's status, so this one isn't sent"
616      );
617    }
618    state.focusing.push(target.to_owned());
619    if !state.status_asked {
620      state.status_asked = true;
621      self.request(state, "j/status", Asked::Status);
622    }
623  }
624
625  /// Dispatches the switch to `target` in the syntax Hyprland reads.
626  fn switch(self: &Rc<Self>, lua: bool, target: &str) {
627    if lua {
628      return self.dispatch(&format!(
629        "hl.dsp.focus({{ workspace = {} }})",
630        lua_string(target)
631      ));
632    }
633    // The old syntax sends it as it is.
634    if target.chars().any(|c| c.is_whitespace() || c.is_control()) {
635      return tracing::warn!(
636        target,
637        "a workspace with whitespace or a control character in its name goes unquoted to \
638         Hyprland's old syntax, so the shell can't switch to it"
639      );
640    }
641    self.dispatch(&format!("workspace {target}"));
642  }
643
644  /// Sends `command` on a connection of its own, after what waits. At
645  /// most [`MAX_IN_FLIGHT`] are out, and a connect never waits: while
646  /// Hyprland's backlog is full, the rest wait for a request to end or
647  /// another to be made.
648  fn request(self: &Rc<Self>, state: &mut State, command: &str, asked: Asked) {
649    state.queued.push_back((asked, command.to_owned()));
650    self.send_queued(state);
651  }
652
653  /// Sends what waits, while fewer than [`MAX_IN_FLIGHT`] requests are
654  /// out and Hyprland's backlog has room.
655  fn send_queued(self: &Rc<Self>, state: &mut State) {
656    while state.requests.len() < MAX_IN_FLIGHT {
657      let Some((asked, command)) = state.queued.pop_front() else {
658        return;
659      };
660      match self.send(state, &command, asked) {
661        Sent::Out => state.retry_wait = RETRY,
662        Sent::Full => {
663          state.queued.push_front((asked, command));
664          return self.retry_later(state);
665        }
666        Sent::Failed => match asked {
667          Asked::List(query) => {
668            state.reading[query as usize] = Reading::Idle;
669            state.answered(query);
670          }
671          Asked::Status => {
672            // The switches waiting for it go, as a dispatch would.
673            state.status_asked = false;
674            state.focusing.clear();
675          }
676          Asked::Dispatch => {}
677        },
678      }
679    }
680  }
681
682  /// Tries the queue again after [`RETRY`], on a one-shot timer, when no
683  /// request of the shell's is out to end and try it sooner.
684  fn retry_later(self: &Rc<Self>, state: &mut State) {
685    if !state.requests.is_empty() || state.retry.is_some() {
686      return;
687    }
688    let Some(event_loop) = self.shared.event_loop() else {
689      return;
690    };
691    let service = Rc::clone(self);
692    let retry = Box::new(move || {
693      // Gone with this call, so nothing removes it again.
694      if let Some(state) = service.state.borrow_mut().as_mut() {
695        state.retry = None;
696      }
697      if !service.alive() {
698        service.close();
699      } else if let Some(state) = service.state.borrow_mut().as_mut() {
700        service.send_queued(state);
701      }
702      TimeoutAction::Drop
703    });
704    state.retry = event_loop.insert_timer(Instant::now() + state.retry_wait, retry);
705    state.retry_wait = (state.retry_wait * 2).min(MAX_RETRY);
706  }
707
708  /// Connects and sends `command`. `Failed`, logged once, if Hyprland
709  /// can't be reached.
710  fn send(self: &Rc<Self>, state: &mut State, command: &str, asked: Asked) -> Sent {
711    let (Some(dir), Some(event_loop)) = (&self.shared.config.hyprland, self.shared.event_loop())
712    else {
713      return Sent::Failed;
714    };
715    let path = dir.join(".socket.sock");
716    let command = command.as_bytes();
717    let opened = open(&path).and_then(|mut stream| {
718      // One write: Hyprland takes what has arrived as the whole request.
719      if stream.write(command)? < command.len() {
720        return Err(std::io::Error::other("the request didn't fit the socket"));
721      }
722      // Hyprland 0.56 and older read until a short read or the end.
723      stream.shutdown(Shutdown::Write)?;
724      let fd = stream.as_fd().try_clone_to_owned()?;
725      Ok((stream, fd))
726    });
727    let (stream, fd) = match opened {
728      Ok(opened) => opened,
729      Err(error) if error.kind() == ErrorKind::WouldBlock => return Sent::Full,
730      Err(error) => {
731        if !std::mem::replace(&mut state.request_failure_logged, true) {
732          let path = path.display();
733          tracing::warn!(%path, %error, "can't send Hyprland a request");
734        }
735        return Sent::Failed;
736      }
737    };
738    state.request_failure_logged = false;
739    let id = state.next_request;
740    state.next_request += 1;
741    let service = Rc::clone(self);
742    let read = Box::new(move || service.on_reply(id));
743    let Some(reader) = event_loop.insert_fd(fd, Interest::READ, read) else {
744      return Sent::Failed;
745    };
746    state.requests.push(Request {
747      id,
748      asked,
749      stream,
750      reader,
751      reply: Vec::new(),
752    });
753    Sent::Out
754  }
755
756  /// Whether the lists are still there: their owner, the root, isn't
757  /// disposed.
758  fn alive(&self) -> bool {
759    let state = self.state.borrow();
760    let alive = state
761      .as_ref()
762      .and_then(|state| state.workspaces.try_with(|_| ()));
763    alive.is_some()
764  }
765
766  /// Reads what came on the event socket, and reads again what the
767  /// events changed.
768  fn on_events(self: &Rc<Self>) {
769    if !self.alive() {
770      return self.close();
771    }
772    let mut chunk = [0; 64 * 1024];
773    let mut guard = self.state.borrow_mut();
774    let state = guard
775      .as_mut()
776      .expect("invariant: started before connecting");
777    let Some(events) = state.events.as_mut() else {
778      return;
779    };
780    let lines = match events.stream.read(&mut chunk) {
781      Ok(0) => return self.closed(guard, "Hyprland closed its event socket"),
782      Ok(read) => events
783        .lines
784        .push(&chunk[..read], &"Hyprland's event socket"),
785      Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {
786        return;
787      }
788      Err(error) => return self.closed(guard, &error.to_string()),
789    };
790    if !lines.is_empty() {
791      state.reconnected = false;
792    }
793    // A burst of events reads each list once.
794    let mut stale = [false; 4];
795    let mut events = Vec::new();
796    let mut urgency = false;
797    for line in lines {
798      let Some((name, data)) = line.split_once(">>") else {
799        let line = cut(line);
800        tracing::warn!(line, "a line from Hyprland's event socket without `>>`");
801        continue;
802      };
803      for &query in Query::after(name) {
804        stale[query as usize] = true;
805      }
806      // Events name a window without JSON's `0x`.
807      let address = || format!("0x{data}");
808      urgency |= match name {
809        "urgent" => state.urgent.len() < MAX_LIST && state.urgent.insert(address()),
810        // Focus ends a window's urgency, as in Hyprland.
811        "activewindowv2" | "closewindow" => state.urgent.remove(&address()),
812        _ => false,
813      };
814      events.push(HyprlandEvent {
815        name: cut(name.to_owned()),
816        data: cut(data.to_owned()),
817      });
818    }
819    if urgency {
820      state.show();
821    }
822    let burst = state.burst();
823    for query in Query::ALL
824      .into_iter()
825      .filter(|&query| stale[query as usize])
826    {
827      self.read(state, query, burst);
828    }
829    drop(guard);
830    for event in events {
831      self.deliver(&event);
832    }
833  }
834
835  /// Calls each raw-event handler with `event`, with nothing borrowed.
836  fn deliver(&self, event: &HyprlandEvent) {
837    let handlers = match self.state.borrow().as_ref() {
838      Some(state) => state.handlers.clone(),
839      None => return,
840    };
841    for Handler { id, at, handler } in handlers {
842      let registered = self
843        .state
844        .borrow()
845        .as_ref()
846        .is_some_and(|state| state.handlers.iter().any(|handler| handler.id == id));
847      if !registered {
848        // An earlier handler's context went.
849        continue;
850      }
851      if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(|| handler(event))) {
852        let message = panic_message(payload.as_ref());
853        let name = &event.name;
854        tracing::error!("Hyprland on_event (called at {at}) panicked on {name}: {message}");
855        drop(self.remove_handler(id));
856      }
857    }
858  }
859
860  fn add_handler(
861    &self,
862    handler: Rc<dyn Fn(&HyprlandEvent)>,
863    at: &'static Location<'static>,
864  ) -> u64 {
865    let mut state = self.state.borrow_mut();
866    let state = state.as_mut().expect("invariant: started by cx.hyprland()");
867    let id = state.next_handler;
868    state.next_handler += 1;
869    state.handlers.push(Handler { id, at, handler });
870    id
871  }
872
873  /// Takes out the handler `id`, for the caller to drop once nothing is
874  /// borrowed.
875  fn remove_handler(&self, id: u64) -> Option<Handler> {
876    let mut state = self.state.borrow_mut();
877    let handlers = &mut state.as_mut()?.handlers;
878    let at = handlers.iter().position(|handler| handler.id == id)?;
879    Some(handlers.remove(at))
880  }
881
882  /// Reads what came of a reply, and acts on it once Hyprland closed the
883  /// connection.
884  fn on_reply(self: &Rc<Self>, id: u64) {
885    if !self.alive() {
886      return self.close();
887    }
888    let mut chunk = [0; 64 * 1024];
889    let mut guard = self.state.borrow_mut();
890    let state = guard.as_mut().expect("invariant: started before reading");
891    let Some(at) = state.requests.iter().position(|request| request.id == id) else {
892      return;
893    };
894    let request = &mut state.requests[at];
895    let failed = match request.stream.read(&mut chunk) {
896      Ok(0) => None,
897      Ok(read) if request.reply.len() + read > MAX_REPLY => Some(String::from("over 8 MiB")),
898      Ok(read) => return request.reply.extend_from_slice(&chunk[..read]),
899      Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {
900        return;
901      }
902      Err(error) => Some(error.to_string()),
903    };
904    let request = state.requests.remove(at);
905    if let Some(event_loop) = self.shared.event_loop() {
906      event_loop.remove(request.reader);
907    }
908    self.send_queued(state);
909    let query = match request.asked {
910      Asked::List(query) => query,
911      Asked::Dispatch => {
912        let reply = String::from_utf8_lossy(&request.reply);
913        if failed.is_some() || reply.trim() != "ok" {
914          let reply = cut(reply.into_owned());
915          tracing::warn!(reply, failed, "Hyprland refused a dispatch");
916        }
917        return;
918      }
919      Asked::Status => {
920        state.status_asked = false;
921        let lua = failed
922          .is_none()
923          .then(|| reads_lua(&request.reply))
924          .flatten();
925        if lua.is_none() {
926          let reply = cut(String::from_utf8_lossy(&request.reply).into_owned());
927          tracing::warn!(
928            reply,
929            failed,
930            "Hyprland's status names no config; dispatching in the old syntax"
931          );
932        }
933        let lua = lua.unwrap_or(false);
934        state.lua = Some(lua);
935        let focusing = std::mem::take(&mut state.focusing);
936        drop(guard);
937        for target in focusing {
938          self.switch(lua, &target);
939        }
940        return;
941      }
942    };
943    match failed {
944      Some(why) => {
945        tracing::warn!(
946          command = query.command(),
947          why,
948          "Hyprland's reply was dropped"
949        );
950      }
951      None => {
952        state.raw.apply(query, &request.reply);
953        state.recheck(query, request.id);
954      }
955    }
956    state.answered(query);
957    if state.reading[query as usize] == Reading::Stale {
958      // For a later event, so no show waits for it.
959      state.reading[query as usize] = Reading::Busy;
960      self.request(state, query.command(), Asked::List(query));
961    } else {
962      state.reading[query as usize] = Reading::Idle;
963    }
964    state.show();
965  }
966
967  /// The event socket closed for `why`. Hyprland closes a client that
968  /// falls 64 events behind and runs on, so while its socket is there,
969  /// this connects once again and reads every list, keeping them
970  /// meanwhile. A connection that closes again before an event came is
971  /// lost.
972  fn closed(self: &Rc<Self>, mut guard: RefMut<'_, Option<State>>, why: &str) {
973    let state = guard
974      .as_mut()
975      .expect("invariant: started before connecting");
976    let dir = self.shared.config.hyprland.as_deref();
977    let Some(dir) = dir.filter(|dir| !state.reconnected && dir.join(".socket2.sock").exists())
978    else {
979      return self.lost(state, why);
980    };
981    tracing::warn!(why, "Hyprland closed its event socket; connecting again");
982    state.reconnected = true;
983    state.recheck = Some(Recheck {
984      urgent: state.urgent.clone(),
985      from: state.next_request,
986      windows: false,
987      active: false,
988    });
989    if let (Some(events), Some(event_loop)) = (state.events.take(), self.shared.event_loop()) {
990      event_loop.remove(events.reader);
991    }
992    drop(guard);
993    if !self.connect(dir)
994      && let Some(state) = self.state.borrow_mut().as_mut()
995    {
996      self.lost(state, "Hyprland's event socket can't be reached again");
997    }
998  }
999
1000  /// Drops every connection and empties the lists. Hyprland doesn't
1001  /// come back under the same signature, so nothing reconnects.
1002  fn lost(&self, state: &mut State, why: &str) {
1003    tracing::warn!(why, "lost Hyprland; its lists are empty");
1004    self.drop_connections(state);
1005    state.raw = Raw::default();
1006    state.urgent.clear();
1007    state.show();
1008  }
1009
1010  /// Closes every connection for good, once the lists are gone.
1011  fn close(&self) {
1012    if let Some(state) = self.state.borrow_mut().as_mut() {
1013      self.drop_connections(state);
1014    }
1015  }
1016
1017  fn drop_connections(&self, state: &mut State) {
1018    let events = state.events.take();
1019    let requests = std::mem::take(&mut state.requests);
1020    state.reading = [Reading::Idle; 4];
1021    state.burst_of = [None; 4];
1022    state.bursts.clear();
1023    state.queued.clear();
1024    let retry = state.retry.take();
1025    state.retry_wait = RETRY;
1026    state.status_asked = false;
1027    state.focusing.clear();
1028    let Some(event_loop) = self.shared.event_loop() else {
1029      return;
1030    };
1031    let readers = events.map(|events| events.reader).into_iter().chain(retry);
1032    for reader in readers.chain(requests.into_iter().map(|request| request.reader)) {
1033      event_loop.remove(reader);
1034    }
1035  }
1036}
1037
1038impl State {
1039  /// After a reconnect, ends the urgency of a window from before it that
1040  /// `query`'s answer, to the request `id`, says was focused or closed.
1041  fn recheck(&mut self, query: Query, id: u64) {
1042    let State {
1043      recheck,
1044      urgent,
1045      raw,
1046      ..
1047    } = self;
1048    let Some(check) = recheck.as_mut().filter(|check| id >= check.from) else {
1049      return;
1050    };
1051    match query {
1052      Query::Clients => {
1053        let listed: HashSet<&str> = raw
1054          .windows
1055          .iter()
1056          .map(|window| window.address.as_str())
1057          .collect();
1058        for address in check
1059          .urgent
1060          .iter()
1061          .filter(|address| !listed.contains(address.as_str()))
1062        {
1063          urgent.remove(address);
1064        }
1065        check.windows = true;
1066      }
1067      Query::ActiveWindow => {
1068        if let Some(active) = raw
1069          .active
1070          .as_ref()
1071          .filter(|active| check.urgent.contains(*active))
1072        {
1073          urgent.remove(active);
1074        }
1075        check.active = true;
1076      }
1077      Query::Workspaces | Query::Monitors => return,
1078    }
1079    if check.windows && check.active {
1080      *recheck = None;
1081    }
1082  }
1083
1084  /// A new burst of reads.
1085  fn burst(&mut self) -> u64 {
1086    self.next_burst += 1;
1087    self.next_burst
1088  }
1089
1090  /// `query`'s read for a burst, if it was one, is answered.
1091  fn answered(&mut self, query: Query) {
1092    let Some(id) = self.burst_of[query as usize].take() else {
1093      return;
1094    };
1095    if let Some(at) = self.bursts.iter().position(|open| open.id == id) {
1096      self.bursts[at].out -= 1;
1097      if self.bursts[at].out == 0 {
1098        self.bursts.remove(at);
1099      }
1100    }
1101  }
1102
1103  /// Builds the lists from what Hyprland last said, and sets each that
1104  /// changed. Nothing shows while a burst has some reads answered and
1105  /// others not, so a frame never mixes one list's answer to an event
1106  /// with another's from before it.
1107  fn show(&self) {
1108    if self.bursts.iter().any(|open| open.out < open.started) {
1109      return;
1110    }
1111    let raw = &self.raw;
1112    let focused = raw.monitors.iter().find(|monitor| monitor.focused);
1113    let urgent: Vec<_> = raw
1114      .windows
1115      .iter()
1116      .filter(|window| self.urgent.contains(&window.address))
1117      .map(|window| &window.workspace)
1118      .collect();
1119    let mut workspaces: Vec<_> = raw
1120      .workspaces
1121      .iter()
1122      .map(|workspace| HyprlandWorkspace {
1123        id: workspace.at.id,
1124        name: workspace.at.name.clone(),
1125        monitor: workspace.monitor.clone(),
1126        windows: workspace.windows,
1127        focused: focused.is_some_and(|monitor| monitor.shows(&workspace.at)),
1128        active: raw
1129          .monitors
1130          .iter()
1131          .any(|monitor| monitor.name == workspace.monitor && monitor.shows(&workspace.at)),
1132        urgent: urgent.iter().any(|at| at.is(&workspace.at)),
1133      })
1134      .collect();
1135    // Named ones first, as Hyprland before 0.57 numbers them below zero.
1136    workspaces.sort_by_key(|workspace| workspace.id.unwrap_or(i64::MIN));
1137    let monitors = raw.monitors.iter().map(|monitor| HyprlandMonitor {
1138      id: monitor.id,
1139      name: monitor.name.clone(),
1140      description: monitor.description.clone(),
1141      focused: monitor.focused,
1142      active_workspace: monitor.active.name.clone(),
1143      x: monitor.x,
1144      y: monitor.y,
1145      width: monitor.width,
1146      height: monitor.height,
1147      scale: monitor.scale,
1148    });
1149    let toplevels = raw.windows.iter().map(|window| HyprlandToplevel {
1150      address: window.address.clone(),
1151      class: window.class.clone(),
1152      title: window.title.clone(),
1153      workspace: window.workspace.name.clone(),
1154      monitor: raw
1155        .monitors
1156        .iter()
1157        .find(|monitor| monitor.id == window.monitor)
1158        .map_or_else(String::new, |monitor| monitor.name.clone()),
1159      floating: window.floating,
1160      fullscreen: window.fullscreen.is_fullscreen(),
1161      focused: raw.active.as_ref() == Some(&window.address),
1162      urgent: self.urgent.contains(&window.address),
1163    });
1164    set_changed(self.workspaces, workspaces);
1165    set_changed(self.monitors, monitors.collect());
1166    set_changed(self.toplevels, toplevels.collect());
1167  }
1168}
1169
1170impl Raw {
1171  /// Keeps what `reply` says for `query`. A reply that doesn't parse is
1172  /// logged and the last one kept; an entry that doesn't is left out.
1173  fn apply(&mut self, query: Query, reply: &[u8]) {
1174    match query {
1175      Query::Workspaces => {
1176        if let Some(list) = list("workspace", reply) {
1177          self.workspaces = list;
1178        }
1179      }
1180      Query::Monitors => {
1181        if let Some(list) = list("monitor", reply) {
1182          self.monitors = list;
1183        }
1184      }
1185      Query::Clients => {
1186        if let Some(list) = list("window", reply) {
1187          self.windows = list;
1188        }
1189      }
1190      Query::ActiveWindow => match serde_json::from_slice::<ActiveWindow>(reply) {
1191        Ok(active) => self.active = active.address,
1192        Err(error) => tracing::warn!(%error, "a bad focused window from Hyprland"),
1193      },
1194    }
1195  }
1196}
1197
1198/// The entries of a JSON list of `what`s, at most [`MAX_LIST`], leaving
1199/// out those that don't parse. `None`, logged, for a reply that isn't a
1200/// list.
1201fn list<T: DeserializeOwned>(what: &str, reply: &[u8]) -> Option<Vec<T>> {
1202  let entries: Vec<serde_json::Value> = serde_json::from_slice(reply)
1203    .inspect_err(|error| tracing::warn!(%error, "a bad {what} list from Hyprland"))
1204    .ok()?;
1205  if entries.len() > MAX_LIST {
1206    let listed = entries.len();
1207    tracing::warn!(
1208      listed,
1209      "Hyprland listed more {what}s than the {MAX_LIST} kept"
1210    );
1211  }
1212  let mut bad = 0;
1213  let list = entries
1214    .into_iter()
1215    .take(MAX_LIST)
1216    .filter_map(|entry| serde_json::from_value(entry).inspect_err(|_| bad += 1).ok())
1217    .collect();
1218  if bad > 0 {
1219    tracing::warn!(
1220      bad,
1221      "Hyprland described some {what}s badly; they are left out"
1222    );
1223  }
1224  Some(list)
1225}
1226
1227/// A workspace as a monitor or a window names it: by number while it has
1228/// one, and from Hyprland 0.57 on by address otherwise.
1229#[derive(Deserialize)]
1230struct WorkspaceRef {
1231  id: Option<i64>,
1232  #[serde(default, deserialize_with = "some_text")]
1233  address: Option<String>,
1234  #[serde(deserialize_with = "text")]
1235  name: String,
1236}
1237
1238impl WorkspaceRef {
1239  fn is(&self, other: &WorkspaceRef) -> bool {
1240    match (self.id, other.id) {
1241      (Some(id), Some(other)) => id == other,
1242      _ => self.address.is_some() && self.address == other.address,
1243    }
1244  }
1245}
1246
1247#[derive(Deserialize)]
1248struct RawWorkspace {
1249  #[serde(flatten)]
1250  at: WorkspaceRef,
1251  #[serde(deserialize_with = "text")]
1252  monitor: String,
1253  windows: u32,
1254}
1255
1256#[derive(Deserialize)]
1257struct RawMonitor {
1258  id: i64,
1259  #[serde(deserialize_with = "text")]
1260  name: String,
1261  #[serde(deserialize_with = "text")]
1262  description: String,
1263  focused: bool,
1264  x: i32,
1265  y: i32,
1266  width: i32,
1267  height: i32,
1268  scale: f64,
1269  #[serde(rename = "activeWorkspace")]
1270  active: WorkspaceRef,
1271  /// The special workspace shown over `active`, which names none as
1272  /// `{"id":0,"name":""}`, or from 0.57 on with an empty address.
1273  #[serde(rename = "specialWorkspace", default)]
1274  special: Option<WorkspaceRef>,
1275}
1276
1277impl RawMonitor {
1278  /// Whether it shows `workspace`, as its active or its special one.
1279  fn shows(&self, workspace: &WorkspaceRef) -> bool {
1280    self.active.is(workspace)
1281      || self
1282        .special
1283        .as_ref()
1284        .is_some_and(|special| special.is(workspace))
1285  }
1286}
1287
1288#[derive(Deserialize)]
1289struct RawWindow {
1290  #[serde(deserialize_with = "text")]
1291  address: String,
1292  #[serde(deserialize_with = "text")]
1293  class: String,
1294  #[serde(deserialize_with = "text")]
1295  title: String,
1296  workspace: WorkspaceRef,
1297  monitor: i64,
1298  floating: bool,
1299  fullscreen: Fullscreen,
1300}
1301
1302/// A window's fullscreen state: a flag in older Hyprland, then its mode,
1303/// where 1 is maximized and 2 fullscreen.
1304#[derive(Deserialize)]
1305#[serde(untagged)]
1306enum Fullscreen {
1307  Flag(bool),
1308  Mode(i64),
1309}
1310
1311impl Fullscreen {
1312  fn is_fullscreen(&self) -> bool {
1313    match *self {
1314      Fullscreen::Flag(flag) => flag,
1315      Fullscreen::Mode(mode) => mode & 2 != 0,
1316    }
1317  }
1318}
1319
1320/// `j/activewindow`'s reply: the focused window, or `{}` for none.
1321#[derive(Deserialize)]
1322struct ActiveWindow {
1323  #[serde(default, deserialize_with = "some_text")]
1324  address: Option<String>,
1325}
1326
1327/// A string from Hyprland, cut to [`MAX_TEXT`].
1328fn text<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
1329  String::deserialize(deserializer).map(cut)
1330}
1331
1332fn some_text<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<String>, D::Error> {
1333  text(deserializer).map(Some)
1334}
1335
1336/// A non-blocking connection to the Unix socket at `path`, made without
1337/// waiting: a listen backlog that is full is `WouldBlock`.
1338fn open(path: &Path) -> std::io::Result<UnixStream> {
1339  use rustix::net::{AddressFamily, SocketAddrUnix, SocketFlags, SocketType};
1340  let flags = SocketFlags::NONBLOCK | SocketFlags::CLOEXEC;
1341  let fd = rustix::net::socket_with(AddressFamily::UNIX, SocketType::STREAM, flags, None)?;
1342  match rustix::net::connect(&fd, &SocketAddrUnix::new(path)?) {
1343    Ok(()) => Ok(UnixStream::from(fd)),
1344    // A Unix socket never connects in the background; were one to, it
1345    // would be as full.
1346    Err(rustix::io::Errno::INPROGRESS) => Err(ErrorKind::WouldBlock.into()),
1347    Err(errno) => Err(errno.into()),
1348  }
1349}
1350
1351/// `text` cut to [`MAX_TEXT`] bytes at a character.
1352fn cut(mut text: String) -> String {
1353  if text.len() > MAX_TEXT {
1354    text.truncate(text.floor_char_boundary(MAX_TEXT));
1355  }
1356  text
1357}
1358
1359/// `text` as a Lua string literal: quoted, with backslashes, quotes and
1360/// control characters escaped, so nothing in it runs.
1361fn lua_string(text: &str) -> String {
1362  let mut quoted = String::from("\"");
1363  for character in text.chars() {
1364    match character {
1365      '\\' | '"' => {
1366        quoted.push('\\');
1367        quoted.push(character);
1368      }
1369      // Three digits, so a digit after it isn't read as part of it.
1370      control if control.is_ascii_control() => {
1371        quoted.push_str(&format!("\\{:03}", u32::from(control)));
1372      }
1373      other => quoted.push(other),
1374    }
1375  }
1376  quoted.push('"');
1377  quoted
1378}
1379
1380/// What `j/status` says, from Hyprland 0.55 on.
1381#[derive(Deserialize)]
1382struct Status {
1383  /// `lua` or `hyprlang`.
1384  #[serde(rename = "configProvider")]
1385  config_provider: String,
1386}
1387
1388/// Whether the Hyprland that sent `reply` to `j/status` reads dispatches
1389/// as Lua, as it does when its config is. Hyprland before 0.55 knows no
1390/// status and reads the old syntax. `None` when the reply says neither.
1391fn reads_lua(reply: &[u8]) -> Option<bool> {
1392  if reply.trim_ascii() == b"unknown request" {
1393    return Some(false);
1394  }
1395  let Status { config_provider } = serde_json::from_slice(reply).ok()?;
1396  match config_provider.as_str() {
1397    "lua" => Some(true),
1398    "hyprlang" => Some(false),
1399    _ => None,
1400  }
1401}