use std::collections::{BTreeMap, VecDeque};
use super::key::Key;
use super::{BindingError, Command, CommandId, KeyChord, KeySequence, Modifiers, WhenContext};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PaletteEntry {
pub label: String,
pub detail: String,
pub value: CommandId,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct KeyOutcome {
pub consumed: bool,
pub command: Option<CommandId>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BindingConflict {
pub command: CommandId,
pub existing: CommandId,
pub sequence: KeySequence,
}
#[derive(Clone, Debug)]
pub struct CommandRegistry {
commands: BTreeMap<CommandId, Command>,
overrides: BTreeMap<CommandId, Option<KeySequence>>,
conflicts: Vec<BindingConflict>,
recent: VecDeque<CommandId>,
pending: Vec<KeyChord>,
pending_at: f64,
pending_timeout: f64,
}
impl Default for CommandRegistry {
fn default() -> Self {
Self {
commands: BTreeMap::new(),
overrides: BTreeMap::new(),
conflicts: Vec::new(),
recent: VecDeque::new(),
pending: Vec::new(),
pending_at: 0.0,
pending_timeout: Self::DEFAULT_TIMEOUT,
}
}
}
impl CommandRegistry {
pub const DEFAULT_TIMEOUT: f64 = 1.5;
pub fn new() -> Self {
Self {
pending_timeout: Self::DEFAULT_TIMEOUT,
..Self::default()
}
}
pub fn register(&mut self, command: Command) -> Option<Command> {
let id = command.id.clone();
if let Some(sequence) = command.default_shortcut.clone()
&& let Some(existing) = self.owner_of(&sequence, Some(&id))
{
self.conflicts.push(BindingConflict {
command: id.clone(),
existing,
sequence,
});
}
self.commands.insert(id, command)
}
pub fn register_all(&mut self, commands: impl IntoIterator<Item = Command>) {
for command in commands {
self.register(command);
}
}
pub fn remove(&mut self, id: &CommandId) -> Option<Command> {
self.overrides.remove(id);
self.recent.retain(|recent| recent != id);
self.commands.remove(id)
}
pub fn get(&self, id: &CommandId) -> Option<&Command> {
self.commands.get(id)
}
pub fn get_mut(&mut self, id: &CommandId) -> Option<&mut Command> {
self.commands.get_mut(id)
}
pub fn iter(&self) -> impl Iterator<Item = &Command> {
self.commands.values()
}
pub fn len(&self) -> usize {
self.commands.len()
}
pub fn is_empty(&self) -> bool {
self.commands.is_empty()
}
pub fn set_enabled(&mut self, id: &CommandId, enabled: bool) -> bool {
match self.commands.get_mut(id) {
Some(command) => {
command.state.enabled = enabled;
true
}
None => false,
}
}
pub fn set_checked(&mut self, id: &CommandId, checked: bool) -> bool {
match self.commands.get_mut(id) {
Some(command) => {
command.state.checked = checked;
true
}
None => false,
}
}
pub fn palette_entries(&self, context: &WhenContext) -> Vec<PaletteEntry> {
let mut entries = Vec::with_capacity(self.commands.len());
for id in self.recent() {
if let Some(entry) = self.entry_for(context, id) {
entries.push(entry);
}
}
for command in self.commands.values() {
if self.recent().any(|recent| recent == &command.id) {
continue;
}
if let Some(entry) = self.entry_for(context, &command.id) {
entries.push(entry);
}
}
entries
}
fn entry_for(&self, context: &WhenContext, id: &CommandId) -> Option<PaletteEntry> {
let command = self.commands.get(id)?;
if !command.is_enabled() || !command.applies(context) {
return None;
}
let shortcut = self.binding(id).map(ToString::to_string).unwrap_or_default();
let detail = if shortcut.is_empty() {
command.category.clone()
} else {
format!("{} · {shortcut}", command.category)
};
Some(PaletteEntry {
label: command.title.clone(),
detail,
value: id.clone(),
})
}
pub fn categories(&self) -> Vec<&str> {
let mut categories: Vec<&str> = self
.commands
.values()
.map(|command| command.category.as_str())
.collect();
categories.sort_unstable();
categories.dedup();
categories
}
pub fn default_binding(&self, id: &CommandId) -> Option<&KeySequence> {
self.commands
.get(id)
.and_then(|command| command.default_shortcut.as_ref())
}
pub fn binding(&self, id: &CommandId) -> Option<&KeySequence> {
match self.overrides.get(id) {
Some(override_binding) => override_binding.as_ref(),
None => self.default_binding(id),
}
}
pub fn bind(&mut self, id: &CommandId, sequence: KeySequence) -> Result<(), BindingError> {
if !self.commands.contains_key(id) {
return Err(BindingError::UnknownCommand(id.clone()));
}
if sequence.is_empty() {
return Err(BindingError::InvalidSequence(String::new()));
}
if let Some(existing) = self.owner_of(&sequence, Some(id)) {
return Err(BindingError::Conflict { sequence, existing });
}
self.overrides.insert(id.clone(), Some(sequence));
Ok(())
}
pub fn unbind(&mut self, id: &CommandId) {
self.overrides.insert(id.clone(), None);
}
pub fn reset_binding(&mut self, id: &CommandId) {
self.overrides.remove(id);
}
pub fn has_override(&self, id: &CommandId) -> bool {
self.overrides.contains_key(id)
}
pub fn owner_of(&self, sequence: &KeySequence, except: Option<&CommandId>) -> Option<CommandId> {
self.commands
.iter()
.filter(|(id, _)| except.is_none_or(|except| *id != except))
.find(|(id, _command)| self.binding(id).is_some_and(|binding| binding == sequence))
.map(|(id, _)| id.clone())
}
pub fn conflicts(&self) -> &[BindingConflict] {
&self.conflicts
}
pub fn bindings(&self) -> Vec<(KeySequence, CommandId)> {
let mut bindings: Vec<(KeySequence, CommandId)> = self
.commands
.keys()
.filter_map(|id| self.binding(id).map(|sequence| (sequence.clone(), id.clone())))
.collect();
bindings.sort_by(|left, right| right.0.len().cmp(&left.0.len()).then_with(|| left.1.cmp(&right.1)));
bindings
}
pub fn handle_key(&mut self, key: Key, modifiers: Modifiers, now: f64, context: &WhenContext) -> KeyOutcome {
if !self.pending.is_empty() && now - self.pending_at > self.pending_timeout {
self.pending.clear();
}
let candidates: Vec<(KeySequence, CommandId)> = self
.bindings()
.into_iter()
.filter(|(_, id)| {
self.commands
.get(id)
.is_some_and(|command| command.is_enabled() && command.applies(context))
})
.collect();
if self.pending.is_empty() {
for (sequence, id) in &candidates {
let Some(first) = sequence.chords().first() else {
continue;
};
if first.matches(modifiers, key) {
if sequence.len() == 1 {
self.note_used(id.clone());
return KeyOutcome {
consumed: true,
command: Some(id.clone()),
};
}
self.pending.push(*first);
self.pending_at = now;
return KeyOutcome {
consumed: true,
command: None,
};
}
}
return KeyOutcome::default();
}
let pending = self.pending.clone();
let mut consumed = false;
for (sequence, id) in &candidates {
if !sequence.starts_with(&pending) || sequence.len() <= pending.len() {
continue;
}
let Some(chord) = sequence.chords().get(pending.len()).copied() else {
continue;
};
if chord.matches(modifiers, key) {
consumed = true;
self.pending.push(chord);
self.pending_at = now;
if self.pending.len() == sequence.len() {
self.pending.clear();
self.note_used(id.clone());
return KeyOutcome {
consumed: true,
command: Some(id.clone()),
};
}
break;
}
}
if !consumed {
self.pending.clear();
}
KeyOutcome {
consumed,
command: None,
}
}
pub fn pending_timeout(&self) -> f64 {
self.pending_timeout
}
pub fn set_pending_timeout(&mut self, seconds: f64) {
self.pending_timeout = seconds.max(0.0);
}
pub fn note_used(&mut self, id: CommandId) {
self.recent.retain(|recent| recent != &id);
self.recent.push_front(id);
while self.recent.len() > 12 {
self.recent.pop_back();
}
}
pub fn recent(&self) -> impl Iterator<Item = &CommandId> {
self.recent.iter()
}
pub fn clear_recent(&mut self) {
self.recent.clear();
}
pub fn pending(&self) -> &[KeyChord] {
&self.pending
}
}
impl FromIterator<Command> for CommandRegistry {
fn from_iter<T: IntoIterator<Item = Command>>(iter: T) -> Self {
let mut registry = Self::new();
registry.register_all(iter);
registry
}
}
#[cfg(test)]
mod tests;