atagen

monolith

public
Star0
Watch0
b5a60c9ce31a8dae390bd950e727784e94d8b53a
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/ipc/src/lib.rsRust327 lines9.7 KB
1
//! The control protocol. Newline-delimited JSON over a unix socket, one
2
//! message per line, each carrying the protocol version `v`.
3
//!
4
//! Commands also have a word form, `focus left` or `spawn beer`, shared by
5
//! the CLI and keybindings in the config.
6
7
use serde::{Deserialize, Serialize};
8
use std::fmt;
9
use std::path::PathBuf;
10
11
pub const VERSION: u32 = 1;
12
13
/// Where the compositor serving `display` listens.
14
pub fn socket_path_for(display: &str) -> Option<PathBuf> {
15
    let dir = std::env::var_os("XDG_RUNTIME_DIR")?;
16
    Some(PathBuf::from(dir).join(format!("monolith-{display}.sock")))
17
}
18
19
/// Where a client should connect. `$MONOLITH_SOCKET`, else the socket of
20
/// the compositor serving `$WAYLAND_DISPLAY`.
21
pub fn socket_path() -> Option<PathBuf> {
22
    if let Some(p) = std::env::var_os("MONOLITH_SOCKET") {
23
        return Some(p.into());
24
    }
25
    socket_path_for(&std::env::var("WAYLAND_DISPLAY").ok()?)
26
}
27
28
pub use monolith_layout::{Axis, Dir};
29
30
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
31
#[serde(rename_all = "kebab-case")]
32
pub enum ExpandScope {
33
    #[default]
34
    Window,
35
    Container,
36
}
37
38
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
39
#[serde(tag = "command", rename_all = "kebab-case", deny_unknown_fields)]
40
pub enum Command {
41
    Spawn {
42
        argv: Vec<String>,
43
    },
44
    Close,
45
    Quit,
46
    Reload,
47
    Focus {
48
        dir: Dir,
49
    },
50
    Move {
51
        dir: Dir,
52
    },
53
    MoveContainer {
54
        dir: Dir,
55
    },
56
    Resize {
57
        axis: Axis,
58
        delta: f64,
59
    },
60
    Expand {
61
        scope: ExpandScope,
62
    },
63
    /// Expands every container above the focused window towards it.
64
    Maximize,
65
    /// Makes the next window move do the opposite of the configured default,
66
    /// swap or merge. Again before moving cancels it.
67
    InvertMove,
68
    Flip,
69
    Float,
70
    Fullscreen,
71
    Sticky,
72
    View {
73
        tag: String,
74
    },
75
    ToggleView {
76
        tag: String,
77
    },
78
    ViewEverywhere {
79
        tag: String,
80
    },
81
    /// Sends the focused window to a tag.
82
    Tag {
83
        tag: String,
84
    },
85
    ReorderTag {
86
        tag: String,
87
        index: usize,
88
    },
89
    FocusOutput {
90
        dir: Dir,
91
    },
92
    SendToOutput {
93
        dir: Dir,
94
    },
95
    /// Adds the focused window to a scratchpad.
96
    Scratchpad {
97
        name: String,
98
    },
99
    Summon {
100
        name: String,
101
    },
102
    Dismiss {
103
        name: Option<String>,
104
    },
105
    /// Switches outputs on or off, all of them without a name.
106
    Power {
107
        on: bool,
108
        #[serde(default)]
109
        output: Option<String>,
110
    },
111
}
112
113
#[derive(Debug, Clone, PartialEq, Eq)]
114
pub struct ParseError(pub String);
115
116
impl fmt::Display for ParseError {
117
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118
        f.write_str(&self.0)
119
    }
120
}
121
122
impl std::error::Error for ParseError {}
123
124
impl Command {
125
    /// Whether a bind running this still fires on a locked session, which
126
    /// leaves out everything that moves focus, windows or tags, and quitting.
127
    pub fn allowed_while_locked(&self) -> bool {
128
        matches!(self, Command::Spawn { .. } | Command::Reload)
129
    }
130
131
    /// Parses the word form, as in `["move-container", "left"]`.
132
    pub fn parse<S: AsRef<str>>(words: &[S]) -> Result<Self, ParseError> {
133
        let words: Vec<&str> = words.iter().map(AsRef::as_ref).collect();
134
        let Some((&name, args)) = words.split_first() else {
135
            return Err(ParseError("empty command".into()));
136
        };
137
        let err = |m: &str| ParseError(format!("{name}: {m}"));
138
        let one = || match args {
139
            [a] => Ok(a.to_string()),
140
            _ => Err(err("takes exactly one argument")),
141
        };
142
        let none = |c: Command| {
143
            if args.is_empty() {
144
                Ok(c)
145
            } else {
146
                Err(err("takes no arguments"))
147
            }
148
        };
149
        let dir = || -> Result<Dir, ParseError> {
150
            match one()?.as_str() {
151
                "left" | "h" => Ok(Dir::Left),
152
                "right" | "l" => Ok(Dir::Right),
153
                "up" | "k" => Ok(Dir::Up),
154
                "down" | "j" => Ok(Dir::Down),
155
                d => Err(err(&format!("unknown direction {d}"))),
156
            }
157
        };
158
        Ok(match name {
159
            "spawn" if !args.is_empty() => Command::Spawn {
160
                argv: args.iter().map(|a| a.to_string()).collect(),
161
            },
162
            "spawn" => return Err(err("needs a program")),
163
            "close" => none(Command::Close)?,
164
            "quit" => none(Command::Quit)?,
165
            "reload" => none(Command::Reload)?,
166
            "flip" => none(Command::Flip)?,
167
            "maximize" => none(Command::Maximize)?,
168
            "invert-move" => none(Command::InvertMove)?,
169
            "float" => none(Command::Float)?,
170
            "fullscreen" => none(Command::Fullscreen)?,
171
            "sticky" => none(Command::Sticky)?,
172
            "focus" => Command::Focus { dir: dir()? },
173
            "move" => Command::Move { dir: dir()? },
174
            "move-container" => Command::MoveContainer { dir: dir()? },
175
            "focus-output" => Command::FocusOutput { dir: dir()? },
176
            "send-to-output" => Command::SendToOutput { dir: dir()? },
177
            "resize" => {
178
                let [axis, delta] = args else {
179
                    return Err(err("takes an axis and a delta"));
180
                };
181
                let axis = match *axis {
182
                    "horizontal" | "h" => Axis::Horizontal,
183
                    "vertical" | "v" => Axis::Vertical,
184
                    a => return Err(err(&format!("unknown axis {a}"))),
185
                };
186
                let delta = delta
187
                    .parse()
188
                    .map_err(|_| err(&format!("bad delta {delta}")))?;
189
                Command::Resize { axis, delta }
190
            }
191
            "expand" => Command::Expand {
192
                scope: match args {
193
                    [] | ["window"] => ExpandScope::Window,
194
                    ["container"] => ExpandScope::Container,
195
                    _ => return Err(err("takes window or container")),
196
                },
197
            },
198
            "view" => Command::View { tag: one()? },
199
            "toggle-view" => Command::ToggleView { tag: one()? },
200
            "view-everywhere" => Command::ViewEverywhere { tag: one()? },
201
            "tag" => Command::Tag { tag: one()? },
202
            "reorder-tag" => {
203
                let [tag, index] = args else {
204
                    return Err(err("takes a tag and an index"));
205
                };
206
                let index = index
207
                    .parse()
208
                    .map_err(|_| err(&format!("bad index {index}")))?;
209
                Command::ReorderTag {
210
                    tag: tag.to_string(),
211
                    index,
212
                }
213
            }
214
            "scratchpad" => Command::Scratchpad { name: one()? },
215
            "summon" => Command::Summon { name: one()? },
216
            "dismiss" => Command::Dismiss {
217
                name: match args {
218
                    [] => None,
219
                    [n] => Some(n.to_string()),
220
                    _ => return Err(err("takes at most one name")),
221
                },
222
            },
223
            "power" => {
224
                let (on, output) = match args {
225
                    ["on"] => (true, None),
226
                    ["off"] => (false, None),
227
                    ["on", o] => (true, Some(o.to_string())),
228
                    ["off", o] => (false, Some(o.to_string())),
229
                    _ => return Err(err("takes on or off and optionally an output")),
230
                };
231
                Command::Power { on, output }
232
            }
233
            _ => return Err(ParseError(format!("unknown command {name}"))),
234
        })
235
    }
236
}
237
238
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
239
#[serde(rename_all = "kebab-case")]
240
pub enum Request {
241
    Run(Command),
242
    Get(Query),
243
    /// Streams a `State` event after every change until the client hangs up.
244
    Subscribe {},
245
}
246
247
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
248
#[serde(rename_all = "kebab-case")]
249
pub enum Query {
250
    State,
251
    Version,
252
}
253
254
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
255
pub struct Envelope<T> {
256
    pub v: u32,
257
    #[serde(default, skip_serializing_if = "Option::is_none")]
258
    pub id: Option<u64>,
259
    #[serde(flatten)]
260
    pub body: T,
261
}
262
263
impl<T> Envelope<T> {
264
    pub fn new(id: Option<u64>, body: T) -> Self {
265
        Self {
266
            v: VERSION,
267
            id,
268
            body,
269
        }
270
    }
271
}
272
273
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
274
#[serde(rename_all = "kebab-case")]
275
pub enum Reply {
276
    Ok(Option<Answer>),
277
    Error(String),
278
    Event(State),
279
}
280
281
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
282
#[serde(rename_all = "kebab-case")]
283
pub enum Answer {
284
    State(State),
285
    Version(String),
286
    Warnings(Vec<String>),
287
}
288
289
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
290
pub struct State {
291
    /// The next window move does the opposite of the configured default.
292
    pub move_inverted: bool,
293
    pub tags: Vec<Tag>,
294
    pub outputs: Vec<Output>,
295
    pub windows: Vec<Window>,
296
}
297
298
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
299
pub struct Tag {
300
    pub name: String,
301
    pub urgent: bool,
302
}
303
304
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
305
pub struct Output {
306
    pub name: String,
307
    /// x, y, width, height in logical pixels.
308
    pub area: [f64; 4],
309
    pub viewed: Vec<String>,
310
    pub active: bool,
311
}
312
313
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
314
pub struct Window {
315
    pub id: u64,
316
    pub app_id: String,
317
    pub title: String,
318
    pub tag: String,
319
    pub output: Option<String>,
320
    pub floating: bool,
321
    pub fullscreen: bool,
322
    pub sticky: bool,
323
    pub scratchpad: Option<String>,
324
    pub visible: bool,
325
    pub focused: bool,
326
    pub urgent: bool,
327
}