use serde_json::{json, Value};
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
pub const SEQUENCE_MS: u64 = 800;
pub const NAMED: &[&str] = &[
"enter", "escape", "tab", "space", "backspace", "delete", "insert", "home", "end", "pageup", "pagedown", "arrowup", "arrowdown", "arrowleft", "arrowright",
"f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
];
const MODS: [&str; 4] = ["ctrl", "alt", "shift", "meta"];
pub const RESERVED: &[&str] = &["t", "w", "n", "tab"];
pub fn reserved(held: [bool; 4], key: &str) -> Option<String> {
((held[0] || held[3]) && !held[1] && RESERVED.contains(&key)).then(|| {
let mut chord = String::new();
for (i, m) in MODS.iter().enumerate() {
if held[i] {
chord.push_str(m);
chord.push('+');
}
}
chord.push_str(key);
format!("`{chord}` is the browser's — no page ever hears it (ctrl+t, ctrl+w, ctrl+n and ctrl+tab, with shift or meta, are kept by the browser); bind another chord")
})
}
pub fn chord(text: &str) -> Result<String, String> {
if text.chars().any(char::is_uppercase) {
return Err(format!("`{text}`: a chord is lower case — write `{}` (a capital is `shift+` and the letter)", text.to_lowercase()));
}
let mut held = [false; 4];
let mut rest = text;
loop {
let Some(i) = MODS.iter().position(|m| rest.len() > m.len() + 1 && rest.get(..m.len()).is_some_and(|p| p.eq_ignore_ascii_case(m)) && rest.as_bytes()[m.len()] == b'+') else { break };
if held[i] {
return Err(format!("`{text}` says {} twice", MODS[i]));
}
held[i] = true;
rest = &rest[MODS[i].len() + 1..];
}
let key = rest.to_lowercase();
let one = key.chars().count() == 1;
if key.is_empty() || key.chars().any(char::is_whitespace) {
return Err(format!("`{text}` names no key"));
}
if !one && !NAMED.contains(&key.as_str()) {
return Err(format!("`{text}`: `{rest}` is no key — a chord is [ctrl+][alt+][shift+][meta+]key, the key one character or one of {}", NAMED.join(", ")));
}
if held[2] && one && !key.chars().all(char::is_alphabetic) {
return Err(format!("`{text}`: shift is in the character — write `{key}`"));
}
if let Some(why) = reserved(held, &key) {
return Err(why);
}
Ok(canonical(held, &key))
}
fn canonical(held: [bool; 4], key: &str) -> String {
let mut out = String::new();
for (i, m) in MODS.iter().enumerate() {
if held[i] {
out.push_str(m);
out.push('+');
}
}
out.push_str(key);
out
}
pub fn hides(a: &[String], b: &[String]) -> bool {
a.len() < b.len() && b.starts_with(a)
}
pub fn sequence(text: &str) -> Result<Vec<String>, String> {
let chords: Vec<String> = text.split(' ').filter(|c| !c.is_empty()).map(chord).collect::<Result<_, _>>()?;
if chords.is_empty() {
return Err("a key is a chord, not empty".into());
}
Ok(chords)
}
pub fn event_chord(key: &str, ctrl: bool, alt: bool, shift: bool, meta: bool) -> Option<String> {
let key = if key == " " { "space".to_string() } else { key.to_lowercase() };
if key.is_empty() || ["control", "shift", "alt", "meta", "altgraph", "capslock", "dead", "unidentified", "process", "os", "fn"].contains(&key.as_str()) {
return None;
}
let one = key.chars().count() == 1;
let shift = shift && (!one || key.chars().all(char::is_alphabetic));
Some(canonical([ctrl, alt, shift, meta], &key))
}
fn modded(chord: &str) -> bool {
chord.starts_with("ctrl+") || chord.contains("meta+")
}
#[derive(Debug, Clone, PartialEq)]
pub struct KeyDecl {
pub chord: String,
pub seq: Vec<String>,
pub to: String,
pub label: Option<String>,
pub in_inputs: bool,
pub only: bool,
pub in_controls: bool,
}
impl KeyDecl {
pub fn new(chord: &str, to: &str, label: Option<String>, in_inputs: bool, only: bool) -> Result<Self, String> {
let seq = sequence(chord)?;
Ok(Self { chord: seq.join(" "), seq, to: to.into(), label, in_inputs, only, in_controls: false })
}
pub fn controls(mut self, in_controls: bool) -> Self {
self.in_controls = in_controls;
self
}
fn heard(&self, p: &Press) -> bool {
if p.editable && !self.in_inputs() {
return false;
}
!(p.activatable && (p.chord == "enter" || p.chord == "space") && !self.in_controls)
}
pub fn shown(&self) -> String {
self.label.clone().filter(|l| !l.is_empty()).unwrap_or_else(|| self.to.clone())
}
fn in_inputs(&self) -> bool {
self.in_inputs || modded(&self.seq[0])
}
}
pub type KeyRun = Rc<dyn Fn(Value)>;
#[derive(Debug, Clone, PartialEq)]
pub struct Press {
pub chord: String,
pub key: String,
pub editable: bool,
pub activatable: bool,
pub repeat: bool,
pub target: Value,
pub at_ms: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Heard {
Nothing,
Ran(usize),
Waiting,
Overlay(bool),
Kept,
}
impl Heard {
pub fn taken(self) -> bool {
self != Heard::Nothing
}
}
struct Entry {
id: u64,
member: u64,
component: String,
decl: KeyDecl,
run: KeyRun,
}
#[derive(Default)]
struct Inner {
entries: RefCell<Vec<Entry>>,
pending: RefCell<(Vec<String>, u64)>,
overlay: Cell<bool>,
next: Cell<u64>,
on_change: RefCell<Option<Rc<dyn Fn()>>>,
}
fn changed(inner: &Inner) {
let f = inner.on_change.borrow().clone();
if let Some(f) = f {
f();
}
}
#[derive(Clone, Default)]
pub struct Keys(Rc<Inner>);
pub type KeyGroups = Vec<(String, Vec<(String, String)>)>;
impl std::fmt::Debug for Keys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Keys({} entries)", self.0.entries.borrow().len())
}
}
pub struct KeysHeld {
keys: Weak<Inner>,
ids: Vec<u64>,
}
impl Drop for KeysHeld {
fn drop(&mut self) {
if let Some(inner) = self.keys.upgrade() {
inner.entries.borrow_mut().retain(|e| !self.ids.contains(&e.id));
if !self.ids.is_empty() {
changed(&inner);
}
}
}
}
impl Keys {
pub fn add(&self, member: u64, component: &str, decls: Vec<(KeyDecl, KeyRun)>) -> KeysHeld {
let mut ids = Vec::new();
{
let mut entries = self.0.entries.borrow_mut();
for (decl, run) in decls {
let id = self.0.next.get() + 1;
self.0.next.set(id);
ids.push(id);
entries.push(Entry { id, member, component: component.into(), decl, run });
}
}
if !ids.is_empty() {
changed(&self.0);
}
KeysHeld { keys: Rc::downgrade(&self.0), ids }
}
pub fn remove_member(&self, member: u64) {
let gone = {
let mut entries = self.0.entries.borrow_mut();
let n = entries.len();
entries.retain(|e| e.member != member);
n != entries.len()
};
if gone {
changed(&self.0);
}
}
pub fn on_change(&self, f: Rc<dyn Fn()>) {
*self.0.on_change.borrow_mut() = Some(f);
}
pub fn close_overlay(&self) {
self.0.overlay.set(false);
}
pub fn len(&self) -> usize {
self.0.entries.borrow().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn overlay(&self) -> bool {
self.0.overlay.get()
}
pub fn groups(&self) -> KeyGroups {
let mut out: KeyGroups = Vec::new();
for e in self.0.entries.borrow().iter() {
let at = match out.iter().position(|(c, _)| c == &e.component) {
Some(i) => i,
None => {
out.push((e.component.clone(), Vec::new()));
out.len() - 1
}
};
if !out[at].1.iter().any(|(c, _)| c == &e.decl.chord) {
out[at].1.push((e.decl.chord.clone(), e.decl.shown()));
}
}
out
}
pub fn press(&self, p: &Press) -> Heard {
let inner = &self.0;
if inner.overlay.get() && p.chord == "?" && p.repeat {
return Heard::Kept;
}
if inner.overlay.get() && (p.chord == "escape" || p.chord == "?") {
inner.overlay.set(false);
return Heard::Overlay(false);
}
let mut seq = {
let pending = inner.pending.borrow();
if !pending.0.is_empty() && p.at_ms.saturating_sub(pending.1) <= SEQUENCE_MS {
pending.0.clone()
} else {
Vec::new()
}
};
seq.push(p.chord.clone());
loop {
let (mut full, prefix) = {
let entries = inner.entries.borrow();
let heard = entries.iter().filter(|e| e.decl.heard(p));
let mut full = Vec::new();
let mut prefix = false;
for e in heard {
if e.decl.seq == seq {
full.push((e.id, e.run.clone(), e.decl.only, e.decl.chord.clone()));
} else if e.decl.seq.len() > seq.len() && e.decl.seq.starts_with(&seq) {
prefix = true;
}
}
full.reverse();
(full, prefix)
};
if !full.is_empty() {
*inner.pending.borrow_mut() = (Vec::new(), 0);
let chosen: Vec<_> = match full.iter().position(|f| f.2) {
Some(i) => vec![full.swap_remove(i)],
None => full,
};
let mut ran = 0;
for (id, run, _, chord) in chosen {
if inner.entries.borrow().iter().any(|e| e.id == id) {
run(json!({ "key": p.key, "chord": chord, "target": p.target }));
ran += 1;
}
}
return Heard::Ran(ran);
}
if prefix {
*inner.pending.borrow_mut() = (seq, p.at_ms);
return Heard::Waiting;
}
if seq.len() > 1 {
seq = vec![p.chord.clone()];
continue;
}
break;
}
*inner.pending.borrow_mut() = (Vec::new(), 0);
if p.chord == "?" && !p.editable && !p.repeat && !inner.entries.borrow().is_empty() {
inner.overlay.set(true);
return Heard::Overlay(true);
}
Heard::Nothing
}
}
#[cfg(test)]
mod tests;