feat(steam): sync QAM controls and pass held Back shortcuts (#1621)

Steam's native QAM sliders now control Android brightness and media
volume, with device changes reflected back in Steam. Holding Android
Back for 700 ms sends a real held QAM button for Steam shortcuts. Single
and double taps keep the existing menu/QAM order and swap setting; the
double-tap window remains 500 ms.

- Discover native brightness through a guest backlight descriptor and
use Android's Modify system settings permission. Retain the latest
pending request until permission is granted or the session stops, with a
notification action for hidden sessions.
- Give DirectAudio and fallback AAudio sinks Android media volume/mute
callbacks, keeping software gain at unity. Recover when initial volume
state is absent or invalid, brightness acknowledgements differ or never
arrive, or the Display bridge is not ready yet.
- Forward other buttons while QAM is held in Steam Deck and Steam
Controller modes. Consume release after a hold and clear pending input
on overlays, focus loss, pause, disconnect, and teardown. The session
menu retains its compact Back choice without an explanatory paragraph.

Validation:
- Local ARM64 release build passed. The latest timing change passed 20
targeted input tests, including release at 600 ms remaining a tap. The
preceding full feature check passed 61 Android input/device-control
tests, with permission cases on API 28 and 33.
- 66 Linux Python/Node/C tests passed for device controls, audio
recovery, Steam compatibility, and file dialogs. Both audio sink modules
rebuilt with Android NDK 27.2.
- Release-signed integration build 14d12cf0 is installed on the unrooted
AYN Thor, carrying the Android/input changes through 749ade4a plus the
existing portrait changes. Device checks confirmed the configured
QAM/menu tap order, Back dismissal, removal of the inline menu
description, and held QAM overlapping X with clean release. Hands-on
testing confirmed this installed build works.
- Earlier Thor testing covered brightness permission and pending
requests, brightness synchronization in both directions, native volume
changes, hardware volume key readback, and both sink backends. Failure
recovery is covered by the automated tests above.

The subsequent queued-notification fix in 4d7ceb23 is covered by the
Linux regression suite and has not replaced the Thor install.

Bluetooth/wired output switching and other device models remain
untested. CI and CodeRabbit monitoring continue against the pushed head.
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-26 13:46:14 -04:00
commit a0a68f7280
19 files changed
+1243 -8

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdio.h>
#include <pulsecore/core-rtclock.h>
#include <pulsecore/core-subscribe.h>
struct android_volume {
pa_sink *sink;
char *directory;
pa_time_event *timer;
};
static bool android_volume_read(const char *directory, unsigned *level, unsigned *maximum, unsigned *muted) {
char *path = pa_sprintf_malloc("%s/volume.state", directory);
FILE *file = fopen(path, "r");
pa_xfree(path);
if (!file) return false;
int fields = fscanf(file, "%u %u %u", level, maximum, muted);
fclose(file);
return fields == 3 && *maximum > 0 && *level <= *maximum && *muted <= 1;
}
static void android_volume_request(pa_sink *sink, const char *name, unsigned value) {
struct userdata *u = sink->userdata;
if (!u->android_volume || sink->state == PA_SINK_INIT) return;
char *path = pa_sprintf_malloc("%s/%s.request", u->android_volume->directory, name);
char *staged = pa_sprintf_malloc("%s.tmp", path);
FILE *file = fopen(staged, "w");
if (file) {
fprintf(file, "%u\n", value);
if (fclose(file) == 0 && rename(staged, path) < 0) pa_log_warn("Could not publish Android %s", name);
}
pa_xfree(staged);
pa_xfree(path);
}
static void android_volume_set(pa_sink *sink) {
struct userdata *u = sink->userdata;
unsigned level, maximum, muted;
if (!u->android_volume || !android_volume_read(u->android_volume->directory, &level, &maximum, &muted)) return;
unsigned requested = PA_MIN(pa_cvolume_max(&sink->real_volume), PA_VOLUME_NORM);
level = ((uint64_t)requested * maximum + PA_VOLUME_NORM / 2) / PA_VOLUME_NORM;
pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
/* Android applies media gain to both PulseAudio and DirectAudio streams. */
pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels);
android_volume_request(sink, "volume", level);
}
static void android_volume_mute(pa_sink *sink) {
android_volume_request(sink, "mute", sink->muted ? 1 : 0);
}
static void android_volume_refresh(pa_mainloop_api *api, pa_time_event *event, const struct timeval *tv, void *userdata) {
struct android_volume *bridge = userdata;
unsigned level, maximum, muted;
char *request = pa_sprintf_malloc("%s/volume.request", bridge->directory);
char *mute_request = pa_sprintf_malloc("%s/mute.request", bridge->directory);
char *processing = pa_sprintf_malloc("%s.processing", request);
char *mute_processing = pa_sprintf_malloc("%s.processing", mute_request);
if (access(request, F_OK) != 0 && access(mute_request, F_OK) != 0 &&
access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0 &&
android_volume_read(bridge->directory, &level, &maximum, &muted)) {
pa_cvolume volume;
if (bridge->sink->n_volume_steps != maximum + 1) {
bridge->sink->n_volume_steps = maximum + 1;
pa_subscription_post(bridge->sink->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, bridge->sink->index);
}
pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) pa_sink_volume_changed(bridge->sink, &volume);
if (bridge->sink->muted != !!muted) pa_sink_mute_changed(bridge->sink, !!muted);
}
pa_xfree(request);
pa_xfree(mute_request);
pa_xfree(processing);
pa_xfree(mute_processing);
pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC);
}
static struct android_volume *android_volume_new(pa_sink *sink, const char *directory) {
unsigned level, maximum, muted;
if (!directory) return NULL;
struct android_volume *bridge = pa_xnew0(struct android_volume, 1);
bridge->sink = sink;
bridge->directory = pa_xstrdup(directory);
if (android_volume_read(directory, &level, &maximum, &muted)) {
pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum);
sink->reference_volume = sink->real_volume;
sink->muted = !!muted;
sink->n_volume_steps = maximum + 1;
}
pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels);
pa_sink_set_set_volume_callback(sink, android_volume_set);
pa_sink_set_set_mute_callback(sink, android_volume_mute);
bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC,
android_volume_refresh, bridge);
return bridge;
}
static void android_volume_free(struct android_volume *bridge) {
if (!bridge) return;
bridge->sink->core->mainloop->time_free(bridge->timer);
pa_xfree(bridge->directory);
pa_xfree(bridge);
}
+11
View File
@@ -42,6 +42,7 @@ PA_MODULE_USAGE(
"channels=<number of channels> "
"channel_map=<channel map> "
"volume=<initial volume, linear, 1.0 = full> "
"control_dir=<Android media volume bridge directory> "
"performance_mode=<0 none, 1 low latency, 2 power saving> "
"adaptive=<grow the buffer after underruns: 0 or 1> "
"buffer_frames=<initial buffer size in frames, 0 = two bursts> "
@@ -56,6 +57,7 @@ PA_MODULE_USAGE(
#define STATS_EVERY_USEC (30 * PA_USEC_PER_SEC)
static const char* const valid_modargs[] = {
"control_dir",
"sink_name",
"sink_properties",
"format",
@@ -70,7 +72,10 @@ static const char* const valid_modargs[] = {
NULL
};
struct android_volume;
struct userdata {
struct android_volume *android_volume;
pa_core *core;
pa_module *module;
pa_sink *sink;
@@ -100,6 +105,9 @@ struct userdata {
int32_t xruns_reported;
};
#include "android-volume.h"
static pa_usec_t frames_to_usec(const struct userdata *u, int64_t frames) {
return (pa_usec_t) (frames * (int64_t) PA_USEC_PER_SEC / (int64_t) u->ss.rate);
}
@@ -472,6 +480,7 @@ int pa__init(pa_module *m) {
goto fail;
}
u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL));
pa_sink_put(u->sink);
pa_modargs_free(ma);
return 0;
@@ -498,6 +507,8 @@ void pa__done(pa_module *m) {
if (!(u = m->userdata))
return;
android_volume_free(u->android_volume);
u->android_volume = NULL;
if (u->sink)
pa_sink_unlink(u->sink);
if (u->thread) {
@@ -59,6 +59,7 @@ PA_MODULE_DESCRIPTION("Android audio output: DirectAudio's AAudio engine, in-pro
PA_MODULE_VERSION(PACKAGE_VERSION);
PA_MODULE_LOAD_ONCE(false);
PA_MODULE_USAGE(
"control_dir=<Android media volume bridge directory> "
"sink_name=<name for the sink> "
"sink_properties=<properties for the sink> "
"volume=<initial volume, linear, 1.0 = full> "
@@ -91,11 +92,15 @@ PA_MODULE_USAGE(
#define DA_FADE_FRAMES 64
static const char* const valid_modargs[] = {
"control_dir",
"sink_name", "sink_properties", "volume", "performance_mode", "buffer_ms", "max_ms", "ring_ms",
"adaptive", "decay", "limiter", "watchdog", NULL
};
struct android_volume;
struct userdata {
struct android_volume *android_volume;
pa_core *core;
pa_module *module;
pa_sink *sink;
@@ -136,6 +141,9 @@ struct userdata {
unsigned int opens;
};
#include "../../aaudio-sink/android-volume.h"
static uint64_t now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -774,6 +782,7 @@ int pa__init(pa_module *m) {
pa_log("Failed to create thread.");
goto fail;
}
u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL));
pa_sink_put(u->sink);
pa_modargs_free(ma);
return 0;
@@ -799,6 +808,8 @@ void pa__done(pa_module *m) {
pa_assert(m);
if (!(u = m->userdata))
return;
android_volume_free(u->android_volume);
u->android_volume = NULL;
if (u->sink)
pa_sink_unlink(u->sink);
if (u->thread) {
@@ -2,6 +2,7 @@
import base64
import ctypes
import json
import math
import os
import runpy
import select
@@ -15,6 +16,50 @@ import time
HERE = os.path.dirname(os.path.realpath(__file__))
COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility"))
BINDING = "droiddeckCompatChanged"
BRIGHTNESS_BINDING = "droiddeckBrightnessChanged"
CONTROLS_DIR = "/etc/droiddeck-device-controls"
BRIGHTNESS_JS = r"""
(() => {
if (window.__droiddeckBrightness) return "present";
const display = SteamClient.System?.Display;
if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable";
const self = { expected: null, updating: true, revision: 0 };
self.set = value => {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return;
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return;
self.expected = value;
self.updating = true;
const revision = ++self.revision;
setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500);
display.SetBrightness(value);
};
self.subscription = display.RegisterForBrightnessChanges(state => {
const value = state?.flBrightness;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1 || self.expected === null) return;
if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; }
if (self.updating) { self.updating = false; return; }
self.expected = value;
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value));
});
window.__droiddeckBrightness = self;
return "installed";
})()
""".replace("__BINDING__", BRIGHTNESS_BINDING)
def brightness_request(payload, directory=CONTROLS_DIR):
try:
value = float(payload)
if not math.isfinite(value) or not 0 <= value <= 1:
return
path = os.path.join(directory, "brightness.request")
with open(path + ".tmp", "w") as target:
target.write(str(value) + "\n")
os.replace(path + ".tmp", path)
except (ValueError, TypeError, OSError):
return
INSTALL_JS = r"""
(() => {
if (window.__droiddeckCompat) return "present";
@@ -633,6 +678,29 @@ class Helper:
self.tools_checked = None
self.vr_launch = None
self.chooser = None
self.controls_state = None
self.controls_installed = False
def sync_controls(self):
try:
with open(os.path.join(CONTROLS_DIR, "state.json")) as source:
state = json.load(source)
value = state.get("brightness")
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 1:
return
if not self.controls_installed:
self.page.call("Runtime.addBinding", {"name": BRIGHTNESS_BINDING})
self.controls_installed = self.page.evaluate(BRIGHTNESS_JS) in ("installed", "present")
if not self.controls_installed:
return
if state != self.controls_state:
if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True:
self.controls_state = state
else:
self.controls_installed = False
self.controls_state = None
except (OSError, ValueError, TypeError):
pass
def open_chooser(self, payload):
try:
@@ -709,6 +777,9 @@ class Helper:
page.call("Runtime.addBinding", {"name": FILE_BINDING})
page.evaluate(FILE_JS)
self.page = page
self.controls_state = None
self.controls_installed = False
self.sync_controls()
return True
page.call("Runtime.addBinding", {"name": BINDING})
page.call("Runtime.addBinding", {"name": VR_BINDING})
@@ -728,6 +799,9 @@ class Helper:
page.ws.close()
raise
self.page = page
self.controls_state = None
self.controls_installed = False
self.sync_controls()
return True
def reconcile(self):
@@ -854,6 +928,8 @@ class Helper:
say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games)))
self.vr_launch = launch_steamvr()
for e in events:
if called(e, BRIGHTNESS_BINDING):
brightness_request(e.get("params", {}).get("payload"))
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
self.open_chooser(e["params"]["payload"])
return events
@@ -861,15 +937,14 @@ class Helper:
def serve_files(self):
say("attached to the client on port %d for its file dialogs" % self.port)
while True:
self.sync_controls()
sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else [])
queued = self.page.ws.pending() or bool(self.page.events)
ready = [self.page.ws] if queued else select.select(sources, [], [], 30)[0]
ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
self.chooser_done()
if self.page.ws in ready or self.page.events:
for e in self.page.drain():
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
self.open_chooser(e["params"]["payload"])
self.drain()
def serve(self, watcher):
if self.files_only:
@@ -880,10 +955,12 @@ class Helper:
self.reconcile()
self.ensure_tools()
while True:
self.sync_controls()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
if self.chooser is not None:
sources.append(self.chooser[1].stdout)
ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0]
queued = self.page.ws.pending() or bool(self.page.events)
ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
self.chooser_done()
due = False
+101
View File
@@ -0,0 +1,101 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
@unittest.skipUnless(shutil.which("cc"), "C compiler required")
class AndroidVolumeTest(unittest.TestCase):
def test_missing_or_invalid_initial_state_recovers_without_restarting_the_sink(self):
header = Path(__file__).resolve().parents[1] / "aaudio-sink/android-volume.h"
harness = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#define PA_VOLUME_NORM 65536U
#define PA_USEC_PER_MSEC 1000
#define PA_SINK_INIT 0
#define PA_SUBSCRIPTION_EVENT_SINK 1
#define PA_SUBSCRIPTION_EVENT_CHANGE 2
#define PA_MIN(a,b) ((a)<(b)?(a):(b))
#define pa_xnew0(type,n) ((type*)calloc(n,sizeof(type)))
#define pa_xstrdup strdup
#define pa_xfree free
#define pa_log_warn(...) ((void)0)
typedef struct { unsigned value; } pa_cvolume;
typedef struct pa_time_event { int value; } pa_time_event;
typedef struct pa_mainloop_api { void (*time_free)(pa_time_event*); } pa_mainloop_api;
typedef struct { pa_mainloop_api *mainloop; } pa_core;
typedef struct pa_sink {
void *userdata; int state; bool muted; unsigned n_volume_steps, index;
struct { unsigned channels; } sample_spec;
pa_cvolume real_volume, reference_volume, soft_volume;
pa_core *core;
void (*set_volume)(struct pa_sink*), (*set_mute)(struct pa_sink*);
} pa_sink;
struct android_volume;
struct userdata { struct android_volume *android_volume; };
static int restarts, frees;
static char *pa_sprintf_malloc(const char *format, ...) {
va_list ap; va_start(ap,format); char *result; assert(vasprintf(&result,format,ap)>=0); va_end(ap); return result;
}
static void pa_cvolume_set(pa_cvolume *volume, unsigned channels, unsigned value) { volume->value=value; }
static unsigned pa_cvolume_max(const pa_cvolume *volume) { return volume->value; }
static void pa_cvolume_reset(pa_cvolume *volume, unsigned channels) { volume->value=PA_VOLUME_NORM; }
static bool pa_cvolume_equal(const pa_cvolume *a, const pa_cvolume *b) { return a->value==b->value; }
static void pa_sink_volume_changed(pa_sink *sink, const pa_cvolume *volume) { sink->real_volume=*volume; }
static void pa_sink_mute_changed(pa_sink *sink, bool muted) { sink->muted=muted; }
static void pa_sink_set_set_volume_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_volume=callback; }
static void pa_sink_set_set_mute_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_mute=callback; }
static void pa_subscription_post(pa_core *core, int event, unsigned index) {}
static uint64_t pa_rtclock_now(void) { return 0; }
static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; }
static pa_time_event *pa_core_rttime_new(pa_core *core, uint64_t time,
void (*callback)(pa_mainloop_api*,pa_time_event*,const struct timeval*,void*), void *userdata) {
return calloc(1,sizeof(pa_time_event));
}
static void free_timer(pa_time_event *event) { frees++; free(event); }
#include "android-volume.h"
static void state(const char *directory, const char *text) {
char *path=pa_sprintf_malloc("%s/volume.state",directory);
FILE *f=fopen(path,"w"); assert(f); fputs(text,f); fclose(f); free(path);
}
int main(int argc, char **argv) {
pa_mainloop_api api={.time_free=free_timer}; pa_core core={.mainloop=&api};
struct userdata userdata={0};
pa_sink sink={.userdata=&userdata,.core=&core,.state=1,.sample_spec={.channels=2},.real_volume={PA_VOLUME_NORM}};
userdata.android_volume=android_volume_new(&sink,argv[1]);
assert(userdata.android_volume && userdata.android_volume->timer && sink.set_volume && sink.set_mute);
state(argv[1],"invalid\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1);
state(argv[1],"3 15 1\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==3*PA_VOLUME_NORM/15 && sink.muted && sink.n_volume_steps==16);
assert(sink.soft_volume.value==PA_VOLUME_NORM && restarts==2);
sink.real_volume.value=2*PA_VOLUME_NORM/3; sink.set_volume(&sink);
char *request=pa_sprintf_malloc("%s/volume.request",argv[1]);
FILE *f=fopen(request,"r"); unsigned level; assert(f && fscanf(f,"%u",&level)==1 && level==10); fclose(f); free(request);
android_volume_free(userdata.android_volume); assert(frees==1);
return 0;
}
'''
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "pulsecore").mkdir()
for name in ("core-rtclock.h", "core-subscribe.h"):
(root / "pulsecore" / name).touch()
source = root / "test.c"
source.write_text(harness)
binary = root / "test"
subprocess.run(["cc", "-std=c11", "-I", str(root), "-I", str(header.parent),
str(source), "-o", str(binary)], check=True, capture_output=True)
subprocess.run([str(binary), str(root)], check=True, capture_output=True)
+171
View File
@@ -0,0 +1,171 @@
import json
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
class DeviceControlsTest(unittest.TestCase):
def test_sync_controls_queued_notifications_are_processed_without_another_frame(self):
with tempfile.TemporaryDirectory() as directory:
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1}))
helper = LIVE["Helper"]("/steam", 0)
helper.controls_installed = True
page = mock.Mock(events=[])
page.ws.pending.return_value = False
helper.page = page
payload = json.dumps({"id": 1, "options": {"strTitle": "Pick a file"}})
def evaluate(expression):
for name, value in [(LIVE["BRIGHTNESS_BINDING"], "0.4"), (LIVE["FILE_BINDING"], payload)]:
page.events.append({"method": "Runtime.bindingCalled", "params": {"name": name, "payload": value}})
return True
def drain():
events, page.events = page.events, []
return events
page.evaluate.side_effect = evaluate
page.drain.side_effect = drain
helper.reconcile = mock.Mock()
helper.ensure_tools = mock.Mock(side_effect=[None, StopIteration])
helper.open_chooser = mock.Mock()
watcher = mock.Mock()
watcher.fileno.return_value = -1
watcher.changed.return_value = False
globals_ = LIVE["Helper"].serve.__globals__
with mock.patch.dict(globals_, {"CONTROLS_DIR": directory,
"brightness_request": lambda value: LIVE["brightness_request"](value, directory)}), \
mock.patch.dict(globals_["COMPAT"], {"state_path": lambda name: str(Path(directory, name))}), \
mock.patch.object(globals_["select"], "select", return_value=([], [], [])) as select_:
with self.assertRaises(StopIteration):
helper.serve(watcher)
self.assertEqual(float(Path(directory, "brightness.request").read_text()), 0.4)
helper.open_chooser.assert_called_once_with(payload)
self.assertEqual(page.events, [])
select_.assert_not_called()
def test_native_brightness_notifications_do_not_echo_android_readback(self):
harness = r"""
const assert = require('assert');
globalThis.window = globalThis;
const requests = [], callbacks = [];
const timers = [];
globalThis.setTimeout = callback => timers.push(callback);
let current = 1;
window.droiddeckBrightnessChanged = value => requests.push(Number(value));
globalThis.SteamClient = { System: { Display: {
RegisterForBrightnessChanges(cb) { callbacks.push(cb); cb({ flBrightness: 1 }); return {}; },
SetBrightness(value) {
if (current === value) return;
current = value;
callbacks.forEach(cb => cb({ flBrightness: value }));
}
} } };
const script = require('fs').readFileSync(process.argv[2], 'utf8');
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
const bridge = window.__droiddeckBrightness;
bridge.set(0.5);
bridge.set(0.5);
assert.deepStrictEqual(requests, []);
callbacks.forEach(cb => cb({ flBrightness: 0.8 }));
assert.deepStrictEqual(requests, [0.8]);
bridge.set(0.7992126);
assert.deepStrictEqual(requests, [0.8]);
for (const value of [NaN, Infinity, -1, 2, '0.5']) callbacks.forEach(cb => cb({ flBrightness: value }));
assert.deepStrictEqual(requests, [0.8]);
assert.strictEqual(callbacks.length, 1);
SteamClient.System.Display.SetBrightness = value => callbacks.forEach(cb => cb({ flBrightness: value + 0.1 }));
bridge.set(0.3);
assert.deepStrictEqual(requests, [0.8]);
callbacks.forEach(cb => cb({ flBrightness: 0.6 }));
assert.deepStrictEqual(requests, [0.8, 0.6]);
SteamClient.System.Display.SetBrightness = () => {};
bridge.set(0.65);
timers.forEach(callback => callback());
callbacks.forEach(cb => cb({ flBrightness: 0.7 }));
assert.deepStrictEqual(requests, [0.8, 0.6, 0.7]);
"""
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "bridge.js"
script.write_text(LIVE["BRIGHTNESS_JS"])
test = Path(directory) / "test.js"
test.write_text(harness)
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_requests_reject_nonfinite_and_out_of_range_values(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "brightness.request"
for value in ["NaN", "Infinity", "-0.1", "1.1", "invalid", None]:
LIVE["brightness_request"](value, directory)
self.assertFalse(path.exists())
LIVE["brightness_request"]("0.4", directory)
self.assertEqual(float(path.read_text()), 0.4)
def test_failed_request_revision_republishes_the_actual_brightness(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
helper = LIVE["Helper"]("/steam", 0)
calls = []
helper.controls_installed = True
helper.page = type("Page", (), {"evaluate": lambda self, expression: calls.append(expression) or True})()
path = Path(directory) / "state.json"
path.write_text(json.dumps({"brightness": 0.5, "revision": 1}))
helper.sync_controls()
helper.sync_controls()
self.assertEqual(len(calls), 1)
path.write_text(json.dumps({"brightness": 0.5, "revision": 2}))
helper.sync_controls()
self.assertEqual(len(calls), 2)
finally:
globals_["CONTROLS_DIR"] = previous
def test_display_bridge_retries_binding_and_install_before_caching_state(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1}))
calls, installs, writes = [], ["unavailable", "installed", "present"], []
class Page:
present = True
def call(self, method, params):
calls.append((method, params))
def evaluate(self, expression):
if expression == LIVE["BRIGHTNESS_JS"]:
return installs.pop(0)
writes.append(expression)
return self.present
helper = LIVE["Helper"]("/steam", 0)
helper.page = Page()
helper.sync_controls()
self.assertIsNone(helper.controls_state)
self.assertFalse(writes)
helper.sync_controls()
helper.sync_controls()
self.assertEqual(len(calls), 2)
self.assertEqual(len(writes), 1)
self.assertEqual(calls[1], ("Runtime.addBinding", {"name": LIVE["BRIGHTNESS_BINDING"]}))
helper.page.present = False
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.7, "revision": 2}))
helper.sync_controls()
self.assertIsNone(helper.controls_state)
self.assertFalse(helper.controls_installed)
helper.page.present = True
helper.sync_controls()
self.assertEqual(len(calls), 3)
self.assertEqual(helper.controls_state["brightness"], 0.7)
finally:
globals_["CONTROLS_DIR"] = previous
if __name__ == "__main__":
unittest.main()