Skip to main content

crisol_core/commands/
registry.rs

1//! The command registry: registration, bindings, and shortcut polling.
2//!
3//! ```
4//! use crisol_core::commands::registry;
5//! ```
6
7use std::collections::{BTreeMap, VecDeque};
8
9use super::key::Key;
10use super::{BindingError, Command, CommandId, KeyChord, KeySequence, Modifiers, WhenContext};
11
12/// One palette row without the widget: label, secondary text, and command id.
13#[derive(Clone, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15/// # Example
16///
17/// ```
18/// use crisol_core::commands::PaletteEntry;
19/// ```
20pub struct PaletteEntry {
21    /// Primary text.
22    pub label: String,
23    /// Secondary text (category and shortcut).
24    pub detail: String,
25    /// The command to run.
26    pub value: CommandId,
27}
28
29/// The result of feeding one key press to the registry.
30#[derive(Clone, Debug, Default, PartialEq, Eq)]
31#[non_exhaustive]
32/// # Example
33///
34/// ```
35/// use crisol_core::commands::KeyOutcome;
36/// ```
37pub struct KeyOutcome {
38    /// Whether the key belonged to a binding (and should not reach a text field).
39    pub consumed: bool,
40    /// The command to run, when the sequence completed.
41    pub command: Option<CommandId>,
42}
43
44/// A default binding that was skipped because another command already owns it.
45#[derive(Clone, Debug, PartialEq, Eq)]
46/// # Example
47///
48/// ```
49/// use crisol_core::commands::BindingConflict;
50/// ```
51pub struct BindingConflict {
52    /// The command whose default was ignored.
53    pub command: CommandId,
54    /// The command that kept the sequence.
55    pub existing: CommandId,
56    /// The sequence.
57    pub sequence: KeySequence,
58}
59
60/// The command registry.
61#[derive(Clone, Debug)]
62/// # Example
63///
64/// ```
65/// use crisol_core::commands::CommandRegistry;
66/// ```
67pub 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    /// The default sequence timeout, in seconds (the 0.1.3 value).
93    pub const DEFAULT_TIMEOUT: f64 = 1.5;
94
95    /// An empty registry.
96    pub fn new() -> Self {
97        Self {
98            pending_timeout: Self::DEFAULT_TIMEOUT,
99            ..Self::default()
100        }
101    }
102
103    /// Register a command. A default shortcut that conflicts with an earlier command is
104    /// skipped and recorded in [`Self::conflicts`].
105    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    /// Register several commands.
120    pub fn register_all(&mut self, commands: impl IntoIterator<Item = Command>) {
121        for command in commands {
122            self.register(command);
123        }
124    }
125
126    /// Remove a command and its binding.
127    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    /// A command by id.
134    pub fn get(&self, id: &CommandId) -> Option<&Command> {
135        self.commands.get(id)
136    }
137
138    /// A command by id, mutably.
139    pub fn get_mut(&mut self, id: &CommandId) -> Option<&mut Command> {
140        self.commands.get_mut(id)
141    }
142
143    /// Every command, sorted by id.
144    pub fn iter(&self) -> impl Iterator<Item = &Command> {
145        self.commands.values()
146    }
147
148    /// The number of commands.
149    pub fn len(&self) -> usize {
150        self.commands.len()
151    }
152
153    /// Whether no command is registered.
154    pub fn is_empty(&self) -> bool {
155        self.commands.is_empty()
156    }
157
158    /// Set the enabled state.
159    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    /// Set the checked state.
170    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    /// The palette metadata for the commands that apply in `context`, recent first.
181    ///
182    /// The UI maps each entry to its own `PaletteItem`; the core does not know the
183    /// widget (CORE-KEY-02).
184    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    /// The categories in display order.
221    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    /// The default shortcut of a command.
233    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    /// The active shortcut of a command, including overrides.
240    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    /// Bind a command to a sequence, replacing its default. Fails when another command
248    /// owns the sequence.
249    ///
250    /// # Errors
251    /// When the command is unknown or another command already owns the sequence.
252    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    /// Remove the active binding of a command.
267    pub fn unbind(&mut self, id: &CommandId) {
268        self.overrides.insert(id.clone(), None);
269    }
270
271    /// Return a command to its default binding.
272    pub fn reset_binding(&mut self, id: &CommandId) {
273        self.overrides.remove(id);
274    }
275
276    /// Whether the command has a user override (including an explicit unbind).
277    pub fn has_override(&self, id: &CommandId) -> bool {
278        self.overrides.contains_key(id)
279    }
280
281    /// The command that owns a sequence, if any.
282    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    /// Defaults that were ignored because another command owned the sequence.
291    pub fn conflicts(&self) -> &[BindingConflict] {
292        &self.conflicts
293    }
294
295    /// Every active binding, longest sequence first.
296    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    /// Feed one key press and resolve it against the registry.
307    ///
308    /// A single chord returns its command immediately. A prefix such as `Ctrl+K` starts
309    /// a pending sequence and returns `consumed = true` with no command; the next chord
310    /// completes it within [`Self::pending_timeout`] seconds. Time is passed in by the
311    /// caller (normally from a [`Clock`](crate::time::Clock)); the core never reads a
312    /// clock itself (CORE-KEY-03, CORE-DET-02).
313    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    /// Seconds a started sequence waits for its next chord.
385    pub fn pending_timeout(&self) -> f64 {
386        self.pending_timeout
387    }
388
389    /// Change the sequence timeout.
390    pub fn set_pending_timeout(&mut self, seconds: f64) {
391        self.pending_timeout = seconds.max(0.0);
392    }
393
394    /// Mark a command as recently used, for palette ranking.
395    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    /// Recently used commands, newest first.
404    pub fn recent(&self) -> impl Iterator<Item = &CommandId> {
405        self.recent.iter()
406    }
407
408    /// Clear the recent list.
409    pub fn clear_recent(&mut self) {
410        self.recent.clear();
411    }
412
413    /// The chord currently being waited for, if a sequence has started.
414    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;