src/config/keybindings.rs

192 lines · 6458 bytes

  1use super::serde::{KeyCodeSerde, KeyVariantsSerde};
  2use crate::global::{
  3    structs::KeyAction,
  4    traits::{ConfigTrait, EXTENSION},
  5};
  6use crossterm::event::{KeyCode, KeyEvent};
  7use home::home_dir;
  8use serde::{Deserialize, Serialize};
  9use std::{
 10    collections::HashMap,
 11    error::Error,
 12    fs::{self, OpenOptions},
 13    io::Write,
 14};
 15use typemap::Key;
 16
 17// The outer HashMap<KeyCode, T> gets a value for whatever code is being pressed
 18// The inner HashMap<u8, KeyAction> gets the action using a u8 representing a key modifier
 19// The u8 for each modifier key can be found in https://docs.rs/crossterm/latest/src/crossterm/event.rs.html#587-603
 20// The sum of u8 for each key modifier would mean having all of those modifiers at the same time
 21/// `keybindings.yml`, contains a hashmap of key + key modifier to action pair
 22#[derive(Clone)]
 23pub struct KeyBindingsConfig(pub HashMap<KeyCode, HashMap<u8, KeyAction>>);
 24
 25impl Key for KeyBindingsConfig {
 26    type Value = Self;
 27}
 28
 29#[derive(Serialize, Deserialize, Clone)]
 30pub struct KeyBindingsConfigSerde(pub HashMap<KeyCodeSerde, HashMap<u8, KeyAction>>);
 31
 32impl ConfigTrait for KeyBindingsConfigSerde {
 33    const LABEL: &'static str = "keybindings";
 34}
 35
 36impl Default for KeyBindingsConfigSerde {
 37    fn default() -> Self {
 38        Self(HashMap::from([
 39            // movement keys                                            // Alt left should be back
 40            (
 41                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Left),
 42                HashMap::from([(0, KeyAction::MoveLeft), (4, KeyAction::Back)]),
 43            ),
 44            (
 45                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Right),
 46                HashMap::from([(0, KeyAction::MoveRight)]),
 47            ),
 48            (
 49                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Up),
 50                HashMap::from([(0, KeyAction::MoveUp)]),
 51            ),
 52            (
 53                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Down),
 54                HashMap::from([(0, KeyAction::MoveDown)]),
 55            ),
 56            // vim keybindings
 57            (
 58                KeyCodeSerde::Char('h'),
 59                HashMap::from([(0, KeyAction::MoveLeft)]),
 60            ),
 61            (
 62                KeyCodeSerde::Char('j'),
 63                HashMap::from([(0, KeyAction::MoveDown)]),
 64            ),
 65            (
 66                KeyCodeSerde::Char('k'),
 67                HashMap::from([(0, KeyAction::MoveUp)]),
 68            ),
 69            (
 70                KeyCodeSerde::Char('l'),
 71                HashMap::from([(0, KeyAction::MoveRight)]),
 72            ),
 73            // functional keys
 74            (
 75                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Enter),
 76                HashMap::from([(0, KeyAction::Select)]),
 77            ),
 78            (
 79                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Esc),
 80                HashMap::from([(0, KeyAction::Deselect)]),
 81            ),
 82            (
 83                KeyCodeSerde::F(String::from("F5")),
 84                HashMap::from([(0, KeyAction::Reload)]),
 85            ),
 86            (
 87                KeyCodeSerde::Char('q'),
 88                HashMap::from([(0, KeyAction::Exit)]),
 89            ),
 90            (
 91                KeyCodeSerde::Char('r'),
 92                HashMap::from([(2, KeyAction::Reload)]),
 93            ),
 94            (
 95                KeyCodeSerde::Char(':'),
 96                HashMap::from([(0, KeyAction::StartCommandCapture)]),
 97            ),
 98            // history
 99            (
100                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Backspace),
101                HashMap::from([(0, KeyAction::Back)]),
102            ),
103            (
104                KeyCodeSerde::KeyVariants(KeyVariantsSerde::End),
105                HashMap::from([(0, KeyAction::ClearHistory)]),
106            ),
107            (
108                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Home),
109                HashMap::from([(0, KeyAction::FirstHistory)]),
110            ),
111            // clipboard
112            (
113                KeyCodeSerde::Char('v'),
114                HashMap::from([(2, KeyAction::Paste)]),
115            ),
116        ]))
117    }
118}
119
120impl KeyBindingsConfigSerde {
121    /// converts KeyBindingsConfigSerde into KeyBindingsConfig
122    pub fn into(self) -> Option<KeyBindingsConfig> {
123        let mut out = HashMap::new();
124
125        // simply loops over the serde hashmap and insert them into the new one
126        for (keycodeserde, map) in self.0.into_iter() {
127            out.insert(keycodeserde.to_keycode()?, map);
128        }
129
130        Some(KeyBindingsConfig(out))
131    }
132}
133
134impl KeyBindingsConfig {
135    /// generates a new file if the original one is invalid
136    pub fn load() -> Result<Self, Box<dyn Error>> {
137        let serde = *KeyBindingsConfigSerde::load()?;
138        // check if it be converted from `KeyBindingsConfigSerde` to `KeyBindingsConfig`
139        let try_into = serde.into();
140
141        if let Some(keybindings) = try_into {
142            return Ok(keybindings);
143        }
144
145        let config_path = home_dir().unwrap().join(format!(
146            ".config/youtube-tui/{}.{}",
147            KeyBindingsConfigSerde::LABEL,
148            EXTENSION
149        ));
150
151        // if it cannot, back it up and regenerate it
152        let mut new_path = config_path.clone();
153        new_path.pop();
154        new_path.push(format!(
155            "{}-{}.{}",
156            KeyBindingsConfigSerde::LABEL,
157            chrono::offset::Local::now(),
158            EXTENSION
159        ));
160        fs::rename(&config_path, &new_path)?;
161
162        // here generates a default and write it to the file
163        let default = KeyBindingsConfigSerde::default();
164
165        let mut file = OpenOptions::new()
166            .write(true)
167            .create(true)
168            .truncate(true)
169            .open(&config_path)?;
170
171        file.write_all(serde_yaml::to_string(&default)?.as_bytes())?;
172
173        match default.into() {
174            Some(keybindings) => Ok(keybindings),
175            // if the default still cannot be converted, panic and exit the program
176            None => panic!(
177                "the default for {}.{} is invalid",
178                KeyBindingsConfigSerde::LABEL,
179                EXTENSION
180            ),
181        }
182    }
183
184    // gets the keyaction with the key
185    pub fn get(&self, key: KeyEvent) -> Option<KeyAction> {
186        if let Some(keyactions) = self.0.get(&key.code) {
187            keyactions.get(&key.modifiers.bits()).copied()
188        } else {
189            None
190        }
191    }
192}