forge
Explore
Log in

Don't you dare go Hollow

binds: allow bare modifier keys and Mod as bind triggers

Browse files at this commit

1b16c765db07b3be065e0086d1fd6db8925b9bb2Justin SpeddingParent: 600ec86
This intentionally introduces a new config parse error:

binds {
    Alt_L { spawn "alacritty"; }
    Alt+Alt_L { spawn "alacritty"; }
}

This used to parse before (only one of the binds worked though). Now
these are considered the same bind, so this config will error
accordingly.
docs/wiki/Configuration:-Key-Bindings.mdmodified+20 -1
@@ -15,7 +15,8 @@ binds {
15 }15 }
16 ```16 ```
17 17
18-The hotkey consists of modifiers separated by `+` signs, followed by an XKB key name in the end.18+The hotkey consists of modifiers separated by `+` signs, followed by a trigger key in the end.
19+The trigger key can be either an XKB key name or <sup>Since: next release</sup> a modifier.
19 20
20 Valid modifiers are:21 Valid modifiers are:
21 22
@@ -31,6 +32,24 @@ Valid modifiers are:
31 This way, you can test niri in a window without causing too many conflicts with the host compositor's key bindings.32 This way, you can test niri in a window without causing too many conflicts with the host compositor's key bindings.
32 For this reason, most of the default keys use the `Mod` modifier.33 For this reason, most of the default keys use the `Mod` modifier.
33 34
35+Specific left or right modifier keys like `Alt_L` or `Alt_R` can be used as triggers, but not as modifiers:
36+
37+```kdl
38+binds {
39+ // Valid:
40+ Ctrl+Alt_L { spawn "alacritty"; }
41+
42+ // Invalid:
43+ // Alt_L+Ctrl { spawn "alacritty"; }
44+
45+ // Also, this is equivalent to just Alt_L
46+ // because Alt_L implies the Alt modifier:
47+ Alt+Alt_L { spawn "the Alt here is unnecessary but allowed"; }
48+ // This is the same:
49+ // Alt_L { spawn "alacritty"; }
50+}
51+```
52+
34 <sup>Since: 25.05</sup> You can customize the `Mod` key [in the `input` section of the config](./Configuration:-Input.md#mod-key-mod-key-nested).53 <sup>Since: 25.05</sup> You can customize the `Mod` key [in the `input` section of the config](./Configuration:-Input.md#mod-key-mod-key-nested).
35 54
36 > [!TIP]55 > [!TIP]
docs/wiki/Configuration:-Recent-Windows.mdmodified+17 -1
@@ -167,7 +167,23 @@ recent-windows {
167 The recent windows binds have lower precedence than the [normal binds](./Configuration:-Key-Bindings.md), meaning that if you have <kbd>Alt</kbd><kbd>Tab</kbd> bound to something else in the normal binds, the `recent-windows` bind won't work.167 The recent windows binds have lower precedence than the [normal binds](./Configuration:-Key-Bindings.md), meaning that if you have <kbd>Alt</kbd><kbd>Tab</kbd> bound to something else in the normal binds, the `recent-windows` bind won't work.
168 In this case, you can remove the conflicting normal bind.168 In this case, you can remove the conflicting normal bind.
169 169
170-All binds in this section must have a modifier key like <kbd>Alt</kbd> or <kbd>Mod</kbd> because the recent windows switcher remains open only while you hold any modifier key.170+All binds in this section must have a modifier key like <kbd>Alt</kbd> or <kbd>Mod</kbd> (that isn't the same as the trigger key) because the recent windows switcher remains open only while you hold any modifier key.
171+
172+```kdl
173+recent-windows {
174+ binds {
175+ // Allowed: has a modifier, two keys.
176+ Ctrl+Alt { next-window; }
177+
178+ // Not allowed: only a single key.
179+ // Alt { next-window; }
180+
181+ // Not allowed: modifier matches the key
182+ // (effectively only a single key).
183+ // Alt+Alt_L { next-window; }
184+ }
185+}
186+```
171 187
172 #### Bindings inside the switcher188 #### Bindings inside the switcher
173 189
niri-config/src/binds.rsmodified+275 -12
@@ -10,7 +10,9 @@ use niri_ipc::{
10 use smithay::input::keyboard::keysyms::KEY_NoSymbol;10 use smithay::input::keyboard::keysyms::KEY_NoSymbol;
11 use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE, KEYSYM_NO_FLAGS};11 use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE, KEYSYM_NO_FLAGS};
12 use smithay::input::keyboard::Keysym;12 use smithay::input::keyboard::Keysym;
13+use tracing::warn;
13 14
15+use crate::input::ModKey;
14 use crate::recent_windows::{MruDirection, MruFilter, MruScope};16 use crate::recent_windows::{MruDirection, MruFilter, MruScope};
15 use crate::utils::{expect_only_children, MergeWith};17 use crate::utils::{expect_only_children, MergeWith};
16 18
@@ -37,6 +39,8 @@ pub struct Key {
37 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]39 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
38 pub enum Trigger {40 pub enum Trigger {
39 Keysym(Keysym),41 Keysym(Keysym),
42+ CompositorMod,
43+ Modifier(ModKey),
40 MouseLeft,44 MouseLeft,
41 MouseRight,45 MouseRight,
42 MouseMiddle,46 MouseMiddle,
@@ -55,6 +59,75 @@ pub enum Trigger {
55 TabletStylusButton3,59 TabletStylusButton3,
56 }60 }
57 61
62+/// Returns whether `keysym` is a modifier key like `Shift_L`.
63+///
64+/// This function matches what the niri config considers modifiers.
65+/// So, it does not correspond exactly to `keysym.is_modifier_key()`.
66+/// For example, unlike XKB, `Caps_Lock` and `ISO_Next_Group` aren't considered modifiers.
67+pub fn is_keysym_modifier(keysym: Keysym) -> bool {
68+ ModKey::from_keysym(keysym).is_some()
69+}
70+
71+impl Trigger {
72+ pub fn is_modifier(self) -> bool {
73+ match self {
74+ Self::CompositorMod | Self::Modifier(_) => true,
75+ Self::Keysym(keysym) => is_keysym_modifier(keysym),
76+ _ => false,
77+ }
78+ }
79+
80+ /// The modifier flags that this trigger sets, if it is a modifier key.
81+ pub fn implied_modifier(self) -> Modifiers {
82+ match self {
83+ Self::CompositorMod => Modifiers::COMPOSITOR,
84+ Self::Modifier(modifier) => modifier.to_modifiers(),
85+ Self::Keysym(keysym) => ModKey::from_keysym(keysym)
86+ .map_or(Modifiers::empty(), |modifier| modifier.to_modifiers()),
87+ _ => Modifiers::empty(),
88+ }
89+ }
90+
91+ /// Whether the same key press can trigger both of these triggers.
92+ fn overlaps(self, other: Self) -> bool {
93+ match (self, other) {
94+ (Self::Modifier(modifier), Self::Keysym(keysym))
95+ | (Self::Keysym(keysym), Self::Modifier(modifier)) => modifier.matches_keysym(keysym),
96+ (a, b) => a == b,
97+ }
98+ }
99+
100+ pub fn is_keyboard(self) -> bool {
101+ matches!(
102+ self,
103+ Trigger::Keysym(_) | Trigger::CompositorMod | Trigger::Modifier(_)
104+ )
105+ }
106+}
107+
108+impl Key {
109+ /// Whether the two keys are triggered by the same key press.
110+ ///
111+ /// Two different keybinds can be triggered by the same key press. For example, a modifier key
112+ /// can be spelled as the modifier itself (`Alt`) or as its keysym (`Alt_L`).
113+ pub fn conflicts_with(&self, other: &Self) -> bool {
114+ // The trigger and the modifiers match exactly.
115+ //
116+ // All non-modifier triggers fall into this category.
117+ if *self == *other {
118+ return true;
119+ }
120+
121+ // Modifiers include the trigger's implied modifier, so differing modifiers can never be
122+ // triggered by the same key press.
123+ if self.modifiers != other.modifiers {
124+ return false;
125+ }
126+
127+ self.trigger.overlaps(other.trigger)
128+ }
129+}
130+
58 bitflags! {131 bitflags! {
59 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]132 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60 pub struct Modifiers : u8 {133 pub struct Modifiers : u8 {
@@ -786,7 +859,9 @@ where
786 ctx.emit_error(e);859 ctx.emit_error(e);
787 }860 }
788 Ok(bind) => {861 Ok(bind) => {
789- let conflict = binds.iter().position(|prev| prev.key == bind.key);862+ let conflict = binds
863+ .iter()
864+ .position(|prev| prev.key.conflicts_with(&bind.key));
790 if let Some(idx) = conflict {865 if let Some(idx) = conflict {
791 // Even though it's technically incorrect, we use866 // Even though it's technically incorrect, we use
792 // `DecodeError::Missing` here because it labels the bind with867 // `DecodeError::Missing` here because it labels the bind with
@@ -799,7 +874,11 @@ where
799 ctx.emit_error(DecodeError::unexpected(874 ctx.emit_error(DecodeError::unexpected(
800 &child.node_name,875 &child.node_name,
801 "keybind",876 "keybind",
802- "duplicate keybind later defined here",877+ if binds[idx].key == bind.key {
878+ "duplicate keybind later defined here"
879+ } else {
880+ "conflicting keybind later defined here"
881+ },
803 ));882 ));
804 } else {883 } else {
805 nodes.push(child);884 nodes.push(child);
@@ -952,34 +1031,36 @@ impl FromStr for Key {
952 return Err(miette!("invalid key with a null byte: {s:?}"));1031 return Err(miette!("invalid key with a null byte: {s:?}"));
953 }1032 }
954 1033
955- let mut modifiers = Modifiers::empty();1034+ let mut written_modifiers: Vec<(Modifiers, &str)> = Vec::new();
956 1035
957 let mut split = s.split('+');1036 let mut split = s.split('+');
958 let key = split.next_back().unwrap();1037 let key = split.next_back().unwrap();
959 1038
960 for part in split {1039 for part in split {
961 let part = part.trim();1040 let part = part.trim();
962- if part.eq_ignore_ascii_case("mod") {1041+ let modifier = if part.eq_ignore_ascii_case("mod") {
963- modifiers |= Modifiers::COMPOSITOR1042+ Modifiers::COMPOSITOR
964 } else if part.eq_ignore_ascii_case("ctrl") || part.eq_ignore_ascii_case("control") {1043 } else if part.eq_ignore_ascii_case("ctrl") || part.eq_ignore_ascii_case("control") {
965- modifiers |= Modifiers::CTRL;1044+ Modifiers::CTRL
966 } else if part.eq_ignore_ascii_case("shift") {1045 } else if part.eq_ignore_ascii_case("shift") {
967- modifiers |= Modifiers::SHIFT;1046+ Modifiers::SHIFT
968 } else if part.eq_ignore_ascii_case("alt") {1047 } else if part.eq_ignore_ascii_case("alt") {
969- modifiers |= Modifiers::ALT;1048+ Modifiers::ALT
970 } else if part.eq_ignore_ascii_case("super") || part.eq_ignore_ascii_case("win") {1049 } else if part.eq_ignore_ascii_case("super") || part.eq_ignore_ascii_case("win") {
971- modifiers |= Modifiers::SUPER;1050+ Modifiers::SUPER
972 } else if part.eq_ignore_ascii_case("iso_level3_shift")1051 } else if part.eq_ignore_ascii_case("iso_level3_shift")
973 || part.eq_ignore_ascii_case("mod5")1052 || part.eq_ignore_ascii_case("mod5")
974 {1053 {
975- modifiers |= Modifiers::ISO_LEVEL3_SHIFT;1054+ Modifiers::ISO_LEVEL3_SHIFT
976 } else if part.eq_ignore_ascii_case("iso_level5_shift")1055 } else if part.eq_ignore_ascii_case("iso_level5_shift")
977 || part.eq_ignore_ascii_case("mod3")1056 || part.eq_ignore_ascii_case("mod3")
978 {1057 {
979- modifiers |= Modifiers::ISO_LEVEL5_SHIFT;1058+ Modifiers::ISO_LEVEL5_SHIFT
980 } else {1059 } else {
981 return Err(miette!("invalid modifier: {part}"));1060 return Err(miette!("invalid modifier: {part}"));
982- }1061+ };
1062+
1063+ written_modifiers.push((modifier, part));
983 }1064 }
984 1065
985 let trigger = if key.eq_ignore_ascii_case("MouseLeft") {1066 let trigger = if key.eq_ignore_ascii_case("MouseLeft") {
@@ -1014,6 +1095,20 @@ impl FromStr for Key {
1014 Trigger::TabletStylusButton21095 Trigger::TabletStylusButton2
1015 } else if key.eq_ignore_ascii_case("TabletStylusButton3") {1096 } else if key.eq_ignore_ascii_case("TabletStylusButton3") {
1016 Trigger::TabletStylusButton31097 Trigger::TabletStylusButton3
1098+ } else if key.eq_ignore_ascii_case("Mod") {
1099+ Trigger::CompositorMod
1100+ } else if key.eq_ignore_ascii_case("Ctrl") || key.eq_ignore_ascii_case("Control") {
1101+ Trigger::Modifier(ModKey::Ctrl)
1102+ } else if key.eq_ignore_ascii_case("Shift") {
1103+ Trigger::Modifier(ModKey::Shift)
1104+ } else if key.eq_ignore_ascii_case("Alt") {
1105+ Trigger::Modifier(ModKey::Alt)
1106+ } else if key.eq_ignore_ascii_case("Super") || key.eq_ignore_ascii_case("Win") {
1107+ Trigger::Modifier(ModKey::Super)
1108+ } else if key.eq_ignore_ascii_case("ISO_Level3_Shift") || key.eq_ignore_ascii_case("Mod5") {
1109+ Trigger::Modifier(ModKey::IsoLevel3Shift)
1110+ } else if key.eq_ignore_ascii_case("ISO_Level5_Shift") || key.eq_ignore_ascii_case("Mod3") {
1111+ Trigger::Modifier(ModKey::IsoLevel5Shift)
1017 } else {1112 } else {
1018 let mut keysym = keysym_from_name(key, KEYSYM_CASE_INSENSITIVE);1113 let mut keysym = keysym_from_name(key, KEYSYM_CASE_INSENSITIVE);
1019 // The keyboard event handling code can receive either1114 // The keyboard event handling code can receive either
@@ -1049,6 +1144,15 @@ impl FromStr for Key {
1049 Trigger::Keysym(keysym)1144 Trigger::Keysym(keysym)
1050 };1145 };
1051 1146
1147+ let mut modifiers = trigger.implied_modifier();
1148+ for (modifier, spelling) in written_modifiers {
1149+ if modifiers.contains(modifier) {
1150+ warn!("redundant modifier `{spelling}` in keybind `{s}`");
1151+ }
1152+
1153+ modifiers |= modifier;
1154+ }
1155+
1052 Ok(Key { trigger, modifiers })1156 Ok(Key { trigger, modifiers })
1053 }1157 }
1054 }1158 }
@@ -1115,6 +1219,165 @@ mod tests {
1115 );1219 );
1116 }1220 }
1117 1221
1222+ #[test]
1223+ fn parse_bare_modifier_spellings() {
1224+ // Each modifier can be spelled with its canonical name or an alias. A bare modifier key
1225+ // parses to `Trigger::Modifier`.
1226+ for (text, modifier) in [
1227+ ("Ctrl", ModKey::Ctrl),
1228+ ("Control", ModKey::Ctrl),
1229+ ("Shift", ModKey::Shift),
1230+ ("Alt", ModKey::Alt),
1231+ ("Super", ModKey::Super),
1232+ ("Win", ModKey::Super),
1233+ ("Mod5", ModKey::IsoLevel3Shift),
1234+ ("ISO_Level3_Shift", ModKey::IsoLevel3Shift),
1235+ ("Mod3", ModKey::IsoLevel5Shift),
1236+ ("ISO_Level5_Shift", ModKey::IsoLevel5Shift),
1237+ ] {
1238+ assert_eq!(
1239+ text.parse::<Key>().unwrap(),
1240+ Key {
1241+ trigger: Trigger::Modifier(modifier),
1242+ modifiers: modifier.to_modifiers(),
1243+ },
1244+ "parsing `{text}`",
1245+ );
1246+ }
1247+ }
1248+
1249+ #[test]
1250+ fn parse_mod_as_trigger() {
1251+ // The mod key keeps its own trigger, which is resolved to a real modifier at runtime.
1252+ assert_eq!(
1253+ "Mod".parse::<Key>().unwrap(),
1254+ Key {
1255+ trigger: Trigger::CompositorMod,
1256+ modifiers: Modifiers::COMPOSITOR,
1257+ },
1258+ );
1259+
1260+ // It can also be used together with other held modifiers.
1261+ assert_eq!(
1262+ "Ctrl+Mod".parse::<Key>().unwrap(),
1263+ Key {
1264+ trigger: Trigger::CompositorMod,
1265+ modifiers: Modifiers::CTRL | Modifiers::COMPOSITOR,
1266+ },
1267+ );
1268+
1269+ // `Mod` also works as a held modifier of another trigger.
1270+ assert_eq!(
1271+ "Mod+Control_L".parse::<Key>().unwrap(),
1272+ Key {
1273+ trigger: Trigger::Keysym(Keysym::Control_L),
1274+ modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
1275+ },
1276+ );
1277+ }
1278+
1279+ #[test]
1280+ fn parse_multi_modifier_triggers() {
1281+ // A modifier key as the trigger with another held modifier, either spelled as the modifier
1282+ // itself or as its keysym.
1283+ assert_eq!(
1284+ "Ctrl+Alt".parse::<Key>().unwrap(),
1285+ Key {
1286+ trigger: Trigger::Modifier(ModKey::Alt),
1287+ modifiers: Modifiers::CTRL | Modifiers::ALT,
1288+ },
1289+ );
1290+ assert_eq!(
1291+ "Ctrl+Alt_L".parse::<Key>().unwrap(),
1292+ Key {
1293+ trigger: Trigger::Keysym(Keysym::Alt_L),
1294+ modifiers: Modifiers::CTRL | Modifiers::ALT,
1295+ },
1296+ );
1297+ }
1298+
1299+ #[test]
1300+ fn parse_normalizes_redundant_modifiers() {
1301+ let key = |text: &str| text.parse::<Key>().unwrap();
1302+
1303+ // Modifier triggers can be written with or without the redundant modifier.
1304+ assert_eq!(key("Alt+Alt_L"), key("Alt_L"));
1305+ assert_eq!(key("Alt+Alt_R"), key("Alt_R"));
1306+ assert_eq!(key("Alt+Alt"), key("Alt"));
1307+ assert_eq!(key("Alt+Alt+Alt_L"), key("Alt_L"));
1308+ assert_eq!(key("Ctrl+Shift+Control_L"), key("Shift+Control_L"));
1309+ assert_eq!(key("Mod+Mod"), key("Mod"));
1310+
1311+ // Duplicate modifiers are fine with non-modifier triggers.
1312+ assert_eq!(key("Alt+Alt+Q"), key("Alt+Q"));
1313+ assert_eq!(key("Mod+Mod+Q"), key("Mod+Q"));
1314+
1315+ // Still works if spelled differently.
1316+ assert_eq!(key("Ctrl+Control+Q"), key("Ctrl+Q"));
1317+ assert_eq!(key("Super+Win+Q"), key("Super+Q"));
1318+ }
1319+
1320+ #[test]
1321+ fn parse_modifier_trigger_includes_implied_modifier() {
1322+ // The modifier that the trigger implies is part of the key.
1323+ assert_eq!(
1324+ "Alt_L".parse::<Key>().unwrap(),
1325+ Key {
1326+ trigger: Trigger::Keysym(Keysym::Alt_L),
1327+ modifiers: Modifiers::ALT,
1328+ },
1329+ );
1330+ assert_eq!(
1331+ "Alt+Alt".parse::<Key>().unwrap(),
1332+ Key {
1333+ trigger: Trigger::Modifier(ModKey::Alt),
1334+ modifiers: Modifiers::ALT,
1335+ },
1336+ );
1337+ // `Mod` is only resolved at runtime, so no trigger implies it.
1338+ assert_eq!(
1339+ "Alt+Mod".parse::<Key>().unwrap(),
1340+ Key {
1341+ trigger: Trigger::CompositorMod,
1342+ modifiers: Modifiers::ALT | Modifiers::COMPOSITOR,
1343+ },
1344+ );
1345+ }
1346+
1347+ #[test]
1348+ fn key_conflicts() {
1349+ let key = |text: &str| text.parse::<Key>().unwrap();
1350+
1351+ // Alt_L and Alt_R conflict with Alt, and vice versa.
1352+ let alt = key("Alt");
1353+ let alt_l = key("Alt_L");
1354+ let alt_r = key("Alt_R");
1355+ assert!(alt.conflicts_with(&alt_l));
1356+ assert!(alt.conflicts_with(&alt_r));
1357+ assert!(alt_l.conflicts_with(&alt));
1358+ assert!(alt_r.conflicts_with(&alt));
1359+
1360+ // The left and right keysyms are different keys.
1361+ assert!(!alt_l.conflicts_with(&alt_r));
1362+
1363+ // Different modifiers mean different binds, even for the same trigger.
1364+ assert!(!alt.conflicts_with(&key("Ctrl+Alt_L")));
1365+
1366+ // Non-overlapping triggers don't conflict, even with the same modifiers.
1367+ assert!(!key("Mod+Q").conflicts_with(&key("Mod+L")));
1368+ assert!(!key("Q").conflicts_with(&key("Ctrl")));
1369+
1370+ // Identical keys are duplicates.
1371+ assert!(key("Q").conflicts_with(&key("Q")));
1372+ assert!(alt.conflicts_with(&alt));
1373+
1374+ // The compositor mod key is only resolved at runtime, so `Mod` isn't compared against the
1375+ // mod key's own spellings.
1376+ let compositor_mod = key("Mod");
1377+ assert!(!compositor_mod.conflicts_with(&key("Super_L")));
1378+ assert!(!compositor_mod.conflicts_with(&key("Super")));
1379+ }
1380+
1118 #[test]1381 #[test]
1119 fn null_byte() {1382 fn null_byte() {
1120 // Shouldn't panic.1383 // Shouldn't panic.
niri-config/src/input.rsmodified+68 -2
@@ -1,7 +1,7 @@
1 use std::str::FromStr;1 use std::str::FromStr;
2 2
3 use miette::miette;3 use miette::miette;
4-use smithay::input::keyboard::XkbConfig;4+use smithay::input::keyboard::{keysyms, Keysym, XkbConfig};
5 use smithay::reexports::input;5 use smithay::reexports::input;
6 6
7 use crate::binds::Modifiers;7 use crate::binds::Modifiers;
@@ -415,7 +415,7 @@ impl FromStr for WarpMouseToFocusMode {
415 }415 }
416 }416 }
417 417
418-#[derive(Debug, PartialEq, Eq, Clone, Copy)]418+#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
419 pub enum ModKey {419 pub enum ModKey {
420 Ctrl,420 Ctrl,
421 Shift,421 Shift,
@@ -436,6 +436,23 @@ impl ModKey {
436 ModKey::IsoLevel5Shift => Modifiers::ISO_LEVEL5_SHIFT,436 ModKey::IsoLevel5Shift => Modifiers::ISO_LEVEL5_SHIFT,
437 }437 }
438 }438 }
439+
440+ /// Returns the modifier key for a keysym, if the keysym is a modifier key.
441+ pub fn from_keysym(keysym: Keysym) -> Option<Self> {
442+ match keysym.raw() {
443+ keysyms::KEY_Control_L | keysyms::KEY_Control_R => Some(Self::Ctrl),
444+ keysyms::KEY_Shift_L | keysyms::KEY_Shift_R => Some(Self::Shift),
445+ keysyms::KEY_Alt_L | keysyms::KEY_Alt_R => Some(Self::Alt),
446+ keysyms::KEY_Super_L | keysyms::KEY_Super_R => Some(Self::Super),
447+ keysyms::KEY_ISO_Level3_Shift => Some(Self::IsoLevel3Shift),
448+ keysyms::KEY_ISO_Level5_Shift => Some(Self::IsoLevel5Shift),
449+ _ => None,
450+ }
451+ }
452+
453+ pub fn matches_keysym(self, keysym: Keysym) -> bool {
454+ Self::from_keysym(keysym) == Some(self)
455+ }
439 }456 }
440 457
441 impl FromStr for ModKey {458 impl FromStr for ModKey {
@@ -526,6 +543,55 @@ mod tests {
526 Input::from_part(&part)543 Input::from_part(&part)
527 }544 }
528 545
546+ #[test]
547+ fn mod_key_names_are_consistent() {
548+ // The X11 `ModN` modifier indices are a separate numbering from the ISO level numbers,
549+ // and the two happen to be crossed over: ISO Level 3 Shift is Mod5, and ISO Level 5 Shift
550+ // is Mod3. This test guards against "fixing" this apparent mismatch.
551+ for (name, modifier, keysym, modifiers) in [
552+ (
553+ "Mod5",
554+ ModKey::IsoLevel3Shift,
555+ keysyms::KEY_ISO_Level3_Shift,
556+ Modifiers::ISO_LEVEL3_SHIFT,
557+ ),
558+ (
559+ "Mod3",
560+ ModKey::IsoLevel5Shift,
561+ keysyms::KEY_ISO_Level5_Shift,
562+ Modifiers::ISO_LEVEL5_SHIFT,
563+ ),
564+ ] {
565+ // Name -> variant.
566+ assert_eq!(
567+ name.parse::<ModKey>().unwrap(),
568+ modifier,
569+ "parsing `{name}`"
570+ );
571+
572+ // Keysym -> variant.
573+ assert_eq!(
574+ ModKey::from_keysym(Keysym::from(keysym)),
575+ Some(modifier),
576+ "keysym for `{name}`",
577+ );
578+ assert!(modifier.matches_keysym(Keysym::from(keysym)));
579+
580+ // Variant -> held modifiers.
581+ assert_eq!(modifier.to_modifiers(), modifiers, "modifiers for `{name}`");
582+ }
583+
584+ // ISO_Level3_Shift and Mod5 are the same modifier, and so are ISO_Level5_Shift and Mod3.
585+ assert_eq!(
586+ "ISO_Level3_Shift".parse::<ModKey>().unwrap(),
587+ "Mod5".parse::<ModKey>().unwrap()
588+ );
589+ assert_eq!(
590+ "ISO_Level5_Shift".parse::<ModKey>().unwrap(),
591+ "Mod3".parse::<ModKey>().unwrap()
592+ );
593+ }
594+
529 #[test]595 #[test]
530 fn parse_scroll_factor_combined() {596 fn parse_scroll_factor_combined() {
531 // Test combined scroll-factor syntax597 // Test combined scroll-factor syntax
niri-config/src/lib.rsmodified+2 -1
@@ -229,7 +229,8 @@ where
229 let mut config = config.borrow_mut();229 let mut config = config.borrow_mut();
230 let binds = &mut config.binds.0;230 let binds = &mut config.binds.0;
231 // Remove existing binds matching any new bind.231 // Remove existing binds matching any new bind.
232- binds.retain(|bind| !part.0.iter().any(|new| new.key == bind.key));232+ binds
233+ .retain(|bind| !part.0.iter().any(|new| new.key.conflicts_with(&bind.key)));
233 // Add all new binds.234 // Add all new binds.
234 binds.extend(part.0);235 binds.extend(part.0);
235 }236 }
niri-config/src/recent_windows.rsmodified+14 -5
@@ -58,7 +58,7 @@ impl MergeWith<RecentWindowsPart> for RecentWindows {
58 if let Some(part) = &part.binds {58 if let Some(part) = &part.binds {
59 // Remove existing binds matching any new bind.59 // Remove existing binds matching any new bind.
60 self.binds60 self.binds
61- .retain(|bind| !part.0.iter().any(|new| new.key == bind.key));61+ .retain(|bind| !part.0.iter().any(|new| new.key.conflicts_with(&bind.key)));
62 // Add all new binds.62 // Add all new binds.
63 self.binds.extend(part.0.iter().cloned().map(Bind::from));63 self.binds.extend(part.0.iter().cloned().map(Bind::from));
64 }64 }
@@ -269,7 +269,9 @@ where
269 ctx.emit_error(e);269 ctx.emit_error(e);
270 }270 }
271 Ok(bind) => {271 Ok(bind) => {
272- let conflict = binds.iter().position(|prev| prev.key == bind.key);272+ let conflict = binds
273+ .iter()
274+ .position(|prev| prev.key.conflicts_with(&bind.key));
273 if let Some(idx) = conflict {275 if let Some(idx) = conflict {
274 // Even though it's technically incorrect, we use276 // Even though it's technically incorrect, we use
275 // `DecodeError::Missing` here because it labels the bind with277 // `DecodeError::Missing` here because it labels the bind with
@@ -282,7 +284,11 @@ where
282 ctx.emit_error(DecodeError::unexpected(284 ctx.emit_error(DecodeError::unexpected(
283 &child.node_name,285 &child.node_name,
284 "keybind",286 "keybind",
285- "duplicate keybind later defined here",287+ if binds[idx].key == bind.key {
288+ "duplicate keybind later defined here"
289+ } else {
290+ "conflicting keybind later defined here"
291+ },
286 ));292 ));
287 } else {293 } else {
288 nodes.push(child);294 nodes.push(child);
@@ -325,8 +331,11 @@ where
325 .parse::<Key>()331 .parse::<Key>()
326 .map_err(|e| DecodeError::conversion(&node.node_name, e.wrap_err("invalid keybind")))?;332 .map_err(|e| DecodeError::conversion(&node.node_name, e.wrap_err("invalid keybind")))?;
327 333
334+ let mut modifiers = key.modifiers;
335+ modifiers &= !key.trigger.implied_modifier();
336+
328 // A modifier is required because MRU remains on screen as long as any modifier is held.337 // A modifier is required because MRU remains on screen as long as any modifier is held.
329- if key.modifiers.is_empty() {338+ if modifiers.is_empty() {
330 ctx.emit_error(DecodeError::unexpected(339 ctx.emit_error(DecodeError::unexpected(
331 &node.node_name,340 &node.node_name,
332 "keybind",341 "keybind",
@@ -336,7 +345,7 @@ where
336 345
337 // FIXME: To support this, all the mods_with_mouse_binds()/mods_with_*wheel_binds()/etc.346 // FIXME: To support this, all the mods_with_mouse_binds()/mods_with_*wheel_binds()/etc.
338 // will need to learn about recent-windows bindings.347 // will need to learn about recent-windows bindings.
339- if !matches!(key.trigger, Trigger::Keysym(_)) {348+ if !key.trigger.is_keyboard() {
340 ctx.emit_error(DecodeError::unexpected(349 ctx.emit_error(DecodeError::unexpected(
341 &node.node_name,350 &node.node_name,
342 "key",351 "key",
src/ui/hotkey_overlay.rsmodified+108 -27
@@ -496,50 +496,37 @@ fn action_name(action: &Action) -> String {
496 fn key_name(screen_reader: bool, mod_key: ModKey, key: &Key) -> String {496 fn key_name(screen_reader: bool, mod_key: ModKey, key: &Key) -> String {
497 let mut name = String::new();497 let mut name = String::new();
498 498
499- let has_comp_mod = key.modifiers.contains(Modifiers::COMPOSITOR);499+ // Do not show modifiers implied by the trigger.
500+ let modifiers = key.modifiers & !key.trigger.implied_modifier();
501+
502+ let has_comp_mod = modifiers.contains(Modifiers::COMPOSITOR);
503+
504+ let mod_key_pretty = modifier_name(mod_key);
500 505
501 // Compositor mod goes first.506 // Compositor mod goes first.
502 if has_comp_mod {507 if has_comp_mod {
503- match mod_key {508+ name.push_str(mod_key_pretty);
504- ModKey::Super => {509+ name.push_str(" + ");
505- name.push_str("Super + ");
506- }
507- ModKey::Alt => {
508- name.push_str("Alt + ");
509- }
510- ModKey::Shift => {
511- name.push_str("Shift + ");
512- }
513- ModKey::Ctrl => {
514- name.push_str("Ctrl + ");
515- }
516- ModKey::IsoLevel3Shift => {
517- name.push_str("Mod5 + ");
518- }
519- ModKey::IsoLevel5Shift => {
520- name.push_str("Mod3 + ");
521- }
522- }
523 }510 }
524 511
525- if key.modifiers.contains(Modifiers::SUPER) && !(has_comp_mod && mod_key == ModKey::Super) {512+ if modifiers.contains(Modifiers::SUPER) && !(has_comp_mod && mod_key == ModKey::Super) {
526 name.push_str("Super + ");513 name.push_str("Super + ");
527 }514 }
528- if key.modifiers.contains(Modifiers::CTRL) && !(has_comp_mod && mod_key == ModKey::Ctrl) {515+ if modifiers.contains(Modifiers::CTRL) && !(has_comp_mod && mod_key == ModKey::Ctrl) {
529 name.push_str("Ctrl + ");516 name.push_str("Ctrl + ");
530 }517 }
531- if key.modifiers.contains(Modifiers::SHIFT) && !(has_comp_mod && mod_key == ModKey::Shift) {518+ if modifiers.contains(Modifiers::SHIFT) && !(has_comp_mod && mod_key == ModKey::Shift) {
532 name.push_str("Shift + ");519 name.push_str("Shift + ");
533 }520 }
534- if key.modifiers.contains(Modifiers::ALT) && !(has_comp_mod && mod_key == ModKey::Alt) {521+ if modifiers.contains(Modifiers::ALT) && !(has_comp_mod && mod_key == ModKey::Alt) {
535 name.push_str("Alt + ");522 name.push_str("Alt + ");
536 }523 }
537- if key.modifiers.contains(Modifiers::ISO_LEVEL3_SHIFT)524+ if modifiers.contains(Modifiers::ISO_LEVEL3_SHIFT)
538 && !(has_comp_mod && mod_key == ModKey::IsoLevel3Shift)525 && !(has_comp_mod && mod_key == ModKey::IsoLevel3Shift)
539 {526 {
540 name.push_str("Mod5 + ");527 name.push_str("Mod5 + ");
541 }528 }
542- if key.modifiers.contains(Modifiers::ISO_LEVEL5_SHIFT)529+ if modifiers.contains(Modifiers::ISO_LEVEL5_SHIFT)
543 && !(has_comp_mod && mod_key == ModKey::IsoLevel5Shift)530 && !(has_comp_mod && mod_key == ModKey::IsoLevel5Shift)
544 {531 {
545 name.push_str("Mod3 + ");532 name.push_str("Mod3 + ");
@@ -547,6 +534,8 @@ fn key_name(screen_reader: bool, mod_key: ModKey, key: &Key) -> String {
547 534
548 let pretty = match key.trigger {535 let pretty = match key.trigger {
549 Trigger::Keysym(keysym) => prettify_keysym_name(screen_reader, &keysym_get_name(keysym)),536 Trigger::Keysym(keysym) => prettify_keysym_name(screen_reader, &keysym_get_name(keysym)),
537+ Trigger::CompositorMod => mod_key_pretty.into(),
538+ Trigger::Modifier(modifier) => modifier_name(modifier).into(),
550 Trigger::MouseLeft => String::from("Mouse Left"),539 Trigger::MouseLeft => String::from("Mouse Left"),
551 Trigger::MouseRight => String::from("Mouse Right"),540 Trigger::MouseRight => String::from("Mouse Right"),
552 Trigger::MouseMiddle => String::from("Mouse Middle"),541 Trigger::MouseMiddle => String::from("Mouse Middle"),
@@ -569,6 +558,17 @@ fn key_name(screen_reader: bool, mod_key: ModKey, key: &Key) -> String {
569 name558 name
570 }559 }
571 560
561+fn modifier_name(modifier: ModKey) -> &'static str {
562+ match modifier {
563+ ModKey::Super => "Super",
564+ ModKey::Alt => "Alt",
565+ ModKey::Shift => "Shift",
566+ ModKey::Ctrl => "Ctrl",
567+ ModKey::IsoLevel3Shift => "Mod5",
568+ ModKey::IsoLevel5Shift => "Mod3",
569+ }
570+}
571+
572 fn prettify_keysym_name(screen_reader: bool, name: &str) -> String {572 fn prettify_keysym_name(screen_reader: bool, name: &str) -> String {
573 let name = if screen_reader {573 let name = if screen_reader {
574 name574 name
@@ -632,6 +632,87 @@ mod tests {
632 // Not bound.632 // Not bound.
633 assert_snapshot!(check("", Action::Screenshot(true, None)), @" (not bound) : Take a Screenshot");633 assert_snapshot!(check("", Action::Screenshot(true, None)), @" (not bound) : Take a Screenshot");
634 634
635+ // Bare modifier binds.
636+ assert_snapshot!(
637+ check(
638+ r#"binds {
639+ Alt { close-window; }
640+ }"#,
641+ Action::CloseWindow,
642+ ),
643+ @" Alt : Close Focused Window"
644+ );
645+ assert_snapshot!(
646+ check(
647+ r#"binds {
648+ Ctrl { close-window; }
649+ Shift { close-window; }
650+ }"#,
651+ Action::CloseWindow,
652+ ),
653+ @" Ctrl : Close Focused Window"
654+ );
655+ assert_snapshot!(
656+ check(
657+ r#"binds {
658+ Mod5 { close-window; }
659+ Mod3 { close-window; }
660+ }"#,
661+ Action::CloseWindow,
662+ ),
663+ @" Mod5 : Close Focused Window"
664+ );
665+ assert_snapshot!(
666+ check(
667+ r#"binds {
668+ Super { close-window; }
669+ }"#,
670+ Action::CloseWindow,
671+ ),
672+ @" Super : Close Focused Window"
673+ );
674+
675+ // Modifier + modifier binds: a held modifier key with another modifier key as the trigger.
676+ assert_snapshot!(
677+ check(
678+ r#"binds {
679+ Ctrl+Alt_L { close-window; }
680+ }"#,
681+ Action::CloseWindow,
682+ ),
683+ @" Ctrl + Alt_L : Close Focused Window"
684+ );
685+ assert_snapshot!(
686+ check(
687+ r#"binds {
688+ Alt+Ctrl { close-window; }
689+ }"#,
690+ Action::CloseWindow,
691+ ),
692+ @" Alt + Ctrl : Close Focused Window"
693+ );
694+
695+ // A Ctrl keysym names only one side of the keyboard, so it keeps its exact name instead of
696+ // being shortened to `Ctrl`.
697+ assert_snapshot!(
698+ check(
699+ r#"binds {
700+ Control_L { close-window; }
701+ }"#,
702+ Action::CloseWindow,
703+ ),
704+ @" Control_L : Close Focused Window"
705+ );
706+ assert_snapshot!(
707+ check(
708+ r#"binds {
709+ Mod+Control_R { close-window; }
710+ }"#,
711+ Action::CloseWindow,
712+ ),
713+ @" Super + Control_R : Close Focused Window"
714+ );
715+
635 // Bound with a default title.716 // Bound with a default title.
636 assert_snapshot!(717 assert_snapshot!(
637 check(718 check(