mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 12:56:06 +00:00
Merge latest upstream main before Controller UI integration
# Conflicts: # app/src/main/java/com/droiddeck/launcher/SessionActivity.kt # app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt # app/src/main/java/com/droiddeck/launcher/input/PadBridge.java # app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt # app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt
This commit is contained in:
commit
ba5876bf6d
360 files changed
+34610
-1088
No files matched your search
@@ -0,0 +1,65 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.os.Bundle
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.installJvmSecureSourceOpener
|
||||
import com.droiddeck.launcher.session.resetSecureSourceOpener
|
||||
import org.json.JSONObject
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], manifest = Config.NONE)
|
||||
class AgentLogExportTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private var previousLogDirectory: File? = null
|
||||
|
||||
@Before fun prepare() {
|
||||
previousLogDirectory = SessionState.logDirectory
|
||||
installJvmSecureSourceOpener()
|
||||
}
|
||||
|
||||
@After fun cleanup() {
|
||||
SessionState.logDirectory = previousLogDirectory
|
||||
resetSecureSourceOpener()
|
||||
}
|
||||
|
||||
@Test fun independentLogRequestsKeepBothExportDirectories() {
|
||||
val session = File(context.cacheDir, "agent-session").apply { mkdirs() }
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
SessionState.logDirectory = session
|
||||
val provider = Robolectric.buildContentProvider(AgentBridgeProvider::class.java).create().get()
|
||||
var firstDir: File? = null
|
||||
var secondDir: File? = null
|
||||
|
||||
try {
|
||||
fun requestLogs() = JSONObject(provider.call("logs", null, Bundle()).getString("json")!!)
|
||||
val first = requestLogs()
|
||||
val second = requestLogs()
|
||||
firstDir = File(first.getString("cleanupDir"))
|
||||
secondDir = File(second.getString("cleanupDir"))
|
||||
val firstZip = File(first.getString("zip"))
|
||||
val secondZip = File(second.getString("zip"))
|
||||
|
||||
assertNotEquals(firstDir, secondDir)
|
||||
assertEquals(firstDir, firstZip.parentFile)
|
||||
assertEquals(secondDir, secondZip.parentFile)
|
||||
assertTrue(firstZip.isFile)
|
||||
assertTrue(secondZip.isFile)
|
||||
} finally {
|
||||
firstDir?.deleteRecursively()
|
||||
secondDir?.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DeviceSupportTest {
|
||||
@Test fun runtimeDownloadAcceptsOnlyRecognizedGraphicsBackends() {
|
||||
assertTrue(DeviceSupport.graphicsAvailable(adreno = true, powerVrReady = false))
|
||||
assertTrue(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = true))
|
||||
// A PowerVR HAL without usable DRM access also reaches this unavailable case.
|
||||
assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false))
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,12 @@ import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class GameEnvironmentTest {
|
||||
@Test fun defaultsIncludeRequestedGraphicsLevelsAndKeepCaching() {
|
||||
@Test fun defaultsDetectGraphicsCapabilitiesAndKeepCaching() {
|
||||
val values = GameEnvironment.defaults("")
|
||||
assertEquals("false", values["MESA_SHADER_CACHE_DISABLE"])
|
||||
assertEquals("1", values["DROIDDECK_ANTICHEAT_OFFLINE"])
|
||||
assertEquals("12_2", values["VKD3D_FEATURE_LEVEL"])
|
||||
assertEquals("6_9", values["VKD3D_SHADER_MODEL"])
|
||||
assertFalse(values.containsKey("VKD3D_FEATURE_LEVEL"))
|
||||
assertFalse(values.containsKey("VKD3D_SHADER_MODEL"))
|
||||
}
|
||||
|
||||
@Test fun forceSsbsIsADefaultAGameCanTurnOff() {
|
||||
@@ -35,14 +35,14 @@ class GameEnvironmentTest {
|
||||
}
|
||||
|
||||
@Test fun graphicsDefaultsRespectExistingEditsAndRemovals() {
|
||||
val config = GameEnvironment.Config(shared = mapOf("VKD3D_FEATURE_LEVEL" to "12_0"))
|
||||
val config = GameEnvironment.Config(shared = mapOf("VKD3D_FEATURE_LEVEL" to "12_0", "VKD3D_SHADER_MODEL" to "6_5"))
|
||||
.withEntries("42", mapOf("VKD3D_SHADER_MODEL" to null))
|
||||
val game = GameEnvironment.effective(config, "", "42")
|
||||
assertEquals("12_0", game["VKD3D_FEATURE_LEVEL"])
|
||||
assertTrue(game.containsKey("VKD3D_SHADER_MODEL"))
|
||||
assertNull(game["VKD3D_SHADER_MODEL"])
|
||||
val restored = GameEnvironment.effective(config.withEntries("42", emptyMap()), "", "42")
|
||||
assertEquals("6_9", restored["VKD3D_SHADER_MODEL"])
|
||||
assertEquals("6_5", restored["VKD3D_SHADER_MODEL"])
|
||||
}
|
||||
|
||||
@Test fun dotnetRuntimeFitsAndroidAddressSpaceForEveryGame() {
|
||||
|
||||
@@ -316,6 +316,60 @@ class LogRedactorTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun oversizedAccountMetadataIsRejectedWithoutForgettingKnownNames() {
|
||||
val users = tmp.newFile("known-loginusers.vdf")
|
||||
val oversized = tmp.newFile("oversized-loginusers.vdf")
|
||||
users.writeText("\"AccountName\" \"previous_player\"")
|
||||
java.io.RandomAccessFile(oversized, "rw").use {
|
||||
it.setLength(LogRedactor.MAX_LEARN_INPUT_BYTES.toLong() + 1)
|
||||
}
|
||||
try {
|
||||
assertTrue(LogRedactor.learnAccounts(users))
|
||||
assertFalse(LogRedactor.learnAccounts(oversized))
|
||||
assertEquals("<redacted:account>", LogRedactor.redact("previous_player"))
|
||||
} finally {
|
||||
LogRedactor.learnAccounts()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun repeatedIncompleteAccountLearningKeepsOnlyABoundedRecentSet() {
|
||||
val users = tmp.newFile("changing-loginusers.vdf")
|
||||
val oversized = tmp.newFile("unreadable-loginusers.vdf")
|
||||
java.io.RandomAccessFile(oversized, "rw").use {
|
||||
it.setLength(LogRedactor.MAX_LEARN_INPUT_BYTES.toLong() + 1)
|
||||
}
|
||||
try {
|
||||
LogRedactor.learnAccounts()
|
||||
repeat(3) { batch ->
|
||||
users.writeText((0 until 1024).joinToString("\n") {
|
||||
"\"AccountName\" \"round${batch}player${it.toString().padStart(4, '0')}\""
|
||||
})
|
||||
assertFalse(LogRedactor.learnAccounts(users, oversized))
|
||||
}
|
||||
assertEquals("<redacted:account>", LogRedactor.redact("round2player0000"))
|
||||
assertEquals("<redacted:account>", LogRedactor.redact("round1player0000"))
|
||||
assertEquals("round0player0000", LogRedactor.redact("round0player0000"))
|
||||
} finally {
|
||||
LogRedactor.learnAccounts()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun oversizedAddressMetadataIsRejectedWithoutForgettingKnownAddresses() {
|
||||
val link = tmp.newFile("known-network")
|
||||
val oversized = tmp.newFile("oversized-network")
|
||||
link.writeText("addr 203.0.113.40 24\n")
|
||||
java.io.RandomAccessFile(oversized, "rw").use {
|
||||
it.setLength(LogRedactor.MAX_LEARN_INPUT_BYTES.toLong() + 1)
|
||||
}
|
||||
try {
|
||||
assertTrue(LogRedactor.learnOwnAddresses(link))
|
||||
assertFalse(LogRedactor.learnOwnAddresses(oversized))
|
||||
assertEquals("<redacted:ip>", LogRedactor.redact("203.0.113.40"))
|
||||
} finally {
|
||||
LogRedactor.learnOwnAddresses(tmp.root.resolve("missing-network"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun manyLearnedAddressesKeepOtherAddresses() {
|
||||
val link = tmp.newFile("droiddeck-net")
|
||||
link.writeText((1..40).joinToString("\n") { "addr 203.0.113.$it 24" })
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import java.io.File
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class AddedGamesCacheTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun game(name: String = "Example"): Pair<File, File> {
|
||||
val folder = tmp.newFolder(name)
|
||||
val exe = File(folder, "bin/$name.exe").apply { parentFile!!.mkdirs(); writeText("game") }
|
||||
return folder to exe
|
||||
}
|
||||
|
||||
private fun store() = File(tmp.root, "scan.json")
|
||||
|
||||
@Test fun aRankingIsReusedAfterARestartWhileItsFolderIsUnchanged() {
|
||||
val (folder, exe) = game()
|
||||
AddedGamesCache(store()).apply { keepRank(folder, GameExePicker.Ranking(listOf(exe), listOf(72), uncertain = true)); save() }
|
||||
val kept = AddedGamesCache(store()).rank(folder)
|
||||
assertEquals(listOf(exe), kept?.exes)
|
||||
assertEquals(listOf(72), kept?.scores)
|
||||
assertEquals(true, kept?.uncertain)
|
||||
}
|
||||
|
||||
@Test fun aChangedFolderOrAMissingExecutableIsWalkedAgain() {
|
||||
val (folder, exe) = game()
|
||||
AddedGamesCache(store()).apply { keepRank(folder, GameExePicker.Ranking(listOf(exe), listOf(72), false)); save() }
|
||||
val modified = folder.lastModified()
|
||||
folder.setLastModified(modified + 60_000)
|
||||
assertNull(AddedGamesCache(store()).rank(folder))
|
||||
folder.setLastModified(modified)
|
||||
assertNotNull(AddedGamesCache(store()).rank(folder))
|
||||
exe.delete()
|
||||
assertNull(AddedGamesCache(store()).rank(folder))
|
||||
}
|
||||
|
||||
@Test fun aRankingOlderThanAWeekIsWalkedAgain() {
|
||||
val (folder, exe) = game()
|
||||
val walked = System.currentTimeMillis() - AddedGamesCache.KEEP_MS - 1
|
||||
store().writeText(JSONObject().put("ranks", JSONObject().put(folder.path, JSONObject()
|
||||
.put("modified", folder.lastModified()).put("at", walked)
|
||||
.put("exes", JSONArray(listOf(exe.path))).put("scores", JSONArray(listOf(72))))).toString())
|
||||
assertNull(AddedGamesCache(store()).rank(folder))
|
||||
}
|
||||
|
||||
@Test fun aFolderWithNoExecutableIsNotKept() {
|
||||
val folder = tmp.newFolder("Empty")
|
||||
AddedGamesCache(store()).apply { keepRank(folder, GameExePicker.Ranking(emptyList(), emptyList(), false)); save() }
|
||||
assertFalse(store().exists())
|
||||
assertNull(AddedGamesCache(store()).rank(folder))
|
||||
}
|
||||
|
||||
@Test fun anIdentifiedNameIsReusedAfterARestart() {
|
||||
AddedGamesCache(store()).apply { keepName("named", "God of War"); keepName("unnamed", ""); save() }
|
||||
val kept = AddedGamesCache(store())
|
||||
assertEquals("God of War", kept.name("named"))
|
||||
assertEquals("", kept.name("unnamed"))
|
||||
assertNull(kept.name("unknown"))
|
||||
}
|
||||
|
||||
@Test fun aMalformedRecordIsSkippedAndTheOthersStillLoad() {
|
||||
val (folder, exe) = game()
|
||||
val (other, _) = game("Other")
|
||||
val now = System.currentTimeMillis()
|
||||
val good = JSONObject().put("modified", folder.lastModified()).put("at", now)
|
||||
.put("exes", JSONArray(listOf(exe.path))).put("scores", JSONArray(listOf(72)))
|
||||
val bad = JSONObject().put("modified", other.lastModified()).put("at", now)
|
||||
.put("exes", JSONArray(listOf("bin/Other.exe"))).put("scores", JSONArray(listOf("bad")))
|
||||
store().writeText(JSONObject()
|
||||
.put("ranks", JSONObject().put(folder.path, good).put(other.path, bad))
|
||||
.put("names", JSONObject().put("broken", "not a record").put("named", JSONObject().put("name", "Bastion").put("at", now)))
|
||||
.toString())
|
||||
val kept = AddedGamesCache(store())
|
||||
assertEquals(listOf(exe), kept.rank(folder)?.exes)
|
||||
assertNull(kept.rank(other))
|
||||
assertEquals("Bastion", kept.name("named"))
|
||||
assertNull(kept.name("broken"))
|
||||
}
|
||||
|
||||
@Test fun aNameOlderThanAWeekIsIdentifiedAgain() {
|
||||
store().writeText(JSONObject().put("names", JSONObject().put("named", JSONObject().put("name", "Bastion")
|
||||
.put("at", System.currentTimeMillis() - AddedGamesCache.KEEP_MS - 1))).toString())
|
||||
assertNull(AddedGamesCache(store()).name("named"))
|
||||
}
|
||||
|
||||
@Test fun aSaveThatCannotBeWrittenIsTriedAgainNextTime() {
|
||||
val blocked = File(tmp.root, "blocked").apply { writeText("a file where the cache folder should be") }
|
||||
val file = File(blocked, "scan.json")
|
||||
val cache = AddedGamesCache(file).apply { keepName("named", "Bastion") }
|
||||
cache.save()
|
||||
assertFalse(file.exists())
|
||||
blocked.delete()
|
||||
blocked.mkdirs()
|
||||
cache.save()
|
||||
assertEquals("Bastion", AddedGamesCache(file).name("named"))
|
||||
}
|
||||
|
||||
@Test fun aRankingAScanReusedIsNotHandedToAFreshLookup() {
|
||||
val folder = tmp.newFolder("Game")
|
||||
val walked = File(folder, "Game.exe").apply { writeText("game") }
|
||||
val kept = File(folder, "Other.exe").apply { writeText("other") }
|
||||
val files = tmp.newFolder("files")
|
||||
val context = object : android.content.ContextWrapper(app) {
|
||||
override fun getFilesDir() = files
|
||||
}
|
||||
AddedGamesCache(File(files, AddedGamesCache.FILE)).apply {
|
||||
keepRank(folder, GameExePicker.Ranking(listOf(kept), listOf(10), false))
|
||||
save()
|
||||
}
|
||||
AddedGames.scan(context)
|
||||
assertEquals(listOf(kept), AddedGames.rank(folder, reuse = true).exes)
|
||||
assertEquals(walked, AddedGames.candidates(folder).first())
|
||||
}
|
||||
|
||||
@Test fun aScanKeepsEachGamesRankingForTheNextLaunch() {
|
||||
val (folder, exe) = game("Card Game")
|
||||
AddedExes.put(app, AddedExes.Entry(folder.path, exe.path, picked = false))
|
||||
AddedGames.scan(app)
|
||||
assertEquals(listOf(exe.path), AddedGamesCache(File(app.filesDir, AddedGamesCache.FILE)).rank(folder)?.exes?.map { it.path })
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,14 @@ class WinCompSourcesTest {
|
||||
|
||||
private fun auto(findings: List<WinCompSources.Finding>) = findings.filter { it.auto }.map { it.component to it.origin }
|
||||
|
||||
@Test fun battleNetRepairKeysMatchRuntimeProfileKeys() {
|
||||
val battlenet = game(null, Store.BATTLENET.id, 4242, library = "battlenet")
|
||||
val steam = game(null, Library.SOURCE_STEAM, 4242, library = "steam")
|
||||
|
||||
assertEquals(battlenet.profileKey, AutoComponents.appKey(battlenet))
|
||||
assertEquals("4242", AutoComponents.appKey(steam))
|
||||
}
|
||||
|
||||
|
||||
@Test fun gogDependencyIdsMapToComponents() {
|
||||
assertEquals(listOf("vcredist2015"), WinCompSources.gog("MSVC2017_x64"))
|
||||
@@ -69,6 +77,8 @@ class WinCompSourcesTest {
|
||||
|
||||
@Test fun steamworksSharedDepotsMapToComponents() {
|
||||
assertEquals(listOf("vcredist2015_dll" to "VC++ 2015", "d3dx9" to "DirectX (June 2010)"), WinCompSources.steamDepots(listOf("228986", "228990", "999")))
|
||||
// Hotline Miami's OpenAL depot: the DLL-copy entry, which installs without running anything.
|
||||
assertEquals(listOf("oalinst_dll" to "OpenAL"), WinCompSources.steamDepots(listOf("229020")))
|
||||
}
|
||||
|
||||
|
||||
@@ -233,16 +243,19 @@ class WinCompSourcesTest {
|
||||
private var session = false
|
||||
private var gameUp = false
|
||||
|
||||
private fun payback(): Library.SteamGame {
|
||||
private fun payback(appId: Int = 1262580): Library.SteamGame {
|
||||
val steamapps = tmp.newFolder("steamapps")
|
||||
val folder = File(steamapps, "common/Payback").apply { mkdirs() }
|
||||
File(steamapps, "appmanifest_1262580.acf").writeText(
|
||||
File(steamapps, "appmanifest_$appId.acf").writeText(
|
||||
"\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228985\"\t\t\"228980\"\n\t\t\"228988\"\t\t\"228980\"\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n",
|
||||
)
|
||||
return game(folder, Library.SOURCE_STEAM, 1262580, library = "steam", name = "Need for Speed Payback")
|
||||
return game(folder, Library.SOURCE_STEAM, appId, library = "steam", name = "Need for Speed Payback")
|
||||
}
|
||||
|
||||
private fun <T> withFakeWorker(block: () -> T): T {
|
||||
val steamPics = SteamAppInfo.pics
|
||||
SteamAppInfo.pics = { null }
|
||||
AutoComponents.repairFailures.value = emptyMap()
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 }
|
||||
AutoComponents.installedOf = { installedNow.toSet() }
|
||||
AutoComponents.installer = { _, c, _, _ -> downloaded.add(c.name); installedNow.add(c.name); null }
|
||||
@@ -255,6 +268,8 @@ class WinCompSourcesTest {
|
||||
return block()
|
||||
} finally {
|
||||
AutoComponents.runNow = false
|
||||
SteamAppInfo.pics = steamPics
|
||||
AutoComponents.repairFailures.value = emptyMap()
|
||||
AutoComponents.catalogOf = { c, network -> if (network) WinComponents.fetch(c) else WinComponents.cached(c) }
|
||||
AutoComponents.installedOf = { WinComponents.installedIds(it).toSet() }
|
||||
AutoComponents.installer = { c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
||||
@@ -264,6 +279,37 @@ class WinCompSourcesTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun anExplicitCheckRefreshesTheCatalogAndAnOfflineCheckUsesTheCache() = withFakeWorker {
|
||||
installedNow.addAll(catalog3.map { it.name })
|
||||
val requests = ArrayList<Boolean>()
|
||||
AutoComponents.catalogOf = { _, network -> requests.add(network); catalog3 }
|
||||
val game = payback()
|
||||
AutoComponents.queueGame(app, game, asked = true)
|
||||
assertTrue(requests.first())
|
||||
requests.clear()
|
||||
AutoComponents.online = { false }
|
||||
AutoComponents.queueGame(app, game, asked = true)
|
||||
assertFalse(requests.first())
|
||||
}
|
||||
|
||||
@Test fun aSweepRefreshesTheCatalogOnlyOnAFavourableConnection() = withFakeWorker {
|
||||
installedNow.addAll(catalog3.map { it.name })
|
||||
val requests = ArrayList<Boolean>()
|
||||
AutoComponents.catalogOf = { _, network -> requests.add(network); catalog3 }
|
||||
val games = listOf(payback())
|
||||
AutoComponents.sweep(app, games)
|
||||
assertTrue(requests.first())
|
||||
requests.clear()
|
||||
AutoComponents.unfavourable = { true }
|
||||
AutoComponents.sweep(app, games)
|
||||
assertFalse(requests.contains(true))
|
||||
requests.clear()
|
||||
AutoComponents.unfavourable = { false }
|
||||
AutoComponents.online = { false }
|
||||
AutoComponents.sweep(app, games)
|
||||
assertFalse(requests.contains(true))
|
||||
}
|
||||
|
||||
@Test fun aSteamListedComponentNotYetDownloadedTurnsOnWhenItLands() = withFakeWorker {
|
||||
installedNow.add("d3dx9")
|
||||
val game = payback()
|
||||
@@ -277,6 +323,244 @@ class WinCompSourcesTest {
|
||||
assertEquals(3, AutoComponents.cachedFindings(app, "1262580")!!.count { it.auto })
|
||||
}
|
||||
|
||||
@Test fun downloadCallbacksReuseTheCatalogInsteadOfRefreshingAgain() = withFakeWorker {
|
||||
val requests = ArrayList<Boolean>()
|
||||
AutoComponents.catalogOf = { _, network -> requests.add(network); catalog3 }
|
||||
AutoComponents.queueGame(app, payback(), asked = true)
|
||||
assertEquals(3, downloaded.size)
|
||||
assertEquals(1 + downloaded.size, requests.count { it })
|
||||
}
|
||||
|
||||
@Test fun normalLaunchRecordsPendingComponentsBeforeQueueingTheirRepairs() = withFakeWorker {
|
||||
AutoComponents.installer = { _, c, _, _ ->
|
||||
assertTrue(c.name in AutoComponents.Pending.ids(app, "1262580"))
|
||||
assertEquals(c.revision, AutoComponents.Pending.revision(app, c.name))
|
||||
downloaded.add(c.name)
|
||||
installedNow.add(c.name)
|
||||
null
|
||||
}
|
||||
|
||||
AutoComponents.queueGame(app, payback(), asked = true)
|
||||
|
||||
assertTrue(AutoComponents.Pending.ids(app, "1262580").isEmpty())
|
||||
}
|
||||
|
||||
@Test fun launchDiscoveryPersistsMissingComponentsWhileAWorkerWaitsForTheSession() = withFakeWorker {
|
||||
session = true
|
||||
gameUp = true
|
||||
val appId = 9876543
|
||||
|
||||
assertTrue(AutoComponents.prepareLaunch(app, payback(appId)))
|
||||
|
||||
assertEquals(setOf("d3dx9", "vcredist2013_dll", "vcredist2019_dll"), AutoComponents.Pending.ids(app, appId.toString()).toSet())
|
||||
session = false
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
}
|
||||
|
||||
@Test fun launchDiscoveryUsesFreshCatalogAndIncludesManualDependencies() = withFakeWorker {
|
||||
session = true
|
||||
gameUp = true
|
||||
val appId = 9876544
|
||||
val manual = WinComponents.Component("manual_component", "", "", "ready", listOf("d3dx9"), emptyList(), revision = 3)
|
||||
val catalog = catalog3 + manual
|
||||
val requests = ArrayList<Boolean>()
|
||||
AutoComponents.catalogOf = { _, network -> requests.add(network); catalog }
|
||||
WinComponents.setUser(app, appId.toString(), manual.name, true)
|
||||
|
||||
assertTrue(AutoComponents.prepareLaunch(app, game(null, Library.SOURCE_STEAM, appId, library = "steam")))
|
||||
|
||||
assertTrue(requests.contains(true))
|
||||
assertEquals(setOf("manual_component", "d3dx9"), AutoComponents.Pending.ids(app, appId.toString()).toSet())
|
||||
session = false
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
}
|
||||
|
||||
@Test fun pendingRepairsSurviveTemporaryCatalogFetchFailure() = withFakeWorker {
|
||||
val id = "vcredist2010_dll"
|
||||
AutoComponents.catalogOf = { _, _ -> null }
|
||||
|
||||
AutoComponents.queueRepair(app, id, "4242", revision = 2)
|
||||
|
||||
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "4242"))
|
||||
assertEquals(2, AutoComponents.Pending.revision(app, id))
|
||||
}
|
||||
|
||||
@Test fun launchCanProceedWithoutCatalogOnlyWhenNoRepairIsPending() = withFakeWorker {
|
||||
AutoComponents.catalogOf = { _, _ -> null }
|
||||
val noPending = game(null, Library.SOURCE_STEAM, 9876545, library = "steam")
|
||||
assertTrue(AutoComponents.prepareLaunch(app, noPending))
|
||||
|
||||
AutoComponents.Pending.add(app, "9876546", listOf("vcredist2010_dll"), mapOf("vcredist2010_dll" to 2))
|
||||
val pending = game(null, Library.SOURCE_STEAM, 9876546, library = "steam")
|
||||
assertFalse(AutoComponents.prepareLaunch(app, pending))
|
||||
assertEquals(listOf("vcredist2010_dll"), AutoComponents.Pending.ids(app, "9876546"))
|
||||
}
|
||||
|
||||
@Test fun offlineLaunchPersistsMissingSelectedComponentsWithoutACatalog() = withFakeWorker {
|
||||
AutoComponents.catalogOf = { _, _ -> null }
|
||||
AutoComponents.online = { false }
|
||||
val appId = 9876547
|
||||
val id = "vcredist2010_dll"
|
||||
WinComponents.setUser(app, appId.toString(), id, true)
|
||||
|
||||
assertFalse(AutoComponents.prepareLaunch(app, game(null, Library.SOURCE_STEAM, appId, library = "steam")))
|
||||
assertEquals(listOf(id), AutoComponents.Pending.ids(app, appId.toString()))
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + ready(id) }
|
||||
AutoComponents.online = { true }
|
||||
AutoComponents.drain(app)
|
||||
}
|
||||
|
||||
@Test fun pendingRepairsKeepTheirRequiredRevisionUntilTheyFinish() = withFakeWorker {
|
||||
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 2)
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
|
||||
WinComponents.setUser(app, "4242", repair.name, true)
|
||||
session = true
|
||||
gameUp = true
|
||||
AutoComponents.restoreMissing(app)
|
||||
val pending = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
|
||||
fun revision() = JSONObject(pending.readText()).getJSONObject("revisions").getInt(repair.name)
|
||||
assertEquals(2, revision())
|
||||
AutoComponents.Pending.add(app, "other", listOf(repair.name), mapOf(repair.name to 1))
|
||||
AutoComponents.Pending.set(app, "4242", listOf(repair.name))
|
||||
assertEquals(2, revision())
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
assertFalse(JSONObject(pending.readText()).getJSONObject("revisions").has(repair.name))
|
||||
}
|
||||
|
||||
@Test fun manualRepairKeepsPendingWhenCatalogIsOlderThanRequestedRevision() = withFakeWorker {
|
||||
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 1)
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
|
||||
installedNow.add(repair.name)
|
||||
AutoComponents.Pending.add(app, "4242", listOf(repair.name), mapOf(repair.name to 2))
|
||||
AutoComponents.queueRepair(app, repair.name, "4242", revision = 1)
|
||||
AutoComponents.drain(app)
|
||||
assertEquals("The component catalog is older than the requested revision", AutoComponents.repairFailures.value[repair.name])
|
||||
assertEquals(listOf(repair.name), AutoComponents.Pending.ids(app, "4242"))
|
||||
val pendingFile = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
|
||||
assertEquals(2, JSONObject(pendingFile.readText()).getJSONObject("revisions").getInt(repair.name))
|
||||
}
|
||||
|
||||
@Test fun restoreRequeuesPersistedRevisionEvenWhenOlderComponentIsInstalled() = withFakeWorker {
|
||||
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 1)
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
|
||||
installedNow.add(repair.name)
|
||||
AutoComponents.Pending.add(app, "4242", listOf(repair.name), mapOf(repair.name to 2))
|
||||
assertTrue(WinComponents.selections(app).isEmpty())
|
||||
assertTrue(AutoComponents.restoreMissing(app).isEmpty())
|
||||
assertEquals("The component catalog is older than the requested revision", AutoComponents.repairFailures.value[repair.name])
|
||||
assertEquals(listOf(repair.name), AutoComponents.Pending.ids(app, "4242"))
|
||||
assertEquals(2, AutoComponents.Pending.revision(app, repair.name))
|
||||
WinComponents.setUser(app, "4242", repair.name, false)
|
||||
AutoComponents.queueInSession(app, game(null, Library.SOURCE_STEAM, 4242, library = "steam"))
|
||||
assertTrue(AutoComponents.Pending.ids(app, "4242").isEmpty())
|
||||
}
|
||||
|
||||
@Test fun missingCatalogComponentCannotDropANewerPendingRepair() = withFakeWorker {
|
||||
val id = "vcredist2010_dll"
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 }
|
||||
session = true
|
||||
gameUp = true
|
||||
AutoComponents.queueRepair(app, id, "4242", revision = 1)
|
||||
AutoComponents.Pending.add(app, "other", listOf(id), mapOf(id to 2))
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "4242"))
|
||||
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "other"))
|
||||
assertEquals(2, AutoComponents.Pending.revision(app, id))
|
||||
}
|
||||
|
||||
@Test fun restoredLegacyPendingRepairUsesThePersistedRevision() = withFakeWorker {
|
||||
val id = "vcredist2010_dll"
|
||||
val repair = WinComponents.Component(id, "", "", "ready", emptyList(), emptyList(), revision = 1)
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
|
||||
var attempts = 0
|
||||
AutoComponents.installer = { _, _, _, _ -> attempts++; null }
|
||||
val pendingFile = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
|
||||
pendingFile.parentFile?.mkdirs()
|
||||
pendingFile.writeText(JSONObject().put("games", JSONObject().put("4242", org.json.JSONArray(listOf(id)))).toString())
|
||||
session = true
|
||||
gameUp = true
|
||||
AutoComponents.queueInSession(app, game(null, Library.SOURCE_STEAM, 4242, library = "steam"))
|
||||
AutoComponents.Pending.add(app, "other", listOf(id), mapOf(id to 2))
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
assertEquals("The component catalog is older than the requested revision", AutoComponents.repairFailures.value[id])
|
||||
assertEquals(0, attempts)
|
||||
assertEquals(2, AutoComponents.Pending.revision(app, id))
|
||||
}
|
||||
|
||||
@Test fun catalogLoadFailureCannotDropANewerPendingRepair() = withFakeWorker {
|
||||
val id = "vcredist2010_dll"
|
||||
AutoComponents.catalogOf = { _, _ -> null }
|
||||
session = true
|
||||
gameUp = true
|
||||
AutoComponents.queueRepair(app, id, "4242", revision = 1)
|
||||
AutoComponents.Pending.add(app, "other", listOf(id), mapOf(id to 2))
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
assertEquals("Could not load the component catalog", AutoComponents.repairFailures.value[id])
|
||||
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "4242"))
|
||||
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "other"))
|
||||
assertEquals(2, AutoComponents.Pending.revision(app, id))
|
||||
}
|
||||
|
||||
@Test fun manualRepairsRecordTheirRevisionAndExposeFailuresForRetry() = withFakeWorker {
|
||||
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 2)
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
|
||||
var attempts = 0
|
||||
AutoComponents.installer = { _, c, _, _ ->
|
||||
attempts++
|
||||
if (attempts == 1) throw IllegalStateException("network unavailable") else { installedNow.add(c.name); null }
|
||||
}
|
||||
session = true
|
||||
gameUp = true
|
||||
AutoComponents.queueRepair(app, repair.name, "4242", repair.revision)
|
||||
val pending = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
|
||||
assertEquals(2, JSONObject(pending.readText()).getJSONObject("revisions").getInt(repair.name))
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
assertEquals("network unavailable", AutoComponents.repairFailures.value[repair.name])
|
||||
assertEquals(1, attempts)
|
||||
assertFalse(JSONObject(pending.readText()).getJSONObject("games").has("4242"))
|
||||
session = false
|
||||
AutoComponents.queueRepair(app, repair.name, "4242", repair.revision)
|
||||
assertEquals(2, attempts)
|
||||
assertEquals(null, AutoComponents.repairFailures.value[repair.name])
|
||||
assertTrue(repair.name in installedNow)
|
||||
assertFalse(JSONObject(pending.readText()).getJSONObject("revisions").has(repair.name))
|
||||
}
|
||||
|
||||
@Test fun anEarlierRepairCannotDropANewerGamesPendingRevision() = withFakeWorker {
|
||||
session = false
|
||||
gameUp = false
|
||||
val first = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 2)
|
||||
val newer = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 3)
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + first }
|
||||
var attempts = 0
|
||||
AutoComponents.installer = { _, c, _, _ ->
|
||||
attempts++
|
||||
if (attempts == 1) {
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + newer }
|
||||
session = true
|
||||
gameUp = true
|
||||
AutoComponents.queueRepair(app, c.name, "other", newer.revision)
|
||||
} else installedNow.add(c.name)
|
||||
null
|
||||
}
|
||||
AutoComponents.queueRepair(app, first.name, "first", first.revision)
|
||||
val pending = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
|
||||
assertEquals(3, JSONObject(pending.readText()).getJSONObject("revisions").getInt(first.name))
|
||||
assertEquals(listOf(first.name), AutoComponents.Pending.ids(app, "other"))
|
||||
gameUp = false
|
||||
session = false
|
||||
AutoComponents.drain(app)
|
||||
assertEquals(2, attempts)
|
||||
assertFalse(JSONObject(pending.readText()).getJSONObject("revisions").has(first.name))
|
||||
}
|
||||
|
||||
@Test fun theQueueWaitsWhileASessionRunsAndResumesAfter() = withFakeWorker {
|
||||
val game = payback()
|
||||
session = true
|
||||
@@ -310,6 +594,21 @@ class WinCompSourcesTest {
|
||||
assertEquals(downloaded.distinct(), downloaded)
|
||||
}
|
||||
|
||||
@Test fun queuedPicsLookupsMergeAppIdsFromLaterSweeps() = withFakeWorker {
|
||||
val lookedUp = ArrayList<List<Int>>()
|
||||
SteamAppInfo.pics = { ids -> lookedUp.add(ids); ids.associateWith { null } }
|
||||
session = true
|
||||
val first = game(null, Library.SOURCE_STEAM, 810001, library = "steam")
|
||||
val second = game(null, Library.SOURCE_STEAM, 810002, library = "steam")
|
||||
|
||||
AutoComponents.sweep(app, listOf(first))
|
||||
AutoComponents.sweep(app, listOf(second))
|
||||
session = false
|
||||
AutoComponents.drain(app)
|
||||
|
||||
assertEquals(listOf(listOf(810001, 810002)), lookedUp)
|
||||
}
|
||||
|
||||
@Test fun aDownloadWaitsForANetwork() = withFakeWorker {
|
||||
val game = payback()
|
||||
AutoComponents.online = { false }
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.BatteryManager
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ClockLogComponentTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
private var clocks: ClockLogComponent? = null
|
||||
|
||||
@After fun stop() { clocks?.stop() }
|
||||
|
||||
@Test fun everySampleCarriesTheBatteryTemperature() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).putExtra(BatteryManager.EXTRA_TEMPERATURE, 412))
|
||||
val log = tmp.newFile("clocks.log")
|
||||
clocks = ClockLogComponent(log).also { it.attach(context); it.start() }
|
||||
val deadline = System.currentTimeMillis() + 5_000
|
||||
while (!log.readText().contains("| battery") && System.currentTimeMillis() < deadline) Thread.sleep(20)
|
||||
assertTrue(log.readText(), log.readText().contains("| battery 41.2 C"))
|
||||
context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).putExtra(BatteryManager.EXTRA_TEMPERATURE, 423))
|
||||
val updatedDeadline = System.currentTimeMillis() + 5_000
|
||||
while (!log.readText().contains("| battery 42.3 C") && System.currentTimeMillis() < updatedDeadline) Thread.sleep(20)
|
||||
assertTrue(log.readText(), log.readText().contains("| battery 42.3 C"))
|
||||
}
|
||||
|
||||
@Test fun stoppedComponentCannotStartFromAnEarlierSnapshot() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val log = tmp.newFile("stopped-clocks.log")
|
||||
clocks = ClockLogComponent(log).also { it.attach(context); it.stop(); it.start() }
|
||||
assertTrue(log.readText(), log.length() == 0L)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class DeviceInfoTest {
|
||||
@Test fun builtinLabelsDistinguishPowerVrFromTurnipAndGenericSystemVulkan() {
|
||||
assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = true))
|
||||
assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = false))
|
||||
assertEquals("the runtime's own Turnip", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = true))
|
||||
assertEquals("System Vulkan", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = false))
|
||||
}
|
||||
}
|
||||
@@ -129,4 +129,19 @@ class DriverBundleTest {
|
||||
assertEquals(2, DriverBundle.all(context).size)
|
||||
assertFalse(first.androidId == second.androidId)
|
||||
}
|
||||
|
||||
@Test fun failedNonAdrenoReplacementKeepsTheInstalledPairAndSelection() {
|
||||
manifest.put("tag", "PanVK-G610-v1")
|
||||
val first = DriverBundle.install(context, bundle())
|
||||
DriverBundle.select(context, first)
|
||||
try {
|
||||
DriverBundle.install(context, bundle(linuxLibc = "libc.so"))
|
||||
fail("Accepted a bionic Linux driver")
|
||||
} catch (_: IllegalArgumentException) {
|
||||
}
|
||||
assertEquals(first.id, DriverBundle.active(context)?.id)
|
||||
assertTrue(TurnipDriver(context).isInstalled(first.androidId))
|
||||
assertTrue(LinuxVulkanDriverManager(context).isInstalled(first.linuxId))
|
||||
assertEquals(1, DriverBundle.all(context).size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class DriverPairUpdateTest {
|
||||
private fun pair(sha: String, id: Long, updated: String, key: String = DriverPairs.nonAdreno("PanVK-Mali-G615")) =
|
||||
TurnipReleases.Asset("Non-Adreno", "panvk-mali-g615", "PanVK-Mali-G615-Pair.zip", "https://example/p", 9_000_000, false,
|
||||
"label", sha, key, bundle = true, assetId = id, updatedAt = updated)
|
||||
|
||||
@Test fun aRebuildUnderTheSameTagIsAnUpdate() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val installed = pair("a".repeat(64), 1, "2026-10-13T10:00:00Z")
|
||||
assertFalse("nothing installed yet", TurnipReleases.updateAvailable(context, installed))
|
||||
TurnipReleases.recordDownload(context, installed, "PanVK-Mali-G615")
|
||||
assertFalse(TurnipReleases.updateAvailable(context, installed))
|
||||
assertEquals("2026-10-13", TurnipReleases.installedBuiltOn(context, installed))
|
||||
assertTrue(TurnipReleases.updateAvailable(context, pair("b".repeat(64), 2, "2026-10-15T10:00:00Z")))
|
||||
assertTrue("a new asset id alone", TurnipReleases.updateAvailable(context, pair("a".repeat(64), 2, "2026-10-13T10:00:00Z")))
|
||||
assertEquals("2026-10-15", pair("b".repeat(64), 2, "2026-10-15T10:00:00Z").builtOn)
|
||||
}
|
||||
|
||||
@Test fun adrenoPairsAreNeverFlagged() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val turnip = pair("a".repeat(64), 1, "2026-10-13T10:00:00Z", key = DriverPairs.BANNER)
|
||||
TurnipReleases.recordDownload(context, turnip, "Turnip-x")
|
||||
assertFalse(TurnipReleases.updateAvailable(context, pair("b".repeat(64), 2, "2026-10-15T10:00:00Z", key = DriverPairs.BANNER)))
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,23 @@ class DriverPairsTest {
|
||||
assertEquals(GpuInfo.Support.UNSUPPORTED, gpu(0, adreno = false).support)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun powerVrUsesItsOwnFamilyWithoutClaimingAllModelsAreTested() {
|
||||
assertEquals(Family.POWERVR, GpuInfo.familyOf(false, 0, powerVr = true))
|
||||
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0, powerVr = false))
|
||||
assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740, powerVr = true))
|
||||
val powerVr = GpuInfo("PowerVR", 0, Family.POWERVR, "", false)
|
||||
assertEquals(GpuInfo.Support.UNTESTED, powerVr.support)
|
||||
assertNull("PowerVR never downloads an Adreno driver pair", DriverPairs.recommendedKey(powerVr, emptyList()))
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER),
|
||||
asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER)),
|
||||
emptyList(), emptyList(), 0L,
|
||||
))
|
||||
assertFalse(pairs.single().suits(powerVr))
|
||||
assertNull(DriverPairs.recommendedKey(powerVr, pairs))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoPicksWinNativeBalancedOn8xxAndBannersElsewhere() {
|
||||
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), emptyList()))
|
||||
@@ -116,4 +133,141 @@ class DriverPairsTest {
|
||||
assertEquals(DriverPairs.BANNER_ONEUI, DriverPairs.recommendedKey(gpu(740, oneUi = true), pairs))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), pairs))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun maliFamiliesFollowTheOpenDriverBuilds() {
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = "Mali-G57 MC2"))
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = "Mali-G77"))
|
||||
assertEquals(Family.MALI_G610_G710, GpuInfo.familyOf(false, 0, mali = "Mali-G710"))
|
||||
assertEquals(Family.MALI_G615, GpuInfo.familyOf(false, 0, mali = "Mali-G615 MC6"))
|
||||
assertEquals(Family.MALI_G720, GpuInfo.familyOf(false, 0, mali = "Mali-G720-Immortalis MC12"))
|
||||
assertEquals(Family.MALI_LATEST, GpuInfo.familyOf(false, 0, mali = "Mali-G925-Immortalis MC12"))
|
||||
assertEquals(Family.MALI_OTHER, GpuInfo.familyOf(false, 0, mali = "Mali-T880"))
|
||||
assertEquals(Family.MALI_OTHER, GpuInfo.familyOf(false, 0, mali = ""))
|
||||
// An Adreno is an Adreno whatever else the device reports, and the system HAL keeps priority.
|
||||
assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740, mali = "Mali-G720"))
|
||||
assertEquals(Family.POWERVR, GpuInfo.familyOf(false, 0, powerVr = true, mali = "Mali-G720"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoPicksTheOpenDriverForEachMaliAndNothingForTheRest() {
|
||||
fun mali(name: String) = GpuInfo(name, 0, GpuInfo.familyOf(false, 0, mali = name), "", false)
|
||||
// Android 14: the per-generation builds; the newest Malis have none and use the bridge.
|
||||
assertEquals(DriverPairs.NAD_MALI_JM, DriverPairs.recommendedKey(mali("Mali-G57"), emptyList(), sdk = 34))
|
||||
assertEquals(DriverPairs.NAD_MALI_G710, DriverPairs.recommendedKey(mali("Mali-G710"), emptyList(), sdk = 34))
|
||||
assertEquals(DriverPairs.NAD_MALI_G615, DriverPairs.recommendedKey(mali("Mali-G615"), emptyList(), sdk = 34))
|
||||
assertEquals(DriverPairs.NAD_MALI_G720, DriverPairs.recommendedKey(mali("Mali-G720"), emptyList(), sdk = 34))
|
||||
assertNull(DriverPairs.recommendedKey(mali("Mali-G925-Immortalis MC12"), emptyList(), sdk = 34))
|
||||
// Android 15+: the one-binary kbase build for every Mali it covers, not the Bifrost G52/G76.
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(mali("Mali-G57"), emptyList(), sdk = 35))
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(mali("Mali-G720"), emptyList(), sdk = 36))
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(mali("Mali-G925-Immortalis MC12"), emptyList(), sdk = 36))
|
||||
assertEquals(DriverPairs.NAD_MALI_JM, DriverPairs.recommendedKey(mali("Mali-G52 MC2"), emptyList(), sdk = 36))
|
||||
assertNull("a Mali no build covers uses the bridge", DriverPairs.recommendedKey(mali("Mali-T880"), emptyList(), sdk = 36))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMissingKbaseReleaseFallsBackToTheGenerationsPair() {
|
||||
val g720 = GpuInfo("Mali-G720", 0, Family.MALI_G720, "", false)
|
||||
fun bundle(id: String) = TurnipReleases.Asset("Non-Adreno", id.lowercase(), "$id-Pair.zip", "https://example/$id", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno(id), bundle = true)
|
||||
val onlyG720 = DriverPairs.from(TurnipReleases.Check(listOf(bundle("PanVK-Mali-G720")), emptyList(), emptyList(), 0L))
|
||||
assertEquals(DriverPairs.NAD_MALI_G720, DriverPairs.recommendedKey(g720, onlyG720, sdk = 36))
|
||||
val both = DriverPairs.from(TurnipReleases.Check(listOf(bundle("PanVK-Mali-G720"), bundle("PanVK-Mali-kbase")), emptyList(), emptyList(), 0L))
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(g720, both, sdk = 36))
|
||||
assertTrue(both.single { it.key == DriverPairs.NAD_MALI_KBASE }.suits(g720))
|
||||
assertFalse(both.single { it.key == DriverPairs.NAD_MALI_KBASE }.suits(GpuInfo("Mali-G52", 0, Family.MALI_JM, "", false)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nonAdrenoPairsComeFromTheirBundlesAndSuitOnlyTheirGpu() {
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(
|
||||
TurnipReleases.Asset("Non-Adreno", "panvk-mali-g720", "PanVK-Mali-G720-Pair.zip", "https://example/a", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno("PanVK-Mali-G720"), bundle = true),
|
||||
TurnipReleases.Asset("Non-Adreno", "radv-xclipse", "RADV-Xclipse-Pair.zip", "https://example/b", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno("RADV-Xclipse"), bundle = true),
|
||||
),
|
||||
emptyList(), emptyList(), 0L,
|
||||
))
|
||||
val g720 = pairs.single { it.key == DriverPairs.NAD_MALI_G720 }
|
||||
val radv = pairs.single { it.key == DriverPairs.NAD_RADV_XCLIPSE }
|
||||
assertTrue(g720.complete)
|
||||
assertTrue(g720.suits(GpuInfo("Mali-G720", 0, Family.MALI_G720, "", false)))
|
||||
assertFalse(g720.suits(gpu(740)))
|
||||
assertTrue(radv.suits(GpuInfo("Xclipse", 0, Family.POWERVR, "", false)))
|
||||
assertFalse("RADV is not for a PowerVR Pixel", radv.suits(GpuInfo("PowerVR", 0, Family.POWERVR, "", false)))
|
||||
assertTrue(DriverPairs.isNonAdreno("PanVK-Mali-G720"))
|
||||
assertTrue(DriverPairs.isNonAdreno("RADV-Xclipse-2"))
|
||||
assertFalse(DriverPairs.isNonAdreno("DD-Turnip-v0.1.0"))
|
||||
assertFalse(DriverPairs.isNonAdreno(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun upstreamRadvIsAManualXclipseChoiceAndAutoKeepsOurs() {
|
||||
val asset = { id: String -> TurnipReleases.Asset("Non-Adreno", id.lowercase(), "$id-Pair.zip", "https://example/$id", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno(id), bundle = true) }
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(listOf(asset("RADV-Xclipse"), asset("RADV-Xclipse-upstream")), emptyList(), emptyList(), 0L))
|
||||
val xclipse = GpuInfo("Samsung Xclipse 940", 0, Family.POWERVR, "", false)
|
||||
val upstream = pairs.single { it.key == DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM }
|
||||
assertEquals("nad:radv-xclipse-upstream", DriverPairs.nonAdreno("RADV-Xclipse-upstream"))
|
||||
assertTrue(upstream.complete)
|
||||
assertTrue(upstream.suits(xclipse))
|
||||
assertFalse(upstream.suits(GpuInfo("PowerVR", 0, Family.POWERVR, "", false)))
|
||||
assertEquals("RADV upstream · Samsung Xclipse", upstream.name)
|
||||
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(xclipse, pairs))
|
||||
for (name in listOf("Samsung Xclipse 530", "Samsung Xclipse 540", "Samsung Xclipse 920"))
|
||||
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(GpuInfo(name, 0, Family.POWERVR, "", false), pairs))
|
||||
assertTrue(DriverPairs.isNonAdreno("RADV-Xclipse-upstream"))
|
||||
for (name in listOf("Samsung Xclipse 950", "Samsung Xclipse 960", "Xclipse")) {
|
||||
val newer = GpuInfo(name, 0, Family.POWERVR, "", false)
|
||||
assertEquals(DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM, DriverPairs.recommendedKey(newer, pairs))
|
||||
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(newer, pairs.filter { it.key != DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM }))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deviceBuildsAreOfferedOnlyForTheirMaliAndNeverByAuto() {
|
||||
fun bundle(id: String) = TurnipReleases.Asset("Non-Adreno", id.lowercase(), "$id-Pair.zip", "https://example/$id", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno(id), bundle = true)
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(bundle("PanVK-faux123-RP4Pro"), bundle("PanVK-faux123-Ace"), bundle("PanVK-faux123-RG556")),
|
||||
emptyList(), emptyList(), 0L))
|
||||
val g77 = GpuInfo("Mali-G77 MC9", 0, Family.MALI_JM, "", false)
|
||||
val g57 = GpuInfo("Mali-G57 MC2", 0, Family.MALI_JM, "", false)
|
||||
val g610 = GpuInfo("Mali-G610 MC6", 0, Family.MALI_G610_G710, "", false)
|
||||
assertTrue(pairs.single { it.key == DriverPairs.NAD_FAUX_RP4PRO }.suits(g77))
|
||||
assertFalse(pairs.single { it.key == DriverPairs.NAD_FAUX_RP4PRO }.suits(g57))
|
||||
assertTrue(pairs.single { it.key == DriverPairs.NAD_FAUX_RG556 }.suits(g57))
|
||||
assertTrue(pairs.single { it.key == DriverPairs.NAD_FAUX_ACE }.suits(g610))
|
||||
assertEquals(DriverPairs.NAD_MALI_JM, DriverPairs.recommendedKey(g77, pairs, sdk = 34))
|
||||
assertTrue(DriverPairs.isNonAdreno("PanVK-faux123-RP4Pro"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMaliTheDeviceDoesNotNameIsKnownByItsChip() {
|
||||
assertEquals("Mali-G720 (by chip mt6989)", GpuInfo.maliOfSoc(listOf("", "mt6989")))
|
||||
assertEquals("Mali-G710 (by chip gs201)", GpuInfo.maliOfSoc(listOf("GS201")))
|
||||
assertEquals(null, GpuInfo.maliOfSoc(listOf("unknown-chip")))
|
||||
// An Exynos with a Mali, and a Helio G99, by board name.
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = GpuInfo.maliOfSoc(listOf("s5e8835"))))
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = GpuInfo.maliOfSoc(listOf("MT6789"))))
|
||||
assertEquals(Family.MALI_G720, GpuInfo.familyOf(false, 0, mali = "Mali-G720 (by chip mt6989)"))
|
||||
assertEquals(Family.MALI_LATEST, GpuInfo.familyOf(false, 0, mali = "Mali-G925 (by chip mt6991)"))
|
||||
assertTrue(GpuInfo.maliKbaseCovered("Mali-G720 (by chip mt6989)"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theMaliG1SeriesHasNoPanVkPairAndIsKnownByItsChip() {
|
||||
// Arch v14 (Dimensity 9500): no PanVK build is proven there, so Auto uses the phone's own driver.
|
||||
assertEquals("Mali-G1-Ultra (by chip mt6993)", GpuInfo.maliOfSoc(listOf("MT6993")))
|
||||
assertEquals(Family.MALI_OTHER, GpuInfo.familyOf(false, 0, mali = "Mali-G1-Ultra MC12"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoTakesRadvOnAnXclipseAndLeavesPowerVrOnTheSystemDriver() {
|
||||
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(GpuInfo("Samsung Xclipse 940", 0, Family.POWERVR, "", false), emptyList()))
|
||||
assertNull(DriverPairs.recommendedKey(GpuInfo("PowerVR", 0, Family.POWERVR, "", false), emptyList()))
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ class GpuDetectionTest {
|
||||
assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", info(true, 850).supportText)
|
||||
assertEquals("Experimental: its drivers are test builds", info(true, 720).supportText)
|
||||
assertEquals("Outside tested hardware (Adreno 650, 725 and newer): it may not run", info(true, 618).supportText)
|
||||
assertEquals("Not supported: DroidDeck needs an Adreno (Snapdragon) GPU", info(false, 0).supportText)
|
||||
assertEquals("Not supported: no compatible graphics backend is available for this GPU", info(false, 0).supportText)
|
||||
assertEquals("Not an Adreno GPU", Family.NOT_ADRENO.label)
|
||||
assertEquals("Adreno 8xx", Family.A8XX.label)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class SystemVulkanPruningTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
|
||||
@Test fun completedReplacementCollectsOnlyManagedOldDirectories() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = completeRuntime(base, "a".repeat(64))
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val stage = abandonedStage(base)
|
||||
val unrelated = File(base, "notes").apply { mkdir(); File(this, "keep").writeText("keep") }
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
|
||||
assertEquals("current ICD", File(current, "icd.json").readText())
|
||||
assertTrue(File(current, "run-proton.py").canExecute())
|
||||
assertFalse(old.exists())
|
||||
assertFalse(stage.exists())
|
||||
assertEquals("keep", File(unrelated, "keep").readText())
|
||||
}
|
||||
|
||||
@Test fun aSurvivingGuestKeepsOldVersionsButNotAbandonedStages() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = completeRuntime(base, "a".repeat(64))
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val stage = abandonedStage(base)
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, false)
|
||||
|
||||
assertTrue(current.isDirectory)
|
||||
assertTrue(old.isDirectory)
|
||||
assertFalse(stage.exists())
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertFalse("collect the old version once guests stop", old.exists())
|
||||
}
|
||||
|
||||
@Test fun failedReplacementPreservesThePreviousGoodRuntime() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = File(base, "a".repeat(64))
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val stage = abandonedStage(base)
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertTrue("missing replacement", old.isDirectory)
|
||||
assertFalse(stage.exists())
|
||||
|
||||
current.mkdir()
|
||||
File(current, "icd.json").writeText("incomplete")
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertEquals("current ICD", File(old, "icd.json").readText())
|
||||
}
|
||||
|
||||
@Test fun deletingOldRuntimeDoesNotFollowItsSymlinks() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = completeRuntime(base, "a".repeat(64))
|
||||
val old = File(base, "b".repeat(64)).apply { mkdir() }
|
||||
val outside = temporary.newFolder("outside")
|
||||
val sentinel = File(outside, "keep").apply { writeText("keep") }
|
||||
Files.createSymbolicLink(File(old, "outside").toPath(), outside.toPath())
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
|
||||
assertFalse(old.exists())
|
||||
assertEquals("keep", sentinel.readText())
|
||||
}
|
||||
|
||||
@Test fun linkedBaseOrCurrentRuntimePreventsCleanup() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val current = File(base, "a".repeat(64))
|
||||
Files.createSymbolicLink(current.toPath(), old.toPath())
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertTrue(old.isDirectory)
|
||||
|
||||
Files.delete(current.toPath())
|
||||
completeRuntime(base, current.name)
|
||||
val alias = File(temporary.root, "alias")
|
||||
Files.createSymbolicLink(alias.toPath(), base.toPath())
|
||||
SystemVulkanDriver.pruneUnused(File(alias, current.name), true)
|
||||
assertTrue(old.isDirectory)
|
||||
}
|
||||
|
||||
private fun abandonedStage(base: File) =
|
||||
File(base, ".stage-12345678-1234-1234-1234-123456789abc").apply { mkdir(); File(this, "partial").writeText("partial") }
|
||||
|
||||
private fun completeRuntime(base: File, version: String): File {
|
||||
val directory = File(base, version).apply { mkdir() }
|
||||
val components = listOf(
|
||||
"lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1", "lib/libhybris/linker/q.so",
|
||||
"lib/libVkLayer_hybris_compat.so", "run-proton.py",
|
||||
"wsi/libVkLayer_window_system_integration.so", "wsi/VkLayer_window_system_integration.json",
|
||||
) + listOf("x32", "x64").flatMap { arch ->
|
||||
listOf("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi").map { "dxvk/$arch/$it.dll" }
|
||||
}
|
||||
components.forEach { path -> File(directory, path).apply { parentFile!!.mkdirs(); writeText("component") } }
|
||||
File(directory, "run-proton.py").setExecutable(true)
|
||||
File(directory, "icd.json").writeText("current ICD")
|
||||
return directory
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class SystemVulkanSelectionTest {
|
||||
@Test fun defaultPowerVrUsesTheSystemBridge() {
|
||||
assertTrue(SystemVulkanDriver.usesDefault(true, ""))
|
||||
assertTrue(SystemVulkanDriver.usesDefault(true, null))
|
||||
}
|
||||
|
||||
@Test fun otherGpusAndExplicitImportsKeepTheirDriver() {
|
||||
assertFalse(SystemVulkanDriver.usesDefault(false, ""))
|
||||
assertFalse(SystemVulkanDriver.usesDefault(false, null))
|
||||
assertFalse(SystemVulkanDriver.usesDefault(true, "custom-driver"))
|
||||
}
|
||||
@Test fun renderNodeRequiresARealCharacterDeviceAndBothAccessModes() {
|
||||
assertTrue(SystemVulkanDriver.renderNodeAvailable(true, true, true))
|
||||
assertFalse("a regular placeholder is not a DRM device", SystemVulkanDriver.renderNodeAvailable(false, true, true))
|
||||
assertFalse("read access is required", SystemVulkanDriver.renderNodeAvailable(true, false, true))
|
||||
assertFalse("write access is required", SystemVulkanDriver.renderNodeAvailable(true, true, false))
|
||||
assertFalse("a missing node is unavailable", SystemVulkanDriver.renderNodeAvailable(false, false, false))
|
||||
}
|
||||
|
||||
@Test fun renderNodeDriverMustIdentifyPowerVrExactly() {
|
||||
for (name in listOf("pvrsrvkm", "pvr", "powervr"))
|
||||
assertTrue(name, SystemVulkanDriver.powerVrDriver(name))
|
||||
for (name in listOf(null, "", "msm", "panfrost", "not-pvr"))
|
||||
assertFalse(name, SystemVulkanDriver.powerVrDriver(name))
|
||||
}
|
||||
|
||||
@Test fun samsungXclipseGpuNodeIsSelectedOverItsDisplayNode() {
|
||||
assertTrue(SystemVulkanDriver.powerVrDriver("sgpu"))
|
||||
assertFalse("the display controller is not the GPU", SystemVulkanDriver.powerVrDriver("exynos-drm"))
|
||||
// Galaxy A56 (Exynos 1580): the GPU owns renderD128, the display controller renderD129.
|
||||
val drivers = mapOf("/dev/dri/renderD128" to "sgpu", "/dev/dri/renderD129" to "exynos-drm")
|
||||
assertEquals("/dev/dri/renderD128", SystemVulkanDriver.findRenderNode(null) { path ->
|
||||
SystemVulkanDriver.powerVrDriver(drivers[path])
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun renderNodeIdentityUsesTheDriverLinkOrUevent() {
|
||||
val device = Files.createTempDirectory("powervr-device").toFile()
|
||||
try {
|
||||
assertFalse("missing identity is unavailable", SystemVulkanDriver.powerVrDevice(device))
|
||||
val uevent = File(device, "uevent")
|
||||
uevent.writeText("DRIVER=pvrsrvkm\nOF_NAME=gpu0\n")
|
||||
assertTrue(SystemVulkanDriver.powerVrDevice(device))
|
||||
uevent.writeText("DRIVER=msm\nOF_COMPATIBLE_0=not-pvr\n")
|
||||
assertFalse(SystemVulkanDriver.powerVrDevice(device))
|
||||
val driver = File(device, "driver").toPath()
|
||||
Files.createSymbolicLink(driver, File("../../drivers/pvrsrvkm").toPath())
|
||||
assertTrue(SystemVulkanDriver.powerVrDevice(device))
|
||||
Files.delete(driver)
|
||||
Files.createSymbolicLink(driver, File("../../drivers/msm").toPath())
|
||||
uevent.writeText("DRIVER=pvrsrvkm\n")
|
||||
assertFalse("an unrelated driver link must not fall back", SystemVulkanDriver.powerVrDevice(device))
|
||||
} finally {
|
||||
device.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun renderNodeDiscoverySkipsOtherDriversAndDeniedNodes() {
|
||||
val drivers = mapOf(
|
||||
"/dev/dri/renderD128" to "msm",
|
||||
"/dev/dri/renderD129" to "pvr",
|
||||
"/dev/dri/renderD130" to "pvrsrvkm",
|
||||
)
|
||||
assertEquals("/dev/dri/renderD129", SystemVulkanDriver.findRenderNode(null) { path ->
|
||||
SystemVulkanDriver.powerVrDriver(drivers[path])
|
||||
})
|
||||
assertEquals("/dev/dri/renderD130", SystemVulkanDriver.findRenderNode(null) { path ->
|
||||
SystemVulkanDriver.powerVrDriver(drivers[path]) &&
|
||||
SystemVulkanDriver.renderNodeAvailable(true, path != "/dev/dri/renderD129", true)
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun renderNodesAreDiscoveredWithoutDirectoryListing() {
|
||||
for (minor in listOf(128, 129, 191)) {
|
||||
val expected = "/dev/dri/renderD$minor"
|
||||
assertEquals(expected, SystemVulkanDriver.findRenderNode(null) { it == expected })
|
||||
}
|
||||
assertNull(SystemVulkanDriver.findRenderNode(null) { false })
|
||||
}
|
||||
|
||||
@Test fun listedRenderNodesCoverExtendedMinorNumbers() {
|
||||
assertEquals("/dev/dri/renderD256", SystemVulkanDriver.findRenderNode(
|
||||
arrayOf("card0", "renderD256", "renderD128/device", "../renderD129"),
|
||||
) { path ->
|
||||
assertTrue(path, path.matches(Regex("/dev/dri/renderD[0-9]+")))
|
||||
path == "/dev/dri/renderD256"
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun defaultPowerVrResolvesToTheSystemIcd() {
|
||||
assertEquals("system/icd.json", LinuxVulkanDriver.resolveIcdPath("", true,
|
||||
{ "system/icd.json" }, { error("default must not resolve an import") }))
|
||||
}
|
||||
|
||||
@Test fun defaultAdrenoLeavesTheRuntimeIcdUnchanged() {
|
||||
assertNull(LinuxVulkanDriver.resolveIcdPath("", false,
|
||||
{ error("Adreno must not prepare the system bridge") }, { error("default must not resolve an import") }))
|
||||
}
|
||||
|
||||
@Test fun missingManualPowerVrImportFailsWithoutSwitchingBackends() {
|
||||
val failure = assertThrows(IllegalStateException::class.java) {
|
||||
LinuxVulkanDriver.resolveIcdPath("missing-driver", true,
|
||||
{ error("manual preference must not silently switch to the system backend") }, { null })
|
||||
}
|
||||
assertTrue(failure.message!!.contains("missing-driver"))
|
||||
assertTrue(failure.message!!.contains("use Auto"))
|
||||
}
|
||||
|
||||
@Test fun missingAdrenoImportKeepsTheExistingRuntimeFallback() {
|
||||
assertNull(LinuxVulkanDriver.resolveIcdPath("missing-driver", false,
|
||||
{ error("Adreno must not prepare the system bridge") }, { null }))
|
||||
}
|
||||
|
||||
@Test fun manualPowerVrResolvesTheChosenImport() {
|
||||
assertEquals("imports/chosen/icd.json", LinuxVulkanDriver.resolveIcdPath("chosen", true,
|
||||
{ error("manual must not prepare the system bridge") }, { "imports/$it/icd.json" }))
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,32 @@ class DroidDeckHudPanelTest {
|
||||
assertEquals("1", DroidDeckHudConfig.DEFAULTS["hudLocked"])
|
||||
}
|
||||
|
||||
@Test fun lowMetricsCanBeHiddenIndependentlyInEveryLayoutThatShowsThem() {
|
||||
val metrics = listOf("showLow1" to "1%", "showLow01" to "0.1%", "showLow001" to "0.01%")
|
||||
for (size in DroidDeckHudSize.values().filter { it != DroidDeckHudSize.PILL }) {
|
||||
for (mask in 0..7) {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val parent = FrameLayout(app)
|
||||
val view = DroidDeckHudView(app)
|
||||
parent.addView(view)
|
||||
parent.layout(0, 0, 4000, 1080)
|
||||
val settings = metrics.mapIndexed { index, (key, _) ->
|
||||
key to if (mask and (1 shl index) != 0) "1" else "0"
|
||||
}.toMap()
|
||||
view.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS +
|
||||
("hudSize" to size.token) + settings))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val lines = view.linesForTest().joinToString(" ")
|
||||
for ((index, metric) in metrics.withIndex()) {
|
||||
val supported = size != DroidDeckHudSize.TILES || index == 0
|
||||
val expected = supported && mask and (1 shl index) != 0
|
||||
val label = Regex("(?<![0-9.])${Regex.escape(metric.second)}")
|
||||
assertEquals("$size, mask=$mask, ${metric.second}: $lines", expected, label.containsMatchIn(lines))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], manifest = Config.NONE)
|
||||
class MouseBackInputTest {
|
||||
private val presses = mutableListOf<Boolean>()
|
||||
private var mouse = true
|
||||
private val input = MouseBackInput(presses::add) { mouse }
|
||||
|
||||
private fun key(action: Int, source: Int = InputDevice.SOURCE_MOUSE, device: Int = 7, repeat: Int = 0,
|
||||
code: Int = KeyEvent.KEYCODE_BACK, flags: Int = 0) =
|
||||
KeyEvent(0L, 0L, action, code, repeat, 0, device, 0, flags, source)
|
||||
|
||||
/** What REDMAGIC's cast mode sends for a right click, as logged on an NX789J. */
|
||||
private fun injected(action: Int, repeat: Int = 0) = key(action, source = InputDevice.SOURCE_KEYBOARD,
|
||||
device = KeyCharacterMap.VIRTUAL_KEYBOARD, repeat = repeat, flags = KeyEvent.FLAG_FROM_SYSTEM)
|
||||
|
||||
/** What the navigation bar and back gesture send, as logged on the same phone. */
|
||||
private fun navigationBar(action: Int) = key(action, source = InputDevice.SOURCE_KEYBOARD,
|
||||
device = KeyCharacterMap.VIRTUAL_KEYBOARD, flags = KeyEvent.FLAG_FROM_SYSTEM or KeyEvent.FLAG_VIRTUAL_HARD_KEY)
|
||||
|
||||
@Test fun mouseBackBecomesTheRightButton() {
|
||||
assertTrue(input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = true))
|
||||
assertTrue(input.onKeyEvent(key(KeyEvent.ACTION_UP), toGuest = true))
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun holdingTheButtonSwallowsRepeatsWithoutPressingAgain() {
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
repeat(3) { assertTrue(input.onKeyEvent(key(KeyEvent.ACTION_DOWN, repeat = it + 1), toGuest = true)) }
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_UP), toGuest = true)
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun relativeMouseBackAlsoBecomesTheRightButton() {
|
||||
assertTrue(input.onKeyEvent(key(KeyEvent.ACTION_DOWN, source = InputDevice.SOURCE_MOUSE_RELATIVE), toGuest = true))
|
||||
assertEquals(listOf(true), presses)
|
||||
}
|
||||
|
||||
@Test fun injectedBackBecomesTheRightButtonWhileAMouseIsConnected() {
|
||||
assertTrue(input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true))
|
||||
assertTrue(input.onKeyEvent(injected(KeyEvent.ACTION_DOWN, repeat = 1), toGuest = true))
|
||||
assertTrue(input.onKeyEvent(injected(KeyEvent.ACTION_UP), toGuest = true))
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun injectedBackStaysBackWithoutAMouse() {
|
||||
mouse = false
|
||||
assertFalse(input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true))
|
||||
assertFalse(input.onKeyEvent(injected(KeyEvent.ACTION_UP), toGuest = true))
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun navigationBarBackStaysBackEvenWithAMouse() {
|
||||
for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) {
|
||||
assertFalse(input.onKeyEvent(navigationBar(action), toGuest = true))
|
||||
}
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun navigationBarBackWhileAnInjectedBackIsHeldStaysBack() {
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
assertFalse(input.onKeyEvent(navigationBar(KeyEvent.ACTION_DOWN), toGuest = true))
|
||||
assertFalse(input.onKeyEvent(navigationBar(KeyEvent.ACTION_UP), toGuest = true))
|
||||
assertEquals(listOf(true), presses)
|
||||
assertTrue(input.onKeyEvent(injected(KeyEvent.ACTION_UP), toGuest = true))
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun overlappingPressesHoldTheButtonUntilTheLastRelease() {
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_UP), toGuest = true)
|
||||
assertEquals(listOf(true), presses)
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_UP), toGuest = true)
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun anUnrelatedDeviceDisconnectingKeepsTheButtonHeld() {
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
input.onDeviceRemoved(9)
|
||||
assertEquals(listOf(true), presses)
|
||||
}
|
||||
|
||||
@Test fun theMouseDisconnectingReleasesItsPress() {
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
input.onDeviceRemoved(7)
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun theLastMouseDisconnectingReleasesAnInjectedPress() {
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
mouse = false
|
||||
input.onDeviceRemoved(7)
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun cancelReleasesAHeldPressOnce() {
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
input.cancel()
|
||||
assertEquals(listOf(true, false), presses)
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_UP), toGuest = true)
|
||||
input.cancel()
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun controllerBackStaysBack() {
|
||||
val source = InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_KEYBOARD
|
||||
assertFalse(input.onKeyEvent(key(KeyEvent.ACTION_DOWN, source = source), toGuest = true))
|
||||
assertFalse(input.onKeyEvent(key(KeyEvent.ACTION_UP, source = source), toGuest = true))
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun otherMouseKeysAreLeftAlone() {
|
||||
assertFalse(input.onKeyEvent(key(KeyEvent.ACTION_DOWN, code = KeyEvent.KEYCODE_FORWARD), toGuest = true))
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun mouseBackStaysBackWhileAMenuIsOpen() {
|
||||
assertFalse(input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = false))
|
||||
assertFalse(input.onKeyEvent(key(KeyEvent.ACTION_DOWN, repeat = 1), toGuest = false))
|
||||
assertFalse(input.onKeyEvent(key(KeyEvent.ACTION_UP), toGuest = false))
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aMenuOpeningMidPressStillReleasesTheButton() {
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
assertTrue(input.onKeyEvent(key(KeyEvent.ACTION_UP), toGuest = false))
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun theMouseDisconnectingMidPressStillReleasesTheButton() {
|
||||
input.onKeyEvent(injected(KeyEvent.ACTION_DOWN), toGuest = true)
|
||||
mouse = false
|
||||
assertTrue(input.onKeyEvent(injected(KeyEvent.ACTION_UP), toGuest = true))
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun aMenuClosingMidPressLeavesTheReleaseToTheMenu() {
|
||||
input.onKeyEvent(key(KeyEvent.ACTION_DOWN), toGuest = false)
|
||||
assertFalse(input.onKeyEvent(key(KeyEvent.ACTION_UP), toGuest = true))
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,11 @@ import kotlin.math.sqrt
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Rect
|
||||
import android.view.DisplayCutout
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import android.widget.FrameLayout
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
@@ -191,6 +194,7 @@ class OnScreenControlsTest {
|
||||
val x = value(left, "cx")
|
||||
val y = value(left, "cy")
|
||||
assertNotEquals(0, pixel(x, y))
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (0f to y)))
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
|
||||
touch(MotionEvent.ACTION_DOWN, 1 to (x + 10f to y))
|
||||
assertEquals(x, value(left, "ax"), 0f)
|
||||
@@ -211,19 +215,62 @@ class OnScreenControlsTest {
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
|
||||
}
|
||||
|
||||
@Test fun adaptiveActivationIsLimitedToExpandedSavedCircle() {
|
||||
@Test fun adaptiveActivationKeepsItsVerticalAndInwardLimits() {
|
||||
val left = control("ls")
|
||||
val x = value(left, "cx")
|
||||
val y = value(left, "cy")
|
||||
val reach = value(left, "radius") * 1.4f * sqrt(1.5f)
|
||||
val reach = activationReach(left)
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach - 1f)))
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach + 1f)))
|
||||
assertEquals(y - reach + 1f, value(left, "ay"), 0.001f)
|
||||
touch(MotionEvent.ACTION_UP, 1 to (x to y - reach + 1f))
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x - reach to y - reach)))
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x + reach to y - reach)))
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
|
||||
}
|
||||
|
||||
@Test fun leftAdaptiveStickCanStartAtTheLeftEdgeAndReleaseNormally() {
|
||||
val left = control("ls")
|
||||
val y = value(left, "cy")
|
||||
val reach = activationReach(left)
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (0f to y - reach - 1f)))
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (0f to y)))
|
||||
assertEquals(1, field(left, "pressedBy"))
|
||||
assertEquals(0f, value(left, "ax"), 0f)
|
||||
assertEquals(0f, value(left, "kx"), 0f)
|
||||
touch(MotionEvent.ACTION_MOVE, 1 to (30f to y))
|
||||
assertEquals(30f, value(left, "kx"), 0f)
|
||||
touch(MotionEvent.ACTION_CANCEL, 1 to (30f to y))
|
||||
assertEquals(-1, field(left, "pressedBy"))
|
||||
assertEquals(0f, value(left, "kx"), 0f)
|
||||
assertEquals(-1, field(control("rs"), "pressedBy"))
|
||||
}
|
||||
|
||||
@Test fun rightAdaptiveStickKeepsItsSavedActivationCircle() {
|
||||
val right = control("rs")
|
||||
val x = value(right, "cx")
|
||||
val y = value(right, "cy")
|
||||
val reach = activationReach(right)
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (1199f to y)))
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x + reach + 1f to y)))
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x + reach - 1f to y)))
|
||||
assertEquals(1, field(right, "pressedBy"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@Config(sdk = [30])
|
||||
@Suppress("DEPRECATION")
|
||||
fun leftActivationStopsAtTheSafeCutoutEdge() {
|
||||
val insets = WindowInsets.Builder()
|
||||
.setDisplayCutout(DisplayCutout(Rect(24, 0, 0, 0), listOf(Rect(0, 380, 24, 420))))
|
||||
.build()
|
||||
view.dispatchApplyWindowInsets(insets)
|
||||
val left = control("ls")
|
||||
val y = value(left, "cy")
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (23f to y)))
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (24f to y)))
|
||||
assertEquals(1, field(left, "pressedBy"))
|
||||
}
|
||||
|
||||
@Test fun touchesOutsideActivationAreasStayWithTrackpad() {
|
||||
val received = mutableListOf<Int>()
|
||||
val trackpad = View(context).apply {
|
||||
@@ -301,8 +348,7 @@ class OnScreenControlsTest {
|
||||
val edge = value(button, "cy") - radius * if (id == "rb") 1.05f else 1.25f
|
||||
val x = value(button, "cx")
|
||||
val left = control("ls")
|
||||
left.javaClass.getDeclaredField("cx").apply { isAccessible = true }.setFloat(left, x)
|
||||
left.javaClass.getDeclaredField("cy").apply { isAccessible = true }.setFloat(left, edge - 10f)
|
||||
moveControl(left, x, edge - 10f)
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 4f)))
|
||||
assertEquals(-1, field(left, "pressedBy"))
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 6f)))
|
||||
@@ -311,6 +357,22 @@ class OnScreenControlsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun leftExtensionKeepsButtonPriorityAndClearance() {
|
||||
val button = control("left")
|
||||
val x = value(button, "cx")
|
||||
val y = value(button, "cy")
|
||||
val edge = y - value(button, "radius") * 1.25f
|
||||
val left = control("ls")
|
||||
moveControl(left, x + 200f, y)
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to y)))
|
||||
assertEquals(1, field(button, "pressedBy"))
|
||||
assertEquals(-1, field(left, "pressedBy"))
|
||||
touch(MotionEvent.ACTION_UP, 1 to (x to y))
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 4f)))
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 6f)))
|
||||
assertEquals(1, field(left, "pressedBy"))
|
||||
}
|
||||
|
||||
private fun control(id: String): Any = (field(view, "controls") as List<*>).first { field(it!!, "id") == id }!!
|
||||
private fun editor() {
|
||||
view = OnScreenControls(context, null, editing = true)
|
||||
@@ -384,6 +446,13 @@ class OnScreenControlsTest {
|
||||
private fun nullableFloat(owner: Any, name: String) = owner.javaClass.getDeclaredField(name).apply { isAccessible = true }.get(owner) as Float?
|
||||
private fun value(owner: Any, name: String) = field(owner, name) as Float
|
||||
|
||||
private fun activationReach(control: Any) = value(control, "radius") * 1.4f * sqrt(1.5f)
|
||||
|
||||
private fun moveControl(control: Any, x: Float, y: Float) {
|
||||
control.javaClass.getDeclaredField("cx").apply { isAccessible = true }.setFloat(control, x)
|
||||
control.javaClass.getDeclaredField("cy").apply { isAccessible = true }.setFloat(control, y)
|
||||
}
|
||||
|
||||
private fun pixel(x: Float, y: Float): Int {
|
||||
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(bitmap))
|
||||
|
||||
@@ -582,13 +582,79 @@ class PadBridgeQamTest {
|
||||
bridge.setInputProfile(profile)
|
||||
}
|
||||
|
||||
@Test fun zeroDeadZoneDriftDoesNotKeepAxesBlockedAfterBackRelease() {
|
||||
val device = controller()
|
||||
bridge.setStickDeadZone(0)
|
||||
motion(device, MotionEvent.AXIS_X, 0.01f)
|
||||
bridge.setBackQamPressed(true)
|
||||
advanceTime()
|
||||
bridge.setBackQamPressed(false)
|
||||
advanceTime()
|
||||
motion(device, MotionEvent.AXIS_X, 0.5f)
|
||||
assertEquals(0.5f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun circularDiagonalDriftDoesNotKeepAxesBlockedAfterBackRelease() {
|
||||
val device = controller()
|
||||
motion(device, MotionEvent.AXIS_X to 0.09f, MotionEvent.AXIS_Y to 0.09f)
|
||||
bridge.setBackQamPressed(true)
|
||||
advanceTime()
|
||||
bridge.setBackQamPressed(false)
|
||||
advanceTime()
|
||||
motion(device, MotionEvent.AXIS_X, 0.5f)
|
||||
assertEquals(0.5f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun changingPreferenceDoesNotBypassARequiredPhysicalNeutralReturn() {
|
||||
val device = controller()
|
||||
bridge.setStickDeadZone(25)
|
||||
motion(device, MotionEvent.AXIS_X, 0.2f)
|
||||
bridge.setBackQamPressed(true)
|
||||
advanceTime()
|
||||
bridge.setBackQamPressed(false)
|
||||
advanceTime()
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0f, pad().leftX)
|
||||
motion(device, MotionEvent.AXIS_X, 0.05f)
|
||||
motion(device, MotionEvent.AXIS_X, 0.5f)
|
||||
assertEquals(0.5f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun smallVirtualStickInputStillRequiresItsOriginalNeutralRelease() {
|
||||
bridge.applyExternal({ it.leftX = 0.01f }, true)
|
||||
bridge.setBackQamPressed(true)
|
||||
advanceTime()
|
||||
bridge.setBackQamPressed(false)
|
||||
advanceTime()
|
||||
bridge.applyExternal({ it.leftX = 0.5f }, true)
|
||||
assertEquals(0f, pad().leftX)
|
||||
bridge.applyExternal({ it.leftX = 0f }, true)
|
||||
bridge.applyExternal({ it.leftX = 0.5f }, true)
|
||||
assertEquals(0.5f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun smallTriggerInputStillRequiresItsOriginalNeutralRelease() {
|
||||
bridge.applyExternal({ it.leftTrigger = 0.01f }, true)
|
||||
bridge.setBackQamPressed(true)
|
||||
advanceTime()
|
||||
bridge.setBackQamPressed(false)
|
||||
advanceTime()
|
||||
bridge.applyExternal({ it.leftTrigger = 0.5f }, true)
|
||||
assertEquals(0f, pad().leftTrigger)
|
||||
bridge.applyExternal({ it.leftTrigger = 0f }, true)
|
||||
bridge.applyExternal({ it.leftTrigger = 0.5f }, true)
|
||||
assertEquals(0.5f, pad().leftTrigger)
|
||||
}
|
||||
|
||||
private fun key(device: InputDevice, code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0, scan: Int = 0) =
|
||||
KeyEvent(0L, 0L, action, code, repeat, 0, device.id, scan, 0, InputDevice.SOURCE_GAMEPAD)
|
||||
|
||||
private fun motion(device: InputDevice, axis: Int, value: Float) {
|
||||
private fun motion(device: InputDevice, axis: Int, value: Float) = motion(device, axis to value)
|
||||
|
||||
private fun motion(device: InputDevice, vararg values: Pair<Int, Float>) {
|
||||
val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1,
|
||||
arrayOf(MotionEvent.PointerProperties().apply { id = 0 }),
|
||||
arrayOf(MotionEvent.PointerCoords().apply { setAxisValue(axis, value) }),
|
||||
arrayOf(MotionEvent.PointerCoords().apply { for ((axis, value) in values) setAxisValue(axis, value) }),
|
||||
0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0)
|
||||
try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.graphics.RectF
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class PointerSpaceTest {
|
||||
private val phonePicture = RectF(0f, 896f, 1080f, 1503f)
|
||||
|
||||
@Test fun theGlassesMakeTheWholeViewThePointerArea() {
|
||||
assertEquals(RectF(0f, 0f, 1080f, 2400f),
|
||||
PointerSpace.area(1080, 2400, glassesOwnOutput = true, phonePicture))
|
||||
}
|
||||
|
||||
@Test fun theViewThatShowsThePictureUsesItsPictureRect() {
|
||||
assertSame(phonePicture, PointerSpace.area(2400, 1504, glassesOwnOutput = false, phonePicture))
|
||||
}
|
||||
|
||||
@Test fun aViewWithoutSizeHasNoPointerArea() {
|
||||
assertNull(PointerSpace.area(0, 2400, glassesOwnOutput = true, phonePicture))
|
||||
assertNull(PointerSpace.area(1080, 0, glassesOwnOutput = false, phonePicture))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.hardware.input.InputManager
|
||||
import android.os.Looper
|
||||
import android.util.SparseArray
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import java.nio.file.Files
|
||||
import java.time.Duration
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.InputDeviceBuilder
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
|
||||
shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class, PadBridgeRoutingTest.RegisteredMotionEvent::class,
|
||||
JoyConPadTest.RecordingWriter::class])
|
||||
class StickDeadZoneTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private val directory = Files.createTempDirectory("stick-dead-zone").toFile()
|
||||
private lateinit var bridge: PadBridge
|
||||
|
||||
@Before fun start() {
|
||||
ControllerPrefs.prefs(context).edit().clear().commit()
|
||||
JoyConPadTest.RecordingWriter.pads.clear()
|
||||
bridge = PadBridge(directory)
|
||||
assertTrue(bridge.start())
|
||||
}
|
||||
|
||||
@After fun stop() {
|
||||
bridge.stop()
|
||||
ControllerPrefs.prefs(context).edit().clear().commit()
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun preferencesDefaultToTwelveAndPersistZero() {
|
||||
assertEquals(12, ControllerPrefs.read(context).deadZone)
|
||||
assertEquals(listOf(0, 5, 8, 12, 15, 20, 25), ControllerPrefs.deadZones)
|
||||
ControllerPrefs.setDeadZone(context, 0)
|
||||
assertEquals(0, ControllerPrefs.read(context).deadZone)
|
||||
}
|
||||
|
||||
@Test fun invalidPreferencesFallBackAndResetRestoresDefault() {
|
||||
ControllerPrefs.setDeadZone(context, 99)
|
||||
assertEquals(12, ControllerPrefs.deadZone(context))
|
||||
ControllerPrefs.setDeadZone(context, 25)
|
||||
ControllerPrefs.resetAll(context)
|
||||
assertEquals(12, ControllerPrefs.deadZone(context))
|
||||
}
|
||||
|
||||
@Test fun changingDeadZonePreservesOfficialShortcutsAndControllerSettings() {
|
||||
val button = PhysicalShortcuts.Button("test-pad", "Test pad", KeyEvent.KEYCODE_BUTTON_MODE, 0)
|
||||
val binding = PhysicalShortcuts.Binding(button, PhysicalShortcuts.Action.QAM)
|
||||
PhysicalShortcuts.assign(context, button, binding.action)
|
||||
ControllerPrefs.setTarget(context, "a", "b")
|
||||
ControllerPrefs.setRumble(context, false)
|
||||
for (percent in ControllerPrefs.deadZones) {
|
||||
ControllerPrefs.setDeadZone(context, percent)
|
||||
val settings = ControllerPrefs.read(context)
|
||||
assertEquals(percent, settings.deadZone)
|
||||
assertEquals(listOf(binding), PhysicalShortcuts.read(context))
|
||||
assertEquals("b", settings.mapping["a"])
|
||||
assertFalse(settings.rumble)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun assigningAnOfficialShortcutPreservesDeadZone() {
|
||||
ControllerPrefs.setDeadZone(context, 25)
|
||||
PhysicalShortcuts.assign(context,
|
||||
PhysicalShortcuts.Button("test-pad", "Test pad", KeyEvent.KEYCODE_BUTTON_MODE, 0),
|
||||
PhysicalShortcuts.Action.STEAM)
|
||||
assertEquals(25, ControllerPrefs.read(context).deadZone)
|
||||
}
|
||||
|
||||
@Test fun defaultSuppressesBothAxesInsideTheCircle() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.05f, MotionEvent.AXIS_Y to -0.06f)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(0f, pad().leftY)
|
||||
}
|
||||
|
||||
@Test fun diagonalOutsideTheCircleIsNotLostToAnAxisCross() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.09f, MotionEvent.AXIS_Y to -0.09f)
|
||||
assertEquals(0.09f, pad().leftX)
|
||||
assertEquals(-0.09f, pad().leftY)
|
||||
}
|
||||
|
||||
@Test fun smallCrossAxisMotionSurvivesWhenTheStickIsHeldOver() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Y to 0.02f)
|
||||
assertEquals(0.6f, pad().leftX)
|
||||
assertEquals(0.02f, pad().leftY)
|
||||
}
|
||||
|
||||
@Test fun zeroDisablesFilteringForBothSticks() {
|
||||
bridge.setStickDeadZone(0)
|
||||
motion(device(), MotionEvent.AXIS_X to 0.01f, MotionEvent.AXIS_Y to -0.02f,
|
||||
MotionEvent.AXIS_Z to 0.03f, MotionEvent.AXIS_RZ to -0.04f)
|
||||
assertEquals(0.01f, pad().leftX)
|
||||
assertEquals(-0.02f, pad().leftY)
|
||||
assertEquals(0.03f, pad().rightX)
|
||||
assertEquals(-0.04f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun changingTheSettingAffectsTheExistingBridge() {
|
||||
val device = device()
|
||||
bridge.setStickDeadZone(25)
|
||||
motion(device, MotionEvent.AXIS_X to 0.2f, MotionEvent.AXIS_Z to 0.4f)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(0.4f, pad().rightX)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.2f, pad().leftX)
|
||||
assertEquals(0.4f, pad().rightX)
|
||||
}
|
||||
|
||||
@Test fun changingPreferenceReprojectsAllSticksWithoutAnotherMotionEvent() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.2f, MotionEvent.AXIS_Y to 0.02f,
|
||||
MotionEvent.AXIS_Z to 0.03f, MotionEvent.AXIS_RZ to -0.04f)
|
||||
bridge.setStickDeadZone(25)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(0f, pad().rightY)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.2f, pad().leftX)
|
||||
assertEquals(0.02f, pad().leftY)
|
||||
assertEquals(0.03f, pad().rightX)
|
||||
assertEquals(-0.04f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun preferenceChangesReprojectEveryPlayer() {
|
||||
motion(device(id = 61), MotionEvent.AXIS_X to 0.2f)
|
||||
motion(device(id = 62), MotionEvent.AXIS_Z to -0.2f)
|
||||
bridge.setStickDeadZone(25)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(0f, requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).rightX)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.2f, pad().leftX)
|
||||
assertEquals(-0.2f, requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).rightX)
|
||||
}
|
||||
|
||||
@Test fun preferenceChangesReprojectBothHalvesOfAJoyConPair() {
|
||||
val left = device(joyCon = true, id = 61)
|
||||
val right = device(joyCon = true, id = 62, rightJoyCon = true)
|
||||
motion(left)
|
||||
motion(right)
|
||||
motion(left, MotionEvent.AXIS_X to 0.2f)
|
||||
motion(right, MotionEvent.AXIS_RX to -0.2f)
|
||||
bridge.setStickDeadZone(25)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(0f, pad().rightX)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.2f, pad().leftX)
|
||||
assertEquals(-0.2f, pad().rightX)
|
||||
}
|
||||
|
||||
@Test fun preferenceChangesDoNotReplaceTouchStickInput() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.2f, MotionEvent.AXIS_Z to -0.2f)
|
||||
bridge.applyTouch { it.leftX = 0.8f }
|
||||
bridge.setStickDeadZone(25)
|
||||
assertEquals(0.8f, pad().leftX)
|
||||
assertEquals(0f, pad().rightX)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.8f, pad().leftX)
|
||||
assertEquals(-0.2f, pad().rightX)
|
||||
}
|
||||
|
||||
@Test fun explicitZeroTouchWriteDiscardsFilteredPhysicalLeftStick() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.05f, MotionEvent.AXIS_Z to -0.05f)
|
||||
bridge.applyTouch(PadBridge.LEFT_STICK) { it.leftX = 0f; it.leftY = 0f }
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(-0.05f, pad().rightX)
|
||||
}
|
||||
|
||||
@Test fun explicitZeroTouchWriteDiscardsFilteredPhysicalRightStick() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.05f, MotionEvent.AXIS_Z to -0.05f)
|
||||
bridge.applyTouch(PadBridge.RIGHT_STICK) { it.rightX = 0f; it.rightY = 0f }
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.05f, pad().leftX)
|
||||
assertEquals(0f, pad().rightX)
|
||||
}
|
||||
|
||||
@Test fun routedTouchStickWritesKeepSeparatePhysicalInput() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.05f)
|
||||
bridge.setTouchRoute(object : PadBridge.TouchRoute {
|
||||
override fun active() = true
|
||||
override fun accept(state: PadState) { assertEquals(0f, state.leftX) }
|
||||
})
|
||||
bridge.applyTouch(PadBridge.LEFT_STICK) { it.leftX = 0f; it.leftY = 0f }
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.05f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun touchButtonOnlyWritesKeepFilteredPhysicalSticks() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.05f)
|
||||
bridge.applyTouch { it.press(PadState.A, true) }
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.05f, pad().leftX)
|
||||
assertTrue(pad().isDown(PadState.A))
|
||||
}
|
||||
|
||||
@Test fun preferenceChangesDoNotReplaceExternalStickInput() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.2f, MotionEvent.AXIS_Z to -0.2f)
|
||||
bridge.applyExternal({ it.rightX = 0.8f }, true)
|
||||
bridge.setStickDeadZone(25)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(0.8f, pad().rightX)
|
||||
}
|
||||
|
||||
@Test fun buttonAndTriggerMutationsKeepPhysicalSticksReprojectable() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.2f)
|
||||
bridge.applyExternal({ it.leftTrigger = 0.7f; it.press(PadState.X, true) }, true)
|
||||
bridge.setStickDeadZone(25)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertEquals(0.7f, pad().leftTrigger)
|
||||
assertTrue(pad().isDown(PadState.X))
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0.2f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun releaseAllDiscardsEvenPreviouslyFilteredRawMotion() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.05f)
|
||||
bridge.releaseAll()
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun aDisconnectedControllerDoesNotReturnOnPreferenceChange() {
|
||||
val device = device()
|
||||
motion(device, MotionEvent.AXIS_X to 0.2f)
|
||||
bridge.onDeviceRemoved(device.id)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun pairingDoesNotRestoreAnOldJoyConPosition() {
|
||||
val left = device(joyCon = true, id = 61)
|
||||
val right = device(joyCon = true, id = 62, rightJoyCon = true)
|
||||
motion(left, MotionEvent.AXIS_X to 0.2f)
|
||||
motion(right)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun aControllerRemovedWhileInactiveDoesNotReturnOnPreferenceChange() {
|
||||
val device = device()
|
||||
motion(device, MotionEvent.AXIS_X to 0.05f)
|
||||
val manager = ReflectionHelpers.callStaticMethod<Any>(Class.forName("android.hardware.input.InputManagerGlobal"), "getInstance")
|
||||
ReflectionHelpers.getField<SparseArray<InputDevice>>(manager, "mInputDevices").remove(device.id)
|
||||
assertNull(InputDevice.getDevice(device.id))
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun excludedControllerInputIsNotRestoredOnPreferenceChange() {
|
||||
val device = device()
|
||||
motion(device, MotionEvent.AXIS_X to 0.2f)
|
||||
bridge.setExcluded { it == device.id }
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun preferenceChangesDoNotGenerateChordInput() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.2f)
|
||||
var notifications = 0
|
||||
bridge.setOnChordInput { notifications++ }
|
||||
bridge.setStickDeadZone(25)
|
||||
bridge.setStickDeadZone(0)
|
||||
assertEquals(0, notifications)
|
||||
}
|
||||
|
||||
@Test fun aStoppedBridgeDoesNotRepublishOldInput() {
|
||||
motion(device(), MotionEvent.AXIS_X to 0.2f)
|
||||
bridge.stop()
|
||||
JoyConPadTest.RecordingWriter.pads.clear()
|
||||
bridge.setStickDeadZone(0)
|
||||
assertTrue(JoyConPadTest.RecordingWriter.pads.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun theBoundaryPassesThroughWithoutRescaling() {
|
||||
assertFalse(PadBridge.inStickDeadZone(0.12f, 0f, 0.12f))
|
||||
motion(device(), MotionEvent.AXIS_X to 0.12f)
|
||||
assertEquals(0.12f, pad().leftX)
|
||||
}
|
||||
|
||||
@Test fun wiredXboxKeepsItsRightStickAndSignedTriggerAxes() {
|
||||
bridge.setStickDeadZone(0)
|
||||
motion(device(wired = true), MotionEvent.AXIS_RX to 0.02f, MotionEvent.AXIS_RY to -0.03f,
|
||||
MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to 1f)
|
||||
assertEquals(0.02f, pad().rightX)
|
||||
assertEquals(-0.03f, pad().rightY)
|
||||
assertEquals(0f, pad().leftTrigger)
|
||||
assertEquals(1f, pad().rightTrigger)
|
||||
}
|
||||
|
||||
@Test fun joyConUsesTheSelectedDeadZone() {
|
||||
bridge.setStickDeadZone(0)
|
||||
motion(device(joyCon = true), MotionEvent.AXIS_X to 0.01f, MotionEvent.AXIS_Y to -0.02f)
|
||||
assertEquals(0.01f, pad().leftX)
|
||||
assertEquals(-0.02f, pad().leftY)
|
||||
}
|
||||
|
||||
@Test fun stickSettingDoesNotChangeMouseAxisHelpers() {
|
||||
bridge.setStickDeadZone(0)
|
||||
for (wired in listOf(false, true)) {
|
||||
var horizontal = 0f
|
||||
var vertical = 0f
|
||||
val mouse = PadMouse(object : PadMouse.Listener {
|
||||
override fun active() = true
|
||||
override fun onScrollStart() {}
|
||||
override fun onScroll(dx: Float, dy: Float) { horizontal += dx; vertical += dy }
|
||||
override fun onKey(evdev: Int, pressed: Boolean) {}
|
||||
override fun onKeyboard() {}
|
||||
override fun onNavigate() {}
|
||||
override fun scrollSpeed() = 2000f
|
||||
}) { 1000L }
|
||||
val event = if (wired) event(device(wired = true, id = 62), MotionEvent.AXIS_RX to 0.02f,
|
||||
MotionEvent.AXIS_RY to 0.6f, MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f)
|
||||
else event(device(), MotionEvent.AXIS_Z to 0.02f, MotionEvent.AXIS_RZ to 0.6f)
|
||||
try {
|
||||
assertTrue(mouse.onMotion(event))
|
||||
mouse.step(0.1f)
|
||||
assertEquals(0f, horizontal)
|
||||
assertTrue(vertical > 0f)
|
||||
} finally { event.recycle(); mouse.reset() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun zeroDeadZoneDriftDoesNotConsumeBackTap() {
|
||||
val (taps, presses) = backTapWithMotion(device(), MotionEvent.AXIS_X to 0.01f)
|
||||
assertEquals(0.01f, pad().leftX)
|
||||
assertEquals(listOf(false), taps)
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun zeroDeadZoneJoyConDriftDoesNotConsumeBackTap() {
|
||||
val (taps, presses) = backTapWithMotion(device(joyCon = true), MotionEvent.AXIS_X to 0.01f)
|
||||
assertEquals(0.01f, pad().leftX)
|
||||
assertEquals(listOf(false), taps)
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun diagonalInsideTheLegacyChordGuardDoesNotConsumeBackTap() {
|
||||
val (taps, presses) = backTapWithMotion(device(), MotionEvent.AXIS_X to 0.09f, MotionEvent.AXIS_Y to 0.09f)
|
||||
assertEquals(0.09f, pad().leftX)
|
||||
assertEquals(0.09f, pad().leftY)
|
||||
assertEquals(listOf(false), taps)
|
||||
assertTrue(presses.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun intentionalMotionOnEitherStickStillMakesABackChord() {
|
||||
val device = device()
|
||||
for (axis in intArrayOf(MotionEvent.AXIS_X, MotionEvent.AXIS_Z)) {
|
||||
val (taps, presses) = backTapWithMotion(device, axis to 0.5f)
|
||||
assertTrue(taps.isEmpty())
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun higherGameDeadZoneDoesNotDisableExistingBackChords() {
|
||||
val (taps, presses) = backTapWithMotion(device(), MotionEvent.AXIS_X to 0.2f, deadZone = 25)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertTrue(taps.isEmpty())
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
@Test fun higherGameDeadZoneDoesNotDisableExistingJoyConBackChords() {
|
||||
val (taps, presses) = backTapWithMotion(device(joyCon = true), MotionEvent.AXIS_X to 0.2f, deadZone = 25)
|
||||
assertEquals(0f, pad().leftX)
|
||||
assertTrue(taps.isEmpty())
|
||||
assertEquals(listOf(true, false), presses)
|
||||
}
|
||||
|
||||
private fun backTapWithMotion(device: InputDevice, vararg axes: Pair<Int, Float>, deadZone: Int = 0): Pair<List<Boolean>, List<Boolean>> {
|
||||
val taps = mutableListOf<Boolean>()
|
||||
val presses = mutableListOf<Boolean>()
|
||||
val input = BackQamInput(presses::add, taps::add)
|
||||
bridge.setStickDeadZone(deadZone)
|
||||
bridge.setOnChordInput(input::onChordInput)
|
||||
assertTrue(input.onKeyEvent(KeyEvent(0, 100, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK,
|
||||
0, 0, device.id, 0), true))
|
||||
motion(device, *axes)
|
||||
assertTrue(input.onKeyEvent(KeyEvent(0, 100, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK,
|
||||
0, 0, device.id, 0), true))
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500))
|
||||
return taps to presses
|
||||
}
|
||||
|
||||
@Test fun neutralScreenStickPressClearsRetainedPhysicalInput() {
|
||||
val device = device()
|
||||
for (adaptive in listOf(false, true)) {
|
||||
ControllerPrefs.setAdaptiveSticks(context, adaptive)
|
||||
ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (0.45f to 0.5f), "rs" to (0.55f to 0.5f)))
|
||||
for (id in listOf("ls", "rs")) {
|
||||
motion(device, MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Z to 0.7f)
|
||||
val view = OnScreenControls(context, bridge)
|
||||
view.layout(0, 0, 1200, 800)
|
||||
val controls = ReflectionHelpers.getField<List<Any>>(view, "controls")
|
||||
val control = controls.first { ReflectionHelpers.getField<String>(it, "id") == id }
|
||||
val x = ReflectionHelpers.getField<Float>(control, "cx")
|
||||
val y = ReflectionHelpers.getField<Float>(control, "cy")
|
||||
val down = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, x, y, 0)
|
||||
try { assertTrue(view.onTouchEvent(down)) } finally { down.recycle() }
|
||||
assertFalse(ReflectionHelpers.getField<Boolean>(control, "dirty"))
|
||||
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f)
|
||||
assertTrue((if (id == "ls") pad().rightX else pad().leftX) > 0f)
|
||||
bridge.setStickDeadZone(25)
|
||||
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f)
|
||||
motion(device, MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Z to 0.7f)
|
||||
val button = controls.first { ReflectionHelpers.getField<String>(it, "id") == "a" }
|
||||
val bx = ReflectionHelpers.getField<Float>(button, "cx")
|
||||
val by = ReflectionHelpers.getField<Float>(button, "cy")
|
||||
fun buttonTouch(action: Int, time: Long) {
|
||||
val event = MotionEvent.obtain(1000, time, action or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), 2,
|
||||
arrayOf(MotionEvent.PointerProperties().apply { this.id = 0; toolType = MotionEvent.TOOL_TYPE_FINGER },
|
||||
MotionEvent.PointerProperties().apply { this.id = 1; toolType = MotionEvent.TOOL_TYPE_FINGER }),
|
||||
arrayOf(MotionEvent.PointerCoords().apply { this.x = x; this.y = y },
|
||||
MotionEvent.PointerCoords().apply { this.x = bx; this.y = by }),
|
||||
0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
|
||||
try { assertTrue(view.onTouchEvent(event)) } finally { event.recycle() }
|
||||
}
|
||||
buttonTouch(MotionEvent.ACTION_POINTER_DOWN, 1030)
|
||||
assertTrue(pad().isDown(PadState.A))
|
||||
assertEquals(0.6f, pad().leftX, 0f)
|
||||
assertEquals(0.7f, pad().rightX, 0f)
|
||||
buttonTouch(MotionEvent.ACTION_POINTER_UP, 1060)
|
||||
assertFalse(pad().isDown(PadState.A))
|
||||
bridge.setStickDeadZone(12)
|
||||
assertEquals(0.6f, pad().leftX, 0f)
|
||||
assertEquals(0.7f, pad().rightX, 0f)
|
||||
val up = MotionEvent.obtain(1000, 1100, MotionEvent.ACTION_UP, x, y, 0)
|
||||
try { assertTrue(view.onTouchEvent(up)) } finally { up.recycle() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun pad() = requireNotNull(JoyConPadTest.RecordingWriter.pads[0])
|
||||
|
||||
private fun motion(device: InputDevice, vararg axes: Pair<Int, Float>) {
|
||||
val event = event(device, *axes)
|
||||
try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() }
|
||||
}
|
||||
|
||||
private fun event(device: InputDevice, vararg axes: Pair<Int, Float>): MotionEvent {
|
||||
val coords = MotionEvent.PointerCoords().apply { for ((axis, value) in axes) setAxisValue(axis, value) }
|
||||
return MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1,
|
||||
arrayOf(MotionEvent.PointerProperties().apply { id = 0 }), arrayOf(coords),
|
||||
0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0)
|
||||
}
|
||||
|
||||
private fun device(wired: Boolean = false, joyCon: Boolean = false, id: Int = 61, rightJoyCon: Boolean = false): InputDevice {
|
||||
val builder = InputDeviceBuilder.newBuilder().setId(id)
|
||||
.setName(if (joyCon) if (rightJoyCon) "Joy-Con (R)" else "Joy-Con (L)" else "dead-zone pad")
|
||||
.setDescriptor("dead-zone-pad-$id").setExternal(true)
|
||||
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)
|
||||
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
|
||||
.setVendorId(if (joyCon) 0x057e else if (wired) 0x20d6 else 0)
|
||||
.setProductId(if (joyCon) if (rightJoyCon) 0x2007 else 0x2006 else if (wired) 0x2063 else 0)
|
||||
for (axis in intArrayOf(MotionEvent.AXIS_X, MotionEvent.AXIS_Y, MotionEvent.AXIS_Z,
|
||||
MotionEvent.AXIS_RZ, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)) {
|
||||
builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0f, 0f, 0f)
|
||||
}
|
||||
return builder.build().also {
|
||||
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -259,6 +259,7 @@ class BattleNetTest {
|
||||
BattleNet.hostFolder(context, "Z:/root/Games/Stores/Battle.net/Hearthstone/"))
|
||||
}
|
||||
|
||||
|
||||
@Test fun wowForeverIsListedBesideRetailInTheSharedWorldOfWarcraftFolder() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
val wow = File(pfx, "drive_c/Program Files (x86)/World of Warcraft").apply { mkdirs() }
|
||||
@@ -331,6 +332,25 @@ class BattleNetTest {
|
||||
assertEquals(listOf(File(wow, "_forever_"), wow), BattleNet.games(context).map { it.folder })
|
||||
}
|
||||
|
||||
@Test fun aGameInstalledUnderBlizzardsChineseUidIsStillListed() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
|
||||
field(1, message(field(1, "osic"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo II Resurrected"))))),
|
||||
field(1, message(field(1, "s2_cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II"))))),
|
||||
))
|
||||
for (folder in listOf("Diablo II Resurrected", "StarCraft II")) {
|
||||
File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/$folder").mkdirs()
|
||||
}
|
||||
val games = BattleNet.games(context)
|
||||
assertEquals(listOf("osic", "s2_cn"), games.map { it.installUid })
|
||||
assertEquals(listOf("osi", "s2"), games.map { it.uid })
|
||||
assertEquals(listOf("Diablo II: Resurrected" to "OSI", "StarCraft II" to "S2"), games.map { it.name to it.code })
|
||||
assertFalse(BattleNet.notInstalled(BattleNet.title("osi")!!, listOf("osic")))
|
||||
assertFalse(BattleNet.notInstalled(BattleNet.title("s2")!!, games.map { it.installUid }))
|
||||
|
||||
}
|
||||
|
||||
@Test fun aGamesShortcutHasBattleNetLaunchItInItsPrefix() {
|
||||
val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() }
|
||||
File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a))
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.net.IpPrefix
|
||||
import android.net.LinkAddress
|
||||
import android.net.LinkProperties
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.RouteInfo
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import java.net.InetAddress
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
import org.robolectric.util.ReflectionHelpers.ClassParameter.from
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28, 34], manifest = Config.NONE)
|
||||
class LinuxNetworkLinkComponentTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
|
||||
private fun capabilities(vpn: Boolean = true, internet: Boolean = true) = NetworkCapabilities().apply {
|
||||
ReflectionHelpers.callInstanceMethod<NetworkCapabilities>(this, "addTransportType",
|
||||
from(Int::class.javaPrimitiveType, if (vpn) NetworkCapabilities.TRANSPORT_VPN else NetworkCapabilities.TRANSPORT_WIFI))
|
||||
if (internet) ReflectionHelpers.callInstanceMethod<NetworkCapabilities>(this, "addCapability",
|
||||
from(Int::class.javaPrimitiveType, NetworkCapabilities.NET_CAPABILITY_INTERNET))
|
||||
}
|
||||
|
||||
private fun properties(vararg addresses: String) = LinkProperties().apply {
|
||||
interfaceName = "tun0"
|
||||
addresses.forEach {
|
||||
val address = ReflectionHelpers.callConstructor<LinkAddress>(LinkAddress::class.java,
|
||||
from(InetAddress::class.java, InetAddress.getByName(it.substringBefore('/'))),
|
||||
from(Int::class.javaPrimitiveType, it.substringAfter('/').toInt()))
|
||||
ReflectionHelpers.callInstanceMethod<Boolean>(this, "addLinkAddress", from(LinkAddress::class.java, address))
|
||||
}
|
||||
}
|
||||
|
||||
private fun LinkProperties.route(destination: String, prefix: Int, gateway: String = "0.0.0.0",
|
||||
type: Int = RouteInfo.RTN_UNICAST) = apply {
|
||||
addRoute(ReflectionHelpers.callConstructor<RouteInfo>(RouteInfo::class.java,
|
||||
from(IpPrefix::class.java, IpPrefix(InetAddress.getByName(destination), prefix)),
|
||||
from(InetAddress::class.java, InetAddress.getByName(gateway)),
|
||||
from(String::class.java, interfaceName),
|
||||
from(Int::class.javaPrimitiveType, type)))
|
||||
}
|
||||
|
||||
private fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?) =
|
||||
LinuxNetworkLinkComponent.gateways(properties, capabilities).map { it.hostAddress }
|
||||
|
||||
@Test fun vpnWithOnLinkDefaultRouteHasNonzeroCompatibilityGateway() {
|
||||
val link = properties("10.0.0.1/24").route("0.0.0.0", 0)
|
||||
assertEquals(listOf("10.0.0.1"), gateways(link, capabilities()))
|
||||
}
|
||||
|
||||
@Test fun vpnWithSplitRoutesHasCompatibilityGatewayWithoutDefaultRoute() {
|
||||
val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1)
|
||||
assertEquals(listOf("10.0.0.1"), gateways(link, capabilities()))
|
||||
assertTrue(link.routes.none { it.isDefaultRoute })
|
||||
assertTrue(link.routes.all { it.gateway!!.isAnyLocalAddress })
|
||||
}
|
||||
|
||||
@Test fun realDefaultGatewayIsPreservedEvenForVpn() {
|
||||
val link = properties("10.0.0.2/24").route("0.0.0.0", 0, "10.0.0.1")
|
||||
assertEquals(listOf("10.0.0.1"), gateways(link, capabilities()))
|
||||
}
|
||||
|
||||
@Test fun wifiDefaultGatewayIsUnchanged() {
|
||||
val link = properties("192.168.1.2/24").route("0.0.0.0", 0, "192.168.1.1")
|
||||
assertEquals(listOf("192.168.1.1"), gateways(link, capabilities(vpn = false)))
|
||||
}
|
||||
|
||||
@Test fun nonVpnLinkWithoutGatewayDoesNotBecomeInternetConnected() {
|
||||
val link = properties("192.168.1.2/24").route("0.0.0.0", 0)
|
||||
assertTrue(gateways(link, capabilities(vpn = false)).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun vpnWithoutInternetCapabilityDoesNotGetGateway() {
|
||||
val link = properties("10.0.0.1/24").route("0.0.0.0", 0)
|
||||
assertTrue(gateways(link, capabilities(internet = false)).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun missingNetworkOrCapabilitiesDoesNotGetGateway() {
|
||||
val link = properties("10.0.0.1/24").route("0.0.0.0", 0)
|
||||
assertTrue(gateways(null, capabilities()).isEmpty())
|
||||
assertTrue(gateways(link, null).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun vpnWithoutRoutesDoesNotGetGateway() {
|
||||
assertTrue(gateways(properties("10.0.0.1/24"), capabilities()).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun vpnWithoutIpv4AddressDoesNotGetIpv4Gateway() {
|
||||
val link = properties("fd00::2/64").route("0.0.0.0", 0)
|
||||
assertTrue(gateways(link, capabilities()).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun vpnWithoutIpv4RoutesDoesNotGetIpv4Gateway() {
|
||||
val link = properties("10.0.0.1/24").route("::", 0, "::")
|
||||
assertTrue(gateways(link, capabilities()).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun reconnectingVpnWithRetainedAddressDoesNotGetGateway() {
|
||||
val link = properties("10.0.0.1/24").apply { interfaceName = null }
|
||||
.route("0.0.0.0", 0, type = RouteInfo.RTN_UNREACHABLE)
|
||||
.route("128.0.0.0", 1, type = RouteInfo.RTN_UNREACHABLE)
|
||||
assertTrue(gateways(link, capabilities()).isEmpty())
|
||||
val description = LinuxNetworkLinkComponent(ApplicationProvider.getApplicationContext<Context>(), temporary.root)
|
||||
.describe(link, capabilities())
|
||||
assertTrue(description.contains("addr 10.0.0.1 24\n"))
|
||||
assertFalse(description.contains("gw "))
|
||||
}
|
||||
|
||||
@Config(sdk = [34])
|
||||
@Test fun vpnWithoutUnicastIpv4RouteDoesNotGetGateway() {
|
||||
val link = properties("10.0.0.1/24")
|
||||
.route("0.0.0.0", 0, type = RouteInfo.RTN_UNREACHABLE)
|
||||
.route("10.0.0.0", 8, type = RouteInfo.RTN_THROW)
|
||||
assertTrue(gateways(link, capabilities()).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun unspecifiedLoopbackAndLinkLocalAddressesAreNotGateways() {
|
||||
val link = properties("0.0.0.0/32", "127.0.0.1/8", "169.254.1.2/16").route("0.0.0.0", 0)
|
||||
assertTrue(gateways(link, capabilities()).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun ipv6DefaultGatewayIsPreservedAlongsideVpnIpv4Gateway() {
|
||||
val link = properties("10.0.0.1/24", "fd00::2/64")
|
||||
.route("0.0.0.0", 0).route("::", 0, "fe80::1")
|
||||
assertEquals(listOf(InetAddress.getByName("10.0.0.1"), InetAddress.getByName("fe80::1")),
|
||||
LinuxNetworkLinkComponent.gateways(link, capabilities()))
|
||||
}
|
||||
|
||||
@Test fun publishedLinkContainsGatewayAndKeepsVpnInterfaceAndAddress() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val component = LinuxNetworkLinkComponent(context, temporary.root)
|
||||
val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1)
|
||||
val before = ReflectionHelpers.callConstructor<LinkProperties>(LinkProperties::class.java, from(LinkProperties::class.java, link))
|
||||
val description = component.describe(link, capabilities())
|
||||
assertTrue(description.contains("if tun0 2 1500\n"))
|
||||
assertTrue(description.contains("addr 10.0.0.1 24\n"))
|
||||
assertTrue(description.contains("gw 10.0.0.1\n"))
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(component, "write",
|
||||
from(LinkProperties::class.java, link), from(NetworkCapabilities::class.java, capabilities()))
|
||||
assertEquals(description, temporary.root.resolve("etc/droiddeck-net").readText())
|
||||
val state = org.json.JSONObject(temporary.root.resolve("etc/droiddeck-network.json").readText())
|
||||
assertEquals("tun0", state.getString("interface"))
|
||||
assertEquals("vpn", state.getString("transport"))
|
||||
assertEquals(listOf("10.0.0.1"), (0 until state.getJSONArray("gateways").length()).map {
|
||||
state.getJSONArray("gateways").getString(it)
|
||||
})
|
||||
assertEquals(before, link)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
class WowAddonsTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private fun zip(vararg files: Pair<String, String>): File {
|
||||
val file = temp.newFile("addon-${System.nanoTime()}.zip")
|
||||
ZipOutputStream(file.outputStream()).use { out ->
|
||||
for ((name, text) in files) {
|
||||
out.putNextEntry(ZipEntry(name))
|
||||
out.write(text.toByteArray())
|
||||
out.closeEntry()
|
||||
}
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
private fun target(): WowAddons.Target {
|
||||
val root = temp.newFolder("World of Warcraft")
|
||||
File(root, "_retail_").mkdirs()
|
||||
return WowAddons.targets(BattleNet.title("wow")!!, root).single()
|
||||
}
|
||||
|
||||
private fun names(vararg files: String) = WowAddons.addons(files.toList()).map { it.name to it.root }
|
||||
|
||||
@Test fun plainFoldersKeepTheirNames() {
|
||||
assertEquals(listOf("Foo" to "Foo/", "Bar" to "Bar/"), names("Foo/Foo.toc", "Foo/a.lua", "Bar/Bar.toc"))
|
||||
}
|
||||
|
||||
@Test fun flavourTocsKeepTheFolderName() {
|
||||
assertEquals(listOf("Foo" to "Foo/"), names("Foo/Foo_Mainline.toc", "Foo/Foo_Vanilla.toc", "Foo/Foo-Classic.toc"))
|
||||
}
|
||||
|
||||
@Test fun anAddonNamedLikeAFlavourStaysWhole() {
|
||||
assertEquals(listOf("Foo_Classic" to "Foo_Classic/"), names("Foo_Classic/Foo_Classic.toc"))
|
||||
}
|
||||
|
||||
@Test fun sourceWrappersTakeTheTocName() {
|
||||
assertEquals(listOf("Foo" to "Foo-main/"), names("Foo-main/Foo.toc", "Foo-main/README.md"))
|
||||
assertEquals(listOf("Foo" to "Repo-1.2.3/"), names("Repo-1.2.3/Foo_Mainline.toc", "Repo-1.2.3/Foo_TBC.toc"))
|
||||
}
|
||||
|
||||
@Test fun packsAndGameFolderWrappersFindEveryAddon() {
|
||||
assertEquals(
|
||||
listOf("Foo" to "Interface/AddOns/Foo/", "Bar" to "Interface/AddOns/Bar/"),
|
||||
names("Interface/AddOns/Foo/Foo.toc", "Interface/AddOns/Bar/Bar.toc"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun bareFilesGetAFolder() {
|
||||
assertEquals(listOf("Foo" to ""), names("Foo.toc", "core.lua"))
|
||||
}
|
||||
|
||||
@Test fun nestedTocsBelongToTheirAddon() {
|
||||
assertEquals(listOf("Foo" to "Foo/"), names("Foo/Foo.toc", "Foo/Libs/Lib/Lib.toc"))
|
||||
}
|
||||
|
||||
@Test fun anAddonInTheFolderOfASimilarNameIsNotNested() {
|
||||
assertEquals(listOf("Foo" to "Foo/", "FooOptions" to "FooOptions/"), names("Foo/Foo.toc", "FooOptions/FooOptions.toc"))
|
||||
}
|
||||
|
||||
@Test fun importsIntoInterfaceAddOns() {
|
||||
val target = target()
|
||||
val zip = zip("Foo-main/Foo.toc" to "toc", "Foo-main/sub/a.lua" to "lua", "__MACOSX/Foo-main/._Foo.toc" to "x")
|
||||
assertEquals(listOf("Foo"), WowAddons.import(zip, target))
|
||||
assertEquals(File(target.addOns.parentFile, "AddOns"), target.addOns)
|
||||
assertEquals("lua", File(target.addOns, "Foo/sub/a.lua").readText())
|
||||
assertEquals(listOf("Foo"), WowAddons.installed(target))
|
||||
assertEquals(listOf("AddOns"), target.addOns.parentFile!!.list()!!.toList())
|
||||
}
|
||||
|
||||
@Test fun reimportReplacesTheFolderIgnoringCase() {
|
||||
val target = target()
|
||||
File(target.addOns, "foo").mkdirs()
|
||||
File(target.addOns, "foo/stale.lua").writeText("old")
|
||||
File(target.addOns, "Keep").mkdirs()
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "new"), target)
|
||||
assertTrue(File(target.addOns, "Foo/Foo.toc").isFile)
|
||||
assertFalse(File(target.addOns, "foo").exists())
|
||||
assertTrue(File(target.addOns, "Keep").isDirectory)
|
||||
}
|
||||
|
||||
@Test fun replacingALinkLeavesItsTargetAlone() {
|
||||
val target = target()
|
||||
val outside = temp.newFolder("outside")
|
||||
File(outside, "keep.lua").writeText("keep")
|
||||
target.addOns.mkdirs()
|
||||
Files.createSymbolicLink(File(target.addOns, "Foo").toPath(), outside.toPath())
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "new"), target)
|
||||
assertEquals("keep", File(outside, "keep.lua").readText())
|
||||
assertFalse(Files.isSymbolicLink(File(target.addOns, "Foo").toPath()))
|
||||
}
|
||||
|
||||
@Test fun deletesOnlyTheChosenAddon() {
|
||||
val target = target()
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "a", "Bar/Bar.toc" to "b"), target)
|
||||
assertEquals(listOf("Bar", "Foo"), WowAddons.installed(target))
|
||||
WowAddons.delete(target, "Foo")
|
||||
assertEquals(listOf("Bar"), WowAddons.installed(target))
|
||||
assertTrue(File(target.addOns, "Bar/Bar.toc").isFile)
|
||||
}
|
||||
|
||||
@Test fun deletingALinkLeavesItsTargetAlone() {
|
||||
val target = target()
|
||||
val outside = temp.newFolder("linked")
|
||||
File(outside, "keep.lua").writeText("keep")
|
||||
target.addOns.mkdirs()
|
||||
Files.createSymbolicLink(File(target.addOns, "Foo").toPath(), outside.toPath())
|
||||
WowAddons.delete(target, "Foo")
|
||||
assertFalse(Files.exists(File(target.addOns, "Foo").toPath(), LinkOption.NOFOLLOW_LINKS))
|
||||
assertEquals("keep", File(outside, "keep.lua").readText())
|
||||
}
|
||||
|
||||
@Test fun onlyAFolderDirectlyInAddOnsCanBeDeleted() {
|
||||
val target = target()
|
||||
val outside = File(target.addOns.parentFile!!.parentFile, "Outside").apply { mkdirs() }
|
||||
target.addOns.mkdirs()
|
||||
assertThrows(IOException::class.java) { WowAddons.delete(target, "../../Outside") }
|
||||
assertTrue(outside.isDirectory)
|
||||
}
|
||||
|
||||
@Test fun aFailedReplacementRestoresEarlierAddons() {
|
||||
val base = temp.newFolder("swap")
|
||||
val addOns = File(base, "AddOns").apply { mkdirs() }
|
||||
File(addOns, "Foo").mkdirs()
|
||||
File(addOns, "Foo/old.lua").writeText("old")
|
||||
File(addOns, "Bar").mkdirs()
|
||||
File(addOns, "Bar/old.lua").writeText("old")
|
||||
val fresh = File(base, "fresh/Foo").apply { mkdirs() }
|
||||
File(fresh, "new.lua").writeText("new")
|
||||
val old = File(base, "old").apply { mkdirs() }
|
||||
assertThrows(IOException::class.java) {
|
||||
WowAddons.swap(listOf(fresh to "Foo", File(base, "fresh/Missing") to "Bar"), addOns, old)
|
||||
}
|
||||
assertEquals("old", File(addOns, "Foo/old.lua").readText())
|
||||
assertEquals("old", File(addOns, "Bar/old.lua").readText())
|
||||
assertFalse(File(addOns, "Foo/new.lua").exists())
|
||||
}
|
||||
|
||||
@Test fun zipsWithoutAnAddonChangeNothing() {
|
||||
val target = target()
|
||||
assertEquals(emptyList<String>(), WowAddons.import(zip("readme.txt" to "x"), target))
|
||||
assertFalse(target.addOns.exists())
|
||||
}
|
||||
|
||||
@Test fun linkEntriesDoNotCountAsAddons() {
|
||||
val target = target()
|
||||
val file = temp.newFile("links.zip")
|
||||
ZipArchiveOutputStream(file).use { out ->
|
||||
val link = ZipArchiveEntry("Foo/Foo.toc").apply { unixMode = 0xA1FF }
|
||||
out.putArchiveEntry(link)
|
||||
out.write("/etc/passwd".toByteArray())
|
||||
out.closeArchiveEntry()
|
||||
}
|
||||
assertEquals(emptyList<String>(), WowAddons.import(file, target))
|
||||
assertFalse(target.addOns.exists())
|
||||
}
|
||||
|
||||
@Test fun aZipWithAnyLinkIsRefusedWhole() {
|
||||
val target = target()
|
||||
File(target.addOns, "Ace3").mkdirs()
|
||||
File(target.addOns, "Ace3/keep.lua").writeText("keep")
|
||||
val file = temp.newFile("nested.zip")
|
||||
ZipArchiveOutputStream(file).use { out ->
|
||||
out.putArchiveEntry(ZipArchiveEntry("Foo/Foo.toc").apply { unixMode = 0xA1FF })
|
||||
out.write("/etc/passwd".toByteArray())
|
||||
out.closeArchiveEntry()
|
||||
out.putArchiveEntry(ZipArchiveEntry("Foo/Libs/Ace3/Ace3.toc"))
|
||||
out.write("toc".toByteArray())
|
||||
out.closeArchiveEntry()
|
||||
}
|
||||
assertEquals(emptyList<String>(), WowAddons.import(file, target))
|
||||
assertEquals("keep", File(target.addOns, "Ace3/keep.lua").readText())
|
||||
}
|
||||
|
||||
@Test fun escapingEntriesAreNeverWritten() {
|
||||
val target = target()
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "a", "../../evil.lua" to "x", "Foo/../../evil2.lua" to "x"), target)
|
||||
val written = target.addOns.parentFile!!.parentFile!!.walkTopDown().map { it.name }.toList()
|
||||
assertFalse("evil.lua" in written)
|
||||
assertFalse("evil2.lua" in written)
|
||||
assertTrue("Foo.toc" in written)
|
||||
}
|
||||
|
||||
@Test fun usesTheInstalledFlavourFolders() {
|
||||
val root = temp.newFolder("wow")
|
||||
listOf("_classic_", "_classic_era_", "_anniversary_", "_retail_").forEach { File(root, it).mkdirs() }
|
||||
val classic = BattleNet.title("wow_classic")!!
|
||||
assertEquals(setOf("_classic_", "_classic_era_", "_anniversary_"), WowAddons.targets(classic, root).map { it.flavor }.toSet())
|
||||
assertEquals(listOf("_retail_"), WowAddons.targets(BattleNet.title("wow")!!, File(root, "_retail_")).map { it.flavor })
|
||||
}
|
||||
|
||||
@Test fun reusesAnExistingFolderSpelling() {
|
||||
val root = temp.newFolder("wow2")
|
||||
File(root, "_forever_/interface/addons").mkdirs()
|
||||
val target = WowAddons.targets(BattleNet.title("wow_forever")!!, root).single()
|
||||
assertEquals(File(root, "_forever_/interface/addons"), target.addOns)
|
||||
}
|
||||
|
||||
@Test fun otherGamesHaveNoTargets() {
|
||||
val root = temp.newFolder("d4")
|
||||
File(root, "_retail_").mkdirs()
|
||||
assertEquals(emptyList<String>(), WowAddons.targets(BattleNet.title("fenris")!!, root).map { it.flavor })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.droiddeck.launcher.session;
|
||||
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
public final class DiagnosticStageLockProbe {
|
||||
public static void main(String[] args) throws Exception {
|
||||
try (FileChannel channel = FileChannel.open(Path.of(args[0]), StandardOpenOption.WRITE)) {
|
||||
FileLock lock = channel.tryLock();
|
||||
if (lock == null) {
|
||||
System.exit(0);
|
||||
}
|
||||
lock.release();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
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 EnhancedDiagnosticsTest {
|
||||
private lateinit var context: Context
|
||||
private lateinit var guest: File
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
SessionPaths.take()?.let { SessionPaths.release(context, it) }
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
|
||||
.remove("logs")
|
||||
.remove("gameDebugLogsEnabled")
|
||||
.remove("enhancedDiagnosticsNext")
|
||||
.remove("enhancedDiagnosticsActiveSessions")
|
||||
.commit()
|
||||
guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json")
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
SessionPaths.take()?.let { folder ->
|
||||
SessionPaths.release(context, folder)
|
||||
folder.deleteRecursively()
|
||||
}
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
|
||||
.remove("logs")
|
||||
.remove("gameDebugLogsEnabled")
|
||||
.remove("enhancedDiagnosticsNext")
|
||||
.remove("enhancedDiagnosticsActiveSessions")
|
||||
.commit()
|
||||
GameEnvironmentStore.publish(context)
|
||||
}
|
||||
|
||||
@Test fun armedSessionIsRetainedAndConsumesTheOneShotPreference() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("logs", false).commit()
|
||||
assertTrue(EnhancedDiagnostics.setArmed(context, true))
|
||||
|
||||
val folder = SessionPaths.beginOrCurrent(context, "enhanced-test")
|
||||
|
||||
assertEquals(SessionFiles.logDirectory(context), folder.parentFile)
|
||||
assertFalse(EnhancedDiagnostics.isArmed(context))
|
||||
assertTrue(EnhancedDiagnostics.isActive(context, folder))
|
||||
val manifest = JSONObject(File(folder, EnhancedDiagnostics.MANIFEST_FILE).readText())
|
||||
assertEquals(1, manifest.getInt("schema"))
|
||||
assertEquals("enhanced", manifest.getString("profile"))
|
||||
assertEquals(folder.name, manifest.getString("sessionId"))
|
||||
assertTrue(manifest.getBoolean("exportBundlesBounded"))
|
||||
assertFalse(manifest.getBoolean("rawCaptureByteBounded"))
|
||||
}
|
||||
|
||||
@Test fun activeProfileForcesGameDiagnosticsWithoutChangingUserPreferences() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
|
||||
.putBoolean("logs", false)
|
||||
.putBoolean("gameDebugLogsEnabled", false)
|
||||
.commit()
|
||||
assertTrue(EnhancedDiagnostics.setArmed(context, true))
|
||||
SessionPaths.beginOrCurrent(context, "enhanced-game-logs")
|
||||
|
||||
GameEnvironmentStore.publish(context)
|
||||
|
||||
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
|
||||
assertFalse(SessionPrefs.logsEnabled(context))
|
||||
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
|
||||
}
|
||||
|
||||
@Test fun cancellingTheOneShotLeavesOrdinaryLogRetentionUnchanged() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("logs", false).commit()
|
||||
assertTrue(EnhancedDiagnostics.setArmed(context, true))
|
||||
assertTrue(EnhancedDiagnostics.setArmed(context, false))
|
||||
|
||||
val folder = SessionPaths.beginOrCurrent(context, "ordinary-test")
|
||||
|
||||
assertEquals(File(context.cacheDir, "session-logs"), folder.parentFile)
|
||||
assertFalse(EnhancedDiagnostics.isActive(context, folder))
|
||||
}
|
||||
|
||||
@Test fun guestCannotForgeEnhancedDiagnosticsByWritingAMarker() {
|
||||
val folder = SessionPaths.beginOrCurrent(context, "forged-marker")
|
||||
File(folder, EnhancedDiagnostics.MANIFEST_FILE).writeText(
|
||||
"""{"schema":1,"profile":"enhanced"}""",
|
||||
)
|
||||
|
||||
assertFalse(EnhancedDiagnostics.isActive(context, folder))
|
||||
assertNull(EnhancedDiagnostics.manifest(context, folder))
|
||||
}
|
||||
|
||||
@Test fun trustedStateSurvivesGuestMarkerDeletionAndSessionRecovery() {
|
||||
assertTrue(EnhancedDiagnostics.setArmed(context, true))
|
||||
val folder = SessionPaths.beginOrCurrent(context, "deleted-marker")
|
||||
assertTrue(File(folder, EnhancedDiagnostics.MANIFEST_FILE).delete())
|
||||
|
||||
assertTrue(EnhancedDiagnostics.isActive(context, File(folder.path)))
|
||||
assertEquals(folder.name, EnhancedDiagnostics.manifest(context, folder)?.getString("sessionId"))
|
||||
assertEquals(folder, SessionPaths.take())
|
||||
assertTrue(EnhancedDiagnostics.isActive(context, folder))
|
||||
}
|
||||
|
||||
@Test fun informationalMarkerFailureDoesNotRearmTheNextSession() {
|
||||
val parent = SessionFiles.logDirectory(context).apply { mkdirs() }
|
||||
val folder = File(parent, "2026-11-04-99-marker-failure").apply { mkdirs() }
|
||||
File(folder, EnhancedDiagnostics.MANIFEST_FILE).mkdirs()
|
||||
assertTrue(EnhancedDiagnostics.setArmed(context, true))
|
||||
|
||||
assertTrue(EnhancedDiagnostics.consumeInto(context, folder))
|
||||
|
||||
assertTrue(EnhancedDiagnostics.isActive(context, folder))
|
||||
assertFalse(EnhancedDiagnostics.isArmed(context))
|
||||
folder.deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun aReusedSessionPathDoesNotInheritTrustedState() {
|
||||
assertTrue(EnhancedDiagnostics.setArmed(context, true))
|
||||
val original = SessionPaths.beginOrCurrent(context, "reused-path")
|
||||
assertTrue(EnhancedDiagnostics.isActive(context, original))
|
||||
assertEquals(original, SessionPaths.take())
|
||||
original.deleteRecursively()
|
||||
|
||||
val replacement = SessionPaths.beginOrCurrent(context, "reused-path")
|
||||
|
||||
assertEquals(original.path, replacement.path)
|
||||
assertFalse(EnhancedDiagnostics.isActive(context, replacement))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Intent
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeFalse
|
||||
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.IOException
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.FileChannel
|
||||
import java.nio.channels.SeekableByteChannel
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardOpenOption
|
||||
import java.nio.file.attribute.PosixFilePermissions
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.zip.ZipFile
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class EnhancedSessionLogShareTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun installSecureSourceOpener() = installJvmSecureSourceOpener()
|
||||
|
||||
@After fun resetSourceOpener() = resetSecureSourceOpener()
|
||||
|
||||
private class CountingChannel(
|
||||
private val delegate: SeekableByteChannel,
|
||||
private val reads: AtomicInteger,
|
||||
) : SeekableByteChannel by delegate {
|
||||
override fun read(dst: ByteBuffer): Int {
|
||||
reads.incrementAndGet()
|
||||
return delegate.read(dst)
|
||||
}
|
||||
}
|
||||
|
||||
private fun installCountingSourceOpener(reads: AtomicInteger) {
|
||||
EnhancedSessionLogShare.setSourceOpenerForTest(object : SecureSourceOpener {
|
||||
override fun <T> withChannel(
|
||||
root: java.nio.file.Path,
|
||||
relative: java.nio.file.Path,
|
||||
block: (SeekableByteChannel) -> T,
|
||||
): T? {
|
||||
val source = root.resolve(relative).normalize()
|
||||
if (!source.startsWith(root) || Files.isSymbolicLink(source)) return null
|
||||
return FileChannel.open(source, StandardOpenOption.READ).use { channel ->
|
||||
block(CountingChannel(channel, reads))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun diagnosticsAreSplitIntoManifestedArchivesWithOneSessionIdentity() {
|
||||
val session = tmp.newFolder("2026-11-04-01-steam")
|
||||
session.resolve("session.log").writeText("startup ok\n")
|
||||
session.resolve("wayland.log").writeText("frame import ok\n")
|
||||
session.resolve("steam-42.log").writeText("dxvk: present ok\n")
|
||||
|
||||
val zips = EnhancedSessionLogShare.create(app, session)
|
||||
|
||||
assertEquals(
|
||||
setOf("session", "graphics", "games"),
|
||||
zips.map { it.nameWithoutExtension.substringAfterLast('-') }.toSet(),
|
||||
)
|
||||
val expected = mapOf(
|
||||
"session" to "${session.name}/session.log",
|
||||
"graphics" to "${session.name}/wayland.log",
|
||||
"games" to "${session.name}/steam-42.log",
|
||||
)
|
||||
zips.forEach { zip ->
|
||||
val category = zip.nameWithoutExtension.substringAfterLast('-')
|
||||
ZipFile(zip).use { archive ->
|
||||
assertTrue(archive.getEntry(expected.getValue(category)) != null)
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
assertEquals(1, manifest.getInt("schema"))
|
||||
assertEquals(session.name, manifest.getString("sessionId"))
|
||||
assertEquals(category, manifest.getString("category"))
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
val record = (0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.single { it.optString("entry") == expected.getValue(category) }
|
||||
assertEquals("captured", record.getString("status"))
|
||||
}
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun oversizedFilesKeepBoundedBeginningAndTailAndDeclareTruncation() {
|
||||
val session = tmp.newFolder("2026-11-04-02-game")
|
||||
session.resolve("steam-7.log").writeText("begin\n" + "middle\n".repeat(100) + "tail\n")
|
||||
val limits = EnhancedShareLimits(maxFilesPerArchive = 8, maxBytesPerFile = 96, maxBytesTotal = 512)
|
||||
|
||||
val games = EnhancedSessionLogShare.create(app, session, limits = limits)
|
||||
.single { it.name.endsWith("-games.zip") }
|
||||
|
||||
ZipFile(games).use { archive ->
|
||||
val text = archive.getInputStream(archive.getEntry("${session.name}/steam-7.log")).bufferedReader().readText()
|
||||
assertTrue(text.startsWith("begin"))
|
||||
assertTrue(text.contains("diagnostic file truncated"))
|
||||
assertTrue(text.endsWith("tail\n"))
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
assertEquals("truncated", manifest.getJSONArray("entries").getJSONObject(0).getString("status"))
|
||||
assertTrue(manifest.getJSONArray("entries").getJSONObject(0).getLong("capturedBytes") <= 96)
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun symbolicLinksAreNotReadAndTheirOmissionIsRecorded() {
|
||||
assumeFalse(System.getProperty("os.name").startsWith("Windows"))
|
||||
val session = tmp.newFolder("2026-11-04-03-steam")
|
||||
session.resolve("session.log").writeText("safe\n")
|
||||
val outside = tmp.newFile("private.log").apply { writeText("do-not-share\n") }
|
||||
val link = session.toPath().resolve("wayland.log")
|
||||
runCatching { Files.createSymbolicLink(link, outside.toPath()) }.getOrElse { return }
|
||||
|
||||
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
|
||||
|
||||
ZipFile(graphics).use { archive ->
|
||||
assertFalse(archive.entries().toList().any { it.name.endsWith("wayland.log") })
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
assertTrue((0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.any { it.optString("reason") == "unsafe-or-unavailable-source" })
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun enhancedShareUsesOneMultipleAttachmentIntent() {
|
||||
val session = tmp.newFolder("2026-11-04-04-steam")
|
||||
session.resolve("session.log").writeText("safe\n")
|
||||
val zips = EnhancedSessionLogShare.create(app, session)
|
||||
|
||||
val chooser = SessionLogShare.shareEnhancedIntent(app, zips)
|
||||
val send = chooser.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)!!
|
||||
|
||||
assertEquals(Intent.ACTION_SEND_MULTIPLE, send.action)
|
||||
assertEquals("application/zip", send.type)
|
||||
val uris = send.getParcelableArrayListExtra<android.net.Uri>(Intent.EXTRA_STREAM)!!
|
||||
assertEquals(3, uris.size)
|
||||
assertEquals(3, send.clipData!!.itemCount)
|
||||
assertTrue(send.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION != 0)
|
||||
val header = app.contentResolver.openInputStream(uris.first())!!.use { it.readNBytes(4) }
|
||||
assertEquals("PK\u0003\u0004", String(header, Charsets.ISO_8859_1))
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun graphicsArchiveIncludesOnlyBoundedFrameTraceSummariesFromTheSessionLog() {
|
||||
val session = tmp.newFolder("2026-11-04-05-steam")
|
||||
session.resolve("session.log").writeText(
|
||||
"normal startup line\n" +
|
||||
"DROIDDECK_FRAME_TRACE xdamage=4 commits=2\n" +
|
||||
"unrelated account=test-user\n" +
|
||||
"DROIDDECK_FRAME_TRACE xdamage=9 commits=8\n" +
|
||||
"DROIDDECK_PROCESS_TRACE pid=42 gpuLibs=libvulkan.so\n",
|
||||
)
|
||||
|
||||
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
|
||||
|
||||
ZipFile(graphics).use { archive ->
|
||||
val trace = archive.getInputStream(archive.getEntry("${session.name}/graphics/frame-trace.log"))
|
||||
.bufferedReader().readText()
|
||||
assertEquals(
|
||||
"DROIDDECK_FRAME_TRACE xdamage=4 commits=2\n" +
|
||||
"DROIDDECK_FRAME_TRACE xdamage=9 commits=8\n",
|
||||
trace,
|
||||
)
|
||||
assertFalse(trace.contains("normal startup"))
|
||||
assertFalse(trace.contains("test-user"))
|
||||
val process = archive.getInputStream(archive.getEntry("${session.name}/graphics/process-trace.log"))
|
||||
.bufferedReader().readText()
|
||||
assertEquals("DROIDDECK_PROCESS_TRACE pid=42 gpuLibs=libvulkan.so\n", process)
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun byteOrientedTraceAndTailScansUseBufferedChannelReads() {
|
||||
val traceSession = tmp.newFolder("2026-11-04-05-buffered-trace")
|
||||
traceSession.resolve("session.log").writeText("x".repeat(1024 * 1024))
|
||||
val traceReads = AtomicInteger()
|
||||
installCountingSourceOpener(traceReads)
|
||||
|
||||
EnhancedSessionLogShare.create(app, traceSession)
|
||||
|
||||
assertTrue("trace scan used ${traceReads.get()} channel reads", traceReads.get() < 200)
|
||||
SessionLogShare.clear(app)
|
||||
|
||||
val tailSession = tmp.newFolder("2026-11-04-05-buffered-tail")
|
||||
tailSession.resolve("steam-7.log").writeText("x".repeat(1024 * 1024))
|
||||
val tailReads = AtomicInteger()
|
||||
installCountingSourceOpener(tailReads)
|
||||
|
||||
EnhancedSessionLogShare.create(
|
||||
app,
|
||||
tailSession,
|
||||
limits = EnhancedShareLimits(maxBytesPerFile = 64 * 1024L, maxBytesTotal = 512 * 1024L),
|
||||
)
|
||||
|
||||
assertTrue("tail scan used ${tailReads.get()} channel reads", tailReads.get() < 100)
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun truncationNeverSharesASecretWhoseLabelWasCutOffAtTheBoundary() {
|
||||
val session = tmp.newFolder("2026-11-04-06-game")
|
||||
val secret = "abcdef1234567890"
|
||||
session.resolve("steam-8.log").writeText(
|
||||
"padding-refresh_token=$secret" + "x".repeat(512) + "\nvisible tail\n",
|
||||
)
|
||||
val limits = EnhancedShareLimits(maxFilesPerArchive = 8, maxBytesPerFile = 128, maxBytesTotal = 512)
|
||||
|
||||
val games = EnhancedSessionLogShare.create(app, session, limits = limits)
|
||||
.single { it.name.endsWith("-games.zip") }
|
||||
|
||||
val shared = ZipFile(games).use { archive ->
|
||||
archive.getInputStream(archive.getEntry("${session.name}/steam-8.log")).bufferedReader().readText()
|
||||
}
|
||||
assertFalse(shared.contains(secret))
|
||||
assertTrue(shared.contains("diagnostic file truncated"))
|
||||
assertTrue(shared.endsWith("visible tail\n"))
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun discoveryStopsAtItsBoundAndDeclaresTheTruncatedInventory() {
|
||||
val session = tmp.newFolder("2026-11-04-07-steam")
|
||||
repeat(20) { session.resolve("log-$it.txt").writeText("line $it\n") }
|
||||
val limits = EnhancedShareLimits(
|
||||
maxFilesPerArchive = 8,
|
||||
maxDiscoveredFiles = 2,
|
||||
maxBytesPerFile = 1024,
|
||||
maxBytesTotal = 4096,
|
||||
)
|
||||
|
||||
val zips = EnhancedSessionLogShare.create(app, session, limits = limits)
|
||||
|
||||
val captured = zips.sumOf { zip ->
|
||||
ZipFile(zip).use { archive -> archive.entries().toList().count { it.name != "diagnostics-manifest.json" } }
|
||||
}
|
||||
assertTrue(captured <= 2)
|
||||
zips.forEach { zip ->
|
||||
ZipFile(zip).use { archive ->
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
assertTrue((0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.any { it.optString("origin") == "discovery" && it.optString("status") == "truncated" })
|
||||
}
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun aGuestForgedActivationMarkerIsNeverExportedAsTrustedMetadata() {
|
||||
val session = tmp.newFolder("2026-11-04-08-steam")
|
||||
session.resolve("session.log").writeText("safe\n")
|
||||
session.resolve(EnhancedDiagnostics.MANIFEST_FILE).writeText("{\"profile\":\"forged\"}\n")
|
||||
|
||||
val zips = EnhancedSessionLogShare.create(app, session)
|
||||
|
||||
zips.forEach { zip ->
|
||||
ZipFile(zip).use { archive ->
|
||||
assertFalse(archive.entries().toList().any { it.name.endsWith(EnhancedDiagnostics.MANIFEST_FILE) })
|
||||
}
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun hardLinksAreRejectedInsteadOfFollowingASecondNameToItsContent() {
|
||||
assumeFalse(System.getProperty("os.name").startsWith("Windows"))
|
||||
val session = tmp.newFolder("2026-11-04-09-steam")
|
||||
session.resolve("session.log").writeText("safe\n")
|
||||
val outside = tmp.newFile("outside-hardlink.log").apply { writeText("private hard-link content\n") }
|
||||
runCatching { Files.createLink(session.toPath().resolve("wayland.log"), outside.toPath()) }.getOrElse { return }
|
||||
|
||||
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
|
||||
|
||||
ZipFile(graphics).use { archive ->
|
||||
assertFalse(archive.entries().toList().any { it.name.endsWith("wayland.log") })
|
||||
val all = archive.entries().toList().joinToString("\n") { entry ->
|
||||
archive.getInputStream(entry).bufferedReader().readText()
|
||||
}
|
||||
assertFalse(all.contains("private hard-link content"))
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun guestControlledAndControlCharacterNamesNeverEnterTheArchiveOrManifest() {
|
||||
val session = tmp.newFolder("2026-11-04-10-steam")
|
||||
session.resolve("private-window-title.log").writeText("safe diagnostic\n")
|
||||
session.resolve("wayland\nsecret.log").writeText("must not be named\n")
|
||||
|
||||
val sessionZip = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-session.zip") }
|
||||
|
||||
ZipFile(sessionZip).use { archive ->
|
||||
val names = archive.entries().toList().map { it.name }
|
||||
assertTrue(names.any { it.contains("/entry-") && it.endsWith(".log") })
|
||||
assertFalse(names.any { it.contains("private-window-title") || it.contains('\n') })
|
||||
val manifest = archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText()
|
||||
assertFalse(manifest.contains("private-window-title"))
|
||||
assertFalse(manifest.contains("wayland\\nsecret"))
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun oneCategoryCannotConsumeTheOtherCategoriesByteReservations() {
|
||||
val session = tmp.newFolder("2026-11-04-11-steam")
|
||||
session.resolve("session.log").writeText("session\n".repeat(100))
|
||||
session.resolve("wayland.log").writeText("graphics\n".repeat(100))
|
||||
session.resolve("steam-11.log").writeText("game\n".repeat(100))
|
||||
val limits = EnhancedShareLimits(maxBytesPerFile = 1024, maxBytesTotal = 300)
|
||||
|
||||
val zips = EnhancedSessionLogShare.create(app, session, limits = limits)
|
||||
|
||||
zips.forEach { zip ->
|
||||
ZipFile(zip).use { archive ->
|
||||
assertTrue(archive.entries().toList().any { it.name != "diagnostics-manifest.json" })
|
||||
}
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun filteredTraceScanFindsLateSummariesAndMarksThePartialSource() {
|
||||
val session = tmp.newFolder("2026-11-04-12-steam")
|
||||
val source = session.resolve("session.log")
|
||||
RandomAccessFile(source, "rw").use { file ->
|
||||
file.setLength(17L * 1024 * 1024)
|
||||
file.seek(file.length() - 80)
|
||||
file.write("\nDROIDDECK_PROCESS_TRACE pid=99 gpuLibs=libGLES.so\n".toByteArray())
|
||||
}
|
||||
|
||||
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
|
||||
|
||||
ZipFile(graphics).use { archive ->
|
||||
val trace = archive.getInputStream(archive.getEntry("${session.name}/graphics/process-trace.log"))
|
||||
.bufferedReader().readText()
|
||||
assertTrue(trace.contains("pid=99"))
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
assertTrue((0 until entries.length()).map { entries.getJSONObject(it) }.any {
|
||||
it.optString("origin") == "guest-process-trace" && it.optString("status") == "truncated"
|
||||
})
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun filteredTraceWithMatchesOnlyOutsideTheScannedRangesStaysTruncated() {
|
||||
val session = tmp.newFolder("2026-11-04-12-partial-empty")
|
||||
val source = session.resolve("session.log")
|
||||
RandomAccessFile(source, "rw").use { file ->
|
||||
file.setLength(17L * 1024 * 1024)
|
||||
file.seek(8L * 1024 * 1024 + 256 * 1024)
|
||||
file.write("DROIDDECK_FRAME_TRACE hidden-in-middle=1\n".toByteArray())
|
||||
}
|
||||
|
||||
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
|
||||
|
||||
ZipFile(graphics).use { archive ->
|
||||
assertTrue(archive.getEntry("${session.name}/graphics/frame-trace.log") == null)
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
val record = (0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.single { it.optString("origin") == "guest-frame-trace" }
|
||||
assertEquals("truncated", record.getString("status"))
|
||||
assertEquals("no-matching-lines-in-bounded-scan", record.getString("reason"))
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun sessionNameCannotMisclassifyPrimarySessionAndGraphicsLogs() {
|
||||
val session = tmp.newFolder("2026-11-04-12-wine")
|
||||
session.resolve("session.log").writeText("session\n")
|
||||
session.resolve("wayland.log").writeText("graphics\n")
|
||||
|
||||
val zips = EnhancedSessionLogShare.create(app, session)
|
||||
val sessionEntries = ZipFile(zips.single { it.name.endsWith("-session.zip") }).use { archive ->
|
||||
archive.entries().toList().map { it.name }
|
||||
}
|
||||
val graphicsEntries = ZipFile(zips.single { it.name.endsWith("-graphics.zip") }).use { archive ->
|
||||
archive.entries().toList().map { it.name }
|
||||
}
|
||||
val gameEntries = ZipFile(zips.single { it.name.endsWith("-games.zip") }).use { archive ->
|
||||
archive.entries().toList().map { it.name }
|
||||
}
|
||||
|
||||
assertTrue(sessionEntries.contains("${session.name}/session.log"))
|
||||
assertTrue(graphicsEntries.contains("${session.name}/wayland.log"))
|
||||
assertFalse(gameEntries.contains("${session.name}/session.log"))
|
||||
assertFalse(gameEntries.contains("${session.name}/wayland.log"))
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun unreadableDiscoverySubtreeKeepsOtherLogsAndMarksTheManifestPartial() {
|
||||
assumeFalse(System.getProperty("os.name").startsWith("Windows"))
|
||||
val session = tmp.newFolder("2026-11-04-12-partial-discovery")
|
||||
session.resolve("session.log").writeText("safe\n")
|
||||
val blocked = session.resolve("blocked").apply { mkdir(); resolve("hidden.log").writeText("hidden\n") }
|
||||
val original = Files.getPosixFilePermissions(blocked.toPath())
|
||||
Files.setPosixFilePermissions(blocked.toPath(), PosixFilePermissions.fromString("---------"))
|
||||
val sessionZip = try {
|
||||
EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-session.zip") }
|
||||
} finally {
|
||||
Files.setPosixFilePermissions(blocked.toPath(), original)
|
||||
}
|
||||
|
||||
ZipFile(sessionZip).use { archive ->
|
||||
assertTrue(archive.getEntry("${session.name}/session.log") != null)
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
assertTrue((0 until entries.length()).map { entries.getJSONObject(it) }.any {
|
||||
it.optString("origin") == "discovery" && it.optString("status") == "truncated" &&
|
||||
it.optString("reason") == "filesystem-error"
|
||||
})
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun diagnosticLookingGuestNamesCannotExposeEmbeddedSecrets() {
|
||||
val session = tmp.newFolder("2026-11-04-13-game")
|
||||
val tokenName = "dxvk-refresh_token_abcdef123456.log"
|
||||
val accountName = "battle.net-secretvalue.log"
|
||||
session.resolve(tokenName).writeText("dxvk diagnostic\n")
|
||||
session.resolve(accountName).writeText("battle net diagnostic\n")
|
||||
|
||||
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
|
||||
|
||||
ZipFile(games).use { archive ->
|
||||
val names = archive.entries().toList().map { it.name }
|
||||
assertFalse(names.any { it.contains("refresh_token") || it.contains("secretvalue") })
|
||||
assertTrue(names.count { it.substringAfterLast('/').startsWith("entry-") } >= 2)
|
||||
val manifest = archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText()
|
||||
assertFalse(manifest.contains("refresh_token"))
|
||||
assertFalse(manifest.contains("secretvalue"))
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun gamesArchiveIncludesOnlyGameLifecycleSummariesFromTheSessionLog() {
|
||||
val session = tmp.newFolder("2026-11-04-14-game")
|
||||
session.resolve("session.log").writeText(
|
||||
"DROIDDECK_DIAGNOSTICS event=game_start appId=42 pid=123\n" +
|
||||
"unrelated launch detail\n" +
|
||||
"DROIDDECK_DIAGNOSTICS event=game_exit appId=42 status=139\n",
|
||||
)
|
||||
|
||||
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
|
||||
|
||||
ZipFile(games).use { archive ->
|
||||
val lifecycle = archive.getInputStream(archive.getEntry("${session.name}/games/game-lifecycle.log"))
|
||||
.bufferedReader().readText()
|
||||
assertEquals(
|
||||
"DROIDDECK_DIAGNOSTICS event=game_start appId=42 pid=123\n" +
|
||||
"DROIDDECK_DIAGNOSTICS event=game_exit appId=42 status=139\n",
|
||||
lifecycle,
|
||||
)
|
||||
assertFalse(lifecycle.contains("unrelated launch detail"))
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText())
|
||||
assertTrue(manifest.toString().contains("guest-game-lifecycle"))
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun injectedSecureOpenFailureFailsClosedAndTheOverrideCanBeReset() {
|
||||
val session = tmp.newFolder("2026-11-04-15-steam")
|
||||
session.resolve("session.log").writeText("must not be shared\n")
|
||||
EnhancedSessionLogShare.setSourceOpenerForTest(object : SecureSourceOpener {
|
||||
override fun <T> withChannel(
|
||||
root: java.nio.file.Path,
|
||||
relative: java.nio.file.Path,
|
||||
block: (java.nio.channels.SeekableByteChannel) -> T,
|
||||
): T? = null
|
||||
})
|
||||
try {
|
||||
val sessionZip = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-session.zip") }
|
||||
ZipFile(sessionZip).use { archive ->
|
||||
assertFalse(archive.entries().toList().any { it.name.endsWith("session.log") })
|
||||
val manifest = archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText()
|
||||
assertTrue(manifest.contains("unsafe-or-unavailable-source"))
|
||||
}
|
||||
} finally {
|
||||
resetSecureSourceOpener()
|
||||
}
|
||||
assertFalse(EnhancedSessionLogShare.hasSourceOpenerForTest())
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
|
||||
@Test fun sourceReadFailureIsRecordedWithoutFailingTheArchive() {
|
||||
val session = tmp.newFolder("2026-11-04-16-steam")
|
||||
session.resolve("session.log").writeText("must not be shared\n")
|
||||
EnhancedSessionLogShare.setSourceOpenerForTest(object : SecureSourceOpener {
|
||||
override fun <T> withChannel(
|
||||
root: java.nio.file.Path,
|
||||
relative: java.nio.file.Path,
|
||||
block: (java.nio.channels.SeekableByteChannel) -> T,
|
||||
): T? = FileChannel.open(root.resolve(relative), StandardOpenOption.READ).use { channel ->
|
||||
block(object : SeekableByteChannel by channel {
|
||||
override fun read(dst: ByteBuffer): Int = throw IOException("injected source read failure")
|
||||
})
|
||||
}
|
||||
})
|
||||
try {
|
||||
val sessionZip = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-session.zip") }
|
||||
ZipFile(sessionZip).use { archive ->
|
||||
assertFalse(archive.entries().toList().any { it.name.endsWith("session.log") })
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
|
||||
.bufferedReader().readText()).getJSONArray("entries")
|
||||
val record = (0 until manifest.length()).map { manifest.getJSONObject(it) }
|
||||
.single { it.optString("entry").endsWith("session.log") }
|
||||
assertEquals("error", record.getString("status"))
|
||||
assertEquals("IOException", record.getString("reason"))
|
||||
}
|
||||
} finally {
|
||||
resetSecureSourceOpener()
|
||||
}
|
||||
SessionLogShare.clear(app)
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,34 @@ class ForcedPackageTest {
|
||||
assertDefaultDxvkRestoreRow(protonName)
|
||||
}
|
||||
|
||||
@Test fun systemPowerVrRejectsNewGameDxvkSelectionsWithoutChangingSavedProfiles() {
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val saved = state.readText()
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ComponentsManager.setGameComponent(context, "42", "dxvk", "replacement.wcp") {
|
||||
ComponentsManager.runtimeManaged(it, true)
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(saved, state.readText())
|
||||
assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
assertFalse(launchState().exists())
|
||||
}
|
||||
|
||||
@Test fun systemPowerVrAllowsClearingASavedGameDxvkSelection() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
|
||||
ComponentsManager.setGameComponent(context, "42", "dxvk", null) {
|
||||
ComponentsManager.runtimeManaged(it, true)
|
||||
}
|
||||
|
||||
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
|
||||
assertDefaultDxvkRestoreRow("proton-exp")
|
||||
}
|
||||
|
||||
@Test fun aNewProtonIsCapturedWhenTheLastOverrideIsReset() {
|
||||
proton("existing")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
|
||||
@@ -164,13 +164,24 @@ class GameEnvironmentStoreTest {
|
||||
assertEquals(config, GameEnvironmentStore.read(context))
|
||||
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
|
||||
assertEquals("false", published.shared["MESA_SHADER_CACHE_DISABLE"])
|
||||
assertEquals("12_2", published.shared["VKD3D_FEATURE_LEVEL"])
|
||||
assertEquals("6_9", published.shared["VKD3D_SHADER_MODEL"])
|
||||
assertFalse(published.shared.containsKey("VKD3D_FEATURE_LEVEL"))
|
||||
assertFalse(published.shared.containsKey("VKD3D_SHADER_MODEL"))
|
||||
assertEquals(config.games, published.games)
|
||||
assertEquals(config.shared["LITERAL"], published.shared["LITERAL"])
|
||||
assertEquals("", published.shared["EMPTY"])
|
||||
}
|
||||
|
||||
@Test fun publishingPreservesExplicitSharedGraphicsCapabilities() {
|
||||
val config = GameEnvironment.Config(shared = mapOf(
|
||||
"VKD3D_FEATURE_LEVEL" to "12_1", "VKD3D_SHADER_MODEL" to "6_6",
|
||||
))
|
||||
GameEnvironmentStore.save(context, config)
|
||||
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
|
||||
assertEquals(config, GameEnvironmentStore.read(context))
|
||||
assertEquals("12_1", published.shared["VKD3D_FEATURE_LEVEL"])
|
||||
assertEquals("6_6", published.shared["VKD3D_SHADER_MODEL"])
|
||||
}
|
||||
|
||||
@Test fun changingFexPresetPublishesForNextGameLaunch() {
|
||||
GameEnvironmentStore.save(context, GameEnvironment.Config())
|
||||
SessionPrefs.setFexPreset(context, "EXTREME")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import java.io.File
|
||||
import org.junit.Assert.*
|
||||
@@ -48,4 +49,46 @@ class GameStorageTest {
|
||||
SessionPrefs.setAddedGamesDirs(app, odd.map { it.path })
|
||||
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun anUnpluggedDriveFallsBackToInternalWithoutForgettingIt() {
|
||||
val gone = "/storage/0000-0000/Android/data/com.droiddeck.launcher/files/steam"
|
||||
SessionPrefs.setGameStorage(app, gone, "USB drive")
|
||||
assertNull(GameStorage.effective(app))
|
||||
assertNull(GameStorage.x64CardLibrary(app))
|
||||
assertEquals(gone, SessionPrefs.gameStorage(app))
|
||||
}
|
||||
|
||||
@Test fun aPluggedInDriveStaysTheLibrary() {
|
||||
val files = tmp.newFolder("files")
|
||||
val steam = File(files, "steam")
|
||||
SessionPrefs.setGameStorage(app, steam.path, "USB drive")
|
||||
assertEquals(steam.path, GameStorage.effective(app)?.path)
|
||||
steam.mkdirs()
|
||||
assertEquals(steam.path, GameStorage.effective(app)?.path)
|
||||
assertEquals("USB drive", GameStorage.effective(app)?.label)
|
||||
}
|
||||
|
||||
@Test fun missingSubfolderIsAttachedWhenItsVolumeIsMounted() {
|
||||
val path = File(tmp.newFolder("mounted-volume"), "missing/steam")
|
||||
assertTrue(GameStorage.attached(path, Environment.MEDIA_MOUNTED, externalStoragePath = true))
|
||||
}
|
||||
|
||||
@Test fun removedVolumeIsNotAttachedEvenWhenItsParentExists() {
|
||||
val parent = tmp.newFolder("storage")
|
||||
val volume = File(parent, "0000-0000")
|
||||
assertTrue(parent.isDirectory)
|
||||
assertFalse(GameStorage.attached(volume, Environment.MEDIA_REMOVED, externalStoragePath = true))
|
||||
assertFalse(GameStorage.attached(volume, Environment.MEDIA_UNKNOWN, externalStoragePath = true))
|
||||
}
|
||||
|
||||
@Test fun onlyASavedDriveThatIsMissingCountsAsDisconnected() {
|
||||
SessionPrefs.setGameStorage(app, "", "")
|
||||
assertFalse(GameStorage.disconnected(app))
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
assertFalse(GameStorage.disconnected(app))
|
||||
SessionPrefs.setGameStorage(app, "/storage/0000-0000/Android/data/com.droiddeck.launcher/files/steam", "USB drive")
|
||||
assertTrue(GameStorage.disconnected(app))
|
||||
SessionPrefs.setGameStorage(app, tmp.newFolder("plugged").path, "USB drive")
|
||||
assertFalse(GameStorage.disconnected(app))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class GraphicsReportTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun deviceNumbersSplitAsLinuxDoes() {
|
||||
// /dev/mali0 on the testers' phones: 10:103 (misc); a DRM render node: 226:128.
|
||||
assertEquals(10L, GraphicsReport.major(10L shl 8 or 103L))
|
||||
assertEquals(103L, GraphicsReport.minor(10L shl 8 or 103L))
|
||||
assertEquals(226L, GraphicsReport.major(226L shl 8 or 128L))
|
||||
assertEquals(128L, GraphicsReport.minor(226L shl 8 or 128L))
|
||||
}
|
||||
|
||||
@Test fun gameLogsAreCutPerFileAndOldestLaunchesGoFirst() {
|
||||
val games = tmp.newFolder("games")
|
||||
fun launch(name: String, bytes: Int) = File(games, name).apply { mkdirs() }.also { File(it, "steam-1.log").writeBytes(ByteArray(bytes)) }
|
||||
val old = launch("20261012-100000-1", 60)
|
||||
val mid = launch("20261012-110000-2", 60)
|
||||
val new = launch("20261012-120000-3", 200)
|
||||
GraphicsReport.capGames(games, fileMax = 100, totalMax = 170)
|
||||
assertEquals(100L, File(new, "steam-1.log").length())
|
||||
assertFalse(old.exists())
|
||||
assertTrue(mid.exists())
|
||||
assertTrue(new.exists())
|
||||
}
|
||||
|
||||
@Test fun aMissingGamesFolderIsFine() {
|
||||
GraphicsReport.capGames(File(tmp.root, "none"))
|
||||
GraphicsReport.finish(tmp.newFolder("session"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Application
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], application = Application::class, qualifiers = "en")
|
||||
class LoadingStateUpdateTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
@Test fun extractingReplacesAnIncompleteDownload() {
|
||||
assertApplying(read("Downloading update (50 of 100 KB)", "Extracting package..."))
|
||||
}
|
||||
|
||||
@Test fun installingClearsTheCompletedDownloadPercentage() {
|
||||
assertApplying(read("Downloading update (100 of 100 KB)", "Installing update..."))
|
||||
}
|
||||
|
||||
@Test fun acceptsForwardedMessagesAndBootstrapPrefixes() {
|
||||
for (message in listOf(
|
||||
"Installing update...",
|
||||
"[2026-10-25 12:00:02] Extracting package...",
|
||||
"[----] Installing update...\r",
|
||||
"[2026-10-25 12:00:02] [----] Extracting package...",
|
||||
)) assertApplying(read(message))
|
||||
}
|
||||
|
||||
@Test fun aNewDownloadReplacesAnOlderApplyingStage() {
|
||||
val state = read("Installing update...", "Downloading update (25 of 100 KB)")
|
||||
assertEquals(25, state.percent)
|
||||
assertEquals("Downloading the Steam client update · 25%", state.step)
|
||||
}
|
||||
|
||||
@Test fun aNewScriptStepReplacesAnOlderApplyingStage() {
|
||||
val state = read("Installing update...", "== STEP 12:00:03 checking the Linux runtime")
|
||||
assertEquals("checking the Linux runtime", state.step)
|
||||
assertEquals(LoadingState.Topic.RUNTIME, state.topic)
|
||||
assertEquals(-1, state.percent)
|
||||
}
|
||||
|
||||
@Test fun unrelatedOutputKeepsTheApplyingStage() {
|
||||
assertApplying(read("Installing update...", "Loading cached metrics", ""))
|
||||
}
|
||||
|
||||
@Test fun similarlyNamedMessagesDoNotReplaceTheDownload() {
|
||||
val state = read(
|
||||
"Downloading update (50 of 100 KB)",
|
||||
"worker: Installing update...",
|
||||
"Installing update for Proton...",
|
||||
"[12:00:02] error: Extracting package...",
|
||||
)
|
||||
assertEquals(50, state.percent)
|
||||
assertEquals("Downloading the Steam client update · 50%", state.step)
|
||||
}
|
||||
|
||||
@Test fun anOlderRuntimeCanReturnToItsPartCountAfterApplying() {
|
||||
val state = read("Installing update...", "== STEP 12:00:03 downloading Steam: a_all (1/2)")
|
||||
assertEquals(50, state.percent)
|
||||
assertEquals("Downloading the Steam client · a_all", state.step)
|
||||
}
|
||||
|
||||
@Test fun desktopStartupDoesNotConsumeSteamApplyingMessages() {
|
||||
val state = read(
|
||||
"== STEP 12:00:01 starting the desktop", "Installing update...", steam = false,
|
||||
)
|
||||
assertEquals("starting the desktop", state.step)
|
||||
assertEquals(LoadingState.Topic.DESKTOP, state.topic)
|
||||
}
|
||||
|
||||
@Test fun anExistingLoadingStateFollowsUpdatesAcrossPolls() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val log = log("Downloading update (100 of 100 KB)")
|
||||
val state = LoadingState(context)
|
||||
state.update(context, log)
|
||||
assertEquals(100, state.percent)
|
||||
log.appendText("\n[12:00:02] Installing update...")
|
||||
state.update(context, log)
|
||||
assertApplying(state)
|
||||
log.appendText("\nDownloading update (20 of 100 KB)")
|
||||
state.update(context, log)
|
||||
assertEquals(20, state.percent)
|
||||
}
|
||||
|
||||
private fun read(vararg lines: String, steam: Boolean = true): LoadingState {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
return LoadingState(context, steam).apply { update(context, log(*lines)) }
|
||||
}
|
||||
|
||||
private fun log(vararg lines: String): File = temp.newFile().apply {
|
||||
writeText((listOf("== STEP 12:00:00 starting the Steam client") + lines).joinToString("\n"))
|
||||
}
|
||||
|
||||
private fun assertApplying(state: LoadingState) {
|
||||
assertEquals(-1, state.percent)
|
||||
assertEquals("Applying the Steam client update…", state.step)
|
||||
assertEquals(LoadingState.Topic.STEAM, state.topic)
|
||||
assertTrue(state.readable)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OrphanReaperProcessTest {
|
||||
@Test fun unavailableProcessListDefersCleanup() {
|
||||
assertTrue(OrphanReaper.hasOtherProcesses(null, 100) { false })
|
||||
}
|
||||
|
||||
@Test fun theAppAndForeignProcessesDoNotKeepOldRuntimes() {
|
||||
assertFalse(OrphanReaper.hasOtherProcesses(listOf(0, 1, 100, 200), 100) { pid ->
|
||||
check(pid == 200) { "do not probe self or process groups" }
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun anyRemainingAppProcessDefersCleanup() {
|
||||
assertTrue(OrphanReaper.hasOtherProcesses(listOf(100, 200, 300), 100) { it == 300 })
|
||||
assertFalse(OrphanReaper.hasOtherProcesses(emptyList(), 100) { true })
|
||||
}
|
||||
}
|
||||
@@ -24,4 +24,10 @@ class PipPolicyTest {
|
||||
assertEquals(100 to 239, PipPolicy.aspect(1080, 5760))
|
||||
assertEquals(16 to 9, PipPolicy.aspect(0, 0))
|
||||
}
|
||||
|
||||
@Test fun pipOutputFitsTheResizedSurfaceWithoutChangingAspectRatio() {
|
||||
assertEquals(640 to 360, PipPolicy.outputSize(640, 480, 1920, 1080))
|
||||
assertEquals(480 to 270, PipPolicy.outputSize(480, 270, 1920, 1080))
|
||||
assertNull(PipPolicy.outputSize(0, 270, 1920, 1080))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class PowerVrAutoDriversTest {
|
||||
private val context: Context = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun reset() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
SessionPrefs.setLinuxDriver(context, "imported-linux")
|
||||
SessionPrefs.setAndroidDriver(context, "imported-display")
|
||||
}
|
||||
|
||||
@Test fun autoRepairsStaleAdrenoSelectionsOnPowerVr() {
|
||||
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
|
||||
assertEquals("", SessionPrefs.linuxDriver(context))
|
||||
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
|
||||
}
|
||||
|
||||
@Test fun explicitManualChoicesRemainOnPowerVr() {
|
||||
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL)
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
|
||||
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
|
||||
assertEquals("imported-display", SessionPrefs.androidDriver(context))
|
||||
}
|
||||
|
||||
@Test fun adrenoAutoChoicesRemain() {
|
||||
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = false)
|
||||
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
|
||||
assertEquals("imported-display", SessionPrefs.androidDriver(context))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PowerVrComponentsTest {
|
||||
@Test fun onlyDxvkIsManagedWithTheSystemPowerVrRuntime() {
|
||||
assertTrue(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = true))
|
||||
assertFalse(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = false))
|
||||
assertFalse(ComponentsManager.runtimeManaged("fex", systemPowerVr = true))
|
||||
assertFalse(ComponentsManager.runtimeManaged("vkd3d", systemPowerVr = true))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class PowerVrQueuedComponentsTest {
|
||||
@Test fun managedDxvkQueueRemainsVisibleAndCanBeCancelled() {
|
||||
val context: Context = RuntimeEnvironment.getApplication()
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
root.deleteRecursively()
|
||||
val data = File(context.filesDir, "components")
|
||||
data.deleteRecursively()
|
||||
data.mkdirs()
|
||||
val proton = File(root, "root/.local/share/Steam/compatibilitytools.d/test-proton")
|
||||
File(proton, "files/lib/wine").mkdirs()
|
||||
File(proton, "proton").writeText("# test Proton\n")
|
||||
File(proton, "version").writeText("1 test-build\n")
|
||||
File(data, "state.json").writeText(JSONObject().put("queued", JSONObject().put("test-proton",
|
||||
JSONObject().put("dxvk", JSONObject().put("kind", "package").put("file", "chosen.wcp").put("label", "chosen DXVK"))
|
||||
)).toString())
|
||||
|
||||
assertTrue(ComponentsManager.applyQueued(context) { ComponentsManager.runtimeManaged(it, true) }.isEmpty())
|
||||
val deferred = ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk")
|
||||
assertEquals("chosen DXVK", deferred.queued)
|
||||
|
||||
ComponentsManager.cancelQueued(context, "test-proton", "dxvk")
|
||||
assertNull(ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk").queued)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.nio.channels.SeekableByteChannel
|
||||
import java.nio.file.DirectoryStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.SecureDirectoryStream
|
||||
import java.nio.file.StandardOpenOption
|
||||
import java.nio.file.attribute.BasicFileAttributeView
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
|
||||
internal object JvmSecureSourceOpener : SecureSourceOpener {
|
||||
override fun <T> withChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
|
||||
val expected = root.resolve(relative).normalize()
|
||||
if (!expected.startsWith(root.normalize())) return null
|
||||
val initial = runCatching {
|
||||
Files.readAttributes(expected, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS)
|
||||
}.getOrNull() ?: return null
|
||||
val links = runCatching {
|
||||
(Files.getAttribute(expected, "unix:nlink", LinkOption.NOFOLLOW_LINKS) as Number).toLong()
|
||||
}.getOrNull() ?: return null
|
||||
val expectedKey = initial.fileKey() ?: return null
|
||||
if (!initial.isRegularFile || initial.isSymbolicLink || links != 1L) return null
|
||||
val first = Files.newDirectoryStream(root)
|
||||
if (first !is SecureDirectoryStream<*>) {
|
||||
first.close()
|
||||
return null
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val secureFirst = first as SecureDirectoryStream<Path>
|
||||
val opened = ArrayList<DirectoryStream<Path>>()
|
||||
opened += first
|
||||
var current = secureFirst
|
||||
return try {
|
||||
val parts = relative.map { it.toString() }
|
||||
if (parts.isEmpty()) return null
|
||||
for (part in parts.dropLast(1)) {
|
||||
val child = Paths.get(part)
|
||||
val attrs = current.getFileAttributeView(
|
||||
child, BasicFileAttributeView::class.java, LinkOption.NOFOLLOW_LINKS,
|
||||
).readAttributes()
|
||||
if (!attrs.isDirectory || attrs.isSymbolicLink) return null
|
||||
val next = current.newDirectoryStream(child, LinkOption.NOFOLLOW_LINKS)
|
||||
opened += next
|
||||
current = next
|
||||
}
|
||||
val leaf = Paths.get(parts.last())
|
||||
val attrs = current.getFileAttributeView(
|
||||
leaf, BasicFileAttributeView::class.java, LinkOption.NOFOLLOW_LINKS,
|
||||
).readAttributes()
|
||||
if (!attrs.isRegularFile || attrs.isSymbolicLink || attrs.fileKey() != expectedKey) return null
|
||||
current.newByteChannel(leaf, setOf(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)).use { channel ->
|
||||
val after = current.getFileAttributeView(
|
||||
leaf, BasicFileAttributeView::class.java, LinkOption.NOFOLLOW_LINKS,
|
||||
).readAttributes()
|
||||
if (after.fileKey() != expectedKey) null else block(channel)
|
||||
}
|
||||
} finally {
|
||||
opened.asReversed().forEach { runCatching { it.close() } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun installJvmSecureSourceOpener() {
|
||||
EnhancedSessionLogShare.setSourceOpenerForTest(JvmSecureSourceOpener)
|
||||
}
|
||||
|
||||
internal fun resetSecureSourceOpener() {
|
||||
EnhancedSessionLogShare.setSourceOpenerForTest(null)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
@@ -31,11 +32,18 @@ class SessionEndHintTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
private lateinit var activity: SessionActivity
|
||||
private var previousArchitecture: String? = null
|
||||
private var previousLog: File? = null
|
||||
private var previousDirectory: File? = null
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
previousArchitecture = SessionState.steamClientArch
|
||||
previousLog = SessionState.logFile
|
||||
previousDirectory = SessionState.logDirectory
|
||||
SessionState.logFile = null
|
||||
SessionState.logDirectory = null
|
||||
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
|
||||
DetectedGpu.name = "test GPU"
|
||||
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
SessionState.steamClientArch = "arm64"
|
||||
}
|
||||
@@ -43,7 +51,10 @@ class SessionEndHintTest {
|
||||
@After
|
||||
fun tearDown() {
|
||||
SessionState.steamClientArch = previousArchitecture
|
||||
SessionState.logFile = previousLog
|
||||
SessionState.logDirectory = previousDirectory
|
||||
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
|
||||
DetectedGpu.name = "test GPU"
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,10 +91,35 @@ class SessionEndHintTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun vulkanFailureOnNonAdrenoExplainsTheMissingLinuxDriver() {
|
||||
DetectedGpu.family = GpuInfo.Family.NOT_ADRENO
|
||||
fun vulkanFailureOnNonAdrenoIdentifiesTheGpuAndOffersDriverGuidance() {
|
||||
for (family in GpuInfo.Family.entries.filter { it.mali || it == GpuInfo.Family.POWERVR || it == GpuInfo.Family.NOT_ADRENO }) {
|
||||
DetectedGpu.family = family
|
||||
val expected = "test GPU (${family.label("test GPU")})\n" + activity.getString(R.string.session_end_vulkan_device)
|
||||
assertEquals(family.name, expected, hintText(vulkanLog()))
|
||||
}
|
||||
DetectedGpu.family = GpuInfo.Family.POWERVR
|
||||
DetectedGpu.name = "Samsung Xclipse 940"
|
||||
assertEquals("Samsung Xclipse 940 (Samsung Xclipse)\n" + activity.getString(R.string.session_end_vulkan_device),
|
||||
hintText(vulkanLog()))
|
||||
}
|
||||
|
||||
assertEquals(activity.getString(R.string.session_end_gpu_unsupported), hintText(vulkanLog()))
|
||||
@Test
|
||||
fun cleanExitRetainsAnUnrecoveredPresentationFault() {
|
||||
SessionState.logDirectory = temporary.root
|
||||
File(temporary.root, "wayland.log").writeText("DD_PRESENT_FAULT: GPU completion is unknown\n")
|
||||
val hint = exitHint(0)
|
||||
assertNotNull(hint)
|
||||
assertEquals(activity.getString(R.string.session_end_present_fault, "GPU completion is unknown"),
|
||||
ReflectionHelpers.getField<String>(hint, "text"))
|
||||
assertTrue(ReflectionHelpers.getField(hint, "evenOnSuccess"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cleanExitIgnoresRecoveredFaultsAndUnrelatedSessionWarnings() {
|
||||
SessionState.logDirectory = temporary.root
|
||||
File(temporary.root, "wayland.log").writeText("DD_PRESENT_FAULT: old fault\npresentation recovered: fault cleared\n")
|
||||
SessionState.logFile = sigillLog()
|
||||
assertNull(exitHint(0))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -103,6 +139,9 @@ class SessionEndHintTest {
|
||||
private fun hint(log: File?): Any? = SessionActivity::class.java
|
||||
.getDeclaredMethod("sessionEndHint", File::class.java).apply { isAccessible = true }.invoke(activity, log)
|
||||
|
||||
private fun exitHint(status: Int): Any? = SessionActivity::class.java
|
||||
.getDeclaredMethod("sessionExitHint", Int::class.javaPrimitiveType).apply { isAccessible = true }.invoke(activity, status)
|
||||
|
||||
private fun hintText(log: File): String {
|
||||
val result = hint(log)
|
||||
assertNotNull(result)
|
||||
@@ -112,10 +151,11 @@ class SessionEndHintTest {
|
||||
@Implements(value = GpuInfo.Companion::class, isInAndroidSdk = false)
|
||||
class DetectedGpu {
|
||||
@Implementation
|
||||
fun detect(): GpuInfo = GpuInfo("test GPU", if (family == GpuInfo.Family.A6XX) 610 else 0, family, "", false)
|
||||
fun detect(): GpuInfo = GpuInfo(name, if (family == GpuInfo.Family.A6XX) 610 else 0, family, "", false)
|
||||
|
||||
companion object {
|
||||
var family = GpuInfo.Family.NOT_ADRENO
|
||||
var name = "test GPU"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
@@ -24,6 +26,10 @@ import java.util.zip.ZipFile
|
||||
class SessionLogShareTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Before fun installSecureSourceOpener() = installJvmSecureSourceOpener()
|
||||
|
||||
@After fun resetSourceOpener() = resetSecureSourceOpener()
|
||||
|
||||
private val secret = "GET /x?sessionid=abcdef123456 200"
|
||||
private val leaked = "abcdef123456"
|
||||
|
||||
@@ -86,8 +92,9 @@ class SessionLogShareTest {
|
||||
File(folder, "events.jsonl").writeText("$secret\n")
|
||||
|
||||
val out = zip(folder)
|
||||
for (name in listOf("app.log", "session.log", "steam/deep/nested.txt", ".hidden.txt", "events.jsonl"))
|
||||
for (name in listOf("app.log", "session.log", "events.jsonl"))
|
||||
assertFalse(name, out.getValue(name).contains(leaked))
|
||||
assertTrue(out.values.none { it.contains(leaked) })
|
||||
}
|
||||
|
||||
@Test fun aRecordUnderOtherRedactorRulesVouchesForNothing() {
|
||||
@@ -187,7 +194,7 @@ class SessionLogShareTest {
|
||||
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
|
||||
}
|
||||
|
||||
@Test fun steamLogsPastTheSizeLimitStayOut() {
|
||||
@Test fun steamLogsPastTheSizeLimitAreBoundedAndDeclared() {
|
||||
val folder = tmp.newFolder("2026-10-06-07-steam")
|
||||
File(folder, "session.log").writeText("ok\n")
|
||||
File(folder, "steam").mkdirs()
|
||||
@@ -196,9 +203,11 @@ class SessionLogShareTest {
|
||||
val line = ByteArray(1024) { 'x'.code.toByte() }.also { it[it.size - 1] = '\n'.code.toByte() }
|
||||
repeat(9 * 1024) { out.write(line) }
|
||||
}
|
||||
val names = zip(folder).keys
|
||||
assertTrue("steam/console_log.txt" in names)
|
||||
assertFalse("steam/cef_log.previous.txt" in names)
|
||||
val output = zip(folder)
|
||||
assertTrue("steam/console_log.txt" in output)
|
||||
assertTrue("steam/cef_log.previous.txt" in output)
|
||||
assertTrue(output.getValue("steam/cef_log.previous.txt").contains("diagnostic file truncated"))
|
||||
assertTrue(output.getValue("diagnostics-manifest.json").contains("\"status\": \"truncated\""))
|
||||
}
|
||||
|
||||
@Test fun streamingComparisonPreservesUnchangedFileAndReplacesChangedFile() {
|
||||
|
||||
@@ -2,14 +2,17 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.UUID
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.zip.ZipFile
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
@@ -21,6 +24,69 @@ import org.robolectric.annotation.Config
|
||||
class SessionLogShareZipTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun installSecureSourceOpener() = installJvmSecureSourceOpener()
|
||||
|
||||
@After fun resetSourceOpener() = resetSecureSourceOpener()
|
||||
|
||||
@Test fun startupRemovesAbandonedDiagnosticStagesAndPreservesActiveSnapshots() {
|
||||
val abandoned = File(app.cacheDir, "share-${UUID.randomUUID()}.diagnostic-stage").apply { mkdirs() }
|
||||
val active = EnhancedSessionLogShare.acquireDiagnosticStage(app, "share")
|
||||
try {
|
||||
EnhancedSessionLogShare.cleanupAbandonedStages(app)
|
||||
assertFalse(abandoned.exists())
|
||||
assertTrue(active.directory.isDirectory)
|
||||
EnhancedSessionLogShare.cleanupAbandonedStages(app)
|
||||
assertTrue(active.directory.isDirectory)
|
||||
val probeClassResource = checkNotNull(
|
||||
DiagnosticStageLockProbe::class.java.getResource("DiagnosticStageLockProbe.class"),
|
||||
)
|
||||
val probeClass = File(probeClassResource.toURI())
|
||||
var classPathRoot = checkNotNull(probeClass.parentFile)
|
||||
repeat(4) { classPathRoot = checkNotNull(classPathRoot.parentFile) }
|
||||
val classPath = classPathRoot.absolutePath
|
||||
val javaName = if (checkNotNull(System.getProperty("os.name")).startsWith("Windows")) {
|
||||
"java.exe"
|
||||
} else {
|
||||
"java"
|
||||
}
|
||||
val java = File(File(System.getProperty("java.home"), "bin"), javaName)
|
||||
val probe = ProcessBuilder(
|
||||
java.absolutePath,
|
||||
"-cp",
|
||||
classPath,
|
||||
DiagnosticStageLockProbe::class.java.name,
|
||||
File(active.directory, ".active").absolutePath,
|
||||
).redirectErrorStream(true).start()
|
||||
val completed = probe.waitFor(5, TimeUnit.SECONDS)
|
||||
if (!completed) probe.destroyForcibly()
|
||||
assertTrue("lock probe timed out", completed)
|
||||
assertEquals("cleanup released the active stage lock", 0, probe.exitValue())
|
||||
} finally {
|
||||
active.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun anArchiveCanBeWrittenOutsideTheShareFolder() {
|
||||
SessionLogShare.clear(app)
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-11-03-01-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/request-1")
|
||||
val secondOut = File(app.getExternalFilesDir(null), "agent-logs/request-2")
|
||||
try {
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
val zip = SessionLogShare.zipFolder(app, session, out)!!
|
||||
val secondZip = SessionLogShare.zipFolder(app, session, secondOut)!!
|
||||
assertEquals(out, zip.parentFile)
|
||||
assertFalse(File(app.cacheDir, "share").exists())
|
||||
assertTrue(zip.isFile)
|
||||
assertEquals(secondOut, secondZip.parentFile)
|
||||
assertTrue(secondZip.isFile)
|
||||
} finally {
|
||||
out.deleteRecursively()
|
||||
secondOut.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aLargeSteamLogIsRedactedInTheSharedArchive() {
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-10-08-02-steam").apply { mkdirs() }
|
||||
val raw = File(session, "steam-42.log")
|
||||
@@ -38,23 +104,11 @@ class SessionLogShareZipTest {
|
||||
val zip = SessionLogShare.zipFolder(app, session)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val entry = archive.getEntry("${session.name}/steam-42.log")!!
|
||||
archive.getInputStream(entry).use { input ->
|
||||
val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n"
|
||||
val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size)
|
||||
var offset = 0
|
||||
while (offset < prefix.size) {
|
||||
val count = input.read(prefix, offset, prefix.size - offset)
|
||||
assertTrue("zip entry ended before its scrubbed prefix", count > 0)
|
||||
offset += count
|
||||
}
|
||||
assertEquals(expected, String(prefix, StandardCharsets.UTF_8))
|
||||
input.bufferedReader().use { reader ->
|
||||
val trailing = requireNotNull(reader.readLine())
|
||||
assertFalse("trailing secret survived", trailing.contains(trailingSecret))
|
||||
assertEquals("refresh_token=<redacted:token>", trailing)
|
||||
assertEquals(null, reader.readLine())
|
||||
}
|
||||
}
|
||||
val shared = archive.getInputStream(entry).bufferedReader().readText()
|
||||
assertTrue(shared.contains("diagnostic file truncated"))
|
||||
assertFalse("early secret survived", shared.contains(earlySecret))
|
||||
assertFalse("trailing secret survived", shared.contains(trailingSecret))
|
||||
assertTrue(shared.contains("refresh_token=<redacted:token>"))
|
||||
}
|
||||
} finally {
|
||||
SessionLogShare.clear(app)
|
||||
|
||||
@@ -41,6 +41,7 @@ class SettingsResetTest {
|
||||
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
|
||||
SessionPrefs.setGuestHostname(app, "MyDeck")
|
||||
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
|
||||
assertTrue(EnhancedDiagnostics.setArmed(app, true))
|
||||
SessionPrefs.setHudShowFps(app, false)
|
||||
SessionPrefs.setHudShowBattery(app, false)
|
||||
SessionPrefs.setHudShowGraph(app, false)
|
||||
@@ -64,6 +65,7 @@ class SettingsResetTest {
|
||||
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
|
||||
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
|
||||
assertFalse(SessionPrefs.gameDebugLogsEnabled(app))
|
||||
assertFalse(EnhancedDiagnostics.isArmed(app))
|
||||
val guest = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
|
||||
"root/.config/droiddeck/game-environment.json")
|
||||
assertFalse(org.json.JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class WinComponentRevisionTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private fun installed(revision: Int? = null): File = temp.newFolder().also { directory ->
|
||||
val meta = JSONObject().put("version", "10.0.40219")
|
||||
revision?.let { meta.put("revision", it) }
|
||||
File(directory, "component.json").writeText(meta.toString())
|
||||
}
|
||||
|
||||
@Test fun legacyComponentsStayInstalledUntilTheCatalogRequestsARepair() {
|
||||
val directory = installed()
|
||||
assertEquals("10.0.40219", WinComponents.installedVersion(directory, 0))
|
||||
assertNull(WinComponents.installedVersion(directory, 1))
|
||||
}
|
||||
|
||||
@Test fun repairedComponentsStayInstalledAndAreNotDowngradedByAnOlderCatalog() {
|
||||
val directory = installed(2)
|
||||
assertEquals("10.0.40219", WinComponents.installedVersion(directory, 2))
|
||||
assertEquals("10.0.40219", WinComponents.installedVersion(directory, 1))
|
||||
assertNull(WinComponents.installedVersion(directory, 3))
|
||||
}
|
||||
|
||||
@Test fun outdatedComponentsRemainDownloadedForOfflineControls() {
|
||||
val directory = installed()
|
||||
assertNull(WinComponents.installedVersion(directory, 1))
|
||||
assertEquals(listOf(directory.name), WinComponents.downloadedIds(directory.parentFile))
|
||||
}
|
||||
|
||||
@Test fun enablingDownloadedComponentsRequiresTheCatalogRevision() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val id = "vcredist2010_dll"
|
||||
val directory = File(LinuxRuntime.rootDir(context), "opt/droiddeck/wincomponents/$id").apply { mkdirs() }
|
||||
val metadata = File(directory, "component.json")
|
||||
metadata.writeText("""{"version":"10.0.40219"}""")
|
||||
val catalog = File(context.filesDir, "wincomponents-catalog.json")
|
||||
catalog.writeText("""{"components":[{"name":"$id","revision":1}]}""")
|
||||
try {
|
||||
assertEquals(listOf(id), WinComponents.downloadedIds(context))
|
||||
assertNull(WinComponents.installed(context, id))
|
||||
metadata.writeText("""{"version":"10.0.40219","revision":1}""")
|
||||
assertEquals("10.0.40219", WinComponents.installed(context, id))
|
||||
catalog.delete()
|
||||
assertEquals("10.0.40219", WinComponents.installed(context, id))
|
||||
} finally {
|
||||
directory.deleteRecursively()
|
||||
catalog.delete()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun missingOrInvalidInstallMetadataNeedsInstallation() {
|
||||
val directory = temp.newFolder()
|
||||
assertNull(WinComponents.installedVersion(directory, 0))
|
||||
File(directory, "component.json").writeText("{")
|
||||
assertNull(WinComponents.installedVersion(directory, 1))
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,22 @@ class CloudPlanTest {
|
||||
assertTrue(CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 2500)), base).transfer.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun gogRawObjectsThatStillMatchTheLocalBytesAreResentOnce() {
|
||||
val base = mapOf("s" to Entry("a", "a", 1000))
|
||||
val plan = CloudPlan.up(mapOf("s" to Local("a")), mapOf("s" to Remote("a", 1000)), base)
|
||||
assertEquals(listOf("s"), plan.same)
|
||||
assertEquals(listOf("s"), CloudPlan.upSend(plan, force = false, repairRawGog = true))
|
||||
assertTrue(CloudPlan.upSend(plan, force = false, repairRawGog = false).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aForcedGogUploadSendsUnchangedFilesEvenWithoutACloudHash() {
|
||||
val base = mapOf("s" to Entry("a", "a", 1000))
|
||||
val plan = CloudPlan.up(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 1000)), base)
|
||||
assertTrue(plan.transfer.isEmpty() && plan.conflicts.isEmpty() && plan.same.isEmpty())
|
||||
assertEquals(listOf("s"), CloudPlan.upSend(plan, force = true, repairRawGog = true, allLocal = listOf("s")))
|
||||
assertTrue(CloudPlan.upSend(plan, force = true, repairRawGog = false, allLocal = listOf("s")).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun theBaselineSurvivesItsJson() {
|
||||
val b = mapOf("a/b.sav" to Entry("l", "c", 5), "x" to Entry("l2", null, -1))
|
||||
assertEquals(b, CloudPlan.fromJson(CloudPlan.toJson(b)))
|
||||
|
||||
@@ -22,7 +22,7 @@ class CloudSavesTest {
|
||||
val puts = ArrayList<String>()
|
||||
override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) }
|
||||
override fun get(file: CloudFile) = files.getValue(file.name)
|
||||
override fun put(files: Map<String, ByteArray>): Map<String, Long> =
|
||||
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> =
|
||||
files.mapValues { (k, v) -> puts += k; this.files[k] = v to 99_000L; 99_000L }
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,81 @@ class GogCloudKeysTest {
|
||||
assertFalse(gzipGogPut(raw).contentEquals(gameGz))
|
||||
assertArrayEquals(gameGz, gogDecodeCloudBody(gameGz, null))
|
||||
}
|
||||
|
||||
@Test fun putUploadsTheGogGzipBodyWithEncodingAndCompressedHash() {
|
||||
val raw = "savegame0".toByteArray()
|
||||
val server = java.net.ServerSocket(0, 4, java.net.InetAddress.getByName("127.0.0.1"))
|
||||
val requests = java.util.concurrent.CopyOnWriteArrayList<Request>()
|
||||
val worker = Thread {
|
||||
repeat(2) {
|
||||
server.accept().use { client ->
|
||||
client.soTimeout = 5_000
|
||||
val input = client.getInputStream()
|
||||
val line = readLine(input)
|
||||
val parts = line.split(' ')
|
||||
val headers = LinkedHashMap<String, String>()
|
||||
while (true) {
|
||||
val h = readLine(input)
|
||||
if (h.isEmpty()) break
|
||||
val colon = h.indexOf(':')
|
||||
headers[h.substring(0, colon).trim().lowercase()] = h.substring(colon + 1).trim()
|
||||
}
|
||||
val length = headers["content-length"]?.toIntOrNull() ?: 0
|
||||
val body = ByteArray(length)
|
||||
var offset = 0
|
||||
while (offset < length) {
|
||||
val n = input.read(body, offset, length - offset)
|
||||
if (n < 0) break
|
||||
offset += n
|
||||
}
|
||||
requests += Request(parts[0], parts[1], headers, body)
|
||||
val response = if (parts[0] == "PUT") {
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
} else {
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n" +
|
||||
"Etag: \"${CloudSaves.md5(body)}\"\r\n" +
|
||||
"Last-Modified: Tue, 20 Oct 2026 10:00:00 GMT\r\nConnection: close\r\n\r\n"
|
||||
}
|
||||
client.getOutputStream().apply { write(response.toByteArray()); flush() }
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
try {
|
||||
val cloud = GogCloud("user", "client", "token", "saves", "http://127.0.0.1:${server.localPort}/v1/user/client")
|
||||
val source = java.io.File.createTempFile("save", ".sav").apply { writeBytes(raw) }
|
||||
val result = try {
|
||||
cloud.putFiles(mapOf("save.sav" to source), mapOf("save.sav" to 1_793_490_825_000L)).getValue("save.sav")
|
||||
} finally {
|
||||
source.delete()
|
||||
}
|
||||
assertTrue(result.modifiedMs > 0)
|
||||
assertEquals(CloudSaves.md5(raw), result.md5)
|
||||
val put = requests[0]
|
||||
assertEquals("PUT", put.method)
|
||||
assertEquals("/v1/user/client/saves%2Fsave.sav", put.path)
|
||||
assertEquals("gzip", put.headers["content-encoding"])
|
||||
assertEquals("2026-10-31T23:53:45+00:00", put.headers["x-object-meta-locallastmodified"])
|
||||
assertArrayEquals(gzipGogPut(raw), put.body)
|
||||
assertEquals(CloudSaves.md5(put.body), put.headers["etag"])
|
||||
assertArrayEquals(raw, gogDecodeCloudBody(put.body, put.headers["content-encoding"]))
|
||||
assertEquals("HEAD", requests[1].method)
|
||||
} finally {
|
||||
server.close()
|
||||
worker.join(2_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Request(val method: String, val path: String, val headers: Map<String, String>, val body: ByteArray)
|
||||
|
||||
private fun readLine(input: java.io.InputStream): String {
|
||||
val out = ByteArrayOutputStream()
|
||||
while (true) {
|
||||
val b = input.read()
|
||||
if (b < 0 || b == '\n'.code) break
|
||||
if (b != '\r'.code) out.write(b)
|
||||
}
|
||||
return out.toString("UTF-8")
|
||||
}
|
||||
|
||||
private fun String.hex() = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
@@ -53,10 +53,10 @@ class StoreInstallRootTest {
|
||||
assertEquals(SessionPrefs.DEFAULT_STORAGE_ASK, SessionPrefs.defaultStorage(app))
|
||||
}
|
||||
|
||||
@Test fun defaultExternalStorageFallsBackToTheInstallDialogWhenNoCardIsPresent() {
|
||||
@Test fun defaultExternalStorageFallsBackToInternalWhenNoCardIsPresent() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
|
||||
assertNull(StoreInstallRoot.defaultTarget(app))
|
||||
assertEquals(StoreInstallRoot.internalRoot(app).absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
}
|
||||
|
||||
@Test fun aChosenFolderIsUsedForDefaultExternalStorage() {
|
||||
@@ -74,7 +74,7 @@ class StoreInstallRootTest {
|
||||
assertFalse(File(root, ".droiddeck-write-probe").exists())
|
||||
}
|
||||
|
||||
@Test fun aDisconnectedChosenFolderDoesNotFallBackToAnotherTarget() {
|
||||
@Test fun aDisconnectedChosenFolderFallsBackToInternalUntilItIsBack() {
|
||||
val card = File(app.filesDir, "card/steam").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, card.path, "Card")
|
||||
val folder = File(app.filesDir, "usb/SSD").apply { mkdirs() }
|
||||
@@ -83,8 +83,11 @@ class StoreInstallRootTest {
|
||||
assertNotNull(StoreInstallRoot.defaultTarget(app))
|
||||
|
||||
assertTrue(folder.delete())
|
||||
assertNull(StoreInstallRoot.defaultTarget(app))
|
||||
assertEquals(StoreInstallRoot.internalRoot(app).absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
assertEquals(File(card, "Games").absolutePath, StoreInstallRoot.detectedExternalTarget(app)?.root?.absolutePath)
|
||||
|
||||
assertTrue(folder.mkdirs())
|
||||
assertEquals(File(folder, "Games").absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
}
|
||||
|
||||
@Test fun filesOnAChosenFolderAreMappedIntoTheGuest() {
|
||||
@@ -303,4 +306,20 @@ class StoreInstallRootTest {
|
||||
assertEquals("itch", StoreInstallRoot.storeDir(File("/games"), Store.ITCH).name)
|
||||
assertEquals("Game Jolt", StoreInstallRoot.storeDir(File("/games"), Store.GAMEJOLT).name)
|
||||
}
|
||||
|
||||
@Test fun anUnpluggedLibraryDriveSendsInstallsToInternalUntilItIsBack() {
|
||||
val files = File(app.filesDir, "usb-drive/files")
|
||||
val library = File(files, "steam")
|
||||
SessionPrefs.setGameStorage(app, library.path, "USB drive")
|
||||
SessionPrefs.setDefaultStorage(app, SessionPrefs.DEFAULT_STORAGE_EXTERNAL)
|
||||
val internal = StoreInstallRoot.internalRoot(app).absolutePath
|
||||
|
||||
assertEquals(internal, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
assertEquals(listOf(internal), StoreInstallRoot.targets(app).map { it.root.absolutePath })
|
||||
assertNull(StoreInstallRoot.libraryRoot(app))
|
||||
|
||||
library.mkdirs()
|
||||
assertEquals(File(library, "Games").absolutePath, StoreInstallRoot.defaultTarget(app)?.root?.absolutePath)
|
||||
assertEquals(File(library, "Games").absolutePath, StoreInstallRoot.libraryRoot(app)?.absolutePath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.app.Application
|
||||
import com.droiddeck.launcher.stores.gog.GogMaintenance
|
||||
import org.json.JSONObject
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowLooper
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], application = Application::class)
|
||||
class StoresStateRefreshTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
private val secret: SecretKey = SecretKeySpec(ByteArray(32), "AES")
|
||||
private val plain = CredentialCipher.KeyProvider { secret }
|
||||
|
||||
private fun opening(onOpen: () -> Unit) = object : CredentialCipher.KeyProvider {
|
||||
override fun key() = secret
|
||||
override fun existing(): SecretKey { onOpen(); return secret }
|
||||
}
|
||||
|
||||
private fun refreshRunning() = Thread.getAllStackTraces().keys.any { it.name == "stores-refresh" }
|
||||
|
||||
private fun awaitRefreshDone() {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10)
|
||||
while (refreshRunning() && System.nanoTime() < deadline) Thread.sleep(10)
|
||||
assertTrue("refresh did not finish", !refreshRunning())
|
||||
ShadowLooper.idleMainLooper()
|
||||
}
|
||||
|
||||
@Before fun setUp() {
|
||||
StoreAccounts.keys = plain
|
||||
StoreAccounts.keystoreFailed = false
|
||||
StoreAccounts.write(app, Store.EPIC, JSONObject().put("access_token", "token").put("display_name", "Someone"))
|
||||
StoresState.accounts.clear()
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
StoreAccounts.keys = plain
|
||||
for (store in Store.entries) StoreAccounts.clear(app, store)
|
||||
StoreAccounts.keys = CredentialCipher.Keystore
|
||||
}
|
||||
|
||||
@Test fun gogCheckDoesNotWaitForTheCredentialLock() {
|
||||
val held = CountDownLatch(1)
|
||||
val release = CountDownLatch(1)
|
||||
val holder = thread { synchronized(StoreAccounts) { held.countDown(); release.await() } }
|
||||
held.await()
|
||||
val done = CountDownLatch(1)
|
||||
thread { GogMaintenance.checkInstalled(app, emptyList()); done.countDown() }
|
||||
try {
|
||||
assertTrue("checkInstalled waited for the credential lock", done.await(2, TimeUnit.SECONDS))
|
||||
} finally {
|
||||
release.countDown()
|
||||
holder.join()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun overlappingRefreshesShareOneMorePass() {
|
||||
val opens = AtomicInteger()
|
||||
val entered = CountDownLatch(1)
|
||||
val release = CountDownLatch(1)
|
||||
StoreAccounts.keys = opening {
|
||||
opens.incrementAndGet()
|
||||
entered.countDown()
|
||||
release.await()
|
||||
}
|
||||
StoresState.refresh(app)
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS))
|
||||
repeat(4) { StoresState.refresh(app) }
|
||||
} finally {
|
||||
release.countDown()
|
||||
}
|
||||
awaitRefreshDone()
|
||||
assertEquals(2, opens.get())
|
||||
assertEquals("Someone", StoresState.accounts[Store.EPIC])
|
||||
}
|
||||
|
||||
@Test fun aRequestMadeDuringAFailedPassStillRuns() {
|
||||
val entered = CountDownLatch(1)
|
||||
val release = CountDownLatch(1)
|
||||
StoreAccounts.keys = opening {
|
||||
entered.countDown()
|
||||
release.await()
|
||||
throw Error("keystore died")
|
||||
}
|
||||
StoresState.refresh(app)
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS))
|
||||
StoresState.refresh(app)
|
||||
StoreAccounts.keys = plain
|
||||
} finally {
|
||||
release.countDown()
|
||||
}
|
||||
awaitRefreshDone()
|
||||
awaitRefreshDone()
|
||||
assertEquals("Someone", StoresState.accounts[Store.EPIC])
|
||||
}
|
||||
|
||||
@Test fun aFailedRefreshDoesNotBlockTheNextOne() {
|
||||
val failed = CountDownLatch(1)
|
||||
StoreAccounts.keys = opening { failed.countDown(); throw Error("keystore died") }
|
||||
StoresState.refresh(app)
|
||||
assertTrue(failed.await(5, TimeUnit.SECONDS))
|
||||
awaitRefreshDone()
|
||||
assertNull(StoresState.accounts[Store.EPIC])
|
||||
StoreAccounts.keys = plain
|
||||
StoresState.refresh(app)
|
||||
awaitRefreshDone()
|
||||
assertEquals("Someone", StoresState.accounts[Store.EPIC])
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,11 @@ class BattleNetInstallTest {
|
||||
assertNull(BattleNetInstall.latestBuild("", "us"))
|
||||
}
|
||||
|
||||
@Test fun theVersionServiceIsBlizzardsChineseOneForChina() {
|
||||
assertEquals("https://us.version.battle.net/v2/products/wow/versions", BattleNetInstall.versionsUrl("us", "wow"))
|
||||
assertEquals("https://cn.version.battlenet.com.cn/v2/products/d3cn/versions", BattleNetInstall.versionsUrl("cn", "d3cn"))
|
||||
}
|
||||
|
||||
@Test fun theDeviceLanguagePicksABlizzardLocale() {
|
||||
assertEquals("enUS", BattleNetInstall.locale(Locale.US))
|
||||
assertEquals("enGB", BattleNetInstall.locale(Locale.UK))
|
||||
|
||||
@@ -457,7 +457,7 @@ class EpicClientTest {
|
||||
assertEquals("/root/Games/Stores/Epic", EpicClient.prepareInstallDir(context))
|
||||
}
|
||||
|
||||
@Test fun aDisconnectedDefaultFolderKeepsTheLauncherInstallDir() {
|
||||
@Test fun aDisconnectedDefaultFolderMovesTheLauncherInstallDirToInternal() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val previousStorage = com.droiddeck.launcher.session.SessionPrefs.defaultStorage(context)
|
||||
val previousFolder = com.droiddeck.launcher.session.SessionPrefs.defaultStorageFolder(context)
|
||||
@@ -470,8 +470,8 @@ class EpicClientTest {
|
||||
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorageFolder(
|
||||
context, File(context.filesDir, "missing-${System.nanoTime()}").path, "SSD")
|
||||
try {
|
||||
assertEquals(current, EpicClient.prepareInstallDir(context))
|
||||
assertEquals(current, org.json.JSONObject(settings.readText()).getString("defaultInstallDir"))
|
||||
assertEquals("/root/Games/Stores/Epic", EpicClient.prepareInstallDir(context))
|
||||
assertEquals("/root/Games/Stores/Epic", org.json.JSONObject(settings.readText()).getString("defaultInstallDir"))
|
||||
} finally {
|
||||
com.droiddeck.launcher.session.SessionPrefs.setDefaultStorage(context, previousStorage)
|
||||
if (previousFolder.isBlank()) com.droiddeck.launcher.session.SessionPrefs.clearDefaultStorageFolder(context)
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.SemanticsMatcher
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.assertIsEnabled
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onLast
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
@@ -12,8 +26,9 @@ import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
// Exercise the component UI without starting App's process-wide servers or crash handler.
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
@Config(sdk = [28], application = Application::class)
|
||||
class ComponentsPageProfileTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
private val gameA = Library.SteamGame(42, "Game A", null, "internal")
|
||||
@@ -98,4 +113,143 @@ class ComponentsPageProfileTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun systemPowerVrKeepsStoredDxvkDisabledAndQueuedDxvkCancellable() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
var cancelled = 0
|
||||
var imported = 0
|
||||
var swapped = 0
|
||||
var restored = 0
|
||||
showDxvk(
|
||||
systemPowerVr = true,
|
||||
onCancel = { cancelled++ },
|
||||
onImport = { imported++ },
|
||||
onSwap = { swapped++ },
|
||||
onRestore = { restored++ },
|
||||
)
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_queued, "Next DXVK"), substring = true).assertExists()
|
||||
compose.onNodeWithText("Stored DXVK").assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.common_cancel)).performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_import_wcp)).performScrollTo().assertIsEnabled().performClick()
|
||||
compose.runOnIdle {
|
||||
assertEquals(1, cancelled)
|
||||
assertEquals(1, imported)
|
||||
assertEquals(0, swapped)
|
||||
assertEquals(0, restored)
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun manualRuntimeKeepsDxvkSelectionAvailable() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
showDxvk(systemPowerVr = false)
|
||||
|
||||
compose.onNode(hasText("Stored DXVK") and SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.RadioButton)).assertIsEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun systemPowerVrGameProfileKeepsOtherComponentChoicesAndRuntimeOptionsAvailable() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
showDxvk(systemPowerVr = true)
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
|
||||
val inheritedChoices = compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general))
|
||||
inheritedChoices.assertCountEquals(4) // FEX preset, FEX package, Proton and VKD3D remain selectable.
|
||||
repeat(4) { inheritedChoices[it].assertIsEnabled() }
|
||||
val runtimeOptions = compose.onAllNodesWithText(context.getString(R.string.comp_game_runtime_options))
|
||||
runtimeOptions.assertCountEquals(2)
|
||||
repeat(2) { runtimeOptions[it].assertIsEnabled() }
|
||||
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertDoesNotExist()
|
||||
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists()
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun systemPowerVrGameProfileCanClearAnExistingDxvkOverrideWithoutSelectingAnother() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
showDxvk(systemPowerVr = true, gameDxvkOverride = true)
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).performScrollTo().assertIsEnabled().performClick()
|
||||
compose.onNodeWithText("Stored DXVK").assertDoesNotExist()
|
||||
compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general)).onLast().performClick()
|
||||
compose.waitUntil(5_000) { "dxvk" !in ComponentsManager.gameComponents(context, "42") }
|
||||
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
|
||||
}
|
||||
|
||||
private fun showDxvk(
|
||||
systemPowerVr: Boolean,
|
||||
gameDxvkOverride: Boolean = false,
|
||||
onCancel: () -> Unit = {},
|
||||
onImport: () -> Unit = {},
|
||||
onSwap: (String) -> Unit = {},
|
||||
onRestore: (String) -> Unit = {},
|
||||
) {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
File(context.filesDir, "components/state.json").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText(if (gameDxvkOverride) """{"profiles":{"42":{"dxvk":"stored.wcp"}}}""" else "{}")
|
||||
}
|
||||
val proton = ComponentsManager.Proton(
|
||||
"test-proton", "Test Proton", File(context.filesDir, "test-proton"), "/test-proton", "1.0", false,
|
||||
)
|
||||
val snapshot = ComponentsManager.Snapshot(
|
||||
protons = listOf(ComponentsManager.ProtonView(
|
||||
proton = proton,
|
||||
components = mapOf("dxvk" to ComponentsManager.Component("1.0", "", "Stored DXVK", "", "stored.wcp", "Next DXVK")),
|
||||
originals = listOf(ComponentsManager.Original("dxvk", "1.0", "Original DXVK", 1)),
|
||||
inUseByGame = false,
|
||||
)),
|
||||
packages = listOf(ComponentsManager.Package("stored.wcp", "dxvk", "Stored DXVK", "", 1)),
|
||||
)
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
ComponentsPage(
|
||||
snapshot = snapshot,
|
||||
catalog = emptyList(),
|
||||
catalogAt = 0,
|
||||
protonId = proton.id,
|
||||
comp = "dxvk",
|
||||
checking = false,
|
||||
busy = null,
|
||||
downloads = emptyMap(),
|
||||
onProton = {},
|
||||
onComp = {},
|
||||
onSwap = onSwap,
|
||||
onRestore = onRestore,
|
||||
onCancelQueued = onCancel,
|
||||
onDeletePackage = {},
|
||||
onDeleteOriginal = {},
|
||||
onDownload = {},
|
||||
onRefresh = {},
|
||||
onImport = onImport,
|
||||
onBack = {},
|
||||
gpu = GpuDriversState(powerVr = true, systemPowerVr = systemPowerVr),
|
||||
games = listOf(Library.SteamGame(42, "Game A", null, "internal")),
|
||||
requestInitialFocus = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -130,6 +130,12 @@ class AppUpdatesTest {
|
||||
assertNull(AppUpdates.installBlock(stable, me("eeeeeee", versionCode = 9)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theNonAdrenoTestBuildIsNeverReplacedByAnOfficialBuild() {
|
||||
val testBuild = AppUpdates.Installed("eeeeeee", 0, "0.2.0", 9, updatable = true, nonAdrenoTest = true)
|
||||
assertNotNull(AppUpdates.installBlock(stable, testBuild))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMissingVariantIsBlockedBeforeDownload() {
|
||||
val missing = release("ddddddd", withApk = false)
|
||||
|
||||
Reference in new issue
Block a user