cnf 0.6.0

Distribution-agnostic 'command not found'-handler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: (C) 2023 Andreas Hartmann <hartan@7x.de>
// This file is part of cnf, available at <https://gitlab.com/hartang/rust/cnf>

//! # Application keybindings handler
//!
//! Provides abstraction over the underlying key-event handler and implements a stateful
//! [`Widget`](ratatui::widgets::StatefulWidget) for displaying keybindings in the main UI.
//!
//! # Configuring keybindings
//!
//! The [configuration file](crate::config::Config) has a `keybindings` section which allows
//! defining the [application keybindings](AppKeybinds). The configuration consists of a pair of
//! pre-defined action, and a keybinding that triggers it.
//!
//! Keybindings are parsed from a user-supplied string. The following rules apply to keybindings:
//!
//! - Each action can be bound only once
//! - A keybinding *must* contain a non-modifier key (e.g. a char/sign/digit/...)
//! - Capital keys/characters must add the [shift modifier](KeyModifier::Shift)
//! - Modifier keys in a keybinding must be unique (no repetitions)
//! - Modifiers and key codes are separated by a single `+` char
//! - Whitespace are ignored (you can perform arbitrary indentation if you like)
//!
//! Note that while the application offers a lot of keybinding combinations, there is a high chance
//! that it will not recognize all keybindings correctly. This is not a shortcoming of the
//! application, but has a lot of reasons: Platform-specific differences, keyboard layout, terminal
//! emulator application, etc...
//!
//! To find out what key maps to which config values, check out the source-code of
//! [`KeyCode::from_str()`] and [`KeyModifier::from_str()`].
//!
//! Here are some examples of what this looks like in the configuration:
//!
//! ```yaml
//! keybindings:
//!   # This is the default keybinding
//!   select_up:   "k"
//!   # You can use modifier keys, just specify them as you'd write them down
//!   select_down: "ctrl + j"
//!   # The order of keys doesn't matter
//!   collapse:    "h + ctrl"
//!   # Capital characters must specifiy the shift modifier!
//!   expand:      "shift + l"
//!   # The casing is irrelevant
//!   install:     "Ctrl + SHiFT + I"
//!   # Whitespace are ignored
//!   execute:     "       e      "
//! ```
mod backend {
    pub(crate) use crossterm::event::{KeyCode, KeyModifiers as KeyModifier};
}
use ratatui::{
    style::{Color, Style},
    text::Span,
};
use serde_derive::{Deserialize, Serialize};

use std::{fmt, rc::Rc, str::FromStr};

/// App-wide keybindings definition.
///
/// Refer to the [module-level documentation](super::keybinds) for further information.
#[derive(Debug, Serialize, Deserialize)]
pub struct AppKeybinds {
    /// Navigate one entry up in the list
    pub select_up: KeyBinding,
    /// Navigate one entry down in the list
    pub select_down: KeyBinding,
    /// Collapse node under cursor
    pub collapse: KeyBinding,
    /// Expand node under cursor
    pub expand: KeyBinding,
    /// Install selection (if possible)
    pub install: KeyBinding,
    /// Execute selection (if possible)
    pub execute: KeyBinding,
    /// Crete command alias
    pub add_alias: KeyBinding,
    /// Quit the application
    pub quit: KeyBinding,
}

impl Default for AppKeybinds {
    fn default() -> Self {
        AppKeybinds {
            select_up: "k".parse().unwrap(),
            select_down: "j".parse().unwrap(),
            collapse: "h".parse().unwrap(),
            expand: "l".parse().unwrap(),
            install: "i".parse().unwrap(),
            execute: "e".parse().unwrap(),
            add_alias: "a".parse().unwrap(),
            quit: "q".parse().unwrap(),
        }
    }
}

impl ratatui::widgets::StatefulWidget for &mut &'static AppKeybinds {
    type State = Option<(Rc<cnf_lib::Query>, usize)>;

    fn render(
        self,
        area: ratatui::layout::Rect,
        buf: &mut ratatui::buffer::Buffer,
        state: &mut Self::State,
    ) {
        let key_style = Style::default().fg(Color::Red);
        let separator_style = Style::default().add_modifier(ratatui::style::Modifier::BOLD);

        let mut span_vec = vec![
            Span::styled(self.quit.to_string(), key_style),
            Span::raw(" quit"),
            Span::styled(" | ", separator_style),
            Span::styled(self.select_down.to_string(), key_style),
            Span::raw("/"),
            Span::styled(self.select_up.to_string(), key_style),
            Span::raw(" select down/up"),
            Span::styled(" | ", separator_style),
            Span::styled(self.collapse.to_string(), key_style),
            Span::raw("/"),
            Span::styled(self.expand.to_string(), key_style),
            Span::raw(" collapse/expand"),
        ];
        if let Some((query, index)) = state {
            if let Some(candidate) = query.results.as_ref().unwrap().get(*index)
                && candidate.actions.install.is_some()
            {
                span_vec.append(&mut vec![
                    Span::styled(" | ", separator_style),
                    Span::styled(self.install.to_string(), key_style),
                    Span::raw(" install"),
                ]);
            };
            span_vec.append(&mut vec![
                Span::styled(" | ", separator_style),
                Span::styled(self.execute.to_string(), key_style),
                Span::raw(" execute"),
            ]);
            span_vec.append(&mut vec![
                Span::styled(" | ", separator_style),
                Span::styled(self.add_alias.to_string(), key_style),
                Span::raw(" add alias"),
            ]);
        };
        let spans = ratatui::text::Spans::from(span_vec);
        let text = ratatui::widgets::Paragraph::new(ratatui::text::Text::from(spans))
            .alignment(ratatui::layout::Alignment::Center)
            .wrap(ratatui::widgets::Wrap { trim: true });
        use ratatui::widgets::Widget;
        text.render(area, buf)
    }
}

/// Custom key code wrapper.
///
/// Refer to the [module-level documentation](super::keybinds) for further information.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyCode {
    /// A regular character key (a-z, ...).
    Char(u8),
    /// A function key (F1, F2, ...)
    Function(u8),
    /// The space ' ' key.
    Space,
    /// The enter key.
    Enter,
    /// The delete 'Del' key.
    Delete,
    /// The left arrow '←' key.
    ArrowLeft,
    /// The right arrow '→' key.
    ArrowRight,
    /// The down arrow '↓' key.
    ArrowDown,
    /// The up arrow '↑' key.
    ArrowUp,
    /// The home 'Home' key.
    Home,
    /// The end 'End' key.
    End,
    /// The page up 'PageUp' key.
    PageUp,
    /// The page down 'PageDn' key.
    PageDown,
    /// The tab '⭾' key.
    Tab,
    /// The escape 'Esc' key.
    Escape,
    /// The plus '+' key.
    // To allow literal '+' as keybindings "glue"
    Plus,
    /// The plus '-' key.
    Minus,
}

/// Convert [`KeyCode`] to the [`crossterm`] equivalent.
impl From<KeyCode> for backend::KeyCode {
    fn from(value: KeyCode) -> Self {
        use KeyCode as Cnf;
        use backend::KeyCode as Backend;

        match value {
            Cnf::Char(val) => Backend::Char(val as char),
            Cnf::Function(val) => Backend::F(val),
            Cnf::Space => Backend::Char(' '),
            Cnf::Enter => Backend::Enter,
            Cnf::Delete => Backend::Delete,
            Cnf::ArrowLeft => Backend::Left,
            Cnf::ArrowDown => Backend::Down,
            Cnf::ArrowUp => Backend::Up,
            Cnf::ArrowRight => Backend::Right,
            Cnf::Home => Backend::Home,
            Cnf::End => Backend::End,
            Cnf::PageUp => Backend::PageUp,
            Cnf::PageDown => Backend::PageDown,
            Cnf::Tab => Backend::Tab,
            Cnf::Escape => Backend::Esc,
            Cnf::Plus => Backend::Char('+'),
            Cnf::Minus => Backend::Char('-'),
        }
    }
}

/// Format [`KeyCode`] for display in the UI (without colors).
impl fmt::Display for KeyCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Char(val) => write!(f, "{}", *val as char),
            Self::Function(val) => write!(f, "F{}", val),
            Self::Space => write!(f, "space"),
            Self::Enter => write!(f, "enter"),
            Self::Delete => write!(f, "delete"),
            Self::ArrowLeft => write!(f, ""),
            Self::ArrowDown => write!(f, ""),
            Self::ArrowUp => write!(f, ""),
            Self::ArrowRight => write!(f, ""),
            Self::Home => write!(f, "home"),
            Self::End => write!(f, "end"),
            Self::PageUp => write!(f, "pageup"),
            Self::PageDown => write!(f, "pagedown"),
            Self::Tab => write!(f, "tab"),
            Self::Escape => write!(f, "esc"),
            Self::Plus => write!(f, "+"),
            Self::Minus => write!(f, "-"),
        }
    }
}

/// Parse [`KeyCode`] from user input.
impl FromStr for KeyCode {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.to_ascii_lowercase();
        let s = s.trim();

        match s {
            "space" => Ok(Self::Space),
            "enter" => Ok(Self::Enter),
            "del" | "delete" => Ok(Self::Delete),
            "" | "left" | "arrowleft" => Ok(Self::ArrowLeft),
            "" | "down" | "arrowdown" => Ok(Self::ArrowDown),
            "" | "up" | "arrowup" => Ok(Self::ArrowUp),
            "" | "right" | "arrowright" => Ok(Self::ArrowRight),
            "home" | "pos1" => Ok(Self::Home),
            "end" => Ok(Self::End),
            "pagedown" | "pgdown" | "pgdn" => Ok(Self::PageDown),
            "pageup" | "pgup" => Ok(Self::PageUp),
            "tab" => Ok(Self::Tab),
            "esc" | "escape" => Ok(Self::Escape),
            "plus" => Ok(Self::Plus),
            "minus" => Ok(Self::Minus),
            "f1" | "f2" | "f3" | "f4" | "f5" | "f6" | "f7" | "f8" | "f9" | "f10" | "f11"
            | "f12" => {
                let num = (s[1..]).parse::<u8>().unwrap();
                Ok(Self::Function(num))
            }
            _ => {
                if s.is_ascii() && s.len() == 1 {
                    let char = s.chars().next().expect("tried parsing from empty string");
                    Ok(Self::Char(char as u8))
                } else {
                    anyhow::bail!("failed to parse '{}' into a valid key code", s);
                }
            }
        }
    }
}

/// Custom key modifier wrapper.
///
/// **Important note**: The `Shift` modifier is currently an explicit modifier key and must be
/// specified if capitalized letters should be used in the application.
///
/// Refer to the [module-level documentation](super::keybinds) for further information.
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub enum KeyModifier {
    /// The shift modifier.
    Shift,
    /// The control 'Ctrl' modifier.
    Control,
    /// The alt 'Alt' modifier.
    Alt,
    /// The super modifier.
    Super,
    /// The meta modifier.
    Meta,
}

/// Convert [`KeyModifier`] into the [`crossterm`] equivalent.
impl From<KeyModifier> for backend::KeyModifier {
    fn from(value: KeyModifier) -> Self {
        use KeyModifier as Cnf;
        use backend::KeyModifier as Backend;

        match value {
            Cnf::Shift => Backend::SHIFT,
            Cnf::Control => Backend::CONTROL,
            Cnf::Alt => Backend::ALT,
            Cnf::Super => Backend::SUPER,
            Cnf::Meta => Backend::META,
        }
    }
}

/// Format [`KeyModifier`] for display in the UI (without colors).
impl fmt::Display for KeyModifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let output = match self {
            Self::Shift => "shift",
            Self::Control => "ctrl",
            Self::Alt => "alt",
            Self::Super => "super",
            Self::Meta => "meta",
        };
        write!(f, "{}", output)
    }
}

/// Parse [`KeyModifier`] from user input.
impl FromStr for KeyModifier {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !s.is_ascii() {
            anyhow::bail!("cannot parse modifier keys from non-ascii input");
        }

        let s = s.to_ascii_lowercase();
        let s = s.trim();
        match s {
            "shift" => Ok(Self::Shift),
            "ctrl" | "control" => Ok(Self::Control),
            "alt" => Ok(Self::Alt),
            "super" => Ok(Self::Super),
            "meta" => Ok(Self::Meta),
            _ => anyhow::bail!("failed to parse '{}' into a valid modifier key", s),
        }
    }
}

/// Custom keybinding container type.
///
/// Manages a [key code](KeyCode) and multiple optional [modifiers](KeyModifier) in a single
/// structure. This is the main type for configuring custom application keybindings.
///
/// Refer to the [module-level documentation](super::keybinds) for further information.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[doc(hidden)]
#[serde(try_from = "String", into = "String")]
pub struct KeyBinding {
    key: KeyCode,
    modifiers: Vec<KeyModifier>,
}

impl PartialEq<crossterm::event::KeyEvent> for KeyBinding {
    fn eq(&self, other: &crossterm::event::KeyEvent) -> bool {
        let mut modifiers = backend::KeyModifier::NONE;
        for m in self.modifiers.clone() {
            modifiers |= m.into();
        }

        let keycode = if self.modifiers.contains(&KeyModifier::Shift) {
            match self.key {
                KeyCode::Char(val) => KeyCode::Char(val.to_ascii_uppercase()),
                _ => self.key,
            }
        } else {
            self.key
        };
        (backend::KeyCode::from(keycode) == other.code) && (modifiers == other.modifiers)
    }
}

impl From<KeyBinding> for crossterm::event::KeyEvent {
    fn from(value: KeyBinding) -> Self {
        let mut modifiers = backend::KeyModifier::NONE;
        for m in value.modifiers {
            modifiers |= m.into();
        }

        crossterm::event::KeyEvent::new_with_kind(
            value.key.into(),
            modifiers,
            crossterm::event::KeyEventKind::Press,
        )
    }
}

impl fmt::Display for KeyBinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut modifiers = self.modifiers.clone();
        modifiers.sort();
        modifiers.dedup();

        // special handling for capital letters
        let key = if let KeyCode::Char(char) = self.key {
            if self.modifiers.contains(&KeyModifier::Shift) && char.is_ascii_lowercase() {
                modifiers.retain(|elem| elem != &KeyModifier::Shift);
                (char as char).to_ascii_uppercase().to_string()
            } else {
                self.key.to_string()
            }
        } else {
            self.key.to_string()
        };

        for m in modifiers {
            write!(f, "{}+", m)?;
        }
        write!(f, "{}", key)
    }
}

impl From<KeyBinding> for String {
    fn from(value: KeyBinding) -> Self {
        value.to_string()
    }
}

impl FromStr for KeyBinding {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut key: Option<KeyCode> = None;
        let mut modifiers: Vec<KeyModifier> = vec![];

        for pat in s.split('+') {
            if let Ok(current) = KeyCode::from_str(pat) {
                if let Some(previous) = key {
                    anyhow::bail!(
                        "found multiple keys in binding: previous: '{}', current: '{}'",
                        previous,
                        current
                    );
                } else {
                    key.replace(current);
                }
                continue;
            }

            if let Ok(modkey) = KeyModifier::from_str(pat) {
                if modifiers.contains(&modkey) {
                    anyhow::bail!("modifier key '{}' exists multiple times in binding", modkey);
                } else {
                    modifiers.push(modkey);
                }
                continue;
            }

            anyhow::bail!(
                "invalid input '{}' is not recognized as bare key or modifier",
                pat
            );
        }

        if let Some(key) = key {
            modifiers.sort();
            Ok(KeyBinding { key, modifiers })
        } else {
            anyhow::bail!("valid key bindings must contain exactly one non-modifier key");
        }
    }
}

impl TryFrom<String> for KeyBinding {
    type Error = anyhow::Error;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::from_str(&value[..])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use KeyCode as Key;
    use KeyModifier as Mod;

    /// Create a new keybinding.
    macro_rules! bind {
        ( $string:expr ) => {
            KeyBinding::from_str($string)
        };
    }

    mod assert {
        /// Assert that the given key is contained inside the binding.
        #[macro_export]
        macro_rules! key {
            ( $bind:ident, $key:expr ) => {
                assert_eq!($bind.key, $key);
            };
        }
        pub(super) use key;

        /// Assert that the bindings modifiers contain the given modifier.
        #[macro_export]
        macro_rules! mods {
            ( $bind:ident, $mod:expr ) => {
                assert!($bind.modifiers.contains(&$mod));
            };
        }
        pub(super) use mods;

        /// Assert that the binding has exactly this many modifiers.
        #[macro_export]
        macro_rules! num_mods {
            ( $bind:ident, $amount:expr ) => {
                assert_eq!($bind.modifiers.len(), $amount);
            };
        }
        pub(super) use num_mods;

        /// Assert that the given [`Result`] is an [`Err`] variant.
        #[macro_export]
        macro_rules! err {
            ( $result:expr ) => {
                assert!($result.is_err());
            };
        }
        pub(super) use err;
    }

    #[test]
    fn ascii_is_char() {
        let bind = bind!("a").unwrap();
        assert_eq!(bind.to_string(), "a".to_string());
    }

    #[test]
    fn ascii_uppercase_is_ignored() {
        let bind = bind!("A").unwrap();
        assert::key!(bind, Key::Char(b'a'));
        assert::num_mods!(bind, 0);
    }

    #[test]
    fn deny_bogus() {
        let bind = bind!("foo");
        assert::err!(bind);
    }

    #[test]
    fn deny_modifiers_only() {
        let bind = bind!("ctrl");
        assert::err!(bind);
    }

    #[test]
    fn char_with_one_modifier() {
        let bind = bind!("shift + a").unwrap();
        assert::key!(bind, Key::Char(b'a'));
        assert::num_mods!(bind, 1);
        assert::mods!(bind, Mod::Shift);
    }

    #[test]
    fn char_with_three_modifiers() {
        let bind = bind!("alt + shift + ctrl + a").unwrap();
        assert::key!(bind, Key::Char(b'a'));
        assert::mods!(bind, Mod::Shift);
        assert::mods!(bind, Mod::Alt);
        assert::mods!(bind, Mod::Control);
    }

    #[test]
    fn char_with_modifier_doubled() {
        let bind = bind!("alt + alt + a");
        assert::err!(bind);
    }

    #[test]
    fn multiple_chars() {
        let bind = bind!("a + b");
        assert::err!(bind);
    }

    #[test]
    fn whitespace_dont_matter() {
        let bind = bind!("          a         ").unwrap();
        assert::key!(bind, Key::Char(b'a'));
        assert::num_mods!(bind, 0);
    }

    #[test]
    fn leading_stray_plus() {
        let bind = bind!("+ a");
        assert::err!(bind);
    }

    #[test]
    fn trailing_stray_plus() {
        let bind = bind!("a +");
        assert::err!(bind);
    }

    #[test]
    fn single_plus_char() {
        let bind = bind!("+");
        assert::err!(bind);
    }

    #[test]
    fn order_is_irrelevant() {
        let bind = bind!("a + ctrl").unwrap();
        assert::key!(bind, Key::Char(b'a'));
        assert::mods!(bind, Mod::Control);
        assert::num_mods!(bind, 1);
    }

    #[test]
    fn casing_is_irrelevant() {
        let bind = bind!("Ctrl + SHiFT + A").unwrap();
        assert::key!(bind, Key::Char(b'a'));
        assert::mods!(bind, Mod::Control);
        assert::mods!(bind, Mod::Shift);
        assert::num_mods!(bind, 2);
    }

    #[test]
    fn upper_char_requires_shift() {
        let bind = bind!("shift + a").unwrap();
        assert_eq!(bind.to_string(), "A".to_string());
        assert::key!(bind, Key::Char(b'a'));
        assert::mods!(bind, Mod::Shift);
        assert::num_mods!(bind, 1);
    }
}