mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 21:35:59 +00:00
Merge remote-tracking branch 'droiddeck/main' into feat/malibridge
# Conflicts: # README.md # app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java # app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt # app/src/main/res/values-ar/strings.xml # app/src/main/res/values-b+es+419/strings.xml # app/src/main/res/values-bg/strings.xml # app/src/main/res/values-cs/strings.xml # app/src/main/res/values-da/strings.xml # app/src/main/res/values-de/strings.xml # app/src/main/res/values-el/strings.xml # app/src/main/res/values-es/strings.xml # app/src/main/res/values-fi/strings.xml # app/src/main/res/values-fr/strings.xml # app/src/main/res/values-hi/strings.xml # app/src/main/res/values-hu/strings.xml # app/src/main/res/values-in/strings.xml # app/src/main/res/values-it/strings.xml # app/src/main/res/values-ja/strings.xml # app/src/main/res/values-ko/strings.xml # app/src/main/res/values-ms/strings.xml # app/src/main/res/values-nb/strings.xml # app/src/main/res/values-nl/strings.xml # app/src/main/res/values-pl/strings.xml # app/src/main/res/values-pt-rPT/strings.xml # app/src/main/res/values-pt/strings.xml # app/src/main/res/values-ro/strings.xml # app/src/main/res/values-ru/strings.xml # app/src/main/res/values-sv/strings.xml # app/src/main/res/values-th/strings.xml # app/src/main/res/values-tr/strings.xml # app/src/main/res/values-uk/strings.xml # app/src/main/res/values-vi/strings.xml # app/src/main/res/values-zh-rCN/strings.xml # app/src/main/res/values-zh-rHK/strings.xml # app/src/main/res/values-zh-rTW/strings.xml # app/src/main/res/values/strings.xml # tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
This commit is contained in:
commit
0a5955d6fa
731 files changed
+54131
-2491
No files matched your search
@@ -156,8 +156,7 @@ object ComponentsManager {
|
||||
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
|
||||
}
|
||||
|
||||
private fun saveState(context: Context, state: JSONObject) {
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
private fun saveState(context: Context, state: JSONObject, prepared: PreparedLaunchState = prepareLaunchState(context, state)) {
|
||||
val dir = launchDir(context)
|
||||
val tmp = File(dir, "desired.tsv.tmp")
|
||||
try {
|
||||
@@ -176,6 +175,17 @@ object ComponentsManager {
|
||||
?.forEach { it.deleteRecursively() }
|
||||
}
|
||||
|
||||
fun republish(context: Context): Boolean = synchronized(lock) {
|
||||
recoverState(context)
|
||||
val saved = stateFile(context)
|
||||
if (saved.exists() && runCatching { JSONObject(saved.readText()) }.isFailure) return false
|
||||
val state = loadState(context)
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
if ((FileUtils.readString(File(launchDir(context), "desired.tsv")) ?: "") == prepared.text) return false
|
||||
saveState(context, state, prepared)
|
||||
true
|
||||
}
|
||||
|
||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||
|
||||
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
|
||||
|
||||
@@ -13,6 +13,7 @@ object GameEnvironmentStore {
|
||||
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
|
||||
const val DXVK_CONFIG = "dxvkConfig"
|
||||
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
|
||||
const val GAME_DEBUG_LOGS = "gameDebugLogs"
|
||||
|
||||
@Synchronized
|
||||
fun read(context: Context): GameEnvironment.Config {
|
||||
@@ -87,7 +88,11 @@ object GameEnvironmentStore {
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||
fun publish(
|
||||
context: Context,
|
||||
config: GameEnvironment.Config = read(context),
|
||||
gameDebugLogsOverride: Boolean? = null,
|
||||
) {
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
val json = encode(resolved)
|
||||
val dxvk = TextureFiltering.dxvkOptions(
|
||||
@@ -110,6 +115,11 @@ object GameEnvironmentStore {
|
||||
)
|
||||
}
|
||||
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
|
||||
json.put(
|
||||
GAME_DEBUG_LOGS,
|
||||
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
|
||||
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
|
||||
)
|
||||
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
if (running && OverlayShown.check(root)) sample()?.let { write(it) }
|
||||
if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.FusionHudHost.showing)) sample()?.let { write(it) }
|
||||
}
|
||||
}, "gpu-mem").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
@@ -51,7 +51,8 @@ object NoSteamLaunch {
|
||||
|
||||
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
|
||||
val id = game.appId.toLong() and 0xFFFFFFFFL
|
||||
return AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
|
||||
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
}
|
||||
|
||||
fun nameFor(program: String?, args: List<String>): String? = when (program) {
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.BatteryManager
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
class PerfHud(context: Context) {
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
var graph by mutableStateOf(FloatArray(0))
|
||||
private set
|
||||
|
||||
private val context = context.applicationContext
|
||||
private val frames = AtomicInteger()
|
||||
private var lastTick = 0L
|
||||
private var lastFps = 0f
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val samples = FloatArray(GRAPH)
|
||||
private var graphBase = 0L
|
||||
private var graphSeen = 0L
|
||||
|
||||
@Volatile private var showFps = true
|
||||
@Volatile private var showBattery = true
|
||||
@Volatile private var showGraph = true
|
||||
|
||||
private val enabled: Boolean
|
||||
get() = SessionPrefs.hudEnabled(context)
|
||||
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
|
||||
|
||||
private val anyPart: Boolean
|
||||
get() = showFps || showBattery || showGraph
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
private var lastWindow: String? = null
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
override fun onGameSurface(window: String?, gpuName: String?) {
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
}
|
||||
}
|
||||
override fun onGameFrame() {
|
||||
frames.incrementAndGet()
|
||||
}
|
||||
}
|
||||
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val dt = (now - lastTick).coerceAtLeast(1L) / 1000f
|
||||
lastTick = now
|
||||
lastFps = frames.getAndSet(0) / dt
|
||||
text = readout(lastFps)
|
||||
if (showGraph) publishGraph() else clearGraph()
|
||||
handler.postDelayed(this, TICK_MS)
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
readOptions()
|
||||
if (!enabled || !anyPart) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
if (!running) start() else {
|
||||
if (!showGraph) clearGraph() else publishGraph()
|
||||
text = readout(lastFps)
|
||||
}
|
||||
}
|
||||
|
||||
fun start() {
|
||||
readOptions()
|
||||
if (!enabled || !anyPart || running) return
|
||||
running = true
|
||||
lastTick = SystemClock.elapsedRealtime()
|
||||
frames.set(0)
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
handler.postDelayed(tick, TICK_MS)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
handler.removeCallbacks(tick)
|
||||
WaylandCompositor.clearGameListener(listener)
|
||||
text = ""
|
||||
graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun readOptions() {
|
||||
showFps = SessionPrefs.hudShowFps(context)
|
||||
showBattery = SessionPrefs.hudShowBattery(context)
|
||||
showGraph = SessionPrefs.hudShowGraph(context)
|
||||
}
|
||||
|
||||
private fun readout(fpsValue: Float): String {
|
||||
val parts = ArrayList<String>(2)
|
||||
if (showFps) parts.add(line(fpsValue))
|
||||
if (showBattery) batteryCelsius(readBatteryDeci())?.let { parts.add(it) }
|
||||
return parts.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun readBatteryDeci(): Int {
|
||||
val sticky = runCatching {
|
||||
context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
}.getOrNull() ?: return 0
|
||||
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
|
||||
}
|
||||
|
||||
private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L }
|
||||
|
||||
private fun clearGraph() {
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
if (graph.isNotEmpty()) graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun publishGraph() {
|
||||
val total = shownTotal()
|
||||
if (total == graphSeen && graph.isNotEmpty()) return
|
||||
graphSeen = total
|
||||
graph = recent(samples, total, graphBase)
|
||||
}
|
||||
|
||||
private fun line(base: Float): String {
|
||||
val mode = FrameGen.mode(context)
|
||||
if (mode.engine == FrameGen.ENGINE_OFF) return fps(base)
|
||||
val lsfg = mode.engine == FrameGen.ENGINE_LSFG
|
||||
val name = if (lsfg) "LSFG" else "DD-FG"
|
||||
val label = FrameGen.label(context, mode)
|
||||
if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name)
|
||||
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
|
||||
val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 }
|
||||
return when {
|
||||
problem == 1 -> context.getString(R.string.hud_fg_unsupported, name)
|
||||
problem == 2 -> context.getString(R.string.hud_fg_failed, name)
|
||||
stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3])
|
||||
else -> context.getString(R.string.hud_fg_starting, label, fps(base))
|
||||
}
|
||||
}
|
||||
|
||||
private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value)
|
||||
|
||||
companion object {
|
||||
private const val TICK_MS = 1_000L
|
||||
private const val GRAPH = 128
|
||||
internal const val GRAPH_MAX_MS = 50f
|
||||
|
||||
internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray {
|
||||
val filled = minOf(total, samples.size.toLong()).toInt()
|
||||
val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt()
|
||||
if (shown < 2) return FloatArray(0)
|
||||
return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) }
|
||||
}
|
||||
|
||||
internal fun batteryCelsius(deci: Int): String? =
|
||||
if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f)
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ class RumbleComponent : SessionPart() {
|
||||
private val joyConPairs = HashMap<Long, Motors>()
|
||||
private var preferences: SharedPreferences? = null
|
||||
private var enabled = false
|
||||
private var quiet = false
|
||||
private var motorThread: HandlerThread? = null
|
||||
private var handler: Handler? = null
|
||||
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
@@ -44,6 +45,11 @@ class RumbleComponent : SessionPart() {
|
||||
if (!enabled) cancelAll()
|
||||
}
|
||||
|
||||
@Synchronized fun quiet(on: Boolean) {
|
||||
quiet = on
|
||||
if (on) cancelAll()
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
val ctx = app() ?: return
|
||||
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
|
||||
@@ -89,7 +95,7 @@ class RumbleComponent : SessionPart() {
|
||||
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
|
||||
|
||||
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
|
||||
if (!enabled) return
|
||||
if (!enabled || quiet) return
|
||||
val target = target(slot)
|
||||
val previous = playing[slot]
|
||||
if (target !== previous) {
|
||||
|
||||
@@ -7,6 +7,9 @@ import com.droiddeck.launcher.core.SessionLogCapture
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.io.Writer
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
@@ -16,6 +19,9 @@ object SessionArtifacts {
|
||||
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
private const val RECOVERY_RUNTIME_CAPTURED_MARKER = ".recovery-runtime-captured"
|
||||
private const val RECOVERY_RUNTIME_EXPIRED_MARKER = ".recovery-runtime-expired"
|
||||
|
||||
private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}"
|
||||
private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""")
|
||||
|
||||
@@ -72,9 +78,9 @@ object SessionArtifacts {
|
||||
copySteamLogs(context, dir, record, steamArch)
|
||||
VacDiagnostics.collect(context, dir)
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
markScrubbed(scrubTree(record))
|
||||
val scrubbed = markScrubbed(scrubTree(record))
|
||||
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
if (scrubbed) File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting session artifacts", e)
|
||||
}
|
||||
@@ -88,15 +94,10 @@ object SessionArtifacts {
|
||||
}?.toList() ?: return
|
||||
if (dirs.isEmpty()) return
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
val workers = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4)
|
||||
val pool = java.util.concurrent.Executors.newFixedThreadPool(workers) { r ->
|
||||
Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "scrub-logs")
|
||||
}
|
||||
val done = try {
|
||||
pool.invokeAll(dirs.map { dir -> java.util.concurrent.Callable { scrubAndMark(dir) } })
|
||||
.count { f -> try { f.get() } catch (e: Exception) { false } }
|
||||
} finally {
|
||||
pool.shutdown()
|
||||
var done = 0
|
||||
for (dir in dirs) {
|
||||
if (SessionState.running) break
|
||||
if (scrubAndMark(dir, stopWhenSessionStarts = true)) done++
|
||||
}
|
||||
val failed = dirs.size - done
|
||||
Log.i(TAG, "logs: scrubbed $done folders under r${LogRedactor.RULES_VERSION}" +
|
||||
@@ -114,35 +115,121 @@ object SessionArtifacts {
|
||||
private class Record(val dir: File) {
|
||||
val files = HashMap<File, Scrubbed>()
|
||||
var failed = false
|
||||
var deferred = false
|
||||
}
|
||||
|
||||
private fun scrubFolder(dir: File, record: Record) {
|
||||
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
|
||||
if (LogRedactor.isBinary(f)) return@forEach
|
||||
// Too large to rewrite in memory: the folder must not be recorded as scrubbed.
|
||||
if (!LogRedactor.isText(f)) { record.failed = true; return@forEach }
|
||||
val done = scrubFile(dir, f)
|
||||
if (done == null) record.failed = true else record.files[f] = done
|
||||
private sealed class ScrubResult {
|
||||
class Done(val scrubbed: Scrubbed) : ScrubResult()
|
||||
object Failed : ScrubResult()
|
||||
object Deferred : ScrubResult()
|
||||
}
|
||||
|
||||
private fun scrubFolder(
|
||||
dir: File,
|
||||
record: Record,
|
||||
shouldStop: () -> Boolean,
|
||||
beforeReplace: (File) -> Unit,
|
||||
listFiles: (File) -> Array<File>?,
|
||||
): Boolean {
|
||||
val files = listFiles(dir)?.filter { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }
|
||||
if (files == null) {
|
||||
record.failed = true
|
||||
return true
|
||||
}
|
||||
for (f in files) {
|
||||
if (shouldStop()) return false
|
||||
if (LogRedactor.isBinary(f)) continue
|
||||
when (val result = scrubFile(dir, f, shouldStop, beforeReplace)) {
|
||||
is ScrubResult.Done -> record.files[f] = result.scrubbed
|
||||
ScrubResult.Failed -> record.failed = true
|
||||
ScrubResult.Deferred -> {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun scrubFile(dir: File, f: File): Scrubbed? {
|
||||
private fun scrubFile(
|
||||
dir: File,
|
||||
f: File,
|
||||
shouldStop: () -> Boolean,
|
||||
beforeReplace: (File) -> Unit,
|
||||
): ScrubResult {
|
||||
val tmp = File(dir, ".${f.name}.scrub")
|
||||
return try {
|
||||
val before = Scrubbed(f.length(), f.lastModified())
|
||||
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
|
||||
val scrubbed = tmp.readBytes()
|
||||
if (scrubbed.contentEquals(f.readBytes())) {
|
||||
val scrubbed = tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w, shouldStop) }
|
||||
if (!scrubbed) {
|
||||
tmp.delete()
|
||||
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
|
||||
} else {
|
||||
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
|
||||
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
|
||||
return ScrubResult.Deferred
|
||||
}
|
||||
val scrubbedLength = tmp.length()
|
||||
when (sameContents(tmp, f, shouldStop)) {
|
||||
null -> {
|
||||
tmp.delete()
|
||||
ScrubResult.Deferred
|
||||
}
|
||||
true -> {
|
||||
tmp.delete()
|
||||
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
|
||||
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
|
||||
}
|
||||
false -> {
|
||||
if (shouldStop()) {
|
||||
tmp.delete()
|
||||
return ScrubResult.Deferred
|
||||
}
|
||||
beforeReplace(f)
|
||||
if (f.length() != before.length || f.lastModified() != before.modified) {
|
||||
tmp.delete()
|
||||
return ScrubResult.Failed
|
||||
}
|
||||
if (!tmp.renameTo(f)) {
|
||||
tmp.delete()
|
||||
return ScrubResult.Failed
|
||||
}
|
||||
Scrubbed(scrubbedLength, f.lastModified()).takeIf { f.length() == it.length }
|
||||
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${f.name}", e)
|
||||
tmp.delete()
|
||||
null
|
||||
ScrubResult.Failed
|
||||
}
|
||||
}
|
||||
|
||||
internal fun sameContents(a: File, b: File, shouldStop: () -> Boolean = { false }): Boolean? {
|
||||
if (shouldStop()) return null
|
||||
if (a.length() != b.length()) return false
|
||||
fun readChunk(input: java.io.InputStream, buffer: ByteArray): Int? {
|
||||
var count = 0
|
||||
while (count < buffer.size) {
|
||||
if (shouldStop()) return null
|
||||
val read = input.read(buffer, count, buffer.size - count)
|
||||
if (shouldStop()) return null
|
||||
if (read < 0) break
|
||||
if (read == 0) continue
|
||||
count += read
|
||||
}
|
||||
return count
|
||||
}
|
||||
return a.inputStream().buffered().use { left ->
|
||||
b.inputStream().buffered().use { right ->
|
||||
val leftBuffer = ByteArray(64 * 1024)
|
||||
val rightBuffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val leftCount = readChunk(left, leftBuffer) ?: return null
|
||||
val rightCount = readChunk(right, rightBuffer) ?: return null
|
||||
if (leftCount != rightCount) return false
|
||||
if (leftCount == 0) break
|
||||
if (shouldStop()) return null
|
||||
for (i in 0 until leftCount) if (leftBuffer[i] != rightBuffer[i]) return false
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,10 +270,44 @@ object SessionArtifacts {
|
||||
}.toSet()
|
||||
}
|
||||
|
||||
internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir)))
|
||||
internal fun scrubAndMark(
|
||||
dir: File,
|
||||
stopWhenSessionStarts: Boolean = false,
|
||||
beforeReplace: (File) -> Unit = {},
|
||||
listFiles: (File) -> Array<File>? = { it.listFiles() },
|
||||
sessionStarted: () -> Boolean = { SessionState.running },
|
||||
): Boolean {
|
||||
val shouldStop = { stopWhenSessionStarts && sessionStarted() }
|
||||
val record = scrubTree(
|
||||
Record(dir),
|
||||
listFiles = listFiles,
|
||||
beforeReplace = beforeReplace,
|
||||
shouldStop = shouldStop,
|
||||
)
|
||||
if (shouldStop()) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
}
|
||||
return markScrubbed(record)
|
||||
}
|
||||
|
||||
private fun scrubTree(record: Record): Record {
|
||||
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
|
||||
private fun scrubTree(
|
||||
record: Record,
|
||||
listFiles: (File) -> Array<File>? = { it.listFiles() },
|
||||
beforeReplace: (File) -> Unit = {},
|
||||
shouldStop: () -> Boolean = { false },
|
||||
): Record {
|
||||
for (dir in record.dir.walkTopDown().filter { it.isDirectory }) {
|
||||
if (shouldStop() || !scrubFolder(dir, record, shouldStop, beforeReplace, listFiles)) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (shouldStop()) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
@@ -205,6 +326,7 @@ object SessionArtifacts {
|
||||
private const val HEAD = 4096L
|
||||
|
||||
private class Mark(val size: Long, val head: String)
|
||||
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
|
||||
|
||||
fun markSteamLogs(dir: File, logs: File) {
|
||||
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
|
||||
@@ -240,23 +362,54 @@ object SessionArtifacts {
|
||||
.firstOrNull { m -> heads.getOrPut(minOf(m.size, HEAD)) { head(src, m.size) } == m.head }?.size ?: 0L
|
||||
}
|
||||
|
||||
private fun copySteamLogs(context: Context, dir: File, record: Record, steamArch: String? = null) {
|
||||
private fun copySteamLogs(
|
||||
context: Context,
|
||||
dir: File,
|
||||
record: Record,
|
||||
steamArch: String? = null,
|
||||
stopWhenSessionStarts: Boolean = false,
|
||||
) {
|
||||
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
|
||||
if (!logs.isDirectory) return
|
||||
val out = File(dir, "steam").apply { mkdirs() }
|
||||
copySessionLogs(logs, dir, out).forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
||||
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
|
||||
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
||||
record.failed = record.failed || result.failed
|
||||
record.deferred = record.deferred || result.deferred
|
||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||
}
|
||||
|
||||
internal fun copySessionLogs(logs: File, dir: File, out: File): List<File> {
|
||||
internal fun copySessionLogs(
|
||||
logs: File,
|
||||
dir: File,
|
||||
out: File,
|
||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
|
||||
|
||||
private fun copySessionLogsResult(
|
||||
logs: File,
|
||||
dir: File,
|
||||
out: File,
|
||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||
shouldStop: () -> Boolean,
|
||||
): CopyResult {
|
||||
val marks = steamLogMarks(dir)
|
||||
val copied = ArrayList<File>()
|
||||
logs.listFiles { f -> f.isFile }?.forEach { src ->
|
||||
var failed = false
|
||||
var deferred = false
|
||||
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
|
||||
for (src in sources) {
|
||||
if (shouldStop()) {
|
||||
failed = true
|
||||
deferred = true
|
||||
break
|
||||
}
|
||||
val size = src.length()
|
||||
val from = marks?.let { startOf(src, size, it) } ?: 0L
|
||||
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) return@forEach
|
||||
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) continue
|
||||
val dst = File(out, src.name)
|
||||
val staging = File(out, ".${src.name}.copy")
|
||||
try {
|
||||
val dst = File(out, src.name)
|
||||
src.inputStream().buffered().use { input ->
|
||||
var left = if (from > 0) from - 1 else 0L
|
||||
while (left > 0) {
|
||||
@@ -270,49 +423,183 @@ object SessionArtifacts {
|
||||
if (c < 0 || c == '\n'.code) break
|
||||
}
|
||||
}
|
||||
dst.bufferedWriter().use { w ->
|
||||
input.bufferedReader().forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
|
||||
val complete = openWriter(staging).use { w -> scrubSteamLog(input, w, shouldStop) }
|
||||
if (!complete) {
|
||||
staging.delete()
|
||||
failed = true
|
||||
deferred = true
|
||||
}
|
||||
}
|
||||
copied.add(dst)
|
||||
if (deferred) break
|
||||
Files.move(
|
||||
staging.toPath(),
|
||||
dst.toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
copied += dst
|
||||
} catch (e: Exception) {
|
||||
staging.delete()
|
||||
Log.w(TAG, "could not scrub ${src.name}", e)
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
return copied
|
||||
return CopyResult(copied, failed, deferred)
|
||||
}
|
||||
|
||||
private fun scrubSteamLog(
|
||||
input: java.io.InputStream,
|
||||
out: java.io.Writer,
|
||||
shouldStop: () -> Boolean,
|
||||
): Boolean {
|
||||
input.reader().use { reader ->
|
||||
val chunk = CharArray(8192)
|
||||
val line = StringBuilder(4096)
|
||||
var oversized = false
|
||||
var pendingContent = false
|
||||
var pendingCarriageReturn = false
|
||||
|
||||
fun emit() {
|
||||
out.write(if (oversized) LogRedactor.OVERSIZED_LINE else LogRedactor.redact(line.toString()))
|
||||
out.write("\n")
|
||||
line.setLength(0)
|
||||
oversized = false
|
||||
pendingContent = false
|
||||
}
|
||||
|
||||
while (true) {
|
||||
if (shouldStop()) return false
|
||||
val count = reader.read(chunk)
|
||||
if (count < 0) break
|
||||
if (shouldStop()) return false
|
||||
for (i in 0 until count) {
|
||||
if (shouldStop()) return false
|
||||
val char = chunk[i]
|
||||
if (pendingCarriageReturn) {
|
||||
emit()
|
||||
pendingCarriageReturn = false
|
||||
if (char == '\n') continue
|
||||
}
|
||||
when (char) {
|
||||
'\r' -> pendingCarriageReturn = true
|
||||
'\n' -> emit()
|
||||
else -> {
|
||||
pendingContent = true
|
||||
if (!oversized) {
|
||||
if (line.length < LogRedactor.MAX_LINE_LENGTH) line.append(char)
|
||||
else {
|
||||
line.setLength(0)
|
||||
oversized = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pendingCarriageReturn || pendingContent) {
|
||||
if (shouldStop()) return false
|
||||
emit()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun finishAbandoned(context: Context) {
|
||||
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
|
||||
val stopWhenSessionStarts = !beforeGuestStart
|
||||
val parent = LinuxRuntime.logDir(context)
|
||||
val abandoned = parent.listFiles { f ->
|
||||
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
|
||||
}?.sortedWith(SessionPaths.chronological) ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
val current = SessionPaths.current()
|
||||
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
abandoned.forEachIndexed { i, dir ->
|
||||
if (dir == current) return@forEachIndexed
|
||||
val newest = i == abandoned.lastIndex
|
||||
for (dir in abandoned) {
|
||||
if (stopWhenSessionStarts && SessionState.running) break
|
||||
if (dir == current) continue
|
||||
if (beforeGuestStart && dir != latestPreviousSession) continue
|
||||
val newest = dir == latestPreviousSession
|
||||
try {
|
||||
File(dir, "ended-without-teardown.txt").writeText(
|
||||
"This session's process ended without running its own teardown - killed by\n" +
|
||||
"Android, a native crash, or the device going down - so the files below were\n" +
|
||||
"gathered when the app next started, at ${now()}.\n" +
|
||||
"The logs written during the session (session.log, app.log, wayland.log,\n" +
|
||||
"audio.log, device.txt) were on disk already and are as they were left.\n" +
|
||||
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
)
|
||||
val recoveryNote = File(dir, "ended-without-teardown.txt")
|
||||
val runtimeCaptured = File(dir, RECOVERY_RUNTIME_CAPTURED_MARKER)
|
||||
val runtimeExpired = File(dir, RECOVERY_RUNTIME_EXPIRED_MARKER)
|
||||
val recoveryPreviouslyAttempted = recoveryNote.exists()
|
||||
val recoveryAttempted = recoveryPreviouslyAttempted &&
|
||||
(runtimeCaptured.exists() || runtimeExpired.exists() || !beforeGuestStart)
|
||||
if (!recoveryAttempted) {
|
||||
recoveryNote.writeText(
|
||||
"This session's process ended without running its own teardown - killed by\n" +
|
||||
"Android, a native crash, or the device going down - so the files below were\n" +
|
||||
"gathered when the app next started, at ${now()}.\n" +
|
||||
"The logs written during the session (session.log, app.log, wayland.log,\n" +
|
||||
"audio.log, device.txt) were on disk already and are as they were left.\n" +
|
||||
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
)
|
||||
}
|
||||
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
|
||||
(runtimeExpired.exists() || !beforeGuestStart) &&
|
||||
!recoveryNote.readText().contains("runtime capture did not finish")) {
|
||||
recoveryNote.appendText(
|
||||
"Steam's logs and VAC evidence are not included: runtime capture did not finish " +
|
||||
"before its evidence expired.\n"
|
||||
)
|
||||
}
|
||||
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() && !beforeGuestStart) {
|
||||
runtimeExpired.writeText("runtime evidence no longer belongs to this session, at ${now()}\n")
|
||||
}
|
||||
val record = Record(dir)
|
||||
if (newest) {
|
||||
copySteamLogs(context, dir, record, recordedClient(dir))
|
||||
VacDiagnostics.collect(context, dir)
|
||||
if (newest && !recoveryAttempted) {
|
||||
copySteamLogs(
|
||||
context,
|
||||
dir,
|
||||
record,
|
||||
steamArch = recordedClient(dir),
|
||||
stopWhenSessionStarts = stopWhenSessionStarts,
|
||||
)
|
||||
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
|
||||
if (!record.failed && VacDiagnostics.collect(context, dir)) {
|
||||
try {
|
||||
runtimeCaptured.writeText("collected at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
record.failed = true
|
||||
if (beforeGuestStart) {
|
||||
runtimeExpired.writeText("runtime capture marker failed, at ${now()}\n")
|
||||
}
|
||||
Log.w(TAG, "could not mark runtime capture for $dir", e)
|
||||
}
|
||||
} else {
|
||||
record.failed = true
|
||||
if (beforeGuestStart) {
|
||||
runtimeExpired.writeText("runtime capture failed, at ${now()}\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (record.deferred || stopWhenSessionStarts && SessionState.running) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
markScrubbed(record)
|
||||
break
|
||||
}
|
||||
val crashLog = File(dir, "crash.log")
|
||||
if (!crashLog.exists()) {
|
||||
SessionLogCapture.dumpCrashBuffer(crashLog)
|
||||
}
|
||||
if (stopWhenSessionStarts && SessionState.running) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
markScrubbed(record)
|
||||
break
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
markScrubbed(scrubTree(record))
|
||||
if (beforeGuestStart) return
|
||||
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
|
||||
val marked = markScrubbed(scrubbed)
|
||||
if (scrubbed.deferred) break
|
||||
if (!marked) continue
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
|
||||
Log.i(TAG, "finished the abandoned session folder $dir")
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -25,6 +25,8 @@ object SessionFiles {
|
||||
"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",
|
||||
"usr/local/bin/droiddeck-library-perms" to "usr/local/bin/droiddeck-library-perms",
|
||||
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
|
||||
"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",
|
||||
@@ -32,7 +34,7 @@ object SessionFiles {
|
||||
|
||||
/** Puts the session's files in place; [startsSession] is true only for the call that starts the Steam session. */
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) {
|
||||
if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
GameEnvironmentStore.publish(context)
|
||||
WinComponents.publish(context)
|
||||
@@ -70,10 +72,21 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
|
||||
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
|
||||
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
|
||||
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
|
||||
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
|
||||
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
|
||||
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
|
||||
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
|
||||
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
|
||||
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
|
||||
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
|
||||
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
|
||||
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
|
||||
"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",
|
||||
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
|
||||
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
|
||||
"usr/local/bin/droiddeck-gog-maintenance" to "usr/local/bin/droiddeck-gog-maintenance",
|
||||
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
|
||||
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
|
||||
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
|
||||
@@ -237,6 +250,7 @@ object SessionFiles {
|
||||
Log.e(TAG, "could not write steam-compatibility-label")
|
||||
}
|
||||
writeCjkFontConfig(root, etc)
|
||||
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
|
||||
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
|
||||
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
|
||||
if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n")
|
||||
@@ -244,6 +258,12 @@ object SessionFiles {
|
||||
stagedSocket.delete()
|
||||
Log.e(TAG, "could not write bwrap-socket")
|
||||
}
|
||||
val stagedRoot = File(droiddeckEtc, "root-socket.staged")
|
||||
if (!FileUtils.writeString(stagedRoot, com.droiddeck.launcher.runtime.RootSpawner.socket(context) + "\n")
|
||||
|| !stagedRoot.renameTo(File(droiddeckEtc, "root-socket"))) {
|
||||
stagedRoot.delete()
|
||||
Log.e(TAG, "could not write root-socket")
|
||||
}
|
||||
|
||||
BootMovie.syncFromSteam(context)
|
||||
val startupMovie = BootMovie.prepare(context)
|
||||
@@ -588,6 +608,28 @@ object SessionFiles {
|
||||
* The fonts themselves are bind-mounted by LinuxRuntime.bindSystemFonts() into
|
||||
* /usr/local/share/fonts/android; here we only need to point fontconfig at them.
|
||||
*/
|
||||
private val DESKTOP_STRINGS = listOf(
|
||||
"desktop_restore_title" to R.string.desktop_restore_title,
|
||||
"desktop_restore_body" to R.string.desktop_restore_body,
|
||||
"desktop_restore_done_title" to R.string.desktop_restore_done_title,
|
||||
"desktop_restore_done_body" to R.string.desktop_restore_done_body,
|
||||
"desktop_restore_failed_title" to R.string.desktop_restore_failed_title,
|
||||
"desktop_restore_failed_body" to R.string.desktop_restore_failed_body,
|
||||
)
|
||||
|
||||
private fun writeDesktopStrings(context: Context, dir: File) {
|
||||
val text = DESKTOP_STRINGS.joinToString("") { (key, id) ->
|
||||
key + "=" + context.getString(id).replace("\\", "\\\\").replace("%", "%%").replace("\n", "\\n") + "\n"
|
||||
}
|
||||
val target = File(dir, "strings")
|
||||
if (FileUtils.readString(target) == text) return
|
||||
val staged = File(dir, "strings.staged")
|
||||
if (!FileUtils.writeString(staged, text) || !staged.renameTo(target)) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write desktop strings")
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeCjkFontConfig(root: File, etc: File) {
|
||||
try {
|
||||
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
enum class SessionLaunchFailure {
|
||||
STEAM_ILLEGAL_INSTRUCTION,
|
||||
VULKAN_DEVICE_MISSING;
|
||||
|
||||
companion object {
|
||||
private val ANSI = Regex("\u001b\\[[0-?]*[ -/]*[@-~]")
|
||||
private val STEAM_EXIT = Regex("== steam exited rc=(\\d+)")
|
||||
|
||||
fun find(lines: Sequence<String>): SessionLaunchFailure? {
|
||||
var steamStarted = false
|
||||
var illegalInstruction = false
|
||||
var missingDevice = false
|
||||
lines.forEach { raw ->
|
||||
val line = ANSI.replace(raw, "").trim()
|
||||
when {
|
||||
line.startsWith("== droiddeck-session ") -> {
|
||||
steamStarted = false
|
||||
illegalInstruction = false
|
||||
missingDevice = false
|
||||
}
|
||||
line.startsWith("== STEP ") && line.contains("starting the Steam client") -> {
|
||||
steamStarted = true
|
||||
illegalInstruction = false
|
||||
}
|
||||
STEAM_EXIT.matches(line) && steamStarted ->
|
||||
illegalInstruction = STEAM_EXIT.matchEntire(line)?.groupValues?.get(1) == "132"
|
||||
line.startsWith("[gamescope]") && line.contains("vulkan:") -> when {
|
||||
line.contains("failed to find physical device") -> missingDevice = true
|
||||
line.contains("selecting physical device") -> missingDevice = false
|
||||
}
|
||||
}
|
||||
}
|
||||
return when {
|
||||
illegalInstruction -> STEAM_ILLEGAL_INSTRUCTION
|
||||
missingDevice -> VULKAN_DEVICE_MISSING
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,10 @@ object SessionPaths {
|
||||
|
||||
fun current(): File? = dir
|
||||
|
||||
/** Whether the current session folder will survive teardown. No session means the next one can retain logs. */
|
||||
fun currentSessionLogsRetained(context: Context): Boolean =
|
||||
dir?.let { it.parentFile == SessionFiles.logDirectory(context) } ?: true
|
||||
|
||||
fun lastEnded(): File? = ended?.takeIf { it.isDirectory }
|
||||
|
||||
@Synchronized
|
||||
|
||||
@@ -21,6 +21,8 @@ object SessionPrefs {
|
||||
private const val LEGACY_SUSPEND_DOWNLOADS = "downloads"
|
||||
private const val STEAM_DOWNLOADS_IN_BACKGROUND = "steamDownloadsInBackground"
|
||||
private const val DECKY_ZIP_WARNING_SEEN = "deckyZipWarningSeen"
|
||||
private const val SLOW_USB_WARNING_OFF = "slowUsbWarningOff"
|
||||
private const val SLOW_USB_DISMISSED = "slowUsbDismissed"
|
||||
|
||||
const val CONTROLLER_DECK = "deck"
|
||||
const val CONTROLLER_XBOX360 = "xbox360"
|
||||
@@ -84,6 +86,32 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("animations", on).apply()
|
||||
}
|
||||
|
||||
fun dualScreenMode(context: Context): String =
|
||||
prefs(context).getString("dualScreenMode", null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
|
||||
?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
|
||||
|
||||
fun setDualScreenMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("dualScreenMode", mode).apply()
|
||||
}
|
||||
|
||||
fun secondScreenPanel(context: Context): String? = prefs(context).getString("secondScreenPanel", null)
|
||||
|
||||
fun setSecondScreenPanel(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("secondScreenPanel", mode).apply()
|
||||
}
|
||||
|
||||
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
|
||||
|
||||
fun setDualScreenLauncher(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("dualScreenLauncher", on).apply()
|
||||
}
|
||||
|
||||
fun dualScreenSessionControls(context: Context): Boolean = prefs(context).getBoolean("dualScreenSessionControls", true)
|
||||
|
||||
fun setDualScreenSessionControls(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("dualScreenSessionControls", on).apply()
|
||||
}
|
||||
|
||||
fun gameStoresEnabled(context: Context): Boolean = prefs(context).getBoolean("gameStoresEnabled", true)
|
||||
|
||||
fun setGameStoresEnabled(context: Context, on: Boolean) {
|
||||
@@ -125,6 +153,30 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
|
||||
}
|
||||
|
||||
fun libraryCardLevel(context: Context): Int = prefs(context).getInt("libraryCardLevel", 2)
|
||||
|
||||
fun setLibraryCardLevel(context: Context, level: Int) {
|
||||
prefs(context).edit().putInt("libraryCardLevel", level).apply()
|
||||
}
|
||||
|
||||
fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", true)
|
||||
|
||||
fun setLibraryShowTitle(context: Context, show: Boolean) {
|
||||
prefs(context).edit().putBoolean("libraryShowTitle", show).apply()
|
||||
}
|
||||
|
||||
fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", true)
|
||||
|
||||
fun setLibraryShowSize(context: Context, show: Boolean) {
|
||||
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
|
||||
}
|
||||
|
||||
fun railLabels(context: Context): Boolean = prefs(context).getBoolean("railLabels", false)
|
||||
|
||||
fun setRailLabels(context: Context, show: Boolean) {
|
||||
prefs(context).edit().putBoolean("railLabels", show).apply()
|
||||
}
|
||||
|
||||
fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false)
|
||||
|
||||
fun setLibraryShowUninstalled(context: Context, show: Boolean) {
|
||||
@@ -195,7 +247,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("gameStoresParallel", count.coerceIn(1, 3)).apply()
|
||||
}
|
||||
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), !mangoappSession(context))
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false)
|
||||
|
||||
fun setHudEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean(hudKey(context), on).apply()
|
||||
@@ -233,6 +285,20 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun fusionHudConfig(context: Context): String? = prefs(context).getString("fusionHud", null)
|
||||
|
||||
fun setFusionHudConfig(context: Context, config: String) {
|
||||
prefs(context).edit().putString("fusionHud", config).apply()
|
||||
}
|
||||
|
||||
fun fusionHudPosition(context: Context): Pair<Float, Float>? =
|
||||
prefs(context).getString("fusionHudPos", null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
|
||||
?.takeIf { it.size == 2 }?.let { it[0] to it[1] }
|
||||
|
||||
fun setFusionHudPosition(context: Context, x: Float, y: Float) {
|
||||
prefs(context).edit().putString("fusionHudPos", "$x,$y").apply()
|
||||
}
|
||||
|
||||
const val HUD_COLOR_MINT = "mint"
|
||||
val HUD_COLORS = listOf(HUD_COLOR_MINT, "white", "sky", "amber", "violet")
|
||||
val HUD_OPACITY_RANGE = 30..100
|
||||
@@ -249,12 +315,34 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("lowLatency", on).apply()
|
||||
}
|
||||
|
||||
fun evdevMouse(context: Context): Boolean = prefs(context).getBoolean("evdevMouse", false)
|
||||
|
||||
fun setEvdevMouse(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("evdevMouse", on).apply()
|
||||
}
|
||||
|
||||
fun directCursor(context: Context): Boolean = prefs(context).getBoolean("directCursor", false)
|
||||
|
||||
fun setDirectCursor(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("directCursor", on).apply()
|
||||
}
|
||||
|
||||
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
||||
|
||||
fun setBackActionsInverted(context: Context, inverted: Boolean) {
|
||||
prefs(context).edit().putBoolean("backActionsInverted", inverted).apply()
|
||||
}
|
||||
|
||||
val BACK_DOUBLE_TAP_MS_OPTIONS = (100..800 step 100).toList()
|
||||
|
||||
fun backDoubleTapMs(context: Context): Int =
|
||||
prefs(context).getInt("backDoubleTapMs", 500).takeIf { it in BACK_DOUBLE_TAP_MS_OPTIONS } ?: 500
|
||||
|
||||
fun setBackDoubleTapMs(context: Context, ms: Int) {
|
||||
require(ms in BACK_DOUBLE_TAP_MS_OPTIONS)
|
||||
prefs(context).edit().putInt("backDoubleTapMs", ms).apply()
|
||||
}
|
||||
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
@@ -592,6 +680,8 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
|
||||
fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true)
|
||||
fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true)
|
||||
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
|
||||
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
@@ -642,8 +732,74 @@ object SessionPrefs {
|
||||
fun logsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("logs", true)
|
||||
|
||||
fun setLogsEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
fun setLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
|
||||
setLogPreference(
|
||||
context,
|
||||
key = "logs",
|
||||
oldValue = logsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
|
||||
)
|
||||
}
|
||||
|
||||
/** Extra Proton, Wine and graphics diagnostics for the next game launch; off unless chosen. */
|
||||
fun gameDebugLogsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("gameDebugLogsEnabled", false)
|
||||
|
||||
fun setGameDebugLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
|
||||
setLogPreference(
|
||||
context,
|
||||
key = "gameDebugLogsEnabled",
|
||||
oldValue = gameDebugLogsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
|
||||
)
|
||||
}
|
||||
|
||||
private fun setLogPreference(
|
||||
context: Context,
|
||||
key: String,
|
||||
oldValue: Boolean,
|
||||
newValue: Boolean,
|
||||
newEffective: Boolean,
|
||||
): Boolean {
|
||||
if (oldValue == newValue) return true
|
||||
val saved = prefs(context)
|
||||
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
|
||||
SessionPaths.currentSessionLogsRetained(context)
|
||||
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
|
||||
if (oldEffective == newEffective) {
|
||||
if (saved.edit().putBoolean(key, newValue).commit()) return true
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
return false
|
||||
}
|
||||
if (oldEffective && !newEffective) {
|
||||
try {
|
||||
publish(false)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("GameEnvironment", "Could not disable game diagnostics", e)
|
||||
return false
|
||||
}
|
||||
if (saved.edit().putBoolean(key, newValue).commit()) return true
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
runCatching { publish(oldEffective) }
|
||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
|
||||
return false
|
||||
}
|
||||
if (!saved.edit().putBoolean(key, newValue).commit()) {
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
return false
|
||||
}
|
||||
return try {
|
||||
publish(newEffective)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
runCatching { publish(oldEffective) }
|
||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
|
||||
android.util.Log.e("GameEnvironment", "Could not update game diagnostics", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
|
||||
@@ -951,22 +1107,24 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Performance mode: buffers go back to the game as soon as they are replaced
|
||||
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
|
||||
*/
|
||||
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
|
||||
|
||||
fun setPerformanceMode(context: Context, mode: String, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("performanceMode.$mode", on).apply()
|
||||
}
|
||||
|
||||
/** Compositor frame limit that releases buffers to the game unpaced. */
|
||||
const val FPS_UNPACED = -1
|
||||
|
||||
/** Mirroring still follows the glasses' refresh rate when Performance mode is on. */
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, performanceMode: Boolean): Int =
|
||||
if (performanceMode && mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
|
||||
/** The drawer's frame limit slider: its first stop is Off. */
|
||||
const val FPS_LIMIT_OFF = 15
|
||||
const val FPS_LIMIT_MAX = 120
|
||||
|
||||
/**
|
||||
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
|
||||
* Steam's Frame Limit in the Quick Access menu caps Steam games, and the drawer's limit caps games
|
||||
* launched without Steam. Mirroring still follows the glasses' refresh rate.
|
||||
*/
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0): Int = when {
|
||||
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
|
||||
mirrorRefreshLimit <= 0 -> sessionLimit
|
||||
sessionLimit <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(mirrorRefreshLimit, sessionLimit)
|
||||
}
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
|
||||
@@ -1147,7 +1305,7 @@ object SessionPrefs {
|
||||
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
|
||||
else prefMode(mode)
|
||||
|
||||
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
|
||||
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
|
||||
|
||||
fun setPipAutoEnter(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
|
||||
@@ -1190,7 +1348,8 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun suspendPolicy(context: Context, mode: String): String =
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}",
|
||||
if (mode == SessionService.MODE_STEAM) SUSPEND_NATIVE else SUSPEND_MANUAL)
|
||||
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
|
||||
?.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_NATIVE, SUSPEND_MANUAL, SUSPEND_NEVER) }
|
||||
?.let { if (mode != SessionService.MODE_STEAM && it == SUSPEND_NATIVE) SUSPEND_AUTO else it }
|
||||
@@ -1216,6 +1375,18 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean(DECKY_ZIP_WARNING_SEEN, true).apply()
|
||||
}
|
||||
|
||||
fun slowUsbWarningOff(context: Context): Boolean = prefs(context).getBoolean(SLOW_USB_WARNING_OFF, false)
|
||||
|
||||
fun setSlowUsbWarningOff(context: Context) {
|
||||
prefs(context).edit().putBoolean(SLOW_USB_WARNING_OFF, true).apply()
|
||||
}
|
||||
|
||||
fun slowUsbDismissed(context: Context): Set<String> = prefs(context).getStringSet(SLOW_USB_DISMISSED, null)?.toSet().orEmpty()
|
||||
|
||||
fun setSlowUsbDismissed(context: Context, keys: Set<String>) {
|
||||
prefs(context).edit().putStringSet(SLOW_USB_DISMISSED, keys.toSet()).apply()
|
||||
}
|
||||
|
||||
fun steamDownloadsInBackground(context: Context): Boolean {
|
||||
val prefs = prefs(context)
|
||||
return prefs.getBoolean(STEAM_DOWNLOADS_IN_BACKGROUND, false) ||
|
||||
|
||||
@@ -91,6 +91,7 @@ class SessionService : Service() {
|
||||
private var screenOn = true
|
||||
private var sessionDisplayId = Display.DEFAULT_DISPLAY
|
||||
private var manualPauseRequested = false
|
||||
private var manualHold = false
|
||||
private var steamSleepToken: String? = null
|
||||
private var nativeSleepToken: String? = null
|
||||
private var nativeSleepReady = false
|
||||
@@ -274,7 +275,11 @@ class SessionService : Service() {
|
||||
val hold = intent?.getBooleanExtra(EXTRA_HOLD, false) == true
|
||||
if (hold == signInHold) return START_NOT_STICKY
|
||||
signInHold = hold
|
||||
if (hold) manualPauseRequested = false
|
||||
if (hold) {
|
||||
manualPauseRequested = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
}
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
@@ -304,6 +309,14 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_PAUSE_NOW -> {
|
||||
if (!SessionState.running || SessionState.suspended || signInHold) return START_NOT_STICKY
|
||||
manualHold = true
|
||||
SessionState.manualPause = true
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_RESUME -> {
|
||||
resumeSession()
|
||||
return START_NOT_STICKY
|
||||
@@ -321,6 +334,7 @@ class SessionService : Service() {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
|
||||
SessionState.fpsLimit = 0
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
activityVisible = true
|
||||
@@ -346,6 +360,8 @@ class SessionService : Service() {
|
||||
SessionState.resumeRequested = false
|
||||
SessionState.resuming = false
|
||||
SessionState.resumeFailed = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
|
||||
@@ -385,10 +401,10 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
|
||||
SessionLogCapture.stopFor(dir)
|
||||
try {
|
||||
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
|
||||
} finally {
|
||||
SessionLogCapture.stopFor(dir)
|
||||
SessionPaths.release(this, dir)
|
||||
}
|
||||
}
|
||||
@@ -461,13 +477,20 @@ class SessionService : Service() {
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
|
||||
SessionArtifacts.awaitCollections()
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
|
||||
VacDiagnostics.arm(this)
|
||||
com.droiddeck.launcher.agent.AgentGuest.reset(this)
|
||||
com.droiddeck.launcher.stores.gog.GogComet.begin()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.start(this)
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
try {
|
||||
GameEnvironmentStore.publish(this)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not publish the game environment", e)
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
|
||||
Log.i(TAG, prootLine)
|
||||
@@ -480,6 +503,9 @@ class SessionService : Service() {
|
||||
val size = SessionState.outputSize
|
||||
val guest = ArrayList<String>()
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
runCatching { ComponentsManager.republish(this) }
|
||||
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
|
||||
.onFailure { Log.w(TAG, "component selections", it) }
|
||||
if (steamHere) {
|
||||
runCatching { ComponentsManager.ensureForcedPackages(this) }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
@@ -508,16 +534,9 @@ class SessionService : Service() {
|
||||
guest.add("DXVK_HDR=1")
|
||||
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
|
||||
}
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
|
||||
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
|
||||
if (SessionState.performanceMode) {
|
||||
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
|
||||
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
|
||||
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
|
||||
}
|
||||
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off"))
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long.
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
||||
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||
guest.add("BL_LOG=" + sessionLog.path)
|
||||
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
|
||||
@@ -525,6 +544,7 @@ class SessionService : Service() {
|
||||
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
|
||||
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
||||
SessionState.deckPad = false
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
deckBinds = emptyList()
|
||||
inputSysfs = null
|
||||
if (controllersOn) {
|
||||
@@ -735,7 +755,7 @@ class SessionService : Service() {
|
||||
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("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games")
|
||||
guest.add("TERM=xterm-256color")
|
||||
guest.add("LANG=C.UTF-8")
|
||||
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
|
||||
@@ -880,7 +900,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
|
||||
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
|
||||
FakeInputWriter.prepareRingSlots(fakeInputDir, 5)
|
||||
val builtinPad = SessionPrefs.builtinPad(this)
|
||||
val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad &&
|
||||
!com.droiddeck.launcher.input.PadBridge.anyControllerConnected()
|
||||
@@ -1038,7 +1058,7 @@ class SessionService : Service() {
|
||||
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
|
||||
}
|
||||
}
|
||||
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRoots(this)) {
|
||||
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRootsForXodus(this)) {
|
||||
if (host.isDirectory && host.canRead()) {
|
||||
File(LinuxRuntime.rootDir(this), guest.removePrefix("/")).mkdirs()
|
||||
binds.add(host.path + ":" + guest)
|
||||
@@ -1354,6 +1374,8 @@ class SessionService : Service() {
|
||||
if (panelVisible) activityVisible = true
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
suspendDownloadNow = false
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
|
||||
completeNativeSleep()
|
||||
@@ -1561,12 +1583,12 @@ class SessionService : Service() {
|
||||
manualPauseRequested = false
|
||||
}
|
||||
val controller = suspendController ?: return
|
||||
if (downloadsBlockingSuspend) acquireLocks()
|
||||
val steamPause = SessionState.mode == MODE_STEAM && !downloadsBlockingSuspend && when (suspendPolicy) {
|
||||
if (downloadsBlockingSuspend && !manualHold) acquireLocks()
|
||||
val steamPause = SessionState.mode == MODE_STEAM && (manualHold || !downloadsBlockingSuspend && when (suspendPolicy) {
|
||||
SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE -> hidden
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested
|
||||
else -> false
|
||||
}
|
||||
})
|
||||
if (!steamPause) {
|
||||
completeNativeSleep()
|
||||
} else if (nativeSleepToken == null && steamSleepToken == null &&
|
||||
@@ -1574,12 +1596,15 @@ class SessionService : Service() {
|
||||
prepareNativeSleep()
|
||||
}
|
||||
val prepared = SessionState.mode != MODE_STEAM || nativeSleepReady
|
||||
val shouldSuspend = steamSleepToken != null || when (suspendPolicy) {
|
||||
val shouldSuspend = steamSleepToken != null || (manualHold && prepared) || when (suspendPolicy) {
|
||||
SessionPrefs.SUSPEND_AUTO -> hidden && prepared && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend
|
||||
else -> false
|
||||
}
|
||||
// A frozen game never sends the stop for a held rumble, so the keepalive would run on.
|
||||
val quietRumble = !screenOn || shouldSuspend || SessionState.suspended
|
||||
components.forEach { (it as? RumbleComponent)?.quiet(quietRumble) }
|
||||
if (freezePending && !shouldSuspend && !freezeCancelled) {
|
||||
freezeCancelled = true
|
||||
controller.cancelFreeze()
|
||||
@@ -1619,6 +1644,8 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.suspend_cancelled")
|
||||
} else {
|
||||
suspendAttemptFailed = true
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
Log.w(TAG, "could not confirm that the session stopped")
|
||||
}
|
||||
}
|
||||
@@ -1667,7 +1694,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun resumeSteamSleepOnReturn() {
|
||||
if (suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
|
||||
if (!manualHold && suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
|
||||
completeNativeSleep()
|
||||
completeSteamSleep()
|
||||
@@ -1725,42 +1752,48 @@ class SessionService : Service() {
|
||||
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
|
||||
}
|
||||
|
||||
private fun finishSessionStop(status: Int, stoppedGen: Int) {
|
||||
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
|
||||
mainHandler.post {
|
||||
if (stoppedGen != sessionGen || SessionState.running) {
|
||||
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
|
||||
return@post
|
||||
try {
|
||||
if (stoppedGen != sessionGen || SessionState.running) {
|
||||
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
|
||||
return@post
|
||||
}
|
||||
SessionState.suspended = false
|
||||
SessionState.resumeRequested = false
|
||||
SessionState.resuming = false
|
||||
SessionState.resumeFailed = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.guestPid = -1
|
||||
com.droiddeck.launcher.agent.AgentGuest.stop()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
|
||||
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
|
||||
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
|
||||
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
|
||||
releaseLocks()
|
||||
MemoryLog.stop()
|
||||
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
|
||||
if (status == 0) {
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
|
||||
} else {
|
||||
val code = SessionState.failureCode ?: "GUEST_EXIT"
|
||||
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
|
||||
val failureStatus = SessionState.failureStatus ?: status
|
||||
SessionEvents.fail(code, message, failureStatus)
|
||||
}
|
||||
SessionState.steamVr = false
|
||||
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
|
||||
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
|
||||
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
|
||||
SessionState.notifyEnded(status)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
} finally {
|
||||
afterStopped()
|
||||
}
|
||||
SessionState.suspended = false
|
||||
SessionState.resumeRequested = false
|
||||
SessionState.resuming = false
|
||||
SessionState.resumeFailed = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.guestPid = -1
|
||||
com.droiddeck.launcher.agent.AgentGuest.stop()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
|
||||
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
|
||||
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
|
||||
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
|
||||
releaseLocks()
|
||||
MemoryLog.stop()
|
||||
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
|
||||
if (status == 0) {
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
|
||||
} else {
|
||||
val code = SessionState.failureCode ?: "GUEST_EXIT"
|
||||
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
|
||||
val failureStatus = SessionState.failureStatus ?: status
|
||||
SessionEvents.fail(code, message, failureStatus)
|
||||
}
|
||||
SessionState.steamVr = false
|
||||
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
|
||||
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
|
||||
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
|
||||
SessionState.notifyEnded(status)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1791,7 +1824,9 @@ class SessionService : Service() {
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
||||
SessionState.running = false
|
||||
SessionPaths.take() to SessionState.steamClientArch
|
||||
val ended = SessionPaths.take()
|
||||
if (ended != null) SessionArtifacts.collectionStarted(ended)
|
||||
ended to SessionState.steamClientArch
|
||||
}
|
||||
SessionState.micAvailable = false
|
||||
SessionState.micEnabled = false
|
||||
@@ -1820,8 +1855,6 @@ class SessionService : Service() {
|
||||
suspendController = null
|
||||
if (ended != null) {
|
||||
VacDiagnostics.snapshot(this, ended)
|
||||
SessionArtifacts.collectionStarted(ended)
|
||||
Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
|
||||
}
|
||||
components.reversed().forEach {
|
||||
try {
|
||||
@@ -1831,6 +1864,9 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
components.clear()
|
||||
val collectEnded = {
|
||||
if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
|
||||
}
|
||||
FakeInputWriter.releaseAllRingSlots()
|
||||
com.droiddeck.launcher.input.SteamTouchDevice.release()
|
||||
val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
@@ -1842,13 +1878,13 @@ class SessionService : Service() {
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
killGuestLeftovers()
|
||||
finishSessionStop(status, stoppedGen)
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
}, "session-teardown").start()
|
||||
} else {
|
||||
Thread({
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
finishSessionStop(status, stoppedGen)
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
}, "gog-session-stop").start()
|
||||
}
|
||||
@@ -1866,6 +1902,9 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (rootIntent?.component?.className in setOf(
|
||||
com.droiddeck.launcher.ui.DualScreenActivity::class.java.name,
|
||||
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return
|
||||
if (pipTask || xrActivityVisible) {
|
||||
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
|
||||
activityVisible = false
|
||||
@@ -2087,6 +2126,7 @@ class SessionService : Service() {
|
||||
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
|
||||
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
|
||||
const val ACTION_SUSPEND_NOW = "com.droiddeck.launcher.SUSPEND_NOW"
|
||||
private const val ACTION_PAUSE_NOW = "com.droiddeck.launcher.PAUSE_NOW"
|
||||
private const val ACTION_PIP_BEGIN = "com.droiddeck.launcher.PIP_BEGIN"
|
||||
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
|
||||
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
|
||||
@@ -2161,6 +2201,7 @@ class SessionService : Service() {
|
||||
fun stop(context: Context) {
|
||||
if (!SessionState.running) {
|
||||
SessionState.stopRequested = true
|
||||
SessionState.installCancellation?.cancel()
|
||||
return
|
||||
}
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
|
||||
@@ -2206,6 +2247,10 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold))
|
||||
}
|
||||
|
||||
fun pause(context: Context) {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PAUSE_NOW))
|
||||
}
|
||||
|
||||
fun resume(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
if (SessionState.suspended) SessionState.resumeRequested = true
|
||||
|
||||
@@ -37,6 +37,9 @@ object SessionState {
|
||||
@Volatile
|
||||
var installing: String? = null
|
||||
|
||||
@Volatile
|
||||
var installCancellation: com.droiddeck.launcher.core.Downloader.Cancellation? = null
|
||||
|
||||
@Volatile
|
||||
var stopRequested = false
|
||||
|
||||
@@ -53,6 +56,7 @@ object SessionState {
|
||||
var resuming by mutableStateOf(false)
|
||||
var resumeFailures by mutableIntStateOf(0)
|
||||
var resumeFailed by mutableStateOf(false)
|
||||
var manualPause by mutableStateOf(false)
|
||||
@Volatile var pipActive = false
|
||||
@Volatile
|
||||
var program: String? = null
|
||||
@@ -87,6 +91,7 @@ object SessionState {
|
||||
|
||||
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
|
||||
@Volatile var secondScreenDisplay = -1
|
||||
@Volatile var secondScreenAutoOpened = false
|
||||
|
||||
@Volatile
|
||||
var mode = "steam"
|
||||
@@ -103,8 +108,9 @@ object SessionState {
|
||||
@Volatile
|
||||
var upscaleRatio: Float = 0f
|
||||
|
||||
/** Frame limit chosen in the drawer for a game launched without Steam; 0 is off. */
|
||||
@Volatile
|
||||
var performanceMode = false
|
||||
var fpsLimit: Int = 0
|
||||
|
||||
@Volatile
|
||||
var firstFrameSeen = false
|
||||
|
||||
@@ -12,16 +12,17 @@ object SettingsReset {
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "fusionHud", "fusionHudPos", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition",
|
||||
"stretch16x9", "picturePosition", "railLabels",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
@@ -37,6 +38,7 @@ object SettingsReset {
|
||||
internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) }
|
||||
|
||||
fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection<String> = emptyList()): Boolean {
|
||||
if (!SessionPrefs.setGameDebugLogsEnabled(context, false)) return false
|
||||
var ok = true
|
||||
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit()
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object SteamImportPrompt {
|
||||
data class Ask(val token: String, val games: List<String>)
|
||||
|
||||
private fun folder(root: File) = File(root, "root/.cache/droiddeck")
|
||||
|
||||
fun read(root: File): Ask? {
|
||||
val text = runCatching { File(folder(root), "steam-import.json").readText() }.getOrNull() ?: return null
|
||||
val json = runCatching { JSONObject(text) }.getOrNull() ?: return null
|
||||
val token = json.optString("token").takeIf { it.isNotEmpty() } ?: return null
|
||||
val list = json.optJSONArray("games")
|
||||
val games = if (list == null) emptyList() else (0 until list.length()).mapNotNull { list.optString(it).takeIf(String::isNotBlank) }
|
||||
return Ask(token, games)
|
||||
}
|
||||
|
||||
fun answer(root: File, token: String, now: Boolean): Boolean = runCatching {
|
||||
val dir = folder(root).apply { mkdirs() }
|
||||
val temp = File(dir, "steam-import.answer.tmp")
|
||||
temp.writeText(JSONObject().put("token", token).put("choice", if (now) "now" else "later").toString())
|
||||
temp.renameTo(File(dir, "steam-import.answer"))
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.storage.StorageManager
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import java.io.File
|
||||
|
||||
object UsbLink {
|
||||
data class Link(val device: String, val mbps: Double, val name: String, val portMbps: Double?, val plug: String = "")
|
||||
|
||||
class SlowDrive(val key: String, val name: String, val mbps: Double, val portMbps: Double?) {
|
||||
val portLimited get() = portMbps != null && portMbps < FAST_MBPS
|
||||
}
|
||||
|
||||
const val FAST_MBPS = 5000.0
|
||||
|
||||
fun markShown(context: Context, drive: SlowDrive) = synchronized(this) {
|
||||
SessionPrefs.setSlowUsbDismissed(context, SessionPrefs.slowUsbDismissed(context) + drive.key)
|
||||
}
|
||||
|
||||
fun stillDue(context: Context, drive: SlowDrive) =
|
||||
!SessionPrefs.slowUsbWarningOff(context) && drive.key !in SessionPrefs.slowUsbDismissed(context)
|
||||
|
||||
fun slowLibrary(context: Context): SlowDrive? {
|
||||
if (SessionPrefs.slowUsbWarningOff(context)) return null
|
||||
val mounts = runCatching { File("/proc/self/mounts").readText() }.getOrNull() ?: return null
|
||||
val sm = context.getSystemService(StorageManager::class.java)
|
||||
val boot = runCatching { android.provider.Settings.Global.getInt(context.contentResolver, android.provider.Settings.Global.BOOT_COUNT) }.getOrDefault(0)
|
||||
val drives = libraries(context).mapNotNull { path ->
|
||||
val link = forPath(path, mounts) ?: return@mapNotNull null
|
||||
if (link.mbps >= FAST_MBPS) return@mapNotNull null
|
||||
val volume = runCatching { sm?.getStorageVolume(File(path))?.getDescription(context) }.getOrNull()
|
||||
SlowDrive(dismissKey(boot, link), link.name.ifBlank { volume.orEmpty() }.ifBlank { File(path).name }, link.mbps, link.portMbps)
|
||||
}
|
||||
return synchronized(this) {
|
||||
val dismissed = SessionPrefs.slowUsbDismissed(context)
|
||||
val current = dismissed.intersect(drives.map { it.key }.toSet())
|
||||
if (current != dismissed) SessionPrefs.setSlowUsbDismissed(context, current)
|
||||
drives.firstOrNull { it.key !in current }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun dismissKey(boot: Int, link: Link) = "$boot/${link.plug}/${link.device}@${link.mbps}"
|
||||
|
||||
private fun libraries(context: Context): List<String> {
|
||||
val pref = SessionPrefs.gameStorage(context)
|
||||
val storage = when (pref) {
|
||||
SessionPrefs.GAME_STORAGE_OFF -> null
|
||||
"" -> GameStorage.effective(context)?.path
|
||||
else -> pref
|
||||
}
|
||||
val folders = runCatching { AddedGames.roots(context).map { it.host.absolutePath } }.getOrDefault(emptyList())
|
||||
return (listOfNotNull(storage) + folders).map(::storagePath).filter { external(it) }.distinct()
|
||||
}
|
||||
|
||||
internal fun storagePath(path: String) = if (path.startsWith("/mnt/media_rw/")) "/storage/" + path.removePrefix("/mnt/media_rw/") else path
|
||||
|
||||
internal fun external(path: String) = path.startsWith("/storage/") && !path.startsWith("/storage/emulated/") && !path.startsWith("/storage/self/")
|
||||
|
||||
fun forPath(path: String, mounts: String, sys: File = File("/sys")): Link? {
|
||||
val device = mountDevice(rawPath(path), mounts) ?: return null
|
||||
val block = blockDir(device, sys) ?: return null
|
||||
val usb = usbDevice(block, sys) ?: return null
|
||||
val mbps = readSpeed(usb) ?: return null
|
||||
val name = listOf("manufacturer", "product").mapNotNull { read(File(usb, it)) }.joinToString(" ").trim()
|
||||
val plug = listOf("busnum", "devnum").mapNotNull { read(File(usb, it)) }.joinToString("-")
|
||||
return Link(device, mbps, name, portSpeed(usb, sys), plug)
|
||||
}
|
||||
|
||||
internal fun rawPath(path: String) = if (external(path)) "/mnt/media_rw/" + path.removePrefix("/storage/") else path
|
||||
|
||||
internal fun mountDevice(path: String, mounts: String): String? {
|
||||
var best: Pair<String, String>? = null
|
||||
for (line in mounts.lineSequence()) {
|
||||
val parts = line.split(' ')
|
||||
if (parts.size < 2) continue
|
||||
val point = parts[1].replace("\\040", " ")
|
||||
if (path != point && !path.startsWith("${point.trimEnd('/')}/")) continue
|
||||
if (best == null || point.length > best.first.length) best = point to parts[0]
|
||||
}
|
||||
val source = best?.second ?: return null
|
||||
Regex(":(\\d+),(\\d+)$").find(source)?.let { return "${it.groupValues[1]}:${it.groupValues[2]}" }
|
||||
return if (source.startsWith("/dev/block/") || source.startsWith("/dev/sd")) "name:" + source.substringAfterLast('/') else null
|
||||
}
|
||||
|
||||
internal fun blockDir(device: String, sys: File): File? {
|
||||
if (device.startsWith("name:")) return File(sys, "class/block/${device.removePrefix("name:")}").takeIf { it.exists() }?.canonicalFile
|
||||
File(sys, "dev/block/$device").takeIf { it.exists() }?.let { return it.canonicalFile }
|
||||
return File(sys, "class/block").listFiles()?.firstOrNull { read(File(it, "dev")) == device }?.canonicalFile
|
||||
}
|
||||
|
||||
internal fun usbDevice(block: File, sys: File): File? {
|
||||
val top = sys.canonicalFile
|
||||
var dir: File? = block
|
||||
while (dir != null && dir != top) {
|
||||
if (File(dir, "speed").isFile && File(dir, "idVendor").isFile) return dir
|
||||
dir = dir.parentFile
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun portSpeed(usb: File, sys: File): Double? {
|
||||
val bus = read(File(usb, "busnum")) ?: return null
|
||||
val hub = File(sys, "bus/usb/devices/usb$bus").takeIf { it.exists() }?.canonicalFile ?: return null
|
||||
val controller = hub.parentFile ?: return null
|
||||
return controller.listFiles { f -> f.name.matches(Regex("usb\\d+")) }?.mapNotNull { readSpeed(it) }?.maxOrNull()
|
||||
}
|
||||
|
||||
private fun readSpeed(dir: File) = read(File(dir, "speed"))?.toDoubleOrNull()
|
||||
|
||||
private fun read(file: File) = runCatching { file.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
fun generation(mbps: Double) = when {
|
||||
mbps <= 12 -> "USB 1.1"
|
||||
mbps < FAST_MBPS -> "USB 2.0"
|
||||
mbps < 10000 -> "USB 3.2 Gen 1"
|
||||
mbps < 20000 -> "USB 3.2 Gen 2"
|
||||
else -> "USB 3.2 Gen 2x2"
|
||||
}
|
||||
|
||||
fun megabytesPerSecond(mbps: Double) = (mbps / 8 * 0.7).toInt()
|
||||
}
|
||||
@@ -68,13 +68,13 @@ object VacDiagnostics {
|
||||
}
|
||||
}
|
||||
|
||||
fun collect(context: Context, dir: File) {
|
||||
fun collect(context: Context, dir: File): Boolean {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val kept = File(dir, SNAPSHOT_MARKER).takeIf { it.isFile }
|
||||
val marker = kept ?: File(root, MARKER)
|
||||
val launchList = if (kept != null) File(dir, SNAPSHOT_LAUNCHES) else File(root, LAUNCHES)
|
||||
if (!marker.isFile) return
|
||||
try {
|
||||
if (!marker.isFile) return true
|
||||
return try {
|
||||
val armed = marker.readLines().map { it.trim() }
|
||||
val since = (armed.getOrNull(0)?.toLongOrNull() ?: 0L) * 1000 - 5_000
|
||||
val arch = armed.getOrNull(1)?.takeIf { it.isNotEmpty() } ?: SessionPrefs.steamClientArch(context)
|
||||
@@ -125,8 +125,10 @@ object VacDiagnostics {
|
||||
File(dir, SNAPSHOT_MARKER).delete()
|
||||
File(dir, SNAPSHOT_LAUNCHES).delete()
|
||||
Log.i(TAG, "VAC diagnostics: ${consoles.size} console log(s), ${steamHits.size} client VAC line(s), into $dir")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting VAC diagnostics", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user