Merge branch 'main' into fix/gog-native-installer-extract

This commit is contained in:
Moroni Granja authored and GitHub committed 2026-10-21 07:56:53 -03:00
commit d006538f13
182 files changed
+9467 -698

No files matched your search

@@ -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)
}
}
@@ -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())
}
}
@@ -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")) {
@@ -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)
@@ -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,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
}
}
@@ -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)
}
}
@@ -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,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)
}
}
@@ -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")
@@ -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))
@@ -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 })
}
}
@@ -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"))
}
}
@@ -19,6 +19,55 @@ class XboxCatalogTest {
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() = JSONObject().put("productId", plan).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)))
@@ -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,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,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)
}
}
}