Doubao-powered voice input for Linux, Wayland and Omarchy
feat(x11): support native X11 input and runtime checks
laukkwa1d46c7b5336
diff --git a/install.sh b/install.shindex 79bc7b5..ccb8618 100755--- a/install.sh+++ b/install.sh@@ -63,8 +63,13 @@ if ! command -v pacman >/dev/null 2>&1; thenexit 1fi-packages=(python python-gobject python-cairo gtk4 gtk4-layer-shell webkitgtk-6.0- pipewire wl-clipboard portaudio)+packages=(python python-gobject python-cairo gtk4 webkitgtk-6.0 pipewire portaudio)+# Match desktop.is_x11(); Python itself may not be installed at this stage.+if [[ -n ${DISPLAY:-} && -z ${WAYLAND_DISPLAY:-} && ${XDG_SESSION_TYPE:-} != wayland && -z ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then+ packages+=(xdotool xclip)+else+ packages+=(gtk4-layer-shell wl-clipboard)+fiif ! $BUNDLE; thenpackages+=(python-sounddevice python-websockets python-evdev)fidiff --git a/packaging/install-release.py b/packaging/install-release.pyindex bb8c0d0..668d866 100644--- a/packaging/install-release.py+++ b/packaging/install-release.py@@ -45,17 +45,16 @@ def verify_bundle(root):return manifest-def check_system():- probe = """import gi, cairo-gi.require_version('Gtk','4.0')-gi.require_version('WebKit','6.0')-gi.require_version('Gtk4LayerShell','1.0')-from gi.repository import Gtk, WebKit, Gtk4LayerShell+def check_system(root):+ probe = """import sys+sys.path.insert(0, sys.argv[1])+from doubao_input.preflight import check_system+missing = [name for name, passed in check_system().items() if not passed]+if missing:+ raise SystemExit('Missing system dependencies: ' + ', '.join(missing) + '. See INSTALL.md')"""- subprocess.run([sys.executable, "-c", probe], check=True)- for command in ("wl-copy", "pw-record"):- if not shutil.which(command):- raise ValueError(f"Missing system dependency: {command}. See INSTALL.md")+ # The verified bundle must remain byte-for-byte unchanged after --check.+ subprocess.run([sys.executable, "-B", "-c", probe, str(Path(root) / "src")], check=True)def quote(value):@@ -121,7 +120,7 @@ def main():print("Uninstalled. Credentials, settings and shared runtime were preserved.")return- check_system()+ check_system(root)if args.check:print(f"Bundle verified: {bundle['version']} {kind}; system dependencies OK")returndiff --git a/src/doubao_input/__main__.py b/src/doubao_input/__main__.pyindex 0091c44..6a01740 100644--- a/src/doubao_input/__main__.py+++ b/src/doubao_input/__main__.py@@ -7,10 +7,13 @@ import osfrom pathlib import Pathimport sys+from doubao_input.desktop import is_x11+def _preload_layer_shell() -> None:"""Re-exec once with gtk4-layer-shell preloaded before GTK/Wayland."""- if os.environ.get("DOUBAO_LAYER_SHELL_PRELOADED") == "1":+ if (is_x11() or os.environ.get("GDK_BACKEND") == "x11"+ or os.environ.get("DOUBAO_LAYER_SHELL_PRELOADED") == "1"):returntry:import ctypes.utildiff --git a/src/doubao_input/desktop.py b/src/doubao_input/desktop.pynew file mode 100644index 0000000..3c341a1--- /dev/null+++ b/src/doubao_input/desktop.py@@ -0,0 +1,9 @@+"""Desktop session detection, usable before GTK or runtime dependencies load."""+import os+++def is_x11():+ # DISPLAY can refer to XWayland. Never use it to bypass Wayland focus guards.+ return bool(os.environ.get("DISPLAY") and not os.environ.get("WAYLAND_DISPLAY")+ and not os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")+ and os.environ.get("XDG_SESSION_TYPE") != "wayland")diff --git a/src/doubao_input/doubao/audio_capture.py b/src/doubao_input/doubao/audio_capture.pyindex a22ba7a..d98ac6a 100644--- a/src/doubao_input/doubao/audio_capture.py+++ b/src/doubao_input/doubao/audio_capture.py@@ -20,6 +20,7 @@ import shutilimport subprocessfrom typing import Any+from doubao_input.desktop import is_x11from doubao_input.doubao.config import AUDIO_BLOCKSIZE, AUDIO_CHANNELS, AUDIO_SAMPLE_RATElogger = logging.getLogger(__name__)@@ -59,9 +60,9 @@ class AudioCapture:self._on_audio_data = on_audio_dataself._on_rms = on_rms if on_rms is not None else self._default_on_rms- # Native PipeWire capture avoids PortAudio's blocking stop/drain on- # suspended Wayland audio graphs. Keep sounddevice for other desktops.- if os.environ.get("WAYLAND_DISPLAY") and shutil.which("pw-record"):+ # The picker returns PipeWire node names on X11 and Wayland. Use the+ # matching backend; retain sounddevice when native capture is unavailable.+ if (os.environ.get("WAYLAND_DISPLAY") or is_x11()) and shutil.which("pw-record"):self._start_pipewire()returndiff --git a/src/doubao_input/inject/injector.py b/src/doubao_input/inject/injector.pyindex 2de7ecb..c8f2d0d 100644--- a/src/doubao_input/inject/injector.py+++ b/src/doubao_input/inject/injector.py@@ -10,12 +10,13 @@ import timefrom typing import Optionalfrom doubao_input.doubao.host_tools import command_candidates-from doubao_input.inject.target import focused_target+from doubao_input.desktop import is_x11+from doubao_input.inject.target import focused_target, x11_windowfrom doubao_input.inject.direct import type_textlogger = logging.getLogger(__name__)-# Pause after wl-copy so the clipboard manager has settled.+# Pause after copying so the clipboard manager has settled.# Also pause after the right-Alt physical release to avoid mixing it# with our injected Left Ctrl.PASTE_DELAY = 0.08 # seconds@@ -35,8 +36,11 @@ TERMINAL_CLASSES = {def active_window_needs_shift() -> bool:- """Use the Hyprland app ID, never window titles, to select terminal paste."""+ """Use the app class, never window titles, to select terminal paste."""from doubao_input.doubao.config import INJECT_USE_SHIFT+ if is_x11():+ window = x11_window()+ return window[1] in TERMINAL_CLASSES if window else INJECT_USE_SHIFTif not os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):return INJECT_USE_SHIFTtry:@@ -65,6 +69,9 @@ class Injector:def inject(self, text: str, use_shift: bool | None = None, *, expected_target=None, cancelled=lambda: False, method="clipboard") -> bool:"""Deliver using the selected method; direct input never falls back to paste."""if method == "direct":+ if is_x11():+ logger.warning("Direct input requires Wayland; text retained")+ return Falsewith self._lock:return type_text(text, expected_target, cancelled)if method != "clipboard":@@ -149,15 +156,15 @@ class Injector:def _copy_to_clipboard(self, text: str) -> bool:data = text.encode("utf-8")- # wl-copy first- for cmd in command_candidates("wl-copy"):+ # Native X11 has no Wayland selection; preserve wl-copy priority elsewhere.+ for cmd in ([] if is_x11() else command_candidates("wl-copy")):try:subprocess.run(cmd, input=data, check=True, timeout=3)logger.info("clipboard: wl-copy ok")return Trueexcept Exception as e:logger.debug("wl-copy failed: %s", e)- # xclip fallback (XWayland only)+ # Native X11, or the existing XWayland fallback.for cmd in command_candidates("xclip"):try:subprocess.run(diff --git a/src/doubao_input/inject/target.py b/src/doubao_input/inject/target.pyindex 8c81cd6..4942eb6 100644--- a/src/doubao_input/inject/target.py+++ b/src/doubao_input/inject/target.py@@ -1,12 +1,36 @@-"""Best-effort Hyprland window identity, without recording window titles."""+"""Best-effort Hyprland/X11 window identity, without recording window titles."""import jsonimport osimport subprocess+from doubao_input.desktop import is_x11+++def x11_window():+ """Return an external active window's identity and class, or fail closed."""+ if not is_x11():+ return None+ try:+ window = int(subprocess.check_output(+ ["xdotool", "getactivewindow"], timeout=0.5, stderr=subprocess.DEVNULL))+ if window <= 0:+ return None+ window_class, pid = subprocess.check_output(+ ["xdotool", "getwindowclassname", str(window), "getwindowpid", str(window)],+ text=True, timeout=0.5, stderr=subprocess.DEVNULL).strip().splitlines()+ pid = int(pid)+ if (not window_class or window_class.casefold() == "md.lifeos.doubaosay"+ or pid <= 0 or pid == os.getpid()):+ return None+ return f"x11:{window}:{pid}", window_class.casefold()+ except (OSError, subprocess.SubprocessError, ValueError):+ return None+def focused_target():if not os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):- return None+ window = x11_window()+ return window[0] if window else Nonetry:data = json.loads(subprocess.check_output(["hyprctl", "activewindow", "-j"], timeout=0.5, stderr=subprocess.DEVNULL))diff --git a/src/doubao_input/preflight.py b/src/doubao_input/preflight.pyindex 5feaa27..5707533 100644--- a/src/doubao_input/preflight.py+++ b/src/doubao_input/preflight.py@@ -4,16 +4,29 @@ import osfrom pathlib import Pathimport shutil+from doubao_input.desktop import is_x11+def check_runtime():+ return {**check_system(), **_check_modules(("evdev", "websockets", "sounddevice"))}+++def _check_modules(modules):results = {}- for module in ("gi", "cairo", "evdev", "websockets", "sounddevice"):+ for module in modules:try:importlib.import_module(module)results[module] = Trueexcept (ImportError, OSError):results[module] = False- for namespace, version in (("Gtk", "4.0"), ("WebKit", "6.0"), ("Gtk4LayerShell", "1.0")):+ return results+++def check_system():+ """Shared with the offline installer, before its Python wheels are installed."""+ results = _check_modules(("gi", "cairo"))+ desktop_namespace = ("GdkX11", "4.0") if is_x11() else ("Gtk4LayerShell", "1.0")+ for namespace, version in (("Gtk", "4.0"), ("WebKit", "6.0"), desktop_namespace):try:import gigi.require_version(namespace, version)@@ -21,7 +34,8 @@ def check_runtime():results[namespace] = Trueexcept (ImportError, OSError, ValueError):results[namespace] = False- for command in ("pw-record", "pw-dump", "wl-copy"):+ clipboard_tools = ("xdotool", "xclip") if is_x11() else ("wl-copy",)+ for command in ("pw-record", "pw-dump", *clipboard_tools):results[command] = shutil.which(command) is not Nonereturn resultsdiff --git a/src/doubao_input/ui/overlay.py b/src/doubao_input/ui/overlay.pyindex 5b74237..284244f 100644--- a/src/doubao_input/ui/overlay.py+++ b/src/doubao_input/ui/overlay.py@@ -1,4 +1,4 @@-"""Bottom-centred, Voxtype-style recording overlay for Wayland.+"""Recording overlay: bottom-anchored on layer-shell, WM-positioned on X11.The public methods are safe to call from worker threads. GTK work ismarshalled to the main loop while audio samples remain plain Python state@@ -70,7 +70,7 @@ STATE_BORDER_KEYS = {class Overlay:- """Non-focusable layer-shell overlay with waveform, meter and live text."""+ """Non-activating recording overlay with waveform, meter and live text."""def __init__(self, app_state: AppState | None = None) -> None:self._main_thread_id = threading.get_ident()@@ -238,8 +238,14 @@ class Overlay:win.set_can_focus(False)win.add_css_class("doubao-overlay")- # Layer-shell must be initialized before the window is realized.- if Gtk4LayerShell is not None:+ # GTK can use X11 even inside a Wayland session. Inspect its display,+ # independently of the desktop protocol used to identify paste targets.+ if win.get_display().__gtype__.name == "GdkX11Display":+ gi.require_version("GdkX11", "4.0")+ from gi.repository import GdkX11+ win.connect("realize", lambda window: GdkX11.X11Surface.set_user_time(+ window.get_surface(), 0))+ elif Gtk4LayerShell is not None and Gtk4LayerShell.is_supported():try:Gtk4LayerShell.init_for_window(win)Gtk4LayerShell.set_namespace(win, "doubao-say-overlay")@@ -260,7 +266,7 @@ class Overlay:logger.exception("Could not initialize gtk4-layer-shell")else:logger.warning(- "Gtk4LayerShell unavailable; compositor will choose overlay position"+ "Layer-shell unavailable or unsupported; compositor will choose overlay position")panel = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=1)@@ -350,6 +356,7 @@ class Overlay:background: transparent;}}.doubao-overlay-panel {{+ color: {self._theme['bright_foreground']};background-color: rgba({background[0]}, {background[1]}, {background[2]}, 0.85);diff --git a/tests/test_audio_capture.py b/tests/test_audio_capture.pyindex 0e82b6a..510e982 100644--- a/tests/test_audio_capture.py+++ b/tests/test_audio_capture.py@@ -8,6 +8,26 @@ from doubao_input.doubao.audio_capture import AudioCaptureclass AudioCallbacksTest(unittest.TestCase):+ def test_x11_uses_pipewire_picker_node_and_keeps_portaudio_fallback(self):+ for available in (True, False):+ with self.subTest(pw_record=available):+ capture, callback = AudioCapture(), Mock()+ capture.device = "alsa_input.test-source"+ with patch.dict(os.environ, {"DISPLAY": ":99", "XDG_SESSION_TYPE": "x11"}, clear=True), \+ patch("doubao_input.doubao.audio_capture.shutil.which", return_value="pw-record" if available else None), \+ patch("doubao_input.doubao.audio_capture.subprocess.Popen") as spawn, \+ patch("doubao_input.doubao.audio_capture.threading.Thread"), \+ patch("doubao_input.doubao.audio_capture._load_sounddevice") as sounddevice:+ capture.start(callback)+ if available:+ args = spawn.call_args.args[0]+ self.assertEqual(args[args.index("--target") + 1], capture.device)+ sounddevice.assert_not_called()+ else:+ spawn.assert_not_called()+ self.assertEqual(sounddevice.return_value.RawInputStream.call_args.kwargs["device"], capture.device)+ capture.stop()+def test_finish_drains_real_pipe_and_joins_reader(self):# A synthetic producer, not pw-record: no microphone or network access.producer = subprocess.Popen(diff --git a/tests/test_desktop.py b/tests/test_desktop.pynew file mode 100644index 0000000..0967708--- /dev/null+++ b/tests/test_desktop.py@@ -0,0 +1,128 @@+"""Desktop checks use fake environments/dependencies; no display or input needed."""+import os+from pathlib import Path+import subprocess+import tempfile+from types import SimpleNamespace+from unittest import TestCase, skipIf+from unittest.mock import patch++from doubao_input import __main__ as entrypoint, preflight+from doubao_input.desktop import is_x11++ROOT = Path(__file__).resolve().parents[1]+SESSIONS = (+ ({"DISPLAY": ":99", "XDG_SESSION_TYPE": "x11"}, True),+ ({"DISPLAY": ":99"}, True),+ ({"DISPLAY": ":99", "WAYLAND_DISPLAY": "wayland-0"}, False),+ ({"DISPLAY": ":99", "XDG_SESSION_TYPE": "wayland"}, False),+ ({"DISPLAY": ":99", "HYPRLAND_INSTANCE_SIGNATURE": "test"}, False),+ ({}, False),+)+++class DesktopTest(TestCase):+ def test_native_x11_is_distinct_from_xwayland_and_headless(self):+ for env, expected in SESSIONS:+ with self.subTest(env=env), patch.dict(os.environ, env, clear=True):+ self.assertIs(is_x11(), expected)++ def test_native_x11_never_preloads_layer_shell(self):+ for env in (SESSIONS[0][0], {"WAYLAND_DISPLAY": "test", "GDK_BACKEND": "x11"}):+ with self.subTest(env=env), patch.dict(os.environ, env, clear=True), \+ patch("ctypes.util.find_library") as find, patch("os.execvpe") as execute:+ entrypoint._preload_layer_shell()+ find.assert_not_called()+ execute.assert_not_called()++ def test_checks_require_only_the_selected_desktops_dependencies(self):+ for env, x11 in SESSIONS:+ with self.subTest(env=env), patch.dict(os.environ, env, clear=True):+ def require(namespace, version):+ if namespace == ("Gtk4LayerShell" if x11 else "GdkX11"):+ raise ValueError("Other desktop library unavailable")+ def available(command):+ return "/bin/" + command if command in (+ "pw-record", "pw-dump", *(('xdotool', 'xclip') if x11 else ('wl-copy',))) else None+ with patch("gi.require_version", side_effect=require), \+ patch.object(preflight.importlib, "import_module"), \+ patch.object(preflight.shutil, "which", side_effect=available):+ results = preflight.check_system()+ self.assertTrue(all(results.values()), results)+ self.assertIn("GdkX11" if x11 else "Gtk4LayerShell", results)+ self.assertNotIn("Gtk4LayerShell" if x11 else "GdkX11", results)+ self.assertNotIn("copyq", results)+ self.assertNotIn("evdev", results)+ self.assertIn("evdev", preflight.check_runtime())++ def test_missing_x11_tool_is_reported(self):+ with patch.dict(os.environ, SESSIONS[0][0], clear=True), \+ patch("gi.require_version"), \+ patch.object(preflight.importlib, "import_module"), \+ patch.object(preflight.shutil, "which", side_effect=lambda tool: None if tool == "xdotool" else tool):+ self.assertFalse(preflight.check_system()["xdotool"])++ @skipIf(os.geteuid() == 0, "The installer refuses root before checking dependencies")+ def test_installer_package_selection_matches_python_session_detection(self):+ with tempfile.TemporaryDirectory() as folder:+ fake = Path(folder) / "pacman"+ fake.write_text("#!/bin/sh\nexit 1\n")+ fake.chmod(0o755)+ for env, x11 in SESSIONS:+ with self.subTest(env=env):+ session = {k: v for k, v in os.environ.items() if k not in (+ "DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE", "HYPRLAND_INSTANCE_SIGNATURE")}+ session.update(env, PATH=folder + os.pathsep + os.environ["PATH"])+ result = subprocess.run([str(ROOT / "install.sh"), "--check"],+ env=session, capture_output=True, text=True, timeout=5)+ self.assertEqual(result.returncode, 1)+ missing = next(line for line in result.stdout.splitlines()+ if line.startswith("Missing system packages:")).split()[3:]+ for package in ("xdotool", "xclip"):+ self.assertEqual(package in missing, x11)+ for package in ("wl-clipboard", "gtk4-layer-shell"):+ self.assertEqual(package in missing, not x11)+ self.assertNotIn("copyq", missing)++ def test_overlay_uses_actual_gdk_backend_even_in_wayland_session(self):+ import gi+ gi.require_version("GdkX11", "4.0")+ from gi.repository import GdkX11+ from doubao_input.ui import overlay+ class StopBeforeWidgets(Exception):+ pass+ owner = SimpleNamespace(_window=None)+ with patch.dict(os.environ, {"DISPLAY": ":99", "WAYLAND_DISPLAY": "wayland-0"}, clear=True), \+ patch.object(overlay.Gtk, "Window") as window, \+ patch.object(overlay.Gtk, "Box", side_effect=StopBeforeWidgets), \+ patch.object(overlay, "Gtk4LayerShell") as layer, \+ patch.object(GdkX11.X11Surface, "set_user_time") as user_time:+ win = window.return_value+ win.get_display.return_value.__gtype__ = SimpleNamespace(name="GdkX11Display")+ with self.assertRaises(StopBeforeWidgets):+ overlay.Overlay._ensure_window(owner)+ signal, callback = win.connect.call_args.args+ self.assertEqual(signal, "realize")+ callback(win)+ user_time.assert_called_once_with(win.get_surface.return_value, 0)+ layer.init_for_window.assert_not_called()++ def test_supported_wayland_keeps_layer_shell_and_unsupported_skips_it(self):+ from doubao_input.ui import overlay+ class StopBeforeWidgets(Exception):+ pass+ for supported in (True, False):+ with self.subTest(supported=supported), \+ patch.object(overlay.Gtk, "Window") as window, \+ patch.object(overlay.Gtk, "Box", side_effect=StopBeforeWidgets), \+ patch.object(overlay, "Gtk4LayerShell") as layer:+ win = window.return_value+ win.get_display.return_value.__gtype__ = SimpleNamespace(name="GdkWaylandDisplay")+ layer.is_supported.return_value = supported+ with self.assertRaises(StopBeforeWidgets):+ overlay.Overlay._ensure_window(SimpleNamespace(_window=None))+ if supported:+ layer.init_for_window.assert_called_once_with(win)+ layer.set_keyboard_mode.assert_called_once_with(win, layer.KeyboardMode.NONE)+ else:+ layer.init_for_window.assert_not_called()diff --git a/tests/test_direct_input.py b/tests/test_direct_input.pyindex 29b7191..80873aa 100644--- a/tests/test_direct_input.py+++ b/tests/test_direct_input.py@@ -10,6 +10,7 @@ from doubao_input.inject.injector import Injectorclass DirectInputTest(TestCase):def setUp(self):+ self.enterContext(patch.dict('os.environ', {'WAYLAND_DISPLAY': 'test'}))self.process = Mock(returncode=0)self.process.poll.return_value = 0self.spawn = self.enterContext(patch(diff --git a/tests/test_marketplace.py b/tests/test_marketplace.pyindex 247a743..7bec354 100644--- a/tests/test_marketplace.py+++ b/tests/test_marketplace.py@@ -58,7 +58,8 @@ class MarketplaceTest(unittest.TestCase):snapshot.export_source(root, root)def test_missing_modules_report_failure(self):- with patch("doubao_input.preflight.shutil.which", return_value=None), \+ with patch.dict("os.environ", {"WAYLAND_DISPLAY": "test"}), \+ patch("doubao_input.preflight.shutil.which", return_value=None), \patch("doubao_input.preflight.importlib.import_module", side_effect=ImportError):results = check_runtime()self.assertFalse(any(results.values()))diff --git a/tests/test_release.py b/tests/test_release.pyindex e8c46cf..a75e406 100644--- a/tests/test_release.py+++ b/tests/test_release.py@@ -24,6 +24,20 @@ with patch.dict(sys.modules):class ReleaseTest(unittest.TestCase):+ def test_bundle_uses_its_own_system_probe_before_python_wheel_installation(self):+ with tempfile.TemporaryDirectory() as folder:+ root = Path(folder)+ package = root / "src/doubao_input"+ package.mkdir(parents=True)+ (package / "__init__.py").write_text("")+ probe = package / "preflight.py"+ probe.write_text("def check_system(): return {'fixture-dependency': True}\n")+ installer.check_system(root)+ self.assertEqual(list(root.rglob("*.pyc")), [], "Read-only bundle checks must not add unlisted files")+ probe.write_text("def check_system(): return {'missing-fixture-dependency': False}\n")+ with self.assertRaises(subprocess.CalledProcessError):+ installer.check_system(root)+def test_manifest_uses_final_product_identity(self):manifest = json.loads((ROOT / "manifest.json").read_text())self.assertEqual(manifest["id"], "md.lifeos.doubao-say")diff --git a/tests/test_runtime_edges.py b/tests/test_runtime_edges.pyindex cdfc230..bc16d1f 100644--- a/tests/test_runtime_edges.py+++ b/tests/test_runtime_edges.py@@ -149,7 +149,8 @@ class InjectorEdgesTest(TestCase):def test_clipboard_falls_back_to_xclip(self):instance = Injector()- with patch("doubao_input.inject.injector.command_candidates",+ with patch.dict("os.environ", {"WAYLAND_DISPLAY": "test"}), \+ patch("doubao_input.inject.injector.command_candidates",side_effect=lambda tool: [[tool]]), \patch("subprocess.run", side_effect=[OSError, SimpleNamespace()]):self.assertTrue(instance._copy_to_clipboard("中文"))diff --git a/tests/test_x11_input.py b/tests/test_x11_input.pynew file mode 100644index 0000000..15e2a55--- /dev/null+++ b/tests/test_x11_input.py@@ -0,0 +1,61 @@+import os+import subprocess+from unittest import TestCase+from unittest.mock import patch++from doubao_input.inject.injector import Injector, active_window_needs_shift+from doubao_input.inject.target import focused_target+++class X11InputTest(TestCase):+ def test_external_window_identity_and_terminal_shortcut(self):+ for app_class, shift in (("Mousepad", False), ("Xfce4-terminal", True),+ ("com.mitchellh.ghostty", True)):+ with self.subTest(app_class=app_class), \+ patch.dict(os.environ, {"DISPLAY": ":0"}, clear=True), \+ patch("subprocess.check_output", side_effect=[+ b"42\n", f"{app_class}\n999999\n",+ b"42\n", f"{app_class}\n999999\n"]):+ self.assertEqual(focused_target(), "x11:42:999999")+ self.assertEqual(active_window_needs_shift(), shift)++ def test_unknown_or_own_window_is_not_a_paste_target(self):+ for metadata in (f"__main__.py\n{os.getpid()}\n", "Mousepad\n0\n",+ "md.lifeos.DoubaoSay\n999999\n",+ "Mousepad\n", "Mousepad\nnot-a-pid\n", "\n999999\n"):+ with self.subTest(metadata=metadata), \+ patch.dict(os.environ, {"DISPLAY": ":0"}, clear=True), \+ patch("subprocess.check_output", side_effect=[b"42\n", metadata]):+ self.assertIsNone(focused_target())+ for result in (b"0", b"not-a-window", OSError(),+ subprocess.TimeoutExpired("xdotool", 0.5)):+ with self.subTest(result=result), \+ patch.dict(os.environ, {"DISPLAY": ":0"}, clear=True), \+ patch("subprocess.check_output", side_effect=[result]):+ self.assertIsNone(focused_target())++ def test_wayland_never_falls_back_to_xwayland_target(self):+ for env in ({"DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"},+ {"DISPLAY": ":0", "XDG_SESSION_TYPE": "wayland"}, {}):+ with self.subTest(env=env), patch.dict(os.environ, env, clear=True), \+ patch("subprocess.check_output") as run:+ self.assertIsNone(focused_target())+ run.assert_not_called()++ def test_native_x11_direct_mode_never_launches_wtype_or_changes_clipboard(self):+ with patch.dict(os.environ, {"DISPLAY": ":0"}, clear=True), \+ patch("doubao_input.inject.injector.type_text") as type_text, \+ patch.object(Injector, "_copy_to_clipboard") as copy:+ self.assertFalse(Injector().inject("中文", method="direct", expected_target="x11:42:999999"))+ type_text.assert_not_called()+ copy.assert_not_called()++ def test_x11_copies_utf8_directly_with_xclip(self):+ with patch.dict(os.environ, {"DISPLAY": ":0"}, clear=True), \+ patch("doubao_input.inject.injector.command_candidates",+ return_value=[["xclip"]]) as candidates, \+ patch("subprocess.run") as run:+ self.assertTrue(Injector()._copy_to_clipboard("中文\n第二行"))+ candidates.assert_called_once_with("xclip")+ run.assert_called_once_with(["xclip", "-selection", "clipboard"],+ input="中文\n第二行".encode(), check=True, timeout=3)