Repository navigation
Expand file tree
/
Copy pathdeck_common.py
More file actions
216 lines (177 loc) · 8.49 KB
/
Copy pathdeck_common.py
File metadata and controls
216 lines (177 loc) · 8.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""Behaviour shared by the Decky backend (main.py) and the MCP server
(mcp_server.py).
Both processes drive the same Gaming Mode session, so the display environment
they hand to child processes and the xdotool/ydotool commands they run have to
agree. Both once carried their own copy and the copies drifted: the ydotool key
map listed F1-F12 on one side and four keys on the other, so `send_key("F5")`
behaved differently depending on whether the panel or Claude sent it.
Stdlib only, and importable as a plain sibling module: mcp_server.py is spawned
by `claude` as a bare `python3` child with no virtualenv.
"""
import os
import re
import subprocess
# ── display environment ────────────────────────────────────────────────────────
def apply_display_env(env: dict[str, str], uid: int | None = None) -> dict[str, str]:
"""Point `env` at the compositor of the running session (mutates and returns it).
`uid` owns the XDG runtime dir; uid 1000 is the SteamOS default but not
universal, so callers pass the user they resolved instead of hardcoding it.
"""
runtime_dir = env.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid() if uid is None else uid}"
env["XDG_RUNTIME_DIR"] = runtime_dir
# Gaming Mode is a gamescope session: its socket is gamescope-N, which a
# wayland-N probe never matches. gamescopectl reads
# GAMESCOPE_WAYLAND_DISPLAY to reach the control protocol.
gamescope_socket = next(
(s for s in ("gamescope-0", "gamescope-1")
if os.path.exists(os.path.join(runtime_dir, s))),
None,
)
if gamescope_socket:
env.setdefault("GAMESCOPE_WAYLAND_DISPLAY", gamescope_socket)
env["WAYLAND_DISPLAY"] = gamescope_socket
else:
for wd in ("wayland-0", "wayland-1", "wayland-2"):
if os.path.exists(os.path.join(runtime_dir, wd)):
env.setdefault("WAYLAND_DISPLAY", wd)
break
env.setdefault("DISPLAY", ":0")
return env
def _xprop(env: dict[str, str], display: str, *args: str) -> str:
try:
r = subprocess.run(
["xprop", "-display", display, *args],
env=env, capture_output=True, timeout=2,
)
except (OSError, subprocess.TimeoutExpired):
return ""
return r.stdout.decode(errors="replace") if r.returncode == 0 else ""
def _cardinal(xprop_out: str, atom: str) -> str | None:
"""First value of `ATOM(CARDINAL) = n, ...`; None when the atom is unset."""
m = re.search(rf"^{atom}\(CARDINAL\) = (\d+)", xprop_out, re.MULTILINE)
return m.group(1) if m else None
def focused_x_display(env: dict[str, str]) -> str | None:
"""The Xwayland display holding gamescope's focused window, if it can be found.
Gamescope runs one Xwayland server per client group: Steam sits on :0, but
a game is often on :1. xdotool only reaches the server named by DISPLAY,
so input sent to :0 while a game on :1 has focus moves an invisible cursor
and types into Steam's hidden window — it exits 0 and nothing happens.
Gamescope publishes its focus on :0's root window. Window ids are only
unique per server, so the focused id is matched together with its
STEAM_GAME appid to pick the right display.
"""
base = env.get("DISPLAY", ":0")
root = _xprop(env, base, "-root", "GAMESCOPE_FOCUSED_WINDOW", "GAMESCOPE_FOCUSED_APP")
window = _cardinal(root, "GAMESCOPE_FOCUSED_WINDOW")
app = _cardinal(root, "GAMESCOPE_FOCUSED_APP")
if not window or not app:
return None
try:
sockets = sorted(os.listdir("/tmp/.X11-unix"))
except OSError:
return None
for sock in sockets:
if not re.fullmatch(r"X\d+", sock):
continue
display = f":{sock[1:]}"
props = _xprop(env, display, "-id", window, "STEAM_GAME")
if _cardinal(props, "STEAM_GAME") == app:
return display
return None
def input_env(env: dict[str, str]) -> dict[str, str]:
"""Copy of `env` with DISPLAY on the focused window's server (see above)."""
env = dict(env)
display = focused_x_display(env)
if display:
env["DISPLAY"] = display
return env
# ── input ──────────────────────────────────────────────────────────────────────
# xdotool speaks X keysym names, ydotool speaks linux/input-event-codes.h. Only
# the names that do not simply uppercase into a KEY_* constant need an entry —
# F1-F12, letters and digits already round-trip through the default below,
# which is why this table is short. Lookup is case-insensitive so both "escape"
# and xdotool's own "Escape" resolve.
KEY_MAP: dict[str, str] = {
"escape": "KEY_ESC",
"esc": "KEY_ESC",
"return": "KEY_ENTER",
"kp_enter": "KEY_KPENTER",
"backspace": "KEY_BACKSPACE",
"prior": "KEY_PAGEUP",
"page_up": "KEY_PAGEUP",
"next": "KEY_PAGEDOWN",
"page_down": "KEY_PAGEDOWN",
"print": "KEY_SYSRQ",
"menu": "KEY_COMPOSE",
"control_l": "KEY_LEFTCTRL",
"control_r": "KEY_RIGHTCTRL",
"alt_l": "KEY_LEFTALT",
"alt_r": "KEY_RIGHTALT",
"shift_l": "KEY_LEFTSHIFT",
"shift_r": "KEY_RIGHTSHIFT",
"super_l": "KEY_LEFTMETA",
"super_r": "KEY_RIGHTMETA",
}
# xdotool numbers buttons the X way; ydotool wants the raw BTN_* codes with the
# 0x40 "click" bit set.
_XDOTOOL_BUTTONS = {"left": "1", "middle": "2", "right": "3"}
_YDOTOOL_BUTTONS = {"left": "0xC0", "right": "0xC1", "middle": "0xC2"}
_BUTTON_NAMES = {1: "left", 2: "middle", 3: "right"}
def ydotool_key(key: str) -> str:
return KEY_MAP.get(key.lower(), f"KEY_{key.upper()}")
def normalize_button(button: str | int) -> str:
"""Accept either the panel's X button number or the MCP tool's name."""
if isinstance(button, int):
return _BUTTON_NAMES.get(button, "left")
return button if button in _XDOTOOL_BUTTONS else "left"
# Games sample input once per frame (RE4 at 30 Hz), so a press and release sent
# back to back usually lands between two samples and is never seen. 120 ms
# spans several frames yet stays well under X's ~250 ms autorepeat delay, so
# Steam's UI and text fields still get exactly one keystroke.
DEFAULT_KEY_HOLD_MS = 120
MAX_KEY_HOLD_MS = 5000
def key_commands(key: str, hold_ms: int = DEFAULT_KEY_HOLD_MS) -> list[list[str]]:
"""xdotool first, ydotool second — try each until one exits 0.
ydotool only works with a running ydotoold and access to /dev/uinput, so it
is the fallback for when there is no X server (or XWayland) to talk to.
ydotool's `key` subcommand takes `<code>:<pressed>` pairs, not a bare key
name — a bare name is a "non-interpretable value" that ydotool silently
treats as a no-op delay while still exiting 0, so this must send an
explicit press (":1") then release (":0") or nothing happens at all.
`hold_ms` keeps the key down between press and release; 0 is an instant
tap. xdotool does the hold in one process via command chaining
(keydown … sleep … keyup), ydotool via its delay between key events.
The hold path leaves out --clearmodifiers: it releases and re-presses the
user's modifiers around each subcommand, and those extra synthetic events
are the prime suspect for a key that RE4 under Wine kept seeing as held
(Ashley couldn't walk until a manual `xdotool keyup`).
"""
code = ydotool_key(key)
hold_ms = max(0, min(int(hold_ms), MAX_KEY_HOLD_MS))
if hold_ms == 0:
return [
["xdotool", "key", "--clearmodifiers", "--", key],
["ydotool", "key", "--", f"{code}:1", f"{code}:0"],
]
return [
["xdotool", "keydown", "--", key,
"sleep", f"{hold_ms / 1000:g}",
"keyup", "--", key],
["ydotool", "key", "-d", str(hold_ms), "--", f"{code}:1", f"{code}:0"],
]
def type_commands(text: str) -> list[list[str]]:
return [
["xdotool", "type", "--clearmodifiers", "--delay", "20", "--", text],
["ydotool", "type", "--", text],
]
def mouse_move_commands(x: int, y: int) -> list[list[str]]:
return [
["xdotool", "mousemove", "--sync", "--", str(x), str(y)],
["ydotool", "mousemove", "--", str(x), str(y)],
]
def click_commands(button: str | int = "left") -> list[list[str]]:
name = normalize_button(button)
return [
["xdotool", "click", _XDOTOOL_BUTTONS[name]],
["ydotool", "click", _YDOTOOL_BUTTONS[name]],
]