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