Compare commits

..
12 changed files with 371 additions and 127 deletions

No files matched your search

@@ -233,14 +233,14 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
timed(folder) { for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true) }
}
}
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
scanGame(context, folder, out, single = entry, reuse = true)
timed(folder) { scanGame(context, folder, out, single = entry, reuse = true) }
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
@@ -250,6 +250,15 @@ object AddedGames {
return out.distinctBy { it.folder.canonicalPath }
}
private const val SLOW_FOLDER_MS = 1_000L
private inline fun timed(folder: File, block: () -> Unit) {
val began = android.os.SystemClock.elapsedRealtime()
block()
val took = android.os.SystemClock.elapsedRealtime() - began
if (took >= SLOW_FOLDER_MS) Log.i(TAG, "games: scanning ${folder.path} took ${took}ms")
}
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
@@ -564,8 +573,10 @@ object AddedGames {
class Listed(val appId: Long, val name: String, val launchOptions: String)
fun listingFile(context: Context): File = File(context.filesDir, "session/added-games.json")
fun listed(context: Context): List<Listed>? = runCatching {
val file = File(context.filesDir, "session/added-games.json")
val file = listingFile(context)
if (!file.isFile) return null
val entries = org.json.JSONArray(file.readText())
(0 until entries.length()).mapNotNull { i ->
@@ -575,7 +586,7 @@ object AddedGames {
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
val file = listingFile(context).apply { parentFile?.mkdirs() }
val json = StringBuilder("[")
games.forEachIndexed { i, g ->
if (i > 0) json.append(',')
@@ -596,10 +607,24 @@ object AddedGames {
if (games.isNotEmpty() || i > 0) json.append(',')
json.append(entry.toString())
}
file.writeText(json.append(']').toString())
val text = json.append(']').toString()
synchronized(listing) {
val partial = File(file.parentFile, file.name + ".part")
try {
partial.writeText(text)
java.nio.file.Files.move(partial.toPath(), file.toPath(),
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.io.IOException) {
Log.w(TAG, "games: listing not replaced: ${e.message}")
partial.delete()
if (!file.isFile) file.writeText(text)
}
}
return file
}
private val listing = Any()
private fun artGuestPath(context: Context, file: File): String? {
val files = context.filesDir.absolutePath
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
@@ -1,17 +1,31 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.os.SystemClock
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.concurrent.Callable
import java.util.concurrent.Executors
object AddedGamesPublisher {
private const val TAG = "AddedGamesPublisher"
private const val CLIENT_WAIT_MS = 600_000L
private const val POLL_MS = 1_000L
private const val RETRY_MS = 5_000L
@VisibleForTesting
@Volatile
internal var now = false
@VisibleForTesting
@Volatile
internal var live: (Context, List<AddedGames.Game>, (AddedGames.Game) -> Boolean) -> Boolean = SteamLiveShortcuts::sync
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
fun later(context: Context, live: () -> Unit = {}) {
@@ -23,10 +37,56 @@ object AddedGamesPublisher {
if (now) work.run() else worker.execute(work)
}
fun republish(context: Context) {
fun republish(context: Context): List<AddedGames.Game> {
val games = AddedGames.scan(context)
AddedGames.writeListing(context, games)
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context)
val arch = SessionPrefs.activeSteamClientArch(context)
LibraryCache.save(context, Library.launchableGames(context, added = games, arch = arch), arch == "x86_64")
return games
}
fun sessionListing(context: Context): File {
val app = context.applicationContext
val started = AddedGames.listed(app)?.map { it.appId }?.toSet()
?: return AddedGames.writeListing(app, AddedGames.scan(app).also { log(it) })
val session = SessionState.sessionId
val work = Runnable {
try {
val began = SystemClock.elapsedRealtime()
val games = serial { republish(app) }
Log.i(TAG, "session refresh: ${games.size} game(s) in ${SystemClock.elapsedRealtime() - began} ms")
log(games)
val fresh = games.filter { (it.appId and 0xFFFFFFFFL) !in started }
if (fresh.isNotEmpty()) deliver(app, session, fresh)
} catch (e: Exception) {
Log.w(TAG, "session refresh: ${e.message}")
}
}
if (now) work.run() else Thread(work, "added-games-refresh").apply { priority = Thread.MIN_PRIORITY }.start()
return AddedGames.listingFile(app)
}
internal fun log(games: List<AddedGames.Game>) {
if (games.isNotEmpty()) Log.i(TAG, "added games: " + games.joinToString { "${it.name} (${it.exe.name})" })
}
private fun deliver(app: Context, session: String?, games: List<AddedGames.Game>) {
val until = SystemClock.uptimeMillis() + CLIENT_WAIT_MS
while (current(session)) {
val ready = SessionState.phase == SessionPhase.READY
if (ready && serial { !current(session) || (SessionState.phase == SessionPhase.READY && syncUnremoved(app, games)) }) return
if (now || SystemClock.uptimeMillis() >= until) return
Thread.sleep(if (ready) RETRY_MS else POLL_MS)
}
}
private fun current(session: String?): Boolean =
SessionState.running && !SessionState.stopRequested && SessionState.sessionId == session
private fun syncUnremoved(app: Context, games: List<AddedGames.Game>): Boolean {
val removed = SessionPrefs.removedAddedGames(app).toSet()
return live(app, games) { it.folder.path !in removed }
}
private fun <T> serial(block: () -> T): T = if (now) block() else worker.submit(Callable { block() }).get()
}
@@ -51,11 +51,12 @@ object GameExePicker {
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
for (f in entries) {
if (visited >= WALK_BUDGET) break@walk
if (isLink(f)) continue
if (f.isDirectory) {
val attrs = attributes(f) ?: continue
if (attrs.isSymbolicLink) continue
if (attrs.isDirectory) {
visited++
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
} else if (attrs.isRegularFile && f.name.endsWith(".exe", ignoreCase = true)) {
visited++
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
}
@@ -98,7 +99,9 @@ object GameExePicker {
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
}
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
private fun attributes(f: File): java.nio.file.attribute.BasicFileAttributes? = runCatching {
java.nio.file.Files.readAttributes(f.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, java.nio.file.LinkOption.NOFOLLOW_LINKS)
}.getOrNull()
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
}
@@ -693,12 +693,14 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
}
if (steamHere || noSteamGame) {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
val listing = if (steamHere) SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGamesPublisher.sessionListing(this) } else {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
com.droiddeck.launcher.frontend.AddedGamesPublisher.log(added)
SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
}
guest.add("DD_ADDED_GAMES=" + listing.path)
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
// Proton builds up to 11.12 report X11 text fields under this name.
@@ -19,25 +19,33 @@ object SteamLiveShortcuts {
private const val EVAL_TIMEOUT_MS = 20_000L
private const val THAW_WAIT_MS = 15_000L
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }): Boolean {
val wanted = games.filter(include)
if (wanted.isEmpty() || !clientRunning()) return
if (wanted.isEmpty()) return true
if (!clientRunning()) return false
val list = JSONArray()
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions))
val js = """
(async () => {
const want = ${list};
let added = 0;
let added = 0, missed = 0;
for (const w of want) {
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++; else missed++;
}
return added;
return JSON.stringify({ added, missed });
})()
""".trimIndent()
val result = evaluate(context, js) ?: return
Log.i(TAG, "live shortcuts: $result added")
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
return synced(evaluate(context, js))
}
internal fun synced(result: String?): Boolean {
val counts = result?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return false
val added = counts.optInt("added")
val missed = counts.optInt("missed")
Log.i(TAG, "live shortcuts: $added added" + if (missed > 0) ", $missed not added" else "")
if (added > 0) StoresState.logLine("Steam: $added shortcut(s) added to the running client")
return missed == 0
}
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
@@ -145,4 +145,15 @@ class AddedGamesCandidatesTest {
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
assertEquals("My Game [Repack]", AddedGames.scan(app).single().name)
}
@Test fun linksAndFoldersNamedLikeAnExeAreNotCandidates() {
val elsewhere = tmp.newFolder("Elsewhere")
exe(elsewhere, "Other.exe")
val game = tmp.newFolder("Linked")
exe(game, "bin/Linked.exe")
File(game, "Folder.exe").mkdirs()
java.nio.file.Files.createSymbolicLink(File(game, "other").toPath(), elsewhere.toPath())
java.nio.file.Files.createSymbolicLink(File(game, "Alias.exe").toPath(), File(elsewhere, "Other.exe").toPath())
assertEquals(listOf("bin/Linked.exe"), names(game))
}
}
@@ -0,0 +1,213 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesSessionListingTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@After fun restore() {
AddedGamesPublisher.now = false
AddedGamesPublisher.live = SteamLiveShortcuts::sync
SessionState.running = false
SessionState.stopRequested = false
SessionState.sessionId = null
SessionState.phase = SessionPhase.IDLE
}
private val stale = """[{"name":"Old","exe":"/root/Games/Old/Old.exe","folder":"/root/Games/Old","dir":"/root/Games/Old","appid":2147483649,"seen":0}]"""
private fun gamesFolder(vararg names: String): File {
val games = tmp.newFolder("PC")
for (n in names) File(games, "$n/$n.exe").apply { parentFile!!.mkdirs() }.writeText("game")
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
return games
}
private fun session(phase: SessionPhase) {
SessionState.sessionId = "session-test"
SessionState.stopRequested = false
SessionState.phase = phase
SessionState.running = true
}
private fun until(what: String, check: () -> Boolean) {
val end = System.currentTimeMillis() + 30_000
while (!check()) {
assertTrue(what, System.currentTimeMillis() < end)
Thread.sleep(20)
}
}
private fun scanLock(): Any =
AddedGames::class.java.getDeclaredField("scanning").apply { isAccessible = true }.get(null)!!
private fun refreshes() = Thread.getAllStackTraces().keys.filter { it.name == "added-games-refresh" }
@Test fun aSessionStartsFromTheLastListingWhileTheLibraryScanHoldsTheLock() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val done = CountDownLatch(1)
var returned: File? = null
var seen = ""
synchronized(scanLock()) {
Thread {
returned = AddedGamesPublisher.sessionListing(app)
seen = listing.readText()
done.countDown()
}.start()
assertTrue("the session start waited for the library scan", done.await(5, TimeUnit.SECONDS))
}
assertEquals(listing.path, returned!!.path)
assertEquals(stale, seen)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
val fresh = listing.readText()
assertTrue(fresh.contains("\"Alpha\""))
assertFalse(fresh.contains("\"Old\""))
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aFirstSessionScansBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app)
listing.delete()
assertEquals(listing.path, AddedGamesPublisher.sessionListing(app).path)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aListingThatCannotBeReplacedKeepsTheOldOne() {
val listing = AddedGames.listingFile(app).apply { parentFile?.mkdirs() }
listing.writeText("[]")
val blocked = File(listing.parentFile, listing.name + ".part").apply { mkdirs() }
gamesFolder("Alpha")
AddedGames.writeListing(app, AddedGames.scan(app))
assertEquals("[]", listing.readText())
assertFalse(blocked.exists())
}
@Test fun anUnreadableListingIsRescannedBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText("[{\"name\":") }
AddedGamesPublisher.sessionListing(app)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
}
@Test fun aGameRemovedWhileTheClientStartsIsNotAddedToIt() {
val games = gamesFolder("Alpha", "Beta")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.STARTING_STEAM)
AddedGamesPublisher.sessionListing(app)
until("the refresh did not write the listing") { listing.readText().contains("\"Beta\"") }
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
SessionState.phase = SessionPhase.READY
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), delivered.toList())
}
@Test fun aDeliveryTheClientRefusesIsRetriedUntilItIsTaken() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<List<String>>())
AddedGamesPublisher.live = { _, found, include -> attempts.add(found.filter(include).map { it.name }); attempts.size > 1 }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf(listOf("Alpha"), listOf("Alpha")), attempts.toList())
}
@Test fun anEndedSessionStopsTheRetries() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, _ -> attempts.addAll(found.map { it.name }); SessionState.running = false; false }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), attempts.toList())
}
@Test fun aDeliveryQueuedForAnEndedSessionIsNotSentToTheNextOne() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.READY)
val first = CountDownLatch(1)
val firstHeld = CountDownLatch(1)
val second = CountDownLatch(1)
val secondHeld = CountDownLatch(1)
AddedGamesPublisher.later(app) { firstHeld.countDown(); first.await() }
try {
assertTrue(firstHeld.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh did not wait for its scan") { refresh.state == Thread.State.WAITING }
AddedGamesPublisher.later(app) { secondHeld.countDown(); second.await() }
first.countDown()
assertTrue(secondHeld.await(30, TimeUnit.SECONDS))
until("the refresh did not queue its delivery") {
refresh.state == Thread.State.WAITING && refresh.stackTrace.any { it.methodName == "deliver" }
}
SessionState.sessionId = "session-next"
} finally {
first.countDown()
second.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(delivered.isEmpty())
}
@Test fun theRefreshWaitsForEarlierPublicationsBeforeWriting() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val hold = CountDownLatch(1)
val holding = CountDownLatch(1)
AddedGamesPublisher.later(app) { holding.countDown(); hold.await() }
try {
assertTrue(holding.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh neither finished nor waited") { refresh.state == Thread.State.WAITING || !refresh.isAlive }
assertTrue("the refresh wrote while an earlier publication was running", refresh.isAlive)
assertEquals(stale, listing.readText())
} finally {
hold.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(listing.readText().contains("\"Alpha\""))
}
}
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamLiveShortcutsSyncTest {
@Test fun everyGameKnownOrAddedIsDelivered() {
assertTrue(SteamLiveShortcuts.synced("""{"added":2,"missed":0}"""))
assertTrue(SteamLiveShortcuts.synced("""{"added":0,"missed":0}"""))
}
@Test fun aGameTheClientRefusedIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced("""{"added":1,"missed":1}"""))
assertFalse(SteamLiveShortcuts.synced("""{"added":0,"missed":3}"""))
}
@Test fun noAnswerIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced(null))
assertFalse(SteamLiveShortcuts.synced("1"))
}
}
-5
View File
@@ -134,11 +134,6 @@ spaces, quotes, or shell characters stay literal. Existing arguments and
settings on the next launch. It does not change Steam probes or native Linux
programs, whose ordinary output remains in the session log.
Proton's log is held to its first 64 MiB, whichever setting turned it on: a
watcher checks `steam-<appid>.log` and `steam-proton.log` every second while the game runs and
cuts them back, and later output continues after the cut. A game stuck in an exception loop
otherwise writes gigabytes per run.
After reproducing once, stop the session and use **Latest session logs > Share
logs**. The archive includes the generated Wine/Proton and graphics logs. Debug
logging can reduce performance and consume storage; disable it after collecting
@@ -3,7 +3,6 @@ import contextlib
import json
import os
import re
import subprocess
import sys
import tempfile
import threading
@@ -75,50 +74,6 @@ def apply_game_debug_logs(env, config=None, debug_dir=None):
return result
# Proton appends its log through one inherited descriptor and never limits it; a game that loops on an
# exception wrote 3 GB per run. Truncating keeps the first part and frees the rest, and Proton's
# appends continue from the new end.
PROTON_LOG_CAP = 64 * 1024 * 1024
PROTON_LOG_CHECK_S = 1
CAP_WATCH = r"""
import os, stat, sys, time
pid, limit, every, paths = int(sys.argv[1]), int(sys.argv[2]), float(sys.argv[3]), sys.argv[4:]
while os.path.isdir("/proc/%d" % pid):
for path in paths:
try:
info = os.lstat(path)
if stat.S_ISREG(info.st_mode) and info.st_size > limit:
os.truncate(path, limit)
except OSError:
pass
time.sleep(every)
"""
def proton_log_paths(env):
if env.get("PROTON_LOG", "0") in ("", "0"):
return []
folder = env.get("PROTON_LOG_DIR") or env.get("HOME") or os.environ.get("HOME") or "/root"
paths = [os.path.join(folder, "steam-proton.log")]
if env.get("SteamGameId"):
paths.insert(0, os.path.join(folder, "steam-%s.log" % env["SteamGameId"]))
return paths
def cap_proton_log(env, pid=None, limit=PROTON_LOG_CAP, every=PROTON_LOG_CHECK_S, popen=subprocess.Popen):
"""Keep Proton's log under `limit` bytes while process `pid` (this launcher, which becomes Proton) runs."""
paths = proton_log_paths(env)
if not paths:
return None
try:
return popen([sys.executable, "-c", CAP_WATCH, str(pid or os.getpid()), str(limit), str(every)] + paths,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
except OSError as error:
print("droiddeck-game-env: Proton log size limit unavailable (%s)" % error, file=sys.stderr)
return None
def capped_log(path, limit, mirror=False):
os.makedirs(os.path.dirname(path), exist_ok=True)
handle = open(path, "wb")
@@ -1748,8 +1748,6 @@ def main():
except OSError as undo:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); Wine uses its own copy "
"and the next launch puts the file back" % undo, file=sys.stderr)
if len(command) > 1 and command[1] == "waitforexitandrun":
GAME_DEBUG["cap_proton_log"](env)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
@@ -6,7 +6,6 @@ import runpy
import subprocess
import sys
import tempfile
import time
import unittest
@@ -14,58 +13,6 @@ BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
DEBUG = runpy.run_path(str(BIN / "droiddeck-game-debug"))
class ProtonLogCapTest(unittest.TestCase):
def test_only_an_enabled_proton_log_is_watched(self):
self.assertEqual(DEBUG["proton_log_paths"]({"PROTON_LOG": "0", "SteamGameId": "1"}), [])
self.assertEqual(DEBUG["proton_log_paths"]({"SteamGameId": "1"}), [])
self.assertEqual(DEBUG["proton_log_paths"]({"PROTON_LOG": "1", "PROTON_LOG_DIR": "/logs", "SteamGameId": "584400"}),
["/logs/steam-584400.log", "/logs/steam-proton.log"])
self.assertEqual(DEBUG["proton_log_paths"]({"PROTON_LOG": "+seh", "HOME": "/root"}), ["/root/steam-proton.log"])
def test_the_watcher_outlives_nothing_but_the_launcher(self):
calls = []
DEBUG["cap_proton_log"]({"PROTON_LOG": "1", "PROTON_LOG_DIR": "/logs", "SteamGameId": "7"}, pid=42,
popen=lambda argv, **kw: calls.append((argv, kw)))
argv, kw = calls[0]
self.assertEqual(argv[3:], ["42", str(DEBUG["PROTON_LOG_CAP"]), str(DEBUG["PROTON_LOG_CHECK_S"]),
"/logs/steam-7.log", "/logs/steam-proton.log"])
self.assertTrue(kw["start_new_session"])
self.assertIsNone(DEBUG["cap_proton_log"]({"PROTON_LOG": "0"}, popen=lambda *a, **k: self.fail("spawned")))
def test_a_flooding_log_is_cut_back_and_appends_continue_after_the_cut(self):
with tempfile.TemporaryDirectory() as folder:
log = Path(folder) / "steam-9.log"
launcher = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(3)"])
with open(log, "ab") as proton:
proton.write(b"Proton: header\n" + b"x" * 300_000)
proton.flush()
watcher = DEBUG["cap_proton_log"]({"PROTON_LOG": "1", "PROTON_LOG_DIR": folder, "SteamGameId": "9"},
pid=launcher.pid, limit=1000, every=0.1)
deadline = time.monotonic() + 5
while log.stat().st_size > 1000 and time.monotonic() < deadline:
time.sleep(0.05)
self.assertEqual(log.stat().st_size, 1000)
proton.write(b"tail")
proton.flush()
self.assertTrue(log.read_bytes().startswith(b"Proton: header"))
self.assertTrue(log.read_bytes().endswith(b"tail"))
self.assertEqual(log.stat().st_size, 1004)
launcher.wait()
watcher.wait(timeout=5)
def test_symlinks_are_left_alone(self):
with tempfile.TemporaryDirectory() as folder:
target = Path(folder) / "other"
target.write_bytes(b"y" * 5000)
(Path(folder) / "steam-3.log").symlink_to(target)
launcher = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(0.5)"])
watcher = DEBUG["cap_proton_log"]({"PROTON_LOG": "1", "PROTON_LOG_DIR": folder, "SteamGameId": "3"},
pid=launcher.pid, limit=10, every=0.1)
launcher.wait()
watcher.wait(timeout=5)
self.assertEqual(target.stat().st_size, 5000)
class DesktopProgramDiagnosticsTest(unittest.TestCase):
def launch(self, folder, desktop=True, **settings):
env = dict(os.environ, DD_DEBUG_DIR=folder, WINEDEBUG="-all", PROTON_LOG="0")