1use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7
8use crate::binding::Action;
9
10#[derive(
16 Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
17)]
18#[expect(
19 clippy::struct_excessive_bools,
20 reason = "four independent modifier flags mirrored from the OS hook"
21)]
22pub struct KeyModifiers {
23 pub shift: bool,
25 pub control: bool,
27 pub option: bool,
29 pub command: bool,
31}
32
33impl KeyModifiers {
34 #[must_use]
36 pub fn is_empty(&self) -> bool {
37 !self.shift && !self.control && !self.option && !self.command
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
49pub struct KeyTrigger {
50 pub keycode: u16,
52 pub modifiers: KeyModifiers,
54}
55
56impl std::fmt::Display for KeyTrigger {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 let mut parts: Vec<&str> = Vec::new();
59 let m = &self.modifiers;
60 if m.shift {
61 parts.push("shift");
62 }
63 if m.control {
64 parts.push("control");
65 }
66 if m.option {
67 parts.push("option");
68 }
69 if m.command {
70 parts.push("command");
71 }
72 parts.push(keycode_to_name(self.keycode).ok_or(std::fmt::Error)?);
73 write!(f, "{}", parts.join("+"))
74 }
75}
76
77fn keycode_to_name(code: u16) -> Option<&'static str> {
80 Some(match code {
81 0x35 => "esc",
82 0x7A => "f1",
83 0x78 => "f2",
84 0x63 => "f3",
85 0x76 => "f4",
86 0x60 => "f5",
87 0x61 => "f6",
88 0x62 => "f7",
89 0x64 => "f8",
90 0x65 => "f9",
91 0x6D => "f10",
92 0x67 => "f11",
93 0x6F => "f12",
94 0x69 => "f13",
95 0x6B => "f14",
96 0x71 => "f15",
97 0x6A => "f16",
98 0x40 => "f17",
99 0x4F => "f18",
100 0x50 => "f19",
101 _ => return None,
102 })
103}
104
105impl Serialize for KeyTrigger {
107 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
108 s.collect_str(self)
109 }
110}
111impl<'de> Deserialize<'de> for KeyTrigger {
112 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
113 let s = String::deserialize(d)?;
114 s.parse().map_err(serde::de::Error::custom)
115 }
116}
117
118#[derive(Debug, Error)]
120#[error("invalid key trigger: {0}")]
121pub struct ParseTriggerError(pub String);
122
123impl std::str::FromStr for KeyTrigger {
124 type Err = ParseTriggerError;
125 fn from_str(s: &str) -> Result<Self, Self::Err> {
126 let mut mods = KeyModifiers::default();
127 let parts: Vec<&str> = s.split('+').map(str::trim).collect();
128 if parts.is_empty() || parts.iter().any(|p| p.is_empty()) {
129 return Err(ParseTriggerError("empty segment".into()));
130 }
131 let (mod_parts, key_part) = parts.split_at(parts.len() - 1);
133 for part in mod_parts {
134 match part.to_ascii_lowercase().as_str() {
135 "shift" => mods.shift = true,
136 "control" | "ctrl" => mods.control = true,
137 "option" | "alt" => mods.option = true,
138 "command" | "cmd" => mods.command = true,
139 other => return Err(ParseTriggerError(format!("unknown modifier '{other}'"))),
140 }
141 }
142 let keycode = match key_part[0].to_ascii_lowercase().as_str() {
143 "esc" => 0x35,
144 "f1" => 0x7A,
145 "f2" => 0x78,
146 "f3" => 0x63,
147 "f4" => 0x76,
148 "f5" => 0x60,
149 "f6" => 0x61,
150 "f7" => 0x62,
151 "f8" => 0x64,
152 "f9" => 0x65,
153 "f10" => 0x6D,
154 "f11" => 0x67,
155 "f12" => 0x6F,
156 "f13" => 0x69,
157 "f14" => 0x6B,
158 "f15" => 0x71,
159 "f16" => 0x6A,
160 "f17" => 0x40,
161 "f18" => 0x4F,
162 "f19" => 0x50,
163 other => return Err(ParseTriggerError(format!("unknown key '{other}'"))),
164 };
165 Ok(KeyTrigger {
166 keycode,
167 modifiers: mods,
168 })
169 }
170}
171
172#[derive(Debug, Clone, Default, Serialize, Deserialize)]
174#[serde(deny_unknown_fields)]
175pub struct KeyboardConfig {
176 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
178 pub bindings: BTreeMap<KeyTrigger, Action>,
179}