Merge current main into PR #1174

This commit is contained in:
Kurt Himebauch committed 2026-10-22 12:13:52 -04:00
commit 0b616146ff
141 files changed
+6310 -274

No files matched your search

@@ -13,6 +13,11 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -232,4 +237,95 @@ class GlassesCallbacksTest {
field("sink").set(null, null)
}
}
@Test fun pro2CallbacksUseSharedPoseAndRejectThePreviousConnection() {
fun v2(gen: Long) = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, gen) as VitureV2Link.Listener
var delivered: FloatArray? = null
var timestamp = 0L
field("sink").set(null, Glasses.PoseSink { x, y, z, w, time ->
delivered = floatArrayOf(x, y, z, w)
timestamp = time
})
try {
val q = floatArrayOf(0f, 0f, 0.6f, 0.8f)
v2(0).onPose(ByteArray(24), q, 100)
assertEquals(null, delivered)
v2(1).onPose(ByteArray(24), q, 101)
org.junit.Assert.assertArrayEquals(q, delivered, 0f)
assertEquals(101L, timestamp)
assertEquals(1L, field("imuPackets").getLong(null))
v2(1).onValue(VitureProtocol.MSG_GET_DISPLAY, 0x32)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.state.value.sbs)
v2(1).onValue(VitureProtocol.MSG_GET_BRIGHTNESS, 8)
v2(1).onReady()
v2(1).onTracking(true)
v2(1).onLost()
generation(2)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(2, Glasses.state.value.brightness)
assertTrue(Glasses.state.value.connected)
assertFalse(Glasses.state.value.supportsScreen3dof)
assertFalse(Glasses.state.value.tracking)
} finally { field("sink").set(null, null) }
}
@Test fun pro2DemandEndingBeforeTheFirstRestartPoseStillStopsTheStream() {
val writes = LinkedBlockingQueue<ByteArray>()
val incoming = LinkedBlockingQueue<VitureV2Link.Received>()
val firstPose = CountDownLatch(1)
val firstRead = CountDownLatch(1)
val delegate = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, 1L) as VitureV2Link.Listener
val listener = object : VitureV2Link.Listener by delegate {
override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) {
delegate.onPose(raw, q, timeNs)
firstPose.countDown()
}
}
val transport = object : VitureV2Link.Transport {
override fun write(packet: ByteArray): Boolean { writes += packet; return true }
override fun read(timeoutMs: Long): VitureV2Link.Received? {
firstRead.countDown()
return incoming.poll(timeoutMs, TimeUnit.MILLISECONDS)
}
override fun close() {}
}
fun expectStream(stream: Int) = org.junit.Assert.assertArrayEquals(
VitureV2Protocol.imuControl(stream), writes.poll(2, TimeUnit.SECONDS))
fun updateImu() = Glasses::class.java.getDeclaredMethod("updateImu")
.apply { isAccessible = true }.invoke(Glasses)
val link = VitureV2Link(transport, listener)
field("link").set(null, link)
field("sink").set(null, null)
try {
expectStream(VitureV2Protocol.STREAM_POSE)
assertTrue("Bootstrap write did not complete", firstRead.await(2, TimeUnit.SECONDS))
val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0).putInt(1).putFloat(1f).putFloat(0f).putFloat(0f).putFloat(0f).array()
incoming += VitureV2Link.Received(VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload), System.nanoTime())
assertTrue(firstPose.await(2, TimeUnit.SECONDS))
shadowOf(Looper.getMainLooper()).idle()
expectStream(VitureV2Protocol.STREAM_OFF)
assertTrue(Glasses.state.value.supportsScreen3dof)
assertFalse(Glasses.state.value.tracking)
field("sink").set(null, Glasses.PoseSink { _, _, _, _, _ -> })
updateImu()
assertFalse(Glasses.state.value.tracking)
field("sink").set(null, null)
updateImu()
expectStream(VitureV2Protocol.STREAM_POSE)
expectStream(VitureV2Protocol.STREAM_OFF)
assertFalse(link.trackingActive)
assertFalse(Glasses.state.value.tracking)
} finally {
generation(2)
link.close()
field("link").set(null, null)
field("sink").set(null, null)
shadowOf(Looper.getMainLooper()).idle()
}
}
}
@@ -155,6 +155,58 @@ class GlassesUsbTest {
assertEquals(listOf(gt), manager.requests)
}
@Test fun pro2RequestsPermissionWithoutTheSdkAndDoesNotClaimCompanionProducts() {
val pro2 = device(0x1301, name = "VITURE Luma Ultra")
manager.devices[pro2.deviceName] = pro2
refresh(ask = true)
assertEquals("VITURE Pro 2", state.value.model)
assertTrue(state.value.controllable)
assertTrue(state.value.experimental)
assertFalse(state.value.hardwareControls)
assertFalse(state.value.supportsDisplayModeControl)
assertFalse(state.value.supportsScreen3dof)
assertFalse(state.value.supportsSpatial)
assertEquals(listOf(pro2), manager.requests)
assertEquals(null, Glasses.deviceModel(device(0x1301, 0x1234, "VITURE Pro 2")))
assertEquals(null, Glasses.deviceModel(device(0x1102, name = "VITURE Pro 2")))
assertEquals(null, Glasses.deviceModel(device(0x1302, name = "VITURE Pro 2")))
val ultra = Glasses.deviceModel(device(0x1104)) as VitureProtocol.Model
assertEquals(VitureProtocol.Family.ULTRA, ultra.family)
assertTrue(ultra.needsSdk)
}
@Test fun pro2PoseAvailabilityDoesNotEnableDisplayOrHardwareWrites() {
val pro2 = device(0x1301)
manager.devices[pro2.deviceName] = pro2
manager.granted.add(pro2.deviceName)
val sent = mutableListOf<Int>()
field("linkDevice").set(null, pro2)
field("link").set(null, object : GlassesLink {
override val hasImu = true
override fun send(msgId: Int, payload: ByteArray): Boolean { sent += msgId; return true }
override fun close() {}
})
try {
refresh()
assertTrue(state.value.canControl)
assertTrue(state.value.supportsScreen3dof)
assertFalse(state.value.can3d)
assertFalse(state.value.supportsDisplayModeControl)
assertFalse(state.value.hardwareControls)
assertEquals(0, state.value.brightnessMax)
assertEquals(0, state.value.volumeMax)
Glasses.sendMode(0x32)
Glasses.setBrightness(5)
Glasses.setVolume(5)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(sent.isEmpty())
} finally {
field("link").set(null, null)
field("linkDevice").set(null, null)
(field("handler").get(null) as Handler).removeCallbacksAndMessages(null)
}
}
@Test fun gtVendorRequestsPermissionAndRetainsMaxProductName() {
val gt = device(0xaf50, 0x3941, "RayNeo GT MAX")
manager.devices[gt.deviceName] = gt
@@ -130,6 +130,31 @@ class VitureProtocolTest {
assertArrayEquals(floatArrayOf(0f, 0f, sin(half).toFloat(), cos(half).toFloat()), q, 1e-5f)
}
@Test fun directPro2KeepsSdkOnlyFamiliesAndUnknownProductsIsolated() {
val direct = VitureProtocol.model(0x1301, "VITURE Luma Ultra")!!
assertEquals("VITURE Pro 2", direct.name)
assertEquals(VitureProtocol.Family.PRO2, direct.family)
assertFalse(direct.needsSdk)
assertFalse(direct.hardwareControls)
assertFalse(direct.supportsDisplayModeControl)
assertFalse(direct.hasSunblock)
assertEquals(0, direct.brightnessMax)
assertEquals(0, direct.volumeMax)
for (pid in listOf(0x1101, 0x1104, 0x1201, 0x1211)) {
val model = VitureProtocol.model(pid, null)!!
assertTrue(model.needsSdk)
assertTrue(model.hardwareControls)
assertTrue(model.supportsDisplayModeControl)
}
assertNull(VitureProtocol.model(0x1102, "VITURE Pro 2"))
assertNull(VitureProtocol.model(0x1302, "VITURE Pro 2"))
val sdk = VitureProtocol.sdkModel("Pro 2")!!
assertTrue(sdk.needsSdk)
assertTrue(sdk.hardwareControls)
assertTrue(sdk.supportsDisplayModeControl)
}
@Test fun imuFallsBackToEuler() {
val payload = ByteBuffer.allocate(12).putFloat(0f).putFloat(0f).putFloat(30f).array()
val q = VitureProtocol.imuQuaternion(payload)!!
@@ -0,0 +1,404 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.math.sqrt
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class VitureV2LinkTest {
private val transport = FakeTransport()
private val listener = RecordingListener()
private var link: VitureV2Link? = null
@After fun close() { link?.close() }
@Test fun writeAndAckDoNotBecomeReadyWithoutAValidPose() {
val link = start()
transport.feed(ack())
transport.feed(pose(1).also { it[8] = (it[8].toInt() xor 1).toByte() })
transport.feed(pose(2, floatArrayOf(0f, 0f, 0f, 0f)))
transport.feed(VitureV2Protocol.packet(VitureV2Protocol.EVENT_RAW, ByteArray(56)))
transport.flush()
assertFalse(link.ready)
assertFalse(link.hasImu)
assertFalse(link.trackingActive)
assertEquals(0, listener.readyCount.get())
assertTrue(listener.poses.isEmpty())
assertEquals(2L, link.badFrames)
val receiptTime = System.nanoTime()
val valid = pose(3)
transport.feed(valid, receiptTime)
transport.flush()
assertTrue(link.ready)
assertTrue(link.hasImu)
assertTrue(link.trackingActive)
assertEquals(1, listener.readyCount.get())
assertEquals(listOf(true), listener.tracking)
assertEquals(1, listener.poses.size)
assertEquals(receiptTime, listener.poses.single().timeNs)
assertArrayEquals(valid, listener.poses.single().raw)
}
@Test fun duplicatesAndBackwardTicksAreDroppedWhileUnsignedWrapAdvances() {
start()
for (tick in listOf(0xFFFFFFFEL, 0xFFFFFFFEL, 0xFFFFFFFDL, 0L, 0L, 0xFFFFFFFFL, 1L)) {
transport.feed(pose(tick))
}
transport.flush()
assertEquals(3, listener.poses.size)
assertEquals(1, listener.readyCount.get())
assertEquals(listOf(true), listener.tracking)
assertEquals(0L, link!!.badFrames)
}
@Test fun poseCollectedDuringBootstrapWriteDoesNotEstablishReadiness() {
transport.collectDuringNextWrite(pose(1))
val link = start()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertTrue(listener.poses.isEmpty())
transport.feed(pose(2))
transport.flush()
assertTrue(link.ready)
assertTrue(link.trackingActive)
assertEquals(1, listener.readyCount.get())
assertEquals(1, listener.poses.size)
}
@Test fun poseCollectedDuringResumeWriteDoesNotRestartTracking() {
val link = startReady(100)
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.flush()
transport.collectDuringNextWrite(pose(101))
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.flush()
assertFalse(link.trackingActive)
assertEquals(1, listener.poses.size)
transport.feed(pose(102))
transport.flush()
assertTrue(link.trackingActive)
assertEquals(2, listener.poses.size)
assertEquals(listOf(true, false, true), listener.tracking)
}
@Test fun stoppingAndRestartingRequiresANewPoseAndRejectsQueuedOldSamples() {
val link = startReady(100)
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0)))
assertFalse(link.trackingActive)
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.feed(pose(101))
transport.feed(ack())
transport.flush()
assertEquals(1, listener.poses.size)
assertTrue(link.ready)
assertFalse(link.trackingActive)
val beforeRestart = System.nanoTime()
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.feed(pose(102), beforeRestart)
transport.feed(ack())
transport.flush()
assertFalse(link.trackingActive)
assertEquals(1, listener.poses.size)
transport.feed(pose(0))
transport.flush()
assertTrue(link.trackingActive)
assertEquals(2, listener.poses.size)
assertEquals(1, listener.readyCount.get())
assertEquals(listOf(true, false, true), listener.tracking)
}
@Test fun onReadyCanStopBootstrapBeforeTheFirstPoseIsForwarded() {
val link = start()
listener.whenReady = { assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) }
transport.feed(pose(1))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.flush()
assertEquals(1, listener.readyCount.get())
assertTrue(link.ready)
assertFalse(link.trackingActive)
assertTrue(listener.poses.isEmpty())
assertEquals(listOf(true, false), listener.tracking)
}
@Test fun rapidStopStartCannotAcceptThePreviousStreamsPendingRead() {
val link = startReady()
val held = transport.hold(pose(2))
try {
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0)))
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
} finally {
held.release.countDown()
}
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.flush()
assertFalse(link.trackingActive)
assertEquals(1, listener.poses.size)
assertEquals(listOf(true, false), listener.tracking)
transport.feed(pose(3))
transport.flush()
assertTrue(link.trackingActive)
assertEquals(2, listener.poses.size)
}
@Test fun onReadyCanCloseWithoutForwardingAPoseOrReportingLoss() {
val link = start()
listener.whenReady = link::close
transport.feed(pose(1))
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertTrue(listener.poses.isEmpty())
assertEquals(0, listener.lostCount.get())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun unsupportedSettersNeverProduceWritesAndQueriesKeepGenericIds() {
val link = startReady()
for ((id, payload) in listOf(
VitureProtocol.MSG_BRIGHTNESS to byteArrayOf(3),
VitureProtocol.MSG_VOLUME to byteArrayOf(3),
VitureProtocol.MSG_DISPLAY to byteArrayOf(0x32),
VitureProtocol.MSG_FILM to byteArrayOf(1),
VitureProtocol.MSG_IMU_RATE to byteArrayOf(3),
VitureProtocol.MSG_IMU to byteArrayOf(2),
VitureProtocol.MSG_IMU to byteArrayOf(),
VitureProtocol.MSG_GET_VOLUME to byteArrayOf(1),
)) assertFalse("msgId=$id", link.send(id, payload))
assertTrue(link.send(VitureProtocol.MSG_GET_IMU, byteArrayOf()))
transport.flush()
assertTrue(transport.writes.isEmpty())
val queries = listOf(
Triple(VitureProtocol.MSG_GET_BRIGHTNESS, VitureV2Protocol.MSG_GET_BRIGHTNESS, 3),
Triple(VitureProtocol.MSG_GET_VOLUME, VitureV2Protocol.MSG_GET_VOLUME, 5),
Triple(VitureProtocol.MSG_GET_DISPLAY, VitureV2Protocol.MSG_GET_DISPLAY, 0x31),
)
for ((genericId, wireId, value) in queries) {
assertTrue(link.send(genericId, byteArrayOf()))
transport.expectWrite(VitureV2Protocol.packet(wireId))
transport.feed(VitureV2Protocol.packet(wireId + VitureV2Protocol.RESPONSE_OFFSET,
byteArrayOf(0, value.toByte())))
}
transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET,
byteArrayOf(1, 7)))
transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET,
byteArrayOf(0, 7, 8)))
transport.flush()
assertEquals(queries.map { it.first to it.third }, listener.values)
}
@Test fun failureToWriteBootstrapClosesTransportAndReportsLoss() {
transport.failNextWrite.set(true)
val link = VitureV2Link(transport, listener).also { this.link = it }
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.hasImu)
assertFalse(link.trackingActive)
assertEquals(0, listener.readyCount.get())
assertEquals(1, listener.lostCount.get())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun rejectedStreamAckClosesWithoutMarkingTrackingActive() {
val link = start()
transport.feed(ack(status = 7))
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertEquals(1, listener.lostCount.get())
assertEquals(0, listener.readyCount.get())
assertTrue(listener.tracking.isEmpty())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun readFailureClearsTrackingAndClosesTransport() {
val link = startReady()
transport.disconnect()
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertEquals(listOf(true, false), listener.tracking)
assertEquals(1, listener.lostCount.get())
assertFalse(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun explicitCloseSendsOffOnceAndDoesNotReportLoss() {
val link = startReady()
link.close()
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertEquals(listOf(true, false), listener.tracking)
assertEquals(0, listener.lostCount.get())
assertEquals(1, transport.closeCount.get())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
link.close()
assertFalse(link.send(VitureProtocol.MSG_GET_BRIGHTNESS, byteArrayOf()))
assertEquals(1, transport.closeCount.get())
assertTrue(transport.writes.isEmpty())
}
@Test fun sharedPoseProducesTheSourceRightUpBackRelativeRotation() {
startReady()
val baseline = listener.poses.single().q
val reference = HeadPose.recenter(HeadPose.fromGlasses(baseline[0], baseline[1], baseline[2], baseline[3]),
centerView = true)
val half = sqrt(0.5f)
val rotations = listOf(
floatArrayOf(half, half, 0f, 0f),
floatArrayOf(half, 0f, half, 0f),
floatArrayOf(half, 0f, 0f, half),
floatArrayOf(0.5f, -0.5f, 0.5f, -0.5f),
)
rotations.forEachIndexed { index, q -> transport.feed(pose(index + 2L, q)) }
transport.flush()
for ((source, event) in rotations.zip(listener.poses.drop(1))) {
val q = event.q
val relative = HeadPose.relative(reference, HeadPose.fromGlasses(q[0], q[1], q[2], q[3]))
assertArrayEquals(HeadPose.fromQuaternion(source[1], source[2], source[3], source[0]), relative, 1e-5f)
}
assertEquals(rotations.size + 1, listener.poses.size)
}
private fun start(): VitureV2Link = VitureV2Link(transport, listener).also {
link = it
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.flush()
}
private fun startReady(tick: Long = 1): VitureV2Link = start().also {
transport.feed(pose(tick))
transport.flush()
assertTrue(it.ready)
}
private fun ack(status: Int = 0) = VitureV2Protocol.packet(
VitureV2Protocol.MSG_IMU_CONTROL + VitureV2Protocol.RESPONSE_OFFSET, byteArrayOf(status.toByte()))
private fun pose(tick: Long, wxyz: FloatArray = floatArrayOf(1f, 0f, 0f, 0f)): ByteArray {
val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0x126).putInt(tick.toInt())
wxyz.forEach(payload::putFloat)
return VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload.array())
}
private data class PoseEvent(val raw: ByteArray, val q: FloatArray, val timeNs: Long)
private class RecordingListener : VitureV2Link.Listener {
val readyCount = AtomicInteger()
val lostCount = AtomicInteger()
val tracking = CopyOnWriteArrayList<Boolean>()
val values = CopyOnWriteArrayList<Pair<Int, Int>>()
val poses = CopyOnWriteArrayList<PoseEvent>()
@Volatile var whenReady: (() -> Unit)? = null
override fun onReady() { readyCount.incrementAndGet(); whenReady?.invoke() }
override fun onValue(msgId: Int, value: Int) { values += msgId to value }
override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) { poses += PoseEvent(raw.copyOf(), q.copyOf(), timeNs) }
override fun onTracking(active: Boolean) { tracking += active }
override fun onLost() { lostCount.incrementAndGet() }
}
private sealed interface ReadStep {
data class Packet(val received: VitureV2Link.Received) : ReadStep
data class Barrier(val reached: CountDownLatch) : ReadStep
data class HeldPacket(
val received: VitureV2Link.Received,
val entered: CountDownLatch = CountDownLatch(1),
val release: CountDownLatch = CountDownLatch(1),
) : ReadStep
data object Disconnected : ReadStep
}
private class FakeTransport : VitureV2Link.Transport {
val writes = LinkedBlockingQueue<ByteArray>(64)
val closeCount = AtomicInteger()
val failNextWrite = AtomicBoolean()
private val collectedDuringWrite = AtomicReference<ByteArray?>()
private val incoming = LinkedBlockingQueue<ReadStep>(128)
private val closed = CountDownLatch(1)
override fun write(packet: ByteArray): Boolean {
check(writes.offer(packet.copyOf()))
val success = !failNextWrite.getAndSet(false)
if (success) collectedDuringWrite.getAndSet(null)?.let { feed(it, System.nanoTime()) }
return success
}
override fun read(timeoutMs: Long): VitureV2Link.Received? = when (
val step = incoming.poll(timeoutMs, TimeUnit.MILLISECONDS)
) {
is ReadStep.Packet -> step.received
is ReadStep.Barrier -> { step.reached.countDown(); null }
is ReadStep.HeldPacket -> {
step.entered.countDown()
check(step.release.await(2, TimeUnit.SECONDS))
step.received
}
ReadStep.Disconnected -> throw IOException("Device disconnected")
null -> null
}
override fun close() { closeCount.incrementAndGet(); closed.countDown() }
fun feed(packet: ByteArray, timeNs: Long = System.nanoTime()) {
check(incoming.offer(ReadStep.Packet(VitureV2Link.Received(packet.copyOf(), timeNs))))
}
fun collectDuringNextWrite(packet: ByteArray) {
check(collectedDuringWrite.compareAndSet(null, packet.copyOf()))
}
fun disconnect() { check(incoming.offer(ReadStep.Disconnected)) }
fun hold(packet: ByteArray): ReadStep.HeldPacket {
val held = ReadStep.HeldPacket(VitureV2Link.Received(packet.copyOf(), System.nanoTime()))
check(incoming.offer(held))
assertTrue("Worker did not enter the held read", held.entered.await(2, TimeUnit.SECONDS))
return held
}
fun expectWrite(expected: ByteArray) {
assertArrayEquals(expected, writes.poll(2, TimeUnit.SECONDS))
}
fun flush() {
val reached = CountDownLatch(1)
check(incoming.offer(ReadStep.Barrier(reached)))
assertTrue("Worker did not consume queued reports", reached.await(2, TimeUnit.SECONDS))
}
fun awaitClosed() { assertTrue("Transport did not close", closed.await(2, TimeUnit.SECONDS)) }
}
}
@@ -0,0 +1,175 @@
// Fixtures adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
package com.droiddeck.launcher.glasses
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sqrt
class VitureV2ProtocolTest {
@Test fun requestsMatchUpstreamWireExamples() {
assertArrayEquals(hex("10 00 01 03 02 00 03 00 01 02"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
assertArrayEquals(hex("10 00 01 03 02 00 04 00 02 02"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW))
assertArrayEquals(hex("10 00 01 03 02 00 00 00 00 00"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
assertArrayEquals(hex("10 00 22 31 00 00 00 00"),
VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_BRIGHTNESS))
}
@Test fun requestBoundsAndStreamLimitsAreEnforced() {
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(-1) }
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0x10000) }
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0, ByteArray(57)) }
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.imuControl(3) }
assertThrows(IllegalArgumentException::class.java) {
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE, VitureV2Protocol.Rate.HZ_500)
}
assertArrayEquals(hex("10 00 01 03 02 00 07 00 02 05"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW, VitureV2Protocol.Rate.HZ_1000))
val maximum = VitureV2Protocol.packet(0xFFFF, ByteArray(56) { 0xFF.toByte() })
assertEquals(64, maximum.size)
assertEquals(0x37C8, (maximum[6].toInt() and 0xFF) or ((maximum[7].toInt() and 0xFF) shl 8))
assertNotNull(VitureV2Protocol.parse(maximum))
}
@Test fun brightnessReplyMatchesUpstreamAndKeepsFailureStatus() {
val frame = VitureV2Protocol.parse(hex("10 00 22 51 02 00 03 00 00 03"))!!
val reply = VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_BRIGHTNESS)!!
assertTrue(reply.success)
assertEquals(0, reply.status)
assertArrayEquals(byteArrayOf(3), reply.body)
assertNull(VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_VOLUME))
assertNull(VitureV2Protocol.reply(frame, -1))
val failure = VitureV2Protocol.parse(hex("10 00 01 23 01 00 07 00 07"))!!
val failedReply = VitureV2Protocol.reply(failure, VitureV2Protocol.MSG_IMU_CONTROL)!!
assertFalse(failedReply.success)
assertEquals(7, failedReply.status)
assertTrue(failedReply.body.isEmpty())
val noStatus = VitureV2Protocol.parse(hex("10 00 01 23 00 00 00 00"))!!
assertNull(VitureV2Protocol.reply(noStatus, VitureV2Protocol.MSG_IMU_CONTROL))
}
@Test fun validatesReceiveBoundsBeforeReadingHeader() {
val valid = hex("10 00 22 51 02 00 03 00 00 03")
for (size in listOf(-1, 0, 7, 9, 11, 65, Int.MAX_VALUE)) {
assertNull("size=$size", VitureV2Protocol.parse(valid, size))
}
assertNull(VitureV2Protocol.parse(ByteArray(0)))
assertNull(VitureV2Protocol.parse(valid.copyOf(65)))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[0] = 0x11 }))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[1] = 1 }))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[6] = 0xFF.toByte() }))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[9] = 4 }))
}
@Test fun rejectsOversizedAndTruncatedDeclaredPayloads() {
val valid = hex("10 00 22 51 02 00 03 00 00 03")
assertNull(VitureV2Protocol.parse(valid.copyOf(9)))
val tooLong = valid.copyOf(64).also { it[4] = 57 }
assertNull(VitureV2Protocol.parse(tooLong))
tooLong[4] = 0xFF.toByte()
tooLong[5] = 0xFF.toByte()
assertNull(VitureV2Protocol.parse(tooLong))
val padded = valid.copyOf(64)
val parsed = VitureV2Protocol.parse(padded)!!
assertArrayEquals(byteArrayOf(0, 3), parsed.payload)
padded[9] = 8
assertArrayEquals(byteArrayOf(0, 3), parsed.payload)
}
@Test fun poseFixturePreservesDeviceCounterAndConvertsWxyzToNormalizedXyzw() {
val frame = VitureV2Protocol.parse(hex(
"10 00 08 73 18 00 9c 08 " +
"26 01 00 00 59 d6 21 00 dd e3 2b 3e 52 5d 7c 3f dd 45 9a 3b e8 27 52 3a"
))!!
val pose = VitureV2Protocol.pose(frame)!!
assertEquals(0x0021D659L, pose.deviceTick)
assertEquals(0x126L, pose.unknown)
val expected = floatArrayOf(Float.fromBits(0x3F7C5D52), Float.fromBits(0x3B9A45DD),
Float.fromBits(0x3A5227E8), Float.fromBits(0x3E2BE3DD))
val norm = sqrt(expected.sumOf { it.toDouble() * it }).toFloat()
assertArrayEquals(expected.map { it / norm }.toFloatArray(), pose.quaternion, 1e-7f)
assertEquals(1.0, pose.quaternion.sumOf { it.toDouble() * it }, 1e-6)
}
@Test fun poseNormalizesSmallScaleErrorsWithoutChangingAxesOrCounter() {
val payload = posePayload(0.5f, -0.5f, 0.5f, -0.5f)
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putInt(4, -1)
val pose = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload))!!
assertEquals(0xFFFFFFFFL, pose.deviceTick)
assertArrayEquals(floatArrayOf(-0.5f, 0.5f, -0.5f, 0.5f), pose.quaternion, 0f)
val scaled = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(1.01f, 0f, 0f, 0f)))!!
assertArrayEquals(floatArrayOf(0f, 0f, 0f, 1f), scaled.quaternion, 1e-7f)
}
@Test fun rejectsMalformedPoseAndInvalidQuaternions() {
val valid = posePayload(1f, 0f, 0f, 0f)
assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_RAW, valid)))
for (size in listOf(0, 23, 25, 56)) {
assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, valid.copyOf(size))))
}
for (bad in listOf(0f, 0.5f, 2f, Float.MAX_VALUE, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) {
assertNull("w=$bad", VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(bad, 0f, 0f, 0f))))
}
for (component in 1..3) {
val payload = valid.copyOf()
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(8 + component * 4, Float.NaN)
assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload)))
}
}
@Test fun rawReadsUnalignedFloatsAndPreservesUnknownBytes() {
val payload = rawPayload()
val frame = event(VitureV2Protocol.EVENT_RAW, payload)
val sample = VitureV2Protocol.raw(frame)!!
assertEquals(0xFFFFFFFEL, sample.deviceTick)
assertArrayEquals(floatArrayOf(1.5f, -2f, 0.25f), sample.gyroRadPerSec, 0f)
assertArrayEquals(floatArrayOf(0.0024f, -0.3221f, -0.9287f), sample.accelG, 0f)
assertArrayEquals(payload, sample.payload)
frame.payload.fill(0)
assertArrayEquals(payload, sample.payload)
}
@Test fun rejectsMalformedRawAndNonfiniteMeasurementsButKeepsOpaqueTail() {
val payload = rawPayload()
assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_POSE, payload)))
for (size in listOf(0, 24, 33, 34, 55)) {
assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload.copyOf(size))))
}
for (offset in listOf(10, 14, 18, 22, 26, 30)) {
for (bad in listOf(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) {
val invalid = payload.copyOf()
ByteBuffer.wrap(invalid).order(ByteOrder.LITTLE_ENDIAN).putFloat(offset, bad)
assertNull("offset=$offset, value=$bad", VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, invalid)))
}
}
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(46, Float.NaN)
assertNotNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload)))
}
private fun event(msgId: Int, payload: ByteArray) =
VitureV2Protocol.parse(VitureV2Protocol.packet(msgId, payload))!!
private fun posePayload(w: Float, x: Float, y: Float, z: Float) =
ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0x126).putInt(123).putFloat(w).putFloat(x).putFloat(y).putFloat(z).array()
private fun rawPayload() = ByteBuffer.allocate(56).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0x126).putInt(-2).putShort(187)
.putFloat(1.5f).putFloat(-2f).putFloat(0.25f)
.putFloat(0.0024f).putFloat(-0.3221f).putFloat(-0.9287f)
.putFloat(117.30f).putFloat(60.75f).putFloat(254.85f)
.put(byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).array()
private fun hex(value: String) = value.split(' ').map { it.toInt(16).toByte() }.toByteArray()
}
@@ -9,7 +9,7 @@ class GpuDetectionTest {
private fun info(adreno: Boolean, model: Int) =
GpuInfo(name = "x", model = model, family = GpuInfo.familyOf(adreno, model), soc = "", oneUi8Gen2 = false)
@Test fun modelIsTheFirstThreeDigitsOfWhateverTheKernelOrVulkanReports() {
@Test fun modelIsParsedOnlyFromAnAdrenoName() {
assertEquals(650, GpuInfo.threeDigits("Adreno650"))
assertEquals(830, GpuInfo.threeDigits("Adreno (TM) 830"))
assertEquals(740, GpuInfo.threeDigits("Adreno740v2"))
@@ -19,6 +19,12 @@ class GpuDetectionTest {
assertEquals(0, GpuInfo.threeDigits(" "))
assertEquals(0, GpuInfo.threeDigits("Adreno"))
assertEquals(0, GpuInfo.threeDigits("Adreno 65"))
assertEquals(850, GpuInfo.threeDigits("Adreno850v2"))
assertEquals(850, GpuInfo.threeDigits("Adreno (TM) 850"))
assertEquals(0, GpuInfo.threeDigits("44051431"))
assertEquals(0, GpuInfo.threeDigits("0x2a02be7"))
assertEquals(0, GpuInfo.threeDigits("Adreno 8500"))
assertEquals(0, GpuInfo.threeDigits("Mali-G850"))
}
@Test fun nonAdrenoRenderersAreNeverAdrenoWhateverNumberTheyCarry() {
@@ -53,12 +59,14 @@ class GpuDetectionTest {
assertEquals(Support.TESTED, info(true, 740).support)
assertEquals(Support.TESTED, info(true, 750).support)
assertEquals(Support.TESTED, info(true, 830).support)
assertEquals(Support.UNTESTED, info(true, 850).support)
assertEquals(Support.UNSUPPORTED, info(false, 0).support)
assertEquals(Support.UNSUPPORTED, info(false, 830).support)
}
@Test fun userFacingTextPerTier() {
assertEquals("Supported", info(true, 830).supportText)
assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", info(true, 850).supportText)
assertEquals("Experimental: its drivers are test builds", info(true, 720).supportText)
assertEquals("Outside tested hardware (Adreno 650, 725 and newer): it may not run", info(true, 618).supportText)
assertEquals("Not supported: DroidDeck needs an Adreno (Snapdragon) GPU", info(false, 0).supportText)
@@ -11,4 +11,61 @@ class GpuModelFallbackTest {
assertEquals(0, GpuInfo.platformModel("somethingelse"))
assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("pineapple")))
}
@Test fun sm8975IsTheOnlyNewSocFallback() {
assertEquals(850, GpuInfo.platformModel("unknown", "", "SM8975"))
assertEquals(850, GpuInfo.platformModel("unknown", "", "QTI SM8975"))
assertEquals(850, GpuInfo.platformModel("unknown", "QTI SM8975", ""))
assertEquals(850, GpuInfo.platformModel("unknown", "", " qti sm8975 "))
assertEquals(0, GpuInfo.platformModel("unknown", "", "SM89750"))
assertEquals(0, GpuInfo.platformModel("unknown", "", "SM8975-PRO"))
assertEquals(0, GpuInfo.platformModel("unknown", "", "Qualcomm SM8975"))
assertEquals(0, GpuInfo.platformModel("unknown", "", "SM8850"))
assertEquals(850, GpuInfo.platformModel("sun", "", "SM8975"))
assertEquals(830, GpuInfo.platformModel("sun", "", "unknown"))
}
@Test fun aKernelModelDoesNotNeedVulkanOrSocFallback() {
assertEquals(850 to "kernel", GpuInfo.modelFromNames("Adreno850v2",
{ error("Vulkan must not be queried when the kernel identifies the GPU") },
{ error("SoC must not override the kernel model") }))
}
@Test fun aMissingKernelModelUsesVulkanBeforeSocFallback() {
assertEquals(830 to "vulkan", GpuInfo.modelFromNames("Adreno", { "Adreno (TM) 830" },
{ error("SoC must not override the Vulkan model") }))
assertEquals(850 to "vulkan", GpuInfo.modelFromNames(null, { "Adreno850v2" }, { 0 }))
}
@Test fun numericChipIdsCannotHideTheSocFallback() {
for (name in listOf(null, "", "Adreno", "44051431", "0x2a02be7")) {
assertEquals(850 to "platform", GpuInfo.modelFromNames(name, { "Adreno" },
{ GpuInfo.platformModel("unknown", "", "QTI SM8975") }))
}
assertEquals(0 to "", GpuInfo.modelFromNames(null, { null }, { 0 }))
}
@Test fun sm8975StaysExperimentalWhenTheDriverReportsA840() {
val fallback = GpuInfo.platformModel("sun", "", "SM8975")
for (kernel in listOf("Adreno", "Adreno (TM) 840")) {
val (model, source) = GpuInfo.modelFromNames(kernel, { "Adreno (TM) 840" }, { fallback })
val gpu = GpuInfo("Adreno $model", model, GpuInfo.familyOf(true, model), "SM8975", false,
modelSource = source, platformGpuModel = fallback)
assertEquals(840, gpu.model)
assertEquals(if (kernel == "Adreno") "vulkan" else "kernel", gpu.modelSource)
assertEquals(GpuInfo.Support.UNTESTED, gpu.support)
assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", gpu.supportText)
}
}
@Test fun anA840WithoutSm8975KeepsItsExistingSupportStatus() {
for (fallback in listOf(0, 830, 840)) {
val gpu = GpuInfo("Adreno 840", 840, GpuInfo.Family.A8XX, "", false,
platformGpuModel = fallback)
assertEquals(GpuInfo.Support.TESTED, gpu.support)
assertEquals("Supported", gpu.supportText)
}
val otherGpu = GpuInfo("Mali", 0, GpuInfo.Family.NOT_ADRENO, "", false,
platformGpuModel = 850)
assertEquals(GpuInfo.Support.UNSUPPORTED, otherGpu.support)
}
}
@@ -21,4 +21,13 @@ class SocNamesTest {
assertEquals("Snapdragon 8 Gen 3 family (SG8350P)", SocNames.label("SG8350P", "pineapple"))
assertEquals("XYZ123", SocNames.label("XYZ123", ""))
}
@Test fun qtiPrefixIsNormalizedWithoutGuessingOtherModelVariants() {
assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("SM8975", ""))
assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("QTI SM8975", ""))
assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name(" qti sm8975 ", ""))
assertEquals("Snapdragon 8 Elite Extreme Gen 6 (QTI SM8975)", SocNames.label("QTI SM8975", ""))
assertNull(SocNames.name("SM89750", ""))
assertNull(SocNames.name("SM8975-PRO", ""))
assertNull(SocNames.name("Qualcomm SM8975", ""))
}
}
@@ -30,4 +30,17 @@ class TurnipDriverAutoTest {
@Test fun otherDevicesRetainTheGenericFallback() {
assertEquals("turnip25.1.0", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
}
@Test fun normalizedGpuModelsSelectExistingGenerationDrivers() {
for (sdk in listOf(28, 36)) {
assertEquals("turnip26.3.0-a6xx", TurnipDriver.chooseByModel(650, sdk))
assertEquals("turnip25.1.0", TurnipDriver.chooseByModel(730, sdk))
assertEquals("turnip-sdk36", TurnipDriver.chooseByModel(850, sdk))
}
}
@Test fun unknownGpuModelsRetainTheSdkFallback() {
assertEquals("turnip25.1.0", TurnipDriver.chooseByModel(0, 28))
assertEquals("turnip-sdk36", TurnipDriver.chooseByModel(0, 36))
}
}
@@ -40,6 +40,33 @@ class SessionDisplayTest {
assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080))
}
private fun unfoldedWanted(
enabled: Boolean = true,
controller: Boolean = false,
keepWithController: Boolean = false,
foldable: Boolean = true,
steamDeckPad: Boolean = true,
pip: Boolean = false,
smallestWidthDp: Int = 700,
) = SessionDisplay.unfoldedControlsWanted(enabled, foldable, controller, keepWithController, steamDeckPad, pip,
2448, 1848, smallestWidthDp)
@Test fun unfoldedControlsHideForAControllerUnlessKeptWithOne() {
assertTrue(unfoldedWanted())
assertFalse(unfoldedWanted(controller = true))
assertTrue(unfoldedWanted(controller = true, keepWithController = true))
assertTrue(unfoldedWanted(keepWithController = true))
}
@Test fun keepingUnfoldedControlsWithAControllerLeavesTheOtherConditions() {
assertFalse(unfoldedWanted(enabled = false, controller = true, keepWithController = true))
assertFalse(unfoldedWanted(foldable = false, keepWithController = true))
assertFalse(unfoldedWanted(steamDeckPad = false, keepWithController = true))
assertFalse(unfoldedWanted(pip = true, keepWithController = true))
assertFalse(unfoldedWanted(smallestWidthDp = 599, keepWithController = true))
assertFalse(SessionDisplay.unfoldedControlsWanted(true, true, true, true, true, false, 0, 1848, 700))
}
@Test fun followScreenKeepsTheWindowShapeAndSkipsTinyWindows() {
assertEquals(2520 to 1080, SessionDisplay.resolveChoice(1080 to 2520, SessionDisplay.FOLLOW_SCREEN))
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class SessionVisibilityPolicyTest {
@Test fun handsetScreenStateControlsActivityOnDefaultDisplay() {
assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false))
assertTrue(SessionVisibilityPolicy.isHidden(true, false, true, true))
}
@Test fun externalDisplayStateControlsActivityIndependentlyOfHandset() {
assertFalse(SessionVisibilityPolicy.isHidden(true, false, false, true))
assertTrue(SessionVisibilityPolicy.isHidden(true, true, false, false))
}
@Test fun missingActivityDisplayIsHiddenUntilActivityMoves() {
assertTrue(SessionVisibilityPolicy.isHidden(true, true, false, false))
assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false))
}
@Test fun stoppedActivityIsHiddenButVisibleXrKeepsSessionVisible() {
assertTrue(SessionVisibilityPolicy.isHidden(false, true, true, true))
assertFalse(SessionVisibilityPolicy.isHidden(false, false, true, false, xrActivityVisible = true))
}
}
@@ -27,6 +27,7 @@ class SettingsResetTest {
@Test fun settingsGoBackToTheirDefaults() {
SessionPrefs.setTheme(app, "ocean")
SessionPrefs.setUnfoldedControlsWithController(app, true)
SessionPrefs.setNoXalia(app, false)
SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30)
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
@@ -45,6 +46,7 @@ class SettingsResetTest {
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
assertEquals("graphite", SessionPrefs.theme(app))
assertFalse(SessionPrefs.unfoldedControlsWithController(app))
assertTrue(SessionPrefs.noXalia(app))
assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
@@ -30,6 +30,21 @@ import org.robolectric.annotation.Config
class GlassesPanelTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun trackingOnlyDeviceHidesDisplayWritesButKeepsHeadTracking() {
show(supportsDisplayModeControl = false)
compose.onNodeWithTag("setting-glasses-hz").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-resolution-two_d").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-3d").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-3dof").assertExists()
}
@Test fun trackingOnlyDeviceHidesVrDisplayWrites() {
show(supportsDisplayModeControl = false, tab = GlassesTab.VR, steamVrRunning = true)
compose.onNodeWithTag("setting-glasses-resolution-vr").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-3d-hz").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-auto3d").assertDoesNotExist()
}
@Test fun flatResolutionMenuShowsPerEyeResolutionsBesideRefresh() {
show()
compose.onNodeWithTag("setting-glasses-hz").assertExists()
@@ -397,6 +412,7 @@ class GlassesPanelTest {
outputActive: Boolean = inSession,
controlAvailable: Boolean = true,
supportsScreen3dof: Boolean = true,
supportsDisplayModeControl: Boolean = true,
supportsSpatial: Boolean = false,
supports30Hz: Boolean = false,
sbs90: Boolean = true,
@@ -406,6 +422,7 @@ class GlassesPanelTest {
onRecenter: (() -> Unit)? = {},
) {
val state = GlassesState(present = true, connected = controlAvailable, controllable = true,
supportsDisplayModeControl = supportsDisplayModeControl,
displayId = Display.DEFAULT_DISPLAY + 1, width = if (stereo) 3840 else 1920, height = 1200,
model = "VITURE Luma Ultra", sbs = stereo, sbs90 = sbs90, supportsScreen3dof = supportsScreen3dof,
supports30Hz = supports30Hz, supportsSpatial = supportsSpatial, resolutions = listOf(
@@ -0,0 +1,100 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.*
import androidx.compose.foundation.layout.size
import androidx.compose.ui.unit.dp
import org.junit.Rule
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class NavigationSelectionTest {
@get:Rule val compose = createRobolectricComposeRule()
@Before fun controlAnimationFrames() {
compose.mainClock.autoAdvance = false
}
@Test fun tabStripAnnouncesSelectionAndUpdatesAfterClick() {
val selected = mutableIntStateOf(0)
compose.setContent { DroidDeckTheme { TabStrip(listOf("First", "Second"), selected.intValue, { selected.intValue = it }) } }
verify("First", "Second")
}
@Test fun sheetChipsAnnounceSelectionAndUpdateAfterClick() {
val selected = mutableIntStateOf(0)
compose.setContent { DroidDeckTheme { SheetChips(listOf("First", "Second"), selected.intValue) { selected.intValue = it } } }
verify("First", "Second")
}
@Test fun segmentedTabsHaveOneTabRoleAndAnnounceTheirGroup() {
val selected = mutableIntStateOf(0)
compose.setContent { DroidDeckTheme { SegmentedTabs(listOf(0 to "First", 1 to "Second"), selected.intValue) { selected.intValue = it } } }
verify("First", "Second")
}
@Test fun sideRailExposesSelectionEvenWhenOnlyIconsAreVisible() {
val selected = mutableStateOf("steam")
Hops.railPreview = null
compose.setContent {
DroidDeckTheme {
SideRail(FrontEndState(
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "",
romsDir = null, logsEnabled = false, steamGames = emptyList(), emulators = emptyList(), running = null,
), selected.value, { selected.value = it }, {}, actions, Modifier.size(300.dp, 600.dp))
}
}
compose.mainClock.advanceTimeBy(1_000)
val steam = compose.onNodeWithTag("rail-steam")
val games = compose.onNodeWithTag("rail-games")
assertTab(steam, true)
assertTab(games, false)
games.performClick()
compose.mainClock.advanceTimeBy(1_000)
assertTab(steam, false)
assertTab(games, true)
assertGroup()
}
private fun verify(first: String, second: String) {
compose.mainClock.advanceTimeBy(1_000)
val a = compose.onNodeWithText(first)
val b = compose.onNodeWithText(second)
assertTab(a, true)
assertTab(b, false)
b.performClick()
compose.mainClock.advanceTimeBy(1_000)
assertTab(a, false)
assertTab(b, true)
assertGroup()
}
private fun assertTab(node: SemanticsNodeInteraction, selected: Boolean) {
node.assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab)).assertHasClickAction()
if (selected) node.assertIsSelected() else node.assertIsNotSelected()
}
private fun assertGroup() {
compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.SelectableGroup)).assertCountEquals(1)
}
private val actions = FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {},
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
)
}
@@ -0,0 +1,158 @@
package com.droiddeck.launcher.ui
import android.hardware.display.DisplayManager
import android.hardware.input.InputManager
import android.view.Display
import android.view.InputDevice
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.compose.ui.test.*
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.input.PadBridgeRoutingTest
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.shadows.InputDeviceBuilder
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w800dp-h600dp")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class SessionSecondScreenTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
private var previousMode = ""
private var previousDeckPad = false
@Before fun setUp() {
previousMode = SessionState.mode
previousDeckPad = SessionState.deckPad
SessionState.deckPad = false
}
@After fun tearDown() {
SessionState.mode = previousMode
SessionState.deckPad = previousDeckPad
}
@Test fun desktopMenuOffersTheExistingTrackpadAndTerminal() = checkModes(steam = false)
@Test fun steamMenuKeepsTheExistingTrackpadAndTerminal() = checkModes(steam = true)
@Test fun desktopWithoutASecondDisplayFallsBackToController() {
SessionState.mode = SessionService.MODE_DESKTOP
var page = SessionDrawerPage.SECOND_SCREEN
compose.setContent {
DroidDeckTheme {
SessionDrawer(true, page, false, { page = it }, actions(false, emptyList()))
}
}
compose.runOnIdle { assertEquals(SessionDrawerPage.CONTROLLER, page) }
compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertDoesNotExist()
}
@Test fun desktopTrackpadOmitsSteamShortcuts() = checkShortcuts(steam = false)
@Test fun steamTrackpadKeepsWorkingSteamShortcuts() = checkShortcuts(steam = true)
@Test
@Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
fun controllerBumpersReachTheSecondScreenInBothSessionModes() {
val device = InputDeviceBuilder.newBuilder().setId(42).setName("Second screen test pad")
.setDescriptor("second-screen-pad").setExternal(true).setSources(InputDevice.SOURCE_GAMEPAD).build()
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
for (mode in listOf(SessionService.MODE_DESKTOP, SessionService.MODE_STEAM)) {
SessionState.mode = mode
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
fun <T> state(name: String): MutableState<T> = ReflectionHelpers.getField(activity, "$name\$delegate")
state<Boolean>("drawerOpen").value = true
state<Boolean>("drawerControllerActive").value = true
state<List<SecondScreenDisplay>>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen"))
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN,
KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) {
assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0,
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)))
assertEquals(page, state<SessionDrawerPage>("drawerPage").value)
}
}
}
private fun checkModes(steam: Boolean) {
SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP
val selected = mutableListOf<SecondScreenMode>()
val displays = listOf(SecondScreenDisplay(1, "Bottom screen"))
compose.setContent {
DroidDeckTheme {
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it })
}
}
for (mode in listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)) {
compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick()
}
compose.onNodeWithText(context.getString(SecondScreenMode.DECK_CONTROLS.label)).assertDoesNotExist()
assertEquals(listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL), selected)
}
private fun checkShortcuts(steam: Boolean) {
SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
var menus = 0
var qams = 0
val panel = SecondScreenPresentation(activity, display, { _, _, _, _ -> }, { _, _ -> }, {},
{ menus++ }, { qams++ }, {})
try {
panel.create()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
val buttons = descendants(panel.window!!.decorView).filterIsInstance<Button>().toList()
assertTrue(buttons.any { it.text == context.getString(R.string.second_show_keyboard) })
val shortcuts = buttons.filter { it.text == "STEAM" || it.text == "…" }
if (steam) {
assertEquals(2, shortcuts.size)
shortcuts.forEach { it.performClick() }
assertEquals(1, menus)
assertEquals(1, qams)
} else {
assertTrue(shortcuts.isEmpty())
}
} finally {
panel.closeControls()
}
}
private fun descendants(view: View): Sequence<View> = sequence {
yield(view)
if (view is ViewGroup) for (index in 0 until view.childCount) yieldAll(descendants(view.getChildAt(index)))
}
private fun actions(steam: Boolean, displays: List<SecondScreenDisplay>, select: (SecondScreenMode) -> Unit = {}) =
DrawerActions(steam = steam, isHomeApp = false, androidApps = emptyList(), hudOn = false,
frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never",
onScreenButtonsVisible = false, suspendPolicy = "auto", backActionsInverted = false,
touchMode = "auto", touchAuto = "trackpad", fexPreset = "default",
secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1,
onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {},
onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {},
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {})
}
@@ -0,0 +1,135 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class ThemeColorsTest {
private val app get() = RuntimeEnvironment.getApplication()
@Before fun clear() {
app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
private fun near(expected: Int, actual: Int) {
for (shift in listOf(16, 8, 0)) assertTrue("${ThemeColors.hex(expected)} vs ${ThemeColors.hex(actual)}", Math.abs((expected shr shift and 0xFF) - (actual shr shift and 0xFF)) <= 1)
}
@Test fun hueSaturationAndBrightnessComeBackAsTheSameColour() {
for (argb in listOf(0xFF8B5CF6.toInt(), 0xFF22D3EE.toInt(), 0xFFFF0000.toInt(), 0xFF336699.toInt(), 0xFF808080.toInt(), 0xFF000000.toInt(), 0xFFFFFFFF.toInt())) {
val hsv = ThemeColors.toHsv(argb)
near(argb, ThemeColors.fromHsv(hsv.h, hsv.s, hsv.v))
}
}
@Test fun hexIsReadWithOrWithoutTheHashAndInShortForm() {
assertEquals(0xFF8B5CF6.toInt(), ThemeColors.parseHex("#8B5CF6"))
assertEquals(0xFF8B5CF6.toInt(), ThemeColors.parseHex("8b5cf6"))
assertEquals(0xFFFF00AA.toInt(), ThemeColors.parseHex(" #f0a "))
assertEquals("#8B5CF6", ThemeColors.hex(0xFF8B5CF6.toInt()))
for (bad in listOf("", "#", "#12", "#1234", "#1234567", "zzzzzz", "#12345g")) assertNull(bad, ThemeColors.parseHex(bad))
}
@Test fun aTooDarkColourIsLiftedAndABrightOneIsLeftAlone() {
val dark = ThemeColors.readable(0xFF050505.toInt())
assertTrue(Color(dark).luminance() >= 0.10f)
assertEquals(0xFF8B5CF6.toInt(), ThemeColors.readable(0xFF8B5CF6.toInt()))
}
@Test fun aDeepBlueThatBrightnessAloneCannotLiftIsMadePaler() {
assertTrue(Color(ThemeColors.readable(0xFF0000FF.toInt())).luminance() >= 0.10f)
assertTrue(Color(ThemeColors.readable(0xFF000000.toInt())).luminance() >= 0.10f)
}
@Test fun theTextColourSuitsTheWorseOfTheTwoGradientColours() {
assertEquals(Color(0xFF03111F), ThemeColors.inkFor(0xFFFFEB3B.toInt(), 0xFF3B4FA8.toInt()))
assertEquals(Color.White, ThemeColors.inkFor(0xFF3B4FA8.toInt(), 0xFF5B2FA8.toInt()))
assertEquals(Color(0xFF03111F), ThemeColors.inkFor(0xFFFFFFFF.toInt(), 0xFFFFEB3B.toInt()))
}
private fun contrast(a: Color, b: Color) = (maxOf(a.luminance(), b.luminance()) + 0.05f) / (minOf(a.luminance(), b.luminance()) + 0.05f)
@Test fun buttonTextIsReadableOnBothGradientColoursForAnyPair() {
val picks = listOf(0xFFFFEB3B, 0xFF1E3A8A, 0xFF0000FF, 0xFFFF0000, 0xFF00FF00, 0xFF808080, 0xFFFFFFFF, 0xFF000000, 0xFF8B5CF6, 0xFF22D3EE, 0xFFFF5722, 0xFF3F51B5)
for (a in picks) for (b in picks) {
val p = ThemeColors.palette(a.toInt(), b.toInt(), 0, 0)
val first = p.primary.toArgb()
val second = p.primary2.toArgb()
for (step in 0..100) {
val fraction = step / 100f
val color = Color(
0xFF000000.toInt() or
(channel(first, 16, second, fraction) shl 16) or
(channel(first, 8, second, fraction) shl 8) or
channel(first, 0, second, fraction),
)
assertTrue(
"${ThemeColors.hex(first)} ${ThemeColors.hex(second)} at $fraction",
contrast(p.onPrimary, color) >= 4.5f,
)
}
}
}
private fun channel(first: Int, shift: Int, second: Int, fraction: Float): Int {
val start = first shr shift and 0xFF
val end = second shr shift and 0xFF
return (start + (end - start) * fraction).toInt().coerceIn(0, 255)
}
@Test fun onlyTheStopThatFailsIsNudged() {
val p = ThemeColors.palette(0xFFFFEB3B.toInt(), 0xFF1E3A8A.toInt(), 0, 0)
assertEquals(Color(0xFFFFEB3B), p.primary)
assertTrue(p.primary2 != Color(0xFF1E3A8A))
assertEquals(Color(0xFF03111F), p.onPrimary)
}
@Test fun thePaletteKeepsTheTwoColoursAndStaysDarkAndReadable() {
val p = ThemeColors.palette(0xFF8B5CF6.toInt(), 0xFF22D3EE.toInt(), 0, 0)
assertEquals(p.primary, p.signal)
assertEquals(Color(0xFF22D3EE), p.primary2)
assertTrue(contrast(p.onPrimary, p.primary) >= 4.5f)
assertTrue(contrast(p.onPrimary, p.primary2) >= 4.5f)
assertTrue(p.background.luminance() < p.surface.luminance())
assertTrue(p.surface.luminance() < p.surfaceVariant.luminance())
assertTrue(p.background.luminance() < 0.02f)
assertTrue(p.onBackground.luminance() > 0.8f)
assertEquals(Color(0xFF03111F), ThemeColors.palette(0xFFFFEB3B.toInt(), 0xFFFFFFFF.toInt(), 0, 0).onPrimary)
assertEquals(Color.White, ThemeColors.palette(0xFF1E40AF.toInt(), 0xFF1D4ED8.toInt(), 0, 0).onPrimary)
}
@Test fun aGreyPrimaryGivesGreyNeutrals() {
val p = ThemeColors.palette(0xFFB0B0B0.toInt(), 0xFFFFFFFF.toInt(), 0, 0)
assertEquals(p.background.red, p.background.blue, 0.002f)
}
@Test fun theGradientThemeFollowsTheSavedColoursAndComesBackAfterARestart() {
Themes.setGradient(app, 0xFFFF5722.toInt(), 0xFF3F51B5.toInt())
val live = Themes.byId(Themes.GRADIENT)
assertEquals(0xFFFF5722.toInt() to 0xFF3F51B5.toInt(), SessionPrefs.gradientColors(app))
assertTrue(contrast(live.onPrimary, live.primary) >= 4.5f)
assertTrue(contrast(live.onPrimary, live.primary2) >= 4.5f)
SessionPrefs.setTheme(app, Themes.GRADIENT)
Themes.setGradient(app, Themes.DEFAULT_PRIMARY, Themes.DEFAULT_SECONDARY)
SessionPrefs.setGradientColors(app, 0xFF00FF00.toInt(), 0xFF0000FF.toInt())
assertEquals(Color(0xFF00FF00), Themes.current(app).primary)
}
@Test fun theGradientIsAChoiceInTheThemeList() {
assertTrue(Themes.all.any { it.id == Themes.GRADIENT })
assertEquals(Themes.GRAPHITE, Themes.byId("nonsense").id)
}
}