1
//! Key-event translation: crossterm [`KeyEvent`] → [`Intent`], through the
2
//! preset keymap and the scope chain `scopes::chain` builds from focus.
3

            
4
use crate::app::{App, button_of_key};
5
use crate::event::{Intent, apply};
6
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
7
use scopes::{SCOPES, Scopes, in_typing_chain};
8
use std::time::Instant;
9
use tvui::keymap::{Chord, Keymap, Pending, Resolved, Written, written_entries};
10

            
11
mod help;
12
mod scopes;
13
mod shown;
14

            
15
pub use help::{help_lines, help_topic};
16
pub use shown::{
17
    Hint, KeyView, here, hinted, in_form, in_modal, in_rows, in_view, in_view_all, in_window,
18
};
19

            
20
/// A keymap file: its name for error messages and its text.
21
type Layer<'a> = (&'a str, &'a str);
22

            
23
const BASE: Layer<'static> = ("base.keys", include_str!("keymap/base.keys"));
24
const EMACS: Layer<'static> = ("emacs.keys", include_str!("keymap/emacs.keys"));
25
const CUA: Layer<'static> = ("cua.keys", include_str!("keymap/cua.keys"));
26
const VIM: Layer<'static> = ("vim.keys", include_str!("keymap/vim.keys"));
27

            
28
/// A preset: the layers it is built from, each over the previous, and its vim state.
29
struct Preset {
30
    name: &'static str,
31
    layers: &'static [Layer<'static>],
32
    vim: VimState,
33
}
34

            
35
/// The preset used when neither the command line nor the config names one.
36
pub const DEFAULT_KEYMAP: &str = "cua";
37

            
38
const PRESETS: &[Preset] = &[
39
    Preset {
40
        name: "cua",
41
        layers: &[BASE, CUA],
42
        vim: VimState::Off,
43
    },
44
    Preset {
45
        name: "emacs",
46
        layers: &[BASE, EMACS],
47
        vim: VimState::Off,
48
    },
49
    Preset {
50
        name: "vim",
51
        layers: &[BASE, EMACS, VIM],
52
        vim: VimState::Insert,
53
    },
54
];
55

            
56
/// Where the vim preset is: typing or normal mode.
57
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58
pub enum VimState {
59
    /// The preset has no vim state.
60
    Off,
61
    Normal,
62
    Insert,
63
}
64

            
65
/// The preset keymap, the chords typed so far and the vim state.
66
pub struct Keys {
67
    name: &'static str,
68
    map: Keymap<Intent>,
69
    pending: Pending,
70
    chain: Vec<&'static str>,
71
    vim: VimState,
72
}
73

            
74
/// What a user override may not bind: a printable key, which would stop typing.
75
746999
fn bound_printable(entry: &Written<'_>, user: bool) -> bool {
76
746999
    let first = entry.chords.split_whitespace().next();
77
746999
    let printable = first.and_then(|chord| chord.parse::<Chord>().ok());
78
746999
    entry.action != "none"
79
746988
        && printable.is_some_and(Chord::is_printable)
80
181339
        && (entry.scope == "global" || (user && in_typing_chain(entry.scope)))
81
746999
}
82

            
83
/// # Errors
84
/// The first entry of `text` binding an unknown scope, or a printable key where it would stop
85
/// typing: always in `global`, and for a `user` override in any scope that types text.
86
6027
fn check_scopes(text: &str, user: bool) -> Result<(), String> {
87
6027
    for entry in written_entries(text) {
88
747002
        let Written { line, scope, .. } = entry;
89
12862067
        if !SCOPES.iter().any(|known| known.name == scope) {
90
3
            return Err(format!("line {line}: unknown scope `{scope}`"));
91
746999
        }
92
746999
        if bound_printable(&entry, user) {
93
10
            let key = entry.chords;
94
10
            return Err(format!(
95
10
                "line {line}: `{scope}` cannot bind the printable key `{key}`"
96
10
            ));
97
746989
        }
98
    }
99
6014
    Ok(())
100
6027
}
101

            
102
/// `text` over `lower`, or alone for the first layer.
103
6007
fn read_layer(
104
6007
    lower: Option<&Keymap<Intent>>,
105
6007
    (file, text): &Layer<'_>,
106
6007
    user: bool,
107
6007
) -> Result<Keymap<Intent>, String> {
108
6007
    check_scopes(text, user).map_err(|err| format!("{file}: {err}"))?;
109
6003
    let read = match lower {
110
3188
        Some(lower) => lower.overridden(text),
111
2815
        None => Keymap::parse(text),
112
    };
113
6003
    read.map_err(|err| format!("{file}: {err}"))
114
6007
}
115

            
116
impl Keys {
117
    /// Whether `other` is the same preset binding the same keys, whatever the typing state.
118
    #[must_use]
119
128
    pub fn same_bindings(&self, other: &Keys) -> bool {
120
128
        self.name == other.name && self.map == other.map
121
128
    }
122

            
123
    /// The names of the built-in keymaps.
124
33
    pub fn preset_names() -> impl Iterator<Item = &'static str> {
125
99
        PRESETS.iter().map(|preset| preset.name)
126
33
    }
127

            
128
    /// # Errors
129
    /// The message for an unknown preset or one that does not parse.
130
2815
    pub fn preset(name: &str) -> Result<Keys, String> {
131
3430
        let Some(preset) = PRESETS.iter().find(|preset| preset.name == name) else {
132
15
            let known: Vec<_> = PRESETS.iter().map(|preset| preset.name).collect();
133
5
            return Err(format!(
134
5
                "unknown keymap `{name}`; known: {}",
135
5
                known.join(", ")
136
5
            ));
137
        };
138
2810
        Keys::layered(preset.name, preset.vim, preset.layers)
139
            .map_err(|err| format!("{name} keymap: {err}"))
140
2815
    }
141

            
142
    /// These keys with the entries of `text` rebound or unbound.
143
    ///
144
    /// # Errors
145
    /// The message for an entry that does not parse, names an unknown scope or binds a
146
    /// printable key where it would stop typing.
147
176
    pub fn overridden(&self, text: &str) -> Result<Keys, String> {
148
176
        let map = read_layer(Some(&self.map), &("overrides", text), true)?;
149
28
        Ok(Keys {
150
28
            name: self.name,
151
28
            map,
152
28
            pending: Pending::default(),
153
28
            chain: Vec::new(),
154
28
            vim: self.vim,
155
28
        })
156
176
    }
157

            
158
2815
    fn layered(name: &'static str, vim: VimState, layers: &[Layer<'_>]) -> Result<Keys, String> {
159
2815
        let mut map = None;
160
2815
        for layer in layers {
161
5831
            map = Some(read_layer(map.as_ref(), layer, false)?);
162
        }
163
        Ok(Keys {
164
2814
            name,
165
2814
            map: map.ok_or("no layers")?,
166
2814
            pending: Pending::default(),
167
2814
            chain: Vec::new(),
168
2814
            vim,
169
        })
170
2815
    }
171

            
172
756
    pub fn vim(&self) -> VimState {
173
756
        self.vim
174
756
    }
175

            
176
    /// Switch the vim state; the emacs preset has none.
177
258
    pub fn set_vim(&mut self, state: VimState) {
178
258
        if self.vim != VimState::Off {
179
84
            self.vim = state;
180
174
        }
181
258
    }
182

            
183
    /// Whether the last key was resolved in a vim mode scope.
184
141
    fn in_vim_scope(&self) -> bool {
185
141
        self.chain
186
141
            .first()
187
141
            .is_some_and(|scope| scope.starts_with("vim-"))
188
141
    }
189

            
190
1451
    pub fn indicator(&self) -> &'static str {
191
1451
        match self.vim {
192
1328
            VimState::Off => self.name,
193
            VimState::Normal => "vim:normal",
194
123
            VimState::Insert => "vim:insert",
195
        }
196
1451
    }
197

            
198
    /// A half-typed binding does not survive a move to other scopes.
199
3369
    fn resolve(&mut self, scopes: Scopes, key: KeyEvent) -> Resolved<Intent> {
200
3369
        if self.chain != scopes.names {
201
1459
            self.pending = Pending::default();
202
1459
            self.chain = scopes.names;
203
1910
        }
204
3369
        match self
205
3369
            .map
206
3369
            .resolve(&self.chain, scopes.text, &mut self.pending, key)
207
        {
208
1149
            Resolved::Text(c) => Resolved::Action(Intent::InsertChar(c)),
209
2220
            other => other,
210
        }
211
3369
    }
212
}
213

            
214
/// Chooses the open menu's entry the typed `key` names, if any.
215
22
fn choose_by_mnemonic(app: &mut App, key: KeyEvent) {
216
22
    if let Some(at) = app.menu_mnemonic(key) {
217
14
        app.select_menu_item(at);
218
14
        apply(app, Intent::MenuSelect);
219
8
    }
220
22
}
221

            
222
/// Applies `intent` of `key`, a button's press by a key first being drawn down.
223
3220
fn act(app: &mut App, key: KeyEvent, intent: Intent) {
224
3220
    match button_of_key(app, key, intent) {
225
115
        Some((index, spec)) => app.hold_button_by_key(index, spec, Instant::now()),
226
3105
        None => apply(app, intent),
227
    }
228
3220
}
229

            
230
3369
fn run(app: &mut App, key: KeyEvent) -> Resolved<Intent> {
231
3369
    app.flush_key_press();
232
3369
    app.cancel_press();
233
3369
    let scopes = scopes::chain(app);
234
3369
    let resolved = app.keys.resolve(scopes, key);
235
3369
    match &resolved {
236
3220
        Resolved::Action(intent) => act(app, key, *intent),
237
141
        Resolved::Unbound if app.menu.is_some() => choose_by_mnemonic(app, key),
238
127
        _ => {}
239
    }
240
3369
    resolved
241
3369
}
242

            
243
/// Translate the key and apply it. Over SSH an Esc followed within 40 ms by a
244
/// key arrives as `M-key`; where vim binds Esc, an unbound `M-key` is both.
245
3359
pub fn handle_key(app: &mut App, key: KeyEvent) {
246
3359
    if run(app, key) != Resolved::Unbound {
247
3218
        return;
248
141
    }
249
141
    let vim_focus = app.keys.in_vim_scope();
250
141
    let split = matches!(key.code, KeyCode::Char(_) | KeyCode::Enter)
251
122
        && key.modifiers.contains(KeyModifiers::ALT);
252
141
    if vim_focus && split {
253
5
        run(app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
254
5
        run(
255
5
            app,
256
5
            KeyEvent::new(key.code, key.modifiers - KeyModifiers::ALT),
257
5
        );
258
136
    }
259
3359
}
260

            
261
#[cfg(test)]
262
mod arrow_tests;
263
#[cfg(test)]
264
mod builder_tests;
265
#[cfg(test)]
266
mod button_hold_tests;
267
#[cfg(test)]
268
mod button_tests;
269
#[cfg(test)]
270
mod confirm_tests;
271
#[cfg(test)]
272
mod console_tests;
273
#[cfg(test)]
274
mod cua_tests;
275
#[cfg(test)]
276
mod cursor_tests;
277
#[cfg(test)]
278
mod field_tests;
279
#[cfg(test)]
280
mod form_hints_tests;
281
#[cfg(test)]
282
mod grid_edit_tests;
283
#[cfg(test)]
284
mod help_tests;
285
#[cfg(test)]
286
mod hints_tests;
287
#[cfg(test)]
288
mod list_page_tests;
289
#[cfg(test)]
290
mod menu_tests;
291
#[cfg(test)]
292
mod preset_tests;
293
#[cfg(test)]
294
mod tab_tests;
295
#[cfg(test)]
296
mod tests;
297
#[cfg(test)]
298
mod vim_list_tests;
299
#[cfg(test)]
300
mod vim_tests;