mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 12:56:06 +00:00
Merge upstream shortcuts and dual-screen session updates
Preserve profile bindings, shared held-input ownership and custom panels alongside upstream physical shortcuts, mouse routing and docked menus. Add integration regressions and record the full 2,918-test JVM run.
This commit is contained in:
commit
d6b4b0589b
630 files changed
+42269
-1875
No files matched your search
@@ -6,6 +6,9 @@ import java.net.Socket
|
||||
import java.nio.file.Files
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -29,6 +32,9 @@ class DownloaderResumeTest {
|
||||
@Volatile private var misbehave = false
|
||||
@Volatile private var etag: String? = "\"v1\""
|
||||
@Volatile private var corrupt = false
|
||||
@Volatile private var holdAfterFirstChunk = false
|
||||
private var bodyStarted = CountDownLatch(1)
|
||||
private var continueBody = CountDownLatch(1)
|
||||
|
||||
@Before fun setUp() {
|
||||
dir = Files.createTempDirectory("downloader-resume").toFile()
|
||||
@@ -70,8 +76,15 @@ class DownloaderResumeTest {
|
||||
val start = if (from == null) "200 OK" else "206 Partial Content"
|
||||
val extra = if (from == null) "" else "Content-Range: bytes 0-${data.size - 1}/${data.size}\r\n"
|
||||
out.write("HTTP/1.1 $start\r\n${extra}${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
out.write(content)
|
||||
out.flush()
|
||||
if (holdAfterFirstChunk) {
|
||||
out.write(content, 0, 1024)
|
||||
out.flush()
|
||||
bodyStarted.countDown()
|
||||
continueBody.await(5, TimeUnit.SECONDS)
|
||||
} else {
|
||||
out.write(content)
|
||||
out.flush()
|
||||
}
|
||||
} else if (from == null) {
|
||||
out.write("HTTP/1.1 200 OK\r\n${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
out.write(content, 0, cutAt)
|
||||
@@ -168,6 +181,48 @@ class DownloaderResumeTest {
|
||||
}
|
||||
|
||||
|
||||
@Test fun cancelStopsTheTransferWithoutTryingAnotherSource() {
|
||||
val first = "http://127.0.0.1:${server.localPort}/first"
|
||||
val second = "http://127.0.0.1:${server.localPort}/second"
|
||||
val target = File(dir, "runtime.tar.zst")
|
||||
misbehave = true
|
||||
val polls = java.util.concurrent.atomic.AtomicInteger()
|
||||
// candidate selection and attempt each check once before the request; later checks follow chunks
|
||||
val cancelled = java.util.function.BooleanSupplier { polls.incrementAndGet() > 2 }
|
||||
assertFalse(Downloader.downloadCandidates(first, listOf(first, second), target, true, null, cancelled, null))
|
||||
assertEquals("a cancel must not fall back to the next source", listOf<String?>(null), requests.toList())
|
||||
assertTrue("the transfer stopped early (kept=${target.length()})", target.length() in 1 until data.size)
|
||||
}
|
||||
|
||||
@Test fun cancellationDisconnectsAStalledTransfer() {
|
||||
val url = "http://127.0.0.1:${server.localPort}/first"
|
||||
val target = File(dir, "runtime.tar.zst")
|
||||
misbehave = true
|
||||
holdAfterFirstChunk = true
|
||||
val cancellation = Downloader.Cancellation()
|
||||
val executor = Executors.newSingleThreadExecutor()
|
||||
val cancelExecutor = Executors.newSingleThreadExecutor()
|
||||
try {
|
||||
val result = executor.submit<Boolean> { Downloader.downloadFile(url, target, true, null, cancellation, null) }
|
||||
assertTrue("server sent the first chunk", bodyStarted.await(2, TimeUnit.SECONDS))
|
||||
val cancelled = cancelExecutor.submit { cancellation.cancel() }
|
||||
cancelled.get(10, TimeUnit.SECONDS)
|
||||
assertFalse("cancelled download", result.get(10, TimeUnit.SECONDS))
|
||||
assertEquals(listOf<String?>(null), requests.toList())
|
||||
} finally {
|
||||
continueBody.countDown()
|
||||
executor.shutdownNow()
|
||||
cancelExecutor.shutdownNow()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aCancelBeforeTheFirstRequestSendsNothing() {
|
||||
val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst"
|
||||
val target = File(dir, "runtime.tar.zst")
|
||||
assertFalse(Downloader.downloadFile(url, target, true, null, { true }, null))
|
||||
assertEquals(emptyList<String?>(), requests.toList())
|
||||
}
|
||||
|
||||
@Test fun withoutADigestOnlyTheOriginalUrlIsTried() {
|
||||
val url = "https://github.com/owner/repo/releases/download/v1/app.AppImage"
|
||||
assertEquals(listOf(url), Downloader.sources(url, null))
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SettingsReset
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
|
||||
class SteamIntegrationSuggestionTest {
|
||||
private val context: Application = ApplicationProvider.getApplicationContext()
|
||||
|
||||
@Test fun closingTheSuggestionKeepsItHiddenForGood() {
|
||||
assertTrue(SteamIntegration.read(context).suggested)
|
||||
SteamIntegration.dismissSuggestion(context)
|
||||
assertFalse(SteamIntegration.read(context).suggested)
|
||||
SettingsReset.resetAll(context, gameProfiles = false)
|
||||
assertFalse(SteamIntegration.read(context).suggested)
|
||||
assertTrue(SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false))
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,135 @@ class AddedExesTest {
|
||||
assertEquals(listOf(pick.path), AddedGames.scan(app).map { it.exe.path })
|
||||
}
|
||||
|
||||
private fun result(r: AddedGames.AddResult): AddedGames.Game = when (r) {
|
||||
is AddedGames.AddResult.Added -> r.game
|
||||
is AddedGames.AddResult.Existing -> r.game
|
||||
is AddedGames.AddResult.Switched -> r.game
|
||||
else -> throw AssertionError("not added: $r")
|
||||
}
|
||||
|
||||
private fun visualNovels(): File {
|
||||
val storage = tmp.newFolder("PC Games")
|
||||
SessionPrefs.setAddedGamesDirs(app, emptyList())
|
||||
SessionPrefs.setGameStorage(app, storage.path, "SD card")
|
||||
exe(File(storage, "VNs/Albatross/Albatross Log.exe"))
|
||||
exe(File(storage, "VNs/Rance 01/Rance01.exe"))
|
||||
exe(File(storage, "VNs/Angel Beats/SiglusEngine.exe"))
|
||||
exe(File(storage, "VNs/Sayonara/SiglusEngine.exe"))
|
||||
return storage
|
||||
}
|
||||
|
||||
@Test fun aGroupFolderOnGameStorageListsEachGameInsideIt() {
|
||||
val storage = visualNovels()
|
||||
val vns = File(storage, "VNs")
|
||||
assertEquals(listOf("Albatross", "Angel Beats", "Rance 01", "Sayonara").map { File(vns, it).path },
|
||||
AddedGames.scan(app).map { it.folder.path })
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun anExePickedInAGroupFolderOnGameStorageIsItsOwnGame() {
|
||||
val storage = visualNovels()
|
||||
val vns = File(storage, "VNs")
|
||||
SessionPrefs.setAddedGameExe(app, vns.path, File(vns, "Albatross/Albatross Log.exe").path)
|
||||
for (pick in listOf("Rance 01/Rance01.exe", "Sayonara/SiglusEngine.exe", "Angel Beats/SiglusEngine.exe")) {
|
||||
val game = result(AddedGames.addExe(app, File(vns, pick)))
|
||||
assertEquals(File(vns, pick).parentFile!!.path, game.folder.path)
|
||||
}
|
||||
assertEquals(4, AddedGames.scan(app).size)
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aRemovedGroupFolderOnGameStorageStaysRemoved() {
|
||||
val storage = visualNovels()
|
||||
val group = File(storage, "VNs")
|
||||
val pick = File(group, "Rance 01/Rance01.exe")
|
||||
AddedGames.remove(app, group)
|
||||
val game = result(AddedGames.addExe(app, pick))
|
||||
assertEquals(pick.parentFile!!.path, game.folder.path)
|
||||
assertTrue(group.path in SessionPrefs.removedAddedGames(app))
|
||||
assertEquals(listOf(pick.parentFile!!.path), AddedGames.scan(app).map { it.folder.path })
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aSiblingExeOfAnAddedGameOnGameStorageSwitchesThatGame() {
|
||||
val storage = tmp.newFolder("PC Games")
|
||||
SessionPrefs.setAddedGamesDirs(app, emptyList())
|
||||
SessionPrefs.setGameStorage(app, storage.path, "SD card")
|
||||
val held = exe(File(storage, "Game/bin/Game.exe"))
|
||||
val pick = exe(File(storage, "Game/launcher/Launcher.exe"))
|
||||
val game = File(storage, "Game")
|
||||
AddedExes.put(app, AddedExes.Entry(game.path, held.path))
|
||||
val result = AddedGames.addExe(app, pick)
|
||||
assertTrue(result is AddedGames.AddResult.Switched)
|
||||
assertEquals(game.path, (result as AddedGames.AddResult.Switched).game.folder.path)
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aHiddenFolderInAGroupIsAddedAsItsOwnGame() {
|
||||
val storage = visualNovels()
|
||||
val vns = File(storage, "VNs")
|
||||
val pick = exe(File(vns, ".Gamma/Gamma.exe"))
|
||||
val game = result(AddedGames.addExe(app, pick))
|
||||
assertEquals(pick.parentFile!!.path, game.folder.path)
|
||||
assertTrue(AddedGames.scan(app).any { it.folder.path == pick.parentFile!!.path })
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aFolderThatDeclaresItsExeInASubfolderStaysOneGame() {
|
||||
val storage = tmp.newFolder("PC Games")
|
||||
SessionPrefs.setAddedGamesDirs(app, emptyList())
|
||||
SessionPrefs.setGameStorage(app, storage.path, "SD card")
|
||||
exe(File(storage, "Halo/Content/Halo.exe"))
|
||||
exe(File(storage, "Halo/Tools/ModKit.exe"))
|
||||
File(storage, "Halo/MicrosoftGame.config").writeText("<Game><Executable Name=\"Content\\Halo.exe\" /></Game>")
|
||||
assertEquals(listOf(File(storage, "Halo").path), AddedGames.scan(app).map { it.folder.path })
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aGroupFolderTheUserAddedAsOneGameStaysOneGame() {
|
||||
val storage = visualNovels()
|
||||
val vns = File(storage, "VNs")
|
||||
AddedExes.put(app, AddedExes.Entry(vns.path, File(vns, "Albatross/Albatross Log.exe").path))
|
||||
assertEquals(listOf(vns.path), AddedGames.scan(app).map { it.folder.path })
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aGameWithBuildFoldersOnGameStorageStaysOneGame() {
|
||||
val storage = tmp.newFolder("PC Games")
|
||||
SessionPrefs.setAddedGamesDirs(app, emptyList())
|
||||
SessionPrefs.setGameStorage(app, storage.path, "SD card")
|
||||
exe(File(storage, "Oddworld/x64/Oddworld.exe"))
|
||||
exe(File(storage, "Oddworld/x86/Oddworld.exe"))
|
||||
exe(File(storage, "Episodes/Episode1/Episode1.exe"))
|
||||
File(storage, "Episodes/Movies").mkdirs()
|
||||
assertEquals(listOf("Episodes", "Oddworld").map { File(storage, it).path }, AddedGames.scan(app).map { it.folder.path })
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aSiblingExeOfAGameOnGameStorageSwitchesThatGame() {
|
||||
val storage = tmp.newFolder("PC Games")
|
||||
SessionPrefs.setAddedGamesDirs(app, emptyList())
|
||||
SessionPrefs.setGameStorage(app, storage.path, "SD card")
|
||||
exe(File(storage, "Game/bin/Game.exe"))
|
||||
val pick = exe(File(storage, "Game/launcher/Launcher.exe"))
|
||||
val result = AddedGames.addExe(app, pick)
|
||||
assertTrue(result is AddedGames.AddResult.Switched)
|
||||
assertEquals(File(storage, "Game").path, (result as AddedGames.AddResult.Switched).game.folder.path)
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun aDeeperExeOfAGameOnGameStorageStillSwitchesThatGame() {
|
||||
val storage = tmp.newFolder("PC Games")
|
||||
SessionPrefs.setAddedGamesDirs(app, emptyList())
|
||||
SessionPrefs.setGameStorage(app, storage.path, "SD card")
|
||||
exe(File(storage, "Example/Example.exe"))
|
||||
val deep = exe(File(storage, "Example/bin/Example64.exe"))
|
||||
val result = AddedGames.addExe(app, deep)
|
||||
assertTrue(result is AddedGames.AddResult.Switched)
|
||||
assertEquals(File(storage, "Example").path, (result as AddedGames.AddResult.Switched).game.folder.path)
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
@Test fun anotherBuildOfTheSameExeInASiblingFolderSwitchesTheGame() {
|
||||
noGamesFolders()
|
||||
val held = onStorage("Games2/Oddworld/x64/Oddworld.exe")
|
||||
|
||||
@@ -446,4 +446,55 @@ class WinCompSourcesTest {
|
||||
AutoComponents.drain(app)
|
||||
assertTrue(AutoComponents.queued().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aLostPartOfAnInstalledBundleIsReinstalledAndTheGameWaitsForIt() = withFakeWorker {
|
||||
val bundle = WinComponents.Component("directmusic", "", "", "ready", listOf("dmband"), emptyList())
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + ready("dmband") + bundle }
|
||||
installedNow.addAll(listOf("directmusic", "d3dx9"))
|
||||
WinComponents.setUser(app, "4242", "directmusic", true)
|
||||
WinComponents.setUser(app, "4242", "d3dx9", true)
|
||||
session = true
|
||||
gameUp = true
|
||||
assertEquals(listOf("dmband"), AutoComponents.restoreMissing(app))
|
||||
assertTrue(downloaded.isEmpty())
|
||||
assertEquals("[\"dmband\"]", AutoComponents.Pending.read(app).optJSONArray("4242").toString())
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
assertEquals(listOf("dmband"), downloaded)
|
||||
assertEquals(0, AutoComponents.Pending.read(app).length())
|
||||
assertTrue(AutoComponents.restoreMissing(app).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aRestoreRunsADownloadQueuedBeforeTheSessionWithoutWaitingForItToEnd() = withFakeWorker {
|
||||
WinComponents.setUser(app, "4243", "vcredist2019_dll", true)
|
||||
session = true
|
||||
AutoComponents.queueGame(app, game(tmp.newFolder("Wait"), Library.ADDED), asked = true)
|
||||
AutoComponents.restoreMissing(app)
|
||||
AutoComponents.restoreMissing(app)
|
||||
assertEquals(listOf("vcredist2019_dll"), downloaded)
|
||||
session = false
|
||||
AutoComponents.drain(app)
|
||||
}
|
||||
|
||||
@Test fun aGameJobThatRunsFirstKeepsARestoredComponentPending() = withFakeWorker {
|
||||
AutoComponents.catalogOf = { _, _ -> catalog3 + ready("dmband") }
|
||||
val seen = ArrayList<List<String>>()
|
||||
AutoComponents.installer = { _, c, _, _ ->
|
||||
if (c.name == "dmband") seen.add(AutoComponents.Pending.ids(app, "1262580"))
|
||||
downloaded.add(c.name); installedNow.add(c.name); null
|
||||
}
|
||||
val game = payback()
|
||||
WinComponents.setUser(app, "1262580", "dmband", true)
|
||||
session = true
|
||||
gameUp = true
|
||||
AutoComponents.queueInSession(app, game)
|
||||
AutoComponents.restoreMissing(app)
|
||||
gameUp = false
|
||||
AutoComponents.drain(app)
|
||||
assertEquals(1, seen.size)
|
||||
assertTrue("dmband" in seen.single())
|
||||
assertEquals(0, AutoComponents.Pending.read(app).length())
|
||||
session = false
|
||||
AutoComponents.drain(app)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.glasses
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
@@ -15,6 +16,8 @@ class SpatialControllerModeTest {
|
||||
private fun snapshot(): ByteBuffer = (SpatialTracking::class.java.getDeclaredField("buffer")
|
||||
.apply { isAccessible = true }.get(null) as ByteBuffer).duplicate().order(ByteOrder.LITTLE_ENDIAN)
|
||||
|
||||
@Before fun outputOnGlasses() = SpatialTracking.setOutputUsesGlasses(true)
|
||||
|
||||
@After fun cleanUp() {
|
||||
SpatialTracking.setSteadyHandAim(false)
|
||||
SpatialTracking.setControllers(false, false)
|
||||
|
||||
@@ -64,6 +64,18 @@ class GpuDetectionTest {
|
||||
assertEquals(Support.UNSUPPORTED, info(false, 830).support)
|
||||
}
|
||||
|
||||
@Test fun adreno722IsSupportedOnlyOnTheRetroidPocketDuo() {
|
||||
assertEquals(true, GpuInfo.verifiedOn(722, "Retroid Pocket Duo"))
|
||||
assertEquals(false, GpuInfo.verifiedOn(722, "Retroid Pocket 5"))
|
||||
assertEquals(false, GpuInfo.verifiedOn(720, "Retroid Pocket Duo"))
|
||||
assertEquals(false, GpuInfo.verifiedOn(740, "Retroid Pocket Duo"))
|
||||
val duo = info(true, 722).copy(verifiedDevice = true)
|
||||
assertEquals(Support.TESTED, duo.support)
|
||||
assertEquals("Supported", duo.supportText)
|
||||
assertEquals(Family.A7XX_LOW, duo.family)
|
||||
assertEquals(Support.UNTESTED, info(true, 722).support)
|
||||
}
|
||||
|
||||
@Test fun userFacingTextPerTier() {
|
||||
assertEquals("Supported", info(true, 830).supportText)
|
||||
assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", info(true, 850).supportText)
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import kotlin.random.Random
|
||||
|
||||
class FrameStatsTest {
|
||||
/** MangoHud's update_hud_info_with_frametime and fps()/frame_timing(), line by line (overlay.cpp). */
|
||||
private class Mango {
|
||||
val frametimeData = ArrayList<Float>(List(200) { 0f })
|
||||
var lastPresentTime = 0L
|
||||
var lastFpsUpdate = 0L
|
||||
var framesSinceUpdate = 0L
|
||||
var fps = 0.0
|
||||
|
||||
fun update(frametimeNs: Long, now: Long) {
|
||||
val elapsed = now - lastFpsUpdate
|
||||
if (lastPresentTime != 0L) {
|
||||
frametimeData.add(frametimeNs / 1000000f)
|
||||
frametimeData.removeAt(0)
|
||||
}
|
||||
if (elapsed >= 500000000L) {
|
||||
fps = 1000000000.0 * framesSinceUpdate / elapsed
|
||||
framesSinceUpdate = 0
|
||||
lastFpsUpdate = now
|
||||
}
|
||||
lastPresentTime = now
|
||||
framesSinceUpdate++
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun readingsMatchMangoHudFrameByFrame() {
|
||||
val random = Random(7)
|
||||
val stats = FrameStats()
|
||||
val mango = Mango()
|
||||
var now = 5_000_000_000L
|
||||
val graph = FloatArray(FrameStats.GRAPH_FRAMES)
|
||||
repeat(20_000) { i ->
|
||||
val frametime = when {
|
||||
i % 977 == 0 -> 100_000_000L
|
||||
i % 131 == 0 -> 33_000_000L
|
||||
else -> 2_700_000L + random.nextLong(-400_000L, 400_000L)
|
||||
}
|
||||
now += frametime
|
||||
stats.add(frametime, now)
|
||||
mango.update(frametime, now)
|
||||
assertEquals("fps at frame $i", mango.fps.toFloat(), stats.fps, 0.0001f)
|
||||
assertEquals(1000f / maxOf(mango.fps.toFloat(), 1f), stats.frametimeMs(), 0.0001f)
|
||||
if (i % 499 == 0 || i < 210) {
|
||||
stats.graph(graph)
|
||||
assertArrayEquals("graph at frame $i", mango.frametimeData.toFloatArray(), graph, 0f)
|
||||
assertEquals(mango.frametimeData.min(), stats.graphMinMs(), 0f)
|
||||
assertEquals(mango.frametimeData.max(), stats.graphMaxMs(), 0f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun compositorFramesWakeTheHudWhenGamescopeSharesNone() {
|
||||
val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames"))
|
||||
var now = 1_000_000_000L
|
||||
assertFalse(feed.poll(now))
|
||||
feed.onCompositorFrame(now)
|
||||
now += 16_666_667L
|
||||
feed.onCompositorFrame(now)
|
||||
assertTrue(feed.poll(now))
|
||||
assertFalse(feed.poll(now + 1))
|
||||
}
|
||||
|
||||
@Test fun aCompletedPeriodIsCountedWhenMangoHudWouldRedraw() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
stats.add(10_000_000L, now)
|
||||
assertEquals(1L, stats.fpsUpdates)
|
||||
repeat(49) { now += 10_000_000L; stats.add(10_000_000L, now) }
|
||||
assertEquals(1L, stats.fpsUpdates)
|
||||
now += 10_000_000L; stats.add(10_000_000L, now)
|
||||
assertEquals(2L, stats.fpsUpdates)
|
||||
assertEquals(100f, stats.fps, 0.01f)
|
||||
}
|
||||
|
||||
@Test fun aSteadyRateReadsExactlyWithoutMillisecondRounding() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
val frametime = 16_666_667L
|
||||
repeat(600) { now += frametime; stats.add(frametime, now) }
|
||||
assertEquals(60f, stats.fps, 0.01f)
|
||||
val lows = stats.lows(now)
|
||||
assertEquals(60f, lows.low1Fps, 0.01f)
|
||||
assertEquals(60f, lows.low01Fps, 0.01f)
|
||||
assertEquals(60f, stats.averageFps(), 0.01f)
|
||||
}
|
||||
|
||||
@Test fun stuttersShowInTheGraphAndTheLows() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
repeat(1000) { i ->
|
||||
val frametime = if (i % 100 == 50) 100_000_000L else 2_700_000L
|
||||
now += frametime
|
||||
stats.add(frametime, now)
|
||||
}
|
||||
assertEquals(100f, stats.graphMaxMs(), 0.001f)
|
||||
assertEquals(2.7f, stats.graphMinMs(), 0.001f)
|
||||
assertEquals(10f, stats.lows(now).low01Fps, 0.01f)
|
||||
assertEquals(370.37f, stats.lows(now).low1Fps, 0.01f)
|
||||
}
|
||||
|
||||
@Test fun pausesStayOutOfTheAverageAndLowsButNotTheGraph() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
repeat(300) { now += 10_000_000L; stats.add(10_000_000L, now) }
|
||||
now += 3_000_000_000L
|
||||
stats.add(3_000_000_000L, now)
|
||||
assertEquals(100f, stats.lows(now).low01Fps, 0.01f)
|
||||
assertEquals(3000f, stats.graphMaxMs(), 0.01f)
|
||||
}
|
||||
|
||||
@Test fun resetStartsOver() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
repeat(300) { now += 10_000_000L; stats.add(10_000_000L, now) }
|
||||
stats.reset()
|
||||
assertEquals(0f, stats.fps, 0f)
|
||||
assertEquals(0f, stats.graphMaxMs(), 0f)
|
||||
assertEquals(FrameStats.Lows.EMPTY, stats.lows(now))
|
||||
}
|
||||
|
||||
@Test fun engineNamesFollowMangoHud() {
|
||||
assertEquals("DXVK", GameFrameFeed.engineLabel("DXVK"))
|
||||
assertEquals("VKD3D", GameFrameFeed.engineLabel("vkd3d"))
|
||||
assertEquals("ZINK", GameFrameFeed.engineLabel("mesa zink"))
|
||||
assertEquals("GAMESCOPE", GameFrameFeed.engineLabel("gamescope"))
|
||||
assertEquals("GAMESCOPE", GameFrameFeed.engineLabel(""))
|
||||
assertEquals("VULKAN", GameFrameFeed.engineLabel("UnityEngine"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.widget.FrameLayout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.time.Duration
|
||||
import java.util.Base64
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sqrt
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], qualifiers = "xhdpi")
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class FusionHudPanelTest {
|
||||
@Test fun minimalIsTheSizeTheHudStartsWith() {
|
||||
assertEquals(FusionSize.MINIMAL, FusionSize.from(FusionHudConfig.DEFAULTS["hudSize"]))
|
||||
}
|
||||
|
||||
@Test fun theHudStartsLocked() {
|
||||
assertEquals("1", FusionHudConfig.DEFAULTS["hudLocked"])
|
||||
}
|
||||
|
||||
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
repeat(2_000) { i ->
|
||||
val frametime = if (i == 1_700) 25_600_000L else 2_850_000L
|
||||
now += frametime
|
||||
stats.add(frametime, now)
|
||||
}
|
||||
val snapshot = SNAPSHOT
|
||||
for (size in FusionSize.values()) {
|
||||
val view = FusionHudView(RuntimeEnvironment.getApplication())
|
||||
view.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudSize" to size.token)))
|
||||
view.setFrameStats(stats)
|
||||
view.showForTest(snapshot, "DXVK", now)
|
||||
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
view.measure(unspecified, unspecified)
|
||||
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
|
||||
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(bitmap))
|
||||
|
||||
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
println("FUSIONHUD-${size.token.uppercase()}-PNG ${Base64.getEncoder().encodeToString(png.toByteArray())}")
|
||||
|
||||
val panel = view.panelForTest()!!
|
||||
assertTrue("$size panel inside the view",
|
||||
panel.left > 0f && panel.top > 0f && panel.right < view.width && panel.bottom < view.height)
|
||||
view.graphForTest()?.let { graph ->
|
||||
val r = view.panelRadiusForTest()
|
||||
val d = maxOf(panel.top + r - graph.top, graph.bottom - (panel.bottom - r), 0f)
|
||||
val edge = panel.right - r + sqrt(r * r - d * d)
|
||||
assertTrue("$size graph clears the round side", graph.right <= edge)
|
||||
}
|
||||
val orb = bitmap.getPixel(panel.left.roundToInt() + 1, panel.centerY().roundToInt())
|
||||
assertTrue("$size orb on the left side", Color.blue(orb) > 200 && Color.alpha(orb) > 200)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun pillShowsEachBatteryPartOnItsOwnSwitch() {
|
||||
fun pill(vararg settings: Pair<String, String>): List<String> {
|
||||
val view = FusionHudView(RuntimeEnvironment.getApplication())
|
||||
view.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudSize" to FusionSize.PILL.token) + settings))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
return view.linesForTest()
|
||||
}
|
||||
val all = pill("showBattery" to "1")
|
||||
assertTrue(all.toString(), all.any { "BAT 79% · 34°C · 16.0W" in it })
|
||||
assertEquals(all.toString(), 1, all.count { "BAT" in it })
|
||||
assertFalse(all.toString(), all.single { "RAM" in it }.contains("BAT"))
|
||||
|
||||
val noMemory = pill("showBattery" to "1", "showRAM" to "0")
|
||||
assertTrue(noMemory.toString(), noMemory.none { "RAM" in it })
|
||||
assertTrue(noMemory.toString(), noMemory.any { "BAT 79% · 34°C · 16.0W" in it })
|
||||
|
||||
val defaults = pill()
|
||||
assertTrue(defaults.toString(), defaults.any { "BAT 34°C · 16.0W" in it })
|
||||
val wattsOnly = pill("showBatteryTemp" to "0")
|
||||
assertTrue(wattsOnly.toString(), wattsOnly.any { "BAT 16.0W" in it })
|
||||
val nothing = pill("showBatteryTemp" to "0", "showPower" to "0")
|
||||
assertTrue(nothing.toString(), nothing.none { "BAT" in it })
|
||||
}
|
||||
|
||||
@Test fun aLockedHudLetsTouchesThroughOnlyWhereAControlTakesThem() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
var reached = 0
|
||||
val under = View(app).apply {
|
||||
setOnTouchListener { _, e -> if (e.actionMasked == MotionEvent.ACTION_DOWN) reached++; true }
|
||||
}
|
||||
val hud = FusionHudView(app)
|
||||
val parent = FrameLayout(app)
|
||||
parent.addView(under, FrameLayout.LayoutParams(2000, 2000))
|
||||
parent.addView(hud, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
|
||||
var control = false
|
||||
hud.passesTouchAt = { _, _ -> control }
|
||||
val locks = ArrayList<Boolean>()
|
||||
hud.setOnLockChangedListener { locks += it }
|
||||
hud.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudLocked" to "0")))
|
||||
hud.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
val exactly = View.MeasureSpec.makeMeasureSpec(2000, View.MeasureSpec.EXACTLY)
|
||||
parent.measure(exactly, exactly)
|
||||
parent.layout(0, 0, 2000, 2000)
|
||||
assertTrue(hud.width > 0 && hud.height > 0)
|
||||
fun touch(holdMs: Long = 50L) {
|
||||
val x = hud.width / 2f; val y = hud.height / 2f
|
||||
val down = SystemClock.uptimeMillis()
|
||||
MotionEvent.obtain(down, down, MotionEvent.ACTION_DOWN, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(holdMs))
|
||||
MotionEvent.obtain(down, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x, y, 0).also { parent.dispatchTouchEvent(it); it.recycle() }
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
}
|
||||
control = true
|
||||
touch()
|
||||
assertEquals("an unlocked HUD keeps the touch (tap, drag, long press)", 0, reached)
|
||||
hud.applyConfig(FusionHudConfig.encode(FusionHudConfig.DEFAULTS + ("hudLocked" to "1")))
|
||||
touch()
|
||||
assertEquals("a locked HUD passes it to the control under it", 1, reached)
|
||||
control = false
|
||||
touch()
|
||||
assertEquals("a locked HUD keeps a touch no control takes", 1, reached)
|
||||
touch(holdMs = ViewConfiguration.getLongPressTimeout() + 300L)
|
||||
assertEquals("a long press there unlocks it", listOf(false), locks)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val SNAPSHOT = HudMetrics.Snapshot(64, 52, 3302, 1050, 89, 79, 10_800_000_000L, 16_000_000_000L, 67f,
|
||||
1_800_000_000L, HudMetrics.Battery(16f, false, 79, 34, null),
|
||||
intArrayOf(91, 91, 48, 50, 48, 19, 17, 73), intArrayOf(2265, 2265, 3148, 3148, 3148, 2956, 2956, 3302),
|
||||
2_700_000_000L, 6_400_000_000L, 31_000L, 9_000L)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class MangoReadingsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun readings() = MangoReadings(tmp.root, tmp.root)
|
||||
|
||||
@Test fun cpuLoadFollowsMangoHudsFormulaAndTruncates() {
|
||||
val stat = File(tmp.root, "stat")
|
||||
val m = readings()
|
||||
// user nice system idle iowait irq softirq steal guest guest_nice
|
||||
stat.writeText("cpu 1000 100 500 8000 400 50 50 0 200 0\ncpu0 500 50 250 4000 200 25 25 0 100 0\ncpu1 500 50 250 4000 200 25 25 0 100 0\nintr 0\n")
|
||||
m.cpu(stat)
|
||||
stat.writeText("cpu 1500 100 700 8600 500 60 70 10 300 0\ncpu0 900 50 400 4100 250 30 35 10 200 0\ncpu1 600 50 300 4500 250 30 35 0 100 0\nintr 0\n")
|
||||
val cpu = m.cpu(stat)!!
|
||||
// busy = user-guest 400 + nice 0 + system+irq+softirq 230 + steal 10 + guest 100 = 740 of 1440 (idle+iowait 700)
|
||||
assertEquals((740 * 100f / 1440).toInt(), cpu.percent)
|
||||
assertEquals(51, cpu.percent)
|
||||
assertArrayEquals(intArrayOf(((300 + 165 + 10 + 100) * 100f / (300 + 165 + 10 + 100 + 150)).toInt(), ((100 + 65) * 100f / (100 + 65 + 550)).toInt()), cpu.perCore)
|
||||
}
|
||||
|
||||
@Test fun anUnchangedCounterKeepsTheLastLoad() {
|
||||
val stat = File(tmp.root, "stat")
|
||||
val m = readings()
|
||||
stat.writeText("cpu 100 0 0 100 0 0 0 0 0 0\n")
|
||||
m.cpu(stat)
|
||||
stat.writeText("cpu 200 0 0 100 0 0 0 0 0 0\n")
|
||||
assertEquals(100, m.cpu(stat)!!.percent)
|
||||
assertEquals(100, m.cpu(stat)!!.percent)
|
||||
}
|
||||
|
||||
private fun battery(status: String, chargeNow: Long, chargeFull: Long, powerUw: Long) {
|
||||
val dir = File(tmp.root, "sys/power_supply/BAT1").apply { mkdirs() }
|
||||
File(dir, "status").writeText("$status\n")
|
||||
File(dir, "charge_now").writeText("$chargeNow\n")
|
||||
File(dir, "charge_full").writeText("$chargeFull\n")
|
||||
File(dir, "power_now").writeText("$powerUw\n")
|
||||
}
|
||||
|
||||
@Test fun batteryHidesWattsWhileChargingAsMangoHudDoes() {
|
||||
battery("Discharging", 3_622_942, 3_854_193, 8_760_000)
|
||||
val discharging = readings().battery()!!
|
||||
assertEquals(94, discharging.percent)
|
||||
assertEquals(8.76f, discharging.watts, 0.001f)
|
||||
assertFalse(discharging.charging)
|
||||
battery("Charging", 3_622_942, 3_854_193, 8_760_000)
|
||||
val charging = readings().battery()!!
|
||||
assertEquals(0f, charging.watts, 0f)
|
||||
assertTrue(charging.charging)
|
||||
}
|
||||
|
||||
@Test fun noBatteryFolderMeansNoReading() {
|
||||
assertNull(readings().battery())
|
||||
}
|
||||
|
||||
@Test fun gpuLoadIsTheLeadingNumber() {
|
||||
val f = File(tmp.root, "perf_now").apply { writeText(" 6 %\n") }
|
||||
assertEquals(6.0, MangoReadings.leadingNumber(f)!!, 0.0)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Looper
|
||||
import android.view.InputDevice
|
||||
import android.view.MotionEvent
|
||||
import java.time.Duration
|
||||
import org.junit.Assert.*
|
||||
@@ -13,68 +14,171 @@ import org.robolectric.annotation.Config
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class DirectTouchHoldTest {
|
||||
private val events = mutableListOf<String>()
|
||||
private val touches = mutableListOf<String>()
|
||||
private val buttons = mutableListOf<String>()
|
||||
private val hold = DirectTouchHold(8f, object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) {}
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
assertEquals(PointerGestures.BTN_RIGHT, button)
|
||||
events += "$pressed at $x,$y"
|
||||
buttons += "$pressed at $x,$y"
|
||||
}
|
||||
override fun onWheel(steps: Int) {}
|
||||
override fun onLongPress() {}
|
||||
}) { events += "cancel touch" }.also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
|
||||
}, object : DirectTouchHold.Touch {
|
||||
override fun down(pointerId: Int, x: Float, y: Float) { touches += "down $pointerId at $x,$y" }
|
||||
override fun move(pointerId: Int, x: Float, y: Float) { touches += "move $pointerId at $x,$y" }
|
||||
override fun up(pointerId: Int, x: Float, y: Float) { touches += "up $pointerId at $x,$y" }
|
||||
override fun cancel() { touches += "cancel" }
|
||||
}).also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
|
||||
|
||||
@Test fun holdReleasesRawTouchBeforeClickAndConsumesTheLift() {
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN))
|
||||
advance(500)
|
||||
assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events)
|
||||
assertTrue(touch(MotionEvent.ACTION_UP))
|
||||
@Test fun holdClicksRightWithoutTouchingTheGame() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(400)
|
||||
assertTrue(buttons.isEmpty())
|
||||
advance(100)
|
||||
assertEquals(listOf("true at 40.0,30.0"), buttons)
|
||||
advance(50)
|
||||
assertEquals("false at 40.0,30.0", events.last())
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN))
|
||||
hold.cancel()
|
||||
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
|
||||
touch(MotionEvent.ACTION_MOVE, 44f)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
assertTrue(touches.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun stillHoldKeepsTheTouchWhenLongPressIsOff() {
|
||||
@Test fun tapForwardsTheTouchWhenItLifts() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(100)
|
||||
touch(MotionEvent.ACTION_UP, 50f)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
|
||||
advance(50)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 50.0,30.0"), touches)
|
||||
assertTrue(buttons.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun noneBehaviorForwardsTheTouchAtOnce() {
|
||||
hold.configure(TouchGestureConfig(directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_NONE))
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
|
||||
advance(600)
|
||||
assertTrue(buttons.isEmpty())
|
||||
touch(MotionEvent.ACTION_MOVE, 60f)
|
||||
assertEquals("move 0 at 60.0,30.0", touches.last())
|
||||
touch(MotionEvent.ACTION_UP, 60f)
|
||||
advance(50)
|
||||
assertEquals("up 0 at 60.0,30.0", touches.last())
|
||||
}
|
||||
|
||||
@Test fun dragForwardsTheTouchOnceItMoves() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_MOVE, 60f)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "move 0 at 60.0,30.0"), touches)
|
||||
advance(600)
|
||||
assertTrue(buttons.isEmpty())
|
||||
touch(MotionEvent.ACTION_UP, 60f)
|
||||
advance(50)
|
||||
assertEquals("up 0 at 60.0,30.0", touches.last())
|
||||
}
|
||||
|
||||
@Test fun dragKeepsForwardingWithinTheSlop() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_MOVE, 44f)
|
||||
assertTrue(touches.isEmpty())
|
||||
touch(MotionEvent.ACTION_UP, 44f)
|
||||
advance(50)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 44.0,30.0"), touches)
|
||||
}
|
||||
|
||||
@Test fun stillHoldClicksRightWithTheDefaultConfig() {
|
||||
hold.configure(TouchGestureConfig())
|
||||
assertFalse(touch(MotionEvent.ACTION_DOWN))
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(2000)
|
||||
assertFalse(touch(MotionEvent.ACTION_MOVE))
|
||||
assertFalse(touch(MotionEvent.ACTION_UP))
|
||||
assertTrue(events.isEmpty())
|
||||
touch(MotionEvent.ACTION_MOVE)
|
||||
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
assertTrue(touches.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun longPressFollowsTheConfiguredDelay() {
|
||||
hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800))
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(700)
|
||||
assertTrue(events.isEmpty())
|
||||
assertTrue(buttons.isEmpty())
|
||||
advance(100)
|
||||
assertEquals(listOf("cancel touch", "true at 40.0,30.0"), events)
|
||||
assertEquals(listOf("true at 40.0,30.0"), buttons)
|
||||
hold.cancel()
|
||||
}
|
||||
|
||||
@Test fun tapDragSecondFingerAndCancellationDoNotRightClick() {
|
||||
for (action in listOf(MotionEvent.ACTION_UP, MotionEvent.ACTION_MOVE,
|
||||
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_CANCEL)) {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
assertFalse(touch(action, 60f))
|
||||
advance(600)
|
||||
assertTrue(events.isEmpty())
|
||||
hold.cancel()
|
||||
}
|
||||
@Test fun holdBehaviorKeepsTheButtonUntilTheLift() {
|
||||
hold.configure(TouchGestureConfig(longPressDelay = 500,
|
||||
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_HOLD))
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(500)
|
||||
assertEquals(listOf("true at 40.0,30.0"), buttons)
|
||||
advance(1000)
|
||||
assertEquals(listOf("true at 40.0,30.0"), buttons)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
|
||||
assertTrue(touches.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun secondFingerForwardsTheTouchAndDropsTheHold() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 60f)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "down 0 at 60.0,30.0"), touches)
|
||||
advance(600)
|
||||
assertTrue(buttons.isEmpty())
|
||||
touch(MotionEvent.ACTION_UP, 60f)
|
||||
}
|
||||
|
||||
@Test fun modeChangeCancelsPendingHoldAndReleasesAnActiveClick() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
hold.cancel()
|
||||
advance(600)
|
||||
assertTrue(events.isEmpty())
|
||||
assertTrue(buttons.isEmpty())
|
||||
assertTrue(touches.isEmpty())
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(500)
|
||||
hold.cancel()
|
||||
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
|
||||
}
|
||||
|
||||
@Test fun cancelForwardsACancelWhenTheTouchIsLive() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_MOVE, 60f)
|
||||
hold.cancel()
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "move 0 at 60.0,30.0", "cancel"), touches)
|
||||
}
|
||||
|
||||
@Test fun cancelDropsAPendingLift() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_UP, 60f)
|
||||
hold.cancel()
|
||||
advance(100)
|
||||
assertEquals(listOf("cancel touch", "true at 40.0,30.0", "false at 40.0,30.0"), events)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "cancel"), touches)
|
||||
}
|
||||
|
||||
@Test fun aQuickSecondTapLiftsTheFirstInsteadOfCancellingIt() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_UP, 50f)
|
||||
advance(20)
|
||||
touch(MotionEvent.ACTION_DOWN, 60f)
|
||||
touch(MotionEvent.ACTION_UP, 60f)
|
||||
advance(50)
|
||||
assertEquals(
|
||||
listOf("down 0 at 40.0,30.0", "up 0 at 50.0,30.0", "down 0 at 60.0,30.0", "up 0 at 60.0,30.0"),
|
||||
touches,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun theSecondFingerLiftsWithItsOwnId() {
|
||||
multi(MotionEvent.ACTION_DOWN, 0, 0 to 40f)
|
||||
multi(MotionEvent.ACTION_POINTER_DOWN, 1, 0 to 40f, 1 to 60f)
|
||||
multi(MotionEvent.ACTION_POINTER_UP, 0, 0 to 40f, 1 to 60f)
|
||||
multi(MotionEvent.ACTION_UP, 0, 1 to 60f)
|
||||
advance(100)
|
||||
assertEquals(
|
||||
listOf("down 0 at 40.0,30.0", "down 1 at 60.0,30.0", "up 0 at 40.0,30.0", "up 1 at 60.0,30.0"),
|
||||
touches,
|
||||
)
|
||||
}
|
||||
|
||||
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
|
||||
@@ -82,4 +186,23 @@ class DirectTouchHoldTest {
|
||||
val event = MotionEvent.obtain(0, 0, action, x, 30f, 0)
|
||||
return hold.onTouch(event).also { event.recycle() }
|
||||
}
|
||||
private fun multi(action: Int, index: Int, vararg points: Pair<Int, Float>): Boolean {
|
||||
val properties = Array(points.size) {
|
||||
MotionEvent.PointerProperties().apply {
|
||||
id = points[it].first
|
||||
toolType = MotionEvent.TOOL_TYPE_FINGER
|
||||
}
|
||||
}
|
||||
val coords = Array(points.size) {
|
||||
MotionEvent.PointerCoords().apply {
|
||||
x = points[it].second
|
||||
y = 30f
|
||||
pressure = 1f
|
||||
size = 1f
|
||||
}
|
||||
}
|
||||
val event = MotionEvent.obtain(0, 0, action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT),
|
||||
points.size, properties, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
|
||||
return hold.onTouch(event).also { event.recycle() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.view.Display
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(manifest = Config.NONE)
|
||||
class DualScreenTest {
|
||||
private val context: Context = ApplicationProvider.getApplicationContext()
|
||||
private val displays = context.getSystemService(DisplayManager::class.java)
|
||||
|
||||
@Test fun internalPanelsCountAsBuiltIn() {
|
||||
assertTrue(DualScreen.isBuiltIn(1, "Anything"))
|
||||
assertFalse(DualScreen.isBuiltIn(2, "Retroid Pocket Duo"))
|
||||
assertFalse(DualScreen.isBuiltIn(5, "AYN Thor"))
|
||||
}
|
||||
|
||||
@Test fun knownModelsCountWhenTheTypeIsHidden() {
|
||||
assertTrue(DualScreen.isBuiltIn(null, "Retroid Pocket Duo"))
|
||||
assertTrue(DualScreen.isBuiltIn(null, " AYN Thor "))
|
||||
assertFalse(DualScreen.isBuiltIn(null, "Pixel 8"))
|
||||
}
|
||||
|
||||
@Test fun oneScreenDevicesGetNoSecondScreenInAnyMode() {
|
||||
for (mode in DualScreen.modes) {
|
||||
SessionPrefs.setDualScreenMode(context, mode)
|
||||
assertNull(DualScreen.display(context, displays, Display.DEFAULT_DISPLAY))
|
||||
assertNull(DualScreen.anyDisplay(displays, Display.DEFAULT_DISPLAY))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun modeDefaultsToAutomaticAndIgnoresUnknownValues() {
|
||||
assertEquals(DualScreen.MODE_AUTO, SessionPrefs.dualScreenMode(context))
|
||||
SessionPrefs.setDualScreenMode(context, "sideways")
|
||||
assertEquals(DualScreen.MODE_AUTO, SessionPrefs.dualScreenMode(context))
|
||||
SessionPrefs.setDualScreenMode(context, DualScreen.MODE_OFF)
|
||||
assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context))
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowBuild
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28, 33], manifest = Config.NONE, application = Application::class)
|
||||
@@ -67,4 +68,24 @@ class HomeGuideInputTest {
|
||||
assertEquals(listOf(true, false), states)
|
||||
assertEquals(1, cancellations)
|
||||
}
|
||||
|
||||
private fun quickMenu(action: Int) = KeyEvent(10, 110, action, KeyEvent.KEYCODE_HOME, 0, 0, 10, 194)
|
||||
|
||||
@Test fun duoQuickMenuHomePassesThroughToTheSystemAndCancelsAHeldGuide() {
|
||||
ShadowBuild.setModel("Retroid Pocket Duo")
|
||||
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true))
|
||||
assertFalse(input.onKeyEvent(quickMenu(KeyEvent.ACTION_DOWN), true))
|
||||
assertEquals(listOf(true, false), states)
|
||||
assertEquals(1, cancellations)
|
||||
assertFalse(input.onKeyEvent(quickMenu(KeyEvent.ACTION_UP), true))
|
||||
assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), true))
|
||||
assertEquals(listOf(true, false), states)
|
||||
}
|
||||
|
||||
@Test fun theSameScanCodeStillHoldsGuideOnOtherDevices() {
|
||||
ShadowBuild.setModel("Retroid Pocket 5")
|
||||
assertTrue(input.onKeyEvent(quickMenu(KeyEvent.ACTION_DOWN), true))
|
||||
assertTrue(input.onKeyEvent(quickMenu(KeyEvent.ACTION_UP), true))
|
||||
assertEquals(listOf(true, false), states)
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,17 @@ class OnScreenControlsTest {
|
||||
assertEquals(-1, field(control("rs"), "pressedBy"))
|
||||
}
|
||||
|
||||
@Test fun takesTouchAtMatchesWhatATouchDoes() {
|
||||
var checked = 0
|
||||
for (x in 0 until 1200 step 40) for (y in 0 until 800 step 40) {
|
||||
val expected = view.takesTouchAt(x.toFloat(), y.toFloat())
|
||||
assertEquals("($x, $y)", expected, touch(MotionEvent.ACTION_DOWN, 0 to (x.toFloat() to y.toFloat())))
|
||||
touch(MotionEvent.ACTION_UP, 0 to (x.toFloat() to y.toFloat()))
|
||||
if (expected) checked++
|
||||
}
|
||||
assertTrue("some points land on controls", checked > 0)
|
||||
}
|
||||
|
||||
@Test fun fixedSticksAndEditorRemainVisibleAtSavedPositions() {
|
||||
ControllerPrefs.setAdaptiveSticks(context, false)
|
||||
view.reload()
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.input.InputManager
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import com.droiddeck.launcher.input.PhysicalShortcuts.Action
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.InputDeviceBuilder
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], manifest = Config.NONE, shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
|
||||
class PhysicalShortcutsTest {
|
||||
private val context: Context get() = RuntimeEnvironment.getApplication()
|
||||
private val router = PhysicalShortcutRouter()
|
||||
private val actions = mutableListOf<Action>()
|
||||
private lateinit var pad: InputDevice
|
||||
|
||||
@Before fun setUp() {
|
||||
ControllerPrefs.prefs(context).edit().clear().commit()
|
||||
pad = device(10, "retroid")
|
||||
}
|
||||
|
||||
@Test fun defaultsDoNotInterceptAnyButton() {
|
||||
assertTrue(PhysicalShortcuts.read(context).isEmpty())
|
||||
for (code in listOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_BUTTON_MODE,
|
||||
KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_1)) {
|
||||
assertFalse(route(key(code)))
|
||||
assertFalse(route(key(code, KeyEvent.ACTION_UP)))
|
||||
}
|
||||
assertTrue(actions.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun assignmentPersistsAndConsumesTheWholePressWithoutRepeating() {
|
||||
assign(key(), Action.STEAM)
|
||||
assertEquals(listOf(PhysicalShortcuts.Binding(button(key()), Action.STEAM)), PhysicalShortcuts.read(context))
|
||||
assertTrue(route(key()))
|
||||
assertTrue(route(key(repeat = 1)))
|
||||
assertTrue(route(key(repeat = 2)))
|
||||
assertTrue(route(key(action = KeyEvent.ACTION_UP)))
|
||||
assertEquals(listOf(Action.STEAM), actions)
|
||||
assertFalse(route(key(action = KeyEvent.ACTION_UP)))
|
||||
}
|
||||
|
||||
@Test fun releaseIsConsumedEvenIfAnActionChangedTheRoutingContextOrSettings() {
|
||||
assign(key(), Action.DROIDDECK)
|
||||
assertTrue(route(key()))
|
||||
router.bindings = emptyList()
|
||||
assertTrue(route(key(action = KeyEvent.ACTION_UP), enabled = false, steam = false))
|
||||
assertEquals(listOf(Action.DROIDDECK), actions)
|
||||
}
|
||||
|
||||
@Test fun aRepeatedDownWithoutAnInitialPressDoesNotTriggerAnAction() {
|
||||
assign(key(), Action.QAM)
|
||||
assertTrue(route(key(repeat = 1)))
|
||||
assertTrue(route(key(action = KeyEvent.ACTION_UP)))
|
||||
assertTrue(actions.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun disabledMappedConfirmLeavesTheWholePressForDrawerNavigation() {
|
||||
assign(key(KeyEvent.KEYCODE_BUTTON_A), Action.DROIDDECK)
|
||||
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A), enabled = false))
|
||||
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, repeat = 1), enabled = false))
|
||||
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false))
|
||||
assertTrue(actions.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun mappedConfirmOpeningTheDrawerConsumesItsReleaseWithoutStayingHeld() {
|
||||
assign(key(KeyEvent.KEYCODE_BUTTON_A), Action.DROIDDECK)
|
||||
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A)))
|
||||
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, repeat = 1), enabled = false))
|
||||
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false))
|
||||
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A), enabled = false))
|
||||
assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false))
|
||||
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A)))
|
||||
assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP)))
|
||||
assertEquals(listOf(Action.DROIDDECK, Action.DROIDDECK), actions)
|
||||
}
|
||||
|
||||
@Test fun aResumePressKeepsItsRepeatsAndReleaseInTheResumePath() {
|
||||
assign(key(), Action.STEAM)
|
||||
assertFalse(route(key(), enabled = false))
|
||||
assertFalse(route(key(repeat = 1), enabled = false))
|
||||
assertFalse(route(key(action = KeyEvent.ACTION_UP), enabled = false))
|
||||
assertTrue(actions.isEmpty())
|
||||
assertTrue(route(key()))
|
||||
assertEquals(listOf(Action.STEAM), actions)
|
||||
}
|
||||
|
||||
@Test fun steamActionsAreInactiveOutsideSteamAndAllActionsRespectDisabledContexts() {
|
||||
for (action in Action.entries) {
|
||||
assign(key(), action)
|
||||
assertFalse(route(key(), enabled = false))
|
||||
assertFalse(route(key(action = KeyEvent.ACTION_UP), enabled = false))
|
||||
assertEquals(action == Action.DROIDDECK, route(key(), steam = false))
|
||||
route(key(action = KeyEvent.ACTION_UP), steam = false)
|
||||
}
|
||||
assertEquals(listOf(Action.DROIDDECK), actions)
|
||||
}
|
||||
|
||||
@Test fun reassigningAButtonReplacesItsPreviousAction() {
|
||||
assign(key(), Action.STEAM)
|
||||
assign(key(), Action.QAM)
|
||||
assertEquals(listOf(Action.QAM), PhysicalShortcuts.read(context).map { it.action })
|
||||
assertTrue(route(key()))
|
||||
assertEquals(listOf(Action.QAM), actions)
|
||||
}
|
||||
|
||||
@Test fun reassigningAnActionOnlyReplacesThatControllersBinding() {
|
||||
val second = device(11, "bluetooth")
|
||||
assign(key(), Action.STEAM)
|
||||
assign(key(device = second), Action.STEAM)
|
||||
assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.STEAM)
|
||||
val saved = PhysicalShortcuts.read(context)
|
||||
assertEquals(2, saved.size)
|
||||
assertTrue(saved.any { it.button.sameInput(button(key(device = second))) })
|
||||
assertTrue(saved.any { it.button.sameInput(button(key(KeyEvent.KEYCODE_BUTTON_2))) })
|
||||
assertFalse(route(key()))
|
||||
}
|
||||
|
||||
@Test fun deviceIdentitySurvivesReconnectionButDoesNotMatchAnUnrelatedController() {
|
||||
assign(key(), Action.QAM)
|
||||
assertFalse(route(key(device = device(11, "other"))))
|
||||
val reconnected = device(12, "retroid")
|
||||
assertTrue(route(key(device = reconnected)))
|
||||
assertEquals(listOf(Action.QAM), actions)
|
||||
}
|
||||
|
||||
@Test fun scanCodesDistinguishButtonsSharingAnAndroidKeyCode() {
|
||||
assign(key(scan = 700), Action.STEAM)
|
||||
assign(key(scan = 701), Action.QAM)
|
||||
assertEquals(2, PhysicalShortcuts.read(context).size)
|
||||
assertTrue(route(key(scan = 700)))
|
||||
assertTrue(route(key(scan = 701)))
|
||||
assertFalse(route(key(scan = 702)))
|
||||
assertEquals(listOf(Action.STEAM, Action.QAM), actions)
|
||||
}
|
||||
|
||||
@Test fun keyboardLikeExtraButtonsCanBeExplicitlyAssignedWithoutChangingKeyboardDefaults() {
|
||||
val keyboard = device(11, "m1-keyboard", InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_ALPHABETIC)
|
||||
val m1 = key(KeyEvent.KEYCODE_F1, device = keyboard)
|
||||
assertFalse(PadBridge.isControllerKeyEvent(m1))
|
||||
assign(m1, Action.STEAM)
|
||||
assertTrue(route(m1))
|
||||
assertFalse(route(key(KeyEvent.KEYCODE_F2, device = keyboard)))
|
||||
assertEquals(listOf(Action.STEAM), actions)
|
||||
}
|
||||
|
||||
@Test fun virtualAndSystemKeysCannotBeAssigned() {
|
||||
val virtual = device(-1, "virtual")
|
||||
assertNull(PhysicalShortcuts.button(key(device = virtual)))
|
||||
for (code in listOf(KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_APP_SWITCH,
|
||||
KeyEvent.KEYCODE_SLEEP, KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_VOLUME_UP,
|
||||
KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) {
|
||||
assertNull(PhysicalShortcuts.button(key(code)))
|
||||
}
|
||||
assertNull(PhysicalShortcuts.button(key(KeyEvent.KEYCODE_UNKNOWN, scan = 0)))
|
||||
assertNotNull(PhysicalShortcuts.button(key(KeyEvent.KEYCODE_UNKNOWN, scan = 700)))
|
||||
}
|
||||
|
||||
@Test fun drawerDirectionalKeysRemainAvailableForNavigation() {
|
||||
for (code in listOf(KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT)) {
|
||||
assertTrue(PhysicalShortcuts.isDrawerNavigationKey(key(code)))
|
||||
}
|
||||
assertFalse(PhysicalShortcuts.isDrawerNavigationKey(key(KeyEvent.KEYCODE_BUTTON_A)))
|
||||
}
|
||||
|
||||
@Test fun resetAndRemovalPreserveOtherControllerSettings() {
|
||||
ControllerPrefs.setSelectSteam(context, true)
|
||||
ControllerPrefs.setTarget(context, "a", "b")
|
||||
assign(key(), Action.STEAM)
|
||||
assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM)
|
||||
PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).first())
|
||||
assertEquals(listOf(Action.QAM), PhysicalShortcuts.read(context).map { it.action })
|
||||
PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).single())
|
||||
assertTrue(PhysicalShortcuts.read(context).isEmpty())
|
||||
assertTrue(ControllerPrefs.read(context).selectSteam)
|
||||
assertEquals("b", ControllerPrefs.target(context, "a"))
|
||||
assign(key(), Action.STEAM)
|
||||
ControllerPrefs.resetAll(context)
|
||||
assertTrue(PhysicalShortcuts.read(context).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun disconnectAndPauseClearHeldButtons() {
|
||||
assign(key(), Action.QAM)
|
||||
assertTrue(route(key()))
|
||||
router.onDeviceRemoved(pad.id)
|
||||
assertFalse(route(key(action = KeyEvent.ACTION_UP)))
|
||||
assertTrue(route(key()))
|
||||
router.clear()
|
||||
assertFalse(route(key(action = KeyEvent.ACTION_UP)))
|
||||
assertTrue(route(key()))
|
||||
assertEquals(listOf(Action.QAM, Action.QAM, Action.QAM), actions)
|
||||
}
|
||||
|
||||
@Test fun malformedPreferencesDoNotCrashInputDispatch() {
|
||||
ControllerPrefs.prefs(context).edit().putString("physicalShortcuts", "invalid").commit()
|
||||
assertTrue(PhysicalShortcuts.read(context).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun malformedEntriesDoNotDiscardValidAssignmentsWhenSaving() {
|
||||
assign(key(), Action.STEAM)
|
||||
assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM)
|
||||
val entries = JSONArray(ControllerPrefs.prefs(context).getString("physicalShortcuts", null))
|
||||
val damaged = JSONArray().put(entries.getJSONObject(0)).put(JSONObject().put("action", "STEAM"))
|
||||
.put("not an object").put(entries.getJSONObject(1))
|
||||
ControllerPrefs.prefs(context).edit().putString("physicalShortcuts", damaged.toString()).commit()
|
||||
assertEquals(listOf(Action.STEAM, Action.QAM), PhysicalShortcuts.read(context).map { it.action })
|
||||
assign(key(KeyEvent.KEYCODE_BUTTON_3), Action.DROIDDECK)
|
||||
assertEquals(listOf(Action.STEAM, Action.QAM, Action.DROIDDECK),
|
||||
PhysicalShortcuts.read(context).map { it.action })
|
||||
}
|
||||
|
||||
@Test fun buttonSummaryKeepsTechnicalDetailsSeparate() {
|
||||
val select = button(key(KeyEvent.KEYCODE_BUTTON_SELECT, scan = 314))
|
||||
val androidName = KeyEvent.keyCodeToString(KeyEvent.KEYCODE_BUTTON_SELECT)
|
||||
assertEquals(androidName.removePrefix("KEYCODE_").removePrefix("BUTTON_"), select.label)
|
||||
assertFalse(select.label.contains("(314)"))
|
||||
}
|
||||
|
||||
private fun assign(event: KeyEvent, action: Action) {
|
||||
PhysicalShortcuts.assign(context, button(event), action)
|
||||
router.bindings = PhysicalShortcuts.read(context)
|
||||
}
|
||||
|
||||
private fun button(event: KeyEvent) = requireNotNull(PhysicalShortcuts.button(event))
|
||||
|
||||
private fun route(event: KeyEvent, enabled: Boolean = true, steam: Boolean = true) =
|
||||
router.onKey(event, enabled, steam) { actions.add(it) }
|
||||
|
||||
private fun key(code: Int = KeyEvent.KEYCODE_BUTTON_1, action: Int = KeyEvent.ACTION_DOWN,
|
||||
repeat: Int = 0, scan: Int = 700, device: InputDevice = pad): KeyEvent =
|
||||
KeyEvent(100L, 100L, action, code, repeat, 0, device.id, scan, 0, device.sources)
|
||||
|
||||
private fun device(id: Int, descriptor: String, sources: Int = InputDevice.SOURCE_GAMEPAD,
|
||||
type: Int = InputDevice.KEYBOARD_TYPE_NONE): InputDevice {
|
||||
val device = InputDeviceBuilder.newBuilder().setId(id).setName("Test $descriptor")
|
||||
.setDescriptor(descriptor).setSources(sources).setKeyboardType(type)
|
||||
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build()
|
||||
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
|
||||
return device
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,22 @@ class ScreenKeysTest {
|
||||
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
|
||||
}
|
||||
|
||||
@Test fun takesTouchAtMatchesWhatATouchDoes() {
|
||||
val keys = ScreenKeys(context) { _, _ -> }
|
||||
keys.layout(0, 0, 1000, 600)
|
||||
keys.add(listOf(KeyEvent.KEYCODE_W))
|
||||
var checked = 0
|
||||
for (x in 0 until 1000 step 25) for (y in 0 until 600 step 25) {
|
||||
val expected = keys.takesTouchAt(x.toFloat(), y.toFloat())
|
||||
val down = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, x.toFloat(), y.toFloat(), 0)
|
||||
assertEquals("($x, $y)", expected, keys.onTouchEvent(down))
|
||||
down.recycle()
|
||||
MotionEvent.obtain(0L, 1L, MotionEvent.ACTION_UP, x.toFloat(), y.toFloat(), 0).also { keys.onTouchEvent(it); it.recycle() }
|
||||
if (expected) checked++
|
||||
}
|
||||
assertTrue("some points land on the key", checked > 0)
|
||||
}
|
||||
|
||||
@Test fun loadingLayoutReleasesLatchedKeysBeforeReplacingEntries() {
|
||||
val sent = mutableListOf<Pair<Int, Boolean>>()
|
||||
val keys = ScreenKeys(context) { code, down -> sent += code to down }
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SecondScreenModeTest {
|
||||
@Test fun withNothingRememberedTheControllerPicksThePanel() {
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false))
|
||||
}
|
||||
|
||||
@Test fun thePanelTheUserPickedLastOpensAgain() {
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true))
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("deck-controls", deckPad = true))
|
||||
assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad = true))
|
||||
}
|
||||
|
||||
@Test fun deckControlsNeedTheDeckPad() {
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false))
|
||||
}
|
||||
|
||||
@Test fun customControlsReopenWithEitherControllerType() {
|
||||
for (deckPad in listOf(false, true)) {
|
||||
assertEquals(SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.opening("custom-controls", deckPad))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun anUnknownOrClosedChoiceFallsBackToTheDefault() {
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true))
|
||||
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad = false))
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,46 @@ class SessionBackBindingTest {
|
||||
assertTrue(events.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun capturedProfileBindingTakesPrecedenceOverGlobalShortcut() {
|
||||
assignMenuShortcut()
|
||||
bindings.configure(listOf(PhysicalInputBinding(PhysicalInputKey.capture(event(true))!!, InputAction.Keys(listOf(28)))))
|
||||
assertTrue(activity.dispatchKeyEvent(event(true)))
|
||||
assertTrue(activity.dispatchKeyEvent(event(false)))
|
||||
assertEquals(listOf(28 to true, 28 to false), events)
|
||||
assertFalse(drawerOpen())
|
||||
}
|
||||
|
||||
@Test fun globalShortcutOverridesDefaultBackQamAndConsumesReleaseAcrossMenuChange() {
|
||||
assignMenuShortcut()
|
||||
assertTrue(activity.dispatchKeyEvent(event(true)))
|
||||
assertTrue(drawerOpen())
|
||||
advance(700)
|
||||
assertFalse(JoyConPadTest.RecordingWriter.pads[0]?.isDown(PadState.QAM) == true)
|
||||
assertTrue(activity.dispatchKeyEvent(event(false)))
|
||||
assertTrue(drawerOpen())
|
||||
assertTrue(activity.dispatchKeyEvent(event(true)))
|
||||
assertFalse(drawerOpen())
|
||||
assertTrue(activity.dispatchKeyEvent(event(false)))
|
||||
assertTrue(events.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun inputSettingsDoNotExecuteGlobalShortcuts() {
|
||||
assignMenuShortcut()
|
||||
ReflectionHelpers.getField<MutableState<Boolean>>(activity, "inputSettingsOpen\$delegate").value = true
|
||||
activity.dispatchKeyEvent(event(true))
|
||||
activity.dispatchKeyEvent(event(false))
|
||||
assertFalse(drawerOpen())
|
||||
assertTrue(events.isEmpty())
|
||||
}
|
||||
|
||||
private fun assignMenuShortcut() {
|
||||
ReflectionHelpers.getField<PhysicalShortcutRouter>(activity, "physicalShortcuts").bindings =
|
||||
listOf(PhysicalShortcuts.Binding(PhysicalShortcuts.button(event(true))!!, PhysicalShortcuts.Action.DROIDDECK))
|
||||
}
|
||||
|
||||
private fun drawerOpen(): Boolean =
|
||||
ReflectionHelpers.getField<MutableState<Boolean>>(activity, "drawerOpenState\$delegate").value
|
||||
|
||||
private fun event(down: Boolean) = KeyEvent(0L, 0L, if (down) KeyEvent.ACTION_DOWN else KeyEvent.ACTION_UP,
|
||||
KeyEvent.KEYCODE_BACK, 0, 0, 42, 158, 0, InputDevice.SOURCE_KEYBOARD)
|
||||
|
||||
|
||||
@@ -220,7 +220,12 @@ class SessionGestureRoutingTest {
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { directButtons += button to pressed }
|
||||
override fun onWheel(steps: Int) {}
|
||||
override fun onLongPress() {}
|
||||
}) {}.also { it.configure(config) }
|
||||
}, object : DirectTouchHold.Touch {
|
||||
override fun down(pointerId: Int, x: Float, y: Float) {}
|
||||
override fun move(pointerId: Int, x: Float, y: Float) {}
|
||||
override fun up(pointerId: Int, x: Float, y: Float) {}
|
||||
override fun cancel() {}
|
||||
}).also { it.configure(config) }
|
||||
setField("directTouchHold", directHold)
|
||||
launcherScroll = ScrollTouchGestures(8f, 50f, object : ScrollTouchGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) { scrollPositions += x to y }
|
||||
|
||||
@@ -41,6 +41,8 @@ class SessionInputPointerTest {
|
||||
refresh()
|
||||
CompositorShadow.pointers.clear()
|
||||
CompositorShadow.events.clear()
|
||||
CompositorShadow.keys.clear()
|
||||
WriterShadow.mouse.clear()
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
@@ -124,6 +126,55 @@ class SessionInputPointerTest {
|
||||
assertFalse(state<Boolean>("cursorVisible").value)
|
||||
}
|
||||
|
||||
@Test fun mappedPointerStaysVisibleWithDirectTouchSelected() {
|
||||
ReflectionHelpers.setField(activity, "routedTouchMode", com.droiddeck.launcher.session.SessionPrefs.TOUCH_DIRECT)
|
||||
state<Boolean>("directCursorOn").value = false
|
||||
output.pointer(20f, 10f)
|
||||
assertTrue(state<Boolean>("cursorVisible").value)
|
||||
}
|
||||
|
||||
@Test fun touchpadZoomDoesNotReleaseCtrlHeldByTheProfileOrScreenKeys() {
|
||||
val held = ReflectionHelpers.getField<HeldInput>(activity, "heldKeys")
|
||||
output.key(29, true)
|
||||
held.set(64, 29, true)
|
||||
ReflectionHelpers.getField<PointerGestures.Listener>(activity, "pointerListener").onZoom(1)
|
||||
assertEquals(listOf(29 to 1), CompositorShadow.keys)
|
||||
output.key(29, false)
|
||||
assertEquals(listOf(29 to 1), CompositorShadow.keys)
|
||||
held.set(64, 29, false)
|
||||
assertEquals(listOf(29 to 1, 29 to 0), CompositorShadow.keys)
|
||||
assertEquals(listOf(Triple(4, 1, 0)), CompositorShadow.events)
|
||||
}
|
||||
|
||||
@Test fun routedMouseUsesRawBackendAndKeepsSharedButtonOwnership() {
|
||||
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
|
||||
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
|
||||
ReflectionHelpers.setField(activity, "pointerLocked", true)
|
||||
val held = ReflectionHelpers.getField<HeldInput>(activity, "heldButtons")
|
||||
output.button(272, true)
|
||||
held.set(2, 272, true)
|
||||
output.button(272, false)
|
||||
assertEquals(listOf("button:272:true"), WriterShadow.mouse)
|
||||
held.set(2, 272, false)
|
||||
output.pointer(2.5f, -1.25f)
|
||||
output.scroll(2)
|
||||
assertEquals(listOf("button:272:true", "button:272:false", "delta:2.5:-1.25", "wheel:-2:0:120"), WriterShadow.mouse)
|
||||
assertTrue(CompositorShadow.events.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun leavingRawMouseReleasesItsHoldBeforeReturningToTheWaylandSeat() {
|
||||
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
|
||||
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
|
||||
output.button(272, true)
|
||||
invoke("closeEvdevMouse")
|
||||
output.button(272, false)
|
||||
assertEquals(listOf("button:272:true", "button:272:false", "release"), WriterShadow.mouse)
|
||||
assertTrue(CompositorShadow.events.isEmpty())
|
||||
output.button(272, true)
|
||||
output.button(272, false)
|
||||
assertEquals(listOf(Triple(3, 272, 1), Triple(3, 272, 0)), CompositorShadow.events)
|
||||
}
|
||||
|
||||
private fun refresh() = invoke("refreshInputProfile")
|
||||
private fun invoke(name: String) = ReflectionHelpers.callInstanceMethod<Unit>(activity, name)
|
||||
private fun <T> state(name: String): MutableState<T> = ReflectionHelpers.getField(activity, "$name\$delegate")
|
||||
@@ -133,15 +184,22 @@ class SessionInputPointerTest {
|
||||
companion object {
|
||||
val pointers = mutableListOf<Triple<Int, Int, Int>>()
|
||||
val events = mutableListOf<Triple<Int, Int, Int>>()
|
||||
val keys = mutableListOf<Pair<Int, Int>>()
|
||||
@JvmStatic @Implementation fun __staticInitializer__() {}
|
||||
@JvmStatic @Implementation fun nativeSendPointer(action: Int, x: Int, y: Int) { pointers += Triple(action, x, y) }
|
||||
@JvmStatic @Implementation fun nativeSendSceneInput(type: Int, code: Int, value: Int) { events += Triple(type, code, value) }
|
||||
@JvmStatic @Implementation fun nativeSendKey(code: Int, value: Int) { keys += code to value }
|
||||
}
|
||||
}
|
||||
|
||||
@Implements(value = FakeInputWriter::class, isInAndroidSdk = false)
|
||||
class WriterShadow {
|
||||
@Implementation fun writeMouseButton(code: Short, down: Boolean) { mouse += "button:$code:$down" }
|
||||
@Implementation fun writeMouseDelta(dx: Float, dy: Float) { mouse += "delta:$dx:$dy" }
|
||||
@Implementation fun writeMouseWheel(vertical: Int, horizontal: Int, value120: Int) { mouse += "wheel:$vertical:$horizontal:$value120" }
|
||||
@Implementation fun softRelease() { mouse += "release" }
|
||||
companion object {
|
||||
val mouse = mutableListOf<String>()
|
||||
@JvmStatic @Implementation fun __staticInitializer__() {}
|
||||
@JvmStatic @Implementation fun writeDeckControls(index: Int, mask: Int, pads: ShortArray, pressure: ShortArray) {}
|
||||
}
|
||||
|
||||
@@ -25,11 +25,14 @@ class TouchpadGesturesTest {
|
||||
private val listener = object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) { events += "move" }
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
val name = if (button == PointerGestures.BTN_RIGHT) "right" else "left"
|
||||
val name = when (button) { PointerGestures.BTN_RIGHT -> "right"; PointerGestures.BTN_MIDDLE -> "middle"; else -> "left" }
|
||||
events += "$name ${if (pressed) "down" else "up"}"
|
||||
}
|
||||
override fun onWheel(steps: Int) { events += "wheel $steps" }
|
||||
override fun onLongPress() { events += "long press" }
|
||||
override fun onScroll(dx: Float, dy: Float) { events += "scroll" }
|
||||
override fun onScrollEnd() { events += "scroll end" }
|
||||
override fun onZoom(steps: Int) { events += "zoom $steps" }
|
||||
}
|
||||
|
||||
@Before fun setUp() {
|
||||
@@ -41,12 +44,58 @@ class TouchpadGesturesTest {
|
||||
@Test fun tapHoldsTheLeftButtonBeforeReleasingIt() {
|
||||
tap()
|
||||
assertEquals(listOf("left down"), events)
|
||||
advance(40)
|
||||
advance(TouchTiming.CLICK_MS - 10)
|
||||
assertEquals(listOf("left down"), events)
|
||||
advance(100)
|
||||
assertEquals(listOf("left down", "left up"), events)
|
||||
}
|
||||
|
||||
@Test fun threeFingerTapClicksTheMiddleButton() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 2, 1 to (400f to 300f), 2 to (600f to 310f), 3 to (800f to 320f))
|
||||
advance(60)
|
||||
touch(MotionEvent.ACTION_POINTER_UP, 2, 1 to (400f to 300f), 2 to (600f to 310f), 3 to (800f to 320f))
|
||||
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 310f))
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
|
||||
advance(100)
|
||||
assertEquals(listOf("middle down", "middle up"), events)
|
||||
}
|
||||
|
||||
@Test fun desktopTwoFingerSlideScrollsSmoothlyAndStops() {
|
||||
touchpad.desktop = true
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 300f))
|
||||
for (step in 1..5) {
|
||||
advance(16)
|
||||
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 300f + step * 20f), 2 to (600f to 300f + step * 20f))
|
||||
}
|
||||
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 400f), 2 to (600f to 400f))
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 400f))
|
||||
advance(100)
|
||||
assertTrue(events.contains("scroll"))
|
||||
assertEquals("scroll end", events.last())
|
||||
assertFalse(events.any { it.startsWith("right") || it.startsWith("wheel") })
|
||||
}
|
||||
|
||||
@Test fun desktopPinchZoomsWithoutScrolling() {
|
||||
touchpad.desktop = true
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (500f to 300f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (500f to 300f), 2 to (600f to 300f))
|
||||
for (step in 1..6) {
|
||||
advance(16)
|
||||
touch(MotionEvent.ACTION_MOVE, 0, 1 to (500f - step * 30f to 300f), 2 to (600f + step * 30f to 300f))
|
||||
}
|
||||
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (320f to 300f), 2 to (780f to 300f))
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (320f to 300f))
|
||||
advance(100)
|
||||
assertTrue(events.isNotEmpty() && events.all { it.startsWith("zoom -") })
|
||||
}
|
||||
|
||||
@Test fun twoFingerTapHoldsTheRightButtonBeforeReleasingIt() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(10)
|
||||
@@ -56,7 +105,7 @@ class TouchpadGesturesTest {
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
|
||||
assertEquals(listOf("right down"), events)
|
||||
advance(30)
|
||||
advance(TouchTiming.CLICK_MS - 20)
|
||||
assertEquals(listOf("right down"), events)
|
||||
advance(100)
|
||||
assertEquals(listOf("right down", "right up"), events)
|
||||
@@ -71,7 +120,7 @@ class TouchpadGesturesTest {
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
|
||||
assertEquals(listOf("right down"), events)
|
||||
advance(40)
|
||||
advance(TouchTiming.CLICK_MS - 10)
|
||||
assertEquals(listOf("right down"), events)
|
||||
advance(100)
|
||||
assertEquals(listOf("right down", "right up"), events)
|
||||
|
||||
@@ -82,9 +82,9 @@ class TouchscreenGesturesTest {
|
||||
@Test fun aVeryFastDoubleTapKeepsFullPressesAndAReleaseGap() {
|
||||
tap(); tap(); advance(250)
|
||||
assertEquals(4, leftClicks.size)
|
||||
assertTrue(leftClicks[1].time - leftClicks[0].time >= 50)
|
||||
assertTrue(leftClicks[2].time - leftClicks[1].time >= 50)
|
||||
assertTrue(leftClicks[3].time - leftClicks[2].time >= 50)
|
||||
assertTrue(leftClicks[1].time - leftClicks[0].time >= TouchTiming.CLICK_MS)
|
||||
assertTrue(leftClicks[2].time - leftClicks[1].time >= TouchTiming.CLICK_MS)
|
||||
assertTrue(leftClicks[3].time - leftClicks[2].time >= TouchTiming.CLICK_MS)
|
||||
}
|
||||
|
||||
@Test fun doubleTapUsesTheFirstClickLocationDespiteNormalFingerDrift() {
|
||||
@@ -121,7 +121,7 @@ class TouchscreenGesturesTest {
|
||||
gestures.configure(TouchGestureConfig(tapEnabled = false))
|
||||
tap(); tap(); advance(250)
|
||||
assertEquals(4, leftClicks.size)
|
||||
assertTrue(leftClicks[2].time - leftClicks[1].time >= 50)
|
||||
assertTrue(leftClicks[2].time - leftClicks[1].time >= TouchTiming.CLICK_MS)
|
||||
}
|
||||
|
||||
@Test fun aRapidThirdTapDoesNotDiscardThePendingSecondClick() {
|
||||
@@ -285,11 +285,11 @@ class TouchscreenGesturesTest {
|
||||
@Test fun twoFingerTapKeepsItsPressAfterTheLastFingerLifts() {
|
||||
twoFingerTap()
|
||||
assertEquals(listOf("button 273 true"), buttons())
|
||||
advance(49)
|
||||
advance(TouchTiming.CLICK_MS - 1)
|
||||
assertEquals(1, rightClicks.size)
|
||||
advance(1)
|
||||
assertEquals(listOf(true, false), rightClicks.map { it.down })
|
||||
assertEquals(50L, rightClicks[1].time - rightClicks[0].time)
|
||||
assertEquals(TouchTiming.CLICK_MS, rightClicks[1].time - rightClicks[0].time)
|
||||
}
|
||||
|
||||
@Test fun threeFingerKeyboardTapHasAnObservablePressAndReleases() {
|
||||
@@ -298,14 +298,14 @@ class TouchscreenGesturesTest {
|
||||
assertEquals(listOf("key 18 true"), events.filter { it.startsWith("key") })
|
||||
advance(50)
|
||||
assertEquals(listOf("key 18 true", "key 18 false"), events.filter { it.startsWith("key") })
|
||||
assertEquals(50L, timedKeys.last().first - timedKeys.first().first)
|
||||
assertEquals(TouchTiming.CLICK_MS, timedKeys.last().first - timedKeys.first().first)
|
||||
}
|
||||
|
||||
@Test fun twoFingerKeyboardTapHasAnObservablePressAndReleases() {
|
||||
gestures.configure(TouchGestureConfig(twoFingerTapAction = "key_E"))
|
||||
twoFingerTap(); advance(50)
|
||||
assertEquals(listOf(true, false), timedKeys.map { it.third })
|
||||
assertEquals(50L, timedKeys.last().first - timedKeys.first().first)
|
||||
assertEquals(TouchTiming.CLICK_MS, timedKeys.last().first - timedKeys.first().first)
|
||||
}
|
||||
|
||||
@Test fun threeFingerMouseTapHasAnObservablePressAndReleases() {
|
||||
@@ -314,7 +314,7 @@ class TouchscreenGesturesTest {
|
||||
assertEquals(listOf("button 273 true"), buttons())
|
||||
advance(50)
|
||||
assertEquals(listOf(true, false), rightClicks.map { it.down })
|
||||
assertEquals(50L, rightClicks[1].time - rightClicks[0].time)
|
||||
assertEquals(TouchTiming.CLICK_MS, rightClicks[1].time - rightClicks[0].time)
|
||||
}
|
||||
|
||||
@Test fun cancellingAMultiFingerTapReleasesItsButtonAndStopsCallbacks() {
|
||||
@@ -338,7 +338,7 @@ class TouchscreenGesturesTest {
|
||||
gestures.configure(TouchGestureConfig(tapAction = "right_click", doubleTapEnabled = false))
|
||||
tap(); tap(); advance(250)
|
||||
assertEquals(listOf(true, false, true, false), rightClicks.map { it.down })
|
||||
assertTrue(rightClicks[2].time - rightClicks[1].time >= 50)
|
||||
assertTrue(rightClicks[2].time - rightClicks[1].time >= TouchTiming.CLICK_MS)
|
||||
}
|
||||
|
||||
@Test fun aFastTwoFingerSwipeDuringSettlingDoesNotClick() {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Looper
|
||||
import android.view.MotionEvent
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import java.time.Duration
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class TwoFingerGesturesTest {
|
||||
private val calls = mutableListOf<String>()
|
||||
private val gestures = TwoFingerGestures(8f, object : TwoFingerGestures.Listener {
|
||||
override fun cancelTouch() { calls += "cancel" }
|
||||
override fun replay(event: MotionEvent) { calls += "replay ${event.actionMasked}" }
|
||||
override fun rightClick(x: Float, y: Float) { calls += "right $x,$y" }
|
||||
override fun scrollStart(x: Float, y: Float) { calls += "start $x,$y" }
|
||||
override fun scroll(dx: Float, dy: Float) { calls += "scroll $dx,$dy" }
|
||||
override fun scrollEnd() { calls += "end" }
|
||||
})
|
||||
private var time = 1000L
|
||||
private var downTime = 0L
|
||||
private val a = 1 to (400f to 300f)
|
||||
private val b = 2 to (500f to 300f)
|
||||
|
||||
@Test fun tapRightClicksWhereTheFirstFingerLanded() {
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 0, a))
|
||||
time += 20
|
||||
assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b))
|
||||
time += 80
|
||||
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 1, a, b))
|
||||
assertTrue(touch(MotionEvent.ACTION_UP, 0, a))
|
||||
assertEquals(listOf("cancel", "right 400.0,300.0"), calls)
|
||||
}
|
||||
|
||||
@Test fun holdRightClicksOnce() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, a)
|
||||
time += 20
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(TwoFingerGestures.HOLD_MS + 10))
|
||||
time += 600
|
||||
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 1, a, b))
|
||||
assertTrue(touch(MotionEvent.ACTION_UP, 0, a))
|
||||
assertEquals(listOf("cancel", "right 400.0,300.0"), calls)
|
||||
}
|
||||
|
||||
@Test fun slidingTogetherScrollsLikeAWheel() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, a)
|
||||
time += 20
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
|
||||
time += 20
|
||||
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 260f), 2 to (500f to 260f)))
|
||||
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 200f), 2 to (500f to 200f)))
|
||||
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 200f), 2 to (500f to 200f)))
|
||||
assertTrue(touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 200f)))
|
||||
assertEquals(listOf("cancel", "start 450.0,260.0", "scroll 0.0,60.0", "end"), calls)
|
||||
}
|
||||
|
||||
@Test fun pinchPassesThroughForZoom() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, a)
|
||||
time += 20
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
|
||||
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (350f to 300f), 2 to (550f to 300f)))
|
||||
assertEquals(listOf("replay 0", "replay 5", "replay 2"), calls)
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(TwoFingerGestures.HOLD_MS + 10))
|
||||
assertFalse(touch(MotionEvent.ACTION_MOVE, 0, 1 to (340f to 300f), 2 to (560f to 300f)))
|
||||
assertFalse(touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (340f to 300f), 2 to (560f to 300f)))
|
||||
assertFalse(touch(MotionEvent.ACTION_UP, 0, 1 to (340f to 300f)))
|
||||
assertEquals(3, calls.size)
|
||||
}
|
||||
|
||||
@Test fun oneFingerTapIsReplayedOnRelease() {
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 0, a))
|
||||
assertTrue(calls.isEmpty())
|
||||
time += 60
|
||||
assertTrue(touch(MotionEvent.ACTION_UP, 0, a))
|
||||
assertEquals(listOf("replay 0", "replay 1"), calls)
|
||||
}
|
||||
|
||||
@Test fun oneFingerStillIsReplayedAfterTheLandingWindow() {
|
||||
assertTrue(touch(MotionEvent.ACTION_DOWN, 0, a))
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(TwoFingerGestures.LAND_MS + 10))
|
||||
assertEquals(listOf("replay 0"), calls)
|
||||
time += 600
|
||||
assertFalse(touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b))
|
||||
assertFalse(touch(MotionEvent.ACTION_POINTER_UP, 1, a, b))
|
||||
assertFalse(touch(MotionEvent.ACTION_UP, 0, a))
|
||||
assertEquals(listOf("replay 0"), calls)
|
||||
}
|
||||
|
||||
@Test fun oneFingerDragIsReplayedOnceItMoves() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, a)
|
||||
time += 16
|
||||
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (402f to 300f)))
|
||||
assertTrue(calls.isEmpty())
|
||||
time += 16
|
||||
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (440f to 300f)))
|
||||
assertEquals(listOf("replay 0", "replay 2", "replay 2"), calls)
|
||||
assertFalse(touch(MotionEvent.ACTION_MOVE, 0, 1 to (480f to 300f)))
|
||||
assertFalse(touch(MotionEvent.ACTION_UP, 0, 1 to (480f to 300f)))
|
||||
}
|
||||
|
||||
private fun touch(action: Int, index: Int, vararg pointers: Pair<Int, Pair<Float, Float>>): Boolean {
|
||||
if (action == MotionEvent.ACTION_DOWN) downTime = time
|
||||
val properties = pointers.map { (id, _) ->
|
||||
MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER }
|
||||
}.toTypedArray()
|
||||
val coords = pointers.map { (_, at) ->
|
||||
MotionEvent.PointerCoords().apply { x = at.first; y = at.second; pressure = 1f; size = 1f }
|
||||
}.toTypedArray()
|
||||
val masked = action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
val event = MotionEvent.obtain(downTime, time, masked, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
|
||||
return gestures.onTouch(event).also { event.recycle() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class AccountsMergeTest {
|
||||
private val own = "root:x:10123:10123:root:/root:/bin/bash"
|
||||
private val zero = "root:x:0:0:root:/root:/bin/bash"
|
||||
|
||||
@Test fun systemUsersSurvive() {
|
||||
val existing = "root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n_apt:x:42:65534::/nonexistent:/usr/sbin/nologin\nmessagebus:x:100:102::/nonexistent:/usr/sbin/nologin\n"
|
||||
assertEquals("$own\n$zero\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n_apt:x:42:65534::/nonexistent:/usr/sbin/nologin\nmessagebus:x:100:102::/nonexistent:/usr/sbin/nologin\n",
|
||||
LinuxRuntime.mergedAccounts(existing, 2, own, zero, 10123))
|
||||
}
|
||||
|
||||
@Test fun anOldSingleLineFileIsReplacedOnce() {
|
||||
val merged = LinuxRuntime.mergedAccounts("$own\n", 2, own, zero, 10123)
|
||||
assertEquals("$own\n$zero\n", merged)
|
||||
assertEquals(merged, LinuxRuntime.mergedAccounts(merged, 2, own, zero, 10123))
|
||||
}
|
||||
|
||||
@Test fun anotherAppUidIsDropped() {
|
||||
assertEquals("$own\n$zero\n", LinuxRuntime.mergedAccounts("root:x:10099:10099:root:/root:/bin/bash\n", 2, own, zero, 10123))
|
||||
}
|
||||
|
||||
@Test fun noFileYet() {
|
||||
assertEquals("$own\n$zero\n", LinuxRuntime.mergedAccounts(null, 2, own, zero, 10123))
|
||||
}
|
||||
|
||||
@Test fun groupsKeepMembers() {
|
||||
val existing = "root:x:0:\nsudo:x:27:\naudio:x:29:pulse\n"
|
||||
assertEquals("root:x:10123:\nroot:x:0:\nsudo:x:27:\naudio:x:29:pulse\n",
|
||||
LinuxRuntime.mergedAccounts(existing, 2, "root:x:10123:", "root:x:0:", 10123))
|
||||
}
|
||||
|
||||
@Test fun storageGroupsAreAddedWithRoot() {
|
||||
assertEquals("root:x:0:\nsudo:x:27:\nsdcard_rw:x:1015:root\nmedia_rw:x:1023:root\neverybody:x:9997:root\n",
|
||||
LinuxRuntime.withStorageGroups("root:x:0:\nsudo:x:27:\n"))
|
||||
}
|
||||
|
||||
@Test fun existingStorageGroupsGainRootOnce() {
|
||||
val existing = "root:x:0:\nmedia_rw:x:1023:pulse\nsdcard_rw:x:1015:root\nshared:x:9997:\n"
|
||||
val updated = LinuxRuntime.withStorageGroups(existing)
|
||||
assertEquals("root:x:0:\nmedia_rw:x:1023:pulse,root\nsdcard_rw:x:1015:root\nshared:x:9997:root\n", updated)
|
||||
assertEquals(updated, LinuxRuntime.withStorageGroups(updated))
|
||||
}
|
||||
}
|
||||
@@ -160,4 +160,25 @@ class BwrapSpawnerPlanTest {
|
||||
assertFalse(plan.binds.any { it.guest.startsWith("/app/bin/") })
|
||||
assertFalse(File(dir, "zypak-wrapper").exists())
|
||||
}
|
||||
|
||||
@Test fun preloadsStayOutOfSandboxesWithAnOlderGlibc() {
|
||||
val base = Files.createTempDirectory("glibc").toFile()
|
||||
try {
|
||||
val rootfs = File(base, "rootfs")
|
||||
File(rootfs, "usr/local/lib").mkdirs()
|
||||
File(rootfs, "etc").mkdirs()
|
||||
File(rootfs, "etc/ld.so.preload").writeText("/usr/local/lib/libone.so\n/usr/local/lib/libtwo.so\n")
|
||||
File(rootfs, "usr/local/lib/libone.so").writeText("x GLIBC_2.17 y GLIBC_2.34 z")
|
||||
File(rootfs, "usr/local/lib/libtwo.so").writeText("GLIBC_2.38 GLIBC_2.25")
|
||||
val old = File(base, "old-libc").apply { writeText("GNU C Library (Ubuntu GLIBC 2.23-0ubuntu11) stable release version 2.23, by Roland") }
|
||||
val new = File(base, "new-libc").apply { writeText("GNU C Library (Ubuntu GLIBC 2.43-0ubuntu1) stable release version 2.43.") }
|
||||
val same = File(base, "same-libc").apply { writeText("stable release version 2.38.") }
|
||||
assertFalse(BwrapSpawner.preloadFits(rootfs.path, old.path))
|
||||
assertTrue(BwrapSpawner.preloadFits(rootfs.path, new.path))
|
||||
assertTrue(BwrapSpawner.preloadFits(rootfs.path, same.path))
|
||||
assertTrue(BwrapSpawner.preloadFits(rootfs.path, File(base, "missing").path))
|
||||
} finally {
|
||||
base.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,4 +76,22 @@ class DesktopFileRemovalTest {
|
||||
file("var/lib/pacman/local/base-1/files", "%FILES%\nusr/\nusr/bin/\nusr/bin/gamescope\n\n%BACKUP%\netc/config\n")
|
||||
assertEquals(setOf("usr/bin/gamescope"), DesktopFileRemoval.runtimeFiles(root))
|
||||
}
|
||||
|
||||
@Test fun desktopPackageRecordsAreNotRuntimeFilesAndAreRemovedWithTheDesktop() {
|
||||
file("var/lib/pacman/local/base-1/files", "%FILES%\nusr/bin/gamescope\n")
|
||||
file("var/lib/pacman/local/kate-26.04.3-1/files", "%FILES%\nusr/bin/kate\n")
|
||||
file("var/lib/pacman/local/kate-26.04.3-1/desc", "%NAME%\nkate\n")
|
||||
file("var/lib/pacman/local/htop-3.5.3-1/files", "%FILES%\nusr/bin/htop\n")
|
||||
file("var/lib/pacman/sync/droiddeck.db", "db")
|
||||
file("var/lib/pacman/droiddeck-desktop", "stamp")
|
||||
file("usr/share/droiddeck/pacman/desktop-packages.txt", "kate 26.04.3-1\n../../etc 1\n")
|
||||
val records = DesktopFileRemoval.desktopRecords(root)
|
||||
assertEquals(setOf("kate-26.04.3-1"), records)
|
||||
assertEquals(setOf("usr/bin/gamescope", "usr/bin/htop"), DesktopFileRemoval.runtimeFiles(root))
|
||||
DesktopFileRemoval.removeRecords(root, records)
|
||||
assertFalse(File(root, "var/lib/pacman/local/kate-26.04.3-1").exists())
|
||||
assertTrue(File(root, "var/lib/pacman/local/htop-3.5.3-1/files").exists())
|
||||
assertFalse(File(root, "var/lib/pacman/sync/droiddeck.db").exists())
|
||||
assertFalse(File(root, "var/lib/pacman/droiddeck-desktop").exists())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.util.zip.GZIPOutputStream
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class DesktopPackTest {
|
||||
private val parent = Files.createTempDirectory("pack").toFile()
|
||||
private val root = File(parent, "root").apply { mkdirs() }
|
||||
|
||||
@After fun tearDown() { FileUtils.delete(parent) }
|
||||
|
||||
private fun file(path: String, text: String) = File(root, path).apply { parentFile?.mkdirs(); writeText(text) }
|
||||
|
||||
private fun line(kind: Char, path: String): String {
|
||||
val file = File(root, path)
|
||||
return when {
|
||||
Files.isSymbolicLink(file.toPath()) -> "$kind\tL\t0\t${Files.readSymbolicLink(file.toPath())}\t$path"
|
||||
file.isDirectory -> "$kind\tD\t0\t-\t$path"
|
||||
else -> "$kind\tF\t${file.length()}\t${Hashes.sha256(file)}\t$path"
|
||||
}
|
||||
}
|
||||
|
||||
private fun manifest(lines: List<String>) {
|
||||
val target = File(root, "${DesktopPack.META}/files.tsv.gz").apply { parentFile?.mkdirs() }
|
||||
GZIPOutputStream(target.outputStream()).bufferedWriter().use { w -> lines.forEach { w.write(it); w.write("\n") } }
|
||||
}
|
||||
|
||||
private fun installed(): List<String> {
|
||||
File(root, DesktopPack.INFO).apply { parentFile?.mkdirs() }
|
||||
.writeText("""{"tag":"ubuntu-r1-desktop","url":"https://example.invalid/d.tar.zst","sha256":"00","size":5}""")
|
||||
file("usr/bin/runtime-tool", "runtime")
|
||||
file("${DesktopPack.META}/originals/var/lib/dpkg/status", "Package: bash\n")
|
||||
file("${DesktopPack.META}/originals/etc/gone.conf", "removed by the desktop")
|
||||
file("${DesktopPack.META}/originals/etc/group", "root:x:0:")
|
||||
file("${DesktopPack.META}/originals/etc/hosts", "runtime hosts")
|
||||
file("etc/group", "root:x:0:\nsddm:x:120:")
|
||||
file("etc/hosts", "desktop hosts")
|
||||
file("var/lib/dpkg/status", "Package: bash\n\nPackage: kwin\n")
|
||||
file("usr/bin/kwin_wayland", "kwin")
|
||||
file("usr/share/kwin/effect.qml", "effect")
|
||||
file("usr/share/kwin/edited.qml", "original")
|
||||
Files.createSymbolicLink(File(root, "usr/bin/kwin").toPath(), File("kwin_wayland").toPath())
|
||||
val lines = listOf(
|
||||
line('N', "usr/share/kwin"), line('N', "usr/bin/kwin_wayland"), line('N', "usr/share/kwin/effect.qml"),
|
||||
line('N', "usr/share/kwin/edited.qml"), line('N', "usr/bin/kwin"), line('C', "var/lib/dpkg/status"), line('C', "etc/group"), line('C', "etc/hosts"),
|
||||
"R\tF\t22\tx\tetc/gone.conf", "N\tF\t1\tx\t../escape",
|
||||
)
|
||||
file("usr/share/kwin/edited.qml", "changed by the user")
|
||||
file("etc/hosts", "edited by the user")
|
||||
file("var/lib/dpkg/status", "Package: bash\n\nPackage: kwin\n\nPackage: vlc\n")
|
||||
return lines
|
||||
}
|
||||
|
||||
@Test fun readsThePackTheRuntimeNames() {
|
||||
installed()
|
||||
val info = DesktopPack.info(root)!!
|
||||
assertEquals("ubuntu-r1-desktop", info.tag)
|
||||
assertEquals(5L, info.size)
|
||||
}
|
||||
|
||||
@Test fun removingPutsTheRuntimeBackAndKeepsWhatTheUserChanged() {
|
||||
manifest(installed())
|
||||
val result = DesktopPack.remove(root)
|
||||
assertEquals("Package: bash\n", File(root, "var/lib/dpkg/status").readText())
|
||||
assertEquals("removed by the desktop", File(root, "etc/gone.conf").readText())
|
||||
assertEquals("root:x:0:", File(root, "etc/group").readText())
|
||||
assertEquals("edited by the user", File(root, "etc/hosts").readText())
|
||||
assertFalse(File(root, "usr/bin/kwin_wayland").exists())
|
||||
assertFalse(Files.exists(File(root, "usr/bin/kwin").toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS))
|
||||
assertFalse(File(root, "usr/share/kwin/effect.qml").exists())
|
||||
assertEquals("changed by the user", File(root, "usr/share/kwin/edited.qml").readText())
|
||||
assertTrue(File(root, "usr/share/kwin").isDirectory)
|
||||
assertEquals("runtime", File(root, "usr/bin/runtime-tool").readText())
|
||||
assertFalse(File(root, DesktopPack.META).exists())
|
||||
assertFalse(DesktopPack.installed(root))
|
||||
assertEquals(3, result.removed)
|
||||
assertEquals(3, result.restored)
|
||||
assertEquals(3, result.kept)
|
||||
}
|
||||
|
||||
@Test fun emptiedDirectoriesGoAway() {
|
||||
val lines = installed()
|
||||
File(root, "usr/share/kwin/edited.qml").delete()
|
||||
manifest(lines)
|
||||
DesktopPack.remove(root)
|
||||
assertFalse(File(root, "usr/share/kwin").exists())
|
||||
assertTrue(File(root, "usr/share").isDirectory)
|
||||
}
|
||||
|
||||
@Test fun finishingAnInstallDeletesWhatTheDesktopRemoved() {
|
||||
file("etc/gone.conf", "runtime copy")
|
||||
manifest(listOf("R\tF\t22\tx\tetc/gone.conf", "R\tF\t1\tx\t../outside"))
|
||||
File(root.parentFile, "outside").writeText("keep")
|
||||
DesktopPack.finishInstall(root)
|
||||
assertFalse(File(root, "etc/gone.conf").exists())
|
||||
assertTrue(File(root.parentFile, "outside").exists())
|
||||
File(root.parentFile, "outside").delete()
|
||||
}
|
||||
|
||||
@Test fun theDesktopKeepsPackagesTheUserInstalledBeforeIt() {
|
||||
val bash = "Package: bash\nArchitecture: arm64\nVersion: 5.2"
|
||||
val vim = "Package: vim\nArchitecture: arm64\nVersion: 9"
|
||||
val kwin = "Package: kwin\nArchitecture: arm64\nVersion: 6.6"
|
||||
file("var/lib/dpkg/status", "$bash\n\n$vim\n\n")
|
||||
DesktopPack.prepareInstall(root)
|
||||
file("${DesktopPack.META}/originals/var/lib/dpkg/status", "$bash\n\n")
|
||||
file("var/lib/dpkg/status", "$bash\n\n$kwin\n\n")
|
||||
manifest(listOf(line('C', "var/lib/dpkg/status")))
|
||||
DesktopPack.finishInstall(root)
|
||||
assertEquals("$bash\n\n$kwin\n\n$vim\n\n", File(root, "var/lib/dpkg/status").readText())
|
||||
assertFalse(File(root, "var/lib/dpkg/status.droiddeck").exists())
|
||||
|
||||
val vlc = "Package: vlc\nArchitecture: arm64\nVersion: 3"
|
||||
file("var/lib/dpkg/status", "$bash\n\n$kwin\n\n$vim\n\n$vlc\n\n")
|
||||
DesktopPack.remove(root)
|
||||
assertEquals("$bash\n\n$vim\n\n$vlc\n\n", File(root, "var/lib/dpkg/status").readText())
|
||||
}
|
||||
|
||||
@Test fun mergingKeepsTheTargetWhenBothSidesChangedAPackage() {
|
||||
val base = "Package: a\nVersion: 1\n\nPackage: b\nVersion: 1\n\nPackage: c\nVersion: 1\n"
|
||||
val target = "Package: a\nVersion: 2\n\nPackage: b\nVersion: 1\n\nPackage: c\nVersion: 1\n"
|
||||
val mine = "Package: a\nVersion: 3\n\nPackage: b\nVersion: 3\n"
|
||||
assertEquals("Package: a\nVersion: 2\n\nPackage: b\nVersion: 3\n\n", DesktopPack.mergeStatus(base, target, mine))
|
||||
}
|
||||
|
||||
@Test fun pathsMayNotLeaveTheRuntime() {
|
||||
assertNull(DesktopPack.inside(root, "../x"))
|
||||
assertNull(DesktopPack.inside(root, "/etc/passwd"))
|
||||
Files.createSymbolicLink(File(root, "link").toPath(), root.parentFile.toPath())
|
||||
assertNull(DesktopPack.inside(root, "link/x"))
|
||||
assertEquals(File(root, "usr/x"), DesktopPack.inside(root, "usr/./x"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class L2sLinkTest {
|
||||
private val dir = Files.createTempDirectory("l2s").toFile()
|
||||
|
||||
@After fun tearDown() { FileUtils.delete(dir) }
|
||||
|
||||
@Test fun aHardLinkBecomesProotsLinkLayout() {
|
||||
val bin = File(dir, "usr/bin").apply { mkdirs() }
|
||||
val coreutils = File(bin, "coreutils").apply { writeText("multicall") }
|
||||
val tail = File(bin, "tail")
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, tail))
|
||||
val intermediate = File(bin, ".l2s.coreutils0001")
|
||||
assertEquals(intermediate.toPath(), Files.readSymbolicLink(coreutils.toPath()))
|
||||
assertEquals(intermediate.toPath(), Files.readSymbolicLink(tail.toPath()))
|
||||
assertEquals(File(bin, ".l2s.coreutils0001.0002").toPath(), Files.readSymbolicLink(intermediate.toPath()))
|
||||
assertEquals("multicall", tail.readText())
|
||||
assertEquals("multicall", coreutils.readText())
|
||||
}
|
||||
|
||||
@Test fun eachFurtherLinkRaisesTheCount() {
|
||||
val bin = File(dir, "usr/bin").apply { mkdirs() }
|
||||
val coreutils = File(bin, "coreutils").apply { writeText("multicall") }
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, File(bin, "tail")))
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, File(bin, "head")))
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(File(bin, "tail"), File(bin, "cat")))
|
||||
val final = File(bin, ".l2s.coreutils0001.0004")
|
||||
assertTrue(final.isFile)
|
||||
assertFalse(File(bin, ".l2s.coreutils0001.0002").exists())
|
||||
for (name in listOf("coreutils", "tail", "head", "cat")) assertEquals("multicall", File(bin, name).readText())
|
||||
}
|
||||
|
||||
@Test fun aSecondFileWithTheSameNameGetsItsOwnChain() {
|
||||
val a = File(dir, "a").apply { mkdirs() }
|
||||
val existing = File(a, ".l2s.tool0001").apply { writeText("taken") }
|
||||
val tool = File(a, "tool").apply { writeText("tool") }
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(tool, File(a, "alias")))
|
||||
assertEquals("taken", existing.readText())
|
||||
assertEquals(File(a, ".l2s.tool0002").toPath(), Files.readSymbolicLink(tool.toPath()))
|
||||
assertEquals("tool", File(a, "alias").readText())
|
||||
}
|
||||
|
||||
@Test fun linksMadeInStagingStillResolveAfterTheTreeIsRenamed() {
|
||||
val staging = File(dir, "linuxfs.new")
|
||||
val live = File(dir, "linuxfs")
|
||||
val bin = File(staging, "usr/bin").apply { mkdirs() }
|
||||
val cargo = File(staging, "usr/lib/cargo/bin/coreutils").apply { mkdirs() }
|
||||
val coreutils = File(bin, "coreutils").apply { writeText("multicall") }
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(coreutils, File(cargo, "echo"), staging, live))
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(File(cargo, "echo"), File(cargo, "cat"), staging, live))
|
||||
assertEquals(File(live, "usr/bin/.l2s.coreutils0001").toPath(), Files.readSymbolicLink(File(cargo, "echo").toPath()))
|
||||
assertTrue(File(staging, "usr/bin/.l2s.coreutils0001.0003").isFile)
|
||||
|
||||
assertTrue(staging.renameTo(live))
|
||||
|
||||
for (rel in listOf("usr/bin/coreutils", "usr/lib/cargo/bin/coreutils/echo", "usr/lib/cargo/bin/coreutils/cat"))
|
||||
assertEquals(rel, "multicall", File(live, rel).readText())
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(File(live, "usr/bin/coreutils"), File(live, "usr/bin/tail")))
|
||||
assertEquals("multicall", File(live, "usr/bin/tail").readText())
|
||||
assertTrue(File(live, "usr/bin/.l2s.coreutils0001.0004").isFile)
|
||||
}
|
||||
|
||||
@Test fun aHardLinkTargetMayAlreadyBeAnL2sLinkToTheFinalTree() {
|
||||
val staging = File(dir, "linuxfs.new")
|
||||
val live = File(dir, "linuxfs")
|
||||
val bin = File(staging, "usr/bin").apply { mkdirs() }
|
||||
File(bin, "coreutils").writeText("multicall")
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(File(bin, "coreutils"), File(bin, "["), staging, live))
|
||||
assertEquals(File(bin, "coreutils"), LinuxRuntimeInstaller.hardLinkTarget(staging, "./usr/bin/coreutils"))
|
||||
assertTrue(LinuxRuntimeInstaller.l2sLink(LinuxRuntimeInstaller.hardLinkTarget(staging, "./usr/bin/coreutils"), File(bin, "ls"), staging, live))
|
||||
assertTrue(staging.renameTo(live))
|
||||
assertEquals("multicall", File(live, "usr/bin/ls").readText())
|
||||
}
|
||||
|
||||
@Test fun aHardLinkTargetCannotLeaveTheTree() {
|
||||
val tree = File(dir, "tree").apply { mkdirs() }
|
||||
val outside = File(dir, "outside").apply { mkdirs() }
|
||||
Files.createSymbolicLink(File(tree, "escape").toPath(), outside.toPath())
|
||||
assertEquals(null, LinuxRuntimeInstaller.hardLinkTarget(tree, "../outside/x"))
|
||||
assertEquals(null, LinuxRuntimeInstaller.hardLinkTarget(tree, "escape/x"))
|
||||
assertEquals(null, LinuxRuntimeInstaller.hardLinkTarget(tree, ".."))
|
||||
assertEquals(File(tree, "x"), LinuxRuntimeInstaller.hardLinkTarget(tree, "./x"))
|
||||
}
|
||||
|
||||
@Test fun directoriesAndPlainSymlinksAreLeftAlone() {
|
||||
val d = File(dir, "d").apply { mkdirs() }
|
||||
assertFalse(LinuxRuntimeInstaller.l2sLink(d, File(dir, "e")))
|
||||
val target = File(dir, "t").apply { writeText("t") }
|
||||
val link = File(dir, "link")
|
||||
Files.createSymbolicLink(link.toPath(), target.toPath())
|
||||
assertFalse(LinuxRuntimeInstaller.l2sLink(link, File(dir, "other")))
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,12 @@ import java.io.File
|
||||
class ProotFastPathTest {
|
||||
private val root = File("/data/data/com.droiddeck.launcher/files/linuxfs")
|
||||
|
||||
@Test fun guestEnvironmentCarriesTheHostAndroidApi() {
|
||||
for (sdk in listOf(33, 35, 36)) {
|
||||
assertTrue(ProotFastPath.guestEnv(root, emptyList(), "test", sdk).contains("PROOT_FP_ANDROID_API=$sdk"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aSessionsUsualBindsGetAKey() {
|
||||
val binds = (1..87).map { "/host/$it:/guest/$it" }
|
||||
assertNotNull(ProotFastPath.key(root, binds))
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.app.Application
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
|
||||
class RuntimeAutoUpdateTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Test fun anInstalledRuntimeBehindTheCatalogUpdatesByItself() {
|
||||
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2"))
|
||||
}
|
||||
|
||||
@Test fun noRuntimeOrTheSameOneIsLeftAlone() {
|
||||
assertFalse(RuntimeAutoUpdate.claim(context, null, "ubuntu-r1-rc2"))
|
||||
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc2", "ubuntu-r1-rc2"))
|
||||
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", null))
|
||||
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", ""))
|
||||
}
|
||||
|
||||
@Test fun aFailingUpdateStopsTryingAfterAFewLaunches() {
|
||||
repeat(RuntimeAutoUpdate.MAX_ATTEMPTS) { assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", it * RuntimeAutoUpdate.RETRY_MS)) }
|
||||
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 10 * RuntimeAutoUpdate.RETRY_MS))
|
||||
}
|
||||
|
||||
@Test fun aRetryWaitsBeforeUsingTheNextTry() {
|
||||
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 1_000L))
|
||||
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 2_000L))
|
||||
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 1_000L + RuntimeAutoUpdate.RETRY_MS))
|
||||
}
|
||||
|
||||
@Test fun aNewerCatalogReleaseStartsAgain() {
|
||||
repeat(RuntimeAutoUpdate.MAX_ATTEMPTS) { RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", it * RuntimeAutoUpdate.RETRY_MS) }
|
||||
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc3", 5 * RuntimeAutoUpdate.RETRY_MS))
|
||||
}
|
||||
|
||||
@Test fun goingBackToAnEarlierReleaseKeepsItsCount() {
|
||||
repeat(RuntimeAutoUpdate.MAX_ATTEMPTS) { RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", it * RuntimeAutoUpdate.RETRY_MS) }
|
||||
assertTrue(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc3", 5 * RuntimeAutoUpdate.RETRY_MS))
|
||||
assertFalse(RuntimeAutoUpdate.claim(context, "ubuntu-r1-rc1", "ubuntu-r1-rc2", 10 * RuntimeAutoUpdate.RETRY_MS))
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ class RuntimeUserDataCarryTest {
|
||||
put(old, "root/save.dat", "mine")
|
||||
put(old, "opt/appimages/user/app1/app.AppImage")
|
||||
put(old, "opt/droiddeck-apps/game/run.sh")
|
||||
put(old, "opt/droiddeck/wincomponents/d3dx9/component.json")
|
||||
put(old, "usr/local/share/applications/droiddeck-app-game.desktop")
|
||||
put(old, "usr/local/share/applications/droiddeck-appimage-app1.desktop")
|
||||
put(old, "usr/local/share/applications/other.desktop")
|
||||
@@ -43,6 +44,7 @@ class RuntimeUserDataCarryTest {
|
||||
assertEquals("mine", File(staging, "root/save.dat").readText())
|
||||
assertFalse("the shipped home is replaced, not merged", File(staging, "root/.bashrc").exists())
|
||||
for (rel in listOf("opt/appimages/user/app1/app.AppImage", "opt/droiddeck-apps/game/run.sh",
|
||||
"opt/droiddeck/wincomponents/d3dx9/component.json",
|
||||
"usr/local/share/applications/droiddeck-app-game.desktop", "usr/local/share/applications/droiddeck-appimage-app1.desktop",
|
||||
"opt/appimages/dolphin.AppImage", "usr/share/applications/droiddeck-dolphin.desktop", ".droiddeck-pkg-dolphin")) {
|
||||
assertTrue(rel, File(staging, rel).exists())
|
||||
@@ -52,6 +54,47 @@ class RuntimeUserDataCarryTest {
|
||||
assertFalse("only DroidDeck's own menu entries are user data", File(staging, "usr/local/share/applications/other.desktop").exists())
|
||||
}
|
||||
|
||||
@Test fun aMenuEntryTheNewRuntimeShipsIsNotCarried() {
|
||||
val old = tmp.newFolder("old").also {
|
||||
put(it, "root/save.dat", "mine")
|
||||
put(it, "usr/share/applications/droiddeck-return-gaming.desktop", "old runtime")
|
||||
put(it, "usr/share/applications/droiddeck-steam-x64.desktop", "made by the old desktop")
|
||||
}
|
||||
val staging = tmp.newFolder("new").also {
|
||||
put(it, "root/.bashrc", "shipped")
|
||||
put(it, "usr/share/applications/droiddeck-return-gaming.desktop", "new runtime")
|
||||
}
|
||||
|
||||
val paths = RuntimeFileTree.existingUserPaths(old, staging)
|
||||
|
||||
assertTrue("root" in paths)
|
||||
assertTrue("usr/share/applications/droiddeck-steam-x64.desktop" in paths)
|
||||
assertFalse("usr/share/applications/droiddeck-return-gaming.desktop" in paths)
|
||||
RuntimeFileTree.carryUserData(old, staging, false, paths)
|
||||
assertEquals("new runtime", File(staging, "usr/share/applications/droiddeck-return-gaming.desktop").readText())
|
||||
}
|
||||
|
||||
@Test fun cachesTiedToThePreviousRuntimeAreDropped() {
|
||||
val root = tmp.newFolder("rt")
|
||||
val keep = listOf("root/.cache/mozilla/cache2/entry", "root/.cache/droiddeck/session.log",
|
||||
"root/.local/share/droiddeck/apt/packages.txt", "root/.local/share/Steam/steam.sh", "root/.config/kwinrc")
|
||||
val drop = listOf("root/.local/share/droiddeck/pacman/packages.txt", "root/.cache/droiddeck/pacman-restore.log",
|
||||
"root/.cache/mesa_shader_cache_db/index", "root/.cache/mesa_shader_cache/a/b", "root/.cache/appstream/x.xb",
|
||||
"root/.cache/discover/c", "root/.cache/ksycoca6_en-POSIX_abc", "root/.cache/plasma_theme_Vapor.kcache",
|
||||
"root/.cache/kwinsession.kcache", "root/.cache/qtshadercache-arm64-little_endian-lp64/s",
|
||||
"root/.cache/event-sound-cache.tdb.1.aarch64-unknown-linux-gnu", "root/.cache/fontconfig/x.cache-9")
|
||||
(keep + drop).forEach { put(root, it) }
|
||||
|
||||
RuntimeFileTree.dropStaleState(root)
|
||||
|
||||
keep.forEach { assertTrue(it, File(root, it).exists()) }
|
||||
drop.forEach { assertFalse(it, File(root, it).exists()) }
|
||||
}
|
||||
|
||||
@Test fun droppingStateWithoutAHomeDoesNothing() {
|
||||
RuntimeFileTree.dropStaleState(tmp.newFolder("empty"))
|
||||
}
|
||||
|
||||
@Test fun aFailureHalfwayPutsEverythingBack() {
|
||||
val old = userTree()
|
||||
val staging = tmp.newFolder("new")
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class HudDefaultTest {
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
context = ApplicationProvider.getApplicationContext()
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
|
||||
@Test fun aNewInstallStartsWithTheHudOff() {
|
||||
assertFalse(SessionPrefs.hudEnabled(context))
|
||||
}
|
||||
|
||||
@Test fun aHudTheUserTurnedOnStaysOn() {
|
||||
SessionPrefs.setHudEnabled(context, true)
|
||||
assertTrue(SessionPrefs.hudEnabled(context))
|
||||
}
|
||||
|
||||
@Test fun aHudTheUserTurnedOffStaysOff() {
|
||||
SessionPrefs.setHudEnabled(context, false)
|
||||
assertFalse(SessionPrefs.hudEnabled(context))
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,15 @@ class OutputPacingTest {
|
||||
assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0))
|
||||
}
|
||||
|
||||
@Test fun sessionLimitPacesThePhone() {
|
||||
assertEquals(45, SessionPrefs.compositorFpsLimit(0, 45))
|
||||
}
|
||||
|
||||
@Test fun sessionLimitNeverExceedsTheGlassesRate() {
|
||||
assertEquals(60, SessionPrefs.compositorFpsLimit(60, 90))
|
||||
assertEquals(30, SessionPrefs.compositorFpsLimit(60, 30))
|
||||
}
|
||||
|
||||
@Test fun mirroringKeepsTheGlassesRate() {
|
||||
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class PerfHudGraphTest {
|
||||
@Test fun theGraphShowsOnlyFramesFromThisHudRun() {
|
||||
val samples = floatArrayOf(9f, 9f, 9f, 9f, 9f, 16.7f, 33.4f, 16.6f)
|
||||
assertArrayEquals(floatArrayOf(16.7f, 33.4f, 16.6f), PerfHud.recent(samples, 105, 102), 0f)
|
||||
assertEquals(0, PerfHud.recent(samples, 103, 102).size)
|
||||
}
|
||||
|
||||
@Test fun anEarlySessionShowsWhatWasShownSoFar() {
|
||||
val samples = floatArrayOf(16.6f, 16.7f, 120f, 0f, 0f, 0f)
|
||||
assertArrayEquals(floatArrayOf(16.6f, 16.7f, 50f), PerfHud.recent(samples, 3, 0), 0f)
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,9 @@ class SessionBackgroundPrefsTest {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
|
||||
@Test fun nativeIsOptInAndDoesNotChangeDesktopOrExistingPolicies() {
|
||||
assertEquals(SessionPrefs.SUSPEND_MANUAL, SessionPrefs.suspendPolicy(context, "steam"))
|
||||
@Test fun nativeIsTheSteamDefaultWithoutChangingOtherModesOrSavedPolicies() {
|
||||
assertEquals(SessionPrefs.SUSPEND_NATIVE, SessionPrefs.suspendPolicy(context, "steam"))
|
||||
assertEquals(SessionPrefs.SUSPEND_MANUAL, SessionPrefs.suspendPolicy(context, SessionService.MODE_RUN))
|
||||
for (policy in listOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_MANUAL, SessionPrefs.SUSPEND_NEVER,
|
||||
SessionPrefs.SUSPEND_NATIVE)) {
|
||||
SessionPrefs.setSuspendPolicy(context, "steam", policy)
|
||||
@@ -28,6 +29,14 @@ class SessionBackgroundPrefsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun automaticPipDefaultsOnAndHonorsSavedChoices() {
|
||||
assertEquals(true, SessionPrefs.pipAutoEnter(context))
|
||||
SessionPrefs.setPipAutoEnter(context, false)
|
||||
assertEquals(false, SessionPrefs.pipAutoEnter(context))
|
||||
SessionPrefs.setPipAutoEnter(context, true)
|
||||
assertEquals(true, SessionPrefs.pipAutoEnter(context))
|
||||
}
|
||||
|
||||
@Test fun directGamesUseAutoWithoutOverwritingSteamsNativeChoice() {
|
||||
SessionPrefs.setSuspendPolicy(context, SessionService.MODE_STEAM, SessionPrefs.SUSPEND_NATIVE)
|
||||
assertEquals(SessionPrefs.SUSPEND_AUTO, SessionPrefs.suspendPolicy(context, SessionService.MODE_RUN))
|
||||
|
||||
@@ -46,6 +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)
|
||||
ControllerPrefs.setOpacity(app, 40)
|
||||
AppUiPrefs.setScale(app, 150)
|
||||
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3))
|
||||
@@ -70,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))
|
||||
assertEquals("32.4°C", PerfHud.batteryCelsius(324))
|
||||
assertNull(PerfHud.batteryCelsius(0))
|
||||
assertNull(SessionPrefs.fusionHudConfig(app))
|
||||
assertNull(SessionPrefs.fusionHudPosition(app))
|
||||
assertEquals(100, ControllerPrefs.read(app).opacity)
|
||||
assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app))
|
||||
assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app))
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Application
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
|
||||
class SteamImportPromptTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private fun ask(root: File, text: String) = File(root, "root/.cache/droiddeck").apply { mkdirs() }.resolve("steam-import.json").writeText(text)
|
||||
|
||||
@Test fun aRequestFromTheGuestIsRead() {
|
||||
val root = temp.newFolder()
|
||||
ask(root, """{"token":"7","games":["Absolum","","Hades"]}""")
|
||||
assertEquals(SteamImportPrompt.Ask("7", listOf("Absolum", "Hades")), SteamImportPrompt.read(root))
|
||||
}
|
||||
|
||||
@Test fun noRequestOrABrokenOneIsIgnored() {
|
||||
val root = temp.newFolder()
|
||||
assertNull(SteamImportPrompt.read(root))
|
||||
ask(root, "{")
|
||||
assertNull(SteamImportPrompt.read(root))
|
||||
ask(root, """{"games":["Hades"]}""")
|
||||
assertNull(SteamImportPrompt.read(root))
|
||||
}
|
||||
|
||||
@Test fun theAnswerCarriesTheTokenAndTheChoice() {
|
||||
val root = temp.newFolder()
|
||||
for ((now, choice) in listOf(true to "now", false to "later")) {
|
||||
SteamImportPrompt.answer(root, "9", now)
|
||||
val json = JSONObject(File(root, "root/.cache/droiddeck/steam-import.answer").readText())
|
||||
assertEquals("9", json.getString("token"))
|
||||
assertEquals(choice, json.getString("choice"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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,97 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class UsbLinkTest {
|
||||
private lateinit var sys: File
|
||||
|
||||
@Before fun setUp() { sys = Files.createTempDirectory("usblink").toFile() }
|
||||
|
||||
@After fun tearDown() {
|
||||
Files.walk(sys.toPath()).use { paths -> paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) } }
|
||||
}
|
||||
|
||||
private val mounts = """
|
||||
/dev/block/dm-5 /data ext4 rw 0 0
|
||||
/dev/fuse /storage/8C5A-1F23 fuse rw 0 0
|
||||
/dev/block/vold/public:8,97 /mnt/media_rw/8C5A-1F23 fuseblk rw 0 0
|
||||
""".trimIndent()
|
||||
|
||||
private fun drive(deviceSpeed: String, otherHub: String) {
|
||||
val controller = File(sys, "devices/platform/xhci")
|
||||
val hub = File(controller, "usb1").apply { mkdirs(); File(this, "speed").writeText("480\n"); File(this, "idVendor").writeText("1d6b\n") }
|
||||
File(controller, "usb2").apply { mkdirs(); File(this, "speed").writeText("$otherHub\n"); File(this, "idVendor").writeText("1d6b\n") }
|
||||
val device = File(hub, "1-1").apply { mkdirs() }
|
||||
File(device, "speed").writeText("$deviceSpeed\n")
|
||||
File(device, "idVendor").writeText("04e8\n")
|
||||
File(device, "busnum").writeText("1\n")
|
||||
File(device, "devnum").writeText("7\n")
|
||||
File(device, "manufacturer").writeText("Samsung\n")
|
||||
File(device, "product").writeText("PSSD T7\n")
|
||||
val part = File(device, "1-1:1.0/host1/target1:0:0/1:0:0:0/block/sdg/sdg1").apply { mkdirs() }
|
||||
File(sys, "dev/block").mkdirs()
|
||||
Files.createSymbolicLink(File(sys, "dev/block/8:97").toPath(), part.toPath())
|
||||
File(sys, "bus/usb/devices").mkdirs()
|
||||
Files.createSymbolicLink(File(sys, "bus/usb/devices/usb1").toPath(), hub.toPath())
|
||||
}
|
||||
|
||||
@Test fun findsTheUsbSpeedOfADriveBehindItsMount() {
|
||||
drive("480", "10000")
|
||||
val link = UsbLink.forPath("/storage/8C5A-1F23/Games", mounts, sys)!!
|
||||
assertEquals("8:97", link.device)
|
||||
assertEquals(480.0, link.mbps, 0.0)
|
||||
assertEquals("Samsung PSSD T7", link.name)
|
||||
assertEquals(10000.0, link.portMbps!!, 0.0)
|
||||
assertEquals("1-7", link.plug)
|
||||
assertEquals("3/1-7/8:97@480.0", UsbLink.dismissKey(3, link))
|
||||
assertFalse(UsbLink.SlowDrive("k", link.name, link.mbps, link.portMbps).portLimited)
|
||||
}
|
||||
|
||||
@Test fun aPortWithoutSuperSpeedIsReportedAsTheLimit() {
|
||||
drive("480", "480")
|
||||
val link = UsbLink.forPath("/storage/8C5A-1F23", mounts, sys)!!
|
||||
assertTrue(UsbLink.SlowDrive("k", link.name, link.mbps, link.portMbps).portLimited)
|
||||
}
|
||||
|
||||
@Test fun anUnknownPortSpeedIsNotReportedAsTheLimit() {
|
||||
drive("480", "10000")
|
||||
Files.delete(File(sys, "bus/usb/devices/usb1").toPath())
|
||||
val link = UsbLink.forPath("/storage/8C5A-1F23", mounts, sys)!!
|
||||
assertNull(link.portMbps)
|
||||
assertFalse(UsbLink.SlowDrive("k", link.name, link.mbps, link.portMbps).portLimited)
|
||||
}
|
||||
|
||||
@Test fun internalStorageAndUnknownMountsHaveNoLink() {
|
||||
drive("480", "10000")
|
||||
assertNull(UsbLink.forPath("/storage/emulated/0/Games", mounts, sys))
|
||||
assertNull(UsbLink.forPath("/storage/ABCD-0000", mounts, sys))
|
||||
}
|
||||
|
||||
@Test fun mountsPickTheLongestMatchingMountPoint() {
|
||||
assertEquals("8:97", UsbLink.mountDevice("/mnt/media_rw/8C5A-1F23/Games/PC", mounts))
|
||||
assertNull(UsbLink.mountDevice("/mnt/media_rw/8C5A-1F230", mounts))
|
||||
assertEquals("name:sda1", UsbLink.mountDevice("/mnt/usb/a", "/dev/block/sda1 /mnt/usb vfat rw 0 0"))
|
||||
}
|
||||
|
||||
@Test fun rawMountPathsAreTreatedAsTheirStorageVolume() {
|
||||
assertEquals("/storage/8C5A-1F23/Games", UsbLink.storagePath("/mnt/media_rw/8C5A-1F23/Games"))
|
||||
assertEquals("/storage/emulated/0/Games", UsbLink.storagePath("/storage/emulated/0/Games"))
|
||||
assertTrue(UsbLink.external(UsbLink.storagePath("/mnt/media_rw/8C5A-1F23/Games")))
|
||||
}
|
||||
|
||||
@Test fun generationsFollowTheLinkSpeed() {
|
||||
assertEquals("USB 1.1", UsbLink.generation(12.0))
|
||||
assertEquals("USB 2.0", UsbLink.generation(480.0))
|
||||
assertEquals("USB 3.2 Gen 1", UsbLink.generation(5000.0))
|
||||
assertEquals("USB 3.2 Gen 2", UsbLink.generation(10000.0))
|
||||
assertEquals(42, UsbLink.megabytesPerSecond(480.0))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GogMaintenanceTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
|
||||
@Test fun selectsPublicBranchAndTreatsBuildIdsAsOpaque() {
|
||||
val builds = JSONObject("""{"items":[
|
||||
{"os":"windows","branch":"beta","build_id":"99","generation":2,"link":"https://example.invalid/beta"},
|
||||
{"os":"windows","branch":null,"build_id":"0002","generation":2,"version_name":"RC-final","link":"https://example.invalid/current"},
|
||||
{"os":"windows","branch":null,"build_id":"10","generation":2,"link":"https://example.invalid/old"}]}""")
|
||||
assertEquals("0002", GogBuild.select(builds)!!.id)
|
||||
assertEquals("99", GogBuild.select(builds, branch = "beta")!!.id)
|
||||
assertEquals("10", GogBuild.select(builds, pinned = "10")!!.id)
|
||||
assertNull(GogBuild.select(builds, pinned = "missing"))
|
||||
assertNull(GogBuild.select(builds, branch = "private"))
|
||||
}
|
||||
|
||||
@Test fun migrationRetainsKnownBuildLanguageAndInstalledProducts() {
|
||||
val folder = temporary.newFolder()
|
||||
File(folder, "_gog_manifest.json").writeText("""{"gameId":"1","buildId":"000123"}""")
|
||||
File(folder, "goggame-2.info").writeText("{}")
|
||||
val sidecar = StoreGameSidecar(Store.GOG, "1", "Game", "game.exe", installVersion = "000123",
|
||||
args = listOf("--custom"), env = mapOf("DD_TEST" to "1"), cloud = false, achievements = false,
|
||||
extra = mapOf(StoreLanguage.EXTRA to "pl-PL"))
|
||||
val record = GogInstallRecord.migrate(folder, sidecar)
|
||||
assertEquals("000123", record.build)
|
||||
assertEquals("pl-PL", record.language)
|
||||
assertEquals(listOf("1", "2"), record.products)
|
||||
assertEquals(record.json().toString(), GogInstallRecord.read(folder)!!.json().toString())
|
||||
assertEquals(listOf("--custom"), sidecar.args)
|
||||
assertFalse(sidecar.cloud)
|
||||
}
|
||||
|
||||
@Test fun missingManifestNeverInventsLatestBuild() {
|
||||
val folder = temporary.newFolder()
|
||||
val record = GogInstallRecord.migrate(folder, StoreGameSidecar(Store.GOG, "1", "Game", "game.exe"))
|
||||
assertEquals("offline", record.source)
|
||||
assertEquals("", record.build)
|
||||
assertEquals(0, record.files.length())
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshWithDlcRequiresAnAuthenticMatchingDepotBuild() {
|
||||
val extracted = temporary.newFolder()
|
||||
val app = File(extracted, "app").apply { mkdirs() }
|
||||
val target = GogInstallRecord("1", "depot", build = "0000123", products = listOf("1", "2"))
|
||||
assertThrows(IllegalArgumentException::class.java) { GogOffline.validateDepotInstaller(extracted, target) }
|
||||
File(app, "goggame-1.info").writeText("""{"buildId":"0000999"}""")
|
||||
assertThrows(IllegalArgumentException::class.java) { GogOffline.validateDepotInstaller(extracted, target) }
|
||||
File(app, "goggame-1.info").writeText("""{"buildId":"0000123"}""")
|
||||
GogOffline.validateDepotInstaller(extracted, target)
|
||||
File(app, "goggame-1.info").delete()
|
||||
GogOffline.validateDepotInstaller(extracted, target.copy(source = "offline", build = ""))
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshRetainsTheExistingExecutableLayout() {
|
||||
val installed = temporary.newFolder()
|
||||
val extracted = temporary.newFolder()
|
||||
val app = File(extracted, "app").apply { mkdirs() }
|
||||
File(app, "game.exe").writeText("replacement")
|
||||
File(installed, "goggame-1.info").writeText("{}")
|
||||
assertEquals(extracted, GogOffline.layout(extracted, installed, "1", "game.exe").source)
|
||||
assertEquals("", GogOffline.layout(extracted, installed, "1", "game.exe").prefix)
|
||||
File(installed, "goggame-1.info").delete()
|
||||
assertEquals(extracted, GogOffline.layout(extracted, installed, "1", "app/game.exe").source)
|
||||
val flat = temporary.newFolder()
|
||||
val legacy = GogOffline.layout(flat, installed, "1", "app/game.exe")
|
||||
assertEquals(flat, legacy.source)
|
||||
assertEquals("app/", legacy.prefix)
|
||||
}
|
||||
|
||||
@Test fun offlineInstallerMatchesRegionalLanguageWithoutChoosingAnotherLanguage() {
|
||||
val downloads = JSONObject("""{"installers":[
|
||||
{"id":"de","os":"windows","language":"de","files":[{"downlink":"https://example.invalid/de"}]},
|
||||
{"id":"en","os":"windows","language":"en","files":[{"downlink":"https://example.invalid/en"}]}]}""")
|
||||
assertEquals("en", GogMaintenance.offlineInstaller(downloads, "en-US").id)
|
||||
assertThrows(IllegalStateException::class.java) { GogMaintenance.offlineInstaller(downloads, "pl-PL") }
|
||||
downloads.getJSONArray("installers").put(0, JSONObject("""{"id":"neutral","os":"windows","language":"Neutral","files":[{"downlink":"https://example.invalid/neutral"}]}"""))
|
||||
assertEquals("en", GogMaintenance.offlineInstaller(downloads, "en-US").id)
|
||||
assertEquals("neutral", GogMaintenance.offlineInstaller(downloads, "pl-PL").id)
|
||||
}
|
||||
|
||||
@Test fun incompleteOfflineExtractionCannotReplaceOrRemoveInstalledFiles() {
|
||||
val folder = temporary.newFolder()
|
||||
StoreGameSidecar(Store.GOG, "1", "Game", "game.exe").write(folder)
|
||||
val game = File(folder, "game.exe").apply { writeText("installed game") }
|
||||
val old = GogInstallRecord("1", "depot", files = JSONArray().put(JSONObject().put("path", game.name)
|
||||
.put("size", game.length()).put("md5", GogFiles.hash(game))))
|
||||
old.write(folder)
|
||||
val extracted = temporary.newFolder()
|
||||
File(extracted, "goggame-1.ico").writeText("ancillary file")
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, old.copy(source = "offline"), GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
}
|
||||
assertEquals("installed game", game.readText())
|
||||
assertFalse(File(folder, "goggame-1.ico").exists())
|
||||
assertEquals("depot", GogInstallRecord.read(folder)!!.source)
|
||||
val migrated = old.copy(files = JSONArray())
|
||||
migrated.write(folder)
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, migrated, migrated.copy(source = "offline"), GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
}
|
||||
assertEquals("installed game", game.readText())
|
||||
assertFalse(File(folder, "goggame-1.ico").exists())
|
||||
assertEquals("depot", GogInstallRecord.read(folder)!!.source)
|
||||
assertEquals(0, GogInstallRecord.read(folder)!!.files.length())
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshCombinesRootPayloadAndAppPlaceholdersInBothLayouts() {
|
||||
for (nested in listOf(false, true)) {
|
||||
val folder = temporary.newFolder()
|
||||
val executable = if (nested) "app/game.exe" else "game.exe"
|
||||
StoreGameSidecar(Store.GOG, "1", "Game", executable).write(folder)
|
||||
val game = File(folder, executable).apply { parentFile!!.mkdirs(); writeText("old game") }
|
||||
val old = GogInstallRecord("1", "offline", files = JSONArray().put(JSONObject().put("path", executable)
|
||||
.put("size", game.length()).put("md5", GogFiles.hash(game))))
|
||||
old.write(folder)
|
||||
val extracted = temporary.newFolder()
|
||||
File(extracted, "game.exe").writeText("complete new game")
|
||||
File(extracted, "Data").mkdirs()
|
||||
File(extracted, "app/Data/SaveGame").mkdirs()
|
||||
File(extracted, "app/Data/SaveGame/dummy.txt").writeBytes(byteArrayOf())
|
||||
File(extracted, "tmp").mkdirs()
|
||||
File(extracted, "tmp/installer.exe").writeText("installer support")
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, old, GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
assertEquals("complete new game", game.readText())
|
||||
assertTrue(File(folder, (if (nested) "app/" else "") + "Data/SaveGame/dummy.txt").isFile)
|
||||
assertFalse(File(folder, "tmp").exists())
|
||||
assertTrue(GogInstallRecord.read(folder)!!.files.objects().any { it.getString("path") == executable })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshDefersDlcCleanupAndRecordPublicationUntilDepotCompletion() {
|
||||
val folder = temporary.newFolder()
|
||||
StoreGameSidecar(Store.GOG, "1", "Game", "base.exe").write(folder)
|
||||
val base = File(folder, "base.exe").apply { writeText("old base") }
|
||||
val dlc = File(folder, "dlc.bin").apply { writeText("old DLC") }
|
||||
val obsolete = File(folder, "old.bin").apply { writeText("obsolete") }
|
||||
val save = File(folder, "save.dat").apply { writeText("player progress") }
|
||||
fun entry(file: File, product: String) = JSONObject().put("path", file.name).put("size", file.length())
|
||||
.put("md5", GogFiles.hash(file)).put("product", product).put("offset", 0).put("remotePath", file.name)
|
||||
val old = GogInstallRecord("1", "depot", build = "old", products = listOf("1", "2"),
|
||||
files = JSONArray().put(entry(base, "1")).put(entry(dlc, "2")).put(entry(obsolete, "1")))
|
||||
old.write(folder)
|
||||
val recordFile = File(GogFiles.dir(folder), "installed.json")
|
||||
val record = recordFile.readText()
|
||||
val extracted = temporary.newFolder()
|
||||
val app = File(extracted, "app").apply { mkdirs() }
|
||||
File(app, "goggame-1.info").writeText("""{"buildId":"new"}""")
|
||||
val replacement = File(app, "base.exe").apply { writeText("new base") }
|
||||
val expectedDlc = File(temporary.newFolder(), "dlc.bin").apply { writeText("new DLC") }
|
||||
val target = old.copy(build = "new", files = JSONArray().put(entry(replacement, "1")).put(entry(expectedDlc, "2")))
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, target, GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
assertEquals("new base", base.readText())
|
||||
assertEquals("old DLC", dlc.readText())
|
||||
assertTrue(obsolete.isFile)
|
||||
assertEquals(record, recordFile.readText())
|
||||
val server = java.net.ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
|
||||
val worker = Thread {
|
||||
server.accept().use { client ->
|
||||
val reader = client.getInputStream().bufferedReader()
|
||||
while (!reader.readLine().isNullOrEmpty()) Unit
|
||||
val content = expectedDlc.readBytes()
|
||||
client.getOutputStream().apply {
|
||||
write("HTTP/1.1 206 Partial Content\r\nContent-Length: ${content.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
write(content); flush()
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
try {
|
||||
GogFallback.transfer(folder, JSONObject().put("files", target.files).put("oldFiles", old.files)
|
||||
.put("links", JSONObject().put("2", JSONArray().put("http://127.0.0.1:${server.localPort}"))), null, AtomicBoolean(false))
|
||||
assertEquals("new DLC", dlc.readText())
|
||||
assertFalse(obsolete.exists())
|
||||
assertEquals("player progress", save.readText())
|
||||
assertEquals(record, recordFile.readText())
|
||||
} finally { server.close(); worker.join(2000) }
|
||||
}
|
||||
|
||||
@Test fun authenticIdentityOverridesAStaleLegacyMarkerWithoutTreatingSchemaAsVersion() {
|
||||
val folder = temporary.newFolder()
|
||||
File(folder, "_gog_manifest.json").writeText("""{"buildId":"old"}""")
|
||||
File(folder, "goggame-1.id").writeText("""{"buildId":"patched"}""")
|
||||
File(folder, "goggame-1.info").writeText("""{"version":1}""")
|
||||
val record = GogInstallRecord.migrate(folder, StoreGameSidecar(Store.GOG, "1", "Game", "game.exe", installVersion = "old"))
|
||||
assertEquals("patched", record.build)
|
||||
assertEquals("", record.version)
|
||||
}
|
||||
|
||||
@Test fun authenticGenerationOneResolvesProductDepotsAndRetainsHashesAndBuild() {
|
||||
fun fixture(name: String) = JSONObject(javaClass.classLoader!!.getResource("gog/$name")!!.readText())
|
||||
val build = GogBuild("3301", "", 1, "", "https://example.invalid/repository.json")
|
||||
val requested = ArrayList<String>()
|
||||
val snapshot = GogContent.snapshot(GogInstallRecord("1207658940", "depot"), build, "unused") { url, _ ->
|
||||
requested.add(url)
|
||||
when {
|
||||
url == build.link -> fixture("rayman-gen1-repository.json")
|
||||
url.endsWith("a01f6fb8-55a8-4f33-bc5b-5f5d2f591775.json") -> fixture("rayman-gen1-neutral.json")
|
||||
url.endsWith("ec88140c-2589-41a0-bbf3-8fc1f215fe5a.json") -> fixture("rayman-gen1-english-excerpt.json")
|
||||
else -> error("Unexpected metadata: $url")
|
||||
}
|
||||
}
|
||||
assertEquals("3301", snapshot.build)
|
||||
assertEquals(1, snapshot.generation)
|
||||
assertEquals(4, snapshot.files.length())
|
||||
val support = snapshot.files.getJSONObject(0)
|
||||
assertEquals("support/1207658940/galaxy_rayman2_2.1.0.39.exe", support.getString("path"))
|
||||
assertEquals("ee2c247373733f29782395f1f92622f6", support.getString("md5"))
|
||||
val game = snapshot.files.getJSONObject(1)
|
||||
assertEquals("Data/World/Levels/Raycap/Raycap.snd", game.getString("path"))
|
||||
assertEquals(384206096L, game.getLong("offset"))
|
||||
assertEquals("1207658940/main.bin", game.getString("remotePath"))
|
||||
assertTrue(requested.drop(1).all { "/1207658940/windows/31847977/" in it })
|
||||
GogFiles.validate(snapshot.files, temporary.newFolder())
|
||||
}
|
||||
|
||||
@Test fun multipartPatchNamesVersionsLanguageAndChecksumsSurviveParsing() {
|
||||
val downloads = JSONObject("""{"patches":[
|
||||
{"id":"patch-1","name":"Patch A to B","version":"B","language":"pl","os":"windows","files":[
|
||||
{"id":"part0","filename":"patch_original.exe","downlink":"https://example.invalid/0","size":3,"md5":"abc"},
|
||||
{"id":"part1","filename":"patch_original-1.bin","downlink":"https://example.invalid/1","size":4}]},
|
||||
{"id":"linux","os":"linux","files":[{"downlink":"https://example.invalid/linux"}]}]}""")
|
||||
val patch = GogOfflineDownload.parse(downloads, "patches").single()
|
||||
assertEquals("Patch A to B", patch.name)
|
||||
assertEquals("B", patch.version)
|
||||
assertEquals("pl", patch.language)
|
||||
assertEquals(7, patch.size)
|
||||
assertEquals(listOf("patch_original.exe", "patch_original-1.bin"), patch.parts.map { it.name })
|
||||
assertEquals("abc", patch.parts.first().md5)
|
||||
assertEquals("patch_(52404)+special.exe", GogContent.downloadFilename("https://example.invalid/patch_%2852404%29+special.exe?token=temporary"))
|
||||
}
|
||||
|
||||
@Test fun pathsRejectTraversalSymlinksCaseCollisionsAndMetadataOverlap() {
|
||||
val folder = temporary.newFolder()
|
||||
for (path in listOf("../escape", "/absolute", "C:/file", "a/./file", "a//file")) {
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.inside(folder, path) }
|
||||
}
|
||||
val files = JSONArray("""[{"path":"Game.exe"},{"path":"game.exe"}]""")
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(files, folder) }
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"Data/a"},{"path":"data/b"}]"""), folder) }
|
||||
File(folder, "Game.bin").writeText("original")
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"game.bin"}]"""), folder) }
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":".droiddeck-store.json"}]"""), folder) }
|
||||
val outside = temporary.newFolder()
|
||||
try { Files.createSymbolicLink(File(folder, "link").toPath(), outside.toPath()) }
|
||||
catch (_: java.nio.file.FileSystemException) { return }
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.inside(folder, "link/game.exe") }
|
||||
}
|
||||
|
||||
@Test fun sameSizeCorruptionFailsVerificationAndLanguageVariantsRemainDistinct() {
|
||||
val folder = temporary.newFolder()
|
||||
val file = File(folder, "game.bin").apply { writeText("original") }
|
||||
val expected = JSONObject().put("path", file.name).put("size", file.length()).put("md5", GogFiles.hash(file))
|
||||
file.writeText("modified")
|
||||
assertFalse(GogFiles.matches(folder, expected))
|
||||
assertTrue(GogContent.languageSelected(listOf("*"), "zh-Hant"))
|
||||
assertFalse(GogContent.languageSelected(listOf("zh-Hans"), "zh-Hant"))
|
||||
assertTrue(GogContent.languageSelected(listOf("Polish"), "pl"))
|
||||
}
|
||||
|
||||
@Test fun persistedManifestsContainNoCredentialsOrTemporaryLinks() {
|
||||
val input = JSONObject("""{"buildId":"1","clientSecret":"secret","urls":[{"url":"https://example.invalid/?token=secret"}],
|
||||
"products":[{"productId":"2","clientSecret":"nested"}],"dependencies":["ISI"]}""")
|
||||
val text = GogContent.sanitize(input).toString()
|
||||
assertFalse(text.contains("secret"))
|
||||
assertFalse(text.contains("https://"))
|
||||
assertTrue(text.contains("ISI"))
|
||||
}
|
||||
|
||||
@Test fun interruptedExternalPatchRestoresRecoveryWithoutExecutingAgain() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "Patch recovery").apply { mkdirs() }
|
||||
try {
|
||||
val sidecar = StoreGameSidecar(Store.GOG, "recovery-test", "Patch recovery", "game.exe",
|
||||
args = listOf("--custom"), env = mapOf("SETTING" to "value"), cloud = false,
|
||||
achievements = false, state = StoreGameSidecar.STATE_UPDATING)
|
||||
sidecar.write(folder)
|
||||
val previous = sidecar.toJson().toString()
|
||||
GogFiles.write(GogFiles.journal(folder), JSONObject().put("operation", "PATCH").put("phase", "patch-applying"))
|
||||
val item = CatalogItem(Store.GOG, sidecar.id, sidecar.title, imageUrl = null, extra = mapOf(
|
||||
GogMaintenance.OPERATION to "PATCH", GogMaintenance.FOLDER to folder.path))
|
||||
GogMaintenance.restore(app, item)
|
||||
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
|
||||
assertTrue(DownloadQueue.entry(item.key)!!.error!!.contains("recovery"))
|
||||
assertEquals(previous, StoreGameSidecar.read(folder)!!.toJson().toString())
|
||||
assertEquals("patch-applying", GogFiles.read(GogFiles.journal(folder))!!.getString("phase"))
|
||||
DownloadQueue.clear(app, item.key)
|
||||
} finally { folder.deleteRecursively() }
|
||||
}
|
||||
|
||||
@Test fun signedOutCheckRemainsAFailureInsteadOfCurrent() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
com.droiddeck.launcher.stores.StoreAccounts.clear(app, Store.GOG)
|
||||
GogMaintenance.reset()
|
||||
val folder = temporary.newFolder()
|
||||
val game = com.droiddeck.launcher.stores.InstalledStoreGame(
|
||||
StoreGameSidecar(Store.GOG, "signed-out-check", "Check", "game.exe", installVersion = "opaque-build"), folder)
|
||||
GogMaintenance.check(app, game, force = true)
|
||||
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5)
|
||||
while (System.nanoTime() < deadline) {
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
if (GogMaintenance.checks[game.sidecar.id]?.state == GogMaintenance.State.FAILED) break
|
||||
Thread.sleep(10)
|
||||
}
|
||||
assertEquals(GogMaintenance.State.FAILED, GogMaintenance.checks[game.sidecar.id]?.state)
|
||||
assertTrue(GogMaintenance.checks[game.sidecar.id]!!.reason.contains("Sign in"))
|
||||
}
|
||||
|
||||
@Test fun pauseBeforeInstallerClaimCannotStartExternalApplication() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val ready = java.util.concurrent.CountDownLatch(1)
|
||||
val proceed = java.util.concurrent.CountDownLatch(1)
|
||||
val finished = java.util.concurrent.CountDownLatch(1)
|
||||
val applied = AtomicBoolean(false)
|
||||
val item = com.droiddeck.launcher.stores.download.DownloadEntry(Store.GOG, "installer-claim", "Installer claim")
|
||||
DownloadQueue.enqueue(app, item) {
|
||||
object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
ready.countDown()
|
||||
try {
|
||||
check(proceed.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
handle.interruptible(false)
|
||||
applied.set(true)
|
||||
return null
|
||||
} finally { finished.countDown() }
|
||||
}
|
||||
override fun cancel(deleteFiles: Boolean) {}
|
||||
}
|
||||
}
|
||||
try {
|
||||
assertTrue(ready.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
DownloadQueue.pause(item.key)
|
||||
proceed.countDown()
|
||||
assertTrue(finished.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
assertFalse(applied.get())
|
||||
} finally {
|
||||
proceed.countDown()
|
||||
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5)
|
||||
while (DownloadQueue.entry(item.key)?.state == DownloadState.RUNNING && System.nanoTime() < deadline) Thread.sleep(10)
|
||||
DownloadQueue.clear(app, item.key)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun fileFallbackVerifiesRemoteBytesAndPreservesOriginalOnCorruption() {
|
||||
val folder = temporary.newFolder()
|
||||
val content = "verified remote content".toByteArray()
|
||||
val original = File(folder, "game.bin").apply { writeText("local data") }
|
||||
val server = java.net.ServerSocket(0, 10, java.net.InetAddress.getByName("127.0.0.1"))
|
||||
var reply = content
|
||||
var transferred = 0
|
||||
val worker = Thread {
|
||||
while (!server.isClosed) {
|
||||
val client = try { server.accept() } catch (_: java.io.IOException) { break }
|
||||
client.use {
|
||||
val reader = it.getInputStream().bufferedReader()
|
||||
while (!reader.readLine().isNullOrEmpty()) Unit
|
||||
it.getOutputStream().apply {
|
||||
write("HTTP/1.1 206 Partial Content\r\nContent-Length: ${reply.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
write(reply); flush(); transferred += reply.size
|
||||
}
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
try {
|
||||
val expected = File(folder, "expected").apply { writeBytes(content) }
|
||||
val file = JSONObject().put("path", "game.bin").put("size", content.size).put("md5", GogFiles.hash(expected))
|
||||
.put("product", "1").put("offset", 0).put("remotePath", "data")
|
||||
val plan = JSONObject().put("files", JSONArray().put(file)).put("links", JSONObject().put("1", JSONArray().put("http://127.0.0.1:${server.localPort}")))
|
||||
reply = ByteArray(content.size) { 65 }
|
||||
assertThrows(IllegalStateException::class.java) { GogFallback.transfer(folder, plan, null, AtomicBoolean(false)) }
|
||||
assertEquals("local data", original.readText())
|
||||
reply = content
|
||||
GogFallback.transfer(folder, plan, null, AtomicBoolean(false))
|
||||
assertArrayEquals(content, original.readBytes())
|
||||
val before = transferred
|
||||
GogFallback.transfer(folder, plan, null, AtomicBoolean(false))
|
||||
assertEquals(before, transferred)
|
||||
} finally { server.close(); worker.join(2000) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
class ItchArchivesTest {
|
||||
private lateinit var dir: File
|
||||
|
||||
@Before fun setUp() {
|
||||
dir = Files.createTempDirectory("itch-archives").toFile()
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
Files.walk(dir.toPath()).sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) }
|
||||
}
|
||||
|
||||
private fun file(name: String, vararg head: Int, size: Int = 64): File {
|
||||
val f = File(dir, name)
|
||||
f.parentFile?.mkdirs()
|
||||
val bytes = ByteArray(maxOf(size, head.size))
|
||||
head.forEachIndexed { i, b -> bytes[i] = b.toByte() }
|
||||
f.writeBytes(bytes)
|
||||
return f
|
||||
}
|
||||
|
||||
@Test fun kindsComeFromTheContentNotTheName() {
|
||||
assertEquals("7z", ItchArchives.kind(file("data.bin", 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C), "data.bin"))
|
||||
assertEquals("zip", ItchArchives.kind(file("a.7z", 0x50, 0x4B, 3, 4), "a.7z"))
|
||||
assertEquals("rar", ItchArchives.kind(file("b", 0x52, 0x61, 0x72, 0x21), "b"))
|
||||
assertEquals("exe", ItchArchives.kind(file("Game.exe", 0x50, 0x4B), "Game.exe"))
|
||||
}
|
||||
|
||||
@Test fun theLargestArchiveInsideIsUnpackedNext() {
|
||||
file("readme.txt", 0x48, 0x69)
|
||||
file("VotV.7z", 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C, size = 4096)
|
||||
file("extras/art.zip", 0x50, 0x4B, 3, 4, size = 128)
|
||||
assertEquals("VotV.7z", ItchArchives.inner(dir)?.name)
|
||||
}
|
||||
|
||||
@Test fun archivesDeeperThanTwoFoldersAreLeftAlone() {
|
||||
file("a/b/c/deep.zip", 0x50, 0x4B, 3, 4)
|
||||
assertNull(ItchArchives.inner(dir))
|
||||
}
|
||||
|
||||
@Test fun nothingPackedMeansNothingToUnpack() {
|
||||
file("game.pak", 0x00, 0x01)
|
||||
file("notes.txt", 0x48, 0x69)
|
||||
assertNull(ItchArchives.inner(dir))
|
||||
}
|
||||
|
||||
@Test fun aNamedArchiveWithoutASignatureIsSkipped() {
|
||||
file("extras.zip", 0x48, 0x69, size = 8192)
|
||||
file("game.7z", 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C, size = 128)
|
||||
assertEquals("game.7z", ItchArchives.inner(dir)?.name)
|
||||
}
|
||||
|
||||
@Test fun symlinksAreNotFollowed() {
|
||||
val root = File(dir, "root").apply { mkdirs() }
|
||||
val outside = File(dir, "outside").apply { mkdirs() }
|
||||
File(outside, "keep.zip").writeBytes(byteArrayOf(0x50, 0x4B, 3, 4))
|
||||
Files.createSymbolicLink(File(root, "link").toPath(), outside.toPath())
|
||||
Files.createSymbolicLink(File(root, "linked.zip").toPath(), File(outside, "keep.zip").toPath())
|
||||
assertNull(ItchArchives.inner(root))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class ItchBuildsTest {
|
||||
private fun file(id: Int, type: String, sub: String, size: Int = 10) =
|
||||
JSONObject().put("id", id).put("type", type).put("sub_type", sub).put("size", size).put("state", "uploaded")
|
||||
|
||||
private fun build(id: Int, vararg files: JSONObject) = JSONObject().put("id", id).put("files", JSONArray(files.toList()))
|
||||
|
||||
private fun path(vararg builds: JSONObject) = JSONObject().put("upgrade_path", JSONObject().put("builds", JSONArray(builds.toList())))
|
||||
|
||||
@Test fun buildIdReadsBothKeyStylesAndIgnoresMissingValues() {
|
||||
assertEquals("55", ItchBuilds.buildId(JSONObject().put("build_id", 55)))
|
||||
assertEquals("56", ItchBuilds.buildId(JSONObject().put("buildId", "56")))
|
||||
assertEquals("", ItchBuilds.buildId(JSONObject().put("build_id", JSONObject.NULL)))
|
||||
assertEquals("", ItchBuilds.buildId(JSONObject().put("build_id", 0)))
|
||||
assertEquals("", ItchBuilds.buildId(JSONObject().put("build_id", "00")))
|
||||
assertEquals("57", ItchBuilds.buildId(JSONObject().put("build_id", "057")))
|
||||
assertEquals("", ItchBuilds.buildId(JSONObject()))
|
||||
}
|
||||
|
||||
@Test fun pathSkipsTheInstalledBuildAndPrefersOptimizedPatches() {
|
||||
val reply = path(
|
||||
build(1, file(11, "patch", "default")),
|
||||
build(2, file(21, "patch", "default", 5), file(22, "patch", "optimized", 3), file(23, "signature", "default")),
|
||||
)
|
||||
val steps = ItchBuilds.steps(reply, 1, 2) { it.optJSONArray("files") }!!
|
||||
assertEquals(1, steps.size)
|
||||
assertEquals(2L, steps.single().buildId)
|
||||
assertEquals(22L, steps.single().patchFile)
|
||||
assertEquals(3L, steps.single().patchSize)
|
||||
assertEquals(23L, steps.single().signatureFile)
|
||||
}
|
||||
|
||||
@Test fun pathIsRefusedWithoutASignatureOrAPatchOrTheRightEnd() {
|
||||
val noSignature = path(build(1), build(2, file(21, "patch", "default")))
|
||||
assertNull(ItchBuilds.steps(noSignature, 1, 2) { it.optJSONArray("files") })
|
||||
val noPatch = path(build(1), build(2, file(23, "signature", "default")))
|
||||
assertNull(ItchBuilds.steps(noPatch, 1, 2) { it.optJSONArray("files") })
|
||||
val wrongEnd = path(build(1), build(3, file(31, "patch", "default"), file(32, "signature", "default")))
|
||||
assertNull(ItchBuilds.steps(wrongEnd, 1, 2) { it.optJSONArray("files") })
|
||||
assertNull(ItchBuilds.steps(JSONObject(), 1, 2) { it.optJSONArray("files") })
|
||||
}
|
||||
|
||||
@Test fun pathNeedsFilesFromALookupWhenTheBuildListsNone() {
|
||||
val reply = path(JSONObject().put("id", 1), JSONObject().put("id", 2))
|
||||
val steps = ItchBuilds.steps(reply, 1, 2) { JSONArray().put(file(21, "patch", "default")).put(file(23, "signature", "default")) }!!
|
||||
assertEquals(21L, steps.single().patchFile)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class ItchStagingTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun file(root: File, path: String, text: String) = File(root, path).also { it.parentFile?.mkdirs(); it.writeText(text) }
|
||||
|
||||
@Test fun newFilesReplaceOldOnesAndEverythingElseStays() {
|
||||
val game = tmp.newFolder("game")
|
||||
val staged = tmp.newFolder("staged")
|
||||
file(game, "game.exe", "old")
|
||||
file(game, "data/level.dat", "old")
|
||||
file(game, "saves/slot1.sav", "mine")
|
||||
file(game, ".droiddeck-store.json", "record")
|
||||
file(staged, "game.exe", "new")
|
||||
file(staged, "data/level.dat", "new")
|
||||
file(staged, "data/extra.dat", "new")
|
||||
file(staged, "saves/default.sav", "new")
|
||||
ItchStaging.merge(staged, game)
|
||||
assertEquals("new", File(game, "game.exe").readText())
|
||||
assertEquals("new", File(game, "data/level.dat").readText())
|
||||
assertEquals("new", File(game, "data/extra.dat").readText())
|
||||
assertEquals("mine", File(game, "saves/slot1.sav").readText())
|
||||
assertEquals("new", File(game, "saves/default.sav").readText())
|
||||
assertEquals("record", File(game, ".droiddeck-store.json").readText())
|
||||
assertTrue(staged.listFiles().orEmpty().all { it.isDirectory && it.listFiles().orEmpty().isEmpty() })
|
||||
}
|
||||
|
||||
@Test fun aFileReplacingADirectoryAndTheOtherWayRound() {
|
||||
val game = tmp.newFolder("game")
|
||||
val staged = tmp.newFolder("staged")
|
||||
file(game, "a/inner.txt", "old")
|
||||
file(game, "b", "old")
|
||||
file(staged, "a", "new")
|
||||
file(staged, "b/inner.txt", "new")
|
||||
ItchStaging.merge(staged, game)
|
||||
assertTrue(File(game, "a").isFile)
|
||||
assertEquals("new", File(game, "a").readText())
|
||||
assertEquals("new", File(game, "b/inner.txt").readText())
|
||||
assertFalse(File(game, "a/inner.txt").exists())
|
||||
}
|
||||
|
||||
@Test fun deletingFollowsNoLinkOutOfTheTree() {
|
||||
val outside = tmp.newFolder("outside")
|
||||
file(outside, "keep.txt", "keep")
|
||||
val staged = tmp.newFolder("staged")
|
||||
file(staged, "own.txt", "x")
|
||||
java.nio.file.Files.createSymbolicLink(File(staged, "link").toPath(), outside.toPath())
|
||||
ItchStaging.delete(staged)
|
||||
assertFalse(staged.exists())
|
||||
assertEquals("keep", File(outside, "keep.txt").readText())
|
||||
}
|
||||
|
||||
@Test fun aLinkInTheGameIsReplacedNotFollowed() {
|
||||
val outside = tmp.newFolder("outside")
|
||||
file(outside, "keep.txt", "keep")
|
||||
val game = tmp.newFolder("game")
|
||||
java.nio.file.Files.createSymbolicLink(File(game, "data").toPath(), outside.toPath())
|
||||
val staged = tmp.newFolder("staged")
|
||||
file(staged, "data/level.dat", "new")
|
||||
ItchStaging.merge(staged, game)
|
||||
assertEquals("keep", File(outside, "keep.txt").readText())
|
||||
assertFalse(File(outside, "level.dat").exists())
|
||||
assertEquals("new", File(game, "data/level.dat").readText())
|
||||
}
|
||||
|
||||
@Test fun theInstallRecordIsNeverReplacedByTheArchive() {
|
||||
val game = tmp.newFolder("game")
|
||||
val staged = tmp.newFolder("staged")
|
||||
file(game, ".droiddeck-store.json", "record")
|
||||
file(staged, ".droiddeck-store.json", "forged")
|
||||
file(staged, "sub/.droiddeck-store.json", "nested")
|
||||
ItchStaging.merge(staged, game)
|
||||
assertEquals("record", File(game, ".droiddeck-store.json").readText())
|
||||
assertEquals("nested", File(game, "sub/.droiddeck-store.json").readText())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
|
||||
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
|
||||
class ItchUpdatesTest {
|
||||
private fun upload(id: String, updated: String, filename: String = "game-$id.zip", windows: Boolean = true, type: String = "default") =
|
||||
JSONObject().put("id", id).put("filename", filename).put("updated_at", updated).put("type", type).put("storage", "hosted")
|
||||
.put("platforms", JSONObject().put("windows", windows).put("linux", !windows))
|
||||
|
||||
private fun list(vararg uploads: JSONObject) = JSONArray().also { a -> uploads.forEach { a.put(it) } }
|
||||
|
||||
@Test fun aNewerStampOnTheSameUploadIsAnUpdate() {
|
||||
val update = ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", "2026-09-01T10:00:00Z")!!
|
||||
assertEquals("7", update.uploadId)
|
||||
assertEquals("2026-10-20T10:00:00Z", update.updatedAt)
|
||||
assertFalse(update.replaced)
|
||||
}
|
||||
|
||||
@Test fun theSameStampIsNotAnUpdate() {
|
||||
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-09-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
|
||||
}
|
||||
|
||||
@Test fun anOlderStampIsNotAnUpdate() {
|
||||
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-08-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
|
||||
}
|
||||
|
||||
@Test fun aMissingUploadFallsBackToTheNewestWindowsOneAndAsksFirst() {
|
||||
val update = ItchUpdates.evaluate(
|
||||
list(upload("8", "2026-10-01T10:00:00Z"), upload("9", "2026-10-05T10:00:00Z"), upload("10", "2026-10-09T10:00:00Z", windows = false)),
|
||||
"7", "2026-09-01T10:00:00Z",
|
||||
)!!
|
||||
assertEquals("9", update.uploadId)
|
||||
assertTrue(update.replaced)
|
||||
}
|
||||
|
||||
@Test fun aReplacedUploadWithNoWindowsBuildLeftIsNotOffered() {
|
||||
val linux = list(upload("8", "2026-10-01T10:00:00Z", windows = false))
|
||||
assertNull(ItchUpdates.evaluate(linux, "7", "2026-09-01T10:00:00Z"))
|
||||
assertNull(ItchUpdates.evaluate(linux, "", "2026-09-01T10:00:00Z"))
|
||||
}
|
||||
|
||||
@Test fun aWindowsBuildOfAnotherTypeBeatsALinuxDefaultOne() {
|
||||
val update = ItchUpdates.evaluate(
|
||||
list(upload("8", "2026-10-09T10:00:00Z", windows = false), upload("9", "2026-10-01T10:00:00Z", type = "other")),
|
||||
"7", "2026-09-01T10:00:00Z",
|
||||
)!!
|
||||
assertEquals("9", update.uploadId)
|
||||
assertTrue(update.replaced)
|
||||
}
|
||||
|
||||
@Test fun anUnknownInstalledVersionNeverReportsAnUpdate() {
|
||||
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", ""))
|
||||
}
|
||||
|
||||
@Test fun noAnswerOrNoWindowsBuildMeansNoUpdate() {
|
||||
assertNull(ItchUpdates.evaluate(null, "7", "2026-09-01T10:00:00Z"))
|
||||
assertNull(ItchUpdates.evaluate(JSONArray(), "7", "2026-09-01T10:00:00Z"))
|
||||
}
|
||||
|
||||
@Test fun anInstallWithoutAnUploadIdComparesTheNewestWindowsBuild() {
|
||||
val update = ItchUpdates.evaluate(list(upload("8", "2026-10-01T10:00:00Z")), "", "2026-09-01T10:00:00Z")!!
|
||||
assertEquals("8", update.uploadId)
|
||||
assertFalse(update.replaced)
|
||||
assertNull(ItchUpdates.evaluate(list(upload("8", "2026-08-01T10:00:00Z")), "", "2026-09-01T10:00:00Z"))
|
||||
}
|
||||
|
||||
@Test fun foundUpdatesSurviveTheCache() {
|
||||
val found = mapOf("itch:a/b" to ItchUpdate("9", "2026-10-05T10:00:00Z", "b.zip", true))
|
||||
val back = ItchUpdates.decode(ItchUpdates.encode(found))
|
||||
assertEquals(setOf("itch:a/b"), back.keys)
|
||||
assertEquals("9", back.getValue("itch:a/b").uploadId)
|
||||
assertTrue(back.getValue("itch:a/b").replaced)
|
||||
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode(null))
|
||||
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode("not json"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.input.CommitTextCommand
|
||||
import androidx.compose.ui.text.input.DeleteAllCommand
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.ImeOptions
|
||||
import androidx.compose.ui.text.input.SetSelectionCommand
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(manifest = Config.NONE)
|
||||
class BottomScreenTypingTest {
|
||||
@Test fun editsReplaceTheWholeFieldAndKeepTheCursor() {
|
||||
val edits = TypingRequest.editsFor(TextFieldValue("fall", TextRange(2, 4)))
|
||||
assertEquals(3, edits.size)
|
||||
assertTrue(edits[0] is DeleteAllCommand)
|
||||
assertEquals("fall", (edits[1] as CommitTextCommand).text)
|
||||
val selection = edits[2] as SetSelectionCommand
|
||||
assertEquals(2, selection.start)
|
||||
assertEquals(4, selection.end)
|
||||
}
|
||||
|
||||
@Test fun requestForwardsTextActionAndClose() {
|
||||
val sent = mutableListOf<String>()
|
||||
val actions = mutableListOf<ImeAction>()
|
||||
var closed = 0
|
||||
val request = TypingRequest(
|
||||
TextFieldValue("a"), ImeOptions(imeAction = ImeAction.Search),
|
||||
{ sent += it.text }, { actions += it }, { closed++ },
|
||||
)
|
||||
request.send(TextFieldValue("ab"))
|
||||
request.action()
|
||||
request.close()
|
||||
assertEquals(listOf("ab"), sent)
|
||||
assertEquals("ab", request.value.text)
|
||||
assertEquals(listOf(ImeAction.Search), actions)
|
||||
assertEquals(1, closed)
|
||||
}
|
||||
|
||||
@Test fun panelStopsOnlyItsOwnRequest() {
|
||||
val first = TypingRequest(TextFieldValue(""), ImeOptions.Default, {}, {})
|
||||
val second = TypingRequest(TextFieldValue(""), ImeOptions.Default, {}, {})
|
||||
DualScreenPanel.startTyping(second)
|
||||
DualScreenPanel.stopTyping(first)
|
||||
assertEquals(second, DualScreenPanel.typing)
|
||||
DualScreenPanel.stopTyping(second)
|
||||
assertNull(DualScreenPanel.typing)
|
||||
}
|
||||
|
||||
@Test fun triggersStepThroughSections() {
|
||||
assertEquals(-1, dualPageStep(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_L2)))
|
||||
assertEquals(1, dualPageStep(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_R2)))
|
||||
assertNull(dualPageStep(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_L1)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import com.droiddeck.launcher.input.JoyConPadTest
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.nio.file.Files
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
|
||||
shadows = [JoyConPadTest.RecordingWriter::class])
|
||||
class DeckControlsPanelTest {
|
||||
@Test fun takesTouchAtMatchesWhatATouchDoes() {
|
||||
val directory = Files.createTempDirectory("deck-panel").toFile()
|
||||
try {
|
||||
SessionState.deckPad = false
|
||||
// No pad: the Deck layouts (trackpads, grips). A pad without Deck controls: the gamepad layout
|
||||
// (sticks, d-pad, face buttons).
|
||||
for (pad in listOf(null, PadBridge(directory))) for (portraitDock in listOf(false, true)) {
|
||||
val name = "pad=${pad != null} portraitDock=$portraitDock"
|
||||
val panel = DeckControlsPanel(RuntimeEnvironment.getApplication(), onClose = {}, onSteamMenu = {}, onQam = {},
|
||||
pad = pad, portraitDock = portraitDock)
|
||||
assertEquals(name, pad == null, panel.deckControls)
|
||||
// The portrait dock sits under a portrait game; its gamepad layout needs a tall panel.
|
||||
val (w, h) = if (portraitDock) 720 to 1000 else 1200 to 480
|
||||
panel.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY),
|
||||
View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY))
|
||||
panel.layout(0, 0, w, h)
|
||||
var taken = 0
|
||||
var missed = 0
|
||||
for (x in 0 until w step w / 40) for (y in 0 until h step h / 24) {
|
||||
val expected = panel.takesTouchAt(x.toFloat(), y.toFloat())
|
||||
val down = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, x.toFloat(), y.toFloat(), 0)
|
||||
assertEquals("$name ($x, $y)", expected, panel.dispatchTouchEvent(down))
|
||||
down.recycle()
|
||||
// Cancel rather than lift, so no button fires its action.
|
||||
MotionEvent.obtain(0L, 1L, MotionEvent.ACTION_CANCEL, x.toFloat(), y.toFloat(), 0).also { panel.dispatchTouchEvent(it); it.recycle() }
|
||||
if (expected) taken++ else missed++
|
||||
}
|
||||
assertTrue("$name: some points land on controls", taken > 0)
|
||||
assertTrue("$name: some points land between them", missed > 0)
|
||||
}
|
||||
} finally {
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class DualScreenPanelOwnerTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@After fun clear() = DualScreenPanel.hide()
|
||||
|
||||
@Test fun aLauncherThatStopsLeavesThePanelOfTheOneThatTookItOver() {
|
||||
DualScreenPanel.show(app, 2, 10)
|
||||
DualScreenPanel.show(app, 2, 11)
|
||||
DualScreenPanel.hide(10)
|
||||
assertEquals(2, DualScreenPanel.shownOn)
|
||||
DualScreenPanel.hide(11)
|
||||
assertEquals(-1, DualScreenPanel.shownOn)
|
||||
}
|
||||
|
||||
@Test fun theOwnerHidesItsOwnPanel() {
|
||||
DualScreenPanel.show(app, 2, 10)
|
||||
DualScreenPanel.hide(10)
|
||||
assertEquals(-1, DualScreenPanel.shownOn)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Application
|
||||
import android.content.res.Configuration
|
||||
import android.hardware.input.InputManager
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.input.PadBridgeRoutingTest
|
||||
import com.droiddeck.launcher.input.PhysicalShortcuts
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.InputDeviceBuilder
|
||||
import org.robolectric.shadows.ShadowDialog
|
||||
import java.util.Locale
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], application = Application::class, qualifiers = "w960dp-h640dp-land",
|
||||
shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
|
||||
class PhysicalShortcutsDialogTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private lateinit var device: InputDevice
|
||||
|
||||
@Before fun setUp() {
|
||||
context.getSharedPreferences("controller", 0).edit().clear().commit()
|
||||
device = InputDeviceBuilder.newBuilder().setId(10).setName("Retroid extra buttons")
|
||||
.setDescriptor("retroid-extra").setSources(InputDevice.SOURCE_KEYBOARD)
|
||||
.setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC)
|
||||
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build()
|
||||
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
|
||||
}
|
||||
|
||||
@Test fun assignmentSavesAutomaticallyOnRelease() {
|
||||
var changes = 0
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows(onChanged = { changes++ }) } }
|
||||
assign(PhysicalShortcuts.Action.STEAM)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
|
||||
compose.onNodeWithText(context.getString(R.string.shortcuts_release)).assertExists()
|
||||
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
|
||||
assertTrue(PhysicalShortcuts.read(context).isEmpty())
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
|
||||
compose.runOnIdle {
|
||||
val binding = PhysicalShortcuts.read(context).single()
|
||||
assertEquals(KeyEvent.KEYCODE_F1, binding.button.keyCode)
|
||||
assertEquals(PhysicalShortcuts.Action.STEAM, binding.action)
|
||||
assertEquals(1, changes)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun inputSettingsPageOpensPhysicalShortcutAssignments() {
|
||||
compose.setContent {
|
||||
DroidDeckTheme { InputSettingsPage(onBack = {}) }
|
||||
}
|
||||
compose.onNodeWithTag("shortcuts-assign-STEAM").assertExists()
|
||||
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
|
||||
compose.onNodeWithTag("shortcuts-assign-DROIDDECK").assertExists()
|
||||
}
|
||||
|
||||
@Test fun backCancelsCaptureWithoutSaving() {
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.QAM)
|
||||
send(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_DOWN)
|
||||
compose.onNodeWithTag("shortcuts-cancel").assertDoesNotExist()
|
||||
compose.runOnIdle {
|
||||
assertTrue(PhysicalShortcuts.read(context).isEmpty())
|
||||
}
|
||||
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
|
||||
}
|
||||
|
||||
@Test fun controllerBCancelsCaptureWithoutSaving() {
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.QAM)
|
||||
send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_DOWN)
|
||||
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
|
||||
assertTrue(PhysicalShortcuts.read(context).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun closingConflictKeepsBothPreviousAssignments() {
|
||||
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))),
|
||||
PhysicalShortcuts.Action.STEAM)
|
||||
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))),
|
||||
PhysicalShortcuts.Action.QAM)
|
||||
val previous = PhysicalShortcuts.read(context)
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.QAM)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithTag("shortcuts-save").assertExists()
|
||||
compose.onNodeWithTag("shortcuts-cancel").performScrollTo().performClick()
|
||||
assertEquals(previous, PhysicalShortcuts.read(context))
|
||||
}
|
||||
|
||||
@Test fun conflictingAssignmentIsNotReplacedUntilSave() {
|
||||
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))),
|
||||
PhysicalShortcuts.Action.STEAM)
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.QAM)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithText(context.getString(R.string.shortcuts_conflict,
|
||||
context.getString(R.string.drawer_steam_menu))).assertExists()
|
||||
val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)))
|
||||
compose.onAllNodesWithText("${button.label} · ${button.name}").assertCountEquals(2)
|
||||
assertEquals(PhysicalShortcuts.Action.STEAM, PhysicalShortcuts.read(context).single().action)
|
||||
compose.onNodeWithTag("shortcuts-save").performScrollTo().performClick()
|
||||
compose.runOnIdle { assertEquals(PhysicalShortcuts.Action.QAM, PhysicalShortcuts.read(context).single().action) }
|
||||
}
|
||||
|
||||
@Test fun removalRestoresDefaultAndPreservesOtherAssignmentsAndControllerSettings() {
|
||||
ControllerPrefs.setSelectSteam(context, true)
|
||||
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))),
|
||||
PhysicalShortcuts.Action.STEAM)
|
||||
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))),
|
||||
PhysicalShortcuts.Action.QAM)
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.STEAM)
|
||||
send(KeyEvent.KEYCODE_F3, KeyEvent.ACTION_DOWN)
|
||||
compose.onNodeWithTag("shortcuts-remove").performScrollTo().performClick()
|
||||
compose.runOnIdle {
|
||||
assertEquals(PhysicalShortcuts.Action.QAM, PhysicalShortcuts.read(context).single().action)
|
||||
assertTrue(ControllerPrefs.read(context).selectSteam)
|
||||
}
|
||||
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.game_settings_default))
|
||||
}
|
||||
|
||||
@Test fun retryRecoversFromAMissingReleaseWithoutSavingTheOldButton() {
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.STEAM)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
|
||||
compose.onNodeWithTag("shortcuts-retry").performScrollTo().performClick()
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
|
||||
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
|
||||
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
|
||||
val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN)))
|
||||
compose.onNodeWithText("${button.label} · ${button.name}").assertExists()
|
||||
compose.runOnIdle { assertEquals(KeyEvent.KEYCODE_F2, PhysicalShortcuts.read(context).single().button.keyCode) }
|
||||
}
|
||||
|
||||
@Test fun longControllerNameDoesNotSqueezeTheMenuLabelInANarrowDrawer() {
|
||||
val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.ACTION_DOWN)))
|
||||
.copy(name = "Xbox Wireless Controller with a long device name")
|
||||
PhysicalShortcuts.assign(context, button, PhysicalShortcuts.Action.STEAM)
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
Box(Modifier.width(360.dp)) { PhysicalShortcutRows() }
|
||||
}
|
||||
}
|
||||
val control = compose.onNodeWithTag("shortcuts-assign-STEAM").getUnclippedBoundsInRoot()
|
||||
val label = compose.onNodeWithText(context.getString(R.string.drawer_steam_menu)).getUnclippedBoundsInRoot()
|
||||
assertTrue(control.right - control.left < 200.dp)
|
||||
assertTrue("Menu label must not wrap vertically: $label", label.bottom - label.top <= 48.dp)
|
||||
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.ctrl_custom))
|
||||
compose.onNodeWithText("${button.label} · ${button.name}").assertExists()
|
||||
}
|
||||
|
||||
@Test fun replacingSameActionsButtonSavesWithoutConfirmation() {
|
||||
val oldButton = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)))
|
||||
PhysicalShortcuts.assign(context, oldButton, PhysicalShortcuts.Action.STEAM)
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.STEAM)
|
||||
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN)
|
||||
assertEquals(oldButton, PhysicalShortcuts.read(context).single().button)
|
||||
send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
|
||||
compose.runOnIdle { assertEquals(KeyEvent.KEYCODE_F2, PhysicalShortcuts.read(context).single().button.keyCode) }
|
||||
}
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "de-rDE-w400dp-h850dp-port")
|
||||
fun narrowLargeTextKeepsTranslatedCaptureReachableAndSavesOnRelease() {
|
||||
compose.setContent {
|
||||
val density = LocalDensity.current
|
||||
CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale = 1.5f)) {
|
||||
DroidDeckTheme { PhysicalShortcutRows() }
|
||||
}
|
||||
}
|
||||
assign(PhysicalShortcuts.Action.DROIDDECK)
|
||||
compose.onNodeWithText(context.getString(R.string.shortcuts_capture,
|
||||
context.getString(R.string.shortcuts_dd_menu))).assertExists()
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
|
||||
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
|
||||
compose.onNodeWithTag("shortcuts-save").assertDoesNotExist()
|
||||
compose.runOnIdle { assertEquals(PhysicalShortcuts.Action.DROIDDECK, PhysicalShortcuts.read(context).single().action) }
|
||||
}
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "ar-rEG-w400dp-h850dp-port")
|
||||
fun rightToLeftDialogKeepsCancelReachable() {
|
||||
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
|
||||
assign(PhysicalShortcuts.Action.QAM)
|
||||
compose.onNodeWithTag("shortcuts-cancel").performScrollTo().assertIsDisplayed().performClick()
|
||||
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
|
||||
}
|
||||
|
||||
@Test fun everySupportedLanguageHasALocalizedShortcutTitleAndValidFormatArguments() {
|
||||
val languages = mutableListOf<String>()
|
||||
context.resources.getXml(R.xml.locales_config).use { xml ->
|
||||
while (xml.next() != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {
|
||||
if (xml.eventType == org.xmlpull.v1.XmlPullParser.START_TAG && xml.name == "locale") {
|
||||
languages.add(xml.getAttributeValue("http://schemas.android.com/apk/res/android", "name"))
|
||||
}
|
||||
}
|
||||
}
|
||||
val english = context.getString(R.string.shortcuts_title)
|
||||
for (language in languages) {
|
||||
val config = Configuration(context.resources.configuration).apply { setLocale(Locale.forLanguageTag(language)) }
|
||||
val localized = context.createConfigurationContext(config)
|
||||
if (language != "en") assertNotEquals(language, english, localized.getString(R.string.shortcuts_title))
|
||||
assertTrue(localized.getString(R.string.shortcuts_capture, "ACTION").contains("ACTION"))
|
||||
assertTrue(localized.getString(R.string.shortcuts_conflict, "ACTION").contains("ACTION"))
|
||||
val detected = localized.getString(R.string.shortcuts_detected, "DEVICE", "BUTTON")
|
||||
assertTrue(detected.contains("DEVICE"))
|
||||
assertTrue(detected.contains("BUTTON"))
|
||||
}
|
||||
}
|
||||
|
||||
private fun assign(action: PhysicalShortcuts.Action) {
|
||||
compose.onNodeWithTag("shortcuts-assign-${action.name}").performClick()
|
||||
}
|
||||
|
||||
private fun send(code: Int, action: Int) {
|
||||
compose.runOnIdle {
|
||||
assertTrue(ShadowDialog.getLatestDialog().window!!.callback.dispatchKeyEvent(event(code, action)))
|
||||
}
|
||||
compose.waitForIdle()
|
||||
}
|
||||
|
||||
private fun event(code: Int, action: Int) =
|
||||
KeyEvent(100L, 100L, action, code, 0, 0, device.id, 700, 0, InputDevice.SOURCE_KEYBOARD)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
|
||||
fun createRobolectricComposeRule() = createComposeRule().also {
|
||||
RingVeil.reset()
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
shadowOf(context.packageManager).addActivityIfNotPresent(
|
||||
ComponentName(context, ComponentActivity::class.java),
|
||||
|
||||
@@ -19,7 +19,8 @@ class SessionDrawerPageTest {
|
||||
assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1))
|
||||
assertEquals(sessionDrawerPages(false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN })
|
||||
for (pages in listOf(connected, sessionDrawerPages(false))) {
|
||||
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.DISPLAY, 1))
|
||||
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
|
||||
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
|
||||
|
||||
@@ -8,7 +8,7 @@ import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import android.widget.TextView
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.semantics.SemanticsProperties.StateDescription
|
||||
import androidx.compose.runtime.MutableState
|
||||
@@ -103,6 +103,28 @@ class SessionSecondScreenTest {
|
||||
} finally { panel.closeControls() }
|
||||
}
|
||||
|
||||
@Test fun trackpadMenuButtonOnlyAppearsWhenTheMenuCanMove() {
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
|
||||
val label = context.getString(R.string.touch_droiddeck_menu)
|
||||
for (movable in listOf(false, true)) {
|
||||
var menus = 0
|
||||
val panel = SecondScreenPresentation(activity, display, { _, _, _, _ -> }, { _, _ -> }, {},
|
||||
{}, {}, {}, onMenu = if (movable) ({ menus++ }) else null)
|
||||
try {
|
||||
panel.create()
|
||||
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
|
||||
val buttons = descendants(panel.window!!.decorView).filter { it.contentDescription == label }.toList()
|
||||
assertEquals(if (movable) 1 else 0, buttons.size)
|
||||
buttons.forEach { it.performClick() }
|
||||
assertEquals(if (movable) 1 else 0, menus)
|
||||
} finally {
|
||||
panel.closeControls()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
|
||||
fun controllerBumpersReachTheSecondScreenInBothSessionModes() {
|
||||
@@ -113,7 +135,7 @@ class SessionSecondScreenTest {
|
||||
SessionState.mode = mode
|
||||
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
fun <T> state(name: String): MutableState<T> = ReflectionHelpers.getField(activity, "$name\$delegate")
|
||||
state<Boolean>("drawerOpen").value = true
|
||||
state<Boolean>("drawerOpenState").value = true
|
||||
state<Boolean>("drawerControllerActive").value = true
|
||||
state<List<SecondScreenDisplay>>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen"))
|
||||
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN,
|
||||
@@ -133,7 +155,7 @@ class SessionSecondScreenTest {
|
||||
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
|
||||
SessionState.mode = SessionService.MODE_STEAM
|
||||
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
val open: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerOpen\$delegate")
|
||||
val open: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerOpenState\$delegate")
|
||||
val controller: MutableState<Boolean> = ReflectionHelpers.getField(activity, "drawerControllerActive\$delegate")
|
||||
controller.value = true
|
||||
for (button in listOf(KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_START)) {
|
||||
@@ -215,9 +237,9 @@ class SessionSecondScreenTest {
|
||||
try {
|
||||
panel.create()
|
||||
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
|
||||
val buttons = descendants(panel.window!!.decorView).filterIsInstance<Button>().toList()
|
||||
val buttons = descendants(panel.window!!.decorView).filterIsInstance<TextView>().filter { it.isClickable }.toList()
|
||||
assertTrue(buttons.any { it.text == context.getString(R.string.second_show_keyboard) })
|
||||
val shortcuts = buttons.filter { it.text == "STEAM" || it.text == "…" }
|
||||
val shortcuts = buttons.filter { it.text == "STEAM" || it.text == "•••" }
|
||||
if (steam) {
|
||||
assertEquals(2, shortcuts.size)
|
||||
shortcuts.forEach { it.performClick() }
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
Generation 1 fixtures from GOG's public Rayman 2 repository, timestamp 31847977,
|
||||
retrieved 2026-10-28. The repository and Neutral depot are complete. The English
|
||||
depot is an excerpt containing its first three original file entries.
|
||||
|
||||
https://gog-cdn-fastly.gog.com/content-system/v1/manifests/1207658940/windows/31847977/repository.json
|
||||
|
||||
The fixtures retain provider paths, support flags, range offsets, and original
|
||||
hexadecimal hashes. They contain no game payload, credentials, or signed links.
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"version": 1,
|
||||
"depot": {
|
||||
"name": "Rayman 2 - The Great Escape",
|
||||
"files": [
|
||||
{
|
||||
"offset": 384206096,
|
||||
"hash": "a08070ecde7f746779259f7ce5775747",
|
||||
"url": "1207658940/main.bin",
|
||||
"path": "/Data/World/Levels/Raycap/Raycap.snd",
|
||||
"size": 32
|
||||
},
|
||||
{
|
||||
"offset": 114255832,
|
||||
"hash": "67165fe729ffda351a04e8bd92e05531",
|
||||
"url": "1207658940/main.bin",
|
||||
"path": "/Data/World/Sound/Bnk_29.bnm",
|
||||
"size": 76
|
||||
},
|
||||
{
|
||||
"offset": 97474601,
|
||||
"hash": "2d2e0b308cae5ff44a620fd32bf6cb4d",
|
||||
"url": "1207658940/main.bin",
|
||||
"path": "/Data/World/Sound/Bnk_43.bnm",
|
||||
"size": 76
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"version": 1,
|
||||
"depot": {
|
||||
"name": "Rayman 2 - The Great Escape",
|
||||
"files": [
|
||||
{
|
||||
"offset": 0,
|
||||
"path": "1207658940/galaxy_rayman2_2.1.0.39.exe",
|
||||
"size": 1258944,
|
||||
"support": true,
|
||||
"hash": "ee2c247373733f29782395f1f92622f6",
|
||||
"url": "1207658940/main.bin"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"product": {
|
||||
"timestamp": 31847977,
|
||||
"depots": [
|
||||
{
|
||||
"languages": [
|
||||
"Neutral"
|
||||
],
|
||||
"size": "1258944",
|
||||
"gameIDs": [
|
||||
"1207658940"
|
||||
],
|
||||
"systems": [
|
||||
"Windows"
|
||||
],
|
||||
"manifest": "a01f6fb8-55a8-4f33-bc5b-5f5d2f591775.json"
|
||||
},
|
||||
{
|
||||
"languages": [
|
||||
"English"
|
||||
],
|
||||
"size": "505011865",
|
||||
"gameIDs": [
|
||||
"1207658940"
|
||||
],
|
||||
"systems": [
|
||||
"Windows"
|
||||
],
|
||||
"manifest": "ec88140c-2589-41a0-bbf3-8fc1f215fe5a.json"
|
||||
},
|
||||
{
|
||||
"redist": "nGlide",
|
||||
"size": "0",
|
||||
"targetDir": "/"
|
||||
}
|
||||
],
|
||||
"support_commands": [
|
||||
{
|
||||
"languages": [
|
||||
"Neutral"
|
||||
],
|
||||
"executable": "/galaxy_rayman2_2.1.0.39.exe",
|
||||
"gameID": "1207658940",
|
||||
"argument": "",
|
||||
"systems": [
|
||||
"Windows"
|
||||
]
|
||||
}
|
||||
],
|
||||
"installDirectory": "Rayman 2",
|
||||
"rootGameID": "1207658940",
|
||||
"gameIDs": [
|
||||
{
|
||||
"gameID": "1207658940",
|
||||
"name": {
|
||||
"en": "Rayman 2 - The Great Escape"
|
||||
},
|
||||
"dependencies": [],
|
||||
"standalone": true
|
||||
}
|
||||
],
|
||||
"projectName": "Rayman 2 - The Great Escape"
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
Reference in new issue
Block a user