1use crate::{WidgetId, World};
2use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
3
4#[macro_export]
11macro_rules! keys {
12 ($($key:expr),+ $(,)?) => {
13 $crate::Keys(vec![$($key.into()),+])
14 };
15}
16
17pub type ActionFn = Box<dyn Fn(&mut World) + Send + Sync>;
18pub type AnyKeyFn = Box<dyn Fn(&mut World, &KeyBinding) + Send + Sync>;
19
20struct Binding {
21 key: KeyBinding,
22 id: WidgetId,
23 action: ActionFn,
24 name: &'static str,
25}
26
27struct AnyKeyHandler {
28 id: WidgetId,
29 handler: AnyKeyFn,
30}
31
32pub struct Keybindings {
47 bindings: Vec<Binding>,
48 any_key_handlers: Vec<AnyKeyHandler>,
49}
50
51impl Default for Keybindings {
52 fn default() -> Self {
53 Self::new()
54 }
55}
56
57impl Keybindings {
58 #[must_use]
59 pub fn new() -> Self {
60 Self {
61 bindings: Vec::new(),
62 any_key_handlers: Vec::new(),
63 }
64 }
65
66 pub fn bind(
67 &mut self,
68 id: WidgetId,
69 key: impl Into<KeyBinding>,
70 name: &'static str,
71 action: impl Fn(&mut World) + Send + Sync + 'static,
72 ) {
73 let key = key.into();
74 self.bindings.retain(|b| !(b.key == key && b.id == id));
75 self.bindings.push(Binding {
76 id,
77 key,
78 action: Box::new(action),
79 name,
80 });
81 }
82
83 pub fn bind_many(
85 &mut self,
86 id: WidgetId,
87 keys: impl Into<Keys>,
88 name: &'static str,
89 action: impl Fn(&mut World) + Send + Sync + Clone + 'static,
90 ) {
91 for key in keys.into().0 {
92 self.bind(id, key, name, action.clone());
93 }
94 }
95
96 pub fn bind_any(
99 &mut self,
100 id: WidgetId,
101 handler: impl Fn(&mut World, &KeyBinding) + Send + Sync + 'static,
102 ) {
103 self.any_key_handlers.push(AnyKeyHandler {
104 id,
105 handler: Box::new(handler),
106 });
107 }
108
109 pub fn handle(&self, key: &KeyBinding, world: &mut World, ids: &[WidgetId]) -> bool {
110 for binding in &self.bindings {
111 if binding.key != *key {
112 continue;
113 }
114
115 if ids.contains(&binding.id) {
116 (binding.action)(world);
117 return true;
118 }
119 }
120
121 for handler in &self.any_key_handlers {
122 if ids.contains(&handler.id) {
123 (handler.handler)(world, key);
124 return true;
125 }
126 }
127
128 false
129 }
130
131 pub fn unbind(&mut self, id: WidgetId) {
133 self.bindings.retain(|b| b.id != id);
134 }
135
136 #[must_use]
139 pub fn display_for(&self, ids: &[WidgetId]) -> Vec<DisplayInfo> {
140 use std::collections::HashMap;
141
142 let mut groups: HashMap<(WidgetId, &'static str), Vec<KeyBinding>> = HashMap::new();
143 let mut order: Vec<(WidgetId, &'static str)> = Vec::new();
144
145 for binding in &self.bindings {
146 if ids.contains(&binding.id) {
147 let key = (binding.id, binding.name);
148 if !groups.contains_key(&key) {
149 order.push(key);
150 }
151 groups.entry(key).or_default().push(binding.key);
152 }
153 }
154
155 order
156 .into_iter()
157 .map(|(id, name)| DisplayInfo {
158 keys: groups.remove(&(id, name)).unwrap_or_default(),
159 id,
160 name,
161 })
162 .collect()
163 }
164
165 #[must_use]
168 pub fn display_all(&self) -> Vec<DisplayInfo> {
169 use std::collections::HashMap;
170
171 let mut groups: HashMap<(WidgetId, &'static str), Vec<KeyBinding>> = HashMap::new();
172 let mut order: Vec<(WidgetId, &'static str)> = Vec::new();
173
174 for binding in &self.bindings {
175 let key = (binding.id, binding.name);
176 if !groups.contains_key(&key) {
177 order.push(key);
178 }
179 groups.entry(key).or_default().push(binding.key);
180 }
181
182 order
183 .into_iter()
184 .map(|(id, name)| DisplayInfo {
185 keys: groups.remove(&(id, name)).unwrap_or_default(),
186 id,
187 name,
188 })
189 .collect()
190 }
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213pub struct KeyBinding {
214 pub code: KeyCode,
215 pub modifiers: KeyModifiers,
216}
217
218impl KeyBinding {
219 #[must_use]
220 pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
221 Self { code, modifiers }
222 }
223
224 #[must_use]
225 pub fn key(code: KeyCode) -> Self {
226 Self::new(code, KeyModifiers::NONE)
227 }
228
229 #[must_use]
230 pub fn ctrl(c: char) -> Self {
231 Self::new(KeyCode::Char(c), KeyModifiers::CONTROL)
232 }
233
234 #[must_use]
235 pub fn alt(c: char) -> Self {
236 Self::new(KeyCode::Char(c), KeyModifiers::ALT)
237 }
238
239 #[must_use]
240 pub fn shift(c: char) -> Self {
241 Self::new(KeyCode::Char(c), KeyModifiers::SHIFT)
242 }
243
244 #[must_use]
251 pub fn display_compact(&self) -> String {
252 let mut parts = String::new();
253
254 if self.modifiers.contains(KeyModifiers::CONTROL) {
255 parts.push('⌃');
256 }
257 if self.modifiers.contains(KeyModifiers::ALT) {
258 parts.push('⌥');
259 }
260 if self.modifiers.contains(KeyModifiers::SHIFT) {
261 parts.push('⇧');
262 }
263
264 let key = match self.code {
265 KeyCode::Char(c) => {
266 if c == ' ' {
267 "Space".to_string()
268 } else {
269 c.to_ascii_lowercase().to_string()
270 }
271 }
272 KeyCode::Up => "↑".to_string(),
273 KeyCode::Down => "↓".to_string(),
274 KeyCode::Left => "←".to_string(),
275 KeyCode::Right => "→".to_string(),
276 KeyCode::Enter => "⏎".to_string(),
277 KeyCode::Esc => "Esc".to_string(),
278 KeyCode::BackTab | KeyCode::Tab => "Tab".to_string(),
279 KeyCode::Backspace => "⌫".to_string(),
280 KeyCode::Delete => "Del".to_string(),
281 KeyCode::Home => "Home".to_string(),
282 KeyCode::End => "End".to_string(),
283 KeyCode::PageUp => "PgUp".to_string(),
284 KeyCode::PageDown => "PgDn".to_string(),
285 KeyCode::F(n) => format!("F{n}"),
286 _ => format!("{:?}", self.code),
287 };
288
289 parts.push_str(&key);
290 parts
291 }
292
293 #[must_use]
294 pub fn display(&self) -> String {
295 let mut parts = Vec::new();
296
297 if self.modifiers.contains(KeyModifiers::CONTROL) {
298 parts.push("Ctrl");
299 }
300 if self.modifiers.contains(KeyModifiers::ALT) {
301 parts.push("Alt");
302 }
303 if self.modifiers.contains(KeyModifiers::SHIFT) {
304 parts.push("Shift");
305 }
306
307 let key = match self.code {
308 KeyCode::Char(c) => {
309 if c == ' ' {
310 return "Space".to_string();
311 }
312 c.to_ascii_lowercase().to_string()
313 }
314 KeyCode::Up => "↑".to_string(),
315 KeyCode::Down => "↓".to_string(),
316 KeyCode::Left => "←".to_string(),
317 KeyCode::Right => "→".to_string(),
318 KeyCode::Enter => "Enter".to_string(),
319 KeyCode::Esc => "Esc".to_string(),
320 KeyCode::Tab => "Tab".to_string(),
321 KeyCode::BackTab => "Shift+Tab".to_string(),
322 KeyCode::Backspace => "Backspace".to_string(),
323 KeyCode::Delete => "Delete".to_string(),
324 KeyCode::Home => "Home".to_string(),
325 KeyCode::End => "End".to_string(),
326 KeyCode::PageUp => "PageUp".to_string(),
327 KeyCode::PageDown => "PageDown".to_string(),
328 KeyCode::F(n) => format!("F{n}"),
329 _ => format!("{:?}", self.code),
330 };
331
332 if parts.is_empty() {
333 key
334 } else {
335 parts.push(&key);
336 parts.join("+")
337 }
338 }
339}
340
341impl From<&KeyEvent> for KeyBinding {
342 fn from(event: &KeyEvent) -> Self {
343 Self::new(event.code, event.modifiers)
344 }
345}
346
347impl From<KeyCode> for KeyBinding {
348 fn from(code: KeyCode) -> Self {
349 Self::key(code)
350 }
351}
352
353impl From<char> for KeyBinding {
354 fn from(c: char) -> Self {
355 if c.is_ascii_uppercase() {
356 Self::new(KeyCode::Char(c), KeyModifiers::SHIFT)
357 } else {
358 Self::key(KeyCode::Char(c))
359 }
360 }
361}
362
363#[derive(Debug, Clone)]
376pub struct Keys(pub Vec<KeyBinding>);
377
378impl From<Vec<KeyBinding>> for Keys {
379 fn from(keys: Vec<KeyBinding>) -> Self {
380 Self(keys)
381 }
382}
383
384impl std::fmt::Display for KeyBinding {
385 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386 write!(f, "{}", self.display())
387 }
388}
389
390#[derive(Debug)]
395pub struct DisplayInfo {
396 pub keys: Vec<KeyBinding>,
397 pub id: WidgetId,
398 pub name: &'static str,
399}
400
401impl DisplayInfo {
402 #[must_use]
410 pub fn keys_display(&self) -> String {
411 self.keys_display_with(KeyBinding::display)
412 }
413
414 #[must_use]
422 pub fn keys_display_compact(&self) -> String {
423 self.keys_display_with(KeyBinding::display_compact)
424 }
425
426 #[must_use]
437 pub fn keys_display_with(&self, formatter: impl Fn(&KeyBinding) -> String) -> String {
438 self.keys
439 .iter()
440 .map(formatter)
441 .collect::<Vec<_>>()
442 .join(", ")
443 }
444}