grabkeys: Avoid missing events when a keysym maps to multiple keycodes 89f99057
It's not uncommon for one keysym to map to multiple keycodes. For
example, the "play" button on my keyboard sends keycode 172, but my
bluetooth headphones send keycode 208, both of which map back to
XF86AudioPlay:

    % xmodmap -pke | grep XF86AudioPlay
    keycode 172 = XF86AudioPlay XF86AudioPause XF86AudioPlay XF86AudioPause
    keycode 208 = XF86AudioPlay NoSymbol XF86AudioPlay
    keycode 215 = XF86AudioPlay NoSymbol XF86AudioPlay

This is a problem because the current code only grabs a single one of
these keycodes, which means that events for any other keycode also
mapping to the bound keysym will not be handled by dwm. In my case, this
means that binding XF86AudioPlay does the right thing and correctly
handles my keyboard's keys, but does nothing on my headphones. I'm not
the only person affected by this, there are other reports[0].

In order to fix this, we look at the mappings between keycodes and
keysyms at grabkeys() time and pick out all matching keycodes rather
than just the first one. The keypress() side of this doesn't need any
changes because the keycode gets converted back to a canonical keysym
before any action is taken.

0: https://github.com/cdown/dwm/issues/11
Chris Down · 2022-12-07 14:55 1 file(s) · +17 −7
dwm.c +17 −7
955 955
{
956 956
	updatenumlockmask();
957 957
	{
958 -
		unsigned int i, j;
958 +
		unsigned int i, j, k;
959 959
		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
960 -
		KeyCode code;
960 +
		int start, end, skip;
961 +
		KeySym *syms;
961 962
962 963
		XUngrabKey(dpy, AnyKey, AnyModifier, root);
963 -
		for (i = 0; i < LENGTH(keys); i++)
964 -
			if ((code = XKeysymToKeycode(dpy, keys[i].keysym)))
965 -
				for (j = 0; j < LENGTH(modifiers); j++)
966 -
					XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
967 -
						True, GrabModeAsync, GrabModeAsync);
964 +
		XDisplayKeycodes(dpy, &start, &end);
965 +
		syms = XGetKeyboardMapping(dpy, start, end - start + 1, &skip);
966 +
		if (!syms)
967 +
			return;
968 +
		for (k = start; k <= end; k++)
969 +
			for (i = 0; i < LENGTH(keys); i++)
970 +
				/* skip modifier codes, we do that ourselves */
971 +
				if (keys[i].keysym == syms[(k - start) * skip])
972 +
					for (j = 0; j < LENGTH(modifiers); j++)
973 +
						XGrabKey(dpy, k,
974 +
							 keys[i].mod | modifiers[j],
975 +
							 root, True,
976 +
							 GrabModeAsync, GrabModeAsync);
977 +
		XFree(syms);
968 978
	}
969 979
}
970 980