Merge latest origin/main and resolve conflicts

This commit is contained in:
DroidDeck Merge committed 2026-11-02 10:44:24 +08:00
commit 8171bf20fd
581 files changed
+14773 -4227

No files matched your search

@@ -56,7 +56,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
// Android can keep reporting charging at 100%; Linux reports Full there, and Steam shows 99% until it does.
val statusText = when (status) {
BatteryManager.BATTERY_STATUS_CHARGING -> if (pct >= 100) "Full" else "Charging"
BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
@@ -127,9 +126,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
companion object {
private const val TAG = "SessionService"
// CURRENT_NOW/CURRENT_AVERAGE are documented as µA, but Samsung and other vendors report mA,
// which made every lifetime estimate 1000x too long. No real µA reading under load is below 10 mA,
// and no mA reading is above 10 A, so anything smaller than 10_000 is taken as mA.
private const val MILLIAMP_CEILING = 10_000L
internal fun toMicroamps(raw: Long): Long = if (abs(raw) < MILLIAMP_CEILING) raw * 1000L else raw
@@ -24,7 +24,6 @@ object BootMovie {
DROIDDECK_60 to "droiddeck-startup-60.webm",
)
// Steam's CEF player only takes WebM codecs; MediaMuxer's WebM writer cannot take AV1.
internal val VIDEO_CODECS = setOf(MediaFormat.MIMETYPE_VIDEO_VP8, MediaFormat.MIMETYPE_VIDEO_VP9, MediaFormat.MIMETYPE_VIDEO_AV1)
private val REMUX_CODECS = setOf(MediaFormat.MIMETYPE_VIDEO_VP8, MediaFormat.MIMETYPE_VIDEO_VP9)
internal val AUDIO_CODECS = setOf(MediaFormat.MIMETYPE_AUDIO_OPUS, MediaFormat.MIMETYPE_AUDIO_VORBIS)
@@ -39,18 +38,14 @@ object BootMovie {
private fun dir(context: Context) = File(context.filesDir, "boot-movie")
private fun customFile(context: Context) = File(dir(context), "custom.webm")
/** A movie imported before movies were kept in Steam's own folder. */
internal fun legacyCustomFile(context: Context) = customFile(context)
/** Unpacks one of DroidDeck's own movies on demand; null for anything else. */
internal fun assetFile(context: Context, id: String): File? = ASSETS[id]?.let { extractAsset(context, it) }
/** Picking a movie here makes it Steam's startup movie at the next session, over whatever Steam had picked. */
fun select(context: Context, id: String) {
SessionPrefs.setBootMovie(context, id)
SessionPrefs.setBootMovieApplyNext(context, true)
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
// Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
@@ -67,7 +62,6 @@ object BootMovie {
}
}
/** The file the current choice plays from, before any volume or length change. */
fun currentFile(context: Context): File? = sourceOf(context, choice(context))
private fun sourceOf(context: Context, choice: String): File? = when {
@@ -84,7 +78,6 @@ object BootMovie {
return variant(context, source)
}
/** The movie as Steam should get it: with the chosen volume and cut off after the chosen number of seconds. */
private fun variant(context: Context, source: File): File? {
val volume = if (SessionPrefs.bootMovieSound(context)) SessionPrefs.bootMovieVolume(context) else 0
val seconds = SessionPrefs.bootMovieSeconds(context)
@@ -124,21 +117,15 @@ object BootMovie {
internal enum class Step { REMUX_SILENT, REMUX_AUDIO, TRANSCODE_SILENT, TRANSCODE_AUDIO, REGAIN }
/**
* How a movie is processed: the steps tried in order until one works, whether the source goes out untouched, and
* whether it still plays as it is when every step fails.
*/
internal class Plan(val passthrough: Boolean, val steps: List<Step>, val sourceOnFailure: Boolean)
internal fun plan(volume: Int, seconds: Int): Plan = when {
volume == 100 && seconds == 0 -> Plan(true, emptyList(), true)
volume == 0 -> Plan(false, listOf(Step.REMUX_SILENT, Step.TRANSCODE_SILENT), false)
// Only a length that could not be applied plays as it is; a volume that could not be applied plays no louder.
volume == 100 -> Plan(false, listOf(Step.REMUX_AUDIO, Step.TRANSCODE_AUDIO), true)
else -> Plan(false, listOf(Step.REGAIN, Step.REMUX_SILENT, Step.TRANSCODE_AUDIO), false)
}
/** Frames beyond 1920x1080 (4K and the like) have made Steam crash while it starts, so such a movie is always scaled down. */
internal const val MAX_LONG_SIDE = 1920
internal const val MAX_SHORT_SIDE = 1080
@@ -150,22 +137,16 @@ object BootMovie {
private fun isOversized(source: File): Boolean = probe(source)?.first?.let { oversized(it) } == true
/** A movie that is too large never goes out as it is: it is converted at the chosen volume, and plays nothing if that fails. */
internal fun oversizedPlan(volume: Int): Plan =
Plan(false, listOf(if (volume == 0) Step.TRANSCODE_SILENT else Step.TRANSCODE_AUDIO), false)
private fun transcodeSilent(source: File, target: File, limitUs: Long) =
BootMovieTranscoder.transcode(source, target, keepAudio = false, limitUs = limitUs) {} != null
/** Keeps at most the one processed copy in use, so trying settings never leaves movies piling up. */
private fun prune(folder: File, keep: String?) {
folder.listFiles()?.forEach { if (it.name != keep) it.delete() }
}
/**
* Takes over a startup movie chosen in Steam's own settings: when Steam's config names a movie it did not name before,
* that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
*/
fun syncFromSteam(context: Context): Boolean {
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context)
@@ -174,7 +155,6 @@ object BootMovie {
if (named == SessionFiles.BOOT_MOVIE_PATH || (named.isEmpty() && seen == null)) return false
val path = named.ifEmpty { "/movies/steam_os_startup.webm" }
val prefix = "/uioverrides/movies/"
// The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
val listed = BootMovieLibrary.list(context).firstOrNull { it.id.startsWith(BootMovieLibrary.STEAM_PREFIX) && it.id.endsWith(path) }
listed?.id ?: BootMovieLibrary.STEAM_PREFIX + path
@@ -9,22 +9,14 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import java.io.File
/**
* The boot movies a person can pick from: DroidDeck's own two, a movie imported before this list existed, every `.webm` in
* Steam's custom movies folder (imports, SteamDeckRepo and movies put there by hand; all of them can be removed), Steam's own
* three startup movies and the movies bought in Steam's points shop (neither can be removed).
*/
object BootMovieLibrary {
private const val TAG = "BootMovieLibrary"
const val PREFIX = "file:"
/** A movie Steam itself keeps outside its custom movies folder, such as one bought in its points shop: `steam:<path Steam names>`. */
const val STEAM_PREFIX = "steam:"
/** Held while the movie list is read and changed, so two imports at once cannot overwrite each other's entries. */
private val lock = Any()
/** Names DroidDeck stages the chosen movie under; they are copies, not movies of their own. */
internal val STAGED = setOf("bigpicture_startup.webm", "steam_os_startup.webm", "droiddeck-startup.webm")
const val SOURCE_DROIDDECK = "droiddeck"
@@ -37,28 +29,21 @@ object BootMovieLibrary {
internal fun moviesDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/config/uioverrides/movies")
/**
* The folders whose custom movies are listed, found and removed: [moviesDir], where imports are put and managed, then the
* x86-64 client's. The order never depends on which client is running, so a saved choice keeps meaning the same file.
*/
internal fun customMovieDirs(context: Context): List<File> =
listOf(moviesDir(context), File(SessionPrefs.steamRoot(context, "x86_64"), "config/uioverrides/movies")).distinctBy { it.path }
/** Where imported and installed movies are kept for good; Steam's folder holds a copy, which is put back if it goes missing. */
internal fun libraryDir(context: Context) = File(context.filesDir, "boot-movie/library")
private fun metaFile(context: Context) = File(context.filesDir, "boot-movie/movies.json")
internal fun steamRoot(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
/** The running (else selected) Steam client's config, the one whose startup movie choice is read and recorded. */
internal fun steamConfig(context: Context) = File(SessionPrefs.activeSteamRoot(context), "config/config.vdf")
private fun thumbsDir(context: Context) = File(context.filesDir, "boot-movie/thumbs")
fun idOf(name: String) = PREFIX + name
/** Every Steam client folder: the usual one and the x86-64 client's. */
internal fun steamRoots(context: Context): List<File> = listOf(
steamRoot(context), File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/.local/share/Steam"),
).filter { it.isDirectory }
@@ -86,7 +71,6 @@ object BootMovieLibrary {
private fun readMeta(context: Context): JSONObject =
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
/** Changes the movie list one writer at a time; [change] gets the list and returns whether to save it. */
private fun editMeta(context: Context, change: (JSONObject) -> Boolean) = synchronized(lock) {
val meta = readMeta(context)
if (change(meta)) {
@@ -100,7 +84,6 @@ object BootMovieLibrary {
}
}
/** The post a movie was installed from, if it came from SteamDeckRepo. */
fun repoId(context: Context, name: String): String? =
readMeta(context).optJSONObject(name)?.optString("repo")?.takeIf { it.isNotEmpty() }
@@ -128,7 +111,6 @@ object BootMovieLibrary {
val info = meta.optJSONObject(f.name)
val source = info?.optString("source")?.takeIf { it.isNotEmpty() } ?: SOURCE_STEAM
val title = info?.optString("title")?.takeIf { it.isNotEmpty() } ?: f.nameWithoutExtension
// Everything in Steam's custom movies folder is the person's own (imported, from SteamDeckRepo or put there by hand).
out.add(Entry(idOf(f.name), title, if (source == SOURCE_STEAM) SOURCE_IMPORT else source, f, removable = true))
}
val steam = LinkedHashMap<String, File>()
@@ -147,14 +129,12 @@ object BootMovieLibrary {
for ((id, file) in steam) {
val native = file.nameWithoutExtension.lowercase() in NATIVE
if ((file.name in STAGED && !native) || !seen.add(file.canonicalPath)) continue
// Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
}
return out
}
/** The four startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf(
"deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup",
"steam_os_startup" to "SteamOS startup",
@@ -167,13 +147,8 @@ object BootMovieLibrary {
private val scans = HashMap<String, Scan>()
/** Forgets the last search for Steam's own movies. */
internal fun forgetScan() = synchronized(scanLock) { scans.clear() }
/**
* Movies Steam keeps outside its custom movies folder, such as ones bought in its points shop: every `.webm` below the
* client's config, cache and user folders. The search is repeated at most every 15 seconds for each client folder.
*/
private fun pointShopMovies(root: File): Scan = synchronized(scanLock) {
val now = System.currentTimeMillis()
scans[root.path]?.let { if (now - it.at < 15_000L) return it }
@@ -191,10 +166,8 @@ object BootMovieLibrary {
scan
}
/** The item number in the name Steam gives a bought movie, `<item number>_<hash>.webm`; null for any other name. */
private fun boughtId(file: File) = Regex("^(\\d+)_").find(file.nameWithoutExtension)?.groupValues?.get(1)
/** What the points shop calls a bought movie, from the list of startup movies Steam keeps in each user's local config. */
private fun boughtTitle(root: File, id: String): String? {
val key = "communityitemid\\\":\\\"$id\\\""
val title = Regex("item_title\\\\\":\\\\\"([^\\\\\"]*)")
@@ -209,7 +182,6 @@ object BootMovieLibrary {
private const val OVERRIDES = "/uioverrides/movies/"
/** Puts back, in Steam's folder, any movie of DroidDeck's that went missing there, such as after the runtime was reset. */
internal fun restore(context: Context) = synchronized(lock) {
migrateLegacyMeta(context)
val meta = readMeta(context)
@@ -222,7 +194,6 @@ object BootMovieLibrary {
}
}
/** Takes in the movie notes an earlier version kept inside Steam's movies folder, so those movies keep their title and source. */
private fun migrateLegacyMeta(context: Context) {
val legacy = File(moviesDir(context), ".droiddeck-movies.json")
if (!legacy.isFile) return
@@ -238,7 +209,6 @@ object BootMovieLibrary {
legacy.delete()
}
/** Copies [kept] to [copy] through a staging name, so Steam never sees half a movie. */
private fun mirror(kept: File, copy: File): Boolean {
val staged = File(copy.parentFile, copy.name + ".${System.nanoTime()}.staged")
return try {
@@ -255,10 +225,8 @@ object BootMovieLibrary {
fun title(context: Context, id: String): String = list(context).firstOrNull { it.id == id }?.title ?: id
/** The file a movie id plays from; DroidDeck's own movies live in the app and are unpacked on demand. */
fun fileOf(context: Context, entry: Entry): File? = entry.file ?: BootMovie.assetFile(context, entry.id)
/** A free `.webm` name for a movie called [title]; the same title twice gets " (2)", " (3)"… */
fun freeName(context: Context, title: String): String {
val base = title.replace(Regex("[^\\p{L}\\p{N} ._()\\-]"), "").replace(Regex("\\s+"), " ").trim().trim('.').take(60).ifEmpty { "movie" }
val dirs = customMovieDirs(context)
@@ -269,10 +237,6 @@ object BootMovieLibrary {
return name
}
/**
* Keeps the finished movie [staged] (a file in [libraryDir]) under a free name, copies it into Steam's folder and notes its
* title, source and cover. Returns the name, or null when it could not be kept. Runs one movie at a time.
*/
internal fun commit(context: Context, staged: File, title: String, source: String, repoId: String? = null, cover: ByteArray? = null): String? =
synchronized(lock) {
val name = freeName(context, title)
@@ -283,7 +247,6 @@ object BootMovieLibrary {
name
}
/** Notes a movie that was just put into Steam's folder: what to call it, where it came from and its cover. */
fun register(context: Context, name: String, title: String, source: String, repoId: String? = null, cover: ByteArray? = null) {
editMeta(context) { meta ->
val info = JSONObject().put("title", title).put("source", source)
@@ -301,12 +264,10 @@ object BootMovieLibrary {
val removed = when {
id == BootMovie.CUSTOM -> { BootMovie.removeCustom(context); true }
else -> {
// Only movies in Steam's custom movies folder are ever deleted; Steam's own and points shop movies are left alone.
if (!id.startsWith(PREFIX)) return false
val name = id.removePrefix(PREFIX)
if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return false
val copies = customMovieDirs(context).map { File(it, name) }
// A name can exist in more than one client's folder; the entry is the first one found (see customMovieDirs), and only that file is deleted.
val target = copies.firstOrNull { it.exists() }
val managed = File(libraryDir(context), name)
if (readMeta(context).optJSONObject(name) == null && target == null && !managed.isFile) return false
@@ -335,14 +296,12 @@ object BootMovieLibrary {
return removed
}
/** What every processed copy of [source] starts with; the hash of its full path keeps same-named files in different places apart. */
internal fun variantPrefix(source: File) = safe(source.name) + "." + Integer.toHexString(source.absolutePath.hashCode()) + "-"
private fun safe(name: String) = name.replace(Regex("[^A-Za-z0-9._-]"), "_")
private fun coverName(name: String) = "cover-" + safe(name)
/** How long a movie runs, in whole seconds; 0 when it cannot be read. */
fun durationSeconds(file: File?): Int {
if (file == null || !file.isFile) return 0
val retriever = MediaMetadataRetriever()
@@ -357,7 +316,6 @@ object BootMovieLibrary {
}
}
/** The first frame that is not nearly black out of several taken through the movie, else the brightest; a movie may open dark. */
private fun brightestFrame(retriever: MediaMetadataRetriever, durationMs: Long): Bitmap? {
var best: Bitmap? = null
var bestLuma = -1
@@ -382,11 +340,9 @@ object BootMovieLibrary {
private const val MIN_COVER_LUMA = 24
/** A cover for a movie: the picture SteamDeckRepo gave it, or one frame taken from the video and remembered. */
fun cover(context: Context, entry: Entry): File? {
val file = fileOf(context, entry) ?: return null
val name = if (entry.id.startsWith(PREFIX)) file.name else entry.id
// Points Shop covers once kept a picture that was not always the movie's own; those files are not used.
val given = File(thumbsDir(context), if (entry.source == SOURCE_POINTSHOP) "v2-" + coverName(name) else coverName(name))
if (given.isFile && given.length() > 0L) return given
val key = "frame-" + safe(name) + "-v2-" + file.length() + "-" + file.lastModified() + ".jpg"
@@ -8,10 +8,6 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* What DroidDeck and Steam know about boot movies, in one text file: Steam's startup movie setting, every movie file and
* where it lives, DroidDeck's own state, and a short trace of what each session start did to Steam's config.
*/
object BootMovieReport {
private const val TAG = "BootMovieReport"
private const val MAX_TRACE_LINES = 200
@@ -23,7 +19,6 @@ object BootMovieReport {
private fun traceFile(context: Context) = File(context.filesDir, "boot-movie/apply.log")
/** Adds a line to the short trace kept for the report; only the latest lines are kept. */
fun note(context: Context, line: String) {
synchronized(lock) {
runCatching {
@@ -36,7 +31,6 @@ object BootMovieReport {
}
}
/** Writes the report to Downloads/DroidDeck, or to the app's own folder when that is not possible; null when the report cannot be built or neither folder works. */
fun write(context: Context): File? {
val text = runCatching { build(context) }.getOrElse {
Log.w(TAG, "could not build the report", it)
@@ -46,7 +46,6 @@ internal object BootMovieTranscoder {
return Result(audioDropped = hadAudio && !muxedAudio)
}
/** Copies the video of [source] untouched and gives it its sound again at [gain] of its level, cut to [limitUs]. */
fun regain(source: File, target: File, gain: Float, limitUs: Long): Boolean {
val audio = runCatching { encodeAudio(source, gain, limitUs) }
.onFailure { Log.w(TAG, "could not change the volume of ${source.name}", it) }.getOrNull() ?: return false
@@ -121,7 +120,6 @@ internal object BootMovieTranscoder {
internal class Layout(val width: Int, val height: Int, val x: Int, val y: Int, val contentWidth: Int, val contentHeight: Int)
// Steam fills the screen with its startup movie, so portrait clips are pillarboxed into 16:9 instead of cropped.
internal fun layout(width: Int, height: Int, rotation: Int): Layout {
val (w, h) = if (rotation % 180 != 0) height to width else width to height
fun even(v: Double) = maxOf(2, (v.toInt() / 2) * 2)
@@ -137,7 +135,6 @@ internal object BootMovieTranscoder {
return Layout(canvas, ch, (canvas - cw) / 2, 0, cw, ch)
}
/** [pcm] made quieter by [gain] and cut to its first [limitUs] microseconds. */
internal fun scale(pcm: ShortArray, channels: Int, gain: Float, limitUs: Long): ShortArray {
val frames = pcm.size / channels
val kept = if (limitUs == Long.MAX_VALUE) frames else minOf(frames.toLong(), limitUs * OPUS_RATE / 1_000_000L).toInt()
@@ -164,7 +161,6 @@ internal object BootMovieTranscoder {
return out
}
/** Most decoded audio held in memory at once: about six minutes of 48 kHz stereo. */
private const val MAX_PCM_BYTES = 64 shl 20
private fun encodeAudio(source: File, gain: Float = 1f, limitUs: Long = Long.MAX_VALUE): Audio? {
@@ -212,7 +208,6 @@ internal object BootMovieTranscoder {
}
dec.releaseOutputBuffer(index, false)
if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break
// Past the length that will be kept there is nothing more to decode; without a length, a track too big to hold is dropped.
if (limitUs != Long.MAX_VALUE && info.presentationTimeUs > limitUs) break
if (pcm.size() > MAX_PCM_BYTES) { if (limitUs == Long.MAX_VALUE) return null else break }
}
@@ -0,0 +1,353 @@
package com.droiddeck.launcher.session
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.util.Log
import android.view.Surface
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.runtime.DesktopCatalog
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.wayland.BottomDesktopCompositorService as Comp
import java.io.File
/**
* KDE Plasma on the bottom screen while the session keeps the top one: its own compositor process
* ([Comp]) and a second guest started with the session's environment, like the bottom-screen terminal.
*/
object BottomDesktop {
private const val TAG = "BottomDesktop"
const val SCRIPT = "/usr/local/bin/droiddeck-bottom-desktop"
private const val TARGET_SHORT_SIDE = 720f
enum class State { OFF, STARTING, RUNNING, ENDED, FAILED }
private class Launch(
val guest: List<String>,
val binds: List<String>,
val sessionRoot: File,
val hostEnvironment: Array<String>,
val root: File,
val sessionDir: File,
val generation: Int,
val installed: Boolean,
)
@Volatile private var launch: Launch? = null
private val launchLock = Any()
private val main = Handler(Looper.getMainLooper())
private val listeners = LinkedHashSet<() -> Unit>()
@Volatile var state = State.OFF
private set
private var onTextInput: ((Boolean) -> Unit)? = null
private var imeWatcher: android.os.FileObserver? = null
private var appContext: Context? = null
private var service: Messenger? = null
private var binding: ServiceConnection? = null
private var pendingAttach: Message? = null
/** The desktop guest's proot: -1 when there is none, 0 while it is being started. */
@Volatile private var guestPid = -1
/** The proot to freeze with the session when it pauses. */
val suspendPid: Int get() = guestPid
private var guestGeneration = 0
private var outputSize = 0 to 0
private var cursorShown = false
/** The session generation whose launch the running compositor and guest belong to; -1 when none. */
private var owner = -1
private val replies = Messenger(object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
if (msg.arg1 != owner) return
when (msg.what) {
Comp.MSG_ATTACHED -> {
service?.let { send(it, Message.obtain(null, Comp.MSG_CURSOR, if (cursorShown) 1 else 0, 0)) }
if (guestPid < 0 && state == State.STARTING) startGuest()
}
Comp.MSG_FIRST_FRAME -> if (state == State.STARTING) setState(State.RUNNING)
}
}
})
fun prepare(
guest: List<String>,
binds: List<String>,
sessionRoot: File,
hostEnvironment: Array<String>,
root: File,
sessionDir: File,
generation: Int,
stillCurrent: () -> Boolean,
) {
val prepared = Launch(ArrayList(guest), ArrayList(binds), sessionRoot, hostEnvironment.copyOf(), root, sessionDir, generation,
DesktopCatalog.desktopInstalled(root))
synchronized(launchLock) { if (stillCurrent()) launch = prepared }
}
fun available(): Boolean =
launch?.installed == true && SessionState.running && SessionState.mode != SessionService.MODE_DESKTOP
/**
* The desktop renders below the panel's resolution: about 720 pixels on the short side keeps
* Plasma's text big enough to touch and its software rendering cheap. A running desktop keeps its size.
*/
fun outputSizeFor(width: Int, height: Int): Pair<Int, Int> {
if ((state == State.STARTING || state == State.RUNNING) && outputSize.first > 0) return outputSize
if (width <= 0 || height <= 0) return 0 to 0
val scale = maxOf(1f, Math.round(minOf(width, height) / TARGET_SHORT_SIDE * 2f) / 2f)
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
}
fun addListener(listener: () -> Unit) { listeners.add(listener) }
fun removeListener(listener: () -> Unit) { listeners.remove(listener) }
/** Called on the main thread when a text field in the desktop gains or loses focus (droiddeck-ime's report). */
fun setTextInputListener(listener: ((Boolean) -> Unit)?) { onTextInput = listener }
private fun watchIme(dir: File) {
imeWatcher?.stopWatching()
dir.deleteRecursively()
dir.mkdirs()
@Suppress("DEPRECATION")
imeWatcher = object : android.os.FileObserver(dir.path, MOVED_TO or CLOSE_WRITE) {
override fun onEvent(event: Int, path: String?) {
if (path != "ime.json") return
val focused = runCatching { org.json.JSONObject(File(dir, path).readText()).optBoolean("textField") }
.getOrNull() ?: return
main.post { if (imeWatcher === this) onTextInput?.invoke(focused) }
}
}.also { it.startWatching() }
}
private fun setState(next: State) {
if (Looper.myLooper() != Looper.getMainLooper()) { main.post { setState(next) }; return }
if (state == next) return
Log.i(TAG, "state $state -> $next")
state = next
listeners.toList().forEach { it() }
}
fun attach(context: Context, surface: Surface, width: Int, height: Int, refreshHz: Float) {
val current = launch
if (current == null || !SessionState.running) {
setState(State.FAILED)
return
}
if (owner != -1 && owner != current.generation) stop(context, owner)
appContext = context.applicationContext
owner = current.generation
outputSize = width to height
val dir = File(current.sessionDir, "bottom-desktop").apply { mkdirs() }
val msg = Message.obtain(null, Comp.MSG_ATTACH).apply {
arg1 = owner
obj = surface
replyTo = replies
data = Bundle().apply {
putString(Comp.KEY_RUNTIME_DIR, runtimeDir(context).path)
putInt(Comp.KEY_WIDTH, width)
putInt(Comp.KEY_HEIGHT, height)
putFloat(Comp.KEY_REFRESH, refreshHz)
putString(Comp.KEY_LOG, File(dir, "wayland.log").path)
}
}
if (state == State.OFF || state == State.ENDED || state == State.FAILED) setState(State.STARTING)
val target = service
if (target != null) send(target, msg) else {
pendingAttach = msg
bind(context.applicationContext)
}
}
fun detach() {
pendingAttach = null
service?.let { send(it, Message.obtain(null, Comp.MSG_DETACH)) }
}
fun sendTouch(action: Int, pointerId: Int, x: Int, y: Int) {
val target = service ?: return
send(target, Message.obtain(null, Comp.MSG_TOUCH, (pointerId shl 8) or (action and 0xff),
(x.coerceIn(0, 0xffff) shl 16) or y.coerceIn(0, 0xffff)))
}
fun sendPointer(x: Int, y: Int) {
val target = service ?: return
send(target, Message.obtain(null, Comp.MSG_POINTER, x, y))
}
/** Button (3), wheel (4) and smooth-scroll (12) input, as `WaylandCompositor.nativeSendSceneInput` takes it. */
fun sendScene(type: Int, a: Int, b: Int = 0) {
val target = service ?: return
send(target, Message.obtain(null, Comp.MSG_SCENE, type, a).apply {
if (b != 0) data = Bundle().apply { putInt(Comp.KEY_B, b) }
})
}
fun showCursor(on: Boolean) {
cursorShown = on
service?.let { send(it, Message.obtain(null, Comp.MSG_CURSOR, if (on) 1 else 0, 0)) }
}
/** False when the next attach starts a new compositor process, which needs a surface no earlier one used. */
val connected: Boolean get() = service != null
fun sendKey(evdev: Int, down: Boolean) {
val target = service ?: return
send(target, Message.obtain(null, Comp.MSG_KEY, evdev, if (down) 1 else 0))
}
fun sendText(text: String) {
val target = service ?: return
send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } })
}
fun stop(context: Context, generation: Int? = null) {
if (Looper.myLooper() != Looper.getMainLooper()) { main.post { stop(context, generation) }; return }
synchronized(launchLock) {
if (generation != null && launch?.generation == generation) launch = null
}
// A newer session may already have prepared its launch; only the desktop the stopped session started goes.
if (generation != null && owner != generation) return
owner = -1
val pid = guestPid
guestPid = -1
guestGeneration++
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
service?.let { send(it, Message.obtain(null, Comp.MSG_STOP)) }
binding?.let { runCatching { context.applicationContext.unbindService(it) } }
binding = null
service = null
pendingAttach = null
imeWatcher?.stopWatching()
imeWatcher = null
setState(State.OFF)
}
private fun bind(context: Context) {
if (binding != null) return
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
if (binding !== this || binder == null) return
val messenger = Messenger(binder)
service = messenger
pendingAttach?.let { send(messenger, it) }
pendingAttach = null
}
override fun onServiceDisconnected(name: ComponentName?) {
if (binding !== this) return
Log.w(TAG, "the desktop's compositor process died")
service = null
binding = null
runCatching { context.unbindService(this) }
val pid = guestPid
guestPid = -1
guestGeneration++
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
imeWatcher?.stopWatching()
imeWatcher = null
owner = -1
setState(State.FAILED)
}
}
binding = connection
val bound = runCatching {
context.bindService(Intent(context, Comp::class.java), connection,
Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT)
}.getOrDefault(false)
if (!bound) {
Log.e(TAG, "could not bind the desktop's compositor")
binding = null
setState(State.FAILED)
}
}
private fun send(target: Messenger, msg: Message) {
runCatching { target.send(msg) }.onFailure { Log.w(TAG, "compositor message ${msg.what} not delivered", it) }
}
private fun runtimeDir(context: Context) = File(context.filesDir, ".wayland-rt-bottom")
private fun startGuest() {
val context = appContext ?: return
val current = launch
if (current == null || !SessionState.running || current.generation != owner) {
setState(State.FAILED)
return
}
// A freeze collects its helpers once, when it begins; a guest started after that would run on unfrozen.
if (SessionState.suspended || SessionState.suspending) {
setState(State.OFF)
return
}
val generation = ++guestGeneration
guestPid = 0
val (width, height) = outputSize
service?.let { send(it, Message.obtain(null, Comp.MSG_NEW_GUEST)) }
Thread({
if (!DesktopCatalog.desktopInstalled(current.root)) {
Log.e(TAG, "the desktop package is not installed")
main.post { if (generation == guestGeneration) { guestPid = -1; setState(State.FAILED) } }
return@Thread
}
val dir = File(current.sessionDir, "bottom-desktop").apply { mkdirs() }
val runtime = runtimeDir(context).apply { mkdirs() }
val imeDir = File(current.sessionRoot, "bottom-desktop-ime")
main.post { if (generation == guestGeneration) watchIme(imeDir) }
val binds = LinuxRuntime.binds(context, current.sessionRoot, runtime, Environment.getExternalStorageDirectory(), current.binds)
val guest = ArrayList(current.guest).apply {
add("BL_WIDTH=$width")
add("BL_HEIGHT=$height")
add("BL_DEBUG_DIR=" + dir.path)
add("BL_TOP_SESSION=" + SessionState.mode)
add("BL_IME_DIR=" + imeDir.path)
add(SCRIPT)
}
val command = LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
val pid = HostProcess.start(line, current.hostEnvironment, current.root, { status ->
main.post {
if (generation != guestGeneration) return@post
Log.i(TAG, "the desktop ended ($status)")
SessionService.terminalProcessExited(context, guestPid)
guestPid = -1
guestGeneration++
setState(if (state == State.RUNNING || status == 0) State.ENDED else State.FAILED)
}
}, null, File(dir, "proot.log"))
main.post {
if (generation != guestGeneration || launch !== current) {
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
if (generation == guestGeneration) guestPid = -1
return@post
}
if (pid <= 1) {
guestPid = -1
Log.e(TAG, "the desktop's guest did not start")
setState(State.FAILED)
return@post
}
if (SessionState.suspended || SessionState.suspending) {
SessionService.stopTerminalProcess(context, pid)
guestPid = -1
guestGeneration++
setState(State.OFF)
return@post
}
guestPid = pid
SessionService.registerTerminalProcess(context, pid)
Log.i(TAG, "desktop guest pid $pid at ${width}x$height")
}
}, "bottom-desktop-start").start()
}
}
@@ -7,13 +7,8 @@ import android.service.notification.StatusBarNotification
import androidx.compose.runtime.mutableStateListOf
import androidx.core.app.NotificationManagerCompat
/** One notification for the bottom-screen list. Kept in memory only; never written to disk or logs. */
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
/**
* Notifications from other apps for the bottom screen, so a message can be read without leaving the game.
* Works only after the user allows DroidDeck notification access in Android settings.
*/
object BottomNotifications {
val items = mutableStateListOf<BottomNotification>()
@@ -12,12 +12,10 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/** A screenshot for the bottom-screen gallery: one DroidDeck took (a MediaStore [uri]) or one Steam saved (a [file]). */
data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) {
val model: Any get() = uri ?: file!!
}
/** Game frames DroidDeck saves to Pictures/DroidDeck, plus the screenshots Steam keeps under userdata. */
object BottomScreenshots {
private const val FOLDER = "DroidDeck"
private const val QUALITY = 95
@@ -58,7 +56,6 @@ object BottomScreenshots {
}
}.getOrDefault(false)
/** Newest first, at most [LIMIT]. */
fun list(context: Context, runtimeRoot: File): List<BottomShot> =
(own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT)
@@ -85,7 +82,6 @@ object BottomScreenshots {
shots
}.getOrDefault(emptyList())
/** The .jpg files in userdata/<account>/760/remote/<app>/screenshots of each Steam home; the thumbnails folder is skipped. */
internal fun steam(runtimeRoot: File): List<BottomShot> =
SteamDownloadMonitor.STEAM_HOMES.flatMap { home ->
File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account ->
@@ -35,7 +35,6 @@ object ComponentsManager {
"Dxvk-gplasync-Linux" to "dxvk",
"Vkd3d-proton-Linux" to "vkd3d",
)
// DD_NIGHTLY holds every component in one release; the file name says which.
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
@@ -979,12 +978,9 @@ object ComponentsManager {
internal fun assetComp(release: String, name: String): String? =
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
// Per component: the stable packages newest first, then the nightlies.
internal val CATALOG_ORDER: Comparator<CatalogItem> =
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
// A nightly DD-<flavor>-<version>[+N]-nightly.wcp pairs with the newest stable <flavor>-<version>[-<rev>]-linux.wcp
// in the same list, so the stable row can offer it behind a Stable/Nightly switch. Unpaired nightlies keep their own row.
internal fun nightlyPairs(items: List<CatalogItem>): Map<CatalogItem, CatalogItem> {
val stable = items.filter { it.release != DD_NIGHTLY }
return items.filter { it.release == DD_NIGHTLY }.mapNotNull { n ->
@@ -7,11 +7,6 @@ import com.droiddeck.launcher.core.Downloader
import org.json.JSONObject
import java.io.File
/**
* The FEX build DroidDeck-Components' fex.json names for x86 programs. A session uses the last copy read.
* Components' build-fex.yml replaces the archive on its single `fex` release and records the build's version;
* a release per build (fex-2610-r5) is still read.
*/
object FexCatalog {
private const val TAG = "FexCatalog"
const val CATALOG_URL = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/fex.json"
@@ -43,7 +38,6 @@ object FexCatalog {
fun cached(context: Context): Build? = runCatching { parse(file(context).readText()) }.getOrNull()
/** Reads fex.json straight from GitHub (a digest never comes from a mirror), at most every ten minutes. */
@Synchronized
fun refresh(context: Context, now: Long = System.currentTimeMillis()): Build? {
if (now - refreshedAt < REFRESH_MS) return cached(context)
@@ -62,7 +56,6 @@ object FexCatalog {
return build
}
/** For droiddeck-fex-update: the build and every source its archive may come from (it checks the sha256). */
fun environment(build: Build, sources: List<String> = DownloadSource.candidates(build.url)): List<String> = listOf(
"BL_FEX_TAG=${build.tag}",
"BL_FEX_SHA256=${build.sha256}",
@@ -17,7 +17,6 @@ object GameStorage {
val primary = context.getExternalFilesDir(null)?.absolutePath
val primaryStorage = Environment.getExternalStorageDirectory()?.absolutePath
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
// Non-primary app dirs are usable even when Android reports the volume as non-removable (USB SSDs often do).
if (primary != null && dir.absolutePath == primary) return@mapNotNull null
if (!primaryStorage.isNullOrBlank() && dir.absolutePath.startsWith("$primaryStorage/")) return@mapNotNull null
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
@@ -63,12 +62,14 @@ object GameStorage {
fun gamesFolderLibraries(context: Context): List<Library> {
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
val card = effective(context)?.let { canonical(File(it.path)) }
val added = SteamLibraries.list(context).map { canonical(it.host) }
val sm = context.getSystemService(StorageManager::class.java)
return AddedGames.roots(context).mapNotNull { root ->
val host = canonical(root.host)
if (!hasInstalledGames(root.host)) return@mapNotNull null
if ('"' in root.guest || '\\' in root.guest || !root.host.isDirectory || !root.host.canWrite()) return@mapNotNull null
if (card != null && (host == card || host.startsWith("$card/") || card.startsWith("$host/"))) return@mapNotNull null
if (added.any { SteamLibraries.overlaps(it, host) }) return@mapNotNull null
val volume = try { sm?.getStorageVolume(root.host)?.getDescription(context) } catch (e: Exception) { null }
val name = root.host.name.ifEmpty { context.getString(R.string.gstore_folder) }
val label = if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume)
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** One reading from a racing game's telemetry. Fractions are 0..1; null means the game does not send it. */
data class Telemetry(
val source: String,
val speedKmh: Float? = null,
@@ -19,33 +18,22 @@ data class Telemetry(
val currentLapS: Float? = null,
val lastLapS: Float? = null,
val bestLapS: Float? = null,
/** G-force as the game sends it (lateral, longitudinal) and steering from -1 (left) to 1 (right). */
val gLat: Float? = null,
val gLon: Float? = null,
val steer: Float? = null,
/** Front left, front right, rear left, rear right. */
val tireTempsC: List<Float>? = null,
val turboBar: Float? = null,
val engineTempC: Float? = null,
val oilTempC: Float? = null,
/** OutGauge dashboard lights that are on, as GameTelemetry.DL_* bits. */
val lights: Int? = null,
)
/**
* Racing telemetry games send over UDP to 127.0.0.1. Each format has its own port, the one the game or
* its common tools use by default:
* - [CODEMASTERS_PORT]: DiRT Rally 1/2, DiRT 4, GRID ("extradata 3" float array), DiRT Showdown (152-byte packet).
* - [FORZA_PORT]: Forza Motorsport 7/2023 and Forza Horizon 4/5 "Data Out" (Sled and Dash).
* - [OUTGAUGE_PORT]: BeamNG.drive and Live for Speed OutGauge.
*/
object GameTelemetry {
const val CODEMASTERS_PORT = 20777
const val FORZA_PORT = 5300
const val OUTGAUGE_PORT = 4444
val PORTS = listOf(CODEMASTERS_PORT, FORZA_PORT, OUTGAUGE_PORT)
// Games send to 127.0.0.1; on Android InetAddress.getLoopbackAddress() is ::1, which IPv4 packets never reach.
val LISTEN_ADDRESS: java.net.InetAddress = java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))
fun parse(port: Int, data: ByteArray, length: Int): Telemetry? = runCatching {
@@ -61,15 +49,12 @@ object GameTelemetry {
private const val MPS_TO_KMH = 3.6f
private const val GRAVITY = 9.81f
// OutGauge DashLights / ShowLights bits (Live for Speed InSim; BeamNG uses the same values).
const val DL_SHIFT = 1
const val DL_HANDBRAKE = 4
const val DL_PITSPEED = 8
const val DL_TC = 16
const val DL_ABS = 1024
// Float indexes of the Codemasters packet; engine rpm values are sent divided by 10. Older games
// (DiRT Showdown) send only the first 38 floats, so lap count, position, fuel and max rpm are missing there.
private const val CM_LAP_TIME = 1
private const val CM_SPEED = 7
private const val CM_THROTTLE = 29
@@ -99,7 +84,6 @@ object GameTelemetry {
speedKmh = f(CM_SPEED) * MPS_TO_KMH,
rpm = f(CM_RPM) * 10f,
maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f },
// Neutral is 0; DiRT Rally 2.0 reports reverse as 10, older games as -1.
gear = when {
gear == 0 -> "N"
gear < 0 || gear == 10 -> "R"
@@ -119,8 +103,6 @@ object GameTelemetry {
)
}
// Forza "Data Out": Sled is 232 bytes; the Dash block follows it (FM7 311, FM 2023 331). Horizon 4/5 send
// 324 bytes with 12 extra bytes before the Dash block.
private const val FORZA_SLED = 232
private const val FORZA_FM7 = 311
private const val FORZA_HORIZON = 324
@@ -140,7 +122,6 @@ object GameTelemetry {
if (dash < 0) return Telemetry(source = "Forza", rpm = rpm, maxRpm = maxRpm.takeIf { it > 0f })
if (!racing) return Telemetry(source = "Forza")
val gear = buf.get(dash + 75).toInt() and 0xFF
// Tire temperatures are read as Fahrenheit, as community Data Out parsers do; not checked on a device.
val tiresF = (0 until 4).map { buf.getFloat(dash + 24 + it * 4) }
return Telemetry(
source = "Forza",
@@ -163,7 +144,6 @@ object GameTelemetry {
)
}
// OutGauge: 92 bytes, or 96 with the optional id at the end.
private const val OUTGAUGE_SIZE = 92
internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? {
@@ -189,14 +169,12 @@ object GameTelemetry {
}
}
/** Games that publish their state locally without any setup: War Thunder's web page and Elite Dangerous' Status.json. */
object GameStatusFiles {
const val WAR_THUNDER_STATE = "http://127.0.0.1:8111/state"
private const val ELITE_APP = "359320"
private const val ELITE_STATUS = "pfx/drive_c/users/steamuser/Saved Games/Frontier Developments/Elite Dangerous/Status.json"
const val WAR_THUNDER_ROWS = 12
/** War Thunder's own labels (for example "TAS, km/h") with their values, while a match runs. */
internal fun warThunder(json: String): List<Pair<String, String>> {
val state = org.json.JSONObject(json)
if (!state.optBoolean("valid", false)) return emptyList()
@@ -214,7 +192,6 @@ object GameStatusFiles {
data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List<Int>?, val legal: String?, val balance: Long?)
/** Null while Elite is at its menus (Status.json then carries only the timestamp and flags). */
internal fun elite(json: String): Elite? {
val s = org.json.JSONObject(json)
val fuel = s.optJSONObject("Fuel")
@@ -12,54 +12,26 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import kotlin.math.abs
/**
* The game's busiest threads named to Android's performance hint service (ADPF) for a session.
*
* Qualcomm's WALT moves a thread to the prime cores only once it fills a mid core (the Odin 3's
* sched_upmigrate is 95), and a game thread that waits on its workers or the GPU for part of each
* frame never does: Factorio's update thread sat at ~68% on cores 0-5 with 6-7 idle, and ran 60%
* faster pinned to 6-7. An app may not raise a thread's uclamp (EPERM without CAP_SYS_NICE), but a
* hint session may name any thread of its UID - the guest's are - and one reported behind its
* target is boosted by the power HAL onto the prime cores: on the Odin 3 a 70%-busy thread of a
* child process went from cores 0-5 to 6-7 and ran 1.7x faster within a second.
*
* Once a second the busiest threads of this UID are read from /proc; one busy more than [ENTER] of
* the time (averaged with the second before, so a loading spike does not count) joins the session,
* and leaves it under [LEAVE] - well below, since it runs faster where it was moved. While the
* session has threads it reports them behind target, which is what asks for the boost: the reports
* carry no frame timing, the busy share is the signal (a capped game's frame interval looks the same
* as a slow one's). Nothing is boosted while the device is critically hot or saves power.
*
* Nor while the game holds the panel's rate or a fraction of it ([holdsPace]): there is nothing to
* gain, and it cost frame pacing - Serious Sam capped at 120 fps ran its boosted main thread on prime
* cores the governor kept at 2.2 GHz, slower than a 3.5 GHz mid core, and 23-25% of its frames fell
* under 90 fps against 2-7% unboosted. A game with no frames (Factorio's benchmark, a loading screen)
* or one falling behind the panel is boosted; one holding pace keeps what it has for [PACE_LEAVE_S]
* seconds and is then let go.
*/
object GameThreadHints {
private const val TAG = "GameThreadHints"
private const val TARGET_NS = 10_000_000L
private const val REPORT_MS = 50L
private const val SCAN_EVERY = 20 // reports, so once a second
private const val SCAN_EVERY = 20
private const val ENTER = 0.6
private const val LEAVE = 0.15 // a capped game's main thread idles to ~30% on a prime core; under 0.3 it hopped back and forth
private const val MAX_THREADS = 2 // one per prime core; a third would be sped up in place instead
private const val LEAVE = 0.15
private const val MAX_THREADS = 2
private const val TOP_PROCESSES = 3
private const val PACE_WINDOW_S = 3
private const val PACE_LEAVE_S = 10
private const val PACE_TOLERANCE = 0.08
/** Busy, but not the game: the app itself and the Steam client, whose UI would otherwise hold the prime cores. */
private val NOT_GAMES = setOf("steam", "steamwebhelper")
private var worker: Thread? = null
/** At a session's start. The line is for the log. */
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
// Measured on the Odin 3 (CQ8725S) only; another HAL may boost differently, or not at all.
if (Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S") return "game thread hints: Odin 3 only"
val hm = context.getSystemService(PerformanceHintManager::class.java)
?: return "game thread hints: no PerformanceHintManager"
@@ -69,7 +41,6 @@ object GameThreadHints {
return "game thread hints: watching"
}
/** At a session's end. */
@Synchronized
fun stop() {
worker?.interrupt()
@@ -92,7 +63,6 @@ object GameThreadHints {
val fps = (frames.last() - frames.first()).toDouble() / (frames.size - 1).coerceAtLeast(1)
val paced = frames.size > PACE_WINDOW_S && holdsPace(fps, SessionState.refreshHz.toDouble())
pacedFor = if (paced) pacedFor + 1 else 0
// Not SEVERE: the Odin 3 reports it once its skin reaches 50 C, a couple of minutes into any game.
val spare = pm.isPowerSaveMode || pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_CRITICAL
val next = when {
spare || pacedFor >= PACE_LEAVE_S -> emptySet()
@@ -101,7 +71,6 @@ object GameThreadHints {
}
if (next != boosted) {
session = update(hm, session, next)
// No session means a thread exited in between: tried again next second.
boosted = if (session == null) emptySet() else next
Log.i(TAG, (if (session == null && next.isNotEmpty()) "no session for " else "boosting ") +
next.joinToString { "${readName("/proc/$it/comm")}/$it ${((busy[it] ?: 0.0) * 100).toInt()}%" }.ifEmpty { "nothing" } +
@@ -119,7 +88,6 @@ object GameThreadHints {
}
}
/** A new session over [tids] in place of [session]; null for none. The set changes seldom, so no setThreads. */
private fun update(hm: PerformanceHintManager, session: PerformanceHintManager.Session?, tids: Set<Int>): PerformanceHintManager.Session? {
session?.close()
if (tids.isEmpty()) return null
@@ -131,19 +99,9 @@ object GameThreadHints {
}
}
/**
* Whether a game presenting [fps] frames a second keeps up with a [refreshHz] panel: within
* [PACE_TOLERANCE] of the rate or of a half, a third or a quarter of it (a 60 fps limiter on 120 Hz).
* A game with next to no frames (a headless benchmark, a loading screen) does not.
*/
// ponytail: a CPU-bound game that happens to run at ~60 fps on a 120 Hz panel reads as limited; narrow the band if that shows up
internal fun holdsPace(fps: Double, refreshHz: Double): Boolean =
fps >= 10 && refreshHz > 0 && (1..4).any { k -> abs(fps - refreshHz / k) < PACE_TOLERANCE * refreshHz / k }
/**
* The threads to boost next: those already boosted that are still above [LEAVE], then new ones
* above [ENTER], busiest first, at most [MAX_THREADS].
*/
internal fun pick(boosted: Set<Int>, busy: Map<Int, Double>): Set<Int> =
busy.entries
.filter { (tid, share) -> share >= if (tid in boosted) LEAVE else ENTER }
@@ -154,7 +112,6 @@ object GameThreadHints {
private fun readName(path: String) = try { File(path).readText().trim() } catch (_: Exception) { "?" }
/** Busy shares of this UID's threads since the last sample: /proc shows an app only its own processes. */
private class Scanner {
private val self = Process.myPid()
private val hz = Os.sysconf(OsConstants._SC_CLK_TCK).toDouble()
@@ -163,7 +120,6 @@ object GameThreadHints {
private var lastThread = HashMap<Int, Long>()
private var lastBusy = HashMap<Int, Double>()
/** Only the busiest few processes have their threads read, so a second costs a few dozen small reads. */
fun sample(): Map<Int, Double> {
val now = System.nanoTime()
val seconds = (now - lastNs) / 1e9
@@ -197,7 +153,6 @@ object GameThreadHints {
return busy
}
/** utime + stime of a /proc stat line; fields counted after the command's closing parenthesis. */
private fun cpuTicks(path: String): Long? = try {
val line = File(path).readText()
val fields = line.substring(line.lastIndexOf(')') + 2).split(' ')
@@ -21,7 +21,8 @@ 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) || com.droiddeck.launcher.hud.DroidDeckHudHost.showing)) sample()?.let { write(it) }
if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.DroidDeckHudHost.showing ||
com.droiddeck.launcher.hud.BottomHudPresence.showing)) sample()?.let { write(it) }
}
}, "gpu-mem").apply { isDaemon = true; start() }
}
@@ -7,10 +7,16 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
class GpuStatsComponent(val dir: File) : SessionPart() {
class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val feeds = ArrayList<Feed>()
private var layerLoad: LayerLoad? = null
private var memstore: KgslBusy.Reader? = null
private var memstoreLoad: MemstoreLoad? = null
private var memstoreState: String? = null
private var cycleClock: KgslClock.Sampler? = null
@Volatile private var shown = false
private class Feed(
val file: File, val source: String, val read: () -> Long?, val format: String, val percent: Boolean = false,
@@ -24,9 +30,11 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
}
fun prepare(): Boolean {
sources = ""
if (!File(KGSL).exists()) return false
val unreadable = MANGOHUD_FILES.any { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }
if (!unreadable && !File(GPUBUSY).canRead()) return false
// Where SELinux hides the kgsl nodes completely (exists() is false too), the layer and cycle-counter feeds stand in.
if (!unreadable && !File(GPUBUSY).canRead() && !loadBlocked()) return false
return try {
dir.mkdirs()
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
@@ -34,19 +42,18 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
PASSTHROUGH_FILES.forEach { name ->
runCatching { File(dir, name).writeText(File(KGSL, name).readText()) }
}
loadFeed()?.let { load ->
(loadFeed() ?: blockedLoadFeed())?.let { load ->
feeds.add(load)
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
}
pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { clock ->
(pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) } ?: cycleClockFeed())?.let { clock ->
feeds.add(clock)
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
}
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
refresh()
Log.i(TAG, "hud: kgsl stats from the session's own: " + MANGOHUD_FILES.joinToString { name ->
"$name " + (feeds.firstOrNull { it.file.name == name }?.source ?: "none")
})
describeSources()
Log.i(TAG, "hud: kgsl stats from the session's own: $sources")
true
} catch (e: Exception) {
Log.w(TAG, "hud: could not stand in for kgsl stats: $e")
@@ -66,19 +73,214 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
}, "gpu-stats").apply { isDaemon = true; start() }
}
// kgsl's gpubusy can read 0 0 straight after a read, so feeds that share a reader share one read.
private fun refresh() {
if (layerLoad != null || cycleClock != null || memstore != null) {
shown = hudShown()
memstore?.run(shown)
if (!shown) memstoreLoad?.pause()
layerLoad?.wanted(shown && memstoreLoad?.working != true)
}
val values = HashMap<() -> Long?, Long?>()
for (feed in feeds) {
if (feed.read !in values) values[feed.read] = feed.read()
values[feed.read]?.let { write(feed, it) }
}
memstoreLoad?.let { load ->
val state = when {
load.working -> "working"
load.failed -> "failed"
else -> null
}
if (state != memstoreState) {
memstoreState = state
if (load.failed) {
memstore?.close()
memstore = null
Log.i(TAG, "hud: kgsl memstore timestamps never moved; GPU load from Vulkan timing")
} else if (load.working) {
Log.i(TAG, "hud: GPU load from the kgsl memstore (all GPU work)")
}
describeSources()
}
}
}
private fun describeSources() {
sources = MANGOHUD_FILES.joinToString { name ->
val source = if (name == "gpu_busy_percentage" && memstoreLoad != null) memstoreSource()
else feeds.firstOrNull { it.file.name == name }?.source
"$name " + (source ?: "none")
}
}
private fun memstoreSource(): String = when {
memstoreLoad?.working == true -> "kgsl memstore ringbuffer timestamps (all GPU work)"
memstoreLoad?.failed == true -> LAYER_SOURCE
else -> "kgsl memstore once its timestamps move; until then $LAYER_SOURCE"
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
memstore?.close()
memstore = null
memstoreLoad = null
memstoreState = null
layerLoad?.clear()
cycleClock?.close()
cycleClock = null
sources = ""
}
private fun hudShown(): Boolean = OverlayShown.check(root) || com.droiddeck.launcher.hud.DroidDeckHudHost.showing ||
com.droiddeck.launcher.hud.BottomHudPresence.showing
// Android hides the load (kgsl sysfs blocked): the kgsl memstore gives the whole GPU's busy share. The in-game
// Vulkan layer and the compositor time their own GPU work until the memstore timestamps are seen moving, and
// for the whole session where they never move.
private fun blockedLoadFeed(): Feed? {
if (!loadBlocked()) return null
val load = LayerLoad(guestLoadDir(root), extra = ::compositorBusyNs, onWanted = ::compositorTiming)
.also { it.clear(); layerLoad = it }
val sampled = KgslBusy.open()?.let { reader ->
memstore = reader
MemstoreLoad(reader::counts).also { memstoreLoad = it }
}
val read = read@{
if (!shown) return@read null
val whole = sampled?.percent()
if (sampled?.working == true) whole else load.percent()
}
return Feed(File(dir, "gpu_busy_percentage"), LAYER_SOURCE, read, "%3d %%\n")
}
// The clock nodes are blocked too: read the GPU's cycle counter from a small GPU job of our own.
private fun cycleClockFeed(): Feed? {
val sampler = KgslClock.open() ?: return null
cycleClock = sampler
// clock_mhz and cur_freq both read this; one GPU job per refresh serves both.
var at = 0L
var last: Long? = null
val read = {
val now = SystemClock.elapsedRealtime()
if (now - at > PERIOD_MS / 2) { at = now; last = if (shown) sampler.mhz()?.toLong() else null }
last
}
return Feed(File(dir, "clock_mhz"), "GPU cycle counter (own GPU job)", read, "%5d\n")
}
private fun compositorBusyNs(): Long? =
runCatching { com.droiddeck.launcher.wayland.WaylandCompositor.nativeGpuBusyNs() }.getOrNull()?.takeIf { it >= 0 }
private fun compositorTiming(on: Boolean) {
runCatching { com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetGpuTiming(on) }
}
/**
* Busy time the layer (tools/gpuload) writes per process, plus [extra] (the compositor's own GPU time), as a share
* of wall time between two reads.
*/
internal class LayerLoad(
private val dir: File,
private val clock: () -> Long = System::nanoTime,
private val extra: () -> Long? = { null },
private val onWanted: (Boolean) -> Unit = {},
) {
private val last = HashMap<String, Long>()
private var lastAt = 0L
private var on = false
fun wanted(on: Boolean) {
val flag = File(dir, "on")
if (on && !flag.exists()) runCatching { dir.mkdirs(); flag.createNewFile() }
if (!on && flag.exists()) { flag.delete(); last.clear(); lastAt = 0L }
if (on != this.on) onWanted(on)
this.on = on
}
fun percent(): Long? {
val now = clock()
val files = dir.listFiles { f -> f.name.isNotEmpty() && f.name.all(Char::isDigit) }.orEmpty()
var busy = 0L
val seen = HashSet<String>()
for (file in files) {
val total = runCatching { file.readText().trim().substringBefore(' ').toLong() }.getOrNull() ?: continue
seen += file.name
last[file.name]?.let { if (total >= it) busy += total - it }
last[file.name] = total
if (System.currentTimeMillis() - file.lastModified() > STALE_MS) file.delete()
}
extra()?.let { total ->
seen += EXTRA
last[EXTRA]?.let { if (total >= it) busy += total - it }
last[EXTRA] = total
}
last.keys.retainAll(seen)
val wall = now - lastAt
val first = lastAt == 0L
lastAt = now
if (first || wall <= 0) return null
return (busy * 100 / wall).coerceIn(0, 100)
}
fun clear() {
dir.listFiles()?.forEach { it.delete() }
last.clear()
lastAt = 0L
if (on) onWanted(false)
on = false
}
private companion object {
const val EXTRA = "compositor"
}
}
/**
* Busy share over the last [WINDOW] reads from [KgslBusy] running totals (busy samples, samples, samples with
* new ringbuffer work). Not [working] until new work has been seen; [failed] once [GIVE_UP_SAMPLES] samples
* passed without any.
*/
internal class MemstoreLoad(private val counts: () -> LongArray?) {
var working = false
private set
var failed = false
private set
private val window = ArrayDeque<LongArray>()
private var waited = 0L
fun percent(): Long? {
if (failed) return null
val now = counts() ?: return null
val previous = window.lastOrNull()
window.addLast(now)
while (window.size > WINDOW + 1) window.removeFirst()
if (previous == null) return null
val fresh = now[1] - previous[1]
if (fresh <= 0) return null
if (!working) {
if (now[2] > previous[2]) {
working = true
} else {
waited += fresh
if (waited >= GIVE_UP_SAMPLES) failed = true
return null
}
}
val base = window.first()
return ((now[0] - base[0]) * 100 / (now[1] - base[1])).coerceIn(0, 100)
}
/** The totals stop while sampling is off; the next reading starts a new window. */
fun pause() {
window.clear()
}
companion object {
const val GIVE_UP_SAMPLES = 5_000L
const val WINDOW = 2
}
}
private fun loadFeed(): Feed? {
@@ -86,8 +288,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
return pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }
}
// kgsl publishes busy/total once per ~1 s of GPU-on time and zeroes it on any read while the GPU is
// power-collapsed, so direct pollers mostly see 0; latch each published window instead.
private fun latchedBusyFeed(): Feed? {
var load = 0L
var windowAt = 0L
@@ -134,6 +334,24 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
private const val LOAD_HOLD_MS = 5_000L
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
private val PASSTHROUGH_FILES = listOf("gpu_model", "gpu_chipid")
const val GUEST_LOAD_DIR = "/run/droiddeck-hud/gpu-load"
private const val LAYER_SOURCE = "Vulkan timing: games ($GUEST_LOAD_DIR) + DroidDeck compositor"
/** Where the running session's GPU feeds come from, for the HUD diagnostics export. */
@Volatile var sources = ""
private const val STALE_MS = 30_000L
fun guestLoadDir(root: File) = File(root, GUEST_LOAD_DIR.removePrefix("/"))
/** True when this app can see kgsl but none of its GPU load nodes (SELinux-blocked, e.g. the Retroid Pocket Duo). */
fun loadBlocked(): Boolean = File(KGSL).exists() && !File(GPUBUSY).canRead() && LOAD_SOURCES.none { File(it).canRead() }
/** Turns on the in-game layer (tools/gpuload) where the load is blocked; empty elsewhere. */
fun guestEnv(root: File): List<String> {
if (!loadBlocked()) return emptyList()
guestLoadDir(root).mkdirs()
return listOf("DROIDDECK_GPU_LOAD=1", "DROIDDECK_GPU_LOAD_DIR=$GUEST_LOAD_DIR")
}
private const val QCOM_GPU = "/sys/kernel/gpu"
private val LOAD_SOURCES = listOf(
"$KGSL/gpu_busy_percentage", "$KGSL/devfreq/gpu_load", "$KGSL/gpuload", "$QCOM_GPU/gpu_busy",
@@ -108,5 +108,9 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
private fun readNumber(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()?.takeIf { it >= 0 }
fun fanSource(): String? = FAN_SOURCES().firstOrNull { readNumber(it) != null }
fun readRpm(path: String): Long? = readNumber(path)
}
}
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.session
import android.util.Log
/**
* Whole-GPU busy share for Adreno devices whose kgsl load nodes are SELinux-blocked for apps
* (app/src/main/cpp/gpuclock/kgsl_busy.c). It covers every process's GPU work, Android's own composition included.
*/
object KgslBusy {
private const val TAG = "SessionService"
@JvmStatic private external fun nativeOpen(error: IntArray): Long
@JvmStatic private external fun nativeRun(handle: Long, on: Boolean)
@JvmStatic private external fun nativeRead(handle: Long, out: LongArray): Boolean
@JvmStatic private external fun nativeClose(handle: Long)
private val loaded: Boolean by lazy {
runCatching { System.loadLibrary("gpuclock") }.onFailure { Log.w(TAG, "hud: gpuclock library: $it") }.isSuccess
}
class Reader internal constructor(private var handle: Long) : AutoCloseable {
/** Samples once a millisecond while on. */
@Synchronized fun run(on: Boolean) {
if (handle != 0L) nativeRun(handle, on)
}
/** Running totals: busy samples, samples, samples in which a ringbuffer started new work. */
@Synchronized fun counts(): LongArray? {
if (handle == 0L) return null
val out = LongArray(3)
return if (nativeRead(handle, out)) out else null
}
@Synchronized override fun close() {
if (handle != 0L) nativeClose(handle)
handle = 0L
}
}
fun open(): Reader? {
if (!loaded) return null
val error = IntArray(1)
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
if (handle == 0L) {
Log.i(TAG, "hud: no GPU load from the kgsl memstore (open error ${error[0]})")
return null
}
return Reader(handle)
}
}
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.session
import android.util.Log
/**
* GPU clock from the GPU's own cycle counter, for Adreno devices whose kgsl clock nodes are SELinux-blocked for
* apps (app/src/main/cpp/gpuclock/kgsl_clock.c). Each [mhz] call runs one tiny GPU job, so callers sample only
* while a HUD is shown.
*/
object KgslClock {
private const val TAG = "SessionService"
@JvmStatic private external fun nativeOpen(error: IntArray): Long
@JvmStatic private external fun nativeSample(handle: Long): Int
@JvmStatic private external fun nativeClose(handle: Long)
private val loaded: Boolean by lazy {
runCatching { System.loadLibrary("gpuclock") }.onFailure { Log.w(TAG, "hud: gpuclock library: $it") }.isSuccess
}
class Sampler internal constructor(private var handle: Long) : AutoCloseable {
/** MHz, or null when this sample was refused or failed its checks. */
@Synchronized fun mhz(): Int? = if (handle == 0L) null else nativeSample(handle).takeIf { it > 0 }
@Synchronized override fun close() {
if (handle != 0L) nativeClose(handle)
handle = 0L
}
}
/** A sampler that already produced one good reading, or null (the reason goes to the log). */
fun open(): Sampler? {
if (!loaded) return null
val error = IntArray(1)
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
if (handle == 0L) {
Log.i(TAG, "hud: no GPU clock from the cycle counter (open error ${error[0]})")
return null
}
val sampler = Sampler(handle)
val first = (0 until 3).firstNotNullOfOrNull { sampler.mhz() }
if (first == null) {
Log.i(TAG, "hud: GPU cycle counter gave no usable reading")
sampler.close()
return null
}
Log.i(TAG, "hud: GPU clock from the cycle counter ($first MHz now)")
return sampler
}
}
@@ -21,7 +21,6 @@ object OfflineMode {
fun account(context: Context): String? {
val root = LinuxRuntime.rootDir(context)
// Until its first start the x86-64 client has no sign-in; droiddeck-steam-x64 --sync-login copies the arm64 one.
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
?: loginUsers(root)
val text = try {
@@ -11,7 +11,7 @@ object OrphanReaper {
fun release(pid: Int) { kept.remove(pid) }
fun reap(reason: String): Int {
fun reap(reason: String, matching: (String) -> Boolean = { true }): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
val spared = descendants(kept)
@@ -21,6 +21,7 @@ object OrphanReaper {
if (pid == me || pid <= 1 || pid in spared) return@forEach
if (uidOf(pid) != uid) return@forEach
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" }
if (!matching(name)) return@forEach
try {
android.os.Process.killProcess(pid)
killed++
@@ -214,8 +214,6 @@ class RumbleComponent : SessionPart() {
if (any) manager.vibrate(combined.combine()) else cancel()
}
// Some vendors' input-device vibrator HALs (Samsung's) don't halt a Bluetooth pad's running
// effect on cancel(), but a new effect always replaces it.
override fun cancel() {
val supersede = CombinedVibration.startParallel()
ids.forEach { supersede.addVibrator(it, VibrationEffect.createOneShot(1L, 1)) }
@@ -255,7 +253,6 @@ class RumbleComponent : SessionPart() {
private const val TAG = "SessionService"
const val NAME = "droiddeck-rumble"
const val MIN_GAP_MS = 50L
// Must match RUMBLE_HOLD_MS in fakeinput_steam.cpp.
const val HOLD_MS = 0xFFFF
const val HOLD_EFFECT_MS = 2000L
const val KEEPALIVE_MS = 1500L
@@ -31,7 +31,6 @@ object SessionArtifacts {
private val collectingDone = collectingLock.newCondition()
private val collecting = HashSet<File>()
/** Recovery leaves [dir] alone from the stop until [collect] has finished it. */
fun collectionStarted(dir: File) {
collectingLock.lock()
try { collecting.add(dir) } finally { collectingLock.unlock() }
@@ -317,7 +316,6 @@ object SessionArtifacts {
runCatching { File(dir, CLIENT_FILE).writeText("$arch\n") }
}
/** The Steam client a session ran, when it recorded one. */
internal fun recordedClient(dir: File): String? =
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
@@ -7,6 +7,10 @@ object SessionDisplay {
const val MATCH_SCREEN = "screen"
const val FOLLOW_SCREEN = "follow"
const val FOLLOW_MIN_SIDE = 480
val FOLLOW_SCALES = listOf(1.5f, 2f, 2.5f, 3f, 4f)
const val FOLLOW_CUSTOM = "follow/custom"
const val FOLLOW_SCALE_MAX = 8f
private const val FOLLOW_SCALED_PREFIX = "follow/"
const val DEFAULT_RESOLUTION = "720p"
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
@@ -14,12 +18,30 @@ object SessionDisplay {
fun presetHeight(choice: String): Int? =
if (choice.endsWith("p")) choice.dropLast(1).toIntOrNull()?.takeIf { it > 0 } else null
fun followScaled(scale: Float): String = FOLLOW_SCALED_PREFIX + formatScale(scale)
fun formatScale(scale: Float): String =
(Math.round(scale * 10) / 10f).let { if (it % 1f == 0f) it.toInt().toString() else it.toString() }
fun parseFollowScale(text: String): Float? =
text.trim().replace(',', '.').toFloatOrNull()
?.let { Math.round(it * 10) / 10f }?.takeIf { it > 1f && it <= FOLLOW_SCALE_MAX }
fun isFollow(choice: String): Boolean = followScale(choice) != null
fun followScale(choice: String): Float? = when {
choice == FOLLOW_SCREEN -> 1f
choice.startsWith(FOLLOW_SCALED_PREFIX) -> parseFollowScale(choice.removePrefix(FOLLOW_SCALED_PREFIX))
else -> null
}
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
fun resolveChoice(panel: Pair<Int, Int>, choice: String, portrait: Boolean = false): Pair<Int, Int> {
fun orient(size: Pair<Int, Int>) = if (portrait) size.second to size.first else size
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return orient(screenSize(panel))
if (choice == MATCH_SCREEN) return orient(screenSize(panel))
followScale(choice)?.let { return orient(scaledDown(screenSize(panel), it)) }
presetHeight(choice)?.let { return orient(resolve(panel, it, SessionPrefs.SHAPE_AUTO)) }
val parts = choice.split('x').map { it.toIntOrNull() }
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
@@ -29,13 +51,16 @@ object SessionDisplay {
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
val panelHeight = minOf(panel.first, panel.second)
return PRESET_HEIGHTS.filter { it <= panelHeight }.map { "${it}p" }
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN + FOLLOW_SCALES.map(::followScaled)
}
fun followSize(width: Int, height: Int, controlsBelow: Boolean = false): Pair<Int, Int>? =
fun followSize(width: Int, height: Int, controlsBelow: Boolean = false, scale: Float = 1f): Pair<Int, Int>? =
if (width <= 0 || height <= 0 ||
(if (controlsBelow) width else minOf(width, height)) < FOLLOW_MIN_SIDE) null
else (width and 1.inv()) to (height and 1.inv())
else scaledDown(width to height, scale)
private fun scaledDown(size: Pair<Int, Int>, scale: Float): Pair<Int, Int> =
(Math.round(size.first / scale) and 1.inv()) to (Math.round(size.second / scale) and 1.inv())
const val UNFOLDED_MAX_GAME_SHARE = 0.8f
@@ -22,6 +22,7 @@ object SessionFiles {
internal val DESKTOP_FILES = arrayOf(
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
"usr/local/bin/droiddeck-bottom-desktop" to "usr/local/bin/droiddeck-bottom-desktop",
"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",
@@ -32,7 +33,6 @@ object SessionFiles {
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
)
/** 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) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
@@ -160,12 +160,16 @@ object SessionFiles {
) + handModels).map { "usr/local/lib/droiddeck-vr/$it" to "usr/local/lib/droiddeck-vr/$it" } +
listOf("usr/local/lib/droiddeck-vr/layer/VK_LAYER_DROIDDECK_vr_implicit.json" to
"usr/share/vulkan/implicit_layer.d/droiddeck_vr.json")
// HUD GPU load where Android hides it (GpuStatsComponent.guestEnv turns the layer on).
val gpuLoad = listOf(
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
)
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
// The gamescope pack carries its own WSI layer (patch 0117); it replaces the runtime's stock copy.
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
@@ -174,7 +178,7 @@ object SessionFiles {
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
) + mangoapp + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
) + mangoapp + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
}
@@ -279,7 +283,6 @@ object SessionFiles {
val movieDir = File(home, "config/uioverrides/movies")
val config = File(home, "config/config.vdf")
if (startupMovie == null) {
// Nothing to play (a movie whose volume could not be set is never played at another volume), so no earlier copy plays either.
for (name in listOf("bigpicture_startup.webm", "steam_os_startup.webm")) {
File(movieDir, name).delete()
File(movieDir, ".$name.source").delete()
@@ -299,17 +302,10 @@ object SessionFiles {
if (!bigPictureMovieInstalled) allInstalled = false
if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else ""
}
// A pick made in the app is done once a session started with every Steam client's config having it; guest commands run
// before that, and a Steam that is already running writes its own choice back when it exits.
if (force && allDone && allInstalled && startsSession) SessionPrefs.setBootMovieApplyNext(context, false)
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
/**
* Points Steam's startup movie back at its own default when it names a movie that is gone: DroidDeck's staged copy that
* could not be prepared, or (when a pick here is waiting) a movie removed from Steam's folder. True when Steam's config
* no longer names a missing movie.
*/
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
if (!config.isFile) return true
val text = runCatching { config.readText() }.getOrElse {
@@ -388,7 +384,6 @@ object SessionFiles {
installed = staged.setReadable(true, false) && staged.renameTo(movie)
if (installed) {
FileUtils.writeString(stamp, identity)
// Steam's picker draws its preview from this picture and does not redraw it when the movie changes.
File(directory, name.removeSuffix(".webm") + ".jpg").delete()
}
} catch (e: Exception) {
@@ -405,10 +400,6 @@ object SessionFiles {
internal const val BOOT_MOVIES_DIR = "/uioverrides/movies/"
internal const val BOOT_MOVIE_PATH = "/uioverrides/movies/bigpicture_startup.webm"
/**
* Steam's startup movie setting is the `StartupMovie` section inside its `Customization` section; the one under the Steam
* settings is where older clients kept it, and DroidDeck still keeps it in step.
*/
private fun customizationMovie(text: String): VdfBlock? {
var from = 0
while (true) {
@@ -418,7 +409,6 @@ object SessionFiles {
}
}
/** The older `StartupMovie` section: the first one that is not inside `Customization`. */
private fun olderMovie(text: String): VdfBlock? {
val inside = customizationMovie(text)
var from = 0
@@ -429,10 +419,8 @@ object SessionFiles {
}
}
/** The section Steam reads: the one under `Customization` when there is one. */
private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text)
/** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */
internal fun startupMoviePath(config: File): String? = startupMovieLocalPath(config)?.takeIf { it.isNotEmpty() }
internal fun startupMovieLocalPath(config: File): String? {
@@ -441,7 +429,6 @@ object SessionFiles {
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")
}
/** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */
internal fun startupMovieBlock(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val parts = listOfNotNull(
@@ -451,7 +438,6 @@ object SessionFiles {
return parts.takeIf { it.isNotEmpty() }?.joinToString("\n")
}
/** The `Customization` section of Steam's config with the lines before it, for the report; null when there is none. */
internal fun customizationBlock(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val customization = findObject(text, "Customization", 0, text.length) ?: return null
@@ -464,7 +450,6 @@ object SessionFiles {
return text.replaceRange(movie.keyStart, movie.close + 1, setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", path, newline))
}
/** True when Steam's config selects DroidDeck's staged movie once this returns. */
internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean {
val path = BOOT_MOVIE_PATH
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
@@ -491,7 +476,6 @@ object SessionFiles {
return false
}
}
// Later sections first, so the positions of earlier ones stay valid.
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
for (target in targets) text = pointAt(text, target, path, newline)
if (olderMovie(text) == null) {
@@ -535,11 +519,6 @@ object SessionFiles {
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
/**
* Sets Steam's Power > "Sleep after" (battery and plugged in) to Disabled at every session start: Android
* owns the device's sleep, and a client that suspends inside the session only shows a black screen. Dimming stays the user's. Runs
* only before the client starts, which rewrites its config on exit.
*/
internal fun disableIdleSleep(steamHome: File): Boolean {
val config = File(steamHome, "config/config.vdf")
val text = runCatching { config.readText() }.getOrNull() ?: return false
@@ -570,7 +549,6 @@ object SessionFiles {
}
}
/** Adds the `Customization` section Steam reads, next to the `Software` section, when the config has none. */
private fun withCustomization(text: String, path: String, newline: String): String {
val root = findObject(text, "InstallConfigStore", 0, text.length) ?: return text
val lineStart = text.lastIndexOf('\n', root.close).let { if (it < 0) 0 else it + 1 }
@@ -640,13 +618,6 @@ object SessionFiles {
fun logDirectory(context: Context): File = LinuxRuntime.logDir(context).apply { mkdirs() }
/**
* Registers the Android system fonts (which include CJK faces such as Noto Sans CJK /
* MiSans) with the container's fontconfig, so the Steam Deck UI (CEF/webkit renderer)
* resolves Chinese/Japanese glyphs instead of showing tofu / mojibake.
* 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,
@@ -69,7 +69,6 @@ object SessionLogShare {
return zip
}
/** Every entry is scrubbed line by line, whatever its size: a raw copy can carry tokens out of the device. */
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
z.putNextEntry(ZipEntry(name))
val w = z.bufferedWriter()
@@ -44,7 +44,6 @@ 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
@@ -100,12 +100,44 @@ object SessionPrefs {
prefs(context).edit().putString("secondScreenPanel", mode).apply()
}
/** The bottom-screen desktop takes touch as a trackpad unless the user switched it to direct touch. */
fun bottomDesktopDirectTouch(context: Context): Boolean = prefs(context).getBoolean("bottomDesktopDirectTouch", false)
fun setBottomDesktopDirectTouch(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("bottomDesktopDirectTouch", on).apply()
}
fun statsStrip(context: Context): String? = prefs(context).getString("statsStrip", null)
fun setStatsStrip(context: Context, id: String) {
prefs(context).edit().putString("statsStrip", id).apply()
}
fun bottomStripMetrics(context: Context): Set<StripMetric> = StripMetric.parse(prefs(context).getString("bottomStripMetrics", null))
fun setBottomStripMetric(context: Context, metric: StripMetric, on: Boolean) {
val now = bottomStripMetrics(context).let { if (on) it + metric else it - metric }
prefs(context).edit().putString("bottomStripMetrics", StripMetric.encode(now)).apply()
}
fun bottomHud(context: Context): Boolean = prefs(context).getBoolean("bottomHud", true)
fun setBottomHud(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("bottomHud", on).apply()
}
fun bottomStripOnTabs(context: Context): Boolean = prefs(context).getBoolean("bottomStripTabs", true)
fun setBottomStripOnTabs(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("bottomStripTabs", on).apply()
}
fun statsHud(context: Context): String? = prefs(context).getString("statsHud", null)
fun setStatsHud(context: Context, id: String) {
prefs(context).edit().putString("statsHud", id).apply()
}
fun statsSpeedUnit(context: Context): String? = prefs(context).getString("statsSpeedUnit", null)
fun setStatsSpeedUnit(context: Context, id: String) {
@@ -118,14 +150,12 @@ object SessionPrefs {
prefs(context).edit().putString("statsDash", id).apply()
}
/** In-game stats "Send dashboard data" Automatic: on unless the user switched it off. */
fun telemetryAuto(context: Context): Boolean = prefs(context).getBoolean("telemetryAuto", true)
fun setTelemetryAuto(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("telemetryAuto", on).apply()
}
/** Games the user switched off by hand, as TelemetryOutput keys; Automatic leaves them alone. */
fun telemetryOff(context: Context): Set<String> = prefs(context).getStringSet("telemetryOff", null)?.toSet().orEmpty()
fun setTelemetryOff(context: Context, keys: Set<String>) {
@@ -156,13 +186,6 @@ object SessionPrefs {
prefs(context).edit().putString("gameStoresSpeedTier", tier).apply()
}
/**
* Hidden A/B switch for the Epic installer: "adaptive" (default: native parallel fetch written
* straight into staged files), "lookahead" (the native ordered-lookahead engine that caches each
* chunk and copies it into staged files), "batch" (the older whole-cache native fetch, then
* native assembly; needs about twice the game's size free) or "java" (the bounded Java writer).
* No UI; set it in the `session` preferences for benchmarks.
*/
fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive"
fun storesShowMature(context: Context): Boolean = prefs(context).getBoolean("storesShowMature", false)
@@ -239,7 +262,6 @@ object SessionPrefs {
prefs(context).edit().putString("storesInstallTarget", path).apply()
}
/** Empty means follow the app/system language for GOG and Epic installs. */
fun storesInstallLanguage(context: Context): String = prefs(context).getString("storesInstallLanguage", "") ?: ""
fun setStoresInstallLanguage(context: Context, code: String) {
@@ -360,6 +382,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("directCursor", on).apply()
}
fun backHold(context: Context): Boolean = prefs(context).getBoolean("backHold", true)
fun setBackHold(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("backHold", on).apply()
}
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
fun setBackActionsInverted(context: Context, inverted: Boolean) {
@@ -459,10 +487,6 @@ object SessionPrefs {
position.takeIf { it in listOf("top", "bottom", "center") } ?: "center").apply()
}
/**
* After a game launched from the front end (or another launcher's link) closes, the client
* exits cleanly and the session returns there, instead of staying in Big Picture.
*/
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
fun setReturnAfterGame(context: Context, on: Boolean) {
@@ -472,11 +496,6 @@ object SessionPrefs {
private fun shaderPrecacheApplied(context: Context) =
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.bl-shader-precache-applied")
/**
* Shader pre-caching as the launcher last set it, until a session reports it written into the
* client's config.vdf; after that the client's own toggle is the user's again. A client that
* has never written a config.vdf starts with pre-caching off.
*/
fun pendingShaderPrecache(context: Context): Boolean? {
val prefs = prefs(context)
if (!prefs.contains("shaderPrecache")) {
@@ -647,7 +666,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gpuClockPin", on).apply()
}
/** Whether the game's busiest threads are named to the power HAL for a boost (GameThreadHints). */
fun gameThreadHints(context: Context): Boolean = prefs(context).getBoolean("gameThreadHints", true)
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
@@ -662,18 +680,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
/** gamescope draws the cursor itself. Off by default: on a phone that plane costs frames. */
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", false)
fun setCursorComposite(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("cursorComposite", on).apply()
}
/**
* The rootfs ships Termux's unpatched proot. A session uses it only when this file exists,
* so a missing add-on pack cannot silently fall back to it.
* Path: Android/data/&lt;package&gt;/files/droiddeck-stock-proot
*/
@JvmStatic
fun allowStockProot(context: Context): Boolean =
context.getExternalFilesDir(null)?.let { File(it, "droiddeck-stock-proot").isFile } == true
@@ -782,7 +794,6 @@ object SessionPrefs {
)
}
/** Extra Proton, Wine and graphics diagnostics for the next game launch; off unless chosen. */
fun gameDebugLogsEnabled(context: Context): Boolean =
prefs(context).getBoolean("gameDebugLogsEnabled", false)
@@ -891,7 +902,7 @@ object SessionPrefs {
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
val saved = prefs(context)
saved.getString("displayResolution.$mode", null)?.let { value ->
if (value == SessionDisplay.MATCH_SCREEN || value == SessionDisplay.FOLLOW_SCREEN ||
if (value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) ||
SessionDisplay.presetHeight(value) != null) return value
parseResolution(value)?.let { return "${it.first}x${it.second}" }
}
@@ -904,7 +915,7 @@ object SessionPrefs {
}
fun setResolutionChoice(context: Context, mode: String, choice: String) {
val value = if (choice == SessionDisplay.MATCH_SCREEN || choice == SessionDisplay.FOLLOW_SCREEN ||
val value = if (choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) ||
SessionDisplay.presetHeight(choice) != null) choice else {
val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" }
"${size.first}x${size.second}"
@@ -936,7 +947,6 @@ object SessionPrefs {
prefs(context).edit().putString("steamClientArch", id).apply()
}
/** The running session's client, else the selected one: a changed setting applies from the next session. */
fun activeSteamClientArch(context: Context): String =
SessionState.steamClientArch?.takeIf { SessionState.running } ?: steamClientArch(context)
@@ -954,13 +964,10 @@ object SessionPrefs {
fun setBootMovieSound(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieSound", on).apply() }
fun bootMovieVolume(context: Context): Int = prefs(context).getInt("bootMovieVolume", 100).coerceIn(0, 100)
fun setBootMovieVolume(context: Context, percent: Int) { prefs(context).edit().putInt("bootMovieVolume", percent.coerceIn(0, 100)).apply() }
/** How long the boot movie plays, in seconds; 0 plays all of it. */
fun bootMovieSeconds(context: Context): Int = prefs(context).getInt("bootMovieSeconds", 0).coerceAtLeast(0)
fun setBootMovieSeconds(context: Context, seconds: Int) { prefs(context).edit().putInt("bootMovieSeconds", seconds.coerceAtLeast(0)).apply() }
/** Set when a movie was picked here, so the next session makes it Steam's startup movie even if Steam had another one. */
fun bootMovieApplyNext(context: Context): Boolean = prefs(context).getBoolean("bootMovieApplyNext", false)
fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() }
/** The startup movie path Steam's config held when it was last looked at, so only a change made in Steam is taken over. */
fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null)
fun setBootMovieSteamSeen(context: Context, path: String) { prefs(context).edit().putString("bootMovieSteamSeen", path).apply() }
fun bootMovieCustomName(context: Context): String? = prefs(context).getString("bootMovieCustomName", null)
@@ -1124,13 +1131,11 @@ object SessionPrefs {
prefs(context).edit().putString("theme", id).apply()
}
/** The custom Gradient theme's primary and secondary colours (ARGB). */
fun gradientColors(context: Context): Pair<Int, Int> = prefs(context).let {
it.getInt("gradientPrimary", com.droiddeck.launcher.ui.Themes.DEFAULT_PRIMARY) to
it.getInt("gradientSecondary", com.droiddeck.launcher.ui.Themes.DEFAULT_SECONDARY)
}
/** How fast the Inner Gamer theme cycles its colours, 1 to 10. */
fun rgbSpeed(context: Context): Int =
prefs(context).getInt("innerGamerSpeed", com.droiddeck.launcher.ui.Themes.DEFAULT_RGB_SPEED).coerceIn(1, com.droiddeck.launcher.ui.Themes.RGB_SPEEDS)
@@ -1160,18 +1165,11 @@ object SessionPrefs {
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
}
/** Compositor frame limit that releases buffers to the game unpaced. */
const val FPS_UNPACED = -1
/** The drawer's frame limit slider: its first stop is Off. */
const val FPS_LIMIT_OFF = 15
const val FPS_LIMIT_MAX = 165
/**
* 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.
*/
const val PIP_FPS = 30
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
@@ -1472,4 +1470,16 @@ object SessionPrefs {
fun setGameStorage(context: Context, path: String, label: String) {
prefs(context).edit().putString("gameStorage", path).putString("gameStorageLabel", label).apply()
}
fun steamLibraries(context: Context): String = prefs(context).getString("steamLibraries", "") ?: ""
fun setSteamLibraries(context: Context, json: String) {
prefs(context).edit().putString("steamLibraries", json).apply()
}
fun steamLibraryNextId(context: Context): Int = prefs(context).getInt("steamLibraryNextId", 1)
fun setSteamLibraryNextId(context: Context, id: Int) {
prefs(context).edit().putInt("steamLibraryNextId", id).apply()
}
}
@@ -107,7 +107,6 @@ class SessionService : Service() {
private var freezeCancelled = false
private var pendingSteamGameId: String? = null
private var pendingSteamGameGeneration = -1
// Bumped to cancel a running game-exit watch (a new launch, or the session ending).
@Volatile private var gameExitWatchToken = 0
private val flushSteamGame = object : Runnable {
override fun run() = flushQueuedSteamGame()
@@ -477,7 +476,6 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
SessionFiles.stage(this, root, startsSession = true)
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
SessionArtifacts.awaitCollections()
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
VacDiagnostics.arm(this)
@@ -536,7 +534,6 @@ 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.
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
@@ -578,6 +575,7 @@ class SessionService : Service() {
add("-c")
add("cd \"\$HOME\" && exec /bin/bash -i")
}
val desktopGuest = ArrayList(guest)
guest.add(LinuxRuntime.SESSION_SCRIPT)
guest.add(SessionState.mode)
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl?.takeIf { it.startsWith("steam://") }?.let {
@@ -644,6 +642,10 @@ class SessionService : Service() {
}
if (gen == sessionGen && SessionState.running) {
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
val (fastPathName, _) = ProotFastPath.hostEnv("")
BottomDesktop.prepare(desktopGuest, binds, sessionRoot,
hostEnv.asArray().filterNot { it.startsWith("$fastPathName=") }.toTypedArray(), root, sessionDir, gen,
) { gen == sessionGen && SessionState.running }
}
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
@@ -705,7 +707,10 @@ class SessionService : Service() {
if (gen == sessionGen && SessionState.running) {
suspendController = SessionSuspendController(
sessionRoot = { sessionPid },
helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } },
helperRoots = {
components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } +
listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 })
},
suspendAudio = {
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
if (!pulse.setMicSuspended(true)) Log.w(TAG, "could not suspend microphone source")
@@ -809,6 +814,7 @@ class SessionService : Service() {
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
guest.add("MESA_DISK_CACHE_DATABASE=1")
guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this)))
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null
@@ -1016,7 +1022,7 @@ class SessionService : Service() {
gpuMem.attach(this)
components.add(gpuMem)
}
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"))
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"), LinuxRuntime.rootDir(this))
if (gpuStats.prepare()) {
gpuStats.attach(this)
components.add(gpuStats)
@@ -1123,8 +1129,43 @@ class SessionService : Service() {
}
}
}
val addedLibraries = ArrayList<SteamLibraries.Entry>()
val cardPath = storageDiagnosticLibrary?.let { library?.path }?.let { runCatching { File(it).canonicalPath }.getOrDefault(it) }
for (entry in SteamLibraries.list(this)) {
if (cardPath != null && SteamLibraries.overlaps(cardPath, runCatching { entry.host.canonicalPath }.getOrDefault(entry.path))) {
Log.w(TAG, "added steam library: ${entry.path} overlaps the card library; not a library this session")
continue
}
if (!entry.host.isDirectory) {
Log.w(TAG, "added steam library: ${entry.path} is not attached; not a library this session")
continue
}
val problem = GameStorage.prepare(this, entry.path)
if (problem != null) {
Log.w(TAG, "added steam library: $problem")
continue
}
try {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds).size
} else Int.MAX_VALUE
val content = SecondaryLibrary.contentPath(entry.host)
val extra = SecondaryLibrary.binds(filesDir, entry.host, listOf(entry.guest), content = content)
if (extra.size > room) {
Log.w(TAG, "added steam library: ${entry.path} needs ${extra.size} binds, $room left for the fast path; not a library this session")
continue
}
File(LinuxRuntime.rootDir(this), entry.guest.removePrefix("/")).mkdirs()
binds.addAll(extra)
libraries.add(entry.guest to entry.label)
steamLibraryMounts = steamLibraryMounts + (entry.guest to content)
addedLibraries.add(entry)
Log.i(TAG, "added steam library: ${content.path} -> ${entry.guest} (\"${entry.label}\")")
} catch (e: Exception) {
Log.w(TAG, "added steam library: ${entry.path} private directories could not be prepared", e)
}
}
val x64Libraries = org.json.JSONArray()
// Desktop mode offers the x86-64 client either way; droiddeck-steam-x64 drops library folders it is not given.
val x64Here = SessionPrefs.steamClientArch(this) == "x86_64" ||
(SessionState.mode == MODE_DESKTOP &&
com.droiddeck.launcher.storage.SteamStorage.x64ClientPresent(SessionPrefs.steamRoot(this, "x86_64")))
@@ -1149,6 +1190,27 @@ class SessionService : Service() {
Log.w(TAG, "x86-64 steam library: $x64 private directories could not be prepared", e)
}
}
if (x64Here) for (entry in addedLibraries) {
val problem = GameStorage.prepare(this, entry.x64Host.path)
if (problem != null) {
Log.w(TAG, "x86-64 steam library: $problem")
continue
}
try {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
if (extra.size > room) {
Log.w(TAG, "x86-64 steam library: ${entry.x64Host} needs ${extra.size} binds, $room left for the fast path; not a library this session")
continue
}
binds.addAll(extra)
x64Libraries.put(org.json.JSONObject().put("path", entry.x64Guest).put("label", entry.label))
} catch (e: Exception) {
Log.w(TAG, "x86-64 steam library: ${entry.x64Host} private directories could not be prepared", e)
}
}
try {
val listing = File(filesDir, "session/steam-libraries-x64.json").apply { parentFile?.mkdirs() }
listing.writeText(x64Libraries.toString())
@@ -1328,13 +1390,6 @@ class SessionService : Service() {
Log.i(TAG, "queued Steam game $gameId for the running client")
}
/**
* A game launched from the front end (the Games tab, or another launcher's link): once it has
* started and then been gone for [GAME_EXIT_GRACE_MS], ask the client to exit through the
* session script's steam-stop request. The client quits cleanly, finishing its cloud sync, so
* the session ends on its own and the activity returns to where the launch came from instead
* of leaving the player in Big Picture. The grace covers launchers that restart the game.
*/
private fun watchGameExit(gameId: String, gen: Int) {
if (!SessionPrefs.returnAfterGame(this)) return
val token = ++gameExitWatchToken
@@ -1349,7 +1404,6 @@ class SessionService : Service() {
seen = true
goneSince = 0L
} else if (!seen) {
// Never started (an install, an update or a failed launch): leave the session be.
if (now > startBy) {
Log.i(TAG, "game $gameId did not start; not watching for its exit")
return@Thread
@@ -1375,8 +1429,6 @@ class SessionService : Service() {
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
}
/** A Steam game is running: the client runs each one under its reaper, and Proton's script
* waits on the game with waitforexitandrun. Read from the command lines, as ComponentsManager does. */
private fun steamGameRunning(): Boolean = SteamGameProcess.running()
private fun resumeSession(panelVisible: Boolean = true) {
@@ -1589,7 +1641,6 @@ class SessionService : Service() {
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) {
manualPauseRequested = true
} else if (!hidden && !SessionState.suspended) {
// Coming back before the freeze finished keeps the game running instead of pausing it a moment later.
manualPauseRequested = false
}
val controller = suspendController ?: return
@@ -1612,7 +1663,6 @@ class SessionService : Service() {
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) {
@@ -1631,6 +1681,7 @@ class SessionService : Service() {
))
if (shouldSuspend) {
freezePending = true
SessionState.suspending = true
freezeCancelled = false
val freezeSteamToken = steamSleepToken
val freezeNativeToken = nativeSleepToken
@@ -1639,6 +1690,7 @@ class SessionService : Service() {
) { success ->
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
SessionState.suspending = false
suspendOperationPending = false
freezePending = false
if (success) {
@@ -1851,6 +1903,7 @@ class SessionService : Service() {
GameThreadHints.stop()
suspendOperationPending = false
freezePending = false
SessionState.suspending = false
launchWatcher?.stopWatching()
launchWatcher = null
syncWatcher?.stopWatching()
@@ -1861,6 +1914,7 @@ class SessionService : Service() {
auxiliaryProcesses.toMap().also { auxiliaryProcesses.clear() }
}
SessionTerminal.clear(sessionGen)
BottomDesktop.stop(this, stoppedGen)
val controller = suspendController
suspendController = null
if (ended != null) {
@@ -1928,7 +1982,7 @@ class SessionService : Service() {
override fun onDestroy() {
stopSession(0)
GameThreadHints.stop() // also when the session never got as far as running
GameThreadHints.stop()
if (screenReceiverRegistered) {
unregisterReceiver(screenReceiver)
screenReceiverRegistered = false
@@ -2167,9 +2221,7 @@ class SessionService : Service() {
private const val DOWNLOAD_POLL_MS = 2_000L
private const val STEAM_GAME_REQUEST = "steam-game"
private const val GAME_URL_PREFIX = "steam://rungameid/"
/** How long a front-end launch may take to start (downloads, first-run installs) before the exit watch gives up. */
private const val GAME_START_TIMEOUT_MS = 20 * 60_000L
/** How long the game must stay gone before the client is asked to exit: launchers restart games. */
private const val GAME_EXIT_GRACE_MS = 10_000L
private const val GAME_EXIT_POLL_MS = 2_000L
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
@@ -54,6 +54,8 @@ object SessionState {
var suspended by mutableStateOf(false)
var resumeRequested by mutableStateOf(false)
var resuming by mutableStateOf(false)
/** A freeze has begun and has not finished; it already chose which processes it stops. */
@Volatile var suspending = false
var resumeFailures by mutableIntStateOf(0)
var resumeFailed by mutableStateOf(false)
var manualPause by mutableStateOf(false)
@@ -70,8 +72,6 @@ object SessionState {
var steamUrl: String? = null
@Volatile
var steamClientArch: String? = null
// A Play SteamVR request can arrive while an existing session is visible.
// Wake the status/launch effect even if no glasses surface has attached yet.
var steamVr by mutableStateOf(false)
var relaunch: android.content.Intent? = null
@JvmStatic var hdr = false
@@ -94,7 +94,6 @@ object SessionState {
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
/** Guest library paths on removable storage and the host folders they are mounted from, set by SessionService. */
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
@Volatile
@@ -105,6 +104,7 @@ object SessionState {
@Volatile
var followScreen = false
var followScale = 1f
@Volatile
var refreshHz: Float = 60f
@@ -112,7 +112,6 @@ object SessionState {
@Volatile
var upscaleRatio: Float = 0f
/** Frame limit chosen in the drawer for a game launched without Steam; 0 is off. */
@Volatile
var fpsLimit: Int = 0
@@ -26,9 +26,7 @@ internal class SessionSuspendController(
private val nowNanos: () -> Long = System::nanoTime,
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _, _ -> },
// False with a RAM cap set: the user asked for the session to use less memory, so nothing is read back.
private val readBackAllowed: () -> Boolean = { true },
// processes is 0 when the read-back was skipped: a RAM cap, or MemAvailable could not take it.
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
) {
@@ -113,12 +111,10 @@ internal class SessionSuspendController(
if (interrupted) Thread.currentThread().interrupt()
}
completion(complete)
// A cancelled or failed freeze leaves the game running with whatever the page-out already moved.
if (!complete && frozen.isEmpty() && !interrupted) readBack()
}, { completion(false) })
}
// A freeze still queued or paging out stops before its next SIGSTOP pass and rolls back.
fun cancelFreeze() {
cancelled = true
}
@@ -252,7 +248,6 @@ internal class SessionSuspendController(
}
private fun stoppedSnapshot(records: List<ProcessRecord>, root: ProcessRecord): Map<TaskIdentity, Long>? {
// PRoot can leave the leader stopped while native worker threads keep running.
val tasks = LinkedHashMap<TaskIdentity, Long>()
var stopped = true
for (record in records) {
@@ -279,9 +274,6 @@ internal class SessionSuspendController(
return tasks.takeIf { stopped && it.isNotEmpty() }
}
// A stopped process cannot run libblsession's SIGURG handler, so the page-out has to finish
// before the stop. Android's low-memory killer otherwise finds the frozen game resident in RAM
// with most of zram still free.
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
val control = zramControl?.takeIf { it.isFile } ?: return
try {
@@ -304,8 +296,6 @@ internal class SessionSuspendController(
val start = nowMillis()
val before = memoryKb(targets)
for (record in targets) send(record, SIGURG)
// A program can replace libblsession's SIGURG handler (PyInstaller's bootloader, the Go runtime);
// such a process never creates its ack and is not waited for once the start window has passed.
val waiting = targets.toMutableList()
while (!closing && !cancelled && nowMillis() - start < PAGE_OUT_TIMEOUT_MS) {
val started = nowMillis() - start >= PAGE_OUT_START_MS
@@ -319,13 +309,6 @@ internal class SessionSuspendController(
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
}
// Left in zram, the paged-out memory comes back one major fault at a time while the game runs; in a heavy
// game that is hundreds of faults per frame and stalls of a quarter second and more, long after the resume.
// libblsession's handler reads back only the swapped pages (mode 0, as the session script does for the client).
// The handler runs on whichever thread takes the signal, so that thread pauses for the read-back,
// once and right after the resume instead of mid-game.
// It signals even with nothing in zram yet: after a cancelled freeze a page-out handler may not have started,
// and it reads the mode only when it starts, so it reads back instead of paging out.
private fun readBack() {
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
@@ -360,15 +343,10 @@ internal class SessionSuspendController(
pagedIn(targets.size, swap, before, available, nowMillis() - start)
}
// Reading back moves the swap into resident memory, out of MemAvailable. On a device short on memory that
// could push Android's low-memory killer onto DroidDeck itself, so the memory comes back only when
// MemAvailable is at least twice the swap and keeps 1 GB or a tenth of MemTotal, whichever is more, after it.
// Otherwise it stays in zram and faults back in as the game touches it, as before.
private fun canTake(swapKb: Long, totalKb: Long, availableKb: Long): Boolean =
availableKb >= swapKb * READ_BACK_AVAILABLE_FACTOR &&
availableKb - swapKb >= maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE)
// MemTotal and MemAvailable, 0 when unreadable (which skips the read-back).
private fun meminfoKb(): Pair<Long, Long> = try {
val values = HashMap<String, Long>()
File(procRoot, "meminfo").forEachLine { line ->
@@ -402,9 +380,6 @@ internal class SessionSuspendController(
return resident to swap
}
// PRoot traces every guest. A stop sent while it runs becomes a group stop that it restarts
// thread by thread; once it is stopped, each thread that takes a SIGSTOP stays parked in its
// signal-delivery stop. So the roots stop first and every guest thread gets its own SIGSTOP.
private fun stop(records: List<ProcessRecord>) {
for (record in records.filter { it.role == Role.SESSION_ROOT }) send(record, SIGSTOP)
for (record in records.filter { it.role == Role.HELPER_ROOT }) send(record, SIGSTOP)
@@ -469,7 +444,6 @@ internal class SessionSuspendController(
val current = try { readProcess(record.pid) } catch (_: Exception) { return false }
if (current == null || current.started != record.started) return true
if (current.state == 'T' || current.state == 't') return false
// A traced worker in 't' is usually PRoot handling a system call; 'T' is a job-control stop.
return File(procRoot, "${record.pid}/task").listFiles().orEmpty().none { entry ->
entry.name.toIntOrNull() != null &&
try { readStat(File(entry, "stat"))[0].first() == 'T' } catch (_: IOException) { false }
@@ -15,7 +15,7 @@ object SettingsReset {
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "railLabels",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
@@ -26,7 +26,7 @@ object SettingsReset {
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsDash", "statsSpeedUnit",
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
)
internal val SESSION_PREFIXES = listOf(
@@ -1,38 +1,58 @@
package com.droiddeck.launcher.session
/** The In-game stats page's top strip, picked on the page (tap or the Layout row) and remembered. */
enum class StatsStrip(val id: String) {
PANEL("panel"), TILES("tiles"), RINGS("rings");
LINE("line"), PANEL("panel"), TILES("tiles"), RINGS("rings");
fun next(): StatsStrip = entries[(ordinal + 1) % entries.size]
companion object {
fun from(id: String?): StatsStrip = entries.firstOrNull { it.id == id } ?: PANEL
fun from(id: String?): StatsStrip = entries.firstOrNull { it.id == id } ?: LINE
}
}
enum class StripMetric(val id: String, val defaultOn: Boolean = true) {
ENGINE("engine"), GRAPH("graph"), LOWS("lows"), LOW001("low001"), GPU("gpu"), GPU_TEMP("gputemp", false),
CPU("cpu"), CPU_TEMP("cputemp"), VRAM("vram"), RAM("ram"), CLOCK("clock");
companion object {
val defaults: Set<StripMetric> = entries.filter { it.defaultOn }.toSet()
fun parse(saved: String?): Set<StripMetric> =
if (saved == null) defaults
else saved.split(',').mapNotNull { id -> entries.firstOrNull { it.id == id.trim() } }.toSet()
fun encode(on: Set<StripMetric>): String = entries.filter { it in on }.joinToString(",") { it.id }
}
}
enum class StatsHud(val id: String) {
BIG_FPS("bigfps"), FULL("full"), TILES("tiles"), RINGS("rings"), GRAPHS("graphs"), CORES("cores"),
HEAT("heat"), GAME("game"), PACING("pacing"), NIGHT("night"), MEGA("mega");
fun next(): StatsHud = entries[(ordinal + 1) % entries.size]
companion object {
fun from(id: String?): StatsHud = entries.firstOrNull { it.id == id } ?: BIG_FPS
}
}
/** Speeds on the racing dashes; telemetry arrives in km/h. */
enum class SpeedUnit(val id: String, val label: String, val perKmh: Float) {
AUTO("auto", "", 1f), KMH("kmh", "km/h", 1f), MPH("mph", "mph", 0.621371f);
/** Auto is mph where road speed limits are signed in mph, by the device's region, else km/h. */
fun resolve(country: String): SpeedUnit = if (this != AUTO) this else if (country.uppercase() in MPH_REGIONS) MPH else KMH
fun next(): SpeedUnit = entries[(ordinal + 1) % entries.size]
companion object {
/** The United States and its territories, the United Kingdom and its Crown Dependencies, Liberia, the Bahamas, Belize. */
private val MPH_REGIONS = setOf("US", "PR", "GU", "VI", "AS", "MP", "GB", "IM", "JE", "GG", "LR", "BS", "BZ")
fun from(id: String?): SpeedUnit = entries.firstOrNull { it.id == id } ?: AUTO
}
}
/** The racing dash under the strip; Auto picks one by the game's data format. */
enum class StatsDash(val id: String) {
AUTO("auto"), SPEEDOMETER("speedometer"), CIRCUIT("circuit"), TRACE("trace"), DIALS("dials"), GLANCE("glance");
/** The dash to draw for data from [source] (Telemetry.source). */
fun resolve(source: String): StatsDash = if (this != AUTO) this else when (source) {
"Forza" -> CIRCUIT
"OutGauge" -> DIALS
@@ -44,7 +64,6 @@ enum class StatsDash(val id: String) {
fun from(id: String?): StatsDash = entries.firstOrNull { it.id == id } ?: AUTO
/** A tap on the dash moves on from the one on screen, so Auto never looks like a tap did nothing. */
fun tapped(shown: StatsDash): StatsDash = DRAWN[(DRAWN.indexOf(shown) + 1).mod(DRAWN.size)]
}
}
@@ -7,12 +7,10 @@ import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/** steamdeckrepo.com's public boot video list, the same one its website and its own manager app read. */
object SteamDeckRepo {
private const val TAG = "SteamDeckRepo"
const val BASE = "https://steamdeckrepo.com"
/** The site shows twelve movies a page. */
const val PAGE_SIZE = 12
const val MAX_DOWNLOAD_BYTES = 120L shl 20
private const val MAX_JSON_BYTES = 1 shl 20
@@ -23,7 +21,6 @@ object SteamDeckRepo {
TRENDING("trending"), DOWNLOADS("downloads-desc"), LIKES("likes-desc"), NEWEST("created_at-desc"),
}
/** `null` is every device. */
val DEVICES = listOf("steam_deck", "steam_machine")
class Post(
@@ -36,7 +33,6 @@ object SteamDeckRepo {
object Failed : Page()
}
/** The text of [key], empty when it is missing or JSON null, which `optString` would turn into the word "null". */
private fun JSONObject.text(key: String): String = if (isNull(key)) "" else optString(key)
fun parse(json: String): List<Post>? {
@@ -83,10 +79,6 @@ object SteamDeckRepo {
return result
}
/**
* The number of the last page for a search, found by asking for pages: the site does not say how many there are, but a
* page past the end is empty and the last one is short. Null when the site cannot be reached.
*/
fun lastPage(sort: Sort, device: String?, search: String, cap: Int = 512, count: (Int) -> Int? = { p ->
(fetch(sort, device, search, p) as? Page.Ok)?.posts?.size
}): Int? {
@@ -111,7 +103,6 @@ object SteamDeckRepo {
return good
}
/** Reads [input] to its end, or null as soon as it holds more than [limit] bytes, so a huge answer is never kept whole. */
internal fun readLimited(input: java.io.InputStream, limit: Int): ByteArray? {
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(16 * 1024)
@@ -142,7 +133,6 @@ object SteamDeckRepo {
}
}
/** Fetches a small picture such as a cover; null when it cannot be had. */
fun bytes(url: String, limit: Int = 4 shl 20): ByteArray? {
if (!url.startsWith("https://")) return null
var connection: HttpURLConnection? = null
@@ -161,10 +151,6 @@ object SteamDeckRepo {
}
}
/**
* Downloads a movie to [target] through the site's own download address, so the site counts it like a download from
* its website, and falls back to the video's address. True when a file was saved.
*/
fun download(post: Post, target: File, onProgress: (Int) -> Unit = {}): Boolean {
for (url in listOf("$BASE/post/download/${post.id}", post.video)) {
if (save(url, target, onProgress)) return true
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.session
import java.io.File
import java.io.RandomAccessFile
/** A Steam download or update the client is working on. [total] is 0 while Steam has not sized it yet. */
data class SteamDownload(
val appId: String,
val name: String,
@@ -13,7 +12,6 @@ data class SteamDownload(
val paused: Boolean = false,
)
/** Reads Steam's own appmanifests and content log, the same files [SteamDownloadMonitor] watches. */
object SteamDownloads {
fun read(runtimeRoot: File, mounts: Map<String, File> = emptyMap(), client: String? = null): List<SteamDownload> {
val names = HashMap<String, String>()
@@ -32,7 +30,6 @@ object SteamDownloads {
return apps + shaders
}
/** The arm64 and x86-64 Steam homes can both hold an unfinished manifest of one app; the page keys rows by app. */
internal fun onePerApp(downloads: List<SteamDownload>): List<SteamDownload> =
downloads.groupBy { it.appId }.values.map { same -> same.maxBy { it.done } }
@@ -46,7 +43,6 @@ object SteamDownloads {
return SteamDownload(id, name, done, total, paused = (flags and UPDATE_PAUSED) != 0L)
}
/** App ids whose latest shader-cache line in the content log says the update is still running. */
internal fun runningShaderUpdates(lines: Sequence<String>): List<String> {
val state = LinkedHashMap<String, Boolean>()
for (line in lines) {
@@ -0,0 +1,100 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.storage.StorageManager
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
import org.json.JSONArray
import org.json.JSONObject
/** Steam libraries the user added beside the internal one and the card library, each a folder of its own. */
object SteamLibraries {
const val GUEST_ROOT = "/mnt/droiddeck-lib"
// Each library costs a bind per redirected tool and prefix folder; the PRoot fast path holds 256 in all.
const val MAX = 4
private val lock = Any()
class Entry(val id: String, val path: String, val label: String) {
val host: File get() = File(path)
val guest: String get() = "$GUEST_ROOT/$id"
val x64Host: File get() = File(path, GameStorage.X64_CARD_DIR)
val x64Guest: String get() = "$guest/${GameStorage.X64_CARD_DIR}"
}
fun list(context: Context): List<Entry> = parse(SessionPrefs.steamLibraries(context))
internal fun parse(json: String): List<Entry> {
if (json.isBlank()) return emptyList()
val array = runCatching { JSONArray(json) }.getOrNull() ?: return emptyList()
return (0 until array.length()).mapNotNull { i ->
val o = array.optJSONObject(i) ?: return@mapNotNull null
val id = o.optString("id")
val path = o.optString("path")
if (!id.matches(Regex("[0-9]{1,6}")) || path.isEmpty()) null else Entry(id, path, clean(o.optString("label")).ifEmpty { File(path).name })
}.distinctBy { it.id }
}
private fun save(context: Context, entries: List<Entry>) {
val array = JSONArray()
for (e in entries) array.put(JSONObject().put("id", e.id).put("path", e.path).put("label", e.label))
SessionPrefs.setSteamLibraries(context, array.toString())
}
/** Steam's libraryfolders.vdf stores labels between quotes with no escaping DroidDeck relies on. */
internal fun clean(label: String): String = label.replace('"', ' ').replace('\\', ' ').replace(Regex("\\s+"), " ").trim()
sealed class AddResult {
class Added(val entry: Entry) : AddResult()
class Refused(val reason: String) : AddResult()
}
fun add(context: Context, path: String, label: String = defaultLabel(context, File(path))): AddResult {
val entries = list(context)
if (entries.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
val host = canonical(File(path))
val taken = entries.map { canonical(it.host) } + listOfNotNull(
GameStorage.effective(context)?.let { canonical(File(it.path)) },
canonical(SessionPrefs.steamRoot(context, "arm64")),
)
if (taken.any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
// Adding a Games folder itself is fine; a child of one would make it overlap and hide the rest of that folder.
if (AddedGames.roots(context).any { host.startsWith(canonical(it.host) + "/") }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
GameStorage.prepare(context, path)?.let { return AddResult.Refused(it) }
synchronized(lock) {
val current = list(context)
if (current.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
if (current.any { overlaps(canonical(it.host), host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
// A removed library's mount stays registered with Steam until its next session, so ids are never reused.
val next = maxOf(SessionPrefs.steamLibraryNextId(context), (current.maxOfOrNull { it.id.toInt() } ?: 0) + 1)
val entry = Entry(next.toString(), path, clean(label).ifEmpty { File(path).name })
save(context, current + entry)
SessionPrefs.setSteamLibraryNextId(context, next + 1)
return AddResult.Added(entry)
}
}
fun rename(context: Context, id: String, label: String) {
val name = clean(label).takeIf { it.isNotEmpty() } ?: return
synchronized(lock) { save(context, list(context).map { if (it.id == id) Entry(it.id, it.path, name) else it }) }
}
/** Forgets the library; its folder and games stay where they are. */
fun remove(context: Context, id: String) {
synchronized(lock) { save(context, list(context).filterNot { it.id == id }) }
}
fun defaultLabel(context: Context, folder: File): String {
val volume = try {
context.getSystemService(StorageManager::class.java)?.getStorageVolume(folder)?.getDescription(context)
} catch (e: Exception) {
null
}
val name = folder.name.ifEmpty { context.getString(R.string.gstore_folder) }
return clean(if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume))
}
internal fun overlaps(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("$a/")
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
}
@@ -8,20 +8,12 @@ import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
/** A cookie for one https host, in the form CookieManager.setCookie takes. */
data class WebCookie(val host: String, val header: String)
/**
* The web sign-in the Steam client in the session already has, so the bottom-screen chat opens signed in.
* Steam's built-in browser keeps it in its Chromium cookie store under config/htmlcache. With no keyring
* (SteamOS and DroidDeck) Chromium encrypts values as "v10": AES-128-CBC, key PBKDF2-SHA1("peanuts",
* "saltysalt", 1 round), IV of 16 spaces. Values are never logged.
*/
object SteamWebLogin {
val HOSTS = listOf("steamcommunity.com", "steam-chat.com")
private const val COOKIES = "config/htmlcache/Default/Cookies"
private const val V10 = "v10"
// From cookie store version 24 Chromium puts the SHA-256 of the host before each value.
private const val HOST_HASH_VERSION = 24
private const val HOST_HASH_BYTES = 32
@@ -39,19 +31,16 @@ object SteamWebLogin {
String(value, Charsets.UTF_8)
}.getOrNull()
/** Steam's own pages send the sign-in with its "||" separator percent-encoded. */
internal fun header(name: String, value: String, httpOnly: Boolean): String {
val v = if (name == "steamLoginSecure") value.replace("||", "%7C%7C") else value
return "$name=$v; Path=/; Secure" + if (httpOnly) "; HttpOnly" else ""
}
/** Empty when the client has no web sign-in, for example before the first login. */
fun read(runtimeRoot: File, client: String?, scratch: File): List<WebCookie> {
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
?: SteamDownloadMonitor.STEAM_HOMES
val store = homes.map { File(runtimeRoot, "$it/$COOKIES") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
?: return emptyList()
// A copy, journal included: Steam keeps the store open and may be in the middle of a write.
scratch.deleteRecursively()
if (!scratch.mkdirs()) return emptyList()
return try {
@@ -4,17 +4,11 @@ import android.content.Context
import com.droiddeck.launcher.frontend.Library
import java.io.File
/**
* Codemasters games keep their UDP / motion output in My Games/<game>/hardwaresettings/hardware_settings_config.xml
* inside the game's Proton prefix and read it when the game starts. Turning it on points that element at the
* In-game stats listener; the file as it was is kept beside it, and its element is put back when turned off.
*/
object TelemetryOutput {
data class Game(val name: String, val prefixId: String, val file: File, val on: Boolean)
data class MenuGame(val name: String, val setting: String, val port: Int)
/** Games whose output is only a setting in the game's own menus, by Steam app id. */
val MENU_GAMES: Map<Int, MenuGame> = mapOf(
1293830 to MenuGame("Forza Horizon 4", "Data Out", GameTelemetry.FORZA_PORT),
1551360 to MenuGame("Forza Horizon 5", "Data Out", GameTelemetry.FORZA_PORT),
@@ -28,7 +22,6 @@ object TelemetryOutput {
private const val ADDRESS = "127.0.0.1"
private const val EXTRADATA = "3"
private val TAGS = listOf("udp", "motion")
// Byte-for-byte: every byte maps to one char and back, whatever the file's own encoding is.
private val BYTES = Charsets.ISO_8859_1
fun scan(compatdata: List<File>): List<Game> = compatdata.asSequence()
@@ -43,7 +36,6 @@ object TelemetryOutput {
.sortedBy { it.name.lowercase() }
.toList()
/** Turns the game's output on or off; false when the file could not be read or written. */
fun set(game: Game, on: Boolean): Boolean = runCatching {
val file = game.file
val original = File(file.path + ORIGINAL_SUFFIX)
@@ -62,7 +54,6 @@ object TelemetryOutput {
true
}.getOrDefault(false)
/** Automatic: turns the output on for every found game the user has not switched off and that is not running. */
fun applyAutomatic(context: Context, running: String?) {
if (!SessionPrefs.telemetryAuto(context)) return
automaticTargets(scan(Library.compatdataDirs(context)), SessionPrefs.telemetryOff(context), running).forEach { set(it, true) }
@@ -73,11 +64,9 @@ object TelemetryOutput {
internal fun automaticTargets(games: List<Game>, off: Set<String>, running: String?): List<Game> =
games.filter { !it.on && key(it) !in off && !isRunning(it.prefixId, running) }
/** Games DroidDeck changed, which go back to their own setting when Automatic is switched off. */
internal fun restoreTargets(games: List<Game>, running: String?): List<Game> =
games.filter { File(it.file.path + ORIGINAL_SUFFIX).isFile && !isRunning(it.prefixId, running) }
/** Whether [running] (the focused Steam app id, or another key for non-Steam programs) may be the game in [prefixId]. */
internal fun isRunning(prefixId: String, running: String?): Boolean {
val id = running?.toLongOrNull() ?: return running != null
return prefixId == id.toString() || prefixId == id.toInt().toString()
@@ -10,17 +10,9 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Source games state VAC-secure or insecure only in their console, which reaches a file (console.log in the
* mod folder) only with -condebug. The report quotes the lines it found and says inconclusive rather than guessing.
*/
object VacDiagnostics {
private const val TAG = "VacDiagnostics"
/**
* Checked by the launch wrapper. Lines: session start (epoch seconds), the Steam client it ran, then
* "length<tab>canonical path" for each console.log already there.
*/
private const val MARKER = "root/.droiddeck-vac-diagnostics"
private const val LAUNCHES = "root/.droiddeck-vac-launches"
@@ -30,7 +22,6 @@ object VacDiagnostics {
private const val MAX_QUOTED = 40
private val INSECURE = Regex("insecure mode", RegexOption.IGNORE_CASE)
// "Connecting to" is only an attempt: L4D2 refuses a VAC server with a dialog that never reaches the console.
private val CONNECTED = Regex("^Connected to", RegexOption.IGNORE_CASE)
private val ATTEMPTED = Regex("^Connecting to", RegexOption.IGNORE_CASE)
private val NOTABLE = Regex("\\bVAC\\b|secure|Connected to|Connecting to|Disconnect|challenge|game coordinator", RegexOption.IGNORE_CASE)
@@ -45,7 +36,6 @@ object VacDiagnostics {
File(root, LAUNCHES).delete()
if (enabled(context)) {
val arch = SessionPrefs.steamClientArch(context)
// -condebug appends, so each console.log's length now is where this session's lines start.
val sizes = consoleLogs(context, arch).joinToString("") { "${it.length()}\t${canonical(it)}\n" }
marker.writeText("${System.currentTimeMillis() / 1000}\n$arch\n$sizes")
} else marker.delete()
@@ -57,7 +47,6 @@ object VacDiagnostics {
private const val SNAPSHOT_MARKER = ".vac-marker"
private const val SNAPSHOT_LAUNCHES = ".vac-launches"
/** Call when a session stops, before the next [arm] replaces its marker and launch list. */
fun snapshot(context: Context, dir: File) {
val root = LinuxRuntime.rootDir(context)
try {
@@ -145,7 +134,6 @@ object VacDiagnostics {
"Inconclusive - the game never connected to a server. Join a VAC-secured server, then check again."
}
/** Source writes <game>/<mod>/console.log, Source 2 <game>/game/<mod>/console.log. */
private fun consoleLogs(context: Context, arch: String): List<File> {
val found = LinkedHashMap<String, File>()
for (library in libraryRoots(context, arch)) {
@@ -176,7 +164,6 @@ object VacDiagnostics {
return roots.filter { it.isDirectory }.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.path) }
}
/** Two libraries can hold the same game and mod folder; a repeated name takes a tag from the log's path. */
internal fun consoleNames(logs: List<File>): List<String> {
val used = HashSet<String>()
return logs.map { log ->
@@ -4,7 +4,6 @@ import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import java.io.File
/** Steam's Remote Play V4L2 encoder in the guest talks to this MediaCodec encoder (venc.c, venc_server.cpp). */
class VideoEncodeBridge(val socket: File) : SessionPart() {
override fun start() {
socket.parentFile?.mkdirs()
@@ -103,11 +103,6 @@ object WinComponents {
const val VCREDIST_ARM64 = "vcredist2022_arm64"
/**
* The ARM64 Visual C++ 2015-2022 runtime as registry values only (the version a 14.44.35211 installer writes, in both
* registry views). Xbox games' launchers running as ARM64EC check for it; Wine's own CRT does the work. Same approach as
* MGamer404's Bannerlator #627. Used until the catalog carries a component of this name.
*/
internal fun builtInArm64Runtime(): Component {
fun value(view: String, name: String, type: String, data: String) = Step("set_register_key", JSONObject()
.put("action", "set_register_key").put("key", "HKLM\\Software\\${view}Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\arm64")
@@ -388,7 +383,6 @@ object WinComponents {
val archiveName = archive.optString("name")
val url = c.snapshot.substringBeforeLast('/') + "/" + archiveName
val file = File(work, "${c.name}.files.tar.xz")
// The snapshot came straight from github.com, so its digest may vouch for a mirror's copy of the archive.
val sha = archive.optString("sha256").takeIf { it.matches(Regex("(?i)[0-9a-f]{64}")) }
if (!Downloader.downloadFile(url, file, false, sha) { f -> onProgress(Progress(c.name, archiveName, Phase.DOWNLOAD, if (f < 0) -1 else Math.round(f * 100f))) }) {
return null to "download failed: $archiveName"