mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +00:00
Merge upstream PC input and dual-screen updates
This commit is contained in:
commit
68b0396dfe
819 files changed
+43953
-6186
No files matched your search
@@ -0,0 +1,22 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import com.droiddeck.launcher.HomeApp.RecentsStep
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class HomeRecentsTest {
|
||||
@Test fun theLauncherHidesAVisibleTaskAndTakesItOver() {
|
||||
assertEquals(RecentsStep.HIDE, HomeApp.recentsStep(hidden = true, owned = false, excluded = false))
|
||||
}
|
||||
|
||||
@Test fun aTaskSomeoneElseExcludedIsNeverClaimedOrShown() {
|
||||
assertEquals(RecentsStep.NONE, HomeApp.recentsStep(hidden = true, owned = false, excluded = true))
|
||||
assertEquals(RecentsStep.NONE, HomeApp.recentsStep(hidden = false, owned = false, excluded = true))
|
||||
}
|
||||
|
||||
@Test fun onlyATaskTheLauncherHidItselfIsShownAgain() {
|
||||
assertEquals(RecentsStep.SHOW, HomeApp.recentsStep(hidden = false, owned = true, excluded = true))
|
||||
assertEquals(RecentsStep.FORGET, HomeApp.recentsStep(hidden = false, owned = true, excluded = false))
|
||||
assertEquals(RecentsStep.NONE, HomeApp.recentsStep(hidden = true, owned = true, excluded = true))
|
||||
}
|
||||
}
|
||||
@@ -181,6 +181,32 @@ class AgentSecurityTest {
|
||||
assertEquals(listOf("TEST=old", "STICKY=1"), AgentEnv.beginSession(context))
|
||||
}
|
||||
|
||||
@Test fun binaryOverridesPreserveTheRuntimeSearchPathForOneSession() {
|
||||
AgentAccess.setCommandsEnabled(context, true)
|
||||
File(AgentEnv.inbox(context).apply { mkdirs() }, "gamescope").writeText("test binary")
|
||||
AgentEnv.override(context, "gamescope")
|
||||
|
||||
val path = AgentEnv.beginSession(context).single { it.startsWith("PATH=") }.substringAfter('=')
|
||||
assertEquals("/opt/droiddeck-agent/bin:" + LinuxRuntime.GUEST_PATH, path)
|
||||
assertTrue(path.split(':').contains("/usr/games"))
|
||||
assertTrue(path.split(':').contains("/usr/sbin"))
|
||||
|
||||
AgentEnv.endSession(context)
|
||||
assertTrue(AgentEnv.beginSession(context).none { it.startsWith("PATH=") })
|
||||
}
|
||||
|
||||
@Test fun binaryOverridesKeepExplicitPathsAndPendingPathPrecedence() {
|
||||
AgentAccess.setCommandsEnabled(context, true)
|
||||
AgentEnv.set(context, listOf("PATH=/custom/persistent"), true)
|
||||
AgentEnv.set(context, listOf("PATH=/custom/next:/usr/games"), false)
|
||||
File(AgentEnv.inbox(context).apply { mkdirs() }, "gamescope").writeText("test binary")
|
||||
AgentEnv.override(context, "gamescope")
|
||||
|
||||
assertEquals("PATH=/opt/droiddeck-agent/bin:/custom/next:/usr/games", AgentEnv.beginSession(context).last())
|
||||
AgentEnv.endSession(context)
|
||||
assertEquals(listOf("PATH=/custom/persistent"), AgentEnv.beginSession(context))
|
||||
}
|
||||
|
||||
@Test fun fastPathLibraryIsValidatedAndSelectedForOneSession() {
|
||||
AgentAccess.setCommandsEnabled(context, true)
|
||||
val source = File(AgentEnv.inbox(context).apply { mkdirs() }, "libblfastpath.so")
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.droiddeck.launcher.audio
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DirectAudioTimingTest {
|
||||
@Test
|
||||
fun lowLatencyOutputKeepsTheDriverDefaults() {
|
||||
assertTrue(DirectAudioTiming.environment(lowLatencyOutput = true).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun outputWithoutLowLatencyGetsALongerPeriodAndBuffer() {
|
||||
assertEquals(listOf("AUDIO_DIRECT_PERIOD_MS=20", "AUDIO_DIRECT_MS=60"), DirectAudioTiming.environment(lowLatencyOutput = false))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@ package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -54,4 +57,35 @@ class AddonPackTest {
|
||||
installed("b".repeat(64))
|
||||
assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = false).installed(context))
|
||||
}
|
||||
|
||||
@Test fun localBuildInstallsTheBundledPackWithoutDownloading() {
|
||||
val archive = tarZst("tool" to "x")
|
||||
val pack = AddonPack("sample", Hashes.sha256(archive), archive.length(), listOf("tool"), bundle = { archive.inputStream() })
|
||||
|
||||
assertTrue(pack.await(context))
|
||||
assertEquals("x", pack.file(context, "tool").readText())
|
||||
}
|
||||
|
||||
@Test fun bundledPackWithTheWrongDigestIsRejected() {
|
||||
val archive = tarZst("tool" to "x")
|
||||
val pack = AddonPack("sample", "a".repeat(64), archive.length(), listOf("tool"),
|
||||
bundle = { archive.inputStream() })
|
||||
|
||||
val copy = File(context.cacheDir, "copy.tar.zst")
|
||||
|
||||
assertFalse(pack.bundled(context, copy))
|
||||
assertFalse(copy.exists())
|
||||
}
|
||||
|
||||
private fun tarZst(vararg files: Pair<String, String>): File =
|
||||
File(context.cacheDir, "sample-${System.nanoTime()}.tar.zst").apply {
|
||||
TarArchiveOutputStream(ZstdOutputStream(outputStream())).use { tar ->
|
||||
for ((path, text) in files) {
|
||||
val bytes = text.toByteArray()
|
||||
tar.putArchiveEntry(TarArchiveEntry(path).apply { size = bytes.size.toLong() })
|
||||
tar.write(bytes)
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,6 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* A download that was cut off keeps its bytes, and a second call with `resume` asks for the rest
|
||||
* with a Range header instead of starting again. The server is a plain socket so the first answer
|
||||
* can promise the whole file and then hang up halfway.
|
||||
*/
|
||||
class DownloaderResumeTest {
|
||||
private val data = ByteArray(300_000) { (it % 251).toByte() }
|
||||
private val cutAt = 100_000
|
||||
@@ -43,11 +38,9 @@ class DownloaderResumeTest {
|
||||
try {
|
||||
while (!server.isClosed) {
|
||||
val socket = server.accept()
|
||||
// the client may hang up on a body it refuses; that must not stop the server
|
||||
runCatching { handle(socket) }
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// closed by tearDown
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
}
|
||||
@@ -72,7 +65,6 @@ class DownloaderResumeTest {
|
||||
val content = if (corrupt && "/corrupt" in path) ByteArray(data.size) else data
|
||||
val from = range?.removePrefix("bytes=")?.substringBefore('-')?.toIntOrNull()
|
||||
if (misbehave) {
|
||||
// answers a Range request with a 206 that starts at 0, and serves plain requests whole
|
||||
val start = if (from == null) "200 OK" else "206 Partial Content"
|
||||
val extra = if (from == null) "" else "Content-Range: bytes 0-${data.size - 1}/${data.size}\r\n"
|
||||
out.write("HTTP/1.1 $start\r\n${extra}${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
@@ -89,7 +81,6 @@ class DownloaderResumeTest {
|
||||
out.write("HTTP/1.1 200 OK\r\n${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
out.write(content, 0, cutAt)
|
||||
out.flush()
|
||||
// hang up with most of the promised body still unsent
|
||||
} else {
|
||||
val rest = data.size - from
|
||||
out.write(("HTTP/1.1 206 Partial Content\r\nContent-Range: bytes $from-${data.size - 1}/${data.size}\r\n" +
|
||||
@@ -187,7 +178,6 @@ class DownloaderResumeTest {
|
||||
val target = File(dir, "runtime.tar.zst")
|
||||
misbehave = true
|
||||
val polls = java.util.concurrent.atomic.AtomicInteger()
|
||||
// candidate selection and attempt each check once before the request; later checks follow chunks
|
||||
val cancelled = java.util.function.BooleanSupplier { polls.incrementAndGet() > 2 }
|
||||
assertFalse(Downloader.downloadCandidates(first, listOf(first, second), target, true, null, cancelled, null))
|
||||
assertEquals("a cancel must not fall back to the next source", listOf<String?>(null), requests.toList())
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ComponentName
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.provider.Settings
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.droiddeck.launcher.input.HomeButtonService
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], application = Application::class)
|
||||
class SteamIntegrationShortcutsTest {
|
||||
private val context: Application = ApplicationProvider.getApplicationContext()
|
||||
private val service = ComponentName(context, HomeButtonService::class.java)
|
||||
|
||||
private fun listed() = context.packageManager.queryIntentServices(
|
||||
Intent("android.accessibilityservice.AccessibilityService").setPackage(context.packageName), 0,
|
||||
).any { ComponentName(it.serviceInfo.packageName, it.serviceInfo.name) == service }
|
||||
|
||||
private fun choose(value: String?) =
|
||||
Settings.Secure.putString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, value)
|
||||
|
||||
@Test fun theShortcutsServiceIsHiddenUntilChosen() {
|
||||
assertTrue(listed())
|
||||
assertFalse(SteamIntegration.shortcutsChosen(context))
|
||||
SteamIntegration.syncShortcutsListing(context)
|
||||
assertFalse(listed())
|
||||
assertEquals(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, context.packageManager.getComponentEnabledSetting(service))
|
||||
}
|
||||
|
||||
@Test fun anUpdateKeepsAServiceTheUserAlreadyTurnedOn() {
|
||||
choose(service.flattenToString())
|
||||
SteamIntegration.syncShortcutsListing(context)
|
||||
assertTrue(listed())
|
||||
assertTrue(SteamIntegration.shortcutsChosen(context))
|
||||
}
|
||||
|
||||
@Test fun openingShortcutSetupListsTheServiceAndBackingOutHidesItAgain() {
|
||||
SteamIntegration.setShortcutsListed(context, true)
|
||||
assertTrue(listed())
|
||||
SteamIntegration.syncShortcutsListing(context)
|
||||
assertFalse(listed())
|
||||
assertEquals(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, context.packageManager.getComponentEnabledSetting(service))
|
||||
}
|
||||
|
||||
@Test fun aChosenServiceStaysListed() {
|
||||
choose("other.app/.Reader:" + service.flattenToShortString())
|
||||
assertTrue(SteamIntegration.shortcutsChosen(context))
|
||||
SteamIntegration.syncShortcutsListing(context)
|
||||
assertTrue(listed())
|
||||
choose(service.flattenToString())
|
||||
assertTrue(SteamIntegration.shortcutsChosen(context))
|
||||
choose("other.app/.Reader")
|
||||
assertFalse(SteamIntegration.shortcutsChosen(context))
|
||||
SteamIntegration.syncShortcutsListing(context)
|
||||
assertFalse(listed())
|
||||
}
|
||||
|
||||
@Test fun anUpdateHidesAnUnchosenServiceWithoutOpeningDroidDeck() {
|
||||
val replaced = Intent(Intent.ACTION_MY_PACKAGE_REPLACED).setPackage(context.packageName)
|
||||
assertTrue(context.packageManager.queryBroadcastReceivers(replaced, 0)
|
||||
.any { it.activityInfo.name == ShortcutsListingReceiver::class.java.name })
|
||||
assertTrue(listed())
|
||||
ShortcutsListingReceiver().onReceive(context, replaced)
|
||||
assertFalse(listed())
|
||||
}
|
||||
|
||||
@Test fun anUpdateLeavesAChosenServiceListed() {
|
||||
choose(service.flattenToString())
|
||||
ShortcutsListingReceiver().onReceive(context, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))
|
||||
assertTrue(listed())
|
||||
assertTrue(SteamIntegration.shortcutsChosen(context))
|
||||
}
|
||||
|
||||
@Test fun otherBroadcastsChangeNothing() {
|
||||
ShortcutsListingReceiver().onReceive(context, Intent(Intent.ACTION_BOOT_COMPLETED))
|
||||
assertTrue(listed())
|
||||
}
|
||||
|
||||
@Test fun turningTheServiceOffInSettingsHidesItAtOnce() {
|
||||
choose(service.flattenToString())
|
||||
val running = org.robolectric.Robolectric.buildService(HomeButtonService::class.java).create().get()
|
||||
running.onUnbind(null)
|
||||
assertTrue(listed())
|
||||
choose("")
|
||||
running.onUnbind(null)
|
||||
assertFalse(listed())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class AllFilesAccessTest {
|
||||
@Test
|
||||
fun androidTenAndOlderNeverAsks() {
|
||||
assertFalse(AllFilesAccess.missing(sdk = 29) { false })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun androidElevenAsksUntilGranted() {
|
||||
assertTrue(AllFilesAccess.missing(sdk = 30) { false })
|
||||
assertFalse(AllFilesAccess.missing(sdk = 30) { true })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun newerAndroidAsksUntilGranted() {
|
||||
assertTrue(AllFilesAccess.missing(sdk = 35) { false })
|
||||
assertFalse(AllFilesAccess.missing(sdk = 35) { true })
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,19 @@ class AddedExesTest {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aGroupFolderWithFoldersHoldingNoGameStillListsEachGame() {
|
||||
val storage = visualNovels()
|
||||
val vns = File(storage, "VNs")
|
||||
File(vns, "steamapps/common").mkdirs()
|
||||
File(vns, "Notes/readme.txt").apply { parentFile!!.mkdirs(); writeText("x") }
|
||||
assertEquals(listOf("Albatross", "Angel Beats", "Rance 01", "Sayonara").map { File(vns, it).path },
|
||||
AddedGames.scan(app).map { it.folder.path })
|
||||
val pick = File(vns, "Rance 01/Rance01.exe")
|
||||
assertEquals(pick.parentFile!!.path, result(AddedGames.addExe(app, pick)).folder.path)
|
||||
assertEquals(4, AddedGames.scan(app).size)
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun anExePickedInAGroupFolderOnGameStorageIsItsOwnGame() {
|
||||
val storage = visualNovels()
|
||||
val vns = File(storage, "VNs")
|
||||
|
||||
@@ -24,12 +24,12 @@ class AddedGameArtFillTest {
|
||||
|
||||
private val coverBytes = byteArrayOf(9, 9, 9)
|
||||
|
||||
private fun game(name: String, appId: Long, cover: Boolean = true, source: String = Library.ADDED): AddedGames.Game {
|
||||
private fun game(name: String, appId: Long, cover: Boolean = true, source: String = Library.ADDED, storeId: String? = null): AddedGames.Game {
|
||||
val dir = tmp.newFolder(name)
|
||||
File(dir, "steam_appid.txt").writeText("504230")
|
||||
if (cover) File(dir, "cover.jpg").writeBytes(coverBytes)
|
||||
val exe = File(dir, "$name.exe").apply { writeText("x") }
|
||||
return AddedGames.Game(dir, name, exe, "/g/$name.exe", "/g", appId, appId, emptyList(), source = source)
|
||||
return AddedGames.Game(dir, name, exe, "/g/$name.exe", "/g", appId, appId, emptyList(), source = source, storeId = storeId)
|
||||
}
|
||||
|
||||
private class Calls {
|
||||
@@ -154,6 +154,121 @@ class AddedGameArtFillTest {
|
||||
assertFalse(File(AddedGameArt.cacheDir(app, second), AddedGameArt.EXTRAS_TRIED).exists())
|
||||
}
|
||||
|
||||
private fun steamFrom(asked: MutableList<String>, bytes: Byte, search: Int? = null, slotsAsked: MutableList<Set<Slot>> = ArrayList()) = AddedGameArt.Sources(
|
||||
storeLogo = { false },
|
||||
steamSearch = { if (search == null) fail("searched although the game names its appid"); search },
|
||||
steam = { id, cache, slots ->
|
||||
asked += id
|
||||
slotsAsked += slots
|
||||
slots.forEach { File(cache, steamNames.getValue(it)).writeBytes(byteArrayOf(bytes)) }
|
||||
slots.isNotEmpty()
|
||||
},
|
||||
sgdbGame = { _, _, _ -> null },
|
||||
sgdb = { _, _, _, _ -> false },
|
||||
)
|
||||
|
||||
@Test fun nameMatchedBattleNetArtIsForgottenOnce() {
|
||||
val game = game("World of Warcraft: Forever", 9001, source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = "wow_forever")
|
||||
val cache = AddedGameArt.cacheDir(app, game).apply { mkdirs() }
|
||||
File(cache, "logo.png").writeBytes(byteArrayOf(1))
|
||||
File(cache, "p.jpg").writeBytes(byteArrayOf(3))
|
||||
File(cache, "sgdb-id").writeText("5")
|
||||
assertTrue(AddedGameArt.forgetNameMatchedBattleNetArt(app, game))
|
||||
assertFalse(File(cache, "logo.png").isFile)
|
||||
assertTrue(File(cache, "p.jpg").isFile)
|
||||
assertFalse(File(cache, "sgdb-id").isFile)
|
||||
File(cache, "logo.png").writeBytes(byteArrayOf(2))
|
||||
assertFalse(AddedGameArt.forgetNameMatchedBattleNetArt(app, game))
|
||||
assertTrue(File(cache, "logo.png").isFile)
|
||||
}
|
||||
|
||||
@Test fun battleNetArtFoundByItsSteamIdIsKept() {
|
||||
val game = game("Call of Duty: Modern Warfare III", 9002, source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = "pinta")
|
||||
val cache = AddedGameArt.cacheDir(app, game).apply { mkdirs() }
|
||||
File(cache, "logo.png").writeBytes(byteArrayOf(1))
|
||||
assertFalse(AddedGameArt.forgetNameMatchedBattleNetArt(app, game))
|
||||
assertTrue(File(cache, "logo.png").isFile)
|
||||
}
|
||||
|
||||
@Test fun artOfTheAppTheFilesNamedBeforeIsFetchedAgain() {
|
||||
val g = game("Peak", 0x8100000AL, cover = false)
|
||||
File(g.folder, "steam_appid.txt").writeText("1029210")
|
||||
val asked = ArrayList<String>()
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 1)))
|
||||
File(g.folder, "steam_appid.txt").writeText("3527290")
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2)))
|
||||
assertEquals(listOf("1029210", "3527290"), asked)
|
||||
assertArrayEquals(byteArrayOf(2), File(AddedGameArt.cacheDir(app, g), "p.jpg").readBytes())
|
||||
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 3)))
|
||||
assertEquals(2, asked.size)
|
||||
}
|
||||
|
||||
@Test fun aPictureTheUserChoseOutlivesTheChange() {
|
||||
val g = game("Peak", 0x8100000BL, cover = false)
|
||||
File(g.folder, "steam_appid.txt").writeText("1029210")
|
||||
AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(ArrayList(), 1))
|
||||
val picked = File(tmp.root, "mine.jpg").apply { writeBytes(byteArrayOf(7)) }
|
||||
assertTrue(AddedGameArt.store(AddedGameArt.cacheDir(app, g), Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
|
||||
File(g.folder, "steam_appid.txt").writeText("3527290")
|
||||
val asked = ArrayList<String>()
|
||||
val slots = ArrayList<Set<Slot>>()
|
||||
AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2, slotsAsked = slots))
|
||||
assertArrayEquals(byteArrayOf(7), AddedGameArt.resolve(app, g).portrait!!.readBytes())
|
||||
assertEquals(listOf("3527290"), asked)
|
||||
assertEquals(listOf(setOf(Slot.WIDE, Slot.BACKGROUND, Slot.LOGO)), slots)
|
||||
val cache = AddedGameArt.cacheDir(app, g)
|
||||
assertArrayEquals(byteArrayOf(2), File(cache, "header.jpg").readBytes())
|
||||
assertArrayEquals(byteArrayOf(2), File(cache, "hero.jpg").readBytes())
|
||||
assertFalse(File(cache, AddedGameArt.REFETCH).exists())
|
||||
}
|
||||
|
||||
private fun olderBuildsArt(g: AddedGames.Game, marker: String): File = AddedGameArt.cacheDir(app, g).apply {
|
||||
mkdirs()
|
||||
File(this, "steam-appid").writeText(marker)
|
||||
steamNames.values.forEach { File(this, it).writeBytes(byteArrayOf(1)) }
|
||||
}
|
||||
|
||||
@Test fun anOlderBuildsSpacewarMarkerGoesWithItsArt() {
|
||||
val g = game("Peak", 0x8100000DL, cover = false)
|
||||
File(g.folder, "steam_appid.txt").writeText("480")
|
||||
val cache = olderBuildsArt(g, "480")
|
||||
val asked = ArrayList<String>()
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2, search = 3527290)))
|
||||
assertEquals(listOf("3527290"), asked)
|
||||
assertArrayEquals(byteArrayOf(2), File(cache, "p.jpg").readBytes())
|
||||
assertFalse(File(cache, "steam-appid").exists())
|
||||
}
|
||||
|
||||
@Test fun anOlderBuildsMatchStaysWhileTheFilesNameNoApp() {
|
||||
val g = game("Hades", 0x8100000EL, cover = false)
|
||||
File(g.folder, "steam_appid.txt").delete()
|
||||
val cache = olderBuildsArt(g, "1145360")
|
||||
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(ArrayList(), 2)))
|
||||
assertEquals("1145360", File(cache, "steam-appid").readText())
|
||||
assertArrayEquals(byteArrayOf(1), File(cache, "p.jpg").readBytes())
|
||||
}
|
||||
|
||||
@Test fun anOlderBuildsMatchGivesWayToTheAppTheFilesName() {
|
||||
val g = game("Peak", 0x8100000FL, cover = false)
|
||||
File(g.folder, "steam_appid.txt").writeText("3527290")
|
||||
val cache = olderBuildsArt(g, "1029210")
|
||||
val asked = ArrayList<String>()
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2)))
|
||||
assertEquals(listOf("3527290"), asked)
|
||||
assertArrayEquals(byteArrayOf(2), File(cache, "p.jpg").readBytes())
|
||||
assertFalse(File(cache, "steam-appid").exists())
|
||||
}
|
||||
|
||||
@Test fun filesThatStopNamingAnAppFallBackToTheGamesName() {
|
||||
val g = game("Peak", 0x8100000CL, cover = false)
|
||||
File(g.folder, "steam_appid.txt").writeText("1029210")
|
||||
val asked = ArrayList<String>()
|
||||
AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 1))
|
||||
File(g.folder, "steam_appid.txt").writeText("480")
|
||||
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2, search = 3527290)))
|
||||
assertEquals(listOf("1029210", "3527290"), asked)
|
||||
}
|
||||
|
||||
@Test fun nothingIsFetchedWhenArtIsOff() {
|
||||
SessionPrefs.setAddedGamesArt(app, false)
|
||||
val calls = Calls()
|
||||
|
||||
@@ -66,6 +66,29 @@ class AddedGameArtLookupTest {
|
||||
assertEquals(SteamMatch.Certainty.NAME, match.certainty)
|
||||
}
|
||||
|
||||
@Test fun anEarlierBuildsSpacewarLookupIsNotAMatch() {
|
||||
val dir = tmp.newFolder("Peak")
|
||||
val exe = File(dir, "PEAK.exe").apply { writeText("x") }
|
||||
val legacy = File(tmp.newFolder(), "steam-appid").apply { writeText("480") }
|
||||
assertEquals(3527290, SteamMatch.resolve(app, dir.path, exe, "PEAK", legacy = legacy) { 3527290 }.appId)
|
||||
}
|
||||
|
||||
@Test fun aSavedSpacewarMatchIsNotAMatch() {
|
||||
val dir = tmp.newFolder("Peak")
|
||||
val exe = File(dir, "PEAK.exe").apply { writeText("x") }
|
||||
SteamMatch.put(app, dir.path, SteamMatch.Match(480, SteamMatch.Certainty.NAME, "store search", System.currentTimeMillis()))
|
||||
assertNull(SteamMatch.resolve(app, dir.path, exe, "PEAK").appId)
|
||||
assertEquals(3527290, SteamMatch.resolve(app, dir.path, exe, "PEAK") { 3527290 }.appId)
|
||||
}
|
||||
|
||||
@Test fun aStoreSearchAnsweringSpacewarIsNoMatch() {
|
||||
val dir = tmp.newFolder("Spacewar Fan Remake")
|
||||
val exe = File(dir, "game.exe").apply { writeText("x") }
|
||||
val match = SteamMatch.resolve(app, dir.path, exe, "Spacewar Fan Remake") { 480 }
|
||||
assertNull(match.appId)
|
||||
assertEquals(SteamMatch.Certainty.NONE, match.certainty)
|
||||
}
|
||||
|
||||
@Test fun aStoreResultIsTakenOnlyWhenItsNameMatches() {
|
||||
assertNull(AddedGameArt.pickStoreResult("My Obscure Game", listOf("10" to "Totally Different", "11" to "Another One")))
|
||||
assertEquals("20", AddedGameArt.pickStoreResult("Hades", listOf("19" to "Hades II Soundtrack Bundle Extra", "20" to "Hades")))
|
||||
@@ -172,4 +195,9 @@ class AddedGameArtLookupTest {
|
||||
assertEquals("grids/game/5?dimensions=600x900&nsfw=false&humor=false", SteamGridDb.path(5, AddedGameArt.Slot.COVER))
|
||||
assertEquals("grids/game/5?dimensions=460x215,920x430&nsfw=false&humor=false", SteamGridDb.path(5, AddedGameArt.Slot.WIDE))
|
||||
}
|
||||
|
||||
@Test fun anExactLookupDoesNotTakeTheBaseGameForASubtitledOne() {
|
||||
assertNull(SteamGridDb.exactMatch("World of Warcraft: Forever", listOf(1 to "World of Warcraft")))
|
||||
assertEquals(2, SteamGridDb.exactMatch("World of Warcraft: Forever", listOf(1 to "World of Warcraft", 2 to "World of Warcraft: Forever")))
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,12 @@ import org.robolectric.annotation.Config
|
||||
class AddedGamesStoreScanTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
private fun install(store: Store, id: String, title: String, exe: String, launcher: Boolean = false): File {
|
||||
private fun install(store: Store, id: String, title: String, exe: String, launcher: Boolean = false, workdir: String? = null): File {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.installRoot(app), store), StoreInstallRoot.folderName(title, id))
|
||||
File(folder, exe).apply { parentFile!!.mkdirs(); writeText("game") }
|
||||
File(folder, "unins000.exe").writeText("uninstaller")
|
||||
var sidecar = StoreGameSidecar(store, id, title, exe, args = if (launcher) listOf("-EpicPortal") else emptyList())
|
||||
var sidecar = StoreGameSidecar(store, id, title, exe, workdir = workdir, args = if (launcher) listOf("-EpicPortal") else emptyList())
|
||||
if (launcher) sidecar = StoreLaunch.writeLauncher(folder, sidecar)
|
||||
sidecar.write(folder)
|
||||
return folder
|
||||
@@ -81,4 +81,39 @@ class AddedGamesStoreScanTest {
|
||||
assertTrue(listing.contains(StoreLaunch.LAUNCHER))
|
||||
assertTrue(listing.contains("\"store\":\"${Store.EPIC.id}\""))
|
||||
}
|
||||
|
||||
// GOG runs a task from its declared working directory; the install root when it declares none.
|
||||
@Test fun aTaskWorkingDirectoryBecomesTheShortcutsStartIn() {
|
||||
val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "System")
|
||||
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
|
||||
assertTrue(game.guestDir.endsWith("/Witcher Game/System"))
|
||||
}
|
||||
|
||||
@Test fun anEmptyTaskWorkingDirectoryIsTheGameFolder() {
|
||||
val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "")
|
||||
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
|
||||
assertEquals("/root/Games/Stores/GOG/Witcher Game", game.guestDir)
|
||||
}
|
||||
|
||||
@Test fun aSidecarWithoutATaskDirectoryStillStartsInTheExeFolder() {
|
||||
val folder = install(Store.GOG, "7", "Old Game", "bin/old.exe")
|
||||
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
|
||||
assertTrue(game.guestDir.endsWith("/Old Game/bin"))
|
||||
}
|
||||
|
||||
// A picked exe that is not the store's own keeps its own folder, not the task directory.
|
||||
@Test fun aPickedExeOnAGogGameStartsInItsOwnFolder() {
|
||||
val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "")
|
||||
val tool = File(folder, "Tools/Editor.exe").apply { parentFile!!.mkdirs(); writeText("tool") }
|
||||
AddedExes.put(app, AddedExes.Entry(folder.path, tool.path, picked = true))
|
||||
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
|
||||
assertTrue(game.guestDir.endsWith("/Witcher Game/Tools"))
|
||||
}
|
||||
|
||||
@Test fun pickingTheStoresOwnExeKeepsTheTaskDirectory() {
|
||||
val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "")
|
||||
AddedExes.put(app, AddedExes.Entry(folder.path, File(folder, "System/witcher.exe").path, picked = true))
|
||||
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
|
||||
assertEquals("/root/Games/Stores/GOG/Witcher Game", game.guestDir)
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,25 @@ class GameIdentifierTest {
|
||||
fun steamAppIdTxt_inSteamSettingsSubdir_isFound() {
|
||||
val dir = tmp.newFolder("Game")
|
||||
File(dir, "steam_settings").mkdirs()
|
||||
File(dir, "steam_settings/steam_appid.txt").writeText("480")
|
||||
assertEquals(480, GameIdentifier.identify(exeIn(dir)).appId)
|
||||
File(dir, "steam_settings/steam_appid.txt").writeText("3527290")
|
||||
assertEquals(3527290, GameIdentifier.identify(exeIn(dir)).appId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spacewarAppId_namesNoGame() {
|
||||
val dir = tmp.newFolder("PEAK")
|
||||
File(dir, "steam_appid.txt").writeText("480")
|
||||
File(dir, "steam_emu.ini").writeText("[Settings]\nAppId=480\n")
|
||||
assertNull(GameIdentifier.identify(exeIn(dir)).appId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spacewarAppId_fallsThroughToTheGamesOwnId() {
|
||||
val dir = tmp.newFolder("PEAK")
|
||||
File(dir, "steam_appid.txt").writeText("480")
|
||||
File(dir, "steam_settings").mkdirs()
|
||||
File(dir, "steam_settings/steam_appid.txt").writeText("3527290")
|
||||
assertEquals(3527290, GameIdentifier.identify(exeIn(dir)).appId)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -44,6 +61,30 @@ class GameIdentifierTest {
|
||||
assertEquals(GameIdentifier.Source.STEAM_EMU_INI, id.source)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spacewarManifest_namesNoGame() {
|
||||
val steamapps = tmp.newFolder("steamapps")
|
||||
File(steamapps, "appmanifest_480.acf").writeText(""""AppState" { "appid" "480" "name" "Spacewar" "installdir" "PEAK" }""")
|
||||
val game = File(steamapps, "common/PEAK").apply { mkdirs() }
|
||||
File(game, "steam_appid.txt").writeText("3527290")
|
||||
val id = GameIdentifier.identify(exeIn(game, "PEAK.exe"))
|
||||
assertEquals(3527290, id.appId)
|
||||
assertEquals(GameIdentifier.Source.STEAM_APPID_TXT, id.source)
|
||||
assertTrue(id.name != "Spacewar")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spacewarManifest_leavesTheGamesOwnManifestForTheSameFolder() {
|
||||
val steamapps = tmp.newFolder("steamapps")
|
||||
File(steamapps, "appmanifest_480.acf").writeText(""""AppState" { "appid" "480" "name" "Spacewar" "installdir" "PEAK" }""")
|
||||
File(steamapps, "appmanifest_3527290.acf").writeText(""""AppState" { "appid" "3527290" "name" "PEAK" "installdir" "PEAK" }""")
|
||||
val game = File(steamapps, "common/PEAK").apply { mkdirs() }
|
||||
val id = GameIdentifier.identify(exeIn(game, "PEAK.exe"))
|
||||
assertEquals(3527290, id.appId)
|
||||
assertEquals("PEAK", id.name)
|
||||
assertEquals(GameIdentifier.Source.STEAM_MANIFEST_ACF, id.source)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun steamManifestAcf_matchedByInstalldir_givesAppIdAndName() {
|
||||
val steamapps = tmp.newFolder("steamapps")
|
||||
|
||||
@@ -67,6 +67,105 @@ class GamesFolderMigrationTest {
|
||||
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aFolderOfGamesInAnOldGamesFolderBecomesOneEntryPerGame() {
|
||||
val pc = tmp.newFolder("PC")
|
||||
val rance = File(pc, "VNs/Rance 01"); exe(pc, "VNs/Rance 01/Rance01.exe")
|
||||
val albatross = File(pc, "VNs/Albatross"); exe(pc, "VNs/Albatross/Albatross Log.exe")
|
||||
File(pc, "VNs/steamapps").mkdirs()
|
||||
val solo = File(pc, "Solo"); exe(pc, "Solo/Solo.exe")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
|
||||
GamesFolderMigration.run(app)
|
||||
assertEquals(setOf(albatross.path, rance.path, solo.path), AddedExes.list(app).map { it.folder }.toSet())
|
||||
assertEquals(setOf(albatross.path, rance.path, solo.path), AddedGames.scan(app).map { it.folder.path }.toSet())
|
||||
}
|
||||
|
||||
@Test fun aRemovedOrAlreadyAddedFolderOfGamesKeepsItsState() {
|
||||
val pc = tmp.newFolder("PC")
|
||||
val gone = File(pc, "Gone"); exe(pc, "Gone/A/a.exe"); exe(pc, "Gone/B/b.exe")
|
||||
val kept = File(pc, "Kept"); val keptExe = exe(pc, "Kept/A/a.exe"); exe(pc, "Kept/B/b.exe")
|
||||
val store = File(pc, "Store"); exe(pc, "Store/Content/game.exe"); exe(pc, "Store/Tools/tool.exe")
|
||||
StoreGameSidecar.file(store).writeText("""{"store":"gog","id":"2","title":"Store Game","exe":"Content/game.exe"}""")
|
||||
val solo = File(pc, "Solo"); exe(pc, "Solo/Extras/viewer.exe"); exe(pc, "Solo/Content/solo.exe")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
|
||||
SessionPrefs.setAddedGameRemoved(app, gone.path, true)
|
||||
AddedExes.put(app, AddedExes.Entry(kept.path, keptExe.path))
|
||||
GamesFolderMigration.run(app)
|
||||
val entries = AddedExes.list(app).map { it.folder }.toSet()
|
||||
assertEquals(setOf(File(gone, "A").path, File(gone, "B").path, kept.path, solo.path), entries)
|
||||
assertTrue(SessionPrefs.removedAddedGames(app).containsAll(listOf(File(gone, "A").path, File(gone, "B").path)))
|
||||
assertEquals(setOf(kept.path, solo.path), AddedGames.scan(app).map { it.folder.path }.toSet())
|
||||
}
|
||||
|
||||
@Test fun aGameSelectedOutsideTheRankedFoldersStaysListed() {
|
||||
val pc = tmp.newFolder("PC")
|
||||
val vns = File(pc, "VNs")
|
||||
exe(pc, "VNs/A/a.exe"); exe(pc, "VNs/B/b.exe")
|
||||
val pick = exe(pc, "VNs/C/helper.exe")
|
||||
val loose = File(pc, "Loose"); exe(pc, "Loose/A/a.exe"); exe(pc, "Loose/B/b.exe")
|
||||
val loosePick = exe(pc, "Loose/setup.exe")
|
||||
val lib = File(pc, "Lib"); exe(pc, "Lib/A/a.exe"); exe(pc, "Lib/B/b.exe")
|
||||
val libPick = exe(pc, "Lib/steamapps/common/Tool/helper.exe")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
|
||||
SessionPrefs.setAddedGameExe(app, vns.path, pick.path)
|
||||
SessionPrefs.setAddedGameExe(app, loose.path, loosePick.path)
|
||||
SessionPrefs.setAddedGameExe(app, lib.path, libPick.path)
|
||||
GamesFolderMigration.run(app)
|
||||
val entries = AddedExes.list(app).associateBy { it.folder }
|
||||
assertEquals(setOf(File(vns, "A").path, File(vns, "B").path, File(vns, "C").path, loose.path, lib.path), entries.keys)
|
||||
assertEquals(libPick.path, entries.getValue(lib.path).exe)
|
||||
assertEquals(pick.path, entries.getValue(File(vns, "C").path).exe)
|
||||
assertTrue(entries.getValue(File(vns, "C").path).picked)
|
||||
assertEquals(loosePick.path, entries.getValue(loose.path).exe)
|
||||
val games = AddedGames.scan(app).associateBy { it.folder.path }
|
||||
assertEquals(pick.path, games.getValue(File(vns, "C").path).exe.path)
|
||||
assertEquals(loosePick.path, games.getValue(loose.path).exe.path)
|
||||
}
|
||||
|
||||
@Test fun aSplitFolderHandsItsSettingsToTheGameItLaunched() {
|
||||
val pc = tmp.newFolder("PC")
|
||||
val vns = File(pc, "VNs")
|
||||
exe(pc, "VNs/Albatross/Albatross.exe")
|
||||
val pick = exe(pc, "VNs/Rance 01/Rance01.exe")
|
||||
File(pc, "VNs/Notes").mkdirs()
|
||||
val plain = File(pc, "Plain"); exe(pc, "Plain/A/a.exe"); exe(pc, "Plain/B/b.exe")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
|
||||
SessionPrefs.setAddedGameExe(app, vns.path, pick.path)
|
||||
SessionPrefs.addedGameAppId(app, vns.path, 0x8111_2222L)
|
||||
SessionPrefs.setAddedGameName(app, vns.path, "Rance")
|
||||
SessionPrefs.setAddedGameLaunch(app, vns.path, "-windowed")
|
||||
SessionPrefs.setAddedGameName(app, File(vns, "Rance 01").path, "Rance 01 Remake")
|
||||
SessionPrefs.addedGameAppId(app, plain.path, 0x8333_4444L)
|
||||
GamesFolderMigration.run(app)
|
||||
val rance = File(vns, "Rance 01").path
|
||||
val games = AddedGames.scan(app).associateBy { it.folder.path }
|
||||
assertEquals(0x8111_2222L, games.getValue(rance).appId)
|
||||
assertEquals("Rance 01 Remake", games.getValue(rance).name)
|
||||
assertEquals("-windowed", games.getValue(rance).launchOptions)
|
||||
assertEquals(pick.path, games.getValue(rance).exe.path)
|
||||
assertTrue(games.getValue(File(vns, "Albatross").path).appId != 0x8111_2222L)
|
||||
assertEquals("", SessionPrefs.addedGameLaunch(app, File(vns, "Albatross").path))
|
||||
assertEquals(0x8333_4444L, games.getValue(File(plain, "A").path).appId)
|
||||
assertTrue(games.getValue(File(plain, "B").path).appId != 0x8333_4444L)
|
||||
}
|
||||
|
||||
@Test fun aSplitFolderKeepsTheExeItLaunchedWithoutAPick() {
|
||||
val pc = tmp.newFolder("PC")
|
||||
val vns = File(pc, "VNs")
|
||||
val launched = exe(pc, "VNs/Rance/VNsPlayer.exe"); exe(pc, "VNs/Rance/Rance.exe")
|
||||
val other = exe(pc, "VNs/Other/Other.exe")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
|
||||
SessionPrefs.addedGameAppId(app, vns.path, 0x8555_6666L)
|
||||
GamesFolderMigration.run(app)
|
||||
val entries = AddedExes.list(app).associateBy { it.folder }
|
||||
assertEquals(launched.path, entries.getValue(File(vns, "Rance").path).exe)
|
||||
assertTrue(entries.getValue(File(vns, "Rance").path).picked)
|
||||
assertFalse(entries.getValue(File(vns, "Other").path).picked)
|
||||
val games = AddedGames.scan(app).associateBy { it.folder.path }
|
||||
assertEquals(launched.path, games.getValue(File(vns, "Rance").path).exe.path)
|
||||
assertEquals(0x8555_6666L, games.getValue(File(vns, "Rance").path).appId)
|
||||
assertEquals(other.path, games.getValue(File(vns, "Other").path).exe.path)
|
||||
}
|
||||
|
||||
@Test fun runningAgainChangesNothing() {
|
||||
val pc = tmp.newFolder("PC")
|
||||
exe(pc, "Alpha/Alpha.exe")
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class SteamLaunchOptionsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun config(apps: String) = listOf(
|
||||
"\"UserLocalConfigStore\"", "{", "\t\"Software\"", "\t{", "\t\t\"Valve\"", "\t\t{", "\t\t\t\"Steam\"", "\t\t\t{",
|
||||
apps, "\t\t\t}", "\t\t}", "\t}", "\t\"WebStorage\"", "\t{", "\t\t\"x\"\t\t\"1\"", "\t}", "}", "",
|
||||
).joinToString("\n")
|
||||
|
||||
private fun apps(vararg lines: String) = (listOf("\t\t\t\t\"apps\"", "\t\t\t\t{") + lines + "\t\t\t\t}").joinToString("\n")
|
||||
|
||||
private val sparking = arrayOf(
|
||||
"\t\t\t\t\t\"1790600\"", "\t\t\t\t\t{", "\t\t\t\t\t\t\"LastPlayed\"\t\t\"1761897600\"", "\t\t\t\t\t\t\"LaunchOptions\"\t\t\"-dx11\"", "\t\t\t\t\t}",
|
||||
)
|
||||
|
||||
@Test fun replacesTheOptionsSteamHas() {
|
||||
val text = config(apps(*sparking))
|
||||
val updated = SteamLaunchOptions.withLaunchOptions(text, 1790600, "-dx12")!!
|
||||
assertEquals(text.replace("\"-dx11\"", "\"-dx12\""), updated)
|
||||
assertEquals("-dx12", SteamLaunchOptions.launchOptions(updated, 1790600))
|
||||
}
|
||||
|
||||
@Test fun addsOptionsToAGameThatHasNone() {
|
||||
val text = config(apps("\t\t\t\t\t\"1790600\"", "\t\t\t\t\t{", "\t\t\t\t\t\t\"LastPlayed\"\t\t\"1761897600\"", "\t\t\t\t\t}"))
|
||||
assertEquals(config(apps(*sparking)).replace("-dx11", "-vulkan"), SteamLaunchOptions.withLaunchOptions(text, 1790600, "-vulkan"))
|
||||
}
|
||||
|
||||
@Test fun addsTheGameAndTheAppsSectionWhenSteamHasNeither() {
|
||||
val updated = SteamLaunchOptions.withLaunchOptions(config("\t\t\t\t\"language\"\t\t\"english\""), 1790600, "-dx11")!!
|
||||
assertEquals(
|
||||
config(
|
||||
"\t\t\t\t\"language\"\t\t\"english\"\n" +
|
||||
apps("\t\t\t\t\t\"1790600\"", "\t\t\t\t\t{", "\t\t\t\t\t\t\"LaunchOptions\"\t\t\"-dx11\"", "\t\t\t\t\t}"),
|
||||
),
|
||||
updated,
|
||||
)
|
||||
assertEquals("-dx11", SteamLaunchOptions.launchOptions(updated, 1790600))
|
||||
}
|
||||
|
||||
@Test fun quotesAndBackslashesAreEscapedAndReadBack() {
|
||||
val options = "PROTON_LOG=1 %command% -path \"C:\\Games\\DB\""
|
||||
val updated = SteamLaunchOptions.withLaunchOptions(config(apps(*sparking)), 1790600, options)!!
|
||||
assertEquals(true, updated.contains("\"PROTON_LOG=1 %command% -path \\\"C:\\\\Games\\\\DB\\\"\""))
|
||||
assertEquals(options, SteamLaunchOptions.launchOptions(updated, 1790600))
|
||||
}
|
||||
|
||||
@Test fun emptyOptionsClearSteams() {
|
||||
val updated = SteamLaunchOptions.withLaunchOptions(config(apps(*sparking)), 1790600, "")!!
|
||||
assertEquals("", SteamLaunchOptions.launchOptions(updated, 1790600))
|
||||
}
|
||||
|
||||
@Test fun windowsLineEndsAreKept() {
|
||||
val text = config("\t\t\t\t\"language\"\t\t\"english\"").replace("\n", "\r\n")
|
||||
val updated = SteamLaunchOptions.withLaunchOptions(text, 1790600, "-dx11")!!
|
||||
assertEquals(false, updated.replace("\r\n", "").contains('\n'))
|
||||
assertEquals("-dx11", SteamLaunchOptions.launchOptions(updated, 1790600))
|
||||
}
|
||||
|
||||
@Test fun onlyTheGamesOwnSectionChanges() {
|
||||
val other = arrayOf(
|
||||
"\t\t\t\t\t\"7\"", "\t\t\t\t\t{", "\t\t\t\t\t\t\"1790600\"", "\t\t\t\t\t\t{", "\t\t\t\t\t\t\t\"LaunchOptions\"\t\t\"keep\"", "\t\t\t\t\t\t}", "\t\t\t\t\t}",
|
||||
)
|
||||
val updated = SteamLaunchOptions.withLaunchOptions(config(apps(*other, *sparking)), 1790600, "-dx12")!!
|
||||
assertEquals(true, updated.contains("\"keep\""))
|
||||
assertEquals("-dx12", SteamLaunchOptions.launchOptions(updated, 1790600))
|
||||
assertNull(SteamLaunchOptions.launchOptions(config(apps(*other)), 1790600))
|
||||
}
|
||||
|
||||
@Test fun otherFilesAreLeftAlone() {
|
||||
assertNull(SteamLaunchOptions.withLaunchOptions("\"InstallConfigStore\"\n{\n}\n", 1790600, "-dx11"))
|
||||
assertNull(SteamLaunchOptions.withLaunchOptions("", 1790600, "-dx11"))
|
||||
assertNull(SteamLaunchOptions.launchOptions("", 1790600))
|
||||
}
|
||||
|
||||
private fun steamHome(home: File = tmp.newFolder("Steam")): File = home.also {
|
||||
File(home, "config").mkdirs()
|
||||
File(home, "config/loginusers.vdf").writeText(
|
||||
"\"users\"\n{\n\t\"76561198021239924\"\n\t{\n\t\t\"AccountName\"\t\t\"a\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
|
||||
}
|
||||
|
||||
private fun localConfig(home: File, account: String) = File(home, "userdata/$account/config/localconfig.vdf").apply { parentFile!!.mkdirs() }
|
||||
|
||||
@Test fun aChangeGoesToTheSignedInAccountOnly() {
|
||||
val home = steamHome()
|
||||
val signedIn = localConfig(home, "60974196").apply { writeText(config(apps(*sparking))) }
|
||||
val other = localConfig(home, "123").apply { writeText(config("\t\t\t\t\"language\"\t\t\"english\"")) }
|
||||
val untouched = other.readText()
|
||||
assertTrue(SteamLaunchOptions.write(home, 1790600, "-dx12"))
|
||||
assertEquals("-dx12", SteamLaunchOptions.launchOptions(signedIn.readText(), 1790600))
|
||||
assertEquals(untouched, other.readText())
|
||||
assertFalse(File(signedIn.parentFile, "localconfig.vdf.staged").exists())
|
||||
}
|
||||
|
||||
@Test fun whatSteamWroteLastIsWhatTheGameHas() {
|
||||
val home = steamHome()
|
||||
val config = localConfig(home, "60974196").apply { writeText(config(apps(*sparking))) }
|
||||
assertTrue(SteamLaunchOptions.write(home, 1790600, "-dx12"))
|
||||
config.writeText(SteamLaunchOptions.withLaunchOptions(config.readText(), 1790600, "-vulkan")!!)
|
||||
assertEquals("-vulkan", SteamLaunchOptions.steam(home, 1790600))
|
||||
assertNull(SteamLaunchOptions.steam(home, 400))
|
||||
}
|
||||
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
private val written = ArrayList<File>()
|
||||
|
||||
private fun sessionConfig(): File {
|
||||
val home = steamHome(SessionPrefs.activeSteamRoot(app))
|
||||
return localConfig(home, "60974196").apply { writeText(config(apps(*sparking))) }
|
||||
.also { written += it; written += File(home, "config/loginusers.vdf") }
|
||||
}
|
||||
|
||||
@After fun noSession() {
|
||||
SessionState.running = false
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
written.forEach { it.delete() }
|
||||
}
|
||||
|
||||
@Test fun aValueChangedInSteamSinceItWasShownIsNotOverwritten() {
|
||||
val config = sessionConfig()
|
||||
assertEquals(SteamLaunchOptions.Saved.NO, SteamLaunchOptions.set(app, 1790600, "-dx12", shown = "-vulkan"))
|
||||
assertEquals("-dx11", SteamLaunchOptions.launchOptions(config.readText(), 1790600))
|
||||
assertEquals(SteamLaunchOptions.Saved.YES, SteamLaunchOptions.set(app, 1790600, "-dx12", shown = "-dx11"))
|
||||
assertEquals("-dx12", SteamLaunchOptions.launchOptions(config.readText(), 1790600))
|
||||
}
|
||||
|
||||
@Test fun aDesktopSessionLeavesTheFileToItsClient() {
|
||||
val config = sessionConfig()
|
||||
val before = config.readText()
|
||||
SessionState.running = true
|
||||
SessionState.mode = SessionService.MODE_DESKTOP
|
||||
assertEquals(SteamLaunchOptions.Saved.DESKTOP, SteamLaunchOptions.set(app, 1790600, "-dx12", shown = "-dx11"))
|
||||
assertEquals(before, config.readText())
|
||||
}
|
||||
|
||||
@Test fun nothingIsWrittenWithoutASignedInAccountsConfig() {
|
||||
assertFalse(SteamLaunchOptions.write(tmp.newFolder("NoSteam"), 1790600, "-dx11"))
|
||||
val home = steamHome()
|
||||
assertFalse(SteamLaunchOptions.write(home, 1790600, "-dx11"))
|
||||
localConfig(home, "60974196").writeText("\"InstallConfigStore\"\n{\n}\n")
|
||||
assertFalse(SteamLaunchOptions.write(home, 1790600, "-dx11"))
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,6 @@ class GlassesDisplayTest {
|
||||
@Test fun gtMaxSmartGlassesEdidUsesTheSameOutputSelectionAsViture() {
|
||||
val panel = display("SmartGlasses", productName = "SmartGlasses", productId = "980")
|
||||
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = true)?.displayId)
|
||||
// The display remains usable while USB control reconnects during a mode switch.
|
||||
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = false)?.displayId)
|
||||
}
|
||||
|
||||
@@ -126,7 +125,6 @@ class GlassesDisplayTest {
|
||||
}
|
||||
}
|
||||
|
||||
// Robolectric exposes display names and flags, but has no product-metadata setter.
|
||||
@Implements(Display::class)
|
||||
class ProductMetadataDisplay : ShadowDisplay() {
|
||||
var productMetadata: DeviceProductInfo? = null
|
||||
|
||||
@@ -63,7 +63,6 @@ class GlassesMenuProjectionTest {
|
||||
private object GlassesMenuProjection {
|
||||
data class Uv(val x: Float, val y: Float)
|
||||
|
||||
// Row-major head-to-anchor rotation; +Y is up, -Z is forward, output UV starts at the top left.
|
||||
fun intersect(frame: GlassesMenuPose.Frame, rayX: Float, rayY: Float, eye: Float,
|
||||
halfWidth: Float, distance: Float, aspect: Float): Uv? {
|
||||
if (frame.rotation.size != 9 || frame.position.size != 3 || frame.rotation.any { !it.isFinite() } ||
|
||||
|
||||
@@ -30,7 +30,6 @@ class GlassesOutputHandoffTest {
|
||||
private lateinit var screen: GlassesScreen
|
||||
|
||||
@Before fun setup() {
|
||||
// Exercise the output lifecycle without starting the native Linux runtime.
|
||||
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
phone = SurfaceView(activity)
|
||||
ReflectionHelpers.setField(activity, "surfaceView", phone)
|
||||
@@ -46,7 +45,7 @@ class GlassesOutputHandoffTest {
|
||||
@Test fun selectingGlassesDoesNotHidePhoneOrClaimOutputBeforeAttachment() {
|
||||
assertFalse(active())
|
||||
assertEquals(View.VISIBLE, phone.visibility)
|
||||
attach(phone.holder) // A late phone callback must not complete the handoff.
|
||||
attach(phone.holder)
|
||||
assertFalse(active())
|
||||
assertEquals(View.VISIBLE, phone.visibility)
|
||||
}
|
||||
|
||||
@@ -183,11 +183,11 @@ class GlassesRenderingTest {
|
||||
picture3d = GlassesSettings.PICTURE_SCREEN)
|
||||
for (state in listOf(ultra.copy(displayId = -1), GlassesState())) {
|
||||
val preview = GlassesRendering.cardboard(base, settings, state, false, true)
|
||||
assertTrue(preview.enabled) // Published as headset proximity, preventing standby.
|
||||
assertTrue(preview.enabled)
|
||||
assertTrue(preview.mono)
|
||||
assertEquals(Cardboard.SOURCE_SBS, preview.source)
|
||||
assertEquals(Cardboard.Viewer.NONE.id, preview.viewer)
|
||||
assertTrue(preview.headTracking) // Phone preference, not dormant glasses settings.
|
||||
assertTrue(preview.headTracking)
|
||||
assertFalse(base.enabled)
|
||||
assertSame(base, GlassesRendering.cardboard(base, settings, state, false, false))
|
||||
}
|
||||
|
||||
@@ -251,8 +251,6 @@ class GlassesSteamVrTest {
|
||||
.set(activity, LoadingState(activity).apply { visible = false })
|
||||
SessionState.steamVr = true
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
// Hold the external worker so status transitions can be exercised
|
||||
// without launching a Linux runtime from the host test process.
|
||||
val worker = SessionActivity::class.java.getDeclaredField("steamVrWorker")
|
||||
.apply { isAccessible = true }.get(null) as ThreadPoolExecutor
|
||||
val blocked = CountDownLatch(1)
|
||||
|
||||
@@ -115,8 +115,6 @@ class RayNeoCalibrationTest {
|
||||
val upright = RayNeoOrientationFilter(profile.rotationXDeg, profile.gtMaxAxes, saved)
|
||||
.update(sample(floatArrayOf(-0.02f, 8.819f, 4.106f), reading.gyroDps))
|
||||
assertArrayEquals(floatArrayOf(1f, 0f, 0f, 0f), upright, 0.001f)
|
||||
// This was the reported failure: the same physical pose cannot calibrate
|
||||
// through the Max's permutation and 35-degree mounting correction.
|
||||
assertNull(finish(RayNeoCalibrationCollector(RayNeoSensorAxes(35f, true), 0), sample = reading))
|
||||
}
|
||||
|
||||
|
||||
@@ -102,7 +102,6 @@ class RayNeoLinkTest {
|
||||
val cmd = bytes[1].toInt() and 0xff
|
||||
commands += cmd
|
||||
if (gtTraffic && cmd in listOf(0, 1)) {
|
||||
// Notifications and unrelated ACKs can precede the requested response.
|
||||
for (other in listOf(0x08, 6, 7, 0x50)) {
|
||||
responses += ByteArray(64).apply {
|
||||
this[0] = 0x99.toByte(); this[1] = 0xc8.toByte(); this[2] = 64
|
||||
|
||||
@@ -79,8 +79,6 @@ class RayNeoOrientationFilterTest {
|
||||
val first = screen(filter.update(sample(0, level)))
|
||||
val ref = HeadPose.recenter(first)
|
||||
var q = FloatArray(4)
|
||||
// Physical 30-degree turn over one second, through the complete shared
|
||||
// VITURE conversion and recenter pipeline. GT signs match device captures.
|
||||
repeat(100) { i ->
|
||||
val a = Math.toRadians((i + 1) * 0.3)
|
||||
val accel = when (axis) {
|
||||
|
||||
@@ -116,7 +116,7 @@ class RayNeoProtocolTest {
|
||||
@Test fun tickWrapDoesNotIntroduceOrientationJump() {
|
||||
val filter = RayNeoOrientationFilter(0f)
|
||||
filter.update(sample(0xfffffff0L, 90f))
|
||||
val q = filter.update(sample(84, 90f)) // 100 ticks = 10ms across uint32 rollover.
|
||||
val q = filter.update(sample(84, 90f))
|
||||
assertEquals(kotlin.math.sin(Math.PI * 0.005).toFloat(), q[2], 1e-4f)
|
||||
}
|
||||
}
|
||||
@@ -71,8 +71,8 @@ class VitureSdkTest {
|
||||
val s = kotlin.math.sin(Math.PI / 12).toFloat()
|
||||
val c = kotlin.math.cos(Math.PI / 12).toFloat()
|
||||
for ((axis, expected) in listOf(
|
||||
2 to floatArrayOf(-0.5f, 0f, -0.8660254f), // Observed left turn: positive Y.
|
||||
1 to floatArrayOf(0f, 0.5f, -0.8660254f), // Observed upward look: positive X.
|
||||
2 to floatArrayOf(-0.5f, 0f, -0.8660254f),
|
||||
1 to floatArrayOf(0f, 0.5f, -0.8660254f),
|
||||
3 to floatArrayOf(-0.5f, 0.8660254f, 0f),
|
||||
)) {
|
||||
val q = floatArrayOf(c, 0f, 0f, 0f).apply { this[axis] = s }
|
||||
@@ -84,7 +84,6 @@ class VitureSdkTest {
|
||||
|
||||
@Test fun ultraOpenGlAxesMatchExistingGlassesHeadTracker() {
|
||||
val a = sqrt(0.5f)
|
||||
// OpenGL Y yaw maps to NWU Z; OpenGL X pitch maps to negative NWU Y.
|
||||
assertArrayEquals(floatArrayOf(0f, 0f, a, a),
|
||||
VitureSdkPose.toGlasses(floatArrayOf(a, 0f, a, 0f), true), 0.00001f)
|
||||
assertArrayEquals(floatArrayOf(0f, -a, 0f, a),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// Fixtures adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
|
||||
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
|
||||
// Fixtures adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick. Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
|
||||
@@ -63,10 +63,8 @@ class XrealOrientationFilterTest {
|
||||
@Test fun capturedNeutralGravityStartsUprightBeforeRecenter() {
|
||||
val pose = XrealOrientationFilter().update(sample(1000000,
|
||||
accel = Vec3(-0.0909f, -9.6529f, -1.0731f)))!!
|
||||
// An upright start must not contain the previous approximately 180-degree
|
||||
// pitch correction. Check before recenter can hide a mounting error.
|
||||
assertTrue(kotlin.math.abs(pose[3]) > 0.99f)
|
||||
val screen = matrix(pose)
|
||||
assertTrue(screen[7] > 0.99f) // Screen up points toward shared world +Z.
|
||||
assertTrue(screen[7] > 0.99f)
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,6 @@ class XrealProtocolTest {
|
||||
assertEquals(0x2822, XrealProtocol.read(requests).command)
|
||||
repeat(3) { assertEquals(0x275e, XrealProtocol.read(requests).command) }
|
||||
assertEquals(0, requests.available())
|
||||
// Actual 1S busy response remains an error, never a successful ack.
|
||||
assertFalse(XrealProtocol.acknowledged(byteArrayOf(0x22, 3, 8, 0x89.toByte(), 0x27)))
|
||||
}
|
||||
|
||||
|
||||
@@ -111,6 +111,9 @@ class DriverPairsTest {
|
||||
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(840), pairs))
|
||||
assertEquals("other 8xx keep WinNative", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), pairs))
|
||||
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), pairs))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs))
|
||||
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(740), pairs))
|
||||
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(722), pairs))
|
||||
assertEquals(DriverPairs.BANNER_ONEUI, DriverPairs.recommendedKey(gpu(740, oneUi = true), pairs))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), pairs))
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,6 @@ class GpuDetectionTest {
|
||||
}
|
||||
|
||||
@Test fun nonAdrenoRenderersAreNeverAdrenoWhateverNumberTheyCarry() {
|
||||
// Xclipse (Exynos), Mali and Immortalis names; familyOf ignores the number off Adreno.
|
||||
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0))
|
||||
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Samsung Xclipse 920")))
|
||||
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Xclipse 940")))
|
||||
|
||||
@@ -17,7 +17,7 @@ class SteamVrDeviceLossLogTest {
|
||||
assertFalse(log.poll())
|
||||
file.appendText("-4\n")
|
||||
assertTrue(log.poll())
|
||||
assertTrue(log.poll()) // Keep pending until the activity is foreground.
|
||||
assertTrue(log.poll())
|
||||
}
|
||||
|
||||
@Test fun onlyExplicitDeviceLossTriggersRecovery() {
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.widget.FrameLayout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.time.Duration
|
||||
import java.util.Base64
|
||||
import kotlin.math.sqrt
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], qualifiers = "xhdpi")
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class DroidDeckHudPanelTest {
|
||||
@Test fun minimalIsTheSizeTheHudStartsWith() {
|
||||
assertEquals(DroidDeckHudSize.MINIMAL, DroidDeckHudSize.from(DroidDeckHudConfig.DEFAULTS["hudSize"]))
|
||||
}
|
||||
|
||||
@Test fun theHudStartsLocked() {
|
||||
assertEquals("1", DroidDeckHudConfig.DEFAULTS["hudLocked"])
|
||||
}
|
||||
|
||||
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
repeat(2_000) { i ->
|
||||
val frametime = if (i == 1_700) 25_600_000L else 2_850_000L
|
||||
now += frametime
|
||||
stats.add(frametime, now)
|
||||
}
|
||||
val snapshot = SNAPSHOT
|
||||
for (size in DroidDeckHudSize.values()) {
|
||||
if (size == DroidDeckHudSize.STRIP) continue
|
||||
val view = DroidDeckHudView(RuntimeEnvironment.getApplication())
|
||||
view.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to size.token)))
|
||||
view.setFrameStats(stats)
|
||||
view.showForTest(snapshot, "DXVK", now)
|
||||
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
view.measure(unspecified, unspecified)
|
||||
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
|
||||
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(bitmap))
|
||||
|
||||
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
println("DROIDDECKHUD-${size.token.uppercase()}-PNG ${Base64.getEncoder().encodeToString(png.toByteArray())}")
|
||||
|
||||
val panel = view.panelForTest()!!
|
||||
assertTrue("$size panel inside the view",
|
||||
panel.left > 0f && panel.top > 0f && panel.right < view.width && panel.bottom < view.height)
|
||||
view.graphForTest()?.let { graph ->
|
||||
val r = view.panelRadiusForTest()
|
||||
val d = maxOf(panel.top + r - graph.top, graph.bottom - (panel.bottom - r), 0f)
|
||||
val edge = panel.right - r + sqrt(r * r - d * d)
|
||||
assertTrue("$size graph clears the round side", graph.right <= edge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun stripIsOneLineAcrossTheParentWithTheClockOnTheRight() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val parent = FrameLayout(app)
|
||||
val view = DroidDeckHudView(app)
|
||||
parent.addView(view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
|
||||
parent.measure(View.MeasureSpec.makeMeasureSpec(2400, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY))
|
||||
parent.layout(0, 0, 2400, 1080)
|
||||
view.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to DroidDeckHudSize.STRIP.token) +
|
||||
("showBattery" to "1")))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
view.measure(unspecified, unspecified)
|
||||
|
||||
assertTrue(view.isStrip)
|
||||
assertEquals(2400, view.measuredWidth)
|
||||
val lines = view.linesForTest()
|
||||
assertEquals(lines.toString(), 1, lines.size)
|
||||
val line = lines.single()
|
||||
listOf("DXVK", "fps", "GPU", "CPU", "RAM", "BAT 79%").forEach { assertTrue(line, it in line) }
|
||||
assertTrue(line, line.indexOf("DXVK") < line.indexOf("GPU") && line.indexOf("GPU") < line.indexOf("BAT"))
|
||||
|
||||
val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
|
||||
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
|
||||
view.draw(Canvas(bitmap))
|
||||
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
println("DROIDDECKHUD-STRIP-PNG ${Base64.getEncoder().encodeToString(png.toByteArray())}")
|
||||
}
|
||||
|
||||
@Test fun stripLeavesOffWhatNoLongerFitsBeforeTheClock() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val parent = FrameLayout(app)
|
||||
val view = DroidDeckHudView(app)
|
||||
parent.addView(view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
|
||||
parent.measure(View.MeasureSpec.makeMeasureSpec(700, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.EXACTLY))
|
||||
parent.layout(0, 0, 700, 400)
|
||||
view.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to DroidDeckHudSize.STRIP.token)))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val line = view.linesForTest().single()
|
||||
assertTrue(line, "fps" in line)
|
||||
assertFalse(line, "BAT" in line)
|
||||
}
|
||||
|
||||
@Test fun stripFollowsTheHudScaleInHeightAndKeepsTheFullWidth() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val parent = FrameLayout(app)
|
||||
val view = DroidDeckHudView(app)
|
||||
parent.addView(view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
|
||||
parent.measure(View.MeasureSpec.makeMeasureSpec(2400, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY))
|
||||
parent.layout(0, 0, 2400, 1080)
|
||||
fun at(scale: Int): Pair<Float, Float> {
|
||||
view.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to DroidDeckHudSize.STRIP.token) +
|
||||
("hudScale" to scale.toString())))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
view.measure(unspecified, unspecified)
|
||||
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
|
||||
val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(bitmap))
|
||||
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
println("DROIDDECKHUD-STRIP$scale-PNG ${Base64.getEncoder().encodeToString(png.toByteArray())}")
|
||||
return Pair(view.contentWidth, view.contentHeight)
|
||||
}
|
||||
val small = at(70); val big = at(150)
|
||||
assertEquals(2400f, small.first); assertEquals(2400f, big.first)
|
||||
assertEquals(big.second / small.second, 150f / 70f, 0.01f)
|
||||
}
|
||||
|
||||
@Test fun pillShowsEachBatteryPartOnItsOwnSwitch() {
|
||||
fun pill(vararg settings: Pair<String, String>): List<String> {
|
||||
val view = DroidDeckHudView(RuntimeEnvironment.getApplication())
|
||||
view.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to DroidDeckHudSize.PILL.token) + settings))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
return view.linesForTest()
|
||||
}
|
||||
val all = pill("showBattery" to "1")
|
||||
assertTrue(all.toString(), all.any { "BAT 79% · 34°C · 16.0W" in it })
|
||||
assertEquals(all.toString(), 1, all.count { "BAT" in it })
|
||||
assertFalse(all.toString(), all.single { "RAM" in it }.contains("BAT"))
|
||||
|
||||
val noMemory = pill("showBattery" to "1", "showRAM" to "0")
|
||||
assertTrue(noMemory.toString(), noMemory.none { "RAM" in it })
|
||||
assertTrue(noMemory.toString(), noMemory.any { "BAT 79% · 34°C · 16.0W" in it })
|
||||
|
||||
val defaults = pill()
|
||||
assertTrue(defaults.toString(), defaults.any { "BAT 34°C · 16.0W" in it })
|
||||
val wattsOnly = pill("showBatteryTemp" to "0")
|
||||
assertTrue(wattsOnly.toString(), wattsOnly.any { "BAT 16.0W" in it })
|
||||
val nothing = pill("showBatteryTemp" to "0", "showPower" to "0")
|
||||
assertTrue(nothing.toString(), nothing.none { "BAT" in it })
|
||||
}
|
||||
|
||||
@Test fun aLockedHudLetsTouchesThroughOnlyWhereAControlTakesThem() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
var reached = 0
|
||||
val under = View(app).apply {
|
||||
setOnTouchListener { _, e -> if (e.actionMasked == MotionEvent.ACTION_DOWN) reached++; true }
|
||||
}
|
||||
val hud = DroidDeckHudView(app)
|
||||
val parent = FrameLayout(app)
|
||||
parent.addView(under, FrameLayout.LayoutParams(2000, 2000))
|
||||
parent.addView(hud, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
|
||||
var control = false
|
||||
hud.passesTouchAt = { _, _ -> control }
|
||||
val locks = ArrayList<Boolean>()
|
||||
hud.setOnLockChangedListener { locks += it }
|
||||
hud.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudLocked" to "0")))
|
||||
hud.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val exactly = View.MeasureSpec.makeMeasureSpec(2000, View.MeasureSpec.EXACTLY)
|
||||
parent.measure(exactly, exactly)
|
||||
parent.layout(0, 0, 2000, 2000)
|
||||
assertTrue(hud.width > 0 && hud.height > 0)
|
||||
fun touch(holdMs: Long = 50L) {
|
||||
val x = hud.width / 2f; val y = hud.height / 2f
|
||||
val down = SystemClock.uptimeMillis()
|
||||
MotionEvent.obtain(down, down, MotionEvent.ACTION_DOWN, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(holdMs))
|
||||
MotionEvent.obtain(down, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
}
|
||||
control = true
|
||||
touch()
|
||||
assertEquals("an unlocked HUD keeps the touch (tap, drag, long press)", 0, reached)
|
||||
hud.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudLocked" to "1")))
|
||||
touch()
|
||||
assertEquals("a locked HUD passes it to the control under it", 1, reached)
|
||||
control = false
|
||||
touch()
|
||||
assertEquals("a locked HUD keeps a touch no control takes", 1, reached)
|
||||
touch(holdMs = ViewConfiguration.getLongPressTimeout() + 300L)
|
||||
assertEquals("a long press there unlocks it", listOf(false), locks)
|
||||
}
|
||||
|
||||
@Test fun aDockedHudIsJustTheFpsTabAndATapBringsItBack() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val hud = DroidDeckHudView(app)
|
||||
hud.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to "full") + ("hudDock" to "left")))
|
||||
hud.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
hud.measure(unspecified, unspecified)
|
||||
hud.layout(0, 0, hud.measuredWidth, hud.measuredHeight)
|
||||
assertEquals(DroidDeckHudDock.LEFT, hud.dock)
|
||||
assertTrue("a tab, not the panel: ${hud.width}x${hud.height}", hud.width < 400 && hud.height < 200)
|
||||
val docks = ArrayList<String>()
|
||||
hud.setOnDockChangedListener { docks += it }
|
||||
val down = SystemClock.uptimeMillis()
|
||||
MotionEvent.obtain(down, down, MotionEvent.ACTION_DOWN, 5f, 5f, 0).also { hud.dispatchTouchEvent(it); it.recycle() }
|
||||
MotionEvent.obtain(down, down + 40, MotionEvent.ACTION_UP, 5f, 5f, 0).also { hud.dispatchTouchEvent(it); it.recycle() }
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals("a locked, docked HUD still answers a tap", listOf("none"), docks)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val SNAPSHOT = HudMetrics.Snapshot(64, 52, 3302, 1050, 89, 79, 10_800_000_000L, 16_000_000_000L, 67f,
|
||||
1_800_000_000L, HudMetrics.Battery(16f, false, 79, 34, null),
|
||||
intArrayOf(91, 91, 48, 50, 48, 19, 17, 73), intArrayOf(2265, 2265, 3148, 3148, 3148, 2956, 2956, 3302),
|
||||
2_700_000_000L, 6_400_000_000L, 31_000L, 9_000L)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import org.junit.Test
|
||||
import kotlin.random.Random
|
||||
|
||||
class FrameStatsTest {
|
||||
/** MangoHud's update_hud_info_with_frametime and fps()/frame_timing(), line by line (overlay.cpp). */
|
||||
private class Mango {
|
||||
val frametimeData = ArrayList<Float>(List(200) { 0f })
|
||||
var lastPresentTime = 0L
|
||||
@@ -69,6 +68,30 @@ class FrameStatsTest {
|
||||
assertFalse(feed.poll(now + 1))
|
||||
}
|
||||
|
||||
@Test fun slowFramesCountOnlyFramesOver33MsInTheWindow() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
for (ft in listOf(16_666_667L, 40_000_000L, 16_666_667L, 50_000_000L, 2_000_000_000L, 16_666_667L)) {
|
||||
now += ft
|
||||
stats.add(ft, now)
|
||||
}
|
||||
assertEquals(2, stats.slowFrames(now, 60_000_000_000L))
|
||||
assertEquals(0, stats.slowFrames(now + 120_000_000_000L, 60_000_000_000L))
|
||||
stats.reset()
|
||||
assertEquals(0, stats.slowFrames(now, 60_000_000_000L))
|
||||
}
|
||||
|
||||
@Test fun compositorFramesDoNotCountAsLiveGamescopeFrames() {
|
||||
val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames"))
|
||||
var now = 1_000_000_000L
|
||||
assertFalse(feed.live)
|
||||
feed.onCompositorFrame(now)
|
||||
now += 16_666_667L
|
||||
feed.onCompositorFrame(now)
|
||||
feed.poll(now)
|
||||
assertFalse(feed.live)
|
||||
}
|
||||
|
||||
@Test fun aCompletedPeriodIsCountedWhenMangoHudWouldRedraw() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.widget.FrameLayout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.time.Duration
|
||||
import java.util.Base64
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sqrt
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], qualifiers = "xhdpi")
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class FusionHudPanelTest {
|
||||
@Test fun minimalIsTheSizeTheHudStartsWith() {
|
||||
assertEquals(FusionSize.MINIMAL, FusionSize.from(FusionHudConfig.DEFAULTS["hudSize"]))
|
||||
}
|
||||
|
||||
@Test fun theHudStartsLocked() {
|
||||
assertEquals("1", FusionHudConfig.DEFAULTS["hudLocked"])
|
||||
}
|
||||
|
||||
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
repeat(2_000) { i ->
|
||||
val frametime = if (i == 1_700) 25_600_000L else 2_850_000L
|
||||
now += frametime
|
||||
stats.add(frametime, now)
|
||||
}
|
||||
val snapshot = SNAPSHOT
|
||||
for (size in FusionSize.values()) {
|
||||
val view = FusionHudView(RuntimeEnvironment.getApplication())
|
||||
view.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudSize" to size.token)))
|
||||
view.setFrameStats(stats)
|
||||
view.showForTest(snapshot, "DXVK", now)
|
||||
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
view.measure(unspecified, unspecified)
|
||||
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
|
||||
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(bitmap))
|
||||
|
||||
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
println("FUSIONHUD-${size.token.uppercase()}-PNG ${Base64.getEncoder().encodeToString(png.toByteArray())}")
|
||||
|
||||
val panel = view.panelForTest()!!
|
||||
assertTrue("$size panel inside the view",
|
||||
panel.left > 0f && panel.top > 0f && panel.right < view.width && panel.bottom < view.height)
|
||||
view.graphForTest()?.let { graph ->
|
||||
val r = view.panelRadiusForTest()
|
||||
val d = maxOf(panel.top + r - graph.top, graph.bottom - (panel.bottom - r), 0f)
|
||||
val edge = panel.right - r + sqrt(r * r - d * d)
|
||||
assertTrue("$size graph clears the round side", graph.right <= edge)
|
||||
}
|
||||
val orb = bitmap.getPixel(panel.left.roundToInt() + 1, panel.centerY().roundToInt())
|
||||
assertTrue("$size orb on the left side", Color.blue(orb) > 200 && Color.alpha(orb) > 200)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun pillShowsEachBatteryPartOnItsOwnSwitch() {
|
||||
fun pill(vararg settings: Pair<String, String>): List<String> {
|
||||
val view = FusionHudView(RuntimeEnvironment.getApplication())
|
||||
view.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudSize" to FusionSize.PILL.token) + settings))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
return view.linesForTest()
|
||||
}
|
||||
val all = pill("showBattery" to "1")
|
||||
assertTrue(all.toString(), all.any { "BAT 79% · 34°C · 16.0W" in it })
|
||||
assertEquals(all.toString(), 1, all.count { "BAT" in it })
|
||||
assertFalse(all.toString(), all.single { "RAM" in it }.contains("BAT"))
|
||||
|
||||
val noMemory = pill("showBattery" to "1", "showRAM" to "0")
|
||||
assertTrue(noMemory.toString(), noMemory.none { "RAM" in it })
|
||||
assertTrue(noMemory.toString(), noMemory.any { "BAT 79% · 34°C · 16.0W" in it })
|
||||
|
||||
val defaults = pill()
|
||||
assertTrue(defaults.toString(), defaults.any { "BAT 34°C · 16.0W" in it })
|
||||
val wattsOnly = pill("showBatteryTemp" to "0")
|
||||
assertTrue(wattsOnly.toString(), wattsOnly.any { "BAT 16.0W" in it })
|
||||
val nothing = pill("showBatteryTemp" to "0", "showPower" to "0")
|
||||
assertTrue(nothing.toString(), nothing.none { "BAT" in it })
|
||||
}
|
||||
|
||||
@Test fun aLockedHudLetsTouchesThroughOnlyWhereAControlTakesThem() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
var reached = 0
|
||||
val under = View(app).apply {
|
||||
setOnTouchListener { _, e -> if (e.actionMasked == MotionEvent.ACTION_DOWN) reached++; true }
|
||||
}
|
||||
val hud = FusionHudView(app)
|
||||
val parent = FrameLayout(app)
|
||||
parent.addView(under, FrameLayout.LayoutParams(2000, 2000))
|
||||
parent.addView(hud, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
|
||||
var control = false
|
||||
hud.passesTouchAt = { _, _ -> control }
|
||||
val locks = ArrayList<Boolean>()
|
||||
hud.setOnLockChangedListener { locks += it }
|
||||
hud.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudLocked" to "0")))
|
||||
hud.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val exactly = View.MeasureSpec.makeMeasureSpec(2000, View.MeasureSpec.EXACTLY)
|
||||
parent.measure(exactly, exactly)
|
||||
parent.layout(0, 0, 2000, 2000)
|
||||
assertTrue(hud.width > 0 && hud.height > 0)
|
||||
fun touch(holdMs: Long = 50L) {
|
||||
val x = hud.width / 2f; val y = hud.height / 2f
|
||||
val down = SystemClock.uptimeMillis()
|
||||
MotionEvent.obtain(down, down, MotionEvent.ACTION_DOWN, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(holdMs))
|
||||
MotionEvent.obtain(down, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
}
|
||||
control = true
|
||||
touch()
|
||||
assertEquals("an unlocked HUD keeps the touch (tap, drag, long press)", 0, reached)
|
||||
hud.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudLocked" to "1")))
|
||||
touch()
|
||||
assertEquals("a locked HUD passes it to the control under it", 1, reached)
|
||||
control = false
|
||||
touch()
|
||||
assertEquals("a locked HUD keeps a touch no control takes", 1, reached)
|
||||
touch(holdMs = ViewConfiguration.getLongPressTimeout() + 300L)
|
||||
assertEquals("a long press there unlocks it", listOf(false), locks)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val SNAPSHOT = HudMetrics.Snapshot(64, 52, 3302, 1050, 89, 79, 10_800_000_000L, 16_000_000_000L, 67f,
|
||||
1_800_000_000L, HudMetrics.Battery(16f, false, 79, 34, null),
|
||||
intArrayOf(91, 91, 48, 50, 48, 19, 17, 73), intArrayOf(2265, 2265, 3148, 3148, 3148, 2956, 2956, 3302),
|
||||
2_700_000_000L, 6_400_000_000L, 31_000L, 9_000L)
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,10 @@ class MangoReadingsTest {
|
||||
@Test fun cpuLoadFollowsMangoHudsFormulaAndTruncates() {
|
||||
val stat = File(tmp.root, "stat")
|
||||
val m = readings()
|
||||
// user nice system idle iowait irq softirq steal guest guest_nice
|
||||
stat.writeText("cpu 1000 100 500 8000 400 50 50 0 200 0\ncpu0 500 50 250 4000 200 25 25 0 100 0\ncpu1 500 50 250 4000 200 25 25 0 100 0\nintr 0\n")
|
||||
m.cpu(stat)
|
||||
stat.writeText("cpu 1500 100 700 8600 500 60 70 10 300 0\ncpu0 900 50 400 4100 250 30 35 10 200 0\ncpu1 600 50 300 4500 250 30 35 0 100 0\nintr 0\n")
|
||||
val cpu = m.cpu(stat)!!
|
||||
// busy = user-guest 400 + nice 0 + system+irq+softirq 230 + steal 10 + guest 100 = 740 of 1440 (idle+iowait 700)
|
||||
assertEquals((740 * 100f / 1440).toInt(), cpu.percent)
|
||||
assertEquals(51, cpu.percent)
|
||||
assertArrayEquals(intArrayOf(((300 + 165 + 10 + 100) * 100f / (300 + 165 + 10 + 100 + 150)).toInt(), ((100 + 65) * 100f / (100 + 65 + 550)).toInt()), cpu.perCore)
|
||||
|
||||
@@ -240,6 +240,30 @@ class BackQamInputTest {
|
||||
assertTrue(taps.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun withHoldsOffTapsStillWorkButHoldsAndChordsDoNothing() {
|
||||
val noHold = BackQamInput(changes::add, taps::add, holds = { false })
|
||||
fun press(action: Int) = noHold.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true)
|
||||
press(KeyEvent.ACTION_DOWN)
|
||||
press(KeyEvent.ACTION_UP)
|
||||
advance(500)
|
||||
assertEquals(listOf(false), taps)
|
||||
press(KeyEvent.ACTION_DOWN)
|
||||
press(KeyEvent.ACTION_UP)
|
||||
press(KeyEvent.ACTION_DOWN)
|
||||
press(KeyEvent.ACTION_UP)
|
||||
assertEquals(listOf(false, true), taps)
|
||||
taps.clear()
|
||||
press(KeyEvent.ACTION_DOWN)
|
||||
advance(2000)
|
||||
assertTrue(press(KeyEvent.ACTION_UP))
|
||||
press(KeyEvent.ACTION_DOWN)
|
||||
noHold.onChordInput()
|
||||
press(KeyEvent.ACTION_UP)
|
||||
advance(1000)
|
||||
assertTrue(changes.isEmpty())
|
||||
assertTrue(taps.isEmpty())
|
||||
}
|
||||
|
||||
private fun advance(millis: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis))
|
||||
|
||||
private fun send(action: Int, repeat: Int = 0, device: Int = 4, enabled: Boolean = true) =
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Looper
|
||||
import android.view.accessibility.AccessibilityWindowInfo
|
||||
import com.droiddeck.launcher.input.BottomScreenGuests.Top
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(manifest = Config.NONE)
|
||||
class BottomScreenGuestsTest {
|
||||
private val homes = setOf("com.android.launcher3", "com.retroidpocket.gamelauncher")
|
||||
|
||||
@After fun clear() = DualScreen.setTaken(emptySet())
|
||||
|
||||
@Test fun onlyTheRetroidPocketDuoAndAynThorWatchTheirBottomScreen() {
|
||||
assertTrue(BottomScreenGuests.supported("Retroid Pocket Duo", 36))
|
||||
assertTrue(BottomScreenGuests.supported(" retroid pocket duo ", 33))
|
||||
assertFalse(BottomScreenGuests.supported("Retroid Pocket Duo", 32))
|
||||
assertTrue(BottomScreenGuests.supported("AYN Thor", 33))
|
||||
assertTrue(BottomScreenGuests.supported("AYN Thor Max", 34))
|
||||
assertFalse(BottomScreenGuests.supported("AYN Odin 2", 36))
|
||||
assertFalse(BottomScreenGuests.supported("Pixel 8", 36))
|
||||
}
|
||||
|
||||
@Test fun anyWindowButTheHomeScreenHoldsTheScreen() {
|
||||
assertEquals(Top.HOME, BottomScreenGuests.classify("com.android.launcher3", homes))
|
||||
assertEquals(Top.GUEST, BottomScreenGuests.classify("com.android.chrome", homes))
|
||||
assertEquals(Top.GUEST, BottomScreenGuests.classify("com.retroidpocket.dualscreen.assistant", homes))
|
||||
assertEquals(Top.NONE, BottomScreenGuests.classify(null, homes))
|
||||
}
|
||||
|
||||
@Test fun theWindowListDecidesWhenItSeesPastDroidDeck() {
|
||||
assertEquals("com.android.chrome", BottomScreenGuests.holder("com.android.chrome", null, homes))
|
||||
assertEquals(null, BottomScreenGuests.holder("com.android.launcher3", "com.android.chrome", homes))
|
||||
}
|
||||
|
||||
@Test fun anAppOpenedUnderDroidDeckHoldsTheScreenUntilTheListSeesIt() {
|
||||
assertEquals("com.google.android.youtube", BottomScreenGuests.holder(null, "com.google.android.youtube", homes))
|
||||
assertEquals(null, BottomScreenGuests.holder(null, "com.android.launcher3", homes))
|
||||
assertEquals(null, BottomScreenGuests.holder(null, null, homes))
|
||||
}
|
||||
|
||||
@Test fun keyboardsAndOverlaysNeverTakeTheScreen() {
|
||||
assertTrue(BottomScreenGuests.ignorable(AccessibilityWindowInfo.TYPE_INPUT_METHOD))
|
||||
assertTrue(BottomScreenGuests.ignorable(AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY))
|
||||
assertFalse(BottomScreenGuests.ignorable(AccessibilityWindowInfo.TYPE_APPLICATION))
|
||||
assertFalse(BottomScreenGuests.ignorable(AccessibilityWindowInfo.TYPE_SYSTEM))
|
||||
}
|
||||
|
||||
@Test fun listenersHearWhenTheScreenIsTakenAndFreed() {
|
||||
var calls = 0
|
||||
val listener: () -> Unit = { calls++ }
|
||||
DualScreen.watchTaken(listener)
|
||||
DualScreen.setTaken(setOf(2))
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertTrue(DualScreen.taken(2))
|
||||
assertFalse(DualScreen.taken(0))
|
||||
DualScreen.setTaken(setOf(2))
|
||||
DualScreen.setTaken(emptySet())
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertFalse(DualScreen.taken(2))
|
||||
assertEquals(2, calls)
|
||||
DualScreen.unwatchTaken(listener)
|
||||
DualScreen.setTaken(setOf(2))
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(2, calls)
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,28 @@ class DualScreenTest {
|
||||
@Test fun knownModelsCountWhenTheTypeIsHidden() {
|
||||
assertTrue(DualScreen.isBuiltIn(null, "Retroid Pocket Duo"))
|
||||
assertTrue(DualScreen.isBuiltIn(null, " AYN Thor "))
|
||||
assertTrue(DualScreen.isBuiltIn(null, "AYN Thor Max"))
|
||||
assertFalse(DualScreen.isBuiltIn(null, "Pixel 8"))
|
||||
}
|
||||
|
||||
@Test fun aSecondPanelNeedsATouchscreenOfItsOwnSize() {
|
||||
val top = 1920 to 1080
|
||||
val bottom = 1280 to 960
|
||||
assertTrue(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1920 to 1080, 1280 to 960)))
|
||||
assertTrue(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1080 to 1920, 960 to 1280)))
|
||||
assertTrue(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1920 to 1080, 1279 to 959)))
|
||||
assertFalse(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1920 to 1080)))
|
||||
assertFalse(DualScreen.hasOwnTouchPanel(bottom, top, emptyList()))
|
||||
}
|
||||
|
||||
@Test fun aPhantomPanelTheSizeOfTheMainScreenIsNotASecondScreen() {
|
||||
val main = 1920 to 1080
|
||||
assertFalse(DualScreen.hasOwnTouchPanel(main, main, listOf(1920 to 1080)))
|
||||
assertFalse(DualScreen.hasOwnTouchPanel(main, main, listOf(1080 to 1920)))
|
||||
assertTrue(DualScreen.hasOwnTouchPanel(main, main, listOf(1920 to 1080, 1920 to 1080)))
|
||||
assertTrue(DualScreen.hasOwnTouchPanel(main, null, listOf(1920 to 1080)))
|
||||
}
|
||||
|
||||
@Test fun oneScreenDevicesGetNoSecondScreenInAnyMode() {
|
||||
for (mode in DualScreen.modes) {
|
||||
SessionPrefs.setDualScreenMode(context, mode)
|
||||
@@ -47,4 +66,19 @@ class DualScreenTest {
|
||||
SessionPrefs.setDualScreenMode(context, DualScreen.MODE_OFF)
|
||||
assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context))
|
||||
}
|
||||
|
||||
@Test fun launcherAndSessionsKeepSeparateModes() {
|
||||
SessionPrefs.setDualScreenMode(context, DualScreen.MODE_OFF)
|
||||
assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context))
|
||||
assertEquals(DualScreen.MODE_AUTO, SessionPrefs.dualScreenSessionMode(context))
|
||||
SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_ON)
|
||||
assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context))
|
||||
assertEquals(DualScreen.MODE_ON, SessionPrefs.dualScreenSessionMode(context))
|
||||
}
|
||||
|
||||
@Test fun anOldDisabledMenuToggleTurnsBothOff() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("dualScreenLauncher", false).commit()
|
||||
assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context))
|
||||
assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenSessionMode(context))
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,13 @@ import org.robolectric.annotation.Config
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class GesturePrefsTest {
|
||||
@Test fun relativeMouseModeSurvivesSerializationAndRejectsUnknownValues() {
|
||||
val on = TouchGestureConfig(relativeMouseMode = TouchGestureConfig.RELATIVE_MOUSE_ON)
|
||||
assertEquals(TouchGestureConfig.RELATIVE_MOUSE_ON, TouchGestureConfig.fromJson(on.toJson()).relativeMouseMode)
|
||||
assertEquals(TouchGestureConfig.RELATIVE_MOUSE_AUTO, TouchGestureConfig.fromJson("""{"relativeMouseMode":9}""").relativeMouseMode)
|
||||
assertEquals(TouchGestureConfig.RELATIVE_MOUSE_AUTO, TouchGestureConfig.fromJson("{}").relativeMouseMode)
|
||||
}
|
||||
|
||||
@Test fun removedOptionsAreIgnoredWhenLoadingExistingSettings() {
|
||||
val old = """{"holdMouseButtonWhileTouchingEnabled":true,"holdMouseButtonWhileTouchingAction":"right_click",
|
||||
"showClickHighlight":true,"showCursorInTouchscreenMode":true,"tapAction":"key_E","longPressDelay":650}"""
|
||||
|
||||
@@ -4,19 +4,26 @@ import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SecondScreenModeTest {
|
||||
@Test fun withNothingRememberedTheControllerPicksThePanel() {
|
||||
@Test fun withNothingRememberedDeckPadsGetControlsAndOthersTheDashboard() {
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true))
|
||||
}
|
||||
|
||||
@Test fun withNothingRememberedAndNoDashboardTheControllerPicksThePanel() {
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false))
|
||||
}
|
||||
|
||||
@Test fun thePanelTheUserPickedLastOpensAgain() {
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("deck-controls", deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true))
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("deck-controls", deckPad = true))
|
||||
assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad = true))
|
||||
}
|
||||
|
||||
@Test fun deckControlsNeedTheDeckPad() {
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false, dashboard = true))
|
||||
}
|
||||
|
||||
@Test fun customControlsReopenWithEitherControllerType() {
|
||||
@@ -26,7 +33,26 @@ class SecondScreenModeTest {
|
||||
}
|
||||
|
||||
@Test fun anUnknownOrClosedChoiceFallsBackToTheDefault() {
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("gone", deckPad = false, dashboard = true))
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad = false))
|
||||
}
|
||||
|
||||
@Test fun theDashboardOpensAgainOnlyWhileItHasPages() {
|
||||
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = false))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("dashboard", deckPad = false))
|
||||
}
|
||||
|
||||
@Test fun theDesktopOpensAgainOnlyWhileItCanRun() {
|
||||
assertEquals(SecondScreenMode.DESKTOP, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true, desktop = true))
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("desktop", deckPad = false))
|
||||
}
|
||||
|
||||
@Test fun withNothingRememberedTheDesktopIsNeverPicked() {
|
||||
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true, desktop = true))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false, desktop = true))
|
||||
}
|
||||
}
|
||||
@@ -146,6 +146,19 @@ class SessionInputPointerTest {
|
||||
assertEquals(listOf(Triple(4, 1, 0)), CompositorShadow.events)
|
||||
}
|
||||
|
||||
@Test fun desktopRightCtrlUsesUpstreamAliasWithoutReleasingTheProfileHold() {
|
||||
fun hardwareCtrl(down: Boolean) = ReflectionHelpers.callInstanceMethod<Unit>(activity, "sendGuestKey",
|
||||
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 97),
|
||||
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, down),
|
||||
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8))
|
||||
output.key(29, true)
|
||||
hardwareCtrl(true)
|
||||
hardwareCtrl(false)
|
||||
assertEquals(listOf(29 to 1), CompositorShadow.keys)
|
||||
output.key(29, false)
|
||||
assertEquals(listOf(29 to 1, 29 to 0), CompositorShadow.keys)
|
||||
}
|
||||
|
||||
@Test fun routedMouseUsesRawBackendAndKeepsSharedButtonOwnership() {
|
||||
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
|
||||
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.KeyEvent
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
class SystemKeyCaptureTest {
|
||||
@Test fun systemCombinationsAreCaptured() {
|
||||
assertTrue(SystemKeyCapture.captures(KeyEvent.KEYCODE_META_LEFT, 0))
|
||||
assertTrue(SystemKeyCapture.captures(KeyEvent.KEYCODE_META_RIGHT, 0))
|
||||
assertTrue(SystemKeyCapture.captures(KeyEvent.KEYCODE_TAB, KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON))
|
||||
assertTrue(SystemKeyCapture.captures(KeyEvent.KEYCODE_ESCAPE, KeyEvent.META_ALT_ON))
|
||||
assertTrue(SystemKeyCapture.captures(KeyEvent.KEYCODE_D, KeyEvent.META_META_ON))
|
||||
}
|
||||
|
||||
@Test fun onlyTheEscapeScanCodeTurnsBackIntoEscape() {
|
||||
assertTrue(GuestKeys.isKeyboardEscape(KeyEvent.KEYCODE_BACK, 1))
|
||||
assertFalse(GuestKeys.isKeyboardEscape(KeyEvent.KEYCODE_BACK, 158))
|
||||
assertFalse(GuestKeys.isKeyboardEscape(KeyEvent.KEYCODE_ESCAPE, 1))
|
||||
}
|
||||
|
||||
@Test fun ordinaryKeysStayWithTheNormalPath() {
|
||||
assertFalse(SystemKeyCapture.captures(KeyEvent.KEYCODE_TAB, 0))
|
||||
assertFalse(SystemKeyCapture.captures(KeyEvent.KEYCODE_A, 0))
|
||||
assertFalse(SystemKeyCapture.captures(KeyEvent.KEYCODE_F, KeyEvent.META_ALT_ON))
|
||||
assertFalse(SystemKeyCapture.captures(KeyEvent.KEYCODE_C, KeyEvent.META_CTRL_ON))
|
||||
}
|
||||
}
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class SystemKeyCaptureHeldKeysTest {
|
||||
private val sent = mutableListOf<Int>()
|
||||
|
||||
private fun key(action: Int, repeat: Int = 0) =
|
||||
KeyEvent(0L, 0L, action, KeyEvent.KEYCODE_META_LEFT, repeat)
|
||||
|
||||
private fun attached(): Any = Any().also {
|
||||
SystemKeyCapture.isKeyboard = { true }
|
||||
SystemKeyCapture.attach(it, { true }) { event -> sent += event.action }
|
||||
}
|
||||
|
||||
@Test fun keyHeldThroughDetachIsReleasedOnceAndItsPhysicalReleaseIsConsumed() {
|
||||
val owner = attached()
|
||||
assertTrue(SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_DOWN)))
|
||||
SystemKeyCapture.detach(owner)
|
||||
assertEquals(listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP), sent)
|
||||
assertTrue(SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_DOWN, repeat = 1)))
|
||||
assertTrue(SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_UP)))
|
||||
assertEquals(2, sent.size)
|
||||
assertFalse(SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_UP)))
|
||||
}
|
||||
|
||||
@Test fun aKeyAlreadyHeldWhenCaptureStartsStaysWithAndroid() {
|
||||
val owner = attached()
|
||||
assertFalse(SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_DOWN, repeat = 1)))
|
||||
assertFalse(SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_UP)))
|
||||
SystemKeyCapture.detach(owner)
|
||||
assertEquals(0, sent.size)
|
||||
}
|
||||
|
||||
@Test fun newPressAfterDetachIsNotSwallowed() {
|
||||
val owner = attached()
|
||||
SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_DOWN))
|
||||
SystemKeyCapture.detach(owner)
|
||||
assertFalse(SystemKeyCapture.onKeyEvent(key(KeyEvent.ACTION_DOWN)))
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,9 @@ class TouchpadGesturesTest {
|
||||
override fun onScroll(dx: Float, dy: Float) { events += "scroll" }
|
||||
override fun onScrollEnd() { events += "scroll end" }
|
||||
override fun onZoom(steps: Int) { events += "zoom $steps" }
|
||||
override fun onThreeFingerTap(): Boolean { events += "three tap"; return claimThreeTap }
|
||||
}
|
||||
private var claimThreeTap = false
|
||||
|
||||
@Before fun setUp() {
|
||||
touchpad = TouchpadGestures(SLOP, listener)
|
||||
@@ -50,7 +52,18 @@ class TouchpadGesturesTest {
|
||||
assertEquals(listOf("left down", "left up"), events)
|
||||
}
|
||||
|
||||
@Test fun threeFingerTapClicksTheMiddleButton() {
|
||||
@Test fun threeFingerTapClicksTheMiddleButtonWhenUnclaimed() {
|
||||
threeFingerTap()
|
||||
assertEquals(listOf("three tap", "middle down", "middle up"), events)
|
||||
}
|
||||
|
||||
@Test fun claimedThreeFingerTapSkipsTheMiddleButton() {
|
||||
claimThreeTap = true
|
||||
threeFingerTap()
|
||||
assertEquals(listOf("three tap"), events)
|
||||
}
|
||||
|
||||
private fun threeFingerTap() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f))
|
||||
@@ -61,7 +74,6 @@ class TouchpadGesturesTest {
|
||||
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 310f))
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
|
||||
advance(100)
|
||||
assertEquals(listOf("middle down", "middle up"), events)
|
||||
}
|
||||
|
||||
@Test fun desktopTwoFingerSlideScrollsSmoothlyAndStops() {
|
||||
|
||||
@@ -738,7 +738,7 @@ class TouchscreenGesturesTest {
|
||||
@Test fun pinchReversalDoesNotConsumeOldDirectionRemainder() {
|
||||
startPinch()
|
||||
events.clear()
|
||||
movePinch(4.5f) // Nine pixels toward zooming in, short of a step.
|
||||
movePinch(4.5f)
|
||||
assertTrue(events.none { it.startsWith("wheel") })
|
||||
for (i in 1..10) movePinch(4.5f - i * .5f)
|
||||
assertEquals(listOf("wheel 1"), events.filter { it.startsWith("wheel") })
|
||||
@@ -794,16 +794,13 @@ class TouchscreenGesturesTest {
|
||||
override fun moveTo(x: Float, y: Float) { cachedX = x; clientX = x }
|
||||
override fun prepareRelativePan() { cachedX = 960f; clientX = 960f }
|
||||
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {
|
||||
// Before pointer lock, the compositor delivers an absolute
|
||||
// position even when we inject a relative delta. The game
|
||||
// only requests lock after seeing this first pan movement.
|
||||
cachedX += dx
|
||||
clientX = cachedX
|
||||
}
|
||||
override fun button(code: Int, down: Boolean) {
|
||||
if (code == 274) {
|
||||
middleDown = down
|
||||
if (down) clientX = 960f // The client warps to the middle when pan starts.
|
||||
if (down) clientX = 960f
|
||||
}
|
||||
}
|
||||
override fun key(code: Int, down: Boolean) {}
|
||||
|
||||
@@ -259,6 +259,78 @@ class BattleNetTest {
|
||||
BattleNet.hostFolder(context, "Z:/root/Games/Stores/Battle.net/Hearthstone/"))
|
||||
}
|
||||
|
||||
@Test fun wowForeverIsListedBesideRetailInTheSharedWorldOfWarcraftFolder() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
val wow = File(pfx, "drive_c/Program Files (x86)/World of Warcraft").apply { mkdirs() }
|
||||
File(wow, "_retail_").mkdirs()
|
||||
File(wow, "_forever_").mkdirs()
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
|
||||
field(1, message(field(1, "wow"), field(2, "wow"), field(3, message(field(1, "C:/Program Files (x86)/World of Warcraft"))))),
|
||||
field(1, message(field(1, "wow_forever"), field(2, "wowf"), field(3, message(field(1, "C:/Program Files (x86)/World of Warcraft"))))),
|
||||
))
|
||||
val games = BattleNet.games(context)
|
||||
assertEquals(listOf("WoW", "WoWF"), games.map { it.code })
|
||||
assertEquals(listOf(wow, File(wow, "_forever_")), games.map { it.folder })
|
||||
assertEquals("World of Warcraft: Forever", games[1].name)
|
||||
assertEquals(2, games.map { it.folder.canonicalPath }.distinct().size)
|
||||
val shortcut = BattleNet.shortcut(context, games[1])!!
|
||||
assertTrue(shortcut.launchOptions.endsWith("--exec=\"launch WoWF\""))
|
||||
}
|
||||
|
||||
@Test fun anInstallWithAnUnknownUidIsListedByItsProductCode() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
File(pfx, "drive_c/Games/World of Warcraft").mkdirs()
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
|
||||
field(1, message(field(1, "wowf_live"), field(2, "wowf"), field(3, message(field(1, "C:/Games/World of Warcraft"))))),
|
||||
field(1, message(field(1, "unknown_thing"), field(2, "nothing"), field(3, message(field(1, "C:/Games/World of Warcraft"))))),
|
||||
))
|
||||
val games = BattleNet.games(context)
|
||||
assertEquals(listOf("WoWF"), games.map { it.code })
|
||||
assertEquals("wowf_live", games[0].installUid)
|
||||
assertEquals("wow_forever", games[0].uid)
|
||||
assertEquals("WoWF", BattleNet.titleForProduct("WOWF")?.code)
|
||||
assertEquals("WTCG", BattleNet.titleForProduct("wtcg")?.code)
|
||||
assertNull(BattleNet.titleForProduct(""))
|
||||
assertEquals(listOf(Triple("wowf_live", "C:/Games/World of Warcraft", "wowf")),
|
||||
BattleNet.productDbInstalls(message(field(1, message(field(1, "wowf_live"), field(2, "wowf"), field(3, message(field(1, "C:/Games/World of Warcraft")))))))!!
|
||||
.map { Triple(it.uid, it.path, it.product) })
|
||||
}
|
||||
|
||||
@Test fun aGameKeepsTheFolderItWasListedWithWhenAnotherVersionComesOrGoes() {
|
||||
val root = File(context.filesDir, "World of Warcraft").apply { mkdirs() }
|
||||
val retailDir = File(root, "_retail_").apply { mkdirs() }
|
||||
val foreverDir = File(root, "_forever_").apply { mkdirs() }
|
||||
val wow = BattleNet.title("wow")!!
|
||||
val forever = BattleNet.title("wow_forever")!!
|
||||
val classic = BattleNet.title("wow_classic")!!
|
||||
assertEquals(mapOf("WoWF" to root), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to null)))
|
||||
assertEquals(mapOf("WoW" to root, "WoWF" to foreverDir),
|
||||
BattleNet.ownFolders(linkedMapOf("WoW" to (wow to root), "WoWF" to (forever to root)), mapOf("WoW" to null, "WoWF" to null)))
|
||||
assertEquals(mapOf("WoWF" to foreverDir), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to foreverDir.path)))
|
||||
assertEquals(mapOf("WoW" to retailDir, "WoWC" to root),
|
||||
BattleNet.ownFolders(linkedMapOf("WoW" to (wow to root), "WoWC" to (classic to root)), mapOf("WoW" to null, "WoWC" to root.path)))
|
||||
assertEquals(mapOf("WoW" to root, "WoWC" to root),
|
||||
BattleNet.ownFolders(linkedMapOf("WoW" to (wow to root), "WoWC" to (classic to root)), mapOf("WoW" to null, "WoWC" to null)))
|
||||
assertEquals(mapOf("WoWF" to root), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to "/elsewhere")))
|
||||
}
|
||||
|
||||
@Test fun theListedFolderIsRememberedAcrossScans() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
val wow = File(pfx, "drive_c/Program Files (x86)/World of Warcraft").apply { mkdirs() }
|
||||
File(wow, "_forever_").mkdirs()
|
||||
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").apply { parentFile!!.mkdirs() }
|
||||
val retail = field(1, message(field(1, "wow"), field(2, "wow"), field(3, message(field(1, "C:/Program Files (x86)/World of Warcraft")))))
|
||||
val forever = field(1, message(field(1, "wow_forever"), field(2, "wowf"), field(3, message(field(1, "C:/Program Files (x86)/World of Warcraft")))))
|
||||
db.writeBytes(message(retail, forever))
|
||||
assertEquals(listOf(wow, File(wow, "_forever_")), BattleNet.games(context).map { it.folder })
|
||||
db.writeBytes(message(forever))
|
||||
assertEquals(listOf(File(wow, "_forever_")), BattleNet.games(context).map { it.folder })
|
||||
db.writeBytes(message(forever, retail))
|
||||
assertEquals(listOf(File(wow, "_forever_"), wow), BattleNet.games(context).map { it.folder })
|
||||
}
|
||||
|
||||
@Test fun aGamesShortcutHasBattleNetLaunchItInItsPrefix() {
|
||||
val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() }
|
||||
File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a))
|
||||
@@ -291,6 +363,7 @@ class BattleNetTest {
|
||||
assertEquals(codes.distinct(), codes)
|
||||
assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes)
|
||||
assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" })
|
||||
assertFalse(BattleNet.STORE.any { it.code == "WoWC" || it.code == "WoWF" })
|
||||
assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid)
|
||||
assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) })
|
||||
val installed = listOf("fenris", "diablo3_enus", null)
|
||||
|
||||
@@ -119,6 +119,27 @@ class BwrapSpawnerPlanTest {
|
||||
assertEquals("org.example.Game", plan.env["FLATPAK_ID"])
|
||||
}
|
||||
|
||||
@Test fun sandboxesStartThroughTheirOwnEnvByDefault() {
|
||||
val plan = BwrapSpawner.plan(RuntimeEnvironment.getApplication(), request(op("t" to "dir", "dest" to "/tmp")), dir)
|
||||
assertEquals("/usr/bin/env", plan.envTool)
|
||||
}
|
||||
|
||||
@Test fun fexSandboxesStartThroughTheEnvTheyBringAndSkipArmPreloads() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
val lib = File(rootfs, "usr/local/lib/libblsession.so").apply { parentFile?.mkdirs(); writeText("") }
|
||||
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libblsession.so\n") }
|
||||
try {
|
||||
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp"))
|
||||
.put("envTool", "/run/droiddeck-fex/bin/env"), dir)
|
||||
assertEquals("/run/droiddeck-fex/bin/env", plan.envTool)
|
||||
assertFalse(plan.env.containsKey("LD_PRELOAD"))
|
||||
assertFalse(plan.binds.any { it.guest.startsWith("/run/droiddeck-preload") })
|
||||
} finally {
|
||||
listOf(lib, preload).forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sandboxedAppsSeeTheSessionsNetworkLink() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import java.util.Locale
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DesktopLanguageTest {
|
||||
private val sha = "a".repeat(64)
|
||||
|
||||
@Test fun indexListsPacksAndSkipsMalformedLines() {
|
||||
val index = DesktopLanguage.parseIndex("pt_BR $sha 1200\ntr $sha 900\nbad line\nxx short 5\n")
|
||||
assertEquals(setOf("pt_BR", "tr"), index.keys)
|
||||
assertTrue(DesktopLanguage.parseIndex("../../x $sha 5\n").isEmpty())
|
||||
assertEquals(1200L, index.getValue("pt_BR").size)
|
||||
}
|
||||
|
||||
@Test fun regionPackThenBareLanguage() {
|
||||
assertEquals(listOf("pt_BR", "pt"), DesktopLanguage.candidates(Locale.forLanguageTag("pt-BR")))
|
||||
assertEquals(listOf("tr_TR", "tr"), DesktopLanguage.candidates(Locale.forLanguageTag("tr")))
|
||||
assertEquals(listOf("zh_HK", "zh_TW", "zh"), DesktopLanguage.candidates(Locale.forLanguageTag("zh-HK")))
|
||||
}
|
||||
|
||||
@Test fun englishAndUnknownNeedNoPack() {
|
||||
assertTrue(DesktopLanguage.candidates(Locale.forLanguageTag("en")).isEmpty())
|
||||
assertTrue(DesktopLanguage.candidates(Locale.forLanguageTag("sw")).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun packsLiveBesideTheKdeArchive() {
|
||||
assertEquals("https://h/r/t/", DesktopLanguage.baseUrl("https://h/r/t/desktop-kde.tar.zst"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
class FlatpakManagerArchTest {
|
||||
private lateinit var dir: File
|
||||
|
||||
@Before fun setUp() {
|
||||
dir = Files.createTempDirectory("flatpak-arch").toFile()
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
|
||||
private fun install(arch: String, branch: String) {
|
||||
File(dir, "$arch/$branch/active").mkdirs()
|
||||
}
|
||||
|
||||
@Test fun armDevicesAlsoListX86Builds() {
|
||||
assertEquals(listOf("aarch64", "x86_64"), FlatpakManager.arches("aarch64"))
|
||||
assertEquals(listOf("x86_64"), FlatpakManager.arches("x86_64"))
|
||||
}
|
||||
|
||||
@Test fun anX86OnlyInstallIsFound() {
|
||||
install("x86_64", "master")
|
||||
val (arch, branch) = FlatpakManager.installedBranch(dir, "aarch64")!!
|
||||
assertEquals("x86_64", arch)
|
||||
assertEquals("master", branch.name)
|
||||
}
|
||||
|
||||
@Test fun theNativeBuildWinsWhenBothAreInstalled() {
|
||||
install("x86_64", "master")
|
||||
install("aarch64", "stable")
|
||||
assertEquals("aarch64", FlatpakManager.installedBranch(dir, "aarch64")!!.first)
|
||||
}
|
||||
|
||||
@Test fun aBranchWithoutAnActiveDeployIsNotInstalled() {
|
||||
File(dir, "x86_64/master").mkdirs()
|
||||
assertNull(FlatpakManager.installedBranch(dir, "aarch64"))
|
||||
}
|
||||
|
||||
@Test fun x86BuildsOnArmLaunchWithTheirArch() {
|
||||
val x86 = FlatpakManager.App("io.github.ebkr.r2modman", "r2modman", null, "master", null, "x86_64")
|
||||
val arm = FlatpakManager.App("org.example.App", "App", null, "stable", null, "aarch64")
|
||||
assertEquals(listOf("--arch=x86_64", "io.github.ebkr.r2modman"), FlatpakManager.launchArgs(x86, "aarch64"))
|
||||
assertEquals(listOf("org.example.App"), FlatpakManager.launchArgs(arm, "aarch64"))
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@ class BootMovieLibraryTest {
|
||||
|
||||
private fun movie(name: String) = File(movies, name).also { it.parentFile!!.mkdirs(); it.writeText("movie") }
|
||||
|
||||
/** A movie DroidDeck itself imported: kept in the library, copied into Steam's folder and noted in the list. */
|
||||
private fun imported(title: String, source: String = BootMovieLibrary.SOURCE_IMPORT, repo: String? = null): String {
|
||||
val staged = File(BootMovieLibrary.libraryDir(app), ".t-${System.nanoTime()}-${Thread.currentThread().id}.staged").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
|
||||
return BootMovieLibrary.commit(app, staged, title, source, repo)!!
|
||||
@@ -258,11 +257,9 @@ class BootMovieLibraryTest {
|
||||
steamPicks("b.webm")
|
||||
assertTrue(BootMovie.syncFromSteam(app))
|
||||
assertEquals("file:b.webm", BootMovie.choice(app))
|
||||
// Picking another one here is not undone by the same Steam setting.
|
||||
BootMovie.select(app, "file:a.webm")
|
||||
assertFalse(BootMovie.syncFromSteam(app))
|
||||
assertEquals("file:a.webm", BootMovie.choice(app))
|
||||
// A new pick inside Steam is adopted again.
|
||||
movie("c.webm")
|
||||
steamPicks("c.webm")
|
||||
assertTrue(BootMovie.syncFromSteam(app))
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class BottomDesktopSizeTest {
|
||||
@Test fun theDuosBottomPanelKeepsItsPixels() {
|
||||
assertEquals(1280 to 848, desktopOutputSize(1280, 848, false, 720f))
|
||||
}
|
||||
|
||||
@Test fun aLargerPanelRendersBelowItsResolution() {
|
||||
assertEquals(826 to 646, desktopOutputSize(1240, 970, false, 720f))
|
||||
assertEquals(1280 to 644, desktopOutputSize(1920, 968, false, 720f))
|
||||
}
|
||||
|
||||
@Test fun theTopScreenAfterASwapGetsItsOwnPixelsAndTheWideShape() {
|
||||
assertEquals(1920 to 968, desktopOutputSize(1920, 968, true, 720f))
|
||||
assertEquals(1920 to 968, desktopOutputSize(1920, 969, true, 720f))
|
||||
}
|
||||
|
||||
@Test fun noPanelNoSize() {
|
||||
assertEquals(0 to 0, desktopOutputSize(0, 848, true, 720f))
|
||||
assertEquals(0 to 0, desktopOutputSize(1280, 0, false, 720f))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BottomNotificationsTest {
|
||||
private val own = "com.droiddeck.launcher"
|
||||
|
||||
@Test fun messagesFromOtherAppsAreKept() {
|
||||
assertTrue(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = false, title = "Kurt", text = "ready?"))
|
||||
}
|
||||
|
||||
@Test fun ownOngoingSummaryAndEmptyNotificationsAreSkipped() {
|
||||
assertFalse(BottomNotifications.keep(own, own, ongoing = false, groupSummary = false, title = "Session", text = "running"))
|
||||
assertFalse(BottomNotifications.keep(own, "com.spotify", ongoing = true, groupSummary = false, title = "Song", text = "Artist"))
|
||||
assertFalse(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = true, title = "2 messages", text = ""))
|
||||
assertFalse(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = false, title = " ", text = ""))
|
||||
}
|
||||
|
||||
@Test fun anUpdatedNotificationMovesToTheTopOnce() {
|
||||
val list = mutableListOf(
|
||||
BottomNotification("a", "App", "one", "", 1L),
|
||||
BottomNotification("b", "App", "two", "", 2L),
|
||||
)
|
||||
BottomNotifications.add(list, BottomNotification("b", "App", "two again", "", 3L))
|
||||
assertEquals(listOf("b", "a"), list.map { it.key })
|
||||
assertEquals("two again", list.first().title)
|
||||
}
|
||||
|
||||
@Test fun theListKeepsTheNewestThirty() {
|
||||
val list = mutableListOf<BottomNotification>()
|
||||
repeat(35) { BottomNotifications.add(list, BottomNotification("k$it", "App", "t$it", "", it.toLong())) }
|
||||
assertEquals(30, list.size)
|
||||
assertEquals("k34", list.first().key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class BottomScreenshotsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun fileNamesSortByTime() {
|
||||
val name = BottomScreenshots.fileName(0L)
|
||||
assertTrue(name, name.startsWith("DroidDeck_") && name.endsWith(".jpg"))
|
||||
assertEquals(29, name.length)
|
||||
}
|
||||
|
||||
@Test fun steamScreenshotsAreFoundAndThumbnailsSkipped() {
|
||||
val root = tmp.root
|
||||
val shots = File(root, "root/.local/share/Steam/userdata/2932373/760/remote/220/screenshots")
|
||||
File(shots, "thumbnails").mkdirs()
|
||||
File(shots, "20261031010101_1.jpg").writeText("x")
|
||||
File(shots, "thumbnails/20261031010101_1.jpg").writeText("x")
|
||||
File(shots, "screenshots.vdf").writeText("x")
|
||||
val x64 = File(root, "root/.droiddeck-x64/.local/share/Steam/userdata/2932373/760/remote/440/screenshots")
|
||||
x64.mkdirs()
|
||||
File(x64, "20261031020202_1.jpg").writeText("x")
|
||||
val found = BottomScreenshots.steam(root).map { it.file!!.name }.sorted()
|
||||
assertEquals(listOf("20261031010101_1.jpg", "20261031020202_1.jpg"), found)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.gpu.AppVulkan
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class BridgeDxvkTest {
|
||||
private val old = ComponentsManager.DXVK_FOR_VULKAN_1_1
|
||||
private val mid = ComponentsManager.DXVK_FOR_VULKAN_1_3_NO_INT64
|
||||
private lateinit var context: Context
|
||||
|
||||
private val g710 = AppVulkan(1, 1, shaderInt64 = false, maxPushConstants = 128, source = "driver")
|
||||
private val promoted = g710.copy(minor = 2, source = "bridge")
|
||||
private val full = AppVulkan(1, 3, shaderInt64 = true, maxPushConstants = 256, source = "driver")
|
||||
private val mali = GpuInfo("Mali-G710", 0, GpuInfo.Family.NOT_ADRENO, "", false)
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
File(context.filesDir, "components").deleteRecursively()
|
||||
LinuxRuntime.rootDir(context).deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun theNewestDxvkThatStartsIsChosen() {
|
||||
assertEquals(old, ComponentsManager.bridgeDxvk(g710)?.file)
|
||||
assertEquals(old, ComponentsManager.bridgeDxvk(promoted)?.file)
|
||||
assertEquals(mid, ComponentsManager.bridgeDxvk(full.copy(shaderInt64 = false))?.file)
|
||||
assertEquals(mid, ComponentsManager.bridgeDxvk(full.copy(maxPushConstants = 128))?.file)
|
||||
assertNull(ComponentsManager.bridgeDxvk(full))
|
||||
assertNull(ComponentsManager.bridgeDxvk(full.copy(shaderInt64 = null, maxPushConstants = null)))
|
||||
assertNull(ComponentsManager.bridgeDxvk(AppVulkan(1, 0, null, null, "driver")))
|
||||
assertNull(ComponentsManager.bridgeDxvk(null))
|
||||
assertEquals("Dxvk-Linux", ComponentsManager.bridgeDxvk(g710)?.release)
|
||||
assertEquals("dxvk", ComponentsManager.bridgeDxvk(g710)?.comp)
|
||||
}
|
||||
|
||||
@Test fun theDriversLinesAreRead() {
|
||||
val vk = AppVulkan.fromDriver(mapOf("device" to "Mali-G710 MC10", "api" to "1.1.177", "shader_int64" to "no", "max_push_constants" to "128"))
|
||||
assertEquals(g710, vk)
|
||||
assertNull(AppVulkan.fromDriver(mapOf("error" to "no Vulkan device")))
|
||||
assertNull(AppVulkan.fromDriver(mapOf("api" to "garbage")))
|
||||
val older = AppVulkan.fromDriver(mapOf("api" to "1.3.250"))!!
|
||||
assertNull(older.shaderInt64)
|
||||
assertNull(older.maxPushConstants)
|
||||
}
|
||||
|
||||
@Test fun theBridgesFileWinsForItsOwnGpuOnly() {
|
||||
val text = "device=Mali-G710 MC10\napi=1.2.177\ndriver_api=1.1.177\npromotion=on\nshader_int64=0\nmax_push_constants=128\n"
|
||||
val on = promoted.copy(source = "bridge, promoted")
|
||||
assertEquals(on, AppVulkan.fromBridgeFile(text, "Mali-G710 MC10"))
|
||||
assertEquals(on, AppVulkan.fromBridgeFile(text, null))
|
||||
assertEquals(on, AppVulkan.fromBridgeFile(text, "Mali-G710 MC10", "1.1.177"))
|
||||
assertNull(AppVulkan.fromBridgeFile(text, "Mali-G720 Immortalis MC12"))
|
||||
assertNull(AppVulkan.fromBridgeFile("device=x\n", null))
|
||||
}
|
||||
|
||||
@Test fun withoutPromotionOnTheDriversVersionCounts() {
|
||||
val g710File = g710.copy(source = "bridge")
|
||||
val off = "device=Mali-G710 MC10\napi=1.1.177\ndriver_api=1.1.177\npromotion=off\nshader_int64=0\nmax_push_constants=128\n"
|
||||
assertEquals(g710File, AppVulkan.fromBridgeFile(off, "Mali-G710 MC10", "1.1.177"))
|
||||
val old = "device=Mali-G710 MC10\napi=1.3.177\ndriver_api=1.1.177\nshader_int64=0\nmax_push_constants=128\n"
|
||||
assertEquals(g710File, AppVulkan.fromBridgeFile(old, "Mali-G710 MC10"))
|
||||
assertNull(AppVulkan.fromBridgeFile(off, "Mali-G710 MC10", "1.3.212"))
|
||||
}
|
||||
|
||||
@Test fun anAdrenoSessionIsNotTouched() {
|
||||
proton("proton-exp")
|
||||
assertNull(run(g710, bridge = false))
|
||||
}
|
||||
|
||||
@Test fun aShippedDxvk3IsReplacedOnAVulkan11Phone() {
|
||||
proton("proton-exp")
|
||||
proton("ge")
|
||||
val applied = mutableListOf<String>()
|
||||
val result = run(g710, applyAuto = { id, file -> applied += "$id $file"; "swapped $id" })
|
||||
assertEquals(listOf("ge $old", "proton-exp $old"), applied.sorted())
|
||||
assertTrue(result!!.startsWith("Vulkan 1.1, shaderInt64 no, push constants 128 (driver): DXVK $old"))
|
||||
}
|
||||
|
||||
@Test fun thePlayersOwnChoiceIsKept() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", JSONObject().put("file", "dxvk-3.1-linux.wcp").put("protonVersion", "experimental-11"))
|
||||
assertNull(run(g710))
|
||||
assertNull(run(full))
|
||||
}
|
||||
|
||||
@Test fun anAutomaticChoiceFollowsTheDevice() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", JSONObject().put("file", mid).put("protonVersion", "experimental-11").put("auto", true))
|
||||
val applied = mutableListOf<String>()
|
||||
run(g710, applyAuto = { id, file -> applied += "$id $file"; "swapped" })
|
||||
assertEquals(listOf("proton-exp $old"), applied)
|
||||
|
||||
writeState("proton-exp", JSONObject().put("file", old).put("protonVersion", "experimental-11").put("auto", true))
|
||||
assertNull(run(g710))
|
||||
val undone = mutableListOf<String>()
|
||||
run(full, undoAuto = { id, comp -> undone += "$id $comp"; "undone" })
|
||||
assertEquals(listOf("proton-exp dxvk"), undone)
|
||||
}
|
||||
|
||||
@Test fun theSwapAndItsUndoReachTheProton() {
|
||||
proton("proton-exp")
|
||||
val d3d11 = File(protonDir("proton-exp"), "files/lib/wine/dxvk/aarch64-windows/d3d11.dll")
|
||||
writePackage(old, "DXVK 1.10.3")
|
||||
val auto: (String, String) -> String = { id, file -> ComponentsManager.swap(context, id, file, auto = true) }
|
||||
val undo: (String, String) -> String = { id, comp -> ComponentsManager.undoAutoChoice(context, id, comp) }
|
||||
|
||||
assertNotNull(run(g710, applyAuto = auto, undoAuto = undo))
|
||||
assertEquals("DXVK 1.10.3", d3d11.readText())
|
||||
val entry = state().getJSONObject("active").getJSONObject("proton-exp").getJSONObject("dxvk")
|
||||
assertEquals(old, entry.getString("file"))
|
||||
assertTrue(entry.getBoolean("auto"))
|
||||
assertNull(run(g710, applyAuto = auto, undoAuto = undo))
|
||||
|
||||
run(full, applyAuto = auto, undoAuto = undo)
|
||||
assertEquals("bundled DXVK experimental-11", d3d11.readText())
|
||||
assertNull(state().getJSONObject("active").optJSONObject("proton-exp")?.optJSONObject("dxvk"))
|
||||
}
|
||||
|
||||
@Test fun aFailedDetectionKeepsTheLastAutomaticChoice() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", JSONObject().put("file", old).put("protonVersion", "experimental-11").put("auto", true))
|
||||
assertNull(run(null))
|
||||
assertEquals(old, state().getJSONObject("active").getJSONObject("proton-exp").getJSONObject("dxvk").getString("file"))
|
||||
}
|
||||
|
||||
@Test fun oneProtonFailingDoesNotStopTheOthers() {
|
||||
proton("ge")
|
||||
proton("proton-exp")
|
||||
val applied = mutableListOf<String>()
|
||||
val result = run(g710, applyAuto = { id, file -> if (id == "ge") error("disk full"); applied += "$id $file"; "swapped $id" })
|
||||
assertEquals(listOf("proton-exp $old"), applied)
|
||||
assertTrue(result!!, result.contains("disk full") && result.contains("swapped proton-exp"))
|
||||
}
|
||||
|
||||
@Test fun aChoiceWhoseSavedCopyIsGoneIsKept() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", JSONObject().put("file", old).put("label", "DXVK 1.10.3").put("protonVersion", "experimental-11").put("auto", true))
|
||||
val result = run(full, undoAuto = { id, comp -> ComponentsManager.undoAutoChoice(context, id, comp) })
|
||||
assertTrue(result!!, result.contains("its own copy is gone"))
|
||||
assertEquals(old, state().getJSONObject("active").getJSONObject("proton-exp").getJSONObject("dxvk").getString("file"))
|
||||
}
|
||||
|
||||
@Test fun aProtonUpdateWithNoRuleLeftJustForgetsTheChoice() {
|
||||
proton("proton-exp", "experimental-12")
|
||||
writeState("proton-exp", JSONObject().put("file", old).put("protonVersion", "experimental-11").put("auto", true))
|
||||
run(full, undoAuto = { id, comp -> ComponentsManager.undoAutoChoice(context, id, comp) })
|
||||
assertNull(state().getJSONObject("active").optJSONObject("proton-exp")?.optJSONObject("dxvk"))
|
||||
assertEquals("bundled DXVK experimental-12", File(protonDir("proton-exp"), "files/lib/wine/dxvk/aarch64-windows/d3d11.dll").readText())
|
||||
}
|
||||
|
||||
@Test fun thePlayerCanKeepProtonsOwnDxvk() {
|
||||
proton("proton-exp")
|
||||
assertNull("nothing chosen when declined", run(g710, keep = true))
|
||||
writeState("proton-exp", JSONObject().put("file", old).put("protonVersion", "experimental-11").put("auto", true))
|
||||
val undone = mutableListOf<String>()
|
||||
run(g710, keep = true, undoAuto = { id, comp -> undone += "$id $comp"; "undone" })
|
||||
assertEquals("an earlier automatic choice goes back", listOf("proton-exp dxvk"), undone)
|
||||
}
|
||||
|
||||
@Test fun turningTheBridgeOffRestoresProtonsOwn() {
|
||||
proton("proton-exp")
|
||||
val d3d11 = File(protonDir("proton-exp"), "files/lib/wine/dxvk/aarch64-windows/d3d11.dll")
|
||||
writePackage(old, "DXVK 1.10.3")
|
||||
val auto: (String, String) -> String = { id, file -> ComponentsManager.swap(context, id, file, auto = true) }
|
||||
val undo: (String, String) -> String = { id, comp -> ComponentsManager.undoAutoChoice(context, id, comp) }
|
||||
run(g710, applyAuto = auto, undoAuto = undo)
|
||||
assertEquals("DXVK 1.10.3", d3d11.readText())
|
||||
run(null, bridge = false, applyAuto = auto, undoAuto = undo)
|
||||
assertEquals("bundled DXVK experimental-11", d3d11.readText())
|
||||
assertNull(state().getJSONObject("active").optJSONObject("proton-exp")?.optJSONObject("dxvk"))
|
||||
}
|
||||
|
||||
@Test fun turningTheBridgeOffKeepsThePlayersOwnChoice() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", JSONObject().put("file", "dxvk-3.1-linux.wcp").put("protonVersion", "experimental-11"))
|
||||
assertNull(run(g710, bridge = false))
|
||||
assertNull(run(g710, keep = true))
|
||||
}
|
||||
|
||||
@Test fun aQueuedAutomaticSwapIsDroppedWhenTheBridgeIsOff() {
|
||||
proton("proton-exp")
|
||||
val f = File(context.filesDir, "components/state.json")
|
||||
f.parentFile!!.mkdirs()
|
||||
f.writeText(JSONObject().put("active", JSONObject())
|
||||
.put("queued", JSONObject().put("proton-exp", JSONObject()
|
||||
.put("dxvk", JSONObject().put("kind", "package").put("file", old).put("auto", true))
|
||||
.put("vkd3d", JSONObject().put("kind", "package").put("file", "vkd3d-x.wcp")))).toString())
|
||||
assertNull(run(null, bridge = false))
|
||||
val q = state().getJSONObject("queued").getJSONObject("proton-exp")
|
||||
assertFalse(q.has("dxvk"))
|
||||
assertTrue("the player's own queued swap stays", q.has("vkd3d"))
|
||||
}
|
||||
|
||||
@Test fun whenAutomaticChoicesAreUndone() {
|
||||
val rule = ComponentsManager.bridgeDxvk(g710)
|
||||
assertTrue(ComponentsManager.autoDxvkUndoWanted(false, false, null, null))
|
||||
assertTrue(ComponentsManager.autoDxvkUndoWanted(true, true, g710, null))
|
||||
assertTrue(ComponentsManager.autoDxvkUndoWanted(true, false, full, null))
|
||||
assertFalse("failed detection keeps it", ComponentsManager.autoDxvkUndoWanted(true, false, null, null))
|
||||
assertFalse(ComponentsManager.autoDxvkUndoWanted(true, false, g710, rule))
|
||||
}
|
||||
|
||||
private fun run(
|
||||
vk: AppVulkan?,
|
||||
bridge: Boolean = true,
|
||||
keep: Boolean = false,
|
||||
applyAuto: (String, String) -> String = { id, file -> error("apply $id $file") },
|
||||
undoAuto: (String, String) -> String = { id, comp -> error("undo $id $comp") },
|
||||
) = ComponentsManager.ensureForcedPackages(
|
||||
context, mali,
|
||||
lookup = { file, release -> ComponentsManager.CatalogItem(file, "dxvk", release, "https://example.invalid/$file", 4, "sha256:" + "ab".repeat(32)) },
|
||||
fetch = {},
|
||||
apply = { id, file -> error("non-automatic apply $id $file") },
|
||||
vulkan = vk, bridgeSession = bridge, applyAuto = applyAuto, undoAuto = undoAuto, keepProtonDxvk = keep,
|
||||
)
|
||||
|
||||
private fun protonDir(name: String) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
|
||||
|
||||
private fun proton(name: String, version: String = "experimental-11") {
|
||||
val dir = protonDir(name)
|
||||
File(dir, "files/lib/wine").mkdirs()
|
||||
File(dir, "proton").writeText("#!/bin/sh\n")
|
||||
File(dir, "version").writeText("1 $version\n")
|
||||
File(dir, "files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("bundled DXVK $version")
|
||||
}
|
||||
}
|
||||
|
||||
private fun state() = JSONObject(File(context.filesDir, "components/state.json").readText())
|
||||
|
||||
private fun writeState(protonId: String, dxvk: JSONObject) {
|
||||
val f = File(context.filesDir, "components/state.json")
|
||||
f.parentFile!!.mkdirs()
|
||||
f.writeText(JSONObject().put("active", JSONObject().put(protonId, JSONObject().put("dxvk", dxvk)))
|
||||
.put("queued", JSONObject()).toString())
|
||||
}
|
||||
|
||||
private fun writePackage(file: String, d3d11: String) {
|
||||
val dest = File(context.filesDir, "components/packages/$file")
|
||||
dest.parentFile!!.mkdirs()
|
||||
TarArchiveOutputStream(ZstdOutputStream(dest.outputStream())).use { tar ->
|
||||
fun put(name: String, bytes: ByteArray) {
|
||||
tar.putArchiveEntry(TarArchiveEntry(name).apply { size = bytes.size.toLong() })
|
||||
tar.write(bytes)
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
put("./profile.json", JSONObject().put("type", "DXVK-Linux").put("versionName", file.removeSuffix(".wcp")).toString().toByteArray())
|
||||
put("./files/lib/wine/dxvk/aarch64-windows/d3d11.dll", d3d11.toByteArray())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,11 +55,9 @@ class ComponentsNightlyCatalogTest {
|
||||
val nVkEc = item("DD-vkd3d-proton-arm64ec-3.0.1+455-nightly.wcp", "vkd3d", n)
|
||||
val pairs = ComponentsManager.nightlyPairs(listOf(dxvk, ec, gpl, fex, vk) + others + listOf(nDxvk, nEc, nGpl, nFex, nVk, nVkEc))
|
||||
assertEquals(mapOf(dxvk to nDxvk, ec to nEc, gpl to nGpl, fex to nFex, vk to nVk), pairs)
|
||||
// Two nightlies for one stable build: the newer one wins.
|
||||
val nDxvkNewer = item("DD-dxvk-3.1.1+154-nightly.wcp", "dxvk", n)
|
||||
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvkNewer, nDxvk)))
|
||||
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvk, nDxvkNewer)))
|
||||
// A nightly of a version with no stable build pairs with nothing.
|
||||
assertEquals(emptyMap<Any, Any>(), ComponentsManager.nightlyPairs(listOf(item("dxvk-3.1-linux.wcp", "dxvk", "Dxvk-Linux"), nDxvk)))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import java.util.Locale
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DesktopLocaleTest {
|
||||
private fun lang(tag: String) = DesktopLocale.lang(Locale.forLanguageTag(tag))
|
||||
|
||||
@Test fun appLanguagesMapToGlibcLocales() {
|
||||
assertEquals("en_US.UTF-8", lang("en"))
|
||||
assertEquals("tr_TR.UTF-8", lang("tr"))
|
||||
assertEquals("pt_BR.UTF-8", lang("pt-BR"))
|
||||
assertEquals("pt_PT.UTF-8", lang("pt-PT"))
|
||||
assertEquals("es_MX.UTF-8", lang("es-419"))
|
||||
assertEquals("zh_CN.UTF-8", lang("zh-CN"))
|
||||
assertEquals("zh_TW.UTF-8", lang("zh-TW"))
|
||||
assertEquals("zh_HK.UTF-8", lang("zh-HK"))
|
||||
}
|
||||
|
||||
@Test fun chineseScriptBeatsRegion() {
|
||||
assertEquals("zh_CN.UTF-8", lang("zh-Hans-HK"))
|
||||
assertEquals("zh_TW.UTF-8", lang("zh-Hant-CN"))
|
||||
assertEquals("zh_TW.UTF-8", lang("zh-MO"))
|
||||
assertEquals("zh_HK:zh_TW:zh", DesktopLocale.language(Locale.forLanguageTag("zh-HK")))
|
||||
}
|
||||
|
||||
@Test fun systemRegionsSurvive() {
|
||||
assertEquals("en_GB.UTF-8", lang("en-GB"))
|
||||
assertEquals("fr_CA.UTF-8", lang("fr-CA"))
|
||||
assertEquals("de_DE.UTF-8", lang("de-XX"))
|
||||
}
|
||||
|
||||
@Test fun everyAppLanguageHasALocale() {
|
||||
AppLanguage.supported.forEach { assertTrue(it, lang(it) != DesktopLocale.DEFAULT) }
|
||||
}
|
||||
|
||||
@Test fun unknownLanguagesFallBack() {
|
||||
assertEquals(DesktopLocale.DEFAULT, lang("sw"))
|
||||
}
|
||||
|
||||
@Test fun languageListPrefersTheRegionThenTheLanguage() {
|
||||
assertEquals("pt_BR:pt", DesktopLocale.language(Locale.forLanguageTag("pt-BR")))
|
||||
assertEquals("tr_TR:tr", DesktopLocale.language(Locale.forLanguageTag("tr")))
|
||||
assertEquals("en_US", DesktopLocale.language(Locale.forLanguageTag("en")))
|
||||
assertNull(DesktopLocale.language(Locale.forLanguageTag("sw")))
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,6 @@ class ForcedPackageTest {
|
||||
ComponentsManager.unpackedCacheKey(filename)
|
||||
fail("Expected cache traversal name to be rejected: $filename")
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// Expected: the derived path would be a dot segment.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
class GameTelemetryTest {
|
||||
private fun packet(size: Int, fill: ByteBuffer.() -> Unit): ByteArray =
|
||||
ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN).apply(fill).array()
|
||||
|
||||
@Test fun codemastersFloatsBecomeADash() {
|
||||
val data = packet(264) {
|
||||
putFloat(7 * 4, 25f)
|
||||
putFloat(29 * 4, 0.8f)
|
||||
putFloat(31 * 4, 0.1f)
|
||||
putFloat(33 * 4, 3f)
|
||||
putFloat(36 * 4, 1f)
|
||||
putFloat(37 * 4, 650f)
|
||||
putFloat(63 * 4, 800f)
|
||||
putFloat(45 * 4, 30f)
|
||||
putFloat(46 * 4, 60f)
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, data, data.size)!!
|
||||
assertEquals(90f, t.speedKmh!!, 0.01f)
|
||||
assertEquals("3", t.gear)
|
||||
assertEquals(6500f, t.rpm!!, 0.01f)
|
||||
assertEquals(8000f, t.maxRpm!!, 0.01f)
|
||||
assertEquals(2, t.lap)
|
||||
assertEquals(0.5f, t.fuel!!, 0.001f)
|
||||
}
|
||||
|
||||
@Test fun codemastersShortPacketFromDirtShowdown() {
|
||||
val data = packet(152) {
|
||||
putFloat(1 * 4, 80.085f)
|
||||
putFloat(7 * 4, 10.739f)
|
||||
putFloat(29 * 4, 0.816f)
|
||||
putFloat(33 * 4, 1f)
|
||||
putFloat(37 * 4, 827.531f)
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, data, data.size)!!
|
||||
assertEquals(38.66f, t.speedKmh!!, 0.01f)
|
||||
assertEquals("1", t.gear)
|
||||
assertEquals(8275.31f, t.rpm!!, 0.01f)
|
||||
assertEquals(0.816f, t.throttle!!, 0.001f)
|
||||
assertEquals(1, t.lap)
|
||||
assertEquals(80.085f, t.currentLapS!!, 0.001f)
|
||||
assertNull(t.maxRpm)
|
||||
assertNull(t.laps)
|
||||
assertNull(t.position)
|
||||
assertNull(t.fuel)
|
||||
assertNull(t.lastLapS)
|
||||
}
|
||||
|
||||
@Test fun codemastersReverseAndNeutral() {
|
||||
fun gear(g: Float) = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, packet(264) { putFloat(33 * 4, g) }, 264)!!.gear
|
||||
assertEquals("N", gear(0f))
|
||||
assertEquals("R", gear(-1f))
|
||||
assertEquals("R", gear(10f))
|
||||
}
|
||||
|
||||
@Test fun forzaHorizonDashSitsTwelveBytesLater() {
|
||||
val dash = 232 + 12
|
||||
val data = packet(324) {
|
||||
putInt(0, 1)
|
||||
putFloat(8, 8000f)
|
||||
putFloat(16, 5000f)
|
||||
putFloat(dash + 12, 50f)
|
||||
put(dash + 71, 255.toByte())
|
||||
put(dash + 75, 4)
|
||||
putShort(dash + 68, 2)
|
||||
put(dash + 70, 5)
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!
|
||||
assertEquals(180f, t.speedKmh!!, 0.01f)
|
||||
assertEquals("4", t.gear)
|
||||
assertEquals(1f, t.throttle!!, 0.001f)
|
||||
assertEquals(3, t.lap)
|
||||
assertEquals(5, t.position)
|
||||
}
|
||||
|
||||
@Test fun forzaMotorsportDashFollowsTheSled() {
|
||||
val data = packet(311) {
|
||||
putInt(0, 1)
|
||||
putFloat(232 + 12, 10f)
|
||||
put(232 + 75, 0)
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!
|
||||
assertEquals(36f, t.speedKmh!!, 0.01f)
|
||||
assertEquals("R", t.gear)
|
||||
}
|
||||
|
||||
@Test fun forzaInMenusHasNoDash() {
|
||||
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, packet(324) {}, 324)!!
|
||||
assertNull(t.speedKmh)
|
||||
}
|
||||
|
||||
@Test fun outGaugeGearsAreShiftedByOne() {
|
||||
val data = packet(96) {
|
||||
put(10, 3)
|
||||
putFloat(12, 20f)
|
||||
putFloat(16, 4000f)
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, data, data.size)!!
|
||||
assertEquals("2", t.gear)
|
||||
assertEquals(72f, t.speedKmh!!, 0.01f)
|
||||
assertEquals(4000f, t.rpm!!, 0.01f)
|
||||
}
|
||||
|
||||
@Test fun listensOnIpv4Loopback() {
|
||||
assertTrue(GameTelemetry.LISTEN_ADDRESS is java.net.Inet4Address)
|
||||
assertEquals("127.0.0.1", GameTelemetry.LISTEN_ADDRESS.hostAddress)
|
||||
}
|
||||
|
||||
@Test fun shortPacketsAreIgnored() {
|
||||
assertNull(GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, ByteArray(148), 148))
|
||||
assertNull(GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, ByteArray(40), 40))
|
||||
assertNull(GameTelemetry.parse(1234, ByteArray(400), 400))
|
||||
}
|
||||
|
||||
@Test fun codemastersGForceAndSteering() {
|
||||
val data = packet(152) {
|
||||
putFloat(30 * 4, -0.5f)
|
||||
putFloat(33 * 4, 2f)
|
||||
putFloat(34 * 4, 1.2f)
|
||||
putFloat(35 * 4, -0.8f)
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, data, data.size)!!
|
||||
assertEquals(-0.5f, t.steer!!, 1e-4f)
|
||||
assertEquals(1.2f, t.gLat!!, 1e-4f)
|
||||
assertEquals(-0.8f, t.gLon!!, 1e-4f)
|
||||
}
|
||||
|
||||
@Test fun forzaReadsBestLapSteeringGForceAndTires() {
|
||||
val dash = 232
|
||||
val data = packet(311) {
|
||||
putInt(0, 1)
|
||||
putFloat(20, 9.81f)
|
||||
putFloat(28, -4.905f)
|
||||
putFloat(dash + 24, 212f)
|
||||
putFloat(dash + 28, 32f)
|
||||
putFloat(dash + 32, 194f)
|
||||
putFloat(dash + 36, 176f)
|
||||
putFloat(dash + 52, 81.5f)
|
||||
put(dash + 75, 3)
|
||||
put(dash + 76, (-127).toByte())
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!
|
||||
assertEquals(1f, t.gLat!!, 1e-3f)
|
||||
assertEquals(-0.5f, t.gLon!!, 1e-3f)
|
||||
assertEquals(listOf(100f, 0f, 90f, 80f), t.tireTempsC!!.map { Math.round(it).toFloat() })
|
||||
assertEquals(81.5f, t.bestLapS!!, 1e-4f)
|
||||
assertEquals(-1f, t.steer!!, 1e-4f)
|
||||
}
|
||||
|
||||
@Test fun forzaWithoutTireDataLeavesThemOut() {
|
||||
val data = packet(311) { putInt(0, 1); put(232 + 75, 2) }
|
||||
assertNull(GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!.tireTempsC)
|
||||
}
|
||||
|
||||
@Test fun outGaugeReadsTurboTemperaturesAndLights() {
|
||||
val data = packet(92) {
|
||||
put(10, 3)
|
||||
putFloat(20, 0.8f)
|
||||
putFloat(24, 92f)
|
||||
putFloat(36, 104f)
|
||||
putInt(40, GameTelemetry.DL_SHIFT or GameTelemetry.DL_ABS or GameTelemetry.DL_HANDBRAKE)
|
||||
putInt(44, GameTelemetry.DL_SHIFT or GameTelemetry.DL_ABS)
|
||||
}
|
||||
val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, data, data.size)!!
|
||||
assertEquals(0.8f, t.turboBar!!, 1e-4f)
|
||||
assertEquals(92f, t.engineTempC!!, 1e-4f)
|
||||
assertEquals(104f, t.oilTempC!!, 1e-4f)
|
||||
assertEquals(GameTelemetry.DL_SHIFT or GameTelemetry.DL_ABS, t.lights)
|
||||
}
|
||||
|
||||
@Test fun outGaugeZeroFieldsStayHidden() {
|
||||
val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, packet(92) { put(10, 2) }, 92)!!
|
||||
assertNull(t.turboBar)
|
||||
assertNull(t.engineTempC)
|
||||
assertNull(t.lights)
|
||||
}
|
||||
}
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GameStatusFilesTest {
|
||||
@Test fun warThunderShowsNumbersOnlyDuringAMatch() {
|
||||
assertEquals(emptyList<Pair<String, String>>(), GameStatusFiles.warThunder("""{"valid": false}"""))
|
||||
val rows = GameStatusFiles.warThunder("""{"valid": true, "H, m": 1520, "TAS, km/h": 512.4, "name": "x"}""")
|
||||
assertEquals(listOf("H, m" to "1520", "TAS, km/h" to "512.4"), rows)
|
||||
}
|
||||
|
||||
@Test fun warThunderKeepsEveryNumberForTheFlightLayout() {
|
||||
val json = buildString {
|
||||
append("{\"valid\": true")
|
||||
for (i in 0 until 20) append(", \"k$i\": $i")
|
||||
append(", \"IAS, km/h\": 512, \"throttle 1, %\": 110}")
|
||||
}
|
||||
val rows = GameStatusFiles.warThunder(json)
|
||||
assertEquals(22, rows.size)
|
||||
assertTrue(com.droiddeck.launcher.ui.FlightLabels.drawable(rows))
|
||||
assertEquals("110", rows.toMap()["throttle 1, %"])
|
||||
}
|
||||
|
||||
@Test fun eliteAtTheMenusShowsNothing() {
|
||||
assertNull(GameStatusFiles.elite("""{"timestamp": "2026-10-31T02:00:00Z", "event": "Status", "Flags": 0}"""))
|
||||
}
|
||||
|
||||
@Test fun eliteInFlight() {
|
||||
val e = GameStatusFiles.elite("""{"Flags": 16777240, "Pips": [4, 8, 0], "Fuel": {"FuelMain": 16.0, "FuelReservoir": 0.43},
|
||||
"Cargo": 2.0, "LegalState": "Clean", "Balance": 1234567}""")!!
|
||||
assertEquals(16.0, e.fuelMain!!, 0.001)
|
||||
assertEquals(listOf(4, 8, 0), e.pips)
|
||||
assertEquals("Clean", e.legal)
|
||||
assertEquals(1234567L, e.balance)
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,7 @@ class GameThreadHintsTest {
|
||||
@Test fun `a thread joins above 60 percent and leaves under 15`() {
|
||||
assertEquals(emptySet<Int>(), GameThreadHints.pick(emptySet(), mapOf(1 to 0.55)))
|
||||
assertEquals(setOf(1), GameThreadHints.pick(emptySet(), mapOf(1 to 0.68)))
|
||||
// Faster where it was moved, or capped by the display, it stays boosted at 25%...
|
||||
assertEquals(setOf(1), GameThreadHints.pick(setOf(1), mapOf(1 to 0.25)))
|
||||
// ...and is let go once it idles.
|
||||
assertEquals(emptySet<Int>(), GameThreadHints.pick(setOf(1), mapOf(1 to 0.1)))
|
||||
}
|
||||
|
||||
@@ -28,8 +26,8 @@ class GameThreadHintsTest {
|
||||
assertTrue(GameThreadHints.holdsPace(119.0, 120.0))
|
||||
assertTrue(GameThreadHints.holdsPace(60.5, 120.0))
|
||||
assertTrue(GameThreadHints.holdsPace(30.0, 120.0))
|
||||
assertFalse(GameThreadHints.holdsPace(92.0, 120.0)) // falling behind: boost
|
||||
assertFalse(GameThreadHints.holdsPace(92.0, 120.0))
|
||||
assertFalse(GameThreadHints.holdsPace(105.0, 120.0))
|
||||
assertFalse(GameThreadHints.holdsPace(3.0, 120.0)) // headless or loading: boost
|
||||
assertFalse(GameThreadHints.holdsPace(3.0, 120.0))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
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
|
||||
|
||||
class GpuLayerLoadTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
private var now = 0L
|
||||
private fun load(dir: File) = GpuStatsComponent.LayerLoad(dir, clock = { now })
|
||||
private fun write(dir: File, pid: Int, busyNs: Long) = File(dir, "$pid").writeText("%20d %-32s\n".format(busyNs, "game"))
|
||||
|
||||
@Test fun busyTimeOfAllProcessesOverWallTime() {
|
||||
val dir = tmp.newFolder("gpu-load")
|
||||
val load = load(dir)
|
||||
write(dir, 100, 1_000_000_000L)
|
||||
write(dir, 200, 5_000_000_000L)
|
||||
now = 10_000_000_000L
|
||||
assertNull(load.percent())
|
||||
write(dir, 100, 1_300_000_000L)
|
||||
write(dir, 200, 5_100_000_000L)
|
||||
now += 1_000_000_000L
|
||||
assertEquals(40L, load.percent())
|
||||
}
|
||||
|
||||
@Test fun aNewProcessStartsFromItsOwnTotalAndAGoneOneStopsCounting() {
|
||||
val dir = tmp.newFolder("gpu-load")
|
||||
val load = load(dir)
|
||||
write(dir, 100, 2_000_000_000L)
|
||||
now = 1L
|
||||
load.percent()
|
||||
File(dir, "100").delete()
|
||||
write(dir, 300, 9_000_000_000L)
|
||||
now += 500_000_000L
|
||||
assertEquals(0L, load.percent())
|
||||
write(dir, 300, 9_250_000_000L)
|
||||
now += 500_000_000L
|
||||
assertEquals(50L, load.percent())
|
||||
}
|
||||
|
||||
@Test fun capsAtFullAndIgnoresOtherFiles() {
|
||||
val dir = tmp.newFolder("gpu-load")
|
||||
val load = load(dir)
|
||||
File(dir, "on").createNewFile()
|
||||
write(dir, 1, 0L)
|
||||
write(dir, 2, 0L)
|
||||
now = 1L
|
||||
load.percent()
|
||||
write(dir, 1, 900_000_000L)
|
||||
write(dir, 2, 900_000_000L)
|
||||
now += 1_000_000_000L
|
||||
assertEquals(100L, load.percent())
|
||||
}
|
||||
|
||||
@Test fun theOnFlagFollowsTheHudAndHidingDropsTheBaseline() {
|
||||
val dir = tmp.newFolder("gpu-load")
|
||||
val load = load(dir)
|
||||
load.wanted(true)
|
||||
assertTrue(File(dir, "on").exists())
|
||||
write(dir, 1, 100L)
|
||||
now = 1L
|
||||
load.percent()
|
||||
load.wanted(false)
|
||||
assertFalse(File(dir, "on").exists())
|
||||
load.wanted(true)
|
||||
now += 1_000L
|
||||
assertNull(load.percent())
|
||||
}
|
||||
|
||||
@Test fun theCompositorsOwnGpuTimeAddsToTheGames() {
|
||||
val dir = tmp.newFolder("gpu-load")
|
||||
var compositor: Long? = 7_000_000_000L
|
||||
val load = GpuStatsComponent.LayerLoad(dir, clock = { now }, extra = { compositor })
|
||||
write(dir, 100, 1_000_000_000L)
|
||||
now = 1L
|
||||
assertNull(load.percent())
|
||||
write(dir, 100, 1_600_000_000L)
|
||||
compositor = 7_150_000_000L
|
||||
now += 1_000_000_000L
|
||||
assertEquals(75L, load.percent())
|
||||
compositor = null
|
||||
write(dir, 100, 1_900_000_000L)
|
||||
now += 1_000_000_000L
|
||||
assertEquals(30L, load.percent())
|
||||
}
|
||||
|
||||
@Test fun onlyTheCompositorCountsWhenNoGameReportsYet() {
|
||||
val dir = File(tmp.root, "never-created")
|
||||
var compositor = 0L
|
||||
val load = GpuStatsComponent.LayerLoad(dir, clock = { now }, extra = { compositor })
|
||||
now = 1L
|
||||
load.percent()
|
||||
compositor = 200_000_000L
|
||||
now += 1_000_000_000L
|
||||
assertEquals(20L, load.percent())
|
||||
}
|
||||
|
||||
@Test fun compositorTimingFollowsTheHudOnlyOnChanges() {
|
||||
val dir = tmp.newFolder("gpu-load")
|
||||
val calls = mutableListOf<Boolean>()
|
||||
val load = GpuStatsComponent.LayerLoad(dir, clock = { now }, onWanted = { calls += it })
|
||||
load.wanted(true)
|
||||
load.wanted(true)
|
||||
load.wanted(false)
|
||||
load.wanted(true)
|
||||
load.clear()
|
||||
assertEquals(listOf(true, false, true, false), calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GpuMemstoreLoadTest {
|
||||
private var busy = 0L
|
||||
private var samples = 0L
|
||||
private var moves = 0L
|
||||
private var available = true
|
||||
private val load = GpuStatsComponent.MemstoreLoad { if (available) longArrayOf(busy, samples, moves) else null }
|
||||
|
||||
private fun tick(newSamples: Long, newBusy: Long, newMoves: Long = 1) {
|
||||
samples += newSamples
|
||||
busy += newBusy
|
||||
moves += newMoves
|
||||
}
|
||||
|
||||
@Test fun notTrustedUntilNewWorkIsSeen() {
|
||||
assertNull(load.percent())
|
||||
tick(500, 400, newMoves = 0)
|
||||
assertNull(load.percent())
|
||||
assertFalse(load.working)
|
||||
tick(500, 300)
|
||||
assertEquals(70L, load.percent())
|
||||
assertTrue(load.working)
|
||||
}
|
||||
|
||||
@Test fun givesUpWhenTheTimestampsNeverMove() {
|
||||
load.percent()
|
||||
repeat(10) {
|
||||
tick(500, 250, newMoves = 0)
|
||||
assertNull(load.percent())
|
||||
}
|
||||
assertTrue(load.failed)
|
||||
tick(500, 250)
|
||||
assertNull(load.percent())
|
||||
assertFalse(load.working)
|
||||
}
|
||||
|
||||
@Test fun averagesOverTheLastTwoReads() {
|
||||
load.percent()
|
||||
tick(500, 500)
|
||||
assertEquals(100L, load.percent())
|
||||
tick(500, 0)
|
||||
assertEquals(50L, load.percent())
|
||||
tick(500, 0, newMoves = 0)
|
||||
assertEquals(0L, load.percent())
|
||||
}
|
||||
|
||||
@Test fun pausingStartsANewWindow() {
|
||||
load.percent()
|
||||
tick(500, 500)
|
||||
load.percent()
|
||||
load.pause()
|
||||
tick(0, 0, newMoves = 0)
|
||||
assertNull(load.percent())
|
||||
tick(500, 100)
|
||||
assertEquals(20L, load.percent())
|
||||
}
|
||||
|
||||
@Test fun noReadingWithoutNewSamplesOrCounts() {
|
||||
load.percent()
|
||||
tick(500, 100)
|
||||
load.percent()
|
||||
assertNull(load.percent())
|
||||
available = false
|
||||
tick(500, 100)
|
||||
assertNull(load.percent())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class GpuReaderStatusTest {
|
||||
@After fun reset() {
|
||||
KgslBusy.status = "not tried"
|
||||
KgslClock.status = "not tried"
|
||||
}
|
||||
|
||||
@Test fun emptyWhereTheReadersWereNotNeeded() {
|
||||
assertEquals("", GpuStatsComponent.readerStatus())
|
||||
}
|
||||
|
||||
@Test fun namesBothReaders() {
|
||||
KgslBusy.status = "per-context stamps (hardware-scheduled kernel)"
|
||||
KgslClock.status = "working (680 MHz at start)"
|
||||
assertEquals(
|
||||
"kgsl memstore per-context stamps (hardware-scheduled kernel); GPU cycle counter working (680 MHz at start)",
|
||||
GpuStatsComponent.readerStatus(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun rangeCheckFailureIsNamed() {
|
||||
assertEquals("sample out of range", KgslErrors.describe(KgslClock.RANGE_CHECK_FAILED))
|
||||
assertEquals("no error code", KgslErrors.describe(0))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class GpuStatsBindsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun feedsWithNoValueYetAreStillBound() {
|
||||
val dir = tmp.newFolder("kgsl-3d0")
|
||||
GpuStatsComponent.createMissing(listOf(File(dir, "perf_now"), File(dir, "cur_freq")))
|
||||
val binds = GpuStatsComponent(dir, tmp.root).binds()
|
||||
assertTrue(binds.contains(File(dir, "perf_now").path + ":" + GpuStatsComponent.MSM_LOAD))
|
||||
assertTrue(binds.contains(File(dir, "cur_freq").path + ":" + GpuStatsComponent.MSM_CLOCK))
|
||||
}
|
||||
|
||||
@Test fun aWrittenValueIsKept() {
|
||||
val dir = tmp.newFolder("kgsl-3d0")
|
||||
File(dir, "cur_freq").writeText("586000000 \n")
|
||||
GpuStatsComponent.createMissing(listOf(File(dir, "cur_freq")))
|
||||
assertEquals("586000000 \n", File(dir, "cur_freq").readText())
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,16 @@ class OutputPacingTest {
|
||||
assertEquals(30, SessionPrefs.compositorFpsLimit(60, 30))
|
||||
}
|
||||
|
||||
@Test fun pictureInPictureHoldsTheSessionToThirty() {
|
||||
assertEquals(SessionPrefs.PIP_FPS, SessionPrefs.compositorFpsLimit(0, pip = true))
|
||||
assertEquals(SessionPrefs.PIP_FPS, SessionPrefs.compositorFpsLimit(0, 60, pip = true))
|
||||
assertEquals(20, SessionPrefs.compositorFpsLimit(0, 20, pip = true))
|
||||
}
|
||||
|
||||
@Test fun pictureInPictureKeepsTheGlassesRate() {
|
||||
assertEquals(60, SessionPrefs.compositorFpsLimit(60, pip = true))
|
||||
}
|
||||
|
||||
@Test fun mirroringKeepsTheGlassesRate() {
|
||||
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class OverlayShownTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun config(name: String, text: String, modified: Long) =
|
||||
File(tmp.root, "tmp").apply { mkdirs() }.resolve(name).apply { writeText(text); setLastModified(modified) }
|
||||
|
||||
@Test fun noConfigIsHidden() {
|
||||
assertFalse(OverlayShown.check(tmp.root))
|
||||
}
|
||||
|
||||
@Test fun mangohudConfigFollowsNoDisplay() {
|
||||
val f = config("mangohud.abcdefgh", "no_display\n", 1_000_000L)
|
||||
assertFalse(OverlayShown.check(tmp.root))
|
||||
f.writeText("preset=3\n")
|
||||
assertTrue(OverlayShown.check(tmp.root))
|
||||
}
|
||||
|
||||
@Test fun steamSessionConfigFollowsNoDisplay() {
|
||||
val f = config("droiddeck-mangohud.conf", "no_display\n", 1_000_000L)
|
||||
assertFalse(OverlayShown.check(tmp.root))
|
||||
f.writeText("preset=3\n")
|
||||
assertTrue(OverlayShown.check(tmp.root))
|
||||
}
|
||||
|
||||
@Test fun newestConfigWins() {
|
||||
config("mangohud.abcdefgh", "no_display\n", 1_000_000L)
|
||||
config("droiddeck-mangohud.conf", "preset=3\n", 2_000_000L)
|
||||
assertTrue(OverlayShown.check(tmp.root))
|
||||
config("mangohud.abcdefgh", "no_display\n", 3_000_000L)
|
||||
assertFalse(OverlayShown.check(tmp.root))
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SessionDisplayTest {
|
||||
private val scaledFollow = listOf("follow/1.5", "follow/2", "follow/2.5", "follow/3", "follow/4")
|
||||
|
||||
@Test fun portraitPresetsSwapTheOutputAndRetainTheResolutionCap() {
|
||||
assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "720p", portrait = true))
|
||||
assertEquals(900 to 1600, SessionDisplay.resolveChoice(1080 to 1920, "900p", portrait = true))
|
||||
@@ -40,13 +42,13 @@ class SessionDisplayTest {
|
||||
|
||||
@Test fun optionsListTheHeightsThePanelCanShowThenThePanel() {
|
||||
val thor = SessionDisplay.resolutionOptions(1920 to 1080)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN), thor)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN),
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow, thor)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow,
|
||||
SessionDisplay.resolutionOptions(2400 to 1080))
|
||||
assertEquals(listOf("720p", "900p", "1080p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN),
|
||||
assertEquals(listOf("720p", "900p", "1080p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow,
|
||||
SessionDisplay.resolutionOptions(3120 to 1440))
|
||||
val small = SessionDisplay.resolutionOptions(1280 to 720)
|
||||
assertEquals(listOf(SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN), small)
|
||||
assertEquals(listOf(SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow, small)
|
||||
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, SessionDisplay.MATCH_SCREEN))
|
||||
assertEquals(2560 to 1440, SessionDisplay.resolveChoice(2560 to 1440, SessionDisplay.MATCH_SCREEN))
|
||||
}
|
||||
@@ -105,6 +107,31 @@ class SessionDisplayTest {
|
||||
assertNull(SessionDisplay.followSize(640, 360))
|
||||
}
|
||||
|
||||
@Test fun scaledFollowDividesTheWindowAndStaysEven() {
|
||||
assertEquals(1260 to 540, SessionDisplay.resolveChoice(1080 to 2520, "follow/2"))
|
||||
assertEquals(540 to 1260, SessionDisplay.resolveChoice(2520 to 1080, "follow/2", portrait = true))
|
||||
assertEquals(1092 to 984, SessionDisplay.followSize(2185, 1969, scale = 2f))
|
||||
assertEquals(656 to 728, SessionDisplay.followSize(1968, 2184, scale = 3f))
|
||||
assertNull(SessionDisplay.followSize(640, 360, scale = 2f))
|
||||
assertEquals(720 to 1600, SessionDisplay.resolveChoice(2400 to 1080, "follow/1.5", portrait = true))
|
||||
assertEquals(1600 to 720, SessionDisplay.resolveChoice(1080 to 2400, "follow/1.5"))
|
||||
assertNull(SessionDisplay.followScale("follow/1.0"))
|
||||
}
|
||||
|
||||
@Test fun onlyKnownFollowChoicesCountAsFollow() {
|
||||
assertEquals(1f, SessionDisplay.followScale(SessionDisplay.FOLLOW_SCREEN))
|
||||
assertEquals(3f, SessionDisplay.followScale("follow/3"))
|
||||
assertEquals(1.3f, SessionDisplay.followScale("follow/1.3"))
|
||||
assertEquals(1.3f, SessionDisplay.followScale("follow/1.26"))
|
||||
assertEquals("follow/1.3", SessionDisplay.followScaled(1.3f))
|
||||
assertEquals("follow/2", SessionDisplay.followScaled(2f))
|
||||
assertNull(SessionDisplay.followScale("follow/1"))
|
||||
assertNull(SessionDisplay.followScale("follow/x"))
|
||||
assertNull(SessionDisplay.followScale("follow/9"))
|
||||
assertNull(SessionDisplay.followScale("720p"))
|
||||
assertFalse(SessionDisplay.isFollow(SessionDisplay.MATCH_SCREEN))
|
||||
}
|
||||
|
||||
@Test fun aPhoneCanFollowTheShortGameAreaAboveItsControls() {
|
||||
assertNull(SessionDisplay.followSize(720, 404))
|
||||
assertEquals(720 to 404, SessionDisplay.followSize(720, 404, controlsBelow = true))
|
||||
|
||||
@@ -27,7 +27,6 @@ class SessionLogShareZipTest {
|
||||
val earlySecret = "early-sessionid-abcdef123456"
|
||||
val trailingSecret = "late-refresh-token-abcdef123456"
|
||||
try {
|
||||
// One long line exercises the streaming limit; the final ordinary line must still be redacted.
|
||||
raw.bufferedWriter().use { out ->
|
||||
out.write("sessionid=$earlySecret")
|
||||
val chunk = "x".repeat(8192)
|
||||
@@ -40,7 +39,6 @@ class SessionLogShareZipTest {
|
||||
ZipFile(zip).use { archive ->
|
||||
val entry = archive.getEntry("${session.name}/steam-42.log")!!
|
||||
archive.getInputStream(entry).use { input ->
|
||||
// Only inspect the bounded scrubbed prefix: the pre-fix raw archive is over 64 MiB.
|
||||
val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n"
|
||||
val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size)
|
||||
var offset = 0
|
||||
@@ -74,7 +72,6 @@ class SessionLogShareZipTest {
|
||||
"Authorization: Bearer abc.def.ghi\n" +
|
||||
"kept: EResult 5, app 1086940, steamapps/common/Game\n"
|
||||
)
|
||||
// StoreLogFiles.prune, started by App.onCreate, deletes a stores log named for a day over a week old.
|
||||
val storesLog = "stores-" + SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date()) + ".log"
|
||||
File(logs, "stores").apply { mkdirs() }.resolve(storesLog).writeText("epic: f_token=zzzzzzzz12 window 32\n")
|
||||
File(logs, SessionPaths.TOOLS_DIR).apply { mkdirs() }.resolve("flatpak-install.log").writeText("== install\nCookie: steamLoginSecure=76561198000000000%7C%7Ceyabc\n")
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.concurrent.AbstractExecutorService
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -86,6 +88,105 @@ class SessionSuspendControllerTest {
|
||||
assertTrue(disabled.pagedOut.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun resumeReadsThePagedOutMemoryBack() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
val resumed = fixture.signals.drop(before)
|
||||
assertEquals(listOf(GAME), resumed.filter { it.signal == URG }.map { it.pid })
|
||||
assertTrue(resumed.indexOfLast { it.signal == CONT } < resumed.indexOfFirst { it.signal == URG })
|
||||
assertEquals("0", fixture.control.readText())
|
||||
assertEquals(listOf(Triple(1, 0L, 3_000_000L)), fixture.pagedIn)
|
||||
assertTrue(fixture.game.threads.all { it.state == 'S' })
|
||||
val again = fixture.signals.size
|
||||
fixture.controller.freeze { assertTrue(it) }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.signals.drop(again).any { it.signal == URG })
|
||||
assertEquals(1, fixture.pagedIn.size)
|
||||
}
|
||||
|
||||
@Test fun noReadBackAfterAFreezeWithoutPageOut() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze { assertTrue(it) }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.signals.any { it.signal == URG })
|
||||
assertTrue(fixture.pagedIn.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun readBackIsSkippedWhenAvailableMemoryCannotTakeIt() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.availableKb = 3_500_000L
|
||||
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 readBackNeedsTwiceTheSwapAvailable() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.availableKb = 5_500_000L
|
||||
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(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn)
|
||||
}
|
||||
|
||||
@Test fun readBackKeepsATenthOfMemTotalAvailable() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.totalKb = 40_000_000L
|
||||
fixture.availableKb = 6_500_000L
|
||||
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(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")
|
||||
fixture.afterSleep = { if (fixture.now >= 200 && fixture.signals.none { it.signal == STOP }) fixture.controller.cancelFreeze() }
|
||||
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(1, fixture.pagedIn.single().first)
|
||||
assertEquals(0L, fixture.pagedIn.single().second)
|
||||
assertTrue(fixture.pagedIn.single().third > 0L)
|
||||
}
|
||||
|
||||
@Test fun cancelledFreezeLeavesAPendingPageOutHandlerReadingBack() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerStalls = true
|
||||
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(Triple(1, 0L, 0L), fixture.pagedIn.single())
|
||||
}
|
||||
|
||||
@Test fun cpuMustBeStableAcrossTwoCompleteSnapshots() {
|
||||
val fixture = fixture(17)
|
||||
var changes = 0
|
||||
@@ -168,6 +269,40 @@ class SessionSuspendControllerTest {
|
||||
assertFalse(fixture.signals.drop(before).any { it.pid == helper.pid })
|
||||
}
|
||||
|
||||
@Test fun frozenTimeIsAddedToTheGuestClockBeforeItContinues() {
|
||||
val fixture = fixture(17)
|
||||
fixture.clock.writeBytes(shift(5_000_000L))
|
||||
fixture.controller.freeze { assertTrue(it) }
|
||||
fixture.now += 90_000L
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
val expected = 5_000_000L + 90_000L * 1_000_000L
|
||||
assertEquals(expected, fixture.clockAtContinue)
|
||||
assertEquals(expected, shift(fixture.clock))
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(expected, shift(fixture.clock))
|
||||
fixture.controller.freeze { assertTrue(it) }
|
||||
fixture.now += 1_000L
|
||||
fixture.controller.closeAndResume {}
|
||||
assertEquals(expected + 1_000L * 1_000_000L, shift(fixture.clock))
|
||||
}
|
||||
|
||||
@Test fun rolledBackFreezeLeavesTheGuestClockAlone() {
|
||||
val fixture = fixture(17)
|
||||
fixture.clock.writeBytes(shift(0L))
|
||||
fixture.neverStop = true
|
||||
fixture.controller.freeze { assertFalse(it) }
|
||||
fixture.controller.resume { }
|
||||
assertEquals(0L, shift(fixture.clock))
|
||||
}
|
||||
|
||||
@Test fun missingClockFileIsNotCreated() {
|
||||
val fixture = fixture(17)
|
||||
fixture.controller.freeze { assertTrue(it) }
|
||||
fixture.now += 5_000L
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.clock.exists())
|
||||
}
|
||||
|
||||
@Test fun timeoutRollsBackAllKnownProcessesAndAudio() {
|
||||
val fixture = fixture(17)
|
||||
fixture.neverStop = true
|
||||
@@ -312,6 +447,10 @@ class SessionSuspendControllerTest {
|
||||
assertEquals(0, fixture.audioSuspends)
|
||||
}
|
||||
|
||||
private fun shift(value: Long) = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(value).array()
|
||||
|
||||
private fun shift(file: File) = ByteBuffer.wrap(file.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
|
||||
|
||||
private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) =
|
||||
Fixture(temporary.newFolder(), temporary.newFolder(), count, executor)
|
||||
|
||||
@@ -337,10 +476,17 @@ class SessionSuspendControllerTest {
|
||||
var rootGone = false
|
||||
var afterSleep: (() -> Unit)? = null
|
||||
val control = File(tmp, ".bl-zram")
|
||||
val clock = File(tmp, ".bl-clock")
|
||||
var clockAtContinue: Long? = null
|
||||
val pagedOut = mutableListOf<Triple<Int, Long, Long>>()
|
||||
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
|
||||
private var pagingIn = false
|
||||
var unacknowledged = -1
|
||||
var handlerStalls = false
|
||||
var handlerReplaced = false
|
||||
@@ -349,10 +495,14 @@ class SessionSuspendControllerTest {
|
||||
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
|
||||
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
|
||||
zramControl = control,
|
||||
clockControl = clock,
|
||||
nowNanos = { now * 1_000_000L },
|
||||
pagedOut = { processes, unacknowledged, resident, swap, _, _ ->
|
||||
pagedOut += Triple(processes, resident, swap)
|
||||
this.unacknowledged = unacknowledged
|
||||
},
|
||||
readBackAllowed = { readBackAllowed },
|
||||
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
|
||||
)
|
||||
|
||||
init { sync() }
|
||||
@@ -367,8 +517,11 @@ class SessionSuspendControllerTest {
|
||||
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
|
||||
}?.state = 't'
|
||||
} else if (signal == URG) {
|
||||
pagingOut = true
|
||||
if (control.readText() == "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
|
||||
}
|
||||
continuing = true
|
||||
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
|
||||
}
|
||||
@@ -398,6 +551,12 @@ class SessionSuspendControllerTest {
|
||||
pagingOut = false
|
||||
}
|
||||
}
|
||||
if (pagingIn) {
|
||||
val moved = minOf(gameSwapKb, 1_000_000L)
|
||||
gameSwapKb -= moved
|
||||
gameResidentKb += moved
|
||||
if (gameSwapKb == 0L) pagingIn = false
|
||||
}
|
||||
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
|
||||
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
|
||||
}
|
||||
@@ -406,6 +565,7 @@ class SessionSuspendControllerTest {
|
||||
}
|
||||
|
||||
fun sync() {
|
||||
File(proc, "meminfo").writeText("MemTotal:\t$totalKb kB\nMemFree:\t1000 kB\nMemAvailable:\t$availableKb kB\n")
|
||||
for (group in groups) {
|
||||
val dir = File(proc, group.pid.toString())
|
||||
if (group == root && rootGone) { dir.deleteRecursively(); continue }
|
||||
|
||||
@@ -46,8 +46,8 @@ class SettingsResetTest {
|
||||
SessionPrefs.setHudShowGraph(app, false)
|
||||
SessionPrefs.setHudColor(app, "amber")
|
||||
SessionPrefs.setHudOpacity(app, 40)
|
||||
SessionPrefs.setFusionHudConfig(app, "hudSize=mega,showFPSGraph=0")
|
||||
SessionPrefs.setFusionHudPosition(app, 120f, 40f)
|
||||
SessionPrefs.setDroidDeckHudConfig(app, "hudSize=mega,showFPSGraph=0")
|
||||
SessionPrefs.setDroidDeckHudPosition(app, 120f, 40f)
|
||||
ControllerPrefs.setOpacity(app, 40)
|
||||
AppUiPrefs.setScale(app, 150)
|
||||
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3))
|
||||
@@ -72,8 +72,8 @@ class SettingsResetTest {
|
||||
assertTrue(SessionPrefs.hudShowGraph(app))
|
||||
assertEquals(SessionPrefs.HUD_COLOR_MINT, SessionPrefs.hudColor(app))
|
||||
assertEquals(SessionPrefs.HUD_OPACITY_DEFAULT, SessionPrefs.hudOpacity(app))
|
||||
assertNull(SessionPrefs.fusionHudConfig(app))
|
||||
assertNull(SessionPrefs.fusionHudPosition(app))
|
||||
assertNull(SessionPrefs.droidDeckHudConfig(app))
|
||||
assertNull(SessionPrefs.droidDeckHudPosition(app))
|
||||
assertEquals(100, ControllerPrefs.read(app).opacity)
|
||||
assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app))
|
||||
assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app))
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ShaderPrecachePrefsTest {
|
||||
private val context: Context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun reset() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
SessionPrefs.steamRoot(context, SessionPrefs.steamClientArch(context)).deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun clientWithoutConfigStartsWithPrecachingOff() {
|
||||
assertEquals(false, SessionPrefs.pendingShaderPrecache(context))
|
||||
assertEquals(false, SessionPrefs.shaderPrecache(context))
|
||||
}
|
||||
|
||||
@Test fun existingConfigKeepsTheClientsChoice() {
|
||||
val config = SessionPrefs.steamRoot(context, SessionPrefs.steamClientArch(context)).resolve("config/config.vdf")
|
||||
config.parentFile!!.mkdirs()
|
||||
config.writeText("\"InstallConfigStore\" {}")
|
||||
assertNull(SessionPrefs.pendingShaderPrecache(context))
|
||||
assertEquals(true, SessionPrefs.shaderPrecache(context))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class StatsLayoutTest {
|
||||
@Test fun unknownIdsFallBackToTheDefaults() {
|
||||
assertEquals(StatsStrip.LINE, StatsStrip.from(null))
|
||||
assertEquals(StatsStrip.LINE, StatsStrip.from("gone"))
|
||||
assertEquals(StatsStrip.PANEL, StatsStrip.from("panel"))
|
||||
assertEquals(StatsStrip.RINGS, StatsStrip.from("rings"))
|
||||
assertEquals(StatsDash.AUTO, StatsDash.from("gone"))
|
||||
assertEquals(StatsDash.TRACE, StatsDash.from("trace"))
|
||||
}
|
||||
|
||||
@Test fun tappingTheStripCyclesThroughEveryStyle() {
|
||||
assertEquals(StatsStrip.PANEL, StatsStrip.LINE.next())
|
||||
assertEquals(StatsStrip.TILES, StatsStrip.PANEL.next())
|
||||
assertEquals(StatsStrip.RINGS, StatsStrip.TILES.next())
|
||||
assertEquals(StatsStrip.LINE, StatsStrip.RINGS.next())
|
||||
}
|
||||
|
||||
@Test fun stripNumbersStartWithEverythingButTheGpuTemperature() {
|
||||
assertEquals(StripMetric.entries.toSet() - StripMetric.GPU_TEMP, StripMetric.parse(null))
|
||||
}
|
||||
|
||||
@Test fun stripNumbersSurviveSavingAndSkipUnknownIds() {
|
||||
val picked = setOf(StripMetric.GPU, StripMetric.RAM, StripMetric.CLOCK)
|
||||
assertEquals(picked, StripMetric.parse(StripMetric.encode(picked)))
|
||||
assertEquals(setOf(StripMetric.CPU), StripMetric.parse("cpu,gone, "))
|
||||
assertEquals(emptySet<StripMetric>(), StripMetric.parse(""))
|
||||
}
|
||||
|
||||
@Test fun autoPicksTheDashByTheGamesFormat() {
|
||||
assertEquals(StatsDash.SPEEDOMETER, StatsDash.AUTO.resolve("Codemasters"))
|
||||
assertEquals(StatsDash.CIRCUIT, StatsDash.AUTO.resolve("Forza"))
|
||||
assertEquals(StatsDash.DIALS, StatsDash.AUTO.resolve("OutGauge"))
|
||||
assertEquals(StatsDash.TRACE, StatsDash.TRACE.resolve("Forza"))
|
||||
}
|
||||
|
||||
@Test fun tappingTheDashMovesOnFromTheOneOnScreen() {
|
||||
assertEquals(StatsDash.CIRCUIT, StatsDash.tapped(StatsDash.SPEEDOMETER))
|
||||
assertEquals(StatsDash.SPEEDOMETER, StatsDash.tapped(StatsDash.GLANCE))
|
||||
assertEquals(StatsDash.SPEEDOMETER, StatsDash.tapped(StatsDash.AUTO))
|
||||
}
|
||||
|
||||
@Test fun automaticSpeedUnitsFollowTheRegion() {
|
||||
assertEquals(SpeedUnit.MPH, SpeedUnit.AUTO.resolve("US"))
|
||||
assertEquals(SpeedUnit.MPH, SpeedUnit.AUTO.resolve("gb"))
|
||||
assertEquals(SpeedUnit.KMH, SpeedUnit.AUTO.resolve("DE"))
|
||||
assertEquals(SpeedUnit.KMH, SpeedUnit.AUTO.resolve(""))
|
||||
assertEquals(SpeedUnit.KMH, SpeedUnit.KMH.resolve("US"))
|
||||
assertEquals(SpeedUnit.MPH, SpeedUnit.MPH.resolve("DE"))
|
||||
}
|
||||
|
||||
@Test fun speedUnitsCycleAndConvert() {
|
||||
assertEquals(SpeedUnit.AUTO, SpeedUnit.from(null))
|
||||
assertEquals(SpeedUnit.MPH, SpeedUnit.from("mph"))
|
||||
assertEquals(SpeedUnit.KMH, SpeedUnit.AUTO.next())
|
||||
assertEquals(SpeedUnit.MPH, SpeedUnit.KMH.next())
|
||||
assertEquals(SpeedUnit.AUTO, SpeedUnit.MPH.next())
|
||||
assertEquals(62.1f, 100f * SpeedUnit.MPH.perKmh, 0.05f)
|
||||
assertEquals(100f, 100f * SpeedUnit.KMH.perKmh, 0f)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SteamDownloadsTest {
|
||||
private fun manifest(flags: Long, done: Long, total: Long) = """
|
||||
"AppState"
|
||||
{
|
||||
"appid" "220"
|
||||
"name" "Half-Life 2"
|
||||
"StateFlags" "$flags"
|
||||
"BytesToDownload" "$total"
|
||||
"BytesDownloaded" "$done"
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
@Test fun anAppUnfinishedInBothSteamHomesIsListedOnce() {
|
||||
val arm = SteamDownload("220", "Half-Life 2", 10L, 100L)
|
||||
val x86 = SteamDownload("220", "Half-Life 2", 60L, 100L)
|
||||
val other = SteamDownload("440", "Team Fortress 2", 5L, 50L)
|
||||
assertEquals(listOf(x86, other), SteamDownloads.onePerApp(listOf(arm, x86, other)))
|
||||
}
|
||||
|
||||
@Test fun anInstalledGameIsNotADownload() {
|
||||
assertNull(SteamDownloads.fromManifest("220", "Half-Life 2", manifest(4, 100, 100)))
|
||||
}
|
||||
|
||||
@Test fun aRunningUpdateShowsItsBytes() {
|
||||
val d = SteamDownloads.fromManifest("220", "Half-Life 2", manifest(1026, 40, 100))!!
|
||||
assertEquals(40L, d.done)
|
||||
assertEquals(100L, d.total)
|
||||
}
|
||||
|
||||
@Test fun aPausedUpdateSaysSo() {
|
||||
assertTrue(SteamDownloads.fromManifest("220", "Half-Life 2", manifest(514, 40, 100))!!.paused)
|
||||
}
|
||||
|
||||
@Test fun anUpdateNotSizedYetIsStillListed() {
|
||||
assertEquals(0L, SteamDownloads.fromManifest("220", "Half-Life 2", manifest(6, 0, 0))!!.total)
|
||||
}
|
||||
|
||||
@Test fun onlyShaderUpdatesStillRunningCount() {
|
||||
val log = sequenceOf(
|
||||
"[2026-10-30 06:33:02] AppID 220 Shader update changed : Running Update,Downloading,",
|
||||
"[2026-10-30 06:33:02] AppID 440 Shader update changed : Running Update,",
|
||||
"[2026-10-30 06:33:03] AppID 440 Shader update changed : None",
|
||||
"[2026-10-30 06:33:03] AppID 570 App update changed : Running Update,",
|
||||
)
|
||||
assertEquals(listOf("220"), SteamDownloads.runningShaderUpdates(log))
|
||||
}
|
||||
|
||||
@Test fun aClientRestartForgetsOlderShaderUpdates() {
|
||||
val log = sequenceOf(
|
||||
"[2026-10-30 06:33:02] AppID 220 Shader update changed : Running Update,",
|
||||
"[2026-10-30 07:00:00] Client version: 1761000000",
|
||||
)
|
||||
assertEquals(emptyList<String>(), SteamDownloads.runningShaderUpdates(log))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class SteamGameProcessTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun cmdline(vararg args: String) = args.joinToString("\u0000", postfix = "\u0000").toByteArray()
|
||||
|
||||
@Test fun theSessionsOwnSearchesAreNotAGame() {
|
||||
assertFalse(SteamGameProcess.matches(cmdline("pgrep", "-a", "-f", "SteamLaunch AppId=[0-9]")))
|
||||
assertFalse(SteamGameProcess.matches(cmdline("pgrep", "-f", "reaper SteamLaunch")))
|
||||
assertFalse(SteamGameProcess.matches(cmdline("pgrep", "-f", "reaper SteamLaunch AppId=976310( |$)")))
|
||||
assertFalse(SteamGameProcess.matches(cmdline("sh", "-c", "pgrep -f 'proton waitforexitandrun'")))
|
||||
assertFalse(SteamGameProcess.matches(cmdline("/usr/bin/steam", "steam://rungameid/976310")))
|
||||
}
|
||||
|
||||
@Test fun steamsReaperAndProtonAreAGame() {
|
||||
assertTrue(SteamGameProcess.matches(cmdline("/root/.local/share/Steam/steamrtarm64/reaper", "SteamLaunch", "AppId=976310", "--",
|
||||
"/root/.local/share/Steam/compatibilitytools.d/droiddeck-proton-arm64/proton", "waitforexitandrun", "MK11.exe")))
|
||||
assertTrue(SteamGameProcess.matches(cmdline("python3", "/proton", "waitforexitandrun", "game.exe")))
|
||||
}
|
||||
|
||||
@Test fun runningLooksAtEveryProcess() {
|
||||
val proc = tmp.newFolder("proc")
|
||||
fun process(pid: String, vararg args: String) = File(proc, pid).apply { mkdirs() }.resolve("cmdline").writeBytes(cmdline(*args))
|
||||
process("100", "pgrep", "-a", "-f", "SteamLaunch AppId=[0-9]")
|
||||
process("self", "reaper", "SteamLaunch", "AppId=1")
|
||||
assertFalse(SteamGameProcess.running(proc))
|
||||
process("200", "reaper", "SteamLaunch", "AppId=976310", "--", "proton", "waitforexitandrun", "MK11.exe")
|
||||
assertTrue(SteamGameProcess.running(proc))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class SteamIdleSleepTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private val keys = listOf(
|
||||
"IdleSuspendBatterySeconds", "IdleSuspendACSeconds",
|
||||
)
|
||||
|
||||
private fun home(vararg steamBody: String): File = temp.newFolder().also {
|
||||
File(it, "config").mkdirs()
|
||||
File(it, "config/config.vdf").writeText(
|
||||
"\"InstallConfigStore\"\n{\n\t\"Software\"\n\t{\n\t\t\"Valve\"\n\t\t{\n\t\t\t\"Steam\"\n\t\t\t{\n" +
|
||||
steamBody.joinToString("") + "\t\t\t}\n\t\t}\n\t}\n}\n",
|
||||
)
|
||||
}
|
||||
|
||||
private fun text(home: File) = File(home, "config/config.vdf").readText()
|
||||
private fun value(text: String, key: String) = Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
|
||||
|
||||
@Test fun freshClientGetsBothSleepTimersDisabled() {
|
||||
val home = home()
|
||||
assertTrue(SessionFiles.disableIdleSleep(home))
|
||||
keys.forEach { assertEquals(it, "0", value(text(home), it)) }
|
||||
}
|
||||
|
||||
@Test fun existingSleepTimersAreReplacedBesideTheOtherSettings() {
|
||||
val home = home(
|
||||
"\t\t\t\t\"system\"\n\t\t\t\t{\n\t\t\t\t\t\"IdleSuspendACSeconds\"\t\t\"900\"\n" +
|
||||
"\t\t\t\t\t\"IdleScreensaverACSeconds\"\t\t\"300\"\n\t\t\t\t\t\"IdleBacklightDimBatterySeconds\"\t\t\"120\"\n\t\t\t\t}\n",
|
||||
)
|
||||
assertTrue(SessionFiles.disableIdleSleep(home))
|
||||
keys.forEach { assertEquals(it, "0", value(text(home), it)) }
|
||||
assertEquals("300", value(text(home), "IdleScreensaverACSeconds"))
|
||||
assertEquals("120", value(text(home), "IdleBacklightDimBatterySeconds"))
|
||||
}
|
||||
|
||||
@Test fun aChoiceMadeInSteamIsResetAtTheNextSession() {
|
||||
val home = home()
|
||||
SessionFiles.disableIdleSleep(home)
|
||||
File(home, "config/config.vdf").writeText(text(home).replace("\"IdleSuspendACSeconds\"\t\t\"0\"", "\"IdleSuspendACSeconds\"\t\t\"600\""))
|
||||
assertTrue(SessionFiles.disableIdleSleep(home))
|
||||
assertEquals("0", value(text(home), "IdleSuspendACSeconds"))
|
||||
}
|
||||
|
||||
@Test fun clientWithoutAConfigIsRetriedNextSession() {
|
||||
val home = temp.newFolder()
|
||||
assertFalse(SessionFiles.disableIdleSleep(home))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.io.File
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class SteamLibrariesTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun added(path: String, label: String = File(path).name): SteamLibraries.Entry =
|
||||
(SteamLibraries.add(app, path, label) as SteamLibraries.AddResult.Added).entry
|
||||
|
||||
@Test fun addedLibrariesGetStableMountsThatSurviveRenameAndRemoval() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val docs = added(tmp.newFolder("Documents").path, "Docs")
|
||||
val usb = added(tmp.newFolder("USB").path)
|
||||
assertEquals(listOf("/mnt/droiddeck-lib/1", "/mnt/droiddeck-lib/2"), SteamLibraries.list(app).map { it.guest })
|
||||
assertTrue(File(docs.path, "steamapps").isDirectory)
|
||||
|
||||
SteamLibraries.rename(app, docs.id, "My \"Docs\"")
|
||||
assertEquals("My Docs", SteamLibraries.list(app).first().label)
|
||||
assertEquals("/mnt/droiddeck-lib/1", SteamLibraries.list(app).first().guest)
|
||||
|
||||
SteamLibraries.remove(app, docs.id)
|
||||
assertEquals(listOf(usb.id), SteamLibraries.list(app).map { it.id })
|
||||
assertTrue(File(docs.path, "steamapps").isDirectory)
|
||||
assertEquals("3", added(tmp.newFolder("Again").path).id)
|
||||
}
|
||||
|
||||
@Test fun overlappingFoldersAndAFifthLibraryAreRefused() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val games = tmp.newFolder("Games")
|
||||
added(games.path)
|
||||
assertTrue(SteamLibraries.add(app, games.path) is SteamLibraries.AddResult.Refused)
|
||||
assertTrue(SteamLibraries.add(app, File(games, "inner").apply { mkdirs() }.path) is SteamLibraries.AddResult.Refused)
|
||||
repeat(SteamLibraries.MAX - 1) { added(tmp.newFolder("L$it").path) }
|
||||
assertTrue(SteamLibraries.add(app, tmp.newFolder("Full").path) is SteamLibraries.AddResult.Refused)
|
||||
}
|
||||
|
||||
@Test fun addedLibrariesAreListedMappedAndKeepGamesFoldersFromDoubling() {
|
||||
val pc = tmp.newFolder("PC")
|
||||
File(pc, "steamapps").mkdirs()
|
||||
File(pc, "steamapps/appmanifest_220.acf").writeText("x")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
|
||||
val lib = added(pc.path, "PC")
|
||||
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
|
||||
assertEquals(1, Library.steamLibraries(app, "arm64").count { it.first == pc })
|
||||
assertTrue(Library.steamLibraries(app, "x86_64").any { it.first == File(pc, GameStorage.X64_CARD_DIR) })
|
||||
assertEquals(File(pc, "steamapps/common"), AddedGames.hostPath(app, "${lib.guest}/steamapps/common"))
|
||||
val docs = added(tmp.newFolder("Documents").path)
|
||||
assertEquals("${docs.guest}/steamapps", AddedGames.guestPath(app, File(docs.path, "steamapps")))
|
||||
val nested = File(pc, "Other").apply { mkdirs() }
|
||||
SteamLibraries.remove(app, lib.id)
|
||||
assertTrue(SteamLibraries.add(app, nested.path) is SteamLibraries.AddResult.Refused)
|
||||
}
|
||||
|
||||
private fun library(dir: File): File = dir.apply { File(this, "steamapps").mkdirs(); File(this, "steamapps/appmanifest_220.acf").writeText("x") }
|
||||
|
||||
@Test fun pickingTheFolderAboveALibraryAddsTheLibraryInside() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val app2 = tmp.newFolder("OtherApp")
|
||||
library(File(app2, "Steam"))
|
||||
val entry = (SteamLibraries.add(app, app2.path) as SteamLibraries.AddResult.Added).entry
|
||||
assertEquals(File(app2, "Steam").path, entry.path)
|
||||
assertEquals("OtherApp", entry.label)
|
||||
val empty = tmp.newFolder("Empty")
|
||||
assertEquals(empty.path, (SteamLibraries.add(app, empty.path) as SteamLibraries.AddResult.Added).entry.path)
|
||||
}
|
||||
|
||||
@Test fun scanLooksTwoLevelsDownAndSkipsHiddenAndAppFolders() {
|
||||
val volume = tmp.newFolder("volume")
|
||||
val shallow = library(File(volume, "SteamLibrary"))
|
||||
val deep = library(File(volume, "Some App/Steam"))
|
||||
library(File(volume, "Android/data/x"))
|
||||
library(File(volume, ".hidden/Steam"))
|
||||
library(File(volume, "a/b/c"))
|
||||
val withGames = SteamLibraries.candidates(volume, 2).filter { SteamLibraries.gameCount(it) > 0 }
|
||||
assertEquals(setOf(shallow, deep), withGames.toSet())
|
||||
}
|
||||
|
||||
private fun depotInstall(common: File, name: String, complete: Boolean = true): File = File(common, name).apply {
|
||||
File(this, ".DepotDownloader").mkdirs()
|
||||
File(this, ".DepotDownloader/depot.config").writeText("""{"installedManifestIDs":{"43":99}}""")
|
||||
File(this, "$name.exe").writeBytes(ByteArray(4))
|
||||
if (complete) File(this, ".download_complete").writeText("")
|
||||
}
|
||||
|
||||
@Test fun finishedDownloadsWithoutManifestsCountAsGames() {
|
||||
val steam = File(tmp.newFolder("card"), "Other/Steam")
|
||||
val common = File(steam, "steamapps/common").apply { mkdirs() }
|
||||
assertEquals(0, SteamLibraries.gameCount(steam))
|
||||
val done = depotInstall(common, "Done")
|
||||
depotInstall(common, "Partial", complete = false)
|
||||
depotInstall(common, "Managed")
|
||||
File(steam, "steamapps/appmanifest_42.acf").writeText("\"AppState\"\n{\n\t\"installdir\"\t\t\"Managed\"\n}\n")
|
||||
val migrated = File(common, "Migrated").apply {
|
||||
File(this, ".DepotDownloader/completed").mkdirs()
|
||||
File(this, ".DepotDownloader/completed/43_99.manifest").writeBytes(ByteArray(4))
|
||||
File(this, ".download_complete").writeText("")
|
||||
}
|
||||
assertEquals(listOf(done, migrated), SteamLibraries.depotInstalls(common))
|
||||
assertEquals(3, SteamLibraries.gameCount(steam))
|
||||
assertEquals(steam, SteamLibraries.innerLibrary(steam.parentFile))
|
||||
}
|
||||
|
||||
@Test fun addedLibrariesImportFinishedDownloadsWithoutManifests() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val steam = tmp.newFolder("Steam")
|
||||
val game = depotInstall(File(steam, "steamapps/common"), "Game")
|
||||
val lib = added(steam.path)
|
||||
val scanned = AddedGames.scan(app).single()
|
||||
assertEquals(game, scanned.folder)
|
||||
assertEquals("${lib.guest}/steamapps/common/Game", AddedGames.guestPath(app, scanned.folder))
|
||||
}
|
||||
|
||||
@Test fun unreadableOrInvalidEntriesAreDropped() {
|
||||
assertTrue(SteamLibraries.parse("{oops").isEmpty())
|
||||
assertEquals(listOf("2"), SteamLibraries.parse("""[{"id":"../x","path":"/a"},{"id":"2","path":"/b","label":""}]""").map { it.id })
|
||||
assertEquals("b", SteamLibraries.parse("""[{"id":"2","path":"/b","label":""}]""").single().label)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SteamUiPacingTest {
|
||||
@Test fun aSixtyOrNinetyHertzScreenIsLeftUncapped() {
|
||||
assertEquals(0, SessionPrefs.steamUiFpsLimit(60f))
|
||||
assertEquals(0, SessionPrefs.steamUiFpsLimit(59.94f))
|
||||
assertEquals(0, SessionPrefs.steamUiFpsLimit(90f))
|
||||
}
|
||||
|
||||
@Test fun fasterScreensGetAnEvenDivisorOfTheirRefresh() {
|
||||
assertEquals(60, SessionPrefs.steamUiFpsLimit(120f))
|
||||
assertEquals(60, SessionPrefs.steamUiFpsLimit(119.99f))
|
||||
assertEquals(60, SessionPrefs.steamUiFpsLimit(120.00001f))
|
||||
assertEquals(72, SessionPrefs.steamUiFpsLimit(144.00002f))
|
||||
assertEquals(82, SessionPrefs.steamUiFpsLimit(165f))
|
||||
assertEquals(61, SessionPrefs.steamUiFpsLimit(185.00002f))
|
||||
assertEquals(60, SessionPrefs.steamUiFpsLimit(240f))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class SteamWebLoginTest {
|
||||
private fun hex(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
|
||||
|
||||
@Test fun chromiumV10ValuesDecrypt() {
|
||||
val encrypted = hex("7631300b9cf0a6eee9cf1aaac601b85ca37cf9fe9e67078564f0e05835ae2aa3d9b0ab")
|
||||
assertEquals("0123456789abcdef01234567", SteamWebLogin.decrypt(encrypted, hostHashed = false))
|
||||
}
|
||||
|
||||
@Test fun newerStoresDropTheHostHash() {
|
||||
val encrypted = hex("7631304d4114329f1e692e807b8b044d67460f5e14d92ffb48b9f83be318ebd0d84c727674aea32f351b8a33c8aa42553dfeb5")
|
||||
assertEquals("hello", SteamWebLogin.decrypt(encrypted, hostHashed = true))
|
||||
}
|
||||
|
||||
@Test fun otherFormatsAreSkipped() {
|
||||
assertNull(SteamWebLogin.decrypt("v11garbage".toByteArray(), hostHashed = false))
|
||||
assertNull(SteamWebLogin.decrypt(ByteArray(2), hostHashed = false))
|
||||
}
|
||||
|
||||
@Test fun theSignInIsSentTheWaySteamPagesSendIt() {
|
||||
assertEquals("steamLoginSecure=76561190000000000%7C%7Ca.b.c; Path=/; Secure; HttpOnly",
|
||||
SteamWebLogin.header("steamLoginSecure", "76561190000000000||a.b.c", httpOnly = true))
|
||||
assertEquals("sessionid=0123; Path=/; Secure", SteamWebLogin.header("sessionid", "0123", httpOnly = false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class TelemetryOutputTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private val showdown = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<hardware_settings_config>\n" +
|
||||
"\t<audio mono=\"false\" />\n\t<motion enabled=\"true\" ip=\"dbox\" port=\"20777\" delay=\"1\" extradata=\"0\" />\n" +
|
||||
"</hardware_settings_config>\n"
|
||||
|
||||
@Test fun turningOnPointsTheMotionLineHereAndKeepsTheRest() {
|
||||
val on = TelemetryOutput.turnedOn(showdown)!!
|
||||
assertTrue(on.contains("<motion enabled=\"true\" ip=\"127.0.0.1\" port=\"20777\" delay=\"1\" extradata=\"3\" />"))
|
||||
assertEquals(showdown.replace("ip=\"dbox\"", "ip=\"127.0.0.1\"").replace("extradata=\"0\"", "extradata=\"3\""), on)
|
||||
assertTrue(TelemetryOutput.pointsHere(TelemetryOutput.element(on)!!.value))
|
||||
assertFalse(TelemetryOutput.pointsHere(TelemetryOutput.element(showdown)!!.value))
|
||||
}
|
||||
|
||||
@Test fun theUdpLineWinsOverTheMotionLineAndLongerTagsAreIgnored() {
|
||||
val xml = "<x><motion_platform><dbox enabled=\"true\" /></motion_platform>" +
|
||||
"<motion enabled=\"true\" ip=\"dbox\" port=\"20777\" />" +
|
||||
"<udp enabled=\"false\" extradata=\"0\" ip=\"127.0.0.1\" port=\"20777\" delay=\"1\" /></x>"
|
||||
assertTrue(TelemetryOutput.element(xml)!!.value.startsWith("<udp "))
|
||||
val on = TelemetryOutput.turnedOn(xml)!!
|
||||
assertTrue(on.contains("<udp enabled=\"true\" extradata=\"3\" ip=\"127.0.0.1\" port=\"20777\" delay=\"1\" />"))
|
||||
assertTrue(on.contains("<motion enabled=\"true\" ip=\"dbox\" port=\"20777\" />"))
|
||||
assertNull(TelemetryOutput.element("<x><motion_platform enabled=\"true\" /></x>"))
|
||||
}
|
||||
|
||||
@Test fun turningOffPutsTheOriginalLineBackOrSwitchesItOff() {
|
||||
val on = TelemetryOutput.turnedOn(showdown)!!
|
||||
assertEquals(showdown, TelemetryOutput.turnedOff(on, showdown))
|
||||
assertTrue(TelemetryOutput.turnedOff(on, null)!!.contains("<motion enabled=\"false\" ip=\"127.0.0.1\""))
|
||||
}
|
||||
|
||||
@Test fun missingAttributesAreAdded() {
|
||||
assertEquals("<udp enabled=\"true\" ip=\"127.0.0.1\" />", TelemetryOutput.withAttr("<udp enabled=\"true\" />", "ip", "127.0.0.1"))
|
||||
assertEquals("<udp a=\"1\" port=\"20777\">", TelemetryOutput.withAttr("<udp a=\"1\">", "port", "20777"))
|
||||
assertTrue(TelemetryOutput.pointsHere("<udp enabled=\"true\" ip=\"127.0.0.1\" port=\"20777\" />"))
|
||||
}
|
||||
|
||||
@Test fun scanFindsTheGameAndARoundTripRestoresTheFile() {
|
||||
val compatdata = tmp.newFolder("steamapps", "compatdata")
|
||||
val config = configFile(compatdata, "2848447563", "DiRT Showdown")
|
||||
config.writeText(showdown)
|
||||
configFile(compatdata, "12345", "Some Other Game").writeText("<hardware_settings_config />")
|
||||
|
||||
val games = TelemetryOutput.scan(listOf(compatdata))
|
||||
assertEquals(listOf("DiRT Showdown"), games.map { it.name })
|
||||
assertEquals("2848447563", games[0].prefixId)
|
||||
assertFalse(games[0].on)
|
||||
|
||||
assertTrue(TelemetryOutput.set(games[0], true))
|
||||
assertTrue(File(config.path + TelemetryOutput.ORIGINAL_SUFFIX).isFile)
|
||||
assertTrue(TelemetryOutput.scan(listOf(compatdata))[0].on)
|
||||
|
||||
assertTrue(TelemetryOutput.set(games[0], false))
|
||||
assertEquals(showdown, config.readText())
|
||||
assertFalse(File(config.path + TelemetryOutput.ORIGINAL_SUFFIX).exists())
|
||||
assertFalse(TelemetryOutput.scan(listOf(compatdata))[0].on)
|
||||
}
|
||||
|
||||
@Test fun theRunningGameIsMatchedByItsPrefixId() {
|
||||
assertTrue(TelemetryOutput.isRunning("2848447563", "2848447563"))
|
||||
assertTrue(TelemetryOutput.isRunning("-1446519733", "2848447563"))
|
||||
assertFalse(TelemetryOutput.isRunning("2848447563", "690790"))
|
||||
assertFalse(TelemetryOutput.isRunning("2848447563", null))
|
||||
assertTrue(TelemetryOutput.isRunning("2848447563", "program:/games/x.exe"))
|
||||
}
|
||||
|
||||
@Test fun automaticSkipsGamesThatAreOnSwitchedOffOrRunning() {
|
||||
val f = File("x")
|
||||
val dirt4 = TelemetryOutput.Game("DiRT 4", "421020", f, on = false)
|
||||
val rally = TelemetryOutput.Game("DiRT Rally 2.0", "690790", f, on = false)
|
||||
val grid = TelemetryOutput.Game("GRID", "703860", f, on = true)
|
||||
val games = listOf(dirt4, rally, grid)
|
||||
assertEquals(listOf(dirt4, rally), TelemetryOutput.automaticTargets(games, emptySet(), null))
|
||||
assertEquals(listOf(rally), TelemetryOutput.automaticTargets(games, setOf("421020/DiRT 4"), null))
|
||||
assertEquals(listOf(dirt4), TelemetryOutput.automaticTargets(games, emptySet(), "690790"))
|
||||
assertEquals("690790/DiRT Rally 2.0", TelemetryOutput.key(rally))
|
||||
}
|
||||
|
||||
@Test fun switchingAutomaticOffRestoresOnlyGamesDroidDeckChanged() {
|
||||
val compatdata = tmp.newFolder("steamapps", "compatdata")
|
||||
val changed = configFile(compatdata, "2848447563", "DiRT Showdown").apply { writeText(showdown) }
|
||||
val own = configFile(compatdata, "690790", "DiRT Rally 2.0")
|
||||
.apply { writeText("<x><udp enabled=\"true\" ip=\"127.0.0.1\" port=\"20777\" /></x>") }
|
||||
assertTrue(TelemetryOutput.set(TelemetryOutput.scan(listOf(compatdata)).first { it.name == "DiRT Showdown" }, true))
|
||||
val targets = TelemetryOutput.restoreTargets(TelemetryOutput.scan(listOf(compatdata)), null)
|
||||
assertEquals(listOf(changed), targets.map { it.file })
|
||||
assertTrue(own.isFile)
|
||||
assertTrue(TelemetryOutput.restoreTargets(TelemetryOutput.scan(listOf(compatdata)), "2848447563").isEmpty())
|
||||
}
|
||||
|
||||
@Test fun automaticTurnsOnDirt3AndShowdownLikeTheOtherGames() {
|
||||
val f = File("x")
|
||||
val showdownGame = TelemetryOutput.Game("DiRT Showdown", "2848447563", f, on = false)
|
||||
val dirt3 = TelemetryOutput.Game("DiRT3", "321040", f, on = false)
|
||||
val rally = TelemetryOutput.Game("DiRT Rally 2.0", "690790", f, on = false)
|
||||
assertEquals(listOf(showdownGame, dirt3, rally), TelemetryOutput.automaticTargets(listOf(showdownGame, dirt3, rally), emptySet(), null))
|
||||
assertEquals(listOf(rally), TelemetryOutput.automaticTargets(listOf(showdownGame, dirt3, rally), setOf("2848447563/DiRT Showdown", "321040/DiRT3"), null))
|
||||
}
|
||||
|
||||
private fun configFile(compatdata: File, id: String, game: String): File =
|
||||
File(compatdata, "$id/pfx/drive_c/users/steamuser/Documents/My Games/$game/hardwaresettings/hardware_settings_config.xml")
|
||||
.apply { parentFile!!.mkdirs() }
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Test
|
||||
|
||||
/** Filling a grid one card at a time: what is on screen stays put, what is new lands where its title belongs. */
|
||||
class StoreCatalogPatchTest {
|
||||
private fun item(id: String, title: String, image: String? = null) = CatalogItem(Store.GOG, id, title, imageUrl = image, owned = true)
|
||||
|
||||
|
||||
@@ -124,6 +124,25 @@ class StoreGameSidecarTest {
|
||||
assertFalse(text.contains("DD_AUTH"))
|
||||
}
|
||||
|
||||
@Test fun aWorkingDirectoryTravelsWithTheSidecar() {
|
||||
val root = StoreGameSidecar(Store.GOG, "1207658924", "The Witcher", "System/witcher.exe", workdir = "")
|
||||
assertTrue(root.toJson().has("workdir"))
|
||||
assertEquals("", StoreGameSidecar.parse(root.toJson().toString())!!.workdir)
|
||||
assertEquals("bin", StoreGameSidecar.parse(root.copy(workdir = "bin").toJson().toString())!!.workdir)
|
||||
assertNull(StoreGameSidecar.parse(root.copy(workdir = null).toJson().toString())!!.workdir)
|
||||
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe"}""")!!.workdir)
|
||||
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe","workdir":"../x"}""")!!.workdir)
|
||||
}
|
||||
|
||||
@Test fun theLauncherCdsIntoTheTaskWorkingDirectory() {
|
||||
assertTrue(StoreLaunch.launcherText(sample.copy(exe = "System/witcher.exe", workdir = ""))
|
||||
.contains("cd /d \"%~dp0\"\r\n"))
|
||||
assertTrue(StoreLaunch.launcherText(sample.copy(exe = "bin/x64/game.exe", workdir = "bin/x64"))
|
||||
.contains("cd /d \"%~dp0bin\\x64\"\r\n"))
|
||||
assertTrue(StoreLaunch.launcherText(sample.copy(exe = "bin/game.exe", workdir = null))
|
||||
.contains("cd /d \"%~dp0bin\"\r\n"))
|
||||
}
|
||||
|
||||
@Test fun epicLauncherPrefersTheClientsArguments() {
|
||||
val text = StoreLaunch.launcherText(sample.copy(exe = "Binaries/Win64/Celeste.exe"))
|
||||
val lines = text.split("\r\n")
|
||||
|
||||
@@ -138,6 +138,32 @@ class StoreInstallRootTest {
|
||||
assertTrue(File(LinuxRuntime.rootDir(app), xodusRoot.second.removePrefix("/")).isDirectory)
|
||||
}
|
||||
|
||||
@Test fun xodusRootsKeepEveryOtherStoreRootAtTheSameGuestPath() {
|
||||
val card = File(app.filesDir, "card2").apply { mkdirs() }
|
||||
val library = File(app.filesDir, "card/steam").apply { mkdirs() }
|
||||
File(library, "Games").mkdirs()
|
||||
SessionPrefs.setDefaultStorageFolder(app, card.path, "Card 2")
|
||||
SessionPrefs.setGameStorage(app, library.path, "Card")
|
||||
|
||||
val xodus = StoreInstallRoot.externalRootsForXodus(app)
|
||||
assertTrue(xodus.containsAll(StoreInstallRoot.externalRoots(app)))
|
||||
assertTrue(xodus.any { it.first.absolutePath == File(library, "Games").absolutePath })
|
||||
}
|
||||
|
||||
@Test fun theSteamLibraryGetsItsOwnGuestPathWhenItSharesACardWithAnotherStoreRoot() {
|
||||
val card = File(app.filesDir, "same-card/Games")
|
||||
val library = File(app.filesDir, "same-card/steam/Games")
|
||||
val base = "/mnt/droiddeck-stores/ABCD-1234"
|
||||
|
||||
val roots = StoreInstallRoot.withSelectedLibrary(listOf(card to base), library, base)
|
||||
assertEquals(2, roots.map { it.second }.distinct().size)
|
||||
assertEquals(base, roots.single { it.first == card }.second)
|
||||
assertTrue(roots.single { it.first == library }.second.startsWith("$base-"))
|
||||
assertEquals("${roots.single { it.first == library }.second}/Xbox/Doom",
|
||||
StoreInstallRoot.externalGuestPath(File(library, "Xbox/Doom"), roots))
|
||||
assertEquals(roots, StoreInstallRoot.withSelectedLibrary(roots, library, base))
|
||||
}
|
||||
|
||||
@Test fun externalStoreBindsCreateGuestTargetsAndSkipUnavailableVolumes() {
|
||||
val host = File(app.filesDir, "card/Games").apply { mkdirs() }
|
||||
val guestRoot = "/mnt/droiddeck-stores/card"
|
||||
@@ -175,6 +201,15 @@ class StoreInstallRootTest {
|
||||
assertTrue(StoreInstallRoot.unfinished(app).none { it.folder.absolutePath == half.absolutePath })
|
||||
}
|
||||
|
||||
@Test fun aGameBeingUpdatedIsNotAnUnfinishedInstallForAnyStore() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
for (store in listOf(Store.EPIC, Store.ITCH, Store.XBOX, Store.AMAZON)) {
|
||||
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), store), StoreInstallRoot.folderName("Updating", "u1")).apply { mkdirs() }
|
||||
StoreGameSidecar(store, "u1", "Updating", "Updating.exe", state = StoreGameSidecar.STATE_UPDATING).write(folder)
|
||||
assertTrue(StoreInstallRoot.unfinished(app).none { it.folder.absolutePath == folder.absolutePath })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theScratchCacheIsPrivateAndNamedSafely() {
|
||||
val dir = StoreInstallRoot.scratchDir(app, Store.EPIC, "a/b:c")
|
||||
assertTrue(dir.absolutePath.startsWith(app.cacheDir.absolutePath))
|
||||
@@ -263,4 +298,9 @@ class StoreInstallRootTest {
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(1L, 1L))
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(0L, 0L))
|
||||
}
|
||||
|
||||
@Test fun itchKeepsTheFolderItsGamesWereInstalledInWhateverItsDisplayName() {
|
||||
assertEquals("itch", StoreInstallRoot.storeDir(File("/games"), Store.ITCH).name)
|
||||
assertEquals("Game Jolt", StoreInstallRoot.storeDir(File("/games"), Store.GAMEJOLT).name)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.stores.battlenet
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BlizzardArtTest {
|
||||
@@ -27,4 +28,23 @@ class BlizzardArtTest {
|
||||
assertNull(BlizzardArt.imageUrl("""<meta property="og:image" content="https://example.com/art.png">"""))
|
||||
assertNull(BlizzardArt.imageUrl("""\"imageUrl\":\"//catalog.blzstatic.com//ff9/a-prod-thumb_bundle.jpg\""""))
|
||||
}
|
||||
|
||||
@Test fun everyChosenImageComesFromBlizzardsHosts() {
|
||||
BlizzardArt.KEY_ART.values.forEach { assertTrue(it, BlizzardArt.allowed(it)) }
|
||||
}
|
||||
|
||||
@Test fun everyChosenImageBelongsToAKnownTitle() {
|
||||
val codes = com.droiddeck.launcher.runtime.BattleNet.TITLES.map { it.code }.toSet()
|
||||
BlizzardArt.KEY_ART.keys.forEach { assertTrue(it, it in codes) }
|
||||
}
|
||||
|
||||
@Test fun classicVariantsShareTheClassicArtTitle() {
|
||||
val battleNet = com.droiddeck.launcher.runtime.BattleNet
|
||||
val era = battleNet.TITLES.first { it.uid == "wow_classic_era" }
|
||||
assertEquals("wow_classic", battleNet.artTitle(era).uid)
|
||||
}
|
||||
|
||||
@Test fun worldOfWarcraftForeverUsesItsOwnArt() {
|
||||
assertTrue("WoW_Forever" in BlizzardArt.KEY_ART.getValue("WoWF"))
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,6 @@ class DownloadQueueRetryTest {
|
||||
DownloadQueue.clear(app, item.key)
|
||||
assertNull(DownloadQueue.entry(item.key))
|
||||
|
||||
// A card resume (including the restored paused path) must retain its real target.
|
||||
val card = File(app.filesDir, "retry-card").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, card.path, "Card")
|
||||
val target = File(card, "Games")
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class GameJoltBrowseTest {
|
||||
private fun qs(query: GameJoltQuery = GameJoltQuery(), page: Int = 1) = GameJoltBrowse.queryString(query, page)
|
||||
|
||||
@Test fun theDefaultQueryAsksForTheFeaturedSectionByName() {
|
||||
assertEquals("section=featured", qs())
|
||||
}
|
||||
|
||||
@Test fun sectionsPriceAndPagesUseTheSiteNames() {
|
||||
assertEquals("section=hot", qs(GameJoltQuery(section = GameJoltBrowse.SECTION_HOT)))
|
||||
assertEquals("section=featured&f_price=5-less&page=3", qs(GameJoltQuery(price = GameJoltBrowse.PRICE_UNDER_5), 3))
|
||||
assertEquals("section=featured&f_price=free", qs(GameJoltQuery(price = GameJoltBrowse.PRICE_FREE)))
|
||||
}
|
||||
|
||||
@Test fun listFiltersKeepTheSiteOrderWhateverTheSelectionOrder() {
|
||||
assertEquals("section=featured&f_os%5B%5D=windows&f_os%5B%5D=linux", qs(GameJoltQuery(os = setOf("linux", "windows"))))
|
||||
assertEquals("section=featured&f_browser%5B%5D=html&f_maturity%5B%5D=everyone&f_status%5B%5D=complete&f_partners%5B%5D=partners",
|
||||
qs(GameJoltQuery(browser = setOf("html"), maturity = setOf("everyone"), status = setOf("complete"), partners = true)))
|
||||
}
|
||||
|
||||
@Test fun devlogGamesAreNeverAskedFor() {
|
||||
assertEquals(setOf("complete", "wip"), GameJoltBrowse.effective(GameJoltQuery(), true).status)
|
||||
assertEquals(setOf("complete", "wip"), GameJoltBrowse.effective(GameJoltQuery(status = setOf("devlog")), true).status)
|
||||
assertEquals(setOf("wip"), GameJoltBrowse.effective(GameJoltQuery(status = setOf("wip", "devlog")), false).status)
|
||||
assertEquals("section=featured&f_status%5B%5D=complete&f_status%5B%5D=wip", qs(GameJoltBrowse.effective(GameJoltQuery(), true).copy(maturity = emptySet())))
|
||||
}
|
||||
|
||||
@Test fun tagsAreSluggedAndRepeatable() {
|
||||
assertEquals("co-op", GameJoltBrowse.tagSlug(" Co-Op "))
|
||||
assertEquals("section=featured&tag=action&tag=co-op", qs(GameJoltQuery(tags = listOf("Action", "co op"))))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class GameJoltBuildsTest {
|
||||
private fun build(id: Int, pkg: Int, release: Int, name: String, vararg flags: String) = JSONObject()
|
||||
.put("id", id).put("game_package_id", pkg).put("game_release_id", release)
|
||||
.put("primary_file", JSONObject().put("filename", name).put("filesize", 100))
|
||||
.also { b -> flags.forEach { b.put(it, true) } }
|
||||
|
||||
private fun payload(vararg builds: JSONObject) = JSONObject()
|
||||
.put("packages", JSONArray().put(JSONObject().put("id", 1).put("title", "Main")))
|
||||
.put("releases", JSONArray().put(JSONObject().put("id", 10).put("published_on", 100).put("version_number", "1.0")).put(JSONObject().put("id", 11).put("published_on", 200).put("version_number", "1.1")))
|
||||
.put("builds", JSONArray(builds.toList()))
|
||||
.put("launchOptions", JSONArray())
|
||||
|
||||
@Test fun onlyTheNewestReleaseOfAPackageIsKept() {
|
||||
val list = GameJoltBuilds.parse(payload(build(1, 1, 10, "old.zip", "os_windows"), build(2, 1, 11, "new.zip", "os_windows")))
|
||||
assertEquals(listOf("2"), list.map { it.id })
|
||||
assertEquals("1.1", list.first().version)
|
||||
}
|
||||
|
||||
@Test fun windowsBuildsAreInstallableAndSortFirst() {
|
||||
val list = GameJoltBuilds.parse(payload(build(1, 1, 11, "game-linux.zip", "os_linux"), build(2, 1, 11, "game-win.zip", "os_windows")))
|
||||
assertEquals(listOf("2", "1"), list.map { it.id })
|
||||
assertTrue(list[0].installable)
|
||||
assertFalse(list[1].installable)
|
||||
}
|
||||
|
||||
@Test fun aBuildWithoutAnOsFlagIsWeb() {
|
||||
assertEquals(setOf("web"), GameJoltBuilds.platforms(JSONObject()))
|
||||
assertEquals(setOf("windows", "osx"), GameJoltBuilds.platforms(JSONObject().put("os_windows", true).put("os_mac", true)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class GameJoltCollectionsTest {
|
||||
@Test fun playlistsBecomeCollectionsByIdAndName() {
|
||||
val list = JSONArray()
|
||||
.put(JSONObject().put("id", 7).put("name", "test list"))
|
||||
.put(JSONObject().put("id", 0).put("name", "no id"))
|
||||
.put(JSONObject().put("id", 9).put("name", ""))
|
||||
val parsed = GameJoltCollections.parse(list)
|
||||
assertEquals(listOf("playlist:7"), parsed.map { it.id })
|
||||
assertEquals(listOf("test list"), parsed.map { it.title })
|
||||
}
|
||||
|
||||
@Test fun eachCollectionHasItsOwnGameListEndpoint() {
|
||||
assertEquals("/web/library/games/followed/@some+one", GameJoltCollections.path(GameJoltCollections.FOLLOWED, "some one"))
|
||||
assertEquals("/web/library/games/playlist/7", GameJoltCollections.path("playlist:7", "x"))
|
||||
assertNull(GameJoltCollections.path("playlist:abc", "x"))
|
||||
assertNull(GameJoltCollections.path("other", "x"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class GameJoltPricingTest {
|
||||
private fun pricing(amount: Long, promotional: Boolean = false, currency: Any = JSONObject.NULL) =
|
||||
JSONObject().put("amount", amount).put("promotional", promotional).put("currency_code", currency)
|
||||
|
||||
private fun sellable(vararg pricings: JSONObject) = JSONObject().put("type", "paid").put("pricings", JSONArray(pricings.toList()))
|
||||
|
||||
@Test fun aRegularPriceIsShownInDollars() {
|
||||
val price = GameJoltPricing.of(sellable(pricing(99)))!!
|
||||
assertEquals("$0.99", price.final)
|
||||
assertEquals("", price.original)
|
||||
assertEquals(0, price.discount)
|
||||
}
|
||||
|
||||
@Test fun aPromotionalPriceBesideTheRegularOneIsASale() {
|
||||
val price = GameJoltPricing.of(sellable(pricing(500), pricing(350, promotional = true)))!!
|
||||
assertEquals("$3.50", price.final)
|
||||
assertEquals("$5.00", price.original)
|
||||
assertEquals(30, price.discount)
|
||||
}
|
||||
|
||||
@Test fun aPromotionalPriceAloneShowsNoDiscount() {
|
||||
val price = GameJoltPricing.of(sellable(pricing(350, promotional = true)))!!
|
||||
assertEquals("$3.50", price.final)
|
||||
assertEquals("", price.original)
|
||||
assertEquals(0, price.discount)
|
||||
}
|
||||
|
||||
@Test fun aPromotionalPriceNotBelowTheRegularOneIsNotASale() {
|
||||
val price = GameJoltPricing.of(sellable(pricing(500), pricing(500, promotional = true)))!!
|
||||
assertEquals("", price.original)
|
||||
assertEquals(0, price.discount)
|
||||
}
|
||||
|
||||
@Test fun aGameWithoutPricingsHasNoPrice() {
|
||||
assertNull(GameJoltPricing.of(sellable()))
|
||||
assertNull(GameJoltPricing.of(null))
|
||||
}
|
||||
|
||||
@Test fun anotherCurrencyIsNamed() {
|
||||
assertEquals("1.50 EUR", GameJoltPricing.of(sellable(pricing(150, currency = "EUR")))!!.final)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class GameJoltUpdatesTest {
|
||||
private fun build(id: String, pkg: String, stamp: String, windows: Boolean = true, name: String = "game.zip") =
|
||||
GameJoltBuild(id, pkg, "Main", "1.0", name, 100L, stamp, if (windows) setOf("windows") else setOf("linux"), "", "")
|
||||
|
||||
@Test fun aNewerReleaseOfTheSamePackageIsAnUpdate() {
|
||||
val update = GameJoltUpdates.evaluate(listOf(build("20", "1", "200", name = "new.zip")), "10", "1", "100")!!
|
||||
assertEquals("20", update.buildId)
|
||||
assertEquals("new.zip", update.filename)
|
||||
assertFalse(update.replaced)
|
||||
}
|
||||
|
||||
@Test fun theInstalledBuildIsNotAnUpdate() {
|
||||
assertNull(GameJoltUpdates.evaluate(listOf(build("10", "1", "100")), "10", "1", "100"))
|
||||
}
|
||||
|
||||
@Test fun anOlderBuildIsNotAnUpdate() {
|
||||
assertNull(GameJoltUpdates.evaluate(listOf(build("5", "1", "50")), "10", "1", "100"))
|
||||
}
|
||||
|
||||
@Test fun theSameReleaseTimeWithAHigherBuildIdIsAnUpdate() {
|
||||
assertEquals("11", GameJoltUpdates.evaluate(listOf(build("11", "1", "100")), "10", "1", "100")?.buildId)
|
||||
}
|
||||
|
||||
@Test fun otherPackagesDoNotCount() {
|
||||
assertEquals("30", GameJoltUpdates.evaluate(listOf(build("40", "2", "900"), build("30", "1", "300")), "10", "1", "100")?.buildId)
|
||||
}
|
||||
|
||||
@Test fun aRemovedPackageFallsBackToTheNewPreferredBuildAndSaysSo() {
|
||||
val update = GameJoltUpdates.evaluate(listOf(build("40", "2", "900")), "10", "1", "100")!!
|
||||
assertEquals("40", update.buildId)
|
||||
assertTrue(update.replaced)
|
||||
}
|
||||
|
||||
@Test fun nonWindowsBuildsAreNeverOffered() {
|
||||
assertNull(GameJoltUpdates.evaluate(listOf(build("40", "1", "900", windows = false)), "10", "1", "100"))
|
||||
}
|
||||
|
||||
@Test fun nothingToCompareMeansNoUpdate() {
|
||||
assertNull(GameJoltUpdates.evaluate(null, "10", "1", "100"))
|
||||
assertNull(GameJoltUpdates.evaluate(listOf(build("40", "1", "900")), "", "1", "100"))
|
||||
}
|
||||
|
||||
@Test fun foundUpdatesSurviveEncodingAndDropEntriesWithoutABuild() {
|
||||
val saved = GameJoltUpdates.encode(mapOf("gamejolt:1" to GameJoltUpdate("20", "200", "new.zip", true)))
|
||||
val back = GameJoltUpdates.decode(saved).getValue("gamejolt:1")
|
||||
assertEquals("20", back.buildId)
|
||||
assertEquals("200", back.stamp)
|
||||
assertEquals("new.zip", back.filename)
|
||||
assertTrue(back.replaced)
|
||||
assertEquals(emptyMap<String, GameJoltUpdate>(), GameJoltUpdates.decode("""{"gamejolt:1":{"stamp":"1"}}"""))
|
||||
assertEquals(emptyMap<String, GameJoltUpdate>(), GameJoltUpdates.decode("not json"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GogGameExeTest {
|
||||
private fun withFolder(block: (File) -> Unit) {
|
||||
val root = kotlin.io.path.createTempDirectory("gog-exe").toFile()
|
||||
try {
|
||||
block(root)
|
||||
} finally {
|
||||
root.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
private fun File.exe(path: String, size: Int = 1024) {
|
||||
val file = File(this, path)
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeBytes(ByteArray(size))
|
||||
}
|
||||
|
||||
// #680: Blood Omen installs dxconfig.exe next to kain.exe, and the config tool won.
|
||||
@Test fun theGameExecutableWinsOverTheConfigToolInTheSameFolder() {
|
||||
withFolder { root ->
|
||||
root.exe("dxconfig.exe")
|
||||
root.exe("kain.exe", 4096)
|
||||
assertEquals("kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aConfigToolInTheGameFolderIsNeverTheFoundExecutable() {
|
||||
withFolder { root ->
|
||||
root.exe("dxconfig.exe")
|
||||
root.exe("bin/kain.exe", 4096)
|
||||
assertEquals("bin/kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theLauncherInTheGameRootLosesToTheGameExecutable() {
|
||||
withFolder { root ->
|
||||
root.exe("Launcher.exe")
|
||||
root.exe("bin/witcher2.exe", 4096)
|
||||
assertEquals(
|
||||
"bin/witcher2.exe",
|
||||
GogDownloadManager.pickExe(root, null, null, "The Witcher 2: Assassins of Kings Enhanced Edition"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theInstallerHintWinsOverTheSearch() {
|
||||
withFolder { root ->
|
||||
root.exe("dxconfig.exe")
|
||||
root.exe("bin/game.exe", 4096)
|
||||
assertEquals("bin/game.exe", GogDownloadManager.pickExe(root, null, "bin/game.exe", "Blood Omen: Legacy of Kain"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aFolderWithoutAGameExecutableYieldsNoPath() {
|
||||
withFolder { root ->
|
||||
root.exe("redist/vcredist_x64.exe")
|
||||
assertEquals("", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theManifestsGameTaskIsTheExecutable() {
|
||||
withFolder { root ->
|
||||
root.exe("dxconfig.exe")
|
||||
root.exe("bin/omen.exe", 4096)
|
||||
File(root, "goggame-1207659641.info").writeText(
|
||||
"""{"gameId":"1207659641","playTasks":[
|
||||
{"category":"tool","path":"dxconfig.exe","type":"FileTask"},
|
||||
{"category":"game","isPrimary":true,"path":"bin\\omen.exe","type":"FileTask"},
|
||||
{"category":"document","path":"manual.pdf","type":"FileTask"}
|
||||
]}""",
|
||||
)
|
||||
assertEquals("bin/omen.exe", GogDownloadManager.pickExe(root, "1207659641", null, "Blood Omen: Legacy of Kain"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aManifestWithOnlyAToolTaskLeavesTheSearchInCharge() {
|
||||
withFolder { root ->
|
||||
root.exe("dxconfig.exe")
|
||||
root.exe("kain.exe", 4096)
|
||||
File(root, "goggame-1207659641.info")
|
||||
.writeText("""{"playTasks":[{"category":"tool","path":"dxconfig.exe","type":"FileTask"}]}""")
|
||||
assertEquals("kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aManifestPathOutsideTheGameFolderIsIgnored() {
|
||||
withFolder { root ->
|
||||
root.exe("kain.exe", 4096)
|
||||
val outside = File(root.parentFile, "outside-${System.nanoTime()}.exe").apply { writeBytes(ByteArray(8)) }
|
||||
try {
|
||||
File(root, "goggame-1207659641.info").writeText(
|
||||
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"../${outside.name}","type":"FileTask"}]}""",
|
||||
)
|
||||
assertEquals("kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain"))
|
||||
} finally {
|
||||
outside.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aPrimaryLauncherTaskIsTheGameOfLauncherGames() {
|
||||
withFolder { root ->
|
||||
root.exe("run.exe")
|
||||
root.exe("game.exe", 4096)
|
||||
File(root, "goggame-7.info").writeText(
|
||||
"""{"playTasks":[
|
||||
{"category":"launcher","isPrimary":true,"path":"run.exe","type":"FileTask"},
|
||||
{"category":"game","path":"game.exe","type":"FileTask"}
|
||||
]}""",
|
||||
)
|
||||
assertEquals("run.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aPrimaryGameTaskBeatsAPrimaryLauncherTask() {
|
||||
withFolder { root ->
|
||||
root.exe("run.exe")
|
||||
root.exe("game.exe", 4096)
|
||||
File(root, "goggame-7.info").writeText(
|
||||
"""{"playTasks":[
|
||||
{"category":"launcher","isPrimary":true,"path":"run.exe","type":"FileTask"},
|
||||
{"category":"game","isPrimary":true,"path":"game.exe","type":"FileTask"}
|
||||
]}""",
|
||||
)
|
||||
assertEquals("game.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theProductsOwnManifestDecidesOverADlcManifest() {
|
||||
withFolder { root ->
|
||||
root.exe("base.exe")
|
||||
root.exe("dlc.exe", 4096)
|
||||
File(root, "goggame-7.info")
|
||||
.writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"base.exe","type":"FileTask"}]}""")
|
||||
File(root, "goggame-9.info")
|
||||
.writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"dlc.exe","type":"FileTask"}]}""")
|
||||
assertEquals("base.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aDlcManifestSuppliesTheGameWhenTheProductsOwnHasNone() {
|
||||
withFolder { root ->
|
||||
root.exe("dxconfig.exe")
|
||||
root.exe("dlc.exe", 4096)
|
||||
File(root, "goggame-7.info")
|
||||
.writeText("""{"playTasks":[{"category":"tool","path":"dxconfig.exe","type":"FileTask"}]}""")
|
||||
File(root, "goggame-9.info")
|
||||
.writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"dlc.exe","type":"FileTask"}]}""")
|
||||
assertEquals("dlc.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theManifestBeatsTheInstallerHint() {
|
||||
withFolder { root ->
|
||||
root.exe("dxconfig.exe")
|
||||
root.exe("kain.exe", 4096)
|
||||
File(root, "goggame-7.info")
|
||||
.writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"kain.exe","type":"FileTask"}]}""")
|
||||
assertEquals(
|
||||
"kain.exe",
|
||||
GogDownloadManager.pickExe(root, "7", "dxconfig.exe", "Blood Omen: Legacy of Kain"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// #694: the GOG build's temp executable is its Galaxy support installer, not the game.
|
||||
@Test
|
||||
fun theGalaxySupportInstallerIsNeverTheGame() {
|
||||
withFolder { root ->
|
||||
root.exe("galaxy_the_witcher_enhanced_edition_2.1.0.15.exe", 1_300_000)
|
||||
root.exe("launcher.exe")
|
||||
root.exe("register.exe")
|
||||
root.exe("System/witcher.exe", 4096)
|
||||
assertEquals(
|
||||
"System/witcher.exe",
|
||||
GogDownloadManager.pickExe(
|
||||
root,
|
||||
"1207658924",
|
||||
"galaxy_the_witcher_enhanced_edition_2.1.0.15.exe",
|
||||
"The Witcher: Enhanced Edition",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aManifestThatNamesTheGalaxySupportInstallerIsIgnored() {
|
||||
withFolder { root ->
|
||||
root.exe("galaxy_the_witcher_enhanced_edition_2.1.0.15.exe", 1_300_000)
|
||||
root.exe("System/witcher.exe", 4096)
|
||||
File(root, "goggame-1207658924.info").writeText(
|
||||
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"galaxy_the_witcher_enhanced_edition_2.1.0.15.exe","type":"FileTask"}]}""",
|
||||
)
|
||||
assertEquals(
|
||||
"System/witcher.exe",
|
||||
GogDownloadManager.pickExe(root, "1207658924", null, "The Witcher: Enhanced Edition"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// GOG's own sample manifest files the Configuration Tool as a non-primary launcher task.
|
||||
@Test
|
||||
fun aNonPrimaryLauncherTaskIsNotTheGame() {
|
||||
withFolder { root ->
|
||||
root.exe("Config2_DX9.exe")
|
||||
root.exe("ed6_win2_DX9.exe", 4096)
|
||||
File(root, "goggame-1207658924.info").writeText(
|
||||
"""{"playTasks":[
|
||||
{"category":"launcher","name":"Configuration Tool","path":"Config2_DX9.exe","type":"FileTask"},
|
||||
{"category":"game","path":"ed6_win2_DX9.exe","type":"FileTask"}
|
||||
]}""",
|
||||
)
|
||||
assertEquals(
|
||||
"ed6_win2_DX9.exe",
|
||||
GogDownloadManager.pickExe(root, "1207658924", null, "The Legend of Heroes: Trails in the Sky SC"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLoneNonPrimaryLauncherLeavesTheSearchInCharge() {
|
||||
withFolder { root ->
|
||||
root.exe("Config2_DX9.exe")
|
||||
root.exe("ed6_win2_DX9.exe", 4096)
|
||||
File(root, "goggame-1207658924.info").writeText(
|
||||
"""{"playTasks":[{"category":"launcher","path":"Config2_DX9.exe","type":"FileTask"}]}""",
|
||||
)
|
||||
assertEquals(
|
||||
"ed6_win2_DX9.exe",
|
||||
GogDownloadManager.pickExe(root, "1207658924", null, "The Legend of Heroes: Trails in the Sky SC"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSupportInstallerHintIsSkippedWhateverItsFolder() {
|
||||
withFolder { root ->
|
||||
root.exe("support/galaxy_setup.exe", 1_300_000)
|
||||
root.exe("System/witcher.exe", 4096)
|
||||
assertEquals(
|
||||
"System/witcher.exe",
|
||||
GogDownloadManager.pickExe(
|
||||
root,
|
||||
"1207658924",
|
||||
"support/galaxy_setup.exe",
|
||||
"The Witcher: Enhanced Edition",
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"System/witcher.exe",
|
||||
GogDownloadManager.pickExe(
|
||||
root,
|
||||
"1207658924",
|
||||
"support\\galaxy_setup.exe",
|
||||
"The Witcher: Enhanced Edition",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInstallerHintOutsideTheGameFolderIsIgnored() {
|
||||
withFolder { root ->
|
||||
root.exe("game.exe", 4096)
|
||||
val outside = File(root.parentFile, "outside-${System.nanoTime()}.exe").apply { writeBytes(ByteArray(8)) }
|
||||
try {
|
||||
assertEquals(
|
||||
"game.exe",
|
||||
GogDownloadManager.pickExe(root, "7", "../${outside.name}", "Some Game"),
|
||||
)
|
||||
} finally {
|
||||
outside.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GOG runs a task from the install root unless it declares a working directory.
|
||||
@Test
|
||||
fun aTaskWithoutAWorkingDirectoryRunsFromTheGameFolder() {
|
||||
withFolder { root ->
|
||||
root.exe("System/witcher.exe", 4096)
|
||||
File(root, "goggame-1207658924.info").writeText(
|
||||
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"System\\witcher.exe","type":"FileTask"}]}""",
|
||||
)
|
||||
val task = GogDownloadManager.pickTask(root, "1207658924", null, "The Witcher: Enhanced Edition")
|
||||
assertEquals("System/witcher.exe", task.path)
|
||||
assertEquals("", task.workDir)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDeclaredWorkingDirectoryIsKept() {
|
||||
withFolder { root ->
|
||||
root.exe("bin/x64/game.exe", 4096)
|
||||
File(root, "goggame-7.info").writeText(
|
||||
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"bin\\x64\\game.exe","workingDir":"bin\\x64","type":"FileTask"}]}""",
|
||||
)
|
||||
val task = GogDownloadManager.pickTask(root, "7", null, "Some Game")
|
||||
assertEquals("bin/x64/game.exe", task.path)
|
||||
assertEquals("bin/x64", task.workDir)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWorkingDirectoryThatLeavesTheGameFolderFallsBackToTheRoot() {
|
||||
withFolder { root ->
|
||||
root.exe("game.exe", 4096)
|
||||
File(root, "goggame-7.info").writeText(
|
||||
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"game.exe","workingDir":"../other","type":"FileTask"}]}""",
|
||||
)
|
||||
assertEquals("", GogDownloadManager.pickTask(root, "7", null, "Some Game").workDir)
|
||||
}
|
||||
}
|
||||
|
||||
// GOG manifests use doubled separators (The Witcher 3: "bin//x64//witcher3.exe"); the sidecar
|
||||
// parser rejects empty path components, so both values must be collapsed before they are stored.
|
||||
@Test
|
||||
fun duplicateSeparatorsInTaskValuesAreCollapsed() {
|
||||
withFolder { root ->
|
||||
root.exe("System/witcher.exe", 4096)
|
||||
File(root, "goggame-1207658924.info").writeText(
|
||||
"""{"playTasks":[{"category":"game","isPrimary":true,"path":"System//witcher.exe","workingDir":"System//","type":"FileTask"}]}""",
|
||||
)
|
||||
val task = GogDownloadManager.pickTask(root, "1207658924", null, "The Witcher: Enhanced Edition")
|
||||
assertEquals("System/witcher.exe", task.path)
|
||||
assertEquals("System", task.workDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/** The account listing: everything the tab needs to draw a library before a product is asked about. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GogListingTest {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class SyncSnapshotTest {
|
||||
private fun folder(state: String = "idle", global: Long = 100, need: Long = 0, blocked: Boolean = false, paused: Boolean = false, errors: Int = 0) =
|
||||
SyncFolder("id", "Saves", "/p", paused, blocked, state, global, need, errors, emptyList())
|
||||
|
||||
private fun snapshot(vararg folders: SyncFolder) = SyncSnapshot("me", folders.toList(), emptyList(), emptyList(), emptyList(), 0, 0)
|
||||
|
||||
@Test
|
||||
fun syncingReportsPercentOfActiveFolders() {
|
||||
val s = snapshot(folder("syncing", global = 1000, need = 360), folder())
|
||||
assertTrue(s.syncing)
|
||||
assertEquals(64, s.percent)
|
||||
assertEquals(360, s.needBytes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blockedOrFailingFoldersNeedAttention() {
|
||||
assertTrue(snapshot(folder(blocked = true, paused = true)).needsAttention)
|
||||
assertTrue(snapshot(folder(errors = 2)).needsAttention)
|
||||
assertTrue(snapshot(folder("idle", need = 5)).needsAttention)
|
||||
assertFalse(snapshot(folder(paused = true, errors = 2)).needsAttention)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unreadableFolderStatusShowsAsError() {
|
||||
val config = JSONObject("""{"id":"saves","label":"Saves","path":"/p","paused":false,"devices":[{"deviceID":"DEV1"}]}""")
|
||||
val f = SyncthingParse.folder(config, SyncthingParse.unreadableStatus(), blocked = false, names = mapOf("DEV1" to "Desktop PC"))
|
||||
assertEquals("error", f.state)
|
||||
assertTrue(f.errors > 0)
|
||||
assertTrue(f.outOfSync)
|
||||
assertFalse(f.syncing)
|
||||
assertEquals(listOf("Desktop PC"), f.sharedWith)
|
||||
assertTrue(snapshot(f).needsAttention)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parsesPendingFoldersWithDeviceNames() {
|
||||
val json = JSONObject("""{"emu":{"offeredBy":{"DEV1":{"label":"Emulation saves","time":"2026-01-01T00:00:00Z"}}}}""")
|
||||
val pending = SyncthingParse.pendingFolders(json, mapOf("DEV1" to "Desktop PC"))
|
||||
assertEquals(listOf(SyncPendingFolder("emu", "Emulation saves", "Desktop PC", "DEV1")), pending)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class SyncthingConfigTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private val generated = """
|
||||
<configuration version="51">
|
||||
<folder id="abc" label="Camera" path="/storage/emulated/0/DCIM" type="sendreceive">
|
||||
<paused>false</paused>
|
||||
</folder>
|
||||
<folder id="def" label="Saves" path="/data/user/0/app/Sync/saves" type="sendreceive">
|
||||
<paused>false</paused>
|
||||
</folder>
|
||||
<device id="PEER" name="Desktop" compression="metadata">
|
||||
<address>dynamic</address>
|
||||
<paused>false</paused>
|
||||
</device>
|
||||
<gui enabled="true" tls="true" debugging="false">
|
||||
<address>127.0.0.1:8384</address>
|
||||
<user>droiddeck</user>
|
||||
<apikey>key123</apikey>
|
||||
</gui>
|
||||
<options>
|
||||
<listenAddress>default</listenAddress>
|
||||
<localAnnouncePort>21027</localAnnouncePort>
|
||||
<urAccepted>0</urAccepted>
|
||||
<startBrowser>true</startBrowser>
|
||||
</options>
|
||||
<defaults>
|
||||
<folder id="" label="" path="~" type="sendreceive"></folder>
|
||||
</defaults>
|
||||
</configuration>
|
||||
""".trimIndent()
|
||||
|
||||
private val ports = SyncthingPorts(22100, 21127)
|
||||
|
||||
@Test
|
||||
fun pausesDisallowedFoldersBeforeLaunch() {
|
||||
val out = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { !it.startsWith("/storage/emulated/0/DCIM") }
|
||||
val camera = out.substringAfter("id=\"abc\"").substringBefore("</folder>")
|
||||
val saves = out.substringAfter("id=\"def\"").substringBefore("</folder>")
|
||||
assertTrue(camera.contains("<paused>true</paused>"))
|
||||
assertTrue(saves.contains("<paused>false</paused>"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pausesDevicesBeforeLaunchWhenPolicyRequires() {
|
||||
val paused = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync", pauseDevices = true) { true }
|
||||
assertTrue(paused.substringAfter("id=\"PEER\"").substringBefore("</device>").contains("<paused>true</paused>"))
|
||||
val open = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync", pauseDevices = false) { true }
|
||||
assertTrue(open.substringAfter("id=\"PEER\"").substringBefore("</device>").contains("<paused>false</paused>"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun replacesConfigFileWithoutLeavingStagedCopy() {
|
||||
val dir = tmp.newFolder()
|
||||
val file = File(dir, "config.xml").apply { writeText(generated) }
|
||||
SyncthingConfig.apply(file, ports, File("/data/st/gui.sock"), File("/ext/Sync"), false) { true }
|
||||
assertEquals(SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { true }, file.readText())
|
||||
assertEquals(listOf("config.xml"), dir.list()!!.toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun applyIsStable() {
|
||||
val once = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { true }
|
||||
assertEquals(once, SyncthingConfig.apply(once, ports, "/data/st/gui.sock", "/ext/Sync") { true })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun guiListensOnlyOnPrivateSocket() {
|
||||
val gui = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { true }.substringAfter("<gui").substringBefore("</gui>")
|
||||
assertTrue(gui.contains("<address>/data/st/gui.sock</address>"))
|
||||
assertTrue(gui.contains("<unixSocketPermissions>600</unixSocketPermissions>"))
|
||||
assertTrue(gui.contains("tls=\"false\""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
class SyncthingGuardTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun setup(): Triple<SyncthingGuard, File, File> {
|
||||
val data = tmp.newFolder("data")
|
||||
val external = tmp.newFolder("external")
|
||||
val home = File(external, "Sync").apply { mkdirs() }
|
||||
val config = File(data, "files/syncthing").apply { mkdirs() }
|
||||
return Triple(SyncthingGuard(home, listOf(data, external), listOf(config)), data, external)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun allowsFoldersInsideAppStorage() {
|
||||
val (guard, data, external) = setup()
|
||||
assertTrue(guard.allows(File(external, "Sync/Game saves").path))
|
||||
assertTrue(guard.allows(File(data, "files/linux/home").path))
|
||||
assertTrue(guard.allows("~/Shared"))
|
||||
assertTrue(guard.allows(external.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blocksFoldersOutsideAppStorage() {
|
||||
val (guard, _, _) = setup()
|
||||
assertFalse(guard.allows(tmp.newFolder("DCIM").path))
|
||||
assertFalse(guard.allows("/storage/emulated/0/Download"))
|
||||
assertFalse(guard.allows(""))
|
||||
assertFalse(guard.allows("relative/path"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blocksSyncthingsOwnConfig() {
|
||||
val (guard, data, _) = setup()
|
||||
assertFalse(guard.allows(File(data, "files/syncthing").path))
|
||||
assertFalse(guard.allows(File(data, "files/syncthing/keys").path))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blocksFoldersHoldingSyncthingsConfig() {
|
||||
val (guard, data, _) = setup()
|
||||
assertFalse(guard.allows(data.path))
|
||||
assertFalse(guard.allows(File(data, "files").path))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blocksSiblingWithSharedPrefix() {
|
||||
val (guard, _, external) = setup()
|
||||
assertFalse(guard.allows(external.path + "-other"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blocksSymlinkPointingOutside() {
|
||||
val (guard, _, external) = setup()
|
||||
val outside = tmp.newFolder("outside")
|
||||
val link = File(external, "Sync/link")
|
||||
Files.createSymbolicLink(link.toPath(), outside.toPath())
|
||||
assertFalse(guard.allows(link.path))
|
||||
assertFalse(guard.allows(File(link, "child").path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
class SyncthingHttpTest {
|
||||
private fun response(raw: String) = SyncthingHttp.readResponse(raw.byteInputStream(Charsets.ISO_8859_1))
|
||||
|
||||
@Test
|
||||
fun readsContentLengthBody() {
|
||||
assertEquals(200 to """{"ping":"pong"}""", response("HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n{\"ping\":\"pong\"}"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun readsChunkedBody() {
|
||||
assertEquals(403 to "CSRF Error", response("HTTP/1.1 403 Forbidden\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nCSRF\r\n6\r\n Error\r\n0\r\n\r\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writesOneShotRequest() {
|
||||
val out = ByteArrayOutputStream()
|
||||
SyncthingHttp.writeRequest(out, "POST", "/rest/system/pause", listOf("X-API-Key" to "k"), null)
|
||||
val text = out.toString("ISO-8859-1")
|
||||
assertTrue(text.startsWith("POST /rest/system/pause HTTP/1.1\r\n"))
|
||||
assertTrue(text.contains("Connection: close\r\n"))
|
||||
assertTrue(text.endsWith("X-API-Key: k\r\nContent-Length: 0\r\n\r\n"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SyncthingPortsTest {
|
||||
@Test
|
||||
fun skipsBusyPorts() {
|
||||
val busy = setOf(22100, 21127)
|
||||
val picked = SyncthingPortPicker.pick({ it !in busy }, { it !in busy })
|
||||
assertEquals(SyncthingPorts(22101, 21128), picked)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException::class)
|
||||
fun failsWhenNoPortIsFree() {
|
||||
SyncthingPortPicker.pick({ false }, { true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.graphics.Color
|
||||
import android.view.ContextThemeWrapper
|
||||
import com.droiddeck.launcher.R
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class AppThemeTest {
|
||||
@Test fun theNavigationBarIsOpaqueAndDarkSoNothingLightShowsThroughIt() {
|
||||
val themed = ContextThemeWrapper(RuntimeEnvironment.getApplication(), R.style.AppTheme)
|
||||
val attrs = themed.obtainStyledAttributes(intArrayOf(android.R.attr.navigationBarColor))
|
||||
val color = attrs.getColor(0, Color.TRANSPARENT)
|
||||
attrs.recycle()
|
||||
assertEquals(0xFF, Color.alpha(color))
|
||||
assertTrue(Color.luminance(color) < 0.1f)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BottomChatPageTest {
|
||||
@Test fun steamSitesOpenOthersDoNot() {
|
||||
assertTrue(steamChatAllows("steamcommunity.com"))
|
||||
assertTrue(steamChatAllows("login.steampowered.com"))
|
||||
assertTrue(steamChatAllows("steam-chat.com"))
|
||||
assertTrue(steamChatAllows("community.cloudflare.steamstatic.com"))
|
||||
assertFalse(steamChatAllows("steamcommunity.com.example.net"))
|
||||
assertFalse(steamChatAllows("evilsteamcommunity.com"))
|
||||
assertFalse(steamChatAllows(null))
|
||||
}
|
||||
|
||||
@Test fun chatFitScriptUsesADotDecimalInEveryLocale() {
|
||||
val before = java.util.Locale.getDefault()
|
||||
try {
|
||||
java.util.Locale.setDefault(java.util.Locale.GERMANY)
|
||||
val js = steamChatFitScript(821, 0.75f)
|
||||
assertTrue(js.contains("m.content='width=821, initial-scale=0.75'"))
|
||||
assertTrue(js.contains("s.textContent='$STEAM_CHAT_FIT_CSS'"))
|
||||
assertFalse(STEAM_CHAT_FIT_CSS.contains('\''))
|
||||
} finally {
|
||||
java.util.Locale.setDefault(before)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theGroupChatListLeavesRoomForTheOnlineFriends() {
|
||||
assertTrue(STEAM_CHAT_FIT_CSS.contains(".ChatRoomList_Empty{display:none!important}"))
|
||||
assertTrue(STEAM_CHAT_FIT_CSS.contains(".chatRoomListContainer{height:auto!important;max-height:25vh!important}"))
|
||||
assertTrue(STEAM_CHAT_FIT_CSS.contains(".chat_main>:has(~.chat_main_flex){display:none!important}"))
|
||||
}
|
||||
|
||||
@Test fun desktopAgentKeepsTheWebViewChromeVersion() {
|
||||
val ua = desktopUserAgent("Mozilla/5.0 (Linux; Android 15; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.122 Mobile Safari/537.36")
|
||||
assertEquals("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Safari/537.36", ua)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class BottomDashboardTest {
|
||||
@Test fun theRememberedPageOpensAgain() {
|
||||
assertEquals("shots", pickBottomPage("shots", listOf("downloads", "shots")))
|
||||
}
|
||||
|
||||
@Test fun aGoneOrMissingPageFallsBackToTheFirst() {
|
||||
assertEquals("downloads", pickBottomPage("gone", listOf("downloads", "shots")))
|
||||
assertEquals("downloads", pickBottomPage(null, listOf("downloads", "shots")))
|
||||
assertNull(pickBottomPage("shots", emptyList()))
|
||||
}
|
||||
|
||||
@Test fun withNothingPickedTheStatsOpen() {
|
||||
val ids = listOf("telemetry", "downloads", "notifications", "screenshots", "chat")
|
||||
assertEquals("telemetry", pickBottomPage(null, ids))
|
||||
assertEquals("telemetry", pickBottomPage("gone", ids))
|
||||
assertEquals("chat", pickBottomPage("chat", ids))
|
||||
assertEquals("telemetry", pickBottomPage("telemetry", ids))
|
||||
assertEquals("screenshots", pickBottomPage("screenshots", ids))
|
||||
}
|
||||
|
||||
@Test fun aGameStartShowsTheInGameStats() {
|
||||
assertEquals("telemetry", pageForGameStart(listOf("telemetry", "downloads", "chat")))
|
||||
assertNull(pageForGameStart(listOf("downloads", "chat")))
|
||||
}
|
||||
}
|
||||
|
||||
class BottomDownloadsRateTest {
|
||||
@Test fun rateIsBytesPerSecondBetweenReads() {
|
||||
assertEquals(1_000_000L, downloadRate(0L, 0L, 2_000_000L, 2_000L))
|
||||
}
|
||||
|
||||
@Test fun noMovementOrARestartIsZero() {
|
||||
assertEquals(0L, downloadRate(500L, 0L, 500L, 2_000L))
|
||||
assertEquals(0L, downloadRate(500L, 0L, 100L, 2_000L))
|
||||
assertEquals(0L, downloadRate(-1L, 0L, 100L, 2_000L))
|
||||
}
|
||||
}
|
||||
|
||||
class BottomTelemetryLapTimeTest {
|
||||
@Test fun lapTimesReadAsMinutesSecondsMillis() {
|
||||
assertEquals("1:23.456", lapTime(83.456f))
|
||||
assertEquals("0:05.000", lapTime(5f))
|
||||
}
|
||||
|
||||
@Test fun eachSessionStartsWithoutAPickedTab() {
|
||||
SessionBottomTab.pick("2026-11-01-01-steam", "screenshots")
|
||||
assertEquals("screenshots", SessionBottomTab.picked("2026-11-01-01-steam"))
|
||||
assertNull(SessionBottomTab.picked("2026-11-01-02-steam"))
|
||||
assertNull(SessionBottomTab.picked(null))
|
||||
assertEquals("telemetry", pickBottomPage(SessionBottomTab.picked("2026-11-01-02-steam"), listOf("telemetry", "chat", "screenshots")))
|
||||
}
|
||||
|
||||
@Test fun theStripNamesTheSteamClient() {
|
||||
assertEquals(com.droiddeck.launcher.R.string.stats_steam_client_x86, steamClientLabel("x86_64"))
|
||||
assertEquals(com.droiddeck.launcher.R.string.stats_steam_client_arm, steamClientLabel("arm64"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class BottomDesktopFitTest {
|
||||
@Test fun aDesktopOfThePanelsShapeFillsThePanel() {
|
||||
assertEquals(1280 to 870, fitDesktop(1280, 870, 1280, 870))
|
||||
assertEquals(1280 to 870, fitDesktop(1280, 870, 1278, 868))
|
||||
}
|
||||
|
||||
@Test fun aDesktopOfAnotherShapeIsFittedNotStretched() {
|
||||
val (w, h) = fitDesktop(1920, 1016, 1280, 870)
|
||||
assertEquals(1016, h)
|
||||
assertEquals(1494, w)
|
||||
}
|
||||
|
||||
@Test fun nothingToFitLeavesThePanelSize() {
|
||||
assertEquals(1920 to 1016, fitDesktop(1920, 1016, 0, 0))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.performClick
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], qualifiers = "w640dp-h480dp-land", application = android.app.Application::class)
|
||||
class BottomScreenBarTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
private val context = RuntimeEnvironment.getApplication()
|
||||
|
||||
@After fun reset() {
|
||||
SessionState.mode = SessionService.MODE_DESKTOP
|
||||
}
|
||||
|
||||
@Test fun steamSessionsGetSteamAndQuickAccess() {
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
var steam = 0
|
||||
var qam = 0
|
||||
val model = sessionBarModel("Trackpad", {}, {}, { steam++ }, { qam++ })
|
||||
assertNotNull(model.onSteam)
|
||||
assertNotNull(model.onQam)
|
||||
model.onSteam?.invoke()
|
||||
model.onQam?.invoke()
|
||||
assertEquals(1, steam)
|
||||
assertEquals(1, qam)
|
||||
}
|
||||
|
||||
@Test fun otherSessionsLeaveSteamOut() {
|
||||
SessionState.mode = SessionService.MODE_DESKTOP
|
||||
val model = sessionBarModel("Trackpad", {}, {}, {}, {})
|
||||
assertNull(model.onSteam)
|
||||
assertNull(model.onQam)
|
||||
}
|
||||
|
||||
@Test fun everyButtonOnTheBarReachesItsAction() {
|
||||
var closes = 0
|
||||
var menus = 0
|
||||
var steam = 0
|
||||
var qam = 0
|
||||
var keyboard = 0
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
BottomScreenBar(BottomBarModel("Trackpad", { closes++ }, { menus++ }, { steam++ }, { qam++ },
|
||||
listOf(BarExtra(context.getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) { keyboard++ })))
|
||||
}
|
||||
}
|
||||
for (label in listOf(R.string.common_close, R.string.touch_droiddeck_menu, R.string.drawer_steam_menu, R.string.drawer_open_qam,
|
||||
R.string.second_show_keyboard)) {
|
||||
compose.onNodeWithContentDescription(context.getString(label)).performClick()
|
||||
}
|
||||
compose.waitForIdle()
|
||||
assertEquals(listOf(1, 1, 1, 1, 1), listOf(closes, menus, steam, qam, keyboard))
|
||||
}
|
||||
|
||||
@Test fun aBarWithoutMenuOrSteamShowsOnlyClose() {
|
||||
compose.setContent {
|
||||
DroidDeckTheme { BottomScreenBar(BottomBarModel("Terminal", {}, null, null, null)) }
|
||||
}
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.common_close)).assertExists()
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.touch_droiddeck_menu)).assertDoesNotExist()
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.drawer_steam_menu)).assertDoesNotExist()
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.drawer_open_qam)).assertDoesNotExist()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class BuildWatermarkTest {
|
||||
@Test
|
||||
fun stableAndPreviewBuildsHaveNoWatermark() {
|
||||
assertNull(BuildWatermark.lines(pr = 0, ci = true, commit = "abcdef0123", title = "", branch = ""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun prBuildShowsNumberHashAndTitle() {
|
||||
assertEquals(
|
||||
listOf("PR-1234 | abcdef0", "Fix: foo the bar"),
|
||||
BuildWatermark.lines(pr = 1234, ci = true, commit = "abcdef0123", title = "Fix: foo the bar", branch = "x"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun longTitlesTruncateAtEightyCharacters() {
|
||||
val lines = BuildWatermark.lines(pr = 7, ci = true, commit = "abcdef0", title = "a".repeat(120), branch = "")!!
|
||||
assertEquals(80, lines[1].length)
|
||||
assertEquals('…', lines[1].last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun localBuildShowsBranch() {
|
||||
assertEquals(
|
||||
listOf("LOCAL | abcdef0", "feat/thing"),
|
||||
BuildWatermark.lines(pr = 0, ci = false, commit = "abcdef0123", title = "", branch = "feat/thing"),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.activity.ComponentActivity
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
@@ -26,7 +26,7 @@ import org.robolectric.annotation.Config
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], shadows = [JoyConPadTest.RecordingWriter::class])
|
||||
class DeckControlsPanelOwnershipTest {
|
||||
private val controller = Robolectric.buildActivity(Activity::class.java).setup()
|
||||
private val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup()
|
||||
private val activity = controller.get()
|
||||
private val root = FrameLayout(activity)
|
||||
private val bridge = PadBridge(File(activity.cacheDir, "panel-ownership"))
|
||||
|
||||
Loaded 100 of 819 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user