1#[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
33pub(crate) const MAX_REPLY: usize = 8 * 1024 * 1024;
35
36pub(crate) const MAX_REQUEST: usize = 8 * 1024;
38
39const MAX_DISPATCHES: usize = 64;
42
43const MAX_IN_FLIGHT: usize = 8;
46
47const RETRY: Duration = Duration::from_millis(100);
53const MAX_RETRY: Duration = Duration::from_secs(2);
54
55pub(crate) const MAX_TEXT: usize = 4 * 1024;
57
58pub(crate) const MAX_LIST: usize = 4096;
60
61#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct HyprlandWorkspace {
64 pub id: Option<i64>,
67 pub name: String,
70 pub monitor: String,
72 pub windows: u32,
74 pub focused: bool,
76 pub active: bool,
78 pub urgent: bool,
80}
81
82#[derive(Clone, Debug, PartialEq)]
84pub struct HyprlandMonitor {
85 pub id: i64,
87 pub name: String,
89 pub description: String,
91 pub focused: bool,
93 pub active_workspace: String,
95 pub x: i32,
97 pub y: i32,
99 pub width: i32,
101 pub height: i32,
103 pub scale: f64,
105}
106
107#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct HyprlandToplevel {
110 pub address: String,
114 pub class: String,
116 pub title: String,
118 pub workspace: String,
120 pub monitor: String,
123 pub floating: bool,
125 pub fullscreen: bool,
128 pub focused: bool,
130 pub urgent: bool,
133}
134
135#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct HyprlandEvent {
139 pub name: String,
141 pub data: String,
144}
145
146impl HyprlandEvent {
147 pub fn parse(&self, fields: usize) -> Vec<&str> {
151 self.data.splitn(fields, ',').collect()
152 }
153}
154
155#[derive(Clone)]
158pub struct Hyprland {
159 service: Option<Rc<Service>>,
161 owner: Owner,
164 workspaces: ReadSignal<Vec<HyprlandWorkspace>>,
165 monitors: ReadSignal<Vec<HyprlandMonitor>>,
166 toplevels: ReadSignal<Vec<HyprlandToplevel>>,
167}
168
169impl Hyprland {
170 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 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 #[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 pub fn workspaces(&self) -> ReadSignal<Vec<HyprlandWorkspace>> {
230 self.workspaces
231 }
232
233 pub fn monitors(&self) -> ReadSignal<Vec<HyprlandMonitor>> {
235 self.monitors
236 }
237
238 pub fn toplevels(&self) -> ReadSignal<Vec<HyprlandToplevel>> {
240 self.toplevels
241 }
242}
243
244pub(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#[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 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 "moveworkspace" | "renameworkspace" | "changeworkspaceid" | "monitoradded"
306 | "monitorremoved" | "configreloaded" => &[Workspaces, Monitors, Clients],
307 "openwindow" | "closewindow" | "movewindow" => &[Workspaces, Clients],
308 "windowtitle" | "changefloatingmode" | "fullscreen" => &[Clients],
309 "activewindow" => &[Clients, ActiveWindow],
311 _ => &[],
312 }
313 }
314}
315
316#[derive(Clone, Copy, PartialEq, Eq)]
318enum Reading {
319 Idle,
320 Busy,
321 Stale,
324}
325
326type Lists = (
327 Signal<Vec<HyprlandWorkspace>>,
328 Signal<Vec<HyprlandMonitor>>,
329 Signal<Vec<HyprlandToplevel>>,
330);
331
332pub(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 events: Option<Events>,
344 reading: [Reading; 4],
346 burst_of: [Option<u64>; 4],
350 bursts: Vec<Burst>,
352 next_burst: u64,
353 requests: Vec<Request>,
355 next_request: u64,
356 request_failure_logged: bool,
359 raw: Raw,
360 urgent: HashSet<String>,
363 handlers: Vec<Handler>,
365 next_handler: u64,
366 lua: Option<bool>,
369 status_asked: bool,
371 focusing: Vec<String>,
373 queued: VecDeque<(Asked, String)>,
375 retry: Option<RegistrationToken>,
378 retry_wait: Duration,
380 recheck: Option<Recheck>,
383 reconnected: bool,
385}
386
387struct Burst {
389 id: u64,
390 started: usize,
391 out: usize,
393}
394
395struct Recheck {
398 urgent: HashSet<String>,
399 from: u64,
402 windows: bool,
403 active: bool,
404}
405
406enum Sent {
408 Out,
409 Full,
411 Failed,
412}
413
414#[derive(Clone, Copy, Debug, PartialEq, Eq)]
416enum Asked {
417 List(Query),
418 Status,
419 Dispatch,
420}
421
422#[derive(Clone)]
424struct Handler {
425 id: u64,
426 at: &'static Location<'static>,
428 handler: Rc<dyn Fn(&HyprlandEvent)>,
429}
430
431struct Unregister(Rc<Service>, u64);
433
434impl Drop for Unregister {
435 fn drop(&mut self) {
436 let handler = self.0.remove_handler(self.1);
437 drop(handler);
439 }
440}
441
442#[derive(Default)]
444struct Raw {
445 workspaces: Vec<RawWorkspace>,
446 monitors: Vec<RawMonitor>,
447 windows: Vec<RawWindow>,
448 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 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 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 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 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 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 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 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 state.status_asked = false;
674 state.focusing.clear();
675 }
676 Asked::Dispatch => {}
677 },
678 }
679 }
680 }
681
682 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 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 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 if stream.write(command)? < command.len() {
720 return Err(std::io::Error::other("the request didn't fit the socket"));
721 }
722 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 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 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 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 let address = || format!("0x{data}");
808 urgency |= match name {
809 "urgent" => state.urgent.len() < MAX_LIST && state.urgent.insert(address()),
810 "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 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 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 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 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 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 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 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 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 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 fn burst(&mut self) -> u64 {
1086 self.next_burst += 1;
1087 self.next_burst
1088 }
1089
1090 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 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 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 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
1198fn 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#[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 #[serde(rename = "specialWorkspace", default)]
1274 special: Option<WorkspaceRef>,
1275}
1276
1277impl RawMonitor {
1278 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#[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#[derive(Deserialize)]
1322struct ActiveWindow {
1323 #[serde(default, deserialize_with = "some_text")]
1324 address: Option<String>,
1325}
1326
1327fn 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
1336fn 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 Err(rustix::io::Errno::INPROGRESS) => Err(ErrorKind::WouldBlock.into()),
1347 Err(errno) => Err(errno.into()),
1348 }
1349}
1350
1351fn 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
1359fn 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 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#[derive(Deserialize)]
1382struct Status {
1383 #[serde(rename = "configProvider")]
1385 config_provider: String,
1386}
1387
1388fn 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}