Merge latest origin/main and resolve conflicts

This commit is contained in:
DroidDeck Merge committed 2026-11-02 10:44:24 +08:00
commit 8171bf20fd
581 files changed
+14773 -4227

No files matched your search

@@ -1,4 +1,3 @@
// Compile with the installed SDK's headers to verify the two mode vocabularies.
#include "viture_protocol_public.h"
#include "../../main/cpp/viture/display_modes.h"
using namespace droiddeck::viture;
@@ -17,11 +17,6 @@ import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
/**
* A download that was cut off keeps its bytes, and a second call with `resume` asks for the rest
* with a Range header instead of starting again. The server is a plain socket so the first answer
* can promise the whole file and then hang up halfway.
*/
class DownloaderResumeTest {
private val data = ByteArray(300_000) { (it % 251).toByte() }
private val cutAt = 100_000
@@ -43,11 +38,9 @@ class DownloaderResumeTest {
try {
while (!server.isClosed) {
val socket = server.accept()
// the client may hang up on a body it refuses; that must not stop the server
runCatching { handle(socket) }
}
} catch (_: Exception) {
// closed by tearDown
}
}.apply { isDaemon = true; start() }
}
@@ -72,7 +65,6 @@ class DownloaderResumeTest {
val content = if (corrupt && "/corrupt" in path) ByteArray(data.size) else data
val from = range?.removePrefix("bytes=")?.substringBefore('-')?.toIntOrNull()
if (misbehave) {
// answers a Range request with a 206 that starts at 0, and serves plain requests whole
val start = if (from == null) "200 OK" else "206 Partial Content"
val extra = if (from == null) "" else "Content-Range: bytes 0-${data.size - 1}/${data.size}\r\n"
out.write("HTTP/1.1 $start\r\n${extra}${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
@@ -89,7 +81,6 @@ class DownloaderResumeTest {
out.write("HTTP/1.1 200 OK\r\n${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray())
out.write(content, 0, cutAt)
out.flush()
// hang up with most of the promised body still unsent
} else {
val rest = data.size - from
out.write(("HTTP/1.1 206 Partial Content\r\nContent-Range: bytes $from-${data.size - 1}/${data.size}\r\n" +
@@ -187,7 +178,6 @@ class DownloaderResumeTest {
val target = File(dir, "runtime.tar.zst")
misbehave = true
val polls = java.util.concurrent.atomic.AtomicInteger()
// candidate selection and attempt each check once before the request; later checks follow chunks
val cancelled = java.util.function.BooleanSupplier { polls.incrementAndGet() > 2 }
assertFalse(Downloader.downloadCandidates(first, listOf(first, second), target, true, null, cancelled, null))
assertEquals("a cancel must not fall back to the next source", listOf<String?>(null), requests.toList())
@@ -93,7 +93,6 @@ class GlassesDisplayTest {
@Test fun gtMaxSmartGlassesEdidUsesTheSameOutputSelectionAsViture() {
val panel = display("SmartGlasses", productName = "SmartGlasses", productId = "980")
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = true)?.displayId)
// The display remains usable while USB control reconnects during a mode switch.
assertEquals(panel.displayId, Glasses.selectGlassesDisplay(listOf(panel), usbPresent = false)?.displayId)
}
@@ -126,7 +125,6 @@ class GlassesDisplayTest {
}
}
// Robolectric exposes display names and flags, but has no product-metadata setter.
@Implements(Display::class)
class ProductMetadataDisplay : ShadowDisplay() {
var productMetadata: DeviceProductInfo? = null
@@ -63,7 +63,6 @@ class GlassesMenuProjectionTest {
private object GlassesMenuProjection {
data class Uv(val x: Float, val y: Float)
// Row-major head-to-anchor rotation; +Y is up, -Z is forward, output UV starts at the top left.
fun intersect(frame: GlassesMenuPose.Frame, rayX: Float, rayY: Float, eye: Float,
halfWidth: Float, distance: Float, aspect: Float): Uv? {
if (frame.rotation.size != 9 || frame.position.size != 3 || frame.rotation.any { !it.isFinite() } ||
@@ -30,7 +30,6 @@ class GlassesOutputHandoffTest {
private lateinit var screen: GlassesScreen
@Before fun setup() {
// Exercise the output lifecycle without starting the native Linux runtime.
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
phone = SurfaceView(activity)
ReflectionHelpers.setField(activity, "surfaceView", phone)
@@ -46,7 +45,7 @@ class GlassesOutputHandoffTest {
@Test fun selectingGlassesDoesNotHidePhoneOrClaimOutputBeforeAttachment() {
assertFalse(active())
assertEquals(View.VISIBLE, phone.visibility)
attach(phone.holder) // A late phone callback must not complete the handoff.
attach(phone.holder)
assertFalse(active())
assertEquals(View.VISIBLE, phone.visibility)
}
@@ -183,11 +183,11 @@ class GlassesRenderingTest {
picture3d = GlassesSettings.PICTURE_SCREEN)
for (state in listOf(ultra.copy(displayId = -1), GlassesState())) {
val preview = GlassesRendering.cardboard(base, settings, state, false, true)
assertTrue(preview.enabled) // Published as headset proximity, preventing standby.
assertTrue(preview.enabled)
assertTrue(preview.mono)
assertEquals(Cardboard.SOURCE_SBS, preview.source)
assertEquals(Cardboard.Viewer.NONE.id, preview.viewer)
assertTrue(preview.headTracking) // Phone preference, not dormant glasses settings.
assertTrue(preview.headTracking)
assertFalse(base.enabled)
assertSame(base, GlassesRendering.cardboard(base, settings, state, false, false))
}
@@ -251,8 +251,6 @@ class GlassesSteamVrTest {
.set(activity, LoadingState(activity).apply { visible = false })
SessionState.steamVr = true
SessionState.mode = SessionService.MODE_STEAM
// Hold the external worker so status transitions can be exercised
// without launching a Linux runtime from the host test process.
val worker = SessionActivity::class.java.getDeclaredField("steamVrWorker")
.apply { isAccessible = true }.get(null) as ThreadPoolExecutor
val blocked = CountDownLatch(1)
@@ -115,8 +115,6 @@ class RayNeoCalibrationTest {
val upright = RayNeoOrientationFilter(profile.rotationXDeg, profile.gtMaxAxes, saved)
.update(sample(floatArrayOf(-0.02f, 8.819f, 4.106f), reading.gyroDps))
assertArrayEquals(floatArrayOf(1f, 0f, 0f, 0f), upright, 0.001f)
// This was the reported failure: the same physical pose cannot calibrate
// through the Max's permutation and 35-degree mounting correction.
assertNull(finish(RayNeoCalibrationCollector(RayNeoSensorAxes(35f, true), 0), sample = reading))
}
@@ -102,7 +102,6 @@ class RayNeoLinkTest {
val cmd = bytes[1].toInt() and 0xff
commands += cmd
if (gtTraffic && cmd in listOf(0, 1)) {
// Notifications and unrelated ACKs can precede the requested response.
for (other in listOf(0x08, 6, 7, 0x50)) {
responses += ByteArray(64).apply {
this[0] = 0x99.toByte(); this[1] = 0xc8.toByte(); this[2] = 64
@@ -79,8 +79,6 @@ class RayNeoOrientationFilterTest {
val first = screen(filter.update(sample(0, level)))
val ref = HeadPose.recenter(first)
var q = FloatArray(4)
// Physical 30-degree turn over one second, through the complete shared
// VITURE conversion and recenter pipeline. GT signs match device captures.
repeat(100) { i ->
val a = Math.toRadians((i + 1) * 0.3)
val accel = when (axis) {
@@ -116,7 +116,7 @@ class RayNeoProtocolTest {
@Test fun tickWrapDoesNotIntroduceOrientationJump() {
val filter = RayNeoOrientationFilter(0f)
filter.update(sample(0xfffffff0L, 90f))
val q = filter.update(sample(84, 90f)) // 100 ticks = 10ms across uint32 rollover.
val q = filter.update(sample(84, 90f))
assertEquals(kotlin.math.sin(Math.PI * 0.005).toFloat(), q[2], 1e-4f)
}
}
@@ -71,8 +71,8 @@ class VitureSdkTest {
val s = kotlin.math.sin(Math.PI / 12).toFloat()
val c = kotlin.math.cos(Math.PI / 12).toFloat()
for ((axis, expected) in listOf(
2 to floatArrayOf(-0.5f, 0f, -0.8660254f), // Observed left turn: positive Y.
1 to floatArrayOf(0f, 0.5f, -0.8660254f), // Observed upward look: positive X.
2 to floatArrayOf(-0.5f, 0f, -0.8660254f),
1 to floatArrayOf(0f, 0.5f, -0.8660254f),
3 to floatArrayOf(-0.5f, 0.8660254f, 0f),
)) {
val q = floatArrayOf(c, 0f, 0f, 0f).apply { this[axis] = s }
@@ -84,7 +84,6 @@ class VitureSdkTest {
@Test fun ultraOpenGlAxesMatchExistingGlassesHeadTracker() {
val a = sqrt(0.5f)
// OpenGL Y yaw maps to NWU Z; OpenGL X pitch maps to negative NWU Y.
assertArrayEquals(floatArrayOf(0f, 0f, a, a),
VitureSdkPose.toGlasses(floatArrayOf(a, 0f, a, 0f), true), 0.00001f)
assertArrayEquals(floatArrayOf(0f, -a, 0f, a),
@@ -1,5 +1,4 @@
// Fixtures adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
// Fixtures adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick. Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
package com.droiddeck.launcher.glasses
import org.junit.Assert.assertArrayEquals
@@ -63,10 +63,8 @@ class XrealOrientationFilterTest {
@Test fun capturedNeutralGravityStartsUprightBeforeRecenter() {
val pose = XrealOrientationFilter().update(sample(1000000,
accel = Vec3(-0.0909f, -9.6529f, -1.0731f)))!!
// An upright start must not contain the previous approximately 180-degree
// pitch correction. Check before recenter can hide a mounting error.
assertTrue(kotlin.math.abs(pose[3]) > 0.99f)
val screen = matrix(pose)
assertTrue(screen[7] > 0.99f) // Screen up points toward shared world +Z.
assertTrue(screen[7] > 0.99f)
}
}
@@ -93,7 +93,6 @@ class XrealProtocolTest {
assertEquals(0x2822, XrealProtocol.read(requests).command)
repeat(3) { assertEquals(0x275e, XrealProtocol.read(requests).command) }
assertEquals(0, requests.available())
// Actual 1S busy response remains an error, never a successful ack.
assertFalse(XrealProtocol.acknowledged(byteArrayOf(0x22, 3, 8, 0x89.toByte(), 0x27)))
}
@@ -111,6 +111,9 @@ class DriverPairsTest {
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(840), pairs))
assertEquals("other 8xx keep WinNative", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), pairs))
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), pairs))
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs))
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(740), pairs))
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(722), pairs))
assertEquals(DriverPairs.BANNER_ONEUI, DriverPairs.recommendedKey(gpu(740, oneUi = true), pairs))
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), pairs))
}
}
@@ -28,7 +28,6 @@ class GpuDetectionTest {
}
@Test fun nonAdrenoRenderersAreNeverAdrenoWhateverNumberTheyCarry() {
// Xclipse (Exynos), Mali and Immortalis names; familyOf ignores the number off Adreno.
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Samsung Xclipse 920")))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, GpuInfo.threeDigits("Xclipse 940")))
@@ -17,7 +17,7 @@ class SteamVrDeviceLossLogTest {
assertFalse(log.poll())
file.appendText("-4\n")
assertTrue(log.poll())
assertTrue(log.poll()) // Keep pending until the activity is foreground.
assertTrue(log.poll())
}
@Test fun onlyExplicitDeviceLossTriggersRecovery() {
@@ -8,7 +8,6 @@ import org.junit.Test
import kotlin.random.Random
class FrameStatsTest {
/** MangoHud's update_hud_info_with_frametime and fps()/frame_timing(), line by line (overlay.cpp). */
private class Mango {
val frametimeData = ArrayList<Float>(List(200) { 0f })
var lastPresentTime = 0L
@@ -69,6 +68,30 @@ class FrameStatsTest {
assertFalse(feed.poll(now + 1))
}
@Test fun slowFramesCountOnlyFramesOver33MsInTheWindow() {
val stats = FrameStats()
var now = 1_000_000_000L
for (ft in listOf(16_666_667L, 40_000_000L, 16_666_667L, 50_000_000L, 2_000_000_000L, 16_666_667L)) {
now += ft
stats.add(ft, now)
}
assertEquals(2, stats.slowFrames(now, 60_000_000_000L))
assertEquals(0, stats.slowFrames(now + 120_000_000_000L, 60_000_000_000L))
stats.reset()
assertEquals(0, stats.slowFrames(now, 60_000_000_000L))
}
@Test fun compositorFramesDoNotCountAsLiveGamescopeFrames() {
val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames"))
var now = 1_000_000_000L
assertFalse(feed.live)
feed.onCompositorFrame(now)
now += 16_666_667L
feed.onCompositorFrame(now)
feed.poll(now)
assertFalse(feed.live)
}
@Test fun aCompletedPeriodIsCountedWhenMangoHudWouldRedraw() {
val stats = FrameStats()
var now = 1_000_000_000L
@@ -18,12 +18,10 @@ class MangoReadingsTest {
@Test fun cpuLoadFollowsMangoHudsFormulaAndTruncates() {
val stat = File(tmp.root, "stat")
val m = readings()
// user nice system idle iowait irq softirq steal guest guest_nice
stat.writeText("cpu 1000 100 500 8000 400 50 50 0 200 0\ncpu0 500 50 250 4000 200 25 25 0 100 0\ncpu1 500 50 250 4000 200 25 25 0 100 0\nintr 0\n")
m.cpu(stat)
stat.writeText("cpu 1500 100 700 8600 500 60 70 10 300 0\ncpu0 900 50 400 4100 250 30 35 10 200 0\ncpu1 600 50 300 4500 250 30 35 0 100 0\nintr 0\n")
val cpu = m.cpu(stat)!!
// busy = user-guest 400 + nice 0 + system+irq+softirq 230 + steal 10 + guest 100 = 740 of 1440 (idle+iowait 700)
assertEquals((740 * 100f / 1440).toInt(), cpu.percent)
assertEquals(51, cpu.percent)
assertArrayEquals(intArrayOf(((300 + 165 + 10 + 100) * 100f / (300 + 165 + 10 + 100 + 150)).toInt(), ((100 + 65) * 100f / (100 + 65 + 550)).toInt()), cpu.perCore)
@@ -240,6 +240,30 @@ class BackQamInputTest {
assertTrue(taps.isEmpty())
}
@Test fun withHoldsOffTapsStillWorkButHoldsAndChordsDoNothing() {
val noHold = BackQamInput(changes::add, taps::add, holds = { false })
fun press(action: Int) = noHold.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
advance(500)
assertEquals(listOf(false), taps)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
assertEquals(listOf(false, true), taps)
taps.clear()
press(KeyEvent.ACTION_DOWN)
advance(2000)
assertTrue(press(KeyEvent.ACTION_UP))
press(KeyEvent.ACTION_DOWN)
noHold.onChordInput()
press(KeyEvent.ACTION_UP)
advance(1000)
assertTrue(changes.isEmpty())
assertTrue(taps.isEmpty())
}
private fun advance(millis: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis))
private fun send(action: Int, repeat: Int = 0, device: Int = 4, enabled: Boolean = true) =
@@ -38,4 +38,15 @@ class SecondScreenModeTest {
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = false))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("dashboard", deckPad = false))
}
@Test fun theDesktopOpensAgainOnlyWhileItCanRun() {
assertEquals(SecondScreenMode.DESKTOP, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true, desktop = true))
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("desktop", deckPad = false))
}
@Test fun withNothingRememberedTheDesktopIsNeverPicked() {
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true, desktop = true))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false, desktop = true))
}
}
@@ -738,7 +738,7 @@ class TouchscreenGesturesTest {
@Test fun pinchReversalDoesNotConsumeOldDirectionRemainder() {
startPinch()
events.clear()
movePinch(4.5f) // Nine pixels toward zooming in, short of a step.
movePinch(4.5f)
assertTrue(events.none { it.startsWith("wheel") })
for (i in 1..10) movePinch(4.5f - i * .5f)
assertEquals(listOf("wheel 1"), events.filter { it.startsWith("wheel") })
@@ -794,16 +794,13 @@ class TouchscreenGesturesTest {
override fun moveTo(x: Float, y: Float) { cachedX = x; clientX = x }
override fun prepareRelativePan() { cachedX = 960f; clientX = 960f }
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {
// Before pointer lock, the compositor delivers an absolute
// position even when we inject a relative delta. The game
// only requests lock after seeing this first pan movement.
cachedX += dx
clientX = cachedX
}
override fun button(code: Int, down: Boolean) {
if (code == 274) {
middleDown = down
if (down) clientX = 960f // The client warps to the middle when pan starts.
if (down) clientX = 960f
}
}
override fun key(code: Int, down: Boolean) {}
@@ -29,7 +29,6 @@ class BootMovieLibraryTest {
private fun movie(name: String) = File(movies, name).also { it.parentFile!!.mkdirs(); it.writeText("movie") }
/** A movie DroidDeck itself imported: kept in the library, copied into Steam's folder and noted in the list. */
private fun imported(title: String, source: String = BootMovieLibrary.SOURCE_IMPORT, repo: String? = null): String {
val staged = File(BootMovieLibrary.libraryDir(app), ".t-${System.nanoTime()}-${Thread.currentThread().id}.staged").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
return BootMovieLibrary.commit(app, staged, title, source, repo)!!
@@ -258,11 +257,9 @@ class BootMovieLibraryTest {
steamPicks("b.webm")
assertTrue(BootMovie.syncFromSteam(app))
assertEquals("file:b.webm", BootMovie.choice(app))
// Picking another one here is not undone by the same Steam setting.
BootMovie.select(app, "file:a.webm")
assertFalse(BootMovie.syncFromSteam(app))
assertEquals("file:a.webm", BootMovie.choice(app))
// A new pick inside Steam is adopted again.
movie("c.webm")
steamPicks("c.webm")
assertTrue(BootMovie.syncFromSteam(app))
@@ -55,11 +55,9 @@ class ComponentsNightlyCatalogTest {
val nVkEc = item("DD-vkd3d-proton-arm64ec-3.0.1+455-nightly.wcp", "vkd3d", n)
val pairs = ComponentsManager.nightlyPairs(listOf(dxvk, ec, gpl, fex, vk) + others + listOf(nDxvk, nEc, nGpl, nFex, nVk, nVkEc))
assertEquals(mapOf(dxvk to nDxvk, ec to nEc, gpl to nGpl, fex to nFex, vk to nVk), pairs)
// Two nightlies for one stable build: the newer one wins.
val nDxvkNewer = item("DD-dxvk-3.1.1+154-nightly.wcp", "dxvk", n)
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvkNewer, nDxvk)))
assertEquals(mapOf(dxvk to nDxvkNewer), ComponentsManager.nightlyPairs(listOf(dxvk, nDxvk, nDxvkNewer)))
// A nightly of a version with no stable build pairs with nothing.
assertEquals(emptyMap<Any, Any>(), ComponentsManager.nightlyPairs(listOf(item("dxvk-3.1-linux.wcp", "dxvk", "Dxvk-Linux"), nDxvk)))
}
@@ -36,7 +36,6 @@ class ForcedPackageTest {
ComponentsManager.unpackedCacheKey(filename)
fail("Expected cache traversal name to be rejected: $filename")
} catch (_: IllegalArgumentException) {
// Expected: the derived path would be a dot segment.
}
}
}
@@ -16,12 +16,12 @@ class GameTelemetryTest {
@Test fun codemastersFloatsBecomeADash() {
val data = packet(264) {
putFloat(7 * 4, 25f) // m/s
putFloat(7 * 4, 25f)
putFloat(29 * 4, 0.8f)
putFloat(31 * 4, 0.1f)
putFloat(33 * 4, 3f)
putFloat(36 * 4, 1f)
putFloat(37 * 4, 650f) // rpm / 10
putFloat(37 * 4, 650f)
putFloat(63 * 4, 800f)
putFloat(45 * 4, 30f)
putFloat(46 * 4, 60f)
@@ -35,7 +35,6 @@ class GameTelemetryTest {
assertEquals(0.5f, t.fuel!!, 0.001f)
}
// Values from a DiRT Showdown packet recorded on a Retroid Pocket Duo (extradata 3 still sends 152 bytes there).
@Test fun codemastersShortPacketFromDirtShowdown() {
val data = packet(152) {
putFloat(1 * 4, 80.085f)
@@ -124,7 +123,6 @@ class GameTelemetryTest {
assertNull(GameTelemetry.parse(1234, ByteArray(400), 400))
}
// DiRT Showdown's 38 floats already carry steering and both G-forces.
@Test fun codemastersGForceAndSteering() {
val data = packet(152) {
putFloat(30 * 4, -0.5f)
@@ -181,7 +179,6 @@ class GameTelemetryTest {
assertEquals(GameTelemetry.DL_SHIFT or GameTelemetry.DL_ABS, t.lights)
}
// BeamNG leaves some OutGauge fields at zero; those stay hidden.
@Test fun outGaugeZeroFieldsStayHidden() {
val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, packet(92) { put(10, 2) }, 92)!!
assertNull(t.turboBar)
@@ -9,9 +9,7 @@ class GameThreadHintsTest {
@Test fun `a thread joins above 60 percent and leaves under 15`() {
assertEquals(emptySet<Int>(), GameThreadHints.pick(emptySet(), mapOf(1 to 0.55)))
assertEquals(setOf(1), GameThreadHints.pick(emptySet(), mapOf(1 to 0.68)))
// Faster where it was moved, or capped by the display, it stays boosted at 25%...
assertEquals(setOf(1), GameThreadHints.pick(setOf(1), mapOf(1 to 0.25)))
// ...and is let go once it idles.
assertEquals(emptySet<Int>(), GameThreadHints.pick(setOf(1), mapOf(1 to 0.1)))
}
@@ -28,8 +26,8 @@ class GameThreadHintsTest {
assertTrue(GameThreadHints.holdsPace(119.0, 120.0))
assertTrue(GameThreadHints.holdsPace(60.5, 120.0))
assertTrue(GameThreadHints.holdsPace(30.0, 120.0))
assertFalse(GameThreadHints.holdsPace(92.0, 120.0)) // falling behind: boost
assertFalse(GameThreadHints.holdsPace(92.0, 120.0))
assertFalse(GameThreadHints.holdsPace(105.0, 120.0))
assertFalse(GameThreadHints.holdsPace(3.0, 120.0)) // headless or loading: boost
assertFalse(GameThreadHints.holdsPace(3.0, 120.0))
}
}
@@ -0,0 +1,114 @@
package com.droiddeck.launcher.session
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class GpuLayerLoadTest {
@get:Rule val tmp = TemporaryFolder()
private var now = 0L
private fun load(dir: File) = GpuStatsComponent.LayerLoad(dir, clock = { now })
private fun write(dir: File, pid: Int, busyNs: Long) = File(dir, "$pid").writeText("%20d %-32s\n".format(busyNs, "game"))
@Test fun busyTimeOfAllProcessesOverWallTime() {
val dir = tmp.newFolder("gpu-load")
val load = load(dir)
write(dir, 100, 1_000_000_000L)
write(dir, 200, 5_000_000_000L)
now = 10_000_000_000L
assertNull(load.percent())
write(dir, 100, 1_300_000_000L)
write(dir, 200, 5_100_000_000L)
now += 1_000_000_000L
assertEquals(40L, load.percent())
}
@Test fun aNewProcessStartsFromItsOwnTotalAndAGoneOneStopsCounting() {
val dir = tmp.newFolder("gpu-load")
val load = load(dir)
write(dir, 100, 2_000_000_000L)
now = 1L
load.percent()
File(dir, "100").delete()
write(dir, 300, 9_000_000_000L)
now += 500_000_000L
assertEquals(0L, load.percent())
write(dir, 300, 9_250_000_000L)
now += 500_000_000L
assertEquals(50L, load.percent())
}
@Test fun capsAtFullAndIgnoresOtherFiles() {
val dir = tmp.newFolder("gpu-load")
val load = load(dir)
File(dir, "on").createNewFile()
write(dir, 1, 0L)
write(dir, 2, 0L)
now = 1L
load.percent()
write(dir, 1, 900_000_000L)
write(dir, 2, 900_000_000L)
now += 1_000_000_000L
assertEquals(100L, load.percent())
}
@Test fun theOnFlagFollowsTheHudAndHidingDropsTheBaseline() {
val dir = tmp.newFolder("gpu-load")
val load = load(dir)
load.wanted(true)
assertTrue(File(dir, "on").exists())
write(dir, 1, 100L)
now = 1L
load.percent()
load.wanted(false)
assertFalse(File(dir, "on").exists())
load.wanted(true)
now += 1_000L
assertNull(load.percent())
}
@Test fun theCompositorsOwnGpuTimeAddsToTheGames() {
val dir = tmp.newFolder("gpu-load")
var compositor: Long? = 7_000_000_000L
val load = GpuStatsComponent.LayerLoad(dir, clock = { now }, extra = { compositor })
write(dir, 100, 1_000_000_000L)
now = 1L
assertNull(load.percent())
write(dir, 100, 1_600_000_000L)
compositor = 7_150_000_000L
now += 1_000_000_000L
assertEquals(75L, load.percent())
compositor = null
write(dir, 100, 1_900_000_000L)
now += 1_000_000_000L
assertEquals(30L, load.percent())
}
@Test fun onlyTheCompositorCountsWhenNoGameReportsYet() {
val dir = File(tmp.root, "never-created")
var compositor = 0L
val load = GpuStatsComponent.LayerLoad(dir, clock = { now }, extra = { compositor })
now = 1L
load.percent()
compositor = 200_000_000L
now += 1_000_000_000L
assertEquals(20L, load.percent())
}
@Test fun compositorTimingFollowsTheHudOnlyOnChanges() {
val dir = tmp.newFolder("gpu-load")
val calls = mutableListOf<Boolean>()
val load = GpuStatsComponent.LayerLoad(dir, clock = { now }, onWanted = { calls += it })
load.wanted(true)
load.wanted(true)
load.wanted(false)
load.wanted(true)
load.clear()
assertEquals(listOf(true, false, true, false), calls)
}
}
@@ -0,0 +1,74 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class GpuMemstoreLoadTest {
private var busy = 0L
private var samples = 0L
private var moves = 0L
private var available = true
private val load = GpuStatsComponent.MemstoreLoad { if (available) longArrayOf(busy, samples, moves) else null }
private fun tick(newSamples: Long, newBusy: Long, newMoves: Long = 1) {
samples += newSamples
busy += newBusy
moves += newMoves
}
@Test fun notTrustedUntilNewWorkIsSeen() {
assertNull(load.percent())
tick(500, 400, newMoves = 0)
assertNull(load.percent())
assertFalse(load.working)
tick(500, 300)
assertEquals(70L, load.percent())
assertTrue(load.working)
}
@Test fun givesUpWhenTheTimestampsNeverMove() {
load.percent()
repeat(10) {
tick(500, 250, newMoves = 0)
assertNull(load.percent())
}
assertTrue(load.failed)
tick(500, 250)
assertNull(load.percent())
assertFalse(load.working)
}
@Test fun averagesOverTheLastTwoReads() {
load.percent()
tick(500, 500)
assertEquals(100L, load.percent())
tick(500, 0)
assertEquals(50L, load.percent())
tick(500, 0, newMoves = 0)
assertEquals(0L, load.percent())
}
@Test fun pausingStartsANewWindow() {
load.percent()
tick(500, 500)
load.percent()
load.pause()
tick(0, 0, newMoves = 0)
assertNull(load.percent())
tick(500, 100)
assertEquals(20L, load.percent())
}
@Test fun noReadingWithoutNewSamplesOrCounts() {
load.percent()
tick(500, 100)
load.percent()
assertNull(load.percent())
available = false
tick(500, 100)
assertNull(load.percent())
}
}
@@ -4,6 +4,8 @@ import org.junit.Assert.*
import org.junit.Test
class SessionDisplayTest {
private val scaledFollow = listOf("follow/1.5", "follow/2", "follow/2.5", "follow/3", "follow/4")
@Test fun portraitPresetsSwapTheOutputAndRetainTheResolutionCap() {
assertEquals(720 to 1280, SessionDisplay.resolveChoice(1920 to 1080, "720p", portrait = true))
assertEquals(900 to 1600, SessionDisplay.resolveChoice(1080 to 1920, "900p", portrait = true))
@@ -40,13 +42,13 @@ class SessionDisplayTest {
@Test fun optionsListTheHeightsThePanelCanShowThenThePanel() {
val thor = SessionDisplay.resolutionOptions(1920 to 1080)
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN), thor)
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN),
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow, thor)
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow,
SessionDisplay.resolutionOptions(2400 to 1080))
assertEquals(listOf("720p", "900p", "1080p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN),
assertEquals(listOf("720p", "900p", "1080p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow,
SessionDisplay.resolutionOptions(3120 to 1440))
val small = SessionDisplay.resolutionOptions(1280 to 720)
assertEquals(listOf(SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN), small)
assertEquals(listOf(SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN) + scaledFollow, small)
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, SessionDisplay.MATCH_SCREEN))
assertEquals(2560 to 1440, SessionDisplay.resolveChoice(2560 to 1440, SessionDisplay.MATCH_SCREEN))
}
@@ -105,6 +107,31 @@ class SessionDisplayTest {
assertNull(SessionDisplay.followSize(640, 360))
}
@Test fun scaledFollowDividesTheWindowAndStaysEven() {
assertEquals(1260 to 540, SessionDisplay.resolveChoice(1080 to 2520, "follow/2"))
assertEquals(540 to 1260, SessionDisplay.resolveChoice(2520 to 1080, "follow/2", portrait = true))
assertEquals(1092 to 984, SessionDisplay.followSize(2185, 1969, scale = 2f))
assertEquals(656 to 728, SessionDisplay.followSize(1968, 2184, scale = 3f))
assertNull(SessionDisplay.followSize(640, 360, scale = 2f))
assertEquals(720 to 1600, SessionDisplay.resolveChoice(2400 to 1080, "follow/1.5", portrait = true))
assertEquals(1600 to 720, SessionDisplay.resolveChoice(1080 to 2400, "follow/1.5"))
assertNull(SessionDisplay.followScale("follow/1.0"))
}
@Test fun onlyKnownFollowChoicesCountAsFollow() {
assertEquals(1f, SessionDisplay.followScale(SessionDisplay.FOLLOW_SCREEN))
assertEquals(3f, SessionDisplay.followScale("follow/3"))
assertEquals(1.3f, SessionDisplay.followScale("follow/1.3"))
assertEquals(1.3f, SessionDisplay.followScale("follow/1.26"))
assertEquals("follow/1.3", SessionDisplay.followScaled(1.3f))
assertEquals("follow/2", SessionDisplay.followScaled(2f))
assertNull(SessionDisplay.followScale("follow/1"))
assertNull(SessionDisplay.followScale("follow/x"))
assertNull(SessionDisplay.followScale("follow/9"))
assertNull(SessionDisplay.followScale("720p"))
assertFalse(SessionDisplay.isFollow(SessionDisplay.MATCH_SCREEN))
}
@Test fun aPhoneCanFollowTheShortGameAreaAboveItsControls() {
assertNull(SessionDisplay.followSize(720, 404))
assertEquals(720 to 404, SessionDisplay.followSize(720, 404, controlsBelow = true))
@@ -27,7 +27,6 @@ class SessionLogShareZipTest {
val earlySecret = "early-sessionid-abcdef123456"
val trailingSecret = "late-refresh-token-abcdef123456"
try {
// One long line exercises the streaming limit; the final ordinary line must still be redacted.
raw.bufferedWriter().use { out ->
out.write("sessionid=$earlySecret")
val chunk = "x".repeat(8192)
@@ -40,7 +39,6 @@ class SessionLogShareZipTest {
ZipFile(zip).use { archive ->
val entry = archive.getEntry("${session.name}/steam-42.log")!!
archive.getInputStream(entry).use { input ->
// Only inspect the bounded scrubbed prefix: the pre-fix raw archive is over 64 MiB.
val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n"
val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size)
var offset = 0
@@ -74,7 +72,6 @@ class SessionLogShareZipTest {
"Authorization: Bearer abc.def.ghi\n" +
"kept: EResult 5, app 1086940, steamapps/common/Game\n"
)
// StoreLogFiles.prune, started by App.onCreate, deletes a stores log named for a day over a week old.
val storesLog = "stores-" + SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date()) + ".log"
File(logs, "stores").apply { mkdirs() }.resolve(storesLog).writeText("epic: f_token=zzzzzzzz12 window 32\n")
File(logs, SessionPaths.TOOLS_DIR).apply { mkdirs() }.resolve("flatpak-install.log").writeText("== install\nCookie: steamLoginSecure=76561198000000000%7C%7Ceyabc\n")
@@ -5,16 +5,30 @@ import org.junit.Test
class StatsLayoutTest {
@Test fun unknownIdsFallBackToTheDefaults() {
assertEquals(StatsStrip.PANEL, StatsStrip.from(null))
assertEquals(StatsStrip.LINE, StatsStrip.from(null))
assertEquals(StatsStrip.LINE, StatsStrip.from("gone"))
assertEquals(StatsStrip.PANEL, StatsStrip.from("panel"))
assertEquals(StatsStrip.RINGS, StatsStrip.from("rings"))
assertEquals(StatsDash.AUTO, StatsDash.from("gone"))
assertEquals(StatsDash.TRACE, StatsDash.from("trace"))
}
@Test fun tappingTheStripCyclesThroughEveryStyle() {
assertEquals(StatsStrip.PANEL, StatsStrip.LINE.next())
assertEquals(StatsStrip.TILES, StatsStrip.PANEL.next())
assertEquals(StatsStrip.RINGS, StatsStrip.TILES.next())
assertEquals(StatsStrip.PANEL, StatsStrip.RINGS.next())
assertEquals(StatsStrip.LINE, StatsStrip.RINGS.next())
}
@Test fun stripNumbersStartWithEverythingButTheGpuTemperature() {
assertEquals(StripMetric.entries.toSet() - StripMetric.GPU_TEMP, StripMetric.parse(null))
}
@Test fun stripNumbersSurviveSavingAndSkipUnknownIds() {
val picked = setOf(StripMetric.GPU, StripMetric.RAM, StripMetric.CLOCK)
assertEquals(picked, StripMetric.parse(StripMetric.encode(picked)))
assertEquals(setOf(StripMetric.CPU), StripMetric.parse("cpu,gone, "))
assertEquals(emptySet<StripMetric>(), StripMetric.parse(""))
}
@Test fun autoPicksTheDashByTheGamesFormat() {
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import java.io.File
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamLibrariesTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
private fun added(path: String, label: String = File(path).name): SteamLibraries.Entry =
(SteamLibraries.add(app, path, label) as SteamLibraries.AddResult.Added).entry
@Test fun addedLibrariesGetStableMountsThatSurviveRenameAndRemoval() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val docs = added(tmp.newFolder("Documents").path, "Docs")
val usb = added(tmp.newFolder("USB").path)
assertEquals(listOf("/mnt/droiddeck-lib/1", "/mnt/droiddeck-lib/2"), SteamLibraries.list(app).map { it.guest })
assertTrue(File(docs.path, "steamapps").isDirectory)
SteamLibraries.rename(app, docs.id, "My \"Docs\"")
assertEquals("My Docs", SteamLibraries.list(app).first().label)
assertEquals("/mnt/droiddeck-lib/1", SteamLibraries.list(app).first().guest)
SteamLibraries.remove(app, docs.id)
assertEquals(listOf(usb.id), SteamLibraries.list(app).map { it.id })
assertTrue(File(docs.path, "steamapps").isDirectory)
assertEquals("3", added(tmp.newFolder("Again").path).id)
}
@Test fun overlappingFoldersAndAFifthLibraryAreRefused() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val games = tmp.newFolder("Games")
added(games.path)
assertTrue(SteamLibraries.add(app, games.path) is SteamLibraries.AddResult.Refused)
assertTrue(SteamLibraries.add(app, File(games, "inner").apply { mkdirs() }.path) is SteamLibraries.AddResult.Refused)
repeat(SteamLibraries.MAX - 1) { added(tmp.newFolder("L$it").path) }
assertTrue(SteamLibraries.add(app, tmp.newFolder("Full").path) is SteamLibraries.AddResult.Refused)
}
@Test fun addedLibrariesAreListedMappedAndKeepGamesFoldersFromDoubling() {
val pc = tmp.newFolder("PC")
File(pc, "steamapps").mkdirs()
File(pc, "steamapps/appmanifest_220.acf").writeText("x")
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path))
val lib = added(pc.path, "PC")
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
assertEquals(1, Library.steamLibraries(app, "arm64").count { it.first == pc })
assertTrue(Library.steamLibraries(app, "x86_64").any { it.first == File(pc, GameStorage.X64_CARD_DIR) })
assertEquals(File(pc, "steamapps/common"), AddedGames.hostPath(app, "${lib.guest}/steamapps/common"))
val docs = added(tmp.newFolder("Documents").path)
assertEquals("${docs.guest}/steamapps", AddedGames.guestPath(app, File(docs.path, "steamapps")))
val nested = File(pc, "Other").apply { mkdirs() }
SteamLibraries.remove(app, lib.id)
assertTrue(SteamLibraries.add(app, nested.path) is SteamLibraries.AddResult.Refused)
}
@Test fun unreadableOrInvalidEntriesAreDropped() {
assertTrue(SteamLibraries.parse("{oops").isEmpty())
assertEquals(listOf("2"), SteamLibraries.parse("""[{"id":"../x","path":"/a"},{"id":"2","path":"/b","label":""}]""").map { it.id })
assertEquals("b", SteamLibraries.parse("""[{"id":"2","path":"/b","label":""}]""").single().label)
}
}
@@ -7,7 +7,6 @@ import org.junit.Test
class SteamWebLoginTest {
private fun hex(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
// Made with: openssl enc -aes-128-cbc -K <PBKDF2-SHA1("peanuts","saltysalt",1)> -iv <16 spaces>, prefixed "v10".
@Test fun chromiumV10ValuesDecrypt() {
val encrypted = hex("7631300b9cf0a6eee9cf1aaac601b85ca37cf9fe9e67078564f0e05835ae2aa3d9b0ab")
assertEquals("0123456789abcdef01234567", SteamWebLogin.decrypt(encrypted, hostHashed = false))
@@ -12,7 +12,6 @@ import java.io.File
class TelemetryOutputTest {
@get:Rule val tmp = TemporaryFolder()
// DiRT Showdown's own line, as found in its prefix on the Retroid Pocket Duo.
private val showdown = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<hardware_settings_config>\n" +
"\t<audio mono=\"false\" />\n\t<motion enabled=\"true\" ip=\"dbox\" port=\"20777\" delay=\"1\" extradata=\"0\" />\n" +
"</hardware_settings_config>\n"
@@ -4,7 +4,6 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
/** Filling a grid one card at a time: what is on screen stays put, what is new lands where its title belongs. */
class StoreCatalogPatchTest {
private fun item(id: String, title: String, image: String? = null) = CatalogItem(Store.GOG, id, title, imageUrl = image, owned = true)
@@ -75,7 +75,6 @@ class DownloadQueueRetryTest {
DownloadQueue.clear(app, item.key)
assertNull(DownloadQueue.entry(item.key))
// A card resume (including the restored paused path) must retain its real target.
val card = File(app.filesDir, "retry-card").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
val target = File(card, "Games")
@@ -7,7 +7,6 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** The account listing: everything the tab needs to draw a library before a product is asked about. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogListingTest {
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.sync
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class SyncSnapshotTest {
private fun folder(state: String = "idle", global: Long = 100, need: Long = 0, blocked: Boolean = false, paused: Boolean = false, errors: Int = 0) =
SyncFolder("id", "Saves", "/p", paused, blocked, state, global, need, errors, emptyList())
private fun snapshot(vararg folders: SyncFolder) = SyncSnapshot("me", folders.toList(), emptyList(), emptyList(), emptyList(), 0, 0)
@Test
fun syncingReportsPercentOfActiveFolders() {
val s = snapshot(folder("syncing", global = 1000, need = 360), folder())
assertTrue(s.syncing)
assertEquals(64, s.percent)
assertEquals(360, s.needBytes)
}
@Test
fun blockedOrFailingFoldersNeedAttention() {
assertTrue(snapshot(folder(blocked = true, paused = true)).needsAttention)
assertTrue(snapshot(folder(errors = 2)).needsAttention)
assertTrue(snapshot(folder("idle", need = 5)).needsAttention)
assertFalse(snapshot(folder(paused = true, errors = 2)).needsAttention)
}
@Test
fun unreadableFolderStatusShowsAsError() {
val config = JSONObject("""{"id":"saves","label":"Saves","path":"/p","paused":false,"devices":[{"deviceID":"DEV1"}]}""")
val f = SyncthingParse.folder(config, SyncthingParse.unreadableStatus(), blocked = false, names = mapOf("DEV1" to "Desktop PC"))
assertEquals("error", f.state)
assertTrue(f.errors > 0)
assertTrue(f.outOfSync)
assertFalse(f.syncing)
assertEquals(listOf("Desktop PC"), f.sharedWith)
assertTrue(snapshot(f).needsAttention)
}
@Test
fun parsesPendingFoldersWithDeviceNames() {
val json = JSONObject("""{"emu":{"offeredBy":{"DEV1":{"label":"Emulation saves","time":"2026-01-01T00:00:00Z"}}}}""")
val pending = SyncthingParse.pendingFolders(json, mapOf("DEV1" to "Desktop PC"))
assertEquals(listOf(SyncPendingFolder("emu", "Emulation saves", "Desktop PC", "DEV1")), pending)
}
}
@@ -0,0 +1,83 @@
package com.droiddeck.launcher.sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class SyncthingConfigTest {
@get:Rule val tmp = TemporaryFolder()
private val generated = """
<configuration version="51">
<folder id="abc" label="Camera" path="/storage/emulated/0/DCIM" type="sendreceive">
<paused>false</paused>
</folder>
<folder id="def" label="Saves" path="/data/user/0/app/Sync/saves" type="sendreceive">
<paused>false</paused>
</folder>
<device id="PEER" name="Desktop" compression="metadata">
<address>dynamic</address>
<paused>false</paused>
</device>
<gui enabled="true" tls="true" debugging="false">
<address>127.0.0.1:8384</address>
<user>droiddeck</user>
<apikey>key123</apikey>
</gui>
<options>
<listenAddress>default</listenAddress>
<localAnnouncePort>21027</localAnnouncePort>
<urAccepted>0</urAccepted>
<startBrowser>true</startBrowser>
</options>
<defaults>
<folder id="" label="" path="~" type="sendreceive"></folder>
</defaults>
</configuration>
""".trimIndent()
private val ports = SyncthingPorts(22100, 21127)
@Test
fun pausesDisallowedFoldersBeforeLaunch() {
val out = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { !it.startsWith("/storage/emulated/0/DCIM") }
val camera = out.substringAfter("id=\"abc\"").substringBefore("</folder>")
val saves = out.substringAfter("id=\"def\"").substringBefore("</folder>")
assertTrue(camera.contains("<paused>true</paused>"))
assertTrue(saves.contains("<paused>false</paused>"))
}
@Test
fun pausesDevicesBeforeLaunchWhenPolicyRequires() {
val paused = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync", pauseDevices = true) { true }
assertTrue(paused.substringAfter("id=\"PEER\"").substringBefore("</device>").contains("<paused>true</paused>"))
val open = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync", pauseDevices = false) { true }
assertTrue(open.substringAfter("id=\"PEER\"").substringBefore("</device>").contains("<paused>false</paused>"))
}
@Test
fun replacesConfigFileWithoutLeavingStagedCopy() {
val dir = tmp.newFolder()
val file = File(dir, "config.xml").apply { writeText(generated) }
SyncthingConfig.apply(file, ports, File("/data/st/gui.sock"), File("/ext/Sync"), false) { true }
assertEquals(SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { true }, file.readText())
assertEquals(listOf("config.xml"), dir.list()!!.toList())
}
@Test
fun applyIsStable() {
val once = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { true }
assertEquals(once, SyncthingConfig.apply(once, ports, "/data/st/gui.sock", "/ext/Sync") { true })
}
@Test
fun guiListensOnlyOnPrivateSocket() {
val gui = SyncthingConfig.apply(generated, ports, "/data/st/gui.sock", "/ext/Sync") { true }.substringAfter("<gui").substringBefore("</gui>")
assertTrue(gui.contains("<address>/data/st/gui.sock</address>"))
assertTrue(gui.contains("<unixSocketPermissions>600</unixSocketPermissions>"))
assertTrue(gui.contains("tls=\"false\""))
}
}
@@ -0,0 +1,69 @@
package com.droiddeck.launcher.sync
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.nio.file.Files
class SyncthingGuardTest {
@get:Rule val tmp = TemporaryFolder()
private fun setup(): Triple<SyncthingGuard, File, File> {
val data = tmp.newFolder("data")
val external = tmp.newFolder("external")
val home = File(external, "Sync").apply { mkdirs() }
val config = File(data, "files/syncthing").apply { mkdirs() }
return Triple(SyncthingGuard(home, listOf(data, external), listOf(config)), data, external)
}
@Test
fun allowsFoldersInsideAppStorage() {
val (guard, data, external) = setup()
assertTrue(guard.allows(File(external, "Sync/Game saves").path))
assertTrue(guard.allows(File(data, "files/linux/home").path))
assertTrue(guard.allows("~/Shared"))
assertTrue(guard.allows(external.path))
}
@Test
fun blocksFoldersOutsideAppStorage() {
val (guard, _, _) = setup()
assertFalse(guard.allows(tmp.newFolder("DCIM").path))
assertFalse(guard.allows("/storage/emulated/0/Download"))
assertFalse(guard.allows(""))
assertFalse(guard.allows("relative/path"))
}
@Test
fun blocksSyncthingsOwnConfig() {
val (guard, data, _) = setup()
assertFalse(guard.allows(File(data, "files/syncthing").path))
assertFalse(guard.allows(File(data, "files/syncthing/keys").path))
}
@Test
fun blocksFoldersHoldingSyncthingsConfig() {
val (guard, data, _) = setup()
assertFalse(guard.allows(data.path))
assertFalse(guard.allows(File(data, "files").path))
}
@Test
fun blocksSiblingWithSharedPrefix() {
val (guard, _, external) = setup()
assertFalse(guard.allows(external.path + "-other"))
}
@Test
fun blocksSymlinkPointingOutside() {
val (guard, _, external) = setup()
val outside = tmp.newFolder("outside")
val link = File(external, "Sync/link")
Files.createSymbolicLink(link.toPath(), outside.toPath())
assertFalse(guard.allows(link.path))
assertFalse(guard.allows(File(link, "child").path))
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.sync
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayOutputStream
class SyncthingHttpTest {
private fun response(raw: String) = SyncthingHttp.readResponse(raw.byteInputStream(Charsets.ISO_8859_1))
@Test
fun readsContentLengthBody() {
assertEquals(200 to """{"ping":"pong"}""", response("HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n{\"ping\":\"pong\"}"))
}
@Test
fun readsChunkedBody() {
assertEquals(403 to "CSRF Error", response("HTTP/1.1 403 Forbidden\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nCSRF\r\n6\r\n Error\r\n0\r\n\r\n"))
}
@Test
fun writesOneShotRequest() {
val out = ByteArrayOutputStream()
SyncthingHttp.writeRequest(out, "POST", "/rest/system/pause", listOf("X-API-Key" to "k"), null)
val text = out.toString("ISO-8859-1")
assertTrue(text.startsWith("POST /rest/system/pause HTTP/1.1\r\n"))
assertTrue(text.contains("Connection: close\r\n"))
assertTrue(text.endsWith("X-API-Key: k\r\nContent-Length: 0\r\n\r\n"))
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.sync
import org.junit.Assert.assertEquals
import org.junit.Test
class SyncthingPortsTest {
@Test
fun skipsBusyPorts() {
val busy = setOf(22100, 21127)
val picked = SyncthingPortPicker.pick({ it !in busy }, { it !in busy })
assertEquals(SyncthingPorts(22101, 21128), picked)
}
@Test(expected = IllegalStateException::class)
fun failsWhenNoPortIsFree() {
SyncthingPortPicker.pick({ false }, { true })
}
}
@@ -31,7 +31,6 @@ class BottomDashboardTest {
}
@Test fun tabNamesShowOnlyWhileEveryTabFits() {
// Retroid Pocket Duo bottom panel: 1280x960 at 320 dpi = 640 dp wide.
assertTrue(bottomTabsWithLabels(640f, 4))
assertFalse(bottomTabsWithLabels(640f, 5))
assertFalse(bottomTabsWithLabels(360f, 3))
@@ -22,14 +22,11 @@ class DeckControlsPanelTest {
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))
@@ -41,7 +38,6 @@ class DeckControlsPanelTest {
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++
}
@@ -0,0 +1,33 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertEquals
import org.junit.Test
class HistoryTest {
@Test fun theSpanIsTheTimeTheKeptReadingsCover() {
val h = History(3)
h.add(1f, 1_000L)
h.add(2f, 1_500L)
assertEquals(1, h.spanSeconds())
h.add(3f, 2_000L)
h.add(4f, 4_000L)
assertEquals(listOf(2f, 3f, 4f), h.snapshot())
assertEquals(3, h.spanSeconds())
}
@Test fun aHistoryThatStopsBeingFedKeepsItsSpan() {
val h = History(4)
h.add(1f, 10_000L)
h.add(2f, 20_000L)
assertEquals(10, h.spanSeconds())
assertEquals(10, h.spanSeconds())
}
@Test fun readingsWithoutATimeHaveNoSpan() {
val h = History(2)
h.add(1f)
assertEquals(0, h.spanSeconds())
assertEquals(0, History(2).spanSeconds())
assertEquals(0, History(2).apply { add(1f, 5_000L) }.spanSeconds())
}
}
@@ -0,0 +1,26 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertArrayEquals
import org.junit.Test
class StripFitTest {
@Test fun everythingFitsOnAWideLine() {
assertArrayEquals(booleanArrayOf(true, true, true), fitByPriority(intArrayOf(10, 20, 30), intArrayOf(0, 1, 2), 5, 100))
}
@Test fun theLeastImportantItemsAreLeftOutFirst() {
assertArrayEquals(booleanArrayOf(true, false, true), fitByPriority(intArrayOf(10, 20, 30), intArrayOf(0, 2, 1), 5, 60))
}
@Test fun anItemThatDoesNotFitEndsTheLine() {
assertArrayEquals(booleanArrayOf(true, false, false), fitByPriority(intArrayOf(10, 50, 5), intArrayOf(0, 1, 2), 2, 40))
}
@Test fun equalPrioritiesKeepTheirOrder() {
assertArrayEquals(booleanArrayOf(true, true, false), fitByPriority(intArrayOf(10, 10, 10), intArrayOf(0, 0, 0), 0, 25))
}
@Test fun nothingFitsInNoRoom() {
assertArrayEquals(booleanArrayOf(false, false), fitByPriority(intArrayOf(10, 10), intArrayOf(0, 1), 0, 5))
}
}
@@ -78,7 +78,6 @@ class TrackingRecoveryViewTest {
difference+=abs(((actual ushr 16) and 255)-((reference ushr 16) and 255))
}
}
// Native text rasterization can round a translated glyph edge differently.
assertTrue("Eye at x=$x changed $changed pixels",changed<pixels/1000)
assertTrue("Eye at x=$x has different content",difference.toDouble()/(pixels*3)<0.1)
}