atagen

monolith

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