src/config/keybindings.rs

196 lines · 6583 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('c'),
114                HashMap::from([(2, KeyAction::Copy)]),
115            ),
116            (
117                KeyCodeSerde::Char('v'),
118                HashMap::from([(2, KeyAction::Paste)]),
119            ),
120        ]))
121    }
122}
123
124impl KeyBindingsConfigSerde {
125    /// converts KeyBindingsConfigSerde into KeyBindingsConfig
126    pub fn into(self) -> Option<KeyBindingsConfig> {
127        let mut out = HashMap::new();
128
129        // simply loops over the serde hashmap and insert them into the new one
130        for (keycodeserde, map) in self.0.into_iter() {
131            out.insert(keycodeserde.to_keycode()?, map);
132        }
133
134        Some(KeyBindingsConfig(out))
135    }
136}
137
138impl KeyBindingsConfig {
139    /// generates a new file if the original one is invalid
140    pub fn load() -> Result<Self, Box<dyn Error>> {
141        let serde = *KeyBindingsConfigSerde::load()?;
142        // check if it be converted from `KeyBindingsConfigSerde` to `KeyBindingsConfig`
143        let try_into = serde.into();
144
145        if let Some(keybindings) = try_into {
146            return Ok(keybindings);
147        }
148
149        let config_path = home_dir().unwrap().join(format!(
150            ".config/youtube-tui/{}.{}",
151            KeyBindingsConfigSerde::LABEL,
152            EXTENSION
153        ));
154
155        // if it cannot, back it up and regenerate it
156        let mut new_path = config_path.clone();
157        new_path.pop();
158        new_path.push(format!(
159            "{}-{}.{}",
160            KeyBindingsConfigSerde::LABEL,
161            chrono::offset::Local::now(),
162            EXTENSION
163        ));
164        fs::rename(&config_path, &new_path)?;
165
166        // here generates a default and write it to the file
167        let default = KeyBindingsConfigSerde::default();
168
169        let mut file = OpenOptions::new()
170            .write(true)
171            .create(true)
172            .truncate(true)
173            .open(&config_path)?;
174
175        file.write_all(serde_yaml::to_string(&default)?.as_bytes())?;
176
177        match default.into() {
178            Some(keybindings) => Ok(keybindings),
179            // if the default still cannot be converted, panic and exit the program
180            None => panic!(
181                "the default for {}.{} is invalid",
182                KeyBindingsConfigSerde::LABEL,
183                EXTENSION
184            ),
185        }
186    }
187
188    // gets the keyaction with the key
189    pub fn get(&self, key: KeyEvent) -> Option<KeyAction> {
190        if let Some(keyactions) = self.0.get(&key.code) {
191            keyactions.get(&key.modifiers.bits()).copied()
192        } else {
193            None
194        }
195    }
196}