chore: remove source comments and unused code, translate every missing string (#1965)

* chore(i18n): translate every missing string in all locales

Adds the 87 strings the bottom-screen Dashboard and in-game stats pages
introduced to all 32 locales, plus the 51 older settings strings Japanese
and the 50 Chinese locales were still missing. Every locale now has all
3456 translatable strings with the same placeholders as English.

Also translates 36 entries that were still English where the language
does not use the English word, and makes es-419 touch_app_id use the same
%1$s placeholder as English.

* chore(patches): drop comments from the lines downstream patches add

Removes comment lines and trailing comments from lines our patches add,
with hunk headers recounted. Lines that a later patch uses as context
and the upstream backport 0123 are left as they are.

The gamescope, FEX, proot and xodus series still apply to their pinned
sources, and the patched trees differ only in those comments.
test_hud_frames now finds the HUD writer by its first declaration.

* docs: credit Greenlight, Better xCloud, viture-v2, GameNative and DiRTTelemetryErrorFix

These were credited only in source headers and NOTICE files.

* chore: remove source comments and unused functions

Removes explanatory comments from first-party Kotlin, Java, C, C++,
Rust, TypeScript, Python, shell, Gradle, CMake and workflow files.
License and attribution headers stay, and vendored third-party trees,
generated files and license files are untouched. A shellcheck directive
is kept, and udevmon's fallthrough comments became fallthrough attributes.

Syntax trees and token streams match the previous sources apart from the
comments and Python docstrings. Module docstrings that argparse prints
are kept, and device-smoke.sh prints the same --help text from a heredoc.

Also removes 37 functions and 4 fields that nothing referenced.

* chore: remove comments from the Syncthing integration and the latest main sources

* docs: credit Syncthing and the syncthing-android fork

* chore(i18n): translate the Syncthing strings in all locales

The 107 strings the Syncthing integration added are now in all 32 locales.
sync_web_path_locked names the Syncthing tab by its label.

* docs: credit @xXJSONDeruloXx for the HUD metric readers

The CPU, GPU load, thermal and battery readers come from their
PerformanceHudView pull requests #777, #877, #991, #1406 and #1573.
The FusionHUD credit line is unchanged.

* docs: credit the HUD metric readers to @xXJSONDeruloXx's work
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-01 16:27:27 -05:00
1 parent d730f0fa8b
commit c5577478ca
511 files changed
+6813 -4068

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 }
}
@@ -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 ->
@@ -34,7 +34,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)
@@ -976,12 +975,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 }
@@ -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(' ')
@@ -73,7 +73,6 @@ class GpuStatsComponent(val dir: File, private val root: 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()
@@ -288,8 +287,6 @@ class GpuStatsComponent(val dir: File, private val root: 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
@@ -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 {
@@ -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" }
@@ -33,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) }
@@ -171,7 +170,6 @@ object SessionFiles {
} + 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/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
@@ -282,7 +280,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()
@@ -302,17 +299,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 {
@@ -391,7 +381,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) {
@@ -408,10 +397,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) {
@@ -421,7 +406,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
@@ -432,10 +416,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? {
@@ -444,7 +426,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(
@@ -454,7 +435,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
@@ -467,7 +447,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"
@@ -494,7 +473,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) {
@@ -538,11 +516,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
@@ -573,7 +546,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 }
@@ -643,13 +615,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
@@ -125,14 +125,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>) {
@@ -163,13 +161,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)
@@ -246,7 +237,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) {
@@ -472,10 +462,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) {
@@ -485,11 +471,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")) {
@@ -660,7 +641,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)
@@ -675,18 +655,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
@@ -772,7 +746,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)
@@ -926,7 +899,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)
@@ -944,13 +916,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)
@@ -1114,13 +1083,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)
@@ -1150,18 +1117,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 {
@@ -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)
@@ -535,7 +533,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))
@@ -1111,7 +1108,6 @@ class SessionService : Service() {
}
}
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")))
@@ -1315,13 +1311,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
@@ -1336,7 +1325,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
@@ -1362,8 +1350,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) {
@@ -1576,7 +1562,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
@@ -1599,7 +1584,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) {
@@ -1919,7 +1903,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
@@ -2158,9 +2142,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"
@@ -72,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
@@ -96,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
@@ -115,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 }
@@ -1,6 +1,5 @@
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");
@@ -11,28 +10,23 @@ enum class StatsStrip(val id: String) {
}
}
/** 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 +38,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) {
@@ -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"