src/config/keybindings.rs

195 lines · 6507 bytes

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