1use std::collections::{BTreeMap, VecDeque};
8
9use super::key::Key;
10use super::{BindingError, Command, CommandId, KeyChord, KeySequence, Modifiers, WhenContext};
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct PaletteEntry {
21 pub label: String,
23 pub detail: String,
25 pub value: CommandId,
27}
28
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct KeyOutcome {
38 pub consumed: bool,
40 pub command: Option<CommandId>,
42}
43
44#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct BindingConflict {
52 pub command: CommandId,
54 pub existing: CommandId,
56 pub sequence: KeySequence,
58}
59
60#[derive(Clone, Debug)]
62pub struct CommandRegistry {
68 commands: BTreeMap<CommandId, Command>,
69 overrides: BTreeMap<CommandId, Option<KeySequence>>,
70 conflicts: Vec<BindingConflict>,
71 recent: VecDeque<CommandId>,
72 pending: Vec<KeyChord>,
73 pending_at: f64,
74 pending_timeout: f64,
75}
76
77impl Default for CommandRegistry {
78 fn default() -> Self {
79 Self {
80 commands: BTreeMap::new(),
81 overrides: BTreeMap::new(),
82 conflicts: Vec::new(),
83 recent: VecDeque::new(),
84 pending: Vec::new(),
85 pending_at: 0.0,
86 pending_timeout: Self::DEFAULT_TIMEOUT,
87 }
88 }
89}
90
91impl CommandRegistry {
92 pub const DEFAULT_TIMEOUT: f64 = 1.5;
94
95 pub fn new() -> Self {
97 Self {
98 pending_timeout: Self::DEFAULT_TIMEOUT,
99 ..Self::default()
100 }
101 }
102
103 pub fn register(&mut self, command: Command) -> Option<Command> {
106 let id = command.id.clone();
107 if let Some(sequence) = command.default_shortcut.clone()
108 && let Some(existing) = self.owner_of(&sequence, Some(&id))
109 {
110 self.conflicts.push(BindingConflict {
111 command: id.clone(),
112 existing,
113 sequence,
114 });
115 }
116 self.commands.insert(id, command)
117 }
118
119 pub fn register_all(&mut self, commands: impl IntoIterator<Item = Command>) {
121 for command in commands {
122 self.register(command);
123 }
124 }
125
126 pub fn remove(&mut self, id: &CommandId) -> Option<Command> {
128 self.overrides.remove(id);
129 self.recent.retain(|recent| recent != id);
130 self.commands.remove(id)
131 }
132
133 pub fn get(&self, id: &CommandId) -> Option<&Command> {
135 self.commands.get(id)
136 }
137
138 pub fn get_mut(&mut self, id: &CommandId) -> Option<&mut Command> {
140 self.commands.get_mut(id)
141 }
142
143 pub fn iter(&self) -> impl Iterator<Item = &Command> {
145 self.commands.values()
146 }
147
148 pub fn len(&self) -> usize {
150 self.commands.len()
151 }
152
153 pub fn is_empty(&self) -> bool {
155 self.commands.is_empty()
156 }
157
158 pub fn set_enabled(&mut self, id: &CommandId, enabled: bool) -> bool {
160 match self.commands.get_mut(id) {
161 Some(command) => {
162 command.state.enabled = enabled;
163 true
164 }
165 None => false,
166 }
167 }
168
169 pub fn set_checked(&mut self, id: &CommandId, checked: bool) -> bool {
171 match self.commands.get_mut(id) {
172 Some(command) => {
173 command.state.checked = checked;
174 true
175 }
176 None => false,
177 }
178 }
179
180 pub fn palette_entries(&self, context: &WhenContext) -> Vec<PaletteEntry> {
185 let mut entries = Vec::with_capacity(self.commands.len());
186 for id in self.recent() {
187 if let Some(entry) = self.entry_for(context, id) {
188 entries.push(entry);
189 }
190 }
191 for command in self.commands.values() {
192 if self.recent().any(|recent| recent == &command.id) {
193 continue;
194 }
195 if let Some(entry) = self.entry_for(context, &command.id) {
196 entries.push(entry);
197 }
198 }
199 entries
200 }
201
202 fn entry_for(&self, context: &WhenContext, id: &CommandId) -> Option<PaletteEntry> {
203 let command = self.commands.get(id)?;
204 if !command.is_enabled() || !command.applies(context) {
205 return None;
206 }
207 let shortcut = self.binding(id).map(ToString::to_string).unwrap_or_default();
208 let detail = if shortcut.is_empty() {
209 command.category.clone()
210 } else {
211 format!("{} ยท {shortcut}", command.category)
212 };
213 Some(PaletteEntry {
214 label: command.title.clone(),
215 detail,
216 value: id.clone(),
217 })
218 }
219
220 pub fn categories(&self) -> Vec<&str> {
222 let mut categories: Vec<&str> = self
223 .commands
224 .values()
225 .map(|command| command.category.as_str())
226 .collect();
227 categories.sort_unstable();
228 categories.dedup();
229 categories
230 }
231
232 pub fn default_binding(&self, id: &CommandId) -> Option<&KeySequence> {
234 self.commands
235 .get(id)
236 .and_then(|command| command.default_shortcut.as_ref())
237 }
238
239 pub fn binding(&self, id: &CommandId) -> Option<&KeySequence> {
241 match self.overrides.get(id) {
242 Some(override_binding) => override_binding.as_ref(),
243 None => self.default_binding(id),
244 }
245 }
246
247 pub fn bind(&mut self, id: &CommandId, sequence: KeySequence) -> Result<(), BindingError> {
253 if !self.commands.contains_key(id) {
254 return Err(BindingError::UnknownCommand(id.clone()));
255 }
256 if sequence.is_empty() {
257 return Err(BindingError::InvalidSequence(String::new()));
258 }
259 if let Some(existing) = self.owner_of(&sequence, Some(id)) {
260 return Err(BindingError::Conflict { sequence, existing });
261 }
262 self.overrides.insert(id.clone(), Some(sequence));
263 Ok(())
264 }
265
266 pub fn unbind(&mut self, id: &CommandId) {
268 self.overrides.insert(id.clone(), None);
269 }
270
271 pub fn reset_binding(&mut self, id: &CommandId) {
273 self.overrides.remove(id);
274 }
275
276 pub fn has_override(&self, id: &CommandId) -> bool {
278 self.overrides.contains_key(id)
279 }
280
281 pub fn owner_of(&self, sequence: &KeySequence, except: Option<&CommandId>) -> Option<CommandId> {
283 self.commands
284 .iter()
285 .filter(|(id, _)| except.is_none_or(|except| *id != except))
286 .find(|(id, _command)| self.binding(id).is_some_and(|binding| binding == sequence))
287 .map(|(id, _)| id.clone())
288 }
289
290 pub fn conflicts(&self) -> &[BindingConflict] {
292 &self.conflicts
293 }
294
295 pub fn bindings(&self) -> Vec<(KeySequence, CommandId)> {
297 let mut bindings: Vec<(KeySequence, CommandId)> = self
298 .commands
299 .keys()
300 .filter_map(|id| self.binding(id).map(|sequence| (sequence.clone(), id.clone())))
301 .collect();
302 bindings.sort_by(|left, right| right.0.len().cmp(&left.0.len()).then_with(|| left.1.cmp(&right.1)));
303 bindings
304 }
305
306 pub fn handle_key(&mut self, key: Key, modifiers: Modifiers, now: f64, context: &WhenContext) -> KeyOutcome {
314 if !self.pending.is_empty() && now - self.pending_at > self.pending_timeout {
315 self.pending.clear();
316 }
317 let candidates: Vec<(KeySequence, CommandId)> = self
318 .bindings()
319 .into_iter()
320 .filter(|(_, id)| {
321 self.commands
322 .get(id)
323 .is_some_and(|command| command.is_enabled() && command.applies(context))
324 })
325 .collect();
326
327 if self.pending.is_empty() {
328 for (sequence, id) in &candidates {
329 let Some(first) = sequence.chords().first() else {
330 continue;
331 };
332 if first.matches(modifiers, key) {
333 if sequence.len() == 1 {
334 self.note_used(id.clone());
335 return KeyOutcome {
336 consumed: true,
337 command: Some(id.clone()),
338 };
339 }
340 self.pending.push(*first);
341 self.pending_at = now;
342 return KeyOutcome {
343 consumed: true,
344 command: None,
345 };
346 }
347 }
348 return KeyOutcome::default();
349 }
350
351 let pending = self.pending.clone();
352 let mut consumed = false;
353 for (sequence, id) in &candidates {
354 if !sequence.starts_with(&pending) || sequence.len() <= pending.len() {
355 continue;
356 }
357 let Some(chord) = sequence.chords().get(pending.len()).copied() else {
358 continue;
359 };
360 if chord.matches(modifiers, key) {
361 consumed = true;
362 self.pending.push(chord);
363 self.pending_at = now;
364 if self.pending.len() == sequence.len() {
365 self.pending.clear();
366 self.note_used(id.clone());
367 return KeyOutcome {
368 consumed: true,
369 command: Some(id.clone()),
370 };
371 }
372 break;
373 }
374 }
375 if !consumed {
376 self.pending.clear();
377 }
378 KeyOutcome {
379 consumed,
380 command: None,
381 }
382 }
383
384 pub fn pending_timeout(&self) -> f64 {
386 self.pending_timeout
387 }
388
389 pub fn set_pending_timeout(&mut self, seconds: f64) {
391 self.pending_timeout = seconds.max(0.0);
392 }
393
394 pub fn note_used(&mut self, id: CommandId) {
396 self.recent.retain(|recent| recent != &id);
397 self.recent.push_front(id);
398 while self.recent.len() > 12 {
399 self.recent.pop_back();
400 }
401 }
402
403 pub fn recent(&self) -> impl Iterator<Item = &CommandId> {
405 self.recent.iter()
406 }
407
408 pub fn clear_recent(&mut self) {
410 self.recent.clear();
411 }
412
413 pub fn pending(&self) -> &[KeyChord] {
415 &self.pending
416 }
417}
418
419impl FromIterator<Command> for CommandRegistry {
420 fn from_iter<T: IntoIterator<Item = Command>>(iter: T) -> Self {
421 let mut registry = Self::new();
422 registry.register_all(iter);
423 registry
424 }
425}
426
427#[cfg(test)]
428mod tests;