mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-25 15:56:01 +00:00
fix: route VR scene focus through Gamescope
This commit is contained in:
1 parent
5e9ebbc7df
commit
46335b7871
7 files changed
+132
-2
No files matched your search
@@ -177,6 +177,11 @@ class X:
|
||||
return list(struct.unpack("<%dI" % n, data))
|
||||
return data
|
||||
|
||||
def cardinals(self, window, name, values):
|
||||
self.s.sendall(struct.pack("<BBHIIIB3xI", 18, 0, 6 + len(values), window,
|
||||
self.atom(name), self.atom("CARDINAL"), 32, len(values))
|
||||
+ struct.pack("<%dI" % len(values), *values))
|
||||
|
||||
|
||||
def windows(x):
|
||||
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
|
||||
@@ -249,6 +254,42 @@ def focus_snapshot():
|
||||
return snap
|
||||
|
||||
|
||||
def vr_scene_app(path=Path('/run/droiddeck/droiddeck-steamvr/scene-focus.json'), proc=Path('/proc')):
|
||||
"""Only a live SteamVR scene with its dashboard hidden may claim game focus."""
|
||||
try:
|
||||
state = json.loads(path.read_text())
|
||||
server, scene = int(state['serverPid']), int(state['scenePid'])
|
||||
if server <= 0 or scene <= 0 or state['dashboard'] is not False:
|
||||
return None
|
||||
if (proc / str(server) / 'comm').read_text().strip() != 'vrserver':
|
||||
return None
|
||||
for entry in (proc / str(scene) / 'environ').read_bytes().split(b'\0'):
|
||||
if entry.startswith(b'SteamAppId='):
|
||||
app = int(entry.split(b'=', 1)[1])
|
||||
return app if 0 < app < 2**32 else None
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
class VrSceneFocus:
|
||||
def __init__(self):
|
||||
self.original = None
|
||||
self.written = None
|
||||
|
||||
def order(self, current, focusable, app):
|
||||
if app is None or app not in focusable:
|
||||
restore = self.original if self.written == current else None
|
||||
self.original = self.written = None
|
||||
return restore
|
||||
if current and current[0] == app:
|
||||
return None
|
||||
if self.original is None:
|
||||
self.original = list(current)
|
||||
self.written = [app] + [item for item in current if item != app]
|
||||
return self.written
|
||||
|
||||
|
||||
class FocusWatcher(threading.Thread):
|
||||
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
|
||||
the windows do (a window can change without any root property moving)."""
|
||||
@@ -259,15 +300,28 @@ class FocusWatcher(threading.Thread):
|
||||
self.changed = threading.Event()
|
||||
self.last = None
|
||||
self.seq = 0
|
||||
self.vr_focus = VrSceneFocus()
|
||||
|
||||
def run(self):
|
||||
threading.Thread(target=self.listen, daemon=True, name="focus-events").start()
|
||||
last_app, last_snapshot = None, 0
|
||||
while True:
|
||||
self.changed.wait(timeout=5)
|
||||
notified = self.changed.wait(timeout=0.5)
|
||||
self.changed.clear()
|
||||
app = vr_scene_app()
|
||||
if not notified and app == last_app and time.monotonic() - last_snapshot < 5:
|
||||
continue
|
||||
last_app, last_snapshot = app, time.monotonic()
|
||||
time.sleep(0.2)
|
||||
try:
|
||||
snap = focus_snapshot()
|
||||
order = self.vr_focus.order(snap.get('baselayerAppIds', []), snap.get('focusableApps', []), app)
|
||||
if order is not None:
|
||||
x = X(os.environ['DISPLAY'])
|
||||
try:
|
||||
x.cardinals(x.root, 'GAMESCOPECTRL_BASELAYER_APPID', order)
|
||||
finally:
|
||||
x.close()
|
||||
except (OSError, AgentError) as e:
|
||||
log("focus snapshot failed: %s" % e)
|
||||
time.sleep(2)
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
"""Reject an APK with missing or stale session helpers, including cached local bundles."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from zipfile import ZipFile
|
||||
|
||||
|
||||
OVERLAY = Path(__file__).resolve().parents[1] / 'linuxfs/overlay'
|
||||
SESSION_FILES = OVERLAY.parents[2] / 'app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt'
|
||||
|
||||
|
||||
def check_extraction(overlay, source):
|
||||
deployed = set(re.findall(r'"(usr/local/bin/droiddeck-[^"]+)"\s+to\s+"\1"', source))
|
||||
return ['not extracted at session start: ' + path.relative_to(overlay).as_posix()
|
||||
for path in sorted((overlay / 'usr/local/bin').glob('droiddeck-*'))
|
||||
if path.relative_to(overlay).as_posix() not in deployed]
|
||||
|
||||
|
||||
def source_assets(overlay=OVERLAY):
|
||||
@@ -23,7 +32,7 @@ def source_assets(overlay=OVERLAY):
|
||||
|
||||
|
||||
def check(apk, overlay=OVERLAY):
|
||||
errors = []
|
||||
errors = check_extraction(overlay, SESSION_FILES.read_text()) if overlay == OVERLAY else []
|
||||
with ZipFile(apk) as package:
|
||||
for source, asset in source_assets(overlay).items():
|
||||
try:
|
||||
|
||||
@@ -335,5 +335,35 @@ class AgentTest(unittest.TestCase):
|
||||
self.assertIn(child.pid, agent.game_pids(424242))
|
||||
|
||||
|
||||
class VrFocusTest(unittest.TestCase):
|
||||
def test_scene_dashboard_and_external_focus_changes(self):
|
||||
focus = agent.VrSceneFocus()
|
||||
self.assertEqual(focus.order([9, 7], [7, 42], 42), [42, 9, 7])
|
||||
self.assertIsNone(focus.order([42, 9, 7], [7, 42], 42))
|
||||
self.assertEqual(focus.order([42, 9, 7], [7, 42], None), [9, 7])
|
||||
self.assertIsNone(focus.order([9, 7], [7], 42))
|
||||
self.assertEqual(focus.order([9, 7], [7, 42], 42), [42, 9, 7])
|
||||
# Do not overwrite a different focus order installed after our last write.
|
||||
self.assertIsNone(focus.order([123, 7], [7, 42], None))
|
||||
|
||||
def test_scene_requires_live_server_and_game_environment(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
state = root / 'scene.json'
|
||||
for pid in (100, 200):
|
||||
(root / str(pid)).mkdir()
|
||||
(root / '100/comm').write_text('vrserver\n')
|
||||
(root / '200/environ').write_bytes(b'SteamAppId=42\0Other=value\0')
|
||||
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=False)))
|
||||
self.assertEqual(agent.vr_scene_app(state, root), 42)
|
||||
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=True)))
|
||||
self.assertIsNone(agent.vr_scene_app(state, root))
|
||||
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=False)))
|
||||
(root / '100/comm').write_text('other\n')
|
||||
self.assertIsNone(agent.vr_scene_app(state, root))
|
||||
(root / '100/comm').unlink()
|
||||
self.assertIsNone(agent.vr_scene_app(state, root))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -37,3 +37,9 @@ class SessionAssetsTest(unittest.TestCase):
|
||||
with ZipFile(self.apk, 'w') as package:
|
||||
package.writestr(self.name, self.helper.read_bytes())
|
||||
self.assertEqual([], assets.check(self.apk, self.overlay))
|
||||
|
||||
def test_bundled_helper_must_also_be_extracted(self):
|
||||
self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'],
|
||||
assets.check_extraction(self.overlay, ''))
|
||||
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1"'
|
||||
self.assertEqual([], assets.check_extraction(self.overlay, mapping))
|
||||
@@ -756,6 +756,7 @@ class Provider : public IServerTrackedDeviceProvider {
|
||||
public:
|
||||
EVRInitError Init(IVRDriverContext *ctx) override {
|
||||
VR_INIT_SERVER_DRIVER_CONTEXT(ctx);
|
||||
focusEnabled_ = access("/run/droiddeck/droiddeck-xr-frames", F_OK) == 0;
|
||||
Log("DroidDeck Cardboard driver loaded");
|
||||
if (!VRServerDriverHost()->TrackedDeviceAdded("droiddeck-cardboard-hmd", TrackedDeviceClass_HMD, &hmd_))
|
||||
Log("TrackedDeviceAdded failed");
|
||||
@@ -767,6 +768,7 @@ public:
|
||||
return VRInitError_None;
|
||||
}
|
||||
void Cleanup() override {
|
||||
if (focusEnabled_) unlink(kFocusPath);
|
||||
if (haptics_) { munmap(haptics_, sizeof(*haptics_)); haptics_ = nullptr; }
|
||||
VR_CLEANUP_SERVER_DRIVER_CONTEXT();
|
||||
}
|
||||
@@ -774,6 +776,13 @@ public:
|
||||
void RunFrame() override {
|
||||
VREvent_t e;
|
||||
while (VRServerDriverHost()->PollNextEvent(&e, sizeof(e))) {
|
||||
if (focusEnabled_) {
|
||||
bool changed = false;
|
||||
if (e.eventType == VREvent_SceneApplicationChanged) { scenePid_ = e.data.process.pid; changed = true; }
|
||||
if (e.eventType == VREvent_DashboardActivated) { dashboard_ = true; changed = true; }
|
||||
if (e.eventType == VREvent_DashboardDeactivated) { dashboard_ = false; changed = true; }
|
||||
if (changed) PublishFocus();
|
||||
}
|
||||
if (e.eventType == VREvent_Input_HapticVibration) {
|
||||
const auto &pulse = e.data.hapticVibration;
|
||||
int hand = pulse.componentHandle == left_.HapticHandle() ? 0 : pulse.componentHandle == right_.HapticHandle() ? 1 : -1;
|
||||
@@ -786,6 +795,21 @@ public:
|
||||
void LeaveStandby() override {}
|
||||
|
||||
private:
|
||||
static constexpr const char *kFocusPath = "/run/droiddeck/droiddeck-steamvr/scene-focus.json";
|
||||
bool focusEnabled_ = false, dashboard_ = true;
|
||||
uint32_t scenePid_ = 0;
|
||||
void PublishFocus() {
|
||||
const std::string temporary = std::string(kFocusPath) + ".tmp";
|
||||
int fd = open(temporary.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);
|
||||
if (fd < 0) return;
|
||||
char body[128];
|
||||
int length = snprintf(body, sizeof(body), "{\"serverPid\":%d,\"scenePid\":%u,\"dashboard\":%s}\n",
|
||||
getpid(), scenePid_, dashboard_ ? "true" : "false");
|
||||
bool written = write(fd, body, length) == length;
|
||||
close(fd);
|
||||
if (written) rename(temporary.c_str(), kFocusPath);
|
||||
else unlink(temporary.c_str());
|
||||
}
|
||||
DroidDeckXrHaptics *haptics_ = nullptr;
|
||||
void SendHaptic(int hand, const VREvent_HapticVibration_t &pulse) {
|
||||
if (!std::isfinite(pulse.fAmplitude) || !std::isfinite(pulse.fFrequency) || !std::isfinite(pulse.fDurationSeconds)) return;
|
||||
|
||||
Reference in new issue
Block a user