Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Fix Alt+Tab dismissal while an input method holds the keyboard grab

vgxl39818b45a580
diff --git a/src/Keyboard.zig b/src/Keyboard.zig
index 926932c..c3bf976 100644
--- a/src/Keyboard.zig
+++ b/src/Keyboard.zig
@@ -129,7 +129,7 @@ fn handleModifiers(listener: *wl.Listener(*wlr.Keyboard), wlr_keyboard: *wlr.Key
if (lock.client) |client| if (client.focused != null) keyboard.server.input.seat.keyboardNotifyModifiers(&wlr_keyboard.modifiers);
return;
}
- const grab = if (keyboard.server.text_input) |relay| relay.keyboardGrab(wlr_keyboard) else null;
+ const grab = if (keyboard.server.text_input) |relay| relay.keyboardGrab(wlr_keyboard, .state) else null;
if (grab) |im_grab| im_grab.sendModifiers(&wlr_keyboard.modifiers) else keyboard.server.input.seat.keyboardNotifyModifiers(&wlr_keyboard.modifiers);
// Accept only when the modifier that opened the carousel is released.
diff --git a/src/Switcher.zig b/src/Switcher.zig
index 2864c87..b4b53e4 100644
--- a/src/Switcher.zig
+++ b/src/Switcher.zig
@@ -74,6 +74,11 @@ pub fn active(self: *const Self) bool {
pub fn triggerHeld(self: *const Self, server: *Server) bool {
var it = server.input.keyboards.iterator(.forward);
while (it.next()) |keyboard| {
+ // The input method's own virtual keyboard echoes what the compositor
+ // forwarded to it; while the switcher owns input that echo can lag or
+ // go stale, so counting it could leave a released trigger looking
+ // held. Only real devices keep the gesture alive.
+ if (server.text_input) |relay| if (relay.isMethodEcho(keyboard.device)) continue;
const mods = keyboard.device.toKeyboard().getModifiers();
if (switch (self.trigger) {
.alt => mods.alt,
diff --git a/src/input/AGENTS.md b/src/input/AGENTS.md
index 0c71b37..59cf1ba 100644
--- a/src/input/AGENTS.md
+++ b/src/input/AGENTS.md
@@ -13,7 +13,11 @@
* **Text input/IME** (`text_input.zig`): `syncFocus` is the only enter path.
IM grabs replace client delivery only (bindings, hardware keys and
shell/lock UI win); an IM's own virtual keyboard bypasses its grab.
- Lock/auth reject virtual input. IPC `GetTextInput` never returns text.
+ While an overlay owns new input, modifier updates and the release of keys
+ the grab already received still reach it, and the IM's virtual keyboard
+ never counts as a physical modifier source (it only echoes forwarded
+ state). Lock/auth reject virtual input. IPC `GetTextInput` never returns
+ text.
* **Layouts:** layout-zero fallback is for binding lookup only; text uses the
active XKB state.
* **Shell key repeat:** one `shell_repeat` per keyboard; a new shell target
diff --git a/src/input/text_input.zig b/src/input/text_input.zig
index 959b59c..a36275a 100644
--- a/src/input/text_input.zig
+++ b/src/input/text_input.zig
@@ -60,10 +60,19 @@ pub fn isVirtual(device: *wlr.InputDevice) bool {
return device.getVirtualKeyboard() != null;
}
-pub fn keyboardGrab(self: *Self, keyboard: *wlr.Keyboard) ?*wlr.InputMethodV2.KeyboardGrab {
+/// Why the compositor is about to hand input to the input method. `.new_input`
+/// is the ordinary delivery path and yields to compositor UI (switcher, panels)
+/// that owns new key presses. `.state` covers modifier updates and the release
+/// of keys the grab already received: those must keep reaching it even while an
+/// overlay owns new input, or the method's mirrored keyboard keeps a released
+/// modifier held and the overlay it opened can never see it end.
+pub const GrabPurpose = enum { new_input, state };
+
+pub fn keyboardGrab(self: *Self, keyboard: *wlr.Keyboard, purpose: GrabPurpose) ?*wlr.InputMethodV2.KeyboardGrab {
const input = &self.server.input;
- if (self.server.locker != null or self.server.polkit_dialog != null or self.server.switcher.active() or
- input.open_wifi != null or input.open_battery != null or input.open_calendar != null or input.open_start_menu != null or (if (input.open_control_center) |cc| cc.hasKeyboardFocus() else false) or input.open_power_menu != null) return null;
+ if (self.server.locker != null or self.server.polkit_dialog != null) return null;
+ if (purpose == .new_input and (self.server.switcher.active() or
+ input.open_wifi != null or input.open_battery != null or input.open_calendar != null or input.open_start_menu != null or (if (input.open_control_center) |cc| cc.hasKeyboardFocus() else false) or input.open_power_menu != null)) return null;
const method = self.method orelse return null;
const grab = self.grab orelse return null;
if (keyboard.base.getVirtualKeyboard()) |virtual| {
@@ -75,6 +84,16 @@ pub fn keyboardGrab(self: *Self, keyboard: *wlr.Keyboard) ?*wlr.InputMethodV2.Ke
return grab;
}
+/// True for the connected input method's own virtual keyboard. What it reports
+/// is an echo of input the compositor forwarded to the method, not a device the
+/// user is pressing, so compositor gestures and the held-modifier switcher must
+/// not treat its (possibly stale) state as physical input.
+pub fn isMethodEcho(self: *Self, device: *wlr.InputDevice) bool {
+ const method = self.method orelse return false;
+ const virtual = device.getVirtualKeyboard() orelse return false;
+ return virtual.resource.getClient() == method.resource.getClient();
+}
+
fn newKeyboard(listener: *wl.Listener(*wlr.VirtualKeyboardV1), virtual: *wlr.VirtualKeyboardV1) void {
const self: *Self = @fieldParentPtr("new_keyboard", listener);
if (virtual.seat != self.server.input.seat) return;
diff --git a/src/keyboard/process.zig b/src/keyboard/process.zig
index 27570f2..7723bf0 100644
--- a/src/keyboard/process.zig
+++ b/src/keyboard/process.zig
@@ -84,7 +84,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
if (generation != 0) {
if (keyboard.server.text_input) |relay| {
if (relay.grab_generation == generation) {
- if (relay.keyboardGrab(wlr_keyboard)) |grab| grab.sendKey(time_msec, event_keycode, state);
+ if (relay.keyboardGrab(wlr_keyboard, .state)) |grab| grab.sendKey(time_msec, event_keycode, state);
}
}
return;
@@ -495,7 +495,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
};
keyboard.server.input.seat.setKeyboard(wlr_keyboard);
@import("../input/layouts.zig").activate(keyboard);
- const grab = if (keyboard.server.text_input) |relay| relay.keyboardGrab(wlr_keyboard) else null;
+ const grab = if (keyboard.server.text_input) |relay| relay.keyboardGrab(wlr_keyboard, .new_input) else null;
if (grab) |im_grab| {
im_grab.sendKey(time_msec, event_keycode, state);
if (state == .pressed and event_keycode < keyboard.grab_pressed.len)
diff --git a/tests/switcher_ime.py b/tests/switcher_ime.py
new file mode 100644
index 0000000..6668a71
--- /dev/null
+++ b/tests/switcher_ime.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""Alt+Tab dismissal while an input method owns the keyboard grab.
+
+An input method (fcitx5) mirrors the modifier state the compositor forwards to
+its keyboard grab onto its own virtual keyboard. While the switcher is open the
+compositor used to stop forwarding to the grab, so the method never learned the
+trigger was released, its virtual keyboard stayed stuck with Alt held, and the
+switcher counted that echo as a held trigger: it was never dismissed. The
+switcher must end on the physical release, and the grab must keep receiving
+modifier updates and the release of keys it was sent.
+"""
+import os
+import subprocess
+import tempfile
+import time
+from pathlib import Path
+
+from PIL import Image
+
+from desktop_zoom import wait_for
+from ipc_client import IPCClient, spawn_compositor, stop_process
+from input_protocols import compile_client
+
+RED = lambda c: c[0] > 220 and 15 < c[1] < 65 and 35 < c[2] < 95 # noqa: E731
+
+
+def red_pixels(path):
+ with Image.open(path) as shot:
+ image = shot.convert("RGB")
+ return sum(1 for y in range(image.height) for x in range(image.width) if RED(image.getpixel((x, y))))
+
+
+def run(scale, style):
+ with tempfile.TemporaryDirectory(prefix="rediwm-switcher-ime-") as directory:
+ tmp = Path(directory)
+ compile_client(tmp)
+ wallpaper = tmp / "wallpaper.png"
+ Image.new("RGB", (32, 32), (20, 24, 30)).save(wallpaper)
+ config = f'[compositor]\nwallpaper = "{wallpaper}"\nswitcher_style = "{style}"\n[keybinds]\n"alt+tab" = "focus_next"\n'
+ proc, log = spawn_compositor(tmp, scale=scale, config_content=config)
+ processes = []
+ logs = []
+ try:
+ with IPCClient(tmp) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display)
+ env.pop("WAYLAND_DEBUG", None)
+
+ def spawn(name, mode):
+ path = tmp / f"{name}.log"
+ out = path.open("w")
+ logs.append(out)
+ peer = subprocess.Popen([str(tmp / "protocol-client"), mode], env=env,
+ stdin=subprocess.PIPE, stdout=out, stderr=subprocess.STDOUT, text=True)
+ processes.append(peer)
+ wait_for(lambda: "ready\n" in path.read_text() or peer.poll() is not None,
+ f"{name} did not start: {path.read_text(errors='replace')[-1500:]}")
+ return peer, path
+
+ def send(peer, path, command):
+ before = path.read_text().count(f"ack {command}\n")
+ peer.stdin.write(command + "\n")
+ peer.stdin.flush()
+ wait_for(lambda: path.read_text().count(f"ack {command}\n") > before or peer.poll() is not None,
+ f"no ack for {command}: {path.read_text(errors='replace')[-1500:]}")
+
+ app_a, log_a = spawn("app-a", "org.test.a")
+ app_b, log_b = spawn("app-b", "org.test.b")
+ wait_for(lambda: len(ipc.get_windows()) == 2, "windows did not map")
+ ids = {w["app_id"]: w["id"] for w in ipc.get_windows()}
+
+ # Focus a text field first, then connect the input method: it
+ # activates on the focused input, grabs the keyboard and mirrors
+ # the state it receives through its own virtual keyboard.
+ ipc.action("focus_window", {"id": ids["org.test.a"]})
+ ime, log_ime = spawn("ime", "ime")
+ send(ime, log_ime, "method")
+ wait_for(lambda: "activate" in log_ime.read_text(), "IME did not activate")
+ wait_for(lambda: "text-enter" in log_a.read_text(), "text input did not enter")
+ send(ime, log_ime, "grab")
+ wait_for(lambda: "grab-keymap" in log_ime.read_text(), "IME did not grab the keyboard")
+ send(ime, log_ime, "forward")
+
+ # Known MRU order: B previous, A current, so Tab selects B.
+ for app in ("org.test.a", "org.test.b", "org.test.a"):
+ ipc.action("focus_window", {"id": ids[app]})
+ time.sleep(0.15)
+
+ def capture(name):
+ path = tmp / f"{name}-{style}-{scale}.png"
+ ipc.screenshot(path=str(path))
+ wait_for(path.exists, "capture")
+ return red_pixels(path)
+
+ ipc.key(56, True) # Alt press; the grab receives it (and mirrors it)
+ wait_for(lambda: "grab-key 56 1" in log_ime.read_text(), "IME never saw the Alt press")
+ ipc.key_down_up(15) # Tab selects the previous window
+ time.sleep(0.2)
+ assert capture("open") > 200, "switcher did not open"
+ ipc.key(56, False) # Alt release must dismiss it
+ wait_for(lambda: (ipc.get_focused_window() or {}).get("app_id") == "org.test.b",
+ "switcher did not accept on the Alt release")
+
+ def closed_pixels():
+ path = tmp / f"closed-{style}-{scale}.png"
+ path.unlink(missing_ok=True)
+ ipc.screenshot(path=str(path))
+ wait_for(path.exists, "capture")
+ return red_pixels(path)
+
+ # Circular plays a short close animation; the linear style
+ # cancels synchronously. Either way the switcher must be gone.
+ wait_for(lambda: closed_pixels() == 0, "switcher stayed on screen after the Alt release")
+ # The grab owns the press, so it must also see the release and
+ # the modifier reset; otherwise the method (and its virtual
+ # keyboard) keeps Alt held and the compositor's own gestures do.
+ wait_for(lambda: "grab-key 56 0" in log_ime.read_text(), "release did not reach the IME grab")
+ wait_for(lambda: not ipc.get_input_state()["modifiers"]["alt"], "stuck Alt modifier after dismiss")
+ assert ipc.get_focused_window()["app_id"] == "org.test.b"
+ print(f"PASS switcher ime dismiss style={style} scale={scale}")
+ except BaseException:
+ print((tmp / "compositor.log").read_text(errors="replace")[-6000:])
+ raise
+ finally:
+ for peer in processes:
+ stop_process(peer)
+ for out in logs:
+ out.close()
+ stop_process(proc)
+ log.close()
+
+
+if __name__ == "__main__":
+ for style in ("linear", "circular"):
+ run(os.environ.get("REDIWM_TEST_SCALE", "1"), style)