mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-25 07:46:01 +00:00
fix(input): reconcile the second-screen picker
This commit is contained in:
commit
ec1d5126c4
197 files changed
+12209
-3764
No files matched your search
@@ -7,6 +7,7 @@ import android.os.Looper
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import com.droiddeck.launcher.frontend.AutoComponents
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.ExperimentalProtons
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
@@ -25,7 +26,9 @@ import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
@@ -88,6 +91,67 @@ class ProtonMenuAutoTest {
|
||||
File(this, "proton").apply { writeText(""); setExecutable(true) }
|
||||
}
|
||||
|
||||
private fun prerelease(tag: String) = ExperimentalProtons.Release(tag, "$tag.tar.xz", "https://github.com/o/r/releases/download/$tag/$tag.tar.xz", null, 1L)
|
||||
|
||||
private fun recreatedMenu(refreshes: AtomicInteger, tag: String) = ProtonMenu(activity, Handler(Looper.getMainLooper())) { idle }.apply {
|
||||
installer = menu.installer
|
||||
latestCheck = { false }
|
||||
experimentalRefresh = {
|
||||
refreshes.incrementAndGet()
|
||||
listOf(prerelease(tag))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRecreatedMenuJoinsTheRunningRefresh() {
|
||||
idle = false
|
||||
val started = CountDownLatch(1)
|
||||
val gate = CountDownLatch(1)
|
||||
val refreshes = AtomicInteger()
|
||||
menu.latestCheck = { false }
|
||||
menu.experimentalRefresh = {
|
||||
started.countDown()
|
||||
gate.await(5, TimeUnit.SECONDS)
|
||||
listOf(prerelease("first"))
|
||||
}
|
||||
menu.checkUpdates()
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS))
|
||||
val recreated = recreatedMenu(refreshes, "second")
|
||||
recreated.checkUpdates()
|
||||
gate.countDown()
|
||||
waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("first") }
|
||||
assertEquals(0, refreshes.get())
|
||||
recreated.checkUpdates()
|
||||
waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("second") }
|
||||
assertEquals(1, refreshes.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFinishedRefreshIsPublishedBeforeTheNextOneStarts() {
|
||||
idle = false
|
||||
val finished = CountDownLatch(1)
|
||||
val refreshes = AtomicInteger()
|
||||
menu.experimentalReleases = emptyList()
|
||||
menu.latestCheck = { false }
|
||||
menu.experimentalRefresh = {
|
||||
finished.countDown()
|
||||
listOf(prerelease("older"))
|
||||
}
|
||||
menu.checkUpdates()
|
||||
assertTrue(finished.await(5, TimeUnit.SECONDS))
|
||||
val recreated = recreatedMenu(refreshes, "newer")
|
||||
repeat(20) {
|
||||
recreated.checkUpdates()
|
||||
Thread.sleep(10)
|
||||
}
|
||||
assertEquals(0, refreshes.get())
|
||||
assertTrue(recreated.experimentalReleases.isEmpty())
|
||||
waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("older") }
|
||||
recreated.checkUpdates()
|
||||
waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("newer") }
|
||||
assertEquals(1, refreshes.get())
|
||||
}
|
||||
|
||||
private fun waitUntil(done: () -> Boolean) {
|
||||
val deadline = System.nanoTime() + 5_000_000_000L
|
||||
while (System.nanoTime() < deadline) {
|
||||
|
||||
@@ -33,27 +33,64 @@ class GameFilesTest {
|
||||
assertEquals("18446744073709551615", file.readText())
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
listOf(Uri.fromFile(file), Uri.parse(file.path)).forEach { uri ->
|
||||
assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri)))
|
||||
assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id)
|
||||
}
|
||||
val provider = LaunchFileProvider(file)
|
||||
provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend" })
|
||||
ShadowContentResolver.registerProviderInternal("frontend", provider)
|
||||
val uri = Uri.parse("content://frontend/document/opaque%3A42")
|
||||
assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri)))
|
||||
assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id)
|
||||
}
|
||||
|
||||
@Test fun readsIdsFromEveryFrontendFileFormat() {
|
||||
listOf("8400\n", "steam://rungameid/8400", "droiddeck://game/8400",
|
||||
"# Daijishou Player Template\n[steamappid] 8400\n", "# DST\n[steamappid] 8400\n",
|
||||
"[InternetShortcut]\r\nIconIndex=0\r\nURL=steam://rungameid/8400\r\nIconFile=C:\\steam.ico\r\n").forEach { value ->
|
||||
assertEquals(value, "8400", GameFiles.read(ByteArrayInputStream(value.toByteArray())))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun rejectsCommandsMalformedIdsLargeFilesAndUnsupportedIntents() {
|
||||
listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400",
|
||||
"8400\n8401", "droiddeck://game/8400", "droiddeck://game/8400?command=quit", "x".repeat(129)).forEach { value ->
|
||||
listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400?x=1", "steam://run/8400",
|
||||
"8400\n8401", "droiddeck://game/8400?command=quit", "x".repeat(4097),
|
||||
"[InternetShortcut]\nURL=https://example.com/8400", "[InternetShortcut]\nURL=8400",
|
||||
"# Daijishou Player Template\n[epicappid] 8400").forEach { value ->
|
||||
assertNull(value, GameFiles.read(ByteArrayInputStream(value.toByteArray())))
|
||||
}
|
||||
assertEquals("8400", GameFiles.read(ByteArrayInputStream("8400\n".toByteArray())))
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_SEND, Uri.parse("droiddeck://game/8400"))))
|
||||
assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/8400.steam"))))
|
||||
assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("file://remote/game.steam"))))
|
||||
assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(tmp.root, "missing.steam")))))
|
||||
assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400"))))
|
||||
assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400")))?.id)
|
||||
assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("8400")))?.id)
|
||||
assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("steam://rungameid/8400")))?.id)
|
||||
}
|
||||
|
||||
@Test fun storeFilesCarryTheirSourceAndTitle() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val epic = File(tmp.root, "Hades II.epic").apply { writeText("17") }
|
||||
val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(epic)))!!
|
||||
assertEquals("epic", request.source)
|
||||
assertEquals("Hades II", request.title)
|
||||
val daijishou = File(tmp.root, "Portal.steamappid").apply { writeText("# Daijishou Player Template\n[steamappid] 400\n") }
|
||||
val steam = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(daijishou)))!!
|
||||
assertEquals(Library.SOURCE_STEAM, steam.source)
|
||||
assertEquals("400", steam.id)
|
||||
}
|
||||
|
||||
@Test fun programFilesArriveAsPathsNotContents() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val exe = File(tmp.newFolder("Game"), "Game.exe").apply { writeBytes(byteArrayOf(0x4d, 0x5a)) }
|
||||
val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(exe)))!!
|
||||
assertEquals(exe.canonicalFile, request.program)
|
||||
assertNull(request.id)
|
||||
val provider = LaunchFileProvider(exe)
|
||||
provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend.files" })
|
||||
ShadowContentResolver.registerProviderInternal("frontend.files", provider)
|
||||
val shared = Uri.parse("content://frontend.files/root" + exe.canonicalPath)
|
||||
assertEquals(exe.canonicalFile, GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, shared))?.program)
|
||||
assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(exe.parentFile, "Missing.exe")))))
|
||||
}
|
||||
|
||||
@Test fun exportsGameIconBeforeCapsuleAndPreservesCustomArtwork() {
|
||||
@@ -185,13 +222,32 @@ class GameFilesTest {
|
||||
val file = GameFiles.export(app, folder, game("620", "Portal 2"))
|
||||
assertEquals("Portal 2.steam", file.name)
|
||||
assertEquals("620", file.readText())
|
||||
assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file))))
|
||||
assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))?.id)
|
||||
val added = Library.SteamGame(1, "Added Game", null, Library.ADDED, -1L)
|
||||
val addedFile = GameFiles.export(app, folder, added)
|
||||
assertEquals("Added Game.steam", addedFile.name)
|
||||
assertEquals("18446744073709551615", addedFile.readText())
|
||||
}
|
||||
|
||||
@Test fun storeGamesExportUnderTheirStoreExtensionAndLaunchBack() {
|
||||
val folder = tmp.newFolder()
|
||||
val forza = Library.SteamGame(1, "Forza Horizon 5", null, Library.ADDED, -7L, source = "xbox", storeId = "9NKX70BBCDRN")
|
||||
val steam = File(folder, "Forza Horizon 5.steam").apply { writeText(forza.gameIdString) }
|
||||
File(folder, ".droiddeck-sync.json").writeText(
|
||||
"""{"format":"droiddeck-game-files-v1","games":{"Forza Horizon 5.steam":"${forza.gameIdString}"}}""")
|
||||
GameFiles.sync(app, folder, listOf(forza))
|
||||
val file = File(folder, "Forza Horizon 5.xbox")
|
||||
assertEquals(forza.gameIdString, file.readText())
|
||||
assertFalse(steam.exists())
|
||||
val request = GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))!!
|
||||
assertEquals("xbox", request.source)
|
||||
assertSame(forza, request.find(listOf(game("620", "Portal 2"), forza)))
|
||||
listOf("ubisoft", "ea", "rockstar", "battlenet", "itch", "gamejolt", "epic", "gog", "amazon").forEach { store ->
|
||||
val game = Library.SteamGame(1, "Game", null, Library.ADDED, -8L, source = store)
|
||||
assertEquals("Game.$store", GameFiles.filename(game))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun steamSyncDisambiguatesTitlesAndPreservesEditedAndForeignFiles() {
|
||||
val folder = tmp.newFolder()
|
||||
val first = game("620", "A/B")
|
||||
|
||||
@@ -14,29 +14,41 @@ class GameLaunchIntentTest {
|
||||
@Test fun acceptsNativeAndExplicitlyRetargetedGameNativeProfiles() {
|
||||
listOf(GameLaunchIntent.ACTION, "app.gamenative.LAUNCH_GAME").forEach { action ->
|
||||
val request = Intent(action).putExtra("app_id", 620).putExtra("game_source", "STEAM")
|
||||
assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request))
|
||||
assertEquals("8400", GameLaunchIntent.readId(Intent(action).putExtra("app_id", "8400")))
|
||||
assertEquals("620", GameLaunchIntent.readId(request.putExtra("game_source", "steam")))
|
||||
assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request)?.id)
|
||||
assertEquals("8400", GameLaunchIntent.readExtras(Intent(action).putExtra("app_id", "8400"))?.id)
|
||||
assertEquals("620", GameLaunchIntent.readExtras(request.putExtra("game_source", "steam"))?.id)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun stringIdsPreserveUnsignedShortcutIds() {
|
||||
@Test fun longAndStringIdsPreserveUnsignedShortcutIds() {
|
||||
listOf("2147483648", "18446744073709551615").forEach { id ->
|
||||
assertEquals(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id)))
|
||||
assertEquals(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))?.id)
|
||||
}
|
||||
assertEquals("620", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L))?.id)
|
||||
assertEquals("18446744073709551615", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1L))?.id)
|
||||
}
|
||||
|
||||
@Test fun storeSourcesComeThroughForLibraryMatching() {
|
||||
mapOf("EPIC" to "epic", "gog" to "gog", "AMAZON" to "amazon", "XBOX" to "xbox", "UBISOFT" to "ubisoft",
|
||||
"EA" to "ea", "ROCKSTAR" to "rockstar", "BATTLENET" to "battlenet", "ITCH" to "itch", "GAMEJOLT" to "gamejolt",
|
||||
"CUSTOM_GAME" to Library.ADDED).forEach { (name, source) ->
|
||||
val request = GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 1207658924).putExtra("game_source", name))
|
||||
assertEquals(name, source, request?.source)
|
||||
assertEquals("1207658924", request?.id)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun rejectsUnsupportedSourcesTypesAndIdsWithoutFallingBackToData() {
|
||||
listOf("", "0", "01", "+1", "-1", "18446744073709551616", "620\n", "steam://rungameid/620").forEach { id ->
|
||||
assertNull(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id)))
|
||||
assertNull(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id)))
|
||||
}
|
||||
listOf("EPIC", "GOG", "CUSTOM_GAME", "", "STEAM ").forEach { source ->
|
||||
assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source)))
|
||||
listOf("STADIA", "", "STEAM ", "added").forEach { source ->
|
||||
assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source)))
|
||||
}
|
||||
assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L)))
|
||||
assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1)))
|
||||
assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1)))
|
||||
assertNull(GameLaunchIntent.readId(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620)))
|
||||
assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 0L)))
|
||||
assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1)))
|
||||
assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1)))
|
||||
assertNull(GameLaunchIntent.readExtras(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620)))
|
||||
assertNull(GameLaunchIntent.read(RuntimeEnvironment.getApplication(), Intent(GameLaunchIntent.ACTION,
|
||||
android.net.Uri.parse("droiddeck://game/620"))))
|
||||
}
|
||||
@@ -44,7 +56,7 @@ class GameLaunchIntentTest {
|
||||
@Test fun deepLinksStillAcceptUnsignedShortcutIds() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
assertEquals("18446744073709551615", GameLaunchIntent.read(context,
|
||||
Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615"))))
|
||||
Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615")))?.id)
|
||||
assertFalse(GameLaunchIntent.accepts(Intent.ACTION_SEND))
|
||||
assertTrue(GameLaunchIntent.accepts(GameLaunchIntent.ACTION))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class GameRequestTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun game(id: Long, name: String, source: String = Library.SOURCE_STEAM, storeId: String? = null, files: File? = null,
|
||||
library: String = "internal", appId: Int = id.toInt()) =
|
||||
Library.SteamGame(appId, name, null, library, id, gameFiles = files, source = source, storeId = storeId)
|
||||
|
||||
@Test fun steamIdsMatchTheGameIdOrAnAddedGamesSteamAppId() {
|
||||
val portal = game(400, "Portal")
|
||||
val added = game(-1L, "Celeste", library = Library.ADDED, source = Library.ADDED, appId = 504230)
|
||||
val games = listOf(portal, added)
|
||||
assertSame(portal, GameRequest("400").find(games))
|
||||
assertSame(added, GameRequest("18446744073709551615").find(games))
|
||||
assertSame(added, GameRequest("504230").find(games))
|
||||
assertNull(GameRequest("401").find(games))
|
||||
}
|
||||
|
||||
@Test fun titleMatchingWaitsForTheFullScan() {
|
||||
val cached = game(-2L, "Example", source = "gog", storeId = "111")
|
||||
assertNull(GameRequest("222", "gog", "Example").find(listOf(cached), byTitle = false))
|
||||
assertSame(cached, GameRequest("222", "gog", "Example").find(listOf(cached)))
|
||||
assertSame(cached, GameRequest("111", "gog", "Other").find(listOf(cached), byTitle = false))
|
||||
}
|
||||
|
||||
@Test fun gogMatchesItsProductIdThenTitle() {
|
||||
val witcher = game(-2L, "The Witcher 3: Wild Hunt", source = "gog", storeId = "1207664663")
|
||||
val games = listOf(game(292030, "The Witcher 3: Wild Hunt"), witcher)
|
||||
assertSame(witcher, GameRequest("1207664663", "gog").find(games))
|
||||
assertSame(witcher, GameRequest("5", "gog", "The Witcher 3 Wild Hunt").find(games))
|
||||
}
|
||||
|
||||
@Test fun storesWithAppLocalIdsMatchByTitleWithinTheirStore() {
|
||||
val hades = game(-3L, "Hades II", source = "epic", storeId = "Ixion")
|
||||
val custom = game(-4L, "Cave Story+", library = Library.ADDED, source = Library.ADDED)
|
||||
val games = listOf(game(1145350, "Hades II"), hades, custom)
|
||||
assertSame(hades, GameRequest("17", "epic", "hades ii").find(games))
|
||||
assertSame(custom, GameRequest("9", Library.ADDED, "Cave Story").find(games))
|
||||
assertNull(GameRequest("17", "epic").find(games))
|
||||
assertNull(GameRequest("17", "amazon", "Hades II").find(games))
|
||||
}
|
||||
|
||||
@Test fun programsStartTheDeepestGameThatOwnsThem() {
|
||||
val root = tmp.newFolder("Games")
|
||||
val suite = File(root, "Suite").apply { mkdirs() }
|
||||
val inner = File(suite, "Episode 2").apply { mkdirs() }
|
||||
val outer = game(-5L, "Suite", files = suite)
|
||||
val episode = game(-6L, "Episode 2", files = inner)
|
||||
val games = listOf(outer, episode)
|
||||
assertSame(episode, GameRequest(program = File(inner, "bin/game.exe")).find(games))
|
||||
assertSame(outer, GameRequest(program = File(suite, "launcher.exe")).find(games))
|
||||
assertNull(GameRequest(program = File(root, "Other/other.exe")).find(games))
|
||||
assertNull(GameRequest(program = File(root, "Suite2/game.exe")).find(games))
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.gpu
|
||||
import android.content.Intent
|
||||
import android.os.BatteryManager
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
@@ -40,4 +42,68 @@ class ClockLogComponentTest {
|
||||
clocks = ClockLogComponent(log).also { it.attach(context); it.stop(); it.start() }
|
||||
assertTrue(log.readText(), log.length() == 0L)
|
||||
}
|
||||
@Test fun gpuStepsAndCeilingAreParsedAndPrinted() {
|
||||
val table = tmp.newFile("gpu_available_frequencies").apply { writeText("443000000 350000000 285000000 160000000\n") }
|
||||
val ceiling = tmp.newFile("max_gpuclk").apply { writeText("285000000\n") }
|
||||
val floor = tmp.newFile("min_clock_mhz").apply { writeText("160\n") }
|
||||
val clock = tmp.newFile("gpu_clock").apply { writeText("230\n") }
|
||||
val steps = GpuLimits.first(listOf(tmp.root.path + "/missing", table.path))!!
|
||||
assertEquals(listOf(160L, 285L, 350L, 443L), steps.mhz)
|
||||
assertEquals(
|
||||
listOf(
|
||||
"gpu steps: 160 285 350 443 MHz from ${table.path}",
|
||||
"gpu ceiling from: ${ceiling.path}",
|
||||
"gpu floor: 160 MHz from ${floor.path}",
|
||||
),
|
||||
ClockLogComponent.limitLines(steps, ceiling.path, GpuLimits.first(listOf(floor.path))),
|
||||
)
|
||||
assertEquals(" | gpu 230/285(of 443) MHz", ClockLogComponent.gpuField(clock.path, ceiling.path, steps.mhz.last()))
|
||||
ceiling.writeText("443000000\n")
|
||||
assertEquals(" | gpu 230/443 MHz", ClockLogComponent.gpuField(clock.path, ceiling.path, steps.mhz.last()))
|
||||
}
|
||||
|
||||
@Test fun aZeroCeilingIsNotALimit() {
|
||||
val clock = tmp.newFile("gpu_clock").apply { writeText("0\n") }
|
||||
val zero = tmp.newFile("max_gpuclk").apply { writeText("0\n") }
|
||||
assertEquals(" | gpu 0 MHz", ClockLogComponent.gpuField(clock.path, zero.path, 443))
|
||||
assertEquals(listOf("gpu limit ${zero.path}: refused"), ClockLogComponent.probeLines("gpu limit", listOf(zero.path), ClockLogComponent::limit))
|
||||
assertEquals(listOf("gpu source ${clock.path}: readable"), ClockLogComponent.probeLines("gpu source", listOf(clock.path)))
|
||||
assertNull(ClockLogComponent.ceilingSource(listOf(zero.path)))
|
||||
zero.writeText("285000000\n")
|
||||
assertEquals(zero.path, ClockLogComponent.ceilingSource(listOf(zero.path)))
|
||||
assertEquals(" | gpu 0/285(of 443) MHz", ClockLogComponent.gpuField(clock.path, zero.path, 443))
|
||||
}
|
||||
|
||||
@Test fun aStepTableWithALeadingZeroIsReadable() {
|
||||
val steps = tmp.newFile("freq_table_mhz").apply { writeText("0 160000000 285000000\n") }
|
||||
assertEquals(listOf(160L, 285L), GpuLimits.first(listOf(steps.path))?.mhz)
|
||||
assertEquals(listOf("gpu limit ${steps.path}: readable"), ClockLogComponent.probeLines("gpu limit", listOf(steps.path), ClockLogComponent::firstStep))
|
||||
}
|
||||
|
||||
@Test fun unreadableOrMissingLimitsLeaveTheSampleUnchanged() {
|
||||
val clock = tmp.newFile("clock_mhz").apply { writeText("230\n") }
|
||||
val refused = tmp.newFolder("max_clock_mhz")
|
||||
val missing = tmp.root.path + "/gpu_max_clock"
|
||||
assertEquals(" | gpu 230 MHz", ClockLogComponent.gpuField(clock.path, null, null))
|
||||
assertEquals(" | gpu 230 MHz", ClockLogComponent.gpuField(clock.path, missing, 443))
|
||||
assertEquals(" | gpu 230 MHz", ClockLogComponent.gpuField(clock.path, refused.path, 443))
|
||||
assertEquals("", ClockLogComponent.gpuField(null, null, null))
|
||||
assertNull(GpuLimits.first(listOf(missing, refused.path)))
|
||||
assertEquals(listOf("gpu limit ${refused.path}: refused"), ClockLogComponent.probeLines("gpu limit", listOf(missing, refused.path)))
|
||||
assertEquals(
|
||||
listOf("gpu steps: nothing readable", "gpu ceiling from: nothing readable", "gpu floor: nothing readable"),
|
||||
ClockLogComponent.limitLines(null, null, null),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aCeilingChangeMidSessionShowsInTheNextSample() {
|
||||
val clock = tmp.newFile("cur_freq").apply { writeText("443000000\n") }
|
||||
val ceiling = tmp.newFile("max_freq").apply { writeText("443000000\n") }
|
||||
val first = ClockLogComponent.gpuField(clock.path, ceiling.path, 443)
|
||||
ceiling.writeText("285000000\n")
|
||||
clock.writeText("285000000\n")
|
||||
val second = ClockLogComponent.gpuField(clock.path, ceiling.path, 443)
|
||||
assertEquals(" | gpu 443/443 MHz", first)
|
||||
assertEquals(" | gpu 285/285(of 443) MHz", second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.file.Files
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
|
||||
import android.app.Activity
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Before
|
||||
import org.robolectric.Robolectric
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ExperimentalProtonsTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
private lateinit var activity: Activity
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileLabelsDropTheWholeArchiveSuffix() {
|
||||
assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.tar.xz"))
|
||||
assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.tar"))
|
||||
assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.7z"))
|
||||
assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.tgz"))
|
||||
assertEquals("Experimental-Build", ExperimentalProtons.dirName("Build", ExperimentalProtons.fileLabel("Build.tar.gz")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun installedReleasesLeaveTheAvailableRows() {
|
||||
val rows = listOf("r34", "r35").map { ExperimentalProtons.Release(it, "$it.tar.xz", "https://example.invalid/$it", null, 1L) }
|
||||
val installed = listOf(
|
||||
ExperimentalProtons.Installed("Experimental-r34", "r34", "release", "r34"),
|
||||
ExperimentalProtons.Installed("Experimental-file", "file", "file"),
|
||||
)
|
||||
assertEquals(listOf("r35"), ExperimentalProtons.available(rows, installed).map { it.tag })
|
||||
assertEquals(listOf("r34", "r35"), ExperimentalProtons.available(rows, emptyList()).map { it.tag })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun releaseRowsOnlyUsePublishedPrereleaseTarAssets() {
|
||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
val releases = JSONArray("""
|
||||
[{"tag_name":"stable","prerelease":false,"published_at":"2026-11-10T00:00:00Z","assets":[{"name":"stable-aarch64.tar.gz","browser_download_url":"https://example/stable"}]},
|
||||
{"tag_name":"pre","prerelease":true,"published_at":"2026-11-12T00:00:00Z","assets":[{"name":"pre-aarch64.tar.xz","browser_download_url":"https://example/pre"}]},
|
||||
{"tag_name":"superseded","prerelease":true,"published_at":"2026-10-25T00:00:00Z","assets":[{"name":"superseded-aarch64.tar.gz","browser_download_url":"https://example/superseded"}]},
|
||||
{"tag_name":"sources","prerelease":true,"published_at":"2026-11-13T00:00:00Z","assets":[{"name":"wine-gecko-x86.tar.xz","browser_download_url":"https://example/sources"}]},
|
||||
{"tag_name":"draft","draft":true,"prerelease":true,"published_at":"2026-11-14T00:00:00Z","assets":[{"name":"draft-aarch64.tar.gz","browser_download_url":"https://example/draft"}]},
|
||||
{"tag_name":"no-tar","prerelease":true,"published_at":"2026-11-15T00:00:00Z","assets":[{"name":"no-tar.sha512sum","browser_download_url":"https://example/sum"}]}]
|
||||
""".trimIndent())
|
||||
assertEquals(listOf("pre"), ProtonExtras.assets(tool, releases, true).map { it.tag })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun markerRoundTripKeepsReleaseTag() {
|
||||
val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() }
|
||||
File(dir, ".droiddeck-experimental.json").writeText(JSONObject().put("label", "Experimental-pre").put("source", "pre").put("releaseTag", "pre").toString())
|
||||
assertEquals("pre", ExperimentalProtons.installed(activity).single().releaseTag)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingReleaseTagsAreAutoRemovedButFileBuildsAreNot() {
|
||||
val complete = ProtonExtras.ReleaseFetch(JSONArray().put(JSONObject().put("tag_name", "kept").put("prerelease", true)), true)
|
||||
val partial = ProtonExtras.ReleaseFetch(JSONArray().put(JSONObject().put("tag_name", "gone").put("prerelease", true)), false)
|
||||
val stable = ProtonExtras.ReleaseFetch(JSONArray().put(JSONObject().put("tag_name", "gone").put("prerelease", false)), false)
|
||||
assertTrue(ExperimentalProtons.shouldRemove("gone", complete) { true })
|
||||
assertFalse(ExperimentalProtons.shouldRemove("gone", complete) { false })
|
||||
assertFalse(ExperimentalProtons.shouldRemove("gone", partial) { true })
|
||||
assertTrue(ExperimentalProtons.shouldRemove("gone", stable) { false })
|
||||
assertFalse(ExperimentalProtons.shouldRemove(null, complete) { true })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun archiveTypeUsesMagicBytes() {
|
||||
val zip = temp.newFile("wrong-name.bin").apply { writeBytes(byteArrayOf(0x50, 0x4B, 0x03, 0x04)) }
|
||||
val seven = temp.newFile("seven.data").apply { writeBytes(byteArrayOf(0x37, 0x7A, 0xBC.toByte(), 0xAF.toByte(), 0x27, 0x1C)) }
|
||||
val tar = temp.newFile("tar.data").apply { RandomAccessFile(this, "rw").use { it.seek(257); it.write("ustar".toByteArray()) } }
|
||||
assertEquals(ExperimentalProtons.ArchiveType.ZIP, ExperimentalProtons.archiveType(zip))
|
||||
assertEquals(ExperimentalProtons.ArchiveType.SEVEN_Z, ExperimentalProtons.archiveType(seven))
|
||||
assertEquals(ExperimentalProtons.ArchiveType.TAR, ExperimentalProtons.archiveType(tar))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun namesNeverCollideWithReleasedBuilds() {
|
||||
val name = ExperimentalProtons.dirName("DroidDeck-Proton-11-12.8-aarch64", "pr34-build")
|
||||
assertEquals("Experimental-DroidDeck-Proton-11-12.8-aarch64-pr34-build", name)
|
||||
assertFalse(name.startsWith("DroidDeck-Proton"))
|
||||
assertEquals("Experimental-DroidDeck-Proton-11-12.8-aarch64",
|
||||
ExperimentalProtons.dirName("DroidDeck-Proton-11-12.8-aarch64", "DroidDeck-Proton-11-12.8-aarch64"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildTreeSkipsLinksOutOfTheArchive() {
|
||||
val outside = protonTree(temp.newFolder("installed"))
|
||||
val unpacked = temp.newFolder("unpacked")
|
||||
Files.createSymbolicLink(File(unpacked, "a-link").toPath(), outside.toPath())
|
||||
assertNull(ExperimentalProtons.buildTree(unpacked))
|
||||
val real = protonTree(File(unpacked, "b-build"))
|
||||
assertEquals(real.canonicalFile, ExperimentalProtons.buildTree(unpacked)?.canonicalFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun buildTreeNeedsWhatTheCatalogNeeds() {
|
||||
val unpacked = temp.newFolder("unpacked")
|
||||
val tree = File(unpacked, "build").apply { mkdirs(); File(this, "toolmanifest.vdf").writeText("x") }
|
||||
assertNull(ExperimentalProtons.buildTree(unpacked))
|
||||
File(tree, "proton").writeText("x")
|
||||
assertNull(ExperimentalProtons.buildTree(unpacked))
|
||||
File(tree, "files/lib/wine").mkdirs()
|
||||
assertEquals(tree.canonicalFile, ExperimentalProtons.buildTree(unpacked)?.canonicalFile)
|
||||
}
|
||||
|
||||
private fun protonTree(dir: File): File = dir.apply {
|
||||
File(this, "files/lib/wine").mkdirs()
|
||||
File(this, "toolmanifest.vdf").writeText("x")
|
||||
File(this, "proton").writeText("x")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ownFileReplacesALinkWithoutTouchingItsTarget() {
|
||||
val victim = temp.newFile("compatibilitytool.vdf").apply { writeText("released") }
|
||||
val tree = temp.newFolder("tree")
|
||||
Files.createSymbolicLink(File(tree, "compatibilitytool.vdf").toPath(), victim.toPath())
|
||||
ExperimentalProtons.ownFile(tree, "compatibilitytool.vdf").writeText("experimental")
|
||||
assertEquals("released", victim.readText())
|
||||
assertFalse(Files.isSymbolicLink(File(tree, "compatibilitytool.vdf").toPath()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deleteTreeDoesNotFollowLinks() {
|
||||
val kept = temp.newFolder("kept").apply { File(this, "file").writeText("x") }
|
||||
val build = temp.newFolder("build")
|
||||
Files.createSymbolicLink(File(build, "lib").toPath(), kept.toPath())
|
||||
assertTrue(ExperimentalProtons.deleteTree(build))
|
||||
assertFalse(build.exists())
|
||||
assertTrue(File(kept, "file").isFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directZipKeepsExecutableModeAndInTreeLinks() {
|
||||
val archive = temp.newFile("tree.zip")
|
||||
ZipArchiveOutputStream(archive).use { zip ->
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/proton").apply { unixMode = 0x81ED })
|
||||
zip.write("binary".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/link").apply { unixMode = 0xA1FF })
|
||||
zip.write("proton".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/files/lib/up").apply { unixMode = 0xA1FF })
|
||||
zip.write("../../proton".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
}
|
||||
val unpacked = temp.newFolder("direct")
|
||||
ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.ZIP)
|
||||
assertTrue(File(unpacked, "build/proton").canExecute())
|
||||
assertTrue(Files.isSymbolicLink(File(unpacked, "build/link").toPath()))
|
||||
assertEquals("proton", Files.readSymbolicLink(File(unpacked, "build/link").toPath()).toString())
|
||||
assertEquals("../../proton", Files.readSymbolicLink(File(unpacked, "build/files/lib/up").toPath()).toString())
|
||||
assertEquals("binary", File(unpacked, "build/files/lib/up").readText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directArchivesFillReadOnlyDirectoriesBeforeLockingThem() {
|
||||
val archive = temp.newFile("locked.zip")
|
||||
ZipArchiveOutputStream(archive).use { zip ->
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/files/").apply { unixMode = 0x416D })
|
||||
zip.closeArchiveEntry()
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/files/data").apply { unixMode = 0x81A4 })
|
||||
zip.write("data".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
}
|
||||
val unpacked = temp.newFolder("locked")
|
||||
ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.ZIP)
|
||||
val directory = File(unpacked, "build/files")
|
||||
assertEquals("data", File(directory, "data").readText())
|
||||
assertFalse(directory.canWrite())
|
||||
directory.setWritable(true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directSevenZipKeepsExecutableModeAndInTreeLinks() {
|
||||
val archive = temp.newFile("tree.7z")
|
||||
SevenZOutputFile(archive).use { seven ->
|
||||
fun add(name: String, mode: Int, text: String) {
|
||||
val entry = SevenZArchiveEntry().apply {
|
||||
this.name = name
|
||||
hasWindowsAttributes = true
|
||||
windowsAttributes = (mode shl 16) or 0x8000
|
||||
}
|
||||
seven.putArchiveEntry(entry)
|
||||
seven.write(text.toByteArray())
|
||||
seven.closeArchiveEntry()
|
||||
}
|
||||
add("build/proton", 0x81ED, "binary")
|
||||
add("build/files/lib/up", 0xA1FF, "../../proton")
|
||||
add("build/plain", 0x81A4, "data")
|
||||
}
|
||||
val unpacked = temp.newFolder("seven")
|
||||
ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.SEVEN_Z)
|
||||
assertTrue(File(unpacked, "build/proton").canExecute())
|
||||
assertFalse(File(unpacked, "build/plain").canExecute())
|
||||
assertEquals("../../proton", Files.readSymbolicLink(File(unpacked, "build/files/lib/up").toPath()).toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directArchivesAllowCurrentDirectoryBeforeAClimb() {
|
||||
val archive = temp.newFile("dot.zip")
|
||||
ZipArchiveOutputStream(archive).use { zip ->
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/lib/wine").apply { unixMode = 0x81ED })
|
||||
zip.write("binary".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/bin/wine").apply { unixMode = 0xA1FF })
|
||||
zip.write("./../lib/wine".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
}
|
||||
val unpacked = temp.newFolder("dot")
|
||||
ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.ZIP)
|
||||
assertEquals("./../lib/wine", Files.readSymbolicLink(File(unpacked, "build/bin/wine").toPath()).toString())
|
||||
assertEquals("binary", File(unpacked, "build/bin/wine").readText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directArchivesRejectLinksThatClimbAfterACurrentDirectoryAndAName() {
|
||||
for (link in listOf("./top/../outside", "./../a/./../..", "top/./../outside")) {
|
||||
val archive = temp.newFile()
|
||||
ZipArchiveOutputStream(archive).use { zip ->
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/a/b/out").apply { unixMode = 0xA1FF })
|
||||
zip.write(link.toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
}
|
||||
val result = runCatching { ExperimentalProtons.extractDirect(archive, temp.newFolder(), ExperimentalProtons.ArchiveType.ZIP) }
|
||||
assertTrue(link, result.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconcileKeepsBuildsWhenASessionStartsDuringTheLookup() {
|
||||
val tools = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d")
|
||||
val dirs = listOf("Experimental-gone-a", "Experimental-gone-b").map { name ->
|
||||
File(tools, name).apply {
|
||||
mkdirs()
|
||||
File(this, ".droiddeck-experimental.json").writeText(JSONObject().put("label", name).put("source", name).put("releaseTag", name).toString())
|
||||
}
|
||||
}
|
||||
val complete = ProtonExtras.ReleaseFetch(JSONArray(), true)
|
||||
var lookups = 0
|
||||
try {
|
||||
ExperimentalProtons.reconcile(activity, complete) {
|
||||
lookups++
|
||||
SessionState.running = true
|
||||
true
|
||||
}
|
||||
} finally {
|
||||
SessionState.running = false
|
||||
}
|
||||
assertEquals(1, lookups)
|
||||
assertTrue(dirs.all { it.isDirectory })
|
||||
ExperimentalProtons.reconcile(activity, complete) { true }
|
||||
assertTrue(dirs.none { it.exists() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removeWaitsForAStartingSessionAndThenKeepsTheBuild() {
|
||||
val tools = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d")
|
||||
val dir = File(tools, "Experimental-starting").apply {
|
||||
mkdirs()
|
||||
File(this, ".droiddeck-experimental.json").writeText(JSONObject().put("label", name).put("source", name).toString())
|
||||
File(this, "proton").writeText("build")
|
||||
}
|
||||
var removed: Boolean? = null
|
||||
val removal = Thread { removed = ExperimentalProtons.remove(activity, dir.name) }
|
||||
try {
|
||||
synchronized(SessionState.startLock) {
|
||||
removal.start()
|
||||
val deadline = System.nanoTime() + 10_000_000_000L
|
||||
while (removal.state != Thread.State.BLOCKED && System.nanoTime() < deadline) Thread.sleep(5)
|
||||
assertEquals(Thread.State.BLOCKED, removal.state)
|
||||
assertTrue(File(dir, "proton").isFile)
|
||||
SessionState.running = true
|
||||
}
|
||||
removal.join(10_000)
|
||||
assertEquals(false, removed)
|
||||
assertTrue(File(dir, "proton").isFile)
|
||||
} finally {
|
||||
SessionState.running = false
|
||||
removal.join(10_000)
|
||||
}
|
||||
assertTrue(ExperimentalProtons.remove(activity, dir.name))
|
||||
assertTrue(!dir.exists())
|
||||
assertTrue(File(tools, ".droiddeck-experimental-gone").list().isNullOrEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directArchivesRejectLinksThatClimbAfterAName() {
|
||||
val archive = temp.newFile("climb.zip")
|
||||
ZipArchiveOutputStream(archive).use { zip ->
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/a/b/top").apply { unixMode = 0xA1FF })
|
||||
zip.write("../../..".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/a/b/out").apply { unixMode = 0xA1FF })
|
||||
zip.write("top/../outside".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
}
|
||||
val result = runCatching { ExperimentalProtons.extractDirect(archive, temp.newFolder("climb-out"), ExperimentalProtons.ArchiveType.ZIP) }
|
||||
assertTrue(result.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directZipRejectsEscapingLinksAndEntries() {
|
||||
val linkArchive = temp.newFile("link.zip")
|
||||
ZipArchiveOutputStream(linkArchive).use { zip ->
|
||||
zip.putArchiveEntry(ZipArchiveEntry("build/link").apply { unixMode = 0xA1FF })
|
||||
zip.write("../../outside".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
}
|
||||
val entryArchive = temp.newFile("entry.zip")
|
||||
ZipArchiveOutputStream(entryArchive).use { zip ->
|
||||
zip.putArchiveEntry(ZipArchiveEntry("../outside"))
|
||||
zip.write("x".toByteArray())
|
||||
zip.closeArchiveEntry()
|
||||
}
|
||||
val linkResult = runCatching { ExperimentalProtons.extractDirect(linkArchive, temp.newFolder("link-out"), ExperimentalProtons.ArchiveType.ZIP) }
|
||||
val entryResult = runCatching { ExperimentalProtons.extractDirect(entryArchive, temp.newFolder("entry-out"), ExperimentalProtons.ArchiveType.ZIP) }
|
||||
assertTrue(linkResult.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException)
|
||||
assertTrue(entryResult.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staleDownloadCleanupOnlyDeletesItsOwnUnlistedFiles() {
|
||||
val downloads = File(activity.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val stale = File(downloads, "droiddeck-gone-archive.tar.xz").apply { writeText("partial") }
|
||||
val kept = File(downloads, "droiddeck-kept-archive.tar.xz").apply { writeText("partial") }
|
||||
val other = File(downloads, "other-archive.tar.xz").apply { writeText("partial") }
|
||||
ExperimentalProtons.removeStaleDownloads(activity, setOf("kept"))
|
||||
assertFalse(stale.exists())
|
||||
assertTrue(kept.exists())
|
||||
assertTrue(other.exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun checksumFileWithoutADigestIsRejected() {
|
||||
assertNull(ExperimentalProtons.checksumIn("not a checksum\n"))
|
||||
val digest = "a".repeat(128)
|
||||
assertEquals(digest, ExperimentalProtons.checksumIn("$digest DroidDeck-Proton.tar.gz\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun checksumLookupDoesNotSelectTheTarball() {
|
||||
assertNull(ExperimentalProtons.checksumEntry(listOf("Proton-sha512.tar.gz"), "Proton-sha512.tar.gz"))
|
||||
assertEquals("Proton-sha512.tar.gz.sha512sum", ExperimentalProtons.checksumEntry(
|
||||
listOf("Proton-sha512.tar.gz", "Proton-sha512.tar.gz.sha512sum"), "Proton-sha512.tar.gz"))
|
||||
assertNull(ExperimentalProtons.checksumEntry(listOf("Proton.tar.gz"), "Proton.tar.gz"))
|
||||
assertEquals("Proton.tar.gz.sha512sum", ExperimentalProtons.checksumEntry(
|
||||
listOf("Proton-debug.tar.gz.sha512sum", "Proton.tar.gz.sha512sum"), "Proton.tar.gz"))
|
||||
assertEquals("Proton.sha512sum", ExperimentalProtons.checksumEntry(listOf("Proton.sha512sum"), "Proton.tar.gz"))
|
||||
assertNull(ExperimentalProtons.checksumEntry(listOf("Proton-debug.tar.gz.sha512sum"), "Proton.tar.gz"))
|
||||
}
|
||||
|
||||
private fun build(dir: File, marker: String): File = dir.apply {
|
||||
mkdirs()
|
||||
File(this, "marker").writeText(marker)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedPlacementRestoresTheExistingBuild() {
|
||||
val tools = temp.newFolder("tools")
|
||||
build(File(tools, "Experimental-A"), "old")
|
||||
assertFalse(ExperimentalProtons.placeTree(File(tools, "missing"), tools, "Experimental-A") { true })
|
||||
assertEquals("old", File(tools, "Experimental-A/marker").readText())
|
||||
assertFalse(ExperimentalProtons.placeTree(build(File(tools, "staged"), "new"), tools, "Experimental-A") { false })
|
||||
assertEquals("old", File(tools, "Experimental-A/marker").readText())
|
||||
assertTrue(tools.walkTopDown().none { it.isFile && it.readText() == "new" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplacedBuildIsForgottenWhileNeitherBuildIsInstalled() {
|
||||
val tools = temp.newFolder("tools")
|
||||
build(File(tools, "Experimental-A"), "old")
|
||||
val forgotten = ArrayList<String>()
|
||||
assertTrue(ExperimentalProtons.placeTree(build(File(tools, "staged"), "new"), tools, "Experimental-A") {
|
||||
assertFalse(File(tools, it).exists())
|
||||
forgotten.add(it)
|
||||
})
|
||||
assertEquals(listOf("Experimental-A"), forgotten)
|
||||
assertEquals("new", File(tools, "Experimental-A/marker").readText())
|
||||
assertTrue(ExperimentalProtons.placeTree(build(File(tools, "staged"), "first"), tools, "Experimental-B") { forgotten.add(it) })
|
||||
assertEquals(listOf("Experimental-A"), forgotten)
|
||||
assertEquals(listOf("Experimental-A", "Experimental-B"), tools.walkTopDown().filter { it.name == "marker" }.map { it.parentFile.name }.sorted().toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInterruptedReplacementIsFinishedWithItsOldStateForgotten() {
|
||||
val tools = temp.newFolder("tools")
|
||||
build(File(tools, "Experimental-A"), "old")
|
||||
build(File(tools, ".droiddeck-experimental-new/Experimental-A"), "new")
|
||||
build(File(tools, ".droiddeck-experimental-old/Experimental-B"), "old")
|
||||
build(File(tools, ".droiddeck-experimental-new/Experimental-B"), "new")
|
||||
build(File(tools, ".droiddeck-experimental-old/Experimental-C"), "old")
|
||||
build(File(tools, ".droiddeck-experimental-old/Experimental-D"), "old")
|
||||
build(File(tools, "Experimental-D"), "new")
|
||||
val forgotten = ArrayList<String>()
|
||||
ExperimentalProtons.restoreInterrupted(tools) { forgotten.add(it) }
|
||||
assertEquals(listOf("Experimental-A", "Experimental-B"), forgotten.sorted())
|
||||
assertEquals(listOf("new", "new", "old", "new"), listOf("A", "B", "C", "D").map { File(tools, "Experimental-$it/marker").readText() })
|
||||
assertTrue(File(tools, ".droiddeck-experimental-old").listFiles().isNullOrEmpty())
|
||||
assertTrue(File(tools, ".droiddeck-experimental-new").listFiles().isNullOrEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInterruptedReplacementKeepsTheOldBuildWhenItsStateCannotBeForgotten() {
|
||||
val tools = temp.newFolder("tools")
|
||||
build(File(tools, ".droiddeck-experimental-old/Experimental-A"), "old")
|
||||
build(File(tools, ".droiddeck-experimental-new/Experimental-A"), "new")
|
||||
ExperimentalProtons.restoreInterrupted(tools) { false }
|
||||
assertEquals("old", File(tools, "Experimental-A/marker").readText())
|
||||
assertTrue(File(tools, ".droiddeck-experimental-new").listFiles().isNullOrEmpty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class GpuClockPinTest {
|
||||
private val context = RuntimeEnvironment.getApplication()
|
||||
|
||||
@After fun stop() { GpuClockPin.stop(context) }
|
||||
|
||||
@Test fun aToggleOutsideASessionSaysNothing() {
|
||||
SessionPrefs.setGpuClockPin(context, true)
|
||||
assertNull(GpuClockPin.sync(context))
|
||||
}
|
||||
|
||||
@Test fun aToggleMidSessionReportsTheHoldWithTheStartWording() {
|
||||
SessionPrefs.setGpuClockPin(context, false)
|
||||
val started = GpuClockPin.start(context)
|
||||
assertEquals("gpu clock: governed", started)
|
||||
SessionPrefs.setGpuClockPin(context, true)
|
||||
val held = GpuClockPin.sync(context)
|
||||
assertEquals("gpu clock: no /dev/kgsl-3d0, left governed", held)
|
||||
SessionPrefs.setGpuClockPin(context, false)
|
||||
assertEquals(started, GpuClockPin.sync(context))
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,12 @@ class PipPolicyTest {
|
||||
assertFalse(PipPolicy.eligible(true, false, SessionPhase.SUSPENDED, true, false))
|
||||
}
|
||||
|
||||
@Test fun goingHomeFloatsOnlyGamesDroidDeckLaunchedItself() {
|
||||
assertTrue(PipPolicy.autoEnter(enabled = true, launchedByAnotherApp = false))
|
||||
assertFalse(PipPolicy.autoEnter(enabled = true, launchedByAnotherApp = true))
|
||||
assertFalse(PipPolicy.autoEnter(enabled = false, launchedByAnotherApp = false))
|
||||
}
|
||||
|
||||
@Test fun aspectRatiosStayWithinAndroidLimitsWithoutChangingNormalContent() {
|
||||
assertEquals(1920 to 1080, PipPolicy.aspect(1920, 1080))
|
||||
assertEquals(239 to 100, PipPolicy.aspect(5760, 1080))
|
||||
|
||||
@@ -30,7 +30,7 @@ class ProtonExtrasTest {
|
||||
.apply { if (digest != null) put("digest", digest) }
|
||||
|
||||
private fun release(tag: String, vararg assets: JSONObject, prerelease: Boolean = false, draft: Boolean = false) = JSONObject()
|
||||
.put("tag_name", tag).put("prerelease", prerelease).put("draft", draft)
|
||||
.put("tag_name", tag).put("prerelease", prerelease).put("draft", draft).put("published_at", "2026-11-12T00:00:00Z")
|
||||
.put("assets", JSONArray().apply { assets.forEach { put(it) } })
|
||||
|
||||
private fun droiddeckRelease(ver: String, prerelease: Boolean = false) = release(
|
||||
@@ -48,6 +48,34 @@ class ProtonExtrasTest {
|
||||
File(this, "proton").apply { writeText(""); setExecutable(true) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun experimentalRowsUseTheReleaseNameAndTagDetail() {
|
||||
val current = release("DroidDeck-Bionic-12.8-r34", asset("DroidDeck-Bionic-12.8-r34-aarch64.tar.xz"), prerelease = true)
|
||||
.put("name", "DroidDeck Bionic 12.8 r34")
|
||||
val selectedAsset = ProtonExtras.assetOf(tool("droiddeck"), current, experimental = true)!!
|
||||
val selected = ProtonExtras.assets(tool("droiddeck"), JSONArray().put(current), true).single()
|
||||
assertEquals("DroidDeck-Bionic-12.8-r34-aarch64.tar.xz", selectedAsset.name)
|
||||
assertEquals("DroidDeck Bionic 12.8 r34", selected.releaseName)
|
||||
assertEquals("DroidDeck-Bionic-12.8-r34", selected.tag)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun experimentalAssetsIgnoreChecksumSidecars() {
|
||||
val sidecarOnly = release("DroidDeck-Bionic-12.8-r36", asset("DroidDeck-Bionic-12.8-r36-aarch64.tar.xz.sha512sum"))
|
||||
assertEquals(null, ProtonExtras.assetOf(tool("droiddeck"), sidecarOnly, experimental = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun experimentalAssetsSkipOtherArchitectures() {
|
||||
val foreign = release("DroidDeck-Bionic-12.8-r37", asset("DroidDeck-Bionic-12.8-r37-x86_64.tar.xz"), asset("DroidDeck-Bionic-12.8-r37-amd64.tar.gz"), prerelease = true)
|
||||
val mixed = release("DroidDeck-Bionic-12.8-r38", asset("DroidDeck-Bionic-12.8-r38-x86_64.tar.xz"), asset("DroidDeck-Bionic-12.8-r38.tar.xz"), prerelease = true)
|
||||
val named = release("DroidDeck-Bionic-12.8-r39", asset("DroidDeck-Bionic-12.8-r39-aarch64.tar.xz"), asset("DroidDeck-Bionic-12.8-r39-x86_64.tar.xz"), prerelease = true)
|
||||
assertEquals(null, ProtonExtras.assetOf(tool("droiddeck"), foreign, experimental = true))
|
||||
assertEquals("DroidDeck-Bionic-12.8-r38.tar.xz", ProtonExtras.assetOf(tool("droiddeck"), mixed, experimental = true)!!.name)
|
||||
assertEquals("DroidDeck-Bionic-12.8-r39-aarch64.tar.xz", ProtonExtras.assetOf(tool("droiddeck"), named, experimental = true)!!.name)
|
||||
assertTrue(ProtonExtras.assets(tool("droiddeck"), JSONArray().put(foreign), true).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theThreeSourcesInOrder() {
|
||||
assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id })
|
||||
@@ -72,6 +100,14 @@ class ProtonExtrasTest {
|
||||
assertNull(picked.sha256)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ownExperimentalReleaseUsesItsCurrentBionicTarballShape() {
|
||||
val current = release("DroidDeck-Bionic-12.8-r34", asset("DroidDeck-Bionic-12.8-r34-aarch64.tar.xz"), asset("DroidDeck-Bionic-12.8-r34-aarch64.sha512sum"), prerelease = true)
|
||||
val rows = ProtonExtras.assets(tool("droiddeck"), JSONArray().put(current), prerelease = true)
|
||||
assertEquals(listOf("DroidDeck-Bionic-12.8-r34"), rows.map { it.tag })
|
||||
assertTrue(ProtonExtras.assets(tool("droiddeck"), JSONArray().put(release("DroidDeck-Bionic-12.8-r35", asset("DroidDeck-Bionic-12.8-r35-aarch64.sha512sum"), prerelease = true)), true).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun githubsDigestIsKeptBesideTheSha512File() {
|
||||
val sum = "ab".repeat(32)
|
||||
@@ -208,8 +244,25 @@ class ProtonExtrasTest {
|
||||
assertFalse(state.getJSONObject("active").has("GE-Proton11-7"))
|
||||
assertFalse(state.getJSONObject("queued").has("GE-Proton11-7"))
|
||||
assertTrue(state.getJSONObject("active").has("GE-Proton11-8"))
|
||||
ComponentsManager.forgetProton(context, kept.name)
|
||||
assertTrue(ComponentsManager.forgetProton(context, kept.name))
|
||||
assertTrue(File(originals, "GE-Proton11-8/GE-Proton11-8/dxvk.wcp").isFile)
|
||||
val published = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
|
||||
published.appendText("*\tExperimental-Gone\t11\tdxvk\tfiles/lib/wine/dxvk/x86_64-windows/dxgi.dll\t-\t-\n")
|
||||
File(originals, "Experimental-Gone/11/dxvk.wcp").apply { parentFile?.mkdirs(); writeText("x") }
|
||||
assertTrue(ComponentsManager.forgetProton(context, "Experimental-Gone"))
|
||||
assertFalse(published.readLines().any { "Experimental-Gone" in it })
|
||||
assertFalse(File(originals, "Experimental-Gone").exists())
|
||||
|
||||
val store = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/store")
|
||||
File(originals, "Experimental-Stale/11/dxvk.wcp").apply { parentFile?.mkdirs(); writeText("x") }
|
||||
val stale = File(store, "original-Experimental-Stale-11-dxvk").apply { mkdirs(); File(this, ".complete").writeText("1\n") }
|
||||
val other = File(store, "original-Experimental-Stale-2-11-dxvk").apply { mkdirs(); File(this, ".complete").writeText("1\n") }
|
||||
File(originals, "Experimental-Stale/2-11/dxvk.wcp").apply { parentFile?.mkdirs(); writeText("x") }
|
||||
published.appendText("*\tExperimental-Stale-2\t11\tdxvk\tfiles/a.dll\t0\t/root/.local/share/droiddeck-components/store/${other.name}/files/a.dll\n")
|
||||
assertTrue(ComponentsManager.forgetProton(context, "Experimental-Stale"))
|
||||
assertFalse(stale.exists())
|
||||
assertTrue(File(other, ".complete").isFile)
|
||||
assertFalse(File(originals, "Experimental-Stale").exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -242,4 +295,76 @@ class ProtonExtrasTest {
|
||||
assertNull(ProtonExtras.missing(context, tool("droiddeck")))
|
||||
assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.update(context, tool("droiddeck")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun laterPagesAreReadOnlyUntilAStableBaselineIsFound() {
|
||||
val tool = tool("droiddeck")
|
||||
val pages = mapOf(
|
||||
1 to JSONArray().apply { repeat(15) { put(droiddeckRelease("11-12.${10 - it}", prerelease = true)) } },
|
||||
2 to JSONArray().put(droiddeckRelease("11-12.8")),
|
||||
3 to JSONArray().put(droiddeckRelease("11-12.7")),
|
||||
)
|
||||
val asked = mutableListOf<Int>()
|
||||
val all = ProtonExtras.releases(tool) { asked += it; pages[it] ?: JSONArray() }!!
|
||||
assertEquals(listOf(1, 2), asked)
|
||||
assertEquals("DroidDeck-Proton-11-12.8", ProtonExtras.pickAsset(tool, all)!!.tag)
|
||||
|
||||
asked.clear()
|
||||
ProtonExtras.releases(tool) { asked += it; pages.getValue(2) }
|
||||
assertEquals(listOf(1), asked)
|
||||
|
||||
asked.clear()
|
||||
assertEquals(0, ProtonExtras.releases(tool) { asked += it; JSONArray() }!!.length())
|
||||
assertEquals(listOf(1), asked)
|
||||
assertNull(ProtonExtras.releases(tool) { null })
|
||||
|
||||
asked.clear()
|
||||
assertNull(ProtonExtras.releases(tool) { page ->
|
||||
asked += page
|
||||
if (page == 1) JSONArray().apply { repeat(15) { put(droiddeckRelease("11-12.${10 - it}", prerelease = true)) } } else null
|
||||
})
|
||||
assertEquals(listOf(1, 2), asked)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOldTestButtonInstallRemainsAUsableInstalledBuild() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
|
||||
val installed = installTool(tools, "DroidDeck-Proton 11-12.9")
|
||||
val releases = File(context.filesDir, "proton-extras.json")
|
||||
releases.writeText(JSONObject().put(installed.name, "DroidDeck-Proton-11-12.9").toString())
|
||||
assertEquals(listOf(installed.name), ProtonExtras.installedAll(context, tool("droiddeck")))
|
||||
assertEquals(listOf("DroidDeck-Proton-11-12.9"), ProtonExtras.installedTags(context, tool("droiddeck")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun malformedReleaseEntriesAreSkipped() {
|
||||
val releases = JSONArray("[null, 5, {\"tag_name\": \"x\", \"assets\": [null]}]").put(droiddeckRelease("11-12.8"))
|
||||
assertEquals("DroidDeck-Proton-11-12.8", ProtonExtras.pickAsset(tool("droiddeck"), releases)!!.tag)
|
||||
assertNull(ProtonExtras.pickAsset(tool("droiddeck"), JSONArray("[null]")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedOrPartialReleaseFetchDoesNotPretendMissingBuildsAreGone() {
|
||||
val tool = tool("droiddeck")
|
||||
assertNull(ProtonExtras.releasesForRemoval(tool) { null })
|
||||
val asked = mutableListOf<Int>()
|
||||
val result = ProtonExtras.releasesForRemoval(tool) { page ->
|
||||
asked += page
|
||||
if (page == 1) JSONArray().apply { repeat(15) { put(droiddeckRelease("11-12.${10 - it}", prerelease = true)) } } else null
|
||||
}
|
||||
assertNull(result)
|
||||
assertEquals(listOf(1, 2), asked)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aShortReleasePageCompletesTheRemovalLookup() {
|
||||
val asked = mutableListOf<Int>()
|
||||
val result = ProtonExtras.releasesForRemoval(tool("droiddeck")) { page ->
|
||||
asked += page
|
||||
JSONArray().put(droiddeckRelease("11-12.8", prerelease = true))
|
||||
}
|
||||
assertTrue(result!!.complete)
|
||||
assertEquals(listOf(1), asked)
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,8 @@ class SessionSuspendControllerTest {
|
||||
val urgent = fixture.signals.filter { it.signal == URG }
|
||||
assertEquals(listOf(GAME), urgent.map { it.pid })
|
||||
assertTrue(fixture.signals.indexOfFirst { it.signal == URG } < fixture.signals.indexOfFirst { it.signal == STOP })
|
||||
assertEquals("1", fixture.control.readText())
|
||||
assertEquals(listOf<String?>("1"), fixture.held)
|
||||
assertEquals("0", fixture.control.readText())
|
||||
assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut)
|
||||
assertEquals(0, fixture.unacknowledged)
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
@@ -56,6 +57,22 @@ class SessionSuspendControllerTest {
|
||||
assertEquals(0, fixture.unacknowledged)
|
||||
}
|
||||
|
||||
@Test fun aTrimAcknowledgementIsNotTakenForAFinishedPageOut() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerStalls = true
|
||||
val ack = File(fixture.control.parentFile, ".dd-zram.ack.$GAME")
|
||||
var stoppedEarly = false
|
||||
fixture.afterSleep = {
|
||||
if (fixture.now == 3000L) fixture.handlerStalls = false
|
||||
if (fixture.handlerStalls && fixture.signals.any { it.signal == URG }) ack.writeText("4096")
|
||||
if (fixture.handlerStalls && fixture.signals.any { it.signal == STOP }) stoppedEarly = true
|
||||
}
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
assertFalse(stoppedEarly)
|
||||
assertEquals(0, fixture.unacknowledged)
|
||||
}
|
||||
|
||||
@Test fun replacedHandlerIsNotWaitedForPastTheStartWindow() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
@@ -107,6 +124,17 @@ class SessionSuspendControllerTest {
|
||||
assertEquals(1, fixture.pagedIn.size)
|
||||
}
|
||||
|
||||
@Test fun theMonitorIsHeldOffWhilePagingOutAndReadingBack() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
val hold = File(fixture.control.parentFile, ".dd-zram.hold")
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
assertFalse(hold.exists())
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(hold.exists())
|
||||
assertEquals(listOf<String?>("1", "0"), fixture.held)
|
||||
}
|
||||
|
||||
@Test fun noReadBackAfterAFreezeWithoutPageOut() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
@@ -116,6 +144,18 @@ class SessionSuspendControllerTest {
|
||||
assertTrue(fixture.pagedIn.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aTrimRequestInTheControlFileDoesNotReplaceThePageOut() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.afterSleep = { fixture.control.writeText("2 4096\n") }
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf<String?>("1", "0"), fixture.held)
|
||||
assertEquals("2 4096\n", fixture.control.readText())
|
||||
assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut)
|
||||
assertEquals(listOf(Triple(1, 0L, 3_000_000L)), fixture.pagedIn)
|
||||
}
|
||||
|
||||
@Test fun readBackIsSkippedWhenAvailableMemoryCannotTakeIt() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
@@ -124,7 +164,7 @@ class SessionSuspendControllerTest {
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.signals.drop(before).any { it.signal == URG })
|
||||
assertEquals("1", fixture.control.readText())
|
||||
assertEquals(listOf<String?>("1"), fixture.held)
|
||||
assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn)
|
||||
}
|
||||
|
||||
@@ -151,18 +191,6 @@ class SessionSuspendControllerTest {
|
||||
assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn)
|
||||
}
|
||||
|
||||
@Test fun noReadBackWithARamCap() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.readBackAllowed = false
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.signals.drop(before).any { it.signal == URG })
|
||||
assertEquals("1", fixture.control.readText())
|
||||
assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn)
|
||||
}
|
||||
|
||||
@Test fun cancelledFreezeReadsBackWhatThePageOutAlreadyMoved() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
@@ -170,7 +198,7 @@ class SessionSuspendControllerTest {
|
||||
fixture.controller.freeze(pageOut = true) { assertFalse(it) }
|
||||
assertFalse(fixture.signals.any { it.signal == STOP })
|
||||
assertEquals(2, fixture.signals.count { it.signal == URG })
|
||||
assertEquals("0", fixture.control.readText())
|
||||
assertEquals(listOf<String?>("1", "0"), fixture.held)
|
||||
assertEquals(1, fixture.pagedIn.single().first)
|
||||
assertEquals(0L, fixture.pagedIn.single().second)
|
||||
assertTrue(fixture.pagedIn.single().third > 0L)
|
||||
@@ -183,7 +211,7 @@ class SessionSuspendControllerTest {
|
||||
fixture.afterSleep = { if (fixture.now >= 500) fixture.controller.cancelFreeze() }
|
||||
fixture.controller.freeze(pageOut = true) { assertFalse(it) }
|
||||
assertEquals(2, fixture.signals.count { it.signal == URG })
|
||||
assertEquals("0", fixture.control.readText())
|
||||
assertEquals(listOf<String?>("1", "0"), fixture.held)
|
||||
assertEquals(Triple(1, 0L, 0L), fixture.pagedIn.single())
|
||||
}
|
||||
|
||||
@@ -467,6 +495,7 @@ class SessionSuspendControllerTest {
|
||||
val groups = mutableListOf(root, game)
|
||||
val helpers = mutableListOf<Int>()
|
||||
val signals = mutableListOf<SentSignal>()
|
||||
val held = mutableListOf<String?>()
|
||||
var rootPid = ROOT
|
||||
var now = 0L
|
||||
var audioSuspends = 0
|
||||
@@ -486,7 +515,6 @@ class SessionSuspendControllerTest {
|
||||
val pagedIn = mutableListOf<Triple<Int, Long, Long>>()
|
||||
var availableKb = 8_000_000L
|
||||
var totalKb = 16_000_000L
|
||||
var readBackAllowed = true
|
||||
private var gameResidentKb = 4_000_000L
|
||||
private var gameSwapKb = 0L
|
||||
private var pagingOut = false
|
||||
@@ -506,7 +534,6 @@ class SessionSuspendControllerTest {
|
||||
pagedOut += Triple(processes, resident, swap)
|
||||
this.unacknowledged = unacknowledged
|
||||
},
|
||||
readBackAllowed = { readBackAllowed },
|
||||
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
|
||||
)
|
||||
|
||||
@@ -514,6 +541,8 @@ class SessionSuspendControllerTest {
|
||||
|
||||
private fun signal(pid: Int, signal: Int) {
|
||||
signals += SentSignal(pid, signal)
|
||||
val request = if (signal == URG) File(control.parentFile, "${control.name}.hold").takeIf { it.isFile }?.readText() else null
|
||||
if (signal == URG) held += request
|
||||
val group = groups.first { it.pid == pid }
|
||||
if (signal == STOP) {
|
||||
continuing = false
|
||||
@@ -522,7 +551,7 @@ class SessionSuspendControllerTest {
|
||||
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
|
||||
}?.state = 't'
|
||||
} else if (signal == URG) {
|
||||
if (control.readText() == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
|
||||
if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
|
||||
} else if (signal == CONT) {
|
||||
if (clockAtContinue == null && clock.isFile) {
|
||||
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
|
||||
|
||||
@@ -20,9 +20,9 @@ class ShaderPrecachePrefsTest {
|
||||
SessionPrefs.steamRoot(context, SessionPrefs.steamClientArch(context)).deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun clientWithoutConfigStartsWithPrecachingOff() {
|
||||
assertEquals(false, SessionPrefs.pendingShaderPrecache(context))
|
||||
assertEquals(false, SessionPrefs.shaderPrecache(context))
|
||||
@Test fun clientWithoutConfigStartsWithPrecachingOn() {
|
||||
assertEquals(true, SessionPrefs.pendingShaderPrecache(context))
|
||||
assertEquals(true, SessionPrefs.shaderPrecache(context))
|
||||
}
|
||||
|
||||
@Test fun existingConfigKeepsTheClientsChoice() {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.storage
|
||||
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], application = android.app.Application::class)
|
||||
class KeptPrefixRemovalTest {
|
||||
private val compat = File("/rootfs/root/.local/share/Steam/steamapps/compatdata")
|
||||
|
||||
private fun kept(id: String, owner: PrefixOwner) = KeptPrefix(File(compat, id), owner, null, 1L shl 30, "Internal", false)
|
||||
|
||||
private fun report(kept: List<KeptPrefix>, storeFolders: List<File> = emptyList()) = StorageReport(
|
||||
0, 0, 0, emptyMap(), 0, 0, 0, 0, emptyList(), emptyList(), emptyList(), emptyList(), 0, emptyList(), emptyList(), 0,
|
||||
kept, true, storeFolders.map { StoreGameUsage(InstalledStoreGame(StoreGameSidecar(Store.BATTLENET, "pro", "Game", "Game.exe"), it), -1, false) },
|
||||
)
|
||||
|
||||
@Test fun launcherAndUnknownPrefixesCanBeRemoved() {
|
||||
val launcher = kept("2929927072", PrefixOwner.LAUNCHER)
|
||||
val unknown = kept("1234", PrefixOwner.UNKNOWN)
|
||||
val r = report(listOf(launcher, unknown))
|
||||
assertTrue(StorageState.keptRemovable(r, launcher))
|
||||
assertTrue(StorageState.keptRemovable(r, unknown))
|
||||
assertTrue(StorageState.keptRemovable(r, kept("0", PrefixOwner.SHARED)))
|
||||
}
|
||||
|
||||
@Test fun aLauncherPrefixHoldingAnInstalledGameStays() {
|
||||
val bnet = kept("2611429436", PrefixOwner.LAUNCHER)
|
||||
val inside = File(bnet.dir, "pfx/drive_c/Program Files (x86)/Overwatch")
|
||||
assertFalse(StorageState.keptRemovable(report(listOf(bnet), listOf(inside)), bnet))
|
||||
val elsewhere = File(compat, "2611429436-other/Overwatch")
|
||||
assertTrue(StorageState.keptRemovable(report(listOf(bnet), listOf(elsewhere)), bnet))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.storage
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], application = android.app.Application::class)
|
||||
class StorageSummaryTest {
|
||||
@Test fun theSavedOverviewReadsBackAsWritten() {
|
||||
val buckets = Bucket.entries.mapIndexed { i, b -> b to (i + 1) * 1_000_000_000L }.toMap()
|
||||
val s = StorageSummary(42, 103L shl 30, 49L shl 30, buckets, 234L shl 20, 3, 1, 7L shl 30, 9L shl 20, 350L shl 20,
|
||||
12, 226L shl 20, 8, 73L shl 20, 0, 0, 105L shl 20, 9L shl 20, 8L shl 30)
|
||||
val back = StorageSummary.fromJson(s.toJson())!!
|
||||
assertEquals(s.toJson(), back.toJson())
|
||||
assertEquals(buckets, back.buckets)
|
||||
assertEquals(s.droiddeck, back.droiddeck)
|
||||
}
|
||||
|
||||
@Test fun anOtherVersionOrDamagedFileReadsAsNone() {
|
||||
assertNull(StorageSummary.fromJson("{\"v\":0}"))
|
||||
assertNull(StorageSummary.fromJson("not json"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.droiddeck.launcher.storage
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class SystemCachesTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private val now = 10L * 24 * 60 * 60 * 1000
|
||||
private val old = now - SystemCaches.TEMP_IDLE_MS - 1000
|
||||
|
||||
private fun file(path: String, modified: Long) = File(tmp.root, path).apply { parentFile!!.mkdirs(); writeText("x"); setLastModified(modified) }
|
||||
|
||||
@Test fun onlyIdleVisibleTemporaryFilesAreCleared() {
|
||||
file("rootfs/tmp/old.deb", old)
|
||||
file("rootfs/tmp/oldDir/a", old).parentFile!!.setLastModified(old)
|
||||
file("rootfs/tmp/busyDir/a", old)
|
||||
file("rootfs/tmp/busyDir/b", now - 1000).parentFile!!.setLastModified(old)
|
||||
file("rootfs/tmp/.X11-unix/X0", old).parentFile!!.setLastModified(old)
|
||||
file("rootfs/tmp/fresh.log", now)
|
||||
val found = SystemCaches.find(File(tmp.root, "rootfs"), emptyList(), now)
|
||||
assertEquals(listOf("old.deb", "oldDir"), found.getValue(SystemCache.TEMP).map { it.name }.sorted())
|
||||
}
|
||||
|
||||
@Test fun packagesAndSteamCachesAreFound() {
|
||||
file("rootfs/var/cache/apt/archives/git_1_arm64.deb", now)
|
||||
file("rootfs/var/cache/apt/archives/lock", now)
|
||||
file("rootfs/var/cache/apt/archives/partial/perl.deb", now)
|
||||
val steam = File(tmp.root, "rootfs/root/.local/share/Steam")
|
||||
file("rootfs/root/.local/share/Steam/config/htmlcache/Cache/data_0", now)
|
||||
file("rootfs/root/.local/share/Steam/steamapps/corrupt/1_2_ab_corrupt.chunk", now)
|
||||
val found = SystemCaches.find(File(tmp.root, "rootfs"), listOf(steam, File(tmp.root, "missing")), now)
|
||||
assertEquals(listOf("git_1_arm64.deb", "perl.deb"), found.getValue(SystemCache.PACKAGES).map { it.name }.sorted())
|
||||
assertEquals(listOf(File(steam, "config/htmlcache")), found.getValue(SystemCache.STEAM_WEB))
|
||||
assertEquals(listOf(File(steam, "steamapps/corrupt")), found.getValue(SystemCache.STEAM_CORRUPT))
|
||||
}
|
||||
|
||||
@Test fun checkoutsAndTheirWorktreeRecordsAreFound() {
|
||||
val rootfs = File(tmp.root, "rootfs")
|
||||
File(rootfs, "root/DroidDeck/.git/worktrees/dd-pet").mkdirs()
|
||||
file("rootfs/root/dd-pet/.git", now).writeText("gitdir: /root/DroidDeck/.git/worktrees/dd-pet\n")
|
||||
file("rootfs/root/own/.git/HEAD", now)
|
||||
file("rootfs/root/notes/readme", now)
|
||||
file("rootfs/root/bad/.git", now).writeText("gitdir: /root/DroidDeck/.git/worktrees/../../../etc\n")
|
||||
assertEquals(listOf("bad", "dd-pet", "own"), SystemCaches.checkouts(rootfs).map { it.name }.sorted())
|
||||
assertEquals(File(rootfs, "root/DroidDeck/.git/worktrees/dd-pet"), SystemCaches.worktreeRecord(rootfs, File(rootfs, "root/dd-pet")))
|
||||
assertEquals(null, SystemCaches.worktreeRecord(rootfs, File(rootfs, "root/own")))
|
||||
assertEquals(null, SystemCaches.worktreeRecord(rootfs, File(rootfs, "root/bad")))
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import com.droiddeck.launcher.stores.ubisoft.MemorySlots
|
||||
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloud
|
||||
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloudTransport
|
||||
import java.io.File
|
||||
import java.util.concurrent.Executor
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
@@ -20,10 +23,18 @@ class CloudSavesTest {
|
||||
private class Memory : CloudTransport {
|
||||
val files = HashMap<String, Pair<ByteArray, Long>>()
|
||||
val puts = ArrayList<String>()
|
||||
var onGet: (CloudFile) -> Unit = {}
|
||||
var raceAfter = Int.MAX_VALUE
|
||||
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>, modifiedMs: Map<String, Long>): Map<String, Long> =
|
||||
files.mapValues { (k, v) -> puts += k; this.files[k] = v to 99_000L; 99_000L }
|
||||
override fun get(file: CloudFile) = files.getValue(file.name).also { onGet(file) }
|
||||
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
|
||||
val sent = LinkedHashMap<String, Long>()
|
||||
for ((k, v) in files) {
|
||||
if (sent.size >= raceAfter) throw CloudChanged(sent, files.keys.filter { it !in sent })
|
||||
puts += k; this.files[k] = v to 99_000L; sent[k] = 99_000L
|
||||
}
|
||||
return sent
|
||||
}
|
||||
}
|
||||
|
||||
private fun dir() = File(app.filesDir, "saves-${System.nanoTime()}").apply { mkdirs() }
|
||||
@@ -50,6 +61,72 @@ class CloudSavesTest {
|
||||
assertEquals("v1", File(kept, "slot0.sav").readText())
|
||||
}
|
||||
|
||||
@Test fun aFolderAliasNeverHidesTheRealSaveFromARestore() {
|
||||
val game = id; val dir = dir()
|
||||
File(dir, "SaveData").mkdirs(); File(dir, "SaveData/slot.sav").writeText("local")
|
||||
val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "Cache").toPath(), File(dir, "SaveData").toPath()) }
|
||||
org.junit.Assume.assumeTrue(link.isSuccess)
|
||||
val memory = Memory().apply { files["SaveData/slot.sav"] = "cloud".toByteArray() to 1000L }
|
||||
val cloud = object : CloudTransport by memory {
|
||||
override fun wants(name: String) = name.startsWith("SaveData/")
|
||||
}
|
||||
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true)
|
||||
assertEquals("cloud", File(dir, "SaveData/slot.sav").readText())
|
||||
val kept = File(app.filesDir, "stores/cloud-backups/gog-$game").listFiles { f -> f.name.startsWith("local-") }!!.single()
|
||||
assertEquals("local", File(kept, "SaveData/slot.sav").readText())
|
||||
}
|
||||
|
||||
@Test fun aSaveReachedOnlyThroughAFolderAliasStillGoesUp() {
|
||||
val game = id; val dir = dir()
|
||||
File(dir, "Actual").mkdirs(); File(dir, "Actual/slot.sav").writeText("played")
|
||||
val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "SaveData").toPath(), File(dir, "Actual").toPath()) }
|
||||
org.junit.Assume.assumeTrue(link.isSuccess)
|
||||
java.nio.file.Files.createSymbolicLink(File(dir, "Actual/loop").toPath(), dir.toPath())
|
||||
val memory = Memory()
|
||||
val cloud = object : CloudTransport by memory {
|
||||
override fun wants(name: String) = name.startsWith("SaveData/")
|
||||
}
|
||||
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
assertEquals("uploaded", r.reason)
|
||||
assertEquals(listOf("SaveData/slot.sav"), memory.puts)
|
||||
assertEquals("played", String(memory.files.getValue("SaveData/slot.sav").first))
|
||||
}
|
||||
|
||||
@Test fun onlySelectedSavesCanCollideByCase() {
|
||||
val names = listOf("Logs/A.txt", "Logs/a.txt", "SaveGame/1")
|
||||
assertFalse(CloudSaves.caseCollision(names) { !it.startsWith("Logs/") })
|
||||
assertTrue(CloudSaves.caseCollision(names) { true })
|
||||
assertTrue(CloudSaves.caseCollision(listOf("SaveGame/1", "savegame/1")) { it.lowercase().startsWith("savegame/") })
|
||||
}
|
||||
|
||||
@Test fun aSavedConflictWhoseSidesNowMatchIsCleared() {
|
||||
val game = id; val dir = dir()
|
||||
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
|
||||
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
cloud.files["slot0.sav"] = "v2".toByteArray() to 50_000L
|
||||
File(dir, "slot0.sav").writeText("v2")
|
||||
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav").apply()
|
||||
assertEquals("up-to-date", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false).reason)
|
||||
assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty())
|
||||
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav").apply()
|
||||
CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aDownloadTheLaunchStoppedWaitingForWritesNothing() {
|
||||
val game = id; val dir = dir()
|
||||
File(dir, "slot0.sav").writeText("local")
|
||||
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
|
||||
val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true, claim = { false })
|
||||
assertEquals("skipped", r.result); assertEquals("launch-moved-on", r.reason)
|
||||
assertEquals("local", File(dir, "slot0.sav").readText())
|
||||
assertFalse(File(app.filesDir, "stores/cloud-backups/gog-$game").exists())
|
||||
var claimed = 0
|
||||
assertEquals("ok", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true, claim = { claimed++; true }).result)
|
||||
assertEquals(1, claimed); assertEquals("v1", File(dir, "slot0.sav").readText())
|
||||
}
|
||||
|
||||
@Test fun aFileChangedOnBothSidesIsLeftForTheUser() {
|
||||
val game = id; val dir = dir()
|
||||
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
|
||||
@@ -65,6 +142,134 @@ class CloudSavesTest {
|
||||
assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aSlotTheGameRewritesDuringADownloadIsKeptAndNamedAsAConflict() {
|
||||
val game = id; val dir = dir()
|
||||
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
|
||||
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
cloud.files["slot0.sav"] = "cloud v2".toByteArray() to 50_000L
|
||||
cloud.onGet = { File(dir, "slot0.sav").writeText("game wrote") }
|
||||
val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
assertEquals("partial", r.result); assertEquals("changed-locally", r.reason); assertEquals(1, r.conflicts)
|
||||
assertTrue(r.detail.contains("slot0.sav"))
|
||||
assertEquals("game wrote", File(dir, "slot0.sav").readText())
|
||||
assertEquals(listOf("slot0.sav"), CloudSaves.conflicts(app, Store.GOG, game))
|
||||
}
|
||||
|
||||
@Test fun aCloudNameOutsideTheSaveFolderIsBlockedNotAConflict() {
|
||||
val game = id; val dir = dir()
|
||||
val cloud = Memory().apply { files["../escape.sav"] = "x".toByteArray() to 1000L }
|
||||
val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
assertEquals("partial", r.result); assertEquals("blocked-path", r.reason); assertEquals(0, r.conflicts)
|
||||
assertTrue(r.detail.contains("../escape.sav"))
|
||||
assertFalse(File(dir.parentFile, "escape.sav").exists())
|
||||
assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun anUploadStoppedByANewerCloudWriteKeepsTheRestAsConflicts() {
|
||||
val game = id; val dir = dir()
|
||||
val cloud = Memory().apply { files["a.sav"] = "a1".toByteArray() to 1000L; files["b.sav"] = "b1".toByteArray() to 1000L }
|
||||
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
File(dir, "a.sav").writeText("a2"); File(dir, "b.sav").writeText("b2")
|
||||
cloud.raceAfter = 1
|
||||
val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
assertEquals("partial", r.result); assertEquals("changed-in-cloud", r.reason); assertEquals(1, r.files)
|
||||
val unsent = listOf("a.sav", "b.sav").single { it !in cloud.puts }
|
||||
assertEquals(listOf(unsent), CloudSaves.conflicts(app, Store.GOG, game))
|
||||
}
|
||||
|
||||
@Test fun aForcedUploadKeepsConflictsForSlotsItDidNotSend() {
|
||||
val game = id; val dir = dir()
|
||||
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L; files["slot1.sav"] = "w1".toByteArray() to 1000L }
|
||||
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
|
||||
File(dir, "slot0.sav").writeText("local v2"); File(dir, "slot1.sav").delete()
|
||||
cloud.files["slot0.sav"] = "cloud v2".toByteArray() to 50_000L
|
||||
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav\nslot1.sav").apply()
|
||||
CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = true)
|
||||
assertEquals("local v2", String(cloud.files.getValue("slot0.sav").first))
|
||||
assertEquals(listOf("slot1.sav"), CloudSaves.conflicts(app, Store.GOG, game))
|
||||
}
|
||||
|
||||
private fun ubisoftDir(user: String, root: File = File(app.filesDir, "ubi-${System.nanoTime()}")) = File(root, "$user/77").apply { mkdirs() }
|
||||
|
||||
@Test fun aSlotBothSidesSavedAlikeIsNotAConflictWhenTheCloudNamesOnlyAVersion() {
|
||||
val game = id; val dir = ubisoftDir("u1")
|
||||
val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) }
|
||||
assertEquals("ok", CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false).result)
|
||||
File(dir, "1.save").writeBytes(MemorySlots.save("a2"))
|
||||
slots.store("1", MemorySlots.save("a2"))
|
||||
val down = CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false)
|
||||
assertEquals(0, down.conflicts)
|
||||
assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, dir).isEmpty())
|
||||
val up = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false)
|
||||
assertEquals("up-to-date", up.reason); assertEquals(0, up.conflicts)
|
||||
File(dir, "1.save").writeBytes(MemorySlots.save("a3 local"))
|
||||
slots.store("1", MemorySlots.save("a3 cloud"))
|
||||
assertEquals(1, CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false).conflicts)
|
||||
}
|
||||
|
||||
@Test fun aNewUbisoftSaveWithAnEmptyIdentifierIsStampedAndUploaded() {
|
||||
val game = id; val dir = ubisoftDir("u1")
|
||||
val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) }
|
||||
CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false)
|
||||
File(dir, "2.save").writeBytes("UBISAVE0".toByteArray() + ByteArray(32) + "fresh slot".toByteArray())
|
||||
File(dir, "3.save").writeBytes("UBISAVE0".toByteArray() + "not-an-identifier-but-not-empty!".toByteArray())
|
||||
val up = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false)
|
||||
assertEquals("uploaded", up.reason)
|
||||
val stamped = UbisoftCloud.mark(File(dir, "2.save").readBytes())
|
||||
assertTrue(stamped != null)
|
||||
assertEquals("fresh slot", String(File(dir, "2.save").readBytes().copyOfRange(40, 50)))
|
||||
assertEquals(stamped, UbisoftCloud.mark(slots.data.getValue("2")))
|
||||
assertFalse("3" in slots.data)
|
||||
assertEquals("not-an-identifier-but-not-empty!", String(File(dir, "3.save").readBytes().copyOfRange(8, 40)))
|
||||
}
|
||||
|
||||
@Test fun aSlotCommittedBeforeALaterOneFailsReachesTheBaseline() {
|
||||
val game = id; val dir = ubisoftDir("u1")
|
||||
val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")); store("2", MemorySlots.save("b1")) }
|
||||
CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false)
|
||||
File(dir, "1.save").writeBytes(MemorySlots.save("a2")); File(dir, "2.save").writeBytes(MemorySlots.save("b2"))
|
||||
slots.uploadsLeft = 1
|
||||
assertTrue(runCatching { CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) }
|
||||
.exceptionOrNull() is java.io.IOException)
|
||||
val base = CloudSaves.baseline(app, Store.UBISOFT, CloudSaves.scope(Store.UBISOFT, game, dir))!!
|
||||
val sent = listOf("1", "2").single { slots.data.getValue(it).contentEquals(MemorySlots.save(if (it == "1") "a2" else "b2")) }
|
||||
val kept = if (sent == "1") "2" else "1"
|
||||
assertEquals(CloudSaves.md5(File(dir, "$sent.save")), base.getValue("$sent.save").localMd5)
|
||||
assertEquals(CloudSaves.md5(MemorySlots.save(if (kept == "1") "a1" else "b1")), base.getValue("$kept.save").localMd5)
|
||||
slots.uploadsLeft = Int.MAX_VALUE
|
||||
val r = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false)
|
||||
assertEquals("ok", r.result); assertEquals(1, r.files); assertEquals(0, r.conflicts)
|
||||
}
|
||||
|
||||
@Test fun ubisoftConflictsBelongToTheAccountAndProductThatHadThem() {
|
||||
val game = id; val root = File(app.filesDir, "ubi-${System.nanoTime()}")
|
||||
val a = ubisoftDir("uA", root); val b = ubisoftDir("uB", root)
|
||||
val cloudB = Memory().apply { files["slot0.save"] = "b1".toByteArray() to 1000L }
|
||||
CloudSaves.downWith(app, Store.UBISOFT, game, b, cloudB, force = false)
|
||||
File(b, "slot0.save").writeText("b local")
|
||||
val cloudA = Memory().apply { files["slot0.save"] = "a1".toByteArray() to 1000L }
|
||||
CloudSaves.downWith(app, Store.UBISOFT, game, a, cloudA, force = false)
|
||||
File(a, "slot0.save").writeText("a local")
|
||||
cloudA.files["slot0.save"] = "a2".toByteArray() to 50_000L
|
||||
assertEquals(1, CloudSaves.downWith(app, Store.UBISOFT, game, a, cloudA, force = false).conflicts)
|
||||
assertEquals(listOf("slot0.save"), CloudSaves.conflicts(app, Store.UBISOFT, game, a))
|
||||
assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, b).isEmpty())
|
||||
CloudSaves.downWith(app, Store.UBISOFT, game, b, cloudB, force = true)
|
||||
assertEquals("b local", File(b, "slot0.save").readText())
|
||||
com.droiddeck.launcher.stores.epic.EpicPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.save").apply()
|
||||
assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, ubisoftDir("uC", root)).isEmpty())
|
||||
assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aUbisoftGameAddedFromAnotherFolderIsFoundForCloudSaves() {
|
||||
val game = id
|
||||
val folder = File(app.filesDir, "Elsewhere/Anno-$game").apply { mkdirs() }
|
||||
File(folder, "Anno.exe").writeText("MZ")
|
||||
StoreGameSidecar(Store.UBISOFT, game, "Anno", "Anno.exe", extra = mapOf("productId" to "77")).write(folder)
|
||||
com.droiddeck.launcher.session.SessionPrefs.followStoreGame(app, "ubisoft:$game", folder.path) { true }
|
||||
assertEquals("not-signed-in", CloudSaves.status(app, Store.UBISOFT, game).reason)
|
||||
}
|
||||
|
||||
@Test fun aDirtyMarkStaysUntilAnUploadGoesThroughOrIsSkippedForGood() {
|
||||
val gameId = "1207664643"
|
||||
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN-mark").apply { mkdirs() }
|
||||
|
||||
@@ -24,4 +24,45 @@ class DownloadEntryTest {
|
||||
assertFalse(e.passed(DownloadStage.INSTALL))
|
||||
assertTrue(e.copy(state = DownloadState.INSTALLED).passed(DownloadStage.INSTALL))
|
||||
}
|
||||
|
||||
@Test fun streamingInstallKeepsDownloadAndInstallProgressApart() {
|
||||
val installBit = 1 shl DownloadStage.INSTALL.ordinal
|
||||
val installing = base.copy(stage = DownloadStage.INSTALL, bytesDone = 10, bytesTotal = 100, stageDone = 25, stageTotal = 100)
|
||||
assertTrue(installing.streaming)
|
||||
assertEquals(0.10f, installing.downloadFraction, 0.001f)
|
||||
assertEquals(0.25f, installing.installFraction, 0.001f)
|
||||
val backToDownload = installing.copy(stage = DownloadStage.DOWNLOAD, stagesPassed = installBit)
|
||||
assertTrue(backToDownload.streaming)
|
||||
assertEquals(0.25f, backToDownload.installFraction, 0.001f)
|
||||
assertFalse(base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 10, bytesTotal = 100).streaming)
|
||||
assertTrue(installing.copy(bytesDone = 99_950, bytesTotal = 100_000).streaming)
|
||||
assertTrue(installing.copy(bytesDone = 99_999_999, bytesTotal = 100_000_000).streaming)
|
||||
assertFalse(installing.copy(bytesDone = 100).streaming)
|
||||
assertFalse(installing.copy(state = DownloadState.PAUSED).streaming)
|
||||
}
|
||||
|
||||
@Test fun overallProgressOnlyGrowsAcrossSequentialAndStreamingStages() {
|
||||
val installBit = 1 shl DownloadStage.INSTALL.ordinal
|
||||
val downloadBit = 1 shl DownloadStage.DOWNLOAD.ordinal
|
||||
val sequential = listOf(
|
||||
base.copy(stage = DownloadStage.MANIFEST),
|
||||
base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 50, bytesTotal = 100),
|
||||
base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 100, bytesTotal = 100),
|
||||
base.copy(stage = DownloadStage.INSTALL, bytesDone = 100, bytesTotal = 100, stagesPassed = downloadBit, stageDone = 0, stageTotal = 10),
|
||||
base.copy(stage = DownloadStage.INSTALL, bytesDone = 100, bytesTotal = 100, stagesPassed = downloadBit, stageDone = 10, stageTotal = 10),
|
||||
base.copy(state = DownloadState.INSTALLED),
|
||||
).map { it.overallFraction }
|
||||
assertEquals(sequential, sequential.sorted())
|
||||
assertEquals(1f, sequential.last(), 0f)
|
||||
val streaming = listOf(
|
||||
base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 10, bytesTotal = 100),
|
||||
base.copy(stage = DownloadStage.INSTALL, bytesDone = 20, bytesTotal = 100, stageDone = 15, stageTotal = 100),
|
||||
base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 40, bytesTotal = 100, stageDone = 15, stageTotal = 100, stagesPassed = installBit),
|
||||
base.copy(stage = DownloadStage.INSTALL, bytesDone = 60, bytesTotal = 100, stageDone = 55, stageTotal = 100, stagesPassed = installBit),
|
||||
base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 100, bytesTotal = 100, stageDone = 60, stageTotal = 100, stagesPassed = installBit),
|
||||
base.copy(stage = DownloadStage.INSTALL, bytesDone = 100, bytesTotal = 100, stageDone = 80, stageTotal = 100, stagesPassed = installBit or downloadBit),
|
||||
).map { it.overallFraction }
|
||||
assertEquals(streaming, streaming.sorted())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.droiddeck.launcher.stores.ea
|
||||
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.CloudSaves
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreLaunch
|
||||
@@ -413,4 +414,190 @@ class EaTest {
|
||||
assertTrue(!EaAuth.storeRefreshed(app, "late", 3600, "r3"))
|
||||
assertNull(EaAuth.load(app))
|
||||
}
|
||||
|
||||
private fun tokenServer(status: String, error: String = "invalid_grant"): java.net.ServerSocket {
|
||||
val server = java.net.ServerSocket(0)
|
||||
Thread {
|
||||
runCatching {
|
||||
server.accept().use { socket ->
|
||||
val input = socket.getInputStream()
|
||||
val head = StringBuilder()
|
||||
while (!head.endsWith("\r\n\r\n")) head.append(input.read().takeIf { it >= 0 }?.toChar() ?: break)
|
||||
val length = Regex("(?i)content-length: *(\\d+)").find(head)?.groupValues?.get(1)?.toInt() ?: 0
|
||||
repeat(length) { input.read() }
|
||||
val body = """{"error":"$error"}""".toByteArray()
|
||||
socket.getOutputStream().apply {
|
||||
write("HTTP/1.1 $status\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
write(body)
|
||||
flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
return server
|
||||
}
|
||||
|
||||
@Test fun aRejectedRefreshAsksForSignInWhileAnUnreachableOneKeepsTheSessionForARetry() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val real = EaAuth.tokenUrl
|
||||
try {
|
||||
com.droiddeck.launcher.stores.StoreAccounts.write(app, Store.EA,
|
||||
JSONObject().put("access_token", "old").put("refresh_token", "r").put("expires_at", 1L).put("user_id", "1"))
|
||||
EaAuth.tokenUrl = "http://127.0.0.1:1/"
|
||||
assertNull(EaAuth.accessToken(app))
|
||||
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
tokenServer("503 Service Unavailable", "temporarily_unavailable").use { server ->
|
||||
EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/"
|
||||
assertNull(EaAuth.accessToken(app))
|
||||
}
|
||||
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
tokenServer("400 Bad Request", "invalid_client").use { server ->
|
||||
EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/"
|
||||
assertNull(EaAuth.accessToken(app))
|
||||
}
|
||||
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
tokenServer("400 Bad Request").use { server ->
|
||||
EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/"
|
||||
assertNull(EaAuth.accessToken(app))
|
||||
}
|
||||
assertFalse(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
assertTrue(EaAuth.storeRefreshed(app, "new", 3600, "r2"))
|
||||
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
|
||||
} finally {
|
||||
EaAuth.tokenUrl = real
|
||||
EaAuth.signOut(app)
|
||||
}
|
||||
}
|
||||
|
||||
private val heat = """<saveFileCriteria>
|
||||
<include order="0">%Documents%/Need for Speed Heat/SaveGame/savegame/</include>
|
||||
<include order="1">%Documents%/Need for Speed Heat/SaveGame/wraps/</include>
|
||||
<include order="2">%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS</include>
|
||||
</saveFileCriteria>"""
|
||||
|
||||
@Test fun rulesFindTheFolderTheyShareAndPickOnlyTheirFiles() {
|
||||
val rules = EaSaveRules.parse(heat)!!
|
||||
assertEquals("%Documents%/Need for Speed Heat/", rules.base())
|
||||
assertEquals("%DOCUMENTS%/Need for Speed Heat/", EaSaveRules.template(rules.base()!!))
|
||||
assertTrue(rules.matches("%Documents%/Need for Speed Heat/SaveGame/savegame/1"))
|
||||
assertTrue(rules.matches("%documents%\\need for speed heat\\settings\\PROFILEOPTIONS"))
|
||||
assertFalse(rules.matches("%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS.bak"))
|
||||
assertFalse(rules.matches("%Documents%/Need for Speed Heat/Logs/crash.txt"))
|
||||
}
|
||||
|
||||
@Test fun globsStayInsideTheirFolderAndExcludesWin() {
|
||||
val bf = EaSaveRules.parse("""<saveFileCriteria><include order="0">%Documents%/Battlefield 6/settings/*.xml</include>
|
||||
<include order="2">%Documents%/Battlefield 6/settings/*.sav</include></saveFileCriteria>""")!!
|
||||
assertEquals("%Documents%/Battlefield 6/settings/", bf.base())
|
||||
assertTrue(bf.matches("%Documents%/Battlefield 6/settings/a.sav"))
|
||||
assertFalse(bf.matches("%Documents%/Battlefield 6/settings/sub/a.sav"))
|
||||
val le = EaSaveRules.parse("""<saveFileCriteria>
|
||||
<exclude order="0">%Documents%/BioWare/Mass Effect Legendary Edition/Config/</exclude>
|
||||
<include order="1">%Documents%/BioWare/Mass Effect Legendary Edition/</include></saveFileCriteria>""")!!
|
||||
assertTrue(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Save/ME1/x.pcsav"))
|
||||
assertFalse(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Config/GamerSettings.ini"))
|
||||
assertNull(EaSaveRules.parse("<saveFileCriteria></saveFileCriteria>"))
|
||||
assertNull(EaSaveRules.parse("""<saveFileCriteria><include order="0">C:/Games/x/</include></saveFileCriteria>""")!!.base())
|
||||
}
|
||||
|
||||
@Test fun rulesApplyInTheirOrderAndTheFirstMatchDecides() {
|
||||
val rules = EaSaveRules.parse("""<saveFileCriteria>
|
||||
<exclude order="1">%Documents%/Game/Config/</exclude>
|
||||
<include order="0">%Documents%/Game/Config/keys.ini</include>
|
||||
<include order="2">%Documents%/Game/</include></saveFileCriteria>""")!!
|
||||
assertTrue(rules.matches("%Documents%/Game/Config/keys.ini"))
|
||||
assertFalse(rules.matches("%Documents%/Game/Config/video.ini"))
|
||||
assertTrue(rules.matches("%Documents%/Game/Save/1.sav"))
|
||||
}
|
||||
|
||||
@Test fun aBarePatternMatchesFileNamesInsideTheSaveFolder() {
|
||||
val dig = EaSaveRules.parse("""<saveFileCriteria>
|
||||
<exclude order="0">%Documents%/My Games/SteamWorld Dig/controls.cfg</exclude>
|
||||
<exclude order="2">%Documents%/My Games/SteamWorld Dig/settings.xml</exclude>
|
||||
<include order="3">*.xml</include>
|
||||
<include order="4">%Documents%/My Games/SteamWorld Dig/profile.dat</include></saveFileCriteria>""")!!
|
||||
assertEquals("%Documents%/My Games/SteamWorld Dig/", dig.base())
|
||||
assertTrue(dig.matches("%Documents%/My Games/SteamWorld Dig/profile1.xml"))
|
||||
assertFalse(dig.matches("%Documents%/My Games/SteamWorld Dig/settings.xml"))
|
||||
assertFalse(dig.matches("%Documents%/Other Game/profile1.xml"))
|
||||
val witness = EaSaveRules.parse("""<saveFileCriteria><include order="0">%AppData%/The Witness/*</include><include order="1">*.png</include></saveFileCriteria>""")!!
|
||||
assertEquals("%AppData%/The Witness/", witness.base())
|
||||
assertTrue(witness.matches("%AppData%/The Witness/shot.png"))
|
||||
}
|
||||
|
||||
@Test fun localLowAndInstallFoldersResolveToTheirTemplates() {
|
||||
val fe = EaSaveRules.parse("""<saveFileCriteria><exclude order="0">%LocalLowAppData%/Zoink Games/Fe/SystemSettings.sav</exclude>
|
||||
<include order="1">%LocalLowAppData%/Zoink Games/Fe/Save1.sav</include></saveFileCriteria>""")!!
|
||||
assertEquals("%APPLICATION_DATA_LOCAL_LOW%/Zoink Games/Fe/", EaSaveRules.template(fe.base()!!))
|
||||
val castle = EaSaveRules.parse("""<saveFileCriteria><include order="0">%InstallDir%/x86/Lost_Castle_Data/lc_game_data</include>
|
||||
<include order="1">%InstallDir%/x64/Lost_Castle_Data/lc_game_data</include></saveFileCriteria>""")!!
|
||||
assertEquals("%INSTALL%/", EaSaveRules.template(castle.base()!!))
|
||||
assertTrue(castle.matches("%InstallDir%/x64/Lost_Castle_Data/lc_game_data"))
|
||||
assertFalse(castle.matches("%InstallDir%/x64/Lost_Castle_Data/other"))
|
||||
}
|
||||
|
||||
@Test fun aManifestWithSingleQuotedAttributesKeepsEveryField() {
|
||||
val m = EaCloud.parse("""<manifest xmlns='http://origin.com/cloudsaves/manifest' lineage='{1}'>
|
||||
<file size='12' href='content/12-ab' md5='q+w=='><localName created='2022-10-17T23:51:04ZZ' lastModified='2022-10-18T00:00:00ZZ'>%Documents%/A & B/1</localName></file>
|
||||
<snapshot>s1</snapshot></manifest>""")
|
||||
val f = m.files.single()
|
||||
assertEquals(12L, f.size); assertEquals("content/12-ab", f.href); assertEquals("q+w==", f.md5)
|
||||
assertEquals("2022-10-17T23:51:04ZZ", f.created); assertEquals("2022-10-18T00:00:00ZZ", f.modified)
|
||||
assertEquals("%Documents%/A & B/1", f.localName)
|
||||
assertEquals("{1}", m.lineage); assertEquals(listOf("s1"), m.snapshots)
|
||||
assertTrue(runCatching { EaCloud.parse("<manifest><file size='1'>") }.isFailure)
|
||||
}
|
||||
|
||||
@Test fun aManifestKeepsItsFilesSnapshotsAndEaTimestampsThroughAWrite() {
|
||||
val xml = """<manifest xmlns="http://origin.com/cloudsaves/manifest" lineage="{00000000-0000-0000-0000-000000000000}">
|
||||
<file size="115352" href="content/115352-c7996be80a6e38d1f8ef28866b114f8b" md5="x5lr6ApuONH47yiGaxFPiw==">
|
||||
<localName created="2022-10-17T23:51:04ZZ" lastModified="2022-10-17T23:51:04ZZ">%Documents%/Need for Speed Heat/SaveGame/savegame/1</localName>
|
||||
</file>
|
||||
<snapshot>80cmnqT/rIKQRmciINSVhQ==</snapshot>
|
||||
</manifest>"""
|
||||
val m = EaCloud.parse(xml)
|
||||
assertEquals(1, m.files.size)
|
||||
assertEquals("c7996be80a6e38d1f8ef28866b114f8b", EaCloud.hex(m.files[0].md5))
|
||||
assertEquals(1666050664000L, EaCloud.parseTime(m.files[0].modified))
|
||||
assertEquals("2022-10-17T23:51:04ZZ", EaCloud.stamp(1666050664123L))
|
||||
val again = EaCloud.parse(EaCloud.write(m))
|
||||
assertEquals(m.files.single().localName, again.files.single().localName)
|
||||
assertEquals(m.files.single().href, again.files.single().href)
|
||||
assertEquals(m.files.single().created, again.files.single().created)
|
||||
assertEquals(m.files.single().modified, again.files.single().modified)
|
||||
assertEquals(m.files.single().size, again.files.single().size)
|
||||
assertEquals(m.files.single().md5, again.files.single().md5)
|
||||
assertEquals(listOf("80cmnqT/rIKQRmciINSVhQ=="), again.snapshots)
|
||||
assertEquals(m.lineage, again.lineage)
|
||||
}
|
||||
|
||||
@Test fun commentedRulesAreIgnoredAndNamesKeepTheirSpaces() {
|
||||
val rules = EaSaveRules.parse("""<saveFileCriteria>
|
||||
<!-- <exclude order="0">%Documents%/Game/Config/</exclude> -->
|
||||
<include order="1"> %Documents%/Game/ </include></saveFileCriteria>""")!!
|
||||
assertEquals(listOf("%Documents%/Game/"), rules.includes)
|
||||
assertTrue(rules.excludes.isEmpty())
|
||||
assertTrue(rules.matches("%Documents%/Game/Config/a.ini"))
|
||||
assertEquals("%Documents%/Game/slot.sav ", EaSaveRules.normalize("%Documents%\\Game\\slot.sav "))
|
||||
}
|
||||
|
||||
@Test fun aTruncatedManifestIsRefused() {
|
||||
val cut = runCatching { EaCloud.parse("""<manifest lineage="{1}"><file size="1" href="content/1-a" md5="x5lr6ApuONH47yiGaxFPiw==">""") }
|
||||
assertTrue(cut.isFailure)
|
||||
val open = runCatching { EaCloud.parse("""<manifest lineage="{1}"><file size="1" href="content/1-a" md5="x5lr6ApuONH47yiGaxFPiw=="><localName>%Documents%/a</localName></manifest>""") }
|
||||
assertTrue(open.isFailure)
|
||||
}
|
||||
|
||||
@Test fun snapshotEntitiesAreDecodedOnceAndWrittenBackTheSame() {
|
||||
val m = EaCloud.parse("""<manifest lineage="{1}"><snapshot>abc+def</snapshot></manifest>""")
|
||||
assertEquals(listOf("abc+def"), m.snapshots)
|
||||
assertEquals(listOf("abc+def"), EaCloud.parse(EaCloud.write(m)).snapshots)
|
||||
}
|
||||
|
||||
@Test fun cloudKeysFollowTheMultiplayerId() {
|
||||
assertEquals(listOf("195133_195133"), EaCloud.keys("195133", "195133"))
|
||||
assertEquals(listOf("52209", "52209_52209"), EaCloud.keys("52209", ""))
|
||||
assertEquals("https://x/y?a=1&b=2", EaCloud.manifestUrl("<sync><manifest>https://x/y?a=1&b=2</manifest></sync>"))
|
||||
assertTrue(CloudSaves.supports(Store.EA))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.droiddeck.launcher.stores.ubisoft
|
||||
|
||||
import com.droiddeck.launcher.stores.CloudSaves
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.time.Instant
|
||||
|
||||
internal class MemorySlots : UbisoftSlots {
|
||||
private var record = JSONObject().put("entityId", "e1").put("name", UbisoftCloud.entityName(77L)).put("revision", 1)
|
||||
.put("obj", JSONObject().put("slots", JSONArray()))
|
||||
private var clock = 1_700_000_000_000L
|
||||
val data = HashMap<String, ByteArray>()
|
||||
var uploadsLeft = Int.MAX_VALUE
|
||||
var afterUpdate: (JSONArray) -> Unit = {}
|
||||
|
||||
override fun entity() = UbisoftCloud.Entity(JSONObject(record.toString()))
|
||||
|
||||
override fun upload(slot: String, data: ByteArray) {
|
||||
if (uploadsLeft-- <= 0) throw java.io.IOException("upload failed")
|
||||
this.data[slot] = data
|
||||
}
|
||||
|
||||
override fun update(entity: UbisoftCloud.Entity, slots: JSONArray) {
|
||||
afterUpdate(slots)
|
||||
record = JSONObject(record.toString()).put("revision", record.getInt("revision") + 1).put("obj", JSONObject().put("slots", slots))
|
||||
}
|
||||
|
||||
override fun download(slot: String) = data[slot]
|
||||
|
||||
fun store(slot: String, bytes: ByteArray) {
|
||||
data[slot] = bytes
|
||||
val slots = JSONArray(record.getJSONObject("obj").getJSONArray("slots").toString())
|
||||
val entry = (0 until slots.length()).map { slots.getJSONObject(it) }.firstOrNull { it.optString("filename") == slot }
|
||||
?: JSONObject().put("filename", slot).put("id", slot.toInt()).also { slots.put(it) }
|
||||
clock += 60_000L
|
||||
entry.put("hash", UbisoftCloud.mark(bytes)).put("size", bytes.size).put("lastModified", Instant.ofEpochMilli(clock).toString())
|
||||
record = JSONObject(record.toString()).put("revision", record.getInt("revision") + 1).put("obj", JSONObject().put("slots", slots))
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun save(tag: String): ByteArray = ("UBISAVE0" + CloudSaves.md5(tag.toByteArray()) + tag).toByteArray()
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreLaunch
|
||||
import org.json.JSONArray
|
||||
import java.io.File
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -39,6 +40,23 @@ class UbisoftTest {
|
||||
assertEquals("Steam", UbisoftLibrary.thirdParty(steamConfig))
|
||||
}
|
||||
|
||||
@Test fun gamesTheProfileLeavesOutTakeTheirArtFromTheConfiguration() {
|
||||
val config = "version: 2.0\r\nroot:\r\n name: l1\r\n thumb_image: THUMBIMAGE\r\n background_image: 'b4c1.jpg'\r\n" +
|
||||
" installer:\r\n thumb_image: nested.jpg\r\nlocalizations:\r\n default:\r\n l1: \"Assassin's Creed\u2122\"\r\n THUMBIMAGE: a3a6.jpg\r\n"
|
||||
val owned = JSONObject().put("games", JSONArray()
|
||||
.put(JSONObject().put("productId", 109).put("spaceId", "space-sc").put("productType", 0).put("owned", true).put("manifest", "AB").put("configuration", config))
|
||||
.put(JSONObject().put("productId", 82).put("spaceId", "space-ac").put("productType", 0).put("owned", true).put("manifest", "CD").put("configuration", config)))
|
||||
val art = CatalogItem(Store.UBISOFT, "space-sc", "Splinter Cell", "https://x/wide.jpg", tallImageUrl = "https://x/tall.jpg", owned = true, extra = mapOf("spaceId" to "space-sc"))
|
||||
val games = UbisoftLibrary.assemble(listOf(art), owned)
|
||||
val assets = "https://static3.cdn.ubi.com/orbit/uplay_launcher_3_0/assets/"
|
||||
val unlisted = games.first { it.id == "space-ac" }
|
||||
assertEquals("Assassin's Creed\u2122", unlisted.title)
|
||||
assertEquals(assets + "b4c1.jpg", unlisted.imageUrl)
|
||||
assertEquals(assets + "a3a6.jpg", unlisted.tallImageUrl)
|
||||
assertEquals("https://x/wide.jpg", games.first { it.id == "space-sc" }.imageUrl)
|
||||
assertNull(UbisoftLibrary.image("root:\n thumb_image: THUMBIMAGE\n", "thumb_image"))
|
||||
}
|
||||
|
||||
@Test fun withoutAnOwnershipAnswerTheProfileListStays() {
|
||||
val profile = listOf(listed("space-sc", "Splinter Cell"), listed("space-gone", "Free Weekend"))
|
||||
assertEquals(listOf("space-gone", "space-sc"), UbisoftLibrary.assemble(profile, JSONObject().put("error", "demux closed")).map { it.id })
|
||||
@@ -98,4 +116,74 @@ class UbisoftTest {
|
||||
assertArrayEquals(bytes, UbisoftActivation.unhex("00017fff802a"))
|
||||
assertNull(UbisoftActivation.unhex("abc"))
|
||||
}
|
||||
|
||||
@Test fun aSaveNamesItsUbisoftIdentifierInItsHeader() {
|
||||
val mark = "4ef5bf634b40daa577aaeaa52c2283a9"
|
||||
val save = byteArrayOf(0x24, 2, 0, 0, 0, 0, 0, 0) + mark.toByteArray() + ByteArray(64) { it.toByte() }
|
||||
assertEquals(mark, UbisoftCloud.mark(save))
|
||||
assertNull(UbisoftCloud.mark(ByteArray(8) + ByteArray(32) + ByteArray(16)))
|
||||
assertNull(UbisoftCloud.mark(ByteArray(39)))
|
||||
}
|
||||
|
||||
@Test fun cloudSaveBodiesSurviveTheZlibHop() {
|
||||
val save = ByteArray(200_000) { (it % 251).toByte() }
|
||||
assertArrayEquals(save, UbisoftCloud.inflate(UbisoftCloud.deflate(save)))
|
||||
assertEquals(0x78, UbisoftCloud.deflate(save)[0].toInt())
|
||||
val packed = UbisoftCloud.deflate(save)
|
||||
val cut = runCatching { UbisoftCloud.inflate(packed.copyOf(packed.size / 2)) }
|
||||
assertTrue(cut.isFailure)
|
||||
}
|
||||
|
||||
@Test fun aSlotVersionChangesWithItsSizeTimeOrIdentifier() {
|
||||
val a = UbisoftCloud.Slot(1, "1", "4ef5bf634b40daa577aaeaa52c2283a9", 2414, 1_689_224_156_000)
|
||||
assertEquals("2414:1689224156000:4ef5bf634b40daa577aaeaa52c2283a9", UbisoftCloud.version(a))
|
||||
assertTrue(UbisoftCloud.version(a) != UbisoftCloud.version(UbisoftCloud.Slot(1, "1", a.hash, 2414, a.modifiedMs + 1)))
|
||||
}
|
||||
|
||||
@Test fun aSlotCommitCountsOnlyWhenNoOtherSlotMovedAndOursLanded() {
|
||||
fun entity(revision: Int, vararg slots: Triple<String, String, Long>) = UbisoftCloud.Entity(JSONObject().put("revision", revision)
|
||||
.put("obj", JSONObject().put("slots", JSONArray().apply {
|
||||
for ((name, hash, size) in slots) put(JSONObject().put("filename", name).put("hash", hash).put("size", size).put("lastModified", "2026-01-01T00:00:00Z"))
|
||||
})))
|
||||
val a = "4ef5bf634b40daa577aaeaa52c2283a9"; val b = "0123456789abcdef0123456789abcdef"; val c = "fedcba9876543210fedcba9876543210"
|
||||
val before = entity(4, Triple("1", a, 10), Triple("2", b, 20))
|
||||
assertEquals(c, UbisoftCloudTransport.committedSlot(before, entity(5, Triple("1", c, 11), Triple("2", b, 20)), "1", c, 11)?.hash)
|
||||
assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", c, 11), Triple("2", a, 21)), "1", c, 11))
|
||||
assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", b, 30), Triple("2", b, 20)), "1", c, 11))
|
||||
assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", c, 11)), "1", c, 11))
|
||||
}
|
||||
|
||||
@Test fun aSlotTheCloudRewritesBeforeItIsVerifiedStaysUnsent() {
|
||||
val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) }
|
||||
val transport = UbisoftCloudTransport(slots, "u1")
|
||||
transport.list()
|
||||
slots.afterUpdate = { list -> list.getJSONObject(0).put("hash", UbisoftCloud.mark(MemorySlots.save("other device"))) }
|
||||
val changed = runCatching { transport.put(mapOf("1.save" to MemorySlots.save("a2"))) }.exceptionOrNull() as com.droiddeck.launcher.stores.CloudChanged
|
||||
assertTrue(changed.sent.isEmpty())
|
||||
assertEquals(listOf("1.save"), changed.unsent)
|
||||
assertNull(transport.committed("1.save"))
|
||||
}
|
||||
|
||||
@Test fun ubisoftCloudSavesAreSupported() {
|
||||
assertTrue(com.droiddeck.launcher.stores.CloudSaves.supports(Store.UBISOFT))
|
||||
assertTrue(!com.droiddeck.launcher.stores.CloudSaves.supports(Store.AMAZON))
|
||||
}
|
||||
|
||||
@Test fun keptGameTokensBelongToOneAccountAndProductUntilDropped() {
|
||||
val root = kotlin.io.path.createTempDirectory().toFile()
|
||||
val dir = File(root, "cache")
|
||||
val cache = UbisoftActivation.TokenCache(dir)
|
||||
assertNull(cache.get("u-1", 109))
|
||||
assertTrue(cache.put("u-1", 109, byteArrayOf(1, 2, 3)))
|
||||
assertArrayEquals(byteArrayOf(1, 2, 3), cache.get("u-1", 109))
|
||||
assertNull(cache.get("u-1", 82))
|
||||
assertNull(cache.get("u-2", 109))
|
||||
assertTrue(cache.put("../u-1", 82, byteArrayOf(4)))
|
||||
assertEquals(listOf("cache"), root.list()!!.toList())
|
||||
assertTrue(dir.listFiles()!!.all { it.parentFile == dir })
|
||||
assertTrue(cache.drop("u-1", 109))
|
||||
assertNull(cache.get("u-1", 109))
|
||||
assertTrue(cache.drop("u-1", 109))
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.junit.After
|
||||
@@ -75,4 +78,35 @@ class BottomScreenBarTest {
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.drawer_steam_menu)).assertDoesNotExist()
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.drawer_open_qam)).assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test fun thePanelNameOpensTheScreenPickerInsteadOfAMenuButton() {
|
||||
var menus = 0
|
||||
val picked = mutableListOf<SecondScreenMode>()
|
||||
val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL, SecondScreenMode.CUSTOM_CONTROLS)
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
BottomScreenBar(BottomBarModel("Trackpad", {}, { menus++ }, null, null,
|
||||
picker = ScreenPicker(modes, SecondScreenMode.KEYBOARD_TRACKPAD, { picked += it }, onMenu = { menus++ })))
|
||||
}
|
||||
}
|
||||
compose.onNodeWithTag("bottom-bar-menu").assertDoesNotExist()
|
||||
compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertExists()
|
||||
compose.onNodeWithTag("bottom-bar-screen").performClick()
|
||||
compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").performClick()
|
||||
compose.waitForIdle()
|
||||
assertEquals(listOf(SecondScreenMode.TERMINAL), picked)
|
||||
compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").assertDoesNotExist()
|
||||
compose.onNodeWithTag("bottom-bar-screen").performClick()
|
||||
compose.onNodeWithTag("screen-picker-menu").performClick()
|
||||
compose.waitForIdle()
|
||||
assertEquals(1, menus)
|
||||
}
|
||||
|
||||
@Test fun focusStartsOnTheMenuFromAPanelAndOnThePanelFromTheMenu() {
|
||||
val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)
|
||||
assertNull(ScreenPicker(modes, SecondScreenMode.TERMINAL, {}, onMenu = {}).focusTarget())
|
||||
assertEquals(SecondScreenMode.TERMINAL, ScreenPicker(modes, SecondScreenMode.TERMINAL, {}, onMenu = {}, menuShown = true).focusTarget())
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, ScreenPicker(modes, SecondScreenMode.NONE, {}, onMenu = {}, menuShown = true).focusTarget())
|
||||
assertEquals(SecondScreenMode.TERMINAL, ScreenPicker(modes, SecondScreenMode.TERMINAL, {}).focusTarget())
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CloudSaves
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
@@ -25,6 +26,15 @@ class CloudMessageTest {
|
||||
assertEquals(ctx.getString(R.string.cloud_not_synced), msg("failed", 0, 0, "SocketTimeoutException"))
|
||||
}
|
||||
|
||||
@Test fun aPartialSyncNamesTheSlotsItLeft() {
|
||||
fun partial(conflicts: Int, detail: String) = cloudMessage(ctx, CloudSaves.Result("partial", 0, 0L, "blocked-path", conflicts, detail))
|
||||
assertEquals(ctx.getString(R.string.cloud_partial, "outside the save folder: ../x.save"), partial(0, "outside the save folder: ../x.save"))
|
||||
assertEquals(ctx.getString(R.string.cloud_conflict_files_detail, 2, "changed locally: 1.save, 2.save"), partial(2, "changed locally: 1.save, 2.save"))
|
||||
assertTrue(partial(1, "changed locally: 1.save").contains("1.save"))
|
||||
assertEquals(ctx.getString(R.string.cloud_conflict_files, 1), partial(1, ""))
|
||||
assertEquals(ctx.getString(R.string.cloud_not_synced), partial(0, ""))
|
||||
}
|
||||
|
||||
@Test fun okResultsSayWhatHappened() {
|
||||
assertEquals(ctx.getString(R.string.cloud_up_to_date), msg("ok", 0, 0, "up-to-date"))
|
||||
assertEquals(ctx.getString(R.string.cloud_done, 3), msg("ok", 3, 0, "uploaded"))
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class LibraryColumnsTest {
|
||||
@Test fun everySizeStepChangesTheColumnCountUntilOne() {
|
||||
val phone = (0..4).map { libraryColumns(width = 1080, base = 450, gap = 30, level = it) }
|
||||
assertEquals(listOf(4, 3, 2, 1, 1), phone)
|
||||
val tablet = (0..4).map { libraryColumns(width = 2400, base = 450, gap = 30, level = it) }
|
||||
assertEquals(listOf(7, 6, 5, 4, 3), tablet)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,25 @@ class LibraryEntriesTest {
|
||||
assertEquals(listOf("steam", "xbox", "epic", "gog", "added"), librarySources(entries, listOf("xbox", "epic", "gog")))
|
||||
}
|
||||
|
||||
@Test fun theLibrarysOwnTabsSitAfterTheTabTheyFollow() {
|
||||
val entries = listOf("added", "gog", "steam", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) }
|
||||
val order = listOf("xbox", "epic", "gog")
|
||||
assertEquals(listOf("steam", "xbox", "added", "epic", "gog"), librarySources(entries, order, places = listOf("added" to "xbox")))
|
||||
assertEquals(listOf("added", "steam", "xbox", "epic", "gog"), librarySources(entries, order, places = listOf("added" to "", "favorites" to "added", "steam" to "favorites")))
|
||||
assertEquals(listOf("xbox", "epic", "steam", "gog", "added"), librarySources(entries, order, places = listOf("favorites" to "epic", "steam" to "favorites", "added" to "nope")))
|
||||
}
|
||||
|
||||
@Test fun hidingTheTabALibraryTabFollowsKeepsItInPlace() {
|
||||
val entries = listOf("added", "gog", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) }
|
||||
assertEquals(listOf("xbox", "added", "gog"), librarySources(entries, listOf("xbox", "epic", "gog"), places = listOf("added" to "epic"), offStores = setOf("epic")))
|
||||
}
|
||||
|
||||
@Test fun placesRoundTripThroughTheirOrder() {
|
||||
val order = listOf("epic", "steam", "favorites", "gog", "xbox", "added")
|
||||
assertEquals(order, placeLibraryTabs(listOf("epic", "gog", "xbox"), libraryPlacesOf(order)))
|
||||
assertEquals(listOf("favorites", "steam", "epic", "gog", "added"), placeLibraryTabs(listOf("epic", "gog"), emptyList()))
|
||||
}
|
||||
|
||||
@Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() {
|
||||
val entries = listOf("epic", "gog", "battlenet").map { LibraryEntry(it, it, it, null, null, false) }
|
||||
assertEquals(listOf("epic", "gog", "battlenet"), librarySources(entries, listOf("missing", "epic", "epic", "amazon")))
|
||||
|
||||
@@ -50,4 +50,9 @@ class LibraryFavoritesTest {
|
||||
assertEquals(listOf(LIBRARY_FAVORITES, "steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123")))
|
||||
assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:999")))
|
||||
}
|
||||
|
||||
@Test fun aHiddenFavoritesTabStaysHiddenWithHeartedGames() {
|
||||
val entries = listOf(steam(440, "Team Fortress 2"), owned("123", "Witcher"))
|
||||
assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"), offTabs = setOf(LIBRARY_FAVORITES)))
|
||||
}
|
||||
}
|
||||
@@ -30,10 +30,16 @@ class LibraryHiddenTest {
|
||||
assertFalse(inLibrarySource(LIBRARY_HIDDEN, cs, emptySet(), hidden))
|
||||
}
|
||||
|
||||
@Test fun theHiddenTabIsLastAndOnlyWhenEnabled() {
|
||||
@Test fun theHiddenTabIsLastAndOnlyWhenTurnedOn() {
|
||||
val entries = listOf(tf2, cs)
|
||||
assertEquals(listOf(Library.SOURCE_STEAM), librarySources(entries, emptyList(), hidden = hidden))
|
||||
assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, showHidden = true))
|
||||
assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, offTabs = emptySet()))
|
||||
}
|
||||
|
||||
@Test fun theHiddenTabSortsLastUnlessMoved() {
|
||||
assertEquals(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, "epic", Library.ADDED, LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic"), DEFAULT_LIBRARY_PLACES))
|
||||
val moved = placeLibraryTabs(listOf("epic"), listOf(LIBRARY_HIDDEN to "epic"))
|
||||
assertEquals(listOf("epic", LIBRARY_HIDDEN), moved.filter { it == "epic" || it == LIBRARY_HIDDEN })
|
||||
}
|
||||
|
||||
@Test fun aStoreTabWithOnlyHiddenGamesDisappears() {
|
||||
|
||||
@@ -76,52 +76,41 @@ class LibraryVisibilityTest {
|
||||
LibraryView.focusFirst = false
|
||||
}
|
||||
|
||||
@Test fun uninstalledGamesAreHiddenUntilSelectedInTheFilterAndTheChoiceSurvivesReopeningLibrary() {
|
||||
@Test fun uninstalledGamesStayFoldedUnderTheirRowAndTheChoiceSurvivesReopeningLibrary() {
|
||||
show()
|
||||
compose.onNodeWithText("Installed Steam game").assertExists()
|
||||
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
|
||||
chooseVisibility(true)
|
||||
compose.onNodeWithText("NOT INSTALLED · 2").assertExists()
|
||||
toggleNotInstalled(true)
|
||||
compose.onNodeWithText("Uninstalled GOG").assertExists()
|
||||
assertTrue(SessionPrefs.libraryShowUninstalled(ctx))
|
||||
compose.runOnIdle { generation++; Snapshot.sendApplyNotifications() }
|
||||
compose.mainClock.advanceTimeBy(2_000)
|
||||
compose.onNodeWithText("Uninstalled GOG").assertExists()
|
||||
chooseVisibility(false)
|
||||
toggleNotInstalled(false)
|
||||
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
|
||||
assertFalse(SessionPrefs.libraryShowUninstalled(ctx))
|
||||
}
|
||||
|
||||
@Test fun theFilterExpandsBesideSortWithoutChangingTheSelectionOnOpen() {
|
||||
@Test fun theNotInstalledRowReplacesTheFilterButtonAndSortStillOpens() {
|
||||
show()
|
||||
val filter = compose.onNodeWithContentDescription("Filter · Installed only")
|
||||
val sort = compose.onNodeWithContentDescription("Sort")
|
||||
assertTrue(filter.fetchSemanticsNode().boundsInRoot.right <= sort.fetchSemanticsNode().boundsInRoot.left)
|
||||
filter.performClick()
|
||||
compose.mainClock.advanceTimeBy(2_000)
|
||||
compose.onNodeWithText("Installed only").assertIsDisplayed()
|
||||
compose.onNodeWithText("All owned games").assertIsDisplayed()
|
||||
compose.onAllNodesWithText("Filter").assertCountEquals(1)
|
||||
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
|
||||
compose.onNodeWithContentDescription("Filter · Installed only").assertDoesNotExist()
|
||||
compose.onNodeWithTag("library-not-installed").assertExists()
|
||||
assertFalse(SessionPrefs.libraryShowUninstalled(ctx))
|
||||
compose.runOnIdle { Steps.fold(); Snapshot.sendApplyNotifications() }
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
sort.performClick()
|
||||
compose.onNodeWithContentDescription("Sort").performClick()
|
||||
compose.mainClock.advanceTimeBy(2_000)
|
||||
compose.onAllNodesWithText("Sort").assertCountEquals(1)
|
||||
compose.onNodeWithText("Recently played").assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test fun theXboxAccessChoicesShareTheLibraryFilter() {
|
||||
@Test fun theXboxFilterOnlyOffersTheXboxAccessChoices() {
|
||||
StoreAccounts.write(ctx, Store.XBOX, JSONObject().put("username", "Library test"))
|
||||
StoresState.accounts[Store.XBOX] = "Library test"
|
||||
StoresState.library[Store.XBOX] = listOf(CatalogItem(Store.XBOX, "owned", "Uninstalled Xbox", null, owned = true))
|
||||
LibraryView.source = Store.XBOX.id
|
||||
try {
|
||||
show()
|
||||
compose.onNodeWithContentDescription("Filter · Installed only").performClick()
|
||||
compose.onNodeWithContentDescription("Filter · All").performClick()
|
||||
compose.mainClock.advanceTimeBy(2_000)
|
||||
compose.onNodeWithText("Installed only").assertIsDisplayed()
|
||||
compose.onNodeWithText("All owned games").assertIsDisplayed()
|
||||
compose.onNodeWithText("Installed only").assertDoesNotExist()
|
||||
compose.onNodeWithText("Game Pass").assertIsDisplayed().performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
assertEquals(XboxLibraryFilter.GAME_PASS, XboxLibraryFilter.current)
|
||||
@@ -131,31 +120,64 @@ class LibraryVisibilityTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aSearchWithOnlyUninstalledMatchesOffersToRevealThem() {
|
||||
@Test fun aSearchWithOnlyUninstalledMatchesShowsTheFoldedRowToRevealThem() {
|
||||
LibraryView.query = "Uninstalled GOG"
|
||||
show()
|
||||
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
|
||||
compose.onNodeWithTag("library-browse-owned").performClick()
|
||||
compose.onNodeWithText("No installed games match these filters", substring = true).assertDoesNotExist()
|
||||
compose.onNodeWithTag("library-not-installed").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithText("Uninstalled GOG").assertExists()
|
||||
assertEquals("Uninstalled GOG", LibraryView.query)
|
||||
compose.onNodeWithTag("library-not-installed").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist()
|
||||
compose.onNodeWithTag("library-not-installed").assertExists()
|
||||
}
|
||||
|
||||
@Test fun aHiddenStoreRemainsReachableInLibraryInItsConfiguredOrder() {
|
||||
@Test fun aSwitchedOffStoreLeavesTheChipsButItsGamesStayUnderAll() {
|
||||
SessionPrefs.setStoresTabOrder(ctx, listOf("epic", "gog"))
|
||||
SessionPrefs.setStoresTabHidden(ctx, setOf("gog"))
|
||||
show()
|
||||
val steam = compose.onNodeWithTag("library-source-steam").fetchSemanticsNode().boundsInRoot.left
|
||||
val epic = compose.onNodeWithTag("library-source-epic").fetchSemanticsNode().boundsInRoot.left
|
||||
val gog = compose.onNodeWithTag("library-source-gog").fetchSemanticsNode().boundsInRoot.left
|
||||
assertTrue(steam < epic && epic < gog)
|
||||
compose.onNodeWithTag("library-source-gog").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithTag("library-browse-owned").assertIsDisplayed().performClick()
|
||||
assertTrue(steam < epic)
|
||||
compose.onNodeWithTag("library-source-gog").assertDoesNotExist()
|
||||
compose.onNodeWithTag("library-not-installed").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithText("Uninstalled GOG").assertExists()
|
||||
}
|
||||
|
||||
@Test fun anEmptyLibraryStillShowsItsChipsSoCustomGamesAndSignInAreReachable() {
|
||||
for (store in listOf(Store.GOG, Store.EPIC)) StoreAccounts.clear(ctx, store)
|
||||
StoresState.library.clear()
|
||||
StoresState.accounts.clear()
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) {
|
||||
FocusGlideHost { Box(Modifier.fillMaxSize()) {
|
||||
LibraryPage(state(emptyList()), actions(), "games", {}, Modifier.fillMaxSize())
|
||||
} }
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(2_000)
|
||||
compose.onNodeWithTag("library-source-added").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithTag("library-custom-empty").assertExists()
|
||||
}
|
||||
|
||||
@Test fun theCustomGamesTabIsAlwaysThereAndOffersToAddWhenEmpty() {
|
||||
show()
|
||||
compose.onNodeWithTag("library-source-added").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithTag("library-custom-empty").assertExists()
|
||||
compose.onNodeWithTag("library-custom-add").performClick()
|
||||
assertTrue(GamesDialogState.adding)
|
||||
GamesDialogState.adding = false
|
||||
}
|
||||
|
||||
@Test fun theStoresOwnedGamesLinkRevealsOwnedGamesDespiteTheSavedInstalledOnlyView() {
|
||||
assertFalse(SessionPrefs.libraryShowUninstalled(ctx))
|
||||
LibraryView.showOwned(ctx, Store.GOG)
|
||||
@@ -188,22 +210,17 @@ class LibraryVisibilityTest {
|
||||
compose.mainClock.advanceTimeBy(2_000)
|
||||
}
|
||||
|
||||
private fun chooseVisibility(show: Boolean) {
|
||||
compose.onNodeWithContentDescription("Filter · " + if (SessionPrefs.libraryShowUninstalled(ctx)) "All owned games" else "Installed only")
|
||||
.performClick()
|
||||
compose.mainClock.advanceTimeBy(2_000)
|
||||
assertTrue(Steps.open)
|
||||
compose.onNodeWithText(if (show) "All owned games" else "Installed only")
|
||||
.performClick()
|
||||
private fun toggleNotInstalled(show: Boolean) {
|
||||
compose.onNodeWithTag("library-not-installed").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
assertEquals(show, SessionPrefs.libraryShowUninstalled(ctx))
|
||||
}
|
||||
|
||||
private fun state() = FrontEndState(
|
||||
private fun state(games: List<Library.SteamGame> = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal"))) = FrontEndState(
|
||||
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
|
||||
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "",
|
||||
romsDir = null, logsEnabled = false,
|
||||
steamGames = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal")),
|
||||
steamGames = games,
|
||||
emulators = emptyList(), running = null,
|
||||
)
|
||||
|
||||
|
||||
@@ -76,9 +76,10 @@ class SecondScreenBarTest {
|
||||
return (0 until root.childCount).map { root.getChildAt(it) }
|
||||
}
|
||||
|
||||
@Test fun trackpadPanelHasTheBarWithTheKeyboardToggleState() {
|
||||
@Test fun trackpadPanelHasTheBarWithTheKeyboardToggleStateAndSwap() {
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
val panel = presentation()
|
||||
var swaps = 0
|
||||
val panel = presentation { swaps++ }
|
||||
try {
|
||||
panel.show()
|
||||
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
|
||||
@@ -89,11 +90,15 @@ class SecondScreenBarTest {
|
||||
assertEquals(context.getString(R.string.second_mode_keyboard_trackpad), bar.title)
|
||||
assertNotNull(bar.onClose); assertNotNull(bar.onMenu); assertNotNull(bar.onSteam); assertNotNull(bar.onQam)
|
||||
assertNull(bar.tabs)
|
||||
val keyboard = bar.extras.single()
|
||||
assertEquals(listOf("bottom-keyboard", "bottom-swap"), bar.extras.map { it.tag })
|
||||
val keyboard = bar.extras.first()
|
||||
assertEquals(context.getString(R.string.second_show_keyboard), keyboard.description)
|
||||
assertFalse(keyboard.active)
|
||||
bar.extras.last().onClick()
|
||||
assertEquals(1, swaps)
|
||||
assertEquals(listOf("bottom-keyboard", "bottom-swap"), panel.barModel(SecondScreenMode.TERMINAL)!!.extras.map { it.tag })
|
||||
ReflectionHelpers.getField<MutableState<Boolean>>(panel, "keyboardShown").value = true
|
||||
val shown = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.single()
|
||||
val shown = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.first()
|
||||
assertEquals(context.getString(R.string.second_hide_keyboard), shown.description)
|
||||
assertTrue(shown.active)
|
||||
} finally { panel.closeControls() }
|
||||
@@ -130,6 +135,8 @@ class SecondScreenBarTest {
|
||||
noSwap.show()
|
||||
noSwap.showMode(SecondScreenMode.DECK_CONTROLS)
|
||||
assertTrue(noSwap.barModel(SecondScreenMode.DECK_CONTROLS)!!.extras.isEmpty())
|
||||
assertEquals(listOf("bottom-keyboard"), noSwap.barModel(SecondScreenMode.TERMINAL)!!.extras.map { it.tag })
|
||||
assertEquals(listOf("bottom-keyboard"), noSwap.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.map { it.tag })
|
||||
} finally { noSwap.closeControls() }
|
||||
}
|
||||
|
||||
|
||||
@@ -4,33 +4,29 @@ import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SessionDrawerPageTest {
|
||||
@Test fun singleScreenNavigationStartsWithControllerAndSkipsSecondScreen() {
|
||||
val pages = sessionDrawerPages(false, hasAgent = false)
|
||||
@Test fun navigationStartsWithControllerAndGoesStraightToDisplay() {
|
||||
val pages = sessionDrawerPages(hasAgent = false)
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, pages.first())
|
||||
assertFalse(SessionDrawerPage.SECOND_SCREEN in pages)
|
||||
assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1))
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1))
|
||||
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
|
||||
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
|
||||
}
|
||||
|
||||
@Test fun connectedSecondaryDisplayAddsItsPageAfterControllerAndPreservesOtherPages() {
|
||||
val connected = sessionDrawerPages(true, hasAgent = false)
|
||||
assertEquals(SessionDrawerPage.SECOND_SCREEN, connected.step(SessionDrawerPage.CONTROLLER, 1))
|
||||
assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1))
|
||||
assertEquals(sessionDrawerPages(false, hasAgent = false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN })
|
||||
for (pages in listOf(connected, sessionDrawerPages(false, hasAgent = false))) {
|
||||
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
|
||||
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
|
||||
}
|
||||
@Test fun glassesAddTheirPageAfterController() {
|
||||
val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false)
|
||||
assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1))
|
||||
assertEquals(sessionDrawerPages(hasAgent = false), pages.filter { it != SessionDrawerPage.GLASSES })
|
||||
}
|
||||
|
||||
@Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() {
|
||||
val with = sessionDrawerPages(false, hasAgent = true)
|
||||
val with = sessionDrawerPages(hasAgent = true)
|
||||
assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1))
|
||||
assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(false, hasAgent = false))
|
||||
assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false))
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ class SessionSecondScreenTest {
|
||||
var selected = SecondScreenMode.CUSTOM_CONTROLS
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {},
|
||||
SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {},
|
||||
actions(true, listOf(SecondScreenDisplay(1, "Bottom screen")),
|
||||
onClose = { closes++ }, select = { selected = it }), docked = true)
|
||||
}
|
||||
@@ -90,18 +90,47 @@ class SessionSecondScreenTest {
|
||||
assertEquals(SecondScreenMode.CUSTOM_CONTROLS, selected)
|
||||
}
|
||||
|
||||
@Test fun desktopWithoutASecondDisplayFallsBackToController() {
|
||||
@Test fun desktopWithoutASecondDisplayHasNoScreenPicker() {
|
||||
SessionState.mode = SessionService.MODE_DESKTOP
|
||||
var page = SessionDrawerPage.SECOND_SCREEN
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, page, false, { page = it }, actions(false, emptyList()))
|
||||
SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(false, emptyList()))
|
||||
}
|
||||
}
|
||||
compose.runOnIdle { assertEquals(SessionDrawerPage.CONTROLLER, page) }
|
||||
compose.onNodeWithTag("drawer-screen-picker").assertDoesNotExist()
|
||||
compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test fun dockedMenuPickerReturnsToThePanelAndHasNoMenuButton() {
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
val selected = mutableListOf<SecondScreenMode>()
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {},
|
||||
actions(true, listOf(SecondScreenDisplay(1, "Bottom screen")), mode = SecondScreenMode.TERMINAL) { selected += it },
|
||||
docked = true)
|
||||
}
|
||||
}
|
||||
compose.onNodeWithTag("bottom-bar-menu").assertDoesNotExist()
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.screen_picker_description,
|
||||
context.getString(R.string.touch_droiddeck_menu))).performClick()
|
||||
compose.onNodeWithTag("screen-picker-menu").assertExists()
|
||||
compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").performClick()
|
||||
assertEquals(listOf(SecondScreenMode.TERMINAL), selected)
|
||||
}
|
||||
|
||||
@Test fun displayPageCarriesTheGameScreenAndDisplayChoices() {
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {},
|
||||
actions(true, listOf(SecondScreenDisplay(1, "Bottom screen"), SecondScreenDisplay(2, "Monitor")), gameSwap = true))
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText(context.getString(R.string.swap_game_screen)).performScrollTo().assertIsDisplayed()
|
||||
compose.onNodeWithText("Bottom screen").performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test fun provisionalBottomScreenPanelSettlesOnlyOnceTheSessionIsInFront() {
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
val previousMode = SessionState.secondScreenMode
|
||||
@@ -233,7 +262,7 @@ class SessionSecondScreenTest {
|
||||
state<Boolean>("drawerOpenState").value = true
|
||||
state<Boolean>("drawerControllerActive").value = true
|
||||
state<List<SecondScreenDisplay>>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen"))
|
||||
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN,
|
||||
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.DISPLAY,
|
||||
KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) {
|
||||
assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0,
|
||||
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)))
|
||||
@@ -311,14 +340,16 @@ class SessionSecondScreenTest {
|
||||
val displays = listOf(SecondScreenDisplay(1, "Bottom screen"))
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it })
|
||||
SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(steam, displays) { selected += it })
|
||||
}
|
||||
}
|
||||
val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL, SecondScreenMode.CUSTOM_CONTROLS)
|
||||
for (mode in modes) {
|
||||
compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick()
|
||||
compose.onNodeWithTag("drawer-screen-picker").performClick()
|
||||
compose.onNodeWithTag("screen-picker-menu").assertDoesNotExist()
|
||||
compose.onNodeWithTag("screen-picker:${SecondScreenMode.DECK_CONTROLS.id}").assertDoesNotExist()
|
||||
compose.onNodeWithTag("screen-picker:${mode.id}").assertIsDisplayed().performClick()
|
||||
}
|
||||
compose.onNodeWithText(context.getString(SecondScreenMode.DECK_CONTROLS.label)).assertDoesNotExist()
|
||||
assertEquals(modes, selected)
|
||||
}
|
||||
|
||||
@@ -330,7 +361,7 @@ class SessionSecondScreenTest {
|
||||
private fun actions(steam: Boolean, displays: List<SecondScreenDisplay>,
|
||||
micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {},
|
||||
desktop: Boolean = !steam, direct: Boolean = false, onInputSelection: (InputRole?) -> Unit = {},
|
||||
onClose: () -> Unit = {},
|
||||
onClose: () -> Unit = {}, mode: SecondScreenMode = SecondScreenMode.NONE, gameSwap: Boolean = false,
|
||||
select: (SecondScreenMode) -> Unit = {}) =
|
||||
DrawerActions(steam = steam, desktop = desktop, direct = direct, onInputSelection = onInputSelection,
|
||||
isHomeApp = false, androidApps = emptyList(), hudOn = false,
|
||||
@@ -338,7 +369,7 @@ class SessionSecondScreenTest {
|
||||
frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never",
|
||||
suspendPolicy = "auto", backActionsInverted = false,
|
||||
touchMode = "auto", touchAuto = "trackpad", fexPreset = "default",
|
||||
secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1,
|
||||
secondScreenMode = mode, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1, gameSwapAvailable = gameSwap,
|
||||
onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {},
|
||||
onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {},
|
||||
onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {},
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], application = android.app.Application::class)
|
||||
class StoreTabsStateTest {
|
||||
private val ctx get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun clear() {
|
||||
ctx.getSharedPreferences("session", 0).edit().clear().commit()
|
||||
StoreTabsState.load(ctx)
|
||||
}
|
||||
|
||||
@Test fun aReorderIsSavedForTheStoresTabAndTheLibrary() {
|
||||
val ids = StoreTabsState.tabs.map { it.store.id }
|
||||
val moved = listOf(ids[1], ids[0]) + ids.drop(2)
|
||||
StoreTabsState.reorder(ctx, moved)
|
||||
assertEquals(moved, StoreTabsState.tabs.map { it.store.id })
|
||||
StoreTabsState.load(ctx)
|
||||
assertEquals(moved, StoreTabsState.tabs.map { it.store.id })
|
||||
}
|
||||
|
||||
@Test fun hidingIsSavedButTheLastShownStoreStays() {
|
||||
assertTrue(StoreTabsState.setShown(ctx, Store.GOG, false))
|
||||
assertTrue(Store.GOG.id in SessionPrefs.storesTabHidden(ctx))
|
||||
for (tab in StoreTabsState.tabs.filter { it.shown }.dropLast(1)) StoreTabsState.setShown(ctx, tab.store, false)
|
||||
val last = StoreTabsState.tabs.single { it.shown }.store
|
||||
assertFalse(StoreTabsState.setShown(ctx, last, false))
|
||||
assertTrue(StoreTabsState.tabs.single { it.store == last }.shown)
|
||||
}
|
||||
|
||||
@Test fun theHiddenTabStartsOffAndItsSwitchSurvivesAReload() {
|
||||
assertTrue(LIBRARY_HIDDEN in StoreTabsState.libraryHidden)
|
||||
StoreTabsState.setLibraryShown(ctx, LIBRARY_HIDDEN, true)
|
||||
assertTrue(SessionPrefs.libraryShowHidden(ctx))
|
||||
StoreTabsState.load(ctx)
|
||||
assertFalse(LIBRARY_HIDDEN in StoreTabsState.libraryHidden)
|
||||
StoreTabsState.setLibraryShown(ctx, LIBRARY_FAVORITES, false)
|
||||
assertEquals(setOf(LIBRARY_FAVORITES), SessionPrefs.libraryTabsHidden(ctx))
|
||||
StoreTabsState.setLibraryShown(ctx, LIBRARY_HIDDEN, false)
|
||||
StoreTabsState.load(ctx)
|
||||
assertEquals(setOf(LIBRARY_FAVORITES, LIBRARY_HIDDEN), StoreTabsState.libraryHidden)
|
||||
}
|
||||
}
|
||||
@@ -188,4 +188,45 @@ class ThemeColorsTest {
|
||||
SessionPrefs.setTheme(app, Themes.TRUE_BLACK)
|
||||
assertEquals(Color(0xFFFF8800), Themes.current(app).primary)
|
||||
}
|
||||
|
||||
@Test fun customThemeRestoresIndependentColorsAndUsesASolidAccent() {
|
||||
val chosen = CustomThemeColors(
|
||||
background = 0xFF101112.toInt(),
|
||||
surface = 0xFF202122.toInt(),
|
||||
surfaceVariant = 0xFF303132.toInt(),
|
||||
line = 0xFF404142.toInt(),
|
||||
line2 = 0xFF505152.toInt(),
|
||||
onBackground = 0xFFF1F2F3.toInt(),
|
||||
onSurfaceVariant = 0xFFD1D2D3.toInt(),
|
||||
primary = 0xFF336699.toInt(),
|
||||
onPrimary = 0xFFFFFFFF.toInt(),
|
||||
signal = 0xFFFFAA00.toInt(),
|
||||
good = 0xFF00CC66.toInt(),
|
||||
error = 0xFFFF4433.toInt(),
|
||||
)
|
||||
|
||||
Themes.setCustomColors(app, CustomThemeColors())
|
||||
SessionPrefs.setCustomThemeColors(app, chosen)
|
||||
SessionPrefs.setTheme(app, Themes.CUSTOM)
|
||||
|
||||
assertEquals(chosen, SessionPrefs.customThemeColors(app))
|
||||
|
||||
val palette = Themes.current(app)
|
||||
assertEquals(Themes.CUSTOM, palette.id)
|
||||
assertEquals(Color(chosen.background), palette.background)
|
||||
assertEquals(Color(chosen.surface), palette.surface)
|
||||
assertEquals(Color(chosen.surfaceVariant), palette.surfaceVariant)
|
||||
assertEquals(Color(chosen.line), palette.line)
|
||||
assertEquals(Color(chosen.line2), palette.line2)
|
||||
assertEquals(Color(chosen.onBackground), palette.onBackground)
|
||||
assertEquals(Color(chosen.onSurfaceVariant), palette.onSurfaceVariant)
|
||||
assertEquals(Color(chosen.primary), palette.primary)
|
||||
assertEquals(Color(chosen.primary), palette.primary2)
|
||||
assertEquals(Color(chosen.onPrimary), palette.onPrimary)
|
||||
assertEquals(Color(chosen.signal), palette.signal)
|
||||
assertEquals(Color(chosen.good), palette.good)
|
||||
assertEquals(Color(chosen.error), palette.error)
|
||||
assertTrue(Themes.all.any { it.id == Themes.CUSTOM })
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user