lib-bspwm 0.1.1

A small library for dealing with the output of `bspc wm -d` & `bspc query` from bspwm
Documentation
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use serde::{Deserialize, Serialize};
use std::{fmt::Display, process::Command};
use thiserror::Error;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Layout {
    Tiled,
    PsuedoTiled,
    Floating,
    Monocle,
}

impl Default for Layout {
    fn default() -> Self {
        Self::Tiled
    }
}

impl Display for Layout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Tiled => write!(f, "tiled"),
            Self::PsuedoTiled => write!(f, "pseudo-tiled"),
            Self::Floating => write!(f, "floating"),
            Self::Monocle => write!(f, "monocle"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SplitType {
    Vertical,
    Horizontal,
}

impl Default for SplitType {
    fn default() -> Self {
        Self::Vertical
    }
}

impl Display for SplitType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SplitType::Vertical => write!(f, "vertical"),
            SplitType::Horizontal => write!(f, "horizontal"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Layer {
    Normal,
}

impl Default for Layer {
    fn default() -> Self {
        Self::Normal
    }
}

impl Display for Layer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Layer::Normal => write!(f, "normal"),
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Constraints {
    pub min_width: usize,
    pub min_height: usize,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Padding {
    pub top: usize,
    pub right: usize,
    pub bottom: usize,
    pub left: usize,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Rectangle {
    pub x: usize,
    pub y: usize,
    pub width: usize,
    pub height: usize,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Focus {
    monitor_id: usize,
    desktop_id: usize,
    node_id: usize,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct State {
    pub focused_monitor_id: usize,
    pub primary_monitor_id: usize,
    pub clients_count: usize,
    pub monitors: Vec<Monitor>,
    pub focus_history: Vec<Focus>,
    pub stacking_list: Vec<usize>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Monitor {
    pub name: String,
    pub id: usize,
    pub randr_id: usize,
    pub wired: bool,
    pub sticky_count: usize,
    pub window_gap: usize,
    pub border_width: usize,
    pub focused_desktop_id: usize,
    pub desktops: Vec<Desktop>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Desktop {
    pub name: String,
    pub id: usize,
    pub layout: Layout,
    pub user_layout: Layout,
    pub window_gap: usize,
    pub border_width: usize,
    pub focused_node_id: usize,
    pub padding: Padding,
    pub root: Option<Tree>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tree {
    pub id: usize,
    pub split_type: SplitType,
    pub vacant: bool,
    pub hidden: bool,
    pub sticky: bool,
    pub private: bool,
    pub locked: bool,
    pub marked: bool,
    pub presel: Option<String>,
    pub rectangle: Rectangle,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Node {
    pub id: usize,
    pub split_type: SplitType,
    pub split_ratio: f32,
    pub vacant: bool,
    pub hidden: bool,
    pub sticky: bool,
    pub private: bool,
    pub locked: bool,
    pub marked: bool,
    pub presel: Option<String>,
    pub rectangle: Rectangle,
    pub constrainnts: Option<Constraints>,
    pub first_child: Option<Box<Node>>,
    pub second_child: Option<Box<Node>>,
    pub client: Client,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Client {
    pub class_name: String,
    pub instance_name: String,
    pub border_width: usize,
    pub state: Layout,
    pub last_state: Layout,
    pub layer: Layer,
    pub last_layer: Layer,
    pub urgent: bool,
    pub shown: bool,
    pub tiled_rectangle: Rectangle,
    pub floating_rectangle: Rectangle,
}

#[derive(Debug, Error)]
pub enum Error {
    #[error("Failed to deserialize output from `bspc wm -d` or `bspc query <DOMAIN>`")]
    Deserialize,

    #[error(transparent)]
    IoError(#[from] std::io::Error),
}

const PROG: &'static str = "bspc";
const DUMP_ARGS: &'static [&'static str; 2] = &["wm", "-d"];
const QUERY_ARGS: &'static [&'static str; 1] = &["query"];
const QUERY_TREE_FLAG: &'static str = "-T";
const MON_SEL_QUERY_FLAG: &'static str = "-m";
const DESK_SEL_QUERY_FLAG: &'static str = "-d";
const NODE_SEL_QUERY_FLAG: &'static str = "-n";
const _MON_ID_OUT_FLAG: &'static str = "-M";
const _DESK_ID_OUT_FLAG: &'static str = "-D";
const _NODE_ID_OUT_FLAG: &'static str = "-N";

pub fn dump_state() -> Result<State, self::Error> {
    match serde_json::from_slice::<State>(&Command::new(PROG).args(DUMP_ARGS).output()?.stdout) {
        Ok(state) => Ok(state),
        Err(_) => Err(self::Error::Deserialize),
    }
}

#[derive(Debug)]
pub struct Query {
    args: Vec<String>,
}

impl Query {
    pub fn new() -> Self {
        Self {
            args: QUERY_ARGS.iter().map(|s| s.to_string()).collect(),
        }
    }

    pub fn monitor(mut self, name: &str) -> Self {
        if name.is_empty() {
            return self;
        }

        // Make a new Vec so that we're aren't passing multiple domain selectors.
        // `bspc` doesn't like it.
        let mut args: Vec<String> = QUERY_ARGS.iter().map(|s| s.to_string()).collect();
        args.push(MON_SEL_QUERY_FLAG.to_string());
        args.push(name.to_string());
        self.args = args;

        self
    }

    pub fn desktop(mut self, name: &str) -> Self {
        if name.is_empty() {
            return self;
        }

        let mut args: Vec<String> = QUERY_ARGS.iter().map(|s| s.to_string()).collect();
        args.push(DESK_SEL_QUERY_FLAG.to_string());
        args.push(name.to_string());
        self.args = args;

        self
    }

    pub fn node(mut self, id: usize) -> Self {
        let mut args: Vec<String> = QUERY_ARGS.iter().map(|s| s.to_string()).collect();
        args.push(NODE_SEL_QUERY_FLAG.to_string());
        args.push(id.to_string());
        self.args = args;

        self
    }

    fn _get_monitor_ids(&mut self) -> Vec<usize> {
        self.args.push(_MON_ID_OUT_FLAG.to_string());
        todo!()
    }

    fn _get_desktop_ids(&mut self) -> Vec<usize> {
        self.args.push(_DESK_ID_OUT_FLAG.to_string());
        todo!()
    }

    fn _get_node_ids(&mut self) -> Vec<usize> {
        self.args.push(_NODE_ID_OUT_FLAG.to_string());
        todo!()
    }

    pub fn get_monitor_tree(&mut self) -> Result<Monitor, self::Error> {
        // `bspc` requires at least one domain flag, even if it's passed
        // parameter-less, so here we count the flags and add a single `-m` if
        // necessary.
        if self.args.len() == 1 {
            self.args.push(MON_SEL_QUERY_FLAG.to_string());
        }

        self.args.push(QUERY_TREE_FLAG.to_string());
        match serde_json::from_slice::<Monitor>(
            &Command::new(PROG).args(&self.args).output()?.stdout,
        ) {
            Ok(m) => Ok(m),
            Err(_) => Err(self::Error::Deserialize),
        }
    }

    pub fn get_desktop_tree(&mut self) -> Result<Desktop, self::Error> {
        if self.args.len() == 1 {
            self.args.push(DESK_SEL_QUERY_FLAG.to_string());
        }

        self.args.push(QUERY_TREE_FLAG.to_string());
        match serde_json::from_slice::<Desktop>(
            &Command::new(PROG).args(&self.args).output()?.stdout,
        ) {
            Ok(d) => Ok(d),
            Err(_) => Err(self::Error::Deserialize),
        }
    }

    pub fn get_node_tree(&mut self) -> Result<Node, self::Error> {
        if self.args.len() == 1 {
            self.args.push(NODE_SEL_QUERY_FLAG.to_string());
        }

        self.args.push(QUERY_TREE_FLAG.to_string());
        match serde_json::from_slice::<Node>(&Command::new(PROG).args(&self.args).output()?.stdout)
        {
            Ok(n) => Ok(n),
            Err(_) => Err(self::Error::Deserialize),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    use crate::{dump_state, Query, DUMP_ARGS, PROG, QUERY_ARGS};

    #[test]
    fn dump_args() {
        let mut args = vec![PROG];
        for arg in DUMP_ARGS {
            args.push(arg)
        }

        assert_eq!(args, vec![PROG, "wm", "-d"])
    }

    #[test]
    fn query_args() {
        let mut args = vec![PROG];
        for arg in QUERY_ARGS {
            args.push(arg)
        }

        assert_eq!(args, vec![PROG, "query"])
    }

    #[test]
    fn outputs() {
        if let Err(e) = Command::new(PROG).args(DUMP_ARGS).output() {
            assert!(false, "{}", e)
        }
    }

    #[test]
    fn deserializes() {
        if let Err(e) = dump_state() {
            assert!(false, "{}", e)
        }
    }

    #[test]
    fn monitor_tree() {
        let mut query = Query::new();
        if let Err(e) = query.get_monitor_tree() {
            eprintln!("{:#?}", query);
            assert!(false, "{}", e)
        }
    }

    #[test]
    fn desktop_tree() {
        let mut query = Query::new();
        if let Err(e) = query.get_desktop_tree() {
            eprintln!("{:#?}", query);
            assert!(false, "{}", e)
        }
    }

    #[test]
    fn node_tree() {
        let mut query = Query::new();
        if let Err(e) = query.get_node_tree() {
            eprintln!("{:#?}", query);
            assert!(false, "{}", e)
        }
    }

    #[test]
    fn with_param() {
        let query = Query::new().monitor("testies");
        assert_eq!(query.args, vec!["query", "-m", "testies"])
    }

    #[test]
    fn try_many_param() {
        let query = Query::new().monitor("discarded").monitor("testies");
        assert_eq!(query.args, vec!["query", "-m", "testies"])
    }
}