summaryrefslogtreecommitdiff
path: root/src/wm_info_provider/hyprland.rs
blob: d1ab42c485380cea052c4e4af9c3ab02d4b0ce87 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::io::{self, Write};
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
use std::path::PathBuf;

use serde::de::DeserializeOwned;
use wayrs_client::IoMode;

use super::*;
use crate::event_loop;
use crate::utils::read_to_vec;

pub struct HyprlandInfoProvider {
    ipc: Ipc,
    workspaces: Vec<IpcWorkspace>,
    active_id: u32,
}

impl HyprlandInfoProvider {
    pub fn new() -> Option<Self> {
        let his = std::env::var("HYPRLAND_INSTANCE_SIGNATURE").ok()?;
        let ipc = Ipc::new(&his)?;
        Some(Self {
            workspaces: ipc.query_sorted_workspaces().ok()?,
            active_id: ipc.query_json::<IpcWorkspace>("j/activeworkspace").ok()?.id,
            ipc,
        })
    }
}

impl WmInfoProvider for HyprlandInfoProvider {
    fn register(&self, event_loop: &mut EventLoop) {
        event_loop.register_with_fd(self.ipc.sock2.as_raw_fd(), |ctx| {
            match hyprland_cb(ctx.conn, ctx.state) {
                Ok(()) => Ok(event_loop::Action::Keep),
                Err(e) => {
                    ctx.state.set_error(ctx.conn, e);
                    ctx.conn.flush(IoMode::Blocking)?;
                    Ok(event_loop::Action::Unregister)
                }
            }
        });
    }

    fn get_tags(&self, output: &Output) -> Vec<Tag> {
        self.workspaces
            .iter()
            .filter(|ws| ws.monitor == output.name)
            .map(|ws| Tag {
                id: ws.id,
                name: ws.name.clone(),
                is_focused: ws.id == self.active_id,
                is_active: true,
                is_urgent: false,
            })
            .collect()
    }

    fn click_on_tag(
        &mut self,
        _: &mut Connection<State>,
        _: WlOutput,
        _: WlSeat,
        tag_id: u32,
        btn: PointerBtn,
    ) {
        if btn == PointerBtn::Left {
            let _ = self.ipc.exec(&format!("/dispatch workspace {tag_id}"));
        }
    }

    fn as_any(&mut self) -> &mut dyn Any {
        self
    }
}

fn hyprland_cb(conn: &mut Connection<State>, state: &mut State) -> io::Result<()> {
    let hyprland = state.shared_state.get_hyprland().unwrap();
    let mut updated = false;
    loop {
        match hyprland.ipc.next_event() {
            Ok(event) => {
                if let Some(active_ws) = event.strip_prefix("workspace>>") {
                    hyprland.active_id = active_ws
                        .parse()
                        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
                    updated = true;
                } else if event.contains("workspace>>") {
                    hyprland.workspaces = hyprland.ipc.query_sorted_workspaces()?;
                    updated = true;
                }
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
            Err(e) => return Err(e),
        }
    }
    if updated {
        state.tags_updated(conn, None);
    }
    Ok(())
}

struct Ipc {
    sock1_path: PathBuf,
    sock2: UnixStream,
    sock2_buf: Vec<u8>,
}

impl Ipc {
    fn new(his: &str) -> Option<Self> {
        let mut path = PathBuf::from("/tmp/hypr");
        if !path.exists() {
            let xdgrd = std::env::var("XDG_RUNTIME_DIR").ok()?;
            path.push(xdgrd);
            path.push("hypr");
        }
        path.push(his);
        let sock1_path = path.join(".socket.sock");
        let sock2_path = path.join(".socket2.sock");
        let sock2 = UnixStream::connect(sock2_path).ok()?;
        sock2.set_nonblocking(true).ok()?;
        Some(Self {
            sock1_path,
            sock2,
            sock2_buf: Vec::new(),
        })
    }

    fn exec(&self, cmd: &str) -> io::Result<()> {
        let mut sock = UnixStream::connect(&self.sock1_path)?;
        sock.write_all(cmd.as_bytes())?;
        sock.flush()?;
        Ok(())
    }

    fn query_json<T: DeserializeOwned>(&self, cmd: &str) -> io::Result<T> {
        let mut sock = UnixStream::connect(&self.sock1_path)?;
        sock.write_all(cmd.as_bytes())?;
        sock.flush()?;
        serde_json::from_reader(&mut sock).map_err(Into::into)
    }

    fn query_sorted_workspaces(&self) -> io::Result<Vec<IpcWorkspace>> {
        let mut workspaces = self.query_json::<Vec<IpcWorkspace>>("j/workspaces")?;
        workspaces.sort_unstable_by_key(|x| x.id);
        Ok(workspaces)
    }

    fn next_event(&mut self) -> io::Result<String> {
        loop {
            if let Some(i) = memchr::memchr(b'\n', &self.sock2_buf) {
                let event = String::from_utf8_lossy(&self.sock2_buf[..i]).into_owned();
                self.sock2_buf.drain(..=i);
                return Ok(event);
            }
            if read_to_vec(&self.sock2, &mut self.sock2_buf)? == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::BrokenPipe,
                    "hyprland socked disconnected",
                ));
            }
        }
    }
}

#[derive(Debug, serde::Deserialize)]
struct IpcWorkspace {
    id: u32,
    name: String,
    monitor: String,
}