Merge main and retain unified input behavior

This commit is contained in:
Delete228 committed 2026-11-07 00:01:20 +03:00
commit f44826ae3a
75 files changed
+2441 -160

No files matched your search

@@ -0,0 +1,312 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.AtomicFile
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AutoComponents
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object ComponentUpdater {
private const val TAG = "ComponentUpdater"
private const val CHECK_EVERY_MS = 3_600_000L
private const val BOOTED_KEPT = 200
private val lock = Any()
private val io = Any()
data class Status(val line: String, val current: String, val previous: String, val protons: List<String>, val note: String)
private fun file(context: Context) = File(File(context.filesDir, "components").apply { mkdirs() }, "updates.json")
private fun load(context: Context): JSONObject = synchronized(io) {
runCatching { JSONObject(String(AtomicFile(file(context)).readFully(), Charsets.UTF_8)) }.getOrDefault(JSONObject())
}
private fun save(context: Context, state: JSONObject) {
synchronized(io) {
val atomic = AtomicFile(file(context))
val output = runCatching { atomic.startWrite() }.onFailure { Log.w(TAG, "could not save", it) }.getOrNull() ?: return
try {
output.write(state.toString(1).toByteArray(Charsets.UTF_8))
atomic.finishWrite(output)
} catch (error: Exception) {
atomic.failWrite(output)
Log.w(TAG, "could not save", error)
}
}
}
private fun Map<String, Map<String, ComponentsManager.Choice>>.fileOf(p: ComponentsManager.Proton, comp: String): String? =
this[p.id]?.get(comp)?.takeIf { it.protonVersion == p.version }?.file
private class Target(val comp: String, val p: ComponentsManager.Proton, val line: ComponentUpdates.Line, val ls: JSONObject) {
val key: String get() = line.key
}
private fun JSONObject.obj(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
private fun JSONArray?.strings(): Set<String> = this?.let { a -> (0 until a.length()).map { a.optString(it) }.toSet() } ?: emptySet()
private fun JSONObject.strings(key: String): Set<String> = optJSONArray(key).strings()
private fun JSONObject?.ints(): Map<String, Int> = this?.keys()?.asSequence()?.associateWith { optInt(it) } ?: emptyMap()
private fun JSONObject?.texts(): Map<String, String> = this?.keys()?.asSequence()?.associateWith { optString(it) } ?: emptyMap()
fun settle(context: Context) {
val owned = load(context).optJSONObject("lines")?.let { lines -> lines.keys().asSequence().flatMap { lines.optJSONObject(it).strings("owned") }.toSet() } ?: emptySet()
val choices = ComponentsManager.activeChoices(context).values.flatMap { it.entries }
for (comp in ComponentsManager.COMPONENTS) {
if (SessionPrefs.componentModeChosen(context, comp)) continue
val manual = choices.any { (c, choice) -> c == comp && !choice.auto && choice.file !in owned && !choice.file.startsWith("original ") }
SessionPrefs.setComponentMode(context, comp, if (manual) ComponentUpdates.MANUAL else ComponentUpdates.AUTO)
}
}
private fun managed(context: Context, comp: String): Boolean =
SessionPrefs.componentMode(context, comp) == ComponentUpdates.AUTO && !(comp == "dxvk" && ComponentsManager.hardwareDxvk(context))
private fun logLines(context: Context): Sequence<String> {
val dir = ComponentsManager.steamLogs(context)
return sequenceOf("console_log.previous.txt", "console_log.txt").map { File(dir, it) }.filter { it.isFile }
.flatMap { f -> runCatching { f.readLines() }.getOrDefault(emptyList()).asSequence() }
}
private val STAMP = Regex("""^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)]""")
private fun latestStamp(context: Context): String =
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
if (!ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.line("fex", false)
val key = "${p.id}|${p.version}"
val flavors = state.obj("flavors").obj(key)
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
return arm64ec?.let { ComponentUpdates.line(comp, it) }
}
fun ensure(context: Context, force: Boolean): List<String> = synchronized(lock) {
if (SessionState.running) return emptyList()
settle(context)
val state = load(context)
val notes = ArrayList<String>()
val protons = runCatching { ComponentsManager.protons(context) }.getOrDefault(emptyList())
judge(context, state, protons, notes)
val due = force || System.currentTimeMillis() - state.optLong("checkedAt") >= CHECK_EVERY_MS
val wanted = ComponentsManager.COMPONENTS.filter { managed(context, it) }
if (wanted.isEmpty() || protons.isEmpty()) {
save(context, state)
return notes
}
try {
dropRemoved(state, protons)
val checked = due && check(context, state, protons, wanted, force, notes)
apply(context, state, protons, wanted, notes)
prune(context, state)
if (checked) state.put("checkedAt", System.currentTimeMillis())
} finally {
save(context, state)
}
notes
}
private fun check(
context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, wanted: List<String>, force: Boolean, notes: MutableList<String>,
): Boolean {
if (!AutoComponents.isOnline(context)) {
state.put("note", context.getString(R.string.comp_auto_waits_network))
return false
}
val catalog = runCatching { ComponentsManager.catalog(context, true).items }
.onFailure { Log.w(TAG, "catalog", it) }.getOrDefault(emptyList())
if (catalog.none { it.release == ComponentsManager.DD_NIGHTLY }) {
state.put("note", context.getString(R.string.comp_auto_check_failed))
return false
}
val holdBack = !force && AutoComponents.constrained(context)
val lines = state.obj("lines")
var complete = true
state.remove("note")
for (comp in wanted) for (p in protons) {
val line = lineOf(context, state, p, comp) ?: continue
val ls = lines.obj(line.key)
if (rollingBack(ls)) {
complete = false
continue
}
val target = ComponentUpdates.pick(catalog, line, ls.strings("bad"))
if (target == null || ls.optString("current") == target.file) continue
val stored = ComponentsManager.isStored(context, target.file)
if (!stored) {
if (holdBack) {
state.put("note", context.getString(R.string.comp_auto_waits_unmetered))
complete = false
continue
}
val got = runCatching { ComponentsManager.download(context, target) {} }
if (got.isFailure) {
Log.w(TAG, "download ${target.file}", got.exceptionOrNull())
state.put("note", context.getString(R.string.comp_auto_check_failed))
complete = false
continue
}
}
val stocks = protons.filter { lineOf(context, state, it, comp)?.key == line.key }.map { ComponentsManager.arm64x(context, it, comp) }
if (ComponentUpdates.needsArm64x(line, stocks) && !ComponentsManager.packageArm64x(context, target.file, comp)) {
Log.w(TAG, "${target.file} is not ARM64X like ${p.name}'s own ${line.key}; skipped")
ls.put("bad", JSONArray(ls.strings("bad") + target.file))
if (!stored) runCatching { ComponentsManager.deletePackage(context, target.file) }
continue
}
ls.put("previous", ls.optString("current").ifEmpty { ComponentUpdates.ORIGINAL })
.put("current", target.file).put("since", latestStamp(context)).put("failed", JSONObject())
if (!stored) ls.put("owned", JSONArray(ls.strings("owned") + target.file))
ls.remove("note")
notes += context.getString(R.string.comp_auto_updated, ComponentsManager.LABEL[comp], target.file.removeSuffix(".wcp"))
}
return complete
}
private fun apply(context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, wanted: List<String>, notes: MutableList<String>) {
val lines = state.obj("lines")
val targets = wanted.flatMap { comp ->
protons.mapNotNull { p -> lineOf(context, state, p, comp)?.let { line -> lines.optJSONObject(line.key)?.let { Target(comp, p, line, it) } } }
}
val choices = ComponentsManager.activeChoices(context)
for (t in targets) {
val from = t.ls.optJSONObject("restore")?.optString(t.p.id).orEmpty()
val current = t.ls.optString("current")
if (from.isNotEmpty()) {
if (choices.fileOf(t.p, t.comp) == from) runCatching { ComponentsManager.restore(context, t.p.id, t.comp, ComponentsManager.safeName(t.p.version)) }
.onFailure { Log.w(TAG, "restore ${t.p.name} ${t.key}", it) }
} else if (current.isNotEmpty() && choices.fileOf(t.p, t.comp) != current) {
if (ComponentUpdates.needsArm64x(t.line, listOf(ComponentsManager.arm64x(context, t.p, t.comp))) &&
!ComponentsManager.packageArm64x(context, current, t.comp)) continue
runCatching { ComponentsManager.swap(context, t.p.id, current) }.onFailure { Log.w(TAG, "${t.p.name} ${t.key}", it) }
}
}
val after = ComponentsManager.activeChoices(context)
val unfinished = HashSet<String>()
for (t in targets) {
val restore = t.ls.optJSONObject("restore")
val from = restore?.optString(t.p.id).orEmpty()
val current = t.ls.optString("current")
if (from.isNotEmpty()) {
if (after.fileOf(t.p, t.comp) == from) unfinished += t.key else restore?.remove(t.p.id)
} else if (current.isNotEmpty() && after.fileOf(t.p, t.comp) != current) {
unfinished += t.key
}
}
for (key in lines.keys().asSequence().toList()) {
val ls = lines.optJSONObject(key) ?: continue
val pending = ls.optString("pendingNote")
if (pending.isEmpty() || key in unfinished || (ls.optJSONObject("restore")?.length() ?: 0) > 0) continue
ls.remove("pendingNote")
ls.put("note", pending)
notes += pending
}
}
internal fun dropRemoved(state: JSONObject, protons: List<ComponentsManager.Proton>) {
val installed = protons.mapTo(HashSet()) { it.id }
val lines = state.optJSONObject("lines") ?: return
for (key in lines.keys().asSequence().toList()) {
val restore = lines.optJSONObject(key)?.optJSONObject("restore") ?: continue
for (id in restore.keys().asSequence().toList()) if (id !in installed) restore.remove(id)
}
}
internal fun rollingBack(ls: JSONObject): Boolean =
(ls.optJSONObject("restore")?.length() ?: 0) > 0 || ls.optString("pendingNote").isNotEmpty()
private fun judge(context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, notes: MutableList<String>) {
val mark = state.optString("logMark")
val runs = ComponentUpdates.launches(logLines(context), mark)
if (runs.isEmpty()) return
state.put("logMark", runs.maxOf { it.start })
val byTool = protons.associateBy { it.dir.name }
val lines = state.obj("lines")
for (comp in ComponentsManager.COMPONENTS) {
val onLine = HashMap<String, MutableList<ComponentUpdates.Launch>>()
for (run in runs) {
val p = byTool[run.tool] ?: continue
if (ComponentsManager.gameComponents(context, run.app).containsKey(comp)) continue
val line = lineOf(context, state, p, comp) ?: continue
onLine.getOrPut(line.key) { ArrayList() } += run
}
for ((key, list) in onLine) {
val ls = lines.obj(key)
val verdict = ComponentUpdates.judge(ComponentUpdates.Trial(
ls.optString("current"), ls.optString("previous"), ls.optString("since"),
ls.optJSONObject("booted").texts(), ls.optJSONObject("failed").ints(),
), list)
ls.put("booted", JSONObject(verdict.booted.entries.toList().takeLast(BOOTED_KEPT).associate { it.key to it.value } as Map<*, *>))
ls.put("failed", JSONObject(verdict.failed as Map<*, *>))
if (verdict.rollBack && managed(context, comp)) rollBack(context, state, protons, comp, key, notes)
}
}
}
private fun rollBack(context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, comp: String, key: String, notes: MutableList<String>) {
val ls = state.obj("lines").obj(key)
val bad = ls.optString("current")
val back = ls.optString("previous")
val choices = ComponentsManager.activeChoices(context)
val targets = protons.filter { lineOf(context, state, it, comp)?.key == key && choices.fileOf(it, comp) == bad }
for (p in targets) {
runCatching {
if (back == ComponentUpdates.ORIGINAL) ComponentsManager.restore(context, p.id, comp, ComponentsManager.safeName(p.version))
else ComponentsManager.swap(context, p.id, back)
}.onFailure { Log.w(TAG, "roll back ${p.name} $key", it) }
}
val after = ComponentsManager.activeChoices(context)
val unfinished = targets.filter { after.fileOf(it, comp) == bad }
ls.put("bad", JSONArray(ls.strings("bad") + bad)).put("current", back).put("previous", ComponentUpdates.ORIGINAL)
.put("since", latestStamp(context)).put("failed", JSONObject())
if (back == ComponentUpdates.ORIGINAL) ls.obj("restore").let { restore -> unfinished.forEach { restore.put(it.id, bad) } }
val label = ComponentsManager.LABEL[comp]
val shown = back.ifEmpty { context.getString(R.string.comp_tag_original) }.removeSuffix(".wcp")
val note = context.getString(R.string.comp_auto_rolled_back, label, bad.removeSuffix(".wcp"), shown)
Log.w(TAG, note)
if (unfinished.isNotEmpty()) {
ls.put("pendingNote", note)
return
}
ls.remove("pendingNote")
ls.put("note", note)
notes += note
prune(context, state)
}
private fun prune(context: Context, state: JSONObject) {
val lines = state.obj("lines")
val selected = ComponentsManager.selectedPackages(context)
val keep = lines.keys().asSequence().flatMap { k ->
val ls = lines.optJSONObject(k) ?: return@flatMap emptySequence()
ComponentUpdates.keep(ls.optString("current"), ls.optString("previous"), selected).asSequence()
}.toSet()
for (k in lines.keys().asSequence().toList()) {
val ls = lines.optJSONObject(k) ?: continue
val owned = ls.strings("owned")
val gone = owned.filter { it !in keep && runCatching { ComponentsManager.deletePackage(context, it) }.isSuccess }
ls.put("owned", JSONArray(owned - gone.toSet()))
}
}
fun status(context: Context, comp: String): List<Status> {
val state = load(context)
val lines = state.optJSONObject("lines") ?: JSONObject()
val protons = runCatching { ComponentsManager.protons(context) }.getOrDefault(emptyList())
val byLine = protons.groupBy { lineOf(context, state, it, comp)?.key }
return ComponentUpdates.LINES.filter { it.comp == comp }.mapNotNull { line ->
val on = byLine[line.key].orEmpty()
val ls = lines.optJSONObject(line.key)
if (on.isEmpty() && ls == null) return@mapNotNull null
val note = ls?.optString("note").orEmpty().ifEmpty { state.optString("note") }
Status(line.key, ls?.optString("current").orEmpty(), ls?.optString("previous").orEmpty(), on.map { it.name }, note)
}
}
}
@@ -0,0 +1,127 @@
package com.droiddeck.launcher.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.text.SimpleDateFormat
import java.util.Locale
object ComponentUpdates {
const val AUTO = "auto"
const val MANUAL = "manual"
const val ORIGINAL = ""
const val BOOT_SECONDS = 30L
const val BOOTED_SECONDS = 60L
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
data class Line(val key: String, val comp: String, val prefix: String)
val LINES = listOf(
Line("dxvk", "dxvk", "DD-dxvk-"),
Line("dxvk-arm64ec", "dxvk", "DD-dxvk-arm64ec-"),
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
Line("fex", "fex", "DD-FEXCore-"),
)
fun line(comp: String, arm64ec: Boolean): Line = LINES.first {
it.comp == comp && (comp == "fex" || it.key.endsWith("-arm64ec") == arm64ec)
}
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
}
fun belongs(file: String, line: Line): Boolean =
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
val header = b.getInt(0x3c)
if (b.getInt(header) != 0x4550) return null
val sections = b.getShort(header + 6).toInt() and 0xffff
val optionalSize = b.getShort(header + 20).toInt() and 0xffff
val optional = header + 24
if ((b.getShort(optional).toInt() and 0xffff) != 0x20b) return false
val loadConfigRva = b.getInt(optional + 112 + 10 * 8)
if (loadConfigRva == 0) return false
val table = optional + optionalSize
var offset = -1
for (i in 0 until sections) {
val s = table + i * 40
val size = b.getInt(s + 8)
val va = b.getInt(s + 12)
if (loadConfigRva >= va && loadConfigRva < va + maxOf(size, 1)) offset = b.getInt(s + 20) + loadConfigRva - va
}
if (offset < 0) return null
b.getInt(offset) >= 0xC8 + 8 && b.getLong(offset + 0xC8) != 0L
}.getOrNull()
fun arm64x(pe: ByteArray): Boolean = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
val header = b.getInt(0x3c)
b.getInt(header) == 0x4550 && (b.getShort(header + 4).toInt() and 0xffff) == 0xaa64 && arm64ec(pe) == true
}.getOrDefault(false)
fun needsArm64x(line: Line, stocks: List<Boolean?>): Boolean =
line.key.endsWith("-arm64ec") && stocks.any { it != false }
data class Launch(val app: String, val tool: String, val start: String, val seconds: Long)
private val PROCESS = Regex("""^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)] Game process (added|removed)\s*: AppID (\d+)(?: "(.*))?""")
private val TOOL = Regex("""compatibilitytools\.d/([^/'"]+)['"]?/|steamapps/common/([^/'"]+)['"]?/proton""")
fun launches(log: Sequence<String>, after: String): List<Launch> {
val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
val open = HashMap<String, Pair<String, String>>()
val out = ArrayList<Launch>()
for (line in log) {
val m = PROCESS.find(line) ?: continue
val (time, what, app) = m.destructured
if (time <= after) continue
if (what == "added") {
val tool = TOOL.find(m.groupValues[4])?.let { t -> t.groupValues[1].ifEmpty { t.groupValues[2] } } ?: continue
open[app] = time to tool
} else {
val (start, tool) = open.remove(app) ?: continue
val seconds = runCatching { (format.parse(time)!!.time - format.parse(start)!!.time) / 1000 }.getOrNull() ?: continue
out += Launch(app, tool, start, seconds)
}
}
return out
}
data class Trial(
val current: String,
val previous: String,
val since: String,
val booted: Map<String, String>,
val failed: Map<String, Int>,
)
data class Verdict(val booted: Map<String, String>, val failed: Map<String, Int>, val rollBack: Boolean)
fun judge(trial: Trial, runs: List<Launch>): Verdict {
val booted = trial.booted.toMutableMap()
val failed = trial.failed.toMutableMap()
var rollBack = false
for (run in runs) {
val build = if (trial.since.isNotEmpty() && run.start > trial.since) trial.current else trial.previous
if (run.seconds >= BOOTED_SECONDS) {
booted[run.app] = build
if (build == trial.current) failed.remove(run.app)
} else if (run.seconds < BOOT_SECONDS && build == trial.current && trial.current != trial.previous &&
booted[run.app] == trial.previous) {
val n = (failed[run.app] ?: 0) + 1
failed[run.app] = n
if (n >= FAILED_BOOTS_BEFORE_ROLLBACK) rollBack = true
}
}
return Verdict(booted, failed, rollBack)
}
fun keep(current: String, previous: String, selected: Set<String>): Set<String> =
(setOf(current, previous) + selected) - ORIGINAL
}
@@ -84,6 +84,7 @@ object ComponentsManager {
private fun root(context: Context) = LinuxRuntime.rootDir(context)
private fun steam(context: Context) = File(root(context), "root/.local/share/Steam")
fun steamLogs(context: Context) = File(steam(context), "logs")
private fun host(context: Context, guest: String) = File(root(context), guest.removePrefix("/"))
private fun dataDir(context: Context) = File(context.filesDir, "components").apply { mkdirs() }
private fun packagesDir(context: Context) = File(dataDir(context), "packages").apply { mkdirs() }
@@ -1031,6 +1032,78 @@ object ComponentsManager {
ForcedPackage(setOf(GpuInfo.Family.A6XX), "dxvk", "dxvk-2.7.1-linux.wcp", "Dxvk-Linux"),
)
private val ARM64EC_PROBE = mapOf("dxvk" to "d3d11.dll", "vkd3d" to "d3d12.dll")
fun arm64ec(context: Context, p: Proton, comp: String): Boolean? = stockProbe(context, p, comp)?.let(ComponentUpdates::arm64ec)
fun arm64x(context: Context, p: Proton, comp: String): Boolean? = stockProbe(context, p, comp)?.let(ComponentUpdates::arm64x)
fun packageArm64x(context: Context, file: String, comp: String): Boolean {
val rel = "${COMP_DIR[comp] ?: return false}/aarch64-windows/${ARM64EC_PROBE.getValue(comp)}"
val f = File(packagesDir(context), safeName(file)).takeIf { it.isFile } ?: return false
return runCatching { readWcpEntry(f, rel) }.getOrNull()?.let(ComponentUpdates::arm64x) == true
}
private fun readWcpEntry(f: File, rel: String): ByteArray? = readWcp(f) { tar ->
var found: ByteArray? = null
while (found == null) {
val e = tar.nextTarEntry ?: break
if (!e.isDirectory && normalize(e.name) == rel) found = tar.readBytes()
}
found
}
private fun stockProbe(context: Context, p: Proton, comp: String): ByteArray? {
val rel = "${COMP_DIR[comp] ?: return null}/aarch64-windows/${ARM64EC_PROBE.getValue(comp)}"
val original = synchronized(lock) {
val swapped = loadState(context).optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(comp)
?.let { liveSelection("active", it, p) } == true
if (!swapped) return File(p.dir, rel).takeIf { it.isFile }?.let { runCatching { it.readBytes() }.getOrNull() }
originalFile(context, p, comp).takeIf { it.isFile } ?: return null
}
return runCatching { readWcpEntry(original, rel) }.getOrNull()
}
fun supports(p: Proton, comp: String): Boolean =
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
fun hardwareDxvk(context: Context): Boolean =
runtimeManaged(context, "dxvk") || FORCED_PACKAGES.any { it.comp == "dxvk" && it.matches(GpuInfo.detect()) } ||
(com.droiddeck.launcher.core.DeviceSupport.vkBridge(context) && !SessionPrefs.bridgeProtonDxvk(context) &&
bridgeDxvk(AppVulkan.detect(context)) != null)
data class Choice(val file: String, val auto: Boolean, val protonVersion: String)
fun activeChoices(context: Context): Map<String, Map<String, Choice>> = synchronized(lock) {
val active = loadState(context).optJSONObject("active") ?: return emptyMap()
active.keys().asSequence().toList().associateWith { pid ->
val comps = active.optJSONObject(pid) ?: JSONObject()
comps.keys().asSequence().toList().mapNotNull { c ->
comps.optJSONObject(c)?.let { c to Choice(it.optString("file"), it.optBoolean("auto"), it.optString("protonVersion")) }
}.toMap()
}
}
fun selectedPackages(context: Context): Set<String> = synchronized(lock) {
val state = loadState(context)
buildSet {
for (key in listOf("active", "queued")) {
val byProton = state.optJSONObject(key) ?: continue
for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (c in comps.keys()) comps.optJSONObject(c)?.optString("file")?.takeIf(String::isNotEmpty)?.let(::add)
}
}
val profiles = state.optJSONObject("profiles")
profiles?.keys()?.forEach { scope ->
val profile = profiles.optJSONObject(scope) ?: return@forEach
for (c in COMPONENTS) profile.optString(c).takeIf(String::isNotEmpty)?.let(::add)
}
}
}
fun isStored(context: Context, file: String): Boolean = File(packagesDir(context), safeName(file)).isFile
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
activeFile.isNullOrEmpty() || !protonVersionMatches
@@ -11,12 +11,4 @@ object PipPolicy {
height.toDouble() / width > 2.39 -> 100 to 239
else -> width to height
}
fun outputSize(width: Int, height: Int, outputWidth: Int, outputHeight: Int): Pair<Int, Int>? {
if (width <= 0 || height <= 0 || outputWidth <= 0 || outputHeight <= 0) return null
val scale = minOf(width.toFloat() / outputWidth, height.toFloat() / outputHeight)
val fittedWidth = ((outputWidth * scale).toInt() and 1.inv()).coerceAtLeast(2)
val fittedHeight = ((outputHeight * scale).toInt() and 1.inv()).coerceAtLeast(2)
return fittedWidth to fittedHeight
}
}
@@ -351,6 +351,8 @@ object SessionPrefs {
}
const val PC_KEYBOARD_SIZE_DEFAULT = 47
const val WOW_CHAT_VOICE = "voice"
const val WOW_CHAT_KEYBOARD = "keyboard"
val PC_KEYBOARD_SIZE_RANGE = 25..70
const val PC_KEYBOARD_OPACITY_DEFAULT = 100
val PC_KEYBOARD_OPACITY_RANGE = 30..100
@@ -362,6 +364,13 @@ object SessionPrefs {
prefs(context).edit().putInt("pcKeyboardSize", percent.coerceIn(PC_KEYBOARD_SIZE_RANGE)).apply()
}
fun wowChatInput(context: Context): String? =
prefs(context).getString("wowChatInput", null)?.takeIf { it == WOW_CHAT_VOICE || it == WOW_CHAT_KEYBOARD }
fun setWowChatInput(context: Context, mode: String?) {
prefs(context).edit().apply { if (mode == null) remove("wowChatInput") else putString("wowChatInput", mode) }.apply()
}
fun pcKeyboardOpacity(context: Context): Int =
prefs(context).getInt("pcKeyboardOpacity", PC_KEYBOARD_OPACITY_DEFAULT).takeIf { it in PC_KEYBOARD_OPACITY_RANGE } ?: PC_KEYBOARD_OPACITY_DEFAULT
@@ -499,6 +508,17 @@ object SessionPrefs {
prefs(context).edit().putString("gpuDriverMode", mode).apply()
}
fun componentMode(context: Context, comp: String): String =
prefs(context).getString("componentMode.$comp", ComponentUpdates.AUTO)
?.takeIf { it == ComponentUpdates.AUTO || it == ComponentUpdates.MANUAL } ?: ComponentUpdates.AUTO
fun componentModeChosen(context: Context, comp: String): Boolean = prefs(context).contains("componentMode.$comp")
fun setComponentMode(context: Context, comp: String, mode: String) {
require(mode == ComponentUpdates.AUTO || mode == ComponentUpdates.MANUAL)
prefs(context).edit().putString("componentMode.$comp", mode).commit()
}
fun settleGpuDriverMode(context: Context) {
val p = prefs(context)
if (p.contains("gpuDriverMode")) return
@@ -31,7 +31,7 @@ object SettingsReset {
)
internal val SESSION_PREFIXES = listOf(
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "performanceMode.", "suspendPolicy.",
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "performanceMode.", "suspendPolicy.", "componentMode.",
)
private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake")