Merge current main into PR #1317

This commit is contained in:
Kurt Himebauch committed 2026-10-22 12:13:54 -04:00
commit e8a8de1b22
161 files changed
+7157 -479

No files matched your search

+6 -4
View File
@@ -22,9 +22,11 @@ through `kwin_wayland_wrapper`. KWin composites in software (QPainter) - the Adr
DRM device - so games and emulators from the menu go through `droiddeck-gpu`, and Steam goes back
to the app as a Steam session.
`build-kwin.sh` builds KWin 6.7.5's Wayland executable and library on a native ARM64 runner, using a disposable
Arch Linux ARM chroot with every build package signature-checked. The KDE source tarball is pinned
by SHA-256 (the same digest in Arch's KWin PKGBUILD); `patches/0001-respect-nested-desktop-scale.patch`
`kwin.env` pins the KWin version shared by the build and packaging jobs. `build-kwin.sh` builds that version's
Wayland executable and library on a native ARM64 runner, using a disposable
Arch Linux ARM chroot with every build package signature-checked. It matches the current KWin package
in Arch Linux ARM even when that repository trails KDE's latest release. The source tarball is pinned
by SHA-256 from KDE's official source inventory; `patches/0001-respect-nested-desktop-scale.patch`
lets Display Settings control the inner desktop scale independently of the outer window size.
It keeps layer sizes, pointer/touch coordinates and the cursor in the same physical pixels.
The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop script supplies.
@@ -32,7 +34,7 @@ The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop sc
The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest
comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch,
executable, library and build package hashes. Corresponding source is
https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz plus the patch in this repository.
https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz plus the patch in this repository.
The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips
its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes.
+8 -3
View File
@@ -3,8 +3,9 @@ set -euo pipefail
out=$(realpath -m "${1:?out dir}")
here=$(cd "$(dirname "$0")" && pwd)
[ "$(uname -m)" = aarch64 ] || { echo 'KWin needs a native aarch64 runner' >&2; exit 1; }
version=6.7.5
source_sha=6baa910b732d93c48c90f9c1cc685cc93d0b8de0cdf138c24192c045bc3a48e2
source "$here/kwin.env"
version=$DESKTOP_KWIN_VERSION
source_sha=4bfaf31e29a8f9fdf231dc3bbb9b09b0ce07cae9fee7a01cfc86425ece796258
mirror=https://fl.us.mirror.archlinuxarm.org/aarch64
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
work=$(mktemp -d)
@@ -18,7 +19,11 @@ for repo in core extra alarm; do
done
touch "$work/runtime.txt"
python3 "$here/closure.py" "$work/db" "$work/runtime.txt" "$here/kwin-build-seeds.txt" > "$work/packages.txt"
grep -Eq '^extra/kwin-6\.7\.5-[0-9]+-aarch64\.pkg\.tar\.' "$work/packages.txt"
kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/packages.txt")
case $kwin_package in
"extra/kwin-$version"-[0-9]*-aarch64.pkg.tar.*) ;;
*) echo "KWin package $kwin_package does not match source KWin $version" >&2; exit 1 ;;
esac
export work mirror builder here
download() {
local entry=$1 sum=$2 file=${1#*/}
+7 -1
View File
@@ -2,6 +2,7 @@
set -euo pipefail
out=${1:?out dir}
here=$(cd "$(dirname "$0")" && pwd)
source "$here/kwin.env"
mirror=${ALARM_MIRROR:-https://fl.us.mirror.archlinuxarm.org/aarch64}
case $mirror in https://*) ;; *) echo "ALARM_MIRROR must be https" >&2; exit 1 ;; esac
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
@@ -36,8 +37,13 @@ done < "$work/pkglist.txt"
cp -a "$here/overlay/." "$work/root/"
if [ -n "${KDE_KWIN_OVERRIDE:-}" ]; then
kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/pkglist.txt")
case $kwin_package in
"extra/kwin-$DESKTOP_KWIN_VERSION"-[0-9]*-aarch64.pkg.tar.*) ;;
*) echo "KWin package $kwin_package does not match the built KWin $DESKTOP_KWIN_VERSION" >&2; exit 1 ;;
esac
install -m 755 "$KDE_KWIN_OVERRIDE/kwin_wayland" "$work/root/usr/bin/kwin_wayland"
install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.6.7.5" "$work/root/usr/lib/libkwin.so.6.7.5"
install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.$DESKTOP_KWIN_VERSION" "$work/root/usr/lib/libkwin.so.$DESKTOP_KWIN_VERSION"
fi
if [ -d "$work/root/usr/share/locale" ]; then
+1
View File
@@ -0,0 +1 @@
DESKTOP_KWIN_VERSION=6.8.0
@@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay)
- steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme),
GPL-3.0.
- kwin_wayland: KWin 6.7.5, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
Corresponding source: https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz and
- kwin_wayland: KWin 6.8.0, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
Corresponding source: https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz and
https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches
(the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package).
@@ -1,78 +1,27 @@
--- a/src/backends/wayland/wayland_output.cpp
+++ b/src/backends/wayland/wayland_output.cpp
@@ -294,6 +294,11 @@
}
}
+qreal WaylandOutput::presentationScale() const
+{
+ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale();
+}
+
bool WaylandOutput::present(const QList<OutputLayer *> &layersToUpdate, const std::shared_ptr<OutputFrame> &frame)
{
auto cursorLayers = layersToUpdate | std::views::filter([](OutputLayer *layer) {
@@ -312,7 +317,7 @@
m_surface->attachBuffer(buffer);
m_mapped = true;
}
- m_viewport->setDestination(QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale())));
+ m_viewport->setDestination(QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale())));
m_surface->setScale(1);
// commit the subsurfaces before the main surface
for (OutputLayer *layer : layersToUpdate) {
@@ -375,9 +380,11 @@
next.enabled = props->enabled.value_or(m_state.enabled);
next.transform = props->transform.value_or(m_state.transform);
next.position = props->pos.value_or(m_state.position);
- // intentionally ignored, as it would get overwritten
- // with the fractional scale protocol anyways
- // next.scale = props->scale.value_or(m_state.scale);
+
+ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
+ next.scale = props->scale.value_or(m_state.scale);
+ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting);
+ }
next.desiredMode = props->desiredMode.value_or(m_state.desiredMode);
next.uuid = props->uuid.value_or(m_state.uuid);
next.replicationSource = props->replicationSource.value_or(m_state.replicationSource);
@@ -466,7 +473,9 @@
State next = m_state;
next.modes = {mode};
next.currentMode = mode;
- next.scale = m_pendingScale;
+ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
+ next.scale = m_pendingScale;
+ }
setState(next);
Q_EMIT m_backend->outputsQueried();
--- a/src/backends/wayland/wayland_output.h
+++ b/src/backends/wayland/wayland_output.h
@@ -93,6 +93,8 @@
void init(const QSize &pixelSize, qreal scale, bool fullscreen);
+
+ qreal presentationScale() const;
bool isReady() const;
KWayland::Client::Surface *surface() const;
WaylandCursor *cursor() const;
diff --git a/src/backends/wayland/wayland_backend.cpp b/src/backends/wayland/wayland_backend.cpp
index f43f03d..211ef09 100644
--- a/src/backends/wayland/wayland_backend.cpp
+++ b/src/backends/wayland/wayland_backend.cpp
@@ -107,8 +107,9 @@
@@ -106,16 +106,8 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Pointer *pointer, Wayla
WaylandOutput *output = m_seat->backend()->findOutput(m_pointer->enteredSurface());
Q_ASSERT(output);
const auto subsurface = m_seat->backend()->findSubSurface(m_pointer->enteredSurface());
- const QPointF absolutePos = output->position() + relativeToSurface
- + (subsurface ? subsurface->position() : QPoint());
+ const QPointF absolutePos = output->position()
+ + (relativeToSurface + (subsurface ? subsurface->position() : QPoint()))
+ * output->presentationScale() / output->scale();
- // A position in the host window is in the coordinates the panel is driven in, while
- // the compositor works in the picture as the user sees it. On a rotated display those
- // are not the same, so the position has to be turned back.
- const QPointF inPanel = relativeToSurface + (subsurface ? subsurface->position() : QPoint());
- // Exactly the size the surface is given in WaylandOutput::present(), rounding and all -
- // turning a position needs the bounds it was expressed in, and being off by the
- // rounding here shifts the pointer by a little more the further it travels.
- const QSizeF panelSize = QSize(std::round(output->modeSize().width() / output->scale()),
- std::round(output->modeSize().height() / output->scale()));
- const QPointF absolutePos = output->position() + output->transform().inverted().map(inPanel, panelSize);
+ const QPointF hostPosition = relativeToSurface + (subsurface ? subsurface->position() : QPoint());
+ const QPointF absolutePos = output->mapToOutput(hostPosition);
Q_EMIT pointerMotionAbsolute(absolutePos, std::chrono::milliseconds(time), this);
});
connect(pointer, &Pointer::buttonStateChanged, this, [this](quint32 serial, quint32 time, quint32 button, Pointer::ButtonState nativeState) {
@@ -182,7 +183,11 @@
@@ -189,7 +181,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::RelativePointer *relati
, m_relativePointer(relativePointer)
{
connect(relativePointer, &RelativePointer::relativeMotion, this, [this](const QSizeF &delta, const QSizeF &deltaNonAccelerated, quint64 timestamp) {
@@ -84,16 +33,17 @@
+ Q_EMIT pointerMotion(sizeToPoint(delta) * factor, sizeToPoint(deltaNonAccelerated) * factor, std::chrono::microseconds(timestamp), this);
});
}
@@ -199,13 +204,19 @@
@@ -206,13 +202,21 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe
connect(touch, &Touch::sequenceStarted, this, [this](TouchPoint *tp) {
auto o = m_seat->backend()->findOutput(tp->surface());
Q_ASSERT(o);
- const QPointF position = o->position() + tp->position();
+ const auto subsurface = m_seat->backend()->findSubSurface(tp->surface());
+ const QPointF position = o->position()
+ + (tp->position() + (subsurface ? subsurface->position() : QPoint()))
+ * o->presentationScale() / o->scale();
+ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint());
+ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")
+ ? o->mapToOutput(hostPosition)
+ : o->position() + tp->position();
Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this);
});
connect(touch, &Touch::pointAdded, this, [this](TouchPoint *tp) {
@@ -101,27 +51,46 @@
Q_ASSERT(o);
- const QPointF position = o->position() + tp->position();
+ const auto subsurface = m_seat->backend()->findSubSurface(tp->surface());
+ const QPointF position = o->position()
+ + (tp->position() + (subsurface ? subsurface->position() : QPoint()))
+ * o->presentationScale() / o->scale();
+ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint());
+ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")
+ ? o->mapToOutput(hostPosition)
+ : o->position() + tp->position();
Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this);
});
connect(touch, &Touch::pointRemoved, this, [this](TouchPoint *tp) {
@@ -214,7 +225,10 @@
@@ -221,7 +225,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe
connect(touch, &Touch::pointMoved, this, [this](TouchPoint *tp) {
auto o = m_seat->backend()->findOutput(tp->surface());
Q_ASSERT(o);
- const QPointF position = o->position() + tp->position();
+ const auto subsurface = m_seat->backend()->findSubSurface(tp->surface());
+ const QPointF position = o->position()
+ + (tp->position() + (subsurface ? subsurface->position() : QPoint()))
+ * o->presentationScale() / o->scale();
+ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint());
+ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")
+ ? o->mapToOutput(hostPosition)
+ : o->position() + tp->position();
Q_EMIT touchMotion(tp->id(), position, std::chrono::milliseconds(tp->time()), this);
});
}
diff --git a/src/backends/wayland/wayland_egl_backend.cpp b/src/backends/wayland/wayland_egl_backend.cpp
index 0c03222..c587db5 100644
--- a/src/backends/wayland/wayland_egl_backend.cpp
+++ b/src/backends/wayland/wayland_egl_backend.cpp
@@ -232,7 +232,9 @@ bool WaylandEglCursorLayer::endFrame(const Region &renderedDeviceRegion, const R
wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer());
Q_ASSERT(buffer);
- static_cast<WaylandOutput *>(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint());
+ auto output = static_cast<WaylandOutput *>(m_output.get());
+ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(),
+ (hotspot() / output->presentationScale()).toPoint());
EGLNativeFence releaseFence{m_backend->eglDisplayObject()};
m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor());
diff --git a/src/backends/wayland/wayland_layer.cpp b/src/backends/wayland/wayland_layer.cpp
index 311be7f..f91a3fb 100644
--- a/src/backends/wayland/wayland_layer.cpp
+++ b/src/backends/wayland/wayland_layer.cpp
@@ -95,7 +95,7 @@
@@ -95,7 +95,7 @@ void WaylandLayer::commit(PresentationMode presentationMode)
// this is a bit annoying, we need a new Wayland protocol
// to do this properly with fractional scaling. Until we
// have that, it may cause blurriness in some cases!
@@ -130,29 +99,74 @@
if (m_viewport) {
m_viewport->setSource(sourceRect());
m_viewport->setDestination(logicalTarget.size());
--- a/src/backends/wayland/wayland_qpainter_backend.cpp
+++ b/src/backends/wayland/wayland_qpainter_backend.cpp
@@ -124,7 +124,9 @@
wl_buffer *buffer = static_cast<WaylandOutput *>(m_output.get())->backend()->importBuffer(m_back->buffer());
Q_ASSERT(buffer);
- static_cast<WaylandOutput *>(m_output.get())->cursor()->update(buffer, m_back->buffer()->size() / m_output->scale(), hotspot().toPoint());
+ auto output = static_cast<WaylandOutput *>(m_output.get());
+ output->cursor()->update(buffer, m_back->buffer()->size() / output->presentationScale(),
+ (hotspot() * output->scale() / output->presentationScale()).toPoint());
m_swapchain->release(m_back);
return true;
diff --git a/src/backends/wayland/wayland_output.cpp b/src/backends/wayland/wayland_output.cpp
index 1543058..a22d974 100644
--- a/src/backends/wayland/wayland_output.cpp
+++ b/src/backends/wayland/wayland_output.cpp
@@ -314,7 +314,7 @@ std::expected<void, OutputError> WaylandOutput::present(const QList<OutputLayer
m_surface->attachBuffer(buffer);
m_mapped = true;
}
- const Rect rect(QPoint(), QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale())));
+ const Rect rect(QPoint(), QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale())));
m_xdgShellSurface->setWindowGeometry(rect);
m_viewport->setDestination(rect.size());
m_surface->setScale(1);
@@ -379,9 +379,10 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config)
next.enabled = props->enabled.value_or(m_state.enabled);
next.transform = props->transform.value_or(m_state.transform);
next.position = props->pos.value_or(m_state.position);
- // intentionally ignored, as it would get overwritten
- // with the fractional scale protocol anyways
- // next.scale = props->scale.value_or(m_state.scale);
+ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
+ next.scale = props->scale.value_or(m_state.scale);
+ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting);
+ }
next.desiredMode = props->desiredMode.value_or(m_state.desiredMode);
next.uuid = props->uuid.value_or(m_state.uuid);
next.replicationSource = props->replicationSource.value_or(m_state.replicationSource);
@@ -397,6 +398,19 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config)
setState(next);
}
--- a/src/backends/wayland/wayland_egl_backend.cpp
+++ b/src/backends/wayland/wayland_egl_backend.cpp
@@ -202,7 +202,9 @@
wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer());
Q_ASSERT(buffer);
- static_cast<WaylandOutput *>(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint());
+ auto output = static_cast<WaylandOutput *>(m_output.get());
+ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(),
+ (hotspot() / output->presentationScale()).toPoint());
EGLNativeFence releaseFence{m_backend->eglDisplayObject()};
m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor());
+qreal WaylandOutput::presentationScale() const
+{
+ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale();
+}
+
+QPointF WaylandOutput::mapToOutput(const QPointF &hostPosition) const
+{
+ const QPointF inPanel = hostPosition * presentationScale() / scale();
+ const QSizeF panelSize = QSize(std::round(modeSize().width() / scale()),
+ std::round(modeSize().height() / scale()));
+ return position() + transform().inverted().map(inPanel, panelSize);
+}
+
bool WaylandOutput::isReady() const
{
return m_ready;
@@ -472,7 +486,9 @@ void WaylandOutput::applyConfigure(const QSize &size, quint32 serial)
State next = m_state;
next.modes = {mode};
next.currentMode = mode;
- next.scale = m_pendingScale;
+ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) {
+ next.scale = m_pendingScale;
+ }
setState(next);
Q_EMIT m_backend->outputsQueried();
diff --git a/src/backends/wayland/wayland_output.h b/src/backends/wayland/wayland_output.h
index dab061b..c019577 100644
--- a/src/backends/wayland/wayland_output.h
+++ b/src/backends/wayland/wayland_output.h
@@ -92,6 +92,8 @@ public:
void init(const QSize &pixelSize, qreal scale, bool fullscreen);
+ qreal presentationScale() const;
+ QPointF mapToOutput(const QPointF &hostPosition) const;
bool isReady() const;
KWayland::Client::Surface *surface() const;
WaylandCursor *cursor() const;
+287
View File
@@ -0,0 +1,287 @@
#!/usr/bin/env bash
# Smoke test of a DroidDeck build on a real device, over plain adb (no python, no root).
#
# What it does, in order, and restores afterwards:
# 1. prints the device (model, Android, kernel, page size, SoC);
# 2. installs --apk when given and launches the app;
# 3. checks that the app starts and that nothing in the crash buffer belongs to it;
# 4. changes the display density and the window size and checks the app keeps its process
# (and does not recreate the activity that is on top);
# 5. on a foldable cycles the device state (half-opened, and with --closed also closed) through
# `cmd device_state`, then puts the original state back;
# 6. reads the newest session folder of a debug build: first frame, last frame rate, the
# memory page size and the last process exits.
#
# Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE]
# [--no-density] [--no-size] [--no-fold] [--closed]
# Exit status: 0 when no check failed, 1 when one did, 2 for a usage or device problem.
#
# Not a replacement for tools/droiddeck-scenario, which drives a game through the agent bridge;
# this covers what that does not: display changes and foldable states.
set -u
export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*'
pkg=com.droiddeck.launcher
serial=${ANDROID_SERIAL:-}
apk=
do_density=1
do_size=1
do_fold=1
do_closed=0
adb_bin=${ADB:-adb}
while [ $# -gt 0 ]; do
case $1 in
--serial) [ $# -ge 2 ] || { echo "--serial needs a value" >&2; exit 2; }; serial=$2; shift ;;
--apk) [ $# -ge 2 ] || { echo "--apk needs a value" >&2; exit 2; }; apk=$2; shift ;;
--pkg) [ $# -ge 2 ] || { echo "--pkg needs a value" >&2; exit 2; }; pkg=$2; shift ;;
--no-density) do_density=0 ;;
--no-size) do_size=0 ;;
--no-fold) do_fold=0 ;;
--closed) do_closed=1 ;;
-h|--help) sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
*) echo "unknown option: $1" >&2; exit 2 ;;
esac
shift
done
adb_cmd=("$adb_bin")
[ -n "$serial" ] && adb_cmd+=(-s "$serial")
A() {
local out rc
out=$("${adb_cmd[@]}" "$@" 2>&1); rc=$?
[ -z "$out" ] || printf '%s\n' "$out" | tr -d '\r'
return $rc
}
sh_() {
local command= arg
for arg in "$@"; do command+="'${arg//\'/\'\\\'\'}' "; done
A shell "$command"
}
pass=0 fail=0 skip=0
ok() { echo " PASS $*"; pass=$((pass + 1)); }
bad() { echo " FAIL $*"; fail=$((fail + 1)); }
note() { echo " SKIP $*"; skip=$((skip + 1)); }
head_() { printf '\n== %s\n' "$*"; }
state=$(A get-state)
if [ "$state" != "device" ]; then
echo "no authorized device (adb get-state: $state)" >&2
exit 2
fi
density_snapshot=$(sh_ wm density) || density_snapshot=
size_snapshot=$(sh_ wm size) || size_snapshot=
orig_density=$(echo "$density_snapshot" | sed -n 's/.*Physical density: \([0-9]*\).*/\1/p' | head -1)
override_density=$(echo "$density_snapshot" | sed -n 's/.*Override density: \([0-9]*\).*/\1/p' | head -1)
override_size=$(echo "$size_snapshot" | sed -n 's/.*Override size: \([0-9]*x[0-9]*\).*/\1/p' | head -1)
ds=$(sh_ cmd device_state state 2>/dev/null)
orig_state=$(echo "$ds" | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1)
pre_override=$(echo "$ds" | sed -n "s/.*Override state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1)
density_changed=0 size_changed=0 fold_changed=0
wm_override() { sed -n "s/.*Override $1: \\([0-9x]*\\).*/\\1/p" | head -1; }
restore_density() {
sh_ wm density "${override_density:-reset}" >/dev/null || return 1
local current
current=$(sh_ wm density) || return 1
echo "$current" | grep -q 'Physical density:' || return 1
[ "$(echo "$current" | wm_override density)" = "$override_density" ]
}
restore_size() {
sh_ wm size "${override_size:-reset}" >/dev/null || return 1
local current
current=$(sh_ wm size) || return 1
echo "$current" | grep -q 'Physical size:' || return 1
[ "$(echo "$current" | wm_override size)" = "$override_size" ]
}
# An override that was already in place (a test lab pins one) is put back; otherwise the request is cancelled.
restore_fold() { if [ -n "$pre_override" ]; then sh_ cmd device_state state "$pre_override" >/dev/null; else sh_ cmd device_state state reset >/dev/null; fi; }
restore() {
local failed=0
if [ "$density_changed" = 1 ]; then
if restore_density; then density_changed=0; else bad "could not restore display density"; failed=1; fi
fi
if [ "$size_changed" = 1 ]; then
if restore_size; then size_changed=0; else bad "could not restore window size"; failed=1; fi
fi
if [ "$fold_changed" = 1 ]; then
if restore_fold; then fold_changed=0; else bad "could not restore fold override"; failed=1; fi
fi
return "$failed"
}
finish() {
local status=$?
restore || status=1
printf '\n%d passed, %d failed, %d skipped\n' "$pass" "$fail" "$skip"
[ "$fail" = 0 ] || status=1
exit "$status"
}
trap finish EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
top_activity() {
sh_ dumpsys activity activities 2>/dev/null | sed -n 's/.*topResumedActivity=ActivityRecord{[^ ]* u[0-9]* \([^ ]*\) .*/\1/p' | head -1
}
app_pid() { sh_ pidof "$pkg" | awk '{print $1}'; }
app_crashes() {
local out pat
out=$(sh_ logcat -b crash -d) || return 1
pat=$(printf '%s' "$pkg" | sed 's/[.[\*^$]/\\&/g')
printf '%s\n' "$out" | grep -c -E "(Process: |Cmdline: |>>> )$pat([ ,<:]|$)" || true
}
relaunches_of() { # $1 = activity class fragment
sh_ logcat -b events -d 2>/dev/null | grep -E 'wm_(relaunch|destroy|create)_activity' | grep -c "$1"
}
head_ "Device"
echo " model $(sh_ getprop ro.product.manufacturer) $(sh_ getprop ro.product.model)"
echo " android $(sh_ getprop ro.build.version.release) (API $(sh_ getprop ro.build.version.sdk)), One UI $(sh_ getprop ro.build.version.oneui)"
echo " kernel $(sh_ uname -r)"
page=$(sh_ getconf PAGE_SIZE)
echo " page size $page"
echo " soc $(sh_ getprop ro.soc.manufacturer) $(sh_ getprop ro.soc.model) ($(sh_ getprop ro.board.platform))"
echo " gpu $(sh_ cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)"
echo " display $(sh_ wm size | tr '\n' ' ') $(sh_ wm density | tr '\n' ' ')"
[ "$page" = 4096 ] || [ "$page" = 16384 ] && ok "page size is $page" || bad "page size reads '$page'"
head_ "Install and launch"
sh_ logcat -b crash -c >/dev/null
sh_ logcat -b events -c >/dev/null
if [ -n "$apk" ]; then
r=$(A install -r -t "$apk" | tail -1)
case $r in *Success*) ok "installed $(basename "$apk")" ;; *) bad "install: $r"; exit 1 ;; esac
fi
packages=$(sh_ pm list packages "$pkg") || { echo "could not query installed packages" >&2; exit 2; }
if ! printf '%s\n' "$packages" | grep -Fxq "package:$pkg"; then echo "package $pkg is not installed" >&2; exit 2; fi
if ! launch=$(sh_ am start -n "$pkg/.MainActivity") || printf '%s\n' "$launch" | grep -q '^Error'; then
bad "could not launch $pkg/.MainActivity"
fi
sleep 6
pid=$(app_pid)
[ -n "$pid" ] && ok "process running (pid $pid)" || bad "the app has no process after launch"
t=$(top_activity)
case $t in
"$pkg"/*|*permissioncontroller*|*GrantPermissions*) ok "top activity: $t" ;;
*) bad "top activity is '$t'" ;;
esac
if c=$(app_crashes); then
[ "${c:-0}" = 0 ] && ok "nothing in the crash buffer belongs to the app" || bad "$c crash entries mention the app"
else
bad "could not read the crash buffer"
fi
if [ "$do_density" = 1 ] && [ -n "$orig_density" ]; then
head_ "Density change"
target=$((orig_density * 5 / 4))
before=$(top_activity); pid0=$(app_pid)
sh_ logcat -b events -c >/dev/null
density_changed=1
wm_status=0
sh_ wm density "$target" >/dev/null || wm_status=$?
sleep 6
applied=$(sh_ wm density) || wm_status=1
after=$(top_activity); pid1=$(app_pid)
if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override density)" != "$target" ]; then
bad "wm density failed"
else
if [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then
ok "same process after $orig_density -> $target dpi"
else
bad "process changed ($pid0 -> $pid1)"
fi
case $before in "$pkg"/*)
n=$(relaunches_of "${before#*/}")
[ "${n:-0}" = 0 ] && ok "$before was not recreated" || bad "$before was recreated ${n}x"
[ "$after" = "$before" ] && ok "same top activity after the change" || bad "top activity changed ($before -> $after)"
;; *) note "top activity was not the app ($before)" ;; esac
fi
if restore_density; then
density_changed=0
else
bad "could not restore display density"
fi
sleep 3
elif [ "$do_density" = 1 ]; then
note "could not read the original display density"
fi
if [ "$do_size" = 1 ]; then
head_ "Window size change"
phys=$(echo "$size_snapshot" | sed -n 's/.*Physical size: \([0-9]*\)x\([0-9]*\).*/\1 \2/p' | head -1)
set -- $phys
if [ -n "${1:-}" ]; then
w=$(( ($2 * 2 / 3) / 2 * 2 )); h=$1 # a narrower, taller window, like a cover screen
pid0=$(app_pid)
size_changed=1
wm_status=0
sh_ wm size "${w}x${h}" >/dev/null || wm_status=$?
sleep 6
applied=$(sh_ wm size) || wm_status=1
pid1=$(app_pid)
if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override size)" != "${w}x${h}" ]; then
bad "wm size failed"
elif [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then
ok "same process at ${w}x${h}"
else
bad "process changed ($pid0 -> $pid1)"
fi
if restore_size; then
size_changed=0
else
bad "could not restore window size"
fi
sleep 3
else
note "could not read the physical size"
fi
fi
if [ "$do_fold" = 1 ]; then
head_ "Foldable states"
states=$(sh_ cmd device_state print-states 2>/dev/null)
if ! echo "$states" | grep -q "identifier"; then
note "no device_state service (not a foldable, or not permitted)"
elif [ -z "$orig_state" ]; then
note "could not read the current device_state identifier"
else
id_of() { echo "$states" | sed -n "s/.*identifier=\([0-9]*\), name='$1'.*/\1/p" | head -1; }
half=$(id_of HALF_OPENED); closed=$(id_of CLOSED)
cycle() { # $1 name $2 id
pid0=$(app_pid)
fold_changed=1
sh_ cmd device_state state "$2" >/dev/null; sleep 8
got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=[0-9]*, name='\([A-Z_]*\)'.*/\1/p" | head -1)
pid1=$(app_pid)
[ "$got" = "$1" ] && ok "device state is $1" || note "asked for $1, committed '$got'"
[ -n "$pid1" ] && [ "$pid0" = "$pid1" ] && ok "same process in $1" || bad "process changed in $1 ($pid0 -> $pid1)"
restore_fold; sleep 6
}
if [ -n "$half" ]; then cycle HALF_OPENED "$half"; else note "no HALF_OPENED state"; fi
if [ "$do_closed" = 1 ] && [ -n "$closed" ]; then
cycle CLOSED "$closed"
note "CLOSED turns the screens off: the session pauses (Background behaviour), Resume it from the app"
fi
got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1)
[ "$got" = "$orig_state" ] && ok "device state restored ($orig_state)" || bad "device state is $got, was $orig_state"
fi
fi
head_ "Session log (debug builds)"
dir=$(sh_ run-as "$pkg" ls -t files/logs 2>/dev/null | head -1)
if [ -z "$dir" ] || echo "$dir" | grep -q -i "not debuggable\|unknown package"; then
note "no readable session folder (release build, or no session has run)"
else
echo " newest session $dir"
ev=$(sh_ run-as "$pkg" cat "files/logs/$dir/events.jsonl" 2>/dev/null)
echo "$ev" | grep -q '"frame.first"' && ok "first frame was drawn" || note "no frame.first in $dir"
echo "$ev" | grep -q '"session.failed"' && bad "session.failed: $(echo "$ev" | grep '"session.failed"' | tail -1 | cut -c1-160)"
fps=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null | grep 'last 10 s:' | tail -1 | sed 's/.*last 10 s: //' | cut -c1-70)
[ -n "$fps" ] && echo " last stats $fps"
sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null | grep -E 'Memory page size|^Kernel' | sed 's/^/ report /'
fi
[ "$fail" = 0 ]
+19
View File
@@ -66,3 +66,22 @@ library list, before anything is published.
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
- `0116-release-cursor-shm-buffers.patch` - this app: pointer cursor surfaces have no
X11/xdg window association, so routing their commits through `g_PendingCommits`
retained every old SHM buffer until the surface was destroyed. Ignore cursor-role
commits before taking the buffer lock; X11 cursor images still follow the existing
MouseCursor path. Window commits awaiting association are unchanged.
The live regression probe is `tools/tests/test_gamescope_cursor_shm.py`. Run it
inside an active Gamescope session with access to that process's `/proc` fd
directory. It submits 20 distinct SHM cursor buffers and requires at most the
current buffer to remain open, then none after surface destruction. The
`--unassigned-control` variant omits the cursor role and verifies that all 20
commits awaiting a window association remain queued until surface destruction.
Device validation (2026-10-20): the stock component retained 20/20 cursor buffers;
the patched component retained 1/20, then 0 after destruction. The unassigned
control retained 20/20 and then 0. In Backpack Battles, two batches of ten touch
drags leaked 188 and 197 SHM descriptors before the fix; the same batches added
zero after the fix (112 total descriptors before and after each batch).
@@ -0,0 +1,15 @@
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -203,6 +203,12 @@
}
void xwayland_surface_commit(struct wlr_surface *wlr_surface) {
+ // Cursor surfaces never acquire an X11/xdg window association. Keeping their
+ // commits in g_PendingCommits pins every old SHM buffer until the cursor
+ // surface is destroyed. X11 cursor images are handled by MouseCursor.
+ if ( wlr_surface->role && strcmp( wlr_surface->role->name, "wl_pointer-cursor" ) == 0 )
+ return;
+
wlr_surface->current.committed = 0;
wlserver_x11_surface_info *wlserver_x11_surface_info = get_wl_surface_info(wlr_surface)->x11_surface;
@@ -96,14 +96,14 @@ done <<<"$pairs"
want+=("vcrt"$'\t'"$VCRT_MAJOR.$VCRT_MINOR.$VCRT_BUILD")
printf -v now '%(%s)T' -1
block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" -v hive="$hive" '
{
path = $1
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
if (path == $1)
next
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
if (substr(path, 1, 10) != "Software\\\\")
if (hive != "HKEY_LOCAL_MACHINE" || substr(path, 1, 10) != "Software\\\\")
next
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", "Software\\\\Wow6432Node\\\\" substr(path, 11), now, $2
}
@@ -115,16 +115,17 @@ block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
unseed() {
local reg=$1 out
shift
out=$(mktemp "${reg%/*}/.system.reg.XXXXXX") || return 1
if printf '%s\n' "$@" | awk -F'\t' '
[ -w "$reg" ] || return 1
out=$(mktemp "${reg%/*}/.${reg##*/}.XXXXXX") || return 1
if printf '%s\n' "$@" | awk -F'\t' -v hive="$hive" '
NR == FNR {
path = $1
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
if (path == $1)
next
path = tolower(path)
drop["[" path "]" SUBSEP tolower($2)] = 1
if (substr(path, 1, 10) == "software\\\\")
if (hive == "HKEY_LOCAL_MACHINE" && substr(path, 1, 10) == "software\\\\")
drop["[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)] = 1
next
}
@@ -145,11 +146,11 @@ unseed() {
# The ledger lines whose values the registry still holds, in both views where we wrote both. A Proton
# update replaces its default_pfx system.reg but not our ledger beside it, and new prefixes copy both.
present() { awk -F'\t' '
present() { awk -F'\t' -v hive="$hive" '
NR == FNR {
path = $1
if (path != "vcrt") {
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
if (path == $1)
next
}
@@ -163,7 +164,7 @@ present() { awk -F'\t' '
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" runtime "]" SUBSEP "installed"
}
} else {
both = substr(path, 1, 10) == "Software\\\\"
both = hive == "HKEY_LOCAL_MACHINE" && substr(path, 1, 10) == "Software\\\\"
path = tolower(path)
key[n, ++need[n]] = "[" path "]" SUBSEP tolower($2)
if (both)
@@ -200,60 +201,80 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
done
declare -A regid=()
if [ ${#regs[@]} -gt 0 ]; then
users=()
for reg in "${regs[@]}"; do users+=("${reg%/*}/user.reg"); done
while IFS=$'\t' read -r id name; do
regid[$name]=$id
done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" 2>/dev/null)
done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" "${users[@]}" 2>/dev/null)
fi
for reg in "${regs[@]}"; do
seeded=${reg%/*}/.droiddeck-redists
checked=${reg%/*}/.droiddeck-redists-checked
id=${regid[$reg]:-}
for system in "${regs[@]}"; do
user=${system%/*}/user.reg
seeded=${system%/*}/.droiddeck-redists
checked=${system%/*}/.droiddeck-redists-checked
id="${regid[$system]:-}|${regid[$user]:-missing}"
prev=
[ -f "$checked" ] && read -r prev <"$checked"
legacy=${reg%/*}/.bannerlator-redists
legacy=${system%/*}/.bannerlator-redists
if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then
mv -f "$legacy" "$seeded"
fi
declare -A had=()
if [ -f "$seeded" ]; then
while IFS= read -r line; do [[ $line == *$'\t'* ]] && had[$line]=1; done <"$seeded"
fi
stale=() kept=()
for line in "${!had[@]}"; do
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
done
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
id=
had=()
for line in "${kept[@]}"; do had[$line]=1; done
printf '%s\n' "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
declare -A held=()
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg")
if [ ${#held[@]} -lt ${#had[@]} ]; then
echo "== $((${#had[@]} - ${#held[@]})) recorded redist markers are gone from $reg"
had=()
for line in "${!held[@]}"; do had[$line]=1; done
printf '%s\n' "${!had[@]}" >"$seeded"
for reg in "$system" "$user"; do
hive=HKEY_LOCAL_MACHINE
[ "$reg" == "$user" ] && hive=HKEY_CURRENT_USER
declare -A had=()
other=()
if [ -f "$seeded" ]; then
while IFS= read -r line; do
[[ $line == *$'\t'* ]] || continue
if [[ $line == "$hive\\"* ]] || { [ "$reg" == "$system" ] && [[ $line == vcrt$'\t'* ]]; }; then
had[$line]=1
else
other+=("$line")
fi
done <"$seeded"
fi
unset held
fi
missing=()
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
if [ ${#missing[@]} -eq 0 ]; then
[ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked"
continue
fi
rm -f "$checked"
dated=$(mktemp) || continue
touch -r "$reg" "$dated"
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
printf '%s\n' "${!had[@]}" "${missing[@]}" >"$seeded"
echo "== seeded redist markers into $reg"
fi
touch -r "$dated" "$reg"
rm -f "$dated"
stale=() kept=()
for line in "${!had[@]}"; do
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
done
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
id=
had=()
for line in "${kept[@]}"; do had[$line]=1; done
printf '%s\n' "${other[@]}" "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
declare -A held=()
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <([ -f "$reg" ] && printf '%s\n' "${!had[@]}" | present "$reg")
if [ ${#held[@]} -lt ${#had[@]} ]; then
echo "== $((${#had[@]} - ${#held[@]})) recorded redist markers are gone from $reg"
had=()
for line in "${!held[@]}"; do had[$line]=1; done
printf '%s\n' "${other[@]}" "${!had[@]}" >"$seeded"
fi
unset held
fi
missing=()
for line in "${want[@]}"; do
[[ $line == "$hive\\"* ]] || { [ "$reg" == "$system" ] && [[ $line == vcrt$'\t'* ]]; } || continue
[ -n "${had[$line]:-}" ] || missing+=("$line")
done
if [ ${#missing[@]} -eq 0 ]; then
[ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked"
continue
fi
[ -f "$reg" ] && [ -w "$reg" ] || continue
rm -f "$checked"
dated=$(mktemp) || continue
touch -r "$reg" "$dated"
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
printf '%s\n' "${other[@]}" "${!had[@]}" "${missing[@]}" >"$seeded"
id=
echo "== seeded redist markers into $reg"
fi
touch -r "$dated" "$reg"
rm -f "$dated"
done
done
@@ -3,7 +3,7 @@ set -u
export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
step() { echo "== STEP $(date -u +%H:%M:%S) $*"; }
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
[ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE"
@@ -182,6 +182,20 @@ SWITCH_JS = r"""
})()
""".replace("__BINDING__", SWITCH_BINDING)
SESSION_SELECT = "/usr/bin/steamos-session-select"
# Steam opens its Steam Controller welcome tour at every start while the client setting
# controller_show_ibex_tour (CMsgClientSettings field 140014) is on, and only a finished tour turns it
# off; closing it leaves it on. The app's pad is an emulated controller, so the tour never applies.
# A pending firmware update still opens Steam's updater, which checks the update priority instead.
TOUR_JS = r"""
(() => {
let key = 140014 * 8;
const bytes = [];
while (key > 127) { bytes.push((key & 127) | 128); key = Math.floor(key / 128); }
bytes.push(key, 0);
SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
return "off";
})()
"""
VR_BINDING = "droiddeckLaunchSteamVr"
VR_HELPER = "/usr/local/bin/droiddeck-steamvr"
VR_JS = r"""
@@ -528,6 +542,11 @@ class Helper:
page.call("Runtime.addBinding", {"name": BINDING})
page.call("Runtime.addBinding", {"name": VR_BINDING})
page.evaluate(VR_JS)
try:
page.evaluate(TOUR_JS)
except RuntimeError:
# The optional tour setting must not block the compat bridge.
pass
if not self.steamos:
page.call("Runtime.addBinding", {"name": SWITCH_BINDING})
page.evaluate(SWITCH_JS)
@@ -466,10 +466,12 @@ verb=$1; shift
case $verb in
getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;;
esac
""" + BL_GAME_CPUS_SETUP + """
bl_game_cpus
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then
exec /usr/local/bin/droiddeck-steamvr-game /usr/local/bin/droiddeck-fex steam "$verb" "$@"
exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
fi
exec /usr/local/bin/droiddeck-fex steam "$verb" "$@"
exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
"""
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Package pinned local community A850 drivers; never download or execute drivers."""
import argparse
import hashlib
import io
import json
import os
from pathlib import Path
import stat
import struct
import tempfile
import zipfile
ANDROID_SHA256 = '0cf849d068c875f6c469380ca1f74da1f757575bce53d4ef9c1f6d38677cbe8b'
LINUX_SHA256 = '40fc59506620001531b9bdd1c9152e104c6fb1f4c07773c4743b9d70deb87eec'
LIBRARY = 'libvulkan_freedreno.so'
VERSION = '20261012-a850exp1'
SOURCE = 'https://github.com/Droid-Deck/DroidDeck/issues/342'
README = f'''# Adreno 850 community experimental
Manual opt-in experiment for DroidDeck; not native Adreno 850 support.
Source: community attachments to {SOURCE}
Android original: AdrenoTools-A850-experimental.zip, SHA256 {ANDROID_SHA256}
Linux original: A850-experimental.zip, SHA256 {LINUX_SHA256}
These community binaries are patched to treat Adreno 850 as Adreno 840.
They have not been validated on the target phone by this project. They may
black-screen, hang, glitch, or fail to boot. They do not establish native 850
support. Import and select this bundle manually; global auto selection is
unchanged. Use sysmem mode as advised in the original Linux metadata.
Both original meta.json files, libraries, and Linux ICD JSON are preserved
byte-for-byte. No drivers are downloaded, executed, or rebuilt by this tool.
'''
NOTICE = f'''Community experimental binaries, distributed without a compatibility guarantee.
Original author attribution and release descriptions are in android/meta.json
and linux/meta.json. The412Banner is the original driver author; the community
attachment describes an experimental binary patch. Source: {SOURCE}
This wrapper makes no new license grant for the enclosed third-party binaries.
'''
def validate_elf(data, platform):
if (len(data) < 64 or data[:6] != b'\x7fELF\x02\x01'
or struct.unpack_from('<H', data, 18)[0] != 183):
raise ValueError(f'{platform}: expected ELF64 little-endian AArch64 library')
if platform == 'linux' and b'libc.so.6\x00' not in data:
raise ValueError('linux: expected glibc library')
if platform == 'android' and b'libc.so.6\x00' in data:
raise ValueError('android: glibc library is not an AdrenoTools driver')
def read_driver(path, platform, expected_hash):
original = Path(path).read_bytes()
if hashlib.sha256(original).hexdigest() != expected_hash:
raise ValueError(f'{platform}: SHA256 mismatch; only the pinned issue #342 attachment is accepted')
allowed = {'meta.json', LIBRARY}
if platform == 'linux':
allowed.add('freedreno_icd.aarch64.json')
with zipfile.ZipFile(io.BytesIO(original)) as archive:
entries = archive.infolist()
names = [entry.filename for entry in entries]
if len(names) != len(set(names)) or set(names) != allowed:
raise ValueError(f'{platform}: expected only {sorted(allowed)}; unsafe, extra or missing entries')
for entry in entries:
mode = entry.external_attr >> 16
if entry.is_dir() or stat.S_IFMT(mode) not in (0, stat.S_IFREG) or entry.flag_bits & 1:
raise ValueError(f'{platform}: entry must be an unencrypted regular file')
files = {name: archive.read(name) for name in names}
meta = json.loads(files['meta.json'])
if not isinstance(meta, dict):
raise ValueError(f'{platform}: meta.json must be an object')
if platform == 'android' and meta.get('libraryName') != LIBRARY:
raise ValueError('android: incorrect meta.json libraryName')
if platform == 'linux':
if meta.get('libc') != 'glibc' or meta.get('kind') != 'linux-vulkan-icd':
raise ValueError('linux: incorrect meta.json libc/kind')
icd = json.loads(files['freedreno_icd.aarch64.json'])
if (not isinstance(icd, dict) or not isinstance(icd.get('ICD'), dict)
or icd['ICD'].get('library_path') != './' + LIBRARY):
raise ValueError('linux: incorrect ICD library_path')
validate_elf(files[LIBRARY], platform)
return files
def prepare_bundle(android, linux, output):
android, linux, output = map(Path, (android, linux, output))
for source in (android, linux):
if source.resolve() == output.resolve() or (output.exists() and source.samefile(output)):
raise ValueError('output must differ from both input archives')
files = {}
for platform, source, digest in (('android', android, ANDROID_SHA256), ('linux', linux, LINUX_SHA256)):
files.update({f'{platform}/{name}': data for name, data in read_driver(source, platform, digest).items()})
manifest = {'package': 'Adreno 850 community experimental', 'version': VERSION, 'tag': VERSION,
'drivers': {'android': {'path': 'android'}, 'linux': {'path': 'linux'}}}
files['manifest.json'] = (json.dumps(manifest, indent=2, sort_keys=True) + '\n').encode()
files['README.md'] = README.encode()
files['NOTICE'] = NOTICE.encode()
temporary = None
try:
with tempfile.NamedTemporaryFile(dir=output.parent, prefix='.' + output.name + '.', delete=False) as target:
temporary = Path(target.name)
with zipfile.ZipFile(target, 'w', compression=zipfile.ZIP_STORED) as archive:
for name, data in sorted(files.items()):
info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
info.create_system = 3
info.external_attr = (stat.S_IFREG | 0o644) << 16
archive.writestr(info, data)
target.flush()
os.fsync(target.fileno())
os.replace(temporary, output)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
return output
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--android', type=Path, required=True, help='Original AdrenoTools-A850-experimental.zip')
parser.add_argument('--linux', type=Path, required=True, help='Original A850-experimental.zip')
parser.add_argument('--output', type=Path, required=True, help='Destination DroidDeck DriverBundle zip')
args = parser.parse_args()
try:
result = prepare_bundle(args.android, args.linux, args.output)
except (OSError, ValueError, zipfile.BadZipFile, RuntimeError) as error:
parser.exit(1, f'error: {error}\n')
print(f'Created {result} (manual opt-in; experimental, no target-phone validation)')
if __name__ == '__main__':
main()
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
import os
from pathlib import Path
import subprocess
import sys
from check_authorship import BOT, COAUTHOR, check_revision
def main():
hook, *args = sys.argv[1:]
payload = sys.stdin.buffer.read() if hook == "pre-push" else None
if hook == "pre-push":
checked = set()
for line in payload.decode().splitlines():
local_ref, local_sha, _, _ = line.split()
if local_sha == "0" * 40 or local_sha in checked:
continue
checked.add(local_sha)
_, errors = check_revision(local_sha)
if errors:
print("\n".join(errors), file=sys.stderr)
return 1
else:
identity = subprocess.check_output(["git", "var", "GIT_AUTHOR_IDENT"], text=True)
if BOT.search(identity):
print("Bot commit author is forbidden: " + identity.strip(), file=sys.stderr)
return 1
message = Path(args[0])
original = message.read_text(encoding="utf-8")
cleaned = "".join(line for line in original.splitlines(keepends=True)
if not (COAUTHOR.match(line) and BOT.search(line)))
if cleaned != original:
message.write_text(cleaned, encoding="utf-8")
print("Removed bot co-author trailers; human credits preserved.", file=sys.stderr)
legacy = Path(__file__).with_name("legacy-" + hook)
if legacy.exists() and os.access(legacy, os.X_OK):
return subprocess.run([str(legacy), *args], input=payload).returncode
return 0
if __name__ == "__main__":
sys.exit(main())
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Reject bot authors and bot co-author trailers without executing reviewed code."""
import argparse
import json
import re
import subprocess
import sys
BOT = re.compile(
r"Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|"
r"Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\]|github-actions|"
r"dependabot|renovate(?:\[bot\])?",
re.IGNORECASE,
)
COAUTHOR = re.compile(r"^\s*Co-authored-by\s*:", re.IGNORECASE)
def commit_violations(commit, raw):
header, separator, message = raw.partition(b"\n\n")
if not separator:
return [f"{commit}: invalid commit object"]
authors = [line[7:] for line in header.splitlines() if line.startswith(b"author ")]
if len(authors) != 1:
return [f"{commit}: expected one author"]
identity = authors[0].decode("utf-8", errors="replace")
errors = []
if BOT.search(identity):
errors.append(f"{commit}: bot author: {identity}")
for line in message.decode("utf-8", errors="replace").splitlines():
if COAUTHOR.match(line) and BOT.search(line):
errors.append(f"{commit}: bot co-author: {line.strip()}")
return errors
def event_violations(event):
pr = event.get("pull_request", {})
user = pr.get("user", {})
errors = []
if user.get("type") == "Bot" or BOT.search(user.get("login", "")):
errors.append("pull request: bot authorship is forbidden")
for field in ("title", "body"):
for line in (pr.get(field) or "").splitlines():
if COAUTHOR.match(line) and BOT.search(line):
errors.append(f"pull request {field}: bot co-author trailer")
return errors
def check_revision(revision):
commits = subprocess.check_output(["git", "rev-list", revision], text=True).splitlines()
errors = []
with subprocess.Popen(["git", "cat-file", "--batch"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process:
for commit in commits:
process.stdin.write((commit + "\n").encode("ascii"))
process.stdin.flush()
descriptor = process.stdout.readline().split()
if len(descriptor) != 3 or descriptor[1] != b"commit":
raise RuntimeError(f"Cannot read commit {commit}")
size = int(descriptor[2])
raw = process.stdout.read(size)
if len(raw) != size or process.stdout.read(1) != b"\n":
raise RuntimeError(f"Truncated commit {commit}")
errors.extend(commit_violations(commit, raw))
process.stdin.close()
if process.wait() != 0:
raise RuntimeError("git cat-file failed")
return commits, errors
def main():
parser = argparse.ArgumentParser()
parser.add_argument("revision")
parser.add_argument("--event")
args = parser.parse_args()
commits, errors = check_revision(args.revision)
if args.event:
with open(args.event, encoding="utf-8") as source:
errors.extend(event_violations(json.load(source)))
for error in errors:
print(f"::error::{error}", file=sys.stderr)
if errors:
return 1
print(f"Human authorship verified for {len(commits)} commits.")
return 0
if __name__ == "__main__":
sys.exit(main())
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Install shared worktree hooks while preserving existing executable hooks."""
from pathlib import Path
import shutil
import subprocess
MARKER = "# DroidDeck human authorship hook"
def install():
common = Path(subprocess.check_output(["git", "rev-parse", "--git-common-dir"], text=True).strip()).resolve()
configured = subprocess.run(["git", "config", "--get", "core.hooksPath"], capture_output=True, text=True)
hooks = Path(configured.stdout.strip()).resolve() if configured.returncode == 0 else common / "hooks"
target = common / "authorship-hooks"
hooks.mkdir(parents=True, exist_ok=True)
target.mkdir(parents=True, exist_ok=True)
for name in ("check_authorship.py", "authorship_hook.py"):
shutil.copyfile(Path(__file__).with_name(name), target / name)
for name in ("prepare-commit-msg", "commit-msg", "pre-push"):
path = hooks / name
if path.exists() and MARKER not in path.read_text(errors="replace"):
legacy = target / ("legacy-" + name)
if legacy.exists():
raise RuntimeError(f"Refusing to replace existing saved hook: {legacy}")
shutil.copy2(path, legacy)
path.write_text(
'#!/bin/sh\n' + MARKER + '\n'
'exec python3 "$(git rev-parse --git-common-dir)/authorship-hooks/authorship_hook.py" '
+ name + ' "$@"\n'
)
path.chmod(0o755)
print(f"Human authorship hooks installed in {hooks}")
if __name__ == "__main__":
install()
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Publish the APK result only after trusted source and metadata validation."""
import json
import os
import subprocess
from urllib.parse import urlencode
from check_authorship import check_revision, event_violations
def api(path, *args):
return json.loads(subprocess.check_output(["gh", "api", path, *args], text=True))
def compilation_state(run, jobs):
for job in jobs:
if job["name"] in ("Compile and test APK", "Build APK"):
if job["status"] != "completed":
return "pending"
return "success" if job["conclusion"] == "success" else "failure"
return "failure" if run["status"] == "completed" else "pending"
def fetch_source(ref, sha):
subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True)
fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip()
if fetched != sha:
raise RuntimeError("Pull request changed while validating")
def documentation_only(sha):
base = subprocess.check_output(["git", "merge-base", "origin/main", sha], text=True).strip()
paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", base, sha]).split(b"\0")
return all(path.endswith(b".md") or path in (b"LICENSE", b".gitignore") for path in paths if path)
def main():
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as source:
event = json.load(source)
repo = os.environ["GITHUB_REPOSITORY"]
event_name = os.environ["GITHUB_EVENT_NAME"]
pr_number = event.get("number") if event_name == "pull_request_target" else None
if event_name == "workflow_dispatch":
pr_number = int(event.get("inputs", {}).get("pr_number") or 0)
run = event.get("workflow_run", {})
expected = event.get("pull_request", {}).get("head", {}).get("sha")
if event_name == "workflow_run":
expected = run["head_sha"]
if run["event"] == "pull_request":
prs = api(f"repos/{repo}/commits/{expected}/pulls")
pr_number = next((pr["number"] for pr in prs
if pr["state"] == "open" and pr["head"]["sha"] == expected), None)
if pr_number is None:
print("Ignoring a superseded or closed pull request build")
return
elif run["head_branch"] != event["repository"]["default_branch"]:
return
if pr_number:
pr = api(f"repos/{repo}/pulls/{pr_number}")
sha = pr["head"]["sha"]
if pr["state"] != "open" or (expected and sha != expected):
print("Ignoring a superseded or closed pull request event")
return
ref = f"refs/pull/{pr_number}/head"
source_event = "pull_request"
else:
pr = None
sha = expected or event.get("after") or os.environ["GITHUB_SHA"]
ref = sha
source_event = "push"
state = "failure"
description = "APK source validation failed"
target = f"https://github.com/{repo}/actions/runs/{os.environ['GITHUB_RUN_ID']}"
try:
fetch_source(ref, sha)
commits, errors = check_revision(sha)
if pr:
errors.extend(event_violations({"pull_request": pr}))
if errors:
raise RuntimeError("\n".join(errors))
print(f"Source and metadata validated for {len(commits)} commits")
if pr and documentation_only(sha):
state = "success"
description = "Source validated; no APK source changes"
return
query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20})
runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"]
runs = [item for item in runs if item["head_sha"] == sha]
if runs:
latest = max(runs, key=lambda item: item["id"])
jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"]
state = compilation_state(latest, jobs)
target = latest["html_url"]
else:
state = "pending"
description = {"pending": "Source validated; awaiting APK compilation",
"success": "Source validation and APK compilation passed",
"failure": "APK compilation failed"}[state]
finally:
api(f"repos/{repo}/statuses/{sha}", "--method", "POST",
"-f", "context=Build APK", "-f", f"state={state}",
"-f", f"description={description}", "-f", f"target_url={target}")
if __name__ == "__main__":
main()
+164
View File
@@ -0,0 +1,164 @@
import hashlib
import importlib.util
import json
from pathlib import Path
import struct
import stat
import tempfile
import unittest
from unittest import mock
import zipfile
spec = importlib.util.spec_from_file_location(
'prepare_a850_driver_bundle', Path(__file__).resolve().parents[1] / 'prepare_a850_driver_bundle.py')
prepare = importlib.util.module_from_spec(spec)
spec.loader.exec_module(prepare)
class A850BundleTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.android = self.root / 'android.zip'
self.linux = self.root / 'linux.zip'
self.output = self.root / 'bundle.zip'
self.android_files = self.files('android')
self.linux_files = self.files('linux')
self.write(self.android, self.android_files)
self.write(self.linux, self.linux_files)
def files(self, platform):
elf = bytearray(64)
elf[:6] = b'\x7fELF\x02\x01'
struct.pack_into('<H', elf, 18, 183)
elf += b'libc.so.6\x00' if platform == 'linux' else b'libc.so\x00'
meta = ({'libc': 'glibc', 'kind': 'linux-vulkan-icd'} if platform == 'linux'
else {'libraryName': prepare.LIBRARY})
files = {'meta.json': json.dumps(meta).encode(), prepare.LIBRARY: bytes(elf)}
if platform == 'linux':
files['freedreno_icd.aarch64.json'] = json.dumps({'ICD': {'library_path': './' + prepare.LIBRARY}}).encode()
return files
def write(self, path, files):
with zipfile.ZipFile(path, 'w') as archive:
for name, data in files.items():
archive.writestr(name, data)
def pinned_fixture(self):
return mock.patch.multiple(prepare,
ANDROID_SHA256=hashlib.sha256(self.android.read_bytes()).hexdigest(),
LINUX_SHA256=hashlib.sha256(self.linux.read_bytes()).hexdigest())
def test_manifest_roundtrip_preserves_both_original_halves_and_is_deterministic(self):
with self.pinned_fixture():
prepare.prepare_bundle(self.android, self.linux, self.output)
first = self.output.read_bytes()
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(first, self.output.read_bytes())
with zipfile.ZipFile(self.output) as archive:
manifest = json.loads(archive.read('manifest.json'))
self.assertEqual('Adreno 850 community experimental', manifest['package'])
self.assertEqual('20261012-a850exp1', manifest['version'])
self.assertEqual(manifest['version'], manifest['tag'])
for platform, originals in (('android', self.android_files), ('linux', self.linux_files)):
directory = manifest['drivers'][platform]['path']
self.assertEqual(platform, directory)
for name, data in originals.items():
self.assertEqual(data, archive.read(directory + '/' + name))
self.assertIn(b'not native Adreno 850 support', archive.read('README.md'))
self.assertIn(b'issues/342', archive.read('NOTICE'))
def test_hash_mismatch_refuses_and_preserves_old_output(self):
self.output.write_bytes(b'previous bundle')
with self.assertRaisesRegex(ValueError, 'SHA256 mismatch'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'previous bundle', self.output.read_bytes())
def test_unsafe_extra_and_missing_entries_refused_before_output_write(self):
for entry in ('../escape', '/absolute', 'sub/../meta.json', 'sub\\meta.json', 'extra.so', None):
with self.subTest(entry=entry):
files = self.android_files.copy()
if entry is None:
files.pop(prepare.LIBRARY)
else:
files[entry] = b'unexpected'
self.write(self.android, files)
self.output.write_bytes(b'old')
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'unsafe, extra or missing'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'old', self.output.read_bytes())
def test_bad_linux_half_does_not_replace_output(self):
self.linux_files['meta.json'] = b'{"libc":"bionic","kind":"linux-vulkan-icd"}'
self.write(self.linux, self.linux_files)
self.output.write_bytes(b'old')
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'libc/kind'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'old', self.output.read_bytes())
def test_bad_android_library_name_refused(self):
self.android_files['meta.json'] = b'{"libraryName":"../evil.so"}'
self.write(self.android, self.android_files)
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'libraryName'):
prepare.prepare_bundle(self.android, self.linux, self.output)
def test_wrong_elf_class_endian_architecture_and_libc_refused(self):
original = self.linux_files[prepare.LIBRARY]
for offset, replacement in ((4, 1), (5, 2), (18, 62)):
elf = bytearray(original)
elf[offset] = replacement
with self.subTest(offset=offset), self.assertRaisesRegex(ValueError, 'ELF64'):
prepare.validate_elf(elf, 'linux')
with self.assertRaisesRegex(ValueError, 'glibc'):
prepare.validate_elf(self.android_files[prepare.LIBRARY], 'linux')
with self.assertRaisesRegex(ValueError, 'AdrenoTools'):
prepare.validate_elf(original, 'android')
def test_output_cannot_overwrite_either_input_or_alias(self):
for source in (self.android, self.linux):
with self.subTest(source=source), self.assertRaisesRegex(ValueError, 'differ'):
prepare.prepare_bundle(self.android, self.linux, source)
alias = self.root / 'alias.zip'
alias.symlink_to(self.android)
with self.assertRaisesRegex(ValueError, 'differ'):
prepare.prepare_bundle(self.android, self.linux, alias)
def test_duplicate_and_symlink_entries_refused(self):
for duplicate in (True, False):
with self.subTest(duplicate=duplicate):
with zipfile.ZipFile(self.android, 'w') as archive:
for name, data in self.android_files.items():
info = zipfile.ZipInfo(name)
if not duplicate and name == prepare.LIBRARY:
info.create_system = 3
info.external_attr = (stat.S_IFLNK | 0o777) << 16
archive.writestr(info, data)
if duplicate:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
archive.writestr('meta.json', b'{}')
with self.pinned_fixture(), self.assertRaises(ValueError):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertFalse(self.output.exists())
def test_malformed_icd_refused(self):
for icd in ({'ICD': []}, {'ICD': {'library_path': '../evil.so'}}):
with self.subTest(icd=icd):
self.linux_files['freedreno_icd.aarch64.json'] = json.dumps(icd).encode()
self.write(self.linux, self.linux_files)
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'ICD library_path'):
prepare.prepare_bundle(self.android, self.linux, self.output)
def test_failed_replace_cleans_temporary_and_preserves_previous_output(self):
self.output.write_bytes(b'old')
with self.pinned_fixture(), mock.patch.object(prepare.os, 'replace', side_effect=OSError('fixture failure')):
with self.assertRaisesRegex(OSError, 'fixture failure'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'old', self.output.read_bytes())
self.assertEqual([], list(self.root.glob('.bundle.zip.*')))
if __name__ == '__main__':
unittest.main()
+83
View File
@@ -0,0 +1,83 @@
import importlib.util
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
path = Path(__file__).resolve().parents[1] / "release/check_authorship.py"
spec = importlib.util.spec_from_file_location("check_authorship", path)
check = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check)
class AuthorshipTest(unittest.TestCase):
def commit(self, author="Human Contributor <human@example.com>", message="Fix a bug\n"):
return (f"tree {'0' * 40}\nauthor {author} 1 +0000\n"
"committer GitHub <noreply@github.com> 1 +0000\n\n" + message).encode()
def test_bot_primary_author_is_rejected_without_a_trailer(self):
for author in ("OpenAI Codex <codex@openai.com>", "Claude <noreply@anthropic.com>",
"github-actions[bot] <actions@example.com>"):
with self.subTest(author=author):
self.assertTrue(check.commit_violations("abc", self.commit(author=author)))
def test_bot_trailers_are_rejected_even_after_human_trailers(self):
message = "Fix\n\nCo-authored-by: Resul Övür <human@example.com>\nco-AUTHORED-by: OpenAI Codex <codex@openai.com>\n"
self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message))))
def test_human_authors_and_human_coauthors_are_preserved(self):
message = "Fix the Codex configuration\n\nCo-authored-by: Resul Övür <human@example.com>\n"
self.assertEqual([], check.commit_violations("abc", self.commit(message=message)))
def test_record_separator_in_message_does_not_hide_a_bot_trailer(self):
self.assertTrue(check.commit_violations("abc", self.commit(message="Fix\x1e\nCo-authored-by: Claude <noreply@anthropic.com>\n")))
def test_pr_metadata_cannot_add_a_bot_to_the_squash_message(self):
for field in ("title", "body"):
self.assertTrue(check.event_violations({"pull_request": {field: "Co-authored-by: Copilot <bot@example.com>"}}))
def test_bot_pr_author_is_rejected(self):
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}}))
def test_missing_author_fails_closed(self):
self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n"))
class InstalledHooksTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.repo = Path(self.directory.name)
self.git("init", "-q")
self.git("config", "user.name", "Human Contributor")
self.git("config", "user.email", "human@example.com")
installer = path.with_name("install_authorship_hooks.py")
subprocess.run([sys.executable, str(installer)], cwd=self.repo, check=True, capture_output=True)
(self.repo / "file").write_text("content")
self.git("add", "file")
def tearDown(self):
self.directory.cleanup()
def git(self, *args):
return subprocess.run(["git", *args], cwd=self.repo, text=True, capture_output=True)
def test_explicit_bot_author_override_is_blocked(self):
result = self.git("commit", "--author=OpenAI Codex <codex@openai.com>", "-m", "Fix")
self.assertNotEqual(0, result.returncode, result.stdout + result.stderr)
self.assertIn("Bot commit author is forbidden", result.stderr)
def test_no_verify_does_not_skip_automatic_trailer_scrubbing(self):
result = self.git("commit", "--no-verify", "-m", "Fix\n\nCo-authored-by: Another Human <other@example.com>\nCo-authored-by: Claude <noreply@anthropic.com>")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
message = self.git("log", "-1", "--format=%B").stdout
self.assertNotIn("noreply@anthropic.com", message)
self.assertIn("Co-authored-by: Another Human <other@example.com>", message)
def test_human_commit_and_human_coauthor_are_allowed(self):
result = self.git("commit", "-m", "Fix\n\nCo-authored-by: Another Human <other@example.com>")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()
+123
View File
@@ -0,0 +1,123 @@
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "device-smoke.sh"
FAKE_ADB = r'''#!/usr/bin/env python3
import json, os, shlex, sys
from pathlib import Path
p = Path(os.environ["SMOKE_STATE"])
s = json.loads(p.read_text())
a = sys.argv[1:]
if a == ["get-state"]:
print("device")
elif a[:1] == ["shell"]:
a = shlex.split(a[1])
if a[:1] == ["wm"]:
kind = a[1]
if len(a) == 2:
if s.get("unreadable") == kind:
print("permission denied")
else:
print("Physical " + kind + ": " + ("400" if kind == "density" else "1080x1920"))
if s.get(kind): print("Override " + kind + ": " + s[kind])
else:
value = a[2]
s["writes"].append([kind, value])
restoring = value in ("reset", "420", "1000x1800")
if not (s.get("ignored") == kind or restoring and s.get("restore_ignored") == kind):
s[kind] = "" if value == "reset" else value
p.write_text(json.dumps(s))
elif a[:1] == ["getconf"]: print("4096")
elif a[:1] == ["pidof"]: print("123")
elif a[:2] == ["dumpsys", "activity"]:
print("topResumedActivity=ActivityRecord{abc u0 com.droiddeck.launcher/.MainActivity t1}")
elif a[:3] == ["pm", "list", "packages"]:
if s.get("query_failed"): sys.exit(1)
print("package:" + s.get("package", "com.droiddeck.launcher"))
elif a[:2] == ["am", "start"] and s.get("launch_failed"):
print("Error: activity could not be started")
sys.exit(1 if s["launch_failed"] == "exit" else 0)
elif a[:1] == ["run-as"]:
if s.get("session"):
s.setdefault("log_commands", []).append(a)
p.write_text(json.dumps(s))
if "ls" in a: print(s["session"])
else: print("package not debuggable")
'''
class DeviceSmokeTest(unittest.TestCase):
def run_smoke(self, **scenario):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
adb = root / "adb"
adb.write_text(FAKE_ADB)
adb.chmod(0o755)
sleep = root / "sleep"
sleep.write_text("#!/bin/sh\nexit 0\n")
sleep.chmod(0o755)
state = root / "state.json"
state.write_text(json.dumps({"density": "", "size": "", "writes": [], **scenario}))
env = dict(os.environ, ADB=str(adb), SMOKE_STATE=str(state), PATH=str(root) + os.pathsep + os.environ["PATH"])
result = subprocess.run(["bash", str(SCRIPT), "--no-fold"], env=env, capture_output=True, text=True, timeout=30)
return result, json.loads(state.read_text())
def test_restores_preexisting_display_overrides(self):
result, state = self.run_smoke(density="420", size="1000x1800")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertEqual("420", state["density"])
self.assertEqual("1000x1800", state["size"])
def test_ignored_display_changes_do_not_pass(self):
for kind in ("density", "size"):
with self.subTest(kind=kind):
result, state = self.run_smoke(ignored=kind)
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("wm " + kind + " failed", result.stdout)
self.assertNotIn("PASS same process " + ("after" if kind == "density" else "at"), result.stdout)
self.assertEqual("", state[kind])
def test_ignored_restore_remains_a_failure_and_is_retried_on_exit(self):
for kind in ("density", "size"):
with self.subTest(kind=kind):
result, state = self.run_smoke(restore_ignored=kind)
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("could not restore", result.stdout)
self.assertNotEqual("", state[kind])
self.assertEqual(2, state["writes"].count([kind, "reset"]))
def test_unreadable_original_settings_are_not_changed(self):
for kind in ("density", "size"):
with self.subTest(kind=kind):
result, state = self.run_smoke(unreadable=kind)
self.assertEqual(0, result.returncode, result.stdout)
self.assertFalse(any(item[0] == kind for item in state["writes"]))
def test_package_filter_does_not_accept_another_variant_or_a_failed_query(self):
for scenario in ({"package": "com.droiddeck.launcher.debug"}, {"query_failed": True}):
with self.subTest(scenario=scenario):
result, state = self.run_smoke(**scenario)
self.assertEqual(2, result.returncode, result.stdout)
self.assertEqual([], state["writes"])
def test_failed_launch_is_not_masked_by_an_existing_process(self):
for failure in ("exit", "message"):
with self.subTest(failure=failure):
result, _ = self.run_smoke(launch_failed=failure)
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("could not launch", result.stdout)
def test_session_name_remains_one_remote_argument(self):
session = "x';id;#"
result, state = self.run_smoke(session=session)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertIn(["run-as", "com.droiddeck.launcher", "cat", "files/logs/" + session + "/events.jsonl"], state["log_commands"])
if __name__ == "__main__":
unittest.main()
+17
View File
@@ -6,6 +6,7 @@ import os
import runpy
import shutil
import struct
import subprocess
import tempfile
import unittest
from pathlib import Path
@@ -866,6 +867,22 @@ class AppInfoTest(unittest.TestCase):
self.assertIn('"from_oslist" "linux"', vdf)
self.assertIn('"to_oslist" "linux"', vdf)
def test_the_tool_runs_games_on_the_chosen_cores(self):
with tempfile.TemporaryDirectory() as tmp:
tool, bin_dir = Path(tmp) / "droiddeck-fex", Path(tmp) / "bin"
self.COMPAT["build_fex_tool"](str(tool))
bin_dir.mkdir()
(bin_dir / "taskset").write_text('#!/bin/sh\necho "taskset $*"\n')
(bin_dir / "taskset").chmod(0o755)
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ.get("PATH", "")), BL_GAME_CPUS="2-7")
run = subprocess.run([str(tool / "droiddeck-fex-tool"), "waitforexitandrun", "/games/a/game"],
env=env, capture_output=True, text=True, timeout=10)
self.assertEqual(run.stdout,
"taskset -c 2-7 /usr/local/bin/droiddeck-fex steam waitforexitandrun /games/a/game\n")
self.assertIn("game cores 2-7", run.stderr)
self.assertIn('exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} '
'/usr/local/bin/droiddeck-fex steam "$verb" "$@"', self.COMPAT["FEX_LAUNCHER_SH"])
if __name__ == "__main__":
unittest.main()
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Live regression probe; run inside a running Gamescope session.
Requires Python 3, WAYLAND_DISPLAY, XDG_RUNTIME_DIR and access to Gamescope's
/proc/<pid>/fd. Creates only a temporary surface with the cursor role; it does
not take pointer focus or change game/save files. Affected Gamescope retains all
20 SHM allocations; fixed Gamescope retains at most the current cursor buffer.
"""
import os
import socket
import struct
import time
import json
import array
import argparse
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--unassigned-control', action='store_true', help='verify that window buffers awaiting association remain queued')
args = parser.parse_args()
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(2)
s.connect(os.path.join(os.environ['XDG_RUNTIME_DIR'], os.environ['WAYLAND_DISPLAY']))
U = lambda *v: struct.pack('<' + 'I' * len(v), *v)
def string(v):
b = v.encode() + b'\x00'
return U(len(b)) + b + b'\x00' * (-len(b) % 4)
def send(obj, op, p=b'', fd=None):
b = U(obj, len(p) + 8 << 16 | op) + p
if fd is None:
s.sendall(b)
else:
s.sendmsg([b], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array('i', [fd]))])
nextid = 2
pids = []
for process in Path('/proc').iterdir():
if not process.name.isdigit():
continue
try:
if (process / 'comm').read_text().strip() == 'gamescope':
pids.append(process)
except (FileNotFoundError, PermissionError):
pass
assert len(pids) == 1, f'expected one Gamescope process, found {[p.name for p in pids]}'
fd_dir = pids[0] / 'fd'
def alloc():
nonlocal nextid
nextid += 1
return nextid
pending = b''
globals = {}
def roundtrip():
nonlocal pending
cb = alloc()
send(1, 0, U(cb))
while True:
while len(pending) >= 8:
obj, h = struct.unpack_from('<II', pending)
n = h >> 16
op = h & 65535
if len(pending) < n:
break
p = pending[8:n]
pending = pending[n:]
if obj == 1 and op == 0:
raise RuntimeError('wayland error ' + repr(p))
if obj == 2 and op == 0:
name, l = struct.unpack_from('<II', p)
itf = p[8:8 + l - 1].decode()
ver = struct.unpack_from('<I', p, 8 + (l + 3) // 4 * 4)[0]
globals[itf] = (name, ver)
if obj == cb:
return
chunk = s.recv(65536)
if not chunk:
raise RuntimeError('Wayland connection closed during roundtrip')
pending += chunk
def bind(itf, version):
obj = alloc()
name, ver = globals[itf]
send(2, 0, U(name) + string(itf) + U(min(ver, version), obj))
return obj
def count():
n = 0
for f in fd_dir.iterdir():
try:
n += 'dd-shm-probe' in os.readlink(f)
except FileNotFoundError:
pass
return n
send(1, 1, U(2))
roundtrip()
comp = bind('wl_compositor', 4)
shm = bind('wl_shm', 1)
seat = bind('wl_seat', 1)
pointer = alloc()
send(seat, 0, U(pointer))
surface = alloc()
send(comp, 0, U(surface))
if not args.unassigned_control:
# wlroots 0.20.2 assigns the cursor role before forwarding this serial
# to Gamescope, so zero avoids needing pointer focus but still tests the
# role guard in xwayland_surface_commit.
send(pointer, 0, U(0, surface, 0, 0))
roundtrip()
before = count()
for i in range(20):
fd = os.memfd_create('dd-shm-probe', os.MFD_CLOEXEC)
os.ftruncate(fd, 64 * 64 * 4)
pool = alloc()
send(shm, 0, U(pool, 64 * 64 * 4), fd)
os.close(fd)
buffer = alloc()
send(pool, 0, U(buffer, 0, 64, 64, 64 * 4, 0))
send(pool, 1)
send(surface, 1, U(buffer, 0, 0))
send(surface, 2, U(0, 0, 64, 64))
send(surface, 6)
send(buffer, 0)
roundtrip()
after_commits = count()
send(surface, 0)
roundtrip()
time.sleep(0.2)
after_surface_destroy = count()
s.close()
print(json.dumps(dict(before=before, after_commits=after_commits, after_surface_destroy=after_surface_destroy, growth=after_commits - before)))
if args.unassigned_control:
assert after_commits - before == 20, 'unassigned window commits were unexpectedly discarded'
else:
assert after_commits - before <= 1, f'cursor buffers leaked: {after_commits - before} retained after 20 commits'
assert after_surface_destroy == before, 'cursor buffers remain after destroying the test surface'
if __name__ == "__main__":
main()
+135 -1
View File
@@ -53,6 +53,8 @@ class SeedRedistsTest(unittest.TestCase):
self.reg = self.steam / "steamapps/compatdata/1234/pfx/system.reg"
self.reg.parent.mkdir(parents=True)
self.reg.write_text("WINE REGISTRY Version 2\n")
self.user = self.reg.with_name("user.reg")
self.user.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Unrelated] 1\n"Keep"="untouched"\n')
def game(self, name="Some Game", script=GAME_SCRIPT, library=None):
root = Path(library or self.steam)
@@ -81,6 +83,93 @@ class SeedRedistsTest(unittest.TestCase):
self.run_seed(str(sd))
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
def test_current_user_and_machine_markers_go_to_their_own_registries(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
with self.reg.open("a") as out:
out.write('\n[Software\\\\Unrelated] 1\n"Keep"="machine"\n')
for reg in (self.reg, self.user):
os.utime(reg, ns=(1_000_000_000_123456789, 1_000_000_000_123456789))
self.run_seed()
system, user = self.reg.read_text(), self.user.read_text()
self.assertEqual(system.count('"VCRedist2022"=dword:00000001'), 2)
self.assertNotIn("UserRedist", system)
self.assertEqual(user.count('"UserRedist"=dword:00000001'), 1)
self.assertNotIn("Wow6432Node", user)
self.assertNotIn("VCRedist2022", user)
self.assertIn('"Keep"="machine"', system)
self.assertIn('"Keep"="untouched"', user)
self.run_seed()
self.assertEqual(system, self.reg.read_text())
self.assertEqual(user, self.user.read_text())
for reg in (self.reg, self.user):
self.assertEqual(reg.stat().st_mtime_ns, 1_000_000_000_123456789)
def test_a_user_marker_with_the_same_machine_path_and_value_is_separate(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
system = self.reg.read_text()
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
self.user.write_text("WINE REGISTRY Version 2\n")
self.run_seed()
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
self.assertEqual(system, self.reg.read_text())
def test_a_legacy_user_ledger_entry_is_checked_in_user_reg(self):
self.game(script=GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
system = self.reg.read_bytes()
self.user.write_text("WINE REGISTRY Version 2\n")
(self.reg.parent / ".droiddeck-redists-checked").write_text(subprocess.check_output(["stat", "-c", "%i %s %.9Y", str(self.reg)], text=True))
self.run_seed()
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
self.assertEqual(system, self.reg.read_bytes())
def test_an_absent_user_registry_is_not_created_or_claimed(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
self.user.unlink()
self.run_seed()
self.assertFalse(self.user.exists())
self.assertNotIn("UserRedist", (self.reg.parent / ".droiddeck-redists").read_text())
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
system = self.reg.read_bytes()
self.user.write_text("WINE REGISTRY Version 2\n")
self.run_seed()
self.assertIn('"UserRedist"=dword:00000001', self.user.read_text())
self.run_seed()
self.user.unlink()
self.run_seed()
self.assertFalse(self.user.exists())
self.assertNotIn("UserRedist", (self.reg.parent / ".droiddeck-redists").read_text())
self.assertEqual(system, self.reg.read_bytes())
@unittest.skipIf(os.name == "posix" and os.geteuid() == 0, "root can write through read-only mode bits")
def test_an_unwritable_user_registry_does_not_claim_a_missing_marker(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
ledger = self.reg.parent / ".droiddeck-redists"
ledger.write_text("HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022\tUserRedist\n")
user = self.user.read_bytes()
self.user.chmod(0o444)
try:
self.run_seed()
self.assertEqual(user, self.user.read_bytes())
self.assertEqual(self.user.stat().st_mode & 0o777, 0o444)
self.assertNotIn("UserRedist", ledger.read_text())
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
finally:
self.user.chmod(0o644)
def test_user_markers_in_a_default_prefix_and_another_library_are_seeded(self):
default = self.steam / "steamapps/common/Proton Test/files/share/default_pfx"
default.mkdir(parents=True)
for name in ("system.reg", "user.reg"):
(default / name).write_text("WINE REGISTRY Version 2\n")
sd = self.tmp / "sd"
self.game(library=sd, script=GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed(str(sd))
self.assertIn('"VCRedist2022"=dword:00000001', (default / "user.reg").read_text())
self.assertNotIn('"VCRedist2022"', (default / "system.reg").read_text())
self.assertIn('"VCRedist2022"=dword:00000001', self.user.read_text())
def test_the_vc_runtime_is_recorded_for_every_architecture_and_view(self):
self.run_seed()
reg = self.reg.read_text()
@@ -156,7 +245,7 @@ class SeedRedistsTest(unittest.TestCase):
self.assertIn('"x64 14.99.1.0"=dword:00000001', self.reg.read_text())
def test_an_unchanged_registry_is_not_read_again(self):
self.game()
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
self.run_seed()
self.run_seed()
shim = self.tmp / "bin"
@@ -166,9 +255,21 @@ class SeedRedistsTest(unittest.TestCase):
(shim / "awk").chmod(0o755)
env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"]))
once = self.reg.read_text()
user = self.user.read_text()
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
self.assertEqual(once, self.reg.read_text())
self.assertEqual(user, self.user.read_text())
self.assertNotIn(str(self.reg), log.read_text() if log.exists() else "")
self.assertNotIn(str(self.user), log.read_text() if log.exists() else "")
replaced = self.user.with_name("user.reg.new")
replaced.write_text(user.replace('"UserRedist"', '"OtherValue"'))
os.utime(replaced, ns=(self.user.stat().st_atime_ns, self.user.stat().st_mtime_ns))
self.assertEqual(replaced.stat().st_size, self.user.stat().st_size)
os.replace(replaced, self.user)
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
self.assertEqual(self.user.read_text().count('"UserRedist"=dword:00000001'), 1)
self.assertIn('"OtherValue"=dword:00000001', self.user.read_text())
self.assertEqual(once, self.reg.read_text())
replaced = self.reg.with_name("system.reg.new")
replaced.write_text("WINE REGISTRY Version 2\n")
os.replace(replaced, self.reg)
@@ -194,6 +295,39 @@ class SeedRedistsTest(unittest.TestCase):
self.assertIn('"RockstarLauncher"=dword:00000001', reg)
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
def test_a_current_user_vulkan_installer_is_left_to_run(self):
self.game(script=VULKAN_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
self.assertIn('"RockstarLauncher"=dword:00000001', self.user.read_text())
self.assertNotIn("Vulkan111080", self.user.read_text())
self.assertNotIn("Vulkan111080", self.reg.read_text())
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
def test_a_current_user_vulkan_marker_comes_out_of_only_its_own_hive(self):
self.game(script=VULKAN_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
system = self.reg.read_bytes() + b'\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n'
self.reg.write_bytes(system)
with self.user.open("a") as out:
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Other"="keep"\n"Vulkan111080"=dword:00000001\n'
'\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n'
'\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\22380] 1\n"Vulkan111080"=dword:00000001\n')
with (self.reg.parent / ".droiddeck-redists").open("a") as out:
out.write("HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080\n")
os.utime(self.user, ns=(1_000_000_000_123456789, 1_000_000_000_123456789))
self.run_seed()
user = self.user.read_text()
self.assertEqual(user.count('"Vulkan111080"'), 2, "the other path and the unseeded user view stay")
self.assertIn('"Other"="keep"', user)
self.assertEqual(system, self.reg.read_bytes())
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
self.assertEqual(self.user.stat().st_mtime_ns, 1_000_000_000_123456789)
with self.user.open("a") as out:
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n')
user = self.user.read_bytes()
self.run_seed()
self.assertEqual(user, self.user.read_bytes())
def test_a_vulkan_marker_an_earlier_seeding_wrote_comes_out_once(self):
self.rdr2()
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080"
+27
View File
@@ -0,0 +1,27 @@
import re
import subprocess
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
def step_function():
match = re.search(r"^step\(\) \{.*\}$", SESSION.read_text(), re.M)
return match.group(0)
class SessionStepTimeTest(unittest.TestCase):
def test_a_step_line_carries_milliseconds_before_its_text(self):
out = subprocess.run(["bash", "-c", step_function() + "\nstep starting the Steam client"],
capture_output=True, text=True, timeout=30).stdout.strip()
self.assertRegex(out, r"^== STEP \d{2}:\d{2}:\d{2}\.\d{3} starting the Steam client$")
def test_the_text_after_the_first_space_is_the_step_name(self):
out = subprocess.run(["bash", "-c", step_function() + "\nstep checking the Steam client"],
capture_output=True, text=True, timeout=30).stdout.strip()
self.assertEqual("checking the Steam client", out.removeprefix("== STEP ").split(" ", 1)[1])
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -774,6 +774,14 @@ class AttachPage:
return {"selected": "", "fallback": "", "tools": []}
class TourFailurePage(AttachPage):
def evaluate(self, expression, timeout=30):
self.scripts.append(expression)
if expression == LIVE["TOUR_JS"]:
raise RuntimeError("SteamClient.Settings.SetSetting is unavailable")
return True
class SwitchToDesktopTest(unittest.TestCase):
def setUp(self):
self.globals = LIVE["Helper"].attach.__globals__
@@ -798,6 +806,14 @@ class SwitchToDesktopTest(unittest.TestCase):
self.assertIn(("Runtime.addBinding", LIVE["VR_BINDING"]), helper.page.calls)
self.assertIn(LIVE["VR_JS"], helper.page.scripts)
def test_missing_optional_tour_setting_does_not_block_attach(self):
with mock.patch.dict(self.globals, {"shared_context": lambda port: "/devtools/page/1", "Page": TourFailurePage}):
helper = LIVE["Helper"]("/steam", 1)
self.assertTrue(helper.attach())
self.assertIn(LIVE["VR_JS"], helper.page.scripts)
self.assertIn(LIVE["TOUR_JS"], helper.page.scripts)
self.assertIsNotNone(helper.page)
def test_vr_bridge_accepts_only_steamvr_and_coalesces_requests(self):
helper = LIVE["Helper"]("/steam", 1)
helper.page = mock.Mock()
+107
View File
@@ -0,0 +1,107 @@
import contextlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
RELEASE = Path(__file__).resolve().parents[1] / "release"
sys.path.insert(0, str(RELEASE))
import validate_apk
class ValidateApkTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
subprocess.run(["git", "init", "-q", self.root], check=True)
self.git("config", "user.name", "Human Developer")
self.git("config", "user.email", "human@example.org")
self.git("commit", "--allow-empty", "-qm", "Baseline")
self.git("update-ref", "refs/remotes/origin/main", "HEAD")
self.statuses = []
def git(self, *args):
return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip()
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"):
(self.root / filename).write_text(message)
self.git("add", filename)
self.git("commit", "--allow-empty", "-qm", message)
sha = self.git("rev-parse", "HEAD")
pr = {"number": 1, "state": "open", "head": {"sha": sha}, "user": {"login": "human", "type": "User"},
"title": "Source change", "body": body}
event = {"number": 1, "pull_request": {"head": {"sha": "stale" if stale else sha}}}
if completed:
event = {"workflow_run": {"event": "pull_request", "head_sha": "stale" if stale else sha}}
path = self.root / "event.json"
path.write_text(json.dumps(event))
def api(path, *args):
if "/statuses/" in path:
self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value))
return {}
if path.endswith("/pulls/1"):
return pr
if "/commits/" in path and path.endswith("/pulls"):
return [pr]
if "workflows/build.yml/runs?" in path:
return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]}
if path.endswith("/jobs?per_page=100"):
return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]}
raise AssertionError(path)
env = {"GITHUB_EVENT_PATH": str(path), "GITHUB_REPOSITORY": "owner/repo",
"GITHUB_EVENT_NAME": "workflow_run" if completed else "pull_request_target", "GITHUB_RUN_ID": "8"}
with contextlib.chdir(self.root), patch.dict(os.environ, env), patch.object(validate_apk, "api", side_effect=api), patch.object(validate_apk, "fetch_source"):
validate_apk.main()
def test_success_requires_compilation_and_clean_authorship(self):
self.validate()
self.assertEqual(self.statuses[-1]["state"], "success")
def test_successful_build_cannot_hide_bot_commit(self):
with self.assertRaises(RuntimeError):
self.validate(message="Change\n\nCo-authored-by: OpenAI Codex <codex@openai.com>")
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_successful_build_cannot_hide_squash_metadata(self):
with self.assertRaises(RuntimeError):
self.validate(body="Co-authored-by: Claude <claude@example.org>")
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_pending_or_failed_compilation_never_passes(self):
for result in ("pending", "failure"):
self.validate(result=result)
self.assertEqual(self.statuses[-1]["state"], result)
def test_superseded_event_cannot_replace_current_status(self):
self.validate(stale=True)
self.assertEqual(self.statuses, [])
def test_completed_build_revalidates_current_squash_metadata(self):
with self.assertRaises(RuntimeError):
self.validate(body="Co-authored-by: Claude <claude@example.org>", completed=True)
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_superseded_build_cannot_replace_current_status(self):
self.validate(stale=True, completed=True)
self.assertEqual(self.statuses, [])
def test_documentation_passes_without_waiting_for_a_skipped_build(self):
self.validate(filename="README.md", result="pending")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_renaming_code_to_documentation_still_requires_compilation(self):
(self.root / "source.kt").write_text("source")
self.git("add", "source.kt")
self.git("commit", "-qm", "Add source")
self.git("update-ref", "refs/remotes/origin/main", "HEAD")
self.git("mv", "source.kt", "README.md")
self.git("commit", "-qm", "Rename source")
with contextlib.chdir(self.root):
self.assertFalse(validate_apk.documentation_only(self.git("rev-parse", "HEAD")))
@@ -0,0 +1 @@
out/
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.droiddeck.viturev2check" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
<uses-feature android:name="android.hardware.usb.host" android:required="true" />
<application android:label="VITURE production driver check" android:debuggable="true" android:allowBackup="false" android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,53 @@
# Production VITURE v2 driver hardware check
This harness calls the actual production `VitureV2Link.Companion.open` and packages
the freshly compiled `VitureV2Link*.class`, `VitureV2Protocol*.class`, and
`GlassesLink*.class` files from `app/build/tmp/kotlin-classes/debug`. It contains no
USB transport or protocol implementation of its own and no vendor SDK or native
library. The Kotlin standard library version matches the root Gradle build, 2.1.0.
The default build relies on Gradle's source/dependency checks to refresh classes
and rejects unexpected application-class dependencies, including an old
orientation-helper dependency. Source and bytecode hashes are recorded together;
file timestamps are not used because Gradle can restore classes from its cache.
Build from the workspace with:
```powershell
./tools/viture/viture-v2-driver-check/build.ps1
```
This first invokes `:app:compileDebugKotlin -PvitureSdkDir=`. If the parent task just
completed that compile, pass `-SkipCompile` to package those classes without starting
another Gradle build. That option requires the caller to ensure the classes are
current. The output is
`tools/viture/viture-v2-driver-check/out/viture-v2-driver-check-debug.apk`.
SDK discovery uses `ANDROID_HOME`, `ANDROID_SDK_ROOT`, then `%LOCALAPPDATA%\Android\Sdk`.
JDK discovery uses `JAVA_HOME`, the optional `%USERPROFILE%\.jdks\jbr-17.0.9`, then
`javac.exe` on PATH. Explicit `-Sdk` and `-Java` override discovery. Kotlin cache
discovery respects `GRADLE_USER_HOME`, falling back to `%USERPROFILE%\.gradle`.
APK assets contain the upstream MIT license and a runtime manifest of the exact
production-class SHA256 hashes and Kotlin library hash. Every session logs this
manifest. The documented upstream protocol itself was derived from third-party
vendor SDK captures; this harness uses the existing SDK-free production driver.
Only an attached `35ca:1301` Pro 2 can be opened. After USB permission, the real
driver bootstraps its pose stream. `onReady` is posted to the main handler so the
link assignment is complete before control commands. The harness sends the
controller's internal IMU-off command, checks for zero new pose callbacks over
500 ms, resumes, captures for 10..15 seconds (default 12), pauses again, checks
another 500 ms, and closes the driver. A watchdog starts closure at 23.5 seconds,
reserving the driver's maximum 1.5-second join for a 25-second test limit after
permission. Android scheduling or system stalls can extend elapsed wall time.
```powershell
adb shell am start -n com.droiddeck.viturev2check/.MainActivity --ez auto true --ei seconds 12
```
JSONL logs are under
`/data/user/0/com.droiddeck.viturev2check/files/checks/driver-check-<wall-ms>.jsonl`.
They include every callback packet with actual length and base64 bytes, the exact
shared `xyzw` quaternion delivered by production code, tracking/ready events,
pause-window counts, errors, bad frames, total and capture pose counts, sample
rate, and final state. This checks the real driver's hardware/session behavior;
it does not run the full application UI or establish the user's physical axis
and recentering experience. Reopen the activity for a separate check.
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Holger Bartnick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,12 @@
The VITURE v2 protocol in the packaged production DroidDeck driver is adapted from
elasticjava/viture-v2, copyright (c) 2026 Holger Bartnick, under the MIT license.
Pinned upstream commit: ece8c30485f7d357fefa362ae74f3eabac9b3899.
See LICENSE.viture-v2 in these APK assets for the complete license.
The APK packages actual compiled DroidDeck VitureV2Link, VitureV2Protocol, and
GlassesLink classes and the Kotlin standard library 2.1.0. Kotlin is copyright
JetBrains and contributors and distributed under Apache License 2.0:
https://www.apache.org/licenses/LICENSE-2.0
See LICENSE.kotlin-Apache-2.0 in these APK assets for the complete license terms.
No vendor SDK or vendor native libraries are included.
@@ -0,0 +1,117 @@
param(
[string]$Sdk,
[string]$Java = $env:JAVA_HOME,
[switch]$SkipCompile
)
$ErrorActionPreference = 'Stop'
if (-not $Sdk) {
if ($env:ANDROID_HOME) { $Sdk = $env:ANDROID_HOME }
elseif ($env:ANDROID_SDK_ROOT) { $Sdk = $env:ANDROID_SDK_ROOT }
elseif ($env:LOCALAPPDATA) { $Sdk = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
else { throw 'Set ANDROID_HOME / ANDROID_SDK_ROOT or pass -Sdk.' }
}
if (-not $Java) {
$fallbackJdk = Join-Path $env:USERPROFILE '.jdks\jbr-17.0.9'
$javacCommand = Get-Command javac.exe -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath (Join-Path $fallbackJdk 'bin\javac.exe')) { $Java = $fallbackJdk }
elseif ($javacCommand) { $Java = Split-Path (Split-Path $javacCommand.Source -Parent) -Parent }
}
if (-not $Java -or -not (Test-Path -LiteralPath (Join-Path $Java 'bin\javac.exe'))) {
throw 'Set JAVA_HOME or pass -Java with a JDK containing bin\javac.exe.'
}
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..'))
$output = Join-Path $PSScriptRoot 'out'
$buildId = [Guid]::NewGuid().ToString('N')
$classes = Join-Path $output ('classes-' + $buildId)
$production = Join-Path $output ('production-' + $buildId)
$productionPackage = Join-Path $production 'com\droiddeck\launcher\glasses'
$assets = Join-Path $output ('assets-' + $buildId)
$dex = Join-Path $output ('dex-' + $buildId)
$buildTools = Join-Path $Sdk 'build-tools\36.0.0'
$androidJar = Join-Path $Sdk 'platforms\android-34\android.jar'
$compiled = Join-Path $repo 'app\build\tmp\kotlin-classes\debug\com\droiddeck\launcher\glasses'
$stdlibVersion = '2.1.0'
$gradleCacheRoot = if ($env:GRADLE_USER_HOME) { $env:GRADLE_USER_HOME } else { Join-Path $env:USERPROFILE '.gradle' }
$stdlibDirectory = Join-Path $gradleCacheRoot ('caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-stdlib\' + $stdlibVersion)
$stdlibFiles = @(Get-ChildItem -LiteralPath $stdlibDirectory -Recurse -File | Where-Object Name -EQ ('kotlin-stdlib-' + $stdlibVersion + '.jar'))
if ($stdlibFiles.Count -ne 1) { throw "Expected one cached Kotlin stdlib $stdlibVersion jar." }
$stdlib = $stdlibFiles[0].FullName
$unsigned = Join-Path $output 'viture-v2-driver-check-unsigned.apk'
$aligned = Join-Path $output 'viture-v2-driver-check-aligned.apk'
$apk = Join-Path $output 'viture-v2-driver-check-debug.apk'
$classJar = Join-Path $output 'harness.jar'
$productionJar = Join-Path $output 'production-driver.jar'
$previousJavaHome = $env:JAVA_HOME
try {
$env:JAVA_HOME = $Java
if (-not $SkipCompile) {
Push-Location -LiteralPath $repo
try {
& (Join-Path $repo 'gradlew.bat') ':app:compileDebugKotlin' '-PvitureSdkDir='
if ($LASTEXITCODE -ne 0) { throw 'Production Kotlin compilation failed.' }
} finally { Pop-Location }
}
$manifestSources = @()
foreach ($pair in @(
@('VitureV2Link.class', 'VitureV2Link.kt'),
@('VitureV2Protocol.class', 'VitureV2Protocol.kt'),
@('GlassesLink.class', 'GlassesHardware.kt')
)) {
$binary = Get-Item -LiteralPath (Join-Path $compiled $pair[0])
$source = Get-Item -LiteralPath (Join-Path $repo ('app\src\main\java\com\droiddeck\launcher\glasses\' + $pair[1]))
$manifestSources += [ordered]@{ name = $source.Name; sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $source.FullName).Hash }
}
New-Item -ItemType Directory -Force -Path $output, $classes, $productionPackage, $assets, $dex | Out-Null
$classFiles = @(Get-ChildItem -LiteralPath $compiled -File | Where-Object {
$_.Name -like 'VitureV2Link*.class' -or $_.Name -like 'VitureV2Protocol*.class' -or $_.Name -like 'GlassesLink*.class'
})
if ($classFiles.Count -lt 3) { throw 'Production class selection is incomplete.' }
$manifestClasses = @()
foreach ($classFile in $classFiles) {
Copy-Item -LiteralPath $classFile.FullName -Destination $productionPackage
$manifestClasses += [ordered]@{ name = $classFile.Name; sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $classFile.FullName).Hash }
}
& (Join-Path $Java 'bin\jar.exe') cf $productionJar -C $production .
if ($LASTEXITCODE -ne 0) { throw 'Production jar creation failed.' }
$dependencies = & (Join-Path $Java 'bin\jdeps.exe') -verbose:class -filter:none $productionJar
if ($LASTEXITCODE -ne 0) { throw 'Production dependency inspection failed.' }
foreach ($line in $dependencies) {
if ($line -match '->\s+(com\.droiddeck\.launcher\.glasses\.\S+)') {
if ($Matches[1] -notmatch '^com\.droiddeck\.launcher\.glasses\.(VitureV2Link|VitureV2Protocol|GlassesLink)(\$|$)') {
throw ('Unexpected production dependency: ' + $Matches[1] + '. Recompile the current isolated driver source.')
}
}
}
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\LICENSE.viture-v2') -Destination $assets
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\NOTICE.txt') -Destination $assets
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\LICENSE.kotlin-Apache-2.0') -Destination $assets
$runtimeManifest = [ordered]@{
source = 'Actual app/build/tmp/kotlin-classes/debug production bytecode; not reimplemented'
upstreamCommit = 'ece8c30485f7d357fefa362ae74f3eabac9b3899'
builtUtc = [DateTime]::UtcNow.ToString('o')
kotlinStdlibVersion = $stdlibVersion
kotlinStdlibSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $stdlib).Hash
productionJarSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $productionJar).Hash
sources = $manifestSources
classes = $manifestClasses
}
$runtimeManifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $assets 'runtime-manifest.json') -Encoding utf8
& (Join-Path $Java 'bin\javac.exe') --release 8 -classpath ($androidJar + ';' + $productionJar + ';' + $stdlib) -encoding UTF-8 -d $classes (Join-Path $PSScriptRoot 'src\com\droiddeck\viturev2check\MainActivity.java')
if ($LASTEXITCODE -ne 0) { throw 'Harness Java compilation failed.' }
& (Join-Path $Java 'bin\jar.exe') cf $classJar -C $classes .
if ($LASTEXITCODE -ne 0) { throw 'Harness jar creation failed.' }
& (Join-Path $buildTools 'd8.bat') --min-api 26 --lib $androidJar --output $dex $classJar $productionJar $stdlib
if ($LASTEXITCODE -ne 0) { throw 'D8 failed.' }
& (Join-Path $buildTools 'aapt2.exe') link --manifest (Join-Path $PSScriptRoot 'AndroidManifest.xml') -A $assets -I $androidJar -o $unsigned --min-sdk-version 26 --target-sdk-version 34
if ($LASTEXITCODE -ne 0) { throw 'Manifest linking failed.' }
& (Join-Path $Java 'bin\jar.exe') uf $unsigned -C $dex classes.dex
if ($LASTEXITCODE -ne 0) { throw 'Dex insertion failed.' }
& (Join-Path $buildTools 'zipalign.exe') -f 4 $unsigned $aligned
if ($LASTEXITCODE -ne 0) { throw 'APK alignment failed.' }
& (Join-Path $buildTools 'apksigner.bat') sign --ks (Join-Path $repo 'keystore\testkey.p12') --ks-key-alias testkey --ks-pass pass:android --key-pass pass:android --out $apk $aligned
if ($LASTEXITCODE -ne 0) { throw 'APK signing failed.' }
& (Join-Path $buildTools 'apksigner.bat') verify --verbose $apk
if ($LASTEXITCODE -ne 0) { throw 'APK verification failed.' }
Get-FileHash -Algorithm SHA256 -LiteralPath $apk
Write-Output $apk
} finally { $env:JAVA_HOME = $previousJavaHome }
@@ -0,0 +1,317 @@
package com.droiddeck.viturev2check;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Base64;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.droiddeck.launcher.glasses.VitureV2Link;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.json.JSONArray;
import org.json.JSONObject;
public final class MainActivity extends Activity {
private static final String PERMISSION = "com.droiddeck.viturev2check.USB_PERMISSION";
private static final int VENDOR = 0x35ca, PRODUCT = 0x1301, INTERNAL_IMU = 0x0015;
private static final long TOTAL_LIMIT_MS = 25000, CLOSE_RESERVE_MS = 1500;
private final Handler handler = new Handler(Looper.getMainLooper());
private final AtomicBoolean finishing = new AtomicBoolean();
private final AtomicLong poses = new AtomicLong(), capturePoses = new AtomicLong(), packetBytes = new AtomicLong();
private final AtomicLong readyCallbacks = new AtomicLong(), trackingOn = new AtomicLong(), trackingOff = new AtomicLong(), errors = new AtomicLong();
private final Object poseLock = new Object();
private UsbManager manager;
private UsbDevice pending;
private TextView status;
private VitureV2Link link;
private Journal journal;
private boolean busy, bootstrapHandled, firstOffAccepted, resumeAccepted, finalOffAccepted;
private int seconds;
private volatile String phase = "idle";
private long startedMs, firstOffExtra = -1, finalOffExtra = -1, captureStartedNs, captureEndedNs;
private long firstCaptureTimeNs, lastCaptureTimeNs;
private float[] lastPose;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
if (!PERMISSION.equals(intent.getAction()) || pending == null) return;
UsbDevice device = pending;
pending = null;
if (manager.hasPermission(device)) begin(device);
else { busy = false; show("USB permission denied."); }
}
};
private final VitureV2Link.Listener listener = new VitureV2Link.Listener() {
@Override public void onReady() {
readyCallbacks.incrementAndGet();
event("ready", "phase", phase);
handler.post(() -> bootstrapOff());
}
@Override public void onValue(int message, int value) { event("value", "messageId", message, "value", value); }
@Override public void onPose(byte[] raw, float[] q, long timeNs) {
long count = poses.incrementAndGet();
packetBytes.addAndGet(raw.length);
String observedPhase = phase;
synchronized (poseLock) {
lastPose = q.clone();
if ("capture".equals(observedPhase)) {
if (capturePoses.incrementAndGet() == 1) firstCaptureTimeNs = timeNs;
lastCaptureTimeNs = timeNs;
}
}
event("pose", "phase", observedPhase, "count", count, "receiptTimeNs", timeNs,
"sharedXyzw", floats(q), "packetLength", raw.length, "packetBase64", Base64.encodeToString(raw, Base64.NO_WRAP));
}
@Override public void onTracking(boolean active) {
if (active) trackingOn.incrementAndGet(); else trackingOff.incrementAndGet();
event("tracking", "active", active, "phase", phase);
}
@Override public void onLost() {
errors.incrementAndGet();
event("lost", "phase", phase);
handler.post(() -> finishCheck("driver_lost"));
}
};
@Override public void onCreate(Bundle saved) {
super.onCreate(saved);
manager = (UsbManager) getSystemService(USB_SERVICE);
seconds = Math.max(10, Math.min(15, getIntent().getIntExtra("seconds", 12)));
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(24, 24, 24, 24);
Button start = new Button(this);
start.setText("Check production driver on Pro 2");
start.setOnClickListener(view -> select());
layout.addView(start);
Button stop = new Button(this);
stop.setText("Stop and close driver");
stop.setOnClickListener(view -> finishCheck("user_stop"));
layout.addView(stop);
status = new TextView(this);
status.setTextIsSelectable(true);
ScrollView scroll = new ScrollView(this);
scroll.addView(status);
layout.addView(scroll);
setContentView(layout);
if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, new IntentFilter(PERMISSION), Context.RECEIVER_NOT_EXPORTED);
else registerReceiver(receiver, new IntentFilter(PERMISSION));
show("Actual compiled production VitureV2Link. Pro 2 only. Ready, pause 500 ms, capture " + seconds + " s, pause 500 ms, close.");
show("Logs: " + getFilesDir() + "/checks");
if (getIntent().getBooleanExtra("auto", false)) select();
}
@Override protected void onDestroy() {
finishCheck("activity_destroyed");
unregisterReceiver(receiver);
super.onDestroy();
}
private void select() {
if (busy || finishing.get()) { show("A check is already active or complete; reopen the activity for another run."); return; }
List<UsbDevice> matches = new ArrayList<>();
for (UsbDevice device : manager.getDeviceList().values()) {
if (device.getVendorId() == VENDOR && device.getProductId() == PRODUCT) matches.add(device);
}
if (matches.size() != 1) { show("Expected exactly one 35ca:1301 Pro 2; found " + matches.size()); return; }
busy = true;
UsbDevice device = matches.get(0);
if (manager.hasPermission(device)) begin(device);
else {
pending = device;
manager.requestPermission(device, PendingIntent.getBroadcast(this, PRODUCT,
new Intent(PERMISSION).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
}
}
private void begin(UsbDevice device) {
if (finishing.get()) return;
startedMs = SystemClock.elapsedRealtime();
try {
File directory = new File(getFilesDir(), "checks");
if (!directory.isDirectory() && !directory.mkdirs()) throw new IllegalStateException("Could not create log directory");
File file = new File(directory, "driver-check-" + System.currentTimeMillis() + ".jsonl");
journal = new Journal(file);
event("session", "vendorId", VENDOR, "productId", PRODUCT, "captureSeconds", seconds,
"totalLimitMillis", TOTAL_LIMIT_MS, "runtime", new JSONObject(readAsset("runtime-manifest.json")));
show("Recording " + file.getAbsolutePath());
phase = "bootstrap";
handler.postDelayed(() -> finishCheck("watchdog"), TOTAL_LIMIT_MS - CLOSE_RESERVE_MS);
link = VitureV2Link.Companion.open(manager, device, listener);
event("open_returned", "opened", link != null);
if (link == null) { errors.incrementAndGet(); finishCheck("open_failed"); }
} catch (Exception error) {
errors.incrementAndGet();
event("error", "operation", "open", "message", error.toString());
finishCheck("open_error");
}
}
private void bootstrapOff() {
if (finishing.get() || bootstrapHandled) return;
if (link == null) { handler.postDelayed(() -> bootstrapOff(), 5); return; }
bootstrapHandled = true;
try {
firstOffAccepted = link.send(INTERNAL_IMU, new byte[] {0});
long baseline = poses.get();
phase = "bootstrap_off";
event("off_requested", "stage", "bootstrap", "accepted", firstOffAccepted, "poseBaseline", baseline);
if (!firstOffAccepted) { errors.incrementAndGet(); finishCheck("bootstrap_off_rejected"); return; }
handler.postDelayed(() -> {
if (finishing.get()) return;
firstOffExtra = poses.get() - baseline;
event("off_observation", "stage", "bootstrap", "windowMillis", 500, "newPoses", firstOffExtra,
"trackingActive", link.getTrackingActive(), "ready", link.getReady());
if (firstOffExtra != 0 || link.getTrackingActive()) errors.incrementAndGet();
resume();
}, 500);
} catch (Exception error) { fail("bootstrap_off", error); }
}
private void resume() {
try {
phase = "capture";
captureStartedNs = System.nanoTime();
resumeAccepted = link.send(INTERNAL_IMU, new byte[] {1});
event("on_requested", "accepted", resumeAccepted);
if (!resumeAccepted) { errors.incrementAndGet(); finishCheck("resume_rejected"); return; }
show("Capturing production-driver poses for " + seconds + " seconds.");
handler.postDelayed(() -> finalOff(), seconds * 1000L);
} catch (Exception error) { fail("resume", error); }
}
private void finalOff() {
if (finishing.get()) return;
try {
finalOffAccepted = link.send(INTERNAL_IMU, new byte[] {0});
captureEndedNs = System.nanoTime();
long baseline = poses.get();
phase = "final_off";
event("off_requested", "stage", "final", "accepted", finalOffAccepted, "poseBaseline", baseline);
if (!finalOffAccepted) { errors.incrementAndGet(); finishCheck("final_off_rejected"); return; }
handler.postDelayed(() -> {
if (finishing.get()) return;
finalOffExtra = poses.get() - baseline;
event("off_observation", "stage", "final", "windowMillis", 500, "newPoses", finalOffExtra,
"trackingActive", link.getTrackingActive(), "ready", link.getReady());
if (finalOffExtra != 0 || link.getTrackingActive()) errors.incrementAndGet();
finishCheck("completed");
}, 500);
} catch (Exception error) { fail("final_off", error); }
}
private void fail(String operation, Exception error) {
errors.incrementAndGet();
event("error", "operation", operation, "message", error.toString());
finishCheck(operation + "_error");
}
private void finishCheck(String reason) {
if (!busy || !finishing.compareAndSet(false, true)) return;
pending = null;
handler.removeCallbacksAndMessages(null);
phase = "closing";
long badFrames = 0;
try {
if (link != null) { badFrames = link.getBadFrames(); link.close(); }
} catch (Exception error) {
errors.incrementAndGet();
event("error", "operation", "close", "message", error.toString());
} finally {
phase = "closed";
long captureCount = capturePoses.get();
long captureNs = captureEndedNs > captureStartedNs ? captureEndedNs - captureStartedNs : 0;
double rate = 0;
JSONArray finalQ;
synchronized (poseLock) {
if (captureCount > 1 && lastCaptureTimeNs > firstCaptureTimeNs)
rate = (captureCount - 1) * 1_000_000_000.0 / (lastCaptureTimeNs - firstCaptureTimeNs);
finalQ = floats(lastPose);
}
boolean pass = "completed".equals(reason) && errors.get() == 0 && readyCallbacks.get() > 0 &&
firstOffAccepted && resumeAccepted && finalOffAccepted && firstOffExtra == 0 && finalOffExtra == 0 && captureCount > 0 &&
trackingOn.get() >= 2 && trackingOff.get() >= 2 && link != null && !link.getReady() && !link.getTrackingActive();
event("summary", "reason", reason, "pass", pass, "totalMillis", SystemClock.elapsedRealtime() - startedMs,
"poseCount", poses.get(), "capturePoseCount", captureCount, "captureMillis", captureNs / 1_000_000.0,
"sampleRateHz", rate, "readyCallbacks", readyCallbacks.get(), "trackingOnCallbacks", trackingOn.get(),
"trackingOffCallbacks", trackingOff.get(), "errors", errors.get(), "badFrames", badFrames,
"bootstrapOffNewPoses", firstOffExtra, "finalOffNewPoses", finalOffExtra,
"readyAfterClose", link != null && link.getReady(), "trackingAfterClose", link != null && link.getTrackingActive(),
"lastSharedXyzw", finalQ, "packetBytes", packetBytes.get());
if (journal != null) {
try { journal.close(); } catch (Exception error) { Log.e("VitureV2Check", "Log close failed", error); }
}
busy = false;
show("Finished: " + reason + ", pass=" + pass + ", capture poses=" + captureCount + ", rate=" + String.format(java.util.Locale.ROOT, "%.1f", rate) + " Hz.");
}
}
private void event(String type, Object... fields) {
Journal output = journal;
if (output == null) return;
try { output.event(type, fields); }
catch (Exception error) { errors.incrementAndGet(); Log.e("VitureV2Check", "Could not log " + type, error); }
}
private String readAsset(String name) throws Exception {
try (InputStream input = getAssets().open(name); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
for (int count; (count = input.read(buffer)) != -1;) output.write(buffer, 0, count);
return new String(output.toByteArray(), StandardCharsets.UTF_8);
}
}
private static JSONArray floats(float[] values) {
JSONArray result = new JSONArray();
if (values != null) for (float value : values) {
try { result.put((double) value); } catch (Exception ignored) { result.put(JSONObject.NULL); }
}
return result;
}
private void show(String message) {
Log.i("VitureV2Check", message);
runOnUiThread(() -> status.append(message + "\n"));
}
private static final class Journal implements AutoCloseable {
private final BufferedWriter writer;
Journal(File file) throws Exception { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); }
synchronized void event(String type, Object... fields) throws Exception {
JSONObject json = new JSONObject();
json.put("event", type);
json.put("elapsedRealtimeNanos", SystemClock.elapsedRealtimeNanos());
for (int i = 0; i < fields.length; i += 2) json.put((String) fields[i], fields[i + 1]);
writer.write(json.toString());
writer.newLine();
writer.flush();
}
@Override public synchronized void close() throws Exception { writer.close(); }
}
}
+1
View File
@@ -0,0 +1 @@
out/
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.droiddeck.viturev2probe" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
<uses-feature android:name="android.hardware.usb.host" android:required="true" />
<application android:label="VITURE Pro 2 probe" android:debuggable="true" android:allowBackup="false" android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Holger Bartnick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,77 @@
# SDK-free Android VITURE Pro 2 probe
Protocol and the pose test vector are adapted from Holger Bartnick's MIT-licensed
[elasticjava/viture-v2](https://github.com/elasticjava/viture-v2), pinned to commit
`ece8c30485f7d357fefa362ae74f3eabac9b3899`. Consult `LICENSE.upstream` for its license;
the APK also includes this notice at `assets/LICENSE.upstream`.
Sources consulted: upstream `PROTOCOL.md`, runtime `src/lib.rs` and `src/usbfs.rs`.
The upstream document says its protocol was derived from official SDK USB captures
and then verified using an independent implementation. This is third-party
SDK-derived protocol documentation, not a claim of clean-room discovery.
This standalone Java application uses Android's USB host APIs. It includes no
vendor SDK, vendor native library, project Kotlin source, or project SDK trace.
The prior local SDK capture directories and downloaded vendor SDK were excluded
from this work. Its build uses the Java sources and manifest in this directory.
Only VITURE Pro 2 `35ca:1301` (decimal PID 4865), interface 0, is accepted. The
active interface must be HID alternate 0 with exactly two endpoints: one 64-byte
interrupt IN and one 64-byte interrupt OUT. Endpoint addresses come from the
device descriptors. Standard GET_CONFIGURATION and GET_INTERFACE reads identify
the current transport; the probe changes neither setting. The input request is
queued before any protocol command.
The probe queries firmware with `0x3003`, enables either pose at 120 Hz
(`0x0301 [1,2]`) or raw at 120 Hz (`0x0301 [2,2]`), and sends stream off
(`0x0301 [0,0]`) in `finally`. It does not query serial numbers or change display,
brightness, volume, film, or calibration settings. Pose and raw are separate modes.
Every input completion retains its actual byte count and base64 bytes. Decoding
requires the v2 preamble, bounded declared length, byte-sum checksum, and exact
known event payload size. Pose requires finite quaternion components and norm
within 0.05 of 1. Raw samples require finite gyro/acceleration components;
acceleration norm is logged without assuming that moving hardware has a 1 g
reading. Valid frame, pose, raw, malformed frame, and malformed sample counters
remain separate. Device tick units are unknown. Transport completion is not a
firmware ACK; control ACKs are logged independently.
Stream off is attempted on orderly completion, stop, activity destruction, and
caught errors after a stream-enable attempt. Input reads remain active for a
bounded off-response grace period before cancellation. Resource closing does not
depend on successful logging. Process termination, unplugging, or power loss can
prevent cleanup.
Build with `./tools/viture/viture-v2-probe/build.ps1`. SDK discovery uses
`ANDROID_HOME`, `ANDROID_SDK_ROOT`, then `%LOCALAPPDATA%\Android\Sdk`. JDK discovery
uses `JAVA_HOME`, the optional `%USERPROFILE%\.jdks\jbr-17.0.9`, then `javac.exe` on
PATH. Explicit `-Sdk` and `-Java` override discovery. Thirteen protocol checks run
before APK compilation and signing. The APK is written to
`tools/viture/viture-v2-probe/out/viture-v2-probe-debug.apk` and uses the repository
test key. No Gradle dependency or vendor library is required.
After installation, launch the default pose capture:
```powershell
adb shell am start -n com.droiddeck.viturev2probe/.MainActivity --ez auto true --ei seconds 15
```
For raw gyro and accelerometer data, pass `--es mode raw`:
```powershell
adb shell am start -n com.droiddeck.viturev2probe/.MainActivity --ez auto true --es mode raw --ei seconds 15
```
`mode` accepts `pose` or `raw` and defaults to `pose`. Automatic launch defaults to
PID 4865 and interface 0; if supplied, `--ei pid` and `--ei interface` must match
those exact values. `seconds` defaults to 15 and is clamped to 1..30. Descriptor
reads and bounded cleanup add a few seconds around that capture window. Allow
the USB permission dialog once. The UI provides a Pro 2 capture button using the
selected mode and a stop button.
Logs are app-private JSONL files under
`/data/user/0/com.droiddeck.viturev2probe/files/captures/` named
`probe-<wall-time-ms>-pid-4865-if-0.jsonl`.
Use `adb shell run-as com.droiddeck.viturev2probe ls files/captures` to enumerate them
and `adb exec-out run-as com.droiddeck.viturev2probe cat files/captures/<name>` to read.
For another launch with new extras, finish the existing activity or force-stop only
after `session_end` is present so the stream-off cleanup can complete.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Holger Bartnick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+61
View File
@@ -0,0 +1,61 @@
param(
[string]$Sdk,
[string]$Java = $env:JAVA_HOME
)
$ErrorActionPreference = 'Stop'
if (-not $Sdk) {
if ($env:ANDROID_HOME) { $Sdk = $env:ANDROID_HOME }
elseif ($env:ANDROID_SDK_ROOT) { $Sdk = $env:ANDROID_SDK_ROOT }
elseif ($env:LOCALAPPDATA) { $Sdk = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
else { throw 'Set ANDROID_HOME / ANDROID_SDK_ROOT or pass -Sdk.' }
}
if (-not $Java) {
$fallbackJdk = Join-Path $env:USERPROFILE '.jdks\jbr-17.0.9'
$javacCommand = Get-Command javac.exe -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath (Join-Path $fallbackJdk 'bin\javac.exe')) { $Java = $fallbackJdk }
elseif ($javacCommand) { $Java = Split-Path (Split-Path $javacCommand.Source -Parent) -Parent }
}
if (-not $Java -or -not (Test-Path -LiteralPath (Join-Path $Java 'bin\javac.exe'))) {
throw 'Set JAVA_HOME or pass -Java with a JDK containing bin\javac.exe.'
}
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..'))
$output = Join-Path $PSScriptRoot 'out'
$classes = Join-Path $output ('classes-' + [Guid]::NewGuid().ToString('N'))
$testClasses = Join-Path $output ('tests-' + [Guid]::NewGuid().ToString('N'))
$dex = Join-Path $output ('dex-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Force -Path $output, $classes, $testClasses, $dex | Out-Null
$buildTools = Join-Path $Sdk 'build-tools\36.0.0'
$androidJar = Join-Path $Sdk 'platforms\android-34\android.jar'
$unsigned = Join-Path $output 'viture-v2-probe-unsigned.apk'
$aligned = Join-Path $output 'viture-v2-probe-aligned.apk'
$apk = Join-Path $output 'viture-v2-probe-debug.apk'
$classJar = Join-Path $output 'classes.jar'
$source = Join-Path $PSScriptRoot 'src\com\droiddeck\viturev2probe'
$previousJavaHome = $env:JAVA_HOME
try {
$env:JAVA_HOME = $Java
& (Join-Path $Java 'bin\javac.exe') --release 8 -encoding UTF-8 -d $testClasses (Join-Path $source 'Protocol.java') (Join-Path $PSScriptRoot 'tests\com\droiddeck\viturev2probe\ProtocolTest.java')
if ($LASTEXITCODE -ne 0) { throw 'test compilation failed' }
& (Join-Path $Java 'bin\java.exe') -cp $testClasses com.droiddeck.viturev2probe.ProtocolTest
if ($LASTEXITCODE -ne 0) { throw 'protocol tests failed' }
& (Join-Path $Java 'bin\javac.exe') --release 8 -classpath $androidJar -encoding UTF-8 -d $classes (Join-Path $source 'Protocol.java') (Join-Path $source 'MainActivity.java')
if ($LASTEXITCODE -ne 0) { throw 'javac failed' }
& (Join-Path $Java 'bin\jar.exe') cf $classJar -C $classes .
if ($LASTEXITCODE -ne 0) { throw 'jar failed' }
& (Join-Path $buildTools 'd8.bat') --min-api 26 --lib $androidJar --output $dex $classJar
if ($LASTEXITCODE -ne 0) { throw 'd8 failed' }
& (Join-Path $buildTools 'aapt2.exe') link --manifest (Join-Path $PSScriptRoot 'AndroidManifest.xml') -A (Join-Path $PSScriptRoot 'assets') -I $androidJar -o $unsigned --min-sdk-version 26 --target-sdk-version 34
if ($LASTEXITCODE -ne 0) { throw 'aapt2 failed' }
& (Join-Path $Java 'bin\jar.exe') uf $unsigned -C $dex classes.dex
if ($LASTEXITCODE -ne 0) { throw 'APK dex insertion failed' }
& (Join-Path $buildTools 'zipalign.exe') -f 4 $unsigned $aligned
if ($LASTEXITCODE -ne 0) { throw 'zipalign failed' }
& (Join-Path $buildTools 'apksigner.bat') sign --ks (Join-Path $repo 'keystore\testkey.p12') --ks-key-alias testkey --ks-pass pass:android --key-pass pass:android --out $apk $aligned
if ($LASTEXITCODE -ne 0) { throw 'APK signing failed' }
& (Join-Path $buildTools 'apksigner.bat') verify --verbose $apk
if ($LASTEXITCODE -ne 0) { throw 'APK verification failed' }
Get-FileHash -Algorithm SHA256 -LiteralPath $apk
Write-Output $apk
} finally {
$env:JAVA_HOME = $previousJavaHome
}
@@ -0,0 +1,451 @@
package com.droiddeck.viturev2probe;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConfiguration;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Base64;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
public final class MainActivity extends Activity {
private static final String PERMISSION = "com.droiddeck.viturev2probe.USB_PERMISSION";
private static final int VENDOR = 0x35ca;
private static final int PRODUCT = 0x1301;
private static final int INTERFACE = 0;
private static final int BYTE_LIMIT = 4 * 1024 * 1024;
private UsbManager manager;
private TextView status;
private volatile boolean stop;
private boolean busy;
private UsbDevice pending;
private int durationSeconds = 15;
private boolean rawMode;
private boolean invalidMode;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
if (!PERMISSION.equals(intent.getAction()) || pending == null) return;
UsbDevice device = pending;
pending = null;
if (manager.hasPermission(device)) start(device);
else { busy = false; show("USB permission denied."); }
}
};
@Override public void onCreate(Bundle saved) {
super.onCreate(saved);
manager = (UsbManager) getSystemService(USB_SERVICE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(24, 24, 24, 24);
status = new TextView(this);
status.setTextIsSelectable(true);
addButton(layout, "Probe VITURE Pro 2", () -> select(PRODUCT, INTERFACE));
addButton(layout, "Stop and disable stream", () -> stop = true);
ScrollView scroll = new ScrollView(this);
scroll.addView(status);
layout.addView(scroll);
setContentView(layout);
if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, new IntentFilter(PERMISSION), Context.RECEIVER_NOT_EXPORTED);
else registerReceiver(receiver, new IntentFilter(PERMISSION));
String mode = getIntent().getStringExtra("mode");
rawMode = "raw".equals(mode);
invalidMode = mode != null && !rawMode && !"pose".equals(mode);
durationSeconds = Math.max(1, Math.min(30, getIntent().getIntExtra("seconds", 15)));
show("Pro 2 firmware query, " + (rawMode ? "raw" : "pose") + " at 120 Hz, then stream off. Capture window: " + durationSeconds + " s.");
if (invalidMode) show("Invalid mode: use pose or raw.");
show("Logs: " + getFilesDir() + "/captures");
for (UsbDevice device : manager.getDeviceList().values()) {
if (device.getVendorId() == VENDOR && device.getProductId() == PRODUCT)
show(String.format("Attached Pro 2 %04x:%04x, %d interfaces", VENDOR, PRODUCT, device.getInterfaceCount()));
}
if (getIntent().getBooleanExtra("auto", false)) {
select(getIntent().getIntExtra("pid", PRODUCT), getIntent().getIntExtra("interface", INTERFACE));
}
}
private void addButton(LinearLayout layout, String label, Runnable action) {
Button button = new Button(this);
button.setText(label);
button.setOnClickListener(view -> action.run());
layout.addView(button);
}
@Override protected void onDestroy() {
stop = true;
unregisterReceiver(receiver);
super.onDestroy();
}
private void show(String message) {
Log.i("VitureV2Probe", message);
runOnUiThread(() -> status.append(message + "\n"));
}
private void select(int product, int intf) {
if (busy) { show("A probe or permission request is already active."); return; }
if (invalidMode) { show("Probe disabled: use mode pose or raw."); return; }
if (product != PRODUCT || intf != INTERFACE) {
show("This probe requires Pro 2 pid 4865 (0x1301), interface 0."); return;
}
List<UsbDevice> matches = new ArrayList<>();
for (UsbDevice device : manager.getDeviceList().values()) {
if (device.getVendorId() == VENDOR && device.getProductId() == product) matches.add(device);
}
if (matches.size() != 1) { show("Expected one matching device; found " + matches.size()); return; }
busy = true;
stop = false;
UsbDevice device = matches.get(0);
if (manager.hasPermission(device)) start(device);
else {
pending = device;
PendingIntent permission = PendingIntent.getBroadcast(this, product,
new Intent(PERMISSION).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
manager.requestPermission(device, permission);
}
}
private void start(UsbDevice device) {
new Thread(() -> {
File directory = new File(getFilesDir(), "captures");
directory.mkdirs();
File file = new File(directory, "probe-" + System.currentTimeMillis() + "-pid-" + device.getProductId() + "-if-" + INTERFACE + ".jsonl");
try (Journal journal = new Journal(file)) {
show("Recording " + file.getName());
journal.event("session", "vendorId", device.getVendorId(), "productId", device.getProductId(),
"interface", INTERFACE, "seconds", durationSeconds, "wallTimeMillis", System.currentTimeMillis(),
"mode", rawMode ? "raw" : "pose",
"modeSource", getIntent().hasExtra("mode") ? "explicit intent extra" : "default pose",
"requestedStream", rawMode ? "raw_120hz" : "pose_120hz",
"upstreamCommit", "ece8c30485f7d357fefa362ae74f3eabac9b3899", "byteLimitPerInput", BYTE_LIMIT,
"quaternionNormTolerance", 0.05, "timestampMeaning", "host elapsedRealtimeNanos; decoded tick is an uncalibrated device field");
describe(device, journal);
probe(device, journal);
journal.event("session_end", "stoppedByUserOrActivity", stop);
show("Saved " + file.getAbsolutePath());
} catch (Exception error) { show("Probe error: " + error); }
finally { runOnUiThread(() -> busy = false); }
}, "viture-v2-probe").start();
}
private void describe(UsbDevice device, Journal journal) throws Exception {
journal.event("device", "vendorId", device.getVendorId(), "productId", device.getProductId(), "configurationCount", device.getConfigurationCount());
for (int c = 0; c < device.getConfigurationCount(); c++) {
UsbConfiguration configuration = device.getConfiguration(c);
journal.event("configuration", "productId", device.getProductId(), "id", configuration.getId(), "interfaceCount", configuration.getInterfaceCount());
for (int i = 0; i < configuration.getInterfaceCount(); i++) {
UsbInterface intf = configuration.getInterface(i);
journal.event("interface", "productId", device.getProductId(), "configurationId", configuration.getId(),
"interface", intf.getId(), "alternate", intf.getAlternateSetting(), "class", intf.getInterfaceClass(),
"subclass", intf.getInterfaceSubclass(), "protocol", intf.getInterfaceProtocol());
for (int e = 0; e < intf.getEndpointCount(); e++) {
UsbEndpoint endpoint = intf.getEndpoint(e);
journal.event("endpoint", "productId", device.getProductId(), "configurationId", configuration.getId(),
"interface", intf.getId(), "alternate", intf.getAlternateSetting(), "address", endpoint.getAddress(),
"type", endpoint.getType(), "direction", endpoint.getDirection(), "maxPacketSize", endpoint.getMaxPacketSize(), "interval", endpoint.getInterval());
}
}
}
}
private void probe(UsbDevice device, Journal journal) throws Exception {
if (device.getVendorId() != VENDOR || device.getProductId() != PRODUCT) {
journal.event("outcome", "result", "unsupported_product"); return;
}
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) { journal.event("outcome", "result", "open_failed"); return; }
UsbInterface claimed = null;
Pump pump = new Pump(connection, journal);
UsbEndpoint output = null;
boolean readsReady = false;
boolean enableAttempted = false;
String result = "unsupported_transport";
try {
byte[] descriptors = connection.getRawDescriptors();
journal.event("raw_descriptors", "length", descriptors == null ? -1 : descriptors.length, "bytesBase64", encode(descriptors));
byte[] active = new byte[1];
int configRead = connection.controlTransfer(0x80, 8, 0, 0, active, 1, 500);
journal.event("get_configuration", "result", configRead, "configuration", configRead == 1 ? active[0] & 255 : -1);
if (configRead != 1) return;
UsbConfiguration configuration = null;
for (int c = 0; c < device.getConfigurationCount(); c++) {
if (device.getConfiguration(c).getId() == (active[0] & 255)) configuration = device.getConfiguration(c);
}
if (configuration == null) return;
List<UsbInterface> alternatives = new ArrayList<>();
for (int i = 0; i < configuration.getInterfaceCount(); i++) {
if (configuration.getInterface(i).getId() == INTERFACE) alternatives.add(configuration.getInterface(i));
}
byte[] alt = new byte[1];
int altRead = connection.controlTransfer(0x81, 10, 0, INTERFACE, alt, 1, 500);
int activeAlt = altRead == 1 ? alt[0] & 255 : alternatives.size() == 1 && alternatives.get(0).getAlternateSetting() == 0 ? 0 : -1;
journal.event("get_interface", "result", altRead, "alternate", activeAlt,
"evidence", altRead == 1 ? "GET_INTERFACE" : "only advertised alternate zero or unknown");
UsbInterface selected = null;
for (UsbInterface intf : alternatives) if (intf.getAlternateSetting() == activeAlt) selected = intf;
if (selected == null) { journal.event("unsupported", "reason", "selected active interface unavailable"); return; }
if (activeAlt != 0 || selected.getInterfaceClass() != UsbConstants.USB_CLASS_HID || selected.getEndpointCount() != 2) {
journal.event("unsupported", "reason", "Pro 2 requires active HID interface 0 alternate 0 with two endpoints"); return;
}
List<UsbEndpoint> ins = new ArrayList<>();
int outputs = 0;
for (int e = 0; e < selected.getEndpointCount(); e++) {
UsbEndpoint endpoint = selected.getEndpoint(e);
if (endpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT || endpoint.getMaxPacketSize() != 64) continue;
if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) ins.add(endpoint);
else { output = endpoint; outputs++; }
}
if (outputs != 1 || ins.size() != 1) {
output = null;
journal.event("unsupported", "reason", "requires exactly one 64-byte interrupt IN and one 64-byte interrupt OUT",
"eligibleInputs", ins.size(), "eligibleOutputs", outputs);
return;
}
boolean success = connection.claimInterface(selected, false);
journal.event("claim_interface", "force", false, "success", success);
if (!success) {
success = connection.claimInterface(selected, true);
journal.event("claim_interface", "force", true, "success", success);
}
if (!success) { output = null; result = "claim_failed"; return; }
claimed = selected;
for (UsbEndpoint endpoint : ins) {
Input input = new Input(endpoint);
if (!input.request.initialize(connection, endpoint)) { input.request.close(); result = "input_initialize_failed"; return; }
input.request.setClientData(input);
pump.inputs.add(input);
}
readsReady = true;
for (Input input : pump.inputs) readsReady &= pump.queue(input);
journal.event("inputs_started", "allQueued", readsReady, "inputCount", pump.inputs.size(), "outputEndpoint", output.getAddress());
if (!readsReady || stop) { result = "input_queue_failed_or_stopped"; return; }
long deadline = SystemClock.elapsedRealtime() + durationSeconds * 1000L;
pump.send(output, "firmware_query", Protocol.firmware());
pump.until(Math.min(deadline, SystemClock.elapsedRealtime() + 400), true, true);
if (!stop && SystemClock.elapsedRealtime() < deadline) {
enableAttempted = true;
pump.send(output, rawMode ? "raw_120hz_enable" : "pose_120hz_enable", rawMode ? Protocol.raw120() : Protocol.pose120());
pump.until(deadline, true, true);
}
result = pump.validPose > 0 ? "validated_v2_pose" : pump.validRaw > 0 ? "validated_v2_raw" : pump.validFrames > 0 ? "v2_frames_without_validated_imu" : "no_validated_v2_frames";
} catch (Exception error) {
result = "error";
journal.event("error", "message", error.toString());
} finally {
if (enableAttempted && claimed != null && output != null && readsReady) {
try {
for (Input input : pump.inputs) if (!input.pending && input.bytes < BYTE_LIMIT) pump.queue(input);
pump.send(output, "stream_off_finally", Protocol.off());
pump.until(SystemClock.elapsedRealtime() + 200, false, true);
} catch (Exception error) { journal.safeEvent("stream_off_error", "message", error.toString()); }
}
try {
for (Input input : pump.inputs) if (input.pending) {
input.cancelRequested = true;
try { journal.safeEvent("input_cancel", "endpoint", input.endpoint.getAddress(), "success", input.request.cancel()); }
catch (Exception error) { journal.safeEvent("input_cancel_error", "message", error.toString()); }
}
for (Command command : pump.commands) if (command.pending) {
command.cancelRequested = true;
try { journal.safeEvent("command_cancel", "name", command.name, "success", command.request.cancel()); }
catch (Exception error) { journal.safeEvent("command_cancel_error", "message", error.toString()); }
}
try { pump.until(SystemClock.elapsedRealtime() + 100, false, false); } catch (Exception ignored) {}
for (Input input : pump.inputs) {
journal.safeEvent("input_end", "endpoint", input.endpoint.getAddress(), "bytes", input.bytes, "packets", input.packets,
"zeroLengthCompletions", input.zeros, "pendingAtClose", input.pending);
}
if (claimed != null) {
try { journal.safeEvent("release_interface", "success", connection.releaseInterface(claimed)); }
catch (Exception error) { journal.safeEvent("release_interface_error", "message", error.toString()); }
}
} finally {
try { connection.close(); }
finally {
for (Input input : pump.inputs) {
try { input.request.close(); } catch (Exception error) { journal.safeEvent("input_close_error", "message", error.toString()); }
}
for (Command command : pump.commands) {
try { command.request.close(); } catch (Exception error) { journal.safeEvent("command_close_error", "message", error.toString()); }
}
}
}
journal.safeEvent("outcome", "result", result, "validFrames", pump.validFrames, "invalidFrames", pump.invalidFrames,
"validPose", pump.validPose, "validRaw", pump.validRaw, "invalidSamples", pump.invalidSamples,
"firmwareReplies", pump.firmwareReplies, "successfulFirmwareReplies", pump.successfulFirmwareReplies, "controlAcks", pump.controlAcks,
"nonzeroControlStatuses", pump.nonzeroControlStatuses, "streamEnableAttempted", enableAttempted,
"poseEnableAttempted", !rawMode && enableAttempted, "rawEnableAttempted", rawMode && enableAttempted,
"streamOffWriteCompleted", pump.offCompleted);
show("Outcome: " + result + "; valid pose " + pump.validPose + ", raw " + pump.validRaw + ", v2 frames " + pump.validFrames);
}
}
private final class Pump {
final UsbDeviceConnection connection;
final Journal journal;
final List<Input> inputs = new ArrayList<>();
final List<Command> commands = new ArrayList<>();
int validFrames, invalidFrames, validPose, validRaw, invalidSamples, firmwareReplies, successfulFirmwareReplies, controlAcks, nonzeroControlStatuses;
boolean offCompleted;
Pump(UsbDeviceConnection connection, Journal journal) { this.connection = connection; this.journal = journal; }
boolean queue(Input input) throws Exception {
if (input.bytes >= BYTE_LIMIT) return false;
input.buffer.clear();
input.buffer.limit(Math.min(input.buffer.capacity(), BYTE_LIMIT - input.bytes));
input.cancelRequested = false;
input.queued = SystemClock.elapsedRealtimeNanos();
input.pending = input.request.queue(input.buffer);
if (!input.pending) journal.event("input_queue_failed", "endpoint", input.endpoint.getAddress());
return input.pending;
}
void send(UsbEndpoint endpoint, String name, byte[] bytes) throws Exception {
Command command = new Command(name, bytes);
if (!command.request.initialize(connection, endpoint)) { command.request.close(); journal.event("command_initialize_failed", "name", name); return; }
command.request.setClientData(command);
commands.add(command);
command.pending = command.request.queue(command.buffer);
journal.event("command_queued", "name", name, "endpoint", endpoint.getAddress(), "length", bytes.length,
"bytesBase64", encode(bytes), "queued", command.pending);
long deadline = SystemClock.elapsedRealtime() + 400;
while (command.pending && SystemClock.elapsedRealtime() < deadline) step(50, true);
if (command.pending) {
command.cancelRequested = true;
journal.event("command_timeout", "name", name, "cancelled", command.request.cancel());
}
}
void until(long deadline, boolean respectStop, boolean requeueInputs) throws Exception {
while ((!respectStop || !stop) && SystemClock.elapsedRealtime() < deadline) {
step(Math.min(50, Math.max(1, deadline - SystemClock.elapsedRealtime())), requeueInputs);
}
}
void step(long timeout, boolean requeue) throws Exception {
try {
UsbRequest completed = connection.requestWait(timeout);
if (completed == null) throw new IllegalStateException("requestWait returned null");
Object data = completed.getClientData();
if (data instanceof Command) {
Command command = (Command) data;
command.pending = false;
int length = command.buffer.position();
if (command.name.equals("stream_off_finally") && length == command.length) offCompleted = true;
journal.event("command_completion", "name", command.name, "actualLength", length, "expectedLength", command.length,
"afterCancel", command.cancelRequested);
return;
}
Input input = (Input) data;
input.pending = false;
int count = input.buffer.position();
byte[] bytes = new byte[count];
input.buffer.flip();
input.buffer.get(bytes);
input.bytes += count;
if (count > 0) input.packets++; else input.zeros++;
journal.event("input_transfer", "endpoint", input.endpoint.getAddress(), "queueElapsedRealtimeNanos", input.queued,
"length", count, "bytesBase64", encode(bytes), "afterCancel", input.cancelRequested);
if (count > 0) decode(bytes, input.endpoint.getAddress());
if (requeue && input.bytes < BYTE_LIMIT) queue(input);
} catch (TimeoutException ignored) {}
}
void decode(byte[] bytes, int endpoint) throws Exception {
Protocol.Frame frame;
try { frame = Protocol.parse(bytes); }
catch (IllegalArgumentException error) { invalidFrames++; journal.event("invalid_v2_frame", "endpoint", endpoint, "reason", error.getMessage()); return; }
validFrames++;
journal.event("v2_frame", "endpoint", endpoint, "messageId", frame.message, "payloadLength", frame.payload.length);
if (frame.message == Protocol.POSE || frame.message == Protocol.RAW) {
try {
Protocol.Sample sample = frame.message == Protocol.POSE ? Protocol.pose(frame) : Protocol.raw(frame);
if (frame.message == Protocol.POSE) validPose++; else validRaw++;
JSONArray values = new JSONArray();
for (float value : sample.values) values.put((double) value);
journal.event(frame.message == Protocol.POSE ? "valid_pose" : "valid_raw", "endpoint", endpoint,
"tick", sample.tick, "values", values, "norm", sample.norm,
"fields", frame.message == Protocol.POSE ? "qw,qx,qy,qz" : "gyroX,gyroY,gyroZ,accelX,accelY,accelZ");
} catch (IllegalArgumentException error) { invalidSamples++; journal.event("invalid_sample", "endpoint", endpoint, "messageId", frame.message, "reason", error.getMessage()); }
} else if (frame.message == Protocol.FIRMWARE + 0x2000 && frame.payload.length >= 1) {
firmwareReplies++;
String firmware = new String(frame.payload, 1, frame.payload.length - 1, StandardCharsets.US_ASCII).replace("\u0000", "");
if (frame.payload[0] == 0 && !firmware.isEmpty() && firmware.matches("[ -~]+")) successfulFirmwareReplies++;
journal.event("firmware_reply", "endpoint", endpoint, "status", frame.payload[0] & 255, "firmware", firmware);
} else if (frame.message == Protocol.CONTROL + 0x2000 && frame.payload.length == 1) {
controlAcks++;
if (frame.payload[0] != 0) nonzeroControlStatuses++;
journal.event("control_ack", "endpoint", endpoint, "status", frame.payload[0] & 255);
}
}
}
private static final class Input {
final UsbEndpoint endpoint;
final UsbRequest request = new UsbRequest();
final ByteBuffer buffer;
boolean pending, cancelRequested;
int bytes, packets, zeros;
long queued;
Input(UsbEndpoint endpoint) { this.endpoint = endpoint; buffer = ByteBuffer.allocateDirect(Math.max(1, endpoint.getMaxPacketSize())); }
}
private static final class Command {
final String name;
final int length;
final UsbRequest request = new UsbRequest();
final ByteBuffer buffer;
boolean pending, cancelRequested;
Command(String name, byte[] bytes) { this.name = name; length = bytes.length; buffer = ByteBuffer.allocateDirect(length); buffer.put(bytes).flip(); }
}
private static String encode(byte[] bytes) { return bytes == null ? "" : Base64.encodeToString(bytes, Base64.NO_WRAP); }
private static final class Journal implements AutoCloseable {
final BufferedWriter writer;
Journal(File file) throws Exception { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); }
void event(String event, Object... fields) throws Exception {
JSONObject json = new JSONObject();
json.put("event", event);
json.put("elapsedRealtimeNanos", SystemClock.elapsedRealtimeNanos());
for (int i = 0; i < fields.length; i += 2) json.put((String) fields[i], fields[i + 1]);
writer.write(json.toString());
writer.newLine();
writer.flush();
}
void safeEvent(String event, Object... fields) {
try { event(event, fields); } catch (Exception error) { Log.e("VitureV2Probe", "Could not log " + event, error); }
}
@Override public void close() throws Exception { writer.close(); }
}
}
@@ -0,0 +1,85 @@
package com.droiddeck.viturev2probe;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
public final class Protocol {
public static final int FIRMWARE = 0x3003;
public static final int CONTROL = 0x0301;
public static final int POSE = 0x7308;
public static final int RAW = 0x7309;
private Protocol() {}
public static byte[] firmware() { return frame(FIRMWARE, new byte[0]); }
public static byte[] pose120() { return frame(CONTROL, new byte[] {1, 2}); }
public static byte[] raw120() { return frame(CONTROL, new byte[] {2, 2}); }
public static byte[] off() { return frame(CONTROL, new byte[] {0, 0}); }
static byte[] frame(int message, byte[] payload) {
if (payload.length > 56) throw new IllegalArgumentException("payload exceeds upstream 64-byte frame");
ByteBuffer buffer = ByteBuffer.allocate(8 + payload.length).order(ByteOrder.LITTLE_ENDIAN);
int sum = 0;
for (byte value : payload) sum = (sum + (value & 255)) & 65535;
buffer.putShort((short) 0x10).putShort((short) message).putShort((short) payload.length).putShort((short) sum).put(payload);
return buffer.array();
}
public static Frame parse(byte[] data) {
if (data.length < 8) throw new IllegalArgumentException("short_header");
if (u16(data, 0) != 0x10) throw new IllegalArgumentException("preamble");
int length = u16(data, 4);
if (length > 56 || length + 8 > data.length) throw new IllegalArgumentException("payload_length");
int sum = 0;
for (int i = 8; i < 8 + length; i++) sum = (sum + (data[i] & 255)) & 65535;
if (sum != u16(data, 6)) throw new IllegalArgumentException("checksum");
return new Frame(u16(data, 2), Arrays.copyOfRange(data, 8, 8 + length));
}
public static Sample pose(Frame frame) {
if (frame.message != POSE || frame.payload.length != 24) throw new IllegalArgumentException("pose_length_or_id");
float[] values = floats(frame.payload, 8, 4);
double squared = 0;
for (float value : values) squared += (double) value * value;
double norm = Math.sqrt(squared);
if (Math.abs(norm - 1.0) > 0.05) throw new IllegalArgumentException("quaternion_norm");
return new Sample(tick(frame.payload), values, norm);
}
public static Sample raw(Frame frame) {
if (frame.message != RAW || frame.payload.length != 56) throw new IllegalArgumentException("raw_length_or_id");
float[] values = floats(frame.payload, 10, 6);
double accelNorm = Math.sqrt((double) values[3] * values[3] + (double) values[4] * values[4] + (double) values[5] * values[5]);
return new Sample(tick(frame.payload), values, accelNorm);
}
private static float[] floats(byte[] data, int offset, int count) {
ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
float[] values = new float[count];
for (int i = 0; i < count; i++) {
values[i] = buffer.getFloat(offset + i * 4);
if (Float.isNaN(values[i]) || Float.isInfinite(values[i])) throw new IllegalArgumentException("non_finite");
}
return values;
}
private static long tick(byte[] payload) {
return ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).getInt(4) & 0xffffffffL;
}
static int u16(byte[] data, int offset) { return (data[offset] & 255) | ((data[offset + 1] & 255) << 8); }
public static final class Frame {
public final int message;
public final byte[] payload;
Frame(int message, byte[] payload) { this.message = message; this.payload = payload; }
}
public static final class Sample {
public final long tick;
public final float[] values;
public final double norm;
Sample(long tick, float[] values, double norm) { this.tick = tick; this.values = values; this.norm = norm; }
}
}
@@ -0,0 +1,48 @@
package com.droiddeck.viturev2probe;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
public final class ProtocolTest {
private static int checks;
public static void main(String[] args) {
equal(Protocol.firmware(), hex("10 00 03 30 00 00 00 00"));
equal(Protocol.pose120(), hex("10 00 01 03 02 00 03 00 01 02"));
equal(Protocol.raw120(), hex("10 00 01 03 02 00 04 00 02 02"));
equal(Protocol.off(), hex("10 00 01 03 02 00 00 00 00 00"));
byte[] payload = hex("26 01 00 00 59 d6 21 00 dd e3 2b 3e 52 5d 7c 3f dd 45 9a 3b e8 27 52 3a");
byte[] poseFrame = Protocol.frame(Protocol.POSE, payload);
Protocol.Sample sample = Protocol.pose(Protocol.parse(poseFrame));
check(sample.tick == 0x0021d659L && Math.abs(sample.norm - 1) < 0.001);
check(Protocol.pose(Protocol.parse(Arrays.copyOf(poseFrame, 64))).tick == sample.tick);
reject(() -> Protocol.parse(Arrays.copyOf(poseFrame, 31)));
byte[] corrupt = poseFrame.clone();
corrupt[8] ^= 1;
reject(() -> Protocol.parse(corrupt));
reject(() -> Protocol.parse(hex("ff fe 00 00 00 00 00 00")));
reject(() -> Protocol.pose(Protocol.parse(Protocol.frame(Protocol.POSE, new byte[24]))));
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(8, Float.NaN);
reject(() -> Protocol.pose(Protocol.parse(Protocol.frame(Protocol.POSE, payload))));
byte[] raw = new byte[56];
ByteBuffer buffer = ByteBuffer.wrap(raw).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(4, -1).putFloat(10, 0.1f).putFloat(14, 0.2f).putFloat(18, 0.3f).putFloat(30, 1f);
Protocol.Sample rawSample = Protocol.raw(Protocol.parse(Protocol.frame(Protocol.RAW, raw)));
check(rawSample.tick == 0xffffffffL && rawSample.values[0] == 0.1f && rawSample.norm == 1);
buffer.putFloat(30, Float.POSITIVE_INFINITY);
reject(() -> Protocol.raw(Protocol.parse(Protocol.frame(Protocol.RAW, raw))));
System.out.println("Protocol tests passed: " + checks);
}
private static void check(boolean condition) { if (!condition) throw new AssertionError(); checks++; }
private static void equal(byte[] actual, byte[] expected) { check(Arrays.equals(actual, expected)); }
private static void reject(Runnable operation) {
try { operation.run(); } catch (IllegalArgumentException expected) { checks++; return; }
throw new AssertionError("Expected rejection");
}
private static byte[] hex(String text) {
String[] parts = text.split(" ");
byte[] result = new byte[parts.length];
for (int i = 0; i < parts.length; i++) result[i] = (byte) Integer.parseInt(parts[i], 16);
return result;
}
}