Compare commits

...
5 Commits
Author SHA1 Message Date
DeeJanuz c377133859 Merge experimental into shortcuts
# Conflicts:
#	input/input-relay.py
2026-10-01 17:08:15 -06:00
DeeJanuzandClaude Opus 5.5 675ef3f0d5 Relay: share a key combination's Meta release with frame-voice
A Meta+key combination (Meta+J for gaze_left, say) hides Meta's release
from the desktop, and the relay skipped share_key for it too. frame-voice
saw Meta go down on @frametop_keys and never come up, so it held all
dictated text back, waiting for that release. Keys of grabbed keyboards
are now shared as pressed, before key_binding() decides what the desktop
gets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:07:38 -06:00
DeeJanuzandClaude Opus 5.5 fadc0f467c Shortcuts: Steam menu, commands, and modifier taps
Key combinations (and mouse and controller buttons) get two new actions:
- steam_menu: Open Steam menu / close dashboard (steam/ft-steam menu).
- command:CMD: run CMD with sh -c, as the relay's service, with layout/,
  float/ and steam/ on its PATH. Input Settings offers it for key
  combinations as Run a command...
Both work without pointer mode.

A modifier on its own is now a key combination too: a tap, pressed and
released with no other key, mouse button, or scroll in between. A bound
tap sends the desktop F24 before the release, so Plasma's launcher stays
shut. The defaults gain a Meta tap for the Steam menu; this replaces
META_DASHBOARD, which only worked in pointer mode.

input/test/keys-test.py runs the relay against fake devices with every
outgoing socket renamed, so it's safe next to the live relay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:06:30 -06:00
DeeJanuzandClaude Opus 5.5 2487351556 ft-steam: open Steam's menu through Steam's own UI
steam/ft-steam menu opens the SteamVR dashboard on Steam's menu, or closes
the dashboard if it's up, without pointer mode: it asks Steam's UI over its
debugging port to show its dashboard overlay (ShowVROverlay, what Steam
calls itself) and focus the Steam frame's left menu (MenuStore.OpenMainMenu).
ft-steam check says whether those calls still exist, and update-check.py
runs it, since a Steam client update can rename them.

The CDP client moves from display-settings/steam_settings.py to
steam/steamui.py, so both use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:06:30 -06:00
DeeJanuzandClaude Opus 5.5 4479fbfcc1 Input relay: typing with the pointer helper down no longer ends the relay
Typing on a pass-through keyboard tells the helper "typing". With the
helper not running (SteamVR off), that send raised ConnectionRefusedError
and the relay exited, dropping every grab until systemd restarted it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:01:31 -06:00
12 changed files with 592 additions and 174 deletions

No files matched your search

+1
View File
@@ -54,6 +54,7 @@ If you work in the desktop for long stretches, or leave the headset on a stand,
| Set a screen to On your head (Frametop Display Settings, Visibility & pins) | Pins it to your head where it is, like a HUD. Grab its bar to move it; it stays on your head |
| Meta+Shift+R in the desktop | Puts the screens back in their layout (also in the menu as Reset Screen Layout, and mappable to a mouse button) |
| Meta+Shift+H in the desktop | Hides or shows all screens (also in the menu as Hide/Show Screens, and mappable). The Visibility & pins tab of Frametop Display Settings can instead show them only with the dashboard open, or while you look at your wrist |
| Tap Meta, on any keyboard | Opens the Steam menu in the SteamVR dashboard, or closes the dashboard, wherever you are. The desktop's launcher is still on the taskbar and Alt+F1. Change it in Frametop Input Settings (Keyboard page), where any key combination or modifier tap can do a Frametop or Steam action, open a profile, or run a command of your own |
| Switch a screen to Hidden (Frametop Display Settings, Visibility & pins → Screens shown) | Hides just that screen until you switch it back, whatever the other visibility settings say; new windows that would open on it float instead |
| Play a VR game | The screens hide and your controllers stay in the game. Open the SteamVR dashboard, or press Meta+Shift+H, to see and use them. To keep them visible over games, change During VR games on the Visibility & pins tab; the controllers still stay in the game, and you use the screens with the mouse or the dashboard |
+11 -102
View File
@@ -4,117 +4,26 @@ Steam, not systemd, puts the Frame to sleep: after "When Plugged In and Idle ->
(an hour by default) without input, even while it charges. That's a Steam client setting,
`system_idle_suspend_ac_sec` (0 = never), with no file or command line to change it. Steam
on the Frame runs with -cef-enable-debugging, so its UI's JavaScript context
(SharedJSContext) is reachable over the Chrome DevTools Protocol on 127.0.0.1:8080. There
`settingsStore.clientSettings` has the current values, and `SteamClient.Settings.SetSetting`
takes a change as a serialized CMsgClientSettings protobuf, which is what Steam's own
Settings -> Power page sends. Standard library only (a minimal WebSocket client).
(SharedJSContext) is reachable over the Chrome DevTools Protocol on 127.0.0.1:8080
(steam/steamui.py). There `settingsStore.clientSettings` has the current values, and
`SteamClient.Settings.SetSetting` takes a change as a serialized CMsgClientSettings protobuf,
which is what Steam's own Settings -> Power page sends.
"""
import base64
import json
import os
import socket
import struct
import urllib.request
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "steam"))
from steamui import SteamUnreachable, evaluate # noqa: E402,F401 (callers catch SteamUnreachable here)
CDP_PORT = 8080
# CMsgClientSettings field numbers (Steam's UI bundle maps the names to these).
FIELDS = {"system_idle_suspend_ac_sec": 24004, "system_idle_suspend_battery_sec": 24003}
class SteamUnreachable(Exception):
pass
class _WebSocket:
def __init__(self, url, timeout=5):
host_port, path = url[len("ws://"):].split("/", 1)
host, port = host_port.rsplit(":", 1)
self.sock = socket.create_connection((host, int(port)), timeout=timeout)
key = base64.b64encode(os.urandom(16)).decode()
self.sock.sendall((f"GET /{path} HTTP/1.1\r\nHost: {host_port}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
head = b""
while b"\r\n\r\n" not in head:
chunk = self.sock.recv(4096)
if not chunk:
raise SteamUnreachable("Steam closed the connection")
head += chunk
if b" 101 " not in head.split(b"\r\n", 1)[0]:
raise SteamUnreachable(head.split(b"\r\n", 1)[0].decode(errors="replace"))
self.buf = head.split(b"\r\n\r\n", 1)[1]
def send(self, text):
data, mask = text.encode(), os.urandom(4)
n = len(data)
if n < 126:
head = struct.pack(">BB", 0x81, 0x80 | n)
elif n < 65536:
head = struct.pack(">BBH", 0x81, 0x80 | 126, n)
else:
head = struct.pack(">BBQ", 0x81, 0x80 | 127, n)
self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
def _take(self, n):
while len(self.buf) < n:
chunk = self.sock.recv(65536)
if not chunk:
raise SteamUnreachable("Steam closed the connection")
self.buf += chunk
out, self.buf = self.buf[:n], self.buf[n:]
return out
def recv(self):
message = b""
while True:
b0, b1 = self._take(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", self._take(2))[0]
elif n == 127:
n = struct.unpack(">Q", self._take(8))[0]
message += self._take(n)
if b0 & 0x80:
return message.decode(errors="replace")
def close(self):
self.sock.close()
def _evaluate(expression):
"""Runs JavaScript in Steam's SharedJSContext and returns its (awaited) value."""
try:
with urllib.request.urlopen(f"http://127.0.0.1:{CDP_PORT}/json", timeout=3) as r:
targets = json.load(r)
except OSError as e:
raise SteamUnreachable(f"Steam isn't reachable on port {CDP_PORT} ({e})") from e
url = next((t["webSocketDebuggerUrl"] for t in targets if t.get("title") == "SharedJSContext"), None)
if not url:
raise SteamUnreachable("Steam's UI isn't running")
try:
ws = _WebSocket(url)
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate",
"params": {"expression": expression, "awaitPromise": True, "returnByValue": True}}))
while True:
reply = json.loads(ws.recv())
if reply.get("id") == 1:
break
finally:
ws.close()
except OSError as e:
raise SteamUnreachable(str(e)) from e
result = reply.get("result", {})
if "exceptionDetails" in result:
details = result["exceptionDetails"]
raise SteamUnreachable(details.get("exception", {}).get("description") or details.get("text", "error"))
return result.get("result", {}).get("value")
def sleep_settings():
"""{"ac": seconds, "battery": seconds}: when Steam puts the Frame to sleep without input,
plugged in and on battery (0 = never)."""
value = _evaluate("(() => { const c = settingsStore.clientSettings; "
"return {ac: c.system_idle_suspend_ac_sec, battery: c.system_idle_suspend_battery_sec}; })()")
value = evaluate("(() => { const c = settingsStore.clientSettings; "
"return {ac: c.system_idle_suspend_ac_sec, battery: c.system_idle_suspend_battery_sec}; })()")
if not isinstance(value, dict) or not all(isinstance(value.get(k), int) for k in ("ac", "battery")):
raise SteamUnreachable("Steam's settings don't have the sleep timeouts")
return value
@@ -125,7 +34,7 @@ def set_sleep_setting(name, seconds):
field, seconds = FIELDS[name], int(seconds)
if seconds < 0:
raise ValueError("seconds must be 0 (never) or more")
ok = _evaluate(f"""(async () => {{
ok = evaluate(f"""(async () => {{
const bytes = [];
const varint = n => {{ while (n > 127) {{ bytes.push((n & 127) | 128); n = Math.floor(n / 128); }} bytes.push(n); }};
varint({field} * 8); varint({seconds});
+5 -3
View File
@@ -85,6 +85,8 @@ The relay also owns the volume keys, on every device that has them, the headset'
desktops.sh relay install # enable it (starts with the next reboot or SteamVR start)
desktops.sh relay status | log | uninstall
input/input-relay.py --no-grab # try it without taking devices from SteamVR
input/test/keys-test.py # key combinations and modifier taps, against fake devices (safe next to the live relay)
steam/ft-steam menu # what Open Steam menu does; ft-steam check: Steam's UI still has the calls
```
The first time, the relay has to start before SteamVR, so reboot or restart SteamVR after installing it. After that it's safe to restart on its own: systemd keeps the virtual devices open in its file descriptor store (`FileDescriptorStorePreserve=yes`), so SteamVR keeps the same devices.
@@ -99,7 +101,7 @@ A mouse drives SteamVR the way a controller's laser does, but shows up as a smal
Whichever device you used last wins. Picking up a controller hands the laser back at once, and moving the mouse takes it again. When the headset comes off, the pointer lets go, so the displays can sleep, and it stays off until you're wearing the headset again.
To move a floating panel, left-drag its grab bar. The scroll wheel pushes and pulls it while you drag. Hold the right button while dragging and move the mouse to tilt the panel around the grab point; the right press isn't sent as a click. The tilt stays for the rest of the drag, and releasing the left button drops the panel as it is. A mapped Toggle dashboard button (or a Meta tap, with `META_DASHBOARD=1`) wakes the pointer if needed and holds the virtual system button for 0.12 s, because SteamVR ignores a press and release in the same instant.
To move a floating panel, left-drag its grab bar. The scroll wheel pushes and pulls it while you drag. Hold the right button while dragging and move the mouse to tilt the panel around the grab point; the right press isn't sent as a click. The tilt stays for the rest of the drag, and releasing the left button drops the panel as it is. A mapped Toggle dashboard button wakes the pointer if needed and holds the virtual system button for 0.12 s, because SteamVR ignores a press and release in the same instant. Open Steam menu / close dashboard (`steam_menu`) needs no pointer: `steam/ft-steam menu` asks Steam's UI, over its debugging port (`steam/steamui.py`), to show its dashboard overlay and focus the Steam frame's menu, or to hide the dashboard if it's up.
```
pointer/driver/build.sh && pointer/driver/install.sh install # then restart SteamVR
@@ -114,10 +116,10 @@ The pointer settings are in `~/.config/frametop.conf`: `POINTER_SENSITIVITY`, `P
A Kirigami app with a Python backend, in the Plasma menu under Settings. It runs in the `dev` container and talks to the relay over its control socket, `@frametop_relay`. It has eight pages:
- Devices lists every USB and Bluetooth mouse and keyboard, with a light that flashes when the device is used. Each device gets a role: 3D pointer (grabbed, drives the pointer; the default for anything with a mouse), Pass through (grabbed only while typing goes to the desktop; the default for keyboards, where a Meta tap toggles the dashboard if `META_DASHBOARD=1` is in `~/.config/frametop.conf`), or Ignore. A device is identified by its Bluetooth address, or its USB ids and name, so all of its input nodes share one role. Forget drops everything saved for a device.
- Devices lists every USB and Bluetooth mouse and keyboard, with a light that flashes when the device is used. Each device gets a role: 3D pointer (grabbed, drives the pointer; the default for anything with a mouse), Pass through (grabbed only while typing goes to the desktop; the default for keyboards, whose key combinations work everywhere), or Ignore. A device is identified by its Bluetooth address, or its USB ids and name, so all of its input nodes share one role. Forget drops everything saved for a device.
- Buttons maps a pointer device's buttons. Choose Capture a button, press the button or key, then pick an action: a click, back, scroll, toggle dashboard, recenter, pointer on or off, head follow on or off, gaze pointer on or off, gaze precision, gaze drag, gaze quick check, faster or slower, reset the screen layout, hide or show the screens, open or close the keyboard, float a window in VR or put it back, put all floating windows back, Open profile NAME (one per profile, [profiles.md](profiles.md)), pass the key through, or nothing. Devices with saved mappings are listed even while they're asleep.
- Controllers maps the Frame controllers' buttons (every button but the system button) to the same actions, except passing a key through and the gaze actions: gaze mode is a mouse and keyboard feature ([gaze-controllers.md](gaze-controllers.md)). Capture a button and press it on a controller, or pick it from the list. The controllers aren't input devices on the host; only SteamVR sees them. So the pointer helper reads them with SteamVR input (`pointer/helper/vrbuttons.h`, `pointer/helper/actions/`) and sends presses to the relay (`vrbtn right/a 1`), which does the mapped action. The helper only takes the buttons that are mapped (the relay tells it with `vrbind`), at an overlay-global priority, and only while no game (scene application) runs, so games keep every button; with In games on (`controller_in_games`), a mapped button is taken from games too. That needs SteamVR's "Enable global input from overlays (Experimental)" setting (`steamvr/globalActionSetPriority`), which the page's Global input switch turns on and off. Mappings are saved as `controller_buttons` in `~/.config/frametop-input.json`.
- Keyboard sets when Frametop's keyboard opens: whenever a text field is selected; only while no pass-through keyboard is connected (the default; keyboards other programs make through uinput, like frame-voice's, don't count); only with a mouse or controller button mapped to Open/close keyboard; or never, which turns the button off too. Keep it open (on by default, `vr_keyboard_persist`) leaves it open after the text field loses focus. The mode is saved as `vr_keyboard` in `~/.config/frametop-input.json`, and the page lists the keyboards that count as connected. Its Key combinations section maps modifiers plus a key, on any keyboard, to any action but passing a key through or nothing. The gaze clicks (Gaze left click and Gaze right click) only go on key combinations. The defaults are Meta+J (gaze left click), Meta+K (gaze right click), and Meta+Shift+F (float window in VR or put it back); remove them or add others there. The combination's last key isn't typed, and the modifiers still reach the app. They're saved as `key_bindings` in the same file.
- Keyboard sets when Frametop's keyboard opens: whenever a text field is selected; only while no pass-through keyboard is connected (the default; keyboards other programs make through uinput, like frame-voice's, don't count); only with a mouse or controller button mapped to Open/close keyboard; or never, which turns the button off too. Keep it open (on by default, `vr_keyboard_persist`) leaves it open after the text field loses focus. The mode is saved as `vr_keyboard` in `~/.config/frametop-input.json`, and the page lists the keyboards that count as connected. Its Key combinations section maps modifiers plus a key, or one modifier tapped on its own, on any keyboard, to any action but passing a key through or nothing, or to Run a command…: a command line the input relay runs with `sh -c` when you press the keys (`command:CMD`). The command runs as the relay's user service, outside the desktop's session, with `layout/`, `float/` and `steam/` on its `PATH` (so `ft-layout use Work` or `ft-float launch org.kde.dolphin` work as they are), and its output goes to the relay's journal. The gaze clicks (Gaze left click and Gaze right click) only go on key combinations. The defaults are a Meta tap (open the Steam menu, or close the dashboard), Meta+J (gaze left click), Meta+K (gaze right click), and Meta+Shift+F (float window in VR or put it back); remove them or add others there. A tap is a press and release with no other key, mouse button, or scroll in between; a bound one sends the desktop F24 before the release, so Plasma's launcher doesn't open on it. The combination's last key isn't typed, and the modifiers still reach the app; while typing goes to Steam rather than the desktop, keyboards aren't grabbed, so Steam or the game sees the keys too. They're saved as `key_bindings` in the same file; a file with its own list, even an empty one, gets no defaults.
- Pointer has a Head follow switch and sliders for the pointer settings, which apply immediately, and a Recenter button.
- Ignored panels lists the SteamVR overlays that are showing, grouped by app (the first two parts of the overlay key, such as `sasaken.frame-perf-overlay`), from the pointer helper (`overlays`). Tick a panel, or Ignore the whole app, and the pointer passes through it to what's behind. It's for panels you only look at, like a performance overlay that follows your view. The list is saved as `POINTER_IGNORE` in `~/.config/frametop.conf`: comma-separated overlay keys, where a shell pattern like `vendor.app*` covers a whole app, including panels it opens later. The helper reloads at once. Frametop's own screens aren't listed, and entries for apps that aren't open are listed below, to remove.
- Gaze has the gaze pointer switch (on now and from now on; a mapped button toggles it until the helper restarts), what the mouse's left button and movement do, the gaze dot, the eye tracker and eye bias, the gaze mode sliders, the gaze service's state (headset, samples per second, how often the tracker is losing each eye, the calibration, the nudges learned), and Quick check, Calibrate, and Check headset fit (each in a panel in the headset), Reload calibration, and Forget nudges. The gaze probe, a development tool, is in the page's overflow menu.
+40 -14
View File
@@ -9,8 +9,9 @@ to the input relay over its control socket (@frametop_relay):
- Controllers: the same for the Frame controllers' buttons, minus the gaze actions (gaze
mode is a mouse feature). They're read by the pointer helper through SteamVR input
(@ft_pointer_helper: vrstatus, vrglobal), and a mapped button is taken from games.
- Keyboard: when Frametop's keyboard opens, and key combinations for any action (Meta+Shift+F
floats a window unless the rules have their own list).
- Keyboard: when Frametop's keyboard opens, and key combinations for any action, a command
of your own too ("command:CMD"), or a modifier tapped alone (a Meta tap opens Steam's menu
and Meta+Shift+F floats a window, unless the rules have their own list).
- Pointer: speed, dot size, distance and the rest, applied live.
- Ignored panels: SteamVR overlays the pointer passes through (POINTER_IGNORE), by app or
one by one. The helper lists them (@ft_pointer_helper "overlays").
@@ -60,6 +61,7 @@ DEFAULT_BUTTONS = {0x110: "left", 0x111: "right", 0x112: "middle", 0x113: "back"
ACTION_LABELS = {
"left": "Left click", "right": "Right click", "middle": "Middle click", "back": "Back",
"scroll_up": "Scroll up", "scroll_down": "Scroll down", "dashboard": "Toggle SteamVR dashboard",
"steam_menu": "Open Steam menu / close dashboard",
"recenter": "Recenter pointer", "pointer_toggle": "Pointer on/off",
"follow_toggle": "Head follow on/off (experimental)", "gaze_toggle": "Gaze pointer on/off (experimental)",
"gaze_precision": "Gaze precision: hold to steer, release to click",
@@ -102,6 +104,8 @@ KEYBOARD_ONLY = ("gaze_left", "gaze_right")
# Profiles (docs/profiles.md): "profile:NAME" opens one (the relay runs ft-layout use NAME).
LAYOUT_PATH = os.path.expanduser("~/.config/frametop-layout.json")
PROFILE = "profile:"
# "command:CMD": the relay runs CMD with sh -c (key combinations only, here).
COMMAND = "command:"
def profile_actions():
@@ -113,6 +117,8 @@ def profile_actions():
def action_label(a):
if a.startswith(PROFILE):
return f"Open profile {a[len(PROFILE):]}"
if a.startswith(COMMAND):
return f"Run: {a[len(COMMAND):]}"
return ACTION_LABELS.get(a, a)
@@ -120,14 +126,18 @@ def is_profile(a):
return a.startswith(PROFILE) and len(a) > len(PROFILE)
def is_command(a):
return a.startswith(COMMAND) and bool(a[len(COMMAND):].strip())
def mappable(a):
"""An action a controller button can have."""
return a in CONTROLLER_ACTIONS or is_profile(a)
def shortcut_mappable(a):
"""An action a key combination can have: the gaze ones too."""
return a in SHORTCUT_ACTIONS or is_profile(a)
"""An action a key combination can have: the gaze ones and commands too."""
return a in SHORTCUT_ACTIONS or is_profile(a) or is_command(a)
# Gaze mode settings (pointer helper), like POINTER_SETTINGS.
GAZE_SETTINGS = [
("POINTER_GAZE_RETAKE", "Look away to hand back", 5, 1, 45, 0.5, "°"),
@@ -141,9 +151,10 @@ GAZE_MOUSE = {"precision": "Gaze precision: hold to steer with the mouse, releas
# Key combinations ("key_bindings" in the rules): modifiers, either side folded into the left code.
MODIFIER_CODES = {29: 29, 97: 29, 42: 42, 54: 42, 56: 56, 100: 56, 125: 125, 126: 125}
MODIFIER_NAMES = {29: "Ctrl", 42: "Shift", 56: "Alt", 125: "Meta"}
# What a rules file without "key_bindings" gets (the relay's DEFAULT_KEY_BINDINGS): Meta+J and
# Meta+K click at the gaze, Meta+Shift+F floats a window.
DEFAULT_KEY_BINDINGS = {"125+36": "gaze_left", "125+37": "gaze_right", "42+125+33": "float_toggle"}
# What a rules file without "key_bindings" gets (the relay's DEFAULT_KEY_BINDINGS): a Meta tap
# opens Steam's menu, Meta+J and Meta+K click at the gaze, Meta+Shift+F floats a window.
DEFAULT_KEY_BINDINGS = {"125": "steam_menu", "125+36": "gaze_left", "125+37": "gaze_right",
"42+125+33": "float_toggle"}
def key_bindings(rules):
@@ -295,6 +306,7 @@ class Backend(QObject):
self._capture_vr = False
self._capture_combo = "" # the action a key combination is being captured for
self._combo_mods = set()
self._combo_tap = None # a modifier pressed alone, nothing since: released, it's a tap
self._vr = {} # the helper's vrstatus, {} when it doesn't answer
self._vr_at = 0.0
self._gaze = {} # ft-gazed's status, {} when it isn't running
@@ -408,13 +420,16 @@ class Backend(QObject):
self.activity.emit(msg["id"])
code, value = int(msg["code"]), msg["value"]
if code in MODIFIER_CODES:
(self._combo_mods.add if value else self._combo_mods.discard)(MODIFIER_CODES[code])
mod = MODIFIER_CODES[code]
if value == 1:
self._combo_tap = None if self._combo_mods else mod
(self._combo_mods.add if value else self._combo_mods.discard)(mod)
if value == 0 and self._combo_tap == mod:
self._end_shortcut_capture(str(mod)) # the relay's modifier tap
elif value == 1 and code < BTN_MISC:
self._save_shortcut("+".join(str(c) for c in sorted(self._combo_mods) + [code]),
self._capture_combo)
self._capture_combo = ""
self._combo_mods = set()
self.shortcutCaptureChanged.emit()
self._end_shortcut_capture("+".join(str(c) for c in sorted(self._combo_mods) + [code]))
elif value == 1:
self._combo_tap = None # a mouse button: no tap
elif t == "event":
self.activity.emit(msg["id"])
if (self._capture_id and msg["id"] == self._capture_id and msg["type"] == "key"
@@ -890,6 +905,8 @@ class Backend(QObject):
# --- key combinations ("key_bindings") ---
def comboName(self, combo):
parts = [int(c) for c in combo.split("+") if c.isdigit()]
if len(parts) == 1 and parts[0] in MODIFIER_NAMES:
return MODIFIER_NAMES[parts[0]] + " tap"
return "+".join(MODIFIER_NAMES.get(c) or self.codeName(c).removeprefix("KEY_").title() for c in parts)
@Property("QVariantList", notify=mappingsChanged)
@@ -900,7 +917,8 @@ class Backend(QObject):
@Property("QVariantList", constant=True)
def shortcutActions(self):
return [{"value": a, "text": action_label(a)} for a in SHORTCUT_ACTIONS + profile_actions()]
return [{"value": a, "text": action_label(a)} for a in SHORTCUT_ACTIONS + profile_actions()] + \
[{"value": COMMAND, "text": "Run a command…"}]
@Property(bool, notify=shortcutCaptureChanged)
def capturingShortcut(self):
@@ -911,6 +929,7 @@ class Backend(QObject):
if shortcut_mappable(action):
self._capture_combo = action
self._combo_mods = set()
self._combo_tap = None
self._send("watch 60")
self.shortcutCaptureChanged.emit()
@@ -919,6 +938,13 @@ class Backend(QObject):
self._capture_combo = ""
self.shortcutCaptureChanged.emit()
def _end_shortcut_capture(self, combo):
self._save_shortcut(combo, self._capture_combo)
self._capture_combo = ""
self._combo_mods = set()
self._combo_tap = None
self.shortcutCaptureChanged.emit()
def _save_shortcut(self, combo, action):
rules = read_json(RULES_PATH)
rules["key_bindings"] = dict(key_bindings(rules), **{combo: action})
+27 -6
View File
@@ -192,7 +192,7 @@ Kirigami.ApplicationWindow {
wrapMode: Text.Wrap
opacity: 0.7
text: "Move or press a device to see which row it is. 3D pointer: grabbed, drives the SteamVR pointer. "
+ "Pass through: left alone (a Meta tap toggles the dashboard if META_DASHBOARD=1). Ignore: left alone."
+ "Pass through: left alone, but its key combinations (Keyboard page) work. Ignore: left alone."
}
}
}
@@ -545,7 +545,11 @@ Kirigami.ApplicationWindow {
delegate: RowLayout {
required property var modelData
Kirigami.FormData.label: modelData.label + ":"
Controls.Label { text: modelData.actionLabel }
Controls.Label {
text: modelData.actionLabel
elide: Text.ElideRight
Layout.maximumWidth: Kirigami.Units.gridUnit * 24
}
Controls.ToolButton {
icon.name: "edit-delete"
display: Controls.AbstractButton.IconOnly
@@ -568,16 +572,33 @@ Kirigami.ApplicationWindow {
}
Controls.Button {
text: backend.capturingShortcut ? "Press the keys… (Cancel)" : "Set keys…"
enabled: backend.capturingShortcut || shortcutAction.currentValue !== "command:"
|| shortcutCommand.text.trim() !== ""
onClicked: backend.capturingShortcut ? backend.cancelShortcutCapture()
: backend.startShortcutCapture(shortcutAction.currentValue)
: backend.startShortcutCapture(
shortcutAction.currentValue === "command:"
? "command:" + shortcutCommand.text.trim()
: shortcutAction.currentValue)
}
}
Controls.TextField {
id: shortcutCommand
Kirigami.FormData.label: "Command:"
visible: shortcutAction.currentValue === "command:"
placeholderText: "e.g. ft-layout use Work"
Layout.preferredWidth: Kirigami.Units.gridUnit * 24
}
Controls.Label {
Layout.maximumWidth: Kirigami.Units.gridUnit * 30
wrapMode: Text.WordWrap
text: "Hold the modifiers (Ctrl, Alt, Shift, Meta), then press the key, on any keyboard. The "
+ "combination's last key isn't typed; the modifiers still reach the app. Meta+Shift+F floats "
+ "the desktop window under the pointer in VR, or puts it back, until you remove or change it."
text: "Hold the modifiers (Ctrl, Alt, Shift, Meta), then press the key, on any keyboard. Or tap "
+ "one modifier on its own. The combination's last key isn't typed; the modifiers still reach "
+ "the app. While you're in Steam or a game, they see the keys too. Until you remove or change "
+ "them, a Meta tap opens the Steam menu (or closes the dashboard) instead of the desktop's "
+ "launcher, and Meta+Shift+F floats the desktop window under the pointer in VR, or puts it "
+ "back. A command runs with sh as the input relay's service, outside the desktop's session, "
+ "with Frametop's ft-layout, ft-float and ft-steam on its path; its output goes to the "
+ "relay's log (journalctl --user -u frametop-input-relay)."
opacity: 0.7
font: Kirigami.Theme.smallFont
}
+89 -47
View File
@@ -14,8 +14,7 @@ keyboard node for its extra buttons). Roles, from ~/.config/frametop-input.json
(written by the Frametop Input Settings app):
pointer grabbed; drives the universal 3D mouse (default for devices with a mouse node)
passthrough keys go to the desktop; grabbed only while typing goes there, otherwise only observed,
e.g. for the Meta dashboard shortcut (default for keyboards; the shortcut is off
unless META_DASHBOARD=1 is in ~/.config/frametop.conf)
for the key combinations below (default for keyboards)
ignore not grabbed, only observed for identification in the settings app
Buttons and keys of pointer devices go through a per-device map to actions
(left, right, middle, back, scroll_up, scroll_down, dashboard, recenter,
@@ -32,19 +31,26 @@ layout_reset = put the desktop screens back in their saved layout, screens_toggl
keyboard_toggle = open or close Frametop's keyboard, float_toggle = float the desktop window under the
pointer (else the active one) in VR, or put it back if it floats, dock_all = put every floating
window back (both to ft-floatd, @frametop_float), profile:NAME = switch to that profile (ft-layout
use NAME: its screens and apps; docs/profiles.md), key = pass through as a key, none).
use NAME: its screens and apps; docs/profiles.md), steam_menu = open the SteamVR dashboard on
Steam's menu, or close the dashboard (steam/ft-steam menu, through Steam's UI), command:CMD = run
CMD with sh -c (on the host, as this service: its environment, output to its log, and
COMMAND_PATH, so ft-layout, ft-float and ft-steam need no path), key = pass through as a key, none).
Frame controller buttons can be mapped too ("controller_buttons": {"right/a": action} in the
rules file; any action but key and the gaze ones, GAZE_ACTIONS: gaze mode is a mouse feature,
docs/gaze-controllers.md). So can key combinations on any keyboard ("key_bindings":
{"29+56+34": action}, evdev codes joined by "+", modifiers first and left-hand codes for
either side, here Ctrl+Alt+G): the combination does the action, and its last key isn't typed.
A rules file without "key_bindings" gets DEFAULT_KEY_BINDINGS (Meta+J: gaze_left, Meta+K:
gaze_right, Meta+Shift+F: float_toggle); one with its own, even an empty one, doesn't. The float
actions work without pointer mode too. A combination with Meta also sends the desktop an F24 press
and Meta's release right away: so letting go of Meta doesn't open Plasma's launcher, and a gaze
click isn't Meta+click (KWin's window move and resize). Another key while Meta is still held gives
the desktop Meta back. The controllers aren't input devices here, only SteamVR sees
A modifier on its own ("125": Meta) is a tap: pressed and released with no other key, mouse
button, or scroll in between; the desktop gets an F24 press before its release, so Plasma's
launcher doesn't open on a Meta tap that's bound. A rules file without "key_bindings" gets
DEFAULT_KEY_BINDINGS (Meta tap: steam_menu, Meta+J: gaze_left, Meta+K: gaze_right, Meta+Shift+F:
float_toggle); one with its own, even an empty one, doesn't. The float, profile, Steam menu and
command actions work without pointer mode too. A combination with Meta also sends the desktop an
F24 press and Meta's release right away: so letting go of Meta doesn't open Plasma's launcher, and
a gaze click isn't Meta+click (KWin's window move and resize). Another key while Meta is still
held gives the desktop Meta back. While typing goes to Steam, keyboards aren't grabbed, so Steam
or the game sees a combination's keys too. The controllers aren't input devices here, only SteamVR sees
them, so the pointer helper reads them with SteamVR input and sends "vrbtn <button> 1|0".
It only takes the buttons the relay tells it to ("vrbind <button>..." to @ft_pointer_helper,
sent on start, reload, and when the helper says "vrhello"), and only while no game runs,
@@ -130,6 +136,7 @@ SYN_REPORT = 0
BTN_MISC, KEY_MAX = 0x100, 0x2FF
KEY_A = 30
REL_X, REL_Y, REL_WHEEL, REL_MAX = 0x00, 0x01, 0x08, 0x0F
SCROLLS = {0x06, REL_WHEEL, 0x0B, 0x0C} # REL_HWHEEL, REL_WHEEL and their _HI_RES
BTN_LEFT, BTN_RIGHT, BTN_MIDDLE, BTN_SIDE, BTN_EXTRA = 0x110, 0x111, 0x112, 0x113, 0x114
KEY_LEFTMETA, KEY_RIGHTMETA = 125, 126
KEY_VOLUMEDOWN, KEY_VOLUMEUP = 114, 115
@@ -189,12 +196,14 @@ RULES_PATH = os.path.expanduser("~/.config/frametop-input.json")
ACTIONS = ("left", "right", "middle", "back", "scroll_up", "scroll_down", "dashboard", "recenter",
"pointer_toggle", "follow_toggle", "gaze_toggle", "gaze_precision", "gaze_drag", "gaze_left", "gaze_right",
"gaze_quickcal", "sens_up", "sens_down", "layout_reset", "screens_toggle", "keyboard_toggle", "float_toggle",
"dock_all", "key", "none")
"dock_all", "steam_menu", "key", "none")
# Gaze mode is a mouse feature: these never come from a controller button (docs/gaze-controllers.md).
GAZE_ACTIONS = ("gaze_toggle", "gaze_precision", "gaze_drag", "gaze_left", "gaze_right", "gaze_quickcal")
# Key combinations a rules file without "key_bindings" gets: Meta+J and Meta+K click at the gaze
# (free on the Frametop desktop, and apps don't use Meta), Meta+Shift+F floats a window.
DEFAULT_KEY_BINDINGS = {"125+36": "gaze_left", "125+37": "gaze_right", "42+125+33": "float_toggle"}
# Key combinations a rules file without "key_bindings" gets: a Meta tap opens Steam's menu, Meta+J
# and Meta+K click at the gaze (free on the Frametop desktop, and apps don't use Meta),
# Meta+Shift+F floats a window.
DEFAULT_KEY_BINDINGS = {"125": "steam_menu", "125+36": "gaze_left", "125+37": "gaze_right",
"42+125+33": "float_toggle"}
KEY_F24 = 194 # sent to the desktop with a Meta combination (see the top)
# Key combinations ("key_bindings"): modifiers, each side's code folded into the left one's.
MODIFIERS = {29: 29, 97: 29, 42: 42, 54: 42, 56: 56, 100: 56, 125: 125, 126: 125}
@@ -211,16 +220,23 @@ FLOAT = "\0frametop_float" # ft-floatd, floating windows in the Frametop deskto
# Actions for ft-floatd ("float_toggle", "dock_all"): they don't need pointer mode.
FLOAT_ACTIONS = {"float_toggle": b"float pointer", "dock_all": b"dock all"}
PROFILE = "profile:" # "profile:NAME": switch to that profile (doesn't need pointer mode either)
COMMAND = "command:" # "command:CMD": run CMD (nor does this)
def known_action(a):
return a in ACTIONS or (isinstance(a, str) and a.startswith(PROFILE) and len(a) > len(PROFILE))
return a in ACTIONS or (isinstance(a, str) and any(a.startswith(p) and a[len(p):].strip()
for p in (PROFILE, COMMAND)))
def needs_pointer(a):
return a not in FLOAT_ACTIONS and not a.startswith(PROFILE)
return a not in FLOAT_ACTIONS and a != "steam_menu" and not a.startswith((PROFILE, COMMAND))
KEYS = "\0frametop_keys" # keys of keyboards grabbed for the desktop, for other readers
FT_LAYOUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "layout", "ft-layout")
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FT_LAYOUT = os.path.join(REPO, "layout", "ft-layout")
FT_STEAM = os.path.join(REPO, "steam", "ft-steam")
# Commands ("command:CMD") find Frametop's own tools (ft-layout, ft-float, ft-steam) on their PATH.
COMMAND_PATH = ":".join([os.path.join(REPO, d) for d in ("layout", "float", "steam")]
+ [os.environ.get("PATH", "/usr/local/bin:/usr/bin")])
DEFAULT_BUTTONS = {BTN_LEFT: "left", BTN_RIGHT: "right", BTN_MIDDLE: "middle",
BTN_SIDE: "back", BTN_EXTRA: "back"}
@@ -672,13 +688,12 @@ def main():
# desktop_until: typing goes to the Frametop desktop until then (ft-screens says so
# every second); typing_applied: the grabs match that as of the last apply_roles().
# vr_capture_until: every controller button is taken until then (the settings app capturing one).
state = {"pointer": None, "rules": {}, "meta_dashboard": False, "share_keys": False,
state = {"pointer": None, "rules": {}, "share_keys": False,
"desktop_until": 0.0, "typing_applied": None, "vr_capture_until": 0.0}
def load_config():
conf = read_config()
state["rules"] = read_rules()
state["meta_dashboard"] = conf.get("META_DASHBOARD", "0") == "1"
state["share_keys"] = conf.get("SHARE_KEYS", "0") == "1"
if conf.get("POINTER", "0") == "1":
p = state["pointer"] or Pointer(0.03, 30)
@@ -692,7 +707,7 @@ def main():
log("pointer mode off: pointer devices feed the virtual mouse and keyboard")
load_config()
meta_down = False # Meta pressed with no other key yet: a tap toggles the dashboard
tap = None # the modifier (folded, MODIFIERS) pressed alone, with nothing since: its release is a tap
screens_sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM | socket.SOCK_NONBLOCK)
last_typing = 0.0 # the helper was last told of a key then (see "typing" at the top)
@@ -748,7 +763,7 @@ def main():
def do_action(action, value, now, source="mouse"):
"""A mapped mouse or controller button, or key combination (pointer mode only, but
for FLOAT_ACTIONS and profiles)."""
for the actions needs_pointer() says don't)."""
if action == "keyboard_toggle":
if value == 1 and vr_keyboard_mode() != "never":
vr_keyboard("toggle")
@@ -758,6 +773,17 @@ def main():
subprocess.Popen([FT_LAYOUT, "use", action[len(PROFILE):]], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
log(action)
elif action == "steam_menu":
if value == 1:
# Talks to Steam's UI for a moment; its errors go to this service's log.
subprocess.Popen([FT_STEAM, "menu"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
start_new_session=True)
log(action)
elif action.startswith(COMMAND):
if value == 1:
subprocess.Popen(["sh", "-c", action[len(COMMAND):]], stdin=subprocess.DEVNULL,
env=dict(os.environ, PATH=COMMAND_PATH), start_new_session=True)
log(action)
elif action in FLOAT_ACTIONS:
if value == 1:
try:
@@ -776,14 +802,20 @@ def main():
def key_binding(code, value, now):
"""A key from a keyboard: does it complete a key combination ("key_bindings")? True if
it was taken for one (then it isn't typed)."""
nonlocal meta_down
nonlocal tap
if code in MODIFIERS:
(held_modifiers.add if value else held_modifiers.discard)(MODIFIERS[code])
mod = MODIFIERS[code]
if value == 1:
tap = mod if not held_modifiers and not combos_down else None
(held_modifiers.add if value else held_modifiers.discard)(mod)
if code in (KEY_LEFTMETA, KEY_RIGHTMETA):
(held_meta.add if value else held_meta.discard)(code)
if value == 0 and code in meta_hidden:
meta_hidden.discard(code)
return True # the desktop already had it come up (below)
if value == 0 and tap == mod:
tap = None
modifier_tap(mod, now)
return False
if value == 1 and code not in combos_down and meta_hidden:
# Another key while Meta is still held after a combination: the desktop gets Meta
@@ -805,10 +837,9 @@ def main():
combos_down[code] = action
if held_meta - meta_hidden:
# The desktop saw Meta go down. Another key in between keeps its release from
# opening Plasma's launcher (and Meta from toggling the dashboard here), and Meta
# comes up there now: KWin takes Meta with a mouse button for moving or resizing
# windows, which would swallow a gaze click. Its real release is dropped (above).
meta_down = False
# opening Plasma's launcher, and Meta comes up there now: KWin takes Meta with a
# mouse button for moving or resizing windows, which would swallow a gaze click.
# Its real release is dropped (above).
to_screens(KEY_F24, 1)
to_screens(KEY_F24, 0)
for c in sorted(held_meta - meta_hidden):
@@ -819,6 +850,20 @@ def main():
log(f"key combination {combo}: {action}")
return True
def modifier_tap(mod, now):
"""A modifier pressed and released alone: its binding, if it has one ("125": Meta tap)."""
action = state["rules"]["key_bindings"].get(str(mod))
if not known_action(action) or action in ("key", "none"):
return
# The desktop gets a key in between before the release goes there, so the tap isn't one
# there too: a Meta tap would open Plasma's launcher.
to_screens(KEY_F24, 1)
to_screens(KEY_F24, 0)
if state["pointer"] or not needs_pointer(action):
do_action(action, 1, now, "keyboard")
do_action(action, 0, now, "keyboard")
log(f"key combination {mod}: {action}")
screens_down = set() # keys the desktop was told went down and not yet up (see reconcile_desktop_keys)
@@ -1136,40 +1181,37 @@ def main():
if etype in (EV_KEY, EV_REL):
broadcast(node, etype, VOLUME_ORIGINAL.get(code, code) if node.remapped else code,
value, now)
if (etype == EV_KEY and value == 1 and code not in MODIFIERS) or (etype == EV_REL and code in SCROLLS):
tap = None # a key, button or scroll in between: a modifier's release isn't a tap
if etype == EV_KEY and ((node.remapped and code in VOLUME_ORIGINAL)
or (node.grabbed and code in VOLUME_STANDIN)):
volume.key(fd, code, value, now)
if value == 1:
meta_down = False # Meta used as a modifier, not a tap
continue
if node.role == "volume":
continue
if node.role != "pointer":
# Observed only, unless typing goes to the desktop. With META_DASHBOARD=1,
# a Meta tap on any keyboard toggles the dashboard.
# Observed only, unless typing goes to the desktop. Key combinations work on
# any pass-through keyboard.
if (node.role == "passthrough" and etype == EV_KEY and node.grabbed
and code < BTN_MISC and value in (0, 1)):
# Shared as pressed, key combinations included: the Meta release a
# combination keeps from the desktop must still reach frame-voice, or
# it waits for that release before typing anything.
share_key(node, code, value)
if value:
node.held.add(code)
else:
node.held.discard(code)
if node.role == "passthrough" and etype == EV_KEY and code < BTN_MISC and key_binding(code, value, now):
continue
if node.role == "passthrough" and etype == EV_KEY:
if value == 1 and code < BTN_MISC and now - last_typing >= 0.25:
last_typing = now
screens_sock.sendto(b"typing", HELPER)
try:
screens_sock.sendto(b"typing", HELPER)
except OSError:
pass # helper not running (SteamVR not running)
to_screens(code, value)
if node.grabbed and code < BTN_MISC and value in (0, 1):
share_key(node, code, value)
if value:
node.held.add(code)
else:
node.held.discard(code)
if (pointer and state["meta_dashboard"] and node.role == "passthrough"
and etype == EV_KEY):
if code in (KEY_LEFTMETA, KEY_RIGHTMETA):
if value == 1:
meta_down = True
elif value == 0 and meta_down:
meta_down = False
pointer.dashboard()
elif value == 1:
meta_down = False # Meta used as a modifier, not a tap
continue
if etype == EV_KEY:
action = buttons.get(str(code), DEFAULT_BUTTONS.get(code, "key"))
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""Offline test of the input relay's key combinations and modifier taps.
Runs the relay's main() against a fake pass-through keyboard and a fake mouse (pipes), with
every socket it sends to renamed, no uinput devices, no grabs, and ft-steam swapped for a
logger. Nothing reaches the live desktop, SteamVR, or the running relay, so it's safe next
to them. Rules come from the test, not ~/.config/frametop-input.json.
input/test/keys-test.py [RELAY] (default: input/input-relay.py next to this folder)
"""
import fcntl
import importlib.util
import os
import shutil
import socket
import struct
import sys
import tempfile
import threading
import time
HERE = os.path.dirname(os.path.abspath(__file__))
relay_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "..", "input-relay.py")
tag = f"ft_keys_test_{os.getpid()}"
with open(relay_path) as f:
src = f.read().replace('"\\0frametop_relay"', f'"\\0{tag}_relay"')
relay = importlib.util.module_from_spec(importlib.util.spec_from_loader("relay", loader=None))
relay.__file__ = os.path.abspath(relay_path)
exec(compile(src, relay_path, "exec"), relay.__dict__)
for name in ("SCREENS", "HELPER", "FLOAT", "GAZED", "KEYS"):
setattr(relay, name, f"\0{tag}_{name.lower()}")
OUT = tempfile.mkdtemp(prefix="ft-keys-test-")
steam_log, cmd_log = f"{OUT}/steam.log", f"{OUT}/cmd.log"
relay.FT_STEAM = f"{OUT}/ft-steam"
with open(relay.FT_STEAM, "w") as f:
f.write(f'#!/bin/sh\necho "$@" >> {steam_log}\n')
os.chmod(relay.FT_STEAM, 0o755)
class NoDevice:
def __init__(self, *args, **kwargs):
pass
def emit(self, *args):
pass
def sync(self):
pass
relay.Virtual = NoDevice
relay.log = lambda *args: None # the relay's own log
bindings = {"now": None} # the rules' key_bindings; None: the relay's defaults
def read_rules(path=None):
rules = {"devices": {}, "buttons": {}, "controller_buttons": {}}
rules["key_bindings"] = dict(relay.DEFAULT_KEY_BINDINGS if bindings["now"] is None else bindings["now"])
return rules
relay.read_rules = read_rules
relay.read_config = lambda path=None: {"POINTER": "0"}
# The fake devices: /dev/input/event900 (keyboard) and event901 (mouse), each a pipe.
kb_r, kb_w = os.pipe()
ms_r, ms_w = os.pipe()
for fd in (kb_r, ms_r):
os.set_blocking(fd, False)
FAKE = {"/dev/input/event900": kb_r, "/dev/input/event901": ms_r}
HELD = {kb_r: set(), ms_r: set()} # what EVIOCGKEY says each holds
class Inode:
st_ino = 1
fake_os = type(os)("os")
fake_os.__dict__.update(os.__dict__)
fake_os.listdir = lambda path: ["event900", "event901"] if path == "/dev/input" else os.listdir(path)
fake_os.stat = lambda path, *a, **k: Inode() if path in FAKE else os.stat(path, *a, **k)
relay.os = fake_os
def ioctl(fd, request, arg=0, *rest):
if fd in HELD and request == relay.EVIOCGKEY:
for c in HELD[fd]:
arg[c // 8] |= 1 << (c % 8)
return 0
return fcntl.ioctl(fd, request, arg, *rest)
fake_fcntl = type(fcntl)("fcntl")
fake_fcntl.__dict__.update(fcntl.__dict__)
fake_fcntl.ioctl = ioctl
relay.fcntl = fake_fcntl
def probe(path):
if FAKE[path] == kb_r:
return relay.Node(path, kb_r, "test keyboard", relay.BUS_USB, 1, 2, "", False, True)
return relay.Node(path, ms_r, "test mouse", relay.BUS_USB, 3, 4, "", True, False)
relay.probe = probe
screens = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
screens.bind(relay.SCREENS)
screens.settimeout(0.05)
EVENT = struct.Struct("llHHi")
def send(fd, etype, code, value):
os.write(fd, EVENT.pack(0, 0, etype, code, value) + EVENT.pack(0, 0, 0, 0, 0))
time.sleep(0.03)
def key(code, value, fd=kb_w):
held = HELD[ms_r if fd == ms_w else kb_r]
(held.add if value else held.discard)(code)
send(fd, relay.EV_KEY, code, value)
def typed():
"""What the desktop was sent since the last call."""
got = []
while True:
try:
got.append(screens.recv(256).decode())
except socket.timeout:
return got
def use(key_bindings):
bindings["now"] = key_bindings
c = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
c.bind("")
c.settimeout(2)
c.sendto(b"reload", f"\0{tag}_relay")
c.recv(4096)
time.sleep(0.05)
typed()
def lines(path, wait=0.3):
time.sleep(wait)
try:
with open(path) as f:
return f.read().split()
except OSError:
return []
failures = []
def check(label, got, want):
ok = got == want
print(("ok " if ok else "FAIL ") + label + ("" if ok else f": got {got!r}, want {want!r}"), flush=True)
if not ok:
failures.append(label)
META, RMETA, SHIFT, CTRL, RCTRL, A, F, J = 125, 126, 42, 29, 97, 30, 33, 36
F24 = ["key 194 1", "key 194 0"]
def tests():
time.sleep(1.5) # the relay's first device scan
typed()
key(META, 1); key(META, 0)
check("Meta tap (default): Steam menu", lines(steam_log), ["menu"])
check("Meta tap: the desktop gets F24 before Meta's release", typed(), ["key 125 1"] + F24 + ["key 125 0"])
key(RMETA, 1); key(RMETA, 2); key(RMETA, 2); key(RMETA, 0)
check("right Meta held (autorepeat), then released: a tap", lines(steam_log), ["menu", "menu"])
typed()
key(META, 1); key(A, 1); key(A, 0); key(META, 0)
check("Meta+A: no tap", lines(steam_log), ["menu", "menu"])
check("Meta+A (unbound) is typed as is", typed(), ["key 125 1", "key 30 1", "key 30 0", "key 125 0"])
key(META, 1); key(relay.BTN_LEFT, 1, ms_w); key(relay.BTN_LEFT, 0, ms_w); key(META, 0)
check("Meta+click: no tap", lines(steam_log), ["menu", "menu"])
key(META, 1); send(ms_w, relay.EV_REL, relay.REL_WHEEL, 1); key(META, 0)
check("Meta+scroll: no tap", lines(steam_log), ["menu", "menu"])
key(META, 1); key(SHIFT, 1); key(SHIFT, 0); key(META, 0)
check("Meta+Shift: no tap", lines(steam_log), ["menu", "menu"])
typed()
key(META, 1); key(J, 1); key(J, 0); key(META, 0)
check("Meta+J (default gaze click): no tap", lines(steam_log), ["menu", "menu"])
check("Meta+J: F24, Meta up early, its real release dropped", typed(), ["key 125 1"] + F24 + ["key 125 0"])
use({"29+42+33": f"command:echo combo >> {cmd_log}", "125": "none"})
key(CTRL, 1); key(SHIFT, 1); key(F, 1); key(F, 0); key(SHIFT, 0); key(CTRL, 0)
check("Ctrl+Shift+F runs its command", lines(cmd_log), ["combo"])
check("the combination's last key isn't typed", [k for k in typed() if k.startswith("key 33 ")], [])
key(META, 1); key(META, 0)
check("Meta tap bound to none: nothing", lines(steam_log), ["menu", "menu"])
check("Meta tap bound to none: no F24", typed(), ["key 125 1", "key 125 0"])
use({"29": f"command:command -v ft-steam ft-layout ft-float | wc -l >> {cmd_log}"})
key(RCTRL, 1); key(RCTRL, 0)
check("right Ctrl tap runs its command, which finds Frametop's tools", lines(cmd_log), ["combo", "3"])
check("Ctrl tap: F24 before Ctrl's release", typed(), ["key 97 1"] + F24 + ["key 97 0"])
check("an empty command isn't an action", relay.known_action("command: "), False)
check("steam_menu and commands work without pointer mode",
(relay.needs_pointer("steam_menu"), relay.needs_pointer("command:ls")), (False, False))
print("FAILED: " + ", ".join(failures) if failures else "all passed", flush=True)
shutil.rmtree(OUT, ignore_errors=True)
os._exit(1 if failures else 0)
threading.Thread(target=tests, daemon=True).start()
sys.argv = [relay_path, "--no-grab"]
relay.main()
+1 -1
View File
@@ -112,7 +112,7 @@ def main():
try:
with open(os.path.join(HOME, ".config/frametop.conf")) as f:
conf = [ln.split("#")[0].strip() for ln in f]
out("Settings: " + " ".join(c for c in conf if re.match(r"(POINTER|META_DASHBOARD|SHARE_KEYS|BACKEND)=", c)))
out("Settings: " + " ".join(c for c in conf if re.match(r"(POINTER|SHARE_KEYS|BACKEND)=", c)))
except OSError:
out("Settings: no ~/.config/frametop.conf")
out("ft-screens state (visibility, manual, wrist, gesture, lasers, game running, in games): "
+25
View File
@@ -321,6 +321,30 @@ def check_services(sockets, desktop_up):
report("FAIL", "XRService", "not running, so hand tracking has no cameras")
def check_steam_ui():
"""Steam's UI calls the Steam menu shortcut uses (steam/ft-steam). They're Steam client
internals, so a Steam update can change them too, not just a SteamOS one."""
# Run from stdin (over SSH) there's no __file__: try the usual checkouts.
repos = [os.path.dirname(os.path.dirname(os.path.abspath(__file__)))] if "__file__" in globals() else []
repos += [os.path.join(HOME, "frametop"), os.path.join(HOME, "dev/frametop")]
tool = next((t for t in (os.path.join(r, "steam/ft-steam") for r in repos) if os.path.exists(t)), None)
if not tool:
report("skip", "Steam menu shortcut", "steam/ft-steam isn't in a checkout here")
return
try:
p = subprocess.run([tool, "check"], capture_output=True, text=True, timeout=15)
except (OSError, subprocess.TimeoutExpired) as e:
report("warn", "Steam menu shortcut", f"ft-steam check didn't run ({e})")
return
detail = (p.stdout + p.stderr).strip()
if p.returncode == 0:
report("ok", "Steam menu shortcut", "Steam's UI still has the calls steam/ft-steam makes")
elif detail.startswith("ft-steam:"):
report("skip", "Steam menu shortcut", detail[len("ft-steam:"):].strip())
else:
report("warn", "Steam menu shortcut", f"{detail}; a Meta tap won't open the Steam menu (steam/ft-steam)")
def check_eye_tracker():
gaze = systemctl("is-enabled", "frametop-gaze") == "enabled"
try:
@@ -369,6 +393,7 @@ def main():
check_openvr()
check_overlays(desktop_up)
check_services(sockets, desktop_up)
check_steam_ui()
check_eye_tracker()
if args == ["--mark-good"]:
-1
View File
@@ -54,7 +54,6 @@ POINTER_PINCH_DEADZONE=1.5 # hands: degrees the pinching hand moves before the p
POINTER_GRIP_GAIN=1 # hands: the pointer moves this times the gripping hand's angle
POINTER_GRIP_BELOW=0.35 # hands: grips beginning more than this (m) below the eyes are ignored (hands on a desk)
POINTER_PINCH_TYPING=1 # hands: no pinch within this many seconds of a key (typing touches thumb to index)
META_DASHBOARD=0 # 1 = a Meta tap on a pass-through keyboard toggles the SteamVR dashboard (pointer mode only)
SHARE_KEYS=0 # 1 = keys of keyboards grabbed for the desktop also go to @frametop_keys, for hotkey tools (any local process can listen)
DISPLAY_OFF_MIN=0 # minutes without use before frametop-power turns the displays off, even if the headset seems worn (0 = never)
DISPLAY_MOVE_MM=5 # displays off: the headset or a controller moving this far (mm) within 10 s counts as use
Executable
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""ft-steam: Steam's menu and checks, through Steam's own UI (steamui.py).
ft-steam menu open the SteamVR dashboard on Steam's menu, or close the dashboard if it's
open (the Steam button's job, as a shortcut: the input relay's steam_menu)
ft-steam check do Steam's UI calls that the above needs still exist (update-check.py)
No pointer mode needed: it asks Steam to show its dashboard overlay (window.ShowVROverlay, what
Steam itself calls) and to focus the Steam frame's left menu (MenuStore.OpenMainMenu, which in
VR invokes the frame's focus_left_frame_menu_action). SteamClient.OpenVR.VROverlay says
whether the dashboard is up and hides it. These are Steam's UI internals, not an API, so a
Steam client update can rename them: `ft-steam check` says so.
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
from steamui import SteamUnreachable, evaluate # noqa: E402
WINDOW = "SteamUIStore.WindowStore.VRGamepadUIMainWindowInstance"
MENU = f"""(async () => {{
const vr = SteamClient.OpenVR.VROverlay;
if (await vr.IsDashboardVisible()) {{ vr.HideDashboard(); return "closed"; }}
const w = {WINDOW};
if (!w) throw new Error("Steam's VR dashboard window isn't open");
ShowVROverlay(w.GetVROverlayKey());
// The frame's menu takes focus only once the dashboard is up.
for (let i = 0; i < 40 && !(await vr.IsDashboardVisible()); i++) await new Promise(r => setTimeout(r, 25));
w.MenuStore.OpenMainMenu();
return "opened";
}})()"""
CHECK = f"""(() => {{
const missing = [];
const vr = SteamClient.OpenVR && SteamClient.OpenVR.VROverlay;
for (const f of ["IsDashboardVisible", "HideDashboard"]) if (!vr || typeof vr[f] !== "function") missing.push("SteamClient.OpenVR.VROverlay." + f);
if (typeof window.ShowVROverlay !== "function") missing.push("ShowVROverlay");
const w = {WINDOW};
if (!w) missing.push("{WINDOW}");
else {{
if (typeof w.GetVROverlayKey !== "function") missing.push("GetVROverlayKey");
if (!w.MenuStore || typeof w.MenuStore.OpenMainMenu !== "function") missing.push("MenuStore.OpenMainMenu");
}}
return missing;
}})()"""
def main():
cmd = sys.argv[1] if len(sys.argv) == 2 else ""
if cmd not in ("menu", "check"):
sys.exit(__doc__)
try:
result = evaluate(MENU if cmd == "menu" else CHECK)
except SteamUnreachable as e:
sys.exit(f"ft-steam: {e}")
if cmd == "check":
if result:
sys.exit("Steam's UI lacks " + ", ".join(result))
print("ok")
else:
print(result)
if __name__ == "__main__":
main()
+108
View File
@@ -0,0 +1,108 @@
"""Run JavaScript in Steam's UI, standard library only.
Steam on the Frame runs with -cef-enable-debugging, so its UI's JavaScript context
(SharedJSContext) is reachable over the Chrome DevTools Protocol on 127.0.0.1:8080. Steam's
own calls live there: SteamClient.* (settings, SteamVR's dashboard) and the UI's stores
(SteamUIStore). Used by Frametop Display Settings (display-settings/steam_settings.py) and
ft-steam (the Steam menu shortcut).
evaluate(expression) the expression's value (awaited, JSON-able); SteamUnreachable when
Steam or its UI isn't there, or the script threw
"""
import base64
import json
import os
import socket
import struct
import urllib.request
CDP_PORT = 8080
class SteamUnreachable(Exception):
pass
class _WebSocket:
def __init__(self, url, timeout=5):
host_port, path = url[len("ws://"):].split("/", 1)
host, port = host_port.rsplit(":", 1)
self.sock = socket.create_connection((host, int(port)), timeout=timeout)
key = base64.b64encode(os.urandom(16)).decode()
self.sock.sendall((f"GET /{path} HTTP/1.1\r\nHost: {host_port}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
head = b""
while b"\r\n\r\n" not in head:
chunk = self.sock.recv(4096)
if not chunk:
raise SteamUnreachable("Steam closed the connection")
head += chunk
if b" 101 " not in head.split(b"\r\n", 1)[0]:
raise SteamUnreachable(head.split(b"\r\n", 1)[0].decode(errors="replace"))
self.buf = head.split(b"\r\n\r\n", 1)[1]
def send(self, text):
data, mask = text.encode(), os.urandom(4)
n = len(data)
if n < 126:
head = struct.pack(">BB", 0x81, 0x80 | n)
elif n < 65536:
head = struct.pack(">BBH", 0x81, 0x80 | 126, n)
else:
head = struct.pack(">BBQ", 0x81, 0x80 | 127, n)
self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
def _take(self, n):
while len(self.buf) < n:
chunk = self.sock.recv(65536)
if not chunk:
raise SteamUnreachable("Steam closed the connection")
self.buf += chunk
out, self.buf = self.buf[:n], self.buf[n:]
return out
def recv(self):
message = b""
while True:
b0, b1 = self._take(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", self._take(2))[0]
elif n == 127:
n = struct.unpack(">Q", self._take(8))[0]
message += self._take(n)
if b0 & 0x80:
return message.decode(errors="replace")
def close(self):
self.sock.close()
def evaluate(expression):
"""Runs JavaScript in Steam's SharedJSContext and returns its (awaited) value."""
try:
with urllib.request.urlopen(f"http://127.0.0.1:{CDP_PORT}/json", timeout=3) as r:
targets = json.load(r)
except OSError as e:
raise SteamUnreachable(f"Steam isn't reachable on port {CDP_PORT} ({e})") from e
url = next((t["webSocketDebuggerUrl"] for t in targets if t.get("title") == "SharedJSContext"), None)
if not url:
raise SteamUnreachable("Steam's UI isn't running")
try:
ws = _WebSocket(url)
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate",
"params": {"expression": expression, "awaitPromise": True, "returnByValue": True}}))
while True:
reply = json.loads(ws.recv())
if reply.get("id") == 1:
break
finally:
ws.close()
except OSError as e:
raise SteamUnreachable(str(e)) from e
result = reply.get("result", {})
if "exceptionDetails" in result:
details = result["exceptionDetails"]
raise SteamUnreachable(details.get("exception", {}).get("description") or details.get("text", "error"))
return result.get("result", {}).get("value")