fix(text-injection): route XWayland clients without IBus through xdotool (#1003)

* fix(text-injection): route XWayland clients without IBus through xdotool

On KDE Plasma Wayland with the KWin IBus bridge enabled, Vocalinux injects through IBus. An X11 client under XWayland only reaches IBus when it loaded an IBus input method module from GTK_IM_MODULE, QT_IM_MODULE or XMODIFIERS. Without one, the engine commit lands in no input context and still reports OK, so the text was lost with no fallback.

Before each WAYLAND_IBUS injection, check XWayland's active window. A real client whose own environment does not select IBus gets that segment through the WAYLAND_XDOTOOL path, and the backend returns to IBus afterwards so native Wayland apps keep using it.

Fixes #972

* fix(text-injection): honour IBus pins and the client toolkit in the XWayland detour

Keep IBus when the user pinned it, judge a GTK or Qt client only by its own toolkit's IM variable (read from the libraries it maps), and have the clipboard restore after an XWayland paste read the X11 clipboard it wrote even after the backend switched back to IBus.

* fix(text-injection): keep a non-text X11 clipboard on the XWayland paste route

WAYLAND_XDOTOOL pasted through the X11 clipboard even when it held an image or file, which it cannot save and restore. Check the clipboard targets there as the X11 route already does, and type the text instead when they hold no text.
This commit is contained in:
Jatin K Malik
2026-10-21 00:40:22 -07:00
committed by GitHub
parent 4d78246174
commit f013b7ff88
5 changed files with 501 additions and 17 deletions
@@ -253,6 +253,120 @@ def _focused_window_x11() -> Optional[FocusedWindow]:
)
def _read_process_environ(pid: str) -> Optional[dict[str, str]]:
"""Return ``/proc/<pid>/environ`` as a dict, or None when it cannot be read."""
if not pid.isdigit():
return None
try:
with open(f"/proc/{pid}/environ", "rb") as handle:
raw = handle.read()
except OSError:
return None
environ: dict[str, str] = {}
for entry in raw.split(b"\0"):
key, sep, value = entry.partition(b"=")
if sep:
environ[key.decode("utf-8", "replace")] = value.decode("utf-8", "replace")
return environ
# Shared libraries that identify the toolkit an X11 client draws its text fields with.
_GTK_LIBRARY_MARKERS = ("libgtk-3.so", "libgtk-x11-2.0.so", "libgtk-4.so")
_QT_LIBRARY_MARKERS = ("libQt5Gui.so", "libQt6Gui.so", "libQtGui.so")
_IM_MODULE_VARIABLES = {"gtk": "GTK_IM_MODULE", "qt": "QT_IM_MODULE"}
def _process_toolkits(pid: str) -> set[str]:
"""Return the GUI toolkits (``gtk``, ``qt``) mapped into a process, if readable."""
if not pid.isdigit():
return set()
try:
with open(f"/proc/{pid}/maps", "r", encoding="utf-8", errors="replace") as handle:
maps = handle.read()
except OSError:
return set()
toolkits: set[str] = set()
if any(marker in maps for marker in _GTK_LIBRARY_MARKERS):
toolkits.add("gtk")
if any(marker in maps for marker in _QT_LIBRARY_MARKERS):
toolkits.add("qt")
return toolkits
def _toolkit_uses_ibus(environ: dict[str, str], toolkit: str) -> bool:
"""True when a GTK or Qt client with this environment loads the IBus module.
The toolkit's own variable decides. ``xim`` hands the choice to XIM, which
reaches IBus only through ``XMODIFIERS=@im=ibus``.
"""
module = environ.get(_IM_MODULE_VARIABLES[toolkit], "").strip().lower()
if module == "xim":
return "@im=ibus" in environ.get("XMODIFIERS", "").lower()
return "ibus" in module
def environ_uses_ibus_im(environ: dict[str, str], toolkits: frozenset[str] = frozenset()) -> bool:
"""True when a client with this environment and these toolkits talks to IBus.
For a known GTK or Qt client only that toolkit's variable counts, so an
IBus setting meant for the other toolkit does not hide a missing one. When
the toolkit is unknown (plain Xlib, Tk, Motif or a custom toolkit), every
input method variable that is set must select IBus, and at least one must.
"""
known = toolkits & _IM_MODULE_VARIABLES.keys()
if known:
return all(_toolkit_uses_ibus(environ, toolkit) for toolkit in known)
values = [
environ.get(name, "").strip().lower()
for name in ("GTK_IM_MODULE", "QT_IM_MODULE", "XMODIFIERS")
]
selected = [value for value in values if value]
return bool(selected) and all("ibus" in value for value in selected)
def focused_xwayland_client_without_ibus() -> bool:
"""True when a Wayland session has an XWayland client focused that IBus cannot reach.
An X11 client only talks to IBus through an input method module that it
loads at startup from GTK_IM_MODULE (GTK), QT_IM_MODULE (Qt) or XMODIFIERS
(XIM). Its toolkit is read from the libraries it has mapped. Without
one, IBus has no input context for it: the Vocalinux engine still commits
and reports success, and the text goes nowhere (#972). The client's own
environment is read because it can differ from the one Vocalinux runs in.
While a native Wayland client holds focus, XWayland's active window is
unset or a placeholder with no pid and no WM_CLASS, so this returns False.
A real client whose environment cannot be read counts as not connected,
since xdotool reaches every XWayland client and IBus does not.
"""
if not os.environ.get("WAYLAND_DISPLAY") or not os.environ.get("DISPLAY"):
return False
if not shutil.which("xdotool"):
return False
env = _x11_probe_env()
window_id = _run_text(["xdotool", "getactivewindow"], env)
if not window_id:
return False
pid = _run_text(["xdotool", "getwindowpid", window_id], env)
if not pid.isdigit():
if not read_wm_class(window_id, env):
return False
logger.debug("Focused XWayland window %s has no pid; assuming no IBus", window_id)
return True
environ = _read_process_environ(pid)
if environ is None:
logger.debug("Cannot read the environment of XWayland pid %s; assuming no IBus", pid)
return True
if environ_uses_ibus_im(environ, frozenset(_process_toolkits(pid))):
return False
logger.debug(
"Focused XWayland client %s (pid %s) has no IBus input method module",
_process_name_for_pid(pid) or window_id,
pid,
)
return True
def _first_string(payload: dict[str, Any], *keys: str) -> str:
"""Return the first non-empty string value for the given keys."""
for key in keys:
+60 -15
View File
@@ -18,7 +18,11 @@ from typing import List, Optional, Tuple, cast
from ..utils.host_process import host_env
from ..utils.paths import config_dir
from .focused_window import is_focused_window_terminal, read_wm_class
from .focused_window import (
focused_xwayland_client_without_ibus,
is_focused_window_terminal,
read_wm_class,
)
from .ibus_engine import (
IBusTextInjector,
is_ibus_active_input_method,
@@ -1676,11 +1680,22 @@ class TextInjector:
if self.environment == DesktopEnvironment.WAYLAND_XDOTOOL:
self._try_recover_from_fallback()
xwayland_detour = False
try:
with self._state_lock:
current_env = self.environment
ibus_injector = self._ibus_injector
if current_env == DesktopEnvironment.WAYLAND_IBUS and self._should_bypass_ibus():
# The IBus engine would commit into no input context and still
# report OK (#972); send this segment through XWayland instead.
logger.info("Focused XWayland client has no IBus input method; using xdotool")
with self._state_lock:
if self.environment == DesktopEnvironment.WAYLAND_IBUS:
self.environment = DesktopEnvironment.WAYLAND_XDOTOOL
xwayland_detour = True
current_env = self.environment
if (
current_env == DesktopEnvironment.WAYLAND_IBUS
or current_env == DesktopEnvironment.X11_IBUS
@@ -1823,6 +1838,25 @@ class TextInjector:
except ImportError:
logger.warning("Could not import audio feedback module")
return False
finally:
if xwayland_detour:
with self._state_lock:
if self.environment == DesktopEnvironment.WAYLAND_XDOTOOL:
self.environment = DesktopEnvironment.WAYLAND_IBUS
def _should_bypass_ibus(self) -> bool:
"""True when IBus cannot reach the focused window but xdotool can (#972).
Only applies when the backend was chosen automatically; a pinned IBus
backend is the user's call and is kept.
"""
if self._backend_pin[0] == "ibus":
return False
try:
return focused_xwayland_client_without_ibus()
except (OSError, subprocess.SubprocessError, ValueError) as exc:
logger.debug(f"XWayland focus probe failed, keeping IBus: {exc}")
return False
def _inject_with_xdotool(self, text: str) -> None:
"""
@@ -1845,12 +1879,17 @@ class TextInjector:
os.environ.setdefault("DISPLAY", env["DISPLAY"])
logger.debug(f"Using XWayland with DISPLAY={env['DISPLAY']}")
self._wait_for_modifiers_released()
if self._inject_via_clipboard_paste(text, env=env):
if self._clipboard_holds_non_text():
logger.info(
"Clipboard holds non-text content; typing instead of pasting to preserve it"
)
elif self._inject_via_clipboard_paste(text, env=env):
return
logger.warning(
"Clipboard paste failed, falling back to xdotool type "
"(character-by-character; text may be scrambled on non-US layouts)"
)
else:
logger.warning(
"Clipboard paste failed, falling back to xdotool type "
"(character-by-character; text may be scrambled on non-US layouts)"
)
# Add a small delay to ensure text is injected properly
time.sleep(0.3) # Increased delay for better reliability
@@ -2038,7 +2077,7 @@ class TextInjector:
except UnicodeEncodeError:
return True
def _read_clipboard(self) -> Optional[str]:
def _read_clipboard(self, prefer_x11: Optional[bool] = None) -> Optional[str]:
"""
Read clipboard text only.
@@ -2048,12 +2087,14 @@ class TextInjector:
On X11 and WAYLAND_XDOTOOL this reads the X11 CLIPBOARD (xclip/xsel),
matching the selection the xdotool paste wrote. wl-paste is a different
clipboard.
clipboard. ``prefer_x11`` overrides that choice so a caller can read the
clipboard it wrote even after the backend has changed.
"""
prefer_x11 = self.environment in (
DesktopEnvironment.X11,
DesktopEnvironment.WAYLAND_XDOTOOL,
)
if prefer_x11 is None:
prefer_x11 = self.environment in (
DesktopEnvironment.X11,
DesktopEnvironment.WAYLAND_XDOTOOL,
)
host_is_wayland = (
self._session_environment == DesktopEnvironment.WAYLAND
or os.environ.get("XDG_SESSION_TYPE", "").lower() == "wayland"
@@ -2096,8 +2137,12 @@ class TextInjector:
return "" if saw_empty else None
def _clipboard_holds_non_text(self) -> bool:
"""Return whether the X11 clipboard has no readable text target."""
if self.environment != DesktopEnvironment.X11:
"""Return whether the X11 clipboard has no readable text target.
Checked on X11 and WAYLAND_XDOTOOL, the two routes that paste through
the X11 clipboard and could not restore an image or file afterwards.
"""
if self.environment not in (DesktopEnvironment.X11, DesktopEnvironment.WAYLAND_XDOTOOL):
return False
if not shutil.which("xclip"):
return self._read_clipboard() is None
@@ -2302,7 +2347,7 @@ class TextInjector:
if target is None:
return
# User copied something else during the delay — leave it alone.
if self._read_clipboard() != text:
if self._read_clipboard(prefer_x11=prefer_x11) != text:
logger.debug("Clipboard changed during restore delay; skipping restore")
return
if target == "":