Doubao-powered voice input for Linux, Wayland and Omarchy
test(x11): add desktop acceptance and installation guides
laukkwb8e7081a65df
diff --git a/README.md b/README.mdindex 76dc978..9a653f5 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@[简体中文](README.zh-CN.md)-A standalone GTK4 voice-input application for Linux/Wayland. It uses Doubao+A standalone GTK4 voice-input application for Linux (Hyprland/Wayland and native X11). It uses Doubaoweb-account recognition by default and can optionally use the official VolcengineSeed ASR 2.0 API. English by default. Settings offers **System / English /简体中文** and saves each choice automatically. System follows the session's language preferences,@@ -86,11 +86,28 @@ endpoint errors also safely fall back to it.The API key is stored separately with owner-only permissions and never appears indiagnostics. Use **Test endpoint** before enabling.+### Desktop support++| Desktop session | Automatic clipboard paste | Direct typing |+| --- | --- | --- |+| Hyprland / Wayland | `wl-copy`; known, unchanged window required | Optional `wtype` |+| Native X11 | `xclip` and `xdotool`; known, unchanged window/PID required | Unavailable; choose Clipboard paste |+| Other Wayland compositors | Retain the result for manual copying when focus cannot be verified | No supported automatic path |++Native X11 uses Ctrl+V, or Ctrl+Shift+V for recognized terminal classes. Its+floating overlay does not request activation; the window manager chooses its+position. Hyprland keeps its bottom-anchored layer-shell overlay. PipeWire+microphone selection works through `pw-record` on both desktops.+XWayland is not treated as a native X11 session.+### Text input methodSettings → Input → **Text input method** defaults to **Clipboard paste**,-including for existing installations. Choose **Direct typing** to keep the-clipboard unchanged. Install `wtype` separately; this mode requires a compatible+including for existing installations. Clipboard paste replaces the current+clipboard contents; clipboard managers may save the recognized text in history.+CopyQ is not required, and no clipboard restoration or history suppression is+performed. Choose **Direct typing** on Hyprland to keep the clipboard unchanged.+Install `wtype` separately; this mode requires a compatibleWayland virtual-keyboard implementation and has been tested on Hyprland.Direct typing sends characters gradually (about 8 seconds for 1,760 characters@@ -163,10 +180,12 @@ or clipboard changes already delivered.Failed recognition can preserve partial text; failed paste preserves the result.This slot is memory-only, not a transcript history. Exiting loses it.-Safe automatic paste currently requires a known, unchanged Hyprland window.-Other compositors or an unknown target retain the result for manual copying.-Focus is checked before paste and Enter, but Wayland cannot make that check and-input delivery atomic. A sent paste shortcut is not proof that an app received it.+Automatic paste requires a known, unchanged Hyprland or native X11 window.+On X11, missing window metadata, a closed window or the app's own window prevents+paste. Unsupported desktops or unknown targets retain the result for manual copying.+Focus is checked before paste and Enter, but focus checks and input delivery are+not atomic. Moving the caret inside the same window is not detected. A sent paste+shortcut is not proof that an app received it.Settings includes hardware key capture with timeout/cancel, PipeWire microphoneselection, lower-frequency waveform updates, account controls, and an allowlisted@@ -250,7 +269,9 @@ when available and otherwise uses `sudo pacman -S --needed` on Arch.Keep this checkout in place: its desktop launcher points to it. Enable standalonestartup in Settings only if the Omarchy plugin is disabled. For other distributions,-resolve equivalent system packages first; automatic paste currently targets Hyprland.+resolve equivalent system packages first; automatic paste targets Hyprland and native X11.+Run installation checks from the desktop session you intend to use so the correct+clipboard and GTK backend dependencies are selected.**App or plugin release archive:**@@ -302,6 +323,19 @@ PYTHONPATH=src .venv/bin/python -m unittest discover -s tests -vpython3 packaging/build-release.py```+Native X11's opt-in desktop test creates a disposable Xephyr/XFWM session and+checks Unicode/multiline paste, terminal shortcuts, cancellation, focus changes+and overlay focus. It uses a separate clipboard without CopyQ; optional PyQt6 and+Electron fixtures extend toolkit coverage. Avoid typing during the test:++```sh+timeout --kill-after=5s 50s env PYTHONPATH=src python3 tests/manual_x11.py --run+```++This requires Xephyr, xfwm4, xfce4-terminal, xdotool, xclip and `/dev/uinput` access.+Real microphone dictation, other window managers and Hyprland acceptance remain+separate checks.+Archives are local artifacts, not published releases. Validate both installationand real desktop workflows before distributing them. No GitHub upload is performedby any build or installation script.@@ -318,7 +352,7 @@ The first release version is **1.0.0**. A `v1.0.0` tag must match every embeddedversion before CI can publish. Tag releases rebuild both offline app and Omarchyplugin archives for Python 3.11–3.14 and attach SHA-256 checksums. A manually startedrelease workflow builds artifacts for inspection but does not publish them. Real-login, microphone, global-key and Wayland behavior still require the manual checklist.+login, microphone, global-key and desktop behavior still require the manual checklist.## Credits and licensingdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 11b606c..eb2c737 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -2,7 +2,7 @@[English](README.md)-独立的 Linux / Wayland GTK4 语音输入应用。默认使用豆包网页账号识别,也可选择+独立的 Linux GTK4 语音输入应用,支持 Hyprland / Wayland 和原生 X11。默认使用豆包网页账号识别,也可选择火山引擎官方 Seed ASR 2.0 API。默认英文,设置提供 **System(跟随系统)/ English / 简体中文**,选择后自动保存并立即生效。System 读取桌面会话的语言偏好,中文区域使用简体中文,其他不支持的语言回退为英文。@@ -64,10 +64,24 @@ API Key 保存在 `~/.config/doubao-say/volcengine_api_key`(或对应的API Key 通过仅限当前用户读取的独立文件保存,不进入诊断信息。建议开启前先点击“测试接口”。+### 桌面支持++| 桌面会话 | 自动剪贴板粘贴 | 直接输入 |+| --- | --- | --- |+| Hyprland / Wayland | 使用 `wl-copy`,要求目标窗口已知且未变化 | 可选 `wtype` |+| 原生 X11 | 使用 `xclip` 和 `xdotool`,要求目标窗口及 PID 已知且未变化 | 不支持,请选择剪贴板粘贴 |+| 其他 Wayland 桌面 | 无法确认焦点时保留结果供手动复制 | 暂无支持的自动输入路径 |++原生 X11 使用 Ctrl+V;识别到终端窗口时使用 Ctrl+Shift+V。悬浮窗不主动请求焦点,+位置由窗口管理器决定。Hyprland 保留底部 layer-shell 悬浮窗。+两个桌面都通过 `pw-record` 使用所选 PipeWire 麦克风。XWayland 不会被当作原生 X11 会话。+### 文字输入方式设置 → 输入 → **文字输入方式**,默认使用**剪贴板粘贴**,已有配置也保持此默认值。-可选择**直接输入**以保持剪贴板不变。此模式需要另行安装 `wtype`,并使用支持+剪贴板粘贴会替换当前剪贴板内容,剪贴板管理器可能将识别文字存入历史。+此功能不依赖 CopyQ,也不会恢复剪贴板或排除历史记录。+Hyprland 下可选择**直接输入**以保持剪贴板不变。此模式需要另行安装 `wtype`,并使用支持Wayland 虚拟键盘的桌面,已在 Hyprland 验证。直接输入会逐字发送,本机测试 1,760 字约需 8 秒。换行和制表符相当于回车和 Tab,@@ -121,10 +135,11 @@ Esc 可停止后续输入,但不能撤回已输入的文字;焦点变化时识别失败时可能保留已收到的部分文字,粘贴失败时会保留结果。这里只在内存中保留一次结果,不是转写历史;退出应用会丢失该结果。-目前,安全自动粘贴要求能确认 Hyprland 目标窗口未变化。-其他桌面或无法确认目标时,保留结果供手动复制。-软件会在粘贴和回车前检查焦点,但 Wayland 下无法保证焦点检查与输入发送是一个不可分割的操作。-发出粘贴快捷键不等于能确认目标应用已收到文字。+自动粘贴要求能确认 Hyprland 或原生 X11 的目标窗口未变化。+X11 窗口信息缺失、窗口关闭或焦点在本应用窗口时,均不自动粘贴。+未支持的桌面或无法确认目标时,保留结果供手动复制。+软件会在粘贴和回车前检查焦点,但焦点检查与输入发送无法成为一个不可分割的操作;+同一窗口内移动光标也无法检测。发出粘贴快捷键不等于能确认目标应用已收到文字。设置支持按键捕获(超时与取消)、PipeWire 麦克风选择、降低波形更新频率、账户管理,以及仅包含允许字段的诊断信息预览与复制。选择按键期间会暂停正常的输入触发。@@ -194,7 +209,8 @@ cd "${XDG_CONFIG_HOME:-$HOME/.config}/omarchy/plugins/md.lifeos.doubao-say"```保留源码目录,桌面入口会指向它。只有 Omarchy 插件已禁用时,才在设置中开启独立应用-自启动。其他发行版需先安装对应系统依赖;自动粘贴目前主要面向 Hyprland。+自启动。其他发行版需先安装对应系统依赖;自动粘贴支持 Hyprland 和原生 X11。+请在实际使用的桌面会话中执行安装检查,以便选择对应的剪贴板及 GTK 后端依赖。**使用独立应用或插件安装包:**@@ -239,6 +255,17 @@ PYTHONPATH=src .venv/bin/python -m unittest discover -s tests -vpython3 packaging/build-release.py```+原生 X11 的可选桌面测试会创建独立 Xephyr/XFWM 会话,检查中文、多行粘贴、终端快捷键、+取消、焦点变化及悬浮窗焦点。测试使用独立剪贴板,不依赖 CopyQ;安装 PyQt6 和 Electron 后+还会检查这两种界面。运行期间请勿打字:++```sh+timeout --kill-after=5s 50s env PYTHONPATH=src python3 tests/manual_x11.py --run+```++需要 Xephyr、xfwm4、xfce4-terminal、xdotool、xclip 和 `/dev/uinput` 权限。+真实麦克风听写、其他窗口管理器及 Hyprland 仍需分别验收。+安装包目前是本地产物,不是已发布版本。分发前需验证安装流程及真实桌面使用流程。构建和安装脚本都不会自动上传 GitHub。@@ -251,7 +278,7 @@ GTK 测试、代码检查、编译、包元数据校验和密钥扫描。覆盖首个发布版本为 **1.0.0**。只有 `v1.0.0` 标签与所有内置版本完全一致时,CI 才能发布。标签发布会为 Python 3.11–3.14 分别构建独立应用与 Omarchy 插件离线包,并附带 SHA-256校验文件。手动启动发布工作流只构建供检查的产物,不会公开发布。真实登录、麦克风、-全局按键及 Wayland 行为仍需按人工验收清单检查。+全局按键及桌面行为仍需按人工验收清单检查。## 致谢与许可diff --git a/packaging/INSTALL.md b/packaging/INSTALL.mdindex 3d537e1..3a204f7 100644--- a/packaging/INSTALL.md+++ b/packaging/INSTALL.md@@ -13,12 +13,30 @@ This bundle includes Python dependency wheels for the Python/CPU version in itsfilename (for example cpython-314 and x86_64). System libraries are not bundled.The recommended `./install.sh` detects missing Arch/Omarchy packages, shows theexact list and asks before installing them. Use `./install.sh --yes` only after-reviewing that list. The equivalent manual command is:+reviewing that list. Run it in the intended desktop session: native X11 selects+`xdotool` and `xclip`; Wayland selects `gtk4-layer-shell` and `wl-clipboard`.+The source installer, archive installer and runtime checks use the same desktop+requirements. XWayland's `DISPLAY` does not select native X11.++The equivalent manual command for Hyprland/Omarchy is:```shomarchy pkg add python python-gobject python-cairo gtk4 gtk4-layer-shell webkitgtk-6.0 pipewire wl-clipboard portaudio```+For a native X11 session on Arch:++```sh+sudo pacman -S --needed python python-gobject python-cairo gtk4 webkitgtk-6.0 pipewire portaudio xdotool xclip+```++X11 requires GTK's GdkX11 backend, but neither layer-shell nor wl-clipboard.+PipeWire is used on X11 and Wayland so microphone node selection matches capture.+CopyQ is not required. Ordinary clipboard paste replaces clipboard contents and+may be stored by a clipboard manager. Direct typing through optional `wtype`+remains a Hyprland/Wayland feature; choose Clipboard paste on native X11.+Other Wayland compositors do not gain automatic input from this X11 support.+Your user needs read access to keyboard events and write access to `/dev/uinput`.On this Omarchy setup, membership in `input` provides these permissions. If absent,run `sudo usermod -aG input "$USER"` and log out/in. Never run the application as root.diff --git a/tests/manual_x11.py b/tests/manual_x11.pynew file mode 100644index 0000000..be21cd3--- /dev/null+++ b/tests/manual_x11.py@@ -0,0 +1,247 @@+"""Opt-in X11 delivery acceptance in a disposable Xephyr/XFWM desktop.++Run: timeout --kill-after=5s 50s env PYTHONPATH=src python tests/manual_x11.py --run+Requires Xephyr, xfwm4, xdotool, xclip, xfce4-terminal and uinput access.+PyQt6 and Electron add optional toolkit checks. Avoid typing/changing focus.+The host clipboard, settings and running app are untouched; no audio/network.+"""+import argparse+from contextlib import ExitStack+import importlib.util+import os+from pathlib import Path+import select+import signal+import subprocess+import sys+import tempfile+import time+import tty+import uuid++from manual_safety import hard_deadline+++def stop(process):+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=2)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=2)+ assert process.poll() is not None, "Test process did not exit"+++def command(*args, env=None):+ return subprocess.check_output(args, env=env, stderr=subprocess.DEVNULL, timeout=2).decode().strip()+++def wait_for(check, seconds=4):+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ try:+ result = check()+ if result:+ return result+ except (subprocess.CalledProcessError, FileNotFoundError):+ pass+ time.sleep(0.025)+ raise AssertionError("Desktop fixture did not reach expected state")+++def helper(kind, result):+ path = Path(result)+ path.write_text("")+ if kind == "terminal":+ tty.setraw(sys.stdin.fileno())+ received = bytearray()+ while True:+ received.extend(os.read(sys.stdin.fileno(), 65536))+ path.write_bytes(received)+ elif kind == "qt":+ from PyQt6.QtWidgets import QApplication, QTextEdit+ app = QApplication([])+ editor = QTextEdit()+ editor.setWindowTitle("Doubao X11 fixture")+ editor.textChanged.connect(lambda: path.write_text(editor.toPlainText()))+ editor.show()+ editor.setFocus()+ app.exec()+ else:+ import gi+ gi.require_version("Gtk", "4.0")+ from gi.repository import Gtk, GLib+ GLib.set_prgname("doubao-x11-fixture")+ Gtk.init()+ win, editor = Gtk.Window(title="Doubao X11 fixture"), Gtk.TextView()+ buffer = editor.get_buffer()+ buffer.connect("changed", lambda buf: path.write_text(+ buf.get_text(buf.get_start_iter(), buf.get_end_iter(), True)))+ win.set_child(editor)+ win.set_default_size(500, 250)+ win.present()+ editor.grab_focus()+ GLib.MainLoop().run()+++def exercise(folder):+ import shutil+ import gi+ gi.require_version("Gtk", "4.0")+ from gi.repository import Gtk, GLib+ from doubao_input.inject.injector import Injector, active_window_needs_shift+ from doubao_input.inject.target import focused_target+ from doubao_input.ui.overlay import Overlay++ Gtk.init()+ host_env = {**os.environ, "DISPLAY": os.environ["DOUBAO_TEST_HOST_DISPLAY"]}+ def host_focused():+ return command("xdotool", "getactivewindow", env=host_env) == os.environ["DOUBAO_TEST_HOST_WINDOW"]+ def window_for(process):+ return wait_for(lambda: command("xdotool", "search", "--onlyvisible", "--pid", str(process.pid)).splitlines()[0])+ def activate(window):+ assert host_focused(), "Host focus changed; stop sending input"+ command("xdotool", "windowactivate", "--sync", window)+ return wait_for(lambda: focused_target() if command("xdotool", "getactivewindow") == window else None)++ with ExitStack() as cleanup, hard_deadline(35):+ injector = Injector()+ cleanup.callback(injector.close)+ wm = subprocess.Popen(["xfwm4", "--sm-client-disable", "--compositor=off"],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ cleanup.callback(stop, wm)+ modes = ["gtk", "terminal"]+ for name, available in (("qt", importlib.util.find_spec("PyQt6")), ("electron", shutil.which("electron"))):+ if available:+ modes.append(name)+ else:+ print(f"SKIP {name}: optional fixture unavailable", flush=True)+ windows = []+ for mode in modes:+ result = folder / (mode + ".txt")+ args = [sys.executable, __file__, "--helper", mode, "--result", str(result)]+ if mode == "terminal":+ args = ["xfce4-terminal", "--disable-server", "--hide-menubar", "--execute", *args]+ elif mode == "electron":+ script = folder / "main.js"+ script.write_text("""const {app, BrowserWindow, ipcMain} = require('electron');+const fs = require('fs');+const result = process.argv[process.argv.length - 1];+app.whenReady().then(() => {+ fs.writeFileSync(result, '');+ const win = new BrowserWindow({width: 600, height: 350,+ webPreferences: {nodeIntegration: true, contextIsolation: false}});+ ipcMain.on('text', (_, text) => fs.writeFileSync(result, text));+ const page = `<textarea autofocus style="width:95%;height:90%"></textarea><script>+ const input = document.querySelector('textarea');+ input.addEventListener('input', () => require('electron').ipcRenderer.send('text', input.value));+ input.focus();</script>`;+ win.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(page));+});+""")+ args = ["electron", "--ozone-platform=x11", "--disable-gpu",+ "--user-data-dir=" + str(folder / "electron-profile"), str(script), str(result)]+ process = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ cleanup.callback(stop, process)+ window = window_for(process)+ target = activate(window)+ wait_for(result.exists)+ # Allow the first focus event and Chromium's initial page to settle.+ time.sleep(0.4)+ text = "中文终端 paste 🙂" if mode == "terminal" else "中文 English 🙂 e\u0301\n第二行。\n" + "长文字 123。" * 200+ assert active_window_needs_shift() == (mode == "terminal")+ assert injector.inject(text, expected_target=target, cancelled=lambda: not host_focused()), mode+ wait_for(lambda: result.read_text() == text)+ time.sleep(0.15)+ assert result.read_text() == text, mode + ": repeated input or unexpected Enter"+ windows.append((window, target))+ print(f"PASS {mode}: exact Unicode paste, no extra Enter", flush=True)++ first_window, first_target = windows[0]+ activate(first_window)+ before = command("xclip", "-selection", "clipboard", "-o")+ assert not injector.inject("cancelled", expected_target=first_target, cancelled=lambda: True)+ activate(windows[1][0])+ assert not injector.inject("wrong window", expected_target=first_target)+ assert not injector.send_enter(expected_target=first_target)+ assert not injector.inject("direct unsupported", expected_target=first_target, method="direct")+ assert command("xclip", "-selection", "clipboard", "-o") == before+ print("PASS cancellation, changed focus, guarded Enter, X11 direct refusal", flush=True)++ activate(first_window)+ overlay = Overlay()+ cleanup.callback(overlay.hide)+ cleanup.callback(lambda: overlay._window and overlay._window.destroy())+ loop = GLib.MainLoop()+ for style in ("bars", "waves", "ripples", "basketball"):+ overlay.waveform_style = style+ overlay.show()+ overlay.push_rms(0.5)+ GLib.timeout_add(250, lambda: loop.quit() or False)+ loop.run()+ assert focused_target() == first_target, "Overlay stole focus"+ for label in (overlay._label, overlay._status_label):+ color = label.get_style_context().get_color()+ expected = overlay._theme["bright_foreground"]+ assert all(abs(value - int(expected[index:index + 2], 16) / 255) < 0.01+ for value, index in zip((color.red, color.green, color.blue), (1, 3, 5))), "Overlay foreground lost"+ overlay.hide()+ print("PASS X11 overlay retains focus across waveform styles", flush=True)+++def run_nested():+ original = command("xdotool", "getactivewindow")+ title = "Doubao-X11-acceptance-" + uuid.uuid4().hex[:8]+ with tempfile.TemporaryDirectory() as temp, ExitStack() as cleanup, hard_deadline(45):+ read_fd, write_fd = os.pipe()+ cleanup.callback(os.close, read_fd)+ xephyr = subprocess.Popen(["Xephyr", "-displayfd", str(write_fd), "-screen", "1000x720",+ "-no-host-grab", "-nolisten", "tcp", "-title", title], pass_fds=(write_fd,),+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ cleanup.callback(stop, xephyr)+ os.close(write_fd)+ assert select.select([read_fd], [], [], 5)[0], "Xephyr did not start"+ display = ":" + os.read(read_fd, 32).decode().strip()+ host_window = wait_for(lambda: command("xdotool", "search", "--onlyvisible", "--name", title).splitlines()[0])+ command("xdotool", "windowactivate", "--sync", host_window)+ env = {k: v for k, v in os.environ.items() if k not in (+ "WAYLAND_DISPLAY", "HYPRLAND_INSTANCE_SIGNATURE", "ELECTRON_RUN_AS_NODE")}+ env.update(DISPLAY=display, XDG_SESSION_TYPE="x11", GDK_BACKEND="x11", GTK_A11Y="none",+ GSK_RENDERER="cairo", GIO_USE_VFS="local", NO_AT_BRIDGE="1",+ XDG_CONFIG_HOME=temp + "/config", XDG_CACHE_HOME=temp + "/cache", XDG_DATA_HOME=temp + "/data",+ QT_QPA_PLATFORM="xcb", DOUBAO_TEST_HOST_DISPLAY=os.environ["DISPLAY"],+ DOUBAO_TEST_HOST_WINDOW=host_window)+ runner = subprocess.Popen(["dbus-run-session", "--", sys.executable, __file__, "--exercise", temp],+ env=env, start_new_session=True)+ def stop_group():+ # Includes xclip's daemon and fixture descendants after a failed run.+ try:+ os.killpg(runner.pid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ stop(runner)+ cleanup.callback(stop_group)+ try:+ assert runner.wait(timeout=38) == 0, "Nested desktop acceptance failed"+ finally:+ if command("xdotool", "getactivewindow") == host_window:+ command("xdotool", "windowactivate", "--sync", original)+ print("PASS disposable desktop exited; host clipboard unchanged", flush=True)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--run", action="store_true")+ parser.add_argument("--helper", choices=("gtk", "qt", "terminal"))+ parser.add_argument("--result")+ parser.add_argument("--exercise")+ options = parser.parse_args()+ if options.helper:+ helper(options.helper, options.result)+ elif options.exercise:+ exercise(Path(options.exercise))+ elif options.run:+ run_nested()+ else:+ parser.error("Live keyboard test requires --run")