xstudio-linux 0.0.0-stage → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +443 -0
- package/LICENSE +31 -0
- package/README.md +527 -2
- package/dist/adapter-cli/cli.d.ts +28 -0
- package/dist/adapter-cli/cli.js +235 -0
- package/dist/adapter-cli/cli.js.map +1 -0
- package/dist/adapter-mcp/server.d.ts +81 -0
- package/dist/adapter-mcp/server.js +477 -0
- package/dist/adapter-mcp/server.js.map +1 -0
- package/dist/config.d.ts +45 -0
- package/dist/config.js +78 -0
- package/dist/config.js.map +1 -0
- package/dist/core/catalog/pronunciation.d.ts +47 -0
- package/dist/core/catalog/pronunciation.js +402 -0
- package/dist/core/catalog/pronunciation.js.map +1 -0
- package/dist/core/catalog/singers.d.ts +46 -0
- package/dist/core/catalog/singers.js +122 -0
- package/dist/core/catalog/singers.js.map +1 -0
- package/dist/core/contracts.d.ts +348 -0
- package/dist/core/contracts.js +17 -0
- package/dist/core/contracts.js.map +1 -0
- package/dist/core/degrade/chain.d.ts +80 -0
- package/dist/core/degrade/chain.js +137 -0
- package/dist/core/degrade/chain.js.map +1 -0
- package/dist/core/diagnose/error-resolver.d.ts +51 -0
- package/dist/core/diagnose/error-resolver.js +202 -0
- package/dist/core/diagnose/error-resolver.js.map +1 -0
- package/dist/core/guard/skill-gate.d.ts +89 -0
- package/dist/core/guard/skill-gate.js +121 -0
- package/dist/core/guard/skill-gate.js.map +1 -0
- package/dist/core/midi/convert.d.ts +31 -0
- package/dist/core/midi/convert.js +125 -0
- package/dist/core/midi/convert.js.map +1 -0
- package/dist/core/midi/smf.d.ts +37 -0
- package/dist/core/midi/smf.js +422 -0
- package/dist/core/midi/smf.js.map +1 -0
- package/dist/core/render/artifacts.d.ts +37 -0
- package/dist/core/render/artifacts.js +417 -0
- package/dist/core/render/artifacts.js.map +1 -0
- package/dist/core/render/orchestrator.d.ts +110 -0
- package/dist/core/render/orchestrator.js +974 -0
- package/dist/core/render/orchestrator.js.map +1 -0
- package/dist/core/svip/codec.d.ts +30 -0
- package/dist/core/svip/codec.js +664 -0
- package/dist/core/svip/codec.js.map +1 -0
- package/dist/core/svip/document.d.ts +31 -0
- package/dist/core/svip/document.js +158 -0
- package/dist/core/svip/document.js.map +1 -0
- package/dist/core/svip/editor.d.ts +71 -0
- package/dist/core/svip/editor.js +245 -0
- package/dist/core/svip/editor.js.map +1 -0
- package/dist/core/svip/model.d.ts +74 -0
- package/dist/core/svip/model.js +158 -0
- package/dist/core/svip/model.js.map +1 -0
- package/dist/core/svip/tick.d.ts +21 -0
- package/dist/core/svip/tick.js +59 -0
- package/dist/core/svip/tick.js.map +1 -0
- package/dist/core/svip/validator.d.ts +39 -0
- package/dist/core/svip/validator.js +267 -0
- package/dist/core/svip/validator.js.map +1 -0
- package/dist/host/linux.d.ts +15 -0
- package/dist/host/linux.js +42 -0
- package/dist/host/linux.js.map +1 -0
- package/dist/host/sidecar.d.ts +61 -0
- package/dist/host/sidecar.js +365 -0
- package/dist/host/sidecar.js.map +1 -0
- package/dist/host/wine-launch.d.ts +60 -0
- package/dist/host/wine-launch.js +77 -0
- package/dist/host/wine-launch.js.map +1 -0
- package/dist/host/wine-paths.d.ts +30 -0
- package/dist/host/wine-paths.js +103 -0
- package/dist/host/wine-paths.js.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/services.d.ts +55 -0
- package/dist/services.js +78 -0
- package/dist/services.js.map +1 -0
- package/dist/shared/errors.d.ts +61 -0
- package/dist/shared/errors.js +125 -0
- package/dist/shared/errors.js.map +1 -0
- package/dist/shared/paths.d.ts +8 -0
- package/dist/shared/paths.js +30 -0
- package/dist/shared/paths.js.map +1 -0
- package/dist/shared/schema.d.ts +26 -0
- package/dist/shared/schema.js +68 -0
- package/dist/shared/schema.js.map +1 -0
- package/dist/shared/types.d.ts +43 -0
- package/dist/shared/types.js +19 -0
- package/dist/shared/types.js.map +1 -0
- package/dist/tests/unit/artifacts.test.d.ts +1 -0
- package/dist/tests/unit/artifacts.test.js +243 -0
- package/dist/tests/unit/artifacts.test.js.map +1 -0
- package/dist/tests/unit/data-plane.test.d.ts +1 -0
- package/dist/tests/unit/data-plane.test.js +153 -0
- package/dist/tests/unit/data-plane.test.js.map +1 -0
- package/dist/tests/unit/degrade.test.d.ts +1 -0
- package/dist/tests/unit/degrade.test.js +133 -0
- package/dist/tests/unit/degrade.test.js.map +1 -0
- package/dist/tests/unit/diagnosis.test.d.ts +1 -0
- package/dist/tests/unit/diagnosis.test.js +66 -0
- package/dist/tests/unit/diagnosis.test.js.map +1 -0
- package/dist/tests/unit/errors.test.d.ts +1 -0
- package/dist/tests/unit/errors.test.js +83 -0
- package/dist/tests/unit/errors.test.js.map +1 -0
- package/dist/tests/unit/mcp-server.test.d.ts +1 -0
- package/dist/tests/unit/mcp-server.test.js +267 -0
- package/dist/tests/unit/mcp-server.test.js.map +1 -0
- package/dist/tests/unit/mcp-smoke.d.ts +6 -0
- package/dist/tests/unit/mcp-smoke.js +7 -0
- package/dist/tests/unit/mcp-smoke.js.map +1 -0
- package/dist/tests/unit/mcp-smoke.test.d.ts +1 -0
- package/dist/tests/unit/mcp-smoke.test.js +196 -0
- package/dist/tests/unit/mcp-smoke.test.js.map +1 -0
- package/dist/tests/unit/midi.test.d.ts +1 -0
- package/dist/tests/unit/midi.test.js +255 -0
- package/dist/tests/unit/midi.test.js.map +1 -0
- package/dist/tests/unit/pronunciation.test.d.ts +1 -0
- package/dist/tests/unit/pronunciation.test.js +83 -0
- package/dist/tests/unit/pronunciation.test.js.map +1 -0
- package/dist/tests/unit/registry-contract.test.d.ts +1 -0
- package/dist/tests/unit/registry-contract.test.js +114 -0
- package/dist/tests/unit/registry-contract.test.js.map +1 -0
- package/dist/tests/unit/render-orchestrator.test.d.ts +1 -0
- package/dist/tests/unit/render-orchestrator.test.js +548 -0
- package/dist/tests/unit/render-orchestrator.test.js.map +1 -0
- package/dist/tests/unit/sidecar.test.d.ts +1 -0
- package/dist/tests/unit/sidecar.test.js +299 -0
- package/dist/tests/unit/sidecar.test.js.map +1 -0
- package/dist/tests/unit/singers.test.d.ts +1 -0
- package/dist/tests/unit/singers.test.js +73 -0
- package/dist/tests/unit/singers.test.js.map +1 -0
- package/dist/tests/unit/skill-gate.test.d.ts +1 -0
- package/dist/tests/unit/skill-gate.test.js +182 -0
- package/dist/tests/unit/skill-gate.test.js.map +1 -0
- package/dist/tests/unit/svip-codec.test.d.ts +1 -0
- package/dist/tests/unit/svip-codec.test.js +182 -0
- package/dist/tests/unit/svip-codec.test.js.map +1 -0
- package/dist/tests/unit/svip-document.test.d.ts +1 -0
- package/dist/tests/unit/svip-document.test.js +137 -0
- package/dist/tests/unit/svip-document.test.js.map +1 -0
- package/dist/tests/unit/svip-editor.test.d.ts +1 -0
- package/dist/tests/unit/svip-editor.test.js +275 -0
- package/dist/tests/unit/svip-editor.test.js.map +1 -0
- package/dist/tests/unit/svip-tick.test.d.ts +1 -0
- package/dist/tests/unit/svip-tick.test.js +66 -0
- package/dist/tests/unit/svip-tick.test.js.map +1 -0
- package/dist/tools/common.d.ts +80 -0
- package/dist/tools/common.js +167 -0
- package/dist/tools/common.js.map +1 -0
- package/dist/tools/control.d.ts +21 -0
- package/dist/tools/control.js +376 -0
- package/dist/tools/control.js.map +1 -0
- package/dist/tools/data.d.ts +37 -0
- package/dist/tools/data.js +680 -0
- package/dist/tools/data.js.map +1 -0
- package/dist/tools/definition.d.ts +60 -0
- package/dist/tools/definition.js +44 -0
- package/dist/tools/definition.js.map +1 -0
- package/dist/tools/degrade.d.ts +3 -0
- package/dist/tools/degrade.js +30 -0
- package/dist/tools/degrade.js.map +1 -0
- package/dist/tools/guide.d.ts +10 -0
- package/dist/tools/guide.js +66 -0
- package/dist/tools/guide.js.map +1 -0
- package/dist/tools/open.d.ts +3 -0
- package/dist/tools/open.js +74 -0
- package/dist/tools/open.js.map +1 -0
- package/dist/tools/probe.d.ts +8 -0
- package/dist/tools/probe.js +132 -0
- package/dist/tools/probe.js.map +1 -0
- package/dist/tools/registry.d.ts +10 -0
- package/dist/tools/registry.js +16 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/version.d.ts +4 -0
- package/dist/version.js +19 -0
- package/dist/version.js.map +1 -0
- package/docs/DESIGN.md +553 -0
- package/docs/RECON-GUI.md +271 -0
- package/docs/RECON.md +339 -0
- package/docs/SPEC.md +786 -0
- package/docs/WINE.md +192 -0
- package/examples/.scratch/01-midi-to-wudi/wudi-demo.svip3 +0 -0
- package/examples/.scratch/01-midi-to-wudi/wudi-melody.mid +0 -0
- package/examples/.scratch/01-midi-to-wudi/wudi-roundtrip.mid +0 -0
- package/examples/.scratch/02-three-singers/melody.chenziyu.svip3 +0 -0
- package/examples/.scratch/02-three-singers/melody.hechang.svip3 +0 -0
- package/examples/.scratch/02-three-singers/melody.svip3 +0 -0
- package/examples/.scratch/02-three-singers/melody.wudi.svip3 +0 -0
- package/examples/.scratch/03-velocity-diction/phrase.svip3 +0 -0
- package/examples/.scratch/03-velocity-diction/phrase.svip3.bak.20261206-163755-200 +0 -0
- package/examples/.scratch/03-velocity-diction/phrase.svip3.bak.20261206-163755-203 +0 -0
- package/examples/.scratch/03-velocity-diction/phrase.svip3.bak.20261206-163755-204 +0 -0
- package/examples/.scratch/04-unknown-dialog-abort/dialog-demo.svip3 +0 -0
- package/examples/01-midi-to-wudi.mjs +144 -0
- package/examples/02-three-singers-compare.mjs +140 -0
- package/examples/03-velocity-diction-rerender.mjs +160 -0
- package/examples/04-unknown-dialog-abort.mjs +126 -0
- package/examples/README.md +101 -0
- package/examples/lib/harness.mjs +274 -0
- package/fixtures/midi/melody-480.mid +0 -0
- package/fixtures/midi/melody-96.mid +0 -0
- package/fixtures/svip/1.svip3 +0 -0
- package/fixtures/svip/3.svip3 +0 -0
- package/fixtures/uia/README.md +37 -0
- package/fixtures/uia/export-dialog.snapshot.json +446 -0
- package/fixtures/uia/main-window.snapshot.json +2997 -0
- package/fixtures/uia/open-dialog.snapshot.json +103 -0
- package/icon.svg +10 -0
- package/package.json +84 -4
- package/proto/xstudio.proto +128 -0
- package/scripts/check-contract.mjs +184 -0
- package/scripts/entry-smoke.mjs +26 -0
- package/scripts/inspect-svip.mjs +161 -0
- package/scripts/setup-venv.sh +93 -0
- package/scripts/wine-gui-probe.py +302 -0
- package/sidecar/xstudio_uia.py +1478 -0
- package/skills/xstudio-gui/SKILL.md +194 -0
- package/skills/xstudio-gui/assertions.md +103 -0
- package/skills/xstudio-gui/dialogs.md +90 -0
- package/skills/xstudio-gui/gestures.md +158 -0
- package/skills/xstudio-gui/ui-map.json +242 -0
|
@@ -0,0 +1,1478 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
UIA sidecar for xstudio-linux (Wine edition).
|
|
5
|
+
|
|
6
|
+
A long-running Python 3 process that speaks newline-delimited JSON on
|
|
7
|
+
stdin/stdout — the exact protocol of the previous PowerShell sidecar
|
|
8
|
+
(sidecar/uia.ps1 on the Windows build). One request per line:
|
|
9
|
+
|
|
10
|
+
{"id":"r1","method":"probe","params":{...}}
|
|
11
|
+
|
|
12
|
+
and one response per line:
|
|
13
|
+
|
|
14
|
+
{"id":"r1","ok":true,"data":{...}}
|
|
15
|
+
{"id":"r1","ok":false,"error":{"code":"GUI_REF_NOT_FOUND","message":"...","hint":"..."}}
|
|
16
|
+
|
|
17
|
+
Methods: probe, snapshot, act, assert, readDialog, respondDialog, abort, close.
|
|
18
|
+
|
|
19
|
+
Implementation notes
|
|
20
|
+
--------------------
|
|
21
|
+
* Window discovery: X11 via Xlib when available, falling back to ``xdotool``
|
|
22
|
+
subprocess queries. The main window is matched by WM_CLASS ``Qt*QWindowIcon*``
|
|
23
|
+
(the Wine-mapped Qt 6 window class) plus a title containing the X Studio
|
|
24
|
+
process name — the same identity the Windows build verified.
|
|
25
|
+
* Element tree: AT-SPI2 via ``pyatspi`` when the desktop's accessibility bus
|
|
26
|
+
exposes the Wine application. Wine's UIA exposure is build-dependent; when
|
|
27
|
+
the tree is unreachable the sidecar still answers probe/snapshot at the
|
|
28
|
+
window level and rejects element-addressed actions with GUI_REF_NOT_FOUND.
|
|
29
|
+
* Actions are pattern-based only (AT-SPI Action/Text/EditableText interfaces).
|
|
30
|
+
Screen coordinates are never consumed; element rectangles are reported only.
|
|
31
|
+
* Destructive element names (save/overwrite/delete/quit/…) are refused for
|
|
32
|
+
click/invoke actions; a destructive dialog is never auto-confirmed.
|
|
33
|
+
* When ``--require-foreground`` is set, mutating actions fail with
|
|
34
|
+
GUI_FOCUS_LOST unless the X Studio window is active.
|
|
35
|
+
|
|
36
|
+
This script never spawns X Studio and never writes into the user's project.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import json
|
|
42
|
+
import os
|
|
43
|
+
import struct
|
|
44
|
+
import re
|
|
45
|
+
import secrets
|
|
46
|
+
import subprocess
|
|
47
|
+
import sys
|
|
48
|
+
import threading
|
|
49
|
+
import time
|
|
50
|
+
import uuid
|
|
51
|
+
|
|
52
|
+
try: # X11 window queries (window list, active window, titles, WM_CLASS)
|
|
53
|
+
import Xlib # noqa: F401
|
|
54
|
+
from Xlib import display as xdisplay
|
|
55
|
+
from Xlib import X, XK # noqa: F401
|
|
56
|
+
from Xlib.ext import xtest # noqa: F401
|
|
57
|
+
|
|
58
|
+
_XLIB_AVAILABLE = True
|
|
59
|
+
except Exception: # pragma: no cover - depends on the host
|
|
60
|
+
_XLIB_AVAILABLE = False
|
|
61
|
+
|
|
62
|
+
# The _NET_WM_NAME atom, resolved once from the backend's own Display and kept
|
|
63
|
+
# module-level because Xlib Window objects cannot resolve atoms themselves.
|
|
64
|
+
_NET_WM_NAME_ATOM = None
|
|
65
|
+
_NET_WM_PID_ATOM = None
|
|
66
|
+
|
|
67
|
+
# AT-SPI2 accessibility tree: pyatspi when present, otherwise GObject
|
|
68
|
+
# Introspection (gi.repository.Atspi — the package most distros ship).
|
|
69
|
+
_atspi = None
|
|
70
|
+
_ATSPI_BACKEND = "none"
|
|
71
|
+
try:
|
|
72
|
+
import pyatspi as _atspi
|
|
73
|
+
|
|
74
|
+
_ATSPI_BACKEND = "pyatspi"
|
|
75
|
+
except Exception:
|
|
76
|
+
try:
|
|
77
|
+
import gi
|
|
78
|
+
|
|
79
|
+
gi.require_version("Atspi", "2.0")
|
|
80
|
+
from gi.repository import Atspi as _atspi_gi
|
|
81
|
+
|
|
82
|
+
_atspi = _atspi_gi
|
|
83
|
+
_ATSPI_BACKEND = "gi"
|
|
84
|
+
except Exception:
|
|
85
|
+
_atspi = None
|
|
86
|
+
_ATSPI_AVAILABLE = _atspi is not None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _atspi_desktop(): # type: ignore[no-untyped-def]
|
|
90
|
+
if _atspi is None:
|
|
91
|
+
return None
|
|
92
|
+
try:
|
|
93
|
+
if _ATSPI_BACKEND == "gi":
|
|
94
|
+
return _atspi.get_desktop(0)
|
|
95
|
+
return _atspi.Registry.getDesktop(0)
|
|
96
|
+
except Exception:
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _atspi_children(node): # type: ignore[no-untyped-def]
|
|
101
|
+
try:
|
|
102
|
+
if _ATSPI_BACKEND == "gi":
|
|
103
|
+
return [node.get_child_at_index(i) for i in range(node.get_child_count())]
|
|
104
|
+
return list(node)
|
|
105
|
+
except Exception:
|
|
106
|
+
return []
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _atspi_name(node): # type: ignore[no-untyped-def]
|
|
110
|
+
try:
|
|
111
|
+
return (node.get_name() if _ATSPI_BACKEND == "gi" else node.name) or ""
|
|
112
|
+
except Exception:
|
|
113
|
+
return ""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _atspi_role(node): # type: ignore[no-untyped-def]
|
|
117
|
+
try:
|
|
118
|
+
return (node.get_role_name() if _ATSPI_BACKEND == "gi" else node.getRoleName()) or ""
|
|
119
|
+
except Exception:
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
# --------------------------------------------------------------------------
|
|
123
|
+
# Constants shared with the Windows build's contract
|
|
124
|
+
# --------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
PROCESS_NAME = "NetEase Cloud Music XStudio"
|
|
127
|
+
# Windows-native builds expose WM_CLASS "Qt622QWindowIcon"; under Wine the
|
|
128
|
+
# class is the process name lowercased with an .exe suffix (verified live:
|
|
129
|
+
# WM_CLASS "netease cloud music xstudio.exe"). Accept both.
|
|
130
|
+
WINDOW_CLASS_PATTERN = re.compile(
|
|
131
|
+
r"Qt.*QWindowIcon.*|netease cloud music xstudio(\.exe)?",
|
|
132
|
+
re.IGNORECASE,
|
|
133
|
+
)
|
|
134
|
+
IGNORED_CLASS_PATTERN = re.compile(r"Qt.*QWindowToolTip.*|MSCTFIME UI|^IME$|^JUCE_")
|
|
135
|
+
# Helper windows Wine creates for the same process (verified live): input
|
|
136
|
+
# method, audio backend and the JUCE helper — never the main window.
|
|
137
|
+
HELPER_TITLE_PATTERN = re.compile(
|
|
138
|
+
r"^(Default IME|JUCEWindow|Windows Audio|DirectSound|MSCTFIME UI|IME)$",
|
|
139
|
+
re.IGNORECASE,
|
|
140
|
+
)
|
|
141
|
+
DIALOG_CLASS = "#32770" # Wine maps Win32 dialogs to this class name too
|
|
142
|
+
TOAST_CLASS_PATTERN = re.compile(r".*Toast.*", re.IGNORECASE)
|
|
143
|
+
|
|
144
|
+
DESTRUCTIVE_NAME_PATTERN = re.compile(
|
|
145
|
+
r"保存|覆盖|删除|退出|卸载|清除|注销|save|overwrite|delete|quit|exit|uninstall",
|
|
146
|
+
re.IGNORECASE,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
DEFAULT_MAX_ELEMENTS = 600
|
|
150
|
+
MAX_DEPTH = 14
|
|
151
|
+
SNAPSHOT_METHOD_TIMEOUT = 4.0 # seconds for one AT-SPI tree walk
|
|
152
|
+
|
|
153
|
+
RESPOND_CHOICES = {
|
|
154
|
+
"cancel": ["取消", "关闭", "否", "cancel", "close", "no", "don't save", "不保存"],
|
|
155
|
+
"dismiss": ["关闭", "忽略", "稍后", "dismiss", "close", "later", "ignore"],
|
|
156
|
+
"confirm": ["确认", "确定", "是", "好", "ok", "yes", "confirm", "open", "打开"],
|
|
157
|
+
"retry": ["重试", "retry", "again"],
|
|
158
|
+
"login": ["登录", "login", "sign in"],
|
|
159
|
+
"manual": [],
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
ERROR_HINTS = {
|
|
163
|
+
"XSTUDIO_NOT_RUNNING": "Start X Studio under Wine, then retry (wine …/NetEase Cloud Music XStudio.exe).",
|
|
164
|
+
"GUI_REF_NOT_FOUND": "Call snapshot again: refs are valid for the latest snapshot only.",
|
|
165
|
+
"GUI_FOCUS_LOST": "Call probe with params {\"activate\": true} to raise the X Studio window via the window manager, then retry.",
|
|
166
|
+
"GUI_ACTION_FAILED": "Check the element state in a fresh snapshot; the action may not be supported.",
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class SidecarProtocolError(Exception):
|
|
171
|
+
"""One structured failure carrying a stable sidecar error code."""
|
|
172
|
+
|
|
173
|
+
def __init__(self, code: str, message: str, hint: str | None = None):
|
|
174
|
+
super().__init__(message)
|
|
175
|
+
self.code = code
|
|
176
|
+
self.message = message
|
|
177
|
+
self.hint = hint or ERROR_HINTS.get(code)
|
|
178
|
+
|
|
179
|
+
def to_payload(self) -> dict:
|
|
180
|
+
error = {"code": self.code, "message": self.message}
|
|
181
|
+
if self.hint:
|
|
182
|
+
error["hint"] = self.hint
|
|
183
|
+
return error
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# --------------------------------------------------------------------------
|
|
187
|
+
# X11 window backend
|
|
188
|
+
# --------------------------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class X11Backend:
|
|
192
|
+
"""Read-only X11 window enumeration via Xlib, with an xdotool fallback."""
|
|
193
|
+
|
|
194
|
+
def __init__(self) -> None:
|
|
195
|
+
self.display = None
|
|
196
|
+
self.net_wm_name_atom = None
|
|
197
|
+
global _NET_WM_NAME_ATOM, _NET_WM_PID_ATOM
|
|
198
|
+
if _XLIB_AVAILABLE:
|
|
199
|
+
try:
|
|
200
|
+
self.display = xdisplay.Display()
|
|
201
|
+
self.net_wm_name_atom = self.display.intern_atom("_NET_WM_NAME")
|
|
202
|
+
_NET_WM_NAME_ATOM = self.net_wm_name_atom
|
|
203
|
+
_NET_WM_PID_ATOM = self.display.intern_atom("_NET_WM_PID")
|
|
204
|
+
except Exception:
|
|
205
|
+
self.display = None
|
|
206
|
+
|
|
207
|
+
# -- low-level helpers ------------------------------------------------
|
|
208
|
+
|
|
209
|
+
def _xdotool(self, *args: str) -> str | None:
|
|
210
|
+
try:
|
|
211
|
+
result = subprocess.run(
|
|
212
|
+
["xdotool", *args],
|
|
213
|
+
capture_output=True,
|
|
214
|
+
text=True,
|
|
215
|
+
timeout=5,
|
|
216
|
+
check=False,
|
|
217
|
+
)
|
|
218
|
+
if result.returncode != 0:
|
|
219
|
+
return None
|
|
220
|
+
return result.stdout.strip()
|
|
221
|
+
except Exception:
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
@staticmethod
|
|
225
|
+
def _window_name(xwindow) -> str: # type: ignore[no-untyped-def]
|
|
226
|
+
# _NET_WM_NAME (UTF-8) first: Wine apps often carry CJK titles that the
|
|
227
|
+
# legacy WM_NAME (COMPOUND_TEXT) cannot represent — verified live with
|
|
228
|
+
# the 网易云音乐·X Studio main window.
|
|
229
|
+
try:
|
|
230
|
+
prop = xwindow.get_full_property(xwindow._NET_WM_NAME_atom, 0) if hasattr(xwindow, "_NET_WM_NAME_atom") else None
|
|
231
|
+
except Exception:
|
|
232
|
+
prop = None
|
|
233
|
+
if prop is None:
|
|
234
|
+
# python-xlib Window objects do not expose the owning Display's
|
|
235
|
+
# intern_atom; the backend pre-resolves the atom in __init__ and
|
|
236
|
+
# passes it via the module-level cache below.
|
|
237
|
+
try:
|
|
238
|
+
prop = xwindow.get_full_property(_NET_WM_NAME_ATOM, 0)
|
|
239
|
+
except Exception:
|
|
240
|
+
prop = None
|
|
241
|
+
try:
|
|
242
|
+
if prop is not None and prop.value:
|
|
243
|
+
return prop.value.decode("utf-8", "replace")
|
|
244
|
+
except Exception:
|
|
245
|
+
pass
|
|
246
|
+
try:
|
|
247
|
+
name = xwindow.get_wm_name()
|
|
248
|
+
if isinstance(name, bytes):
|
|
249
|
+
name = name.decode("latin1", "replace")
|
|
250
|
+
if isinstance(name, str) and name:
|
|
251
|
+
return name
|
|
252
|
+
except Exception:
|
|
253
|
+
pass
|
|
254
|
+
return ""
|
|
255
|
+
|
|
256
|
+
@staticmethod
|
|
257
|
+
def _window_class(xwindow) -> str: # type: ignore[no-untyped-def]
|
|
258
|
+
try:
|
|
259
|
+
wm_class = xwindow.get_wm_class()
|
|
260
|
+
if isinstance(wm_class, (list, tuple)) and len(wm_class) >= 2:
|
|
261
|
+
return f"{wm_class[0] or ''}|{wm_class[1] or ''}"
|
|
262
|
+
except Exception:
|
|
263
|
+
pass
|
|
264
|
+
return ""
|
|
265
|
+
|
|
266
|
+
def _windows(self) -> list: # type: ignore[no-untyped-def]
|
|
267
|
+
if self.display is None:
|
|
268
|
+
return []
|
|
269
|
+
try:
|
|
270
|
+
root = self.display.screen().root
|
|
271
|
+
return list(root.query_tree().children)
|
|
272
|
+
except Exception:
|
|
273
|
+
return []
|
|
274
|
+
|
|
275
|
+
# -- public API --------------------------------------------------------
|
|
276
|
+
|
|
277
|
+
def find_main_window(self) -> dict | None:
|
|
278
|
+
"""Return {xid, title, pid, className} for the X Studio main window.
|
|
279
|
+
|
|
280
|
+
Also searches one level of child windows: `wine explorer /desktop=…`
|
|
281
|
+
nests every app window inside a single managed desktop window.
|
|
282
|
+
"""
|
|
283
|
+
candidates: list[dict] = []
|
|
284
|
+
search_list: list = []
|
|
285
|
+
for top in self._windows():
|
|
286
|
+
search_list.append(top)
|
|
287
|
+
try:
|
|
288
|
+
# One nested level (the wine-desktop case); deeper nesting is
|
|
289
|
+
# not a real Wine layout.
|
|
290
|
+
search_list.extend(top.query_tree().children)
|
|
291
|
+
except Exception:
|
|
292
|
+
pass
|
|
293
|
+
for xwindow in search_list:
|
|
294
|
+
try:
|
|
295
|
+
klass = self._window_class(xwindow)
|
|
296
|
+
if not WINDOW_CLASS_PATTERN.search(klass):
|
|
297
|
+
continue
|
|
298
|
+
if IGNORED_CLASS_PATTERN.search(klass):
|
|
299
|
+
continue
|
|
300
|
+
title = self._window_name(xwindow)
|
|
301
|
+
if HELPER_TITLE_PATTERN.match(title):
|
|
302
|
+
continue
|
|
303
|
+
# Title may be empty under Wine (verified live); the class match
|
|
304
|
+
# alone identifies the process. Rank by geometry: the main
|
|
305
|
+
# window is by far the largest mapped top-level of the group.
|
|
306
|
+
geometry = None
|
|
307
|
+
mapped = False
|
|
308
|
+
try:
|
|
309
|
+
g = xwindow.get_geometry()
|
|
310
|
+
geometry = (int(g.width), int(g.height))
|
|
311
|
+
mapped = xwindow.get_attributes().map_state == 2 # IsViewable
|
|
312
|
+
except Exception:
|
|
313
|
+
geometry = (0, 0)
|
|
314
|
+
pid = 0
|
|
315
|
+
try:
|
|
316
|
+
if _NET_WM_PID_ATOM is not None:
|
|
317
|
+
prop = xwindow.get_full_property(_NET_WM_PID_ATOM, 0)
|
|
318
|
+
if prop is not None and prop.value:
|
|
319
|
+
pid = int(prop.value[0])
|
|
320
|
+
except Exception:
|
|
321
|
+
pid = 0
|
|
322
|
+
candidates.append(
|
|
323
|
+
{
|
|
324
|
+
"xid": int(xwindow.id),
|
|
325
|
+
"title": title,
|
|
326
|
+
"pid": int(pid),
|
|
327
|
+
"className": klass.split("|")[-1] or klass,
|
|
328
|
+
"area": geometry[0] * geometry[1],
|
|
329
|
+
"mapped": mapped,
|
|
330
|
+
}
|
|
331
|
+
)
|
|
332
|
+
except Exception:
|
|
333
|
+
continue
|
|
334
|
+
if not candidates:
|
|
335
|
+
return None
|
|
336
|
+
# Prefer the mapped (viewable) window when one exists — the unmapped
|
|
337
|
+
# candidate is an iconic/minimized instance.
|
|
338
|
+
best = max(candidates, key=lambda c: (c["mapped"], c["area"]))
|
|
339
|
+
best.pop("area", None)
|
|
340
|
+
return best
|
|
341
|
+
|
|
342
|
+
def _kwin_activate(self) -> bool:
|
|
343
|
+
"""Set the KWin Wayland active window to X Studio via a temp script.
|
|
344
|
+
|
|
345
|
+
X-level activation alone does NOT move the Wayland focus; keyboard
|
|
346
|
+
synthesis (XTEST/uinput) only reaches the app once KWin itself routes
|
|
347
|
+
input to the XWayland surface (verified live: after this call a uinput
|
|
348
|
+
Space produces Wine CPU activity and an XsToast).
|
|
349
|
+
"""
|
|
350
|
+
import tempfile
|
|
351
|
+
|
|
352
|
+
script = """
|
|
353
|
+
const target = [];
|
|
354
|
+
workspace.windowList().forEach(w => {
|
|
355
|
+
const cls = String(w.resourceClass).toLowerCase();
|
|
356
|
+
const cap = String(w.caption);
|
|
357
|
+
if (cls.includes('xstudio') || cap.includes('X Studio') || (cls.includes('explorer') && cap.includes('Wine'))) {
|
|
358
|
+
target.push(w);
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
if (target.length > 0) {
|
|
362
|
+
// Prefer the largest candidate (the wine-desktop window when present).
|
|
363
|
+
target.sort((a, b) => (b.area || 0) - (a.area || 0) || (b.caption || '').length - (a.caption || '').length);
|
|
364
|
+
workspace.activeWindow = target[0];
|
|
365
|
+
print('ACTIVATED: ' + target[0].caption);
|
|
366
|
+
} else {
|
|
367
|
+
print('NOT FOUND');
|
|
368
|
+
}
|
|
369
|
+
"""
|
|
370
|
+
try:
|
|
371
|
+
fd, path = tempfile.mkstemp(suffix='.js', prefix='xstudio-activate-')
|
|
372
|
+
with os.fdopen(fd, 'w') as f:
|
|
373
|
+
f.write(script)
|
|
374
|
+
import shutil
|
|
375
|
+
qdbus = shutil.which('qdbus6') or shutil.which('qdbus')
|
|
376
|
+
if qdbus is None:
|
|
377
|
+
return False
|
|
378
|
+
def run(*args: str) -> str:
|
|
379
|
+
return subprocess.run([qdbus, *args], capture_output=True, text=True, timeout=5).stdout.strip()
|
|
380
|
+
unique_name = f'xstudio-activate-{uuid.uuid4().hex[:8]}'
|
|
381
|
+
sid = run('org.kde.KWin', '/Scripting', 'org.kde.kwin.Scripting.loadScript', path, unique_name)
|
|
382
|
+
if not sid:
|
|
383
|
+
return False
|
|
384
|
+
subprocess.run([qdbus, 'org.kde.KWin', f'/Scripting/Script{sid}', 'org.kde.kwin.Script.run'],
|
|
385
|
+
capture_output=True, text=True, timeout=5)
|
|
386
|
+
time.sleep(0.8)
|
|
387
|
+
subprocess.run([qdbus, 'org.kde.KWin', f'/Scripting/Script{sid}', 'org.kde.kwin.Script.stop'],
|
|
388
|
+
capture_output=True, text=True, timeout=5)
|
|
389
|
+
try:
|
|
390
|
+
os.unlink(path)
|
|
391
|
+
except Exception:
|
|
392
|
+
pass
|
|
393
|
+
return True
|
|
394
|
+
except Exception:
|
|
395
|
+
return False
|
|
396
|
+
|
|
397
|
+
def activate_window(self, xid: int | None) -> bool:
|
|
398
|
+
"""Deiconify + raise X Studio at both levels: the X server (EWMH) and
|
|
399
|
+
the Wayland compositor (KWin activeWindow). The Wayland step is the
|
|
400
|
+
one that actually routes keyboard input (verified live)."""
|
|
401
|
+
if xid is None:
|
|
402
|
+
return False
|
|
403
|
+
# Wayland/compositor level first — without it, X-level activation is
|
|
404
|
+
# cosmetic for input routing.
|
|
405
|
+
self._kwin_activate()
|
|
406
|
+
if self.display is None:
|
|
407
|
+
return self.app_owns_foreground(xid)
|
|
408
|
+
try:
|
|
409
|
+
from Xlib import X
|
|
410
|
+
from Xlib.protocol import event as xevent
|
|
411
|
+
|
|
412
|
+
root = self.display.screen().root
|
|
413
|
+
|
|
414
|
+
def send(client_type: int, payload: list[int]) -> None:
|
|
415
|
+
message = xevent.ClientMessage(
|
|
416
|
+
display=self.display,
|
|
417
|
+
window=xid,
|
|
418
|
+
client_type=client_type,
|
|
419
|
+
data=(32, payload),
|
|
420
|
+
)
|
|
421
|
+
root.send_event(message, event_mask=X.SubstructureRedirectMask | X.SubstructureNotifyMask)
|
|
422
|
+
self.display.sync()
|
|
423
|
+
|
|
424
|
+
wm_change_state = self.display.intern_atom("WM_CHANGE_STATE")
|
|
425
|
+
send(wm_change_state, [1, 0, 0, 0, 0])
|
|
426
|
+
time.sleep(0.4)
|
|
427
|
+
send(self.display.intern_atom("_NET_ACTIVE_WINDOW"), [1, 0, xid, 0, 0])
|
|
428
|
+
time.sleep(0.6)
|
|
429
|
+
return self.app_owns_foreground(xid)
|
|
430
|
+
except Exception:
|
|
431
|
+
return self.app_owns_foreground(xid)
|
|
432
|
+
|
|
433
|
+
def _active_window_xid(self) -> int | None:
|
|
434
|
+
if self.display is not None:
|
|
435
|
+
try:
|
|
436
|
+
root = self.display.screen().root
|
|
437
|
+
prop = root.get_full_property(
|
|
438
|
+
self.display.intern_atom("_NET_ACTIVE_WINDOW"), 0
|
|
439
|
+
)
|
|
440
|
+
if prop and prop.value and len(prop.value) > 0:
|
|
441
|
+
return int(prop.value[0])
|
|
442
|
+
except Exception:
|
|
443
|
+
pass
|
|
444
|
+
active = self._xdotool("getactivewindow")
|
|
445
|
+
if active is not None:
|
|
446
|
+
try:
|
|
447
|
+
return int(active)
|
|
448
|
+
except ValueError:
|
|
449
|
+
return None
|
|
450
|
+
return None
|
|
451
|
+
|
|
452
|
+
def is_active(self, xid: int | None) -> bool:
|
|
453
|
+
return self._active_window_xid() == (int(xid) if xid is not None else None)
|
|
454
|
+
|
|
455
|
+
def app_owns_foreground(self, xid: int | None) -> bool:
|
|
456
|
+
"""True when the active window belongs to the same Wine process, or is
|
|
457
|
+
the wine-desktop container that hosts it (`wine explorer /desktop=…`).
|
|
458
|
+
|
|
459
|
+
Wine file dialogs are separate X11 windows with the same _NET_WM_PID;
|
|
460
|
+
typing into the app while one is open is legitimate.
|
|
461
|
+
"""
|
|
462
|
+
active = self._active_window_xid()
|
|
463
|
+
if active is None or xid is None:
|
|
464
|
+
return False
|
|
465
|
+
if active == int(xid):
|
|
466
|
+
return True
|
|
467
|
+
if self.display is None:
|
|
468
|
+
return False
|
|
469
|
+
try:
|
|
470
|
+
# Desktop-container containment: walk up from `xid`; if the active
|
|
471
|
+
# window is an ancestor (the wine desktop window), focus is ours.
|
|
472
|
+
node = self.display.create_resource_object("window", int(xid))
|
|
473
|
+
for _depth in range(6):
|
|
474
|
+
parent_info = node.query_tree().parent
|
|
475
|
+
if parent_info is None or int(parent_info.id) == int(self.display.screen().root.id):
|
|
476
|
+
break
|
|
477
|
+
if int(parent_info.id) == active:
|
|
478
|
+
return True
|
|
479
|
+
node = parent_info
|
|
480
|
+
active_window = self.display.create_resource_object("window", active)
|
|
481
|
+
prop = active_window.get_full_property(_NET_WM_PID_ATOM, 0) if _NET_WM_PID_ATOM is not None else None
|
|
482
|
+
if prop is not None and prop.value:
|
|
483
|
+
return int(prop.value[0]) == int(self._xid_pid(xid))
|
|
484
|
+
except Exception:
|
|
485
|
+
return False
|
|
486
|
+
return False
|
|
487
|
+
|
|
488
|
+
def _xid_pid(self, xid: int) -> int:
|
|
489
|
+
try:
|
|
490
|
+
window = self.display.create_resource_object("window", xid)
|
|
491
|
+
prop = window.get_full_property(_NET_WM_PID_ATOM, 0) if _NET_WM_PID_ATOM is not None else None
|
|
492
|
+
if prop is not None and prop.value:
|
|
493
|
+
return int(prop.value[0])
|
|
494
|
+
except Exception:
|
|
495
|
+
pass
|
|
496
|
+
return 0
|
|
497
|
+
|
|
498
|
+
def window_geometry(self, xid: int | None) -> dict | None:
|
|
499
|
+
if xid is None or self.display is None:
|
|
500
|
+
return None
|
|
501
|
+
try:
|
|
502
|
+
from Xlib import X # noqa: F401
|
|
503
|
+
|
|
504
|
+
xwindow = self.display.create_resource_object("window", xid)
|
|
505
|
+
geometry = xwindow.get_geometry()
|
|
506
|
+
# Translate to root coordinates (Wine windows are top-level).
|
|
507
|
+
coords = xwindow.translate_coordinates(
|
|
508
|
+
self.display.screen().root, 0, 0
|
|
509
|
+
)
|
|
510
|
+
if coords is None:
|
|
511
|
+
return None
|
|
512
|
+
return {
|
|
513
|
+
"x": int(coords.x),
|
|
514
|
+
"y": int(coords.y),
|
|
515
|
+
"width": int(geometry.width),
|
|
516
|
+
"height": int(geometry.height),
|
|
517
|
+
}
|
|
518
|
+
except Exception:
|
|
519
|
+
return None
|
|
520
|
+
|
|
521
|
+
# -- keyboard input ------------------------------------------------------
|
|
522
|
+
|
|
523
|
+
_KEYSYM_ALIASES = {
|
|
524
|
+
"\n": "Return",
|
|
525
|
+
"\r": "Return",
|
|
526
|
+
"\t": "Tab",
|
|
527
|
+
"\b": "BackSpace",
|
|
528
|
+
"\x1b": "Escape",
|
|
529
|
+
" ": "space",
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
# Modifier names accepted in combos ("ctrl+o", "ctrl+shift+s", "alt+F4").
|
|
533
|
+
MODIFIER_KEYS = {"ctrl": "Control_L", "control": "Control_L", "alt": "Alt_L", "shift": "Shift_L", "super": "Super_L", "meta": "Super_L"}
|
|
534
|
+
# Standalone key names beyond single characters (aliases → X keysym names).
|
|
535
|
+
NAMED_KEYS = {
|
|
536
|
+
"enter": "Return", "return": "Return", "esc": "Escape", "escape": "Escape",
|
|
537
|
+
"tab": "Tab", "space": "space", "backspace": "BackSpace", "delete": "Delete",
|
|
538
|
+
"up": "Up", "down": "Down", "left": "Left", "right": "Right",
|
|
539
|
+
"home": "Home", "end": "End", "pageup": "Prior", "pagedown": "Next",
|
|
540
|
+
"f1": "F1", "f2": "F2", "f3": "F3", "f4": "F4", "f5": "F5",
|
|
541
|
+
"f6": "F6", "f7": "F7", "f8": "F8", "f9": "F9", "f10": "F10",
|
|
542
|
+
"f11": "F11", "f12": "F12",
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
@classmethod
|
|
546
|
+
def _keysym_for(cls, char: str) -> int | None:
|
|
547
|
+
name = cls._KEYSYM_ALIASES.get(char, char)
|
|
548
|
+
try:
|
|
549
|
+
keysym = XK.string_to_keysym(name)
|
|
550
|
+
except Exception:
|
|
551
|
+
keysym = 0
|
|
552
|
+
if keysym == 0:
|
|
553
|
+
# Unicode: X11 keysyms for Latin-1 equal the code point; for CJK
|
|
554
|
+
# there is no direct keysym, so the character is unsendable here.
|
|
555
|
+
if len(char) == 1 and 0x20 <= ord(char) <= 0xFF:
|
|
556
|
+
return ord(char)
|
|
557
|
+
return None
|
|
558
|
+
return keysym
|
|
559
|
+
|
|
560
|
+
@staticmethod
|
|
561
|
+
def _keycode_for(display, keysym: int): # type: ignore[no-untyped-def]
|
|
562
|
+
try:
|
|
563
|
+
return display.keysym_to_keycode(keysym)
|
|
564
|
+
except Exception:
|
|
565
|
+
return 0
|
|
566
|
+
|
|
567
|
+
def _press_key(self, keycode: int, hold_modifiers: list[tuple[int, int]]) -> None:
|
|
568
|
+
"""Press+release one keycode while `hold_modifiers` (code, press_event) are down."""
|
|
569
|
+
xtest.fake_input(self.display, 2, keycode) # press
|
|
570
|
+
self.display.sync()
|
|
571
|
+
xtest.fake_input(self.display, 3, keycode) # release
|
|
572
|
+
self.display.sync()
|
|
573
|
+
|
|
574
|
+
def _hold_modifier(self, keysym_name: str) -> tuple[int, int] | None:
|
|
575
|
+
"""Resolve a modifier name to its keycode; None when unavailable."""
|
|
576
|
+
if self.display is None:
|
|
577
|
+
return None
|
|
578
|
+
try:
|
|
579
|
+
keysym = XK.string_to_keysym(keysym_name)
|
|
580
|
+
keycode = self.display.keysym_to_keycode(keysym)
|
|
581
|
+
return (keycode, 2) if keycode else None
|
|
582
|
+
except Exception:
|
|
583
|
+
return None
|
|
584
|
+
|
|
585
|
+
# -- uinput fallback ---------------------------------------------------
|
|
586
|
+
|
|
587
|
+
_UINPUT_KEYMAP = {
|
|
588
|
+
" ": 57, "enter": 36, "return": 36, "esc": 1, "escape": 1,
|
|
589
|
+
"backspace": 14, "tab": 15, "up": 103, "down": 108, "left": 105, "right": 106,
|
|
590
|
+
"a": 30, "b": 48, "c": 46, "d": 32, "e": 18, "f": 33, "g": 34, "h": 35,
|
|
591
|
+
"i": 23, "j": 36, "k": 37, "l": 38, "m": 39, "n": 49, "o": 24, "p": 25,
|
|
592
|
+
"q": 16, "r": 19, "s": 31, "t": 20, "u": 22, "v": 47, "w": 17, "x": 45,
|
|
593
|
+
"y": 21, "z": 44,
|
|
594
|
+
"0": 11, "1": 2, "2": 3, "3": 4, "4": 5, "5": 6, "6": 7, "7": 8, "8": 9, "9": 10,
|
|
595
|
+
"-": 12, "=": 13, "[": 26, "]": 27, "\\": 43, ";": 39, "'": 40, ",": 51,
|
|
596
|
+
".": 52, "/": 53, "`": 41,
|
|
597
|
+
"f1": 59, "f2": 60, "f3": 61, "f4": 62, "f5": 63, "f6": 64, "f7": 65,
|
|
598
|
+
"f8": 66, "f9": 67, "f10": 68, "f11": 87, "f12": 88,
|
|
599
|
+
"leftctrl": 29, "rightctrl": 97, "leftshift": 42, "rightshift": 54,
|
|
600
|
+
"leftalt": 56, "rightalt": 100, "leftsuper": 125, "rightsuper": 126,
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
def send_keys_uinput(self, text: str) -> bool:
|
|
604
|
+
"""Send keys through /dev/uinput (kernel-level, reaches Wine via the
|
|
605
|
+
Wayland→libinput→XWayland stack even when direct XTEST does not).
|
|
606
|
+
|
|
607
|
+
Limited to the key subset mapped above; returns False when anything
|
|
608
|
+
in `text` is unsendable so callers can degrade honestly.
|
|
609
|
+
"""
|
|
610
|
+
try:
|
|
611
|
+
fd = os.open('/dev/uinput', os.O_WRONLY)
|
|
612
|
+
except Exception:
|
|
613
|
+
return False
|
|
614
|
+
try:
|
|
615
|
+
import fcntl
|
|
616
|
+
|
|
617
|
+
def _IOW(t, nr, size):
|
|
618
|
+
return (1 << 30) | (size << 16) | (ord(t) << 8) | nr
|
|
619
|
+
UI_SET_EVBIT, UI_SET_KEYBIT = _IOW('U', 100, 4), _IOW('U', 101, 4)
|
|
620
|
+
UI_DEV_CREATE, UI_DEV_DESTROY = 0x5501, 0x5502
|
|
621
|
+
EV_KEY, EV_SYN, SYN_REPORT = 0x01, 0x00, 0
|
|
622
|
+
fcntl.ioctl(fd, UI_SET_EVBIT, EV_KEY)
|
|
623
|
+
# 解析需要的键并启用
|
|
624
|
+
tokens = self._tokenize_keys(text)
|
|
625
|
+
codes = []
|
|
626
|
+
for tok in tokens:
|
|
627
|
+
code = self._UINPUT_KEYMAP.get(tok)
|
|
628
|
+
if code is None and len(tok) == 1:
|
|
629
|
+
code = self._UINPUT_KEYMAP.get(tok.lower())
|
|
630
|
+
if code is None:
|
|
631
|
+
return False
|
|
632
|
+
codes.append(code)
|
|
633
|
+
for code in set(codes):
|
|
634
|
+
fcntl.ioctl(fd, UI_SET_KEYBIT, code)
|
|
635
|
+
fmt = '80sHHHHI' + 'i' * 256
|
|
636
|
+
os.write(fd, struct.pack(fmt, b'xstudio-kbd\x00'.ljust(80, b'\x00'), 0x06, 0, 0, 0, 0, *([0] * 256)))
|
|
637
|
+
fcntl.ioctl(fd, UI_DEV_CREATE)
|
|
638
|
+
|
|
639
|
+
def emit(keycode, press):
|
|
640
|
+
t = time.time()
|
|
641
|
+
os.write(fd, struct.pack('llHHi', int(t), int((t % 1) * 1e6), EV_KEY, keycode, press))
|
|
642
|
+
os.write(fd, struct.pack('llHHi', int(t), int((t % 1) * 1e6), EV_SYN, SYN_REPORT, 0))
|
|
643
|
+
|
|
644
|
+
for code in codes:
|
|
645
|
+
emit(code, 1)
|
|
646
|
+
emit(code, 0)
|
|
647
|
+
time.sleep(0.03)
|
|
648
|
+
# Destroying the device immediately makes libinput/KWin miss events
|
|
649
|
+
# (observed: "Failed to open /dev/input/eventN device"); keep the
|
|
650
|
+
# device alive long enough for the compositor to consume the keys,
|
|
651
|
+
# then destroy it from a detached thread.
|
|
652
|
+
time.sleep(0.2)
|
|
653
|
+
timer = threading.Timer(1.5, lambda: (fcntl.ioctl(fd, UI_DEV_DESTROY), os.close(fd)))
|
|
654
|
+
timer.daemon = True
|
|
655
|
+
timer.start()
|
|
656
|
+
return True
|
|
657
|
+
except Exception:
|
|
658
|
+
return False
|
|
659
|
+
finally:
|
|
660
|
+
try:
|
|
661
|
+
os.close(fd)
|
|
662
|
+
except Exception:
|
|
663
|
+
pass
|
|
664
|
+
|
|
665
|
+
def _tokenize_keys(self, text: str) -> list[str]:
|
|
666
|
+
"""Split `text` into uinput-keyable tokens (named keys or chars)."""
|
|
667
|
+
lowered = text.strip()
|
|
668
|
+
# 组合键形式:ctrl+o 等 —— 只映射最后一个 token(修饰键暂不支持 uinput 组合)
|
|
669
|
+
if '+' in lowered:
|
|
670
|
+
lowered = lowered.split('+')[-1].strip()
|
|
671
|
+
lowered_l = lowered.lower()
|
|
672
|
+
if lowered_l in self._UINPUT_KEYMAP:
|
|
673
|
+
return [lowered_l]
|
|
674
|
+
# 纯空白(空格键)也是合法 token,不能被 strip 掉。
|
|
675
|
+
if text.strip() == '' and ' ' in text:
|
|
676
|
+
return [' ']
|
|
677
|
+
return [ch for ch in lowered]
|
|
678
|
+
|
|
679
|
+
def toast_window_visible(self) -> bool:
|
|
680
|
+
"""True when an XsToast window (app-level transient notice) is mapped."""
|
|
681
|
+
if self.display is None:
|
|
682
|
+
return False
|
|
683
|
+
try:
|
|
684
|
+
for xwindow in self._windows():
|
|
685
|
+
klass = self._window_class(xwindow)
|
|
686
|
+
if not WINDOW_CLASS_PATTERN.search(klass):
|
|
687
|
+
continue
|
|
688
|
+
if self._window_name(xwindow) == "XsToast":
|
|
689
|
+
return True
|
|
690
|
+
except Exception:
|
|
691
|
+
pass
|
|
692
|
+
return False
|
|
693
|
+
|
|
694
|
+
def send_keys(self, text: str) -> bool:
|
|
695
|
+
"""Type `text` into the focused window via XTEST (no xdotool needed).
|
|
696
|
+
|
|
697
|
+
Syntax: plain characters type literally; `+`-separated combos press a
|
|
698
|
+
chord — `ctrl+o`, `ctrl+shift+s`, `alt+F4` — and named keys (`Return`,
|
|
699
|
+
`Escape`, `Tab`, `F5`, `Down`, …) map to their X keysyms. A lone
|
|
700
|
+
modifier combo like `ctrl+shift` just presses/releases the chord.
|
|
701
|
+
Returns False when the display or a key cannot be synthesized.
|
|
702
|
+
"""
|
|
703
|
+
if self.display is None:
|
|
704
|
+
return self._xdotool("type", "--", text) is not None
|
|
705
|
+
try:
|
|
706
|
+
stripped = text.strip()
|
|
707
|
+
# Combo: all + separated parts are key names (no free text mixed).
|
|
708
|
+
parts = [p for p in stripped.split("+")] if stripped else []
|
|
709
|
+
if len(parts) > 1 and all(p.strip() and (p.strip().lower() in self.MODIFIER_KEYS or p.strip().lower() in self.NAMED_KEYS or len(p.strip()) == 1) for p in parts):
|
|
710
|
+
hold: list[tuple[int, int]] = []
|
|
711
|
+
for part in parts[:-1]:
|
|
712
|
+
mod = self._hold_modifier(self.MODIFIER_KEYS.get(part.strip().lower(), part.strip()))
|
|
713
|
+
if mod is None:
|
|
714
|
+
return False
|
|
715
|
+
xtest.fake_input(self.display, mod[1], mod[0])
|
|
716
|
+
self.display.sync()
|
|
717
|
+
hold.append(mod)
|
|
718
|
+
last = parts[-1].strip()
|
|
719
|
+
keysym = None
|
|
720
|
+
lowered = last.lower()
|
|
721
|
+
if lowered in self.MODIFIER_KEYS:
|
|
722
|
+
mod = self._hold_modifier(self.MODIFIER_KEYS[lowered])
|
|
723
|
+
if mod is not None:
|
|
724
|
+
xtest.fake_input(self.display, 2, mod[0])
|
|
725
|
+
self.display.sync()
|
|
726
|
+
xtest.fake_input(self.display, 3, mod[0])
|
|
727
|
+
self.display.sync()
|
|
728
|
+
else:
|
|
729
|
+
name = self.NAMED_KEYS.get(lowered, last)
|
|
730
|
+
keysym = self._keysym_for(name if len(name) > 1 else name)
|
|
731
|
+
if lowered in self.NAMED_KEYS:
|
|
732
|
+
keysym = XK.string_to_keysym(self.NAMED_KEYS[lowered])
|
|
733
|
+
if keysym is None:
|
|
734
|
+
return False
|
|
735
|
+
keycode = self._keycode_for(self.display, keysym)
|
|
736
|
+
if keycode == 0:
|
|
737
|
+
return False
|
|
738
|
+
self._press_key(keycode, hold)
|
|
739
|
+
for mod in reversed(hold):
|
|
740
|
+
xtest.fake_input(self.display, 3, mod[0]) # release
|
|
741
|
+
self.display.sync()
|
|
742
|
+
return True
|
|
743
|
+
|
|
744
|
+
# Free text: type literally.
|
|
745
|
+
for char in text:
|
|
746
|
+
keysym = self._keysym_for(char)
|
|
747
|
+
if keysym is None:
|
|
748
|
+
return False
|
|
749
|
+
keycode = self._keycode_for(self.display, keysym)
|
|
750
|
+
if keycode == 0:
|
|
751
|
+
return False
|
|
752
|
+
pending_shift = False
|
|
753
|
+
try:
|
|
754
|
+
first = self.display.keycode_to_keysym(keycode, 0)
|
|
755
|
+
pending_shift = first != keysym
|
|
756
|
+
except Exception:
|
|
757
|
+
pending_shift = False
|
|
758
|
+
if pending_shift:
|
|
759
|
+
xtest.fake_input(self.display, 2, 50) # ShiftL press
|
|
760
|
+
self.display.sync()
|
|
761
|
+
xtest.fake_input(self.display, 2, keycode)
|
|
762
|
+
self.display.sync()
|
|
763
|
+
xtest.fake_input(self.display, 3, keycode) # release
|
|
764
|
+
self.display.sync()
|
|
765
|
+
if pending_shift:
|
|
766
|
+
xtest.fake_input(self.display, 3, 50) # ShiftL release
|
|
767
|
+
self.display.sync()
|
|
768
|
+
return True
|
|
769
|
+
except Exception:
|
|
770
|
+
return False
|
|
771
|
+
|
|
772
|
+
def screenshot(self, path: str) -> bool:
|
|
773
|
+
try:
|
|
774
|
+
result = subprocess.run(
|
|
775
|
+
["import", "-window", "root", path],
|
|
776
|
+
capture_output=True,
|
|
777
|
+
timeout=10,
|
|
778
|
+
check=False,
|
|
779
|
+
)
|
|
780
|
+
return result.returncode == 0 and os.path.exists(path)
|
|
781
|
+
except Exception:
|
|
782
|
+
return False
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
# --------------------------------------------------------------------------
|
|
786
|
+
# AT-SPI2 element tree backend
|
|
787
|
+
# --------------------------------------------------------------------------
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
class AtspiBackend:
|
|
791
|
+
"""Element tree access via pyatspi (AT-SPI2), when the desktop exposes it."""
|
|
792
|
+
|
|
793
|
+
ROLE_CONTROL_TYPES = {
|
|
794
|
+
"push button": "Button",
|
|
795
|
+
"button": "Button",
|
|
796
|
+
"menu item": "MenuItem",
|
|
797
|
+
"menu bar": "MenuBar",
|
|
798
|
+
"menu": "Menu",
|
|
799
|
+
"text": "Edit",
|
|
800
|
+
"entry": "Edit",
|
|
801
|
+
"label": "Text",
|
|
802
|
+
"check box": "CheckBox",
|
|
803
|
+
"check menu item": "MenuItem",
|
|
804
|
+
"combo box": "ComboBox",
|
|
805
|
+
"list item": "ListItem",
|
|
806
|
+
"list": "List",
|
|
807
|
+
"dialog": "Window",
|
|
808
|
+
"frame": "Window",
|
|
809
|
+
"window": "Window",
|
|
810
|
+
"root pane": "Pane",
|
|
811
|
+
"panel": "Pane",
|
|
812
|
+
"page tab": "TabItem",
|
|
813
|
+
"page tab list": "TabList",
|
|
814
|
+
"progress bar": "ProgressBar",
|
|
815
|
+
"slider": "Slider",
|
|
816
|
+
"toggle button": "Button",
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
def __init__(self) -> None:
|
|
820
|
+
self.available = _ATSPI_AVAILABLE
|
|
821
|
+
|
|
822
|
+
@staticmethod
|
|
823
|
+
def _element_name(obj) -> str: # type: ignore[no-untyped-def]
|
|
824
|
+
try:
|
|
825
|
+
return obj.name or ""
|
|
826
|
+
except Exception:
|
|
827
|
+
return ""
|
|
828
|
+
|
|
829
|
+
@staticmethod
|
|
830
|
+
def _object_id(obj) -> str: # type: ignore[no-untyped-def]
|
|
831
|
+
# Stable-ish identity: app + role + path indices are too brittle; use
|
|
832
|
+
# the AT-SPI object's unique path (application + roles chain length is
|
|
833
|
+
# not needed — the snapshot token covers staleness).
|
|
834
|
+
try:
|
|
835
|
+
return str(getattr(obj, "get_object_locale", lambda: "")())
|
|
836
|
+
except Exception:
|
|
837
|
+
return ""
|
|
838
|
+
|
|
839
|
+
def find_application(self, process_name: str): # type: ignore[no-untyped-def]
|
|
840
|
+
"""Return the AT-SPI application desktop object for X Studio, or None."""
|
|
841
|
+
desktop = _atspi_desktop()
|
|
842
|
+
if desktop is None:
|
|
843
|
+
return None
|
|
844
|
+
for app in _atspi_children(desktop):
|
|
845
|
+
if app is None:
|
|
846
|
+
continue
|
|
847
|
+
if process_name.lower() in _atspi_name(app).lower():
|
|
848
|
+
return app
|
|
849
|
+
return None
|
|
850
|
+
|
|
851
|
+
def find_window_for_app(self, app, title_fragment: str): # type: ignore[no-untyped-def]
|
|
852
|
+
if app is None:
|
|
853
|
+
return None
|
|
854
|
+
for window in _atspi_children(app):
|
|
855
|
+
if window is None:
|
|
856
|
+
continue
|
|
857
|
+
if title_fragment.lower() in _atspi_name(window).lower():
|
|
858
|
+
return window
|
|
859
|
+
return None
|
|
860
|
+
|
|
861
|
+
def walk(self, root, max_elements: int): # type: ignore[no-untyped-def]
|
|
862
|
+
"""BFS the accessible tree, yielding (node, depth) pairs."""
|
|
863
|
+
if root is None:
|
|
864
|
+
return
|
|
865
|
+
queue = [(root, 0)]
|
|
866
|
+
count = 0
|
|
867
|
+
while queue and count < max_elements:
|
|
868
|
+
node, depth = queue.pop(0)
|
|
869
|
+
count += 1
|
|
870
|
+
yield node, depth
|
|
871
|
+
if depth >= MAX_DEPTH:
|
|
872
|
+
continue
|
|
873
|
+
for child in _atspi_children(node):
|
|
874
|
+
if child is not None:
|
|
875
|
+
queue.append((child, depth + 1))
|
|
876
|
+
|
|
877
|
+
@staticmethod
|
|
878
|
+
def _has_interface(obj, interface_name: str) -> bool: # type: ignore[no-untyped-def]
|
|
879
|
+
try:
|
|
880
|
+
return obj.queryInterface(interface_name) is not None
|
|
881
|
+
except Exception:
|
|
882
|
+
return False
|
|
883
|
+
|
|
884
|
+
def element_record(self, node, depth: int) -> dict: # type: ignore[no-untyped-def]
|
|
885
|
+
name = _atspi_name(node)
|
|
886
|
+
role = _atspi_role(node)
|
|
887
|
+
automation_id = ""
|
|
888
|
+
try:
|
|
889
|
+
attributes = node.getAttributes() or []
|
|
890
|
+
for attribute in attributes:
|
|
891
|
+
if attribute.startswith("id:"):
|
|
892
|
+
automation_id = attribute[3:]
|
|
893
|
+
break
|
|
894
|
+
except Exception:
|
|
895
|
+
automation_id = ""
|
|
896
|
+
patterns: list[str] = []
|
|
897
|
+
for query, pattern in (
|
|
898
|
+
("queryAction", "Invoke"),
|
|
899
|
+
("queryEditableText", "Value"),
|
|
900
|
+
("queryText", "Value"),
|
|
901
|
+
("querySelection", "SelectionItem"),
|
|
902
|
+
("queryToggle", "Toggle"),
|
|
903
|
+
("queryExpandCollapse", "ExpandCollapse"),
|
|
904
|
+
("queryValue", "RangeValue"),
|
|
905
|
+
):
|
|
906
|
+
try:
|
|
907
|
+
getattr(node, query)()
|
|
908
|
+
if pattern not in patterns:
|
|
909
|
+
patterns.append(pattern)
|
|
910
|
+
except Exception:
|
|
911
|
+
continue
|
|
912
|
+
enabled = True
|
|
913
|
+
try:
|
|
914
|
+
if _ATSPI_BACKEND == "gi":
|
|
915
|
+
state = node.get_state_set()
|
|
916
|
+
enabled = state.contains(_atspi.StateType.STATE_ENABLED)
|
|
917
|
+
else:
|
|
918
|
+
state = node.getState()
|
|
919
|
+
enabled = state.contains(_atspi.STATE_ENABLED)
|
|
920
|
+
except Exception:
|
|
921
|
+
enabled = True
|
|
922
|
+
value = None
|
|
923
|
+
try:
|
|
924
|
+
text_iface = node.queryText()
|
|
925
|
+
value = text_iface.get_text(0, -1) if _ATSPI_BACKEND == "gi" else text_iface.getText(0, -1)
|
|
926
|
+
if value == "":
|
|
927
|
+
value = None
|
|
928
|
+
except Exception:
|
|
929
|
+
value = None
|
|
930
|
+
control_type = self.ROLE_CONTROL_TYPES.get(role.lower(), role or "Custom")
|
|
931
|
+
return {
|
|
932
|
+
"name": name,
|
|
933
|
+
"automationId": automation_id,
|
|
934
|
+
"className": role,
|
|
935
|
+
"controlType": control_type,
|
|
936
|
+
"patterns": patterns,
|
|
937
|
+
"enabled": bool(enabled),
|
|
938
|
+
"offscreen": depth > 0 and not self._has_interface(node, "Component"),
|
|
939
|
+
"depth": depth,
|
|
940
|
+
"value": value,
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
# -- actions -----------------------------------------------------------
|
|
944
|
+
|
|
945
|
+
def do_invoke(self, node) -> bool: # type: ignore[no-untyped-def]
|
|
946
|
+
try:
|
|
947
|
+
action = node.queryAction()
|
|
948
|
+
count = action.get_n_actions() if _ATSPI_BACKEND == "gi" else action.nActions()
|
|
949
|
+
get_name = action.get_action_name if _ATSPI_BACKEND == "gi" else action.getName
|
|
950
|
+
do_action = action.do_action if _ATSPI_BACKEND == "gi" else action.doAction
|
|
951
|
+
for index in range(count):
|
|
952
|
+
name = get_name(index) or ""
|
|
953
|
+
if name.lower() in ("click", "press", "invoke", "activate", ""):
|
|
954
|
+
return bool(do_action(index))
|
|
955
|
+
return bool(do_action(0))
|
|
956
|
+
except Exception:
|
|
957
|
+
return False
|
|
958
|
+
|
|
959
|
+
def do_set_text(self, node, value: str) -> bool: # type: ignore[no-untyped-def]
|
|
960
|
+
try:
|
|
961
|
+
editable = node.queryEditableText()
|
|
962
|
+
setter = editable.set_text_contents if _ATSPI_BACKEND == "gi" else editable.setTextContents
|
|
963
|
+
return bool(setter(value))
|
|
964
|
+
except Exception:
|
|
965
|
+
pass
|
|
966
|
+
try:
|
|
967
|
+
text_iface = node.queryText()
|
|
968
|
+
setter = text_iface.set_text_contents if _ATSPI_BACKEND == "gi" else text_iface.setTextContents
|
|
969
|
+
setter(value)
|
|
970
|
+
return True
|
|
971
|
+
except Exception:
|
|
972
|
+
return False
|
|
973
|
+
|
|
974
|
+
def do_select(self, node) -> bool: # type: ignore[no-untyped-def]
|
|
975
|
+
try:
|
|
976
|
+
selection = node.querySelection()
|
|
977
|
+
if _ATSPI_BACKEND == "gi":
|
|
978
|
+
if selection.get_n_selected_children() > 0:
|
|
979
|
+
selection.clear_selection()
|
|
980
|
+
return bool(selection.select_child(0))
|
|
981
|
+
if selection.nSelectedChildren() > 0:
|
|
982
|
+
selection.clearSelection()
|
|
983
|
+
return bool(selection.selectChild(0))
|
|
984
|
+
except Exception:
|
|
985
|
+
return False
|
|
986
|
+
|
|
987
|
+
def do_toggle(self, node) -> bool: # type: ignore[no-untyped-def]
|
|
988
|
+
try:
|
|
989
|
+
toggle = node.queryToggle()
|
|
990
|
+
if _ATSPI_BACKEND == "gi":
|
|
991
|
+
toggle.do_action(toggle.get_current_toggle_state() == 1)
|
|
992
|
+
else:
|
|
993
|
+
toggle.doToggleAction()
|
|
994
|
+
return True
|
|
995
|
+
except Exception:
|
|
996
|
+
return False
|
|
997
|
+
|
|
998
|
+
def do_expand(self, node, expand: bool) -> bool: # type: ignore[no-untyped-def]
|
|
999
|
+
try:
|
|
1000
|
+
expandable = node.queryExpandCollapse()
|
|
1001
|
+
if _ATSPI_BACKEND == "gi":
|
|
1002
|
+
if expand:
|
|
1003
|
+
expandable.expand()
|
|
1004
|
+
else:
|
|
1005
|
+
expandable.collapse()
|
|
1006
|
+
else:
|
|
1007
|
+
if expand:
|
|
1008
|
+
expandable.expand()
|
|
1009
|
+
else:
|
|
1010
|
+
expandable.collapse()
|
|
1011
|
+
return True
|
|
1012
|
+
except Exception:
|
|
1013
|
+
return False
|
|
1014
|
+
|
|
1015
|
+
|
|
1016
|
+
# --------------------------------------------------------------------------
|
|
1017
|
+
# Snapshot state: refs are valid for the latest snapshot only
|
|
1018
|
+
# --------------------------------------------------------------------------
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
class SnapshotStore:
|
|
1022
|
+
def __init__(self) -> None:
|
|
1023
|
+
self.token: str | None = None
|
|
1024
|
+
self.elements: dict[str, object] = {} # ref -> AT-SPI node
|
|
1025
|
+
self.window_ref: str | None = None
|
|
1026
|
+
|
|
1027
|
+
def new_token(self) -> str:
|
|
1028
|
+
self.token = secrets.token_hex(4)
|
|
1029
|
+
self.elements = {}
|
|
1030
|
+
self.window_ref = None
|
|
1031
|
+
return self.token
|
|
1032
|
+
|
|
1033
|
+
def make_ref(self, index: int, window: bool = False) -> str:
|
|
1034
|
+
return f"{self.token}:{'w' if window else 'e'}{index}"
|
|
1035
|
+
|
|
1036
|
+
def resolve(self, ref: str):
|
|
1037
|
+
if self.token is None:
|
|
1038
|
+
raise SidecarProtocolError(
|
|
1039
|
+
"GUI_REF_NOT_FOUND", "No snapshot has been taken yet; call snapshot first."
|
|
1040
|
+
)
|
|
1041
|
+
if not isinstance(ref, str) or not ref.startswith(f"{self.token}:"):
|
|
1042
|
+
raise SidecarProtocolError(
|
|
1043
|
+
"GUI_REF_NOT_FOUND",
|
|
1044
|
+
f"Ref '{ref}' is stale or malformed; refs are snapshot-scoped. Take a fresh snapshot.",
|
|
1045
|
+
)
|
|
1046
|
+
node = self.elements.get(ref)
|
|
1047
|
+
if node is None:
|
|
1048
|
+
raise SidecarProtocolError(
|
|
1049
|
+
"GUI_REF_NOT_FOUND",
|
|
1050
|
+
f"Ref '{ref}' is not in the current snapshot; the element may be gone.",
|
|
1051
|
+
)
|
|
1052
|
+
return node
|
|
1053
|
+
|
|
1054
|
+
|
|
1055
|
+
# --------------------------------------------------------------------------
|
|
1056
|
+
# The sidecar application
|
|
1057
|
+
# --------------------------------------------------------------------------
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
class Sidecar:
|
|
1061
|
+
def __init__(self, workspace_dir: str, require_foreground: bool) -> None:
|
|
1062
|
+
self.workspace_dir = workspace_dir
|
|
1063
|
+
self.require_foreground = require_foreground
|
|
1064
|
+
self.x11 = X11Backend()
|
|
1065
|
+
self.atspi = AtspiBackend()
|
|
1066
|
+
self.store = SnapshotStore()
|
|
1067
|
+
self.aborting = False
|
|
1068
|
+
self.closed = False
|
|
1069
|
+
|
|
1070
|
+
# -- probe ---------------------------------------------------------------
|
|
1071
|
+
|
|
1072
|
+
def method_probe(self, params: dict) -> dict:
|
|
1073
|
+
window = self.x11.find_main_window()
|
|
1074
|
+
toast_seen = self.x11.toast_window_visible()
|
|
1075
|
+
# App-level foreground: any top-level window of the same Wine process
|
|
1076
|
+
# counts (toasts/dialogs legitimately take focus during a task).
|
|
1077
|
+
active = self.x11.app_owns_foreground(window["xid"]) if window else False
|
|
1078
|
+
if params.get("activate") is True and window is not None and not active:
|
|
1079
|
+
active = self.x11.activate_window(window["xid"])
|
|
1080
|
+
window = self.x11.find_main_window() or window
|
|
1081
|
+
return {
|
|
1082
|
+
"running": window is not None,
|
|
1083
|
+
"foreground": bool(active),
|
|
1084
|
+
"windowTitle": window["title"] if window else None,
|
|
1085
|
+
"pid": window["pid"] if window else None,
|
|
1086
|
+
"mapped": window["mapped"] if window else None,
|
|
1087
|
+
# The label reflects the *reachable* tree, not importability: a
|
|
1088
|
+
# gi import succeeding does not mean the Wine app is exposed.
|
|
1089
|
+
"backend": ("atspi" if (self.atspi.available and self.atspi.find_application(PROCESS_NAME) is not None) else "x11-only"),
|
|
1090
|
+
"atspiLib": self.atspi.available,
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
# -- snapshot -------------------------------------------------------------
|
|
1094
|
+
|
|
1095
|
+
def method_snapshot(self, params: dict) -> dict:
|
|
1096
|
+
window = self.x11.find_main_window()
|
|
1097
|
+
if window is None:
|
|
1098
|
+
raise SidecarProtocolError("XSTUDIO_NOT_RUNNING", f"No window matched process '{PROCESS_NAME}' (WM_CLASS Qt*QWindowIcon*).")
|
|
1099
|
+
max_elements = params.get("maxElements") or DEFAULT_MAX_ELEMENTS
|
|
1100
|
+
try:
|
|
1101
|
+
max_elements = max(1, min(2000, int(max_elements)))
|
|
1102
|
+
except Exception:
|
|
1103
|
+
max_elements = DEFAULT_MAX_ELEMENTS
|
|
1104
|
+
|
|
1105
|
+
token = self.store.new_token()
|
|
1106
|
+
elements: list[dict] = []
|
|
1107
|
+
|
|
1108
|
+
root_window_ref = self.store.make_ref(0, window=True)
|
|
1109
|
+
self.store.window_ref = root_window_ref
|
|
1110
|
+
self.store.elements[root_window_ref] = window
|
|
1111
|
+
|
|
1112
|
+
app = self.atspi.find_application(PROCESS_NAME)
|
|
1113
|
+
atspi_window = self.atspi.find_window_for_app(app, window["title"]) if app else None
|
|
1114
|
+
if atspi_window is not None:
|
|
1115
|
+
self.store.elements[root_window_ref] = atspi_window
|
|
1116
|
+
|
|
1117
|
+
if atspi_window is not None:
|
|
1118
|
+
index = 1
|
|
1119
|
+
for node, depth in self.atspi.walk(atspi_window, max_elements):
|
|
1120
|
+
if node is atspi_window:
|
|
1121
|
+
continue
|
|
1122
|
+
try:
|
|
1123
|
+
record = self.atspi.element_record(node, depth)
|
|
1124
|
+
except Exception:
|
|
1125
|
+
continue
|
|
1126
|
+
ref = self.store.make_ref(index)
|
|
1127
|
+
self.store.elements[ref] = node
|
|
1128
|
+
record["ref"] = ref
|
|
1129
|
+
elements.append(record)
|
|
1130
|
+
index += 1
|
|
1131
|
+
if index > max_elements:
|
|
1132
|
+
break
|
|
1133
|
+
|
|
1134
|
+
include_screenshot = params.get("includeScreenshot") is True
|
|
1135
|
+
screenshot_path = None
|
|
1136
|
+
if include_screenshot:
|
|
1137
|
+
snap_dir = os.path.join(self.workspace_dir or "/tmp", "uia-snapshots")
|
|
1138
|
+
try:
|
|
1139
|
+
os.makedirs(snap_dir, exist_ok=True)
|
|
1140
|
+
candidate = os.path.join(snap_dir, f"snapshot-{time.strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}.png")
|
|
1141
|
+
if self.x11.screenshot(candidate):
|
|
1142
|
+
screenshot_path = candidate
|
|
1143
|
+
except Exception:
|
|
1144
|
+
screenshot_path = None
|
|
1145
|
+
|
|
1146
|
+
geometry = self.x11.window_geometry(window["xid"])
|
|
1147
|
+
return {
|
|
1148
|
+
"window": {
|
|
1149
|
+
"title": window["title"],
|
|
1150
|
+
"pid": window["pid"],
|
|
1151
|
+
"className": window["className"],
|
|
1152
|
+
**({"bounds": geometry} if geometry else {}),
|
|
1153
|
+
},
|
|
1154
|
+
"snapshotToken": token,
|
|
1155
|
+
"elements": elements,
|
|
1156
|
+
"treeAvailable": atspi_window is not None,
|
|
1157
|
+
**({"screenshot": screenshot_path} if screenshot_path else {}),
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
# -- element resolution -----------------------------------------------------
|
|
1161
|
+
|
|
1162
|
+
def _require_tree(self):
|
|
1163
|
+
app = self.atspi.find_application(PROCESS_NAME)
|
|
1164
|
+
if app is None:
|
|
1165
|
+
raise SidecarProtocolError(
|
|
1166
|
+
"GUI_REF_NOT_FOUND",
|
|
1167
|
+
"The AT-SPI2 accessibility tree for X Studio is not reachable; element actions are unavailable in this session.",
|
|
1168
|
+
hint=(
|
|
1169
|
+
"Verify the desktop accessibility bus is running (AT_SPI_BUS), that the X Studio "
|
|
1170
|
+
"window exposes AT-SPI under Wine (see scripts/wine-gui-probe.py), and take a fresh snapshot. "
|
|
1171
|
+
"Alternatively use xstudio_guide_print for manual steps."
|
|
1172
|
+
),
|
|
1173
|
+
)
|
|
1174
|
+
return app
|
|
1175
|
+
|
|
1176
|
+
def _resolve_element(self, ref: str):
|
|
1177
|
+
node = self.store.resolve(ref)
|
|
1178
|
+
if isinstance(node, dict): # a bare X11 window record is not actionable
|
|
1179
|
+
raise SidecarProtocolError(
|
|
1180
|
+
"GUI_REF_NOT_FOUND",
|
|
1181
|
+
f"Ref '{ref}' has no actionable AT-SPI element in this session.",
|
|
1182
|
+
)
|
|
1183
|
+
return node
|
|
1184
|
+
|
|
1185
|
+
def _check_foreground(self) -> None:
|
|
1186
|
+
if not self.require_foreground:
|
|
1187
|
+
return
|
|
1188
|
+
window = self.x11.find_main_window()
|
|
1189
|
+
if window is None:
|
|
1190
|
+
raise SidecarProtocolError("XSTUDIO_NOT_RUNNING", "X Studio is not running.")
|
|
1191
|
+
# A Wine file dialog is a different X11 window with the same PID;
|
|
1192
|
+
# both count as "the user is inside X Studio".
|
|
1193
|
+
if not self.x11.app_owns_foreground(window["xid"]):
|
|
1194
|
+
raise SidecarProtocolError(
|
|
1195
|
+
"GUI_FOCUS_LOST",
|
|
1196
|
+
"X Studio does not own the foreground window; the action was not performed.",
|
|
1197
|
+
hint='Call probe with params {"activate": true} to raise the X Studio window via the window manager, then retry.',
|
|
1198
|
+
)
|
|
1199
|
+
|
|
1200
|
+
# -- act -----------------------------------------------------------------
|
|
1201
|
+
|
|
1202
|
+
def method_act(self, params: dict) -> dict:
|
|
1203
|
+
ref = params.get("ref") or ""
|
|
1204
|
+
op = params.get("op") or ""
|
|
1205
|
+
value = params.get("value")
|
|
1206
|
+
# send_keys targets the focused window, not a snapshot element — it is
|
|
1207
|
+
# a window-level operation and works without the accessibility tree.
|
|
1208
|
+
if op == "send_keys":
|
|
1209
|
+
self._check_foreground()
|
|
1210
|
+
if value is None:
|
|
1211
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", "send_keys requires a string value.")
|
|
1212
|
+
# uinput first (kernel-level; verified to reach Wine through the
|
|
1213
|
+
# Wayland→libinput stack), XTEST as the fallback for the rare
|
|
1214
|
+
# environments where /dev/uinput is unavailable.
|
|
1215
|
+
if self.x11.send_keys_uinput(str(value)):
|
|
1216
|
+
return {"ok": True, "detail": "keys sent via /dev/uinput (kernel-level)"}
|
|
1217
|
+
if self.x11.send_keys(str(value)):
|
|
1218
|
+
return {"ok": True, "detail": "keys sent to the focused window (XTEST)"}
|
|
1219
|
+
raise SidecarProtocolError(
|
|
1220
|
+
"GUI_ACTION_FAILED",
|
|
1221
|
+
"send_keys failed: no /dev/uinput, no X display, or a character with no keysym.",
|
|
1222
|
+
hint="ASCII keys work via uinput or XTEST; CJK characters need an input method.",
|
|
1223
|
+
)
|
|
1224
|
+
self._require_tree()
|
|
1225
|
+
node = self._resolve_element(ref)
|
|
1226
|
+
name = _atspi_name(node)
|
|
1227
|
+
if op in ("click", "invoke_pattern") and DESTRUCTIVE_NAME_PATTERN.search(name or ""):
|
|
1228
|
+
raise SidecarProtocolError(
|
|
1229
|
+
"GUI_ACTION_FAILED",
|
|
1230
|
+
f"Refused: element '{name}' matches the destructive-name blacklist; confirm manually.",
|
|
1231
|
+
)
|
|
1232
|
+
if op in ("click", "invoke_pattern", "set_text", "select", "expand", "collapse"):
|
|
1233
|
+
self._check_foreground()
|
|
1234
|
+
if op == "click" or op == "invoke_pattern":
|
|
1235
|
+
if self.atspi.do_invoke(node):
|
|
1236
|
+
return {"ok": True, "detail": f"invoked '{name or ref}'"}
|
|
1237
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", f"Element '{name or ref}' exposes no usable action interface.")
|
|
1238
|
+
if op == "set_text":
|
|
1239
|
+
if value is None:
|
|
1240
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", "set_text requires a string value.")
|
|
1241
|
+
if self.atspi.do_set_text(node, str(value)):
|
|
1242
|
+
return {"ok": True, "detail": f"set text on '{name or ref}'"}
|
|
1243
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", f"Element '{name or ref}' is not editable (no EditableText/Text interface).")
|
|
1244
|
+
if op == "select":
|
|
1245
|
+
if self.atspi.do_select(node):
|
|
1246
|
+
return {"ok": True, "detail": f"selected '{name or ref}'"}
|
|
1247
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", f"Element '{name or ref}' is not selectable.")
|
|
1248
|
+
if op == "expand":
|
|
1249
|
+
if self.atspi.do_expand(node, True):
|
|
1250
|
+
return {"ok": True, "detail": f"expanded '{name or ref}'"}
|
|
1251
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", f"Element '{name or ref}' cannot expand.")
|
|
1252
|
+
if op == "collapse":
|
|
1253
|
+
if self.atspi.do_expand(node, False):
|
|
1254
|
+
return {"ok": True, "detail": f"collapsed '{name or ref}'"}
|
|
1255
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", f"Element '{name or ref}' cannot collapse.")
|
|
1256
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", f"Unknown op '{op}'.")
|
|
1257
|
+
|
|
1258
|
+
# -- assert -----------------------------------------------------------------
|
|
1259
|
+
|
|
1260
|
+
def method_assert(self, params: dict) -> dict:
|
|
1261
|
+
ref = params.get("ref")
|
|
1262
|
+
text = params.get("text")
|
|
1263
|
+
state = params.get("state")
|
|
1264
|
+
expect = params.get("expect")
|
|
1265
|
+
self._require_tree()
|
|
1266
|
+
if ref is not None:
|
|
1267
|
+
node = self._resolve_element(ref)
|
|
1268
|
+
record = self.atspi.element_record(node, 0)
|
|
1269
|
+
if text is not None:
|
|
1270
|
+
actual = record["name"]
|
|
1271
|
+
ok = str(expect).lower() in (actual or "").lower() if expect is not None else bool(actual)
|
|
1272
|
+
return {"ok": ok, "actual": actual, "detail": f"name={actual!r}"}
|
|
1273
|
+
if state is not None:
|
|
1274
|
+
actual = record
|
|
1275
|
+
if state == "exists":
|
|
1276
|
+
return {"ok": True, "actual": record["controlType"]}
|
|
1277
|
+
if state == "enabled":
|
|
1278
|
+
return {"ok": bool(record["enabled"]), "actual": str(record["enabled"])}
|
|
1279
|
+
if state == "visible":
|
|
1280
|
+
return {"ok": not record["offscreen"], "actual": str(not record["offscreen"])}
|
|
1281
|
+
if state == "value":
|
|
1282
|
+
value = record.get("value")
|
|
1283
|
+
if expect is not None:
|
|
1284
|
+
return {"ok": str(value or "") == str(expect), "actual": str(value or "")}
|
|
1285
|
+
return {"ok": value is not None, "actual": str(value or "")}
|
|
1286
|
+
return {"ok": False, "actual": "", "detail": f"unsupported state '{state}'"}
|
|
1287
|
+
elif text is not None:
|
|
1288
|
+
# Window-level text search in the latest snapshot's element names.
|
|
1289
|
+
window = self.x11.find_main_window()
|
|
1290
|
+
if window is None:
|
|
1291
|
+
raise SidecarProtocolError("XSTUDIO_NOT_RUNNING", "X Studio is not running.")
|
|
1292
|
+
needle = str(text).lower()
|
|
1293
|
+
for stored_ref, node in self.store.elements.items():
|
|
1294
|
+
try:
|
|
1295
|
+
name = (node.name or "") if not isinstance(node, dict) else ""
|
|
1296
|
+
except Exception:
|
|
1297
|
+
name = ""
|
|
1298
|
+
if needle in name.lower():
|
|
1299
|
+
return {"ok": expect is None or expect == "exists", "actual": name}
|
|
1300
|
+
raise SidecarProtocolError(
|
|
1301
|
+
"GUI_ASSERT_FAILED",
|
|
1302
|
+
f"No element whose name contains '{text}' exists in the latest snapshot.",
|
|
1303
|
+
)
|
|
1304
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", "assert requires ref (with text/state) or text.")
|
|
1305
|
+
|
|
1306
|
+
# -- dialogs -----------------------------------------------------------------
|
|
1307
|
+
|
|
1308
|
+
def _current_dialog(self): # type: ignore[no-untyped-def]
|
|
1309
|
+
"""Return (root, dialog_node) for the topmost dialog window, or (None, None)."""
|
|
1310
|
+
app = self._require_tree()
|
|
1311
|
+
for window in _atspi_children(app):
|
|
1312
|
+
if window is None:
|
|
1313
|
+
continue
|
|
1314
|
+
role = _atspi_role(window)
|
|
1315
|
+
name = _atspi_name(window)
|
|
1316
|
+
if TOAST_CLASS_PATTERN.search(name):
|
|
1317
|
+
continue
|
|
1318
|
+
if role.lower() in ("dialog", "alert", "window") and name and PROCESS_NAME.lower() not in name.lower():
|
|
1319
|
+
# A second top-level window with a different title is dialog-like.
|
|
1320
|
+
return window
|
|
1321
|
+
return None
|
|
1322
|
+
|
|
1323
|
+
def method_read_dialog(self, _params: dict) -> dict | None:
|
|
1324
|
+
dialog = self._current_dialog()
|
|
1325
|
+
if dialog is None:
|
|
1326
|
+
return None
|
|
1327
|
+
name = _atspi_name(dialog)
|
|
1328
|
+
texts: list[str] = []
|
|
1329
|
+
buttons: list[str] = []
|
|
1330
|
+
for node, _depth in self.atspi.walk(dialog, 200):
|
|
1331
|
+
role = _atspi_role(node)
|
|
1332
|
+
node_name = _atspi_name(node)
|
|
1333
|
+
if role.lower() in ("label", "static", "text"):
|
|
1334
|
+
if node_name and node_name != name:
|
|
1335
|
+
texts.append(node_name)
|
|
1336
|
+
if role.lower() in ("push button", "button", "toggle button"):
|
|
1337
|
+
if node_name:
|
|
1338
|
+
buttons.append(node_name)
|
|
1339
|
+
return {
|
|
1340
|
+
"title": name,
|
|
1341
|
+
"text": "\n".join(texts[:10]),
|
|
1342
|
+
"buttons": buttons[:20],
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
def method_respond_dialog(self, params: dict) -> dict:
|
|
1346
|
+
choice = str(params.get("choice") or "").strip().lower()
|
|
1347
|
+
dialog = self._current_dialog()
|
|
1348
|
+
if dialog is None:
|
|
1349
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", "No dialog is currently open.")
|
|
1350
|
+
self._check_foreground()
|
|
1351
|
+
name = _atspi_name(dialog)
|
|
1352
|
+
if DESTRUCTIVE_NAME_PATTERN.search(name or ""):
|
|
1353
|
+
raise SidecarProtocolError(
|
|
1354
|
+
"GUI_ACTION_FAILED",
|
|
1355
|
+
f"Refused: dialog '{name}' matches the destructive-name blacklist; confirm manually.",
|
|
1356
|
+
)
|
|
1357
|
+
if choice not in RESPOND_CHOICES:
|
|
1358
|
+
raise SidecarProtocolError("GUI_ACTION_FAILED", f"Unknown dialog choice '{choice}'.")
|
|
1359
|
+
candidates = RESPOND_CHOICES[choice]
|
|
1360
|
+
for node, _depth in self.atspi.walk(dialog, 300):
|
|
1361
|
+
role = _atspi_role(node)
|
|
1362
|
+
node_name = _atspi_name(node)
|
|
1363
|
+
if role.lower() not in ("push button", "button"):
|
|
1364
|
+
continue
|
|
1365
|
+
for candidate in candidates:
|
|
1366
|
+
if candidate.lower() in node_name.lower():
|
|
1367
|
+
if choice in ("manual", "login") and self.atspi.do_invoke(node):
|
|
1368
|
+
# login/manual still require a human afterwards
|
|
1369
|
+
return {"ok": False, "detail": f"clicked '{node_name}'; manual follow-up required", "manual": True}
|
|
1370
|
+
if self.atspi.do_invoke(node):
|
|
1371
|
+
return {"ok": True, "detail": f"clicked '{node_name}'"}
|
|
1372
|
+
if choice in ("login", "manual"):
|
|
1373
|
+
return {"ok": False, "detail": "No matching button; handle this dialog manually.", "manual": True}
|
|
1374
|
+
raise SidecarProtocolError(
|
|
1375
|
+
"GUI_ACTION_FAILED",
|
|
1376
|
+
f"No button matching choice '{choice}' was found in dialog '{name}'.",
|
|
1377
|
+
)
|
|
1378
|
+
|
|
1379
|
+
# -- abort / close -------------------------------------------------------------
|
|
1380
|
+
|
|
1381
|
+
def method_abort(self, _params: dict) -> dict:
|
|
1382
|
+
self.aborting = True
|
|
1383
|
+
return {"ok": True, "detail": "abort noted; state cleared for a clean shutdown"}
|
|
1384
|
+
|
|
1385
|
+
def method_close(self, _params: dict) -> dict:
|
|
1386
|
+
self.closed = True
|
|
1387
|
+
return {"ok": True, "detail": "closing"}
|
|
1388
|
+
|
|
1389
|
+
|
|
1390
|
+
METHODS = {
|
|
1391
|
+
"probe": Sidecar.method_probe,
|
|
1392
|
+
"snapshot": Sidecar.method_snapshot,
|
|
1393
|
+
"act": Sidecar.method_act,
|
|
1394
|
+
"assert": Sidecar.method_assert,
|
|
1395
|
+
"readDialog": Sidecar.method_read_dialog,
|
|
1396
|
+
"respondDialog": Sidecar.method_respond_dialog,
|
|
1397
|
+
"abort": Sidecar.method_abort,
|
|
1398
|
+
"close": Sidecar.method_close,
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
|
|
1402
|
+
def write_message(payload: dict) -> None:
|
|
1403
|
+
sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
|
|
1404
|
+
sys.stdout.flush()
|
|
1405
|
+
|
|
1406
|
+
|
|
1407
|
+
def main() -> int:
|
|
1408
|
+
workspace_dir = ""
|
|
1409
|
+
require_foreground = False
|
|
1410
|
+
args = sys.argv[1:]
|
|
1411
|
+
index = 0
|
|
1412
|
+
while index < len(args):
|
|
1413
|
+
arg = args[index]
|
|
1414
|
+
if arg in ("--workspace-dir", "-w") and index + 1 < len(args):
|
|
1415
|
+
workspace_dir = args[index + 1]
|
|
1416
|
+
index += 2
|
|
1417
|
+
elif arg == "--workspace-dir" and "=" in arg:
|
|
1418
|
+
pass
|
|
1419
|
+
elif arg.startswith("--workspace-dir="):
|
|
1420
|
+
workspace_dir = arg.split("=", 1)[1]
|
|
1421
|
+
index += 1
|
|
1422
|
+
elif arg == "--require-foreground":
|
|
1423
|
+
require_foreground = True
|
|
1424
|
+
index += 1
|
|
1425
|
+
else:
|
|
1426
|
+
index += 1
|
|
1427
|
+
|
|
1428
|
+
sidecar = Sidecar(workspace_dir, require_foreground)
|
|
1429
|
+
sys.stderr.write(
|
|
1430
|
+
f"xstudio_uia sidecar ready (python {sys.version.split()[0]}, "
|
|
1431
|
+
f"atspi={'yes' if sidecar.atspi.available else 'no'}, xlib={'yes' if _XLIB_AVAILABLE else 'xdotool-fallback'})\n"
|
|
1432
|
+
)
|
|
1433
|
+
sys.stderr.flush()
|
|
1434
|
+
|
|
1435
|
+
for line in sys.stdin:
|
|
1436
|
+
if sidecar.closed:
|
|
1437
|
+
break
|
|
1438
|
+
stripped = line.strip()
|
|
1439
|
+
if not stripped:
|
|
1440
|
+
continue
|
|
1441
|
+
try:
|
|
1442
|
+
request = json.loads(stripped)
|
|
1443
|
+
except Exception:
|
|
1444
|
+
continue # noise tolerated, mirrors the Windows sidecar
|
|
1445
|
+
request_id = request.get("id")
|
|
1446
|
+
method = request.get("method") or ""
|
|
1447
|
+
params = request.get("params") or {}
|
|
1448
|
+
if not isinstance(params, dict):
|
|
1449
|
+
params = {}
|
|
1450
|
+
handler = METHODS.get(method)
|
|
1451
|
+
if handler is None:
|
|
1452
|
+
write_message(
|
|
1453
|
+
{
|
|
1454
|
+
"id": request_id,
|
|
1455
|
+
"ok": False,
|
|
1456
|
+
"error": {"code": "GUI_ACTION_FAILED", "message": f"Unknown method '{method}'."},
|
|
1457
|
+
}
|
|
1458
|
+
)
|
|
1459
|
+
continue
|
|
1460
|
+
try:
|
|
1461
|
+
data = handler(sidecar, params)
|
|
1462
|
+
write_message({"id": request_id, "ok": True, "data": data})
|
|
1463
|
+
except SidecarProtocolError as error:
|
|
1464
|
+
write_message({"id": request_id, "ok": False, "error": error.to_payload()})
|
|
1465
|
+
except Exception as error: # noqa: BLE001 - the loop must survive
|
|
1466
|
+
write_message(
|
|
1467
|
+
{
|
|
1468
|
+
"id": request_id,
|
|
1469
|
+
"ok": False,
|
|
1470
|
+
"error": {"code": "GUI_ACTION_FAILED", "message": f"unhandled: {error}"},
|
|
1471
|
+
}
|
|
1472
|
+
)
|
|
1473
|
+
sys.stderr.write(f"unhandled: {error}\n")
|
|
1474
|
+
return 0
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
if __name__ == "__main__":
|
|
1478
|
+
sys.exit(main())
|