Skip to main content

egui_pop_model/
keymap.rs

1//! Keys bound to commands, resolved by the framework alone (ADR 0007).
2//!
3//! Bindings come in layers: the user's over the workspace's over the
4//! framework's defaults over the suggestions components make. Among the
5//! bindings of the pressed keys whose `when` holds, the winner is the
6//! greatest `(depth, layer, specificity, order)`: the binding testing
7//! keys set nearest the focus, then the higher layer, then the clause
8//! testing more keys, then the last declared.
9//!
10//! Two removals: a binding to [`Action::Remove`] (`"-id"` in files) takes
11//! a command's bindings away from the layers below, and [`Action::Unbind`]
12//! (`null` in files) takes away every binding of exactly those keys from
13//! the layers below. Keys are logical: what the key produces, so top-row
14//! and keypad digits are the same. A shortcut is one or more chords
15//! (`Ctrl+K Ctrl+S`).
16//!
17//! A binding whose command went with its plugin is **dormant**
18//! ([`Keymap::set_dormant`], ADR 0028): it stays in its layer and is saved
19//! with it, but it does not take its keys, which go to the next binding
20//! of them; it shows no key and makes no conflict, a trace says
21//! [`DORMANT`], and [`Keymap::dormant`] lists it for a shortcuts editor.
22//! It is live again as soon as its command is taken out of the set.
23//!
24//! A chord's key may also be a pointer gesture ([`Pointer`]): the wheel,
25//! a smooth scroll, a pinch, a click, a double click or a drag of a
26//! button, with the same modifiers (`Ctrl+Wheel`, `MiddleDrag`,
27//! `Shift+PrimaryDrag`). Such a chord stands alone (never in a
28//! sequence) and is bound in a canvas's scope (`surface:canvas.image`);
29//! the key dispatcher never sees it: the canvas asks the keymap
30//! ([`Keymap::pointer_bindings`]) what its gestures do.
31//!
32//! ```
33//! use egui_pop_model::ids::{CommandId, OwnerId};
34//! use egui_pop_model::keymap::{Action, Keymap, Keys, Layer, Resolution};
35//! use egui_pop_model::when::WhenContext;
36//!
37//! let mut k = Keymap::new();
38//! let fw = OwnerId::FRAMEWORK;
39//! k.bind(&fw, Layer::Default, "Ctrl+K Ctrl+S", Action::run("keys.editor"), "").unwrap();
40//! let cx = WhenContext::new();
41//! assert_eq!(k.resolve(&Keys::parse("Ctrl+K").unwrap(), &cx), Resolution::Pending);
42//! let (r, trace) = k.resolve_traced(&Keys::parse("Ctrl+K Ctrl+S").unwrap(), &cx);
43//! assert_eq!(r, Resolution::Run(CommandId::from_static("keys.editor")));
44//! assert_eq!(trace.candidates.len(), 1);
45//! ```
46
47use std::fmt;
48
49use serde::{Deserialize, Serialize};
50
51use crate::diagnostics::Diagnostics;
52use crate::ids::{CommandId, OwnerId};
53use crate::registry::OwnedList;
54use crate::when::{When, WhenContext};
55
56/// What a trace says of a binding whose command's plugin is
57/// disconnected: the `because` of its [`Verdict::Lost`], whose `to` is
58/// the binding that got the keys (empty when none did). A verdict of its
59/// own comes with the next breaking release of this enum.
60pub const DORMANT: &str = "dormant: its command's plugin is disconnected";
61
62/// The context key naming the keys the focused widget reads itself, as
63/// chord key names separated by spaces (`arrowleft arrowright home`): set by
64/// the key dispatcher while such a widget has the focus. A global binding of
65/// one of them without Ctrl or Alt is left to the widget
66/// ([`Verdict::LeftToWidget`]), unless it fires `always` or its clause tests
67/// this key itself.
68pub const CONTEXT_WIDGET_KEYS: &str = "focusedWidgetKeys";
69
70/// Where a binding comes from; later variants win.
71#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
72#[serde(rename_all = "lowercase")]
73pub enum Layer {
74    Suggestion,
75    Default,
76    Workspace,
77    User,
78}
79
80/// A pointer button, by its logical role: the system swaps primary and
81/// secondary for a left hand, and the application never sees it.
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
83pub enum Button {
84    Primary,
85    Secondary,
86    Middle,
87    Back,
88    Forward,
89}
90
91impl Button {
92    pub const ALL: [Button; 5] = [
93        Button::Primary,
94        Button::Secondary,
95        Button::Middle,
96        Button::Back,
97        Button::Forward,
98    ];
99
100    /// As in chords: `Primary`, `Secondary`, `Middle`, `Back`, `Forward`.
101    pub fn name(self) -> &'static str {
102        match self {
103            Button::Primary => "Primary",
104            Button::Secondary => "Secondary",
105            Button::Middle => "Middle",
106            Button::Back => "Back",
107            Button::Forward => "Forward",
108        }
109    }
110}
111
112/// The pointer part of a chord: what the pointer does while the chord's
113/// modifiers are held.
114#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
115pub enum Pointer {
116    /// A mouse wheel's notches (line units).
117    Wheel,
118    /// A smooth scroll in points: a trackpad's two fingers, a
119    /// free-spinning or high-resolution wheel.
120    Scroll,
121    /// A pinch: a trackpad's or a touch screen's two fingers moving
122    /// apart or together (a browser also sends a trackpad's pinch this
123    /// way).
124    Pinch,
125    /// A button pressed and released without moving.
126    Click(Button),
127    DoubleClick(Button),
128    /// A button held while the pointer moves.
129    Drag(Button),
130}
131
132impl Pointer {
133    /// Every pointer gesture, in a stable order.
134    pub fn all() -> Vec<Pointer> {
135        let mut out = vec![Pointer::Wheel, Pointer::Scroll, Pointer::Pinch];
136        for b in Button::ALL {
137            out.extend([Pointer::Click(b), Pointer::DoubleClick(b), Pointer::Drag(b)]);
138        }
139        out
140    }
141
142    /// As in chords: `Wheel`, `Scroll`, `Pinch`, `PrimaryClick`,
143    /// `MiddleDoubleClick`, `SecondaryDrag`.
144    pub fn name(self) -> String {
145        match self {
146            Pointer::Wheel => "Wheel".into(),
147            Pointer::Scroll => "Scroll".into(),
148            Pointer::Pinch => "Pinch".into(),
149            Pointer::Click(b) => format!("{}Click", b.name()),
150            Pointer::DoubleClick(b) => format!("{}DoubleClick", b.name()),
151            Pointer::Drag(b) => format!("{}Drag", b.name()),
152        }
153    }
154
155    /// From its name, in any case.
156    pub fn parse(text: &str) -> Option<Pointer> {
157        Pointer::all()
158            .into_iter()
159            .find(|p| p.name().eq_ignore_ascii_case(text))
160    }
161
162    /// The wheel, a scroll or a pinch (not a button).
163    pub fn is_wheel(self) -> bool {
164        matches!(self, Pointer::Wheel | Pointer::Scroll | Pointer::Pinch)
165    }
166
167    /// Its button, for a click, a double click or a drag.
168    pub fn button(self) -> Option<Button> {
169        match self {
170            Pointer::Click(b) | Pointer::DoubleClick(b) | Pointer::Drag(b) => Some(b),
171            _ => None,
172        }
173    }
174}
175
176/// One chord: modifiers and a logical key, or a pointer gesture
177/// ([`Chord::pointer`]).
178#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
179pub struct Chord {
180    pub ctrl: bool,
181    pub alt: bool,
182    pub shift: bool,
183    pub meta: bool,
184    /// Lowercase key name: `a`, `3`, `f1`, `space`, `tab`, `escape`; or
185    /// a pointer gesture's name, lowercase (`wheel`, `middledrag`).
186    pub key: String,
187}
188
189impl Chord {
190    /// A chord without modifiers.
191    pub fn key(key: &str) -> Chord {
192        Chord {
193            ctrl: false,
194            alt: false,
195            shift: false,
196            meta: false,
197            key: normalize_key(&key.to_lowercase()),
198        }
199    }
200
201    pub fn parse(text: &str) -> Result<Chord, String> {
202        let mut c = Chord::key("");
203        let parts: Vec<&str> = text.split('+').collect();
204        // `Ctrl++` binds the plus key.
205        let (mods, key) = if text.ends_with("++") {
206            (&parts[..parts.len() - 2], "+")
207        } else {
208            let (m, k) = parts.split_at(parts.len() - 1);
209            (m, k[0])
210        };
211        for m in mods {
212            match m.to_lowercase().as_str() {
213                "ctrl" | "control" => c.ctrl = true,
214                "alt" | "option" => c.alt = true,
215                "shift" => c.shift = true,
216                "meta" | "super" | "cmd" => c.meta = true,
217                other => return Err(format!("`{other}` is not a modifier in `{text}`")),
218            }
219        }
220        let key = key.to_lowercase();
221        if key.is_empty() {
222            return Err(format!("no key in `{text}`"));
223        }
224        c.key = normalize_key(&key);
225        Ok(c)
226    }
227
228    /// A pointer gesture without modifiers.
229    pub fn pointer_gesture(pointer: Pointer) -> Chord {
230        Chord::key(&pointer.name())
231    }
232
233    /// Its pointer gesture, when its key is one.
234    pub fn pointer(&self) -> Option<Pointer> {
235        Pointer::parse(&self.key)
236    }
237
238    /// Whether it is a pointer gesture.
239    pub fn is_pointer(&self) -> bool {
240        self.pointer().is_some()
241    }
242
243    /// The same modifiers, nothing else (what a held set of keys is
244    /// compared with).
245    pub fn same_modifiers(&self, other: &Chord) -> bool {
246        (self.ctrl, self.alt, self.shift, self.meta)
247            == (other.ctrl, other.alt, other.shift, other.meta)
248    }
249
250    /// Modifiers alone, as in files: `Ctrl+Shift`, `Alt`, empty for
251    /// none. The chord's key is empty.
252    pub fn parse_modifiers(text: &str) -> Result<Chord, String> {
253        let mut c = Chord::key("");
254        for m in text.split('+').map(str::trim).filter(|m| !m.is_empty()) {
255            match m.to_lowercase().as_str() {
256                "ctrl" | "control" => c.ctrl = true,
257                "alt" | "option" => c.alt = true,
258                "shift" => c.shift = true,
259                "meta" | "super" | "cmd" => c.meta = true,
260                other => return Err(format!("`{other}` is not a modifier in `{text}`")),
261            }
262        }
263        Ok(c)
264    }
265}
266
267/// Keypad digits are digits; `esc` is `escape`.
268fn normalize_key(key: &str) -> String {
269    let key = key.strip_prefix("numpad").unwrap_or(key);
270    match key {
271        "esc" => "escape".into(),
272        "return" => "enter".into(),
273        "del" => "delete".into(),
274        other => other.into(),
275    }
276}
277
278impl fmt::Display for Chord {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        for (on, name) in [
281            (self.ctrl, "Ctrl"),
282            (self.alt, "Alt"),
283            (self.shift, "Shift"),
284            (self.meta, "Meta"),
285        ] {
286            if on {
287                write!(f, "{name}+")?;
288            }
289        }
290        if let Some(p) = self.pointer() {
291            return write!(f, "{}", p.name());
292        }
293        let mut k = self.key.clone();
294        if let Some(first) = k.get_mut(0..1) {
295            first.make_ascii_uppercase();
296        }
297        write!(f, "{k}")
298    }
299}
300
301/// A key sequence: one or more chords.
302#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
303pub struct Keys(pub Vec<Chord>);
304
305impl Keys {
306    pub fn parse(text: &str) -> Result<Keys, String> {
307        let chords = text
308            .split_whitespace()
309            .map(Chord::parse)
310            .collect::<Result<Vec<_>, _>>()?;
311        if chords.is_empty() {
312            return Err("no keys".into());
313        }
314        if chords.len() > 1 && chords.iter().any(Chord::is_pointer) {
315            return Err(format!(
316                "a pointer gesture is a chord of its own, never in a sequence: `{text}`"
317            ));
318        }
319        Ok(Keys(chords))
320    }
321
322    /// Its pointer gesture, when it is one chord holding one.
323    pub fn pointer(&self) -> Option<(&Chord, Pointer)> {
324        match self.0.as_slice() {
325            [c] => c.pointer().map(|p| (c, p)),
326            _ => None,
327        }
328    }
329}
330
331impl fmt::Display for Keys {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        let parts: Vec<String> = self.0.iter().map(Chord::to_string).collect();
334        write!(f, "{}", parts.join(" "))
335    }
336}
337
338/// What a binding does.
339#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
340#[serde(tag = "action", content = "command", rename_all = "lowercase")]
341pub enum Action {
342    /// Runs a command.
343    Run(CommandId),
344    /// Removes a command's bindings from the layers below.
345    Remove(CommandId),
346    /// Removes every binding of these keys from the layers below.
347    Unbind,
348}
349
350impl Action {
351    /// Runs a command given by a literal.
352    pub fn run(id: &'static str) -> Action {
353        Action::Run(CommandId::from_static(id))
354    }
355
356    /// As in files: `"id"`, `"-id"` or `null`.
357    pub fn parse(command: Option<&str>) -> Result<Action, String> {
358        match command {
359            None => Ok(Action::Unbind),
360            Some(c) => match c.strip_prefix('-') {
361                Some(rest) => CommandId::new(rest)
362                    .map(Action::Remove)
363                    .map_err(|e| e.to_string()),
364                None => CommandId::new(c)
365                    .map(Action::Run)
366                    .map_err(|e| e.to_string()),
367            },
368        }
369    }
370
371    /// As in files.
372    pub fn to_file(&self) -> Option<String> {
373        match self {
374            Action::Run(c) => Some(c.to_string()),
375            Action::Remove(c) => Some(format!("-{c}")),
376            Action::Unbind => None,
377        }
378    }
379
380    fn command(&self) -> Option<&CommandId> {
381        match self {
382            Action::Run(c) => Some(c),
383            _ => None,
384        }
385    }
386}
387
388/// Where a binding listens. Each window dispatches its own keys and
389/// bubbles outwards: a surface holding the focus, then the window's
390/// focused panel, then the window, then the whole application
391/// ([`KeyScope::tier`]); a binding of a narrower scope wins over one of a
392/// wider scope on the same keys.
393#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
394pub enum KeyScope {
395    /// Any window, whatever has the focus (a text input may keep the key,
396    /// see [`Typing`]); a modal open in the window blocks it.
397    #[default]
398    Global,
399    /// Only while the surface (a focus scope of that name) holds the
400    /// focus, shown with a focus ring or not.
401    Surface(String),
402    /// Also while the application does not have the focus: the system
403    /// delivers the keys (a global shortcut, registered by a plugin that
404    /// reads [`Keymap::system_bindings`]). Inside the window it fires as
405    /// a [`KeyScope::Global`] binding does.
406    System,
407    /// Only in that application window (the context key `appWindow`:
408    /// `main` for the main window and its detached panels).
409    Window(String),
410    /// Only while that panel is the focused panel of the window the keys
411    /// are pressed in (the context key `focusedPanel`, which each window
412    /// keeps for itself): never from another window.
413    Panel(String),
414}
415
416impl KeyScope {
417    pub fn surface(name: &str) -> KeyScope {
418        KeyScope::Surface(name.into())
419    }
420
421    pub fn window(id: &str) -> KeyScope {
422        KeyScope::Window(id.into())
423    }
424
425    pub fn panel(id: &str) -> KeyScope {
426        KeyScope::Panel(id.into())
427    }
428
429    /// As in files and traces: `global`, `surface:<name>`, `system`,
430    /// `window:<id>`, `panel:<id>`.
431    pub fn parse(text: &str) -> Result<KeyScope, String> {
432        let t = text.trim();
433        let named = |prefix: &str| t.strip_prefix(prefix).filter(|n| !n.is_empty());
434        match t {
435            "" | "global" => Ok(KeyScope::Global),
436            "system" => Ok(KeyScope::System),
437            _ => {
438                if let Some(n) = named("surface:") {
439                    Ok(KeyScope::Surface(n.into()))
440                } else if let Some(n) = named("window:") {
441                    Ok(KeyScope::Window(n.into()))
442                } else if let Some(n) = named("panel:") {
443                    Ok(KeyScope::Panel(n.into()))
444                } else {
445                    Err(format!(
446                        "`{t}` is none of `global`, `system`, `surface:<name>`, `window:<id>`, `panel:<id>`"
447                    ))
448                }
449            }
450        }
451    }
452
453    /// The scope a binding declared without one gets, from its clause:
454    /// a clause requiring `focusedPanel == '<id>'` (alone or in a
455    /// conjunction) is the panel's ([`KeyScope::Panel`]); any other is
456    /// [`KeyScope::Global`]. What keymaps written before scopes existed
457    /// load as.
458    pub fn infer(when: &When) -> KeyScope {
459        fn panel(w: &When) -> Option<&str> {
460            match w {
461                When::Eq(k, v) if k == "focusedPanel" && !v.is_empty() => Some(v),
462                When::And(a, b) => panel(a).or_else(|| panel(b)),
463                _ => None,
464            }
465        }
466        panel(when).map_or(KeyScope::Global, KeyScope::panel)
467    }
468
469    /// [`KeyScope::infer`] from a clause's text; a clause that does not
470    /// parse is global.
471    pub fn infer_from(when: &str) -> KeyScope {
472        When::parse(when).map_or(KeyScope::Global, |w| KeyScope::infer(&w))
473    }
474
475    /// Whether it listens in every window (`global`, and `system`
476    /// inside the window).
477    pub fn is_global(&self) -> bool {
478        matches!(self, KeyScope::Global | KeyScope::System)
479    }
480
481    /// Whether the system delivers it while the application is not
482    /// focused.
483    pub fn is_system(&self) -> bool {
484        matches!(self, KeyScope::System)
485    }
486
487    /// Its place in the bubble order, nearer the focus higher: a surface
488    /// 3, a panel 2, a window 1, global and system 0.
489    pub fn tier(&self) -> u8 {
490        match self {
491            KeyScope::Surface(_) => 3,
492            KeyScope::Panel(_) => 2,
493            KeyScope::Window(_) => 1,
494            KeyScope::Global | KeyScope::System => 0,
495        }
496    }
497}
498
499impl fmt::Display for KeyScope {
500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501        match self {
502            KeyScope::Global => write!(f, "global"),
503            KeyScope::Surface(n) => write!(f, "surface:{n}"),
504            KeyScope::System => write!(f, "system"),
505            KeyScope::Window(n) => write!(f, "window:{n}"),
506            KeyScope::Panel(n) => write!(f, "panel:{n}"),
507        }
508    }
509}
510
511impl Serialize for KeyScope {
512    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
513        s.collect_str(self)
514    }
515}
516
517/// Whether a binding fires while a text input has the focus.
518#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
519#[serde(rename_all = "kebab-case")]
520pub enum Typing {
521    /// `always` for shortcuts with Ctrl, Alt or Meta, for function keys
522    /// and for bindings whose clause tests `textInputFocus`;
523    /// `unless-typing` for the other keys, which type or edit text.
524    #[default]
525    Auto,
526    /// Fires even while typing, and before a focused widget that reads
527    /// the key itself ([`CONTEXT_WIDGET_KEYS`]).
528    Always,
529    /// Left to the text input while one has the focus (and, global, to a
530    /// focused widget that reads the key).
531    UnlessTyping,
532}
533
534impl Typing {
535    /// `always` or `unless-typing`, for these keys.
536    pub fn effective(self, keys: &Keys) -> Typing {
537        match self {
538            Typing::Auto => {
539                let first = keys.0.first();
540                let chorded = first.is_some_and(|c| c.ctrl || c.alt || c.meta);
541                let function = first.is_some_and(|c| {
542                    c.key.len() > 1
543                        && c.key.starts_with('f')
544                        && c.key[1..].chars().all(|d| d.is_ascii_digit())
545                });
546                if chorded || function {
547                    Typing::Always
548                } else {
549                    Typing::UnlessTyping
550                }
551            }
552            other => other,
553        }
554    }
555}
556
557/// How a binding listens: its scope, whether it fires while typing, and
558/// whether a modal lets it through.
559#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
560pub struct BindOptions {
561    pub scope: KeyScope,
562    pub typing: Typing,
563    /// A global binding that still fires while a modal is open (a modal
564    /// otherwise blocks every global binding).
565    pub through_modal: bool,
566}
567
568impl BindOptions {
569    /// Global, typing decided by the keys.
570    pub fn global() -> BindOptions {
571        BindOptions::default()
572    }
573
574    /// Only while that surface has the focus.
575    pub fn surface(name: &str) -> BindOptions {
576        BindOptions {
577            scope: KeyScope::surface(name),
578            ..BindOptions::default()
579        }
580    }
581
582    /// Only in that application window ([`KeyScope::Window`]).
583    pub fn window(id: &str) -> BindOptions {
584        BindOptions {
585            scope: KeyScope::window(id),
586            ..BindOptions::default()
587        }
588    }
589
590    /// Only while that panel is its window's focused panel
591    /// ([`KeyScope::Panel`]).
592    pub fn panel(id: &str) -> BindOptions {
593        BindOptions {
594            scope: KeyScope::panel(id),
595            ..BindOptions::default()
596        }
597    }
598
599    /// Also while the application is not focused ([`KeyScope::System`]):
600    /// a global shortcut of the desktop.
601    pub fn system() -> BindOptions {
602        BindOptions {
603            scope: KeyScope::System,
604            ..BindOptions::default()
605        }
606    }
607
608    pub fn typing(mut self, typing: Typing) -> BindOptions {
609        self.typing = typing;
610        self
611    }
612
613    pub fn through_modal(mut self) -> BindOptions {
614        self.through_modal = true;
615        self
616    }
617}
618
619/// A binding as declared.
620#[derive(Clone, Debug, PartialEq, Serialize)]
621pub struct Binding {
622    pub keys: Keys,
623    pub action: Action,
624    pub when: String,
625    pub layer: Layer,
626    /// Who declared it.
627    pub owner: OwnerId,
628    /// Where it listens, while typing, through modals.
629    pub options: BindOptions,
630}
631
632#[derive(Clone, Debug)]
633struct Rule {
634    binding: Binding,
635    when: When,
636}
637
638/// What a key sequence does in a context.
639#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
640#[serde(tag = "kind", content = "command", rename_all = "lowercase")]
641pub enum Resolution {
642    /// Run this command.
643    Run(CommandId),
644    /// The keys so far start a longer shortcut: wait for the next chord.
645    Pending,
646    Nothing,
647}
648
649/// Why a candidate binding did or did not win.
650#[derive(Clone, Debug, PartialEq, Serialize)]
651#[serde(tag = "verdict", rename_all = "snake_case")]
652pub enum Verdict {
653    Won,
654    /// Another binding won over it.
655    Lost {
656        to: String,
657        because: &'static str,
658    },
659    /// Its `when` clause does not hold here.
660    WhenFalse,
661    /// Its command was removed by a higher layer.
662    RemovedBy {
663        owner: OwnerId,
664        layer: Layer,
665    },
666    /// Its keys were unbound by a higher layer.
667    UnboundBy {
668        owner: OwnerId,
669        layer: Layer,
670    },
671    /// It is longer: the keys so far are its start.
672    Prefix,
673    /// Its surface does not hold the focus.
674    SurfaceNotFocused {
675        surface: String,
676    },
677    /// The keys were pressed in another application window.
678    OtherWindow {
679        window: String,
680    },
681    /// Its panel is not the focused panel of the window the keys were
682    /// pressed in.
683    PanelNotFocused {
684        panel: String,
685    },
686    /// A text input has the focus and keeps the key.
687    LeftToTyping,
688    /// The focused widget reads the key itself and the binding is global
689    /// ([`CONTEXT_WIDGET_KEYS`]).
690    LeftToWidget,
691    /// A modal is open in the window and the binding is not a surface's.
692    BlockedByModal,
693}
694
695/// One candidate in a trace.
696#[derive(Clone, Debug, PartialEq, Serialize)]
697pub struct Candidate {
698    pub binding: Binding,
699    /// Its depth in this context: its surface's, or its clause's.
700    pub depth: u32,
701    pub verdict: Verdict,
702}
703
704/// How a key sequence was resolved: every binding considered and why.
705#[derive(Clone, Debug, PartialEq, Serialize)]
706pub struct Trace {
707    pub keys: String,
708    pub resolution: Resolution,
709    /// The winning binding's scope (`global`, `surface:<name>`).
710    pub scope: Option<String>,
711    pub candidates: Vec<Candidate>,
712}
713
714impl fmt::Display for Action {
715    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716        match self {
717            Action::Run(c) => write!(f, "{c}"),
718            Action::Remove(c) => write!(f, "-{c}"),
719            Action::Unbind => write!(f, "(unbind)"),
720        }
721    }
722}
723
724impl fmt::Display for Resolution {
725    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726        match self {
727            Resolution::Run(c) => write!(f, "runs {c}"),
728            Resolution::Pending => write!(f, "waits for the next chord"),
729            Resolution::Nothing => write!(f, "does nothing"),
730        }
731    }
732}
733
734impl fmt::Display for Verdict {
735    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736        match self {
737            Verdict::Won => write!(f, "won"),
738            Verdict::Lost { to, because } if *because == DORMANT && to.is_empty() => {
739                write!(f, "{because}")
740            }
741            Verdict::Lost { to, because } if *because == DORMANT => {
742                write!(f, "{because}; the keys go to {to}")
743            }
744            Verdict::Lost { to, because } => write!(f, "lost to {to} ({because})"),
745            Verdict::WhenFalse => write!(f, "its clause is false here"),
746            Verdict::RemovedBy { owner, layer } => {
747                write!(f, "removed by {owner} ({layer:?} layer)")
748            }
749            Verdict::UnboundBy { owner, layer } => {
750                write!(f, "unbound by {owner} ({layer:?} layer)")
751            }
752            Verdict::Prefix => write!(f, "longer: these keys start it"),
753            Verdict::SurfaceNotFocused { surface } => {
754                write!(f, "its surface `{surface}` does not have the focus")
755            }
756            Verdict::OtherWindow { window } => {
757                write!(f, "it listens in the window `{window}` only")
758            }
759            Verdict::PanelNotFocused { panel } => {
760                write!(f, "its panel `{panel}` is not this window's focused panel")
761            }
762            Verdict::LeftToTyping => write!(f, "left to the text input"),
763            Verdict::LeftToWidget => write!(f, "left to the focused widget, which reads it"),
764            Verdict::BlockedByModal => write!(f, "blocked by a modal"),
765        }
766    }
767}
768
769impl fmt::Display for Trace {
770    /// `Alt+Down: runs x`, then one line per binding considered.
771    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772        write!(f, "{}: {}", self.keys, self.resolution)?;
773        if let Some(s) = &self.scope {
774            write!(f, " ({s})")?;
775        }
776        for c in &self.candidates {
777            write!(f, "\n  {} {}", c.binding.keys, c.binding.action)?;
778            if !c.binding.when.is_empty() {
779                write!(f, " when {}", c.binding.when)?;
780            }
781            write!(
782                f,
783                " ({:?}, {}, depth {}, by {}): {}",
784                c.binding.layer, c.binding.options.scope, c.depth, c.binding.owner, c.verdict
785            )?;
786        }
787        Ok(())
788    }
789}
790
791/// A user's (or workspace's) keymap as saved: the `keymap` document.
792#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
793pub struct KeymapDoc {
794    pub bindings: Vec<DocBinding>,
795}
796
797/// A binding as saved.
798#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
799pub struct DocBinding {
800    /// Empty for a command's removal (`"-id"`), which needs no keys.
801    #[serde(default)]
802    pub keys: String,
803    /// `"id"`, `"-id"` to remove a command's bindings, `null` to unbind
804    /// the keys.
805    pub command: Option<String>,
806    #[serde(default, skip_serializing_if = "String::is_empty")]
807    pub when: String,
808    /// `global`, `surface:<name>`, `system`, `window:<id>` or
809    /// `panel:<id>`; empty or `global` with a clause requiring a panel
810    /// is that panel's ([`KeyScope::infer`]).
811    #[serde(default, skip_serializing_if = "String::is_empty")]
812    pub scope: String,
813    #[serde(default, skip_serializing_if = "is_auto")]
814    pub typing: Typing,
815    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
816    pub through_modal: bool,
817}
818
819fn is_auto(t: &Typing) -> bool {
820    *t == Typing::Auto
821}
822
823/// The bindings, by layer.
824#[derive(Clone, Debug, Default)]
825pub struct Keymap {
826    rules: OwnedList<Rule>,
827    /// Commands whose bindings are dormant.
828    dormant: std::collections::BTreeSet<CommandId>,
829}
830
831impl Keymap {
832    pub fn new() -> Self {
833        Self::default()
834    }
835
836    /// Adds a binding, its scope inferred from its clause (see
837    /// [`Keymap::bind_with`]); its keys and clause must parse.
838    pub fn bind(
839        &mut self,
840        owner: &OwnerId,
841        layer: Layer,
842        keys: &str,
843        action: Action,
844        when: &str,
845    ) -> Result<(), String> {
846        self.bind_with(owner, layer, keys, action, when, BindOptions::global())
847    }
848
849    /// Adds a binding with its scope and typing rule. A global scope is
850    /// narrowed to the panel its clause requires ([`KeyScope::infer`]:
851    /// `focusedPanel == '<id>'`), which fires exactly where the clause
852    /// holds and wins over the wider scopes.
853    pub fn bind_with(
854        &mut self,
855        owner: &OwnerId,
856        layer: Layer,
857        keys: &str,
858        action: Action,
859        when: &str,
860        options: BindOptions,
861    ) -> Result<(), String> {
862        // A command's removal needs no keys: it takes every binding of the
863        // command in the layers below.
864        let parsed = if keys.trim().is_empty() && matches!(action, Action::Remove(_)) {
865            Keys(Vec::new())
866        } else {
867            Keys::parse(keys)?
868        };
869        let w = When::parse(when).map_err(|e| format!("`{keys}`: {e}"))?;
870        let mut options = options;
871        if options.scope == KeyScope::Global {
872            options.scope = KeyScope::infer(&w);
873        }
874        self.rules.push(
875            owner,
876            Rule {
877                binding: Binding {
878                    keys: parsed,
879                    action,
880                    when: when.into(),
881                    layer,
882                    owner: owner.clone(),
883                    options,
884                },
885                when: w,
886            },
887        );
888        Ok(())
889    }
890
891    /// The rule that takes a binding away, if one does.
892    fn removed_by(&self, b: &Binding) -> Option<Verdict> {
893        for r in self.rules.iter().map(|s| &s.item) {
894            if r.binding.layer <= b.layer {
895                continue;
896            }
897            match &r.binding.action {
898                Action::Remove(c) if b.action.command() == Some(c) => {
899                    return Some(Verdict::RemovedBy {
900                        owner: r.binding.owner.clone(),
901                        layer: r.binding.layer,
902                    });
903                }
904                Action::Unbind if r.binding.keys == b.keys => {
905                    return Some(Verdict::UnboundBy {
906                        owner: r.binding.owner.clone(),
907                        layer: r.binding.layer,
908                    });
909                }
910                _ => {}
911            }
912        }
913        None
914    }
915
916    /// Makes the bindings running these commands dormant, and those of
917    /// every other command live: the commands that went with a
918    /// disconnected plugin (ADR 0028). Whether the set changed.
919    pub fn set_dormant(&mut self, commands: impl IntoIterator<Item = CommandId>) -> bool {
920        let commands: std::collections::BTreeSet<CommandId> = commands.into_iter().collect();
921        let changed = commands != self.dormant;
922        self.dormant = commands;
923        changed
924    }
925
926    /// Whether a command's bindings are dormant.
927    pub fn is_dormant(&self, command: &CommandId) -> bool {
928        self.dormant.contains(command)
929    }
930
931    /// The dormant bindings, in declaration order: those running a
932    /// command of [`Keymap::set_dormant`] that no higher layer removed
933    /// (what a shortcuts editor lists apart, with the plugin's name).
934    pub fn dormant(&self) -> Vec<Binding> {
935        let removals = Removals::of(self);
936        self.rules
937            .iter()
938            .map(|s| &s.item.binding)
939            .filter(|b| self.asleep(b) && !removals.removes(b))
940            .cloned()
941            .collect()
942    }
943
944    fn asleep(&self, b: &Binding) -> bool {
945        b.action.command().is_some_and(|c| self.dormant.contains(c))
946    }
947
948    /// The bindings in force, after removals and without the dormant
949    /// ones, with their order.
950    fn live(&self) -> impl Iterator<Item = (u64, &Rule)> {
951        // The removals are indexed once: a binding is out when a higher
952        // layer removes its command or unbinds its keys (what
953        // `removed_by` says), found without a pass over every rule for
954        // each binding.
955        let removals = Removals::of(self);
956        self.rules
957            .iter()
958            .filter(move |s| {
959                matches!(s.item.binding.action, Action::Run(_))
960                    && !self.asleep(&s.item.binding)
961                    && !removals.removes(&s.item.binding)
962            })
963            .map(|s| (s.order, &s.item))
964    }
965
966    /// Its depth here: its surface's when it has one, else its
967    /// clause's.
968    fn depth(r: &Rule, cx: &WhenContext) -> u32 {
969        let surface = match &r.binding.options.scope {
970            KeyScope::Surface(n) => cx.depth_of(&format!("{n}Focus")).unwrap_or(0),
971            _ => 0,
972        };
973        surface.max(r.when.depth(cx))
974    }
975
976    /// Nearer the focus first (its depth, then its scope's place in the
977    /// bubble order), then the higher layer, the more specific clause,
978    /// the last declared.
979    fn rank(r: &Rule, order: u64, cx: &WhenContext) -> (u32, u8, Layer, usize, u64) {
980        (
981            Self::depth(r, cx),
982            r.binding.options.scope.tier(),
983            r.binding.layer,
984            r.when.specificity(),
985            order,
986        )
987    }
988
989    /// Why a binding cannot fire here, apart from its clause: its surface
990    /// does not have the focus, a text input keeps the key, a modal
991    /// blocks it.
992    fn blocked(r: &Rule, cx: &WhenContext) -> Option<Verdict> {
993        let truthy = |k: &str| !matches!(cx.get(k), "" | "false");
994        let o = &r.binding.options;
995        if let KeyScope::Surface(n) = &o.scope
996            && cx.depth_of(&format!("{n}Focus")).is_none()
997        {
998            return Some(Verdict::SurfaceNotFocused { surface: n.clone() });
999        }
1000        if let KeyScope::Window(w) = &o.scope
1001            && cx.get("appWindow") != w
1002        {
1003            return Some(Verdict::OtherWindow { window: w.clone() });
1004        }
1005        if let KeyScope::Panel(p) = &o.scope
1006            && cx.get("focusedPanel") != p
1007        {
1008            return Some(Verdict::PanelNotFocused { panel: p.clone() });
1009        }
1010        // A clause testing `textInputFocus` decides for itself.
1011        let about_typing = r.when.keys().contains(&"textInputFocus");
1012        if o.typing.effective(&r.binding.keys) == Typing::UnlessTyping
1013            && !(o.typing == Typing::Auto && about_typing)
1014            && truthy("textInputFocus")
1015        {
1016            return Some(Verdict::LeftToTyping);
1017        }
1018        // The focused widget reads the key itself: it goes before a
1019        // global binding (one scoped to its place still goes first).
1020        if o.scope.is_global()
1021            && o.typing.effective(&r.binding.keys) == Typing::UnlessTyping
1022            && !(o.typing == Typing::Auto && r.when.keys().contains(&CONTEXT_WIDGET_KEYS))
1023            && r.binding.keys.0.first().is_some_and(|c| {
1024                cx.get(CONTEXT_WIDGET_KEYS)
1025                    .split(' ')
1026                    .any(|k| !k.is_empty() && k == c.key)
1027            })
1028        {
1029            return Some(Verdict::LeftToWidget);
1030        }
1031        // A modal blocks every binding but a surface's (a surface under a
1032        // modal does not hold the focus).
1033        if !matches!(o.scope, KeyScope::Surface(_)) && !o.through_modal && truthy("modalOpen") {
1034            return Some(Verdict::BlockedByModal);
1035        }
1036        None
1037    }
1038
1039    /// Whether a binding may fire here.
1040    fn fires(r: &Rule, cx: &WhenContext) -> bool {
1041        Self::blocked(r, cx).is_none() && r.when.eval(cx)
1042    }
1043
1044    /// The bindings declared at a layer, in order (removals included).
1045    pub fn bindings(&self, layer: Layer) -> Vec<&Binding> {
1046        self.rules
1047            .iter()
1048            .filter(|s| s.item.binding.layer == layer)
1049            .map(|s| &s.item.binding)
1050            .collect()
1051    }
1052
1053    /// Every binding, in declaration order.
1054    pub fn all(&self) -> impl Iterator<Item = &Binding> {
1055        self.rules.iter().map(|s| &s.item.binding)
1056    }
1057
1058    /// Forgets every binding of a layer (before loading another profile).
1059    pub fn clear(&mut self, layer: Layer) {
1060        self.rules.retain(|s| s.item.binding.layer != layer);
1061    }
1062
1063    /// Forgets an owner's bindings; returns how many.
1064    pub fn remove_owner(&mut self, owner: &OwnerId) -> usize {
1065        self.rules.remove_owner(owner)
1066    }
1067
1068    /// What pressing `keys` (the chords so far) does here.
1069    pub fn resolve(&self, keys: &Keys, cx: &WhenContext) -> Resolution {
1070        let winner = self
1071            .live()
1072            .filter(|(_, r)| &r.binding.keys == keys && Self::fires(r, cx))
1073            .max_by_key(|(o, r)| Self::rank(r, *o, cx));
1074        if let Some((_, r)) = winner
1075            && let Action::Run(c) = &r.binding.action
1076        {
1077            return Resolution::Run(c.clone());
1078        }
1079        let longer = self.live().any(|(_, r)| {
1080            r.binding.keys.0.len() > keys.0.len()
1081                && r.binding.keys.0.starts_with(&keys.0)
1082                && Self::fires(r, cx)
1083        });
1084        if longer {
1085            Resolution::Pending
1086        } else {
1087            Resolution::Nothing
1088        }
1089    }
1090
1091    /// Resolves and says why: every binding of these keys or starting
1092    /// with them, with its verdict.
1093    pub fn resolve_traced(&self, keys: &Keys, cx: &WhenContext) -> (Resolution, Trace) {
1094        let resolution = self.resolve(keys, cx);
1095        let winner = self
1096            .live()
1097            .filter(|(_, r)| &r.binding.keys == keys && Self::fires(r, cx))
1098            .max_by_key(|(o, r)| Self::rank(r, *o, cx))
1099            .map(|(o, r)| {
1100                (
1101                    o,
1102                    Self::rank(r, o, cx),
1103                    r.binding.action.clone(),
1104                    r.binding.options.scope.to_string(),
1105                )
1106            });
1107        let mut candidates = Vec::new();
1108        for s in self.rules.iter() {
1109            let r = &s.item;
1110            if !matches!(r.binding.action, Action::Run(_)) {
1111                continue;
1112            }
1113            let exact = &r.binding.keys == keys;
1114            let prefix =
1115                r.binding.keys.0.len() > keys.0.len() && r.binding.keys.0.starts_with(&keys.0);
1116            if !exact && !prefix {
1117                continue;
1118            }
1119            let verdict = if let Some(v) = self.removed_by(&r.binding) {
1120                v
1121            } else if self.asleep(&r.binding) {
1122                Verdict::Lost {
1123                    to: winner
1124                        .as_ref()
1125                        .filter(|_| exact)
1126                        .and_then(|w| w.2.to_file())
1127                        .unwrap_or_default(),
1128                    because: DORMANT,
1129                }
1130            } else if let Some(v) = Self::blocked(r, cx) {
1131                v
1132            } else if !r.when.eval(cx) {
1133                Verdict::WhenFalse
1134            } else if prefix {
1135                Verdict::Prefix
1136            } else {
1137                match &winner {
1138                    Some((o, _, _, _)) if *o == s.order => Verdict::Won,
1139                    Some((_, rank, action, _)) => {
1140                        let mine = Self::rank(r, s.order, cx);
1141                        let because = if rank.0 != mine.0 {
1142                            "nearer the focus"
1143                        } else if rank.1 != mine.1 {
1144                            "narrower scope"
1145                        } else if rank.2 != mine.2 {
1146                            "higher layer"
1147                        } else if rank.3 != mine.3 {
1148                            "more specific clause"
1149                        } else {
1150                            "declared later"
1151                        };
1152                        Verdict::Lost {
1153                            to: action.to_file().unwrap_or_default(),
1154                            because,
1155                        }
1156                    }
1157                    None => Verdict::WhenFalse,
1158                }
1159            };
1160            candidates.push(Candidate {
1161                binding: r.binding.clone(),
1162                depth: Self::depth(r, cx),
1163                verdict,
1164            });
1165        }
1166        let trace = Trace {
1167            keys: keys.to_string(),
1168            resolution: resolution.clone(),
1169            scope: winner.map(|w| w.3),
1170            candidates,
1171        };
1172        (resolution, trace)
1173    }
1174
1175    /// The live bindings in the [`KeyScope::System`] scope: what a
1176    /// plugin registers with the system as global shortcuts, each
1177    /// command once per keys.
1178    pub fn system_bindings(&self) -> Vec<Binding> {
1179        let mut out: Vec<Binding> = Vec::new();
1180        for (_, r) in self.live() {
1181            let b = &r.binding;
1182            if b.options.scope.is_system()
1183                && !out.iter().any(|o| o.keys == b.keys && o.action == b.action)
1184            {
1185                out.push(b.clone());
1186            }
1187        }
1188        out
1189    }
1190
1191    /// The live bindings of pointer gestures ([`Pointer`]), one per scope
1192    /// and gesture: the winner among those of the same keys in the same
1193    /// scope by layer, then the clause testing more keys, then the last
1194    /// declared (the order [`Keymap::conflicts`] reports). Clauses are
1195    /// not evaluated: a canvas reads this table once per change of the
1196    /// keymap.
1197    pub fn pointer_bindings(&self) -> Vec<Binding> {
1198        let mut out: Vec<(Binding, (Layer, usize, u64))> = Vec::new();
1199        for (order, r) in self.live() {
1200            if r.binding.keys.pointer().is_none() {
1201                continue;
1202            }
1203            let rank = (r.binding.layer, r.when.specificity(), order);
1204            match out.iter_mut().find(|(b, _)| {
1205                b.keys == r.binding.keys && b.options.scope == r.binding.options.scope
1206            }) {
1207                Some(slot) if rank > slot.1 => *slot = (r.binding.clone(), rank),
1208                Some(_) => {}
1209                None => out.push((r.binding.clone(), rank)),
1210            }
1211        }
1212        out.into_iter().map(|(b, _)| b).collect()
1213    }
1214
1215    /// The keys bound to a command (what menus and tooltips show).
1216    pub fn keys_for(&self, command: &CommandId) -> Vec<Keys> {
1217        let mut keys: Vec<Keys> = self
1218            .live()
1219            .filter(|(_, r)| r.binding.action.command() == Some(command))
1220            .map(|(_, r)| r.binding.keys.clone())
1221            .collect();
1222        keys.sort();
1223        keys.dedup();
1224        keys
1225    }
1226
1227    /// The live bindings running a command, with the layer each comes
1228    /// from (what a shortcuts editor shows as their source), by keys.
1229    pub fn sources_for(&self, command: &CommandId) -> Vec<Binding> {
1230        let mut out: Vec<Binding> = self
1231            .live()
1232            .filter(|(_, r)| r.binding.action.command() == Some(command))
1233            .map(|(_, r)| r.binding.clone())
1234            .collect();
1235        out.sort_by(|a, b| a.keys.cmp(&b.keys).then(b.layer.cmp(&a.layer)));
1236        out.dedup_by(|b, a| a.keys == b.keys);
1237        out
1238    }
1239
1240    /// Bindings sharing keys with another of the same or a higher layer
1241    /// that wins over them (ignoring focus depth, which only the moment
1242    /// decides): what a shortcuts editor shows as conflicts. Two whose
1243    /// `when` clauses can never both hold (`When::excludes`) are none.
1244    pub fn conflicts(&self) -> Vec<(Binding, Binding)> {
1245        let live: Vec<(u64, &Rule)> = self.live().collect();
1246        let mut out = Vec::new();
1247        for (i, (oa, a)) in live.iter().enumerate() {
1248            for (ob, b) in &live[i + 1..] {
1249                // A system binding listens in the whole window too.
1250                let same_scope = a.binding.options.scope == b.binding.options.scope
1251                    || (a.binding.options.scope.is_global() && b.binding.options.scope.is_global());
1252                // Clauses that never hold together never compete.
1253                if a.binding.keys == b.binding.keys
1254                    && same_scope
1255                    && a.binding.action != b.binding.action
1256                    && !a.when.excludes(&b.when)
1257                {
1258                    let ka = (a.binding.layer, a.when.specificity(), *oa);
1259                    let kb = (b.binding.layer, b.when.specificity(), *ob);
1260                    let (lose, win) = if ka < kb { (a, b) } else { (b, a) };
1261                    out.push((lose.binding.clone(), win.binding.clone()));
1262                }
1263            }
1264        }
1265        out
1266    }
1267
1268    /// [`Keymap::conflicts`], by scope (`global`, `surface:<name>`).
1269    pub fn conflicts_by_scope(
1270        &self,
1271    ) -> std::collections::BTreeMap<String, Vec<(Binding, Binding)>> {
1272        let mut out: std::collections::BTreeMap<String, Vec<(Binding, Binding)>> =
1273            std::collections::BTreeMap::new();
1274        for (lose, win) in self.conflicts() {
1275            out.entry(lose.options.scope.to_string())
1276                .or_default()
1277                .push((lose, win));
1278        }
1279        out
1280    }
1281
1282    /// Every binding of a layer, whoever declared it, as saved.
1283    pub fn export_layer(&self, layer: Layer) -> KeymapDoc {
1284        KeymapDoc {
1285            bindings: self
1286                .rules
1287                .iter()
1288                .filter(|s| s.item.binding.layer == layer)
1289                .map(|s| doc_binding(&s.item.binding))
1290                .collect(),
1291        }
1292    }
1293
1294    /// Removes an owner's bindings running a command, in every layer;
1295    /// returns how many.
1296    pub fn remove_command(&mut self, owner: &OwnerId, command: &CommandId) -> usize {
1297        let before = self.rules.iter().count();
1298        self.rules.retain(|s| {
1299            !(s.owner == *owner
1300                && matches!(&s.item.binding.action, Action::Run(c) | Action::Remove(c) if c == command))
1301        });
1302        before - self.rules.iter().count()
1303    }
1304
1305    /// Gives a command new keys in `layer` (the user's, from a shortcuts
1306    /// editor): the owner's earlier rules there about the command go, the
1307    /// command's bindings in the layers below are removed (a removal with
1308    /// no keys), and `keys` (none: no key at all) run it, typing decided
1309    /// by the keys, in the scope of the binding it replaces (the highest
1310    /// layer's below; global when the command had none): a system
1311    /// shortcut stays one.
1312    pub fn rebind(
1313        &mut self,
1314        owner: &OwnerId,
1315        layer: Layer,
1316        command: &CommandId,
1317        keys: Option<&str>,
1318    ) -> Result<(), String> {
1319        let parsed = keys.map(Keys::parse).transpose()?;
1320        let (when, options) = self.declared(layer, command);
1321        self.reset(owner, layer, command);
1322        self.bind(owner, layer, "", Action::Remove(command.clone()), "")?;
1323        if let Some(k) = parsed {
1324            self.bind_with(
1325                owner,
1326                layer,
1327                &k.to_string(),
1328                Action::Run(command.clone()),
1329                &when,
1330                options,
1331            )?;
1332        }
1333        Ok(())
1334    }
1335
1336    /// How a command's keys listen below `layer`: their clause and options,
1337    /// which a rebound key keeps; only the keys change.
1338    fn declared(&self, layer: Layer, command: &CommandId) -> (String, BindOptions) {
1339        self.rules
1340            .iter()
1341            .filter(|s| {
1342                s.item.binding.layer < layer
1343                    && s.item.binding.action == Action::Run(command.clone())
1344            })
1345            .max_by_key(|s| s.item.binding.layer)
1346            .map(|s| (s.item.binding.when.clone(), s.item.binding.options.clone()))
1347            .unwrap_or_default()
1348    }
1349
1350    /// [`Keymap::rebind`] with several keys at once (none: no key at
1351    /// all): what a pointer gesture keeps when one of its gestures is
1352    /// added or taken away (`Wheel`, `Ctrl+Scroll`, `Pinch` all zoom).
1353    pub fn rebind_all(
1354        &mut self,
1355        owner: &OwnerId,
1356        layer: Layer,
1357        command: &CommandId,
1358        keys: &[&str],
1359    ) -> Result<(), String> {
1360        let parsed = keys
1361            .iter()
1362            .map(|k| Keys::parse(k))
1363            .collect::<Result<Vec<_>, _>>()?;
1364        let (when, options) = self.declared(layer, command);
1365        self.reset(owner, layer, command);
1366        self.bind(owner, layer, "", Action::Remove(command.clone()), "")?;
1367        for k in parsed {
1368            self.bind_with(
1369                owner,
1370                layer,
1371                &k.to_string(),
1372                Action::Run(command.clone()),
1373                &when,
1374                options.clone(),
1375            )?;
1376        }
1377        Ok(())
1378    }
1379
1380    /// Takes back what [`Keymap::rebind`] did: the owner's rules in
1381    /// `layer` running or removing the command go. Returns how many.
1382    pub fn reset(&mut self, owner: &OwnerId, layer: Layer, command: &CommandId) -> usize {
1383        let before = self.rules.iter().count();
1384        self.rules.retain(|s| {
1385            !(s.owner == *owner
1386                && s.item.binding.layer == layer
1387                && matches!(&s.item.binding.action, Action::Run(c) | Action::Remove(c) if c == command))
1388        });
1389        before - self.rules.iter().count()
1390    }
1391
1392    /// Whether the owner changed the command's keys in `layer`.
1393    pub fn rebound(&self, owner: &OwnerId, layer: Layer, command: &CommandId) -> bool {
1394        self.rules.iter().any(|s| {
1395            s.owner == *owner
1396                && s.item.binding.layer == layer
1397                && matches!(&s.item.binding.action, Action::Run(c) | Action::Remove(c) if c == command)
1398        })
1399    }
1400
1401    /// Loads a saved keymap into a layer, owned by `owner`, replacing
1402    /// that owner's bindings there. Entries that do not parse are skipped
1403    /// and reported.
1404    pub fn load(&mut self, owner: &OwnerId, layer: Layer, doc: &KeymapDoc) -> Diagnostics {
1405        self.rules
1406            .retain(|s| !(s.owner == *owner && s.item.binding.layer == layer));
1407        let mut d = Diagnostics::new();
1408        for b in &doc.bindings {
1409            let result = Action::parse(b.command.as_deref()).and_then(|a| {
1410                let options = BindOptions {
1411                    scope: KeyScope::parse(&b.scope)?,
1412                    typing: b.typing,
1413                    through_modal: b.through_modal,
1414                };
1415                self.bind_with(owner, layer, &b.keys, a, &b.when, options)
1416            });
1417            if let Err(e) = result {
1418                d.warn(
1419                    "bad-binding",
1420                    Some(owner),
1421                    &b.keys,
1422                    format!("{e}: this binding is skipped"),
1423                );
1424            }
1425        }
1426        d
1427    }
1428
1429    /// An owner's bindings of a layer, as saved.
1430    pub fn export(&self, owner: &OwnerId, layer: Layer) -> KeymapDoc {
1431        KeymapDoc {
1432            bindings: self
1433                .rules
1434                .iter()
1435                .filter(|s| s.owner == *owner && s.item.binding.layer == layer)
1436                .map(|s| doc_binding(&s.item.binding))
1437                .collect(),
1438        }
1439    }
1440}
1441
1442/// The highest layer removing each command and unbinding each set of
1443/// keys: whether a binding is taken away, in one lookup.
1444struct Removals<'a> {
1445    commands: std::collections::HashMap<&'a CommandId, Layer>,
1446    keys: std::collections::HashMap<&'a Keys, Layer>,
1447}
1448
1449impl<'a> Removals<'a> {
1450    fn of(keymap: &'a Keymap) -> Removals<'a> {
1451        let mut out = Removals {
1452            commands: std::collections::HashMap::new(),
1453            keys: std::collections::HashMap::new(),
1454        };
1455        for r in keymap.rules.iter().map(|s| &s.item.binding) {
1456            let slot = match &r.action {
1457                Action::Remove(c) => out.commands.entry(c).or_insert(r.layer),
1458                Action::Unbind => out.keys.entry(&r.keys).or_insert(r.layer),
1459                Action::Run(_) => continue,
1460            };
1461            *slot = (*slot).max(r.layer);
1462        }
1463        out
1464    }
1465
1466    /// Whether a higher layer removes the binding's command or unbinds
1467    /// its keys (as `Keymap::removed_by` finds).
1468    fn removes(&self, b: &Binding) -> bool {
1469        b.action
1470            .command()
1471            .and_then(|c| self.commands.get(c))
1472            .is_some_and(|l| *l > b.layer)
1473            || self.keys.get(&b.keys).is_some_and(|l| *l > b.layer)
1474    }
1475}
1476
1477/// A binding as saved.
1478fn doc_binding(b: &Binding) -> DocBinding {
1479    let o = &b.options;
1480    DocBinding {
1481        keys: b.keys.to_string(),
1482        command: b.action.to_file(),
1483        when: b.when.clone(),
1484        // Left out when loading would infer it from the clause.
1485        scope: if o.scope == KeyScope::infer_from(&b.when) {
1486            String::new()
1487        } else {
1488            o.scope.to_string()
1489        },
1490        typing: o.typing,
1491        through_modal: o.through_modal,
1492    }
1493}
1494
1495/// Version 3 of the keymap document lets a chord be a pointer gesture
1496/// (`Ctrl+Wheel`, `MiddleDrag`); version 2 documents read the same.
1497pub fn pointer_chords(json: serde_json::Value) -> Result<serde_json::Value, String> {
1498    Ok(json)
1499}
1500
1501/// Version 1 of the keymap document gave a command's removal a
1502/// placeholder key (`Ctrl+Alt+Shift+F24`); version 2 gives it none.
1503pub fn drop_placeholder_keys(mut json: serde_json::Value) -> Result<serde_json::Value, String> {
1504    if let Some(list) = json
1505        .get_mut("bindings")
1506        .and_then(serde_json::Value::as_array_mut)
1507    {
1508        for b in list {
1509            let removal = b
1510                .get("command")
1511                .and_then(serde_json::Value::as_str)
1512                .is_some_and(|c| c.starts_with('-'));
1513            if removal
1514                && b.get("keys").and_then(serde_json::Value::as_str) == Some("Ctrl+Alt+Shift+F24")
1515            {
1516                b["keys"] = serde_json::Value::String(String::new());
1517            }
1518        }
1519    }
1520    Ok(json)
1521}
1522
1523/// What loading a keymap document changes, against what was there.
1524#[derive(Clone, Debug, Default, PartialEq, Serialize)]
1525pub struct KeymapDiff {
1526    /// Bindings the document adds.
1527    pub added: Vec<DocBinding>,
1528    /// Bindings it drops.
1529    pub removed: Vec<DocBinding>,
1530    /// Bindings on the same keys, scope and clause whose command changed:
1531    /// before, after.
1532    pub changed: Vec<(DocBinding, DocBinding)>,
1533    /// Bindings that do not parse, skipped.
1534    pub skipped: Vec<String>,
1535    /// Keys two commands claim in one scope after the load: loser, winner.
1536    pub conflicts: Vec<String>,
1537}
1538
1539impl KeymapDiff {
1540    /// Compares two documents of one layer.
1541    pub fn between(before: &KeymapDoc, after: &KeymapDoc) -> KeymapDiff {
1542        let key = |b: &DocBinding| (b.keys.clone(), b.scope.clone(), b.when.clone());
1543        let mut added: Vec<DocBinding> = after
1544            .bindings
1545            .iter()
1546            .filter(|b| !before.bindings.contains(b))
1547            .cloned()
1548            .collect();
1549        let mut removed: Vec<DocBinding> = before
1550            .bindings
1551            .iter()
1552            .filter(|b| !after.bindings.contains(b))
1553            .cloned()
1554            .collect();
1555        let mut changed = Vec::new();
1556        removed.retain(|r| match added.iter().position(|a| key(a) == key(r)) {
1557            Some(i) => {
1558                changed.push((r.clone(), added.remove(i)));
1559                false
1560            }
1561            None => true,
1562        });
1563        KeymapDiff {
1564            added,
1565            removed,
1566            changed,
1567            skipped: Vec::new(),
1568            conflicts: Vec::new(),
1569        }
1570    }
1571
1572    /// Whether nothing changes.
1573    pub fn is_empty(&self) -> bool {
1574        self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
1575    }
1576}