use crate::colors::Colors;
use std::io::Result;
use std::process::Command;
#[derive(Clone, Debug)]
pub struct Keybind {
keymap: String,
command: String,
}
#[derive(Debug)]
pub struct Config {
keybinds: Vec<Keybind>,
colors: Colors,
modifier: String,
}
impl Config {
pub fn new() -> Config {
Config {
keybinds: vec![],
colors: Colors::default(),
modifier: String::from("Super"),
}
}
pub fn set_repeat(&self, repeat_rate: i32, repeat_delay: i32) -> &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");
return self;
}
pub fn change_super(&mut self, key: &str) -> &mut Self {
self.modifier = String::from(key);
return self;
}
pub fn set_keybind(&mut self, keys: &String, command: &String) -> &mut Self {
let keys = keys.clone();
let command = command.clone();
let keybind = Keybind {
keymap: keys,
command,
};
self.keybinds.push(keybind);
return self;
}
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]);
}
return self;
}
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);
}
return self;
}
fn apply_mouse_keybind(&self, position: &str, command: &str) {
let pos: &str;
match position {
"left" => {
pos = "BTN_LEFT";
}
"right" => {
pos = "BTN_RIGHT";
}
"middle" => {
pos = "BTN_MIDDLE";
}
_ => {
pos = "BTN_LEFT";
}
}
Command::new("riverctl")
.args([
"map-pointer",
"normal",
self.modifier.as_str(),
pos,
command,
])
.spawn()
.expect("Can't set the mouse keybind");
}
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])])
}
return new_arr;
}
fn apply_keybind(&self, keybind: Keybind) {
let command: Vec<&str> = keybind.command.split_whitespace().collect();
Command::new("riverctl")
.args([
"map",
"normal",
self.modifier.as_str(),
keybind.keymap.as_str(),
command[0],
command[1],
])
.spawn()
.expect("Can't set the keybind");
}
pub fn apply(&self) -> Result<()> {
for keybind in &self.keybinds {
let keybind = keybind.clone();
self.apply_keybind(keybind);
}
return Ok(());
}
}