Skip to main content

velox_engine/
keymap.rs

1//! 作用域感知快捷键与命令路由系统(`Keymap` / `KeyStroke` / `KeyChord` / `ActionId`,100% `#![no_std]` 零堆)。
2//!
3//! 对标 GPUI / VS Code 的声明式键盘命令派发模型:
4//! - 支持单键组合(如 `Ctrl+S`、`Ctrl+Shift+P`)与两段弦键(如 `Ctrl+K, Ctrl+S`);
5//! - 支持按焦点上下文栈(如 `&["Editor", "Workspace", "Global"]`)自内向外精准匹配命令;
6//! - 弦键等待态内置自动超时复位,避免误按前缀键卡死后续输入。
7
8use crate::arena::SmallVec;
9use crate::pod::{KeyCode, KeyModifiers};
10
11/// 强类型业务命令/动作 ID(例如 `const SAVE: ActionId = ActionId(1);`)。
12#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
13pub struct ActionId(pub u32);
14
15/// 单个按键组合(键值 + 修饰键位掩码)。
16#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
17pub struct KeyStroke {
18    pub key: KeyCode,
19    pub modifiers: KeyModifiers,
20}
21
22impl KeyStroke {
23    #[inline(always)]
24    pub const fn new(key: KeyCode, modifiers: KeyModifiers) -> Self {
25        Self { key, modifiers }
26    }
27
28    #[inline(always)]
29    pub const fn plain(key: KeyCode) -> Self {
30        Self::new(key, KeyModifiers::NONE)
31    }
32
33    #[inline(always)]
34    pub const fn ctrl(ch: char) -> Self {
35        Self::new(KeyCode::Char(ch), KeyModifiers::CTRL)
36    }
37
38    #[inline(always)]
39    pub const fn ctrl_shift(ch: char) -> Self {
40        Self::new(
41            KeyCode::Char(ch),
42            KeyModifiers(KeyModifiers::CTRL.0 | KeyModifiers::SHIFT.0),
43        )
44    }
45
46    #[inline(always)]
47    pub const fn alt(ch: char) -> Self {
48        Self::new(KeyCode::Char(ch), KeyModifiers::ALT)
49    }
50}
51
52/// 单键或两段弦键快捷键序列(如 `Ctrl+K` 后接 `Ctrl+S`)。
53#[derive(Copy, Clone, PartialEq, Eq, Debug)]
54pub struct KeyChord {
55    pub first: KeyStroke,
56    pub second: Option<KeyStroke>,
57}
58
59impl KeyChord {
60    #[inline(always)]
61    pub const fn single(stroke: KeyStroke) -> Self {
62        Self {
63            first: stroke,
64            second: None,
65        }
66    }
67
68    #[inline(always)]
69    pub const fn pair(first: KeyStroke, second: KeyStroke) -> Self {
70        Self {
71            first,
72            second: Some(second),
73        }
74    }
75}
76
77/// 单条作用域快捷键绑定记录(`context == None` 表示全局兜底生效)。
78#[derive(Copy, Clone, PartialEq, Eq, Debug)]
79pub struct KeyBinding {
80    pub context: Option<&'static str>,
81    pub chord: KeyChord,
82    pub action: ActionId,
83}
84
85impl KeyBinding {
86    /// 创建全局生效的快捷键绑定。
87    #[inline(always)]
88    pub const fn global(chord: KeyChord, action: ActionId) -> Self {
89        Self {
90            context: None,
91            chord,
92            action,
93        }
94    }
95
96    /// 创建限定在特定焦点上下文作用域(如 `"CodeEditor"` / `"Dialog"`)内的快捷键绑定。
97    #[inline(always)]
98    pub const fn scoped(context: &'static str, chord: KeyChord, action: ActionId) -> Self {
99        Self {
100            context: Some(context),
101            chord,
102            action,
103        }
104    }
105}
106
107/// 快捷键解析结果。
108#[derive(Copy, Clone, PartialEq, Eq, Debug)]
109pub enum KeymapMatch {
110    /// 精确命中某条绑定命令。
111    Matched(ActionId),
112    /// 命中了某条两段弦键的前缀键,正等待第二键输入(调用方应吞掉本次事件避免误输入)。
113    PendingChord,
114    /// 未命中任何绑定。
115    NoMatch,
116}
117
118/// 定长无堆作用域快捷键路由表与弦键状态机(默认最多 64 条绑定,支持 `#![no_std]`)。
119#[derive(Clone, Debug)]
120pub struct Keymap<const CAP: usize = 64> {
121    bindings: SmallVec<KeyBinding, CAP>,
122    pending_first: Option<KeyStroke>,
123    pending_since_ms: u32,
124    chord_timeout_ms: u32,
125}
126
127impl<const CAP: usize> Default for Keymap<CAP> {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133impl<const CAP: usize> Keymap<CAP> {
134    #[inline]
135    pub const fn new() -> Self {
136        Self {
137            bindings: SmallVec::new(),
138            pending_first: None,
139            pending_since_ms: 0,
140            chord_timeout_ms: 1500,
141        }
142    }
143
144    /// 设置弦键前缀等待超时毫秒数(默认 `1500ms`)。
145    #[inline(always)]
146    pub fn set_chord_timeout_ms(&mut self, timeout_ms: u32) {
147        self.chord_timeout_ms = timeout_ms.max(100);
148    }
149
150    /// 注册一条快捷键绑定(后注册的同作用域绑定具有更高优先级,允许用户覆盖默认键位)。
151    #[inline]
152    pub fn bind(&mut self, binding: KeyBinding) -> bool {
153        self.bindings.push(binding)
154    }
155
156    /// 清空全部绑定与待定弦键状态。
157    #[inline]
158    pub fn clear(&mut self) {
159        self.bindings.clear();
160        self.pending_first = None;
161    }
162
163    /// 复位进行中的弦键前缀状态。
164    #[inline(always)]
165    pub fn reset_pending(&mut self) {
166        self.pending_first = None;
167    }
168
169    /// 返回当前是否正在等待两段弦键的第二个按键。
170    #[inline(always)]
171    pub const fn has_pending_chord(&self) -> bool {
172        self.pending_first.is_some()
173    }
174
175    /// 归一化字符大小写(例如按下 `Ctrl+Shift+p` 与 `Ctrl+Shift+P` 视为同一快捷键)。
176    #[inline]
177    fn normalize_stroke(mut stroke: KeyStroke) -> KeyStroke {
178        if let KeyCode::Char(c) = stroke.key {
179            if c.is_ascii_uppercase() {
180                stroke.key = KeyCode::Char(c.to_ascii_lowercase());
181            }
182        }
183        stroke
184    }
185
186    fn find_in_context(
187        &self,
188        target_ctx: Option<&str>,
189        first: KeyStroke,
190        second: Option<KeyStroke>,
191    ) -> Option<ActionId> {
192        let nf = Self::normalize_stroke(first);
193        let ns = second.map(Self::normalize_stroke);
194        for b in self.bindings.as_slice().iter().rev() {
195            if b.context != target_ctx {
196                continue;
197            }
198            let bf = Self::normalize_stroke(b.chord.first);
199            let bs = b.chord.second.map(Self::normalize_stroke);
200            if bf == nf && bs == ns {
201                return Some(b.action);
202            }
203        }
204        None
205    }
206
207    fn has_chord_prefix_in_context(&self, target_ctx: Option<&str>, first: KeyStroke) -> bool {
208        let nf = Self::normalize_stroke(first);
209        for b in self.bindings.as_slice() {
210            if b.context == target_ctx
211                && b.chord.second.is_some()
212                && Self::normalize_stroke(b.chord.first) == nf
213            {
214                return true;
215            }
216        }
217        false
218    }
219
220    /// 按焦点作用域链(由最内层焦点控件向外排列,例如 `&["CodeEditor", "Workspace"]`)解析按键。
221    pub fn resolve(
222        &mut self,
223        context_chain: &[&str],
224        stroke: KeyStroke,
225        now_ms: u32,
226    ) -> KeymapMatch {
227        if let Some(prev) = self.pending_first {
228            if now_ms.wrapping_sub(self.pending_since_ms) > self.chord_timeout_ms {
229                self.pending_first = None;
230            } else {
231                self.pending_first = None;
232                for &ctx in context_chain {
233                    if let Some(act) = self.find_in_context(Some(ctx), prev, Some(stroke)) {
234                        return KeymapMatch::Matched(act);
235                    }
236                }
237                if let Some(act) = self.find_in_context(None, prev, Some(stroke)) {
238                    return KeymapMatch::Matched(act);
239                }
240            }
241        }
242
243        // 先检查是否命中某个两段弦键前缀(最内层作用域优先)
244        for &ctx in context_chain {
245            if self.has_chord_prefix_in_context(Some(ctx), stroke) {
246                self.pending_first = Some(stroke);
247                self.pending_since_ms = now_ms;
248                return KeymapMatch::PendingChord;
249            }
250            if let Some(act) = self.find_in_context(Some(ctx), stroke, None) {
251                return KeymapMatch::Matched(act);
252            }
253        }
254        if self.has_chord_prefix_in_context(None, stroke) {
255            self.pending_first = Some(stroke);
256            self.pending_since_ms = now_ms;
257            return KeymapMatch::PendingChord;
258        }
259        if let Some(act) = self.find_in_context(None, stroke, None) {
260            return KeymapMatch::Matched(act);
261        }
262        KeymapMatch::NoMatch
263    }
264}