Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

fix(x11): request above stacking for the recording overlay (#69)

laukkwa1afb0da6156
diff --git a/.github/workflows/x11-overlay.yml b/.github/workflows/x11-overlay.yml
new file mode 100644
index 0000000..ba506e9
--- /dev/null
+++ b/.github/workflows/x11-overlay.yml
@@ -0,0 +1,60 @@
+name: X11 overlay stacking
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - .github/workflows/x11-overlay.yml
+ - src/doubao_input/ui/overlay.py
+ - src/doubao_input/ui/x11_stacking.py
+ - src/doubao_input/doubao/host_tools.py
+ - tests/manual/overlay_stacking.py
+ - tests/manual/x11.py
+ - tests/manual/safety.py
+ push:
+ branches: [main]
+ paths:
+ - .github/workflows/x11-overlay.yml
+ - src/doubao_input/ui/overlay.py
+ - src/doubao_input/ui/x11_stacking.py
+ - src/doubao_input/doubao/host_tools.py
+ - tests/manual/overlay_stacking.py
+ - tests/manual/x11.py
+ - tests/manual/safety.py
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: x11-overlay-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ xfwm-overlay:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+ with:
+ persist-credentials: false
+ - name: Install isolated X11 test environment
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y python3-gi python3-cairo gir1.2-gtk-4.0 \
+ python3-xlib xvfb xfwm4 wmctrl xdotool imagemagick dbus-x11
+ - name: Verify stacking, focus and bounded helper cleanup
+ env:
+ PYTHONPATH: src
+ PYTHONDONTWRITEBYTECODE: "1"
+ run: |
+ timeout --signal=TERM --kill-after=5s 40s /usr/bin/python3 \
+ tests/manual/overlay_stacking.py --run --artifacts artifacts/x11
+ - name: Upload X11 observations and screenshots
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
+ with:
+ name: x11-overlay-evidence
+ path: artifacts/x11/
+ if-no-files-found: warn
+ retention-days: 14
diff --git a/README.md b/README.md
index 33e75de..739469a 100644
--- a/README.md
+++ b/README.md
@@ -160,11 +160,16 @@ diagnostics. Use **Test endpoint** before enabling.
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
+position. When GTK uses X11, optional `wmctrl` requests above-window stacking
+each time the overlay is shown, without activating it or waiting on the GTK main loop.
+If the helper is missing or fails, recording and input continue with the window
+manager's normal stacking. Fullscreen coverage depends on the window manager.
+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. The X11 helpers are probed at
-runtime; without either one, recognition still works and the result is retained
-for manual copying.
+runtime; without `xdotool` or `xclip`, recognition still works and the result is retained
+for manual copying. Install `wmctrl` separately for X11 overlay stacking
+(`sudo apt install wmctrl` or `sudo pacman -S --needed wmctrl`).
### Text input method
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 6a085b9..821668d 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -124,9 +124,13 @@ API Key 通过仅限当前用户读取的独立文件保存,不进入诊断信
| 其他 Wayland 桌面 | 无法确认焦点时保留结果供手动复制 | 暂无支持的自动输入路径 |
原生 X11 使用 Ctrl+V;识别到终端窗口时使用 Ctrl+Shift+V。悬浮窗不主动请求焦点,
-位置由窗口管理器决定。Hyprland 保留底部 layer-shell 悬浮窗。
+位置由窗口管理器决定。GTK 使用 X11 时,可选工具 `wmctrl` 会在浮窗每次显示时请求置顶,
+不激活浮窗,也不在 GTK 主线程等待命令完成。工具缺失或失败时沿用窗口管理器的正常层级,
+录音和文字输入继续工作;能否覆盖全屏窗口取决于窗口管理器。
+Hyprland 保留底部 layer-shell 悬浮窗。
两个桌面都通过 `pw-record` 使用所选 PipeWire 麦克风。XWayland 不会被当作原生 X11 会话。
-程序会在运行时探测 X11 辅助工具;缺少任一工具都不影响安装和识别,结果会保留供手动复制。
+程序会在运行时探测 X11 辅助工具;缺少 `xdotool` 或 `xclip` 不影响安装和识别,结果会保留供手动复制。
+X11 浮窗置顶需另行安装 `wmctrl`:`sudo apt install wmctrl` 或 `sudo pacman -S --needed wmctrl`。
### 文字输入方式
diff --git a/packaging/DEPENDENCIES.md b/packaging/DEPENDENCIES.md
index 5c91ab2..b303d0a 100644
--- a/packaging/DEPENDENCIES.md
+++ b/packaging/DEPENDENCIES.md
@@ -14,8 +14,9 @@ all source files or transitive system-library obligations.
Wheels are distributed intact, including these notices. GTK, WebKit, PipeWire,
PortAudio, Cairo and system PyGObject are installed by the OS and not bundled.
-The optional X11 helpers `xdotool` and `xclip` are also not bundled; they are
-probed at runtime and are not required for installation or Wayland. Ruff is
+The optional X11 helpers `xdotool`, `xclip` and `wmctrl` are also not bundled;
+`wmctrl` requests overlay stacking, while the others support automatic paste.
+They are probed at runtime and are not required for installation or Wayland. Ruff is
development-only, not part of end-user archives. Rebuild this inventory when
dependency pins change.
diff --git a/packaging/INSTALL.md b/packaging/INSTALL.md
index 60cf532..71778ef 100644
--- a/packaging/INSTALL.md
+++ b/packaging/INSTALL.md
@@ -38,6 +38,10 @@ Automatic paste on native X11 additionally uses the optional `xdotool` and
`xclip` helpers. They are probed at runtime and can be installed on Arch with
`sudo pacman -S --needed xdotool xclip`. If either is unavailable, installation
and startup still succeed and recognized text is retained for manual copying.
+For X11 overlay stacking, install optional `wmctrl` (`sudo apt install wmctrl`
+or `sudo pacman -S --needed wmctrl`). It requests ABOVE without activation on
+each mapping; missing or failed requests leave recording and input operational.
+The window manager decides whether ABOVE also covers fullscreen windows.
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.
diff --git a/src/doubao_input/ui/overlay.py b/src/doubao_input/ui/overlay.py
index 2180ee0..0c2c23b 100644
--- a/src/doubao_input/ui/overlay.py
+++ b/src/doubao_input/ui/overlay.py
@@ -15,6 +15,7 @@ import tomllib
from html import escape
from pathlib import Path
from typing import TYPE_CHECKING
+from doubao_input.ui.x11_stacking import X11Stacking
from doubao_input.i18n import tr
from doubao_input.ui.voice_motion import VoiceMotion
from doubao_input.ui.waveform import draw_waveform
@@ -78,6 +79,7 @@ class Overlay:
self.waveform_style = "bars"
self._app_state = app_state
self._window: Gtk.Window | None = None
+ self._x11_stacking = X11Stacking()
self._label: Gtk.Label | None = None
self._status_label: Gtk.Label | None = None
self._status_row = None
@@ -282,6 +284,9 @@ class Overlay:
from gi.repository import GdkX11
win.connect("realize", lambda window: GdkX11.X11Surface.set_user_time(
window.get_surface(), 0))
+ win.connect("map", self._x11_stacking.request)
+ win.connect("unmap", self._x11_stacking.cancel)
+ win.connect("unrealize", self._x11_stacking.cancel)
elif Gtk4LayerShell is not None and Gtk4LayerShell.is_supported():
try:
Gtk4LayerShell.init_for_window(win)
diff --git a/src/doubao_input/ui/x11_stacking.py b/src/doubao_input/ui/x11_stacking.py
new file mode 100644
index 0000000..8fa9746
--- /dev/null
+++ b/src/doubao_input/ui/x11_stacking.py
@@ -0,0 +1,74 @@
+"""Own the optional X11 stacking request and its bounded helper lifetime."""
+import logging
+from gi.repository import Gio, GLib
+from doubao_input.doubao.host_tools import command_candidates
+
+logger = logging.getLogger(__name__)
+
+
+class X11Stacking:
+ def __init__(self):
+ self._process = None
+ self._timeout = None
+
+ def request(self, window) -> None:
+ """Request stacking for this mapping without delaying GTK or activation."""
+ self.cancel()
+ commands = iter(command_candidates("wmctrl"))
+ from gi.repository import GdkX11
+ xid = GdkX11.X11Surface.get_xid(window.get_surface())
+ display = window.get_display()
+ # The helper uses a separate connection; submit GTK's map request first.
+ display.flush()
+ display_name = display.get_name()
+ launcher = Gio.SubprocessLauncher.new(
+ Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE)
+ launcher.setenv("DISPLAY", display_name, True)
+
+ def start_next():
+ if not window.get_mapped():
+ return
+ for prefix in commands:
+ if prefix[0] == "flatpak-spawn":
+ # Killing the wrapper must also stop its host-side command.
+ prefix = [*prefix[:1], "--watch-bus", f"--env=DISPLAY={display_name}", *prefix[1:]]
+ try:
+ process = launcher.spawnv([*prefix, "-i", "-r", hex(xid), "-b", "add,above"])
+ except GLib.Error:
+ continue
+ self._process = process
+ self._timeout = GLib.timeout_add(500, expired)
+ process.wait_check_async(None, completed)
+ return
+ logger.warning("X11 overlay stacking unavailable; install wmctrl or check the window manager")
+
+ def completed(process, result):
+ try:
+ success = process.wait_check_finish(result)
+ except GLib.Error:
+ success = False
+ # A hidden/remapped overlay may already have a different request.
+ if self._process is not process:
+ return
+ self._process = None
+ if self._timeout is not None:
+ GLib.source_remove(self._timeout)
+ self._timeout = None
+ if not success:
+ start_next()
+
+ def expired():
+ self._timeout = None
+ self.cancel()
+ logger.warning("X11 overlay stacking request timed out")
+ return GLib.SOURCE_REMOVE
+
+ start_next()
+
+ def cancel(self, *_args) -> None:
+ if self._timeout is not None:
+ GLib.source_remove(self._timeout)
+ self._timeout = None
+ process, self._process = self._process, None
+ if process is not None:
+ process.force_exit()
diff --git a/tests/manual/overlay_stacking.py b/tests/manual/overlay_stacking.py
new file mode 100644
index 0000000..5aeb6e4
--- /dev/null
+++ b/tests/manual/overlay_stacking.py
@@ -0,0 +1,226 @@
+"""Opt-in overlay stacking/focus check on an isolated Xvfb/XFWM desktop.
+
+Run with PYTHONPATH=src and a 40s process timeout:
+ python tests/manual/overlay_stacking.py --run --artifacts /tmp/overlay-check
+Requires Xvfb, xfwm4, wmctrl, xdotool, ImageMagick and python-xlib.
+No microphone, network, clipboard or keyboard injection. --expect-hidden checks
+an unpatched source tree using the same fullscreen reproduction.
+"""
+import argparse
+from contextlib import ExitStack
+import json
+import os
+from pathlib import Path
+import select
+import subprocess
+import sys
+import tempfile
+import time
+from unittest.mock import patch
+
+from safety import hard_deadline
+from x11 import command, stop, wait_for
+
+
+def target():
+ import gi
+ gi.require_version("Gtk", "4.0")
+ from gi.repository import GLib, Gtk
+ Gtk.init()
+ win = Gtk.Window(title="Synthetic fullscreen target")
+ editor = Gtk.TextView()
+ editor.get_buffer().set_text("Synthetic separate target — microphone off")
+ win.set_child(editor)
+ win.set_default_size(900, 600)
+ win.fullscreen()
+ win.present()
+ editor.grab_focus()
+ GLib.MainLoop().run()
+
+
+def exercise(artifacts, expect_hidden):
+ import gi
+ gi.require_version("Gtk", "4.0")
+ gi.require_version("GdkX11", "4.0")
+ from gi.repository import GdkX11, GLib, Gtk
+ from Xlib import X, display
+ from doubao_input.ui.overlay import Overlay
+
+ with ExitStack() as cleanup, hard_deadline(28):
+ log = cleanup.enter_context((artifacts / "xfwm.log").open("w"))
+ wm = subprocess.Popen(["xfwm4", "--sm-client-disable", "--compositor=off"], stdout=log, stderr=subprocess.STDOUT)
+ cleanup.callback(stop, wm)
+ conn = display.Display()
+ cleanup.callback(conn.close)
+ root = conn.screen().root
+ def props(window, name):
+ value = window.get_full_property(conn.intern_atom(name), X.AnyPropertyType)
+ return list(value.value) if value is not None else []
+ wait_for(lambda: props(root, "_NET_SUPPORTING_WM_CHECK"))
+ Gtk.init()
+ process = subprocess.Popen([sys.executable, __file__, "--target"], stderr=log)
+ cleanup.callback(stop, process)
+ target_id = int(wait_for(lambda: command("xdotool", "search", "--onlyvisible", "--all", "--pid",
+ str(process.pid), "--name", "^Synthetic fullscreen target$").splitlines()[0]))
+ def settle(ms=180):
+ loop = GLib.MainLoop()
+ GLib.timeout_add(ms, lambda: loop.quit() or False)
+ loop.run()
+ wait_for(lambda: target_id in props(root, "_NET_CLIENT_LIST"))
+ command("wmctrl", "-i", "-a", hex(target_id))
+ wait_for(lambda: props(root, "_NET_ACTIVE_WINDOW")[:1] == [target_id])
+ settle(300)
+ assert props(root, "_NET_ACTIVE_WINDOW")[:1] == [target_id]
+ focus = conn.get_input_focus().focus.id
+ focus_changes, ticks = [], []
+ def heartbeat():
+ if props(root, "_NET_ACTIVE_WINDOW")[:1] != [target_id] or conn.get_input_focus().focus.id != focus:
+ focus_changes.append(time.monotonic())
+ ticks.append(time.monotonic())
+ return True
+ timer = GLib.timeout_add(20, heartbeat)
+ cleanup.callback(GLib.source_remove, timer)
+ overlay = Overlay()
+ cleanup.callback(lambda: overlay._window and overlay._window.destroy())
+ cleanup.callback(overlay.hide)
+ rows = []
+ def frame(xid):
+ window = conn.create_resource_object("window", xid)
+ for _ in range(10):
+ parent = window.query_tree().parent
+ if parent.id == root.id:
+ return window.id
+ window = parent
+ raise AssertionError("Unexpected X11 tree depth")
+ def inspect(name, above=True, screenshot=False):
+ xid = GdkX11.X11Surface.get_xid(overlay._window.get_surface())
+ window = conn.create_resource_object("window", xid)
+ stack = [w.id for w in root.query_tree().children]
+ row = dict(case=name, mapped=window.get_attributes().map_state == X.IsViewable,
+ above=stack.index(frame(xid)) > stack.index(frame(target_id)),
+ active_retained=props(root, "_NET_ACTIVE_WINDOW")[:1] == [target_id],
+ focus_retained=conn.get_input_focus().focus.id == focus,
+ states=[conn.get_atom_name(a) for a in props(window, "_NET_WM_STATE")])
+ rows.append(row)
+ (artifacts / "results.json").write_text(json.dumps(rows, indent=2) + "\n")
+ if screenshot:
+ command("import", "-window", "root", str(artifacts / (name + ".png")))
+ assert row["mapped"] and row["above"] == above, row
+ assert row["active_retained"] and row["focus_retained"], row
+ assert "_NET_WM_STATE_STICKY" not in row["states"]
+ if above:
+ assert "_NET_WM_STATE_ABOVE" in row["states"]
+ print("PASS", name, flush=True)
+ overlay.show("Synthetic listening · microphone off")
+ overlay.set_text("中文测试 · synthetic transcript")
+ overlay.push_rms(.4)
+ settle(350)
+ inspect("before" if expect_hidden else "after", above=not expect_hidden, screenshot=True)
+ if expect_hidden:
+ assert not focus_changes
+ return
+ overlay.hide()
+ settle()
+ for reduced in (False, True):
+ for style in ("bars", "waves", "ripples", "basketball"):
+ overlay.waveform_style, overlay.reduced_motion = style, reduced
+ overlay.show("Synthetic listening")
+ overlay.push_rms(.4)
+ settle()
+ inspect(style + ("-reduced" if reduced else ""))
+ overlay.hide()
+ settle(50)
+ assert overlay._x11_stacking._process is None and overlay._x11_stacking._timeout is None
+ overlay.show_polishing("Synthetic polishing result")
+ settle()
+ inspect("polishing")
+ overlay.set_status("Synthetic transcribing")
+ settle()
+ inspect("transcribing")
+ overlay.hide()
+ settle()
+ assert not focus_changes, "Overlay changed keyboard focus before workspace switch"
+ command("wmctrl", "-n", "2")
+ command("wmctrl", "-i", "-r", hex(target_id), "-t", "1")
+ command("wmctrl", "-i", "-a", hex(target_id))
+ settle()
+ # Workspace transitions can temporarily focus root; check after settling.
+ focus_changes.clear()
+ overlay.show("Synthetic second workspace")
+ settle()
+ inspect("second-workspace")
+ overlay.hide()
+ settle()
+ command("wmctrl", "-i", "-r", hex(target_id), "-b", "remove,fullscreen")
+ settle()
+ overlay.show("Synthetic ordinary target")
+ settle()
+ inspect("ordinary-target")
+ overlay.hide()
+ settle()
+ with tempfile.TemporaryDirectory() as folder:
+ for mode in ("missing", "slow", "hide", "destroy"):
+ if mode == "slow":
+ helper = Path(folder) / "wmctrl"
+ helper.write_text("#!/bin/sh\nexec /usr/bin/sleep 10\n")
+ helper.chmod(0o755)
+ before = len(ticks)
+ with patch.dict(os.environ, {"PATH": folder}):
+ overlay.show("Synthetic helper failure")
+ child = overlay._x11_stacking._process
+ if mode == "hide":
+ overlay.hide()
+ elif mode == "destroy":
+ overlay._window.destroy()
+ settle(650 if mode in ("missing", "slow") else 180)
+ assert len(ticks) - before >= 4, "GTK blocked by helper"
+ assert overlay._x11_stacking._process is None and overlay._x11_stacking._timeout is None
+ if child is not None:
+ assert child.get_if_exited() or child.get_if_signaled()
+ overlay.hide()
+ settle(50)
+ print("PASS helper", mode, flush=True)
+ assert not focus_changes, "Overlay changed keyboard focus"
+ print("PASS repeated maps, states, workspace, focus and bounded helper cleanup", flush=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run", action="store_true")
+ parser.add_argument("--target", action="store_true")
+ parser.add_argument("--exercise", action="store_true")
+ parser.add_argument("--expect-hidden", action="store_true")
+ parser.add_argument("--artifacts", type=Path)
+ args = parser.parse_args()
+ if args.target:
+ target()
+ return
+ if args.artifacts is None or not (args.run or args.exercise):
+ parser.error("use --run --artifacts PATH")
+ artifacts = args.artifacts.resolve()
+ artifacts.mkdir(parents=True, exist_ok=True)
+ if args.exercise:
+ exercise(artifacts, args.expect_hidden)
+ return
+ with ExitStack() as cleanup, tempfile.TemporaryDirectory() as folder, hard_deadline(35):
+ env = {k: v for k, v in os.environ.items() if k not in ("WAYLAND_DISPLAY", "HYPRLAND_INSTANCE_SIGNATURE", "LD_PRELOAD")}
+ env.update(GDK_BACKEND="x11", GDK_SCALE="1", GSK_RENDERER="cairo", GTK_A11Y="none", NO_AT_BRIDGE="1",
+ XDG_SESSION_TYPE="x11", XDG_CONFIG_HOME=folder + "/config", XDG_CACHE_HOME=folder + "/cache",
+ XDG_DATA_HOME=folder + "/data", XDG_STATE_HOME=folder + "/state", PYTHONDONTWRITEBYTECODE="1")
+ read_fd, write_fd = os.pipe()
+ cleanup.callback(os.close, read_fd)
+ server = subprocess.Popen(["Xvfb", "-displayfd", str(write_fd), "-screen", "0", "1280x800x24", "-nolisten", "tcp"],
+ pass_fds=(write_fd,), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ cleanup.callback(stop, server)
+ os.close(write_fd)
+ assert select.select([read_fd], [], [], 4)[0], "Xvfb startup timed out"
+ env["DISPLAY"] = ":" + os.read(read_fd, 32).decode().strip()
+ child = subprocess.Popen(["dbus-run-session", "--", sys.executable, __file__, "--exercise", "--artifacts", str(artifacts),
+ *(["--expect-hidden"] if args.expect_hidden else [])], env=env)
+ cleanup.callback(stop, child)
+ assert child.wait(timeout=30) == 0, "Desktop probe failed"
+ print("PASS disposable desktop processes exited", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/unit/test_desktop.py b/tests/unit/test_desktop.py
index eec2c20..36dac64 100644
--- a/tests/unit/test_desktop.py
+++ b/tests/unit/test_desktop.py
@@ -100,7 +100,7 @@ class DesktopTest(TestCase):
from doubao_input.ui import overlay
class StopBeforeWidgets(Exception):
pass
- owner = SimpleNamespace(_window=None)
+ owner = overlay.Overlay()
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), \
@@ -111,9 +111,12 @@ class DesktopTest(TestCase):
with self.assertRaises(StopBeforeWidgets):
overlay.Overlay._ensure_window(owner)
win.set_focusable.assert_called_once_with(False)
- signal, callback = win.connect.call_args.args
- self.assertEqual(signal, "realize")
- callback(win)
+ handlers = dict(call.args for call in win.connect.call_args_list)
+ self.assertEqual(set(handlers), {"realize", "map", "unmap", "unrealize"})
+ self.assertEqual(handlers["map"], owner._x11_stacking.request)
+ self.assertEqual(handlers["unmap"], owner._x11_stacking.cancel)
+ self.assertEqual(handlers["unrealize"], owner._x11_stacking.cancel)
+ handlers["realize"](win)
user_time.assert_called_once_with(win.get_surface.return_value, 0)
layer.init_for_window.assert_not_called()
@@ -131,6 +134,7 @@ class DesktopTest(TestCase):
layer.is_supported.return_value = supported
with self.assertRaises(StopBeforeWidgets):
overlay.Overlay._ensure_window(SimpleNamespace(_window=None))
+ win.connect.assert_not_called()
if supported:
layer.init_for_window.assert_called_once_with(win)
layer.set_keyboard_mode.assert_called_once_with(win, layer.KeyboardMode.NONE)
diff --git a/tests/unit/test_overlay_stacking.py b/tests/unit/test_overlay_stacking.py
new file mode 100644
index 0000000..1507c0f
--- /dev/null
+++ b/tests/unit/test_overlay_stacking.py
@@ -0,0 +1,105 @@
+"""No display or processes: exercise the overlay helper's async lifecycle."""
+from unittest import TestCase
+from unittest.mock import Mock, patch
+
+import gi
+
+gi.require_version("GdkX11", "4.0")
+from gi.repository import GdkX11
+from doubao_input.ui import x11_stacking
+
+
+class OverlayStackingTest(TestCase):
+ def setUp(self):
+ self.owner = x11_stacking.X11Stacking()
+ self.window = Mock()
+ self.window.get_display.return_value.get_name.return_value = ":93.0"
+ self.window.get_mapped.return_value = True
+ self.candidates = self.enterContext(patch.object(
+ x11_stacking, "command_candidates", return_value=[["wmctrl"]]))
+ self.enterContext(patch.object(GdkX11.X11Surface, "get_xid", return_value=0x123))
+ self.launcher_type = self.enterContext(patch.object(x11_stacking.Gio, "SubprocessLauncher"))
+ self.launcher = self.launcher_type.new.return_value
+ self.timer = self.enterContext(patch.object(x11_stacking.GLib, "timeout_add", side_effect=range(10, 30)))
+ self.remove = self.enterContext(patch.object(x11_stacking.GLib, "source_remove"))
+ self.log = self.enterContext(patch.object(x11_stacking, "logger"))
+
+ def complete(self, process, success=True):
+ process.wait_check_finish.return_value = success
+ process.wait_check_async.call_args.args[1](process, Mock())
+
+ def test_own_window_request_is_async_and_cleans_up_after_success(self):
+ self.owner.request(self.window)
+ self.candidates.assert_called_once_with("wmctrl")
+ self.window.get_display.return_value.flush.assert_called_once()
+ self.launcher.setenv.assert_called_once_with("DISPLAY", ":93.0", True)
+ self.launcher.spawnv.assert_called_once_with(
+ ["wmctrl", "-i", "-r", "0x123", "-b", "add,above"])
+ process = self.owner._process
+ process.wait_check.assert_not_called()
+ self.complete(process)
+ self.assertIsNone(self.owner._process)
+ self.assertIsNone(self.owner._timeout)
+ self.remove.assert_called_once_with(10)
+ process.force_exit.assert_not_called()
+
+ def test_missing_helper_and_spawn_error_leave_overlay_usable(self):
+ for commands in ([], [["wmctrl"]]):
+ with self.subTest(commands=commands):
+ self.candidates.return_value = commands
+ self.launcher.spawnv.side_effect = x11_stacking.GLib.Error("missing")
+ self.owner.request(self.window)
+ self.assertIsNone(self.owner._process)
+ self.assertIsNone(self.owner._timeout)
+ self.timer.assert_not_called()
+
+ def test_failed_local_command_can_use_host_with_wrapper_cleanup(self):
+ self.candidates.return_value = [["wmctrl"], ["flatpak-spawn", "--host", "wmctrl"]]
+ first, host = Mock(), Mock()
+ self.launcher.spawnv.side_effect = [first, host]
+ self.owner.request(self.window)
+ first.wait_check_finish.side_effect = x11_stacking.GLib.Error("failed")
+ self.complete(first)
+ self.launcher.spawnv.assert_called_with([
+ "flatpak-spawn", "--watch-bus", "--env=DISPLAY=:93.0", "--host", "wmctrl",
+ "-i", "-r", "0x123", "-b", "add,above"])
+ self.complete(host)
+ self.assertIsNone(self.owner._process)
+ self.assertEqual(self.remove.call_count, 2)
+
+ def test_timeout_kills_and_reaps_without_starting_fallback(self):
+ self.candidates.return_value = [["wmctrl"], ["flatpak-spawn", "--host", "wmctrl"]]
+ self.owner.request(self.window)
+ process = self.owner._process
+ delay, callback = self.timer.call_args.args
+ self.assertEqual(delay, 500)
+ self.assertFalse(callback())
+ process.force_exit.assert_called_once()
+ self.assertIsNone(self.owner._timeout)
+ self.complete(process, False)
+ process.wait_check_finish.assert_called_once()
+ self.launcher.spawnv.assert_called_once()
+ self.remove.assert_not_called()
+
+ def test_late_cancelled_completion_cannot_touch_next_mapping(self):
+ first, second = Mock(), Mock()
+ self.launcher.spawnv.side_effect = [first, second]
+ self.owner.request(self.window)
+ self.owner.cancel(self.window)
+ first.force_exit.assert_called_once()
+ self.owner.request(self.window)
+ self.complete(first, False)
+ self.assertIs(self.owner._process, second)
+ self.assertEqual(self.owner._timeout, 11)
+ self.remove.assert_called_once_with(10)
+ self.owner.cancel(self.window)
+ self.complete(second, False)
+ self.assertIsNone(self.owner._process)
+ self.assertIsNone(self.owner._timeout)
+ self.assertEqual(self.launcher.spawnv.call_count, 2)
+
+ def test_unmapped_window_never_starts_a_helper(self):
+ self.window.get_mapped.return_value = False
+ self.owner.request(self.window)
+ self.launcher.spawnv.assert_not_called()
+ self.timer.assert_not_called()