atagen

monolith

public
Star0
Watch0
cd797308501128825795c9b79466c9c5c2bd0fcb
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/ipc/src/lib.rsRust319 lines9.3 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
    /// Parses the word form, as in `["move-container", "left"]`.
126
    pub fn parse<S: AsRef<str>>(words: &[S]) -> Result<Self, ParseError> {
127
        let words: Vec<&str> = words.iter().map(AsRef::as_ref).collect();
128
        let Some((&name, args)) = words.split_first() else {
129
            return Err(ParseError("empty command".into()));
130
        };
131
        let err = |m: &str| ParseError(format!("{name}: {m}"));
132
        let one = || match args {
133
            [a] => Ok(a.to_string()),
134
            _ => Err(err("takes exactly one argument")),
135
        };
136
        let none = |c: Command| {
137
            if args.is_empty() {
138
                Ok(c)
139
            } else {
140
                Err(err("takes no arguments"))
141
            }
142
        };
143
        let dir = || -> Result<Dir, ParseError> {
144
            match one()?.as_str() {
145
                "left" | "h" => Ok(Dir::Left),
146
                "right" | "l" => Ok(Dir::Right),
147
                "up" | "k" => Ok(Dir::Up),
148
                "down" | "j" => Ok(Dir::Down),
149
                d => Err(err(&format!("unknown direction {d}"))),
150
            }
151
        };
152
        Ok(match name {
153
            "spawn" if !args.is_empty() => Command::Spawn {
154
                argv: args.iter().map(|a| a.to_string()).collect(),
155
            },
156
            "spawn" => return Err(err("needs a program")),
157
            "close" => none(Command::Close)?,
158
            "quit" => none(Command::Quit)?,
159
            "reload" => none(Command::Reload)?,
160
            "flip" => none(Command::Flip)?,
161
            "maximize" => none(Command::Maximize)?,
162
            "invert-move" => none(Command::InvertMove)?,
163
            "float" => none(Command::Float)?,
164
            "fullscreen" => none(Command::Fullscreen)?,
165
            "sticky" => none(Command::Sticky)?,
166
            "focus" => Command::Focus { dir: dir()? },
167
            "move" => Command::Move { dir: dir()? },
168
            "move-container" => Command::MoveContainer { dir: dir()? },
169
            "focus-output" => Command::FocusOutput { dir: dir()? },
170
            "send-to-output" => Command::SendToOutput { dir: dir()? },
171
            "resize" => {
172
                let [axis, delta] = args else {
173
                    return Err(err("takes an axis and a delta"));
174
                };
175
                let axis = match *axis {
176
                    "horizontal" | "h" => Axis::Horizontal,
177
                    "vertical" | "v" => Axis::Vertical,
178
                    a => return Err(err(&format!("unknown axis {a}"))),
179
                };
180
                let delta = delta
181
                    .parse()
182
                    .map_err(|_| err(&format!("bad delta {delta}")))?;
183
                Command::Resize { axis, delta }
184
            }
185
            "expand" => Command::Expand {
186
                scope: match args {
187
                    [] | ["window"] => ExpandScope::Window,
188
                    ["container"] => ExpandScope::Container,
189
                    _ => return Err(err("takes window or container")),
190
                },
191
            },
192
            "view" => Command::View { tag: one()? },
193
            "toggle-view" => Command::ToggleView { tag: one()? },
194
            "view-everywhere" => Command::ViewEverywhere { tag: one()? },
195
            "tag" => Command::Tag { tag: one()? },
196
            "reorder-tag" => {
197
                let [tag, index] = args else {
198
                    return Err(err("takes a tag and an index"));
199
                };
200
                let index = index
201
                    .parse()
202
                    .map_err(|_| err(&format!("bad index {index}")))?;
203
                Command::ReorderTag {
204
                    tag: tag.to_string(),
205
                    index,
206
                }
207
            }
208
            "scratchpad" => Command::Scratchpad { name: one()? },
209
            "summon" => Command::Summon { name: one()? },
210
            "dismiss" => Command::Dismiss {
211
                name: match args {
212
                    [] => None,
213
                    [n] => Some(n.to_string()),
214
                    _ => return Err(err("takes at most one name")),
215
                },
216
            },
217
            "power" => {
218
                let (on, output) = match args {
219
                    ["on"] => (true, None),
220
                    ["off"] => (false, None),
221
                    ["on", o] => (true, Some(o.to_string())),
222
                    ["off", o] => (false, Some(o.to_string())),
223
                    _ => return Err(err("takes on or off and optionally an output")),
224
                };
225
                Command::Power { on, output }
226
            }
227
            _ => return Err(ParseError(format!("unknown command {name}"))),
228
        })
229
    }
230
}
231
232
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
233
#[serde(rename_all = "kebab-case")]
234
pub enum Request {
235
    Run(Command),
236
    Get(Query),
237
    /// Streams a `State` event after every change until the client hangs up.
238
    Subscribe {},
239
}
240
241
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
242
#[serde(rename_all = "kebab-case")]
243
pub enum Query {
244
    State,
245
    Version,
246
}
247
248
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
249
pub struct Envelope<T> {
250
    pub v: u32,
251
    #[serde(default, skip_serializing_if = "Option::is_none")]
252
    pub id: Option<u64>,
253
    #[serde(flatten)]
254
    pub body: T,
255
}
256
257
impl<T> Envelope<T> {
258
    pub fn new(id: Option<u64>, body: T) -> Self {
259
        Self {
260
            v: VERSION,
261
            id,
262
            body,
263
        }
264
    }
265
}
266
267
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
268
#[serde(rename_all = "kebab-case")]
269
pub enum Reply {
270
    Ok(Option<Answer>),
271
    Error(String),
272
    Event(State),
273
}
274
275
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
276
#[serde(rename_all = "kebab-case")]
277
pub enum Answer {
278
    State(State),
279
    Version(String),
280
}
281
282
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
283
pub struct State {
284
    /// The next window move does the opposite of the configured default.
285
    pub move_inverted: bool,
286
    pub tags: Vec<Tag>,
287
    pub outputs: Vec<Output>,
288
    pub windows: Vec<Window>,
289
}
290
291
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
292
pub struct Tag {
293
    pub name: String,
294
    pub urgent: bool,
295
}
296
297
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
298
pub struct Output {
299
    pub name: String,
300
    /// x, y, width, height in logical pixels.
301
    pub area: [f64; 4],
302
    pub viewed: Vec<String>,
303
    pub active: bool,
304
}
305
306
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
307
pub struct Window {
308
    pub id: u64,
309
    pub app_id: String,
310
    pub title: String,
311
    pub tag: String,
312
    pub output: Option<String>,
313
    pub floating: bool,
314
    pub fullscreen: bool,
315
    pub sticky: bool,
316
    pub scratchpad: Option<String>,
317
    pub visible: bool,
318
    pub focused: bool,
319
}