Merge upstream main and close diagnostic publication races

This commit is contained in:
wallentx committed 2026-10-25 18:15:44 -05:00
commit f4adbeb602
473 files changed
+36063 -3507

No files matched your search

@@ -56,8 +56,9 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
// Android can keep reporting charging at 100%; Linux reports Full there, and Steam shows 99% until it does.
val statusText = when (status) {
BatteryManager.BATTERY_STATUS_CHARGING -> "Charging"
BatteryManager.BATTERY_STATUS_CHARGING -> if (pct >= 100) "Full" else "Charging"
BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
BatteryManager.BATTERY_STATUS_FULL -> "Full"
BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging"
@@ -51,7 +51,7 @@ object BootMovie {
SessionPrefs.setBootMovieApplyNext(context, true)
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
// Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
fun customName(context: Context): String? =
@@ -167,10 +167,12 @@ object BootMovie {
* that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
*/
fun syncFromSteam(context: Context): Boolean {
val path = SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context)) ?: return false
if (path == SessionPrefs.bootMovieSteamSeen(context)) return false
SessionPrefs.setBootMovieSteamSeen(context, path)
if (path == SessionFiles.BOOT_MOVIE_PATH) return false
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context)
if (named == seen) return false
SessionPrefs.setBootMovieSteamSeen(context, named)
if (named == SessionFiles.BOOT_MOVIE_PATH || (named.isEmpty() && seen == null)) return false
val path = named.ifEmpty { "/movies/steam_os_startup.webm" }
val prefix = "/uioverrides/movies/"
// The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
@@ -79,8 +79,9 @@ object BootMovieLibrary {
return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L }
}
private fun isMovie(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) &&
file.name !in STAGED && !file.name.startsWith(".")
private fun isMovie(file: File) = isWebm(file) && file.name !in STAGED
private fun isWebm(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) && !file.name.startsWith(".")
private fun readMeta(context: Context): JSONObject =
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
@@ -136,7 +137,7 @@ object BootMovieLibrary {
}
val bought = HashMap<String, String>()
for (root in steamRoots(context)) {
File(root, "steamui/movies").listFiles { f -> isMovie(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
File(root, "steamui/movies").listFiles { f -> isWebm(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
.sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) }
val scan = pointShopMovies(root)
bought.putAll(scan.titles)
@@ -144,8 +145,8 @@ object BootMovieLibrary {
}
val seen = HashSet<String>()
for ((id, file) in steam) {
if (file.name in STAGED || !seen.add(file.canonicalPath)) continue
val native = file.nameWithoutExtension.lowercase() in NATIVE
if ((file.name in STAGED && !native) || !seen.add(file.canonicalPath)) continue
// Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
@@ -153,8 +154,11 @@ object BootMovieLibrary {
return out
}
/** The three startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf("deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup")
/** The four startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf(
"deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup",
"steam_os_startup" to "SteamOS startup",
)
private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache")
@@ -721,13 +721,19 @@ object ComponentsManager {
class StoredOriginal(val protonId: String, val protonName: String?, val comp: String, val protonVersion: String, val size: Long, val kept: Boolean)
class Stored(val packages: List<StoredPackage>, val originals: List<StoredOriginal>)
private fun packagesInUse(state: JSONObject): Set<String> {
internal fun liveSelection(key: String, entry: JSONObject, proton: Proton?): Boolean =
proton != null && (key == "queued" || entry.optString("protonVersion") == proton.version)
private fun packagesInUse(state: JSONObject, installed: Map<String, Proton>): Set<String> {
val names = HashSet<String>()
for (key in listOf("active", "queued")) {
val byProton = state.optJSONObject(key) ?: continue
for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys()) comps.optJSONObject(comp)?.optString("file")?.takeIf { it.isNotEmpty() }?.let(names::add)
for (comp in comps.keys()) {
val entry = comps.optJSONObject(comp) ?: continue
if (liveSelection(key, entry, installed[pid])) entry.optString("file").takeIf { it.isNotEmpty() }?.let(names::add)
}
}
}
val profiles = state.optJSONObject("profiles")
@@ -747,8 +753,8 @@ object ComponentsManager {
fun stored(context: Context): Stored = synchronized(lock) {
val state = loadState(context)
val used = packagesInUse(state)
val installed = protons(context).associateBy { it.id }
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
val used = packagesInUse(state, installed)
val originals = originalsDir(context).listFiles()?.filter { it.isDirectory }?.flatMap { proton ->
proton.listFiles()?.filter { it.isDirectory }?.flatMap { version ->
COMPONENTS.mapNotNull { comp ->
@@ -774,27 +780,135 @@ object ComponentsManager {
true
}
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val queued = state.sub("queued")
for (pid in queued.keys()) {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val active = state.sub("active")
for (pid in active.keys()) {
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
private fun checkPackageUnused(context: Context, state: JSONObject, name: String) {
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
for (key in listOf("queued", "active")) {
val byProton = state.sub(key)
for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys()) {
val entry = comps.optJSONObject(comp) ?: continue
check(entry.optString("file") != name || !liveSelection(key, entry, installed[pid])) {
context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid)
}
}
}
}
val profiles = state.sub("profiles")
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
}
}
fun carryOver(context: Context, fromDir: String, toDir: String) {
synchronized(lock) {
val target = protons(context).firstOrNull { it.id == safeName(toDir) } ?: return
val state = loadState(context)
val wanted = carried(state, safeName(fromDir)) { File(packagesDir(context), it).isFile }
val active = state.sub("active").optJSONObject(target.id)
val queued = state.sub("queued").sub(target.id)
var changed = false
wanted.forEach { (comp, entry) ->
if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry)
changed = true
}
}
if (queued.length() == 0) state.sub("queued").remove(target.id)
if (changed) saveState(context, state)
}
}
internal fun carried(state: JSONObject, from: String, present: (String) -> Boolean): Map<String, JSONObject> = buildMap {
state.optJSONObject("active")?.optJSONObject(from)?.let { active ->
active.keys().forEach { comp ->
val entry = active.optJSONObject(comp) ?: return@forEach
val file = entry.optString("file")
if (comp in COMPONENTS && file.endsWith(".wcp") && present(file)) {
put(comp, JSONObject().put("kind", "package").put("file", file).put("label", entry.optString("label")))
}
}
}
state.optJSONObject("queued")?.optJSONObject(from)?.let { queued ->
queued.keys().forEach { comp ->
val entry = queued.optJSONObject(comp) ?: return@forEach
if (comp in COMPONENTS && entry.optString("kind") == "package" && present(entry.optString("file"))) put(comp, entry)
}
}
}
fun forgetProton(context: Context, dirName: String) {
synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
if (selected && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return
File(originalsDir(context), id).deleteRecursively()
}
}
private fun storePackage(context: Context, part: File, dest: File) {
try {
if (dest.isFile && runCatching { Hashes.sha256(dest) }.getOrNull()?.equals(Hashes.sha256(part), true) == true) return
if (dest.exists()) checkPackageUnused(context, loadState(context), dest.name)
val store = File(launchDir(context), "store").canonicalFile
val cacheKey = unpackedCacheKey(dest.name)
val unpacked = File(store, cacheKey).canonicalFile
check(unpacked.parentFile == store) { "Invalid unpacked component cache path for ${dest.name}" }
val complete = File(unpacked, ".complete")
if (complete.exists()) check(complete.delete()) { "Could not invalidate unpacked component ${dest.name}" }
if (!part.renameTo(dest)) {
dest.delete()
check(part.renameTo(dest)) { "Could not store ${dest.name}" }
}
if (!unpacked.deleteRecursively() && unpacked.exists()) {
check(!complete.exists()) { "Could not invalidate unpacked component ${dest.name}" }
Log.w(TAG, "Could not remove stale unpacked files for ${dest.name}; cache marker is invalidated")
}
} finally {
part.delete()
}
}
internal fun unpackedCacheKey(filename: String): String = safeName(filename.removeSuffix(".wcp")).also {
require(it != "." && it != "..") { "Invalid component cache name" }
}
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
val byProton = state.sub(key)
for (pid in byProton.keys().asSequence().toList()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val entry = comps.optJSONObject(comp) ?: continue
if (entry.optString("file") != name) continue
check(!liveSelection(key, entry, installed[pid])) { context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid) }
comps.remove(comp)
changed = true
}
if (comps.length() == 0) byProton.remove(pid)
}
}
val f = File(packagesDir(context), name)
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
f.delete()
val profiles = state.sub("profiles")
for (scope in profiles.keys().asSequence().toList()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS.filter { profile.optString(it) == name }) {
rememberProfiledComponent(state, comp)
profile.remove(comp)
changed = true
}
if (profile.length() == 0) profiles.remove(scope)
}
check(f.delete()) { name }
if (changed) saveState(context, state)
context.getString(R.string.cmgr_deleted, name)
}
@@ -811,7 +925,7 @@ object ComponentsManager {
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
val info = packageInfo(context, source)
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
storePackage(context, source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true), dest)
info.copy(file = dest.name)
}
@@ -834,6 +948,7 @@ object ComponentsManager {
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
}
}
if (items.length() == 0 && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000)
val tmp = File(cache.parentFile, cache.name + ".tmp")
tmp.writeText(out.toString()); tmp.renameTo(cache)
@@ -963,7 +1078,7 @@ object ComponentsManager {
}
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) }
val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it }
synchronized(lock) { part.renameTo(dest) }
synchronized(lock) { storePackage(context, part, dest) }
return info.copy(file = dest.name)
}
}
@@ -79,6 +79,14 @@ object GameEnvironmentStore {
return config
}
@Synchronized
fun setDefault(context: Context, scope: String, name: String, value: String): Boolean {
val config = read(context)
if (GameEnvironment.hasOverride(config, scope, name)) return false
save(context, GameEnvironment.withScopeValue(config, scope, name, value))
return true
}
@Synchronized
fun publish(
context: Context,
@@ -14,9 +14,12 @@ object GameStorage {
fun options(context: Context): List<Option> {
val sm = context.getSystemService(StorageManager::class.java)
val primary = context.getExternalFilesDir(null)?.absolutePath
val primaryStorage = Environment.getExternalStorageDirectory()?.absolutePath
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
if (!removable) return@mapNotNull null
// Non-primary app dirs are usable even when Android reports the volume as non-removable (USB SSDs often do).
if (primary != null && dir.absolutePath == primary) return@mapNotNull null
if (!primaryStorage.isNullOrBlank() && dir.absolutePath.startsWith("$primaryStorage/")) return@mapNotNull null
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: context.getString(R.string.gstore_sd_card)
Option(context.getString(R.string.gstore_volume_free, name, free(dir)), File(dir, "steam").absolutePath, name)
@@ -26,6 +26,7 @@ object GpuClockPin {
pinned = true
"gpu clock: held at its top"
} catch (t: Throwable) {
File(context.filesDir, MARKER).delete()
Log.w(TAG, "pin", t)
"gpu clock: pin failed"
}
@@ -87,11 +87,10 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
if (line.startsWith("== STEP ")) {
stepAt = at
stepText = line.substringAfter("== STEP ").substringAfter(' ')
val m = INSTALL_COUNT.find(line)
if (m != null) {
clientDownload(line)?.let { (what, percent) ->
clientDownloadAt = at
clientDownload = m.groupValues[1]
clientPercent = m.groupValues[2].toInt() * 100 / maxOf(1, m.groupValues[3].toInt())
clientDownload = what
clientPercent = percent
}
} else {
val m = UPDATE_PROGRESS.find(line)
@@ -132,6 +131,19 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
}
}
internal fun clientDownload(line: String): Pair<String, Int>? {
val count = INSTALL_COUNT.find(line) ?: return null
val mb = INSTALL_MEGABYTES.find(line.substring(count.range.last + 1))
val done = mb?.groupValues?.get(1)?.toLongOrNull()
val total = mb?.groupValues?.get(2)?.toLongOrNull()
if (done != null && total != null && total > 0) {
return "$done / $total MB" to (done * 100 / total).toInt().coerceIn(0, 100)
}
val part = count.groupValues[2].toIntOrNull() ?: return null
val all = count.groupValues[3].toIntOrNull() ?: return null
return count.groupValues[1] to (part.toLong() * 100 / maxOf(1, all)).coerceIn(0L, 100L).toInt()
}
internal fun readableScriptStep(scriptStep: String): Boolean {
val t = scriptStep.lowercase()
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
@@ -140,5 +152,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
}
}
@@ -0,0 +1,175 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import java.io.File
import java.util.Locale
internal object MemoryReadout {
data class Device(val totalKb: Long, val availableKb: Long, val swapTotalKb: Long, val swapFreeKb: Long) {
val usedKb get() = (totalKb - availableKb).coerceAtLeast(0)
val swapUsedKb get() = (swapTotalKb - swapFreeKb).coerceAtLeast(0)
}
data class Split(val gameKb: Long, val droiddeckKb: Long, val gpuKb: Long?)
fun parseMeminfo(text: String): Device? {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(text)?.groupValues?.get(1)?.toLongOrNull()
val total = field("MemTotal") ?: return null
val available = field("MemAvailable") ?: return null
return Device(total, available, field("SwapTotal") ?: 0, field("SwapFree") ?: 0)
}
fun residentKb(status: String): Long {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(status)?.groupValues?.get(1)?.toLongOrNull() ?: 0
return field("RssAnon") + field("RssShmem")
}
fun inWinePrefix(environ: ByteArray): Boolean {
var start = 0
val key = "WINEPREFIX=".toByteArray()
for (i in 0..environ.size) {
if (i == environ.size || environ[i] == 0.toByte()) {
if (i - start >= key.size && (key.indices).all { environ[start + it] == key[it] }) return true
start = i + 1
}
}
return false
}
fun androidKb(device: Device, split: Split): Long =
(device.usedKb - split.gameKb - split.droiddeckKb - (split.gpuKb ?: 0)).coerceAtLeast(0)
fun gb(kb: Long): String = String.format(Locale.US, "%.1f", kb / (1024.0 * 1024.0))
fun availableMb(): Long? = runCatching { parseMeminfo(File("/proc/meminfo").readText())?.availableKb?.div(1024) }.getOrNull()
fun device(): Device? = runCatching { parseMeminfo(File("/proc/meminfo").readText()) }.getOrNull()
fun split(root: Int = android.os.Process.myPid()): Split {
val parents = HashMap<Int, Int>()
File("/proc").listFiles()?.forEach { entry ->
val pid = entry.name.toIntOrNull() ?: return@forEach
parentOf(pid)?.let { parents[pid] = it }
}
val children = parents.entries.groupBy({ it.value }, { it.key })
var game = 0L
var droiddeck = 0L
val queue = ArrayDeque<Int>().apply { add(root) }
val seen = HashSet<Int>()
while (queue.isNotEmpty()) {
val pid = queue.removeFirst()
if (!seen.add(pid)) continue
val status = runCatching { File("/proc/$pid/status").readText() }.getOrNull()
if (status != null) {
val kb = residentKb(status)
val windows = pid != root && runCatching { inWinePrefix(File("/proc/$pid/environ").readBytes()) }.getOrDefault(false)
if (windows) game += kb else droiddeck += kb
}
children[pid]?.let(queue::addAll)
}
return Split(game, droiddeck, gpuKb())
}
private fun parentOf(pid: Int): Int? {
val stat = runCatching { File("/proc/$pid/stat").readText() }.getOrNull() ?: return null
val close = stat.lastIndexOf(')')
if (close < 0 || close + 2 >= stat.length) return null
return stat.substring(close + 2).split(' ').getOrNull(1)?.toIntOrNull()
}
private fun gpuKb(): Long? = runCatching {
File("/sys/class/kgsl/kgsl/page_alloc").readText().trim().split(Regex("\\s+"))[0].toLong() / 1024
}.getOrNull()
}
object MemoryLog {
private const val TAG = "Memory"
private const val PERIOD_MS = 10_000L
@Volatile private var thread: Thread? = null
internal fun line(device: MemoryReadout.Device, split: MemoryReadout.Split): String =
"used ${device.usedKb / 1024}/${device.totalKb / 1024} MB, available ${device.availableKb / 1024} MB, " +
"swap ${device.swapUsedKb / 1024}/${device.swapTotalKb / 1024} MB | game ${split.gameKb / 1024}, " +
"droiddeck ${split.droiddeckKb / 1024}, android ${MemoryReadout.androidKb(device, split) / 1024}, " +
"gpu ${split.gpuKb?.div(1024) ?: "?"} MB"
@Synchronized
fun start() {
if (thread != null) return
thread = Thread({
while (!Thread.currentThread().isInterrupted) {
runCatching { MemoryReadout.device()?.let { android.util.Log.i(TAG, line(it, MemoryReadout.split())) } }
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}, "memory-log").apply { isDaemon = true; start() }
}
@Synchronized
fun stop() {
thread?.interrupt()
thread = null
}
}
class MemoryHud(context: Context) {
var text by mutableStateOf("")
private set
private val context = context.applicationContext
private val handler = Handler(Looper.getMainLooper())
@Volatile private var running = false
@Volatile private var generation = 0
private var thread: Thread? = null
fun refresh() {
if (SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) stop() else start()
}
fun start() {
if (running || SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) return
running = true
val token = ++generation
thread = Thread({
while (running && generation == token) {
val line = runCatching { sample() }.getOrDefault("")
handler.post { if (running && generation == token) text = line }
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}, "memory-hud").apply { isDaemon = true; start() }
}
fun stop() {
running = false
generation++
thread?.interrupt()
thread = null
text = ""
}
private fun sample(): String {
val device = MemoryReadout.device() ?: return ""
val memory = context.getString(
R.string.memory_hud_simple,
MemoryReadout.gb(device.usedKb), MemoryReadout.gb(device.totalKb),
MemoryReadout.gb(device.swapUsedKb), MemoryReadout.gb(device.swapTotalKb),
)
if (SessionPrefs.memoryHud(context) != SessionPrefs.MEMORY_HUD_ADVANCED) return memory
val split = MemoryReadout.split()
val parts = context.getString(
R.string.memory_hud_split,
MemoryReadout.gb(split.gameKb), MemoryReadout.gb(split.droiddeckKb), MemoryReadout.gb(MemoryReadout.androidKb(device, split)),
)
val gpu = split.gpuKb?.let { context.getString(R.string.memory_hud_gpu, MemoryReadout.gb(it)) }
return listOfNotNull(memory, parts, gpu).joinToString("\n")
}
private companion object {
const val PERIOD_MS = 2000L
}
}
@@ -9,11 +9,13 @@ import com.droiddeck.launcher.stores.epic.EpicClient
object NoSteamLaunch {
const val PROTON_RUN = "/usr/local/bin/droiddeck-proton-run"
const val EPIC = "/usr/local/bin/droiddeck-epic"
const val BATTLENET = com.droiddeck.launcher.runtime.BattleNet.PROGRAM
class Command(val program: String, val args: List<String>, val name: String)
fun scope(game: Library.SteamGame): String? = when {
game.library == Library.EPIC_LAUNCHER -> EpicClient.shortcutAppId.toString()
game.library == Library.BATTLENET_LAUNCHER -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
game.library == Library.ADDED || game.appId > 0 -> game.profileKey
else -> null
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
@@ -30,6 +32,8 @@ object NoSteamLaunch {
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id ->
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
else -> null
@@ -37,7 +41,9 @@ object NoSteamLaunch {
fun addedCommand(game: AddedGames.Game): Command = Command(
PROTON_RUN,
listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir, "--options", game.launchOptions, "--", game.guestExe),
listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir) +
(if (game.launchOptions.isEmpty()) emptyList() else listOf("--options", game.launchOptions)) +
listOf("--", game.guestExe),
game.name,
)
@@ -50,6 +56,7 @@ object NoSteamLaunch {
fun nameFor(program: String?, args: List<String>): String? = when (program) {
EPIC -> Library.EPIC_LAUNCHER_NAME
BATTLENET -> args.getOrNull(args.indexOf("launch") + 1)?.takeIf { args.contains("launch") }?.let { names[it] } ?: com.droiddeck.launcher.stores.Store.BATTLENET.label
PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }?.let { names[it] }
else -> null
}
@@ -58,5 +65,6 @@ object NoSteamLaunch {
fun remember(command: Command) {
if (command.program == PROTON_RUN) command.args.getOrNull(command.args.indexOf("--app") + 1)?.let { names[it] = command.name }
if (command.program == BATTLENET) command.args.getOrNull(command.args.indexOf("launch") + 1)?.takeIf { command.args.contains("launch") }?.let { names[it] = command.name }
}
}
@@ -114,12 +114,19 @@ object ProtonDefault {
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
if (choices.values.none { it != null && !it.valve && it.dir in from }) return null
return choices.mapValues { (_, choice) -> if (choice != null && !choice.valve && choice.dir in from) GameChoice(false, to) else choice }
}
@Synchronized
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
require(GameEnvironment.validScope(scope))
fun moveGames(context: Context, from: Set<String>, to: String) {
val d = dir(context)
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
val moved = movedGames(parseGames(read(File(d, GAMES))), from, to) ?: return
writeGames(d, moved)
}
private fun writeGames(d: File, choices: Map<String, GameChoice?>) {
val games = JSONObject()
choices.forEach { (id, choice) ->
games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL)
@@ -134,6 +141,15 @@ object ProtonDefault {
Log.w(TAG, "could not write the per-game Proton request", e)
throw e
}
}
@Synchronized
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
require(GameEnvironment.validScope(scope))
val d = dir(context)
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
writeGames(d, choices)
val state = state(context)
val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } }
return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) {
@@ -16,16 +16,20 @@ object ProtonExtras {
private const val TAG = "ProtonExtras"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
private set
@Volatile
private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null)
const val OWN = "droiddeck"
val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
@@ -78,11 +82,23 @@ object ProtonExtras {
fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool))
fun missing(context: Context, tool: Tool): String? =
if (tool.id == OWN && !declined(context) && installedAll(context, tool).isEmpty()) cachedLatest(context, tool) else null
private fun choices(context: Context) = context.getSharedPreferences("proton-auto-updates", Context.MODE_PRIVATE)
fun declined(context: Context): Boolean = choices(context).getBoolean("$OWN.declined", false)
fun setDeclined(context: Context, declined: Boolean) {
choices(context).edit().putBoolean("$OWN.declined", declined).apply()
}
fun cachedLatest(context: Context, tool: Tool): String? =
readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null }
private val checkLock = Any()
private const val RETRY_MS = 15L * 60 * 1000
private const val USER_SETTINGS = "user_settings.py"
private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
@@ -136,11 +152,51 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
File(toolsDir(context), name).deleteRecursively()
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
}
fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach { File(toolsDir(context), it).deleteRecursively() }
installedAll(context, tool).dropLast(1).forEach {
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
}
}
private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return
val older = all.dropLast(1)
if (older.isEmpty()) return
replacing = true
try {
for (old in older.asReversed()) {
if (SessionState.running) break
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old")
}
} finally {
replacing = false
}
}
private fun keepUserSettings(context: Context, old: String, newest: String) {
val from = File(File(toolsDir(context), old), USER_SETTINGS)
val to = File(File(toolsDir(context), newest), USER_SETTINGS)
if (from.isFile && !to.exists()) from.copyTo(to)
}
fun tidy(context: Context) {
val tool = tools.firstOrNull { it.id == OWN } ?: return
if (installedAll(context, tool).size > 1) replaceOlder(context, tool)
}
fun awaitReplacement(timeoutMs: Long) {
val until = System.currentTimeMillis() + timeoutMs
while (replacing && System.currentTimeMillis() < until) {
try { Thread.sleep(50) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return }
}
}
@Synchronized
@@ -244,6 +300,7 @@ object ProtonExtras {
archive.delete()
unqueue(context, tool)
record(context, tool, placed, asset.tag)
if (tool.id == OWN) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1)
try {
@@ -121,12 +121,17 @@ object SessionArtifacts {
object Deferred : ScrubResult()
}
private fun scrubFolder(dir: File, record: Record, shouldStop: () -> Boolean): Boolean {
private fun scrubFolder(
dir: File,
record: Record,
shouldStop: () -> Boolean,
beforeReplace: (File) -> Unit,
): Boolean {
val files = dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files } ?: return true
for (f in files) {
if (shouldStop()) return false
if (LogRedactor.isBinary(f)) continue
when (val result = scrubFile(dir, f, shouldStop)) {
when (val result = scrubFile(dir, f, shouldStop, beforeReplace)) {
is ScrubResult.Done -> record.files[f] = result.scrubbed
ScrubResult.Failed -> record.failed = true
ScrubResult.Deferred -> {
@@ -138,7 +143,12 @@ object SessionArtifacts {
}
return true
}
private fun scrubFile(dir: File, f: File, shouldStop: () -> Boolean): ScrubResult {
private fun scrubFile(
dir: File,
f: File,
shouldStop: () -> Boolean,
beforeReplace: (File) -> Unit,
): ScrubResult {
val tmp = File(dir, ".${f.name}.scrub")
return try {
val before = Scrubbed(f.length(), f.lastModified())
@@ -163,6 +173,11 @@ object SessionArtifacts {
tmp.delete()
return ScrubResult.Deferred
}
beforeReplace(f)
if (f.length() != before.length || f.lastModified() != before.modified) {
tmp.delete()
return ScrubResult.Failed
}
if (!tmp.renameTo(f)) {
tmp.delete()
return ScrubResult.Failed
@@ -251,9 +266,10 @@ object SessionArtifacts {
dir: File,
stopWhenSessionStarts: Boolean = false,
sessionStarted: () -> Boolean = { SessionState.running },
beforeReplace: (File) -> Unit = {},
): Boolean {
val shouldStop = { stopWhenSessionStarts && sessionStarted() }
val record = scrubTree(Record(dir), shouldStop)
val record = scrubTree(Record(dir), shouldStop, beforeReplace)
if (shouldStop()) {
record.failed = true
record.deferred = true
@@ -261,9 +277,13 @@ object SessionArtifacts {
return markScrubbed(record)
}
private fun scrubTree(record: Record, shouldStop: () -> Boolean = { false }): Record {
private fun scrubTree(
record: Record,
shouldStop: () -> Boolean = { false },
beforeReplace: (File) -> Unit = {},
): Record {
for (dir in record.dir.walkTopDown().filter { it.isDirectory }) {
if (shouldStop() || !scrubFolder(dir, record, shouldStop)) {
if (shouldStop() || !scrubFolder(dir, record, shouldStop, beforeReplace)) {
record.failed = true
record.deferred = true
break
@@ -286,6 +306,47 @@ object SessionArtifacts {
internal fun recordedClient(dir: File): String? =
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
private const val LOG_MARKS = "steam-log-marks.txt"
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
private const val HEAD = 4096L
private class Mark(val size: Long, val head: String)
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
fun markSteamLogs(dir: File, logs: File) {
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
val size = f.length()
head(f, size)?.let { "$size\t$it\t${f.name}" }
} ?: return
runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) }
}
private fun head(f: File, length: Long): String? = runCatching {
val buf = ByteArray(minOf(length, HEAD).toInt())
f.inputStream().use { input ->
var off = 0
while (off < buf.size) {
val n = input.read(buf, off, buf.size - off)
if (n < 0) return@runCatching null
off += n
}
}
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
}.getOrNull()
private fun steamLogMarks(dir: File): List<Mark>? = runCatching {
File(dir, LOG_MARKS).readLines().mapNotNull { line ->
val parts = line.split('\t', limit = 3)
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
}
}.getOrNull()
private fun startOf(src: File, size: Long, marks: List<Mark>): Long {
val heads = HashMap<Long, String?>()
return marks.filter { it.size <= size }.sortedByDescending { it.size }
.firstOrNull { m -> heads.getOrPut(minOf(m.size, HEAD)) { head(src, m.size) } == m.head }?.size ?: 0L
}
private fun copySteamLogs(
context: Context,
dir: File,
@@ -296,35 +357,123 @@ object SessionArtifacts {
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
val sources = logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }
if (sources == null) {
record.failed = true
return
}
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
record.failed = record.failed || result.failed
record.deferred = record.deferred || result.deferred
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
internal fun copySessionLogs(logs: File, dir: File, out: File): List<File> =
copySessionLogsResult(logs, dir, out) { false }.files
private fun copySessionLogsResult(
logs: File,
dir: File,
out: File,
shouldStop: () -> Boolean,
): CopyResult {
val marks = steamLogMarks(dir)
val copied = ArrayList<File>()
var failed = false
var deferred = false
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
for (src in sources) {
if (stopWhenSessionStarts && SessionState.running) {
record.failed = true
record.deferred = true
if (shouldStop()) {
failed = true
deferred = true
break
}
val size = src.length()
val from = marks?.let { startOf(src, size, it) } ?: 0L
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) continue
try {
val dst = File(out, src.name)
val copied = dst.bufferedWriter().use { w ->
LogRedactor.scrubTo(src, w) { stopWhenSessionStarts && SessionState.running }
src.inputStream().buffered().use { input ->
var left = if (from > 0) from - 1 else 0L
while (left > 0) {
val skipped = input.skip(left)
if (skipped <= 0) break
left -= skipped
}
if (from > 0 && input.read() != '\n'.code) {
while (true) {
val c = input.read()
if (c < 0 || c == '\n'.code) break
}
}
val complete = dst.bufferedWriter().use { w -> scrubSteamLog(input, w, shouldStop) }
if (!complete) {
dst.delete()
failed = true
deferred = true
}
}
if (!copied) {
dst.delete()
record.failed = true
record.deferred = true
break
}
record.files[dst] = Scrubbed(dst.length(), dst.lastModified())
if (deferred) break
copied += dst
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${src.name}", e)
record.failed = true
failed = true
}
}
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
return CopyResult(copied, failed, deferred)
}
private fun scrubSteamLog(
input: java.io.InputStream,
out: java.io.Writer,
shouldStop: () -> Boolean,
): Boolean {
input.reader().use { reader ->
val chunk = CharArray(8192)
val line = StringBuilder(4096)
var oversized = false
var pendingContent = false
var pendingCarriageReturn = false
fun emit() {
out.write(if (oversized) LogRedactor.OVERSIZED_LINE else LogRedactor.redact(line.toString()))
out.write("\n")
line.setLength(0)
oversized = false
pendingContent = false
}
while (true) {
if (shouldStop()) return false
val count = reader.read(chunk)
if (count < 0) break
if (shouldStop()) return false
for (i in 0 until count) {
if (shouldStop()) return false
val char = chunk[i]
if (pendingCarriageReturn) {
emit()
pendingCarriageReturn = false
if (char == '\n') continue
}
when (char) {
'\r' -> pendingCarriageReturn = true
'\n' -> emit()
else -> {
pendingContent = true
if (!oversized) {
if (line.length < LogRedactor.MAX_LINE_LENGTH) line.append(char)
else {
line.setLength(0)
oversized = true
}
}
}
}
}
}
if (pendingCarriageReturn || pendingContent) {
if (shouldStop()) return false
emit()
}
}
return true
}
@Synchronized
@@ -79,5 +79,5 @@ object SessionDisplay {
}
fun canStretch16x9(size: Pair<Int, Int>): Boolean =
(size.second * 16 + 4) / 9 / 2 * 2 > size.first
(size.second * 16 + 4) / 9 / 2 * 2 > size.first || (size.first * 9 + 8) / 16 / 2 * 2 > size.second
}
@@ -58,8 +58,10 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
"usr/local/bin/droiddeck-steam-desktop-ui" to "usr/local/bin/droiddeck-steam-desktop-ui",
"usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library",
"usr/local/bin/droiddeck-steam-share" to "usr/local/bin/droiddeck-steam-share",
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
"usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores",
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
@@ -72,12 +74,14 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
"usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url",
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
"usr/local/bin/droiddeck-steam-x64" to "usr/local/bin/droiddeck-steam-x64",
"usr/local/bin/droiddeck-steamrt-shim" to "usr/local/bin/droiddeck-steamrt-shim",
"usr/local/bin/droiddeck-x64-arm-proton" to "usr/local/bin/droiddeck-x64-arm-proton",
"usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper",
"usr/local/bin/droiddeck-x64-webhelper" to "usr/local/bin/droiddeck-x64-webhelper",
@@ -94,6 +98,15 @@ object SessionFiles {
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
"usr/local/bin/droiddeck-innoextract" to "usr/local/bin/droiddeck-innoextract",
"usr/local/lib/droiddeck-inno/innoextract" to "usr/local/lib/droiddeck-inno/innoextract",
"usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0",
"usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract" to "usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract",
"usr/local/share/licenses/droiddeck-inno/LICENSE.boost" to "usr/local/share/licenses/droiddeck-inno/LICENSE.boost",
"usr/bin/steamos-update" to "usr/bin/steamos-update",
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
"usr/bin/steamos-session-select" to "usr/bin/steamos-session-select",
@@ -138,6 +151,8 @@ object SessionFiles {
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
// The gamescope pack carries its own WSI layer (patch 0117); it replaces the runtime's stock copy.
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
@@ -202,7 +217,11 @@ object SessionFiles {
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n")
if (ProotFastPath.enabled(context)) {
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
preload.append(library + "\n")
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
}
val etc = File(root, "etc").apply { mkdirs() }
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
@@ -388,10 +407,12 @@ object SessionFiles {
private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text)
/** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */
internal fun startupMoviePath(config: File): String? {
internal fun startupMoviePath(config: File): String? = startupMovieLocalPath(config)?.takeIf { it.isNotEmpty() }
internal fun startupMovieLocalPath(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val movie = activeStartupMovie(text) ?: return null
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")?.takeIf { it.isNotEmpty() }
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")
}
/** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */
@@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue
import androidx.core.content.FileProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.zip.ZipEntry
@@ -49,7 +50,8 @@ object SessionLogShare {
val logs = LinuxRuntime.logDir(context)
val stores = recent(File(logs, STORES_DIR))
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
val total = (files + live + stores + tools).sumOf { it.length() }.coerceAtLeast(1L)
val battleNet = battleNetLogs(context)
val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L
var shown = -1
fun advance(f: File) {
@@ -62,6 +64,7 @@ object SessionLogShare {
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) }
}
return zip
}
@@ -88,6 +91,27 @@ object SessionLogShare {
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
private const val BATTLENET_DIR = "battlenet"
private fun battleNetLogs(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") }
return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) +
newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) +
newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) +
newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true)
}
private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dirs.flatMap { dir ->
dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList()
}.sortedByDescending { it.lastModified() }.take(count).map { f ->
(if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f
}
}
private fun recent(dir: File): List<File> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
@@ -4,7 +4,6 @@ import android.content.Context
import android.content.pm.ActivityInfo
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.CpuAllocationDefaults
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard
@@ -50,9 +49,9 @@ object SessionPrefs {
)
fun orientation(context: Context): Int =
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun setOrientation(context: Context, orientation: Int) {
require(orientationOptions.any { it.first == orientation })
@@ -92,13 +91,6 @@ object SessionPrefs {
*/
fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive"
fun storesOpenTab(context: Context): String =
prefs(context).getString("storesOpenTab", STORES_OPEN_LIBRARY)?.takeIf { it == STORES_OPEN_STORE } ?: STORES_OPEN_LIBRARY
fun setStoresOpenTab(context: Context, tab: String) {
prefs(context).edit().putString("storesOpenTab", if (tab == STORES_OPEN_STORE) STORES_OPEN_STORE else STORES_OPEN_LIBRARY).apply()
}
fun storesShowMature(context: Context): Boolean = prefs(context).getBoolean("storesShowMature", false)
fun setStoresShowMature(context: Context, show: Boolean) {
@@ -136,9 +128,6 @@ object SessionPrefs {
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
val STORES_VIEWS = listOf("cards", "capsules", "list")
const val STORES_OPEN_LIBRARY = "library"
const val STORES_OPEN_STORE = "store"
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
fun setStoresInstallTarget(context: Context, path: String) {
@@ -152,6 +141,34 @@ object SessionPrefs {
prefs(context).edit().putString("storesInstallLanguage", code).apply()
}
const val DEFAULT_STORAGE_ASK = "ask"
const val DEFAULT_STORAGE_INTERNAL = "internal"
const val DEFAULT_STORAGE_EXTERNAL = "external"
private val DEFAULT_STORAGE_VALUES = setOf(DEFAULT_STORAGE_ASK, DEFAULT_STORAGE_INTERNAL, DEFAULT_STORAGE_EXTERNAL)
fun defaultStorage(context: Context): String =
prefs(context).getString("defaultStorage", DEFAULT_STORAGE_ASK)
?.takeIf { it in DEFAULT_STORAGE_VALUES } ?: DEFAULT_STORAGE_ASK
fun setDefaultStorage(context: Context, value: String) {
prefs(context).edit().putString("defaultStorage", value.takeIf { it in DEFAULT_STORAGE_VALUES } ?: DEFAULT_STORAGE_ASK).apply()
}
fun defaultStorageFolder(context: Context): String = prefs(context).getString("defaultStorageFolder", "") ?: ""
fun defaultStorageFolderLabel(context: Context): String = prefs(context).getString("defaultStorageFolderLabel", "") ?: ""
fun setDefaultStorageFolder(context: Context, path: String, label: String) {
prefs(context).edit()
.putString("defaultStorageFolder", path)
.putString("defaultStorageFolderLabel", label)
.apply()
}
fun clearDefaultStorageFolder(context: Context) {
prefs(context).edit().remove("defaultStorageFolder").remove("defaultStorageFolderLabel").apply()
}
fun gameStoresParallel(context: Context): Int = prefs(context).getInt("gameStoresParallel", 1).coerceIn(1, 3)
fun setGameStoresParallel(context: Context, count: Int) {
@@ -263,6 +280,19 @@ object SessionPrefs {
const val GPU_DRIVERS_MANUAL = "manual"
const val GPU_DRIVERS_MIX = "mix"
const val TP_UBWC_AUTO = "auto"
const val TP_UBWC_ON = "on"
const val TP_UBWC_OFF = "off"
fun tpUbwcMode(context: Context): String =
prefs(context).getString("tpUbwcMode", TP_UBWC_AUTO)
?.takeIf { it in setOf(TP_UBWC_AUTO, TP_UBWC_ON, TP_UBWC_OFF) } ?: TP_UBWC_AUTO
fun setTpUbwcMode(context: Context, mode: String) {
require(mode in setOf(TP_UBWC_AUTO, TP_UBWC_ON, TP_UBWC_OFF))
prefs(context).edit().putString("tpUbwcMode", mode).commit()
}
fun gpuDriverMode(context: Context): String =
prefs(context).getString("gpuDriverMode", GPU_DRIVERS_AUTO) ?: GPU_DRIVERS_AUTO
@@ -304,6 +334,34 @@ object SessionPrefs {
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
}
private fun shaderPrecacheApplied(context: Context) =
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.bl-shader-precache-applied")
/**
* Shader pre-caching as the launcher last set it, until a session reports it written into the
* client's config.vdf; after that the client's own toggle is the user's again.
*/
fun pendingShaderPrecache(context: Context): Boolean? {
val prefs = prefs(context)
if (!prefs.contains("shaderPrecache")) return null
val on = prefs.getBoolean("shaderPrecache", true)
val applied = shaderPrecacheApplied(context)
val written = runCatching { applied.readText().trim() }.getOrNull() ?: return on
applied.delete()
if (written != if (on) "1" else "0") return on
prefs.edit().remove("shaderPrecache").apply()
return null
}
fun setShaderPrecache(context: Context, on: Boolean) {
shaderPrecacheApplied(context).delete()
prefs(context).edit().putBoolean("shaderPrecache", on).apply()
}
fun shaderPrecache(context: Context): Boolean = pendingShaderPrecache(context)
?: runCatching { com.droiddeck.launcher.storage.SteamStorage.shaderPrecache(
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf").readText()) }.getOrDefault(true)
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
fun setStretch16x9(context: Context, on: Boolean) {
@@ -341,30 +399,19 @@ object SessionPrefs {
prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply()
}
internal data class CoreAllocation(val clientOverride: Boolean, val clientCpus: String, val gameCpus: String)
internal fun coreAllocation(context: Context, defaults: CpuAllocationDefaults.Allocation? = CpuAllocationDefaults.device): CoreAllocation {
val saved = prefs(context)
return CoreAllocation(
saved.getBoolean("clientCpusOverride", defaults != null && !saved.contains("clientCpus")),
saved.getString("clientCpus", defaults?.client.orEmpty()).orEmpty(),
saved.getString("gameCpus", defaults?.game.orEmpty()).orEmpty(),
)
}
fun clientCpusOverride(context: Context): Boolean = coreAllocation(context).clientOverride
fun clientCpusOverride(context: Context): Boolean = prefs(context).getBoolean("clientCpusOverride", false)
fun setClientCpusOverride(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
}
fun clientCpus(context: Context): String = coreAllocation(context).clientCpus
fun clientCpus(context: Context): String = prefs(context).getString("clientCpus", "").orEmpty()
fun setClientCpus(context: Context, list: String) {
prefs(context).edit().putString("clientCpus", list).apply()
}
fun gameCpus(context: Context): String = coreAllocation(context).gameCpus
fun gameCpus(context: Context): String = prefs(context).getString("gameCpus", "").orEmpty()
fun setGameCpus(context: Context, list: String) {
prefs(context).edit().putString("gameCpus", list).apply()
@@ -376,7 +423,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("noXalia", on).apply()
}
fun fastSync(context: Context): Boolean = prefs(context).getBoolean("fastSync", false)
fun fastSync(context: Context): Boolean = prefs(context).getBoolean("fastSync", true)
fun setFastSync(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("fastSync", on).apply()
@@ -411,6 +458,17 @@ object SessionPrefs {
.apply()
}
fun applyNtsyncDefault(context: Context) {
val prefs = prefs(context)
if (prefs.getBoolean("ntsyncDefaultV1", false)) return
prefs.edit()
.putBoolean("fastSync", true)
.putBoolean("fsyncFirst", false)
.putBoolean("syncFallback", true)
.putBoolean("ntsyncDefaultV1", true)
.apply()
}
fun syncFallback(context: Context): Boolean = prefs(context).getBoolean("syncFallback", true)
fun setSyncFallback(context: Context, on: Boolean) {
@@ -423,6 +481,24 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gamescopeRealtime", on).apply()
}
fun ramCapMb(context: Context): Int = prefs(context).getInt("ramCapMb", 0).coerceAtLeast(0)
fun setRamCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("ramCapMb", mb.coerceAtLeast(0)).apply()
}
fun zramClient(context: Context): Boolean = prefs(context).getBoolean("zramClient", true)
fun setZramClient(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramClient", on).apply()
}
fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0)
fun setVramCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("vramCapMb", mb.coerceAtLeast(0)).apply()
}
fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false)
fun setGpuClockPin(context: Context, on: Boolean) {
@@ -444,6 +520,13 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
/** gamescope draws the cursor itself. Off by default: on a phone that plane costs frames. */
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", false)
fun setCursorComposite(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("cursorComposite", on).apply()
}
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
@JvmStatic
@@ -513,25 +596,29 @@ object SessionPrefs {
fun logsEnabled(context: Context): Boolean =
prefs(context).getBoolean("logs", true)
fun setLogsEnabled(context: Context, on: Boolean): Boolean = setLogPreference(
context,
key = "logs",
oldValue = logsEnabled(context),
newValue = on,
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
)
fun setLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
setLogPreference(
context,
key = "logs",
oldValue = logsEnabled(context),
newValue = on,
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
)
}
/** Extra Proton, Wine and graphics diagnostics for the next game launch; off unless chosen. */
fun gameDebugLogsEnabled(context: Context): Boolean =
prefs(context).getBoolean("gameDebugLogsEnabled", false)
fun setGameDebugLogsEnabled(context: Context, on: Boolean): Boolean = setLogPreference(
context,
key = "gameDebugLogsEnabled",
oldValue = gameDebugLogsEnabled(context),
newValue = on,
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
)
fun setGameDebugLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
setLogPreference(
context,
key = "gameDebugLogsEnabled",
oldValue = gameDebugLogsEnabled(context),
newValue = on,
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
)
}
private fun setLogPreference(
context: Context,
@@ -545,6 +632,11 @@ object SessionPrefs {
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
SessionPaths.currentSessionLogsRetained(context)
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
if (oldEffective == newEffective) {
if (saved.edit().putBoolean(key, newValue).commit()) return true
saved.edit().putBoolean(key, oldValue).commit()
return false
}
if (oldEffective && !newEffective) {
try {
publish(false)
@@ -574,6 +666,32 @@ object SessionPrefs {
}
}
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false)
fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() }
fun backgroundAppLimit(context: Context): Int =
prefs(context).getInt("backgroundAppLimit", com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
.takeIf { it in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES } ?: com.droiddeck.launcher.core.BackgroundAppLimit.OFF
fun setBackgroundAppLimit(context: Context, limit: Int) {
require(limit in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES)
prefs(context).edit().putInt("backgroundAppLimit", limit).apply()
}
const val MEMORY_HUD_OFF = "off"
const val MEMORY_HUD_SIMPLE = "simple"
const val MEMORY_HUD_ADVANCED = "advanced"
fun memoryHud(context: Context): String =
prefs(context).getString("memoryHud", MEMORY_HUD_OFF)
?.takeIf { it == MEMORY_HUD_SIMPLE || it == MEMORY_HUD_ADVANCED } ?: MEMORY_HUD_OFF
fun setMemoryHud(context: Context, value: String) {
require(value == MEMORY_HUD_OFF || value == MEMORY_HUD_SIMPLE || value == MEMORY_HUD_ADVANCED)
prefs(context).edit().putString("memoryHud", value).apply()
}
fun storageDiagnosticsEnabled(context: Context): Boolean =
prefs(context).getBoolean("storageDiagnostics", false)
@@ -821,6 +939,14 @@ object SessionPrefs {
it.getInt("gradientSecondary", com.droiddeck.launcher.ui.Themes.DEFAULT_SECONDARY)
}
/** How fast the Inner Gamer theme cycles its colours, 1 to 10. */
fun rgbSpeed(context: Context): Int =
prefs(context).getInt("innerGamerSpeed", com.droiddeck.launcher.ui.Themes.DEFAULT_RGB_SPEED).coerceIn(1, com.droiddeck.launcher.ui.Themes.RGB_SPEEDS)
fun setRgbSpeed(context: Context, speed: Int) {
prefs(context).edit().putInt("innerGamerSpeed", speed.coerceIn(1, com.droiddeck.launcher.ui.Themes.RGB_SPEEDS)).apply()
}
fun setGradientColors(context: Context, primary: Int, secondary: Int) {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
@@ -843,7 +969,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
}
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0)
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0).coerceAtLeast(0)
fun setFpsLimit(context: Context, mode: String, fps: Int) {
prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply()
@@ -854,6 +980,22 @@ object SessionPrefs {
fun fpsLimitChoices(context: Context): List<Pair<Int, String>> =
fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label }
/**
* Performance mode: without a frame limit, buffers go back to the game as soon as they are replaced
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
*/
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
fun setPerformanceMode(context: Context, mode: String, on: Boolean) {
prefs(context).edit().putBoolean("performanceMode.$mode", on).apply()
}
/** Compositor frame limit that releases buffers to the game unpaced. */
const val FPS_UNPACED = -1
/** The limit handed to the compositor: Performance mode without a limit is unpaced, a chosen limit still paces. */
fun compositorFpsLimit(limit: Int, performanceMode: Boolean): Int = if (performanceMode && limit <= 0) FPS_UNPACED else limit
val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
@@ -71,6 +71,7 @@ class SessionService : Service() {
private val steamDownloadMonitor = SteamDownloadMonitor()
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var clientInstallActive = false
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
private var suspendDownloadNow = false
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
@@ -277,6 +278,16 @@ class SessionService : Service() {
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_MIC_CHANGED -> {
if (SessionState.running && SessionState.micAvailable && !SessionState.suspended) {
val enabled = intent.getBooleanExtra("enabled", false)
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay?.setMicEnabled(enabled) != true) {
android.widget.Toast.makeText(this, R.string.drawer_mic_failed, android.widget.Toast.LENGTH_LONG).show()
}
}
return START_NOT_STICKY
}
ACTION_SUSPEND_POLICY_CHANGED -> {
if (!SessionState.running) return START_NOT_STICKY
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
@@ -321,19 +332,27 @@ class SessionService : Service() {
suspendDownloadNow = false
steamDownloadMonitor.reset()
downloadActive = false
clientInstallActive = false
steamSleepToken = null
completeNativeSleep()
suspendOperationPending = false
freezePending = false
suspendAttemptFailed = false
suspendController = null
SessionState.micAvailable = false
SessionState.micEnabled = false
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
SessionState.pipActive = false
pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.gameId = intent?.getStringExtra(EXTRA_GAME_ID)
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
@@ -348,6 +367,9 @@ class SessionService : Service() {
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
com.droiddeck.launcher.wayland.CompositorHost.newSession()
val gen = ++sessionGen
SessionPrefs.backgroundAppLimit(this).takeIf { it != com.droiddeck.launcher.core.BackgroundAppLimit.OFF }
?.let { com.droiddeck.launcher.core.BackgroundAppLimit.applyAsync(this, it) }
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
cancelQueuedSteamGame(clearMailbox = false)
clearSteamGameMailbox()
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
@@ -355,16 +377,17 @@ class SessionService : Service() {
acquireLocks()
Thread({
OrphanReaper.reap("session starting")
ProtonExtras.awaitReplacement(120_000)
runSession(gen)
}, "session-start").start()
return START_NOT_STICKY
}
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
SessionLogCapture.stopFor(dir)
try {
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
} finally {
SessionLogCapture.stopFor(dir)
SessionPaths.release(this, dir)
}
}
@@ -394,7 +417,7 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionTerminal.clear()
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice()
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)
try {
LinuxRuntime.writeAccounts(this)
} catch (e: Exception) {
@@ -409,6 +432,9 @@ class SessionService : Service() {
killStragglers()
for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO))
if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable")
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
SessionFiles.stage(this, root, startsSession = true)
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
SessionArtifacts.awaitCollections()
@@ -439,7 +465,7 @@ class SessionService : Service() {
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "forced components", it) }
}
addClientEnvironment(guest, steamHere)
addClientEnvironment(guest, steamHere, agentEnvironment)
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
@@ -460,6 +486,16 @@ class SessionService : Service() {
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
}
guest.add("BL_FPS=" + SessionState.fpsLimit)
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
if (SessionPrefs.compositorFpsLimit(SessionState.fpsLimit, SessionState.performanceMode) == SessionPrefs.FPS_UNPACED) {
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
}
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off") + ", frame limit " + SessionState.fpsLimit)
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
@@ -549,6 +585,9 @@ class SessionService : Service() {
Log.i(TAG, "proot: seccomp acceleration off by request")
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } }
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { hostEnv[key] = it }
}
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
@@ -591,7 +630,7 @@ class SessionService : Service() {
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
stopSession(program ?: status ?: -1)
}, null)
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() })
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while its guest was starting; taking it down")
@@ -644,8 +683,8 @@ class SessionService : Service() {
}
},
)
mainHandler.post { updateSuspendPolicy() }
updateDownloadMonitoring()
mainHandler.post { updateSuspendPolicy() }
}
}
@@ -660,10 +699,11 @@ class SessionService : Service() {
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log"))
MemoryLog.start()
return sessionDir
}
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean) {
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) {
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
@@ -677,6 +717,7 @@ class SessionService : Service() {
com.droiddeck.launcher.core.AppLanguage.system(this).country,
))
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("BL_SHADER_PRECACHE=" + if (it) "1" else "0") }
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
@@ -699,7 +740,6 @@ class SessionService : Service() {
val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice()?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
if (SessionPrefs.zinkLazy(this)) {
guest.add("ZINK_DESCRIPTORS=lazy")
guest.add("ZINK_DEBUG=compact")
@@ -712,7 +752,10 @@ class SessionService : Service() {
SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null
SessionState.steamClientArch?.let { arch ->
guest.add("BL_STEAM_CLIENT_ARCH=$arch")
SessionPaths.current()?.let { SessionArtifacts.recordClient(it, arch) }
SessionPaths.current()?.let {
SessionArtifacts.recordClient(it, arch)
SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs"))
}
if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
}
if (SessionState.mode == MODE_STEAM) {
@@ -723,11 +766,18 @@ class SessionService : Service() {
guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0"))
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
if (com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1")
if (com.droiddeck.launcher.core.ZramSupport.supported()) {
guest.add("BL_ZRAM=1")
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_RAM_CAP_MB=$it") }
if (!SessionPrefs.zramClient(this)) guest.add("BL_ZRAM_CLIENT=0")
}
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") }
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this)
val extra = extraEnv() + agentEnvironment
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
extra.forEach { guest.add(it) }
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this)
if (clientPinned) {
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
@@ -737,7 +787,7 @@ class SessionService : Service() {
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC)
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
@@ -758,6 +808,15 @@ class SessionService : Service() {
components.add(pulse)
if (wantsDirectAudio || wantsMic) {
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
val gen = sessionGen
relay.onMicEnabled = java.util.function.Consumer { enabled ->
mainHandler.post {
if (gen == sessionGen && SessionState.running && wantsMic) {
SessionState.micAvailable = true
SessionState.micEnabled = enabled
}
}
}
relay.setLogFile(audioLog)
relay.attach(this)
components.add(relay)
@@ -1028,6 +1087,7 @@ class SessionService : Service() {
if (!stillSameProcess()) return
val tree = descendants(prootPid)
if (!stillSameProcess()) return
saveWineRegistries(tree)
android.os.Process.sendSignal(prootPid, 15)
if (!waitForExit(prootPid, GRACE_MS)) {
if (!stillSameProcess()) return
@@ -1044,6 +1104,31 @@ class SessionService : Service() {
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
}
private fun clearCachedApps() {
val app = applicationContext
Thread({
val before = MemoryReadout.availableMb()
val result = runCatching { com.droiddeck.launcher.core.WirelessAdbFix.clearCachedApps(app) }
val after = MemoryReadout.availableMb()
result.onSuccess { Log.i(TAG, "cached apps closed: available memory $before -> $after MB") }
.onFailure { Log.w(TAG, "cached apps not closed: ${it.message}") }
}, "clear-cached-apps").start()
}
private fun saveWineRegistries(tree: List<Pair<Int, Long>>) {
val servers = tree.filter { (pid, started) ->
readStat(pid)?.second == started && WineProcesses.isWineserver(
runCatching { File("/proc/$pid/cmdline").readBytes() }.getOrNull(),
runCatching { File("/proc/$pid/comm").readText() }.getOrNull(),
)
}
if (servers.isEmpty()) return
servers.forEach { (pid, _) -> android.os.Process.sendSignal(pid, 15) }
val deadline = System.currentTimeMillis() + WINE_SAVE_MS
val saved = servers.count { (pid, _) -> waitForExit(pid, (deadline - System.currentTimeMillis()).coerceAtLeast(0)) }
Log.i(TAG, "wineserver registry save: $saved of ${servers.size} exited after SIGTERM")
}
private fun descendants(root: Int): List<Pair<Int, Long>> {
val started = HashMap<Int, Long>()
val children = HashMap<Int, MutableList<Int>>()
@@ -1217,6 +1302,7 @@ class SessionService : Service() {
}
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
@@ -1322,6 +1408,11 @@ class SessionService : Service() {
}
return
}
if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) {
File(dir, path).delete()
com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir)
return
}
if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) {
val request = File(dir, path)
val text = runCatching { request.readText() }.getOrNull() ?: return
@@ -1414,10 +1505,12 @@ class SessionService : Service() {
private fun updateSuspendPolicy() {
if (!SessionState.running) return
val hidden = !hasVisibleSurface
val downloadsBlockingSuspend = steamDownloadsInBackground && SessionState.mode == MODE_STEAM &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER && hidden && downloadActive && !suspendDownloadNow
val downloadsBlockingSuspend = downloadsKeepAwake() && hidden && !suspendDownloadNow
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) {
manualPauseRequested = true
} else if (!hidden && !SessionState.suspended) {
// Coming back before the freeze finished keeps the game running instead of pausing it a moment later.
manualPauseRequested = false
}
val controller = suspendController ?: return
if (downloadsBlockingSuspend) acquireLocks()
@@ -1443,6 +1536,7 @@ class SessionService : Service() {
freezeCancelled = true
controller.cancelFreeze()
}
if (shouldSuspend && SessionState.suspended && !suspendOperationPending) SessionState.resumeRequested = false
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
val gen = sessionGen
suspendOperationPending = true
@@ -1466,6 +1560,7 @@ class SessionService : Service() {
freezePending = false
if (success) {
SessionState.suspended = true
SessionState.resumeFailed = false
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
releaseLocks()
refreshNotification()
@@ -1484,16 +1579,22 @@ class SessionService : Service() {
}
} else {
acquireLocks()
SessionState.resuming = true
controller.resume { success ->
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
suspendOperationPending = false
SessionState.resuming = false
SessionState.resumeRequested = false
if (success) {
SessionState.suspended = false
SessionState.resumeFailed = false
SessionEvents.transition(SessionEvents.resumePhase(), "session.resumed")
refreshNotification()
} else {
suspendAttemptFailed = true
SessionState.resumeFailures++
SessionState.resumeFailed = true
Log.w(TAG, "could not confirm that the session resumed")
}
updateSuspendPolicy()
@@ -1576,37 +1677,46 @@ class SessionService : Service() {
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
}
private fun finishSessionStop(status: Int, stoppedGen: Int) {
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
mainHandler.post {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
try {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
}
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
com.droiddeck.launcher.agent.AgentGuest.stop()
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
MemoryLog.stop()
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
val code = SessionState.failureCode ?: "GUEST_EXIT"
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
val failureStatus = SessionState.failureStatus ?: status
SessionEvents.fail(code, message, failureStatus)
}
SessionState.steamVr = false
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
} finally {
afterStopped()
}
SessionState.suspended = false
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
com.droiddeck.launcher.agent.AgentGuest.stop()
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
val code = SessionState.failureCode ?: "GUEST_EXIT"
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
val failureStatus = SessionState.failureStatus ?: status
SessionEvents.fail(code, message, failureStatus)
}
SessionState.steamVr = false
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
@@ -1634,19 +1744,22 @@ class SessionService : Service() {
completeNativeSleep()
val (ended, endedArch) = synchronized(stopLock) {
if (!SessionState.running) return
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
SessionState.running = false
SessionPaths.take() to SessionState.steamClientArch
}
SessionState.micAvailable = false
SessionState.micEnabled = false
xrActivityVisible = false
updateDownloadMonitoring()
val stoppedGen = sessionGen
val stoppedSession = SessionState.sessionId
val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC
val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC ||
SessionState.program == NoSteamLaunch.BATTLENET
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
GpuClockPin.stop(this)
GameThreadHints.stop()
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
suspendOperationPending = false
freezePending = false
launchWatcher?.stopWatching()
@@ -1664,7 +1777,6 @@ class SessionService : Service() {
if (ended != null) {
VacDiagnostics.snapshot(this, ended)
SessionArtifacts.collectionStarted(ended)
Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
}
components.reversed().forEach {
try {
@@ -1674,6 +1786,9 @@ class SessionService : Service() {
}
}
components.clear()
val collectEnded = {
if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
}
FakeInputWriter.releaseAllRingSlots()
com.droiddeck.launcher.input.SteamTouchDevice.release()
val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
@@ -1685,13 +1800,13 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
finishSessionStop(status, stoppedGen)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "session-teardown").start()
} else {
Thread({
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "gog-session-stop").start()
}
@@ -1703,6 +1818,9 @@ class SessionService : Service() {
private fun importLauncherGames() {
runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.importClientGames(this) }
.onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") }
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(this) }
.onFailure { Log.w(TAG, "Battle.net sign-in check failed: ${it.javaClass.simpleName}") }
com.droiddeck.launcher.stores.StoresState.notifyLibraryChanged(this)
}
override fun onTaskRemoved(rootIntent: Intent?) {
@@ -1815,8 +1933,7 @@ class SessionService : Service() {
.setContentText(getString(
when {
SessionState.suspended -> R.string.session_notification_paused
downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER -> R.string.session_notification_downloads
downloadsKeepAwake() -> R.string.session_notification_downloads
else -> R.string.session_notification
}
))
@@ -1824,8 +1941,7 @@ class SessionService : Service() {
.apply {
if (SessionState.suspended) {
addAction(Notification.Action.Builder(null, getString(R.string.resume_session), resume).build())
} else if (downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER) {
} else if (downloadsKeepAwake()) {
val suspend = PendingIntent.getService(
this@SessionService, 3,
Intent(this@SessionService, SessionService::class.java).setAction(ACTION_SUSPEND_NOW),
@@ -1845,33 +1961,50 @@ class SessionService : Service() {
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
}
private fun downloadsKeepAwake(): Boolean =
downloadActive && (steamDownloadsInBackground || clientInstallActive) &&
SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER
private fun downloadWatchWanted(): Boolean =
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
private fun updateDownloadMonitoring() {
val enabled = SessionState.running && SessionState.mode == MODE_STEAM &&
steamDownloadsInBackground && suspendPolicy != SessionPrefs.SUSPEND_NEVER
if (!enabled) {
if (!downloadWatchWanted()) {
val wasActive = downloadActive
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
steamDownloadMonitor.reset()
downloadActive = false
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
clientInstallActive = false
if (wasActive) refreshNotification()
return
}
if (downloadMonitorTask != null) return
val poll = object : Runnable {
override fun run() {
if (downloadMonitorTask !== this || !SessionState.running ||
SessionState.mode != MODE_STEAM || !steamDownloadsInBackground ||
suspendPolicy == SessionPrefs.SUSPEND_NEVER) {
if (downloadMonitorTask !== this) return
if (!downloadWatchWanted()) {
downloadMonitorTask = null
updateDownloadMonitoring()
updateSuspendPolicy()
return
}
val root = LinuxRuntime.rootDir(this@SessionService)
val wasActive = downloadActive
downloadActive = steamDownloadMonitor.poll(
LinuxRuntime.rootDir(this@SessionService),
val wasInstalling = clientInstallActive
clientInstallActive = !SessionState.firstFrameSeen &&
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
root,
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
client = SessionState.steamClientArch,
mounts = steamLibraryMounts,
)
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
}
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
@@ -1916,6 +2049,7 @@ class SessionService : Service() {
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
const val ACTION_AGENT_START = "com.droiddeck.launcher.AGENT_START"
private const val ACTION_MIC_CHANGED = "com.droiddeck.launcher.MIC_CHANGED"
private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED"
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
@@ -1934,6 +2068,7 @@ class SessionService : Service() {
private val STRAGGLERS = listOf("droiddeck-session", "gamescope", "Xwayland", "steamrtarm64",
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
private const val GRACE_MS = 1200L
private const val WINE_SAVE_MS = 3000L
private const val STEAM_PICKUP_MS = 1500L
private const val STEAM_EXIT_MS = 10_000L
private const val GAME_LAUNCH_RETRY_MS = 250L
@@ -1965,6 +2100,7 @@ class SessionService : Service() {
fun start(
context: Context, mode: String = MODE_STEAM, program: String? = null,
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY,
) {
SessionState.activityDisplayId = displayId
@@ -1975,6 +2111,7 @@ class SessionService : Service() {
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl)
if (gameId != null) intent.putExtra(EXTRA_GAME_ID, gameId)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent)
else context.startService(intent)
}
@@ -2029,6 +2166,7 @@ class SessionService : Service() {
fun resume(context: Context) {
if (!SessionState.running) return
if (SessionState.suspended) SessionState.resumeRequested = true
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
}
@@ -2045,6 +2183,11 @@ class SessionService : Service() {
}.getOrDefault(false)
}
fun setMicEnabled(context: Context, enabled: Boolean) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_MIC_CHANGED)
.putExtra("enabled", enabled))
}
fun suspendPolicyChanged(context: Context) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import java.io.File
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
@@ -45,13 +46,21 @@ object SessionState {
var activityDisplayId = 0
@Volatile
var runtimeDriver: String? = null
var micAvailable by mutableStateOf(false)
var micEnabled by mutableStateOf(false)
var suspended by mutableStateOf(false)
var resumeRequested by mutableStateOf(false)
var resuming by mutableStateOf(false)
var resumeFailures by mutableIntStateOf(0)
var resumeFailed by mutableStateOf(false)
@Volatile var pipActive = false
@Volatile
var program: String? = null
@Volatile
var programArgs: List<String> = emptyList()
@Volatile
var gameId: String? = null
@Volatile
var steamUi: String? = null
@Volatile
var steamUrl: String? = null
@@ -97,6 +106,9 @@ object SessionState {
@Volatile
var fpsLimit: Int = 0
@Volatile
var performanceMode = false
@Volatile
var firstFrameSeen = false
@@ -18,9 +18,9 @@ object SettingsReset {
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
@@ -29,7 +29,7 @@ object SettingsReset {
)
internal val SESSION_PREFIXES = listOf(
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "suspendPolicy.",
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "performanceMode.", "suspendPolicy.",
)
private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake")
@@ -1,7 +1,7 @@
package com.droiddeck.launcher.session
import java.io.File
import java.io.RandomAccessFile
import java.io.FileInputStream
internal class SteamDownloadMonitor {
private data class ManifestState(
@@ -63,16 +63,17 @@ internal class SteamDownloadMonitor {
lastContentActivityAt = 0L
}
runCatching {
RandomAccessFile(log, "r").use { input ->
input.seek(contentLogOffset)
FileInputStream(log).use { input ->
input.channel.position(contentLogOffset)
val reader = input.bufferedReader(Charsets.ISO_8859_1)
while (true) {
val line = input.readLine() ?: break
val line = reader.readLine() ?: break
when {
"Client version:" in line -> {
activeContentUpdates.clear()
lastContentActivityAt = 0L
}
CONTENT_UPDATE.find(line)?.let { match ->
" update changed : " in line && CONTENT_UPDATE.find(line)?.let { match ->
val appId = match.groupValues[1]
val updateType = match.groupValues[2]
val state = match.groupValues[3]
@@ -85,14 +86,15 @@ internal class SteamDownloadMonitor {
}
true
} == true -> Unit
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
"Current download rate: " in line &&
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
lastContentActivityAt = now
"Downloading " in line && " chunks for depot " in line ->
lastContentActivityAt = now
}
if (activeContentUpdates.isNotEmpty()) lastContentActivityAt = now
}
contentLogOffset = input.filePointer
contentLogOffset = input.channel.position()
}
}
return activeContentUpdates.isNotEmpty() && lastContentActivityAt > 0L &&
@@ -138,13 +140,21 @@ internal class SteamDownloadMonitor {
private fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
private companion object {
const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
companion object {
fun clientInstallPending(runtimeRoot: File): Boolean {
val home = File(runtimeRoot, "root")
val steam = File(home, ".local/share/Steam")
val stamped = File(steam, "package/droiddeck-installed").isFile ||
File(steam, "package/bannerlator-installed").isFile
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
}
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
}
}
@@ -101,10 +101,28 @@ object WinComponents {
fun cached(context: Context): List<Component>? =
runCatching { parse(File(context.filesDir, CATALOG_CACHE).readText()) }.getOrNull()
const val VCREDIST_ARM64 = "vcredist2022_arm64"
/**
* The ARM64 Visual C++ 2015-2022 runtime as registry values only (the version a 14.44.35211 installer writes, in both
* registry views). Xbox games' launchers running as ARM64EC check for it; Wine's own CRT does the work. Same approach as
* MGamer404's Bannerlator #627. Used until the catalog carries a component of this name.
*/
internal fun builtInArm64Runtime(): Component {
fun value(view: String, name: String, type: String, data: String) = Step("set_register_key", JSONObject()
.put("action", "set_register_key").put("key", "HKLM\\Software\\${view}Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\arm64")
.put("value", name).put("type", type).put("data", data))
val steps = listOf("", "Wow6432Node\\").flatMap { view ->
listOf(value(view, "Installed", "REG_DWORD", "1"), value(view, "Major", "REG_DWORD", "14"), value(view, "Minor", "REG_DWORD", "44"),
value(view, "Bld", "REG_DWORD", "35211"), value(view, "Rbld", "REG_DWORD", "0"), value(view, "Version", "REG_SZ", "v14.44.35211.00"))
}
return Component(VCREDIST_ARM64, "Microsoft Visual C++ 2015-2022 ARM64 runtime 14.44.35211 (registry entries only)", "Microsoft", "ready", emptyList(), steps)
}
private fun parse(body: String): List<Component>? {
return try {
val arr = JSONObject(body).getJSONArray("components")
(0 until arr.length()).mapNotNull { i ->
val listed = (0 until arr.length()).mapNotNull { i ->
val o = arr.getJSONObject(i)
val name = o.optString("name")
if (!validId(name)) return@mapNotNull null
@@ -117,6 +135,7 @@ object WinComponents {
o.optString("snapshot"),
)
}
if (listed.any { it.name == VCREDIST_ARM64 }) listed else listed + builtInArm64Runtime()
} catch (e: Exception) {
Log.w(TAG, "catalog: $e"); null
}
@@ -0,0 +1,13 @@
package com.droiddeck.launcher.session
internal object WineProcesses {
private const val WINESERVER = "wineserver"
fun isWineserver(cmdline: ByteArray?, comm: String?): Boolean {
val program = cmdline?.let { bytes ->
val end = bytes.indexOf(0.toByte()).let { if (it < 0) bytes.size else it }
String(bytes, 0, end, Charsets.UTF_8).substringAfterLast('/')
}
return program == WINESERVER || comm?.trim() == WINESERVER
}
}