Merge remote-tracking branch 'droiddeck/main' into feat/malibridge

# Conflicts:
#	README.md
#	app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
#	app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
#	app/src/main/res/values-ar/strings.xml
#	app/src/main/res/values-b+es+419/strings.xml
#	app/src/main/res/values-bg/strings.xml
#	app/src/main/res/values-cs/strings.xml
#	app/src/main/res/values-da/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-el/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-fi/strings.xml
#	app/src/main/res/values-fr/strings.xml
#	app/src/main/res/values-hi/strings.xml
#	app/src/main/res/values-hu/strings.xml
#	app/src/main/res/values-in/strings.xml
#	app/src/main/res/values-it/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values-ko/strings.xml
#	app/src/main/res/values-ms/strings.xml
#	app/src/main/res/values-nb/strings.xml
#	app/src/main/res/values-nl/strings.xml
#	app/src/main/res/values-pl/strings.xml
#	app/src/main/res/values-pt-rPT/strings.xml
#	app/src/main/res/values-pt/strings.xml
#	app/src/main/res/values-ro/strings.xml
#	app/src/main/res/values-ru/strings.xml
#	app/src/main/res/values-sv/strings.xml
#	app/src/main/res/values-th/strings.xml
#	app/src/main/res/values-tr/strings.xml
#	app/src/main/res/values-uk/strings.xml
#	app/src/main/res/values-vi/strings.xml
#	app/src/main/res/values-zh-rCN/strings.xml
#	app/src/main/res/values-zh-rHK/strings.xml
#	app/src/main/res/values-zh-rTW/strings.xml
#	app/src/main/res/values/strings.xml
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
This commit is contained in:
maxjivi05 committed 2026-10-30 11:58:55 -04:00
commit 0a5955d6fa
731 files changed
+54131 -2491

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
@@ -0,0 +1,20 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Test
class DeviceReportCpuTest {
@Test fun onlyFeatureListsAreReportedAndDifferentCoreCapabilitiesAreKept() {
val cpuInfo = """
processor : 0
Features : fp asimd aes
Serial : private-device-id
processor : 1
Features : fp asimd aes atomics
processor : 2
Features : fp asimd aes
""".trimIndent()
assertEquals("fp asimd aes | fp asimd aes atomics", DeviceReport.cpuFeaturesSummary(cpuInfo))
assertEquals("not reported", DeviceReport.cpuFeaturesSummary("processor : 0\n"))
}
}
@@ -6,6 +6,9 @@ import java.net.Socket
import java.nio.file.Files
import java.security.MessageDigest
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
@@ -29,6 +32,9 @@ class DownloaderResumeTest {
@Volatile private var misbehave = false
@Volatile private var etag: String? = "\"v1\""
@Volatile private var corrupt = false
@Volatile private var holdAfterFirstChunk = false
private var bodyStarted = CountDownLatch(1)
private var continueBody = CountDownLatch(1)
@Before fun setUp() {
dir = Files.createTempDirectory("downloader-resume").toFile()
@@ -70,8 +76,15 @@ class DownloaderResumeTest {
val start = if (from == null) "200 OK" else "206 Partial Content"
val extra = if (from == null) "" else "Content-Range: bytes 0-${data.size - 1}/${data.size}\r\n"
out.write("HTTP/1.1 $start\r\n${extra}${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(content)
out.flush()
if (holdAfterFirstChunk) {
out.write(content, 0, 1024)
out.flush()
bodyStarted.countDown()
continueBody.await(5, TimeUnit.SECONDS)
} else {
out.write(content)
out.flush()
}
} else if (from == null) {
out.write("HTTP/1.1 200 OK\r\n${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(content, 0, cutAt)
@@ -168,6 +181,48 @@ class DownloaderResumeTest {
}
@Test fun cancelStopsTheTransferWithoutTryingAnotherSource() {
val first = "http://127.0.0.1:${server.localPort}/first"
val second = "http://127.0.0.1:${server.localPort}/second"
val target = File(dir, "runtime.tar.zst")
misbehave = true
val polls = java.util.concurrent.atomic.AtomicInteger()
// candidate selection and attempt each check once before the request; later checks follow chunks
val cancelled = java.util.function.BooleanSupplier { polls.incrementAndGet() > 2 }
assertFalse(Downloader.downloadCandidates(first, listOf(first, second), target, true, null, cancelled, null))
assertEquals("a cancel must not fall back to the next source", listOf<String?>(null), requests.toList())
assertTrue("the transfer stopped early (kept=${target.length()})", target.length() in 1 until data.size)
}
@Test fun cancellationDisconnectsAStalledTransfer() {
val url = "http://127.0.0.1:${server.localPort}/first"
val target = File(dir, "runtime.tar.zst")
misbehave = true
holdAfterFirstChunk = true
val cancellation = Downloader.Cancellation()
val executor = Executors.newSingleThreadExecutor()
val cancelExecutor = Executors.newSingleThreadExecutor()
try {
val result = executor.submit<Boolean> { Downloader.downloadFile(url, target, true, null, cancellation, null) }
assertTrue("server sent the first chunk", bodyStarted.await(2, TimeUnit.SECONDS))
val cancelled = cancelExecutor.submit { cancellation.cancel() }
cancelled.get(10, TimeUnit.SECONDS)
assertFalse("cancelled download", result.get(10, TimeUnit.SECONDS))
assertEquals(listOf<String?>(null), requests.toList())
} finally {
continueBody.countDown()
executor.shutdownNow()
cancelExecutor.shutdownNow()
}
}
@Test fun aCancelBeforeTheFirstRequestSendsNothing() {
val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst"
val target = File(dir, "runtime.tar.zst")
assertFalse(Downloader.downloadFile(url, target, true, null, { true }, null))
assertEquals(emptyList<String?>(), requests.toList())
}
@Test fun withoutADigestOnlyTheOriginalUrlIsTried() {
val url = "https://github.com/owner/repo/releases/download/v1/app.AppImage"
assertEquals(listOf(url), Downloader.sources(url, null))
@@ -3,9 +3,14 @@ package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.StringWriter
class LogRedactorTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun labelledJwtIsRedacted() {
val out = LogRedactor.redact("Using JWT 25484942796017334")
assertFalse(out.contains("25484942796017334"))
@@ -226,6 +231,103 @@ class LogRedactorTest {
assertEquals(once, LogRedactor.redactForShare(once))
}
@Test fun anOversizedDirectInputIsWithheldBeforeRegex() {
val secret = "sessionid=abcdef123456"
val line = "x".repeat(LogRedactor.MAX_LINE_LENGTH) + secret
assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redact(line))
assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redactForShare(line))
}
@Test fun streamWithholdsAnOversizedLogicalLineWholeAndContinues() {
val secret = "sessionid=abcdef123456"
val src = tmp.newFile("oversized.log")
src.writeText(
"before\r" +
"x".repeat(LogRedactor.MAX_LINE_LENGTH - 3) + secret + "\r\n" +
"after $secret"
)
val out = StringWriter()
LogRedactor.scrubTo(src, out)
assertEquals(
"before\n${LogRedactor.OVERSIZED_LINE}\nafter sessionid=<redacted:token>\n",
out.toString(),
)
assertFalse(out.toString().contains("abcdef123456"))
}
@Test fun sharedStreamDistinguishesOversizedAndUnsupportedLines() {
val src = tmp.newFile("shared-lines.log")
src.writeText(
"x".repeat(LogRedactor.MAX_LINE_LENGTH + 1) + "\n" +
"private-prefix\u0000private-suffix\n" +
"after sessionid=abcdef123456\n"
)
val out = StringWriter()
assertTrue(LogRedactor.scrubForShare(src, out))
assertEquals(
"${LogRedactor.OVERSIZED_LINE}\n" +
"<unsupported or oversized line withheld>\n" +
"after sessionid=<redacted:token>\n",
out.toString(),
)
}
@Test fun aMaximumLengthLineBeforeCrLfIsStillScrubbed() {
val src = tmp.newFile("maximum.log")
val line = "x ".repeat(LogRedactor.MAX_LINE_LENGTH / 2)
src.writeText(line + "\r\n")
val out = StringWriter()
LogRedactor.scrubTo(src, out)
assertEquals(line + "\n", out.toString())
assertFalse(out.toString().contains(LogRedactor.OVERSIZED_LINE))
}
@Test fun streamingScrubStopsBetweenInputChunks() {
val src = tmp.newFile("cancelled.log")
src.writeText("first safe line\n" + "x".repeat(20_000) + " sessionid=abcdef123456\n")
val out = StringWriter()
var checks = 0
val complete = LogRedactor.scrubTo(src, out) { ++checks >= 4 }
assertFalse(complete)
assertFalse(out.toString().contains("abcdef123456"))
assertTrue(checks >= 4)
}
@Test fun manyLearnedAccountsKeepBoundariesAndLiteralNames() {
val users = tmp.newFile("loginusers.vdf")
users.writeText((0 until 40).joinToString("\n") {
"\"AccountName\" \"probe_account_$it\""
} + "\n\"PersonaName\" \"Player.+[40]\"\n")
try {
LogRedactor.learnAccounts(users)
assertEquals("owner=<redacted:account> persona=<redacted:account>",
LogRedactor.redact("owner=probe_account_39 persona=Player.+[40]"))
assertEquals("owner=probe_account_390", LogRedactor.redact("owner=probe_account_390"))
} finally {
LogRedactor.learnAccounts(tmp.root.resolve("missing-users"))
}
}
@Test fun manyLearnedAddressesKeepOtherAddresses() {
val link = tmp.newFile("droiddeck-net")
link.writeText((1..40).joinToString("\n") { "addr 203.0.113.$it 24" })
try {
LogRedactor.learnOwnAddresses(link)
assertEquals("local=<redacted:ip> server=203.0.113.200",
LogRedactor.redact("local=203.0.113.40 server=203.0.113.200"))
} finally {
LogRedactor.learnOwnAddresses(tmp.root.resolve("missing-network"))
}
}
@Test fun learnedAccountsComeFromBothClients() {
val root = java.nio.file.Files.createTempDirectory("redactor").toFile()
try {
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.core
import android.app.Application
import androidx.test.core.app.ApplicationProvider
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SettingsReset
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
class SteamIntegrationSuggestionTest {
private val context: Application = ApplicationProvider.getApplicationContext()
@Test fun closingTheSuggestionKeepsItHiddenForGood() {
assertTrue(SteamIntegration.read(context).suggested)
SteamIntegration.dismissSuggestion(context)
assertFalse(SteamIntegration.read(context).suggested)
SettingsReset.resetAll(context, gameProfiles = false)
assertFalse(SteamIntegration.read(context).suggested)
assertTrue(SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false))
}
}
@@ -112,6 +112,135 @@ class AddedExesTest {
assertEquals(listOf(pick.path), AddedGames.scan(app).map { it.exe.path })
}
private fun result(r: AddedGames.AddResult): AddedGames.Game = when (r) {
is AddedGames.AddResult.Added -> r.game
is AddedGames.AddResult.Existing -> r.game
is AddedGames.AddResult.Switched -> r.game
else -> throw AssertionError("not added: $r")
}
private fun visualNovels(): File {
val storage = tmp.newFolder("PC Games")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "SD card")
exe(File(storage, "VNs/Albatross/Albatross Log.exe"))
exe(File(storage, "VNs/Rance 01/Rance01.exe"))
exe(File(storage, "VNs/Angel Beats/SiglusEngine.exe"))
exe(File(storage, "VNs/Sayonara/SiglusEngine.exe"))
return storage
}
@Test fun aGroupFolderOnGameStorageListsEachGameInsideIt() {
val storage = visualNovels()
val vns = File(storage, "VNs")
assertEquals(listOf("Albatross", "Angel Beats", "Rance 01", "Sayonara").map { File(vns, it).path },
AddedGames.scan(app).map { it.folder.path })
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun anExePickedInAGroupFolderOnGameStorageIsItsOwnGame() {
val storage = visualNovels()
val vns = File(storage, "VNs")
SessionPrefs.setAddedGameExe(app, vns.path, File(vns, "Albatross/Albatross Log.exe").path)
for (pick in listOf("Rance 01/Rance01.exe", "Sayonara/SiglusEngine.exe", "Angel Beats/SiglusEngine.exe")) {
val game = result(AddedGames.addExe(app, File(vns, pick)))
assertEquals(File(vns, pick).parentFile!!.path, game.folder.path)
}
assertEquals(4, AddedGames.scan(app).size)
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aRemovedGroupFolderOnGameStorageStaysRemoved() {
val storage = visualNovels()
val group = File(storage, "VNs")
val pick = File(group, "Rance 01/Rance01.exe")
AddedGames.remove(app, group)
val game = result(AddedGames.addExe(app, pick))
assertEquals(pick.parentFile!!.path, game.folder.path)
assertTrue(group.path in SessionPrefs.removedAddedGames(app))
assertEquals(listOf(pick.parentFile!!.path), AddedGames.scan(app).map { it.folder.path })
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aSiblingExeOfAnAddedGameOnGameStorageSwitchesThatGame() {
val storage = tmp.newFolder("PC Games")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "SD card")
val held = exe(File(storage, "Game/bin/Game.exe"))
val pick = exe(File(storage, "Game/launcher/Launcher.exe"))
val game = File(storage, "Game")
AddedExes.put(app, AddedExes.Entry(game.path, held.path))
val result = AddedGames.addExe(app, pick)
assertTrue(result is AddedGames.AddResult.Switched)
assertEquals(game.path, (result as AddedGames.AddResult.Switched).game.folder.path)
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aHiddenFolderInAGroupIsAddedAsItsOwnGame() {
val storage = visualNovels()
val vns = File(storage, "VNs")
val pick = exe(File(vns, ".Gamma/Gamma.exe"))
val game = result(AddedGames.addExe(app, pick))
assertEquals(pick.parentFile!!.path, game.folder.path)
assertTrue(AddedGames.scan(app).any { it.folder.path == pick.parentFile!!.path })
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aFolderThatDeclaresItsExeInASubfolderStaysOneGame() {
val storage = tmp.newFolder("PC Games")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "SD card")
exe(File(storage, "Halo/Content/Halo.exe"))
exe(File(storage, "Halo/Tools/ModKit.exe"))
File(storage, "Halo/MicrosoftGame.config").writeText("<Game><Executable Name=\"Content\\Halo.exe\" /></Game>")
assertEquals(listOf(File(storage, "Halo").path), AddedGames.scan(app).map { it.folder.path })
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aGroupFolderTheUserAddedAsOneGameStaysOneGame() {
val storage = visualNovels()
val vns = File(storage, "VNs")
AddedExes.put(app, AddedExes.Entry(vns.path, File(vns, "Albatross/Albatross Log.exe").path))
assertEquals(listOf(vns.path), AddedGames.scan(app).map { it.folder.path })
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aGameWithBuildFoldersOnGameStorageStaysOneGame() {
val storage = tmp.newFolder("PC Games")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "SD card")
exe(File(storage, "Oddworld/x64/Oddworld.exe"))
exe(File(storage, "Oddworld/x86/Oddworld.exe"))
exe(File(storage, "Episodes/Episode1/Episode1.exe"))
File(storage, "Episodes/Movies").mkdirs()
assertEquals(listOf("Episodes", "Oddworld").map { File(storage, it).path }, AddedGames.scan(app).map { it.folder.path })
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aSiblingExeOfAGameOnGameStorageSwitchesThatGame() {
val storage = tmp.newFolder("PC Games")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "SD card")
exe(File(storage, "Game/bin/Game.exe"))
val pick = exe(File(storage, "Game/launcher/Launcher.exe"))
val result = AddedGames.addExe(app, pick)
assertTrue(result is AddedGames.AddResult.Switched)
assertEquals(File(storage, "Game").path, (result as AddedGames.AddResult.Switched).game.folder.path)
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun aDeeperExeOfAGameOnGameStorageStillSwitchesThatGame() {
val storage = tmp.newFolder("PC Games")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "SD card")
exe(File(storage, "Example/Example.exe"))
val deep = exe(File(storage, "Example/bin/Example64.exe"))
val result = AddedGames.addExe(app, deep)
assertTrue(result is AddedGames.AddResult.Switched)
assertEquals(File(storage, "Example").path, (result as AddedGames.AddResult.Switched).game.folder.path)
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
@Test fun anotherBuildOfTheSameExeInASiblingFolderSwitchesTheGame() {
noGamesFolders()
val held = onStorage("Games2/Oddworld/x64/Oddworld.exe")
@@ -446,4 +446,55 @@ class WinCompSourcesTest {
AutoComponents.drain(app)
assertTrue(AutoComponents.queued().isEmpty())
}
@Test fun aLostPartOfAnInstalledBundleIsReinstalledAndTheGameWaitsForIt() = withFakeWorker {
val bundle = WinComponents.Component("directmusic", "", "", "ready", listOf("dmband"), emptyList())
AutoComponents.catalogOf = { _, _ -> catalog3 + ready("dmband") + bundle }
installedNow.addAll(listOf("directmusic", "d3dx9"))
WinComponents.setUser(app, "4242", "directmusic", true)
WinComponents.setUser(app, "4242", "d3dx9", true)
session = true
gameUp = true
assertEquals(listOf("dmband"), AutoComponents.restoreMissing(app))
assertTrue(downloaded.isEmpty())
assertEquals("[\"dmband\"]", AutoComponents.Pending.read(app).optJSONArray("4242").toString())
gameUp = false
AutoComponents.drain(app)
assertEquals(listOf("dmband"), downloaded)
assertEquals(0, AutoComponents.Pending.read(app).length())
assertTrue(AutoComponents.restoreMissing(app).isEmpty())
}
@Test fun aRestoreRunsADownloadQueuedBeforeTheSessionWithoutWaitingForItToEnd() = withFakeWorker {
WinComponents.setUser(app, "4243", "vcredist2019_dll", true)
session = true
AutoComponents.queueGame(app, game(tmp.newFolder("Wait"), Library.ADDED), asked = true)
AutoComponents.restoreMissing(app)
AutoComponents.restoreMissing(app)
assertEquals(listOf("vcredist2019_dll"), downloaded)
session = false
AutoComponents.drain(app)
}
@Test fun aGameJobThatRunsFirstKeepsARestoredComponentPending() = withFakeWorker {
AutoComponents.catalogOf = { _, _ -> catalog3 + ready("dmband") }
val seen = ArrayList<List<String>>()
AutoComponents.installer = { _, c, _, _ ->
if (c.name == "dmband") seen.add(AutoComponents.Pending.ids(app, "1262580"))
downloaded.add(c.name); installedNow.add(c.name); null
}
val game = payback()
WinComponents.setUser(app, "1262580", "dmband", true)
session = true
gameUp = true
AutoComponents.queueInSession(app, game)
AutoComponents.restoreMissing(app)
gameUp = false
AutoComponents.drain(app)
assertEquals(1, seen.size)
assertTrue("dmband" in seen.single())
assertEquals(0, AutoComponents.Pending.read(app).length())
session = false
AutoComponents.drain(app)
}
}
@@ -1,12 +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.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
@@ -38,12 +39,10 @@ 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.performanceMode = false
activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@After fun cleanup() {
SessionState.performanceMode = false
activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@@ -53,7 +52,7 @@ class GlassesMirrorPacingTest {
apply(connected, settings.copy(refreshHz = 90))
expect(2, 90f, 90)
apply(GlassesState(), settings)
expect(3, 120f, 0)
expect(3, 120f, SessionPrefs.FPS_UNPACED)
}
@Test fun retiredSavedLimitsDoNotCapThePhoneOrMirroredOutput() {
@@ -64,21 +63,22 @@ class GlassesMirrorPacingTest {
apply(connected.copy(hz = 120f), settings)
expect(1, 60f, 60)
apply(GlassesState(), settings)
expect(3, 120f, 0)
}
@Test fun performanceModeResumesUnpacedOutputAfterMirrorDisconnects() {
SessionState.performanceMode = true
apply(connected, settings)
expect(1, 60f, 60)
apply(GlassesState(), settings)
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) {
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.glasses
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.After
import org.junit.Before
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@@ -15,6 +16,8 @@ class SpatialControllerModeTest {
private fun snapshot(): ByteBuffer = (SpatialTracking::class.java.getDeclaredField("buffer")
.apply { isAccessible = true }.get(null) as ByteBuffer).duplicate().order(ByteOrder.LITTLE_ENDIAN)
@Before fun outputOnGlasses() = SpatialTracking.setOutputUsesGlasses(true)
@After fun cleanUp() {
SpatialTracking.setSteadyHandAim(false)
SpatialTracking.setControllers(false, false)
@@ -64,6 +64,18 @@ class GpuDetectionTest {
assertEquals(Support.UNSUPPORTED, info(false, 830).support)
}
@Test fun adreno722IsSupportedOnlyOnTheRetroidPocketDuo() {
assertEquals(true, GpuInfo.verifiedOn(722, "Retroid Pocket Duo"))
assertEquals(false, GpuInfo.verifiedOn(722, "Retroid Pocket 5"))
assertEquals(false, GpuInfo.verifiedOn(720, "Retroid Pocket Duo"))
assertEquals(false, GpuInfo.verifiedOn(740, "Retroid Pocket Duo"))
val duo = info(true, 722).copy(verifiedDevice = true)
assertEquals(Support.TESTED, duo.support)
assertEquals("Supported", duo.supportText)
assertEquals(Family.A7XX_LOW, duo.family)
assertEquals(Support.UNTESTED, info(true, 722).support)
}
@Test fun userFacingTextPerTier() {
assertEquals("Supported", info(true, 830).supportText)
assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", info(true, 850).supportText)
@@ -1,6 +1,11 @@
package com.droiddeck.launcher.gpu
import android.os.Environment
import android.os.Build
import com.droiddeck.launcher.session.QuestExperimental
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@@ -9,6 +14,7 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -16,10 +22,23 @@ class TurnipDriverAutoTest {
@Before fun reset() {
ShadowBuild.setModel("Phone")
ShadowBuild.setDevice("phone")
overrideFile().delete()
}
@After fun cleanUp() {
overrideFile().delete()
SessionPrefs.setAndroidDriver(RuntimeEnvironment.getApplication(), TurnipDriver.AUTO)
File(RuntimeEnvironment.getApplication().filesDir, "graphics_driver/test-pinned").deleteRecursively()
}
private fun overrideFile() = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-driver")
private fun gpu(model: Int, adreno: Boolean = true) = GpuInfo(
"test GPU", model, GpuInfo.familyOf(adreno, model), "", false,
)
@Test fun questModelsUseTheirPatchedDriverAsTheFallback() {
val driver = TurnipDriver(RuntimeEnvironment.getApplication())
val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("Quest must not use generic GPU detection") }
for (model in listOf("Quest 3", "Quest 3S", "Quest 2")) {
ShadowBuild.setModel(model)
assertEquals(if (model == "Quest 2") QuestExperimental.DRIVER_A6XX else QuestExperimental.DRIVER,
@@ -27,8 +46,54 @@ class TurnipDriverAutoTest {
}
}
@Test fun otherDevicesRetainTheGenericFallback() {
assertEquals("turnip25.1.0", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
@Test fun aNonAdrenoDeviceDoesNotAutomaticallyLoadTurnip() {
assertEquals(GpuInfo.Family.NOT_ADRENO, GpuInfo.detect().family)
assertEquals("system", TurnipDriver(RuntimeEnvironment.getApplication()).autoId())
}
@Test fun autoSelectionUsesTheDetectedFamilyAndModel() {
val context = RuntimeEnvironment.getApplication()
for ((detected, expected) in listOf(
gpu(0, adreno = false) to "system",
gpu(0) to "turnip25.1.0",
gpu(650) to "turnip26.3.0-a6xx",
gpu(730) to "turnip25.1.0",
gpu(850) to "turnip-sdk36",
)) {
var calls = 0
assertEquals(expected, TurnipDriver(context) { calls++; detected }.autoId())
assertEquals(1, calls)
}
}
@Test fun nonAdrenoDoesNotUseTheAndroid16TurnipFallback() {
val context = RuntimeEnvironment.getApplication()
val sdk = Build.VERSION.SDK_INT
try {
ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 36)
assertEquals("system", TurnipDriver(context) { gpu(0, adreno = false) }.autoId())
assertEquals("turnip-sdk36", TurnipDriver(context) { gpu(0) }.autoId())
} finally {
ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", sdk)
}
}
@Test fun externalOverrideStillTakesPriorityOverDetection() {
val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("override must precede detection") }
overrideFile().parentFile!!.mkdirs()
overrideFile().writeText("system")
assertEquals("system", driver.autoId())
overrideFile().writeText("a8")
assertEquals("turnip-sdk36", driver.autoId())
}
@Test fun aManuallySelectedImportedDriverStillTakesPriorityOverDetection() {
val context = RuntimeEnvironment.getApplication()
val dir = File(context.filesDir, "graphics_driver/test-pinned").apply { mkdirs() }
File(dir, "meta.json").writeText("""{"libraryName":"test.so"}""")
File(dir, "test.so").writeText("")
SessionPrefs.setAndroidDriver(context, "test-pinned")
assertEquals("test-pinned", TurnipDriver(context) { error("manual choice must precede detection") }.install())
}
@Test fun normalizedGpuModelsSelectExistingGenerationDrivers() {
@@ -0,0 +1,138 @@
package com.droiddeck.launcher.hud
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 kotlin.random.Random
class FrameStatsTest {
/** MangoHud's update_hud_info_with_frametime and fps()/frame_timing(), line by line (overlay.cpp). */
private class Mango {
val frametimeData = ArrayList<Float>(List(200) { 0f })
var lastPresentTime = 0L
var lastFpsUpdate = 0L
var framesSinceUpdate = 0L
var fps = 0.0
fun update(frametimeNs: Long, now: Long) {
val elapsed = now - lastFpsUpdate
if (lastPresentTime != 0L) {
frametimeData.add(frametimeNs / 1000000f)
frametimeData.removeAt(0)
}
if (elapsed >= 500000000L) {
fps = 1000000000.0 * framesSinceUpdate / elapsed
framesSinceUpdate = 0
lastFpsUpdate = now
}
lastPresentTime = now
framesSinceUpdate++
}
}
@Test fun readingsMatchMangoHudFrameByFrame() {
val random = Random(7)
val stats = FrameStats()
val mango = Mango()
var now = 5_000_000_000L
val graph = FloatArray(FrameStats.GRAPH_FRAMES)
repeat(20_000) { i ->
val frametime = when {
i % 977 == 0 -> 100_000_000L
i % 131 == 0 -> 33_000_000L
else -> 2_700_000L + random.nextLong(-400_000L, 400_000L)
}
now += frametime
stats.add(frametime, now)
mango.update(frametime, now)
assertEquals("fps at frame $i", mango.fps.toFloat(), stats.fps, 0.0001f)
assertEquals(1000f / maxOf(mango.fps.toFloat(), 1f), stats.frametimeMs(), 0.0001f)
if (i % 499 == 0 || i < 210) {
stats.graph(graph)
assertArrayEquals("graph at frame $i", mango.frametimeData.toFloatArray(), graph, 0f)
assertEquals(mango.frametimeData.min(), stats.graphMinMs(), 0f)
assertEquals(mango.frametimeData.max(), stats.graphMaxMs(), 0f)
}
}
}
@Test fun compositorFramesWakeTheHudWhenGamescopeSharesNone() {
val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames"))
var now = 1_000_000_000L
assertFalse(feed.poll(now))
feed.onCompositorFrame(now)
now += 16_666_667L
feed.onCompositorFrame(now)
assertTrue(feed.poll(now))
assertFalse(feed.poll(now + 1))
}
@Test fun aCompletedPeriodIsCountedWhenMangoHudWouldRedraw() {
val stats = FrameStats()
var now = 1_000_000_000L
stats.add(10_000_000L, now)
assertEquals(1L, stats.fpsUpdates)
repeat(49) { now += 10_000_000L; stats.add(10_000_000L, now) }
assertEquals(1L, stats.fpsUpdates)
now += 10_000_000L; stats.add(10_000_000L, now)
assertEquals(2L, stats.fpsUpdates)
assertEquals(100f, stats.fps, 0.01f)
}
@Test fun aSteadyRateReadsExactlyWithoutMillisecondRounding() {
val stats = FrameStats()
var now = 1_000_000_000L
val frametime = 16_666_667L
repeat(600) { now += frametime; stats.add(frametime, now) }
assertEquals(60f, stats.fps, 0.01f)
val lows = stats.lows(now)
assertEquals(60f, lows.low1Fps, 0.01f)
assertEquals(60f, lows.low01Fps, 0.01f)
assertEquals(60f, stats.averageFps(), 0.01f)
}
@Test fun stuttersShowInTheGraphAndTheLows() {
val stats = FrameStats()
var now = 1_000_000_000L
repeat(1000) { i ->
val frametime = if (i % 100 == 50) 100_000_000L else 2_700_000L
now += frametime
stats.add(frametime, now)
}
assertEquals(100f, stats.graphMaxMs(), 0.001f)
assertEquals(2.7f, stats.graphMinMs(), 0.001f)
assertEquals(10f, stats.lows(now).low01Fps, 0.01f)
assertEquals(370.37f, stats.lows(now).low1Fps, 0.01f)
}
@Test fun pausesStayOutOfTheAverageAndLowsButNotTheGraph() {
val stats = FrameStats()
var now = 1_000_000_000L
repeat(300) { now += 10_000_000L; stats.add(10_000_000L, now) }
now += 3_000_000_000L
stats.add(3_000_000_000L, now)
assertEquals(100f, stats.lows(now).low01Fps, 0.01f)
assertEquals(3000f, stats.graphMaxMs(), 0.01f)
}
@Test fun resetStartsOver() {
val stats = FrameStats()
var now = 1_000_000_000L
repeat(300) { now += 10_000_000L; stats.add(10_000_000L, now) }
stats.reset()
assertEquals(0f, stats.fps, 0f)
assertEquals(0f, stats.graphMaxMs(), 0f)
assertEquals(FrameStats.Lows.EMPTY, stats.lows(now))
}
@Test fun engineNamesFollowMangoHud() {
assertEquals("DXVK", GameFrameFeed.engineLabel("DXVK"))
assertEquals("VKD3D", GameFrameFeed.engineLabel("vkd3d"))
assertEquals("ZINK", GameFrameFeed.engineLabel("mesa zink"))
assertEquals("GAMESCOPE", GameFrameFeed.engineLabel("gamescope"))
assertEquals("GAMESCOPE", GameFrameFeed.engineLabel(""))
assertEquals("VULKAN", GameFrameFeed.engineLabel("UnityEngine"))
}
}
@@ -0,0 +1,148 @@
package com.droiddeck.launcher.hud
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.os.Looper
import android.os.SystemClock
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.FrameLayout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import java.io.ByteArrayOutputStream
import java.time.Duration
import java.util.Base64
import kotlin.math.roundToInt
import kotlin.math.sqrt
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], qualifiers = "xhdpi")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class FusionHudPanelTest {
@Test fun minimalIsTheSizeTheHudStartsWith() {
assertEquals(FusionSize.MINIMAL, FusionSize.from(FusionHudConfig.DEFAULTS["hudSize"]))
}
@Test fun theHudStartsLocked() {
assertEquals("1", FusionHudConfig.DEFAULTS["hudLocked"])
}
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
val stats = FrameStats()
var now = 1_000_000_000L
repeat(2_000) { i ->
val frametime = if (i == 1_700) 25_600_000L else 2_850_000L
now += frametime
stats.add(frametime, now)
}
val snapshot = SNAPSHOT
for (size in FusionSize.values()) {
val view = FusionHudView(RuntimeEnvironment.getApplication())
view.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudSize" to size.token)))
view.setFrameStats(stats)
view.showForTest(snapshot, "DXVK", now)
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
view.measure(unspecified, unspecified)
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
println("FUSIONHUD-${size.token.uppercase()}-PNG ${Base64.getEncoder().encodeToString(png.toByteArray())}")
val panel = view.panelForTest()!!
assertTrue("$size panel inside the view",
panel.left > 0f && panel.top > 0f && panel.right < view.width && panel.bottom < view.height)
view.graphForTest()?.let { graph ->
val r = view.panelRadiusForTest()
val d = maxOf(panel.top + r - graph.top, graph.bottom - (panel.bottom - r), 0f)
val edge = panel.right - r + sqrt(r * r - d * d)
assertTrue("$size graph clears the round side", graph.right <= edge)
}
val orb = bitmap.getPixel(panel.left.roundToInt() + 1, panel.centerY().roundToInt())
assertTrue("$size orb on the left side", Color.blue(orb) > 200 && Color.alpha(orb) > 200)
}
}
@Test fun pillShowsEachBatteryPartOnItsOwnSwitch() {
fun pill(vararg settings: Pair<String, String>): List<String> {
val view = FusionHudView(RuntimeEnvironment.getApplication())
view.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudSize" to FusionSize.PILL.token) + settings))
view.showForTest(SNAPSHOT, "DXVK", 0L)
return view.linesForTest()
}
val all = pill("showBattery" to "1")
assertTrue(all.toString(), all.any { "BAT 79% · 34°C · 16.0W" in it })
assertEquals(all.toString(), 1, all.count { "BAT" in it })
assertFalse(all.toString(), all.single { "RAM" in it }.contains("BAT"))
val noMemory = pill("showBattery" to "1", "showRAM" to "0")
assertTrue(noMemory.toString(), noMemory.none { "RAM" in it })
assertTrue(noMemory.toString(), noMemory.any { "BAT 79% · 34°C · 16.0W" in it })
val defaults = pill()
assertTrue(defaults.toString(), defaults.any { "BAT 34°C · 16.0W" in it })
val wattsOnly = pill("showBatteryTemp" to "0")
assertTrue(wattsOnly.toString(), wattsOnly.any { "BAT 16.0W" in it })
val nothing = pill("showBatteryTemp" to "0", "showPower" to "0")
assertTrue(nothing.toString(), nothing.none { "BAT" in it })
}
@Test fun aLockedHudLetsTouchesThroughOnlyWhereAControlTakesThem() {
val app = RuntimeEnvironment.getApplication()
var reached = 0
val under = View(app).apply {
setOnTouchListener { _, e -> if (e.actionMasked == MotionEvent.ACTION_DOWN) reached++; true }
}
val hud = FusionHudView(app)
val parent = FrameLayout(app)
parent.addView(under, FrameLayout.LayoutParams(2000, 2000))
parent.addView(hud, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
var control = false
hud.passesTouchAt = { _, _ -> control }
val locks = ArrayList<Boolean>()
hud.setOnLockChangedListener { locks += it }
hud.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudLocked" to "0")))
hud.showForTest(SNAPSHOT, "DXVK", 0L)
val exactly = View.MeasureSpec.makeMeasureSpec(2000, View.MeasureSpec.EXACTLY)
parent.measure(exactly, exactly)
parent.layout(0, 0, 2000, 2000)
assertTrue(hud.width > 0 && hud.height > 0)
fun touch(holdMs: Long = 50L) {
val x = hud.width / 2f; val y = hud.height / 2f
val down = SystemClock.uptimeMillis()
MotionEvent.obtain(down, down, MotionEvent.ACTION_DOWN, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(holdMs))
MotionEvent.obtain(down, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
shadowOf(Looper.getMainLooper()).idle()
}
control = true
touch()
assertEquals("an unlocked HUD keeps the touch (tap, drag, long press)", 0, reached)
hud.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudLocked" to "1")))
touch()
assertEquals("a locked HUD passes it to the control under it", 1, reached)
control = false
touch()
assertEquals("a locked HUD keeps a touch no control takes", 1, reached)
touch(holdMs = ViewConfiguration.getLongPressTimeout() + 300L)
assertEquals("a long press there unlocks it", listOf(false), locks)
}
private companion object {
val SNAPSHOT = HudMetrics.Snapshot(64, 52, 3302, 1050, 89, 79, 10_800_000_000L, 16_000_000_000L, 67f,
1_800_000_000L, HudMetrics.Battery(16f, false, 79, 34, null),
intArrayOf(91, 91, 48, 50, 48, 19, 17, 73), intArrayOf(2265, 2265, 3148, 3148, 3148, 2956, 2956, 3302),
2_700_000_000L, 6_400_000_000L, 31_000L, 9_000L)
}
}
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.hud
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.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class MangoReadingsTest {
@get:Rule val tmp = TemporaryFolder()
private fun readings() = MangoReadings(tmp.root, tmp.root)
@Test fun cpuLoadFollowsMangoHudsFormulaAndTruncates() {
val stat = File(tmp.root, "stat")
val m = readings()
// user nice system idle iowait irq softirq steal guest guest_nice
stat.writeText("cpu 1000 100 500 8000 400 50 50 0 200 0\ncpu0 500 50 250 4000 200 25 25 0 100 0\ncpu1 500 50 250 4000 200 25 25 0 100 0\nintr 0\n")
m.cpu(stat)
stat.writeText("cpu 1500 100 700 8600 500 60 70 10 300 0\ncpu0 900 50 400 4100 250 30 35 10 200 0\ncpu1 600 50 300 4500 250 30 35 0 100 0\nintr 0\n")
val cpu = m.cpu(stat)!!
// busy = user-guest 400 + nice 0 + system+irq+softirq 230 + steal 10 + guest 100 = 740 of 1440 (idle+iowait 700)
assertEquals((740 * 100f / 1440).toInt(), cpu.percent)
assertEquals(51, cpu.percent)
assertArrayEquals(intArrayOf(((300 + 165 + 10 + 100) * 100f / (300 + 165 + 10 + 100 + 150)).toInt(), ((100 + 65) * 100f / (100 + 65 + 550)).toInt()), cpu.perCore)
}
@Test fun anUnchangedCounterKeepsTheLastLoad() {
val stat = File(tmp.root, "stat")
val m = readings()
stat.writeText("cpu 100 0 0 100 0 0 0 0 0 0\n")
m.cpu(stat)
stat.writeText("cpu 200 0 0 100 0 0 0 0 0 0\n")
assertEquals(100, m.cpu(stat)!!.percent)
assertEquals(100, m.cpu(stat)!!.percent)
}
private fun battery(status: String, chargeNow: Long, chargeFull: Long, powerUw: Long) {
val dir = File(tmp.root, "sys/power_supply/BAT1").apply { mkdirs() }
File(dir, "status").writeText("$status\n")
File(dir, "charge_now").writeText("$chargeNow\n")
File(dir, "charge_full").writeText("$chargeFull\n")
File(dir, "power_now").writeText("$powerUw\n")
}
@Test fun batteryHidesWattsWhileChargingAsMangoHudDoes() {
battery("Discharging", 3_622_942, 3_854_193, 8_760_000)
val discharging = readings().battery()!!
assertEquals(94, discharging.percent)
assertEquals(8.76f, discharging.watts, 0.001f)
assertFalse(discharging.charging)
battery("Charging", 3_622_942, 3_854_193, 8_760_000)
val charging = readings().battery()!!
assertEquals(0f, charging.watts, 0f)
assertTrue(charging.charging)
}
@Test fun noBatteryFolderMeansNoReading() {
assertNull(readings().battery())
}
@Test fun gpuLoadIsTheLeadingNumber() {
val f = File(tmp.root, "perf_now").apply { writeText(" 6 %\n") }
assertEquals(6.0, MangoReadings.leadingNumber(f)!!, 0.0)
}
}
@@ -40,6 +40,29 @@ class BackQamInputTest {
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)
@@ -90,6 +113,55 @@ class BackQamInputTest {
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))
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.view.InputDevice
import android.view.MotionEvent
import java.time.Duration
import org.junit.Assert.*
@@ -13,68 +14,171 @@ import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class DirectTouchHoldTest {
private val events = mutableListOf<String>()
private val touches = mutableListOf<String>()
private val buttons = mutableListOf<String>()
private val hold = DirectTouchHold(8f, object : PointerGestures.Listener {
override fun onMove(x: Float, y: Float) {}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
assertEquals(PointerGestures.BTN_RIGHT, button)
events += "$pressed at $x,$y"
buttons += "$pressed at $x,$y"
}
override fun onWheel(steps: Int) {}
override fun onLongPress() {}
}) { events += "cancel touch" }.also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
}, object : DirectTouchHold.Touch {
override fun down(pointerId: Int, x: Float, y: Float) { touches += "down $pointerId at $x,$y" }
override fun move(pointerId: Int, x: Float, y: Float) { touches += "move $pointerId at $x,$y" }
override fun up(pointerId: Int, x: Float, y: Float) { touches += "up $pointerId at $x,$y" }
override fun cancel() { touches += "cancel" }
}).also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
@Test fun holdReleasesRawTouchBeforeClickAndConsumesTheLift() {
assertFalse(touch(MotionEvent.ACTION_DOWN))
advance(500)
assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events)
assertTrue(touch(MotionEvent.ACTION_UP))
@Test fun holdClicksRightWithoutTouchingTheGame() {
touch(MotionEvent.ACTION_DOWN)
advance(400)
assertTrue(buttons.isEmpty())
advance(100)
assertEquals(listOf("true at 40.0,30.0"), buttons)
advance(50)
assertEquals("false at 40.0,30.0", events.last())
assertFalse(touch(MotionEvent.ACTION_DOWN))
hold.cancel()
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
touch(MotionEvent.ACTION_MOVE, 44f)
touch(MotionEvent.ACTION_UP)
assertTrue(touches.isEmpty())
}
@Test fun stillHoldKeepsTheTouchWhenLongPressIsOff() {
@Test fun tapForwardsTheTouchWhenItLifts() {
touch(MotionEvent.ACTION_DOWN)
advance(100)
touch(MotionEvent.ACTION_UP, 50f)
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
advance(50)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 50.0,30.0"), touches)
assertTrue(buttons.isEmpty())
}
@Test fun noneBehaviorForwardsTheTouchAtOnce() {
hold.configure(TouchGestureConfig(directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_NONE))
touch(MotionEvent.ACTION_DOWN)
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
advance(600)
assertTrue(buttons.isEmpty())
touch(MotionEvent.ACTION_MOVE, 60f)
assertEquals("move 0 at 60.0,30.0", touches.last())
touch(MotionEvent.ACTION_UP, 60f)
advance(50)
assertEquals("up 0 at 60.0,30.0", touches.last())
}
@Test fun dragForwardsTheTouchOnceItMoves() {
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_MOVE, 60f)
assertEquals(listOf("down 0 at 40.0,30.0", "move 0 at 60.0,30.0"), touches)
advance(600)
assertTrue(buttons.isEmpty())
touch(MotionEvent.ACTION_UP, 60f)
advance(50)
assertEquals("up 0 at 60.0,30.0", touches.last())
}
@Test fun dragKeepsForwardingWithinTheSlop() {
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_MOVE, 44f)
assertTrue(touches.isEmpty())
touch(MotionEvent.ACTION_UP, 44f)
advance(50)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 44.0,30.0"), touches)
}
@Test fun stillHoldClicksRightWithTheDefaultConfig() {
hold.configure(TouchGestureConfig())
assertFalse(touch(MotionEvent.ACTION_DOWN))
touch(MotionEvent.ACTION_DOWN)
advance(2000)
assertFalse(touch(MotionEvent.ACTION_MOVE))
assertFalse(touch(MotionEvent.ACTION_UP))
assertTrue(events.isEmpty())
touch(MotionEvent.ACTION_MOVE)
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
touch(MotionEvent.ACTION_UP)
assertTrue(touches.isEmpty())
}
@Test fun longPressFollowsTheConfiguredDelay() {
hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800))
touch(MotionEvent.ACTION_DOWN)
advance(700)
assertTrue(events.isEmpty())
assertTrue(buttons.isEmpty())
advance(100)
assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events)
assertEquals(listOf("true at 40.0,30.0"), buttons)
hold.cancel()
}
@Test fun tapDragSecondFingerAndCancellationDoNotRightClick() {
for (action in listOf(MotionEvent.ACTION_UP, MotionEvent.ACTION_MOVE,
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_CANCEL)) {
touch(MotionEvent.ACTION_DOWN)
assertFalse(touch(action, 60f))
advance(600)
assertTrue(events.isEmpty())
hold.cancel()
}
@Test fun holdBehaviorKeepsTheButtonUntilTheLift() {
hold.configure(TouchGestureConfig(longPressDelay = 500,
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_HOLD))
touch(MotionEvent.ACTION_DOWN)
advance(500)
assertEquals(listOf("true at 40.0,30.0"), buttons)
advance(1000)
assertEquals(listOf("true at 40.0,30.0"), buttons)
touch(MotionEvent.ACTION_UP)
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
assertTrue(touches.isEmpty())
}
@Test fun secondFingerForwardsTheTouchAndDropsTheHold() {
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_POINTER_DOWN, 60f)
assertEquals(listOf("down 0 at 40.0,30.0", "down 0 at 60.0,30.0"), touches)
advance(600)
assertTrue(buttons.isEmpty())
touch(MotionEvent.ACTION_UP, 60f)
}
@Test fun modeChangeCancelsPendingHoldAndReleasesAnActiveClick() {
touch(MotionEvent.ACTION_DOWN)
hold.cancel()
advance(600)
assertTrue(events.isEmpty())
assertTrue(buttons.isEmpty())
assertTrue(touches.isEmpty())
touch(MotionEvent.ACTION_DOWN)
advance(500)
hold.cancel()
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
}
@Test fun cancelForwardsACancelWhenTheTouchIsLive() {
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_MOVE, 60f)
hold.cancel()
assertEquals(listOf("down 0 at 40.0,30.0", "move 0 at 60.0,30.0", "cancel"), touches)
}
@Test fun cancelDropsAPendingLift() {
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_UP, 60f)
hold.cancel()
advance(100)
assertEquals(listOf("cancel touch", "true at 40.0,30.0", "false at 40.0,30.0"), events)
assertEquals(listOf("down 0 at 40.0,30.0", "cancel"), touches)
}
@Test fun aQuickSecondTapLiftsTheFirstInsteadOfCancellingIt() {
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_UP, 50f)
advance(20)
touch(MotionEvent.ACTION_DOWN, 60f)
touch(MotionEvent.ACTION_UP, 60f)
advance(50)
assertEquals(
listOf("down 0 at 40.0,30.0", "up 0 at 50.0,30.0", "down 0 at 60.0,30.0", "up 0 at 60.0,30.0"),
touches,
)
}
@Test fun theSecondFingerLiftsWithItsOwnId() {
multi(MotionEvent.ACTION_DOWN, 0, 0 to 40f)
multi(MotionEvent.ACTION_POINTER_DOWN, 1, 0 to 40f, 1 to 60f)
multi(MotionEvent.ACTION_POINTER_UP, 0, 0 to 40f, 1 to 60f)
multi(MotionEvent.ACTION_UP, 0, 1 to 60f)
advance(100)
assertEquals(
listOf("down 0 at 40.0,30.0", "down 1 at 60.0,30.0", "up 0 at 40.0,30.0", "up 1 at 60.0,30.0"),
touches,
)
}
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
@@ -82,4 +186,23 @@ class DirectTouchHoldTest {
val event = MotionEvent.obtain(0, 0, action, x, 30f, 0)
return hold.onTouch(event).also { event.recycle() }
}
private fun multi(action: Int, index: Int, vararg points: Pair<Int, Float>): Boolean {
val properties = Array(points.size) {
MotionEvent.PointerProperties().apply {
id = points[it].first
toolType = MotionEvent.TOOL_TYPE_FINGER
}
}
val coords = Array(points.size) {
MotionEvent.PointerCoords().apply {
x = points[it].second
y = 30f
pressure = 1f
size = 1f
}
}
val event = MotionEvent.obtain(0, 0, action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT),
points.size, properties, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
return hold.onTouch(event).also { event.recycle() }
}
}
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.test.core.app.ApplicationProvider
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class DualScreenTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val displays = context.getSystemService(DisplayManager::class.java)
@Test fun internalPanelsCountAsBuiltIn() {
assertTrue(DualScreen.isBuiltIn(1, "Anything"))
assertFalse(DualScreen.isBuiltIn(2, "Retroid Pocket Duo"))
assertFalse(DualScreen.isBuiltIn(5, "AYN Thor"))
}
@Test fun knownModelsCountWhenTheTypeIsHidden() {
assertTrue(DualScreen.isBuiltIn(null, "Retroid Pocket Duo"))
assertTrue(DualScreen.isBuiltIn(null, " AYN Thor "))
assertFalse(DualScreen.isBuiltIn(null, "Pixel 8"))
}
@Test fun oneScreenDevicesGetNoSecondScreenInAnyMode() {
for (mode in DualScreen.modes) {
SessionPrefs.setDualScreenMode(context, mode)
assertNull(DualScreen.display(context, displays, Display.DEFAULT_DISPLAY))
assertNull(DualScreen.anyDisplay(displays, Display.DEFAULT_DISPLAY))
}
}
@Test fun modeDefaultsToAutomaticAndIgnoresUnknownValues() {
assertEquals(DualScreen.MODE_AUTO, SessionPrefs.dualScreenMode(context))
SessionPrefs.setDualScreenMode(context, "sideways")
assertEquals(DualScreen.MODE_AUTO, SessionPrefs.dualScreenMode(context))
SessionPrefs.setDualScreenMode(context, DualScreen.MODE_OFF)
assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context))
}
}
@@ -0,0 +1,91 @@
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
import org.robolectric.shadows.ShadowBuild
@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)
}
private fun quickMenu(action: Int) = KeyEvent(10, 110, action, KeyEvent.KEYCODE_HOME, 0, 0, 10, 194)
@Test fun duoQuickMenuHomePassesThroughToTheSystemAndCancelsAHeldGuide() {
ShadowBuild.setModel("Retroid Pocket Duo")
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true))
assertFalse(input.onKeyEvent(quickMenu(KeyEvent.ACTION_DOWN), true))
assertEquals(listOf(true, false), states)
assertEquals(1, cancellations)
assertFalse(input.onKeyEvent(quickMenu(KeyEvent.ACTION_UP), true))
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), true))
assertEquals(listOf(true, false), states)
}
@Test fun theSameScanCodeStillHoldsGuideOnOtherDevices() {
ShadowBuild.setModel("Retroid Pocket 5")
assertTrue(input.onKeyEvent(quickMenu(KeyEvent.ACTION_DOWN), true))
assertTrue(input.onKeyEvent(quickMenu(KeyEvent.ACTION_UP), true))
assertEquals(listOf(true, false), states)
}
}
@@ -173,6 +173,17 @@ class OnScreenControlsTest {
assertEquals(-1, field(control("rs"), "pressedBy"))
}
@Test fun takesTouchAtMatchesWhatATouchDoes() {
var checked = 0
for (x in 0 until 1200 step 40) for (y in 0 until 800 step 40) {
val expected = view.takesTouchAt(x.toFloat(), y.toFloat())
assertEquals("($x, $y)", expected, touch(MotionEvent.ACTION_DOWN, 0 to (x.toFloat() to y.toFloat())))
touch(MotionEvent.ACTION_UP, 0 to (x.toFloat() to y.toFloat()))
if (expected) checked++
}
assertTrue("some points land on controls", checked > 0)
}
@Test fun fixedSticksAndEditorRemainVisibleAtSavedPositions() {
ControllerPrefs.setAdaptiveSticks(context, false)
view.reload()
@@ -236,6 +247,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)
@@ -1,6 +1,11 @@
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
@@ -10,13 +15,16 @@ 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"],
shadows = [JoyConPadTest.RecordingWriter::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
@@ -45,6 +53,7 @@ class PadBridgeQamTest {
bridge.applyExternal({}, false)
assertEquals(supported, pad().isDown(PadState.QAM))
bridge.setBackQamPressed(false)
advanceTime()
}
SessionState.deckPad = false
assertFalse(bridge.canHoldQam())
@@ -54,10 +63,12 @@ class PadBridgeQamTest {
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))
@@ -72,6 +83,7 @@ class PadBridgeQamTest {
bridge.setSystemButtons(false, false)
assertTrue(pad().isDown(PadState.QAM))
bridge.setBackQamPressed(false)
advanceTime()
assertFalse(pad().isDown(PadState.QAM))
}
@@ -106,10 +118,346 @@ class PadBridgeQamTest {
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,254 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
import com.droiddeck.launcher.input.PhysicalShortcuts.Action
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
class PhysicalShortcutsTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
private val router = PhysicalShortcutRouter()
private val actions = mutableListOf<Action>()
private lateinit var pad: InputDevice
@Before fun setUp() {
ControllerPrefs.prefs(context).edit().clear().commit()
pad = device(10, "retroid")
}
@Test fun defaultsDoNotInterceptAnyButton() {
assertTrue(PhysicalShortcuts.read(context).isEmpty())
for (code in listOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_BUTTON_MODE,
KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_1)) {
assertFalse(route(key(code)))
assertFalse(route(key(code, KeyEvent.ACTION_UP)))
}
assertTrue(actions.isEmpty())
}
@Test fun assignmentPersistsAndConsumesTheWholePressWithoutRepeating() {
assign(key(), Action.STEAM)
assertEquals(listOf(PhysicalShortcuts.Binding(button(key()), Action.STEAM)), PhysicalShortcuts.read(context))
assertTrue(route(key()))
assertTrue(route(key(repeat = 1)))
assertTrue(route(key(repeat = 2)))
assertTrue(route(key(action = KeyEvent.ACTION_UP)))
assertEquals(listOf(Action.STEAM), actions)
assertFalse(route(key(action = KeyEvent.ACTION_UP)))
}
@Test fun releaseIsConsumedEvenIfAnActionChangedTheRoutingContextOrSettings() {
assign(key(), Action.DROIDDECK)
assertTrue(route(key()))
router.bindings = emptyList()
assertTrue(route(key(action = KeyEvent.ACTION_UP), enabled = false, steam = false))
assertEquals(listOf(Action.DROIDDECK), actions)
}
@Test fun aRepeatedDownWithoutAnInitialPressDoesNotTriggerAnAction() {
assign(key(), Action.QAM)
assertTrue(route(key(repeat = 1)))
assertTrue(route(key(action = KeyEvent.ACTION_UP)))
assertTrue(actions.isEmpty())
}
@Test fun disabledMappedConfirmLeavesTheWholePressForDrawerNavigation() {
assign(key(KeyEvent.KEYCODE_BUTTON_A), Action.DROIDDECK)
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A), enabled = false))
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, repeat = 1), enabled = false))
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false))
assertTrue(actions.isEmpty())
}
@Test fun mappedConfirmOpeningTheDrawerConsumesItsReleaseWithoutStayingHeld() {
assign(key(KeyEvent.KEYCODE_BUTTON_A), Action.DROIDDECK)
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A)))
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, repeat = 1), enabled = false))
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false))
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A), enabled = false))
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false))
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A)))
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP)))
assertEquals(listOf(Action.DROIDDECK, Action.DROIDDECK), actions)
}
@Test fun aResumePressKeepsItsRepeatsAndReleaseInTheResumePath() {
assign(key(), Action.STEAM)
assertFalse(route(key(), enabled = false))
assertFalse(route(key(repeat = 1), enabled = false))
assertFalse(route(key(action = KeyEvent.ACTION_UP), enabled = false))
assertTrue(actions.isEmpty())
assertTrue(route(key()))
assertEquals(listOf(Action.STEAM), actions)
}
@Test fun steamActionsAreInactiveOutsideSteamAndAllActionsRespectDisabledContexts() {
for (action in Action.entries) {
assign(key(), action)
assertFalse(route(key(), enabled = false))
assertFalse(route(key(action = KeyEvent.ACTION_UP), enabled = false))
assertEquals(action == Action.DROIDDECK, route(key(), steam = false))
route(key(action = KeyEvent.ACTION_UP), steam = false)
}
assertEquals(listOf(Action.DROIDDECK), actions)
}
@Test fun reassigningAButtonReplacesItsPreviousAction() {
assign(key(), Action.STEAM)
assign(key(), Action.QAM)
assertEquals(listOf(Action.QAM), PhysicalShortcuts.read(context).map { it.action })
assertTrue(route(key()))
assertEquals(listOf(Action.QAM), actions)
}
@Test fun reassigningAnActionOnlyReplacesThatControllersBinding() {
val second = device(11, "bluetooth")
assign(key(), Action.STEAM)
assign(key(device = second), Action.STEAM)
assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.STEAM)
val saved = PhysicalShortcuts.read(context)
assertEquals(2, saved.size)
assertTrue(saved.any { it.button.sameInput(button(key(device = second))) })
assertTrue(saved.any { it.button.sameInput(button(key(KeyEvent.KEYCODE_BUTTON_2))) })
assertFalse(route(key()))
}
@Test fun deviceIdentitySurvivesReconnectionButDoesNotMatchAnUnrelatedController() {
assign(key(), Action.QAM)
assertFalse(route(key(device = device(11, "other"))))
val reconnected = device(12, "retroid")
assertTrue(route(key(device = reconnected)))
assertEquals(listOf(Action.QAM), actions)
}
@Test fun scanCodesDistinguishButtonsSharingAnAndroidKeyCode() {
assign(key(scan = 700), Action.STEAM)
assign(key(scan = 701), Action.QAM)
assertEquals(2, PhysicalShortcuts.read(context).size)
assertTrue(route(key(scan = 700)))
assertTrue(route(key(scan = 701)))
assertFalse(route(key(scan = 702)))
assertEquals(listOf(Action.STEAM, Action.QAM), actions)
}
@Test fun keyboardLikeExtraButtonsCanBeExplicitlyAssignedWithoutChangingKeyboardDefaults() {
val keyboard = device(11, "m1-keyboard", InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_ALPHABETIC)
val m1 = key(KeyEvent.KEYCODE_F1, device = keyboard)
assertFalse(PadBridge.isControllerKeyEvent(m1))
assign(m1, Action.STEAM)
assertTrue(route(m1))
assertFalse(route(key(KeyEvent.KEYCODE_F2, device = keyboard)))
assertEquals(listOf(Action.STEAM), actions)
}
@Test fun virtualAndSystemKeysCannotBeAssigned() {
val virtual = device(-1, "virtual")
assertNull(PhysicalShortcuts.button(key(device = virtual)))
for (code in listOf(KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_APP_SWITCH,
KeyEvent.KEYCODE_SLEEP, KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_VOLUME_UP,
KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) {
assertNull(PhysicalShortcuts.button(key(code)))
}
assertNull(PhysicalShortcuts.button(key(KeyEvent.KEYCODE_UNKNOWN, scan = 0)))
assertNotNull(PhysicalShortcuts.button(key(KeyEvent.KEYCODE_UNKNOWN, scan = 700)))
}
@Test fun drawerDirectionalKeysRemainAvailableForNavigation() {
for (code in listOf(KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT)) {
assertTrue(PhysicalShortcuts.isDrawerNavigationKey(key(code)))
}
assertFalse(PhysicalShortcuts.isDrawerNavigationKey(key(KeyEvent.KEYCODE_BUTTON_A)))
}
@Test fun resetAndRemovalPreserveOtherControllerSettings() {
ControllerPrefs.setSelectSteam(context, true)
ControllerPrefs.setTarget(context, "a", "b")
assign(key(), Action.STEAM)
assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM)
PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).first())
assertEquals(listOf(Action.QAM), PhysicalShortcuts.read(context).map { it.action })
PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).single())
assertTrue(PhysicalShortcuts.read(context).isEmpty())
assertTrue(ControllerPrefs.read(context).selectSteam)
assertEquals("b", ControllerPrefs.target(context, "a"))
assign(key(), Action.STEAM)
ControllerPrefs.resetAll(context)
assertTrue(PhysicalShortcuts.read(context).isEmpty())
}
@Test fun disconnectAndPauseClearHeldButtons() {
assign(key(), Action.QAM)
assertTrue(route(key()))
router.onDeviceRemoved(pad.id)
assertFalse(route(key(action = KeyEvent.ACTION_UP)))
assertTrue(route(key()))
router.clear()
assertFalse(route(key(action = KeyEvent.ACTION_UP)))
assertTrue(route(key()))
assertEquals(listOf(Action.QAM, Action.QAM, Action.QAM), actions)
}
@Test fun malformedPreferencesDoNotCrashInputDispatch() {
ControllerPrefs.prefs(context).edit().putString("physicalShortcuts", "invalid").commit()
assertTrue(PhysicalShortcuts.read(context).isEmpty())
}
@Test fun malformedEntriesDoNotDiscardValidAssignmentsWhenSaving() {
assign(key(), Action.STEAM)
assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM)
val entries = JSONArray(ControllerPrefs.prefs(context).getString("physicalShortcuts", null))
val damaged = JSONArray().put(entries.getJSONObject(0)).put(JSONObject().put("action", "STEAM"))
.put("not an object").put(entries.getJSONObject(1))
ControllerPrefs.prefs(context).edit().putString("physicalShortcuts", damaged.toString()).commit()
assertEquals(listOf(Action.STEAM, Action.QAM), PhysicalShortcuts.read(context).map { it.action })
assign(key(KeyEvent.KEYCODE_BUTTON_3), Action.DROIDDECK)
assertEquals(listOf(Action.STEAM, Action.QAM, Action.DROIDDECK),
PhysicalShortcuts.read(context).map { it.action })
}
@Test fun buttonSummaryKeepsTechnicalDetailsSeparate() {
val select = button(key(KeyEvent.KEYCODE_BUTTON_SELECT, scan = 314))
val androidName = KeyEvent.keyCodeToString(KeyEvent.KEYCODE_BUTTON_SELECT)
assertEquals(androidName.removePrefix("KEYCODE_").removePrefix("BUTTON_"), select.label)
assertFalse(select.label.contains("(314)"))
}
private fun assign(event: KeyEvent, action: Action) {
PhysicalShortcuts.assign(context, button(event), action)
router.bindings = PhysicalShortcuts.read(context)
}
private fun button(event: KeyEvent) = requireNotNull(PhysicalShortcuts.button(event))
private fun route(event: KeyEvent, enabled: Boolean = true, steam: Boolean = true) =
router.onKey(event, enabled, steam) { actions.add(it) }
private fun key(code: Int = KeyEvent.KEYCODE_BUTTON_1, action: Int = KeyEvent.ACTION_DOWN,
repeat: Int = 0, scan: Int = 700, device: InputDevice = pad): KeyEvent =
KeyEvent(100L, 100L, action, code, repeat, 0, device.id, scan, 0, device.sources)
private fun device(id: Int, descriptor: String, sources: Int = InputDevice.SOURCE_GAMEPAD,
type: Int = InputDevice.KEYBOARD_TYPE_NONE): InputDevice {
val device = InputDeviceBuilder.newBuilder().setId(id).setName("Test $descriptor")
.setDescriptor(descriptor).setSources(sources).setKeyboardType(type)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build()
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
return device
}
}
@@ -68,6 +68,22 @@ class ScreenKeysTest {
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
}
@Test fun takesTouchAtMatchesWhatATouchDoes() {
val keys = ScreenKeys(context) { _, _ -> }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_W))
var checked = 0
for (x in 0 until 1000 step 25) for (y in 0 until 600 step 25) {
val expected = keys.takesTouchAt(x.toFloat(), y.toFloat())
val down = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, x.toFloat(), y.toFloat(), 0)
assertEquals("($x, $y)", expected, keys.onTouchEvent(down))
down.recycle()
MotionEvent.obtain(0L, 1L, MotionEvent.ACTION_UP, x.toFloat(), y.toFloat(), 0).also { keys.onTouchEvent(it); it.recycle() }
if (expected) checked++
}
assertTrue("some points land on the key", checked > 0)
}
@Test fun loadingLayoutReleasesLatchedKeysBeforeReplacingEntries() {
val sent = mutableListOf<Pair<Int, Boolean>>()
val keys = ScreenKeys(context) { code, down -> sent += code to down }
@@ -0,0 +1,26 @@
package com.droiddeck.launcher.input
import org.junit.Assert.assertEquals
import org.junit.Test
class SecondScreenModeTest {
@Test fun withNothingRememberedTheControllerPicksThePanel() {
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false))
}
@Test fun thePanelTheUserPickedLastOpensAgain() {
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true))
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("deck-controls", deckPad = true))
assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad = true))
}
@Test fun deckControlsNeedTheDeckPad() {
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false))
}
@Test fun anUnknownOrClosedChoiceFallsBackToTheDefault() {
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad = false))
}
}
@@ -220,7 +220,12 @@ 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) }
}, object : DirectTouchHold.Touch {
override fun down(pointerId: Int, x: Float, y: Float) {}
override fun move(pointerId: Int, x: Float, y: Float) {}
override fun up(pointerId: Int, x: Float, y: Float) {}
override fun cancel() {}
}).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())
}
}
@@ -25,11 +25,14 @@ class TouchpadGesturesTest {
private val listener = object : PointerGestures.Listener {
override fun onMove(x: Float, y: Float) { events += "move" }
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
val name = if (button == PointerGestures.BTN_RIGHT) "right" else "left"
val name = when (button) { PointerGestures.BTN_RIGHT -> "right"; PointerGestures.BTN_MIDDLE -> "middle"; else -> "left" }
events += "$name ${if (pressed) "down" else "up"}"
}
override fun onWheel(steps: Int) { events += "wheel $steps" }
override fun onLongPress() { events += "long press" }
override fun onScroll(dx: Float, dy: Float) { events += "scroll" }
override fun onScrollEnd() { events += "scroll end" }
override fun onZoom(steps: Int) { events += "zoom $steps" }
}
@Before fun setUp() {
@@ -41,12 +44,58 @@ class TouchpadGesturesTest {
@Test fun tapHoldsTheLeftButtonBeforeReleasingIt() {
tap()
assertEquals(listOf("left down"), events)
advance(40)
advance(TouchTiming.CLICK_MS - 10)
assertEquals(listOf("left down"), events)
advance(100)
assertEquals(listOf("left down", "left up"), events)
}
@Test fun threeFingerTapClicksTheMiddleButton() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 2, 1 to (400f to 300f), 2 to (600f to 310f), 3 to (800f to 320f))
advance(60)
touch(MotionEvent.ACTION_POINTER_UP, 2, 1 to (400f to 300f), 2 to (600f to 310f), 3 to (800f to 320f))
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 310f))
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
advance(100)
assertEquals(listOf("middle down", "middle up"), events)
}
@Test fun desktopTwoFingerSlideScrollsSmoothlyAndStops() {
touchpad.desktop = true
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 300f))
for (step in 1..5) {
advance(16)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 300f + step * 20f), 2 to (600f to 300f + step * 20f))
}
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 400f), 2 to (600f to 400f))
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 400f))
advance(100)
assertTrue(events.contains("scroll"))
assertEquals("scroll end", events.last())
assertFalse(events.any { it.startsWith("right") || it.startsWith("wheel") })
}
@Test fun desktopPinchZoomsWithoutScrolling() {
touchpad.desktop = true
touch(MotionEvent.ACTION_DOWN, 0, 1 to (500f to 300f))
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (500f to 300f), 2 to (600f to 300f))
for (step in 1..6) {
advance(16)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (500f - step * 30f to 300f), 2 to (600f + step * 30f to 300f))
}
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (320f to 300f), 2 to (780f to 300f))
touch(MotionEvent.ACTION_UP, 0, 1 to (320f to 300f))
advance(100)
assertTrue(events.isNotEmpty() && events.all { it.startsWith("zoom -") })
}
@Test fun twoFingerTapHoldsTheRightButtonBeforeReleasingIt() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(10)
@@ -56,7 +105,7 @@ class TouchpadGesturesTest {
advance(10)
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
assertEquals(listOf("right down"), events)
advance(30)
advance(TouchTiming.CLICK_MS - 20)
assertEquals(listOf("right down"), events)
advance(100)
assertEquals(listOf("right down", "right up"), events)
@@ -71,7 +120,7 @@ class TouchpadGesturesTest {
advance(10)
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
assertEquals(listOf("right down"), events)
advance(40)
advance(TouchTiming.CLICK_MS - 10)
assertEquals(listOf("right down"), events)
advance(100)
assertEquals(listOf("right down", "right up"), events)
@@ -82,9 +82,9 @@ class TouchscreenGesturesTest {
@Test fun aVeryFastDoubleTapKeepsFullPressesAndAReleaseGap() {
tap(); tap(); advance(250)
assertEquals(4, leftClicks.size)
assertTrue(leftClicks[1].time - leftClicks[0].time >= 50)
assertTrue(leftClicks[2].time - leftClicks[1].time >= 50)
assertTrue(leftClicks[3].time - leftClicks[2].time >= 50)
assertTrue(leftClicks[1].time - leftClicks[0].time >= TouchTiming.CLICK_MS)
assertTrue(leftClicks[2].time - leftClicks[1].time >= TouchTiming.CLICK_MS)
assertTrue(leftClicks[3].time - leftClicks[2].time >= TouchTiming.CLICK_MS)
}
@Test fun doubleTapUsesTheFirstClickLocationDespiteNormalFingerDrift() {
@@ -121,7 +121,7 @@ class TouchscreenGesturesTest {
gestures.configure(TouchGestureConfig(tapEnabled = false))
tap(); tap(); advance(250)
assertEquals(4, leftClicks.size)
assertTrue(leftClicks[2].time - leftClicks[1].time >= 50)
assertTrue(leftClicks[2].time - leftClicks[1].time >= TouchTiming.CLICK_MS)
}
@Test fun aRapidThirdTapDoesNotDiscardThePendingSecondClick() {
@@ -285,11 +285,11 @@ class TouchscreenGesturesTest {
@Test fun twoFingerTapKeepsItsPressAfterTheLastFingerLifts() {
twoFingerTap()
assertEquals(listOf("button 273 true"), buttons())
advance(49)
advance(TouchTiming.CLICK_MS - 1)
assertEquals(1, rightClicks.size)
advance(1)
assertEquals(listOf(true, false), rightClicks.map { it.down })
assertEquals(50L, rightClicks[1].time - rightClicks[0].time)
assertEquals(TouchTiming.CLICK_MS, rightClicks[1].time - rightClicks[0].time)
}
@Test fun threeFingerKeyboardTapHasAnObservablePressAndReleases() {
@@ -298,14 +298,14 @@ class TouchscreenGesturesTest {
assertEquals(listOf("key 18 true"), events.filter { it.startsWith("key") })
advance(50)
assertEquals(listOf("key 18 true", "key 18 false"), events.filter { it.startsWith("key") })
assertEquals(50L, timedKeys.last().first - timedKeys.first().first)
assertEquals(TouchTiming.CLICK_MS, timedKeys.last().first - timedKeys.first().first)
}
@Test fun twoFingerKeyboardTapHasAnObservablePressAndReleases() {
gestures.configure(TouchGestureConfig(twoFingerTapAction = "key_E"))
twoFingerTap(); advance(50)
assertEquals(listOf(true, false), timedKeys.map { it.third })
assertEquals(50L, timedKeys.last().first - timedKeys.first().first)
assertEquals(TouchTiming.CLICK_MS, timedKeys.last().first - timedKeys.first().first)
}
@Test fun threeFingerMouseTapHasAnObservablePressAndReleases() {
@@ -314,7 +314,7 @@ class TouchscreenGesturesTest {
assertEquals(listOf("button 273 true"), buttons())
advance(50)
assertEquals(listOf(true, false), rightClicks.map { it.down })
assertEquals(50L, rightClicks[1].time - rightClicks[0].time)
assertEquals(TouchTiming.CLICK_MS, rightClicks[1].time - rightClicks[0].time)
}
@Test fun cancellingAMultiFingerTapReleasesItsButtonAndStopsCallbacks() {
@@ -338,7 +338,7 @@ class TouchscreenGesturesTest {
gestures.configure(TouchGestureConfig(tapAction = "right_click", doubleTapEnabled = false))
tap(); tap(); advance(250)
assertEquals(listOf(true, false, true, false), rightClicks.map { it.down })
assertTrue(rightClicks[2].time - rightClicks[1].time >= 50)
assertTrue(rightClicks[2].time - rightClicks[1].time >= TouchTiming.CLICK_MS)
}
@Test fun aFastTwoFingerSwipeDuringSettlingDoesNotClick() {
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.view.MotionEvent
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class TwoFingerGesturesTest {
private val calls = mutableListOf<String>()
private val gestures = TwoFingerGestures(8f, object : TwoFingerGestures.Listener {
override fun cancelTouch() { calls += "cancel" }
override fun replay(event: MotionEvent) { calls += "replay ${event.actionMasked}" }
override fun rightClick(x: Float, y: Float) { calls += "right $x,$y" }
override fun scrollStart(x: Float, y: Float) { calls += "start $x,$y" }
override fun scroll(dx: Float, dy: Float) { calls += "scroll $dx,$dy" }
override fun scrollEnd() { calls += "end" }
})
private var time = 1000L
private var downTime = 0L
private val a = 1 to (400f to 300f)
private val b = 2 to (500f to 300f)
@Test fun tapRightClicksWhereTheFirstFingerLanded() {
assertTrue(touch(MotionEvent.ACTION_DOWN, 0, a))
time += 20
assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b))
time += 80
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 1, a, b))
assertTrue(touch(MotionEvent.ACTION_UP, 0, a))
assertEquals(listOf("cancel", "right 400.0,300.0"), calls)
}
@Test fun holdRightClicksOnce() {
touch(MotionEvent.ACTION_DOWN, 0, a)
time += 20
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(TwoFingerGestures.HOLD_MS + 10))
time += 600
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 1, a, b))
assertTrue(touch(MotionEvent.ACTION_UP, 0, a))
assertEquals(listOf("cancel", "right 400.0,300.0"), calls)
}
@Test fun slidingTogetherScrollsLikeAWheel() {
touch(MotionEvent.ACTION_DOWN, 0, a)
time += 20
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
time += 20
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 260f), 2 to (500f to 260f)))
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 200f), 2 to (500f to 200f)))
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 200f), 2 to (500f to 200f)))
assertTrue(touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 200f)))
assertEquals(listOf("cancel", "start 450.0,260.0", "scroll 0.0,60.0", "end"), calls)
}
@Test fun pinchPassesThroughForZoom() {
touch(MotionEvent.ACTION_DOWN, 0, a)
time += 20
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (350f to 300f), 2 to (550f to 300f)))
assertEquals(listOf("replay 0", "replay 5", "replay 2"), calls)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(TwoFingerGestures.HOLD_MS + 10))
assertFalse(touch(MotionEvent.ACTION_MOVE, 0, 1 to (340f to 300f), 2 to (560f to 300f)))
assertFalse(touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (340f to 300f), 2 to (560f to 300f)))
assertFalse(touch(MotionEvent.ACTION_UP, 0, 1 to (340f to 300f)))
assertEquals(3, calls.size)
}
@Test fun oneFingerTapIsReplayedOnRelease() {
assertTrue(touch(MotionEvent.ACTION_DOWN, 0, a))
assertTrue(calls.isEmpty())
time += 60
assertTrue(touch(MotionEvent.ACTION_UP, 0, a))
assertEquals(listOf("replay 0", "replay 1"), calls)
}
@Test fun oneFingerStillIsReplayedAfterTheLandingWindow() {
assertTrue(touch(MotionEvent.ACTION_DOWN, 0, a))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(TwoFingerGestures.LAND_MS + 10))
assertEquals(listOf("replay 0"), calls)
time += 600
assertFalse(touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b))
assertFalse(touch(MotionEvent.ACTION_POINTER_UP, 1, a, b))
assertFalse(touch(MotionEvent.ACTION_UP, 0, a))
assertEquals(listOf("replay 0"), calls)
}
@Test fun oneFingerDragIsReplayedOnceItMoves() {
touch(MotionEvent.ACTION_DOWN, 0, a)
time += 16
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (402f to 300f)))
assertTrue(calls.isEmpty())
time += 16
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (440f to 300f)))
assertEquals(listOf("replay 0", "replay 2", "replay 2"), calls)
assertFalse(touch(MotionEvent.ACTION_MOVE, 0, 1 to (480f to 300f)))
assertFalse(touch(MotionEvent.ACTION_UP, 0, 1 to (480f to 300f)))
}
private fun touch(action: Int, index: Int, vararg pointers: Pair<Int, Pair<Float, Float>>): Boolean {
if (action == MotionEvent.ACTION_DOWN) downTime = time
val properties = pointers.map { (id, _) ->
MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER }
}.toTypedArray()
val coords = pointers.map { (_, at) ->
MotionEvent.PointerCoords().apply { x = at.first; y = at.second; pressure = 1f; size = 1f }
}.toTypedArray()
val masked = action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
val event = MotionEvent.obtain(downTime, time, masked, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
return gestures.onTouch(event).also { event.recycle() }
}
}
@@ -0,0 +1,47 @@
package com.droiddeck.launcher.runtime
import org.junit.Assert.assertEquals
import org.junit.Test
class AccountsMergeTest {
private val own = "root:x:10123:10123:root:/root:/bin/bash"
private val zero = "root:x:0:0:root:/root:/bin/bash"
@Test fun systemUsersSurvive() {
val existing = "root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n_apt:x:42:65534::/nonexistent:/usr/sbin/nologin\nmessagebus:x:100:102::/nonexistent:/usr/sbin/nologin\n"
assertEquals("$own\n$zero\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n_apt:x:42:65534::/nonexistent:/usr/sbin/nologin\nmessagebus:x:100:102::/nonexistent:/usr/sbin/nologin\n",
LinuxRuntime.mergedAccounts(existing, 2, own, zero, 10123))
}
@Test fun anOldSingleLineFileIsReplacedOnce() {
val merged = LinuxRuntime.mergedAccounts("$own\n", 2, own, zero, 10123)
assertEquals("$own\n$zero\n", merged)
assertEquals(merged, LinuxRuntime.mergedAccounts(merged, 2, own, zero, 10123))
}
@Test fun anotherAppUidIsDropped() {
assertEquals("$own\n$zero\n", LinuxRuntime.mergedAccounts("root:x:10099:10099:root:/root:/bin/bash\n", 2, own, zero, 10123))
}
@Test fun noFileYet() {
assertEquals("$own\n$zero\n", LinuxRuntime.mergedAccounts(null, 2, own, zero, 10123))
}
@Test fun groupsKeepMembers() {
val existing = "root:x:0:\nsudo:x:27:\naudio:x:29:pulse\n"
assertEquals("root:x:10123:\nroot:x:0:\nsudo:x:27:\naudio:x:29:pulse\n",
LinuxRuntime.mergedAccounts(existing, 2, "root:x:10123:", "root:x:0:", 10123))
}
@Test fun storageGroupsAreAddedWithRoot() {
assertEquals("root:x:0:\nsudo:x:27:\nsdcard_rw:x:1015:root\nmedia_rw:x:1023:root\neverybody:x:9997:root\n",
LinuxRuntime.withStorageGroups("root:x:0:\nsudo:x:27:\n"))
}
@Test fun existingStorageGroupsGainRootOnce() {
val existing = "root:x:0:\nmedia_rw:x:1023:pulse\nsdcard_rw:x:1015:root\nshared:x:9997:\n"
val updated = LinuxRuntime.withStorageGroups(existing)
assertEquals("root:x:0:\nmedia_rw:x:1023:pulse,root\nsdcard_rw:x:1015:root\nshared:x:9997:root\n", updated)
assertEquals(updated, LinuxRuntime.withStorageGroups(updated))
}
}
@@ -160,4 +160,25 @@ class BwrapSpawnerPlanTest {
assertFalse(plan.binds.any { it.guest.startsWith("/app/bin/") })
assertFalse(File(dir, "zypak-wrapper").exists())
}
@Test fun preloadsStayOutOfSandboxesWithAnOlderGlibc() {
val base = Files.createTempDirectory("glibc").toFile()
try {
val rootfs = File(base, "rootfs")
File(rootfs, "usr/local/lib").mkdirs()
File(rootfs, "etc").mkdirs()
File(rootfs, "etc/ld.so.preload").writeText("/usr/local/lib/libone.so\n/usr/local/lib/libtwo.so\n")
File(rootfs, "usr/local/lib/libone.so").writeText("x GLIBC_2.17 y GLIBC_2.34 z")
File(rootfs, "usr/local/lib/libtwo.so").writeText("GLIBC_2.38 GLIBC_2.25")
val old = File(base, "old-libc").apply { writeText("GNU C Library (Ubuntu GLIBC 2.23-0ubuntu11) stable release version 2.23, by Roland") }
val new = File(base, "new-libc").apply { writeText("GNU C Library (Ubuntu GLIBC 2.43-0ubuntu1) stable release version 2.43.") }
val same = File(base, "same-libc").apply { writeText("stable release version 2.38.") }
assertFalse(BwrapSpawner.preloadFits(rootfs.path, old.path))
assertTrue(BwrapSpawner.preloadFits(rootfs.path, new.path))
assertTrue(BwrapSpawner.preloadFits(rootfs.path, same.path))
assertTrue(BwrapSpawner.preloadFits(rootfs.path, File(base, "missing").path))
} finally {
base.deleteRecursively()
}
}
}
@@ -76,4 +76,22 @@ class DesktopFileRemovalTest {
file("var/lib/pacman/local/base-1/files", "%FILES%\nusr/\nusr/bin/\nusr/bin/gamescope\n\n%BACKUP%\netc/config\n")
assertEquals(setOf("usr/bin/gamescope"), DesktopFileRemoval.runtimeFiles(root))
}
@Test fun desktopPackageRecordsAreNotRuntimeFilesAndAreRemovedWithTheDesktop() {
file("var/lib/pacman/local/base-1/files", "%FILES%\nusr/bin/gamescope\n")
file("var/lib/pacman/local/kate-26.04.3-1/files", "%FILES%\nusr/bin/kate\n")
file("var/lib/pacman/local/kate-26.04.3-1/desc", "%NAME%\nkate\n")
file("var/lib/pacman/local/htop-3.5.3-1/files", "%FILES%\nusr/bin/htop\n")
file("var/lib/pacman/sync/droiddeck.db", "db")
file("var/lib/pacman/droiddeck-desktop", "stamp")
file("usr/share/droiddeck/pacman/desktop-packages.txt", "kate 26.04.3-1\n../../etc 1\n")
val records = DesktopFileRemoval.desktopRecords(root)
assertEquals(setOf("kate-26.04.3-1"), records)
assertEquals(setOf("usr/bin/gamescope", "usr/bin/htop"), DesktopFileRemoval.runtimeFiles(root))
DesktopFileRemoval.removeRecords(root, records)
assertFalse(File(root, "var/lib/pacman/local/kate-26.04.3-1").exists())
assertTrue(File(root, "var/lib/pacman/local/htop-3.5.3-1/files").exists())
assertFalse(File(root, "var/lib/pacman/sync/droiddeck.db").exists())
assertFalse(File(root, "var/lib/pacman/droiddeck-desktop").exists())
}
}
@@ -0,0 +1,145 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.Hashes
import java.io.File
import java.nio.file.Files
import java.util.zip.GZIPOutputStream
import org.junit.After
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 org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class DesktopPackTest {
private val parent = Files.createTempDirectory("pack").toFile()
private val root = File(parent, "root").apply { mkdirs() }
@After fun tearDown() { FileUtils.delete(parent) }
private fun file(path: String, text: String) = File(root, path).apply { parentFile?.mkdirs(); writeText(text) }
private fun line(kind: Char, path: String): String {
val file = File(root, path)
return when {
Files.isSymbolicLink(file.toPath()) -> "$kind\tL\t0\t${Files.readSymbolicLink(file.toPath())}\t$path"
file.isDirectory -> "$kind\tD\t0\t-\t$path"
else -> "$kind\tF\t${file.length()}\t${Hashes.sha256(file)}\t$path"
}
}
private fun manifest(lines: List<String>) {
val target = File(root, "${DesktopPack.META}/files.tsv.gz").apply { parentFile?.mkdirs() }
GZIPOutputStream(target.outputStream()).bufferedWriter().use { w -> lines.forEach { w.write(it); w.write("\n") } }
}
private fun installed(): List<String> {
File(root, DesktopPack.INFO).apply { parentFile?.mkdirs() }
.writeText("""{"tag":"ubuntu-r1-desktop","url":"https://example.invalid/d.tar.zst","sha256":"00","size":5}""")
file("usr/bin/runtime-tool", "runtime")
file("${DesktopPack.META}/originals/var/lib/dpkg/status", "Package: bash\n")
file("${DesktopPack.META}/originals/etc/gone.conf", "removed by the desktop")
file("${DesktopPack.META}/originals/etc/group", "root:x:0:")
file("${DesktopPack.META}/originals/etc/hosts", "runtime hosts")
file("etc/group", "root:x:0:\nsddm:x:120:")
file("etc/hosts", "desktop hosts")
file("var/lib/dpkg/status", "Package: bash\n\nPackage: kwin\n")
file("usr/bin/kwin_wayland", "kwin")
file("usr/share/kwin/effect.qml", "effect")
file("usr/share/kwin/edited.qml", "original")
Files.createSymbolicLink(File(root, "usr/bin/kwin").toPath(), File("kwin_wayland").toPath())
val lines = listOf(
line('N', "usr/share/kwin"), line('N', "usr/bin/kwin_wayland"), line('N', "usr/share/kwin/effect.qml"),
line('N', "usr/share/kwin/edited.qml"), line('N', "usr/bin/kwin"), line('C', "var/lib/dpkg/status"), line('C', "etc/group"), line('C', "etc/hosts"),
"R\tF\t22\tx\tetc/gone.conf", "N\tF\t1\tx\t../escape",
)
file("usr/share/kwin/edited.qml", "changed by the user")
file("etc/hosts", "edited by the user")
file("var/lib/dpkg/status", "Package: bash\n\nPackage: kwin\n\nPackage: vlc\n")
return lines
}
@Test fun readsThePackTheRuntimeNames() {
installed()
val info = DesktopPack.info(root)!!
assertEquals("ubuntu-r1-desktop", info.tag)
assertEquals(5L, info.size)
}
@Test fun removingPutsTheRuntimeBackAndKeepsWhatTheUserChanged() {
manifest(installed())
val result = DesktopPack.remove(root)
assertEquals("Package: bash\n", File(root, "var/lib/dpkg/status").readText())
assertEquals("removed by the desktop", File(root, "etc/gone.conf").readText())
assertEquals("root:x:0:", File(root, "etc/group").readText())
assertEquals("edited by the user", File(root, "etc/hosts").readText())
assertFalse(File(root, "usr/bin/kwin_wayland").exists())
assertFalse(Files.exists(File(root, "usr/bin/kwin").toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS))
assertFalse(File(root, "usr/share/kwin/effect.qml").exists())
assertEquals("changed by the user", File(root, "usr/share/kwin/edited.qml").readText())
assertTrue(File(root, "usr/share/kwin").isDirectory)
assertEquals("runtime", File(root, "usr/bin/runtime-tool").readText())
assertFalse(File(root, DesktopPack.META).exists())
assertFalse(DesktopPack.installed(root))
assertEquals(3, result.removed)
assertEquals(3, result.restored)
assertEquals(3, result.kept)
}
@Test fun emptiedDirectoriesGoAway() {
val lines = installed()
File(root, "usr/share/kwin/edited.qml").delete()
manifest(lines)
DesktopPack.remove(root)
assertFalse(File(root, "usr/share/kwin").exists())
assertTrue(File(root, "usr/share").isDirectory)
}
@Test fun finishingAnInstallDeletesWhatTheDesktopRemoved() {
file("etc/gone.conf", "runtime copy")
manifest(listOf("R\tF\t22\tx\tetc/gone.conf", "R\tF\t1\tx\t../outside"))
File(root.parentFile, "outside").writeText("keep")
DesktopPack.finishInstall(root)
assertFalse(File(root, "etc/gone.conf").exists())
assertTrue(File(root.parentFile, "outside").exists())
File(root.parentFile, "outside").delete()
}
@Test fun theDesktopKeepsPackagesTheUserInstalledBeforeIt() {
val bash = "Package: bash\nArchitecture: arm64\nVersion: 5.2"
val vim = "Package: vim\nArchitecture: arm64\nVersion: 9"
val kwin = "Package: kwin\nArchitecture: arm64\nVersion: 6.6"
file("var/lib/dpkg/status", "$bash\n\n$vim\n\n")
DesktopPack.prepareInstall(root)
file("${DesktopPack.META}/originals/var/lib/dpkg/status", "$bash\n\n")
file("var/lib/dpkg/status", "$bash\n\n$kwin\n\n")
manifest(listOf(line('C', "var/lib/dpkg/status")))
DesktopPack.finishInstall(root)
assertEquals("$bash\n\n$kwin\n\n$vim\n\n", File(root, "var/lib/dpkg/status").readText())
assertFalse(File(root, "var/lib/dpkg/status.droiddeck").exists())
val vlc = "Package: vlc\nArchitecture: arm64\nVersion: 3"
file("var/lib/dpkg/status", "$bash\n\n$kwin\n\n$vim\n\n$vlc\n\n")
DesktopPack.remove(root)
assertEquals("$bash\n\n$vim\n\n$vlc\n\n", File(root, "var/lib/dpkg/status").readText())
}
@Test fun mergingKeepsTheTargetWhenBothSidesChangedAPackage() {
val base = "Package: a\nVersion: 1\n\nPackage: b\nVersion: 1\n\nPackage: c\nVersion: 1\n"
val target = "Package: a\nVersion: 2\n\nPackage: b\nVersion: 1\n\nPackage: c\nVersion: 1\n"
val mine = "Package: a\nVersion: 3\n\nPackage: b\nVersion: 3\n"
assertEquals("Package: a\nVersion: 2\n\nPackage: b\nVersion: 3\n\n", DesktopPack.mergeStatus(base, target, mine))
}
@Test fun pathsMayNotLeaveTheRuntime() {
assertNull(DesktopPack.inside(root, "../x"))
assertNull(DesktopPack.inside(root, "/etc/passwd"))
Files.createSymbolicLink(File(root, "link").toPath(), root.parentFile.toPath())
assertNull(DesktopPack.inside(root, "link/x"))
assertEquals(File(root, "usr/x"), DesktopPack.inside(root, "usr/./x"))
}
}
@@ -66,14 +66,25 @@ class DeviceControlsComponentTest {
assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC))
}
@Test fun deniedBrightnessIsReadBackAndAppliedOnlyAfterPermission() {
@Test fun everyVolumeStepIsPublishedWithoutWaitingForThePoll() {
for (level in 2..5) {
audio.setStreamVolume(AudioManager.STREAM_MUSIC, level, 0)
context.sendBroadcast(android.content.Intent("android.media.VOLUME_CHANGED_ACTION"))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(level.toString(), File(directory, "volume.state").readText().split(" ").first())
}
}
@Test fun deniedBrightnessDoesNotOpenSettingsOrReplayAnOldSliderValueAfterPermission() {
WriteSettingsShadow.writable = false
request("brightness", "0.75")
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
assertEquals(Settings.ACTION_MANAGE_WRITE_SETTINGS, shadowOf(context).nextStartedActivity.action)
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))
}
@@ -87,7 +98,7 @@ class DeviceControlsComponentTest {
assertEquals(1.0, JSONObject(File(directory, "state.json").readText()).getDouble("brightness"), 0.0001)
}
@Test fun hiddenPermissionRequestOffersANotificationAndRetainsTheLatestValue() {
@Test fun permissionNotificationOpensOptionalLauncherSetupOnlyWhenSelected() {
visible = false
WriteSettingsShadow.writable = false
request("brightness", "0.25")
@@ -96,11 +107,13 @@ class DeviceControlsComponentTest {
val notifications = context.getSystemService(NotificationManager::class.java)
val notification = notifications.activeNotifications.single().notification
notification.contentIntent.send()
assertEquals(Settings.ACTION_MANAGE_WRITE_SETTINGS, shadowOf(context).nextStartedActivity.action)
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(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
assertTrue(notifications.activeNotifications.isEmpty())
}
@@ -123,15 +136,15 @@ class DeviceControlsComponentTest {
assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))
}
@Test fun rejectedPermissionCanBeRequestedAgainWithoutOpeningRepeatedScreens() {
@Test fun repeatedSliderChangesDoNotInterruptTheSession() {
WriteSettingsShadow.writable = false
request("brightness", "0.75")
assertNotNull(shadowOf(context).nextStartedActivity)
assertNull(shadowOf(context).nextStartedActivity)
request("brightness", "0.8")
assertNull(shadowOf(context).nextStartedActivity)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(5))
request("brightness", "0.8")
assertNotNull(shadowOf(context).nextStartedActivity)
assertNull(shadowOf(context).nextStartedActivity)
}
@Test fun oversizedRequestsAreDiscardedAndDoNotBlockLaterCommands() {
@@ -0,0 +1,102 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.FileUtils
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class L2sLinkTest {
private val dir = Files.createTempDirectory("l2s").toFile()
@After fun tearDown() { FileUtils.delete(dir) }
@Test fun aHardLinkBecomesProotsLinkLayout() {
val bin = File(dir, "usr/bin").apply { mkdirs() }
val coreutils = File(bin, "coreutils").apply { writeText("multicall") }
val tail = File(bin, "tail")
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, tail))
val intermediate = File(bin, ".l2s.coreutils0001")
assertEquals(intermediate.toPath(), Files.readSymbolicLink(coreutils.toPath()))
assertEquals(intermediate.toPath(), Files.readSymbolicLink(tail.toPath()))
assertEquals(File(bin, ".l2s.coreutils0001.0002").toPath(), Files.readSymbolicLink(intermediate.toPath()))
assertEquals("multicall", tail.readText())
assertEquals("multicall", coreutils.readText())
}
@Test fun eachFurtherLinkRaisesTheCount() {
val bin = File(dir, "usr/bin").apply { mkdirs() }
val coreutils = File(bin, "coreutils").apply { writeText("multicall") }
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, File(bin, "tail")))
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, File(bin, "head")))
assertTrue(LinuxRuntimeInstaller.l2sLink(File(bin, "tail"), File(bin, "cat")))
val final = File(bin, ".l2s.coreutils0001.0004")
assertTrue(final.isFile)
assertFalse(File(bin, ".l2s.coreutils0001.0002").exists())
for (name in listOf("coreutils", "tail", "head", "cat")) assertEquals("multicall", File(bin, name).readText())
}
@Test fun aSecondFileWithTheSameNameGetsItsOwnChain() {
val a = File(dir, "a").apply { mkdirs() }
val existing = File(a, ".l2s.tool0001").apply { writeText("taken") }
val tool = File(a, "tool").apply { writeText("tool") }
assertTrue(LinuxRuntimeInstaller.l2sLink(tool, File(a, "alias")))
assertEquals("taken", existing.readText())
assertEquals(File(a, ".l2s.tool0002").toPath(), Files.readSymbolicLink(tool.toPath()))
assertEquals("tool", File(a, "alias").readText())
}
@Test fun linksMadeInStagingStillResolveAfterTheTreeIsRenamed() {
val staging = File(dir, "linuxfs.new")
val live = File(dir, "linuxfs")
val bin = File(staging, "usr/bin").apply { mkdirs() }
val cargo = File(staging, "usr/lib/cargo/bin/coreutils").apply { mkdirs() }
val coreutils = File(bin, "coreutils").apply { writeText("multicall") }
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, File(cargo, "echo"), staging, live))
assertTrue(LinuxRuntimeInstaller.l2sLink(File(cargo, "echo"), File(cargo, "cat"), staging, live))
assertEquals(File(live, "usr/bin/.l2s.coreutils0001").toPath(), Files.readSymbolicLink(File(cargo, "echo").toPath()))
assertTrue(File(staging, "usr/bin/.l2s.coreutils0001.0003").isFile)
assertTrue(staging.renameTo(live))
for (rel in listOf("usr/bin/coreutils", "usr/lib/cargo/bin/coreutils/echo", "usr/lib/cargo/bin/coreutils/cat"))
assertEquals(rel, "multicall", File(live, rel).readText())
assertTrue(LinuxRuntimeInstaller.l2sLink(File(live, "usr/bin/coreutils"), File(live, "usr/bin/tail")))
assertEquals("multicall", File(live, "usr/bin/tail").readText())
assertTrue(File(live, "usr/bin/.l2s.coreutils0001.0004").isFile)
}
@Test fun aHardLinkTargetMayAlreadyBeAnL2sLinkToTheFinalTree() {
val staging = File(dir, "linuxfs.new")
val live = File(dir, "linuxfs")
val bin = File(staging, "usr/bin").apply { mkdirs() }
File(bin, "coreutils").writeText("multicall")
assertTrue(LinuxRuntimeInstaller.l2sLink(File(bin, "coreutils"), File(bin, "["), staging, live))
assertEquals(File(bin, "coreutils"), LinuxRuntimeInstaller.hardLinkTarget(staging, "./usr/bin/coreutils"))
assertTrue(LinuxRuntimeInstaller.l2sLink(LinuxRuntimeInstaller.hardLinkTarget(staging, "./usr/bin/coreutils"), File(bin, "ls"), staging, live))
assertTrue(staging.renameTo(live))
assertEquals("multicall", File(live, "usr/bin/ls").readText())
}
@Test fun aHardLinkTargetCannotLeaveTheTree() {
val tree = File(dir, "tree").apply { mkdirs() }
val outside = File(dir, "outside").apply { mkdirs() }
Files.createSymbolicLink(File(tree, "escape").toPath(), outside.toPath())
assertEquals(null, LinuxRuntimeInstaller.hardLinkTarget(tree, "../outside/x"))
assertEquals(null, LinuxRuntimeInstaller.hardLinkTarget(tree, "escape/x"))
assertEquals(null, LinuxRuntimeInstaller.hardLinkTarget(tree, ".."))
assertEquals(File(tree, "x"), LinuxRuntimeInstaller.hardLinkTarget(tree, "./x"))
}
@Test fun directoriesAndPlainSymlinksAreLeftAlone() {
val d = File(dir, "d").apply { mkdirs() }
assertFalse(LinuxRuntimeInstaller.l2sLink(d, File(dir, "e")))
val target = File(dir, "t").apply { writeText("t") }
val link = File(dir, "link")
Files.createSymbolicLink(link.toPath(), target.toPath())
assertFalse(LinuxRuntimeInstaller.l2sLink(link, File(dir, "other")))
}
}
@@ -10,6 +10,12 @@ import java.io.File
class ProotFastPathTest {
private val root = File("/data/data/com.droiddeck.launcher/files/linuxfs")
@Test fun guestEnvironmentCarriesTheHostAndroidApi() {
for (sdk in listOf(33, 35, 36)) {
assertTrue(ProotFastPath.guestEnv(root, emptyList(), "test", sdk).contains("PROOT_FP_ANDROID_API=$sdk"))
}
}
@Test fun aSessionsUsualBindsGetAKey() {
val binds = (1..87).map { "/host/$it:/guest/$it" }
assertNotNull(ProotFastPath.key(root, binds))
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.runtime
import android.app.Application
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
class RuntimeAutoUpdateTest {
private val context get() = RuntimeEnvironment.getApplication()
@Test fun anInstalledRuntimeBehindTheCatalogUpdatesByItself() {
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2"))
}
@Test fun noRuntimeOrTheSameOneIsLeftAlone() {
assertFalse(RuntimeAutoUpdate.claim(context, null, "ubuntu-r1-rc2"))
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc2", "ubuntu-r1-rc2"))
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", null))
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", ""))
}
@Test fun aFailingUpdateStopsTryingAfterAFewLaunches() {
repeat(RuntimeAutoUpdate.MAX_ATTEMPTS) { assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", it * RuntimeAutoUpdate.RETRY_MS)) }
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 10 * RuntimeAutoUpdate.RETRY_MS))
}
@Test fun aRetryWaitsBeforeUsingTheNextTry() {
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 1_000L))
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 2_000L))
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 1_000L + RuntimeAutoUpdate.RETRY_MS))
}
@Test fun aNewerCatalogReleaseStartsAgain() {
repeat(RuntimeAutoUpdate.MAX_ATTEMPTS) { RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", it * RuntimeAutoUpdate.RETRY_MS) }
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc3", 5 * RuntimeAutoUpdate.RETRY_MS))
}
@Test fun goingBackToAnEarlierReleaseKeepsItsCount() {
repeat(RuntimeAutoUpdate.MAX_ATTEMPTS) { RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", it * RuntimeAutoUpdate.RETRY_MS) }
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc3", 5 * RuntimeAutoUpdate.RETRY_MS))
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 10 * RuntimeAutoUpdate.RETRY_MS))
}
}
@@ -25,6 +25,7 @@ class RuntimeUserDataCarryTest {
put(old, "root/save.dat", "mine")
put(old, "opt/appimages/user/app1/app.AppImage")
put(old, "opt/droiddeck-apps/game/run.sh")
put(old, "opt/droiddeck/wincomponents/d3dx9/component.json")
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")
@@ -43,6 +44,7 @@ class RuntimeUserDataCarryTest {
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",
"opt/droiddeck/wincomponents/d3dx9/component.json",
"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())
@@ -52,6 +54,47 @@ class RuntimeUserDataCarryTest {
assertFalse("only DroidDeck's own menu entries are user data", File(staging, "usr/local/share/applications/other.desktop").exists())
}
@Test fun aMenuEntryTheNewRuntimeShipsIsNotCarried() {
val old = tmp.newFolder("old").also {
put(it, "root/save.dat", "mine")
put(it, "usr/share/applications/droiddeck-return-gaming.desktop", "old runtime")
put(it, "usr/share/applications/droiddeck-steam-x64.desktop", "made by the old desktop")
}
val staging = tmp.newFolder("new").also {
put(it, "root/.bashrc", "shipped")
put(it, "usr/share/applications/droiddeck-return-gaming.desktop", "new runtime")
}
val paths = RuntimeFileTree.existingUserPaths(old, staging)
assertTrue("root" in paths)
assertTrue("usr/share/applications/droiddeck-steam-x64.desktop" in paths)
assertFalse("usr/share/applications/droiddeck-return-gaming.desktop" in paths)
RuntimeFileTree.carryUserData(old, staging, false, paths)
assertEquals("new runtime", File(staging, "usr/share/applications/droiddeck-return-gaming.desktop").readText())
}
@Test fun cachesTiedToThePreviousRuntimeAreDropped() {
val root = tmp.newFolder("rt")
val keep = listOf("root/.cache/mozilla/cache2/entry", "root/.cache/droiddeck/session.log",
"root/.local/share/droiddeck/apt/packages.txt", "root/.local/share/Steam/steam.sh", "root/.config/kwinrc")
val drop = listOf("root/.local/share/droiddeck/pacman/packages.txt", "root/.cache/droiddeck/pacman-restore.log",
"root/.cache/mesa_shader_cache_db/index", "root/.cache/mesa_shader_cache/a/b", "root/.cache/appstream/x.xb",
"root/.cache/discover/c", "root/.cache/ksycoca6_en-POSIX_abc", "root/.cache/plasma_theme_Vapor.kcache",
"root/.cache/kwinsession.kcache", "root/.cache/qtshadercache-arm64-little_endian-lp64/s",
"root/.cache/event-sound-cache.tdb.1.aarch64-unknown-linux-gnu", "root/.cache/fontconfig/x.cache-9")
(keep + drop).forEach { put(root, it) }
RuntimeFileTree.dropStaleState(root)
keep.forEach { assertTrue(it, File(root, it).exists()) }
drop.forEach { assertFalse(it, File(root, it).exists()) }
}
@Test fun droppingStateWithoutAHomeDoesNothing() {
RuntimeFileTree.dropStaleState(tmp.newFolder("empty"))
}
@Test fun aFailureHalfwayPutsEverythingBack() {
val old = userTree()
val staging = tmp.newFolder("new")
@@ -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()
}
}
}
@@ -4,6 +4,7 @@ import android.content.Context
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -12,6 +13,8 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -21,10 +24,137 @@ class GameEnvironmentStoreTest {
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.commit()
guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json")
File(context.filesDir, "game-environment.json").delete()
}
@After fun tearDown() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.commit()
}
@Test fun gameDebugLogsAreOffByDefault() {
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
GameEnvironmentStore.save(context, GameEnvironment.Config())
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun gameDebugLogsRequireSessionLogsAndPreserveCustomDiagnostics() {
val config = GameEnvironment.Config(shared = mapOf("PROTON_LOG" to "0", "WINEDEBUG" to "+warn"))
GameEnvironmentStore.save(context, config)
SessionPrefs.setGameDebugLogsEnabled(context, true)
var published = JSONObject(guest.readText())
assertTrue(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals("0", published.getJSONObject("shared").getString("PROTON_LOG"))
assertEquals("+warn", published.getJSONObject("shared").getString("WINEDEBUG"))
assertEquals(config, GameEnvironmentStore.read(context))
SessionPrefs.setLogsEnabled(context, false)
published = JSONObject(guest.readText())
assertFalse(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
SessionPrefs.setLogsEnabled(context, true)
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun failedGameDebugOptOutLeavesTheEnabledPreferenceVisible() {
assertTrue(SessionPrefs.setGameDebugLogsEnabled(context, true))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
val guestDirectory = guest.parentFile!!
guestDirectory.deleteRecursively()
guestDirectory.parentFile!!.mkdirs()
guestDirectory.writeText("blocks the guest configuration directory\n")
try {
assertFalse(SessionPrefs.setGameDebugLogsEnabled(context, false))
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
} finally {
guestDirectory.delete()
guestDirectory.mkdirs()
GameEnvironmentStore.publish(context)
}
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun unchangedEffectiveDiagnosticsDoNotRequireGuestPublication() {
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
val guestDirectory = guest.parentFile!!
guestDirectory.deleteRecursively()
guestDirectory.parentFile!!.mkdirs()
guestDirectory.writeText("blocks the guest configuration directory\n")
try {
assertTrue(SessionPrefs.setLogsEnabled(context, false))
assertFalse(SessionPrefs.logsEnabled(context))
} finally {
guestDirectory.delete()
guestDirectory.mkdirs()
SessionPrefs.setLogsEnabled(context, true)
GameEnvironmentStore.publish(context)
}
}
@Test fun logPreferenceUpdatesUseThePublisherLock() {
GameEnvironmentStore.publish(context)
val entered = CountDownLatch(1)
val finished = CountDownLatch(1)
lateinit var thread: Thread
synchronized(GameEnvironmentStore) {
thread = Thread {
entered.countDown()
SessionPrefs.setGameDebugLogsEnabled(context, true)
finished.countDown()
}
thread.start()
assertTrue(entered.await(5, TimeUnit.SECONDS))
assertFalse(finished.await(100, TimeUnit.MILLISECONDS))
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
assertTrue(finished.await(5, TimeUnit.SECONDS))
thread.join()
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
}
@Test fun gameDebugLogsWaitForARetainedSessionFolder() {
assertNull(SessionPaths.current())
assertTrue(SessionPaths.currentSessionLogsRetained(context))
GameEnvironmentStore.publish(context)
SessionPrefs.setLogsEnabled(context, false)
val cacheSession = SessionPaths.beginOrCurrent(context, "game-debug-logs")
try {
assertFalse(SessionPaths.currentSessionLogsRetained(context))
SessionPrefs.setLogsEnabled(context, true)
SessionPrefs.setGameDebugLogsEnabled(context, true)
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals(cacheSession, SessionPaths.take())
SessionPaths.release(context, cacheSession)
val retainedSession = SessionPaths.beginOrCurrent(context, "game-debug-logs")
assertTrue(SessionPaths.currentSessionLogsRetained(context))
GameEnvironmentStore.publish(context)
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertEquals(retainedSession, SessionPaths.current())
} finally {
SessionPaths.take()?.let { ended ->
SessionPaths.release(context, ended)
ended.deleteRecursively()
}
}
}
@Test fun savedSettingsAndPublishedSettingsPreserveUnsetsAndLiteralValues() {
val config = GameEnvironment.Config(
shared = mapOf("LITERAL" to "a=b 'quoted' $(echo test)", "EMPTY" to ""),
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.session
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class HudDefaultTest {
private lateinit var context: Context
@Before fun setUp() {
context = ApplicationProvider.getApplicationContext()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@After fun tearDown() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun aNewInstallStartsWithTheHudOff() {
assertFalse(SessionPrefs.hudEnabled(context))
}
@Test fun aHudTheUserTurnedOnStaysOn() {
SessionPrefs.setHudEnabled(context, true)
assertTrue(SessionPrefs.hudEnabled(context))
}
@Test fun aHudTheUserTurnedOffStaysOff() {
SessionPrefs.setHudEnabled(context, false)
assertFalse(SessionPrefs.hudEnabled(context))
}
}
@@ -0,0 +1,23 @@
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 sessionLimitPacesThePhone() {
assertEquals(45, SessionPrefs.compositorFpsLimit(0, 45))
}
@Test fun sessionLimitNeverExceedsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60, 90))
assertEquals(30, SessionPrefs.compositorFpsLimit(60, 30))
}
@Test fun mirroringKeepsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
}
}
@@ -1,18 +0,0 @@
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)
}
}
@@ -1,36 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class PerformanceModeTest {
private val app get() = RuntimeEnvironment.getApplication()
private val session get() = app.getSharedPreferences("session", Context.MODE_PRIVATE)
@Before fun clear() { session.edit().clear().commit() }
@Test fun offByDefaultAndPerMode() {
assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM))
SessionPrefs.setPerformanceMode(app, SessionService.MODE_STEAM, true)
assertTrue(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_DESKTOP))
}
@Test fun offKeepsDisplayAndMirrorPacing() {
assertEquals(0, SessionPrefs.compositorFpsLimit(0, false))
assertEquals(60, SessionPrefs.compositorFpsLimit(60, false))
}
@Test fun onIsUnpacedUnlessMirroring() {
assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0, true))
assertEquals(60, SessionPrefs.compositorFpsLimit(60, true))
}
}
@@ -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 }
@@ -18,8 +18,9 @@ class SessionBackgroundPrefsTest {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun nativeIsOptInAndDoesNotChangeDesktopOrExistingPolicies() {
assertEquals(SessionPrefs.SUSPEND_MANUAL, SessionPrefs.suspendPolicy(context, "steam"))
@Test fun nativeIsTheSteamDefaultWithoutChangingOtherModesOrSavedPolicies() {
assertEquals(SessionPrefs.SUSPEND_NATIVE, SessionPrefs.suspendPolicy(context, "steam"))
assertEquals(SessionPrefs.SUSPEND_MANUAL, SessionPrefs.suspendPolicy(context, SessionService.MODE_RUN))
for (policy in listOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_MANUAL, SessionPrefs.SUSPEND_NEVER,
SessionPrefs.SUSPEND_NATIVE)) {
SessionPrefs.setSuspendPolicy(context, "steam", policy)
@@ -28,6 +29,14 @@ class SessionBackgroundPrefsTest {
}
}
@Test fun automaticPipDefaultsOnAndHonorsSavedChoices() {
assertEquals(true, SessionPrefs.pipAutoEnter(context))
SessionPrefs.setPipAutoEnter(context, false)
assertEquals(false, SessionPrefs.pipAutoEnter(context))
SessionPrefs.setPipAutoEnter(context, true)
assertEquals(true, SessionPrefs.pipAutoEnter(context))
}
@Test fun directGamesUseAutoWithoutOverwritingSteamsNativeChoice() {
SessionPrefs.setSuspendPolicy(context, SessionService.MODE_STEAM, SessionPrefs.SUSPEND_NATIVE)
assertEquals(SessionPrefs.SUSPEND_AUTO, SessionPrefs.suspendPolicy(context, SessionService.MODE_RUN))
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.session
import android.app.Application
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.GpuInfo
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
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.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(
sdk = [33], application = Application::class, qualifiers = "en-rUS",
instrumentedPackages = ["com.droiddeck.launcher.gpu.GpuInfo"],
shadows = [SessionEndHintTest.DetectedGpu::class],
)
class SessionEndHintTest {
@get:Rule val temporary = TemporaryFolder()
private lateinit var activity: SessionActivity
private var previousArchitecture: String? = null
@Before
fun setUp() {
previousArchitecture = SessionState.steamClientArch
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
SessionState.steamClientArch = "arm64"
}
@After
fun tearDown() {
SessionState.steamClientArch = previousArchitecture
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
}
@Test
fun sigillOnArm64IncludesTheExperimentalX64Fallback() {
SessionState.steamClientArch = "arm64"
assertEquals(
activity.getString(R.string.session_end_steam_sigill) + "\n" + activity.getString(R.string.session_end_steam_try_x64),
hintText(sigillLog()),
)
}
@Test
fun sigillOnX86_64DoesNotSuggestSwitchingToItself() {
SessionState.steamClientArch = "x86_64"
assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog()))
}
@Test
fun sigillWithUnknownArchitectureDoesNotAssumeArm64() {
SessionState.steamClientArch = null
assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog()))
}
@Test
fun vulkanFailureOnAdrenoSelectsTheDriverHint() {
for (family in listOf(GpuInfo.Family.A6XX, GpuInfo.Family.ADRENO_UNKNOWN)) {
DetectedGpu.family = family
assertEquals(family.name, activity.getString(R.string.session_end_vulkan_device), hintText(vulkanLog()))
}
}
@Test
fun vulkanFailureOnNonAdrenoExplainsTheMissingLinuxDriver() {
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
assertEquals(activity.getString(R.string.session_end_gpu_unsupported), hintText(vulkanLog()))
}
@Test
fun missingEmptyAndUnrelatedLogsHaveNoHint() {
assertNull(hint(null))
assertNull(hint(File(temporary.root, "missing.log")))
assertNull(hint(log("")))
assertNull(hint(log("game: Illegal instruction\n== steam exited rc=132")))
}
private fun sigillLog() = log("== STEP 12:00:00 starting the Steam client\n== steam exited rc=132\n")
private fun vulkanLog() = log("[gamescope] [Error] vulkan: failed to find physical device\n")
private fun log(text: String): File = temporary.newFile().apply { writeText(text) }
private fun hint(log: File?): Any? = SessionActivity::class.java
.getDeclaredMethod("sessionEndHint", File::class.java).apply { isAccessible = true }.invoke(activity, log)
private fun hintText(log: File): String {
val result = hint(log)
assertNotNull(result)
return ReflectionHelpers.getField(result, "text")
}
@Implements(value = GpuInfo.Companion::class, isInAndroidSdk = false)
class DetectedGpu {
@Implementation
fun detect(): GpuInfo = GpuInfo("test GPU", if (family == GpuInfo.Family.A6XX) 610 else 0, family, "", false)
companion object {
var family = GpuInfo.Family.NOT_ADRENO
}
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SessionLaunchFailureTest {
private fun find(vararg lines: String) = SessionLaunchFailure.find(lines.asSequence())
@Test fun installedSteamThatExitsWithSigillHasACpuFailureHint() {
assertEquals(SessionLaunchFailure.STEAM_ILLEGAL_INSTRUCTION, find(
"== STEP 06:35:36.987 Steam client ready",
"== STEP 06:35:41.058 starting the Steam client",
"/usr/local/bin/droiddeck-session: line 309: 1192 Illegal instruction steam",
"== steam exited rc=132",
"(EE) failed to read Wayland events: Broken pipe",
))
}
@Test fun gamescopeWithoutAPhysicalDeviceHasAGraphicsFailureHint() {
assertEquals(SessionLaunchFailure.VULKAN_DEVICE_MISSING, find(
"[gamescope] [\u001b[0;31mError\u001b[0m] \u001b[0;37mvulkan:\u001b[0m failed to find physical device",
"SDL_Vulkan_CreateSurface failed: VK_KHR_wayland_surface extension is not enabled in the Vulkan instance.Failed to create backend.",
))
}
@Test fun unrelatedIllegalInstructionsAndExitCodesAreNotBlamedOnSteam() {
assertNull(find("game: Illegal instruction", "== steam exited rc=132"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=139"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=1320"))
assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=0"))
}
@Test fun onlyTheLatestClientAttemptCounts() {
assertNull(find(
"== STEP 12:00:00 starting the Steam client", "== steam exited rc=132",
"== STEP 12:01:00 starting the Steam client", "== steam exited rc=0",
))
}
@Test fun aLaterSuccessfulDeviceSelectionClearsTheGraphicsFailure() {
assertNull(find(
"[gamescope] [Error] vulkan: failed to find physical device",
"[gamescope] [Info] vulkan: selecting physical device 'Turnip Adreno (TM) 610': queue family 0",
))
}
@Test fun aNewSessionDoesNotReuseAnOldFailure() {
assertNull(find(
"== STEP 12:00:00 starting the Steam client", "== steam exited rc=132",
"== droiddeck-session Fri Oct 23 12:01:00 mode=steam",
))
}
}
@@ -1,8 +1,10 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.LogRedactor
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.Rule
import org.junit.Test
@@ -12,6 +14,9 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipFile
@RunWith(RobolectricTestRunner::class)
@@ -147,6 +152,41 @@ class SessionLogShareTest {
assertTrue(zip(folder).values.none { it.contains(leaked) })
}
@Test fun aDirectoryListingFailureLeavesTheTreeUnrecordedButDoesNotStopSiblingScrubbing() {
val folder = tmp.newFolder("2026-10-06-06-listing")
val unavailable = File(folder, "unavailable").apply { mkdirs() }
val unavailableLog = File(unavailable, "session.log").apply { writeText("$secret\n") }
val availableLog = File(folder, "available/session.log").apply {
parentFile!!.mkdirs()
writeText("$secret\n")
}
assertFalse(SessionArtifacts.scrubAndMark(folder, listFiles = {
if (it == unavailable) null else it.listFiles()
}))
assertTrue(unavailableLog.readText().contains(leaked))
assertFalse(availableLog.readText().contains(leaked))
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun aFailedScrubStillRecordsTheCollectionEventWithoutCompletingTheFolder() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = tmp.newFolder("2026-10-06-06-collect")
File(folder, "wayland.log").writeText("test compositor log\n")
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply {
mkdirs()
resolve("blocker").writeText("force marker write failure\n")
}
SessionArtifacts.collect(context, folder, "test")
assertTrue(File(folder, "events.jsonl").readText().contains("session.artifacts_collected"))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
}
@Test fun steamLogsPastTheSizeLimitStayOut() {
val folder = tmp.newFolder("2026-10-06-07-steam")
File(folder, "session.log").writeText("ok\n")
@@ -160,4 +200,322 @@ class SessionLogShareTest {
assertTrue("steam/console_log.txt" in names)
assertFalse("steam/cef_log.previous.txt" in names)
}
@Test fun streamingComparisonPreservesUnchangedFileAndReplacesChangedFile() {
val folder = tmp.newFolder("2026-10-06-08-steam")
val unchanged = File(folder, "unchanged.log")
unchanged.bufferedWriter().use { out -> repeat(5000) { out.write("safe diagnostic $it\n") } }
val originalModified = 1_600_000_000_000L
assertTrue(unchanged.setLastModified(originalModified))
val changed = File(folder, "changed.log")
changed.bufferedWriter().use { out ->
repeat(5000) { out.write("safe diagnostic $it\n") }
out.write("$secret\n")
}
assertTrue(SessionArtifacts.scrubAndMark(folder))
assertEquals(originalModified, unchanged.lastModified())
assertFalse(changed.readText().contains(leaked))
assertTrue(changed.readText().contains("sessionid=<redacted:token>"))
}
@Test fun historicalScrubDefersWithoutLeavingMarkersAndResumes() {
val folder = tmp.newFolder("2026-10-06-09-steam")
val log = File(folder, "session.log").apply { writeText("$secret\n") }
val rulesMarker = File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").apply { writeText("stale\n") }
val treeMarker = File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply { writeText("rules ${LogRedactor.RULES_VERSION}\n") }
SessionState.running = true
try {
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true))
} finally {
SessionState.running = false
}
assertFalse(rulesMarker.exists())
assertFalse(treeMarker.exists())
assertTrue(log.readText().contains(leaked))
assertTrue(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true))
assertFalse(log.readText().contains(leaked))
assertTrue(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").isFile)
}
@Test fun historicalScrubCancellationDuringStreamingPreservesTheOriginal() {
val folder = tmp.newFolder("2026-10-06-10-steam")
val original = "first safe line\n" + "x".repeat(20_000) + " $secret\n"
val log = File(folder, "session.log").apply { writeText(original) }
var checks = 0
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { ++checks >= 4 })
assertEquals(original, log.readText())
assertFalse(File(folder, ".session.log.scrub").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun historicalScrubCancellationBeforeComparisonPreservesTheOriginal() {
val folder = tmp.newFolder("2026-10-06-11-steam")
val original = "safe diagnostic\n"
val log = File(folder, "session.log").apply { writeText(original) }
val temporary = File(folder, ".session.log.scrub")
assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { temporary.length() > 0 })
assertEquals(original, log.readText())
assertFalse(temporary.exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun historicalScrubDoesNotReplaceALogThatChangedBeforeCommit() {
val folder = tmp.newFolder("2026-10-06-12-steam")
val original = "sessionid=$leaked\n"
val appended = "writer finished after collection started\n"
val log = File(folder, "session.log").apply { writeText(original) }
assertFalse(SessionArtifacts.scrubAndMark(folder, beforeReplace = { it.appendText(appended) }))
assertEquals(original + appended, log.readText())
assertFalse(File(folder, ".session.log.scrub").exists())
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
}
@Test fun comparisonCancellationWinsOverAnImmediateLengthMismatch() {
val left = tmp.newFile("left.log").apply { writeText("short\n") }
val right = tmp.newFile("right.log").apply { writeText("a different length\n") }
assertNull(SessionArtifacts.sameContents(left, right) { true })
}
@Test fun recoveryRetryKeepsItsSteamLogsWhenALaterSessionLeftNoFolder() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2026-10-08-01-steam").apply { mkdirs() }
val saved = File(folder, "steam/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session A\n")
}
File(folder, "ended-without-teardown.txt").writeText("recovery attempted before session B\n")
val runtime = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session B\n")
}
SessionArtifacts.finishAbandoned(context)
assertEquals("session A\n", saved.readText())
assertEquals("session B\n", runtime.readText())
assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish"))
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
}
@Test fun abandonedRecoveryDoesNotCopyLogsFromANewerCompletedSession() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context)
val folder = File(logs, "2026-10-08-02-steam").apply { mkdirs() }
val saved = File(folder, "steam/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session A\n")
}
File(logs, "2026-10-08-03-steam").apply { mkdirs() }
.resolve(SessionArtifacts.COMPLETE_MARKER).writeText("finished session B\n")
File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply {
parentFile!!.mkdirs()
writeText("session B\n")
}
SessionArtifacts.finishAbandoned(context)
assertEquals("session A\n", saved.readText())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
}
@Test fun startupRecoveryRunsBeforeVacMarkerArmWhileOrdinaryCleanupDefers() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2999-12-31-99-startup-recovery")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/startup-recovery-vac.log")
val sessionLog = File(folder, "session.log")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
val previousPhase = SessionState.phase
try {
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
sessionLog.writeText("$secret\n")
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("startup VAC evidence\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("startup VAC evidence\n") }
SessionState.running = true
SessionState.phase = SessionPhase.STARTING_GUEST
SessionArtifacts.finishAbandoned(context)
assertFalse(File(folder, "ended-without-teardown.txt").exists())
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("startup VAC evidence\n", File(folder, "steam/startup-recovery-vac.log").readText())
assertTrue(File(folder, "vac.txt").readText().contains("startup VAC evidence"))
assertTrue(File(folder, ".recovery-runtime-captured").isFile)
assertTrue(crashLog.isFile && crashLog.length() > 0L)
assertTrue(sessionLog.readText().contains(leaked))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertFalse(sessionLog.readText().contains(leaked))
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
SessionState.phase = previousPhase
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun startupRecoveryExcludesCurrentFolderAndCapturesDeferredRuntime() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context)
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
val olderFolder = File(logs, "$day-8999-older-recovery")
val folder = File(logs, "$day-9000-deferred-recovery")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/deferred-recovery-vac.log")
val previousRunning = SessionState.running
val previousPhase = SessionState.phase
val previousLogsEnabled = SessionPrefs.logsEnabled(context)
var currentFolder: File? = null
try {
olderFolder.deleteRecursively()
olderFolder.mkdirs()
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n")
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("deferred VAC evidence\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("deferred VAC evidence\n") }
SessionState.running = true
SessionState.phase = SessionPhase.STARTING_GUEST
SessionPrefs.setLogsEnabled(context, true)
currentFolder = SessionPaths.beginOrCurrent(context, "current-session")
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("deferred VAC evidence\n", File(folder, "steam/deferred-recovery-vac.log").readText())
assertTrue(File(folder, "vac.txt").readText().contains("deferred VAC evidence"))
assertTrue(File(folder, ".recovery-runtime-captured").isFile)
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(olderFolder, "ended-without-teardown.txt").exists())
assertFalse(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).exists())
assertFalse(File(currentFolder, "ended-without-teardown.txt").exists())
assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
assertTrue(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).isFile)
assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists())
} finally {
SessionState.running = previousRunning
SessionState.phase = previousPhase
SessionPaths.take()?.let { SessionPaths.release(context, it) }
currentFolder?.deleteRecursively()
SessionPrefs.setLogsEnabled(context, previousLogsEnabled)
olderFolder.deleteRecursively()
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun failedPreGuestRuntimeCaptureWritesNeitherCaptureNorCompleteMarker() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-01-vac-failure")
val marker = File(root, "root/.droiddeck-vac-diagnostics")
val launches = File(root, "root/.droiddeck-vac-launches")
val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/expired-recovery.log")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
try {
folder.deleteRecursively()
folder.mkdirs()
SessionArtifacts.recordClient(folder, "arm64")
File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n")
val firstCrashSnapshot = "first crash snapshot\n".toByteArray()
crashLog.writeBytes(firstCrashSnapshot)
File(folder, "vac.txt").mkdirs()
marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") }
launches.writeText("VAC evidence that cannot be reported\n")
runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("session A\n") }
SessionState.running = true
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertFalse(File(folder, ".recovery-runtime-captured").exists())
assertTrue(File(folder, ".recovery-runtime-expired").isFile)
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
File(folder, "vac.txt").deleteRecursively()
runtimeSteamLog.writeText("session B\n")
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertEquals("session A\n", File(folder, "steam/expired-recovery.log").readText())
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish"))
assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertArrayEquals(firstCrashSnapshot, crashLog.readBytes())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
folder.deleteRecursively()
runtimeSteamLog.delete()
marker.delete()
launches.delete()
}
}
@Test fun emptyCrashSnapshotIsPreservedAcrossRecovery() {
val context: android.content.Context = RuntimeEnvironment.getApplication()
val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-02-empty-crash")
val crashLog = File(folder, "crash.log")
val previousRunning = SessionState.running
try {
folder.deleteRecursively()
folder.mkdirs()
crashLog.writeBytes(ByteArray(0))
SessionState.running = true
SessionArtifacts.finishAbandoned(context, beforeGuestStart = true)
assertTrue(crashLog.isFile)
assertEquals(0L, crashLog.length())
SessionState.running = false
SessionArtifacts.finishAbandoned(context)
assertTrue(crashLog.isFile)
assertEquals(0L, crashLog.length())
assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile)
} finally {
SessionState.running = previousRunning
folder.deleteRecursively()
}
}
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -20,6 +21,49 @@ import org.robolectric.annotation.Config
class SessionLogShareZipTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun aLargeSteamLogIsRedactedInTheSharedArchive() {
val session = File(LinuxRuntime.logDir(app), "2026-10-08-02-steam").apply { mkdirs() }
val raw = File(session, "steam-42.log")
val earlySecret = "early-sessionid-abcdef123456"
val trailingSecret = "late-refresh-token-abcdef123456"
try {
// One long line exercises the streaming limit; the final ordinary line must still be redacted.
raw.bufferedWriter().use { out ->
out.write("sessionid=$earlySecret")
val chunk = "x".repeat(8192)
repeat(8192) { out.write(chunk) }
out.write("\nrefresh_token=$trailingSecret\n")
}
assertTrue(raw.length() > 64L * 1024 * 1024)
val zip = SessionLogShare.zipFolder(app, session)!!
ZipFile(zip).use { archive ->
val entry = archive.getEntry("${session.name}/steam-42.log")!!
archive.getInputStream(entry).use { input ->
// Only inspect the bounded scrubbed prefix: the pre-fix raw archive is over 64 MiB.
val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n"
val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size)
var offset = 0
while (offset < prefix.size) {
val count = input.read(prefix, offset, prefix.size - offset)
assertTrue("zip entry ended before its scrubbed prefix", count > 0)
offset += count
}
assertEquals(expected, String(prefix, StandardCharsets.UTF_8))
input.bufferedReader().use { reader ->
val trailing = requireNotNull(reader.readLine())
assertFalse("trailing secret survived", trailing.contains(trailingSecret))
assertEquals("refresh_token=<redacted:token>", trailing)
assertEquals(null, reader.readLine())
}
}
}
} finally {
SessionLogShare.clear(app)
session.deleteRecursively()
}
}
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
@@ -2,10 +2,13 @@ package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.IOException
import java.io.Writer
class SessionSteamLogsTest {
@get:Rule val tmp = TemporaryFolder()
@@ -59,4 +62,37 @@ class SessionSteamLogsTest {
assertEquals(listOf("web.txt"), names(copied))
assertFalse(File(out, "web.txt").readText().contains("abcdef123456"))
}
@Test fun aCopyFailurePreservesThePreviousSnapshotAndRemovesPartialStaging() {
val logs = tmp.newFolder("logs")
val session = tmp.newFolder("session")
val out = tmp.newFolder("out")
File(logs, "console_log.txt").writeText("new complete line\n")
val snapshot = File(out, "console_log.txt").apply { writeText("previous valid snapshot\n") }
lateinit var staging: File
val copied = SessionArtifacts.copySessionLogs(logs, session, out) { target ->
staging = target
val delegate = target.bufferedWriter()
object : Writer() {
private var failed = false
override fun write(buffer: CharArray, offset: Int, length: Int) {
if (!failed) {
delegate.write(buffer, offset, minOf(length, 4))
delegate.flush()
failed = true
}
throw IOException("injected writer failure")
}
override fun flush() = delegate.flush()
override fun close() = delegate.close()
}
}
assertTrue(copied.isEmpty())
assertEquals("previous valid snapshot\n", snapshot.readText())
assertFalse(staging.exists())
}
}
@@ -27,17 +27,21 @@ class SettingsResetTest {
@Test fun settingsGoBackToTheirDefaults() {
SessionPrefs.setTheme(app, "ocean")
SessionPrefs.setBackDoubleTapMs(app, 100)
SessionPrefs.setUnfoldedControlsWithController(app, true)
SessionPrefs.setNoXalia(app, false)
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")
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
SessionPrefs.setHudShowFps(app, false)
SessionPrefs.setHudShowBattery(app, false)
SessionPrefs.setHudShowGraph(app, false)
SessionPrefs.setHudColor(app, "amber")
SessionPrefs.setHudOpacity(app, 40)
SessionPrefs.setFusionHudConfig(app, "hudSize=mega,showFPSGraph=0")
SessionPrefs.setFusionHudPosition(app, 120f, 40f)
ControllerPrefs.setOpacity(app, 40)
AppUiPrefs.setScale(app, 150)
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3))
@@ -46,25 +50,46 @@ 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))
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))
assertFalse(SessionPrefs.gameDebugLogsEnabled(app))
val guest = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
"root/.config/droiddeck/game-environment.json")
assertFalse(org.json.JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertTrue(SessionPrefs.hudShowFps(app))
assertTrue(SessionPrefs.hudShowBattery(app))
assertTrue(SessionPrefs.hudShowGraph(app))
assertEquals(SessionPrefs.HUD_COLOR_MINT, SessionPrefs.hudColor(app))
assertEquals(SessionPrefs.HUD_OPACITY_DEFAULT, SessionPrefs.hudOpacity(app))
assertEquals("32.4°C", PerfHud.batteryCelsius(324))
assertNull(PerfHud.batteryCelsius(0))
assertNull(SessionPrefs.fusionHudConfig(app))
assertNull(SessionPrefs.fusionHudPosition(app))
assertEquals(100, ControllerPrefs.read(app).opacity)
assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app))
assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app))
assertFalse(prefs("steam_touch").contains("gyro"))
}
@Test fun aFailedDebugOptOutDoesNotHideTheEnabledPreference() {
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
val directory = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
"root/.config/droiddeck")
directory.deleteRecursively()
directory.writeText("blocks configuration publication")
try {
assertFalse(SettingsReset.resetAll(app, gameProfiles = false))
assertTrue(SessionPrefs.gameDebugLogsEnabled(app))
} finally {
directory.delete()
directory.mkdirs()
GameEnvironmentStore.publish(app)
}
}
@Test fun libraryAndRecordsAreKept() {
val folder = "/storage/emulated/0/Games/Foo"
SessionPrefs.setAddedGameName(app, folder, "Foo")
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.session
import android.app.Application
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
class SteamImportPromptTest {
@get:Rule val temp = TemporaryFolder()
private fun ask(root: File, text: String) = File(root, "root/.cache/droiddeck").apply { mkdirs() }.resolve("steam-import.json").writeText(text)
@Test fun aRequestFromTheGuestIsRead() {
val root = temp.newFolder()
ask(root, """{"token":"7","games":["Absolum","","Hades"]}""")
assertEquals(SteamImportPrompt.Ask("7", listOf("Absolum", "Hades")), SteamImportPrompt.read(root))
}
@Test fun noRequestOrABrokenOneIsIgnored() {
val root = temp.newFolder()
assertNull(SteamImportPrompt.read(root))
ask(root, "{")
assertNull(SteamImportPrompt.read(root))
ask(root, """{"games":["Hades"]}""")
assertNull(SteamImportPrompt.read(root))
}
@Test fun theAnswerCarriesTheTokenAndTheChoice() {
val root = temp.newFolder()
for ((now, choice) in listOf(true to "now", false to "later")) {
SteamImportPrompt.answer(root, "9", now)
val json = JSONObject(File(root, "root/.cache/droiddeck/steam-import.answer").readText())
assertEquals("9", json.getString("token"))
assertEquals(choice, json.getString("choice"))
}
}
}
@@ -0,0 +1,97 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class UsbLinkTest {
private lateinit var sys: File
@Before fun setUp() { sys = Files.createTempDirectory("usblink").toFile() }
@After fun tearDown() {
Files.walk(sys.toPath()).use { paths -> paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) } }
}
private val mounts = """
/dev/block/dm-5 /data ext4 rw 0 0
/dev/fuse /storage/8C5A-1F23 fuse rw 0 0
/dev/block/vold/public:8,97 /mnt/media_rw/8C5A-1F23 fuseblk rw 0 0
""".trimIndent()
private fun drive(deviceSpeed: String, otherHub: String) {
val controller = File(sys, "devices/platform/xhci")
val hub = File(controller, "usb1").apply { mkdirs(); File(this, "speed").writeText("480\n"); File(this, "idVendor").writeText("1d6b\n") }
File(controller, "usb2").apply { mkdirs(); File(this, "speed").writeText("$otherHub\n"); File(this, "idVendor").writeText("1d6b\n") }
val device = File(hub, "1-1").apply { mkdirs() }
File(device, "speed").writeText("$deviceSpeed\n")
File(device, "idVendor").writeText("04e8\n")
File(device, "busnum").writeText("1\n")
File(device, "devnum").writeText("7\n")
File(device, "manufacturer").writeText("Samsung\n")
File(device, "product").writeText("PSSD T7\n")
val part = File(device, "1-1:1.0/host1/target1:0:0/1:0:0:0/block/sdg/sdg1").apply { mkdirs() }
File(sys, "dev/block").mkdirs()
Files.createSymbolicLink(File(sys, "dev/block/8:97").toPath(), part.toPath())
File(sys, "bus/usb/devices").mkdirs()
Files.createSymbolicLink(File(sys, "bus/usb/devices/usb1").toPath(), hub.toPath())
}
@Test fun findsTheUsbSpeedOfADriveBehindItsMount() {
drive("480", "10000")
val link = UsbLink.forPath("/storage/8C5A-1F23/Games", mounts, sys)!!
assertEquals("8:97", link.device)
assertEquals(480.0, link.mbps, 0.0)
assertEquals("Samsung PSSD T7", link.name)
assertEquals(10000.0, link.portMbps!!, 0.0)
assertEquals("1-7", link.plug)
assertEquals("3/1-7/8:97@480.0", UsbLink.dismissKey(3, link))
assertFalse(UsbLink.SlowDrive("k", link.name, link.mbps, link.portMbps).portLimited)
}
@Test fun aPortWithoutSuperSpeedIsReportedAsTheLimit() {
drive("480", "480")
val link = UsbLink.forPath("/storage/8C5A-1F23", mounts, sys)!!
assertTrue(UsbLink.SlowDrive("k", link.name, link.mbps, link.portMbps).portLimited)
}
@Test fun anUnknownPortSpeedIsNotReportedAsTheLimit() {
drive("480", "10000")
Files.delete(File(sys, "bus/usb/devices/usb1").toPath())
val link = UsbLink.forPath("/storage/8C5A-1F23", mounts, sys)!!
assertNull(link.portMbps)
assertFalse(UsbLink.SlowDrive("k", link.name, link.mbps, link.portMbps).portLimited)
}
@Test fun internalStorageAndUnknownMountsHaveNoLink() {
drive("480", "10000")
assertNull(UsbLink.forPath("/storage/emulated/0/Games", mounts, sys))
assertNull(UsbLink.forPath("/storage/ABCD-0000", mounts, sys))
}
@Test fun mountsPickTheLongestMatchingMountPoint() {
assertEquals("8:97", UsbLink.mountDevice("/mnt/media_rw/8C5A-1F23/Games/PC", mounts))
assertNull(UsbLink.mountDevice("/mnt/media_rw/8C5A-1F230", mounts))
assertEquals("name:sda1", UsbLink.mountDevice("/mnt/usb/a", "/dev/block/sda1 /mnt/usb vfat rw 0 0"))
}
@Test fun rawMountPathsAreTreatedAsTheirStorageVolume() {
assertEquals("/storage/8C5A-1F23/Games", UsbLink.storagePath("/mnt/media_rw/8C5A-1F23/Games"))
assertEquals("/storage/emulated/0/Games", UsbLink.storagePath("/storage/emulated/0/Games"))
assertTrue(UsbLink.external(UsbLink.storagePath("/mnt/media_rw/8C5A-1F23/Games")))
}
@Test fun generationsFollowTheLinkSpeed() {
assertEquals("USB 1.1", UsbLink.generation(12.0))
assertEquals("USB 2.0", UsbLink.generation(480.0))
assertEquals("USB 3.2 Gen 1", UsbLink.generation(5000.0))
assertEquals("USB 3.2 Gen 2", UsbLink.generation(10000.0))
assertEquals(42, UsbLink.megabytesPerSecond(480.0))
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.stores
import android.app.Application
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
@@ -18,7 +19,7 @@ import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
@Config(sdk = [33], application = Application::class)
class StoreAccountsCipherTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun newKey(): SecretKey = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES")
@@ -138,6 +138,32 @@ class StoreInstallRootTest {
assertTrue(File(LinuxRuntime.rootDir(app), xodusRoot.second.removePrefix("/")).isDirectory)
}
@Test fun xodusRootsKeepEveryOtherStoreRootAtTheSameGuestPath() {
val card = File(app.filesDir, "card2").apply { mkdirs() }
val library = File(app.filesDir, "card/steam").apply { mkdirs() }
File(library, "Games").mkdirs()
SessionPrefs.setDefaultStorageFolder(app, card.path, "Card 2")
SessionPrefs.setGameStorage(app, library.path, "Card")
val xodus = StoreInstallRoot.externalRootsForXodus(app)
assertTrue(xodus.containsAll(StoreInstallRoot.externalRoots(app)))
assertTrue(xodus.any { it.first.absolutePath == File(library, "Games").absolutePath })
}
@Test fun theSteamLibraryGetsItsOwnGuestPathWhenItSharesACardWithAnotherStoreRoot() {
val card = File(app.filesDir, "same-card/Games")
val library = File(app.filesDir, "same-card/steam/Games")
val base = "/mnt/droiddeck-stores/ABCD-1234"
val roots = StoreInstallRoot.withSelectedLibrary(listOf(card to base), library, base)
assertEquals(2, roots.map { it.second }.distinct().size)
assertEquals(base, roots.single { it.first == card }.second)
assertTrue(roots.single { it.first == library }.second.startsWith("$base-"))
assertEquals("${roots.single { it.first == library }.second}/Xbox/Doom",
StoreInstallRoot.externalGuestPath(File(library, "Xbox/Doom"), roots))
assertEquals(roots, StoreInstallRoot.withSelectedLibrary(roots, library, base))
}
@Test fun externalStoreBindsCreateGuestTargetsAndSkipUnavailableVolumes() {
val host = File(app.filesDir, "card/Games").apply { mkdirs() }
val guestRoot = "/mnt/droiddeck-stores/card"
@@ -0,0 +1,402 @@
package com.droiddeck.launcher.stores.gog
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.nio.file.Files
import java.util.concurrent.atomic.AtomicBoolean
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogMaintenanceTest {
@get:Rule val temporary = TemporaryFolder()
@Test fun selectsPublicBranchAndTreatsBuildIdsAsOpaque() {
val builds = JSONObject("""{"items":[
{"os":"windows","branch":"beta","build_id":"99","generation":2,"link":"https://example.invalid/beta"},
{"os":"windows","branch":null,"build_id":"0002","generation":2,"version_name":"RC-final","link":"https://example.invalid/current"},
{"os":"windows","branch":null,"build_id":"10","generation":2,"link":"https://example.invalid/old"}]}""")
assertEquals("0002", GogBuild.select(builds)!!.id)
assertEquals("99", GogBuild.select(builds, branch = "beta")!!.id)
assertEquals("10", GogBuild.select(builds, pinned = "10")!!.id)
assertNull(GogBuild.select(builds, pinned = "missing"))
assertNull(GogBuild.select(builds, branch = "private"))
}
@Test fun migrationRetainsKnownBuildLanguageAndInstalledProducts() {
val folder = temporary.newFolder()
File(folder, "_gog_manifest.json").writeText("""{"gameId":"1","buildId":"000123"}""")
File(folder, "goggame-2.info").writeText("{}")
val sidecar = StoreGameSidecar(Store.GOG, "1", "Game", "game.exe", installVersion = "000123",
args = listOf("--custom"), env = mapOf("DD_TEST" to "1"), cloud = false, achievements = false,
extra = mapOf(StoreLanguage.EXTRA to "pl-PL"))
val record = GogInstallRecord.migrate(folder, sidecar)
assertEquals("000123", record.build)
assertEquals("pl-PL", record.language)
assertEquals(listOf("1", "2"), record.products)
assertEquals(record.json().toString(), GogInstallRecord.read(folder)!!.json().toString())
assertEquals(listOf("--custom"), sidecar.args)
assertFalse(sidecar.cloud)
}
@Test fun missingManifestNeverInventsLatestBuild() {
val folder = temporary.newFolder()
val record = GogInstallRecord.migrate(folder, StoreGameSidecar(Store.GOG, "1", "Game", "game.exe"))
assertEquals("offline", record.source)
assertEquals("", record.build)
assertEquals(0, record.files.length())
}
@Test fun offlineRefreshWithDlcRequiresAnAuthenticMatchingDepotBuild() {
val extracted = temporary.newFolder()
val app = File(extracted, "app").apply { mkdirs() }
val target = GogInstallRecord("1", "depot", build = "0000123", products = listOf("1", "2"))
assertThrows(IllegalArgumentException::class.java) { GogOffline.validateDepotInstaller(extracted, target) }
File(app, "goggame-1.info").writeText("""{"buildId":"0000999"}""")
assertThrows(IllegalArgumentException::class.java) { GogOffline.validateDepotInstaller(extracted, target) }
File(app, "goggame-1.info").writeText("""{"buildId":"0000123"}""")
GogOffline.validateDepotInstaller(extracted, target)
File(app, "goggame-1.info").delete()
GogOffline.validateDepotInstaller(extracted, target.copy(source = "offline", build = ""))
}
@Test fun offlineRefreshRetainsTheExistingExecutableLayout() {
val installed = temporary.newFolder()
val extracted = temporary.newFolder()
val app = File(extracted, "app").apply { mkdirs() }
File(app, "game.exe").writeText("replacement")
File(installed, "goggame-1.info").writeText("{}")
assertEquals(extracted, GogOffline.layout(extracted, installed, "1", "game.exe").source)
assertEquals("", GogOffline.layout(extracted, installed, "1", "game.exe").prefix)
File(installed, "goggame-1.info").delete()
assertEquals(extracted, GogOffline.layout(extracted, installed, "1", "app/game.exe").source)
val flat = temporary.newFolder()
val legacy = GogOffline.layout(flat, installed, "1", "app/game.exe")
assertEquals(flat, legacy.source)
assertEquals("app/", legacy.prefix)
}
@Test fun offlineInstallerMatchesRegionalLanguageWithoutChoosingAnotherLanguage() {
val downloads = JSONObject("""{"installers":[
{"id":"de","os":"windows","language":"de","files":[{"downlink":"https://example.invalid/de"}]},
{"id":"en","os":"windows","language":"en","files":[{"downlink":"https://example.invalid/en"}]}]}""")
assertEquals("en", GogMaintenance.offlineInstaller(downloads, "en-US").id)
assertThrows(IllegalStateException::class.java) { GogMaintenance.offlineInstaller(downloads, "pl-PL") }
downloads.getJSONArray("installers").put(0, JSONObject("""{"id":"neutral","os":"windows","language":"Neutral","files":[{"downlink":"https://example.invalid/neutral"}]}"""))
assertEquals("en", GogMaintenance.offlineInstaller(downloads, "en-US").id)
assertEquals("neutral", GogMaintenance.offlineInstaller(downloads, "pl-PL").id)
}
@Test fun incompleteOfflineExtractionCannotReplaceOrRemoveInstalledFiles() {
val folder = temporary.newFolder()
StoreGameSidecar(Store.GOG, "1", "Game", "game.exe").write(folder)
val game = File(folder, "game.exe").apply { writeText("installed game") }
val old = GogInstallRecord("1", "depot", files = JSONArray().put(JSONObject().put("path", game.name)
.put("size", game.length()).put("md5", GogFiles.hash(game))))
old.write(folder)
val extracted = temporary.newFolder()
File(extracted, "goggame-1.ico").writeText("ancillary file")
assertThrows(IllegalStateException::class.java) {
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, old.copy(source = "offline"), GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
}
assertEquals("installed game", game.readText())
assertFalse(File(folder, "goggame-1.ico").exists())
assertEquals("depot", GogInstallRecord.read(folder)!!.source)
val migrated = old.copy(files = JSONArray())
migrated.write(folder)
assertThrows(IllegalStateException::class.java) {
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, migrated, migrated.copy(source = "offline"), GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
}
assertEquals("installed game", game.readText())
assertFalse(File(folder, "goggame-1.ico").exists())
assertEquals("depot", GogInstallRecord.read(folder)!!.source)
assertEquals(0, GogInstallRecord.read(folder)!!.files.length())
}
@Test fun offlineRefreshCombinesRootPayloadAndAppPlaceholdersInBothLayouts() {
for (nested in listOf(false, true)) {
val folder = temporary.newFolder()
val executable = if (nested) "app/game.exe" else "game.exe"
StoreGameSidecar(Store.GOG, "1", "Game", executable).write(folder)
val game = File(folder, executable).apply { parentFile!!.mkdirs(); writeText("old game") }
val old = GogInstallRecord("1", "offline", files = JSONArray().put(JSONObject().put("path", executable)
.put("size", game.length()).put("md5", GogFiles.hash(game))))
old.write(folder)
val extracted = temporary.newFolder()
File(extracted, "game.exe").writeText("complete new game")
File(extracted, "Data").mkdirs()
File(extracted, "app/Data/SaveGame").mkdirs()
File(extracted, "app/Data/SaveGame/dummy.txt").writeBytes(byteArrayOf())
File(extracted, "tmp").mkdirs()
File(extracted, "tmp/installer.exe").writeText("installer support")
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, old, GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
assertEquals("complete new game", game.readText())
assertTrue(File(folder, (if (nested) "app/" else "") + "Data/SaveGame/dummy.txt").isFile)
assertFalse(File(folder, "tmp").exists())
assertTrue(GogInstallRecord.read(folder)!!.files.objects().any { it.getString("path") == executable })
}
}
@Test fun offlineRefreshDefersDlcCleanupAndRecordPublicationUntilDepotCompletion() {
val folder = temporary.newFolder()
StoreGameSidecar(Store.GOG, "1", "Game", "base.exe").write(folder)
val base = File(folder, "base.exe").apply { writeText("old base") }
val dlc = File(folder, "dlc.bin").apply { writeText("old DLC") }
val obsolete = File(folder, "old.bin").apply { writeText("obsolete") }
val save = File(folder, "save.dat").apply { writeText("player progress") }
fun entry(file: File, product: String) = JSONObject().put("path", file.name).put("size", file.length())
.put("md5", GogFiles.hash(file)).put("product", product).put("offset", 0).put("remotePath", file.name)
val old = GogInstallRecord("1", "depot", build = "old", products = listOf("1", "2"),
files = JSONArray().put(entry(base, "1")).put(entry(dlc, "2")).put(entry(obsolete, "1")))
old.write(folder)
val recordFile = File(GogFiles.dir(folder), "installed.json")
val record = recordFile.readText()
val extracted = temporary.newFolder()
val app = File(extracted, "app").apply { mkdirs() }
File(app, "goggame-1.info").writeText("""{"buildId":"new"}""")
val replacement = File(app, "base.exe").apply { writeText("new base") }
val expectedDlc = File(temporary.newFolder(), "dlc.bin").apply { writeText("new DLC") }
val target = old.copy(build = "new", files = JSONArray().put(entry(replacement, "1")).put(entry(expectedDlc, "2")))
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, target, GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
assertEquals("new base", base.readText())
assertEquals("old DLC", dlc.readText())
assertTrue(obsolete.isFile)
assertEquals(record, recordFile.readText())
val server = java.net.ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
val worker = Thread {
server.accept().use { client ->
val reader = client.getInputStream().bufferedReader()
while (!reader.readLine().isNullOrEmpty()) Unit
val content = expectedDlc.readBytes()
client.getOutputStream().apply {
write("HTTP/1.1 206 Partial Content\r\nContent-Length: ${content.size}\r\nConnection: close\r\n\r\n".toByteArray())
write(content); flush()
}
}
}.apply { isDaemon = true; start() }
try {
GogFallback.transfer(folder, JSONObject().put("files", target.files).put("oldFiles", old.files)
.put("links", JSONObject().put("2", JSONArray().put("http://127.0.0.1:${server.localPort}"))), null, AtomicBoolean(false))
assertEquals("new DLC", dlc.readText())
assertFalse(obsolete.exists())
assertEquals("player progress", save.readText())
assertEquals(record, recordFile.readText())
} finally { server.close(); worker.join(2000) }
}
@Test fun authenticIdentityOverridesAStaleLegacyMarkerWithoutTreatingSchemaAsVersion() {
val folder = temporary.newFolder()
File(folder, "_gog_manifest.json").writeText("""{"buildId":"old"}""")
File(folder, "goggame-1.id").writeText("""{"buildId":"patched"}""")
File(folder, "goggame-1.info").writeText("""{"version":1}""")
val record = GogInstallRecord.migrate(folder, StoreGameSidecar(Store.GOG, "1", "Game", "game.exe", installVersion = "old"))
assertEquals("patched", record.build)
assertEquals("", record.version)
}
@Test fun authenticGenerationOneResolvesProductDepotsAndRetainsHashesAndBuild() {
fun fixture(name: String) = JSONObject(javaClass.classLoader!!.getResource("gog/$name")!!.readText())
val build = GogBuild("3301", "", 1, "", "https://example.invalid/repository.json")
val requested = ArrayList<String>()
val snapshot = GogContent.snapshot(GogInstallRecord("1207658940", "depot"), build, "unused") { url, _ ->
requested.add(url)
when {
url == build.link -> fixture("rayman-gen1-repository.json")
url.endsWith("a01f6fb8-55a8-4f33-bc5b-5f5d2f591775.json") -> fixture("rayman-gen1-neutral.json")
url.endsWith("ec88140c-2589-41a0-bbf3-8fc1f215fe5a.json") -> fixture("rayman-gen1-english-excerpt.json")
else -> error("Unexpected metadata: $url")
}
}
assertEquals("3301", snapshot.build)
assertEquals(1, snapshot.generation)
assertEquals(4, snapshot.files.length())
val support = snapshot.files.getJSONObject(0)
assertEquals("support/1207658940/galaxy_rayman2_2.1.0.39.exe", support.getString("path"))
assertEquals("ee2c247373733f29782395f1f92622f6", support.getString("md5"))
val game = snapshot.files.getJSONObject(1)
assertEquals("Data/World/Levels/Raycap/Raycap.snd", game.getString("path"))
assertEquals(384206096L, game.getLong("offset"))
assertEquals("1207658940/main.bin", game.getString("remotePath"))
assertTrue(requested.drop(1).all { "/1207658940/windows/31847977/" in it })
GogFiles.validate(snapshot.files, temporary.newFolder())
}
@Test fun multipartPatchNamesVersionsLanguageAndChecksumsSurviveParsing() {
val downloads = JSONObject("""{"patches":[
{"id":"patch-1","name":"Patch A to B","version":"B","language":"pl","os":"windows","files":[
{"id":"part0","filename":"patch_original.exe","downlink":"https://example.invalid/0","size":3,"md5":"abc"},
{"id":"part1","filename":"patch_original-1.bin","downlink":"https://example.invalid/1","size":4}]},
{"id":"linux","os":"linux","files":[{"downlink":"https://example.invalid/linux"}]}]}""")
val patch = GogOfflineDownload.parse(downloads, "patches").single()
assertEquals("Patch A to B", patch.name)
assertEquals("B", patch.version)
assertEquals("pl", patch.language)
assertEquals(7, patch.size)
assertEquals(listOf("patch_original.exe", "patch_original-1.bin"), patch.parts.map { it.name })
assertEquals("abc", patch.parts.first().md5)
assertEquals("patch_(52404)+special.exe", GogContent.downloadFilename("https://example.invalid/patch_%2852404%29+special.exe?token=temporary"))
}
@Test fun pathsRejectTraversalSymlinksCaseCollisionsAndMetadataOverlap() {
val folder = temporary.newFolder()
for (path in listOf("../escape", "/absolute", "C:/file", "a/./file", "a//file")) {
assertThrows(IllegalArgumentException::class.java) { GogFiles.inside(folder, path) }
}
val files = JSONArray("""[{"path":"Game.exe"},{"path":"game.exe"}]""")
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(files, folder) }
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"Data/a"},{"path":"data/b"}]"""), folder) }
File(folder, "Game.bin").writeText("original")
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"game.bin"}]"""), folder) }
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":".droiddeck-store.json"}]"""), folder) }
val outside = temporary.newFolder()
try { Files.createSymbolicLink(File(folder, "link").toPath(), outside.toPath()) }
catch (_: java.nio.file.FileSystemException) { return }
assertThrows(IllegalArgumentException::class.java) { GogFiles.inside(folder, "link/game.exe") }
}
@Test fun sameSizeCorruptionFailsVerificationAndLanguageVariantsRemainDistinct() {
val folder = temporary.newFolder()
val file = File(folder, "game.bin").apply { writeText("original") }
val expected = JSONObject().put("path", file.name).put("size", file.length()).put("md5", GogFiles.hash(file))
file.writeText("modified")
assertFalse(GogFiles.matches(folder, expected))
assertTrue(GogContent.languageSelected(listOf("*"), "zh-Hant"))
assertFalse(GogContent.languageSelected(listOf("zh-Hans"), "zh-Hant"))
assertTrue(GogContent.languageSelected(listOf("Polish"), "pl"))
}
@Test fun persistedManifestsContainNoCredentialsOrTemporaryLinks() {
val input = JSONObject("""{"buildId":"1","clientSecret":"secret","urls":[{"url":"https://example.invalid/?token=secret"}],
"products":[{"productId":"2","clientSecret":"nested"}],"dependencies":["ISI"]}""")
val text = GogContent.sanitize(input).toString()
assertFalse(text.contains("secret"))
assertFalse(text.contains("https://"))
assertTrue(text.contains("ISI"))
}
@Test fun interruptedExternalPatchRestoresRecoveryWithoutExecutingAgain() {
val app = RuntimeEnvironment.getApplication()
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "Patch recovery").apply { mkdirs() }
try {
val sidecar = StoreGameSidecar(Store.GOG, "recovery-test", "Patch recovery", "game.exe",
args = listOf("--custom"), env = mapOf("SETTING" to "value"), cloud = false,
achievements = false, state = StoreGameSidecar.STATE_UPDATING)
sidecar.write(folder)
val previous = sidecar.toJson().toString()
GogFiles.write(GogFiles.journal(folder), JSONObject().put("operation", "PATCH").put("phase", "patch-applying"))
val item = CatalogItem(Store.GOG, sidecar.id, sidecar.title, imageUrl = null, extra = mapOf(
GogMaintenance.OPERATION to "PATCH", GogMaintenance.FOLDER to folder.path))
GogMaintenance.restore(app, item)
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
assertTrue(DownloadQueue.entry(item.key)!!.error!!.contains("recovery"))
assertEquals(previous, StoreGameSidecar.read(folder)!!.toJson().toString())
assertEquals("patch-applying", GogFiles.read(GogFiles.journal(folder))!!.getString("phase"))
DownloadQueue.clear(app, item.key)
} finally { folder.deleteRecursively() }
}
@Test fun signedOutCheckRemainsAFailureInsteadOfCurrent() {
val app = RuntimeEnvironment.getApplication()
com.droiddeck.launcher.stores.StoreAccounts.clear(app, Store.GOG)
GogMaintenance.reset()
val folder = temporary.newFolder()
val game = com.droiddeck.launcher.stores.InstalledStoreGame(
StoreGameSidecar(Store.GOG, "signed-out-check", "Check", "game.exe", installVersion = "opaque-build"), folder)
GogMaintenance.check(app, game, force = true)
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5)
while (System.nanoTime() < deadline) {
org.robolectric.shadows.ShadowLooper.idleMainLooper()
if (GogMaintenance.checks[game.sidecar.id]?.state == GogMaintenance.State.FAILED) break
Thread.sleep(10)
}
assertEquals(GogMaintenance.State.FAILED, GogMaintenance.checks[game.sidecar.id]?.state)
assertTrue(GogMaintenance.checks[game.sidecar.id]!!.reason.contains("Sign in"))
}
@Test fun pauseBeforeInstallerClaimCannotStartExternalApplication() {
val app = RuntimeEnvironment.getApplication()
val ready = java.util.concurrent.CountDownLatch(1)
val proceed = java.util.concurrent.CountDownLatch(1)
val finished = java.util.concurrent.CountDownLatch(1)
val applied = AtomicBoolean(false)
val item = com.droiddeck.launcher.stores.download.DownloadEntry(Store.GOG, "installer-claim", "Installer claim")
DownloadQueue.enqueue(app, item) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
ready.countDown()
try {
check(proceed.await(5, java.util.concurrent.TimeUnit.SECONDS))
handle.interruptible(false)
applied.set(true)
return null
} finally { finished.countDown() }
}
override fun cancel(deleteFiles: Boolean) {}
}
}
try {
assertTrue(ready.await(5, java.util.concurrent.TimeUnit.SECONDS))
DownloadQueue.pause(item.key)
proceed.countDown()
assertTrue(finished.await(5, java.util.concurrent.TimeUnit.SECONDS))
assertFalse(applied.get())
} finally {
proceed.countDown()
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(item.key)?.state == DownloadState.RUNNING && System.nanoTime() < deadline) Thread.sleep(10)
DownloadQueue.clear(app, item.key)
}
}
@Test fun fileFallbackVerifiesRemoteBytesAndPreservesOriginalOnCorruption() {
val folder = temporary.newFolder()
val content = "verified remote content".toByteArray()
val original = File(folder, "game.bin").apply { writeText("local data") }
val server = java.net.ServerSocket(0, 10, java.net.InetAddress.getByName("127.0.0.1"))
var reply = content
var transferred = 0
val worker = Thread {
while (!server.isClosed) {
val client = try { server.accept() } catch (_: java.io.IOException) { break }
client.use {
val reader = it.getInputStream().bufferedReader()
while (!reader.readLine().isNullOrEmpty()) Unit
it.getOutputStream().apply {
write("HTTP/1.1 206 Partial Content\r\nContent-Length: ${reply.size}\r\nConnection: close\r\n\r\n".toByteArray())
write(reply); flush(); transferred += reply.size
}
}
}
}.apply { isDaemon = true; start() }
try {
val expected = File(folder, "expected").apply { writeBytes(content) }
val file = JSONObject().put("path", "game.bin").put("size", content.size).put("md5", GogFiles.hash(expected))
.put("product", "1").put("offset", 0).put("remotePath", "data")
val plan = JSONObject().put("files", JSONArray().put(file)).put("links", JSONObject().put("1", JSONArray().put("http://127.0.0.1:${server.localPort}")))
reply = ByteArray(content.size) { 65 }
assertThrows(IllegalStateException::class.java) { GogFallback.transfer(folder, plan, null, AtomicBoolean(false)) }
assertEquals("local data", original.readText())
reply = content
GogFallback.transfer(folder, plan, null, AtomicBoolean(false))
assertArrayEquals(content, original.readBytes())
val before = transferred
GogFallback.transfer(folder, plan, null, AtomicBoolean(false))
assertEquals(before, transferred)
} finally { server.close(); worker.join(2000) }
}
}
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.stores.itch
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import java.io.File
import java.nio.file.Files
class ItchArchivesTest {
private lateinit var dir: File
@Before fun setUp() {
dir = Files.createTempDirectory("itch-archives").toFile()
}
@After fun tearDown() {
Files.walk(dir.toPath()).sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) }
}
private fun file(name: String, vararg head: Int, size: Int = 64): File {
val f = File(dir, name)
f.parentFile?.mkdirs()
val bytes = ByteArray(maxOf(size, head.size))
head.forEachIndexed { i, b -> bytes[i] = b.toByte() }
f.writeBytes(bytes)
return f
}
@Test fun kindsComeFromTheContentNotTheName() {
assertEquals("7z", ItchArchives.kind(file("data.bin", 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C), "data.bin"))
assertEquals("zip", ItchArchives.kind(file("a.7z", 0x50, 0x4B, 3, 4), "a.7z"))
assertEquals("rar", ItchArchives.kind(file("b", 0x52, 0x61, 0x72, 0x21), "b"))
assertEquals("exe", ItchArchives.kind(file("Game.exe", 0x50, 0x4B), "Game.exe"))
}
@Test fun theLargestArchiveInsideIsUnpackedNext() {
file("readme.txt", 0x48, 0x69)
file("VotV.7z", 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C, size = 4096)
file("extras/art.zip", 0x50, 0x4B, 3, 4, size = 128)
assertEquals("VotV.7z", ItchArchives.inner(dir)?.name)
}
@Test fun archivesDeeperThanTwoFoldersAreLeftAlone() {
file("a/b/c/deep.zip", 0x50, 0x4B, 3, 4)
assertNull(ItchArchives.inner(dir))
}
@Test fun nothingPackedMeansNothingToUnpack() {
file("game.pak", 0x00, 0x01)
file("notes.txt", 0x48, 0x69)
assertNull(ItchArchives.inner(dir))
}
@Test fun aNamedArchiveWithoutASignatureIsSkipped() {
file("extras.zip", 0x48, 0x69, size = 8192)
file("game.7z", 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C, size = 128)
assertEquals("game.7z", ItchArchives.inner(dir)?.name)
}
@Test fun symlinksAreNotFollowed() {
val root = File(dir, "root").apply { mkdirs() }
val outside = File(dir, "outside").apply { mkdirs() }
File(outside, "keep.zip").writeBytes(byteArrayOf(0x50, 0x4B, 3, 4))
Files.createSymbolicLink(File(root, "link").toPath(), outside.toPath())
Files.createSymbolicLink(File(root, "linked.zip").toPath(), File(outside, "keep.zip").toPath())
assertNull(ItchArchives.inner(root))
}
}
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.stores.itch
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class ItchBuildsTest {
private fun file(id: Int, type: String, sub: String, size: Int = 10) =
JSONObject().put("id", id).put("type", type).put("sub_type", sub).put("size", size).put("state", "uploaded")
private fun build(id: Int, vararg files: JSONObject) = JSONObject().put("id", id).put("files", JSONArray(files.toList()))
private fun path(vararg builds: JSONObject) = JSONObject().put("upgrade_path", JSONObject().put("builds", JSONArray(builds.toList())))
@Test fun buildIdReadsBothKeyStylesAndIgnoresMissingValues() {
assertEquals("55", ItchBuilds.buildId(JSONObject().put("build_id", 55)))
assertEquals("56", ItchBuilds.buildId(JSONObject().put("buildId", "56")))
assertEquals("", ItchBuilds.buildId(JSONObject().put("build_id", JSONObject.NULL)))
assertEquals("", ItchBuilds.buildId(JSONObject().put("build_id", 0)))
assertEquals("", ItchBuilds.buildId(JSONObject().put("build_id", "00")))
assertEquals("57", ItchBuilds.buildId(JSONObject().put("build_id", "057")))
assertEquals("", ItchBuilds.buildId(JSONObject()))
}
@Test fun pathSkipsTheInstalledBuildAndPrefersOptimizedPatches() {
val reply = path(
build(1, file(11, "patch", "default")),
build(2, file(21, "patch", "default", 5), file(22, "patch", "optimized", 3), file(23, "signature", "default")),
)
val steps = ItchBuilds.steps(reply, 1, 2) { it.optJSONArray("files") }!!
assertEquals(1, steps.size)
assertEquals(2L, steps.single().buildId)
assertEquals(22L, steps.single().patchFile)
assertEquals(3L, steps.single().patchSize)
assertEquals(23L, steps.single().signatureFile)
}
@Test fun pathIsRefusedWithoutASignatureOrAPatchOrTheRightEnd() {
val noSignature = path(build(1), build(2, file(21, "patch", "default")))
assertNull(ItchBuilds.steps(noSignature, 1, 2) { it.optJSONArray("files") })
val noPatch = path(build(1), build(2, file(23, "signature", "default")))
assertNull(ItchBuilds.steps(noPatch, 1, 2) { it.optJSONArray("files") })
val wrongEnd = path(build(1), build(3, file(31, "patch", "default"), file(32, "signature", "default")))
assertNull(ItchBuilds.steps(wrongEnd, 1, 2) { it.optJSONArray("files") })
assertNull(ItchBuilds.steps(JSONObject(), 1, 2) { it.optJSONArray("files") })
}
@Test fun pathNeedsFilesFromALookupWhenTheBuildListsNone() {
val reply = path(JSONObject().put("id", 1), JSONObject().put("id", 2))
val steps = ItchBuilds.steps(reply, 1, 2) { JSONArray().put(file(21, "patch", "default")).put(file(23, "signature", "default")) }!!
assertEquals(21L, steps.single().patchFile)
}
}
@@ -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,85 @@
package com.droiddeck.launcher.stores.itch
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class ItchStagingTest {
@get:Rule val tmp = TemporaryFolder()
private fun file(root: File, path: String, text: String) = File(root, path).also { it.parentFile?.mkdirs(); it.writeText(text) }
@Test fun newFilesReplaceOldOnesAndEverythingElseStays() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, "game.exe", "old")
file(game, "data/level.dat", "old")
file(game, "saves/slot1.sav", "mine")
file(game, ".droiddeck-store.json", "record")
file(staged, "game.exe", "new")
file(staged, "data/level.dat", "new")
file(staged, "data/extra.dat", "new")
file(staged, "saves/default.sav", "new")
ItchStaging.merge(staged, game)
assertEquals("new", File(game, "game.exe").readText())
assertEquals("new", File(game, "data/level.dat").readText())
assertEquals("new", File(game, "data/extra.dat").readText())
assertEquals("mine", File(game, "saves/slot1.sav").readText())
assertEquals("new", File(game, "saves/default.sav").readText())
assertEquals("record", File(game, ".droiddeck-store.json").readText())
assertTrue(staged.listFiles().orEmpty().all { it.isDirectory && it.listFiles().orEmpty().isEmpty() })
}
@Test fun aFileReplacingADirectoryAndTheOtherWayRound() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, "a/inner.txt", "old")
file(game, "b", "old")
file(staged, "a", "new")
file(staged, "b/inner.txt", "new")
ItchStaging.merge(staged, game)
assertTrue(File(game, "a").isFile)
assertEquals("new", File(game, "a").readText())
assertEquals("new", File(game, "b/inner.txt").readText())
assertFalse(File(game, "a/inner.txt").exists())
}
@Test fun deletingFollowsNoLinkOutOfTheTree() {
val outside = tmp.newFolder("outside")
file(outside, "keep.txt", "keep")
val staged = tmp.newFolder("staged")
file(staged, "own.txt", "x")
java.nio.file.Files.createSymbolicLink(File(staged, "link").toPath(), outside.toPath())
ItchStaging.delete(staged)
assertFalse(staged.exists())
assertEquals("keep", File(outside, "keep.txt").readText())
}
@Test fun aLinkInTheGameIsReplacedNotFollowed() {
val outside = tmp.newFolder("outside")
file(outside, "keep.txt", "keep")
val game = tmp.newFolder("game")
java.nio.file.Files.createSymbolicLink(File(game, "data").toPath(), outside.toPath())
val staged = tmp.newFolder("staged")
file(staged, "data/level.dat", "new")
ItchStaging.merge(staged, game)
assertEquals("keep", File(outside, "keep.txt").readText())
assertFalse(File(outside, "level.dat").exists())
assertEquals("new", File(game, "data/level.dat").readText())
}
@Test fun theInstallRecordIsNeverReplacedByTheArchive() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, ".droiddeck-store.json", "record")
file(staged, ".droiddeck-store.json", "forged")
file(staged, "sub/.droiddeck-store.json", "nested")
ItchStaging.merge(staged, game)
assertEquals("record", File(game, ".droiddeck-store.json").readText())
assertEquals("nested", File(game, "sub/.droiddeck-store.json").readText())
}
}
@@ -0,0 +1,84 @@
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 ItchUpdatesTest {
private fun upload(id: String, updated: String, filename: String = "game-$id.zip", windows: Boolean = true, type: String = "default") =
JSONObject().put("id", id).put("filename", filename).put("updated_at", updated).put("type", type).put("storage", "hosted")
.put("platforms", JSONObject().put("windows", windows).put("linux", !windows))
private fun list(vararg uploads: JSONObject) = JSONArray().also { a -> uploads.forEach { a.put(it) } }
@Test fun aNewerStampOnTheSameUploadIsAnUpdate() {
val update = ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", "2026-09-01T10:00:00Z")!!
assertEquals("7", update.uploadId)
assertEquals("2026-10-20T10:00:00Z", update.updatedAt)
assertFalse(update.replaced)
}
@Test fun theSameStampIsNotAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-09-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
}
@Test fun anOlderStampIsNotAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-08-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
}
@Test fun aMissingUploadFallsBackToTheNewestWindowsOneAndAsksFirst() {
val update = ItchUpdates.evaluate(
list(upload("8", "2026-10-01T10:00:00Z"), upload("9", "2026-10-05T10:00:00Z"), upload("10", "2026-10-09T10:00:00Z", windows = false)),
"7", "2026-09-01T10:00:00Z",
)!!
assertEquals("9", update.uploadId)
assertTrue(update.replaced)
}
@Test fun aReplacedUploadWithNoWindowsBuildLeftIsNotOffered() {
val linux = list(upload("8", "2026-10-01T10:00:00Z", windows = false))
assertNull(ItchUpdates.evaluate(linux, "7", "2026-09-01T10:00:00Z"))
assertNull(ItchUpdates.evaluate(linux, "", "2026-09-01T10:00:00Z"))
}
@Test fun aWindowsBuildOfAnotherTypeBeatsALinuxDefaultOne() {
val update = ItchUpdates.evaluate(
list(upload("8", "2026-10-09T10:00:00Z", windows = false), upload("9", "2026-10-01T10:00:00Z", type = "other")),
"7", "2026-09-01T10:00:00Z",
)!!
assertEquals("9", update.uploadId)
assertTrue(update.replaced)
}
@Test fun anUnknownInstalledVersionNeverReportsAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", ""))
}
@Test fun noAnswerOrNoWindowsBuildMeansNoUpdate() {
assertNull(ItchUpdates.evaluate(null, "7", "2026-09-01T10:00:00Z"))
assertNull(ItchUpdates.evaluate(JSONArray(), "7", "2026-09-01T10:00:00Z"))
}
@Test fun anInstallWithoutAnUploadIdComparesTheNewestWindowsBuild() {
val update = ItchUpdates.evaluate(list(upload("8", "2026-10-01T10:00:00Z")), "", "2026-09-01T10:00:00Z")!!
assertEquals("8", update.uploadId)
assertFalse(update.replaced)
assertNull(ItchUpdates.evaluate(list(upload("8", "2026-08-01T10:00:00Z")), "", "2026-09-01T10:00:00Z"))
}
@Test fun foundUpdatesSurviveTheCache() {
val found = mapOf("itch:a/b" to ItchUpdate("9", "2026-10-05T10:00:00Z", "b.zip", true))
val back = ItchUpdates.decode(ItchUpdates.encode(found))
assertEquals(setOf("itch:a/b"), back.keys)
assertEquals("9", back.getValue("itch:a/b").uploadId)
assertTrue(back.getValue("itch:a/b").replaced)
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode(null))
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode("not json"))
}
}
@@ -0,0 +1,64 @@
package com.droiddeck.launcher.ui
import android.view.KeyEvent
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.CommitTextCommand
import androidx.compose.ui.text.input.DeleteAllCommand
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.SetSelectionCommand
import androidx.compose.ui.text.input.TextFieldValue
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
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(manifest = Config.NONE)
class BottomScreenTypingTest {
@Test fun editsReplaceTheWholeFieldAndKeepTheCursor() {
val edits = TypingRequest.editsFor(TextFieldValue("fall", TextRange(2, 4)))
assertEquals(3, edits.size)
assertTrue(edits[0] is DeleteAllCommand)
assertEquals("fall", (edits[1] as CommitTextCommand).text)
val selection = edits[2] as SetSelectionCommand
assertEquals(2, selection.start)
assertEquals(4, selection.end)
}
@Test fun requestForwardsTextActionAndClose() {
val sent = mutableListOf<String>()
val actions = mutableListOf<ImeAction>()
var closed = 0
val request = TypingRequest(
TextFieldValue("a"), ImeOptions(imeAction = ImeAction.Search),
{ sent += it.text }, { actions += it }, { closed++ },
)
request.send(TextFieldValue("ab"))
request.action()
request.close()
assertEquals(listOf("ab"), sent)
assertEquals("ab", request.value.text)
assertEquals(listOf(ImeAction.Search), actions)
assertEquals(1, closed)
}
@Test fun panelStopsOnlyItsOwnRequest() {
val first = TypingRequest(TextFieldValue(""), ImeOptions.Default, {}, {})
val second = TypingRequest(TextFieldValue(""), ImeOptions.Default, {}, {})
DualScreenPanel.startTyping(second)
DualScreenPanel.stopTyping(first)
assertEquals(second, DualScreenPanel.typing)
DualScreenPanel.stopTyping(second)
assertNull(DualScreenPanel.typing)
}
@Test fun triggersStepThroughSections() {
assertEquals(-1, dualPageStep(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_L2)))
assertEquals(1, dualPageStep(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_R2)))
assertNull(dualPageStep(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_L1)))
}
}
@@ -0,0 +1,55 @@
package com.droiddeck.launcher.ui
import android.view.MotionEvent
import android.view.View
import com.droiddeck.launcher.input.JoyConPadTest
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.session.SessionState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.nio.file.Files
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
shadows = [JoyConPadTest.RecordingWriter::class])
class DeckControlsPanelTest {
@Test fun takesTouchAtMatchesWhatATouchDoes() {
val directory = Files.createTempDirectory("deck-panel").toFile()
try {
SessionState.deckPad = false
// No pad: the Deck layouts (trackpads, grips). A pad without Deck controls: the gamepad layout
// (sticks, d-pad, face buttons).
for (pad in listOf(null, PadBridge(directory))) for (portraitDock in listOf(false, true)) {
val name = "pad=${pad != null} portraitDock=$portraitDock"
val panel = DeckControlsPanel(RuntimeEnvironment.getApplication(), onClose = {}, onSteamMenu = {}, onQam = {},
pad = pad, portraitDock = portraitDock)
assertEquals(name, pad == null, panel.deckControls)
// The portrait dock sits under a portrait game; its gamepad layout needs a tall panel.
val (w, h) = if (portraitDock) 720 to 1000 else 1200 to 480
panel.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY))
panel.layout(0, 0, w, h)
var taken = 0
var missed = 0
for (x in 0 until w step w / 40) for (y in 0 until h step h / 24) {
val expected = panel.takesTouchAt(x.toFloat(), y.toFloat())
val down = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, x.toFloat(), y.toFloat(), 0)
assertEquals("$name ($x, $y)", expected, panel.dispatchTouchEvent(down))
down.recycle()
// Cancel rather than lift, so no button fires its action.
MotionEvent.obtain(0L, 1L, MotionEvent.ACTION_CANCEL, x.toFloat(), y.toFloat(), 0).also { panel.dispatchTouchEvent(it); it.recycle() }
if (expected) taken++ else missed++
}
assertTrue("$name: some points land on controls", taken > 0)
assertTrue("$name: some points land between them", missed > 0)
}
} finally {
directory.deleteRecursively()
}
}
}
@@ -0,0 +1,32 @@
package com.droiddeck.launcher.ui
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class DualScreenPanelOwnerTest {
private val app get() = RuntimeEnvironment.getApplication()
@After fun clear() = DualScreenPanel.hide()
@Test fun aLauncherThatStopsLeavesThePanelOfTheOneThatTookItOver() {
DualScreenPanel.show(app, 2, 10)
DualScreenPanel.show(app, 2, 11)
DualScreenPanel.hide(10)
assertEquals(2, DualScreenPanel.shownOn)
DualScreenPanel.hide(11)
assertEquals(-1, DualScreenPanel.shownOn)
}
@Test fun theOwnerHidesItsOwnPanel() {
DualScreenPanel.show(app, 2, 10)
DualScreenPanel.hide(10)
assertEquals(-1, DualScreenPanel.shownOn)
}
}
@@ -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())
}
}
@@ -144,7 +144,7 @@ class GlobalGlassesSettingsTest {
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {})
), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {})
}
}
}
@@ -94,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,253 @@
package com.droiddeck.launcher.ui
import android.app.Application
import android.content.res.Configuration
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.test.*
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.PadBridgeRoutingTest
import com.droiddeck.launcher.input.PhysicalShortcuts
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.InputDeviceBuilder
import org.robolectric.shadows.ShadowDialog
import java.util.Locale
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], application = Application::class, qualifiers = "w960dp-h640dp-land",
shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
class PhysicalShortcutsDialogTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
private lateinit var device: InputDevice
@Before fun setUp() {
context.getSharedPreferences("controller", 0).edit().clear().commit()
device = InputDeviceBuilder.newBuilder().setId(10).setName("Retroid extra buttons")
.setDescriptor("retroid-extra").setSources(InputDevice.SOURCE_KEYBOARD)
.setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build()
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
}
@Test fun assignmentSavesAutomaticallyOnRelease() {
var changes = 0
compose.setContent { DroidDeckTheme { PhysicalShortcutRows(onChanged = { changes++ }) } }
assign(PhysicalShortcuts.Action.STEAM)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
compose.onNodeWithText(context.getString(R.string.shortcuts_release)).assertExists()
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
assertTrue(PhysicalShortcuts.read(context).isEmpty())
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
compose.runOnIdle {
val binding = PhysicalShortcuts.read(context).single()
assertEquals(KeyEvent.KEYCODE_F1, binding.button.keyCode)
assertEquals(PhysicalShortcuts.Action.STEAM, binding.action)
assertEquals(1, changes)
}
}
@Test fun buttonMappingPageOpensPhysicalShortcutAssignments() {
compose.setContent {
DroidDeckTheme { ControllerMappingPage(emptyMap(), { _, _ -> }, {}, {}) }
}
compose.onNodeWithTag("shortcuts-assign-STEAM").assertExists()
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
compose.onNodeWithTag("shortcuts-assign-DROIDDECK").assertExists()
}
@Test fun backCancelsCaptureWithoutSaving() {
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.QAM)
send(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_DOWN)
compose.onNodeWithTag("shortcuts-cancel").assertDoesNotExist()
compose.runOnIdle {
assertTrue(PhysicalShortcuts.read(context).isEmpty())
}
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
}
@Test fun controllerBCancelsCaptureWithoutSaving() {
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.QAM)
send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_DOWN)
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
assertTrue(PhysicalShortcuts.read(context).isEmpty())
}
@Test fun closingConflictKeepsBothPreviousAssignments() {
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))),
PhysicalShortcuts.Action.STEAM)
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))),
PhysicalShortcuts.Action.QAM)
val previous = PhysicalShortcuts.read(context)
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.QAM)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
compose.onNodeWithTag("shortcuts-save").assertExists()
compose.onNodeWithTag("shortcuts-cancel").performScrollTo().performClick()
assertEquals(previous, PhysicalShortcuts.read(context))
}
@Test fun conflictingAssignmentIsNotReplacedUntilSave() {
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))),
PhysicalShortcuts.Action.STEAM)
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.QAM)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
compose.onNodeWithText(context.getString(R.string.shortcuts_conflict,
context.getString(R.string.drawer_steam_menu))).assertExists()
val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)))
compose.onAllNodesWithText("${button.label} · ${button.name}").assertCountEquals(2)
assertEquals(PhysicalShortcuts.Action.STEAM, PhysicalShortcuts.read(context).single().action)
compose.onNodeWithTag("shortcuts-save").performScrollTo().performClick()
compose.runOnIdle { assertEquals(PhysicalShortcuts.Action.QAM, PhysicalShortcuts.read(context).single().action) }
}
@Test fun removalRestoresDefaultAndPreservesOtherAssignmentsAndControllerSettings() {
ControllerPrefs.setSelectSteam(context, true)
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))),
PhysicalShortcuts.Action.STEAM)
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))),
PhysicalShortcuts.Action.QAM)
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.STEAM)
send(KeyEvent.KEYCODE_F3, KeyEvent.ACTION_DOWN)
compose.onNodeWithTag("shortcuts-remove").performScrollTo().performClick()
compose.runOnIdle {
assertEquals(PhysicalShortcuts.Action.QAM, PhysicalShortcuts.read(context).single().action)
assertTrue(ControllerPrefs.read(context).selectSteam)
}
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.game_settings_default))
}
@Test fun retryRecoversFromAMissingReleaseWithoutSavingTheOldButton() {
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.STEAM)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
compose.onNodeWithTag("shortcuts-retry").performScrollTo().performClick()
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_UP)
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN)))
compose.onNodeWithText("${button.label} · ${button.name}").assertExists()
compose.runOnIdle { assertEquals(KeyEvent.KEYCODE_F2, PhysicalShortcuts.read(context).single().button.keyCode) }
}
@Test fun longControllerNameDoesNotSqueezeTheMenuLabelInANarrowDrawer() {
val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.ACTION_DOWN)))
.copy(name = "Xbox Wireless Controller with a long device name")
PhysicalShortcuts.assign(context, button, PhysicalShortcuts.Action.STEAM)
compose.setContent {
DroidDeckTheme {
Box(Modifier.width(360.dp)) { PhysicalShortcutRows() }
}
}
val control = compose.onNodeWithTag("shortcuts-assign-STEAM").getUnclippedBoundsInRoot()
val label = compose.onNodeWithText(context.getString(R.string.drawer_steam_menu)).getUnclippedBoundsInRoot()
assertTrue(control.right - control.left < 200.dp)
assertTrue("Menu label must not wrap vertically: $label", label.bottom - label.top <= 48.dp)
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.ctrl_custom))
compose.onNodeWithText("${button.label} · ${button.name}").assertExists()
}
@Test fun replacingSameActionsButtonSavesWithoutConfirmation() {
val oldButton = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)))
PhysicalShortcuts.assign(context, oldButton, PhysicalShortcuts.Action.STEAM)
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.STEAM)
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN)
assertEquals(oldButton, PhysicalShortcuts.read(context).single().button)
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_UP)
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
compose.runOnIdle { assertEquals(KeyEvent.KEYCODE_F2, PhysicalShortcuts.read(context).single().button.keyCode) }
}
@Test
@Config(qualifiers = "de-rDE-w400dp-h850dp-port")
fun narrowLargeTextKeepsTranslatedCaptureReachableAndSavesOnRelease() {
compose.setContent {
val density = LocalDensity.current
CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale = 1.5f)) {
DroidDeckTheme { PhysicalShortcutRows() }
}
}
assign(PhysicalShortcuts.Action.DROIDDECK)
compose.onNodeWithText(context.getString(R.string.shortcuts_capture,
context.getString(R.string.shortcuts_dd_menu))).assertExists()
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
compose.runOnIdle { assertEquals(PhysicalShortcuts.Action.DROIDDECK, PhysicalShortcuts.read(context).single().action) }
}
@Test
@Config(qualifiers = "ar-rEG-w400dp-h850dp-port")
fun rightToLeftDialogKeepsCancelReachable() {
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.QAM)
compose.onNodeWithTag("shortcuts-cancel").performScrollTo().assertIsDisplayed().performClick()
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
}
@Test fun everySupportedLanguageHasALocalizedShortcutTitleAndValidFormatArguments() {
val languages = mutableListOf<String>()
context.resources.getXml(R.xml.locales_config).use { xml ->
while (xml.next() != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {
if (xml.eventType == org.xmlpull.v1.XmlPullParser.START_TAG && xml.name == "locale") {
languages.add(xml.getAttributeValue("http://schemas.android.com/apk/res/android", "name"))
}
}
}
val english = context.getString(R.string.shortcuts_title)
for (language in languages) {
val config = Configuration(context.resources.configuration).apply { setLocale(Locale.forLanguageTag(language)) }
val localized = context.createConfigurationContext(config)
if (language != "en") assertNotEquals(language, english, localized.getString(R.string.shortcuts_title))
assertTrue(localized.getString(R.string.shortcuts_capture, "ACTION").contains("ACTION"))
assertTrue(localized.getString(R.string.shortcuts_conflict, "ACTION").contains("ACTION"))
val detected = localized.getString(R.string.shortcuts_detected, "DEVICE", "BUTTON")
assertTrue(detected.contains("DEVICE"))
assertTrue(detected.contains("BUTTON"))
}
}
private fun assign(action: PhysicalShortcuts.Action) {
compose.onNodeWithTag("shortcuts-assign-${action.name}").performClick()
}
private fun send(code: Int, action: Int) {
compose.runOnIdle {
assertTrue(ShadowDialog.getLatestDialog().window!!.callback.dispatchKeyEvent(event(code, action)))
}
compose.waitForIdle()
}
private fun event(code: Int, action: Int) =
KeyEvent(100L, 100L, action, code, 0, 0, device.id, 700, 0, InputDevice.SOURCE_KEYBOARD)
}
@@ -8,6 +8,7 @@ import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
fun createRobolectricComposeRule() = createComposeRule().also {
RingVeil.reset()
val context = RuntimeEnvironment.getApplication()
shadowOf(context.packageManager).addActivityIfNotPresent(
ComponentName(context, ComponentActivity::class.java),
@@ -19,7 +19,8 @@ class SessionDrawerPageTest {
assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1))
assertEquals(sessionDrawerPages(false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN })
for (pages in listOf(connected, sessionDrawerPages(false))) {
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.DISPLAY, 1))
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
@@ -7,7 +7,7 @@ import android.view.InputDevice
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.compose.ui.test.*
import androidx.compose.ui.semantics.SemanticsProperties.StateDescription
import androidx.compose.runtime.MutableState
@@ -76,6 +76,28 @@ class SessionSecondScreenTest {
@Test fun steamTrackpadKeepsWorkingSteamShortcuts() = checkShortcuts(steam = true)
@Test fun trackpadMenuButtonOnlyAppearsWhenTheMenuCanMove() {
SessionState.mode = SessionService.MODE_STEAM
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val label = context.getString(R.string.touch_droiddeck_menu)
for (movable in listOf(false, true)) {
var menus = 0
val panel = SecondScreenPresentation(activity, display, { _, _, _, _ -> }, { _, _ -> }, {},
{}, {}, {}, onMenu = if (movable) ({ menus++ }) else null)
try {
panel.create()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
val buttons = descendants(panel.window!!.decorView).filter { it.contentDescription == label }.toList()
assertEquals(if (movable) 1 else 0, buttons.size)
buttons.forEach { it.performClick() }
assertEquals(if (movable) 1 else 0, menus)
} finally {
panel.closeControls()
}
}
}
@Test
@Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
fun controllerBumpersReachTheSecondScreenInBothSessionModes() {
@@ -86,7 +108,7 @@ class SessionSecondScreenTest {
SessionState.mode = mode
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
fun <T> state(name: String): MutableState<T> = ReflectionHelpers.getField(activity, "$name\$delegate")
state<Boolean>("drawerOpen").value = true
state<Boolean>("drawerOpenState").value = true
state<Boolean>("drawerControllerActive").value = true
state<List<SecondScreenDisplay>>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen"))
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN,
@@ -106,7 +128,7 @@ class SessionSecondScreenTest {
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 open: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerOpenState\$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)) {
@@ -188,9 +210,9 @@ class SessionSecondScreenTest {
try {
panel.create()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
val buttons = descendants(panel.window!!.decorView).filterIsInstance<Button>().toList()
val buttons = descendants(panel.window!!.decorView).filterIsInstance<TextView>().filter { it.isClickable }.toList()
assertTrue(buttons.any { it.text == context.getString(R.string.second_show_keyboard) })
val shortcuts = buttons.filter { it.text == "STEAM" || it.text == "…" }
val shortcuts = buttons.filter { it.text == "STEAM" || it.text == "•••" }
if (steam) {
assertEquals(2, shortcuts.size)
shortcuts.forEach { it.performClick() }
@@ -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())
}
}
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.update.AppUpdates.Offer
import com.droiddeck.launcher.update.AppUpdates.PreviewChange
import com.droiddeck.launcher.update.AppUpdates.PreviewHistoryKind
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.json.JSONArray
@@ -285,4 +286,69 @@ class AppUpdatesTest {
} catch (_: IOException) {
}
}
@Test fun anOlderStableIsGuessedStableAndSaved() {
val g = AppUpdates.guessFollow(catalog, me("eeeeeee999", version = "0.1.9"))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertTrue(g.certain)
}
@Test fun anOlderBuildInPreviewHistoryKeepsStableAsAnUncertainGuess() {
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.1.0"))
assertEquals(Channel.STABLE, g.follow.channel)
assertFalse(g.certain)
}
@Test fun anOlderCataloguedBuildDoesNotPersistAGuessAndExplicitChoicesStillWin() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val preferences = context.getSharedPreferences("app_updates", android.content.Context.MODE_PRIVATE)
preferences.edit().clear().commit()
try {
val installed = me("2".repeat(40), version = "0.1.0")
val newerStable = release("0".repeat(40), version = "9999.0.0")
val currentPreview = release(installed.commit)
val newerCatalog = AppUpdates.Catalog(newerStable, currentPreview, emptyList(), 0L)
assertEquals(Channel.STABLE, AppUpdates.follow(context, newerCatalog, installed).channel)
assertNull(preferences.getString("channel", null))
assertEquals(Channel.STABLE, AppUpdates.follow(context, null, installed).channel)
assertNull(preferences.getString("channel", null))
for (choice in listOf(Follow(Channel.STABLE), Follow(Channel.NIGHTLY), Follow(Channel.TEST, 93))) {
AppUpdates.setFollow(context, choice)
val actual = AppUpdates.follow(context, newerCatalog, installed)
assertEquals(choice.channel, actual.channel)
assertEquals(choice.pr, actual.pr)
}
} finally {
preferences.edit().clear().commit()
}
}
@Test fun runningTheCatalogStableIsCertainStable() {
val g = AppUpdates.guessFollow(catalog, me(stable.commit))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertTrue(g.certain)
}
@Test fun aPublishedPreviewPastStableIsGuessedNightlyWithoutSaving() {
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.NIGHTLY, g.follow.channel)
assertFalse(g.certain)
}
@Test fun anUncataloguedNewerBuildStaysStableForNow() {
val g = AppUpdates.guessFollow(catalog, me("9".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.STABLE, g.follow.channel)
assertFalse(g.certain)
val offline = AppUpdates.guessFollow(null, me("9".repeat(40), version = "0.3.0"))
assertEquals(AppUpdates.Channel.STABLE, offline.follow.channel)
assertFalse(offline.certain)
}
@Test fun aPullRequestBuildIsCertainTest() {
val g = AppUpdates.guessFollow(catalog, me("ccccccc2222222222222222222222222222222", pr = 93))
assertEquals(AppUpdates.Channel.TEST, g.follow.channel)
assertTrue(g.certain)
}
}