1use 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
56pub const DORMANT: &str = "dormant: its command's plugin is disconnected";
61
62pub const CONTEXT_WIDGET_KEYS: &str = "focusedWidgetKeys";
69
70#[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#[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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
115pub enum Pointer {
116 Wheel,
118 Scroll,
121 Pinch,
125 Click(Button),
127 DoubleClick(Button),
128 Drag(Button),
130}
131
132impl Pointer {
133 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 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 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 pub fn is_wheel(self) -> bool {
164 matches!(self, Pointer::Wheel | Pointer::Scroll | Pointer::Pinch)
165 }
166
167 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#[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 pub key: String,
187}
188
189impl Chord {
190 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 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 pub fn pointer_gesture(pointer: Pointer) -> Chord {
230 Chord::key(&pointer.name())
231 }
232
233 pub fn pointer(&self) -> Option<Pointer> {
235 Pointer::parse(&self.key)
236 }
237
238 pub fn is_pointer(&self) -> bool {
240 self.pointer().is_some()
241 }
242
243 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 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
267fn 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#[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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
340#[serde(tag = "action", content = "command", rename_all = "lowercase")]
341pub enum Action {
342 Run(CommandId),
344 Remove(CommandId),
346 Unbind,
348}
349
350impl Action {
351 pub fn run(id: &'static str) -> Action {
353 Action::Run(CommandId::from_static(id))
354 }
355
356 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 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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
394pub enum KeyScope {
395 #[default]
398 Global,
399 Surface(String),
402 System,
407 Window(String),
410 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 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 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 pub fn infer_from(when: &str) -> KeyScope {
472 When::parse(when).map_or(KeyScope::Global, |w| KeyScope::infer(&w))
473 }
474
475 pub fn is_global(&self) -> bool {
478 matches!(self, KeyScope::Global | KeyScope::System)
479 }
480
481 pub fn is_system(&self) -> bool {
484 matches!(self, KeyScope::System)
485 }
486
487 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
519#[serde(rename_all = "kebab-case")]
520pub enum Typing {
521 #[default]
525 Auto,
526 Always,
529 UnlessTyping,
532}
533
534impl Typing {
535 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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
560pub struct BindOptions {
561 pub scope: KeyScope,
562 pub typing: Typing,
563 pub through_modal: bool,
566}
567
568impl BindOptions {
569 pub fn global() -> BindOptions {
571 BindOptions::default()
572 }
573
574 pub fn surface(name: &str) -> BindOptions {
576 BindOptions {
577 scope: KeyScope::surface(name),
578 ..BindOptions::default()
579 }
580 }
581
582 pub fn window(id: &str) -> BindOptions {
584 BindOptions {
585 scope: KeyScope::window(id),
586 ..BindOptions::default()
587 }
588 }
589
590 pub fn panel(id: &str) -> BindOptions {
593 BindOptions {
594 scope: KeyScope::panel(id),
595 ..BindOptions::default()
596 }
597 }
598
599 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#[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 pub owner: OwnerId,
628 pub options: BindOptions,
630}
631
632#[derive(Clone, Debug)]
633struct Rule {
634 binding: Binding,
635 when: When,
636}
637
638#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
640#[serde(tag = "kind", content = "command", rename_all = "lowercase")]
641pub enum Resolution {
642 Run(CommandId),
644 Pending,
646 Nothing,
647}
648
649#[derive(Clone, Debug, PartialEq, Serialize)]
651#[serde(tag = "verdict", rename_all = "snake_case")]
652pub enum Verdict {
653 Won,
654 Lost {
656 to: String,
657 because: &'static str,
658 },
659 WhenFalse,
661 RemovedBy {
663 owner: OwnerId,
664 layer: Layer,
665 },
666 UnboundBy {
668 owner: OwnerId,
669 layer: Layer,
670 },
671 Prefix,
673 SurfaceNotFocused {
675 surface: String,
676 },
677 OtherWindow {
679 window: String,
680 },
681 PanelNotFocused {
684 panel: String,
685 },
686 LeftToTyping,
688 LeftToWidget,
691 BlockedByModal,
693}
694
695#[derive(Clone, Debug, PartialEq, Serialize)]
697pub struct Candidate {
698 pub binding: Binding,
699 pub depth: u32,
701 pub verdict: Verdict,
702}
703
704#[derive(Clone, Debug, PartialEq, Serialize)]
706pub struct Trace {
707 pub keys: String,
708 pub resolution: Resolution,
709 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 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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
793pub struct KeymapDoc {
794 pub bindings: Vec<DocBinding>,
795}
796
797#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
799pub struct DocBinding {
800 #[serde(default)]
802 pub keys: String,
803 pub command: Option<String>,
806 #[serde(default, skip_serializing_if = "String::is_empty")]
807 pub when: String,
808 #[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#[derive(Clone, Debug, Default)]
825pub struct Keymap {
826 rules: OwnedList<Rule>,
827 dormant: std::collections::BTreeSet<CommandId>,
829}
830
831impl Keymap {
832 pub fn new() -> Self {
833 Self::default()
834 }
835
836 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 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 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 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 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 pub fn is_dormant(&self, command: &CommandId) -> bool {
928 self.dormant.contains(command)
929 }
930
931 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 fn live(&self) -> impl Iterator<Item = (u64, &Rule)> {
951 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 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 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 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 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 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 if !matches!(o.scope, KeyScope::Surface(_)) && !o.through_modal && truthy("modalOpen") {
1034 return Some(Verdict::BlockedByModal);
1035 }
1036 None
1037 }
1038
1039 fn fires(r: &Rule, cx: &WhenContext) -> bool {
1041 Self::blocked(r, cx).is_none() && r.when.eval(cx)
1042 }
1043
1044 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 pub fn all(&self) -> impl Iterator<Item = &Binding> {
1055 self.rules.iter().map(|s| &s.item.binding)
1056 }
1057
1058 pub fn clear(&mut self, layer: Layer) {
1060 self.rules.retain(|s| s.item.binding.layer != layer);
1061 }
1062
1063 pub fn remove_owner(&mut self, owner: &OwnerId) -> usize {
1065 self.rules.remove_owner(owner)
1066 }
1067
1068 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
1442struct 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 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
1477fn 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 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
1495pub fn pointer_chords(json: serde_json::Value) -> Result<serde_json::Value, String> {
1498 Ok(json)
1499}
1500
1501pub 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#[derive(Clone, Debug, Default, PartialEq, Serialize)]
1525pub struct KeymapDiff {
1526 pub added: Vec<DocBinding>,
1528 pub removed: Vec<DocBinding>,
1530 pub changed: Vec<(DocBinding, DocBinding)>,
1533 pub skipped: Vec<String>,
1535 pub conflicts: Vec<String>,
1537}
1538
1539impl KeymapDiff {
1540 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 pub fn is_empty(&self) -> bool {
1574 self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
1575 }
1576}