src/config/keybindings.rs

224 lines · 7423 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
 43            // Alt left should be back
 44            (
 45                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Left),
 46                HashMap::from([
 47                    (0, KeyAction::MoveLeft),
 48                    (2, KeyAction::PreviousWord),
 49                    (4, KeyAction::Back),
 50                ]),
 51            ),
 52            (
 53                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Right),
 54                HashMap::from([(0, KeyAction::MoveRight), (2, KeyAction::NextWord)]),
 55            ),
 56            (
 57                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Up),
 58                HashMap::from([(0, KeyAction::MoveUp)]),
 59            ),
 60            (
 61                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Down),
 62                HashMap::from([(0, KeyAction::MoveDown)]),
 63            ),
 64            // vim keybindings
 65            (
 66                KeyCodeSerde::Char('h'),
 67                HashMap::from([(0, KeyAction::MoveLeft)]),
 68            ),
 69            (
 70                KeyCodeSerde::Char('j'),
 71                HashMap::from([(0, KeyAction::MoveDown)]),
 72            ),
 73            (
 74                KeyCodeSerde::Char('k'),
 75                HashMap::from([(0, KeyAction::MoveUp)]),
 76            ),
 77            (
 78                KeyCodeSerde::Char('l'),
 79                HashMap::from([(0, KeyAction::MoveRight)]),
 80            ),
 81            // functional keys
 82            (
 83                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Enter),
 84                HashMap::from([(0, KeyAction::Select)]),
 85            ),
 86            (
 87                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Esc),
 88                HashMap::from([(0, KeyAction::Deselect)]),
 89            ),
 90            (
 91                KeyCodeSerde::F(String::from("F5")),
 92                HashMap::from([(0, KeyAction::Reload)]),
 93            ),
 94            (
 95                KeyCodeSerde::Char('q'),
 96                HashMap::from([(0, KeyAction::Exit)]),
 97            ),
 98            (
 99                KeyCodeSerde::F("F5".to_string()),
100                HashMap::from([(0, KeyAction::Reload)]),
101            ),
102            (
103                KeyCodeSerde::Char('r'),
104                HashMap::from([(2, KeyAction::Reload)]),
105            ),
106            (
107                KeyCodeSerde::Char(':'),
108                HashMap::from([(0, KeyAction::StartCommandCapture)]),
109            ),
110            // history
111            (
112                KeyCodeSerde::Char('d'),
113                HashMap::from([(0, KeyAction::ClearHistory), (4, KeyAction::RemoveWord)]),
114            ),
115            (
116                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Backspace),
117                HashMap::from([(0, KeyAction::Back)]),
118            ),
119            (
120                KeyCodeSerde::KeyVariants(KeyVariantsSerde::End),
121                HashMap::from([(0, KeyAction::ClearHistory)]),
122            ),
123            (
124                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Home),
125                HashMap::from([(0, KeyAction::FirstHistory)]),
126            ),
127            // text editing
128            (
129                KeyCodeSerde::Char('v'),
130                HashMap::from([(2, KeyAction::Paste)]),
131            ),
132            (
133                KeyCodeSerde::Char('w'),
134                HashMap::from([(2, KeyAction::RemoveWord)]),
135            ),
136            (
137                KeyCodeSerde::Char('u'),
138                HashMap::from([(2, KeyAction::ClearLine)]),
139            ),
140            (
141                KeyCodeSerde::Char('a'),
142                HashMap::from([(2, KeyAction::First)]),
143            ),
144            (
145                KeyCodeSerde::Char('e'),
146                HashMap::from([(2, KeyAction::End)]),
147            ),
148        ]))
149    }
150}
151
152impl KeyBindingsConfigSerde {
153    /// converts KeyBindingsConfigSerde into KeyBindingsConfig
154    pub fn into(self) -> Option<KeyBindingsConfig> {
155        let mut out = HashMap::new();
156
157        // simply loops over the serde hashmap and insert them into the new one
158        for (keycodeserde, map) in self.0.into_iter() {
159            out.insert(keycodeserde.to_keycode()?, map);
160        }
161
162        Some(KeyBindingsConfig(out))
163    }
164}
165
166impl KeyBindingsConfig {
167    /// generates a new file if the original one is invalid
168    pub fn load(write: WriteConfig) -> Result<Self, Box<dyn Error>> {
169        let serde = *KeyBindingsConfigSerde::load(write)?;
170        // check if it be converted from `KeyBindingsConfigSerde` to `KeyBindingsConfig`
171        let try_into = serde.into();
172
173        if let Some(keybindings) = try_into {
174            return Ok(keybindings);
175        }
176
177        let config_path = home_dir().unwrap().join(format!(
178            ".config/youtube-tui/{}.{}",
179            KeyBindingsConfigSerde::LABEL,
180            EXTENSION
181        ));
182
183        // if it cannot, back it up and regenerate it
184        let mut new_path = config_path.clone();
185        new_path.pop();
186        new_path.push(format!(
187            "{}-{}.{}",
188            KeyBindingsConfigSerde::LABEL,
189            chrono::offset::Local::now(),
190            EXTENSION
191        ));
192        fs::rename(&config_path, &new_path)?;
193
194        // here generates a default and write it to the file
195        let default = KeyBindingsConfigSerde::default();
196
197        let mut file = OpenOptions::new()
198            .write(true)
199            .create(true)
200            .truncate(true)
201            .open(&config_path)?;
202
203        file.write_all(serde_yaml::to_string(&default)?.as_bytes())?;
204
205        match default.into() {
206            Some(keybindings) => Ok(keybindings),
207            // if the default still cannot be converted, panic and exit the program
208            None => panic!(
209                "the default for {}.{} is invalid",
210                KeyBindingsConfigSerde::LABEL,
211                EXTENSION
212            ),
213        }
214    }
215
216    // gets the keyaction with the key
217    pub fn get(&self, key: KeyEvent) -> Option<KeyAction> {
218        if let Some(keyactions) = self.0.get(&key.code) {
219            keyactions.get(&key.modifiers.bits()).copied()
220        } else {
221            None
222        }
223    }
224}