mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 21:06:09 +00:00
cleanup (#764)
This commit is contained in:
1 parent
5fd47421f9
commit
aecd2ebe1d
852 files changed
+4844
-46144
No files matched your search
@@ -8,30 +8,11 @@ import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* The battery the Steam client can see.
|
||||
*
|
||||
* The client reads `/sys/class/power_supply/BAT<n>/...` - a laptop's or a Deck's naming and files
|
||||
* (`energy_now`, `power_now`, `time_to_empty_now`, a `uevent` of `POWER_SUPPLY_*` lines). Android
|
||||
* names its supply `battery` and lays it out differently, and on many phones an app may not read
|
||||
* it at all, so the client showed no battery. This writes one `BAT1` (the Deck's name)
|
||||
* from Android's own battery API - the same on every device - into a directory the session binds
|
||||
* over `/sys/class/power_supply`, refreshed every few seconds while the session runs.
|
||||
*
|
||||
* Steam's Quick Access Menu takes its time estimates from neither: it reads the files in `/run/vpower` (as on
|
||||
* SteamOS), and with those absent showed "?h ?m" for projected battery life and for time to full.
|
||||
* The same estimates are written there too, into [vpowerDir] in the guest's own `/run`.
|
||||
*
|
||||
* Values: charge in µAh from the charge counter; energy in µWh from charge × voltage; power in µW
|
||||
* from |current| × voltage; time to empty from charge ÷ |average current| while discharging. Where
|
||||
* a device reports no current, the client still gets status and percentage.
|
||||
*/
|
||||
class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
|
||||
override fun start() {
|
||||
// Older builds exported the same aggregate battery twice; MangoHud counts both supplies.
|
||||
File(dir, "BAT0").deleteRecursively()
|
||||
running = true
|
||||
write()
|
||||
@@ -48,7 +29,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
// Stale estimates would outlive the session in the rootfs; Steam falls back to "?h ?m".
|
||||
for (name in VPOWER_FILES) File(vpowerDir, name).delete()
|
||||
}
|
||||
|
||||
@@ -67,7 +47,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
val chargeNowUah = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER)?.takeIf { it > 0 && it != Long.MIN_VALUE } ?: 0L
|
||||
val currentNowUa = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)?.takeIf { it != Long.MIN_VALUE } ?: 0L
|
||||
val currentAvgUa = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE)?.takeIf { it != Long.MIN_VALUE && it != 0L } ?: currentNowUa
|
||||
// Android's sign convention varies by vendor; the status says which way the current flows.
|
||||
val discharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING
|
||||
val chargeFullUah = if (chargeNowUah > 0 && pct > 0) chargeNowUah * 100 / pct else 0L
|
||||
val energyNowUwh = chargeNowUah * voltageUv / 1_000_000L
|
||||
@@ -129,7 +108,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
"ac_status" to if (plugged) "Connected" else "Disconnected",
|
||||
"battery_percent" to "%.2f".format(java.util.Locale.ROOT, pct.toDouble()),
|
||||
"battery_status" to statusText,
|
||||
// Steam reads a separate file for each direction; -1 = no estimate.
|
||||
"secs_until_battery_full" to (if (timeToFullS > 0) timeToFullS else -1L).toString(),
|
||||
"secs_until_shutdown_request" to (if (timeToEmptyS > 0) timeToEmptyS else -1L).toString(),
|
||||
)
|
||||
@@ -139,7 +117,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomic per file: a reader in the guest never sees a half-written value. */
|
||||
private fun put(target: File, text: String) {
|
||||
val tmp = File(target.parentFile, "." + target.name + ".tmp")
|
||||
tmp.writeText(text)
|
||||
|
||||
@@ -22,30 +22,9 @@ import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
|
||||
/**
|
||||
* FEX, DXVK and VKD3D-Proton per Proton, for the Linux Steam client.
|
||||
*
|
||||
* Every Proton the client runs games with keeps its own copy of these three inside its tree. This
|
||||
* lists them, stores packages (.wcp: tar + zstd with a profile.json) downloaded from the Nightlies
|
||||
* "-Linux" releases or imported, swaps one into a Proton, keeps the Proton's shipped files as
|
||||
* "original bundles" - one per Proton build, so a Steam update adds a new one instead of replacing
|
||||
* the last - restores those, and deletes stored packages.
|
||||
*
|
||||
* Where a Proton reads each component (its own `proton` script, ARM64 host):
|
||||
* DXVK files/lib/wine/dxvk/{aarch64,i386}-windows -> the prefix's system32 / syswow64
|
||||
* VKD3D files/lib/wine/vkd3d-proton/{aarch64,i386}-windows -> the same, on every launch
|
||||
* FEX files/lib/wine/aarch64-windows/lib{arm64ec,wow64}fex.dll
|
||||
* files/lib/wine/aarch64-unix/lib{arm64ec,wow64}fex.so (FEX 2607 and newer)
|
||||
* Proton copies DXVK and VKD3D into the prefix on every normal launch, so a swap applies the next
|
||||
* time a game starts. A swap into a Proton a running game is using waits until that game exits.
|
||||
*
|
||||
* Same formats and data layout as the Decky "Components Manager" plugin, whose data is taken over
|
||||
* once on first use.
|
||||
*/
|
||||
object ComponentsManager {
|
||||
private const val TAG = "Components"
|
||||
private const val NIGHTLIES = "The412Banner/Nightlies"
|
||||
/** Release tag -> component. Only the Linux repacks: the Android releases carry bionic unixlibs. */
|
||||
private val RELEASES = linkedMapOf(
|
||||
"FexCore-Linux" to "fex",
|
||||
"Dxvk-Linux" to "dxvk",
|
||||
@@ -66,13 +45,7 @@ object ComponentsManager {
|
||||
"$WINE/aarch64-unix/libwow64fex.so",
|
||||
)
|
||||
private val COMP_DIR = mapOf("dxvk" to "$WINE/dxvk", "vkd3d" to "$WINE/vkd3d-proton")
|
||||
/** The folders a Proton reads on ARM64. */
|
||||
private val PE_ARCHES = listOf("aarch64-windows", "i386-windows")
|
||||
/**
|
||||
* The DLLs that ARE the component. A swap clears exactly these before unpacking, so no file of
|
||||
* the previous version is left mixed in; anything else a Proton keeps beside them - GE's
|
||||
* openvr_api_dxvk.dll, which its launcher copies into every prefix and aborts without - stays.
|
||||
*/
|
||||
private val COMP_DLLS = mapOf(
|
||||
"dxvk" to setOf("d3d8.dll", "d3d9.dll", "d3d10.dll", "d3d10_1.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll"),
|
||||
"vkd3d" to setOf("d3d12.dll", "d3d12core.dll"),
|
||||
@@ -93,7 +66,6 @@ object ComponentsManager {
|
||||
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
|
||||
data class ProtonView(
|
||||
val proton: Proton, val components: Map<String, Component>, val originals: List<Original>, val inUseByGame: Boolean,
|
||||
/** When a launch last had to put this Proton's chosen files back (epoch seconds), or 0. */
|
||||
val reappliedAt: Long = 0,
|
||||
val sync: EsyncPacks.ToolState? = null,
|
||||
)
|
||||
@@ -102,7 +74,6 @@ object ComponentsManager {
|
||||
|
||||
private val lock = Any()
|
||||
|
||||
// ------------------------------------------------------------------ paths
|
||||
|
||||
private fun root(context: Context) = LinuxRuntime.rootDir(context)
|
||||
private fun steam(context: Context) = File(root(context), "root/.local/share/Steam")
|
||||
@@ -112,10 +83,6 @@ object ComponentsManager {
|
||||
private fun originalsDir(context: Context) = File(dataDir(context), "originals").apply { mkdirs() }
|
||||
private fun stateFile(context: Context) = File(dataDir(context), "state.json")
|
||||
private fun catalogFile(context: Context) = File(dataDir(context), "catalog.json")
|
||||
/**
|
||||
* Inside the Linux runtime, read by the Proton launch wrappers (steam-compatibility's
|
||||
* bl_components) before every game launch: desired.tsv + an unpacked copy of each package in use.
|
||||
*/
|
||||
private const val LAUNCH_DIR = "root/.local/share/droiddeck-components"
|
||||
private const val LEGACY_LAUNCH_DIR = "root/.local/share/bannerlator-components"
|
||||
private fun launchDir(context: Context): File {
|
||||
@@ -135,7 +102,6 @@ object ComponentsManager {
|
||||
|
||||
fun safeName(s: String): String = s.replace(Regex("[^A-Za-z0-9._+-]+"), "_").trim('_').ifEmpty { "unnamed" }
|
||||
|
||||
// ------------------------------------------------------------------ state
|
||||
|
||||
private fun pendingStateFile(context: Context) = File(dataDir(context), "state.pending.json")
|
||||
|
||||
@@ -173,7 +139,6 @@ object ComponentsManager {
|
||||
val expected = transaction.getString("launchSha256")
|
||||
val published = File(launchDir(context), "desired.tsv")
|
||||
val staged = File(launchDir(context), "desired.tsv.tmp")
|
||||
// The launch-table rename is the commit point. Never read stale app selections after it.
|
||||
if (!staged.exists() && published.isFile && Hashes.sha256(published) == expected) {
|
||||
writeStateFile(stateFile(context), state.toString(2))
|
||||
Log.i(TAG, "recovered published component selections")
|
||||
@@ -206,7 +171,6 @@ object ComponentsManager {
|
||||
|
||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||
|
||||
// Keep launch-time restore rows after the last per-game selection is removed.
|
||||
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
|
||||
val profiled = state.optJSONArray("profiledComponents")?.let { values ->
|
||||
(0 until values.length()).mapNotNull { values.optString(it).takeIf(COMPONENTS::contains) }
|
||||
@@ -252,7 +216,6 @@ object ComponentsManager {
|
||||
saveState(context, state)
|
||||
}
|
||||
|
||||
/** Takes over the Decky plugin's packages, originals and swap records, once. */
|
||||
private fun migratePlugin(context: Context) {
|
||||
val marker = File(dataDir(context), ".plugin-imported")
|
||||
if (marker.isFile) return
|
||||
@@ -275,7 +238,6 @@ object ComponentsManager {
|
||||
marker.writeText("1\n")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Protons
|
||||
|
||||
private fun libraryRoots(context: Context): List<File> {
|
||||
val roots = mutableListOf(steam(context))
|
||||
@@ -298,13 +260,10 @@ object ComponentsManager {
|
||||
if (parts.size > 1) parts[1] else parts.firstOrNull()?.ifEmpty { null } ?: "unknown"
|
||||
}.getOrDefault("unknown")
|
||||
|
||||
/** Every Proton tree with a Wine inside. Launch wrappers pointing at another Proton are left out. */
|
||||
fun protons(context: Context): List<Proton> {
|
||||
val found = LinkedHashMap<String, Proton>()
|
||||
val bases = listOf(File(steam(context), "compatibilitytools.d") to false) +
|
||||
libraryRoots(context).map { File(it, "steamapps/common") to true }
|
||||
// Not canonical: /data/user/0 is a link to /data/data on many devices, and the guest path is
|
||||
// what is left after removing the rootfs prefix exactly as the paths were built.
|
||||
val rootPath = root(context).absolutePath.trimEnd('/')
|
||||
for ((base, valve) in bases) {
|
||||
val entries = base.listFiles()?.sortedBy { it.name } ?: continue
|
||||
@@ -322,17 +281,9 @@ object ComponentsManager {
|
||||
private fun proton(context: Context, id: String) = protons(context).firstOrNull { it.id == id }
|
||||
?: throw IllegalStateException("No Proton with id $id")
|
||||
|
||||
/**
|
||||
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
|
||||
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
|
||||
*/
|
||||
fun inUse(context: Context, proton: Proton): Boolean =
|
||||
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = false) }
|
||||
|
||||
/**
|
||||
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
|
||||
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
|
||||
*/
|
||||
fun gameRunning(context: Context, proton: Proton): Boolean =
|
||||
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = true) }
|
||||
|
||||
@@ -357,14 +308,12 @@ object ComponentsManager {
|
||||
return false
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ component files
|
||||
|
||||
private fun readVersionFile(f: File): String = runCatching {
|
||||
val text = f.readText().trim()
|
||||
Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last()
|
||||
}.getOrDefault("")
|
||||
|
||||
/** The FEX build's version name; [unnamed] when its DLL carries none, "" when there is no FEX. */
|
||||
private fun fexVersion(dir: File, unnamed: String = "FEX (build without a version name)"): String {
|
||||
val dll = File(dir, FEX_FILES[0])
|
||||
if (!dll.isFile) return ""
|
||||
@@ -384,7 +333,6 @@ object ComponentsManager {
|
||||
private fun fingerprint(dir: File, comp: String): Map<String, String> =
|
||||
compFiles(dir, comp).filter { owned(comp, it) }.associateWith { Hashes.sha256(File(dir, it)) }
|
||||
|
||||
// ------------------------------------------------------------------ packages
|
||||
|
||||
private fun normalize(name: String) = name.removePrefix("./").trimStart('/')
|
||||
|
||||
@@ -406,14 +354,12 @@ object ComponentsManager {
|
||||
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
|
||||
}
|
||||
|
||||
/** The stored packages, newest version first. */
|
||||
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
|
||||
?.filter { it.isFile && it.name.endsWith(".wcp") }
|
||||
?.mapNotNull { f -> runCatching { packageInfo(context, f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
|
||||
?.sortedWith(newestFirst { it.version.ifEmpty { it.file } })
|
||||
?: emptyList()
|
||||
|
||||
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
|
||||
private fun installFiles(context: Context, dir: File, comp: String, wcp: File): Map<String, String> {
|
||||
val staged = File(dataDir(context), "staging-${System.nanoTime()}")
|
||||
try {
|
||||
@@ -472,7 +418,6 @@ object ComponentsManager {
|
||||
check(tmp.renameTo(dest)) { "Could not save original bundle ${dest.name}" }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ originals
|
||||
|
||||
private fun originalFile(context: Context, p: Proton, comp: String) =
|
||||
File(originalsDir(context), "${p.id}/${safeName(p.version)}/$comp.wcp").apply { parentFile?.mkdirs() }
|
||||
@@ -488,10 +433,6 @@ object ComponentsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a Proton's shipped files for this component before they are first replaced in this
|
||||
* Proton build. A build already swapped into is not saved again: its files are ours.
|
||||
*/
|
||||
private fun ensureOriginal(context: Context, p: Proton, comp: String, state: JSONObject) {
|
||||
val dest = originalFile(context, p, comp)
|
||||
if (dest.isFile) return
|
||||
@@ -520,7 +461,6 @@ object ComponentsManager {
|
||||
Log.i(TAG, "saved original $comp of ${p.name} ${p.version}")
|
||||
}
|
||||
|
||||
/** Saves the originals of every Proton build not seen yet (first open, and after a Steam update). */
|
||||
fun snapshotAll(context: Context) = synchronized(lock) {
|
||||
migratePlugin(context)
|
||||
val state = loadState(context)
|
||||
@@ -530,7 +470,6 @@ object ComponentsManager {
|
||||
runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ view
|
||||
|
||||
fun snapshot(context: Context): Snapshot = synchronized(lock) {
|
||||
migratePlugin(context)
|
||||
@@ -575,26 +514,15 @@ object ComponentsManager {
|
||||
Snapshot(views, packages(context))
|
||||
}
|
||||
|
||||
/**
|
||||
* The label of a chosen or queued original, in the app's language: the stored "label" was written
|
||||
* in English when it was chosen. Null for a package, whose label is its version.
|
||||
*/
|
||||
private fun originalLabel(context: Context, entry: JSONObject): String? = when {
|
||||
entry.optString("kind") == "original" -> context.getString(R.string.cmgr_original_version, entry.optString("protonVersion"))
|
||||
entry.optString("file").startsWith("original ") -> context.getString(R.string.cmgr_original_from, entry.optString("file").removePrefix("original "))
|
||||
else -> null
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ launch-time enforcement
|
||||
|
||||
private data class PreparedLaunchState(val text: String, val keep: Set<String>)
|
||||
|
||||
/**
|
||||
* Stages what each Proton should use for the launch wrappers. General rows use scope `*`;
|
||||
* per-game rows use the game's compatdata id and replace General for that component. Deletion
|
||||
* rows remove managed DLLs absent from the chosen package, so switching games cannot leave files
|
||||
* from the previous game's component set behind.
|
||||
*/
|
||||
private fun prepareLaunchState(context: Context, state: JSONObject): PreparedLaunchState {
|
||||
val dir = launchDir(context)
|
||||
val store = File(dir, "store").apply { mkdirs() }
|
||||
@@ -694,9 +622,7 @@ object ComponentsManager {
|
||||
return PreparedLaunchState(lines.toString(), keep)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ actions
|
||||
|
||||
/** Applies a package now, or queues it when a game is running on that Proton. Returns what happened. */
|
||||
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(packagesDir(context), safeName(file))
|
||||
@@ -749,7 +675,6 @@ object ComponentsManager {
|
||||
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
|
||||
}
|
||||
|
||||
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
|
||||
fun applyQueued(context: Context): List<String> = synchronized(lock) {
|
||||
val state = loadState(context)
|
||||
val queued = state.sub("queued")
|
||||
@@ -815,7 +740,6 @@ object ComponentsManager {
|
||||
context.getString(R.string.cmgr_deleted_original, protonVersion, LABEL[comp])
|
||||
}
|
||||
|
||||
/** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */
|
||||
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" })
|
||||
@@ -823,9 +747,7 @@ object ComponentsManager {
|
||||
info.copy(file = dest.name)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ catalog
|
||||
|
||||
/** The Nightlies listing: cached on disk, fetched again only when [force] (the refresh button). */
|
||||
fun catalog(context: Context, force: Boolean): Catalog {
|
||||
val cache = catalogFile(context)
|
||||
if (!force && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
|
||||
@@ -838,7 +760,6 @@ object ComponentsManager {
|
||||
val a = assets.getJSONObject(i)
|
||||
val name = a.optString("name")
|
||||
if (!name.endsWith(".wcp")) continue
|
||||
// Only packages GitHub has a sha256 for are offered: the download is checked against it.
|
||||
if (!Hashes.isGithubSha256(a.optString("digest"))) continue
|
||||
items.put(JSONObject().put("file", name).put("comp", comp).put("release", tag)
|
||||
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
|
||||
@@ -858,15 +779,9 @@ object ComponentsManager {
|
||||
return Catalog(items, o.optLong("fetchedAt"))
|
||||
}
|
||||
|
||||
/** By the version in [of], highest first: the newest builds lead a list, as they are what is picked. */
|
||||
private fun <T> newestFirst(of: (T) -> String): Comparator<T> =
|
||||
Comparator { a, b -> ProtonExtras.compareVersions(of(b), of(a)) }
|
||||
|
||||
/**
|
||||
* A package Proton does not ship, required on the GPUs listed here. An empty [models] set
|
||||
* means every model in [families]. A row the user already chose in Components is left alone;
|
||||
* a Steam update that puts the Proton's own files back is replaced on the next session.
|
||||
*/
|
||||
internal data class ForcedPackage(
|
||||
val families: Set<GpuInfo.Family>,
|
||||
val comp: String,
|
||||
@@ -878,28 +793,15 @@ object ComponentsManager {
|
||||
}
|
||||
|
||||
internal val FORCED_PACKAGES = listOf(
|
||||
// DXVK 3 refuses to start unless the device exposes storageBuffer8BitAccess. Turnip on
|
||||
// Adreno 6xx does not. 2.7.1 is the last DXVK 2 package on the Dxvk-Linux tag.
|
||||
ForcedPackage(setOf(GpuInfo.Family.A6XX), "dxvk", "dxvk-2.7.1-linux.wcp", "Dxvk-Linux"),
|
||||
)
|
||||
|
||||
/**
|
||||
* True when this Proton should receive the forced package. No active swap means the Proton's
|
||||
* own copy. A record for a different Proton build means a Steam update put that copy back,
|
||||
* whichever package was recorded. A record for this build is a Components choice and stays.
|
||||
*/
|
||||
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
|
||||
activeFile.isNullOrEmpty() || !protonVersionMatches
|
||||
|
||||
/** The catalog row for this file and release, or null. */
|
||||
internal fun catalogMatch(items: List<CatalogItem>, file: String, release: String): CatalogItem? =
|
||||
items.firstOrNull { it.file == file && it.release == release }
|
||||
|
||||
/**
|
||||
* Install every [FORCED_PACKAGES] row this GPU matches into each Proton that
|
||||
* [forcedPackageWanted] selects. Returns a line for the log, or null when this GPU or these
|
||||
* Protons need nothing. A failed fetch throws and the session logs it without stopping.
|
||||
*/
|
||||
fun ensureForcedPackages(context: Context): String? = ensureForcedPackages(
|
||||
context, GpuInfo.detect(),
|
||||
{ file, release -> catalogItem(context, file, release) },
|
||||
@@ -935,7 +837,6 @@ object ComponentsManager {
|
||||
return lines.joinToString("; ").ifEmpty { null }
|
||||
}
|
||||
|
||||
/** Null when [rule]'s package is stored and readable. Otherwise the log line, after a fetch. */
|
||||
private fun missingPackage(
|
||||
context: Context,
|
||||
rule: ForcedPackage,
|
||||
@@ -951,11 +852,9 @@ object ComponentsManager {
|
||||
return null
|
||||
}
|
||||
|
||||
/** The cached Nightlies row for this file, fetching the listing when the cache does not have it. */
|
||||
internal fun catalogItem(context: Context, file: String, release: String): CatalogItem? =
|
||||
resolveCatalogItem(file, release, { catalog(context, false).items }, { catalog(context, true).items })
|
||||
|
||||
/** [cached] when it has the row, otherwise [refresh]. [refresh] is not called on a hit. */
|
||||
internal fun resolveCatalogItem(
|
||||
file: String,
|
||||
release: String,
|
||||
@@ -963,7 +862,6 @@ object ComponentsManager {
|
||||
refresh: () -> List<CatalogItem>,
|
||||
): CatalogItem? = catalogMatch(cached(), file, release) ?: catalogMatch(refresh(), file, release)
|
||||
|
||||
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
|
||||
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
||||
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { context.getString(R.string.cmgr_nightlies_only) }
|
||||
require(Hashes.isGithubSha256(item.digest)) { context.getString(R.string.cmgr_list_predates_checksums) }
|
||||
|
||||
@@ -5,19 +5,6 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* A `/proc/stat` that moves.
|
||||
*
|
||||
* Android has refused apps `/proc/stat` since 8.0, and the session's stand-in for it was one
|
||||
* `cpu0` line of zeros - enough for glibc and Steam to start, but every CPU load in the session
|
||||
* read 0 % (the performance overlay showed one core, idle). The kernel still lets apps read each
|
||||
* core's idle residency (`cpuidle/stateN/time`, µs, the same label as the cpufreq files), which is
|
||||
* how overlays on Android work out CPU load: a core's busy time is the time that passed less the
|
||||
* time it spent idle. This writes `/proc/stat` from that, one line per core, refreshed twice a
|
||||
* second. Counters only grow - a sample's idle is never more than the time that passed - so a
|
||||
* reader taking the difference of two reads never sees a negative. Where `/proc/stat` is readable,
|
||||
* or the idle times are not, nothing is done.
|
||||
*/
|
||||
class CpuStatComponent(val file: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
@@ -28,7 +15,6 @@ class CpuStatComponent(val file: File) : SessionPart() {
|
||||
private var lastMs = 0L
|
||||
private val bootSeconds = (System.currentTimeMillis() - SystemClock.elapsedRealtime()) / 1000
|
||||
|
||||
/** Writes the first sample; true when it should be bound over `/proc/stat`. */
|
||||
fun prepare(): Boolean {
|
||||
if (File("/proc/stat").canRead() || cores.isEmpty() || idleUs(0) == null) return false
|
||||
lastMs = SystemClock.elapsedRealtime()
|
||||
@@ -62,7 +48,6 @@ class CpuStatComponent(val file: File) : SessionPart() {
|
||||
if (elapsed <= 0) return
|
||||
lastMs += elapsed * MS_PER_TICK
|
||||
for (i in cores) {
|
||||
// An offline core has no idle residency to count and runs nothing: all idle.
|
||||
val us = idleUs(i)
|
||||
val idleTicks = if (us == null) elapsed else ((us - lastIdleUs[i]) / US_PER_TICK).coerceIn(0, elapsed)
|
||||
if (us != null) lastIdleUs[i] = us
|
||||
@@ -71,7 +56,6 @@ class CpuStatComponent(val file: File) : SessionPart() {
|
||||
}
|
||||
}
|
||||
|
||||
/** The whole file at once, renamed into place: a reader opens either the last sample or this one. */
|
||||
private fun write() {
|
||||
val text = StringBuilder()
|
||||
text.append("cpu ${busy.sum()} 0 0 ${idle.sum()} 0 0 0 0 0 0\n")
|
||||
@@ -88,14 +72,12 @@ class CpuStatComponent(val file: File) : SessionPart() {
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val PERIOD_MS = 500L
|
||||
/** /proc/stat counts in USER_HZ, 100 a second on every Linux the guest runs. */
|
||||
private const val MS_PER_TICK = 10L
|
||||
private const val US_PER_TICK = 10_000L
|
||||
|
||||
private fun coreCount(): Int =
|
||||
File("/sys/devices/system/cpu").list()?.count { it.matches(Regex("cpu\\d+")) } ?: 0
|
||||
|
||||
/** The core's total idle residency in µs, or null when it has none to read (offline). */
|
||||
private fun idleUs(core: Int): Long? {
|
||||
val states = File("/sys/devices/system/cpu/cpu$core/cpuidle").listFiles { f -> f.name.startsWith("state") }
|
||||
?: return null
|
||||
|
||||
@@ -6,16 +6,6 @@ import java.io.File
|
||||
import java.io.PrintWriter
|
||||
import java.io.StringWriter
|
||||
|
||||
/**
|
||||
* The last thing that runs when our own code throws on any thread: the stack trace into the
|
||||
* session's folder, then the folder's ending ([SessionArtifacts.collect]), then Android's own
|
||||
* handler so the crash is still reported and still lands in the crash buffer. Bounded, because
|
||||
* a handler that hangs turns a crash into a frozen app: the collect gets a few seconds and the
|
||||
* process dies regardless.
|
||||
*
|
||||
* A native crash (the compositor, a JNI call) never reaches here - the process is gone before
|
||||
* Java sees anything. [SessionArtifacts.finishAbandoned] at the next start covers that case.
|
||||
*/
|
||||
object CrashHandler {
|
||||
private const val TAG = "CrashHandler"
|
||||
|
||||
@@ -40,10 +30,8 @@ object CrashHandler {
|
||||
worker.start()
|
||||
worker.join(8000)
|
||||
}
|
||||
// The session's tree would outlive us otherwise, and block the next launch.
|
||||
OrphanReaper.reap("app crash")
|
||||
} catch (e: Throwable) {
|
||||
// Nothing more to do for a crash inside the crash handler.
|
||||
} finally {
|
||||
previous?.uncaughtException(thread, error) ?: Runtime.getRuntime().halt(2)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import java.io.File
|
||||
object GameEnvironmentStore {
|
||||
private const val SETTINGS = "game-environment.json"
|
||||
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
|
||||
/** The published file's extra DXVK options (droiddeck-game-env reads it; the app's own file has none). */
|
||||
const val DXVK_CONFIG = "dxvkConfig"
|
||||
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
|
||||
|
||||
@@ -76,8 +75,6 @@ object GameEnvironmentStore {
|
||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
val json = encode(resolved)
|
||||
// The Display page's texture filtering, as DXVK options the launcher appends to
|
||||
// DXVK_CONFIG after the profiles - a user's own DXVK_CONFIG entry keeps its options.
|
||||
val dxvk = TextureFiltering.dxvkOptions(
|
||||
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
|
||||
TextureFiltering.autoLodBias(SessionState.upscaleRatio),
|
||||
|
||||
@@ -6,7 +6,6 @@ internal class GameProfileInventoryCache<T : Any> {
|
||||
private var revision: Long? = null
|
||||
private var value: List<T>? = null
|
||||
|
||||
// Called only by the refresh worker; the UI invalidates through request revisions.
|
||||
fun get(requestedRevision: Long, load: () -> List<T>): List<T> = synchronized(lock) {
|
||||
value?.takeIf { revision == requestedRevision } ?: load().toList().also {
|
||||
value = it
|
||||
|
||||
@@ -17,30 +17,18 @@ import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipInputStream
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
/**
|
||||
* Game saves in and out of a game's Proton prefix, as zips other apps read: GameHub keeps a prefix's
|
||||
* drive_c rooted at "/drive_c/users/steamuser/…", Winlator / WinNative / Bannerlator at
|
||||
* "drive_c/users/xuser/…". Proton here runs as steamuser too, so on the way in any user folder but
|
||||
* Public becomes steamuser, and on the way out the chosen layout decides the user segment.
|
||||
*
|
||||
* Saves belong to the game's prefix (compatdata/<appid>/pfx), whichever Proton it runs with.
|
||||
* Ported from Bannerlator's GameSaveBackup and SaveLocator.
|
||||
*/
|
||||
object GameSaves {
|
||||
enum class Layout(val app: String, val rootPrefix: String, val user: String) {
|
||||
GAMEHUB("GameHub", "/drive_c/", "steamuser"),
|
||||
WINLATOR("Winlator", "drive_c/", "xuser");
|
||||
|
||||
/** "GameHub zip", in the app's language. */
|
||||
fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app)
|
||||
}
|
||||
|
||||
/** A game, its prefix, and the save folders found in it. */
|
||||
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>) {
|
||||
val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true
|
||||
}
|
||||
|
||||
/** A folder of saves, relative to the steamuser profile. */
|
||||
data class SaveDir(val relPath: String, val files: Int, val bytes: Long)
|
||||
|
||||
private const val USER = "steamuser"
|
||||
@@ -48,21 +36,14 @@ object GameSaves {
|
||||
fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves")
|
||||
private fun backupsDir(): File = File(savesDir(), "backups")
|
||||
|
||||
/** [game] with its prefix and the saves found there; reads files, so not on the main thread. */
|
||||
fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList())
|
||||
|
||||
// ------------------------------------------------------------------ finding saves
|
||||
|
||||
/** Roots of the steamuser profile that hold most PC game saves, in the order they are trusted. */
|
||||
private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow")
|
||||
private const val KEEP_THRESHOLD = 50
|
||||
|
||||
private fun profile(prefix: File) = File(prefix, "drive_c/users/$USER")
|
||||
|
||||
/**
|
||||
* Folders under the save roots, one and two deep, whose names match the game's name or its folder's.
|
||||
* Nested matches keep the outer folder only.
|
||||
*/
|
||||
fun locate(prefix: File, game: Library.SteamGame): List<SaveDir> {
|
||||
val profile = profile(prefix)
|
||||
if (!profile.isDirectory) return emptyList()
|
||||
@@ -102,7 +83,6 @@ object GameSaves {
|
||||
return Ident(cleaned.filter { it.isLetterOrDigit() }, cleaned.split(Regex("[^a-z0-9]+")).filter { it.isNotEmpty() }.toSet())
|
||||
}
|
||||
|
||||
/** exact 100, one contains the other 70, half the words shared 50, close spelling 40. */
|
||||
private fun score(a: Ident, b: Ident): Int {
|
||||
if (a.norm.isEmpty() || b.norm.isEmpty()) return 0
|
||||
if (a.norm == b.norm) return 100
|
||||
@@ -123,15 +103,10 @@ object GameSaves {
|
||||
return prev[b.length]
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ export
|
||||
|
||||
private fun stamp() = SimpleDateFormat("yyyy-MM-dd_HHmm", Locale.US).format(Date())
|
||||
private fun safe(name: String) = name.replace(Regex("[/\\\\:*?\"<>|]"), "_").trim().ifEmpty { "game" }
|
||||
|
||||
/**
|
||||
* Zips the game's saves into [dir] as "<Game>_<date>.zip" in [layout]. The found save folders when
|
||||
* there are any, else the whole steamuser profile minus Temp and crash dumps. Returns the zip.
|
||||
*/
|
||||
fun export(context: Context, game: Game, layout: Layout, dir: File): Pair<File, Int> {
|
||||
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name))
|
||||
dir.mkdirs()
|
||||
@@ -160,13 +135,7 @@ object GameSaves {
|
||||
return count
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ import
|
||||
|
||||
/**
|
||||
* Unzips a GameHub or Winlator save zip into the game's drive_c, after zipping what its steamuser
|
||||
* profile holds now into Download/DroidDeck/Saves/backups. Entries outside drive_c, launcher
|
||||
* shortcuts and anything escaping drive_c are skipped. Returns (files written, backup or null).
|
||||
*/
|
||||
fun import(context: Context, game: Game, zip: File): Pair<Int, File?> {
|
||||
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name))
|
||||
val driveC = File(prefix, "drive_c")
|
||||
@@ -201,7 +170,6 @@ object GameSaves {
|
||||
return written to backup.takeIf { it.exists() }
|
||||
}
|
||||
|
||||
/** Which layout a zip was written in, from its first user folder; null when it has none. */
|
||||
fun layoutOf(zip: File): Layout? = runCatching {
|
||||
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
|
||||
var e = zis.nextEntry
|
||||
@@ -223,11 +191,9 @@ object GameSaves {
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** An entry's path below drive_c, with any user folder but Public renamed to steamuser. */
|
||||
private fun remap(raw: String): String? {
|
||||
val segs = driveCSegments(raw)?.takeIf { it.isNotEmpty() } ?: return null
|
||||
if (segs.any { it == ".." }) return null
|
||||
// GameHub also packs its own launcher shortcuts; they are never saves.
|
||||
if (segs[0].equals("proton_shortcuts", true)) return null
|
||||
val last = segs.last().lowercase()
|
||||
if ((last.endsWith(".lnk") || last.endsWith(".desktop") || last.endsWith(".url")) && segs.any { it.equals("Desktop", true) }) return null
|
||||
|
||||
@@ -9,20 +9,9 @@ import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Where a second Steam library can live on this device.
|
||||
*
|
||||
* An SD card is offered through the app's own folder on it ({@code Android/data/<pkg>/files/steam}):
|
||||
* the one place on a card a targetSdk-28 app may write without a permission prompt, and a real
|
||||
* filesystem path the session can bind. Any other folder comes from the File Manager's pick mode
|
||||
* and is checked for writing before it is accepted. Both are FUSE-backed on Android and stream
|
||||
* slowly (intro movies, big asset loads); internal stays the default and the dialog says so.
|
||||
*/
|
||||
object GameStorage {
|
||||
/** A library root: [label] as the menu lists it (a volume with its free space), [name] alone. */
|
||||
class Option(val label: String, val path: String, val name: String = label)
|
||||
|
||||
/** Every removable volume, as its app folder, with the free space it has. */
|
||||
fun options(context: Context): List<Option> {
|
||||
val sm = context.getSystemService(StorageManager::class.java)
|
||||
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
|
||||
@@ -40,10 +29,6 @@ object GameStorage {
|
||||
"?"
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes [path] a library root the session can bind - the folder and its steamapps/ - and proves
|
||||
* it writable. Returns why it cannot be used, or null when it can.
|
||||
*/
|
||||
fun prepare(context: Context, path: String): String? {
|
||||
val root = File(path)
|
||||
val steamapps = File(root, "steamapps")
|
||||
@@ -56,7 +41,6 @@ object GameStorage {
|
||||
}
|
||||
}
|
||||
|
||||
/** The root the session binds, from the setting: automatic = the first card in the phone. */
|
||||
fun effective(context: Context): Option? {
|
||||
val pref = SessionPrefs.gameStorage(context)
|
||||
return when {
|
||||
@@ -68,12 +52,6 @@ object GameStorage {
|
||||
|
||||
class Library(val host: File, val guest: String, val label: String)
|
||||
|
||||
/**
|
||||
* Games folders an earlier build registered as Steam libraries that Steam has installed games
|
||||
* into (an appmanifest in their steamapps/): those stay libraries, so the games are not lost.
|
||||
* Any other Games folder is no longer one; the session's library list leaves it out and the
|
||||
* runtime's droiddeck-steam-library forgets it.
|
||||
*/
|
||||
fun gamesFolderLibraries(context: Context): List<Library> {
|
||||
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
|
||||
val card = effective(context)?.let { canonical(File(it.path)) }
|
||||
@@ -90,13 +68,11 @@ object GameStorage {
|
||||
}
|
||||
}
|
||||
|
||||
/** Steam has installed a game into [root] as a library: a manifest in its steamapps/. */
|
||||
internal fun hasInstalledGames(root: File): Boolean =
|
||||
File(root, "steamapps").listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }?.isNotEmpty() == true
|
||||
|
||||
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||
|
||||
/** The label the client shows for a chosen folder: its last name, or the volume's. */
|
||||
fun labelFor(context: Context, path: String): String =
|
||||
options(context).firstOrNull { it.path == path }?.name
|
||||
?: File(path).name.ifEmpty { context.getString(R.string.gstore_folder) }
|
||||
|
||||
@@ -5,18 +5,6 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The GPU held at its top clock for a session, without root: KGSL's power-control property turned
|
||||
* off on /dev/kgsl-3d0, the node the driver already opens (adrenotools' "turbo"). Left to itself the
|
||||
* governor lets the GPU sit low between bursts, and a frame that lands on a low clock is a hitch;
|
||||
* Bannerlator measured the clock going from 231 to 1000 MHz with this set. It costs power and heat,
|
||||
* so it is opt-in, and the kernel's thermal limits still apply on top of it.
|
||||
*
|
||||
* The property belongs to the device, not to this process, and a killed app cannot unwind it: it
|
||||
* is cleared when a session stops, and at the next app start when a marker file says this app set
|
||||
* it and never cleared it - only then, so another app's own setting is not undone.
|
||||
* (Bannerlator, PerfGpuTurbo.)
|
||||
*/
|
||||
object GpuClockPin {
|
||||
private const val TAG = "GpuClockPin"
|
||||
private const val KGSL_NODE = "/dev/kgsl-3d0"
|
||||
@@ -28,7 +16,6 @@ object GpuClockPin {
|
||||
|
||||
private val supported: Boolean by lazy { File(KGSL_NODE).exists() }
|
||||
|
||||
/** At a session's start: pins the clock when the user asked for it. The line is for the log. */
|
||||
@Synchronized
|
||||
fun start(context: Context): String {
|
||||
if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed"
|
||||
@@ -44,13 +31,11 @@ object GpuClockPin {
|
||||
}
|
||||
}
|
||||
|
||||
/** At a session's end. */
|
||||
@Synchronized
|
||||
fun stop(context: Context) {
|
||||
if (pinned) clear(context)
|
||||
}
|
||||
|
||||
/** At the app's start: a process killed with the clock pinned left only the marker behind. */
|
||||
@Synchronized
|
||||
fun clearLeftover(context: Context) {
|
||||
if (File(context.filesDir, MARKER).exists()) clear(context)
|
||||
|
||||
@@ -4,32 +4,11 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The GPU memory in use, for the performance overlay's VRAM and PVRAM lines.
|
||||
*
|
||||
* Valve's mangoapp reads it from the kernel's gpu_mem_total tracepoint, which no Android app may
|
||||
* reach, so both lines read 0. Our libtracefs for mangoapp (tools/mangoapp/libtracefs-shim.c) hands
|
||||
* it what this writes to [file] - `/run/droiddeck-hud/gpu-mem` in the guest - every few seconds, in
|
||||
* bytes, from the best of what KGSL lets the app read:
|
||||
*
|
||||
* - `/sys/class/kgsl/kgsl/page_alloc`, every GPU page on the device - what the tracepoint's total
|
||||
* counts, where the policy allows it;
|
||||
* - else KGSL's own accounting of each of the session's processes
|
||||
* (`/sys/class/kgsl/kgsl/proc/<pid>/gpumem_mapped` and `gpumem_unmapped`);
|
||||
* - else the size of the KGSL mappings in each of the session's processes' `maps` - only the
|
||||
* buffers the CPU has mapped, so less than the GPU holds (about 40 % of KGSL's own count in a
|
||||
* game on an AYN Thor), but always readable: every process the app can see in `/proc` is one of
|
||||
* its own. `maps` rather than `smaps`, which gives the same sizes but walks page tables to do it:
|
||||
* in a game, 180,000 lines and most of a second of CPU a pass.
|
||||
*
|
||||
* Sampled only while the overlay shows (OverlayShown).
|
||||
*/
|
||||
class GpuMemComponent(private val file: File, private val root: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
private var source = ""
|
||||
|
||||
/** True when there is a source to write from. */
|
||||
fun prepare(): Boolean {
|
||||
val bytes = sample() ?: return false
|
||||
write(bytes)
|
||||
@@ -76,11 +55,9 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP
|
||||
return null
|
||||
}
|
||||
|
||||
/** The processes this app may see in /proc: Android hides every other uid's. */
|
||||
private fun sessionPids(): List<String> =
|
||||
File("/proc").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) }.orEmpty()
|
||||
|
||||
/** Size of a process's mappings of the KGSL device, in kB; null where its maps cannot be read. */
|
||||
private fun kgslMappedKb(pid: String): Long? = runCatching {
|
||||
var bytes = 0L
|
||||
File("/proc/$pid/maps").forEachLine { line ->
|
||||
@@ -95,7 +72,6 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP
|
||||
bytes / 1024
|
||||
}.getOrNull()
|
||||
|
||||
/** Whole, renamed into place: the reader opens either the last value or this one. */
|
||||
private fun write(bytes: Long) {
|
||||
try {
|
||||
file.parentFile?.mkdirs()
|
||||
@@ -109,7 +85,6 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val KGSL_ROOT = "/sys/class/kgsl/kgsl"
|
||||
/** GPU memory moves slowly; a pass over every process's maps is ~40 ms of CPU in a game. */
|
||||
private const val PERIOD_MS = 5_000L
|
||||
|
||||
private fun readLong(path: String): Long? =
|
||||
|
||||
@@ -6,34 +6,15 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
/**
|
||||
* The Adreno's stats as mangoapp (Deck mode's performance overlay) reads them.
|
||||
*
|
||||
* MangoHud takes an Adreno's load, clock and temperature from `gpu_busy_percentage`, `clock_mhz`
|
||||
* and `temp` in `/sys/class/kgsl/kgsl-3d0`, and ends the process on one of them it may not read -
|
||||
* not on one that is missing, which it skips. An enforcing SELinux policy (every retail phone)
|
||||
* refuses apps some or all of KGSL's sysfs, each vendor differently, so mangoapp died on start and
|
||||
* the session ran with no overlay. Where any of the three is refused, a directory of our own is
|
||||
* bound there instead. A value with no
|
||||
* readable source is left out, and the overlay shows no line for it. Where all three are
|
||||
* readable, nothing is done.
|
||||
*
|
||||
* Valve's build also reads load and clock where a mainline msm kernel has them (debugfs
|
||||
* `perf_now`, the GPU's devfreq `cur_freq` in Hz) - the paths LinuxRuntime.bindAdrenoStats points
|
||||
* at KGSL's own files when it may - so the same values are fed there too, in the same formats
|
||||
* ([binds]).
|
||||
*/
|
||||
class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
private val feeds = ArrayList<Feed>()
|
||||
|
||||
/** One of MangoHud's files and where its value comes from. */
|
||||
private class Feed(
|
||||
val file: File, val source: String, val read: () -> Long?, val format: String, val percent: Boolean = false,
|
||||
)
|
||||
|
||||
/** Where Valve's msm reader looks, and the feed for it, as host:guest binds. */
|
||||
fun binds(): List<String> {
|
||||
val list = mutableListOf(dir.path + ":" + KGSL)
|
||||
if (File(dir, "perf_now").exists()) list.add(File(dir, "perf_now").path + ":" + MSM_LOAD)
|
||||
@@ -41,7 +22,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
return list
|
||||
}
|
||||
|
||||
/** Writes the directory; true when it should be bound over [KGSL]. */
|
||||
fun prepare(): Boolean {
|
||||
if (!File(KGSL).exists() || MANGOHUD_FILES.none { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }) return false
|
||||
return try {
|
||||
@@ -50,8 +30,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
feeds.clear()
|
||||
loadFeed()?.let { load ->
|
||||
feeds.add(load)
|
||||
// KGSL's gpu_busy_percentage reads "37 %"; padded after, so a shorter value
|
||||
// written over a longer one leaves no digits behind.
|
||||
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
|
||||
}
|
||||
pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { clock ->
|
||||
@@ -88,7 +66,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
thread = null
|
||||
}
|
||||
|
||||
/** Load: a file that states it in percent, else KGSL's busy and total of the last sample. */
|
||||
private fun loadFeed(): Feed? {
|
||||
pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }?.let { return it }
|
||||
val gpubusy = "$KGSL/gpubusy"
|
||||
@@ -102,7 +79,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
return if (read() != null) Feed(File(dir, "gpu_busy_percentage"), gpubusy, read, "%3d %%\n") else null
|
||||
}
|
||||
|
||||
/** The first of [sources] that reads as a number, its value put in MangoHud's unit by [unit]. */
|
||||
private fun pick(name: String, sources: List<String>, format: String, unit: (Long) -> Long?): Feed? {
|
||||
for (source in sources) {
|
||||
val read = { firstNumber(source)?.let(unit) }
|
||||
@@ -111,7 +87,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
return null
|
||||
}
|
||||
|
||||
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
|
||||
private fun write(feed: Feed, value: Long) {
|
||||
try {
|
||||
val text = if (feed.percent) String.format(feed.format, "$value %") else String.format(feed.format, value)
|
||||
@@ -123,17 +98,14 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
const val KGSL = "/sys/class/kgsl/kgsl-3d0"
|
||||
/** Must match LinuxRuntime.bindAdrenoStats. */
|
||||
const val MSM_LOAD = "/sys/kernel/debug/dri/0/perf_now"
|
||||
const val MSM_CLOCK = "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"
|
||||
private const val PERIOD_MS = 500L
|
||||
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
|
||||
/** Qualcomm's own GPU summary, beside KGSL in vendor kernels, under the plain sysfs label. */
|
||||
private const val QCOM_GPU = "/sys/kernel/gpu"
|
||||
private val LOAD_SOURCES = listOf(
|
||||
"$KGSL/gpu_busy_percentage", "$KGSL/devfreq/gpu_load", "$KGSL/gpuload", "$QCOM_GPU/gpu_busy",
|
||||
)
|
||||
/** The GPU's devfreq node is named by its register address, which differs between Snapdragons. */
|
||||
private val DEVFREQ_NODES = listOf(
|
||||
"kgsl-3d0", "3d00000.qcom,kgsl-3d0", "2c00000.qcom,kgsl-3d0", "5000000.qcom,kgsl-3d0", "5900000.qcom,kgsl-3d0",
|
||||
)
|
||||
@@ -152,11 +124,9 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
private fun tempSources(): List<String> =
|
||||
listOfNotNull("$KGSL/temp", "$KGSL/devfreq/temp", "$QCOM_GPU/temp", LinuxRuntime.gpuTempSource()).distinct()
|
||||
|
||||
/** The first integer in the file ("550", "37 %", "550000000"), or null. */
|
||||
private fun firstNumber(path: String): Long? =
|
||||
runCatching { Regex("-?\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
|
||||
|
||||
/** Hz, kHz or MHz to MHz, as the files differ; a stopped clock reads 0. */
|
||||
private fun mhz(raw: Long): Long? = when {
|
||||
raw < 0 -> null
|
||||
raw > 10_000_000 -> raw / 1_000_000
|
||||
@@ -164,7 +134,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
else -> raw
|
||||
}
|
||||
|
||||
/** °C or m°C to MangoHud's m°C; nothing a GPU reads at is below 1 °C or above 1000. */
|
||||
private fun milliCelsius(raw: Long): Long? = when {
|
||||
raw <= 0 -> null
|
||||
raw < 1000 -> raw * 1000
|
||||
|
||||
@@ -8,25 +8,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
/**
|
||||
* The session's `/sys/class/hwmon`, as mangoapp (Deck mode's performance overlay) looks there.
|
||||
*
|
||||
* MangoHud finds a CPU's temperature by an hwmon sensor named `cpuN_thermal`, and an Adreno's
|
||||
* temperature, fan and power by one whose name has `gpuss` in it - a mainline Arm kernel's names.
|
||||
* An Android kernel has neither (its hwmon holds the PMIC's sensors, or nothing), and where the
|
||||
* app may not list hwmon at all the overlay logged an error twice a second. So the overlay showed
|
||||
* no CPU temperature and no fan. This is two sensors named so:
|
||||
*
|
||||
* - `hwmon0` (`cpu0_thermal`): `temp1_input` linked to a CPU thermal zone the app can read;
|
||||
* - `hwmon1` (`gpuss0_thermal`): `temp1_input` linked to the GPU's zone, and `fan1_input` with
|
||||
* the device's fan speed where it has a fan the app can read - an AYN handheld's tachometer
|
||||
* (`/sys/class/gpio5_pwm2/speed`), or a `fan*_input` in the device's own hwmon;
|
||||
* - `hwmon2` (`slg4ax46073v`): the same fan, for Valve's own Qualcomm reader (msm.cpp), which
|
||||
* looks for its fan controller by that name and halves what it reads - that part reports twice
|
||||
* the real speed - so this one holds twice it.
|
||||
*
|
||||
* Nothing in a phone's own hwmon is read by the overlay, so standing in for it loses nothing.
|
||||
*/
|
||||
class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
@@ -36,7 +17,6 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
private var lastRpm = 0L
|
||||
private var lastRpmAt = 0L
|
||||
|
||||
/** Writes the sensors; true when the directory should be bound over `/sys/class/hwmon`. */
|
||||
fun prepare(): Boolean = try {
|
||||
dir.mkdirs()
|
||||
clear(dir)
|
||||
@@ -65,7 +45,6 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(FAN_PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
// A tachometer read busy-waits 100 ms in the kernel: only while the overlay shows.
|
||||
if (running && OverlayShown.check(root)) writeFan(sampleFan())
|
||||
}
|
||||
}, "hwmon-fan").apply { isDaemon = true; start() }
|
||||
@@ -77,11 +56,6 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
thread = null
|
||||
}
|
||||
|
||||
/**
|
||||
* The fan's speed in RPM. An AYN tachometer counts pulses over a short window per read and
|
||||
* often catches none, reading 0 while the fan turns; a reading is held until a newer one
|
||||
* comes or [FAN_HOLD_MS] passes with only zeros, when the fan is taken to have stopped.
|
||||
*/
|
||||
private fun sampleFan(): Long {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val rpm = fanSource?.let { readNumber(it) } ?: 0L
|
||||
@@ -94,7 +68,6 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
return lastRpm
|
||||
}
|
||||
|
||||
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
|
||||
private fun writeFan(rpm: Long) {
|
||||
for ((file, value) in listOf(fanFile to rpm, valveFanFile to rpm * 2)) {
|
||||
try {
|
||||
@@ -112,7 +85,6 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
Os.symlink(target, link.path)
|
||||
}
|
||||
|
||||
/** Only files and links are made here; deleting a link must not follow it into sysfs. */
|
||||
private fun clear(root: File) {
|
||||
root.listFiles()?.forEach { f ->
|
||||
if (!java.nio.file.Files.isSymbolicLink(f.toPath()) && f.isDirectory) clear(f)
|
||||
@@ -122,7 +94,6 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
/** The AYN tachometer reads 0 if read again within a couple of seconds. */
|
||||
private const val FAN_PERIOD_MS = 3_000L
|
||||
private const val FAN_HOLD_MS = 10_000L
|
||||
|
||||
|
||||
@@ -10,45 +10,32 @@ import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
/**
|
||||
* The loading overlay's state: what to say, read out of the session log, and a clock so a user
|
||||
* can see that time is passing even when the log is quiet. The runtime script marks its
|
||||
* milestones with "== STEP"; the client's own bootstrap does not, but it does print its download
|
||||
* progress, and lifting that out is the difference between "starting the Steam client" for three
|
||||
* minutes and a percentage that moves.
|
||||
*/
|
||||
class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
var visible by mutableStateOf(true)
|
||||
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
|
||||
private set
|
||||
/** What [step] is about, so the screen picks its checklist stage without reading the (translated) words. */
|
||||
var topic by mutableStateOf(Topic.SESSION)
|
||||
private set
|
||||
/** [step] is a download or install line worth showing as it is, not one of the script's own notes. */
|
||||
var readable by mutableStateOf(false)
|
||||
private set
|
||||
var percent by mutableIntStateOf(-1)
|
||||
var elapsed by mutableStateOf("")
|
||||
var hint by mutableStateOf("")
|
||||
var ended by mutableStateOf(false)
|
||||
/** The technical side of an ended session (exit status, log path), under the advice in [step]. */
|
||||
var endedDetail by mutableStateOf<String?>(null)
|
||||
|
||||
// The desktop and the emulators get their own: the Steam ones talk about Steam.
|
||||
private val hints = context.resources.getStringArray(
|
||||
if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop,
|
||||
)
|
||||
private val res = context.resources
|
||||
private val startedAt = SystemClock.elapsedRealtime()
|
||||
|
||||
/** Once a second: the clock and the hint. */
|
||||
fun tick() {
|
||||
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
||||
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60)
|
||||
hint = hints[((seconds / 8) % hints.size).toInt()]
|
||||
}
|
||||
|
||||
/** A line the app itself writes (an install's progress, the session starting). */
|
||||
fun say(line: String, topic: Topic, readable: Boolean) {
|
||||
step = line
|
||||
this.topic = topic
|
||||
@@ -62,7 +49,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
endedDetail = detail
|
||||
}
|
||||
|
||||
/** Re-reads the end of the log and updates the line and the bar. */
|
||||
fun update(context: Context, log: File?) {
|
||||
val state = read(context, log) ?: return
|
||||
step = state.line
|
||||
@@ -73,7 +59,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
|
||||
private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean)
|
||||
|
||||
/** Only the tail is read: the client alone writes megabytes an hour. */
|
||||
private fun read(context: Context, log: File?): Line? {
|
||||
if (log == null || !log.isFile) return null
|
||||
val text = try {
|
||||
@@ -132,14 +117,9 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The checklist stages a loading line can move the screen to. */
|
||||
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* A session script "== STEP" line's topic in a Steam ([steam]) or desktop session; those
|
||||
* lines are English whatever the app's language.
|
||||
*/
|
||||
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
|
||||
val t = scriptStep.lowercase()
|
||||
return when {
|
||||
@@ -152,7 +132,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The script's install lines are worth reading as they are; its other notes are not. */
|
||||
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")
|
||||
|
||||
@@ -6,13 +6,6 @@ import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Once, on the first start of a build with private logs: the session folders, tools/ and the loose
|
||||
* tool logs that earlier builds left in `Download/DroidDeck/` move into `files/logs/`. Best effort:
|
||||
* an item that cannot be moved stays where it is. Moved session folders lose their old scrub markers
|
||||
* ([SessionArtifacts.unmarkMoved]), so [SessionArtifacts.scrubOlder] scrubs them under the current rules. Nothing else in that folder is touched - game
|
||||
* save backups (Saves/) stay public - and after this pass the app never reads it again.
|
||||
*/
|
||||
object LogMigration {
|
||||
private const val TAG = "LogMigration"
|
||||
private const val MARKER = ".moved-from-downloads"
|
||||
@@ -24,7 +17,6 @@ object LogMigration {
|
||||
if (marker.exists()) return
|
||||
val legacy = LinuxRuntime.legacyLogDir()
|
||||
val items = if (legacy.isDirectory) legacy.listFiles() else emptyArray()
|
||||
// Unreadable (no storage access yet): try again next start rather than give up on them.
|
||||
if (items == null) { Log.w(TAG, "$legacy cannot be listed; logs there stay until it can"); return }
|
||||
var moved = 0
|
||||
val movedFolders = ArrayList<File>()
|
||||
@@ -40,15 +32,11 @@ object LogMigration {
|
||||
if (SessionPaths.isSessionFolder(dest)) movedFolders.add(dest)
|
||||
} else Log.w(TAG, "could not move ${f.name}; left in place")
|
||||
}
|
||||
// Earlier builds scrubbed these under older rules (or not at all) and marked them done:
|
||||
// without their markers, the pass over older folders that follows at the same start puts
|
||||
// them through the current redactor.
|
||||
SessionArtifacts.unmarkMoved(movedFolders)
|
||||
try { marker.writeText("moved $moved item(s)\n") } catch (e: Exception) { Log.w(TAG, "could not mark the move: ${e.message}") }
|
||||
if (moved > 0) Log.i(TAG, "moved $moved log item(s) from $legacy into $target")
|
||||
}
|
||||
|
||||
/** A rename where it works (same volume), else a copy then the source's removal; false = left as it was. */
|
||||
private fun move(src: File, dest: File): Boolean {
|
||||
if (src.renameTo(dest)) return true
|
||||
return try {
|
||||
|
||||
@@ -5,19 +5,6 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Starting the Steam client signed out of Valve's servers.
|
||||
*
|
||||
* The client can run without a connection - installed games launch, Proton and the frame-gen are
|
||||
* all local - but only if it has credentials from an earlier successful sign-in. Two keys in
|
||||
* loginusers.vdf decide what it does when it cannot reach a CM: WantsOfflineMode makes it go
|
||||
* offline on its own, SkipOfflineModeWarning stops it asking first. Both are read once, while the
|
||||
* client starts, which is why this belongs to the main screen and not to the in-session drawer:
|
||||
* changing it during a session would write the file and change nothing until the next launch.
|
||||
*
|
||||
* The client rewrites this file when it exits, so the request is kept as our own preference and
|
||||
* written into the file again at every session start.
|
||||
*/
|
||||
object OfflineMode {
|
||||
private const val TAG = "OfflineMode"
|
||||
private const val KEY = "steam_offline"
|
||||
@@ -30,7 +17,6 @@ object OfflineMode {
|
||||
|
||||
private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf")
|
||||
|
||||
/** The account the client could sign in as offline: its name, "" when it recorded none, null when there is none. */
|
||||
fun account(context: Context): String? {
|
||||
val file = loginUsers(LinuxRuntime.rootDir(context))
|
||||
val text = try {
|
||||
@@ -49,12 +35,6 @@ object OfflineMode {
|
||||
apply(context, LinuxRuntime.rootDir(context))
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the request into loginusers.vdf. Every account block gets the same answer: the client
|
||||
* signs in as one of them and we have no say in which. Keys the file does not carry are added
|
||||
* beside the account's name; a file without an account block is left alone, since there is
|
||||
* nothing to be offline as.
|
||||
*/
|
||||
fun apply(context: Context, root: File) {
|
||||
val file = loginUsers(root)
|
||||
if (!file.isFile) return
|
||||
|
||||
@@ -3,26 +3,10 @@ package com.droiddeck.launcher.session
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Kills every process of this app's uid other than the app itself.
|
||||
*
|
||||
* A session is a tree of processes under proot, and proot dies with the app only when the app's
|
||||
* own teardown runs. When the app is killed or crashes instead, the tree stays: proot holding the
|
||||
* rootfs, gamescope holding the GPU, Steam holding its lock file - and the next session never
|
||||
* comes up, or comes up beside a client that is already running. A user on a Thor Pro had to
|
||||
* force-stop the app before every launch. Everything of ours that should be alive between
|
||||
* sessions is inside the app process, so at session start anything else under our uid is a
|
||||
* leftover, and this sweeps it. Each pid is checked by uid at kill time, never by name.
|
||||
*
|
||||
* The one exception is work the app started outside any session and is still waiting on - a
|
||||
* Flatpak install from the store - registered with [keep]: that process and everything under it
|
||||
* are left to finish.
|
||||
*/
|
||||
object OrphanReaper {
|
||||
private const val TAG = "OrphanReaper"
|
||||
private val kept = java.util.concurrent.ConcurrentHashMap.newKeySet<Int>()
|
||||
|
||||
/** Spares [pid] and its descendants until [release]. */
|
||||
fun keep(pid: Int) { if (pid > 0) kept.add(pid) }
|
||||
|
||||
fun release(pid: Int) { kept.remove(pid) }
|
||||
@@ -49,14 +33,12 @@ object OrphanReaper {
|
||||
return killed
|
||||
}
|
||||
|
||||
/** [roots] and every process below them, by each process's parent in /proc/<pid>/stat. */
|
||||
private fun descendants(roots: Set<Int>): Set<Int> {
|
||||
if (roots.isEmpty()) return emptySet()
|
||||
val parent = HashMap<Int, Int>()
|
||||
File("/proc").listFiles()?.forEach { entry ->
|
||||
val pid = entry.name.toIntOrNull() ?: return@forEach
|
||||
val stat = try { File(entry, "stat").readText() } catch (e: Exception) { return@forEach }
|
||||
// "pid (comm) state ppid ...": comm may hold spaces and parentheses; the last ')' ends it.
|
||||
stat.substringAfterLast(") ").split(' ').getOrNull(1)?.toIntOrNull()?.let { parent[pid] = it }
|
||||
}
|
||||
val out = HashSet(roots)
|
||||
|
||||
@@ -2,12 +2,6 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Whether Deck mode's performance overlay is on screen. The client sets its level by rewriting
|
||||
* mangoapp's config (droiddeck-session makes it, `/tmp/mangohud.*`), and `no_display` is the
|
||||
* level that hides it. The feeds whose reads cost something - the fan's tachometer busy-waits in
|
||||
* the kernel, GPU memory walks every process's mappings - only run while it shows.
|
||||
*/
|
||||
object OverlayShown {
|
||||
fun check(root: File): Boolean {
|
||||
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") }
|
||||
|
||||
@@ -16,17 +16,7 @@ import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* The numbers behind the top-right line: the game's own frame rate and, when frame generation
|
||||
* is on, what the screen is actually being shown - "60 → 118 fps" is the proof that the engine
|
||||
* is doing something, and "FG starting" or a reason is the proof that it is not.
|
||||
*
|
||||
* The base rate is the game window's own frames, counted here from the compositor's per-frame
|
||||
* callback with or without an engine - what Steam's overlay counts too. The presented rate comes
|
||||
* from the engine's telemetry while it generates.
|
||||
*/
|
||||
class PerfHud(context: Context) {
|
||||
/** Empty when the HUD is off or not yet started. */
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
|
||||
@@ -36,19 +26,15 @@ class PerfHud(context: Context) {
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
/** The session's own switch (drawer), with the Downloads file as a device-side override. */
|
||||
private val enabled: Boolean
|
||||
get() = SessionPrefs.hudEnabled(context)
|
||||
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
|
||||
|
||||
/** Told, on the main thread, when the window presenting frames changes. */
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
private var lastWindow: String? = null
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
override fun onGameSurface(window: String?, gpuName: String?) {
|
||||
// gamescope forwards a fullscreen game's own buffers straight through and its composited
|
||||
// output when the Steam menu is up; each is a different window here. Compositor thread.
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
@@ -68,7 +54,6 @@ class PerfHud(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-reads the switch: starts or stops to match it. */
|
||||
fun refresh() {
|
||||
if (enabled) start() else stop()
|
||||
}
|
||||
|
||||
@@ -8,33 +8,12 @@ import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* What a session tells Android about itself so the SoC is run for a game, not for an app.
|
||||
*
|
||||
* The manifest already makes the app a game (appCategory + game_mode_config); this is the
|
||||
* per-window half, applied when the session activity is created:
|
||||
*
|
||||
* - NOT sustained performance mode: on Pixel and Qualcomm power HALs it caps the CPU and GPU at
|
||||
* a level the device can hold indefinitely rather than holding a floor, which cost games and
|
||||
* Big Picture their peak clocks. WinNative never asks for it; the thermal budget is left to
|
||||
* the game;
|
||||
* - the panel's fastest mode at its current size (Android 6+), up to the user's peak refresh rate
|
||||
* ([peakRefreshCap]): a 120 Hz phone is switched to 120 Hz for the menu, not only when a game
|
||||
* votes for it. With a frame cap, the fastest mode
|
||||
* the cap divides evenly, so every capped frame is shown for the same number of refreshes;
|
||||
* - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases
|
||||
* its boost on loading screens or menus keeps it up.
|
||||
*
|
||||
* Every step is version-guarded and skipped silently below its API; the returned line is what
|
||||
* the session log shows, which is the first thing to read on a device that feels slow.
|
||||
*/
|
||||
object PerfMode {
|
||||
private const val TAG = "PerfMode"
|
||||
|
||||
fun apply(a: Activity, fpsLimit: Int = 0): String {
|
||||
val parts = ArrayList<String>(2)
|
||||
|
||||
// The fastest display mode at the panel's current size.
|
||||
parts += try {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay
|
||||
if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else {
|
||||
@@ -54,7 +33,6 @@ object PerfMode {
|
||||
}
|
||||
} catch (t: Throwable) { Log.w(TAG, "display mode", t); "display mode failed" }
|
||||
|
||||
// GameManager: what mode the OS put us in, and that we are playing.
|
||||
parts += if (Build.VERSION.SDK_INT >= 31) {
|
||||
val gm = a.getSystemService(GameManager::class.java)
|
||||
if (gm == null) "no GameManager" else {
|
||||
@@ -74,13 +52,6 @@ object PerfMode {
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest rate Android will run the panel at: the user's "peak refresh rate" (Smooth display,
|
||||
* or the AYN/Odin quick-settings tile). Above it a mode can be requested and is even reported back
|
||||
* as active, while SurfaceFlinger keeps composing at the cap. The Thor set to 60 Hz ran 120 Hz
|
||||
* sessions at 60: gamescope and Steam were told 120, every game topped out at 60, and the QAM's
|
||||
* Frame Limit read "60 FPS (120 Hz)" and changed nothing. Unset (most phones) is no cap.
|
||||
*/
|
||||
fun peakRefreshCap(context: Context): Float {
|
||||
val peak = try {
|
||||
Settings.System.getFloat(context.contentResolver, "peak_refresh_rate")
|
||||
@@ -88,7 +59,6 @@ object PerfMode {
|
||||
return if (peak >= 1f) peak else Float.POSITIVE_INFINITY
|
||||
}
|
||||
|
||||
/** A panel rate that shows every capped frame for a whole number of refreshes (no cap: any). */
|
||||
fun cadenceFits(hz: Float, fpsLimit: Int): Boolean {
|
||||
if (fpsLimit <= 0) return true
|
||||
val ratio = hz / fpsLimit
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** Platform-independent eligibility; a service existing alone does not mean it has a picture. */
|
||||
object PipPolicy {
|
||||
fun eligible(running: Boolean, frameSeen: Boolean, phase: SessionPhase, suspended: Boolean, automatic: Boolean): Boolean =
|
||||
running && frameSeen && phase in setOf(SessionPhase.READY, SessionPhase.SUSPENDED) &&
|
||||
|
||||
@@ -12,12 +12,10 @@ import java.io.File
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
||||
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"
|
||||
/** How long a release check stands before the next one goes to GitHub. */
|
||||
const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
@@ -25,7 +23,6 @@ object ProtonExtras {
|
||||
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||
|
||||
/** [sha256] from GitHub's asset digest; [sha512] the URL of a checksum file published beside it. */
|
||||
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||
val sha256: String? = null)
|
||||
|
||||
@@ -38,15 +35,11 @@ object ProtonExtras {
|
||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
private fun requests(context: Context) = File(home(context), ".bl-proton-extra")
|
||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||
/** The release tag each build was installed from, by directory name. */
|
||||
private fun releasesFile(context: Context) = File(context.filesDir, "proton-extras.json")
|
||||
/** The newest release seen per source, and when it was looked up. */
|
||||
private fun latestFile(context: Context) = File(context.filesDir, "proton-latest.json")
|
||||
|
||||
/** The installed build's directory name (e.g. GE-Proton11-7), the newest when there are several, or null. */
|
||||
fun installed(context: Context, tool: Tool): String? = installedIn(toolsDir(context), tool).lastOrNull()
|
||||
|
||||
/** Every installed build's directory name, oldest first. */
|
||||
fun installedAll(context: Context, tool: Tool): List<String> = installedIn(toolsDir(context), tool)
|
||||
|
||||
internal fun installedIn(dir: File, tool: Tool): List<String> =
|
||||
@@ -56,15 +49,12 @@ object ProtonExtras {
|
||||
?.sortedWith { a, b -> compareVersions(a, b) }
|
||||
?: emptyList()
|
||||
|
||||
// Architecture names carry digits (aarch64, x86_64) that are not part of a version.
|
||||
private val ARCH = Regex("(?i)aarch64|arm64|x86_64|x86-64|amd64")
|
||||
private val NUMBER = Regex("\\d+")
|
||||
|
||||
/** The numbers in a release tag or build folder, in order: GE-Proton11-10 is 11, 10. */
|
||||
internal fun versionKey(name: String): List<Long> =
|
||||
NUMBER.findAll(ARCH.replace(name, " ")).mapNotNull { it.value.toLongOrNull() }.toList()
|
||||
|
||||
/** Orders by those numbers, so 11-10 is after 11-9; the name itself only breaks a tie. */
|
||||
internal fun compareVersions(a: String, b: String): Int {
|
||||
val x = versionKey(a)
|
||||
val y = versionKey(b)
|
||||
@@ -72,7 +62,6 @@ object ProtonExtras {
|
||||
return if (x.size != y.size) x.size.compareTo(y.size) else a.compareTo(b)
|
||||
}
|
||||
|
||||
/** [latest] when it is newer than every installed release, else null. Nothing installed is not an update. */
|
||||
internal fun updateFor(installed: List<String>, latest: String?): String? {
|
||||
if (latest == null || installed.isEmpty()) return null
|
||||
val newest = installed.maxWithOrNull { a, b -> compareVersions(a, b) } ?: return null
|
||||
@@ -82,28 +71,20 @@ object ProtonExtras {
|
||||
return if (x.size > y.size) latest else null
|
||||
}
|
||||
|
||||
/** The release each installed build came from: the tag recorded at install, else its folder name. */
|
||||
fun installedTags(context: Context, tool: Tool): List<String> {
|
||||
val recorded = readJson(releasesFile(context))
|
||||
return installedAll(context, tool).map { recorded.optString(it).ifEmpty { it } }
|
||||
}
|
||||
|
||||
/** A newer release than the installed one, from the last check (no network), or null. */
|
||||
fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool))
|
||||
|
||||
fun cachedLatest(context: Context, tool: Tool): String? =
|
||||
readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null }
|
||||
|
||||
/** Its own lock, not the install's: a check must not wait behind a download. */
|
||||
private val checkLock = Any()
|
||||
/** A failed look-up (offline) is not repeated on every resume, only after this long. */
|
||||
private const val RETRY_MS = 15L * 60 * 1000
|
||||
private var lastAttempt = 0L
|
||||
|
||||
/**
|
||||
* Looks up each source's newest release unless it was looked up within [CHECK_EVERY_MS] (or
|
||||
* [force]). Offline or rate limited, the last answer stands. True when anything was asked.
|
||||
*/
|
||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
||||
synchronized(checkLock) {
|
||||
val file = latestFile(context)
|
||||
@@ -143,7 +124,6 @@ object ProtonExtras {
|
||||
private fun readJson(file: File): JSONObject =
|
||||
runCatching { JSONObject(FileUtils.readString(file) ?: "{}") }.getOrDefault(JSONObject())
|
||||
|
||||
/** A request left by an earlier app version, still consumed by the session shim. */
|
||||
fun queued(context: Context, tool: Tool): Boolean =
|
||||
requestLines(context).any { it.trim() == tool.id || it.trim().startsWith(tool.id + " ") }
|
||||
|
||||
@@ -154,18 +134,15 @@ object ProtonExtras {
|
||||
else file.writeText(lines.joinToString("\n") + "\n")
|
||||
}
|
||||
|
||||
/** Deletes one installed build ([dir], else the newest); Steam discovers its absence on its next start. */
|
||||
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()
|
||||
}
|
||||
|
||||
/** Deletes every build but the newest. */
|
||||
fun removeOlder(context: Context, tool: Tool) {
|
||||
installedAll(context, tool).dropLast(1).forEach { File(toolsDir(context), it).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
@@ -211,8 +188,6 @@ object ProtonExtras {
|
||||
return context.getString(R.string.pextra_incomplete)
|
||||
}
|
||||
|
||||
// One checksum has to be found and has to match: GitHub's sha256 digest, else the
|
||||
// release's own sha512 file. A download neither vouches for is not installed.
|
||||
onProgress(context.getString(R.string.pextra_verifying), -1)
|
||||
val verified = when {
|
||||
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
|
||||
@@ -257,7 +232,6 @@ object ProtonExtras {
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
// "droiddeck-proton-extra: installed <folder>", the folder as the tarball names it.
|
||||
line.substringAfter("droiddeck-proton-extra: installed ", "").takeIf { it.isNotEmpty() }?.let { placed = it }
|
||||
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
||||
onProgress(installing, -1)
|
||||
@@ -296,7 +270,6 @@ object ProtonExtras {
|
||||
}
|
||||
}
|
||||
|
||||
/** The newest full release in GitHub's list (newest first) that carries [tool]'s ARM64 archive. */
|
||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
||||
for (i in 0 until array.length()) {
|
||||
val release = array.getJSONObject(i)
|
||||
|
||||
@@ -6,7 +6,6 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import java.io.File
|
||||
|
||||
/** Device-detected defaults and launch evidence for experimental Quest compatibility. */
|
||||
object QuestExperimental {
|
||||
private const val TAG = "QuestExperimental"
|
||||
const val DRIVER = "turnip25.1.0-quest1"
|
||||
@@ -30,14 +29,10 @@ object QuestExperimental {
|
||||
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
val defaultsKey = if (isQuest2()) "quest2DefaultsV1" else "questDefaultsV1"
|
||||
if (!prefs.getBoolean(defaultsKey, false)) {
|
||||
// Auto would download an unwrapped display driver and lose the compatibility path.
|
||||
// Apply once so deliberate changes made during headset testing remain possible.
|
||||
prefs.edit()
|
||||
.putString("gpuDriverMode", SessionPrefs.GPU_DRIVERS_MANUAL)
|
||||
.putString("androidDriver", if (isQuest2()) DRIVER_A6XX else DRIVER)
|
||||
.putString("linuxDriver", "")
|
||||
// The existing HDR option uses SurfaceControl presentation. This is a
|
||||
// corruption workaround from upstream issue #245, not a claim of HDR accuracy.
|
||||
.putBoolean("hdr.steam", true)
|
||||
.putBoolean(defaultsKey, true)
|
||||
.apply()
|
||||
|
||||
@@ -4,25 +4,11 @@ import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Other apps on the device that sign into the user's Steam account with their own client. Steam
|
||||
* allows one session per account: the moment one of them signs in, ours is signed out - which
|
||||
* shows up as "Session Replaced" in the client's log 2-3 seconds after every login, and looks
|
||||
* like a bug in this app.
|
||||
*
|
||||
* Installed is the most a normal app can know (since Android 7 `getRunningAppProcesses()` returns
|
||||
* only the caller's own), so the list is checked for presence and then asked to stop.
|
||||
* `killBackgroundProcesses` is a normal permission: it ends an app's background processes and
|
||||
* leaves anything in the foreground alone - and background is exactly the case that keeps
|
||||
* happening, because GameHub declares boot receivers and is running from the moment the phone
|
||||
* starts without ever having been opened. Telling someone to close an app they never opened is
|
||||
* not much help. Ported from Bannerlator's Linux session (GPL-3.0).
|
||||
*/
|
||||
object RivalClients {
|
||||
private const val TAG = "RivalClients"
|
||||
|
||||
private val PACKAGES = arrayOf(
|
||||
"com.xiaoji.egggame", // GameHub
|
||||
"com.xiaoji.egggame",
|
||||
)
|
||||
|
||||
fun installed(context: Context): List<String> =
|
||||
@@ -32,10 +18,6 @@ object RivalClients {
|
||||
|
||||
fun name(pkg: String): String = if (pkg == "com.xiaoji.egggame") "GameHub" else pkg
|
||||
|
||||
/**
|
||||
* Stop the installed rivals' background processes before the client starts. A rival in the
|
||||
* foreground survives this. The activity service call and its log messages are unchanged.
|
||||
*/
|
||||
fun stopBeforeSession(context: Context) {
|
||||
val rivals = installed(context)
|
||||
if (rivals.isEmpty()) return
|
||||
|
||||
@@ -17,26 +17,11 @@ import com.droiddeck.launcher.input.PadBridge
|
||||
import java.io.DataInputStream
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Rumble for the pad, on the motors in the player's hands.
|
||||
*
|
||||
* When a game plays a force-feedback effect on the fake pad (or Steam Input sends the Deck's
|
||||
* rumble report), the fake evdev layer inside the guest connects to the abstract socket [NAME]
|
||||
* and sends one packet: strong, weak, duration in ms and the pad slot, four little-endian 16-bit
|
||||
* values. This listens for those and plays the effect on the physical controller playing in that
|
||||
* slot (PadBridge.controllerForSlot) when Android exposes its motors - strong and weak separately
|
||||
* where it has two - and otherwise on the device's own vibrator, with the stronger motor's
|
||||
* strength: the on-screen pad, or a controller without rumble. Best effort both ways: a missing
|
||||
* listener costs the guest nothing, and a bad packet is dropped.
|
||||
*/
|
||||
class RumbleComponent : SessionPart() {
|
||||
@Volatile private var server: LocalServerSocket? = null
|
||||
private var phone: Motors? = null
|
||||
/** Per slot, where its last effect went, so the next one (or a stop) can end it there. */
|
||||
private val playing = HashMap<Int, Motors>()
|
||||
/** Per slot, the last effect handed to the motors and when, to drop the repeats games stream. */
|
||||
private val sent = HashMap<Int, Sent>()
|
||||
/** Each controller's motors, looked up once; null when it has none. */
|
||||
private val controllers = HashMap<Int, Motors?>()
|
||||
private var preferences: SharedPreferences? = null
|
||||
private var enabled = false
|
||||
@@ -44,7 +29,6 @@ class RumbleComponent : SessionPart() {
|
||||
if (key == null || key == "rumble") refreshEnabled()
|
||||
}
|
||||
|
||||
/** The motors of the controller with this input device id, or null when it has none. Tests swap it. */
|
||||
internal var controllerMotors: (Int) -> Motors? = ::lookupController
|
||||
|
||||
@Synchronized private fun refreshEnabled() {
|
||||
@@ -69,9 +53,8 @@ class RumbleComponent : SessionPart() {
|
||||
DataInputStream(client.inputStream).readFully(bytes)
|
||||
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6))
|
||||
} catch (e: Exception) {
|
||||
// A partial packet or a closed peer: nothing to play.
|
||||
} finally {
|
||||
try { client.close() } catch (e: Exception) { /* already gone */ }
|
||||
try { client.close() } catch (e: Exception) { }
|
||||
}
|
||||
}
|
||||
}, "rumble").apply { isDaemon = true; start() }
|
||||
@@ -87,7 +70,7 @@ class RumbleComponent : SessionPart() {
|
||||
controllers.clear()
|
||||
val s = server
|
||||
server = null
|
||||
try { s?.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
|
||||
try { s?.close() } catch (e: Exception) { }
|
||||
}
|
||||
|
||||
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
|
||||
@@ -104,8 +87,6 @@ class RumbleComponent : SessionPart() {
|
||||
}
|
||||
if (target == null) return
|
||||
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); sent.remove(slot); return }
|
||||
// Games re-send their effect every frame; restarting the motor that often floods the haptics
|
||||
// driver. ponytail: a change inside MIN_GAP_MS is dropped, the game's next packet brings it.
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val last = sent[slot]
|
||||
if (last != null && (now - last.at < MIN_GAP_MS || (last.strong == strong && last.weak == weak && now < last.until))) return
|
||||
@@ -118,7 +99,6 @@ class RumbleComponent : SessionPart() {
|
||||
}
|
||||
}
|
||||
|
||||
/** The motors of the controller playing in this slot when it has any, else the phone's. */
|
||||
private fun target(slot: Int): Motors? {
|
||||
val id = PadBridge.controllerForSlot(slot)
|
||||
if (id == PadBridge.NO_CONTROLLER) return phone
|
||||
@@ -134,7 +114,6 @@ class RumbleComponent : SessionPart() {
|
||||
|
||||
private data class Sent(val strong: Int, val weak: Int, val at: Long, val until: Long)
|
||||
|
||||
/** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */
|
||||
internal interface Motors {
|
||||
val name: String
|
||||
fun play(strong: Int, weak: Int, ms: Long)
|
||||
@@ -147,7 +126,6 @@ class RumbleComponent : SessionPart() {
|
||||
override fun cancel() = vibrator.cancel()
|
||||
}
|
||||
|
||||
/** Android 12+: each of the pad's motors on its own, the lower id being the strong one. */
|
||||
@RequiresApi(31)
|
||||
private class PadMotors(override val name: String, private val manager: VibratorManager, private val ids: IntArray) : Motors {
|
||||
override fun play(strong: Int, weak: Int, ms: Long) {
|
||||
@@ -164,7 +142,6 @@ class RumbleComponent : SessionPart() {
|
||||
override fun cancel() = manager.cancel()
|
||||
}
|
||||
|
||||
/** Before Android 12 a pad has one vibrator. */
|
||||
private class LegacyPadMotors(override val name: String, private val vibrator: Vibrator) : Motors {
|
||||
override fun play(strong: Int, weak: Int, ms: Long) = vibrator.vibrate(oneShot(vibrator, max(strong, weak), ms))
|
||||
override fun cancel() = vibrator.cancel()
|
||||
@@ -172,9 +149,7 @@ class RumbleComponent : SessionPart() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
/** Must match the fake evdev layer (fakeinput_steam.cpp). */
|
||||
const val NAME = "droiddeck-rumble"
|
||||
/** The shortest time between two effects started on one slot's motors. */
|
||||
const val MIN_GAP_MS = 50L
|
||||
|
||||
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
|
||||
|
||||
@@ -7,7 +7,6 @@ import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
|
||||
import java.security.MessageDigest
|
||||
import java.util.Locale
|
||||
|
||||
/** Android shared storage cannot create the links in Wine prefixes or native Steam depots. */
|
||||
object SecondaryLibrary {
|
||||
private val bootstrapTools = linkedMapOf(
|
||||
"4185400" to "SteamLinuxRuntime_4-arm64",
|
||||
@@ -25,12 +24,10 @@ object SecondaryLibrary {
|
||||
|
||||
val CARD_GUESTS = listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")
|
||||
|
||||
/** Parent binds come first; the more specific private directories override them in PRoot. */
|
||||
fun binds(files: File, library: File, guests: List<String> = CARD_GUESTS): List<String> {
|
||||
val private = privateRoot(files, library)
|
||||
val apps = File(library, "steamapps")
|
||||
val tools = LinkedHashMap(bootstrapTools)
|
||||
// Include other installed Proton/runtime versions, without routing ordinary game depots.
|
||||
apps.listFiles()?.filter { it.name.matches(Regex("appmanifest_\\d+\\.acf")) }?.forEach { manifest ->
|
||||
val text = manifest.readText()
|
||||
val id = Regex("\"appid\"\\s+\"(\\d+)\"").find(text)?.groupValues?.get(1)
|
||||
@@ -48,13 +45,8 @@ object SecondaryLibrary {
|
||||
for (relative in listOf("steamapps/common/$dir", "steamapps/downloading/$id")) {
|
||||
val target = File(private, relative)
|
||||
migrate(File(library, relative), target)
|
||||
// FUSE discarded the executable bits. Steam will restore the depot's exact modes
|
||||
// on verification; its launchers must already be executable when importing it.
|
||||
target.walkTopDown().filter { it.isFile }.forEach { it.setExecutable(true, true) }
|
||||
overrides.add(target to relative)
|
||||
// Steam normalizes depot install directories to lowercase on Android's
|
||||
// case-insensitive shared storage. PRoot binds are case-sensitive, so both
|
||||
// spellings must reach the same private directory during the commit.
|
||||
val lower = relative.lowercase(Locale.ROOT)
|
||||
if (lower != relative) overrides.add(target to lower)
|
||||
}
|
||||
@@ -64,7 +56,6 @@ object SecondaryLibrary {
|
||||
}
|
||||
}
|
||||
|
||||
/** Copy once into a staging directory; retain the source and never merge over a live prefix. */
|
||||
private fun migrate(source: File, target: File) {
|
||||
val migrated = File(target.parentFile, ".${target.name}.migrated")
|
||||
if (target.isDirectory) {
|
||||
|
||||
@@ -16,7 +16,6 @@ data class SelectedGameProfile(
|
||||
val componentFiles: Map<String, String>,
|
||||
val environmentOverrides: Int,
|
||||
val windowsComponentNames: List<String>,
|
||||
/** Start without Steam (GameEnvironment.NO_STEAM) is on for this game. */
|
||||
val startWithoutSteam: Boolean = false,
|
||||
) {
|
||||
val hasOverrides: Boolean
|
||||
@@ -53,7 +52,6 @@ data class SelectedGameProfile(
|
||||
inherited = override == null,
|
||||
)
|
||||
}
|
||||
// Start without Steam is a switch of its own on the Games page, listed by name.
|
||||
val otherEnvironment = environment.games[game.profileKey].orEmpty().keys - FexPreset.environmentKeys -
|
||||
GameEnvironment.NO_STEAM
|
||||
return SelectedGameProfile(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** An active game needs a live window; a launch URL or stale Steam base layer is insufficient. */
|
||||
internal object SessionAchievementGame {
|
||||
fun activeAppId(focused: Long?, windows: List<Long>, installed: Set<Long>): Long? {
|
||||
if (focused != null && focused > 0 && focused != 769L) {
|
||||
|
||||
@@ -11,44 +11,16 @@ import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Finishes a session's folder: the compositor's log, the Steam client's logs scrubbed line by
|
||||
* line, Android's crash buffer, and a marker that says the folder is complete.
|
||||
*
|
||||
* Three callers, because a session ends three ways. [collect] runs at an ordinary stop. The
|
||||
* app's uncaught-exception handler ([CrashHandler]) runs it as the process dies, so a crash in
|
||||
* our own code leaves a full folder and not a half one. And [finishAbandoned] runs at the next
|
||||
* app start for a folder that has no marker: the process was killed outright (Android's phantom
|
||||
* process killer, a native crash in the compositor, the battery) and nothing of ours got to run.
|
||||
* Everything written *during* the session - session.log, app.log, wayland.log, audio.log, the
|
||||
* device report - is already on disk at that point; only the pieces gathered at the end were
|
||||
* missing, and the crash buffer keeps its entries after the process is gone, which is the whole
|
||||
* reason it is worth coming back for.
|
||||
*/
|
||||
object SessionArtifacts {
|
||||
private const val TAG = "SessionArtifacts"
|
||||
|
||||
/** Written last; a folder without it did not get its ending. */
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
/**
|
||||
* Every file in the folder has been through the redactor under its current rules. Named after
|
||||
* [LogRedactor.RULES_VERSION], so a folder scrubbed under older rules is scrubbed again.
|
||||
*/
|
||||
private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}"
|
||||
private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""")
|
||||
|
||||
/**
|
||||
* Written by a session's own ending, and only when every file in the folder, subfolders
|
||||
* included (whatever the session script copied into steam/ and droiddeck-esync/ as well as what
|
||||
* the app wrote), went through the redactor without a failure. It lists each of those files
|
||||
* with its size and modification time, under the redactor's rules version ([scrubbedFiles]).
|
||||
* A share no longer relies on it: every text file goes through the share pass on the way into
|
||||
* the zip regardless.
|
||||
*/
|
||||
const val SCRUBBED_TREE_MARKER = ".scrubbed-tree"
|
||||
|
||||
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
|
||||
fun collect(context: Context, dir: File, reason: String) {
|
||||
try {
|
||||
val wayland = File(dir, "wayland.log")
|
||||
@@ -60,7 +32,6 @@ object SessionArtifacts {
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
val record = Record(dir)
|
||||
copySteamLogs(context, dir, record)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
markScrubbed(scrubTree(record))
|
||||
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
|
||||
@@ -70,17 +41,6 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every session folder not yet scrubbed under the redactor's current rules - written before
|
||||
* every file was scrubbed, before the device's own addresses or the Steam account were, or
|
||||
* moved in from Download/ ([LogMigration] strips their markers first, [unmarkMoved]): the
|
||||
* whole folder, steam/ and every other subfolder included, through the redactor, and the
|
||||
* current marker written in place of the old ones. Runs at app start with [finishAbandoned].
|
||||
*
|
||||
* A folder holds some 30 MB of Steam logs, about half a minute's work, so folders go through
|
||||
* a few at a time; one the process does not get to keeps its old marker and is taken up at
|
||||
* the next start.
|
||||
*/
|
||||
@Synchronized
|
||||
fun scrubOlder(context: Context) {
|
||||
val current = SessionPaths.current()
|
||||
@@ -104,27 +64,14 @@ object SessionArtifacts {
|
||||
if (failed > 0) ", $failed not fully (again at the next start)" else "")
|
||||
}
|
||||
|
||||
/**
|
||||
* Folders [LogMigration] just moved in lose every scrub marker an earlier build left, so
|
||||
* [scrubOlder], which runs right after it, puts them through the current rules whatever those
|
||||
* markers claimed.
|
||||
*/
|
||||
fun unmarkMoved(dirs: List<File>) {
|
||||
dirs.filter { SessionPaths.isSessionFolder(it) }.forEach { dir ->
|
||||
dir.listFiles { f -> OLD_SCRUBBED_MARKER.matches(f.name) || f.name == SCRUBBED_TREE_MARKER }?.forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's own files (session.log, app.log, desktop.log, the Steam desktop client's
|
||||
* steam-desktop.log, ...) were written as they happened, unscrubbed; this pass puts every one
|
||||
* through the redactor before the folder can be shared. A file is rewritten only if a line
|
||||
* changed. steam/ was scrubbed on the way in.
|
||||
*/
|
||||
/** A file's size and modification time as they stood right after it was scrubbed. */
|
||||
private class Scrubbed(val length: Long, val modified: Long)
|
||||
|
||||
/** Files of a folder as they stood right after scrubbing, filled by [scrubTree] and [copySteamLogs]. */
|
||||
private class Record(val dir: File) {
|
||||
val files = HashMap<File, Scrubbed>()
|
||||
var failed = false
|
||||
@@ -138,12 +85,6 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts [f] through the redactor in place. Returns its size and modification time as it then
|
||||
* stands, or null if it could not, and [f] may still hold the original. A writer still
|
||||
* appending to [f] (the app's own log capture) changes its size afterwards, and a share then
|
||||
* scrubs it again.
|
||||
*/
|
||||
private fun scrubFile(dir: File, f: File): Scrubbed? {
|
||||
val tmp = File(dir, ".${f.name}.scrub")
|
||||
return try {
|
||||
@@ -152,11 +93,8 @@ object SessionArtifacts {
|
||||
val scrubbed = tmp.readBytes()
|
||||
if (scrubbed.contentEquals(f.readBytes())) {
|
||||
tmp.delete()
|
||||
// Unchanged by the redactor, and by anything else while it read.
|
||||
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
|
||||
} else {
|
||||
// Shared storage can refuse a rename; then the scrubbed bytes are written over the
|
||||
// original instead, so it never stays behind unscrubbed.
|
||||
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
|
||||
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
|
||||
}
|
||||
@@ -167,14 +105,9 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records [record]'s folder as scrubbed - every file went through without a failure - or
|
||||
* leaves it unmarked, so the next share and the pass over older folders scrub it again.
|
||||
*/
|
||||
private fun markScrubbed(record: Record): Boolean {
|
||||
val dir = record.dir
|
||||
val tree = File(dir, SCRUBBED_TREE_MARKER)
|
||||
// A marker from older rules vouches for nothing now, whether or not this pass succeeded.
|
||||
dir.listFiles { f -> OLD_SCRUBBED_MARKER.matches(f.name) }?.forEach { it.delete() }
|
||||
if (record.failed) {
|
||||
tree.delete()
|
||||
@@ -197,11 +130,6 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The files of [dir] that its own ending scrubbed and that are unchanged since (same size and
|
||||
* modification time), by path relative to [dir]. Empty when the folder has no such record, or
|
||||
* one made under other redactor rules.
|
||||
*/
|
||||
fun scrubbedFiles(dir: File): Set<String> {
|
||||
val lines = try { File(dir, SCRUBBED_TREE_MARKER).takeIf { it.isFile }?.readLines() } catch (e: Exception) { null }
|
||||
?: return emptySet()
|
||||
@@ -214,21 +142,13 @@ object SessionArtifacts {
|
||||
}.toSet()
|
||||
}
|
||||
|
||||
/** The end-of-session scrub of [dir] on its own (steam/ already in place); also the pass over older and moved folders. */
|
||||
internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir)))
|
||||
|
||||
/**
|
||||
* [record]'s folder and every folder under it (steam/, droiddeck-esync/): the session script
|
||||
* copied files there verbatim, and a Steam log the app did not copy over again (gone from the
|
||||
* runtime, or past its size limit) stayed as the script left it. Files [copySteamLogs] already
|
||||
* redacted on the way in are in [record] and left alone.
|
||||
*/
|
||||
private fun scrubTree(record: Record): Record {
|
||||
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
|
||||
return record
|
||||
}
|
||||
|
||||
/** Steam's logs: redacted into steam/, never copied verbatim. What it wrote goes in [record]. */
|
||||
private fun copySteamLogs(context: Context, dir: File, record: Record) {
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
if (!logs.isDirectory) return
|
||||
@@ -247,12 +167,6 @@ object SessionArtifacts {
|
||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||
}
|
||||
|
||||
/**
|
||||
* Every session folder without a marker gets its ending now. Only the newest of them gets the
|
||||
* Steam logs - the runtime holds one set, and it belongs to the last session that ran; an
|
||||
* older folder would be handed logs that are not its own. Runs on a worker thread at app
|
||||
* start; nothing here touches the session that is about to begin.
|
||||
*/
|
||||
@Synchronized
|
||||
fun finishAbandoned(context: Context) {
|
||||
val parent = LinuxRuntime.logDir(context)
|
||||
@@ -289,12 +203,6 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the newest [SessionPaths.KEEP_SESSIONS] session folders and deletes the rest: a few
|
||||
* days of testing left hundreds, and the one a report needed was lost among them. Only folders
|
||||
* that are finished; the session in progress is never touched. Runs at app start after
|
||||
* [finishAbandoned], on its worker thread.
|
||||
*/
|
||||
@Synchronized
|
||||
fun prune(context: Context) {
|
||||
val current = SessionPaths.current()
|
||||
@@ -304,11 +212,6 @@ object SessionArtifacts {
|
||||
if (old.isNotEmpty()) Log.i(TAG, "deleted ${old.size} session folder(s) past the newest ${SessionPaths.KEEP_SESSIONS}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Every session folder but the one in progress, and the one-off command logs (tools/, or loose
|
||||
* beside the folders from before it): the Setup page's Clear logs. Returns how many session
|
||||
* folders went.
|
||||
*/
|
||||
@Synchronized
|
||||
fun clearAll(context: Context): Int {
|
||||
val current = SessionPaths.current()
|
||||
|
||||
@@ -3,26 +3,14 @@ package com.droiddeck.launcher.session
|
||||
import android.content.Context
|
||||
import android.view.WindowManager
|
||||
|
||||
/** The virtual display advertised to the guest, before it is fitted onto the Android panel. */
|
||||
object SessionDisplay {
|
||||
const val MATCH_SCREEN = "screen"
|
||||
/** The window's size, kept in step while the session runs: a foldable opening or closing, a
|
||||
* split screen or a freeform window resizes the guest's display instead of letterboxing it. */
|
||||
const val FOLLOW_SCREEN = "follow"
|
||||
/** Below this a side is a picture-in-picture or a sliver of split screen: not worth a resize. */
|
||||
const val FOLLOW_MIN_SIDE = 480
|
||||
|
||||
/**
|
||||
* Presets are heights, not sizes: "720p" is the panel's own shape at 720 lines, never narrower
|
||||
* than 16:9 and never taller than the panel (SHAPE_AUTO). The client treats the output as the
|
||||
* games' native resolution, so the height is what bounds a game's default size on a 1440p
|
||||
* phone; the shape is what keeps the client's interface edge to edge on a 20:9 one (1600x720)
|
||||
* and keeps games at 16:9 or wider on a foldable's near-square panel.
|
||||
*/
|
||||
const val DEFAULT_RESOLUTION = "720p"
|
||||
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
|
||||
|
||||
/** The height of a preset choice ("900p"), or null for Match screen and fixed sizes. */
|
||||
fun presetHeight(choice: String): Int? =
|
||||
if (choice.endsWith("p")) choice.dropLast(1).toIntOrNull()?.takeIf { it > 0 } else null
|
||||
|
||||
@@ -32,42 +20,27 @@ object SessionDisplay {
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> {
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return screenSize(panel)
|
||||
presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) }
|
||||
// Fixed sizes (custom, or a preset saved before presets were heights) keep their exact size,
|
||||
// including legacy ones past the custom dialog's limit.
|
||||
val parts = choice.split('x').map { it.toIntOrNull() }
|
||||
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
|
||||
else resolve(panel, 720, SessionPrefs.SHAPE_AUTO)
|
||||
}
|
||||
|
||||
/** The height presets the panel is tall enough for, then the panel itself, with no duplicate
|
||||
* sizes, then Follow screen. */
|
||||
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
|
||||
val panelHeight = minOf(panel.first, panel.second)
|
||||
return PRESET_HEIGHTS.filter { it <= panelHeight }.map { "${it}p" }
|
||||
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN
|
||||
}
|
||||
|
||||
/** A Follow screen session's display for a window of this size: its own shape, square or
|
||||
* portrait included, with even sides; null when it is too small to follow (PiP). */
|
||||
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
|
||||
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
|
||||
|
||||
/** Unfolded controls: the most of the window the game may take, so a window near 16:9 itself
|
||||
* still leaves the Deck controls room. */
|
||||
const val UNFOLDED_MAX_GAME_SHARE = 0.8f
|
||||
|
||||
/** A foldable: Android 11's hinge angle sensor, which foldables report and slates do not. Unfolded
|
||||
* controls are offered only there - untested on tablets, whose 16:10 landscape leaves them
|
||||
* little room under a 16:9 game. */
|
||||
fun foldable(context: Context): Boolean =
|
||||
context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")
|
||||
|
||||
/** A panel at least this wide on its shortest side (dp) is a foldable's unfolded inner screen. */
|
||||
const val UNFOLDED_MIN_DP = 600
|
||||
|
||||
/** Unfolded controls: the game's height in a window of this size - 16:9 across the full width,
|
||||
* held either way, with even sides - and the Deck controls take the rest below it, laid out to
|
||||
* whatever that leaves (DeckControlsPanel's GamepadLayout). */
|
||||
fun unfoldedGameHeight(width: Int, height: Int): Int =
|
||||
minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) and 1.inv()
|
||||
|
||||
@@ -79,13 +52,10 @@ object SessionDisplay {
|
||||
return maxOf(mode.physicalWidth, mode.physicalHeight) to minOf(mode.physicalWidth, mode.physicalHeight)
|
||||
}
|
||||
|
||||
/** Interpret an older cap/aspect combination without altering the saved picture size. */
|
||||
fun resolve(panel: Pair<Int, Int>, cap: Int, shape: String, custom: Pair<Int, Int>? = null): Pair<Int, Int> {
|
||||
custom?.let { return it }
|
||||
val panelW = maxOf(panel.first, panel.second).toFloat()
|
||||
val panelH = minOf(panel.first, panel.second).toFloat().coerceAtLeast(1f)
|
||||
// Auto retains wide panels but floors squarer ones at 16:9 for game compatibility.
|
||||
// Match screen removes that floor; fixed 16:9 also keeps foldable sessions stable.
|
||||
val aspect = when (shape) {
|
||||
SessionPrefs.SHAPE_WIDE -> 16f / 9f
|
||||
SessionPrefs.SHAPE_EXACT -> panelW / panelH
|
||||
@@ -95,7 +65,6 @@ object SessionDisplay {
|
||||
return ((height * aspect).toInt() and 1.inv()) to (height and 1.inv())
|
||||
}
|
||||
|
||||
/** Mirrors gamescope's even-width 16:9 calculation, including near-16:9 rounding. */
|
||||
fun canStretch16x9(size: Pair<Int, Int>): Boolean =
|
||||
(size.second * 16 + 4) / 9 / 2 * 2 > size.first
|
||||
}
|
||||
@@ -6,15 +6,11 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
|
||||
/** Writes the machine-readable lifecycle stream beside the existing session artifacts. */
|
||||
object SessionEvents {
|
||||
private const val TAG = "SessionEvents"
|
||||
private val lock = Any()
|
||||
|
||||
/** [label] names the session's folder for what is being run (SessionPaths.label). */
|
||||
fun begin(context: Context, mode: String, label: String? = null) {
|
||||
// A runtime-install failure can leave the folder claimed before the service ever starts.
|
||||
// Keep that folder, but give the next attempt its own session directory.
|
||||
SessionPaths.take()
|
||||
val dir = SessionPaths.beginOrCurrent(context, label ?: SessionPaths.label(mode, null))
|
||||
synchronized(SessionState) {
|
||||
|
||||
@@ -11,37 +11,22 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import java.io.File
|
||||
|
||||
/** Everything the session needs written into the runtime before it starts. */
|
||||
object SessionFiles {
|
||||
private const val TAG = "SessionFiles"
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
/** Where the DirectAudio driver lives inside the runtime; the wrappers get it as BL_DIRECTAUDIO. */
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
/** The driver sets staged under it: classic Wine 11 (Valve, GE) and the system-thread interface (Proton-CachyOS). */
|
||||
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
|
||||
|
||||
// Staged only with a complete desktop; removal matches these against the APK as well.
|
||||
internal val DESKTOP_FILES = arrayOf(
|
||||
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
|
||||
// Games and emulators from the menu, full screen in a gamescope of their own.
|
||||
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
|
||||
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
|
||||
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
|
||||
// KWin at the app's surface size, for Plasma's session (it starts KWin through this name).
|
||||
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
|
||||
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
||||
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
|
||||
)
|
||||
|
||||
/**
|
||||
* The libraries and scripts the session runs, refreshed from the apk at every launch.
|
||||
*
|
||||
* The runtime image carries its own copies, but a runtime installed months ago carries the
|
||||
* copies of that day and a device has no way to replace them from outside the app. Staging
|
||||
* them here is how a fix inside the session shim, the controller reader or one of the scripts
|
||||
* reaches an already-installed runtime without a ~790 MB re-download. Each lands through a
|
||||
* rename, so a session that still has one mapped keeps the file it opened.
|
||||
*/
|
||||
fun stage(context: Context, root: File) {
|
||||
if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
@@ -81,47 +66,30 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
|
||||
"usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim",
|
||||
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
|
||||
// Asks the app for an Epic game's sign-in code at launch, from the compat tool (StoreLaunchRequests).
|
||||
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
|
||||
// A game's web links to Android's browser (Wine's winebrowser starts it).
|
||||
"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",
|
||||
// Cardboard mode's SteamVR: install, start and stop (docs/cardboard-vr.md).
|
||||
"usr/local/bin/droiddeck-steamvr" to "usr/local/bin/droiddeck-steamvr",
|
||||
// Flatpak: the bwrap stand-in, the store's helper and setup, and the front end's launcher.
|
||||
"usr/local/bin/droiddeck-bwrap" to "usr/local/bin/droiddeck-bwrap",
|
||||
"usr/local/bin/droiddeck-flatpak" to "usr/local/bin/droiddeck-flatpak",
|
||||
"usr/local/bin/droiddeck-flatpak-setup" to "usr/local/bin/droiddeck-flatpak-setup",
|
||||
"usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run",
|
||||
// The user's own AppImages, extracted at import (AppImageManager).
|
||||
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
|
||||
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
|
||||
// The desktop's Run entries and its exec fallback: Windows programs through Steam's Proton,
|
||||
// x86 Linux programs through FEX.
|
||||
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
|
||||
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
|
||||
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
|
||||
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
|
||||
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
||||
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
|
||||
// Big Picture's "Switch to Desktop": asks the app for the desktop with Steam in it.
|
||||
"usr/bin/steamos-session-select" to "usr/bin/steamos-session-select",
|
||||
"usr/bin/jupiter-biosupdate" to "usr/bin/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-priv-write" to "usr/bin/steamos-polkit-helpers/steamos-priv-write",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-set-timezone" to "usr/bin/steamos-polkit-helpers/steamos-set-timezone",
|
||||
// On device the client called these four by their polkit-helpers path, not /usr/bin: the
|
||||
// "Update Error" dialog was steamos-update missing there.
|
||||
"usr/bin/steamos-polkit-helpers/steamos-update" to "usr/bin/steamos-polkit-helpers/steamos-update",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-select-branch" to "usr/bin/steamos-polkit-helpers/steamos-select-branch",
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-biosupdate" to "usr/bin/steamos-polkit-helpers/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-dock-updater" to "usr/bin/steamos-polkit-helpers/jupiter-dock-updater",
|
||||
)
|
||||
// The patched gamescope (tools/gamescope): the runtime's own version rebuilt with the ARM64
|
||||
// client fixes, over /usr/local/bin so it comes first in the session's PATH. Only when the
|
||||
// apk carries it - a build without the asset leaves the runtime's copy alone.
|
||||
// Valve's mangoapp (tools/mangoapp) - Deck mode's performance overlay - with the five
|
||||
// libraries the runtime lacks beside it, and the wrapper on PATH that points it at them.
|
||||
val mangoapp = listOf(
|
||||
"usr/local/bin/mangoapp",
|
||||
"usr/local/lib/mangoapp/mangoapp",
|
||||
@@ -131,11 +99,9 @@ object SessionFiles {
|
||||
"usr/local/lib/mangoapp/libtraceevent.so.1",
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
// What the Windows components installer reads .msi packages with (tools/msitools).
|
||||
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||
// Cardboard mode's SteamVR driver and the Vulkan layer its compositor needs (tools/vr).
|
||||
val vr = listOf(
|
||||
"droiddeck/bin/linuxarm64/driver_droiddeck.so",
|
||||
"droiddeck/driver.vrdrivermanifest",
|
||||
@@ -143,8 +109,6 @@ object SessionFiles {
|
||||
"layer/libVkLayer_droiddeck_vr.so",
|
||||
"layer/VK_LAYER_DROIDDECK_vr.json",
|
||||
).map { "usr/local/lib/droiddeck-vr/$it" to "usr/local/lib/droiddeck-vr/$it" } +
|
||||
// The same layer, implicit for the whole session: it passes everything through until SteamVR
|
||||
// runs, then Steam's own web helper gets the shared-texture support it needs (tools/vr).
|
||||
listOf("usr/local/lib/droiddeck-vr/layer/VK_LAYER_DROIDDECK_vr_implicit.json" to
|
||||
"usr/share/vulkan/implicit_layer.d/droiddeck_vr.json")
|
||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||
@@ -180,12 +144,6 @@ object SessionFiles {
|
||||
LegacyNames.migrateRootfs(root)
|
||||
ComponentsManager.migrateLaunchDir(context)
|
||||
EsyncPacks.stageBundled(context, root)
|
||||
// The DirectAudio driver for games under Proton: the glibc build of winedirectaudio, which
|
||||
// the Proton wrappers add to WINEDLLPATH when the session asks for it (BL_DIRECTAUDIO). Two
|
||||
// sets, one per Wine audio interface - the wrapper picks by what the Proton's own winepulse.so
|
||||
// imports (see steam-compatibility), because both Wines call themselves 11.0 and the wrong set
|
||||
// plays silence. Staged like the scripts, so a driver fix reaches an installed runtime without
|
||||
// re-hosting. The sets come from the pinned DirectAudio release (tools/directaudio/release.env).
|
||||
val directAudio = arrayOf(
|
||||
"aarch64-unix/winedirectaudio.so",
|
||||
"aarch64-windows/winedirectaudio.drv",
|
||||
@@ -209,18 +167,11 @@ object SessionFiles {
|
||||
}
|
||||
if (!installed) Log.e(TAG, "DirectAudio $set/$relative NOT staged")
|
||||
}
|
||||
// A runtime from before the sets had names kept the driver at the directory's root; it would
|
||||
// never be picked again, so it goes.
|
||||
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
|
||||
// What every process in the session preloads. LD_PRELOAD in the environment would not
|
||||
// survive: the Steam client rebuilds it for each process it starts and appends its own
|
||||
// overlay entry without a separator, which silently drops whatever was there.
|
||||
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
// Last, so the others' opens and stats reach it through RTLD_NEXT. It stays idle in any
|
||||
// process its proot did not describe to it (ProotFastPath).
|
||||
if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n")
|
||||
val etc = File(root, "etc").apply { mkdirs() }
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
@@ -234,8 +185,6 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
val startupMovieDir = File(root, "root/.local/share/Steam/config/uioverrides/movies")
|
||||
// Steam looks up these conventional names in its user override directory. Keep both
|
||||
// variants populated because the startup movie name differs across Steam clients.
|
||||
val bigPictureMovieInstalled = stageStartupMovie(
|
||||
context,
|
||||
startupMovieDir,
|
||||
@@ -387,10 +336,5 @@ object SessionFiles {
|
||||
indent + "}",
|
||||
).joinToString(newline)
|
||||
|
||||
/**
|
||||
* Where the session writes its log: app-private `files/logs`, bound into the session at the same
|
||||
* path, so the session script's own redirection always opens. A folder leaves the device only
|
||||
* through Share logs, which scrubs every file again on the way into the zip.
|
||||
*/
|
||||
fun logDirectory(context: Context): File = LinuxRuntime.logDir(context).apply { mkdirs() }
|
||||
}
|
||||
@@ -17,28 +17,12 @@ import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
/**
|
||||
* Share logs: one zip, made when asked, of a session folder (the newest by default) with the last
|
||||
* seven days of the stores' log and the one-off command logs beside it, handed to Android's share
|
||||
* sheet. Logs live in app-private `files/logs`; this is how they leave the device. Every text file
|
||||
* goes through [LogRedactor.redactForShare] on the way in, so even a file written before a rule
|
||||
* existed is clean in the zip. The zip sits in `cache/share/` until the next share or app start.
|
||||
*/
|
||||
object SessionLogShare {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* How far the zip for a share has got, 0..1, or null when none is being made. The Share logs
|
||||
* buttons show it in place of their label, so a tap is answered at once.
|
||||
*/
|
||||
var progress by mutableStateOf<Float?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* Zips [folder] on a worker thread with [progress] following along, then hands the zip (null
|
||||
* if there was nothing to zip or it failed) to [done] on the main thread. Call on the main
|
||||
* thread; a tap while a zip is being made is ignored.
|
||||
*/
|
||||
fun prepare(context: Context, folder: () -> File?, done: (File?) -> Unit) {
|
||||
if (progress != null) return
|
||||
progress = 0f
|
||||
@@ -50,29 +34,17 @@ object SessionLogShare {
|
||||
}, "share-logs").start()
|
||||
}
|
||||
|
||||
/** The newest session folder in either place logs are written, or null if there is none. */
|
||||
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
|
||||
|
||||
/** Builds the zip (blocking). Returns null when there is no session to share. */
|
||||
|
||||
/** Builds a zip for one specific session folder (blocking). */
|
||||
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
|
||||
if (!folder.isDirectory) return null
|
||||
// The client's logs past STEAM_LOG_MAX_BYTES stay out, as they do from the app's own copy: a
|
||||
// CEF debug log or an old *.previous.txt reached 17 MB, every share scrubbed them line by
|
||||
// line, and the share sheet took ten seconds to appear.
|
||||
val files = folder.walkTopDown().filter { it.isFile }
|
||||
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
|
||||
if (files.isEmpty()) return null
|
||||
val out = shareDir(context).apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
|
||||
// session pass yet, and the redactor changes nothing in a line that is already clean.
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
// A finished folder was scrubbed whole when it ended. A file its record lists, unchanged
|
||||
// since, goes in as it is; anything else (added or changed since, hidden, or any file of a
|
||||
// session still running) is scrubbed again. Scrubbing tens of MB of the client's logs on
|
||||
// every share kept the share sheet from appearing for ten seconds or more.
|
||||
val live = liveSteamLogs(context, folder)
|
||||
val logs = LinuxRuntime.logDir(context)
|
||||
val stores = recent(File(logs, STORES_DIR))
|
||||
@@ -96,7 +68,6 @@ object SessionLogShare {
|
||||
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
|
||||
z.putNextEntry(ZipEntry(name))
|
||||
// Every text file, every time: the folder's own scrub may predate a rule.
|
||||
if (LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubForShare(f, w)
|
||||
@@ -107,38 +78,26 @@ object SessionLogShare {
|
||||
z.closeEntry()
|
||||
}
|
||||
|
||||
/**
|
||||
* The client's own logs as they stand, for a session shared while it runs. The session script
|
||||
* copies them into steam/ only as it exits, so a zip made from the drawer had none - and
|
||||
* controller.txt (which pad the client opened, the touch mode it set) is what a controller or
|
||||
* touch report needs most. Only for the running session: an older folder would get this
|
||||
* session's logs. The same files the script copies; nothing holding credentials is in logs/.
|
||||
*/
|
||||
private fun liveSteamLogs(context: Context, folder: File): List<File> {
|
||||
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
|
||||
}
|
||||
|
||||
/** The client's content and bootstrap logs grow large over months and say nothing about a session. */
|
||||
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||
|
||||
/** The stores' engine log, one file a day, under files/logs. */
|
||||
const val STORES_DIR = "stores"
|
||||
private const val RECENT_DAYS = 7
|
||||
|
||||
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
|
||||
|
||||
/** The files in [dir] changed in the last [RECENT_DAYS] days. */
|
||||
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()
|
||||
}
|
||||
|
||||
/** Deletes the last share's zip; at app start, so a zip never outlives the share it was made for. */
|
||||
fun clear(context: Context) {
|
||||
shareDir(context).deleteRecursively()
|
||||
// Where builds before this one put it.
|
||||
File(context.cacheDir, "shared-logs").deleteRecursively()
|
||||
}
|
||||
|
||||
|
||||
@@ -7,42 +7,14 @@ import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* One folder per session under app-private `files/logs/`, holding everything that session recorded,
|
||||
* named for the day, that day's session number and what was run, so the one a report is about can
|
||||
* be picked out without opening any:
|
||||
*
|
||||
* ```
|
||||
* files/logs/2026-09-30-03-steam/
|
||||
* device.txt what this device is, and every setting the session ran with
|
||||
* session.log the guest session: proot, gamescope, the client's stdout
|
||||
* wayland.log the app's compositor
|
||||
* steam.log the Steam client's own log, scrubbed (Steam mode)
|
||||
* steam/ the rest of the client's logs, scrubbed (Steam mode)
|
||||
* desktop.log KWin, Plasma and the programs on it (desktop mode)
|
||||
* files/logs/tools/ one-off commands: Flatpak installs, AppImage imports
|
||||
* files/logs/stores/ the stores' engine log, one file a day
|
||||
* ```
|
||||
*
|
||||
* Folders from before this naming (`session-20260930-180642`) are still recognised, shared and
|
||||
* pruned with the rest.
|
||||
*
|
||||
* The folder is claimed by whoever starts first - the activity starts the compositor before the
|
||||
* service starts the session - so both write into the same one, and a recreated activity (a
|
||||
* foldable opening mid-session) joins the folder in progress instead of opening another.
|
||||
*/
|
||||
object SessionPaths {
|
||||
private const val TAG = "SessionPaths"
|
||||
|
||||
/** How many session folders are kept; older ones go at the next app start. */
|
||||
const val KEEP_SESSIONS = 30
|
||||
|
||||
/** Beside the session folders: the logs of one-off commands (GuestCommand's logName). */
|
||||
const val TOOLS_DIR = "tools"
|
||||
|
||||
/** `2026-09-30-03-steam`: day, that day's session number, what was run. */
|
||||
private val NAMED = Regex("""^(\d{4})-(\d{2})-(\d{2})-(\d{2,})-.+$""")
|
||||
/** `session-20260930-180642`, from before. */
|
||||
private val LEGACY = Regex("""^session-(\d{8})-(\d{6})(-\d+)?$""")
|
||||
|
||||
@Volatile
|
||||
@@ -51,20 +23,12 @@ object SessionPaths {
|
||||
@Volatile
|
||||
private var ended: File? = null
|
||||
|
||||
/**
|
||||
* The folder for the session now starting, or the one already in progress. With logs turned
|
||||
* off on the main screen the folder lives in the app's cache instead of Downloads - the
|
||||
* scripts and the compositor still need somewhere to write - and [release] deletes it.
|
||||
* [label] says what is being run (see [label]); without one it comes from the session's state.
|
||||
*/
|
||||
@Synchronized
|
||||
fun beginOrCurrent(context: Context, label: String? = null): File {
|
||||
dir?.let { if (it.isDirectory) return it }
|
||||
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
|
||||
else File(context.cacheDir, "session-logs")
|
||||
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
|
||||
// The day's highest number plus one, not a count: pruning removes the oldest folders, and
|
||||
// a count would hand out a number already in use.
|
||||
val last = parent.listFiles()?.mapNotNull { f ->
|
||||
NAMED.matchEntire(f.name)?.takeIf { f.name.startsWith("$day-") }?.groupValues?.get(4)?.toIntOrNull()
|
||||
}?.maxOrNull() ?: 0
|
||||
@@ -80,14 +44,8 @@ object SessionPaths {
|
||||
|
||||
fun current(): File? = dir
|
||||
|
||||
/** The folder of the session that ended last, while it is still there: what its Share logs sends. */
|
||||
fun lastEnded(): File? = ended?.takeIf { it.isDirectory }
|
||||
|
||||
/**
|
||||
* The ending session takes its folder with it: the next session (one that replaces this one
|
||||
* in place) then claims a folder of its own instead of sharing, and this one's collector
|
||||
* finishes the folder it was handed. Called on the main thread as the session stops.
|
||||
*/
|
||||
@Synchronized
|
||||
fun take(): File? {
|
||||
val taken = dir
|
||||
@@ -98,22 +56,14 @@ object SessionPaths {
|
||||
|
||||
fun file(name: String): File? = dir?.let { File(it, name) }
|
||||
|
||||
/** Let the next session claim a new folder. Called when a session ends. */
|
||||
@Synchronized
|
||||
fun release(context: Context, ended: File) {
|
||||
// Only the session that owns the folder lets go of it (take() usually has already): the
|
||||
// next session may have claimed its own by the time the last one's collector gets here.
|
||||
if (dir == ended) dir = null
|
||||
// A folder kept in the cache was never meant to outlive its session.
|
||||
if (ended != null && ended.path.startsWith(context.cacheDir.path)) {
|
||||
com.droiddeck.launcher.core.FileUtils.delete(ended)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a session's folder is named for: Steam, the desktop, or the program started from the
|
||||
* rail by its own name (`2026-10-01-02-retroarch`).
|
||||
*/
|
||||
fun label(mode: String, program: String?): String = when (mode) {
|
||||
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(program)
|
||||
?: program?.substringAfterLast('/')
|
||||
@@ -122,21 +72,15 @@ object SessionPaths {
|
||||
else -> mode
|
||||
}
|
||||
|
||||
/** Whether [f] is a session's folder, in either naming. */
|
||||
fun isSessionFolder(f: File): Boolean =
|
||||
f.isDirectory && (NAMED.matches(f.name) || LEGACY.matches(f.name))
|
||||
|
||||
/**
|
||||
* Oldest first: by day, then by when in the day. A folder from before the new naming sorts
|
||||
* ahead of a new one from the same day, which it always predates.
|
||||
*/
|
||||
val chronological: Comparator<File> = compareBy { f ->
|
||||
NAMED.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}${g[2]}${g[3]}1${g[4].padStart(6, '0')}" }
|
||||
?: LEGACY.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}0${g[2]}${g[3].removePrefix("-").padStart(2, '0')}" }
|
||||
?: f.name
|
||||
}
|
||||
|
||||
/** Every session folder in the places logs are written, oldest first. */
|
||||
fun sessionFolders(context: Context): List<File> =
|
||||
(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList())
|
||||
.sortedWith(chronological)
|
||||
|
||||
@@ -12,7 +12,6 @@ import android.widget.Toast
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
|
||||
/** Owns Android's PiP parameters, while the service continues to own the session. */
|
||||
class SessionPipController(
|
||||
private val activity: SessionActivity,
|
||||
private val bounds: () -> Rect,
|
||||
|
||||
@@ -12,7 +12,6 @@ import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import org.json.JSONObject
|
||||
|
||||
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
|
||||
object SessionPrefs {
|
||||
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
|
||||
|
||||
@@ -32,10 +31,8 @@ object SessionPrefs {
|
||||
const val OSC_ALWAYS = "always"
|
||||
const val OSC_STEAM_QAM = "steam-qam"
|
||||
const val OSC_NEVER = "never"
|
||||
/** Steam's touch controller (SteamTouchControls) in place of the app's pad; Steam sessions only. */
|
||||
const val OSC_STEAM_TOUCH = "steam-touch"
|
||||
|
||||
/** What Back does in a Steam session, first press then second: the labels of the two orders. */
|
||||
val BACK_MENU_THEN_QAM = R.string.back_menu_then_qam
|
||||
val BACK_QAM_THEN_MENU = R.string.back_qam_then_menu
|
||||
|
||||
@@ -61,7 +58,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("orientation", orientation).apply()
|
||||
}
|
||||
|
||||
/** Whether the launcher hides Android's status and navigation bars. */
|
||||
fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
|
||||
|
||||
fun setLauncherFullscreen(context: Context, on: Boolean) {
|
||||
@@ -80,14 +76,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("gameStoresEnabled", on).apply()
|
||||
}
|
||||
|
||||
/** The store download engine's speed tier (stores/download/StoreDownloadTier ids); Fast unless chosen otherwise. */
|
||||
fun gameStoresSpeedTier(context: Context): String = prefs(context).getString("gameStoresSpeedTier", "fast") ?: "fast"
|
||||
|
||||
fun setGameStoresSpeedTier(context: Context, tier: String) {
|
||||
prefs(context).edit().putString("gameStoresSpeedTier", tier).apply()
|
||||
}
|
||||
|
||||
/** Which tab a signed-in store opens on when its chip is picked: [STORES_OPEN_LIBRARY] or [STORES_OPEN_STORE]. */
|
||||
fun storesOpenTab(context: Context): String =
|
||||
prefs(context).getString("storesOpenTab", STORES_OPEN_LIBRARY)?.takeIf { it == STORES_OPEN_STORE } ?: STORES_OPEN_LIBRARY
|
||||
|
||||
@@ -95,7 +89,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("storesOpenTab", if (tab == STORES_OPEN_STORE) STORES_OPEN_STORE else STORES_OPEN_LIBRARY).apply()
|
||||
}
|
||||
|
||||
/** Mature titles (the stores' own 17+/18 ratings or adult tags) in the storefront's shelves and search; off by default. Owned games always show. */
|
||||
fun storesShowMature(context: Context): Boolean = prefs(context).getBoolean("storesShowMature", false)
|
||||
|
||||
fun setStoresShowMature(context: Context, show: Boolean) {
|
||||
@@ -105,25 +98,18 @@ object SessionPrefs {
|
||||
const val STORES_OPEN_LIBRARY = "library"
|
||||
const val STORES_OPEN_STORE = "store"
|
||||
|
||||
/** The install root picked last time the Stores asked where (a StoreInstallRoot target's path); only the dialog's default, never a silent choice. */
|
||||
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
|
||||
|
||||
fun setStoresInstallTarget(context: Context, path: String) {
|
||||
prefs(context).edit().putString("storesInstallTarget", path).apply()
|
||||
}
|
||||
|
||||
/** How many store downloads run at once, 1..3; one by default (a single download already fills the link). */
|
||||
fun gameStoresParallel(context: Context): Int = prefs(context).getInt("gameStoresParallel", 1).coerceIn(1, 3)
|
||||
|
||||
fun setGameStoresParallel(context: Context, count: Int) {
|
||||
prefs(context).edit().putInt("gameStoresParallel", count.coerceIn(1, 3)).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's performance HUD (the fps box). A Deck-mode Steam session with the performance
|
||||
* overlay has Steam's own (mangoapp, from the QAM), so there the HUD is off unless turned on
|
||||
* in one - a choice kept apart from every other session's, where it stays on by default.
|
||||
*/
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), !mangoappSession(context))
|
||||
|
||||
fun setHudEnabled(context: Context, on: Boolean) {
|
||||
@@ -132,11 +118,9 @@ object SessionPrefs {
|
||||
|
||||
private fun hudKey(context: Context) = if (mangoappSession(context)) "hudDeck" else "hud"
|
||||
|
||||
/** A Steam session with Deck mode's performance overlay (mangoapp). */
|
||||
private fun mangoappSession(context: Context) =
|
||||
SessionState.mode == SessionService.MODE_STEAM && mangoapp(context)
|
||||
|
||||
/** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */
|
||||
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
||||
|
||||
fun setBackActionsInverted(context: Context, inverted: Boolean) {
|
||||
@@ -148,9 +132,6 @@ object SessionPrefs {
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
const val TOUCH_OFF = "off"
|
||||
|
||||
/** How touch drives the pointer: a touchpad (drag moves it from where it is) or direct
|
||||
* (it jumps under the finger). Auto = touchpad on the desktop, direct in Steam.
|
||||
* Off ignores touches on the guest picture; Android controls remain usable. */
|
||||
fun touchMode(context: Context): String = prefs(context).getString("touch", TOUCH_AUTO) ?: TOUCH_AUTO
|
||||
|
||||
fun setTouchMode(context: Context, mode: String) {
|
||||
@@ -161,12 +142,6 @@ object SessionPrefs {
|
||||
const val SHAPE_WIDE = "16:9"
|
||||
const val SHAPE_EXACT = "exact"
|
||||
|
||||
/**
|
||||
* The shape of the display the session presents: the panel's own (never narrower than 16:9),
|
||||
* exactly the panel's (a 4:3 or 3:2 handheld, drawn edge to edge), or a fixed 16:9. A foldable defaults to 16:9, which sits with modest bars on either of its
|
||||
* panels; the panel's own shape would fit one and leave a strip on the other, and gamescope's
|
||||
* display cannot change size once the session is up.
|
||||
*/
|
||||
private fun shapeMode(context: Context): String =
|
||||
prefs(context).getString("shape", null)
|
||||
?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO
|
||||
@@ -177,12 +152,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("osc", mode).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The imported glibc Turnip every session draws with inside the runtime - Steam, its games and
|
||||
* the desktop alike, as they run on the same GPU; "" = the driver built into the runtime.
|
||||
* Resolved by LinuxVulkanDriver at session start. It was once chosen per mode: the Steam
|
||||
* session's choice, the one nearly everyone set, carries over.
|
||||
*/
|
||||
fun linuxDriver(context: Context): String =
|
||||
prefs(context).getString("linuxDriver", null)
|
||||
?: prefs(context).getString("linuxDriver.steam", null)
|
||||
@@ -195,11 +164,6 @@ object SessionPrefs {
|
||||
const val GPU_DRIVERS_AUTO = "auto"
|
||||
const val GPU_DRIVERS_MANUAL = "manual"
|
||||
|
||||
/**
|
||||
* Who picks the GPU drivers: [GPU_DRIVERS_AUTO] (the app, the matched pair recommended for
|
||||
* this GPU, kept current - DriverPairs) or [GPU_DRIVERS_MANUAL] (the user). Auto for new
|
||||
* installs; see settleGpuDriverMode.
|
||||
*/
|
||||
fun gpuDriverMode(context: Context): String =
|
||||
prefs(context).getString("gpuDriverMode", GPU_DRIVERS_AUTO) ?: GPU_DRIVERS_AUTO
|
||||
|
||||
@@ -207,10 +171,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("gpuDriverMode", mode).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto arrived after people had picked drivers by hand: an install that chose either driver
|
||||
* keeps its choice (Manual), everyone else is Auto. Decided once, at process start.
|
||||
*/
|
||||
fun settleGpuDriverMode(context: Context) {
|
||||
val p = prefs(context)
|
||||
if (p.contains("gpuDriverMode")) return
|
||||
@@ -218,7 +178,6 @@ object SessionPrefs {
|
||||
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
|
||||
}
|
||||
|
||||
/** Drivers Auto downloaded: the only ones it removes when a newer pair replaces them. */
|
||||
fun gpuAutoInstalled(context: Context): Set<String> =
|
||||
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
|
||||
|
||||
@@ -226,9 +185,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply()
|
||||
}
|
||||
|
||||
// The Steam client's own sound has one route now: DirectAudio's engine inside the PulseAudio
|
||||
// daemon (PulseAudioComponent), one step from Android. The old "clientDirectAudio" boolean
|
||||
// (which meant the relay route, one hop more) is no longer read.
|
||||
|
||||
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
|
||||
|
||||
@@ -237,20 +193,14 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On
|
||||
* unless the user turned it off.
|
||||
*/
|
||||
fun directAudio(context: Context): Boolean = prefs(context).getBoolean("directAudio", true)
|
||||
|
||||
fun setDirectAudio(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("directAudio", on).apply()
|
||||
}
|
||||
|
||||
/** The microphone for voice chat, off until the user turns it on (which asks for RECORD_AUDIO). */
|
||||
fun micEnabled(context: Context): Boolean = prefs(context).getBoolean("mic", false)
|
||||
|
||||
/** Whether the app has already asked for the microphone once at start-up. */
|
||||
fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false)
|
||||
|
||||
fun setMicAsked(context: Context) {
|
||||
@@ -261,7 +211,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("mic", on).apply()
|
||||
}
|
||||
|
||||
/** Optional SSID reporting and scans. A Location grant alone never opts the user in. */
|
||||
fun wifiDiscoveryEnabled(context: Context): Boolean = prefs(context).getBoolean("wifiDiscovery", false)
|
||||
|
||||
fun setWifiDiscoveryEnabled(context: Context, on: Boolean) {
|
||||
@@ -276,7 +225,6 @@ object SessionPrefs {
|
||||
|
||||
internal data class CoreAllocation(val clientOverride: Boolean, val clientCpus: String, val gameCpus: String)
|
||||
|
||||
/** Defaults are read only for absent keys; even a saved empty/all-core choice wins. */
|
||||
internal fun coreAllocation(context: Context, defaults: CpuAllocationDefaults.Allocation? = CpuAllocationDefaults.device): CoreAllocation {
|
||||
val saved = prefs(context)
|
||||
return CoreAllocation(
|
||||
@@ -286,37 +234,24 @@ object SessionPrefs {
|
||||
)
|
||||
}
|
||||
|
||||
/** Use the device default until the user saves an override or a client mask. */
|
||||
fun clientCpusOverride(context: Context): Boolean = coreAllocation(context).clientOverride
|
||||
|
||||
fun setClientCpusOverride(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
|
||||
}
|
||||
|
||||
/** Comma-separated core list for the client (taskset -c syntax); "" = every core. */
|
||||
fun clientCpus(context: Context): String = coreAllocation(context).clientCpus
|
||||
|
||||
fun setClientCpus(context: Context, list: String) {
|
||||
prefs(context).edit().putString("clientCpus", list).apply()
|
||||
}
|
||||
|
||||
/** Comma-separated core list for games (taskset -c syntax); "" = every core (explicitly restored when the client is pinned). */
|
||||
fun gameCpus(context: Context): String = coreAllocation(context).gameCpus
|
||||
|
||||
fun setGameCpus(context: Context, list: String) {
|
||||
prefs(context).edit().putString("gameCpus", list).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Steam's xalia helper is kept out of the session (PROTON_USE_XALIA=0).
|
||||
*
|
||||
* xalia is an x86 Windows program Proton launches to give Windows programs gamepad navigation.
|
||||
* Under FEX it cannot load the session's aarch64 preload shim, so its socket() and memfd calls
|
||||
* reach the vendor's seccomp filter raw; where that answers ENOSYS - a Galaxy Fold, measured -
|
||||
* it storms, and the session dies seconds after Big Picture appears. On by default: where it
|
||||
* does run, it sits beside every game under FEX for nothing a controller-first session needs
|
||||
* (about 10% of a core beside Once Upon a KATAMARI on an SD 8 Gen 2).
|
||||
*/
|
||||
fun noXalia(context: Context): Boolean = prefs(context).getBoolean("noXalia", true)
|
||||
|
||||
fun setNoXalia(context: Context, on: Boolean) {
|
||||
@@ -340,10 +275,6 @@ object SessionPrefs {
|
||||
const val SYNC_FSYNC = "fsync"
|
||||
const val SYNC_WINESERVER = "wineserver"
|
||||
|
||||
/**
|
||||
* The sync Proton games use, as the three switches above decide it: droiddeck-ntsync wins
|
||||
* while it is on, then droiddeck-fsync first, then droiddeck-esync, and wineserver alone while all three are off.
|
||||
*/
|
||||
fun syncBackend(context: Context): String = syncBackendOf(fastSync(context), fsyncFirst(context), syncFallback(context))
|
||||
|
||||
fun syncBackendOf(fastSync: Boolean, fsyncFirst: Boolean, syncFallback: Boolean): String = when {
|
||||
@@ -353,7 +284,6 @@ object SessionPrefs {
|
||||
else -> SYNC_WINESERVER
|
||||
}
|
||||
|
||||
/** Picks one sync for Proton games; the switches change together, in one write. */
|
||||
fun setSyncBackend(context: Context, backend: String) {
|
||||
require(backend == SYNC_ESYNC || backend == SYNC_NTSYNC || backend == SYNC_FSYNC || backend == SYNC_WINESERVER) { "unknown sync $backend" }
|
||||
prefs(context).edit()
|
||||
@@ -369,28 +299,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("syncFallback", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether gamescope asks for realtime-priority Vulkan queues (GAMESCOPE_FORCE_VULKAN_REALTIME=1,
|
||||
* which the app's gamescope build honours without CAP_SYS_NICE). Off by default, as in
|
||||
* Bannerlator's session: the compositor's queue preempting the game's buys nothing on a device
|
||||
* whose GPU is waiting on the CPU.
|
||||
*/
|
||||
fun gamescopeRealtime(context: Context): Boolean = prefs(context).getBoolean("gamescopeRealtime", false)
|
||||
|
||||
fun setGamescopeRealtime(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("gamescopeRealtime", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether proot runs without its seccomp acceleration (PROOT_NO_SECCOMP=1).
|
||||
*
|
||||
* proot normally installs a seccomp filter so only the syscalls it must rewrite stop in the
|
||||
* tracer; everything else runs untraced, which is most of proot's speed. Where a vendor kernel
|
||||
* handles that filter badly the wrong calls are trapped or refused - ENOSYS from calls that
|
||||
* plainly exist is the signature - and the fallback is to trace everything instead: slower,
|
||||
* but correct. Max's advice for devices whose kernels "don't work well with it".
|
||||
*/
|
||||
/** Hold the GPU at its top clock during a session (GpuClockPin). Off by default: power and heat. */
|
||||
fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false)
|
||||
|
||||
fun setGpuClockPin(context: Context, on: Boolean) {
|
||||
@@ -403,11 +317,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the session's path lookups take proot's fast path (ProotFastPath): answered inside
|
||||
* each process instead of a round trip through the tracer. On by default; it needs proot's
|
||||
* seccomp filter, so it is off whenever proot runs without one.
|
||||
*/
|
||||
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
|
||||
|
||||
fun setProotFastPath(context: Context, on: Boolean) {
|
||||
@@ -430,43 +339,21 @@ object SessionPrefs {
|
||||
return trimmed.takeIf { Regex("[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?").matches(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Turnip's sysmem rendering (TU_DEBUG=sysmem) for the runtime's driver: bypasses GMEM tiling.
|
||||
* On by default, as WinNative runs every Linux session: Chromium -> ANGLE -> Zink draws the
|
||||
* client's interface as many small render passes, each paying GMEM's load/store and binning,
|
||||
* and WinNative's A/B on an Adreno 840 put a game ahead with it too (Palworld 42.8 against 41.3).
|
||||
*/
|
||||
fun tuSysmem(context: Context): Boolean = prefs(context).getBoolean("tuSysmem", true)
|
||||
|
||||
fun setTuSysmem(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("tuSysmem", on).apply()
|
||||
}
|
||||
|
||||
/*
|
||||
* The client's interface is drawn Chromium -> ANGLE -> Zink -> Turnip, and that chain is what
|
||||
* limits its menus (~14 fps on an Adreno 840 while a game ran 89). These make the chain
|
||||
* cheaper rather than asking for more; the three environment switches are on by default,
|
||||
* Deck mode off. Bannerlator's LinuxTuning, carried over; none device-proven here yet.
|
||||
*/
|
||||
/** mesa_glthread=true: GL marshalled off the calling thread. */
|
||||
fun glThread(context: Context): Boolean = prefs(context).getBoolean("glThread", true)
|
||||
fun setGlThread(context: Context, on: Boolean) { prefs(context).edit().putBoolean("glThread", on).apply() }
|
||||
|
||||
/** MESA_NO_ERROR=1: no GL error checking. */
|
||||
fun noGlError(context: Context): Boolean = prefs(context).getBoolean("noGlError", true)
|
||||
fun setNoGlError(context: Context, on: Boolean) { prefs(context).edit().putBoolean("noGlError", on).apply() }
|
||||
|
||||
/**
|
||||
* What the pad is to the Steam client: [CONTROLLER_DECK], a Steam Deck controller (Quick Access
|
||||
* button, gyro, Steam Input's full treatment - SteamDeckPad), [CONTROLLER_STEAM], a 2025 Steam
|
||||
* Controller (the same, plus grip sense and its own haptics), [CONTROLLER_DS4] or
|
||||
* [CONTROLLER_DUALSENSE], a PlayStation pad with its touchpad fed by the trackpads, or
|
||||
* [CONTROLLER_XBOX360], the plain Xbox 360 pad of earlier versions (QAM by the Guide+A chord).
|
||||
*/
|
||||
fun steamController(context: Context): String =
|
||||
prefs(context).getString("steamController", CONTROLLER_DECK) ?: CONTROLLER_DECK
|
||||
fun setSteamController(context: Context, id: String) { prefs(context).edit().putString("steamController", id).apply() }
|
||||
/** [steamController]'s choice as libfakeinput's pad type (FakeInputWriter.PAD_TYPE_*). */
|
||||
fun padType(id: String): Int = when (id) {
|
||||
CONTROLLER_STEAM -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM
|
||||
CONTROLLER_XBOX360 -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_XBOX
|
||||
@@ -475,24 +362,15 @@ object SessionPrefs {
|
||||
else -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DECK
|
||||
}
|
||||
|
||||
/**
|
||||
* Deck mode's performance overlay (mangoapp, beside gamescope): the QAM's Overlay Level draws
|
||||
* through it. Off is the way out where Valve's mangoapp crashes (one Turnip build did).
|
||||
*/
|
||||
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
|
||||
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
|
||||
|
||||
/**
|
||||
* Zink's lazy descriptor mode (ZINK_DESCRIPTORS=lazy) with its compact set layout
|
||||
* (ZINK_DEBUG=compact) for the client's GL-on-Vulkan UI, as WinNative runs it. On by default.
|
||||
*/
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
|
||||
fun setZinkLazy(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zinkLazy", on).apply()
|
||||
}
|
||||
|
||||
/** The Android driver the compositor loads: "" = pick by GPU, else a bundled or imported id. */
|
||||
@JvmStatic
|
||||
fun androidDriver(context: Context): String = prefs(context).getString("androidDriver", "") ?: ""
|
||||
|
||||
@@ -501,12 +379,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("androidDriver", id).apply()
|
||||
}
|
||||
|
||||
// ── Storage the session can see ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The folder on this device that every session shows at `/root/ROMs`, for the emulators on the
|
||||
* desktop. "" = none chosen. All of internal storage is at `/root/Storage` regardless.
|
||||
*/
|
||||
fun romsDir(context: Context): String =
|
||||
prefs(context).getString("romsDir", "") ?: ""
|
||||
|
||||
@@ -514,11 +387,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("romsDir", path).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a session keeps its folder under files/logs. Off, the same logs are kept in
|
||||
* the app's cache for the session's lifetime (the scripts need somewhere to write) and thrown
|
||||
* away at the end, so nothing accumulates in Downloads.
|
||||
*/
|
||||
fun logsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("logs", true)
|
||||
|
||||
@@ -526,7 +394,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
}
|
||||
|
||||
/** Steam storage-call diagnostics are opt-in because they add timing work to file operations. */
|
||||
fun storageDiagnosticsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("storageDiagnostics", false)
|
||||
|
||||
@@ -534,24 +401,13 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("storageDiagnostics", on).apply()
|
||||
}
|
||||
|
||||
// ── Per-mode display ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The tallest the session's display may be, in pixels, for MODE_STEAM / MODE_DESKTOP:
|
||||
* 0 = the panel's own height, otherwise a cap. Both modes default to 720p: the client's CEF
|
||||
* is the heaviest thing in a session, Big Picture is drawn for a TV at arm's length, and on
|
||||
* a handheld panel 720p is where its menus stay responsive on a regular flagship; the desktop
|
||||
* and the emulators under it get the same GPU headroom. Read once, when the session's display
|
||||
* is sized; a cap the user chose wins over the default.
|
||||
*/
|
||||
private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720)
|
||||
|
||||
/** Whether the user chose the mode's resolution (a cap or a custom size) rather than the default. */
|
||||
fun resolutionChosen(context: Context, mode: String): Boolean =
|
||||
prefs(context).contains("displayResolution.$mode") ||
|
||||
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
|
||||
|
||||
/** One per-mode choice now owns both dimensions; old caps/shapes are read only for migration. */
|
||||
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
|
||||
val saved = prefs(context)
|
||||
saved.getString("displayResolution.$mode", null)?.let { value ->
|
||||
@@ -574,24 +430,10 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("displayResolution.$mode", value).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults.
|
||||
* Performance + TSO unless chosen, WinNative's default: FEX's own defaults keep half-barrier TSO
|
||||
* and full-precision x87, which cost every x86 game time; a game that needs them can still be
|
||||
* given another preset.
|
||||
*/
|
||||
fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", DEFAULT_FEX_PRESET) ?: DEFAULT_FEX_PRESET
|
||||
|
||||
private const val DEFAULT_FEX_PRESET = "PERFORMANCE_TSO"
|
||||
|
||||
/**
|
||||
* Force SSBS for Proton games: Wine resumes threads from a Windows CONTEXT that never carries
|
||||
* PSTATE.SSBS, so they run with speculative store bypass disabled; libssbs.so keeps it set
|
||||
* (on DiRT 3 / GE-Proton: from ~99% of a game's threads running without it to none). The
|
||||
* speed-up is reported on Oryon cores (Snapdragon 8 Elite) and was not measurable on an
|
||||
* 8 Gen 3, so it is off unless turned on. A game's own environment can still say
|
||||
* DROIDDECK_FORCE_SSBS=0.
|
||||
*/
|
||||
fun forceSsbs(context: Context): Boolean = prefs(context).getBoolean("forceSsbs", false)
|
||||
|
||||
fun setForceSsbs(context: Context, on: Boolean) {
|
||||
@@ -606,18 +448,12 @@ object SessionPrefs {
|
||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) }
|
||||
}
|
||||
|
||||
/** Whether opening DroidDeck starts a Steam session instead of showing the front end. */
|
||||
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
|
||||
|
||||
fun setRunSteamAtStartup(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("runSteamAtStartup", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The Games folders earlier builds let the user add (one game per subfolder); read only by
|
||||
* GamesFolderMigration, which turns them into entries and clears them. The single folder an
|
||||
* even earlier build kept is carried in.
|
||||
*/
|
||||
fun addedGamesDirs(context: Context): List<String> {
|
||||
val p = prefs(context)
|
||||
val list = p.getString("addedGamesDirs", null)
|
||||
@@ -630,10 +466,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The Games folders earlier builds had (host path, guest path), still bound into the session so
|
||||
* their games keep their paths; written once by GamesFolderMigration.
|
||||
*/
|
||||
fun gameFolderBinds(context: Context): List<Pair<String, String>> =
|
||||
(prefs(context).getString("gameFolderBinds", "") ?: "").split('\n').mapNotNull { line ->
|
||||
line.split('\t').takeIf { it.size == 2 && it[0].isNotEmpty() && it[1].isNotEmpty() }?.let { it[0] to it[1] }
|
||||
@@ -643,17 +475,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("gameFolderBinds", binds.distinctBy { it.first }.joinToString("\n") { "${it.first}\t${it.second}" }).apply()
|
||||
}
|
||||
|
||||
/** The Games folders were turned into entries (GamesFolderMigration); a record, not a gate. */
|
||||
fun gamesFoldersMigrated(context: Context): Boolean = prefs(context).getBoolean("gamesFoldersMigrated", false)
|
||||
|
||||
fun setGamesFoldersMigrated(context: Context) {
|
||||
prefs(context).edit().putBoolean("gamesFoldersMigrated", true).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Game folders (by path) the user removed from the added games: a scan skips them, so they
|
||||
* stay off the Games tab and out of Steam until restored. Nothing on disk is touched.
|
||||
*/
|
||||
fun removedAddedGames(context: Context): List<String> =
|
||||
(prefs(context).getString("removedAddedGames", "") ?: "").split('\n').filter { it.isNotEmpty() }
|
||||
|
||||
@@ -664,31 +491,24 @@ object SessionPrefs {
|
||||
}
|
||||
}
|
||||
|
||||
/** An added game's name as the user set it (in the app, or in Steam's Properties); "" = automatic. */
|
||||
fun addedGameName(context: Context, folderPath: String): String = prefs(context).getString("addedName:$folderPath", "") ?: ""
|
||||
|
||||
fun setAddedGameName(context: Context, folderPath: String, name: String) {
|
||||
prefs(context).edit().putString("addedName:$folderPath", name.trim()).apply()
|
||||
}
|
||||
|
||||
/** An added game's Start in, as the session sees it; "" = the exe's own folder. */
|
||||
fun addedGameStartIn(context: Context, folderPath: String): String = prefs(context).getString("addedStartIn:$folderPath", "") ?: ""
|
||||
|
||||
fun setAddedGameStartIn(context: Context, folderPath: String, guestDir: String) {
|
||||
prefs(context).edit().putString("addedStartIn:$folderPath", guestDir.trim()).apply()
|
||||
}
|
||||
|
||||
/** An added game's launch options, as Steam takes them ("-dx11", "VAR=1 %command%"). */
|
||||
fun addedGameLaunch(context: Context, folderPath: String): String = prefs(context).getString("addedLaunch:$folderPath", "") ?: ""
|
||||
|
||||
fun setAddedGameLaunch(context: Context, folderPath: String, options: String) {
|
||||
prefs(context).edit().putString("addedLaunch:$folderPath", options.trim()).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The last value of [field] (AppName, StartDir, LaunchOptions) taken over from Steam's own
|
||||
* Properties for this game, so the same Steam edit is not taken again over a later app edit.
|
||||
*/
|
||||
fun addedGameAdopted(context: Context, folderPath: String, field: String): String? =
|
||||
prefs(context).getString("addedAdopted:$field:$folderPath", null)
|
||||
|
||||
@@ -696,7 +516,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("addedAdopted:$field:$folderPath", value).apply()
|
||||
}
|
||||
|
||||
/** Where an added game's art for [slot] comes from when the user chose it ("folder", "steam", "sgdb", "file"); "" = automatic. */
|
||||
fun addedGameArtSource(context: Context, folderPath: String, slot: String): String =
|
||||
prefs(context).getString("addedArt:$slot:$folderPath", "") ?: ""
|
||||
|
||||
@@ -704,14 +523,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("addedArt:$slot:$folderPath", source).apply()
|
||||
}
|
||||
|
||||
/** Whether added games without art of their own get Steam's store art fetched for them. */
|
||||
fun addedGamesArt(context: Context): Boolean = prefs(context).getBoolean("addedGamesArt", true)
|
||||
|
||||
fun setAddedGamesArt(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("addedGamesArt", on).apply()
|
||||
}
|
||||
|
||||
/** The .exe the user chose for one game folder (by its path), "" = the scanner's pick. */
|
||||
fun addedGameExe(context: Context, folderPath: String): String = prefs(context).getString("addedExe:$folderPath", "") ?: ""
|
||||
|
||||
private val addedGameLock = Any()
|
||||
@@ -729,7 +546,6 @@ object SessionPrefs {
|
||||
unchanged
|
||||
}
|
||||
|
||||
/** The shortcut appid stored for the folder, or null before its first scan. */
|
||||
fun addedGameStoredAppId(context: Context, folderPath: String): Long? =
|
||||
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
|
||||
|
||||
@@ -739,21 +555,15 @@ object SessionPrefs {
|
||||
?: first.also { p.edit().putLong("addedAppId:$folderPath", it).apply() }
|
||||
}
|
||||
|
||||
/** The app's colour theme (ui/Themes ids); Graphite unless chosen otherwise. */
|
||||
fun theme(context: Context): String = prefs(context).getString("theme", "graphite") ?: "graphite"
|
||||
|
||||
fun setTheme(context: Context, id: String) {
|
||||
prefs(context).edit().putString("theme", id).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* A fixed size for the session's display, per mode, or null. When set it replaces both the
|
||||
* cap and the shape: the compositor fits it to the panel with bars where the shapes differ.
|
||||
*/
|
||||
private fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
|
||||
parseResolution(prefs(context).getString("customRes.$mode", null))
|
||||
|
||||
/** "1024x768" (or ×, or *) to an even size inside 320x240..3840x2160; anything else is null. */
|
||||
fun parseResolution(text: String?): Pair<Int, Int>? {
|
||||
val parts = text?.trim()?.split('x', 'X', '×', '*')?.map { it.trim() } ?: return null
|
||||
if (parts.size != 2) return null
|
||||
@@ -763,25 +573,12 @@ object SessionPrefs {
|
||||
return Pair(w and 1.inv(), h and 1.inv())
|
||||
}
|
||||
|
||||
/**
|
||||
* HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel
|
||||
* lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app
|
||||
* process: a change applies after the app is fully closed and opened again.
|
||||
*/
|
||||
fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean("hdr.$mode", false)
|
||||
|
||||
fun setHdr(context: Context, mode: String, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's frame cap, 0 for none. One number used everywhere a frame is paced: gamescope's
|
||||
* -r (what the client and its games see as the display's rate), the compositor's buffer release
|
||||
* pacer, the rate the display layer votes for, and the panel mode picked, which is the fastest
|
||||
* one the cap divides evenly (40 on a 120 Hz panel, not on a 144 Hz one). A 60 fps cap on a
|
||||
* 144 Hz panel with nothing else changed judders; this is what WinNative's per-shortcut limit
|
||||
* does. Applies next session.
|
||||
*/
|
||||
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0)
|
||||
|
||||
fun setFpsLimit(context: Context, mode: String, fps: Int) {
|
||||
@@ -790,28 +587,19 @@ object SessionPrefs {
|
||||
|
||||
val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120")
|
||||
|
||||
/** [fpsLimitChoices] labelled in the app's language. */
|
||||
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 }
|
||||
|
||||
/**
|
||||
* How the compositor resizes the session onto the panel (WaylandCompositor.nativeSetUpscaler's
|
||||
* modes). Linear is the default; Nearest preserves hard pixel edges. Spatial filters work
|
||||
* when enlarged; Sharpen only works at any size. The old Off/Linear and FSR/FSR Fit pairs
|
||||
* are equivalent on Wayland, so saved aliases resolve to one choice.
|
||||
*/
|
||||
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",
|
||||
)
|
||||
|
||||
/** The [upscalerChoices] labels that are words rather than product names. */
|
||||
private val upscalerLabels = mapOf(
|
||||
0 to R.string.sprefs_upscaler_linear, 2 to R.string.sprefs_upscaler_nearest,
|
||||
8 to R.string.sprefs_upscaler_gsr_quality, 6 to R.string.sprefs_upscaler_sharpen,
|
||||
)
|
||||
|
||||
/** [upscalerChoices] labelled in the app's language; the English list stays for the device report. */
|
||||
fun upscalerChoices(context: Context): List<Pair<Int, String>> =
|
||||
upscalerChoices.map { (mode, label) -> mode to (upscalerLabels[mode]?.let(context::getString) ?: label) }
|
||||
|
||||
@@ -835,9 +623,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("upscaleSharpness", pct.coerceIn(0, 100)).apply()
|
||||
}
|
||||
|
||||
// ── Screen effects and texture filtering (the Display page) ─────────────────────────────
|
||||
|
||||
/** The compositor's post chain as last set; off until the user picks a Look or moves a row. */
|
||||
fun screenEffects(context: Context): ScreenEffects {
|
||||
val text = prefs(context).getString("screenEffects", null) ?: return ScreenEffects.OFF
|
||||
return runCatching { ScreenEffects.decode(JSONObject(text)) }.getOrDefault(ScreenEffects.OFF)
|
||||
@@ -847,10 +633,8 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("screenEffects", effects.encode().toString()).apply()
|
||||
}
|
||||
|
||||
/** The key [cardboard] lives under; SessionActivity watches it so a change applies live. */
|
||||
const val CARDBOARD_KEY = "cardboard"
|
||||
|
||||
/** Cardboard mode (gpu/Cardboard) as last set; off by default. */
|
||||
fun cardboard(context: Context): Cardboard {
|
||||
val text = prefs(context).getString(CARDBOARD_KEY, null) ?: return Cardboard.OFF
|
||||
return runCatching { Cardboard.decode(JSONObject(text)) }.getOrDefault(Cardboard.OFF)
|
||||
@@ -860,21 +644,16 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString(CARDBOARD_KEY, cardboard.encode().toString()).apply()
|
||||
}
|
||||
|
||||
/** The Cardboard picture (Cardboard.SOURCE_*) to go back to once SteamVR stops; -1 = none (it was
|
||||
* not switched for SteamVR). Kept across activity restarts, so a SteamVR session that outlives the
|
||||
* activity still hands the picture back. */
|
||||
fun cardboardSourceBeforeSteamVr(context: Context): Int = prefs(context).getInt("cardboardSourceBeforeSteamVr", -1)
|
||||
|
||||
fun setCardboardSourceBeforeSteamVr(context: Context, source: Int) {
|
||||
prefs(context).edit().putInt("cardboardSourceBeforeSteamVr", source).apply()
|
||||
}
|
||||
|
||||
/** The prefs file [cardboard] lives in, for a change listener. */
|
||||
fun sessionPrefs(context: Context): android.content.SharedPreferences = prefs(context)
|
||||
|
||||
val textureAnisotropyChoices = TextureFiltering.ANISOTROPY.map { it to if (it == 0) "Off" else "${it}x" }
|
||||
|
||||
/** [textureAnisotropyChoices] labelled in the app's language. */
|
||||
fun textureAnisotropyChoices(context: Context): List<Pair<Int, String>> =
|
||||
textureAnisotropyChoices.map { (value, label) -> value to if (value == 0) context.getString(R.string.frame_gen_off) else label }
|
||||
|
||||
@@ -886,7 +665,6 @@ object SessionPrefs {
|
||||
}
|
||||
}
|
||||
|
||||
/** [textureLodBiasChoices] labelled in the app's language. */
|
||||
fun textureLodBiasChoices(context: Context): List<Pair<String, String>> = textureLodBiasChoices.map { (value, label) ->
|
||||
value to when (value) {
|
||||
TextureFiltering.LOD_BIAS_OFF -> context.getString(R.string.frame_gen_off)
|
||||
@@ -895,7 +673,6 @@ object SessionPrefs {
|
||||
}
|
||||
}
|
||||
|
||||
/** Anisotropic filtering forced on DirectX 9-11 games (core/TextureFiltering); 0 = the game's own. */
|
||||
fun textureAnisotropy(context: Context): Int =
|
||||
prefs(context).getInt("textureAnisotropy", 0).takeIf { it in TextureFiltering.ANISOTROPY } ?: 0
|
||||
|
||||
@@ -904,7 +681,6 @@ object SessionPrefs {
|
||||
publishGameEnvironment(context)
|
||||
}
|
||||
|
||||
/** Texture sharpness: the mip LOD bias choice (TextureFiltering.LOD_BIAS), "0" = the game's own. */
|
||||
fun textureLodBias(context: Context): String =
|
||||
prefs(context).getString("textureLodBias", null)?.takeIf { it in TextureFiltering.LOD_BIAS } ?: TextureFiltering.LOD_BIAS_OFF
|
||||
|
||||
@@ -981,16 +757,11 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("gameTextureFiltering", json.toString()).apply()
|
||||
}
|
||||
|
||||
/** Hands the change to the next game launch (GameEnvironmentStore); the running game keeps its own. */
|
||||
private fun publishGameEnvironment(context: Context) {
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a
|
||||
* fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices.
|
||||
*/
|
||||
fun prefMode(mode: String): String = if (mode == SessionService.MODE_RUN) SessionService.MODE_STEAM else mode
|
||||
|
||||
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
|
||||
@@ -999,7 +770,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
|
||||
}
|
||||
|
||||
/** A foldable's unfolded panel shows the game above the Deck controls (SessionDisplay.unfoldedGameHeight). */
|
||||
fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false)
|
||||
|
||||
fun setUnfoldedControls(context: Context, enabled: Boolean) {
|
||||
@@ -1009,8 +779,6 @@ object SessionPrefs {
|
||||
const val SURFACE_STICK = "stick"
|
||||
const val SURFACE_TRACKPAD = "trackpad"
|
||||
|
||||
/** The Deck controls' gamepad tab: what each side is - an analog stick or a Steam trackpad.
|
||||
* Left a stick and right a trackpad until changed, as a Deck is mostly played. */
|
||||
fun gamepadSurface(context: Context, right: Boolean): String =
|
||||
prefs(context).getString(if (right) "gamepadRight" else "gamepadLeft", null)
|
||||
?: if (right) SURFACE_TRACKPAD else SURFACE_STICK
|
||||
@@ -1023,7 +791,6 @@ object SessionPrefs {
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
|
||||
?.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_NATIVE, SUSPEND_MANUAL, SUSPEND_NEVER) }
|
||||
// Direct games share Steam's settings but have no Steam client to prepare.
|
||||
?.let { if (mode != SessionService.MODE_STEAM && it == SUSPEND_NATIVE) SUSPEND_AUTO else it }
|
||||
?: SUSPEND_MANUAL
|
||||
|
||||
@@ -1058,7 +825,6 @@ object SessionPrefs {
|
||||
}.apply()
|
||||
}
|
||||
|
||||
/** Steam only: the client's memory goes to the device's zram while a game runs (ZramSupport). */
|
||||
fun zramCompression(context: Context): Boolean {
|
||||
val prefs = prefs(context)
|
||||
return if (prefs.contains("zramCompression")) prefs.getBoolean("zramCompression", false) else ZramSupport.recommended(context)
|
||||
@@ -1068,15 +834,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("zramCompression", on).apply()
|
||||
}
|
||||
|
||||
// ── Game storage ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A second Steam library on this device: the folder bound at /mnt/droiddeck-sd and
|
||||
* registered with the client, which then asks where to install every game and shows both
|
||||
* on its Storage page. "" = automatic: the SD card when one is in the phone (the default,
|
||||
* so the choice is made inside the client like anywhere else); GAME_STORAGE_OFF = internal
|
||||
* only; otherwise the folder chosen.
|
||||
*/
|
||||
fun gameStorage(context: Context): String = prefs(context).getString("gameStorage", "") ?: ""
|
||||
|
||||
const val GAME_STORAGE_OFF = "off"
|
||||
|
||||
@@ -50,32 +50,16 @@ import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Owns the running session: the proot tree, the audio daemon, the network link and the locks that
|
||||
* keep all three alive while the app is not on screen.
|
||||
*
|
||||
* The session deliberately does **not** belong to the activity. Android demotes a process the
|
||||
* moment it loses its last visible activity, and the low-memory killer then reaps the guest - so
|
||||
* leaving Big Picture to answer a message would come back to a dead Steam. A foreground service
|
||||
* holds the process at perceptible priority, a partial wake lock keeps the CPU from dropping the
|
||||
* guest's threads, and a high-performance WiFi lock keeps the radio out of power-save so a
|
||||
* backgrounded download does not throttle to nothing. All three are Bannerlator's recipe, where
|
||||
* each was added to fix a failure seen on a device.
|
||||
*
|
||||
* The activity comes and goes on top of this; see [com.droiddeck.launcher.wayland.CompositorHost].
|
||||
*/
|
||||
class SessionService : Service() {
|
||||
override fun attachBaseContext(newBase: android.content.Context) =
|
||||
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(newBase))
|
||||
|
||||
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
|
||||
/** The Steam Deck controller's sysfs binds (SteamDeckPad), when this session has one. */
|
||||
private var deckBinds: List<String> = emptyList()
|
||||
private val stopLock = Any()
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
private var wifiLock: WifiManager.WifiLock? = null
|
||||
private var sessionPid = -1
|
||||
/** Auxiliary PTY-backed proot shells launched from a secondary-display terminal. */
|
||||
private val auxiliaryProcesses = HashMap<Int, Long>()
|
||||
private val auxiliaryProcessesLock = Any()
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
@@ -89,7 +73,6 @@ class SessionService : Service() {
|
||||
private var activityVisible = true
|
||||
private var screenOn = true
|
||||
private var manualPauseRequested = false
|
||||
/** An explicit Steam sleep request is independent of the background policy. */
|
||||
private var steamSleepToken: String? = null
|
||||
private var nativeSleepToken: String? = null
|
||||
private var nativeSleepReady = false
|
||||
@@ -98,7 +81,6 @@ class SessionService : Service() {
|
||||
private var suspendOperationPending = false
|
||||
private var pipTask = false
|
||||
private var suspendAttemptFailed = false
|
||||
/** One validated game request waiting for this Steam session to reach a usable state. */
|
||||
private var pendingSteamGameId: String? = null
|
||||
private var pendingSteamGameGeneration = -1
|
||||
private val flushSteamGame = object : Runnable {
|
||||
@@ -117,7 +99,6 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
}
|
||||
/** Counts sessions this service has started; a process exit from an earlier one is ignored. */
|
||||
@Volatile private var sessionGen = 0
|
||||
|
||||
override fun onCreate() {
|
||||
@@ -246,47 +227,26 @@ class SessionService : Service() {
|
||||
stopSession(0)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
// Another Steam client on the device signs ours out seconds after every login; the one that
|
||||
// does it here runs from boot without being opened. Only the Steam session signs in.
|
||||
// The desktop too: its Steam launchers run the client right there (droiddeck-steam-launch).
|
||||
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) RivalClients.stopBeforeSession(this)
|
||||
SessionState.firstFrameSeen = false
|
||||
SessionState.guestPid = -1
|
||||
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
|
||||
// Re-arm after clearing readiness: a retained picture can present between the activity's
|
||||
// start request and this callback, and that notice must not be erased by the reset above.
|
||||
com.droiddeck.launcher.wayland.CompositorHost.newSession()
|
||||
// This session's number, claimed here and not when its process starts: the session it
|
||||
// replaces can report its own exit in the gap between the two, and that exit must not
|
||||
// be taken as this one's.
|
||||
val gen = ++sessionGen
|
||||
cancelQueuedSteamGame(clearMailbox = false)
|
||||
clearSteamGameMailbox()
|
||||
acquireLocks()
|
||||
Thread({
|
||||
// A tree the last session left behind (the app was killed or crashed, so its teardown
|
||||
// never ran) would hold the rootfs, the GPU and Steam's lock: nothing of ours should
|
||||
// be alive between sessions outside this process.
|
||||
OrphanReaper.reap("session starting")
|
||||
runSession(gen)
|
||||
}, "session-start").start()
|
||||
// The activity or the notification stops us; the system must not resurrect a session whose
|
||||
// guest processes are long gone.
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish the session's folder after the session has stopped, then let go of it. The guest
|
||||
* script copies Steam's logs too, at a clean exit; this runs whatever killed the session,
|
||||
* which is when they matter. The collecting itself is [SessionArtifacts], shared with the
|
||||
* crash handler and the next-start sweep so a folder is finished whichever way it ends.
|
||||
*/
|
||||
private fun collectSessionArtifacts(dir: File) {
|
||||
try {
|
||||
SessionArtifacts.collect(this, dir, "session stopped")
|
||||
} finally {
|
||||
// Last, so everything above is in the file it is about - and only this session's:
|
||||
// a session that replaced this one may already own the capture and the folder.
|
||||
SessionLogCapture.stopFor(dir)
|
||||
SessionPaths.release(this, dir)
|
||||
}
|
||||
@@ -315,7 +275,6 @@ class SessionService : Service() {
|
||||
return if (name.contains("710-720") || name.contains("710_720")) "sysmem" else null
|
||||
}
|
||||
|
||||
// ── The session ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private fun runSession(gen: Int) {
|
||||
SessionTerminal.clear()
|
||||
@@ -333,7 +292,6 @@ class SessionService : Service() {
|
||||
killStragglers()
|
||||
SessionFiles.stage(this, root)
|
||||
com.droiddeck.launcher.agent.AgentGuest.reset(this)
|
||||
// The compat tool asks for an Epic game's sign-in code at every launch, the client's Play button included.
|
||||
com.droiddeck.launcher.stores.gog.GogComet.begin()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.start(this)
|
||||
|
||||
@@ -344,31 +302,21 @@ class SessionService : Service() {
|
||||
|
||||
val size = SessionState.outputSize
|
||||
val guest = ArrayList<String>()
|
||||
// The desktop's Steam launchers start the client there (droiddeck-steam-launch), through the
|
||||
// same set-up as a Steam session: it gets what the client and its games are started with.
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
// Some GPUs need a component Proton does not ship. Apply those before the guest, so the
|
||||
// next game launch copies them into the prefix. A download failure is logged and the
|
||||
// session still starts; the next session tries again.
|
||||
if (steamHere) {
|
||||
runCatching { ComponentsManager.ensureForcedPackages(this) }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
.onFailure { Log.w(TAG, "forced components", it) }
|
||||
}
|
||||
addClientEnvironment(guest, steamHere)
|
||||
// Where the fast path's description of proot's view goes, once the binds are known.
|
||||
val fastPathAt = guest.size
|
||||
|
||||
val pulse = startAudio(guest, sessionDir)
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
// Follow screen: the output is resized under gamescope when a foldable opens or closes,
|
||||
// and the session script asks gamescope to resize Steam's X screen along with it.
|
||||
if (SessionState.followScreen) guest.add("BL_FOLLOW_OUTPUT=1")
|
||||
if (SessionState.hdr) {
|
||||
// The activity opened the compositor's HDR gate: gamescope offers HDR to its clients
|
||||
// and DXVK takes the HDR10 swapchain when a game asks for one.
|
||||
guest.add("BL_HDR=1")
|
||||
guest.add("DXVK_HDR=1")
|
||||
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
|
||||
@@ -384,12 +332,8 @@ class SessionService : Service() {
|
||||
deckBinds = emptyList()
|
||||
if (controllersOn) {
|
||||
addControllerEnvironment(guest, fakeInputDir, sessionDir)
|
||||
// Steam enumerates /dev/input while it starts. Make every attached controller's
|
||||
// discovery node exist after the rings and guest environment are ready.
|
||||
SessionState.padBridge?.syncConnectedControllers()
|
||||
}
|
||||
// The user's own games, for the runtime's shortcuts writer to put in the client's library
|
||||
// before the client starts (see frontend/AddedGames and droiddeck-steam-shortcuts).
|
||||
if (steamHere) {
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
|
||||
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
|
||||
@@ -398,9 +342,7 @@ class SessionService : Service() {
|
||||
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1")
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
// Where the guest leaves a request for another session (the desktop's Steam launchers).
|
||||
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
|
||||
// The second library's name, for droiddeck-steam-library; the bind itself is made below.
|
||||
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
|
||||
val shellGuest = ArrayList(guest).apply {
|
||||
@@ -416,13 +358,7 @@ class SessionService : Service() {
|
||||
guest.add(it)
|
||||
Log.i(TAG, "steam: handing the client $it")
|
||||
}
|
||||
// A game whose download finishes in this session gets its Windows components readied in it.
|
||||
if (SessionState.mode == MODE_STEAM) com.droiddeck.launcher.frontend.SessionInstalls.watch(this)
|
||||
// A program under gamescope: the script's run mode takes the path (an AppImage, a script
|
||||
// or a binary inside the runtime). This is how an emulator gets the GPU - the desktop's
|
||||
// KWin composites in software and offers no dma-buf, so a Vulkan swapchain cannot exist
|
||||
// there (RPCS3 died with VK_ERROR_SURFACE_LOST); gamescope's Xwayland is the path the
|
||||
// Steam games already render through.
|
||||
if (SessionState.mode == MODE_RUN) {
|
||||
val program = SessionState.program
|
||||
if (program.isNullOrEmpty()) {
|
||||
@@ -435,12 +371,9 @@ class SessionService : Service() {
|
||||
Log.i(TAG, "run: $program (${SessionState.programArgs.size} arguments) under gamescope")
|
||||
}
|
||||
|
||||
// Android has no /dev/shm; the cache stands in for it and, unlike the real thing, keeps
|
||||
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
|
||||
FileUtils.clear(File(cacheDir, "shm"))
|
||||
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir)
|
||||
// The fast path is told exactly the rootfs and binds proot is given (ProotFastPath).
|
||||
val fastPathKey = if (ProotFastPath.enabled(this)) {
|
||||
val prootBinds = LinuxRuntime.binds(
|
||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds,
|
||||
@@ -464,10 +397,6 @@ class SessionService : Service() {
|
||||
val hostEnv = HostEnvironment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
||||
hostEnv["PROOT_TMP_DIR"] = cacheDir.path
|
||||
// proot links against a libtalloc beside it, and Android's linker does not search an
|
||||
// executable's own directory: unnamed, the process dies before it starts and says so only
|
||||
// in `logcat -b crash`.
|
||||
// proot reads this itself, so it belongs in proot's own environment rather than the guest's.
|
||||
if (SessionPrefs.prootNoSeccomp(this)) {
|
||||
hostEnv["PROOT_NO_SECCOMP"] = "1"
|
||||
Log.i(TAG, "proot: seccomp acceleration off by request")
|
||||
@@ -488,8 +417,6 @@ class SessionService : Service() {
|
||||
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
|
||||
}
|
||||
|
||||
// Whether the client signs in to Valve or starts offline: read once, while it starts, and
|
||||
// rewritten by the client when it exits, so it is set again here at every session start.
|
||||
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
|
||||
|
||||
val networkLink = LinuxNetworkLinkComponent(this, root)
|
||||
@@ -509,10 +436,6 @@ class SessionService : Service() {
|
||||
watchLaunchRequests(sessionRoot)
|
||||
watchSyncWanted(root)
|
||||
EsyncPacks.fetchInBackground(this, root)
|
||||
// One session replacing another (the desktop's Steam launchers): the old proot is killed
|
||||
// by the teardown a second after the new one has started, and its exit used to arrive
|
||||
// here as "session ended: 137" and end the NEW session. An exit belongs to the session
|
||||
// that started it.
|
||||
val pid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
|
||||
if (gen != sessionGen) {
|
||||
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
|
||||
@@ -561,10 +484,7 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
/** The session's own log folder, opened and filled with what is known before anything starts. */
|
||||
private fun openSessionFolder(): File {
|
||||
// One folder per session, claimed by whoever started first - the activity starts the
|
||||
// compositor before this service runs - so the compositor's log lands in the same place.
|
||||
val sessionDir = SessionPaths.beginOrCurrent(this)
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
SessionState.logFile = sessionLog
|
||||
@@ -572,155 +492,91 @@ class SessionService : Service() {
|
||||
SessionState.sessionId = sessionDir.name
|
||||
SessionState.eventsFile = File(sessionDir, "events.jsonl")
|
||||
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
|
||||
// Written first, so a session that dies in its first second still says what it ran on.
|
||||
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
|
||||
NetworkReport.write(this, File(sessionDir, "network.txt"))
|
||||
// Everything the app decides from here on - the driver it chose, the audio line, a rival
|
||||
// client stopped, the exit status - reaches logcat and nowhere a user can get at. Mirror it.
|
||||
SessionLogCapture.start(File(sessionDir, "app.log"))
|
||||
return sessionDir
|
||||
}
|
||||
|
||||
/** The guest's base environment: paths, the display, the GL/Vulkan stack and the client's switches. */
|
||||
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean) {
|
||||
guest.add("/usr/bin/env")
|
||||
guest.add("-i")
|
||||
// PRoot executes guest[0] directly; assignments belong after env -i.
|
||||
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
|
||||
guest.add("HOME=/root")
|
||||
guest.add("USER=root")
|
||||
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
|
||||
guest.add("TERM=xterm-256color")
|
||||
guest.add("LANG=C.UTF-8")
|
||||
// Steam's interface language: the app's (Setup's choice, or the system's). The system's
|
||||
// region decides between Spain's and Latin American Spanish, which the app has one of.
|
||||
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
|
||||
com.droiddeck.launcher.core.AppLanguage.effective(this),
|
||||
com.droiddeck.launcher.core.AppLanguage.system(this).country,
|
||||
))
|
||||
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
|
||||
// session bundle sit hours off the device's. Bannerlator carries the same line.
|
||||
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
|
||||
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
||||
guest.add("XDG_SESSION_TYPE=wayland")
|
||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||
guest.add("BL_ANDROID_CLIPBOARD=" + File(filesDir, "session/android-clipboard").path)
|
||||
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
|
||||
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
|
||||
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
|
||||
guest.add("GALLIUM_DRIVER=zink")
|
||||
guest.add("LIBGL_KOPPER_DRI2=true")
|
||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
// An imported glibc Turnip, when one is set (by the user, or by Auto): the session script
|
||||
// checks the manifest and its library from inside and points the loader at it with
|
||||
// VK_DRIVER_FILES, so the runtime's own driver above stays untouched and is what a bad
|
||||
// import falls back to. One driver for every session: the driver's shader cache is keyed on
|
||||
// its build, and with one per mode every emulator compiled its shaders twice.
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this)
|
||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
|
||||
// Downloads holds the value verbatim ("sysmem", "sysmem,deck_emu"); with nothing there, an
|
||||
// imported driver from the A710/A720/A722 legs gets "sysmem" on its own, which is what both
|
||||
// its authors advise for those GPUs and what nothing else in the list needs.
|
||||
tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
|
||||
// Zink renders the client's UI (Chromium -> ANGLE -> Zink -> Turnip). Lazy descriptors is
|
||||
// the mode Zink recommends where the driver has no descriptor buffer, and what Ludashi ships
|
||||
// by default for its Zink path; a switch here because on one Fold the menus run at 14 fps.
|
||||
// compact packs Zink's descriptor sets into fewer, so a draw binds less (WinNative's default).
|
||||
if (SessionPrefs.zinkLazy(this)) {
|
||||
guest.add("ZINK_DESCRIPTORS=lazy")
|
||||
guest.add("ZINK_DEBUG=compact")
|
||||
}
|
||||
// The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling
|
||||
// thread and no GL error checks.
|
||||
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
|
||||
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
||||
// Mesa's shader cache as one database instead of a file per entry. Every lookup in the
|
||||
// file cache is an open and every store an open and a rename, each a proot stop (a rename
|
||||
// two), for every pipeline DXVK, vkd3d-proton and Zink compile or find; the database is
|
||||
// opened once and read and written with pread/pwrite, which proot never sees. Mesa removes
|
||||
// the old folder itself once it has gone a week untouched.
|
||||
guest.add("MESA_DISK_CACHE_DATABASE=1")
|
||||
// glibc's per-thread rseq registration is refused by Android's app seccomp policy, so
|
||||
// every thread start paid a SIGSYS that proot answers; the malloc top pad grows the heap
|
||||
// 16 MB at a time instead of 128 KB, and every brk(2) is a proot stop too.
|
||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
||||
}
|
||||
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
|
||||
// XALIA_SUPPORTED_ONLY itself otherwise). Skipped by default: under FEX it costs every game
|
||||
// a slice of a core for gamepad navigation the session already has.
|
||||
if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0")
|
||||
guest.add("BL_SYNC=" + (if (SessionPrefs.fastSync(this)) "1" else "0"))
|
||||
guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0"))
|
||||
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
|
||||
// gamescope's realtime Vulkan queues (the session script turns this into
|
||||
// GAMESCOPE_FORCE_VULKAN_REALTIME); off unless the user turns it on.
|
||||
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM && SessionPrefs.zramCompression(this) &&
|
||||
com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
|
||||
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
|
||||
// Anything else, for a device that cannot be reached with a debugger: droiddeck-env in the
|
||||
// app's own external files (envSwitchFile) holds KEY=VALUE lines that go into the session's
|
||||
// environment as written, after ours, so a line here wins. Zink and Turnip tunables
|
||||
// (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's, the client's - whatever the experiment
|
||||
// needs, without a build per attempt.
|
||||
extraEnv().forEach { guest.add(it) }
|
||||
// The agent bridge's experiment lines (AgentEnv), after the user's so an agent's win.
|
||||
com.droiddeck.launcher.agent.AgentEnv.beginSession(this).forEach { guest.add(it) }
|
||||
// A game launched by pinned Steam inherits its mask. Explicitly restore all game cores
|
||||
// when requested, as well as applying restricted game choices in the Proton wrapper.
|
||||
val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this)
|
||||
if (clientPinned) {
|
||||
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
|
||||
}
|
||||
// The game cores also pin the desktop and a program from the rail; without a choice the
|
||||
// session script picks every core but the slowest cluster for those (program_cores).
|
||||
CpuCores.gameLaunchList(SessionPrefs.gameCpus(this), clientPinned)
|
||||
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
||||
}
|
||||
|
||||
/** PulseAudio, and the DirectAudio relay when a path needs it; returns the daemon for suspend and resume. */
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
|
||||
// PulseAudio always: the client is a native Linux program and has no other way to make a
|
||||
// sound - its menus, its music and its voice chat all go through here. DirectAudio is not
|
||||
// an alternative to it on this path: it replaces the audio driver INSIDE Wine, so it
|
||||
// changes what games do and leaves the client alone. The microphone is its own opt-in on
|
||||
// top, and the helper only opens an input stream when asked - so a user who wants game
|
||||
// sound but no recording gets exactly that, and Android's recording indicator stays off.
|
||||
// The desktop starts Windows programs through the same Proton wrappers (droiddeck-proton-run).
|
||||
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) &&
|
||||
SessionPrefs.directAudio(this)
|
||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
// Both paths sit under the app's files directory, which the session binds at its own path,
|
||||
// so the same string is valid on both sides and nothing has to be translated.
|
||||
val audioDir = File(filesDir, "directaudio").apply { mkdirs() }
|
||||
val relaySocket = File(audioDir, "relay.sock")
|
||||
val micFifo = if (wantsMic) File(audioDir, "mic.fifo") else null
|
||||
|
||||
val audioLog = File(sessionDir, "audio.log")
|
||||
val pulse = PulseAudioComponent(this, micFifo?.absolutePath)
|
||||
// The client's own sound: DirectAudio's engine inside the daemon, one step from Android (the
|
||||
// daemon runs on the Android side). The relay below is for games and the microphone only.
|
||||
pulse.setLogFile(audioLog)
|
||||
pulse.attach(this)
|
||||
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
|
||||
components.add(pulse)
|
||||
if (wantsDirectAudio || wantsMic) {
|
||||
// After the daemon in the list, so it can wait for the pipe the daemon makes.
|
||||
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
|
||||
relay.setLogFile(audioLog)
|
||||
relay.attach(this)
|
||||
components.add(relay)
|
||||
}
|
||||
if (wantsDirectAudio) {
|
||||
// Read by the Proton wrappers, which point Wine at the driver and name it in the
|
||||
// prefix. Absent, they take an early return and the game uses Proton's own audio - so
|
||||
// this variable is the whole of the selection.
|
||||
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
|
||||
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
|
||||
}
|
||||
@@ -730,11 +586,8 @@ class SessionService : Service() {
|
||||
return pulse
|
||||
}
|
||||
|
||||
/** The fake evdev pads: the ring files the app writes and the identity SDL and Steam see. */
|
||||
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
|
||||
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
|
||||
// Virtual pads a client made last session (event16 and up, and their hidden rings) are
|
||||
// not there any more; a client that crashed never took its own down.
|
||||
fakeInputDir.listFiles()?.forEach { file ->
|
||||
val node = Regex("event(\\d+)").matchEntire(file.name)?.groupValues?.get(1)?.toIntOrNull()
|
||||
if (file.name.startsWith(".uinput-") || (node != null && node >= FIRST_VIRTUAL_PAD)) file.delete()
|
||||
@@ -742,24 +595,13 @@ class SessionService : Service() {
|
||||
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
|
||||
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
|
||||
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
|
||||
// SDL and Steam key their mapping database on bus+vendor+product: only a known
|
||||
// identity gets the standard layout without the user configuring the pad by hand.
|
||||
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
|
||||
guest.add("FAKE_EVDEV_VIBRATION=1")
|
||||
val uinput = !File(Environment.getExternalStorageDirectory(), NO_UINPUT_SWITCH).exists()
|
||||
// In Steam, the pad is what a Deck's is: a Steam Deck controller the client reads over
|
||||
// hidraw (SteamDeckPad), which only works with Steam Input's virtual pad for games to read.
|
||||
// Decided only once its sysfs is in place: without it the client would find no Deck, and
|
||||
// with the Deck asked for the pad's own nodes are withdrawn - no controller at all.
|
||||
// Set up whatever the pad is to be, so the drawer can switch it between a Deck, a Steam
|
||||
// Controller and an Xbox 360 pad while the session runs (FakeInputWriter.setPadType).
|
||||
val wantsDeck = uinput && SessionState.mode == MODE_STEAM &&
|
||||
SessionState.steamUi != "desktop" &&
|
||||
!File(Environment.getExternalStorageDirectory(), NO_DECK_PAD_SWITCH).exists()
|
||||
// Steam's touch controller rides on the Deck's sysfs and is offered only beside it.
|
||||
val wantsTouch = wantsDeck && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
|
||||
// A paired Triton is exposed as a second native Steam Controller HID, with its original
|
||||
// report IDs and output path, beside whatever the handheld's own pad is.
|
||||
val wantsTriton = wantsDeck && SteamControllerBle.hasPairedController(this)
|
||||
deckBinds = if (wantsDeck) SteamDeckPad.prepare(this, fakeInputDir.parentFile!!.parentFile!!, wantsTouch, wantsTriton,
|
||||
SessionPrefs.padType(SessionPrefs.steamController(this))) else emptyList()
|
||||
@@ -767,43 +609,29 @@ class SessionService : Service() {
|
||||
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
|
||||
logControllersAtStart()
|
||||
if (uinput) {
|
||||
// /dev/uinput, stood in for by libfakeinput: the virtual pad Steam Input makes for a
|
||||
// game becomes a node the game reads, carrying the player's layout, as on a Deck.
|
||||
guest.add("FAKE_EVDEV_UINPUT=1")
|
||||
if (SessionState.deckPad) {
|
||||
guest.add("FAKE_EVDEV_DECK=1")
|
||||
if (wantsTriton) guest.add("FAKE_EVDEV_TRITON=1")
|
||||
// What the pad starts as; the drawer's changes reach libfakeinput through the ring.
|
||||
val padType = SessionPrefs.steamController(this)
|
||||
guest.add("FAKE_EVDEV_PAD_TYPE=$padType")
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(padType))
|
||||
// Steam's touch controller (SteamTouchDevice): the file the app and libfakeinput share.
|
||||
if (wantsTouch) com.droiddeck.launcher.input.SteamTouchDevice.prepare(fakeInputDir)?.let {
|
||||
guest.add("FAKE_TOUCHCTL_RING=" + it.path)
|
||||
}
|
||||
guest.add("FAKE_DECK_SYSFS_LISTING=" + SteamDeckPad.listingDir(fakeInputDir.parentFile!!.parentFile!!).path)
|
||||
}
|
||||
} else if (SessionState.mode == MODE_STEAM) {
|
||||
// Without it, games see the pad itself wearing Steam Input's virtual-gamepad identity -
|
||||
// for games the client starts only. Everywhere else (the desktop, a program from the
|
||||
// rail) that identity hides the pad: SDL ignores a Steam virtual gamepad unless it
|
||||
// runs under Steam, so every SDL emulator came up with no controller.
|
||||
guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
|
||||
}
|
||||
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
|
||||
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
|
||||
// The client reads a Deck controller through SDL's HIDAPI; a hint in the environment
|
||||
// outranks the client's own. Nothing else is shown the Deck (libfakeinput).
|
||||
if (!SessionState.deckPad) guest.add("SDL_JOYSTICK_HIDAPI=0")
|
||||
// The guest side of the pads (libfakeinput: which pads were opened, the Deck's hidraw and why
|
||||
// it was refused) in pad.log beside the session's other logs, so it is in every shared zip.
|
||||
// Setup-time lines only, nothing per input event.
|
||||
guest.add("FAKE_EVDEV_LOG=1")
|
||||
guest.add("FAKE_EVDEV_LOG_FILE=" + File(sessionDir, "pad.log").path)
|
||||
SessionState.fakeInputDir = fakeInputDir
|
||||
}
|
||||
|
||||
/** What proot binds into the guest: the pads, the battery, storage, the game library, added games and ROMs. */
|
||||
private fun sessionBinds(
|
||||
controllersOn: Boolean,
|
||||
fakeInputDir: File,
|
||||
@@ -815,11 +643,6 @@ class SessionService : Service() {
|
||||
val binds = ArrayList<String>()
|
||||
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
||||
if (controllersOn) binds.addAll(deckBinds)
|
||||
// The client's battery readout (the Quick Access Menu, the top bar) reads
|
||||
// /sys/class/power_supply/BAT<n>/..., a laptop's or a Deck's naming; Android's supply is
|
||||
// called "battery" and its files differ, so the client sees no battery at all. A directory
|
||||
// of our own, written from Android's battery API every few seconds, is bound over it.
|
||||
// Steam's time estimates come from /run/vpower instead, written straight into the rootfs.
|
||||
val battery = BatteryComponent(
|
||||
File(filesDir, "session/sys/power_supply"),
|
||||
File(LinuxRuntime.rootDir(this), "run/vpower"),
|
||||
@@ -827,55 +650,39 @@ class SessionService : Service() {
|
||||
battery.attach(this)
|
||||
components.add(battery)
|
||||
binds.add(battery.dir.path + ":/sys/class/power_supply")
|
||||
// The overlay's CPU and GPU temperatures and the fan, as hwmon sensors it knows by name.
|
||||
val hwmon = HwmonComponent(File(filesDir, "session/sys/hwmon"), LinuxRuntime.rootDir(this))
|
||||
if (hwmon.prepare()) {
|
||||
hwmon.attach(this)
|
||||
components.add(hwmon)
|
||||
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
|
||||
}
|
||||
// CPU load for everything in the session that reads /proc/stat, the overlay among them.
|
||||
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
|
||||
if (cpuStat.prepare()) {
|
||||
cpuStat.attach(this)
|
||||
components.add(cpuStat)
|
||||
binds.add(cpuStat.file.path + ":/proc/stat")
|
||||
}
|
||||
// The GPU memory in use for the overlay's VRAM lines, which it would read from tracefs.
|
||||
val gpuMem = GpuMemComponent(File(LinuxRuntime.rootDir(this), "run/droiddeck-hud/gpu-mem"), LinuxRuntime.rootDir(this))
|
||||
if (gpuMem.prepare()) {
|
||||
gpuMem.attach(this)
|
||||
components.add(gpuMem)
|
||||
}
|
||||
// The GPU's load and temperature for the performance overlay, where KGSL's sysfs is refused.
|
||||
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"))
|
||||
if (gpuStats.prepare()) {
|
||||
gpuStats.attach(this)
|
||||
components.add(gpuStats)
|
||||
binds.addAll(gpuStats.binds())
|
||||
}
|
||||
// Rumble for the on-screen pad: the fake evdev layer sends force-feedback effects to this
|
||||
// listener, which drives the phone's vibrator (see RumbleComponent).
|
||||
if (controllersOn) components.add(RumbleComponent().also { it.attach(this) })
|
||||
// Where the device's files appear inside the session. Internal storage is bound at its own
|
||||
// path already, and every program's file dialog opens at home and lists "Computer" from
|
||||
// /proc/mounts, where a proot bind never shows - so a user saw only the runtime's own
|
||||
// tree and could not find the phone at all. The same storage is placed under home as
|
||||
// well, and the ROMs folder chosen on the main screen beside it; a bind rather than a
|
||||
// link, so a folder on an SD card works the same.
|
||||
val home = File(LinuxRuntime.rootDir(this), "root")
|
||||
File(home, "Storage").mkdirs()
|
||||
binds.add(Environment.getExternalStorageDirectory().path + ":/root/Storage")
|
||||
// A second Steam library: the storage chosen in the Steam cog, at the path the runtime's
|
||||
// droiddeck-steam-library registers with the client. Nothing bound = the script removes
|
||||
// the entry, so the client never offers a place that is not there.
|
||||
val library = GameStorage.effective(this)
|
||||
var storageDiagnosticLibrary: File? = null
|
||||
if (library != null) {
|
||||
val problem = GameStorage.prepare(this, library.path)
|
||||
if (problem == null) {
|
||||
File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs()
|
||||
// Links, prefixes and Steam entries made before the rename still name the old path.
|
||||
File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs()
|
||||
try {
|
||||
binds.addAll(SecondaryLibrary.binds(filesDir, File(library.path)))
|
||||
@@ -900,8 +707,6 @@ class SessionService : Service() {
|
||||
} ?: false,
|
||||
)
|
||||
if (device != null) {
|
||||
// guest already has the session command at this point. Put these with the `env -i`
|
||||
// assignments so they reach the Steam process instead of becoming script args.
|
||||
val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size
|
||||
guest.add(envAt, "BL_STORAGE_DIAGNOSTICS=1")
|
||||
guest.add(envAt + 1, "BL_STORAGE_DEVICE=$device")
|
||||
@@ -910,8 +715,6 @@ class SessionService : Service() {
|
||||
Log.w(TAG, "storage diagnostics: selected library could not be identified; metadata snapshot only")
|
||||
}
|
||||
}
|
||||
// The user's own games folder (the Steam cog's "Added games"), bound at a fixed place so
|
||||
// the shortcuts the app writes point somewhere whatever storage the folder is on.
|
||||
for (root in com.droiddeck.launcher.frontend.AddedGames.roots(this)) {
|
||||
if (root.host.isDirectory && root.host.canRead()) {
|
||||
File(LinuxRuntime.rootDir(this), root.guest.removePrefix("/")).mkdirs()
|
||||
@@ -921,8 +724,6 @@ class SessionService : Service() {
|
||||
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
|
||||
}
|
||||
}
|
||||
// Store games installed on a card: each card's Games root at its own fixed place, so the
|
||||
// shortcuts point somewhere whether or not the card is also the Steam library.
|
||||
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRoots(this)) {
|
||||
if (host.isDirectory && host.canRead()) {
|
||||
File(LinuxRuntime.rootDir(this), guest.removePrefix("/")).mkdirs()
|
||||
@@ -930,7 +731,6 @@ class SessionService : Service() {
|
||||
Log.i(TAG, "store games: $host -> $guest")
|
||||
}
|
||||
}
|
||||
// Folders of added scripts outside internal storage, where their links point.
|
||||
binds.addAll(com.droiddeck.launcher.runtime.UserApps.binds(this))
|
||||
val roms = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }?.let { File(it) }
|
||||
if (roms != null && roms.isDirectory && roms.canRead()) {
|
||||
@@ -987,7 +787,7 @@ class SessionService : Service() {
|
||||
if (!stillSameProcess()) return
|
||||
val tree = descendants(prootPid)
|
||||
if (!stillSameProcess()) return
|
||||
android.os.Process.sendSignal(prootPid, 15) // SIGTERM
|
||||
android.os.Process.sendSignal(prootPid, 15)
|
||||
if (!waitForExit(prootPid, GRACE_MS)) {
|
||||
if (!stillSameProcess()) return
|
||||
Log.w(TAG, "proot $prootPid did not exit on SIGTERM; killing it")
|
||||
@@ -995,15 +795,14 @@ class SessionService : Service() {
|
||||
}
|
||||
var killed = 0
|
||||
for ((pid, started) in tree) {
|
||||
val stat = readStat(pid) ?: continue // already gone
|
||||
if (stat.second != started) continue // same number, different process
|
||||
val stat = readStat(pid) ?: continue
|
||||
if (stat.second != started) continue
|
||||
android.os.Process.killProcess(pid)
|
||||
killed++
|
||||
}
|
||||
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
|
||||
}
|
||||
|
||||
/** Every process under [root], as (pid, start time), from a single walk of /proc. */
|
||||
private fun descendants(root: Int): List<Pair<Int, Long>> {
|
||||
val started = HashMap<Int, Long>()
|
||||
val children = HashMap<Int, MutableList<Int>>()
|
||||
@@ -1027,7 +826,6 @@ class SessionService : Service() {
|
||||
return out
|
||||
}
|
||||
|
||||
/** (parent pid, start time) from /proc/pid/stat, or null when the process is gone. */
|
||||
private fun readStat(pid: Int): Pair<Int, Long>? {
|
||||
val stat = try { File("/proc/$pid/stat").readText() } catch (e: Exception) { return null }
|
||||
val close = stat.lastIndexOf(')')
|
||||
@@ -1140,19 +938,6 @@ class SessionService : Service() {
|
||||
File(directory, STEAM_GAME_REQUEST + ".tmp").delete()
|
||||
}
|
||||
|
||||
/**
|
||||
* proot's --kill-on-exit takes its tracees down, but a session that died from the inside
|
||||
* (the client asserting, Xwayland going) leaves gamescopereaper and the session script
|
||||
* behind, still holding the Wayland socket and the audio server the next session needs. They
|
||||
* are our uid, so they are ours to kill.
|
||||
*/
|
||||
/**
|
||||
* Every process of ours still running a program out of the Linux runtime once proot is gone.
|
||||
* proot's --kill-on-exit and the tree sweep only reach what proot still traces; a tracee it
|
||||
* lost - an Xwayland that aborted from one thread and then looped on a syscall proot's own
|
||||
* seccomp filter, with no tracer left, answers ENOSYS - survives both, reparented to init,
|
||||
* and wrote 9 GB of one line into the session log before anything killed it.
|
||||
*/
|
||||
private fun killGuestLeftovers() {
|
||||
val me = android.os.Process.myPid()
|
||||
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
|
||||
@@ -1161,7 +946,6 @@ class SessionService : Service() {
|
||||
for (proc in procs) {
|
||||
val pid = proc.name.toIntOrNull() ?: continue
|
||||
if (pid == me) continue
|
||||
// Another uid's exe is not ours to read; a process already gone has none.
|
||||
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
|
||||
if (!exe.startsWith(rootfs)) continue
|
||||
android.os.Process.killProcess(pid)
|
||||
@@ -1189,13 +973,6 @@ class SessionService : Service() {
|
||||
if (killed > 0) Log.w(TAG, "killed $killed leftover process(es) of a previous session")
|
||||
}
|
||||
|
||||
/**
|
||||
* The desktop's Steam launchers cannot start the client where they are (no dma-buf on the
|
||||
* desktop), so they leave `steam-launch` in the session directory instead: which UI, and a
|
||||
* steam:// URL or nothing. This ends the session and hands the activity the one to start.
|
||||
* `session=desktop` (Big Picture's "Switch to Desktop", steamos-session-select) asks for the
|
||||
* desktop instead, with Steam's desktop client started in it.
|
||||
*/
|
||||
private var launchWatcher: android.os.FileObserver? = null
|
||||
|
||||
private fun watchLaunchRequests(dir: File) {
|
||||
@@ -1275,12 +1052,6 @@ class SessionService : Service() {
|
||||
|
||||
private val desktopImports = java.util.concurrent.ConcurrentHashMap<String, Any>()
|
||||
|
||||
/**
|
||||
* What the desktop cannot run where it lies (droiddeck-open), added as Add an app adds it, menu entry
|
||||
* included: an AppImage of sharun's, whose hard links Android denies apps and only the app's own proot
|
||||
* (link2symlink) makes, or a script or program whose folder of Linux programs is on noexec shared
|
||||
* storage, copied in. The answer goes beside the request, "ok <folder>" or "error <why>".
|
||||
*/
|
||||
private fun importForDesktop(dir: File, text: String) {
|
||||
val fields = text.lineSequence().mapNotNull { line ->
|
||||
line.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0] to it[1].trim() }
|
||||
@@ -1291,7 +1062,6 @@ class SessionService : Service() {
|
||||
val binds = LinuxRuntime.lastBinds(this).map { BwrapSpawner.Bind.parse(it) }
|
||||
val file = File(BwrapSpawner.hostPath(binds, LinuxRuntime.rootDir(this).path, guestPath))
|
||||
val context = applicationContext
|
||||
// A request for what is already being added waits for that, then finds it.
|
||||
val lock = desktopImports.computeIfAbsent(key) { Any() }
|
||||
Thread({
|
||||
fun imported() = UserApps.desktopImport(context, key, guestPath)?.let { "ok $it" }
|
||||
@@ -1413,8 +1183,6 @@ class SessionService : Service() {
|
||||
|
||||
private fun completeSteamSleep() {
|
||||
val token = steamSleepToken ?: return
|
||||
// Write before SIGCONT: the guest's login1 sees it immediately on thaw
|
||||
// and delivers PrepareForSleep(false), restoring Steam's main surface.
|
||||
writeSteamSleepState(token, "awake")
|
||||
steamSleepToken = null
|
||||
}
|
||||
@@ -1427,7 +1195,6 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Let Steam prepare before freezing; retain the wake lock until that freeze completes. */
|
||||
private fun prepareNativeSleep() {
|
||||
val token = UUID.randomUUID().toString().replace("-", "")
|
||||
nativeSleepToken = token
|
||||
@@ -1451,7 +1218,6 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
nativeSleepTimeout = timeout
|
||||
// A missing or stalled guest helper must not keep the device awake indefinitely.
|
||||
mainHandler.postDelayed(timeout, 4000L)
|
||||
}
|
||||
|
||||
@@ -1468,7 +1234,6 @@ class SessionService : Service() {
|
||||
nativeSleepFallback = false
|
||||
}
|
||||
|
||||
/** Resume must also recover a Steam sleep whose request never reached Android. */
|
||||
private fun requestSteamWake() {
|
||||
if (!SessionState.running || SessionState.mode != MODE_STEAM) return
|
||||
val dir = LinuxRuntime.sessionRoot(this)
|
||||
@@ -1491,8 +1256,6 @@ class SessionService : Service() {
|
||||
SessionState.guestPid = -1
|
||||
com.droiddeck.launcher.agent.AgentGuest.stop()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
|
||||
// Cloud saves of a store game played this session, if the compat tool's exit request did
|
||||
// not upload them (a session closed from the drawer never reaches it).
|
||||
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) }
|
||||
@@ -1511,13 +1274,6 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* proot is one thread, and every syscall it traps anywhere in the session - a path lookup in
|
||||
* Proton's python, Wine's file opens, the Steam client's /proc scans - waits for that thread to
|
||||
* be scheduled, at nice 0 beside a game that keeps the big cores busy. It is raised to nice -6,
|
||||
* under the compositor's -8. After a moment, not at once: the first guest process is forked by
|
||||
* proot itself and would inherit the value, and with it everything the session starts.
|
||||
*/
|
||||
private fun raiseTracer(pid: Int, gen: Int) {
|
||||
Thread({
|
||||
try {
|
||||
@@ -1555,13 +1311,6 @@ class SessionService : Service() {
|
||||
launchWatcher = null
|
||||
syncWatcher?.stopWatching()
|
||||
syncWatcher = null
|
||||
// proot's --kill-on-exit takes the guest tree down only if proot gets to run it, and
|
||||
// SIGKILL never lets it. A SIGKILLed proot left its tracees alive with no tracer: every
|
||||
// seccomp-trapped syscall then failed with ENOSYS, they spun on retries at a full core
|
||||
// for over an hour, and the reaper could not even open /proc to kill them. So: SIGTERM,
|
||||
// a grace for proot's own cleanup, SIGKILL only if it will not go, then a sweep of the
|
||||
// tree it had - snapshotted first, each pid checked against its start time so a number
|
||||
// reused by a new process is never touched.
|
||||
val prootPid = sessionPid
|
||||
sessionPid = -1
|
||||
val auxiliary = synchronized(auxiliaryProcessesLock) {
|
||||
@@ -1570,11 +1319,6 @@ class SessionService : Service() {
|
||||
SessionTerminal.clear(sessionGen)
|
||||
val controller = suspendController
|
||||
suspendController = null
|
||||
// On its own thread, never here: stopSession runs on the main thread (the notification's
|
||||
// Stop action arrives there), and collecting means copying the compositor's log, scrubbing
|
||||
// every Steam log line by line - 42 files on one measured run - and waiting for logcat to
|
||||
// dump the crash buffer. That was about four and a half seconds of blocked main thread,
|
||||
// and Android ANR'd the app for it: the desktop session that would not let go.
|
||||
val ended = SessionPaths.take()
|
||||
if (ended != null) Thread({ collectSessionArtifacts(ended) }, "session-collect").start()
|
||||
components.reversed().forEach {
|
||||
@@ -1606,10 +1350,6 @@ class SessionService : Service() {
|
||||
if (controller != null) controller.closeAndResume(finishAfterTeardown) else finishAfterTeardown()
|
||||
}
|
||||
|
||||
/**
|
||||
* Swiped out of recents. The activity is destroyed without any of our teardown running, so the
|
||||
* guest would survive as an orphan holding the rootfs and the GPU. Treat the swipe as "quit".
|
||||
*/
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (pipTask) {
|
||||
Log.i(TAG, "PiP task dismissed - retaining the session under its background policy")
|
||||
@@ -1633,7 +1373,6 @@ class SessionService : Service() {
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
// ── Keeping the process alive ───────────────────────────────────────────────────────────
|
||||
|
||||
private fun acquireLocks() {
|
||||
try {
|
||||
@@ -1652,7 +1391,7 @@ class SessionService : Service() {
|
||||
val wifi = applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
val allowed = DeviceSupport.lowLatencyWifiSafe()
|
||||
if (!allowed) Log.i(TAG, "wifi lock skipped: its low-latency mode resets this device")
|
||||
@Suppress("DEPRECATION") // deprecated from API 29, still honoured; targetSdk is 28
|
||||
@Suppress("DEPRECATION")
|
||||
if (allowed && wifiLock?.isHeld != true) {
|
||||
wifiLock = wifi?.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "DroidDeck:session-wifi")
|
||||
?.apply {
|
||||
@@ -1662,8 +1401,6 @@ class SessionService : Service() {
|
||||
}
|
||||
Log.i(TAG, "wifi lock held=${wifiLock?.isHeld}")
|
||||
} catch (t: Throwable) {
|
||||
// A partial wake lock keeps the process alive but does not stop WiFi power-save from
|
||||
// throttling a backgrounded download to nothing, which is what this lock is for.
|
||||
Log.w(TAG, "no wifi lock (${t.message}) - a backgrounded download may stall")
|
||||
}
|
||||
}
|
||||
@@ -1683,11 +1420,9 @@ class SessionService : Service() {
|
||||
wifiLock = null
|
||||
}
|
||||
|
||||
// ── Notification ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
// IMPORTANCE_LOW: it must never make a sound or push a heads-up over a game.
|
||||
val channel = NotificationChannel(CHANNEL_ID, getString(R.string.session_channel),
|
||||
NotificationManager.IMPORTANCE_LOW).apply {
|
||||
description = getString(R.string.session_channel_description)
|
||||
@@ -1784,7 +1519,6 @@ class SessionService : Service() {
|
||||
mainHandler.post(poll)
|
||||
}
|
||||
|
||||
/** The pads attached as the session starts; the activity logs the ones that come and go after. */
|
||||
private fun logControllersAtStart() {
|
||||
val pads = ArrayList<String>()
|
||||
for (id in android.view.InputDevice.getDeviceIds()) {
|
||||
@@ -1798,25 +1532,11 @@ class SessionService : Service() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
/** proot's tracer: above everything in the guest, under the compositor thread's -8. */
|
||||
private const val TRACER_NICE = -6
|
||||
/** Downloads file whose contents become TU_DEBUG inside the session, e.g. "sysmem". */
|
||||
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
|
||||
/**
|
||||
* Where droiddeck-env (KEY=VALUE lines added to the session environment verbatim) used to
|
||||
* be. Ignored now: a line there reaches the Steam client's environment as written
|
||||
* (LD_PRELOAD, VK_ICD_FILENAMES, PATH...), and any app with storage access can write to
|
||||
* Download - code of its choosing inside our sandbox, next to the client's saved login.
|
||||
*/
|
||||
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
|
||||
private const val ENV_SWITCH_NAME = "droiddeck-env"
|
||||
|
||||
/**
|
||||
* The session's extra-environment file: Android/data/<package>/files/droiddeck-env. Only
|
||||
* this app, adb and the user (through the app's own file manager) can write there - from
|
||||
* Android 11 on. Before that other apps with storage access can reach Android/data too, so
|
||||
* there is no such file at all.
|
||||
*/
|
||||
fun envSwitchFile(context: Context): File? =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
|
||||
context.getExternalFilesDir(null)?.let { File(it, ENV_SWITCH_NAME) }
|
||||
@@ -1837,10 +1557,8 @@ class SessionService : Service() {
|
||||
private const val ACTION_STOP_AUXILIARY = "com.droiddeck.launcher.STOP_AUXILIARY"
|
||||
private const val ACTION_AUXILIARY_EXITED = "com.droiddeck.launcher.AUXILIARY_EXITED"
|
||||
private const val EXTRA_AUXILIARY_PID = "auxiliaryPid"
|
||||
/** Command lines that can only belong to a session of ours. */
|
||||
private val STRAGGLERS = listOf("droiddeck-session", "gamescope", "Xwayland", "steamrtarm64",
|
||||
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
|
||||
/** How long proot gets to run its own cleanup before it is killed outright. */
|
||||
private const val GRACE_MS = 1200L
|
||||
private const val STEAM_PICKUP_MS = 1500L
|
||||
private const val STEAM_EXIT_MS = 10_000L
|
||||
@@ -1851,19 +1569,14 @@ class SessionService : Service() {
|
||||
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
|
||||
private const val NO_DECK_PAD_SWITCH = "Download/droiddeck-no-deck-pad"
|
||||
private const val NO_STEAM_TOUCH_SWITCH = "Download/droiddeck-no-steam-touch"
|
||||
/** libfakeinput numbers the pads made through its /dev/uinput stand-in from here. */
|
||||
private const val FIRST_VIRTUAL_PAD = 16
|
||||
|
||||
const val EXTRA_MODE = "mode"
|
||||
const val MODE_STEAM = "steam"
|
||||
const val MODE_DESKTOP = "lxqt"
|
||||
/** A program inside the runtime, fullscreen under gamescope (EXTRA_PROGRAM = its path). */
|
||||
const val MODE_RUN = "run"
|
||||
const val EXTRA_PROGRAM = "program"
|
||||
/** MODE_RUN: arguments after the program (a game to boot). */
|
||||
const val EXTRA_PROGRAM_ARGS = "programArgs"
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI (default Big Picture); a steam:// URL to hand it.
|
||||
* MODE_DESKTOP: "desktop" = open Steam's desktop client in the desktop once it is up. */
|
||||
const val EXTRA_STEAM_UI = "steamUi"
|
||||
const val EXTRA_STEAM_URL = "steamUrl"
|
||||
const val EXTRA_GAME_ID = "gameId"
|
||||
@@ -1904,7 +1617,6 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
|
||||
}
|
||||
|
||||
/** Route a validated decimal Steam game id through the current guest session. */
|
||||
fun launchGame(context: Context, gameId: String): Boolean {
|
||||
if (!GameLaunchLink.validId(gameId) || !SessionState.running ||
|
||||
SessionState.mode != MODE_STEAM || SessionState.stopRequested) return false
|
||||
@@ -1923,7 +1635,6 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
|
||||
}
|
||||
|
||||
/** Let the session service clean up the PTY's proot tree if the control screen closes. */
|
||||
fun stopTerminalProcess(context: Context, pid: Int) {
|
||||
if (pid > 1) context.startService(
|
||||
Intent(context, SessionService::class.java)
|
||||
|
||||
@@ -5,11 +5,6 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
/**
|
||||
* The little that the activity and the service have to agree on. Process-wide rather than passed
|
||||
* through intents, because both halves live in one process and the point of the split is that
|
||||
* either can outlive the other.
|
||||
*/
|
||||
object SessionState {
|
||||
@Volatile
|
||||
var phase = SessionPhase.IDLE
|
||||
@@ -48,26 +43,17 @@ object SessionState {
|
||||
var running = false
|
||||
var suspended by mutableStateOf(false)
|
||||
@Volatile var pipActive = false
|
||||
/** MODE_RUN: the program inside the runtime the session was started for. */
|
||||
@Volatile
|
||||
var program: String? = null
|
||||
@Volatile
|
||||
var programArgs: List<String> = emptyList()
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI, else Big Picture; and a steam:// URL to hand it. */
|
||||
@Volatile
|
||||
var steamUi: String? = null
|
||||
@Volatile
|
||||
var steamUrl: String? = null
|
||||
/** A session the guest asked for (the desktop's Steam launchers): started by the activity once this one has ended. */
|
||||
var relaunch: android.content.Intent? = null
|
||||
/** HDR10 was asked for and the panel can show it: the compositor was told, and the session
|
||||
* gets DXVK_HDR=1 and gamescope --hdr-enabled. Decided by the activity before the compositor starts. */
|
||||
@JvmStatic var hdr = false
|
||||
|
||||
/** The pad is presented to the Steam client as a Steam Deck controller this session
|
||||
* (SteamDeckPad): its Quick Access button is a real button, not the Guide+A chord. Decided by
|
||||
* the service as the session starts, which can be after the activity has resumed - hence
|
||||
* [deckPadListener]. */
|
||||
@Volatile private var deckPadValue = false
|
||||
@JvmStatic var deckPad: Boolean
|
||||
get() = deckPadValue
|
||||
@@ -77,57 +63,40 @@ object SessionState {
|
||||
deckPadListener?.invoke()
|
||||
}
|
||||
|
||||
/** Told (on the thread that changed it) whenever [deckPad] changes. */
|
||||
@Volatile var deckPadListener: (() -> Unit)? = null
|
||||
|
||||
/** The session screen's virtual pad, for the agent bridge's pad input (AgentInput). */
|
||||
@Volatile var padBridge: com.droiddeck.launcher.input.PadBridge? = null
|
||||
|
||||
/** What the second screen shows, and on which display: kept for the session, so a screen
|
||||
* turned off (sleep, a closed lid) or an activity recreated brings it back as it was. */
|
||||
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
|
||||
@Volatile var secondScreenDisplay = -1
|
||||
|
||||
/** Which session this is: SessionService.MODE_STEAM or MODE_DESKTOP. */
|
||||
@Volatile
|
||||
var mode = "steam"
|
||||
|
||||
/** The size gamescope was told to render at; set by the activity before the service starts. */
|
||||
@Volatile
|
||||
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
|
||||
|
||||
/** The session's resolution is "Follow screen": outputSize tracks the window while it runs. */
|
||||
@Volatile
|
||||
var followScreen = false
|
||||
|
||||
@Volatile
|
||||
var refreshHz: Float = 60f
|
||||
|
||||
/**
|
||||
* How far the compositor enlarges the session onto the panel (panel over outputSize, long
|
||||
* side to long side); set with outputSize. 0 before a session has been sized. Texture
|
||||
* sharpness "Auto" (core/TextureFiltering) is derived from it when a game launches.
|
||||
*/
|
||||
@Volatile
|
||||
var upscaleRatio: Float = 0f
|
||||
|
||||
/** The session's frame cap (SessionPrefs.fpsLimit), fixed when it starts; 0 = none. */
|
||||
@Volatile
|
||||
var fpsLimit: Int = 0
|
||||
|
||||
/** The compositor has presented a frame, so the loading panel is behind us for this session. */
|
||||
@Volatile
|
||||
var firstFrameSeen = false
|
||||
|
||||
/** Where this session is writing its log, for the "it ended" message. */
|
||||
@Volatile
|
||||
var logFile: File? = null
|
||||
|
||||
/** The fake evdev directory, once the service has prepared the rings. */
|
||||
@Volatile
|
||||
var fakeInputDir: File? = null
|
||||
|
||||
/** Told when the session ends, so a visible activity can close itself. */
|
||||
@Volatile
|
||||
var endListener: ((Int) -> Unit)? = null
|
||||
|
||||
@@ -136,7 +105,6 @@ object SessionState {
|
||||
}
|
||||
}
|
||||
|
||||
/** Stable lifecycle values returned by the debug agent bridge. */
|
||||
enum class SessionPhase {
|
||||
IDLE,
|
||||
PREPARING,
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import java.io.File
|
||||
|
||||
/** Immutable launch context for the optional PTY shell attached to the active Linux runtime. */
|
||||
object SessionTerminal {
|
||||
private data class Launch(
|
||||
val command: Array<String>,
|
||||
|
||||
@@ -6,15 +6,6 @@ import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
|
||||
/**
|
||||
* Setup's "Reset all settings": every choice goes back to the default its getter falls back to.
|
||||
*
|
||||
* Only settings are removed. The "session" file also holds the library (added games' names, exes,
|
||||
* appids and art picks), migration records, the drivers Auto installed, the storage and ROMs
|
||||
* folders and the one-time permission prompts; those stay, as do store sign-ins, imported drivers
|
||||
* and Lossless Scaling. Game profiles (each game's and the Default profile's environment
|
||||
* overrides) are cleared only when asked for.
|
||||
*/
|
||||
object SettingsReset {
|
||||
private const val TAG = "SettingsReset"
|
||||
|
||||
@@ -30,11 +21,9 @@ object SettingsReset {
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline",
|
||||
// Cleared so the Quest's one-time compatibility defaults are written again.
|
||||
"questDefaultsV1",
|
||||
)
|
||||
|
||||
/** Per-mode settings, stored as "<prefix><mode>". */
|
||||
internal val SESSION_PREFIXES = listOf(
|
||||
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "suspendPolicy.",
|
||||
)
|
||||
@@ -43,13 +32,6 @@ object SettingsReset {
|
||||
|
||||
internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) }
|
||||
|
||||
/**
|
||||
* Resets the settings, then per-game profiles when [gameProfiles] is set ([gameScopes] are the
|
||||
* library's profile keys; scopes with saved overrides are found on their own). Blocking: call
|
||||
* off the main thread. Returns false if a part could not be reset; the rest is still done.
|
||||
* The language is not reset here: AppLanguage.setChosen changes the process locale, so the
|
||||
* caller does that on the main thread.
|
||||
*/
|
||||
fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection<String> = emptyList()): Boolean {
|
||||
var ok = true
|
||||
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
@@ -7,33 +7,8 @@ import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The session's pad, described to the Steam client as a Steam Deck controller.
|
||||
*
|
||||
* On a Deck - and on the handhelds InputPlumber serves as one - the client finds the controller
|
||||
* through libudev as a `hidraw` device under a `hid` device under a USB interface and reads it
|
||||
* itself. libfakeinput serves the device node (`/dev/hidraw16`, built from the pad's input ring);
|
||||
* what the client also needs is the sysfs it walks to find and identify that node, which a sandbox
|
||||
* shows nothing of. This writes that sysfs as the kernel lays out a Deck's controller interface and
|
||||
* returns the binds that put it in place:
|
||||
*
|
||||
* - `/sys/devices/droiddeck/usb1` - the USB device (Valve, 28de:1205), its interface 2, the HID
|
||||
* device on it (`HID_ID`, `report_descriptor`) and that device's `hidraw/hidraw16`;
|
||||
* - `/sys/class/hidraw/hidraw16` - what an enumeration of the `hidraw` subsystem lists;
|
||||
* - `/sys/dev/char/240:16` - how the node's device number is looked up (in the directory the
|
||||
* runtime already binds there for the GPU);
|
||||
* - `/run/udev/data/c240:16` - the udev database entry that marks the device initialised, without
|
||||
* which libudev's enumeration leaves a device node out;
|
||||
* - [listingDir] - stand-ins for the listings of `/sys`, `/sys/class` and `/sys/bus`. An app under
|
||||
* an enforcing SELinux policy (every retail phone) may not list those directories, and libudev
|
||||
* abandons its whole scan when it cannot, so the client never reached `hidraw`; libfakeinput
|
||||
* lists these to the client instead when the real listing is refused (FAKE_DECK_SYSFS_LISTING).
|
||||
*
|
||||
* Symlinks are absolute guest paths; proot resolves them inside the session.
|
||||
*/
|
||||
object SteamDeckPad {
|
||||
private const val TAG = "SessionService"
|
||||
/** Must match libfakeinput (fakeinput_steam.cpp: DECK_HIDRAW_*). */
|
||||
private const val MAJOR = 240
|
||||
private const val MINOR = 16
|
||||
private const val NODE = "hidraw$MINOR"
|
||||
@@ -44,20 +19,14 @@ object SteamDeckPad {
|
||||
private const val HIDRAW = "$HID/hidraw/$NODE"
|
||||
private const val SERIAL = "DROIDDECK0001"
|
||||
|
||||
// The paired Bluetooth Steam Controller is a separate Triton HID device. It must not inherit
|
||||
// the Deck's identity or report format. Must match fakeinput_steam.cpp (TRITON_HIDRAW_*).
|
||||
private const val TRITON_MINOR = 18
|
||||
private const val TRITON_HID = "$GUEST_DEVICES/bluetooth/0005:28DE:1303.0003"
|
||||
private const val TRITON_SERIAL = "DROIDDECKSC01"
|
||||
// The handheld's own pad as the Steam Controller (SessionPrefs.CONTROLLER_STEAM): the wired
|
||||
// controller (28de:1302) on a USB device of its own, since it is built in.
|
||||
private const val TRITON_USB = "$GUEST_DEVICES/usb3"
|
||||
private const val TRITON_INTERFACE = "$TRITON_USB/3-1:1.0"
|
||||
private const val TRITON_WIRED_HID = "$TRITON_INTERFACE/0003:28DE:1302.0004"
|
||||
/** Must match libfakeinput (DS4_HIDRAW_MINOR, DUALSENSE_HIDRAW_MINOR). */
|
||||
private const val SONY_DS4_MINOR = 20
|
||||
private const val SONY_DUALSENSE_MINOR = 21
|
||||
/** Must match libfakeinput's kDs4ReportDescriptor and kDualSenseReportDescriptor. */
|
||||
private val DS4_REPORT_DESCRIPTOR = intArrayOf(
|
||||
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08,
|
||||
0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x05, 0x09, 0x21, 0x95, 0x1f, 0x91, 0x02,
|
||||
@@ -71,11 +40,8 @@ object SteamDeckPad {
|
||||
0x85, 0x05, 0x09, 0x22, 0x95, 0x28, 0xb1, 0x02, 0x85, 0x09, 0x09, 0x23, 0x95, 0x13, 0xb1, 0x02,
|
||||
0x85, 0x20, 0x09, 0x24, 0x95, 0x3f, 0xb1, 0x02, 0xc0,
|
||||
).map { it.toByte() }.toByteArray()
|
||||
/** Must match libfakeinput (TRITON_PAD_HIDRAW_*): its own node, so a paired controller keeps 18. */
|
||||
private const val TRITON_PAD_MINOR = 19
|
||||
|
||||
// Steam's touch controller (SteamTouchDevice), a second device beside the Deck's: 0000:11fb,
|
||||
// "Mobile Touch Control", on a USB device of its own. Must match libfakeinput (TOUCH_*).
|
||||
private const val TOUCH_MINOR = 17
|
||||
private const val TOUCH_NODE = "hidraw$TOUCH_MINOR"
|
||||
private const val TOUCH_USB = "$GUEST_DEVICES/usb2"
|
||||
@@ -84,7 +50,6 @@ object SteamDeckPad {
|
||||
private const val TOUCH_HIDRAW = "$TOUCH_HID/hidraw/$TOUCH_NODE"
|
||||
private const val TOUCH_SERIAL = "DROIDDECK0001"
|
||||
|
||||
/** libfakeinput's kTouchReportDescriptor: Generic Desktop / Game Pad, 40-byte input report. */
|
||||
private val TOUCH_REPORT_DESCRIPTOR = intArrayOf(
|
||||
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01,
|
||||
0x09, 0x02, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x28, 0x81, 0x02,
|
||||
@@ -92,14 +57,12 @@ object SteamDeckPad {
|
||||
0x09, 0x04, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0,
|
||||
).map { it.toByte() }.toByteArray()
|
||||
|
||||
/** InputPlumber's CONTROLLER_DESCRIPTOR, as libfakeinput answers HIDIOCGRDESC. */
|
||||
private val REPORT_DESCRIPTOR = intArrayOf(
|
||||
0x06, 0xff, 0xff, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00,
|
||||
0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x06, 0x09, 0x07,
|
||||
0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0,
|
||||
).map { it.toByte() }.toByteArray()
|
||||
|
||||
/** Triton's native 0x45/0x47 input and 0x80-0x85 haptic output report IDs. */
|
||||
private val TRITON_REPORT_DESCRIPTOR = intArrayOf(
|
||||
0x06, 0x00, 0xff, 0x09, 0x01, 0xa1, 0x01,
|
||||
0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08,
|
||||
@@ -115,23 +78,13 @@ object SteamDeckPad {
|
||||
0xc0,
|
||||
).map { it.toByte() }.toByteArray()
|
||||
|
||||
/** The wired controller's: its 0x42 state report in place of the Bluetooth 0x45. */
|
||||
private val TRITON_WIRED_REPORT_DESCRIPTOR = TRITON_REPORT_DESCRIPTOR.copyOf().also { it[15] = 0x42 }
|
||||
|
||||
/** Where [prepare] puts the stand-in listings; bound into the guest at the same path. */
|
||||
fun listingDir(sessionRoot: File) = File(sessionRoot, "sys/deck/listing")
|
||||
|
||||
/** Writes the tree and returns the `host:guest` binds for it, or none if it could not be made. */
|
||||
/** The pad's own devices by minor (the Deck, its Steam Controller, the PlayStation pads): guest paths. */
|
||||
private val padNodes = mutableMapOf<Int, String>()
|
||||
@Volatile private var hidrawClassDir: File? = null
|
||||
|
||||
/**
|
||||
* Lists only the device the pad is now ([padType], FakeInputWriter.PAD_TYPE_*) in
|
||||
* /sys/class/hidraw, none for an Xbox 360 pad. Device scans then find what is plugged in: SDL's
|
||||
* (the PlayStation pads' driver) keeps a device it found and could not open, and never tries it
|
||||
* again, while one that disappears from the listing is let go. Before the shim is told.
|
||||
*/
|
||||
@Synchronized
|
||||
fun showPad(padType: Int) {
|
||||
val dir = hidrawClassDir ?: return
|
||||
@@ -200,11 +153,8 @@ object SteamDeckPad {
|
||||
padNodes.clear()
|
||||
padNodes[MINOR] = HIDRAW
|
||||
|
||||
// Only the names matter: libudev reads a listing for the subsystems to descend into and
|
||||
// then opens /sys/class/hidraw itself, which is the bind above.
|
||||
val listing = listingDir(sessionRoot)
|
||||
for (name in listOf("sys/bus", "sys/class", "sys/devices", "class/hidraw", "bus")) File(listing, name).mkdirs()
|
||||
// The runtime binds this directory over /sys/dev/char for the GPU (LinuxRuntime.bindGpuNode).
|
||||
link(File(context.cacheDir, "drm/sys/$MAJOR:$MINOR"), HIDRAW)
|
||||
|
||||
val udevData = File(LinuxRuntime.rootDir(context), "run/udev/data").apply { mkdirs() }
|
||||
@@ -238,8 +188,6 @@ object SteamDeckPad {
|
||||
Log.i(TAG, "deck pad: /dev/$TOUCH_NODE described as Steam's touch controller (0000:11fb)")
|
||||
}
|
||||
|
||||
// A Steam Controller's HID device: the handheld's own pad as the wired one, or the paired
|
||||
// one on Bluetooth. Both are always described; libfakeinput offers whichever is in use.
|
||||
fun describeTriton(wired: Boolean) {
|
||||
val hid = if (wired) TRITON_WIRED_HID else TRITON_HID
|
||||
val product = if (wired) "1302" else "1303"
|
||||
@@ -276,8 +224,6 @@ object SteamDeckPad {
|
||||
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
|
||||
Log.i(TAG, "steam controller: /dev/$node described as Triton (28de:$product)")
|
||||
}
|
||||
// The handheld's own pad as a PlayStation controller, each a USB device of its own with
|
||||
// the report descriptor libfakeinput serves (kDs4/kDualSenseReportDescriptor).
|
||||
fun describeSony(dualSense: Boolean) {
|
||||
val bus = if (dualSense) 5 else 4
|
||||
val product = if (dualSense) "0ce6" else "09cc"
|
||||
|
||||
@@ -17,11 +17,6 @@ internal class SteamDownloadMonitor {
|
||||
private var lastReceivedBytes = -1L
|
||||
private var lastReceivedAt = 0L
|
||||
|
||||
/**
|
||||
* [receivedBytes] is the app uid's received-byte counter (the guest runs as that uid), or a
|
||||
* negative value when Android does not report one. Steam writes its rate line about once a
|
||||
* minute and flushes manifest counters even less often, so live traffic is what bridges them.
|
||||
*/
|
||||
fun poll(runtimeRoot: File, now: Long = System.currentTimeMillis(), receivedBytes: Long = -1L): Boolean {
|
||||
val current = manifests(runtimeRoot).associate { it.path to read(it) }
|
||||
val progressed = current.any { (path, state) ->
|
||||
@@ -128,7 +123,6 @@ internal class SteamDownloadMonitor {
|
||||
|
||||
private companion object {
|
||||
const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
|
||||
// Longer than Steam's ~60 s between rate lines, for when no traffic counter is available.
|
||||
const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
|
||||
const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
|
||||
val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
|
||||
|
||||
@@ -2,14 +2,9 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Steam's name for a language: the API language codes the client and the Steamworks API use
|
||||
* ("english", "schinese", "koreana"...), for every language Steam's interface comes in.
|
||||
*/
|
||||
object SteamLanguage {
|
||||
const val DEFAULT = "english"
|
||||
|
||||
/** Every language the Steam client's interface is offered in. */
|
||||
val all: Set<String> = setOf(
|
||||
"arabic", "bulgarian", "schinese", "tchinese", "czech", "danish", "dutch", "english",
|
||||
"finnish", "french", "german", "greek", "hungarian", "indonesian", "italian", "japanese",
|
||||
@@ -17,16 +12,11 @@ object SteamLanguage {
|
||||
"spanish", "latam", "swedish", "thai", "turkish", "ukrainian", "vietnamese", "malay",
|
||||
)
|
||||
|
||||
/** Spanish-speaking regions Steam serves with Latin American Spanish rather than Spain's. */
|
||||
private val latinAmerica = setOf(
|
||||
"419", "AR", "BO", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "HN", "MX", "NI", "PA", "PE",
|
||||
"PR", "PY", "SV", "US", "UY", "VE",
|
||||
)
|
||||
|
||||
/**
|
||||
* Steam's language for [locale]. [region] stands in for the locale's own when it has none: the
|
||||
* app's Spanish carries no region, and a player in Mexico should get Latin American Spanish.
|
||||
*/
|
||||
fun forLocale(locale: Locale, region: String? = null): String {
|
||||
val country = locale.country.ifEmpty { region.orEmpty() }
|
||||
return when (locale.language) {
|
||||
|
||||
@@ -5,14 +5,9 @@ import android.system.Os
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/** The opt-in snapshot written beside a session's other logs. */
|
||||
object StorageDiagnostics {
|
||||
private const val TAG = "StorageDiagnostics"
|
||||
|
||||
/**
|
||||
* Records facts about the library actually selected for this session and returns its device
|
||||
* number for the preload shim. The path and volume ID stay out of the shared log.
|
||||
*/
|
||||
fun writeSnapshot(
|
||||
sessionDir: File,
|
||||
library: File,
|
||||
@@ -46,7 +41,6 @@ object StorageDiagnostics {
|
||||
}
|
||||
}
|
||||
|
||||
/** The longest matching mount entry determines the filesystem for nested bindable folders. */
|
||||
private fun filesystemType(path: File): String? = runCatching {
|
||||
val canonical = path.canonicalPath
|
||||
File("/proc/mounts").useLines { lines ->
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/**
|
||||
* What to call a catalog component on screen. Bannerlator's catalog keys (vcredist2010_dll,
|
||||
* oalinst_dll, d3dcompiler_47...) have no display name, and some descriptions do not fit the entry,
|
||||
* so names come from here: families by pattern, the rest from a table, the key itself otherwise.
|
||||
* The "_dll" twin of an installer (the direct DLL copy) shares the installer's name.
|
||||
*/
|
||||
object WinComponentNames {
|
||||
private val TABLE = mapOf(
|
||||
"oalinst" to "OpenAL", "XLiveRedist" to "Games for Windows Live", "gfw" to "Games for Windows Live",
|
||||
|
||||
@@ -19,23 +19,6 @@ import java.io.FileOutputStream
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.ZipInputStream
|
||||
|
||||
/**
|
||||
* Windows components (OpenAL, d3dx9, XAudio, VC++ DLLs...) for a game's Proton prefix, picked per
|
||||
* game, from Bannerlator's catalog (components.json on winlator-contents, Bottles' manifest format).
|
||||
*
|
||||
* Installing one runs its steps once, into the runtime: the archives it names are downloaded and
|
||||
* its DLLs copied to /opt/droiddeck/wincomponents/<name>/{system32,syswow64}, with component.json
|
||||
* holding its DLL overrides and the components it bundles. The picks go to the runtime as
|
||||
* ~/.config/droiddeck/wincomponents.json, and droiddeck-wincomponents copies the picked components
|
||||
* into the game's prefix at every launch (see that script for why every launch).
|
||||
*
|
||||
* A component whose installer is a Windows Installer package (.msi: XNA, PhysX, Games for Windows
|
||||
* Live, MSXML...) installs here too, without running it: droiddeck-msi-install reads the package's
|
||||
* tables in the runtime and lays out its files (Program Files, the .NET GAC, winsxs) and registry
|
||||
* values the way Wine's msiexec would, under the same store folder. One that runs any other
|
||||
* installer (.exe), unpacks a cabinet or edits the prefix's registry by itself is listed with the
|
||||
* reason it cannot be installed yet.
|
||||
*/
|
||||
object WinComponents {
|
||||
private const val TAG = "WinComponents"
|
||||
const val CATALOG_URL = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/components.json"
|
||||
@@ -43,46 +26,23 @@ object WinComponents {
|
||||
private const val GUEST_SELECTION = "root/.config/droiddeck/wincomponents.json"
|
||||
private const val STORE = "opt/droiddeck/wincomponents"
|
||||
private val ID = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
|
||||
// register_dll is left out on purpose: the DLLs it names are ones Wine ships and has registered
|
||||
// at the same path, so the native file at that path is the one the registration loads.
|
||||
private val FILE_STEPS = setOf("download_archive", "archive_extract", "copy_dll", "copy_file", "override_dll", "register_dll")
|
||||
private val INSTALLER_STEPS = setOf("install_exe", "install_msi")
|
||||
/**
|
||||
* Steps done here without any installer running: a Windows version or registry value for the
|
||||
* prefix (written by droiddeck-wincomponents with the rest), files picked out of a cabinet, and
|
||||
* "uninstall Wine Mono", which the mscoree override beside it already does for the game.
|
||||
*/
|
||||
private val OFFLINE_STEPS = setOf("set_windows", "set_register_key", "get_from_cab", "uninstall")
|
||||
/**
|
||||
* Installers that are their own setup program (NSIS, InnoSetup, IExpress scripts): nothing
|
||||
* inside them is a package to lay out, so they wait for a way to run them.
|
||||
*/
|
||||
private val RUNS_OWN_SETUP = setOf(
|
||||
"K-Lite", "ffdshow", "lavfilters702", "lavfilters741", "quicktime72", "dirac", "webview2", "aairruntime",
|
||||
"gfw", "ie8_kb2936068", "art2k7min", "vcredist6sp6", "VulkanRT", "jet40", "mdac28", "oalinst",
|
||||
"dotnet20", "dotnet20sp1", "dotnet35", "dotnet35sp1",
|
||||
)
|
||||
private const val MSI_INSTALL = "/usr/local/bin/droiddeck-msi-install"
|
||||
/** Where a downloaded package or installer waits for the installer, inside the runtime so it can read it. */
|
||||
private const val MSI_CACHE = "$STORE/.packages"
|
||||
/**
|
||||
* Catalog entries every Proton here already ships, which an install would only shadow: Wine
|
||||
* Gecko and Mono, the Chinese/Japanese/Korean fonts (Malgun, MS Gothic, YaHei, SimSun are in
|
||||
* share/fonts of Proton Experimental, GE-Proton and proton-cachyos alike), Wine's own
|
||||
* PowerShell wrapper and the Vulkan loader (vulkan-1.dll, 32- and 64-bit, in all three).
|
||||
*/
|
||||
private val PROTON_PROVIDES = setOf("gecko", "mono", "cjkfonts", "powershell", "VulkanRT")
|
||||
/** The keys the catalog nests under "environment" on a few .NET entries. */
|
||||
private val NESTED_KEYS = setOf("url", "file_name", "file_checksum", "file_size")
|
||||
|
||||
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
|
||||
|
||||
private val BACKGROUND = ThreadLocal<Boolean>()
|
||||
|
||||
/**
|
||||
* Runs [block] as background work: the runtime helpers an install starts on this thread run
|
||||
* at the lowest CPU and I/O priority (nice 19, ionice idle where the runtime has it).
|
||||
*/
|
||||
fun <T> background(block: () -> T): T {
|
||||
BACKGROUND.set(true)
|
||||
try { return block() } finally { BACKGROUND.remove() }
|
||||
@@ -101,58 +61,35 @@ object WinComponents {
|
||||
class Component(
|
||||
val name: String, val description: String, val provider: String, val status: String,
|
||||
val dependencies: List<String>, val steps: List<Step>,
|
||||
/**
|
||||
* A recording of what the component's own installer leaves in a prefix (winlator-contents'
|
||||
* component-snapshots release, made by tools/snapshot/record.py): the files it places and
|
||||
* the registry values it writes. With one, the installer never runs: the files come from
|
||||
* the archive beside the recording or out of the vendor's installer, the registry from the
|
||||
* recording. Empty for a component without one.
|
||||
*/
|
||||
val snapshot: String = "",
|
||||
)
|
||||
|
||||
enum class Support { READY, NEEDS_INSTALLER, UNSUPPORTED }
|
||||
|
||||
/** The two halves of an install the page shows one after the other, each 0..100. */
|
||||
enum class Phase { DOWNLOAD, INSTALL }
|
||||
|
||||
/** Progress: the component being worked on, what it is doing, the phase, 0..100 or -1 when unknown. */
|
||||
class Progress(val component: String, val stage: String, val phase: Phase, val percent: Int)
|
||||
|
||||
/** The percent a droiddeck-msi-install progress line carries ("progress 37% placing files"), or -1. */
|
||||
private val PERCENT_LINE = Regex("""^(\d{1,3})% (.*)$""")
|
||||
private fun engineLine(text: String): Pair<String, Int> =
|
||||
PERCENT_LINE.find(text)?.let { it.groupValues[2] to it.groupValues[1].toInt().coerceIn(0, 100) } ?: (text to -1)
|
||||
|
||||
/**
|
||||
* A step that installs a Windows Installer package, or an installer .exe that is a wrapper
|
||||
* around packages (a WiX bundle, a self-extracting cabinet or 7-Zip archive), which
|
||||
* droiddeck-msi-install lays out here without running it.
|
||||
*/
|
||||
private fun isPackage(step: Step): Boolean = step.action in INSTALLER_STEPS && step.str("url").startsWith("https://") &&
|
||||
(step.action == "install_msi" || listOf(step.str("file_name"), step.str("url").substringBefore('?'))
|
||||
.any { it.endsWith(".msi", ignoreCase = true) || it.endsWith(".exe", ignoreCase = true) })
|
||||
|
||||
/**
|
||||
* Catalog entries nothing here can use: the IE8 security update patches a browser no prefix
|
||||
* has; the OpenAL setup program is a twin of oalinst_dll, which copies the same DLLs; and
|
||||
* WebView2 can only be installed by running Microsoft's installer in the prefix (its files
|
||||
* sit in a container nothing opens and may not be hosted), which no runtime here does.
|
||||
*/
|
||||
private val POINTLESS = setOf("ie8_kb2936068", "oalinst", "webview2")
|
||||
|
||||
private fun protonProvides(name: String): Boolean = name in PROTON_PROVIDES || name in POINTLESS || name.startsWith("mono-")
|
||||
|
||||
fun hasSnapshot(c: Component): Boolean = c.snapshot.startsWith("https://github.com/") && c.snapshot.endsWith(".snapshot.json")
|
||||
|
||||
/** The steps a recording makes redundant: everything that places files or edits the registry. */
|
||||
private val SNAPSHOT_COVERS = INSTALLER_STEPS + setOf("download_archive", "archive_extract", "copy_dll", "copy_file") + OFFLINE_STEPS
|
||||
|
||||
fun fetch(): List<Component>? = Downloader.downloadString(CATALOG_URL)?.let { parse(it) }
|
||||
|
||||
private const val CATALOG_CACHE = "wincomponents-catalog.json"
|
||||
|
||||
/** The catalog from the network, kept for later; the copy kept last time when offline. */
|
||||
fun fetch(context: Context): List<Component>? {
|
||||
val cache = File(context.filesDir, CATALOG_CACHE)
|
||||
Downloader.downloadString(CATALOG_URL)?.let { body ->
|
||||
@@ -161,7 +98,6 @@ object WinComponents {
|
||||
return runCatching { parse(cache.readText()) }.getOrNull()
|
||||
}
|
||||
|
||||
/** The copy of the catalog kept by [fetch], without asking the network; null before the first fetch. */
|
||||
fun cached(context: Context): List<Component>? =
|
||||
runCatching { parse(File(context.filesDir, CATALOG_CACHE).readText()) }.getOrNull()
|
||||
|
||||
@@ -186,21 +122,14 @@ object WinComponents {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog entry that installs [name] here: the detector names installers
|
||||
* (vcredist2022, oalinst), and their DLL-copy twin (vcredist2022_dll, oalinst_dll) is the one
|
||||
* that installs without running anything; [name] itself when there is no such twin.
|
||||
*/
|
||||
fun installable(name: String, all: Map<String, Component>): String {
|
||||
val twin = all[if (name == "oalinst") "oalinst_dll" else "${name}_dll"]
|
||||
return if (twin != null && support(twin, all) == Support.READY) twin.name else name
|
||||
}
|
||||
|
||||
/** Whether [c] can be installed here, its bundled components included. */
|
||||
fun support(c: Component, all: Map<String, Component>, depth: Int = 0): Support {
|
||||
if (c.status != "ready" || depth > 8 || protonProvides(c.name)) return Support.UNSUPPORTED
|
||||
val installers = c.steps.filter { it.action in INSTALLER_STEPS }
|
||||
// A recording of the installer's result stands in for running it, whatever the steps say.
|
||||
if (hasSnapshot(c)) {
|
||||
return c.dependencies.map { all[it]?.let { d -> support(d, all, depth + 1) } ?: Support.UNSUPPORTED }
|
||||
.maxOrNull() ?: Support.READY
|
||||
@@ -219,7 +148,6 @@ object WinComponents {
|
||||
}
|
||||
|
||||
private fun fileStepOk(step: Step): Boolean = when (step.action) {
|
||||
// An .exe or .cab archive (DirectX's redistributable) is opened by the runtime's tools.
|
||||
"download_archive", "archive_extract" -> step.str("url").let { url ->
|
||||
!url.startsWith("http") || url.startsWith("https://github.com/") &&
|
||||
url.substringBefore('?').lowercase().let { it.endsWith(".tar.xz") || it.endsWith(".zip") || it.endsWith(".exe") || it.endsWith(".cab") }
|
||||
@@ -228,20 +156,14 @@ object WinComponents {
|
||||
else -> true
|
||||
}
|
||||
|
||||
/** The installed version of a component, or null. */
|
||||
fun installed(context: Context, id: String): String? = runCatching {
|
||||
JSONObject(File(LinuxRuntime.rootDir(context), "$STORE/$id/component.json").readText()).optString("version", "?")
|
||||
}.getOrNull()
|
||||
|
||||
/** Every component in the runtime, by id. */
|
||||
fun installedIds(context: Context): List<String> =
|
||||
File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
|
||||
.orEmpty().map { it.name }.filter { installed(context, it) != null }.sorted()
|
||||
|
||||
/**
|
||||
* Installs [c] and the components it bundles that are not installed yet. [onProgress] gets a
|
||||
* line for the step and 0..100 (or -1). Returns null on success, else a message.
|
||||
*/
|
||||
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
|
||||
if (support(c, all) != Support.READY) return "${c.name} cannot be installed here yet"
|
||||
val order = ArrayList<Component>()
|
||||
@@ -251,8 +173,6 @@ object WinComponents {
|
||||
if (x.name == c.name || installed(context, x.name) == null) order.add(x)
|
||||
}
|
||||
visit(c, 0)
|
||||
// One download per archive however many components copy out of it (DirectMusic's eleven
|
||||
// parts all come from dxnt, 100 MB).
|
||||
val work = File(context.cacheDir, "wincomponents").apply { FileUtils.delete(this); mkdirs() }
|
||||
val archives = HashMap<String, File>()
|
||||
return try {
|
||||
@@ -276,10 +196,7 @@ object WinComponents {
|
||||
val overrides = ArrayList<String>()
|
||||
var source: File? = null
|
||||
var msi: JSONObject? = null
|
||||
// The registry values the steps themselves set (a Windows version, a key), beside the packages'.
|
||||
val registry = ArrayList<JSONObject>()
|
||||
// Archives the runtime's tools opened (installer .exe, cabinets), by the name the catalog
|
||||
// calls them, and the folders they were opened into; cleaned up at the end.
|
||||
val runtimeArchives = HashMap<String, File>()
|
||||
val runtimeDirs = ArrayList<File>()
|
||||
val cabs = HashMap<String, File>()
|
||||
@@ -293,8 +210,6 @@ object WinComponents {
|
||||
for (step in c.steps) when {
|
||||
hasSnapshot(c) && step.action in SNAPSHOT_COVERS -> Unit
|
||||
else -> when (step.action) {
|
||||
// A component may have several packages (PowerShell's 32- and 64-bit): each adds to the
|
||||
// same folder, the first one names the component.
|
||||
"install_msi", "install_exe" -> {
|
||||
val (result, problem) = installPackage(context, c, step, staging, onProgress)
|
||||
if (result == null) return problem
|
||||
@@ -303,15 +218,12 @@ object WinComponents {
|
||||
result.optJSONArray("notes")?.let { for (i in 0 until it.length()) notes.put(it.get(i)) }
|
||||
} ?: result
|
||||
}
|
||||
// A catalog step that makes room for the installer's own copy; ours is copied anyway.
|
||||
"delete_dlls" -> Unit
|
||||
"download_archive", "archive_extract" -> {
|
||||
val url = step.str("url")
|
||||
if (!url.startsWith("http")) continue
|
||||
source = archives[url] ?: run {
|
||||
val name = url.substringBefore('?').substringAfterLast('/')
|
||||
// A zip or tar.xz is opened here; an .exe or .cab by the runtime's tools, so it
|
||||
// is downloaded where the runtime can read it and kept for get_from_cab steps.
|
||||
val byRuntime = name.lowercase().let { it.endsWith(".exe") || it.endsWith(".cab") }
|
||||
val file = if (byRuntime) File(root, "$MSI_CACHE/${archives.size}-$name").apply { parentFile?.mkdirs() }
|
||||
else File(work, "${archives.size}-$name")
|
||||
@@ -333,8 +245,6 @@ object WinComponents {
|
||||
dir.also { archives[url] = it }
|
||||
}
|
||||
}
|
||||
// Files picked out of a cabinet: one the catalog downloaded (DirectX's redistributable,
|
||||
// a self-extracting cabinet), or cabinets an earlier pick put under temp/.
|
||||
"get_from_cab" -> {
|
||||
val pattern = step.str("source")
|
||||
val containers = runtimeArchives[pattern]?.let { listOf(it) } ?: run {
|
||||
@@ -362,7 +272,6 @@ object WinComponents {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The Windows version a game sees: HKCU\Software\Wine "Version", the last word wins.
|
||||
"set_windows" -> step.str("version").takeIf { it.isNotEmpty() }?.let { version ->
|
||||
registry.removeAll { it.optString("key") == "Software\\Wine" && it.optString("name") == "Version" }
|
||||
registry += JSONObject().put("hive", "HKCU").put("key", "Software\\Wine").put("name", "Version").put("type", "sz").put("data", version)
|
||||
@@ -385,8 +294,6 @@ object WinComponents {
|
||||
}
|
||||
registry += value
|
||||
}
|
||||
// "Uninstall Wine Mono" before a real .NET Framework: the mscoree override the catalog
|
||||
// sets beside it is what takes Mono out of the game's way; nothing to remove here.
|
||||
"uninstall" -> Unit
|
||||
"copy_dll", "copy_file" -> {
|
||||
val from = source ?: return "a copy step before any archive"
|
||||
@@ -424,7 +331,6 @@ object WinComponents {
|
||||
FileUtils.delete(temp)
|
||||
}
|
||||
if (registry.isNotEmpty()) {
|
||||
// The packages' values are already in registry.json; the steps' own go after them.
|
||||
val file = File(staging, "registry.json")
|
||||
val values = runCatching { JSONObject(file.readText()).optJSONArray("values") }.getOrNull() ?: JSONArray()
|
||||
registry.forEach { values.put(it) }
|
||||
@@ -444,13 +350,6 @@ object WinComponents {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays the component out from its recording: downloads the snapshot, then its files (the
|
||||
* archive beside it when the recording carries them, else out of the vendor's installer by
|
||||
* the paths the recording maps, small generated ones inline) into [staging]/drive_c, and the
|
||||
* recorded registry values into registry.json. Returns a result like the MSI engine's, or
|
||||
* null and why.
|
||||
*/
|
||||
private fun installSnapshot(context: Context, c: Component, staging: File, work: File, onProgress: (Progress) -> Unit): Pair<JSONObject?, String> {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val name = c.snapshot.substringAfterLast('/')
|
||||
@@ -481,7 +380,6 @@ object WinComponents {
|
||||
file.delete()
|
||||
placed = drive.walkTopDown().count { it.isFile }
|
||||
} else {
|
||||
// The files come out of the installer the catalog names, by the paths the recording maps.
|
||||
val step = c.steps.firstOrNull { it.action in INSTALLER_STEPS && it.str("url").startsWith("https://") }
|
||||
?: return null to "the recording needs the installer, which the catalog does not name"
|
||||
val url = step.str("url")
|
||||
@@ -532,14 +430,9 @@ object WinComponents {
|
||||
.put("notes", JSONArray(notes + listOfNotNull(installerVersion.takeIf { it.isNotEmpty() }?.let { "recorded from $it on ${snapshot.optString("wine")}" }))) to ""
|
||||
}
|
||||
|
||||
/** The regex for a catalog file pattern: * matches anything, case does not matter. */
|
||||
private fun globRegex(pattern: String) =
|
||||
Regex("^" + pattern.split("*").joinToString(".*") { Regex.escape(it) } + "$", RegexOption.IGNORE_CASE)
|
||||
|
||||
/**
|
||||
* Has the runtime's tools open [archive] (an installer .exe, a cabinet, a self-extracting
|
||||
* one) into a folder of the package cache called [tag]; that folder, or null and a log line.
|
||||
*/
|
||||
private fun unpackInRuntime(context: Context, c: Component, archive: File, tag: String, onProgress: (Progress) -> Unit): File? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val cache = File(root, MSI_CACHE)
|
||||
@@ -563,12 +456,6 @@ object WinComponents {
|
||||
return dir
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads the component's package (.msi) or installer (.exe) into the runtime and has
|
||||
* droiddeck-msi-install lay it out in [staging]. Returns the installer's result (product,
|
||||
* version, counts, notes), or null and why. Everything the installer prints also goes to
|
||||
* files/logs/tools.
|
||||
*/
|
||||
private fun installPackage(context: Context, c: Component, step: Step, staging: File, onProgress: (Progress) -> Unit): Pair<JSONObject?, String> {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val url = step.str("url")
|
||||
@@ -641,10 +528,6 @@ object WinComponents {
|
||||
Log.w(TAG, "extract ${archive.name}", e); false
|
||||
}
|
||||
|
||||
/**
|
||||
* Bannerlator's rule: the manifest's own temp paths are Bottles', so the files are found by name
|
||||
* anywhere in the unpacked tree, preferring the ones under the matching win32/win64 folder.
|
||||
*/
|
||||
private fun copyMatching(srcRoot: File, pattern: String, dest: File, arch: String?) {
|
||||
if (pattern.isEmpty()) return
|
||||
val rx = Regex("^" + pattern.split("*").joinToString(".*") { Regex.escape(it) } + "$", RegexOption.IGNORE_CASE)
|
||||
@@ -658,7 +541,6 @@ object WinComponents {
|
||||
matches.forEach { f -> f.copyTo(File(dest, f.name.lowercase()), overwrite = true) }
|
||||
}
|
||||
|
||||
/** Removes a component from the runtime and from every game's picks. */
|
||||
@Synchronized
|
||||
fun uninstall(context: Context, id: String) {
|
||||
require(validId(id))
|
||||
@@ -666,17 +548,8 @@ object WinComponents {
|
||||
save(context, selections(context).mapValues { (_, sel) -> Selection(sel.auto - id, sel.user - id) })
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a component was turned on for a game by itself ([setAuto]): [kind] says whose list it came
|
||||
* from (see AutoComponents), [args] what the reason line names. Kept beside the picks.
|
||||
*/
|
||||
class AutoReason(val kind: String, val args: List<String>)
|
||||
|
||||
/**
|
||||
* Everything kept per game, by the appid its prefix is named after: [auto] - turned on by
|
||||
* itself, with its reason; [user] - a switch the user pressed (true on, false off), which wins
|
||||
* over [auto] either way. What the launch reads is [effective].
|
||||
*/
|
||||
class Selection(val auto: Map<String, AutoReason>, val user: Map<String, Boolean>) {
|
||||
val effective: List<String>
|
||||
get() = (auto.keys.filter { user[it] != false } + user.filterValues { it }.keys).distinct()
|
||||
@@ -697,7 +570,6 @@ object WinComponents {
|
||||
AutoReason(r.optString("kind"), (0 until a.length()).map { a.optString(it) })
|
||||
}
|
||||
}.orEmpty()
|
||||
// Before there were overrides, every pick was the user's own.
|
||||
val user = if (users == null) games.optJSONArray(app)?.let { ids -> (0 until ids.length()).map { ids.getString(it) }.filter { validId(it) }.associateWith { true } }.orEmpty()
|
||||
else users.optJSONObject(app)?.let { o -> o.keys().asSequence().filter { validId(it) }.associateWith { o.optBoolean(it) } }.orEmpty()
|
||||
Selection(auto, user)
|
||||
@@ -706,7 +578,6 @@ object WinComponents {
|
||||
emptyMap()
|
||||
}
|
||||
|
||||
/** Each game's picks as the launch takes them, by the appid its prefix is named after. */
|
||||
fun read(context: Context): Map<String, List<String>> =
|
||||
selections(context).mapValues { it.value.effective }.filterValues { it.isNotEmpty() }
|
||||
|
||||
@@ -714,7 +585,6 @@ object WinComponents {
|
||||
|
||||
fun selection(context: Context, appKey: String): Selection = selections(context)[appKey] ?: Selection(emptyMap(), emptyMap())
|
||||
|
||||
/** The user's own switch for [id] in [appKey]: on or off, over whatever was picked by itself. */
|
||||
@Synchronized
|
||||
fun setUser(context: Context, appKey: String, id: String, on: Boolean) {
|
||||
require(validId(id))
|
||||
@@ -724,7 +594,6 @@ object WinComponents {
|
||||
save(context, all)
|
||||
}
|
||||
|
||||
/** The components picked by themselves for [appKey], replacing the earlier ones; the user's switches stay. */
|
||||
@Synchronized
|
||||
fun setAuto(context: Context, appKey: String, auto: Map<String, AutoReason>) {
|
||||
require(auto.keys.all { validId(it) })
|
||||
@@ -734,7 +603,6 @@ object WinComponents {
|
||||
save(context, all)
|
||||
}
|
||||
|
||||
/** The user's picks for [appKey] set outright (each listed on, every other user switch dropped). */
|
||||
@Synchronized
|
||||
fun setPicks(context: Context, appKey: String, ids: List<String>) {
|
||||
require(ids.all { validId(it) })
|
||||
@@ -746,7 +614,6 @@ object WinComponents {
|
||||
|
||||
private fun save(context: Context, games: Map<String, Selection>) {
|
||||
val kept = games.filterValues { it.auto.isNotEmpty() || it.user.isNotEmpty() }
|
||||
// Version 1 still: droiddeck-wincomponents reads "games" and ignores the rest.
|
||||
val text = JSONObject().put("version", 1)
|
||||
.put("games", JSONObject().apply { kept.forEach { (app, sel) -> sel.effective.takeIf { it.isNotEmpty() }?.let { put(app, JSONArray(it)) } } })
|
||||
.put("auto", JSONObject().apply {
|
||||
@@ -762,11 +629,6 @@ object WinComponents {
|
||||
publish(context, text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the picks where the launch script reads them; SessionFiles calls this at every session
|
||||
* start too, so a runtime reinstalled since keeps them. An empty selection still writes a file,
|
||||
* which is how a component turned off for every game is taken out of their prefixes.
|
||||
*/
|
||||
@Synchronized
|
||||
fun publish(context: Context, text: String? = null) {
|
||||
val body = text ?: runCatching { AtomicFile(File(context.filesDir, SELECTION)).readFully().toString(Charsets.UTF_8) }.getOrNull() ?: return
|
||||
|
||||
Reference in new issue
Block a user