chore: merge main to catch up with 0.5.0

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

No files matched your search

@@ -0,0 +1,69 @@
package com.droiddeck.launcher.session
import android.content.Context
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 AddedGameMoveTest {
private val app get() = RuntimeEnvironment.getApplication()
private val prefs get() = app.getSharedPreferences("session", Context.MODE_PRIVATE)
private val from = "/data/root/Games/Stores/Epic/Fig"
private val to = "/storage/emulated/0/Games/Games/Epic/Fig"
@Test
fun settingsOfTheOldFolderMoveToTheNewOne() {
val all = mapOf(
"addedAppId:$from" to 3703311242L,
"addedExe:$from" to "$from/Fig.exe",
"addedExeSeen:$from" to 2,
"addedArt:hero:$from" to "https://cdn/hero.png",
"addedAdopted:exe:$from" to from,
"addedAppId:$from-2" to 5L,
"addedName:/other" to "Other",
"theme" to "graphite",
)
assertEquals(
mapOf(
"addedAppId:$from" to ("addedAppId:$to" to 3703311242L),
"addedExe:$from" to ("addedExe:$to" to "$to/Fig.exe"),
"addedExeSeen:$from" to ("addedExeSeen:$to" to 2),
"addedArt:hero:$from" to ("addedArt:hero:$to" to "https://cdn/hero.png"),
"addedAdopted:exe:$from" to ("addedAdopted:exe:$to" to to),
),
SessionPrefs.movedAddedGame(all, from, to),
)
}
@Test
fun nothingMovesWithoutSettings() {
assertEquals(emptyMap<String, Pair<String, Any?>>(), SessionPrefs.movedAddedGame(mapOf("theme" to "x"), from, to))
}
@Test
fun aMovedStoreGameKeepsItsAppIdAndRemoval() {
SessionPrefs.followStoreGame(app, "epic:fig", from) { true }
assertEquals(3703311242L, SessionPrefs.addedGameAppId(app, from, 3703311242L))
SessionPrefs.setAddedGameExe(app, from, "$from/Fig.exe")
SessionPrefs.setAddedGameRemoved(app, from, true)
SessionPrefs.followStoreGame(app, "epic:fig", to) { true }
assertEquals(3703311242L, SessionPrefs.addedGameAppId(app, to, 1L))
assertEquals("$to/Fig.exe", SessionPrefs.addedGameExe(app, to))
assertEquals(listOf(to), SessionPrefs.removedAddedGames(app))
assertEquals(false, prefs.contains("addedAppId:$from"))
}
@Test
fun aCopyThatIsStillThereKeepsItsOwnSettings() {
SessionPrefs.followStoreGame(app, "epic:fig", from) { false }
SessionPrefs.addedGameAppId(app, from, 7L)
SessionPrefs.followStoreGame(app, "epic:fig", to) { false }
assertEquals(9L, SessionPrefs.addedGameAppId(app, to, 9L))
assertEquals(7L, SessionPrefs.addedGameAppId(app, from, 1L))
}
}
@@ -41,6 +41,14 @@ class BatteryComponentTest {
assertTelemetry(supplies, vpower)
}
@Test fun vendorsReportingMilliampsGetTheSameEstimatesAsMicroamps() {
val supplies = tmp.newFolder("power_supply")
val vpower = tmp.newFolder("vpower")
start(supplies, vpower, -2_000L)
assertTelemetry(supplies, vpower)
assertEquals("-2000000", File(supplies, "BAT1/current_now").readText().trim())
}
private fun start(supplies: File, vpower: File, currentUa: Long) {
val context = RuntimeEnvironment.getApplication()
context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).apply {
@@ -61,7 +69,6 @@ class BatteryComponentTest {
val discovered = supplies.listFiles()!!.filter { it.name.contains("BAT") }
assertEquals(listOf("BAT1"), discovered.map { it.name })
fun read(name: String) = File(discovered.single(), name).readText().trim().toLong()
// One 4 Ah battery at 4 V drawing 2 A: 8 W and two hours, regardless of vendor current sign.
assertEquals(8_000_000L, read("power_now"))
assertEquals(16_000_000L, read("energy_now"))
assertEquals(7200L, read("time_to_empty_now"))
@@ -0,0 +1,99 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class BootMovieTest {
private val app get() = RuntimeEnvironment.getApplication()
private val custom get() = File(app.filesDir, "boot-movie/custom.webm")
@Before fun clear() {
app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
File(app.filesDir, "boot-movie").deleteRecursively()
}
@Test fun defaultsToThe30FpsMovieWithSound() {
assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app))
assertTrue(SessionPrefs.bootMovieSound(app))
assertNull(BootMovie.customName(app))
}
@Test fun customFallsBackWhenItsFileIsMissing() {
SessionPrefs.setBootMovie(app, BootMovie.CUSTOM)
assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app))
custom.parentFile!!.mkdirs()
custom.writeText("movie")
SessionPrefs.setBootMovieCustomName(app, "intro.webm")
assertEquals(BootMovie.CUSTOM, BootMovie.choice(app))
assertEquals("intro.webm", BootMovie.customName(app))
}
@Test fun unknownChoiceFallsBack() {
SessionPrefs.setBootMovie(app, "dd120")
assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app))
SessionPrefs.setBootMovie(app, BootMovie.DROIDDECK_60)
assertEquals(BootMovie.DROIDDECK_60, BootMovie.choice(app))
}
@Test fun removingTheCustomMovieReturnsToTheDefault() {
custom.parentFile!!.mkdirs()
custom.writeText("movie")
File(custom.parentFile, "custom-muted.webm").writeText("muted")
SessionPrefs.setBootMovieCustomName(app, "intro.webm")
SessionPrefs.setBootMovie(app, BootMovie.CUSTOM)
BootMovie.removeCustom(app)
assertFalse(custom.exists())
assertFalse(File(custom.parentFile, "custom-muted.webm").exists())
assertNull(BootMovie.customName(app))
assertEquals(BootMovie.DROIDDECK_30, SessionPrefs.bootMovie(app))
}
@Test fun unreadableImportsAreRefused() {
val junk = File(app.cacheDir, "junk.webm")
junk.writeBytes(ByteArray(1024))
assertEquals(BootMovie.Import.Unsupported(null), BootMovie.import(app, junk))
assertFalse(custom.exists())
}
@Test fun convertedMoviesFitA720pBoxAndKeepTheirShape() {
fun size(w: Int, h: Int, r: Int) = BootMovieTranscoder.layout(w, h, r).let { it.width to it.height }
assertEquals(1280 to 720, size(3840, 2160, 0))
assertEquals(640 to 480, size(640, 480, 180))
assertEquals(960 to 720, size(1440, 1080, 0))
}
@Test fun portraitMoviesArePillarboxedInto16x9() {
for (layout in listOf(BootMovieTranscoder.layout(1920, 1080, 90), BootMovieTranscoder.layout(1080, 1920, 0))) {
assertEquals(1280, layout.width)
assertEquals(720, layout.height)
assertEquals(404 to 720, layout.contentWidth to layout.contentHeight)
assertEquals(438, layout.x)
}
}
@Test fun audioIsResampledTo48kHz() {
val stereo = ShortArray(44_100 * 2) { if (it % 2 == 0) 1000 else -1000 }
val out = BootMovieTranscoder.resample(stereo, 2, 44_100)
assertEquals(48_000 * 2, out.size)
assertTrue(out.withIndex().all { (i, v) -> v == (if (i % 2 == 0) 1000 else -1000).toShort() })
assertSame(stereo, BootMovieTranscoder.resample(stereo, 2, 48_000))
}
@Test fun resetCoversTheChoiceButNotTheImportedName() {
assertTrue(SettingsReset.isSessionSetting("bootMovie"))
assertTrue(SettingsReset.isSessionSetting("bootMovieSound"))
assertFalse(SettingsReset.isSessionSetting("bootMovieCustomName"))
}
}
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ComponentsProcessTest {
private val guestPath = "/root/.local/share/Steam/steamapps/common/Proton"
private val hostPath = "/data/user/0/com.droiddeck.launcher/files/root/root/.local/share/Steam/steamapps/common/Proton"
@Test
fun `running game is recognized through guest path`() {
val command = "python3 $guestPath/proton waitforexitandrun game.exe"
assertTrue(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
}
@Test
fun `running game is recognized through Android host path`() {
val command = "python3 $hostPath/proton waitforexitandrun game.exe"
assertTrue(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
}
@Test
fun `Steam startup Proton process is not reported as a running game`() {
val command = "python3 $hostPath/proton run wineboot.exe"
assertFalse(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
assertTrue(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = false))
}
@Test
fun `unrelated Proton process is ignored`() {
val command = "python3 /other/Proton/proton waitforexitandrun game.exe"
assertFalse(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
}
}
@@ -0,0 +1,49 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.CpuAllocationDefaults
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 CoreAllocationPrefsTest {
private val app get() = RuntimeEnvironment.getApplication()
private val defaults = CpuAllocationDefaults.Allocation("7", "3,4,5,6")
private val saved get() = app.getSharedPreferences("session", Context.MODE_PRIVATE)
@Before fun clear() { saved.edit().clear().commit() }
@Test fun absentPreferencesUseTheDeviceDefaultWithoutWritingIt() {
assertEquals(SessionPrefs.CoreAllocation(true, "7", "3,4,5,6"), SessionPrefs.coreAllocation(app, defaults))
assertTrue(saved.all.isEmpty())
assertEquals(SessionPrefs.CoreAllocation(false, "", ""), SessionPrefs.coreAllocation(app, null))
}
@Test fun explicitDisableAndAllCoreChoicesSurviveAnUpdate() {
saved.edit().putBoolean("clientCpusOverride", false).putString("clientCpus", "").putString("gameCpus", "").commit()
assertEquals(SessionPrefs.CoreAllocation(false, "", ""), SessionPrefs.coreAllocation(app, defaults))
}
@Test fun existingCustomMasksArePreserved() {
saved.edit().putBoolean("clientCpusOverride", true).putString("clientCpus", "0,1").putString("gameCpus", "2,7").commit()
assertEquals(SessionPrefs.CoreAllocation(true, "0,1", "2,7"), SessionPrefs.coreAllocation(app, defaults))
}
@Test fun anOldClientMaskIsNotEnabledWithoutAnOverrideChoice() {
saved.edit().putString("clientCpus", "0,1").commit()
assertEquals(SessionPrefs.CoreAllocation(false, "0,1", "3,4,5,6"), SessionPrefs.coreAllocation(app, defaults))
}
@Test fun changingOneChoiceDoesNotReplaceTheOtherDefaults() {
SessionPrefs.setGameCpus(app, "0,1,2,3,4,5,6,7")
assertEquals(SessionPrefs.CoreAllocation(true, "7", "0,1,2,3,4,5,6,7"), SessionPrefs.coreAllocation(app, defaults))
SessionPrefs.setClientCpusOverride(app, false)
assertEquals(SessionPrefs.CoreAllocation(false, "7", "0,1,2,3,4,5,6,7"), SessionPrefs.coreAllocation(app, defaults))
}
}
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class FexCatalogTest {
private val sha = "0fc1ca2ba13817ad70d1ea157119a75c9c02446b57d166e6d676cce0807c19c4"
private val url = "https://github.com/Droid-Deck/DroidDeck-Components/releases/download/fex-2610-r5/fex.tzst"
private fun json(release: String = "fex-2610-r5", url: String = this.url, sha256: String = sha) =
"""{"schemaVersion": 1, "category": "fex", "release": "$release", "url": "$url", "sha256": "$sha256", "size": 4083539}"""
@Test fun readsTheBuildComponentsNames() {
assertEquals(FexCatalog.Build("fex-2610-r5", url, sha), FexCatalog.parse(json()))
}
@Test fun readsTheSingleReleaseByItsVersion() {
val single = "https://github.com/Droid-Deck/DroidDeck-Components/releases/download/fex/fex.tzst"
assertEquals(FexCatalog.Build("fex-2610-r6", single, sha), FexCatalog.parse(json(release = "fex", url = single).replace("}", ", \"version\": \"2610-r6\"}")))
assertNull(FexCatalog.parse(json(release = "fex", url = single).replace("}", ", \"version\": \"latest\"}")))
assertNull(FexCatalog.parse(json(release = "fex", url = single)))
}
@Test fun refusesAnArchiveOutsideItsOwnRelease() {
assertNull(FexCatalog.parse(json(url = "https://example.com/fex.tzst")))
assertNull(FexCatalog.parse(json(url = url.replace("fex-2610-r5/", "fex-2610-r4/"))))
assertNull(FexCatalog.parse(json(release = "latest", url = url.replace("fex-2610-r5", "latest"))))
}
@Test fun refusesAMissingOrMalformedDigest() {
assertNull(FexCatalog.parse(json(sha256 = "abc")))
assertNull(FexCatalog.parse("""{"release": "fex-2610-r5", "url": "$url"}"""))
assertNull(FexCatalog.parse("not json"))
}
@Test fun theSessionGetsTheBuildAndEverySource() {
val env = FexCatalog.environment(FexCatalog.Build("fex-2610-r5", url, sha), listOf(url, "https://ghfast.top/$url"))
assertEquals(listOf("BL_FEX_TAG=fex-2610-r5", "BL_FEX_SHA256=$sha", "BL_FEX_URLS=$url https://ghfast.top/$url"), env)
}
}
@@ -2,7 +2,10 @@ package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
@@ -89,6 +92,283 @@ class ForcedPackageTest {
assertNull(install(gpu(650, GpuInfo.Family.A6XX)))
}
@Test fun gameComponentProfilesReadOnlyKnownComponents() {
val state = File(context.filesDir, "components/state.json")
state.parentFile!!.mkdirs()
state.writeText(JSONObject()
.put("active", JSONObject())
.put("queued", JSONObject())
.put("profiles", JSONObject().put("42", JSONObject()
.put("fex", "fex.wcp")
.put("dxvk", "dxvk.wcp")
.put("unknown", "ignored.wcp")))
.toString())
assertEquals(mapOf("fex" to "fex.wcp", "dxvk" to "dxvk.wcp"), ComponentsManager.gameComponents(context, "42"))
assertTrue(ComponentsManager.gameComponents(context, "43").isEmpty())
}
@Test fun removingLastGameOverrideKeepsBundledComponentRestoreRow() {
val protonName = "proton-exp"
proton(protonName)
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
ComponentsManager.clearGameComponents(context, "42")
assertFalse(ComponentsManager.gameComponents(context, "42").containsKey("dxvk"))
assertDefaultDxvkRestoreRow(protonName)
}
@Test fun usingDefaultForLastGameOverrideKeepsBundledComponentRestoreRow() {
val protonName = "proton-exp"
proton(protonName)
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
ComponentsManager.setGameComponent(context, "42", "dxvk", null)
assertFalse(ComponentsManager.gameComponents(context, "42").containsKey("dxvk"))
assertDefaultDxvkRestoreRow(protonName)
}
@Test fun aNewProtonIsCapturedWhenTheLastOverrideIsReset() {
proton("existing")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
ComponentsManager.snapshotAll(context)
proton("new-proton")
ComponentsManager.clearGameComponents(context, "42")
assertDefaultDxvkRestoreRow("existing")
assertDefaultDxvkRestoreRow("new-proton")
}
@Test fun anUpdatedBuildIsCapturedEvenAfterTheLastProfileWasRemoved() {
proton("proton-exp")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
ComponentsManager.clearGameComponents(context, "42")
proton("proton-exp", "experimental-12")
ComponentsManager.setGameComponent(context, "43", "dxvk", null)
assertDefaultDxvkRestoreRow("proton-exp", "experimental-12")
assertTrue(original("proton-exp", "experimental-11").isFile)
assertTrue(original("proton-exp", "experimental-12").isFile)
}
@Test fun aKnownEmptyComponentHasAnExplicitOriginalBundle() {
proton("proton-exp", dxvk = false)
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
ComponentsManager.clearGameComponents(context, "42")
assertTrue(original("proton-exp").isFile)
val rows = launchState().readLines().map { it.split('\t') }
assertEquals(14, rows.size)
assertTrue(rows.all { it[3] == "dxvk" && it[5] == "-" && it[6] == "-" })
}
@Test fun missingOriginalsCannotBeRecapturedFromPreviouslyProfiledFiles() {
proton("proton-exp")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
val saved = File(context.filesDir, "components/state.json").readText()
val prior = "42\tproton-exp\texperimental-11\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t-\t-\n"
launchState().apply { parentFile!!.mkdirs(); writeText(prior) }
assertThrows(IllegalStateException::class.java) {
ComponentsManager.setGameComponent(context, "42", "dxvk", null)
}
assertEquals(saved, File(context.filesDir, "components/state.json").readText())
assertEquals(prior, launchState().readText())
assertFalse(original("proton-exp").isFile)
}
@Test fun aBrokenOriginalDoesNotPublishDeletionRowsOrRemoveThePreviousStore() {
proton("proton-exp")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
val state = File(context.filesDir, "components/state.json")
val saved = state.readText()
val prior = "*\tother\tbuild\tdxvk\tfiles/old.dll\told-hash\t/old.dll\n"
launchState().apply { parentFile!!.mkdirs(); writeText(prior) }
val oldSource = File(launchState().parentFile, "store/old/files/old.dll")
oldSource.apply { parentFile!!.mkdirs(); writeText("old component") }
original("proton-exp").apply { parentFile!!.mkdirs(); writeText("not a bundle") }
assertThrows(java.io.IOException::class.java) {
ComponentsManager.clearGameComponents(context, "42")
}
assertEquals(saved, state.readText())
assertEquals(prior, launchState().readText())
assertEquals("old component", oldSource.readText())
}
@Test fun anArchiveWithoutAProfileIsNotAKnownEmptyOriginal() {
proton("proton-exp")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
val bundle = original("proton-exp")
bundle.parentFile!!.mkdirs()
TarArchiveOutputStream(ZstdOutputStream(bundle.outputStream())).use { }
assertThrows(IllegalArgumentException::class.java) {
ComponentsManager.clearGameComponents(context, "42")
}
assertFalse(launchState().exists())
assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
}
@Test fun aFailedStateCommitIsRecoveredBeforeSelectionsCanBeRead() {
proton("proton-exp")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
val state = File(context.filesDir, "components/state.json")
val saved = state.readText()
val blocked = File(context.filesDir, "components/state.json.tmp")
blocked.mkdir()
val blocker = File(blocked, "blocker").apply { writeText("keep directory nonempty") }
val oldSource = File(launchState().parentFile, "store/old/files/old.dll").apply {
parentFile!!.mkdirs()
writeText("old component")
}
assertThrows(java.io.IOException::class.java) {
ComponentsManager.clearGameComponents(context, "42")
}
assertEquals(saved, state.readText())
assertTrue(pendingState().isFile)
assertTrue(launchState().isFile)
assertEquals(Hashes.sha256(launchState()), JSONObject(pendingState().readText()).getString("launchSha256"))
assertEquals("old component", oldSource.readText())
assertThrows(java.io.IOException::class.java) {
ComponentsManager.gameComponents(context, "42")
}
assertTrue(pendingState().isFile)
assertTrue(blocker.delete())
assertTrue(blocked.delete())
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
assertFalse(pendingState().exists())
assertDefaultDxvkRestoreRow("proton-exp")
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
ComponentsManager.snapshotAll(context)
assertFalse(oldSource.exists())
assertDefaultDxvkRestoreRow("proton-exp")
}
@Test fun aFailedLaunchPublicationRetainsTheOldSelectionsAndStore() {
proton("proton-exp")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
val state = File(context.filesDir, "components/state.json")
val saved = state.readText()
launchState().mkdirs()
val blocker = File(launchState(), "blocker").apply { writeText("block rename") }
val oldSource = File(launchState().parentFile, "store/old/files/old.dll").apply {
parentFile!!.mkdirs()
writeText("old component")
}
assertThrows(IllegalStateException::class.java) {
ComponentsManager.clearGameComponents(context, "42")
}
assertEquals(saved, state.readText())
assertTrue(pendingState().isFile)
assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
assertFalse(pendingState().exists())
assertEquals("old component", oldSource.readText())
assertTrue(blocker.delete())
assertTrue(launchState().delete())
ComponentsManager.clearGameComponents(context, "42")
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
assertFalse(oldSource.exists())
assertDefaultDxvkRestoreRow("proton-exp")
}
@Test fun interruptionBeforePublicationDiscardsOnlyThePendingSelections() {
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
val state = File(context.filesDir, "components/state.json")
val saved = state.readText()
val next = JSONObject(saved).apply {
getJSONObject("profiles").getJSONObject("42").put("dxvk", "new-dxvk.wcp")
}
val staged = File(launchState().parentFile, "desired.tsv.tmp").apply {
parentFile!!.mkdirs()
writeText("new launch table")
}
launchState().writeText("old launch table")
writePendingState(next, staged)
assertEquals("old-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
assertEquals(saved, state.readText())
assertEquals("old launch table", launchState().readText())
assertFalse(pendingState().exists())
assertFalse(staged.exists())
}
@Test fun identicalLaunchTablesDoNotCommitUnpublishedSettings() {
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
val state = File(context.filesDir, "components/state.json")
val saved = state.readText()
val next = JSONObject(saved).put("queued", JSONObject().put("proton-exp", JSONObject()))
val staged = File(launchState().parentFile, "desired.tsv.tmp").apply {
parentFile!!.mkdirs()
writeText("unchanged launch table")
}
launchState().writeText(staged.readText())
writePendingState(next, staged)
assertEquals("old-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
assertEquals(saved, state.readText())
assertFalse(pendingState().exists())
assertFalse(staged.exists())
}
@Test fun interruptionAfterPublicationRecoversAllSelectionsAndIsIdempotent() {
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
val next = JSONObject()
.put("active", JSONObject().put("proton-exp", JSONObject().put("dxvk", JSONObject().put("file", dxvk2))))
.put("queued", JSONObject().put("proton-exp", JSONObject().put("fex", JSONObject().put("file", "fex.wcp"))))
.put("profiles", JSONObject()
.put("42", JSONObject().put("dxvk", "new-dxvk.wcp"))
.put("43", JSONObject().put("fex", "fex.wcp")))
.put("profiledComponents", JSONArray(listOf("dxvk", "fex")))
launchState().apply { parentFile!!.mkdirs(); writeText("published launch table") }
writePendingState(next, launchState())
assertEquals("new-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
assertEquals("fex.wcp", ComponentsManager.gameComponents(context, "43")["fex"])
assertEquals(next.toString(2), File(context.filesDir, "components/state.json").readText())
assertFalse(pendingState().exists())
assertEquals("published launch table", launchState().readText())
assertEquals("new-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
}
@Test fun aPendingTransactionAfterTheStateCommitCanBeRecoveredAgain() {
writeGameProfile("42", "dxvk", "new-dxvk.wcp")
val state = File(context.filesDir, "components/state.json")
val next = JSONObject(state.readText())
launchState().apply { parentFile!!.mkdirs(); writeText("published launch table") }
writePendingState(next, launchState())
assertEquals("new-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
assertEquals(next.toString(2), state.readText())
assertFalse(pendingState().exists())
}
@Test fun anUnreadableRecoveryRecordDoesNotSilentlyReturnStaleSelections() {
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
pendingState().writeText("incomplete recovery record")
assertThrows(org.json.JSONException::class.java) {
ComponentsManager.gameComponents(context, "42")
}
assertTrue(pendingState().isFile)
}
@Test fun theSamePackageOnThisProtonBuildIsNotFetchedAgain() {
proton("proton-exp")
writeState("proton-exp", dxvk2, "experimental-11")
@@ -204,11 +484,57 @@ class ForcedPackageTest {
private fun refuseApply(protonId: String, file: String): String = error("apply $protonId $file")
private fun proton(name: String, version: String = "experimental-11") {
private fun writeGameProfile(scope: String, comp: String, file: String) {
val state = File(context.filesDir, "components/state.json")
state.parentFile!!.mkdirs()
state.writeText(
JSONObject()
.put("active", JSONObject())
.put("queued", JSONObject())
.put("profiles", JSONObject().put(scope, JSONObject().put(comp, file)))
.toString(),
)
}
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
private fun pendingState() = File(context.filesDir, "components/state.pending.json")
private fun writePendingState(state: JSONObject, launch: File) {
pendingState().writeText(JSONObject()
.put("state", state)
.put("launchSha256", Hashes.sha256(launch))
.toString())
}
private fun original(protonName: String, version: String = "experimental-11") =
File(context.filesDir, "components/originals/$protonName/$version/dxvk.wcp")
private fun assertDefaultDxvkRestoreRow(protonName: String, version: String = "experimental-11") {
val row = launchState().readLines().map { it.split('\t') }.single {
it.size == 7 && it[0] == "*" && it[1] == protonName && it[2] == version &&
it[3] == "dxvk" && it[4].endsWith("/aarch64-windows/d3d11.dll")
}
assertNotEquals("-", row[6])
val source = File(LinuxRuntime.rootDir(context), row[6].removePrefix("/"))
assertEquals("bundled DXVK $version", source.readText())
assertEquals(Hashes.sha256(source), row[5])
assertTrue(original(protonName, version).isFile)
val state = JSONObject(File(context.filesDir, "components/state.json").readText())
assertEquals(listOf("dxvk"), state.getJSONArray("profiledComponents").let { values ->
(0 until values.length()).map(values::getString)
})
}
private fun proton(name: String, version: String = "experimental-11", dxvk: Boolean = true) {
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")
if (dxvk) File(dir, "files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply {
parentFile!!.mkdirs()
writeText("bundled DXVK $version")
}
}
private fun writeState(protonId: String, file: String, protonVersion: String) {
@@ -60,7 +60,6 @@ class GameEnvironmentStoreTest {
"d3d9.samplerAnisotropy = 16; d3d11.samplerAnisotropy = 16; d3d9.samplerLodBias = -0.58; d3d11.samplerLodBias = -0.58",
json.getString(GameEnvironmentStore.DXVK_CONFIG),
)
// The user's own entry is untouched; the launcher appends the options at launch.
assertEquals("dxvk.tearFree = True", json.getJSONObject("shared").getString("DXVK_CONFIG"))
assertEquals(GameEnvironment.Config(shared = mapOf("DXVK_CONFIG" to "dxvk.tearFree = True")), GameEnvironmentStore.read(context))
SessionPrefs.setTextureAnisotropy(context, 0)
@@ -69,6 +68,91 @@ class GameEnvironmentStoreTest {
SessionState.upscaleRatio = 0f
}
@Test fun changingGameFexPresetPreservesDefaultAndOtherGameSettings() {
SessionPrefs.setFexPreset(context, "PERFORMANCE_TSO")
val original = GameEnvironment.withGameFexPreset(
GameEnvironment.Config(
shared = mapOf("PROTON_LOG" to "1"),
games = mapOf("42" to mapOf("DXVK_HUD" to "fps")),
),
"43",
"COMPATIBILITY",
)
GameEnvironmentStore.save(context, original)
GameEnvironmentStore.setGameFexPreset(context, "42", "STABILITY")
val saved = GameEnvironmentStore.read(context)
assertEquals("STABILITY", GameEnvironment.gameFexPreset(saved, "42"))
assertEquals("fps", saved.entries("42")["DXVK_HUD"])
assertEquals(original.shared, saved.shared)
assertEquals(original.entries("43"), saved.entries("43"))
assertEquals("PERFORMANCE_TSO", SessionPrefs.fexPreset(context))
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals(saved.games, published.games)
assertEquals("0", published.shared["FEX_HALFBARRIERTSOENABLED"])
assertEquals("1", published.entries("42")["FEX_HALFBARRIERTSOENABLED"])
}
@Test fun gameFexDefaultsAndInheritanceRemainDistinct() {
SessionPrefs.setFexPreset(context, "EXTREME")
val original = GameEnvironment.Config(
games = mapOf("42" to mapOf("DXVK_HUD" to "fps")),
)
GameEnvironmentStore.save(context, original)
GameEnvironmentStore.setGameFexPreset(context, "42", "")
val explicitDefaults = GameEnvironmentStore.read(context)
assertEquals("", GameEnvironment.gameFexPreset(explicitDefaults, "42"))
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertTrue(published.entries("42").containsKey("FEX_SMCCHECKS"))
assertNull(published.entries("42")["FEX_SMCCHECKS"])
GameEnvironmentStore.setGameFexPreset(context, "42", null)
assertEquals(original, GameEnvironmentStore.read(context))
val inherited = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertFalse(inherited.entries("42").containsKey("FEX_SMCCHECKS"))
assertEquals("none", inherited.shared["FEX_SMCCHECKS"])
assertEquals("EXTREME", SessionPrefs.fexPreset(context))
}
@Test fun invalidGamePresetEditsCannotChangeSavedOrPublishedSettings() {
val original = GameEnvironment.Config(shared = mapOf("PROTON_LOG" to "1"))
GameEnvironmentStore.save(context, original)
val published = guest.readText()
assertThrows(IllegalArgumentException::class.java) {
GameEnvironmentStore.setGameFexPreset(context, "", "STABILITY")
}
assertThrows(IllegalArgumentException::class.java) {
GameEnvironmentStore.setGameFexPreset(context, "42", GameEnvironment.CUSTOM_FEX_PRESET)
}
assertEquals(original, GameEnvironmentStore.read(context))
assertEquals(published, guest.readText())
}
@Test fun targetedFexUpdateDoesNotRestoreEnvironmentClearedByACompletedReset() {
val original = GameEnvironment.withGameFexPreset(
GameEnvironment.Config(games = mapOf("42" to mapOf("DXVK_HUD" to "fps"))),
"42",
"COMPATIBILITY",
)
GameEnvironmentStore.save(context, original)
val staleEditorSnapshot = GameEnvironmentStore.read(context)
val resetEnvironment = staleEditorSnapshot.withEntries("42", emptyMap())
GameEnvironmentStore.save(context, resetEnvironment)
GameEnvironmentStore.setGameFexPreset(context, "43", "PERFORMANCE_TSO")
val saved = GameEnvironmentStore.read(context)
assertTrue(saved.entries("42").isEmpty())
assertEquals("PERFORMANCE_TSO", GameEnvironment.gameFexPreset(saved, "43"))
assertFalse(saved.games.containsKey("42"))
}
@Test fun unchosenFexPresetPublishesPerformanceTso() {
GameEnvironmentStore.save(context, GameEnvironment.Config())
val shared = JSONObject(guest.readText()).getJSONObject("shared")
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class GameProfileFollowStateTest {
@Test fun reopeningGamesPageResumesFollowingSteamAfterManualInspection() {
val state = GameProfileFollowState()
state.selectManually()
assertFalse(state.followsSteam)
state.resumeFollowingSteam()
assertTrue(state.followsSteam)
}
}
@@ -0,0 +1,103 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class GameProfileInventoryCacheTest {
@Test
fun loadsOnlyOncePerRevision() {
val cache = GameProfileInventoryCache<String>()
var loads = 0
assertEquals(listOf("one"), cache.get(0) { loads++; listOf("one") })
assertEquals(listOf("one"), cache.get(0) { loads++; listOf("two") })
assertEquals(1, loads)
assertEquals(listOf("two"), cache.get(1) { loads++; listOf("two") })
assertEquals(2, loads)
}
@Test
fun failedLoadIsRetriedInsteadOfCached() {
val cache = GameProfileInventoryCache<String>()
var loads = 0
assertThrows(IllegalStateException::class.java) {
cache.get(0) { loads++; error("inventory unavailable") }
}
assertEquals(listOf("recovered"), cache.get(0) { loads++; listOf("recovered") })
assertEquals(2, loads)
}
@Test
fun failedNewRevisionDoesNotReuseThePreviousInventory() {
val cache = GameProfileInventoryCache<String>()
assertEquals(listOf("old"), cache.get(0) { listOf("old") })
assertThrows(IllegalStateException::class.java) {
cache.get(1) { error("inventory unavailable") }
}
assertEquals(listOf("new"), cache.get(1) { listOf("new") })
assertEquals(listOf("new"), cache.get(1) { error("should use cached inventory") })
}
@Test
fun emptyInventoryIsCachedUntilTheRevisionChanges() {
val cache = GameProfileInventoryCache<String>()
assertEquals(emptyList<String>(), cache.get(0) { emptyList() })
assertEquals(emptyList<String>(), cache.get(0) { error("should use cached inventory") })
assertEquals(listOf("installed"), cache.get(1) { listOf("installed") })
}
@Test(timeout = 10_000)
fun reopeningDuringAScanQueuesFreshInventoryWithoutWaitingAndRejectsOldResults() {
data class Refresh(val appId: Long, val inventoryRevision: Long)
val cache = GameProfileInventoryCache<String>()
val coordinator = LatestRequestCoordinator<Refresh>()
val scanStarted = CountDownLatch(1)
val finishScan = CountDownLatch(1)
val worker = Executors.newSingleThreadExecutor()
try {
assertTrue(coordinator.submit(Refresh(42, 0)))
val first = coordinator.takeLatest()!!
val oldInventory = worker.submit<List<String>> {
cache.get(first.value.inventoryRevision) {
scanStarted.countDown()
check(finishScan.await(5, TimeUnit.SECONDS))
listOf("old")
}
}
assertTrue(scanStarted.await(5, TimeUnit.SECONDS))
assertFalse(coordinator.submit(Refresh(42, 1)))
assertFalse(oldInventory.isDone)
assertFalse(coordinator.isLatest(first))
finishScan.countDown()
assertEquals(listOf("old"), oldInventory.get(5, TimeUnit.SECONDS))
assertFalse(coordinator.isLatest(first))
val reopened = coordinator.takeLatest()!!
val newInventory = worker.submit<List<String>> {
cache.get(reopened.value.inventoryRevision) { listOf("new") }
}
assertEquals(listOf("new"), newInventory.get(5, TimeUnit.SECONDS))
assertTrue(coordinator.isLatest(reopened))
assertNull(coordinator.takeLatest())
} finally {
finishScan.countDown()
worker.shutdownNow()
assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS))
}
}
}
@@ -0,0 +1,103 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.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 GameProfileManagerTest {
private lateinit var context: Context
@Before
fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
File(context.filesDir, "game-environment.json").delete()
File(context.filesDir, "wincomponents.json").delete()
File(context.filesDir, "components").deleteRecursively()
File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").deleteRecursively()
}
@Test
fun resetClearsOnlyTheSelectedGameProfile() {
val game = "42"
val other = "43"
GameEnvironmentStore.save(
context,
GameEnvironment.Config(
games = mapOf(
game to mapOf("DXVK_HUD" to "fps"),
other to mapOf("DXVK_HUD" to "compiler"),
),
),
)
ProtonDefault.requestGame(context, game, proton("game"))
ProtonDefault.requestGame(context, other, proton("other"))
seedComponentProfiles(game, other)
SessionPrefs.setGameTextureAnisotropy(context, game, 4)
SessionPrefs.setGameTextureAnisotropy(context, other, 8)
WinComponents.setPicks(context, game, listOf("vcrun2022"))
WinComponents.setPicks(context, other, listOf("dotnet48"))
GameProfileManager.reset(context, game)
val environment = GameEnvironmentStore.read(context)
assertFalse(environment.games.containsKey(game))
assertEquals("compiler", environment.entries(other)["DXVK_HUD"])
assertNull(ProtonDefault.gameChoice(context, game))
assertEquals("other", ProtonDefault.gameChoice(context, other)?.dir)
assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, game))
assertEquals("other.wcp", ComponentsManager.gameComponents(context, other)["dxvk"])
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, game))
assertEquals(8, SessionPrefs.gameTextureFiltering(context, other).anisotropy)
assertEquals(emptyList<String>(), WinComponents.picks(context, game))
assertEquals(listOf("dotnet48"), WinComponents.picks(context, other))
}
@Test
fun resetRejectsEmptyScopeWithoutChangingSharedSettings() {
GameEnvironmentStore.save(
context,
GameEnvironment.Config(shared = mapOf("DXVK_HUD" to "fps")),
)
assertThrows(IllegalArgumentException::class.java) {
GameProfileManager.reset(context, "")
}
assertEquals("fps", GameEnvironmentStore.read(context).shared["DXVK_HUD"])
}
private fun proton(name: String) = ComponentsManager.Proton(
id = name,
name = name,
dir = File(context.filesDir, name),
guestPath = "/proton/$name",
version = "1",
valve = false,
)
private fun seedComponentProfiles(game: String, other: String) {
val components = File(context.filesDir, "components").apply { mkdirs() }
File(components, "state.json").writeText(
JSONObject().put(
"profiles",
JSONObject()
.put(game, JSONObject().put("dxvk", "game.wcp"))
.put(other, JSONObject().put("dxvk", "other.wcp")),
).toString(),
)
}
}
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class GameProfileRefreshStateTest {
@Test
fun firstFailureKeepsInitialStateWithoutCachedData() {
val state = GameProfileRefreshState<String>().failed()
assertTrue(state.failed)
assertFalse(state.loaded)
assertNull(state.data)
}
@Test
fun failureAfterSuccessPreservesCachedData() {
val state = GameProfileRefreshState<String>().succeeded("cached profiles").failed()
assertTrue(state.failed)
assertTrue(state.loaded)
assertEquals("cached profiles", state.data)
}
@Test
fun successAfterFailureReplacesCachedDataAndClearsWarning() {
val state = GameProfileRefreshState<String>()
.succeeded("old profiles")
.failed()
.succeeded("new profiles")
assertFalse(state.failed)
assertTrue(state.loaded)
assertEquals("new profiles", state.data)
}
@Test
fun retryingClearsWarningWithoutDiscardingCachedData() {
val state = GameProfileRefreshState<String>().succeeded("cached profiles").failed().retrying()
assertFalse(state.failed)
assertTrue(state.loaded)
assertEquals("cached profiles", state.data)
}
}
@@ -0,0 +1,35 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class GameThreadHintsTest {
@Test fun `a thread joins above 60 percent and leaves under 15`() {
assertEquals(emptySet<Int>(), GameThreadHints.pick(emptySet(), mapOf(1 to 0.55)))
assertEquals(setOf(1), GameThreadHints.pick(emptySet(), mapOf(1 to 0.68)))
// Faster where it was moved, or capped by the display, it stays boosted at 25%...
assertEquals(setOf(1), GameThreadHints.pick(setOf(1), mapOf(1 to 0.25)))
// ...and is let go once it idles.
assertEquals(emptySet<Int>(), GameThreadHints.pick(setOf(1), mapOf(1 to 0.1)))
}
@Test fun `at most two threads, the boosted ones kept before busier newcomers`() {
val busy = mapOf(1 to 0.2, 2 to 0.9, 3 to 0.8, 4 to 0.7, 5 to 0.95)
assertEquals(setOf(1, 5), GameThreadHints.pick(setOf(1), busy))
}
@Test fun `a thread gone from proc is dropped`() {
assertEquals(setOf(2), GameThreadHints.pick(setOf(1, 2), mapOf(2 to 0.7)))
}
@Test fun `a game at the panel's rate or a fraction of it holds pace`() {
assertTrue(GameThreadHints.holdsPace(119.0, 120.0))
assertTrue(GameThreadHints.holdsPace(60.5, 120.0))
assertTrue(GameThreadHints.holdsPace(30.0, 120.0))
assertFalse(GameThreadHints.holdsPace(92.0, 120.0)) // falling behind: boost
assertFalse(GameThreadHints.holdsPace(105.0, 120.0))
assertFalse(GameThreadHints.holdsPace(3.0, 120.0)) // headless or loading: boost
}
}
@@ -0,0 +1,68 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class LatestRequestCoordinatorTest {
@Test fun coalescesPendingRequestsToTheLatestValue() {
val coordinator = LatestRequestCoordinator<String>()
assertTrue(coordinator.submit("first"))
val first = coordinator.takeLatest()!!
assertFalse(coordinator.submit("second"))
assertFalse(coordinator.submit("third"))
assertFalse(coordinator.isLatest(first))
val latest = coordinator.takeLatest()!!
assertEquals("third", latest.value)
assertTrue(coordinator.isLatest(latest))
assertNull(coordinator.takeLatest())
}
@Test fun requestAfterWorkerBecomesIdleStartsAnotherWorker() {
val coordinator = LatestRequestCoordinator<String>()
assertTrue(coordinator.submit("first"))
coordinator.takeLatest()
assertNull(coordinator.takeLatest())
assertTrue(coordinator.submit("second"))
assertEquals("second", coordinator.takeLatest()!!.value)
}
@Test fun newerRequestInvalidatesCompletedResultBeforeItIsApplied() {
val coordinator = LatestRequestCoordinator<String>()
assertTrue(coordinator.submit("first"))
val completed = coordinator.takeLatest()!!
assertFalse(coordinator.submit("second"))
assertFalse(coordinator.isLatest(completed))
assertEquals("second", coordinator.takeLatest()!!.value)
}
@Test fun profileSwitchInvalidatesAnOlderFailedRefresh() {
val coordinator = LatestRequestCoordinator<Long?>()
assertTrue(coordinator.submit(42L))
val failedRefresh = coordinator.takeLatest()!!
assertFalse(coordinator.submit(43L))
assertFalse(coordinator.isLatest(failedRefresh))
assertEquals(43L, coordinator.takeLatest()!!.value)
}
@Test fun repeatedPollDoesNotInvalidateEquivalentInFlightResult() {
val coordinator = LatestRequestCoordinator<String>()
assertTrue(coordinator.submit("same"))
val inFlight = coordinator.takeLatest()!!
assertFalse(coordinator.submit("same"))
assertTrue(coordinator.isLatest(inFlight))
assertEquals("same", coordinator.takeLatest()!!.value)
}
}
@@ -0,0 +1,95 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.epic.EpicClient
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
import org.robolectric.RuntimeEnvironment
import java.io.File
@RunWith(RobolectricTestRunner::class)
class NoSteamLaunchTest {
private val context get() = RuntimeEnvironment.getApplication()
@After fun clean() {
File(context.filesDir, "game-environment.json").delete()
NoSteamLaunch.names.clear()
}
private val steamGame = Library.SteamGame(413150, "Stardew Valley", null, "internal")
private val shortcut = Library.SteamGame((2733369024L).toInt(), "Hogwarts Legacy", null, Library.ADDED, source = "epic")
private val launcher = Library.SteamGame(EpicClient.LAUNCHER_APP_ID, Library.EPIC_LAUNCHER_NAME, null, Library.EPIC_LAUNCHER, source = "epic")
@Test fun eachKindOfGameKeepsTheSettingUnderItsOwnId() {
assertEquals("413150", NoSteamLaunch.scope(steamGame))
assertEquals("2733369024", NoSteamLaunch.scope(shortcut))
assertEquals(EpicClient.shortcutAppId.toString(), NoSteamLaunch.scope(launcher))
assertNull(NoSteamLaunch.scope(Library.SteamGame(0, "nothing", null, "internal")))
}
@Test fun theSettingIsRememberedPerGame() {
assertFalse(NoSteamLaunch.enabled(context, shortcut))
GameEnvironmentStore.setGameNoSteam(context, "2733369024", true)
assertTrue(NoSteamLaunch.enabled(context, shortcut))
assertTrue(NoSteamLaunch.enabled(context, 2733369024L))
assertFalse(NoSteamLaunch.enabled(context, steamGame))
assertFalse(NoSteamLaunch.enabled(context, launcher))
GameEnvironmentStore.setGameNoSteam(context, EpicClient.shortcutAppId.toString(), true)
assertTrue(NoSteamLaunch.enabled(context, launcher))
GameEnvironmentStore.setGameNoSteam(context, "2733369024", false)
assertFalse(NoSteamLaunch.enabled(context, shortcut))
assertTrue(GameEnvironment.gameNoSteam(GameEnvironmentStore.read(context), EpicClient.shortcutAppId.toString()))
}
@Test fun eachGameStartsInItsOwnProtonOrTheLauncherWithoutSteam() {
val game = AddedGames.Game(
File("/x/Hogwarts Legacy"), "Hogwarts Legacy", File("/x/Hogwarts Legacy/.droiddeck-launch.bat"),
"/mnt/droiddeck-sd/Games/Epic/Hogwarts Legacy/.droiddeck-launch.bat", "/mnt/droiddeck-sd/Games/Epic/Hogwarts Legacy",
2733369024L, 0L, emptyList(), source = "epic", launchOptions = "-windowed",
)
val added = NoSteamLaunch.command(shortcut, game)!!
assertEquals(NoSteamLaunch.PROTON_RUN, added.program)
assertEquals(
listOf("--app", "2733369024", "--dir", game.guestDir, "--options", "-windowed", "--", game.guestExe),
added.args,
)
assertNull(NoSteamLaunch.command(shortcut, null))
val steam = NoSteamLaunch.command(steamGame, null)!!
assertEquals(listOf("--app", "413150"), steam.args)
val epic = NoSteamLaunch.command(launcher, null)!!
assertEquals(NoSteamLaunch.EPIC to listOf("run"), epic.program to epic.args)
}
@Test fun anAddedGameOwnedOnSteamUsesItsSteamIdForSettingsAndLaunch() {
val routed = AddedGames.Game(
File("/x/Stardew Valley"), "Stardew Valley", File("/x/Stardew Valley/Stardew Valley.exe"),
"/mnt/droiddeck-sd/Games/Stardew Valley/Stardew Valley.exe", "/mnt/droiddeck-sd/Games/Stardew Valley",
2733369024L, 413150L, emptyList(), steamAppId = 413150,
)
assertEquals(413150L, NoSteamLaunch.settingsId(routed))
val entry = Library.SteamGame(413150, "Stardew Valley", null, Library.ADDED)
assertEquals(NoSteamLaunch.settingsId(routed).toString(), NoSteamLaunch.scope(entry))
val command = NoSteamLaunch.command(entry, routed)!!
assertEquals(NoSteamLaunch.PROTON_RUN to listOf("--app", "413150"), command.program to command.args)
val plain = AddedGames.Game(File("/x/a"), "a", File("/x/a/a.exe"), "/g/a.exe", "/g", 2733369024L, 0L, emptyList())
assertEquals(2733369024L, NoSteamLaunch.settingsId(plain))
}
@Test fun theRunningSessionIsNamedAfterItsGame() {
val command = NoSteamLaunch.command(steamGame, null)!!
assertNull(NoSteamLaunch.nameFor(command.program, command.args))
NoSteamLaunch.remember(command)
assertEquals("Stardew Valley", NoSteamLaunch.nameFor(command.program, command.args))
assertEquals(Library.EPIC_LAUNCHER_NAME, NoSteamLaunch.nameFor(NoSteamLaunch.EPIC, listOf("run")))
assertNull(NoSteamLaunch.nameFor("/usr/bin/retroarch", emptyList()))
assertNull(NoSteamLaunch.nameFor(NoSteamLaunch.PROTON_RUN, listOf("/x/a.exe")))
}
}
@@ -0,0 +1,37 @@
package com.droiddeck.launcher.session
import android.view.Display
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowDisplayManager
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], manifest = Config.NONE)
class PerfModeTest {
private fun mode(id: Int, hz: Float, width: Int = 1080): Display.Mode =
ShadowDisplayManager.ModeBuilder.modeBuilder(id)
.setWidth(width).setHeight(2520).setRefreshRate(hz).build()
@Test fun sixtyHzMirrorChoosesSixtyEvenThoughOneTwentyHasMatchingCadence() {
val low = mode(1, 60f)
val high = mode(2, 120f)
assertEquals(low, PerfMode.selectMode(arrayOf(low, high), high, 60, 60f))
assertEquals(high, PerfMode.selectMode(arrayOf(low, high), low, 0, Float.POSITIVE_INFINITY))
}
@Test fun aLowerGameLimitDoesNotOverrideTheGlassesRefreshCeiling() {
val modes = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f))
assertEquals(modes[0], PerfMode.selectMode(modes, modes[2], 30, 60f))
assertEquals(modes[1], PerfMode.selectMode(modes, modes[2], 45, 90f))
}
@Test fun selectionPreservesResolutionAndUsesTheLowestModeIfTheCapIsUnsupported() {
val low = mode(1, 90f)
val high = mode(2, 120f)
val otherResolution = mode(3, 60f, 720)
assertEquals(low, PerfMode.selectMode(arrayOf(low, high, otherResolution), high, 60, 60f))
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -7,6 +8,7 @@ import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.io.File
@RunWith(RobolectricTestRunner::class)
@@ -59,4 +61,46 @@ class ProtonDefaultTest {
assertNull(ProtonDefault.chosen(ProtonDefault.parseState("{"), ProtonDefault.parseRequest("[]")))
assertNull(ProtonDefault.parseRequest("""{"seq": 0, "dir": "x"}"""))
}
@Test
fun perGameChoicesPreserveCustomizeAndInheritSemantics() {
val games = ProtonDefault.parseGames(
"""{"version":1,"games":{"42":{"valve":false,"dir":"GE-Proton11-7"},"43":null,"0":null,"bad":{},"44":{"valve":"false","dir":"GE-Proton9-1"}}}""",
)
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton11-7"), games["42"])
assertTrue(games.containsKey("43"))
assertNull(games["43"])
assertFalse(games.containsKey("0"))
assertFalse(games.containsKey("bad"))
assertFalse(games.containsKey("44"))
assertTrue(ProtonDefault.parseGames("""{"version":2,"games":{"42":null}}""").isEmpty())
}
@Test
fun perGameRequestsPersistCustomizeThenInherit() {
val context = RuntimeEnvironment.getApplication()
val file = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat/games.json")
file.parentFile?.deleteRecursively()
val selected = proton("GE-Proton11-7", false)
ProtonDefault.requestGame(context, "42", selected)
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton11-7"), ProtonDefault.parseGames(file.readText())["42"])
ProtonDefault.requestGame(context, "42", null)
val inherited = ProtonDefault.parseGames(file.readText())
assertTrue(inherited.containsKey("42"))
assertNull(inherited["42"])
}
@Test
fun missingPerGameProtonIdentityRemainsStoredButUnresolved() {
val context = RuntimeEnvironment.getApplication()
val file = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat/games.json")
file.parentFile?.deleteRecursively()
ProtonDefault.requestGame(context, "42", proton("GE-Proton9-1", false))
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton9-1"), ProtonDefault.gameChoice(context, "42"))
assertNull(ProtonDefault.gameSelectedId(context, "42", listOf(proton("GE-Proton11-7", false))))
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton9-1"), ProtonDefault.parseGames(file.readText())["42"])
}
}
@@ -0,0 +1,174 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
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.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ProtonExtrasTest {
@get:Rule val temp = TemporaryFolder()
private fun tool(id: String) = ProtonExtras.tools.single { it.id == id }
private fun asset(name: String, digest: String? = null) = JSONObject()
.put("name", name)
.put("browser_download_url", "https://github.com/o/r/releases/download/t/$name")
.put("size", 625_775_670L)
.apply { if (digest != null) put("digest", digest) }
private fun release(tag: String, vararg assets: JSONObject, prerelease: Boolean = false, draft: Boolean = false) = JSONObject()
.put("tag_name", tag).put("prerelease", prerelease).put("draft", draft)
.put("assets", JSONArray().apply { assets.forEach { put(it) } })
private fun droiddeckRelease(ver: String, prerelease: Boolean = false) = release(
"DroidDeck-Proton-$ver",
asset("DroidDeck-Proton-$ver-aarch64.build-info.json"),
asset("DroidDeck-Proton-$ver-aarch64.sha512sum"),
asset("DroidDeck-Proton-$ver-aarch64.tar.gz"),
prerelease = prerelease,
)
private fun installTool(parent: File, name: String) = File(parent, name).apply {
mkdirs()
File(this, "toolmanifest.vdf").writeText("\"manifest\" { \"commandline\" \"/proton %verb%\" }")
}
@Test
fun theThreeSourcesInOrder() {
assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id })
val droiddeck = tool("droiddeck")
assertEquals("DroidDeck-Proton", droiddeck.name)
assertEquals("DroidDeck-Proton", droiddeck.prefix)
assertEquals("Droid-Deck/DroidDeck-Proton", droiddeck.repo)
assertTrue(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
assertTrue(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-8-aarch64.tar.xz"))
assertFalse(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
assertFalse(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.build-info.json"))
assertFalse(tool("cachyos").assetPattern.containsMatchIn("proton-cachyos-11.0-20261005-slr-x86_64.tar.xz"))
}
@Test
fun theTarballAndItsSha512FileArePicked() {
val picked = ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-7.5")))!!
assertEquals("DroidDeck-Proton-11-7.5", picked.tag)
assertEquals("DroidDeck-Proton-11-7.5-aarch64.tar.gz", picked.name)
assertEquals("https://github.com/o/r/releases/download/t/DroidDeck-Proton-11-7.5-aarch64.sha512sum", picked.sha512)
assertEquals(625_775_670L, picked.size)
assertNull(picked.sha256)
}
@Test
fun githubsDigestIsKeptBesideTheSha512File() {
val sum = "ab".repeat(32)
val release = release("GE-Proton11-7", asset("GE-Proton11-7-x86_64.tar.gz"), asset("GE-Proton11-7-aarch64.sha512sum"),
asset("GE-Proton11-7-aarch64.tar.gz", "sha256:$sum"))
val picked = ProtonExtras.pickAsset(tool("ge"), JSONArray().put(release))!!
assertEquals("GE-Proton11-7-aarch64.tar.gz", picked.name)
assertEquals(sum, picked.sha256)
assertTrue(picked.sha512!!.endsWith("GE-Proton11-7-aarch64.sha512sum"))
}
@Test
fun prereleasesDraftsAndReleasesWithoutAnArm64BuildAreSkipped() {
val releases = JSONArray()
.put(droiddeckRelease("11-8", prerelease = true))
.put(release("DroidDeck-Proton-11-7.9", asset("DroidDeck-Proton-11-7.9-aarch64.tar.gz"), draft = true))
.put(release("DroidDeck-Proton-11-7.8", asset("DroidDeck-Proton-11-7.8-x86_64.tar.gz")))
.put(droiddeckRelease("11-7.5"))
assertEquals("DroidDeck-Proton-11-7.5", ProtonExtras.pickAsset(tool("droiddeck"), releases)?.tag)
assertNull(ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-8", prerelease = true))))
}
@Test
fun versionsCompareByTheirNumbers() {
val sorted = listOf("GE-Proton11-10", "GE-Proton10-25", "GE-Proton11-9", "GE-Proton11-1")
.sortedWith { a, b -> ProtonExtras.compareVersions(a, b) }
assertEquals(listOf("GE-Proton10-25", "GE-Proton11-1", "GE-Proton11-9", "GE-Proton11-10"), sorted)
assertTrue(ProtonExtras.compareVersions("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10") < 0)
assertTrue(ProtonExtras.compareVersions("DroidDeck-Proton 11-7.10", "DroidDeck-Proton 11-8") < 0)
assertTrue(ProtonExtras.compareVersions("DroidDeck-Proton 11-7", "DroidDeck-Proton 11-7.1") < 0)
assertTrue(ProtonExtras.compareVersions("cachyos-11.0-20260703-slr", "cachyos-11.0-20261005-slr") < 0)
assertTrue(ProtonExtras.compareVersions("cachyos-10.0-sunset-slr", "cachyos-11.0-20260601-slr") < 0)
assertEquals(listOf(11L, 7L), ProtonExtras.versionKey("GE-Proton11-7-aarch64"))
assertEquals(listOf(11L, 0L, 20261005L), ProtonExtras.versionKey("proton-cachyos-11.0-20261005-slr-arm64"))
assertEquals(listOf(11L, 7L, 5L), ProtonExtras.versionKey("DroidDeck-Proton 11-7.5"))
assertEquals(ProtonExtras.versionKey("DroidDeck-Proton-11-7.5"), ProtonExtras.versionKey("DroidDeck-Proton 11-7.5"))
}
@Test
fun installedBuildsAreFoundByPrefixNewestLast() {
val tools = temp.newFolder("compatibilitytools.d")
for (name in listOf("GE-Proton11-10", "GE-Proton11-9", "DroidDeck-Proton 11-7.10", "DroidDeck-Proton 11-7.5",
"droiddeck-proton-arm64", "droiddeck-proton-11-arm64", "proton-cachyos-11.0-20261005-slr-arm64")) installTool(tools, name)
File(tools, "DroidDeck-Proton 11-6").mkdirs()
assertEquals(listOf("GE-Proton11-9", "GE-Proton11-10"), ProtonExtras.installedIn(tools, tool("ge")))
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedIn(tools, tool("droiddeck")))
assertEquals(listOf("proton-cachyos-11.0-20261005-slr-arm64"), ProtonExtras.installedIn(tools, tool("cachyos")))
assertEquals(emptyList<String>(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge")))
}
@Test
fun anUpdateIsANewerReleaseThanTheNewestInstalledBuild() {
assertEquals("DroidDeck-Proton-11-7.6", ProtonExtras.updateFor(listOf("DroidDeck-Proton 11-7.5"), "DroidDeck-Proton-11-7.6"))
assertEquals("DroidDeck-Proton-11-7.10", ProtonExtras.updateFor(listOf("DroidDeck-Proton-11-7.9"), "DroidDeck-Proton-11-7.10"))
assertNull(ProtonExtras.updateFor(listOf("DroidDeck-Proton 11-7.5"), "DroidDeck-Proton-11-7.5"))
assertNull(ProtonExtras.updateFor(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-7.6"), "DroidDeck-Proton-11-7.6"))
assertNull(ProtonExtras.updateFor(listOf("GE-Proton11-10"), "GE-Proton11-9"))
assertNull(ProtonExtras.updateFor(listOf("GE-Proton11-7-aarch64"), "GE-Proton11-7"))
assertEquals("GE-Proton11-10", ProtonExtras.updateFor(listOf("GE-Proton11-7-aarch64", "GE-Proton11-9"), "GE-Proton11-10"))
assertEquals("cachyos-11.0-20261101-slr", ProtonExtras.updateFor(listOf("proton-cachyos-11.0-20261005-slr-arm64"), "cachyos-11.0-20261101-slr"))
assertNull(ProtonExtras.updateFor(listOf("proton-cachyos-11.0-20261005-slr-arm64"), "cachyos-10.0-sunset-slr"))
assertNull(ProtonExtras.updateFor(emptyList(), "GE-Proton11-10"))
assertNull(ProtonExtras.updateFor(listOf("GE-Proton11-7"), null))
}
@Test
fun aRecentCheckIsReusedAndComparedWithTheInstalledBuild() {
val context = RuntimeEnvironment.getApplication()
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
installTool(tools, "DroidDeck-Proton 11-7.5")
installTool(tools, "GE-Proton11-7")
val now = 1_800_000_000_000L
val latest = JSONObject()
.put("ge", JSONObject().put("tag", "GE-Proton11-7").put("at", now - 60_000))
.put("cachyos", JSONObject().put("tag", "cachyos-11.0-20261005-slr").put("at", now - 60_000))
.put("droiddeck", JSONObject().put("tag", "DroidDeck-Proton-11-7.6").put("at", now - ProtonExtras.CHECK_EVERY_MS + 60_000))
File(context.filesDir, "proton-latest.json").writeText(latest.toString())
assertFalse(ProtonExtras.checkLatest(context, now = now))
assertEquals("DroidDeck-Proton-11-7.6", ProtonExtras.update(context, tool("droiddeck")))
assertNull(ProtonExtras.update(context, tool("ge")))
assertNull(ProtonExtras.update(context, tool("cachyos")))
assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedTags(context, tool("droiddeck")))
File(context.filesDir, "proton-extras.json").writeText(JSONObject().put("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-7.6").toString())
assertEquals(listOf("DroidDeck-Proton-11-7.6"), ProtonExtras.installedTags(context, tool("droiddeck")))
assertNull(ProtonExtras.update(context, tool("droiddeck")))
}
@Test
fun removingDeletesOneBuildOrEveryOlderOne() {
val context = RuntimeEnvironment.getApplication()
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.6", "DroidDeck-Proton 11-7.10", "GE-Proton11-7")) installTool(tools, name)
ProtonExtras.remove(context, tool("droiddeck"), "DroidDeck-Proton 11-7.6")
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
ProtonExtras.remove(context, tool("droiddeck"), "GE-Proton11-7")
assertTrue(File(tools, "GE-Proton11-7").isDirectory)
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
ProtonExtras.removeOlder(context, tool("droiddeck"))
assertEquals(listOf("DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
assertEquals("DroidDeck-Proton 11-7.10", ProtonExtras.installed(context, tool("droiddeck")))
}
}
@@ -0,0 +1,119 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.content.ContextWrapper
import com.droiddeck.launcher.runtime.BwrapSpawner
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class QuestExperimentalTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
ShadowBuild.setModel("Phone")
ShadowBuild.setDevice("phone")
}
@Test fun otherDevicesKeepTheirSettings() {
for (model in listOf("Phone", "Quest", "Quest Pro")) {
ShadowBuild.setModel(model)
QuestExperimental.initialize(context)
assertEquals(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.gpuDriverMode(context))
assertEquals("", SessionPrefs.androidDriver(context))
assertFalse(SessionPrefs.hdr(context, "steam"))
}
assertFalse(QuestExperimental.supported("Phone", "hollywood", "Other"))
}
@Test fun quest2SelectsA6xxInsteadOfQuest3DriverAndPreservesLaterChoices() {
ShadowBuild.setModel("Quest 2")
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putBoolean("questDefaultsV1", true).commit()
QuestExperimental.initialize(context)
assertEquals(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.gpuDriverMode(context))
assertEquals(QuestExperimental.DRIVER_A6XX, SessionPrefs.androidDriver(context))
assertEquals("", SessionPrefs.linuxDriver(context))
assertTrue(SessionPrefs.hdr(context, "steam"))
assertTrue(QuestExperimental.supported("unknown", "hollywood", "Oculus"))
assertTrue(QuestExperimental.supported("unknown", "hollywood", "Meta"))
assertFalse(QuestExperimental.quest2("Quest 3", "eureka", "Meta"))
SessionPrefs.setAndroidDriver(context, "chosen-a6xx-driver")
QuestExperimental.initialize(context)
assertEquals("chosen-a6xx-driver", SessionPrefs.androidDriver(context))
}
@Test fun questDefaultsSelectBothCompatibilityPathsAndAreAppliedOnlyOnce() {
ShadowBuild.setModel("Quest 3")
val standard = object : ContextWrapper(context) {
override fun getPackageName() = "com.droiddeck.launcher"
}
QuestExperimental.initialize(standard)
assertEquals(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.gpuDriverMode(context))
assertEquals(QuestExperimental.DRIVER, SessionPrefs.androidDriver(context))
assertEquals("", SessionPrefs.linuxDriver(context))
assertTrue(SessionPrefs.hdr(context, "steam"))
assertTrue(context.filesDir.resolve("quest-startup.txt").readText().contains("model=Quest 3"))
SessionPrefs.setAndroidDriver(context, "chosen-driver")
SessionPrefs.setHdr(context, "steam", false)
QuestExperimental.initialize(context)
assertEquals("chosen-driver", SessionPrefs.androidDriver(context))
assertFalse(SessionPrefs.hdr(context, "steam"))
}
@Test fun quest3sIsRecognizedByModelOrDevice() {
assertTrue(QuestExperimental.supported("Quest 3S", "unknown", "Oculus"))
assertTrue(QuestExperimental.supported("unknown", "panther", "Oculus"))
assertTrue(QuestExperimental.supported("unknown", "eureka", "Meta"))
assertFalse(QuestExperimental.supported("Pixel 7", "panther", "Google"))
}
@Test fun autoUsesTheQuestPairWithoutChangingOtherSettings() {
for (model in listOf("Quest 3", "Quest 3S", "Quest 2")) {
ShadowBuild.setModel(model)
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setAndroidDriver(context, "downloaded-display")
SessionPrefs.setLinuxDriver(context, "downloaded-linux")
SessionPrefs.setHdr(context, "steam", false)
assertTrue(QuestExperimental.applyAutoDrivers(context))
assertEquals(if (model == "Quest 2") QuestExperimental.DRIVER_A6XX else QuestExperimental.DRIVER,
SessionPrefs.androidDriver(context))
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.gpuDriverMode(context))
assertFalse(SessionPrefs.hdr(context, "steam"))
}
}
@Test fun autoLeavesManualQuestChoicesAndOtherDevicesAlone() {
for ((model, mode) in listOf("Quest 3" to SessionPrefs.GPU_DRIVERS_MANUAL,
"Phone" to SessionPrefs.GPU_DRIVERS_AUTO)) {
ShadowBuild.setModel(model)
SessionPrefs.setGpuDriverMode(context, mode)
SessionPrefs.setAndroidDriver(context, "chosen-display")
SessionPrefs.setLinuxDriver(context, "chosen-linux")
assertFalse(QuestExperimental.applyAutoDrivers(context))
assertEquals("chosen-display", SessionPrefs.androidDriver(context))
assertEquals("chosen-linux", SessionPrefs.linuxDriver(context))
}
}
@Test fun installedPackagesUseSeparateSandboxSockets() {
val packages = listOf("com.droiddeck.launcher", "com.tencent.ig",
"com.antutu.benchmark.full", "com.ludashi.benchmark")
val sockets = packages.map { name ->
val variant = object : ContextWrapper(context) {
override fun getPackageName() = name
}
BwrapSpawner.socket(variant).also { assertEquals("$name.bwrap", it) }
}
assertEquals(packages.size, sockets.toSet().size)
}
}
@@ -8,6 +8,7 @@ import android.os.Looper
import android.os.Vibrator
import android.os.VibratorManager
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.JoyCon
import com.droiddeck.launcher.input.PadBridge
import java.io.IOException
import org.junit.After
@@ -35,7 +36,7 @@ class RumbleComponentTest {
vibrator = if (Build.VERSION.SDK_INT >= 31) context.getSystemService(VibratorManager::class.java).defaultVibrator
else context.getSystemService(Vibrator::class.java)
shadowOf(vibrator).setHasVibrator(true)
rumble = RumbleComponent().also { it.attach(context); it.start() }
rumble = RumbleComponent().also { it.motorLooper = Looper.getMainLooper(); it.attach(context); it.start() }
}
@After fun stopListener() { rumble.stop() }
@@ -78,24 +79,73 @@ class RumbleComponentTest {
assertFalse("the phone buzzed as well", shadowOf(vibrator).isVibrating)
}
@Test fun repeatedAndRapidEffectsDoNotRestartTheMotors() {
@Test fun repeatedAndRapidEffectsDoNotRestartTheMotorsButTheLatestStillLands() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
repeat(5) { effect(strong = 40000, weak = 1000) }
effect(strong = 20000, weak = 1000)
effect(strong = 30000, weak = 1000)
assertEquals("a stream of packets restarted the motor each time", 1, pad.played.size)
shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofMillis(RumbleComponent.MIN_GAP_MS))
effect(strong = 40000, weak = 1000)
assertEquals("the same strength, still playing, was started again", 1, pad.played.size)
effect(strong = 20000, weak = 1000)
assertEquals(Triple(20000, 1000, 5000L), pad.played.last())
idle(RumbleComponent.MIN_GAP_MS)
assertEquals("the last change inside the gap was lost",
listOf(Triple(40000, 1000, 5000L), Triple(30000, 1000, 5000L)), pad.played)
effect(strong = 30000, weak = 1000)
assertEquals("the same strength, still playing, was started again", 2, pad.played.size)
effect(strong = 0, weak = 0)
assertFalse(pad.vibrating)
effect(strong = 20000, weak = 1000)
assertTrue("an effect right after a stop was dropped", pad.vibrating)
}
@Test fun aHeldEffectKeepsTheMotorsRunningUntilTheGameStopsIt() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS)
assertEquals(listOf(Triple(40000, 20000, RumbleComponent.HOLD_EFFECT_MS)), pad.played)
idle(RumbleComponent.KEEPALIVE_MS * 4 + 100)
assertEquals("the held effect was not re-armed before it ran out", 5, pad.played.size)
effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS)
assertEquals("a repeat of the held strength restarted the motors", 5, pad.played.size)
effect(strong = 0, weak = 0)
assertFalse(pad.vibrating)
idle(RumbleComponent.KEEPALIVE_MS * 4 + 100)
assertEquals("the keepalive restarted the motors after a stop", 5, pad.played.size)
assertFalse(pad.vibrating)
}
@Test fun aHeldEffectFollowsTheGamesNewStrength() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect(strong = 40000, weak = 0, ms = RumbleComponent.HOLD_MS)
effect(strong = 10000, weak = 0, ms = RumbleComponent.HOLD_MS)
idle(RumbleComponent.KEEPALIVE_MS * 2)
assertTrue(pad.played.drop(1).isNotEmpty())
assertTrue("the keepalive replayed an old strength", pad.played.drop(1).all { it.first == 10000 })
}
@Test fun aTimedEffectIsNotRearmed() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect(strong = 40000, weak = 0, ms = 300)
idle(RumbleComponent.KEEPALIVE_MS * 3)
assertEquals(listOf(Triple(40000, 0, 300L)), pad.played)
}
@Test fun disablingStopsTheKeepalive() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect(ms = RumbleComponent.HOLD_MS)
ControllerPrefs.setRumble(context, false)
idle(RumbleComponent.KEEPALIVE_MS * 3)
assertEquals(1, pad.played.size)
assertFalse(pad.vibrating)
}
@Test fun aControllerWithoutMotorsFallsBackToThePhone() {
rumble.controllerMotors = { null }
activeController(PAD_ID)
@@ -153,8 +203,53 @@ class RumbleComponentTest {
assertFalse(shadowOf(vibrator).isVibrating)
}
@Test fun eachVrHandRumblesItsOwnJoyConAndNeverThePhone() {
val left = FakeMotors()
val right = FakeMotors()
rumble.controllerMotors = { id -> if (id == PAD_ID) left else if (id == SECOND_PAD_ID) right else null }
JoyCon.setVrDevices(this, intArrayOf(PAD_ID, SECOND_PAD_ID))
effect(strong = 30000, weak = 30000, slot = JoyCon.VR_RUMBLE_SLOT + JoyCon.LEFT)
effect(strong = 20000, weak = 20000, slot = JoyCon.VR_RUMBLE_SLOT + JoyCon.RIGHT)
assertEquals(listOf(Triple(30000, 30000, 5000L)), left.played)
assertEquals(listOf(Triple(20000, 20000, 5000L)), right.played)
JoyCon.clearVrDevices(this)
effect(strong = 10000, weak = 10000, slot = JoyCon.VR_RUMBLE_SLOT + JoyCon.LEFT)
assertFalse("the hand kept rumbling after SteamVR let it go", left.vibrating)
assertFalse(shadowOf(vibrator).isVibrating)
}
@Test fun aJoyConPairSplitsTheMotorsLikeOneController() {
val left = FakeMotors()
val right = FakeMotors()
rumble.controllerMotors = { id -> if (id == PAD_ID) left else if (id == SECOND_PAD_ID) right else null }
activeController(SECOND_PAD_ID)
joyCons(0, PAD_ID, SECOND_PAD_ID)
effect(strong = 40000, weak = 1000)
assertEquals(listOf(Triple(40000, 0, 5000L)), left.played)
assertEquals(listOf(Triple(0, 1000, 5000L)), right.played)
shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofMillis(RumbleComponent.MIN_GAP_MS))
effect(strong = 20000, weak = 0)
assertTrue(left.vibrating)
assertFalse(right.vibrating)
joyCons(0, PadBridge.NO_CONTROLLER, PadBridge.NO_CONTROLLER)
effect(strong = 10000, weak = 10000)
assertEquals("a lone Joy-Con missed the effect", Triple(10000, 10000, 5000L), right.played.last())
assertFalse("the departed Joy-Con kept rumbling", left.vibrating)
assertFalse(shadowOf(vibrator).isVibrating)
}
@After fun clearActiveController() {
for (slot in 0 until PadBridge.SLOTS) activeController(PadBridge.NO_CONTROLLER, slot)
for (slot in 0 until PadBridge.SLOTS) {
activeController(PadBridge.NO_CONTROLLER, slot)
joyCons(slot, PadBridge.NO_CONTROLLER, PadBridge.NO_CONTROLLER)
}
JoyCon.clearVrDevices(this)
}
private fun joyCons(slot: Int, left: Int, right: Int) {
val pairs = PadBridge::class.java.getDeclaredField("slotJoyCons").apply { isAccessible = true }.get(null)
(pairs as java.util.concurrent.atomic.AtomicIntegerArray).set(slot * 2 + JoyCon.LEFT, left)
pairs.set(slot * 2 + JoyCon.RIGHT, right)
}
private fun activeController(id: Int, slot: Int = 0) {
@@ -163,13 +258,14 @@ class RumbleComponentTest {
(slots as java.util.concurrent.atomic.AtomicIntegerArray).set(slot, id)
}
private fun effect(strong: Int = 65535, weak: Int = 65535, slot: Int = 0) {
// Inject a decoded force-feedback packet; transport is outside these tests.
private fun effect(strong: Int = 65535, weak: Int = 65535, slot: Int = 0, ms: Int = 5000) {
val int = Int::class.javaPrimitiveType
RumbleComponent::class.java.getDeclaredMethod("buzz", int, int, int, int)
.apply { isAccessible = true }.invoke(rumble, strong, weak, 5000, slot)
.apply { isAccessible = true }.invoke(rumble, strong, weak, ms, slot)
}
private fun idle(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofMillis(ms))
private class FakeMotors : RumbleComponent.Motors {
override val name = "fake pad"
val played = mutableListOf<Triple<Int, Int, Long>>()
@@ -10,6 +10,47 @@ import org.junit.rules.TemporaryFolder
class SecondaryLibraryTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun directContentKeepsTheConfiguredLibrarysPrivateDirectories() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("shared")
val content = tmp.newFolder("direct")
val private = SecondaryLibrary.privateRoot(files, library)
val binds = SecondaryLibrary.binds(files, library, listOf("/mnt/droiddeck-sd"), content)
assertEquals("${content.path}:/mnt/droiddeck-sd", binds.first())
assertTrue(binds.contains("$private/steamapps/compatdata:/mnt/droiddeck-sd/steamapps/compatdata"))
assertFalse(SecondaryLibrary.privateRoot(files, content).exists())
}
@Test fun aWritableAliasIsSelectedAndItsProbeIsRemoved() {
val library = tmp.newFolder("shared")
val candidate = File(tmp.root, "direct")
Files.createSymbolicLink(candidate.toPath(), library.toPath())
assertEquals(candidate, SecondaryLibrary.verifiedAlias(library, candidate))
assertTrue(library.listFiles()!!.isEmpty())
}
@Test fun aDeniedAliasFallsBackBeforeCreatingAProbe() {
val library = tmp.newFolder("shared")
val candidate = tmp.newFolder("denied")
assertEquals(library, SecondaryLibrary.verifiedAlias(library, candidate) { false })
assertTrue(candidate.listFiles()!!.isEmpty())
assertTrue(library.listFiles()!!.isEmpty())
}
@Test fun anUnrelatedOrMissingDirectoryCannotReplaceTheLibrary() {
val library = tmp.newFolder("shared")
val candidate = tmp.newFolder("other")
assertEquals(library, SecondaryLibrary.verifiedAlias(library, candidate))
assertTrue(candidate.listFiles()!!.isEmpty())
assertTrue(library.listFiles()!!.isEmpty())
assertEquals(library, SecondaryLibrary.verifiedAlias(library, File(tmp.root, "missing")))
}
@Test fun aNonStorageLibraryKeepsItsConfiguredPath() {
val library = tmp.newFolder("games")
assertSame(library, SecondaryLibrary.contentPath(library))
}
@Test fun gamesStaySharedButPrefixesAndNativeDownloadsArePrivate() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("card")
@@ -0,0 +1,141 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.frontend.Library
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
class SelectedGameProfileTest {
private val proton = ComponentsManager.Proton("p1", "Proton 10", File("p1"), "/p1", "10", true)
private val snapshot = ComponentsManager.Snapshot(
protons = listOf(
ComponentsManager.ProtonView(
proton = proton,
components = mapOf(
"fex" to component("FEX General"),
"dxvk" to component("DXVK General"),
"vkd3d" to component("VKD3D General"),
),
originals = emptyList(),
inUseByGame = false,
),
),
packages = listOf(ComponentsManager.Package("dxvk.wcp", "dxvk", "DXVK Game", "", 1)),
)
private val game = Library.SteamGame(3180310, "Billies Wheelie", null, "internal")
@Test fun inheritedValuesUseGeneralProfile() {
val profile = resolve()
assertEquals("Billies Wheelie", profile!!.name)
assertEquals("PERFORMANCE_TSO", profile.fexPreset.value)
assertTrue(profile.fexPreset.inherited)
assertEquals("Proton 10", profile.proton.value)
assertTrue(profile.proton.inherited)
assertEquals("p1", profile.protonId)
assertEquals("DXVK General", profile.components.getValue("dxvk").value)
assertTrue(profile.components.getValue("dxvk").inherited)
assertEquals(emptyMap<String, String>(), profile.componentFiles)
assertEquals(0, profile.environmentOverrides)
assertEquals(emptyList<String>(), profile.windowsComponentNames)
assertFalse(profile.hasOverrides)
}
@Test fun explicitValuesOverrideGeneralProfile() {
val preset = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), game.profileKey, "STABILITY")
val environment = preset.withEntries(game.profileKey, preset.entries(game.profileKey) + ("PROTON_LOG" to "1"))
val profile = resolve(
environment = environment,
gameChoice = ProtonDefault.GameChoice(true, "p1"),
gameComponents = mapOf("dxvk" to "dxvk.wcp"),
)
assertEquals("STABILITY", profile!!.fexPreset.value)
assertFalse(profile.fexPreset.inherited)
assertFalse(profile.proton.inherited)
assertEquals("DXVK Game", profile.components.getValue("dxvk").value)
assertFalse(profile.components.getValue("dxvk").inherited)
assertEquals("dxvk.wcp", profile.componentFiles.getValue("dxvk"))
assertEquals(1, profile.environmentOverrides)
assertTrue(profile.hasOverrides)
}
@Test fun windowsComponentsMakeProfileCustom() {
val profile = resolve(gameWindowsComponents = listOf("oalinst_dll", "vcredist2010_dll"))
assertEquals(listOf("OpenAL", "Visual C++ 2010"), profile!!.windowsComponentNames)
assertTrue(profile.hasOverrides)
}
@Test fun startWithoutSteamIsListedByNameAndMakesProfileCustom() {
val environment = GameEnvironment.withGameNoSteam(GameEnvironment.Config(), game.profileKey, true)
val profile = resolve(environment = environment)
assertTrue(profile!!.startWithoutSteam)
assertEquals(0, profile.environmentOverrides)
assertTrue(profile.hasOverrides)
val off = GameEnvironment.withGameNoSteam(environment, game.profileKey, false)
assertFalse(resolve(environment = off)!!.startWithoutSteam)
assertEquals(emptyMap<String, Map<String, String?>>(), off.games)
}
@Test fun unknownSelectedAppIsIgnored() {
assertNull(resolve(selectedAppId = 42))
}
@Test fun switchingProfilesResolvesEachGamesFexPresetWithoutChangingSettings() {
val other = Library.SteamGame(42, "Other game", null, "internal")
val games = listOf(game, other)
val environment = GameEnvironment.withGameFexPreset(
GameEnvironment.Config(), game.profileKey, "STABILITY",
)
assertEquals(ProfileValue("STABILITY", false),
resolve(games = games, environment = environment)!!.fexPreset)
assertEquals(ProfileValue("PERFORMANCE_TSO", true),
resolve(selectedAppId = 42, games = games, environment = environment)!!.fexPreset)
assertEquals(ProfileValue("STABILITY", false),
resolve(games = games, environment = environment)!!.fexPreset)
assertNull(GameEnvironment.gameFexPreset(environment, other.profileKey))
}
@Test fun customAndExplicitDefaultFexPresetsAreNotShownAsInherited() {
val custom = GameEnvironment.Config(
games = mapOf(game.profileKey to mapOf("FEX_TSOENABLED" to "0")),
)
assertEquals(ProfileValue(GameEnvironment.CUSTOM_FEX_PRESET, false),
resolve(environment = custom)!!.fexPreset)
val defaults = GameEnvironment.withGameFexPreset(custom, game.profileKey, "")
assertEquals(ProfileValue("", false), resolve(environment = defaults)!!.fexPreset)
val inherited = GameEnvironment.withGameFexPreset(defaults, game.profileKey, null)
assertEquals(ProfileValue("PERFORMANCE_TSO", true), resolve(environment = inherited)!!.fexPreset)
}
private fun resolve(
selectedAppId: Long = 3180310,
games: List<Library.SteamGame> = listOf(game),
environment: GameEnvironment.Config = GameEnvironment.Config(),
gameChoice: ProtonDefault.GameChoice? = null,
gameComponents: Map<String, String> = emptyMap(),
gameWindowsComponents: List<String> = emptyList(),
) = SelectedGameProfile.resolve(
selectedAppId = selectedAppId,
games = games,
generalFexPreset = "PERFORMANCE_TSO",
environment = environment,
snapshot = snapshot,
generalProtonId = "p1",
gameProtonChoice = gameChoice,
gameProtonId = "p1",
gameComponents = gameComponents,
gameWindowsComponents = gameWindowsComponents,
)
private fun component(label: String) =
ComponentsManager.Component(label, "", "Changed outside Components", label, null, null)
}
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SessionAchievementGameTest {
private val installed = setOf(10L, 20L)
@Test fun exitingGameCannotRemainSelectedWithoutItsWindow() {
assertNull(SessionAchievementGame.activeAppId(10, listOf(769), installed))
}
@Test fun steamOverlayKeepsTheRunningGameSelected() {
assertEquals(10L, SessionAchievementGame.activeAppId(769, listOf(769, 10), installed))
}
@Test fun anotherForegroundAppCannotBorrowABackgroundGamesAchievements() {
assertNull(SessionAchievementGame.activeAppId(30, listOf(30, 10), installed))
}
@Test fun ambiguousBackgroundGamesDoNotPickAnArbitraryGame() {
assertNull(SessionAchievementGame.activeAppId(769, listOf(769, 10, 20), installed))
}
@Test fun theForegroundGameWinsWhenSeveralGamesAreRunning() {
assertEquals(20L, SessionAchievementGame.activeAppId(20, listOf(769, 10, 20), installed))
}
}
@@ -0,0 +1,20 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class SessionClientRecordTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun aSessionFolderKeepsTheClientItRan() {
val dir = tmp.newFolder("2026-10-18-01-steam")
assertNull(SessionArtifacts.recordedClient(dir))
SessionArtifacts.recordClient(dir, "x86_64")
assertEquals("x86_64", SessionArtifacts.recordedClient(dir))
java.io.File(dir, "steam-client.txt").writeText("something else\n")
assertNull(SessionArtifacts.recordedClient(dir))
}
}
@@ -12,16 +12,12 @@ class SessionDisplayTest {
}
@Test fun heightPresetsKeepThePanelShapeWithASixteenByNineFloor() {
// 20:9 phone: edge to edge, no bars for the client's interface.
assertEquals(1600 to 720, SessionDisplay.resolveChoice(2400 to 1080, SessionDisplay.DEFAULT_RESOLUTION))
assertEquals(1608 to 720, SessionDisplay.resolveChoice(2412 to 1080, "720p"))
// 1440p phone: bounded by the preset height, not the panel.
assertEquals(1560 to 720, SessionDisplay.resolveChoice(3120 to 1440, "720p"))
assertEquals(2340 to 1080, SessionDisplay.resolveChoice(3120 to 1440, "1080p"))
// Foldable inner panel and 4:3 handhelds: never narrower than 16:9.
assertEquals(1280 to 720, SessionDisplay.resolveChoice(2208 to 1840, "720p"))
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1440 to 1080, "720p"))
// Never taller than the panel.
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, "1080p"))
}
@@ -39,10 +35,8 @@ class SessionDisplayTest {
}
@Test fun unfoldedControlsKeepTheGameSixteenByNineAcrossTheWidth() {
// Fold inner screen held as a tablet, and upright: 16:9 either way, the controls the rest.
assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848))
assertEquals(1038, SessionDisplay.unfoldedGameHeight(1848, 2448))
// A window near 16:9 itself still leaves the controls a fifth of it.
assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080))
}
@@ -27,7 +27,6 @@ class SessionLogShareTest {
z.entries().toList().associate { it.name.substringAfter('/') to z.getInputStream(it).bufferedReader().readText() }
}
/** A record as the session's ending writes it, listing [files] as they stand now. */
private fun record(folder: File, vararg files: String, rules: Int = LogRedactor.RULES_VERSION) {
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).writeText(
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
@@ -35,8 +34,6 @@ class SessionLogShareTest {
@Test fun aRecordedUnchangedFileIsScrubbedAgainOnTheWayIntoTheZip() {
val folder = tmp.newFolder("2026-10-06-01-steam")
// A file the ending recorded as scrubbed still gets the share's final pass: the record
// may predate a rule, and a zip is the one way a log leaves the device.
File(folder, "session.log").writeText("$secret\n")
record(folder, "session.log")
assertFalse(zip(folder).getValue("session.log").contains(leaked))
@@ -50,7 +47,6 @@ class SessionLogShareTest {
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
File(folder, ".hidden.txt").writeText("$secret\n")
record(folder, "app.log", "session.log")
// Appended to after the ending (the app's log capture), and touched with an older time.
File(folder, "app.log").appendText("$secret\n")
File(folder, "session.log").apply { writeText("$secret\n".padEnd(3, ' ')); setLastModified(1_000L) }
File(folder, "events.jsonl").writeText("$secret\n")
@@ -109,7 +105,7 @@ class SessionLogShareTest {
@Test fun aFileThatCouldNotBeScrubbedLeavesTheFolderUnrecorded() {
val folder = tmp.newFolder("2026-10-06-06-steam")
File(folder, "session.log").writeText("$secret\n")
// A folder the scrubbed copy cannot be written into: the scrub fails, the original stays.
org.junit.Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows"))
folder.setWritable(false)
try {
SessionArtifacts.scrubAndMark(folder)
@@ -2,6 +2,9 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipFile
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -12,7 +15,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A shared zip is scrubbed on the way in, whatever the files on disk still hold. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SessionLogShareZipTest {
@@ -21,7 +23,6 @@ class SessionLogShareZipTest {
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
// Written raw, as a file from before a rule existed would be.
File(session, "session.log").writeText(
"fetch https://gog-cdn-fastly.gog.com/token=nva=1791500000~dirs=/x~token=0a1b2c3d4e5f/content-system/v2/store/1/ab/cd/f\n" +
"fetch https://epicgames-download1.akamaized.net/Builds/Org/a/ChunksV4/12/ABCD.chunk?__token__=exp=1~hmac=deadbeefcafe\n" +
@@ -29,18 +30,19 @@ class SessionLogShareZipTest {
"Authorization: Bearer abc.def.ghi\n" +
"kept: EResult 5, app 1086940, steamapps/common/Game\n"
)
File(logs, "stores").apply { mkdirs() }.resolve("stores-2026-10-08.log").writeText("epic: f_token=zzzzzzzz12 window 32\n")
// StoreLogFiles.prune, started by App.onCreate, deletes a stores log named for a day over a week old.
val storesLog = "stores-" + SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date()) + ".log"
File(logs, "stores").apply { mkdirs() }.resolve(storesLog).writeText("epic: f_token=zzzzzzzz12 window 32\n")
File(logs, SessionPaths.TOOLS_DIR).apply { mkdirs() }.resolve("flatpak-install.log").writeText("== install\nCookie: steamLoginSecure=76561198000000000%7C%7Ceyabc\n")
val zip = SessionLogShare.zipFolder(app, session)!!
assertTrue(zip.path.startsWith(File(app.cacheDir, "share").path))
val text = ZipFile(zip).use { z -> z.entries().toList().associate { e -> e.name to z.getInputStream(e).bufferedReader().readText() } }
assertTrue(text.keys.containsAll(listOf("2026-10-08-01-steam/session.log", "stores/stores-2026-10-08.log", "tools/flatpak-install.log")))
assertTrue(text.keys.containsAll(listOf("2026-10-08-01-steam/session.log", "stores/$storesLog", "tools/flatpak-install.log")))
val all = text.values.joinToString("\n")
for (secret in listOf("0a1b2c3d4e5f", "deadbeefcafe", "abcdef123456", "someone@example.com", "AUTHCODE123", "abc.def.ghi", "zzzzzzzz12", "eyabc")) {
assertFalse("$secret survived", all.contains(secret))
}
// What makes a log worth reading stays.
assertTrue(all.contains("kept: EResult 5, app 1086940, steamapps/common/Game"))
assertTrue(all.contains("https://gog-cdn-fastly.gog.com/"))
@@ -53,9 +55,6 @@ class SessionLogShareZipTest {
assertEquals(line, com.droiddeck.launcher.core.LogRedactor.redactForShare(line))
}
// Folders an earlier build scrubbed and marked under older rules, their copied Steam UI log
// still naming the account: one app start (the move out of Download/, then the pass over
// older folders) leaves every one scrubbed on disk under the current rules.
private fun olderFolder(parent: File, name: String, marker: String = ".scrubbed-2"): File {
val dir = File(parent, name).apply { mkdirs() }
File(dir, marker).writeText("scrubbed earlier\n")
@@ -91,12 +90,10 @@ class SessionLogShareZipTest {
val legacy = LinuxRuntime.legacyLogDir().apply { mkdirs() }
val names = (1..9).map { "2026-10-0${it}-01-steam" }
names.forEachIndexed { i, name ->
// Old markers of every kind an earlier build left, one even claiming the current rules.
olderFolder(legacy, name, marker = listOf(".scrubbed-2", ".scrubbed-1", ".scrubbed-r${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}")[i % 3])
}
File(legacy, "Saves").apply { mkdirs() }.resolve("keep.txt").writeText("save\n")
// What MainActivity runs at start.
LogMigration.run(app)
SessionArtifacts.scrubOlder(app)
@@ -0,0 +1,28 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class SessionVisibilityTest {
@Test fun xrVisibilitySurvivesPanelHandoffAndPanelScreenState() {
for (panelVisible in listOf(false, true)) {
for (screenOn in listOf(false, true)) {
assertTrue(sessionHasVisibleSurface(panelVisible, screenOn, true))
}
}
}
@Test fun normalPanelStillRequiresAnInteractiveScreen() {
assertTrue(sessionHasVisibleSurface(true, true, false))
assertFalse(sessionHasVisibleSurface(false, true, false))
assertFalse(sessionHasVisibleSurface(true, false, false))
assertFalse(sessionHasVisibleSurface(false, false, false))
}
@Test fun losingXrVisibilityReturnsToNormalSuspendRules() {
assertTrue(sessionHasVisibleSurface(false, false, true))
assertFalse(sessionHasVisibleSurface(false, false, false))
assertTrue(sessionHasVisibleSurface(true, true, false))
}
}
@@ -0,0 +1,96 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.input.ControllerPrefs
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 SettingsResetTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun prefs(name: String) = app.getSharedPreferences(name, Context.MODE_PRIVATE)
private val session get() = prefs("session")
@Before fun clear() {
listOf("session", "controller", "app-ui", "frame_gen", "steam_touch", "agent").forEach {
prefs(it).edit().clear().commit()
}
}
@Test fun settingsGoBackToTheirDefaults() {
SessionPrefs.setTheme(app, "ocean")
SessionPrefs.setNoXalia(app, false)
SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30)
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
ControllerPrefs.setOpacity(app, 40)
AppUiPrefs.setScale(app, 150)
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_WINFG, 3))
prefs("steam_touch").edit().putBoolean("gyro", false).commit()
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
assertEquals("graphite", SessionPrefs.theme(app))
assertTrue(SessionPrefs.noXalia(app))
assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(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 libraryAndRecordsAreKept() {
val folder = "/storage/emulated/0/Games/Foo"
SessionPrefs.setAddedGameName(app, folder, "Foo")
SessionPrefs.setAddedGameExe(app, folder, "$folder/foo.exe")
SessionPrefs.addedGameAppId(app, folder, 1234L)
SessionPrefs.setAddedGameRemoved(app, "/storage/emulated/0/Games/Bar", true)
SessionPrefs.setGamesFoldersMigrated(app)
SessionPrefs.setGpuAutoInstalled(app, setOf("turnip-a"))
SessionPrefs.setRomsDir(app, "/storage/emulated/0/ROMs")
SessionPrefs.setGameStorage(app, "/storage/ABCD-1234", "SD Card")
SessionPrefs.setMicAsked(app)
prefs("steam_touch").edit().putString("copiedLayout", "a:1,2").commit()
SettingsReset.resetAll(app, gameProfiles = false)
assertEquals("Foo", SessionPrefs.addedGameName(app, folder))
assertEquals("$folder/foo.exe", SessionPrefs.addedGameExe(app, folder))
assertEquals(1234L, SessionPrefs.addedGameStoredAppId(app, folder))
assertEquals(listOf("/storage/emulated/0/Games/Bar"), SessionPrefs.removedAddedGames(app))
assertTrue(SessionPrefs.gamesFoldersMigrated(app))
assertEquals(setOf("turnip-a"), SessionPrefs.gpuAutoInstalled(app))
assertEquals("/storage/emulated/0/ROMs", SessionPrefs.romsDir(app))
assertEquals("/storage/ABCD-1234", SessionPrefs.gameStorage(app))
assertTrue(SessionPrefs.micAsked(app))
assertEquals("a:1,2", prefs("steam_touch").getString("copiedLayout", null))
}
@Test fun gameTextureFilteringIsKeptUnlessGameProfilesAreReset() {
session.edit().putString("gameTextureFiltering", """{"440":{"anisotropy":16}}""").commit()
SettingsReset.resetAll(app, gameProfiles = false)
assertEquals(16, SessionPrefs.gameTextureFiltering(app, "440").anisotropy)
SettingsReset.resetAll(app, gameProfiles = true)
assertTrue(SessionPrefs.gameTextureFiltering(app).isEmpty())
}
@Test fun perModeKeysAreSettings() {
listOf("resolutionCap.steam", "displayResolution.desktop", "customRes.steam", "hdr.steam", "fpsLimit.desktop", "suspendPolicy.steam")
.forEach { assertTrue(it, SettingsReset.isSessionSetting(it)) }
listOf("addedName:/x", "addedAppId:/x", "gpuAutoInstalled", "romsDir", "gameStorage", "micAsked", "gameTextureFiltering")
.forEach { assertFalse(it, SettingsReset.isSessionSetting(it)) }
}
}
@@ -24,6 +24,21 @@ class SteamDownloadMonitorTest {
}
}
@Test fun followsTheX8664ClientsOwnLibrary() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val steam = File(root, "root/.droiddeck-x64/.local/share/Steam")
val manifest = manifest(steam, "49520", downloaded = 10, total = 100, flags = 6)
val monitor = SteamDownloadMonitor()
assertFalse(monitor.poll(root, now = 1_000L))
manifest.writeText(appManifest(downloaded = 20, total = 100, flags = 6))
assertTrue(monitor.poll(root, now = 3_000L))
} finally {
root.deleteRecursively()
}
}
@Test fun findsDownloadsInAdditionalSteamLibraries() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
@@ -67,6 +82,51 @@ class SteamDownloadMonitorTest {
}
}
@Test fun theOtherClientsLogIsReadFromItsStart() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
File(root, "root/.local/share/Steam/logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText("[2026-10-06 14:00:00] Client version: 1\n" + "[2026-10-06 14:00:01] nothing to download\n".repeat(20))
setLastModified(10_000L)
}
val monitor = SteamDownloadMonitor()
assertFalse(monitor.poll(root, now = 1_000L))
File(root, "root/.droiddeck-x64/.local/share/Steam/logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText("[2026-10-06 14:44:17] AppID 44 App update changed : Running Update,Downloading,Staging,\n" +
"[2026-10-06 14:44:18] Current download rate: 0.000 Mbps\n".repeat(30))
setLastModified(20_000L)
}
assertTrue(monitor.poll(root, now = 2_000L))
} finally {
root.deleteRecursively()
}
}
@Test fun theRunningClientsLogIsFollowedWhenTheOtherOneIsNewer() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
File(root, "root/.local/share/Steam/logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText("[2026-10-06 14:44:17] AppID 44 App update changed : Running Update,Downloading,Staging,\n")
setLastModified(10_000L)
}
File(root, "root/.droiddeck-x64/.local/share/Steam/logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText("[2026-10-06 14:00:00] Client version: 1\n")
setLastModified(20_000L)
}
val monitor = SteamDownloadMonitor()
assertTrue(monitor.poll(root, now = 1_000L, client = "arm64"))
assertTrue(monitor.poll(root, now = 2_000L, client = "arm64"))
assertFalse(SteamDownloadMonitor().poll(root, now = 1_000L, client = "x86_64"))
} finally {
root.deleteRecursively()
}
}
@Test fun receivedTrafficBridgesSteamRateLines() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
@@ -79,13 +139,11 @@ class SteamDownloadMonitorTest {
var now = 1_000L
assertTrue(monitor.poll(root, now, received))
// Five minutes of a download Steam no longer logs, at 4 MB/s.
while (now < 300_000L) {
now += 2_000L
received += 8_000_000L
assertTrue(monitor.poll(root, now, received))
}
// Traffic stops: the session may suspend once the grace runs out.
assertTrue(monitor.poll(root, now + 90_000L, received))
assertFalse(monitor.poll(root, now + 92_001L, received))
@@ -18,6 +18,18 @@ class SteamLanguageTest {
assertEquals("tchinese", steam("zh-HK"))
}
@Test fun everyAppLanguageButHindiHasSteamsOwn() {
com.droiddeck.launcher.core.AppLanguage.supported.forEach {
val steam = steam(it)
assertTrue("$it -> $steam", (steam == "english") == (it == "en" || it == "hi"))
}
assertEquals("brazilian", steam("pt-BR"))
assertEquals("portuguese", steam("pt-PT"))
assertEquals("latam", steam("es-419"))
assertEquals("indonesian", steam("id"))
assertEquals("malay", steam("ms"))
}
@Test fun chineseFollowsTheScriptBeforeTheRegion() {
assertEquals("tchinese", steam("zh-Hant-CN"))
assertEquals("schinese", steam("zh-Hans-HK"))
@@ -30,7 +42,6 @@ class SteamLanguageTest {
assertEquals("latam", steam("es-MX"))
assertEquals("latam", steam("es-419"))
assertEquals("spanish", steam("es-ES"))
// The app's Spanish has no region; the system's says where the player is.
assertEquals("latam", steam("es", region = "AR"))
assertEquals("spanish", steam("es", region = "ES"))
}
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
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
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamRepairTest {
private val app get() = RuntimeEnvironment.getApplication()
@Before @After fun idle() {
SessionState.running = false
SessionState.steamClientArch = null
}
private fun marker(home: String) = File(LinuxRuntime.rootDir(app), "root/$home/package/droiddeck-unconfirmed").apply {
parentFile?.mkdirs()
writeText("tracked\nstart\nstart\n")
}
@Test fun aShownClientClearsOnlyItsOwnUnconfirmedStarts() {
val arm = marker(".local/share/Steam")
val x64 = marker(".droiddeck-x64/.local/share/Steam")
SteamRepair.clientShown(app)
assertFalse(arm.exists())
assertTrue(x64.exists())
marker(".local/share/Steam")
SessionPrefs.setSteamClientArch(app, "x86_64")
SteamRepair.clientShown(app)
assertTrue(arm.exists())
assertFalse(x64.exists())
}
}
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.runtime.LinuxRuntime
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.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 TextureFilteringPrefsTest {
private lateinit var context: Context
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
File(context.filesDir, "game-environment.json").delete()
File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json").delete()
}
@Test fun gameChoicesRemainSeparateFromDefaultAndCanInheritAgain() {
SessionPrefs.setTextureAnisotropy(context, 16)
SessionPrefs.setTextureLodBias(context, TextureFiltering.LOD_BIAS_AUTO)
SessionPrefs.setGameTextureAnisotropy(context, "42", 4)
SessionPrefs.setGameTextureLodBias(context, "42", "-0.5")
assertEquals(16, SessionPrefs.textureAnisotropy(context))
assertEquals(TextureFiltering.LOD_BIAS_AUTO, SessionPrefs.textureLodBias(context))
assertEquals(SessionPrefs.GameTextureFiltering(4, "-0.5"), SessionPrefs.gameTextureFiltering(context, "42"))
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, "43"))
SessionPrefs.setGameTextureAnisotropy(context, "42", null)
SessionPrefs.setGameTextureLodBias(context, "42", null)
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, "42"))
assertFalse(SessionPrefs.gameTextureFiltering(context).containsKey("42"))
}
@Test fun publishedDxvkOptionsUseGameOverridesWithoutChangingDefault() {
SessionPrefs.setTextureAnisotropy(context, 16)
SessionPrefs.setGameTextureAnisotropy(context, "42", 0)
SessionPrefs.setGameTextureLodBias(context, "42", TextureFiltering.LOD_BIAS_OFF)
val published = JSONObject(
File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json").readText(),
)
assertTrue(published.getString(GameEnvironmentStore.DXVK_CONFIG).contains("samplerAnisotropy = 16"))
assertEquals("", published.getJSONObject(GameEnvironmentStore.DXVK_CONFIG_GAMES).getString("42"))
assertNull(SessionPrefs.gameTextureFiltering(context, "43").anisotropy)
}
@Test fun clearingGameChoicesPreservesOtherProfiles() {
SessionPrefs.setGameTextureAnisotropy(context, "42", 4)
SessionPrefs.setGameTextureLodBias(context, "42", "-0.5")
SessionPrefs.setGameTextureAnisotropy(context, "43", 8)
SessionPrefs.clearGameTextureFiltering(context, "42")
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, "42"))
assertEquals(8, SessionPrefs.gameTextureFiltering(context, "43").anisotropy)
}
}
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class VacDiagnosticsTest {
@Test fun tailReadsOnlyWhatThisSessionAppended() {
val log = java.io.File.createTempFile("console", ".log")
try {
log.writeText("You are in insecure mode.\nConnected to 1.2.3.4\n")
val armed = log.length()
log.appendText("Connecting to 5.6.7.8\n")
assertEquals(listOf("Connecting to 5.6.7.8", ""), VacDiagnostics.tail(log, armed))
} finally {
log.delete()
}
}
@Test fun theSameGameInTwoLibrariesGetsTwoConsoleNames() {
val a = java.io.File("/lib1/steamapps/common/Team Fortress 2/tf/console.log")
val b = java.io.File("/lib2/steamapps/common/Team Fortress 2/tf/console.log")
val c = java.io.File("/lib1/steamapps/common/Half-Life 2/hl2/console.log")
val names = VacDiagnostics.consoleNames(listOf(a, b, c))
assertEquals("Team Fortress 2-tf", names[0])
assertTrue(names[1].startsWith("Team Fortress 2-tf-") && names[1] != names[0])
assertEquals("Half-Life 2-hl2", names[2])
assertEquals(names, VacDiagnostics.consoleNames(listOf(a, b, c)))
}
@Test fun tailReadsAllOfAReplacedFile() {
val log = java.io.File.createTempFile("console", ".log")
try {
log.writeText("new\n")
assertEquals(listOf("new", ""), VacDiagnostics.tail(log, 1000L))
} finally {
log.delete()
}
}
@Test fun onlyConsoleLogsThisSessionWroteAreReported() {
val log = java.io.File.createTempFile("console", ".log")
try {
log.writeText("Connected to 1.2.3.4\n")
val since = log.lastModified() - 5_000
val armed = mapOf(log.canonicalPath to log.length())
assertFalse(VacDiagnostics.writtenThisSession(log, since, armed))
log.appendText("Connecting to 5.6.7.8\n")
assertTrue(VacDiagnostics.writtenThisSession(log, since, armed))
assertTrue(VacDiagnostics.writtenThisSession(log, since, emptyMap()))
assertFalse(VacDiagnostics.writtenThisSession(log, log.lastModified() + 1_000, emptyMap()))
} finally {
log.delete()
}
}
}
@@ -23,7 +23,6 @@ class WinComponentsSupportTest {
@Test fun windowsInstallerPackagesInstallHere() {
assertEquals(Support.READY, support(component("xna40", step("install_msi", "url" to "$base/xna40.msi"))))
// The catalog names some .msi packages install_exe.
assertEquals(Support.READY, support(component("XLiveRedist",
step("install_exe", "url" to "$base/XLiveRedist.msi", "file_name" to "XLiveRedist1.2.0238.msi"))))
assertEquals(Support.READY, support(component("msxml3", step("delete_dlls", "dest" to "win32"),
@@ -33,12 +32,10 @@ class WinComponentsSupportTest {
}
@Test fun installerWrappersInstallHere() {
// A WiX bundle, a self-extracting cabinet or 7-Zip archive: the packages inside are laid out.
assertEquals(Support.READY, support(component("vcredist2022",
step("install_exe", "url" to "$base/vcredist2022__VC_redist.x86.exe", "file_name" to "VC_redist.x86.exe"),
step("install_exe", "url" to "$base/vcredist2022__VC_redist.x64.exe", "file_name" to "VC_redist.x64.exe"),
step("override_dll", "dll" to "vcruntime140", "type" to "native,builtin"))))
// .NET Framework: "uninstall Wine Mono", the Windows version, the installer, a registry key.
assertEquals(Support.READY, support(component("dotnet40",
step("uninstall", "file_name" to "Wine Mono"), step("set_windows", "version" to "win7"),
step("install_exe", "url" to "https://download.microsoft.com/x/dotNetFx40_Full_x86_x64.exe", "file_name" to "dotNetFx40_Full_x86_x64.exe"),
@@ -48,7 +45,6 @@ class WinComponentsSupportTest {
}
@Test fun nestedCatalogKeysAreRead() {
// A few .NET entries keep url and file_name under "environment".
val nested = WinComponents.Step("install_exe", JSONObject().put("environment", JSONObject()
.put("WINEDLLOVERRIDES", "fusion=b").put("file_name", "ndp48-x86-x64-allos-enu.exe")
.put("url", "https://download.visualstudio.microsoft.com/x/ndp48-x86-x64-allos-enu.exe")))
@@ -67,14 +63,11 @@ class WinComponentsSupportTest {
@Test fun recordedInstallersInstallHere() {
val snapshot = "https://github.com/Droid-Deck/DroidDeck-Components/releases/download/component-snapshots-v1/K-Lite.snapshot.json"
// A setup program with a recording of its result installs from the recording.
val klite = WinComponents.Component("K-Lite", "", "", "ready", emptyList(),
listOf(step("install_exe", "url" to "$base/K-Lite.exe", "file_name" to "K-Lite_1960.exe")), snapshot)
assertEquals(Support.READY, WinComponents.support(klite, mapOf(klite.name to klite)))
// Only a recording on the release counts.
val elsewhere = WinComponents.Component("K-Lite", "", "", "ready", emptyList(), klite.steps, "http://example.com/K-Lite.snapshot.json")
assertEquals(Support.NEEDS_INSTALLER, WinComponents.support(elsewhere, mapOf(elsewhere.name to elsewhere)))
// Its prerequisites still have to be installable.
val sp1 = WinComponents.Component("dotnet20sp1", "", "", "ready", listOf("dotnet20"), emptyList(), snapshot.replace("K-Lite", "dotnet20sp1"))
val base20 = WinComponents.Component("dotnet20", "", "", "ready", emptyList(),
listOf(step("install_exe", "url" to "$base/dotnet20__dotnetfx.exe", "file_name" to "dotnetfx.exe")))
@@ -82,7 +75,6 @@ class WinComponentsSupportTest {
}
@Test fun setupProgramsStillWait() {
// NSIS / InnoSetup installers hold no package to lay out.
assertEquals(Support.NEEDS_INSTALLER, support(component("K-Lite",
step("install_exe", "url" to "$base/K-Lite.exe", "file_name" to "K-Lite_1960.exe"))))
assertEquals(Support.NEEDS_INSTALLER, support(component("plain", step("install_msi", "url" to "http://example.com/a.msi"))))