Skip to main content

lefthk_core/config/command/
chord.rs

1use ron::ser::PrettyConfig;
2use serde::{Deserialize, Serialize};
3
4use crate::{
5    config::{Keybind, command::utils::denormalize_function::DenormalizeCommandFunction},
6    errors::Error,
7    worker::Worker,
8};
9
10use super::{Command, NormalizedCommand};
11
12inventory::submit! {DenormalizeCommandFunction::new::<Chord>()}
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct Chord(Vec<Keybind>);
16
17impl Chord {
18    #[must_use]
19    pub fn new(keybinds: Vec<Keybind>) -> Self {
20        Self(keybinds)
21    }
22}
23
24impl Command for Chord {
25    fn normalize(&self) -> NormalizedCommand {
26        let serialized_string =
27            ron::ser::to_string_pretty(self, PrettyConfig::new().struct_names(true)).unwrap();
28        NormalizedCommand(serialized_string)
29    }
30
31    fn denormalize(generalized: &NormalizedCommand) -> Option<Box<Self>> {
32        ron::from_str(&generalized.0).ok()
33    }
34
35    fn execute(&self, worker: &mut Worker) -> Error {
36        worker.xwrap.grab_keys(&self.0);
37        worker.chord_ctx.keybinds = Some(self.0.clone());
38        Ok(())
39    }
40
41    fn get_name(&self) -> &'static str {
42        "Chord"
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use crate::config::{Command, Keybind, command::Reload};
49
50    use super::Chord;
51
52    #[test]
53    fn normalize_process() {
54        let command = Chord::new(vec![Keybind {
55            command: Reload::new().normalize(),
56            modifier: vec![],
57            key: String::new(),
58        }]);
59
60        let normalized = command.normalize();
61        let denormalized = Chord::denormalize(&normalized).unwrap();
62
63        assert_eq!(
64            Box::new(command.clone()),
65            denormalized,
66            "{command:?}, {denormalized:?}",
67        );
68    }
69}