fix(input): reconcile the second-screen picker

This commit is contained in:
Kurt Himebauch committed 2026-11-20 07:30:42 -05:00
commit ec1d5126c4
197 files changed
+12209 -3764

No files matched your search

@@ -282,6 +282,8 @@ object ComponentsManager {
if (parts.size > 1) parts[1] else parts.firstOrNull()?.ifEmpty { null } ?: "unknown"
}.getOrDefault("unknown")
internal fun isProtonTree(dir: File): Boolean = File(dir, WINE).isDirectory && File(dir, "proton").isFile
fun protons(context: Context): List<Proton> {
val found = LinkedHashMap<String, Proton>()
val bases = listOf(File(steam(context), "compatibilitytools.d") to false) +
@@ -290,7 +292,7 @@ object ComponentsManager {
for ((base, valve) in bases) {
val entries = base.listFiles()?.sortedBy { it.name } ?: continue
for (dir in entries) {
if (!File(dir, WINE).isDirectory || !File(dir, "proton").isFile) continue
if (!isProtonTree(dir)) continue
val real = runCatching { dir.canonicalPath }.getOrDefault(dir.path)
if (found.containsKey(real)) continue
val guest = if (dir.absolutePath.startsWith(rootPath)) dir.absolutePath.removePrefix(rootPath) else dir.absolutePath
@@ -900,15 +902,26 @@ object ComponentsManager {
}
}
fun forgetProton(context: Context, dirName: String) {
synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
if (selected && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return
File(originalsDir(context), id).deleteRecursively()
}
fun forgetProton(context: Context, dirName: String): Boolean = synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return true
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
val published = File(launchDir(context), "desired.tsv")
val listed = published.takeIf { it.isFile }
?.useLines { rows -> rows.any { it.split('\t').getOrNull(1) == dirName } } == true
if ((selected || listed) && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return false
val originals = File(originalsDir(context), id)
val store = File(launchDir(context), "store")
val used = published.takeIf { it.isFile }?.useLines { rows ->
rows.mapNotNull { it.substringAfterLast('\t').substringAfter("/store/", "").substringBefore('/').ifEmpty { null } }.toSet()
}.orEmpty()
val unpacked = originals.listFiles().orEmpty().flatMap { version ->
version.listFiles().orEmpty().map { File(store, "original-$id-${version.name}-${it.name.removeSuffix(".wcp")}") }
}.filter { it.name !in used }
if (unpacked.any { File(it, ".complete").delete(); !it.deleteRecursively() && it.exists() }) return false
originals.deleteRecursively()
true
}
private fun storePackage(context: Context, part: File, dest: File) {
@@ -708,10 +708,10 @@ internal object EnhancedSessionLogShare {
}
val logs = LinuxRuntime.logDir(context)
for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) {
val scan = directFiles(root, remaining(maxFiles, out.size))
val scan = directFiles(root, STORE_LOG_SCAN)
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) }
scan.files.filter { recent(it) }.sortedByDescending { it.lastModified() }.take(remaining(maxFiles, out.size))
.forEach { add(it, root, "$name/${it.name}", name) }
}
if (legacy) {
@@ -965,6 +965,7 @@ internal object EnhancedSessionLogShare {
"events.jsonl", "memory.csv", "capture.json", "crash.log",
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val STORE_LOG_SCAN = 512
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
@@ -0,0 +1,412 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.StatFs
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermission
import java.security.DigestOutputStream
import java.security.MessageDigest
import java.util.zip.ZipFile
import org.apache.commons.compress.archivers.sevenz.SevenZFile
import org.apache.commons.compress.archivers.zip.ZipFile as CommonsZipFile
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.deleteRecursively
import org.json.JSONArray
import org.json.JSONObject
object ExperimentalProtons {
private const val TAG = "ExperimentalProtons"
const val PREFIX = "Experimental-"
private const val MARKER = ".droiddeck-experimental.json"
private const val STAGING = ".droiddeck-experimental"
private const val BACKUPS = ".droiddeck-experimental-old"
private const val INCOMING = ".droiddeck-experimental-new"
private const val REMOVED = ".droiddeck-experimental-gone"
private const val GUEST_TOOLS = "/root/.local/share/Steam/compatibilitytools.d"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val USER_SETTINGS = "user_settings.py"
internal val TARBALL = Regex("(?i)\\.tar(\\.(gz|xz|zst|bz2))?$")
internal val FOREIGN_ARCH = Regex("(?i)(^|[^a-z0-9])(x86|x64|amd64|i[3-6]86)([^a-z0-9]|$)")
private val DOWNLOAD_PREFIX = "droiddeck-"
data class Installed(val dir: String, val label: String, val source: String, val releaseTag: String? = null)
data class Release(val tag: String, val asset: String, val url: String, val sha512: String?, val size: Long, val name: String = tag)
enum class ArchiveType { ZIP, SEVEN_Z, TAR, UNKNOWN }
private fun toolsDir(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_TOOLS.removePrefix("/"))
fun installed(context: Context): List<Installed> =
toolsDir(context).listFiles()
?.filter { it.isDirectory && File(it, MARKER).isFile }
?.map { dir ->
val info = runCatching { JSONObject(File(dir, MARKER).readText()) }.getOrDefault(JSONObject())
Installed(dir.name, info.optString("label").ifEmpty { dir.name }, info.optString("source"), info.optString("releaseTag").ifEmpty { null })
}
?.sortedBy { it.dir }
?: emptyList()
fun remove(context: Context, dir: String): Boolean {
val tools = toolsDir(context)
val target = File(tools, dir)
if (!File(target, MARKER).isFile) return false
val doomed = File(File(tools, REMOVED).apply { mkdirs() }, dir)
if (!deleteTree(doomed)) return false
val detached = synchronized(SessionState.startLock) { !SessionState.running && target.renameTo(doomed) }
if (!detached) return false
ComponentsManager.forgetProton(context, dir)
deleteTree(doomed)
deleteTree(File(File(tools, BACKUPS), dir))
deleteTree(File(File(tools, INCOMING), dir))
return true
}
internal fun dirName(tree: String, label: String?): String {
val base = ComponentsManager.safeName(tree)
val tag = label?.let(ComponentsManager::safeName)?.takeIf { it != "unnamed" && !base.contains(it, ignoreCase = true) }
return PREFIX + base + (tag?.let { "-$it" } ?: "")
}
fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) {
reconcile(context, fetched)
if (fetched.complete) removeStaleDownloads(context, fetched.releases.tags())
}
return rows
}
private fun JSONArray.tags(): Set<String> = (0 until length()).mapNotNull { optJSONObject(it)?.optString("tag_name")?.takeIf(String::isNotEmpty) }.toSet()
internal fun removeStaleDownloads(context: Context, availableTags: Set<String>) {
val downloads = File(context.filesDir, "proton-downloads")
downloads.listFiles()?.filter { file ->
file.isFile && file.name.startsWith(DOWNLOAD_PREFIX) && availableTags.none { tag -> file.name.startsWith("$DOWNLOAD_PREFIX${ComponentsManager.safeName(tag)}-") }
}?.forEach { it.delete() }
}
internal fun available(releases: List<Release>, installed: List<Installed>): List<Release> =
releases.filter { release -> installed.none { it.releaseTag == release.tag } }
internal fun shouldRemove(installedReleaseTag: String?, fetched: ProtonExtras.ReleaseFetch, gone: (String) -> Boolean): Boolean {
val tag = installedReleaseTag ?: return false
val release = (0 until fetched.releases.length()).asSequence()
.mapNotNull { fetched.releases.optJSONObject(it) }
.firstOrNull { it.optString("tag_name") == tag }
return if (release != null) !release.optBoolean("prerelease", false) else fetched.complete && gone(tag)
}
internal fun reconcile(
context: Context,
fetched: ProtonExtras.ReleaseFetch,
gone: (String) -> Boolean = { tag -> ProtonExtras.releaseGone(ProtonExtras.tools.first { it.id == ProtonExtras.OWN }, tag) },
) {
for (build in installed(context)) {
if (SessionState.running) return
if (shouldRemove(build.releaseTag, fetched, gone)) remove(context, build.dir)
}
}
internal fun compatVdf(name: String): String = """"compatibilitytools"
{
"compat_tools"
{
"$name"
{
"install_path" "."
"display_name" "$name"
"from_oslist" "windows"
"to_oslist" "linux"
}
}
}
"""
fun installFromFile(context: Context, file: File, onProgress: (String, Int) -> Unit): String? {
preflight(context)?.let { return it }
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + file.length()) {
return context.getString(R.string.xproton_no_space)
}
return install(context, file, fileLabel(file.name), file.name, null, onProgress, false)
}
internal fun fileLabel(name: String): String =
if (TARBALL.containsMatchIn(name)) name.replace(TARBALL, "") else name.substringBeforeLast('.')
fun installRelease(context: Context, release: Release, onProgress: (String, Int) -> Unit): String? {
preflight(context)?.let { return it }
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "droiddeck-${ComponentsManager.safeName(release.tag)}-${release.asset}")
if (release.size > 0 && archive.length() > release.size) archive.delete()
val missing = (release.size - archive.length()).coerceAtLeast(0L)
val copyBytes = if (sameFileStore(archive, toolsDir(context))) 0L else release.size
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing + copyBytes) return context.getString(R.string.xproton_no_space)
val title = context.getString(R.string.pextra_downloading, "Proton", release.tag)
onProgress(title, 0)
if (!Downloader.downloadFile(release.url, archive, true) { fraction ->
onProgress(title, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
}) return context.getString(R.string.pextra_download_failed)
if (release.size > 0 && archive.length() != release.size) return context.getString(R.string.pextra_incomplete)
if (release.sha512 != null) {
val expected = Downloader.downloadDirect(release.sha512)?.let(::checksumIn)
?: return context.getString(R.string.pextra_checksum_unreadable)
if (!expected.equals(Hashes.sha512(archive), true)) {
archive.delete()
return context.getString(R.string.pextra_checksum_mismatch)
}
}
return try { install(context, archive, release.tag, release.tag, release.tag, onProgress, true) }
finally { archive.delete() }
}
private fun sameFileStore(file: File, directory: File): Boolean = runCatching {
directory.mkdirs()
Files.getFileStore((file.takeIf(File::exists) ?: file.parentFile).toPath()) == Files.getFileStore(directory.toPath())
}.getOrDefault(false)
private fun preflight(context: Context): String? = when {
SessionState.running -> context.getString(R.string.pextra_stop_session)
!LinuxRuntime.isInstalled(context) -> context.getString(R.string.user_apps_runtime_required)
else -> null
}
private fun install(context: Context, archive: File, label: String, source: String, releaseTag: String?, onProgress: (String, Int) -> Unit, downloaded: Boolean): String? {
val tools = toolsDir(context).apply { mkdirs() }
val staging = File(tools, STAGING)
val forget = { name: String -> ComponentsManager.forgetProton(context, name) }
restoreInterrupted(tools, forget)
deleteTree(staging)
staging.mkdirs()
try {
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, LinuxRuntime.rootDir(context))
onProgress(context.getString(R.string.xproton_unpacking), -1)
val unpacked = File(staging, "unpacked").apply { mkdirs() }
val type = archiveType(archive)
if (SessionState.running) return context.getString(R.string.pextra_session_started)
onProgress(context.getString(R.string.xproton_unpacking), -1)
when (type) {
ArchiveType.ZIP -> {
val tarball = extractTarball(archive, staging)
if (tarball == null) {
extractDirect(archive, unpacked, ArchiveType.ZIP)
} else {
val status = runGuest(context, listOf("tar", "-xf", "$GUEST_TOOLS/$STAGING/${tarball.name}", "-C", "$GUEST_TOOLS/$STAGING/unpacked"))
tarball.delete()
if (status != 0) return context.getString(R.string.xproton_untar_failed, status)
}
}
ArchiveType.SEVEN_Z -> extractDirect(archive, unpacked, ArchiveType.SEVEN_Z)
ArchiveType.TAR -> {
val stagedArchive = File(staging, archive.name)
if (!archive.canonicalFile.equals(stagedArchive.canonicalFile) && !(downloaded && archive.renameTo(stagedArchive))) {
archive.copyTo(stagedArchive, overwrite = true)
}
val status = runGuest(context, listOf("tar", "-xf", "$GUEST_TOOLS/$STAGING/${stagedArchive.name}", "-C", "$GUEST_TOOLS/$STAGING/unpacked"))
if (status != 0) return context.getString(R.string.xproton_untar_failed, status)
}
ArchiveType.UNKNOWN -> return context.getString(R.string.xproton_archive_invalid)
}
val tree = buildTree(unpacked) ?: return context.getString(R.string.xproton_no_tree)
val name = dirName(tree.name, label)
ownFile(tree, "compatibilitytool.vdf").writeText(compatVdf(name))
ownFile(tree, MARKER).writeText(
JSONObject().put("label", name).put("source", source).putOpt("releaseTag", releaseTag).put("at", System.currentTimeMillis() / 1000).toString(),
)
val final = File(tools, name)
val settings = File(final, USER_SETTINGS)
if (Files.isRegularFile(settings.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
settings.copyTo(ownFile(tree, USER_SETTINGS))
}
if (!placeTree(tree, tools, name, forget)) return context.getString(R.string.xproton_place_failed)
onProgress(context.getString(R.string.pextra_installing, name), -1)
runGuest(context, listOf("steam-compatibility", "/root/.local/share/Steam"))
return null
} catch (e: Exception) {
Log.e(TAG, "install $source", e)
return if (e is UnsafeArchiveException) context.getString(R.string.xproton_archive_unsafe) else context.getString(R.string.xproton_archive_invalid)
} finally {
deleteTree(staging)
}
}
internal fun buildTree(unpacked: File): File? {
val root = unpacked.canonicalFile
return unpacked.listFiles()?.sortedBy { it.name }?.firstOrNull {
!Files.isSymbolicLink(it.toPath()) && it.isDirectory && it.canonicalFile.parentFile == root &&
Files.isRegularFile(File(it, "toolmanifest.vdf").toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS) &&
ComponentsManager.isProtonTree(it)
}
}
@OptIn(ExperimentalPathApi::class)
internal fun deleteTree(dir: File): Boolean =
runCatching { dir.toPath().deleteRecursively() }.onFailure { Log.w(TAG, "delete $dir", it) }.isSuccess && !Files.exists(dir.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)
internal fun ownFile(tree: File, name: String): File {
val file = File(tree, name)
Files.deleteIfExists(file.toPath())
return file
}
internal fun placeTree(tree: File, tools: File, name: String, forget: (String) -> Boolean): Boolean {
val incoming = File(File(tools, INCOMING).apply { mkdirs() }, name)
if (!deleteTree(incoming) || !tree.renameTo(incoming)) return false
return finishPlacing(tools, name, forget)
}
private fun finishPlacing(tools: File, name: String, forget: (String) -> Boolean): Boolean {
val incoming = File(File(tools, INCOMING), name)
val final = File(tools, name)
val backup = File(File(tools, BACKUPS).apply { mkdirs() }, name)
val moved = !final.exists() || (deleteTree(backup) && final.renameTo(backup))
val placed = moved && (!backup.exists() || forget(name)) && incoming.renameTo(final)
if (!placed) {
if (!final.exists()) backup.renameTo(final)
deleteTree(incoming)
}
if (final.exists()) deleteTree(backup)
return placed
}
internal fun restoreInterrupted(tools: File, forget: (String) -> Boolean) {
deleteTree(File(tools, REMOVED))
File(tools, INCOMING).listFiles()?.forEach { finishPlacing(tools, it.name, forget) }
File(tools, BACKUPS).listFiles()?.forEach { if (File(tools, it.name).exists()) deleteTree(it) else it.renameTo(File(tools, it.name)) }
}
internal fun archiveType(file: File): ArchiveType {
val head = runCatching { file.inputStream().use { ByteArray(300).also { b -> it.read(b) } } }.getOrNull() ?: return ArchiveType.UNKNOWN
fun at(i: Int, vararg bytes: Int) = bytes.indices.all { head.getOrNull(i + it) == bytes[it].toByte() }
return when {
at(0, 0x50, 0x4B) -> ArchiveType.ZIP
at(0, 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> ArchiveType.SEVEN_Z
at(0, 0x1F, 0x8B) || at(0, 0x42, 0x5A, 0x68) || at(0, 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00) || at(0, 0x28, 0xB5, 0x2F, 0xFD) || at(257, 0x75, 0x73, 0x74, 0x61, 0x72) -> ArchiveType.TAR
else -> ArchiveType.UNKNOWN
}
}
private fun extractTarball(zip: File, into: File): File? = ZipFile(zip).use { z ->
val entries = z.entries().toList().filter { !it.isDirectory }
val entry = entries.filter { TARBALL.containsMatchIn(it.name) }.maxByOrNull { it.size } ?: return null
val name = File(entry.name).name
val sums = checksumEntry(entries.map { it.name }, name)?.let { checksumName -> entries.first { it.name == checksumName } }
val expected = sums?.let { e ->
z.getInputStream(e).use { checksumIn(it.readBytes().decodeToString()) }
?: throw IllegalStateException("${File(e.name).name} holds no SHA-512 checksum")
}
val out = File(into, name)
val digest = MessageDigest.getInstance("SHA-512")
z.getInputStream(entry).use { input -> DigestOutputStream(FileOutputStream(out), digest).use { input.copyTo(it, 1 shl 16) } }
if (expected != null && !expected.equals(digest.digest().joinToString("") { "%02x".format(it) }, ignoreCase = true)) {
out.delete()
throw IllegalStateException("Checksum mismatch in $name")
}
out
}
internal class UnsafeArchiveException : Exception()
internal fun extractDirect(archive: File, into: File, type: ArchiveType) {
val root = into.toPath().toAbsolutePath().normalize()
fun target(name: String): File {
val clean = name.replace('\\', '/')
val parts = clean.split('/')
if (clean.startsWith('/') || parts.any { it == ".." }) throw UnsafeArchiveException()
val path = root.resolve(clean).normalize()
if (!path.startsWith(root)) throw UnsafeArchiveException()
var parent = path.parent
while (parent != null && parent.startsWith(root) && parent != root) {
if (Files.isSymbolicLink(parent)) throw UnsafeArchiveException()
parent = parent.parent
}
return path.toFile()
}
fun applyMode(file: File, mode: Int) {
val permissions = mutableSetOf<PosixFilePermission>()
if (mode and 0x100 != 0) permissions += PosixFilePermission.OWNER_READ
if (mode and 0x80 != 0) permissions += PosixFilePermission.OWNER_WRITE
if (mode and 0x40 != 0) permissions += PosixFilePermission.OWNER_EXECUTE
if (mode and 0x20 != 0) permissions += PosixFilePermission.GROUP_READ
if (mode and 0x10 != 0) permissions += PosixFilePermission.GROUP_WRITE
if (mode and 0x08 != 0) permissions += PosixFilePermission.GROUP_EXECUTE
if (mode and 0x04 != 0) permissions += PosixFilePermission.OTHERS_READ
if (mode and 0x02 != 0) permissions += PosixFilePermission.OTHERS_WRITE
if (mode and 0x01 != 0) permissions += PosixFilePermission.OTHERS_EXECUTE
if (permissions.isNotEmpty()) Files.setPosixFilePermissions(file.toPath(), permissions)
}
val directoryModes = mutableListOf<Pair<File, Int>>()
fun place(name: String, mode: Int, directory: Boolean, content: () -> InputStream) {
val file = target(name)
when {
mode and 0xF000 == 0xA000 -> {
val link = content().use { it.readBytes().decodeToString() }
val parent = file.parentFile ?: throw UnsafeArchiveException()
val climbsLater = link.split('/').filter { it != "." }.dropWhile { it == ".." }.any { it == ".." }
if (link.startsWith('/') || climbsLater || !parent.toPath().resolve(link).normalize().startsWith(root)) throw UnsafeArchiveException()
parent.mkdirs()
Files.deleteIfExists(file.toPath())
Files.createSymbolicLink(file.toPath(), java.nio.file.Paths.get(link))
}
directory -> {
file.mkdirs()
directoryModes += file to mode
}
else -> {
if (Files.isSymbolicLink(file.toPath())) throw UnsafeArchiveException()
file.parentFile?.mkdirs()
content().use { input -> file.outputStream().use { output -> input.copyTo(output, 1 shl 16) } }
applyMode(file, mode)
}
}
}
when (type) {
ArchiveType.ZIP -> CommonsZipFile.builder().setFile(archive).get().use { zip ->
for (entry in zip.entries) place(entry.name, entry.unixMode, entry.isDirectory) { zip.getInputStream(entry) }
}
ArchiveType.SEVEN_Z -> Files.newByteChannel(archive.toPath()).use { channel ->
SevenZFile.builder().setSeekableByteChannel(channel).get().use { seven ->
for (entry in seven.entries) {
val unix = entry.hasWindowsAttributes && entry.windowsAttributes and 0x8000 != 0
place(entry.name, if (unix) entry.windowsAttributes ushr 16 else 0, entry.isDirectory) { seven.getInputStream(entry) }
}
}
}
else -> error("Unsupported direct archive")
}
directoryModes.sortedByDescending { it.first.path.length }.forEach { (directory, mode) -> applyMode(directory, mode) }
}
internal fun checksumIn(text: String): String? = Regex("(?i)\\b[0-9a-f]{128}\\b").find(text)?.value
internal fun checksumEntry(entries: List<String>, tarball: String): String? {
val stem = tarball.substringBefore(".tar")
return entries.firstOrNull {
val name = File(it).name
!TARBALL.containsMatchIn(name) && (name.startsWith("$tarball.") || name.startsWith("$stem.")) && name.contains("sha512", true)
}
}
private fun runGuest(context: Context, command: List<String>): Int {
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
) + command
val child = ProtonExtras.guestProcess(context, guest).start()
child.inputStream.bufferedReader().useLines { lines -> lines.forEach { Log.i(TAG, it) } }
return child.waitFor()
}
}
@@ -25,7 +25,7 @@ object GameSaves {
fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app)
}
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>) {
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>, val root: String? = null) {
val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true
}
@@ -36,7 +36,28 @@ object GameSaves {
fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves")
private fun backupsDir(): File = File(savesDir(), "backups")
fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList())
fun game(context: Context, game: Library.SteamGame): Game {
val root = if (ubisoft(game)) ubisoftRoot(context, game) else null
val saves = game.protonPrefix?.let { prefix -> if (ubisoft(game)) root?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game) }.orEmpty()
return Game(game, game.protonPrefix, saves, root)
}
fun saves(context: Context, prefix: File, game: Library.SteamGame): List<SaveDir> =
if (ubisoft(game)) ubisoftRoot(context, game)?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game)
private fun ubisoftRoot(context: Context, game: Library.SteamGame): String? {
val product = game.gameFiles?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it) }?.extra?.get("productId")?.toLongOrNull() ?: return null
val user = com.droiddeck.launcher.stores.ubisoft.UbisoftAuth.load(context)?.userId
if (user.isNullOrEmpty() || user.contains('/') || user.contains("..")) return null
return "Saved Games/Ubisoft/$user/$product"
}
private fun ubisoft(game: Library.SteamGame) = game.source == com.droiddeck.launcher.stores.Store.UBISOFT.id
private fun ubisoftSaves(prefix: File, rel: String): List<SaveDir> {
val files = File(profile(prefix), rel).walkTopDown().filter { it.isFile }.toList()
return if (files.isEmpty()) emptyList() else listOf(SaveDir(rel, files.size, files.sumOf { it.length() }))
}
private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow")
@@ -109,9 +130,11 @@ object GameSaves {
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))
val roots = game.saves.map { it.relPath }
if (roots.isEmpty() && ubisoft(game.game)) error(context.getString(R.string.saves_none_found, game.game.name))
dir.mkdirs()
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
val count = zipProfile(profile(prefix), roots.ifEmpty { null }, layout, out)
if (count == 0) { out.delete(); error(context.getString(R.string.saves_none_found, game.game.name)) }
return out to count
}
@@ -142,12 +165,21 @@ object GameSaves {
if (!driveC.isDirectory) error(context.getString(R.string.saves_not_launched, game.game.name))
if (!looksLikeSaveZip(zip)) error(context.getString(R.string.saves_not_save_zip, zip.name))
val scoped = if (ubisoft(game.game)) game.root ?: error(context.getString(R.string.saves_none_found, game.game.name)) else null
if (scoped != null) {
val base = File(profile(prefix), scoped).canonicalFile
val eligible = ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
generateSequence { zis.nextEntry }.any { e -> !e.isDirectory && remap(e.name)?.let { File(driveC, it).canonicalFile.path.startsWith(base.path + File.separator) } == true }
}
if (!eligible) error(context.getString(R.string.saves_not_save_zip, zip.name))
}
backupsDir().mkdirs()
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
val backedUp = zipProfile(profile(prefix), null, Layout.GAMEHUB, backup)
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}_${System.currentTimeMillis()}.zip")
val backedUp = if (scoped != null && File(profile(prefix), scoped).walkTopDown().none { it.isFile }) 0
else zipProfile(profile(prefix), scoped?.let(::listOf), Layout.GAMEHUB, backup)
if (backedUp == 0) backup.delete()
val base = driveC.canonicalFile
val base = (if (scoped != null) File(profile(prefix), scoped) else driveC).canonicalFile
var written = 0
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
var e = zis.nextEntry
@@ -14,10 +14,22 @@ object GpuClockPin {
@Volatile
private var pinned = false
private val supported: Boolean by lazy { File(KGSL_NODE).exists() }
@Volatile
var failed = false
private set
val supported: Boolean by lazy { File(KGSL_NODE).exists() }
private var live = false
@Synchronized
fun start(context: Context): String {
live = true
return hold(context)
}
private fun hold(context: Context): String {
failed = false
if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed"
if (!supported) return "gpu clock: no $KGSL_NODE, left governed"
return try {
@@ -28,12 +40,21 @@ object GpuClockPin {
} catch (t: Throwable) {
File(context.filesDir, MARKER).delete()
Log.w(TAG, "pin", t)
failed = true
"gpu clock: pin failed"
}
}
@Synchronized
fun sync(context: Context): String? {
if (!live) return null
if (!SessionPrefs.gpuClockPin(context) && pinned) clear(context)
return hold(context)
}
@Synchronized
fun stop(context: Context) {
live = false
if (pinned) clear(context)
}
@@ -9,11 +9,15 @@ import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.Display
import android.view.MotionEvent
import android.view.WindowManager
// While a session runs, sits invisibly on top of every other display until it ends, so
// that display's home launcher is not its top activity. lmkd kills the launcher first; restarted as a
// top activity it takes focus from the session, which then drops to adj 50 and is killed next.
// While a session is on screen, sits invisibly on top of every other display, so that display's
// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity
// it takes focus from the session, which then drops to adj 50 and is killed next.
// Android gives a translucent activity alone in its task an input sink that eats every touch on the
// display whatever its window flags say, so a touch makes the guard leave that display until the
// session is back on top.
class KeepTopActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -27,13 +31,28 @@ class KeepTopActivity : Activity() {
finishAndRemoveTask()
return
}
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
val id = display?.displayId ?: Display.INVALID_DISPLAY
starting.remove(id)
if (id in yielded) {
finishAndRemoveTask()
return
}
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
guards[id] = this
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) {
val id = display?.displayId ?: Display.INVALID_DISPLAY
yielded.add(id)
Log.i(TAG, "display $id touched, leaving it to the app below")
finishAndRemoveTask()
onYield?.invoke()
}
return true
}
override fun onDestroy() {
guards.values.remove(this)
super.onDestroy()
@@ -49,13 +68,18 @@ class KeepTopActivity : Activity() {
private val guards = HashMap<Int, KeepTopActivity>()
private const val START_TIMEOUT_MS = 2_000L
private val starting = HashMap<Int, Long>()
private val yielded = HashSet<Int>()
const val YIELD_GRACE_MS = 5_000L
var onYield: (() -> Unit)? = null
fun rearm() = yielded.clear()
fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean {
val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false
var started = false
for (display in displays) {
val id = display.displayId
if (id == sessionDisplay || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue
runCatching {
launch(context, id, bounce = false)
@@ -73,13 +97,18 @@ class KeepTopActivity : Activity() {
const val RETRY_MS = START_TIMEOUT_MS + 250
fun release() {
fun stepAside() {
generation++
guards.values.toList().forEach { it.finishAndRemoveTask() }
guards.clear()
starting.clear()
}
fun release() {
stepAside()
yielded.clear()
}
private fun launch(context: Context, displayId: Int, bounce: Boolean) {
val intent = Intent(context, KeepTopActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
@@ -5,6 +5,11 @@ object PipPolicy {
running && frameSeen && phase in setOf(SessionPhase.READY, SessionPhase.SUSPENDED) &&
(!automatic || !suspended)
// A front end or shortcut that launched the game brings it back by moving its task to the
// front, which Android ignores for a task in picture in picture, and draws its resume controls
// where the picture would sit. Going home suspends the game for it instead.
fun autoEnter(enabled: Boolean, launchedByAnotherApp: Boolean): Boolean = enabled && !launchedByAnotherApp
fun aspect(width: Int, height: Int): Pair<Int, Int> = when {
width <= 0 || height <= 0 -> 16 to 9
width.toDouble() / height > 2.39 -> 239 to 100
@@ -9,13 +9,17 @@ import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.Locale
import org.json.JSONArray
import org.json.JSONObject
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"
private const val RELEASE_PAGE_SIZE = 15
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=$RELEASE_PAGE_SIZE&page=%d"
private const val RELEASE_PAGES = 5
private const val RELEASE_TAG = "https://api.github.com/repos/%s/releases/tags/%s"
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
@@ -26,7 +30,8 @@ object ProtonExtras {
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null)
val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck"
@@ -120,22 +125,25 @@ object ProtonExtras {
if (due.isEmpty() || !force && (now - lastAttempt) in 0 until RETRY_MS) return false
lastAttempt = now
for (tool in due) {
val tag = findLatestAsset(tool)?.tag ?: continue
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
updateLatest(cache, tool, releases(tool), now)
}
runCatching { file.writeText(cache.toString()) }
return true
}
}
internal fun recordLatest(latest: JSONObject, tool: Tool, tag: String, now: Long): Boolean {
val entry = latest.optJSONObject(tool.id)
val known = entry?.optString("tag")
if (!known.isNullOrEmpty() && compareVersions(tag, known) < 0) return false
latest.put(tool.id, JSONObject().put("tag", tag).put("at", now))
return true
}
private fun record(context: Context, tool: Tool, dir: String?, tag: String) {
runCatching {
val latest = readJson(latestFile(context))
val known = latest.optJSONObject(tool.id)?.optString("tag")
if (known.isNullOrEmpty() || compareVersions(tag, known) >= 0) {
latest.put(tool.id, JSONObject().put("tag", tag).put("at", System.currentTimeMillis()))
latestFile(context).writeText(latest.toString())
}
if (recordLatest(latest, tool, tag, System.currentTimeMillis())) latestFile(context).writeText(latest.toString())
if (dir != null) {
val releases = readJson(releasesFile(context))
val present = toolsDir(context).list()?.toSet() ?: emptySet()
@@ -218,7 +226,7 @@ object ProtonExtras {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = findLatestAsset(tool) ?: return context.getString(R.string.pextra_no_release, tool.name)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
@@ -277,26 +285,12 @@ object ProtonExtras {
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
"/usr/local/bin/droiddeck-proton-extra", "/root/.local/share/Steam", archive.absolutePath,
)
val process = if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
.directory(root)
.redirectErrorStream(true)
.also { builder ->
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
}
}
val process = guestProcess(context, guest)
val child = process.start()
var placed: String? = null
child.inputStream.bufferedReader().useLines { lines ->
@@ -331,36 +325,106 @@ object ProtonExtras {
}
}
private fun findLatestAsset(tool: Tool): Asset? {
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
return try {
pickAsset(tool, JSONArray(releases))
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
internal fun guestProcess(context: Context, guest: List<String>): ProcessBuilder {
val root = LinuxRuntime.rootDir(context)
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
return if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
.directory(root)
.redirectErrorStream(true)
.also { builder ->
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
}
}
}
internal fun releases(tool: Tool): JSONArray? = releases(tool) { page ->
Downloader.downloadString(RELEASES.format(Locale.ROOT, tool.repo, page))?.let { body ->
try {
JSONArray(body)
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
}
}
}
internal fun releases(tool: Tool, fetch: (Int) -> JSONArray?): JSONArray? {
return releasesResult(tool, fetch, stopAtStable = true)?.releases
}
internal fun releasesForRemoval(tool: Tool, fetch: (Int) -> JSONArray? = { page ->
Downloader.downloadString(RELEASES.format(Locale.ROOT, tool.repo, page))?.let { body ->
runCatching { JSONArray(body) }.getOrNull()
}
}): ReleaseFetch? = releasesResult(tool, fetch, stopAtStable = false)
internal fun releaseGone(tool: Tool, tag: String): Boolean =
Downloader.gone(RELEASE_TAG.format(Locale.ROOT, tool.repo, java.net.URLEncoder.encode(tag, "UTF-8").replace("+", "%20"))) == true
private fun releasesResult(tool: Tool, fetch: (Int) -> JSONArray?, stopAtStable: Boolean): ReleaseFetch? {
val all = fetch(1) ?: return null
var page = 1
var last = all.length()
var complete = last < RELEASE_PAGE_SIZE
while (!complete && page < RELEASE_PAGES && (!stopAtStable || pickAsset(tool, all) == null)) {
val next = fetch(++page) ?: return null
for (i in 0 until next.length()) all.put(next.opt(i))
last = next.length()
complete = last < RELEASE_PAGE_SIZE
}
return ReleaseFetch(all, complete)
}
internal fun assets(tool: Tool, array: JSONArray, prerelease: Boolean): List<Asset> {
val releases = (0 until array.length()).mapNotNull { array.optJSONObject(it) }.filter { !it.optBoolean("draft", false) }
val stableAt = releases.filter { !it.optBoolean("prerelease", false) }.maxOfOrNull { it.optString("published_at") }.orEmpty()
return releases
.filter { it.optBoolean("prerelease", false) == prerelease && (!prerelease || it.optString("published_at") > stableAt) }
.mapNotNull { assetOf(tool, it, experimental = prerelease) }
}
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
for (i in 0 until array.length()) {
val release = array.getJSONObject(i)
if (release.optBoolean("draft", false) || release.optBoolean("prerelease", false)) continue
val assets = release.optJSONArray("assets") ?: continue
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
}
internal fun updateLatest(cache: JSONObject, tool: Tool, array: JSONArray?, now: Long) {
if (array == null) return
val tag = pickAsset(tool, array)?.tag
if (tag == null) {
return
}
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
}
internal fun assetOf(tool: Tool, release: JSONObject, requireChecksum: Boolean = false, experimental: Boolean = false): Asset? = try {
val assets = release.optJSONArray("assets")
val entries = assets?.let { list -> (0 until list.length()).mapNotNull { list.optJSONObject(it) } }.orEmpty()
entries.sortedBy { it.optString("name") }.filter {
val name = it.optString("name")
if (experimental && tool.id == OWN) name.startsWith(release.optString("tag_name")) && ExperimentalProtons.TARBALL.containsMatchIn(name) && !ExperimentalProtons.FOREIGN_ARCH.containsMatchIn(name) else tool.assetPattern.containsMatchIn(name)
}.mapNotNull { archive ->
val name = archive.optString("name")
val stem = name.substringBefore(".tar")
val checksum = entries.firstOrNull {
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
return Asset(
release.optString("tag_name"), name,
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
archive.optLong("size", 0L),
Hashes.githubSha256(archive.optString("digest")),
)
}
return null
archive.optString("browser_download_url").takeIf { it.startsWith("http") }?.let { url ->
Asset(release.optString("tag_name"), name, url, checksum, archive.optLong("size", 0L), Hashes.githubSha256(archive.optString("digest")), release.optString("name").ifEmpty { release.optString("tag_name") })
}
}.let { found -> if (requireChecksum) found.firstOrNull { it.sha256 != null || it.sha512 != null } else found.firstOrNull() }
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
}
private fun requestLines(context: Context): List<String> =
@@ -234,8 +234,6 @@ object SessionFiles {
val gpuLoad = listOf(
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_vram_cap.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json",
)
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libddsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
@@ -282,6 +280,8 @@ object SessionFiles {
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
}
File(root, "usr/local/bin/bannerlator-steam-compat").delete()
File(root, "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so").delete()
File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete()
LegacyNames.migrateRootfs(root)
ComponentsManager.migrateLaunchDir(context)
EsyncPacks.stageBundled(context, root)
@@ -16,6 +16,7 @@ class SessionPipController(
private val activity: SessionActivity,
private val bounds: () -> Rect,
private val showPipUi: (Boolean) -> Unit,
private val launchedByAnotherApp: () -> Boolean = { false },
) {
var transitioning = false
private set
@@ -29,7 +30,8 @@ class SessionPipController(
PipPolicy.eligible(SessionState.running, SessionState.firstFrameSeen, SessionState.phase,
SessionState.suspended, automatic)
fun automatic() = !suppressAuto && SessionPrefs.pipAutoEnter(activity) && eligible(true)
fun automatic() = !suppressAuto && PipPolicy.autoEnter(SessionPrefs.pipAutoEnter(activity), launchedByAnotherApp()) &&
eligible(true)
fun refresh(force: Boolean = false) {
if (!supported(activity)) return
@@ -280,6 +280,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("developerTools", on).apply()
}
fun previewShortcuts(context: Context): Boolean = prefs(context).getBoolean("previewShortcuts", false)
fun setPreviewShortcuts(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("previewShortcuts", on).apply()
}
fun fpsLimitKey(mode: String?, game: String?): String? = when (mode) {
SessionService.MODE_RUN -> game?.trim()?.takeIf(com.droiddeck.launcher.frontend.GameLaunchLink::validId)?.let { "fpsLimit.game.$it" }
SessionService.MODE_DESKTOP -> "fpsLimit.desktop"
@@ -352,6 +358,25 @@ object SessionPrefs {
prefs(context).edit().putString("storesTabOrder", order.joinToString(",")).apply()
}
/**
* Where the Library's own tabs (Favorites, Steam, Custom games) sit among the store tabs, as "tab=the tab it follows" pairs in
* strip order ("" follows nothing, i.e. first). Null until arranged.
*/
fun libraryTabPlaces(context: Context): List<Pair<String, String>>? =
prefs(context).getString("libraryTabPlaces", null)?.split(',')?.mapNotNull { pair ->
pair.split('=', limit = 2).takeIf { it.size == 2 && it[0].isNotEmpty() }?.let { it[0] to it[1] }
}
fun setLibraryTabPlaces(context: Context, places: List<Pair<String, String>>) {
prefs(context).edit().putString("libraryTabPlaces", places.joinToString(",") { "${it.first}=${it.second}" }).apply()
}
fun libraryTabsHidden(context: Context): Set<String> = idList(prefs(context).getString("libraryTabsHidden", null)).toSet()
fun setLibraryTabsHidden(context: Context, hidden: Set<String>) {
prefs(context).edit().putString("libraryTabsHidden", hidden.joinToString(",")).apply()
}
fun storesTabHidden(context: Context): Set<String> = idList(prefs(context).getString("storesTabHidden", null)).toSet()
fun setStoresTabHidden(context: Context, hidden: Set<String>) {
@@ -787,7 +812,7 @@ object SessionPrefs {
val prefs = prefs(context)
if (!prefs.contains("shaderPrecache")) {
if (steamConfig(context).exists()) return null
prefs.edit().putBoolean("shaderPrecache", false).apply()
prefs.edit().putBoolean("shaderPrecache", true).apply()
}
val on = prefs.getBoolean("shaderPrecache", true)
val applied = shaderPrecacheApplied(context)
@@ -947,29 +972,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gamescopeRealtime", on).apply()
}
fun ramCapMb(context: Context): Int = prefs(context).getInt("ramCapMb", 0).coerceAtLeast(0)
fun setRamCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("ramCapMb", mb.coerceAtLeast(0)).apply()
}
fun zramClient(context: Context): Boolean = prefs(context).getBoolean("zramClient", true)
fun setZramClient(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramClient", on).apply()
}
fun zramIdle(context: Context): Boolean = prefs(context).getBoolean("zramIdle", true)
fun setZramIdle(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramIdle", on).apply()
}
fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0)
fun setVramCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("vramCapMb", mb.coerceAtLeast(0)).apply()
}
fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false)
@@ -1499,6 +1501,8 @@ object SessionPrefs {
(id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:")
}.toMap()
fun storeGameFolder(context: Context, key: String): String? = prefs(context).getString("storeFolder:$key", null)
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
val p = prefs(context)
val previous = p.getString("storeFolder:$key", null)
@@ -1570,6 +1574,45 @@ object SessionPrefs {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
fun customThemeColors(context: Context): com.droiddeck.launcher.ui.CustomThemeColors =
prefs(context).let { p ->
val defaults = com.droiddeck.launcher.ui.CustomThemeColors()
com.droiddeck.launcher.ui.CustomThemeColors(
background = p.getInt("customThemeBackground", defaults.background),
surface = p.getInt("customThemeSurface", defaults.surface),
surfaceVariant = p.getInt("customThemeSurfaceVariant", defaults.surfaceVariant),
line = p.getInt("customThemeLine", defaults.line),
line2 = p.getInt("customThemeLine2", defaults.line2),
onBackground = p.getInt("customThemeOnBackground", defaults.onBackground),
onSurfaceVariant = p.getInt("customThemeOnSurfaceVariant", defaults.onSurfaceVariant),
primary = p.getInt("customThemePrimary", defaults.primary),
onPrimary = p.getInt("customThemeOnPrimary", defaults.onPrimary),
signal = p.getInt("customThemeSignal", defaults.signal),
good = p.getInt("customThemeGood", defaults.good),
error = p.getInt("customThemeError", defaults.error),
)
}
fun setCustomThemeColors(
context: Context,
colors: com.droiddeck.launcher.ui.CustomThemeColors,
) {
prefs(context).edit()
.putInt("customThemeBackground", colors.background)
.putInt("customThemeSurface", colors.surface)
.putInt("customThemeSurfaceVariant", colors.surfaceVariant)
.putInt("customThemeLine", colors.line)
.putInt("customThemeLine2", colors.line2)
.putInt("customThemeOnBackground", colors.onBackground)
.putInt("customThemeOnSurfaceVariant", colors.onSurfaceVariant)
.putInt("customThemePrimary", colors.primary)
.putInt("customThemeOnPrimary", colors.onPrimary)
.putInt("customThemeSignal", colors.signal)
.putInt("customThemeGood", colors.good)
.putInt("customThemeError", colors.error)
.apply()
}
fun trueBlackHighlight(context: Context): Int =
prefs(context).getInt("trueBlackHighlight", com.droiddeck.launcher.ui.Themes.DEFAULT_HIGHLIGHT)
@@ -417,10 +417,12 @@ class SessionService : Service() {
SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program),
)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
val gen = synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
++sessionGen
val gen = synchronized(SessionState.startLock) {
synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
++sessionGen
}
}
if (SessionState.stopRequested) {
stopSession(0)
@@ -911,10 +913,9 @@ class SessionService : Service() {
))
}
},
readBackAllowed = { SessionPrefs.ramCapMb(this) == 0 },
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
if (processes == 0) {
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (RAM cap, or ${availableKb / 1024} MB available is too little)")
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (${availableKb / 1024} MB available is too little)")
} else {
Log.i(TAG, "read back $processes processes in $millis ms: zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
}
@@ -1085,11 +1086,7 @@ class SessionService : Service() {
relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") }
if (com.droiddeck.launcher.core.ZramSupport.supported()) {
guest.add("DD_ZRAM=1")
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_RAM_CAP_MB=$it") }
if (!SessionPrefs.zramClient(this)) guest.add("DD_ZRAM_CLIENT=0")
if (!SessionPrefs.zramIdle(this)) guest.add("DD_ZRAM_IDLE=0")
}
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_VRAM_MB=$it") }
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
@@ -43,6 +43,8 @@ object SessionState {
@Volatile
var stopRequested = false
val startLock = Any()
@Volatile
var running = false
@Volatile
@@ -27,7 +27,6 @@ internal class SessionSuspendController(
private val nowNanos: () -> Long = System::nanoTime,
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _, _ -> },
private val readBackAllowed: () -> Boolean = { true },
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
) {
@@ -278,12 +277,21 @@ internal class SessionSuspendController(
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
val control = zramControl?.takeIf { it.isFile } ?: return
val hold = holdFile(control)
try {
addSnapshot(records, root, helpers)
control.writeText("1")
hold.writeText(PAGE_OUT_REQUEST)
sleep(PAGE_OUT_POLL_MS)
pageOut(control, records, root, helpers)
} catch (_: IOException) {
return
} finally {
hold.delete()
}
}
private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold")
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
addSnapshot(records, root, helpers)
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
@@ -301,16 +309,22 @@ internal class SessionSuspendController(
val waiting = targets.toMutableList()
while (!closing && !cancelled && nowMillis() - start < PAGE_OUT_TIMEOUT_MS) {
val started = nowMillis() - start >= PAGE_OUT_START_MS
waiting.removeAll { val ack = acks.getValue(it); ack.length() > 0 || (started && !ack.exists()) || isGone(it) }
waiting.removeAll { val ack = acks.getValue(it); pagedOut(ack) || (started && !ack.exists()) || isGone(it) }
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
val unacknowledged = targets.count { acks.getValue(it).length() == 0L && !isGone(it) }
val unacknowledged = targets.count { !pagedOut(acks.getValue(it)) && !isGone(it) }
acks.values.forEach { it.delete() }
val after = memoryKb(targets)
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
}
private fun pagedOut(ack: File): Boolean = try {
ack.readText().trim() == PAGE_OUT_ACK
} catch (_: IOException) {
false
}
private fun readBack() {
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
@@ -318,13 +332,15 @@ internal class SessionSuspendController(
if (targets.isEmpty() || closing) return
val before = memoryKb(targets).second
val (total, available) = meminfoKb()
if (!readBackAllowed() || !canTake(before, total, available)) {
if (!canTake(before, total, available)) {
pagedIn(0, before, before, available, 0)
return
}
val hold = holdFile(control)
try {
control.writeText("0")
hold.writeText(READ_BACK_REQUEST)
} catch (_: IOException) {
hold.delete()
return
}
val start = nowMillis()
@@ -341,6 +357,8 @@ internal class SessionSuspendController(
}
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
} finally {
hold.delete()
}
pagedIn(targets.size, swap, before, available, nowMillis() - start)
}
@@ -456,6 +474,9 @@ internal class SessionSuspendController(
const val SIGSTOP = 19
const val SIGCONT = 18
const val SIGURG = 23
const val PAGE_OUT_ACK = "1"
const val PAGE_OUT_REQUEST = "1"
const val READ_BACK_REQUEST = "0"
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
@@ -20,7 +20,7 @@ object SettingsReset {
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",