rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! Named actions and the key chords that trigger them.
//!
//! Every app-level shortcut is an `Action` with default chords; the `[keys]` table in
//! `config.toml` can rebind any of them: `split_right = "ctrl+alt+right"`, or a list of chords
//! (`paste = ["ctrl+v", "shift+insert"]`). A chord is modifiers joined with `+`, then a key:
//! a character (`f`, `=`, `,`) or a name (`left`, `pageup`, `enter`, `f5`, ...).

use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Serialize};
use winit::event::KeyEvent;
use winit::keyboard::{Key, ModifiersState, NamedKey};
use winit::platform::modifier_supplement::KeyEventExtModifierSupplement;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Action {
    SplitLeft,
    SplitRight,
    SplitUp,
    SplitDown,
    FocusLeft,
    FocusRight,
    FocusUp,
    FocusDown,
    ResizeLeft,
    ResizeRight,
    ResizeUp,
    ResizeDown,
    ClosePane,
    Zoom,
    Copy,
    /// Copy if something is selected, otherwise pass Ctrl+C through to the program.
    SmartCopy,
    Paste,
    SelectAll,
    Find,
    CopyOutput,
    OpenFolder,
    FontBigger,
    FontSmaller,
    FontReset,
    ScrollPageUp,
    ScrollPageDown,
    ScrollTop,
    ScrollBottom,
    Palette,
    Settings,
    Review,
    Git,
    T3,
    Chat,
}

struct Info {
    action: Action,
    id: &'static str,
    label: &'static str,
    keys: &'static [&'static str],
}

macro_rules! info {
    ($action:ident, $id:literal, $label:literal, [$($key:literal),*]) => {
        Info { action: Action::$action, id: $id, label: $label, keys: &[$($key),*] }
    };
}

const ACTIONS: &[Info] = &[
    info!(SplitRight, "split_right", "Split right", ["ctrl+shift+right"]),
    info!(SplitLeft, "split_left", "Split left", ["ctrl+shift+left"]),
    info!(SplitDown, "split_down", "Split down", ["ctrl+shift+down"]),
    info!(SplitUp, "split_up", "Split up", ["ctrl+shift+up"]),
    info!(FocusLeft, "focus_left", "Focus the pane to the left", ["alt+left"]),
    info!(FocusRight, "focus_right", "Focus the pane to the right", ["alt+right"]),
    info!(FocusUp, "focus_up", "Focus the pane above", ["alt+up"]),
    info!(FocusDown, "focus_down", "Focus the pane below", ["alt+down"]),
    info!(ResizeLeft, "resize_left", "Move the divider left", ["alt+shift+left"]),
    info!(ResizeRight, "resize_right", "Move the divider right", ["alt+shift+right"]),
    info!(ResizeUp, "resize_up", "Move the divider up", ["alt+shift+up"]),
    info!(ResizeDown, "resize_down", "Move the divider down", ["alt+shift+down"]),
    info!(ClosePane, "close_pane", "Close the pane", ["ctrl+shift+w"]),
    info!(Zoom, "zoom", "Zoom the pane", ["ctrl+shift+z"]),
    info!(Copy, "copy", "Copy the selection", ["ctrl+shift+c"]),
    info!(SmartCopy, "copy_or_interrupt", "Copy, or interrupt when nothing is selected", ["ctrl+c"]),
    info!(Paste, "paste", "Paste", ["ctrl+v", "ctrl+shift+v", "shift+insert"]),
    info!(SelectAll, "select_all", "Select the command line", ["ctrl+a"]),
    info!(Find, "find", "Find in the scrollback", ["ctrl+shift+f"]),
    info!(CopyOutput, "copy_output", "Copy the last command's output", ["ctrl+shift+o"]),
    info!(OpenFolder, "open_folder", "Open the folder in Explorer", ["ctrl+shift+e"]),
    info!(FontBigger, "font_bigger", "Bigger text", ["ctrl+=", "ctrl++"]),
    info!(FontSmaller, "font_smaller", "Smaller text", ["ctrl+-"]),
    info!(FontReset, "font_reset", "Reset the text size", ["ctrl+0"]),
    info!(ScrollPageUp, "scroll_page_up", "Scroll a page up", ["shift+pageup"]),
    info!(ScrollPageDown, "scroll_page_down", "Scroll a page down", ["shift+pagedown"]),
    info!(ScrollTop, "scroll_top", "Scroll to the top", ["shift+home"]),
    info!(ScrollBottom, "scroll_bottom", "Scroll to the bottom", ["shift+end"]),
    info!(Palette, "palette", "Command palette", ["ctrl+shift+p"]),
    info!(Settings, "settings", "Settings", ["ctrl+,"]),
    info!(Review, "review", "Review changes", ["ctrl+shift+r"]),
    info!(Git, "git", "Git workspace", ["ctrl+shift+b"]),
    info!(T3, "t3", "Switch between T3 Code and the terminal", ["ctrl+shift+t"]),
    info!(Chat, "chat", "Switch between the do conversation and the terminal", ["ctrl+shift+a"]),
];

impl Action {
    pub fn all() -> impl Iterator<Item = Action> {
        ACTIONS.iter().map(|i| i.action)
    }

    fn info(self) -> &'static Info {
        ACTIONS.iter().find(|i| i.action == self).expect("every action is listed")
    }

    /// The name used in `config.toml`.
    pub fn id(self) -> &'static str {
        self.info().id
    }

    pub fn label(self) -> &'static str {
        self.info().label
    }

    pub fn defaults(self) -> &'static [&'static str] {
        self.info().keys
    }

    pub fn from_id(id: &str) -> Option<Action> {
        ACTIONS.iter().find(|i| i.id == id).map(|i| i.action)
    }
}

/// One or more chords for an action, as written in `config.toml`.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum KeyList {
    One(String),
    Many(Vec<String>),
}

impl KeyList {
    pub fn chords(&self) -> Vec<&str> {
        match self {
            KeyList::One(s) => vec![s.as_str()],
            KeyList::Many(v) => v.iter().map(String::as_str).collect(),
        }
    }
}

/// Key names accepted besides single characters.
const NAMED: &[&str] = &[
    "left", "right", "up", "down", "pageup", "pagedown", "home", "end", "insert", "delete", "tab", "enter", "escape",
    "space", "backspace", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
];

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Chord {
    pub ctrl: bool,
    pub shift: bool,
    pub alt: bool,
    /// A single lowercase character, or one of `NAMED`.
    pub key: String,
}

impl Chord {
    pub fn parse(text: &str) -> Option<Chord> {
        let text = text.trim().to_lowercase();
        // `ctrl++` is Ctrl and the + key; a single trailing + is a mistake.
        let (mods, key) = if text == "+" {
            ("", "+".to_string())
        } else if let Some(head) = text.strip_suffix("++") {
            (head, "+".to_string())
        } else if text.ends_with('+') {
            return None;
        } else {
            match text.rsplit_once('+') {
                Some((mods, key)) => (mods, key.trim().to_string()),
                None => ("", text.clone()),
            }
        };
        let key = match key.as_str() {
            "esc" => "escape".to_string(),
            "return" => "enter".to_string(),
            "pgup" => "pageup".to_string(),
            "pgdn" => "pagedown".to_string(),
            "del" => "delete".to_string(),
            "ins" => "insert".to_string(),
            "plus" => "+".to_string(),
            "comma" => ",".to_string(),
            "minus" => "-".to_string(),
            k if k.starts_with("arrow") => k["arrow".len()..].to_string(),
            k => k.to_string(),
        };
        if key.chars().count() != 1 && !NAMED.contains(&key.as_str()) {
            return None;
        }
        let mut chord = Chord { ctrl: false, shift: false, alt: false, key };
        for m in mods.split('+').map(str::trim).filter(|m| !m.is_empty()) {
            match m {
                "ctrl" | "control" => chord.ctrl = true,
                "shift" => chord.shift = true,
                "alt" | "option" => chord.alt = true,
                _ => return None,
            }
        }
        Some(chord)
    }

    /// The chord for a key press, if it is one we can name.
    pub fn from_event(event: &KeyEvent, mods: ModifiersState) -> Option<Chord> {
        let key = match &event.logical_key {
            Key::Named(n) => match n {
                NamedKey::ArrowLeft => "left",
                NamedKey::ArrowRight => "right",
                NamedKey::ArrowUp => "up",
                NamedKey::ArrowDown => "down",
                NamedKey::PageUp => "pageup",
                NamedKey::PageDown => "pagedown",
                NamedKey::Home => "home",
                NamedKey::End => "end",
                NamedKey::Insert => "insert",
                NamedKey::Delete => "delete",
                NamedKey::Tab => "tab",
                NamedKey::Enter => "enter",
                NamedKey::Escape => "escape",
                NamedKey::Space => "space",
                NamedKey::Backspace => "backspace",
                NamedKey::F1 => "f1",
                NamedKey::F2 => "f2",
                NamedKey::F3 => "f3",
                NamedKey::F4 => "f4",
                NamedKey::F5 => "f5",
                NamedKey::F6 => "f6",
                NamedKey::F7 => "f7",
                NamedKey::F8 => "f8",
                NamedKey::F9 => "f9",
                NamedKey::F10 => "f10",
                NamedKey::F11 => "f11",
                NamedKey::F12 => "f12",
                _ => return None,
            }
            .to_string(),
            // The key without Shift, so Ctrl+Shift+= is "=" and not "+".
            Key::Character(_) => match event.key_without_modifiers() {
                Key::Character(c) if c.chars().count() == 1 => c.to_lowercase(),
                _ => return None,
            },
            _ => return None,
        };
        Some(Chord { ctrl: mods.control_key(), shift: mods.shift_key(), alt: mods.alt_key(), key })
    }

    /// The text written in `config.toml`: `ctrl+shift+f`.
    pub fn to_config(&self) -> String {
        let mut parts = Vec::new();
        if self.ctrl {
            parts.push("ctrl");
        }
        if self.alt {
            parts.push("alt");
        }
        if self.shift {
            parts.push("shift");
        }
        parts.push(&self.key);
        parts.join("+")
    }

    /// For display: `Ctrl+Shift+F`, `Alt+PageUp`.
    pub fn pretty(&self) -> String {
        let key = match self.key.as_str() {
            "pageup" => "PageUp".to_string(),
            "pagedown" => "PageDown".to_string(),
            k if k.chars().count() == 1 => k.to_uppercase(),
            k => {
                let mut c = k.chars();
                c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
            }
        };
        let mut parts = Vec::new();
        if self.ctrl {
            parts.push("Ctrl".to_string());
        }
        if self.alt {
            parts.push("Alt".to_string());
        }
        if self.shift {
            parts.push("Shift".to_string());
        }
        parts.push(key);
        parts.join("+")
    }
}

/// Which action each chord triggers.
#[derive(Clone, Debug, Default)]
pub struct Keymap {
    map: HashMap<Chord, Action>,
}

impl Keymap {
    /// The defaults, with the user's `[keys]` on top. Rebinding an action replaces all its
    /// default chords, and a chord given to one action is taken away from any other.
    /// Returns what could not be understood, to show the user.
    pub fn build(overrides: &BTreeMap<String, KeyList>) -> (Keymap, Vec<String>) {
        let mut problems = Vec::new();
        let mut bindings: Vec<(Action, Vec<Chord>)> = Vec::new();
        let mut custom: Vec<(Action, Vec<Chord>)> = Vec::new();
        for (id, keys) in overrides {
            let Some(action) = Action::from_id(id) else {
                problems.push(format!("unknown action '{id}' in [keys]"));
                continue;
            };
            let mut chords = Vec::new();
            for text in keys.chords() {
                match Chord::parse(text) {
                    Some(c) => chords.push(c),
                    None => problems.push(format!("can't read the key '{text}' for {id}")),
                }
            }
            custom.push((action, chords));
        }
        for action in Action::all() {
            if custom.iter().any(|(a, _)| *a == action) {
                continue;
            }
            bindings.push((action, action.defaults().iter().filter_map(|k| Chord::parse(k)).collect()));
        }
        let mut map = HashMap::new();
        for (action, chords) in bindings {
            for chord in chords {
                map.insert(chord, action);
            }
        }
        // The user's chords go last, so they win any clash.
        for (action, chords) in custom {
            for chord in chords {
                map.insert(chord, action);
            }
        }
        (Keymap { map }, problems)
    }

    pub fn get(&self, chord: &Chord) -> Option<Action> {
        self.map.get(chord).copied()
    }

    /// The chords for an action, in a stable order.
    pub fn chords(&self, action: Action) -> Vec<Chord> {
        let mut chords: Vec<Chord> = self.map.iter().filter(|(_, a)| **a == action).map(|(c, _)| c.clone()).collect();
        chords.sort_by_key(Chord::to_config);
        chords
    }

    /// `Ctrl+Shift+F`, or several chords separated by " / ".
    pub fn describe(&self, action: Action) -> String {
        self.chords(action).iter().map(Chord::pretty).collect::<Vec<_>>().join(" / ")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn chord(s: &str) -> Chord {
        Chord::parse(s).unwrap_or_else(|| panic!("{s} should parse"))
    }

    #[test]
    fn chords_parse_and_print() {
        let c = chord("Ctrl+Shift+F");
        assert_eq!((c.ctrl, c.shift, c.alt, c.key.as_str()), (true, true, false, "f"));
        assert_eq!(c.to_config(), "ctrl+shift+f");
        assert_eq!(c.pretty(), "Ctrl+Shift+F");
        assert_eq!(chord("alt+pgup").to_config(), "alt+pageup");
        assert_eq!(chord("alt+PageUp").pretty(), "Alt+PageUp");
        assert_eq!(chord("ctrl+arrowleft"), chord("ctrl+left"));
        assert_eq!(chord("ctrl++").key, "+");
        assert_eq!(chord("ctrl+,").key, ",");
        assert_eq!(chord("ctrl+comma"), chord("ctrl+,"));
        assert_eq!(chord("f5").pretty(), "F5");
        assert_eq!(chord("esc").key, "escape");
        for bad in ["", "ctrl+", "ctrl+shift+nope", "hyper+x", "ctrl+ab"] {
            assert!(Chord::parse(bad).is_none(), "{bad:?} should not parse");
        }
    }

    #[test]
    fn defaults_are_valid_and_do_not_clash() {
        let (map, problems) = Keymap::build(&BTreeMap::new());
        assert!(problems.is_empty(), "{problems:?}");
        let total: usize = Action::all().map(|a| a.defaults().len()).sum();
        assert_eq!(map.map.len(), total, "two actions share a default chord");
        for action in Action::all() {
            assert!(!map.chords(action).is_empty(), "{action:?} has no key");
            assert_eq!(Action::from_id(action.id()), Some(action));
        }
        assert_eq!(map.get(&chord("ctrl+shift+f")), Some(Action::Find));
        assert_eq!(map.describe(Action::Paste), "Ctrl+Shift+V / Ctrl+V / Shift+Insert");
    }

    #[test]
    fn user_keys_replace_defaults_and_win_clashes() {
        let mut keys = BTreeMap::new();
        keys.insert("find".to_string(), KeyList::One("ctrl+alt+f".into()));
        // Taken from `zoom`, which has it by default.
        keys.insert("settings".to_string(), KeyList::Many(vec!["ctrl+shift+z".into(), "f12".into()]));
        keys.insert("nonsense".to_string(), KeyList::One("ctrl+x".into()));
        keys.insert("copy".to_string(), KeyList::One("ctrl+shift+nope".into()));
        let (map, problems) = Keymap::build(&keys);
        assert_eq!(map.get(&chord("ctrl+alt+f")), Some(Action::Find));
        assert_eq!(map.get(&chord("ctrl+shift+f")), None, "the old key is gone");
        assert_eq!(map.get(&chord("ctrl+shift+z")), Some(Action::Settings));
        assert_eq!(map.get(&chord("f12")), Some(Action::Settings));
        assert!(map.chords(Action::Zoom).is_empty(), "zoom lost its key to settings");
        assert_eq!(problems.len(), 2, "{problems:?}");
        // A bad chord leaves the action with no key rather than its old one.
        assert!(map.chords(Action::Copy).is_empty());
    }

    #[test]
    fn config_accepts_one_chord_or_a_list() {
        #[derive(Deserialize)]
        struct T {
            keys: BTreeMap<String, KeyList>,
        }
        let t: T = toml::from_str("[keys]\nfind = \"ctrl+f\"\npaste = [\"ctrl+v\", \"shift+insert\"]\n").unwrap();
        assert_eq!(t.keys["find"].chords(), vec!["ctrl+f"]);
        assert_eq!(t.keys["paste"].chords(), vec!["ctrl+v", "shift+insert"]);
    }
}