fix(install): recheck cancellation after sha256 and wire package resume cancel

This commit is contained in:
ovurrsl committed 2026-10-27 23:51:46 +03:00
commit 1b5cd6add9
399 files changed
+28516 -1432

No files matched your search

@@ -0,0 +1,268 @@
package com.droiddeck.launcher
import android.content.Intent
import android.os.Bundle
import android.os.Looper
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.ui.LaunchOrigin
import java.time.Duration
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class CompatLaunchTest {
private lateinit var activity: FrontEndActivity
private lateinit var protons: ProtonMenu
@Before fun setUp() {
installing(false)
LaunchOrigin.take()
activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
protons = ReflectionHelpers.getField(activity, "protons")
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
protons.protonBusyId = "droiddeck"
protons.protonProblem = null
protons.protonStage = "Downloading DroidDeck Proton"
protons.protonPercent = 37
setString("setPkgStage", null)
}
@After fun cleanUp() {
cancel()
protons.protonBusyId = null
protons.protonProblem = null
protons.protonStage = null
protons.protonPercent = -1
setString("setPkgStage", null)
installing(false)
LaunchOrigin.take()
}
@Test fun waitingShowsRealProgressThenStartsTheOriginalRequestOnce() {
activity.startActivity(request("steam://rungameid/42"))
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals(37, loading().percent)
assertTrue(loading().step.contains("37%"))
protons.protonStage = "Verifying download"
protons.protonPercent = -1
advance()
assertEquals("Verifying download", loading().step)
assertEquals(-1, loading().percent)
protons.protonBusyId = null
advance()
assertEquals("steam://rungameid/42", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
assertNull(waiting())
advance()
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun cancellingTheLaunchLeavesTheInstallRunningAndPreventsALateStart() {
activity.startActivity(request("first"))
cancel()
assertEquals("droiddeck", protons.protonBusyId)
protons.protonBusyId = null
advance()
assertNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun installationFailureStaysOnTheLoadingErrorWithoutStarting() {
activity.startActivity(request("first"))
protons.protonProblem = "Checksum verification failed"
protons.protonBusyId = null
advance()
assertTrue(loading().ended)
assertEquals("Checksum verification failed", loading().step)
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun repeatedLaunchesDoNotReplaceThePendingGame() {
activity.startActivity(request("first"))
activity.startActivity(request("second"))
protons.protonBusyId = null
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun anInstallOutsideTheLauncherUsesIndeterminateProgress() {
protons.protonBusyId = null
installing(true)
activity.startActivity(request("first"))
assertEquals(-1, loading().percent)
assertNull(shadowOf(activity).nextStartedActivity)
installing(false)
advance()
assertNotNull(shadowOf(activity).nextStartedActivity)
}
@Test fun finishingInTheBackgroundWaitsUntilTheLauncherIsVisible() {
activity.startActivity(request("first"))
ReflectionHelpers.setField(activity, "compatLaunchVisible", false)
protons.protonBusyId = null
advance()
assertNull(shadowOf(activity).nextStartedActivity)
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
advance()
assertNotNull(shadowOf(activity).nextStartedActivity)
}
@Test fun aRestoredCompletedRequestWaitsForResume() {
activity.startActivity(request("first"))
val saved = save()
cancel()
protons.protonBusyId = null
recreate(saved)
advance()
assertNull(shadowOf(activity).nextStartedActivity)
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
}
@Test fun overlappingPackageWorkKeepsTheOriginalLaunchUntilItFinishes() {
activity.startActivity(request("first"))
setString("setPkgStage", "Installing desktop")
ReflectionHelpers.callInstanceMethod<Void>(activity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 64))
protons.protonBusyId = null
advance()
assertNotNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals("Installing desktop", loading().step)
assertEquals(64, loading().percent)
setString("setPkgStage", null)
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
advance()
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun overlappingRuntimeWorkDoesNotDropThePendingLaunch() {
activity.startActivity(request("first"))
setString("setStage", "Updating runtime")
ReflectionHelpers.callInstanceMethod<Void>(activity, "setBusy", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
protons.protonBusyId = null
advance()
assertNotNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals("Updating runtime", loading().step)
ReflectionHelpers.callInstanceMethod<Void>(activity, "setBusy", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false))
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
}
@Test fun aPackageDownloadStillBlocksTheLaunchAfterRecreationAndReportsOldWorkerProgress() {
activity.startActivity(request("first"))
setString("setPkgStage", "Downloading AppImage")
ReflectionHelpers.callInstanceMethod<Void>(activity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 23))
val workerActivity = activity
val saved = save()
cancel()
recreate(saved)
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
protons.protonBusyId = null
advance()
assertNotNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals("Downloading AppImage", loading().step)
assertEquals(23, loading().percent)
android.os.Handler(Looper.getMainLooper()).post {
setString("setPkgStage", "Placing AppImage", workerActivity)
ReflectionHelpers.callInstanceMethod<Void>(workerActivity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 90))
}
advance()
assertEquals("Placing AppImage", loading().step)
assertEquals(90, loading().percent)
assertNull(shadowOf(activity).nextStartedActivity)
android.os.Handler(Looper.getMainLooper()).post { setString("setPkgStage", null, workerActivity) }
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
advance()
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun aFailedInstallAfterRecreationKeepsItsProgressAndError() = recreationFailure(false)
@Test fun aFailedInstallBeforeRestorationStillShowsItsError() = recreationFailure(true)
private fun recreationFailure(finishBeforeRestore: Boolean) {
val entered = CountDownLatch(1)
val finish = CountDownLatch(1)
protons.protonBusyId = null
protons.installer = { _, progress ->
progress("Verifying download", 64)
entered.countDown()
check(finish.await(5, TimeUnit.SECONDS))
"Checksum verification failed"
}
try {
protons.installProton("droiddeck")
assertTrue(entered.await(5, TimeUnit.SECONDS))
activity.startActivity(request("first"))
val saved = save()
cancel()
if (finishBeforeRestore) {
finish.countDown()
waitForInstall()
}
recreate(saved)
if (!finishBeforeRestore) {
advance()
assertEquals(64, loading().percent)
finish.countDown()
waitForInstall()
}
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
advance()
assertEquals("Checksum verification failed", loading().step)
assertTrue(loading().ended)
assertNull(shadowOf(activity).nextStartedActivity)
} finally {
finish.countDown()
waitForInstall()
}
}
private fun waitForInstall() {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (protons.protonBusyId != null && System.nanoTime() < deadline) {
shadowOf(Looper.getMainLooper()).idle()
Thread.sleep(10)
}
assertNull(protons.protonBusyId)
}
private fun save() = Bundle().also {
ReflectionHelpers.callInstanceMethod<Void>(activity, "saveCompatLaunch", ReflectionHelpers.ClassParameter.from(Bundle::class.java, it))
}
private fun recreate(saved: Bundle) {
activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
protons = ReflectionHelpers.getField(activity, "protons")
ReflectionHelpers.callInstanceMethod<Void>(activity, "restoreCompatLaunch", ReflectionHelpers.ClassParameter.from(Bundle::class.java, saved))
}
private fun setString(method: String, value: String?, target: FrontEndActivity = activity) {
ReflectionHelpers.callInstanceMethod<Void>(target, method, ReflectionHelpers.ClassParameter.from(String::class.java, value))
}
private fun request(url: String) = Intent(activity, SessionActivity::class.java).putExtra(SessionService.EXTRA_STEAM_URL, url)
private fun installing(on: Boolean) = ReflectionHelpers.setStaticField(ProtonExtras::class.java, "installInProgress", on)
private fun waiting(): Any? = ReflectionHelpers.callInstanceMethod(activity, "getCompatLaunch")
private fun loading(): LoadingState = ReflectionHelpers.getField(requireNotNull(waiting()), "loading")
private fun cancel() { ReflectionHelpers.callInstanceMethod<Void>(activity, "cancelCompatLaunch") }
private fun advance() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(250))
}
@@ -56,6 +56,10 @@ class ProtonMenuAutoTest {
.put("tag", "${tool.prefix}-11-12").put("at", System.currentTimeMillis()))
File(activity.filesDir, "proton-latest.json").writeText(latest.toString())
menu = ProtonMenu(activity, Handler(Looper.getMainLooper())) { idle }
menu.protonBusyId = null
menu.protonProblem = null
menu.protonStage = null
menu.protonPercent = -1
menu.installer = { tool, progress ->
progress("Installing ${tool.name}", 50)
install("${tool.prefix}-11-12")
@@ -64,6 +68,10 @@ class ProtonMenuAutoTest {
}
@After fun reset() {
menu.protonBusyId = null
menu.protonProblem = null
menu.protonStage = null
menu.protonPercent = -1
AutoComponents.online = online
AutoComponents.unfavourable = constrained
SessionState.running = false
@@ -88,7 +96,7 @@ class ProtonMenuAutoTest {
fail("Proton work did not finish")
}
@Test fun aCachedCheckUpdatesOnlyInstalledFamiliesAndKeepsOlderBuildsAndSelections() {
@Test fun aCachedCheckUpdatesOnlyInstalledFamiliesAndReplacesOlderDroidDeckProton() {
val older = install("DroidDeck-Proton-11-11.1")
val request = File(root, "root/.local/share/droiddeck-compat/request.json").apply {
parentFile!!.mkdirs()
@@ -97,8 +105,8 @@ class ProtonMenuAutoTest {
val before = request.readText()
assertFalse(ProtonExtras.checkLatest(activity))
menu.checkUpdates()
waitUntil { menu.protonRows.singleOrNull { it.id == "droiddeck" }?.installed == "DroidDeck-Proton-11-12" && menu.protonBusyId == null }
assertTrue(older.isDirectory)
waitUntil { menu.protonRows.singleOrNull { it.id == "droiddeck" }?.installed == "DroidDeck-Proton-11-12" && menu.protonBusyId == null && !older.exists() }
assertEquals(listOf("DroidDeck-Proton-11-12"), ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
assertEquals(before, request.readText())
assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "ge" }).isEmpty())
assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "cachyos" }).isEmpty())
@@ -128,7 +136,7 @@ class ProtonMenuAutoTest {
@Test fun aFailedUpdateDoesNotLoopOrBlockOtherInstalledFamilies() {
val ge = install("GE-Proton11-11")
val dd = install("DroidDeck-Proton-11-11.1")
install("DroidDeck-Proton-11-11.1")
menu.installer = { tool, _ ->
attempts.add(tool.id)
if (tool.id == "ge") throw IllegalStateException("download failed")
@@ -138,10 +146,10 @@ class ProtonMenuAutoTest {
menu.ensureAutoUpdates()
waitUntil { menu.protonBusyId == null }
menu.ensureAutoUpdates()
shadowOf(Looper.getMainLooper()).idle()
waitUntil { menu.protonBusyId == null }
assertEquals(listOf("ge", "droiddeck"), attempts)
assertTrue(ge.isDirectory)
assertTrue(dd.isDirectory)
assertEquals(listOf("DroidDeck-Proton-11-12"), ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
assertNull(menu.protonStage)
assertEquals(-1, menu.protonPercent)
}
@@ -184,6 +192,31 @@ class ProtonMenuAutoTest {
assertEquals("DroidDeck-Proton-11-12", ProtonExtras.installed(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
}
@Test fun droidDeckProtonIsInstalledWhenMissingUnlessTheUserRemovedIt() {
menu.installer = { tool, _ -> attempts.add(tool.id); install("${tool.prefix}-11-12"); null }
ProtonExtras.setDeclined(activity, true)
menu.ensureAutoUpdates()
assertNull(menu.protonBusyId)
assertTrue(attempts.isEmpty())
ProtonExtras.setDeclined(activity, false)
menu.ensureAutoUpdates()
waitUntil { menu.protonBusyId == null }
assertEquals(listOf("droiddeck"), attempts)
assertEquals("DroidDeck-Proton-11-12", ProtonExtras.installed(activity, ProtonExtras.tools.first { it.id == "droiddeck" }))
assertTrue(ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == "ge" }).isEmpty())
menu.removeProton("droiddeck")
waitUntil { menu.protonBusyId == null }
assertTrue(ProtonExtras.declined(activity))
menu.installer = { _, _ -> "failed" }
menu.installProton("droiddeck")
waitUntil { menu.protonBusyId == null }
assertTrue(ProtonExtras.declined(activity))
menu.installer = { tool, _ -> install("${tool.prefix}-11-12"); null }
menu.installProton("droiddeck")
waitUntil { menu.protonBusyId == null }
assertFalse(ProtonExtras.declined(activity))
}
@Test fun aPendingAnimatedLaunchPreventsAnAutomaticInstall() {
install("DroidDeck-Proton-11-11.1")
val launcher = Robolectric.buildActivity(FrontEndActivity::class.java).get()
@@ -9,6 +9,8 @@ import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.text.AnnotatedString
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.session.SessionState
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.After
@@ -179,6 +181,31 @@ class AgentSecurityTest {
assertEquals(listOf("TEST=old", "STICKY=1"), AgentEnv.beginSession(context))
}
@Test fun fastPathLibraryIsValidatedAndSelectedForOneSession() {
AgentAccess.setCommandsEnabled(context, true)
val source = File(AgentEnv.inbox(context).apply { mkdirs() }, "libblfastpath.so")
source.writeText("wrong architecture")
refused("INVALID_LIBRARY") { AgentEnv.override(context, source.name) }
val header = ByteArray(64)
byteArrayOf(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1).copyInto(header)
header[16] = 3
header[18] = 183.toByte()
source.writeBytes(header)
SessionState.running = true
try {
refused("SESSION_ACTIVE") { AgentEnv.override(context, source.name) }
} finally {
SessionState.running = false
}
val response = AgentEnv.override(context, source.name)
assertEquals(64, response.getString("sha256").length)
assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context))
AgentEnv.beginSession(context)
assertEquals("/opt/droiddeck-agent/bin/libblfastpath.so", AgentEnv.fastPathLibrary(context))
AgentEnv.endSession(context)
assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context))
}
@Test fun environmentValuesAreNotLogged() {
AgentAccess.setCommandsEnabled(context, true)
AgentEnv.set(context, listOf("CUSTOM=synthetic-private-value"), false)
@@ -0,0 +1,40 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
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 BackgroundAppLimitTest {
@Test fun theLimitIsActivityManagersCachedProcessCap() {
assertEquals("device_config get activity_manager max_cached_processes", BackgroundAppLimit.readCommand())
assertEquals("device_config put activity_manager max_cached_processes 4", BackgroundAppLimit.setCommand(4))
assertEquals("device_config put activity_manager max_cached_processes 0", BackgroundAppLimit.setCommand(0))
assertThrows(IllegalArgumentException::class.java) { BackgroundAppLimit.setCommand(-1) }
}
@Test fun whatWasThereIsWhatGoesBack() {
assertNull(BackgroundAppLimit.parse("null\n"))
assertNull(BackgroundAppLimit.parse(""))
assertEquals("16", BackgroundAppLimit.parse("16\n"))
assertEquals("device_config delete activity_manager max_cached_processes", BackgroundAppLimit.restoreCommand(null))
assertEquals("device_config put activity_manager max_cached_processes 16", BackgroundAppLimit.restoreCommand("16"))
}
@Test fun setupOffersOffAndDeveloperOptionsOwnLimits() {
val context = RuntimeEnvironment.getApplication()
assertEquals(BackgroundAppLimit.OFF, SessionPrefs.backgroundAppLimit(context))
for (limit in listOf(4, 1, 0, BackgroundAppLimit.OFF)) {
SessionPrefs.setBackgroundAppLimit(context, limit)
assertEquals(limit, SessionPrefs.backgroundAppLimit(context))
}
assertThrows(IllegalArgumentException::class.java) { SessionPrefs.setBackgroundAppLimit(context, 7) }
}
}
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.core
import java.net.InetSocketAddress
import java.net.Proxy
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class DownloadSourceProxyTest {
@Test fun hostAndPortBecomeAnHttpProxy() {
val proxy = DownloadSource.proxyOf("127.0.0.1:9910")
assertEquals(Proxy.Type.HTTP, proxy?.type())
val address = proxy?.address() as InetSocketAddress
assertEquals("127.0.0.1", address.hostString)
assertEquals(9910, address.port)
}
@Test fun missingOrInvalidPortIsIgnored() {
assertNull(DownloadSource.proxyOf(""))
assertNull(DownloadSource.proxyOf("127.0.0.1"))
assertNull(DownloadSource.proxyOf("127.0.0.1:"))
assertNull(DownloadSource.proxyOf("127.0.0.1:notaport"))
}
@Test fun normalizationAcceptsSchemeAndTrailingSlash() {
assertEquals("127.0.0.1:9910", DownloadSource.normalizeProxy(" http://127.0.0.1:9910/ "))
assertEquals("192.168.1.2:8080", DownloadSource.normalizeProxy("192.168.1.2:8080"))
}
@Test fun invalidInputDisablesTheProxy() {
assertEquals("", DownloadSource.normalizeProxy(""))
assertEquals("", DownloadSource.normalizeProxy("127.0.0.1"))
assertEquals("", DownloadSource.normalizeProxy("127.0.0.1:70000"))
assertEquals("", DownloadSource.normalizeProxy("http://127.0.0.1:notaport"))
}
}
@@ -0,0 +1,37 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
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.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class HostProcessTest {
@get:Rule val temporary = TemporaryFolder()
@Test fun appendsBothOutputStreamsToTheExistingLog() {
val windows = System.getProperty("os.name").orEmpty().startsWith("Windows")
val log = temporary.newFile("session.log").apply { writeText("guest output\n") }
val script = temporary.newFile(if (windows) "tracer.cmd" else "tracer.sh").apply {
writeText(if (windows) "@echo off\r\necho tracer stdout\r\necho tracer stderr>&2\r\n"
else "printf 'tracer stdout\\n'\nprintf 'tracer stderr\\n' >&2\n")
}
val finished = CountDownLatch(1)
var exitCode = -1
val shell = if (windows) "cmd.exe /c" else "/bin/sh"
HostProcess.start("$shell ${script.name}", null, temporary.root, {
exitCode = it
finished.countDown()
}, null, log)
assertTrue(finished.await(5, TimeUnit.SECONDS))
assertEquals(0, exitCode)
assertEquals(listOf("guest output", "tracer stdout", "tracer stderr"), log.readLines())
}
}
@@ -195,6 +195,7 @@ class LogRedactorTest {
"auth: login=maskeduser42&remember=1",
"accountName: maskeduser42",
"{\"username\": \"masked user 42\"}",
"[Clubs] {Main} Club membership subscription created: |accountId=maskeduser42",
)
for (line in lines) {
val out = LogRedactor.redactForShare(line)
@@ -0,0 +1,71 @@
package com.droiddeck.launcher.files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class StorageRootsTest {
@Test fun usbAndSdMountsAreFound() {
val mounts = """
/dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0
/dev/block/vold/public:8,1 /mnt/media_rw/A1B2-C3D4 vfat rw,dirsync 0 0
/mnt/media_rw/A1B2-C3D4 /storage/A1B2-C3D4 fuse rw,nosuid,nodev 0 0
/dev/block/vold/public:179,65 /mnt/media_rw/9C33-1A2B exfat rw,dirsync 0 0
/mnt/media_rw/9C33-1A2B /storage/9C33-1A2B fuse rw,nosuid,nodev 0 0
/dev/block/dm-5 /data ext4 rw,seclabel 0 0
""".trimIndent()
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
assertTrue(points.contains("/storage/A1B2-C3D4"))
assertTrue(points.contains("/storage/9C33-1A2B"))
assertTrue(points.contains("/mnt/media_rw/A1B2-C3D4"))
}
@Test fun voldLocationsCountWhateverTheFstypeIs() {
val mounts = """
/dev/block/sda1 /storage/0D19-CC0A fuse rw,nosuid,nodev 0 0
/dev/block/sda1 /mnt/media_rw/0D19-CC0A exfat rw,dirsync 0 0
""".trimIndent()
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
assertTrue(points.contains("/storage/0D19-CC0A"))
assertTrue(points.contains("/mnt/media_rw/0D19-CC0A"))
}
@Test fun usbMountsDirectlyUnderMntAreFound() {
val mounts = """
/dev/block/sda1 /mnt/usb_storage exfat rw,dirsync 0 0
tmpfs /mnt/media_rw tmpfs rw,seclabel 0 0
/dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0
""".trimIndent()
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
assertTrue(points.contains("/mnt/usb_storage"))
assertEquals(1, points.size)
}
@Test fun emulatedAndSystemMountsAreIgnored() {
val mounts = """
/dev/fuse /mnt/user/0/emulated fuse rw,nosuid,nodev 0 0
/mnt/media_rw/emulated /storage/emulated sdcardfs rw,nosuid,nodev 0 0
tmpfs /storage/self tmpfs rw,seclabel 0 0
overlay /system ext4 ro,seclabel 0 0
/dev/block/sda1 /data ext4 rw,seclabel 0 0
""".trimIndent()
assertEquals(emptyList<String>(), StorageRoots.parseExternalMounts(mounts).map { it.path })
}
@Test fun escapedSpacesAndNtfsAreHandled() {
val mounts = "/dev/block/vold/public:8,1 /mnt/media_rw/My\\040USB ntfs rw,dirsync 0 0\n" +
"/mnt/media_rw/My\\040USB /storage/My\\040USB fuse rw,nosuid,nodev 0 0\n"
val points = StorageRoots.parseExternalMounts(mounts).map { it.path }
assertTrue(points.contains("/mnt/media_rw/My USB"))
assertTrue(points.contains("/storage/My USB"))
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.frontend
import java.io.ByteArrayOutputStream
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.assertEquals
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
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class LibraryShortcutsLastPlayedTest {
@get:Rule val tmp = TemporaryFolder()
private fun steamRoot(): File = tmp.newFolder("Steam").also { root ->
File(root, "config").mkdirs()
File(root, "config/loginusers.vdf").writeText(
"\"users\"\n{\n\t\"76561198352563669\"\n\t{\n\t\t\"AccountName\"\t\t\"a\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
}
private class Vdf {
val out = ByteArrayOutputStream()
fun key(type: Int, k: String) { out.write(type); out.write(k.toByteArray()); out.write(0) }
fun map(k: String, body: Vdf.() -> Unit) { key(0, k); body(); out.write(8) }
fun str(k: String, v: String) { key(1, k); out.write(v.toByteArray()); out.write(0) }
fun int(k: String, v: Long) { key(2, k); out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v.toInt()).array()) }
}
@Test fun readsEachShortcutsLastPlayTimeByUnsignedAppId() {
val root = steamRoot()
val vdf = Vdf().apply {
map("shortcuts") {
map("0") { int("appid", 3388195926L); str("AppName", "Rayman 2"); int("LastPlayTime", 1792931476L) }
map("1") { int("appid", 2228102537L); str("AppName", "Do Not Disturb"); int("LastPlayTime", 0L) }
map("2") { int("appid", 1234L); str("appname", "Old"); int("lastplaytime", 1700000000L) }
}
out.write(8)
}
File(root, "userdata/392297941/config").apply { mkdirs() }.resolve("shortcuts.vdf").writeBytes(vdf.out.toByteArray())
assertEquals(mapOf(3388195926L to 1792931476L, 1234L to 1700000000L), Library.shortcutsLastPlayed(root))
}
@Test fun missingOrBrokenShortcutsGiveNothing() {
val root = steamRoot()
assertEquals(emptyMap<Long, Long>(), Library.shortcutsLastPlayed(root))
File(root, "userdata/392297941/config").apply { mkdirs() }.resolve("shortcuts.vdf").writeBytes(byteArrayOf(0, 's'.code.toByte()))
assertEquals(emptyMap<Long, Long>(), Library.shortcutsLastPlayed(root))
}
}
@@ -238,4 +238,17 @@ class SteamGridTest {
assertEquals(names.sorted(), names)
assertEquals(5L, AddedGameArt.chosen(dir, AddedGameArt.Slot.COVER)?.length())
}
@Test fun aChoiceSurvivesTheGridFolderBeingWipedAndIsPlacedAgain() {
File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs()
val picked = image("mine.png", 12)
SteamGameArt.choose(app, game(), AddedGameArt.Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))
assertEquals(12L, File(grid, "620p.png").length())
assertTrue(grid.deleteRecursively())
grid.mkdirs()
assertFalse(SteamGrid.sync(app, listOf(target())))
assertEquals(12L, SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.COVER)?.length())
assertEquals(12L, File(grid, "620p.png").length())
}
}
@@ -42,6 +42,51 @@ class WinComponentDetectorsTest {
assertEquals(emptyList<DependencyDetector.Recommendation>(), SteamRedists.detect(game, 1))
}
@Test fun skyrimGetsTheXactAudioItsInstallScriptRunsOnWindows() {
val steamapps = tmp.newFolder("steamapps")
val game = File(steamapps, "common/Skyrim Special Edition").apply { mkdirs() }
File(steamapps, "appmanifest_489830.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n")
val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
val found = WinCompSources.steamList(context, game, 489830, "Skyrim Special Edition", auto = true)
assertEquals(listOf("d3dx9", "xact_x64"), found.map { it.component })
assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM })
assertEquals(listOf("DirectX XACT audio (64-bit)", "Skyrim Special Edition", "489830"), found.last().args)
assertEquals(emptyList<String?>(), WinCompSources.steamList(context, game, 409710, "Other", auto = true).map { it.component })
}
@Test fun theGamesInstallScriptRedistsAreInstalledAsSteamWould() {
val steamapps = tmp.newFolder("steamapps")
val game = File(steamapps, "common/DiRT 3 Complete Edition").apply { mkdirs() }
File(steamapps, "appmanifest_321040.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228983\"\t\t\"228980\"\n\t}\n}\n")
File(game, "installscript.vdf").writeText(
"""
"InstallScript"
{
"Registry" { "HKEY_LOCAL_MACHINE\\Software\\Codemasters" { "string" { "Path" "%INSTALLDIR%" } } }
"Run Process"
{
"OpenAL"
{
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\321040"
"process 1" "%INSTALLDIR%\\_CommonRedist\\OpenAL\\2.0.7.0\\oalinst.exe"
"command 1" "/s"
}
"VC2010"
{
"process 1" "%INSTALLDIR%\\_CommonRedist\\vcredist\\2010\\vcredist_x86.exe"
}
}
}
""".trimIndent(),
)
assertEquals(listOf("oalinst", "vcredist2010"), SteamRedists.installScript(game).map { it.first })
val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
val found = WinCompSources.steamList(context, game, 321040, "DiRT 3 Complete Edition", auto = true)
assertEquals(listOf("vcredist2010_dll", "oalinst"), found.map { it.component })
assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM })
assertEquals(emptyList<Pair<String, String>>(), SteamRedists.installScript(File(steamapps, "missing")))
}
@Test fun thePrefixCountsOnlyWhatDroidDeckDidNotPutThere() {
val compat = tmp.newFolder("compatdata", "409710")
val pfx = File(compat, "pfx")
@@ -1,10 +1,13 @@
package com.droiddeck.launcher.glasses
import android.content.Context
import android.database.ContentObserver
import android.provider.Settings
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
@@ -36,10 +39,12 @@ class GlassesMirrorPacingTest {
val panel = Shadow.extract<ModeDisplay>(activity.display)
panel.supported = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f))
panel.current = panel.supported.last()
SessionState.fpsLimit = 0
activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@After fun cleanup() { SessionState.fpsLimit = 0 }
@After fun cleanup() {
activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun connectingChangingRateAndDisconnectingUpdatePhonePacingWithoutSavingPreferences() {
apply(connected, settings)
@@ -47,25 +52,33 @@ class GlassesMirrorPacingTest {
apply(connected, settings.copy(refreshHz = 90))
expect(2, 90f, 90)
apply(GlassesState(), settings)
expect(3, 120f, 0)
assertEquals(0, SessionState.fpsLimit)
expect(3, 120f, SessionPrefs.FPS_UNPACED)
}
@Test fun lowerSavedLimitSurvivesMirroringAndStalePhoneRefreshReports() {
SessionState.fpsLimit = 30
@Test fun retiredSavedLimitsDoNotCapThePhoneOrMirroredOutput() {
activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putInt("fpsLimit.steam", 30).putInt("fpsLimit.desktop", 40).commit()
apply(connected, settings)
expect(1, 60f, 30)
expect(1, 60f, 60)
apply(connected.copy(hz = 120f), settings)
expect(1, 60f, 30)
expect(1, 60f, 60)
apply(GlassesState(), settings)
expect(3, 120f, 30)
assertEquals(30, SessionState.fpsLimit)
expect(3, 120f, SessionPrefs.FPS_UNPACED)
}
@Test fun pacingFollowsThePanelWhenTheSystemKeepsALowerRateThanRequested() {
Shadow.extract<ModeDisplay>(activity.display).current = mode(2, 90f)
apply(GlassesState(), settings)
expect(3, 90f, 0)
expect(3, 90f, SessionPrefs.FPS_UNPACED)
}
@Test fun aHigherRefreshSettingChoosesTheFasterModeAgain() {
Settings.System.putFloat(activity.contentResolver, "peak_refresh_rate", 60f)
apply(GlassesState(), settings)
assertEquals(1, activity.window.attributes.preferredDisplayModeId)
Settings.System.putFloat(activity.contentResolver, "peak_refresh_rate", 120f)
ReflectionHelpers.getField<ContentObserver>(activity, "refreshSettingObserver").onChange(false)
assertEquals(3, activity.window.attributes.preferredDisplayModeId)
}
private fun apply(state: GlassesState, config: GlassesSettings) {
@@ -58,13 +58,6 @@ class GlassesRenderingTest {
assertEquals(0, GlassesRendering.mirrorRefreshLimit(settings, ultra, true))
}
@Test fun mirrorCapPreservesLowerLimitsAndRestoresTheRequestedLimitAfterDisconnect() {
for (requested in listOf(0, 30, 60, 90, 120)) {
assertEquals(if (requested == 30) 30 else 60, GlassesRendering.fpsLimit(requested, 60))
assertEquals(requested, GlassesRendering.fpsLimit(requested, 0))
}
}
private fun render(settings: GlassesSettings, state: GlassesState = ultra, steamVr: Boolean = false) =
GlassesRendering.cardboard(base, settings, state, outputActive = true, steamVrRunning = steamVr)
@@ -269,6 +269,17 @@ class GlassesUsbTest {
assertTrue(Glasses.isGlassesDisplayName("Rokid Max"))
}
@Test fun rokidMax2RequestsPermissionForItsOwnProductId() {
val max2 = device(0x2002, 0x04d2, "Rokid Max2")
manager.devices[max2.deviceName] = max2
refresh(ask = true)
assertEquals("Rokid Max2", state.value.model)
assertTrue(state.value.controllable)
assertEquals(listOf(max2), manager.requests)
assertTrue(Glasses.isGlassesDisplayName("Rokid Max 2"))
assertEquals(null, Glasses.deviceModel(device(0x2002, 0x04d2, "Generic HID")))
}
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"),
@@ -13,6 +13,10 @@ class RokidProtocolTest {
@Test fun identityRequiresRokidProductString() {
assertEquals("Rokid Max", RokidModel.model(0x04d2, 0x162f, "Rokid Max")?.name)
assertEquals("Rokid Air", RokidModel.model(0x04d2, 0x162f, "Rokid Air")?.name)
assertEquals("Rokid Max2", RokidModel.model(0x04d2, 0x2002, "Rokid Max2")?.name)
assertNull(RokidModel.model(0x04d2, 0x2002, "USB Keyboard"))
assertNull(RokidModel.model(0x04d2, 0x2002, null))
assertNull(RokidModel.model(0x1234, 0x2002, "Rokid Max2"))
assertNull(RokidModel.model(0x04d2, 0x162f, "USB Keyboard"))
assertNull(RokidModel.model(0x04d2, 0x162f, null))
assertNull(RokidModel.model(0x04d2, 0x1234, "Rokid Max"))
@@ -40,6 +44,21 @@ class RokidProtocolTest {
assertEquals(listOf(60), air.rates2d)
}
@Test fun max2UsesMaxModesAndParsesItsCapturedCombinedReport() {
val max2 = RokidModel.model(0x04d2, 0x2002, "Rokid Max2")!!
assertEquals(RokidModel.MODE_2D_120, max2.mode(120, false, null))
assertEquals(RokidModel.MODE_SBS_1080_60, max2.mode(60, true, GlassesResolution(1920, 1080)))
assertEquals(RokidModel.MODE_SBS_1200_90, max2.mode(90, true, null))
val packet = hex("119ceac6a47b000000542389bf2f430f41de9f6fc000967a38666144bbd0d4413b66661bc2cdcc2c4066e6e142000000ea70a2a47b0000000000006464000000")
val sample = RokidProtocol.Parser().parse(packet)!!
assertEquals(0x7ba4c6ea9cL, sample.timeNs)
assertEquals(8.954f, sample.accel.y, 0.001f)
assertEquals(100, sample.brightness)
val pose = ImuFusion().update(sample.timeNs, sample.accel, sample.gyro)
assertNotNull(pose)
assertTrue(pose!!.all { it.isFinite() })
}
@Test fun brightnessStepsRoundTripTheDevicePercent() {
assertEquals(8, RokidModel.brightnessStep(80))
assertEquals(10, RokidModel.brightnessStep(100))
@@ -0,0 +1,247 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.view.KeyEvent
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 = [34], manifest = Config.NONE)
class BackQamInputTest {
private val changes = mutableListOf<Boolean>()
private val taps = mutableListOf<Boolean>()
private val input = BackQamInput(changes::add, taps::add)
@Test fun singleTapWaitsForTheDoubleTapWindowWithoutPressingQam() {
send(KeyEvent.ACTION_DOWN)
advance(100)
send(KeyEvent.ACTION_UP)
advance(499)
assertTrue(taps.isEmpty())
advance(1)
assertEquals(listOf(false), taps)
assertTrue(changes.isEmpty())
}
@Test fun doubleTapProducesOnlyTheDoubleAction() {
repeat(2) {
send(KeyEvent.ACTION_DOWN)
advance(100)
send(KeyEvent.ACTION_UP)
advance(100)
}
advance(1000)
assertEquals(listOf(true), taps)
assertTrue(changes.isEmpty())
}
@Test fun theConfiguredWindowControlsSingleAndDoubleTaps() {
for (window in listOf(100L, 800L)) {
taps.clear()
val configured = BackQamInput(changes::add, taps::add, doubleTapMs = { window })
fun press(action: Int) = configured.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
advance(window - 1)
assertTrue(taps.isEmpty())
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
assertEquals(listOf(true), taps)
taps.clear()
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
advance(window - 1)
assertTrue(taps.isEmpty())
advance(1)
assertEquals(listOf(false), taps)
assertTrue(changes.isEmpty())
}
}
@Test fun aHoldStartsAt700msAndNeverProducesATap() {
assertTrue(send(KeyEvent.ACTION_DOWN))
advance(699)
assertTrue(changes.isEmpty())
advance(1)
for (repeat in 1..10) assertTrue(send(KeyEvent.ACTION_DOWN, repeat = repeat))
advance(4000)
assertEquals(listOf(true), changes)
assertTrue(send(KeyEvent.ACTION_UP))
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun releasingBetween500And700msStillProducesASingleTap() {
send(KeyEvent.ACTION_DOWN)
advance(600)
send(KeyEvent.ACTION_UP)
advance(500)
assertEquals(listOf(false), taps)
assertTrue(changes.isEmpty())
}
@Test fun holdingTheSecondPressCancelsTheFirstTap() {
send(KeyEvent.ACTION_DOWN)
send(KeyEvent.ACTION_UP)
advance(400)
send(KeyEvent.ACTION_DOWN)
advance(699)
assertTrue(taps.isEmpty())
advance(1)
assertEquals(listOf(true), changes)
send(KeyEvent.ACTION_UP)
advance(1000)
assertTrue(taps.isEmpty())
}
@Test fun otherButtonsAndSelectPassThroughWhileBackIsHeld() {
send(KeyEvent.ACTION_DOWN)
advance(700)
for (code in listOf(KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_BUTTON_SELECT)) {
for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) {
assertFalse(input.onKeyEvent(KeyEvent(action, code), true))
}
}
assertEquals(listOf(true), changes)
send(KeyEvent.ACTION_UP)
assertEquals(listOf(true, false), changes)
}
@Test fun aChordImmediatelyStartsAHoldAndSuppressesTheTap() {
send(KeyEvent.ACTION_DOWN)
advance(25)
input.onChordInput()
assertEquals(listOf(true), changes)
input.onChordInput()
send(KeyEvent.ACTION_UP)
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun aChordOnTheSecondPressCancelsBothTapActions() {
send(KeyEvent.ACTION_DOWN)
send(KeyEvent.ACTION_UP)
advance(100)
send(KeyEvent.ACTION_DOWN)
input.onChordInput()
send(KeyEvent.ACTION_UP)
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun controllerInputAfterBackIsReleasedOrCancelledCannotStartAHold() {
send(KeyEvent.ACTION_DOWN)
send(KeyEvent.ACTION_UP)
input.onChordInput()
advance(500)
assertEquals(listOf(false), taps)
send(KeyEvent.ACTION_DOWN)
input.cancel()
input.onChordInput()
advance(1000)
assertTrue(changes.isEmpty())
}
@Test fun anImmediateChordKeepsAllBackOwnersUntilTheLastRelease() {
send(KeyEvent.ACTION_DOWN, device = 4)
send(KeyEvent.ACTION_DOWN, device = 5)
input.onChordInput()
input.onDeviceRemoved(4)
assertEquals(listOf(true), changes)
send(KeyEvent.ACTION_UP, device = 5)
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun disabledRoutingPreservesBackNavigation() {
assertFalse(send(KeyEvent.ACTION_DOWN, enabled = false))
assertFalse(send(KeyEvent.ACTION_UP, enabled = false))
assertTrue(changes.isEmpty())
assertTrue(taps.isEmpty())
}
@Test fun losingFocusReleasesQamAndConsumesTheLateRelease() {
send(KeyEvent.ACTION_DOWN)
advance(700)
input.cancel()
input.cancel()
assertTrue(send(KeyEvent.ACTION_DOWN, repeat = 1, enabled = false))
assertTrue(send(KeyEvent.ACTION_UP, enabled = false))
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun cancellationBeforeTheThresholdPreventsBothHoldAndTap() {
send(KeyEvent.ACTION_DOWN)
advance(100)
input.cancel()
send(KeyEvent.ACTION_UP)
advance(1000)
assertTrue(changes.isEmpty())
assertTrue(taps.isEmpty())
}
@Test fun cancellationAlsoDiscardsAPendingSingleTap() {
send(KeyEvent.ACTION_DOWN)
send(KeyEvent.ACTION_UP)
input.cancel()
advance(1000)
assertTrue(taps.isEmpty())
}
@Test fun openingAnOverlayReleasesQamBeforeRoutingItsNextKey() {
send(KeyEvent.ACTION_DOWN)
advance(700)
assertFalse(input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_B), false))
assertTrue(send(KeyEvent.ACTION_UP, enabled = false))
assertEquals(listOf(true, false), changes)
}
@Test fun repeatsAfterCancellationCannotReassertQam() {
send(KeyEvent.ACTION_DOWN)
advance(700)
input.cancel()
assertTrue(send(KeyEvent.ACTION_DOWN, repeat = 1))
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(send(KeyEvent.ACTION_DOWN))
advance(700)
assertTrue(send(KeyEvent.ACTION_UP))
assertEquals(listOf(true, false, true, false), changes)
}
@Test fun cancelledReleaseNeverProducesATap() {
send(KeyEvent.ACTION_DOWN)
assertTrue(input.onKeyEvent(KeyEvent(0, 100, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK,
0, 0, 4, 0, KeyEvent.FLAG_CANCELED), true))
advance(1000)
assertTrue(changes.isEmpty())
assertTrue(taps.isEmpty())
}
@Test fun removingOneDeviceDoesNotReleaseAnotherDevicesHold() {
send(KeyEvent.ACTION_DOWN, device = 4)
send(KeyEvent.ACTION_DOWN, device = 5)
advance(700)
input.onDeviceRemoved(4)
assertEquals(listOf(true), changes)
send(KeyEvent.ACTION_UP, device = 5)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
private fun advance(millis: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis))
private fun send(action: Int, repeat: Int = 0, device: Int = 4, enabled: Boolean = true) =
input.onKeyEvent(KeyEvent(0, 100, action, KeyEvent.KEYCODE_BACK, repeat, 0, device, 0), enabled)
}
@@ -22,7 +22,7 @@ class DirectTouchHoldTest {
}
override fun onWheel(steps: Int) {}
override fun onLongPress() {}
}) { events += "cancel touch" }
}) { events += "cancel touch" }.also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
@Test fun holdReleasesRawTouchBeforeClickAndConsumesTheLift() {
assertFalse(touch(MotionEvent.ACTION_DOWN))
@@ -35,6 +35,25 @@ class DirectTouchHoldTest {
hold.cancel()
}
@Test fun stillHoldKeepsTheTouchWhenLongPressIsOff() {
hold.configure(TouchGestureConfig())
assertFalse(touch(MotionEvent.ACTION_DOWN))
advance(2000)
assertFalse(touch(MotionEvent.ACTION_MOVE))
assertFalse(touch(MotionEvent.ACTION_UP))
assertTrue(events.isEmpty())
}
@Test fun longPressFollowsTheConfiguredDelay() {
hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800))
touch(MotionEvent.ACTION_DOWN)
advance(700)
assertTrue(events.isEmpty())
advance(100)
assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events)
hold.cancel()
}
@Test fun tapDragSecondFingerAndCancellationDoNotRightClick() {
for (action in listOf(MotionEvent.ACTION_UP, MotionEvent.ACTION_MOVE,
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_CANCEL)) {
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.input
import android.app.Application
import android.view.KeyEvent
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28, 33], manifest = Config.NONE, application = Application::class)
class HomeGuideInputTest {
private val states = mutableListOf<Boolean>()
private var cancellations = 0
private val input = HomeGuideInput({ states.add(it) }, { cancellations++ })
private fun home(action: Int, device: Int = 10, repeat: Int = 0, down: Long = 10) =
KeyEvent(down, down + 100, action, KeyEvent.KEYCODE_HOME, repeat, 0, device, 102)
@Test fun guideIsHeldImmediatelyAndReleaseDoesNotDependOnAndroidDownTime() {
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true))
assertEquals(listOf(true), states)
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN, repeat = 1), true))
assertFalse(input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_X), true))
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP, down = 77), true))
assertEquals(listOf(true, false), states)
}
@Test fun genericLayoutMoveHomeHoldsGuideLikeHome() {
val down = KeyEvent(10, 110, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102)
val up = KeyEvent(10, 200, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102)
assertTrue(input.onKeyEvent(down, true))
assertTrue(input.onKeyEvent(up, true))
assertEquals(listOf(true, false), states)
}
@Test fun anUnownedHomePressKeepsAndroidBehaviorEvenIfSessionBecomesEligibleBeforeRelease() {
assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false))
assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), true))
assertTrue(states.isEmpty())
}
@Test fun focusLossReleasesGuideAndConsumesTheOwnedReleaseWithoutAnotherTap() {
input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true)
input.cancel()
assertEquals(1, cancellations)
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN, repeat = 2), false))
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), false))
assertEquals(listOf(true, false), states)
assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), false))
}
@Test fun disablingDuringAHoldReleasesItAndDoesNotStealTheNextAndroidHomePress() {
input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true)
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), false))
assertEquals(listOf(true, false), states)
assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false))
}
@Test fun guideStaysHeldUntilAllOwnersReleaseAndDisconnectCancelsTheLastOwner() {
input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true)
input.onKeyEvent(home(KeyEvent.ACTION_DOWN, device = 11), true)
input.onKeyEvent(home(KeyEvent.ACTION_UP), true)
assertEquals(listOf(true), states)
input.onDeviceRemoved(11)
assertEquals(listOf(true, false), states)
assertEquals(1, cancellations)
}
}
@@ -19,6 +19,7 @@ import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadows.InputDeviceBuilder
import org.robolectric.shadows.ShadowBuild
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
@@ -82,6 +83,34 @@ class JoyConPadTest {
assertEquals(0, RecordingWriter.grips)
}
@Test fun novaControllerUsesCForTheLeftPaddleAndZForTheRight() {
ShadowBuild.setModel("Retroid Pocket Nova")
for (product in listOf(0x3001, 0x3002)) {
val pad = controller(0x2022, product)
assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_C, KeyEvent.KEYCODE_BUTTON_Z)
bridge.onDeviceRemoved(pad.id)
}
}
@Test fun theSameControllerIdsKeepTheDefaultPaddlesOnOtherHandhelds() {
for (product in listOf(0x3001, 0x3002)) {
val pad = controller(0x2022, product)
for (model in listOf("Retroid Pocket 6", "Retroid Pocket 5", "AYN Thor")) {
ShadowBuild.setModel(model)
assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_Z, KeyEvent.KEYCODE_BUTTON_C)
}
bridge.onDeviceRemoved(pad.id)
}
}
@Test fun otherControllerIdsKeepTheDefaultPaddlesOnANova() {
ShadowBuild.setModel("Retroid Pocket Nova")
for (pad in listOf(controller(0x045e, 0x0b13), controller(0x2022, 0x3003), controller(0x2020, 0x3001))) {
assertPaddles(pad, KeyEvent.KEYCODE_BUTTON_Z, KeyEvent.KEYCODE_BUTTON_C)
bridge.onDeviceRemoved(pad.id)
}
}
@Test fun whenOneJoyConLeavesTheOtherKeepsThePlayer() {
pair()
assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH))
@@ -140,6 +169,17 @@ class JoyConPadTest {
private fun pad(slot: Int): PadState = RecordingWriter.pads[slot] ?: PadState()
private fun assertPaddles(device: InputDevice, leftCode: Int, rightCode: Int) {
assertTrue(bridge.onKeyEvent(key(device, leftCode, 0)))
assertEquals(DeckControls.L4, RecordingWriter.grips)
assertTrue(bridge.onKeyEvent(key(device, rightCode, 0)))
assertEquals(DeckControls.L4 or DeckControls.R4, RecordingWriter.grips)
assertTrue(bridge.onKeyEvent(key(device, leftCode, 0, KeyEvent.ACTION_UP)))
assertEquals(DeckControls.R4, RecordingWriter.grips)
assertTrue(bridge.onKeyEvent(key(device, rightCode, 0, KeyEvent.ACTION_UP)))
assertEquals(0, RecordingWriter.grips)
}
private fun press(device: InputDevice, code: Int, scanCode: Int): Boolean =
bridge.onKeyEvent(JoyCon.normalize(key(device, code, scanCode)))
@@ -162,10 +202,12 @@ class JoyConPadTest {
private var nextId = 60
private fun joyCon(product: Int, vararg axes: Int): InputDevice {
private fun joyCon(product: Int, vararg axes: Int): InputDevice = controller(NINTENDO, product, *axes)
private fun controller(vendor: Int, product: Int, vararg axes: Int): InputDevice {
val id = nextId++
val builder = InputDeviceBuilder.newBuilder().setId(id).setName("Joy-Con $id").setDescriptor("joycon-$id")
.setExternal(true).setVendorId(NINTENDO).setProductId(product)
.setExternal(true).setVendorId(vendor).setProductId(product)
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK or InputDevice.SOURCE_KEYBOARD)
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD))
@@ -236,6 +236,53 @@ class OnScreenControlsTest {
assertEquals(-1, field(control("ls"), "pressedBy"))
}
@Test fun trackpadFingerKeepsItsOwnStreamWhileAStickIsHeld() {
val forwarded = mutableListOf<Triple<Int, Int, Float>>()
view.onTouchMiss = { forwarded += Triple(it.actionMasked, it.getPointerId(0), it.getX(0)) }
touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f))
assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (540f to 400f), 9 to (600f to 200f)))
touch(MotionEvent.ACTION_MOVE, 7 to (500f to 400f), 9 to (650f to 200f))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (500f to 400f), 9 to (650f to 200f))
assertEquals(listOf(
Triple(MotionEvent.ACTION_DOWN, 9, 600f),
Triple(MotionEvent.ACTION_MOVE, 9, 650f),
Triple(MotionEvent.ACTION_UP, 9, 650f),
), forwarded)
assertEquals(7, field(control("ls"), "pressedBy"))
assertTrue(value(control("ls"), "kx") < 0f)
}
@Test fun stickPressedAfterTrackpadFingerReachesTheControls() {
val received = mutableListOf<Triple<Int, Int, Int>>()
val trackpad = View(context).apply {
setOnTouchListener { _, event -> received += Triple(event.actionMasked, event.pointerCount, event.getPointerId(0)); true }
}
val root = FrameLayout(context).apply {
isMotionEventSplittingEnabled = true
addView(trackpad, FrameLayout.LayoutParams(1200, 800))
addView(view, FrameLayout.LayoutParams(1200, 800))
measure(View.MeasureSpec.makeMeasureSpec(1200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY))
layout(0, 0, 1200, 800)
}
fun dispatch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>) {
val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray()
val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray()
val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
try { assertTrue(root.dispatchTouchEvent(event)) } finally { event.recycle() }
}
dispatch(MotionEvent.ACTION_DOWN, 0 to (600f to 200f))
dispatch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 0 to (600f to 200f), 1 to (540f to 400f))
dispatch(MotionEvent.ACTION_MOVE, 0 to (640f to 220f), 1 to (500f to 400f))
assertEquals(1, field(control("ls"), "pressedBy"))
assertTrue(value(control("ls"), "kx") < 0f)
dispatch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 0 to (640f to 220f), 1 to (500f to 400f))
dispatch(MotionEvent.ACTION_UP, 0 to (640f to 220f))
assertEquals(-1, field(control("ls"), "pressedBy"))
assertEquals(Triple(MotionEvent.ACTION_DOWN, 1, 0), received.first())
assertEquals(Triple(MotionEvent.ACTION_UP, 1, 0), received.last())
assertTrue(received.all { it.second == 1 && it.third == 0 })
}
@Test fun adaptiveActivationLeavesFivePixelsAroundButtonHitTargets() {
for (id in listOf("a", "rb")) {
val button = control(id)
@@ -0,0 +1,463 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import com.droiddeck.launcher.session.SessionState
import java.nio.file.Files
import java.time.Duration
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.util.ReflectionHelpers
import org.robolectric.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter", "com.droiddeck.launcher.wayland.WaylandCompositor"],
shadows = [JoyConPadTest.RecordingWriter::class, PadBridgeRoutingTest.RegisteredKeyEvent::class,
PadBridgeRoutingTest.RegisteredMotionEvent::class, SessionGestureRoutingTest.CompositorShadow::class])
class PadBridgeQamTest {
private val directory = Files.createTempDirectory("qam-pad").toFile()
private lateinit var bridge: PadBridge
@Before fun start() {
JoyConPadTest.RecordingWriter.pads.clear()
ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", FakeInputWriter.PAD_TYPE_DECK)
SessionState.deckPad = true
bridge = PadBridge(directory)
assertTrue(bridge.start())
}
@After fun stop() {
bridge.stop()
SessionState.deckPad = false
directory.deleteRecursively()
}
@Test fun onlyNativeQamControllersAcceptAHeldBack() {
for (type in listOf(-1, FakeInputWriter.PAD_TYPE_DECK, FakeInputWriter.PAD_TYPE_STEAM,
FakeInputWriter.PAD_TYPE_XBOX, FakeInputWriter.PAD_TYPE_DS4, FakeInputWriter.PAD_TYPE_DUALSENSE)) {
ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", type)
val supported = type <= FakeInputWriter.PAD_TYPE_STEAM
assertEquals(supported, bridge.canHoldQam())
bridge.setBackQamPressed(true)
bridge.applyExternal({}, false)
assertEquals(supported, pad().isDown(PadState.QAM))
bridge.setBackQamPressed(false)
advanceTime()
}
SessionState.deckPad = false
assertFalse(bridge.canHoldQam())
}
@Test fun qamAndOtherButtonsShareAReportUntilBackIsReleased() {
bridge.setBackQamPressed(true)
advanceTime()
bridge.applyExternal({ it.press(PadState.X, true); it.press(PadState.SELECT, true) }, true)
advanceTime()
assertTrue(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
assertTrue(pad().isDown(PadState.SELECT))
bridge.setBackQamPressed(false)
advanceTime()
assertFalse(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
assertTrue(pad().isDown(PadState.SELECT))
}
@Test fun touchQamAndBackHaveIndependentReleases() {
bridge.setBackQamPressed(true)
bridge.setSystemButtons(false, true)
bridge.setBackQamPressed(false)
assertTrue(pad().isDown(PadState.QAM))
bridge.setBackQamPressed(true)
bridge.setSystemButtons(false, false)
assertTrue(pad().isDown(PadState.QAM))
bridge.setBackQamPressed(false)
advanceTime()
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun aTimedQamTapCannotReleaseAHeldBack() {
bridge.triggerQam()
bridge.setBackQamPressed(true)
advanceTime()
assertTrue(pad().isDown(PadState.QAM))
bridge.setBackQamPressed(false)
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun releasingAllOrStoppingClearsTheHold() {
bridge.setBackQamPressed(true)
bridge.releaseAll()
assertFalse(pad().isDown(PadState.QAM))
bridge.setBackQamPressed(true)
bridge.stop()
bridge.start()
bridge.applyExternal({}, false)
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun disablingTheBuiltinPadClearsAndRejectsTheHold() {
bridge.setBackQamPressed(true)
bridge.setBuiltinPad(false)
assertFalse(bridge.canHoldQam())
assertFalse(pad().isDown(PadState.QAM))
bridge.setBackQamPressed(true)
bridge.setBuiltinPad(true)
bridge.applyExternal({}, false)
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun aQuickPartnerPressReachesSteamWithQamAndReleasesIndependently() {
val device = controller()
val taps = mutableListOf<Boolean>()
val input = BackQamInput(bridge::setBackQamPressed, taps::add)
bridge.setOnChordInput {
assertFalse(pad().isDown(PadState.X))
input.onChordInput()
}
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), true)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(25))
assertTrue(bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X)))
assertTrue(pad().isDown(PadState.QAM))
assertFalse(pad().isDown(PadState.X))
advance(79)
assertFalse(pad().isDown(PadState.X))
advance(1)
assertTrue(pad().isDown(PadState.X))
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK), true)
assertFalse(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP))
advance(80)
assertFalse(pad().isDown(PadState.X))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
assertTrue(taps.isEmpty())
}
@Test fun onlyFreshAcceptedPrimaryControllerPressesPromoteAChord() {
val device = controller()
val second = controller(11)
val promoted = mutableListOf<Boolean>()
bridge.setOnChordInput { promoted.add(true) }
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, repeat = 1))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_A))
bridge.onKeyEvent(key(second, KeyEvent.KEYCODE_BUTTON_X))
bridge.setExcluded { it == device.id }
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X))
assertTrue(promoted.isEmpty())
bridge.setExcluded { false }
for (code in listOf(KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_BUTTON_L2)) {
bridge.onKeyEvent(key(device, code))
}
assertEquals(3, promoted.size)
}
@Test fun aQuickChordKeepsItsPressAndReleaseAfterTheModifierLead() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.press(PadState.X, true) }, true)
advance(20)
bridge.applyExternal({ it.press(PadState.X, false) }, true)
bridge.setBackQamPressed(false)
assertTrue(pad().isDown(PadState.QAM))
assertFalse(pad().isDown(PadState.X))
advance(60)
assertTrue(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
advance(19)
assertTrue(pad().isDown(PadState.X))
advance(1)
assertFalse(pad().isDown(PadState.X))
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun cancellationDiscardsQueuedPartnersAndTheirReleases() {
val input = BackQamInput(bridge::setBackQamPressed, {}, onCancel = bridge::cancelBackQam)
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), true)
input.onChordInput()
bridge.applyExternal({ it.press(PadState.LB, true) }, true)
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK), true)
input.cancel()
advance(1000)
assertFalse(pad().isDown(PadState.LB))
assertFalse(pad().isDown(PadState.QAM))
bridge.applyExternal({ it.press(PadState.X, true) }, true)
input.cancel()
assertTrue(pad().isDown(PadState.X))
}
@Test fun aSettledHoldDoesNotDelayLaterPartnerInput() {
bridge.setBackQamPressed(true)
advance(80)
bridge.applyExternal({ it.press(PadState.LB, true) }, true)
assertTrue(pad().isDown(PadState.LB))
bridge.setBackQamPressed(false)
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun disconnectingThePartnerControllerDiscardsItsQueuedPress() {
val device = controller()
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1))
advance(20)
bridge.onDeviceRemoved(device.id)
assertTrue(pad().isDown(PadState.QAM))
assertFalse(pad().isDown(PadState.LB))
advance(60)
assertFalse(pad().isDown(PadState.LB))
advance(1000)
assertFalse(pad().isDown(PadState.LB))
assertTrue(pad().isDown(PadState.QAM))
}
@Test fun disconnectingThePartnerControllerImmediatelyReleasesADeliveredPress() {
val device = controller()
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1))
advance(80)
assertTrue(pad().isDown(PadState.LB))
bridge.onDeviceRemoved(device.id)
assertFalse(pad().isDown(PadState.LB))
assertTrue(pad().isDown(PadState.QAM))
advance(1000)
assertFalse(pad().isDown(PadState.LB))
}
@Test fun removingAnotherPlayerDoesNotDiscardThePrimaryPlayersQueuedChord() {
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.ACTION_UP))
val other = controller(11)
bridge.onKeyEvent(key(other, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP))
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1))
bridge.onDeviceRemoved(other.id)
advance(80)
assertTrue(pad().isDown(PadState.LB))
assertTrue(pad().isDown(PadState.QAM))
}
@Test fun pairingOnAnIgnoredRailKeyImmediatelyReleasesDeliveredButtonsAndDropsQueuedOnes() {
val left = controller(product = 0x2006)
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_L1))
advance(80)
assertTrue(pad().isDown(PadState.LB))
bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_X))
val right = controller(11, product = 0x2007)
assertTrue(bridge.onKeyEvent(key(right, KeyEvent.KEYCODE_BUTTON_L1, scan = 0x136)))
assertFalse(pad().isDown(PadState.LB))
assertFalse(pad().isDown(PadState.X))
assertTrue(pad().isDown(PadState.QAM))
advance(1000)
assertFalse(pad().isDown(PadState.LB))
assertFalse(pad().isDown(PadState.X))
}
@Test fun queuedReportsUseTheLiveStickAndStopItImmediatelyOnBackRelease() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.press(PadState.X, true); it.leftY = -1f }, true)
advance(20)
bridge.applyExternal({ it.leftY = -0.25f }, true)
advance(60)
assertEquals(-0.25f, pad().leftY)
bridge.setBackQamPressed(false)
assertEquals(0f, pad().leftY)
advance(1000)
assertEquals(0f, pad().leftY)
bridge.applyExternal({ it.leftY = 0f }, true)
bridge.applyExternal({ it.leftY = 0.75f }, true)
assertEquals(0.75f, pad().leftY)
}
@Test fun releasingBackDuringTheLeadNeverReplaysAnOldStickMovement() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.leftY = -1f }, true)
advance(20)
bridge.setBackQamPressed(false)
advance(1000)
assertEquals(0f, pad().leftY)
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun theInitialPartnerKeepsItsDurationWhenReleasedAfterTheLead() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.press(PadState.X, true) }, true)
advance(100)
bridge.applyExternal({ it.press(PadState.X, false) }, true)
assertTrue(pad().isDown(PadState.X))
advance(79)
assertTrue(pad().isDown(PadState.X))
advance(1)
assertFalse(pad().isDown(PadState.X))
}
@Test fun deliberateStickTriggerAndHatMotionPromoteChordsButNeutralAndDriftDoNot() {
val device = controller()
val promoted = mutableListOf<Boolean>()
bridge.setOnChordInput { promoted.add(true) }
for ((axis, value) in listOf(MotionEvent.AXIS_X to 0f, MotionEvent.AXIS_X to 0.1f,
MotionEvent.AXIS_LTRIGGER to 0f, MotionEvent.AXIS_HAT_Y to 0f)) motion(device, axis, value)
assertTrue(promoted.isEmpty())
for ((axis, value) in listOf(MotionEvent.AXIS_X to -0.15f, MotionEvent.AXIS_LTRIGGER to 0.75f,
MotionEvent.AXIS_HAT_Y to -1f)) motion(device, axis, value)
assertEquals(3, promoted.size)
}
private fun controller(id: Int = 10, product: Int = 0): InputDevice {
val builder = InputDeviceBuilder.newBuilder().setId(id).setName("QAM pad $id")
.setVendorId(if (product == 0) 0 else 0x057e).setProductId(product)
.setDescriptor("qam-pad-$id").setExternal(true).setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)
for (axis in listOf(MotionEvent.AXIS_X, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_HAT_Y)) {
builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, 0f, 1f, 0f, 0f, 0f)
}
return builder.build().also {
shadowOf(RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)).addInputDevice(it)
bridge.applyExternal({}, false)
}
}
@Test fun homeGuidePrecedesEarlyPartnerInputAndDoesNotGenerateABareButton() {
bridge.setHomeGuidePressed(true)
assertTrue(pad().isDown(PadState.GUIDE))
bridge.applyExternal({ it.press(PadState.X, true) }, true)
assertFalse(pad().isDown(PadState.X))
advance(80)
assertTrue(pad().isDown(PadState.GUIDE))
assertTrue(pad().isDown(PadState.X))
bridge.applyExternal({ it.press(PadState.X, false) }, true)
bridge.setHomeGuidePressed(false)
advance(1000)
assertFalse(pad().isDown(PadState.GUIDE))
assertFalse(pad().isDown(PadState.X))
}
@Test fun homeGuideHoldsOnThePrimaryPlayerWithoutABuiltinPad() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
bridge.setHomeGuidePressed(true)
assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
bridge.setHomeGuidePressed(false)
assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun homeGuideAndControllerGuideReleaseIndependentlyOnThePrimaryPlayer() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE))
bridge.setHomeGuidePressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP))
assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE))
bridge.setHomeGuidePressed(false)
assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP))
assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun removingThePrimaryPlayerForgetsItsHomeGuide() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP))
bridge.setHomeGuidePressed(true)
bridge.onDeviceRemoved(device.id)
JoyConPadTest.RecordingWriter.pads.remove(1)
bridge.cancelHomeGuide()
bridge.setHomeGuidePressed(false)
assertNull(JoyConPadTest.RecordingWriter.pads[1])
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun cancellingHomeGuideOnAPlayerSlotKeepsItsHeldControls() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A))
bridge.setHomeGuidePressed(true)
bridge.cancelHomeGuide()
val pad = requireNotNull(JoyConPadTest.RecordingWriter.pads[1])
assertFalse(pad.isDown(PadState.GUIDE))
assertTrue(pad.isDown(PadState.A))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun cancellingHomeDiscardsQueuedPartnersAndReleasesGuideImmediately() {
bridge.setHomeGuidePressed(true)
bridge.applyExternal({ it.press(PadState.LB, true); it.leftY = -1f }, true)
bridge.cancelHomeGuide()
advance(1000)
assertFalse(pad().isDown(PadState.GUIDE))
assertFalse(pad().isDown(PadState.LB))
assertEquals(0f, pad().leftY)
}
@Test fun homeAndTouchGuideHaveIndependentReleases() {
bridge.setHomeGuidePressed(true)
bridge.setSystemButtons(true, false)
bridge.setHomeGuidePressed(false)
advance(1000)
assertTrue(pad().isDown(PadState.GUIDE))
bridge.setSystemButtons(false, false)
advance(1000)
assertFalse(pad().isDown(PadState.GUIDE))
}
@Test fun releasingHomeStopsHeldAxesFromBecomingNavigation() {
bridge.setHomeGuidePressed(true)
bridge.applyExternal({ it.leftY = -1f }, true)
advance(80)
assertEquals(-1f, pad().leftY)
bridge.setHomeGuidePressed(false)
advance(1000)
assertEquals(0f, pad().leftY)
assertFalse(pad().isDown(PadState.GUIDE))
}
private fun key(device: InputDevice, code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0, scan: Int = 0) =
KeyEvent(0L, 0L, action, code, repeat, 0, device.id, scan, 0, InputDevice.SOURCE_GAMEPAD)
private fun motion(device: InputDevice, axis: Int, value: Float) {
val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1,
arrayOf(MotionEvent.PointerProperties().apply { id = 0 }),
arrayOf(MotionEvent.PointerCoords().apply { setAxisValue(axis, value) }),
0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0)
try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() }
}
private fun pad() = requireNotNull(JoyConPadTest.RecordingWriter.pads[0])
private fun advanceTime() {
val handler = ReflectionHelpers.getStaticField<Handler>(PadBridge::class.java, "chordHandler")
shadowOf(handler.looper).idleFor(Duration.ofSeconds(2))
advance(2000)
}
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
}
@@ -84,6 +84,20 @@ class PadBridgeRoutingTest {
assertFalse(PadBridge.anyControllerConnected())
}
@Test fun homeShortcutsIgnoreHomeFromSystemKeys() {
val gpio = device(InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, name = "gpio-keys")
val pad = device(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
assertFalse(PadBridge.isControllerKeyEvent(key(gpio, KeyEvent.KEYCODE_HOME, KeyEvent.ACTION_DOWN)))
assertTrue(PadBridge.isControllerKeyEvent(key(pad, KeyEvent.KEYCODE_HOME, KeyEvent.ACTION_DOWN)))
val owner = Any()
HomeButtonShortcuts.attach(owner, { true }, { fail("system Home must not press Guide") }, {})
try {
for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) {
assertFalse(HomeButtonShortcuts.onKeyEvent(RuntimeEnvironment.getApplication(), key(gpio, KeyEvent.KEYCODE_HOME, action)))
}
} finally { HomeButtonShortcuts.detach(owner) }
}
@Test fun keyAndMotionOwnershipDoesNotFollowEverySourceOnTheDevice() {
val keyboard = device(InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_ALPHABETIC)
val composite = device(COMPOSITE, InputDevice.KEYBOARD_TYPE_ALPHABETIC)
@@ -0,0 +1,124 @@
package com.droiddeck.launcher.input
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ScreenKeysTest {
private val context = RuntimeEnvironment.getApplication()
@Before fun clearKeys() {
ControllerPrefs.setScreenKeys(context, emptyList())
}
@Test fun missesAreForwardedAsTheirOwnTouchStreamWhileAKeyIsHeld() {
val sent = mutableListOf<Pair<Int, Boolean>>()
val keys = ScreenKeys(context) { code, down -> sent += code to down }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_W))
val forwarded = mutableListOf<Pair<Int, Int>>()
keys.onTouchMiss = { forwarded += it.actionMasked to it.getPointerId(0) }
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
send(keys, MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(300f, 900f), listOf(372f, 550f))
send(keys, MotionEvent.ACTION_MOVE, listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f))
send(keys, MotionEvent.ACTION_POINTER_UP or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f))
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(310f), listOf(372f))
assertEquals(
listOf(
MotionEvent.ACTION_DOWN to 1,
MotionEvent.ACTION_MOVE to 1,
MotionEvent.ACTION_UP to 1,
),
forwarded,
)
assertEquals(listOf(KeyEvent.KEYCODE_W to true, KeyEvent.KEYCODE_W to false), sent)
}
@Test fun gestureRecognizerKeepsOneSplitTargetOwnerUntilItsStreamEnds() {
val gate = GestureTouchStreamGate()
fun accepts(source: GestureTouchStreamGate.Source, action: Int): Boolean {
val event = MotionEvent.obtain(0L, 1L, action, 1f, 1f, 0)
return try { gate.accepts(source, event) } finally { event.recycle() }
}
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_MOVE))
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_UP))
assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
assertFalse(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_CANCEL))
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
gate.reset()
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
}
@Test fun loadingLayoutReleasesLatchedKeysBeforeReplacingEntries() {
val sent = mutableListOf<Pair<Int, Boolean>>()
val keys = ScreenKeys(context) { code, down -> sent += code to down }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT))
keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true)
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f))
keys.load("")
assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent)
}
@Test fun hidingTheViewReleasesLatchedKeys() {
val sent = mutableListOf<Pair<Int, Boolean>>()
val keys = ScreenKeys(context) { code, down -> sent += code to down }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT))
keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true)
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f))
keys.visibility = View.GONE
assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent)
}
private fun send(view: View, action: Int, ids: List<Int>, xs: List<Float>, ys: List<Float>) {
val properties = Array(ids.size) { index ->
MotionEvent.PointerProperties().apply {
id = ids[index]
toolType = MotionEvent.TOOL_TYPE_FINGER
}
}
val coordinates = Array(ids.size) { index ->
MotionEvent.PointerCoords().apply {
x = xs[index]
y = ys[index]
pressure = 1f
size = 1f
}
}
val event = MotionEvent.obtain(
0L, 1L, action, ids.size, properties, coordinates, 0, 0,
1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0,
)
try {
view.onTouchEvent(event)
} finally {
event.recycle()
}
}
}
@@ -172,7 +172,7 @@ class SessionGestureRoutingTest {
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))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(if (gestureMode) 350 else 320))
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")
@@ -220,7 +220,7 @@ class SessionGestureRoutingTest {
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { directButtons += button to pressed }
override fun onWheel(steps: Int) {}
override fun onLongPress() {}
}) {}
}) {}.also { it.configure(config) }
setField("directTouchHold", directHold)
launcherScroll = ScrollTouchGestures(8f, 50f, object : ScrollTouchGestures.Listener {
override fun onMove(x: Float, y: Float) { scrollPositions += x to y }
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.input
import android.media.AudioManager
import android.view.KeyEvent
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28, 33])
class SteamVolumeKeysTest {
private val adjustments = mutableListOf<Int>()
private fun key(code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) =
KeyEvent(0L, 0L, action, code, repeat)
private fun dispatch(code: Int, enabled: Boolean = true, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) =
SteamVolumeKeys.dispatch(key(code, action, repeat), enabled, adjustments::add)
@Test fun enabledKeysAdjustOncePerDownAndConsumeRelease() {
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, repeat = 1))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, action = KeyEvent.ACTION_UP))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN, action = KeyEvent.ACTION_UP))
assertEquals(listOf(AudioManager.ADJUST_RAISE, AudioManager.ADJUST_RAISE, AudioManager.ADJUST_LOWER), adjustments)
}
@Test fun muteTogglesOnlyOnInitialPress() {
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, repeat = 1))
assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, action = KeyEvent.ACTION_UP))
assertEquals(listOf(AudioManager.ADJUST_TOGGLE_MUTE), adjustments)
}
@Test fun disabledAndNonVolumeKeysFallThrough() {
for (code in listOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) {
assertFalse(dispatch(code, enabled = false))
assertFalse(dispatch(code, enabled = false, action = KeyEvent.ACTION_UP))
}
assertFalse(dispatch(KeyEvent.KEYCODE_BUTTON_A))
assertTrue(adjustments.isEmpty())
}
}
@@ -0,0 +1,398 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
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
import java.io.File
import java.nio.file.Files
import java.util.zip.CRC32
private val REGISTRY = """
WINE REGISTRY Version 2
;; All keys relative to \\Machine
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Battle.net] 1760380000
#time=1dc3c6e0a5e1f2a
"DisplayName"="Battle.net"
"InstallLocation"="C:\\Program Files (x86)\\Battle.net"
"UninstallString"="\"C:\\Program Files (x86)\\Battle.net\\Battle.net Uninstaller.exe\" --lang=enUS"
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo IV] 1760380001
"DisplayIcon"="C:\\Program Files (x86)\\Diablo IV\\Diablo IV Launcher.exe"
"DisplayName"="Diablo\xae IV"
"InstallLocation"="C:\\Program Files (x86)\\Diablo IV"
"Publisher"="Blizzard Entertainment"
"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=fenris --displayname=\"Diablo IV\""
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Overwatch] 1760380002
"InstallLocation"="C:\\Program Files (x86)\\Overwatch"
"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=prometheus --displayname=\"Overwatch\""
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Steam] 1760380003
"InstallLocation"="C:\\Program Files (x86)\\Steam"
"UninstallString"="C:\\Program Files (x86)\\Steam\\uninstall.exe --uid=steam"
[Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo II Resurrected] 1760380004
"UninstallString"=str(2):"\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --lang=enUS --uid=osi --displayname=\"Diablo II: Resurrected\""
"InstallLocation"="C:/Games/Diablo II Resurrected"
[Software\\Wine\\Fonts] 1760380005
"InstallLocation"="C:\\x"
"UninstallString"="Battle.net --uid=wow"
""".trimStart()
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class BattleNetTest {
private lateinit var context: Context
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
File(context.filesDir, "components").deleteRecursively()
LinuxRuntime.rootDir(context).deleteRecursively()
}
@Test fun theIdIsTheShortcutIdTheScriptNames() {
val crc = CRC32().apply { update("\"droiddeck-battlenet\"Battle.net".toByteArray()) }.value
assertEquals(crc or 0x80000000L, BattleNet.APP_ID)
}
@Test fun theNewestD2rfixIsTheHighestFexThenTheHighestFix() {
val items = listOf(
item("FEXCore-2610-linux.wcp"),
item("FEXCore-2609-d2rfix25-linux.wcp"),
item("FEXCore-2610-d2rfix9-linux.wcp"),
item("FEXCore-2610-d2rfix28-linux.wcp"),
item("FEXCore-2509.1-d2rfix40-linux.wcp"),
)
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.newestD2rFix(items)?.file)
assertEquals("FEXCore-2610.1-d2rfix1-linux.wcp", BattleNet.newestD2rFix(items + item("FEXCore-2610.1-d2rfix1-linux.wcp"))?.file)
assertEquals("FexCore-2611-D2RFIX2-linux.wcp", BattleNet.newestD2rFix(items + item("FexCore-2611-D2RFIX2-linux.wcp"))?.file)
}
@Test fun onlyFexD2rfixPackagesCount() {
assertNull(BattleNet.newestD2rFix(listOf(item("FEXCore-2610-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp", comp = "dxvk"))))
assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp.part"))
assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix-linux.wcp"))
assertEquals(listOf(2610L) to 28L, BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp"))
}
@Test fun theNewestStoredBuildIsSetForThePrefix() {
catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp", "FEXCore-2610-linux.wcp")
store("FEXCore-2610-d2rfix28-linux.wcp")
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh))
assertEquals(mapOf("fex" to "FEXCore-2610-d2rfix28-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh))
}
@Test fun aNewerBuildReplacesTheOldOne() {
catalog("FEXCore-2609-d2rfix25-linux.wcp")
store("FEXCore-2609-d2rfix25-linux.wcp")
BattleNet.ensureFex(context, ::noRefresh)
catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp")
store("FEXCore-2610-d2rfix28-linux.wcp")
BattleNet.ensureFex(context, ::noRefresh)
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"])
}
@Test fun aStaleListingIsFetchedAgain() {
catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1)
store("FEXCore-2610-d2rfix28-linux.wcp")
BattleNet.ensureFex(context) { listOf(item("FEXCore-2609-d2rfix25-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp")) }
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"])
}
@Test fun aFailedFetchFallsBackOnTheCachedListing() {
catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1)
store("FEXCore-2609-d2rfix25-linux.wcp")
assertEquals("FEXCore-2609-d2rfix25-linux.wcp", BattleNet.ensureFex(context) { error("offline") })
}
@Test fun aListingWithoutD2rfixIsAnError() {
catalog("FEXCore-2610-linux.wcp")
var refreshed = 0
assertThrows(IllegalStateException::class.java) { BattleNet.ensureFex(context) { refreshed++; emptyList() } }
assertEquals(1, refreshed)
assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
}
@Test fun installedIsTheLauncherInThePrefix() {
assertFalse(BattleNet.installed(context))
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
assertTrue(BattleNet.installed(context))
}
@Test fun theEnvironmentEditorNamesBattleNetsProfileOnceItIsInstalled() {
assertNull(BattleNet.profile(context))
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
assertEquals(BattleNet.APP_ID.toString() to "Battle.net", BattleNet.profile(context))
}
@Test fun removeTakesThePrefixItsMenuEntryAndCacheButNothingItLinksTo() {
catalog("FEXCore-2610-d2rfix28-linux.wcp")
store("FEXCore-2610-d2rfix28-linux.wcp")
BattleNet.ensureFex(context, ::noRefresh)
val root = LinuxRuntime.rootDir(context)
fun put(relative: String) = File(root, relative).apply { parentFile!!.mkdirs(); writeText("x") }
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
val outside = File(context.cacheDir, "bnet-outside").apply { mkdirs() }
val kept = File(outside, "kept").apply { writeText("x") }
val drives = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() }
Files.createSymbolicLink(File(drives, "z:").toPath(), outside.toPath())
val menu = put("usr/local/share/applications/droiddeck-battlenet.desktop")
val otherMenu = put("usr/local/share/applications/other.desktop")
val log = put("root/.cache/droiddeck/battlenet/battlenet.log")
val otherPrefix = put("root/.local/share/Steam/steamapps/compatdata/123/pfx/system.reg")
BattleNet.remove(context)
assertFalse(BattleNet.prefix(context).exists())
assertFalse(BattleNet.installed(context))
assertTrue(kept.isFile)
assertFalse(menu.exists())
assertTrue(otherMenu.isFile)
assertFalse(log.parentFile!!.exists())
assertTrue(otherPrefix.isFile)
assertNull(BattleNet.fexInUse(context))
outside.deleteRecursively()
}
@Test fun anIdNamesItsTitleWithOrWithoutItsLocale() {
assertEquals("Pro", BattleNet.title("prometheus")?.code)
assertEquals("D3", BattleNet.title("diablo3_enus")?.code)
assertEquals("Fen", BattleNet.title("Fenris")?.code)
assertEquals("WTCG", BattleNet.title("hs_beta")?.code)
assertEquals("Diablo II: Resurrected", BattleNet.title("osi_dede")?.name)
assertEquals("WoWC", BattleNet.title("wow_classic")?.code)
assertEquals("WoWC", BattleNet.title("wow_classic_era_enus")?.code)
assertNull(BattleNet.title("agent"))
assertNull(BattleNet.title("osi_beta"))
}
@Test fun theUninstallEntriesOfBattleNetsGamesAreRead() {
val entries = BattleNet.uninstallEntries(REGISTRY.lineSequence())
assertEquals(listOf(
"fenris" to "C:\\Program Files (x86)\\Diablo IV",
"prometheus" to "C:\\Program Files (x86)\\Overwatch",
"osi" to "C:/Games/Diablo II Resurrected",
), entries)
}
@Test fun productDbsInstallsAreRead() {
val db = message(
field(1, message(field(1, "agent"), field(2, "agent"), field(3, message(field(1, "C:/ProgramData/Battle.net/Agent"))))),
varintField(7, 300),
field(1, message(field(1, "hs_beta"), field(2, "wtcg"), varintField(9, 1), field(3, message(field(1, "C:/Program Files (x86)/Hearthstone"), field(2, "US"))))),
field(1, message(field(1, "s2"))),
field(1, message(field(1, "s1"), field(3, message(field(1, "Z:/mnt/droiddeck-sd/Games/Battle.net/StarCraft"))), field(4, message(field(1, message(varintField(1, 0), varintField(2, 0))))))),
field(1, message(field(1, "wow_classic_anniversary"), field(3, message(field(1, "Z:/root/Games/World of Warcraft"))), field(4, message(field(1, message(varintField(1, 1), varintField(2, 1))))))),
)
assertEquals(listOf("agent" to "C:/ProgramData/Battle.net/Agent", "hs_beta" to "C:/Program Files (x86)/Hearthstone", "wow_classic_anniversary" to "Z:/root/Games/World of Warcraft"),
BattleNet.productDbEntries(db))
assertNull(BattleNet.productDbEntries(db.copyOf(db.size - 3)))
assertNull(BattleNet.productDbEntries(byteArrayOf(0x0a, 0x7f, 0x01)))
assertNull(BattleNet.productDbEntries(ByteArray(0)))
assertNull(BattleNet.productDbEntries(byteArrayOf(0x0a, 0x03, 0x0a, 0x7f, 0x01)))
assertEquals(emptyList<Pair<String, String>>(), BattleNet.productDbEntries(message(field(1, message(field(1, "s1"), field(3, message(field(1, "Z:/Games/StarCraft"))), field(4, message(field(1, message(varintField(1, 0))))))))))
}
@Test fun theAgentDoesNotStartWithoutTheGameStorageCard() {
val card = Files.createTempDirectory("card").toFile()
com.droiddeck.launcher.session.SessionPrefs.setGameStorage(context, card.path, "SD Card")
assertTrue(com.droiddeck.launcher.stores.battlenet.BattleNetInstall.binds(context).any { it.endsWith(":/mnt/droiddeck-sd") })
card.deleteRecursively()
assertThrows(IllegalStateException::class.java) { com.droiddeck.launcher.stores.battlenet.BattleNetInstall.binds(context) }
}
@Test fun aGameTheAgentNoLongerTracksIsNotInstalled() {
val registry = listOf("wow" to "Z:\\mnt\\droiddeck-sd\\Games\\Battle.net\\World of Warcraft", "hs_beta" to "C:\\Hearthstone")
assertEquals(listOf("hs_beta" to "C:\\Hearthstone", "HS_BETA" to "C:/Hearthstone"), BattleNet.installs(registry, listOf("HS_BETA" to "C:/Hearthstone")))
assertEquals(registry, BattleNet.installs(registry, null))
assertEquals(emptyList<Pair<String, String>>(), BattleNet.installs(registry, emptyList()))
}
@Test fun theGamesAreTheTitlesInstalledInTheirFolders() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "system.reg").writeText(REGISTRY)
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "hs_beta"), field(3, message(field(1, "C:/Program Files (x86)/Hearthstone"))))),
field(1, message(field(1, "fenris"), field(3, message(field(1, "C:/Program Files (x86)/Diablo IV"))))),
field(1, message(field(1, "wow_classic"), field(3, message(field(1, "C:/Program Files (x86)/World of Warcraft"))))),
))
for (folder in listOf("Program Files (x86)/Diablo IV", "Games/Diablo II Resurrected", "Program Files (x86)/Hearthstone", "Program Files (x86)/World of Warcraft")) {
File(pfx, "drive_c/$folder").mkdirs()
}
val games = BattleNet.games(context)
assertEquals(listOf("Fen", "WTCG", "WoWC"), games.map { it.code })
assertEquals(listOf("Diablo IV", "Hearthstone", "World of Warcraft Classic"), games.map { it.name })
assertEquals(File(pfx, "drive_c/Program Files (x86)/Hearthstone"), games[1].folder)
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").delete()
assertEquals(listOf("Fen", "OSI"), BattleNet.games(context).map { it.code })
assertNull(BattleNet.hostFolder(context, "D:\\Games\\X"))
assertNull(BattleNet.hostFolder(context, "C:\\..\\..\\etc"))
assertNull(BattleNet.hostFolder(context, "Z:\\root\\..\\..\\etc"))
assertEquals(File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Hearthstone"),
BattleNet.hostFolder(context, "Z:/root/Games/Stores/Battle.net/Hearthstone/"))
}
@Test fun aGamesShortcutHasBattleNetLaunchItInItsPrefix() {
val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() }
File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a))
val shortcut = BattleNet.shortcut(context, BattleNet.Game("fenris", "Diablo IV", "Fen", folder))!!
val exe = "/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe"
assertEquals(exe, shortcut.guestExe)
assertEquals(exe.substringBeforeLast('/'), shortcut.guestDir)
assertEquals("STEAM_COMPAT_DATA_PATH=/root/.local/share/Steam/steamapps/compatdata/2596113170 %command% --exec=\"launch Fen\"", shortcut.launchOptions)
val crc = CRC32().apply { update("\"$exe\"Diablo IV".toByteArray()) }.value
assertEquals(crc or 0x80000000L, shortcut.appId)
assertEquals((shortcut.appId shl 32) or 0x02000000L, shortcut.gameId)
assertEquals(com.droiddeck.launcher.stores.Store.BATTLENET.id, shortcut.source)
assertEquals("Diablo IV Launcher.exe", shortcut.exe.name)
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(context, listOf(shortcut)).readText()
val entry = JSONArray(listing).getJSONObject(0)
assertEquals(com.droiddeck.launcher.stores.Store.BATTLENET.id, entry.getString("store"))
assertEquals(shortcut.launchOptions, entry.getString("launch"))
assertEquals(exe, entry.getString("exe"))
}
@Test fun titlesSharingALaunchCodeShareTheirArt() {
val cover = File(context.filesDir, "battlenet-art/fenris/p.jpg").apply { parentFile!!.mkdirs(); writeBytes(byteArrayOf(1)) }
assertEquals(cover, BattleNet.art(context, BattleNet.title("fen")!!).cover)
val wide = File(context.filesDir, "battlenet-art/wow_classic/blizzard.jpg").apply { parentFile!!.mkdirs(); writeBytes(byteArrayOf(1)) }
assertEquals(wide, BattleNet.art(context, BattleNet.title("wow_classic_anniversary")!!).header)
}
@Test fun theStoreOffersEachTitleOnceAndHidesWhatIsInstalled() {
val codes = BattleNet.STORE.map { it.code }
assertEquals(codes.distinct(), codes)
assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes)
assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" })
assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid)
assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) })
val installed = listOf("fenris", "diablo3_enus", null)
val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code }
assertFalse("Fen" in offered || "D3" in offered)
assertTrue("OSI" in offered)
}
@Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() {
File(context.filesDir, "game-environment.json").delete()
val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() }
File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a))
val shortcut = BattleNet.shortcut(context, BattleNet.Game("fenris", "Diablo IV", "Fen", folder))!!
val game = com.droiddeck.launcher.frontend.Library.SteamGame(
shortcut.appId.toInt(), shortcut.name, null, com.droiddeck.launcher.frontend.Library.ADDED, shortcut.gameId,
source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = shortcut.storeId)
val noSteam = com.droiddeck.launcher.session.NoSteamLaunch
assertEquals(BattleNet.APP_ID.toString(), noSteam.scope(game))
assertFalse(noSteam.enabled(context, game))
assertTrue(BattleNet.ensureNoSteam(context))
assertTrue(noSteam.enabled(context, game))
val command = noSteam.command(game, shortcut)!!
assertEquals(noSteam.BATTLENET, command.program)
assertEquals(listOf("launch", "Fen"), command.args)
GameEnvironmentStore.setGameNoSteam(context, BattleNet.APP_ID.toString(), false)
assertFalse(BattleNet.ensureNoSteam(context))
assertFalse(noSteam.enabled(context, game))
}
@Test fun theGamesAreToldOfAFifthOfThePhonesMemory() {
assertEquals(2048, BattleNet.videoMemory(11113))
assertEquals(1536, BattleNet.videoMemory(7468))
assertEquals(2560, BattleNet.videoMemory(15200))
assertEquals(3584, BattleNet.videoMemory(60000))
assertTrue(BattleNet.videoMemory(Long.MAX_VALUE / 2) < 4096)
assertEquals(
"dxgi.maxDeviceMemory = 2048; dxgi.maxSharedMemory = 2048; d3d9.maxAvailableMemory = 2048",
BattleNet.videoMemoryOptions(2048),
)
}
@Test fun theCapIsTheBattleNetProfilesOwnDxvkConfigUnlessItHasOne() {
File(context.filesDir, "game-environment.json").delete()
val manager = context.getSystemService(android.app.ActivityManager::class.java)
org.robolectric.Shadows.shadowOf(manager).setMemoryInfo(android.app.ActivityManager.MemoryInfo().apply { totalMem = 11113L shl 20 })
val scope = BattleNet.APP_ID.toString()
assertTrue(BattleNet.ensureVideoMemory(context))
assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG"))
val published = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json").readText()
assertTrue("dxgi.maxDeviceMemory = 2048" in JSONObject(published).getJSONObject("games").getJSONObject(scope).getString("DXVK_CONFIG"))
assertFalse(BattleNet.ensureVideoMemory(context))
for (own in listOf("dxvk.maxFrameRate = 30", null)) {
GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).let { it.withEntries(scope, it.entries(scope) + ("DXVK_CONFIG" to own)) })
assertFalse(BattleNet.ensureVideoMemory(context))
assertEquals(own, GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG"))
}
GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).let { it.withEntries(scope, it.entries(scope) - "DXVK_CONFIG") })
assertTrue(BattleNet.ensureVideoMemory(context))
}
private fun launcher() = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe")
private fun varint(value: Long): ByteArray {
val out = java.io.ByteArrayOutputStream()
var v = value
while (v >= 0x80) { out.write(((v and 0x7f) or 0x80).toInt()); v = v ushr 7 }
out.write(v.toInt())
return out.toByteArray()
}
private fun field(number: Int, bytes: ByteArray) = varint((number shl 3 or 2).toLong()) + varint(bytes.size.toLong()) + bytes
private fun field(number: Int, text: String) = field(number, text.toByteArray())
private fun varintField(number: Int, value: Long) = varint((number shl 3).toLong()) + varint(value)
private fun message(vararg fields: ByteArray) = fields.fold(ByteArray(0)) { all, f -> all + f }
private fun noRefresh(context: Context): List<ComponentsManager.CatalogItem> = error("the cached listing was fresh")
private fun item(file: String, comp: String = "fex") = ComponentsManager.CatalogItem(
file, comp, "FexCore-Linux", "https://github.com/The412Banner/Nightlies/releases/download/FexCore-Linux/$file", 4, "sha256:" + "ab".repeat(32),
)
private fun catalog(vararg files: String, fetchedAt: Long = System.currentTimeMillis() / 1000) {
val cache = File(context.filesDir, "components/catalog.json")
cache.parentFile!!.mkdirs()
val items = JSONArray()
for (file in files) items.put(JSONObject().put("file", file).put("comp", "fex").put("release", "FexCore-Linux")
.put("url", item(file).url).put("size", 4).put("digest", item(file).digest))
cache.writeText(JSONObject().put("items", items).put("fetchedAt", fetchedAt).toString())
}
private fun store(file: String) {
val wcp = File(context.filesDir, "components/packages/$file")
wcp.parentFile!!.mkdirs()
TarArchiveOutputStream(ZstdOutputStream(wcp.outputStream())).use { tar ->
fun put(name: String, bytes: ByteArray) {
tar.putArchiveEntry(TarArchiveEntry(name).apply { size = bytes.size.toLong() })
tar.write(bytes)
tar.closeArchiveEntry()
}
put("profile.json", JSONObject().put("type", "FEXCore-Linux").put("versionName", file.removeSuffix(".wcp")).toString().toByteArray())
put("files/lib/wine/aarch64-windows/libarm64ecfex.dll", "arm64ec $file".toByteArray())
put("files/lib/wine/aarch64-windows/libwow64fex.dll", "wow64 $file".toByteArray())
}
}
}
@@ -119,6 +119,21 @@ class BwrapSpawnerPlanTest {
assertEquals("org.example.Game", plan.env["FLATPAK_ID"])
}
@Test fun sandboxedAppsSeeTheSessionsNetworkLink() {
val context = RuntimeEnvironment.getApplication()
val rootfs = LinuxRuntime.rootDir(context)
val lib = File(rootfs, "usr/local/lib/libblsession.so").apply { parentFile?.mkdirs(); writeText("") }
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libblsession.so\n") }
val link = File(rootfs, "etc/droiddeck-net").apply { writeText("if wlan0 2 1500\n") }
try {
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
assertEquals("/run/droiddeck-preload/libblsession.so", plan.env["LD_PRELOAD"])
assertEquals(link.path, plan.binds.single { it.guest == "/etc/droiddeck-net" }.host)
} finally {
listOf(lib, preload, link).forEach { it.delete() }
}
}
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
val context = RuntimeEnvironment.getApplication()
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
@@ -0,0 +1,155 @@
package com.droiddeck.launcher.runtime
import android.app.Application
import android.app.NotificationManager
import android.content.Context
import android.media.AudioManager
import android.os.Looper
import android.provider.Settings
import java.io.File
import java.time.Duration
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implements
import org.robolectric.annotation.Implementation
import org.robolectric.shadows.ShadowSettings
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28, 33], manifest = Config.NONE, application = Application::class, shadows = [WriteSettingsShadow::class])
class DeviceControlsComponentTest {
@get:Rule val tmp = TemporaryFolder()
private val context get() = RuntimeEnvironment.getApplication()
private val audio get() = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
private lateinit var component: DeviceControlsComponent
private lateinit var directory: File
private var visible = true
@Before fun start() {
WriteSettingsShadow.writable = true
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
val root = tmp.newFolder()
directory = DeviceControlsComponent.directory(root)
component = DeviceControlsComponent(context, root) { visible }
component.publish()
component.start()
shadowOf(Looper.getMainLooper()).idle()
}
@After fun stop() {
component.stop()
shadowOf(Looper.getMainLooper()).idle()
}
private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(300))
private fun request(name: String, text: String) {
File(directory, "$name.request").writeText(text)
tick()
}
@Test fun androidChangesArePublishedAndRequestsUseDeviceVolumeSteps() {
request("volume", "999")
assertEquals(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), audio.getStreamVolume(AudioManager.STREAM_MUSIC))
audio.setStreamVolume(AudioManager.STREAM_MUSIC, 3, 0)
tick()
assertEquals("3", File(directory, "volume.state").readText().split(" ").first())
request("volume", "invalid")
assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC))
}
@Test fun deniedBrightnessDoesNotOpenSettingsOrReplayAnOldSliderValueAfterPermission() {
WriteSettingsShadow.writable = false
request("brightness", "0.75")
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
assertNull(shadowOf(context).nextStartedActivity)
assertFalse(JSONObject(File(directory, "state.json").readText()).getBoolean("brightnessWritable"))
WriteSettingsShadow.writable = true
tick()
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
request("brightness", "0.75")
assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
}
@Test fun brightnessIsBoundedAndExternalChangesAreReadBack() {
for (invalid in listOf("NaN", "Infinity", "-0.1", "1.1")) request("brightness", invalid)
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
request("brightness", "0")
assertEquals(1, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 255)
tick()
assertEquals(1.0, JSONObject(File(directory, "state.json").readText()).getDouble("brightness"), 0.0001)
}
@Test fun permissionNotificationOpensOptionalLauncherSetupOnlyWhenSelected() {
visible = false
WriteSettingsShadow.writable = false
request("brightness", "0.25")
request("brightness", "0.75")
assertNull(shadowOf(context).nextStartedActivity)
val notifications = context.getSystemService(NotificationManager::class.java)
val notification = notifications.activeNotifications.single().notification
notification.contentIntent.send()
val intent = shadowOf(context).nextStartedActivity
assertEquals(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP, intent.action)
assertEquals("BRIGHTNESS", intent.getStringExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(121))
WriteSettingsShadow.writable = true
tick()
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
assertTrue(notifications.activeNotifications.isEmpty())
}
@Test fun stoppingClearsThePermissionNotificationAndPendingRequest() {
visible = false
WriteSettingsShadow.writable = false
request("brightness", "0.75")
component.stop()
shadowOf(Looper.getMainLooper()).idle()
assertTrue(context.getSystemService(NotificationManager::class.java).activeNotifications.isEmpty())
WriteSettingsShadow.writable = true
tick()
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
}
@Test fun stoppedSessionsDoNotConsumeNewCommands() {
component.stop()
shadowOf(Looper.getMainLooper()).idle()
request("brightness", "0.2")
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
}
@Test fun repeatedSliderChangesDoNotInterruptTheSession() {
WriteSettingsShadow.writable = false
request("brightness", "0.75")
assertNull(shadowOf(context).nextStartedActivity)
request("brightness", "0.8")
assertNull(shadowOf(context).nextStartedActivity)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(5))
request("brightness", "0.8")
assertNull(shadowOf(context).nextStartedActivity)
}
@Test fun oversizedRequestsAreDiscardedAndDoNotBlockLaterCommands() {
request("brightness", "0".repeat(1000))
assertFalse(File(directory, "brightness.request.processing").exists())
request("brightness", "0.75")
assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
}
}
@Implements(Settings.System::class)
class WriteSettingsShadow : ShadowSettings.ShadowSystem() {
companion object {
@JvmField var writable = true
@JvmStatic @Implementation fun canWrite(context: Context) = writable
}
}
@@ -1,7 +1,9 @@
package com.droiddeck.launcher.runtime
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
@@ -17,4 +19,12 @@ class ProotFastPathTest {
val binds = (1..ProotFastPath.MAX_BINDS + 1).map { "/host/$it:/guest/$it" }
assertNull(ProotFastPath.key(root, binds))
}
@Test fun fastPathStaysOffForTheRootfsProot() {
assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING))
assertFalse(ProotFastPath.allows(preference = false, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = true, source = LinuxRuntime.PROOT_PACK))
}
}
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.runtime
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.core.AddonPack
import java.io.ByteArrayOutputStream
import java.io.File
import java.net.ServerSocket
import java.security.MessageDigest
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Predicate
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.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
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class)
class RuntimeInstallRollbackTest {
@get:Rule val tmp = TemporaryFolder()
@After fun resetFaults() { RuntimeFileTree.refuseForTest = null }
private fun put(root: File, rel: String, data: String) = File(root, rel).apply {
checkNotNull(parentFile).mkdirs()
writeText(data)
}
private data class Attempt(val root: File, val staging: File, val old: File, val result: Boolean)
private fun attempt(failRollback: Boolean): Attempt {
val files = tmp.newFolder("files")
val cache = tmp.newFolder("cache")
val context = object : ContextWrapper(RuntimeEnvironment.getApplication()) {
override fun getFilesDir(): File = files
override fun getCacheDir(): File = cache
override fun getApplicationContext(): Context = this
}
for ((pack, pin, required) in listOf(
Triple(AddonPack.PROOT, BuildConfig.PACK_PROOT_SHA256, listOf("libproot.so", "libproot-loader.so")),
Triple(AddonPack.DIRECTAUDIO, BuildConfig.PACK_DIRECTAUDIO_SHA256,
listOf("linux-wine11/version.txt", "linux-wine11-systhread/version.txt")),
)) {
val version = pin.ifEmpty { "0".repeat(64) }
val directory = File(files, "addons/${pack.name}/$version")
required.forEach { put(directory, it, "test pack") }
put(directory, AddonPack.COMPLETE, version)
}
val root = LinuxRuntime.rootDir(context)
val staging = File(files, LinuxRuntime.DIR + ".new")
val old = File(files, LinuxRuntime.DIR + ".old")
put(root, "root/save.dat", "original user data")
put(root, "opt/appimages/user/game/app.AppImage", "original app")
put(root, "usr/bin/usable", "previous runtime")
val payload = ByteArrayOutputStream().also { bytes ->
ZstdCompressorOutputStream(bytes).use { zstd ->
TarArchiveOutputStream(zstd).use { tar ->
for ((name, value) in listOf("root/.bashrc" to "shipped home", "usr/bin/new" to "new runtime",
"opt/appimages/user/block" to "shipped app")) {
val data = value.toByteArray()
tar.putArchiveEntry(TarArchiveEntry(name).apply { size = data.size.toLong() })
tar.write(data)
tar.closeArchiveEntry()
}
}
}
}.toByteArray()
val digest = MessageDigest.getInstance("SHA-256").digest(payload).joinToString("") { "%02x".format(it) }
val faultSeen = AtomicBoolean()
RuntimeFileTree.refuseForTest = Predicate { path ->
if (path == File(staging, "opt/appimages/user/block").toPath() && faultSeen.compareAndSet(false, true)) {
if (failRollback) put(old, "root/rollback-block", "concurrent data")
true
} else failRollback && path == File(old, "root/rollback-block").toPath()
}
val server = ServerSocket(0)
val thread = Thread {
runCatching {
server.accept().use { socket ->
socket.soTimeout = 5000
val input = socket.getInputStream().bufferedReader(Charsets.ISO_8859_1)
while (true) {
val line = input.readLine() ?: break
if (line.isEmpty()) break
}
val out = socket.getOutputStream()
out.write(("HTTP/1.1 200 OK\r\nContent-Length: ${payload.size}\r\nConnection: close\r\n\r\n").toByteArray())
out.write(payload)
out.flush()
}
}
}.apply { isDaemon = true; start() }
try {
val release = LinuxRuntimeInstaller.Release("synthetic", "http://127.0.0.1:${server.localPort}/runtime.tar.zst", digest, payload.size.toLong())
val result = LinuxRuntimeInstaller.install(context, release, null)
assertTrue("the intended carry fault was not reached", faultSeen.get())
return Attempt(root, staging, old, result)
} finally {
server.close()
thread.join(1000)
RuntimeFileTree.refuseForTest = null
}
}
@Test fun aFailedCarryAndFailedRollbackKeepTheOnlyStagedCopy() {
val attempt = attempt(failRollback = true)
assertFalse(attempt.result)
assertTrue("the only staged copy was deleted", File(attempt.staging, "root/save.dat").isFile)
assertEquals("original user data", File(attempt.staging, "root/save.dat").readText())
assertEquals("original app", File(attempt.root, "opt/appimages/user/game/app.AppImage").readText())
assertEquals("previous runtime", File(attempt.root, "usr/bin/usable").readText())
repeat(2) {
assertThrows(java.io.IOException::class.java) {
LinuxRuntimeInstaller.recoverInterruptedSwap(attempt.root, attempt.staging, attempt.old)
}
assertEquals("original user data", File(attempt.staging, "root/save.dat").readText())
}
}
@Test fun aCompleteRollbackStillRestoresAndCleansTheFailedCandidate() {
val attempt = attempt(failRollback = false)
assertFalse(attempt.result)
assertEquals("original user data", File(attempt.root, "root/save.dat").readText())
assertEquals("original app", File(attempt.root, "opt/appimages/user/game/app.AppImage").readText())
assertFalse(attempt.staging.exists())
}
}
@@ -69,6 +69,7 @@ class RuntimeRemovalTest {
val old = File(dir, "linuxfs.old").apply { File(this, "root").mkdirs() }
val staging = File(dir, "linuxfs.new").apply { File(this, "root").mkdirs() }
File(staging, "root/save").writeText("user data")
File(staging, LinuxRuntimeInstaller.CARRY_MARKER).writeText("1")
for (tree in listOf(old, staging))
Files.setPosixFilePermissions(tree.toPath(), PosixFilePermissions.fromString("r-xr-xr-x"))
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
@@ -0,0 +1,243 @@
package com.droiddeck.launcher.runtime
import java.io.File
import java.io.IOException
import java.nio.file.Files
import org.junit.After
import org.junit.Assume.assumeTrue
import org.junit.Assert.assertThrows
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class RuntimeUserDataCarryTest {
@get:Rule val tmp = TemporaryFolder()
@After fun resetFaults() { RuntimeFileTree.refuseForTest = null }
private fun put(root: File, rel: String, text: String = rel) = File(root, rel).apply { parentFile.mkdirs(); writeText(text) }
private fun userTree(): File = tmp.newFolder("old").also { old ->
put(old, "root/save.dat", "mine")
put(old, "opt/appimages/user/app1/app.AppImage")
put(old, "opt/droiddeck-apps/game/run.sh")
put(old, "usr/local/share/applications/droiddeck-app-game.desktop")
put(old, "usr/local/share/applications/droiddeck-appimage-app1.desktop")
put(old, "usr/local/share/applications/other.desktop")
put(old, "opt/appimages/dolphin.AppImage")
put(old, "usr/share/applications/droiddeck-dolphin.desktop")
put(old, ".droiddeck-pkg-dolphin", "1.0")
put(old, "usr/bin/tool", "old system file")
}
@Test fun anUpdateKeepsImportedAppsCatalogAppImagesAndHome() {
val old = userTree()
val staging = tmp.newFolder("new").also { put(it, "root/.bashrc", "shipped"); put(it, "usr/bin/tool", "new system file") }
val moved = RuntimeFileTree.carryUserData(old, staging, false)
assertEquals("mine", File(staging, "root/save.dat").readText())
assertFalse("the shipped home is replaced, not merged", File(staging, "root/.bashrc").exists())
for (rel in listOf("opt/appimages/user/app1/app.AppImage", "opt/droiddeck-apps/game/run.sh",
"usr/local/share/applications/droiddeck-app-game.desktop", "usr/local/share/applications/droiddeck-appimage-app1.desktop",
"opt/appimages/dolphin.AppImage", "usr/share/applications/droiddeck-dolphin.desktop", ".droiddeck-pkg-dolphin")) {
assertTrue(rel, File(staging, rel).exists())
assertTrue(rel, rel in moved || moved.any { rel.startsWith("$it/") })
}
assertEquals("system files come from the new runtime", "new system file", File(staging, "usr/bin/tool").readText())
assertFalse("only DroidDeck's own menu entries are user data", File(staging, "usr/local/share/applications/other.desktop").exists())
}
@Test fun aFailureHalfwayPutsEverythingBack() {
val old = userTree()
val staging = tmp.newFolder("new")
put(staging, "usr/local", "a file where a folder is needed")
try {
RuntimeFileTree.carryUserData(old, staging, false)
fail("expected the carry to fail")
} catch (expected: IOException) {
}
assertEquals("mine", File(old, "root/save.dat").readText())
assertTrue(File(old, "opt/appimages/user/app1/app.AppImage").exists())
assertTrue(File(old, "opt/droiddeck-apps/game/run.sh").exists())
assertFalse(File(staging, "root").exists())
}
@Test fun recoveryOnlyFillsWhatIsMissing() {
val target = tmp.newFolder("target").also { put(it, "opt/droiddeck-apps/game/run.sh", "kept") }
val staging = tmp.newFolder("staging").also {
put(it, "opt/droiddeck-apps/game/run.sh", "stale")
put(it, "opt/appimages/user/app1/app.AppImage")
}
val moved = RuntimeFileTree.carryUserData(staging, target, true)
assertEquals(listOf("opt/appimages/user"), moved)
assertEquals("kept", File(target, "opt/droiddeck-apps/game/run.sh").readText())
assertTrue(File(target, "opt/appimages/user/app1/app.AppImage").exists())
}
@Test fun recoveryFindsCompanionsWhoseAppImageWasAlreadyPutBack() {
val root = tmp.newFolder("runtime")
val staging = tmp.newFolder("runtime.new")
val old = File(tmp.root, "runtime.old")
put(root, "opt/appimages/dolphin.AppImage", "user app")
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
put(staging, "usr/share/applications/droiddeck-dolphin.desktop", "menu")
put(staging, ".droiddeck-pkg-dolphin", "version")
put(staging, ".droiddeck-pkg-desktop-kde", "system package marker")
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
assertEquals("menu", File(root, "usr/share/applications/droiddeck-dolphin.desktop").readText())
assertEquals("version", File(root, ".droiddeck-pkg-dolphin").readText())
assertFalse(File(root, ".droiddeck-pkg-desktop-kde").exists())
assertEquals("user app", File(root, "opt/appimages/dolphin.AppImage").readText())
}
@Test fun unmarkedExtractedStagingDoesNotBlockRecovery() {
val root = tmp.newFolder("runtime")
val staging = tmp.newFolder("runtime.new")
val old = File(tmp.root, "runtime.old")
put(root, "root/save.dat", "current user data")
put(staging, "root/.bashrc", "shipped home from interrupted extract")
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
assertEquals("current user data", File(root, "root/save.dat").readText())
assertEquals("shipped home from interrupted extract", File(staging, "root/.bashrc").readText())
}
@Test fun anUnreadableAppImageDirectoryAbortsBeforeMovingHome() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val old = userTree()
val images = File(old, "opt/appimages")
val staging = tmp.newFolder("staging")
assertTrue(images.setReadable(false, false))
assertTrue(images.setExecutable(false, false))
try {
assertThrows(IOException::class.java) { RuntimeFileTree.carryUserData(old, staging, false) }
assertEquals("mine", File(old, "root/save.dat").readText())
assertFalse(File(staging, "root/save.dat").exists())
} finally {
images.setReadable(true, true)
images.setExecutable(true, true)
}
}
@Test fun recoveryRestoresTheRuntimeBeforeTryingAFallibleHomeMove() {
val root = File(tmp.root, "runtime")
val old = tmp.newFolder("runtime.old")
val staging = tmp.newFolder("runtime.new")
put(old, "usr/bin/usable", "previous runtime")
File(old, "root").mkdirs()
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
put(staging, "root/save.dat", "staged user data")
RuntimeFileTree.refuseForTest = java.util.function.Predicate { it.fileName.toString() == "root" }
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
assertTrue("the previous runtime was not restored", root.isDirectory)
assertEquals("previous runtime", File(root, "usr/bin/usable").readText())
assertEquals("staged user data", File(staging, "root/save.dat").readText())
}
@Test fun conflictingRecoveryDataIsRetainedOnEveryRetry() {
val root = tmp.newFolder("runtime")
val staging = tmp.newFolder("runtime.new")
val old = File(tmp.root, "runtime.old")
put(root, "root/current.dat", "current user data")
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
put(staging, "root/older.dat", "unrecovered user data")
repeat(2) {
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
assertEquals("current user data", File(root, "root/current.dat").readText())
assertEquals("unrecovered user data", File(staging, "root/older.dat").readText())
}
}
@Test fun stagedDataWithoutASurvivingRuntimeIsKeptForRecovery() {
val root = File(tmp.root, "runtime")
val old = File(tmp.root, "runtime.old")
val staging = tmp.newFolder("runtime.new")
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
put(staging, "root/save.dat", "only surviving user data")
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
assertEquals("only surviving user data", File(staging, "root/save.dat").readText())
}
@Test fun conflictingIntendedHomesAreRetainedWithoutProofOfTheirContents() {
val root = File(tmp.root, "runtime")
val old = tmp.newFolder("runtime.old")
val staging = tmp.newFolder("runtime.new")
put(old, "root/save.dat", "user data")
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "root")
put(staging, "root/.bashrc", "shipped default")
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
assertEquals("user data", File(root, "root/save.dat").readText())
assertEquals("shipped default", File(staging, "root/.bashrc").readText())
assertTrue(File(staging, LinuxRuntimeInstaller.CARRY_MARKER).exists())
}
@Test fun anUnreadableCarryMarkerStopsRecovery() {
val root = tmp.newFolder("runtime")
val staging = tmp.newFolder("runtime.new")
val old = File(tmp.root, "runtime.old")
val marker = File(staging, LinuxRuntimeInstaller.CARRY_MARKER).apply { mkdirs() }
assertThrows(IOException::class.java) { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }
assertTrue(marker.isDirectory)
}
@Test fun recoveryMovesOnlyAnIntendedPathThatWasAlreadyCarried() {
val root = File(tmp.root, "runtime")
val old = tmp.newFolder("runtime.old")
val staging = tmp.newFolder("runtime.new")
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "root")
put(staging, "root/save.dat", "moved user data")
LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old)
assertEquals("moved user data", File(root, "root/save.dat").readText())
assertFalse(File(staging, LinuxRuntimeInstaller.CARRY_MARKER).exists())
}
@Test fun aSymlinkedParentCannotRedirectAUserDataMoveOutsideTheRuntime() {
val old = tmp.newFolder("old")
val staging = tmp.newFolder("staging")
val outside = tmp.newFolder("outside")
put(outside, "droiddeck-apps/game/run.sh", "outside data")
Files.createSymbolicLink(File(old, "opt").toPath(), outside.toPath())
assertThrows(IOException::class.java) { RuntimeFileTree.carryUserData(old, staging, false) }
assertEquals("outside data", File(outside, "droiddeck-apps/game/run.sh").readText())
assertFalse(File(staging, "opt/droiddeck-apps").exists())
}
@Test fun anInaccessibleLiveHomeIsNeverTreatedAsMissing() {
assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix"))
val root = tmp.newFolder("runtime")
val staging = tmp.newFolder("runtime.new")
val old = File(tmp.root, "runtime.old")
put(root, "root/keep.dat", "current user data")
put(staging, LinuxRuntimeInstaller.CARRY_MARKER, "1")
put(staging, "root/staged.dat", "staged user data")
assertTrue(root.setExecutable(false, false))
val failure = try {
runCatching { LinuxRuntimeInstaller.recoverInterruptedSwap(root, staging, old) }.exceptionOrNull()
} finally {
root.setExecutable(true, true)
}
assertTrue("the existing live home was deleted", File(root, "root/keep.dat").isFile)
assertEquals("current user data", File(root, "root/keep.dat").readText())
assertEquals("staged user data", File(staging, "root/staged.dat").readText())
assertTrue("inaccessible data must abort recovery", failure is IOException)
}
}
@@ -49,11 +49,25 @@ class BatteryComponentTest {
assertEquals("-2000000", File(supplies, "BAT1/current_now").readText().trim())
}
private fun start(supplies: File, vpower: File, currentUa: Long) {
@Test fun chargingAtFullLevelIsReportedFullSoSteamStopsSaying99() {
val supplies = tmp.newFolder("power_supply")
val vpower = tmp.newFolder("vpower")
start(supplies, vpower, 2_000_000L, BatteryManager.BATTERY_STATUS_CHARGING, 100)
assertEquals("Full", File(supplies, "BAT1/status").readText().trim())
assertEquals("Full", File(vpower, "battery_status").readText().trim())
battery?.stop()
start(supplies, vpower, 2_000_000L, BatteryManager.BATTERY_STATUS_CHARGING, 99)
assertEquals("Charging", File(supplies, "BAT1/status").readText().trim())
}
private fun start(
supplies: File, vpower: File, currentUa: Long,
status: Int = BatteryManager.BATTERY_STATUS_DISCHARGING, level: Int = 50,
) {
val context = RuntimeEnvironment.getApplication()
context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).apply {
putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_DISCHARGING)
putExtra(BatteryManager.EXTRA_LEVEL, 50)
putExtra(BatteryManager.EXTRA_STATUS, status)
putExtra(BatteryManager.EXTRA_LEVEL, level)
putExtra(BatteryManager.EXTRA_SCALE, 100)
putExtra(BatteryManager.EXTRA_VOLTAGE, 4000)
})
@@ -0,0 +1,135 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
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
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ComponentImportTest {
private lateinit var context: Context
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
File(context.filesDir, "components").deleteRecursively()
LinuxRuntime.rootDir(context).deleteRecursively()
}
@Test fun refusesOverwritingReferencedPackageWithDifferentContent() {
val wcpA = createWcp("src-a.wcp", "A")
val wcpB = createWcp("src-b.wcp", "B")
val shaA = Hashes.sha256(wcpA)
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk.wcp")
assertThrows(IllegalStateException::class.java) {
ComponentsManager.importPackage(context, wcpB, "dxvk.wcp")
}
val stored = File(context.filesDir, "components/packages/dxvk.wcp")
assertEquals(shaA, Hashes.sha256(stored))
assertFalse(File(context.filesDir, "components/packages/dxvk.wcp.part").exists())
}
@Test fun allowsReimportingIdenticalPackageWhileReferenced() {
val wcpA = createWcp("src-a.wcp", "A")
val shaA = Hashes.sha256(wcpA)
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk.wcp")
val reimported = ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
assertEquals("A", reimported.version)
assertEquals("dxvk.wcp", reimported.file)
val stored = File(context.filesDir, "components/packages/dxvk.wcp")
assertEquals(shaA, Hashes.sha256(stored))
assertFalse(File(context.filesDir, "components/packages/dxvk.wcp.part").exists())
}
@Test fun invalidatesUnpackedStoreWhenReplacingUnreferencedPackage() {
val wcpA = createWcp("src-a.wcp", "A")
val wcpB = createWcp("src-b.wcp", "B")
val shaB = Hashes.sha256(wcpB)
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
val unpacked = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/store/dxvk")
unpacked.mkdirs()
File(unpacked, ".complete").writeText("ok")
assertTrue(File(unpacked, ".complete").isFile)
val replaced = ComponentsManager.importPackage(context, wcpB, "dxvk.wcp")
assertEquals("B", replaced.version)
val stored = File(context.filesDir, "components/packages/dxvk.wcp")
assertEquals(shaB, Hashes.sha256(stored))
assertFalse(unpacked.exists())
}
@Test fun deletingAPackageAGameProfileUsesClearsThatProfileEntry() {
val wcpA = createWcp("src-a.wcp", "A")
ComponentsManager.importPackage(context, wcpA, "dxvk.wcp")
writeGameProfile("10", "dxvk", "dxvk.wcp")
ComponentsManager.deletePackage(context, "dxvk.wcp")
assertFalse(File(context.filesDir, "components/packages/dxvk.wcp").exists())
val state = JSONObject(File(context.filesDir, "components/state.json").readText())
assertFalse(state.optJSONObject("profiles")?.optJSONObject("10")?.has("dxvk") == true)
}
private fun writeGameProfile(scope: String, comp: String, file: String) {
val state = File(context.filesDir, "components/state.json")
state.parentFile!!.mkdirs()
state.writeText(
JSONObject()
.put("active", JSONObject())
.put("queued", JSONObject())
.put("profiles", JSONObject().put(scope, JSONObject().put(comp, file)))
.toString(),
)
}
private fun createWcp(fileName: String, version: String): File {
val out = File(context.cacheDir, fileName)
val profile = JSONObject()
.put("type", "DXVK-Linux")
.put("versionName", version)
.put("description", "DXVK $version")
.toString()
.toByteArray(Charsets.UTF_8)
val dll = "dxvk-dll-$version".toByteArray(Charsets.UTF_8)
TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(out)))).use { tar ->
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX)
val profEntry = TarArchiveEntry("profile.json").apply { size = profile.size.toLong() }
tar.putArchiveEntry(profEntry)
tar.write(profile)
tar.closeArchiveEntry()
val dllEntry = TarArchiveEntry("files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply { size = dll.size.toLong() }
tar.putArchiveEntry(dllEntry)
tar.write(dll)
tar.closeArchiveEntry()
}
return out
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.session
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class ComponentsCarryOverTest {
@Test
fun swappedPackagesFollowTheBuildThatReplacesTheirProton() {
val state = JSONObject("""
{"active": {"DroidDeck-Proton_11-11.2": {
"dxvk": {"file": "dxvk-2.7.wcp", "label": "2.7", "protonVersion": "11-11.2"},
"vkd3d": {"file": "original 11-11.1", "label": "Original from 11-11.1"},
"fex": {"file": "gone.wcp", "label": "old"}}},
"queued": {"DroidDeck-Proton_11-11.2": {
"vkd3d": {"kind": "package", "file": "vkd3d-3.0.wcp", "label": "3.0"},
"fex": {"kind": "original", "protonVersion": "11-11.1", "label": "Original 11-11.1"}}}}
""".trimIndent())
val carried = ComponentsManager.carried(state, "DroidDeck-Proton_11-11.2") { it != "gone.wcp" }
assertEquals(setOf("dxvk", "vkd3d"), carried.keys)
assertEquals("package", carried.getValue("dxvk").getString("kind"))
assertEquals("dxvk-2.7.wcp", carried.getValue("dxvk").getString("file"))
assertEquals("2.7", carried.getValue("dxvk").getString("label"))
assertEquals("vkd3d-3.0.wcp", carried.getValue("vkd3d").getString("file"))
assertEquals(emptyMap<String, JSONObject>(), ComponentsManager.carried(state, "GE-Proton11-7") { true })
}
}
@@ -0,0 +1,110 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ComponentsRepublishTest {
private val fex = "FEXCore-2610-d2rfix28-linux.wcp"
private val scope = "2596113170"
private val dll = "files/lib/wine/aarch64-windows/libwow64fex.dll"
private lateinit var context: Context
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
File(context.filesDir, "components").deleteRecursively()
LinuxRuntime.rootDir(context).deleteRecursively()
}
@Test fun aGameFexChoiceReachesAProtonInstalledAfterIt() {
proton("DroidDeck-Proton 11-11.7", "DroidDeck-Proton-11-11.7")
packageFile()
ComponentsManager.setGameComponent(context, scope, "fex", fex)
assertEquals(setOf("DroidDeck-Proton 11-11.7"), scopedTools())
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
assertEquals(setOf("DroidDeck-Proton 11-11.7"), scopedTools())
assertTrue(ComponentsManager.republish(context))
assertEquals(setOf("DroidDeck-Proton 11-11.7", "DroidDeck-Proton 11-11.8"), scopedTools())
val row = rows().single { it[0] == scope && it[1] == "DroidDeck-Proton 11-11.8" && it[4] == dll }
assertEquals("DroidDeck-Proton-11-11.8", row[2])
assertEquals("d2rfix28 wow64", File(LinuxRuntime.rootDir(context), row[6].removePrefix("/")).readText())
assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"])
}
@Test fun nothingIsRewrittenWhileTheToolsAreUnchanged() {
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
packageFile()
ComponentsManager.setGameComponent(context, scope, "fex", fex)
val published = launchState().readText()
val modified = launchState().lastModified()
assertFalse(ComponentsManager.republish(context))
assertEquals(published, launchState().readText())
assertEquals(modified, launchState().lastModified())
}
@Test fun anUnreadableStateLeavesThePublishedSelectionsAlone() {
proton("DroidDeck-Proton 11-11.7", "DroidDeck-Proton-11-11.7")
packageFile()
ComponentsManager.setGameComponent(context, scope, "fex", fex)
val published = launchState().readText()
val state = File(context.filesDir, "components/state.json").apply { writeText("{\"active\": ") }
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
assertFalse(ComponentsManager.republish(context))
assertEquals(published, launchState().readText())
assertEquals("{\"active\": ", state.readText())
}
@Test fun withNoSelectionsNothingIsPublished() {
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
assertFalse(ComponentsManager.republish(context))
assertFalse(launchState().exists())
}
private fun scopedTools() = rows().filter { it[0] == scope }.map { it[1] }.toSet()
private fun rows() = launchState().readLines().filter { it.isNotEmpty() }.map { it.split('\t') }
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
private fun proton(name: String, version: String) {
val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
File(dir, "files/lib/wine").mkdirs()
File(dir, "proton").writeText("#!/bin/sh\n")
File(dir, "version").writeText("1 $version\n")
File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") }
}
private fun packageFile() {
val out = File(context.filesDir, "components/packages/$fex").apply { parentFile!!.mkdirs() }
val profile = JSONObject().put("type", "FEXCore-Linux").put("versionName", "2610-d2rfix28").toString().toByteArray()
val body = "d2rfix28 wow64".toByteArray()
TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar ->
tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() })
tar.write(profile)
tar.closeArchiveEntry()
tar.putArchiveEntry(TarArchiveEntry(dll).apply { size = body.size.toLong() })
tar.write(body)
tar.closeArchiveEntry()
}
}
}
@@ -29,6 +29,18 @@ class ForcedPackageTest {
LinuxRuntime.rootDir(context).deleteRecursively()
}
@Test fun unpackedCacheNameCannotEscapeStoreDirectory() {
assertEquals("dxvk-2.7.1-linux", ComponentsManager.unpackedCacheKey(dxvk2))
for (filename in listOf("..wcp", "...wcp")) {
try {
ComponentsManager.unpackedCacheKey(filename)
fail("Expected cache traversal name to be rejected: $filename")
} catch (_: IllegalArgumentException) {
// Expected: the derived path would be a dot segment.
}
}
}
@Test fun adreno6xxForcesDxvk2AndNothingElseDoes() {
val rule = ComponentsManager.FORCED_PACKAGES.single { GpuInfo.Family.A6XX in it.families }
assertEquals("dxvk", rule.comp)
@@ -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.Test
class MemoryReadoutTest {
private val meminfo = """
MemTotal: 11379920 kB
MemFree: 527864 kB
MemAvailable: 3235768 kB
Buffers: 1024 kB
SwapTotal: 16777212 kB
SwapFree: 10358080 kB
""".trimIndent()
@Test fun memoryAndSwapInUseComeFromMeminfo() {
val device = MemoryReadout.parseMeminfo(meminfo)!!
assertEquals(11379920L - 3235768L, device.usedKb)
assertEquals(16777212L - 10358080L, device.swapUsedKb)
assertEquals("7.8", MemoryReadout.gb(device.usedKb))
assertEquals("10.9", MemoryReadout.gb(device.totalKb))
assertEquals(0L, MemoryReadout.parseMeminfo("MemTotal: 100 kB\nMemAvailable: 40 kB\n")!!.swapUsedKb)
assertNull(MemoryReadout.parseMeminfo("MemTotal: 100 kB\n"))
}
@Test fun aProcessCountsItsResidentAnonymousAndSharedMemory() {
val status = """
Name: Diablo IV.exe
VmRSS: 2000000 kB
RssAnon: 1500000 kB
RssFile: 400000 kB
RssShmem: 100000 kB
VmSwap: 300000 kB
""".trimIndent()
assertEquals(1600000L, MemoryReadout.residentKb(status))
assertEquals(0L, MemoryReadout.residentKb("Name:\tkthreadd\n"))
}
@Test fun theGameIsWhatRunsInAWinePrefix() {
fun env(vararg vars: String) = vars.joinToString("\u0000", postfix = "\u0000").toByteArray()
assertTrue(MemoryReadout.inWinePrefix(env("HOME=/root", "WINEPREFIX=/root/pfx", "DISPLAY=:0")))
assertTrue(MemoryReadout.inWinePrefix("WINEPREFIX=/x".toByteArray()))
assertFalse(MemoryReadout.inWinePrefix(env("HOME=/root", "STEAM_COMPAT_DATA_PATH=/x", "MY_WINEPREFIX=/y")))
assertFalse(MemoryReadout.inWinePrefix(ByteArray(0)))
}
@Test fun androidIsWhatIsLeftOfTheMemoryInUse() {
val device = MemoryReadout.Device(totalKb = 10_000, availableKb = 3_000, swapTotalKb = 0, swapFreeKb = 0)
assertEquals(3_000L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 2_000, droiddeckKb = 1_000, gpuKb = 1_000)))
assertEquals(4_000L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 2_000, droiddeckKb = 1_000, gpuKb = null)))
assertEquals(0L, MemoryReadout.androidKb(device, MemoryReadout.Split(gameKb = 6_000, droiddeckKb = 2_000, gpuKb = 1_000)))
}
@Test fun theLogLineSaysEveryPartInMegabytes() {
val device = MemoryReadout.Device(totalKb = 11_379_920, availableKb = 1_048_576, swapTotalKb = 16_777_212, swapFreeKb = 8_388_606)
val split = MemoryReadout.Split(gameKb = 2_097_152, droiddeckKb = 524_288, gpuKb = 3_145_728)
assertEquals(
"used 10089/11113 MB, available 1024 MB, swap 8191/16383 MB | game 2048, droiddeck 512, android 4457, gpu 3072 MB",
MemoryLog.line(device, split),
)
assertTrue(MemoryLog.line(device, split.copy(gpuKb = null)).endsWith("gpu ? MB"))
}
}
@@ -61,6 +61,8 @@ class NoSteamLaunchTest {
listOf("--app", "2733369024", "--dir", game.guestDir, "--options", "-windowed", "--", game.guestExe),
added.args,
)
val plain = NoSteamLaunch.addedCommand(AddedGames.Game(game.folder, game.name, game.exe, game.guestExe, game.guestDir, 2733369024L, 0L, emptyList(), source = "gog"))
assertEquals(listOf("--app", "2733369024", "--dir", game.guestDir, "--", game.guestExe), plain.args)
assertNull(NoSteamLaunch.command(shortcut, null))
val steam = NoSteamLaunch.command(steamGame, null)!!
assertEquals(listOf("--app", "413150"), steam.args)
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import android.content.Context
import android.content.pm.ActivityInfo
import com.droiddeck.launcher.core.AppUiPrefs
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -17,15 +18,12 @@ class OrientationTest {
@Before fun clearOrientation() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun landscapeChoicesPersistGloballyAndCanRestoreAutomaticRotation() {
@Test fun sessionChoicesPersistGloballyWithLandscapeAsTheDefault() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
for (value in listOf(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
)) {
for ((value, _) in SessionPrefs.orientationOptions) {
SessionPrefs.setOrientation(context, value)
assertEquals(value, SessionPrefs.orientation(context.createConfigurationContext(context.resources.configuration)))
}
@@ -33,12 +31,61 @@ class OrientationTest {
@Test fun invalidStoredOrientationFallsBackAndInvalidChoicePreservesTheSavedValue() {
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT).commit()
prefs.edit().putInt("orientation", 999).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertThrows(IllegalArgumentException::class.java) {
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
SessionPrefs.setOrientation(context, 999)
}
assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context))
}
@Test fun launcherFollowsDeviceRotationAndPortraitDoesNotChangeSessions() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context))
for ((value, _) in AppUiPrefs.orientationOptions) {
AppUiPrefs.setOrientation(context, value)
assertEquals(value, AppUiPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
}
AppUiPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context))
AppUiPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, AppUiPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.orientation(context))
}
@Test fun explicitOrientationTakesPriorityOverLargeFollowScreenWindows() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, true, 700))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.windowOrientation(context, true, 400))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.windowOrientation(context, false, 700))
for ((value, _) in SessionPrefs.orientationOptions) {
SessionPrefs.setOrientation(context, value)
assertEquals(value, SessionPrefs.windowOrientation(context, true, 700))
}
}
@Test fun sessionPortraitUsesItsOwnLockOrTheCurrentRotation() {
val config = android.content.res.Configuration(context.resources.configuration)
config.orientation = android.content.res.Configuration.ORIENTATION_PORTRAIT
val portrait = context.createConfigurationContext(config)
config.orientation = android.content.res.Configuration.ORIENTATION_LANDSCAPE
val landscape = context.createConfigurationContext(config)
assertFalse(SessionPrefs.portrait(portrait))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
assertTrue(SessionPrefs.portrait(landscape))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_USER)
assertTrue(SessionPrefs.portrait(portrait))
assertFalse(SessionPrefs.portrait(landscape))
}
@Test fun invalidLauncherOrientationFallsBackAndInvalidChoicePreservesPreference() {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", 999).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context))
AppUiPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
assertThrows(IllegalArgumentException::class.java) { AppUiPrefs.setOrientation(context, 999) }
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context))
}
}
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Test
class OutputPacingTest {
@Test fun phoneOutputIsUnpaced() {
assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0))
}
@Test fun mirroringKeepsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
class PerfHudGraphTest {
@Test fun theGraphShowsOnlyFramesFromThisHudRun() {
val samples = floatArrayOf(9f, 9f, 9f, 9f, 9f, 16.7f, 33.4f, 16.6f)
assertArrayEquals(floatArrayOf(16.7f, 33.4f, 16.6f), PerfHud.recent(samples, 105, 102), 0f)
assertEquals(0, PerfHud.recent(samples, 103, 102).size)
}
@Test fun anEarlySessionShowsWhatWasShownSoFar() {
val samples = floatArrayOf(16.6f, 16.7f, 120f, 0f, 0f, 0f)
assertArrayEquals(floatArrayOf(16.6f, 16.7f, 50f), PerfHud.recent(samples, 3, 0), 0f)
}
}
@@ -103,4 +103,28 @@ class ProtonDefaultTest {
assertNull(ProtonDefault.gameSelectedId(context, "42", listOf(proton("GE-Proton11-7", false))))
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton9-1"), ProtonDefault.parseGames(file.readText())["42"])
}
@Test
fun aReplacedBuildsPerGamePicksMoveToTheNewest() {
val old = ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.2")
val ge = ProtonDefault.GameChoice(false, "GE-Proton11-7")
val valve = ProtonDefault.GameChoice(true, "DroidDeck-Proton 11-11.2")
val moved = ProtonDefault.movedGames(mapOf("42" to old, "43" to ge, "44" to null, "45" to valve), setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4")
assertEquals(mapOf("42" to ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.4"), "43" to ge, "44" to null, "45" to valve), moved)
assertNull(ProtonDefault.movedGames(mapOf("43" to ge, "44" to null), setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4"))
}
@Test
fun movingPicksRewritesTheGamesFile() {
val context = RuntimeEnvironment.getApplication()
val file = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat/games.json")
file.parentFile?.deleteRecursively()
ProtonDefault.requestGame(context, "42", proton("DroidDeck-Proton 11-11.2", false))
ProtonDefault.requestGame(context, "43", null)
ProtonDefault.moveGames(context, setOf("DroidDeck-Proton 11-11.2"), "DroidDeck-Proton 11-11.4")
val games = ProtonDefault.parseGames(file.readText())
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-11.4"), games["42"])
assertTrue(games.containsKey("43"))
assertNull(games["43"])
}
}
@@ -198,4 +198,35 @@ class ProtonExtrasTest {
ComponentsManager.forgetProton(context, kept.name)
assertTrue(File(originals, "GE-Proton11-8/GE-Proton11-8/dxvk.wcp").isFile)
}
@Test
fun anUpdateKeepsTheUsersProtonSettingsFile() {
val context = RuntimeEnvironment.getApplication()
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
tools.deleteRecursively()
File(installTool(tools, "DroidDeck-Proton 11-11.1"), "user_settings.py").writeText("old")
File(installTool(tools, "DroidDeck-Proton 11-11.4"), "user_settings.py").writeText("mine")
installTool(tools, "DroidDeck-Proton 11-11.5")
ProtonExtras.tidy(context)
assertEquals(listOf("DroidDeck-Proton 11-11.5"), ProtonExtras.installedAll(context, tool("droiddeck")))
assertEquals("mine", File(tools, "DroidDeck-Proton 11-11.5/user_settings.py").readText())
}
@Test
fun droidDeckProtonIsFetchedWhenMissingUnlessTheUserRemovedIt() {
val context = RuntimeEnvironment.getApplication()
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
tools.deleteRecursively()
File(context.filesDir, "proton-latest.json").writeText(
"""{"droiddeck":{"tag":"DroidDeck-Proton-11-11.4","at":1},"ge":{"tag":"GE-Proton11-7","at":1}}""")
ProtonExtras.setDeclined(context, false)
assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.missing(context, tool("droiddeck")))
assertNull(ProtonExtras.missing(context, tool("ge")))
ProtonExtras.setDeclined(context, true)
assertNull(ProtonExtras.missing(context, tool("droiddeck")))
ProtonExtras.setDeclined(context, false)
installTool(tools, "DroidDeck-Proton 11-11.2")
assertNull(ProtonExtras.missing(context, tool("droiddeck")))
assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.update(context, tool("droiddeck")))
}
}
@@ -115,6 +115,22 @@ class RumbleComponentTest {
assertFalse(pad.vibrating)
}
@Test fun quietingStopsAHeldEffectAndDropsEffectsUntilLifted() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS)
rumble.quiet(true)
assertFalse(pad.vibrating)
idle(RumbleComponent.KEEPALIVE_MS * 4 + 100)
assertEquals("the keepalive restarted the motors while quiet", 1, pad.played.size)
effect(strong = 40000, weak = 20000)
assertFalse("an effect played while quiet", pad.vibrating)
rumble.quiet(false)
effect(strong = 40000, weak = 20000)
assertTrue(pad.vibrating)
}
@Test fun aHeldEffectFollowsTheGamesNewStrength() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
@@ -4,6 +4,23 @@ import org.junit.Assert.*
import org.junit.Test
class SessionDisplayTest {
@Test fun portraitPresetsSwapTheOutputAndRetainTheResolutionCap() {
assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "720p", portrait = true))
assertEquals(900 to 1600, SessionDisplay.resolveChoice(1080 to 1920, "900p", portrait = true))
assertEquals(720 to 1280, SessionDisplay.resolveChoice(1440 to 1080, "720p", portrait = true))
assertEquals(720 to 1600, SessionDisplay.resolveChoice(2400 to 1080, "720p", portrait = true))
assertEquals(1080 to 1920, SessionDisplay.resolveChoice(1921 to 1081, SessionDisplay.MATCH_SCREEN, portrait = true))
assertEquals(1080 to 2400, SessionDisplay.resolveChoice(2400 to 1080, SessionDisplay.FOLLOW_SCREEN, portrait = true))
assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "invalid", portrait = true))
}
@Test fun customDimensionsStayExplicitInEitherOrientation() {
for (portrait in listOf(false, true)) {
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1920 to 1080, "1280x720", portrait))
assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "720x1280", portrait))
}
}
@Test fun fixedSizesAndMatchScreenResolveWithoutAnyAspectSetting() {
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1440 to 1080, "1280x720"))
assertEquals(1600 to 900, SessionDisplay.resolveChoice(1280 to 720, "1600x900"))
@@ -35,6 +52,7 @@ class SessionDisplayTest {
}
@Test fun unfoldedControlsKeepTheGameSixteenByNineAcrossTheWidth() {
assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920))
assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848))
assertEquals(1038, SessionDisplay.unfoldedGameHeight(1848, 2448))
assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080))
@@ -67,6 +85,18 @@ class SessionDisplayTest {
assertFalse(SessionDisplay.unfoldedControlsWanted(true, true, true, true, true, false, 0, 1848, 700))
}
@Test fun portraitControlsWorkOnHandheldsAndPhonesWithoutAHinge() {
fun wanted(width: Int = 1080, height: Int = 1920, controller: Boolean = false,
keep: Boolean = false, pad: Boolean = true, pip: Boolean = false) =
SessionDisplay.unfoldedControlsWanted(true, false, controller, keep, pad, pip, width, height, 393)
assertTrue(wanted())
assertFalse(wanted(width = 1920, height = 1080))
assertFalse(wanted(controller = true))
assertTrue(wanted(controller = true, keep = true))
assertFalse(wanted(pad = false))
assertFalse(wanted(pip = true))
}
@Test fun followScreenKeepsTheWindowShapeAndSkipsTinyWindows() {
assertEquals(2520 to 1080, SessionDisplay.resolveChoice(1080 to 2520, SessionDisplay.FOLLOW_SCREEN))
@@ -75,6 +105,13 @@ class SessionDisplayTest {
assertNull(SessionDisplay.followSize(640, 360))
}
@Test fun aPhoneCanFollowTheShortGameAreaAboveItsControls() {
assertNull(SessionDisplay.followSize(720, 404))
assertEquals(720 to 404, SessionDisplay.followSize(720, 404, controlsBelow = true))
assertNull(SessionDisplay.followSize(320, 180, controlsBelow = true))
assertNull(SessionDisplay.followSize(720, 0, controlsBelow = true))
}
@Test fun resolutionCapsPreserveTheSelectedShapeWithoutExceedingPanelHeight() {
assertEquals(1280 to 720, SessionDisplay.resolve(1920 to 1080, 720, SessionPrefs.SHAPE_AUTO))
assertEquals(960 to 720, SessionDisplay.resolve(1440 to 1080, 720, SessionPrefs.SHAPE_EXACT))
@@ -96,7 +133,10 @@ class SessionDisplayTest {
@Test fun gameStretchAvailabilityMatchesTheRuntimeIncludingRounding() {
assertTrue(SessionDisplay.canStretch16x9(960 to 720))
assertFalse(SessionDisplay.canStretch16x9(1280 to 720))
assertFalse(SessionDisplay.canStretch16x9(1600 to 720))
assertTrue(SessionDisplay.canStretch16x9(1600 to 720))
assertTrue(SessionDisplay.canStretch16x9(2400 to 1080))
assertFalse(SessionDisplay.canStretch16x9(1920 to 1080))
assertFalse(SessionDisplay.canStretch16x9(1366 to 768))
val wide = SessionDisplay.resolve(1440 to 1080, 0, SessionPrefs.SHAPE_WIDE)
assertFalse(SessionDisplay.canStretch16x9(wide))
}
@@ -50,6 +50,34 @@ class SessionLogShareZipTest {
assertFalse(zip.exists())
}
@Test fun battleNetAndBlizzardLogsComeAlongScrubbedAndNewestFirst() {
val session = File(LinuxRuntime.logDir(app), "2026-10-25-05-battle-net").apply { mkdirs() }
File(session, "session.log").writeText("droiddeck-battlenet: open (from the menu)\n")
val root = LinuxRuntime.rootDir(app)
File(root, "root/.cache/droiddeck/battlenet").apply { mkdirs() }.apply {
resolve("battlenet.log").writeText("launching WoW\n")
resolve("other.log").writeText("other\n")
}
val drive = File(com.droiddeck.launcher.runtime.BattleNet.prefix(app), "pfx/drive_c")
val client = File(drive, "users/steamuser/AppData/Local/Battle.net/Logs").apply { mkdirs() }
val now = System.currentTimeMillis()
for (i in 1..8) client.resolve("battle.net-$i.log").apply { writeText("client $i accountId=1:0:5ca1ab1e\n"); setLastModified(now - i * 60_000L) }
client.resolve("battle.net-old.log").apply { writeText("old\n"); setLastModified(now - 30L * 86_400_000L) }
File(drive, "ProgramData/Battle.net/Agent/Agent.9824/Logs").apply { mkdirs() }.resolve("Agent-1.log").writeText("agent someone@example.com\n")
File(drive, "ProgramData/Battle.net/Agent/Agent.9900/Logs").apply { mkdirs() }.resolve("Agent-1.log").writeText("agent 9900\n")
File(drive, "ProgramData/Battle.net/Setup/bna_2/Logs").apply { mkdirs() }.resolve("battle.net-setup-1.log").writeText("setup\n")
val zip = SessionLogShare.zipFolder(app, session)!!
val text = ZipFile(zip).use { z -> z.entries().toList().associate { e -> e.name to z.getInputStream(e).bufferedReader().readText() } }
assertTrue(text.keys.containsAll(listOf("battlenet/droiddeck/battlenet.log", "battlenet/agent/Agent.9824/Agent-1.log", "battlenet/agent/Agent.9900/Agent-1.log", "battlenet/setup/bna_2/battle.net-setup-1.log")))
assertFalse(text.containsKey("battlenet/droiddeck/other.log"))
assertEquals((1..6).map { "battlenet/client/battle.net-$it.log" }.toSet(), text.keys.filter { it.startsWith("battlenet/client/") }.toSet())
val all = text.values.joinToString("\n")
assertFalse(all.contains("5ca1ab1e"))
assertFalse(all.contains("someone@example.com"))
SessionLogShare.clear(app)
}
@Test fun theSharePassChangesNothingInACleanLine() {
val line = "dxvk: Device 0x5 (Adreno 750) https://github.com/doitsujin/dxvk/releases code 403"
assertEquals(line, com.droiddeck.launcher.core.LogRedactor.redactForShare(line))
@@ -13,6 +13,16 @@ import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SessionScalingPrefsTest {
@Test fun legacyAutomaticResolutionsRemainRotatablePresets() {
val context = RuntimeEnvironment.getApplication()
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putString("shape", SessionPrefs.SHAPE_AUTO).putInt("resolutionCap.steam", 900).commit()
assertEquals("900p", SessionPrefs.resolutionChoice(context, "steam", 1920 to 1080))
val desktop = SessionPrefs.resolutionChoice(context, "lxqt", 1920 to 1080)
assertEquals("720p", desktop)
assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, desktop, portrait = true))
}
@Before fun clearSettings() {
RuntimeEnvironment.getApplication().getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@@ -27,9 +27,10 @@ class SettingsResetTest {
@Test fun settingsGoBackToTheirDefaults() {
SessionPrefs.setTheme(app, "ocean")
SessionPrefs.setBackDoubleTapMs(app, 100)
SessionPrefs.setUnfoldedControlsWithController(app, true)
SessionPrefs.setNoXalia(app, false)
SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30)
session.edit().putInt("fpsLimit.steam", 30).commit()
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
@@ -46,9 +47,10 @@ class SettingsResetTest {
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
assertEquals("graphite", SessionPrefs.theme(app))
assertEquals(500, SessionPrefs.backDoubleTapMs(app))
assertFalse(SessionPrefs.unfoldedControlsWithController(app))
assertTrue(SessionPrefs.noXalia(app))
assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM))
assertFalse(session.contains("fpsLimit.steam"))
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class WineProcessesTest {
private fun argv(vararg args: String) = args.joinToString("\u0000", postfix = "\u0000").toByteArray()
@Test fun aWineserverIsKnownByItsProgramOrItsName() {
assertTrue(WineProcesses.isWineserver(argv("/root/.local/share/droiddeck-esync/dist/valve-11/files/bin-arm64/wineserver"), "wineserver\n"))
assertTrue(WineProcesses.isWineserver(argv("wineserver", "-p0"), null))
assertTrue(WineProcesses.isWineserver(null, "wineserver\n"))
assertTrue(WineProcesses.isWineserver(ByteArray(0), "wineserver"))
}
@Test fun nothingElseIs() {
assertFalse(WineProcesses.isWineserver(argv("C:\\windows\\system32\\services.exe"), "services.exe\n"))
assertFalse(WineProcesses.isWineserver(argv("/usr/bin/python3", "/x/files/bin-arm64/wineserver"), "python3\n"))
assertFalse(WineProcesses.isWineserver(argv("/opt/wineserver-helper"), "wineserver-help"))
assertFalse(WineProcesses.isWineserver(null, null))
}
}
@@ -47,4 +47,34 @@ class CloudSavePathsTest {
File(profile, "AppData/Local/My-Game").mkdirs()
assertEquals(File(profile, "AppData/Local/My-Game").path, CloudSavePaths.epic("{AppData}/MyGame", prefix, install, "acc", "app")!!.path)
}
@Test fun gogGalaxySdkEmptyLocationsUseDefaultLocation() {
val loc = CloudSavePaths.gogSaveFromRemote(true, emptyList(), "1")!!
assertEquals(
"%LocalAppData%/GOG.com/Galaxy/Applications/1/Storage/Shared/Files",
loc.template,
)
assertEquals(CloudSavePaths.GOG_DEFAULT_NAMESPACE, loc.name)
val dir = CloudSavePaths.gog(loc.template, prefix, install)
assertEquals(
File(profile, "AppData/Local/GOG.com/Galaxy/Applications/1/Storage/Shared/Files").path,
dir!!.path,
)
}
@Test fun gogCloudDisabledOrUnknownClientIsNone() {
assertNull(CloudSavePaths.gogSaveFromRemote(false, emptyList(), "1"))
assertNull(CloudSavePaths.gogSaveFromRemote(true, emptyList(), ""))
assertNull(CloudSavePaths.gogSaveFromRemote(true, listOf("saves" to ""), ""))
}
@Test fun gogNamedLocationKeepsItsNameAndPreferSaves() {
val loc = CloudSavePaths.gogSaveFromRemote(
true,
listOf("other" to "<?SAVED_GAMES?>/A", "Saves" to "<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN"),
"1",
)!!
assertEquals("<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN", loc.template)
assertEquals("Saves", loc.name)
}
}
@@ -0,0 +1,76 @@
package com.droiddeck.launcher.stores
import java.io.File
import java.nio.file.Files
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 CloudSavesMigrationTest {
private val dir = Files.createTempDirectory("cloud-migrate").toFile()
private fun entry(bytes: ByteArray) = CloudPlan.Entry(CloudSaves.md5(bytes), null, 1000L)
private fun nested(name: String, path: String, text: String): File =
File(dir, "$name/$path").apply { parentFile?.mkdirs(); writeText(text) }
@Test fun movesOnlyFilesTheOldBaselineOwns() {
val a = "old save".toByteArray()
val game = "game wrote this".toByteArray()
nested("saves", "a.dat", String(a))
nested("saves", "game.dat", String(game))
val base = mapOf("saves/a.dat" to entry(a))
val result = CloudSaves.migrateNested(dir, "saves", base)!!
assertEquals(1, result.moved)
assertEquals(0, result.cleaned)
assertEquals(String(a), File(dir, "a.dat").readText())
assertEquals(String(game), File(dir, "saves/game.dat").readText())
assertTrue("saves/a.dat" !in result.baseline)
assertEquals(entry(a), result.baseline["a.dat"])
}
@Test fun anIdenticalLeftoverIsRemovedAndItsBaselineKeyRewritten() {
val a = "old save".toByteArray()
File(dir, "a.dat").writeText(String(a))
nested("saves", "a.dat", String(a))
val result = CloudSaves.migrateNested(dir, "saves", mapOf("saves/a.dat" to entry(a)))!!
assertEquals(0, result.moved)
assertEquals(1, result.cleaned)
assertFalse(File(dir, "saves").exists())
assertEquals(entry(a), result.baseline["a.dat"])
assertTrue("saves/a.dat" !in result.baseline)
}
@Test fun aDifferentDestinationKeepsTheGameFileAndTheBaseline() {
val a = "old save".toByteArray()
File(dir, "a.dat").writeText("newer game save")
nested("saves", "a.dat", String(a))
val base = mapOf("saves/a.dat" to entry(a))
val result = CloudSaves.migrateNested(dir, "saves", base)!!
assertEquals(0, result.moved)
assertEquals(0, result.cleaned)
assertEquals("newer game save", File(dir, "a.dat").readText())
assertEquals(String(a), File(dir, "saves/a.dat").readText())
assertEquals(base, result.baseline)
}
@Test fun aSymlinkedAncestorIsNotMigrated() {
val outside = Files.createTempDirectory("cloud-outside").toFile()
File(outside, "a.dat").writeText("outside")
File(dir, "saves").mkdirs()
Files.createSymbolicLink(File(dir, "saves/link").toPath(), outside.toPath())
val result = CloudSaves.migrateNested(dir, "saves",
mapOf("saves/link/a.dat" to entry("outside".toByteArray())))!!
assertEquals(0, result.moved)
assertEquals(0, result.cleaned)
assertTrue(File(outside, "a.dat").isFile)
}
@Test fun aLocationNameThatCanLeaveTheFolderIsRefused() {
nested("saves", "a.dat", "x")
assertNull(CloudSaves.migrateNested(dir, "../saves", emptyMap()))
assertNull(CloudSaves.migrateNested(dir, "..", emptyMap()))
assertNull(CloudSaves.migrateNested(dir, "saves/..", emptyMap()))
}
}
@@ -4,6 +4,7 @@ import java.io.File
import java.util.concurrent.Executor
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
@@ -77,12 +78,22 @@ class CloudSavesTest {
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
CloudSaves.uploadAllDirty(app, "recovery", running = true)
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_template_$gameId", "").apply()
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit()
.putString("cloud_template_$gameId", "none")
.putLong("cloud_template_at_$gameId", System.currentTimeMillis())
.apply()
assertEquals("no-cloud-saves", CloudSaves.uploadDirty(app, Store.GOG, gameId, "exit")!!.reason)
assertTrue(CloudSaves.dirty(app).none { it.second == gameId })
assertEquals(null, CloudSaves.uploadDirty(app, Store.GOG, gameId, "session-end"))
}
@Test fun aNegativeCloudTemplateIsRetriedAfterADay() {
val now = 1_000_000L
assertTrue(CloudSaves.noneTemplateIsCurrent(now, now + 60_000L))
assertFalse(CloudSaves.noneTemplateIsCurrent(now, now + CloudSaves.TEMPLATE_NONE_TTL_MS))
assertFalse(CloudSaves.noneTemplateIsCurrent(0L, now))
}
@Test fun aFirstLaunchWithoutAPrefixIsDeferredNotBlocked() {
val deferred = ArrayList<Runnable>()
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN").apply { mkdirs() }
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.stores
import java.io.ByteArrayOutputStream
import java.util.zip.GZIPOutputStream
import org.junit.Assert.assertArrayEquals
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 GogCloudKeysTest {
@Test fun defaultLocationIsStrippedLikeAnyNamedLocation() {
val files = listOf(CloudFile("__default/savegame0.sav", 1L), CloudFile("saves/slot0.sav", 2L))
val (chosen, relative) = gogRelativeNames(files, "__default")
assertEquals("__default", chosen)
assertEquals(listOf("savegame0.sav"), relative.map { it.name })
}
@Test fun gzipGogPutMatchesPythonGzipCompressLevel6Mtime0() {
val raw = "savegame0".toByteArray()
val expected = "1f8b08000000000000032b4e2c4b4d4fcc4d35000065fc333209000000".hex()
assertArrayEquals(expected, gzipGogPut(raw))
assertArrayEquals(raw, gunzip(expected))
}
@Test fun contentEncodingGzipIsPeeledOnce() {
val raw = "savegame0".toByteArray()
val gz = ByteArrayOutputStream().also { GZIPOutputStream(it).use { z -> z.write(raw) } }.toByteArray()
assertArrayEquals(raw, gogDecodeCloudBody(gz, "gzip"))
assertArrayEquals(raw, gogDecodeCloudBody(raw, "gzip"))
}
@Test fun corruptDeclaredGzipIsRejected() {
val corrupt = gzipGogPut("savegame0".toByteArray()).dropLast(2).toByteArray()
assertTrue(isGzip(corrupt))
assertTrue(runCatching { gogDecodeCloudBody(corrupt, "gzip") }.isFailure)
}
@Test fun isoDateHonorsOffsetAndFractionalSeconds() {
val expected = java.time.Instant.parse("2024-01-02T01:04:05.123Z").toEpochMilli()
assertEquals(expected, isoDate("2024-01-02T03:04:05.123+02:00"))
assertEquals(expected, isoDate("2024-01-02T01:04:05.123"))
}
@Test fun gogPutWrappedBodyWithoutEncodingIsPeeled() {
val raw = "savegame0".toByteArray()
assertArrayEquals(raw, gogDecodeCloudBody(gzipGogPut(raw), null))
assertArrayEquals(raw, gogDecodeCloudBody(raw, null))
}
@Test fun gzipThatIsTheSaveIsLeftIntact() {
val raw = "savegame0".toByteArray()
val gameGz = ByteArrayOutputStream().also { GZIPOutputStream(it).use { z -> z.write(raw) } }.toByteArray()
assertTrue(isGzip(gameGz))
assertFalse(gzipGogPut(raw).contentEquals(gameGz))
assertArrayEquals(gameGz, gogDecodeCloudBody(gameGz, null))
}
}
private fun String.hex() = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class GogCloudNamesTest {
private fun files(vararg names: String) = names.map { CloudFile(it, 1000L) }
@Test fun silksongLocationIsDroppedFromThePath() {
val (location, mapped) = gogRelativeNames(
files("saves/user1.dat", "saves/shared.dat", "saves/Restore_Points1/restoreData2.dat"), "saves")
assertEquals("saves", location)
assertEquals(listOf("user1.dat", "shared.dat", "Restore_Points1/restoreData2.dat"), mapped.map { it.name })
}
@Test fun anotherLocationIsFilteredOut() {
val (_, mapped) = gogRelativeNames(files("saves/a.dat", "__default/settings.ini"), "saves")
assertEquals(listOf("a.dat"), mapped.map { it.name })
}
@Test fun theOnlyLocationIsInferredWhenItsNameWasNotCached() {
val (location, mapped) = gogRelativeNames(files("saves/a.dat", "saves/b.dat"), null)
assertEquals("saves", location)
assertEquals(listOf("a.dat", "b.dat"), mapped.map { it.name })
}
@Test fun namesWithoutALocationPrefixAreLeftAlone() {
val (location, mapped) = gogRelativeNames(files("a.dat", "b.dat"), null)
assertNull(location)
assertEquals(listOf("a.dat", "b.dat"), mapped.map { it.name })
}
@Test fun aConfiguredLocationDoesNotYieldToAnotherLocation() {
val (location, mapped) = gogRelativeNames(files("__default/settings.ini"), "saves")
assertEquals("saves", location)
assertTrue(mapped.isEmpty())
}
@Test fun aMixedListingWithOneSubfolderIsLeftAlone() {
val (location, mapped) = gogRelativeNames(files("a.dat", "sub/b.dat"), "saves")
assertNull(location)
assertEquals(listOf("a.dat", "sub/b.dat"), mapped.map { it.name })
}
@Test fun aMissingCachedLocationDoesNotHideUnprefixedNames() {
val (location, mapped) = gogRelativeNames(files("a.dat"), "saves")
assertNull(location)
assertEquals(listOf("a.dat"), mapped.map { it.name })
}
}
@@ -5,7 +5,10 @@ import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@@ -18,6 +21,12 @@ import org.robolectric.shadows.ShadowStatFs
class StoreInstallRootTest {
private val app get() = RuntimeEnvironment.getApplication()
@Before fun resetStoragePreferences() {
SessionPrefs.setDefaultStorageFolder(app, "", "")
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_ASK)
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun theDefaultRootIsInternalWhateverTheSteamLibrarySettingSays() {
val card = File(app.filesDir, "fake-card/steam").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
@@ -26,6 +35,72 @@ class StoreInstallRootTest {
assertFalse(StoreInstallRoot.targets(app).first().removable)
}
@Test fun defaultStoragePicksTheInternalOrTheConfiguredExternalTarget() {
val library = File(app.filesDir, "default-card/steam").apply { mkdirs() }
SessionPrefs.setGameStorage(app, library.path, "Card")
val external = File(library, "Games")
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_INTERNAL)
assertEquals(StoreInstallRoot.internalRoot(app).absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
assertEquals(external.absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_ASK)
assertNull(StoreInstallRoot.defaultTarget(app))
SessionPrefs.setDefaultStorage(app, "bogus")
assertEquals(SessionPrefs.DEFAULT_STORAGE_ASK, SessionPrefs.defaultStorage(app))
}
@Test fun defaultExternalStorageFallsBackToTheInstallDialogWhenNoCardIsPresent() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
assertNull(StoreInstallRoot.defaultTarget(app))
}
@Test fun aChosenFolderIsUsedForDefaultExternalStorage() {
val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() }
assertNull(StoreInstallRoot.prepareDefaultFolder(app, folder))
val root = File(folder, "Games")
assertTrue(root.isDirectory)
SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD")
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
assertEquals(root.absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
assertTrue(StoreInstallRoot.targets(app).any { it.root.absolutePath == root.absolutePath && it.folder })
assertTrue(StoreInstallRoot.roots(app).any { it.absolutePath == root.absolutePath })
assertTrue(StoreInstallRoot.externalRoots(app).any { it.first.absolutePath == root.absolutePath })
assertFalse(File(root, ".droiddeck-write-probe").exists())
}
@Test fun aDisconnectedChosenFolderDoesNotFallBackToAnotherTarget() {
val card = File(app.filesDir, "card/steam").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() }
SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD")
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
assertNotNull(StoreInstallRoot.defaultTarget(app))
assertTrue(folder.delete())
assertNull(StoreInstallRoot.defaultTarget(app))
assertEquals(File(card, "Games").absolutePath, StoreInstallRoot.detectedExternalTarget(app)?.root?.absolutePath)
}
@Test fun filesOnAChosenFolderAreMappedIntoTheGuest() {
val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() }
SessionPrefs.setDefaultStorageFolder(app, folder.path, "SSD")
val game = File(folder, "Games/GOG/Test/game.exe").apply {
parentFile?.mkdirs()
writeText("MZ")
}
val guest = StoreInstallRoot.externalGuestPath(app, game)
assertNotNull(guest)
assertTrue(guest!!.startsWith(StoreInstallRoot.GUEST_EXTERNAL + "/"))
assertTrue(guest.endsWith("/GOG/Test/game.exe"))
}
@Test fun theSteamLibraryFolderIsOfferedAsAnInstallTarget() {
val library = File(app.filesDir, "Documents/Games").apply { mkdirs() }
SessionPrefs.setGameStorage(app, library.path, "Games")
@@ -0,0 +1,87 @@
package com.droiddeck.launcher.stores.battlenet
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.file.Files
import java.util.Locale
class BattleNetInstallTest {
private val buildInfo = """
Branch!STRING:0|Active!DEC:1|Build Key!HEX:16|CDN Key!HEX:16|Install Key!HEX:16|IM Size!DEC:4|Version!STRING:0|Product!STRING:0
eu|0|11111111111111111111111111111111|db0583272ed15286569b5f24ce516876|||16.1.1.1|gryphon
us|1|e474008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876|||16.1.2.119725|gryphon
""".trimIndent()
private val versions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 4048130
us|f00d008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876||119800|16.1.3.119800|f6a454799d25791e5a37a7547d75ce49
eu|e474008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876||119725|16.1.2.119725|f6a454799d25791e5a37a7547d75ce49
""".trimIndent()
@Test fun theActiveRowGivesTheRegionAndBuildOnDisk() {
assertEquals("us" to "e474008a3535d8ea978949a90d9873e6", BattleNetInstall.buildKey(buildInfo))
assertNull(BattleNetInstall.buildKey("Branch!STRING:0|Active!DEC:1\n"))
assertNull(BattleNetInstall.buildKey("Branch!STRING:0|Active!DEC:1|Build Key!HEX:16\nus|1|not-a-key\n"))
}
@Test fun theLiveBuildIsReadForTheSameRegion() {
assertEquals("f00d008a3535d8ea978949a90d9873e6", BattleNetInstall.latestBuild(versions, "us"))
assertEquals("e474008a3535d8ea978949a90d9873e6", BattleNetInstall.latestBuild(versions, "eu"))
assertNull(BattleNetInstall.latestBuild(versions, "kr"))
assertNull(BattleNetInstall.latestBuild("", "us"))
}
@Test fun theDeviceLanguagePicksABlizzardLocale() {
assertEquals("enUS", BattleNetInstall.locale(Locale.US))
assertEquals("enGB", BattleNetInstall.locale(Locale.UK))
assertEquals("enUS", BattleNetInstall.locale(Locale("en", "AU")))
assertEquals("deDE", BattleNetInstall.locale(Locale.GERMANY))
assertEquals("ptBR", BattleNetInstall.locale(Locale("pt", "BR")))
assertEquals("ptPT", BattleNetInstall.locale(Locale("pt", "PT")))
assertEquals("zhTW", BattleNetInstall.locale(Locale.forLanguageTag("zh-Hant-HK")))
assertEquals("zhCN", BattleNetInstall.locale(Locale.SIMPLIFIED_CHINESE))
assertEquals("enUS", BattleNetInstall.locale(Locale("nl", "NL")))
}
@Test fun theCountryIsSentInBothForms() {
assertEquals("DEU" to "DE", BattleNetInstall.country(Locale.GERMANY))
assertEquals("USA" to "US", BattleNetInstall.country(Locale("en")))
}
@Test fun everyStoreTitleWithAProductInstallsHeadless() {
val products = BattleNet.TITLES.mapNotNull { it.product }
assertTrue(products.all { Regex("[a-z0-9_]{1,32}").matches(it) })
assertTrue(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "gryphon", "Warcraft Rumble", null)))
assertEquals("hsb", BattleNetInstall.product("hs_beta"))
assertEquals("d3", BattleNetInstall.product("diablo3_enus"))
assertFalse(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "d3cn", "Diablo III", null)))
assertFalse(BattleNetInstall.headless(CatalogItem(Store.EPIC, "gryphon", "Warcraft Rumble", null)))
}
@Test fun aCheckThatCouldNotRunIsTriedAgainNextTime() {
val folder = Files.createTempDirectory("bnet").toFile()
try {
BattleNetInstall.check("gryphon", folder, false)
BattleNetInstall.checks.submit {}.get()
assertFalse(synchronized(BattleNetInstall.checkedAt) { "gryphon" in BattleNetInstall.checkedAt })
} finally {
folder.deleteRecursively()
}
}
@Test fun theAgentStatusPicksTheDownloadStep() {
assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1008, 0, 0, 0))
assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1003, 500, 0, 0))
assertEquals(BattleNetInstall.Step.DOWNLOADING, BattleNetInstall.step(1003, 500, 31405777, 6746574227))
assertEquals(BattleNetInstall.Step.APPLYING, BattleNetInstall.step(1003, 500, 6746574227, 6746574227))
assertEquals(BattleNetInstall.Step.APPLYING, BattleNetInstall.step(1003, 2000, 1, 9))
assertEquals(BattleNetInstall.Step.APPLYING, BattleNetInstall.step(1004, 1000, 0, 0))
}
}
@@ -0,0 +1,38 @@
package com.droiddeck.launcher.stores.battlenet
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 BattleNetRequestTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun requestsLeftBeforeThePollAreAllKeptInOrder() {
val root = tmp.root
assertTrue(BattleNetClient.request(root, listOf("install-game", "wow")))
assertTrue(BattleNetClient.request(root, listOf("install-game", "fenris")))
assertTrue(BattleNetClient.request(root, listOf("launch", "OSI")))
val names = root.list()!!.sorted()
assertEquals(3, names.size)
assertTrue(names.all { Regex("battlenet-request\\.\\d{20}").matches(it) })
assertEquals(listOf("install-game\nwow\n", "install-game\nfenris\n", "launch\nOSI\n"), names.map { java.io.File(root, it).readText() })
}
@Test fun aLineBreakInAnArgumentIsRefused() {
assertFalse(BattleNetClient.request(tmp.root, listOf("launch", "OSI\nreboot")))
assertEquals(0, tmp.root.list()!!.size)
}
@Test fun aNewSessionClearsEveryLeftRequest() {
val root = tmp.root
BattleNetClient.request(root, listOf("launch", "WTCG"))
java.io.File(root, "battlenet-request").writeText("launch\nPro\n")
java.io.File(root, "battlenet-request.1.tmp").writeText("launch\nPro\n")
java.io.File(root, "battlenet-fex.request").writeText("x")
BattleNetClient.clearRequests(root)
assertEquals(listOf("battlenet-fex.request"), root.list()!!.toList())
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.stores.battlenet
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class BlizzardArtTest {
@Test fun theShopsKeyArtIsUsed() {
val page = """<meta property="og:image" content="https://blz-contentstack-images.akamaized.net/v3/assets/a/b/c/art.png">"""
assertEquals("https://blz-contentstack-images.akamaized.net/v3/assets/a/b/c/art.png", BlizzardArt.imageUrl(page))
}
@Test fun aVideoStillFallsBackToTheFirstThumbnailThatIsNotABundle() {
val page = """<meta property="og:image" content="https://img.youtube.com/vi/x/maxresdefault.jpg">""" +
"""\"imageUrl\":\"//catalog.blzstatic.com//ff9/a-prod-thumb_bundle.jpg\",""" +
"""\"imageUrl\":\"//catalog.blzstatic.com//feb/b-prod-thumb.jpg\""""
assertEquals("https://catalog.blzstatic.com//feb/b-prod-thumb.jpg", BlizzardArt.imageUrl(page))
}
@Test fun anOpenGraphImageFromAnotherHostFallsBackToTheThumbnail() {
val page = """<meta property="og:image" content="https://example.com/art.png">""" +
"""\"imageUrl\":\"//catalog.blzstatic.com//feb/b-prod-thumb.jpg\""""
assertEquals("https://catalog.blzstatic.com//feb/b-prod-thumb.jpg", BlizzardArt.imageUrl(page))
}
@Test fun artFromOtherHostsIsRefused() {
assertNull(BlizzardArt.imageUrl("""<meta property="og:image" content="https://example.com/art.png">"""))
assertNull(BlizzardArt.imageUrl("""\"imageUrl\":\"//catalog.blzstatic.com//ff9/a-prod-thumb_bundle.jpg\""""))
}
}
@@ -456,4 +456,26 @@ class EpicClientTest {
settings.writeText("""{"defaultInstallDir":"/mnt/droiddeck-sd/Stores/Epic"}""")
assertEquals("/root/Games/Stores/Epic", EpicClient.prepareInstallDir(context))
}
@Test fun aDisconnectedDefaultFolderKeepsTheLauncherInstallDir() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val previousStorage = com.droiddeck.launcher.session.SessionPrefs.defaultStorage(context)
val previousFolder = com.droiddeck.launcher.session.SessionPrefs.defaultStorageFolder(context)
val previousLabel = com.droiddeck.launcher.session.SessionPrefs.defaultStorageFolderLabel(context)
val settings = File(EpicClient.dataDir(context), "settings/app-settings.json").apply { parentFile!!.mkdirs() }
val current = "/mnt/droiddeck-stores/1234/Epic"
settings.writeText("""{"defaultInstallDir":"$current"}""")
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorage(
context, com.droiddeck.launcher.session.SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorageFolder(
context, File(context.filesDir, "missing-${System.nanoTime()}").path, "SSD")
try {
assertEquals(current, EpicClient.prepareInstallDir(context))
assertEquals(current, org.json.JSONObject(settings.readText()).getString("defaultInstallDir"))
} finally {
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorage(context, previousStorage)
if (previousFolder.isBlank()) com.droiddeck.launcher.session.SessionPrefs.clearDefaultStorageFolder(context)
else com.droiddeck.launcher.session.SessionPrefs.setDefaultStorageFolder(context, previousFolder, previousLabel)
}
}
}
@@ -0,0 +1,90 @@
package com.droiddeck.launcher.stores.gog
import java.io.File
import java.io.IOException
import java.nio.file.Files
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
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)
@Config(sdk = [33])
class GogInstallerPartsTest {
private fun downloads(json: String) = JSONObject("""{"downloads":$json}""").getJSONObject("downloads")
@Test fun everyFileOfTheWindowsInstallerIsKeptAndThePartsAreNamedAfterItsSetup() {
val parts = GogDownloadManager.installerParts(
downloads(
"""{"installers":[
{"os":"windows","language":"en","files":[
{"id":"en1installer0","size":1048576,"downlink":"https://api.gog.com/products/1947927225/downlink/installer/en1installer0"},
{"id":"en1installer1","size":3786407936,"downlink":"https://api.gog.com/products/1947927225/downlink/installer/en1installer1"}
]},
{"os":"linux","files":[{"downlink":"https://example.invalid/linux"}]}
]}""",
),
"1947927225",
)
assertEquals(listOf("setup_1947927225.exe", "setup_1947927225-1.bin"), parts.map { it.filename })
assertEquals(listOf(1048576L, 3786407936L), parts.map { it.size })
assertTrue(parts[1].url.endsWith("en1installer1"))
}
@Test fun explicitNamesAreKeptAndUnnamedPartsFollowTheFirstSetupExe() {
val parts = GogDownloadManager.installerParts(
downloads(
"""{"installers":[{"os":"windows","files":[
{"filename":"setup_witcher_2.1.0.exe","downlink":"https://example.invalid/setup"},
{"downlink":"https://example.invalid/data"},
{"filename":"readme.bin","downlink":"https://example.invalid/readme"}
]}]}""",
),
"1207658924",
)
assertEquals(listOf("setup_witcher_2.1.0.exe", "setup_witcher_2.1.0-1.bin", "readme.bin"), parts.map { it.filename })
}
@Test fun aSingleManualInstallerIsNamedForTheGameAndSanitised() {
val parts = GogDownloadManager.installerParts(
downloads("""{"installers":[{"os":"windows","manualUrl":"https://example.invalid/setup","total_size":42}]}"""),
"../game id",
)
assertEquals(1, parts.size)
assertEquals("setup_.._game_id.exe", parts[0].filename)
assertEquals(42L, parts[0].size)
}
@Test fun installerPartsStayInsideTheGameFolder() {
val root = kotlin.io.path.createTempDirectory("gog-installer").toFile()
try {
assertEquals(
File(root, "setup_1.exe").canonicalFile,
GogDownloadManager.installerDestination(root, "setup_1.exe"),
)
assertThrows(IOException::class.java) {
GogDownloadManager.installerDestination(root, "../outside.exe")
}
val outside = File(root.parentFile, "outside-${System.nanoTime()}.bin").apply { writeText("x") }
try {
Files.createSymbolicLink(File(root, "setup_1-1.bin").toPath(), outside.toPath())
assertThrows(IOException::class.java) {
GogDownloadManager.installerDestination(root, "setup_1-1.bin")
}
} finally {
outside.delete()
}
} finally {
root.deleteRecursively()
}
}
@Test fun anotherPlatformOrNoDownloadsAddsNothing() {
assertEquals(0, GogDownloadManager.installerParts(downloads("""{"installers":[{"os":"linux","manualUrl":"https://example.invalid/x"}]}"""), "1").size)
assertEquals(0, GogDownloadManager.installerParts(downloads("{}"), "1").size)
}
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.stores.itch
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Test
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class ItchCollectionsTest {
@Test fun collectionsKeepTheirIdTitleAndCount() {
val body = JSONArray()
.put(JSONObject().put("id", 8356509).put("title", "library").put("games_count", 12))
.put(JSONObject().put("id", 7).put("title", "").put("games_count", 3))
.put(JSONObject().put("title", "no id"))
val list = ItchCollections.parseCollections(body)
assertEquals(listOf("8356509"), list.map { it.id })
assertEquals("library", list.single().title)
assertEquals(12, list.single().count)
}
@Test fun collectionGamesReadBothKeyStylesAndSkipRowsWithoutAGame() {
val game = JSONObject().put("id", 99).put("title", "Celeste 64").put("url", "https://noel.itch.io/celeste64")
val snake = JSONObject().put("collection_games", JSONArray().put(JSONObject().put("game", game)).put(JSONObject().put("position", 1)))
val camel = JSONObject().put("collectionGames", JSONArray().put(JSONObject().put("game", game)))
assertEquals(listOf("noel.itch.io/celeste64"), ItchCollections.parseGames(snake).map { it.id })
assertEquals(1, ItchCollections.parseGames(camel).size)
assertEquals(false, ItchCollections.parseGames(snake).single().owned)
assertEquals(0, ItchCollections.parseGames(JSONObject()).size)
}
}
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.stores.itch
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class ItchGameTest {
private fun upload(id: String, filename: String, vararg traits: String, type: String = "default", storage: String = "hosted", demo: Boolean = false, updated: String = "2026-09-16T02:26:06Z") =
JSONObject().put("id", id).put("filename", filename).put("size", 1000).put("type", type).put("storage", storage)
.put("demo", demo).put("traits", JSONArray(traits.toList())).put("updated_at", updated)
@Test fun theGameNumberComesFromThePageMeta() {
assertEquals("1576684", ItchGame.idFromPage("""<head><meta name="itch:path" content="games/1576684"></head>"""))
assertEquals("1576684", ItchGame.idFromPage("""<meta content="games/1576684" name="itch:path">"""))
assertNull(ItchGame.idFromPage("<html>no meta here</html>"))
}
@Test fun platformsComeFromTheTraits() {
assertEquals(setOf("windows"), ItchUploads.platforms(upload("1", "a.zip", "p_windows")))
assertEquals(setOf("linux", "osx"), ItchUploads.platforms(upload("2", "a.zip", "p_linux", "p_osx")))
assertEquals(setOf("android"), ItchUploads.platforms(upload("3", "a.apk", "p_android")))
assertEquals(setOf("web"), ItchUploads.platforms(upload("4", "a.zip", type = "html")))
}
@Test fun anUploadWithNoPlatformIsTreatedAsWindows() {
assertEquals(setOf("windows"), ItchUploads.platforms(upload("5", "a.zip")))
}
@Test fun platformsAlsoReadTheFlagObject() {
val flags = JSONObject().put("windows", false).put("linux", true)
assertEquals(setOf("linux"), ItchUploads.platforms(JSONObject().put("platforms", flags)))
}
@Test fun buildsSkipExternalUploadsAndPutWindowsFirst() {
val uploads = JSONArray()
.put(upload("10", "linux.tar.gz", "p_linux", updated = "2026-10-01T00:00:00Z"))
.put(upload("11", "win.zip", "p_windows", updated = "2026-09-01T00:00:00Z"))
.put(upload("12", "site", "p_windows", storage = "external"))
val builds = ItchGame.builds(uploads)
assertEquals(listOf("11", "10"), builds.map { it.uploadId })
assertTrue(builds[0].installable)
assertFalse(builds[1].installable)
}
@Test fun aDemoIsFlagged() {
assertTrue(ItchGame.builds(JSONArray().put(upload("20", "demo.zip", "p_windows", demo = true))).single().demo)
}
@Test fun anUploadIsFoundById() {
val uploads = JSONArray().put(upload("30", "a.zip")).put(upload("31", "b.zip"))
assertEquals("b.zip", ItchUploads.byId(uploads, "31")?.optString("filename"))
assertNull(ItchUploads.byId(uploads, "99"))
assertNull(ItchUploads.byId(uploads, ""))
}
@Test fun noDownloadKeyMeansNoKeyInTheAddress() {
assertEquals("https://api.itch.io/uploads/13619666/download", ItchApi.downloadUrl("13619666", ""))
assertEquals("https://api.itch.io/uploads/13619666/download?download_key_id=7", ItchApi.downloadUrl("13619666", "7"))
}
}
@@ -20,8 +20,8 @@ class FexVersionTest {
}
@Test fun theShippedLauncherHasOne() {
val script = java.io.File("../tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64").takeIf { it.isFile }
?: java.io.File("tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64")
val script = java.io.File("../tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update").takeIf { it.isFile }
?: java.io.File("tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update")
assertEquals(true, fexVersionOf(script.readText()) != null)
}
}
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.ui
import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
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
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class FocusGlideRenderingTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun largeJumpCollapsesIntoABallAndExpandsAtTheDestination() {
val context = RuntimeEnvironment.getApplication()
SessionPrefs.setAnimationsEnabled(context, true)
Motion.refresh(context)
compose.mainClock.autoAdvance = false
lateinit var view: View
val from = FocusRequester()
val to = FocusRequester()
compose.setContent {
view = LocalView.current
FocusGlideHost(Modifier.fillMaxSize().background(Color.Black)) {
Box(Modifier.offset(10.dp, 10.dp).size(80.dp, 40.dp).focusRequester(from)
.focusGlide(RectangleShape, Color.White).focusable())
Box(Modifier.offset(650.dp, 400.dp).size(80.dp, 40.dp).focusRequester(to)
.focusGlide(RectangleShape, Color.White).focusable())
}
}
fun ringBounds(): Rect = compose.runOnIdle {
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
var left = view.width
var top = view.height
var right = 0
var bottom = 0
for (y in 0 until bitmap.height) for (x in 0 until bitmap.width) {
if (android.graphics.Color.red(bitmap.getPixel(x, y)) > 200) {
left = minOf(left, x); top = minOf(top, y)
right = maxOf(right, x + 1); bottom = maxOf(bottom, y + 1)
}
}
bitmap.recycle()
Rect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
}
compose.runOnIdle { from.requestFocus() }
compose.mainClock.advanceTimeBy(1_000)
assertTrue(ringBounds().width > 60f)
compose.runOnIdle { to.requestFocus() }
compose.mainClock.advanceTimeBy(160)
val ball = ringBounds()
assertTrue("Ball bounds: $ball", ball.width in 8f..16f && ball.height in 8f..16f)
compose.mainClock.advanceTimeBy(1_500)
val landed = ringBounds()
assertTrue("Landed bounds: $landed", landed.width > 60f && landed.left > 600f)
}
@Test fun hollowGlideKeepsItsOutlineWithoutTintingTheContent() {
val context = RuntimeEnvironment.getApplication()
SessionPrefs.setAnimationsEnabled(context, false)
Motion.refresh(context)
try {
lateinit var view: View
var bounds = Rect.Zero
var hollow by mutableStateOf(true)
compose.setContent {
view = LocalView.current
FocusGlideHost {
Box(Modifier.size(120.dp).background(Color.Black)
.glideBorder(true, RectangleShape, Color.White, hotFillAlpha = if (hollow) 0f else 0.14f)
.onGloballyPositioned { bounds = it.boundsInRoot() })
}
}
fun sample(): Pair<Int, Int> = compose.runOnIdle {
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
val center = bitmap.getPixel(bounds.center.x.toInt(), bounds.center.y.toInt())
val edge = bitmap.getPixel(bounds.left.toInt(), bounds.center.y.toInt())
bitmap.recycle()
center to edge
}
val (center, edge) = sample()
assertEquals(android.graphics.Color.BLACK, center)
assertEquals(android.graphics.Color.WHITE, edge)
compose.runOnIdle { hollow = false }
assertTrue(android.graphics.Color.red(sample().first) > 0)
} finally {
SessionPrefs.setAnimationsEnabled(context, true)
Motion.refresh(context)
}
}
}
@@ -0,0 +1,152 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalView
import com.droiddeck.launcher.stores.xbox.XboxMenuEntry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
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.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land")
class FocusGlideWindowsTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun standaloneThemedControlsShareTheGlide() {
lateinit var glide: FocusGlide
val focus = List(6) { FocusRequester() }
compose.setContent {
DroidDeckTheme {
glide = LocalFocusGlide.current!!
Column {
TextButton(onClick = {}, modifier = Modifier.focusRequester(focus[0]).focusGlide()) { Text("Action") }
IconButton(onClick = {}, modifier = Modifier.focusRequester(focus[1]).focusGlide()) { Text("Icon") }
Switch(false, {}, modifier = Modifier.focusRequester(focus[2]).focusGlide())
Slider(0.5f, {}, modifier = Modifier.focusRequester(focus[3]).focusGlide())
OutlinedTextField("Value", {}, modifier = Modifier.focusRequester(focus[4]).focusGlide())
XboxMenuEntry("Xbox action", null, focus = focus[5], onClick = {})
}
}
}
var previous: GlideSource? = null
for (requester in focus) {
compose.runOnIdle { requester.requestFocus() }
compose.runOnIdle {
val source = glide.current
assertNotNull(source)
assertNotSame(previous, source)
assertEquals(1, glide.hot.size)
assertNotNull(glide.boundsOf(source!!))
previous = source
}
}
}
@Test fun alertDialogButtonsShareTheirOwnWindowGlide() {
lateinit var parent: FocusGlide
lateinit var dialog: FocusGlide
val focus = List(2) { FocusRequester() }
compose.setContent {
DroidDeckTheme {
parent = LocalFocusGlide.current!!
GlideAlertDialog(
onDismissRequest = {},
title = { Text("Dialog") },
confirmButton = {
dialog = LocalFocusGlide.current!!
val view = LocalView.current
SideEffect { assertSame(view, dialog.view) }
TextButton(onClick = {}, modifier = Modifier.focusRequester(focus[0]).focusGlide()) { Text("Confirm") }
},
dismissButton = {
TextButton(onClick = {}, modifier = Modifier.focusRequester(focus[1]).focusGlide()) { Text("Cancel") }
},
)
}
}
assertNotSame(parent, dialog)
assertWindowHandoff(dialog, focus)
}
@Test fun customDialogsHaveAHostInsideTheirWindow() {
lateinit var parent: FocusGlide
lateinit var dialog: FocusGlide
val focus = List(2) { FocusRequester() }
compose.setContent {
DroidDeckTheme {
parent = LocalFocusGlide.current!!
GlideDialog(onDismissRequest = {}) {
dialog = LocalFocusGlide.current!!
Column {
SecondaryButton("First", modifier = Modifier.focusRequester(focus[0])) {}
SecondaryButton("Second", modifier = Modifier.focusRequester(focus[1])) {}
}
}
}
}
assertNotSame(parent, dialog)
assertWindowHandoff(dialog, focus)
}
@Test fun dropdownItemsShareTheirOwnWindowGlide() {
lateinit var parent: FocusGlide
lateinit var menu: FocusGlide
val focus = List(2) { FocusRequester() }
var expanded by mutableStateOf(true)
compose.setContent {
DroidDeckTheme {
parent = LocalFocusGlide.current!!
GlideDropdownMenu(expanded = expanded, onDismissRequest = {}) {
menu = LocalFocusGlide.current!!
for (i in focus.indices) DropdownMenuItem(
text = { Text("Item $i") }, onClick = {},
modifier = Modifier.focusRequester(focus[i]).focusGlide(),
)
}
}
}
assertNotSame(parent, menu)
assertWindowHandoff(menu, focus)
compose.runOnIdle { expanded = false }
compose.waitForIdle()
compose.runOnIdle { expanded = true }
compose.waitForIdle()
assertWindowHandoff(menu, focus)
}
private fun assertWindowHandoff(glide: FocusGlide, focus: List<FocusRequester>) {
var previous: GlideSource? = null
for (requester in focus) {
compose.runOnIdle { requester.requestFocus() }
compose.runOnIdle {
assertNotNull(glide.host)
val current = glide.current
assertNotNull(current)
assertNotSame(previous, current)
assertTrue(glide.boundsOf(current!!)!!.width > 0f)
previous = current
}
}
}
}
@@ -0,0 +1,63 @@
package com.droiddeck.launcher.ui
import android.content.Intent
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.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsFocused
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.frontend.Library
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.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@OptIn(androidx.compose.ui.test.ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class)
class GameResourcesRowTest {
@get:Rule val compose = createRobolectricComposeRule()
private val ctx get() = RuntimeEnvironment.getApplication()
private val game = Library.SteamGame(292030, "The Witcher 3", null, "/steam")
@Test fun everyResourceIsReachableOnANarrowPageAndOpensTheExpectedBrowserUrl() {
compose.setContent { DroidDeckTheme { GameResourcesRow(game.name, game) } }
for (link in gameResources(game.name, game)) {
compose.onNodeWithText(ctx.getString(link.label)).assertIsDisplayed().performClick()
val intent = shadowOf(ctx).nextStartedActivity
assertEquals(Intent.ACTION_VIEW, intent.action)
assertEquals(link.url, intent.dataString)
}
}
@Test fun controllerCanMoveBetweenLinksAndOpenAResource() {
lateinit var inputMode: InputModeManager
compose.setContent { DroidDeckTheme {
inputMode = LocalInputModeManager.current
GameResourcesRow(game.name, game)
} }
compose.runOnIdle { inputMode.requestInputMode(InputMode.Keyboard) }
compose.onNodeWithText(ctx.getString(R.string.game_resource_pcgw)).requestFocus().assertIsFocused().performKeyInput { pressKey(Key.DirectionRight) }
compose.onNodeWithText(ctx.getString(R.string.game_resource_guides)).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
assertEquals(gameResources(game.name, game)[1].url, shadowOf(ctx).nextStartedActivity.dataString)
}
@Test @Config(qualifiers = "w640dp-h360dp-land")
fun shortLandscapeWindowsKeepEveryResourceVisible() {
compose.setContent { DroidDeckTheme { GameResourcesRow(game.name, game) } }
for (link in gameResources(game.name, game)) {
compose.onNodeWithText(ctx.getString(link.label)).assertIsDisplayed()
}
}
}
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.net.URI
import java.net.URLDecoder
class GameResourcesTest {
@Test fun searchesPreserveUnicodeAndEscapeQueryDelimiters() {
val title = "Ōkami HD & friends + 100% #1?"
val links = gameResources(" $title ", null)
assertEquals(3, links.size)
links.forEach { link ->
val uri = URI(link.url)
assertEquals("https", uri.scheme)
assertEquals(null, uri.fragment)
assertEquals(title, URLDecoder.decode(uri.rawQuery.substringAfter('='), "UTF-8"))
}
}
@Test fun onlySteamClientGamesGetAppSpecificSteamResources() {
val steam = Library.SteamGame(292030, "The Witcher 3", null, "/steam")
val links = gameResources(steam.name, steam)
assertEquals("https://www.protondb.com/app/292030", links.single { it.label == R.string.game_resource_protondb }.url)
assertEquals("https://store.steampowered.com/account/remotestorageapp/?appid=292030", links.single { it.label == R.string.game_resource_steam_cloud }.url)
val others = listOf(
Library.SteamGame(292030, steam.name, null, Library.ADDED),
Library.SteamGame(292030, steam.name, null, Library.ADDED, source = "gog", storeId = "292030"),
Library.SteamGame(292030, steam.name, null, Library.XBOX_CLOUD, source = "xbox"),
Library.SteamGame(-1, steam.name, null, "/steam"),
)
others.forEach { game ->
assertEquals(3, gameResources(game.name, game).size)
}
}
@Test fun loadingPagesHaveNoResourcesUntilTheyHaveATitle() {
assertTrue(gameResources(" ", null).isEmpty())
}
}
@@ -13,6 +13,9 @@ class GamepadGeometryTest {
}
private val panels = listOf(
Panel("Thor portrait", 1080, 1920, 369 / 160f),
Panel("720p phone portrait", 720, 1280, 2f),
Panel("Phone portrait", 1080, 2400, 2.75f),
Panel("Fold 8 upright", 1848, 2448, 2.625f),
Panel("Fold 8 as a tablet", 2448, 1848, 2.625f),
Panel("Pixel Fold upright", 1840, 2208, 2.625f),
@@ -26,10 +29,15 @@ class GamepadGeometryTest {
private fun boxes(panel: Panel) =
GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density)
private val grips = setOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4)
private val portraitPanels get() = panels.take(3) + Panel("312dp phone portrait", 720, 1280, 369 / 160f)
private fun portraitBoxes(panel: Panel) =
GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true)
@Test fun everyControlIsPlacedAndPanelsOnlyWhenUpright() {
for (panel in panels) {
val upright = panel.height > panel.width
val expected = Slot.values().toSet() - if (upright) emptySet() else setOf(Slot.PANELS)
val expected = Slot.values().toSet() - grips - if (upright) emptySet() else setOf(Slot.PANELS)
assertEquals(panel.name, expected, boxes(panel).keys)
}
}
@@ -81,4 +89,56 @@ class GamepadGeometryTest {
assertTrue(panel.name, before(Slot.STEAM, Slot.QAM))
}
}
@Test fun portraitDockPlacesAllControlsWithinThePanel() {
for (panel in portraitPanels) {
val b = portraitBoxes(panel)
assertEquals(panel.name, Slot.values().toSet(), b.keys)
for ((slot, box) in b) {
val where = "${panel.name}: $slot $box"
assertTrue(where, box.left >= 0f && box.top >= 0f)
assertTrue(where, box.right <= panel.width && box.bottom <= panel.controlsHeight)
assertTrue(where, box.width >= 44 * panel.density - 1 && box.height >= 44 * panel.density - 1)
}
}
}
@Test fun portraitDockControlsDoNotOverlap() {
for (panel in portraitPanels) {
val placed = portraitBoxes(panel).entries.toList()
for (i in placed.indices) for (j in i + 1 until placed.size) {
assertFalse("${panel.name}: ${placed[i].key} overlaps ${placed[j].key}",
placed[i].value.overlaps(placed[j].value))
}
}
}
@Test fun portraitDockUsesMoreSpaceForTheThumbSurfaces() {
for (panel in portraitPanels) {
val old = boxes(panel)
val b = portraitBoxes(panel)
for (slot in listOf(Slot.LEFT_MAIN, Slot.RIGHT_MAIN, Slot.LEFT_SECOND, Slot.RIGHT_SECOND)) {
assertTrue("${panel.name}: $slot", b.getValue(slot).width >= old.getValue(slot).width * 1.2f)
}
assertEquals(panel.name, b.getValue(Slot.LEFT_MAIN).cx, b.getValue(Slot.LEFT_SECOND).cx, 0.5f)
assertEquals(panel.name, panel.width - b.getValue(Slot.LEFT_MAIN).cx, b.getValue(Slot.RIGHT_MAIN).cx, 0.5f)
}
}
@Test fun portraitDockMovesUtilitiesAndGripsAboveTheGamepad() {
for (panel in portraitPanels) {
val b = portraitBoxes(panel)
assertEquals(panel.name, 8 * panel.density, b.getValue(Slot.VIEW).top, 0.5f)
assertTrue(panel.name, b.getValue(Slot.MENU).bottom < b.getValue(Slot.L4).top)
assertTrue(panel.name, b.getValue(Slot.L4).bottom < b.getValue(Slot.LEFT_OUTER_SHOULDER).top)
assertTrue(panel.name, b.getValue(Slot.LEFT_OUTER_SHOULDER).bottom < b.getValue(Slot.LEFT_SECOND).top)
}
}
@Test fun shortPanelsKeepTheExistingLayoutEvenWhenPortraitDockIsRequested() {
for ((width, height, density) in listOf(Triple(1920f, 1080f, 2f), Triple(720f, 600f, 2.3f))) {
assertEquals(GamepadGeometry.layout(width, height, density),
GamepadGeometry.layout(width, height, density, portraitDock = true))
}
}
}
@@ -144,7 +144,7 @@ class GlobalGlassesSettingsTest {
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {})
), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {})
}
}
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -36,11 +37,56 @@ class LibraryEntriesTest {
assertTrue(entries.single().installed)
}
@Test fun aSavedCloudGameStaysNotInstalledAndKeepsItsLicenseFilters() {
val game = Library.SteamGame(-20, "Cloud game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "cloud")
val product = owned(Store.XBOX, "cloud").copy(subscription = true, extra = mapOf("cloud" to "1"))
val entries = libraryEntries(listOf(game), mapOf(Store.XBOX to listOf(product)), emptySet())
val entry = entries.single()
assertFalse(entry.installed)
for (filter in XboxLibraryFilter.ALL_FILTERS) assertTrue(filter, keepsXbox(filter, entry))
assertEquals(listOf("local", entry.key), installedFirst(listOf(entry, LibraryEntry("local", "steam", "Local", null, null, true))).map { it.key })
}
@Test fun anInstalledPcCopyTakesPrecedenceOverTheSavedCloudRow() {
val local = Library.SteamGame(-5, "PC game", null, Library.ADDED, source = "xbox", storeId = "same")
val cloud = Library.SteamGame(-20, "PC game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "same")
val entries = libraryEntries(listOf(cloud, local), mapOf(Store.XBOX to listOf(owned(Store.XBOX, "same"))), setOf("xbox:same"))
assertEquals(1, entries.size)
assertEquals(local, entries.single().game)
assertTrue(entries.single().installed)
}
@Test fun aSavedCloudGameWithoutACatalogStillAppearsInTheCloudFilter() {
val cloud = Library.SteamGame(-20, "Cloud game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "cloud")
val entry = libraryEntries(listOf(cloud), emptyMap(), emptySet()).single()
assertFalse(entry.installed)
assertTrue(keepsXbox(XboxLibraryFilter.CLOUD, entry))
assertFalse(keepsXbox(XboxLibraryFilter.OWNED, entry))
}
@Test fun distinctLocalShortcutsForTheSameProductArePreserved() {
val first = Library.SteamGame(-5, "First install", null, Library.ADDED, source = "xbox", storeId = "same")
val second = Library.SteamGame(-6, "Second install", null, Library.ADDED, source = "xbox", storeId = "same")
val cloud = Library.SteamGame(-20, "Cloud game", null, Library.XBOX_CLOUD, source = "xbox", storeId = "same")
val entries = libraryEntries(listOf(cloud, first, second), mapOf(Store.XBOX to listOf(owned(Store.XBOX, "same"))), setOf("xbox:same"))
assertEquals(listOf(first, second), entries.map { it.game })
}
@Test fun installedGamesComeFirstKeepingTheirSortedOrder() {
val entries = listOf("a", "b", "c", "d").map { LibraryEntry(it, "steam", it, null, null, installed = it == "b" || it == "d") }
assertEquals(listOf("b", "d", "a", "c"), installedFirst(entries).map { it.key })
}
@Test fun librarySourcesFollowTheConfiguredStoreOrderWithSteamFirstAndAddedLast() {
val entries = listOf("added", "gog", "steam", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) }
assertEquals(listOf("steam", "xbox", "epic", "gog", "added"), librarySources(entries, listOf("xbox", "epic", "gog")))
}
@Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() {
val entries = listOf("epic", "gog", "battlenet").map { LibraryEntry(it, it, it, null, null, false) }
assertEquals(listOf("epic", "gog", "battlenet"), librarySources(entries, listOf("missing", "epic", "epic", "amazon")))
}
@Test fun gameKeysNameEitherAnAppOrAStoreProduct() {
GameRef.parse("app:440").let { assertEquals(440, it.appId); assertNull(it.store) }
GameRef.parse("app:-12").let { assertEquals(-12, it.appId) }
@@ -48,4 +94,23 @@ class LibraryEntriesTest {
GameRef.parse("xbox:9NBLGGH4R315").let { assertEquals(Store.XBOX, it.store); assertEquals("9NBLGGH4R315", it.storeId) }
GameRef.parse("app:nope:1").let { assertNull(it.store); assertNull(it.appId) }
}
@Test fun aCollectionKeepsItsInstalledGamesAndListsTheRestAsNotInstalled() {
val games = listOf(
Library.SteamGame(440, "Team Fortress 2", null, "Steam library"),
Library.SteamGame(-5, "Celeste", null, Library.ADDED, source = "itch", storeId = "a/celeste"),
Library.SteamGame(-6, "Other", null, Library.ADDED, source = "itch", storeId = "a/other"),
)
val library = mapOf(Store.ITCH to listOf(owned(Store.ITCH, "a/celeste"), owned(Store.ITCH, "a/other"), owned(Store.ITCH, "b/owned")))
val all = libraryEntries(games, library, setOf("itch:a/celeste", "itch:a/other"))
val collection = listOf(owned(Store.ITCH, "a/celeste"), owned(Store.ITCH, "b/owned"), owned(Store.ITCH, "c/new"))
val out = collectionEntries(all, collection)
assertEquals(listOf("app:-5", "app:itch:b/owned", "app:itch:c/new"), out.map { it.key })
assertEquals(listOf(true, false, false), out.map { it.installed })
}
@Test fun anEmptyCollectionHidesEveryGame() {
val all = libraryEntries(listOf(Library.SteamGame(440, "Team Fortress 2", null, "Steam library")), emptyMap(), emptySet())
assertEquals(emptyList<String>(), collectionEntries(all, emptyList()).map { it.key })
}
}
@@ -0,0 +1,219 @@
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.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.CredentialCipher
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
import org.json.JSONObject
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.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import javax.crypto.spec.SecretKeySpec
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class)
class LibraryVisibilityTest {
@get:Rule val compose = createRobolectricComposeRule()
private val ctx get() = RuntimeEnvironment.getApplication()
private var generation by mutableIntStateOf(0)
@Before fun prepare() {
StoreAccounts.keys = CredentialCipher.KeyProvider { SecretKeySpec(ByteArray(32) { 7 }, "AES") }
StoreAccounts.keystoreFailed = false
ctx.getSharedPreferences("session", 0).edit().clear().commit()
LibraryView.source = LIBRARY_ALL
LibraryView.query = ""
LibraryView.focusFirst = false
StoresState.library.clear()
StoresState.accounts.clear()
for (store in listOf(Store.GOG, Store.EPIC)) {
StoreAccounts.write(ctx, store, JSONObject().put("access_token", "test-only").put("display_name", "Library test"))
StoresState.accounts[store] = "Library test"
StoresState.library[store] = listOf(CatalogItem(store, "owned", "Uninstalled ${store.shortLabel}", null, owned = true, sizeBytes = 1024))
}
}
@After fun clear() {
Steps.drop()
XboxLibraryFilter.set(ctx, XboxLibraryFilter.ALL)
for (store in listOf(Store.GOG, Store.EPIC)) StoreAccounts.clear(ctx, store)
StoreAccounts.keys = CredentialCipher.Keystore
StoreAccounts.keystoreFailed = false
StoresState.library.clear()
StoresState.accounts.clear()
ctx.getSharedPreferences("session", 0).edit().clear().commit()
LibraryView.source = LIBRARY_ALL
LibraryView.query = ""
LibraryView.focusFirst = false
}
@Test fun uninstalledGamesAreHiddenUntilSelectedInTheFilterAndTheChoiceSurvivesReopeningLibrary() {
show()
compose.onNodeWithText("Installed Steam game").assertExists()
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
chooseVisibility(true)
compose.onNodeWithText("Uninstalled GOG").assertExists()
assertTrue(SessionPrefs.libraryShowUninstalled(ctx))
compose.runOnIdle { generation++; Snapshot.sendApplyNotifications() }
compose.mainClock.advanceTimeBy(2_000)
compose.onNodeWithText("Uninstalled GOG").assertExists()
chooseVisibility(false)
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
assertFalse(SessionPrefs.libraryShowUninstalled(ctx))
}
@Test fun theFilterExpandsBesideSortWithoutChangingTheSelectionOnOpen() {
show()
val filter = compose.onNodeWithContentDescription("Filter · Installed only")
val sort = compose.onNodeWithContentDescription("Sort")
assertTrue(filter.fetchSemanticsNode().boundsInRoot.right <= sort.fetchSemanticsNode().boundsInRoot.left)
filter.performClick()
compose.mainClock.advanceTimeBy(2_000)
compose.onNodeWithText("Installed only").assertIsDisplayed()
compose.onNodeWithText("All owned games").assertIsDisplayed()
compose.onAllNodesWithText("Filter").assertCountEquals(1)
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
assertFalse(SessionPrefs.libraryShowUninstalled(ctx))
compose.runOnIdle { Steps.fold(); Snapshot.sendApplyNotifications() }
compose.mainClock.advanceTimeBy(1_000)
sort.performClick()
compose.mainClock.advanceTimeBy(2_000)
compose.onAllNodesWithText("Sort").assertCountEquals(1)
compose.onNodeWithText("Recently played").assertIsDisplayed()
}
@Test fun theXboxAccessChoicesShareTheLibraryFilter() {
StoreAccounts.write(ctx, Store.XBOX, JSONObject().put("username", "Library test"))
StoresState.accounts[Store.XBOX] = "Library test"
StoresState.library[Store.XBOX] = listOf(CatalogItem(Store.XBOX, "owned", "Uninstalled Xbox", null, owned = true))
LibraryView.source = Store.XBOX.id
try {
show()
compose.onNodeWithContentDescription("Filter · Installed only").performClick()
compose.mainClock.advanceTimeBy(2_000)
compose.onNodeWithText("Installed only").assertIsDisplayed()
compose.onNodeWithText("All owned games").assertIsDisplayed()
compose.onNodeWithText("Game Pass").assertIsDisplayed().performClick()
compose.mainClock.advanceTimeBy(1_000)
assertEquals(XboxLibraryFilter.GAME_PASS, XboxLibraryFilter.current)
assertFalse(SessionPrefs.libraryShowUninstalled(ctx))
} finally {
StoreAccounts.clear(ctx, Store.XBOX)
}
}
@Test fun aSearchWithOnlyUninstalledMatchesOffersToRevealThem() {
LibraryView.query = "Uninstalled GOG"
show()
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
compose.onNodeWithTag("library-browse-owned").performClick()
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Uninstalled GOG").assertExists()
assertEquals("Uninstalled GOG", LibraryView.query)
}
@Test fun aHiddenStoreRemainsReachableInLibraryInItsConfiguredOrder() {
SessionPrefs.setStoresTabOrder(ctx, listOf("epic", "gog"))
SessionPrefs.setStoresTabHidden(ctx, setOf("gog"))
show()
val steam = compose.onNodeWithTag("library-source-steam").fetchSemanticsNode().boundsInRoot.left
val epic = compose.onNodeWithTag("library-source-epic").fetchSemanticsNode().boundsInRoot.left
val gog = compose.onNodeWithTag("library-source-gog").fetchSemanticsNode().boundsInRoot.left
assertTrue(steam < epic && epic < gog)
compose.onNodeWithTag("library-source-gog").performClick()
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithTag("library-browse-owned").assertIsDisplayed().performClick()
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Uninstalled GOG").assertExists()
}
@Test fun theStoresOwnedGamesLinkRevealsOwnedGamesDespiteTheSavedInstalledOnlyView() {
assertFalse(SessionPrefs.libraryShowUninstalled(ctx))
LibraryView.showOwned(ctx, Store.GOG)
show()
compose.onNodeWithText("Uninstalled GOG").assertExists()
compose.onNodeWithText("Installed Steam game").assertDoesNotExist()
}
@Test fun theStoresOwnedGamesLinkUpdatesALibraryPageThatIsStillComposed() {
LibraryView.source = Store.GOG.id
show()
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
compose.runOnIdle { LibraryView.showOwned(ctx, Store.GOG); Snapshot.sendApplyNotifications() }
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Uninstalled GOG").assertExists()
}
private fun show() {
compose.mainClock.autoAdvance = false
compose.setContent { key(generation) {
DroidDeckTheme {
CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) {
FocusGlideHost { Box(Modifier.fillMaxSize()) {
LibraryPage(state(), actions(), "games", {}, Modifier.fillMaxSize())
StepsLayer(Offset.Zero)
} }
}
}
} }
compose.mainClock.advanceTimeBy(2_000)
}
private fun chooseVisibility(show: Boolean) {
compose.onNodeWithContentDescription("Filter · " + if (SessionPrefs.libraryShowUninstalled(ctx)) "All owned games" else "Installed only")
.performClick()
compose.mainClock.advanceTimeBy(2_000)
assertTrue(Steps.open)
compose.onNodeWithText(if (show) "All owned games" else "Installed only")
.performClick()
compose.mainClock.advanceTimeBy(1_000)
assertEquals(show, SessionPrefs.libraryShowUninstalled(ctx))
}
private fun state() = FrontEndState(
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "",
romsDir = null, logsEnabled = false,
steamGames = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal")),
emulators = emptyList(), running = null,
)
private fun 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,137 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.*
import androidx.compose.ui.unit.dp
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.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w960dp-h900dp-mdpi")
class PortraitLayoutTest {
@get:Rule val compose = createRobolectricComposeRule()
@Before fun freezeAnimations() {
compose.mainClock.autoAdvance = false
Hops.railPreview = null
}
@Test fun navigationSitsAtBottomAndRotatingPreservesContentState() {
val portrait = mutableStateOf(true)
compose.setContent {
DroidDeckTheme {
LauncherLayout(portrait.value, Color.Gray,
Modifier.size(if (portrait.value) 480.dp else 800.dp, if (portrait.value) 800.dp else 480.dp).testTag("launcher"),
navigation = {
if (portrait.value) BottomBar(state, "steam", {}, {}, actions, Modifier)
else SideRail(state, "steam", {}, {}, actions, Modifier.fillMaxHeight())
},
) {
var count by remember { mutableIntStateOf(0) }
Box(Modifier.fillMaxSize().testTag("pane")) {
TextButton(onClick = { count++ }) { Text("Count $count") }
}
}
}
}
compose.mainClock.advanceTimeBy(1_000)
val root = compose.onNodeWithTag("launcher").getUnclippedBoundsInRoot()
val pane = compose.onNodeWithTag("pane").getUnclippedBoundsInRoot()
val steam = compose.onNodeWithTag("rail-steam").getUnclippedBoundsInRoot()
assertEquals(root.left, pane.left)
assertEquals(root.right, pane.right)
assertTrue(steam.top >= pane.bottom)
assertEquals(root.bottom - 4.dp, steam.bottom)
compose.onNodeWithText("Count 0").performClick()
compose.runOnIdle { portrait.value = false }
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Count 1").assertExists()
val landscapePane = compose.onNodeWithTag("pane").getUnclippedBoundsInRoot()
val rail = compose.onNodeWithTag("rail-steam").getUnclippedBoundsInRoot()
assertTrue(landscapePane.left > rail.right)
assertEquals(0.dp, landscapePane.top)
compose.runOnIdle { portrait.value = true }
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Count 1").assertExists()
}
@Test fun narrowBottomBarScrollsToEveryDestinationWithAppsAndResumeVisible() {
val selected = mutableStateOf("steam")
compose.setContent {
DroidDeckTheme {
BottomBar(stateWithAppsAndSession, selected.value, { selected.value = it }, {}, actions, Modifier.size(320.dp, 64.dp))
}
}
compose.mainClock.advanceTimeBy(1_000)
for (key in listOf("games", "stores", "desktop", "components", "android-apps", "setup", "updates", "steam")) {
compose.onNodeWithTag("rail-$key").performScrollTo()
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithTag("rail-$key").assertIsDisplayed().performClick()
compose.mainClock.advanceTimeBy(1_000)
compose.runOnIdle { assertEquals(key, selected.value); assertNull(Hops.railPreview) }
compose.onNodeWithTag("rail-$key").assertIsSelected().assertHeightIsAtLeast(48.dp).assertWidthIsAtLeast(48.dp)
}
compose.onNodeWithContentDescription("Resume Steam").assertIsDisplayed()
}
@Test fun compactHeaderKeepsAllActionsReachable() {
compose.setContent {
DroidDeckTheme {
CompositionLocalProvider(LocalNarrowPane provides true) {
Box(Modifier.size(320.dp, 240.dp)) {
ModeHeader("Library", "", {}, "Search library") {
for (label in listOf("Filter", "Sort", "View", "Frontend files", "Add game")) {
SecondaryButton(label) {}
}
}
}
}
}
}
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Add game").performScrollTo()
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Add game").assertIsDisplayed()
compose.onNodeWithText("Filter").performScrollTo()
compose.mainClock.advanceTimeBy(1_000)
compose.onNodeWithText("Filter").assertIsDisplayed()
}
private fun state(home: Boolean = false, running: String? = null) = 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 = running,
isHomeApp = home,
)
private val state get() = state()
private val stateWithAppsAndSession get() = state(home = true, running = "Steam")
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 = { _, _ -> },
)
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
@@ -9,7 +10,9 @@ 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.Assert.assertNotNull
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@@ -21,7 +24,7 @@ import org.robolectric.annotation.Config
class PrimaryButtonFocusContrastTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun focusedPrimaryButtonDoesNotClaimAColorOverlayAboveItsLabel() {
@Test fun focusedPrimaryButtonClaimsTheGlideWithoutAColorOverlayAboveItsLabel() {
lateinit var glide: FocusGlide
var clicks = 0
compose.setContent {
@@ -36,11 +39,51 @@ class PrimaryButtonFocusContrastTest {
val button = compose.onNodeWithText("Play")
button.performSemanticsAction(SemanticsActions.RequestFocus)
button.assertIsFocused()
compose.runOnIdle { assertNull(glide.current) }
compose.runOnIdle {
assertNotNull(glide.current)
assertEquals(0f, glide.current!!.fillAlpha)
}
button.performClick()
compose.runOnIdle {
assertEquals(1, clicks)
assertNull(glide.current)
assertNotNull(glide.current)
assertEquals(0f, glide.current!!.fillAlpha)
}
}
@Test fun focusCanGlideIntoAndBackOutOfPrimaryButtons() {
lateinit var glide: FocusGlide
val focus = FrontFocus()
compose.setContent {
val view = LocalView.current
glide = remember(view) { FocusGlide(view) }
DroidDeckTheme {
CompositionLocalProvider(LocalFocusGlide provides glide, LocalFrontFocus provides focus) {
Column {
SecondaryButton("Tab") {}
PrimaryButton("Play Steam", main = true, large = true) {}
}
}
}
}
val tab = compose.onNodeWithText("Tab")
val play = compose.onNodeWithText("Play Steam")
tab.performSemanticsAction(SemanticsActions.RequestFocus)
tab.assertIsFocused()
val tabSource = compose.runOnIdle { glide.current!! }
compose.runOnIdle { focus.primary.requestFocus() }
play.assertIsFocused()
compose.runOnIdle {
assertNotNull(glide.current)
assertNotSame(tabSource, glide.current)
assertEquals(0f, glide.current!!.fillAlpha)
assertEquals(1, glide.hot.size)
}
tab.performSemanticsAction(SemanticsActions.RequestFocus)
tab.assertIsFocused()
compose.runOnIdle {
assertSame(tabSource, glide.current)
assertEquals(1, glide.hot.size)
}
}
}
@@ -98,6 +98,33 @@ class SessionSecondScreenTest {
}
}
@Test
@Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
fun drawerShortcutsConsumeRepeatsAndReleasesAfterClosing() {
val device = InputDeviceBuilder.newBuilder().setId(43).setName("Drawer shortcut test pad")
.setDescriptor("drawer-shortcut-pad").setExternal(true).setSources(InputDevice.SOURCE_GAMEPAD).build()
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
SessionState.mode = SessionService.MODE_STEAM
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val open: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerOpen\$delegate")
val controller: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerControllerActive\$delegate")
controller.value = true
for (button in listOf(KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_START)) {
fun event(action: Int, repeat: Int = 0) = KeyEvent(0L, 0L, action, button, repeat, 0,
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)
open.value = true
assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_DOWN)))
assertEquals(false, open.value)
open.value = true
assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_DOWN, 1)))
assertEquals(true, open.value)
open.value = false
assertTrue(activity.dispatchKeyEvent(event(KeyEvent.ACTION_UP)))
val held: Set<Pair<Int, Int>> = ReflectionHelpers.getField(activity, "drawerShortcutKeysDown")
assertTrue(held.isEmpty())
}
}
@Test fun sessionMicrophoneCanBeTurnedOff() {
val changes = mutableListOf<Boolean>()
compose.setContent {
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.SemanticsMatcher
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.core.SteamIntegration
import com.droiddeck.launcher.core.SteamIntegration.Feature
import org.junit.Assert.*
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 = [33], qualifiers = "w960dp-h540dp-land")
class SteamIntegrationGroupTest {
@get:Rule val compose = createRobolectricComposeRule()
private val state = mutableStateOf(SteamIntegration.State())
private val requests = mutableListOf<Feature>()
private var appInfo = 0
private var location = 0
private fun stateIs(value: String) = SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, value)
private fun show() = compose.setContent {
DroidDeckTheme {
SteamIntegrationGroup(state.value, onFeature = { requests.add(it) }, onAppInfo = { appInfo++ }, onLocation = { location++ })
}
}
@Test fun everySwitchRequestsOnlyItsOwnFeature() {
state.value = SteamIntegration.State(home = true)
show()
compose.onNodeWithTag("integration-action-brightness").performClick()
compose.onNodeWithTag("integration-action-home").performClick()
compose.onNodeWithTag("integration-action-shortcuts").performClick()
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests)
}
@Test fun switchesReflectAndroidGrants() {
state.value = SteamIntegration.State(brightness = true, home = true, shortcuts = true)
show()
compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On"))
compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On"))
compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off"))
compose.onNodeWithText("3 of 4 on").assertExists()
}
@Test fun shortcutsWaitForHome() {
show()
compose.onNodeWithTag("integration-action-shortcuts").assertIsNotEnabled()
compose.onNodeWithText("Needs DroidDeck as Home").assertExists()
compose.runOnIdle { state.value = state.value.copy(home = true) }
compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled()
}
@Test fun restrictedShortcutsPointToAppInfo() {
state.value = SteamIntegration.State(home = true, shortcutsRestricted = true)
show()
compose.onNodeWithTag("integration-action-shortcuts").assertIsNotEnabled()
compose.onNodeWithText("App info").performClick()
assertEquals(1, appInfo)
compose.runOnIdle { state.value = state.value.copy(shortcutsRestricted = false) }
compose.onNodeWithText("App info").assertDoesNotExist()
compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled()
}
@Test fun unconfirmedRestrictionOffersAppInfoAfterAnAttempt() {
state.value = SteamIntegration.State(home = true)
show()
compose.onNodeWithText("App info").assertDoesNotExist()
compose.runOnIdle { state.value = state.value.copy(shortcutsTried = true) }
compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled()
compose.onNodeWithText("App info").performClick()
assertEquals(1, appInfo)
}
@Test fun deniedLocationPointsToAppInfoWithoutTogglingWifi() {
state.value = SteamIntegration.State(locationBlocked = true)
show()
compose.onNodeWithText("Location denied · allow it in App info").assertExists()
compose.onNodeWithText("App info").performClick()
assertEquals(1, location)
assertTrue(requests.isEmpty())
}
}
@@ -0,0 +1,151 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.xbox.XboxBackend
import com.droiddeck.launcher.stores.xbox.XboxContent
import org.json.JSONObject
import org.junit.After
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class)
class StoreRestorationTest {
@get:Rule val compose = createRobolectricComposeRule()
private val ctx get() = RuntimeEnvironment.getApplication()
private val product = CatalogItem(Store.XBOX, "9NBLGGH4R315", "Test game", null, owned = true, sizeBytes = 10_485_760L, extra = mapOf("cloud" to "1"))
private val cloud = Library.SteamGame(-20, product.title, null, Library.XBOX_CLOUD, source = "xbox", storeId = product.id)
@After fun clear() {
StoresState.publishDownloads(emptyList())
StoresState.unfinished = emptyList()
StoreSizes.onDisk.clear()
XboxContent.dismiss()
}
@Test fun manageContentReportsItsResultWithoutComposingTheStoresPage() {
val base = InstalledStoreGame(StoreGameSidecar(Store.XBOX, product.id, product.title, "game.exe"), File(ctx.cacheDir, "missing-xbox-manifest"))
compose.mainClock.autoAdvance = false
compose.setContent {
DroidDeckTheme { FrontEndScreen(state(), actions(), page = { Text("Library game page") }) }
}
compose.mainClock.advanceTimeBy(2_000)
compose.runOnIdle { XboxContent.manage(ctx, base) }
compose.waitUntil(5_000) {
shadowOf(android.os.Looper.getMainLooper()).idle()
XboxContent.plan != null
}
compose.mainClock.advanceTimeBy(100)
compose.onNodeWithText(ctx.getString(R.string.stores_xbox_content_title)).assertExists()
compose.onNodeWithText("Missing or ambiguous MicrosoftGame.config.").assertExists()
compose.onNodeWithText(ctx.getString(android.R.string.ok)).performClick()
compose.runOnIdle { assertNull(XboxContent.plan) }
}
@Test fun packageChoicesRenderOutsideTheStoresPage() {
val choices = (1..24).map { JSONObject().put("title", "Package $it").put("kind", "Game") }
val pending = XboxBackend.PackageChoice(product, ctx.cacheDir, choices)
compose.setContent { DroidDeckTheme { XboxStoreDialogs(content = null, pending = pending) } }
compose.onNodeWithText(ctx.getString(R.string.stores_xbox_choose_content)).assertExists()
choices.forEach { compose.onNodeWithText(ctx.getString(R.string.stores_xbox_choice, it.getString("title"), "Game")).performScrollTo().assertIsDisplayed() }
compose.onNodeWithText(ctx.getString(android.R.string.cancel)).assertExists()
}
@Test fun everyContentOfferCanBeReachedInALandscapeDialog() {
val base = InstalledStoreGame(StoreGameSidecar(Store.XBOX, product.id, product.title, "game.exe"), ctx.cacheDir)
val offers = (1..24).map { XboxContent.Offer(product.copy(id = "dlc-$it", title = "Content $it"), installed = false) }
val plan = XboxContent.Plan(base, offers)
compose.setContent { DroidDeckTheme { XboxStoreDialogs(content = plan, pending = null) } }
offers.forEach { compose.onNodeWithText(ctx.getString(R.string.stores_xbox_content_install, it.item.title)).performScrollTo().assertIsDisplayed() }
}
@Test fun libraryCardsShowDownloadAndInstalledSizes() {
val owned = LibraryEntry("owned", "xbox", product.title, null, product, false)
val installed = LibraryEntry("installed", "xbox", product.title, null, product.copy(id = "installed"), true)
StoreSizes.onDisk["xbox:installed"] = 20_971_520L
compose.setContent { DroidDeckTheme { Column {
LibraryMarker(owned, null)
LibraryMarker(installed, null)
} } }
compose.onNodeWithText("10.0 MB").assertExists()
compose.onNodeWithText("20.0 MB").assertExists()
}
@Test fun aSavedCloudGamesDownloadKeepsPauseResumeCancelAndFailureRecovery() {
val entry = DownloadEntry(Store.XBOX, product.id, product.title, state = DownloadState.RUNNING)
StoresState.publishDownloads(listOf(entry))
compose.setContent { DroidDeckTheme { GameActions(Store.XBOX, product.id, cloud, product, null, state(), actions(), Modifier) } }
compose.onNodeWithText(ctx.getString(R.string.stores_dl_pause)).assertExists()
compose.onNodeWithText(ctx.getString(R.string.stores_dl_cancel)).assertExists()
compose.onNodeWithText(ctx.getString(R.string.game_stream)).assertExists()
compose.runOnIdle { StoresState.publishDownloads(listOf(entry.copy(state = DownloadState.PAUSED))) }
compose.onNodeWithText(ctx.getString(R.string.stores_dl_resume)).assertExists()
compose.onNodeWithText(ctx.getString(R.string.stores_dl_cancel)).assertExists()
compose.runOnIdle { StoresState.publishDownloads(listOf(entry.copy(state = DownloadState.FAILED))) }
compose.onNodeWithText(ctx.getString(R.string.stores_dl_resume)).assertExists()
compose.onNodeWithText(ctx.getString(R.string.stores_dl_clear)).assertExists()
compose.onNodeWithText(ctx.getString(R.string.game_stream)).assertExists()
}
@Test fun aConsoleOnlyCloudGameDoesNotOfferAPcInstall() {
compose.setContent { DroidDeckTheme { GameActions(Store.XBOX, product.id, cloud, product.copy(sizeBytes = 0, extra = mapOf("pc" to "0", "cloud" to "1")), null, state(), actions(), Modifier) } }
compose.onNodeWithText(ctx.getString(R.string.game_stream)).assertExists()
compose.onNodeWithText(ctx.getString(R.string.stores_install)).assertDoesNotExist()
}
@Test fun anInterruptedCloudDownloadCanBeClearedAfterItsLicenseOrPcMetadataChanges() {
StoresState.unfinished = listOf(StoreInstallRoot.Unfinished(Store.XBOX, product.id, File(ctx.cacheDir, "partial")))
var item by mutableStateOf(product)
compose.setContent { DroidDeckTheme { GameActions(Store.XBOX, product.id, cloud, item, null, state(), actions(), Modifier) } }
compose.onNodeWithText(ctx.getString(R.string.stores_resume_install)).assertExists()
for (changed in listOf(product.copy(owned = false), product.copy(extra = mapOf("pc" to "0", "cloud" to "1")))) {
compose.runOnIdle { item = changed }
compose.onNodeWithText(ctx.getString(R.string.stores_dl_clear)).assertExists()
compose.onNodeWithText(ctx.getString(R.string.stores_resume_install)).assertDoesNotExist()
}
}
private fun state() = 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,
pageKey = "test-game", navigate = "games",
)
private fun 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 = { _, _ -> },
)
}