1use serde_json::{json, Value};
35use std::cell::{Cell, RefCell};
36use std::rc::{Rc, Weak};
37
38pub const SEQUENCE_MS: u64 = 800;
40
41pub const NAMED: &[&str] = &[
43 "enter", "escape", "tab", "space", "backspace", "delete", "insert", "home", "end", "pageup", "pagedown", "arrowup", "arrowdown", "arrowleft", "arrowright",
44 "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
45];
46
47const MODS: [&str; 4] = ["ctrl", "alt", "shift", "meta"];
48
49pub const RESERVED: &[&str] = &["t", "w", "n", "tab"];
54
55pub fn reserved(held: [bool; 4], key: &str) -> Option<String> {
57 ((held[0] || held[3]) && !held[1] && RESERVED.contains(&key)).then(|| {
58 let mut chord = String::new();
59 for (i, m) in MODS.iter().enumerate() {
60 if held[i] {
61 chord.push_str(m);
62 chord.push('+');
63 }
64 }
65 chord.push_str(key);
66 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")
67 })
68}
69
70pub fn chord(text: &str) -> Result<String, String> {
75 if text.chars().any(char::is_uppercase) {
76 return Err(format!("`{text}`: a chord is lower case — write `{}` (a capital is `shift+` and the letter)", text.to_lowercase()));
77 }
78 let mut held = [false; 4];
79 let mut rest = text;
80 loop {
81 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 };
82 if held[i] {
83 return Err(format!("`{text}` says {} twice", MODS[i]));
84 }
85 held[i] = true;
86 rest = &rest[MODS[i].len() + 1..];
87 }
88 let key = rest.to_lowercase();
89 let one = key.chars().count() == 1;
90 if key.is_empty() || key.chars().any(char::is_whitespace) {
91 return Err(format!("`{text}` names no key"));
92 }
93 if !one && !NAMED.contains(&key.as_str()) {
94 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(", ")));
95 }
96 if held[2] && one && !key.chars().all(char::is_alphabetic) {
97 return Err(format!("`{text}`: shift is in the character — write `{key}`"));
98 }
99 if let Some(why) = reserved(held, &key) {
100 return Err(why);
101 }
102 Ok(canonical(held, &key))
103}
104
105fn canonical(held: [bool; 4], key: &str) -> String {
106 let mut out = String::new();
107 for (i, m) in MODS.iter().enumerate() {
108 if held[i] {
109 out.push_str(m);
110 out.push('+');
111 }
112 }
113 out.push_str(key);
114 out
115}
116
117pub fn hides(a: &[String], b: &[String]) -> bool {
120 a.len() < b.len() && b.starts_with(a)
121}
122
123pub fn sequence(text: &str) -> Result<Vec<String>, String> {
125 let chords: Vec<String> = text.split(' ').filter(|c| !c.is_empty()).map(chord).collect::<Result<_, _>>()?;
126 if chords.is_empty() {
127 return Err("a key is a chord, not empty".into());
128 }
129 Ok(chords)
130}
131
132pub fn event_chord(key: &str, ctrl: bool, alt: bool, shift: bool, meta: bool) -> Option<String> {
135 let key = if key == " " { "space".to_string() } else { key.to_lowercase() };
136 if key.is_empty() || ["control", "shift", "alt", "meta", "altgraph", "capslock", "dead", "unidentified", "process", "os", "fn"].contains(&key.as_str()) {
137 return None;
138 }
139 let one = key.chars().count() == 1;
140 let shift = shift && (!one || key.chars().all(char::is_alphabetic));
142 Some(canonical([ctrl, alt, shift, meta], &key))
143}
144
145fn modded(chord: &str) -> bool {
146 chord.starts_with("ctrl+") || chord.contains("meta+")
147}
148
149#[derive(Debug, Clone, PartialEq)]
152pub struct KeyDecl {
153 pub chord: String,
155 pub seq: Vec<String>,
156 pub to: String,
157 pub label: Option<String>,
158 pub in_inputs: bool,
159 pub only: bool,
160 pub in_controls: bool,
162}
163
164impl KeyDecl {
165 pub fn new(chord: &str, to: &str, label: Option<String>, in_inputs: bool, only: bool) -> Result<Self, String> {
167 let seq = sequence(chord)?;
168 Ok(Self { chord: seq.join(" "), seq, to: to.into(), label, in_inputs, only, in_controls: false })
169 }
170
171 pub fn controls(mut self, in_controls: bool) -> Self {
173 self.in_controls = in_controls;
174 self
175 }
176
177 fn heard(&self, p: &Press) -> bool {
179 if p.editable && !self.in_inputs() {
180 return false;
181 }
182 !(p.activatable && (p.chord == "enter" || p.chord == "space") && !self.in_controls)
183 }
184
185 pub fn shown(&self) -> String {
187 self.label.clone().filter(|l| !l.is_empty()).unwrap_or_else(|| self.to.clone())
188 }
189
190 fn in_inputs(&self) -> bool {
192 self.in_inputs || modded(&self.seq[0])
193 }
194}
195
196pub type KeyRun = Rc<dyn Fn(Value)>;
198
199#[derive(Debug, Clone, PartialEq)]
201pub struct Press {
202 pub chord: String,
204 pub key: String,
206 pub editable: bool,
208 pub activatable: bool,
211 pub repeat: bool,
213 pub target: Value,
215 pub at_ms: u64,
217}
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub enum Heard {
222 Nothing,
224 Ran(usize),
226 Waiting,
228 Overlay(bool),
230 Kept,
233}
234
235impl Heard {
236 pub fn taken(self) -> bool {
238 self != Heard::Nothing
239 }
240}
241
242struct Entry {
243 id: u64,
244 member: u64,
245 component: String,
246 decl: KeyDecl,
247 run: KeyRun,
248}
249
250#[derive(Default)]
251struct Inner {
252 entries: RefCell<Vec<Entry>>,
253 pending: RefCell<(Vec<String>, u64)>,
255 overlay: Cell<bool>,
256 next: Cell<u64>,
257 on_change: RefCell<Option<Rc<dyn Fn()>>>,
259}
260
261fn changed(inner: &Inner) {
262 let f = inner.on_change.borrow().clone();
263 if let Some(f) = f {
264 f();
265 }
266}
267
268#[derive(Clone, Default)]
270pub struct Keys(Rc<Inner>);
271
272pub type KeyGroups = Vec<(String, Vec<(String, String)>)>;
275
276impl std::fmt::Debug for Keys {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 write!(f, "Keys({} entries)", self.0.entries.borrow().len())
279 }
280}
281
282pub struct KeysHeld {
284 keys: Weak<Inner>,
285 ids: Vec<u64>,
286}
287
288impl Drop for KeysHeld {
289 fn drop(&mut self) {
290 if let Some(inner) = self.keys.upgrade() {
291 inner.entries.borrow_mut().retain(|e| !self.ids.contains(&e.id));
292 if !self.ids.is_empty() {
293 changed(&inner);
294 }
295 }
296 }
297}
298
299impl Keys {
300 pub fn add(&self, member: u64, component: &str, decls: Vec<(KeyDecl, KeyRun)>) -> KeysHeld {
302 let mut ids = Vec::new();
303 {
304 let mut entries = self.0.entries.borrow_mut();
305 for (decl, run) in decls {
306 let id = self.0.next.get() + 1;
307 self.0.next.set(id);
308 ids.push(id);
309 entries.push(Entry { id, member, component: component.into(), decl, run });
310 }
311 }
312 if !ids.is_empty() {
313 changed(&self.0);
314 }
315 KeysHeld { keys: Rc::downgrade(&self.0), ids }
316 }
317
318 pub fn remove_member(&self, member: u64) {
320 let gone = {
321 let mut entries = self.0.entries.borrow_mut();
322 let n = entries.len();
323 entries.retain(|e| e.member != member);
324 n != entries.len()
325 };
326 if gone {
327 changed(&self.0);
328 }
329 }
330
331 pub fn on_change(&self, f: Rc<dyn Fn()>) {
334 *self.0.on_change.borrow_mut() = Some(f);
335 }
336
337 pub fn close_overlay(&self) {
339 self.0.overlay.set(false);
340 }
341
342 pub fn len(&self) -> usize {
344 self.0.entries.borrow().len()
345 }
346
347 pub fn is_empty(&self) -> bool {
348 self.len() == 0
349 }
350
351 pub fn overlay(&self) -> bool {
353 self.0.overlay.get()
354 }
355
356 pub fn groups(&self) -> KeyGroups {
359 let mut out: KeyGroups = Vec::new();
360 for e in self.0.entries.borrow().iter() {
361 let at = match out.iter().position(|(c, _)| c == &e.component) {
362 Some(i) => i,
363 None => {
364 out.push((e.component.clone(), Vec::new()));
365 out.len() - 1
366 }
367 };
368 if !out[at].1.iter().any(|(c, _)| c == &e.decl.chord) {
369 out[at].1.push((e.decl.chord.clone(), e.decl.shown()));
370 }
371 }
372 out
373 }
374
375 pub fn press(&self, p: &Press) -> Heard {
379 let inner = &self.0;
380 if inner.overlay.get() && p.chord == "?" && p.repeat {
381 return Heard::Kept;
382 }
383 if inner.overlay.get() && (p.chord == "escape" || p.chord == "?") {
384 inner.overlay.set(false);
385 return Heard::Overlay(false);
386 }
387 let mut seq = {
388 let pending = inner.pending.borrow();
389 if !pending.0.is_empty() && p.at_ms.saturating_sub(pending.1) <= SEQUENCE_MS {
390 pending.0.clone()
391 } else {
392 Vec::new()
393 }
394 };
395 seq.push(p.chord.clone());
396 loop {
397 let (mut full, prefix) = {
400 let entries = inner.entries.borrow();
401 let heard = entries.iter().filter(|e| e.decl.heard(p));
402 let mut full = Vec::new();
403 let mut prefix = false;
404 for e in heard {
405 if e.decl.seq == seq {
406 full.push((e.id, e.run.clone(), e.decl.only, e.decl.chord.clone()));
407 } else if e.decl.seq.len() > seq.len() && e.decl.seq.starts_with(&seq) {
408 prefix = true;
409 }
410 }
411 full.reverse();
412 (full, prefix)
413 };
414 if !full.is_empty() {
415 *inner.pending.borrow_mut() = (Vec::new(), 0);
416 let chosen: Vec<_> = match full.iter().position(|f| f.2) {
417 Some(i) => vec![full.swap_remove(i)],
418 None => full,
419 };
420 let mut ran = 0;
421 for (id, run, _, chord) in chosen {
422 if inner.entries.borrow().iter().any(|e| e.id == id) {
424 run(json!({ "key": p.key, "chord": chord, "target": p.target }));
425 ran += 1;
426 }
427 }
428 return Heard::Ran(ran);
429 }
430 if prefix {
431 *inner.pending.borrow_mut() = (seq, p.at_ms);
432 return Heard::Waiting;
433 }
434 if seq.len() > 1 {
435 seq = vec![p.chord.clone()];
437 continue;
438 }
439 break;
440 }
441 *inner.pending.borrow_mut() = (Vec::new(), 0);
442 if p.chord == "?" && !p.editable && !p.repeat && !inner.entries.borrow().is_empty() {
443 inner.overlay.set(true);
444 return Heard::Overlay(true);
445 }
446 Heard::Nothing
447 }
448}
449
450#[cfg(test)]
451mod tests;