Merge current main while preserving subscription access and game logos

This commit is contained in:
xXJsonDeruloXx committed 2026-10-22 10:41:17 -04:00
commit e6265c1262
509 files changed
+36029 -2264

No files matched your search

@@ -0,0 +1,57 @@
package com.droiddeck.launcher.core
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import java.io.File
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
@RunWith(RobolectricTestRunner::class)
class AddonPackTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val root get() = File(context.filesDir, "addons/sample")
@Before fun clean() {
root.deleteRecursively()
}
private fun installed(version: String, complete: Boolean = true, modified: Long = 1_000L): File =
File(root, version).apply {
mkdirs()
File(this, "tool").writeText("x")
if (complete) File(this, AddonPack.COMPLETE).writeText(version)
setLastModified(modified)
}
@Test fun unpinnedLocalBuildReusesTheNewestCompletePack() {
installed("a".repeat(64), modified = 1_000L)
installed("b".repeat(64), modified = 2_000L)
installed("c".repeat(64), complete = false, modified = 3_000L)
val pack = AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = true)
assertTrue(pack.installed(context))
assertEquals("b".repeat(64), pack.dir(context).name)
}
@Test fun unpinnedLocalBuildWithNothingInstalledHasNoPack() {
assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = true).installed(context))
}
@Test fun pinnedBuildIgnoresOtherInstalledVersions() {
installed("b".repeat(64))
val pack = AddonPack("sample", "a".repeat(64), 1L, listOf("tool"))
assertFalse(pack.installed(context))
assertEquals("a".repeat(64), pack.dir(context).name)
}
@Test fun ciBuildWithoutAPinNeverReuses() {
installed("b".repeat(64))
assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = false).installed(context))
}
}
@@ -167,4 +167,10 @@ class DownloaderResumeTest {
assertEquals(listOf(catalog), DownloadSource.candidates(catalog))
}
@Test fun withoutADigestOnlyTheOriginalUrlIsTried() {
val url = "https://github.com/owner/repo/releases/download/v1/app.AppImage"
assertEquals(listOf(url), Downloader.sources(url, null))
assertEquals(DownloadSource.candidates(url), Downloader.sources(url, "a".repeat(64)))
}
}
@@ -7,6 +7,7 @@ class GameEnvironmentTest {
@Test fun defaultsIncludeRequestedGraphicsLevelsAndKeepCaching() {
val values = GameEnvironment.defaults("")
assertEquals("false", values["MESA_SHADER_CACHE_DISABLE"])
assertEquals("1", values["DROIDDECK_ANTICHEAT_OFFLINE"])
assertEquals("12_2", values["VKD3D_FEATURE_LEVEL"])
assertEquals("6_9", values["VKD3D_SHADER_MODEL"])
}
@@ -0,0 +1,86 @@
package com.droiddeck.launcher.core
import java.io.StringWriter
import java.io.Writer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class LogRedactorStreamTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun utf16AndNulDelimitedSecretsAreWithheld() {
val token = "synthetic_private_value"
for (encoding in listOf(Charsets.UTF_16LE, Charsets.UTF_16BE, Charsets.UTF_16)) {
val src = tmp.newFile()
src.writeBytes("sessionid=$token".toByteArray(encoding))
val out = StringWriter()
LogRedactor.scrubForShare(src, out)
assertFalse(out.toString().replace("\u0000", "").contains(token))
assertTrue(out.toString().contains("withheld"))
}
}
@Test fun aNulAfterTheInitialBinaryProbeWithholdsTheWholeLine() {
val src = tmp.newFile()
src.writeText(".".repeat(9000) + "\u0000sessionid=synthetic_private_value")
val out = StringWriter()
LogRedactor.scrubForShare(src, out)
assertFalse(out.toString().contains("synthetic_private_value"))
assertTrue(out.toString().contains("withheld"))
}
@Test fun aVeryLongLineIsWithheldAndTheFollowingLineIsScrubbed() {
val src = tmp.newFile()
src.bufferedWriter().use { writer ->
writer.write("sessionid=synthetic_private_value ")
repeat(128) { writer.write(".".repeat(64 * 1024)) }
writer.write("\nready=1 token=another_private_value\n")
}
val out = StringWriter()
LogRedactor.scrubForShare(src, out)
assertTrue("oversized line was retained", out.toString().length < 1024)
assertTrue(out.toString().contains("withheld"))
assertTrue(out.toString().contains("ready=1 token=<redacted:token>"))
assertFalse(out.toString().contains("private_value"))
}
@Test fun malformedUtf8WithholdsWithoutReturningTheUnredactedLine() {
val src = tmp.newFile()
src.writeBytes("sessionid=synthetic_private_value ".toByteArray() + byteArrayOf(0xc3.toByte(), 0x28))
val out = StringWriter()
LogRedactor.scrubForShare(src, out)
assertFalse(out.toString().contains("synthetic_private_value"))
assertTrue(out.toString().contains("withheld"))
}
@Test fun normalUnicodeAndLineEndingsKeepTheirDiagnosticContent() {
val src = tmp.newFile()
src.writeText("hazır=✓ token=synthetic_private_value\r\n\rstatus=ok\nson")
val out = StringWriter()
LogRedactor.scrubForShare(src, out)
assertEquals("hazır=✓ token=<redacted:token>\n\nstatus=ok\nson\n", out.toString())
}
@Test fun aLogAboveTheInMemoryLimitIsStillStreamed() {
val src = tmp.newFile()
val block = ("status=ok " + ".".repeat(4090) + "\n").repeat(16)
src.bufferedWriter().use { writer ->
while (src.length() <= LogRedactor.IN_MEMORY_SCRUB_MAX) {
writer.write(block)
writer.flush()
}
}
var chars = 0L
val out = object : Writer() {
override fun write(buffer: CharArray, offset: Int, length: Int) { chars += length }
override fun flush() {}
override fun close() {}
}
LogRedactor.scrubForShare(src, out)
assertEquals(src.length(), chars)
}
}
@@ -37,6 +37,83 @@ class LogRedactorTest {
assertEquals("login <redacted:email> ok", LogRedactor.redact("login someone@example.com ok"))
}
@Test fun onlyLoaderDiagnosticsKeepHidlSharedLibraryNames() {
val library = "android.hardware.graphics.mapper@4.0.so"
val line = "dlopen failed: library \"$library\" not found"
val pathLine = "dlopen failed: library \"/vendor/lib64/hw/$library\" not found"
assertEquals(line, LogRedactor.redact(line))
assertEquals(line, LogRedactor.redactForShare(line))
assertEquals(pathLine, LogRedactor.redact(pathLine))
assertEquals(pathLine, LogRedactor.redactForShare(pathLine))
}
@Test fun privacyRulesOverrideTheHidlSharedLibraryException() {
val library = "android.hardware.graphics.mapper@4.0.so"
assertEquals("token=<redacted:token>", LogRedactor.redact("token=$library"))
assertEquals("username=<redacted:account>", LogRedactor.redact("username=$library"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redact("{\"password\":\"$library\"}"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redactForShare("{\"password\":\"$library\"}"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redact("{\"password\":\"don't-use-$library\"}"))
assertEquals("{\"password\":\"<redacted:token>\"}", LogRedactor.redactForShare("{\"password\":\"don't-use-$library\"}"))
val mixed = "dlopen failed: library \"$library\" not found; token=abcdef123456; contact=alice!$library; {\"password\":\"library \\\"$library\\\" not found\"}"
val expected = "dlopen failed: library \"$library\" not found; token=<redacted:token>; contact=alice!<redacted:email>; {\"password\":\"<redacted:token>\"}"
assertEquals(expected, LogRedactor.redact(mixed))
assertEquals(expected, LogRedactor.redactForShare(mixed))
val root = java.nio.file.Files.createTempDirectory("hidl-redactor").toFile()
val users = java.io.File(root, "loginusers.vdf")
users.writeText("\"AccountName\" \"$library\"")
try {
LogRedactor.learnAccounts(users)
assertEquals("<redacted:account>", LogRedactor.redact(library))
} finally {
LogRedactor.learnAccounts()
root.deleteRecursively()
}
}
@Test fun hidlSharedLibraryNamesAreRedactedOutsideLoaderDiagnostics() {
val library = "android.hardware.graphics.mapper@4.0.so"
assertEquals("<redacted:email>", LogRedactor.redact(library))
assertEquals("<redacted:email>", LogRedactor.redactForShare(library))
assertEquals("/vendor/lib64/hw/<redacted:email>", LogRedactor.redact("/vendor/lib64/hw/$library"))
for (punctuation in listOf("!", "#", "~", "/", "=")) {
val expected = "contact=alice$punctuation<redacted:email>"
assertEquals(expected, LogRedactor.redact("contact=alice$punctuation$library"))
assertEquals(expected, LogRedactor.redactForShare("contact=alice$punctuation$library"))
}
assertEquals("<redacted:email>", LogRedactor.redact("$library.evil"))
assertEquals("<redacted:email>", LogRedactor.redact("someone@company.so"))
assertEquals("<redacted:email>", LogRedactor.redact("not$library"))
assertEquals("<redacted:email>_debug", LogRedactor.redact("${library}_debug"))
assertEquals("<redacted:email>.1", LogRedactor.redact("${library}.1"))
assertEquals("<redacted:email>@attacker", LogRedactor.redact("${library}@attacker"))
assertEquals("<redacted:email>", LogRedactor.redact("android.hardware.graphics.mapper@4.0.software"))
assertEquals("<redacted:email>", LogRedactor.redact("android.hardware.graphics.mapper@4.0.so.evil"))
}
@Test fun loaderContextRequiresExactWordsAndABoundedAndroidPath() {
val library = "android.hardware.graphics.mapper@4.0.so"
val valid = "library \"/system/lib64/$library\" not found: needed by app"
assertEquals(valid, LogRedactor.redact(valid))
assertEquals(valid, LogRedactor.redactForShare(valid))
for (line in listOf(
"not_library \"$library\" not found",
"library \"$library\" not found_suffix",
"library \"/home/user/$library\" not found",
"library \"relative/$library\" not found",
"library \"/vendor/invalid!/$library\" not found",
"library \"/vendor/" + "a/".repeat(2050) + "$library\" not found",
)) {
val expected = line.replace(library, "<redacted:email>")
assertEquals(expected, LogRedactor.redact(line))
assertEquals(expected, LogRedactor.redactForShare(line))
}
}
@Test fun clockTimeIsNotAnAddress() {
val line = "[2026-09-27 10:03:05] Startup"
assertEquals(line, LogRedactor.redact(line))
@@ -0,0 +1,172 @@
package com.droiddeck.launcher.files
import java.io.File
import java.util.concurrent.CancellationException
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermissions
import org.junit.Assume.assumeTrue
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class FileOpsCopyTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun cancellingAnOverwritePreservesTheDestinationAndSource() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") })
}
assertTrue("original destination was removed", dst.exists())
assertEquals("original user data", dst.readText())
assertEquals("replacement", src.readText())
assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet())
}
@Test fun cancellingANewCopyLeavesNoPartialDestination() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = File(tmp.root, "dest")
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") })
}
assertFalse(dst.exists())
assertEquals("replacement", src.readText())
assertEquals(setOf("source"), tmp.root.list()!!.toSet())
}
@Test fun cancellingAMoveFallbackPreservesBothFiles() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertThrows(CancellationException::class.java) {
FileOps.moveWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") })
}
assertTrue("original destination was removed", dst.exists())
assertEquals("original user data", dst.readText())
assertEquals("replacement", src.readText())
}
@Test fun cancellingStopsATreeOfEmptyFiles() {
val src = tmp.newFolder("source")
for (name in listOf("a", "b", "c")) File(src, name).createNewFile()
val dst = File(tmp.root, "dest")
var checks = 0
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, null) { checks++ > 1 }
}
assertEquals(1, dst.list()!!.size)
assertEquals(3, src.list()!!.size)
}
@Test fun cancellingStopsATreeOfEmptyFolders() {
val src = tmp.newFolder("source")
for (name in listOf("a", "b", "c")) File(src, name).mkdir()
val dst = File(tmp.root, "dest")
var checks = 0
assertThrows(CancellationException::class.java) {
FileOps.copyWithProgress(src, dst, null) { checks++ > 1 }
}
assertEquals(1, dst.list()!!.size)
}
@Test fun aCompletedCopyReplacesTheDestination() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("replacement", dst.readText())
assertEquals("replacement", src.readText())
assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet())
}
@Test fun aLongDestinationNameDoesNotOverflowTheStagingName() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = File(tmp.root, "d".repeat(240))
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("replacement", dst.readText())
}
@Test fun anOverwritePreservesTheTargetsExecutablePermissions() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original") }
val permissions = PosixFilePermissions.fromString("rwxr-x---")
Files.setPosixFilePermissions(dst.toPath(), permissions)
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("replacement", dst.readText())
assertEquals(permissions, Files.getPosixFilePermissions(dst.toPath()))
}
@Test fun aMoveFallbackPreservesTheTargetsExecutablePermissions() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original") }
val permissions = PosixFilePermissions.fromString("rwxr-x---")
Files.setPosixFilePermissions(dst.toPath(), permissions)
assertTrue(FileOps.moveWithProgress(src, dst, null))
assertFalse(src.exists())
assertEquals("replacement", dst.readText())
assertEquals(permissions, Files.getPosixFilePermissions(dst.toPath()))
}
@Test fun anOverwriteStillRefusesAReadOnlyDestination() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original") }
Files.setPosixFilePermissions(dst.toPath(), PosixFilePermissions.fromString("r--r--r--"))
try {
assertFalse(FileOps.copyWithProgress(src, dst, null))
assertEquals("original", dst.readText())
assertEquals("replacement", src.readText())
} finally {
dst.setWritable(true)
}
}
@Test fun anEmptyFileCanReplaceAnExistingFile() {
val src = tmp.newFile("source")
val dst = tmp.newFile("dest").apply { writeText("original user data") }
var callbacks = 0
assertTrue(FileOps.copyWithProgress(src, dst, { _, _ -> callbacks++ }))
assertEquals(0, callbacks)
assertEquals(0L, dst.length())
assertTrue(src.exists())
}
@Test fun aFailedPublicationPreservesTheDestinationAndCleansStaging() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFolder("dest")
File(dst, "keep").writeText("original user data")
assertFalse(FileOps.copyWithProgress(src, dst, null))
assertEquals("original user data", File(dst, "keep").readText())
assertEquals("replacement", src.readText())
assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet())
}
@Test fun aSuccessfulMoveFallbackDeletesTheSourceOnlyAfterCopying() {
val src = tmp.newFile("source").apply { writeText("replacement") }
val dst = tmp.newFile("dest").apply { writeText("original user data") }
assertTrue(FileOps.moveWithProgress(src, dst, null))
assertFalse(src.exists())
assertEquals("replacement", dst.readText())
assertEquals(setOf("dest"), tmp.root.list()!!.toSet())
}
@Test fun overwritingThroughASymlinkKeepsTheLinkAndUpdatesItsTarget() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val src = tmp.newFile("source").apply { writeText("replacement") }
val realTarget = tmp.newFile("real-target").apply { writeText("original user data") }
val link = File(tmp.root, "dest-link")
Files.createSymbolicLink(link.toPath(), realTarget.toPath())
assertTrue(FileOps.copyWithProgress(src, link, null))
assertTrue("destination symlink was replaced instead of written through", Files.isSymbolicLink(link.toPath()))
assertEquals("replacement", realTarget.readText())
}
}
@@ -0,0 +1,85 @@
package com.droiddeck.launcher.files
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class FileOpsLinksTest {
@get:Rule val tmp = TemporaryFolder()
private fun link(at: File, target: String): Boolean =
runCatching { Files.createSymbolicLink(at.toPath(), File(target).toPath()) }.isSuccess
@Test fun aMovedFolderKeepsItsLinks() {
val src = tmp.newFolder("game")
File(src, "data.bin").writeText("x")
assumeTrue("symlinks unavailable here", link(File(src, "lib.so"), "data.bin"))
val dst = File(tmp.root, "other/game")
File(dst, "keep").mkdirs()
assertTrue(FileOps.moveWithProgress(src, dst, null))
assertFalse(src.exists())
assertTrue(Files.isSymbolicLink(File(dst, "lib.so").toPath()))
assertEquals("data.bin", Files.readSymbolicLink(File(dst, "lib.so").toPath()).toString())
}
@Test fun aCopiedLinkPointsWhereTheOriginalDoes() {
val src = tmp.newFolder("a")
assumeTrue("symlinks unavailable here", link(File(src, "l"), "/nowhere/target"))
val dst = File(tmp.root, "b")
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertTrue(Files.isSymbolicLink(File(src, "l").toPath()))
assertTrue(Files.isSymbolicLink(File(dst, "l").toPath()))
}
@Test fun copyingALinkPreservesAnUnrelatedStagingName() {
val src = File(tmp.root, "source")
assumeTrue("symlinks unavailable here", link(src, "missing-target"))
val dst = File(tmp.root, "dest")
dst.writeText("old destination")
val sibling = File(tmp.root, ".dest.link-tmp")
sibling.writeText("unrelated user data")
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("unrelated user data", sibling.readText())
assertEquals("missing-target", Files.readSymbolicLink(dst.toPath()).toString())
assertEquals(setOf("source", "dest", ".dest.link-tmp"), tmp.root.list()!!.toSet())
}
@Test fun anUnrelatedStagingDirectoryDoesNotPreventCopyingALink() {
val src = File(tmp.root, "source")
assumeTrue("symlinks unavailable here", link(src, "missing-target"))
val sibling = tmp.newFolder(".dest.link-tmp")
File(sibling, "keep").writeText("unrelated user data")
assertTrue(FileOps.copyWithProgress(src, File(tmp.root, "dest"), null))
assertEquals("unrelated user data", File(sibling, "keep").readText())
}
@Test fun aLongDestinationNameDoesNotOverflowTheStagingName() {
val src = File(tmp.root, "source")
assumeTrue("symlinks unavailable here", link(src, "missing-target"))
val dst = File(tmp.root, "d".repeat(240))
assertTrue(FileOps.copyWithProgress(src, dst, null))
assertEquals("missing-target", Files.readSymbolicLink(dst.toPath()).toString())
}
@Test fun aLinkThatCannotReplaceTheDestinationLeavesItAlone() {
val src = tmp.newFolder("c")
assumeTrue("symlinks unavailable here", link(File(src, "l"), "x"))
val dst = File(tmp.root, "d")
File(dst, "l").mkdirs()
File(dst, "l/keep.txt").writeText("kept")
assertFalse(FileOps.copyWithProgress(File(src, "l"), File(dst, "l"), null))
assertEquals("kept", File(dst, "l/keep.txt").readText())
assertFalse(File(dst, ".l.link-tmp").exists())
}
}
@@ -4,6 +4,7 @@ import android.os.Environment
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -84,12 +85,141 @@ class AddedExesTest {
assertEquals(listOf(File(games, "Example").path), AddedExes.list(app).map { it.folder })
}
@Test fun anExeTheSessionCannotSeeIsNotAdded() {
@Test fun aGameInsideAFolderAddedAsOneGameIsAddedOnItsOwn() {
noGamesFolders()
val held = onStorage("Download/ADM/Death Stranding/ds.exe")
val pick = onStorage("Download/ADM/Pro Evolution Soccer 2017/PES2017.exe")
val container = held.parentFile!!.parentFile!!
AddedExes.put(app, AddedExes.Entry(container.path, held.path, picked = false))
val added = AddedGames.addExe(app, pick)
assertTrue(added is AddedGames.AddResult.Added)
assertEquals(pick.parentFile!!.path, (added as AddedGames.AddResult.Added).game.folder.path)
assertEquals(setOf(held.path, pick.path), AddedGames.scan(app).map { it.exe.path }.toSet())
}
@Test fun aRemovedFolderGameDoesNotComeBackForAnotherGame() {
noGamesFolders()
val held = onStorage("Download/ADM/Death Stranding/ds.exe")
val pick = onStorage("Download/ADM/Blur Game/Blur.exe")
val container = held.parentFile!!.parentFile!!
AddedExes.put(app, AddedExes.Entry(container.path, held.path, picked = false))
SessionPrefs.setAddedGameName(app, container.path, "Death Stranding Directors Cut")
AddedGames.remove(app, container)
val added = AddedGames.addExe(app, pick)
assertTrue(added is AddedGames.AddResult.Added)
assertEquals("Blur Game", (added as AddedGames.AddResult.Added).game.name)
assertTrue(container.path in SessionPrefs.removedAddedGames(app))
assertEquals(listOf(pick.path), AddedGames.scan(app).map { it.exe.path })
}
@Test fun anotherBuildOfTheSameExeInASiblingFolderSwitchesTheGame() {
noGamesFolders()
val held = onStorage("Games2/Oddworld/x64/Oddworld.exe")
val other = onStorage("Games2/Oddworld/x86/Oddworld.exe")
val folder = held.parentFile!!.parentFile!!
AddedExes.put(app, AddedExes.Entry(folder.path, held.path, picked = false))
val switched = AddedGames.addExe(app, other)
assertTrue(switched is AddedGames.AddResult.Switched)
assertEquals(folder.path, (switched as AddedGames.AddResult.Switched).game.folder.path)
assertEquals(listOf(other.path), AddedGames.scan(app).map { it.exe.path })
}
@Test fun aDifferentGameWithANumberedNameIsNotTakenAsAnotherBuild() {
noGamesFolders()
val held = onStorage("Games2/id/Doom/Doom.exe")
val pick = onStorage("Games2/id/Doom64/Doom64.exe")
AddedExes.put(app, AddedExes.Entry(held.parentFile!!.parentFile!!.path, held.path, picked = false))
assertTrue(AddedGames.addExe(app, pick) is AddedGames.AddResult.Added)
assertEquals(2, AddedGames.scan(app).size)
}
@Test fun anExeTheSessionCannotSeeBindsItsFolderAndIsAdded() {
noGamesFolders()
val outside = exe(File(tmp.newFolder("card"), "Hades/Hades.exe"))
assertNull(AddedGames.guestPath(app, outside))
val game = (AddedGames.addExe(app, outside) as AddedGames.AddResult.Added).game
assertEquals(listOf(outside.parent to "${AddedGames.GUEST_DIR}/Hades"), SessionPrefs.gameFolderBinds(app))
assertEquals("${AddedGames.GUEST_DIR}/Hades/Hades.exe", game.guestExe)
assertTrue(AddedGames.addExe(app, outside) is AddedGames.AddResult.Existing)
assertEquals(1, SessionPrefs.gameFolderBinds(app).size)
}
@Test fun anotherExeOfAGameTheSessionCannotSeeBindsTheGameFolder() {
noGamesFolders()
val held = exe(File(tmp.newFolder("card"), "Hades/Hades.exe"))
val pick = exe(File(held.parentFile, "x64/Hades.exe"))
AddedExes.put(app, AddedExes.Entry(held.parent!!, held.path, picked = false))
val switched = AddedGames.addExe(app, pick) as AddedGames.AddResult.Switched
assertEquals(listOf(held.parent to "${AddedGames.GUEST_DIR}/Hades"), SessionPrefs.gameFolderBinds(app))
assertEquals("${AddedGames.GUEST_DIR}/Hades/x64/Hades.exe", switched.game.guestExe)
}
@Test fun aGameFolderTheSessionAlreadySeesIsNotBoundAgain() {
noGamesFolders()
val held = onStorage("Games2/Hades/Hades.exe")
onStorage("Games2/Hades/x64/Hades.exe")
AddedExes.put(app, AddedExes.Entry(held.parent!!, held.path, picked = false))
val alias = File(tmp.root, "alias").toPath()
java.nio.file.Files.createSymbolicLink(alias, held.parentFile!!.parentFile!!.toPath())
assertEquals(AddedGames.AddResult.Unreachable, AddedGames.addExe(app, File(alias.toFile(), "Hades/x64/Hades.exe")))
assertEquals(0, SessionPrefs.gameFolderBinds(app).size)
}
@Test fun anExeInAFolderTheAppCannotReadIsNotAdded() {
noGamesFolders()
val outside = exe(File(tmp.newFolder("elsewhere"), "Game/Game.exe"))
assertEquals(AddedGames.AddResult.Unreachable, AddedGames.addExe(app, outside))
outside.parentFile!!.setReadable(false)
try {
assertEquals(AddedGames.AddResult.Unreachable, AddedGames.addExe(app, outside))
} finally {
outside.parentFile!!.setReadable(true)
}
assertEquals(0, AddedExes.list(app).size)
assertEquals(0, AddedGames.scan(app).size)
assertEquals(0, SessionPrefs.gameFolderBinds(app).size)
}
@Test fun addingAFolderTheSessionCannotSeeBindsItAndAddsItsGames() {
noGamesFolders()
val games = File(tmp.newFolder("card"), "Winlator/Games")
exe(File(games, "Alpha/Alpha.exe"))
exe(File(games, "Beta/Beta.exe"))
File(games, "steamapps").mkdirs()
assertNull(AddedGames.guestPath(app, games))
val result = AddedGames.addFolder(app, games)
assertEquals(listOf("Alpha", "Beta"), result.added.map { it.name })
assertEquals(listOf(games.path to "${AddedGames.GUEST_DIR}/Games"), SessionPrefs.gameFolderBinds(app))
assertEquals("${AddedGames.GUEST_DIR}/Games/Alpha/Alpha.exe", result.added.first().guestExe)
val again = AddedGames.addFolder(app, games)
assertEquals(0, again.added.size)
assertEquals(2, again.already)
assertEquals(1, SessionPrefs.gameFolderBinds(app).size)
}
@Test fun aSecondFolderWithTheSameNameGetsItsOwnGuestPath() {
noGamesFolders()
val first = File(tmp.newFolder("a"), "Games").apply { exe(File(this, "One/One.exe")) }
val second = File(tmp.newFolder("b"), "Games").apply { exe(File(this, "Two/Two.exe")) }
AddedGames.addFolder(app, first)
AddedGames.addFolder(app, second)
val guests = SessionPrefs.gameFolderBinds(app).map { it.second }
assertEquals(2, guests.toSet().size)
assertEquals("${AddedGames.GUEST_DIR}/Games", guests.first())
}
@Test fun aGuestPathAlreadyTakenIsNeverReused() {
noGamesFolders()
val a = File(tmp.newFolder("a"), "Games").apply { mkdirs() }
val b = File(tmp.newFolder("b"), "Games").apply { mkdirs() }
val c = File(tmp.newFolder("c"), "Games").apply { exe(File(this, "Three/Three.exe")) }
val clash = GamesFolderMigration.legacyRoots(listOf(a.path, b.path, c.path)).last().guest
SessionPrefs.setGameFolderBinds(app, listOf(a.path to "${AddedGames.GUEST_DIR}/Games", b.path to clash))
AddedGames.addFolder(app, c)
val guests = SessionPrefs.gameFolderBinds(app).map { it.second }
assertEquals(3, guests.size)
assertEquals(3, guests.toSet().size)
assertEquals("$clash-2", guests.last())
}
@Test fun aRemovedSingleExeGameStaysOffUntilPickedAgain() {
@@ -0,0 +1,19 @@
package com.droiddeck.launcher.frontend
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class AddedGamesSkipExeTest {
@Test fun gameTitlesContainingShortSkipWordsAreKept() {
listOf("BeachBuggyRacing.exe", "Reach.exe", "Breach.exe", "Crashday.exe", "CrashBandicoot.exe",
"Observer.exe", "Observer-Win64-Shipping.exe", "Game.exe").forEach { assertFalse(it, AddedGames.skipExe(it)) }
}
@Test fun installersToolsAndServersAreSkipped() {
listOf("unins000.exe", "setup.exe", "vc_redist.x64.exe", "DXSETUP.exe", "CrashReportClient.exe",
"UnityCrashHandler64.exe", "gamelaunchhelper.exe", "EACLauncher.exe", "DedicatedServer.exe",
"UE4Editor.exe", "valheim_server.exe", "GameConfig.exe", "GameConfigure.exe", "Settings.exe", "Updater.exe",
"EasyAntiCheat_Setup.exe").forEach { assertTrue(it, AddedGames.skipExe(it)) }
}
}
@@ -132,6 +132,23 @@ class GameFilesTest {
}
}
@Test fun longTitlesKeepTheirEndingAndStayApart() {
val folder = tmp.newFolder()
val first = game("32370", "STAR WARS™ Knights of the Old Republic™")
val second = game("208580", "STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™")
assertEquals("STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™.steam", GameFiles.filename(second))
GameFiles.sync(app, folder, listOf(first, second))
GameFiles.sync(app, folder, listOf(first, second))
assertEquals("32370", File(folder, "STAR WARS™ Knights of the Old Republic™.steam").readText())
assertEquals("208580", File(folder, "STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™.steam").readText())
assertEquals(2, folder.listFiles()!!.count { it.extension == GameFiles.EXTENSION })
assertEquals("a".repeat(200) + ".steam", GameFiles.filename(game(name = "a".repeat(300))))
assertEquals("a".repeat(199) + ".steam", GameFiles.filename(game(name = "a".repeat(199) + " b")))
assertEquals("Game.steam", GameFiles.filename(game(name = " . ")))
assertEquals("Game.steam", GameFiles.filename(game(name = "Game . .")))
assertEquals("a".repeat(197) + ".steam", GameFiles.filename(game(name = "a".repeat(197) + " . b")))
}
@Test fun refusesSymlinksLeavingTheExportFolder() {
val folder = tmp.newFolder()
val outside = tmp.newFile()
@@ -179,7 +179,7 @@ class GameIdentifierTest {
@Test
fun isJunkPeName_flagsLaunchersNotGames() {
for (junk in listOf("Rockstar Games Launcher Redirector", "GSE", "Steam", "Launcher", "Epic Games Launcher")) {
for (junk in listOf("Rockstar Games Launcher Redirector", "GSE", "Steam", "Launcher", "Epic Games Launcher", "BootstrapPackagedGame")) {
assertTrue("expected junk: $junk", GameIdentifier.isJunkPeName(junk))
}
for (real in listOf("God of War", "Grand Theft Auto V", "DARK SOULS: REMASTERED", "Hades")) {
@@ -36,7 +36,7 @@ class StoreGameArtTest {
}
@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"))) {
for ((store, id, title) in listOf(Triple(Store.GOG, "1207658924", "Heroes III"), Triple(Store.EPIC, "abc", "Celeste"), Triple(Store.AMAZON, "amzn1.x", "Yakuza 0"), Triple(Store.XBOX, "9NBLGGH4X1", "Forza Horizon"), Triple(Store.ITCH, "12345", "Night in the Woods"))) {
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)
@@ -13,6 +13,11 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -232,4 +237,95 @@ class GlassesCallbacksTest {
field("sink").set(null, null)
}
}
@Test fun pro2CallbacksUseSharedPoseAndRejectThePreviousConnection() {
fun v2(gen: Long) = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, gen) as VitureV2Link.Listener
var delivered: FloatArray? = null
var timestamp = 0L
field("sink").set(null, Glasses.PoseSink { x, y, z, w, time ->
delivered = floatArrayOf(x, y, z, w)
timestamp = time
})
try {
val q = floatArrayOf(0f, 0f, 0.6f, 0.8f)
v2(0).onPose(ByteArray(24), q, 100)
assertEquals(null, delivered)
v2(1).onPose(ByteArray(24), q, 101)
org.junit.Assert.assertArrayEquals(q, delivered, 0f)
assertEquals(101L, timestamp)
assertEquals(1L, field("imuPackets").getLong(null))
v2(1).onValue(VitureProtocol.MSG_GET_DISPLAY, 0x32)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(Glasses.state.value.sbs)
v2(1).onValue(VitureProtocol.MSG_GET_BRIGHTNESS, 8)
v2(1).onReady()
v2(1).onTracking(true)
v2(1).onLost()
generation(2)
shadowOf(Looper.getMainLooper()).idle()
assertEquals(2, Glasses.state.value.brightness)
assertTrue(Glasses.state.value.connected)
assertFalse(Glasses.state.value.supportsScreen3dof)
assertFalse(Glasses.state.value.tracking)
} finally { field("sink").set(null, null) }
}
@Test fun pro2DemandEndingBeforeTheFirstRestartPoseStillStopsTheStream() {
val writes = LinkedBlockingQueue<ByteArray>()
val incoming = LinkedBlockingQueue<VitureV2Link.Received>()
val firstPose = CountDownLatch(1)
val firstRead = CountDownLatch(1)
val delegate = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(Glasses, 1L) as VitureV2Link.Listener
val listener = object : VitureV2Link.Listener by delegate {
override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) {
delegate.onPose(raw, q, timeNs)
firstPose.countDown()
}
}
val transport = object : VitureV2Link.Transport {
override fun write(packet: ByteArray): Boolean { writes += packet; return true }
override fun read(timeoutMs: Long): VitureV2Link.Received? {
firstRead.countDown()
return incoming.poll(timeoutMs, TimeUnit.MILLISECONDS)
}
override fun close() {}
}
fun expectStream(stream: Int) = org.junit.Assert.assertArrayEquals(
VitureV2Protocol.imuControl(stream), writes.poll(2, TimeUnit.SECONDS))
fun updateImu() = Glasses::class.java.getDeclaredMethod("updateImu")
.apply { isAccessible = true }.invoke(Glasses)
val link = VitureV2Link(transport, listener)
field("link").set(null, link)
field("sink").set(null, null)
try {
expectStream(VitureV2Protocol.STREAM_POSE)
assertTrue("Bootstrap write did not complete", firstRead.await(2, TimeUnit.SECONDS))
val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0).putInt(1).putFloat(1f).putFloat(0f).putFloat(0f).putFloat(0f).array()
incoming += VitureV2Link.Received(VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload), System.nanoTime())
assertTrue(firstPose.await(2, TimeUnit.SECONDS))
shadowOf(Looper.getMainLooper()).idle()
expectStream(VitureV2Protocol.STREAM_OFF)
assertTrue(Glasses.state.value.supportsScreen3dof)
assertFalse(Glasses.state.value.tracking)
field("sink").set(null, Glasses.PoseSink { _, _, _, _, _ -> })
updateImu()
assertFalse(Glasses.state.value.tracking)
field("sink").set(null, null)
updateImu()
expectStream(VitureV2Protocol.STREAM_POSE)
expectStream(VitureV2Protocol.STREAM_OFF)
assertFalse(link.trackingActive)
assertFalse(Glasses.state.value.tracking)
} finally {
generation(2)
link.close()
field("link").set(null, null)
field("sink").set(null, null)
shadowOf(Looper.getMainLooper()).idle()
}
}
}
@@ -5,6 +5,14 @@ import org.junit.Assert.*
import org.junit.Test
class GlassesRenderingTest {
@Test fun modelTwoDRatesLimitChoicesAndSavedRatesFallBackToAnOfferedOne() {
val rokid = GlassesState(displayId = 2, width = 1920, height = 1080, hz = 60f, rates2d = listOf(60, 120))
assertEquals(listOf(60, 120), GlassesRendering.refreshRates(GlassesSettings(), rokid))
assertEquals(60, GlassesRendering.outputHz(GlassesSettings(refreshHz = 90), rokid))
assertEquals(120, GlassesRendering.outputHz(GlassesSettings(refreshHz = 120), rokid))
assertEquals(listOf(60, 90, 120), GlassesRendering.refreshRates(GlassesSettings(), rokid.copy(rates2d = listOf(60, 90, 120))))
}
private val ultra = GlassesState(
model = "VITURE Luma Ultra", connected = true, controllable = true,
displayId = 2, width = 1920, height = 1200,
@@ -155,6 +155,58 @@ class GlassesUsbTest {
assertEquals(listOf(gt), manager.requests)
}
@Test fun pro2RequestsPermissionWithoutTheSdkAndDoesNotClaimCompanionProducts() {
val pro2 = device(0x1301, name = "VITURE Luma Ultra")
manager.devices[pro2.deviceName] = pro2
refresh(ask = true)
assertEquals("VITURE Pro 2", state.value.model)
assertTrue(state.value.controllable)
assertTrue(state.value.experimental)
assertFalse(state.value.hardwareControls)
assertFalse(state.value.supportsDisplayModeControl)
assertFalse(state.value.supportsScreen3dof)
assertFalse(state.value.supportsSpatial)
assertEquals(listOf(pro2), manager.requests)
assertEquals(null, Glasses.deviceModel(device(0x1301, 0x1234, "VITURE Pro 2")))
assertEquals(null, Glasses.deviceModel(device(0x1102, name = "VITURE Pro 2")))
assertEquals(null, Glasses.deviceModel(device(0x1302, name = "VITURE Pro 2")))
val ultra = Glasses.deviceModel(device(0x1104)) as VitureProtocol.Model
assertEquals(VitureProtocol.Family.ULTRA, ultra.family)
assertTrue(ultra.needsSdk)
}
@Test fun pro2PoseAvailabilityDoesNotEnableDisplayOrHardwareWrites() {
val pro2 = device(0x1301)
manager.devices[pro2.deviceName] = pro2
manager.granted.add(pro2.deviceName)
val sent = mutableListOf<Int>()
field("linkDevice").set(null, pro2)
field("link").set(null, object : GlassesLink {
override val hasImu = true
override fun send(msgId: Int, payload: ByteArray): Boolean { sent += msgId; return true }
override fun close() {}
})
try {
refresh()
assertTrue(state.value.canControl)
assertTrue(state.value.supportsScreen3dof)
assertFalse(state.value.can3d)
assertFalse(state.value.supportsDisplayModeControl)
assertFalse(state.value.hardwareControls)
assertEquals(0, state.value.brightnessMax)
assertEquals(0, state.value.volumeMax)
Glasses.sendMode(0x32)
Glasses.setBrightness(5)
Glasses.setVolume(5)
shadowOf(Looper.getMainLooper()).idle()
assertTrue(sent.isEmpty())
} finally {
field("link").set(null, null)
field("linkDevice").set(null, null)
(field("handler").get(null) as Handler).removeCallbacksAndMessages(null)
}
}
@Test fun gtVendorRequestsPermissionAndRetainsMaxProductName() {
val gt = device(0xaf50, 0x3941, "RayNeo GT MAX")
manager.devices[gt.deviceName] = gt
@@ -209,6 +261,14 @@ class GlassesUsbTest {
assertEquals(null, Glasses.deviceModel(device(0x043e, 0x1234, "XREAL 1S")))
}
@Test fun rokidMaxRoutesThroughItsOwnModelAndSharedVendorIdNeedsTheName() {
val max = Glasses.deviceModel(device(0x162f, 0x04d2, "Rokid Max"))
assertTrue(max is RokidModel)
assertEquals("Rokid Max", max?.name)
assertEquals(null, Glasses.deviceModel(device(0x162f, 0x04d2, "Generic HID")))
assertTrue(Glasses.isGlassesDisplayName("Rokid Max"))
}
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"),
@@ -0,0 +1,94 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import org.junit.Assert.*
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
class RokidProtocolTest {
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun matrix(q: FloatArray) = HeadPose.fromGlasses(q[0], q[1], q[2], q[3])
@Test fun identityRequiresRokidProductString() {
assertEquals("Rokid Max", RokidModel.model(0x04d2, 0x162f, "Rokid Max")?.name)
assertEquals("Rokid Air", RokidModel.model(0x04d2, 0x162f, "Rokid Air")?.name)
assertNull(RokidModel.model(0x04d2, 0x162f, "USB Keyboard"))
assertNull(RokidModel.model(0x04d2, 0x162f, null))
assertNull(RokidModel.model(0x04d2, 0x1234, "Rokid Max"))
assertTrue(RokidModel.isDisplay("Rokid Max"))
}
@Test fun maxModesFollowRefreshAndStereoResolution() {
val max = RokidModel.model(0x04d2, 0x162f, "Rokid Max")!!
assertEquals(RokidModel.MODE_2D_60, max.mode(60, false, null))
assertEquals(RokidModel.MODE_2D_120, max.mode(120, false, null))
assertEquals(RokidModel.MODE_2D_60, max.mode(90, false, null))
assertEquals(listOf(60, 120), max.rates2d)
assertEquals(RokidModel.MODE_SBS_1200_60, max.mode(60, true, null))
assertEquals(RokidModel.MODE_SBS_1200_90, max.mode(90, true, null))
assertEquals(RokidModel.MODE_SBS_1080_60, max.mode(90, true, GlassesResolution(1920, 1080)))
assertTrue(max.sbs90)
assertFalse(max.hasSunblock)
}
@Test fun airStaysOnSixtyHertzModes() {
val air = RokidModel.model(0x04d2, 0x162f, "Rokid Air")!!
assertEquals(RokidModel.MODE_2D_60, air.mode(120, false, null))
assertEquals(RokidModel.MODE_SBS_1080_60, air.mode(90, true, null))
assertFalse(air.sbs90)
assertEquals(listOf(60), air.rates2d)
}
@Test fun brightnessStepsRoundTripTheDevicePercent() {
assertEquals(8, RokidModel.brightnessStep(80))
assertEquals(10, RokidModel.brightnessStep(100))
assertEquals(3, RokidModel.brightnessStep(32))
assertEquals(0, RokidModel.brightnessStep(0))
assertEquals(30, RokidModel.brightnessRaw(3))
assertEquals(100, RokidModel.brightnessRaw(12))
}
@Test fun capturedMaxCombinedReportParsesAccelGyroAndBrightness() {
val packet = hex("11d09b3e3700000000bb9eb03f9147f0c06e86c340306a43bc9c227b3ad3e6aebb000055c29a99abc1cdccfac10000000000000000000000000000503c000000")
val sample = RokidProtocol.Parser().parse(packet)!!
assertEquals(0x373e9bd0L, sample.timeNs)
assertEquals(1.380f, sample.accel.x, 0.001f)
assertEquals(-7.509f, sample.accel.y, 0.001f)
assertEquals(6.110f, sample.accel.z, 0.001f)
assertEquals(-0.0119f, sample.gyro.x, 0.0001f)
assertEquals(80, sample.brightness)
assertNull(RokidProtocol.Parser().parse(packet.copyOf(32)))
}
@Test fun airSeparateReportsPairOnSharedTimestamp() {
fun report(type: Int, time: Long, v: Vec3) = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN).apply {
put(0, 4); put(1, type.toByte()); putLong(9, time)
putFloat(21, v.x); putFloat(25, v.y); putFloat(29, v.z)
}.array()
val parser = RokidProtocol.Parser()
assertNull(parser.parse(report(1, 500, Vec3(0f, 9.81f, 0f))))
val sample = parser.parse(report(2, 500, Vec3(0.1f, 0f, 0f)))!!
assertEquals(500_000L, sample.timeNs)
assertEquals(9.81f, sample.accel.y, 0f)
assertEquals(0.1f, sample.gyro.x, 0f)
assertNull(sample.brightness)
assertNull(parser.parse(report(2, 600, Vec3(0f, 0f, 0f))))
}
@Test fun capturedRestingGravityStartsUpright() {
val pose = ImuFusion().update(1_000_000, Vec3(0.01f, 9.58f, -2.20f), Vec3(0f, 0f, 0f))!!
assertTrue(kotlin.math.abs(pose[3]) > 0.97f)
}
@Test fun capturedLeftTurnSignLooksLeft() {
val fusion = ImuFusion()
val first = matrix(fusion.update(1_000_000, Vec3(0f, 9.81f, 0f), Vec3(0f, 0f, 0f))!!)
var last = FloatArray(4)
repeat(1000) {
last = fusion.update((it + 2) * 1_000_000L, Vec3(0f, 9.81f, 0f), 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.01f)
}
}
@@ -130,6 +130,31 @@ class VitureProtocolTest {
assertArrayEquals(floatArrayOf(0f, 0f, sin(half).toFloat(), cos(half).toFloat()), q, 1e-5f)
}
@Test fun directPro2KeepsSdkOnlyFamiliesAndUnknownProductsIsolated() {
val direct = VitureProtocol.model(0x1301, "VITURE Luma Ultra")!!
assertEquals("VITURE Pro 2", direct.name)
assertEquals(VitureProtocol.Family.PRO2, direct.family)
assertFalse(direct.needsSdk)
assertFalse(direct.hardwareControls)
assertFalse(direct.supportsDisplayModeControl)
assertFalse(direct.hasSunblock)
assertEquals(0, direct.brightnessMax)
assertEquals(0, direct.volumeMax)
for (pid in listOf(0x1101, 0x1104, 0x1201, 0x1211)) {
val model = VitureProtocol.model(pid, null)!!
assertTrue(model.needsSdk)
assertTrue(model.hardwareControls)
assertTrue(model.supportsDisplayModeControl)
}
assertNull(VitureProtocol.model(0x1102, "VITURE Pro 2"))
assertNull(VitureProtocol.model(0x1302, "VITURE Pro 2"))
val sdk = VitureProtocol.sdkModel("Pro 2")!!
assertTrue(sdk.needsSdk)
assertTrue(sdk.hardwareControls)
assertTrue(sdk.supportsDisplayModeControl)
}
@Test fun imuFallsBackToEuler() {
val payload = ByteBuffer.allocate(12).putFloat(0f).putFloat(0f).putFloat(30f).array()
val q = VitureProtocol.imuQuaternion(payload)!!
@@ -0,0 +1,404 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.math.sqrt
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class VitureV2LinkTest {
private val transport = FakeTransport()
private val listener = RecordingListener()
private var link: VitureV2Link? = null
@After fun close() { link?.close() }
@Test fun writeAndAckDoNotBecomeReadyWithoutAValidPose() {
val link = start()
transport.feed(ack())
transport.feed(pose(1).also { it[8] = (it[8].toInt() xor 1).toByte() })
transport.feed(pose(2, floatArrayOf(0f, 0f, 0f, 0f)))
transport.feed(VitureV2Protocol.packet(VitureV2Protocol.EVENT_RAW, ByteArray(56)))
transport.flush()
assertFalse(link.ready)
assertFalse(link.hasImu)
assertFalse(link.trackingActive)
assertEquals(0, listener.readyCount.get())
assertTrue(listener.poses.isEmpty())
assertEquals(2L, link.badFrames)
val receiptTime = System.nanoTime()
val valid = pose(3)
transport.feed(valid, receiptTime)
transport.flush()
assertTrue(link.ready)
assertTrue(link.hasImu)
assertTrue(link.trackingActive)
assertEquals(1, listener.readyCount.get())
assertEquals(listOf(true), listener.tracking)
assertEquals(1, listener.poses.size)
assertEquals(receiptTime, listener.poses.single().timeNs)
assertArrayEquals(valid, listener.poses.single().raw)
}
@Test fun duplicatesAndBackwardTicksAreDroppedWhileUnsignedWrapAdvances() {
start()
for (tick in listOf(0xFFFFFFFEL, 0xFFFFFFFEL, 0xFFFFFFFDL, 0L, 0L, 0xFFFFFFFFL, 1L)) {
transport.feed(pose(tick))
}
transport.flush()
assertEquals(3, listener.poses.size)
assertEquals(1, listener.readyCount.get())
assertEquals(listOf(true), listener.tracking)
assertEquals(0L, link!!.badFrames)
}
@Test fun poseCollectedDuringBootstrapWriteDoesNotEstablishReadiness() {
transport.collectDuringNextWrite(pose(1))
val link = start()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertTrue(listener.poses.isEmpty())
transport.feed(pose(2))
transport.flush()
assertTrue(link.ready)
assertTrue(link.trackingActive)
assertEquals(1, listener.readyCount.get())
assertEquals(1, listener.poses.size)
}
@Test fun poseCollectedDuringResumeWriteDoesNotRestartTracking() {
val link = startReady(100)
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.flush()
transport.collectDuringNextWrite(pose(101))
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.flush()
assertFalse(link.trackingActive)
assertEquals(1, listener.poses.size)
transport.feed(pose(102))
transport.flush()
assertTrue(link.trackingActive)
assertEquals(2, listener.poses.size)
assertEquals(listOf(true, false, true), listener.tracking)
}
@Test fun stoppingAndRestartingRequiresANewPoseAndRejectsQueuedOldSamples() {
val link = startReady(100)
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0)))
assertFalse(link.trackingActive)
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.feed(pose(101))
transport.feed(ack())
transport.flush()
assertEquals(1, listener.poses.size)
assertTrue(link.ready)
assertFalse(link.trackingActive)
val beforeRestart = System.nanoTime()
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.feed(pose(102), beforeRestart)
transport.feed(ack())
transport.flush()
assertFalse(link.trackingActive)
assertEquals(1, listener.poses.size)
transport.feed(pose(0))
transport.flush()
assertTrue(link.trackingActive)
assertEquals(2, listener.poses.size)
assertEquals(1, listener.readyCount.get())
assertEquals(listOf(true, false, true), listener.tracking)
}
@Test fun onReadyCanStopBootstrapBeforeTheFirstPoseIsForwarded() {
val link = start()
listener.whenReady = { assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) }
transport.feed(pose(1))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.flush()
assertEquals(1, listener.readyCount.get())
assertTrue(link.ready)
assertFalse(link.trackingActive)
assertTrue(listener.poses.isEmpty())
assertEquals(listOf(true, false), listener.tracking)
}
@Test fun rapidStopStartCannotAcceptThePreviousStreamsPendingRead() {
val link = startReady()
val held = transport.hold(pose(2))
try {
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0)))
assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
} finally {
held.release.countDown()
}
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.flush()
assertFalse(link.trackingActive)
assertEquals(1, listener.poses.size)
assertEquals(listOf(true, false), listener.tracking)
transport.feed(pose(3))
transport.flush()
assertTrue(link.trackingActive)
assertEquals(2, listener.poses.size)
}
@Test fun onReadyCanCloseWithoutForwardingAPoseOrReportingLoss() {
val link = start()
listener.whenReady = link::close
transport.feed(pose(1))
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertTrue(listener.poses.isEmpty())
assertEquals(0, listener.lostCount.get())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun unsupportedSettersNeverProduceWritesAndQueriesKeepGenericIds() {
val link = startReady()
for ((id, payload) in listOf(
VitureProtocol.MSG_BRIGHTNESS to byteArrayOf(3),
VitureProtocol.MSG_VOLUME to byteArrayOf(3),
VitureProtocol.MSG_DISPLAY to byteArrayOf(0x32),
VitureProtocol.MSG_FILM to byteArrayOf(1),
VitureProtocol.MSG_IMU_RATE to byteArrayOf(3),
VitureProtocol.MSG_IMU to byteArrayOf(2),
VitureProtocol.MSG_IMU to byteArrayOf(),
VitureProtocol.MSG_GET_VOLUME to byteArrayOf(1),
)) assertFalse("msgId=$id", link.send(id, payload))
assertTrue(link.send(VitureProtocol.MSG_GET_IMU, byteArrayOf()))
transport.flush()
assertTrue(transport.writes.isEmpty())
val queries = listOf(
Triple(VitureProtocol.MSG_GET_BRIGHTNESS, VitureV2Protocol.MSG_GET_BRIGHTNESS, 3),
Triple(VitureProtocol.MSG_GET_VOLUME, VitureV2Protocol.MSG_GET_VOLUME, 5),
Triple(VitureProtocol.MSG_GET_DISPLAY, VitureV2Protocol.MSG_GET_DISPLAY, 0x31),
)
for ((genericId, wireId, value) in queries) {
assertTrue(link.send(genericId, byteArrayOf()))
transport.expectWrite(VitureV2Protocol.packet(wireId))
transport.feed(VitureV2Protocol.packet(wireId + VitureV2Protocol.RESPONSE_OFFSET,
byteArrayOf(0, value.toByte())))
}
transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET,
byteArrayOf(1, 7)))
transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET,
byteArrayOf(0, 7, 8)))
transport.flush()
assertEquals(queries.map { it.first to it.third }, listener.values)
}
@Test fun failureToWriteBootstrapClosesTransportAndReportsLoss() {
transport.failNextWrite.set(true)
val link = VitureV2Link(transport, listener).also { this.link = it }
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.hasImu)
assertFalse(link.trackingActive)
assertEquals(0, listener.readyCount.get())
assertEquals(1, listener.lostCount.get())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun rejectedStreamAckClosesWithoutMarkingTrackingActive() {
val link = start()
transport.feed(ack(status = 7))
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertEquals(1, listener.lostCount.get())
assertEquals(0, listener.readyCount.get())
assertTrue(listener.tracking.isEmpty())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun readFailureClearsTrackingAndClosesTransport() {
val link = startReady()
transport.disconnect()
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertEquals(listOf(true, false), listener.tracking)
assertEquals(1, listener.lostCount.get())
assertFalse(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1)))
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
}
@Test fun explicitCloseSendsOffOnceAndDoesNotReportLoss() {
val link = startReady()
link.close()
transport.awaitClosed()
assertFalse(link.ready)
assertFalse(link.trackingActive)
assertEquals(listOf(true, false), listener.tracking)
assertEquals(0, listener.lostCount.get())
assertEquals(1, transport.closeCount.get())
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
link.close()
assertFalse(link.send(VitureProtocol.MSG_GET_BRIGHTNESS, byteArrayOf()))
assertEquals(1, transport.closeCount.get())
assertTrue(transport.writes.isEmpty())
}
@Test fun sharedPoseProducesTheSourceRightUpBackRelativeRotation() {
startReady()
val baseline = listener.poses.single().q
val reference = HeadPose.recenter(HeadPose.fromGlasses(baseline[0], baseline[1], baseline[2], baseline[3]),
centerView = true)
val half = sqrt(0.5f)
val rotations = listOf(
floatArrayOf(half, half, 0f, 0f),
floatArrayOf(half, 0f, half, 0f),
floatArrayOf(half, 0f, 0f, half),
floatArrayOf(0.5f, -0.5f, 0.5f, -0.5f),
)
rotations.forEachIndexed { index, q -> transport.feed(pose(index + 2L, q)) }
transport.flush()
for ((source, event) in rotations.zip(listener.poses.drop(1))) {
val q = event.q
val relative = HeadPose.relative(reference, HeadPose.fromGlasses(q[0], q[1], q[2], q[3]))
assertArrayEquals(HeadPose.fromQuaternion(source[1], source[2], source[3], source[0]), relative, 1e-5f)
}
assertEquals(rotations.size + 1, listener.poses.size)
}
private fun start(): VitureV2Link = VitureV2Link(transport, listener).also {
link = it
transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
transport.flush()
}
private fun startReady(tick: Long = 1): VitureV2Link = start().also {
transport.feed(pose(tick))
transport.flush()
assertTrue(it.ready)
}
private fun ack(status: Int = 0) = VitureV2Protocol.packet(
VitureV2Protocol.MSG_IMU_CONTROL + VitureV2Protocol.RESPONSE_OFFSET, byteArrayOf(status.toByte()))
private fun pose(tick: Long, wxyz: FloatArray = floatArrayOf(1f, 0f, 0f, 0f)): ByteArray {
val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0x126).putInt(tick.toInt())
wxyz.forEach(payload::putFloat)
return VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload.array())
}
private data class PoseEvent(val raw: ByteArray, val q: FloatArray, val timeNs: Long)
private class RecordingListener : VitureV2Link.Listener {
val readyCount = AtomicInteger()
val lostCount = AtomicInteger()
val tracking = CopyOnWriteArrayList<Boolean>()
val values = CopyOnWriteArrayList<Pair<Int, Int>>()
val poses = CopyOnWriteArrayList<PoseEvent>()
@Volatile var whenReady: (() -> Unit)? = null
override fun onReady() { readyCount.incrementAndGet(); whenReady?.invoke() }
override fun onValue(msgId: Int, value: Int) { values += msgId to value }
override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) { poses += PoseEvent(raw.copyOf(), q.copyOf(), timeNs) }
override fun onTracking(active: Boolean) { tracking += active }
override fun onLost() { lostCount.incrementAndGet() }
}
private sealed interface ReadStep {
data class Packet(val received: VitureV2Link.Received) : ReadStep
data class Barrier(val reached: CountDownLatch) : ReadStep
data class HeldPacket(
val received: VitureV2Link.Received,
val entered: CountDownLatch = CountDownLatch(1),
val release: CountDownLatch = CountDownLatch(1),
) : ReadStep
data object Disconnected : ReadStep
}
private class FakeTransport : VitureV2Link.Transport {
val writes = LinkedBlockingQueue<ByteArray>(64)
val closeCount = AtomicInteger()
val failNextWrite = AtomicBoolean()
private val collectedDuringWrite = AtomicReference<ByteArray?>()
private val incoming = LinkedBlockingQueue<ReadStep>(128)
private val closed = CountDownLatch(1)
override fun write(packet: ByteArray): Boolean {
check(writes.offer(packet.copyOf()))
val success = !failNextWrite.getAndSet(false)
if (success) collectedDuringWrite.getAndSet(null)?.let { feed(it, System.nanoTime()) }
return success
}
override fun read(timeoutMs: Long): VitureV2Link.Received? = when (
val step = incoming.poll(timeoutMs, TimeUnit.MILLISECONDS)
) {
is ReadStep.Packet -> step.received
is ReadStep.Barrier -> { step.reached.countDown(); null }
is ReadStep.HeldPacket -> {
step.entered.countDown()
check(step.release.await(2, TimeUnit.SECONDS))
step.received
}
ReadStep.Disconnected -> throw IOException("Device disconnected")
null -> null
}
override fun close() { closeCount.incrementAndGet(); closed.countDown() }
fun feed(packet: ByteArray, timeNs: Long = System.nanoTime()) {
check(incoming.offer(ReadStep.Packet(VitureV2Link.Received(packet.copyOf(), timeNs))))
}
fun collectDuringNextWrite(packet: ByteArray) {
check(collectedDuringWrite.compareAndSet(null, packet.copyOf()))
}
fun disconnect() { check(incoming.offer(ReadStep.Disconnected)) }
fun hold(packet: ByteArray): ReadStep.HeldPacket {
val held = ReadStep.HeldPacket(VitureV2Link.Received(packet.copyOf(), System.nanoTime()))
check(incoming.offer(held))
assertTrue("Worker did not enter the held read", held.entered.await(2, TimeUnit.SECONDS))
return held
}
fun expectWrite(expected: ByteArray) {
assertArrayEquals(expected, writes.poll(2, TimeUnit.SECONDS))
}
fun flush() {
val reached = CountDownLatch(1)
check(incoming.offer(ReadStep.Barrier(reached)))
assertTrue("Worker did not consume queued reports", reached.await(2, TimeUnit.SECONDS))
}
fun awaitClosed() { assertTrue("Transport did not close", closed.await(2, TimeUnit.SECONDS)) }
}
}
@@ -0,0 +1,175 @@
// Fixtures adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
package com.droiddeck.launcher.glasses
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sqrt
class VitureV2ProtocolTest {
@Test fun requestsMatchUpstreamWireExamples() {
assertArrayEquals(hex("10 00 01 03 02 00 03 00 01 02"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))
assertArrayEquals(hex("10 00 01 03 02 00 04 00 02 02"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW))
assertArrayEquals(hex("10 00 01 03 02 00 00 00 00 00"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF))
assertArrayEquals(hex("10 00 22 31 00 00 00 00"),
VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_BRIGHTNESS))
}
@Test fun requestBoundsAndStreamLimitsAreEnforced() {
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(-1) }
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0x10000) }
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0, ByteArray(57)) }
assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.imuControl(3) }
assertThrows(IllegalArgumentException::class.java) {
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE, VitureV2Protocol.Rate.HZ_500)
}
assertArrayEquals(hex("10 00 01 03 02 00 07 00 02 05"),
VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW, VitureV2Protocol.Rate.HZ_1000))
val maximum = VitureV2Protocol.packet(0xFFFF, ByteArray(56) { 0xFF.toByte() })
assertEquals(64, maximum.size)
assertEquals(0x37C8, (maximum[6].toInt() and 0xFF) or ((maximum[7].toInt() and 0xFF) shl 8))
assertNotNull(VitureV2Protocol.parse(maximum))
}
@Test fun brightnessReplyMatchesUpstreamAndKeepsFailureStatus() {
val frame = VitureV2Protocol.parse(hex("10 00 22 51 02 00 03 00 00 03"))!!
val reply = VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_BRIGHTNESS)!!
assertTrue(reply.success)
assertEquals(0, reply.status)
assertArrayEquals(byteArrayOf(3), reply.body)
assertNull(VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_VOLUME))
assertNull(VitureV2Protocol.reply(frame, -1))
val failure = VitureV2Protocol.parse(hex("10 00 01 23 01 00 07 00 07"))!!
val failedReply = VitureV2Protocol.reply(failure, VitureV2Protocol.MSG_IMU_CONTROL)!!
assertFalse(failedReply.success)
assertEquals(7, failedReply.status)
assertTrue(failedReply.body.isEmpty())
val noStatus = VitureV2Protocol.parse(hex("10 00 01 23 00 00 00 00"))!!
assertNull(VitureV2Protocol.reply(noStatus, VitureV2Protocol.MSG_IMU_CONTROL))
}
@Test fun validatesReceiveBoundsBeforeReadingHeader() {
val valid = hex("10 00 22 51 02 00 03 00 00 03")
for (size in listOf(-1, 0, 7, 9, 11, 65, Int.MAX_VALUE)) {
assertNull("size=$size", VitureV2Protocol.parse(valid, size))
}
assertNull(VitureV2Protocol.parse(ByteArray(0)))
assertNull(VitureV2Protocol.parse(valid.copyOf(65)))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[0] = 0x11 }))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[1] = 1 }))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[6] = 0xFF.toByte() }))
assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[9] = 4 }))
}
@Test fun rejectsOversizedAndTruncatedDeclaredPayloads() {
val valid = hex("10 00 22 51 02 00 03 00 00 03")
assertNull(VitureV2Protocol.parse(valid.copyOf(9)))
val tooLong = valid.copyOf(64).also { it[4] = 57 }
assertNull(VitureV2Protocol.parse(tooLong))
tooLong[4] = 0xFF.toByte()
tooLong[5] = 0xFF.toByte()
assertNull(VitureV2Protocol.parse(tooLong))
val padded = valid.copyOf(64)
val parsed = VitureV2Protocol.parse(padded)!!
assertArrayEquals(byteArrayOf(0, 3), parsed.payload)
padded[9] = 8
assertArrayEquals(byteArrayOf(0, 3), parsed.payload)
}
@Test fun poseFixturePreservesDeviceCounterAndConvertsWxyzToNormalizedXyzw() {
val frame = VitureV2Protocol.parse(hex(
"10 00 08 73 18 00 9c 08 " +
"26 01 00 00 59 d6 21 00 dd e3 2b 3e 52 5d 7c 3f dd 45 9a 3b e8 27 52 3a"
))!!
val pose = VitureV2Protocol.pose(frame)!!
assertEquals(0x0021D659L, pose.deviceTick)
assertEquals(0x126L, pose.unknown)
val expected = floatArrayOf(Float.fromBits(0x3F7C5D52), Float.fromBits(0x3B9A45DD),
Float.fromBits(0x3A5227E8), Float.fromBits(0x3E2BE3DD))
val norm = sqrt(expected.sumOf { it.toDouble() * it }).toFloat()
assertArrayEquals(expected.map { it / norm }.toFloatArray(), pose.quaternion, 1e-7f)
assertEquals(1.0, pose.quaternion.sumOf { it.toDouble() * it }, 1e-6)
}
@Test fun poseNormalizesSmallScaleErrorsWithoutChangingAxesOrCounter() {
val payload = posePayload(0.5f, -0.5f, 0.5f, -0.5f)
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putInt(4, -1)
val pose = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload))!!
assertEquals(0xFFFFFFFFL, pose.deviceTick)
assertArrayEquals(floatArrayOf(-0.5f, 0.5f, -0.5f, 0.5f), pose.quaternion, 0f)
val scaled = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(1.01f, 0f, 0f, 0f)))!!
assertArrayEquals(floatArrayOf(0f, 0f, 0f, 1f), scaled.quaternion, 1e-7f)
}
@Test fun rejectsMalformedPoseAndInvalidQuaternions() {
val valid = posePayload(1f, 0f, 0f, 0f)
assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_RAW, valid)))
for (size in listOf(0, 23, 25, 56)) {
assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, valid.copyOf(size))))
}
for (bad in listOf(0f, 0.5f, 2f, Float.MAX_VALUE, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) {
assertNull("w=$bad", VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(bad, 0f, 0f, 0f))))
}
for (component in 1..3) {
val payload = valid.copyOf()
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(8 + component * 4, Float.NaN)
assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload)))
}
}
@Test fun rawReadsUnalignedFloatsAndPreservesUnknownBytes() {
val payload = rawPayload()
val frame = event(VitureV2Protocol.EVENT_RAW, payload)
val sample = VitureV2Protocol.raw(frame)!!
assertEquals(0xFFFFFFFEL, sample.deviceTick)
assertArrayEquals(floatArrayOf(1.5f, -2f, 0.25f), sample.gyroRadPerSec, 0f)
assertArrayEquals(floatArrayOf(0.0024f, -0.3221f, -0.9287f), sample.accelG, 0f)
assertArrayEquals(payload, sample.payload)
frame.payload.fill(0)
assertArrayEquals(payload, sample.payload)
}
@Test fun rejectsMalformedRawAndNonfiniteMeasurementsButKeepsOpaqueTail() {
val payload = rawPayload()
assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_POSE, payload)))
for (size in listOf(0, 24, 33, 34, 55)) {
assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload.copyOf(size))))
}
for (offset in listOf(10, 14, 18, 22, 26, 30)) {
for (bad in listOf(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) {
val invalid = payload.copyOf()
ByteBuffer.wrap(invalid).order(ByteOrder.LITTLE_ENDIAN).putFloat(offset, bad)
assertNull("offset=$offset, value=$bad", VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, invalid)))
}
}
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(46, Float.NaN)
assertNotNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload)))
}
private fun event(msgId: Int, payload: ByteArray) =
VitureV2Protocol.parse(VitureV2Protocol.packet(msgId, payload))!!
private fun posePayload(w: Float, x: Float, y: Float, z: Float) =
ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0x126).putInt(123).putFloat(w).putFloat(x).putFloat(y).putFloat(z).array()
private fun rawPayload() = ByteBuffer.allocate(56).order(ByteOrder.LITTLE_ENDIAN)
.putInt(0x126).putInt(-2).putShort(187)
.putFloat(1.5f).putFloat(-2f).putFloat(0.25f)
.putFloat(0.0024f).putFloat(-0.3221f).putFloat(-0.9287f)
.putFloat(117.30f).putFloat(60.75f).putFloat(254.85f)
.put(byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).array()
private fun hex(value: String) = value.split(' ').map { it.toInt(16).toByte() }.toByteArray()
}
@@ -62,4 +62,25 @@ class AutoDriverTrialTest {
assertNull(AutoDriverTrial.rollbackDue(context))
assertEquals("banner@r5", AutoDriverTrial.current(context)?.release)
}
@Test fun displayDriverCrashesBeforeSessionStartStillCount() {
AutoDriverTrial.displayStarting(context, "new-display")
assertNull(AutoDriverTrial.rollbackDue(context))
AutoDriverTrial.displayStarting(context, "new-display")
assertEquals(2, AutoDriverTrial.rollbackDue(context)?.starts)
}
@Test fun aNormalStartIsCountedOnce() {
AutoDriverTrial.displayStarting(context, "new-display")
AutoDriverTrial.sessionStarting(context, "new-display", "new-linux")
assertEquals(1, AutoDriverTrial.current(context)?.starts)
AutoDriverTrial.displayStarting(context, "other-display")
assertEquals(1, AutoDriverTrial.current(context)?.starts)
}
@Test fun aTrialStartedBeforeDisplayCountingStillRollsBackOnTheNextCrash() {
AutoDriverTrial.sessionStarting(context, "new-display", "new-linux")
AutoDriverTrial.displayStarting(context, "new-display")
assertEquals(2, AutoDriverTrial.rollbackDue(context)?.starts)
}
}
@@ -36,7 +36,13 @@ class FrameGenTest {
@Test fun onlyLsfgIsAdaptive() {
context.getSharedPreferences("frame_gen", Context.MODE_PRIVATE).edit()
.putString("engine", FrameGen.ENGINE_WINFG).putInt("multiplier", 4).putInt("target", 60).commit()
assertEquals(FrameGen.Mode(FrameGen.ENGINE_WINFG, 4), FrameGen.mode(context))
.putString("engine", FrameGen.ENGINE_DDFG).putInt("multiplier", 4).putInt("target", 60).commit()
assertEquals(FrameGen.Mode(FrameGen.ENGINE_DDFG, 4), FrameGen.mode(context))
}
@Test fun aSavedWinFgChoiceBecomesDdFg() {
context.getSharedPreferences("frame_gen", Context.MODE_PRIVATE).edit()
.putString("engine", "winfg").putInt("multiplier", 2).commit()
assertEquals(FrameGen.Mode(FrameGen.ENGINE_DDFG, 2), FrameGen.mode(context))
}
}
@@ -9,7 +9,7 @@ class GpuDetectionTest {
private fun info(adreno: Boolean, model: Int) =
GpuInfo(name = "x", model = model, family = GpuInfo.familyOf(adreno, model), soc = "", oneUi8Gen2 = false)
@Test fun modelIsTheFirstThreeDigitsOfWhateverTheKernelOrVulkanReports() {
@Test fun modelIsParsedOnlyFromAnAdrenoName() {
assertEquals(650, GpuInfo.threeDigits("Adreno650"))
assertEquals(830, GpuInfo.threeDigits("Adreno (TM) 830"))
assertEquals(740, GpuInfo.threeDigits("Adreno740v2"))
@@ -19,6 +19,12 @@ class GpuDetectionTest {
assertEquals(0, GpuInfo.threeDigits(" "))
assertEquals(0, GpuInfo.threeDigits("Adreno"))
assertEquals(0, GpuInfo.threeDigits("Adreno 65"))
assertEquals(850, GpuInfo.threeDigits("Adreno850v2"))
assertEquals(850, GpuInfo.threeDigits("Adreno (TM) 850"))
assertEquals(0, GpuInfo.threeDigits("44051431"))
assertEquals(0, GpuInfo.threeDigits("0x2a02be7"))
assertEquals(0, GpuInfo.threeDigits("Adreno 8500"))
assertEquals(0, GpuInfo.threeDigits("Mali-G850"))
}
@Test fun nonAdrenoRenderersAreNeverAdrenoWhateverNumberTheyCarry() {
@@ -53,12 +59,14 @@ class GpuDetectionTest {
assertEquals(Support.TESTED, info(true, 740).support)
assertEquals(Support.TESTED, info(true, 750).support)
assertEquals(Support.TESTED, info(true, 830).support)
assertEquals(Support.UNTESTED, info(true, 850).support)
assertEquals(Support.UNSUPPORTED, info(false, 0).support)
assertEquals(Support.UNSUPPORTED, info(false, 830).support)
}
@Test fun userFacingTextPerTier() {
assertEquals("Supported", info(true, 830).supportText)
assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", info(true, 850).supportText)
assertEquals("Experimental: its drivers are test builds", info(true, 720).supportText)
assertEquals("Outside tested hardware (Adreno 650, 725 and newer): it may not run", info(true, 618).supportText)
assertEquals("Not supported: DroidDeck needs an Adreno (Snapdragon) GPU", info(false, 0).supportText)
@@ -11,4 +11,61 @@ class GpuModelFallbackTest {
assertEquals(0, GpuInfo.platformModel("somethingelse"))
assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("pineapple")))
}
@Test fun sm8975IsTheOnlyNewSocFallback() {
assertEquals(850, GpuInfo.platformModel("unknown", "", "SM8975"))
assertEquals(850, GpuInfo.platformModel("unknown", "", "QTI SM8975"))
assertEquals(850, GpuInfo.platformModel("unknown", "QTI SM8975", ""))
assertEquals(850, GpuInfo.platformModel("unknown", "", " qti sm8975 "))
assertEquals(0, GpuInfo.platformModel("unknown", "", "SM89750"))
assertEquals(0, GpuInfo.platformModel("unknown", "", "SM8975-PRO"))
assertEquals(0, GpuInfo.platformModel("unknown", "", "Qualcomm SM8975"))
assertEquals(0, GpuInfo.platformModel("unknown", "", "SM8850"))
assertEquals(850, GpuInfo.platformModel("sun", "", "SM8975"))
assertEquals(830, GpuInfo.platformModel("sun", "", "unknown"))
}
@Test fun aKernelModelDoesNotNeedVulkanOrSocFallback() {
assertEquals(850 to "kernel", GpuInfo.modelFromNames("Adreno850v2",
{ error("Vulkan must not be queried when the kernel identifies the GPU") },
{ error("SoC must not override the kernel model") }))
}
@Test fun aMissingKernelModelUsesVulkanBeforeSocFallback() {
assertEquals(830 to "vulkan", GpuInfo.modelFromNames("Adreno", { "Adreno (TM) 830" },
{ error("SoC must not override the Vulkan model") }))
assertEquals(850 to "vulkan", GpuInfo.modelFromNames(null, { "Adreno850v2" }, { 0 }))
}
@Test fun numericChipIdsCannotHideTheSocFallback() {
for (name in listOf(null, "", "Adreno", "44051431", "0x2a02be7")) {
assertEquals(850 to "platform", GpuInfo.modelFromNames(name, { "Adreno" },
{ GpuInfo.platformModel("unknown", "", "QTI SM8975") }))
}
assertEquals(0 to "", GpuInfo.modelFromNames(null, { null }, { 0 }))
}
@Test fun sm8975StaysExperimentalWhenTheDriverReportsA840() {
val fallback = GpuInfo.platformModel("sun", "", "SM8975")
for (kernel in listOf("Adreno", "Adreno (TM) 840")) {
val (model, source) = GpuInfo.modelFromNames(kernel, { "Adreno (TM) 840" }, { fallback })
val gpu = GpuInfo("Adreno $model", model, GpuInfo.familyOf(true, model), "SM8975", false,
modelSource = source, platformGpuModel = fallback)
assertEquals(840, gpu.model)
assertEquals(if (kernel == "Adreno") "vulkan" else "kernel", gpu.modelSource)
assertEquals(GpuInfo.Support.UNTESTED, gpu.support)
assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", gpu.supportText)
}
}
@Test fun anA840WithoutSm8975KeepsItsExistingSupportStatus() {
for (fallback in listOf(0, 830, 840)) {
val gpu = GpuInfo("Adreno 840", 840, GpuInfo.Family.A8XX, "", false,
platformGpuModel = fallback)
assertEquals(GpuInfo.Support.TESTED, gpu.support)
assertEquals("Supported", gpu.supportText)
}
val otherGpu = GpuInfo("Mali", 0, GpuInfo.Family.NOT_ADRENO, "", false,
platformGpuModel = 850)
assertEquals(GpuInfo.Support.UNSUPPORTED, otherGpu.support)
}
}
@@ -21,4 +21,13 @@ class SocNamesTest {
assertEquals("Snapdragon 8 Gen 3 family (SG8350P)", SocNames.label("SG8350P", "pineapple"))
assertEquals("XYZ123", SocNames.label("XYZ123", ""))
}
@Test fun qtiPrefixIsNormalizedWithoutGuessingOtherModelVariants() {
assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("SM8975", ""))
assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("QTI SM8975", ""))
assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name(" qti sm8975 ", ""))
assertEquals("Snapdragon 8 Elite Extreme Gen 6 (QTI SM8975)", SocNames.label("QTI SM8975", ""))
assertNull(SocNames.name("SM89750", ""))
assertNull(SocNames.name("SM8975-PRO", ""))
assertNull(SocNames.name("Qualcomm SM8975", ""))
}
}
@@ -13,9 +13,15 @@ class TpUbwcHintTest {
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, "512.762.10"))
}
@Test fun a740OnOneUiTurnsTheHintOnWhateverTheBlobVersion() {
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, "512.676.53", samsung = true))
assertEquals("enable_tp_ubwc_flag_hint=1", TpUbwcHint.features(740, null, samsung = true))
}
@Test fun otherGpusKeepTheirDriverDefault() {
assertNull(TpUbwcHint.features(750, "512.762.10"))
assertNull(TpUbwcHint.features(830, "512.676.53"))
assertNull(TpUbwcHint.features(750, "512.676.53", samsung = true))
}
@Test fun anUnreadableSystemDriverKeepsTheDriverDefault() {
@@ -30,4 +30,17 @@ class TurnipDriverAutoTest {
@Test fun otherDevicesRetainTheGenericFallback() {
assertEquals("turnip25.1.0", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
}
@Test fun normalizedGpuModelsSelectExistingGenerationDrivers() {
for (sdk in listOf(28, 36)) {
assertEquals("turnip26.3.0-a6xx", TurnipDriver.chooseByModel(650, sdk))
assertEquals("turnip25.1.0", TurnipDriver.chooseByModel(730, sdk))
assertEquals("turnip-sdk36", TurnipDriver.chooseByModel(850, sdk))
}
}
@Test fun unknownGpuModelsRetainTheSdkFallback() {
assertEquals("turnip25.1.0", TurnipDriver.chooseByModel(0, 28))
assertEquals("turnip-sdk36", TurnipDriver.chooseByModel(0, 36))
}
}
@@ -45,11 +45,12 @@ class HandTrackingTest {
assertEquals(TrackingCameras.REAR, s.side)
}
@Test fun trackingNeedsThePermissionAndACamera() {
@Test fun trackingNeedsThePermissionACameraAndTheTrackingPack() {
val context = RuntimeEnvironment.getApplication()
assertFalse(both.copy(enabled = true).ready)
assertTrue(both.copy(enabled = true, permitted = true).ready)
assertFalse(HandTracking.Settings(enabled = true, permitted = true).ready)
assertFalse(both.copy(enabled = true, downloaded = true).ready)
assertFalse(both.copy(enabled = true, permitted = true).ready)
assertTrue(both.copy(enabled = true, permitted = true, downloaded = true).ready)
assertFalse(HandTracking.Settings(enabled = true, permitted = true, downloaded = true).ready)
shadowOf(context).grantPermissions(Manifest.permission.CAMERA)
HandTracking.refreshPermission(context)
assertTrue(HandTracking.settings.value.permitted)
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.view.MotionEvent
import java.time.Duration
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class DirectTouchHoldTest {
private val events = mutableListOf<String>()
private val hold = DirectTouchHold(8f, object : PointerGestures.Listener {
override fun onMove(x: Float, y: Float) {}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
assertEquals(PointerGestures.BTN_RIGHT, button)
events += "$pressed at $x,$y"
}
override fun onWheel(steps: Int) {}
override fun onLongPress() {}
}) { events += "cancel touch" }
@Test fun holdReleasesRawTouchBeforeClickAndConsumesTheLift() {
assertFalse(touch(MotionEvent.ACTION_DOWN))
advance(500)
assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events)
assertTrue(touch(MotionEvent.ACTION_UP))
advance(50)
assertEquals("false at 40.0,30.0", events.last())
assertFalse(touch(MotionEvent.ACTION_DOWN))
hold.cancel()
}
@Test fun tapDragSecondFingerAndCancellationDoNotRightClick() {
for (action in listOf(MotionEvent.ACTION_UP, MotionEvent.ACTION_MOVE,
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_CANCEL)) {
touch(MotionEvent.ACTION_DOWN)
assertFalse(touch(action, 60f))
advance(600)
assertTrue(events.isEmpty())
hold.cancel()
}
}
@Test fun modeChangeCancelsPendingHoldAndReleasesAnActiveClick() {
touch(MotionEvent.ACTION_DOWN)
hold.cancel()
advance(600)
assertTrue(events.isEmpty())
touch(MotionEvent.ACTION_DOWN)
advance(500)
hold.cancel()
advance(100)
assertEquals(listOf("cancel touch", "true at 40.0,30.0", "false at 40.0,30.0"), events)
}
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
private fun touch(action: Int, x: Float = 40f): Boolean {
val event = MotionEvent.obtain(0, 0, action, x, 30f, 0)
return hold.onTouch(event).also { event.recycle() }
}
}
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.input
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 GesturePrefsTest {
@Test fun removedOptionsAreIgnoredWhenLoadingExistingSettings() {
val old = """{"holdMouseButtonWhileTouchingEnabled":true,"holdMouseButtonWhileTouchingAction":"right_click",
"showClickHighlight":true,"showCursorInTouchscreenMode":true,"tapAction":"key_E","longPressDelay":650}"""
val config = TouchGestureConfig.fromJson(old)
assertEquals("key_E", config.tapAction)
assertEquals(650, config.longPressDelay)
assertFalse(config.toJson().contains("holdMouseButtonWhileTouching"))
assertFalse(config.toJson().contains("showClickHighlight"))
assertFalse(config.toJson().contains("showCursorInTouchscreenMode"))
}
@Test fun gameOverridesFallBackToDefaultsAndSurviveSerialization() {
val context = RuntimeEnvironment.getApplication()
val defaults = TouchGestureConfig(tapAction = "key_E", mouseDragMovementMode = "relative")
GesturePrefs.save(context, null, defaults)
assertEquals(defaults, GesturePrefs.read(context, "123"))
val game = defaults.copy(twoFingerTapAction = "show_keyboard", longPressDelay = 650)
GesturePrefs.save(context, "123", game)
assertEquals(game, GesturePrefs.read(context, "123"))
assertEquals(defaults, GesturePrefs.read(context, "456"))
GesturePrefs.clear(context, "123")
assertEquals(defaults, GesturePrefs.read(context, "123"))
}
}
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.os.SystemClock
import android.view.Gravity
import android.view.InputDevice
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.FrameLayout
import java.time.Duration
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.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class GestureRoutingTest {
@Test fun controlFingerDoesNotCountTowardGestureWhenControlIsTouchedFirst() = checkOrder(controlFirst = true)
@Test fun controlFingerDoesNotCountTowardGestureWhenScreenIsTouchedFirst() = checkOrder(controlFirst = false)
private fun checkOrder(controlFirst: Boolean) {
val context = RuntimeEnvironment.getApplication()
val buttons = mutableListOf<Pair<Int, Boolean>>()
val gestures = TouchscreenGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), object : TouchscreenGestures.Output {
override fun moveTo(x: Float, y: Float) {}
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {}
override fun button(code: Int, down: Boolean) { buttons += code to down }
override fun key(code: Int, down: Boolean) {}
override fun wheel(steps: Int) {}
override fun showKeyboard() {}
})
val root = FrameLayout(context).apply { isMotionEventSplittingEnabled = true }
root.addView(View(context).apply { setOnTouchListener { _, e -> gestures.onTouch(e) } }, FrameLayout.LayoutParams(1000, 600))
root.addView(View(context).apply { setOnTouchListener { _, _ -> true } }, FrameLayout.LayoutParams(200, 600, Gravity.RIGHT))
root.measure(View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY))
root.layout(0, 0, 1000, 600)
val firstX = if (controlFirst) 900f else 400f
val secondX = if (controlFirst) 400f else 900f
val downTime = SystemClock.uptimeMillis()
fun send(action: Int, index: Int, vararg points: Pair<Int, Float>) {
val properties = points.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray()
val coords = points.map { (_, px) -> MotionEvent.PointerCoords().apply { x = px; y = 300f; pressure = 1f; size = 1f } }.toTypedArray()
MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), points.size,
properties, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0).also {
root.dispatchTouchEvent(it); it.recycle()
}
}
send(MotionEvent.ACTION_DOWN, 0, 3 to firstX)
send(MotionEvent.ACTION_POINTER_DOWN, 1, 3 to firstX, 8 to secondX)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(30))
send(MotionEvent.ACTION_POINTER_UP, 1, 3 to firstX, 8 to secondX)
send(MotionEvent.ACTION_UP, 0, 3 to firstX)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100))
assertEquals(listOf(272 to true, 272 to false), buttons)
}
}
@@ -71,6 +71,17 @@ class PadBridgeRoutingTest {
InputDevice.KEYBOARD_TYPE_NONE, id = -1)
assertTrue(virtual.isVirtual)
assertFalse(PadBridge.isFromController(virtual))
for (uinputName in listOf("uinput-xiaomi", "uinput-fpc", "uinput_nav")) {
val phantom = device(
InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK,
InputDevice.KEYBOARD_TYPE_NONE,
name = uinputName,
)
assertFalse(phantom.isVirtual)
assertFalse(PadBridge.isFromController(phantom))
assertFalse(PadBridge.isControllerKeyEvent(key(phantom, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN)))
}
assertFalse(PadBridge.anyControllerConnected())
}
@Test fun keyAndMotionOwnershipDoesNotFollowEverySourceOnTheDevice() {
@@ -122,6 +133,21 @@ class PadBridgeRoutingTest {
}
}
@Test fun onlyAxesTheDeviceReportsReplaceKeyDrivenTriggersAndDpad() {
val js = InputDevice.SOURCE_JOYSTICK
val sticksOnly = device(js or InputDevice.SOURCE_GAMEPAD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, rangeSource = js, axis = MotionEvent.AXIS_X)
val withTrigger = device(js or InputDevice.SOURCE_GAMEPAD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, rangeSource = js, axis = MotionEvent.AXIS_LTRIGGER)
val withHat = device(js or InputDevice.SOURCE_GAMEPAD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, rangeSource = js, axis = MotionEvent.AXIS_HAT_Y)
val triggers = intArrayOf(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_BRAKE, MotionEvent.AXIS_GAS)
val hat = intArrayOf(MotionEvent.AXIS_HAT_X, MotionEvent.AXIS_HAT_Y)
assertFalse(PadBridge.hasAxis(sticksOnly, js, *triggers))
assertFalse(PadBridge.hasAxis(sticksOnly, js, *hat))
assertTrue(PadBridge.hasAxis(withTrigger, js, *triggers))
assertFalse(PadBridge.hasAxis(withTrigger, js, *hat))
assertTrue(PadBridge.hasAxis(withHat, js, *hat))
assertFalse(PadBridge.hasAxis(null, js, *hat))
}
private fun key(device: InputDevice, code: Int, action: Int, source: Int = InputDevice.SOURCE_KEYBOARD): KeyEvent {
val event = KeyEvent(0L, 0L, action, code, 0, 0, device.id, 0, 0, source)
assertSame(device, event.device)
@@ -131,8 +157,8 @@ class PadBridgeRoutingTest {
private var nextId = 10
private fun device(sources: Int, type: Int, keys: IntArray = intArrayOf(KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_DPAD_UP),
rangeSource: Int? = null, axis: Int = MotionEvent.AXIS_X, id: Int = nextId++): InputDevice {
val builder = InputDeviceBuilder.newBuilder().setId(id).setName("routing fixture $id")
rangeSource: Int? = null, axis: Int = MotionEvent.AXIS_X, id: Int = nextId++, name: String = "routing fixture $id"): InputDevice {
val builder = InputDeviceBuilder.newBuilder().setId(id).setName(name)
.setDescriptor("routing-$id").setExternal(true).setSources(sources).setKeyboardType(type)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD))
if (rangeSource != null) builder.addMotionRange(axis, rangeSource, -1f, 1f, 0f, 0f, 0f)
@@ -0,0 +1,128 @@
package com.droiddeck.launcher.input
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.*
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.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class, PadBridgeRoutingTest.RegisteredMotionEvent::class,
JoyConPadTest.RecordingWriter::class])
class PadPartialAxesTest {
private val directory = Files.createTempDirectory("partial-pad").toFile()
private lateinit var bridge: PadBridge
@Before fun start() {
JoyConPadTest.RecordingWriter.pads.clear()
bridge = PadBridge(directory)
assertTrue(bridge.start())
}
@After fun stop() {
bridge.stop()
directory.deleteRecursively()
}
@Test fun leftTriggerAxisPreservesRightTriggerKey() = trigger(MotionEvent.AXIS_LTRIGGER, false)
@Test fun brakeAxisPreservesRightTriggerKey() = trigger(MotionEvent.AXIS_BRAKE, false)
@Test fun rightTriggerAxisPreservesLeftTriggerKey() = trigger(MotionEvent.AXIS_RTRIGGER, true)
@Test fun gasAxisPreservesLeftTriggerKey() = trigger(MotionEvent.AXIS_GAS, true)
private fun trigger(axis: Int, leftKey: Boolean) {
val device = device(axis)
key(device, if (leftKey) KeyEvent.KEYCODE_BUTTON_L2 else KeyEvent.KEYCODE_BUTTON_R2)
motion(device, axis to 0.75f)
assertEquals(1f, if (leftKey) pad().leftTrigger else pad().rightTrigger)
assertEquals(0.75f, if (leftKey) pad().rightTrigger else pad().leftTrigger)
motion(device, axis to 0f)
assertEquals(1f, if (leftKey) pad().leftTrigger else pad().rightTrigger)
assertEquals(0f, if (leftKey) pad().rightTrigger else pad().leftTrigger)
}
@Test fun horizontalHatPreservesVerticalKeys() {
val device = device(MotionEvent.AXIS_HAT_X)
key(device, KeyEvent.KEYCODE_DPAD_UP)
motion(device, MotionEvent.AXIS_HAT_X to 1f)
assertTrue(pad().up)
assertTrue(pad().right)
motion(device, MotionEvent.AXIS_HAT_X to 0f)
assertTrue(pad().up)
assertFalse(pad().right)
}
@Test fun verticalHatPreservesHorizontalKeys() {
val device = device(MotionEvent.AXIS_HAT_Y)
key(device, KeyEvent.KEYCODE_DPAD_LEFT)
motion(device, MotionEvent.AXIS_HAT_Y to -1f)
assertTrue(pad().left)
assertTrue(pad().up)
motion(device, MotionEvent.AXIS_HAT_Y to 0f)
assertTrue(pad().left)
assertFalse(pad().up)
}
@Test fun wiredXboxTriggersStillUseTheirSignedZAxes() {
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ, wired = true)
motion(device, MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to 1f,
MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f)
assertEquals(0f, pad().leftTrigger)
assertEquals(1f, pad().rightTrigger)
assertEquals(0.6f, pad().rightX)
assertEquals(-0.6f, pad().rightY)
}
@Test fun sticksWithoutTriggerOrHatAxesPreserveAllDigitalControls() {
val device = device()
key(device, KeyEvent.KEYCODE_BUTTON_L2)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
key(device, KeyEvent.KEYCODE_DPAD_DOWN)
motion(device)
assertEquals(1f, pad().leftTrigger)
assertEquals(1f, pad().rightTrigger)
assertTrue(pad().down)
}
private fun pad(): PadState = requireNotNull(JoyConPadTest.RecordingWriter.pads[0])
private fun key(device: InputDevice, code: Int) {
assertTrue(bridge.onKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, code, 0, 0,
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)))
}
private fun motion(device: InputDevice, vararg values: Pair<Int, Float>) {
val coords = MotionEvent.PointerCoords().apply {
setAxisValue(MotionEvent.AXIS_X, 0.5f)
for ((axis, value) in values) setAxisValue(axis, value)
}
val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1,
arrayOf(MotionEvent.PointerProperties().apply { id = 0 }), arrayOf(coords),
0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0)
try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() }
}
private fun device(vararg axes: Int, wired: Boolean = false): InputDevice {
val builder = InputDeviceBuilder.newBuilder().setId(60).setName("partial pad")
.setDescriptor("partial-pad").setExternal(true)
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
.setVendorId(if (wired) 0x20d6 else 0).setProductId(if (wired) 0x2063 else 0)
for (axis in axes.toList() + MotionEvent.AXIS_X) {
builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0f, 0f, 0f)
}
return builder.build().also {
shadowOf(RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)).addInputDevice(it)
}
}
}
@@ -0,0 +1,266 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.os.SystemClock
import android.content.res.Configuration
import android.view.InputDevice
import android.view.MotionEvent
import android.view.SurfaceView
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.time.Duration
import org.junit.After
import org.junit.Assert.*
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.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, shadows = [SessionGestureRoutingTest.CompositorShadow::class])
class SessionGestureRoutingTest {
private lateinit var activity: SessionActivity
private lateinit var gestures: TouchscreenGestures
private lateinit var steamTap: ThreeFingerTap
private lateinit var launcherScroll: ScrollTouchGestures
private lateinit var directHold: DirectTouchHold
private val keys = mutableListOf<Pair<Int, Boolean>>()
private val directButtons = mutableListOf<Pair<Int, Boolean>>()
private val scrollPositions = mutableListOf<Pair<Float, Float>>()
private val scrollDeltas = mutableListOf<Pair<Float, Float>>()
private var keyboards = 0
@After fun tearDown() {
if (::gestures.isInitialized) gestures.cancel()
if (::launcherScroll.isInitialized) launcherScroll.cancel()
if (::directHold.isInitialized) directHold.cancel()
SessionState.mode = SessionService.MODE_STEAM
SessionState.steamUi = null
SessionState.suspended = false
}
@Test fun configuredThreeFingerActionTakesPrecedenceOverSteamShortcut() {
prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(threeFingerTapAction = "key_E"))
tapThreeFingers(expectSteamGesture = false)
assertEquals(listOf(18 to true, 18 to false), keys)
assertEquals(0, keyboards)
}
@Test fun disablingThreeFingerTapDoesNotFallBackToSteamShortcut() {
prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(threeFingerTapEnabled = false))
tapThreeFingers(expectSteamGesture = false)
assertTrue(keys.isEmpty())
assertEquals(0, keyboards)
}
@Test fun defaultThreeFingerActionOpensPcKeyboardOnce() {
prepare(SessionPrefs.TOUCH_GESTURES)
tapThreeFingers(expectSteamGesture = false)
assertEquals(1, keyboards)
assertTrue(keys.isEmpty())
}
@Test fun gestureModeKeepsItsBindingsWhileLauncherMouseIsAvailable() {
prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(threeFingerTapAction = "key_E"))
setField("padMouseOn", true)
tapThreeFingers(expectSteamGesture = false)
assertEquals(listOf(18 to true, 18 to false), keys)
assertTrue(scrollPositions.isEmpty())
assertTrue(scrollDeltas.isEmpty())
}
@Test fun directModeStillRoutesLauncherTouchesToScrolling() {
prepare(SessionPrefs.TOUCH_DIRECT)
setField("padMouseOn", true)
val down = SystemClock.uptimeMillis()
for ((index, action) in listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP).withIndex()) {
val event = MotionEvent.obtain(down, down + index * 32L, action, 400f, if (index == 0) 300f else 200f, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
}
assertEquals(listOf(400f to 300f), scrollPositions)
assertTrue(scrollDeltas.isNotEmpty())
assertTrue(keys.isEmpty())
assertFalse(steamTap.active)
}
@Test fun upstreamSteamShortcutStillReceivesTouchesInLegacyModes() {
for (mode in listOf(SessionPrefs.TOUCH_DIRECT, SessionPrefs.TOUCH_PAD)) {
prepare(mode)
tapThreeFingers(expectSteamGesture = true)
assertTrue(keys.isEmpty())
assertEquals(0, keyboards)
}
}
@Test fun configurationChangeReleasesHeldGestureAndResetsPointerAnchor() {
startLongPress()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350))
assertEquals(listOf(18 to true), keys)
activity.onConfigurationChanged(Configuration(activity.resources.configuration).apply {
orientation = Configuration.ORIENTATION_PORTRAIT
})
assertEquals(listOf(18 to true, 18 to false), keys)
assertFalse(SessionActivity::class.java.getDeclaredField("gesturePointerReady").apply { isAccessible = true }.getBoolean(activity))
}
@Test fun surfaceResizeCancelsPendingHoldAndResetsPointerAnchor() {
startLongPress()
setField("surfaceW", 1000)
setField("surfaceH", 600)
val window = android.view.Surface(android.graphics.SurfaceTexture(0))
var activeHolder: android.view.SurfaceHolder? = null
val surface = object : SurfaceView(RuntimeEnvironment.getApplication()) {
override fun getHolder() = activeHolder ?: super.getHolder()
}.apply { layout(0, 0, 1000, 600) }
activeHolder = object : android.view.SurfaceHolder by surface.holder {
override fun getSurface() = window
}
setField("surfaceView", surface)
try { activity.surfaceChanged(surface.holder, 0, 800, 600) } finally { window.release() }
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350))
assertTrue(keys.isEmpty())
assertFalse(SessionActivity::class.java.getDeclaredField("gesturePointerReady").apply { isAccessible = true }.getBoolean(activity))
}
@Test fun unchangedSurfaceDimensionsDoNotInterruptPendingHold() {
startLongPress()
setField("surfaceW", 1000)
setField("surfaceH", 600)
val surface = SessionActivity::class.java.getDeclaredField("surfaceView").apply { isAccessible = true }.get(activity) as SurfaceView
activity.surfaceChanged(surface.holder, 0, 1000, 600)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350))
assertEquals(listOf(18 to true), keys)
}
@Test fun inactiveSurfaceDestructionDoesNotInterruptCurrentGesture() {
startLongPress()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350))
val staleSurface = SurfaceView(RuntimeEnvironment.getApplication())
activity.surfaceDestroyed(staleSurface.holder)
assertEquals(listOf(18 to true), keys)
assertTrue(SessionActivity::class.java.getDeclaredField("gesturePointerReady").apply { isAccessible = true }.getBoolean(activity))
}
@Test fun pausingCancelsPendingHoldsInBothTouchModes() {
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
val now = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
ReflectionHelpers.callInstanceMethod<Unit>(activity, "onPause")
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(700))
assertTrue(keys.isEmpty())
assertTrue(directButtons.isEmpty())
}
}
@Test fun pausingReleasesActiveHoldsInBothTouchModes() {
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
keys.clear()
directButtons.clear()
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
val now = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
val gestureMode = mode == SessionPrefs.TOUCH_GESTURES
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(if (gestureMode) 350 else 500))
assertEquals(if (gestureMode) listOf(18 to true) else emptyList(), keys)
assertEquals(if (gestureMode) emptyList() else listOf(PointerGestures.BTN_RIGHT to true), directButtons)
ReflectionHelpers.callInstanceMethod<Unit>(activity, "onPause")
assertEquals(if (gestureMode) listOf(18 to true, 18 to false) else emptyList(), keys)
assertEquals(if (gestureMode) emptyList() else listOf(PointerGestures.BTN_RIGHT to true, PointerGestures.BTN_RIGHT to false), directButtons)
}
}
private fun startLongPress() {
prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
val now = SystemClock.uptimeMillis()
MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0).also {
try { assertTrue(activity.onTouchEvent(it)) } finally { it.recycle() }
}
setField("gesturePointerReady", true)
}
private fun prepare(mode: String, config: TouchGestureConfig = TouchGestureConfig()) {
SessionState.mode = SessionService.MODE_STEAM
SessionState.steamUi = "bigpicture"
SessionState.suspended = false
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
steamTap = ThreeFingerTap(8f)
gestures = TouchscreenGestures(8f, object : TouchscreenGestures.Output {
override fun moveTo(x: Float, y: Float) {}
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {}
override fun button(code: Int, down: Boolean) { fail("Unexpected mouse button: $code $down") }
override fun key(code: Int, down: Boolean) { keys += code to down }
override fun wheel(steps: Int) { fail("Unexpected wheel input") }
override fun showKeyboard() { keyboards++ }
}).also { it.configure(config) }
setField("routedTouchMode", mode)
setField("padMouseCheckedAt", SystemClock.uptimeMillis())
setField("threeFingerTap", steamTap)
setField("touchscreenGestures", gestures)
setField("surfaceView", SurfaceView(RuntimeEnvironment.getApplication()).apply { layout(0, 0, 1000, 600) })
setField("touchpad", TouchpadGestures(8f, object : PointerGestures.Listener {
override fun onMove(x: Float, y: Float) {}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {}
override fun onWheel(steps: Int) {}
override fun onLongPress() {}
}))
directHold = DirectTouchHold(8f, object : PointerGestures.Listener {
override fun onMove(x: Float, y: Float) {}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { directButtons += button to pressed }
override fun onWheel(steps: Int) {}
override fun onLongPress() {}
}) {}
setField("directTouchHold", directHold)
launcherScroll = ScrollTouchGestures(8f, 50f, object : ScrollTouchGestures.Listener {
override fun onMove(x: Float, y: Float) { scrollPositions += x to y }
override fun onButton(button: Int, pressed: Boolean) {}
override fun onScroll(dx: Float, dy: Float) { scrollDeltas += dx to dy }
override fun onLongPress() {}
})
setField("scrollTouch", launcherScroll)
}
private fun tapThreeFingers(expectSteamGesture: Boolean) {
val down = SystemClock.uptimeMillis()
fun send(action: Int, index: Int, count: Int) {
val properties = Array(count) { MotionEvent.PointerProperties().apply { id = it; toolType = MotionEvent.TOOL_TYPE_FINGER } }
val coordinates = Array(count) { MotionEvent.PointerCoords().apply { x = 300f + it * 100; y = 300f; pressure = 1f } }
val event = MotionEvent.obtain(down, SystemClock.uptimeMillis(), action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT),
count, properties, coordinates, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
}
send(MotionEvent.ACTION_DOWN, 0, 1)
send(MotionEvent.ACTION_POINTER_DOWN, 1, 2)
send(MotionEvent.ACTION_POINTER_DOWN, 2, 3)
assertEquals(expectSteamGesture, steamTap.active)
send(MotionEvent.ACTION_POINTER_UP, 2, 3)
send(MotionEvent.ACTION_POINTER_UP, 1, 2)
send(MotionEvent.ACTION_UP, 0, 1)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(200))
assertFalse(steamTap.active)
}
private fun setField(name: String, value: Any) {
SessionActivity::class.java.getDeclaredField(name).apply { isAccessible = true }.set(activity, value)
}
@Implements(value = WaylandCompositor::class, isInAndroidSdk = false)
class CompositorShadow {
companion object {
@JvmStatic @Implementation fun __staticInitializer__() {}
@JvmStatic @Implementation fun nativeSendTouch(action: Int, id: Int, x: Int, y: Int) {}
@JvmStatic @Implementation fun nativeSendSceneInput(type: Int, code: Int, value: Int) {}
}
}
}
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.view.View
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import java.nio.file.Files
import org.junit.After
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.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SessionKeyboardPadTest {
private lateinit var activity: SessionActivity
private lateinit var controls: OnScreenControls
private val directory = Files.createTempDirectory("keyboard-pad").toFile()
@Before fun setUp() {
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
activity.getSharedPreferences("session", 0).edit().clear().commit()
SessionState.mode = SessionService.MODE_STEAM
controls = OnScreenControls(activity, null).apply { visibility = View.GONE }
ReflectionHelpers.setField(activity, "onScreenControls", controls)
}
@After fun tearDown() {
steamKeyboard(false)
SteamTouchDevice.release()
directory.deleteRecursively()
SessionState.mode = SessionService.MODE_STEAM
}
@Test fun padStepsAsideWhileEitherKeyboardIsUpInSteam() {
SessionPrefs.setOscMode(activity, SessionPrefs.OSC_ALWAYS)
update()
assertEquals(View.VISIBLE, controls.visibility)
steamKeyboard(true)
update()
assertEquals(View.GONE, controls.visibility)
steamKeyboard(false)
update()
assertEquals(View.VISIBLE, controls.visibility)
pcKeyboard(true)
update()
assertEquals(View.GONE, controls.visibility)
pcKeyboard(false)
update()
assertEquals(View.VISIBLE, controls.visibility)
}
@Test fun steamsKeyboardLeavesThePadAloneOutsideSteam() {
SessionState.mode = SessionService.MODE_DESKTOP
SessionPrefs.setOscMode(activity, SessionPrefs.OSC_ALWAYS)
steamKeyboard(true)
update()
assertEquals(View.VISIBLE, controls.visibility)
pcKeyboard(true)
update()
assertEquals(View.GONE, controls.visibility)
}
@Test fun steamTouchControllerHidesAndHandsTouchBackWhileSteamsKeyboardIsUp() {
SteamTouchDevice.prepare(directory)
val steam = SteamTouchControls(activity, SteamTouchDevice.current!!, {}, {})
ReflectionHelpers.setField(activity, "steamTouchControls", steam)
ReflectionHelpers.setField(activity, "steamTouchOptions",
SteamTouchConfig.Options(inputMode = SteamTouchConfig.INPUT_CONTROLLER))
SessionPrefs.setTouchMode(activity, SessionPrefs.TOUCH_DIRECT)
SessionPrefs.setOscMode(activity, SessionPrefs.OSC_STEAM_TOUCH)
update()
assertEquals(View.VISIBLE, steam.visibility)
assertEquals(SessionPrefs.TOUCH_OFF, routedTouchMode())
steamKeyboard(true)
update()
assertEquals(View.GONE, steam.visibility)
assertTrue(SteamTouchDevice.current!!.plugged)
assertEquals(SessionPrefs.TOUCH_DIRECT, routedTouchMode())
steamKeyboard(false)
update()
assertEquals(View.VISIBLE, steam.visibility)
assertEquals(SessionPrefs.TOUCH_OFF, routedTouchMode())
}
@Test fun endingTheAgentForgetsSteamsKeyboard() {
steamKeyboard(true)
AgentGuest.stop()
shadowOf(Looper.getMainLooper()).idle()
assertFalse(AgentGuest.steamKeyboard)
}
private fun update() = ReflectionHelpers.callInstanceMethod<Any?>(activity, "updateOnScreenControls")
private fun routedTouchMode() = ReflectionHelpers.getField<String>(activity, "routedTouchMode")
private fun pcKeyboard(open: Boolean) {
ReflectionHelpers.getField<MutableState<Boolean>>(activity, "pcKeyboardOpen\$delegate").value = open
}
@Suppress("UNCHECKED_CAST")
private fun steamKeyboard(showing: Boolean) {
val field = AgentGuest::class.java.getDeclaredField("steamKeyboard\$delegate").apply { isAccessible = true }
(field.get(AgentGuest) as MutableState<Boolean>).value = showing
}
}
@@ -0,0 +1,69 @@
package com.droiddeck.launcher.input
import android.view.View
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import java.nio.file.Files
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.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SessionTouchRoutingTest {
private lateinit var activity: SessionActivity
private lateinit var steam: SteamTouchControls
private lateinit var touchpad: TouchpadGestures
private val directory = Files.createTempDirectory("touch-routing").toFile()
@Before fun setUp() {
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
activity.getSharedPreferences("session", 0).edit().clear().commit()
SessionState.mode = SessionService.MODE_STEAM
SteamTouchDevice.prepare(directory)
steam = SteamTouchControls(activity, SteamTouchDevice.current!!, {}, {})
steam.visibility = View.VISIBLE
touchpad = TouchpadGestures(8f, object : PointerGestures.Listener {
override fun onMove(x: Float, y: Float) {}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {}
override fun onWheel(steps: Int) {}
override fun onLongPress() {}
})
field("onScreenControls", OnScreenControls(activity, null).apply { visibility = View.GONE })
field("steamTouchControls", steam)
field("steamTouchOptions", SteamTouchConfig.Options(inputMode = SteamTouchConfig.INPUT_MOUSE, mouseMode = SteamTouchConfig.MOUSE_ABSOLUTE, trackpadSensitivity = 2f))
field("touchpad", touchpad)
field("routedTouchMode", SessionPrefs.TOUCH_DIRECT)
}
@After fun tearDown() {
SteamTouchDevice.release()
directory.deleteRecursively()
SessionState.mode = SessionService.MODE_STEAM
}
@Test fun disablingSteamTouchRestoresEverySavedModeEvenWhenRegularControlsAreAlreadyHidden() {
for (mode in listOf(SessionPrefs.TOUCH_PAD, SessionPrefs.TOUCH_DIRECT, SessionPrefs.TOUCH_AUTO, SessionPrefs.TOUCH_OFF)) {
SessionPrefs.setTouchMode(activity, mode)
SessionPrefs.setOscMode(activity, SessionPrefs.OSC_NEVER)
steam.visibility = View.VISIBLE
invoke("readPrefs")
assertEquals(SessionPrefs.TOUCH_DIRECT, ReflectionHelpers.getField<String>(activity, "routedTouchMode"))
invoke("updateOnScreenControls")
assertEquals(View.GONE, steam.visibility)
assertEquals(mode, ReflectionHelpers.getField<String>(activity, "routedTouchMode"))
assertEquals(1.15f, touchpad.sensitivity, 0f)
}
}
private fun field(name: String, value: Any) = ReflectionHelpers.setField(activity, name, value)
private fun invoke(name: String) = ReflectionHelpers.callInstanceMethod<Any?>(activity, name)
}
@@ -115,4 +115,20 @@ class SteamTouchBindingsTest {
assertEquals("Jump", SteamTouchBindings.bindingAt(reparsed, ref)!!.label)
assertNull(SteamTouchBindings.rewrite(config, SteamTouchBindings.Ref("5", "button_a")) { it })
}
@Test
fun labelsDropQuotesBackslashesCommasAndControls() {
assertEquals("a b c d e", SteamTouchBindings.cleanLabel("a\"b\\c,d\n e"))
assertEquals(32, SteamTouchBindings.cleanLabel("x".repeat(40)).length)
val b = SteamTouchBindings.Binding("key_press SPACE", "Ju\"mp", "", "", "")
assertEquals("Ju mp", SteamTouchBindings.parse(b.compose()).label)
val comma = SteamTouchBindings.Binding("key_press SPACE", "Jump,Run", "icon", "#FFFFFF", "")
assertEquals(SteamTouchBindings.Binding("key_press SPACE", "Jump Run", "icon", "#FFFFFF", ""), SteamTouchBindings.parse(comma.compose()))
}
@Test
fun labelsAreCutAtACharacterBoundary() {
val label = SteamTouchBindings.cleanLabel("a".repeat(31) + "🎮" + "b")
assertEquals("a".repeat(31) + "🎮", label)
}
}
@@ -57,4 +57,60 @@ class SteamTouchConfigFilesTest {
assertTrue(device.contains("\"8400\""))
assertEquals(saved, SteamTouchConfig.load(context, 204360).file)
}
private val template get() = File(steam, "controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf")
private fun shortcut(name: String): Int {
val shortcut = 2702387189L.toInt()
template.apply { parentFile!!.mkdirs(); writeText(touch("Gamepad with Joystick")) }
File(steam, "logs/console_log.txt").apply { parentFile!!.mkdirs() }.writeText(
"!! Controller 0 attributes:\n Type: 43\n" +
"Loaded Config for Last Resort Path for App ID 2702387189, Controller 0: /root/.local/share/Steam//controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf\n",
)
File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs() }
.writeText("\"users\"\n{\n\t\"76561197960265851\"\n\t{\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
val vdf = java.io.ByteArrayOutputStream().apply {
write("\u0000shortcuts\u0000\u00000\u0000\u0002appid\u0000".toByteArray())
write(java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.LITTLE_ENDIAN).putInt(shortcut).array())
write("\u0001AppName\u0000$name\u0000\u0008\u0008\u0008".toByteArray())
}
File(steam, "userdata/123/config/shortcuts.vdf").apply { parentFile!!.mkdirs() }.writeBytes(vdf.toByteArray())
return shortcut
}
@Test fun aShortcutFindsSteamsConfigAndSavesUnderItsName() {
val shortcut = shortcut("Epic Games Launcher")
val config = SteamTouchConfig.load(context, shortcut)
assertEquals(template, config.file)
assertEquals("Epic Games Launcher", SteamTouchConfig.gameName(context, shortcut))
val saved = SteamTouchConfig.saveLayouts(context, shortcut, config, mapOf(1 to emptyList()))
assertEquals(File(dir, "epic games launcher/controller_mobile_touch.vdf"), saved)
assertTrue(File(dir, "configset_controller_mobile_touch.vdf").readText().contains("\"epic games launcher\""))
assertEquals(saved, SteamTouchConfig.load(context, shortcut).file)
}
@Test fun aShortcutNameThatIsNoPlainFolderNameUsesTheAppId() {
for (name in listOf("../escape", "a/b", "..", "Tab\tName")) {
assertEquals(name, "2702387189", SteamTouchConfig.steamKey(context, shortcut(name)))
}
}
@Test fun aShortcutNameWithADollarSavesAgain() {
val shortcut = shortcut("Game $1")
val config = SteamTouchConfig.load(context, shortcut)
SteamTouchConfig.saveLayouts(context, shortcut, config, mapOf(1 to emptyList()))
val saved = SteamTouchConfig.saveLayouts(context, shortcut, SteamTouchConfig.load(context, shortcut), mapOf(1 to emptyList()))
assertEquals(File(dir, "game $1/controller_mobile_touch.vdf"), saved)
assertEquals(1, Regex("\"game \\$1\"").findAll(File(dir, "configset_controller_mobile_touch.vdf").readText()).count())
}
@Test fun aMixedCaseEntryOfTheShortcutIsReplacedNotDuplicated() {
val shortcut = shortcut("Epic Games Launcher")
configset("configset_controller_mobile_touch.vdf", "Epic Games Launcher" to "\"template\"\t\t\"controller_mobile_touch_gamepad_joystick.vdf\"")
configset("configset_MT-DROIDDECK0001.vdf", "Epic Games Launcher" to "\"workshop\"\t\t\"1\"")
SteamTouchConfig.saveLayouts(context, shortcut, SteamTouchConfig.load(context, shortcut), mapOf(1 to emptyList()))
val entries = Regex("\"epic games launcher\"", RegexOption.IGNORE_CASE)
assertEquals(1, entries.findAll(File(dir, "configset_controller_mobile_touch.vdf").readText()).count())
assertEquals(0, entries.findAll(File(dir, "configset_MT-DROIDDECK0001.vdf").readText()).count())
}
}
@@ -65,4 +65,27 @@ class SteamTouchConfigTest {
val config = SteamTouchConfig.Config(null, null, null, emptyMap(), kv)
assertEquals(listOf(1 to "Desktop", 2 to "Gamepad"), SteamTouchConfig.actionSets(config))
}
@Test
fun remapHeldKeepsSurvivingControlsAndDropsRemovedOrNullOnes() {
val layouts = SteamTouchConfig.decodeLayouts(SteamTouchConfig.hexToBytes(saved))
val baseConfig = SteamTouchConfig.Config(null, null, layouts, mapOf(0 to setOf(SteamTouchConfig.A, SteamTouchConfig.JOYSTICK_LEFT)))
val layerConfig = SteamTouchConfig.Config(null, null, layouts, mapOf(0 to setOf(SteamTouchConfig.A), 1 to setOf(SteamTouchConfig.B)))
val after = SteamTouchConfig.elementsFor(layerConfig, 0, listOf(2))
val remapped = SteamTouchConfig.remapHeld(
mapOf(
7 to SteamTouchConfig.A,
8 to SteamTouchConfig.JOYSTICK_LEFT,
9 to null,
10 to SteamTouchConfig.B,
),
after,
)
assertEquals(setOf(7, 10), remapped.keys)
assertEquals(after.first { it.type == SteamTouchConfig.A }, remapped[7])
assertEquals(after.first { it.type == SteamTouchConfig.B }, remapped[10])
assertFalse(baseConfig.availableFor(0, emptyList()).isEmpty())
}
}
@@ -5,6 +5,8 @@ import android.os.Looper
import android.view.MotionEvent
import java.time.Duration
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
@@ -109,6 +111,96 @@ class TouchpadGesturesTest {
assertEquals(listOf("left down", "left up"), events)
}
@Test fun liftingTheSecondFingerAfterAScrollKeepsTheCursorStill() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 600f), 2 to (600f to 610f))
assertTrue(events.contains("wheel -8"))
advance(10)
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 600f), 2 to (600f to 610f))
advance(10)
val sx = touchpad.x
val sy = touchpad.y
touch(MotionEvent.ACTION_MOVE, 0, 1 to (401f to 601f))
assertEquals(sx, touchpad.x, 0.01f)
assertEquals(sy, touchpad.y, 0.01f)
assertFalse(events.contains("move"))
}
@Test fun trackingResumesNormallyAfterTheScroll() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 600f), 2 to (600f to 610f))
advance(10)
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 600f), 2 to (600f to 610f))
advance(10)
val sy = touchpad.y
touch(MotionEvent.ACTION_MOVE, 0, 1 to (401f to 621f))
val delta = touchpad.y - sy
assertTrue(delta in 20f..65f)
assertTrue(events.contains("move"))
}
@Test fun liftingTheAnchorFirstAfterAScrollKeepsTheCursorStill() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 600f), 2 to (600f to 610f))
advance(10)
touch(MotionEvent.ACTION_POINTER_UP, 0, 1 to (400f to 600f), 2 to (600f to 610f))
advance(10)
val sx = touchpad.x
val sy = touchpad.y
touch(MotionEvent.ACTION_MOVE, 0, 2 to (601f to 611f))
assertEquals(sx, touchpad.x, 0.01f)
assertEquals(sy, touchpad.y, 0.01f)
assertFalse(events.contains("move"))
}
@Test fun twoFingerScrollWithLeadingFingerDoesNotPressLeft() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 300f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 303f), 2 to (600f to 310f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 340f), 2 to (600f to 350f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 380f), 2 to (600f to 390f))
assertFalse(events.contains("left down"))
assertTrue(events.any { it.startsWith("wheel ") })
}
@Test fun holdDragStillWorks() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 300f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 300f), 2 to (620f to 300f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 300f), 2 to (640f to 300f))
assertEquals("left down", events.firstOrNull())
assertTrue(events.contains("move"))
touch(MotionEvent.ACTION_POINTER_UP, 0, 1 to (400f to 300f), 2 to (640f to 300f))
assertTrue(events.contains("left up"))
}
@Test fun anchorMovedLocksOutHoldDrag() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 300f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 309f), 2 to (600f to 302f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 309f), 2 to (640f to 302f))
assertFalse(events.contains("left down"))
}
private fun tap() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(80)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,13 @@
package com.droiddeck.launcher.input
import org.junit.Assert.assertEquals
import org.junit.Test
class VrControllersTest {
@Test fun encodesTheKeysTheSteamVrDriverReads() {
assertEquals("emulate=index\nsticks=game\n", VrControllers.encode(VrControllers.Settings()))
assertEquals("emulate=touch\nsticks=hands\n",
VrControllers.encode(VrControllers.Settings(VrControllers.Emulate.TOUCH, sticksMoveHands = true)))
assertEquals(listOf("off", "index", "touch", "vive"), VrControllers.Emulate.entries.map { it.key })
}
}
@@ -118,4 +118,31 @@ class BwrapSpawnerPlanTest {
assertEquals("/app", plan.cwd)
assertEquals("org.example.Game", plan.env["FLATPAK_ID"])
}
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
val context = RuntimeEnvironment.getApplication()
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
File(app, "bin/zypak-wrapper.sh").writeText("#!/usr/bin/bash\nexec zypak-helper host - \"\$@\"\n")
Files.createSymbolicLink(File(app, "bin/zypak-wrapper").toPath(), java.nio.file.Paths.get("/app/bin/zypak-wrapper.sh"))
val plan = BwrapSpawner.plan(context, request(
op("t" to "bind", "src" to "/runtime-files/app", "dest" to "/app", "ro" to true),
), dir)
val shim = plan.binds.single { it.guest == "/app/bin/zypak-wrapper.sh" }
assertTrue(shim.host.startsWith(dir.path))
assertTrue(File(shim.host).readText().contains("exec \"\$program\" --no-sandbox \"\$@\""))
assertFalse(plan.binds.any { it.guest == "/app/bin/zypak-wrapper" })
assertTrue(File(app, "bin/zypak-wrapper.sh").readText().contains("zypak-helper"))
}
@Test fun appsWithoutZypakKeepTheirFiles() {
val context = RuntimeEnvironment.getApplication()
File(runtime, "app/bin").mkdirs()
val plan = BwrapSpawner.plan(context, request(
op("t" to "bind", "src" to "/runtime-files/app", "dest" to "/app", "ro" to true),
), dir)
assertFalse(plan.binds.any { it.guest.startsWith("/app/bin/") })
assertFalse(File(dir, "zypak-wrapper").exists())
}
}
@@ -0,0 +1,32 @@
package com.droiddeck.launcher.runtime
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class DeckyChannelTest {
private fun release(tag: String, prerelease: Boolean) =
DeckyManager.Release(tag, prerelease, "PluginLoader-arm64", "https://example.invalid/$tag", null, null, 1, 183)
@Test fun stableSkipsPrereleasesAndPrereleaseTakesTheNewestTag() {
val pre = release("v3.4.0-pre1", true)
val stable = release("v3.3.0", false)
val channels = DeckyManager.ReleaseChannels(listOf(stable), listOf(pre), listOf(pre, stable))
assertEquals("v3.3.0", DeckyManager.latest(channels, DeckyManager.BRANCH_STABLE)?.tag)
assertEquals("v3.4.0-pre1", DeckyManager.latest(channels, DeckyManager.BRANCH_PRERELEASE)?.tag)
}
@Test fun prereleaseFollowsAStableThatShippedAfterTheLastPrerelease() {
val stable = release("v3.3.0", false)
val pre = release("v3.3.0-pre1", true)
val channels = DeckyManager.ReleaseChannels(listOf(stable), listOf(pre), listOf(stable, pre))
assertEquals("v3.3.0", DeckyManager.latest(channels, DeckyManager.BRANCH_PRERELEASE)?.tag)
}
@Test fun stableHasNothingWhenOnlyPrereleasesExist() {
val pre = release("v3.4.0-pre1", true)
assertNull(DeckyManager.latest(DeckyManager.ReleaseChannels(emptyList(), listOf(pre), listOf(pre)), DeckyManager.BRANCH_STABLE))
}
}
@@ -2,12 +2,16 @@ package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.BuildConfig
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class DesktopCatalogTest {
@get:Rule val temporary = TemporaryFolder()
@@ -30,4 +34,26 @@ class DesktopCatalogTest {
kwin.delete()
assertFalse(DesktopCatalog.desktopInstalled(root))
}
@Test fun anInterruptedInstallIsFoundAgainWithEverythingNeededToFinishIt() {
val root = temporary.root
val entry = DesktopCatalog.Entry(
DesktopCatalog.DESKTOP_ID, "Desktop", 1, "desktop-kde-r2", "tar",
"https://example.invalid/desktop-kde.tar.zst", "a".repeat(64), 846933224L, "", "", "",
)
assertTrue(DesktopCatalog.interrupted(root).isEmpty())
File(root, ".droiddeck-pkg-${entry.id}.installing").writeText(DesktopCatalog.entryJson(entry).toString())
File(root, ".droiddeck-pkg-emulators.installing").writeText("not json")
File(root, ".droiddeck-pkg-emulators").writeText("1")
val found = DesktopCatalog.interrupted(root).single()
assertEquals(entry.id, found.id)
assertEquals(entry.version, found.version)
assertEquals(entry.url, found.url)
assertEquals(entry.sha256, found.sha256)
assertEquals(entry.size, found.size)
assertEquals(entry.kind, found.kind)
}
}
@@ -0,0 +1,122 @@
package com.droiddeck.launcher.runtime
import android.content.ContextWrapper
import com.droiddeck.launcher.BuildConfig
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.util.zip.GZIPInputStream
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class DesktopRemovalTest {
private val dir = Files.createTempDirectory("desktop-removal").toFile()
private val context = object : ContextWrapper(RuntimeEnvironment.getApplication()) {
override fun getFilesDir() = File(dir, "files").apply { mkdirs() }
override fun getCacheDir() = File(dir, "cache").apply { mkdirs() }
}
private val root = LinuxRuntime.rootDir(context).apply { mkdirs() }
private val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
private val journal = File(root, marker.name + ".installing")
private val pending = File(root, DesktopRemoval.PENDING)
private val listener = LinuxRuntimeInstaller.ProgressListener { _, _ -> }
@After fun cleanup() { dir.deleteRecursively() }
@Test fun removesTheDesktopWhileKeepingRuntimeAppsGamesAndSettings() {
val desktop = desktopFiles()
marker.writeText(BuildConfig.DESKTOP_KDE_TAG)
val keep = listOf("root/.local/share/Steam/steamapps/common/game/data", "root/.config/kdeglobals",
"opt/appimages/custom.AppImage", "usr/lib/shared.so", "usr/share/plasma/custom")
.map { file(it, "keep") }
assertTrue(DesktopCatalog.desktopPresent(context))
assertNull(DesktopCatalog.removeDesktop(context, listener))
assertFalse(Files.exists(desktop.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS))
keep.forEach { assertEquals("keep", it.readText()) }
assertFalse(DesktopCatalog.desktopPresent(context))
assertFalse(DesktopCatalog.desktopInstalled(context))
}
@Test fun interruptedInstallCanBeRemovedWithoutBeingResumedAtTheNextLaunch() {
desktopFiles()
val entry = DesktopCatalog.desktopEntry(context)
journal.writeText(DesktopCatalog.entryJson(entry).toString())
val download = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download").apply { writeText("download") }
val resume = File(download.path + ".resume.properties").apply { writeText("resume") }
val unrelated = file(".droiddeck-pkg-emulators.installing", DesktopCatalog.entryJson(DesktopCatalog.Entry(
"emulators", "Emulators", 1, "1", "tar", "https://example.invalid/emulators", "a".repeat(64), 1L, "", "", "",
)).toString())
assertTrue(DesktopCatalog.desktopPresent(context))
assertNotNull(DesktopCatalog.removeDesktop(context) { _, _ -> error("interrupted") })
assertTrue(pending.exists())
assertTrue(journal.exists())
assertTrue(DesktopCatalog.desktopPresent(context))
assertNull(DesktopCatalog.removeDesktop(context, listener))
assertFalse(journal.exists())
assertFalse(pending.exists())
assertFalse(download.exists())
assertFalse(resume.exists())
assertFalse(DesktopCatalog.desktopPresent(context))
assertEquals(listOf("emulators"), DesktopCatalog.interrupted(context).map { it.id })
assertTrue(unrelated.exists())
}
@Test fun refusesUnknownDesktopVersionsAndMissingRuntimeOwnershipBeforeDeletingAnything() {
val desktop = desktopFiles()
marker.writeText("future-desktop")
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertEquals("future-desktop", marker.readText())
marker.writeText(BuildConfig.DESKTOP_KDE_TAG)
journal.writeText(DesktopCatalog.entryJson(DesktopCatalog.desktopEntry(context)).put("version", "future-desktop").toString())
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertTrue(journal.exists())
journal.delete()
File(root, "var/lib/pacman/local/base-1/files").delete()
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertEquals(BuildConfig.DESKTOP_KDE_TAG, marker.readText())
assertFalse(pending.exists())
assertTrue(Files.isSymbolicLink(desktop.toPath()))
}
@Test fun failedDownloadCleanupKeepsTheInstallRecordSoRemovalCanRetry() {
val entry = DesktopCatalog.desktopEntry(context)
val download = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download")
for (blocked in listOf(download, File(download.path + ".resume.properties"))) {
desktopFiles()
journal.writeText(DesktopCatalog.entryJson(entry).toString())
blocked.mkdirs()
val blocker = File(blocked, "blocker").apply { writeText("fixture") }
assertNotNull(DesktopCatalog.removeDesktop(context, listener))
assertTrue(journal.exists())
assertTrue(pending.exists())
assertTrue(blocker.delete())
assertNull(DesktopCatalog.removeDesktop(context, listener))
assertFalse(blocked.exists())
assertFalse(journal.exists())
assertFalse(pending.exists())
}
}
private fun file(path: String, text: String) = File(root, path).apply { parentFile!!.mkdirs(); writeText(text) }
private fun desktopFiles(): File {
file("var/lib/pacman/local/base-1/files", "%FILES%\nusr/lib/shared.so\n")
val entry = GZIPInputStream(context.assets.open("desktop-removal/kde-remove.tsv.gzip")).bufferedReader().use { reader ->
reader.lineSequence().map(DesktopFileRemoval.Entry::parse).first { it.kind == "L" && it.path.startsWith("usr/") }
}
return File(root, entry.path).apply {
parentFile!!.mkdirs()
Files.createSymbolicLink(toPath(), Paths.get(entry.identity))
}
}
}
@@ -0,0 +1,38 @@
package com.droiddeck.launcher.runtime
import android.content.ContextWrapper
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class LinuxRuntimeProcFilesTest {
private val root = Files.createTempDirectory("guest-proc-files").toFile()
private val context = object : ContextWrapper(RuntimeEnvironment.getApplication()) {
override fun getFilesDir() = File(root, "files").apply { mkdirs() }
override fun getCacheDir() = File(root, "cache").apply { mkdirs() }
override fun getNoBackupFilesDir() = File(root, "no_backup").apply { mkdirs() }
}
private val fakeProc get() = File(LinuxRuntime.rootDir(context), "etc/droiddeck/proc")
@After fun tearDown() {
root.deleteRecursively()
}
@Test fun theGuestGetsAnOvercommitPolicyItCanRead() {
LinuxRuntime.binds(context, null, null, null, null)
assertEquals("0\n", File(fakeProc, "overcommit_memory").readText())
assertEquals("9223372036854775807\n", File(fakeProc, "file-max").readText())
}
@Test fun aSeededFileIsKept() {
File(fakeProc, "overcommit_memory").apply { parentFile!!.mkdirs(); writeText("1\n") }
LinuxRuntime.binds(context, null, null, null, null)
assertEquals("1\n", File(fakeProc, "overcommit_memory").readText())
}
}
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.runtime
import java.io.ByteArrayOutputStream
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorOutputStream
import org.junit.After
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
@RunWith(RobolectricTestRunner::class)
class PackageExtractTest {
private val dir = Files.createTempDirectory("package-extract").toFile()
private val root = File(dir, "linuxfs").apply { mkdirs() }
private val context = RuntimeEnvironment.getApplication()
@After fun tearDown() { dir.deleteRecursively() }
private sealed class Item(val name: String) {
class Link(name: String, val target: String) : Item(name)
class Data(name: String, val text: String) : Item(name)
}
private fun archive(vararg items: Item): File {
val tar = ByteArrayOutputStream()
TarArchiveOutputStream(tar).use { out ->
for (item in items) {
when (item) {
is Item.Link -> out.putArchiveEntry(TarArchiveEntry(item.name, TarArchiveEntry.LF_SYMLINK).apply { linkName = item.target })
is Item.Data -> {
val bytes = item.text.toByteArray()
out.putArchiveEntry(TarArchiveEntry(item.name).apply { size = bytes.size.toLong(); mode = 0b111_101_101 })
out.write(bytes)
}
}
out.closeArchiveEntry()
}
}
return File(dir, "pkg-${System.nanoTime()}.tar.zst").apply {
ZstdCompressorOutputStream(outputStream()).use { it.write(tar.toByteArray()) }
}
}
private fun lib(name: String) = File(root, "usr/lib/$name")
private fun installOld() {
lib("").mkdirs()
lib("libvulkan.so.1.4.357").writeText("old")
Files.createSymbolicLink(lib("libvulkan.so.1").toPath(), Paths.get("libvulkan.so.1.4.357"))
}
@Test fun linksListedBeforeTheirTargetsResolveAfterExtraction() {
installOld()
val pkg = archive(
Item.Link("usr/lib/libvulkan.so.1", "libvulkan.so.1.4.363"),
Item.Data("usr/lib/libvulkan.so.1.4.363", "new"),
)
assertTrue(LinuxRuntimeInstaller.extract(context, pkg, root, null))
assertEquals("new", lib("libvulkan.so.1").readText())
assertEquals(emptyList<String>(), RuntimeHealth.brokenLibraryLinks(root))
assertFalse(lib("").list()!!.any { it.startsWith(".dd-part-") })
}
@Test fun anExtractionStoppedBetweenALinkAndItsTargetLeavesTheOldLinkWorking() {
installOld()
val pkg = archive(
Item.Link("usr/lib/libvulkan.so.1", "libvulkan.so.1.4.363"),
Item.Data("usr/lib/libharfbuzz.so.0", "harfbuzz"),
Item.Data("usr/lib/libharfbuzz.so.0/cannot-be-written", "stops here"),
Item.Data("usr/lib/libvulkan.so.1.4.363", "new"),
)
assertFalse(LinuxRuntimeInstaller.extract(context, pkg, root, null))
assertEquals("old", lib("libvulkan.so.1").readText())
assertFalse(lib("libvulkan.so.1.4.363").exists())
assertEquals(emptyList<String>(), RuntimeHealth.brokenLibraryLinks(root))
}
@Test fun aFileReplacesAnExistingLinkInsteadOfWritingThroughIt() {
installOld()
val pkg = archive(Item.Data("usr/lib/libvulkan.so.1", "now a file"))
assertTrue(LinuxRuntimeInstaller.extract(context, pkg, root, null))
assertFalse(Files.isSymbolicLink(lib("libvulkan.so.1").toPath()))
assertEquals("now a file", lib("libvulkan.so.1").readText())
assertEquals("old", lib("libvulkan.so.1.4.357").readText())
assertTrue(lib("libvulkan.so.1").canExecute())
}
@Test fun theLastEntryForAPathWins() {
lib("").mkdirs()
lib("target").writeText("t")
val pkg = archive(
Item.Link("usr/lib/libdup.so", "target"),
Item.Data("usr/lib/libdup.so", "file"),
Item.Data("usr/lib/libother.so", "file"),
Item.Link("usr/lib/libother.so", "target"),
)
assertTrue(LinuxRuntimeInstaller.extract(context, pkg, root, null))
assertFalse(Files.isSymbolicLink(lib("libdup.so").toPath()))
assertEquals("file", lib("libdup.so").readText())
assertTrue(Files.isSymbolicLink(lib("libother.so").toPath()))
}
}
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.runtime
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class RuntimeHealthTest {
@get:Rule val temporary = TemporaryFolder()
private fun link(root: File, name: String, target: String) =
Files.createSymbolicLink(File(root, "usr/lib/$name").toPath(), Paths.get(target))
@Test fun reportsOnlyLibraryLinksWhoseTargetIsMissingInsideTheRuntime() {
val root = temporary.root
val lib = File(root, "usr/lib").apply { mkdirs() }
File(lib, "libvulkan.so.1.4.357").writeText("lib")
File(root, "etc").mkdirs()
File(root, "etc/ld.conf").writeText("conf")
link(root, "libvulkan.so.1", "libvulkan.so.1.4.357")
link(root, "libvulkan.so", "libvulkan.so.1")
link(root, "libabsolute.so", "/etc/ld.conf")
link(root, "libharfbuzz.so.0", "libharfbuzz.so.0.61460.0")
link(root, "libchain.so", "libharfbuzz.so.0")
link(root, "libhost.so", File(lib, "libvulkan.so.1.4.357").absolutePath)
assertEquals(listOf("libchain.so", "libharfbuzz.so.0", "libhost.so"), RuntimeHealth.brokenLibraryLinks(root))
}
@Test fun aMissingLibraryFolderIsNotReportedAsDamage() {
assertEquals(emptyList<String>(), RuntimeHealth.brokenLibraryLinks(temporary.root))
}
}
@@ -0,0 +1,310 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.junit.Assert.*
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(sdk = [33])
class BootMovieLibraryTest {
private val app get() = RuntimeEnvironment.getApplication()
private val movies get() = BootMovieLibrary.moviesDir(app)
@Before fun clear() {
app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
File(app.filesDir, "boot-movie").deleteRecursively()
movies.deleteRecursively()
BootMovieLibrary.libraryDir(app).deleteRecursively()
File(BootMovieLibrary.steamRoot(app), "steamui").deleteRecursively()
File(BootMovieLibrary.steamRoot(app), "appcache").deleteRecursively()
BootMovieLibrary.forgetScan()
BootMovieLibrary.steamConfig(app).delete()
}
private fun movie(name: String) = File(movies, name).also { it.parentFile!!.mkdirs(); it.writeText("movie") }
/** A movie DroidDeck itself imported: kept in the library, copied into Steam's folder and noted in the list. */
private fun imported(title: String, source: String = BootMovieLibrary.SOURCE_IMPORT, repo: String? = null): String {
val staged = File(BootMovieLibrary.libraryDir(app), ".t-${System.nanoTime()}-${Thread.currentThread().id}.staged").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
return BootMovieLibrary.commit(app, staged, title, source, repo)!!
}
private fun steamPicksAt(path: String) {
BootMovieLibrary.steamConfig(app).also { it.parentFile!!.mkdirs() }.writeText(
"\"InstallConfigStore\"\n{\n\t\"StartupMovie\"\n\t{\n\t\t\"MovieID\"\t\t\"x\"\n\t\t\"LocalPath\"\t\t\"$path\"\n\t}\n}\n",
)
}
private fun steamPicks(name: String) = steamPicksAt("/uioverrides/movies/$name")
@Test fun theActiveX64ClientsOwnMoviesAreListedAndRemovedToo() {
SessionPrefs.setSteamClientArch(app, "x86_64")
val x64 = File(SessionPrefs.steamRoot(app, "x86_64"), "config/uioverrides/movies")
try {
File(x64, "Mine.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
movie("Main.webm")
val entries = BootMovieLibrary.list(app).filter { it.id.startsWith(BootMovieLibrary.PREFIX) }
assertEquals(listOf("file:Main.webm", "file:Mine.webm"), entries.map { it.id })
assertTrue(entries.all { it.removable })
assertEquals("Mine.webm", BootMovieLibrary.file(app, "file:Mine.webm")?.name)
assertEquals("Mine (2).webm", BootMovieLibrary.freeName(app, "Mine"))
assertTrue(BootMovieLibrary.remove(app, "file:Mine.webm"))
assertFalse(File(x64, "Mine.webm").exists())
} finally {
x64.deleteRecursively()
}
}
@Test fun removingAMovieKeepsTheSameNamedOneInTheOtherSteamFolder() {
SessionPrefs.setSteamClientArch(app, "x86_64")
val x64 = File(SessionPrefs.steamRoot(app, "x86_64"), "config/uioverrides/movies")
try {
File(x64, "Intro.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
movie("Intro.webm")
assertTrue(BootMovieLibrary.remove(app, "file:Intro.webm"))
assertFalse(File(movies, "Intro.webm").exists())
assertTrue(File(x64, "Intro.webm").isFile)
assertTrue(BootMovieLibrary.list(app).any { it.id == "file:Intro.webm" })
assertTrue(BootMovieLibrary.remove(app, "file:Intro.webm"))
assertFalse(File(x64, "Intro.webm").exists())
} finally {
x64.deleteRecursively()
}
}
@Test fun aSavedChoiceKeepsMeaningTheSameFileWhicheverClientRuns() {
val x64 = File(SessionPrefs.steamRoot(app, "x86_64"), "config/uioverrides/movies")
try {
File(x64, "Intro.webm").also { it.parentFile!!.mkdirs(); it.writeText("other") }
val main = movie("Intro.webm")
SessionPrefs.setSteamClientArch(app, "x86_64")
assertEquals(main.path, BootMovieLibrary.file(app, "file:Intro.webm")?.path)
SessionPrefs.setSteamClientArch(app, "arm64")
assertEquals(main.path, BootMovieLibrary.file(app, "file:Intro.webm")?.path)
} finally {
x64.deleteRecursively()
}
}
@Test fun listsTheDroidDeckMoviesAndEveryWebmButNotTheStagedCopies() {
movie("Intro.webm")
movie("bigpicture_startup.webm")
movie("steam_os_startup.webm")
movie("notes.txt")
movie(".hidden.webm")
val ids = BootMovieLibrary.list(app).map { it.id }
assertEquals(listOf(BootMovie.DROIDDECK_30, BootMovie.DROIDDECK_60, "file:Intro.webm"), ids)
}
@Test fun usesTheTitleItWasRegisteredWithAndFallsBackToTheFileName() {
imported("Fancy", BootMovieLibrary.SOURCE_REPO, "id1"); movie("b.webm")
val list = BootMovieLibrary.list(app).associateBy { it.id }
assertEquals("Fancy", list["file:Fancy.webm"]!!.title)
assertEquals(BootMovieLibrary.SOURCE_REPO, list["file:Fancy.webm"]!!.source)
assertTrue(list["file:Fancy.webm"]!!.removable)
assertTrue(list["file:b.webm"]!!.removable)
assertEquals("b", list["file:b.webm"]!!.title)
assertEquals(BootMovieLibrary.SOURCE_IMPORT, list["file:b.webm"]!!.source)
assertEquals(setOf("id1"), BootMovieLibrary.installedRepoIds(app))
assertEquals("Fancy.webm", BootMovieLibrary.nameForRepo(app, "id1"))
}
@Test fun aChosenFileMovieIsKeptAndFallsBackOnceItIsGone() {
val name = imported("Mine")
BootMovie.select(app, "file:$name")
assertEquals("file:$name", BootMovie.choice(app))
assertTrue(BootMovieLibrary.remove(app, "file:$name"))
assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app))
assertFalse(File(movies, name).exists())
assertFalse(File(BootMovieLibrary.libraryDir(app), name).exists())
}
@Test fun aMovieInSteamsCustomFolderCanBeRemovedEvenWithoutANote() {
movie("by-hand.webm")
assertTrue(BootMovieLibrary.list(app).first { it.id == "file:by-hand.webm" }.removable)
assertTrue(BootMovieLibrary.remove(app, "file:by-hand.webm"))
assertFalse(File(movies, "by-hand.webm").exists())
}
@Test fun steamsOwnMoviesAreNeverDeleted() {
val own = File(BootMovieLibrary.steamRoot(app), "steamui/movies/deck_startup.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
val entry = BootMovieLibrary.list(app).first { it.id == "steam:/movies/deck_startup.webm" }
assertFalse(entry.removable)
assertFalse(BootMovieLibrary.remove(app, entry.id))
assertTrue(own.exists())
}
@Test fun anImportSurvivesTheRuntimeBeingReset() {
val name = imported("Keep")
movies.deleteRecursively()
assertTrue(BootMovieLibrary.list(app).any { it.id == "file:$name" })
assertTrue(File(movies, name).isFile)
}
@Test fun importsAtTheSameTimeAllLandInTheList() {
val names = java.util.Collections.synchronizedList(ArrayList<String>())
(1..8).map { n -> Thread { names.add(imported("Movie")) } }.onEach { it.start() }.forEach { it.join() }
assertEquals(8, names.toSet().size)
assertEquals(8, BootMovieLibrary.list(app).count { it.source == BootMovieLibrary.SOURCE_IMPORT })
}
@Test fun steamIsPointedBackAtItsDefaultWhenTheStagedMovieIsGone() {
steamPicksAt(SessionFiles.BOOT_MOVIE_PATH)
assertTrue(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), false))
assertNull(SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app)))
}
@Test fun aMissingConfigNeedsNoReset() {
assertTrue(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), true))
}
@Test fun aStagedMovieThatIsThereIsLeftAlone() {
movie("bigpicture_startup.webm")
steamPicksAt(SessionFiles.BOOT_MOVIE_PATH)
assertFalse(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), false))
assertEquals(SessionFiles.BOOT_MOVIE_PATH, SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app)))
}
@Test fun aPendingPickResetsASteamMovieThatWasRemoved() {
steamPicksAt("/uioverrides/movies/gone.webm")
assertFalse(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), false))
assertTrue(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), true))
assertNull(SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app)))
}
@Test fun onlyTheThreeStartupMoviesOfSteamAreListed() {
listOf("deck_startup", "oled_startup", "startup_machine", "controller_generic_thumbstick_move").forEach {
File(BootMovieLibrary.steamRoot(app), "steamui/movies/$it.webm").also { f -> f.parentFile!!.mkdirs(); f.writeText("movie") }
}
val ids = BootMovieLibrary.list(app).map { it.id }.filter { it.startsWith("steam:") }
assertEquals(
listOf("steam:/movies/deck_startup.webm", "steam:/movies/oled_startup.webm", "steam:/movies/startup_machine.webm"),
ids.sorted(),
)
}
@Test fun aMovieBoughtInThePointsShopIsListedAndAdopted() {
val file = File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/Bought.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
val entry = BootMovieLibrary.list(app).first { it.id == "steam:/appcache/startupmovies/Bought.webm" }
assertFalse(entry.removable)
assertEquals(BootMovieLibrary.SOURCE_POINTSHOP, entry.source)
steamPicksAt("/appcache/startupmovies/Bought.webm")
assertTrue(BootMovie.syncFromSteam(app))
assertEquals("steam:/appcache/startupmovies/Bought.webm", BootMovie.choice(app))
assertEquals(file, BootMovie.currentFile(app))
assertNull(BootMovieLibrary.file(app, "steam:/../x.webm"))
}
@Test fun aBoughtMovieNamedByIdAndHashIsShownByItsId() {
File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/39900045022_590371b7f10882d09ac59e5d3691b462c0091a6d.webm")
.also { it.parentFile!!.mkdirs(); it.writeText("movie") }
val entry = BootMovieLibrary.list(app).first { it.source == BootMovieLibrary.SOURCE_POINTSHOP }
assertEquals("#39900045022", entry.title)
}
@Test fun theReportNamesWhatStageDidAndWhereMoviesAre() {
File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/1_ab.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
BootMovieReport.note(app, "stage test")
val report = BootMovieReport.build(app)
assertTrue(report.contains("== DroidDeck state"))
assertTrue(report.contains("startupmovies/1_ab.webm"))
assertTrue(report.contains("stage test"))
}
@Test fun pathTricksAreNotMovies() {
movie("a.webm")
assertNull(BootMovieLibrary.file(app, "file:../a.webm"))
assertNull(BootMovieLibrary.file(app, "file:bigpicture_startup.webm"))
assertFalse(BootMovieLibrary.remove(app, "file:../a.webm"))
}
@Test fun freeNameNeverReusesAFileOrAStagedName() {
movie("Intro.webm")
assertEquals("Intro (2).webm", BootMovieLibrary.freeName(app, "Intro"))
assertEquals("movie.webm", BootMovieLibrary.freeName(app, "///"))
}
@Test fun aMovieChosenInsideSteamIsAdoptedOnce() {
movie("a.webm"); movie("b.webm")
BootMovie.select(app, "file:a.webm")
steamPicks("b.webm")
assertTrue(BootMovie.syncFromSteam(app))
assertEquals("file:b.webm", BootMovie.choice(app))
// Picking another one here is not undone by the same Steam setting.
BootMovie.select(app, "file:a.webm")
assertFalse(BootMovie.syncFromSteam(app))
assertEquals("file:a.webm", BootMovie.choice(app))
// A new pick inside Steam is adopted again.
movie("c.webm")
steamPicks("c.webm")
assertTrue(BootMovie.syncFromSteam(app))
assertEquals("file:c.webm", BootMovie.choice(app))
}
@Test fun aSteamPickIsTakenOverWithoutBeingStagedOverSteamsOwnSetting() {
movie("a.webm")
BootMovie.select(app, "file:a.webm")
SessionPrefs.setBootMovieApplyNext(app, false)
steamPicks("a.webm")
assertFalse(BootMovie.syncFromSteam(app))
assertEquals("file:a.webm", BootMovie.choice(app))
assertFalse(SessionPrefs.bootMovieApplyNext(app))
}
@Test fun theStagedCopyNamedInSteamsConfigIsNotAPick() {
movie("a.webm")
BootMovie.select(app, "file:a.webm")
steamPicksAt(SessionFiles.BOOT_MOVIE_PATH)
assertFalse(BootMovie.syncFromSteam(app))
assertEquals("file:a.webm", BootMovie.choice(app))
}
@Test fun aBoughtMovieIsShownUnderItsPointsShopTitle() {
File(BootMovieLibrary.steamRoot(app), "config/communityitemscache/startupmovies/39900045022_ab12.webm")
.also { it.parentFile!!.mkdirs(); it.writeText("movie") }
File(BootMovieLibrary.steamRoot(app), "userdata/1/config/localconfig.vdf").also { it.parentFile!!.mkdirs() }.writeText(
"\"GetStartupMovies\"\t\t\"[{\\\"communityitemid\\\":\\\"39900045022\\\",\\\"image_small\\\":\\\"x.png\\\",\\\"name\\\":\\\"Turret Factory\\\",\\\"item_title\\\":\\\"Turret Factory\\\"}]\"\n",
)
val entry = BootMovieLibrary.list(app).first { it.source == BootMovieLibrary.SOURCE_POINTSHOP }
assertEquals("Turret Factory", entry.title)
}
@Test fun notesKeptInSteamsMoviesFolderByAnEarlierVersionAreTakenOver() {
movie("Old.webm")
File(movies, ".droiddeck-movies.json").writeText("{\"Old.webm\":{\"title\":\"Old one\",\"source\":\"repo\",\"repo\":\"r1\"}}")
val entry = BootMovieLibrary.list(app).first { it.id == "file:Old.webm" }
assertEquals("Old one", entry.title)
assertEquals(BootMovieLibrary.SOURCE_REPO, entry.source)
assertEquals(setOf("r1"), BootMovieLibrary.installedRepoIds(app))
assertFalse(File(movies, ".droiddeck-movies.json").exists())
}
@Test fun aPickMadeHereBeatsAnOlderSteamPickThatWasNeverSeen() {
movie("a.webm"); movie("b.webm")
steamPicks("b.webm")
BootMovie.select(app, "file:a.webm")
assertFalse(BootMovie.syncFromSteam(app))
assertEquals("file:a.webm", BootMovie.choice(app))
}
@Test fun steamPointingAtAMovieThatIsNotThereChangesNothing() {
steamPicks("gone.webm")
assertFalse(BootMovie.syncFromSteam(app))
assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app))
}
@Test fun volumeAndLengthDefaultToTheWholeMovieAtFullVolume() {
assertEquals(100, SessionPrefs.bootMovieVolume(app))
assertEquals(0, SessionPrefs.bootMovieSeconds(app))
SessionPrefs.setBootMovieVolume(app, 40)
SessionPrefs.setBootMovieSeconds(app, 3)
assertEquals(40, SessionPrefs.bootMovieVolume(app))
assertEquals(3, SessionPrefs.bootMovieSeconds(app))
}
}
@@ -0,0 +1,59 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.session.BootMovie.Step
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class BootMoviePlanTest {
@Test
fun fullVolumeWithoutLimitPassesTheSourceThrough() {
val plan = BootMovie.plan(100, 0)
assertTrue(plan.passthrough)
assertTrue(plan.steps.isEmpty())
}
@Test
fun fullVolumeWithLimitKeepsSoundAndFallsBackToTheSource() {
val plan = BootMovie.plan(100, 5)
assertFalse(plan.passthrough)
assertEquals(listOf(Step.REMUX_AUDIO, Step.TRANSCODE_AUDIO), plan.steps)
assertTrue(plan.sourceOnFailure)
}
@Test
fun silentGoesWithoutSoundAndNeverFallsBackToTheSource() {
val plan = BootMovie.plan(0, 0)
assertEquals(listOf(Step.REMUX_SILENT, Step.TRANSCODE_SILENT), plan.steps)
assertFalse(plan.sourceOnFailure)
}
@Test
fun partialVolumeDegradesToSilenceNotToFullVolume() {
val plan = BootMovie.plan(40, 0)
assertEquals(listOf(Step.REGAIN, Step.REMUX_SILENT, Step.TRANSCODE_AUDIO), plan.steps)
assertFalse(plan.passthrough)
assertFalse(plan.sourceOnFailure)
}
@Test
fun framesBeyondFullHdAreOversizedInEitherOrientation() {
assertTrue(BootMovie.oversized(3840, 2160))
assertTrue(BootMovie.oversized(2160, 3840))
assertFalse(BootMovie.oversized(1920, 1080))
assertFalse(BootMovie.oversized(1280, 800))
assertFalse(BootMovie.oversized(1080, 1920))
}
@Test
fun anOversizedMovieIsAlwaysConvertedAndNeverFallsBackToTheSource() {
for (volume in listOf(0, 40, 100)) {
val plan = BootMovie.oversizedPlan(volume)
assertFalse(plan.passthrough)
assertFalse(plan.sourceOnFailure)
}
assertEquals(listOf(Step.TRANSCODE_SILENT), BootMovie.oversizedPlan(0).steps)
assertEquals(listOf(Step.TRANSCODE_AUDIO), BootMovie.oversizedPlan(60).steps)
}
}
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
class BootMovieTranscoderTest {
@Test fun scaleQuietsAndCutsTheSoundAtTheSameTime() {
val pcm = ShortArray(48_000 * 2) { 1000 }
assertSame(pcm, BootMovieTranscoder.scale(pcm, 2, 1f, Long.MAX_VALUE))
val quieter = BootMovieTranscoder.scale(pcm, 2, 0.5f, Long.MAX_VALUE)
assertEquals(pcm.size, quieter.size)
assertEquals(500.toShort(), quieter[0])
val cut = BootMovieTranscoder.scale(pcm, 2, 1f, 500_000L)
assertEquals(24_000 * 2, cut.size)
}
}
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.session
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 ComponentsNightlyCatalogTest {
@Test
fun nightlyFilesGoToTheirComponentList() {
val n = ComponentsManager.DD_NIGHTLY
assertEquals("dxvk", ComponentsManager.assetComp(n, "DD-dxvk-3.1.1+153-nightly.wcp"))
assertEquals("dxvk", ComponentsManager.assetComp(n, "DD-dxvk-arm64ec-3.1.1+153-nightly.wcp"))
assertEquals("dxvk", ComponentsManager.assetComp(n, "DD-dxvk-gplasync-3.1.1+153-nightly.wcp"))
assertEquals("vkd3d", ComponentsManager.assetComp(n, "DD-vkd3d-proton-arm64ec-3.0.1+455-nightly.wcp"))
assertEquals("fex", ComponentsManager.assetComp(n, "DD-FEXCore-2610+58-nightly.wcp"))
assertNull(ComponentsManager.assetComp(n, "state.json"))
assertNull(ComponentsManager.assetComp(n, "something-else.wcp"))
assertEquals("dxvk", ComponentsManager.assetComp("Dxvk-gplasync-Linux", "dxvk-gplasync-3.1.1-1-linux.wcp"))
assertNull(ComponentsManager.assetComp("Unknown-Release", "dxvk-3.1.1-linux.wcp"))
}
@Test
fun nightliesListBelowTheStablePackages() {
fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "dxvk", release, "", 0, "")
val sorted = listOf(
item("DD-dxvk-3.1.1+153-nightly.wcp", ComponentsManager.DD_NIGHTLY),
item("dxvk-2.7.1-linux.wcp", "Dxvk-Linux"),
item("dxvk-3.1.1-linux.wcp", "Dxvk-Linux"),
).sortedWith(ComponentsManager.CATALOG_ORDER).map { it.file }
assertEquals(listOf("dxvk-3.1.1-linux.wcp", "dxvk-2.7.1-linux.wcp", "DD-dxvk-3.1.1+153-nightly.wcp"), sorted)
}
@Test
fun nightliesPairWithTheStableOfTheSameFlavorAndVersion() {
val n = ComponentsManager.DD_NIGHTLY
fun item(file: String, comp: String, release: String) = ComponentsManager.CatalogItem(file, comp, release, "", 0, "")
val dxvk = item("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux")
val ec = item("dxvk-arm64ec-3.1.1-linux.wcp", "dxvk", "Dxvk-arm64ec-Linux")
val gpl = item("dxvk-gplasync-3.1.1-1-linux.wcp", "dxvk", "Dxvk-gplasync-Linux")
val fex = item("FEXCore-2610-linux.wcp", "fex", "FexCore-Linux")
val vk = item("vkd3d-proton-3.0.1-linux.wcp", "vkd3d", "Vkd3d-proton-Linux")
val others = listOf(
item("dxvk-low-latency-3.1.1-2-linux.wcp", "dxvk", "Dxvk-Linux"),
item("dxvk-3.1-linux.wcp", "dxvk", "Dxvk-Linux"),
item("dxvk-gplasync-3.1-1-linux.wcp", "dxvk", "Dxvk-gplasync-Linux"),
item("FEXCore-2610-d2rfix28-linux.wcp", "fex", "FexCore-Linux"),
)
val nDxvk = item("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", n)
val nEc = item("DD-dxvk-arm64ec-3.1.1+153-nightly.wcp", "dxvk", n)
val nGpl = item("DD-dxvk-gplasync-3.1.1+153-nightly.wcp", "dxvk", n)
val nFex = item("DD-FEXCore-2610+58-nightly.wcp", "fex", n)
val nVk = item("DD-vkd3d-proton-3.0.1+455-nightly.wcp", "vkd3d", n)
val nVkEc = item("DD-vkd3d-proton-arm64ec-3.0.1+455-nightly.wcp", "vkd3d", n)
val pairs = ComponentsManager.nightlyPairs(listOf(dxvk, ec, gpl, fex, vk) + others + listOf(nDxvk, nEc, nGpl, nFex, nVk, nVkEc))
assertEquals(mapOf(dxvk to nDxvk, ec to nEc, gpl to nGpl, fex to nFex, vk to nVk), pairs)
// Two nightlies for one stable build: the newer one wins.
val nDxvkNewer = item("DD-dxvk-3.1.1+154-nightly.wcp", "dxvk", n)
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvkNewer, nDxvk)))
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvk, nDxvkNewer)))
// A nightly of a version with no stable build pairs with nothing.
assertEquals(emptyMap<Any, Any>(), ComponentsManager.nightlyPairs(listOf(item("dxvk-3.1-linux.wcp", "dxvk", "Dxvk-Linux"), nDxvk)))
}
@Test
fun downloadsOnlyFromTheTwoRepositories() {
assertTrue(ComponentsManager.allowedDownload("https://github.com/The412Banner/Nightlies/releases/download/Dxvk-Linux/dxvk-3.1.1-linux.wcp"))
assertTrue(ComponentsManager.allowedDownload("https://github.com/Droid-Deck/DroidDeck-Components/releases/download/linux-nightly/DD-FEXCore-2610+58-nightly.wcp"))
assertFalse(ComponentsManager.allowedDownload("https://github.com/someone/else/releases/download/x/y.wcp"))
assertFalse(ComponentsManager.allowedDownload("https://github.com/Droid-Deck/DroidDeck-Components-evil/releases/download/x/y.wcp"))
}
}
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.input.FakeInputWriter
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 InputSysfsComponentTest {
@Test fun steamInputsVirtualPadKeepsItsIdentity() {
val pad = InputSysfsComponent.virtualPad("PRODUCT=3/28de/11ff/1\nNAME=\"Microsoft X-Box 360 pad 0\"\nPHYS=\"\"\n")!!
assertEquals(listOf(3, 0x28de, 0x11ff, 1), listOf(pad.bus, pad.vendor, pad.product, pad.version))
assertEquals("Microsoft X-Box 360 pad 0", pad.name)
assertEquals("", pad.phys)
assertTrue(pad.uevent().startsWith("PRODUCT=3/28de/11ff/1\nNAME=\"Microsoft X-Box 360 pad 0\"\n"))
}
@Test fun anUnreadableDescriptionIsNotListed() {
assertNull(InputSysfsComponent.virtualPad(""))
assertNull(InputSysfsComponent.virtualPad("PRODUCT=3/28de\nNAME=\"pad\"\n"))
assertNull(InputSysfsComponent.virtualPad("PRODUCT=3/28de/11ff/1\n"))
}
@Test fun ringPadsMatchWhatTheirIoctlsAnswer() {
val xbox = InputSysfsComponent.ringPad(1, steamVirtual = false)
assertEquals("Xbox 360 Controller (1)", xbox.name)
assertEquals(listOf(0x045e, 0x028e, 0x110), listOf(xbox.vendor, xbox.product, xbox.version))
val steam = InputSysfsComponent.ringPad(0, steamVirtual = true)
assertEquals("Microsoft X-Box 360 pad 0", steam.name)
assertEquals(listOf(0x28de, 0x11ff), listOf(steam.vendor, steam.product))
}
@Test fun ringPadsAreHiddenWhereGamesCannotOpenThem() {
assertFalse(InputSysfsComponent.ringWithdrawn(deckPad = false, type = FakeInputWriter.PAD_TYPE_DECK))
assertFalse(InputSysfsComponent.ringWithdrawn(deckPad = true, type = FakeInputWriter.PAD_TYPE_XBOX))
assertTrue(InputSysfsComponent.ringWithdrawn(deckPad = true, type = FakeInputWriter.PAD_TYPE_DECK))
assertTrue(InputSysfsComponent.ringWithdrawn(deckPad = true, type = -1))
}
@Test fun onlyThePadsOwnUdevRecordsAreCleared() {
assertTrue(InputSysfsComponent.isPadRecord("c13:64"))
assertTrue(InputSysfsComponent.isPadRecord("c13:80"))
assertTrue(InputSysfsComponent.isPadRecord("+input:input16"))
assertFalse(InputSysfsComponent.isPadRecord("c13:63"))
assertFalse(InputSysfsComponent.isPadRecord("c13:128"))
assertFalse(InputSysfsComponent.isPadRecord("c240:16"))
assertFalse(InputSysfsComponent.isPadRecord("+input:input64"))
}
@Test fun theUdevRecordMarksAnInitializedJoystick() {
val record = InputSysfsComponent.udevRecord(42).lines()
assertEquals("I:42", record.first())
assertTrue("E:ID_INPUT_JOYSTICK=1" in record)
assertTrue("E:ID_INPUT=1" in record)
}
}
@@ -20,7 +20,7 @@ class OrientationTest {
}
@Test fun landscapeChoicesPersistGloballyAndCanRestoreAutomaticRotation() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
for (value in listOf(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
@@ -34,7 +34,7 @@ class OrientationTest {
@Test fun invalidStoredOrientationFallsBackAndInvalidChoicePreservesTheSavedValue() {
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertThrows(IllegalArgumentException::class.java) {
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
@@ -32,6 +32,35 @@ class SessionLogShareTest {
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
}
@Test fun aLogPastTheInMemoryCapIsStillScrubbedIntoTheZip() {
val folder = tmp.newFolder("2026-10-18-01-steam")
val line = ("x".repeat(1023) + "\n").toByteArray()
File(folder, "session.log").outputStream().buffered().use { out ->
out.write("$secret\n".toByteArray())
repeat(65 * 1024) { out.write(line) }
}
assertTrue(File(folder, "session.log").length() >= LogRedactor.IN_MEMORY_SCRUB_MAX)
val out = zip(folder)
assertTrue(out.containsKey("session.log"))
assertFalse(out.getValue("session.log").contains(leaked))
}
@Test fun aLogWithANulByteIsScrubbedNotCopiedRaw() {
val folder = tmp.newFolder("2026-10-18-02-steam")
File(folder, "crash.log").writeBytes(byteArrayOf(0) + "$secret\n".toByteArray())
val out = zip(folder)
assertTrue(out.containsKey("crash.log"))
assertFalse(out.getValue("crash.log").contains(leaked))
}
@Test fun utf16SecretsDoNotEscapeInTheSharedZip() {
val folder = tmp.newFolder("2026-10-18-03-steam")
File(folder, "crash.log").writeBytes("sessionid=$leaked".toByteArray(Charsets.UTF_16LE))
val output = zip(folder).getValue("crash.log")
assertFalse(output.replace("\u0000", "").contains(leaked))
assertTrue(output.contains("withheld"))
}
@Test fun aRecordedUnchangedFileIsScrubbedAgainOnTheWayIntoTheZip() {
val folder = tmp.newFolder("2026-10-06-01-steam")
File(folder, "session.log").writeText("$secret\n")
@@ -40,6 +40,19 @@ class SessionScalingPrefsTest {
assertEquals("800x600", SessionPrefs.resolutionChoice(context, "lxqt", 1440 to 1080))
}
@Test fun userAppsTakeTheDesktopResolutionOnceItIsChosen() {
val context = RuntimeEnvironment.getApplication()
val script = com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER
assertEquals("steam", SessionPrefs.displayMode(context, "run", script))
SessionPrefs.setResolutionChoice(context, "lxqt", SessionDisplay.MATCH_SCREEN)
assertEquals("lxqt", SessionPrefs.displayMode(context, "run", script))
assertEquals("lxqt", SessionPrefs.displayMode(context, "run", com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER))
val choice = SessionPrefs.resolutionChoice(context, SessionPrefs.displayMode(context, "run", script), 1240 to 1080)
assertEquals(1240 to 1080, SessionDisplay.resolveChoice(1240 to 1080, choice))
assertEquals("steam", SessionPrefs.displayMode(context, "run", "/usr/bin/retroarch"))
assertEquals("steam", SessionPrefs.displayMode(context, "steam", script))
}
@Test fun freshSettingsUseTheConcreteDefaultAndCustomSizesAreNormalized() {
val context = RuntimeEnvironment.getApplication()
assertEquals(SessionDisplay.DEFAULT_RESOLUTION, SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080))
@@ -0,0 +1,379 @@
package com.droiddeck.launcher.session
import java.io.File
import java.util.concurrent.AbstractExecutorService
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.TimeUnit
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class SessionSuspendControllerTest {
@get:Rule val temporary = TemporaryFolder()
@Test fun everyWorkerThreadIsStoppedAfterTheRoot() {
for (count in listOf(17, 68)) {
val fixture = fixture(count)
fixture.controller.freeze { assertTrue(it) }
assertTrue(fixture.game.threads.all { it.state == 't' })
assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= count)
assertEquals(ROOT, fixture.signals.first { it.signal == STOP }.pid)
assertTrue(fixture.now < 1000)
assertEquals(1, fixture.audioSuspends)
}
}
@Test fun cpuMustBeStableAcrossTwoCompleteSnapshots() {
val fixture = fixture(17)
var changes = 0
fixture.afterSleep = {
if (fixture.game.threads.all { it.state == 't' } && changes < 3) {
fixture.game.threads.last().cpu++
changes++
}
}
fixture.controller.freeze { assertTrue(it) }
assertEquals(3, changes)
assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 17)
}
@Test fun reusedTidAndNewThreadMustJoinTheStableInventory() {
val fixture = fixture(17)
var changed = false
fixture.afterSleep = {
if (!changed && fixture.game.threads.all { it.state == 't' }) {
changed = true
fixture.game.threads.last().apply { started++; state = 'S'; cpu = 0 }
fixture.game.threads += Task(500, 9000, 'S')
}
}
fixture.controller.freeze { assertTrue(it) }
assertTrue(changed)
assertTrue(fixture.game.threads.all { it.state == 't' })
assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 19)
}
@Test fun zombieLeaderDoesNotHideRunningWorkers() {
val fixture = fixture(17)
fixture.game.threads.first().state = 'Z'
fixture.sync()
fixture.controller.freeze { assertTrue(it) }
assertEquals('Z', fixture.game.threads.first().state)
assertTrue(fixture.game.threads.drop(1).all { it.state == 't' })
assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 16)
}
@Test fun lateReparentedTraceeIsDiscoveredAndResumed() {
val fixture = fixture(17)
val late = Group(600, 1, ROOT, mutableListOf(Task(600, 6000, 'S')))
fixture.afterSleep = {
if (fixture.root.threads.first().state == 'T' && late !in fixture.groups) fixture.groups += late
}
fixture.controller.freeze { assertTrue(it) }
assertEquals('t', late.threads.first().state)
fixture.controller.resume { assertTrue(it) }
assertEquals('S', late.threads.first().state)
}
@Test fun descendantHelperKeepsRootStopAndResumeOrdering() {
val fixture = fixture(17)
val helper = Group(700, ROOT, 0, mutableListOf(Task(700, 7000, 'S')))
fixture.groups += helper
fixture.helpers += helper.pid
fixture.sync()
fixture.controller.freeze { assertTrue(it) }
val stops = fixture.signals.filter { it.signal == STOP }
assertTrue(stops.indexOfFirst { it.pid == ROOT } < stops.indexOfFirst { it.pid == helper.pid })
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(ROOT, helper.pid, GAME), fixture.signals.drop(before).take(3).map { it.pid })
}
@Test fun retainedHelperDoesNotAdoptAReusedPidOnRefreeze() {
val fixture = fixture(17)
val helper = Group(700, 9000, 0, mutableListOf(Task(700, 7000, 'S')))
fixture.groups += helper
fixture.helpers += helper.pid
fixture.sync()
fixture.controller.freeze { assertTrue(it) }
fixture.blockGameContinue = true
fixture.controller.resume { assertFalse(it) }
helper.threads.first().apply { started++; state = 'S' }
fixture.sync()
val before = fixture.signals.size
fixture.controller.freeze { assertTrue(it) }
assertFalse(fixture.signals.drop(before).any { it.pid == helper.pid })
}
@Test fun timeoutRollsBackAllKnownProcessesAndAudio() {
val fixture = fixture(17)
fixture.neverStop = true
fixture.controller.freeze { assertFalse(it) }
assertTrue(fixture.now <= 8100)
assertEquals(ROOT, fixture.signals.first { it.signal == CONT }.pid)
assertTrue(fixture.game.threads.all { it.state == 'S' })
assertEquals(1, fixture.audioResumes)
}
@Test fun missingKnownStatCannotBeMistakenForAnExitedProcess() {
val fixture = fixture(17)
fixture.afterSleep = {
if (fixture.root.threads.first().state == 'T') fixture.missingGameStat = true
}
fixture.controller.freeze { assertFalse(it) }
assertEquals(1, fixture.audioResumes)
fixture.missingGameStat = false
fixture.sync()
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
@Test fun unavailableOrEmptyThreadInventoryCannotReportSuccess() {
for (empty in listOf(false, true)) {
val fixture = fixture(17)
fixture.emptyGameTasks = empty
fixture.missingGameTasks = !empty
fixture.sync()
fixture.controller.freeze { assertFalse(it) }
assertEquals(1, fixture.audioResumes)
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
}
@Test fun disappearingRootFailsAndStillResumesKnownChildren() {
val fixture = fixture(17)
fixture.afterSleep = {
if (fixture.root.threads.first().state == 'T') fixture.rootGone = true
}
fixture.controller.freeze { assertFalse(it) }
assertTrue(fixture.game.threads.all { it.state == 'S' })
assertEquals(1, fixture.audioResumes)
}
@Test fun replacementRootIsNeverStoppedOrContinued() {
val fixture = fixture(17)
var atReplacement = -1
fixture.afterSleep = {
if (atReplacement < 0 && fixture.root.threads.first().state == 'T') {
atReplacement = fixture.signals.size
fixture.root.threads.first().apply { started++; state = 'S' }
}
}
fixture.controller.freeze { assertFalse(it) }
assertTrue(atReplacement > 0)
assertFalse(fixture.signals.drop(atReplacement).any { it.pid == ROOT })
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
@Test fun reusedChildPidIsNotContinuedDuringResume() {
val fixture = fixture(17)
fixture.controller.freeze { assertTrue(it) }
fixture.game.threads.first().apply { started++; state = 'S' }
fixture.game.parent = 1
fixture.game.tracer = 0
fixture.sync()
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.signals.drop(before).any { it.pid == GAME })
}
@Test fun closeCancelsFreezeAndRestoresSavedRootAfterServiceClearsIt() {
val executor = QueueExecutor()
val fixture = fixture(68, executor)
var closed = false
var requested = false
fixture.afterSleep = {
if (!requested && fixture.root.threads.first().state == 'T') {
requested = true
fixture.rootPid = -1
fixture.controller.closeAndResume { closed = true }
}
}
fixture.controller.freeze { assertFalse(it) }
executor.drain()
assertTrue(closed)
assertTrue(executor.isShutdown)
assertTrue(fixture.game.threads.all { it.state == 'S' })
assertEquals(1, fixture.audioResumes)
}
@Test fun successfulFreezeIsRecheckedAndAudioIsReassertedAfterFailedResume() {
val fixture = fixture(17)
fixture.controller.freeze { assertTrue(it) }
fixture.blockGameContinue = true
fixture.controller.resume { assertFalse(it) }
assertEquals(1, fixture.audioResumes)
fixture.blockGameContinue = false
fixture.game.threads.last().state = 'S'
fixture.sync()
fixture.controller.freeze { assertTrue(it) }
assertTrue(fixture.game.threads.all { it.state == 't' })
assertEquals(2, fixture.audioSuspends)
}
@Test fun failedRollbackCanBeRefrozenAndAudioIsSuspendedAgain() {
val fixture = fixture(17)
fixture.neverStop = true
fixture.blockGameContinue = true
fixture.controller.freeze { assertFalse(it) }
fixture.neverStop = false
fixture.blockGameContinue = false
fixture.controller.freeze { assertTrue(it) }
assertTrue(fixture.game.threads.all { it.state == 't' })
assertEquals(2, fixture.audioSuspends)
assertEquals(1, fixture.audioResumes)
}
@Test fun repeatedFreezeResumeKeepsOriginalRootFirstOrdering() {
val fixture = fixture(17)
repeat(2) {
fixture.controller.freeze { assertTrue(it) }
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertEquals(ROOT, fixture.signals.drop(before).first().pid)
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
fixture.controller.freeze { assertTrue(it) }
fixture.rootPid = -1
var closed = false
fixture.controller.closeAndResume { closed = true }
assertTrue(closed)
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
@Test fun rejectedExecutorDoesNotFreezeOnTheCallingThread() {
val executor = QueueExecutor().apply { shutdown() }
val fixture = fixture(17, executor)
fixture.controller.freeze { assertFalse(it) }
assertTrue(fixture.signals.isEmpty())
assertEquals(0, fixture.audioSuspends)
}
private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) =
Fixture(temporary.newFolder(), count, executor)
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList<Task>)
private data class SentSignal(val pid: Int, val signal: Int)
private class Fixture(val proc: File, count: Int, executor: QueueExecutor) {
val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S')))
val game = Group(GAME, ROOT, ROOT, MutableList(count) { Task(GAME + it, 2000L + it, 'S') })
val groups = mutableListOf(root, game)
val helpers = mutableListOf<Int>()
val signals = mutableListOf<SentSignal>()
var rootPid = ROOT
var now = 0L
var audioSuspends = 0
var audioResumes = 0
var neverStop = false
var blockGameContinue = false
var missingGameStat = false
var missingGameTasks = false
var emptyGameTasks = false
var rootGone = false
var afterSleep: (() -> Unit)? = null
private var continuing = false
val controller = SessionSuspendController(
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
)
init { sync() }
private fun signal(pid: Int, signal: Int) {
signals += SentSignal(pid, signal)
val group = groups.first { it.pid == pid }
if (signal == STOP) {
continuing = false
if (pid == ROOT) group.threads.forEach { it.state = 'T' }
else group.threads.firstOrNull {
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
}?.state = 't'
} else if (signal == CONT) {
continuing = true
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
}
sync()
}
private fun threadSignal(pid: Int, tid: Int, signal: Int) {
signals += SentSignal(pid, signal)
val task = groups.first { it.pid == pid }.threads.first { it.tid == tid }
if (signal == STOP && task.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && task == game.threads.last())) {
task.state = 't'
}
sync()
}
private fun sleep(millis: Long) {
now += millis
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
}
afterSleep?.invoke()
sync()
}
fun sync() {
for (group in groups) {
val dir = File(proc, group.pid.toString())
if (group == root && rootGone) { dir.deleteRecursively(); continue }
dir.mkdirs()
val stat = File(dir, "stat")
if (group == game && missingGameStat) stat.delete()
else stat.writeText(stat(group, group.threads.first()))
File(dir, "status").writeText("TracerPid: ${group.tracer}\n")
val taskDir = File(dir, "task")
if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue }
taskDir.mkdirs()
if (group == game && emptyGameTasks) { taskDir.listFiles().orEmpty().forEach { it.deleteRecursively() }; continue }
for (task in group.threads) {
val entry = File(taskDir, task.tid.toString()).apply { mkdirs() }
File(entry, "stat").writeText(stat(group, task))
}
}
}
private fun stat(group: Group, task: Task): String {
val fields = MutableList(20) { "0" }
fields[0] = task.state.toString()
fields[1] = group.parent.toString()
fields[11] = task.cpu.toString()
fields[19] = task.started.toString()
return "${task.tid} (fixture (worker)) ${fields.joinToString(" ")}"
}
}
private open class QueueExecutor : AbstractExecutorService() {
private val queue = ArrayDeque<Runnable>()
private var stopped = false
override fun execute(command: Runnable) {
if (stopped) throw RejectedExecutionException()
queue.add(command)
}
fun drain() { while (queue.isNotEmpty()) queue.removeFirst().run() }
override fun shutdown() { stopped = true }
override fun shutdownNow(): MutableList<Runnable> {
stopped = true
return queue.toMutableList().also { queue.clear() }
}
override fun isShutdown() = stopped
override fun isTerminated() = stopped && queue.isEmpty()
override fun awaitTermination(timeout: Long, unit: TimeUnit) = isTerminated
}
private class InlineExecutor : QueueExecutor() {
override fun execute(command: Runnable) { super.execute(command); drain() }
}
private companion object {
const val ROOT = 100
const val GAME = 200
const val STOP = 19
const val CONT = 18
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.session
import android.view.Display
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -20,6 +21,34 @@ class SessionVisibilityTest {
assertFalse(sessionHasVisibleSurface(false, false, false))
}
@Test fun phoneDisplayFollowsTheInteractiveState() {
assertTrue(sessionScreenOn(true, true, null))
assertFalse(sessionScreenOn(true, false, null))
assertFalse(sessionScreenOn(true, false, Display.STATE_ON))
}
@Test fun externalDisplayKeepsTheSessionAwakeWhileThePhoneScreenIsOff() {
assertTrue(sessionScreenOn(false, false, Display.STATE_ON))
assertTrue(sessionScreenOn(false, false, Display.STATE_ON_SUSPEND))
assertTrue(sessionScreenOn(false, false, Display.STATE_VR))
}
@Test fun externalDisplayTurnedOffSuspendsEvenWithThePhoneScreenOn() {
assertFalse(sessionScreenOn(false, true, Display.STATE_OFF))
assertFalse(sessionScreenOn(false, true, Display.STATE_DOZE))
assertFalse(sessionScreenOn(false, true, Display.STATE_DOZE_SUSPEND))
}
@Test fun missingExternalDisplayFallsBackToThePhone() {
assertTrue(sessionScreenOn(false, true, null))
assertFalse(sessionScreenOn(false, false, null))
}
@Test fun unknownExternalDisplayStateFallsBackToThePhone() {
assertTrue(sessionScreenOn(false, true, Display.STATE_UNKNOWN))
assertFalse(sessionScreenOn(false, false, Display.STATE_UNKNOWN))
}
@Test fun losingXrVisibilityReturnsToNormalSuspendRules() {
assertTrue(sessionHasVisibleSurface(false, false, true))
assertFalse(sessionHasVisibleSurface(false, false, false))
@@ -32,9 +32,14 @@ class SettingsResetTest {
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
SessionPrefs.setHudShowFps(app, false)
SessionPrefs.setHudShowBattery(app, false)
SessionPrefs.setHudShowGraph(app, false)
SessionPrefs.setHudColor(app, "amber")
SessionPrefs.setHudOpacity(app, 40)
ControllerPrefs.setOpacity(app, 40)
AppUiPrefs.setScale(app, 150)
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_WINFG, 3))
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3))
prefs("steam_touch").edit().putBoolean("gyro", false).commit()
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
@@ -45,6 +50,13 @@ class SettingsResetTest {
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
assertTrue(SessionPrefs.hudShowFps(app))
assertTrue(SessionPrefs.hudShowBattery(app))
assertTrue(SessionPrefs.hudShowGraph(app))
assertEquals(SessionPrefs.HUD_COLOR_MINT, SessionPrefs.hudColor(app))
assertEquals(SessionPrefs.HUD_OPACITY_DEFAULT, SessionPrefs.hudOpacity(app))
assertEquals("32.4°C", PerfHud.batteryCelsius(324))
assertNull(PerfHud.batteryCelsius(0))
assertEquals(100, ControllerPrefs.read(app).opacity)
assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app))
assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app))
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
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 = [33])
class StartupMovieConfigTest {
@get:Rule val folder = TemporaryFolder()
private val older = "\t\t\t\t\"StartupMovie\"\n\t\t\t\t{\n\t\t\t\t\t\"MovieID\"\t\t\"0\"\n\t\t\t\t\t\"LocalPath\"\t\t\"%s\"\n\t\t\t\t}\n"
private val customization = "\t\"Customization\"\n\t{\n\t\t\"StartupMovie\"\n\t\t{\n\t\t\t\"MovieID\"\t\t\"%s\"\n\t\t\t\"LocalPath\"\t\t\"%s\"\n\t\t}\n\t}\n"
private fun config(olderPath: String?, id: String?, path: String?): File {
val text = StringBuilder("\"InstallConfigStore\"\n{\n\t\"Software\"\n\t{\n\t\t\"Valve\"\n\t\t{\n\t\t\t\"Steam\"\n\t\t\t{\n")
if (olderPath != null) text.append(older.format(olderPath))
text.append("\t\t\t}\n\t\t}\n\t}\n")
if (id != null && path != null) text.append(customization.format(id, path))
text.append("}\n")
return folder.newFile().also { it.writeText(text.toString()) }
}
@Test fun steamReadsTheMovieUnderCustomizationNotTheOlderOne() {
val file = config(SessionFiles.BOOT_MOVIE_PATH, "39900045022", "/communityitemscache/startupmovies/39900045022_ab.webm")
assertEquals("/communityitemscache/startupmovies/39900045022_ab.webm", SessionFiles.startupMoviePath(file))
}
@Test fun aPickIsWrittenWhereSteamReadsItAndTheOlderPlaceIsKeptInStep() {
val file = config("/uioverrides/movies/x.webm", "39900045022", "/communityitemscache/startupmovies/39900045022_ab.webm")
assertTrue(SessionFiles.ensureStartupMovieDefault(file, force = true))
val text = file.readText()
assertEquals(SessionFiles.BOOT_MOVIE_PATH, SessionFiles.startupMoviePath(file))
assertFalse(text.contains("39900045022"))
assertEquals(2, Regex("\"LocalPath\"\\s+\"" + Regex.escape(SessionFiles.BOOT_MOVIE_PATH) + "\"").findAll(text).count())
}
@Test fun aPickMadeInSteamIsLeftAloneWithoutAPendingPick() {
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", "/uioverrides/movies/Undertale.webm")
assertFalse(SessionFiles.ensureStartupMovieDefault(file, force = false))
assertEquals("/uioverrides/movies/Undertale.webm", SessionFiles.startupMoviePath(file))
}
@Test fun aConfigWithoutCustomizationGetsOne() {
val file = config(null, null, null)
assertTrue(SessionFiles.ensureStartupMovieDefault(file, force = false))
val text = file.readText()
assertTrue(text.contains("\"Customization\""))
assertEquals(SessionFiles.BOOT_MOVIE_PATH, SessionFiles.startupMoviePath(file))
assertEquals(2, Regex("\"StartupMovie\"").findAll(text).count())
}
@Test fun aMissingStagedMovieResetsTheSectionSteamReads() {
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
assertTrue(SessionFiles.resetMissingStartupMovie(file, false))
assertNull(SessionFiles.startupMoviePath(file))
}
}
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.session
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 SteamClientSetupFailureTest {
private fun find(vararg lines: String) = SteamClientSetupFailure.find(lines.asSequence())
@Test fun aBlockedDownloadCarriesTheLastCurlError() {
val failure = find(
"== STEP 12:35:22 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (7) Failed to connect to client-update.steamstatic.com:443 after 3 ms: Could not connect to server",
"curl: (35) Recv failure: Connection reset by peer",
"droiddeck-steam-install: no Steam client CDN answered for steam_client_steamdeck_publicbeta_linuxarm64",
"== steam: the Steam client could not be set up (status 1)",
"[gamescope] [Info] launch: Primary child shut down!",
)!!
assertTrue(failure.download)
assertEquals("curl: (35) Recv failure: Connection reset by peer", failure.curlError)
}
@Test fun aFailureWithoutCurlErrorIsNotCalledADownloadProblem() {
val failure = find(
"== STEP 12:35:22 checking the Steam client (a first run downloads it)",
"== STEP 12:35:30 downloading Steam: bins_linuxarm64_linuxarm64 (2/17)",
"error: cannot create /root/.local/share/Steam/ubuntu12_32/steam-runtime.tar.xz",
"== steam: the Steam client could not be set up (status 50)",
)!!
assertFalse(failure.download)
assertNull(failure.curlError)
}
@Test fun aReadyClientIsNoFailure() {
assertNull(find(
"== STEP 12:35:22 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (35) Recv failure: Connection reset by peer",
"== STEP 12:35:40 Steam client ready",
))
}
@Test fun onlyTheLatestCheckCounts() {
assertNull(find(
"== STEP 10:00:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (6) Could not resolve host: client-update.steamstatic.com",
"== steam: the Steam client could not be set up (status 1)",
"== STEP 10:05:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"== STEP 10:06:00 Steam client ready",
))
val failure = find(
"== STEP 10:00:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"curl: (6) Could not resolve host: client-update.steamstatic.com",
"== steam: the Steam client could not be set up (status 1)",
"== STEP 10:05:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)",
"== steam: the Steam client could not be set up (status 9)",
)!!
assertNull(failure.curlError)
}
@Test fun anArm64SyncErrorIsNotBlamedForTheX64Client() {
val failure = find(
"== STEP 10:00:00 checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)",
"curl: (6) Could not resolve host: client-update.steamstatic.com",
"== STEP 10:00:05 could not update the arm64 client's parts; the x86-64 client keeps its own web helper",
"== STEP 10:00:05 checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)",
"== steam: the Steam client could not be set up (status 3)",
)!!
assertNull(failure.curlError)
}
}
@@ -0,0 +1,92 @@
package com.droiddeck.launcher.session
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 = [33])
class SteamDeckRepoTest {
private val sample = """
{"posts":[
{"id":"p1","title":"Cool","content":"c","user":{"steam_name":"Ann"},"thumbnail":"https://x/t.png","video":"https://x/v.webm",
"video_duration":7,"likes":3,"downloads":9,"devices":["steam_deck"],"url":"https://steamdeckrepo.com/post/p1"},
{"id":"p2","title":"","video":"http://insecure/v.webm"},
{"id":"","video":"https://x/v.webm"},
{"id":"p3","video":"https://x/v3.webm","thumbnail":"ftp://bad"}
],"currentSort":"trending"}
""".trimIndent()
@Test fun parsesPostsAndSkipsBrokenOnes() {
val posts = SteamDeckRepo.parse(sample)!!
assertEquals(listOf("p1", "p3"), posts.map { it.id })
val first = posts[0]
assertEquals("Cool", first.title)
assertEquals("Ann", first.author)
assertEquals(7, first.seconds)
assertEquals(listOf("steam_deck"), first.devices)
assertEquals("p3", posts[1].title)
assertEquals("", posts[1].thumbnail)
}
@Test fun notJsonIsNotAPage() {
assertNull(SteamDeckRepo.parse("<html>"))
assertNull(SteamDeckRepo.parse("{}"))
}
@Test fun buildsTheSameAddressesAsTheWebsite() {
assertEquals("https://steamdeckrepo.com/api/posts?sort=trending", SteamDeckRepo.url(SteamDeckRepo.Sort.TRENDING, null, ""))
assertEquals(
"https://steamdeckrepo.com/api/posts?sort=downloads-desc&device=steam_machine&search=a%20b%26c&page=3",
SteamDeckRepo.url(SteamDeckRepo.Sort.DOWNLOADS, "steam_machine", " a b&c ", 3),
)
}
@Test fun readsAreCutOffAtTheLimit() {
assertEquals(10, SteamDeckRepo.readLimited(ByteArray(10).inputStream(), 10)!!.size)
assertNull(SteamDeckRepo.readLimited(ByteArray(11).inputStream(), 10))
}
@Test fun jsonNullsAreEmptyTextNotTheWordNull() {
val posts = SteamDeckRepo.parse(
"""{"posts":[{"id":"p9","title":null,"content":null,"user":{"steam_name":null},"thumbnail":null,"video":"https://x/v.webm","url":null}]}""",
)!!
val post = posts.single()
assertEquals("p9", post.title)
assertEquals("", post.content)
assertEquals("", post.author)
assertEquals("", post.thumbnail)
assertEquals("", post.url)
assertTrue(SteamDeckRepo.parse("""{"posts":[{"id":null,"video":"https://x/v.webm"}]}""")!!.isEmpty())
}
@Test fun aPageHoldsTwelveMovies() {
assertEquals(12, SteamDeckRepo.PAGE_SIZE)
}
private fun lastPageOf(pages: Int, tail: Int = SteamDeckRepo.PAGE_SIZE) = SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "") { p ->
when {
p < pages -> SteamDeckRepo.PAGE_SIZE
p == pages -> tail
else -> 0
}
}
@Test fun theLastPageIsFoundByAskingForPages() {
for (pages in listOf(2, 3, 7, 8, 9, 33, 100, 500)) assertEquals(pages, lastPageOf(pages))
}
@Test fun aShortLastPageEndsTheSearchAtOnce() {
assertEquals(1, lastPageOf(1, tail = 5))
assertEquals(5, lastPageOf(5, tail = 3))
assertEquals(37, lastPageOf(37, tail = 1))
}
@Test fun aSearchWithNothingHasOnePageAndAnUnreachableSiteHasNone() {
assertEquals(1, SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "x") { 0 })
assertNull(SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "x") { null })
assertNull(SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "x") { p -> if (p < 4) SteamDeckRepo.PAGE_SIZE else null })
}
}
@@ -57,6 +57,25 @@ class SteamDownloadMonitorTest {
}
}
@Test fun readsBoundCardLibrariesFromTheirHostPath() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val card = File(root, "card").apply { mkdirs() }
File(root, "root/.local/share/Steam/steamapps").apply { mkdirs() }
.resolve("libraryfolders.vdf")
.writeText("\"libraryfolders\" { \"1\" { \"path\" \"/mnt/droiddeck-sd\" } }")
val manifest = manifest(card, "44", downloaded = 10, total = 100, flags = 6)
val monitor = SteamDownloadMonitor()
val mounts = mapOf("/mnt/droiddeck-sd" to card)
assertFalse(monitor.poll(root, now = 1_000L, mounts = mounts))
manifest.writeText(appManifest(downloaded = 20, total = 100, flags = 6))
assertTrue(monitor.poll(root, now = 3_000L, mounts = mounts))
} finally {
root.deleteRecursively()
}
}
@Test fun followsSteamContentActivityWhenManifestProgressIsNotFlushed() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.stores
import java.io.File
import java.util.concurrent.Executor
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
@@ -11,7 +12,7 @@ import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
@Config(sdk = [33], application = android.app.Application::class)
class CloudSavesTest {
private val app get() = RuntimeEnvironment.getApplication()
@@ -83,9 +84,11 @@ class CloudSavesTest {
}
@Test fun aFirstLaunchWithoutAPrefixIsDeferredNotBlocked() {
val deferred = ArrayList<Runnable>()
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN").apply { mkdirs() }
File(folder, "ELDERBORN.exe").writeText("MZ")
StoreGameSidecar(Store.GOG, "1207664643", "ELDERBORN", "ELDERBORN.exe").write(folder)
assertEquals("deferred", CloudSaves.downloadOrDefer(app, Store.GOG, "1207664643").result)
assertEquals("deferred", CloudSaves.downloadOrDefer(app, Store.GOG, "1207664643", Executor { deferred += it }).result)
assertEquals(1, deferred.size)
}
}
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class DetailCatalogItemTest {
private fun item(store: Store, id: String, title: String) = CatalogItem(store, id, title, imageUrl = null)
private val shelves = StoreShelves(trending = listOf(item(Store.XBOX, "9SHELF000001", "Shelf game")))
@Test fun aSearchOnlyResultKeepsItsMetadataOnTheDetailPage() {
val found = listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver"))
assertEquals("Echo Weaver", detailCatalogItem(Store.XBOX, "9SEARCH00001", emptyList(), found, shelves)?.title)
}
@Test fun theLibraryWinsOverSearchAndShelvesForTheSameProduct() {
val library = listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver").copy(owned = true, sizeBytes = 42))
val found = listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver").copy(owned = false))
val resolved = detailCatalogItem(Store.XBOX, "9SEARCH00001", library, found, shelves)!!
assertEquals(true, resolved.owned)
assertEquals(42L, resolved.sizeBytes)
}
@Test fun shelvesRemainAFallbackAndTheItemStaysInItsStore() {
assertEquals("Shelf game", detailCatalogItem(Store.XBOX, "9SHELF000001", emptyList(), emptyList(), shelves)?.title)
assertNull(detailCatalogItem(Store.GOG, "9SEARCH00001", emptyList(), listOf(item(Store.XBOX, "9SEARCH00001", "Echo Weaver")), shelves))
assertNull(detailCatalogItem(Store.XBOX, "9UNKNOWN0001", emptyList(), emptyList(), shelves))
}
}
@@ -112,6 +112,25 @@ class StoreAccountsCipherTest {
assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString())
}
@Test fun xboxNeverFallsBackToPlaintextWhenKeystoreFails() {
StoreAccounts.keys = broken
org.junit.Assert.assertThrows(IllegalStateException::class.java) {
StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "test@example.test").put("slots", JSONObject().put("user-tokens", "synthetic-secret")))
}
assertFalse(file(Store.XBOX).exists())
StoreAccounts.keys = fake
StoreAccounts.write(app, Store.XBOX, creds)
assertTrue(CredentialCipher.isEnvelope(JSONObject(file(Store.XBOX).readText())))
}
@Test fun xboxUsernameAndBackendSlotsAreEncryptedTogether() {
val xbox = JSONObject().put("username", "test@example.test").put("slots", JSONObject().put("user-tokens", "synthetic-secret"))
StoreAccounts.write(app, Store.XBOX, xbox)
assertFalse(file(Store.XBOX).readText().contains("synthetic-secret"))
assertFalse(file(Store.XBOX).readText().contains("test@example.test"))
assertEquals("test@example.test", StoreAccounts.signedInAs(app, Store.XBOX))
}
@Test fun signOutRemovesTheFile() {
StoreAccounts.write(app, Store.GOG, creds)
StoreAccounts.clear(app, Store.GOG)
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
/** Filling a grid one card at a time: what is on screen stays put, what is new lands where its title belongs. */
class StoreCatalogPatchTest {
private fun item(id: String, title: String, image: String? = null) = CatalogItem(Store.GOG, id, title, imageUrl = image, owned = true)
@Test fun onlyTheCardItWasGivenIsReplaced() {
val alpha = item("1", "Alpha")
val beta = item("2", "Beta")
val next = patchItems(listOf(alpha, beta), listOf(item("2", "Beta", "wide.jpg")))
assertEquals(2, next.size)
assertSame(alpha, next[0])
assertEquals("wide.jpg", next[1].imageUrl)
}
@Test fun aCardTheGridDoesNotHaveYetIsAddedInTitleOrder() {
val next = patchItems(listOf(item("1", "Alpha"), item("3", "Gamma")), listOf(item("2", "Beta")))
assertEquals(listOf("Alpha", "Beta", "Gamma"), next.map { it.title })
}
@Test fun anEmptyGridTakesTheCardAsItComes() {
val next = patchItems(null, listOf(item("2", "Beta")))
assertEquals(listOf("Beta"), next.map { it.title })
}
}
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.stores
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.util.Locale
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], application = android.app.Application::class)
class StoreLanguageTest {
@Test
fun polishDepotIsKeptWhenPolishIsChosen() {
assertTrue(StoreLanguage.depotAccepted(arrayOf("pl-PL"), "pl"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("pl"), "pl-PL"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("polish"), "pl-PL"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("*"), "pl"))
assertTrue(StoreLanguage.depotAccepted(emptyArray(), "pl"))
assertTrue(StoreLanguage.depotAccepted(null, "pl"))
}
@Test
fun englishDepotIsSkippedWhenPolishIsChosen() {
assertFalse(StoreLanguage.depotAccepted(arrayOf("en-US"), "pl-PL"))
assertFalse(StoreLanguage.depotAccepted(arrayOf("en", "english"), "pl"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("en-US"), "en"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("en"), "en-US"))
assertTrue(StoreLanguage.depotAccepted(arrayOf("english"), "en-US"))
}
@Test
fun pickPrefersSystemLanguageThenEnglish() {
val available = listOf("en-US", "de-DE", "pl-PL")
assertEquals("pl-PL", StoreLanguage.pick(available, "pl"))
assertEquals("en-US", StoreLanguage.pick(available, "ja"))
assertEquals("de-DE", StoreLanguage.pick(listOf("de-DE", "fr-FR"), "de"))
assertEquals("wanted", StoreLanguage.pick(emptyList(), "wanted"))
}
@Test
fun pickPrefersExactCodeBeforeTheBaseLanguage() {
val both = listOf("pl", "pl-PL", "en-US")
assertEquals("pl-PL", StoreLanguage.pick(both, "pl-PL"))
assertEquals("pl", StoreLanguage.pick(both, "pl"))
assertEquals("pl-PL", StoreLanguage.pick(listOf("en-US", "pl-PL"), "pl"))
}
@Test
fun resolvedDepotKeepsSharedFilesAndOnlyTheChosenVariant() {
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("*"), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(emptyArray(), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(null, "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("pl-PL", "*"), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("pl-PL"), "pl-PL"))
assertFalse(StoreLanguage.depotMatchesResolved(arrayOf("pl"), "pl-PL"))
assertFalse(StoreLanguage.depotMatchesResolved(arrayOf("en-US"), "pl-PL"))
assertTrue(StoreLanguage.depotMatchesResolved(arrayOf("polish"), "pl"))
}
@Test
fun tagForFollowsLocale() {
assertEquals("pl-PL", StoreLanguage.tagFor(Locale("pl", "PL")))
assertEquals("pl", StoreLanguage.tagFor(Locale("pl")))
assertEquals("pt-BR", StoreLanguage.tagFor(Locale("pt", "BR")))
assertEquals("es-419", StoreLanguage.tagFor(Locale("es", "MX")))
assertEquals("zh-Hans", StoreLanguage.tagFor(Locale.SIMPLIFIED_CHINESE))
assertEquals("zh-Hant", StoreLanguage.tagFor(Locale.TRADITIONAL_CHINESE))
}
@Test
fun codesFromDepotsSkipStarAndDuplicates() {
val depots = JSONArray()
.put(JSONObject().put("languages", JSONArray().put("*").put("en-US")))
.put(JSONObject().put("languages", JSONArray().put("pl-PL").put("en-US")))
.put(JSONObject().put("languages", JSONArray()))
assertEquals(listOf("en-US", "pl-PL"), StoreLanguage.codesFromDepots(depots))
assertTrue(StoreLanguage.codesFromDepots(null).isEmpty())
}
@Test
fun selectableStoresAreGogAndEpic() {
assertTrue(StoreLanguage.selectable(Store.GOG))
assertTrue(StoreLanguage.selectable(Store.EPIC))
assertFalse(StoreLanguage.selectable(Store.AMAZON))
assertFalse(StoreLanguage.selectable(Store.XBOX))
assertFalse(StoreLanguage.selectable(Store.ITCH))
}
}
@@ -0,0 +1,56 @@
package com.droiddeck.launcher.stores
import android.app.Application
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.session.SessionPrefs
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
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], application = Application::class)
class StoreLaunchTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun install(state: String = StoreGameSidecar.STATE_INSTALLED): File {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.installRoot(app), Store.XBOX), "Deep Rock Galactic")
File(folder, "FSD/Binaries/WinGDK/FSD.exe").apply { parentFile!!.mkdirs(); writeText("licensed image") }
StoreGameSidecar(Store.XBOX, "9NHFVWX1V7QJ", "Deep Rock Galactic", "FSD/Binaries/WinGDK/FSD.exe", state = state).write(folder)
return folder
}
@Test fun aCompletedInstallCanLaunchBeforeTheFrontendLibraryRefreshes() {
val folder = install()
val game = StoreLaunch.installedGame(app, Store.XBOX, "9NHFVWX1V7QJ")!!
val added = AddedGames.single(app, folder.path)!!
assertEquals("xbox", game.source)
assertEquals("9NHFVWX1V7QJ", game.storeId)
assertEquals(folder, game.gameFiles)
assertEquals(added.gameId, game.gameId)
assertTrue(added.guestExe.endsWith("/FSD/Binaries/WinGDK/FSD.exe"))
}
@Test fun unfinishedPackagesCannotBecomePlayableThroughTheFallback() {
for (state in listOf(StoreGameSidecar.STATE_INSTALLING, StoreGameSidecar.STATE_UPDATING)) {
install(state)
assertNull(StoreLaunch.installedGame(app, Store.XBOX, "9NHFVWX1V7QJ"))
}
}
@Test fun anotherStoreOrProductCannotUseTheXboxInstall() {
install()
assertNull(StoreLaunch.installedGame(app, Store.GOG, "9NHFVWX1V7QJ"))
assertNull(StoreLaunch.installedGame(app, Store.XBOX, "OTHERPRODUCT"))
}
@Test fun aMissingExecutableDoesNotBecomeALaunchTarget() {
val folder = install()
File(folder, "FSD/Binaries/WinGDK/FSD.exe").delete()
assertNull(StoreLaunch.installedGame(app, Store.XBOX, "9NHFVWX1V7QJ"))
}
}
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.stores
import android.os.Build
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class StoreLoginUserAgentTest {
@Test fun theDevicesWebViewAgentIsSentAsChrome() {
assertEquals(
"Mozilla/5.0 (Linux; Android 16; NP06J) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Mobile Safari/537.36",
StoreLoginActivity.chromeUserAgent(
"Mozilla/5.0 (Linux; Android 16; NP06J Build/BP2A.250605.031.A3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.122 Mobile Safari/537.36",
),
)
}
@Test fun noWebViewAgentFallsBackToChromeWithoutAnotherDevicesModel() {
for (agent in listOf(null, "", "Dalvik/2.1.0 (Linux; U; Android 16)")) {
val ua = StoreLoginActivity.chromeUserAgent(agent)
assertTrue(ua, "Chrome/" in ua)
assertFalse(ua, "SM-S918B" in ua)
assertTrue(ua, "Android ${Build.VERSION.RELEASE}; ${Build.MODEL})" in ua)
}
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.stores
import com.droiddeck.launcher.stores.gog.GogAuth
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class WebCookiesTest {
@Test fun gogLoginCookiesAreExpiredOnTheLoginHostAndTheDomain() {
val lines = WebCookies.expired("galaxy-login-s=a; galaxy-login-tsa=b; galaxy-login-al=c", GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com")
assertEquals(9, lines.size)
assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure"))
assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure; Domain=.gog.com"))
assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure; Domain=login.gog.com"))
assertTrue(lines.none { it.startsWith("galaxy-login-al=c") })
assertEquals(emptyList<String>(), WebCookies.expired(null, GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com"))
}
}
@@ -0,0 +1,79 @@
package com.droiddeck.launcher.stores.gog
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
/** The account listing: everything the tab needs to draw a library before a product is asked about. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogListingTest {
@Test
fun aPageCarriesTheGamesTheAppCanInstall() {
val page = GogLibrary.parseListing(PAGE)!!
assertEquals(2, page.totalPages)
assertEquals(listOf("Shadowrun Returns", "Witcher 3: Wild Hunt, The"), page.games.map { it.title })
val shadowrun = page.games[0]
assertEquals("1207660413", shadowrun.gameId)
assertEquals("https://images-2.gog.com/6c35ecb988f57725cc0f385acf860241082da16eda9fab66115f4da883dae3d1_glx_vertical_cover.webp", shadowrun.verticalCover)
assertEquals("", shadowrun.imageUrl)
assertEquals("Role-playing", shadowrun.category)
assertEquals("2013-07-25", shadowrun.releaseDate)
assertEquals("", shadowrun.description)
}
@Test
fun moviesOtherPlatformsAndGalaxysOwnEntryAreLeftOut() {
assertEquals(listOf("1207660413", "1207664663"), GogLibrary.parseListing(PAGE)!!.games.map { it.gameId })
}
@Test
fun aResponseThatIsNotAListingIsNull() {
assertNull(GogLibrary.parseListing("""{"error":"unauthorized"}"""))
assertNull(GogLibrary.parseListing("not json"))
}
private companion object {
val PAGE = """
{
"sortBy": "title",
"page": 1,
"totalProducts": 6,
"totalPages": 2,
"productsPerPage": 100,
"products": [
{
"id": 1207660413,
"title": "Shadowrun Returns",
"image": "//images-2.gog.com/6c35ecb988f57725cc0f385acf860241082da16eda9fab66115f4da883dae3d1",
"worksOn": { "Windows": true, "Mac": true, "Linux": true },
"category": "Role-playing",
"isComingSoon": false,
"isMovie": false,
"isGame": true,
"slug": "shadowrun_returns",
"dlcCount": 0,
"releaseDate": { "date": "2013-07-25 00:00:00.000000", "timezone_type": 3, "timezone": "Europe/Nicosia" }
},
{
"id": 1207664663,
"title": " Witcher 3: Wild Hunt, The ",
"image": "//images-3.gog.com/60c724a052275a049d857d53957dc38e9347742f52372bb956d992b43efa8fb5",
"worksOn": { "Windows": true, "Mac": false, "Linux": false },
"category": "Role-playing",
"isMovie": false,
"isGame": true,
"releaseDate": { "date": "2015-05-19 02:00:00.000000", "timezone_type": 3, "timezone": "Europe/Nicosia" }
},
{ "id": 1582718039, "title": "A Movie", "image": "//images-1.gog.com/movie", "isMovie": true, "isGame": false },
{ "id": 1430747193, "title": "Mac Only", "image": "//images-1.gog.com/mac", "worksOn": { "Windows": false, "Mac": true }, "isMovie": false, "isGame": true },
{ "id": 1801418160, "title": "GOG Galaxy", "image": "//images-1.gog.com/galaxy", "worksOn": { "Windows": true }, "isMovie": false, "isGame": true },
{ "id": 1401362385, "title": "Soundtrack", "image": "//images-1.gog.com/ost", "worksOn": { "Windows": true }, "isMovie": false, "isGame": false }
]
}
""".trimIndent()
}
}
@@ -0,0 +1,60 @@
package com.droiddeck.launcher.stores.xbox
import androidx.test.core.app.ApplicationProvider
import org.junit.Assert.*
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class XboxAccountLifecycleTest {
private val app = ApplicationProvider.getApplicationContext<android.content.Context>()
@Test fun staleSignInCommitsAndBackendStartsCannotAcquireANewerAccount() {
val original = XboxCredentials.lifecycle(app) { it }
XboxCredentials.invalidate(app)
var committed = false
assertThrows(IllegalStateException::class.java) {
XboxCredentials.lifecycle(app, original) { committed = true }
}
assertFalse(committed)
assertThrows(IllegalStateException::class.java) { XboxCredentials(app, original) }
XboxCredentials.lifecycle(app) { current -> assertNotEquals(original, current) }
}
@Test fun accountCommitAndLaunchAuthorizationWaitUntilRevocationFinishes() {
val revoked = CountDownLatch(1)
val releaseStop = CountDownLatch(1)
val attempted = CountDownLatch(1)
val committed = AtomicBoolean(false)
val authorized = CountDownLatch(1)
val signOut = Thread {
XboxCredentials.invalidate(app) {
revoked.countDown()
check(releaseStop.await(5, TimeUnit.SECONDS))
}
}.apply { start() }
assertTrue(revoked.await(5, TimeUnit.SECONDS))
val signIn = Thread {
attempted.countDown()
XboxCredentials.lifecycle(app) {
committed.set(true)
authorized.countDown()
}
}.apply { start() }
try {
assertTrue(attempted.await(5, TimeUnit.SECONDS))
assertFalse(authorized.await(100, TimeUnit.MILLISECONDS))
assertFalse(committed.get())
} finally {
releaseStop.countDown()
signOut.join(5000)
signIn.join(5000)
}
assertTrue(committed.get())
assertFalse(signOut.isAlive)
assertFalse(signIn.isAlive)
}
}
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.stores.xbox
import org.junit.Assert.*
import org.junit.Test
class XboxBackendMappingTest {
private val path = "/runtime/xodus-cli"
private fun mapping(permissions: String = "r-xp", inode: Long = 42, name: String = path) =
"7a0000-7b0000 $permissions 00001000 00:31 $inode $name\n"
@Test fun prootLoaderDoesNotHideTheVerifiedBackendImage() {
val maps = mapping(name = "/android/libproot-loader.so", inode = 1) + mapping()
assertTrue(XboxCredentials.mapsBackend(maps, path, 42))
}
@Test fun loaderAloneOrAnotherGuestExecutableCannotAuthenticate() {
assertFalse(XboxCredentials.mapsBackend(mapping(name = "/android/libproot-loader.so"), path, 42))
assertFalse(XboxCredentials.mapsBackend(mapping(name = "/runtime/other-cli"), path, 42))
assertFalse(XboxCredentials.mapsBackend(mapping(inode = 43), path, 42))
assertFalse(XboxCredentials.mapsBackend(mapping(permissions = "r--p"), path, 42))
assertFalse(XboxCredentials.mapsBackend(mapping(name = "$path (deleted)"), path, 42))
assertFalse(XboxCredentials.mapsBackend("malformed\n", path, 42))
}
}
@@ -0,0 +1,168 @@
package com.droiddeck.launcher.stores.xbox
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import java.time.Instant
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class XboxCatalogTest {
private val now = Instant.parse("2026-10-19T12:00:00Z")
private val game = "9AAAAAAAAAAA"
private val parent = "9BBBBBBBBBBB"
private val plan = "CFQ7TTC0KGQ8"
private fun row(id: String, parent: String? = null) = JSONObject().put("productId", id).put("status", "Active")
.put("isTrial", false).put("special", false).put("sharingSource", "None")
.put("endDate", "2099-01-01T00:00:00Z").put("satisfiedByProductId", parent ?: JSONObject.NULL)
private fun envelope(vararg rows: JSONObject) = JSONObject().put("schema", 1).put("account", "test@example.test")
.put("market", "US").put("checkedAt", now.toString()).put("entitlements", JSONArray(rows.toList()))
private fun access(vararg rows: JSONObject) = XboxCatalog.access(envelope(*rows), "test@example.test", "US", now)
private fun membership(id: String = plan) = JSONObject().put("productId", id).put("status", "Active").put("endDate", "2099-01-01T00:00:00Z")
private fun withMembership(json: JSONObject, vararg plans: JSONObject) = json.put("subscriptions", JSONArray(plans.toList()))
@Test fun separateMembershipRestoresSubscriptionChildrenWithoutInventingOwnership() {
val json = withMembership(envelope(row(game), row(parent, plan)), membership())
assertEquals(mapOf(game to "owned", parent to "gamepass"), XboxCatalog.access(json, "test@example.test", "US", now))
assertTrue(XboxCatalog.access(withMembership(envelope(), membership()), "test@example.test", "US", now).isEmpty())
assertEquals(mapOf(game to "gamepass", parent to "gamepass"), XboxCatalog.access(
withMembership(envelope(row(game, parent), row(parent, plan)), membership()), "test@example.test", "US", now))
}
@Test fun separateMembershipPreservesProductRestrictionsAndExistingPlanEvidence() {
for (member in listOf(membership().put("status", "Expired"), membership().put("endDate", now.toString()))) {
assertTrue(XboxCatalog.access(withMembership(envelope(row(game, plan)), member), "test@example.test", "US", now).isEmpty())
}
assertEquals(mapOf(game to "gamepass"), XboxCatalog.access(
withMembership(envelope(row(game, plan), row(plan))), "test@example.test", "US", now))
for ((key, value) in listOf("status" to "Expired", "isTrial" to true, "special" to true,
"sharingSource" to "Family", "endDate" to now.toString())) {
for (rows in listOf(arrayOf(row(game, plan).put(key, value)), arrayOf(row(game, plan), row(plan).put(key, value)))) {
assertTrue(XboxCatalog.access(withMembership(envelope(*rows), membership()), "test@example.test", "US", now).isEmpty())
}
}
}
@Test fun malformedMembershipFailsTheRefreshInsteadOfBecomingAnEmptySuccessfulLibrary() {
for (json in listOf(
withMembership(envelope(row(game, plan)), membership().put("endDate", "invalid")),
withMembership(envelope(row(game, plan)), membership(), membership()),
withMembership(envelope(row(game, plan)), membership().put("productId", game)),
envelope(row(game, plan)).put("subscriptions", JSONObject.NULL),
)) {
assertThrows(Exception::class.java) { XboxCatalog.access(json, "test@example.test", "US", now) }
}
}
@Test fun membershipCannotCrossAccountMarketOrFreshnessBoundaries() {
for ((key, value) in listOf("account" to "other@example.test", "market" to "GB", "checkedAt" to "2020-01-01T00:00:00Z")) {
val json = withMembership(envelope(row(game, plan)).put(key, value), membership())
assertThrows(IllegalArgumentException::class.java) { XboxCatalog.access(json, "test@example.test", "US", now) }
}
}
@Test fun libraryDiagnosticsContainCountsWithoutAccountOrProductIdentifiers() {
val lines = mutableListOf<String>()
XboxCatalog.access(envelope(row(game), row(parent, plan)), "test@example.test", "US", now, lines::add)
assertEquals(listOf("library entitlements=2 invalid=0 restricted=0 unverified-plan=1 owned=1 gamepass=0"), lines)
assertFalse(lines.single().contains(game) || lines.single().contains(parent) || lines.single().contains("@"))
}
@Test fun purchasedAndSubscriptionAccessRemainDistinct() {
assertEquals(mapOf(game to "owned", parent to "gamepass"), access(row(game), row(parent, plan), row(plan)))
assertFalse(access(row(plan)).containsKey(plan))
}
@Test fun subscriptionRequiresAnActivePlanRow() {
assertTrue(access(row(game, plan)).isEmpty())
for ((key, value) in listOf("status" to "Expired", "isTrial" to true, "special" to true,
"sharingSource" to "Family", "endDate" to now.toString())) {
assertTrue(access(row(game, plan), row(plan).put(key, value)).isEmpty())
}
assertEquals(mapOf(game to "gamepass", parent to "gamepass"), access(row(game, parent), row(parent, plan), row(plan)))
}
@Test fun onlyPcPlansGrantSubscriptionAccess() {
for (pc in listOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC10QFD")) {
assertEquals(mapOf(game to "gamepass"), access(row(game, pc), row(pc)))
}
val console = "CFQ7TTC0K6L8"
assertTrue(access(row(game, console), row(console)).isEmpty())
assertTrue(XboxCatalog.access(withMembership(envelope(row(game, console)), membership(console)),
"test@example.test", "US", now).isEmpty())
}
@Test fun backendRfc3339OffsetsAndNanosecondsAreAccepted() {
val checked = "2026-10-19T19:02:38.173609086+00:00"
val response = envelope(row(game).put("endDate", "2099-01-01T01:00:00.000000001+01:00"))
.put("checkedAt", checked)
assertEquals(mapOf(game to "owned"), XboxCatalog.access(response, "test@example.test", "US",
Instant.parse("2026-10-19T19:02:39Z")))
}
@Test fun expiredTrialSharedAndUnknownFlagsDoNotGrantAccess() {
for ((key, value) in listOf("status" to "Expired", "isTrial" to true, "special" to true,
"sharingSource" to "Family", "endDate" to "2020-01-01T00:00:00Z")) {
assertTrue(access(row(game).put(key, value)).isEmpty())
}
}
@Test fun malformedAndConflictingParentsCannotGrantDependentAccess() {
assertTrue(access(row(game, parent), row(parent).put("isTrial", JSONObject.NULL)).isEmpty())
assertTrue(access(row(game, plan), row(plan).put("endDate", "invalid")).isEmpty())
assertTrue(access(row(game), row(game, plan)).isEmpty())
assertTrue(access(row(game, parent), row(parent, game)).isEmpty())
}
@Test fun mismatchedAccountAndStaleResultsAreRejected() {
for (json in listOf(envelope(row(game)).put("account", "other@example.test"),
envelope(row(game)).put("checkedAt", "2020-01-01T00:00:00Z"))) {
assertThrows(IllegalArgumentException::class.java) { XboxCatalog.access(json, "test@example.test", "US", now) }
}
}
@Test fun installedSubscriptionDoesNotBecomeOwnershipWithoutACachedLibrary() {
val sidecar = com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.XBOX,
game, "A game", "Game.exe", extra = mapOf("access" to "gamepass"))
val card = com.droiddeck.launcher.stores.installedCards(com.droiddeck.launcher.stores.Store.XBOX,
listOf(com.droiddeck.launcher.stores.InstalledStoreGame(sidecar, java.io.File("/synthetic-game"))), emptyList()).single()
assertFalse(card.owned); assertTrue(card.subscription)
}
@Test fun pcSubscriptionAffirmationsOfferAnInstallWithoutClaimingOwnership() {
fun offer(vararg affirmations: String) = JSONObject().put("ProductId", game).put("ProductType", "Game")
.put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "A Pass game")
.put("EligibilityProperties", JSONObject().put("Affirmations", JSONArray(affirmations.map {
JSONObject().put("AffirmationProductId", it)
})))))
.put("DisplaySkuAvailabilities", JSONArray().put(JSONObject().put("Sku", JSONObject().put("Properties", JSONObject()
.put("Packages", JSONArray().put(JSONObject().put("PackageFormat", "MSIXVC").put("PlatformDependencies",
JSONArray().put(JSONObject().put("PlatformName", "Windows.Desktop")))))))))
val pc = XboxCatalog.product(offer("CFQ7TTC0KGQ8"), emptyMap())!!
assertEquals("PC Game Pass", pc.includedWith)
assertFalse(pc.accessible); assertTrue(pc.installable)
assertEquals("Game Pass Ultimate", XboxCatalog.product(offer("CFQ7TTC0KHS0"), emptyMap())!!.includedWith)
assertEquals("Xbox Game Pass Premium", XboxCatalog.product(offer("CFQ7TTC0P85B"), emptyMap())!!.includedWith)
assertEquals("Xbox Game Pass Essential", XboxCatalog.product(offer("CFQ7TTC0K5DJ"), emptyMap())!!.includedWith)
assertEquals("Xbox Game Pass (Starter Edition)", XboxCatalog.product(offer("CFQ7TTC10QFD"), emptyMap())!!.includedWith)
val console = XboxCatalog.product(offer("CFQ7TTC0K6L8"), emptyMap())!!
assertEquals("", console.includedWith); assertFalse(console.installable)
assertFalse(XboxCatalog.product(offer(), emptyMap())!!.installable)
}
@Test fun consoleAndUwpOffersAreFilteredOut() {
fun product(platform: String, format: String) = JSONObject().put("ProductId", game).put("ProductType", "Game")
.put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "A PC game")))
.put("DisplaySkuAvailabilities", JSONArray().put(JSONObject().put("Sku", JSONObject().put("Properties", JSONObject()
.put("Packages", JSONArray().put(JSONObject().put("PackageFormat", format).put("PlatformDependencies",
JSONArray().put(JSONObject().put("PlatformName", platform)))))))))
assertNull(XboxCatalog.product(product("Xbox.One", "MSIXVC"), mapOf(game to "owned")))
assertNull(XboxCatalog.product(product("Windows.Desktop", "APPX"), mapOf(game to "owned")))
val pc = XboxCatalog.product(product("Windows.Desktop", "MSIXVC"), mapOf(game to "gamepass"))!!
assertEquals(game, XboxCatalog.product(product("Windows.Desktop", "MSIXVC").put("ProductId", game.lowercase()), mapOf(game to "owned"))!!.id)
assertTrue(pc.accessible); assertTrue(pc.subscription); assertFalse(pc.owned)
}
}
@@ -0,0 +1,91 @@
package com.droiddeck.launcher.stores.xbox
import org.junit.Assert.*
import org.junit.Test
import java.io.Closeable
class XboxLaunchLeasesTest {
private var time = 0L
private val leases = XboxLaunchLeases { time }
private var closed = 0
private fun launch(account: String = "account", session: String = "session"): String {
return leases.begin("game", account, session).also { leases.attach(it, Closeable { closed++ }) }
}
private fun reap(account: String? = "account", session: String? = "session", suspended: Boolean = false) {
leases.stale(account, session, suspended).forEach { it.close() }
}
@Test fun steamLaunchCanCreateASessionBoundLease() {
val token = leases.begin("game", "account", "session")
assertTrue(leases.active("game"))
assertFalse(leases.renew(token, "game", "account", "other"))
assertThrows(IllegalStateException::class.java) { leases.begin("game", "account", "session") }
}
@Test fun releaseIsIdempotentAndCannotDecrementANewLaunch() {
val old = launch()
leases.release(old)?.close()
leases.release(old)?.close()
assertEquals(1, closed)
assertFalse(leases.active("game"))
val current = launch()
leases.release(old)?.close()
assertTrue(leases.active("game"))
leases.release(current)?.close()
assertEquals(2, closed)
}
@Test fun renewalCannotCrossAccountSessionOrGameBoundaries() {
val token = launch()
assertFalse(leases.renew(token, "other", "account", "session"))
assertFalse(leases.renew(token, "game", "other", "session"))
assertFalse(leases.renew(token, "game", "account", "other"))
assertTrue(leases.renew(token, "game", "account", "session"))
time = 60_000
assertFalse(leases.renew(token, "game", "account", "session"))
reap()
assertEquals(1, closed)
assertFalse(leases.active("game"))
}
@Test fun abandonedPreparationAndSessionEndCleanUp() {
launch()
time = 180_000
reap()
assertEquals(1, closed)
launch()
reap(session = null)
assertEquals(2, closed)
}
@Test fun accountSwitchInvalidatesOldLaunchWithoutAffectingItsReplacement() {
val old = launch()
reap(account = "next")
launch("next")
leases.release(old)?.close()
assertEquals(1, closed)
assertTrue(leases.active("game"))
}
@Test fun stopRemovesLeaseAndRejectsLateAttachment() {
val token = leases.begin("game", "account", "session")
leases.clear().forEach { it.close() }
assertFalse(leases.attach(token, Closeable { closed++ }))
assertFalse(leases.active("game"))
val next = leases.begin("game", "account", "new-session")
assertTrue(leases.active("game"))
assertFalse(leases.attach(token, Closeable { closed++ }))
assertTrue(leases.attach(next, Closeable { closed++ }))
}
@Test fun suspensionKeepsLiveLeasesUntilResume() {
val token = launch()
time = 200_000
reap(suspended = true)
time += 20_000
assertTrue(leases.renew(token, "game", "account", "session"))
reap()
assertEquals(0, closed)
}
@Test fun activityQueriesDoNotWaitForBackendClose() {
val token = launch()
val detached = leases.release(token)
val gate = java.util.concurrent.CountDownLatch(1)
val worker = Thread { gate.await(); detached?.close() }.apply { start() }
try { assertFalse(leases.active("game")); launch("next") } finally { gate.countDown(); worker.join(1000) }
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.stores.xbox
import org.junit.Assert.*
import org.junit.Test
import java.nio.file.Files
class XboxLaunchViewsTest {
@Test fun cleanupRemovesLicensedCopiesWithoutFollowingGameLinks() {
val root = Files.createTempDirectory("xbox-view-test").toFile()
try {
val game = root.resolve("installed").apply { mkdirs() }
game.resolve("Game.exe").writeText("encrypted original")
val view = XboxLaunchViews().create(root)
view.resolve("Game.exe").writeText("licensed copy")
Files.createSymbolicLink(view.resolve("originals").toPath(), game.toPath())
XboxLaunchViews.remove(view)
XboxLaunchViews.remove(view)
assertFalse(view.exists())
assertEquals("encrypted original", game.resolve("Game.exe").readText())
} finally { root.deleteRecursively() }
}
@Test fun recoveryRejectsARedirectedStorageRoot() {
val root = Files.createTempDirectory("xbox-view-links").toFile()
try {
val outside = root.resolve("installed").apply { mkdirs() }
val game = outside.resolve("launch-game").apply { mkdirs() }.resolve("Game.exe")
game.writeText("preserve")
val runtime = root.resolve("xbox-runtime").apply { mkdirs() }
Files.createSymbolicLink(runtime.resolve("views").toPath(), outside.toPath())
assertThrows(IllegalStateException::class.java) { XboxLaunchViews().create(root) }
assertEquals("preserve", game.readText())
} finally { root.deleteRecursively() }
}
@Test fun recoveryRemovesAbandonedViewsAndPreservesNewLiveViews() {
val root = Files.createTempDirectory("xbox-view-recovery").toFile()
try {
val old = XboxLaunchViews().create(root)
old.resolve("Game.exe").writeText("abandoned copy")
val evidence = old.parentFile!!.resolve("diagnostics").apply { mkdirs() }.resolve("report")
evidence.writeText("preserve")
val fresh = XboxLaunchViews()
val first = fresh.create(root)
first.resolve("Game.exe").writeText("running copy")
val second = fresh.create(root)
assertFalse(old.exists())
assertEquals("running copy", first.resolve("Game.exe").readText())
assertTrue(second.isDirectory)
assertEquals("preserve", evidence.readText())
} finally { root.deleteRecursively() }
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.stores.xbox
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import org.junit.Assert.*
import org.junit.Test
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class XboxLibraryCacheTest {
private val account = "test@example.test"
private val now = 1_792_440_000_000L
private fun game(id: String, subscription: Boolean) = CatalogItem(Store.XBOX, id, "A game", "https://example.test/hero",
tallImageUrl = "https://example.test/poster", description = "Description", developer = "Developer", publisher = "Publisher",
sizeBytes = 12345, owned = !subscription, subscription = subscription, storeUrl = "https://www.xbox.com/games/store/$id",
extra = mapOf("market" to "US", "access" to if (subscription) "gamepass" else "owned"))
@Test fun restartRestoresMetadataWithoutTurningSubscriptionsIntoPurchases() {
val games = listOf(game("9AAAAAAAAAAA", false), game("9BBBBBBBBBBB", true))
val text = XboxLibraryCache.encode(account, "US", games, now)
val cached = XboxLibraryCache.decode(text, account, "US", now)!!
assertEquals(games, cached.games)
assertFalse(cached.games[1].owned)
assertTrue(cached.games[1].subscription)
}
@Test fun anotherAccountMarketOrInvalidEnvelopeCannotRestoreTheLibrary() {
val text = XboxLibraryCache.encode(account, "US", listOf(game("9AAAAAAAAAAA", false)), now)
assertNull(XboxLibraryCache.decode(text, "other@example.test", "US", now))
assertNull(XboxLibraryCache.decode(text, account, "GB", now))
assertNull(XboxLibraryCache.decode(text.replace("\"schema\":1", "\"schema\":2"), account, "US", now))
assertNull(XboxLibraryCache.decode("invalid", account, "US", now))
assertNull(XboxLibraryCache.decode(text, account, "US", now - 120_000))
}
@Test fun freshCacheAvoidsNetworkAndForceOrStalenessRequestsARefresh() {
val cached = XboxLibraryCache.Snapshot(emptyList(), now)
assertFalse(cached.needsRefresh(false, now + 899_999))
assertTrue(cached.needsRefresh(false, now + 900_000))
assertTrue(cached.needsRefresh(true, now))
val old = XboxLibraryCache.decode(XboxLibraryCache.encode(account, "US", emptyList(), now), account, "US", now + 86_400_000)!!
assertTrue(old.needsRefresh(false, now + 86_400_000))
assertTrue(old.games.isEmpty())
}
@Test fun clearingTheCacheRemovesThePersistedAccountLibrary() {
val app = org.robolectric.RuntimeEnvironment.getApplication()
XboxLibraryCache.write(app, account, "US", listOf(game("9AAAAAAAAAAA", false)))
assertNotNull(XboxLibraryCache.read(app, account, "US"))
XboxLibraryCache.clear(app)
assertNull(XboxLibraryCache.read(app, account, "US"))
}
}
@@ -0,0 +1,55 @@
package com.droiddeck.launcher.stores.xbox
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class XboxManifestTest {
@get:Rule val temporary = TemporaryFolder()
@Test fun resolvesTheManifestExecutableWithWindowsLetterCasing() {
val root = temporary.newFolder()
java.io.File(root, "Bin").mkdir()
java.io.File(root, "Bin/Game.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.Config").writeText("<Game><ExecutableList><Executable Name=\"bin\\GAME.EXE\" TargetDeviceFamily=\"PC\"/></ExecutableList></Game>")
assertEquals("Bin/Game.exe", XboxInstaller.executable(root))
}
@Test fun rejectsTraversalAndExternalEntities() {
for (xml in listOf("<Game><Executable Name=\"../escape.exe\"/></Game>",
"<!DOCTYPE Game [<!ENTITY external SYSTEM 'file:///etc/passwd'>]><Game>&external;</Game>",
"<!DOCTYPE Game SYSTEM 'https://example.test/manifest.dtd'><Game/>",
"<!DOCTYPE Game [<!ENTITY internal 'test'>]><Game/>")) {
val root = temporary.newFolder()
java.io.File(root, "MicrosoftGame.config").writeText(xml)
assertThrows(Exception::class.java) { XboxInstaller.executable(root) }
}
}
@Test fun androidManifestParserPreservesIdentityAndSelectsTheRetailPcExecutable() {
val root = temporary.newFolder()
java.io.File(root, "Retail.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.Config").writeText("""<?xml version="1.0" encoding="utf-8"?>
<Game configVersion="1"><!-- package comment -->
<Identity Name="Test.Game" Publisher="CN=A &amp; B" Version="1.2.3.0"/>
<ExecutableList><Executable Name="Console.exe" TargetDeviceFamily="XboxOne"/>
<Executable Name="Dev.exe" TargetDeviceFamily="PC" IsDevOnly="true"/>
<Executable Name="Retail.exe" TargetDeviceFamily="PC" IsDevOnly="false"/></ExecutableList>
<StoreId>9AAAAAAAAAAA</StoreId><RelatedProduct>9BBBBBBBBBBB</RelatedProduct>
<MainPackageDependency Name="Test.Base"/></Game>""")
val info = XboxManifest.read(root)
assertEquals("9AAAAAAAAAAA", info.storeId)
assertEquals("Test.Game", info.name)
assertEquals("CN=A & B", info.publisher)
assertEquals("1.2.3.0", info.version)
assertEquals("Test.Base", info.dependency)
assertEquals(listOf("9BBBBBBBBBBB"), info.related)
assertEquals(listOf("Retail.exe"), info.executables)
assertEquals("Retail.exe", XboxManifest.executable(root))
}
@Test fun signInBridgeRejectsUntrustedAndNonHttpsOrigins() {
assertTrue(XboxLoginActivity.trusted("https://login.live.com/ppsecure/InlineLogin.srf"))
for (url in listOf("http://login.live.com/", "https://login.live.com.evil.test/", "https://evil.test@login.live.com/", "https://login.live.com:8443/"))
assertFalse(XboxLoginActivity.trusted(url))
}
}
@@ -0,0 +1,21 @@
package com.droiddeck.launcher.stores.xbox
import org.junit.Assert.*
import org.junit.Test
import java.io.File
class XboxServiceSocketTest {
@Test fun serviceSocketsFitUnixAddressesForEveryPackageAndRemainDistinct() {
val variants = generateSequence(File(requireNotNull(System.getProperty("user.dir")))) { it.parentFile }
.map { File(it, "tools/release/variants.txt") }.first { it.isFile }
val packages = variants.readLines().filter { it.isNotBlank() && !it.startsWith('#') }
.map { it.trim().split(Regex("\\s+"))[1] }
for (pkg in packages) for (user in listOf(0, 99999)) {
val files = File("/data/user/$user/$pkg/files")
val first = XboxRuntime.newServiceSocket(files)
val second = XboxRuntime.newServiceSocket(files)
assertTrue(first.path, first.path.toByteArray(Charsets.UTF_8).size < 108)
assertNotEquals(first, second)
}
}
}
@@ -0,0 +1,33 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CloudSaves
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 CloudMessageTest {
private val ctx get() = RuntimeEnvironment.getApplication()
private fun msg(result: String, files: Int, conflicts: Int, reason: String) =
cloudMessage(ctx, CloudSaves.Result(result, files, 0L, reason, conflicts))
@Test fun aSkippedSyncNeverReadsAsZeroFilesDone() {
assertEquals(ctx.getString(R.string.cloud_signed_out), msg("skipped", 0, 0, "not-signed-in"))
assertEquals(ctx.getString(R.string.cloud_none), msg("skipped", 0, 0, "no-cloud-saves"))
for (reason in listOf("off", "no-baseline", "nothing-local", "store-unreachable", "unresolved")) {
assertEquals(reason, ctx.getString(R.string.cloud_not_synced), msg("skipped", 0, 0, reason))
}
assertEquals(ctx.getString(R.string.cloud_not_synced), msg("failed", 0, 0, "SocketTimeoutException"))
}
@Test fun okResultsSayWhatHappened() {
assertEquals(ctx.getString(R.string.cloud_up_to_date), msg("ok", 0, 0, "up-to-date"))
assertEquals(ctx.getString(R.string.cloud_done, 3), msg("ok", 3, 0, "uploaded"))
assertEquals(ctx.getString(R.string.cloud_conflict_files, 2), msg("ok", 1, 2, "conflict"))
}
}
@@ -4,11 +4,20 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performKeyInput
import androidx.compose.ui.test.pressKey
import androidx.compose.ui.test.requestFocus
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.ComponentsManager
import org.junit.Assert.assertEquals
@@ -19,10 +28,12 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@OptIn(ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class ComponentDownloadsDrawerTest {
@get:Rule val compose = createRobolectricComposeRule()
private lateinit var inputMode: InputModeManager
private val dxvk = item("dxvk-2.4.1-linux.wcp", "dxvk")
private val stored = item("dxvk-2.3-linux.wcp", "dxvk")
@@ -42,6 +53,40 @@ class ComponentDownloadsDrawerTest {
compose.onNodeWithText("45%").assertExists()
}
@Test fun pairedNightlyRidesOnTheStableRowBehindTheSwitch() {
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
val requested = mutableListOf<ComponentsManager.CatalogItem>()
show(catalog = listOf(stable, nightly), onDownload = requested::add)
compose.onNodeWithTag("cmp-download-dxvk").performClick()
compose.onNodeWithText("dxvk-3.1.1-linux").assertExists()
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").assertDoesNotExist()
compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)).performClick()
compose.onNodeWithText("dxvk-3.1.1-linux").assertDoesNotExist()
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").performClick()
assertEquals(listOf(nightly), requested)
}
@Test fun controllerPicksNightlyOnItsTabThenDownloadsItFromTheRow() {
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
val requested = mutableListOf<ComponentsManager.CatalogItem>()
show(catalog = listOf(stable, nightly), onDownload = requested::add)
compose.onNodeWithTag("cmp-download-dxvk").performClick()
compose.runOnIdle { inputMode.requestInputMode(InputMode.Keyboard) }
compose.onNodeWithText("dxvk-3.1.1-linux").requestFocus().assertIsFocused()
compose.onNodeWithText("dxvk-3.1.1-linux").performKeyInput { pressKey(Key.DirectionRight) }
val nightlyTab = RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)
compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_stable)).assertIsFocused()
.performKeyInput { pressKey(Key.DirectionRight) }
compose.onNodeWithText(nightlyTab).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").assertExists()
assertEquals(emptyList<ComponentsManager.CatalogItem>(), requested)
compose.onNodeWithText(nightlyTab).performKeyInput { pressKey(Key.DirectionLeft); pressKey(Key.DirectionLeft) }
compose.onNodeWithText("DD-dxvk-3.1.1+153-nightly").assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
assertEquals(listOf(nightly), requested)
}
@Test fun emptyCatalogOffersRefreshAndDisablesVersionChoicesWhileChecking() {
var refreshes = 0
show(catalog = emptyList(), checking = false, onRefresh = { refreshes++ })
@@ -64,6 +109,7 @@ class ComponentDownloadsDrawerTest {
onDownload: (ComponentsManager.CatalogItem) -> Unit = {},
) {
compose.setContent {
inputMode = LocalInputModeManager.current
DroidDeckTheme {
Column(Modifier.verticalScroll(rememberScrollState())) {
ComponentDownloadsDrawerGroup(
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.R
@@ -15,9 +16,59 @@ import org.robolectric.annotation.Config
@Config(sdk = [28])
class ComponentsPageProfileTest {
@get:Rule val compose = createRobolectricComposeRule()
private val gameA = Library.SteamGame(42, "Game A", null, "internal")
private val gameB = Library.SteamGame(43, "Game B", null, "internal")
@Test fun gameProfilesCoexistWithTheDefaultComponentStack() {
val context = RuntimeEnvironment.getApplication()
show()
val stackHeading = context.getString(R.string.comp_this_proton).uppercase()
compose.onNodeWithText(stackHeading).assertExists()
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText("Game A").performClick()
compose.onNodeWithText(context.getString(R.string.comp_game_hint)).assertExists()
compose.onNodeWithText(stackHeading).assertDoesNotExist()
compose.onNodeWithText("Game A").performClick()
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText(stackHeading).assertExists()
}
@Test fun opensTheRequestedGameProfileAndAllowsSwitchingToDefault() {
val context = RuntimeEnvironment.getApplication()
show { gameB.profileKey }
compose.onNodeWithText("Game B").assertExists()
compose.onNodeWithText(context.getString(R.string.comp_game_hint)).assertExists()
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertDoesNotExist()
compose.onNodeWithText("Game B").performClick()
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists()
}
@Test fun aNewNavigationTargetReplacesThePreviousProfile() {
val context = RuntimeEnvironment.getApplication()
val target = mutableStateOf<String?>(gameA.profileKey)
show { target.value }
compose.onNodeWithText("Game A").assertExists()
compose.runOnIdle { target.value = gameB.profileKey }
compose.onNodeWithText("Game B").assertExists()
compose.onNodeWithText("Game A").assertDoesNotExist()
compose.runOnIdle { target.value = null }
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).assertExists()
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists()
}
@Test fun anUnavailableGameFallsBackToTheDefaultProfile() {
val context = RuntimeEnvironment.getApplication()
show { "missing-game" }
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).assertExists()
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists()
}
private fun show(initialGameKey: () -> String? = { null }) {
compose.setContent {
DroidDeckTheme {
ComponentsPage(
@@ -40,20 +91,11 @@ class ComponentsPageProfileTest {
onRefresh = {},
onImport = {},
onBack = {},
games = listOf(Library.SteamGame(42, "Game A", null, "internal")),
games = listOf(gameA, gameB),
initialGameKey = initialGameKey(),
requestInitialFocus = false,
)
}
}
val stackHeading = context.getString(R.string.comp_this_proton).uppercase()
compose.onNodeWithText(stackHeading).assertExists()
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText("Game A").performClick()
compose.onNodeWithText(context.getString(R.string.comp_game_hint)).assertExists()
compose.onNodeWithText(stackHeading).assertDoesNotExist()
compose.onNodeWithText("Game A").performClick()
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText(stackHeading).assertExists()
}
}
@@ -0,0 +1,101 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onLast
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class)
class DesktopUninstallTest {
@get:Rule val compose = createRobolectricComposeRule()
private var removals = 0
private var runtimeBlocked by mutableStateOf(false)
@After fun closeConfirmation() { Steps.drop() }
@Test fun uninstallIsAvailableOnTheDesktopPageAndRequiresConfirmation() {
show()
compose.onNodeWithText("Open desktop").assertIsDisplayed()
compose.onNodeWithText("Uninstall").assertIsDisplayed().performClick()
settle()
assertEquals(0, removals)
compose.onNodeWithText("Uninstall the desktop?").assertIsDisplayed()
compose.onAllNodesWithText("Uninstall").onLast().performClick()
assertEquals(1, removals)
}
@Test fun uninstallIsDisabledWhileRuntimeChangesAreBlocked() {
show(blocked = true)
compose.onNodeWithText("Uninstall").assertIsNotEnabled()
}
@Test fun aPartialDesktopStillOffersUninstall() {
show(installed = false)
compose.onNodeWithText("Uninstall").assertIsDisplayed()
}
@Test fun anUninstalledDesktopNoLongerOffersUninstall() {
show(installed = false, present = false)
compose.onNodeWithText("Uninstall").assertDoesNotExist()
}
@Test fun startingRuntimeWorkWhileConfirmingDisablesUninstall() {
show()
compose.onNodeWithText("Uninstall").performClick()
settle()
compose.runOnIdle { runtimeBlocked = true }
settle()
compose.onAllNodesWithText("Uninstall").onLast().assertIsNotEnabled()
assertEquals(0, removals)
}
private fun settle() = compose.mainClock.advanceTimeBy(2_000)
private fun show(installed: Boolean = true, blocked: Boolean = false, present: Boolean = true) {
runtimeBlocked = blocked
compose.mainClock.autoAdvance = false
compose.setContent {
DroidDeckTheme {
CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) {
FocusGlideHost {
Box(Modifier.fillMaxSize()) {
DesktopPage(FrontEndState(
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
desktopInstalled = installed, desktopPresent = present, runtimeActionsBlocked = runtimeBlocked,
offlineAccount = null, offline = false, frameGenLabel = "", romsDir = null, logsEnabled = false,
steamGames = emptyList(), emulators = emptyList(), running = null,
), FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {},
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {},
onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {},
onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = { removals++ },
), Modifier.fillMaxSize(), onSelect = {})
StepsLayer(Offset.Zero)
}
}
}
}
}
settle()
}
}
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.material3.Text
import androidx.compose.runtime.remember
import androidx.compose.ui.test.assertHasNoClickAction
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class DialogSemanticsTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun dialogTextNodesStaySeparateAndNonClickableInMergedSemanticsTree() {
var closed = 0
compose.setContent {
DroidDeckTheme {
val shown = remember { MutableTransitionState(true) }
AppDialog(shown = shown, close = { closed++ }, label = "testDialog", wide = false) {
Text("Dialog Title")
Text("Dialog Hint")
Text("Body Copy")
}
}
}
compose.onNodeWithText("Dialog Title").assertExists().assertHasNoClickAction()
compose.onNodeWithText("Dialog Hint").assertExists().assertHasNoClickAction()
compose.onNodeWithText("Body Copy").assertExists().assertHasNoClickAction()
compose.onNodeWithText("Dialog Title").performClick()
compose.onNodeWithText("Body Copy").performClick()
compose.waitForIdle()
assertEquals(0, closed)
}
}
@@ -0,0 +1,37 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.*
import org.junit.Test
class GestureActionsTest {
@Test fun categoryActionsAreAlphabeticalIncludingFilteredResults() {
val actions = listOf("Z", "C", "A", "B").map { GestureAction("key_$it", it, GestureActionGroup.LETTERS) } +
listOf("Right click", "Middle click", "Left click").map { GestureAction(it, it, GestureActionGroup.MOUSE) }
assertEquals(listOf("A", "B", "C", "Z"), filterGestureActions(actions, "", GestureActionGroup.LETTERS).map { it.title })
assertEquals(listOf("Left click", "Middle click", "Right click"), filterGestureActions(actions, "click", null).map { it.title })
}
@Test fun numberedFunctionKeysStayInNumericOrder() {
val actions = listOf(12, 2, 10, 1).map { GestureAction("key_F$it", "F$it", GestureActionGroup.FUNCTION) }
assertEquals(listOf("F1", "F2", "F10", "F12"), filterGestureActions(actions, "", null).map { it.title })
}
@Test fun actionGroupsKeepKeysAndMouseBindingsInTheirOwnCategories() {
assertEquals(GestureActionGroup.MOUSE, gestureActionGroup("middle_mouse_pan"))
assertEquals(GestureActionGroup.LETTERS, gestureActionGroup("key_F"))
assertEquals(GestureActionGroup.FUNCTION, gestureActionGroup("key_F12"))
assertEquals(GestureActionGroup.NUMPAD, gestureActionGroup("key_KP_ENTER"))
assertEquals(GestureActionGroup.MODIFIERS, gestureActionGroup("key_CTRL_R"))
}
@Test fun searchCombinesWordsAndCategoryWithoutChangingTheSelection() {
val actions = listOf(
GestureAction("key_ENTER", "Enter", GestureActionGroup.NAVIGATION),
GestureAction("key_KP_ENTER", "Numpad Enter", GestureActionGroup.NUMPAD),
GestureAction("key_KP_1", "Numpad 1", GestureActionGroup.NUMPAD),
)
assertEquals(listOf(actions[1]), filterGestureActions(actions, " ENTER numpad ", null))
assertEquals(listOf(actions[1]), filterGestureActions(actions, "enter", GestureActionGroup.NUMPAD))
assertTrue(filterGestureActions(actions, "not a key", null).isEmpty())
}
}
@@ -0,0 +1,89 @@
package com.droiddeck.launcher.ui
import android.app.Application
import android.view.View
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.test.*
import androidx.compose.ui.unit.Density
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.GesturePrefs
import com.droiddeck.launcher.input.TouchGestureConfig
import com.droiddeck.launcher.input.TouchscreenGestures.Gesture
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
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], application = Application::class, qualifiers = "w400dp-h850dp-port")
class GestureLocalizationTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
@Before fun clearPrefs() {
context.getSharedPreferences("touch_gestures", 0).edit().clear().commit()
}
@Test
@Config(qualifiers = "fr-rFR-w400dp-h850dp-port")
fun pageKeysAndModifierNamesUseLocalizedResources() {
compose.setContent {
DroidDeckTheme {
Column {
Text(gestureActionTitle("page_up_down"))
Text(gestureActionTitle("key_SHIFT_L"))
}
}
}
compose.onNodeWithText("Page précédente / Page suivante").assertIsDisplayed()
compose.onNodeWithText("Maj gauche").assertIsDisplayed()
}
@Test
@Config(qualifiers = "de-rDE-w400dp-h850dp-port")
fun longTranslationsKeepDefaultRestorationAndSaveUsable() {
GesturePrefs.save(context, "123", TouchGestureConfig(tapAction = "key_E"))
compose.setContent {
val density = LocalDensity.current
CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale = 1.5f)) {
DroidDeckTheme { TouchGestureDialog("123", {}, {}) }
}
}
val restore = compose.onNodeWithTag("gesture-inherit")
restore.assertIsDisplayed()
val scope = compose.onNodeWithTag("gesture-scope-game").fetchSemanticsNode().boundsInRoot
assertTrue("The restore action must have room for its translated label", restore.fetchSemanticsNode().boundsInRoot.width > scope.width)
restore.performClick()
compose.onNodeWithTag("gesture-save").assertIsDisplayed().performClick()
compose.runOnIdle { assertFalse(GesturePrefs.hasOverride(context, "123")) }
}
@Test
@Config(qualifiers = "ar-rEG-w400dp-h850dp-port")
fun arabicPickerSearchPreservesBindingsAndMirrorsFooter() {
assertEquals(View.LAYOUT_DIRECTION_RTL, context.resources.configuration.layoutDirection)
compose.setContent { DroidDeckTheme { TouchGestureDialog(null, {}, {}) } }
val save = compose.onNodeWithTag("gesture-save").fetchSemanticsNode().boundsInRoot
val cancel = compose.onNodeWithText(context.getString(R.string.gesture_cancel)).fetchSemanticsNode().boundsInRoot
assertTrue("Save $save and Cancel $cancel should follow the right-to-left layout", save.left < cancel.left)
compose.onNodeWithTag("gesture-choice-tap").performScrollTo().performClick()
compose.onNodeWithTag("gesture-action-search").performTextInput("هروب")
compose.onNodeWithTag("gesture-action-key_ESC").assertIsDisplayed().performClick()
compose.onNodeWithTag("gesture-save").performClick()
compose.runOnIdle { assertEquals("key_ESC", GesturePrefs.read(context).tapAction) }
}
@Test
@Config(qualifiers = "ja-rJP-w400dp-h850dp-port")
fun recognizedGestureFeedbackUsesTheActiveLanguage() {
compose.setContent { DroidDeckTheme { GestureFeedback(Gesture.TWO_FINGER_HOLD) } }
compose.onNodeWithText("2本指で長押し").assertIsDisplayed()
}
}
@@ -30,6 +30,21 @@ import org.robolectric.annotation.Config
class GlassesPanelTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun trackingOnlyDeviceHidesDisplayWritesButKeepsHeadTracking() {
show(supportsDisplayModeControl = false)
compose.onNodeWithTag("setting-glasses-hz").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-resolution-two_d").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-3d").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-3dof").assertExists()
}
@Test fun trackingOnlyDeviceHidesVrDisplayWrites() {
show(supportsDisplayModeControl = false, tab = GlassesTab.VR, steamVrRunning = true)
compose.onNodeWithTag("setting-glasses-resolution-vr").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-3d-hz").assertDoesNotExist()
compose.onNodeWithTag("setting-glasses-auto3d").assertDoesNotExist()
}
@Test fun flatResolutionMenuShowsPerEyeResolutionsBesideRefresh() {
show()
compose.onNodeWithTag("setting-glasses-hz").assertExists()
@@ -397,6 +412,7 @@ class GlassesPanelTest {
outputActive: Boolean = inSession,
controlAvailable: Boolean = true,
supportsScreen3dof: Boolean = true,
supportsDisplayModeControl: Boolean = true,
supportsSpatial: Boolean = false,
supports30Hz: Boolean = false,
sbs90: Boolean = true,
@@ -406,6 +422,7 @@ class GlassesPanelTest {
onRecenter: (() -> Unit)? = {},
) {
val state = GlassesState(present = true, connected = controlAvailable, controllable = true,
supportsDisplayModeControl = supportsDisplayModeControl,
displayId = Display.DEFAULT_DISPLAY + 1, width = if (stereo) 3840 else 1920, height = 1200,
model = "VITURE Luma Ultra", sbs = stereo, sbs90 = sbs90, supportsScreen3dof = supportsScreen3dof,
supports30Hz = supports30Hz, supportsSpatial = supportsSpatial, resolutions = listOf(
@@ -0,0 +1,44 @@
package com.droiddeck.launcher.ui
import android.content.res.Configuration
import android.os.LocaleList
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.assertCountEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.util.Locale
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class HeadingLocaleTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun headingsFollowTheAppLanguageAndRecomposeWhenItChanges() {
val appLocale = mutableStateOf(Locale.forLanguageTag("tr"))
compose.setContent {
val configuration = Configuration(LocalConfiguration.current).apply {
setLocales(LocaleList(appLocale.value))
}
CompositionLocalProvider(LocalConfiguration provides configuration) {
DroidDeckTheme {
Column {
Eyebrow("Bileşenler Iİıi")
SectionTitle("Bileşenler Iİıi", null)
}
}
}
}
compose.onAllNodesWithText("BİLEŞENLER IİIİ").assertCountEquals(2)
compose.runOnIdle { appLocale.value = Locale.ENGLISH }
compose.onAllNodesWithText("BILEŞENLER IİII").assertCountEquals(2)
compose.runOnIdle { appLocale.value = Locale.forLanguageTag("tr") }
compose.onAllNodesWithText("BİLEŞENLER IİIİ").assertCountEquals(2)
}
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
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 LaunchSettingsComponentsTest {
@get:Rule val compose = createRobolectricComposeRule()
private var openedGame: Library.SteamGame? = null
private var defaultOpens = 0
@Test fun gameComponentsCardPassesItsGameInsteadOfOpeningDefault() {
val game = Library.SteamGame(42, "Game A", null, "internal")
show(game)
clickComponents()
assertEquals(game, openedGame)
assertEquals(0, defaultOpens)
}
@Test fun addedGameComponentsCardPreservesItsUnsignedProfileKey() {
val game = Library.SteamGame(-42, "Added game", null, Library.ADDED)
show(game)
clickComponents()
assertEquals(game.profileKey, openedGame?.profileKey)
assertEquals("4294967254", openedGame?.profileKey)
assertEquals(0, defaultOpens)
}
@Test fun generalComponentsCardStillOpensDefault() {
show(null)
clickComponents()
assertNull(openedGame)
assertEquals(1, defaultOpens)
}
private fun clickComponents() {
compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.setup_card_components)).performClick()
compose.waitForIdle()
}
private fun show(game: Library.SteamGame?) {
compose.setContent {
DroidDeckTheme {
LaunchSettings(
FrontEndState(
installed = null, ready = false, available = null, busy = false, stage = "", percent = -1,
desktopInstalled = false, offlineAccount = null, offline = false, frameGenLabel = "",
romsDir = null, logsEnabled = false, steamGames = listOfNotNull(game),
emulators = emptyList(), running = null,
),
FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
onImportLossless = {}, onProtons = {}, onComponents = { defaultOpens++ },
onGameComponents = { openedGame = it }, onPerformance = {},
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
),
rememberMenuHost(),
game,
)
}
}
}
}
@@ -0,0 +1,97 @@
package com.droiddeck.launcher.ui
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.R
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
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], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class)
class ModeHeaderFocusTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun reenteringCompositionWithNonEmptyQueryDoesNotStealFocus() {
lateinit var root: View
var show by mutableStateOf(true)
var query by mutableStateOf("celeste")
compose.setContent {
DroidDeckTheme {
val view = LocalView.current
SideEffect { root = view.rootView }
if (show) {
ModeHeader(
title = "Library",
query = query,
onQuery = { query = it },
placeholder = "Search",
trailing = {},
)
}
}
}
compose.waitForIdle()
val initialField = editText(root)!!
compose.runOnIdle {
assertEquals("celeste", initialField.text.toString())
assertFalse("Pre-populated search field must not auto-focus on mount", initialField.isFocused)
show = false
}
compose.waitForIdle()
compose.runOnIdle { show = true }
compose.waitForIdle()
val remountedField = editText(root)!!
compose.runOnIdle {
assertEquals("celeste", remountedField.text.toString())
assertFalse("Remounted search field must not steal focus when scrolled back into view", remountedField.isFocused)
}
}
@Test fun clickingSearchIconFocusesField() {
lateinit var root: View
var query by mutableStateOf("")
compose.setContent {
DroidDeckTheme {
val view = LocalView.current
SideEffect { root = view.rootView }
ModeHeader(
title = "Library",
query = query,
onQuery = { query = it },
placeholder = "Search",
trailing = {},
)
}
}
val context = RuntimeEnvironment.getApplication()
compose.onNodeWithContentDescription(context.getString(R.string.stores_search_open)).performClick()
compose.waitForIdle()
val field = editText(root)!!
compose.runOnIdle {
assertTrue("Opening search via icon must focus the text field", field.isFocused)
}
}
private fun editText(view: View): EditText? {
if (view is EditText) return view
if (view is ViewGroup) for (i in 0 until view.childCount) {
editText(view.getChildAt(i))?.let { return it }
}
return null
}
}
@@ -0,0 +1,100 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.*
import androidx.compose.foundation.layout.size
import androidx.compose.ui.unit.dp
import org.junit.Rule
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class NavigationSelectionTest {
@get:Rule val compose = createRobolectricComposeRule()
@Before fun controlAnimationFrames() {
compose.mainClock.autoAdvance = false
}
@Test fun tabStripAnnouncesSelectionAndUpdatesAfterClick() {
val selected = mutableIntStateOf(0)
compose.setContent { DroidDeckTheme { TabStrip(listOf("First", "Second"), selected.intValue, { selected.intValue = it }) } }
verify("First", "Second")
}
@Test fun sheetChipsAnnounceSelectionAndUpdateAfterClick() {
val selected = mutableIntStateOf(0)
compose.setContent { DroidDeckTheme { SheetChips(listOf("First", "Second"), selected.intValue) { selected.intValue = it } } }
verify("First", "Second")
}
@Test fun segmentedTabsHaveOneTabRoleAndAnnounceTheirGroup() {
val selected = mutableIntStateOf(0)
compose.setContent { DroidDeckTheme { SegmentedTabs(listOf(0 to "First", 1 to "Second"), selected.intValue) { selected.intValue = it } } }
verify("First", "Second")
}
@Test fun sideRailExposesSelectionEvenWhenOnlyIconsAreVisible() {
val selected = mutableStateOf("steam")
Hops.railPreview = null
compose.setContent {
DroidDeckTheme {
SideRail(FrontEndState(
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "",
romsDir = null, logsEnabled = false, steamGames = emptyList(), emulators = emptyList(), running = null,
), selected.value, { selected.value = it }, {}, actions, Modifier.size(300.dp, 600.dp))
}
}
compose.mainClock.advanceTimeBy(1_000)
val steam = compose.onNodeWithTag("rail-steam")
val games = compose.onNodeWithTag("rail-games")
assertTab(steam, true)
assertTab(games, false)
games.performClick()
compose.mainClock.advanceTimeBy(1_000)
assertTab(steam, false)
assertTab(games, true)
assertGroup()
}
private fun verify(first: String, second: String) {
compose.mainClock.advanceTimeBy(1_000)
val a = compose.onNodeWithText(first)
val b = compose.onNodeWithText(second)
assertTab(a, true)
assertTab(b, false)
b.performClick()
compose.mainClock.advanceTimeBy(1_000)
assertTab(a, false)
assertTab(b, true)
assertGroup()
}
private fun assertTab(node: SemanticsNodeInteraction, selected: Boolean) {
node.assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab)).assertHasClickAction()
if (selected) node.assertIsSelected() else node.assertIsNotSelected()
}
private fun assertGroup() {
compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.SelectableGroup)).assertCountEquals(1)
}
private val actions = FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {},
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
)
}
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import org.junit.Assert.assertTrue
import org.junit.Test
class PrimaryButtonContrastTest {
@Test fun electricTextButtonsRemainReadableOnPageAndDialogSurfaces() {
val palette = Themes.byId(Themes.ELECTRIC)
for (background in listOf(palette.background, palette.surface)) {
assertTrue("Electric text button: ${contrast(palette.primary, background)}",
contrast(palette.primary, background) >= 4.5f)
}
}
@Test fun normalSizedPrimaryTextMeetsContrastAcrossEveryThemeGradient() {
for (palette in Themes.all) {
for (step in 0..100) {
val fraction = step / 100f
val start = palette.primary
val end = palette.primary2
val background = Color(
start.red + (end.red - start.red) * fraction,
start.green + (end.green - start.green) * fraction,
start.blue + (end.blue - start.blue) * fraction,
)
val ratio = contrast(palette.onPrimary, background)
assertTrue("${palette.id} gradient $step: $ratio", ratio >= 4.5f)
}
}
}
private fun contrast(a: Color, b: Color): Float {
val light = maxOf(a.luminance(), b.luminance())
val dark = minOf(a.luminance(), b.luminance())
return (light + 0.05f) / (dark + 0.05f)
}
}
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performSemanticsAction
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class PrimaryButtonFocusContrastTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun focusedPrimaryButtonDoesNotClaimAColorOverlayAboveItsLabel() {
lateinit var glide: FocusGlide
var clicks = 0
compose.setContent {
val view = LocalView.current
glide = remember(view) { FocusGlide(view) }
DroidDeckTheme(Themes.ELECTRIC) {
CompositionLocalProvider(LocalFocusGlide provides glide) {
PrimaryButton("Play") { clicks++ }
}
}
}
val button = compose.onNodeWithText("Play")
button.performSemanticsAction(SemanticsActions.RequestFocus)
button.assertIsFocused()
compose.runOnIdle { assertNull(glide.current) }
button.performClick()
compose.runOnIdle {
assertEquals(1, clicks)
assertNull(glide.current)
}
}
}
@@ -1,61 +0,0 @@
package com.droiddeck.launcher.ui
import android.app.Application
import android.content.Intent
import android.hardware.display.DisplayManager
import android.view.Display
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
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.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(application = Application::class, manifest = Config.NONE, sdk = [28, 33])
@LooperMode(LooperMode.Mode.PAUSED)
class SecondScreenActivityTest {
@Before fun setUp() {
SessionState.running = true
SessionState.stopRequested = false
}
@After fun tearDown() {
SessionState.running = false
SessionState.stopRequested = false
}
@Test fun removingControlsTaskDoesNotStopTheRunningSession() {
val service = Robolectric.buildService(SessionService::class.java).get()
service.onTaskRemoved(Intent(service, SecondScreenActivity::class.java))
assertTrue(SessionState.running)
assertFalse(SessionState.stopRequested)
}
@Test fun activityRestoredWithoutItsSessionOwnerFinishes() {
val activity = Robolectric.buildActivity(SecondScreenActivity::class.java).create().get()
assertTrue(activity.isFinishing)
assertTrue(SessionState.running)
}
@Test fun closingBeforeTheSecondaryActivityStartsRejectsTheLateLaunch() {
val session = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = session.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val controls = SecondScreenWindow(session, display, { _, _, _, _ -> }, { _, _ -> }, {}, {}, {}, {})
controls.show()
val intent = shadowOf(session).nextStartedActivity
controls.closeControls()
val activity = Robolectric.buildActivity(SecondScreenActivity::class.java, intent).create().get()
assertTrue(activity.isFinishing)
assertFalse(controls.isShowing)
assertTrue(SessionState.running)
}
}
@@ -0,0 +1,158 @@
package com.droiddeck.launcher.ui
import android.hardware.display.DisplayManager
import android.hardware.input.InputManager
import android.view.Display
import android.view.InputDevice
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.compose.ui.test.*
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.input.PadBridgeRoutingTest
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.shadows.InputDeviceBuilder
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w800dp-h600dp")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class SessionSecondScreenTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
private var previousMode = ""
private var previousDeckPad = false
@Before fun setUp() {
previousMode = SessionState.mode
previousDeckPad = SessionState.deckPad
SessionState.deckPad = false
}
@After fun tearDown() {
SessionState.mode = previousMode
SessionState.deckPad = previousDeckPad
}
@Test fun desktopMenuOffersTheExistingTrackpadAndTerminal() = checkModes(steam = false)
@Test fun steamMenuKeepsTheExistingTrackpadAndTerminal() = checkModes(steam = true)
@Test fun desktopWithoutASecondDisplayFallsBackToController() {
SessionState.mode = SessionService.MODE_DESKTOP
var page = SessionDrawerPage.SECOND_SCREEN
compose.setContent {
DroidDeckTheme {
SessionDrawer(true, page, false, { page = it }, actions(false, emptyList()))
}
}
compose.runOnIdle { assertEquals(SessionDrawerPage.CONTROLLER, page) }
compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertDoesNotExist()
}
@Test fun desktopTrackpadOmitsSteamShortcuts() = checkShortcuts(steam = false)
@Test fun steamTrackpadKeepsWorkingSteamShortcuts() = checkShortcuts(steam = true)
@Test
@Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
fun controllerBumpersReachTheSecondScreenInBothSessionModes() {
val device = InputDeviceBuilder.newBuilder().setId(42).setName("Second screen test pad")
.setDescriptor("second-screen-pad").setExternal(true).setSources(InputDevice.SOURCE_GAMEPAD).build()
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
for (mode in listOf(SessionService.MODE_DESKTOP, SessionService.MODE_STEAM)) {
SessionState.mode = mode
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
fun <T> state(name: String): MutableState<T> = ReflectionHelpers.getField(activity, "$name\$delegate")
state<Boolean>("drawerOpen").value = true
state<Boolean>("drawerControllerActive").value = true
state<List<SecondScreenDisplay>>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen"))
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN,
KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) {
assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0,
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)))
assertEquals(page, state<SessionDrawerPage>("drawerPage").value)
}
}
}
private fun checkModes(steam: Boolean) {
SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP
val selected = mutableListOf<SecondScreenMode>()
val displays = listOf(SecondScreenDisplay(1, "Bottom screen"))
compose.setContent {
DroidDeckTheme {
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it })
}
}
for (mode in listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)) {
compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick()
}
compose.onNodeWithText(context.getString(SecondScreenMode.DECK_CONTROLS.label)).assertDoesNotExist()
assertEquals(listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL), selected)
}
private fun checkShortcuts(steam: Boolean) {
SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
var menus = 0
var qams = 0
val panel = SecondScreenPresentation(activity, display, { _, _, _, _ -> }, { _, _ -> }, {},
{ menus++ }, { qams++ }, {})
try {
panel.create()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
val buttons = descendants(panel.window!!.decorView).filterIsInstance<Button>().toList()
assertTrue(buttons.any { it.text == context.getString(R.string.second_show_keyboard) })
val shortcuts = buttons.filter { it.text == "STEAM" || it.text == "…" }
if (steam) {
assertEquals(2, shortcuts.size)
shortcuts.forEach { it.performClick() }
assertEquals(1, menus)
assertEquals(1, qams)
} else {
assertTrue(shortcuts.isEmpty())
}
} finally {
panel.closeControls()
}
}
private fun descendants(view: View): Sequence<View> = sequence {
yield(view)
if (view is ViewGroup) for (index in 0 until view.childCount) yieldAll(descendants(view.getChildAt(index)))
}
private fun actions(steam: Boolean, displays: List<SecondScreenDisplay>, select: (SecondScreenMode) -> Unit = {}) =
DrawerActions(steam = steam, isHomeApp = false, androidApps = emptyList(), hudOn = false,
frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never",
onScreenButtonsVisible = false, suspendPolicy = "auto", backActionsInverted = false,
touchMode = "auto", touchAuto = "trackpad", fexPreset = "default",
secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1,
onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {},
onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {},
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {})
}
@@ -0,0 +1,95 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.R
import com.droiddeck.launcher.storage.ComponentUsage
import com.droiddeck.launcher.storage.StorageReport
import com.droiddeck.launcher.storage.StorageState
import org.junit.Assert.assertFalse
import org.junit.Rule
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 StorageComponentsBulkConfirmTest {
@get:Rule val compose = createRobolectricComposeRule()
private fun reportWith(components: List<ComponentUsage>) = StorageReport(
at = 1L,
total = 64L * 1024 * 1024 * 1024,
free = 32L * 1024 * 1024 * 1024,
buckets = emptyMap(),
prefixes = 0L,
shaders = 0L,
workshop = 0L,
flatpak = 0L,
games = emptyList(),
tools = emptyList(),
leftovers = emptyList(),
logs = emptyList(),
logBytes = 0L,
components = components,
flatpakApps = emptyList(),
flatpakRuntimes = 0L,
otherPrefixes = 0L,
leftoversChecked = true,
)
@Test fun bulkRemoveWithUnusedPackageShowsImportedWarningAndCancelKeepsIdle() {
val context = RuntimeEnvironment.getApplication()
val mb10 = 10L * 1024 * 1024
val report = reportWith(
listOf(
ComponentUsage(comp = "dxvk", version = "2.4.1", bytes = mb10, inUse = false, packageFile = "dxvk-2.4.1.wcp"),
ComponentUsage(comp = "vkd3d-proton", version = "2.13", bytes = mb10, inUse = false, protonId = "proton-9", protonName = "Proton 9"),
),
)
compose.setContent {
DroidDeckTheme {
Column {
ComponentsView(report = report, sessionRunning = false, onBack = {})
}
}
}
val removeUnusedBtn = context.getString(R.string.storage_remove_unused, "20 MB")
compose.onNodeWithText(removeUnusedBtn).performClick()
assertFalse(StorageState.cleaning)
val expectedWarning = context.getString(R.string.storage_component_confirm, "20 MB")
compose.onNodeWithText(expectedWarning, substring = true).assertExists()
compose.onNodeWithText("• DXVK 2.4.1 10 MB", substring = true).assertExists()
compose.onNodeWithText(context.getString(R.string.common_cancel)).performClick()
compose.onNodeWithText(expectedWarning, substring = true).assertDoesNotExist()
assertFalse(StorageState.cleaning)
}
@Test fun bulkRemoveWithOnlyUnusedOriginalsShowsOriginalConfirmText() {
val context = RuntimeEnvironment.getApplication()
val mb10 = 10L * 1024 * 1024
val report = reportWith(
listOf(
ComponentUsage(comp = "dxvk", version = "2.4", bytes = mb10, inUse = false, protonId = "proton-9", protonName = "Proton 9"),
),
)
compose.setContent {
DroidDeckTheme {
Column {
ComponentsView(report = report, sessionRunning = false, onBack = {})
}
}
}
val removeUnusedBtn = context.getString(R.string.storage_remove_unused, "10 MB")
compose.onNodeWithText(removeUnusedBtn).performClick()
assertFalse(StorageState.cleaning)
val expectedWarning = context.getString(R.string.storage_original_confirm, "10 MB")
compose.onNodeWithText(expectedWarning, substring = true).assertExists()
}
}
@@ -0,0 +1,135 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class ThemeColorsTest {
private val app get() = RuntimeEnvironment.getApplication()
@Before fun clear() {
app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
private fun near(expected: Int, actual: Int) {
for (shift in listOf(16, 8, 0)) assertTrue("${ThemeColors.hex(expected)} vs ${ThemeColors.hex(actual)}", Math.abs((expected shr shift and 0xFF) - (actual shr shift and 0xFF)) <= 1)
}
@Test fun hueSaturationAndBrightnessComeBackAsTheSameColour() {
for (argb in listOf(0xFF8B5CF6.toInt(), 0xFF22D3EE.toInt(), 0xFFFF0000.toInt(), 0xFF336699.toInt(), 0xFF808080.toInt(), 0xFF000000.toInt(), 0xFFFFFFFF.toInt())) {
val hsv = ThemeColors.toHsv(argb)
near(argb, ThemeColors.fromHsv(hsv.h, hsv.s, hsv.v))
}
}
@Test fun hexIsReadWithOrWithoutTheHashAndInShortForm() {
assertEquals(0xFF8B5CF6.toInt(), ThemeColors.parseHex("#8B5CF6"))
assertEquals(0xFF8B5CF6.toInt(), ThemeColors.parseHex("8b5cf6"))
assertEquals(0xFFFF00AA.toInt(), ThemeColors.parseHex(" #f0a "))
assertEquals("#8B5CF6", ThemeColors.hex(0xFF8B5CF6.toInt()))
for (bad in listOf("", "#", "#12", "#1234", "#1234567", "zzzzzz", "#12345g")) assertNull(bad, ThemeColors.parseHex(bad))
}
@Test fun aTooDarkColourIsLiftedAndABrightOneIsLeftAlone() {
val dark = ThemeColors.readable(0xFF050505.toInt())
assertTrue(Color(dark).luminance() >= 0.10f)
assertEquals(0xFF8B5CF6.toInt(), ThemeColors.readable(0xFF8B5CF6.toInt()))
}
@Test fun aDeepBlueThatBrightnessAloneCannotLiftIsMadePaler() {
assertTrue(Color(ThemeColors.readable(0xFF0000FF.toInt())).luminance() >= 0.10f)
assertTrue(Color(ThemeColors.readable(0xFF000000.toInt())).luminance() >= 0.10f)
}
@Test fun theTextColourSuitsTheWorseOfTheTwoGradientColours() {
assertEquals(Color(0xFF03111F), ThemeColors.inkFor(0xFFFFEB3B.toInt(), 0xFF3B4FA8.toInt()))
assertEquals(Color.White, ThemeColors.inkFor(0xFF3B4FA8.toInt(), 0xFF5B2FA8.toInt()))
assertEquals(Color(0xFF03111F), ThemeColors.inkFor(0xFFFFFFFF.toInt(), 0xFFFFEB3B.toInt()))
}
private fun contrast(a: Color, b: Color) = (maxOf(a.luminance(), b.luminance()) + 0.05f) / (minOf(a.luminance(), b.luminance()) + 0.05f)
@Test fun buttonTextIsReadableOnBothGradientColoursForAnyPair() {
val picks = listOf(0xFFFFEB3B, 0xFF1E3A8A, 0xFF0000FF, 0xFFFF0000, 0xFF00FF00, 0xFF808080, 0xFFFFFFFF, 0xFF000000, 0xFF8B5CF6, 0xFF22D3EE, 0xFFFF5722, 0xFF3F51B5)
for (a in picks) for (b in picks) {
val p = ThemeColors.palette(a.toInt(), b.toInt(), 0, 0)
val first = p.primary.toArgb()
val second = p.primary2.toArgb()
for (step in 0..100) {
val fraction = step / 100f
val color = Color(
0xFF000000.toInt() or
(channel(first, 16, second, fraction) shl 16) or
(channel(first, 8, second, fraction) shl 8) or
channel(first, 0, second, fraction),
)
assertTrue(
"${ThemeColors.hex(first)} ${ThemeColors.hex(second)} at $fraction",
contrast(p.onPrimary, color) >= 4.5f,
)
}
}
}
private fun channel(first: Int, shift: Int, second: Int, fraction: Float): Int {
val start = first shr shift and 0xFF
val end = second shr shift and 0xFF
return (start + (end - start) * fraction).toInt().coerceIn(0, 255)
}
@Test fun onlyTheStopThatFailsIsNudged() {
val p = ThemeColors.palette(0xFFFFEB3B.toInt(), 0xFF1E3A8A.toInt(), 0, 0)
assertEquals(Color(0xFFFFEB3B), p.primary)
assertTrue(p.primary2 != Color(0xFF1E3A8A))
assertEquals(Color(0xFF03111F), p.onPrimary)
}
@Test fun thePaletteKeepsTheTwoColoursAndStaysDarkAndReadable() {
val p = ThemeColors.palette(0xFF8B5CF6.toInt(), 0xFF22D3EE.toInt(), 0, 0)
assertEquals(p.primary, p.signal)
assertEquals(Color(0xFF22D3EE), p.primary2)
assertTrue(contrast(p.onPrimary, p.primary) >= 4.5f)
assertTrue(contrast(p.onPrimary, p.primary2) >= 4.5f)
assertTrue(p.background.luminance() < p.surface.luminance())
assertTrue(p.surface.luminance() < p.surfaceVariant.luminance())
assertTrue(p.background.luminance() < 0.02f)
assertTrue(p.onBackground.luminance() > 0.8f)
assertEquals(Color(0xFF03111F), ThemeColors.palette(0xFFFFEB3B.toInt(), 0xFFFFFFFF.toInt(), 0, 0).onPrimary)
assertEquals(Color.White, ThemeColors.palette(0xFF1E40AF.toInt(), 0xFF1D4ED8.toInt(), 0, 0).onPrimary)
}
@Test fun aGreyPrimaryGivesGreyNeutrals() {
val p = ThemeColors.palette(0xFFB0B0B0.toInt(), 0xFFFFFFFF.toInt(), 0, 0)
assertEquals(p.background.red, p.background.blue, 0.002f)
}
@Test fun theGradientThemeFollowsTheSavedColoursAndComesBackAfterARestart() {
Themes.setGradient(app, 0xFFFF5722.toInt(), 0xFF3F51B5.toInt())
val live = Themes.byId(Themes.GRADIENT)
assertEquals(0xFFFF5722.toInt() to 0xFF3F51B5.toInt(), SessionPrefs.gradientColors(app))
assertTrue(contrast(live.onPrimary, live.primary) >= 4.5f)
assertTrue(contrast(live.onPrimary, live.primary2) >= 4.5f)
SessionPrefs.setTheme(app, Themes.GRADIENT)
Themes.setGradient(app, Themes.DEFAULT_PRIMARY, Themes.DEFAULT_SECONDARY)
SessionPrefs.setGradientColors(app, 0xFF00FF00.toInt(), 0xFF0000FF.toInt())
assertEquals(Color(0xFF00FF00), Themes.current(app).primary)
}
@Test fun theGradientIsAChoiceInTheThemeList() {
assertTrue(Themes.all.any { it.id == Themes.GRADIENT })
assertEquals(Themes.GRAPHITE, Themes.byId("nonsense").id)
}
}
@@ -0,0 +1,112 @@
package com.droiddeck.launcher.ui
import android.app.Application
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.test.*
import com.droiddeck.launcher.input.GesturePrefs
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
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], application = Application::class, qualifiers = "w960dp-h640dp-land")
class TouchGestureDialogTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
@Before fun clearPrefs() {
context.getSharedPreferences("touch_gestures", 0).edit().clear().commit()
}
@Test fun searchSelectAndSaveAKeyboardAction() {
compose.setContent { DroidDeckTheme { TouchGestureDialog(null, {}, {}) } }
compose.onNodeWithTag("gesture-choice-tap").performScrollTo().performClick()
compose.onNodeWithTag("gesture-action-left_click").assertIsSelected()
compose.onNodeWithTag("gesture-action-search").performTextInput("numpad enter")
compose.onNodeWithTag("gesture-action-key_KP_ENTER").assertIsDisplayed().performClick()
compose.onNodeWithTag("gesture-save").performClick()
compose.runOnIdle { assertEquals("key_KP_ENTER", GesturePrefs.read(context).tapAction) }
}
@Test fun switchingTabsKeepsEditsAndLetsTwoFingerPanBeChanged() {
compose.setContent { DroidDeckTheme { TouchGestureDialog(null, {}, {}) } }
compose.onNodeWithTag("gesture-tab-1").performClick()
compose.onNodeWithTag("gesture-choice-two-drag").performScrollTo().performClick()
compose.onNodeWithTag("gesture-action-search").performTextInput("middle mouse pan")
compose.onNodeWithTag("gesture-action-middle_mouse_pan").performClick()
compose.onNodeWithTag("gesture-tab-3").performClick()
compose.onNodeWithTag("gesture-tab-1").performClick()
compose.onNodeWithText("Middle mouse pan").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("gesture-save").performClick()
compose.runOnIdle { assertEquals("middle_mouse_pan", GesturePrefs.read(context).twoFingerDragAction) }
}
@Test fun closingWithoutSavingDiscardsTheDraft() {
val open = mutableStateOf(true)
compose.setContent { DroidDeckTheme { if (open.value) TouchGestureDialog(null, { open.value = false }, {}) } }
chooseTap("Escape", "key_ESC")
compose.onNodeWithContentDescription("Close").performClick()
compose.runOnIdle { assertEquals("left_click", GesturePrefs.read(context).tapAction) }
}
@Test fun defaultsAndGameDraftsSurviveScopeChangesAndSaveTogether() {
compose.setContent { DroidDeckTheme { TouchGestureDialog("123", {}, {}) } }
chooseTap("numpad enter", "key_KP_ENTER")
compose.onNodeWithTag("gesture-scope-default").performClick()
chooseTap("Escape", "key_ESC")
compose.onNodeWithTag("gesture-scope-game").performClick()
compose.onNodeWithTag("gesture-choice-tap").performScrollTo()
compose.onNodeWithText("Numpad Enter").assertIsDisplayed()
compose.onNodeWithTag("gesture-save").performClick()
compose.runOnIdle {
assertEquals("key_ESC", GesturePrefs.read(context).tapAction)
assertEquals("key_KP_ENTER", GesturePrefs.read(context, "123").tapAction)
}
}
@Test fun aFocusChangeCannotRetargetAnOpenGameEditor() {
val game = mutableStateOf("123")
compose.setContent { DroidDeckTheme { TouchGestureDialog(game.value, {}, {}) } }
chooseTap("Escape", "key_ESC")
compose.runOnIdle {
game.value = "456"
Snapshot.sendApplyNotifications()
}
compose.onNodeWithTag("gesture-save").performClick()
compose.runOnIdle {
assertEquals("key_ESC", GesturePrefs.read(context, "123").tapAction)
assertFalse(GesturePrefs.hasOverride(context, "456"))
}
}
@Test
@Config(qualifiers = "w400dp-h850dp-port")
fun aNarrowWindowWithLargeTextKeepsNavigationAndSaveReachable() {
compose.setContent {
val density = LocalDensity.current
CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale = 1.5f)) {
DroidDeckTheme { TouchGestureDialog("123", {}, {}) }
}
}
compose.onNodeWithContentDescription("Close").assertIsDisplayed()
compose.onNodeWithTag("gesture-save").assertIsDisplayed()
compose.onNodeWithTag("gesture-tab-3").performScrollTo().performClick()
compose.onNodeWithText("Mouse movement").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("gesture-save").assertIsDisplayed()
}
private fun chooseTap(search: String, id: String) {
compose.onNodeWithTag("gesture-choice-tap").performScrollTo().performClick()
compose.onNodeWithTag("gesture-action-search").performTextInput(search)
compose.onNodeWithTag("gesture-action-$id").performClick()
}
}
@@ -0,0 +1,35 @@
package com.droiddeck.launcher.update
import android.content.pm.PackageInfo
import android.content.pm.Signature
import java.security.MessageDigest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
class SelfInstallerSignerTest {
private val cert = byteArrayOf(1, 2, 3, 4, 5)
private val expected = MessageDigest.getInstance("SHA-256").digest(cert).joinToString("") { "%02x".format(it) }
@Suppress("DEPRECATION")
private fun archive() = PackageInfo().apply { signatures = arrayOf(Signature(cert)) }
@Config(sdk = [28, 29])
@Test fun androidNineAndTenUseTheSignaturesWhenSigningInfoIsMissing() {
assertEquals(listOf(expected), SelfInstaller.archiveSignerDigests(archive()))
}
@Config(sdk = [26])
@Test fun androidEightIsCheckedToo() {
assertEquals(listOf(expected), SelfInstaller.archiveSignerDigests(archive()))
}
@Config(sdk = [33])
@Test fun anArchiveWithNoCertificatesHasNoDigests() {
assertTrue(SelfInstaller.archiveSignerDigests(PackageInfo()).isEmpty())
}
}