chore: merge main to catch up with 0.5.0

This commit is contained in:
xXJsonDeruloXx committed 2026-10-18 17:05:49 -04:00
commit 6d105c1649
1480 files changed
+186541 -49002

No files matched your search

@@ -0,0 +1,56 @@
package com.droiddeck.launcher
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.droiddeck.launcher.session.QuestExperimental
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class DriverMenusAutoTest {
@Before fun reset() {
RuntimeEnvironment.getApplication().getSharedPreferences("session", Context.MODE_PRIVATE)
.edit().clear().commit()
ShadowBuild.setModel("Quest 3")
ShadowBuild.setDevice("eureka")
}
@Test fun selectingAutoUsesTheQuestPairWithoutStartingADownload() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MANUAL)
SessionPrefs.setAndroidDriver(activity, "chosen-display")
SessionPrefs.setLinuxDriver(activity, "chosen-linux")
val menus = DriverMenus(activity, Handler(Looper.getMainLooper()))
menus.setMode(true)
assertEquals(QuestExperimental.DRIVER, SessionPrefs.androidDriver(activity))
assertEquals("", SessionPrefs.linuxDriver(activity))
assertEquals(activity.getString(R.string.drivers_using_quest), menus.autoStatus)
assertFalse(menus.releaseChecking)
assertNull(menus.pairBusy)
menus.ensureAuto(force = true)
assertFalse(menus.releaseChecking)
}
@Test fun openingManualDriverSettingsRetainsTheSelectedPair() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MANUAL)
SessionPrefs.setAndroidDriver(activity, "chosen-display")
SessionPrefs.setLinuxDriver(activity, "chosen-linux")
DriverMenus(activity, Handler(Looper.getMainLooper())).ensureAuto(force = true)
assertEquals("chosen-display", SessionPrefs.androidDriver(activity))
assertEquals("chosen-linux", SessionPrefs.linuxDriver(activity))
}
}
@@ -0,0 +1,88 @@
package com.droiddeck.launcher.agent
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class AgentGuestSelectionTest {
private val installedAppIds = setOf(646570L, 3180310L)
@Test fun focusedInstalledGameIsSelected() {
assertEquals(3180310L, AgentGuest.focusedInstalledSteamAppId(3180310L, installedAppIds))
}
@Test fun focusedInstalledGameIsActive() {
assertEquals(
3180310L,
AgentGuest.activeInstalledSteamAppId(3180310L, listOf(769L, 3180310L), installedAppIds),
)
}
@Test fun selectedSteamGameWinsOverStaleActiveSteamGame() {
assertEquals(
646570L,
AgentGuest.preferredInstalledSteamAppId(646570L, 3180310L, installedAppIds),
)
}
@Test fun validGamescopeGameFallsBackWhenSteamSelectionFails() {
assertEquals(
3180310L,
AgentGuest.selectedOrActiveInstalledSteamAppId(
Result.failure(IllegalStateException("agent unavailable")),
3180310L,
installedAppIds,
),
)
}
@Test fun absentSelectionAndActiveGameRemainAValidNoSelection() {
assertNull(AgentGuest.selectedOrActiveInstalledSteamAppId(Result.success(null), null, installedAppIds))
}
@Test(expected = IllegalStateException::class)
fun selectionFailureWithoutGamescopeFallbackRemainsAnError() {
AgentGuest.selectedOrActiveInstalledSteamAppId(
Result.failure(IllegalStateException("agent unavailable")),
null,
installedAppIds,
)
}
@Test fun soleFocusableInstalledGameRemainsActiveUnderSteamOverlay() {
assertEquals(
3180310L,
AgentGuest.activeInstalledSteamAppId(769L, listOf(3180310L), installedAppIds),
)
}
@Test fun ambiguousFocusableGamesAreIgnored() {
assertNull(
AgentGuest.activeInstalledSteamAppId(769L, listOf(646570L, 3180310L), installedAppIds),
)
}
@Test fun soleBaselayerGameResolvesAmbiguousSteamOverlayFocus() {
assertEquals(
646570L,
AgentGuest.activeInstalledSteamAppId(
focusedAppId = 769L,
focusableAppIds = listOf(646570L, 3180310L),
installedAppIds = installedAppIds,
baselayerAppIds = listOf(769L, 646570L),
),
)
}
@Test fun steamClientFocusIsIgnored() {
assertNull(AgentGuest.focusedInstalledSteamAppId(769L, installedAppIds))
}
@Test fun unknownGameFocusIsIgnored() {
assertNull(AgentGuest.focusedInstalledSteamAppId(42L, installedAppIds))
}
@Test fun missingFocusSnapshotIsIgnored() {
assertNull(AgentGuest.focusedInstalledSteamAppId(null, installedAppIds))
}
}
@@ -7,6 +7,7 @@ import android.util.Base64
import androidx.compose.ui.semantics.SemanticsConfiguration
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.text.AnnotatedString
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.Assert.*
@@ -68,6 +69,13 @@ class AgentSecurityTest {
assertFalse(AgentAccess.commandsAllowed(context))
}
@Test fun theRefusalNamesTheSetupTabThatHoldsTheToggle() {
val refusal = refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireCommands(context) }
val tab = context.getString(R.string.setup_tab_diagnostics)
val toggle = context.getString(R.string.setup_agent_commands)
assertTrue(refusal.message, refusal.message!!.contains("Setup > $tab > $toggle"))
}
@Test fun runCannotBypassTheToggle() {
refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireStart(context, JSONObject().put("mode", "run")) }
AgentAccess.requireStart(context, JSONObject().put("mode", "steam"))
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.core
import java.io.File
import java.util.Locale
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class AppLanguageTest {
private fun tag(languageTag: String) = AppLanguage.supportedTag(Locale.forLanguageTag(languageTag))
private val folders = mapOf(
"id" to "in", "ms" to "ms", "cs" to "cs", "da" to "da", "de" to "de", "es" to "es",
"es-419" to "b+es+419", "fr" to "fr", "it" to "it", "hu" to "hu", "nl" to "nl", "nb" to "nb",
"pl" to "pl", "pt-BR" to "pt", "pt-PT" to "pt-rPT", "ro" to "ro", "fi" to "fi", "sv" to "sv",
"vi" to "vi", "tr" to "tr", "el" to "el", "bg" to "bg", "ru" to "ru", "uk" to "uk", "ar" to "ar",
"hi" to "hi", "th" to "th", "ja" to "ja", "ko" to "ko", "zh-CN" to "zh-rCN", "zh-TW" to "zh-rTW",
"zh-HK" to "zh-rHK",
)
@Test fun everyLanguageReadsAsItself() {
AppLanguage.supported.forEach { assertEquals(it, tag(it)) }
}
@Test fun everyLanguageHasItsOwnName() {
val names = AppLanguage.supported.map(AppLanguage::nativeName)
assertEquals(names.size, names.toSet().size)
AppLanguage.supported.forEach { assertTrue(it, AppLanguage.nativeName(it) != it) }
}
@Test fun systemLocalesFindTheirLanguage() {
assertEquals("es-419", tag("es-MX"))
assertEquals("es-419", tag("es-US"))
assertEquals("es", tag("es-ES"))
assertEquals("pt-BR", tag("pt-BR"))
assertEquals("pt-BR", tag("pt"))
assertEquals("pt-PT", tag("pt-PT"))
assertEquals("pt-PT", tag("pt-AO"))
assertEquals("id", tag("in-ID"))
assertEquals("id", tag("id-ID"))
assertEquals("de", tag("de-AT"))
assertEquals("ar", tag("ar-EG"))
assertEquals("zh-HK", tag("zh-MO"))
assertNull(tag("sw-KE"))
assertNull(tag("nn-NO"))
}
@Test fun everyLanguageShipsStringsAndIsOfferedToAndroid() {
assertEquals(AppLanguage.supported.toSet() - "en", folders.keys)
val res = File("src/main/res")
folders.values.forEach { assertTrue(it, File(res, "values-$it/strings.xml").isFile) }
val config = File(res, "xml/locales_config.xml").readText()
val offered = Regex("""android:name="([^"]+)"""").findAll(config).map { it.groupValues[1] }.toList()
assertEquals(AppLanguage.supported, offered)
}
}
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.core
import org.junit.Assert.*
import org.junit.Test
class CpuAllocationDefaultsTest {
private val thor = (0..7).associateWith { when (it) { in 0..2 -> 2.016; in 3..6 -> 2.8032; else -> 3.1872 } }
@Test fun gen2UsesTheFourMiddleCoresAndOnePrime() {
for (model in listOf("SM8550", "QCS8550", "sm8550-ac")) {
assertEquals(CpuAllocationDefaults.Allocation("7", "3,4,5,6"), CpuAllocationDefaults.forDevice(model, "", thor))
}
assertEquals(CpuAllocationDefaults.Allocation("7", "3,4,5,6"), CpuAllocationDefaults.forDevice("", "kalama", thor))
}
@Test fun coreNumbersAndClockVariantsAreDetectedInsteadOfHardcoded() {
val reordered = mapOf(0 to 3.36, 1 to 2.0, 2 to 2.0, 3 to 2.0, 4 to 2.8, 5 to 2.8, 6 to 2.8, 7 to 2.8)
assertEquals(CpuAllocationDefaults.Allocation("0", "4,5,6,7"), CpuAllocationDefaults.forDevice("SM8550-AC", "kalama", reordered))
}
@Test fun anotherOrUnknownChipDoesNotAcquireThisDefault() {
assertNull(CpuAllocationDefaults.forDevice("SM8650", "pineapple", thor))
assertNull(CpuAllocationDefaults.forDevice("SM8650", "kalama", thor))
assertNull(CpuAllocationDefaults.forDevice("", "", thor))
}
@Test fun missingOrUnexpectedTopologyKeepsTheSchedulerDefault() {
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor - 7))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to null)))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to 0.0)))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to Double.NaN)))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", (0..7).associateWith { 2.8 }))
}
@Test fun allCoreGamesUndoTheClientsInheritedRestriction() {
val all = CpuCores.listOrAll("")
assertEquals(all, CpuCores.gameLaunchList("", clientPinned = true))
assertEquals(all, CpuCores.gameLaunchList(all, clientPinned = true))
assertEquals("", CpuCores.gameLaunchList("", clientPinned = false))
assertEquals("0", CpuCores.gameLaunchList("0", clientPinned = true))
}
}
@@ -0,0 +1,28 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DeviceReportExitTest {
@Test fun knownReasonCodesHaveTheirPlatformNames() {
assertEquals("EXIT_SELF", DeviceReport.exitReasonName(1))
assertEquals("LOW_MEMORY", DeviceReport.exitReasonName(3))
assertEquals("CRASH_NATIVE", DeviceReport.exitReasonName(5))
assertEquals("EXCESSIVE_RESOURCE_USAGE", DeviceReport.exitReasonName(9))
assertEquals("FREEZER", DeviceReport.exitReasonName(14))
}
@Test fun anUnknownCodeStillShowsItsNumber() {
assertEquals("REASON_99", DeviceReport.exitReasonName(99))
assertEquals("REASON_-1", DeviceReport.exitReasonName(-1))
}
@Test fun aSummaryNamesTheProcessReasonAndStatus() {
val line = DeviceReport.exitSummary("com.droiddeck.launcher", 3, 0, " low mem & is ok ")
assertTrue(line, line.startsWith("com.droiddeck.launcher LOW_MEMORY status=0"))
assertTrue(line, line.endsWith("low mem & is ok"))
assertEquals("? UNKNOWN status=0", DeviceReport.exitSummary(null, 0, 0, null))
assertEquals("p SIGNALED status=9", DeviceReport.exitSummary("p", 2, 9, " "))
}
}
@@ -0,0 +1,28 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Test
class DeviceReportPerfTest {
@Test fun thermalStatusesHaveTheirPlatformNames() {
assertEquals("NONE", DeviceReport.thermalStatusName(0))
assertEquals("MODERATE", DeviceReport.thermalStatusName(2))
assertEquals("CRITICAL", DeviceReport.thermalStatusName(4))
assertEquals("SHUTDOWN", DeviceReport.thermalStatusName(6))
assertEquals("STATUS_9", DeviceReport.thermalStatusName(9))
}
@Test fun gameModesHaveTheirPlatformNames() {
assertEquals("UNSUPPORTED", DeviceReport.gameModeName(0))
assertEquals("STANDARD", DeviceReport.gameModeName(1))
assertEquals("PERFORMANCE", DeviceReport.gameModeName(2))
assertEquals("BATTERY", DeviceReport.gameModeName(3))
assertEquals("MODE_7", DeviceReport.gameModeName(7))
}
@Test fun refreshModesAreRoundedDeduplicatedAndListedFastestFirst() {
assertEquals("120 Hz, 60 Hz", DeviceReport.refreshModesSummary(listOf(60.0f, 120.00001f, 60.00001f)))
assertEquals("60 Hz", DeviceReport.refreshModesSummary(listOf(59.94f)))
assertEquals("", DeviceReport.refreshModesSummary(emptyList()))
}
}
@@ -0,0 +1,170 @@
package com.droiddeck.launcher.core
import java.io.File
import java.net.ServerSocket
import java.net.Socket
import java.nio.file.Files
import java.security.MessageDigest
import java.util.concurrent.CopyOnWriteArrayList
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.Before
import org.junit.Test
/**
* A download that was cut off keeps its bytes, and a second call with `resume` asks for the rest
* with a Range header instead of starting again. The server is a plain socket so the first answer
* can promise the whole file and then hang up halfway.
*/
class DownloaderResumeTest {
private val data = ByteArray(300_000) { (it % 251).toByte() }
private val cutAt = 100_000
private val requests = CopyOnWriteArrayList<String?>()
private lateinit var server: ServerSocket
private lateinit var dir: File
private lateinit var thread: Thread
@Volatile private var misbehave = false
@Volatile private var etag: String? = "\"v1\""
@Volatile private var corrupt = false
@Before fun setUp() {
dir = Files.createTempDirectory("downloader-resume").toFile()
server = ServerSocket(0)
thread = Thread {
try {
while (!server.isClosed) {
val socket = server.accept()
// the client may hang up on a body it refuses; that must not stop the server
runCatching { handle(socket) }
}
} catch (_: Exception) {
// closed by tearDown
}
}.apply { isDaemon = true; start() }
}
@After fun tearDown() {
server.close()
dir.deleteRecursively()
}
private fun handle(socket: Socket) = socket.use {
val input = it.getInputStream().bufferedReader(Charsets.ISO_8859_1)
val path = input.readLine() ?: return@use
var range: String? = null
while (true) {
val line = input.readLine() ?: break
if (line.isEmpty()) break
if (line.startsWith("Range:", ignoreCase = true)) range = line.substringAfter(':').trim()
}
requests.add(range)
val out = it.getOutputStream()
val validator = etag?.let { tag -> "ETag: $tag\r\n" } ?: ""
val content = if (corrupt && "/corrupt" in path) ByteArray(data.size) else data
val from = range?.removePrefix("bytes=")?.substringBefore('-')?.toIntOrNull()
if (misbehave) {
// answers a Range request with a 206 that starts at 0, and serves plain requests whole
val start = if (from == null) "200 OK" else "206 Partial Content"
val extra = if (from == null) "" else "Content-Range: bytes 0-${data.size - 1}/${data.size}\r\n"
out.write("HTTP/1.1 $start\r\n${extra}${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(content)
out.flush()
} else if (from == null) {
out.write("HTTP/1.1 200 OK\r\n${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(content, 0, cutAt)
out.flush()
// hang up with most of the promised body still unsent
} else {
val rest = data.size - from
out.write(("HTTP/1.1 206 Partial Content\r\nContent-Range: bytes $from-${data.size - 1}/${data.size}\r\n" +
"${validator}Content-Length: $rest\r\nConnection: close\r\n\r\n").toByteArray())
out.write(content, from, rest)
out.flush()
}
}
@Test fun cutOffDownloadResumesFromWhatWasKept() {
val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst"
val target = File(dir, "runtime.tar.zst")
assertFalse("the cut-off transfer must not report success", Downloader.downloadFile(url, target, true, null))
val kept = target.length()
assertTrue("the partial bytes stay on disk (kept=$kept)", kept in 1 until data.size)
assertTrue(Downloader.downloadFile(url, target, true, null))
assertEquals(data.size.toLong(), target.length())
assertArrayEquals(data, target.readBytes())
assertEquals(listOf<String?>(null, "bytes=$kept-"), requests.toList())
}
@Test fun answerFromTheWrongOffsetIsNotAppended() {
val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst"
val target = File(dir, "runtime.tar.zst")
assertFalse(Downloader.downloadFile(url, target, true, null))
val kept = target.length()
assertTrue(kept in 1 until data.size)
misbehave = true
assertTrue(Downloader.downloadFile(url, target, true, null))
assertEquals(data.size.toLong(), target.length())
assertArrayEquals("the file must not be the kept bytes plus a misplaced body", data, target.readBytes())
assertEquals(listOf<String?>(null, "bytes=$kept-", null), requests.toList())
}
@Test fun legacyPartialWithoutValidatorRestartsAtZero() {
val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst"
val target = File(dir, "runtime.tar.zst")
target.writeBytes(ByteArray(cutAt) { 9 })
misbehave = true
assertTrue(Downloader.downloadFile(url, target, true, null))
assertArrayEquals(data, target.readBytes())
assertEquals(listOf<String?>(null), requests.toList())
}
@Test fun missingStrongETagPreventsUnsafeResume() {
val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst"
val target = File(dir, "runtime.tar.zst")
etag = null
assertFalse(Downloader.downloadFile(url, target, true, null))
misbehave = true
assertTrue(Downloader.downloadFile(url, target, true, null))
assertArrayEquals(data, target.readBytes())
assertEquals(listOf<String?>(null, null), requests.toList())
}
@Test fun switchingCandidateDoesNotAppendToDifferentSource() {
val first = "http://127.0.0.1:${server.localPort}/first"
val second = "http://127.0.0.1:${server.localPort}/second"
val target = File(dir, "runtime.tar.zst")
val sha256 = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it.toInt() and 0xff) }
assertFalse(Downloader.downloadFile(first, target, true, sha256, null))
misbehave = true
assertTrue(Downloader.downloadFile(second, target, true, sha256, null))
assertArrayEquals(data, target.readBytes())
assertEquals(listOf<String?>(null, null), requests.toList())
}
@Test fun corruptCandidateFallsBackAfterChecksumMismatch() {
val first = "http://127.0.0.1:${server.localPort}/corrupt"
val second = "http://127.0.0.1:${server.localPort}/clean"
val target = File(dir, "runtime.tar.zst")
val sha256 = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it.toInt() and 0xff) }
misbehave = true
corrupt = true
assertTrue(Downloader.downloadCandidates(first, listOf(first, second), target, true, sha256, null))
assertArrayEquals(data, target.readBytes())
assertEquals(listOf<String?>(null, null), requests.toList())
}
@Test fun executableMetadataIsAlwaysDirect() {
val url = "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases"
assertEquals(listOf(url), DownloadSource.candidates(url))
val catalog = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-CI/main/catalog.json"
assertEquals(listOf(catalog), DownloadSource.candidates(catalog))
}
}
@@ -102,4 +102,46 @@ class GameEnvironmentTest {
assertTrue(GameEnvironment.validScope("4294967295"))
for (scope in listOf("0", "-1", "01", "+1", "4294967296", "../42")) assertFalse(GameEnvironment.validScope(scope))
}
@Test fun gameFexPresetOverridesGeneralAndCanInheritAgain() {
val performance = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "42", "PERFORMANCE")
assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(performance, "42"))
assertEquals("0", GameEnvironment.effective(performance, "STABILITY", "42")["FEX_TSOENABLED"])
assertEquals("1", GameEnvironment.effective(performance, "STABILITY", "43")["FEX_TSOENABLED"])
val inherited = GameEnvironment.withGameFexPreset(performance, "42", null)
assertNull(GameEnvironment.gameFexPreset(inherited, "42"))
assertFalse(inherited.games.containsKey("42"))
}
@Test fun gameFexPresetPreservesOtherOverridesAndRecognizesCustomValues() {
val original = GameEnvironment.Config(games = mapOf("42" to mapOf("CUSTOM" to "value", "FEX_MULTIBLOCK" to "7")))
assertEquals(GameEnvironment.CUSTOM_FEX_PRESET, GameEnvironment.gameFexPreset(original, "42"))
val compatibility = GameEnvironment.withGameFexPreset(original, "42", "COMPATIBILITY")
assertEquals("value", compatibility.games.getValue("42")["CUSTOM"])
assertEquals("COMPATIBILITY", GameEnvironment.gameFexPreset(compatibility, "42"))
}
@Test fun gameSyncChoiceMatchesTheAppWideChoiceAndCanInheritAgain() {
val base = GameEnvironment.Config(games = mapOf("42" to mapOf("FEX_TSOENABLED" to "1", "PROTON_NO_ESYNC" to "1")))
assertEquals(GameEnvironment.CUSTOM_SYNC, GameEnvironment.gameSync(base, "42"))
assertNull(GameEnvironment.gameSync(base, "43"))
for (backend in GameEnvironment.syncBackends) {
val chosen = GameEnvironment.withGameSync(base, "42", backend)
assertEquals(backend, GameEnvironment.gameSync(chosen, "42"))
assertEquals("1", chosen.games["42"]!!["FEX_TSOENABLED"])
}
val ntsync = GameEnvironment.withGameSync(base, "42", "ntsync").games["42"]!!
assertEquals(listOf("1", "0", "1"), listOf(ntsync["BL_SYNC"], ntsync["BL_FSYNC_FIRST"], ntsync["BL_SYNC_FALLBACK"]))
assertFalse(ntsync.containsKey("PROTON_NO_ESYNC"))
val fsync = GameEnvironment.withGameSync(base, "42", "fsync").games["42"]!!
assertEquals(listOf("0", "1", "1", "1"), listOf(fsync["BL_SYNC"], fsync["BL_FSYNC_FIRST"], fsync["BL_SYNC_FALLBACK"], fsync["PROTON_NO_ESYNC"]))
val wineserver = GameEnvironment.withGameSync(base, "42", "wineserver").games["42"]!!
assertEquals(listOf("0", "0", "0"), listOf(wineserver["BL_SYNC"], wineserver["BL_FSYNC_FIRST"], wineserver["BL_SYNC_FALLBACK"]))
val inherited = GameEnvironment.withGameSync(base, "42", null)
assertNull(GameEnvironment.gameSync(inherited, "42"))
assertEquals(mapOf("FEX_TSOENABLED" to "1"), inherited.games["42"])
assertTrue(GameEnvironment.withGameSync(GameEnvironment.Config(), "42", null).games.isEmpty())
}
}
@@ -88,7 +88,6 @@ class LogRedactorTest {
}
}
// The Steam UI's own login line (webhelper_js.txt), as the privacy scan found it.
@Test fun loginStateLineLosesAnEmailAccount() {
val line = "[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange someone.masked@example.com 2 1 0 0"
val out = LogRedactor.redact(line)
@@ -148,4 +147,23 @@ class LogRedactorTest {
val once = LogRedactor.redactForShare("resolver: 192.168.0.1")
assertEquals(once, LogRedactor.redactForShare(once))
}
@Test fun learnedAccountsComeFromBothClients() {
val root = java.nio.file.Files.createTempDirectory("redactor").toFile()
try {
val arm = java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf")
arm.parentFile.mkdirs()
arm.writeText("\"users\" { \"7656\" { \"AccountName\" \"armplayer\" \"PersonaName\" \"Arm Persona\" } }")
LogRedactor.learnFromRuntime(root)
assertEquals("hi <redacted:account> and <redacted:account>", LogRedactor.redact("hi armplayer and Arm Persona"))
val x64 = java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
x64.parentFile.mkdirs()
x64.writeText("\"users\" { \"7656\" { \"AccountName\" \"x64player\" } }")
LogRedactor.learnFromRuntime(root)
assertEquals("<redacted:account> <redacted:account>", LogRedactor.redact("armplayer x64player"))
} finally {
LogRedactor.learnAccounts()
root.deleteRecursively()
}
}
}
@@ -35,11 +35,17 @@ class PhantomProcessLimitTest {
listOf(
"device_config set_sync_disabled_for_tests persistent",
"device_config put activity_manager max_phantom_processes 2147483647",
"settings put global settings_enable_monitor_phantom_procs false",
),
PhantomProcessLimit.shellCommands(enabled = false, sdk = 31),
)
assertTrue(PhantomProcessLimit.verified("2147483647\n", enabled = false, sdk = 31))
assertFalse(PhantomProcessLimit.verified("null", enabled = false, sdk = 31))
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.android12Status(true, null, null))
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.android12Status(false, "false", null))
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.android12Status(false, null, "0"))
assertEquals(PhantomProcessStatus.UNREADABLE, PhantomProcessLimit.android12Status(false, null, null))
assertEquals(PhantomProcessStatus.UNREADABLE, PhantomProcessLimit.android12Status(false, "true", null))
}
@Test
@@ -13,7 +13,6 @@ class SecretScrubTest {
"0024:warn:seh:dispatch_exception code=c0000005 flags=0 addr=0000000140012345",
"0030:trace:seh:handle_syscall_fault code=80000003 flags=0",
"exception code=0xC0000005 at 0x140012345",
// An exception code stays one even on a line that also carries OAuth keys.
"client_id=abc code=c0000005",
)) assertEquals(line, share(line))
}
@@ -0,0 +1,37 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ZramSupportTest {
@Test
fun kernelVersionsFromAndroidReleases() {
assertTrue(ZramSupport.kernelAtLeast("6.12.38-android16-5-g665eafb62659-ab14778838-4k", 5, 4))
assertTrue(ZramSupport.kernelAtLeast("5.4.0", 5, 4))
assertFalse(ZramSupport.kernelAtLeast("4.19.157-perf+", 5, 4))
assertFalse(ZramSupport.kernelAtLeast("", 5, 4))
}
@Test
fun underTwelveGbFromAdvertisedOrTotalMemory() {
val gb = 1_000_000_000L
val gib = 1L shl 30
assertTrue(ZramSupport.belowTwelveGb(8 * gb, 0))
assertTrue(ZramSupport.belowTwelveGb(8 * gib, 0))
assertFalse(ZramSupport.belowTwelveGb(12 * gb, 0))
assertFalse(ZramSupport.belowTwelveGb(12 * gib, 0))
assertTrue(ZramSupport.belowTwelveGb(0, 7_400_000L * 1024))
assertTrue(ZramSupport.belowTwelveGb(0, 9_300_000L * 1024))
assertFalse(ZramSupport.belowTwelveGb(0, 11_100_000L * 1024))
assertFalse(ZramSupport.belowTwelveGb(0, 15_600_380L * 1024))
}
@Test
fun swapTotalComesFromMeminfo() {
assertEquals(12582908L, ZramSupport.swapTotalKb(listOf("MemTotal: 15600380 kB", "SwapTotal: 12582908 kB")))
assertEquals(0L, ZramSupport.swapTotalKb(listOf("SwapTotal: 0 kB")))
assertEquals(0L, ZramSupport.swapTotalKb(emptyList()))
}
}
@@ -13,7 +13,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** The Games tab's +: one picked .exe becomes a game, once, wherever the session can see it. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedExesTest {
@@ -54,7 +53,6 @@ class AddedExesTest {
assertEquals(Library.ADDED, game.source)
assertTrue(File(app.filesDir, "session/added-games.json").readText().contains("Celeste.exe"))
// The same exe again: the game it already is, no second entry.
val again = AddedGames.addExe(app, pick)
assertTrue(again is AddedGames.AddResult.Existing)
assertEquals(game.appId, (again as AddedGames.AddResult.Existing).game.appId)
@@ -83,7 +81,6 @@ class AddedExesTest {
val result = AddedGames.addExe(app, deep)
assertTrue(result is AddedGames.AddResult.Switched)
assertEquals(deep.path, AddedGames.scan(app).single().exe.path)
// The Games folder's game is an entry of its own (GamesFolderMigration); no second one.
assertEquals(listOf(File(games, "Example").path), AddedExes.list(app).map { it.folder })
}
@@ -20,7 +20,6 @@ import java.io.File
import java.security.SecureRandom
import javax.crypto.spec.SecretKeySpec
/** Where an added game's art comes from: its own Steam appid, a matching name, SteamGridDB's key. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGameArtLookupTest {
@@ -39,7 +38,6 @@ class AddedGameArtLookupTest {
val match = SteamMatch.resolve(app, dir.path, exe, "Palworld") { fail("searched"); null }
assertEquals(1623730, match.appId)
assertEquals(SteamMatch.Certainty.FILES, match.certainty)
// The same record for everyone who asks.
assertEquals(1623730, SteamMatch.get(app, dir.path)!!.appId)
}
@@ -68,7 +66,6 @@ class AddedGameArtLookupTest {
}
@Test fun aStoreResultIsTakenOnlyWhenItsNameMatches() {
// The first result is no longer taken for being first.
assertNull(AddedGameArt.pickStoreResult("My Obscure Game", listOf("10" to "Totally Different", "11" to "Another One")))
assertEquals("20", AddedGameArt.pickStoreResult("Hades", listOf("19" to "Hades II Soundtrack Bundle Extra", "20" to "Hades")))
assertEquals("30", AddedGameArt.pickStoreResult("Skyrim Special Edition Complete Edition", listOf("1" to "Unrelated", "30" to "Skyrim Special Edition")))
@@ -95,7 +92,6 @@ class AddedGameArtLookupTest {
assertEquals("build", SteamGridDb.pick("", "build"))
assertEquals("build", SteamGridDb.pick(" ", "build"))
assertEquals("", SteamGridDb.pick("", ""))
// This test build carries no key.
assertEquals("", SteamGridDb.builtInKey())
assertEquals("", SteamGridDb.key(app))
}
@@ -112,4 +108,66 @@ class AddedGameArtLookupTest {
assertFalse(file.exists())
assertEquals("", SteamGridDb.key(app))
}
@Test fun aFailedLookupIsNotRememberedAsNoMatch() {
val marker = File(tmp.newFolder(), "sgdb-id")
try {
AddedGameArt.remembered(marker) { throw SteamGridDb.Failed(SteamGridDb.Status.BAD_KEY) }
fail("the failure was swallowed")
} catch (e: SteamGridDb.Failed) {
assertEquals(SteamGridDb.Status.BAD_KEY, e.status)
}
assertFalse(marker.exists())
}
@Test fun aMissIsKeptUntilTheKeyChangesOrTheUserAsksAgain() {
val marker = File(tmp.newFolder(), "sgdb-id")
var asked = 0
assertNull(AddedGameArt.remembered(marker) { asked++; null })
assertEquals("none", marker.readText())
assertNull(AddedGameArt.remembered(marker) { asked++; "9" })
assertEquals(1, asked)
assertEquals("9", AddedGameArt.remembered(marker, notBefore = System.currentTimeMillis() + 1000) { asked++; "9" })
assertEquals(2, asked)
assertEquals("9", AddedGameArt.remembered(marker) { fail("asked again"); null })
val old = File(marker.parentFile, "old-id").apply { writeText("none") }
assertEquals("5", AddedGameArt.remembered(old, retryMiss = true) { "5" })
assertEquals("5", old.readText())
}
@Test fun savingAKeyMarksWhenItChanged() {
SteamGridDb.keys = CredentialCipher.KeyProvider { SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES") }
assertEquals(0L, SteamGridDb.keyChangedAt(app))
SteamGridDb.setUserKey(app, "abcdef0123456789")
assertTrue(SteamGridDb.keyChangedAt(app) > 0L)
}
@Test fun aBadResponseSaysWhatWentWrong() {
assertEquals(SteamGridDb.Status.BAD_KEY, SteamGridDb.failure(401))
assertEquals(SteamGridDb.Status.BAD_KEY, SteamGridDb.failure(403))
assertEquals(SteamGridDb.Status.LIMIT, SteamGridDb.failure(429))
assertEquals(SteamGridDb.Status.SERVER, SteamGridDb.failure(503))
assertNull(SteamGridDb.failure(404))
assertNull(SteamGridDb.failure(200))
}
@Test fun searchResultsKeepOnlyGamesWithAnIdAndAName() {
val data = JSONArray()
.put(JSONObject().put("id", 7).put("name", "DONTFORGET").put("verified", true))
.put(JSONObject().put("id", 0).put("name", "No id"))
.put(JSONObject().put("id", 8).put("name", ""))
.put("junk")
val games = SteamGridDb.games(data)
assertEquals(1, games.size)
assertEquals(7, games[0].id)
assertEquals("DONTFORGET", games[0].name)
assertTrue(games[0].verified)
}
@Test fun eachSlotAsksItsOwnEndpoint() {
assertEquals("heroes/game/5?nsfw=false&humor=false", SteamGridDb.path(5, AddedGameArt.Slot.BACKGROUND))
assertEquals("grids/game/5?dimensions=600x900&nsfw=false&humor=false", SteamGridDb.path(5, AddedGameArt.Slot.COVER))
assertEquals("grids/game/5?dimensions=460x215,920x430&nsfw=false&humor=false", SteamGridDb.path(5, AddedGameArt.Slot.WIDE))
}
}
@@ -18,7 +18,6 @@ import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
/** "Add all games in this folder", the editor's writes to the shortcut listing, art choices. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGameEditsTest {
@@ -52,14 +51,11 @@ class AddedGameEditsTest {
val alpha = result.added.first { it.name == "Alpha" }
assertEquals("Alpha.exe", alpha.exe.name)
assertFalse(alpha.exeUncertain)
// Two lookalikes: the best guess, marked.
assertTrue(result.added.first { it.name == "Beta" }.exeUncertain)
// Entries, not a Games folder.
assertEquals(emptyList<String>(), SessionPrefs.addedGamesDirs(app))
assertEquals(3, AddedExes.list(app).size)
assertTrue(listing().map { it.getString("name") }.containsAll(listOf("Alpha", "Beta", "Celeste")))
// Again: nothing new, all three there already.
val again = AddedGames.addFolder(app, dir)
assertEquals(emptyList<String>(), again.added.map { it.name })
assertEquals(3, again.already)
@@ -84,7 +80,6 @@ class AddedGameEditsTest {
assertEquals(game.appId, entry.getLong("appid"))
assertEquals(game.appId, AddedGameEdits.game(app, folder)!!.appId)
// Back to automatic.
AddedGameEdits.setName(app, folder, "")
assertTrue(AddedGameEdits.setStartIn(app, folder, ""))
val auto = listing().single()
@@ -109,8 +104,6 @@ class AddedGameEditsTest {
assertEquals("/g/Game/data", SessionPrefs.addedGameStartIn(app, folder.path))
assertEquals("-safe", SessionPrefs.addedGameLaunch(app, folder.path))
// The user renames it in the app before Steam's shortcut is written again: the same Steam
// value is not taken a second time.
SessionPrefs.setAddedGameName(app, folder.path, "Mine")
AddedGames.adoptSteamEdits(app, folder, record)
assertEquals("Mine", SessionPrefs.addedGameName(app, folder.path))
@@ -13,7 +13,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** The .exe picker below a game folder (five levels, past installer folders, ranked) and the names it finds. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesCandidatesTest {
@@ -65,7 +64,6 @@ class AddedGamesCandidatesTest {
val game = tmp.newFolder("Huge")
for (i in 0 until GameExePicker.WALK_BUDGET + 50) File(game, "data/d%04d".format(i)).mkdirs()
exe(game, "zzz/Late.exe")
// data/ alone fills the budget before zzz/ is listed.
assertEquals(emptyList<String>(), names(game))
val small = tmp.newFolder("Small")
exe(small, "x/y/Found.exe")
@@ -136,7 +134,6 @@ class AddedGamesCandidatesTest {
game.setLastModified(game.lastModified() + 10_000)
val after = AddedGames.scan(app).single()
assertEquals("The Witcher 3 - Wild Hunt", after.name)
// Already added under the folder name: the shortcut keeps its id.
assertEquals(before.appId, after.appId)
}
@@ -12,7 +12,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Removing an added game stops listing it and keeps it off after a rescan, until it is added again; nothing on disk goes. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesRemoveTest {
@@ -47,7 +46,6 @@ class AddedGamesRemoveTest {
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
assertEquals(listOf("Alpha", "Gamma"), AddedGames.scan(app).map { it.name })
// A rescan does not bring it back.
assertEquals(listOf("Alpha", "Gamma"), AddedGames.scan(app).map { it.name })
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, false)
@@ -66,7 +64,6 @@ class AddedGamesRemoveTest {
assertTrue(!listing.contains("\"Beta\""))
assertTrue(File(beta, "Beta.exe").isFile)
// Added again with the +: it comes back.
assertTrue(AddedGames.addExe(app, File(beta, "Beta.exe")) is AddedGames.AddResult.Switched)
assertEquals(emptyList<String>(), SessionPrefs.removedAddedGames(app))
assertTrue(File(app.filesDir, "session/added-games.json").readText().contains("\"Beta\""))
@@ -28,6 +28,30 @@ class AddedGamesScanTest {
assertEquals(listOf("Example"), AddedGames.scan(app).map { it.name })
}
private fun cardWithX8664Library(): File {
val card = tmp.newFolder("Card")
File(card, "Example").mkdirs()
File(card, "Example/Example.exe").writeText("game")
File(card, "x86-64/steamapps/common/FlatOut").mkdirs()
File(card, "x86-64/steamapps/common/FlatOut/FlatOut.exe").writeText("steam game")
return card
}
@Test fun theX8664ClientsCardLibraryIsNotAGame() {
val card = cardWithX8664Library()
SessionPrefs.setGameStorage(app, card.path, "Card")
assertEquals(listOf("Example"), AddedGames.scan(app).map { it.name })
assertTrue(AddedGames.isSteamLibraryFolder("x86-64"))
assertFalse(AddedGames.isSteamLibraryFolder("x86-64 games"))
}
@Test fun anOldGamesFolderHoldingTheX8664LibraryDoesNotMigrateItAsAGame() {
val card = cardWithX8664Library()
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, listOf(card.path))
assertEquals(listOf("Example"), AddedGames.scan(app).map { it.name })
}
@Test fun aStorePackageLaunchesTheExecutableItDeclares() {
val game = tmp.newFolder("Minecraft Dungeons")
File(game, "Dungeons.exe").writeText("unreal bootstrap")
@@ -13,7 +13,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A store install is one more folder the scan finds, named and aimed by its sidecar. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesStoreScanTest {
@@ -38,7 +37,6 @@ class AddedGamesStoreScanTest {
assertEquals("HOMM3.exe", game.exe.name)
assertEquals(Store.GOG.id, game.source)
assertEquals("1207658924", game.storeId)
// Inside the runtime's tree the folder needs no bind: its guest path is its path from the tree's root.
assertEquals("/root/Games/Stores/GOG/Heroes of Might and Magic 3 Complete/HOMM3.exe", game.guestExe)
assertEquals("/root/Games/Stores/GOG/Heroes of Might and Magic 3 Complete", game.guestDir)
}
@@ -51,6 +49,23 @@ class AddedGamesStoreScanTest {
assertEquals(Store.EPIC.id, game.source)
}
@Test fun anEpicGameAlwaysUsesItsLauncherWrapperEvenAfterAnExeIsPicked() {
val folder = install(Store.EPIC, "picked", "Picked Epic", "Binaries/Game.exe", launcher = true)
AddedExes.put(app, AddedExes.Entry(folder.path, File(folder, "Binaries/Game.exe").path, picked = true))
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertEquals("Binaries/Game.exe", game.exe.relativeTo(folder).path)
assertTrue(game.guestExe.endsWith("/" + StoreLaunch.LAUNCHER))
}
@Test fun aDifferentPickedExeOnAnEpicGameIsRunDirectly() {
val folder = install(Store.EPIC, "other", "Other Epic", "Binaries/Game.exe", launcher = true)
val tool = File(folder, "Tools/Editor.exe").apply { parentFile!!.mkdirs(); writeText("tool") }
AddedExes.put(app, AddedExes.Entry(folder.path, tool.path, picked = true))
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertEquals("Tools/Editor.exe", game.exe.relativeTo(folder).path)
assertTrue(game.guestExe.endsWith("/Tools/Editor.exe"))
}
@Test fun anOlderSidecarsSteamSwitchIsIgnoredEveryInstallIsListed() {
val folder = install(Store.AMAZON, "amzn1.adg.product.x", "Yakuza 0", "Yakuza0.exe")
val file = StoreGameSidecar.file(folder)
@@ -64,5 +79,6 @@ class AddedGamesStoreScanTest {
val listing = AddedGames.writeListing(app, games).readText()
assertTrue(listing.contains("\"name\":\"Celeste\""))
assertTrue(listing.contains(StoreLaunch.LAUNCHER))
assertTrue(listing.contains("\"store\":\"${Store.EPIC.id}\""))
}
}
@@ -19,7 +19,6 @@ class AddedGamesTest {
"\"AppState\"\n{\n\t\"appid\"\t\t\"17410\"\n\t\"installdir\"\t\t\"Mirrors Edge\"\n}\n",
)
assertEquals(setOf("monster_hunter_stories_3_twisted_reflection", "mirrors edge"), AddedGames.steamInstallDirs(common))
// Loose game folders at the library root are never Steam's.
assertEquals(emptySet<String>(), AddedGames.steamInstallDirs(library))
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.frontend
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class DependencyDetectorTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun foldersAboveTheGameDoNotChangeWhatIsFound() {
val folder = File(tmp.newFolder("Games 2005", "agility"), "Game")
File(folder, "_CommonRedist/vcredist/2013").mkdirs()
File(folder, "_CommonRedist/vcredist/2013/vcredist_x64.exe").writeText("x")
assertEquals(listOf("vcredist2013"), DependencyDetector.detect(folder).map { it.componentName })
}
}
@@ -30,7 +30,6 @@ class GameFileSyncTest {
assertEquals("8400", File(folder, "Geometry Wars.steam").readText())
assertEquals(folder.path, GameFileSync.folder(context))
assertEquals(1, folder.listFiles()!!.count { it.extension == GameFiles.EXTENSION })
// An unavailable source must leave the existing export intact.
val unavailable = File(steamapps.parentFile, "steamapps-unavailable")
assertTrue(steamapps.renameTo(unavailable))
assertThrows(IllegalStateException::class.java) { GameFileSync.syncConfigured(context) }
@@ -38,11 +37,9 @@ class GameFileSyncTest {
assertTrue(unavailable.renameTo(steamapps))
GameFileSync.syncConfigured(context)
assertTrue(File(folder, "Geometry Wars.steam").exists())
// A genuine uninstall removes the owned export at the next tick.
assertTrue(manifest.delete())
GameFileSync.syncConfigured(context)
assertEquals(0, folder.listFiles()!!.count { it.extension == GameFiles.EXTENSION })
// Disabled sync does not write files for new installs.
GameFileSync.disable(context)
manifest.writeText("\"name\" \"Geometry Wars\"\n\"StateFlags\" \"4\"")
GameFileSync.syncConfigured(context)
@@ -38,7 +38,6 @@ class GameFilesTest {
val provider = LaunchFileProvider(file)
provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend" })
ShadowContentResolver.registerProviderInternal("frontend", provider)
// Providers often give opaque document IDs with no filename extension.
val uri = Uri.parse("content://frontend/document/opaque%3A42")
assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri)))
}
@@ -9,18 +9,13 @@ import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
/**
* Signal-chain coverage for [GameIdentifier]. Pure JVM: builds
* fake game layouts in a temp dir and asserts the right appId/name/source/confidence come back.
* The PE version-resource path is exercised on-device (real .exe), not here.
*/
class GameIdentifierTest {
@get:Rule
val tmp = TemporaryFolder()
private fun exeIn(dir: File, name: String = "game.exe"): File =
File(dir, name).apply { parentFile?.mkdirs(); writeBytes(byteArrayOf(0x4D, 0x5A)) } // "MZ" — not a real PE
File(dir, name).apply { parentFile?.mkdirs(); writeBytes(byteArrayOf(0x4D, 0x5A)) }
@Test
fun steamAppIdTxt_besideExe_givesHighConfidenceAppId() {
@@ -51,7 +46,6 @@ class GameIdentifierTest {
@Test
fun steamManifestAcf_matchedByInstalldir_givesAppIdAndName() {
// steamapps/common/Palworld/Pal/Binaries/Win64/Palworld-Win64-Shipping.exe
val steamapps = tmp.newFolder("steamapps")
File(steamapps, "appmanifest_1623730.acf").writeText(
"""
@@ -63,7 +57,6 @@ class GameIdentifierTest {
}
""".trimIndent()
)
// a decoy manifest that must NOT win
File(steamapps, "appmanifest_570.acf").writeText(
""""AppState" { "appid" "570" "name" "Dota 2" "installdir" "dota 2 beta" }"""
)
@@ -81,9 +74,6 @@ class GameIdentifierTest {
"""{"gameId":"1207658691","name":"The Witcher 3: Wild Hunt","version":1}"""
)
val id = GameIdentifier.identify(exeIn(dir))
// normalizeName() deliberately converts ":" to " - " (a colon is illegal in a Windows
// filename), so the identified name never carries one. The test asserted the raw GOG
// string and had never passed.
assertEquals("The Witcher 3 - Wild Hunt", id.name)
assertEquals("1207658691", id.gogId)
assertNull(id.appId)
@@ -103,7 +93,6 @@ class GameIdentifierTest {
@Test
fun noMarkers_fallsBackToCleanedFolderName_forEngineBinary() {
// UE shipping binary → the folder name is the real title, exe basename is noise.
val dir = tmp.newFolder("Hades")
val id = GameIdentifier.identify(exeIn(dir, "Hades-Win64-Shipping.exe"))
assertEquals("Hades", id.name)
@@ -115,18 +104,16 @@ class GameIdentifierTest {
fun fallbackName_stripsRepackTagsAndVersionTokens() {
val dir = tmp.newFolder("Stardew Valley [FitGirl Repack] v1.5.4")
val id = GameIdentifier.identify(exeIn(dir, "Stardew.exe"))
assertEquals("Stardew", id.name) // exe basename wins (not an engine binary); folder tags irrelevant here
// and a repack-style exe basename is cleaned too:
assertEquals("Stardew", id.name)
val id2 = GameIdentifier.identify(exeIn(tmp.newFolder("g2"), "Game.CODEX.exe"))
assertEquals(GameIdentifier.Source.FILENAME, id2.source)
}
@Test
fun fltIni_gameSettingsAppId_isParsed() {
// Real God of War (FLT release) layout: flt.ini holds the appid under [GameSettings].
val dir = tmp.newFolder("GodOfWar")
File(dir, "flt.ini").writeText("[GameSettings]\nAppId=1593500\nUserName=X\nBuildId=7969425\n")
File(dir, "settings.ini").writeText("[Settings]\nVideoDevice=Wrapper\nMonitor=0\n") // no AppId -> ignored
File(dir, "settings.ini").writeText("[Settings]\nVideoDevice=Wrapper\nMonitor=0\n")
val id = GameIdentifier.identify(exeIn(dir, "GoW.exe"))
assertEquals(1593500, id.appId)
assertEquals(GameIdentifier.Confidence.HIGH, id.confidence)
@@ -141,12 +128,10 @@ class GameIdentifierTest {
@Test
fun bestName_prefersFileDescriptionWhenProductNameIsAbbreviation() {
// God of War ships ProductName "GoW" but FileDescription "God of War".
assertEquals(
"God of War",
PeVersionInfo.bestName(mapOf("ProductName" to "GoW", "FileDescription" to "God of War")),
)
// Normal case: ProductName is the full title -> keep it.
assertEquals(
"Cyberpunk 2077",
PeVersionInfo.bestName(mapOf("ProductName" to "Cyberpunk 2077", "FileDescription" to "Cyberpunk 2077")),
@@ -156,18 +141,15 @@ class GameIdentifierTest {
@Test
fun name_isNormalizedToBeFilesystemSafeAndTidy() {
// Colon → " - " (would otherwise be sanitized to '_' by the shortcut writer).
val d1 = tmp.newFolder("ds")
File(d1, "goggame-1.info").writeText("""{"name":"Dark Souls: Remastered"}""")
assertEquals("Dark Souls - Remastered", GameIdentifier.identify(exeIn(d1)).name)
// Trademark marks (symbol and text forms) stripped.
val d2 = tmp.newFolder("gow2")
File(d2, "goggame-2.info").writeText("""{"name":"God of War™"}""")
assertEquals("God of War", GameIdentifier.identify(exeIn(d2)).name)
val d3 = tmp.newFolder("ds3")
File(d3, "goggame-3.info").writeText("""{"name":"DARK SOULS(TM): REMASTERED"}""")
assertEquals("DARK SOULS - REMASTERED", GameIdentifier.identify(exeIn(d3)).name)
// Trailing PE descriptors dropped (DiRT 3's FileDescription is "DiRT 3 Executable").
val d4 = tmp.newFolder("dirt")
File(d4, "goggame-4.info").writeText("""{"name":"DiRT 3 Executable"}""")
assertEquals("DiRT 3", GameIdentifier.identify(exeIn(d4)).name)
@@ -175,8 +157,6 @@ class GameIdentifierTest {
@Test
fun launcherExe_prefersFolderName_overLauncher() {
// GTA V Enhanced: user picks the Rockstar launcher PlayGTAV.exe (no Steam id, PE = junk on
// a real exe). Fallback must use the folder title, not "PlayGTAV".
val dir = tmp.newFolder("Grand Theft Auto V Enhanced")
val id = GameIdentifier.identify(exeIn(dir, "PlayGTAV.exe"))
assertEquals("Grand Theft Auto V Enhanced", id.name)
@@ -187,12 +167,11 @@ class GameIdentifierTest {
fun launcherExe_withSeparator_prefersFolder_andStripsSiteTag() {
val dir = tmp.newFolder("Grand-Theft-Auto-IV-AnkerGames")
val id = GameIdentifier.identify(exeIn(dir, "Play - GTA IV.exe"))
assertEquals("Grand Theft Auto IV", id.name) // "AnkerGames" site tag stripped
assertEquals("Grand Theft Auto IV", id.name)
}
@Test
fun nonLauncherExe_startingWithPlay_keepsItsOwnName() {
// "PlayerUnknown" must NOT be treated as a launcher (would wrongly use the folder name).
val dir = tmp.newFolder("SomeInstallFolder")
val id = GameIdentifier.identify(exeIn(dir, "PlayerUnknown.exe"))
assertEquals("PlayerUnknown", id.name)
@@ -211,8 +190,7 @@ class GameIdentifierTest {
@Test
fun emptyWhenNothingIdentifiable() {
val dir = tmp.newFolder("x")
val id = GameIdentifier.identify(exeIn(dir, "Game.exe")) // engine-ish base → folder "x"
// "x" is a valid (if useless) fallback name; the point is it must not crash and appId is null.
val id = GameIdentifier.identify(exeIn(dir, "Game.exe"))
assertNull(id.appId)
assertTrue(id.confidence == GameIdentifier.Confidence.LOW)
}
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.frontend
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class GameShortcutsIconTest {
private lateinit var dir: File
@Before fun setUp() {
dir = Files.createTempDirectory("shortcut-icons").toFile()
}
@Test fun aSmallSteamIconGivesWayToTheMiddleOfTheCoverArt() {
val icon = image("icon.png", 32, 32, Color.GREEN)
val cover = image("cover.png", 300, 450, Color.BLUE, band = 75, bandColor = Color.RED)
val bitmap = GameShortcuts.iconBitmap(game(icon = icon, art = cover))!!
assertEquals(300, bitmap.width)
assertEquals(300, bitmap.height)
assertEquals(Color.BLUE, bitmap.getPixel(0, 0))
assertEquals(Color.BLUE, bitmap.getPixel(299, 299))
}
@Test fun anIconLargeEnoughForTheHomeScreenIsKept() {
val icon = image("icon.png", 256, 256, Color.GREEN)
val cover = image("cover.png", 300, 450, Color.BLUE)
val bitmap = GameShortcuts.iconBitmap(game(icon = icon, art = cover))!!
assertEquals(256, bitmap.width)
assertEquals(Color.GREEN, bitmap.getPixel(128, 128))
}
@Test fun theSmallIconIsStillUsedWhenThereIsNoArt() {
val icon = image("icon.png", 32, 32, Color.GREEN)
val bitmap = GameShortcuts.iconBitmap(game(icon = icon, art = null))!!
assertEquals(32, bitmap.width)
assertEquals(Color.GREEN, bitmap.getPixel(16, 16))
}
private fun game(icon: File?, art: File?) =
Library.SteamGame(appId = 17480, name = "Game", art = art, library = "test", icon = icon)
private fun image(name: String, width: Int, height: Int, color: Int, band: Int = 0, bandColor: Int = color): File {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawColor(color)
if (band > 0) {
val paint = Paint().apply { this.color = bandColor }
canvas.drawRect(0f, 0f, width.toFloat(), band.toFloat(), paint)
canvas.drawRect(0f, (height - band).toFloat(), width.toFloat(), height.toFloat(), paint)
}
return File(dir, name).also { file -> file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } }
}
}
@@ -16,7 +16,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Games folders from earlier builds become entries, every game keeping what it had. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GamesFolderMigrationTest {
@@ -40,7 +39,6 @@ class GamesFolderMigrationTest {
StoreGameSidecar.file(store).writeText("""{"store":"gog","id":"1","title":"Store Game","exe":"Store.exe"}""")
File(pc, "Notes").mkdirs()
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
// What earlier scans had kept, by folder.
SessionPrefs.setAddedGameExe(app, beta.path, pick.path)
SessionPrefs.addedGameAppId(app, alpha.path, 0x8123_4567L)
SessionPrefs.addedGameAppId(app, beta.path, 0x8765_4321L)
@@ -63,11 +61,9 @@ class GamesFolderMigrationTest {
assertEquals(0x8765_4321L, games.getValue(beta.path).appId)
assertEquals("Alpha GOTY", games.getValue(alpha.path).name)
assertEquals(pick.path, games.getValue(beta.path).exe.path)
// The same path inside the session as before: the shortcut keeps its target.
assertEquals(AddedGames.GUEST_DIR + "/PC/Alpha/Alpha.exe", games.getValue(alpha.path).guestExe)
assertEquals(AddedGames.GUEST_DIR + "/PC/Beta/bin/Beta64.exe", games.getValue(beta.path).guestExe)
assertTrue(SessionPrefs.removedAddedGames(app).contains(gone.path))
// Not a library any more.
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
}
@@ -0,0 +1,25 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.Assert.assertEquals
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 LibraryArchTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun aScanReadsTheClientItWasGivenNotTheSelectedOne() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setSteamClientArch(app, "arm64")
val apps = File(SessionPrefs.steamRoot(app, "x86_64"), "steamapps").apply { mkdirs() }
File(apps, "appmanifest_440.acf").writeText("\"AppState\"\n{\n\t\"appid\"\t\t\"440\"\n\t\"name\"\t\t\"Team Fortress 2\"\n\t\"StateFlags\"\t\t\"4\"\n}\n")
assertEquals(listOf("Team Fortress 2"), Library.launchableGames(app, added = emptyList(), arch = "x86_64").map { it.name })
assertEquals(emptyList<String>(), Library.launchableGames(app, added = emptyList(), arch = "arm64").map { it.name })
}
}
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.frontend
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.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class LibraryCacheClientTest {
private val app get() = RuntimeEnvironment.getApplication()
private val games = listOf(Library.SteamGame(440, "Team Fortress 2", null, "Steam library"))
@Test fun aCacheFromBeforeTheClientWasRecordedIsArm64s() {
java.io.File(app.filesDir, "library-cache.json").writeText("""[{"appId":440,"name":"Team Fortress 2","library":"Steam library","gameId":440}]""")
val (games, x64) = LibraryCache.snapshot(app)
assertEquals(listOf("Team Fortress 2"), games.map { it.name })
assertFalse(x64)
}
@Test fun theListAndItsClientAreOneFile() {
LibraryCache.save(app, games, x64 = true)
assertEquals(listOf("library-cache.json"), app.filesDir.list().orEmpty().filter { it.startsWith("library-cache") })
assertEquals(listOf("Team Fortress 2") to true, LibraryCache.snapshot(app).let { (g, x) -> g.map { it.name } to x })
}
@Test fun theListsClientIsKeptUntilAListForAnotherIsSaved() {
LibraryCache.save(app, games, x64 = true)
assertTrue(LibraryCache.listedX64(app))
LibraryCache.save(app, emptyList())
assertTrue(LibraryCache.listedX64(app))
LibraryCache.save(app, games, x64 = false)
assertFalse(LibraryCache.listedX64(app))
}
}
@@ -0,0 +1,15 @@
package com.droiddeck.launcher.frontend
import org.junit.Assert.assertEquals
import org.junit.Test
class LibraryFromSteamClientTest {
@Test fun onlyTheClientsOwnInstallsAreDroppedOnASwitch() {
val games = listOf(
Library.SteamGame(440, "Team Fortress 2", null, "Steam library"),
Library.SteamGame(1, "God of War", null, Library.ADDED, gameId = 9_000_000_001L),
Library.SteamGame(2, "Store game", null, "Games", gameId = 9_000_000_002L, source = "gog"),
)
assertEquals(listOf("God of War", "Store game"), games.filterNot(Library::fromSteamClient).map { it.name })
}
}
@@ -0,0 +1,51 @@
package com.droiddeck.launcher.frontend
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class LogoPositionTest {
@Test fun steamsOwnJsonIsReadAndWrittenBack() {
val steam = """{"nVersion":1,"logoPosition":{"pinnedPosition":"BottomLeft","nWidthPct":50,"nHeightPct":50}}"""
assertEquals(LogoPosition.DEFAULT, LogoPosition.parse(steam))
assertEquals(LogoPosition.DEFAULT, LogoPosition.parse(LogoPosition.toJson(LogoPosition.DEFAULT).toString()))
}
@Test fun everyPinKeepsItsSteamName() {
for (pin in LogoPosition.Pin.values()) {
val json = LogoPosition.toJson(LogoPosition.sized(pin, 40))
assertEquals(pin.steam, json.getJSONObject("logoPosition").getString("pinnedPosition"))
assertEquals(pin, LogoPosition.parse(json)?.pin)
}
assertEquals(setOf("BottomLeft", "UpperLeft", "CenterCenter", "UpperCenter", "BottomCenter"), LogoPosition.Pin.values().map { it.steam }.toSet())
}
@Test fun sizesAreKeptInsideTheRange() {
assertEquals(LogoPosition.MAX_PCT, LogoPosition.sized(LogoPosition.Pin.CENTER, 400).widthPct)
assertEquals(LogoPosition.MIN_PCT, LogoPosition.sized(LogoPosition.Pin.CENTER, 0).heightPct)
val wild = """{"logoPosition":{"pinnedPosition":"CenterCenter","nWidthPct":900,"nHeightPct":-4}}"""
assertEquals(LogoPosition.Value(LogoPosition.Pin.CENTER, LogoPosition.MAX_PCT, LogoPosition.MIN_PCT), LogoPosition.parse(wild))
}
@Test fun somethingThatIsNotAPositionIsNotOne() {
assertNull(LogoPosition.parse("not json"))
assertNull(LogoPosition.parse("{}"))
assertNull(LogoPosition.parse("""{"logoPosition":{"pinnedPosition":"Nowhere","nWidthPct":5,"nHeightPct":5}}"""))
assertNull(LogoPosition.parse("""{"logoPosition":{"pinnedPosition":"CenterCenter"}}"""))
}
@Test fun clearingKeepsForeignKeysAndEmptiesAJsonThatHeldNothingElse() {
val mixed = LogoPosition.toJson(LogoPosition.DEFAULT, JSONObject().put("other", 1))
val kept = LogoPosition.without(mixed)
assertNotNull(kept)
assertEquals(1, kept!!.getInt("other"))
assertNull(LogoPosition.without(LogoPosition.toJson(LogoPosition.DEFAULT)))
}
}
@@ -0,0 +1,65 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamGameArtTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Before fun noGamesFolders() {
AddedGamesPublisher.now = true
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, emptyList())
}
private fun game(art: File? = null) = Library.SteamGame(620, "Portal 2", art, "Steam library")
private fun image(name: String) = File(tmp.root, name).apply { writeBytes(ByteArray(8)) }
@Test fun aChosenImageReplacesTheCoverAndResetBringsBackSteams() {
val stock = image("stock.jpg")
val picked = image("mine.png")
val option = AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)
assertTrue(SteamGameArt.choose(app, game(stock), AddedGameArt.Slot.COVER, option))
val shown = SteamGameArt.withOverrides(app, game(stock))
assertTrue(shown.art!!.name.matches(Regex("chosen-p-\\d+\\.png")))
val states = SteamGameArt.describe(app, game(stock))
assertTrue(states.first { it.slot == AddedGameArt.Slot.COVER }.chosen)
assertFalse(states.first { it.slot == AddedGameArt.Slot.BACKGROUND }.chosen)
assertEquals(picked.path, SteamGameArt.chosenSource(app, 620, AddedGameArt.Slot.COVER).second)
SteamGameArt.reset(app, game(stock), AddedGameArt.Slot.COVER)
assertEquals(stock, SteamGameArt.withOverrides(app, game(stock)).art)
assertNull(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER))
assertEquals("", SteamGameArt.chosenSource(app, 620, AddedGameArt.Slot.COVER).first)
}
@Test fun aGameWithoutChoicesIsLeftAsItIs() {
val g = game(image("stock.jpg"))
assertTrue(SteamGameArt.withOverrides(app, g) === g)
}
@Test fun aChoiceForOneGameDoesNotTouchAnother() {
val picked = image("mine.png")
SteamGameArt.choose(app, game(), AddedGameArt.Slot.BACKGROUND, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
val other = Library.SteamGame(730, "Counter-Strike 2", null, "Steam library")
assertTrue(SteamGameArt.withOverrides(app, other) === other)
assertTrue(SteamGameArt.withOverrides(app, game()).hero!!.name.startsWith("chosen-hero"))
}
}
@@ -0,0 +1,241 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamGridTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
private lateinit var grid: File
@Before fun account() {
AddedGamesPublisher.now = true
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, emptyList())
grid = File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config/grid")
}
private fun game() = Library.SteamGame(620, "Portal 2", null, "Steam library")
private fun target() = SteamGrid.target(game(), app)
private fun image(name: String, size: Int) = File(tmp.root, name).apply { writeBytes(ByteArray(size) { 1 }) }
@Test fun aChoiceIsPlacedInTheGridFolderWhileSteamIsClosed() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val picked = image("mine.png", 12)
SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
assertEquals(12L, File(grid, "620p.png").length())
SteamGameArt.reset(app, game(), AddedGameArt.Slot.COVER)
assertFalse(File(grid, "620p.png").exists())
}
@Test fun aWideCoverGoesToTheUnsuffixedGridFileAndComesBackFromSteam() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val picked = image("wide.png", 14)
assertTrue(SteamGameArt.choose(app, game(), AddedGameArt.Slot.WIDE, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
assertEquals(14L, File(grid, "620.png").length())
assertFalse(File(grid, "620p.png").exists())
assertTrue(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.WIDE)!!.name.matches(Regex("chosen-header-\\d+\\.png")))
assertNull(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER))
File(grid, "620.png").delete()
assertTrue(SteamGrid.sync(app, listOf(target())))
assertNull(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.WIDE))
}
private val corner = LogoPosition.Value(LogoPosition.Pin.UPPER_CENTER, 35, 35)
@Test fun aLogoPositionIsWrittenToSteamsJsonKeepingWhatElseIsInIt() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
grid.mkdirs()
File(grid, "620.json").writeText("""{"nVersion":1,"other":"kept"}""")
assertTrue(SteamGameArt.setPosition(app, game(), corner))
val written = org.json.JSONObject(File(grid, "620.json").readText())
assertEquals("kept", written.getString("other"))
assertEquals(corner, LogoPosition.parse(written))
assertEquals(corner, SteamGameArt.position(app, game()))
assertTrue(SteamGameArt.setPosition(app, game(), null))
val left = org.json.JSONObject(File(grid, "620.json").readText())
assertFalse(left.has("logoPosition"))
assertEquals("kept", left.getString("other"))
assertNull(SteamGameArt.position(app, game()))
}
@Test fun aLogoPositionAloneLeavesNoFileBehindWhenCleared() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
assertTrue(SteamGameArt.setPosition(app, game(), corner))
assertEquals(corner, LogoPosition.parse(File(grid, "620.json").readText()))
assertTrue(SteamGameArt.setPosition(app, game(), null))
assertFalse(File(grid, "620.json").exists())
}
@Test fun aLogoPositionSetInSteamIsTakenOverAndRemovingItDropsIt() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
grid.mkdirs()
val theirs = File(grid, "620.json").apply { writeText(LogoPosition.toJson(corner).toString()) }
SteamGrid.sync(app, listOf(target()))
assertEquals(corner, SteamGameArt.position(app, game()))
theirs.writeText(LogoPosition.toJson(LogoPosition.Value(LogoPosition.Pin.CENTER, 80, 80)).toString())
theirs.setLastModified(theirs.lastModified() + 5000)
SteamGrid.sync(app, listOf(target()))
assertEquals(LogoPosition.Pin.CENTER, SteamGameArt.position(app, game())?.pin)
theirs.delete()
SteamGrid.sync(app, listOf(target()))
assertNull(SteamGameArt.position(app, game()))
}
@Test fun aLogoPositionChosenHereIsNotTakenBackAsASteamChange() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
assertTrue(SteamGameArt.setPosition(app, game(), corner))
SteamGrid.sync(app, listOf(target()))
assertEquals(corner, SteamGameArt.position(app, game()))
assertEquals(corner, LogoPosition.parse(File(grid, "620.json").readText()))
}
@Test fun aLogoPositionWithoutSteamAccountIsStillKeptHere() {
assertTrue(SteamGameArt.setPosition(app, game(), corner))
assertEquals(corner, SteamGameArt.position(app, game()))
}
@Test fun artSetInSteamIsTakenOverAndRemovingItInSteamDropsIt() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
grid.mkdirs()
val theirs = File(grid, "620_hero.jpg").apply { writeBytes(ByteArray(20) { 2 }) }
assertTrue(SteamGrid.sync(app, listOf(target())))
assertEquals(20L, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.BACKGROUND)?.length())
assertEquals(AddedGameArt.STEAM, SteamGameArt.chosenSource(app, 620, AddedGameArt.Slot.BACKGROUND).first)
assertFalse(SteamGrid.sync(app, listOf(target())))
theirs.delete()
assertTrue(SteamGrid.sync(app, listOf(target())))
assertNull(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.BACKGROUND))
}
@Test fun theOtherClientsEmptyGridGetsTheChoiceInsteadOfDroppingIt() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val picked = image("mine.png", 12)
SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
assertFalse(SteamGrid.sync(app, listOf(target())))
val x64 = File(SessionPrefs.steamRoot(app, "x86_64"), "userdata/123/config").apply { mkdirs() }
SessionPrefs.setSteamClientArch(app, "x86_64")
assertFalse(SteamGrid.sync(app, listOf(target())))
assertEquals(12L, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)?.length())
assertEquals(12L, File(x64, "grid/620p.png").length())
SessionPrefs.setSteamClientArch(app, "arm64")
assertFalse(SteamGrid.sync(app, listOf(target())))
assertEquals(12L, File(grid, "620p.png").length())
}
@Test fun aChoiceMadeHereIsNotTakenBackAsASteamChange() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val picked = image("mine.png", 12)
SteamGameArt.choose(app, game(), AddedGameArt.Slot.LOGO, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
File(grid, "620_logo.png").writeBytes(picked.readBytes())
assertFalse(SteamGrid.sync(app, listOf(target())))
assertEquals(AddedGameArt.FILE, SteamGameArt.chosenSource(app, 620, AddedGameArt.Slot.LOGO).first)
}
@Test fun artDroidDeckPlacedItselfIsNotTakenAsAChoice() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
grid.mkdirs()
File(grid, "620p.png").writeBytes(ByteArray(7))
File(grid, ".droiddeck-art.json").writeText("""{"620p.png": 7}""")
assertFalse(SteamGrid.sync(app, listOf(target())))
assertNull(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER))
}
@Test fun withoutASteamAccountNothingHappens() {
assertFalse(SteamGrid.sync(app, listOf(target())))
}
@Test fun aSteamImageAlreadyThereIsKeptOverAnOlderChoiceOnTheFirstLook() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val old = image("old.png", 5)
val dir = SteamGameArt.dir(app, 620)
assertTrue(AddedGameArt.store(dir, AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, old.path, old.path)))
grid.mkdirs()
File(grid, "620p.png").writeBytes(ByteArray(30) { 3 })
assertTrue(SteamGrid.sync(app, listOf(target())))
assertEquals(30L, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)?.length())
assertEquals(30L, File(grid, "620p.png").length())
}
@Test fun aChoiceSurvivesWhenOnlyDroidDecksOwnWriterFileIsInTheFolder() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val picked = image("mine.png", 12)
SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
File(grid, "620p.png").writeBytes(ByteArray(12) { 9 })
File(grid, ".droiddeck-art.json").writeText("""{"620p.png": 12}""")
assertFalse(SteamGrid.sync(app, listOf(target())))
assertEquals(12L, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)?.length())
}
@Test fun anImageSteamCannotReadIsNotWrittenAndTheCurrentOneStays() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val png = image("mine.png", 12)
SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, png.path, png.path))
val ico = image("mine.ico", 6)
SteamGrid.write(app, target(), AddedGameArt.Slot.COVER, ico)
assertEquals(12L, File(grid, "620p.png").length())
assertFalse(File(grid, "620p.ico").exists())
}
@Test fun aChoiceSteamCannotReadIsRefusedAndNotKept() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val ico = image("mine.ico", 6)
assertFalse(SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, ico.path, ico.path)))
assertNull(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER))
}
@Test fun aStaleFileLeftByAnEarlierFailedWriteIsReplacedByTheLocalChoice() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val picked = image("mine.png", 12)
SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)!!.writeBytes(ByteArray(15) { 4 })
assertFalse(SteamGrid.sync(app, listOf(target())))
assertEquals(15L, File(grid, "620p.png").length())
}
@Test fun aRefusedReplacementLeavesTheLastGoodChoiceInPlace() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val png = image("mine.png", 12)
assertTrue(SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, png.path, png.path)))
val kept = SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)
val ico = image("mine.ico", 6)
assertFalse(SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, ico.path, ico.path)))
assertEquals(kept, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER))
assertEquals(12L, File(grid, "620p.png").length())
}
@Test fun choicesMadeInTheSameMillisecondGetDifferentNamesAndTheLastOneWins() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val dir = SteamGameArt.dir(app, 620)
val names = (1..5).map { n ->
val image = image("pick$n.png", n)
AddedGameArt.storeNew(dir, AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, image.path, image.path))!!.name
}
assertEquals(5, names.toSet().size)
assertEquals(names.sorted(), names)
assertEquals(5L, AddedGameArt.chosen(dir, AddedGameArt.Slot.COVER)?.length())
}
}
@@ -17,13 +17,11 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Steam's app info asked anonymously: the answer read, batched, kept, and asked only when needed. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamPicsTest {
private val app get() = RuntimeEnvironment.getApplication()
/** Dragon's Dogma 2's app info as Steam's anonymous PICS answer carried it (recorded 2026-10-10). */
private val recorded: String get() = javaClass.classLoader!!.getResource("steam-pics/app_2054970.vdf")!!.readText()
@After fun tearDown() { SteamAppInfo.pics = { SteamPics.lookup(it) } }
@@ -32,7 +30,6 @@ class SteamPicsTest {
val info = SteamPics.infoFromKeyValues(recorded)!!
assertEquals("Dragon's Dogma 2", info.name)
assertEquals(listOf("228988"), info.sharedDepots)
// VC++ 2019 for the Windows components.
assertEquals(listOf("vcredist2019_dll" to "VC++ 2019"), WinCompSources.steamDepots(info.sharedDepots))
}
@@ -66,11 +63,9 @@ class SteamPicsTest {
val calls = ArrayList<List<Int>>()
SteamAppInfo.pics = { ids -> calls.add(ids); mapOf(2054970 to SteamPics.infoFromKeyValues(recorded), 7 to null) }
assertTrue(SteamAppInfo.lookup(app, listOf(2054970, 7)))
// One connection for both.
assertEquals(listOf(listOf(2054970, 7)), calls)
assertEquals(listOf("228988"), SteamAppInfo.info(app, 2054970)!!.sharedDepots)
assertNull(SteamAppInfo.info(app, 7))
// Kept: nothing asked again (the miss waits a week).
assertFalse(SteamAppInfo.lookup(app, listOf(2054970, 7)))
assertEquals(1, calls.size)
assertEquals("hit", SteamAppInfo.state(app, 2054970))
@@ -78,7 +73,6 @@ class SteamPicsTest {
}
@Test fun noNetworkWhenTheClientsCacheHasTheApp() {
// An appinfo.vdf with the app in it (built as in WinCompSourcesTest).
val file = SteamAppInfo.appinfoFile(app)
WinCompSourcesTest.writeAppinfo(file, 1145360)
SteamAppInfo.pics = { fail("asked Steam"); null }
@@ -0,0 +1,56 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreGameArtTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Before fun setUp() {
AddedGamesPublisher.now = true
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
private fun install(store: Store, id: String, title: String): File {
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.installRoot(app), store), StoreInstallRoot.folderName(title, id))
File(folder, "Game.exe").apply { parentFile!!.mkdirs(); writeText("game") }
StoreGameSidecar(store, id, title, "Game.exe").write(folder)
return folder
}
@Test fun anArtChoiceOnAStoreGameIsKeptShownAndResetsWithoutTouchingItsTitle() {
for ((store, id, title) in listOf(Triple(Store.GOG, "1207658924", "Heroes III"), Triple(Store.EPIC, "abc", "Celeste"), Triple(Store.AMAZON, "amzn1.x", "Yakuza 0"))) {
val folder = install(store, id, title)
val image = File(tmp.root, "$id.png").apply { writeBytes(ByteArray(9) { 1 }) }
val option = AddedGameArt.Option(AddedGameArt.FILE, image.path, image.path)
assertTrue(AddedGameEdits.setArt(app, folder.path, AddedGameArt.Slot.COVER, option))
val game = AddedGames.single(app, folder.path)!!
assertEquals(title, game.name)
assertEquals(store.id, game.source)
val shown = Library.addedGame(app, game)
assertEquals(AddedGameArt.chosen(AddedGameArt.cacheDir(app, game), AddedGameArt.Slot.COVER), shown.art)
assertEquals(9L, shown.art?.length())
AddedGameEdits.resetArt(app, folder.path, AddedGameArt.Slot.COVER)
assertNull(AddedGameArt.chosen(AddedGameArt.cacheDir(app, game), AddedGameArt.Slot.COVER))
}
}
}
@@ -20,7 +20,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Each source's list of Windows components, how it maps to the catalog, and what turns on by itself. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class WinCompSourcesTest {
@@ -35,7 +34,6 @@ class WinCompSourcesTest {
private fun auto(findings: List<WinCompSources.Finding>) = findings.filter { it.auto }.map { it.component to it.origin }
// ---- mapping tables ----
@Test fun gogDependencyIdsMapToComponents() {
assertEquals(listOf("vcredist2015"), WinCompSources.gog("MSVC2017_x64"))
@@ -62,7 +60,6 @@ class WinCompSourcesTest {
assertEquals(listOf("vcredist2015_dll" to "VC++ 2015", "d3dx9" to "DirectX (June 2010)"), WinCompSources.steamDepots(listOf("228986", "228990", "999")))
}
// ---- per source ----
@Test fun steamTakesItsSharedDepotsAndTurnsThemOn() {
val steamapps = tmp.newFolder("steamapps")
@@ -80,7 +77,6 @@ class WinCompSourcesTest {
sidecar(folder, Store.GOG, mapOf(WinCompSources.GOG_DEPENDENCIES to "MSVC2017_x64,DirectX,ISI"))
val findings = WinCompSources.forGame(app, game(folder, "gog"))
assertEquals(listOf("vcredist2015" to WinCompSources.Origin.GOG, "d3dx9" to WinCompSources.Origin.GOG), auto(findings))
// ISI is none of ours: a suggestion under its own name.
assertEquals(listOf("ISI"), findings.filter { it.component == null }.map { it.original })
}
@@ -105,12 +101,10 @@ class WinCompSourcesTest {
assertEquals(listOf("Activate.exe"), findings.filter { it.component == null }.map { it.original })
}
// ---- Custom: certainty decides ----
private fun appinfo(file: File, appId: Int) = writeAppinfo(file, appId)
companion object {
/** A version 29 appinfo.vdf with one app, whose depots point at two Steamworks Shared ones. */
fun writeAppinfo(file: File, appId: Int) {
val strings = listOf("appinfo", "common", "name", "depots", "228986", "depotfromapp", "228990", "1001", "maxsize")
fun key(s: String) = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(strings.indexOf(s)).array()
@@ -173,7 +167,6 @@ class WinCompSourcesTest {
assertEquals(listOf("vcredist2013" to WinCompSources.Origin.FOLDER), findings.map { it.component to it.origin })
}
// ---- what turns on, and the user's switches ----
private fun ready(name: String) = WinComponents.Component(name, "", "", "ready", emptyList(),
listOf(WinComponents.Step("override_dll", JSONObject().put("dll", "x").put("type", "native"))))
@@ -187,7 +180,6 @@ class WinCompSourcesTest {
WinCompSources.Finding("d3dx9", "d3dx9_43.dll", WinCompSources.Origin.FOLDER, false),
)
val picks = AutoComponents.autoPicks(findings, catalog)
// The detector's name installs as its DLL twin; physx cannot install; the folder scan only recommends.
assertEquals(listOf("vcredist2015_dll"), picks.keys.toList())
assertEquals("GOG", picks.getValue("vcredist2015_dll").kind)
}
@@ -199,11 +191,9 @@ class WinCompSourcesTest {
WinComponents.setUser(app, key, "d3dx9", false)
WinComponents.setUser(app, key, "oalinst_dll", true)
assertEquals(listOf("xact", "oalinst_dll"), WinComponents.picks(app, key))
// A new automatic list keeps the user's switches.
WinComponents.setAuto(app, key, mapOf("d3dx9" to WinComponents.AutoReason("GOG", listOf("DirectX"))))
assertEquals(listOf("oalinst_dll"), WinComponents.picks(app, key))
assertEquals(mapOf("d3dx9" to false, "oalinst_dll" to true), WinComponents.selection(app, key).user)
// What the launch reads stays version 1 with the effective list.
val text = File(app.filesDir, "wincomponents.json").readText()
assertEquals(1, JSONObject(text).getInt("version"))
assertEquals("oalinst_dll", JSONObject(text).getJSONObject("games").getJSONArray(key).getString(0))
@@ -219,10 +209,8 @@ class WinCompSourcesTest {
val folder = tmp.newFolder("Shared")
val exe = File(folder, "Shared.exe").apply { writeText("x") }
val art = AddedGames.Game(folder, "Shared", exe, "/g/Shared.exe", "/g", 0x81234567L, 0L, emptyList())
// The art fetch finds it by name ...
val match = AddedGameArt.steamMatch(app, art) { 4242 }
assertEquals(4242, match.appId)
// ... and the components read the same record.
assertEquals(4242, SteamMatch.get(app, folder.path)!!.appId)
assertEquals(SteamMatch.Certainty.NAME, SteamMatch.get(app, folder.path)!!.certainty)
assertFalse(WinCompSources.forGame(app, game(folder, Library.ADDED)).any { it.auto })
@@ -268,7 +256,6 @@ class WinCompSourcesTest {
@Test fun aSteamListedComponentNotYetDownloadedTurnsOnWhenItLands() = withFakeWorker {
installedNow.add("d3dx9")
val game = payback()
// The user had switched one off: it is never downloaded for an automatic pick.
WinComponents.setUser(app, "1262580", "vcredist2019_dll", false)
AutoComponents.queueGame(app, game, asked = true)
assertEquals(listOf("vcredist2013_dll"), downloaded)
@@ -276,7 +263,6 @@ class WinCompSourcesTest {
assertEquals(setOf("d3dx9", "vcredist2013_dll", "vcredist2019_dll"), sel.auto.keys)
assertEquals(setOf("d3dx9", "vcredist2013_dll"), WinComponents.picks(app, "1262580").toSet())
assertEquals("STEAM", sel.auto.getValue("vcredist2013_dll").kind)
// The list is kept for the page.
assertEquals(3, AutoComponents.cachedFindings(app, "1262580")!!.count { it.auto })
}
@@ -297,7 +283,6 @@ class WinCompSourcesTest {
AutoComponents.unfavourable = { true }
AutoComponents.queueGame(app, game, asked = false)
assertTrue(downloaded.isEmpty())
// The user opens the page: asked for, it goes.
AutoComponents.queueGame(app, game, asked = true)
assertEquals(3, downloaded.size)
}
@@ -311,7 +296,6 @@ class WinCompSourcesTest {
assertEquals(listOf("g:1262580"), AutoComponents.queued())
session = false
AutoComponents.drain(app)
// Each component once, though two games could want it.
assertEquals(downloaded.distinct(), downloaded)
}
@@ -319,7 +303,6 @@ class WinCompSourcesTest {
val game = payback()
AutoComponents.online = { false }
AutoComponents.queueGame(app, game, asked = true)
// The list is worked out offline; the downloads wait.
assertTrue(downloaded.isEmpty())
assertTrue(AutoComponents.queued().all { it.startsWith("c:") })
AutoComponents.online = { true }
@@ -327,7 +310,6 @@ class WinCompSourcesTest {
assertEquals(3, downloaded.size)
}
// ---- older store installs: the list read once from the store ----
@Test fun anOlderGogInstallGetsItsListFromTheStoreOnce() {
val folder = tmp.newFolder("DOOM I Enhanced")
@@ -338,7 +320,6 @@ class WinCompSourcesTest {
try {
assertTrue(StoreListBackfill.fill(app, folder))
assertEquals("MSVC2019_x64,DirectX", StoreGameSidecar.read(folder)!!.extra[WinCompSources.GOG_DEPENDENCIES])
// Kept like a fresh install: not fetched again.
assertFalse(StoreListBackfill.fill(app, folder))
assertEquals(1, fetches)
assertEquals(listOf("vcredist2019" to WinCompSources.Origin.GOG, "d3dx9" to WinCompSources.Origin.GOG), auto(WinCompSources.forGame(app, game(folder, "gog"))))
@@ -377,7 +358,6 @@ class WinCompSourcesTest {
AutoComponents.online = { true }
assertFalse(StoreListBackfill.fill(app, folder))
assertFalse(StoreListBackfill.fill(app, folder))
// Signed out or the store refused: once, then a week's rest; the sidecar is untouched.
assertEquals(1, fetches)
assertTrue(StoreListBackfill.needs(StoreGameSidecar.read(folder)!!))
} finally {
@@ -386,16 +366,13 @@ class WinCompSourcesTest {
}
}
// ---- apps the client never saw ----
@Test fun anAppTheClientLearnsLaterIsReadOnceItsCacheIsWritten() {
val file = SteamAppInfo.appinfoFile(app)
appinfo(file, 1)
file.setLastModified(1_000_000_000_000L)
assertEquals(null, SteamAppInfo.info(app, 1145360))
// Unchanged file: the miss stands (no re-read).
assertEquals(null, SteamAppInfo.info(app, 1145360))
// The client wrote its cache with the app in it: read at once, not a week later.
appinfo(file, 1145360)
file.setLastModified(1_000_000_100_000L)
assertEquals(listOf("228986", "228990"), SteamAppInfo.info(app, 1145360)!!.sharedDepots)
@@ -418,7 +395,6 @@ class WinCompSourcesTest {
assertTrue(StoreListBackfill.needs(StoreGameSidecar.read(older)!!))
}
// ---- a game installed during the session ----
private fun manifest(dir: File, appId: Int, state: Int, time: Long) =
File(dir, "appmanifest_$appId.acf").apply {
@@ -431,7 +407,6 @@ class WinCompSourcesTest {
manifest(steamapps, 12900, 1026, 1_000_000L)
manifest(steamapps, 570, 4, 1_000_000L)
val watch = SessionInstalls.Watch { listOf(steamapps) }
// What was there when the session started is not new.
assertTrue(watch.poll().isEmpty())
assertTrue(watch.poll().isEmpty())
manifest(steamapps, 12900, 4, 2_000_000L)
@@ -448,14 +423,12 @@ class WinCompSourcesTest {
gameUp = true
AutoComponents.queueInSession(app, installed)
assertTrue(downloaded.isEmpty())
// Other work stays paused in the session.
val other = game(tmp.newFolder("Other"), Library.ADDED)
AutoComponents.queueGame(app, other, asked = false)
gameUp = false
AutoComponents.drain(app)
assertEquals(3, downloaded.size)
assertEquals(setOf("d3dx9", "vcredist2013_dll", "vcredist2019_dll"), WinComponents.picks(app, "1262580").toSet())
// Nothing left pending for the launch to wait on; the other game still waits for the session's end.
assertEquals(0, AutoComponents.Pending.read(app).length())
assertEquals(listOf("g:${AutoComponents.appKey(other)}"), AutoComponents.queued())
session = false
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
import java.util.Locale
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import com.droiddeck.launcher.R
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class CalibrationDistanceCheckTest {
private val context get() = RuntimeEnvironment.getApplication()
private fun board(z: Float)=List(24) { i -> SpatialVector((i%4-1.5f)*.03f,(i/4-2.5f)*.03f,z) }
@Test
@Config(qualifiers = "fr")
fun rejectedCaptureExplainsTheProblemInTheSelectedLanguage() {
val result = CalibrationDistanceCheck.evaluate(context, .3048f, 3, null)
assertFalse(result.accepted)
assertEquals(context.getString(R.string.spatial_distance_corners, 3), result.message)
assertFalse(result.message.contains("checkerboard corners detected"))
assertTrue(result.message.contains("3 / 24"))
}
@Test fun missingAndPartialBoardsExplainVisibilityRatherThanDistance() {
for (count in listOf(0,12,23)) {
val result=CalibrationDistanceCheck.evaluate(context,.508f,count,null)
assertFalse(result.accepted)
assertTrue(result.message.contains("$count / 24"))
}
}
@Test fun fullBoardWithRejectedStereoGeometryCannotPass() {
assertFalse(CalibrationDistanceCheck.evaluate(context,.508f,24,null).accepted)
assertFalse(CalibrationDistanceCheck.evaluate(context,.508f,24,board(.508f).dropLast(1)).accepted)
assertFalse(CalibrationDistanceCheck.evaluate(context,.508f,24,board(.508f).toMutableList().also {
it[0]=SpatialVector(z=Float.NaN)
}).accepted)
}
@Test fun preservesFiveCentimeterToleranceAndReportsBothUnits() {
val locale=Locale.getDefault()
try {
Locale.setDefault(Locale.US)
assertTrue(CalibrationDistanceCheck.evaluate(context,.508f,24,board(.508f)).accepted)
assertTrue(CalibrationDistanceCheck.evaluate(context,.3048f,24,board(.3048f)).accepted)
assertFalse(CalibrationDistanceCheck.evaluate(context,.508f,24,board(.3048f)).accepted)
assertTrue(CalibrationDistanceCheck.evaluate(context,.508f,24,board(.557f)).accepted)
val result=CalibrationDistanceCheck.evaluate(context,.508f,24,board(.60f))
assertFalse(result.accepted)
assertTrue(result.message.contains("60.0 cm (23.62 in)"))
assertTrue(result.message.contains("50.8 cm (20.00 in)"))
} finally { Locale.setDefault(locale) }
}
@Test fun checksCameraToCenterDistanceRatherThanOnlyForwardDepth() {
val points=board(.4f).map { it+SpatialVector(x=.3f) }
assertTrue(CalibrationDistanceCheck.evaluate(context,.5f,24,points).accepted)
assertFalse(CalibrationDistanceCheck.evaluate(context,.4f,24,points).accepted)
}
@Test fun rejectsInvalidRequestedDistances() {
for(distance in listOf(0f,Float.NaN,Float.POSITIVE_INFINITY)) {
assertThrows(IllegalArgumentException::class.java) { CalibrationDistanceCheck.evaluate(context,distance,24,board(.5f)) }
}
}
}
@@ -0,0 +1,47 @@
package com.droiddeck.launcher.glasses
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk=[28],manifest=Config.NONE)
class CalibrationObservationDataTest {
private fun view(count: Int=24) = JSONObject().put("objects",JSONArray((0 until count).map {
JSONArray(listOf((it%4+1)*0.03,(it/4+1)*0.03,0.0))
})).put("left",JSONArray((0 until count).map { JSONArray(listOf(100.0+it,200.0)) }))
.put("right",JSONArray((0 until count).map { JSONArray(listOf(80.0+it,200.0)) }))
.put("head",JSONArray(listOf(0.1,0.2,0.3,1.0,0.0,0.0,0.0)))
@Test fun preservesPartialBoardCorrespondencesAndHeadPose() {
for(count in listOf(12,20,24)) {
val restored=CalibrationObservationData.parse(JSONObject(view(count).toString()))
assertEquals(count,restored.objects.size)
assertEquals(20.0,restored.left.last()[0]-restored.right.last()[0],0.0)
assertEquals(SpatialVector(.1f,.2f,.3f),restored.head.position)
assertEquals(SpatialRotation(),restored.head.rotation)
}
}
@Test fun rejectsTruncatedOrMismatchedCorrespondences() {
assertThrows(IllegalArgumentException::class.java) { CalibrationObservationData.parse(view(11)) }
assertThrows(IllegalArgumentException::class.java) { CalibrationObservationData.parse(view(25)) }
assertThrows(IllegalArgumentException::class.java) {
CalibrationObservationData.parse(view().put("right",view(20).getJSONArray("right")))
}
assertThrows(IllegalArgumentException::class.java) {
CalibrationObservationData.parse(view().also { it.getJSONArray("left").put(0,JSONArray(listOf(1.0))) })
}
}
@Test fun rejectsInvalidHeadRotationAndFloatOverflow() {
assertThrows(IllegalStateException::class.java) {
CalibrationObservationData.parse(view().put("head",JSONArray(listOf(0,0,0,0,0,0,0))))
}
assertThrows(IllegalStateException::class.java) {
CalibrationObservationData.parse(view().put("head",JSONArray(listOf(1e100,0,0,1,0,0,0))))
}
}
}
@@ -0,0 +1,450 @@
package com.droiddeck.launcher.glasses
import android.content.Context
import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Assert.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@LooperMode(LooperMode.Mode.PAUSED)
class Glasses3dRoutingTest {
private val handler = Handler(Looper.getMainLooper())
private val commands = mutableListOf<Pair<Int, Boolean>>()
private val hardwareMessages = mutableListOf<Int>()
private lateinit var stateBefore: GlassesState
private lateinit var settingsBefore: GlassesSettings
private val supportedModels: List<GlassesModel> =
listOf("One", "Lite", "Pro", "Pro 2", "Luma", "Luma Pro", "Luma Cyber", "Luma Ultra", "Beast")
.map { VitureProtocol.sdkModel(it)!! } + listOf(
RayNeoModel.model(0x1bbb, 0xaf50, "RayNeo Air 4 Pro")!!,
RayNeoModel.model(0x3941, 0xaf50, "RayNeo GT")!!,
RayNeoModel.model(0x3941, 0xaf50, "RayNeo GT MAX")!!,
XrealModel,
)
private fun field(name: String) = Glasses::class.java.getDeclaredField(name).apply { isAccessible = true }
@Before fun prepare() {
stateBefore = Glasses.state.value
settingsBefore = Glasses.settings.value
val context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("glasses", Context.MODE_PRIVATE).edit().clear().commit()
field("app").set(null, context)
field("handler").set(null, handler)
field("model").set(null, VitureProtocol.model(0x1019, null))
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = GlassesState(connected = true, controllable = true,
displayId = 2, width = 1920, height = 1080)
@Suppress("UNCHECKED_CAST")
val settings = field("_settings").get(null) as MutableStateFlow<GlassesSettings>
settings.value = GlassesSettings(gameOnGlasses = false)
field("link").set(null, object : GlassesLink {
override val hasImu = false
override fun send(msgId: Int, payload: ByteArray): Boolean {
hardwareMessages += msgId
if (msgId == VitureProtocol.MSG_DISPLAY)
commands += (payload[0].toInt() and 255) to Glasses.settings.value.gameOnGlasses
return true
}
override fun close() {}
})
}
@After fun cleanUp() {
handler.removeCallbacksAndMessages(null)
field("link").set(null, null)
(field("modeState").get(null) as GlassesModeState).apply { manual(); sent(false, 0) }
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = stateBefore
@Suppress("UNCHECKED_CAST")
val settings = field("_settings").get(null) as MutableStateFlow<GlassesSettings>
settings.value = settingsBefore
}
@Test fun lumaJoyConsDefaultOffPersistAndExcludeBareHands() {
assertFalse(GlassesSettings().joyConTracking)
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(supportsSpatial = true)
@Suppress("UNCHECKED_CAST")
val settings = field("_settings").get(null) as MutableStateFlow<GlassesSettings>
Glasses.setJoyConTracking(true)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.settings.value.joyConTracking)
settings.value = settings.value.copy(positionalTracking = true, handControllers = true)
Glasses.setJoyConTracking(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.settings.value.joyConTracking)
assertFalse(Glasses.settings.value.handControllers)
val prefs = RuntimeEnvironment.getApplication().getSharedPreferences("glasses", Context.MODE_PRIVATE)
assertTrue(prefs.getBoolean("joyConTracking", false))
val loaded = Glasses::class.java.getDeclaredMethod("load").apply { isAccessible = true }.invoke(Glasses) as GlassesSettings
assertTrue(loaded.joyConTracking)
Glasses.setHandControllers(true)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.settings.value.joyConTracking)
assertTrue(Glasses.settings.value.handControllers)
SpatialTracking.setControllers(false, false)
}
@Test fun otherGlassesRejectSpatialEnableAndRestartWithoutClosingTheirLink() {
val before = Glasses.settings.value
val link = field("link").get(null)
Glasses.setPositionalTracking(true)
Glasses.restartSpatialTracking()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(before, Glasses.settings.value)
assertSame(link, field("link").get(null))
assertTrue(hardwareMessages.isEmpty())
}
@Test fun manual3dSelectsAndSavesGlassesOutputBeforeSwitchingTheDisplay() {
Glasses.set3d(true)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x32 to true), commands)
assertTrue(Glasses.settings.value.gameOnGlasses)
val prefs = RuntimeEnvironment.getApplication().getSharedPreferences("glasses", Context.MODE_PRIVATE)
assertTrue(prefs.getBoolean("gameOnGlasses", false))
}
@Test fun nativeThirtyHzIsSavedWithoutSendingAFabricatedHardwareMode() {
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
Glasses.setGameOnGlasses(true)
shadowOf(Looper.getMainLooper()).idle()
state.value = state.value.copy(supports30Hz = true)
Glasses.setRefreshHz(30)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(30, Glasses.settings.value.refreshHz)
assertTrue(hardwareMessages.isEmpty())
state.value = state.value.copy(sbs = true, width = 3840)
Glasses.setSbsHz(30)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(30, Glasses.settings.value.sbsHz)
assertTrue(hardwareMessages.isEmpty())
val saved = Glasses::class.java.getDeclaredMethod("load").apply { isAccessible = true }
.invoke(Glasses) as GlassesSettings
assertEquals(30, saved.refreshHz)
assertEquals(30, saved.sbsHz)
}
@Test fun unsupportedThirtyHzRequestsLeavePreferencesAndHardwareUnchanged() {
val before = Glasses.settings.value
Glasses.setRefreshHz(30)
Glasses.setSbsHz(30)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(before, Glasses.settings.value)
assertTrue(hardwareMessages.isEmpty())
}
@Test fun automaticSteamVr3dAlsoSelectsGlassesOutput() {
Glasses.set3dForVr(true)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x32 to true), commands)
assertTrue(Glasses.settings.value.gameOnGlasses)
}
@Test fun returningTo2dKeepsTheGameOnGlasses() {
Glasses.set3d(true)
shadowOf(Looper.getMainLooper()).idle()
Glasses.set3d(false)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x32 to true, 0x34 to true), commands)
assertTrue(Glasses.settings.value.gameOnGlasses)
}
@Test fun turningOff3dDoesNotEnableGlassesOutput() {
Glasses.set3d(false)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x34 to false), commands)
assertFalse(Glasses.settings.value.gameOnGlasses)
}
@Test fun turningOffGlassesOutputRestores2dOnEverySupportedModel() {
for (model in supportedModels) {
selectModel(model)
Glasses.set3dof(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.settings.value.screen3dof)
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(sbs = true, width = 3840)
commands.clear()
Glasses.setGameOnGlasses(false)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(model.mode(120, false) to true), commands)
assertFalse(Glasses.settings.value.gameOnGlasses)
assertFalse(Glasses.settings.value.screen3dof)
assertEquals(GlassesSettings.PICTURE_AUTO, Glasses.settings.value.picture3d)
val prefs = RuntimeEnvironment.getApplication().getSharedPreferences("glasses", Context.MODE_PRIVATE)
assertFalse(prefs.getBoolean("gameOnGlasses", true))
}
}
@Test fun turningOffGlassesOutputCancelsAnUnconfirmedStereoSwitch() {
Glasses.set3d(true)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.state.value.sbs)
assertTrue(Glasses.state.value.switching3d)
Glasses.setGameOnGlasses(false)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x32 to true, 0x34 to true), commands)
assertFalse(Glasses.state.value.switching3d)
assertFalse(Glasses.settings.value.gameOnGlasses)
}
@Test fun turningOffGlassesOutputTakesOwnershipFromAutomaticVr() {
Glasses.set3dForVr(true)
shadowOf(Looper.getMainLooper()).idle()
Glasses.setGameOnGlasses(false)
shadowOf(Looper.getMainLooper()).idle()
Glasses.set3dForVr(false)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x32 to true, 0x34 to true), commands)
assertFalse(Glasses.state.value.switching3d)
assertFalse(Glasses.settings.value.gameOnGlasses)
}
@Test fun togglingGlassesOutputIn2dDoesNotSendDisplayCommands() {
Glasses.setGameOnGlasses(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.settings.value.gameOnGlasses)
Glasses.setGameOnGlasses(false)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.settings.value.gameOnGlasses)
assertTrue(hardwareMessages.isEmpty())
}
@Test fun turningOffGlassesOutputDisablesVirtualScreenAndSavesTheChoice() {
selectModel(supportedModels.first())
Glasses.set3dof(true)
shadowOf(Looper.getMainLooper()).idle()
Glasses.setGameOnGlasses(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.settings.value.screen3dof)
Glasses.setGameOnGlasses(false)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.settings.value.screen3dof)
assertEquals(GlassesSettings.PICTURE_AUTO, Glasses.settings.value.picture3d)
val saved = Glasses::class.java.getDeclaredMethod("load").apply { isAccessible = true }
.invoke(Glasses) as GlassesSettings
assertFalse(saved.gameOnGlasses)
assertFalse(saved.screen3dof)
assertEquals(GlassesSettings.PICTURE_AUTO, saved.picture3d)
Glasses.setGameOnGlasses(true)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.settings.value.screen3dof)
assertTrue(hardwareMessages.isEmpty())
}
@Test fun turningOffGlassesOutputDisablesVirtualScreenWithoutDeviceControl() {
selectModel(supportedModels.first())
Glasses.set3dof(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.settings.value.screen3dof)
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(connected = false, supportsScreen3dof = false)
Glasses.setGameOnGlasses(false)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.settings.value.gameOnGlasses)
assertFalse(Glasses.settings.value.screen3dof)
assertEquals(GlassesSettings.PICTURE_AUTO, Glasses.settings.value.picture3d)
assertTrue(hardwareMessages.isEmpty())
}
@Test fun enabling3dofRoutesFlatContentWithoutSendingAStereoCommandAndSurvivesReload() {
for (model in supportedModels) {
selectModel(model)
Glasses.set3dof(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(hardwareMessages.isEmpty())
assertFalse(Glasses.state.value.sbs)
assertFalse(Glasses.state.value.switching3d)
assertTrue(Glasses.settings.value.screen3dof)
assertTrue(Glasses.settings.value.gameOnGlasses)
val saved = Glasses::class.java.getDeclaredMethod("load").apply { isAccessible = true }
.invoke(Glasses) as GlassesSettings
assertTrue(saved.screen3dof)
assertTrue(saved.gameOnGlasses)
}
}
@Test fun stereoAnd3dofCanBeToggledIndependentlyOnEverySupportedModel() {
for (model in supportedModels) {
selectModel(model)
Glasses.set3dof(true)
Glasses.set3d(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.settings.value.screen3dof)
Glasses.set3d(false)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.settings.value.screen3dof)
assertEquals(listOf(model.mode(60, true) to true, model.mode(120, false) to true), commands)
commands.clear()
hardwareMessages.clear()
Glasses.set3dof(false)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(hardwareMessages.isEmpty())
assertFalse(Glasses.settings.value.screen3dof)
assertEquals(GlassesSettings.PICTURE_AUTO, Glasses.settings.value.picture3d)
assertTrue(Glasses.settings.value.gameOnGlasses)
}
}
@Test fun enabling3dofWithoutHeadTrackingSupportLeavesSettingsUnchanged() {
val before = Glasses.settings.value
Glasses.set3dof(true)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(before, Glasses.settings.value)
assertTrue(hardwareMessages.isEmpty())
}
@Test fun resolutionsPersistIndependentlyAndOnlyTheActiveProfileChangesHardware() {
selectModel(VitureProtocol.sdkModel("Luma Ultra")!!)
Glasses.setResolution(GlassesDisplayProfile.THREE_D, "1920x1080")
Glasses.setResolution(GlassesDisplayProfile.VR, "1920x1200")
shadowOf(Looper.getMainLooper()).idle()
assertTrue(hardwareMessages.isEmpty())
Glasses.setResolution(GlassesDisplayProfile.TWO_D, "1920x1080")
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x34 to false), commands)
assertEquals(120, Glasses.settings.value.refreshHz)
assertEquals(60, Glasses.settings.value.sbsHz)
val saved = Glasses::class.java.getDeclaredMethod("load").apply { isAccessible = true }
.invoke(Glasses) as GlassesSettings
assertEquals("1920x1080", saved.resolution2d)
assertEquals("1920x1080", saved.resolution3d)
assertEquals("1920x1200", saved.resolutionVr)
assertEquals(listOf(VitureProtocol.MSG_DISPLAY), hardwareMessages)
}
@Test fun vrResolutionIsAppliedAndTheOrdinaryResolutionIsRestoredAfterStopping() {
selectModel(VitureProtocol.sdkModel("Luma Ultra")!!)
Glasses.setResolution(GlassesDisplayProfile.TWO_D, "1920x1080")
Glasses.setResolution(GlassesDisplayProfile.VR, "1920x1200")
shadowOf(Looper.getMainLooper()).idle()
commands.clear()
Glasses.setVrActive(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.state.value.vrActive)
assertEquals(listOf(0x44 to false), commands)
Glasses.setVrActive(false)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.state.value.vrActive)
assertEquals(listOf(0x44 to false, 0x34 to false), commands)
}
@Test fun vrResolutionUsesStereoCommandsAndRestoresThePreVrLayoutOnce() {
selectModel(VitureProtocol.sdkModel("Luma Ultra")!!)
Glasses.setGameOnGlasses(true)
Glasses.setAuto3d(true)
Glasses.setResolution(GlassesDisplayProfile.VR, "1920x1080")
shadowOf(Looper.getMainLooper()).idle()
Glasses.setVrActive(true)
Glasses.set3dForVr(true)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x32 to true), commands)
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(sbs = true, width = 3840, switching3d = false)
(field("modeState").get(null) as GlassesModeState).observe(true, 0)
Glasses.setSbsHz(90)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(0x35 to true, commands.last())
Glasses.setVrActive(false)
Glasses.set3dForVr(false)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x32 to true, 0x35 to true, 0x44 to true), commands)
}
@Test fun invalidResolutionCannotChangePreferencesOrSendDeviceCommands() {
selectModel(VitureProtocol.sdkModel("Pro")!!)
val before = Glasses.settings.value
for (value in listOf("1920x1200", "3840x1080", "-1x1080", "unknown"))
Glasses.setResolution(GlassesDisplayProfile.TWO_D, value)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(before, Glasses.settings.value)
assertTrue(hardwareMessages.isEmpty())
}
@Test fun startingVrDuringAStereoSwitchDoesNotSendAFlatMode() {
selectModel(VitureProtocol.sdkModel("Luma Ultra")!!)
Glasses.setResolution(GlassesDisplayProfile.VR, "1920x1080")
Glasses.set3d(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.state.value.switching3d)
Glasses.setVrActive(true)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x42 to true, 0x32 to true), commands)
}
@Test fun reconnectRestoresASavedResolutionEvenWhenRefreshAlreadyMatches() {
selectModel(VitureProtocol.sdkModel("Luma Ultra")!!)
Glasses.setResolution(GlassesDisplayProfile.TWO_D, "1920x1080")
shadowOf(Looper.getMainLooper()).idle()
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(width = 1920, height = 1200, hz = 120f)
field("glassesMode").setInt(null, 0)
field("autoModeSent").setBoolean(null, false)
field("lastModeSentAt").setLong(null, -10_000L)
commands.clear()
Glasses::class.java.getDeclaredMethod("applyMode", Boolean::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, false)
assertEquals(listOf(0x34 to false), commands)
}
@Test fun defaultVrProfileDoesNotSendExtraDisplayCommands() {
selectModel(VitureProtocol.sdkModel("Luma Ultra")!!)
Glasses.setVrActive(true)
Glasses.setVrActive(false)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(hardwareMessages.isEmpty())
}
private fun selectModel(model: GlassesModel) {
field("model").set(null, model)
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(model = model.name, supportsScreen3dof = true, resolutions = model.resolutions)
@Suppress("UNCHECKED_CAST")
val settings = field("_settings").get(null) as MutableStateFlow<GlassesSettings>
settings.value = GlassesSettings(gameOnGlasses = false, headTracking = false)
assertFalse(settings.value.screen3dof)
}
}
@@ -0,0 +1,235 @@
package com.droiddeck.launcher.glasses
import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesCallbacksTest {
private fun field(name: String) = Glasses::class.java.getDeclaredField(name).apply { isAccessible = true }
private fun generation(value: Long) = field("linkGeneration").setLong(null, value)
private fun listener(generation: Long): VitureLink.Listener =
Glasses::class.java.getDeclaredMethod("linkListener", Long::class.javaPrimitiveType).apply { isAccessible = true }
.invoke(Glasses, generation) as VitureLink.Listener
@Before fun prepare() {
field("handler").set(null, Handler(Looper.getMainLooper()))
generation(1)
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = GlassesState(connected = true, brightness = 2, displayId = 2, width = 640, height = 480, noSignal = true)
field("imuPackets").setLong(null, 0)
field("probe").set(null, null)
}
private fun brightness(value: Int) = VitureProtocol.Frame(
VitureProtocol.MAGIC_REPORT, VitureProtocol.EVENT_BRIGHTNESS, byteArrayOf(value.toByte()), true,
)
@Test fun statusIncludesCalibrationAndTransportChecksumDiagnostics() {
val previousLink = field("link").get(null)
@Suppress("UNCHECKED_CAST")
val calibration = field("_calibration").get(null) as MutableStateFlow<GlassesCalibrationState>
val previousCalibration = calibration.value
try {
field("link").set(null, object : GlassesLink {
override val hasImu = true
override val badFrames = 7L
override fun send(msgId: Int, payload: ByteArray) = false
override fun close() {}
})
calibration.value = GlassesCalibrationState(supported = true, saved = true,
phase = CalibrationPhase.SAVED, progress = 100)
val status = Glasses.status()
assertEquals(7L, status.getLong("badFrames"))
val reportedCalibration = status.getJSONObject("calibration")
assertTrue(reportedCalibration.getBoolean("supported"))
assertTrue(reportedCalibration.getBoolean("saved"))
assertEquals("SAVED", reportedCalibration.getString("phase"))
assertEquals(100, reportedCalibration.getInt("progress"))
field("link").set(null, null)
assertEquals(0L, Glasses.status().getLong("badFrames"))
} finally {
field("link").set(null, previousLink)
calibration.value = previousCalibration
}
}
@Test fun queuedDisconnectCannotCloseAReplacementLink() {
val old = listener(1)
old.onLost()
old.onLost()
generation(2)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.state.value.connected)
}
@Test fun queuedReportCannotOverwriteReplacementState() {
listener(1).onFrame(brightness(7))
generation(2)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(2, Glasses.state.value.brightness)
listener(2).onFrame(brightness(4))
listener(1).onFrame(brightness(8))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(4, Glasses.state.value.brightness)
}
@Test fun oldImuPacketsCannotReachTheNewProbe() {
var samples = 0
val probe: (ByteArray?, FloatArray?) -> Unit = { _, _ -> samples++ }
field("probe").set(null, probe)
generation(2)
listener(1).onImu(ByteArray(12), 0)
assertEquals(0, samples)
assertEquals(0L, field("imuPackets").getLong(null))
listener(2).onImu(ByteArray(12), 0)
assertEquals(1, samples)
assertEquals(1L, field("imuPackets").getLong(null))
}
@Test fun rayNeoPoseUsesTheExistingSinkAndRejectsAnOldConnection() {
fun rayneo(gen: Long) = Glasses::class.java.getDeclaredMethod("rayNeoListener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, gen) as RayNeoLink.Listener
var delivered: FloatArray? = null
var timestamp = 0L
val sink = Glasses.PoseSink { x, y, z, w, time ->
delivered = floatArrayOf(x, y, z, w)
timestamp = time
}
field("sink").set(null, sink)
try {
val q = floatArrayOf(0f, 0f, 0.6f, 0.8f)
rayneo(0).onPose(ByteArray(64), q, 99)
assertEquals(null, delivered)
rayneo(1).onPose(ByteArray(64), q, 123)
org.junit.Assert.assertArrayEquals(q, delivered, 0f)
assertEquals(123L, timestamp)
assertEquals(1L, field("imuPackets").getLong(null))
rayneo(0).onLost()
generation(2)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.state.value.connected)
} finally {
field("sink").set(null, null)
}
}
@Test fun deviceModeReportsCannotConfirmThePhysicalStereoSignal() {
listener(1).onFrame(VitureProtocol.Frame(
VitureProtocol.MAGIC_REPORT, VitureProtocol.EVENT_DISPLAY, byteArrayOf(0x32), true,
))
listener(1).onFrame(VitureProtocol.Frame(
VitureProtocol.MAGIC_REPORT, VitureProtocol.MSG_GET_DISPLAY, byteArrayOf(0, 0x32), true,
))
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.state.value.sbs)
assertTrue(Glasses.state.value.noSignal)
assertEquals(640, Glasses.state.value.width)
}
@Test fun xrealCallbacksUseSharedPoseAndIgnoreDetachedDeviceValues() {
fun xreal(gen: Long) = Glasses::class.java.getDeclaredMethod("xrealListener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, gen) as XrealLink.Listener
var delivered: FloatArray? = null
field("sink").set(null, Glasses.PoseSink { x, y, z, w, _ -> delivered = floatArrayOf(x, y, z, w) })
try {
val q = floatArrayOf(0f, 0f, 0.6f, 0.8f)
xreal(0).onPose(ByteArray(128), q, 1)
assertEquals(null, delivered)
xreal(1).onPose(ByteArray(128), q, 2)
org.junit.Assert.assertArrayEquals(q, delivered, 0f)
xreal(1).onValue(VitureProtocol.MSG_BRIGHTNESS, 8)
xreal(1).onUnavailable(true)
generation(2)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(2, Glasses.state.value.brightness)
assertTrue(Glasses.state.value.connected)
} finally { field("sink").set(null, null) }
}
@Test fun cancelledCalibrationCallbacksCannotResurrectOrOverwriteTheProfile() {
val rayneo = Glasses::class.java.getDeclaredMethod("rayNeoListener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, 1L) as RayNeoLink.Listener
@Suppress("UNCHECKED_CAST")
val calibration = field("_calibration").get(null) as MutableStateFlow<GlassesCalibrationState>
calibration.value = GlassesCalibrationState(supported = true, saved = true, phase = CalibrationPhase.SETTLING)
field("calibrationRevision").setLong(null, 1)
rayneo.onCalibrationSaved(1, RayNeoCalibration(Vec3(0f, 0f, 0f), Quaternion.IDENTITY))
rayneo.onCalibration(1, CalibrationPhase.SAVED, 100)
field("calibrationRevision").setLong(null, 2)
calibration.value = calibration.value.copy(phase = CalibrationPhase.IDLE)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(CalibrationPhase.IDLE, calibration.value.phase)
assertTrue(calibration.value.saved)
}
@Test fun disconnectedRayNeoBoardCannotChangeTheCurrentCalibrationKey() {
val rayneo = Glasses::class.java.getDeclaredMethod("rayNeoListener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, 1L) as RayNeoLink.Listener
val previous = field("calibrationKey").get(null)
try {
field("calibrationKey").set(null, "current-profile")
rayneo.onDeviceInfo(0x40, true)
generation(2)
shadowOf(Looper.getMainLooper()).idle()
assertEquals("current-profile", field("calibrationKey").get(null))
} finally { field("calibrationKey").set(null, previous) }
}
@Test fun sdkCallbacksCannotCrossConnectionGenerationsOrFakeStereoConfirmation() {
fun sdk(gen: Long) = Glasses::class.java.getDeclaredMethod("sdkListener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, gen) as VitureSdkLink.Listener
var samples = 0
val probe: (ByteArray?, FloatArray?) -> Unit = { raw, pose ->
assertEquals(null, raw)
assertEquals(4, pose!!.size)
samples++
}
field("probe").set(null, probe)
try {
sdk(0).onPose(floatArrayOf(0f, 0f, 0f, 1f), 100)
sdk(1).onPose(floatArrayOf(0f, 0f, 0f, 1f), 101)
assertEquals(1, samples)
sdk(0).onValue(VitureProtocol.MSG_GET_BRIGHTNESS, 8)
sdk(1).onValue(VitureProtocol.MSG_GET_DISPLAY, 0x42)
sdk(0).onLost()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(2, Glasses.state.value.brightness)
assertFalse(Glasses.state.value.sbs)
assertTrue(Glasses.state.value.connected)
} finally { field("probe").set(null, null) }
}
@Test fun rejectedTrackingStartDoesNotAdvertiseTracking() {
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(tracking = false)
val rejected = object : GlassesLink {
override val hasImu = true
override fun send(msgId: Int, payload: ByteArray) = false
override fun close() {}
}
field("link").set(null, rejected)
field("sink").set(null, Glasses.PoseSink { _, _, _, _, _ -> })
try {
Glasses::class.java.getDeclaredMethod("updateImu").apply { isAccessible = true }.invoke(Glasses)
assertFalse(Glasses.state.value.tracking)
} finally {
field("link").set(null, null)
field("sink").set(null, null)
}
}
}
@@ -0,0 +1,62 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class GlassesDisplayModesTest {
private val fullHd = GlassesResolution(1920, 1080)
private val tall = GlassesResolution(1920, 1200)
private val ultra = VitureProtocol.sdkModel("Luma Ultra")!!
private val state = GlassesState(resolutions = ultra.resolutions)
@Test fun separateProfilesRetainTheirOwnResolutions() {
val settings = GlassesSettings(resolution2d = fullHd.key, resolution3d = tall.key, resolutionVr = fullHd.key)
assertEquals(fullHd, GlassesDisplayModes.selected(settings, state))
assertEquals(tall, GlassesDisplayModes.selected(settings, state.copy(sbs = true)))
for (stereo in listOf(false, true))
assertEquals(fullHd, GlassesDisplayModes.selected(settings, state.copy(sbs = stereo, vrActive = true)))
}
@Test fun automaticVrInheritsTheActiveLayoutAndDefaultsKeepNativeBehavior() {
val settings = GlassesSettings(resolution2d = fullHd.key, resolution3d = tall.key)
assertEquals(fullHd, GlassesDisplayModes.selected(settings, state.copy(vrActive = true)))
assertEquals(tall, GlassesDisplayModes.selected(settings, state.copy(sbs = true, vrActive = true)))
assertNull(GlassesDisplayModes.selected(GlassesSettings(), state))
assertNull(GlassesDisplayModes.selected(GlassesSettings(), state.copy(sbs = true, vrActive = true)))
}
@Test fun anotherHeadsetDoesNotReceiveAnUnsupportedSavedResolution() {
val settings = GlassesSettings(resolution2d = tall.key, resolutionVr = tall.key)
assertNull(GlassesDisplayModes.selected(settings, state.copy(resolutions = listOf(fullHd))))
assertNull(GlassesDisplayModes.selected(settings, state.copy(resolutions = emptyList(), vrActive = true)))
assertEquals(tall, GlassesDisplayModes.selected(settings, state))
}
@Test fun ultraResolutionsMapToVendorCommandsAtEverySupportedRefresh() {
for ((hz, code) in listOf(60 to 0x31, 90 to 0x33, 120 to 0x34)) {
assertEquals(code, ultra.mode(hz, false, fullHd))
assertEquals(code + 0x10, ultra.mode(hz, false, tall))
}
for ((hz, code) in listOf(60 to 0x32, 90 to 0x35)) {
assertEquals(code, ultra.mode(hz, true, fullHd))
assertEquals(code + 0x10, ultra.mode(hz, true, tall))
}
assertEquals(0x41, ultra.mode(30, false, tall))
assertEquals(0x42, ultra.mode(30, true, tall))
}
@Test fun olderModelsKeepTheirNativeResolutionAndStereoRateLimits() {
for (name in listOf("One", "Pro", "Pro 2")) {
val model = VitureProtocol.sdkModel(name)!!
assertEquals(listOf(fullHd), model.resolutions)
assertEquals(0x34, model.mode(120, false, tall))
assertEquals(0x32, model.mode(90, true, tall))
}
for (name in listOf("Luma", "Luma Pro", "Luma Ultra", "Beast")) {
val model = VitureProtocol.sdkModel(name)!!
assertEquals(listOf(fullHd, tall), model.resolutions)
assertEquals(0x44, model.mode(120, false))
assertEquals(if (model.sbs90) 0x45 else 0x42, model.mode(90, true))
}
}
}
@@ -0,0 +1,137 @@
package com.droiddeck.launcher.glasses
import android.hardware.display.DeviceProductInfo
import android.hardware.display.DisplayManager
import android.view.Display
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.annotation.LooperMode
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowDisplay
import org.robolectric.shadows.ShadowDisplayManager
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], manifest = Config.NONE, shadows = [GlassesDisplayTest.ProductMetadataDisplay::class])
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesDisplayTest {
@Test fun connectedGlassesUseTheOnlyExternalPanelWhenProductMetadataIsMissing() {
val panel = display("External Display")
assertNull(panel.deviceProductInfo)
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = true)?.displayId)
}
@Test fun missingProductMetadataDoesNotIdentifyGlassesWithoutUsb() {
val panel = display("External Display")
assertNull(Glasses.selectGlassesDisplay(listOf(panel), usbPresent = false))
}
@Test fun connectedGlassesDoNotChooseBetweenMultipleUnidentifiedPanels() {
val first = display("External Display 1")
val second = display("External Display 2")
assertNull(Glasses.selectGlassesDisplay(listOf(first, second), usbPresent = true))
}
@Test fun primaryAndNonPresentationDisplaysCannotBecomeTheGlassesOutput() {
val primary = displayManager().getDisplay(Display.DEFAULT_DISPLAY)
shadowOf(primary).setName("RayNeo Air 4 Pro")
shadowOf(primary).setFlags(Display.FLAG_PRESENTATION)
val nonPresentation = display("RayNeo Air 4 Pro", flags = 0)
assertNull(Glasses.selectGlassesDisplay(listOf(primary, nonPresentation), usbPresent = true))
}
@Test fun rayNeoDisplayNameIsRecognizedEvenWhenProductMetadataHasAGenericName() {
val panel = display("RayNeo Air 4 Pro", productName = "External Monitor")
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = false)?.displayId)
}
@Test fun rayNeoProductMetadataIsRecognizedWhenAndroidUsesAGenericDisplayName() {
val panel = display("External Display", productName = "RayNeo Air 3")
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = false)?.displayId)
}
@Test fun anUnrelatedNamedMonitorIsNotClaimedByConnectedGlasses() {
val monitor = display("External Display", productName = "TCL TV")
assertNull(Glasses.selectGlassesDisplay(listOf(monitor), usbPresent = true))
}
@Test fun namedRayNeoDisplayWorksWithoutUsbControlPermission() {
val panel = display("RayNeo GT")
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = false)?.displayId)
}
@Test fun blankProductNameRetainsTheSinglePanelUsbFallback() {
val panel = display("External Display", productName = " ")
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = true)?.displayId)
}
@Test fun brandedGlassesWinOverAnUnidentifiedSecondDisplay() {
val monitor = display("External Display")
val glasses = display("RayNeo Air 2s")
assertEquals(glasses.displayId, Glasses.selectGlassesDisplay(listOf(monitor, glasses), usbPresent = true)?.displayId)
}
@Test fun gtMaxSmartGlassesEdidUsesTheSameOutputSelectionAsViture() {
val panel = display("SmartGlasses", productName = "SmartGlasses", productId = "980")
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = true)?.displayId)
// The display remains usable while USB control reconnects during a mode switch.
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = false)?.displayId)
}
@Test fun gtMaxMetadataIsRecognizedBehindGenericAndroidNameAndOtherPanels() {
val monitor = display("External Display", productName = "TCL TV")
val panel = display("External Display", productName = "SmartGlasses", productId = "980")
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(monitor, panel), usbPresent = true)?.displayId)
}
@Test fun genericSmartGlassesNameDoesNotClaimUnverifiedProducts() {
val unknown = display("SmartGlasses", productName = "SmartGlasses")
assertNull(Glasses.selectGlassesDisplay(listOf(unknown), usbPresent = true))
assertFalse(RayNeoModel.isDisplayProduct("SmartGlasses", "OTHER", "980"))
assertFalse(RayNeoModel.isDisplayProduct("TCL TV", "TCL", "980"))
}
private fun displayManager(): DisplayManager =
RuntimeEnvironment.getApplication().getSystemService(DisplayManager::class.java)
private fun display(name: String, productName: String? = null, flags: Int = Display.FLAG_PRESENTATION,
productId: String = "test-panel"): Display {
val external = ReflectionHelpers.getStaticField<Int>(Display::class.java, "TYPE_EXTERNAL")
val id = ShadowDisplayManager.addDisplay("w1920dp-h1080dp", external)
return displayManager().getDisplay(id).also { panel ->
shadowOf(panel).setName(name)
shadowOf(panel).setFlags(flags)
Shadow.extract<ProductMetadataDisplay>(panel).productMetadata = productName?.let {
DeviceProductInfo(it, "TCL", productId, 2024, DeviceProductInfo.CONNECTION_TO_SINK_DIRECT)
}
}
}
// Robolectric exposes display names and flags, but has no product-metadata setter.
@Implements(Display::class)
class ProductMetadataDisplay : ShadowDisplay() {
var productMetadata: DeviceProductInfo? = null
@Implementation(minSdk = 31)
protected fun getDeviceProductInfo(): DeviceProductInfo? = productMetadata
}
}
@@ -0,0 +1,15 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class GlassesFovTest {
@Test fun native1sAspectUsesThePerEyeResolution() {
val native = GlassesState(width = 1920, height = 1200, diagonalFovDeg = 52f)
val stereo = native.copy(width = 3840, sbs = true)
val widescreen = native.copy(height = 1080)
assertEquals(native.verticalFovDeg, stereo.verticalFovDeg, 0.001f)
assertTrue(native.verticalFovDeg > widescreen.verticalFovDeg)
assertEquals(widescreen.verticalFovDeg, native.copy(width = 0, height = 0).verticalFovDeg, 0.001f)
}
}
@@ -0,0 +1,149 @@
package com.droiddeck.launcher.glasses
import android.app.Activity
import android.app.Application
import android.app.Dialog
import android.app.Presentation
import android.graphics.SurfaceTexture
import android.hardware.display.DisplayManager
import android.view.Choreographer
import android.view.Surface
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.android.controller.ActivityController
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowDisplayManager
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [29], manifest = Config.NONE, application = Application::class)
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesMenuCaptureTest {
private lateinit var controller: ActivityController<Activity>
private lateinit var activity: Activity
private val dialogs = mutableListOf<Dialog>()
@Before fun setUp() {
controller = Robolectric.buildActivity(Activity::class.java).setup().visible()
activity = controller.get()
activity.window.decorView.layout(0, 0, 1920, 1080)
}
@After fun tearDown() {
dialogs.forEach { it.dismiss() }
controller.pause().stop().destroy()
}
@Test fun onlyTheActivityAndItsOwnDialogAreIncludedOnce() {
val own = dialog(activity)
val otherController = Robolectric.buildActivity(Activity::class.java).setup().visible()
val other = otherController.get()
val otherDialog = dialog(other)
try {
val decor = activity.window.decorView
val roots = GlassesMenuCapture.captureRoots(activity,
listOf(other.window.decorView, own, otherDialog, decor, own))
assertEquals(listOf(decor, own), roots)
} finally {
dialogs.removeAll { if (it.ownerActivity === other) { it.dismiss(); true } else false }
otherController.pause().stop().destroy()
}
}
@Test fun secureActivityProducesNoRootsAndSecureDialogsAreExcluded() {
val secure = dialog(activity)
val params = secure.layoutParams as WindowManager.LayoutParams
params.flags = params.flags or WindowManager.LayoutParams.FLAG_SECURE
assertEquals(listOf(activity.window.decorView), GlassesMenuCapture.captureRoots(activity, listOf(secure)))
activity.window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
assertTrue(GlassesMenuCapture.captureRoots(activity, listOf(secure)).isEmpty())
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
assertEquals(listOf(activity.window.decorView), GlassesMenuCapture.captureRoots(activity, listOf(secure)))
}
@Test fun systemWindowsAndPresentationsOnOtherDisplaysAreExcluded() {
val own = dialog(activity)
(own.layoutParams as WindowManager.LayoutParams).type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
val displayId = ShadowDisplayManager.addDisplay("w1920dp-h1080dp")
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(displayId)
val presentation = Presentation(activity, display).apply {
setContentView(FrameLayout(context))
show()
}.also(dialogs::add)
try {
assertEquals(listOf(activity.window.decorView), GlassesMenuCapture.captureRoots(activity,
listOf(own, presentation.window!!.decorView)))
} finally {
presentation.dismiss()
dialogs.remove(presentation)
ShadowDisplayManager.removeDisplay(displayId)
}
}
@Test
@Config(sdk = [26])
fun olderAndroidCapturesOnlyTheActivityDecor() {
val own = dialog(activity)
assertEquals(listOf(activity.window.decorView), GlassesMenuCapture.captureRoots(activity, listOf(own)))
}
@Test fun captureSizesPreserveOrientationAndNeverUpscale() {
assertEquals(1920 to 1080, GlassesMenuCapture.captureSize(3840, 2160))
assertEquals(1080 to 1920, GlassesMenuCapture.captureSize(2160, 3840))
assertEquals(1200 to 1800, GlassesMenuCapture.captureSize(1200, 1800))
val fold = GlassesMenuCapture.captureSize(2152, 1812)!!
assertEquals(1920, fold.first)
assertEquals(2152.0 / 1812.0, fold.first.toDouble() / fold.second, 0.001)
assertNull(GlassesMenuCapture.captureSize(0, 1000))
assertNull(GlassesMenuCapture.captureSize(1000, -1))
}
@Test fun repeatedSurfaceFailureStopsOnceAndDoesNotRetryAfterStop() {
var sizes = 0
var failures = 0
val capture = GlassesMenuCapture(activity, { _, _ -> sizes++ }, { failures++ })
val input = SurfaceTexture(0)
val target = Surface(input)
target.release()
try {
capture.attach(input, target)
capture.start()
for (time in listOf(1L, 33_333_335L, 66_666_669L, 100_000_003L)) {
Choreographer.getInstance().removeFrameCallback(capture)
capture.doFrame(time)
}
assertEquals(1, failures)
assertEquals(0, sizes)
assertFalse(pending(capture))
} finally {
capture.stop()
input.release()
}
}
@Test fun stoppingRejectsAnAlreadyDispatchedFrameWithoutRescheduling() {
val capture = GlassesMenuCapture(activity, { _, _ -> fail("Stopped capture changed its size") })
capture.start()
capture.stop()
capture.doFrame(1L)
assertFalse(pending(capture))
}
private fun dialog(owner: Activity): View = Dialog(owner).apply {
setOwnerActivity(owner)
setContentView(FrameLayout(context))
show()
}.also(dialogs::add).window!!.decorView
private fun pending(capture: GlassesMenuCapture): Boolean =
GlassesMenuCapture::class.java.getDeclaredField("framePending").apply { isAccessible = true }.getBoolean(capture)
}
@@ -0,0 +1,340 @@
package com.droiddeck.launcher.glasses
import android.app.Activity
import android.app.Application
import android.hardware.display.DisplayManager
import android.view.Display
import android.view.WindowManager
import com.droiddeck.launcher.QuestXrActivity
import com.droiddeck.launcher.SessionActivity
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.android.controller.ActivityController
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowDisplayManager
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class, manifest = Config.NONE)
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesMenuControllerTest {
private lateinit var owner: Activity
private lateinit var ownerLifecycle: ActivityController<Activity>
private lateinit var external: Display
private lateinit var menus: GlassesMenuController
private val displays = mutableListOf<Int>()
private val outputs = mutableListOf<FakeOutput>()
private val subscriptions = mutableListOf<Boolean>()
private val scheduled = ArrayDeque<() -> Unit>()
private var target: Display? = null
private var creationError: RuntimeException? = null
private var onCreateOutput: (FakeOutput) -> Unit = {}
private val saved = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN,
headTracking = true, screenWidthDm = 35, screenDistanceDm = 45)
private lateinit var glasses: GlassesState
@Before fun setUp() {
ownerLifecycle = Robolectric.buildActivity(Activity::class.java).setup()
owner = ownerLifecycle.get()
external = addDisplay()
target = external
glasses = GlassesState(present = true, connected = true, controllable = true,
supportsScreen3dof = true, displayId = external.displayId, width = 1920, height = 1080)
menus = GlassesMenuController(GlassesMenuPose(spatialEnabled = { false }),
display = { target }, observe = { subscriptions += it },
create = { activity, display, failure ->
creationError?.let { throw it }
FakeOutput(activity, display, failure).also {
outputs += it
onCreateOutput(it)
}
}, schedule = { scheduled.addLast(it) })
menus.update(glasses, saved)
}
@After fun tearDown() {
menus.pause(owner)
ownerLifecycle.pause().stop().destroy()
displays.forEach(ShadowDisplayManager::removeDisplay)
}
@Test fun menusStartOnlyForSupportedControlledExternalOutputWithTrackingSelected() {
val invalid = listOf(
glasses.copy(connected = false) to saved,
glasses.copy(controllable = false) to saved,
glasses.copy(supportsScreen3dof = false) to saved,
glasses.copy(noSignal = true) to saved,
glasses.copy(displayId = Display.INVALID_DISPLAY) to saved,
glasses to saved.copy(gameOnGlasses = false),
glasses to saved.copy(headTracking = false),
glasses to saved.copy(picture3d = GlassesSettings.PICTURE_AUTO),
)
for ((state, preferences) in invalid) {
menus.update(state, preferences)
menus.resume(owner)
assertTrue(outputs.isEmpty())
assertTrue(subscriptions.isEmpty())
}
menus.update(glasses, saved)
assertEquals(1, outputs.size)
assertEquals(listOf(true), subscriptions)
assertEquals(1, outputs.single().shows)
assertEquals(saved, outputs.single().settings)
}
@Test fun absentDisplayAndThePhoneDisplayNeverCreateAnOutput() {
target = null
menus.resume(owner)
target = owner.windowManager.defaultDisplay
menus.update(glasses, saved)
assertTrue(outputs.isEmpty())
assertTrue(subscriptions.isEmpty())
target = external
menus.update(glasses, saved)
assertEquals(1, outputs.size)
}
@Test fun sessionContentIsExcludedUntilItsMenuIsVisibleAndStalePauseCannotCloseNewOwner() {
menus.resume(owner)
val first = outputs.single()
val session = Robolectric.buildActivity(SessionActivity::class.java).get()
menus.resume(session)
assertEquals(1, first.closes)
assertEquals(1, outputs.size)
menus.setSessionMenuVisible(session, true)
val overlay = outputs.last()
assertSame(session, overlay.owner)
assertEquals(2, outputs.size)
menus.setSessionMenuVisible(session, false)
assertEquals(1, overlay.closes)
menus.resume(owner)
val latest = outputs.last()
menus.pause(session)
menus.setSessionMenuVisible(session, true)
assertEquals(0, latest.closes)
assertEquals(3, outputs.size)
}
@Test fun pauseReleasesSubscriptionAndLateFailureCannotCloseAReplacement() {
menus.resume(owner)
val old = outputs.single()
menus.pause(owner)
menus.pause(owner)
assertEquals(1, old.closes)
assertEquals(listOf(true, false), subscriptions)
menus.resume(owner)
val current = outputs.last()
old.fail(IllegalStateException("late GL callback"))
assertEquals(0, current.closes)
assertEquals(2, outputs.size)
menus.pause(owner)
assertEquals(1, current.closes)
assertFalse(subscriptions.last())
}
@Test fun destroyedActivityCannotRecreateItsOutputAfterCleanup() {
val lifecycle = Robolectric.buildActivity(Activity::class.java).setup()
val destroyed = lifecycle.get()
menus.resume(destroyed)
val output = outputs.single()
lifecycle.pause().stop().destroy()
menus.pause(destroyed)
menus.resume(destroyed)
assertEquals(1, output.closes)
assertEquals(1, outputs.size)
assertFalse(subscriptions.last())
menus.pause(destroyed)
}
@Test fun secureFinishingAndImmersiveQuestActivitiesCannotBeCaptured() {
owner.window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
menus.resume(owner)
assertTrue(outputs.isEmpty())
owner.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
val quest = Robolectric.buildActivity(QuestXrActivity::class.java).get()
menus.resume(quest)
assertTrue(outputs.isEmpty())
owner.finish()
menus.resume(owner)
assertTrue(outputs.isEmpty())
}
@Test fun settingsReconfigureTheSameOutputAndDisablingTrackingClosesIt() {
menus.resume(owner)
val output = outputs.single()
val changed = saved.copy(screenWidthDm = 50, screenDistanceDm = 60, positionalTracking = true)
menus.update(glasses.copy(sbs = true), changed)
assertEquals(1, outputs.size)
assertEquals(2, output.configurations)
assertEquals(changed, output.settings)
assertTrue(output.state!!.sbs)
assertEquals(listOf(true), subscriptions)
menus.update(glasses, changed.copy(headTracking = false))
assertEquals(1, output.closes)
assertFalse(subscriptions.last())
menus.update(glasses, changed)
assertEquals(2, outputs.size)
assertTrue(subscriptions.last())
}
@Test fun displayRemovalAndReplacementCloseOldOutputAndRebindOnlyTheCurrentDisplay() {
menus.resume(owner)
val old = outputs.single()
target = null
menus.update(glasses.copy(displayId = Display.INVALID_DISPLAY), saved)
assertEquals(1, old.closes)
assertFalse(subscriptions.last())
target = addDisplay()
menus.update(glasses.copy(displayId = target!!.displayId), saved)
assertEquals(2, outputs.size)
assertSame(target, outputs.last().display)
old.fail(IllegalStateException("removed display"))
assertEquals(0, outputs.last().closes)
}
@Test fun creationFailureIsLatchedUntilPreferencesChangeWithoutSubscribing() {
creationError = IllegalStateException("no EGL display")
menus.resume(owner)
assertTrue(outputs.isEmpty())
assertTrue(subscriptions.isEmpty())
creationError = null
menus.update(glasses, saved)
assertTrue(outputs.isEmpty())
menus.update(glasses, saved.copy(screenWidthDm = 40))
assertEquals(1, outputs.size)
assertTrue(subscriptions.last())
}
@Test fun configureAndShowExceptionsReleaseOutputAndDoNotEscapeUpdates() {
onCreateOutput = { it.showError = IllegalStateException("window removed") }
menus.resume(owner)
assertEquals(1, outputs.single().closes)
assertEquals(listOf(true, false), subscriptions)
onCreateOutput = {}
menus.update(glasses, saved.copy(screenWidthDm = 40))
val next = outputs.last()
next.onConfigure = { throw IllegalStateException("surface lost") }
menus.update(glasses, saved)
assertEquals(1, next.closes)
assertFalse(subscriptions.last())
menus.update(glasses, saved)
assertEquals(2, outputs.size)
}
@Test fun synchronousFactoryOrConfigureFailureCannotShowOrSubscribeAClosedOutput() {
onCreateOutput = { it.fail(IllegalStateException("creation callback")) }
menus.resume(owner)
assertEquals(0, outputs.single().shows)
assertEquals(1, outputs.single().closes)
assertFalse(subscriptions.contains(true))
onCreateOutput = { output -> output.onConfigure = { output.fail(IllegalStateException("configure callback")) } }
menus.update(glasses, saved.copy(screenWidthDm = 40))
assertEquals(2, outputs.size)
assertEquals(0, outputs.last().shows)
assertEquals(1, outputs.last().closes)
assertFalse(subscriptions.contains(true))
}
@Test fun closeFailureStillReleasesObserverAndDoesNotBlockTheNextResume() {
menus.resume(owner)
outputs.single().closeError = IllegalStateException("already destroyed surface")
menus.pause(owner)
assertFalse(subscriptions.last())
menus.resume(owner)
assertEquals(2, outputs.size)
assertEquals(1, outputs.last().shows)
}
@Test fun unexpectedDismissalGetsOneScheduledRetryAndStopsAfterASecondFailure() {
menus.resume(owner)
val old = outputs.single()
old.fail(GlassesMenuDisplayStopped())
assertEquals(1, old.closes)
assertFalse(subscriptions.last())
assertEquals(1, scheduled.size)
assertEquals(1, outputs.size)
scheduled.removeFirst().invoke()
assertEquals(2, outputs.size)
assertTrue(subscriptions.last())
outputs.last().fail(GlassesMenuDisplayStopped())
assertTrue(scheduled.isEmpty())
assertFalse(subscriptions.last())
menus.update(glasses, saved)
assertEquals(2, outputs.size)
menus.update(glasses, saved.copy(screenWidthDm = 40))
assertEquals(3, outputs.size)
outputs.last().fail(GlassesMenuDisplayStopped())
assertEquals(1, scheduled.size)
}
@Test fun scheduledDismissalRecoveryCannotReopenAfterPauseOrReplaceANewerOutput() {
menus.resume(owner)
outputs.single().fail(GlassesMenuDisplayStopped())
menus.pause(owner)
scheduled.removeFirst().invoke()
assertEquals(1, outputs.size)
assertFalse(subscriptions.last())
menus.resume(owner)
outputs.last().fail(GlassesMenuDisplayStopped())
menus.pause(owner)
menus.resume(owner)
val replacement = outputs.last()
scheduled.removeFirst().invoke()
assertEquals(3, outputs.size)
assertEquals(0, replacement.closes)
assertTrue(subscriptions.last())
}
@Test fun displayResizeAllowsRetryAfterARealRendererFailureWithoutRetryingEveryStateUpdate() {
menus.resume(owner)
outputs.single().fail(IllegalStateException("old surface size"))
assertTrue(scheduled.isEmpty())
menus.update(glasses.copy(tracking = true), saved)
assertEquals(1, outputs.size)
menus.update(glasses.copy(width = 3840, sbs = true), saved)
assertEquals(2, outputs.size)
assertEquals(3840, outputs.last().state!!.width)
assertTrue(subscriptions.last())
}
private fun addDisplay(): Display {
val id = ShadowDisplayManager.addDisplay("w1920dp-h1080dp")
displays += id
return RuntimeEnvironment.getApplication().getSystemService(DisplayManager::class.java).getDisplay(id)
}
private class FakeOutput(val owner: Activity, val display: Display, val fail: (Throwable) -> Unit) : GlassesMenuController.Output {
var configurations = 0
var shows = 0
var closes = 0
var state: GlassesState? = null
var settings: GlassesSettings? = null
var onConfigure: () -> Unit = {}
var showError: RuntimeException? = null
var closeError: RuntimeException? = null
override fun configure(state: GlassesState, settings: GlassesSettings) {
configurations++
this.state = state
this.settings = settings
onConfigure()
}
override fun show() { shows++; showError?.let { throw it } }
override fun close() { closes++; closeError?.let { throw it } }
}
}
@@ -0,0 +1,142 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class GlassesMenuPoseTest {
private val time = 1_000_000_000L
@Test fun firstFreshGlassesPoseCentersTheScreenInAllThreeAxes() {
val pose = GlassesMenuPose(spatialEnabled = { false })
pose.onPose(0.2f, -0.3f, 0.1f, 0.9f, time)
val frame = pose.snapshot(time)
assertTrue(frame.valid)
assertArrayEquals(HeadPose.IDENTITY, frame.rotation, 1e-5f)
assertArrayEquals(FloatArray(3), frame.position, 0f)
}
@Test fun pageConfigurationPreservesTheThreeDofAnchorUntilExplicitRecenter() {
val pose = GlassesMenuPose(spatialEnabled = { false })
pose.onPose(0f, 0f, 0f, 1f, time)
pose.snapshot(time)
pose.onPose(0f, 0f, 0.1f, 0.995f, time+1)
val moved = pose.snapshot(time+1)
pose.configure(GlassesSettings(screenWidthDm = 40))
assertArrayEquals(moved.rotation, pose.snapshot(time+2).rotation, 0f)
assertTrue(moved.rotation.zip(HeadPose.IDENTITY.toList()).any { (a, b) -> kotlin.math.abs(a-b) > 0.1f })
pose.recenter()
assertArrayEquals(HeadPose.IDENTITY, pose.snapshot(time+3).rotation, 1e-5f)
}
@Test fun invalidOldAndFutureSamplesCannotReplaceTheLastSafeView() {
val pose = GlassesMenuPose(spatialEnabled = { false })
pose.onPose(0f, 0f, 0f, 1f, time)
pose.snapshot(time)
pose.onPose(0f, 0.1f, 0f, 0.995f, time+1)
val valid = pose.snapshot(time+1)
pose.onPose(Float.NaN, 0f, 0f, 1f, time+2)
pose.onPose(0f, 0f, 0f, 0f, time+3)
pose.onPose(0.1f, 0f, 0f, 0.995f, time)
val stale = pose.snapshot(time+GlassesMenuPose.MAX_AGE_NS+2)
assertFalse(stale.valid)
assertArrayEquals(valid.rotation, stale.rotation, 0f)
pose.onPose(0.1f, 0f, 0f, 0.995f, time+1_000_000_000L)
val future = pose.snapshot(time+20)
assertFalse(future.valid)
assertArrayEquals(valid.rotation, future.rotation, 0f)
}
@Test fun detachResetDiscardsOldOriginAndHeldPose() {
val pose = GlassesMenuPose(spatialEnabled = { false })
pose.onPose(0f, 0f, 0f, 1f, time)
pose.snapshot(time)
pose.onPose(0f, 0.2f, 0f, 0.98f, time+1)
pose.snapshot(time+1)
pose.reset()
assertFalse(pose.snapshot(time+2).valid)
assertArrayEquals(HeadPose.IDENTITY, pose.snapshot(time+2).rotation, 0f)
pose.onPose(0.2f, 0f, 0f, 0.98f, time+3)
assertArrayEquals(HeadPose.IDENTITY, pose.snapshot(time+3).rotation, 1e-5f)
}
@Test fun spatialScreenPoseKeepsMetresAndHoldsDuringTrackingLoss() {
var current: SpatialPose? = SpatialPose(SpatialVector(0.2f, -0.1f, 0.3f), SpatialRotation(y = 0.1f, w = 0.995f))
var recenters = 0
val pose = GlassesMenuPose({ true }, { current }, { recenters++ })
pose.configure(GlassesSettings(positionalTracking = true))
val valid = pose.snapshot(time)
assertTrue(valid.spatial)
assertTrue(valid.valid)
assertArrayEquals(floatArrayOf(0.2f, -0.1f, 0.3f), valid.position, 0f)
current = null
val lost = pose.snapshot(time+1)
assertFalse(lost.valid)
assertArrayEquals(valid.position, lost.position, 0f)
assertArrayEquals(valid.rotation, lost.rotation, 0f)
pose.recenter()
assertEquals(1, recenters)
}
@Test fun disabledTrackingReturnsAnUntranslatedCenteredView() {
val pose = GlassesMenuPose({ true }, { SpatialPose(SpatialVector(x = 0.2f)) }, {})
pose.configure(GlassesSettings(positionalTracking = true))
pose.snapshot(time)
pose.configure(GlassesSettings(headTracking = false, positionalTracking = true))
val frame = pose.snapshot(time+1)
assertFalse(frame.valid)
assertArrayEquals(HeadPose.IDENTITY, frame.rotation, 0f)
assertArrayEquals(FloatArray(3), frame.position, 0f)
}
@Test fun menuRecenterChangesTheScreenOriginWithoutMovingTheVrFloorOrigin() {
val session = SpatialSession()
session.reset(1, 1.6f)
session.accept(SpatialSample(SpatialPose(SpatialVector(1f, 2f, 3f)), time, 1, true))
session.accept(SpatialSample(SpatialPose(SpatialVector(1.2f, 2.1f, 3f)), time+1, 1, true))
val pose = GlassesMenuPose({ true }, { now -> session.view(true).takeIf { session.valid(now) } },
{ session.recenter(true, time+1) })
pose.configure(GlassesSettings(positionalTracking = true))
val vrBefore = session.view(false)!!
assertArrayEquals(floatArrayOf(0.2f, 0.1f, 0f), pose.snapshot(time+1).position, 1e-5f)
pose.recenter()
assertArrayEquals(FloatArray(3), pose.snapshot(time+1).position, 1e-5f)
assertEquals(vrBefore, session.view(false))
}
@Test fun malformedSpatialPoseCannotReplaceTheHeldView() {
var current = SpatialPose(SpatialVector(x = 0.1f))
val pose = GlassesMenuPose({ true }, { current }, {})
pose.configure(GlassesSettings(positionalTracking = true))
val valid = pose.snapshot(time)
current = SpatialPose(SpatialVector(x = Float.NaN))
assertFalse(pose.snapshot(time+1).valid)
assertArrayEquals(valid.position, pose.snapshot(time+1).position, 0f)
current = SpatialPose(rotation = SpatialRotation(w = 0f))
assertFalse(pose.snapshot(time+2).valid)
assertArrayEquals(valid.rotation, pose.snapshot(time+2).rotation, 0f)
}
@Test fun snapshotsDoNotExposeTheHeldArraysForMutation() {
val pose = GlassesMenuPose(spatialEnabled = { false })
pose.onPose(0f, 0f, 0f, 1f, time)
pose.snapshot(time).rotation.fill(Float.NaN)
assertArrayEquals(HeadPose.IDENTITY, pose.snapshot(time+GlassesMenuPose.MAX_AGE_NS+1).rotation, 1e-5f)
}
}
@@ -0,0 +1,82 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
class GlassesMenuProjectionTest {
private fun frame(rotation: FloatArray = HeadPose.IDENTITY, position: FloatArray = FloatArray(3)) =
GlassesMenuPose.Frame(rotation, position, true, false)
private fun hit(pose: GlassesMenuPose.Frame = frame(), x: Float = 0f, y: Float = 0f, eye: Float = 0f,
aspect: Float = 2f) = GlassesMenuProjection.intersect(pose, x, y, eye, 1f, 3f, aspect)
@Test fun centeredForwardRaySamplesTheTextureCenter() {
assertEquals(GlassesMenuProjection.Uv(0.5f, 0.5f), hit())
}
@Test fun screenTopAndRightRaysUseTopLeftTextureCoordinates() {
val topRight = hit(x = 1f/3f, y = -1f/6f)!!
assertEquals(1f, topRight.x, 1e-5f)
assertEquals(0f, topRight.y, 1e-5f)
}
@Test fun eyeOriginsShiftByPhysicalIpdWhileMonoUsesTheCenter() {
val left = hit(eye = -GlassesMenuSurface.IPD_METERS/2)!!
val right = hit(eye = GlassesMenuSurface.IPD_METERS/2)!!
assertEquals(0.484f, left.x, 1e-5f)
assertEquals(0.516f, right.x, 1e-5f)
assertEquals(0.5f, hit()!!.x, 0f)
}
@Test fun translatedHeadUsesMetresInTheAnchoredScreenFrame() {
val translated = hit(frame(position = floatArrayOf(0.2f, 0.1f, 0f)))!!
assertEquals(0.6f, translated.x, 1e-5f)
assertEquals(0.4f, translated.y, 1e-5f)
}
@Test fun rowMajorPositiveYawTurnsTheForwardRayTowardNegativeX() {
val angle = Math.toRadians(10.0)
val rotation = SpatialRotation(y = kotlin.math.sin(angle/2).toFloat(), w = kotlin.math.cos(angle/2).toFloat()).matrix()
assertEquals(0.5f - 1.5f*kotlin.math.tan(angle).toFloat(), hit(frame(rotation))!!.x, 1e-5f)
}
@Test fun aRayBehindTheHeadOrOutsideThePlaneHasNoUiHit() {
assertNull(hit(frame(rotation = SpatialRotation(y = 1f, w = 0f).matrix())))
assertNull(hit(x = 1f))
assertNull(hit(frame(position = floatArrayOf(0f, 0f, -4f))))
}
@Test fun sourceAspectChangesThePlaneHeightWithoutStretchingItsWidth() {
assertNotNull(hit(y = 0.2f, aspect = 1f))
assertNull(hit(y = 0.2f, aspect = 2f))
}
@Test fun nonFiniteInputsCannotCreateTextureCoordinates() {
assertNull(hit(x = Float.NaN))
assertNull(hit(frame(position = floatArrayOf(Float.POSITIVE_INFINITY, 0f, 0f))))
}
}
private object GlassesMenuProjection {
data class Uv(val x: Float, val y: Float)
// Row-major head-to-anchor rotation; +Y is up, -Z is forward, output UV starts at the top left.
fun intersect(frame: GlassesMenuPose.Frame, rayX: Float, rayY: Float, eye: Float,
halfWidth: Float, distance: Float, aspect: Float): Uv? {
if (frame.rotation.size != 9 || frame.position.size != 3 || frame.rotation.any { !it.isFinite() } ||
frame.position.any { !it.isFinite() } || listOf(rayX, rayY, eye, halfWidth, distance, aspect).any { !it.isFinite() } ||
halfWidth <= 0f || distance <= 0f || aspect <= 0f) return null
val r = frame.rotation
val d = FloatArray(3) { row -> r[row*3]*rayX - r[row*3+1]*rayY - r[row*3+2] }
val o = FloatArray(3) { row -> frame.position[row] + r[row*3]*eye }
if (d[2] >= -0.0001f) return null
val t = (-distance-o[2]) / d[2]
if (t <= 0f) return null
val u = (o[0]+d[0]*t) / halfWidth * 0.5f + 0.5f
val v = -(o[1]+d[1]*t) * aspect / halfWidth * 0.5f + 0.5f
return Uv(u, v).takeIf { u in 0f..1f && v in 0f..1f }
}
}
@@ -0,0 +1,87 @@
package com.droiddeck.launcher.glasses
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.annotation.LooperMode
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowDisplay
import org.robolectric.shadows.ShadowDisplayManager
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], manifest = Config.NONE, shadows = [GlassesMirrorPacingTest.ModeDisplay::class])
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesMirrorPacingTest {
private lateinit var activity: SessionActivity
private val connected = GlassesState(present = true, displayId = 2, width = 1920, height = 1080)
private val settings = GlassesSettings(gameOnGlasses = false, refreshHz = 60)
@Before fun setup() {
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
ReflectionHelpers.setField(activity, "mBase", activity.baseContext.createDisplayContext(display))
val panel = Shadow.extract<ModeDisplay>(activity.display)
panel.supported = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f))
panel.current = panel.supported.last()
SessionState.fpsLimit = 0
}
@After fun cleanup() { SessionState.fpsLimit = 0 }
@Test fun connectingChangingRateAndDisconnectingUpdatePhonePacingWithoutSavingPreferences() {
apply(connected, settings)
expect(1, 60f, 60)
apply(connected, settings.copy(refreshHz = 90))
expect(2, 90f, 90)
apply(GlassesState(), settings)
expect(3, 120f, 0)
assertEquals(0, SessionState.fpsLimit)
}
@Test fun lowerSavedLimitSurvivesMirroringAndStalePhoneRefreshReports() {
SessionState.fpsLimit = 30
apply(connected, settings)
expect(1, 60f, 30)
apply(connected.copy(hz = 120f), settings)
expect(1, 60f, 30)
apply(GlassesState(), settings)
expect(3, 120f, 30)
assertEquals(30, SessionState.fpsLimit)
}
private fun apply(state: GlassesState, config: GlassesSettings) {
ReflectionHelpers.getField<MutableState<GlassesState>>(activity, "glasses\$delegate").value = state
ReflectionHelpers.getField<MutableState<GlassesSettings>>(activity, "glassesSettings\$delegate").value = config
ReflectionHelpers.callInstanceMethod<Void>(activity, "applyOutputPacing")
}
private fun expect(mode: Int, hz: Float, fps: Int) {
assertEquals(mode, activity.window.attributes.preferredDisplayModeId)
assertEquals(hz, ReflectionHelpers.callInstanceMethod<Float>(activity, "refreshHz"), 0.01f)
assertEquals(fps, ReflectionHelpers.callInstanceMethod<Int>(activity, "outputFpsLimit").toInt())
}
private fun mode(id: Int, hz: Float): Display.Mode = ShadowDisplayManager.ModeBuilder.modeBuilder(id)
.setWidth(1080).setHeight(2520).setRefreshRate(hz).build()
@Implements(Display::class)
class ModeDisplay : ShadowDisplay() {
lateinit var current: Display.Mode
var supported = emptyArray<Display.Mode>()
@Implementation protected fun getMode(): Display.Mode = current
@Implementation protected fun getSupportedModes(): Array<Display.Mode> = supported
}
}
@@ -0,0 +1,162 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.glasses.GlassesModeState.Confirmation
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class GlassesModeStateTest {
private val device = GlassesModeState.Device(0x101d, "pro")
private val state = GlassesModeState(20_000).apply { updateDevice(device, 0) }
@Test fun transientFallbackDoesNotRejectAWorkingStereoTransition() {
state.sent(true, 100)
assertEquals(Confirmation.WAITING, state.observe(false, 2_000))
assertEquals(Confirmation.WAITING, state.observe(false, 19_000))
assertFalse(state.restorePending)
assertEquals(Confirmation.CONFIRMED, state.observe(true, 19_500))
assertFalse(state.pendingStereo)
assertEquals(Confirmation.NONE, state.observe(false, 20_100))
}
@Test fun missingSignalAtDeadlineRequestsOneFallback() {
state.sent(true, 100)
assertEquals(Confirmation.WAITING, state.observe(false, 20_099))
assertEquals(Confirmation.FAILED, state.observe(false, 20_100))
assertTrue(state.restorePending)
assertEquals(Confirmation.NONE, state.observe(false, 40_000))
state.sent(false, 40_001)
assertFalse(state.restorePending)
assertFalse(state.stopVr())
}
@Test fun stoppingVrBeforeStereoAppearsStillRestores2d() {
state.sent(true, 100)
state.startVr()
assertTrue(state.stopVr())
assertTrue(state.restorePending)
state.sent(false, 200)
assertFalse(state.pendingStereo)
assertFalse(state.restorePending)
assertFalse(state.stopVr())
assertEquals(Confirmation.NONE, state.observe(true, 400))
}
@Test fun failedRevertRemainsPendingUntilAWriteSucceeds() {
state.sent(true, 100)
state.startVr()
state.observe(true, 200)
state.stopVr()
state.cancelPending()
assertTrue(state.restorePending)
assertTrue(state.stopVr())
state.sent(false, 300)
assertFalse(state.restorePending)
}
@Test fun manualModeTakesOwnershipFromVr() {
state.sent(true, 100)
state.startVr()
state.manual()
state.sent(true, 200)
assertFalse(state.stopVr())
assertFalse(state.restorePending)
assertEquals(Confirmation.CONFIRMED, state.observe(true, 300))
}
@Test fun manualRetryGetsItsOwnConfirmationWindow() {
state.sent(true, 100)
assertEquals(Confirmation.FAILED, state.observe(false, 20_100))
state.sent(false, 20_101)
state.manual()
state.sent(true, 30_000)
assertEquals(Confirmation.WAITING, state.observe(false, 49_999))
assertEquals(Confirmation.CONFIRMED, state.observe(true, 50_000))
assertFalse(state.restorePending)
}
@Test fun cancelledOrDisconnectedRequestCannotFailLater() {
state.sent(true, 100)
state.cancelPending()
assertFalse(state.pendingStereo)
assertEquals(Confirmation.NONE, state.observe(false, 20_100))
assertFalse(state.restorePending)
}
@Test fun manual2dCancelsThePendingStereoDeadline() {
state.sent(true, 100)
state.manual()
state.sent(false, 200)
assertFalse(state.pendingStereo)
assertEquals(Confirmation.NONE, state.observe(false, 20_100))
}
@Test fun modeReenumerationPreservesDeadlineAndVrOwnership() {
state.sent(true, 100)
state.startVr()
assertFalse(state.updateDevice(null, 1_000))
assertEquals(Confirmation.WAITING, state.observe(false, 1_000))
assertFalse(state.updateDevice(device, 2_000))
assertEquals(20_100L, state.nextCheckAt)
assertEquals(Confirmation.CONFIRMED, state.observe(true, 3_000))
assertTrue(state.stopVr())
}
@Test fun absentAtDeadlineCancelsWithoutFailureOrLateRestore() {
state.sent(true, 100)
state.startVr()
state.updateDevice(null, 1_000)
state.stopVr()
assertEquals(Confirmation.NONE, state.observe(false, 20_100))
assertFalse(state.restorePending)
assertNull(state.nextCheckAt)
assertFalse(state.updateDevice(device, 40_000))
assertFalse(state.stopVr())
}
@Test fun differentModelOrKnownSerialCannotInheritARequest() {
listOf(GlassesModeState.Device(0x1131, "pro"), device.copy(serial = "other")).forEach { other ->
state.updateDevice(device, 0)
state.sent(true, 100)
state.startVr()
state.updateDevice(null, 1_000)
assertTrue(state.updateDevice(other, 2_000))
assertFalse(state.pendingStereo)
assertFalse(state.stopVr())
}
}
@Test fun permissionPendingReconnectKeepsTheKnownIdentity() {
state.sent(true, 100)
state.startVr()
state.updateDevice(null, 1_000)
assertFalse(state.updateDevice(device.copy(serial = null), 2_000))
assertTrue(state.pendingStereo)
assertTrue(state.updateDevice(device.copy(serial = "other"), 3_000))
assertFalse(state.pendingStereo)
assertFalse(state.stopVr())
}
@Test fun sameDeviceReconnectDoesNotResetFailureStatus() {
state.sent(true, 100)
assertEquals(Confirmation.FAILED, state.observe(false, 20_100))
state.sent(false, 20_101)
assertFalse(state.updateDevice(null, 21_000))
assertFalse(state.updateDevice(device, 22_000))
}
@Test fun confirmedVrCannotRestoreAfterAProlongedUnplug() {
state.sent(true, 100)
state.startVr()
state.observe(true, 200)
state.updateDevice(null, 1_000)
assertTrue(state.stopVr())
assertEquals(21_000L, state.nextCheckAt)
state.updateDevice(device, 22_000)
assertFalse(state.restorePending)
assertFalse(state.stopVr())
assertNull(state.nextCheckAt)
}
}
@@ -0,0 +1,99 @@
package com.droiddeck.launcher.glasses
import android.hardware.display.DisplayManager
import android.view.Display
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import org.junit.Assert.*
import org.junit.Before
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.LooperMode
import org.robolectric.shadows.ShadowDisplayManager
import org.robolectric.util.ReflectionHelpers
import org.robolectric.util.ReflectionHelpers.ClassParameter.from
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], manifest = Config.NONE)
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesOutputHandoffTest {
private lateinit var activity: SessionActivity
private lateinit var phone: SurfaceView
private lateinit var screen: GlassesScreen
@Before fun setup() {
// Exercise the output lifecycle without starting the native Linux runtime.
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
phone = SurfaceView(activity)
ReflectionHelpers.setField(activity, "surfaceView", phone)
ReflectionHelpers.setField(activity, "ended", true)
val app = RuntimeEnvironment.getApplication()
val id = ShadowDisplayManager.addDisplay("w1920dp-h1080dp")
val display = app.getSystemService(DisplayManager::class.java).getDisplay(id)
shadowOf(display).setFlags(Display.FLAG_PRESENTATION)
screen = GlassesScreen(activity, display, 60, activity)
ReflectionHelpers.setField(activity, "glassesScreen", screen)
}
@Test fun selectingGlassesDoesNotHidePhoneOrClaimOutputBeforeAttachment() {
assertFalse(active())
assertEquals(View.VISIBLE, phone.visibility)
attach(phone.holder) // A late phone callback must not complete the handoff.
assertFalse(active())
assertEquals(View.VISIBLE, phone.visibility)
}
@Test fun attachingGlassesRemovesPhoneSurfaceButPreservesItsInputLayout() {
phone.layout(0, 0, 1200, 800)
attach(screen.holder)
assertTrue(active())
assertEquals(View.INVISIBLE, phone.visibility)
assertEquals(1200, phone.width)
assertEquals(800, phone.height)
}
@Test fun latePhoneDestructionDoesNotResetTheGlassesOutput() {
attach(screen.holder)
ReflectionHelpers.setField(activity, "surfaceW", 3840)
ReflectionHelpers.setField(activity, "surfaceH", 1080)
activity.surfaceDestroyed(phone.holder)
assertTrue(active())
assertEquals(3840, ReflectionHelpers.getField<Int>(activity, "surfaceW"))
assertEquals(1080, ReflectionHelpers.getField<Int>(activity, "surfaceH"))
}
@Test fun disconnectRestoresPhoneAndRejectsLateGlassesAttachment() {
attach(screen.holder)
ReflectionHelpers.callInstanceMethod<Void>(activity, "restorePhoneOutput", from(GlassesScreen::class.java, screen))
assertFalse(active())
assertEquals(View.VISIBLE, phone.visibility)
attach(screen.holder)
assertFalse(active())
assertEquals(View.VISIBLE, phone.visibility)
}
@Test fun losingGlassesSurfaceClearsThePlayingHint() {
attach(screen.holder)
activity.surfaceDestroyed(screen.holder)
assertFalse(active())
}
private fun attach(holder: SurfaceHolder) {
ReflectionHelpers.callInstanceMethod<Void>(activity, "onOutputAttached", from(SurfaceHolder::class.java, holder))
}
private fun active(): Boolean =
ReflectionHelpers.getField<MutableState<Boolean>>(activity, "glassesOutputActive\$delegate").value
}
@@ -0,0 +1,233 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.Cardboard
import org.junit.Assert.*
import org.junit.Test
class GlassesRenderingTest {
private val ultra = GlassesState(
model = "VITURE Luma Ultra", connected = true, controllable = true,
displayId = 2, width = 1920, height = 1200,
)
private val base = Cardboard(ipdMm = 67)
@Test fun thirtyHzRequiresANativeModeAndDedicatedGlassesOutput() {
val settings = GlassesSettings(refreshHz = 30, sbsHz = 30)
for (stereo in listOf(false, true)) for (sbs90 in listOf(false, true)) {
val state = ultra.copy(sbs = stereo, sbs90 = sbs90, supports30Hz = true)
assertTrue(GlassesRendering.refreshRates(settings, state).contains(30))
assertEquals(30, GlassesRendering.outputHz(settings, state))
assertEquals(60, GlassesRendering.mirrorRefreshLimit(settings, state.copy(hz = 60f), false))
assertEquals(30, GlassesRendering.mirrorRefreshLimit(settings, state.copy(hz = 29.97f), false))
for (unavailable in listOf(state.copy(supports30Hz = false), state.copy(noSignal = true), state.copy(displayId = -1))) {
assertFalse(GlassesRendering.refreshRates(settings, unavailable).contains(30))
assertEquals(60, GlassesRendering.outputHz(settings, unavailable))
}
val mirrored = settings.copy(gameOnGlasses = false)
assertFalse(GlassesRendering.refreshRates(mirrored, state).contains(30))
assertEquals(60, GlassesRendering.outputHz(mirrored, state))
assertEquals(60, GlassesRendering.mirrorRefreshLimit(mirrored, state, false))
}
}
@Test fun mirroredRefreshUsesTheSelectedGlassesRateEvenBeforeTheDisplaySwitches() {
val settings = GlassesSettings(gameOnGlasses = false, refreshHz = 60)
assertEquals(60, GlassesRendering.mirrorRefreshLimit(settings, ultra.copy(hz = 120f), false))
assertEquals(90, GlassesRendering.mirrorRefreshLimit(settings.copy(refreshHz = 90), ultra, false))
assertEquals(60, GlassesRendering.mirrorRefreshLimit(settings, ultra.copy(connected = false), false))
}
@Test fun mirroredStereoUsesTheStereoRefreshAndItsHardwareLimit() {
val settings = GlassesSettings(refreshHz = 120, sbsHz = 90)
assertEquals(60, GlassesRendering.mirrorRefreshLimit(settings, ultra.copy(sbs = true), false))
assertEquals(90, GlassesRendering.mirrorRefreshLimit(settings, ultra.copy(sbs = true, sbs90 = true), false))
}
@Test fun disconnectOrDedicatedOutputRemovesTheMirrorCap() {
val settings = GlassesSettings(refreshHz = 60)
assertEquals(0, GlassesRendering.mirrorRefreshLimit(settings, GlassesState(), false))
assertEquals(0, GlassesRendering.mirrorRefreshLimit(settings, ultra.copy(noSignal = true), false))
assertEquals(0, GlassesRendering.mirrorRefreshLimit(settings, ultra, true))
}
@Test fun mirrorCapPreservesLowerLimitsAndRestoresTheRequestedLimitAfterDisconnect() {
for (requested in listOf(0, 30, 60, 90, 120)) {
assertEquals(if (requested == 30) 30 else 60, GlassesRendering.fpsLimit(requested, 60))
assertEquals(requested, GlassesRendering.fpsLimit(requested, 0))
}
}
private fun render(settings: GlassesSettings, state: GlassesState = ultra, steamVr: Boolean = false) =
GlassesRendering.cardboard(base, settings, state, outputActive = true, steamVrRunning = steamVr)
@Test fun steamVrDefaultsToOneTrackedEyeWithoutRequestingStereo() {
val settings = GlassesSettings()
assertFalse(settings.auto3d)
val projection = render(settings, steamVr = true)
assertTrue(projection.enabled)
assertTrue(projection.mono)
assertTrue(projection.headTracking)
assertEquals(Cardboard.SOURCE_SBS, projection.source)
}
@Test fun automatic2dIsFlatSoVirtualScreenSettingsDoNotApply() {
val settings = GlassesSettings(screenWidthDm = 40, screenDistanceDm = 80)
assertEquals(GlassesRendering.Picture.FLAT, GlassesRendering.picture(settings, false, false))
assertEquals(Cardboard.OFF, render(settings))
assertEquals(Cardboard.OFF, render(settings.copy(screenWidthDm = 10, screenDistanceDm = 10)))
}
@Test fun selectingVirtualScreenMakesSizeDistanceAndTrackingReachTheRendererIn2d() {
val settings = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN,
screenWidthDm = 40, screenDistanceDm = 80)
val projection = render(settings)
assertTrue(projection.enabled)
assertTrue(projection.mono)
assertTrue(projection.headTracking)
assertEquals(Cardboard.SOURCE_SCREEN, projection.source)
assertEquals(40, projection.screenWidthDm)
assertEquals(80, projection.screenDistanceDm)
assertEquals(67, projection.ipdMm)
val changed = render(settings.copy(screenWidthDm = 15, screenDistanceDm = 20, headTracking = false))
assertEquals(15, changed.screenWidthDm)
assertEquals(20, changed.screenDistanceDm)
assertFalse(changed.headTracking)
}
@Test fun automaticSbsDuplicatesTheWholeFrameWithoutEnablingHeadTracking() {
val settings = GlassesSettings()
val stereo = ultra.copy(sbs = true, width = 3840)
assertEquals(GlassesRendering.Picture.DUPLICATED, GlassesRendering.picture(settings, true, false))
assertEquals(Cardboard.SOURCE_FLAT, render(settings, stereo).source)
assertFalse(render(settings, stereo).headTracking)
assertFalse(render(settings, stereo).mono)
assertEquals(GlassesRendering.Picture.STEREO, GlassesRendering.picture(settings, true, true))
assertEquals(Cardboard.SOURCE_SBS, render(settings, stereo, steamVr = true).source)
assertTrue(render(settings, stereo, steamVr = true).headTracking)
}
@Test fun flatSbsDoesNotDependOnTheTrackingPreferenceOrUsbControl() {
for (tracking in listOf(false, true)) for (connected in listOf(false, true)) {
for (height in listOf(1080, 1200)) {
val state = ultra.copy(sbs = true, width = 3840, height = height, connected = connected)
val settings = GlassesSettings(headTracking = tracking)
val flat = render(settings, state)
assertTrue(flat.enabled)
assertFalse(flat.mono)
assertFalse(flat.headTracking)
assertEquals(Cardboard.SOURCE_FLAT, flat.source)
assertEquals(Cardboard.SOURCE_SBS, render(settings.copy(picture3d = GlassesSettings.PICTURE_SBS), state).source)
}
}
}
@Test fun virtualScreenTracksFlatContentIndependentlyOfTheHardwareSbsMode() {
val settings = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN)
assertTrue(settings.screen3dof)
assertFalse(settings.copy(headTracking = false).screen3dof)
for (height in listOf(1080, 1200)) {
for (sbs in listOf(false, true)) {
val projection = render(settings, ultra.copy(width = if (sbs) 3840 else 1920, height = height, sbs = sbs))
assertTrue(projection.enabled)
assertTrue(projection.headTracking)
assertEquals(Cardboard.SOURCE_SCREEN, projection.source)
assertEquals(!sbs, projection.mono)
}
}
}
@Test fun explicitPictureChoiceOverridesAutomaticResolutionOutsideSteamVr() {
val virtual = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN)
val direct = GlassesSettings(picture3d = GlassesSettings.PICTURE_SBS)
for (stereo in listOf(false, true)) {
assertEquals(GlassesRendering.Picture.VIRTUAL_SCREEN, GlassesRendering.picture(virtual, stereo, false))
assertEquals(GlassesRendering.Picture.STEREO, GlassesRendering.picture(direct, stereo, false))
}
}
@Test fun steamVrSplitsTheEyePairRegardlessOfTheSavedFlatGamePicture() {
for (picture in listOf(GlassesSettings.PICTURE_AUTO, GlassesSettings.PICTURE_SCREEN, GlassesSettings.PICTURE_SBS)) {
val settings = GlassesSettings(picture3d = picture, auto3d = true)
for (stereo in listOf(false, true)) for (outputActive in listOf(false, true)) {
val state = ultra.copy(sbs = stereo, width = if (stereo) 3840 else 1920)
val projection = GlassesRendering.cardboard(base, settings, state, outputActive, true)
assertEquals(GlassesRendering.Picture.STEREO, GlassesRendering.picture(settings, stereo, true))
assertEquals(Cardboard.SOURCE_SBS, projection.source)
assertEquals(!stereo, projection.mono)
assertTrue(projection.enabled)
assertTrue(projection.headTracking)
}
}
}
@Test fun stoppingSteamVrRestoresTheSavedVirtualScreen() {
val settings = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN, auto3d = true,
screenWidthDm = 18, screenDistanceDm = 30)
val before = render(settings)
assertEquals(Cardboard.SOURCE_SCREEN, before.source)
assertEquals(Cardboard.SOURCE_SBS, render(settings, steamVr = true).source)
assertEquals(before, render(settings))
assertEquals(GlassesSettings.PICTURE_SCREEN, settings.picture3d)
}
@Test fun mirrorModeKeepsThePhoneProjectionInsteadOfApplyingDormantGlassesSettings() {
val phone = base.copy(enabled = true, screenWidthDm = 60, screenDistanceDm = 20)
val settings = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN,
gameOnGlasses = false, screenWidthDm = 10, screenDistanceDm = 50)
assertSame(phone, GlassesRendering.cardboard(phone, settings, ultra, false, false))
}
@Test fun steamVrOnPhoneKeepsHeadsetActiveWithoutEnablingTheSavedCardboardSetting() {
val settings = GlassesSettings(gameOnGlasses = false, headTracking = false,
picture3d = GlassesSettings.PICTURE_SCREEN)
for (state in listOf(ultra.copy(displayId = -1), GlassesState())) {
val preview = GlassesRendering.cardboard(base, settings, state, false, true)
assertTrue(preview.enabled) // Published as headset proximity, preventing standby.
assertTrue(preview.mono)
assertEquals(Cardboard.SOURCE_SBS, preview.source)
assertEquals(Cardboard.Viewer.NONE.id, preview.viewer)
assertTrue(preview.headTracking) // Phone preference, not dormant glasses settings.
assertFalse(base.enabled)
assertSame(base, GlassesRendering.cardboard(base, settings, state, false, false))
}
val noTracking = base.copy(headTracking = false)
assertFalse(GlassesRendering.cardboard(noTracking, settings, GlassesState(), false, true).headTracking)
}
@Test fun steamVrKeepsAnEnabledPhoneViewerAndSwitchesBackToGlassesRenderingOnHandoff() {
val phone = base.copy(enabled = true, source = Cardboard.SOURCE_SBS)
val settings = GlassesSettings()
assertSame(phone, GlassesRendering.cardboard(phone, settings, GlassesState(), false, true))
val glasses = GlassesRendering.cardboard(base, settings, ultra.copy(sbs = true), true, true)
assertTrue(glasses.enabled)
assertFalse(glasses.mono)
assertEquals(Cardboard.Viewer.VITURE.id, glasses.viewer)
assertEquals(Cardboard.SOURCE_SBS, glasses.source)
}
@Test fun steamVrMirroringKeepsTheSameGlassesPictureAndSensorSource() {
for (stereo in listOf(false, true)) {
val state = ultra.copy(sbs = stereo)
for (picture in listOf(GlassesSettings.PICTURE_AUTO, GlassesSettings.PICTURE_SCREEN, GlassesSettings.PICTURE_SBS)) {
val settings = GlassesSettings(picture3d = picture)
val dedicated = GlassesRendering.cardboard(base, settings, state, true, true)
val mirrored = GlassesRendering.cardboard(base, settings.copy(gameOnGlasses = false), state, false, true)
assertEquals(dedicated, mirrored)
assertTrue(mirrored.enabled)
assertTrue(mirrored.headTracking)
assertTrue(GlassesRendering.usesGlasses(state, false, true))
}
}
assertFalse(GlassesRendering.usesGlasses(ultra, false, false))
assertFalse(GlassesRendering.usesGlasses(GlassesState(), false, true))
assertTrue(GlassesRendering.usesGlasses(ultra, true, false))
}
@Test fun missingUsbControlOnlyDisablesTrackingNotScreenSize() {
val settings = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN, screenWidthDm = 35)
val projection = render(settings, ultra.copy(connected = false))
assertTrue(projection.enabled)
assertFalse(projection.headTracking)
assertEquals(35, projection.screenWidthDm)
}
}
@@ -0,0 +1,146 @@
package com.droiddeck.launcher.glasses
import android.hardware.display.DisplayManager
import android.view.Display
import android.view.SurfaceHolder
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.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.annotation.LooperMode
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowDisplay
import org.robolectric.shadows.ShadowDisplayManager
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], manifest = Config.NONE, shadows = [GlassesScreenTest.ModeDisplay::class])
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesScreenTest {
@Test fun recoveryCoversTheExistingRenderSurfaceWithoutReplacingIt() {
val flat=mode(1,1920,1200,60f)
val (screen,_)=screen(flat,arrayOf(flat),60)
val holder=screen.holder
val root=screen.surfaceView.parent as android.view.ViewGroup
assertTrue(root.indexOfChild(screen.trackingRecovery)>root.indexOfChild(screen.surfaceView))
screen.trackingRecovery.update(TrackingRecovery.LOST,false)
assertEquals(android.view.View.VISIBLE,screen.trackingRecovery.visibility)
screen.trackingRecovery.update(null,false)
assertEquals(android.view.View.GONE,screen.trackingRecovery.visibility)
assertTrue(holder===screen.holder)
}
@Test fun nativeThirtyHzMustMatchBothDimensionsOfTheCurrentEyeLayout() {
val flat60 = mode(1, 1920, 1200, 60f)
val flat30 = mode(2, 1920, 1200, 29.97f)
val stereo60 = mode(3, 3840, 1200, 60f)
val stereo30 = mode(4, 3840, 1200, 30f)
val short30 = mode(5, 3840, 1080, 30f)
val (screen, panel) = screen(flat60, arrayOf(flat60, flat30, stereo60, short30), 30)
assertTrue(Glasses.supports30Hz(screen.display))
assertEquals(flat30.modeId, screen.window!!.attributes.preferredDisplayModeId)
panel.current = stereo60
screen.prefer(30)
assertFalse(Glasses.supports30Hz(screen.display))
assertEquals(stereo60.modeId, screen.window!!.attributes.preferredDisplayModeId)
panel.supported += stereo30
screen.prefer(30)
assertTrue(Glasses.supports30Hz(screen.display))
assertEquals(stereo30.modeId, screen.window!!.attributes.preferredDisplayModeId)
}
@Test fun switchingBetween2dAndStereoRefreshesTheModePreferenceEvenAtTheSameHz() {
val flat = mode(1, 1920, 1200, 60f)
val stereo = mode(2, 3840, 1200, 60f)
val (screen, panel) = screen(flat, arrayOf(flat, stereo), 60)
assertEquals(flat.modeId, screen.window!!.attributes.preferredDisplayModeId)
panel.current = stereo
screen.prefer(60)
assertEquals(stereo.modeId, screen.window!!.attributes.preferredDisplayModeId)
panel.current = flat
screen.prefer(60)
assertEquals(flat.modeId, screen.window!!.attributes.preferredDisplayModeId)
}
@Test fun refreshPreferenceKeepsBothDimensionsOfTheActiveStereoMode() {
val stereo1080 = mode(1, 3840, 1080, 90f)
val stereo1200 = mode(2, 3840, 1200, 60f)
val (screen, _) = screen(stereo1200, arrayOf(stereo1080, stereo1200), 90)
assertEquals(stereo1200.modeId, screen.window!!.attributes.preferredDisplayModeId)
}
@Test fun refreshChangesStillChooseTheNearestRateAtTheCurrentResolution() {
val stereo60 = mode(1, 3840, 1200, 60f)
val stereo90 = mode(2, 3840, 1200, 90f)
val flat120 = mode(3, 1920, 1200, 120f)
val (screen, _) = screen(stereo60, arrayOf(stereo60, stereo90, flat120), 60)
screen.prefer(120)
assertEquals(stereo90.modeId, screen.window!!.attributes.preferredDisplayModeId)
}
@Test fun explicitResolutionChangesBothDimensionsWithoutSwitchingEyeLayout() {
val flat1080 = mode(1, 1920, 1080, 90f)
val flat1200 = mode(2, 1920, 1200, 90f)
val stereo1080 = mode(3, 3840, 1080, 90f)
val stereo1200 = mode(4, 3840, 1200, 90f)
val (screen, panel) = screen(flat1200, arrayOf(flat1080, flat1200, stereo1080, stereo1200), 90)
screen.prefer(90, GlassesResolution(1920, 1080))
assertEquals(flat1080.modeId, screen.window!!.attributes.preferredDisplayModeId)
panel.current = stereo1200
screen.prefer(90, GlassesResolution(1920, 1080))
assertEquals(stereo1080.modeId, screen.window!!.attributes.preferredDisplayModeId)
screen.prefer(90, GlassesResolution(1920, 1200))
assertEquals(stereo1200.modeId, screen.window!!.attributes.preferredDisplayModeId)
}
@Test fun unavailableResolutionKeepsTheCurrentModeUntilHardwareConfirmsTheChange() {
val stereo60 = mode(1, 3840, 1200, 60f)
val stereo90 = mode(2, 3840, 1200, 90f)
val flat1080 = mode(3, 1920, 1080, 90f)
val (screen, _) = screen(stereo60, arrayOf(stereo60, stereo90, flat1080), 60)
screen.prefer(90, GlassesResolution(1920, 1080))
assertEquals(stereo90.modeId, screen.window!!.attributes.preferredDisplayModeId)
}
private fun mode(id: Int, width: Int, height: Int, hz: Float): Display.Mode =
ShadowDisplayManager.ModeBuilder.modeBuilder(id)
.setWidth(width).setHeight(height).setRefreshRate(hz).build()
private fun screen(current: Display.Mode, modes: Array<Display.Mode>, hz: Int): Pair<GlassesScreen, ModeDisplay> {
val context = RuntimeEnvironment.getApplication()
val id = ShadowDisplayManager.addDisplay("w1920dp-h1200dp")
val display = context.getSystemService(DisplayManager::class.java).getDisplay(id)
shadowOf(display).setFlags(Display.FLAG_PRESENTATION)
val panel = Shadow.extract<ModeDisplay>(display).apply {
this.current = current
supported = modes
}
val callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) = Unit
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
override fun surfaceDestroyed(holder: SurfaceHolder) = Unit
}
return GlassesScreen(context, display, hz, callback).apply { create() } to panel
}
@Implements(Display::class)
class ModeDisplay : ShadowDisplay() {
lateinit var current: Display.Mode
var supported = emptyArray<Display.Mode>()
@Implementation protected fun getMode(): Display.Mode = current
@Implementation protected fun getSupportedModes(): Array<Display.Mode> = supported
}
}
@@ -0,0 +1,152 @@
package com.droiddeck.launcher.glasses
import android.app.Application
import android.content.Intent
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.SteamVr
import com.droiddeck.launcher.runtime.FlatpakManager
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowDisplayManager
import org.robolectric.util.ReflectionHelpers
import org.robolectric.util.ReflectionHelpers.ClassParameter
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class, manifest = Config.NONE)
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesSessionModesTest {
private data class Launch(val name: String, val mode: String, val program: String? = null, val args: Array<String>? = null)
private val launches = listOf(
Launch("Steam and store games", SessionService.MODE_STEAM),
Launch("Desktop", SessionService.MODE_DESKTOP),
Launch("Standalone", SessionService.MODE_RUN, "/usr/bin/example-game"),
Launch("Emulator", SessionService.MODE_RUN, "/usr/bin/retroarch", arrayOf("/games/example.rom")),
Launch("Flatpak", SessionService.MODE_RUN, FlatpakManager.LAUNCHER, arrayOf("org.example.Game")),
)
private lateinit var display: Display
private lateinit var restore: () -> Unit
private val saved = GlassesSettings(picture3d = GlassesSettings.PICTURE_SCREEN,
headTracking = true, screenWidthDm = 35, screenDistanceDm = 45)
private val phone = Cardboard(enabled = true, source = Cardboard.SOURCE_SCREEN, ipdMm = 67,
screenWidthDm = 20, screenDistanceDm = 30, headTracking = false)
@Before fun setUp() {
val running = SessionState.running
val steamVr = SessionState.steamVr
val mode = SessionState.mode
val fields = listOf("context", "publisherAttached").associateWith {
SpatialTracking::class.java.getDeclaredField(it).apply { isAccessible = true }
}
val values = fields.mapValues { it.value.get(null) }
fields.getValue("context").set(null, null)
fields.getValue("publisherAttached").set(null, false)
restore = {
fields.forEach { (name, field) -> field.set(null, values[name]) }
SessionState.running = running
SessionState.steamVr = steamVr
SessionState.mode = mode
}
val id = ShadowDisplayManager.addDisplay("w1920dp-h1080dp")
display = RuntimeEnvironment.getApplication().getSystemService(DisplayManager::class.java).getDisplay(id)
SessionState.running = true
SessionState.steamVr = false
}
@After fun tearDown() {
SpatialTracking.useLegacyTracking()
SpatialTracking.disconnect()
ShadowDisplayManager.removeDisplay(display.displayId)
restore()
}
@Test fun flatScreenSizeDistanceAndTrackingReachEveryGuestSessionWithoutSteamVr() {
for (launch in launches) for (spatial in listOf(false, true)) {
val activity = activity(launch, saved.copy(positionalTracking = spatial), output = true)
SpatialTracking.connect(0, 101, null, spatial, 1.6f, false)
val projection = projection(activity)
assertTrue(launch.name, projection.enabled)
assertTrue(launch.name, projection.headTracking)
assertTrue(launch.name, projection.mono)
assertEquals(launch.name, Cardboard.SOURCE_SCREEN, projection.source)
assertEquals(launch.name, Cardboard.Viewer.VITURE.id, projection.viewer)
assertEquals(launch.name, 35, projection.screenWidthDm)
assertEquals(launch.name, 45, projection.screenDistanceDm)
assertEquals(launch.name, phone.ipdMm, projection.ipdMm)
assertEquals(launch.name, if (spatial) TrackingRecovery.LOST else null, recovery(activity))
}
}
@Test fun positionalRecoverySurvivesUsbLossInEveryGuestSessionAndHonorsTrackingOff() {
for (launch in launches) {
val activity = activity(launch, saved.copy(positionalTracking = true), output = true)
SpatialTracking.connect(0, 102, null, true, 1.6f, false)
assertEquals(launch.name, TrackingRecovery.LOST, recovery(activity))
SpatialTracking.disconnect()
state(activity, "glasses", glasses().copy(connected = false, supportsSpatial = false))
assertEquals(launch.name, TrackingRecovery.DISCONNECTED, recovery(activity))
state(activity, "glassesSettings", saved.copy(positionalTracking = true, headTracking = false))
assertFalse(launch.name, projection(activity).headTracking)
assertNull(launch.name, recovery(activity))
}
}
@Test fun savedGlassesTrackingDoesNotChangePhoneRenderingOrRecoveryInAnySessionMode() {
for (launch in launches) {
val activity = activity(launch, saved.copy(positionalTracking = true), output = false)
SpatialTracking.connect(0, 103, null, true, 1.6f, false)
assertSame(launch.name, phone, projection(activity))
assertNull(launch.name, recovery(activity))
}
}
private fun activity(launch: Launch, settings: GlassesSettings, output: Boolean): SessionActivity {
val intent = Intent(RuntimeEnvironment.getApplication(), SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, launch.mode)
.putExtra(SessionService.EXTRA_PROGRAM, launch.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, launch.args)
SessionState.mode = launch.mode
return Robolectric.buildActivity(SessionActivity::class.java, intent).get().also {
ReflectionHelpers.setField(it, "loading", LoadingState(it).apply { visible = false })
ReflectionHelpers.setField(it, "started", true)
if (output) ReflectionHelpers.setField(it, "glassesScreen", GlassesScreen(it, display, 60, it))
state(it, "glassesOutputActive", output)
state(it, "glasses", glasses())
state(it, "glassesSettings", settings)
state(it, "steamVrStatus", SteamVr.Status.READY)
}
}
private fun glasses() = GlassesState(present = true, connected = true, controllable = true,
supportsSpatial = true, supportsScreen3dof = true, displayId = display.displayId, width = 1920, height = 1080)
private fun projection(activity: SessionActivity): Cardboard = ReflectionHelpers.callInstanceMethod(
activity, "effectiveCardboard", ClassParameter.from(Cardboard::class.java, phone))
private fun recovery(activity: SessionActivity): TrackingRecovery? {
ReflectionHelpers.callInstanceMethod<Void>(activity, "updateTrackingRecovery")
return ReflectionHelpers.getField<MutableState<TrackingRecovery?>>(activity, "trackingRecovery\$delegate").value
}
private fun <T> state(activity: SessionActivity, name: String, value: T) {
ReflectionHelpers.getField<MutableState<T>>(activity, name + "\$delegate").value = value
}
}
@@ -0,0 +1,33 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class GlassesSpatialAvailabilityTest {
private val ultra = GlassesState(connected = true, controllable = true, supportsSpatial = true)
private val selected = GlassesSettings(positionalTracking = true, handControllers = true)
@Test fun sdkConfirmedConnectedUltraOwnsSpatialControllerInput() {
assertTrue(ultra.spatialConnected)
assertTrue(ultra.usesSpatialControllers(selected))
assertTrue(ultra.usesSpatialControllers(selected.copy(handControllers = false, joyConTracking = true)))
assertFalse(ultra.usesSpatialControllers(selected.copy(positionalTracking = false)))
assertFalse(ultra.usesSpatialControllers(selected.copy(handControllers = false)))
}
@Test fun savedUltraPreferencesDoNotSelectSpatialInputForOtherGlasses() {
for (name in listOf("VITURE Luma Ultra", "VITURE Luma Pro", "VITURE Pro", "XREAL", "RayNeo")) {
val other = ultra.copy(model = name, supportsSpatial = false)
assertFalse(name, other.spatialConnected)
assertFalse(name, other.usesSpatialControllers(selected))
assertFalse(name, other.usesSpatialControllers(selected.copy(handControllers = false, joyConTracking = true)))
}
}
@Test fun disconnectedOrUncontrollableUltraCannotClaimSpatialInput() {
for (state in listOf(ultra.copy(connected = false), ultra.copy(controllable = false), GlassesState())) {
assertFalse(state.spatialConnected)
assertFalse(state.usesSpatialControllers(selected))
}
}
}
@@ -0,0 +1,269 @@
package com.droiddeck.launcher.glasses
import android.app.Application
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.SteamVr
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Assert.*
import org.junit.After
import org.junit.Before
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.LooperMode
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class)
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesSteamVrTest {
private val commands = mutableListOf<Int>()
private val handler = Handler(Looper.getMainLooper())
private lateinit var restore: () -> Unit
private fun field(name: String) = Glasses::class.java.getDeclaredField(name).apply { isAccessible = true }
private val spatialGate get() = field("steamVrSpatialGate").get(null) as SteamVrSpatialGate
@Before fun prepare() {
spatialGate.cancel()
val fields = listOf("handler", "app", "model").associateWith { field(it).get(null) }
@Suppress("UNCHECKED_CAST")
val flows = listOf("_state", "_settings").map { field(it).get(null) as MutableStateFlow<Any> }
val values = flows.map { it.value }
val mode = SessionState.mode
restore = {
fields.forEach { (name, value) -> field(name).set(null, value) }
flows.zip(values).forEach { (flow, value) -> flow.value = value }
SessionState.mode = mode
}
field("handler").set(null, handler)
field("app").set(null, RuntimeEnvironment.getApplication())
field("model").set(null, VitureProtocol.model(0x1019, null))
field("link").set(null, object : GlassesLink {
override val hasImu = false
override fun send(msgId: Int, payload: ByteArray): Boolean {
if (msgId == VitureProtocol.MSG_DISPLAY) commands.add(payload[0].toInt() and 255)
return true
}
override fun close() {}
})
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = GlassesState(present = true, connected = true, controllable = true,
displayId = 2, width = 1920, height = 1080)
}
@After fun cleanUp() {
handler.removeCallbacksAndMessages(null)
spatialGate.cancel()
field("link").set(null, null)
(field("modeState").get(null) as GlassesModeState).apply { manual(); sent(false, 0) }
SessionState.steamVr = false
restore()
}
@Test fun defaultLaunchAndRunningStatusKeepTheDisplayIn2d() = withLaunch(auto3d = false) { activity ->
status(activity, SteamVr.Status.READY)
status(activity, SteamVr.Status.RUNNING)
status(activity, SteamVr.Status.READY)
assertEquals(emptyList<Int>(), commands)
assertFalse(Glasses.state.value.switching3d)
}
@Test fun optedInLaunchWaitsForRunningAndRestoresOnlyAfterStopping() = withLaunch(auto3d = true) { activity ->
status(activity, SteamVr.Status.READY)
status(activity, SteamVr.Status.READY)
assertEquals("Startup must not change the display mode", emptyList<Int>(), commands)
status(activity, SteamVr.Status.RUNNING)
status(activity, SteamVr.Status.RUNNING)
assertEquals(listOf(0x32), commands)
assertTrue(Glasses.state.value.switching3d)
status(activity, SteamVr.Status.UNAVAILABLE)
assertEquals("A failed status poll is not a stop", listOf(0x32), commands)
status(activity, SteamVr.Status.READY)
assertEquals(listOf(0x32, 0x34), commands)
assertFalse(Glasses.state.value.switching3d)
}
@Test fun ignoredManualSwitchKeepsThePending2dRestore() {
val mode = field("modeState").get(null) as GlassesModeState
mode.startVr()
mode.stopVr()
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = state.value.copy(width = 640, height = 480, noSignal = true)
Glasses.set3d(true)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(emptyList<Int>(), commands)
assertTrue(mode.restorePending)
state.value = state.value.copy(width = 1920, height = 1080, noSignal = false)
Glasses.set3d(false)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(listOf(0x34), commands)
assertFalse(mode.restorePending)
}
@Test fun absentPreferenceDefaultsTo2dAndAnExplicitOptInSurvivesReload() {
val prefs = RuntimeEnvironment.getApplication().getSharedPreferences("glasses", Context.MODE_PRIVATE)
prefs.edit().clear().commit()
fun load() = Glasses::class.java.getDeclaredMethod("load").apply { isAccessible = true }
.invoke(Glasses) as GlassesSettings
assertFalse(load().auto3d)
prefs.edit().putBoolean("auto3d", true).commit()
assertTrue(load().auto3d)
prefs.edit().putBoolean("auto3d", false).commit()
assertFalse(load().auto3d)
}
@Test fun manualStartOnDisplayOnlyGlassesRequestsPollingWithoutDuplicatingLaunch() {
@Suppress("UNCHECKED_CAST")
val state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = GlassesState(present = true, displayId = 2, width = 1920, height = 1080)
withLaunch(auto3d = false) { activity ->
SessionState.steamVr = false
fun action(name: String) = SessionActivity::class.java.getDeclaredMethod("steamVrAction", String::class.java)
.apply { isAccessible = true }.invoke(activity, name)
action("start")
assertTrue("A manual start must keep status polling alive", SessionState.steamVr)
shadowOf(Looper.getMainLooper()).idle()
val worker = SessionActivity::class.java.getDeclaredField("steamVrWorker")
.apply { isAccessible = true }.get(null) as ThreadPoolExecutor
assertEquals(1, worker.queue.size)
status(activity, SteamVr.Status.READY)
assertEquals("Polling must not launch a duplicate instance", 1, worker.queue.size)
status(activity, SteamVr.Status.RUNNING)
status(activity, SteamVr.Status.UNAVAILABLE)
assertTrue(SessionState.steamVr)
action("stop")
assertFalse(SessionState.steamVr)
}
}
@Test fun preparationCallbackRunsAfterSuspensionAndCancelWorksBeforeRunning() {
@Suppress("UNCHECKED_CAST")
val settings = field("_settings").get(null) as MutableStateFlow<GlassesSettings>
settings.value = GlassesSettings(positionalTracking = true, handControllers = true)
val saved = settings.value
var prepared = 0
repeat(2) {
Glasses.prepareSteamVrStart {
assertFalse(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
prepared++
}
}
shadowOf(Looper.getMainLooper()).idle()
assertEquals(2, prepared)
Glasses.setVrActive(false)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(3))
assertFalse(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
Glasses.cancelSteamVrStart()
shadowOf(Looper.getMainLooper()).idle()
assertTrue(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
assertEquals(saved, settings.value)
}
@Test fun rapidRestartDoesNotLaunchTheCancelledPreparedRequest() = withLaunch(auto3d = false) { activity ->
SessionState.steamVr = false
val action = SessionActivity::class.java.getDeclaredMethod("steamVrAction", String::class.java)
.apply { isAccessible = true }
action.invoke(activity, "start")
action.invoke(activity, "stop")
action.invoke(activity, "start")
shadowOf(Looper.getMainLooper()).idle()
val worker = SessionActivity::class.java.getDeclaredField("steamVrWorker")
.apply { isAccessible = true }.get(null) as ThreadPoolExecutor
assertTrue(SessionState.steamVr)
assertEquals("Only stop and the latest start should reach the worker", 2, worker.queue.size)
}
@Test fun duplicateRunningKeepsDeadlineAndStoppingCancelsThePendingResume() {
Glasses.prepareSteamVrStart()
Glasses.setVrActive(true)
shadowOf(Looper.getMainLooper()).idle()
val deadline = spatialGate.deadline!!
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1_999))
var prepared = false
Glasses.prepareSteamVrStart { prepared = true }
Glasses.setVrActive(true)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(prepared)
assertEquals(deadline, spatialGate.deadline)
assertFalse(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1))
assertTrue(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
Glasses.setVrActive(false)
Glasses.prepareSteamVrStart()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(3))
assertFalse(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
assertNull(spatialGate.deadline)
}
@Test fun restartWhileDisplayStillReportsRunningGetsANewTrackingDeadline() {
Glasses.setVrActive(true)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(3))
assertTrue(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
Glasses.cancelSteamVrStart()
Glasses.prepareSteamVrStart()
shadowOf(Looper.getMainLooper()).idle()
assertTrue(Glasses.state.value.vrActive)
assertFalse(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
Glasses.setVrActive(true)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1_999))
assertFalse(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1))
assertTrue(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
}
@Test fun endedSessionIgnoresLateRunningStatus() = withLaunch(auto3d = true) { activity ->
SessionActivity::class.java.getDeclaredField("ended").apply { isAccessible = true }.set(activity, true)
status(activity, SteamVr.Status.RUNNING)
assertFalse(Glasses.state.value.vrActive)
assertNull(spatialGate.deadline)
assertTrue(spatialGate.spatialEnabled(true, SystemClock.uptimeMillis()))
assertTrue(commands.isEmpty())
}
private fun status(activity: SessionActivity, status: SteamVr.Status) {
SessionActivity::class.java.getDeclaredMethod("onSteamVrStatus", SteamVr.Status::class.java)
.apply { isAccessible = true }.invoke(activity, status)
shadowOf(Looper.getMainLooper()).idle()
}
private fun withLaunch(auto3d: Boolean, check: (SessionActivity) -> Unit) {
@Suppress("UNCHECKED_CAST")
val settings = field("_settings").get(null) as MutableStateFlow<GlassesSettings>
settings.value = GlassesSettings(auto3d = auto3d)
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
SessionActivity::class.java.getDeclaredField("loading").apply { isAccessible = true }
.set(activity, LoadingState(activity).apply { visible = false })
SessionState.steamVr = true
SessionState.mode = SessionService.MODE_STEAM
// Hold the external worker so status transitions can be exercised
// without launching a Linux runtime from the host test process.
val worker = SessionActivity::class.java.getDeclaredField("steamVrWorker")
.apply { isAccessible = true }.get(null) as ThreadPoolExecutor
val blocked = CountDownLatch(1)
val release = CountDownLatch(1)
worker.execute { blocked.countDown(); release.await(30, TimeUnit.SECONDS) }
try {
assertTrue(blocked.await(5, TimeUnit.SECONDS))
check(activity)
} finally {
worker.queue.clear()
release.countDown()
}
}
}
@@ -0,0 +1,192 @@
package com.droiddeck.launcher.glasses
import android.app.Application
import android.os.HandlerThread
import android.view.Display
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.SteamVr
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.JoyConVr
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.SessionState
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class, manifest = Config.NONE)
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesTrackingRoutingTest {
private lateinit var activity: SessionActivity
private lateinit var restore: () -> Unit
private val ultra = GlassesState(present = true, connected = true, controllable = true,
supportsSpatial = true, displayId = Display.DEFAULT_DISPLAY + 1, width = 1920, height = 1080)
private val saved = GlassesSettings(positionalTracking = true, handControllers = true)
@Before fun setUp() {
val running = SessionState.running
val steamVr = SessionState.steamVr
val fields = listOf("context", "publisherAttached").associateWith {
SpatialTracking::class.java.getDeclaredField(it).apply { isAccessible = true }
}
val values = fields.mapValues { it.value.get(null) }
fields.getValue("context").set(null, null)
fields.getValue("publisherAttached").set(null, false)
restore = {
fields.forEach { (name, field) -> field.set(null, values[name]) }
SessionState.running = running
SessionState.steamVr = steamVr
}
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
ReflectionHelpers.setField(activity, "loading", LoadingState(activity).apply { visible = false })
ReflectionHelpers.setField(activity, "started", true)
ReflectionHelpers.setField(activity, "activeCardboard", Cardboard.OFF)
state("glasses", ultra)
state("glassesSettings", saved)
state("steamVrStatus", SteamVr.Status.RUNNING)
SessionState.running = true
SessionState.steamVr = true
SpatialTracking.setOutputUsesGlasses(true)
SpatialTracking.connect(0, 81, null, true, 1.6f, true)
}
@After fun tearDown() {
SpatialTracking.useLegacyTracking()
SpatialTracking.disconnect()
SpatialTracking.setOutputUsesGlasses(true)
restore()
}
@Test fun usbLossKeepsSpatialOwnershipAndShowsRecoveryOnTheGlassesDisplay() {
SpatialTracking.disconnect()
state("glasses", ultra.copy(connected = false, supportsSpatial = false))
updateRouting()
assertEquals(3, modes())
assertTrue(SpatialTracking.selected)
assertEquals(TrackingRecovery.DISCONNECTED, recovery())
}
@Test fun phoneHandoffClearsPublishedModesWithoutErasingTheGlassesSelection() {
for (joyCons in listOf(false, true)) {
val selected = saved.copy(handControllers = !joyCons, joyConTracking = joyCons)
state("glassesSettings", selected)
SpatialTracking.connect(0, if (joyCons) 83 else 82, null, true, 1.6f, !joyCons, joyCons)
SpatialTracking.disconnect()
state("glasses", GlassesState())
updateRouting()
assertEquals(0, modes())
assertTrue(SpatialTracking.selected)
assertEquals(selected, stateValue<GlassesSettings>("glassesSettings"))
assertNull(recovery())
SpatialTracking.setControllers(!joyCons, joyCons)
assertEquals("Later controller updates must not reclaim the phone output", 0, modes())
SpatialTracking.connect(0, if (joyCons) 85 else 84, null, true, 1.6f, !joyCons, joyCons)
assertEquals("Reconnecting waits for the output handoff", 0, modes())
state("glasses", ultra)
updateRouting()
assertEquals(if (joyCons) 5 else 3, modes())
}
}
@Test fun endingTheSessionReleasesSpatialInputEvenWhileTheGlassesRemainConnected() {
ReflectionHelpers.setField(activity, "ended", true)
updateRouting()
assertEquals(0, modes())
assertTrue(SpatialTracking.selected)
assertEquals(saved, stateValue<GlassesSettings>("glassesSettings"))
assertNull(recovery())
}
@Test @Config(sdk = [31]) fun displayLossReleasesSpatialControllerOverridesWhileUsbRemainsConnected() {
val previousJoyConVr = ControllerPrefs.joyConVr(activity)
ControllerPrefs.setJoyConVr(activity, false)
val joyCon = JoyConVr(activity, File(activity.cacheDir, "routing-joycons")) { _, _ -> }
ReflectionHelpers.setField(activity, "joyConVr", joyCon)
val worker = ReflectionHelpers.getField<HandlerThread>(joyCon, "thread")
fun updateInputs(): Boolean {
ReflectionHelpers.callInstanceMethod<Void>(activity, "updateJoyConTracking")
shadowOf(worker.looper).idle()
return ReflectionHelpers.getField(joyCon, "wanted")
}
try {
for (joyCons in listOf(false, true)) {
val selected = saved.copy(handControllers = !joyCons, joyConTracking = joyCons)
state("glassesSettings", selected)
for (displayLost in listOf(ultra.copy(noSignal = true), ultra.copy(displayId = Display.INVALID_DISPLAY))) {
state("glasses", ultra)
assertTrue(ReflectionHelpers.callInstanceMethod(activity, "usesSpatialControllers"))
assertEquals(joyCons, updateInputs())
state("glasses", displayLost)
updateRouting()
assertTrue(displayLost.spatialConnected)
assertEquals(0, modes())
assertFalse("The phone camera must not be suppressed by a missing display",
ReflectionHelpers.callInstanceMethod(activity, "usesSpatialControllers"))
assertFalse("Saved glasses Joy-Cons must not override the phone preference", updateInputs())
assertEquals(selected, stateValue<GlassesSettings>("glassesSettings"))
ControllerPrefs.setJoyConVr(activity, true)
assertTrue("The phone Joy-Con preference must still apply", updateInputs())
ControllerPrefs.setJoyConVr(activity, false)
state("glasses", ultra)
updateRouting()
assertTrue(ReflectionHelpers.callInstanceMethod(activity, "usesSpatialControllers"))
assertEquals(joyCons, updateInputs())
}
}
} finally {
ReflectionHelpers.setField(activity, "joyConVr", null)
joyCon.close()
ControllerPrefs.setJoyConVr(activity, previousJoyConVr)
}
}
@Test fun anotherGlassesModelDoesNotActivateSavedUltraTracking() {
SpatialTracking.disconnect()
SpatialTracking.useLegacyTracking()
state("glasses", ultra.copy(model = "XREAL", supportsSpatial = false))
updateRouting()
assertEquals(0, modes())
assertFalse(SpatialTracking.selected)
assertEquals(saved, stateValue<GlassesSettings>("glassesSettings"))
assertNull(recovery())
}
private fun updateRouting() {
ReflectionHelpers.callInstanceMethod<Void>(activity, "updateHeadTracker")
ReflectionHelpers.callInstanceMethod<Void>(activity, "updateTrackingRecovery")
}
private fun modes(): Int {
val field = SpatialTracking::class.java.getDeclaredField("buffer").apply { isAccessible = true }
return (field.get(null) as ByteBuffer).duplicate().order(ByteOrder.LITTLE_ENDIAN).getInt(32)
}
private fun recovery(): TrackingRecovery? = stateValue("trackingRecovery")
private fun <T> state(name: String, value: T) {
ReflectionHelpers.getField<MutableState<T>>(activity, name + "\$delegate").value = value
}
private fun <T> stateValue(name: String): T =
ReflectionHelpers.getField<MutableState<T>>(activity, name + "\$delegate").value
}
@@ -0,0 +1,236 @@
package com.droiddeck.launcher.glasses
import android.app.PendingIntent
import android.content.Context
import android.hardware.display.DisplayManager
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.Display
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.annotation.LooperMode
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowDisplayManager
import org.robolectric.shadows.ShadowSystemClock
import org.robolectric.shadows.ShadowUsbManager
import org.robolectric.util.ReflectionHelpers
import org.robolectric.util.ReflectionHelpers.ClassParameter.from
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, shadows = [GlassesUsbTest.RecordingUsbManager::class])
@LooperMode(LooperMode.Mode.PAUSED)
class GlassesUsbTest {
private lateinit var manager: RecordingUsbManager
private lateinit var state: MutableStateFlow<GlassesState>
private fun field(name: String) = Glasses::class.java.getDeclaredField(name).apply { isAccessible = true }
@Before fun prepare() {
val context = RuntimeEnvironment.getApplication()
val usb = context.getSystemService(Context.USB_SERVICE) as UsbManager
manager = Shadow.extract(usb)
field("app").set(null, context)
field("usb").set(null, usb)
field("displays").set(null, context.getSystemService(Context.DISPLAY_SERVICE))
field("handler").set(null, Handler(Looper.getMainLooper()))
field("asked").setBoolean(null, false)
@Suppress("UNCHECKED_CAST")
state = field("_state").get(null) as MutableStateFlow<GlassesState>
state.value = GlassesState()
}
@Test fun controllableGlassesTakePriorityOverDockAndUnsupportedGlasses() {
val dock = device(0x3011)
val beast = device(0x1201)
val pro = device(0x101d)
manager.devices.putAll(listOf(dock, beast, pro).associateBy { it.deviceName })
refresh()
assertEquals(listOf(pro), manager.requests)
assertTrue(state.value.controllable)
assertEquals(Glasses.Permission.ASKING, state.value.permission)
}
@Test fun unsupportedDevicesNeverRequestOrAdvertiseUsbPermission() {
for (pid in listOf(0x3011, 0xffff, 0x1201)) {
val device = device(pid)
manager.devices.clear()
manager.devices[device.deviceName] = device
state.value = GlassesState()
refresh(ask = true)
assertTrue(manager.requests.isEmpty())
assertEquals(Glasses.Permission.NONE, state.value.permission)
manager.granted.add(device.deviceName)
state.value = GlassesState(permission = Glasses.Permission.ASKING)
refresh(ask = true)
assertTrue(manager.requests.isEmpty())
assertEquals(Glasses.Permission.NONE, state.value.permission)
assertEquals(pid == 0x1201, state.value.present)
assertFalse(state.value.controllable)
assertFalse(state.value.connected)
}
}
@Test fun dockPresenceStillIdentifiesAnUnnamedPresentationDisplay() {
val hdmi = ReflectionHelpers.getStaticField<Int>(Display::class.java, "TYPE_HDMI")
val displayId = ShadowDisplayManager.addDisplay("w1920dp-h1080dp", hdmi)
val displays = RuntimeEnvironment.getApplication().getSystemService(DisplayManager::class.java)
val display = displays.getDisplay(displayId)
shadowOf(display).setFlags(Display.FLAG_PRESENTATION)
assertEquals(displayId, displays.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).single().displayId)
assertFalse(display.name.contains("VITURE", ignoreCase = true))
val dock = device(0x3011)
manager.devices[dock.deviceName] = dock
refresh()
assertEquals(displayId, state.value.displayId)
assertTrue(manager.requests.isEmpty())
assertEquals(Glasses.Permission.NONE, state.value.permission)
}
@Test fun noSignalStereoFailureIsRememberedPerModel() {
val prefs = RuntimeEnvironment.getApplication().getSharedPreferences("glasses", Context.MODE_PRIVATE)
prefs.edit().clear().commit()
val hdmi = ReflectionHelpers.getStaticField<Int>(Display::class.java, "TYPE_HDMI")
val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", hdmi)
val displays = RuntimeEnvironment.getApplication().getSystemService(DisplayManager::class.java)
shadowOf(displays.getDisplay(displayId)).setFlags(Display.FLAG_PRESENTATION)
val pro = device(0x1019)
manager.devices[pro.deviceName] = pro
refresh()
assertTrue(state.value.noSignal)
(field("modeState").get(null) as GlassesModeState).sent(true, SystemClock.uptimeMillis())
ShadowSystemClock.advanceBy(Duration.ofSeconds(21))
refresh()
assertEquals(GlassesState.SBS_FAILS, state.value.sbsSupport)
assertEquals(setOf("1019"), prefs.getStringSet("sbsFailed", null))
ShadowDisplayManager.removeDisplay(displayId)
val xr = device(0x101d)
manager.devices.clear()
manager.devices[xr.deviceName] = xr
refresh()
assertEquals(GlassesState.SBS_UNKNOWN, state.value.sbsSupport)
manager.devices.clear()
manager.devices[pro.deviceName] = pro
refresh()
assertEquals(GlassesState.SBS_FAILS, state.value.sbsSupport)
assertFalse(state.value.can3d)
}
@Test fun rayNeoRequestsPermissionWithoutClaimingUnrelatedTclDevices() {
val air = device(0xaf50, 0x1bbb, "RayNeo Air 4 Pro")
manager.devices[air.deviceName] = air
refresh(ask = true)
assertEquals("RayNeo Air 4 Pro", state.value.model)
assertTrue(state.value.controllable)
assertFalse(state.value.hardwareControls)
assertEquals(listOf(air), manager.requests)
manager.devices.clear()
manager.devices["phone"] = device(0x1234, 0x1bbb, "TCL Phone")
manager.requests.clear()
refresh(ask = true)
assertFalse(state.value.present)
assertTrue(manager.requests.isEmpty())
}
@Test fun alternateBridgeRequiresRayNeoModelIdentity() {
val gt = device(0x1234, 0x22d9, "RayNeo GT")
manager.devices[gt.deviceName] = gt
refresh(ask = true)
assertEquals("RayNeo GT", state.value.model)
assertEquals(listOf(gt), manager.requests)
}
@Test fun gtVendorRequestsPermissionAndRetainsMaxProductName() {
val gt = device(0xaf50, 0x3941, "RayNeo GT MAX")
manager.devices[gt.deviceName] = gt
refresh(ask = true)
assertEquals("RayNeo GT MAX", state.value.model)
assertTrue(state.value.controllable)
assertFalse(state.value.hardwareControls)
assertEquals(listOf(gt), manager.requests)
}
@Test fun screen3dofAvailabilityFollowsTheTrackingTransportAcrossBrands() {
val devices = listOf(device(0x1011), device(0x1019), device(0x1131),
device(0xaf50, 0x1bbb, "RayNeo Air 4 Pro"),
device(0xaf50, 0x3941, "RayNeo GT MAX"),
device(0x043e, 0x3318, "XREAL 1S"))
try {
for (device in devices) for (imu in listOf(false, true)) {
manager.devices.clear()
manager.devices[device.deviceName] = device
manager.granted.add(device.deviceName)
field("linkDevice").set(null, device)
field("link").set(null, object : GlassesLink {
override val hasImu = imu
override fun send(msgId: Int, payload: ByteArray) = true
override fun close() {}
})
refresh()
assertTrue(state.value.canControl)
assertEquals(imu, state.value.supportsScreen3dof)
}
manager.devices.clear()
refresh()
assertFalse(state.value.supportsScreen3dof)
} finally {
field("link").set(null, null)
field("linkDevice").set(null, null)
(field("handler").get(null) as Handler).removeCallbacksAndMessages(null)
}
}
private fun refresh(ask: Boolean = false) {
Glasses::class.java.getDeclaredMethod("refresh", Boolean::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, ask)
}
@Test fun xreal1SUsesExactIdentityAndExcludesAirOneProAndRecoveryProducts() {
assertEquals(XrealModel, Glasses.deviceModel(device(0x043e, 0x3318, "XREAL 1S")))
assertTrue(Glasses.isGlassesDisplayName("XREAL 1S"))
for (pid in listOf(0x043d, 0x0435, 0x0436, 0x0424, 0xffff)) {
assertEquals(null, Glasses.deviceModel(device(pid, 0x3318, "XREAL 1S")))
}
assertEquals(null, Glasses.deviceModel(device(0x043e, 0x1234, "XREAL 1S")))
}
private fun device(pid: Int, vid: Int = VitureProtocol.VENDOR_ID, name: String = "VITURE device"): UsbDevice = ReflectionHelpers.callConstructor(
UsbDevice::class.java,
from(String::class.java, "/dev/bus/usb/$pid"),
from(Int::class.javaPrimitiveType, vid),
from(Int::class.javaPrimitiveType, pid),
from(Int::class.javaPrimitiveType, 0),
from(Int::class.javaPrimitiveType, 0),
from(Int::class.javaPrimitiveType, 0),
from(String::class.java, "VITURE"),
from(String::class.java, name),
from(String::class.java, "1.0"),
from(String::class.java, "test-$pid"),
)
@Implements(UsbManager::class)
class RecordingUsbManager : ShadowUsbManager() {
val devices = linkedMapOf<String, UsbDevice>()
val granted = mutableSetOf<String>()
val requests = mutableListOf<UsbDevice>()
@Implementation override fun getDeviceList(): HashMap<String, UsbDevice> = LinkedHashMap(devices)
@Implementation override fun hasPermission(device: UsbDevice): Boolean = device.deviceName in granted
@Implementation fun requestPermission(device: UsbDevice, intent: PendingIntent) { requests += device }
}
}
@@ -0,0 +1,192 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class HandGesturesTest {
private fun openHand(): MutableList<SpatialVector> {
val p=MutableList(21) { SpatialVector(z=.5f) }
p[0]=SpatialVector(0f,0f,.5f)
p[4]=SpatialVector(.07f,-.05f,.5f)
for((base,x) in listOf(5 to .035f,9 to .01f,13 to -.015f,17 to -.04f)) {
for(j in 0..3)p[base+j]=SpatialVector(x,-.06f-.025f*j,.5f)
}
return p
}
@Test fun triangulatedMetersAreTransformedIntoTheHeadWorldFrame() {
val h=HandGestures(rightHand=false).estimate(openHand(),SpatialPose(SpatialVector(1f,2f,3f)),1_000_000_000)!!
assertEquals(3.5f,h.pose.position.z,.0001f)
assertTrue(h.pose.rotation.normalized()!=null);assertFalse(h.grip);assertEquals(0f,h.trigger,.0001f)
}
@Test fun mirroredHandsUseTheSamePalmNormalAndFingerDirection() {
val left=openHand().apply { this[9]=SpatialVector(0f,-.06f,.5f) }
val right=left.map { SpatialVector(-it.x,it.y,it.z) }
val world=SpatialPose(SpatialVector(1f,2f,3f),SpatialRotation(.2f,-.3f,.1f,.9f).normalized()!!)
for(turn in listOf(SpatialRotation(),SpatialRotation(y=1f,w=0f),
SpatialRotation(.3f,.1f,-.2f,.9f).normalized()!!)) {
val hands=listOf(left,right).mapIndexed { side,points ->
HandGestures(rightHand=side==1).estimate(points.map(turn::apply),world,1_000_000_000)!!
}
for(hand in hands) {
val rotation=hand.pose.rotation
assertVector(world.rotation.apply(turn.apply(SpatialVector(z=-1f))),rotation.apply(SpatialVector(y=1f)))
assertVector(world.rotation.apply(turn.apply(SpatialVector(y=-1f))),rotation.apply(SpatialVector(z=-1f)))
val x=rotation.apply(SpatialVector(x=1f));val y=rotation.apply(SpatialVector(y=1f))
assertVector(rotation.apply(SpatialVector(z=1f)),x.cross(y))
}
}
}
@Test fun rightHandOrientationDoesNotChangePinchOrGrip() {
val points=openHand()
points[4]=points[8]
for((tip,base) in listOf(12 to 9,16 to 13,20 to 17)) points[tip]=points[base]
val left=HandGestures(rightHand=false).estimate(points,SpatialPose(),1_000_000_000)!!
val right=HandGestures(rightHand=true).estimate(points.map { SpatialVector(-it.x,it.y,it.z) },SpatialPose(),1_000_000_000)!!
assertEquals(left.flags(),right.flags());assertEquals(1f,right.trigger,0f);assertTrue(right.grip)
assertEquals(left.timeNs,right.timeNs)
assertVector(SpatialVector(-left.pose.position.x,left.pose.position.y,left.pose.position.z),right.pose.position)
}
private fun assertVector(expected: SpatialVector,actual: SpatialVector) {
assertEquals(expected.x,actual.x,.0001f);assertEquals(expected.y,actual.y,.0001f);assertEquals(expected.z,actual.z,.0001f)
}
@Test fun pinchAndFingerClosureProduceTriggerAndGrip() {
val detector=HandGestures(rightHand=false);val p=openHand()
detector.estimate(p,SpatialPose(),1_000_000_000)
p[4]=p[8]
for((tip,base) in listOf(12 to 9,16 to 13,20 to 17)) p[tip]=p[base]
val pressed=detector.estimate(p,SpatialPose(),1_040_000_000)!!
assertEquals(1f,pressed.trigger,.0001f);assertTrue(pressed.grip)
val released=detector.estimate(openHand(),SpatialPose(),1_080_000_000)!!
assertEquals(0f,released.trigger,.0001f);assertFalse(released.grip)
}
@Test fun invalidGeometryAndImplausibleTemporalJumpAreRejected() {
val detector=HandGestures(rightHand=false)
assertNull(detector.estimate(emptyList(),SpatialPose(),1))
assertEquals(HandObservationOutcome.LANDMARK_COUNT_INVALID,detector.lastOutcome)
assertNull(detector.estimate(List(21) { SpatialVector() },SpatialPose(),1))
assertEquals(HandObservationOutcome.PALM_WIDTH_INVALID,detector.lastOutcome)
detector.estimate(openHand(),SpatialPose(),1_000_000_000)
assertNull(detector.estimate(openHand(),SpatialPose(SpatialVector(2f,0f,0f)),1_040_000_000))
assertEquals(HandObservationOutcome.PALM_MOTION_REJECTED,detector.lastOutcome)
detector.reset()
assertNotNull(detector.estimate(openHand(),SpatialPose(SpatialVector(2f,0f,0f)),1_080_000_000))
assertEquals(HandObservationOutcome.ACCEPTED,detector.lastOutcome)
}
@Test fun anUnreliableUnusedJointDoesNotHideThePalmOrDisableGestures() {
val points=openHand().map { it as SpatialVector? }.toMutableList()
points[6]=null
val hand=HandGestures(rightHand=false).estimate(points,SpatialPose(),1_000_000_000)!!
assertTrue(hand.valid);assertTrue(hand.triggerValid);assertTrue(hand.gripValid)
assertEquals(7,hand.flags())
}
@Test fun repeatedMotionRejectionsPreserveTheLastPoseAndGripHysteresis() {
val detector=HandGestures(false)
val closed=openHand().apply {
for((tip,base) in listOf(12 to 9,16 to 13,20 to 17)) this[tip]=this[base]
}
assertTrue(detector.estimate(closed,SpatialPose(),1_000_000_000)!!.grip)
for(time in listOf(1_040_000_000L,1_080_000_000L,1_120_000_000L)) {
assertNull(detector.estimate(openHand(),SpatialPose(SpatialVector(2f,0f,0f)),time))
assertEquals(HandObservationOutcome.PALM_MOTION_REJECTED,detector.lastOutcome)
detector.resetAfterRejection(detector.lastOutcome)
}
val partlyClosed=openHand().apply { this[12]=this[9];this[16]=this[13] }
val recovered=detector.estimate(partlyClosed,SpatialPose(),1_160_000_000)!!
assertTrue(recovered.grip)
assertEquals(1_160_000_000L,recovered.timeNs)
}
@Test fun motionRejectionDoesNotPreventReacquisitionAfterTheMotionWindow() {
val detector=HandGestures(false)
detector.estimate(openHand(),SpatialPose(),1_000_000_000)
val moved=SpatialPose(SpatialVector(2f,0f,0f))
for(time in listOf(1_040_000_000L,1_160_000_000L)) {
assertNull(detector.estimate(openHand(),moved,time))
detector.resetAfterRejection(detector.lastOutcome)
}
val reacquired=detector.estimate(openHand(),moved,1_200_000_000)!!
assertEquals(HandObservationOutcome.ACCEPTED,detector.lastOutcome)
assertEquals(1_200_000_000L,reacquired.timeNs)
}
@Test fun actualDetectionLossClearsMotionHistoryAndGripEvenAfterAMotionRejection() {
val detector=HandGestures(false)
val closed=openHand().apply {
for((tip,base) in listOf(12 to 9,16 to 13,20 to 17)) this[tip]=this[base]
}
assertTrue(detector.estimate(closed,SpatialPose(),1_000_000_000)!!.grip)
val moved=SpatialPose(SpatialVector(2f,0f,0f))
assertNull(detector.estimate(closed,moved,1_040_000_000))
detector.resetAfterRejection(detector.lastOutcome)
detector.resetAfterRejection(HandObservationOutcome.NO_MATCHING_DETECTION)
val partlyClosed=openHand().apply { this[12]=this[9];this[16]=this[13] }
val reacquired=detector.estimate(partlyClosed,moved,1_080_000_000)!!
assertFalse(reacquired.grip)
}
@Test fun occludedPinchKeepsThePalmAndIndependentGrip() {
val detector=HandGestures(rightHand=false)
val points=openHand().map { it as SpatialVector? }.toMutableList()
points[4]=points[8]
for((tip,base) in listOf(12 to 9,16 to 13,20 to 17)) points[tip]=points[base]
assertEquals(1f,detector.estimate(points,SpatialPose(),1_000_000_000)!!.trigger,0f)
points[4]=null
val hand=detector.estimate(points,SpatialPose(),1_080_000_000)!!
assertTrue(hand.valid);assertFalse(hand.triggerValid);assertEquals(0f,hand.trigger,0f)
assertTrue(hand.gripValid);assertTrue(hand.grip);assertEquals(5,hand.flags())
}
@Test fun occludedGripKeepsThePalmAndIndependentPinch() {
val points=openHand().map { it as SpatialVector? }.toMutableList()
points[4]=points[8];points[16]=SpatialVector(Float.NaN,0f,.5f)
val hand=HandGestures(rightHand=false).estimate(points,SpatialPose(),1_000_000_000)!!
assertTrue(hand.valid);assertTrue(hand.triggerValid);assertEquals(1f,hand.trigger,0f)
assertFalse(hand.gripValid);assertFalse(hand.grip);assertEquals(3,hand.flags())
}
@Test fun missingPalmStillRejectsTheController() {
for(index in listOf(0,5,9,13,17)) {
val points=openHand().map { it as SpatialVector? }.toMutableList();points[index]=null
val detector=HandGestures(rightHand=false)
assertNull(detector.estimate(points,SpatialPose(),1_000_000_000))
assertEquals(HandObservationOutcome.PALM_LANDMARK_MISSING,detector.lastOutcome)
assertNotNull(detector.estimate(openHand(),SpatialPose(),1_040_000_000))
assertEquals(HandObservationOutcome.ACCEPTED,detector.lastOutcome)
}
assertEquals(0,SpatialHand(triggerValid=true,gripValid=true).flags())
}
@Test fun degeneratePalmAxesAreDistinguishedFromMissingStereoLandmarks() {
val detector=HandGestures(rightHand=false)
for(middle in listOf(SpatialVector(0f,0f,.5f),SpatialVector(.04f,0f,.5f))) {
val points=openHand().apply { this[9]=middle }
assertNull(detector.estimate(points,SpatialPose(),1_000_000_000))
assertEquals(HandObservationOutcome.PALM_BASIS_INVALID,detector.lastOutcome)
}
assertNotNull(detector.estimate(openHand(),SpatialPose(),1_040_000_000))
assertEquals(HandObservationOutcome.ACCEPTED,detector.lastOutcome)
}
@Test fun agreeingImageCurlsAndPinchSurviveMissingTriangulatedFingertips() {
val image=openHand().apply {
this[4]=this[8]
for((tip,base) in listOf(12 to 9,16 to 13,20 to 17)) this[tip]=this[base]
}.map { SpatialVector(320f+it.x*1000f,240f+it.y*1000f) }
val points=openHand().map { it as SpatialVector? }.toMutableList()
for(index in listOf(4,8,12,16,20)) points[index]=null
val hand=HandGestures(false).estimate(points,SpatialPose(),1_000_000_000,image,image)!!
assertTrue(hand.valid);assertTrue(hand.gripValid);assertTrue(hand.grip)
assertTrue(hand.triggerValid);assertEquals(1f,hand.trigger,0f)
assertVector(HandGestures(false).estimate(openHand(),SpatialPose(),1_000_000_000)!!.pose.position,hand.pose.position)
}
@Test fun imageDisagreementInvalidatesGestureInsteadOfFallingBackToPressedDepth() {
val closed=openHand().apply {
this[4]=this[8]
for((tip,base) in listOf(12 to 9,16 to 13,20 to 17)) this[tip]=this[base]
}
fun image(points: List<SpatialVector>)=points.map { SpatialVector(it.x*1000f,it.y*1000f) }
val detector=HandGestures(false)
assertTrue(detector.estimate(closed,SpatialPose(),1_000_000_000,image(closed),image(closed))!!.grip)
val conflict=detector.estimate(closed,SpatialPose(),1_080_000_000,image(closed),image(openHand()))!!
assertTrue(conflict.valid);assertFalse(conflict.triggerValid);assertFalse(conflict.gripValid)
assertFalse(conflict.grip);assertEquals(0f,conflict.trigger,0f)
val missingView=detector.estimate(closed,SpatialPose(),1_120_000_000,image(closed),null)!!
assertTrue(missingView.valid);assertFalse(missingView.triggerValid);assertFalse(missingView.gripValid)
val released=detector.estimate(closed,SpatialPose(),1_160_000_000,image(openHand()),image(openHand()))!!
assertTrue(released.triggerValid);assertTrue(released.gripValid)
assertFalse(released.grip);assertEquals(0f,released.trigger,0f)
}
}
@@ -0,0 +1,90 @@
package com.droiddeck.launcher.glasses
import android.graphics.Bitmap
import android.graphics.Color
import com.google.mediapipe.framework.image.ByteBufferExtractor
import com.google.mediapipe.framework.image.MPImage
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk=[28],manifest=Config.NONE)
class HandImageBufferTest {
private fun bitmap(vararg values: Int) = Bitmap.createBitmap(values.size, 1, Bitmap.Config.ARGB_8888).apply {
setPixels(values.map { Color.rgb(it, it, it) }.toIntArray(), 0, values.size, 0, 0, values.size, 1)
}
private fun values(buffer: HandImageBuffer, bitmap: Bitmap): List<Int> = values(buffer.image(bitmap))
private fun values(image: MPImage): List<Int> = image.use {
assertEquals(MPImage.IMAGE_FORMAT_RGB, image.containedImageProperties.single().imageFormat)
val pixels = ByteBufferExtractor.extract(image)
assertTrue(pixels.isDirect)
assertEquals(image.width * image.height * 3, pixels.remaining())
List(image.width * image.height) {
val red = pixels.get().toInt() and 255
assertEquals(red, pixels.get().toInt() and 255)
assertEquals(red, pixels.get().toInt() and 255)
red
}
}
@Test fun liveDefaultUsesFullModelAndPreservesCameraPixelCoordinatesAndExposure() {
assertEquals(HandModel.FULL, HandModel.DEFAULT)
val input = byteArrayOf(32, 64, 96, 128.toByte(), 160.toByte(), 192.toByte())
val original = input.copyOf()
val image = HandImageBuffer().image(input, 3, 2)
assertEquals(3, image.width); assertEquals(2, image.height)
assertEquals(listOf(32, 64, 96, 128, 160, 192), values(image))
assertArrayEquals(original, input)
}
@Test fun directCameraAndRawBitmapInputsMatchAcrossEveryGrayValueAndFrameSize() {
val buffer = HandImageBuffer()
for ((width, height) in listOf(16 to 16, 3 to 2, 2 to 3, 1 to 1)) {
val input = ByteArray(width * height) { ((it * 73 + 32) and 255).toByte() }
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply {
setPixels(input.map { (it.toInt() and 255).let { value -> Color.rgb(value, value, value) } }.toIntArray(),
0, width, 0, 0, width, height)
}
try {
val expected = input.map { it.toInt() and 255 }
assertEquals(expected, values(buffer.image(input, width, height)))
assertEquals(expected, values(buffer.image(bitmap)))
} finally { bitmap.recycle() }
}
}
@Test(expected = IllegalArgumentException::class)
fun cameraDimensionsMustMatchTheGrayscaleFrame() {
HandImageBuffer().image(ByteArray(5), 3, 2)
}
@Test fun resizedAndSuccessiveFramesDoNotRetainOldPixelsOrExposure() {
val buffer = HandImageBuffer()
for (input in listOf(intArrayOf(32, 96, 160), intArrayOf(64, 128, 192), intArrayOf(0, 255))) {
val bitmap = bitmap(*input)
try {
assertEquals(input.toList(), values(buffer, bitmap))
} finally { bitmap.recycle() }
}
}
@Test fun closingInferenceImagesDoesNotRecycleReusableCameraBitmap() {
val bitmap=Bitmap.createBitmap(2,2,Bitmap.Config.ARGB_8888)
val buffer=HandImageBuffer()
repeat(3) { frame ->
bitmap.eraseColor(if(frame%2==0) Color.WHITE else Color.BLACK)
buffer.image(bitmap).use { image ->
assertEquals(2,image.width);assertEquals(2,image.height)
val pixels=ByteBufferExtractor.extract(image)
assertEquals(if(frame%2==0) 255 else 0,pixels.get(0).toInt() and 255)
}
assertFalse(bitmap.isRecycled)
}
bitmap.recycle()
}
}
@@ -0,0 +1,128 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class HandInferenceScheduleTest {
private fun frame(schedule: HandInferenceSchedule, time: Long, left: List<Int> = listOf(0),
right: List<Int> = left, rawLeft: Int = left.size, rawRight: Int = right.size): Int {
val maximum = schedule.select(time)
schedule.observe(time, left, right, rawLeft, rawRight)
return maximum
}
private fun stable(schedule: HandInferenceSchedule, side: Int = 0) {
for (time in listOf(0L, 80L, 160L)) assertEquals(2, frame(schedule, time, listOf(side)))
}
@Test fun requiresThreeStereoConsistentFramesBeforeSingleHandTracking() {
val schedule = HandInferenceSchedule()
stable(schedule)
assertEquals(1, frame(schedule, 240))
assertEquals(1, frame(schedule, 320))
assertEquals(2, frame(schedule, 400))
assertEquals(1, frame(schedule, 480))
}
@Test fun discoversSecondHandAtBothCameraInputCadences() {
for (cadence in listOf(40L, 80L)) {
val schedule = HandInferenceSchedule()
val searches = ArrayList<Long>()
for (time in 0L..1200L step cadence) {
if (frame(schedule, time) == 2) searches.add(time)
}
assertTrue(searches.size >= 5)
assertTrue(searches.zipWithNext().all { (first, second) -> second - first <= 240 })
}
}
@Test fun delayedFrameStillSearchesAtFirstFrameAfterDiscoveryDeadline() {
val schedule = HandInferenceSchedule()
stable(schedule)
assertEquals(1, frame(schedule, 240))
assertEquals(1, frame(schedule, 399))
assertEquals(2, frame(schedule, 479))
assertEquals(1, frame(schedule, 559))
}
@Test fun secondHandDiscoveredBySearchKeepsBothHandDetectorsSelected() {
val schedule = HandInferenceSchedule()
stable(schedule)
assertEquals(1, frame(schedule, 240))
assertEquals(2, frame(schedule, 400, listOf(0, 1)))
for (time in listOf(480L, 560L, 640L)) assertEquals(2, frame(schedule, time, listOf(1, 0)))
for (time in listOf(720L, 800L, 880L)) assertEquals(2, frame(schedule, time))
assertEquals(1, frame(schedule, 960))
}
@Test fun anyCameraLossImmediatelyReturnsToFullSearch() {
for ((left, right) in listOf(emptyList<Int>() to listOf(0), listOf(0) to emptyList())) {
val schedule = HandInferenceSchedule()
stable(schedule)
assertEquals(1, frame(schedule, 240, left, right))
assertEquals(2, frame(schedule, 320))
}
}
@Test fun ambiguousOrFilteredDetectionsNeverMaintainSingleHandMode() {
val invalid = listOf(
listOf(0) to listOf(1),
listOf(0, 0) to listOf(0),
listOf(0) to listOf(0, 0),
listOf(-1) to listOf(-1),
listOf(2) to listOf(2)
)
for ((left, right) in invalid) {
val schedule = HandInferenceSchedule()
stable(schedule)
frame(schedule, 240, left, right)
assertEquals(2, frame(schedule, 320))
}
for ((rawLeft, rawRight) in listOf(2 to 1, 1 to 2, 0 to 1, -1 to 1)) {
val schedule = HandInferenceSchedule()
stable(schedule)
frame(schedule, 240, rawLeft = rawLeft, rawRight = rawRight)
assertEquals(2, frame(schedule, 320))
}
}
@Test fun changingSidesRequiresFreshFullSearchStability() {
val schedule = HandInferenceSchedule()
stable(schedule)
assertEquals(1, frame(schedule, 240, listOf(1)))
for (time in listOf(320L, 400L, 480L)) assertEquals(2, frame(schedule, time, listOf(1)))
assertEquals(1, frame(schedule, 560, listOf(1)))
}
@Test fun inconsistentInitialSidesCannotAccumulateStability() {
val schedule = HandInferenceSchedule()
for (index in 0..8) assertEquals(2, frame(schedule, index * 80L, listOf(index % 2)))
}
@Test fun resetDropsSessionState() {
val schedule = HandInferenceSchedule()
stable(schedule)
frame(schedule, 240)
schedule.reset()
stable(schedule, 1)
assertEquals(1, frame(schedule, 240, listOf(1)))
}
@Test fun longGapAndNonmonotonicTimeRequireFreshStability() {
for (time in listOf(160L, 120L, 561L, -1L)) {
val schedule = HandInferenceSchedule()
stable(schedule)
assertEquals(2, frame(schedule, time))
assertEquals(2, frame(schedule, maxOf(0, time) + 80))
}
}
@Test fun unobservedInferenceAndMismatchedObservationResetSchedule() {
val schedule = HandInferenceSchedule()
stable(schedule)
assertEquals(1, schedule.select(240))
assertEquals(2, frame(schedule, 320))
schedule.observe(240, listOf(0), listOf(0))
assertEquals(2, frame(schedule, 400))
}
}
@@ -0,0 +1,65 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class HandObservationTest {
private val time=1_000_000_000L
private fun session()=SpatialSession().apply {
reset(7,1.6f)
accept(SpatialSample(SpatialPose(),time,7,true))
}
private fun advance(session: SpatialSession, ms: Long, valid: Boolean=true, x: Float=.1f) {
session.accept(SpatialSample(SpatialPose(SpatialVector(x=x)),time+ms*1_000_000,7,valid))
}
@Test fun lateCameraConfirmationUsesTheCapturePoseInsteadOfTheLatestPose() {
val session=session()
val observation=HandObservation(time,7,session.trackingFrameGeneration)
assertNull(observation.headPose(session,false,time))
advance(session,150)
assertEquals(SpatialPose(),observation.headPose(session,true,time+150_000_000))
assertEquals(time,observation.timeNs)
}
@Test fun missingConfirmationOrExpiredObservationCannotPublish() {
val session=session()
val observation=HandObservation(time,7,session.trackingFrameGeneration)
advance(session,180)
assertNull(observation.headPose(session,false,time+180_000_000))
assertNotNull(observation.headPose(session,true,time+200_000_000))
assertNull(observation.headPose(session,true,time+200_000_001))
assertNull(observation.headPose(session,true,time-1))
}
@Test fun longerHandWindowDoesNotExtendHeadFreshness() {
val session=session()
val observation=HandObservation(time,7,session.trackingFrameGeneration)
assertNotNull(observation.headPose(session,true,time+100_000_000))
assertNull(observation.headPose(session,true,time+100_000_001))
advance(session,150)
assertNotNull(observation.headPose(session,true,time+150_000_000))
}
@Test fun trackingLossAndRecoveredDiscontinuityInvalidateInFlightInference() {
val session=session()
val observation=HandObservation(time,7,session.trackingFrameGeneration)
advance(session,20,valid=false)
assertNull(observation.headPose(session,true,time+20_000_000))
advance(session,30,x=5f)
assertNull(observation.headPose(session,true,time+30_000_000))
session.setFloor(1.6f,time+30_000_000)
assertTrue(session.valid(time+30_000_000))
assertNull(observation.headPose(session,true,time+30_000_000))
}
@Test fun reconnectAndMissingHistoryCannotBorrowAnotherPose() {
val session=session()
val observation=HandObservation(time,7,session.trackingFrameGeneration)
advance(session,40)
assertNull(observation.copy(timeNs=time+20_000_000).headPose(session,true,time+40_000_000))
session.reset(8,1.6f)
session.accept(SpatialSample(SpatialPose(),time+50_000_000,8,true))
assertNull(observation.headPose(session,true,time+50_000_000))
}
}
@@ -0,0 +1,119 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class HandProcessingRateTest {
private fun sample(rate: HandProcessingRate, processingMs: Long = 35, ageMs: Long = 65,
healthy: Boolean = true): Int =
rate.observe(processingMs * 1_000_000, ageMs * 1_000_000, healthy)
private fun fastest(rate: HandProcessingRate) {
repeat(16) { sample(rate) }
assertEquals(800, rate.permille)
}
@Test fun beginsConservativelyAndRequiresEightHealthySamplesPerIncrease() {
val rate = HandProcessingRate()
assertEquals(500, rate.permille)
repeat(7) { assertEquals(500, sample(rate)) }
assertEquals(600, sample(rate))
repeat(7) { assertEquals(600, sample(rate)) }
assertEquals(800, sample(rate))
repeat(20) { assertEquals(800, sample(rate)) }
}
@Test fun onlySelectsFifteenHzWhenTwentyHzHasInsufficientHeadroom() {
val rate = HandProcessingRate()
repeat(8) { sample(rate, 50, 80) }
assertEquals(600, rate.permille)
repeat(30) { assertEquals(600, sample(rate, 50, 80)) }
}
@Test fun slowProcessingStaysAtTwelvePointFiveHz() {
val rate = HandProcessingRate()
repeat(30) { assertEquals(500, sample(rate, 60, 100)) }
}
@Test fun sustainedProcessingPastTheCurrentPeriodReducesRate() {
val rate = HandProcessingRate()
fastest(rate)
repeat(2) { assertEquals(800, sample(rate, 70)) }
assertEquals(600, sample(rate, 70))
repeat(7) { assertEquals(600, sample(rate, 70)) }
assertEquals(500, sample(rate, 70))
repeat(7) { assertEquals(500, sample(rate)) }
}
@Test fun largeProcessingSpikeSkipsDirectlyToConservativeRate() {
val rate = HandProcessingRate()
fastest(rate)
assertEquals(500, sample(rate, 80, 100))
}
@Test fun ageLimitReducesRateWithoutWaitingForProcessingAverage() {
val rate = HandProcessingRate()
fastest(rate)
assertEquals(500, sample(rate, ageMs = 140))
repeat(7) { assertEquals(500, sample(rate)) }
assertEquals(600, sample(rate))
}
@Test fun agingFramesCannotRaiseTheRate() {
val rate = HandProcessingRate()
repeat(30) { assertEquals(500, sample(rate, ageMs = 111)) }
repeat(8) { sample(rate, ageMs = 100) }
assertEquals(600, rate.permille)
repeat(30) { assertEquals(600, sample(rate, ageMs = 91)) }
}
@Test fun marginalHeadroomInterruptsConsecutiveUpshiftSamples() {
val rate = HandProcessingRate()
repeat(7) { sample(rate, 55) }
assertEquals(500, sample(rate, 60))
repeat(7) { assertEquals(500, sample(rate)) }
assertEquals(600, sample(rate))
}
@Test fun recoveryMustAlsoBringAverageProcessingBelowUpshiftThreshold() {
val rate = HandProcessingRate()
sample(rate, 100)
repeat(8) { assertEquals(500, sample(rate)) }
repeat(8) { sample(rate) }
assertEquals(600, rate.permille)
}
@Test fun trackingLossAndInvalidTimingResetTheRateAndHistory() {
for (invalid in listOf(Triple(35_000_000L, 65_000_000L, false),
Triple(0L, 65_000_000L, true), Triple(-1L, 65_000_000L, true),
Triple(35_000_000L, -1L, true))) {
val rate = HandProcessingRate()
fastest(rate)
assertEquals(500, rate.observe(invalid.first, invalid.second, invalid.third))
repeat(7) { assertEquals(500, sample(rate)) }
assertEquals(600, sample(rate))
}
}
@Test fun lifecycleResetDropsOldHeadroom() {
val rate = HandProcessingRate()
fastest(rate)
assertEquals(500, rate.reset())
repeat(7) { assertEquals(500, sample(rate)) }
assertEquals(600, sample(rate))
}
@Test fun periodicDiscoverySearchesPermitFifteenHzButNotTwentyHz() {
val rate = HandProcessingRate()
repeat(8) { sample(rate, if (it % 3 == 2) 74 else 36, 90) }
assertEquals(600, rate.permille)
for (frame in 8 until 90) {
assertEquals(600, sample(rate, if (frame % 3 == 2) 74 else 36, 90))
}
}
@Test fun continuouslySlowDiscoveryCannotRaiseRate() {
val rate = HandProcessingRate()
repeat(30) { assertEquals(500, sample(rate, 70, 100)) }
}
}
@@ -0,0 +1,119 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class HandTrackingMetricsTest {
private val missing = HandObservationDiagnostic(HandObservationOutcome.NO_MATCHING_DETECTION)
private fun accepted(trigger: Float = 0f, grip: Boolean = false) = HandObservationDiagnostic(
HandObservationOutcome.ACCEPTED, listOf(0,5,9,13,17), trigger, true, grip, true)
@Test fun cameraSequencesCountOnceAndSkippedPairsAreNotInvented() {
val metrics = HandTrackingMetrics()
metrics.observe(0, true, accepted(), accepted())
metrics.observe(10, true, accepted(), missing)
metrics.observe(10, true, missing, accepted())
metrics.observe(9, true, missing, accepted())
metrics.observe(15, true, accepted(), missing)
val result = metrics.snapshot()
assertEquals(2L, result.processedPairs)
assertEquals(2L, result.inferencePairs)
assertEquals(2L, result.left.accepted)
assertEquals(0L, result.right.accepted)
assertEquals(2L, result.right.observations)
assertEquals(0L, result.left.trackingLosses)
}
@Test fun setupAndUnavailableFramesRemainDistinctFromInference() {
val metrics = HandTrackingMetrics()
val setup = HandObservationDiagnostic(HandObservationOutcome.CALIBRATION_REQUIRED)
val unavailable = HandObservationDiagnostic(HandObservationOutcome.INFERENCE_UNAVAILABLE)
metrics.observe(1, false, setup, setup)
metrics.observe(2, false, unavailable, unavailable)
metrics.observe(3, true, accepted(), missing)
val result = metrics.snapshot()
assertEquals(3L, result.processedPairs)
assertEquals(1L, result.inferencePairs)
assertEquals(3L, result.left.observations)
assertEquals(1L, result.left.accepted)
assertEquals(1L, result.left.outcomes[HandObservationOutcome.CALIBRATION_REQUIRED])
assertEquals(1L, result.left.outcomes[HandObservationOutcome.INFERENCE_UNAVAILABLE])
assertEquals(3L, result.right.maximumConsecutiveRejected)
}
@Test fun countsGestureLossesIndependentlyFromPalmLossAndOtherHand() {
val metrics = HandTrackingMetrics()
metrics.observe(1, true, accepted(), accepted())
metrics.observe(2, true, accepted().copy(triggerGeometryValid = false), accepted())
metrics.observe(3, true, accepted().copy(gripGeometryValid = false), accepted())
metrics.observe(4, true, missing, accepted())
metrics.observe(5, true, missing, accepted())
val result = metrics.snapshot()
assertEquals(3L, result.left.accepted)
assertEquals(1L, result.left.trackingLosses)
assertEquals(2L, result.left.triggerLosses)
assertEquals(1L, result.left.gripLosses)
assertEquals(2L, result.left.maximumConsecutiveRejected)
assertEquals(0L, result.right.trackingLosses)
assertEquals(0L, result.right.triggerLosses)
assertEquals(0L, result.right.gripLosses)
}
@Test fun rejectedObservationRetainsRawEstimatesButCannotCountUsableInputs() {
val metrics = HandTrackingMetrics()
val stale = accepted(1f, true).copy(outcome = HandObservationOutcome.STALE_OBSERVATION)
assertEquals(1f, stale.triggerEstimate, 0f)
assertTrue(stale.gripEstimate)
assertTrue(stale.triggerGeometryValid)
assertFalse(stale.accepted)
assertFalse(stale.triggerValid)
assertFalse(stale.gripValid)
metrics.observe(1, true, stale, stale)
val side = metrics.snapshot().left
assertEquals(0L, side.accepted)
assertEquals(0L, side.triggerValid)
assertEquals(0L, side.gripValid)
assertEquals(0L, side.triggerAboveClickThreshold)
assertEquals(0L, side.gripPressed)
}
@Test fun thresholdCountsDescribeValidEstimatesWithoutClaimingDriverPresses() {
val metrics = HandTrackingMetrics()
for ((index, trigger) in listOf(0f, .25f, .65f, 1f).withIndex())
metrics.observe(index + 1L, true, accepted(trigger, index == 3), missing)
metrics.observe(5, true, accepted(1f, true).copy(triggerGeometryValid = false, gripGeometryValid = false), missing)
val side = metrics.snapshot().left
assertEquals(5L, side.accepted)
assertEquals(4L, side.triggerValid)
assertEquals(4L, side.gripValid)
assertEquals(1L, side.triggerAboveClickThreshold)
assertEquals(1L, side.triggerReleased)
assertEquals(1L, side.gripPressed)
}
@Test fun snapshotsRetainTheirCountsWhenLaterFramesArrive() {
val metrics = HandTrackingMetrics()
metrics.observe(1, true, accepted(), missing)
val first = metrics.snapshot()
metrics.observe(2, true, missing, accepted())
assertEquals(1L, first.processedPairs)
assertEquals(mapOf(HandObservationOutcome.ACCEPTED to 1L), first.left.outcomes)
assertEquals(0L, first.left.trackingLosses)
assertEquals(2L, metrics.snapshot().processedPairs)
assertEquals(1L, metrics.snapshot().left.trackingLosses)
}
@Test fun aNewTrackingConnectionStartsCountsAndSequenceFromZero() {
val old = HandTrackingMetrics()
old.observe(500, true, accepted(), missing)
old.observe(501, true, missing, missing)
val current = HandTrackingMetrics()
assertEquals(0L, current.snapshot().processedPairs)
current.observe(1, true, accepted(), accepted())
val result = current.snapshot()
assertEquals(1L, result.processedPairs)
assertEquals(1L, result.left.accepted)
assertEquals(0L, result.left.trackingLosses)
assertEquals(0L, result.right.maximumConsecutiveRejected)
}
}
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class JoyConFlowGateTest {
@Test fun missingDetectionsCannotExtendTheSeedLifetime() {
val seed = 1_000_000_000L
assertTrue(JoyConFlowGate.fresh(seed, seed + 640_000_000, seed + 720_000_000))
assertFalse(JoyConFlowGate.fresh(seed, seed + 720_000_000, seed + 800_000_000))
assertFalse(JoyConFlowGate.fresh(seed, seed, seed + 200_000_001))
assertFalse(JoyConFlowGate.fresh(seed, seed, seed))
}
@Test fun featureMustBeVisibleAndReturnToItsOriginalLocation() {
assertTrue(JoyConFlowGate.point(110.0,105.0,100.5,100.5,100.0,100.0,5f,true,true,640,480))
assertFalse(JoyConFlowGate.point(110.0,105.0,103.0,100.0,100.0,100.0,5f,true,true,640,480))
assertFalse(JoyConFlowGate.point(110.0,105.0,100.0,100.0,100.0,100.0,30f,true,true,640,480))
assertFalse(JoyConFlowGate.point(110.0,105.0,100.0,100.0,100.0,100.0,5f,false,true,640,480))
assertFalse(JoyConFlowGate.point(Double.NaN,105.0,100.0,100.0,100.0,100.0,5f,true,true,640,480))
assertFalse(JoyConFlowGate.point(640.0,105.0,100.0,100.0,100.0,100.0,5f,true,true,640,480))
}
}
@@ -0,0 +1,69 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class JoyConWristPositionTest {
private fun points(depth: Float = .4f): MutableList<SpatialVector?> = MutableList<SpatialVector?>(21) { null }.apply {
this[0] = SpatialVector(0f, 0f, depth)
this[5] = SpatialVector(.035f, -.06f, depth)
this[9] = SpatialVector(0f, -.065f, depth)
this[13] = SpatialVector(-.02f, -.06f, depth)
this[17] = SpatialVector(-.045f, -.05f, depth)
}
@Test fun grippingControllerNeedsOnlyTheWristAndNeverGeneratesFingerGestures() {
val estimator = JoyConWristPosition()
val full = estimator.estimate(points(), SpatialPose(), 1_000_000_000)!!
val occluded = MutableList<SpatialVector?>(21) { null }.apply { this[0] = points()[0] }
val grip = estimator.estimate(occluded, SpatialPose(), 1_080_000_000)!!
assertEquals(occluded[0], grip.pose.position)
assertEquals(full.pose.position, grip.pose.position)
assertTrue(grip.valid)
assertFalse(grip.triggerValid)
assertFalse(grip.gripValid)
assertNull(HandGestures(false).estimate(occluded, SpatialPose(), 1_080_000_000))
}
@Test fun erroneousKnucklesCannotMoveOrRejectTheWrist() {
val malformed = points().apply {
this[5] = SpatialVector(Float.NaN, 0f, .4f)
this[9] = SpatialVector(4f, 5f, 6f)
this[13] = this[0]
this[17] = null
}
val grip = JoyConWristPosition().estimate(malformed, SpatialPose(), 1)!!
assertEquals(malformed[0], grip.pose.position)
}
@Test fun measuredExtensionMovesTheWorldPositionByTheSameDistance() {
val estimator = JoyConWristPosition()
val world = SpatialPose(SpatialVector(1f, 2f, 3f), SpatialRotation(y = 1f, w = 0f))
val near = estimator.estimate(points(.3f).take(1), world, 1_000_000_000)!!
val far = estimator.estimate(points(.7f).take(1), world, 1_300_000_000)!!
assertEquals(SpatialVector(1f, 2f, 2.7f), near.pose.position)
assertEquals(-.4f, far.pose.position.z - near.pose.position.z, .0001f)
assertEquals(near.pose.position.x, far.pose.position.x, .0001f)
assertEquals(1_300_000_000, far.timeNs)
}
@Test fun missingOrNonfiniteWristIsRejectedEvenWithVisibleKnuckles() {
for (wrist in listOf(null, SpatialVector(Float.NaN, 0f, .4f), SpatialVector(0f, 0f, Float.POSITIVE_INFINITY))) {
val estimator = JoyConWristPosition()
assertNull(estimator.estimate(points().apply { this[0] = wrist }, SpatialPose(), 1))
assertEquals(HandObservationOutcome.WRIST_LANDMARK_MISSING, estimator.lastOutcome)
}
assertNull(JoyConWristPosition().estimate(emptyList(), SpatialPose(), 1))
}
@Test fun implausibleJumpsAndRepeatedFramesStayRejectedWithoutPoisoningTheLastPosition() {
val estimator = JoyConWristPosition()
assertNotNull(estimator.estimate(points(), SpatialPose(), 1_000_000_000))
assertNull(estimator.estimate(points(1.2f), SpatialPose(), 1_080_000_000))
assertEquals(HandObservationOutcome.WRIST_MOTION_REJECTED, estimator.lastOutcome)
assertNull(estimator.estimate(points(), SpatialPose(), 1_000_000_000))
assertNotNull(estimator.estimate(points(.45f).take(1), SpatialPose(), 1_090_000_000))
estimator.reset()
assertNotNull(estimator.estimate(points(1.2f).take(1), SpatialPose(), 1_100_000_000))
}
}
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.glasses
import android.app.Application
import android.os.SystemClock
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.json.JSONObject
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
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(application = Application::class)
class LumaRgbDiagnosticTest {
private val context get() = RuntimeEnvironment.getApplication()
private val statusFile get() = File(context.filesDir, "spatial/rgb-diagnostic.json")
@Before fun reset() { statusFile.delete(); statusFile.parentFile?.mkdirs() }
@Test fun aDeadWorkerOrPreviousBootCannotLeaveCapturePermanentlyBusy() {
for (started in listOf(SystemClock.elapsedRealtime() - 16_000, SystemClock.elapsedRealtime() + 5_000)) {
statusFile.writeText("""{"state":"capturing","startedMs":$started}""")
assertEquals("failed", LumaRgbDiagnostic.status(context).getString("state"))
}
}
@Test fun onlyPendingCapturesExpire() {
statusFile.writeText("""{"state":"completed","path":"saved-capture"}""")
assertEquals("completed", LumaRgbDiagnostic.status(context).getString("state"))
statusFile.writeText("""{"state":"capturing","startedMs":${SystemClock.elapsedRealtime()}}""")
assertEquals("capturing", LumaRgbDiagnostic.status(context).getString("state"))
}
@Test fun longerReliabilityCaptureRemainsBusyUntilItsBoundedDeadline() {
val started = SystemClock.elapsedRealtime() - 20_000
statusFile.writeText("""{"state":"capturing","startedMs":$started,"timeoutMs":45000}""")
assertEquals("capturing", LumaRgbDiagnostic.status(context).getString("state"))
statusFile.writeText("""{"state":"capturing","startedMs":${started-30_000},"timeoutMs":999999}""")
assertEquals("failed", LumaRgbDiagnostic.status(context).getString("state"))
}
@Test fun terminalResultWaitsForWorkerExitBeforeAnotherRequest() {
for (result in listOf("completed","failed")) {
val record=JSONObject().put("state",result).put("workerPid",123).put("startedMs",1000)
val finishing=LumaRgbDiagnostic.resolveStatus(JSONObject(record.toString()),2000,true)
assertEquals("capturing",finishing.getString("state"))
assertEquals("finishing",finishing.getString("phase"))
assertEquals(result,finishing.getString("resultState"))
assertTrue(finishing.getBoolean("busy"))
val exited=LumaRgbDiagnostic.resolveStatus(record,2000,false)
assertEquals(result,exited.getString("state"))
assertFalse(exited.getBoolean("busy"))
}
}
@Test fun deadWorkerFailsImmediatelyAndExpiredWorkerRemainsBusyOnlyUntilExit() {
val record=JSONObject().put("state","capturing").put("workerPid",123).put("startedMs",1000)
val dead=LumaRgbDiagnostic.resolveStatus(JSONObject(record.toString()),2000,false)
assertEquals("failed",dead.getString("state"))
assertFalse(dead.getBoolean("busy"))
val expired=LumaRgbDiagnostic.resolveStatus(JSONObject(record.toString()),17000,true)
assertEquals("failed",expired.getString("state"))
assertTrue(expired.getBoolean("busy"))
val exited=LumaRgbDiagnostic.resolveStatus(record,17000,false)
assertEquals("failed",exited.getString("state"))
assertFalse(exited.getBoolean("busy"))
}
}
@@ -0,0 +1,137 @@
package com.droiddeck.launcher.glasses
import android.content.Context
import org.junit.Assert.*
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 = [28], manifest = Config.NONE)
class RayNeoCalibrationTest {
private val axes = RayNeoSensorAxes(0f, false)
private fun sample(a: FloatArray = floatArrayOf(0f, -9.81f, 0f), g: FloatArray = floatArrayOf(0.5f, -0.3f, 0.2f)) =
RayNeoSensorSample(a, g, 0f, FloatArray(3), 0f, 0f, 0)
private fun finish(c: RayNeoCalibrationCollector, start: Long = 0, sample: RayNeoSensorSample = sample()): RayNeoCalibration? {
var result: RayNeoCalibration? = null
for (ms in start..(start + 8100) step 10) c.update(sample, ms)?.let { result = it }
return result
}
@Test fun upsideDownStillPoseMeasuresBiasAfterSettlingAndFiveSeconds() {
val c = RayNeoCalibrationCollector(axes, 0)
for (ms in 0L..7990 step 10) assertNull(c.update(sample(), ms))
val result = c.update(sample(), 8000)!!
assertEquals(CalibrationPhase.SAVED, c.phase)
assertEquals(100, c.progress)
assertEquals(Vec3(0.5f, -0.3f, 0.2f), result.gyroBiasDps)
assertEquals(Quaternion.IDENTITY, result.level)
}
@Test fun uprightOrSidewaysCannotSave() {
for (a in listOf(floatArrayOf(0f, 9.81f, 0f), floatArrayOf(9.81f, 0f, 0f))) {
val c = RayNeoCalibrationCollector(axes, 0)
assertNull(finish(c, sample = sample(a)))
assertEquals(CalibrationPhase.TURN_OVER, c.phase)
}
}
@Test fun movementRestartsTheWindowAndAllowsRecovery() {
val c = RayNeoCalibrationCollector(axes, 0)
for (ms in 0L..6000 step 10) c.update(sample(), ms)
c.update(sample(g = floatArrayOf(20f, 0f, 0f)), 6010)
assertEquals(CalibrationPhase.MOVING, c.phase)
assertEquals(0, c.progress)
assertNotNull(finish(c, 6020))
}
@Test fun VibrationIsRejectedEvenBelowTheInstantSpeedLimit() {
val c = RayNeoCalibrationCollector(axes, 0)
var result: RayNeoCalibration? = null
for (ms in 0L..12000 step 10) {
val gyro = if (ms % 20 == 0L) 4f else -4f
c.update(sample(g = floatArrayOf(gyro, 0f, 0f)), ms)?.let { result = it }
}
assertNull(result)
}
@Test fun missingSamplesCannotCompleteAStationaryWindow() {
val c = RayNeoCalibrationCollector(axes, 0)
for (ms in 0L..6000 step 10) c.update(sample(), ms)
assertNull(c.update(sample(), 9000))
assertEquals(CalibrationPhase.MOVING, c.phase)
assertNull(c.update(sample(), 30_000))
assertEquals(CalibrationPhase.FAILED, c.phase)
}
@Test fun nonFiniteOrInvalidGravityCannotSave() {
for (a in listOf(floatArrayOf(Float.NaN, -9.81f, 0f), FloatArray(3), floatArrayOf(0f, -20f, 0f))) {
assertNull(finish(RayNeoCalibrationCollector(axes, 0), sample = sample(a)))
}
}
@Test fun levelCorrectionAlignsBothInvertedAndUprightGravity() {
val c = RayNeoCalibrationCollector(axes, 0)
val result = finish(c, sample = sample(floatArrayOf(0.85f, -9.735f, 0.85f)))!!
val up = result.level.rotate(Vec3(-0.85f, 9.735f, -0.85f).normalized())
assertEquals(0f, up.x, 0.001f); assertEquals(1f, up.y, 0.001f); assertEquals(0f, up.z, 0.001f)
val filter = RayNeoOrientationFilter(0f, calibration = result)
var q = FloatArray(4)
repeat(1000) { q = filter.update(sample(floatArrayOf(-0.85f, 9.735f, -0.85f)).copy(deviceTick100us = it * 100L)) }
assertArrayEquals(floatArrayOf(1f, 0f, 0f, 0f), q, 0.001f)
}
@Test fun profilePersistenceIsIsolatedByVendorProductAndSerialAndCanReset() {
val prefs = RuntimeEnvironment.getApplication().getSharedPreferences("cal-test", Context.MODE_PRIVATE)
val store = RayNeoCalibrationStore(prefs)
val value = RayNeoCalibration(Vec3(0.1f, 0.2f, 0.3f), Quaternion.IDENTITY)
val key = store.key(0x3941, 0xaf50, "first")
store.save(key, value)
assertEquals(value, store.load(key))
for (other in listOf(store.key(0x3941, 0xaf50, "second"), store.key(0x1bbb, 0xaf50, "first"), store.key(0x3941, 1, "first"))) {
assertNull(store.load(other))
}
store.save(key, null)
assertNull(store.load(key))
}
@Test fun corruptOrExcessiveProfilesFallBackToDefaults() {
assertNull(RayNeoCalibration.decode("bad"))
assertNull(RayNeoCalibration.decode("{\"version\":2}"))
assertNull(RayNeoCalibration.decode(RayNeoCalibration(Vec3(10f, 0f, 0f), Quaternion.IDENTITY).encode()))
assertNull(RayNeoCalibration.decode(RayNeoCalibration(Vec3(0f, 0f, 0f), Quaternion(0f, 1f, 0f, 0f)).encode()))
}
@Test fun recordedNonMaxRestingPoseCalibratesWithItsOwnProfile() {
val profile = RayNeoSensorProfile.forDevice(true, 0x40)
val collector = RayNeoCalibrationCollector(RayNeoSensorAxes(profile.rotationXDeg, profile.gtMaxAxes), 0)
val reading = sample(floatArrayOf(0.02f, -8.819f, -4.106f), floatArrayOf(-0.1f, 0.35f, -0.038f))
val saved = finish(collector, sample = reading)!!
assertEquals(CalibrationPhase.SAVED, collector.phase)
assertEquals(-0.1f, saved.gyroBiasDps.x, 0.0001f)
val upright = RayNeoOrientationFilter(profile.rotationXDeg, profile.gtMaxAxes, saved)
.update(sample(floatArrayOf(-0.02f, 8.819f, 4.106f), reading.gyroDps))
assertArrayEquals(floatArrayOf(1f, 0f, 0f, 0f), upright, 0.001f)
// This was the reported failure: the same physical pose cannot calibrate
// through the Max's permutation and 35-degree mounting correction.
assertNull(finish(RayNeoCalibrationCollector(RayNeoSensorAxes(35f, true), 0), sample = reading))
}
@Test fun nonMaxProfileCannotOverwriteLegacyMaxCalibrationWithTheSameUsbIdentity() {
val prefs = RuntimeEnvironment.getApplication().getSharedPreferences("cal-profile-test", Context.MODE_PRIVATE)
val store = RayNeoCalibrationStore(prefs)
val base = store.key(0x3941, 0xaf50, "00000001")
val standard = RayNeoCalibrationStore.profileKey(base, true, 0x40)
val legacy = RayNeoCalibration(Vec3(1f, 0f, 0f), Quaternion.IDENTITY)
val current = RayNeoCalibration(Vec3(0f, 1f, 0f), Quaternion.IDENTITY)
store.save(base, legacy); store.save(standard, current)
assertEquals(legacy, store.load(base))
assertEquals(current, store.load(standard))
assertEquals(base, RayNeoCalibrationStore.profileKey(base, false, 0x40))
assertEquals(base, RayNeoCalibrationStore.profileKey(base, true, 0x7f))
assertEquals(base, RayNeoCalibrationStore.profileKey(base, true, 0x41))
}
}
@@ -0,0 +1,62 @@
package com.droiddeck.launcher.glasses
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadow.api.Shadow
import org.robolectric.util.ReflectionHelpers
import org.robolectric.util.ReflectionHelpers.ClassParameter.from
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class RayNeoEndpointsTest {
@Test fun gtPrefersInterfaceNumberFiveOverEarlierPairs() {
val other = iface(1)
val control = iface(5)
val selected = RayNeoProtocol.selectEndpoints(device(0x3941, other, control))!!
assertSame(control, selected.usbInterface)
assertEquals(0x81, selected.inEndpoint.address)
assertEquals(0x01, selected.outEndpoint.address)
}
@Test fun gtAcceptsUniqueRenumberedPairAndIgnoresSmallButtonReports() {
val control = iface(0)
assertSame(control, RayNeoProtocol.selectEndpoints(
device(0x3941, iface(5, packetSize = 8), control))?.usbInterface)
}
@Test fun gtDoesNotGuessBetweenAmbiguousPairsOrUseInputOnlyInterface() {
assertNull(RayNeoProtocol.selectEndpoints(device(0x3941, iface(0), iface(1))))
assertNull(RayNeoProtocol.selectEndpoints(device(0x3941, iface(5, output = false))))
assertNull(RayNeoProtocol.selectEndpoints(device(0x3941, iface(5, packetSize = 8))))
}
@Test fun airRetainsItsExistingFirstInterruptPairSelection() {
val first = iface(1)
assertSame(first, RayNeoProtocol.selectEndpoints(device(0x1bbb, first, iface(5)))?.usbInterface)
}
private fun device(vid: Int, vararg interfaces: UsbInterface): UsbDevice =
Shadow.newInstanceOf(UsbDevice::class.java).also {
ReflectionHelpers.setField(it, "mVendorId", vid)
ReflectionHelpers.setField(it, "mProductId", 0xaf50)
ReflectionHelpers.setField(it, "mInterfaces", interfaces)
}
private fun iface(id: Int, packetSize: Int = 64, output: Boolean = true): UsbInterface =
Shadow.newInstanceOf(UsbInterface::class.java).also {
ReflectionHelpers.setField(it, "mId", id)
val endpoints = if (output) arrayOf(endpoint(0x81, packetSize), endpoint(1, packetSize))
else arrayOf(endpoint(0x81, packetSize))
ReflectionHelpers.setField(it, "mEndpoints", endpoints)
}
private fun endpoint(address: Int, size: Int) = ReflectionHelpers.callConstructor(UsbEndpoint::class.java,
from(Int::class.javaPrimitiveType, address), from(Int::class.javaPrimitiveType, 3),
from(Int::class.javaPrimitiveType, size), from(Int::class.javaPrimitiveType, 1))
}
@@ -0,0 +1,150 @@
package com.droiddeck.launcher.glasses
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.time.Duration
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.annotation.LooperMode
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowSystemClock
import org.robolectric.util.ReflectionHelpers
import org.robolectric.util.ReflectionHelpers.ClassParameter.from
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, shadows = [RayNeoLinkTest.Connection::class])
@LooperMode(LooperMode.Mode.PAUSED)
class RayNeoLinkTest {
@Test fun handshakeWarmupPoseAndShutdownUseOnlyRayNeoWireCommands() = exerciseLink(false)
@Test fun gtControlTrafficDoesNotBreakHandshakeOrTracking() = exerciseLink(true)
@Test fun nonMaxBoardSelectsItsProfileBeforeTrackingStarts() = exerciseLink(true, true)
private fun exerciseLink(gtTraffic: Boolean, nonMax: Boolean = false) {
fun endpoint(address: Int) = ReflectionHelpers.callConstructor(UsbEndpoint::class.java,
from(Int::class.javaPrimitiveType, address), from(Int::class.javaPrimitiveType, 3),
from(Int::class.javaPrimitiveType, 64), from(Int::class.javaPrimitiveType, 1))
val iface = Shadow.newInstanceOf(UsbInterface::class.java)
val conn = Shadow.newInstanceOf(UsbDeviceConnection::class.java)
val io = Shadow.extract<Connection>(conn)
io.gtTraffic = gtTraffic
io.boardId = if (nonMax) 0x40 else if (gtTraffic) 0x41 else 0
lateinit var link: RayNeoLink
var ready = false
var pose: FloatArray? = null
var lost = false
var loadedBoard = -1
var reportedBoard = -1
val listener = object : RayNeoLink.Listener {
override fun onDeviceInfo(boardId: Int, calibrationSaved: Boolean) {
reportedBoard = boardId
assertFalse(calibrationSaved)
}
override fun onReady() {
assertEquals(io.boardId, loadedBoard)
assertEquals(io.boardId, reportedBoard)
ready = true
if (gtTraffic) {
assertTrue(link.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(6)))
assertTrue(link.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(7)))
}
}
override fun onPose(raw: ByteArray, xyzw: FloatArray, timeNs: Long) {
pose = xyzw
link.close()
}
override fun onLost() { lost = true }
}
val ctor = RayNeoLink::class.java.declaredConstructors.first { it.parameterCount == 5 }.apply { isAccessible = true }
val loadCalibration: (Int) -> RayNeoCalibration? = { board -> loadedBoard = board; null }
link = ctor.newInstance(conn, RayNeoEndpointSelection(iface, endpoint(0x81), endpoint(0x01)), listener, gtTraffic, loadCalibration) as RayNeoLink
ReflectionHelpers.setField(link, "worker", Thread.currentThread())
assertFalse(link.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(8)))
assertFalse(link.send(VitureProtocol.MSG_FILM, byteArrayOf(1)))
assertFalse(link.send(VitureProtocol.MSG_IMU_RATE, byteArrayOf(3)))
assertTrue(io.commands.isEmpty())
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
RayNeoLink::class.java.getDeclaredMethod("run").apply { isAccessible = true }.invoke(link)
assertTrue(ready)
assertFalse(lost)
assertEquals(if (gtTraffic) listOf(0, 6, 7, 1, 2) else listOf(0, 1, 2), io.commands)
assertTrue(io.samples >= 200)
assertTrue(io.closed)
assertTrue(io.released)
assertNotNull(pose)
assertEquals(0f, pose!![0], 1e-5f)
assertEquals(0f, pose!![1], 1e-5f)
assertTrue(pose!![2] > 0)
}
@Implements(UsbDeviceConnection::class)
class Connection {
val commands = mutableListOf<Int>()
private val responses = ArrayDeque<ByteArray>()
var samples = 0
var closed = false
var released = false
var gtTraffic = false
var boardId = 0
private var streaming = false
@Implementation fun bulkTransfer(ep: UsbEndpoint, bytes: ByteArray, count: Int, timeout: Int): Int {
if (ep.direction == 0) {
check(bytes[0] == 0x66.toByte() && count == 64)
val cmd = bytes[1].toInt() and 0xff
commands += cmd
if (gtTraffic && cmd in listOf(0, 1)) {
// Notifications and unrelated ACKs can precede the requested response.
for (other in listOf(0x08, 6, 7, 0x50)) {
responses += ByteArray(64).apply {
this[0] = 0x99.toByte(); this[1] = 0xc8.toByte(); this[2] = 64
this[8] = other.toByte()
}
}
}
responses += ByteArray(64).apply {
this[0] = 0x99.toByte(); this[1] = 0xc8.toByte(); this[2] = 64
this[8] = cmd.toByte()
if (cmd == 0) this[21] = boardId.toByte()
}
if (cmd == 1) streaming = true
if (cmd == 2) streaming = false
return count
}
ShadowSystemClock.advanceBy(Duration.ofMillis(10))
val packet = if (responses.isNotEmpty()) responses.removeFirst() else {
check(streaming)
check(++samples < 500) { "Warmup never delivered a pose" }
ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN).apply {
put(0, 0x99.toByte()); put(1, 0x65); put(2, 64)
if (gtTraffic && boardId == 0x40) {
val s = kotlin.math.sin(Math.toRadians(25.0)).toFloat()
val c = kotlin.math.cos(Math.toRadians(25.0)).toFloat()
putFloat(8, 9.81f * c); putFloat(12, 9.81f * s)
putFloat(20, 90f * c); putFloat(24, 90f * s)
} else if (gtTraffic) {
val s = kotlin.math.sin(Math.toRadians(35.0)).toFloat()
val c = kotlin.math.cos(Math.toRadians(35.0)).toFloat()
putFloat(4, 9.81f * s); putFloat(12, 9.81f * c)
putFloat(16, 90f * s); putFloat(24, 90f * c)
} else {
putFloat(8, 9.81f); putFloat(20, 90f)
}
putInt(40, samples * 100)
}.array()
}
packet.copyInto(bytes)
return packet.size
}
@Implementation fun releaseInterface(iface: UsbInterface): Boolean { released = true; return true }
@Implementation fun close() { closed = true }
}
}
@@ -0,0 +1,115 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import kotlin.math.cos
import kotlin.math.sin
import org.junit.Assert.*
import org.junit.Test
class RayNeoOrientationFilterTest {
private fun sample(tick: Long, accel: FloatArray, gyro: FloatArray = FloatArray(3)) =
RayNeoSensorSample(accel, gyro, 0f, FloatArray(3), 0f, 0f, tick)
private fun screen(q: FloatArray): FloatArray {
val p = RayNeoOrientationFilter.glassesPose(q)
return HeadPose.fromGlasses(p[0], p[1], p[2], p[3])
}
@Test fun gravityCorrectionSettlesTowardTiltInsteadOfAwayFromIt() {
val filter = RayNeoOrientationFilter(0f)
filter.update(sample(0, floatArrayOf(0f, 9.81f, 0f)))
val angle = Math.toRadians(20.0)
val accel = floatArrayOf(0f, 9.81f * cos(angle).toFloat(), -9.81f * sin(angle).toFloat())
var q = FloatArray(4)
repeat(1000) { q = filter.update(sample((it + 1) * 100L, accel)) }
assertArrayEquals(floatArrayOf(cos(angle / 2).toFloat(), sin(angle / 2).toFloat(), 0f, 0f), q, 0.002f)
}
@Test fun initialGravityDoesNotRotateAfterTheFirstRecenter() {
val filter = RayNeoOrientationFilter(0f)
val accel = floatArrayOf(4.905f, 8.4957f, 0f)
val first = filter.update(sample(0, accel))
var last = first
repeat(1000) { last = filter.update(sample((it + 1) * 100L, accel)) }
assertArrayEquals(first, last, 0.0001f)
assertEquals(sin(Math.toRadians(15.0)).toFloat(), first[3], 0.001f)
}
@Test fun recordedGtLevelGravityStartsWithAnUprightHorizon() {
val q = RayNeoOrientationFilter(0f, gt = true)
.update(sample(0, floatArrayOf(5.697f, 0.001f, 7.947f)))
val m = screen(q)
val relative = HeadPose.relative(HeadPose.recenter(m), m)
assertArrayEquals(HeadPose.IDENTITY, relative, 0.02f)
}
@Test fun gtLeftTurnLooksLeftWithoutPitchOrRoll() = checkGtMotion(0)
@Test fun gtLookingUpLooksUpWithoutYawOrRoll() = checkGtMotion(1)
@Test fun gtRollTiltsTheHorizonWithoutTurningTheView() = checkGtMotion(2)
@Test fun nonMaxMountingKeepsYawAndPitchSeparateThroughTheSharedPosePath() {
val profile = RayNeoSensorProfile.forDevice(true, 0x40)
assertFalse(profile.gtMaxAxes)
val mount = Math.toRadians(25.0)
val s = sin(mount).toFloat(); val c = cos(mount).toFloat()
for (pitch in listOf(false, true)) {
val filter = RayNeoOrientationFilter(profile.rotationXDeg, profile.gtMaxAxes)
val level = floatArrayOf(0f, 9.81f * c, 9.81f * s)
val ref = HeadPose.recenter(screen(filter.update(sample(0, level))))
var q = FloatArray(4)
repeat(100) { i ->
val angle = Math.toRadians((i + 1) * 0.3)
val accel = if (pitch) floatArrayOf(0f, 9.81f * cos(mount - angle).toFloat(), 9.81f * sin(mount - angle).toFloat()) else level
val gyro = if (pitch) floatArrayOf(30f, 0f, 0f) else floatArrayOf(0f, 30f * c, 30f * s)
q = filter.update(sample((i + 1) * 100L, accel, gyro))
}
val forward = HeadPose.apply(HeadPose.relative(ref, screen(q)), floatArrayOf(0f, 0f, -1f))
assertArrayEquals(if (pitch) floatArrayOf(0f, 0.5f, -0.8660254f) else floatArrayOf(-0.5f, 0f, -0.8660254f), forward, 0.01f)
}
assertTrue(RayNeoSensorProfile.forDevice(true, 0x7f).gtMaxAxes)
assertTrue(RayNeoSensorProfile.forDevice(true, 0x41).gtMaxAxes)
assertEquals(-20f, RayNeoSensorProfile.forDevice(false, 0x3a).rotationXDeg, 0f)
}
private fun checkGtMotion(axis: Int) {
val mount = Math.toRadians(35.0)
val s = sin(mount).toFloat(); val c = cos(mount).toFloat()
val filter = RayNeoOrientationFilter(0f, gt = true)
val level = floatArrayOf(9.81f * s, 0f, 9.81f * c)
val first = screen(filter.update(sample(0, level)))
val ref = HeadPose.recenter(first)
var q = FloatArray(4)
// Physical 30-degree turn over one second, through the complete shared
// VITURE conversion and recenter pipeline. GT signs match device captures.
repeat(100) { i ->
val a = Math.toRadians((i + 1) * 0.3)
val accel = when (axis) {
1 -> floatArrayOf(9.81f * sin(mount + a).toFloat(), 0f, 9.81f * cos(mount + a).toFloat())
2 -> floatArrayOf(9.81f * s * cos(a).toFloat(), -9.81f * sin(a).toFloat(), 9.81f * c * cos(a).toFloat())
else -> level
}
val gyro = when (axis) {
0 -> floatArrayOf(30f * s, 0f, 30f * c)
1 -> floatArrayOf(0f, -30f, 0f)
else -> floatArrayOf(-30f * c, 0f, 30f * s)
}
q = filter.update(sample((i + 1) * 100L, accel, gyro))
}
val view = HeadPose.relative(ref, screen(q))
val forward = HeadPose.apply(view, floatArrayOf(0f, 0f, -1f))
val up = HeadPose.apply(view, floatArrayOf(0f, 1f, 0f))
val c30 = cos(Math.toRadians(30.0)).toFloat()
val expectedForward = when (axis) {
0 -> floatArrayOf(-0.5f, 0f, -c30)
1 -> floatArrayOf(0f, 0.5f, -c30)
else -> floatArrayOf(0f, 0f, -1f)
}
val expectedUp = when (axis) {
0 -> floatArrayOf(0f, 1f, 0f)
1 -> floatArrayOf(0f, c30, 0.5f)
else -> floatArrayOf(-0.5f, c30, 0f)
}
assertArrayEquals(expectedForward, forward, 0.01f)
assertArrayEquals(expectedUp, up, 0.01f)
}
}
@@ -0,0 +1,122 @@
package com.droiddeck.launcher.glasses
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.*
import org.junit.Test
import kotlin.math.sqrt
class RayNeoProtocolTest {
private fun sensor(tick: Long = 1234L): ByteArray = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN).apply {
put(0, 0x99.toByte()); put(1, 0x65); put(2, 64)
putFloat(4, 1f); putFloat(8, 9.81f); putFloat(12, -2f)
putFloat(16, 30f); putFloat(20, -60f); putFloat(24, 90f)
putFloat(28, 25f); putFloat(32, 2f); putFloat(36, 3f)
putInt(40, tick.toInt()); putFloat(44, 1f); putFloat(48, 42f); putFloat(52, 4f)
}.array()
@Test fun decodesScaffoldLayoutAndUnsignedTick() {
val p = RayNeoProtocol.classifyPacket(sensor(0xfffffff0L)) as RayNeoPacket.Sensor
assertArrayEquals(floatArrayOf(1f, 9.81f, -2f), p.sample.accelMps2, 0f)
assertArrayEquals(floatArrayOf(30f, -60f, 90f), p.sample.gyroDps, 0f)
assertArrayEquals(floatArrayOf(2f, 3f, 4f), p.sample.magnet, 0f)
assertEquals(0xfffffff0L, p.sample.deviceTick100us)
assertEquals(25f, p.sample.temperatureC, 0f)
assertEquals(42f, p.sample.light, 0f)
}
@Test fun rejectsTruncationBadHeaderAndNonfiniteMotion() {
assertSame(RayNeoPacket.Unknown, RayNeoProtocol.classifyPacket(sensor().copyOf(40)))
assertSame(RayNeoPacket.Unknown, RayNeoProtocol.classifyPacket(sensor().apply { this[0] = 0 }))
assertSame(RayNeoPacket.Unknown, RayNeoProtocol.classifyPacket(sensor().apply { this[2] = 56 }))
val nan = sensor().apply { ByteBuffer.wrap(this).order(ByteOrder.LITTLE_ENDIAN).putFloat(16, Float.NaN) }
assertSame(RayNeoPacket.Unknown, RayNeoProtocol.classifyPacket(nan))
}
@Test fun assemblesFragmentedAndCoalescedFramesAfterNoise() {
val a = RayNeoPacketAssembler()
val packet = sensor()
val bytes = byteArrayOf(1, 2, 0x99.toByte(), 0, 0) + packet + packet
a.append(bytes.copyOf(20), 20)
assertNull(a.nextPacket())
val rest = bytes.copyOfRange(20, bytes.size)
a.append(rest, rest.size)
assertArrayEquals(packet, a.nextPacket())
assertArrayEquals(packet, a.nextPacket())
assertNull(a.nextPacket())
}
@Test fun commandAndDeviceInfoMatchScaffold() {
assertArrayEquals(byteArrayOf(0x66, 1, 0) + ByteArray(61), RayNeoProtocol.buildCommandPacket(1, 0, 64))
val info = ByteArray(64).apply {
this[0] = 0x99.toByte(); this[1] = 0xc8.toByte(); this[2] = 64
this[8] = 0; this[21] = 0x3a; this[43] = 1
}
assertEquals(RayNeoDeviceInfo(0x3a, true), RayNeoProtocol.parseDeviceInfo(info))
assertNull(RayNeoProtocol.parseDeviceInfo(info.copyOf(21)))
info[8] = 1
assertNull(RayNeoProtocol.parseDeviceInfo(info))
}
@Test fun discoveryDoesNotClaimEveryTclOrBridgeDevice() {
assertNotNull(RayNeoModel.model(0x1bbb, 0xaf50, null))
for (name in listOf("RayNeo Air 2", "RayNeo Air 2s", "RayNeo Air 3", "RayNeo Air 4 Pro", "RayNeo GT")) {
assertEquals(name, RayNeoModel.model(0x22d9, 1, name)?.name)
assertTrue(Glasses.isGlassesDisplayName(name))
}
assertNull(RayNeoModel.model(0x1bbb, 1, "TCL Phone"))
assertNull(RayNeoModel.model(0x22d9, 1, "USB bridge"))
assertNull(RayNeoModel.model(0x1234, 0xaf50, "RayNeo Air 3"))
assertFalse(Glasses.isGlassesDisplayName("TCL TV"))
assertTrue(Glasses.isGlassesDisplayName("VITURE Pro"))
}
@Test fun gtIdentityWorksWithoutProductNameAndPreservesMaxName() {
assertEquals("RayNeo GT series", RayNeoModel.model(0x3941, 0xaf50, null)?.name)
assertEquals("RayNeo GT series", RayNeoModel.model(0x3941, 0xaf50, "USB device")?.name)
for (name in listOf("RayNeo GT", "RayNeo GT MAX")) {
val model = RayNeoModel.model(0x3941, 0xaf50, name)!!
assertEquals(name, model.name)
assertEquals(6, model.mode(60, true))
assertEquals(7, model.mode(120, false))
assertTrue(Glasses.isGlassesDisplayName(name))
}
assertNull(RayNeoModel.model(0x3941, 0x1234, "RayNeo GT"))
assertNull(RayNeoModel.model(0x1234, 0xaf50, "RayNeo GT MAX"))
}
@Test fun gtNotificationsAndControlAcksAreNotDeviceInfo() {
for (cmd in listOf(0x08, 6, 7, 0x50)) {
val raw = ByteArray(64).apply {
this[0] = 0x99.toByte(); this[1] = 0xc8.toByte(); this[2] = 64
this[8] = cmd.toByte()
}
assertEquals(cmd, (RayNeoProtocol.classifyPacket(raw) as RayNeoPacket.Response).cmd)
assertNull(RayNeoProtocol.parseDeviceInfo(raw))
}
}
private fun sample(tick: Long, yawDps: Float = 0f) = RayNeoSensorSample(
floatArrayOf(0f, 9.81f, 0f), floatArrayOf(0f, yawDps, 0f), 0f,
FloatArray(3), 0f, 0f, tick,
)
@Test fun stationaryPoseIsFiniteAndYawUsesVitureUpAxis() {
val stationary = RayNeoOrientationFilter(0f)
repeat(100) { assertArrayEquals(floatArrayOf(1f, 0f, 0f, 0f), stationary.update(sample(it * 100L)), 1e-6f) }
val filter = RayNeoOrientationFilter(0f)
var q = FloatArray(4)
repeat(100) { q = filter.update(sample(it * 100L, 90f)) }
assertEquals(1f, sqrt(q.sumOf { (it * it).toDouble() }).toFloat(), 1e-5f)
val pose = RayNeoOrientationFilter.glassesPose(q)
assertEquals(0f, pose[0], 1e-5f); assertEquals(0f, pose[1], 1e-5f)
assertEquals(sqrt(0.5f), pose[2], 0.01f); assertEquals(sqrt(0.5f), pose[3], 0.01f)
}
@Test fun tickWrapDoesNotIntroduceOrientationJump() {
val filter = RayNeoOrientationFilter(0f)
filter.update(sample(0xfffffff0L, 90f))
val q = filter.update(sample(84, 90f)) // 100 ticks = 10ms across uint32 rollover.
assertEquals(kotlin.math.sin(Math.PI * 0.005).toFloat(), q[2], 1e-4f)
}
}
@@ -0,0 +1,77 @@
package com.droiddeck.launcher.glasses
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SpatialControllerModeTest {
private fun snapshot(): ByteBuffer = (SpatialTracking::class.java.getDeclaredField("buffer")
.apply { isAccessible = true }.get(null) as ByteBuffer).duplicate().order(ByteOrder.LITTLE_ENDIAN)
@After fun cleanUp() {
SpatialTracking.setSteadyHandAim(false)
SpatialTracking.setControllers(false, false)
SpatialTracking.disconnect()
}
@Test fun joyConModeStartsStereoWithoutSelectingGestureControllersAndPersistsAcrossLoss() {
SpatialTracking.connect(0, 1, null, true, 1.6f, false, true)
assertTrue(SpatialTracking.handsEnabled)
assertEquals(4, snapshot().getInt(4))
assertEquals(5, snapshot().getInt(32))
SpatialTracking.disconnect()
assertFalse(SpatialTracking.handsEnabled)
assertEquals(5, snapshot().getInt(32))
assertEquals(0, snapshot().getInt(76))
SpatialTracking.setControllers(false, false)
assertEquals(1, snapshot().getInt(32))
}
@Test fun steadyAimIsOptInAndOnlyAppliesToBareHands() {
assertFalse(GlassesSettings().steadyHandAim)
SpatialTracking.connect(0, 4, null, true, 1.6f, true)
assertEquals(3, snapshot().getInt(32))
SpatialTracking.setSteadyHandAim(true)
assertEquals(11, snapshot().getInt(32))
SpatialTracking.setControllers(false, true)
assertEquals(5, snapshot().getInt(32))
SpatialTracking.setControllers(true, false)
assertEquals(11, snapshot().getInt(32))
SpatialTracking.setSteadyHandAim(false)
assertEquals(3, snapshot().getInt(32))
SpatialTracking.connect(0, 5, null, true, 1.6f, true, steadyAim = true)
assertEquals(11, snapshot().getInt(32))
SpatialTracking.useLegacyTracking()
assertEquals(0, snapshot().getInt(32))
}
@Test fun openingOtherGlassesClearsTheRetainedUltraMode() {
SpatialTracking.connect(0, 3, null, true, 1.6f, false, true)
SpatialTracking.disconnect()
assertEquals(5, snapshot().getInt(32))
SpatialTracking.useLegacyTracking()
assertEquals(0, snapshot().getInt(32))
assertFalse(SpatialTracking.enabled)
assertFalse(SpatialTracking.handsEnabled)
}
@Test fun switchingControllerModesClearsOldStereoObservations() {
SpatialTracking.connect(0, 2, null, true, 1.6f, true)
assertEquals(3, snapshot().getInt(32))
SpatialTracking.setControllers(false, true)
assertTrue(SpatialTracking.handsEnabled)
assertEquals(5, snapshot().getInt(32))
SpatialTracking.setControllers(true, false)
assertEquals(3, snapshot().getInt(32))
SpatialTracking.setControllers(false, false)
assertFalse(SpatialTracking.handsEnabled)
assertEquals(1, snapshot().getInt(32))
}
}
@@ -0,0 +1,25 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
import java.util.Locale
class SpatialMeasurementsTest {
@Test fun validationKeepsExactImperialAndMetricMeasurements() {
assertEquals(0.3048f, CalibrationDistance.INCHES_12.meters, 0.000001f)
assertEquals(0.3f, CalibrationDistance.CENTIMETERS_30.meters, 0.000001f)
assertEquals(0.508f, CalibrationDistance.INCHES_20.meters, 0.000001f)
assertEquals(0.5f, CalibrationDistance.CENTIMETERS_50.meters, 0.000001f)
}
@Test fun heightCarriesRoundedInchesIntoFeetAndAlwaysShowsBothUnits() {
val previous = Locale.getDefault()
try {
Locale.setDefault(Locale.US)
assertEquals("160 cm (5 ft 3.0 in)", SpatialMeasurements.height(160))
assertEquals("183 cm (6 ft 0.0 in)", SpatialMeasurements.height(183))
assertEquals("1.0 m (3.3 ft)", SpatialMeasurements.distance(1f))
assertEquals("50.8 cm (20.00 in)", SpatialMeasurements.validation(0.508f))
} finally { Locale.setDefault(previous) }
}
}
@@ -0,0 +1,310 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
import kotlin.math.sqrt
class SpatialPoseTest {
private val t=1_000_000_000L
private fun sample(x: Float=0f,y: Float=0f,z: Float=0f,time: Long=t,generation: Long=7,valid: Boolean=true,
rotation: SpatialRotation=SpatialRotation())=SpatialSample(SpatialPose(SpatialVector(x,y,z),rotation),time,generation,valid)
private fun session()=SpatialSession().apply { reset(7,1.6f);accept(sample()) }
private fun near(expected: Float,actual: Float)=assertEquals(expected,actual,0.0001f)
@Test fun sdkPoseKeepsMetersAndCanonicalAxes() {
val p=SpatialPose.fromSdk(floatArrayOf(1f,2f,-3f,1.1f,0f,0f,0f))!!
assertEquals(SpatialVector(1f,2f,-3f),p.position);near(1f,p.rotation.w)
assertNull(SpatialPose.fromSdk(floatArrayOf(0f,0f,0f,0f,0f,0f,0f)))
assertNull(SpatialPose.fromSdk(floatArrayOf(Float.NaN,0f,0f,1f,0f,0f,0f)))
}
@Test fun quaternionRotationAndInverseAgree() {
val q=SpatialRotation(y=sqrt(0.5f),w=sqrt(0.5f))
val p=SpatialPose(SpatialVector(1f,2f,3f),q)
val front=q.apply(SpatialVector(z=-1f));near(-1f,front.x);near(0f,front.z)
val inverse=p.inverse()*p;near(0f,inverse.position.length());near(1f,inverse.rotation.w)
}
@Test fun floorSurvivesCrouchedRecenter() {
val s=session();s.accept(sample(x=.2f,y=-.3f,time=t+10));s.recenter(false,t+10)
near(1.3f,s.view(false)!!.position.y);near(0f,s.view(false)!!.position.x)
s.accept(sample(x=.2f,time=t+20));near(1.6f,s.view(false)!!.position.y)
}
@Test fun screenAndVrOriginsStayIndependent() {
val s=session();s.accept(sample(x=.2f,time=t+10));s.recenter(true,t+10)
near(0f,s.view(true)!!.position.x);near(.2f,s.view(false)!!.position.x)
s.accept(sample(x=.3f,time=t+20));s.recenter(false,t+20)
near(.1f,s.view(true)!!.position.x);near(0f,s.view(false)!!.position.x)
}
@Test fun screenRecenterPreservesRecliningRotation() {
val s=SpatialSession();s.reset(7,1.6f)
val tilt=SpatialRotation(x=sqrt(.5f),w=sqrt(.5f))
s.accept(sample(rotation=tilt));near(1f,s.view(true)!!.rotation.w)
near(tilt.x,s.view(false)!!.rotation.x)
}
@Test fun staleHeadFreezesViewAndRejectsOldConnection() {
val s=session();s.accept(sample(x=.1f,time=t+10));val last=s.view(false)
assertFalse(s.accept(sample(x=99f,time=t+20,generation=6)))
s.accept(sample(time=t+20,valid=false));assertEquals(last,s.view(false));assertFalse(s.valid(t+21))
s.accept(sample(x=.1f,time=t+30));assertFalse(s.valid(t+100_000_031))
assertFalse(s.accept(sample(x=Float.NaN,time=t+40)));assertEquals(last,s.view(false))
}
@Test fun discontinuityRequiresExplicitRecovery() {
val s=session();assertFalse(s.accept(sample(x=5f,time=t+10)))
assertTrue(s.needsRecenter);assertFalse(s.valid(t+10));near(0f,s.view(false)!!.position.x)
s.recenter(false,t+10);assertTrue(s.recenterPending);assertFalse(s.valid(t+10))
for (i in 1..6) s.accept(sample(x=5f,time=t+i*50_000_000L))
assertTrue(s.valid(t+300_000_000));near(0f,s.view(false)!!.position.x)
s.reset(8,1.6f,true);s.accept(sample(generation=8,time=t+400_000_000));assertFalse(s.valid(t+400_000_000))
s.recenter(false,t+400_000_000)
for (i in 1..6) s.accept(sample(generation=8,time=t+400_000_000+i*50_000_000L))
assertTrue(s.valid(t+700_000_000))
}
@Test fun recenterDuringLostTrackingWaitsForSteadySamplesInsteadOfDroppingTheRequest() {
val s=session();s.accept(sample(time=t+10,valid=false));val frozen=s.view(false)
s.recenter(false,t+20);assertTrue(s.recenterPending)
s.accept(sample(x=.2f,time=t+50_000_000))
assertFalse(s.valid(t+50_000_000));assertEquals(frozen,s.view(false))
for(i in 2..6) s.accept(sample(x=.2f,time=t+i*50_000_000L))
assertFalse(s.recenterPending);assertTrue(s.valid(t+300_000_000));near(0f,s.view(false)!!.position.x)
near(1.6f,s.view(false)!!.position.y)
}
@Test fun staleRecenterWaitsAndRepeatedTapsDoNotRestartTheWait() {
val s=session();s.recenter(true,t+200_000_000);assertTrue(s.recenterPending)
s.accept(sample(x=.2f,time=t+250_000_000))
s.recenter(true,t+250_000_000)
for(i in 1..5) s.accept(sample(x=.2f,time=t+250_000_000+i*50_000_000L))
assertFalse(s.recenterPending);near(0f,s.view(true)!!.position.x)
near(.2f,s.view(false)!!.position.x)
}
@Test fun unstableOrInterruptedRecoveryCannotAcceptANewOrigin() {
val s=session();s.accept(sample(x=5f,time=t+10));s.recenter(false,t+10)
for(i in 1..8) s.accept(sample(x=5f+(i%2)*.1f,time=t+i*50_000_000L))
assertTrue(s.recenterPending);assertTrue(s.needsRecenter)
s.accept(sample(x=5f,time=t+450_000_000))
s.accept(sample(x=5f,time=t+500_000_000,valid=false))
s.accept(sample(x=5f,time=t+550_000_000))
assertTrue(s.recenterPending)
for(i in 1..5) s.accept(sample(x=5f,time=t+550_000_000+i*50_000_000L))
assertFalse(s.recenterPending);assertTrue(s.valid(t+800_000_000))
}
@Test fun disconnectCancelsQueuedRecenterAndOldSamplesCannotCompleteIt() {
val s=session();s.recenter(false,t+200_000_000);assertTrue(s.recenterPending)
s.reset(8,1.6f,true);assertFalse(s.recenterPending)
for(i in 1..10) s.accept(sample(time=t+i*50_000_000L))
assertTrue(s.needsRecenter);assertNull(s.latest())
s.accept(sample(generation=8,time=t+600_000_000));assertFalse(s.valid(t+600_000_000))
}
@Test fun recoverableQuaternionScaleDoesNotCreateFalseDiscontinuities() {
val s=session()
for(i in 1..4) assertTrue(s.accept(sample(time=t+i,rotation=SpatialRotation(w=.8f))))
assertFalse(s.needsRecenter);near(1f,s.latest()!!.pose.rotation.w)
}
@Test fun calibrationFrameChangesOnlyWhenTheTrackingFrameChanges() {
val s=session();val frame=s.trackingFrameGeneration
s.recenter(false,t);assertEquals(frame,s.trackingFrameGeneration)
s.accept(sample(x=5f,time=t+10));assertEquals(frame+1,s.trackingFrameGeneration)
s.accept(sample(x=5f,time=t+20));assertEquals(frame+1,s.trackingFrameGeneration)
s.reset(8,1.6f,true);assertEquals(frame+2,s.trackingFrameGeneration)
}
@Test fun captureRemainsValidWhenHeadPollingAdvancesDuringBoardDetection() {
val s=session();val frame=s.trackingFrameGeneration
val detectionStarted=t+1_000_000L
s.accept(sample(x=.01f,time=t+20_000_000L))
assertFalse(s.valid(detectionStarted))
assertTrue(s.isCurrentTrackingFrame(7,frame) { t+25_000_000L })
}
@Test fun captureCompletionStillRejectsStaleChangedAndDisconnectedTracking() {
val s=session();val frame=s.trackingFrameGeneration
assertFalse(s.isCurrentTrackingFrame(7,frame) { t+100_000_001L })
s.accept(sample(x=5f,time=t+10));assertFalse(s.isCurrentTrackingFrame(7,frame) { t+20 })
s.recenter(false,t+20)
for(i in 1..6) s.accept(sample(x=5f,time=t+i*50_000_000L))
assertTrue(s.valid(t+300_000_000L))
assertFalse(s.isCurrentTrackingFrame(7,frame) { t+300_000_000L })
s.reset(8,1.6f);s.accept(sample(generation=8,time=t+400_000_000L))
assertFalse(s.isCurrentTrackingFrame(7,frame) { t+400_000_000L })
}
@Test fun newerHeadDoesNotRefreshOlderHand() {
val s=session();s.setHands(7,SpatialHand(SpatialPose(),t,true,1f,true),SpatialHand())
s.accept(sample(time=t+80_000_000))
s.accept(sample(time=t+150_000_000));assertTrue(s.hand(0,t+200_000_000).valid)
assertEquals(t,s.hand(0,t+200_000_000).timeNs)
assertFalse(s.hand(0,t+200_000_001).valid)
s.recenter(false,t+200_000_001);assertFalse(s.hand(0,t+200_000_001).valid)
s.reset(8,1.6f);s.setHands(7,SpatialHand(timeNs=t,valid=true),SpatialHand());assertFalse(s.hand(0,t).valid)
}
private fun heldHand(time: Long = t) = SpatialHand(timeNs=time,valid=true,trigger=1f,grip=true)
private fun epochs(session: SpatialSession) = List(4) { (session.inputEpochs() ushr (it*8)) and 0xff }
@Test fun overwrittenHandLossRemainsVisibleAfterHeldGestureReturns() {
val s=session();s.setHands(7,heldHand(),heldHand())
s.setHands(7,SpatialHand(),heldHand(t+10))
s.setHands(7,heldHand(t+20),heldHand(t+20))
assertEquals(listOf(1,1,0,0),epochs(s))
assertTrue(s.hand(0,t+20).valid);assertTrue(s.hand(0,t+20).grip)
assertEquals(listOf(1,1,0,0),epochs(s))
}
@Test fun triggerAndGripLossEpochsAreIndependentForBothHands() {
val s=session();s.setHands(7,heldHand(),heldHand())
s.setHands(7,heldHand(t+10).copy(triggerValid=false),heldHand(t+10))
assertEquals(listOf(1,0,0,0),epochs(s))
assertTrue(s.hand(0,t+10).gripValid)
s.setHands(7,heldHand(t+20).copy(gripValid=false),heldHand(t+20).copy(triggerValid=false))
assertEquals(listOf(1,1,1,0),epochs(s))
s.setHands(7,heldHand(t+30).copy(gripValid=false),heldHand(t+30).copy(triggerValid=false))
assertEquals(listOf(1,1,1,0),epochs(s))
assertFalse(s.hand(0,t+30).gripValid);assertTrue(s.hand(0,t+30).triggerValid)
}
@Test fun overwrittenHeadLossDoesNotLoseTheInputReset() {
val s=session();s.setHands(7,heldHand(),heldHand())
s.accept(sample(time=t+10,valid=false))
s.accept(sample(time=t+20))
s.setHands(7,heldHand(t+20),heldHand(t+20))
assertEquals(listOf(1,1,1,1),epochs(s))
assertTrue(s.hand(0,t+20).triggerValid)
}
@Test fun headGapClearsCachedHandsEvenWithoutAnInvalidSnapshot() {
val s=session();s.setHands(7,heldHand(),heldHand())
s.accept(sample(time=t+100_000_001))
assertFalse(s.hand(0,t+100_000_001).valid)
assertEquals(listOf(1,1,1,1),epochs(s))
s.setHands(7,heldHand(t+110_000_000),heldHand(t+110_000_000))
assertTrue(s.hand(0,t+110_000_000).valid)
assertEquals(listOf(1,1,1,1),epochs(s))
}
@Test fun latePreLossCaptureCannotRearmAnInputAfterHeadRecovery() {
val s=session();s.setHands(7,heldHand(),heldHand())
s.accept(sample(time=t+20,valid=false));s.accept(sample(time=t+30))
val released=heldHand(t+10).copy(trigger=0f,grip=false)
s.setHands(7,released,released)
val late=s.hand(0,t+30)
assertTrue(late.valid);assertFalse(late.triggerValid);assertFalse(late.gripValid)
assertEquals(listOf(1,1,1,1),epochs(s))
s.setHands(7,released.copy(timeNs=t+40),released.copy(timeNs=t+40))
assertTrue(s.hand(0,t+40).triggerValid);assertTrue(s.hand(0,t+40).gripValid)
assertEquals(listOf(1,1,1,1),epochs(s))
}
@Test fun freshReplacementAfterLongHandGapStillAdvancesResetEpoch() {
val s=session();s.setHands(7,heldHand(),heldHand())
for(i in 1..5) s.accept(sample(time=t+i*50_000_000))
s.setHands(7,heldHand(t+250_000_000),heldHand(t+250_000_000))
assertTrue(s.hand(0,t+250_000_000).valid)
assertEquals(listOf(1,1,1,1),epochs(s))
}
@Test fun handExpiryAndRepeatedInvalidPollsOnlyIncrementOnce() {
val s=session();s.setHands(7,heldHand(),SpatialHand())
for(i in 1..4) s.accept(sample(time=t+i*50_000_000))
assertTrue(s.hand(0,t+200_000_000).valid)
repeat(4) { assertFalse(s.hand(0,t+200_000_001+it).valid) }
assertEquals(listOf(1,1,0,0),epochs(s))
s.setHands(7,heldHand(t+210_000_000),SpatialHand())
assertTrue(s.hand(0,t+210_000_000).valid)
assertEquals(listOf(1,1,0,0),epochs(s))
}
@Test fun headExpiryThenDelayedHeadSampleDoesNotDoubleCountLoss() {
val s=session();s.setHands(7,heldHand(),heldHand())
for(i in 0..1) assertFalse(s.hand(i,t+100_000_001).valid)
assertEquals(listOf(1,1,1,1),epochs(s))
s.accept(sample(time=t+150_000_000))
s.setHands(7,heldHand(t+160_000_000),heldHand(t+160_000_000))
assertEquals(listOf(1,1,1,1),epochs(s))
}
@Test fun disabledHandsReleaseOnceAndWrongGenerationDoesNotAffectCurrentHands() {
val s=session();s.setHands(7,heldHand(),heldHand())
s.setHands(6,SpatialHand(),SpatialHand())
assertTrue(s.hand(0,t).valid);assertEquals(listOf(0,0,0,0),epochs(s))
repeat(3) { s.setHands(7,SpatialHand(),SpatialHand()) }
assertEquals(listOf(1,1,1,1),epochs(s))
s.reset(8,1.6f)
assertEquals(0,s.inputEpochs())
}
@Test fun invalidTriggerValueOnlyInvalidatesItsOwnGestureEpoch() {
val s=session();s.setHands(7,heldHand(),heldHand())
s.setHands(7,heldHand(t+10).copy(trigger=Float.NaN),heldHand(t+10))
assertEquals(listOf(1,0,0,0),epochs(s))
assertFalse(s.hand(0,t+10).triggerValid);assertTrue(s.hand(0,t+10).gripValid)
}
@Test fun eachPackedEpochWrapsWithinItsOwnByte() {
val s=session()
repeat(255) {
s.setHands(7,heldHand(t+it*2),heldHand(t+it*2))
s.setHands(7,SpatialHand(),SpatialHand())
}
assertEquals(listOf(255,255,255,255),epochs(s));assertEquals(-1,s.inputEpochs())
s.setHands(7,heldHand(t+512),heldHand(t+512));s.setHands(7,SpatialHand(),SpatialHand())
assertEquals(0,s.inputEpochs())
}
@Test fun historyNeverCrossesReconnectOrLargeTimeGap() {
val s=session();assertNotNull(s.poseAt(t+4_000_000,7));assertNull(s.poseAt(t+20_000_000,7))
s.reset(8,1.6f);assertNull(s.poseAt(t,7))
}
@Test fun cameraClockWarmsUpAndRejectsResetAndJitter() {
val clock=CameraClock();val offset=10_000_000_000L
for(i in 1..15) assertNull(clock.map(i*40_000_000L,offset+i*40_000_000L))
assertEquals(offset+640_000_000L,clock.map(640_000_000L,offset+640_000_000L))
assertNull(clock.map(1,offset+1))
val bad=CameraClock()
for(i in 1..30) assertNull(bad.map(i*40_000_000L,offset+i*40_000_000L+(i%2)*30_000_000L))
}
@Test fun halfRateCameraClockRetainsSourceTimeThroughSkippedPairs() {
val clock=CameraClock();val offset=10_000_000_000L
for(i in 1..15) assertNull(clock.map(i*80_000_000L,offset+i*80_000_000L))
assertEquals(offset+1_280_000_000L,clock.map(1_280_000_000L,offset+1_280_000_000L))
assertEquals(offset+1_440_000_000L,clock.map(1_440_000_000L,offset+1_440_000_000L))
assertNull(clock.map(1,offset+1))
}
@Test fun cameraClockKeepsAlignedMappingAfterLongSkippedGaps() {
val offset=10_000_000_000L
for(gap in listOf(240_000_000L,1_000_000_000L)) {
val clock=CameraClock()
for(i in 1..16) clock.map(i*80_000_000L,offset+i*80_000_000L)
val source=1_280_000_000L+gap
assertEquals(offset+source,clock.map(source,offset+source))
assertEquals(offset+source+80_000_000L,clock.map(source+80_000_000L,offset+source+80_000_000L))
}
}
@Test fun cameraClockRewarmsAfterSourceOrReceiptStopsOrReverses() {
val offset=10_000_000_000L;val end=1_280_000_000L
val resets=listOf(1L to offset+end+80_000_000L,
end to offset+end+80_000_000L,
end+80_000_000L to 1L,
end+80_000_000L to offset+end)
for((source,receipt) in resets) {
val clock=CameraClock()
for(i in 1..16) clock.map(i*80_000_000L,offset+i*80_000_000L)
for(i in 0..14) assertNull(clock.map(source+i*80_000_000L,receipt+i*80_000_000L))
assertEquals(receipt+1_200_000_000L,clock.map(source+1_200_000_000L,receipt+1_200_000_000L))
}
}
@Test fun cameraClockRewarmsAfterOffsetJumpAcrossSkippedFrames() {
val offset=10_000_000_000L
for(gap in listOf(240_000_000L,1_000_000_000L)) for(jump in listOf(-20_000_001L,20_000_001L)) {
val clock=CameraClock()
for(i in 1..16) clock.map(i*80_000_000L,offset+i*80_000_000L)
val source=1_280_000_000L+gap;val receipt=source+offset+jump
for(i in 0..14) assertNull(clock.map(source+i*80_000_000L,receipt+i*80_000_000L))
assertEquals(receipt+1_200_000_000L,clock.map(source+1_200_000_000L,receipt+1_200_000_000L))
}
}
@Test fun cameraClockRetainsMappingWithBoundedJitterAcrossSkippedFrames() {
val clock=CameraClock();val offset=10_000_000_000L
for(i in 1..16) clock.map(i*80_000_000L,offset+i*80_000_000L+(i%2)*20_000_000L)
assertEquals(offset+1_520_000_000L,clock.map(1_520_000_000L,offset+1_540_000_000L))
assertEquals(offset+2_520_000_000L,clock.map(2_520_000_000L,offset+2_520_000_000L))
assertNull(clock.map(2_760_000_000L,offset+2_780_000_001L))
}
@Test fun cameraClockRetainsMappingThroughIsolatedShortGapReceiptJitter() {
val clock=CameraClock();val offset=10_000_000_000L
for(i in 1..16) clock.map(i*80_000_000L,offset+i*80_000_000L)
assertEquals(offset+1_360_000_000L,clock.map(1_360_000_000L,offset+1_390_000_000L))
assertEquals(offset+1_440_000_000L,clock.map(1_440_000_000L,offset+1_440_000_000L))
}
@Test fun cameraClockInvalidTimestampRequiresFreshWarmup() {
val offset=10_000_000_000L
for((source,receipt) in listOf(0L to offset,-1L to offset,1L to 0L,1L to -1L)) {
val clock=CameraClock()
for(i in 1..16) clock.map(i*80_000_000L,offset+i*80_000_000L)
assertNull(clock.map(source,receipt))
for(i in 17..31) assertNull(clock.map(i*80_000_000L,offset+i*80_000_000L))
assertEquals(offset+2_560_000_000L,clock.map(2_560_000_000L,offset+2_560_000_000L))
}
}
}
@@ -0,0 +1,68 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class SteamVrSpatialGateTest {
@Test fun launchWaitsForRunningThenTheEntireSettleInterval() {
val gate = SteamVrSpatialGate()
assertTrue(gate.spatialEnabled(true, 0))
gate.prepare()
assertFalse(gate.spatialEnabled(true, 60_000))
gate.setRunning(false, 60_000)
assertFalse(gate.spatialEnabled(true, 60_000))
gate.setRunning(true, 60_000)
assertFalse(gate.spatialEnabled(true, 61_999))
assertTrue(gate.spatialEnabled(true, 62_000))
assertFalse(gate.spatialEnabled(false, 62_000))
}
@Test fun repeatedRunningAndActivityPreparationDoNotMoveTheDeadline() {
val gate = SteamVrSpatialGate()
gate.prepare()
gate.setRunning(true, 100)
gate.prepare()
gate.setRunning(true, 1_900)
assertEquals(2_100L, gate.deadline)
assertTrue(gate.spatialEnabled(true, 2_100))
gate.prepare()
gate.setRunning(true, 10_000)
assertTrue(gate.spatialEnabled(true, 10_000))
}
@Test fun explicitCancelRestoresSavedTrackingBeforeRunningAndDuringSettling() {
val gate = SteamVrSpatialGate()
gate.prepare()
gate.cancel()
assertTrue(gate.spatialEnabled(true, 100))
assertFalse(gate.spatialEnabled(false, 100))
gate.prepare()
gate.setRunning(true, 200)
gate.cancel()
assertNull(gate.deadline)
assertTrue(gate.spatialEnabled(true, 201))
assertFalse(gate.spatialEnabled(false, 10_000))
}
@Test fun stopAndNewLaunchCannotReuseAnEarlierDeadline() {
val gate = SteamVrSpatialGate()
gate.prepare()
gate.setRunning(true, 100)
gate.setRunning(false, 200)
assertTrue(gate.spatialEnabled(true, 200))
gate.prepare()
assertFalse(gate.spatialEnabled(true, 2_100))
gate.setRunning(false, 2_100)
assertFalse(gate.spatialEnabled(true, 2_100))
gate.setRunning(true, 3_000)
assertFalse(gate.spatialEnabled(true, 4_999))
assertTrue(gate.spatialEnabled(true, 5_000))
}
@Test fun discoveringAnAlreadyRunningSessionStillAllowsSettling() {
val gate = SteamVrSpatialGate()
gate.setRunning(true, 100)
assertFalse(gate.spatialEnabled(true, 2_099))
assertTrue(gate.spatialEnabled(true, 2_100))
}
}
@@ -0,0 +1,89 @@
package com.droiddeck.launcher.glasses
import org.json.JSONObject
import org.junit.Assert.*
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 = [28])
class StereoCalibrationProfileTest {
private fun base() = RuntimeEnvironment.getApplication().assets.open(StereoCalibrationProfile.BASE_ASSET)
.bufferedReader().use { it.readText() }
private fun device(verified: Boolean = true) = JSONObject(base()).put("identity", "my-glasses")
.put("verified", verified).toString()
private fun select(saved: String? = null, identity: String? = "my-glasses", width: Int = 640, height: Int = 480) =
StereoCalibrationProfile.select(saved, ::base, identity, width, height)
@Test fun newGlassesUseSharedGeometryWithoutClaimingIndividualValidation() {
val profile = select()!!
assertEquals("my-glasses", profile.identity)
assertTrue(profile.bundledBase)
assertFalse(profile.verified)
assertEquals(1.1209395390660726, profile.error, 0.0)
assertEquals(226.0499636040297, profile.matrices[0].values[0], 0.0)
assertEquals(-0.05607918f, profile.cameraToHead.position.x, 0f)
}
@Test fun unknownSerialCanUseTheModelBase() {
val profile = select(identity = null)!!
assertEquals(StereoCalibrationProfile.BASE_IDENTITY, profile.identity)
assertTrue(profile.bundledBase)
assertFalse(profile.verified)
}
@Test fun savedDeviceProfileWinsWithoutReadingTheAsset() {
val profile = StereoCalibrationProfile.select(device(), { error("Base must not be read") }, "my-glasses", 640, 480)!!
assertFalse(profile.bundledBase)
assertTrue(profile.verified)
}
@Test fun unfinishedPersonalCalibrationStillRequiresDistanceValidation() {
val profile = select(device(verified = false))!!
assertFalse(profile.bundledBase)
assertFalse(profile.verified)
}
@Test fun foreignOrCorruptDeviceProfileFallsBackToBase() {
assertTrue(select(JSONObject(device()).put("identity", "other-glasses").toString())!!.bundledBase)
assertTrue(select("not json")!!.bundledBase)
}
@Test fun otherCameraGeometryDoesNotUseTheBase() {
assertNull(select(width = 1280, height = 960))
assertNull(select(width = 480, height = 640))
}
@Test fun baseRequiresTheCorrectModelAndCameraPair() {
for ((key, value) in listOf("deviceModel" to "VITURE Luma Pro", "cameraPair" to "left1-right1", "identity" to "device-serial")) {
val text = JSONObject(base()).put(key, value).toString()
assertNull(StereoCalibrationProfile.select(null, { text }, "my-glasses", 640, 480))
}
}
@Test fun badLensDimensionsAndInvalidFitsAreRejectedBeforeNativeAllocation() {
for (name in listOf("k1", "d1", "k2", "d2", "r", "t")) {
val data = JSONObject(base())
data.getJSONObject(name).put("rows", 2)
assertNull(StereoCalibrationProfile.parse(data.toString(), StereoCalibrationProfile.BASE_IDENTITY, 640, 480, true))
}
for (error in listOf(-1.0, 2.01)) {
val data = JSONObject(base()).put("error", error)
assertNull(StereoCalibrationProfile.parse(data.toString(), StereoCalibrationProfile.BASE_IDENTITY, 640, 480, true))
}
}
@Test fun missingAssetAndNoDeviceProfileRequiresCalibration() {
assertNull(StereoCalibrationProfile.select(null, { null }, "my-glasses", 640, 480))
}
@Test fun shippedBaseContainsNoSourceSerialOrFalseValidationClaim() {
val data = JSONObject(base())
assertEquals(StereoCalibrationProfile.BASE_IDENTITY, data.getString("identity"))
assertFalse(data.getBoolean("verified"))
assertTrue(data.getJSONObject("sourceValidation").getBoolean("sourceDeviceVerified"))
}
}
@@ -0,0 +1,87 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
import kotlin.math.cos
import kotlin.math.sin
class StereoFingerGesturesTest {
private fun open(): MutableList<SpatialVector> {
val p=MutableList(21) { SpatialVector(320f,240f) }
p[4]=SpatialVector(390f,190f)
for((base,x) in listOf(5 to 355f,9 to 330f,13 to 305f,17 to 280f)) {
for(j in 0..3) p[base+j]=SpatialVector(x,180f-25f*j)
}
return p
}
private fun curl(p: MutableList<SpatialVector>,reach: Float=1f) = p.apply {
for(base in listOf(9,13,17)) this[base+3]=this[0]+(this[base]-this[0])*reach
}
private fun transform(p: List<SpatialVector>,angle: Float,scale: Float,mirror: Boolean) = p.map {
val x=(if(mirror) -it.x else it.x)*scale
val y=it.y*scale
SpatialVector(x*cos(angle)-y*sin(angle)+700f,x*sin(angle)+y*cos(angle)-80f)
}
@Test fun openingAndClosingAreIndependentOfImageScaleRotationAndHandedness() {
for(mirror in listOf(false,true)) for(angle in listOf(0f,.7f,2.8f)) {
val closed=curl(open()).apply { this[4]=this[8] }
val result=StereoFingerGestures.estimate(transform(closed,angle,1.5f,mirror),
transform(closed,angle+.12f,.7f,mirror),false)
assertTrue(result.gripValid);assertTrue(result.grip)
assertTrue(result.triggerValid);assertEquals(1f,result.trigger,0f)
val released=StereoFingerGestures.estimate(transform(open(),angle,1.5f,mirror),
transform(open(),angle+.12f,.7f,mirror),true)
assertTrue(released.gripValid);assertFalse(released.grip)
assertTrue(released.triggerValid);assertEquals(0f,released.trigger,0f)
}
}
@Test fun curlThresholdsProvideObservedHysteresisAndRelease() {
val partial=curl(open(),1.4f)
val idle=StereoFingerGestures.estimate(partial,partial,false)
val held=StereoFingerGestures.estimate(partial,partial,true)
assertTrue(idle.gripValid);assertFalse(idle.grip)
assertTrue(held.gripValid);assertTrue(held.grip)
val opening=curl(open(),1.6f)
assertFalse(StereoFingerGestures.estimate(opening,opening,true).grip)
val two=curl(open()).apply { for(i in 17..20) this[i]=open()[i] }
assertFalse(StereoFingerGestures.estimate(two,two,false).grip)
assertTrue(StereoFingerGestures.estimate(two,two,true).grip)
}
@Test fun shortStraightProjectedFingersDoNotCountAsCurled() {
val straight=open().apply {
for(base in listOf(9,13,17)) for(j in 1..3) this[base+j]=this[base]+SpatialVector(y=-4.5f*j)
}
val result=StereoFingerGestures.estimate(straight,straight,false)
assertTrue(result.gripValid);assertFalse(result.grip)
}
@Test fun pinchRequiresBothEyesAndUsesTheirMoreOpenEstimate() {
fun pinch(ratio: Float)=open().apply { this[4]=this[8]+SpatialVector(x=75f*ratio) }
val result=StereoFingerGestures.estimate(pinch(.25f),pinch(.30f),false)
assertTrue(result.triggerValid);assertEquals((.55f-.30f)/.35f,result.trigger,.0001f)
val conflict=StereoFingerGestures.estimate(pinch(.25f),pinch(.50f),false)
assertFalse(conflict.triggerValid);assertEquals(0f,conflict.trigger,0f)
assertTrue(conflict.gripValid);assertFalse(conflict.grip)
}
@Test fun conflictingCurlDoesNotReportAnObservedRelease() {
val result=StereoFingerGestures.estimate(curl(open()),open(),true)
assertFalse(result.gripValid);assertFalse(result.grip)
assertTrue(result.triggerValid)
}
@Test fun invalidJointsOnlyInvalidateTheirOwnGesture() {
val badPinch=open().apply { this[4]=SpatialVector(Float.NaN,190f) }
val pinch=StereoFingerGestures.estimate(badPinch,open(),false)
assertFalse(pinch.triggerValid);assertTrue(pinch.gripValid)
val badGrip=open().apply { this[15]=SpatialVector(300f,Float.POSITIVE_INFINITY) }
val grip=StereoFingerGestures.estimate(open(),badGrip,true)
assertTrue(grip.triggerValid);assertFalse(grip.gripValid);assertFalse(grip.grip)
}
@Test fun missingViewsAndDegeneratePalmsCannotArmInputs() {
val flat=open().apply { for(i in listOf(0,5,9,13,17)) this[i]=SpatialVector(i.toFloat(),0f) }
val collapsed=open().apply { this[17]=this[5] }
for(invalid in listOf(null,emptyList(),flat,collapsed)) {
val result=StereoFingerGestures.estimate(open(),invalid,true)
assertFalse(result.triggerValid);assertFalse(result.gripValid)
assertEquals(0f,result.trigger,0f);assertFalse(result.grip)
}
}
}
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.glasses
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.junit.Assert.*
import org.junit.Test
class StereoInferenceRunnerTest {
@Test fun camerasRunConcurrentlyAndRightDetectorKeepsItsOwnerThread() {
StereoInferenceRunner().use { runner ->
val owner=runner.onRight { Thread.currentThread() }
val rightStarted=CountDownLatch(1)
val leftStarted=CountDownLatch(1)
val pair=runner.pair({
leftStarted.countDown()
assertTrue(rightStarted.await(2,TimeUnit.SECONDS))
1
}, {
rightStarted.countDown()
assertTrue(leftStarted.await(2,TimeUnit.SECONDS))
assertSame(owner,Thread.currentThread())
2
})
assertEquals(1 to 2,pair)
assertSame(owner,runner.onRight { Thread.currentThread() })
}
}
@Test fun leftFailureDoesNotReleasePixelsWhileRightStillUsesThem() {
StereoInferenceRunner().use { runner ->
val finished=CountDownLatch(1)
val failure=IllegalStateException("left")
try {
runner.pair({ throw failure }, { Thread.sleep(25);finished.countDown();1 })
fail("Expected inference failure")
} catch(e: IllegalStateException) { assertSame(failure,e) }
assertEquals(0L,finished.count)
}
}
@Test fun rightFailureReachesOwnerAndWorkerCanStillCloseDetector() {
StereoInferenceRunner().use { runner ->
val failure=IllegalStateException("right")
try {
runner.pair({ 1 }, { throw failure })
fail("Expected inference failure")
} catch(e: IllegalStateException) { assertSame(failure,e) }
assertTrue(runner.onRight { true })
}
}
@Test fun shutdownInterruptionWaitsForInferenceBeforeReturningBuffers() {
StereoInferenceRunner().use { runner ->
val owner=Executors.newSingleThreadExecutor()
val running=CountDownLatch(1);val release=CountDownLatch(1)
try {
val result=owner.submit<Boolean> {
Thread.currentThread().interrupt()
assertEquals(1 to 2,runner.pair({ 1 }, {
running.countDown();check(release.await(2,TimeUnit.SECONDS));2
}))
Thread.interrupted()
}
assertTrue(running.await(2,TimeUnit.SECONDS))
assertFalse(result.isDone)
release.countDown()
assertTrue(result.get(2,TimeUnit.SECONDS))
} finally { release.countDown();owner.shutdownNow() }
}
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class StereoPointValidationTest {
private val p1=doubleArrayOf(400.0,0.0,320.0,0.0, 0.0,400.0,240.0,0.0, 0.0,0.0,1.0,0.0)
private val p2=p1.copyOf().apply { this[3]=-24.0 }
private val point=doubleArrayOf(0.0,0.0,.5,1.0)
private val left=doubleArrayOf(320.0,240.0)
private val right=doubleArrayOf(272.0,240.0)
@Test fun metricDepthAndReprojectionThresholdAreUnchanged() {
val result=StereoPointValidation.reconstruct(point,left,right,p1,p2)!!
assertEquals(.5f,result.z,0f)
assertNotNull(StereoPointValidation.reconstruct(point,left,doubleArrayOf(275.0,240.0),p1,p2))
assertNull(StereoPointValidation.reconstruct(point,left,doubleArrayOf(275.01,240.0),p1,p2))
}
@Test fun aRejectedLandmarkDoesNotRemoveItsValidNeighbors() {
val observations=listOf(left,doubleArrayOf(Double.NaN,240.0),left)
val points=observations.map { StereoPointValidation.reconstruct(point,it,right,p1,p2) }
assertNotNull(points[0]);assertNull(points[1]);assertNotNull(points[2])
}
@Test fun invalidDepthAndProjectionNeverProduceValidPoints() {
for(z in listOf(-.5,.149,1.501,Double.NaN,Double.POSITIVE_INFINITY))
assertNull(StereoPointValidation.reconstruct(doubleArrayOf(0.0,0.0,z,1.0),left,right,p1,p2))
assertNull(StereoPointValidation.reconstruct(point.copyOf().apply { this[3]=0.0 },left,right,p1,p2))
assertNull(StereoPointValidation.reconstruct(point,left,right,p1,p2.copyOf().apply { this[10]=-1.0 }))
assertNull(StereoPointValidation.reconstruct(point,left,right,p1,p2.copyOf().apply { this[0]=Double.NaN }))
}
}
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
class TrackingRecoveryTest {
@Test fun periodicStatusRefreshDetectsExpiryWithoutAnotherPoseCallback() {
val time=1_000_000_000L
val session=SpatialTracking.session
try {
session.reset(91,1.6f)
session.accept(SpatialSample(SpatialPose(),time,91,true))
SpatialTracking.refreshStatus(time)
assertTrue(SpatialTracking.status.value.headFresh)
assertNull(TrackingRecovery.forSession(true,true,SpatialTracking.status.value))
SpatialTracking.refreshStatus(time+100_000_001)
assertFalse(SpatialTracking.status.value.headFresh)
assertEquals(TrackingRecovery.LOST,TrackingRecovery.forSession(true,true,SpatialTracking.status.value))
session.accept(SpatialSample(SpatialPose(),time+110_000_000,91,true))
SpatialTracking.refreshStatus(time+110_000_000)
assertNull(TrackingRecovery.forSession(true,true,SpatialTracking.status.value))
} finally {
session.reset(92,1.6f)
SpatialTracking.refreshStatus(time+200_000_000)
}
}
@Test fun healthyAndNonSpatialSessionsNeverShowRecovery() {
assertNull(TrackingRecovery.forSession(true,true,SpatialTrackingStatus(trackingValid=true,headFresh=true)))
assertNull(TrackingRecovery.forSession(false,false,SpatialTrackingStatus()))
assertEquals(TrackingRecovery.DISCONNECTED,TrackingRecovery.forSession(true,false,SpatialTrackingStatus(trackingValid=true)))
}
@Test fun pendingRecenterStillRequiresLookingAroundUntilHeadTrackingReturns() {
val pending=SpatialTrackingStatus(recenterPending=true,needsRecenter=true)
assertEquals(TrackingRecovery.LOST,TrackingRecovery.forSession(true,true,pending))
assertEquals(TrackingRecovery.STABILIZING,TrackingRecovery.forSession(true,true,pending.copy(headFresh=true)))
assertNull(TrackingRecovery.forSession(true,true,pending.copy(headFresh=true,trackingValid=true,recenterPending=false,needsRecenter=false)))
}
@Test fun newTrackingFrameExplainsTheRequiredRecenter() {
val changed=SpatialTrackingStatus(needsRecenter=true,headFresh=true)
assertEquals(TrackingRecovery.RECENTER,TrackingRecovery.forSession(true,true,changed))
assertEquals(TrackingRecovery.LOST,TrackingRecovery.forSession(true,true,changed.copy(headFresh=false)))
}
}
@@ -0,0 +1,49 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class UvcStreamHealthTest {
private fun sample(frames: Long = 901, lastMs: Long = 30990, endMs: Long = 31000,
maximumGapMs: Long = 34) = LongArray(14).apply {
this[6]=lastMs*1_000_000
this[7]=1_000_000_000
this[8]=maximumGapMs*1_000_000
this[9]=frames
this[12]=endMs*1_000_000
this[13]=(endMs-lastMs)*1_000_000
}
@Test fun sustainedStreamMeasuresEntireWindow() {
val health=UvcStreamHealth.assess(sample(),30,30000)
assertTrue(health.healthy)
assertEquals(30000.0,health.observationMs,0.001)
assertEquals(30.0,health.observedFps,0.001)
}
@Test fun earlyFramesCannotHideLongFinalStall() {
val health=UvcStreamHealth.assess(sample(frames=31,lastMs=2000),30,30000)
assertFalse(health.healthy)
assertEquals(1.0,health.observedFps,0.001)
assertEquals(29000.0,health.maximumGapMs,0.001)
assertFalse(UvcStreamHealth.assess(sample(frames=1,lastMs=1000),30,30000).healthy)
}
@Test fun frameRateCannotHideInterFrameOrFinalGaps() {
assertFalse(UvcStreamHealth.assess(sample(maximumGapMs=500),30,30000).healthy)
assertFalse(UvcStreamHealth.assess(sample(lastMs=30500),30,30000).healthy)
}
@Test fun shortObservationAndLowFrameRateAreUnhealthy() {
assertFalse(UvcStreamHealth.assess(sample(frames=31,lastMs=1990,endMs=2000),30,30000).healthy)
assertFalse(UvcStreamHealth.assess(sample(frames=601),30,30000).healthy)
assertFalse(UvcStreamHealth.assess(sample().apply { this[4]=-1 },30,30000).healthy)
}
@Test fun lowFrameRateAllowsThreeFramePeriods() {
assertTrue(UvcStreamHealth.assess(sample(frames=151,lastMs=30600,maximumGapMs=400),5,30000).healthy)
assertFalse(UvcStreamHealth.assess(sample(frames=151,lastMs=30300,maximumGapMs=700),5,30000).healthy)
}
}
@@ -0,0 +1,192 @@
package com.droiddeck.launcher.glasses
import android.content.Context
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.os.Parcelable
import android.util.Log
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.Assert.fail
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
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
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowLog
import org.robolectric.util.ReflectionHelpers
import org.robolectric.util.ReflectionHelpers.ClassParameter.from
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, shadows = [VitureLinkTest.QueuedConnection::class])
class VitureLinkTest {
private val frames = LinkedBlockingQueue<VitureProtocol.Frame>()
private val imu = LinkedBlockingQueue<ByteArray>()
private var link: VitureLink? = null
private val listener = object : VitureLink.Listener {
override fun onFrame(frame: VitureProtocol.Frame) { frames += frame }
override fun onImu(payload: ByteArray, timeNs: Long) { imu += payload }
override fun onLost() {}
}
@Before fun prepare() {
incoming.clear()
ShadowLog.clear()
}
@After fun close() { link?.close() }
@Test fun framesWithABadChecksumAreDroppedAndCounted() {
val usb = RuntimeEnvironment.getApplication().getSystemService(Context.USB_SERVICE) as UsbManager
val l = VitureLink.open(usb, glasses(), listener)
assertNotNull(l)
link = l
val report = packet(VitureProtocol.MAGIC_REPORT, VitureProtocol.EVENT_BRIGHTNESS, byteArrayOf(6))
val pose = ByteArray(36) { it.toByte() }
val imuPacket = packet(VitureProtocol.MAGIC_IMU, 0, pose)
feed(MCU_IN, corrupt(report), report)
feed(IMU_IN, corrupt(imuPacket), imuPacket)
val frame = frames.poll(2, TimeUnit.SECONDS)
assertNotNull(frame)
assertEquals(VitureProtocol.EVENT_BRIGHTNESS, frame!!.msgId)
assertArrayEquals(byteArrayOf(6), frame.payload)
assertArrayEquals(pose, imu.poll(2, TimeUnit.SECONDS))
assertNull(frames.poll(200, TimeUnit.MILLISECONDS))
assertNull(imu.poll(0, TimeUnit.MILLISECONDS))
val transport: GlassesLink = l!!
assertEquals(2L, transport.badFrames)
assertEquals(1, ShadowLog.getLogsForTag("VitureLink").count { it.type == Log.WARN })
}
@Test fun bothReadersDiscardCorruptReportsAndAcceptTheNextValidPacket() {
for (imuEndpoint in listOf(false, true)) {
checkPackets(VitureProtocol.MAGIC_REPORT, imuEndpoint, expectImu = false)
}
}
@Test fun imuReaderDiscardsCorruptPoseAndAcceptsTheNextValidPacket() {
checkPackets(VitureProtocol.MAGIC_IMU, imuEndpoint = true, expectImu = true)
}
private fun checkPackets(magic: Int, imuEndpoint: Boolean, expectImu: Boolean) {
val frames = mutableListOf<VitureProtocol.Frame>()
val poses = mutableListOf<ByteArray>()
val listener = object : VitureLink.Listener {
override fun onFrame(frame: VitureProtocol.Frame) { frames += frame }
override fun onImu(payload: ByteArray, timeNs: Long) { poses += payload }
override fun onLost() { fail("A corrupt packet must not disconnect the link") }
}
val ctor = VitureLink::class.java.getDeclaredConstructor(UsbDeviceConnection::class.java,
UsbInterface::class.java, UsbEndpoint::class.java, UsbEndpoint::class.java,
UsbInterface::class.java, UsbEndpoint::class.java, VitureLink.Listener::class.java)
.apply { isAccessible = true }
val link = ctor.newInstance(Shadow.newInstanceOf(UsbDeviceConnection::class.java),
Shadow.newInstanceOf(UsbInterface::class.java), Shadow.newInstanceOf(UsbEndpoint::class.java),
null, null, null, listener)
val receive = VitureLink::class.java.getDeclaredMethod("onPacket", ByteArray::class.java,
Int::class.javaPrimitiveType, Boolean::class.javaPrimitiveType).apply { isAccessible = true }
val payload = byteArrayOf(0, 0x32)
val valid = VitureProtocol.packet(VitureProtocol.MSG_DISPLAY, payload).also { it[1] = magic.toByte() }
val corrupt = valid.copyOf().also { it[18] = 1 }
assertFalse(VitureProtocol.parse(corrupt, corrupt.size)!!.crcOk)
receive.invoke(link, corrupt, corrupt.size, imuEndpoint)
assertTrue(frames.isEmpty())
assertTrue(poses.isEmpty())
receive.invoke(link, valid, valid.size, imuEndpoint)
assertEquals(if (expectImu) 0 else 1, frames.size)
assertEquals(if (expectImu) 1 else 0, poses.size)
assertArrayEquals(payload, if (expectImu) poses.single() else frames.single().payload)
}
private fun packet(magic: Int, msgId: Int, payload: ByteArray) =
VitureProtocol.packet(msgId, payload).also { it[1] = magic.toByte() }
private fun corrupt(packet: ByteArray) = packet.copyOf().also { it[18] = (it[18].toInt() xor 0x01).toByte() }
private fun feed(address: Int, vararg packets: ByteArray) {
val queue = incoming.getOrPut(address) { LinkedBlockingQueue() }
packets.forEach(queue::put)
}
private fun glasses(): UsbDevice {
fun endpoint(address: Int): UsbEndpoint = ReflectionHelpers.callConstructor(
UsbEndpoint::class.java,
from(Int::class.javaPrimitiveType, address),
from(Int::class.javaPrimitiveType, UsbConstants.USB_ENDPOINT_XFER_INT),
from(Int::class.javaPrimitiveType, VitureProtocol.PACKET_SIZE),
from(Int::class.javaPrimitiveType, 1),
)
fun hid(id: Int, vararg endpoints: UsbEndpoint): UsbInterface = ReflectionHelpers.callConstructor(
UsbInterface::class.java,
from(Int::class.javaPrimitiveType, id),
from(Int::class.javaPrimitiveType, 0),
from(String::class.java, "hid$id"),
from(Int::class.javaPrimitiveType, UsbConstants.USB_CLASS_HID),
from(Int::class.javaPrimitiveType, 0),
from(Int::class.javaPrimitiveType, 0),
).also { hidden(it, "setEndpoints", *endpoints) }
val config: UsbConfiguration = ReflectionHelpers.callConstructor(
UsbConfiguration::class.java,
from(Int::class.javaPrimitiveType, 1),
from(String::class.java, "default"),
from(Int::class.javaPrimitiveType, 0),
from(Int::class.javaPrimitiveType, 250),
)
hidden(config, "setInterfaces", hid(0, endpoint(IMU_IN)), hid(1, endpoint(MCU_IN), endpoint(MCU_OUT)))
return ReflectionHelpers.callConstructor(
UsbDevice::class.java,
from(String::class.java, "/dev/bus/usb/001/002"),
from(Int::class.javaPrimitiveType, VitureProtocol.VENDOR_ID),
from(Int::class.javaPrimitiveType, 0x101d),
from(Int::class.javaPrimitiveType, 0),
from(Int::class.javaPrimitiveType, 0),
from(Int::class.javaPrimitiveType, 0),
from(String::class.java, "VITURE"),
from(String::class.java, "VITURE Pro XR"),
from(String::class.java, "1.0"),
from(String::class.java, "test"),
).also { hidden(it, "setConfigurations", config) }
}
private fun hidden(target: Any, method: String, vararg items: Parcelable) {
ReflectionHelpers.callInstanceMethod<Unit>(target, method, from(Array<Parcelable>::class.java, arrayOf(*items)))
}
@Implements(UsbDeviceConnection::class)
class QueuedConnection {
@Implementation fun claimInterface(intf: UsbInterface, force: Boolean) = true
@Implementation fun releaseInterface(intf: UsbInterface) = true
@Implementation fun bulkTransfer(endpoint: UsbEndpoint, buffer: ByteArray, length: Int, timeout: Int): Int {
if (endpoint.direction == UsbConstants.USB_DIR_OUT) return length
val packet = incoming[endpoint.address]?.poll(timeout.toLong(), TimeUnit.MILLISECONDS) ?: return 0
packet.copyInto(buffer, endIndex = minOf(packet.size, length))
return minOf(packet.size, length)
}
}
companion object {
private const val IMU_IN = 0x81
private const val MCU_IN = 0x82
private const val MCU_OUT = 0x02
private val incoming = ConcurrentHashMap<Int, LinkedBlockingQueue<ByteArray>>()
}
}
@@ -0,0 +1,142 @@
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.assertTrue
import org.junit.Test
import java.nio.ByteBuffer
import kotlin.math.cos
import kotlin.math.sin
class VitureProtocolTest {
private fun u8(b: Byte) = b.toInt() and 0xFF
private fun u16(b: ByteArray, at: Int) = u8(b[at]) or (u8(b[at + 1]) shl 8)
@Test fun crcIsXmodem() {
val check = "123456789".toByteArray()
assertEquals(0x31C3, VitureProtocol.crc16(check, 0, check.size))
}
@Test fun packetLayout() {
val p = VitureProtocol.packet(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(5, 0))
assertEquals(VitureProtocol.PACKET_SIZE, p.size)
assertEquals(0xFF, u8(p[0]))
assertEquals(VitureProtocol.MAGIC_COMMAND, u8(p[1]))
assertEquals(2 + 0x0C, u16(p, 4))
assertEquals(VitureProtocol.MSG_BRIGHTNESS, u16(p, 14))
assertEquals(5, u8(p[18]))
assertEquals(VitureProtocol.crc16(p, 4, u16(p, 4) + 2), u16(p, 2))
for (i in 6 until 14) assertEquals(0, u8(p[i]))
}
@Test fun parseRoundTripsAndChecksCrc() {
val p = VitureProtocol.packet(VitureProtocol.MSG_DISPLAY, byteArrayOf(0x34))
val f = VitureProtocol.parse(p, p.size)
assertNotNull(f)
assertEquals(VitureProtocol.MAGIC_COMMAND, f!!.magic)
assertEquals(VitureProtocol.MSG_DISPLAY, f.msgId)
assertArrayEquals(byteArrayOf(0x34), f.payload)
assertTrue(f.crcOk)
p[18] = 0x31
val badCrc = VitureProtocol.parse(p, p.size)!!
assertFalse(badCrc.crcOk)
assertArrayEquals(byteArrayOf(0x31), badCrc.payload)
}
@Test fun parseAcceptsPaddingOutsideDeclaredFrame() {
val payload = byteArrayOf(0, 0x32)
val p = VitureProtocol.packet(VitureProtocol.MSG_DISPLAY, payload)
val end = 18 + payload.size
p.fill(0x5A, end)
for (size in listOf(end, p.size)) {
val frame = VitureProtocol.parse(p, size)!!
assertArrayEquals(payload, frame.payload)
assertTrue(frame.crcOk)
}
}
@Test fun parseRejectsTruncatedDeclaredFrame() {
val p = VitureProtocol.packet(VitureProtocol.MSG_DISPLAY, byteArrayOf(0, 0x32))
val received = 19
assertNull(VitureProtocol.parse(p, received))
assertNull(VitureProtocol.parse(p.copyOf(received), received))
p[4] = 0xFF.toByte()
p[5] = 0xFF.toByte()
assertNull(VitureProtocol.parse(p, p.size))
}
@Test fun parseRejectsInvalidReceiveSize() {
val p = VitureProtocol.packet(VitureProtocol.MSG_DISPLAY, byteArrayOf(0, 0x32))
assertNull(VitureProtocol.parse(p, p.size + 1))
assertNull(VitureProtocol.parse(p, 17))
assertNull(VitureProtocol.parse(ByteArray(0), 18))
assertNull(VitureProtocol.parse(ByteArray(0), 0))
assertNull(VitureProtocol.parse(p, -1))
}
@Test fun parseReadsRepliesAndRejectsJunk() {
val reply = VitureProtocol.packet(VitureProtocol.MSG_GET_VOLUME, byteArrayOf(0, 5))
reply[1] = VitureProtocol.MAGIC_REPORT.toByte()
val f = VitureProtocol.parse(reply, reply.size)!!
assertEquals(VitureProtocol.MAGIC_REPORT, f.magic)
assertArrayEquals(byteArrayOf(0, 5), f.payload)
assertNull(VitureProtocol.parse(ByteArray(64), 64))
assertNull(VitureProtocol.parse(reply, 8))
val wrongMagic = reply.copyOf().also { it[1] = 0x10 }
assertNull(VitureProtocol.parse(wrongMagic, wrongMagic.size))
}
@Test fun modelsAndModes() {
val pro = VitureProtocol.model(0x101d, "VITURE Pro XR Glasses")!!
assertEquals("VITURE Pro XR", pro.name)
assertEquals(VitureProtocol.Family.PRO, pro.family)
assertTrue(pro.controllable)
assertFalse(pro.sbs90)
assertEquals(0x34, pro.mode(120, false))
assertEquals(0x33, pro.mode(90, false))
assertEquals(0x31, pro.mode(60, false))
assertEquals(0x32, pro.mode(90, true))
assertEquals(0x32, pro.mode(60, true))
val luma = VitureProtocol.model(0x1131, null)!!
assertEquals("VITURE Luma", luma.name)
assertFalse(luma.sbs90)
assertEquals(0x44, luma.mode(120, false))
assertEquals(0x42, luma.mode(90, true))
assertEquals(0x42, luma.mode(60, true))
val ultra = VitureProtocol.model(0x1101, null)!!
assertTrue(ultra.sbs90)
assertEquals(0x45, ultra.mode(90, true))
assertEquals(0x42, ultra.mode(60, true))
assertTrue(VitureProtocol.model(0x1201, null)!!.controllable)
assertTrue(VitureProtocol.model(0x1201, null)!!.needsSdk)
assertNull(VitureProtocol.model(0x9999, "VITURE"))
assertEquals("VITURE One", VitureProtocol.model(0x1011, "Something else")!!.name)
}
@Test fun imuPrefersTheQuaternion() {
val half = Math.toRadians(30.0) / 2
val payload = ByteBuffer.allocate(40)
.putFloat(1f).putFloat(2f).putFloat(3f)
.putFloat(0f).putFloat(0f)
.putFloat(cos(half).toFloat()).putFloat(0f).putFloat(0f).putFloat(sin(half).toFloat())
.array()
val q = VitureProtocol.imuQuaternion(payload)!!
assertArrayEquals(floatArrayOf(0f, 0f, sin(half).toFloat(), cos(half).toFloat()), q, 1e-5f)
}
@Test fun imuFallsBackToEuler() {
val payload = ByteBuffer.allocate(12).putFloat(0f).putFloat(0f).putFloat(30f).array()
val q = VitureProtocol.imuQuaternion(payload)!!
val half = Math.toRadians(30.0) / 2
assertArrayEquals(floatArrayOf(0f, 0f, sin(half).toFloat(), cos(half).toFloat()), q, 1e-5f)
assertNull(VitureProtocol.imuQuaternion(ByteArray(8)))
val nan = ByteBuffer.allocate(12).putFloat(Float.NaN).putFloat(0f).putFloat(0f).array()
assertNull(VitureProtocol.imuQuaternion(nan))
}
}
@@ -0,0 +1,105 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
import kotlin.math.sqrt
import com.droiddeck.launcher.gpu.HeadPose
class VitureSdkTest {
@Test fun spatialIdentityUsesTheFullSdkDigestAndRejectsMissingValues() {
assertNull(VitureSpatialIdentity.fromSerialHash(null))
assertNull(VitureSpatialIdentity.fromSerialHash(ByteArray(32)))
assertNull(VitureSpatialIdentity.fromSerialHash(ByteArray(31) { 1 }))
val digest=ByteArray(32) { it.toByte() }
val id=VitureSpatialIdentity.fromSerialHash(digest)
assertEquals("viture:sn-sha256:000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",id)
assertEquals(id,VitureSpatialIdentity.fromSerialHash(digest.copyOf()))
assertNotEquals(id,VitureSpatialIdentity.fromSerialHash(digest.copyOf().also { it[31]=0xff.toByte() }))
}
@Test fun pro2UsesItsOwnSdkTransportAndDisplayLimits() {
val m = VitureProtocol.sdkModel("Pro 2")!!
assertTrue(m.needsSdk)
assertEquals(VitureProtocol.Family.PRO2, m.family)
assertEquals(0x34, m.mode(120, false))
assertEquals(0x32, m.mode(90, true))
assertFalse(m.sbs90)
assertFalse(m.hasSunblock)
assertEquals(8, m.volumeMax)
assertEquals(50f, m.diagonalFovDeg, 0f)
}
@Test fun ultraUsesSdkWith1200pAnd90HzStereo() {
val m = VitureProtocol.sdkModel("Luma Ultra")!!
assertTrue(m.needsSdk)
assertEquals(0x44, m.mode(120, false))
assertEquals(0x42, m.mode(60, true))
assertEquals(0x45, m.mode(90, true))
assertTrue(m.hasSunblock)
}
@Test fun gen2DoesNotImplyBeastCapabilities() {
val beast = VitureProtocol.sdkModel("Beast")!!
assertTrue(beast.needsSdk)
assertEquals(15, beast.volumeMax)
assertTrue(beast.hasSunblock)
assertFalse(VitureProtocol.sdkModel("Pro")!!.needsSdk)
assertNull(VitureProtocol.sdkModel("Unknown"))
assertNull(VitureProtocol.sdkModel("Mobile Dock"))
}
@Test fun otherGen2DevicesPreserveSdkNwuAxesAndChangeComponentOrder() {
val a = sqrt(0.5f)
assertArrayEquals(floatArrayOf(0f, 0f, a, a),
VitureSdkPose.toGlasses(floatArrayOf(a, 0f, 0f, a), false), 0.00001f)
}
@Test fun pro2AndCarinaSelectOpenGlButOtherGen2ModelsKeepTheirExistingBasis() {
assertTrue(VitureSdkPose.usesOpenGlAxes(false, VitureProtocol.Family.PRO2))
assertTrue(VitureSdkPose.usesOpenGlAxes(true, VitureProtocol.Family.ULTRA))
assertFalse(VitureSdkPose.usesOpenGlAxes(false, VitureProtocol.Family.BEAST))
assertFalse(VitureSdkPose.usesOpenGlAxes(false, VitureProtocol.Family.PRO))
assertFalse(VitureSdkPose.usesOpenGlAxes(false, null))
}
@Test fun pro2YawPitchAndRollReachTheCorrectRendererAxes() {
val openGl = VitureSdkPose.usesOpenGlAxes(false, VitureProtocol.sdkModel("Pro 2")!!.family)
fun screen(wxyz: FloatArray): FloatArray {
val q = VitureSdkPose.toGlasses(wxyz, openGl)!!
return HeadPose.fromGlasses(q[0], q[1], q[2], q[3])
}
val ref = HeadPose.recenter(screen(floatArrayOf(1f, 0f, 0f, 0f)))
val s = kotlin.math.sin(Math.PI / 12).toFloat()
val c = kotlin.math.cos(Math.PI / 12).toFloat()
for ((axis, expected) in listOf(
2 to floatArrayOf(-0.5f, 0f, -0.8660254f), // Observed left turn: positive Y.
1 to floatArrayOf(0f, 0.5f, -0.8660254f), // Observed upward look: positive X.
3 to floatArrayOf(-0.5f, 0.8660254f, 0f),
)) {
val q = floatArrayOf(c, 0f, 0f, 0f).apply { this[axis] = s }
val view = HeadPose.relative(ref, screen(q))
val direction = if (axis == 3) floatArrayOf(0f, 1f, 0f) else floatArrayOf(0f, 0f, -1f)
assertArrayEquals(expected, HeadPose.apply(view, direction), 0.001f)
}
}
@Test fun ultraOpenGlAxesMatchExistingGlassesHeadTracker() {
val a = sqrt(0.5f)
// OpenGL Y yaw maps to NWU Z; OpenGL X pitch maps to negative NWU Y.
assertArrayEquals(floatArrayOf(0f, 0f, a, a),
VitureSdkPose.toGlasses(floatArrayOf(a, 0f, a, 0f), true), 0.00001f)
assertArrayEquals(floatArrayOf(0f, -a, 0f, a),
VitureSdkPose.toGlasses(floatArrayOf(a, a, 0f, 0f), true), 0.00001f)
assertArrayEquals(floatArrayOf(-a, 0f, 0f, a),
VitureSdkPose.toGlasses(floatArrayOf(a, 0f, 0f, a), true), 0.00001f)
}
@Test fun invalidOrUninitializedSdkPosesNeverReachTheRenderer() {
for (q in listOf(FloatArray(4), floatArrayOf(Float.NaN, 0f, 0f, 0f),
floatArrayOf(Float.POSITIVE_INFINITY, 0f, 0f, 0f), floatArrayOf(3f, 0f, 0f, 0f), FloatArray(7))) {
assertNull(VitureSdkPose.toGlasses(q, false))
assertNull(VitureSdkPose.toGlasses(q, true))
}
assertArrayEquals(floatArrayOf(0f, 0f, 0f, 1f),
VitureSdkPose.toGlasses(floatArrayOf(1.1f, 0f, 0f, 0f), true), 0.00001f)
}
}
@@ -0,0 +1,149 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class XrealLinkTest {
private class Input : InputStream() {
private val bytes = LinkedBlockingQueue<Int>()
@Volatile private var closed = false
fun add(value: ByteArray) { value.forEach { bytes.add(it.toInt() and 255) } }
override fun read(): Int = if (closed && bytes.isEmpty()) -1 else bytes.take()
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (len == 0) return 0
val first = read()
if (first < 0) return -1
b[off] = first.toByte()
var count = 1
while (count < len) {
val value = bytes.poll() ?: break
if (value < 0) break
b[off + count++] = value.toByte()
}
return count
}
override fun close() { closed = true; bytes.clear(); bytes.offer(-1) }
}
private class Channels : XrealChannels {
override val controlInput = Input()
override val reports = Input()
val wrote = LinkedBlockingQueue<Int>()
val closed = CountDownLatch(1)
@Volatile var acknowledge = true
override val controlOutput = object : OutputStream() {
private val buffer = ByteArrayOutputStream()
override fun write(b: Int) { buffer.write(b) }
override fun flush() {
val data = buffer.toByteArray(); buffer.reset()
val request = XrealProtocol.read(data.inputStream())
val id = ByteBuffer.wrap(request.body).int and Int.MAX_VALUE
wrote.offer(request.command)
if (acknowledge) controlInput.add(XrealProtocolTest.response(request.command, id,
if (request.command == XrealProtocol.GET_DISPLAY) byteArrayOf(0x22, 2, 0x10, 2) else byteArrayOf(0x22, 0)))
}
}
override fun close() { controlInput.close(); reports.close(); closed.countDown() }
}
private class Listener : XrealLink.Listener {
val ready = CountDownLatch(1)
val poses = LinkedBlockingQueue<FloatArray>()
val values = LinkedBlockingQueue<Pair<Int, Int>>()
val errors = LinkedBlockingQueue<Boolean>()
override fun onReady() { ready.countDown() }
override fun onValue(message: Int, value: Int) { values.offer(message to value) }
override fun onPose(raw: ByteArray, pose: FloatArray, timeNs: Long) { poses.offer(pose) }
override fun onUnavailable(networkMissing: Boolean) { errors.offer(networkMissing) }
}
@Test fun trackingUsesSharedPoseAndCommandsAreAcknowledgedBeforePublishing() {
val channels = Channels()
val listener = Listener()
val connector = object : XrealConnector {
override fun connect() = channels
override fun close() = channels.close()
}
val link = XrealLink(connector, listener)
try {
assertTrue(listener.ready.await(2, TimeUnit.SECONDS))
assertEquals(VitureProtocol.MSG_GET_DISPLAY to 2, listener.values.poll(2, TimeUnit.SECONDS))
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
channels.reports.add(XrealProtocolTest.frame(XrealProtocol.REPORT, XrealProtocolTest.sensor()))
assertNotNull(listener.poses.poll(2, TimeUnit.SECONDS))
assertFalse(link.send(VitureProtocol.MSG_VOLUME, byteArrayOf(5)))
assertFalse(link.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(0x32)))
assertTrue(link.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(6)))
assertEquals(VitureProtocol.MSG_BRIGHTNESS to 6, listener.values.poll(2, TimeUnit.SECONDS))
} finally { link.close() }
assertFalse(link.ready)
assertTrue(channels.closed.await(1, TimeUnit.SECONDS))
assertFalse(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
}
@Test fun failedControlReadDisconnectsWithoutPublishingRequestedBrightness() {
val channels = Channels()
val listener = Listener()
val link = XrealLink(object : XrealConnector {
override fun connect() = channels
override fun close() = channels.close()
}, listener)
try {
assertTrue(listener.ready.await(2, TimeUnit.SECONDS))
listener.values.clear()
channels.acknowledge = false
assertTrue(link.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(8)))
channels.controlInput.close()
assertEquals(false, listener.errors.poll(2, TimeUnit.SECONDS))
assertFalse(link.ready)
assertNull(listener.values.poll())
} finally { link.close() }
}
@Test fun missingNetworkIsReportedAndCloseCancelsRetry() {
val listener = Listener()
val closed = AtomicBoolean()
val link = XrealLink(object : XrealConnector {
override fun connect(): XrealChannels = throw XrealNetworkMissing()
override fun close() { closed.set(true) }
}, listener)
try {
assertEquals(true, listener.errors.poll(2, TimeUnit.SECONDS))
assertFalse(link.ready)
} finally { link.close() }
assertTrue(closed.get())
}
@Test fun closeDuringConnectCannotPublishReadyOrLeakSockets() {
val entered = CountDownLatch(1)
val release = CountDownLatch(1)
val channels = Channels()
val listener = Listener()
val link = XrealLink(object : XrealConnector {
override fun connect(): XrealChannels {
entered.countDown()
release.await()
return channels
}
override fun close() { release.countDown(); channels.close() }
}, listener)
assertTrue(entered.await(2, TimeUnit.SECONDS))
link.close()
assertTrue(channels.closed.await(1, TimeUnit.SECONDS))
assertFalse(listener.ready.await(100, TimeUnit.MILLISECONDS))
assertTrue(listener.values.isEmpty())
}
}
@@ -0,0 +1,37 @@
package com.droiddeck.launcher.glasses
import android.net.IpPrefix
import android.net.LinkProperties
import android.net.RouteInfo
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
import org.robolectric.util.ReflectionHelpers.ClassParameter.from
import java.net.InetAddress
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class XrealNetworkTest {
private val target = InetAddress.getByName(XrealProtocol.HOST)
private fun properties(address: String, prefix: Int, gateway: String? = null) = LinkProperties().apply {
interfaceName = "eth0"
val route = ReflectionHelpers.callConstructor<RouteInfo>(RouteInfo::class.java,
from(IpPrefix::class.java, IpPrefix(InetAddress.getByName(address), prefix)),
from(InetAddress::class.java, InetAddress.getByName(gateway ?: "0.0.0.0")),
from(String::class.java, "eth0"))
addRoute(route)
}
@Test fun onlyAnOnLinkGlassesRouteQualifies() {
val direct = properties("169.254.2.0", 24)
val default = properties("0.0.0.0", 0)
val gateway = properties("169.254.2.0", 24, "192.168.1.1")
val unrelated = properties("192.168.1.0", 24)
assertTrue(AndroidXrealConnector.hasDirectRoute(direct, target))
assertFalse(AndroidXrealConnector.hasDirectRoute(default, target))
assertFalse(AndroidXrealConnector.hasDirectRoute(gateway, target))
assertFalse(AndroidXrealConnector.hasDirectRoute(unrelated, target))
}
}
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import org.junit.Assert.*
import org.junit.Test
import kotlin.math.cos
import kotlin.math.sin
class XrealOrientationFilterTest {
private fun sample(time: Long, gyro: Vec3 = Vec3(0f, 0f, 0f), accel: Vec3 = Vec3(0f, -9.81f, 0f)) =
XrealProtocol.Sample(time, gyro, accel)
private fun matrix(q: FloatArray) = HeadPose.fromGlasses(q[0], q[1], q[2], q[3])
@Test fun firstPoseAlignsGravityAndDuplicateOrReversedTimeIsDiscarded() {
val filter = XrealOrientationFilter()
val tilted = Vec3(4.905f, -8.4957f, 0f)
val first = filter.update(sample(1000000, accel = tilted))!!
assertNull(filter.update(sample(1000000)))
assertNull(filter.update(sample(999999)))
assertArrayEquals(first, filter.update(sample(2000000, accel = tilted)), 0.0001f)
}
@Test fun reconnectGapDoesNotIntegrateSecondsOfGyro() {
val filter = XrealOrientationFilter()
val first = filter.update(sample(1000000))!!
assertArrayEquals(first, filter.update(sample(5000000000, Vec3(2f, 2f, 2f))), 0.0001f)
}
@Test fun invalidStartupGravityWaitsForAStationarySample() {
val filter = XrealOrientationFilter()
assertNull(filter.update(sample(1000000, accel = Vec3(0f, 0f, 0f))))
assertNotNull(filter.update(sample(2000000)))
}
@Test fun observedNegativeYawTurnsLeftThirtyDegreesAtOneKhzThroughSharedPosePath() {
val filter = XrealOrientationFilter()
val first = matrix(filter.update(sample(1000000))!!)
var last = FloatArray(4)
repeat(1000) { last = filter.update(sample((it + 2) * 1000000L, Vec3(0f, -(Math.PI / 6).toFloat(), 0f)))!! }
val view = HeadPose.relative(HeadPose.recenter(first), matrix(last))
assertArrayEquals(floatArrayOf(-0.5f, 0f, -0.8660254f), HeadPose.apply(view, floatArrayOf(0f, 0f, -1f)), 0.001f)
}
@Test fun observedPositivePitchAndRollLookUpAndTiltRightWithoutCrossingAxes() {
for (roll in listOf(false, true)) {
val filter = XrealOrientationFilter()
val first = matrix(filter.update(sample(1000000))!!)
var last = FloatArray(4)
repeat(1000) {
val angle = (it + 1) * Math.PI / 6000
val accel = if (roll) Vec3(-9.81f * sin(angle).toFloat(), -9.81f * cos(angle).toFloat(), 0f)
else Vec3(0f, -9.81f * cos(angle).toFloat(), 9.81f * sin(angle).toFloat())
val rate = (Math.PI / 6).toFloat()
last = filter.update(sample((it + 2) * 1000000L,
if (roll) Vec3(0f, 0f, rate) else Vec3(rate, 0f, 0f), accel))!!
}
val view = HeadPose.relative(HeadPose.recenter(first), matrix(last))
val actual = HeadPose.apply(view, if (roll) floatArrayOf(0f, 1f, 0f) else floatArrayOf(0f, 0f, -1f))
assertArrayEquals(if (roll) floatArrayOf(0.5f, 0.8660254f, 0f) else floatArrayOf(0f, 0.5f, -0.8660254f), actual, 0.002f)
}
}
@Test fun capturedNeutralGravityStartsUprightBeforeRecenter() {
val pose = XrealOrientationFilter().update(sample(1000000,
accel = Vec3(-0.0909f, -9.6529f, -1.0731f)))!!
// An upright start must not contain the previous approximately 180-degree
// pitch correction. Check before recenter can hide a mounting error.
assertTrue(kotlin.math.abs(pose[3]) > 0.99f)
val screen = matrix(pose)
assertTrue(screen[7] > 0.99f) // Screen up points toward shared world +Z.
}
}
@@ -0,0 +1,127 @@
package com.droiddeck.launcher.glasses
import org.junit.Assert.*
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
class XrealProtocolTest {
@Test fun fragmentedAndCoalescedFramesRetainBoundariesAndDeviceUnits() {
val bytes = frame(XrealProtocol.REPORT, sensor()) + frame(0x272e, byteArrayOf(1, 2))
val input = object : ByteArrayInputStream(bytes) {
override fun read(b: ByteArray, off: Int, len: Int) = super.read(b, off, minOf(3, len))
}
val sample = XrealProtocol.sample(XrealProtocol.read(input))!!
assertEquals(123456789L, sample.timeNs)
assertEquals(0.5f, sample.gyro.y, 0f)
assertEquals(9.81f, sample.accel.y, 0f)
assertArrayEquals(byteArrayOf(1, 2), XrealProtocol.read(input).body)
}
@Test fun invalidLengthsAndTruncationFailWithoutUnboundedAllocation() {
for (size in listOf(-1, Int.MAX_VALUE, XrealProtocol.MAX_BODY + 1)) {
val bytes = ByteBuffer.allocate(6).putShort(0x2836).putInt(size).array()
assertThrows(IOException::class.java) { XrealProtocol.read(bytes.inputStream()) }
}
assertThrows(IOException::class.java) { XrealProtocol.read(byteArrayOf(0x28).inputStream()) }
assertThrows(IOException::class.java) { XrealProtocol.read(frame(0x2836, sensor()).dropLast(1).toByteArray().inputStream()) }
}
@Test fun onlyCompleteFiniteImuReportsAreAccepted() {
assertNull(XrealProtocol.sample(XrealProtocol.Frame(0x2836, ByteArray(84))))
assertNull(XrealProtocol.sample(XrealProtocol.Frame(0x272e, sensor())))
for ((offset, value) in listOf(24 to 4, 28 to Float.NaN.toRawBits(), 40 to Float.POSITIVE_INFINITY.toRawBits())) {
val bytes = sensor()
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putInt(offset, value)
assertNull(XrealProtocol.sample(XrealProtocol.Frame(0x2836, bytes)))
}
}
@Test fun commandAndTransactionMustBothMatchBeforeParsingAcknowledgement() {
val body = ByteBuffer.allocate(6).putInt(7).put(byteArrayOf(0x22, 0)).array()
val reply = XrealProtocol.Frame(0x271c, body)
assertNull(XrealProtocol.response(reply, 0x271c, 8))
assertNull(XrealProtocol.response(reply, 0x275f, 7))
assertTrue(XrealProtocol.acknowledged(XrealProtocol.response(reply, 0x271c, 7)!!))
assertFalse(XrealProtocol.acknowledged(byteArrayOf(0x22, 1, 0)))
assertEquals(5, XrealProtocol.numeric(byteArrayOf(0x22, 2, 0x10, 5)))
assertNull(XrealProtocol.numeric(byteArrayOf(0x22, 2, 8, 5)))
}
@Test fun getAndSetCommandsUseBigEndianHeaderAndProtobufBody() {
assertArrayEquals(byteArrayOf(0x27, 0x5e, 0, 0, 0, 6, 0x80.toByte(), 0, 0, 1, 0x18, 0),
XrealProtocol.request(XrealProtocol.GET_DISPLAY, 1))
assertArrayEquals(byteArrayOf(0x27, 0x1c, 0, 0, 0, 8, 0x80.toByte(), 0, 0, 2, 0x1a, 2, 8, 9),
XrealProtocol.request(XrealProtocol.SET_BRIGHTNESS, 2, 9))
}
@Test fun controlIgnoresUnsolicitedAndStaleRepliesAndRejectsFailure() {
val output = ByteArrayOutputStream()
val replies = frame(0x272e, ByteArray(8)) + response(0x275e, 99, byteArrayOf(0x22, 2, 0x10, 4)) +
response(0x275e, 1, byteArrayOf(0x22, 2, 0x10, 2)) + response(0x271c, 2, byteArrayOf(0x22, 1, 1))
val control = XrealControl(channels(replies.inputStream(), output))
assertEquals(2, control.display())
assertThrows(IOException::class.java) { control.set(0x271c, 5) }
assertEquals(26, output.size())
}
@Test fun unrelatedResponsesCannotKeepControlWaitingForever() {
val replies = ByteArrayOutputStream().apply { repeat(32) { write(frame(0x272e, ByteArray(8))) } }
val control = XrealControl(channels(replies.toByteArray().inputStream(), ByteArrayOutputStream()))
assertThrows(IOException::class.java) { control.display() }
}
@Test fun captured1sNativeDisplayResponsePreserves1200LineMode() {
val reply = byteArrayOf(0x22, 2, 0x10, 0x1d)
val control = XrealControl(channels(response(0x275e, 1, reply).inputStream(), ByteArrayOutputStream()))
assertEquals(29, control.display())
assertEquals(29, XrealModel.mode(60, false))
}
@Test fun stereoWaitsForEdidChangeWithoutSendingASecondModeCommandWhileBusy() {
val output = ByteArrayOutputStream()
val replies = response(0x2822, 1, byteArrayOf(0x22, 0)) +
response(0x275e, 2, byteArrayOf(0x22, 2, 0x10, 29)) +
response(0x275e, 3, byteArrayOf(0x22, 0)) +
response(0x275e, 4, byteArrayOf(0x22, 2, 0x10, 5))
assertEquals(5, XrealControl(channels(replies.inputStream(), output), 0).changeDisplay(5))
val requests = output.toByteArray().inputStream()
assertEquals(0x2822, XrealProtocol.read(requests).command)
repeat(3) { assertEquals(0x275e, XrealProtocol.read(requests).command) }
assertEquals(0, requests.available())
// Actual 1S busy response remains an error, never a successful ack.
assertFalse(XrealProtocol.acknowledged(byteArrayOf(0x22, 3, 8, 0x89.toByte(), 0x27)))
}
@Test fun stereoCanReturnToNative1200LinesAndAnUnfinishedTransitionIsBounded() {
val replies = response(0x2822, 1, byteArrayOf(0x22, 0)) +
response(0x275e, 2, byteArrayOf(0x22, 0)) +
response(0x275e, 3, byteArrayOf(0x22, 2, 0x10, 29))
assertEquals(29, XrealControl(channels(replies.inputStream(), ByteArrayOutputStream()), 0).changeDisplay(29))
val stalled = ByteArrayOutputStream().apply {
write(response(0x2822, 1, byteArrayOf(0x22, 0)))
repeat(40) { write(response(0x275e, it + 2, byteArrayOf(0x22, 0))) }
}
val control = XrealControl(channels(stalled.toByteArray().inputStream(), ByteArrayOutputStream()), 0)
assertThrows(IOException::class.java) { control.changeDisplay(5) }
}
companion object {
fun sensor(time: Long = 123456789L): ByteArray = ByteBuffer.allocate(128).order(ByteOrder.LITTLE_ENDIAN)
.putLong(8, time).putInt(24, 11).putFloat(32, 0.5f).putFloat(44, 9.81f).array()
fun frame(command: Int, body: ByteArray): ByteArray = ByteBuffer.allocate(6 + body.size)
.putShort(command.toShort()).putInt(body.size).put(body).array()
fun response(command: Int, transaction: Int, body: ByteArray) = frame(command,
ByteBuffer.allocate(4 + body.size).putInt(transaction).put(body).array())
internal fun channels(input: InputStream, output: ByteArrayOutputStream) = object : XrealChannels {
override val controlInput = input
override val controlOutput = output
override val reports = ByteArrayInputStream(ByteArray(0))
override fun close() = Unit
}
}
}
@@ -0,0 +1,65 @@
package com.droiddeck.launcher.gpu
import android.content.Context
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 = [28], manifest = Config.NONE)
class AutoDriverTrialTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
context.getSharedPreferences("gpu_auto_trial", Context.MODE_PRIVATE).edit().clear().commit()
SessionPrefs.setAndroidDriver(context, "new-display")
SessionPrefs.setLinuxDriver(context, "new-linux")
SessionPrefs.setGpuAutoInstalled(context, setOf("old-display", "old-linux", "new-display", "new-linux"))
AutoDriverTrial.begin(context, "banner@r5", "Banners r5", "new-display", "new-linux", "old-display", "old-linux")
}
@Test fun aReadySessionKeepsTheNewDriversAndDropsTheOldOnes() {
AutoDriverTrial.sessionStarting(context, "new-display", "new-linux")
AutoDriverTrial.sessionReady()
assertNull(AutoDriverTrial.current(context))
assertEquals(setOf("new-display", "new-linux"), SessionPrefs.gpuAutoInstalled(context))
assertEquals("new-linux", SessionPrefs.linuxDriver(context))
}
@Test fun startsThatNeverGetReadyRollBackAndMarkTheReleaseBad() {
AutoDriverTrial.sessionStarting(context, "new-display", "new-linux")
assertNull(AutoDriverTrial.rollbackDue(context))
AutoDriverTrial.sessionStarting(context, "new-display", "new-linux")
val trial = AutoDriverTrial.rollbackDue(context)!!
AutoDriverTrial.rollBack(context, trial)
assertEquals("old-display", SessionPrefs.androidDriver(context))
assertEquals("old-linux", SessionPrefs.linuxDriver(context))
assertEquals(setOf("old-display", "old-linux"), SessionPrefs.gpuAutoInstalled(context))
assertTrue("banner@r5" in AutoDriverTrial.bad(context))
assertNull(AutoDriverTrial.current(context))
}
@Test fun rollingBackKeepsADriverTheUserSelectedSince() {
SessionPrefs.setGpuAutoInstalled(context, setOf("old-display", "old-linux", "new-display", "new-linux", "chosen-linux"))
SessionPrefs.setLinuxDriver(context, "chosen-linux")
AutoDriverTrial.rollBack(context, AutoDriverTrial.current(context)!!)
assertEquals("chosen-linux", SessionPrefs.linuxDriver(context))
assertTrue("chosen-linux" in SessionPrefs.gpuAutoInstalled(context))
}
@Test fun sessionsOnOtherDriversDoNotCountTowardsTheTrial() {
AutoDriverTrial.sessionStarting(context, "old-display", "new-linux")
AutoDriverTrial.sessionStarting(context, "old-display", "new-linux")
AutoDriverTrial.sessionReady()
assertNull(AutoDriverTrial.rollbackDue(context))
assertEquals("banner@r5", AutoDriverTrial.current(context)?.release)
}
}
@@ -0,0 +1,67 @@
package com.droiddeck.launcher.gpu
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class AutoPicksTest {
private fun gpu(model: Int) = GpuInfo("Adreno $model", model, GpuInfo.familyOf(true, model), "", false)
private fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000,
false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true)
private fun half(name: String, tag: String, linux: Boolean, pair: String) =
TurnipReleases.Asset("src", tag, name, "https://example/$name", 3_000_000, linux, "label", "0".repeat(64), pair)
private val pairs = DriverPairs.from(TurnipReleases.Check(
listOf(
bundle("DD-Turnip-v0.3.0"),
half("Turnip-r6.zip", "r6", false, DriverPairs.BANNER),
half("Turnip-r6-Linux.zip", "r6", true, DriverPairs.BANNER),
),
emptyList(), emptyList(), 0L,
))
private val manifest = """
{"schemaVersion": 1, "rules": [
{"families": ["A7XX"], "models": [740], "blobMin": 700, "prefer": ["banner"]},
{"families": ["A7XX", "A6XX"], "prefer": ["dd-turnip", "banner"]},
{"families": ["A9XX"], "prefer": ["banner"]}
]}
""".trimIndent()
@Test fun theManifestOrdersPreferencesAndTheNewestDdTurnipResolves() {
val rules = AutoPicks.parse(manifest)!!
assertEquals(2, rules.size)
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v0.3.0"), DriverPairs.recommendedKey(gpu(650), pairs, rules))
}
@Test fun aReleaseMarkedBadFallsThroughToTheNextPreference() {
val rules = AutoPicks.parse(manifest)!!
val dd = pairs.first { it.key.startsWith(DriverPairs.DD_TURNIP) }
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), pairs, rules, bad = setOf(AutoDriverTrial.release(dd))))
}
@Test fun systemDriverRulesOnlyMatchAKnownBlob() {
val rules = AutoPicks.parse(manifest)!!
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs, rules, blob = 744))
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v0.3.0"), DriverPairs.recommendedKey(gpu(740), pairs, rules, blob = 676))
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v0.3.0"), DriverPairs.recommendedKey(gpu(740), pairs, rules, blob = null))
assertEquals(744, AutoPicks.blobVersion("512.744.0"))
}
@Test fun aGpuTheManifestDoesNotCoverUsesTheBuiltInTable() {
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), pairs, AutoPicks.parse(manifest)!!))
}
@Test fun anotherSchemaOrNoUsableRulesIsIgnored() {
assertNull(AutoPicks.parse("""{"schemaVersion": 2, "rules": [{"families": ["A7XX"], "prefer": ["banner"]}]}"""))
assertNull(AutoPicks.parse("""{"schemaVersion": 1, "rules": [{"families": ["A9XX"], "prefer": ["banner"]}]}"""))
assertNull(AutoPicks.parse("not json"))
}
}
@@ -0,0 +1,203 @@
package com.droiddeck.launcher.gpu
import org.json.JSONObject
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 kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class CardboardTest {
private val eps = 1e-4f
private fun assertVec(expected: FloatArray, actual: FloatArray) = assertArrayEquals(expected, actual, eps)
private fun quat(ax: Float, ay: Float, az: Float, deg: Double): FloatArray {
val h = deg * PI / 360.0
val s = sin(h).toFloat()
return floatArrayOf(ax * s, ay * s, az * s, cos(h).toFloat())
}
private fun matrix(q: FloatArray) = HeadPose.fromQuaternion(q[0], q[1], q[2], q[3])
@Test fun settingsRoundTripAndClamp() {
val c = Cardboard(enabled = true, source = Cardboard.SOURCE_SBS, viewer = "none", ipdMm = 70,
screenWidthDm = 55, screenDistanceDm = 25, headTracking = false)
assertEquals(c, Cardboard.decode(c.encode()))
val flat = c.copy(source = Cardboard.SOURCE_FLAT)
assertEquals(flat, Cardboard.decode(flat.encode()))
val wild = Cardboard.decode(JSONObject().put("ipdMm", 500).put("screenWidthDm", -3).put("viewer", "nope").put("source", 7))
assertEquals(80, wild.ipdMm)
assertEquals(5, wild.screenWidthDm)
assertEquals(Cardboard.Viewer.CARDBOARD_V2.id, wild.viewer)
assertEquals(Cardboard.SOURCE_SCREEN, wild.source)
assertEquals(Cardboard.OFF, Cardboard.decode(JSONObject()))
}
@Test fun lensInsetLinesTheEyesUpWithTheLenses() {
assertEquals(0f, Cardboard.lensInset(128f, 64f), eps)
assertEquals(5.5f / 75f, Cardboard.lensInset(150f, 64f), eps)
assertEquals(true, Cardboard.lensInset(110f, 64f) < 0f)
assertEquals(0f, Cardboard.lensInset(0f, 64f), eps)
assertEquals(0f, Cardboard.lensInset(150f, 0f), eps)
}
@Test fun steamVrStatusFollowsTheAgentAnswer() {
fun answer(vararg pairs: Pair<String, Boolean>) = JSONObject().apply { pairs.forEach { put(it.first, it.second) } }
assertEquals(SteamVr.Status.UNAVAILABLE, SteamVr.parse(answer("ok" to false, "installed" to true, "driver" to true)))
assertEquals(SteamVr.Status.UNAVAILABLE, SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to false)))
assertEquals(SteamVr.Status.NOT_INSTALLED, SteamVr.parse(answer("ok" to true, "driver" to true)))
assertEquals(SteamVr.Status.INSTALLING, SteamVr.parse(answer("ok" to true, "installing" to true)))
assertEquals(SteamVr.Status.READY, SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true)))
assertEquals(SteamVr.Status.RUNNING,
SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true, "running" to true)))
assertEquals(SteamVr.Status.UNAVAILABLE,
SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true).put("exitCode", 1)))
}
@Test fun steamVrActionsSucceedOnlyWhenTheHelperDid() {
fun answer(ok: Boolean, exitCode: Int? = null, started: Boolean? = null) = JSONObject().apply {
put("ok", ok)
exitCode?.let { put("exitCode", it) }
started?.let { put("started", it) }
}
assertTrue(SteamVr.succeeded("start", answer(true, exitCode = 0)))
assertTrue(SteamVr.succeeded("stop", answer(true, exitCode = 0)))
assertFalse(SteamVr.succeeded("start", answer(true, exitCode = 1)))
assertFalse(SteamVr.succeeded("stop", answer(true, exitCode = 2)))
assertFalse(SteamVr.succeeded("start", answer(true)))
assertFalse(SteamVr.succeeded("start", answer(false, exitCode = 0)))
assertTrue(SteamVr.succeeded("install", answer(true, started = true)))
assertFalse(SteamVr.succeeded("install", answer(true)))
assertFalse(SteamVr.succeeded("install", answer(false, started = true)))
}
@Test fun quaternionMatchesKnownRotations() {
val m = matrix(quat(0f, 0f, 1f, 90.0))
assertVec(floatArrayOf(0f, 1f, 0f), HeadPose.apply(m, floatArrayOf(1f, 0f, 0f)))
val q = HeadPose.quaternionFromRotationVector(floatArrayOf(0f, 0f, sin(PI / 4).toFloat()))
assertEquals(cos(PI / 4).toFloat(), q[3], eps)
}
@Test fun recenterMakesTheCurrentViewStraightAhead() {
for (heading in listOf(0.0, 37.0, 140.0, -100.0)) {
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
val yaw = matrix(quat(0f, 0f, 1f, heading))
val screenToWorld = HeadPose.multiply(yaw, upright)
assertVec(HeadPose.IDENTITY, HeadPose.relative(HeadPose.recenter(screenToWorld), screenToWorld))
}
}
@Test fun recenterKeepsPitchButDropsHeading() {
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
val pitched = HeadPose.multiply(upright, matrix(quat(1f, 0f, 0f, -30.0)))
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 50.0)), pitched)
val pose = HeadPose.relative(HeadPose.recenter(turned), turned)
val forward = HeadPose.apply(pose, floatArrayOf(0f, 0f, -1f))
assertEquals(0f, forward[0], eps)
assertEquals(-sin(PI / 6).toFloat(), forward[1], eps)
assertEquals(-cos(PI / 6).toFloat(), forward[2], eps)
}
@Test fun virtualScreenRecenterUsesTheCurrentHeightAndDirection() {
for (pitch in listOf(-30.0, -10.0, 15.0, 35.0)) {
val yaw = matrix(quat(0f, 0f, 1f, 50.0))
val tilt = HeadPose.multiply(matrix(quat(1f, 0f, 0f, pitch)), matrix(quat(0f, 0f, 1f, 12.0)))
val screen = HeadPose.multiply(HeadPose.multiply(yaw, HeadPose.fromGlasses(0f, 0f, 0f, 1f)), tilt)
val ref = HeadPose.recenter(screen, centerView = true)
assertVec(HeadPose.IDENTITY, HeadPose.relative(ref, screen))
val lookUp = matrix(quat(1f, 0f, 0f, 20.0))
assertVec(lookUp, HeadPose.relative(ref, HeadPose.multiply(screen, lookUp)))
}
}
@Test fun turningTheHeadTurnsTheView() {
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
val ref = HeadPose.recenter(upright)
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 90.0)), upright)
val forward = HeadPose.apply(HeadPose.relative(ref, turned), floatArrayOf(0f, 0f, -1f))
assertVec(floatArrayOf(-1f, 0f, 0f), forward)
}
@Test fun heldFlatTheViewStartsStraightAhead() {
for (m in listOf(HeadPose.IDENTITY, HeadPose.multiply(matrix(quat(0f, 0f, 1f, 30.0)), matrix(quat(1f, 0f, 0f, 20.0))))) {
assertVec(HeadPose.IDENTITY, HeadPose.relative(HeadPose.recenter(m), m))
}
}
@Test fun heldFlatTurningAtTheHipsPans() {
val flat = HeadPose.IDENTITY
val ref = HeadPose.recenter(flat)
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 40.0)), flat)
val pose = HeadPose.relative(ref, turned)
val forward = HeadPose.apply(pose, floatArrayOf(0f, 0f, -1f))
val up = HeadPose.apply(pose, floatArrayOf(0f, 1f, 0f))
assertVec(floatArrayOf(-sin(PI * 40 / 180).toFloat(), 0f, -cos(PI * 40 / 180).toFloat()), forward)
assertVec(floatArrayOf(0f, 1f, 0f), up)
val tipped = HeadPose.multiply(flat, matrix(quat(1f, 0f, 0f, -20.0)))
val down = HeadPose.apply(HeadPose.relative(ref, tipped), floatArrayOf(0f, 0f, -1f))
assertEquals(-sin(PI / 9).toFloat(), down[1], eps)
}
@Test fun fieldOfViewComesFromThePanelSeenThroughTheLens() {
val v2 = Cardboard.Viewer.CARDBOARD_V2
assertEquals(87.07f, Cardboard.fovDeg(v2, 74.7f), 0.05f)
assertEquals(v2.fallbackFovDeg, Cardboard.fovDeg(v2, 0f), eps)
assertEquals(Cardboard.Viewer.NONE.fallbackFovDeg, Cardboard.fovDeg(Cardboard.Viewer.NONE, 74.7f), eps)
}
@Test fun displayRotationRemapsTheScreenAxes() {
val r = matrix(quat(0.3f, -0.5f, 0.2f, 70.0).let { q ->
val n = sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]); floatArrayOf(q[0] / n, q[1] / n, q[2] / n, q[3] / n)
})
assertVec(r, HeadPose.toScreen(r, 0))
val s90 = HeadPose.toScreen(r, 1)
assertVec(HeadPose.apply(r, floatArrayOf(0f, -1f, 0f)), HeadPose.apply(s90, floatArrayOf(1f, 0f, 0f)))
assertVec(HeadPose.apply(r, floatArrayOf(1f, 0f, 0f)), HeadPose.apply(s90, floatArrayOf(0f, 1f, 0f)))
val s270 = HeadPose.toScreen(r, 3)
assertVec(HeadPose.apply(r, floatArrayOf(0f, 1f, 0f)), HeadPose.apply(s270, floatArrayOf(1f, 0f, 0f)))
assertVec(r, HeadPose.toScreen(HeadPose.toScreen(HeadPose.toScreen(HeadPose.toScreen(r, 1), 1), 1), 1))
}
@Test fun glassesLevelAndAheadIsStraightAhead() {
val s2w = HeadPose.fromGlasses(0f, 0f, 0f, 1f)
assertVec(floatArrayOf(1f, 0f, 0f), HeadPose.apply(s2w, floatArrayOf(0f, 0f, -1f)))
assertVec(floatArrayOf(0f, 0f, 1f), HeadPose.apply(s2w, floatArrayOf(0f, 1f, 0f)))
assertVec(HeadPose.IDENTITY, HeadPose.relative(HeadPose.recenter(s2w), s2w))
}
@Test fun glassesTurnedLeftLookLeft() {
val ref = HeadPose.recenter(HeadPose.fromGlasses(0f, 0f, 0f, 1f))
val q = quat(0f, 0f, 1f, 30.0)
val view = HeadPose.relative(ref, HeadPose.fromGlasses(q[0], q[1], q[2], q[3]))
val s = sin(PI / 6).toFloat(); val c = cos(PI / 6).toFloat()
assertVec(floatArrayOf(-s, 0f, -c), HeadPose.apply(view, floatArrayOf(0f, 0f, -1f)))
assertVec(floatArrayOf(0f, 1f, 0f), HeadPose.apply(view, floatArrayOf(0f, 1f, 0f)))
}
@Test fun glassesRecenterKeepsTheHorizon() {
val q = quat(0f, 0f, 1f, 75.0)
val ref = HeadPose.recenter(HeadPose.fromGlasses(q[0], q[1], q[2], q[3]))
assertVec(HeadPose.IDENTITY, HeadPose.relative(ref, HeadPose.fromGlasses(q[0], q[1], q[2], q[3])))
val tilt = quat(0f, 1f, 0f, 20.0)
val both = HeadPose.multiply(HeadPose.fromQuaternion(q[0], q[1], q[2], q[3]), HeadPose.fromQuaternion(tilt[0], tilt[1], tilt[2], tilt[3]))
val view = HeadPose.multiply(HeadPose.transpose(ref.basis), HeadPose.multiply(both, floatArrayOf(0f, 0f, -1f, -1f, 0f, 0f, 0f, 1f, 0f)))
val ahead = HeadPose.apply(view, floatArrayOf(0f, 0f, -1f))
assertEquals(0f, ahead[0], eps)
assertEquals(-sin(PI / 9).toFloat(), ahead[1], eps)
}
@Test fun monoIsNotPartOfTheSavedSettings() {
val c = Cardboard(enabled = true, mono = true)
assertEquals(false, Cardboard.decode(c.encode()).mono)
}
}
@@ -34,7 +34,6 @@ class DriverBundleTest {
SessionPrefs.setLinuxDriver(context, "")
}
/** Enough of an AArch64 ELF for the importers: the header they read, then the libc they look for. */
private fun library(libc: String) = ByteArray(64).also {
byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(it)
it[18] = 0xB7.toByte()
@@ -60,7 +60,6 @@ class DriverPairsTest {
listOf(
asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER),
asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER),
// The A8xx set's newest display build is r4, but its Linux half is only in r3.
asset("Turnip-r4-A8xx.zip", "r4", false, DriverPairs.BANNER_A8XX),
asset("Turnip-r3-A8xx-Linux.zip", "r3", true, DriverPairs.BANNER_A8XX),
asset("WN-Turnip-1.19-b_Axxx.zip", "v1.19", false, DriverPairs.WN_BALANCED),
@@ -0,0 +1,80 @@
package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.gpu.GpuInfo.Family
import com.droiddeck.launcher.gpu.GpuInfo.Support
import org.junit.Assert.assertEquals
import org.junit.Test
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() {
assertEquals(650, GpuInfo.threeDigits("Adreno650"))
assertEquals(830, GpuInfo.threeDigits("Adreno (TM) 830"))
assertEquals(740, GpuInfo.threeDigits("Adreno740v2"))
assertEquals(618, GpuInfo.threeDigits(" adreno 618 "))
assertEquals(750, GpuInfo.threeDigits("Adreno (TM) 750 (Qualcomm)"))
assertEquals(0, GpuInfo.threeDigits(""))
assertEquals(0, GpuInfo.threeDigits(" "))
assertEquals(0, GpuInfo.threeDigits("Adreno"))
assertEquals(0, GpuInfo.threeDigits("Adreno 65"))
}
@Test fun nonAdrenoRenderersAreNeverAdrenoWhateverNumberTheyCarry() {
// Xclipse (Exynos), Mali and Immortalis names; familyOf ignores the number off Adreno.
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Samsung Xclipse 920")))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Xclipse 940")))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Mali-G720-Immortalis MC12")))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Mali-G715")))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 830))
}
@Test fun familyBoundaries() {
assertEquals(Family.ADRENO_UNKNOWN, GpuInfo.familyOf(true, 0))
assertEquals(Family.ADRENO_UNKNOWN, GpuInfo.familyOf(true, 540))
assertEquals(Family.ADRENO_UNKNOWN, GpuInfo.familyOf(true, 599))
for (m in listOf(600, 618, 619, 640, 650, 660, 690)) assertEquals("$m", Family.A6XX, GpuInfo.familyOf(true, m))
for (m in listOf(710, 720, 722)) assertEquals("$m", Family.A7XX_LOW, GpuInfo.familyOf(true, m))
for (m in listOf(700, 702, 725, 730, 740, 750, 780)) assertEquals("$m", Family.A7XX, GpuInfo.familyOf(true, m))
for (m in listOf(800, 825, 829, 830, 840, 999)) assertEquals("$m", Family.A8XX, GpuInfo.familyOf(true, m))
}
@Test fun supportTiers() {
assertEquals(Support.TESTED, info(true, 650).support)
assertEquals(Support.UNTESTED, info(true, 640).support)
assertEquals(Support.UNTESTED, info(true, 618).support)
assertEquals(Support.UNTESTED, info(true, 660).support)
assertEquals(Support.UNTESTED, info(true, 720).support)
assertEquals(Support.UNTESTED, info(true, 722).support)
assertEquals(Support.UNTESTED, info(true, 0).support)
assertEquals(Support.TESTED, info(true, 725).support)
assertEquals(Support.TESTED, info(true, 740).support)
assertEquals(Support.TESTED, info(true, 750).support)
assertEquals(Support.TESTED, info(true, 830).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: 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)
assertEquals("Not an Adreno GPU", Family.NOT_ADRENO.label)
assertEquals("Adreno 8xx", Family.A8XX.label)
}
@Test fun platformCodeNamesIncludingCaseAndUnknowns() {
assertEquals(640, GpuInfo.platformModel("msmnile"))
assertEquals(650, GpuInfo.platformModel("kona"))
assertEquals(660, GpuInfo.platformModel("LAHAINA"))
assertEquals(730, GpuInfo.platformModel("taro"))
assertEquals(730, GpuInfo.platformModel("cape"))
assertEquals(830, GpuInfo.platformModel("Sun"))
assertEquals(0, GpuInfo.platformModel(""))
assertEquals(0, GpuInfo.platformModel("exynos2400"))
assertEquals(0, GpuInfo.platformModel(" kona "))
}
}
@@ -5,7 +5,6 @@ import org.junit.Test
class GpuModelFallbackTest {
@Test fun aPlatformCodeNameGivesItsAdreno() {
// AYANEO's Pocket FIT: KGSL says "Adreno33v2", the platform says pineapple.
assertEquals(750, GpuInfo.platformModel("pineapple"))
assertEquals(740, GpuInfo.platformModel("KALAMA"))
assertEquals(830, GpuInfo.platformModel("sun"))
@@ -8,7 +8,6 @@ class SocNamesTest {
private fun props(vararg pairs: Pair<String, String>): (String) -> String = { pairs.toMap()[it].orEmpty() }
@Test fun theModelIsFoundWhereVendorsPutIt() {
// AYANEO Pocket FIT: ro.soc.model blank, the vendor property set, ro.fota.platform a branch name.
assertEquals("SG8350P", SocNames.model(props("ro.vendor.qti.soc_model" to "SG8350P", "ro.fota.platform" to "MSM_13.0")))
assertEquals("QCS8550", SocNames.model(props("ro.soc.model" to "QCS8550", "ro.vendor.qti.soc_model" to "other")))
assertEquals("", SocNames.model(props("ro.fota.platform" to "MSM_13.0")))
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.gpu
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class SteamVrDeviceLossLogTest {
@get:Rule val temp = TemporaryFolder()
@Test fun oldErrorsAreIgnoredButFreshSplitLinesAreDetected() {
val file = temp.newFile().apply { writeText("old vkerror=-4\n") }
val log = SteamVrDeviceLossLog(file)
assertFalse(log.poll())
file.appendText("WaitForAcquire timed out\nFailed GetDeltas(Compositor): vkerror=")
assertFalse(log.poll())
file.appendText("-4\n")
assertTrue(log.poll())
assertTrue(log.poll()) // Keep pending until the activity is foreground.
}
@Test fun onlyExplicitDeviceLossTriggersRecovery() {
assertTrue(SteamVrDeviceLossLog.isDeviceLoss("Failed GetDeltas: vkerror=-4\n"))
assertTrue(SteamVrDeviceLossLog.isDeviceLoss("Submit returned VK_ERROR_DEVICE_LOST\n"))
for (text in listOf("vkerror=-40", "vkerror=-1", "headset taken off", "WaitForAcquire timed out",
"Unexpected failure when checking for timeline signal", "Failed to submit to queue")) {
assertFalse(text, SteamVrDeviceLossLog.isDeviceLoss(text))
}
}
@Test fun handlesMissingLogCreationAndTruncation() {
val file = File(temp.root, "vrcompositor.txt")
val log = SteamVrDeviceLossLog(file)
assertFalse(log.poll())
file.writeText("healthy line\n".repeat(100))
assertFalse(log.poll())
file.writeText("vkerror=-4\n")
assertTrue(log.poll())
}
@Test fun detectsReplacementEvenWhenNewFileIsLargerThanTheOldOffset() {
val file = temp.newFile().apply { writeText("old\n".repeat(50)) }
val log = SteamVrDeviceLossLog(file)
assertTrue(file.renameTo(File(temp.root, "previous.txt")))
file.writeText("VK_ERROR_DEVICE_LOST\n" + "new\n".repeat(100))
assertTrue(log.poll())
}
@Test fun scansBoundedTailOfRapidlyGrowingFaultLogs() {
val file = temp.newFile()
val log = SteamVrDeviceLossLog(file)
file.writeText("ordinary line\n".repeat(100_000) + "vkerror=-4\n")
assertTrue(log.poll())
}
@Test fun catchesTruncateAndRegrowBetweenPollsWithoutAnInodeChange() {
val file = temp.newFile().apply { writeText("previous run\n".repeat(100)) }
val log = SteamVrDeviceLossLog(file)
file.writeText("new run vkerror=-4\n" + "new output\n".repeat(200))
assertTrue(log.poll())
}
@Test fun cooldownSurvivesRepeatedFailuresAndClockRollback() {
val now = 1_000_000L
assertTrue(SteamVrRecoveryPolicy.canRestartAutomatically(0, now))
assertFalse(SteamVrRecoveryPolicy.canRestartAutomatically(now, now))
assertFalse(SteamVrRecoveryPolicy.canRestartAutomatically(now, now - 1))
assertFalse(SteamVrRecoveryPolicy.canRestartAutomatically(now, now + 599_999))
assertTrue(SteamVrRecoveryPolicy.canRestartAutomatically(now, now + 600_000))
}
}
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.gpu
import org.junit.Assert.*
import org.junit.Test
class SteamVrLaunchTest {
@Test fun manualRequestKeepsPollingWithoutGlassesControlOrCardboard() {
for (status in listOf(null, SteamVr.Status.READY, SteamVr.Status.UNAVAILABLE, SteamVr.Status.RUNNING)) {
assertTrue(SteamVr.shouldPoll(status, false, false, false, true))
}
}
@Test fun observedActivityIsPolledUntilItStopsEvenWithoutARequest() {
assertTrue(SteamVr.shouldPoll(SteamVr.Status.RUNNING, false, false, false, false))
assertTrue(SteamVr.shouldPoll(SteamVr.Status.INSTALLING, false, false, false, false))
assertFalse(SteamVr.shouldPoll(SteamVr.Status.READY, false, false, false, false))
assertFalse(SteamVr.shouldPoll(null, false, false, false, false))
}
@Test fun explicitPlayRequestStartsWhenRuntimeIsReadyWithoutWaitingForGlassesControlOrOutput() {
assertEquals("start", action(SteamVr.Status.READY))
}
@Test fun pendingRequestWaitsForGuestAndLoadingThenStarts() {
assertNull(action(SteamVr.Status.UNAVAILABLE))
assertNull(action(SteamVr.Status.READY, loading = true))
assertEquals("start", action(SteamVr.Status.READY))
}
@Test fun missingRuntimeIsInstalledOnceAndThenStarted() {
assertEquals("install", action(SteamVr.Status.NOT_INSTALLED))
assertNull(action(SteamVr.Status.NOT_INSTALLED, installTried = true))
assertNull(action(SteamVr.Status.INSTALLING, installTried = true))
assertEquals("start", action(SteamVr.Status.READY, installTried = true))
}
@Test fun runningRuntimeOrAttemptedStartDoesNotLaunchAnotherInstance() {
assertNull(action(SteamVr.Status.RUNNING))
assertNull(action(SteamVr.Status.READY, startTried = true))
}
@Test fun ordinarySessionsAndCancelledRequestsDoNotAutostart() {
assertNull(SteamVr.autoAction(SteamVr.Status.READY, false, false, true, false, false))
assertNull(SteamVr.autoAction(SteamVr.Status.READY, true, false, false, false, false))
}
private fun action(status: SteamVr.Status, loading: Boolean = false,
startTried: Boolean = false, installTried: Boolean = false) =
SteamVr.autoAction(status, true, loading, true, startTried, installTried)
}
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.gpu
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SteamVrRecoverySettingsTest {
@get:Rule val temp = TemporaryFolder()
@Test fun recoveryUnblocksOnlyOurHeadsetAndKeepsUserSettings() {
val file = temp.newFile().apply { writeText("""{
"driver_droiddeck":{"blocked_by_safe_mode":true,"other":42},
"driver_other":{"blocked_by_safe_mode":true},
"steamvr":{"enableSafeMode":true,"environmentMode":0},
"GpuSpeed":{"gpuSpeed0":450}
}""") }
assertTrue(SteamVrRecoverySettings.unblockHeadset(file))
val after = JSONObject(file.readText())
assertFalse(after.getJSONObject("driver_droiddeck").getBoolean("blocked_by_safe_mode"))
assertEquals(42, after.getJSONObject("driver_droiddeck").getInt("other"))
assertTrue(after.getJSONObject("driver_other").getBoolean("blocked_by_safe_mode"))
assertTrue(after.getJSONObject("steamvr").getBoolean("enableSafeMode"))
assertEquals(0, after.getJSONObject("steamvr").getInt("environmentMode"))
assertEquals(450, after.getJSONObject("GpuSpeed").getInt("gpuSpeed0"))
val unchanged = file.readText()
assertFalse(SteamVrRecoverySettings.unblockHeadset(file))
assertEquals(unchanged, file.readText())
}
@Test fun missingOrUnblockedConfigIsNotRewritten() {
assertFalse(SteamVrRecoverySettings.unblockHeadset(File(temp.root, "missing")))
for (text in listOf("{}", "{\"driver_droiddeck\":{\"blocked_by_safe_mode\":false}}")) {
val file = temp.newFile().apply { writeText(text) }
assertFalse(SteamVrRecoverySettings.unblockHeadset(file))
assertEquals(text, file.readText())
}
}
@Test fun malformedConfigIsPreservedAndRecoveryFailsInsteadOfReplacingIt() {
val file = temp.newFile().apply { writeText("broken JSON") }
assertTrue(runCatching { SteamVrRecoverySettings.unblockHeadset(file) }.isFailure)
assertEquals("broken JSON", file.readText())
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.gpu
import android.app.Activity
import android.content.Context
import android.os.Looper
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowAlertDialog
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@LooperMode(LooperMode.Mode.PAUSED)
class SteamVrRecoveryTest {
private lateinit var activity: Activity
@Before fun setup() {
activity = Robolectric.buildActivity(Activity::class.java).setup().get()
activity.getSharedPreferences(SteamVrRecovery.PREFS, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun countdownLaunchesPrivateRestartActivityAndPersistsLoopGuard() {
val recovery = SteamVrRecovery(activity) { true }
recovery.detected()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(7))
assertNull(shadowOf(activity).nextStartedActivity)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
assertEquals(SteamVrRestartActivity::class.java.name, shadowOf(activity).nextStartedActivity.component?.className)
assertTrue(activity.getSharedPreferences(SteamVrRecovery.PREFS, Context.MODE_PRIVATE)
.getLong(SteamVrRecovery.LAST_ATTEMPT, 0) > 0)
recovery.close()
}
@Test fun cancellationPreventsRestartAndRepeatedPrompts() {
val recovery = SteamVrRecovery(activity) { true }
recovery.detected()
ShadowAlertDialog.getLatestAlertDialog().getButton(android.app.AlertDialog.BUTTON_NEGATIVE).performClick()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(20))
recovery.detected()
assertNull(shadowOf(activity).nextStartedActivity)
assertFalse(ShadowAlertDialog.getLatestAlertDialog().isShowing)
}
@Test fun recentRecoveryDoesNotAutomaticallyRestartAgain() {
activity.getSharedPreferences(SteamVrRecovery.PREFS, Context.MODE_PRIVATE).edit()
.putLong(SteamVrRecovery.LAST_ATTEMPT, System.currentTimeMillis()).commit()
val recovery = SteamVrRecovery(activity) { true }
recovery.detected()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(20))
assertNull(shadowOf(activity).nextStartedActivity)
assertTrue(ShadowAlertDialog.getLatestAlertDialog().isShowing)
val outside = android.view.MotionEvent.obtain(0, 0, android.view.MotionEvent.ACTION_OUTSIDE, -10f, -10f, 0)
try {
assertFalse(ShadowAlertDialog.getLatestAlertDialog().onTouchEvent(outside))
assertTrue(ShadowAlertDialog.getLatestAlertDialog().isShowing)
} finally { outside.recycle() }
recovery.close()
}
@Test fun backgroundingCancelsTheCountdownUntilTheSessionReturns() {
var foreground = true
val recovery = SteamVrRecovery(activity) { foreground }
recovery.detected()
foreground = false
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(20))
assertNull(shadowOf(activity).nextStartedActivity)
assertFalse(ShadowAlertDialog.getLatestAlertDialog().isShowing)
recovery.detected()
assertFalse(ShadowAlertDialog.getLatestAlertDialog().isShowing)
foreground = true
recovery.detected()
assertTrue(ShadowAlertDialog.getLatestAlertDialog().isShowing)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(8))
assertEquals(SteamVrRestartActivity::class.java.name, shadowOf(activity).nextStartedActivity.component?.className)
recovery.close()
}
}
Loaded 100 of 1480 files, more files were not shown because too many files have changed in this diff. Show more