src/config/keybindings.rs

174 lines · 5888 bytes

  1use super::serde::{KeyCodeSerde, KeyVariantsSerde};
  2use crate::global::{
  3    structs::KeyAction,
  4    traits::{ConfigTrait, EXTENSION},
  5};
  6use crossterm::event::KeyCode;
  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            // history
 95            (
 96                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Backspace),
 97                HashMap::from([(0, KeyAction::Back)]),
 98            ),
 99            (
100                KeyCodeSerde::KeyVariants(KeyVariantsSerde::End),
101                HashMap::from([(0, KeyAction::ClearHistory)]),
102            ),
103            (
104                KeyCodeSerde::KeyVariants(KeyVariantsSerde::Home),
105                HashMap::from([(0, KeyAction::FirstHistory)]),
106            ),
107        ]))
108    }
109}
110
111impl KeyBindingsConfigSerde {
112    /// converts KeyBindingsConfigSerde into KeyBindingsConfig
113    pub fn into(self) -> Option<KeyBindingsConfig> {
114        let mut out = HashMap::new();
115
116        // simply loops over the serde hashmap and insert them into the new one
117        for (keycodeserde, map) in self.0.into_iter() {
118            out.insert(keycodeserde.to_keycode()?, map);
119        }
120
121        Some(KeyBindingsConfig(out))
122    }
123}
124
125impl KeyBindingsConfig {
126    /// generates a new file if the original one is invalid
127    pub fn load() -> Result<Self, Box<dyn Error>> {
128        let serde = *KeyBindingsConfigSerde::load()?;
129        // check if it be converted from `KeyBindingsConfigSerde` to `KeyBindingsConfig`
130        let try_into = serde.into();
131
132        if let Some(keybindings) = try_into {
133            return Ok(keybindings);
134        }
135
136        let config_path = home_dir().unwrap().join(format!(
137            ".config/youtube-tui/{}.{}",
138            KeyBindingsConfigSerde::LABEL,
139            EXTENSION
140        ));
141
142        // if it cannot, back it up and regenerate it
143        let mut new_path = config_path.clone();
144        new_path.pop();
145        new_path.push(format!(
146            "{}-{}.{}",
147            KeyBindingsConfigSerde::LABEL,
148            chrono::offset::Local::now(),
149            EXTENSION
150        ));
151        fs::rename(&config_path, &new_path)?;
152
153        // here generates a default and write it to the file
154        let default = KeyBindingsConfigSerde::default();
155
156        let mut file = OpenOptions::new()
157            .write(true)
158            .create(true)
159            .truncate(true)
160            .open(&config_path)?;
161
162        file.write_all(serde_yaml::to_string(&default)?.as_bytes())?;
163
164        match default.into() {
165            Some(keybindings) => Ok(keybindings),
166            // if the default still cannot be converted, panic and exit the program
167            None => panic!(
168                "the default for {}.{} is invalid",
169                KeyBindingsConfigSerde::LABEL,
170                EXTENSION
171            ),
172        }
173    }
174}