mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-27 08:35:42 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0a4b084d9 | ||
|
|
ae66be5521 | ||
|
|
aef4a11595 | ||
|
|
cc04546373 | ||
|
|
bdd3d247c3 | ||
|
|
e71c37b34f |
No files matched your search
@@ -1769,6 +1769,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
wowChat = wowChat.remembered,
|
||||
onWowChat = wowChat::choose,
|
||||
controller = controllerSettings,
|
||||
onControllerSize = { percent -> updateControllerPrefs { ControllerPrefs.setSize(this@SessionActivity, percent) } },
|
||||
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
|
||||
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
||||
@@ -2110,6 +2111,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
change()
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
onScreenControls?.reload()
|
||||
bottomInputControls?.reload()
|
||||
unfoldedPanel?.reload()
|
||||
}
|
||||
|
||||
private fun routeBackAction() {
|
||||
@@ -2846,7 +2849,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun installProton(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
||||
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(this)) return installOwnProton()
|
||||
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
@@ -2859,24 +2861,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
}
|
||||
|
||||
private fun installOwnProton(): String? {
|
||||
val extras = com.droiddeck.launcher.session.ProtonExtras
|
||||
while ((extras.prefetching || extras.installInProgress) && !SessionState.stopRequested) {
|
||||
try { Thread.sleep(250) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return "interrupted" }
|
||||
}
|
||||
if (SessionState.stopRequested) return "cancelled"
|
||||
if (!com.droiddeck.launcher.runtime.DesktopCatalog.ownProtonMissing(this)) return null
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
return try {
|
||||
extras.install(this, extras.tools.first { it.id == extras.OWN }, cancellation) { label, percent ->
|
||||
uiHandler.post { loading.percent = percent; loading.say(label, PROTON_LINES.topic, readable = true) }
|
||||
}.also { if (it == null) com.droiddeck.launcher.session.Onboarding.recheck(this) }
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
if (holder !== outputHolder()) return
|
||||
if (installingRuntime || SessionState.stopRequested || ended) return
|
||||
|
||||
@@ -126,6 +126,16 @@ object AgentSetup {
|
||||
Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start()
|
||||
}
|
||||
|
||||
/** The last failed refresh ends the script: the installs after it would run from stale indexes and could report success. */
|
||||
internal fun installScript(harnessInstall: String) = "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
||||
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
|
||||
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
|
||||
"for i in 1 2 3; do apt -o APT::Update::Error-Mode=any update -q && break; " +
|
||||
"[ \$i = 3 ] && { echo 'Some package sources could not be refreshed'; exit 1; }; " +
|
||||
"echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
|
||||
"apt -f install -y --fix-missing; " +
|
||||
"apt install -y --no-install-recommends git gh adb curl ca-certificates python3; $harnessInstall"
|
||||
|
||||
fun runsAsRoot(step: Step) = step == Step.INSTALL
|
||||
|
||||
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
|
||||
@@ -140,12 +150,7 @@ object AgentSetup {
|
||||
val command = override ?: when (step) {
|
||||
Step.CONNECTION -> return
|
||||
Step.INSTALL -> {
|
||||
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
||||
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
|
||||
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
|
||||
"for i in 1 2 3; do apt -o APT::Update::Error-Mode=any update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
|
||||
"apt -f install -y --fix-missing; " +
|
||||
"apt install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
||||
listOf("sh", "-c", installScript(harness.install))
|
||||
}
|
||||
Step.SIGN_IN -> harness.signIn
|
||||
Step.GITHUB -> listOf("dd-gh-login")
|
||||
|
||||
@@ -5,7 +5,7 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
internal object DroidDeckHudConfig {
|
||||
val DEFAULTS: Map<String, String> = linkedMapOf(
|
||||
"hudSize" to "minimal", "hudLocked" to "1", "hudHold" to "collapse", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
|
||||
"hudSize" to "minimal", "hudLocked" to "0", "hudHold" to "collapse", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
|
||||
"hudOutline" to "40", "hudOutlineAccent" to "1",
|
||||
"showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1",
|
||||
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
|
||||
|
||||
@@ -349,7 +349,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
showProton = switchOn("showProton")
|
||||
showSession = switchOn("showSession")
|
||||
tempDisplay = HudMetrics.TempDisplay.from(cfg)
|
||||
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
|
||||
lockController.setLocked(cfg.get("hudLocked", "0") == "1")
|
||||
lockController.setHoldLocks(cfg.get("hudHold", "collapse") == DroidDeckHudConfig.HOLD_LOCKS)
|
||||
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ object ControllerPrefs {
|
||||
|
||||
val opacities = listOf(40, 60, 80, 100)
|
||||
|
||||
val sizes = listOf(80, 90, 100, 110, 125)
|
||||
val sizes = listOf(80, 85, 90, 95, 100, 105, 110, 115, 120, 125)
|
||||
|
||||
val deadZones = listOf(0, 5, 8, 12, 15, 20, 25)
|
||||
const val DEFAULT_DEAD_ZONE_PERCENT = 12
|
||||
|
||||
@@ -5,7 +5,7 @@ import android.graphics.Rect
|
||||
import kotlin.math.*
|
||||
|
||||
internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val safe: Rect = Rect(),
|
||||
private val scale: Float = 1f) {
|
||||
private val scale: Float = 1f, private val sizeOverride: Int? = null) {
|
||||
private val resources get() = context.resources
|
||||
private val settings = ControllerPrefs.read(context)
|
||||
private var fit = 1f
|
||||
@@ -41,7 +41,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
||||
|
||||
private fun dp(value: Float) = value * resources.displayMetrics.density
|
||||
|
||||
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
|
||||
private fun scaled(value: Float) = dp(value) * (sizeOverride ?: settings.size) / 100f * scale * fit
|
||||
|
||||
private fun fitScale(): Float {
|
||||
val metrics = resources.displayMetrics
|
||||
|
||||
@@ -44,9 +44,10 @@ object OnScreenLayout {
|
||||
val (reference, matched) = reference(context, layout, width, height)
|
||||
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
||||
if (dock?.portrait == true && !dock.grips && !matched && layout.aspect > 0f && layout.aspect < 1f && stored.any(::isGamepad))
|
||||
return cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe)
|
||||
val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
|
||||
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
|
||||
return scaleDocked(context, cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe), ControllerPrefs.read(context).size / 100f, width, height, safe)
|
||||
val oppositeOrientation = layout.aspect > 0f && ((layout.aspect < 1f) != (height > width))
|
||||
val generated = matched ||
|
||||
dock == null && oppositeOrientation && stored.any(::isGamepad)
|
||||
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
|
||||
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
||||
val regenerated = when {
|
||||
@@ -57,22 +58,144 @@ object OnScreenLayout {
|
||||
val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } }
|
||||
val byId = (placed + others).associateBy { it.id }
|
||||
val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
|
||||
val kit = PadKit.forOverlay(context, layout) ?: return ordered
|
||||
val kit = PadKit.forOverlay(context, layout) ?: return if (dock == null) ordered else scaleDocked(context, ordered, ControllerPrefs.read(context).size / 100f, width, height, safe)
|
||||
val controllerScale = layout.scale * ControllerPrefs.read(context).size / 100f
|
||||
if (generated &&
|
||||
ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() &&
|
||||
ControllerPrefs.layout(context, width, height).isEmpty()) {
|
||||
if (dock != null || height > width) {
|
||||
return ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density)
|
||||
.place(ordered, kit, dock != null, layout.scale, rearButtons == true, trackpads == true)
|
||||
val placed = ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density)
|
||||
.place(ordered, kit, dock != null, controllerScale, rearButtons == true, trackpads == true)
|
||||
return if (dock != null) {
|
||||
scaleDocked(context, placed, ControllerPrefs.read(context).size / 100f, width, height, safe)
|
||||
} else placed
|
||||
}
|
||||
return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
|
||||
return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, controllerScale)
|
||||
.place(ordered, kit, rearButtons == true, trackpads == true)
|
||||
}
|
||||
if (dock != null || !kit.steam) return ordered
|
||||
if (dock != null || !kit.steam) {
|
||||
if (dock == null) return ordered
|
||||
return scaleDocked(context, ordered, ControllerPrefs.read(context).size / 100f, width, height, safe)
|
||||
}
|
||||
return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density)
|
||||
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
|
||||
}
|
||||
|
||||
private fun scaleDocked(context: Context, elements: List<InputSurfaceElement>, scale: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
|
||||
val usableWidth = (width - safe.left - safe.right).coerceAtLeast(1).toFloat() / width
|
||||
val usableHeight = (height - safe.top - safe.bottom).coerceAtLeast(1).toFloat() / height
|
||||
val leftBound = safe.left.toFloat() / width
|
||||
val rightBound = (width - safe.right).toFloat() / width
|
||||
val topBound = safe.top.toFloat() / height
|
||||
val bottomBound = (height - safe.bottom).toFloat() / height
|
||||
val scaled = elements.map { element ->
|
||||
if (!isGamepad(element)) return@map element
|
||||
val w = (element.width * scale).coerceIn(min(.001f, usableWidth), usableWidth)
|
||||
val h = (element.height * scale).coerceIn(min(.001f, usableHeight), usableHeight)
|
||||
val x = (element.x + element.width / 2f - w / 2f)
|
||||
.coerceIn(leftBound, (rightBound - w).coerceAtLeast(leftBound))
|
||||
val y = (element.y + element.height / 2f - h / 2f)
|
||||
.coerceIn(topBound, (bottomBound - h).coerceAtLeast(topBound))
|
||||
element.copy(x = x, y = y, width = w, height = h).bounded()
|
||||
}.toMutableList()
|
||||
if (scale > 1f) {
|
||||
val gap = 4f / width
|
||||
fun spacePair(leftControl: InputControl, rightControl: InputControl) {
|
||||
val li = scaled.indexOfFirst { isGamepad(it) && it.control == leftControl }
|
||||
val ri = scaled.indexOfFirst { isGamepad(it) && it.control == rightControl }
|
||||
if (li < 0 || ri < 0) return
|
||||
var left = scaled[li]
|
||||
var right = scaled[ri]
|
||||
val available = (rightBound - leftBound).coerceAtLeast(.001f)
|
||||
var gapSize = gap.coerceAtMost(available / 4f)
|
||||
if (left.width + right.width + gapSize > available) {
|
||||
val factor = ((available - gapSize).coerceAtLeast(0f) / (left.width + right.width)).coerceAtMost(1f)
|
||||
left = left.copy(width = left.width * factor)
|
||||
right = right.copy(width = right.width * factor)
|
||||
}
|
||||
val total = left.width + gapSize + right.width
|
||||
val center = ((left.x + left.width / 2f) + (right.x + right.width / 2f)) / 2f
|
||||
val start = (center - total / 2f).coerceIn(leftBound, (rightBound - total).coerceAtLeast(leftBound))
|
||||
scaled[li] = left.copy(x = start)
|
||||
scaled[ri] = right.copy(x = start + left.width + gapSize)
|
||||
}
|
||||
spacePair(InputControl.LT, InputControl.LB)
|
||||
spacePair(InputControl.RB, InputControl.RT)
|
||||
}
|
||||
if (scale > 1f && ControllerPrefs.layout(context, width, height).isEmpty()) {
|
||||
repeat(scaled.size) {
|
||||
for (i in scaled.indices) {
|
||||
if (!isGamepad(scaled[i])) continue
|
||||
for (j in i + 1 until scaled.size) {
|
||||
if (!isGamepad(scaled[j])) continue
|
||||
val a = scaled[i]
|
||||
val b = scaled[j]
|
||||
val overlapX = min(a.x + a.width, b.x + b.width) - max(a.x, b.x)
|
||||
val overlapY = min(a.y + a.height, b.y + b.height) - max(a.y, b.y)
|
||||
if (overlapX <= 0f || overlapY <= 0f) continue
|
||||
|
||||
val centerAX = a.x + a.width / 2f
|
||||
val centerBX = b.x + b.width / 2f
|
||||
val centerAY = a.y + a.height / 2f
|
||||
val centerBY = b.y + b.height / 2f
|
||||
if (overlapX / min(a.width, b.width) <= overlapY / min(a.height, b.height)) {
|
||||
val gapX = 2f / width
|
||||
val available = (rightBound - leftBound).coerceAtLeast(.001f)
|
||||
val leftFirst = centerAX <= centerBX
|
||||
val factor = ((available - gapX).coerceAtLeast(0f) / (a.width + b.width)).coerceIn(0f, 1f)
|
||||
val aw = a.width * factor
|
||||
val ah = a.height * factor
|
||||
val bw = b.width * factor
|
||||
val bh = b.height * factor
|
||||
val total = aw + gapX + bw
|
||||
val center = ((centerAX + centerBX) / 2f).coerceIn(
|
||||
leftBound + total / 2f,
|
||||
(rightBound - total / 2f).coerceAtLeast(leftBound + total / 2f))
|
||||
val firstX = center - total / 2f
|
||||
val secondX = firstX + (if (leftFirst) aw else bw) + gapX
|
||||
scaled[i] = if (leftFirst) {
|
||||
a.copy(x = firstX, y = centerAY - ah / 2f, width = aw, height = ah)
|
||||
} else {
|
||||
a.copy(x = secondX, y = centerAY - ah / 2f, width = aw, height = ah)
|
||||
}
|
||||
scaled[j] = if (leftFirst) {
|
||||
b.copy(x = secondX, y = centerBY - bh / 2f, width = bw, height = bh)
|
||||
} else {
|
||||
b.copy(x = firstX, y = centerBY - bh / 2f, width = bw, height = bh)
|
||||
}
|
||||
} else {
|
||||
val gapY = 2f / height
|
||||
val available = (bottomBound - topBound).coerceAtLeast(.001f)
|
||||
val topFirst = centerAY <= centerBY
|
||||
val factor = ((available - gapY).coerceAtLeast(0f) / (a.height + b.height)).coerceIn(0f, 1f)
|
||||
val aw = a.width * factor
|
||||
val ah = a.height * factor
|
||||
val bw = b.width * factor
|
||||
val bh = b.height * factor
|
||||
val total = ah + gapY + bh
|
||||
val center = ((centerAY + centerBY) / 2f).coerceIn(
|
||||
topBound + total / 2f,
|
||||
(bottomBound - total / 2f).coerceAtLeast(topBound + total / 2f))
|
||||
val firstY = center - total / 2f
|
||||
val secondY = firstY + (if (topFirst) ah else bh) + gapY
|
||||
scaled[i] = if (topFirst) {
|
||||
a.copy(x = centerAX - aw / 2f, y = firstY, width = aw, height = ah)
|
||||
} else {
|
||||
a.copy(x = centerAX - aw / 2f, y = secondY, width = aw, height = ah)
|
||||
}
|
||||
scaled[j] = if (topFirst) {
|
||||
b.copy(x = centerBX - bw / 2f, y = secondY, width = bw, height = bh)
|
||||
} else {
|
||||
b.copy(x = centerBX - bw / 2f, y = firstY, width = bw, height = bh)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return scaled
|
||||
}
|
||||
|
||||
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width)
|
||||
|
||||
private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout {
|
||||
@@ -181,7 +304,14 @@ object OnScreenLayout {
|
||||
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
|
||||
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
|
||||
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
|
||||
if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true
|
||||
val sizedGenerator = LegacyGamepadLayout(
|
||||
display, w, h, scale = layout.scale,
|
||||
sizeOverride = ControllerPrefs.read(context).size
|
||||
)
|
||||
if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true)) ||
|
||||
matches(gamepad, sizedGenerator.elements()) || matches(gamepad, sizedGenerator.elements(previousStickGeometry = true))) {
|
||||
return (w.toFloat() to h.toFloat()) to true
|
||||
}
|
||||
}
|
||||
}
|
||||
val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short)
|
||||
|
||||
@@ -39,6 +39,10 @@ internal object BuildWatermarkSetting {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
notifyChanged(context)
|
||||
}
|
||||
|
||||
fun notifyChanged(context: Context) {
|
||||
context.sendBroadcast(Intent(CHANGED).setPackage(context.packageName))
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,9 @@ object SessionPaths {
|
||||
@Volatile
|
||||
private var startedAt = 0L
|
||||
|
||||
@Volatile
|
||||
private var debugLogsContext: Context? = null
|
||||
|
||||
@Synchronized
|
||||
fun beginOrCurrent(context: Context, label: String? = null): File {
|
||||
dir?.let { if (it.isDirectory) return it }
|
||||
@@ -44,6 +47,7 @@ object SessionPaths {
|
||||
startedAt = System.currentTimeMillis()
|
||||
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
|
||||
dir = made
|
||||
debugLogsContext = if (SessionPrefs.gameDebugLogsEnabled(context)) context.applicationContext else null
|
||||
if (enhanced && !EnhancedDiagnostics.consumeInto(context, made)) {
|
||||
Log.e(TAG, "could not activate enhanced diagnostics for $made")
|
||||
}
|
||||
@@ -65,6 +69,9 @@ object SessionPaths {
|
||||
val taken = dir
|
||||
dir = null
|
||||
if (taken != null) ended = taken
|
||||
val expiring = debugLogsContext
|
||||
debugLogsContext = null
|
||||
if (taken != null && expiring != null) SessionPrefs.expireGameDebugLogs(expiring)
|
||||
return taken
|
||||
}
|
||||
|
||||
|
||||
@@ -1228,7 +1228,7 @@ object SessionPrefs {
|
||||
oldValue = logsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = gameDebugLogsEffective(context, on, gameDebugLogsEnabled(context)),
|
||||
)
|
||||
).also { if (it) BuildWatermarkSetting.notifyChanged(context) }
|
||||
}
|
||||
|
||||
fun gameDebugLogsEnabled(context: Context): Boolean =
|
||||
@@ -1241,7 +1241,13 @@ object SessionPrefs {
|
||||
oldValue = gameDebugLogsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = gameDebugLogsEffective(context, logsEnabled(context), on),
|
||||
)
|
||||
).also { if (it) BuildWatermarkSetting.notifyChanged(context) }
|
||||
}
|
||||
|
||||
/** The setting lasts for the session that started with it on; the next session's start republishes the environment. */
|
||||
internal fun expireGameDebugLogs(context: Context) {
|
||||
prefs(context).edit().putBoolean("gameDebugLogsEnabled", false).apply()
|
||||
runCatching { BuildWatermarkSetting.notifyChanged(context) }
|
||||
}
|
||||
|
||||
private fun setLogPreference(
|
||||
|
||||
@@ -122,16 +122,10 @@ object StoreInstalls {
|
||||
|
||||
fun discard(context: Context, folder: File, caches: List<File>) {
|
||||
val app = context.applicationContext
|
||||
inBackground(folder) { discardNow(app, folder, caches) }
|
||||
}
|
||||
|
||||
fun deleteLater(dir: File) = inBackground(dir) { deleteTree(dir) }
|
||||
|
||||
private fun inBackground(folder: File, work: () -> Unit) {
|
||||
beginDiscard(folder)
|
||||
val worker = Thread({
|
||||
try {
|
||||
work()
|
||||
discardNow(app, folder, caches)
|
||||
} finally {
|
||||
endDiscard(folder)
|
||||
}
|
||||
|
||||
@@ -318,7 +318,7 @@ object StoresState {
|
||||
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
|
||||
uninstalling[key] = 0f
|
||||
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
|
||||
if (!com.droiddeck.launcher.stores.download.DownloadQueue.stopForRemoval(app, key)) {
|
||||
if (!com.droiddeck.launcher.stores.download.DownloadQueue.holdForRemovalWhenFree(key)) {
|
||||
logLine("kept \"${game.sidecar.title}\": its download or update is still running")
|
||||
main.post { uninstalling.remove(key); onDone() }
|
||||
return@background
|
||||
|
||||
@@ -9,7 +9,6 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object DownloadQueue {
|
||||
private const val TAG = "StoreDownloads"
|
||||
private const val REMOVAL_WAIT_MS = 30_000L
|
||||
|
||||
interface DownloadJob {
|
||||
fun run(handle: JobHandle): String?
|
||||
@@ -121,24 +120,17 @@ object DownloadQueue {
|
||||
|
||||
fun releaseRemoval(key: String) { synchronized(lock) { removing.remove(key); (lock as Object).notifyAll() } }
|
||||
|
||||
fun stopForRemoval(context: Context, key: String): Boolean {
|
||||
if (synchronized(lock) { busyLocked(key) }) cancel(context, key)
|
||||
val deadline = android.os.SystemClock.uptimeMillis() + REMOVAL_WAIT_MS
|
||||
return synchronized(lock) {
|
||||
while (true) {
|
||||
val busy = busyLocked(key)
|
||||
if (!busy && key !in cleaningUp && key !in removing) break
|
||||
val left = deadline - android.os.SystemClock.uptimeMillis()
|
||||
if (busy && left <= 0) return@synchronized false
|
||||
(lock as Object).wait(if (busy) left else 0L)
|
||||
}
|
||||
removing.add(key)
|
||||
true
|
||||
fun holdForRemovalWhenFree(key: String): Boolean = synchronized(lock) {
|
||||
while (true) {
|
||||
val item = items[key]
|
||||
if (item?.entry?.isActive == true || item?.job != null) return@synchronized false
|
||||
if (key !in cleaningUp && key !in removing) break
|
||||
(lock as Object).wait()
|
||||
}
|
||||
removing.add(key)
|
||||
true
|
||||
}
|
||||
|
||||
private fun busyLocked(key: String): Boolean = items[key].let { it?.entry?.isActive == true || it?.job != null }
|
||||
|
||||
private fun beginCleanup(key: String): Boolean = synchronized(lock) {
|
||||
if (key in removing) return@synchronized false
|
||||
cleaningUp.merge(key, 1, Int::plus)
|
||||
@@ -420,7 +412,6 @@ object DownloadQueue {
|
||||
}
|
||||
item.job = null
|
||||
publishLocked()
|
||||
(lock as Object).notifyAll()
|
||||
}
|
||||
when (item.entry.state) {
|
||||
DownloadState.INSTALLED -> {
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
@@ -216,7 +215,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
val before = EpicClient.read(app)
|
||||
val needApp = !(before.version == launcher.version && File(state, "app/${launcher.version}/.droiddeck-ready").isFile)
|
||||
val needRuntime = !(before.runtimeVersion == runtime.version && File(state, "runtime/${runtime.version}/.droiddeck-ready").isFile)
|
||||
val dir = EpicClient.downloadsDir(app).also { StoreInstalls.awaitDiscard(it) }.apply { mkdirs() }
|
||||
val dir = EpicClient.downloadsDir(app).apply { mkdirs() }
|
||||
val gles = EpicClientSources.gles()
|
||||
val appPart = if (needApp) Part(listOf(launcher.url), File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true) else null
|
||||
val desktopParts = if (needApp) EpicClientSources.DESKTOP.map { Part(it.urls, File(dir, it.file), it.sha256, false, it.size) } else emptyList()
|
||||
@@ -266,7 +265,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
runCatching { connection?.disconnect() }
|
||||
if (deleteFiles) StoreInstalls.deleteLater(EpicClient.downloadsDir(app))
|
||||
if (deleteFiles) EpicClient.downloadsDir(app).deleteRecursively()
|
||||
}
|
||||
|
||||
private fun length(url: String): Long {
|
||||
|
||||
@@ -282,7 +282,7 @@ internal object SteamStore {
|
||||
if (key in StoresState.uninstalling) return
|
||||
StoresState.uninstalling[key] = 0f
|
||||
Thread({
|
||||
if (!DownloadQueue.stopForRemoval(app, key)) {
|
||||
if (!DownloadQueue.holdForRemovalWhenFree(key)) {
|
||||
StoresState.logLine("Steam: kept $appId, its download is still running")
|
||||
StoresState.post { StoresState.uninstalling.remove(key); onDone() }
|
||||
return@Thread
|
||||
|
||||
@@ -137,7 +137,7 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
delete = deleteFiles
|
||||
val process = child
|
||||
if (process == null) {
|
||||
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteLater(folder)
|
||||
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
|
||||
else if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -81,10 +81,13 @@ object BuildWatermark {
|
||||
if (activity is QuestXrActivity) return
|
||||
val decor = activity.window.decorView as? ViewGroup ?: return
|
||||
decor.findViewWithTag<View>(TAG)?.let(decor::removeView)
|
||||
if (!com.droiddeck.launcher.session.SessionPrefs.buildWatermarkEnabled(activity)) return
|
||||
val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" }
|
||||
val build = lineProvider().orEmpty()
|
||||
val content = (listOfNotNull(lab) + build).ifEmpty { return }
|
||||
val prefs = com.droiddeck.launcher.session.SessionPrefs
|
||||
val debugLogs = if (prefs.logsEnabled(activity) && prefs.gameDebugLogsEnabled(activity)) DEBUG_LOGS_LINE else null
|
||||
val build = if (prefs.buildWatermarkEnabled(activity)) {
|
||||
listOfNotNull(com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" }) +
|
||||
lineProvider().orEmpty()
|
||||
} else emptyList()
|
||||
val content = (build + listOfNotNull(debugLogs)).ifEmpty { return }
|
||||
val margin = (8 * activity.resources.displayMetrics.density).toInt()
|
||||
decor.addView(
|
||||
MarkView(activity, content).apply { tag = TAG },
|
||||
@@ -96,6 +99,8 @@ object BuildWatermark {
|
||||
)
|
||||
}
|
||||
|
||||
internal const val DEBUG_LOGS_LINE = "GAME DEBUG LOGS ON | slows games"
|
||||
|
||||
private const val TAG = "build-watermark"
|
||||
|
||||
private class MarkView(context: Context, private val lines: List<String>) : View(context) {
|
||||
|
||||
@@ -226,10 +226,22 @@ internal fun GameDetail(
|
||||
val t = tab ?: return@LaunchedEffect
|
||||
if (!inPage) focusWithinFrames({ onStrip }) { tabFocus.getValue(t) }
|
||||
}
|
||||
var steppedTo by remember(key) { mutableStateOf<GameTab?>(null) }
|
||||
LaunchedEffect(steppedTo, tab) {
|
||||
val t = steppedTo ?: return@LaunchedEffect
|
||||
if (t != tab) {
|
||||
steppedTo = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
focusSoon { tabFocus.getValue(t) }
|
||||
steppedTo = null
|
||||
}
|
||||
fun cycle(step: Int) {
|
||||
if (tabs.size < 2) return
|
||||
val at = tabs.indexOf(tab).coerceAtLeast(0)
|
||||
picked = tabs[(at + step + tabs.size) % tabs.size]
|
||||
val next = tabs[(at + step + tabs.size) % tabs.size]
|
||||
picked = next
|
||||
if (inPage) steppedTo = next
|
||||
}
|
||||
val art: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
|
||||
val artModel: Any? = if (art is String) cardArtRequest(art, item?.tallImageUrl) else art
|
||||
|
||||
@@ -374,7 +374,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
.map { it.store.id }.toSet()
|
||||
val sources = librarySources(
|
||||
all, storeTabs.map { it.store.id },
|
||||
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.ADDED.takeIf { stores }).toSet() + signInChips,
|
||||
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.ADDED.takeIf { stores }, Store.BATTLENET.id.takeIf { stores }).toSet() + signInChips,
|
||||
favorites, concealed,
|
||||
offStores = if (soundMode) emptySet() else storeTabs.filterNot { it.shown }.map { it.store.id }.toSet(),
|
||||
places = if (soundMode) DEFAULT_LIBRARY_PLACES else StoreTabsState.libraryPlaces,
|
||||
@@ -632,7 +632,8 @@ private fun LibraryGrid(
|
||||
// A search that matches nothing keeps the toolbar, so the search can still be cleared.
|
||||
val customEmpty = !soundMode && source == Library.ADDED && visible.isEmpty() && hiddenUninstalled == 0 && LibraryView.query.isBlank()
|
||||
val splash = !soundMode && (signInStore != null || customEmpty)
|
||||
val headerItems = (if (splash) 1 else 2) + (if (sizesPending) 1 else 0) + syncing.size
|
||||
val showHeader = !splash || source == Store.BATTLENET.id
|
||||
val headerItems = (if (showHeader) 2 else 1) + (if (sizesPending) 1 else 0) + syncing.size
|
||||
val expanded = showUninstalled == true
|
||||
val notInstalled = if (expanded) visible.count { !it.installed } else hiddenUninstalled
|
||||
val toggleAt = when {
|
||||
@@ -766,7 +767,7 @@ private fun LibraryGrid(
|
||||
Box(Modifier.onSizeChanged { chipsH = it.height }) { Rise(0) { if (soundMode) header() else filters() } }
|
||||
}
|
||||
val splashHeight = with(density) { (gridH - chipsH).toDp() - 28.dp }.coerceAtLeast(300.dp)
|
||||
if (!splash) item(key = if (soundMode) "filters" else "header", span = { GridItemSpan(maxLineSpan) }) { Rise(1) { if (soundMode) filters() else header() } }
|
||||
if (showHeader) item(key = if (soundMode) "filters" else "header", span = { GridItemSpan(maxLineSpan) }) { Rise(1) { if (soundMode) filters() else header() } }
|
||||
for ((store, line) in syncing) item(key = "sync-${store.id}", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(store.shortLabel + " · " + line, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
@@ -882,6 +883,12 @@ private fun LibraryHeader(
|
||||
clearSearchFocus = searchCleared, inlineWhenStacked = true,
|
||||
lead = soundLead,
|
||||
) {
|
||||
if (!soundMode && !s.shortcutPicker && source == Store.BATTLENET.id) {
|
||||
SecondaryButton(
|
||||
stringResource(R.string.bnet_open), enabled = !s.busy && DevPreview.library == LibraryPreview.OFF,
|
||||
compact = true, modifier = Modifier.testTag("library-battlenet-open"), onClick = a.onBattleNet,
|
||||
)
|
||||
}
|
||||
if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onClick = onCollections)
|
||||
if (!soundMode && DeveloperTools.on && DevPreview.shortcuts) LibraryPreviewButton()
|
||||
DisplayButton()
|
||||
|
||||
@@ -27,7 +27,7 @@ internal object DeveloperTools {
|
||||
internal object NavTabs {
|
||||
const val MORE = "more"
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
|
||||
val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
|
||||
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "agent")
|
||||
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
||||
|
||||
@@ -315,6 +315,7 @@ class DrawerActions(
|
||||
val onOsc: (String) -> Unit,
|
||||
val onEditSteamTouch: (() -> Unit)? = null,
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val onControllerSize: (Int) -> Unit = {},
|
||||
val onRumble: (Boolean) -> Unit = {},
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
|
||||
@@ -749,9 +750,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
type, chipModifier = focus.track(page, "pad-type"), onPick = a.onPadType)
|
||||
}
|
||||
a.controller?.let { c ->
|
||||
SliderRow(stringResource(R.string.ctrl_size), null, c.size, 80..125, step = 5,
|
||||
format = { "$it%" }, modifier = focus.track(page, "controller-size"),
|
||||
onChange = a.onControllerSize)
|
||||
ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble,
|
||||
chipModifier = focus.track(page, "rumble"), onChange = a.onRumble)
|
||||
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_touchscreen)) {
|
||||
|
||||
@@ -966,7 +966,7 @@
|
||||
<string name="diagnostics_share_games">Games and compatibility</string>
|
||||
<string name="diagnostics_share_all">All bundles</string>
|
||||
<string name="setup_game_debug_logs">Game debug logs</string>
|
||||
<string name="setup_game_debug_logs_hint">Include Proton, Wine and graphics diagnostics on the next game launch. Can reduce performance and use more storage.</string>
|
||||
<string name="setup_game_debug_logs_hint">Include Proton, Wine and graphics diagnostics on the next game launch. Turns itself off when that session ends. Can reduce performance and use more storage.</string>
|
||||
<string name="setup_game_debug_logs_restart">Restart this session to save game debug logs</string>
|
||||
<string name="setup_logging_update_failed">Couldn\'t update logging. Check the switch and try again.</string>
|
||||
<string name="setup_agent_commands">Debugging tools</string>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::Mutex;
|
||||
@@ -17,7 +18,6 @@ use super::net;
|
||||
use super::zip::{self, Entry};
|
||||
use crate::amazon::install::check::{free_bytes, space_problem};
|
||||
use crate::amazon::install::{Events, ReplaceGate, Stop};
|
||||
use crate::grow_write::{holes_supported, is_cancel, GrowFront};
|
||||
use crate::fetch_core::{distinct_host_count, run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
|
||||
|
||||
pub const LEDGER: &str = ".droiddeck-ea-files";
|
||||
@@ -37,7 +37,6 @@ struct Split {
|
||||
file: Mutex<Option<File>>,
|
||||
received: Vec<AtomicU64>,
|
||||
left: AtomicUsize,
|
||||
front: GrowFront,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -484,16 +483,9 @@ impl Placer<'_> {
|
||||
let old = split.received[part].swap(0, Ordering::Relaxed);
|
||||
self.in_flight.fetch_sub(old, Ordering::Relaxed);
|
||||
}
|
||||
split
|
||||
.front
|
||||
.write_all_at(handle, start + offset, data, self.stop)
|
||||
.map_err(|e| {
|
||||
if is_cancel(&e) {
|
||||
SinkError::Retry(format!("{}: cancelled", job.path))
|
||||
} else {
|
||||
SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path)))
|
||||
}
|
||||
})?;
|
||||
handle
|
||||
.write_all_at(data, start + offset)
|
||||
.map_err(|e| SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path))))?;
|
||||
drop(file);
|
||||
split.received[part].fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
self.in_flight.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
@@ -706,7 +698,6 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
|
||||
let host = origin(&req.url);
|
||||
let works = works(&remote, req.part_bytes);
|
||||
let holes = holes_supported(&req.game_dir);
|
||||
let splits: Vec<Option<Split>> = remote
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -720,7 +711,6 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
file: Mutex::new(None),
|
||||
received: (0..parts).map(|_| AtomicU64::new(0)).collect(),
|
||||
left: AtomicUsize::new(parts),
|
||||
front: GrowFront::new(holes),
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -807,13 +797,13 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
return Err(Stop::Failed(message));
|
||||
}
|
||||
if !placed_all {
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
if let Some(error) = outcome.as_ref().and_then(|o| o.error.clone()) {
|
||||
ev.log(&format!("download failed: {error}"));
|
||||
return Err(Stop::Failed("A file failed to download".into()));
|
||||
}
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
return Err(Stop::Failed("The download ended before every file was written".into()));
|
||||
}
|
||||
|
||||
|
||||
@@ -21,14 +21,7 @@ fn rejects_third_party_managed_install_before_manifest_parsing() {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Misses {
|
||||
seen: AtomicUsize,
|
||||
cancel_at: usize,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>, misses: Arc<Misses>) -> String {
|
||||
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let files = Arc::new(files);
|
||||
@@ -37,14 +30,13 @@ fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>, misses: Arc<Mi
|
||||
let Ok(stream) = stream else { continue };
|
||||
let files = Arc::clone(&files);
|
||||
let hits = Arc::clone(&hits);
|
||||
let misses = Arc::clone(&misses);
|
||||
std::thread::spawn(move || answer(stream, &files, &hits, &misses));
|
||||
std::thread::spawn(move || answer(stream, &files, &hits));
|
||||
}
|
||||
});
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize, misses: &Misses) {
|
||||
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize) {
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut first = String::new();
|
||||
if reader.read_line(&mut first).is_err() {
|
||||
@@ -62,13 +54,7 @@ fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &Atomic
|
||||
hits.fetch_add(1, Ordering::Relaxed);
|
||||
let (status, body) = match files.get(&path) {
|
||||
Some(b) => ("200 OK", b.clone()),
|
||||
None => {
|
||||
if misses.seen.fetch_add(1, Ordering::SeqCst) + 1 == misses.cancel_at {
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
misses.cancel.store(true, Ordering::SeqCst);
|
||||
}
|
||||
("404 Not Found", Vec::new())
|
||||
}
|
||||
None => ("404 Not Found", Vec::new()),
|
||||
};
|
||||
let head = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
|
||||
let _ = stream.write_all(head.as_bytes());
|
||||
@@ -120,10 +106,6 @@ fn pattern(seed: u8, len: usize) -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
fixture_missing(false, Arc::new(Misses::default()))
|
||||
}
|
||||
|
||||
fn fixture_missing(last_chunk: bool, misses: Arc<Misses>) -> Fixture {
|
||||
let mut c1 = chunk(1, 4096);
|
||||
let mut c2 = chunk(2, 2048);
|
||||
let mut c3 = chunk(3, 1000);
|
||||
@@ -186,13 +168,10 @@ fn fixture_missing(last_chunk: bool, misses: Arc<Misses>) -> Fixture {
|
||||
let mut served = HashMap::new();
|
||||
served.insert("/Builds/x/test.manifest".to_string(), manifest_bytes);
|
||||
for (info, data) in [(&c1, &d1), (&c2, &d2), (&c3, &d3)] {
|
||||
if last_chunk && info.guid == c3.guid {
|
||||
continue;
|
||||
}
|
||||
served.insert(format!("/Builds/x/{}", parsed.chunk_path(info)), encode(data, true));
|
||||
}
|
||||
let hits = Arc::new(AtomicUsize::new(0));
|
||||
let base = serve(served, Arc::clone(&hits), misses);
|
||||
let base = serve(served, Arc::clone(&hits));
|
||||
Fixture {
|
||||
base,
|
||||
hits,
|
||||
@@ -294,40 +273,6 @@ fn a_cancelled_run_reports_cancel() {
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
fn kept_c(fx: &Fixture, game: &Path) -> bool {
|
||||
let c = &fx.expected[1].1;
|
||||
let partial = game.join(staging::DIR_NAME).join(staging::partial_name("b/c.bin", c.len() as u64, Some(Sha1::digest(c).into())));
|
||||
partial.is_file() && staging::list_path(&partial).is_file()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_that_cannot_be_fetched_fails_and_keeps_written_parts() {
|
||||
let misses = Arc::new(Misses::default());
|
||||
let fx = fixture_missing(true, Arc::clone(&misses));
|
||||
let game = temp_game("fetch-fail");
|
||||
let cancel = AtomicBool::new(false);
|
||||
let err = run(&request(&fx, &game), &cancel, &Recorder::default()).unwrap_err();
|
||||
assert!(matches!(&err, Stop::Failed(m) if m.starts_with("Download failed: ")), "{err:?}");
|
||||
assert_eq!(misses.seen.load(Ordering::SeqCst), crate::fetch_core::MAX_ITEM_ATTEMPTS as usize);
|
||||
assert!(kept_c(&fx, &game));
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_during_the_last_fetch_attempt_reports_cancel_and_keeps_written_parts() {
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let last = crate::fetch_core::MAX_ITEM_ATTEMPTS as usize;
|
||||
let misses = Arc::new(Misses { seen: AtomicUsize::new(0), cancel_at: last, cancel: Arc::clone(&cancel) });
|
||||
let fx = fixture_missing(true, Arc::clone(&misses));
|
||||
let game = temp_game("fetch-cancel");
|
||||
let events = Recorder::default();
|
||||
assert_eq!(run(&request(&fx, &game), &cancel, &events).unwrap_err(), Stop::Cancelled);
|
||||
assert_eq!(misses.seen.load(Ordering::SeqCst), last);
|
||||
assert!(events.logs.lock().unwrap().iter().any(|l| l.contains(&format!("failed after {last} attempts"))));
|
||||
assert!(kept_c(&fx, &game));
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
fn place_partial(fx: &Fixture, game: &Path, data: &[u8], list: &str) -> PathBuf {
|
||||
let stage = staging::recover(game).unwrap();
|
||||
let a = &fx.expected[0].1;
|
||||
|
||||
@@ -8,7 +8,6 @@ use std::time::{Duration, Instant};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
use super::cache;
|
||||
use crate::grow_write::{holes_supported, is_cancel, GrowFront};
|
||||
use super::schedule::{PlanPart, Schedule, NONE};
|
||||
use super::{staging, Events, Stop};
|
||||
use crate::epic::chunk;
|
||||
@@ -81,7 +80,6 @@ struct Coord {
|
||||
struct Engine<'a> {
|
||||
input: &'a EngineInput<'a>,
|
||||
slots: Vec<Mutex<Slot>>,
|
||||
fronts: Vec<GrowFront>,
|
||||
coord: Mutex<Coord>,
|
||||
wake: Condvar,
|
||||
admitted: AtomicUsize,
|
||||
@@ -97,17 +95,6 @@ struct Engine<'a> {
|
||||
total_bytes: u64,
|
||||
}
|
||||
|
||||
enum Halt {
|
||||
Cancelled,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl From<String> for Halt {
|
||||
fn from(message: String) -> Self {
|
||||
Halt::Failed(message)
|
||||
}
|
||||
}
|
||||
|
||||
enum Source<'d> {
|
||||
Memory(&'d [u8]),
|
||||
Cache(PathBuf),
|
||||
@@ -125,13 +112,6 @@ impl<'a> Engine<'a> {
|
||||
message
|
||||
}
|
||||
|
||||
fn sink_error(&self, halt: Halt) -> SinkError {
|
||||
match halt {
|
||||
Halt::Cancelled => SinkError::Retry("cancelled".into()),
|
||||
Halt::Failed(message) => SinkError::Fatal(self.fail(message)),
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_path(&self, producer: usize) -> PathBuf {
|
||||
let p = &self.input.schedule.producers[producer];
|
||||
let info = &self.input.manifest.chunks[p.chunk as usize];
|
||||
@@ -178,7 +158,7 @@ impl<'a> Engine<'a> {
|
||||
self.input.schedule.producers[fetch[at] as usize].anchor as usize + 1
|
||||
}
|
||||
|
||||
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), Halt> {
|
||||
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), String> {
|
||||
let schedule = &self.input.schedule;
|
||||
let f = schedule.use_file[u] as usize;
|
||||
let j = u - schedule.file_start[f] as usize;
|
||||
@@ -195,22 +175,16 @@ impl<'a> Engine<'a> {
|
||||
let start = part.chunk_offset as usize;
|
||||
let end = start + part.size as usize;
|
||||
if end > data.len() {
|
||||
return Err(format!("A chunk is too short for {}", file.path).into());
|
||||
return Err(format!("A chunk is too short for {}", file.path));
|
||||
}
|
||||
let piece = &data[start..end];
|
||||
let handle = self.slots[f].lock().expect("slot lock").file.clone();
|
||||
let Some(handle) = handle else {
|
||||
return Err(format!("internal: {} is not open", file.path).into());
|
||||
return Err(format!("internal: {} is not open", file.path));
|
||||
};
|
||||
self.fronts[f]
|
||||
.write_all_at(&handle, part.file_offset, piece, self.stop)
|
||||
.map_err(|e| {
|
||||
if is_cancel(&e) {
|
||||
Halt::Cancelled
|
||||
} else {
|
||||
Halt::Failed(format!("Could not assemble or atomically replace {}: {e}", file.path))
|
||||
}
|
||||
})?;
|
||||
handle
|
||||
.write_all_at(piece, part.file_offset)
|
||||
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
|
||||
self.written.fetch_add(piece.len() as u64, Ordering::Relaxed);
|
||||
|
||||
let complete = {
|
||||
@@ -369,18 +343,14 @@ impl<'a> Engine<'a> {
|
||||
}
|
||||
};
|
||||
let Some(f) = candidate else { continue };
|
||||
match self.admit(f) {
|
||||
Ok(()) => {}
|
||||
Err(Halt::Cancelled) => return,
|
||||
Err(Halt::Failed(e)) => {
|
||||
self.fail(e);
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self.admit(f) {
|
||||
self.fail(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn admit(&self, f: usize) -> Result<(), Halt> {
|
||||
fn admit(&self, f: usize) -> Result<(), String> {
|
||||
self.open_stage(f)?;
|
||||
let schedule = &self.input.schedule;
|
||||
let file = &self.input.files[f];
|
||||
@@ -445,7 +415,7 @@ impl<'a> Engine<'a> {
|
||||
out
|
||||
};
|
||||
for u in claims {
|
||||
self.write_use(u, &Source::Memory(&data)).map_err(|h| self.sink_error(h))?;
|
||||
self.write_use(u, &Source::Memory(&data)).map_err(|e| SinkError::Fatal(self.fail(e)))?;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
@@ -476,10 +446,8 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
cached[i] = true;
|
||||
}
|
||||
}
|
||||
let holes = holes_supported(&input.stage_dir);
|
||||
let engine = Engine {
|
||||
input,
|
||||
fronts: input.files.iter().map(|_| GrowFront::new(holes)).collect(),
|
||||
slots: input
|
||||
.files
|
||||
.iter()
|
||||
@@ -564,7 +532,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
}
|
||||
ready
|
||||
};
|
||||
let (outcome, cancelled) = std::thread::scope(|scope| {
|
||||
let outcome = std::thread::scope(|scope| {
|
||||
let admitter = std::thread::Builder::new()
|
||||
.name("epic-admit".into())
|
||||
.spawn_scoped(scope, || {
|
||||
@@ -573,7 +541,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
});
|
||||
if let Err(e) = admitter {
|
||||
engine.fail(format!("could not start the install thread: {e}"));
|
||||
return (None, false);
|
||||
return None;
|
||||
}
|
||||
let outcome = if items.is_empty() {
|
||||
None
|
||||
@@ -584,9 +552,11 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
let mut c = engine.coord.lock().expect("coord lock");
|
||||
c.fetch_done = true;
|
||||
}
|
||||
let cancelled = settle(outcome.as_ref().is_some_and(|o| !o.ok()), stop);
|
||||
if outcome.as_ref().is_some_and(|o| !o.ok()) {
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
engine.wake.notify_all();
|
||||
(outcome, cancelled)
|
||||
outcome
|
||||
});
|
||||
|
||||
let failure = engine.failure.lock().expect("failure lock").take().filter(|m| !m.is_empty());
|
||||
@@ -623,35 +593,16 @@ fetches={} refetches={} peak_cache_mib={} hosts={}",
|
||||
hosts.join(","),
|
||||
));
|
||||
|
||||
ending(failure, complete, fetch_error, cancelled, stop.load(Ordering::SeqCst))?;
|
||||
Ok(Stats { bytes_written: written, files_written: input.files.len() })
|
||||
}
|
||||
|
||||
fn settle(fetch_failed: bool, stop: &AtomicBool) -> bool {
|
||||
let cancelled = stop.load(Ordering::SeqCst);
|
||||
if fetch_failed {
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
cancelled
|
||||
}
|
||||
|
||||
fn ending(
|
||||
failure: Option<String>,
|
||||
complete: bool,
|
||||
fetch_error: Option<String>,
|
||||
cancelled: bool,
|
||||
stopped: bool,
|
||||
) -> Result<(), Stop> {
|
||||
if let Some(message) = failure {
|
||||
return Err(Stop::Failed(message));
|
||||
}
|
||||
if complete {
|
||||
return Ok(());
|
||||
return Ok(Stats { bytes_written: written, files_written: input.files.len() });
|
||||
}
|
||||
if let Some(message) = fetch_error.filter(|_| !cancelled) {
|
||||
if let Some(message) = fetch_error {
|
||||
return Err(Stop::Failed(format!("Download failed: {}", tidy_fetch_error(&message))));
|
||||
}
|
||||
if stopped {
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
Err(Stop::Failed("The download ended before every file was written".into()))
|
||||
@@ -753,37 +704,4 @@ mod tests {
|
||||
assert_eq!(fs::read_to_string(staging::list_path(&kept)).unwrap(), "10\n20\n");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn end(fetch_error: Option<&str>, stop: &AtomicBool) -> Result<(), Stop> {
|
||||
let cancelled = settle(fetch_error.is_some(), stop);
|
||||
ending(None, false, fetch_error.map(str::to_string), cancelled, stop.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_during_the_last_fetch_attempt_ends_as_cancelled() {
|
||||
let stop = AtomicBool::new(true);
|
||||
assert!(matches!(end(Some("timed out"), &stop), Err(Stop::Cancelled)));
|
||||
assert!(matches!(end(None, &stop), Err(Stop::Cancelled)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fetch_failure_without_a_cancel_ends_as_failed() {
|
||||
let stop = AtomicBool::new(false);
|
||||
match end(Some("timed out"), &stop) {
|
||||
Err(Stop::Failed(message)) => assert!(message.starts_with("Download failed: ")),
|
||||
_ => panic!("a fetch failure must be reported"),
|
||||
}
|
||||
assert!(stop.load(Ordering::SeqCst));
|
||||
let idle = AtomicBool::new(false);
|
||||
assert!(matches!(end(None, &idle), Err(Stop::Failed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_failure_or_a_finished_install_wins_over_a_cancel() {
|
||||
assert!(matches!(
|
||||
ending(Some("disk full".into()), false, None, true, true),
|
||||
Err(Stop::Failed(message)) if message == "disk full"
|
||||
));
|
||||
assert!(ending(None, true, Some("late".into()), true, true).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io;
|
||||
use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub const FILL_STEP: usize = 4 * 1024 * 1024;
|
||||
pub const DIRECT_GAP: u64 = 4 * 1024 * 1024;
|
||||
const PROBE_GAP: u64 = 1024 * 1024;
|
||||
static PROBE_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
const PROBE_PREFIX: &str = ".droiddeck-hole-probe-";
|
||||
|
||||
pub fn is_cancel(err: &io::Error) -> bool {
|
||||
err.kind() == io::ErrorKind::Interrupted
|
||||
}
|
||||
|
||||
pub fn holes_supported(dir: &Path) -> bool {
|
||||
let probe = dir.join(format!(
|
||||
"{PROBE_PREFIX}{}-{}",
|
||||
std::process::id(),
|
||||
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let Ok(file) = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(&probe)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let written = file.write_all_at(&[0u8], PROBE_GAP - 1);
|
||||
drop(file);
|
||||
let measured = written.and_then(|_| fs::symlink_metadata(&probe));
|
||||
let _ = fs::remove_file(&probe);
|
||||
measured
|
||||
.map(|meta| meta.blocks().saturating_mul(512) < PROBE_GAP)
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub struct GrowFront {
|
||||
holes: bool,
|
||||
size: AtomicU64,
|
||||
known: AtomicBool,
|
||||
fill: Mutex<()>,
|
||||
}
|
||||
|
||||
impl GrowFront {
|
||||
pub fn new(holes: bool) -> Self {
|
||||
GrowFront {
|
||||
holes,
|
||||
size: AtomicU64::new(0),
|
||||
known: AtomicBool::new(false),
|
||||
fill: Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&self) {
|
||||
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.known.store(false, Ordering::Release);
|
||||
self.size.store(0, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn write_all_at(
|
||||
&self,
|
||||
file: &File,
|
||||
offset: u64,
|
||||
data: &[u8],
|
||||
cancel: &AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
let end = offset.saturating_add(data.len() as u64);
|
||||
if self.holes
|
||||
|| (self.known.load(Ordering::Acquire) && end <= self.size.load(Ordering::Acquire))
|
||||
{
|
||||
return file.write_all_at(data, offset);
|
||||
}
|
||||
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut size = self.current(file)?;
|
||||
if offset > size.saturating_add(DIRECT_GAP) {
|
||||
self.fill_to(file, &mut size, offset - DIRECT_GAP, cancel)?;
|
||||
}
|
||||
if let Err(err) = file.write_all_at(data, offset) {
|
||||
self.known.store(false, Ordering::Release);
|
||||
return Err(err);
|
||||
}
|
||||
self.publish(size.max(end));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn extend_to(&self, file: &File, len: u64, cancel: &AtomicBool) -> io::Result<()> {
|
||||
if self.holes {
|
||||
return file.set_len(len);
|
||||
}
|
||||
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut size = self.current(file)?;
|
||||
if size < len {
|
||||
self.fill_to(file, &mut size, len, cancel)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn current(&self, file: &File) -> io::Result<u64> {
|
||||
if self.known.load(Ordering::Acquire) {
|
||||
Ok(self.size.load(Ordering::Acquire))
|
||||
} else {
|
||||
Ok(file.metadata()?.len())
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_to(
|
||||
&self,
|
||||
file: &File,
|
||||
size: &mut u64,
|
||||
target: u64,
|
||||
cancel: &AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
let zeros = vec![0u8; FILL_STEP];
|
||||
while *size < target {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
self.publish(*size);
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
}
|
||||
let step = ((target - *size) as usize).min(FILL_STEP);
|
||||
if let Err(err) = file.write_all_at(&zeros[..step], *size) {
|
||||
self.known.store(false, Ordering::Release);
|
||||
return Err(err);
|
||||
}
|
||||
*size += step as u64;
|
||||
self.publish(*size);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn publish(&self, size: u64) {
|
||||
self.size.store(size, Ordering::Release);
|
||||
self.known.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"grow-write-{tag}-{}-{}",
|
||||
std::process::id(),
|
||||
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> File {
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.truncate(false)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_write_fills_the_gap_in_bounded_steps_and_keeps_data() {
|
||||
let dir = temp_dir("far");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(false);
|
||||
let cancel = AtomicBool::new(false);
|
||||
front.write_all_at(&file, 0, b"head", &cancel).unwrap();
|
||||
let far = 3 * FILL_STEP as u64 + 123;
|
||||
front.write_all_at(&file, far, b"tail", &cancel).unwrap();
|
||||
front.write_all_at(&file, 100, b"mid", &cancel).unwrap();
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
assert_eq!(bytes.len() as u64, far + 4);
|
||||
assert_eq!(&bytes[0..4], b"head");
|
||||
assert_eq!(&bytes[100..103], b"mid");
|
||||
assert_eq!(&bytes[far as usize..], b"tail");
|
||||
assert!(bytes[103..far as usize].iter().all(|b| *b == 0));
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_stops_a_gap_fill_between_steps() {
|
||||
let dir = temp_dir("cancel");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(false);
|
||||
let cancel = AtomicBool::new(true);
|
||||
let err = front
|
||||
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::Interrupted);
|
||||
assert_eq!(fs::metadata(&path).unwrap().len(), 0);
|
||||
cancel.store(false, Ordering::Relaxed);
|
||||
front.write_all_at(&file, 10, b"ok", &cancel).unwrap();
|
||||
assert_eq!(&fs::read(&path).unwrap()[10..], b"ok");
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_writers_never_lose_data_to_the_fill() {
|
||||
let dir = temp_dir("race");
|
||||
let path = dir.join("f.bin");
|
||||
let file = Arc::new(open(&path));
|
||||
let front = Arc::new(GrowFront::new(false));
|
||||
let piece = 64 * 1024u64;
|
||||
let count = 256u64;
|
||||
let mut order: Vec<u64> = (0..count).collect();
|
||||
order.reverse();
|
||||
let lanes: Vec<Vec<u64>> = (0..4)
|
||||
.map(|lane| order.iter().copied().filter(|i| i % 4 == lane).collect())
|
||||
.collect();
|
||||
let handles: Vec<_> = lanes
|
||||
.into_iter()
|
||||
.map(|lane| {
|
||||
let file = Arc::clone(&file);
|
||||
let front = Arc::clone(&front);
|
||||
std::thread::spawn(move || {
|
||||
let cancel = AtomicBool::new(false);
|
||||
for i in lane {
|
||||
let data = vec![(i % 251) as u8 + 1; piece as usize];
|
||||
front.write_all_at(&file, i * piece, &data, &cancel).unwrap();
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for handle in handles {
|
||||
handle.join().unwrap();
|
||||
}
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
assert_eq!(bytes.len() as u64, piece * count);
|
||||
for i in 0..count {
|
||||
let start = (i * piece) as usize;
|
||||
assert!(bytes[start..start + piece as usize]
|
||||
.iter()
|
||||
.all(|b| *b == (i % 251) as u8 + 1));
|
||||
}
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_to_grows_in_steps_and_never_shrinks() {
|
||||
let dir = temp_dir("extend");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(false);
|
||||
let cancel = AtomicBool::new(false);
|
||||
front.write_all_at(&file, 0, b"data", &cancel).unwrap();
|
||||
let len = 2 * FILL_STEP as u64 + 7;
|
||||
front.extend_to(&file, len, &cancel).unwrap();
|
||||
front.extend_to(&file, 2, &cancel).unwrap();
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
assert_eq!(bytes.len() as u64, len);
|
||||
assert_eq!(&bytes[0..4], b"data");
|
||||
assert!(bytes[4..].iter().all(|b| *b == 0));
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hole_capable_storage_writes_directly() {
|
||||
let dir = temp_dir("holes");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(true);
|
||||
let cancel = AtomicBool::new(true);
|
||||
front
|
||||
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
|
||||
.unwrap();
|
||||
assert_eq!(fs::metadata(&path).unwrap().len(), 8 * FILL_STEP as u64 + 1);
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_leaves_nothing_behind() {
|
||||
let dir = temp_dir("probe");
|
||||
let other = dir.join(format!("{PROBE_PREFIX}game-file"));
|
||||
fs::write(&other, b"kept").unwrap();
|
||||
let _ = holes_supported(&dir);
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(fs::read(&other).unwrap(), b"kept");
|
||||
fs::remove_file(&other).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ pub mod epic;
|
||||
pub mod fetch_core;
|
||||
pub mod fetch_tuning;
|
||||
pub mod gog;
|
||||
pub mod grow_write;
|
||||
pub mod md5_small;
|
||||
pub mod priority;
|
||||
pub mod steam;
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
//! read back and checked before anything is fetched.
|
||||
|
||||
use crate::fetch_core::{run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
|
||||
use crate::grow_write::{holes_supported, GrowFront};
|
||||
use crate::steam::cdn;
|
||||
use crate::steam::content_manifest::{ChunkData, ContentManifest};
|
||||
use crate::steam::depot_chunk::{process_depot_chunk, steam_adler_hash};
|
||||
@@ -111,7 +110,6 @@ struct FileSlot {
|
||||
size: u64,
|
||||
path: PathBuf,
|
||||
mode: u32,
|
||||
front: GrowFront,
|
||||
}
|
||||
|
||||
struct DepotFiles {
|
||||
@@ -157,23 +155,17 @@ impl DepotFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn write(
|
||||
&self,
|
||||
file_idx: usize,
|
||||
offset: u64,
|
||||
data: &[u8],
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<(), String> {
|
||||
fn write(&self, file_idx: usize, offset: u64, data: &[u8]) -> Result<(), String> {
|
||||
let file = self.acquire(file_idx)?;
|
||||
let slot = &self.slots[file_idx];
|
||||
slot.front.write_all_at(&file, offset, data, cancel).map_err(|err| {
|
||||
pwrite_all_at(&file, offset, data).map_err(|err| {
|
||||
format!(
|
||||
"write '{}' at {offset}: {err}",
|
||||
self.slots[file_idx].path.display()
|
||||
)
|
||||
})?;
|
||||
let slot = &self.slots[file_idx];
|
||||
if slot.remaining.fetch_sub(1, Ordering::AcqRel) == 1 {
|
||||
finalize(&file, slot, cancel)?;
|
||||
finalize(&file, slot)?;
|
||||
drop(file);
|
||||
self.release(file_idx);
|
||||
} else if self.open_count.load(Ordering::Relaxed) > MAX_OPEN_FILES {
|
||||
@@ -184,7 +176,7 @@ impl DepotFiles {
|
||||
}
|
||||
|
||||
/// Files with nothing left to fetch (zero chunks, or every chunk already correct on disk).
|
||||
fn finalize_untouched(&self, idx: usize, cancel: &AtomicBool) -> Result<(), String> {
|
||||
fn finalize_untouched(&self, idx: usize) -> Result<(), String> {
|
||||
let slot = &self.slots[idx];
|
||||
make_parent_dirs(&self.root, &slot.path)?;
|
||||
check_file_target(&self.root, &slot.path)?;
|
||||
@@ -196,11 +188,6 @@ impl DepotFiles {
|
||||
.map_err(|err| format!("open '{}': {err}", slot.path.display()))?;
|
||||
set_file_mode(&file, &slot.path, slot.mode)?;
|
||||
let current = file.metadata().map(|m| m.len()).unwrap_or(u64::MAX);
|
||||
if current < slot.size {
|
||||
slot.front
|
||||
.extend_to(&file, slot.size, cancel)
|
||||
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
|
||||
}
|
||||
if current != slot.size {
|
||||
file.set_len(slot.size)
|
||||
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
|
||||
@@ -209,10 +196,7 @@ impl DepotFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize(file: &File, slot: &FileSlot, cancel: &AtomicBool) -> Result<(), String> {
|
||||
slot.front
|
||||
.extend_to(file, slot.size, cancel)
|
||||
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
|
||||
fn finalize(file: &File, slot: &FileSlot) -> Result<(), String> {
|
||||
file.set_len(slot.size)
|
||||
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
|
||||
file.sync_all()
|
||||
@@ -223,7 +207,6 @@ struct ChunkSink<'a> {
|
||||
chunks: &'a [UniqueChunk],
|
||||
files: &'a DepotFiles,
|
||||
depot_key: &'a [u8],
|
||||
cancel: &'a AtomicBool,
|
||||
}
|
||||
|
||||
impl FetchSink for ChunkSink<'_> {
|
||||
@@ -242,12 +225,7 @@ impl FetchSink for ChunkSink<'_> {
|
||||
let mut credited = 0u64;
|
||||
for target in &chunk.targets {
|
||||
self.files
|
||||
.write(
|
||||
target.file_idx as usize,
|
||||
target.offset,
|
||||
&processed.data,
|
||||
self.cancel,
|
||||
)
|
||||
.write(target.file_idx as usize, target.offset, &processed.data)
|
||||
.map_err(SinkError::Fatal)?;
|
||||
credited += processed.data.len() as u64;
|
||||
}
|
||||
@@ -298,7 +276,6 @@ fn prepare(
|
||||
}
|
||||
};
|
||||
|
||||
let holes = holes_supported(&root);
|
||||
let mut slots = Vec::with_capacity(manifest.files.len());
|
||||
let mut existing = Vec::with_capacity(manifest.files.len());
|
||||
for file in &manifest.files {
|
||||
@@ -320,7 +297,6 @@ fn prepare(
|
||||
} else {
|
||||
0o644
|
||||
},
|
||||
front: GrowFront::new(holes),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -378,10 +354,7 @@ fn prepare(
|
||||
continue;
|
||||
}
|
||||
let mut remaining = 0usize;
|
||||
let mut by_offset: Vec<usize> = (0..file.chunks.len()).collect();
|
||||
by_offset.sort_by_key(|&idx| file.chunks[idx].offset);
|
||||
for chunk_idx in by_offset {
|
||||
let chunk = &file.chunks[chunk_idx];
|
||||
for (chunk_idx, chunk) in file.chunks.iter().enumerate() {
|
||||
if verified[file_idx].get(chunk_idx).copied().unwrap_or(false) {
|
||||
bytes_verified += chunk.cb_original as u64;
|
||||
continue;
|
||||
@@ -420,13 +393,7 @@ fn prepare(
|
||||
if is_regular(file.flags, &file.linktarget)
|
||||
&& files.slots[idx].remaining.load(Ordering::Relaxed) == 0
|
||||
{
|
||||
if let Err(err) = files.finalize_untouched(idx, cancel) {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(DepotWriteOutcome {
|
||||
cancelled: true,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if let Err(err) = files.finalize_untouched(idx) {
|
||||
return Err(DepotWriteOutcome::fail(err));
|
||||
}
|
||||
}
|
||||
@@ -482,7 +449,6 @@ pub fn write_depot(
|
||||
chunks: &chunks,
|
||||
files: &files,
|
||||
depot_key: request.depot_key,
|
||||
cancel,
|
||||
};
|
||||
let depot_id = manifest.metadata.depot_id;
|
||||
let done_before = AtomicU64::new(bytes_verified);
|
||||
@@ -710,6 +676,12 @@ fn set_file_mode(_file: &File, _path: &Path, _mode: u32) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn pwrite_all_at(file: &File, offset: u64, data: &[u8]) -> std::io::Result<()> {
|
||||
use std::os::unix::fs::FileExt;
|
||||
file.write_all_at(data, offset)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn pread_exact_at(file: &File, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
|
||||
use std::os::unix::fs::FileExt;
|
||||
@@ -794,7 +766,6 @@ mod tests {
|
||||
size: 10,
|
||||
path: path.clone(),
|
||||
mode: 0o644,
|
||||
front: GrowFront::new(true),
|
||||
}];
|
||||
let root = fs::canonicalize(&dir).unwrap();
|
||||
let flags = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(false));
|
||||
@@ -837,44 +808,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queues_each_files_chunks_in_offset_order() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"droiddeck_steam_order_{}",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let key = [5u8; 32];
|
||||
let manifest = ContentManifest {
|
||||
files: vec![FileMapping {
|
||||
filename: "big.pak".into(),
|
||||
size: 15,
|
||||
chunks: vec![chunk(b"three", 10), chunk(b"first", 0), chunk(b"other", 5)],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let request = DepotWriteRequest {
|
||||
manifest: &manifest,
|
||||
depot_key: &key,
|
||||
servers: &[],
|
||||
target_dir: &dir,
|
||||
ca_bundle_path: "",
|
||||
max_workers: 1,
|
||||
process_workers: 1,
|
||||
};
|
||||
let prepared = prepare(&request, &AtomicBool::new(false)).unwrap();
|
||||
let offsets: Vec<u64> = prepared
|
||||
.chunks
|
||||
.iter()
|
||||
.map(|c| c.targets[0].offset)
|
||||
.collect();
|
||||
assert_eq!(offsets, vec![0, 5, 10]);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_in_place_dedupes_chunks_and_resumes_from_disk() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
@@ -934,7 +867,6 @@ mod tests {
|
||||
chunks: &prepared.chunks,
|
||||
files: &prepared.files,
|
||||
depot_key: &key,
|
||||
cancel: &cancel,
|
||||
};
|
||||
let item = |id: u64| FetchItem {
|
||||
id,
|
||||
@@ -954,7 +886,6 @@ mod tests {
|
||||
chunks: &wrong,
|
||||
files: &prepared.files,
|
||||
depot_key: &key,
|
||||
cancel: &cancel,
|
||||
};
|
||||
assert!(matches!(
|
||||
wrong_sink.process(&item(0), encrypted_chunk(&key, b"HELLO")),
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class AgentSetupInstallScriptTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun run(updateSucceedsOnCall: Int): Pair<Int, List<String>> {
|
||||
val sh = listOf("/bin/sh", "/usr/bin/sh").firstOrNull { File(it).canExecute() }
|
||||
assumeTrue(sh != null)
|
||||
val bin = tmp.newFolder("bin")
|
||||
val calls = File(tmp.root, "calls")
|
||||
fun tool(name: String, body: String) = File(bin, name).apply { writeText("#!/bin/sh\n$body\n"); setExecutable(true) }
|
||||
tool("dpkg", "exit 0")
|
||||
tool("sleep", "exit 0")
|
||||
tool("apt-get", """
|
||||
echo "${'$'}*" >> '${calls.path}'
|
||||
case "${'$'}*" in
|
||||
*" update "*) n=${'$'}(grep -c ' update ' '${calls.path}'); [ "${'$'}n" -ge $updateSucceedsOnCall ] ;;
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
""".trimIndent())
|
||||
val child = ProcessBuilder(sh, "-c", AgentSetup.installScript("echo harness-installed >> '${calls.path}'"))
|
||||
.apply { environment()["PATH"] = bin.path + File.pathSeparator + System.getenv("PATH") }
|
||||
.redirectErrorStream(true).start()
|
||||
child.inputStream.readBytes()
|
||||
val exit = child.waitFor()
|
||||
return exit to (if (calls.exists()) calls.readLines() else emptyList())
|
||||
}
|
||||
|
||||
@Test fun theInstallStopsWhenEveryUpdateAttemptFails() {
|
||||
val (exit, calls) = run(updateSucceedsOnCall = 99)
|
||||
assertTrue(exit != 0)
|
||||
assertEquals(3, calls.count { " update " in "$it " })
|
||||
assertTrue(calls.none { "install" in it })
|
||||
}
|
||||
|
||||
@Test fun theInstallContinuesWhenALaterUpdateAttemptSucceeds() {
|
||||
val (exit, calls) = run(updateSucceedsOnCall = 3)
|
||||
assertEquals(0, exit)
|
||||
assertTrue(calls.any { "install -y --no-install-recommends" in it })
|
||||
assertTrue("harness-installed" in calls.last())
|
||||
}
|
||||
}
|
||||
@@ -34,8 +34,8 @@ class DroidDeckHudPanelTest {
|
||||
assertEquals(DroidDeckHudSize.MINIMAL, DroidDeckHudSize.from(DroidDeckHudConfig.DEFAULTS["hudSize"]))
|
||||
}
|
||||
|
||||
@Test fun theHudStartsLocked() {
|
||||
assertEquals("1", DroidDeckHudConfig.DEFAULTS["hudLocked"])
|
||||
@Test fun theHudStartsUnlocked() {
|
||||
assertEquals("0", DroidDeckHudConfig.DEFAULTS["hudLocked"])
|
||||
}
|
||||
|
||||
@Test fun aLongPressCollapsesTheHudUnlessTheUserChoseToLockWithIt() {
|
||||
|
||||
@@ -96,6 +96,115 @@ class OnScreenLayoutTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun changingControllerSizeRegeneratesAnUneditedBuiltInLandscapeOverlay() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val layout = gamepad()
|
||||
val w = 1200
|
||||
val h = 540
|
||||
ControllerPrefs.setSize(context, 100)
|
||||
val original = OnScreenLayout.elements(context, layout, w, h, Rect())
|
||||
ControllerPrefs.setSize(context, 115)
|
||||
val resized = OnScreenLayout.elements(context, layout, w, h, Rect())
|
||||
assertNotEquals(original.single { it.id == "legacy:a" }.width, resized.single { it.id == "legacy:a" }.width, .0001f)
|
||||
assertNotEquals(original.single { it.id == "legacy:ls" }.height, resized.single { it.id == "legacy:ls" }.height, .0001f)
|
||||
}
|
||||
|
||||
@Test fun unchangedSizeDoesNotCollapseCoincidentEditedPortraitControls() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val stock = gamepad()
|
||||
val coincident = stock.elements.map { element ->
|
||||
if (element.id == "legacy:a" || element.id == "legacy:b") {
|
||||
element.copy(x = .2f, y = .2f, width = .1f, height = .1f)
|
||||
} else element
|
||||
}
|
||||
val edited = stock.copy(elements = coincident, aspect = .5f)
|
||||
ControllerPrefs.setSize(context, 100)
|
||||
val placed = OnScreenLayout.elements(
|
||||
context, edited, 540, 1080, Rect(),
|
||||
dock = OnScreenLayout.Dock(true, false),
|
||||
)
|
||||
assertTrue(placed.at(InputControl.A).width > 0f)
|
||||
assertTrue(placed.at(InputControl.B).width > 0f)
|
||||
}
|
||||
|
||||
@Test fun changingControllerSizeResizesDefaultDockedControlsWithoutASavedLayout() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val layout = gamepad()
|
||||
val w = 1200
|
||||
val h = 540
|
||||
val dock = OnScreenLayout.Dock(false, false)
|
||||
ControllerPrefs.setSize(context, 100)
|
||||
val original = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock)
|
||||
ControllerPrefs.setSize(context, 125)
|
||||
val resized = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock)
|
||||
assertNotEquals(original.at(InputControl.LS).width, resized.at(InputControl.LS).width, .0001f)
|
||||
assertNotEquals(original.at(InputControl.A).height, resized.at(InputControl.A).height, .0001f)
|
||||
assertInside(resized, w, h)
|
||||
}
|
||||
|
||||
@Test fun changingControllerSizeRegeneratesSavedLandscapeBuiltInOverlay() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val layout = gamepad().copy(aspect = 2f)
|
||||
val w = 1200
|
||||
val h = 540
|
||||
ControllerPrefs.setSize(context, 100)
|
||||
val original = OnScreenLayout.elements(context, layout, w, h, Rect())
|
||||
ControllerPrefs.setSize(context, 125)
|
||||
val resized = OnScreenLayout.elements(context, layout, w, h, Rect())
|
||||
assertNotEquals(original.at(InputControl.A).width, resized.at(InputControl.A).width, .0001f)
|
||||
}
|
||||
|
||||
@Test fun enlargedDefaultDockedControlsDoNotOverlapTheActionButtonAndRightStick() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
ControllerPrefs.setSize(context, 125)
|
||||
val placed = OnScreenLayout.elements(
|
||||
context, gamepad(), 1200, 540, Rect(),
|
||||
dock = OnScreenLayout.Dock(false, false),
|
||||
)
|
||||
val stick = placed.at(InputControl.RS)
|
||||
val button = placed.at(InputControl.A)
|
||||
val overlapX = minOf(stick.x + stick.width, button.x + button.width) - maxOf(stick.x, button.x)
|
||||
val overlapY = minOf(stick.y + stick.height, button.y + button.height) - maxOf(stick.y, button.y)
|
||||
assertFalse("RS and A hit rectangles must not overlap", overlapX > 0f && overlapY > 0f)
|
||||
}
|
||||
|
||||
@Test fun changingControllerSizeResizesDockedControlsWithASavedLayout() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val layout = gamepad()
|
||||
val w = 1200
|
||||
val h = 540
|
||||
ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (.12f to .7f)))
|
||||
val dock = OnScreenLayout.Dock(false, false)
|
||||
ControllerPrefs.setSize(context, 100)
|
||||
val original = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock)
|
||||
ControllerPrefs.setSize(context, 120)
|
||||
val resized = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock)
|
||||
val before = original.single { it.id == "legacy:a" }
|
||||
val after = resized.single { it.id == "legacy:a" }
|
||||
assertTrue(after.width > before.width)
|
||||
assertTrue(after.height > before.height)
|
||||
assertEquals(before.x + before.width / 2f, after.x + after.width / 2f, .001f)
|
||||
assertEquals(before.y + before.height / 2f, after.y + after.height / 2f, .001f)
|
||||
assertEquals(mapOf("ls" to (.12f to .7f)), ControllerPrefs.layout(context, w, h))
|
||||
}
|
||||
|
||||
@Test fun enlargedDockedControlsStayInsideSafeAreaAndKeepShoulderGaps() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val w = 1080
|
||||
val h = 200
|
||||
val safe = Rect(20, 0, 20, 24)
|
||||
ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (.12f to .7f)))
|
||||
ControllerPrefs.setSize(context, 125)
|
||||
val placed = OnScreenLayout.elements(context, gamepad(), w, h, safe, dock = OnScreenLayout.Dock(false, false))
|
||||
assertInside(placed, w, h, safe)
|
||||
for ((left, right) in listOf(InputControl.LT to InputControl.LB, InputControl.RB to InputControl.RT)) {
|
||||
val a = placed.single { it.control == left }
|
||||
val b = placed.single { it.control == right }
|
||||
assertTrue("$left should remain left of $right", a.x + a.width <= b.x)
|
||||
assertTrue("$left and $right should retain a gap", (b.x - a.x - a.width) * w >= 3.5f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
|
||||
fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
|
||||
@@ -574,6 +683,12 @@ class OnScreenLayoutTest {
|
||||
val normal = at(1f)
|
||||
for (scale in listOf(.8f, 1.25f)) {
|
||||
val placed = at(scale)
|
||||
for (control in listOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y, InputControl.LS, InputControl.RS)) {
|
||||
val before = normal.at(control)
|
||||
val after = placed.at(control)
|
||||
assertEquals("$kit $scale ${control.id} aspect ratio", before.width / before.height,
|
||||
after.width / after.height, .02f)
|
||||
}
|
||||
assertEquals("$kit $scale", normal.at(InputControl.A).width * scale, placed.at(InputControl.A).width, .002f)
|
||||
assertEquals("$kit $scale", normal.at(InputControl.LS).height * scale, placed.at(InputControl.LS).height, .002f)
|
||||
if (scale > 1f) for (cluster in listOf(face, dpad)) {
|
||||
@@ -699,4 +814,34 @@ class OnScreenLayoutTest {
|
||||
assertFalse(kit.artwork(layout.elements.first { it.control == InputControl.A }.copy(image = "picture")))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dockedSizeAppliesWithoutAKitAndToThePortraitCluster() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
|
||||
val stock = gamepad()
|
||||
val dock = OnScreenLayout.Dock(false, false)
|
||||
|
||||
ControllerPrefs.setSize(context, 100)
|
||||
val defaultNormal = OnScreenLayout.elements(context, stock, 1200, 540, Rect(), dock = dock)
|
||||
ControllerPrefs.setSize(context, 125)
|
||||
val defaultLarge = OnScreenLayout.elements(context, stock, 1200, 540, Rect(), dock = dock)
|
||||
assertTrue(defaultLarge.at(InputControl.A).width > defaultNormal.at(InputControl.A).width)
|
||||
|
||||
val portraitEdited = stock.copy(
|
||||
elements = stock.elements.map {
|
||||
if (it.control == InputControl.A) it.copy(x = it.x + .07f) else it
|
||||
},
|
||||
aspect = .5f,
|
||||
)
|
||||
val portraitDock = OnScreenLayout.Dock(true, false)
|
||||
ControllerPrefs.setSize(context, 100)
|
||||
val clusterNormal = OnScreenLayout.elements(
|
||||
context, portraitEdited, 540, 1200, Rect(), dock = portraitDock,
|
||||
)
|
||||
ControllerPrefs.setSize(context, 125)
|
||||
val clusterLarge = OnScreenLayout.elements(
|
||||
context, portraitEdited, 540, 1200, Rect(), dock = portraitDock,
|
||||
)
|
||||
assertTrue(clusterLarge.at(InputControl.A).width > clusterNormal.at(InputControl.A).width)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.os.Looper
|
||||
import android.view.View
|
||||
import com.droiddeck.launcher.ui.BuildWatermark
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.ConscryptMode
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@ConscryptMode(ConscryptMode.Mode.OFF)
|
||||
@GraphicsMode(GraphicsMode.Mode.LEGACY)
|
||||
@Config(sdk = [34], manifest = Config.NONE, application = Application::class)
|
||||
class GameDebugLogsExpiryTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private val prefs get() = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
@Before fun reset() {
|
||||
SessionPaths.take()
|
||||
prefs.edit().clear().commit()
|
||||
listOf("build-watermark", "build-watermark.lock").forEach { File(context.filesDir, it).delete() }
|
||||
}
|
||||
|
||||
@After fun end() {
|
||||
SessionPaths.take()
|
||||
}
|
||||
|
||||
private fun setDebugLogs(on: Boolean) = prefs.edit().putBoolean("gameDebugLogsEnabled", on).commit()
|
||||
|
||||
@Test fun settingTurnsOffWhenTheSessionItStartedWithEnds() {
|
||||
setDebugLogs(true)
|
||||
SessionPaths.beginOrCurrent(context, "steam")
|
||||
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
|
||||
SessionPaths.take()
|
||||
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
|
||||
}
|
||||
|
||||
@Test fun settingStaysOnForTheSessionRunningWhenItWasEnabled() {
|
||||
SessionPaths.beginOrCurrent(context, "steam")
|
||||
setDebugLogs(true)
|
||||
SessionPaths.take()
|
||||
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
|
||||
SessionPaths.beginOrCurrent(context, "steam")
|
||||
SessionPaths.take()
|
||||
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
|
||||
}
|
||||
|
||||
@Test fun settingThatWasOffStaysOff() {
|
||||
SessionPaths.beginOrCurrent(context, "steam")
|
||||
SessionPaths.take()
|
||||
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
|
||||
}
|
||||
|
||||
@Test fun badgeShowsWhileOnEvenWithTheBuildWatermarkOff() {
|
||||
BuildWatermark.install(context)
|
||||
SessionPrefs.setBuildWatermarkEnabled(context, false)
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup()
|
||||
try {
|
||||
assertNull(activity.get().window.decorView.findViewWithTag<View>("build-watermark"))
|
||||
setDebugLogs(true)
|
||||
BuildWatermarkSetting.notifyChanged(context)
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertNotNull(activity.get().window.decorView.findViewWithTag<View>("build-watermark"))
|
||||
SessionPaths.beginOrCurrent(context, "steam")
|
||||
SessionPaths.take()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertNull(activity.get().window.decorView.findViewWithTag<View>("build-watermark"))
|
||||
} finally {
|
||||
activity.pause().stop().destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -188,34 +188,6 @@ class DownloadQueueRemovalTest {
|
||||
assertFalse(folder.exists())
|
||||
}
|
||||
|
||||
@Test fun uninstallStopsARunningDownloadThenRemovesTheGame() {
|
||||
val running = CountDownLatch(1)
|
||||
val cancels = AtomicInteger()
|
||||
val entry = DownloadEntry(Store.GOG, "uninstall-while-running", "Running")
|
||||
DownloadQueue.enqueue(app, entry) {
|
||||
object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
running.countDown()
|
||||
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(10)
|
||||
while (!handle.isCancelled && System.nanoTime() < until) Thread.sleep(10)
|
||||
return null
|
||||
}
|
||||
override fun cancel(deleteFiles: Boolean) { cancels.incrementAndGet() }
|
||||
}
|
||||
}
|
||||
assertTrue(running.await(5, TimeUnit.SECONDS))
|
||||
val folder = File(app.filesDir, "uninstall-while-running").apply { mkdirs() }
|
||||
File(folder, "game.bin").writeText("x")
|
||||
val game = InstalledStoreGame(StoreGameSidecar(Store.GOG, "uninstall-while-running", "Running", exe = "game.bin"), folder)
|
||||
assertEquals(entry.key, game.key)
|
||||
val done = CountDownLatch(1)
|
||||
StoresState.uninstall(app, game) { done.countDown() }
|
||||
assertTrue(idleUntil { done.count == 0L })
|
||||
assertEquals(1, cancels.get())
|
||||
assertTrue(DownloadQueue.entry(entry.key)?.state.let { it == null || it == DownloadState.CANCELLED })
|
||||
assertFalse(folder.exists())
|
||||
}
|
||||
|
||||
private fun blockDiscards(): CountDownLatch {
|
||||
val release = CountDownLatch(1)
|
||||
StoreInstalls.beforeDiscard = { release.await(5, TimeUnit.SECONDS) }
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.compose.runtime.snapshots.Snapshot
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
@@ -195,13 +196,32 @@ class LibraryVisibilityTest {
|
||||
compose.onNodeWithText("Uninstalled GOG").assertExists()
|
||||
}
|
||||
|
||||
private fun show() {
|
||||
@Test fun battleNetHasAnOpenClientActionEvenWithoutInstalledGames() {
|
||||
var opened = 0
|
||||
show(actions(onBattleNet = { opened++ }))
|
||||
compose.onNodeWithTag("library-battlenet-open").assertDoesNotExist()
|
||||
compose.onNodeWithTag("library-source-battlenet").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithTag("library-battlenet-open").assertIsDisplayed().performClick()
|
||||
assertEquals(1, opened)
|
||||
compose.onNodeWithTag("library-source-steam").performClick()
|
||||
compose.mainClock.advanceTimeBy(1_000)
|
||||
compose.onNodeWithTag("library-battlenet-open").assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test fun battleNetOpenIsDisabledWhileBusy() {
|
||||
LibraryView.source = Store.BATTLENET.id
|
||||
show(frontState = state(busy = true))
|
||||
compose.onNodeWithTag("library-battlenet-open").assertIsNotEnabled()
|
||||
}
|
||||
|
||||
private fun show(frontActions: FrontEndActions = actions(), frontState: FrontEndState = state()) {
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.setContent { key(generation) {
|
||||
DroidDeckTheme {
|
||||
CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) {
|
||||
FocusGlideHost { Box(Modifier.fillMaxSize()) {
|
||||
LibraryPage(state(), actions(), "games", {}, Modifier.fillMaxSize())
|
||||
LibraryPage(frontState, frontActions, "games", {}, Modifier.fillMaxSize())
|
||||
StepsLayer(Offset.Zero)
|
||||
} }
|
||||
}
|
||||
@@ -216,15 +236,16 @@ class LibraryVisibilityTest {
|
||||
assertEquals(show, SessionPrefs.libraryShowUninstalled(ctx))
|
||||
}
|
||||
|
||||
private fun state(games: List<Library.SteamGame> = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal"))) = FrontEndState(
|
||||
installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1,
|
||||
private fun state(games: List<Library.SteamGame> = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal")), busy: Boolean = false) = FrontEndState(
|
||||
installed = "r9", ready = true, available = null, busy = busy, stage = "", percent = -1,
|
||||
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "",
|
||||
romsDir = null, logsEnabled = false,
|
||||
steamGames = games,
|
||||
emulators = emptyList(), running = null,
|
||||
)
|
||||
|
||||
private fun actions() = FrontEndActions(
|
||||
private fun actions(onBattleNet: () -> Unit = {}) = FrontEndActions(
|
||||
onBattleNet = onBattleNet,
|
||||
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
|
||||
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
|
||||
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
|
||||
|
||||
@@ -40,8 +40,8 @@ class NavTabsTest {
|
||||
}
|
||||
|
||||
@Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() {
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
|
||||
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
|
||||
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent"))
|
||||
assertFalse(com.droiddeck.launcher.agent.AgentTab.shown)
|
||||
@@ -66,13 +66,13 @@ class NavTabsTest {
|
||||
@Test fun showingMusicOnceKeepsItShownAfterReload() {
|
||||
place("soundtracks", TabPlace.BAR)
|
||||
NavTabs.load(ctx)
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "soundtracks", NavTabs.MORE), navigationKeys(state()))
|
||||
}
|
||||
|
||||
@Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() {
|
||||
place("desktop", TabPlace.MORE)
|
||||
val s = state()
|
||||
assertEquals(listOf("desktop", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
|
||||
assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
|
||||
assertEquals(NavTabs.MORE, navigationKeys(s).last())
|
||||
assertFalse("desktop" in navigationKeys(s))
|
||||
}
|
||||
@@ -85,14 +85,14 @@ class NavTabsTest {
|
||||
}
|
||||
|
||||
@Test fun resettingPutsBackTheDefaultLayout() {
|
||||
place("stores", TabPlace.MORE)
|
||||
place("stores", TabPlace.BAR)
|
||||
place("updates", TabPlace.HIDDEN)
|
||||
moveTab("downloads", -1)
|
||||
assertFalse(NavTabs.isDefault())
|
||||
NavTabs.reset(ctx)
|
||||
NavTabs.load(ctx)
|
||||
assertTrue(NavTabs.isDefault())
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state()))
|
||||
}
|
||||
|
||||
@Test fun anOldLayoutKeepsWhatItsSwitchesShowed() {
|
||||
|
||||
Reference in new issue
Block a user