mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa645396ff | ||
|
|
a02ea07386 | ||
|
|
c1d6d425fa | ||
|
|
70be3d3eea | ||
|
|
f2206893d0 | ||
|
|
ce64f5ade4 | ||
|
|
723d78cc63 |
No files matched your search
@@ -955,6 +955,7 @@ jobs:
|
||||
with:
|
||||
artifact: droiddeck-signed
|
||||
variant: standard
|
||||
fail_on_detection: true
|
||||
secrets: inherit
|
||||
|
||||
packs:
|
||||
|
||||
@@ -40,7 +40,8 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
PILL("pill", "Pill"),
|
||||
MINIMAL("minimal", "Minimal"),
|
||||
MEGA("mega", "Mega"),
|
||||
STRIP("strip", "Strip");
|
||||
STRIP("strip", "Strip"),
|
||||
SIDE_STRIP("side_strip", "Side strip");
|
||||
|
||||
fun next(): DroidDeckHudSize {
|
||||
val all = values()
|
||||
@@ -96,6 +97,11 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||
"showPower", "showDisplay", "showHdr", "showGpuModel",
|
||||
),
|
||||
SIDE_STRIP to listOf(
|
||||
"showFPS", "showFPSGraph", "showAvg", "showLow1",
|
||||
"showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp", "showRAM", "showVram",
|
||||
"showPower", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -110,6 +116,7 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
|
||||
band = 9.5f, gutter = 16f),
|
||||
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
|
||||
SIDE_STRIP to DroidDeckHudStyle(row = 11.5f, unit = 9f, pad = 8f, lineGap = 4f, labelGap = 4f, key = 9f),
|
||||
)
|
||||
|
||||
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
|
||||
|
||||
@@ -573,6 +573,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (s == null) { contentW = 0f; contentH = 0f; return }
|
||||
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
||||
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
|
||||
if (size == DroidDeckHudSize.SIDE_STRIP) { buildSideStrip(s); return }
|
||||
buildRows(s)
|
||||
if (contentW <= 0f || contentH <= 0f) return
|
||||
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
|
||||
@@ -684,8 +685,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
finishPanel(panel, halfRound = halfRound)
|
||||
}
|
||||
|
||||
private fun finishPanel(panel: RectF, halfRound: Boolean) {
|
||||
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, sp(56f))
|
||||
private fun finishPanel(panel: RectF, halfRound: Boolean, maxRadius: Float = sp(56f), inset: Float = panelInset()) {
|
||||
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, maxRadius)
|
||||
val margin = outlineWidth() + sp(4f)
|
||||
fun curveIn(top: Float, bottom: Float): Float {
|
||||
val d = max(max(panel.top + r - top, bottom - (panel.bottom - r)), 0f)
|
||||
@@ -703,8 +704,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
for (t in tileRects) right = max(right, t.right + curveIn(t.top, t.bottom) + margin)
|
||||
panel.right = max(right, panel.left + sp(6f) + r)
|
||||
dPanel = panel; dRadius = r
|
||||
contentW = panel.right + panelInset()
|
||||
contentH = panel.bottom + panelInset()
|
||||
contentW = panel.right + inset
|
||||
contentH = panel.bottom + inset
|
||||
}
|
||||
|
||||
private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date())
|
||||
@@ -936,6 +937,58 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildSideStrip(s: HudMetrics.Snapshot) {
|
||||
val style = size.style
|
||||
val inset = sp(5f)
|
||||
val panelWidth = sp(86f)
|
||||
val pad = sp(style.pad)
|
||||
val left = inset + pad
|
||||
val right = inset + panelWidth - pad
|
||||
val markHeight = sp(12f)
|
||||
val markTop = inset + sp(6f)
|
||||
val markLeft = left - DroidDeckMark.inkLeftFor(markHeight)
|
||||
headerMark = RectF(markLeft, markTop, markLeft + DroidDeckMark.widthFor(markHeight), markTop + markHeight)
|
||||
dDividerTop = markTop + markHeight + sp(6f)
|
||||
|
||||
if (showClockTime) {
|
||||
val clock = clockTimeString()
|
||||
val clockPx = sp(8.5f)
|
||||
val clockWidth = measure(clock, clockPx)
|
||||
if (right - clockWidth >= markLeft + DroidDeckMark.inkRightFor(markHeight) + sp(4f)) {
|
||||
val baseline = markTop + (markHeight + capHeight(clockPx)) / 2f
|
||||
glyphs.add(Glyph(right - clockWidth, baseline, clock, blend(colDim), clockPx))
|
||||
}
|
||||
}
|
||||
|
||||
val labelPx = sp(style.key)
|
||||
val rowPx = sp(style.row)
|
||||
val unitPx = sp(style.unit)
|
||||
val lineGap = sp(style.lineGap)
|
||||
var y = dDividerTop + sp(6f)
|
||||
for (key in size.rowsIn(storedOrder)) {
|
||||
if (!switchOn(key)) continue
|
||||
if (key == "showFPSGraph") {
|
||||
val height = sp(15f)
|
||||
graphRect = RectF(left, y, right, y + height)
|
||||
y += height + lineGap
|
||||
continue
|
||||
}
|
||||
|
||||
val valuePx = if (key == "showFPS") sp(16f) else rowPx
|
||||
val row = reading(key, s, labelPx, valuePx, unitPx)
|
||||
val available = right - left - measure(row.label.text, labelPx) - sp(style.labelGap)
|
||||
val fit = (available / runWidth(row.vals)).coerceIn(0f, 1f)
|
||||
val values = row.vals.map { Span(it.text, it.color, it.sizePx * fit, it.glow) }
|
||||
val baseline = y - ascent(valuePx)
|
||||
placeRun(left, baseline, listOf(row.label))
|
||||
placeRun(right - runWidth(values), baseline, values)
|
||||
y += lineH(valuePx) + lineGap
|
||||
}
|
||||
|
||||
val panel = RectF(inset, inset, inset + panelWidth, y + sp(7f))
|
||||
finishPanel(panel, halfRound = false, maxRadius = sp(11f), inset = inset)
|
||||
}
|
||||
|
||||
private fun buildStrip(s: HudMetrics.Snapshot) {
|
||||
val rowPx = sp(11.5f); val unitPx = rowPx * 0.8f; val fpsPx = sp(15f)
|
||||
val padX = sp(10f); val groupGap = sp(13f)
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.os.ParcelFileDescriptor
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONArray
|
||||
@@ -25,6 +26,7 @@ import java.nio.channels.SeekableByteChannel
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.NoSuchFileException
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.StandardOpenOption
|
||||
@@ -221,7 +223,7 @@ internal object EnhancedSessionLogShare {
|
||||
Category.values().map { category ->
|
||||
val budget = budgets.getValue(category)
|
||||
val records = ArrayList<Record>()
|
||||
val selected = candidates.filter { it.category == category }
|
||||
val selected = candidates.filter { it.category == category }.sortedBy(::sharePriority)
|
||||
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
|
||||
val names = HashSet<String>()
|
||||
@@ -616,7 +618,8 @@ internal object EnhancedSessionLogShare {
|
||||
redactionLearningComplete: Boolean,
|
||||
) {
|
||||
val entries = JSONArray()
|
||||
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
|
||||
val (discovery, rest) = records.partition { it.origin == "discovery" }
|
||||
(discovery + rest).take(MAX_MANIFEST_RECORDS).forEach { record ->
|
||||
entries.put(JSONObject().apply {
|
||||
put("entry", record.entry)
|
||||
put("origin", record.origin)
|
||||
@@ -680,6 +683,15 @@ internal object EnhancedSessionLogShare {
|
||||
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
|
||||
}
|
||||
}
|
||||
fun addRecentLogs(root: File, entryPrefix: String, origin: String) {
|
||||
val scan = walk(root, remaining(maxFiles, out.size))
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
val base = root.toPath().toAbsolutePath().normalize()
|
||||
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }.forEach { file ->
|
||||
add(file, root, "$entryPrefix/${base.relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")}", origin)
|
||||
}
|
||||
}
|
||||
CRITICAL_SESSION_FILES.forEach { name ->
|
||||
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
|
||||
}
|
||||
@@ -713,16 +725,7 @@ internal object EnhancedSessionLogShare {
|
||||
add(source.file, source.root, source.entry, "battlenet")
|
||||
}
|
||||
} else {
|
||||
battleNetRoots(context).forEach { (prefix, root) ->
|
||||
val scan = walk(root, remaining(maxFiles, out.size))
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
|
||||
.forEach { file ->
|
||||
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
|
||||
add(file, root, "battlenet/$prefix/$relative", "battlenet")
|
||||
}
|
||||
}
|
||||
battleNetRoots(context).forEach { (prefix, root) -> addRecentLogs(root, "battlenet/$prefix", "battlenet") }
|
||||
}
|
||||
val sessionScan = walk(folder, remaining(maxFiles, out.size))
|
||||
truncated = truncated || sessionScan.truncated
|
||||
@@ -733,6 +736,9 @@ internal object EnhancedSessionLogShare {
|
||||
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
|
||||
add(file, folder, "${folder.name}/$relative", "session")
|
||||
}
|
||||
val antiCheat = antiCheatRoots(context)
|
||||
partial = partial || antiCheat.partial
|
||||
antiCheat.roots.forEach { (appId, root) -> addRecentLogs(root, "anticheat/$appId", "anticheat") }
|
||||
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
|
||||
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
|
||||
val scan = directFiles(steam, remaining(maxFiles, out.size))
|
||||
@@ -748,7 +754,8 @@ internal object EnhancedSessionLogShare {
|
||||
private fun sharePriority(candidate: Candidate): Int = when {
|
||||
candidate.origin == "session-critical" -> 0
|
||||
candidate.origin == "session" && candidate.category == Category.GAMES -> 1
|
||||
else -> 2
|
||||
candidate.origin == "anticheat" -> 2
|
||||
else -> 3
|
||||
}
|
||||
|
||||
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
|
||||
@@ -822,6 +829,39 @@ internal object EnhancedSessionLogShare {
|
||||
return ScanResult(files, truncated, partial)
|
||||
}
|
||||
|
||||
private class AntiCheatRoots(val roots: List<Pair<String, File>>, val partial: Boolean)
|
||||
|
||||
private fun antiCheatRoots(context: Context): AntiCheatRoots {
|
||||
var partial = false
|
||||
val seen = HashSet<String>()
|
||||
val dirs = runCatching { Library.compatdataDirs(context) }.getOrElse { partial = true; emptyList() }
|
||||
val roots = dirs.flatMapIndexed { library, compatdata ->
|
||||
val prefixes = compatdata.listFiles() ?: run { partial = true; emptyArray() }
|
||||
prefixes.filter { !Files.isSymbolicLink(it.toPath()) }.mapNotNull { prefix ->
|
||||
val appId = steamAppId(prefix.name) ?: return@mapNotNull null
|
||||
val root = File(prefix, EAC_LOG_DIR)
|
||||
val directory = try {
|
||||
Files.readAttributes(root.toPath(), BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS).isDirectory
|
||||
} catch (_: NoSuchFileException) {
|
||||
false
|
||||
} catch (_: Exception) {
|
||||
partial = true
|
||||
false
|
||||
}
|
||||
if (!directory) return@mapNotNull null
|
||||
val base = "$appId/library${library + 1}"
|
||||
val key = base.takeIf { seen.add(it) } ?: "$base-${prefix.name}".takeIf { seen.add(it) }
|
||||
if (key != null) key to root else { partial = true; null }
|
||||
}
|
||||
}
|
||||
return AntiCheatRoots(roots, partial)
|
||||
}
|
||||
|
||||
private fun steamAppId(name: String): String? =
|
||||
name.takeIf { SIGNED_APP_ID.matches(it) }?.toLongOrNull()
|
||||
?.takeIf { it in Int.MIN_VALUE.toLong()..0xffffffffL }
|
||||
?.let { (it and 0xffffffffL).toString() }
|
||||
|
||||
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
|
||||
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
||||
val data = File(drive, "ProgramData/Battle.net")
|
||||
@@ -928,7 +968,9 @@ internal object EnhancedSessionLogShare {
|
||||
val normalized = name.replace('\\', '/').trimStart('/')
|
||||
val parts = normalized.split('/')
|
||||
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
|
||||
return parts.joinToString("/") { safeComponent(it) }
|
||||
return parts.mapIndexed { index, part ->
|
||||
if (index == 1 && parts[0] == "anticheat" && APP_ID.matches(part)) part else safeComponent(part)
|
||||
}.joinToString("/")
|
||||
}
|
||||
|
||||
private fun safeComponent(value: String): String {
|
||||
@@ -941,7 +983,7 @@ internal object EnhancedSessionLogShare {
|
||||
|
||||
private fun category(entry: String): Category {
|
||||
val value = entry.lowercase(Locale.US)
|
||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||
if (value.startsWith("battlenet/") || value.startsWith("anticheat/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
|
||||
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
||||
@@ -950,7 +992,7 @@ internal object EnhancedSessionLogShare {
|
||||
|
||||
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
|
||||
private val KNOWN_COMPONENTS = setOf(
|
||||
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
|
||||
"steam", "graphics", "games", "battlenet", "anticheat", "anticheatlauncher.log", "client", "agent", "setup", "stores", "tools",
|
||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
||||
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
||||
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
||||
@@ -961,11 +1003,15 @@ internal object EnhancedSessionLogShare {
|
||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
||||
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
||||
Regex("steam-[0-9]+\\.(?:log|txt)"),
|
||||
Regex("library[0-9]+(?:--?[0-9]{1,10})?"),
|
||||
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
|
||||
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
|
||||
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
|
||||
Regex("library[0-9]{1,3}"),
|
||||
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
|
||||
)
|
||||
private val APP_ID = Regex("[0-9]{1,10}")
|
||||
private val SIGNED_APP_ID = Regex("-?[0-9]{1,10}")
|
||||
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
|
||||
private val CRITICAL_SESSION_FILES = listOf(
|
||||
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
|
||||
@@ -973,6 +1019,7 @@ internal object EnhancedSessionLogShare {
|
||||
)
|
||||
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
|
||||
private const val STORE_LOG_SCAN = 512
|
||||
private const val EAC_LOG_DIR = "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat"
|
||||
private const val COPY_BUFFER_BYTES = 64 * 1024
|
||||
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
|
||||
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||
|
||||
@@ -39,7 +39,8 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
}
|
||||
if (!a.hudOn) return@SettingsGroup
|
||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint),
|
||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size),
|
||||
stringResource(if (size == DroidDeckHudSize.SIDE_STRIP) R.string.hud_size_side_strip_hint else R.string.hud_size_hint),
|
||||
listOf(
|
||||
DroidDeckHudSize.FULL to stringResource(R.string.hud_size_full),
|
||||
DroidDeckHudSize.TILES to stringResource(R.string.hud_size_tiles),
|
||||
@@ -47,6 +48,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
||||
DroidDeckHudSize.MEGA to stringResource(R.string.hud_size_mega),
|
||||
DroidDeckHudSize.STRIP to stringResource(R.string.hud_size_strip),
|
||||
DroidDeckHudSize.SIDE_STRIP to stringResource(R.string.hud_size_side_strip),
|
||||
),
|
||||
size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) }
|
||||
ChoiceRow(host, "hud-hold", stringResource(R.string.hud_hold), null,
|
||||
|
||||
@@ -737,6 +737,8 @@
|
||||
<string name="hud_size_minimal">Minimal</string>
|
||||
<string name="hud_size_mega">Mega</string>
|
||||
<string name="hud_size_strip">Strip</string>
|
||||
<string name="hud_size_side_strip">Side strip</string>
|
||||
<string name="hud_size_side_strip_hint">Drag the column to either side of the game. Tap the HUD to cycle sizes.</string>
|
||||
<string name="hud_locked">Lock in place</string>
|
||||
<string name="hud_locked_hint">Drag the HUD to move it. While it is locked, on-screen controls under it still work.</string>
|
||||
<string name="hud_hold">Long press</string>
|
||||
|
||||
@@ -133,6 +133,38 @@ class DroidDeckHudPanelTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sideStripOffersOnlyTheOnePercentLow() {
|
||||
val readings = DroidDeckHudSize.SIDE_STRIP.rows
|
||||
assertEquals(listOf("showLow1"), readings.filter { it.startsWith("showLow") })
|
||||
}
|
||||
|
||||
@Test fun sideStripFitsOneSideOfAWideScreenAndUsesItsOwnReadingOrder() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val view = DroidDeckHudView(app)
|
||||
val config = DroidDeckHudConfig.DEFAULTS + mapOf(
|
||||
"hudSize" to "side_strip",
|
||||
"hudOrder" to "strip:showCPUUsage|showRAM;side_strip:showRAM|showFPS|showFPSGraph",
|
||||
"showClock" to "0",
|
||||
)
|
||||
view.applyConfig(DroidDeckHudConfig.encode(config))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
|
||||
val density = app.resources.displayMetrics.density
|
||||
val height = (360 * density).toInt()
|
||||
val width = height * 21 / 9
|
||||
val sideMargin = (width - height * 16 / 9) / 2
|
||||
view.measure(
|
||||
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST),
|
||||
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST),
|
||||
)
|
||||
|
||||
assertTrue("HUD fits in one side margin", view.measuredWidth <= sideMargin)
|
||||
assertTrue("HUD is taller than it is wide", view.measuredHeight > view.measuredWidth)
|
||||
assertTrue("RAM is first", view.linesForTest().first().startsWith("RAM"))
|
||||
assertTrue("FPS is second", view.linesForTest()[1].startsWith("FPS"))
|
||||
assertTrue("The graph is inside the column", view.graphForTest()!!.right < view.measuredWidth)
|
||||
}
|
||||
|
||||
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.assumeFilePermissionsEnforced
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
@@ -8,6 +9,7 @@ import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.zip.ZipFile
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
@@ -144,6 +146,136 @@ class SessionLogShareZipTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theEasyAntiCheatLauncherLogsFromGamePrefixesComeAlong() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-09-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat")
|
||||
val prefix = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata/976730")
|
||||
val second = File(app.getExternalFilesDir(null), "second-library-${UUID.randomUUID()}").apply { mkdirs() }
|
||||
val library = SteamLibraries.add(app, second.path) as SteamLibraries.AddResult.Added
|
||||
try {
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/4815162342").apply { mkdirs() }
|
||||
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 261\n")
|
||||
File(eac, "old.log").apply {
|
||||
writeText("stale\n")
|
||||
setLastModified(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
|
||||
}
|
||||
val secondEac = File(second, "steamapps/compatdata/976730/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/b1d0a8c3").apply { mkdirs() }
|
||||
File(secondEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n")
|
||||
val signedEac = File(prefix.parentFile, "-1768546955/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
|
||||
File(signedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30005\n")
|
||||
val unsignedEac = File(prefix.parentFile, "2526420341/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
|
||||
File(unsignedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30007\n")
|
||||
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val logs = archive.entries().toList().filter { it.name.startsWith("anticheat/976730/") }
|
||||
assertEquals(2, logs.size)
|
||||
assertTrue(logs.all { it.name.endsWith("/anticheatlauncher.log") && !it.name.contains("4815162342") })
|
||||
val texts = logs.map { archive.getInputStream(it).bufferedReader().readText() }
|
||||
assertTrue(texts.any { it.contains("Launch Error: 261") })
|
||||
assertTrue(texts.any { it.contains("Launch Error: 206") })
|
||||
val aliases = archive.entries().toList().filter { it.name.startsWith("anticheat/2526420341/") }
|
||||
assertEquals(2, aliases.size)
|
||||
assertEquals(2, aliases.map { it.name.split('/')[2] }.filter { it.startsWith("library1") }.toSet().size)
|
||||
val aliasTexts = aliases.map { archive.getInputStream(it).bufferedReader().readText() }
|
||||
assertTrue(aliasTexts.any { it.contains("Launch Error: 30005") })
|
||||
assertTrue(aliasTexts.any { it.contains("Launch Error: 30007") })
|
||||
}
|
||||
} finally {
|
||||
SteamLibraries.remove(app, library.entry.id)
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
prefix.deleteRecursively()
|
||||
File(prefix.parentFile, "-1768546955").deleteRecursively()
|
||||
File(prefix.parentFile, "2526420341").deleteRecursively()
|
||||
second.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theSessionsGameLogComesAlongWhenManyAntiCheatLogsAreFound() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-11-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-flood")
|
||||
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
|
||||
val prefixes = (0 until 300).map { File(compatdata, "${900000 + it}") }
|
||||
try {
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
File(session, "steam-976730.log").writeText("proton: game started\n")
|
||||
prefixes.forEach { prefix ->
|
||||
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
|
||||
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n" + "x".repeat(64 * 1024))
|
||||
}
|
||||
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val game = archive.entries().toList().single { it.name.endsWith("/steam-976730.log") }
|
||||
assertTrue(archive.getInputStream(game).bufferedReader().readText().contains("game started"))
|
||||
}
|
||||
} finally {
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
prefixes.forEach { it.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aDiscoveryFailureStaysInTheManifestWhenRecordsPassTheLimit() {
|
||||
assumeFilePermissionsEnforced()
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-10-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/manifest-limit")
|
||||
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata").apply { mkdirs() }
|
||||
try {
|
||||
repeat(300) {
|
||||
File(session, "part-$it.log").writeText("line $it\n")
|
||||
File(session, "wayland-$it.log").writeText("line $it\n")
|
||||
File(session, "proton-$it.log").writeText("line $it\n")
|
||||
}
|
||||
assertTrue(compatdata.setReadable(false, false))
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
|
||||
assertTrue(entries.length() > 512)
|
||||
assertTrue(reasons.toString(), "filesystem-error" in reasons)
|
||||
}
|
||||
} finally {
|
||||
compatdata.setReadable(true, false)
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aPrefixThatDeniesTheAntiCheatFolderIsRecordedAsADiscoveryFailure() {
|
||||
assumeFilePermissionsEnforced()
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-12-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-denied")
|
||||
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
|
||||
val prefix = File(compatdata, "976731")
|
||||
val users = File(prefix, "pfx/drive_c/users").apply { mkdirs() }
|
||||
try {
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
assertTrue(users.setExecutable(false, false))
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
|
||||
assertTrue(reasons.toString(), "filesystem-error" in reasons)
|
||||
}
|
||||
} finally {
|
||||
users.setExecutable(true, false)
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
prefix.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
|
||||
val logs = LinuxRuntime.logDir(app)
|
||||
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
|
||||
|
||||
@@ -252,13 +252,15 @@ self-extractor stops at "Path not found", so the values it installs are applied
|
||||
`goggame-<id>.info`, and a script's own `setRegistry` entries always win over the built-in table.
|
||||
|
||||
The script's `supportData` actions run right after: files and folders from the game folder
|
||||
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}` and
|
||||
`{localappdata}` in the prefix, and `type: folder` without a source creates the folder. Mods such
|
||||
as one-click editions ship their `Plugins.txt` and INI files this way. Paths match without regard
|
||||
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}`,
|
||||
`{localappdata}` or `{userappdata}` in the prefix, and `type: folder` without a source creates the
|
||||
folder. Mods such as one-click editions ship their `Plugins.txt` and INI files this way. The
|
||||
`savePath` action's `savePath` folder is created with the same path rules, including the common
|
||||
case where a one-click edition names it again as a `supportData` folder. Paths match without regard
|
||||
to case, links are copied as links, and a path outside those folders is refused. A file the
|
||||
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` in
|
||||
the prefix holds the actions' hash, so they run once per script revision and a player's later
|
||||
edits stay.
|
||||
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` and
|
||||
`.droiddeck-gog-save-path` in the prefix hold the actions' hashes, so they run once per script
|
||||
revision and a player's later edits stay.
|
||||
|
||||
A GOG game's exe comes from its own manifest first: `goggame-<id>.info`'s play task in category
|
||||
`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#include <elf.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
@@ -547,3 +548,55 @@ EXPORT uid_t getuid(void)
|
||||
}
|
||||
return (uid_t)raw_getuid();
|
||||
}
|
||||
|
||||
static bool read_at(int fd, void *buf, size_t n, off_t at)
|
||||
{
|
||||
return pread(fd, buf, n, at) == (ssize_t)n;
|
||||
}
|
||||
|
||||
static void load_needed_of(const char *path)
|
||||
{
|
||||
Elf64_Ehdr e;
|
||||
Elf64_Phdr ph[32];
|
||||
Elf64_Dyn dyn[128];
|
||||
uint64_t strtab = 0, strsz = 0, needed[32];
|
||||
size_t n_dyn = 0, n_needed = 0;
|
||||
off_t names_at = -1;
|
||||
char *names = NULL;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return;
|
||||
if (!read_at(fd, &e, sizeof e, 0) || memcmp(e.e_ident, ELFMAG, SELFMAG) || e.e_ident[EI_CLASS] != ELFCLASS64 ||
|
||||
e.e_phentsize != sizeof *ph || e.e_phnum > 32 || !read_at(fd, ph, e.e_phnum * sizeof *ph, (off_t)e.e_phoff))
|
||||
goto out;
|
||||
for (int i = 0; i < e.e_phnum; i++) {
|
||||
if (ph[i].p_type != PT_DYNAMIC) continue;
|
||||
n_dyn = ph[i].p_filesz / sizeof *dyn;
|
||||
if (n_dyn > 128) n_dyn = 128;
|
||||
if (!read_at(fd, dyn, n_dyn * sizeof *dyn, (off_t)ph[i].p_offset)) goto out;
|
||||
break;
|
||||
}
|
||||
for (size_t i = 0; i < n_dyn && dyn[i].d_tag != DT_NULL; i++) {
|
||||
if (dyn[i].d_tag == DT_STRTAB) strtab = dyn[i].d_un.d_ptr;
|
||||
else if (dyn[i].d_tag == DT_STRSZ) strsz = dyn[i].d_un.d_val;
|
||||
else if (dyn[i].d_tag == DT_NEEDED && n_needed < 32) needed[n_needed++] = dyn[i].d_un.d_val;
|
||||
}
|
||||
for (int i = 0; i < e.e_phnum; i++)
|
||||
if (ph[i].p_type == PT_LOAD && strtab >= ph[i].p_vaddr && strtab - ph[i].p_vaddr + strsz <= ph[i].p_filesz)
|
||||
names_at = (off_t)(ph[i].p_offset + strtab - ph[i].p_vaddr);
|
||||
if (names_at < 0 || !strsz || strsz > (16u << 20) || !(names = malloc(strsz + 1)) ||
|
||||
!read_at(fd, names, strsz, names_at))
|
||||
goto out;
|
||||
names[strsz] = 0;
|
||||
for (size_t i = 0; i < n_needed; i++)
|
||||
if (needed[i] < strsz && !dlopen(names + needed[i], RTLD_NOW))
|
||||
say("steamshm: %s, needed by %s, did not load: %s\n", names + needed[i], path, dlerror());
|
||||
out:
|
||||
free(names);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void link_steamclient_needs_before_it(void)
|
||||
{
|
||||
const char *path = getenv("WINESTEAMCLIENTPATH64");
|
||||
if (path && *path) load_needed_of(path);
|
||||
}
|
||||
@@ -573,11 +573,11 @@ def inspector_url(url):
|
||||
|
||||
|
||||
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
|
||||
command_line_api=False):
|
||||
command_line_api=False, connect_timeout=5):
|
||||
if inspector is not None:
|
||||
url, name = inspector_url(inspector), "inspector"
|
||||
else:
|
||||
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
|
||||
targets = [t for t in cdp_targets(agent_dir, timeout=connect_timeout) if t.get("webSocketDebuggerUrl")]
|
||||
want = target or "SharedJSContext"
|
||||
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
|
||||
if not match:
|
||||
@@ -841,6 +841,75 @@ class KeyboardWatcher(threading.Thread):
|
||||
self.report(params.get("payload") == "true")
|
||||
|
||||
|
||||
NATIVE_SUSPEND_JS = r"""/* Template arguments are inserted by Python after validation. */
|
||||
async (operation, token, value, order) => {
|
||||
const root = globalThis;
|
||||
const leases = root.__droiddeckNativeSleep ??= { current: null, order: 0n, canceled: false };
|
||||
const sequence = BigInt(order);
|
||||
if (sequence < leases.order) return operation === "wake" ? "miss" : "expired";
|
||||
if (sequence > leases.order) {
|
||||
// An older renderer evaluation can arrive after a newer one. Only
|
||||
// the newest Android request may own a still-in-flight preparation,
|
||||
// including when its own preparation cannot start before deadline.
|
||||
leases.order = sequence;
|
||||
leases.canceled = false;
|
||||
if (leases.current && !leases.current.result) {
|
||||
leases.current.owner = token;
|
||||
leases.current.wake = false;
|
||||
} else {
|
||||
leases.current = null;
|
||||
}
|
||||
}
|
||||
const busy = () => root.SuspendResumeStore?.m_bSuspending === true;
|
||||
const user = root.SteamClient?.User;
|
||||
async function recover(lease) {
|
||||
if (leases.current !== lease || lease.recovered || !lease.wake || busy()) return;
|
||||
if (typeof user?.ResumeSuspendedGames !== "function") return;
|
||||
lease.recovered = true;
|
||||
try { await user.ResumeSuspendedGames(false); } catch { /* no session kick or retry */ }
|
||||
}
|
||||
|
||||
if (operation === "wake") {
|
||||
leases.canceled = true;
|
||||
const lease = leases.current;
|
||||
if (lease?.owner !== token) return "miss";
|
||||
lease.wake = true;
|
||||
// If login1 already signaled sleep and preparation had settled before
|
||||
// wake, its normal resume notification owns recovery. A late success
|
||||
// must recover again only because that notification could precede it.
|
||||
if (lease.result === "prepared" && value !== "signaled") void recover(lease);
|
||||
return "ack";
|
||||
}
|
||||
|
||||
if (leases.canceled) return "expired";
|
||||
const active = leases.current;
|
||||
// A reused in-flight call still requires wake recovery, even when
|
||||
// this request is too late to issue its own call.
|
||||
if (active && !active.result) return "coalesced";
|
||||
if (Date.now() >= value) return "expired";
|
||||
if (typeof user?.PrepareForSystemSuspend !== "function") return "unavailable";
|
||||
if (busy()) return "steam-busy";
|
||||
if (active) return active.result;
|
||||
const lease = { owner: token, result: null, wake: false, recovered: false };
|
||||
leases.current = lease;
|
||||
try {
|
||||
const reply = await user.PrepareForSystemSuspend();
|
||||
lease.result = reply?.result === 1 ? "prepared" : "rejected";
|
||||
} catch {
|
||||
lease.result = "uncertain";
|
||||
}
|
||||
if (lease.result === "prepared" && lease.wake) void recover(lease);
|
||||
return lease.result;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def native_suspend_lease(agent_dir, command, token, value, order):
|
||||
expression = "(" + NATIVE_SUSPEND_JS + ")(" + ", ".join(map(json.dumps, (command, token, value, order))) + ")"
|
||||
return cdp_eval(agent_dir, expression, timeout=1.45 if command == "prepare" else 0.75,
|
||||
connect_timeout=0.35).get("value")
|
||||
|
||||
|
||||
def steam_idle_inhibit(agent_dir, inhibit):
|
||||
expression = """(async want => {
|
||||
const toggle = () => new Promise(done => {
|
||||
@@ -1318,6 +1387,23 @@ def main(argv):
|
||||
time.sleep(0.5)
|
||||
print({True: "yes", False: "no"}.get(value, "unknown"))
|
||||
return {True: 0, False: 5}.get(value, 1)
|
||||
if argv and argv[0] in ("--steam-prepare-native-suspend", "--steam-wake-native-suspend"):
|
||||
if (len(argv) != 4 or re.fullmatch(r"[0-9a-f]{32}", argv[1]) is None or
|
||||
re.fullmatch(r"[1-9][0-9]{0,19}", argv[3]) is None):
|
||||
return 2
|
||||
prepare = argv[0] == "--steam-prepare-native-suspend"
|
||||
if prepare and (not argv[2].isascii() or not argv[2].isdigit() or len(argv[2]) > 14):
|
||||
return 2
|
||||
if not prepare and argv[2] not in ("signaled", "unsignaled", "uncertain"):
|
||||
return 2
|
||||
kind = "prepare" if prepare else "wake"
|
||||
value = int(argv[2]) if prepare else argv[2]
|
||||
try:
|
||||
result = native_suspend_lease(Path(base) / "agent", kind, argv[1], value, argv[3])
|
||||
except (AgentError, OSError, ValueError):
|
||||
result = "uncertain"
|
||||
print(result or "uncertain")
|
||||
return 0 if result in ("prepared", "ack", "miss") else 1
|
||||
if argv and argv[0] == "--steam-asleep":
|
||||
expression = """(() => {
|
||||
const store = globalThis.SuspendResumeStore;
|
||||
|
||||
@@ -7,6 +7,7 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import gi
|
||||
@@ -20,6 +21,10 @@ INTERFACE = NAME + ".Manager"
|
||||
UPOWER = "org.freedesktop.UPower"
|
||||
UPOWER_ROOT = "/org/freedesktop/UPower"
|
||||
NATIVE_PREPARE_MS = 1500
|
||||
STEAM_PREPARE_WAIT = 1.95
|
||||
STEAM_PREPARE_START_MS = 850
|
||||
STEAM_WAKE_WAIT = 1.25
|
||||
STEAM_WAKE_RETRY_DELAYS = (0, 0.2, 0.5)
|
||||
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
|
||||
ASLEEP_WAIT = 6
|
||||
INHIBIT_WAIT = 12
|
||||
@@ -55,6 +60,10 @@ class LoginManager:
|
||||
self.native_ready = self.directory / "steam-native-ready"
|
||||
self.pending = None
|
||||
self.pending_idle = False
|
||||
self.native_preparation = None
|
||||
self.native_signaled = False
|
||||
self.native_order = None
|
||||
self.native_wake_work = None
|
||||
self.waiting = set()
|
||||
self.timeout = None
|
||||
self.preparation = None
|
||||
@@ -90,6 +99,7 @@ class LoginManager:
|
||||
if self.pending:
|
||||
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
||||
return
|
||||
self.cancel_native_wake()
|
||||
self.pending = uuid.uuid4().hex
|
||||
self.pending_idle = False
|
||||
self.notify(True)
|
||||
@@ -133,19 +143,42 @@ class LoginManager:
|
||||
return
|
||||
self.pending = token
|
||||
self.pending_idle = words[1:] == ["idle"]
|
||||
# Idle requests never take ownership of Steam preparation. Preserve any
|
||||
# earlier wake delivery so an in-flight prepare cannot outlive its wake.
|
||||
if not self.pending_idle:
|
||||
self.cancel_native_wake()
|
||||
self.waiting = {"hold"} if self.pending_idle else {"hold", "prepare"}
|
||||
self.hold(token, self.prepared, token, "hold")
|
||||
if self.pending_idle:
|
||||
return
|
||||
self.native_preparation = "pending"
|
||||
order = self.native_order = str(time.monotonic_ns())
|
||||
deadline = int(time.time() * 1000) + STEAM_PREPARE_START_MS
|
||||
|
||||
def prepare():
|
||||
_, out = agent("--steam-prepare-native-suspend", token, str(deadline), order, timeout=STEAM_PREPARE_WAIT)
|
||||
GLib.idle_add(self.steam_prepared, token, out.strip() or "uncertain")
|
||||
|
||||
threading.Thread(target=prepare, daemon=True).start()
|
||||
|
||||
def steam_prepared(self, token, outcome):
|
||||
self.check_state()
|
||||
if self.pending != token:
|
||||
return False
|
||||
self.native_preparation = outcome
|
||||
self.native_signaled = True
|
||||
print("== login1: Steam native preparation " + outcome, flush=True)
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.prepare_after_flush, token)
|
||||
return False
|
||||
|
||||
def prepare_after_flush(self, connection, result, token):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
except GLib.Error as error:
|
||||
print("== login1: cannot prepare native sleep: " + str(error), file=sys.stderr)
|
||||
self.resume()
|
||||
if self.pending == token:
|
||||
self.resume()
|
||||
return
|
||||
self.check_state()
|
||||
if self.pending == token:
|
||||
@@ -269,19 +302,49 @@ class LoginManager:
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.finish_recovery, None)
|
||||
return
|
||||
token = self.pending
|
||||
idle = self.pending_idle
|
||||
native = self.native_preparation
|
||||
signaled = self.native_signaled
|
||||
order = self.native_order
|
||||
self.native_order = None
|
||||
self.pending = None
|
||||
self.pending_idle = False
|
||||
self.native_preparation = None
|
||||
self.native_signaled = False
|
||||
if self.preparation is not None:
|
||||
GLib.source_remove(self.preparation)
|
||||
self.preparation = None
|
||||
if self.timeout is not None:
|
||||
GLib.source_remove(self.timeout)
|
||||
self.timeout = None
|
||||
if not idle:
|
||||
if not idle and (native is None or signaled):
|
||||
self.notify(False)
|
||||
if native in ("pending", "uncertain", "coalesced") or native == "prepared" and not signaled:
|
||||
phase = "uncertain" if signaled else "unsignaled"
|
||||
self.deliver_native_wake(token, phase, order)
|
||||
self.release_later()
|
||||
|
||||
def cancel_native_wake(self):
|
||||
if self.native_wake_work is not None:
|
||||
self.native_wake_work.set()
|
||||
self.native_wake_work = None
|
||||
|
||||
def deliver_native_wake(self, token, phase, order):
|
||||
work = self.native_wake_work = threading.Event()
|
||||
|
||||
def deliver():
|
||||
for delay in STEAM_WAKE_RETRY_DELAYS:
|
||||
if work.wait(delay):
|
||||
return
|
||||
code, outcome = agent("--steam-wake-native-suspend", token, phase, order, timeout=STEAM_WAKE_WAIT)
|
||||
if code == 0 and outcome.strip() in ("ack", "miss"):
|
||||
return
|
||||
if not work.is_set():
|
||||
print("== login1: Steam native wake recovery not acknowledged", file=sys.stderr, flush=True)
|
||||
|
||||
threading.Thread(target=deliver, daemon=True).start()
|
||||
|
||||
def finish_recovery(self, connection, result, _data):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
|
||||
@@ -968,6 +968,7 @@ def prepare_gog(sidecar, compat_data, launch_dir):
|
||||
GOG_SCRIPTS = "goggame-*.script"
|
||||
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
|
||||
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
|
||||
GOG_SAVE_PATH_MARK = ".droiddeck-gog-save-path"
|
||||
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
|
||||
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
|
||||
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
|
||||
@@ -1716,7 +1717,7 @@ def prepare_steam_ea(argv, compat_data, launch_dir):
|
||||
return REPLACED
|
||||
|
||||
|
||||
def gog_support_actions(folder):
|
||||
def gog_script_actions(folder, name):
|
||||
found = []
|
||||
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
|
||||
product = script.name[len("goggame-"):-len(".script")]
|
||||
@@ -1726,17 +1727,34 @@ def gog_support_actions(folder):
|
||||
continue
|
||||
for action in actions if isinstance(actions, list) else []:
|
||||
install = action.get("install") if isinstance(action, dict) else None
|
||||
if isinstance(install, dict) and install.get("action") == "supportData" \
|
||||
if isinstance(install, dict) and install.get("action") == name \
|
||||
and isinstance(install.get("arguments"), dict):
|
||||
found.append((product, install["arguments"]))
|
||||
return found
|
||||
|
||||
|
||||
def gog_support_actions(folder):
|
||||
return gog_script_actions(folder, "supportData")
|
||||
|
||||
|
||||
def gog_case_child(path, part):
|
||||
exact = path / part
|
||||
try:
|
||||
if not exact.exists() and path.is_dir():
|
||||
return next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
|
||||
except OSError:
|
||||
pass
|
||||
return exact
|
||||
|
||||
|
||||
def gog_support_bases(folder, product, pfx):
|
||||
user = Path(pfx) / "drive_c" / "users" / "steamuser"
|
||||
support = Path(folder) / "support" / product
|
||||
appdata = gog_case_child(user, "AppData")
|
||||
return {"app": Path(folder), "supportdir": support, "support": support,
|
||||
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
|
||||
"userdocs": gog_case_child(user, "Documents"),
|
||||
"localappdata": gog_case_child(appdata, "Local"),
|
||||
"userappdata": gog_case_child(appdata, "Roaming")}
|
||||
|
||||
|
||||
def gog_inside(path, base):
|
||||
@@ -1755,10 +1773,7 @@ def gog_support_path(text, bases):
|
||||
base = bases[match.group(1).lower()]
|
||||
path = base
|
||||
for part in parts:
|
||||
exact = path / part
|
||||
if not exact.exists() and path.is_dir():
|
||||
exact = next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
|
||||
path = exact
|
||||
path = gog_case_child(path, part)
|
||||
if path != base and not gog_inside(path.parent, base):
|
||||
return None
|
||||
return path, base
|
||||
@@ -1830,6 +1845,44 @@ def gog_support_data(folder, compat_data, proton):
|
||||
return "copied=%d%s" % (copied, note)
|
||||
|
||||
|
||||
def gog_save_paths(folder, compat_data, proton):
|
||||
actions = gog_script_actions(folder, "savePath")
|
||||
if not actions:
|
||||
return "none"
|
||||
pfx = Path(compat_data) / "pfx" if compat_data else None
|
||||
if not pfx or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
|
||||
made = create_prefix(compat_data, proton)
|
||||
if made not in ("present", "created") or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
|
||||
return "no-prefix"
|
||||
stamp = hashlib.sha256(json.dumps(actions, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
marker = pfx / GOG_SAVE_PATH_MARK
|
||||
try:
|
||||
if marker.is_file() and marker.read_text() == stamp:
|
||||
return "ready"
|
||||
except OSError:
|
||||
pass
|
||||
paths = skipped = 0
|
||||
for product, arguments in actions:
|
||||
bases = gog_support_bases(folder, product, pfx)
|
||||
found = gog_support_path(arguments.get("savePath") or arguments.get("target"), bases)
|
||||
if found is None:
|
||||
skipped += 1
|
||||
continue
|
||||
target, _root = found
|
||||
try:
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
paths += 1
|
||||
except OSError:
|
||||
skipped += 1
|
||||
note = " skipped=%d" % skipped if skipped else ""
|
||||
if not skipped:
|
||||
try:
|
||||
marker.write_text(stamp)
|
||||
except OSError:
|
||||
pass
|
||||
return "paths=%d%s" % (paths, note)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
|
||||
return 0
|
||||
@@ -1876,6 +1929,7 @@ def main(argv):
|
||||
prepare_gog(sidecar, compat_data, launch_dir)
|
||||
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
log("gog save paths: " + gog_save_paths(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
if store == "rockstar":
|
||||
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
|
||||
if compat_data:
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
STEAMSHM = Path(__file__).resolve().parents[1] / "bionic-runtime/steamshm.c"
|
||||
|
||||
SOURCES = {
|
||||
"libsystemxml.so": ("int xml_copy(void) { return 1; }\n", []),
|
||||
"libvendor.so": ("int xml_copy(void);\nint vendor_xml_copy(void) { return xml_copy(); }\n", ["systemxml"]),
|
||||
"libframework.so": ("int framework(void) { return 0; }\n", ["vendor"]),
|
||||
"libsteam.so": ("int xml_copy(void) { return 2; }\nint CreateInterface(void) { return 0; }\n", ["framework"]),
|
||||
}
|
||||
|
||||
LOADER_PRELUDE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <elf.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#define say(...) fprintf(stderr, __VA_ARGS__)
|
||||
"""
|
||||
|
||||
|
||||
def steamclient_loader():
|
||||
source = STEAMSHM.read_text()
|
||||
return LOADER_PRELUDE + source[source.index("static bool read_at("):]
|
||||
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
int main(void) {
|
||||
if (!dlopen("libsteam.so", RTLD_NOW)) { puts(dlerror()); return 1; }
|
||||
void *vendor = dlopen("libvendor.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
int (*copy)(void) = vendor ? (int (*)(void))dlsym(vendor, "vendor_xml_copy") : 0;
|
||||
if (!copy) return 1;
|
||||
printf("%d\n", copy());
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class SteamClientNeedsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
for name, (code, needs) in SOURCES.items():
|
||||
src = self.dir / (name + ".c")
|
||||
src.write_text(code)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-o", str(self.dir / name), str(src), "-L", str(self.dir),
|
||||
"-Wl,--no-as-needed", *("-l" + n for n in needs)], check=True)
|
||||
(self.dir / "main.c").write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-o", str(self.dir / "main"), str(self.dir / "main.c"), "-ldl"], check=True)
|
||||
loader = self.dir / "loader.c"
|
||||
loader.write_text(steamclient_loader())
|
||||
self.preload = self.dir / "libsteamshm.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-fvisibility=hidden",
|
||||
str(loader), "-ldl", "-o", str(self.preload)], check=True)
|
||||
|
||||
def vendor_binding(self, preload=True, steam=None):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "WINESTEAMCLIENTPATH64")}
|
||||
env["LD_LIBRARY_PATH"] = str(self.dir)
|
||||
if steam:
|
||||
env["WINESTEAMCLIENTPATH64"] = steam
|
||||
if preload:
|
||||
env["LD_PRELOAD"] = str(self.preload)
|
||||
run = subprocess.run([str(self.dir / "main")], env=env, capture_output=True, text=True, check=True)
|
||||
return run.stdout.strip()
|
||||
|
||||
def test_without_the_preload_a_framework_library_binds_to_steams_copy(self):
|
||||
self.assertEqual(self.vendor_binding(preload=False), "2")
|
||||
|
||||
def test_the_libraries_steam_needs_link_to_their_own_copy_first(self):
|
||||
self.assertEqual(self.vendor_binding(steam=str(self.dir / "libsteam.so")), "1")
|
||||
|
||||
def test_without_a_steam_library_path_nothing_is_loaded_early(self):
|
||||
self.assertEqual(self.vendor_binding(), "2")
|
||||
|
||||
def test_a_missing_or_foreign_steam_library_is_ignored(self):
|
||||
self.assertEqual(self.vendor_binding(steam=str(self.dir / "missing.so")), "2")
|
||||
self.assertEqual(self.vendor_binding(steam=str(self.dir / "main.c")), "2")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+240
-2
@@ -1,7 +1,9 @@
|
||||
from contextlib import contextmanager
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import signal
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
@@ -146,9 +148,9 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
staged.write_text("wake\n")
|
||||
staged.replace(self.dir / "steam-wake")
|
||||
|
||||
def request_native(self, token="1" * 32):
|
||||
def request_native(self, token="1" * 32, idle=False):
|
||||
staged = self.dir / "steam-native-sleep.tmp"
|
||||
staged.write_text(token + "\n")
|
||||
staged.write_text(token + (" idle" if idle else "") + "\n")
|
||||
staged.replace(self.dir / "steam-native-sleep")
|
||||
return token
|
||||
|
||||
@@ -325,6 +327,132 @@ class AsleepSteamTest(FakeAgentCase):
|
||||
"--steam-idle-inhibit", "off"], self.asked())
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class NativePrepareTest(FakeAgentCase):
|
||||
AGENT_EXIT = 0
|
||||
|
||||
def prepare_agent(self, delay, fail_first_wake=False, gated=False):
|
||||
script = self.dir / "bin/droiddeck-agent"
|
||||
prepare = f'sleep {delay}'
|
||||
failed_wake = ':'
|
||||
if gated:
|
||||
prepare = f'while [ ! -f "{self.dir / "release-prepare"}" ]; do sleep 0.025; done'
|
||||
failed_wake = f'while [ ! -f "{self.dir / "release-wake"}" ]; do sleep 0.025; done'
|
||||
script.write_text(
|
||||
f'#!/bin/sh\necho "$@" >> "{self.dir / "agent-calls"}"\n'
|
||||
f'case "$1" in --steam-prepare-native-suspend) {prepare}; echo prepared;;\n'
|
||||
'--steam-wake-native-suspend)\n'
|
||||
f' if [ "{int(fail_first_wake)}" -eq 1 ] && [ ! -f "{self.dir / "wake-tried"}" ]; then\n'
|
||||
f' touch "{self.dir / "wake-tried"}"; {failed_wake}; echo uncertain; exit 1; fi\n'
|
||||
' echo ack;; esac\n'
|
||||
"exit 0\n"
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def gated_agent(self, fail_first_wake=False):
|
||||
self.prepare_agent(0, fail_first_wake=fail_first_wake, gated=True)
|
||||
release_prepare = self.dir / "release-prepare"
|
||||
release_wake = self.dir / "release-wake"
|
||||
try:
|
||||
yield release_prepare, release_wake
|
||||
finally:
|
||||
release_prepare.touch()
|
||||
release_wake.touch()
|
||||
|
||||
def test_native_prepare_precedes_real_sleep_and_normal_wake_does_not_call_recovery(self):
|
||||
with self.gated_agent() as (release_prepare, _):
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.assertEqual(self.signals, [])
|
||||
release_prepare.touch()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertNotIn("--steam-wake-native-suspend", self.asked())
|
||||
|
||||
def test_awake_during_rpc_never_notifies_or_publishes_a_stale_pause(self):
|
||||
with self.gated_agent() as (release_prepare, _):
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: "unsignaled" in self.asked())
|
||||
release_prepare.touch()
|
||||
time.sleep(0.6)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
self.assertEqual(self.signals, [])
|
||||
subsequent = self.request_native("3" * 32)
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.assertEqual((self.dir / "steam-native-ready").read_text().strip(), subsequent)
|
||||
self.state(subsequent, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
|
||||
def test_ambiguous_wake_retries_transient_discovery_with_same_token(self):
|
||||
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: (self.dir / "wake-tried").exists())
|
||||
release_prepare.touch()
|
||||
release_wake.touch()
|
||||
self.wait_for(lambda: self.asked().count("--steam-wake-native-suspend") == 2)
|
||||
time.sleep(0.8)
|
||||
calls = (self.dir / "agent-calls").read_text().splitlines()
|
||||
wakes = [call.split() for call in calls if call.startswith("--steam-wake-native-suspend ")]
|
||||
self.assertEqual(len(wakes), 2)
|
||||
self.assertEqual(wakes[0], wakes[1])
|
||||
self.assertEqual(wakes[0][1:3], [token, "unsignaled"])
|
||||
prepare = next(call.split() for call in calls if call.startswith("--steam-prepare-native-suspend "))
|
||||
self.assertEqual(wakes[0][3], prepare[3])
|
||||
self.assertEqual(self.signals, [])
|
||||
|
||||
def test_new_sleep_request_cancels_retry_of_older_wake(self):
|
||||
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
|
||||
first = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(first, "awake")
|
||||
self.wait_for(lambda: (self.dir / "wake-tried").exists())
|
||||
second = self.request_native("3" * 32)
|
||||
self.wait_for(lambda: second in self.asked())
|
||||
release_prepare.touch()
|
||||
release_wake.touch()
|
||||
time.sleep(0.9)
|
||||
self.assertEqual(self.asked().count("--steam-wake-native-suspend"), 1)
|
||||
self.state(second, "awake")
|
||||
|
||||
def test_idle_request_preserves_retry_of_older_wake(self):
|
||||
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
|
||||
first = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(first, "awake")
|
||||
self.wait_for(lambda: (self.dir / "wake-tried").exists())
|
||||
release_prepare.touch()
|
||||
idle = self.request_native("3" * 32, idle=True)
|
||||
ready = self.dir / "steam-native-ready"
|
||||
self.wait_for(lambda: ready.exists() and ready.read_text().strip() == idle)
|
||||
self.state(idle, "paused")
|
||||
self.state(idle, "awake")
|
||||
release_wake.touch()
|
||||
self.wait_for(lambda: self.asked().count("--steam-wake-native-suspend") == 2)
|
||||
wakes = [call for call in (self.dir / "agent-calls").read_text().splitlines()
|
||||
if call.startswith("--steam-wake-native-suspend ")]
|
||||
self.assertEqual(wakes[0], wakes[1])
|
||||
self.assertEqual(wakes[0].split()[1:3], [first, "unsignaled"])
|
||||
self.assertEqual(self.asked().count("--steam-prepare-native-suspend"), 1)
|
||||
self.assertEqual(self.signals, [])
|
||||
|
||||
def test_timed_out_rpc_allows_sleep_and_wake_recovers_that_token(self):
|
||||
self.prepare_agent(6)
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True], timeout=3.0)
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists(), timeout=2.0)
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False] and "uncertain" in self.asked())
|
||||
self.assertIn(token, self.asked())
|
||||
|
||||
|
||||
class WithNetworkManagerTest(SleepHandshakeTest):
|
||||
ARGS = ["--with-netmanager"]
|
||||
|
||||
@@ -342,5 +470,115 @@ class WithNetworkManagerTest(SleepHandshakeTest):
|
||||
self.assertEqual(self.owner(NAME), self.process.pid)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("node"), "node is not installed")
|
||||
class NativeSleepLeaseTest(unittest.TestCase):
|
||||
def test_wake_and_prepare_ordering_in_the_renderer(self):
|
||||
result = subprocess.run(["node", "-e", NATIVE_LEASE_CASES, str(SCRIPT.with_name("droiddeck-agent"))],
|
||||
text=True, capture_output=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("PASS nine native preparation lease sequences", result.stdout)
|
||||
|
||||
|
||||
NATIVE_LEASE_CASES = r'''const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const text = fs.readFileSync(process.argv[1], "utf8").match(/NATIVE_SUSPEND_JS = r"""([\s\S]*?)"""/)[1];
|
||||
const call = eval("(" + text + ")");
|
||||
const run = (op, token, value) => call(op, token, value, token === a ? "100" : "200");
|
||||
const a = "1".repeat(32);
|
||||
const b = "2".repeat(32);
|
||||
const future = () => Date.now() + 5000;
|
||||
let invoked, resumes, result;
|
||||
function setup() {
|
||||
delete globalThis.__droiddeckNativeSleep;
|
||||
globalThis.SuspendResumeStore = { m_bSuspending: false };
|
||||
invoked = resumes = 0;
|
||||
globalThis.SteamClient = { User: {
|
||||
PrepareForSystemSuspend() { invoked++; return new Promise(resolve => { result = resolve; }); },
|
||||
ResumeSuspendedGames(kick) { assert.equal(kick, false); resumes++; return Promise.resolve({ result: 1 }); }
|
||||
}};
|
||||
}
|
||||
(async () => {
|
||||
setup();
|
||||
assert.equal(await run("prepare", a, Date.now() - 1), "expired");
|
||||
assert.equal(await run("wake", a, "unsignaled"), "miss");
|
||||
assert.equal(await run("prepare", a, future()), "expired");
|
||||
assert.equal(invoked, 0);
|
||||
|
||||
setup();
|
||||
let prep = run("prepare", a, future());
|
||||
result({result: 1});
|
||||
assert.equal(await prep, "prepared");
|
||||
await run("wake", a, "signaled");
|
||||
assert.equal(resumes, 0);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
await run("wake", a, "unsignaled");
|
||||
result({result: 1});
|
||||
assert.equal(await prep, "prepared");
|
||||
await run("wake", a, "unsignaled");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
result({result: 1});
|
||||
await prep;
|
||||
await run("wake", a, "uncertain");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
await run("wake", a, "unsignaled");
|
||||
assert.equal(await run("prepare", b, future()), "coalesced");
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(invoked, 1);
|
||||
assert.equal(resumes, 0);
|
||||
await run("wake", b, "uncertain");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
await run("wake", a, "unsignaled");
|
||||
globalThis.SuspendResumeStore.m_bSuspending = true;
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(resumes, 0);
|
||||
assert.equal(await run("prepare", b, future()), "steam-busy");
|
||||
assert.equal(invoked, 1);
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
assert.equal(await run("wake", a, "uncertain"), "ack");
|
||||
assert.equal(await run("prepare", b, Date.now() - 1), "coalesced");
|
||||
assert.equal(await run("wake", a, "uncertain"), "miss");
|
||||
assert.equal(await run("prepare", a, future()), "expired");
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(invoked, 1);
|
||||
assert.equal(resumes, 0);
|
||||
await run("wake", b, "uncertain");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
assert.equal(await run("wake", b, "uncertain"), "ack");
|
||||
assert.equal(await run("prepare", b, future()), "expired");
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(invoked, 1);
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(await run("wake", a, "uncertain"), "ack");
|
||||
assert.equal(await run("wake", a, "uncertain"), "ack");
|
||||
assert.equal(resumes, 1);
|
||||
console.log("PASS nine native preparation lease sequences");
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
'''
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -667,6 +667,10 @@ def support_data(**arguments):
|
||||
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
|
||||
|
||||
|
||||
def save_path(**arguments):
|
||||
return {'install': {'action': 'savePath', 'arguments': arguments}, 'name': 'saveFolders'}
|
||||
|
||||
|
||||
class GogSupportData(unittest.TestCase):
|
||||
def prefix(self, root):
|
||||
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
|
||||
@@ -850,6 +854,117 @@ class GogSupportData(unittest.TestCase):
|
||||
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
|
||||
|
||||
|
||||
class GogSavePaths(unittest.TestCase):
|
||||
def prefix(self, root):
|
||||
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
|
||||
user.mkdir(parents=True)
|
||||
return user
|
||||
|
||||
def test_the_london_script_creates_its_save_path_and_keeps_player_settings(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1897848199')
|
||||
user = self.prefix(root)
|
||||
support = folder / 'support/1897848199'
|
||||
(support / 'docs').mkdir(parents=True)
|
||||
(folder / '__AppData').mkdir()
|
||||
(folder / '__AppData/save.dat').write_text('save')
|
||||
for name in ('Fallout4Prefs.ini', 'Fallout4.ini'):
|
||||
(support / 'docs' / name).write_text('[Archive]\n')
|
||||
for name in ('DLCList.txt', 'Plugins.txt', 'UserDownloadedContent.txt'):
|
||||
(support / name).write_text('*LondonWorldSpace.esm\n')
|
||||
gog_script(folder, '1897848199', [
|
||||
save_path(savePath='{userdocs}/My Games/Fallout4', type='folder'),
|
||||
set_registry(root='HKLM', subkey='Software\\Bethesda Softworks\\Fallout4',
|
||||
valueName='Installed Path', valueData='{app}\\', valueType='string'),
|
||||
support_data(type='folder', target='{userdocs}/My Games/Fallout4'),
|
||||
support_data(type='folder', target='{localappdata}/Fallout4'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4Prefs.ini',
|
||||
target='{userdocs}/My Games/Fallout4/Fallout4Prefs.ini'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4.ini',
|
||||
target='{userdocs}/My Games/Fallout4/Fallout4.ini'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/DLCList.txt',
|
||||
target='{localappdata}/Fallout4/DLCList.txt'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/Plugins.txt',
|
||||
target='{localappdata}/Fallout4/Plugins.txt'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/UserDownloadedContent.txt',
|
||||
target='{localappdata}/Fallout4/UserDownloadedContent.txt'),
|
||||
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/Fallout4'),
|
||||
])
|
||||
with patch.object(store, 'create_prefix') as create:
|
||||
self.assertEqual('copied=6', store.gog_support_data(folder, root + '/compat', '/proton'))
|
||||
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
create.assert_not_called()
|
||||
saves = user / 'Documents/My Games/Fallout4'
|
||||
self.assertTrue(saves.is_dir())
|
||||
self.assertEqual('[Archive]\n', (saves / 'Fallout4.ini').read_text())
|
||||
self.assertEqual('*LondonWorldSpace.esm\n', (user / 'AppData/Local/Fallout4/Plugins.txt').read_text())
|
||||
self.assertTrue((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).is_file())
|
||||
(saves / 'my settings.ini').write_text('player')
|
||||
self.assertEqual('ready', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertEqual('player', (saves / 'my settings.ini').read_text())
|
||||
|
||||
def test_existing_prefix_base_names_keep_their_actual_case(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
user = self.prefix(root)
|
||||
(user / 'documents' / 'fixture').mkdir(parents=True)
|
||||
(user / 'aPPdATA' / 'roaming').mkdir(parents=True)
|
||||
gog_script(folder, '9', [
|
||||
save_path(savePath='{UserDocs}/Fixture/Saves'),
|
||||
save_path(savePath='{UserAppData}/Fixture/Settings'),
|
||||
])
|
||||
self.assertEqual('paths=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertTrue((user / 'documents/fixture/Saves').is_dir())
|
||||
self.assertTrue((user / 'aPPdATA/roaming/Fixture/Settings').is_dir())
|
||||
self.assertEqual({'documents', 'aPPdATA'}, {p.name for p in user.iterdir()})
|
||||
self.assertEqual({'roaming'}, {p.name for p in (user / 'aPPdATA').iterdir()})
|
||||
|
||||
def test_only_save_path_actions_create_known_folders(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
user = self.prefix(root)
|
||||
saves = user / 'Documents/My Games/Fallout4'
|
||||
saves.mkdir(parents=True)
|
||||
(saves / 'Fallout4Prefs.ini').write_text('player')
|
||||
gog_script(folder, '9', [
|
||||
set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string'),
|
||||
{'install': {'action': 'createFolder', 'arguments': {'savePath': '{userdocs}/Other'}}},
|
||||
save_path(savePath='{windir}/evil'),
|
||||
save_path(savePath='{userdocs}/../../escape'),
|
||||
save_path(savePath='{userappdata}/Ubisoft/Anno1404/Config'),
|
||||
])
|
||||
self.assertEqual('paths=1 skipped=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertTrue((user / 'AppData/Roaming/Ubisoft/Anno1404/Config').is_dir())
|
||||
self.assertFalse((user / 'Documents/Other').exists())
|
||||
self.assertFalse((Path(root) / 'escape').exists())
|
||||
self.assertEqual('player', (saves / 'Fallout4Prefs.ini').read_text())
|
||||
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).exists())
|
||||
|
||||
def test_without_save_paths_no_prefix_is_made(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
gog_script(folder, '9', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a',
|
||||
valueData='b', valueType='string')])
|
||||
with patch.object(store, 'create_prefix') as create:
|
||||
self.assertEqual('none', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
create.assert_not_called()
|
||||
|
||||
def test_a_missing_prefix_is_made_first(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
gog_script(folder, '9', [save_path(savePath='{userdocs}/My Games/G')])
|
||||
with patch.object(store, 'create_prefix', return_value='failed') as create:
|
||||
self.assertEqual('no-prefix', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
create.assert_called_once_with(root + '/compat', '/proton')
|
||||
|
||||
def made(compat_data, proton):
|
||||
self.prefix(root)
|
||||
return 'created'
|
||||
with patch.object(store, 'create_prefix', side_effect=made):
|
||||
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
|
||||
|
||||
|
||||
class GogRegistry(unittest.TestCase):
|
||||
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
|
||||
Reference in new issue
Block a user