src/config/remap.rs

139 lines · 3776 bytes

  1use std::{
  2    collections::HashMap,
  3    error::Error,
  4    fs::{self, OpenOptions},
  5    io::Write,
  6};
  7
  8use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
  9use home::home_dir;
 10use serde::{Deserialize, Serialize};
 11use typemap::Key;
 12
 13use crate::global::traits::{ConfigTrait, EXTENSION};
 14
 15use super::{serde::KeyCodeSerde, WriteConfig};
 16
 17#[derive(Clone, Serialize, Deserialize)]
 18pub struct RemapConfigSerde(pub HashMap<KeyCodeSerde, HashMap<u8, RemapItemSerde>>);
 19
 20#[derive(Clone, Serialize, Deserialize)]
 21pub struct RemapItemSerde {
 22    pub code: KeyCodeSerde,
 23    pub modifiers: u8,
 24}
 25
 26#[derive(Clone)]
 27pub struct RemapItem {
 28    pub code: KeyCode,
 29    pub modifiers: KeyModifiers,
 30}
 31
 32impl RemapItemSerde {
 33    pub fn try_into_remap(self) -> Option<RemapItem> {
 34        Some(RemapItem {
 35            code: self.code.to_keycode()?,
 36            modifiers: KeyModifiers::from_bits(self.modifiers)?,
 37        })
 38    }
 39}
 40impl RemapConfigSerde {
 41    /// converts KeyBindingsConfigSerde into KeyBindingsConfig
 42    pub fn into(self) -> Option<RemapConfig> {
 43        let mut out = HashMap::new();
 44
 45        // simply loops over the serde hashmap and insert them into the new one
 46        for (remapserde, map) in self.0.into_iter() {
 47            let mut keyout = HashMap::new();
 48            for (modifier, item) in map.into_iter() {
 49                keyout.insert(modifier, item.try_into_remap()?);
 50            }
 51            out.insert(remapserde.to_keycode()?, keyout);
 52        }
 53
 54        Some(RemapConfig(out))
 55    }
 56}
 57
 58impl ConfigTrait for RemapConfigSerde {
 59    const LABEL: &'static str = "remaps";
 60}
 61
 62impl Default for RemapConfigSerde {
 63    fn default() -> Self {
 64        Self(HashMap::from([(
 65            KeyCodeSerde::Char('a'),
 66            HashMap::from([(
 67                5,
 68                RemapItemSerde {
 69                    code: KeyCodeSerde::Char('b'),
 70                    modifiers: 5,
 71                },
 72            )]),
 73        )]))
 74    }
 75}
 76
 77#[derive(Clone)]
 78pub struct RemapConfig(pub HashMap<KeyCode, HashMap<u8, RemapItem>>);
 79
 80impl RemapConfig {
 81    pub fn load(write: WriteConfig) -> Result<Self, Box<dyn Error>> {
 82        let serde = *RemapConfigSerde::load(write)?;
 83        let try_into = serde.into();
 84
 85        if let Some(keybindings) = try_into {
 86            return Ok(keybindings);
 87        }
 88
 89        let config_path = home_dir().unwrap().join(format!(
 90            ".config/youtube-tui/{}.{}",
 91            RemapConfigSerde::LABEL,
 92            EXTENSION
 93        ));
 94
 95        // if it cannot, back it up and regenerate it
 96        let mut new_path = config_path.clone();
 97        new_path.pop();
 98        new_path.push(format!(
 99            "{}-{}.{}",
100            RemapConfigSerde::LABEL,
101            chrono::offset::Local::now(),
102            EXTENSION
103        ));
104        fs::rename(&config_path, &new_path)?;
105
106        // here generates a default and write it to the file
107        let default = RemapConfigSerde::default();
108
109        let mut file = OpenOptions::new()
110            .write(true)
111            .create(true)
112            .truncate(true)
113            .open(&config_path)?;
114
115        file.write_all(serde_yaml_ng::to_string(&default)?.as_bytes())?;
116
117        match default.into() {
118            Some(keybindings) => Ok(keybindings),
119            None => panic!(
120                "the default for {}.{} is invalid",
121                RemapConfigSerde::LABEL,
122                EXTENSION
123            ),
124        }
125    }
126
127    pub fn get(&self, key: &mut KeyEvent) {
128        if let Some(remaps) = self.0.get(&key.code) {
129            if let Some(remapped) = remaps.get(&key.modifiers.bits()) {
130                key.code = remapped.code;
131                key.modifiers = remapped.modifiers;
132            }
133        }
134    }
135}
136
137impl Key for RemapConfig {
138    type Value = Self;
139}