use super::{action_id, Chord, Conflict, ConflictKind, Platform, Stroke};
use crate::{context::invalid_value, Id};
use std::{collections::HashMap, hash::Hash, time::Duration};
mod lookup;
mod store;
pub(crate) use lookup::Lookup;
pub use store::KeymapIssue;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Binding {
pub action: Id,
pub context: Option<String>,
pub chord: Chord,
}
#[derive(Clone, Debug)]
struct Entry {
binding: Binding,
resolved: Vec<Stroke>,
}
#[derive(Clone, Debug)]
pub struct Keymap {
platform: Platform,
timeout: Duration,
names: Vec<(Id, String)>,
defaults: HashMap<Id, Vec<Binding>>,
overrides: HashMap<Id, Vec<Binding>>,
entries: Vec<Entry>,
first: HashMap<Stroke, Vec<usize>>,
}
impl Default for Keymap {
fn default() -> Self {
Self {
platform: Platform::current(),
timeout: Duration::from_millis(1500),
names: Vec::new(),
defaults: HashMap::new(),
overrides: HashMap::new(),
entries: Vec::new(),
first: HashMap::new(),
}
}
}
impl Keymap {
pub fn platform(&self) -> Platform {
self.platform
}
pub fn set_platform(&mut self, platform: Platform) {
if self.platform != platform {
self.platform = platform;
self.rebuild();
}
}
pub fn chord_timeout(&self) -> Duration {
self.timeout
}
#[track_caller]
pub fn set_chord_timeout(&mut self, timeout: Duration) {
if timeout.is_zero() {
invalid_value(
"Keymap::set_chord_timeout",
"expected a duration > 0; ignored".into(),
);
} else {
self.timeout = timeout;
}
}
pub fn bindings(&self) -> impl Iterator<Item = &Binding> {
self.entries.iter().map(|entry| &entry.binding)
}
pub fn bindings_of(&self, id: impl Hash) -> Vec<&Binding> {
let id = action_id(id);
self.bindings()
.filter(|binding| binding.action == id)
.collect()
}
pub fn shortcut_of(&self, id: Id, context: &str) -> Option<&Chord> {
let own = || self.bindings().filter(|binding| binding.action == id);
own()
.find(|binding| lookup::applies(binding.context.as_deref(), context))
.or_else(|| own().next())
.map(|binding| &binding.chord)
}
pub(super) fn add_action(&mut self, id: Id, name: &str) {
self.names.push((id, name.to_owned()));
}
pub(super) fn add_default(&mut self, binding: Binding) -> Vec<Conflict> {
let id = binding.action;
self.defaults.entry(id).or_default().push(binding.clone());
if self.overrides.contains_key(&id) {
return Vec::new();
}
let added = self.entries.len();
self.push_entry(binding);
self.conflicts_with(added, true)
}
fn push_entry(&mut self, binding: Binding) {
let platform = self.platform;
let resolved: Vec<Stroke> = binding
.chord
.strokes()
.iter()
.map(|stroke| stroke.concrete(platform))
.collect();
if let Some(first) = resolved.first() {
self.first
.entry(*first)
.or_default()
.push(self.entries.len());
self.entries.push(Entry { binding, resolved });
}
}
fn rebuild(&mut self) {
self.entries.clear();
self.first.clear();
let order: Vec<Id> = self.names.iter().map(|(id, _)| *id).collect();
for id in order {
let list = self.overrides.get(&id).or_else(|| self.defaults.get(&id));
for binding in list.cloned().unwrap_or_default() {
self.push_entry(binding);
}
}
}
#[track_caller]
pub fn rebind(&mut self, id: impl Hash, chord: Option<Chord>) -> Vec<Conflict> {
let id = action_id(id);
if !self.names.iter().any(|(known, _)| *known == id) {
invalid_value("Keymap::rebind", "unknown action; ignored".into());
return Vec::new();
}
let context = self
.entries
.iter()
.find(|entry| entry.binding.action == id)
.and_then(|entry| entry.binding.context.clone());
let bindings = chord
.filter(|chord| !chord.is_empty())
.map(|chord| Binding {
action: id,
context,
chord,
})
.into_iter()
.collect();
self.overrides.insert(id, bindings);
self.rebuild();
self.conflicts_of(id)
}
pub fn reset(&mut self, id: impl Hash) {
if self.overrides.remove(&action_id(id)).is_some() {
self.rebuild();
}
}
pub fn reset_all(&mut self) {
if !self.overrides.is_empty() {
self.overrides.clear();
self.rebuild();
}
}
pub fn is_overridden(&self, id: impl Hash) -> bool {
self.overrides.contains_key(&action_id(id))
}
pub fn conflicts(&self) -> Vec<Conflict> {
(0..self.entries.len())
.flat_map(|index| self.conflicts_with(index, true))
.collect()
}
pub fn conflicts_of(&self, id: Id) -> Vec<Conflict> {
let mut found: Vec<Conflict> = Vec::new();
for index in (0..self.entries.len()).filter(|i| self.entries[*i].binding.action == id) {
for conflict in self.conflicts_with(index, false) {
if !found.contains(&conflict) {
found.push(conflict);
}
}
}
found
}
fn conflicts_with(&self, index: usize, older_only: bool) -> Vec<Conflict> {
let entry = &self.entries[index];
let Some(candidates) = entry.resolved.first().and_then(|key| self.first.get(key)) else {
return Vec::new();
};
let mut found = Vec::new();
for &other in candidates
.iter()
.filter(|other| **other != index && (**other < index || !older_only))
{
let (a, b) = (&self.entries[other], entry);
if a.binding.action == b.binding.action || a.binding.context != b.binding.context {
continue;
}
let (first, second, kind) = if a.resolved == b.resolved {
if other < index {
(a, b, ConflictKind::Same)
} else {
(b, a, ConflictKind::Same)
}
} else if b.resolved.starts_with(&a.resolved) {
(a, b, ConflictKind::Prefix)
} else if a.resolved.starts_with(&b.resolved) {
(b, a, ConflictKind::Prefix)
} else {
continue;
};
found.push(Conflict {
context: first.binding.context.clone(),
chord: first.binding.chord.clone(),
first: first.binding.action,
second: second.binding.action,
kind,
});
}
found
}
pub fn name_of(&self, id: Id) -> Option<&str> {
self.names
.iter()
.find(|(known, _)| *known == id)
.map(|(_, name)| name.as_str())
}
}