river-rs 0.3.3

Utilities for configuring River Window Manager.
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
//! # Config
//!
//! The heart of river-rs library
use crate::colors::Colors;
use crate::layout::Layout;
use std::io::stdout;
use std::io::Result;
use std::io::Write;
use std::process::Command;

/// Struct for info of modifier, keymap and associated command.
///
/// You should not write Keybinds by yourself, that's why `set_keybind` and `set_keybinds` are for.
#[derive(Clone, Debug)]
pub struct Keybind {
    modifier: String,
    keymap: String,
    command: String,
}
/// Struct for setting xkb settings. After creating struct, apply settings with `Config.set_keyboard_layout`.
pub struct KeyboardLayout<T> {
    pub rules: Option<T>,
    pub model: Option<T>,
    pub variant: Option<T>,
    pub options: Option<T>,
    pub layout: Option<T>,
}
/// The heart of the River configuration, holding values for default and mouse-related keybinds, colors and modifier
///
/// Each value can only be changed with methods, because it is Rust, baby!
/// For more info, check associated structs and implemented methods.
#[derive(Debug)]
pub struct Config {
    keybinds: Vec<Keybind>,
    colors: Colors,
    layout: Layout,
    modifier: String,
}

// Util functions
impl Config {
    /// Convenient function to simplify writing config from the end users perspective
    fn serialize_to_owned(&self, arr: &Vec<[&str; 2]>) -> Vec<Vec<String>> {
        let mut new_arr: Vec<Vec<String>> = Vec::new();

        for keybind in arr {
            new_arr.push(vec![String::from(keybind[0]), String::from(keybind[1])])
        }

        new_arr
    }

    pub fn print_keybindings(&self) {
        let mut writer = stdout();
        write!(writer, "{:?}", self.keybinds).unwrap();
    }
}

// Keybinds
impl Config {
    /// Sets the single keybind
    ///
    /// # Example
    /// ```
    /// use river_rs::config::Config;
    ///
    /// let mut config = Config::default();
    /// let key = String::from("Q");
    /// let command = String::from("spanw foo");
    /// config.set_keybind(&key, &command);
    /// ```
    pub fn set_keybind(&mut self, keys: &str, command: &str) -> &mut Self {
        let keybind = Keybind {
            modifier: self.modifier.clone(),
            keymap: String::from(keys),
            command: String::from(command),
        };

        self.keybinds.push(keybind);
        self
    }
    /// Sets keybinds based on the vector of lists with 2 values
    ///
    /// Second command can be written with spaces, no need to define every argument separatly.
    ///  
    /// Takes the ownership of the vector and modifies it to supply `riverctl`
    ///
    /// # Examples
    /// ```
    /// use river_rs::config::Config;
    ///
    /// let mut config = Config::default();
    /// let keybinds = vec![
    ///   ["Q", "spawn foo"],
    ///   ["E", "exit"],
    ///   ["M", "spawn bruh"]
    /// ];
    /// config.set_keybinds(keybinds);
    /// ```
    pub fn set_keybinds(&mut self, keybinds: Vec<[&str; 2]>) -> &mut Self {
        let keybinds = self.serialize_to_owned(&keybinds);

        for keybind in keybinds {
            self.set_keybind(&keybind[0], &keybind[1]);
        }

        self
    }

    /// Every keybind is optional, so you can just provide it with `None` keyword
    ///
    /// # Example
    /// ```
    /// use river_rs::config::Config;
    ///
    /// let mut config = Config::default();
    /// config.set_mouse_keybinds(Some("move-view"), Some("resize-view"), None);
    /// ```
    ///
    pub fn set_mouse_keybinds(
        &mut self,
        left: Option<&str>,
        right: Option<&str>,
        middle: Option<&str>,
    ) -> &mut Self {
        if let Some(left_command) = left {
            self.apply_mouse_keybind("left", left_command);
        }
        if let Some(right_command) = right {
            self.apply_mouse_keybind("right", right_command);
        }
        if let Some(middle_command) = middle {
            self.apply_mouse_keybind("middle", middle_command);
        }
        self
    }

    fn apply_mouse_keybind(&self, position: &str, command: &str) {
        let pos: &str = match position {
            "left" => "BTN_LEFT",

            "right" => "BTN_RIGHT",

            "middle" => "BTN_MIDDLE",

            _ => "BTN_LEFT",
        };
        Command::new("riverctl")
            .args([
                "map-pointer",
                "normal",
                self.modifier.as_str(),
                pos,
                command,
            ])
            .spawn()
            .expect("Can't set the mouse keybind")
            .wait()
            .unwrap();
    }

    fn apply_keybind(&self, keybind: Keybind) {
        let command: Vec<&str> = keybind.command.split_whitespace().collect();
        match command.len() {
            1 => {
                Command::new("riverctl")
                    .args([
                        "map",
                        "normal",
                        keybind.modifier.as_str(),
                        keybind.keymap.as_str(),
                        command[0],
                    ])
                    .spawn()
                    .expect("Can't set the keybind\n")
                    .wait()
                    .unwrap();
            }
            2 => {
                let args = [
                    "map",
                    "normal",
                    keybind.modifier.as_str(),
                    keybind.keymap.as_str(),
                    command[0],
                    command[1],
                ];
                Command::new("riverctl")
                    .args(args)
                    .spawn()
                    .expect("Can't set the keybind\n")
                    .wait()
                    .unwrap();
            }
            0 => {
                panic!("There are no commands provided for the riverctl!\n")
            }
            _ => {
                let args: Vec<&str> = [
                    "map",
                    "normal",
                    keybind.modifier.as_str(),
                    keybind.keymap.as_str(),
                ]
                .iter()
                .chain(&command)
                .copied()
                .collect();
                Command::new("riverctl")
                    .args(args)
                    .spawn()
                    .expect("Can't set the keybind\n")
                    .wait()
                    .unwrap();
            }
        }
    }
}

impl Default for Config {
    /// Creates empty config with no keybinds.
    ///
    /// The default modifier is `Super`.
    /// To check the default colors visit Colors struct.
    fn default() -> Self {
        Config {
            keybinds: vec![],
            colors: Colors::default(),
            layout: Layout::default(),
            modifier: String::from("Super"),
        }
    }
}

// Basics
impl Config {
    /// Sets xkb settings related to repeat_rate and repeat_delay.
    ///
    /// The typematic delay indicates the amount of time (typically in milliseconds) a key needs to be pressed and held in order for the repeating process to begin.
    /// After the repeating process has been triggered, the character will be repeated with a certain frequency (usually given in Hz) specified by the typematic rate.
    ///`(Taken from the Arch Wiki)`
    pub fn set_repeat(&mut self, repeat_rate: u32, repeat_delay: u32) -> &mut Self {
        Command::new("riverctl")
            .args([
                "set-repeat",
                repeat_rate.to_string().as_str(),
                repeat_delay.to_string().as_str(),
            ])
            .spawn()
            .expect("Can't set xkb settings")
            .wait()
            .unwrap();

        self
    }

    pub fn set_layout_generator(&mut self, layout: Layout) -> &mut Self {
        self.layout = layout;
        self
    }
    /// Set xkb settings for window manager. To check available settings, look at `KeyboardLayout`
    /// struct.
    pub fn set_keyboard_layout(&mut self, layout: KeyboardLayout<&str>) -> &mut Self {
        let rules = layout.rules.unwrap_or("");
        let model = layout.model.unwrap_or("");
        let variant = layout.variant.unwrap_or("");
        let options = layout.options.unwrap_or("");

        let layout = match layout.layout {
            Some(layout) => layout,
            None => panic!("Keyboard layout is not set"),
        };

        Command::new("riverctl")
            .args([
                "keyboard-layout",
                "-rules",
                rules,
                "-model",
                model,
                "-variant",
                variant,
                "-options",
                options,
                layout,
            ])
            .spawn()
            .expect("Can't set the keyboard layout!\n")
            .wait()
            .unwrap();
        self
    }

    /// Changes the River Modifier key.
    ///
    /// Useful when chaining `set_keybinds` with different modifiers.
    ///
    /// # Example
    /// ```
    /// use river_rs::config::Config;
    ///
    /// let mut config = Config::default();
    ///
    /// let keybinds = vec![
    ///     ["C", "close"],
    ///     ["J", "focus-view next"],
    ///     ["K", "focus-view previous"],
    /// ];
    /// let shift_keybinds = vec![
    ///     ["E", "exit"],
    ///     ["J", "swap next"],
    ///     ["K", "swap previous"],
    /// ];
    /// config
    ///     .set_keybinds(keybinds)
    ///     .change_super("Super+Shift")
    ///     .set_keybinds(shift_keybinds)
    ///     .apply()
    ///     .unwrap();
    /// ```
    pub fn change_super(&mut self, key: &str) -> &mut Self {
        self.modifier = String::from(key);
        self
    }

    /// Sets tags from 1 to 9 based on passed modifiers
    pub fn set_tags(&mut self, modifier: &str, switch_modifier: &str) -> &mut Self {
        let tags: Vec<u32> = (0..9).collect();
        let tag_ids: Vec<u32> = tags.iter().map(|x| 2_u32.pow(*x)).collect();
        let mut keybinds: Vec<Keybind> = Vec::new();
        let mut idx = 0;
        while idx < tags.len() {
            keybinds.push(Keybind {
                modifier: String::from(modifier),
                keymap: (tags[idx] + 1).to_string(),
                command: String::from("set-focused-tags ") + tag_ids[idx].to_string().as_str(),
            });
            keybinds.push(Keybind {
                modifier: String::from(switch_modifier),
                keymap: (tags[idx] + 1).to_string(),
                command: String::from("set-view-tags ") + tag_ids[idx].to_string().as_str(),
            });
            idx += 1;
        }
        for keybind in keybinds {
            self.keybinds.push(keybind);
        }
        self
    }

    /// Set your autostart programs to spawn on launching River
    /// # Example
    /// ```
    /// use crate::river_rs::config::Config;
    /// let autostart = vec![
    ///     "firefox",
    ///     "kitty"
    /// ];
    ///
    /// let mut config = Config::default();
    /// config.autostart(autostart);
    /// ```
    pub fn autostart(&mut self, applications: Vec<&str>) -> &mut Self {
        for app in applications {
            Command::new("riverctl")
                .args(["spawn", app])
                .spawn()
                .expect("Can't spawn autostart programs")
                .wait()
                .unwrap();
        }
        self
    }

    fn apply_colors(&mut self) -> &mut Self {
        let background_color = format!("{:#X}", self.colors.background_color);
        let border_color_focused = format!("{:#X}", self.colors.border_color_focused);
        let border_color_unfocused = format!("{:#X}", self.colors.border_color_unfocused);

        let commands = vec![
            ["background-color", background_color.as_str()],
            ["border-color-focused", border_color_focused.as_str()],
            ["border-color-unfocused", border_color_unfocused.as_str()],
        ];

        for command in commands {
            Command::new("riverctl")
                .args(command)
                .spawn()
                .expect("Can't set colors with riverctl\n")
                .wait()
                .unwrap();
        }

        self
    }

    /// Finish setting up the config.
    ///
    /// Needs to be run at the end of setup via chaining.
    pub fn apply(&mut self) -> Result<()> {
        for keybind in &self.keybinds {
            let keybind = keybind.clone();
            self.apply_keybind(keybind);
        }
        self.layout.spawn();
        Ok(())
    }
}