src/config/keybindings.rs

59 lines · 2527 bytes

 1use crate::global::{structs::KeyAction, traits::ConfigTrait};
 2use crossterm::event::KeyCode;
 3use serde::{Deserialize, Serialize};
 4use std::collections::HashMap;
 5use typemap::Key;
 6
 7// The outer HashMap<KeyCode, T> gets a value for whatever code is being pressed
 8// The inner HashMap<u8, KeyAction> gets the action using a u8 representing a key modifier
 9// The u8 for each modifier key can be found in https://docs.rs/crossterm/latest/src/crossterm/event.rs.html#587-603
10// The sum of u8 for each key modifier would mean having all of those modifiers at the same time
11/// `keybindings.yml`, contains a hashmap of key + key modifier to action pair
12#[derive(Serialize, Deserialize, Clone)]
13pub struct KeyBindingsConfig(pub HashMap<KeyCode, HashMap<u8, KeyAction>>);
14
15impl ConfigTrait for KeyBindingsConfig {
16    const LABEL: &'static str = "keybindings";
17}
18
19impl Key for KeyBindingsConfig {
20    type Value = Self;
21}
22
23impl Default for KeyBindingsConfig {
24    fn default() -> Self {
25        Self(HashMap::from([
26            // movement keys                                            // Alt left should be back
27            (
28                KeyCode::Left,
29                HashMap::from([(0, KeyAction::MoveLeft), (4, KeyAction::Back)]),
30            ),
31            (KeyCode::Right, HashMap::from([(0, KeyAction::MoveRight)])),
32            (KeyCode::Up, HashMap::from([(0, KeyAction::MoveUp)])),
33            (KeyCode::Down, HashMap::from([(0, KeyAction::MoveDown)])),
34            // vim keybindings
35            (
36                KeyCode::Char('h'),
37                HashMap::from([(0, KeyAction::MoveLeft)]),
38            ),
39            (
40                KeyCode::Char('j'),
41                HashMap::from([(0, KeyAction::MoveDown)]),
42            ),
43            (KeyCode::Char('k'), HashMap::from([(0, KeyAction::MoveUp)])),
44            (
45                KeyCode::Char('l'),
46                HashMap::from([(0, KeyAction::MoveRight)]),
47            ),
48            // functional keys
49            (KeyCode::Enter, HashMap::from([(0, KeyAction::Select)])),
50            (KeyCode::Esc, HashMap::from([(0, KeyAction::Deselect)])),
51            (KeyCode::Char('q'), HashMap::from([(0, KeyAction::Exit)])),
52            (KeyCode::Char('r'), HashMap::from([(2, KeyAction::Reload)])),
53            // history
54            (KeyCode::Backspace, HashMap::from([(0, KeyAction::Back)])),
55            (KeyCode::End, HashMap::from([(0, KeyAction::ClearHistory)])),
56            (KeyCode::Home, HashMap::from([(0, KeyAction::FirstHistory)])),
57        ]))
58    }
59}